Class: Cataract::Parser
- Inherits:
-
Object
- Object
- Cataract::Parser
- Defined in:
- lib/cataract/pure/parser.rb
Overview
Pure Ruby CSS parser - char-by-char, NO REGEXP
Constant Summary collapse
- MAX_PARSE_DEPTH =
Maximum parse depth (prevent infinite recursion)
10- MAX_MEDIA_QUERIES =
Maximum media queries (prevent symbol table exhaustion)
1000- AT_RULE_TYPES =
%w[supports layer container scope].freeze
Instance Method Summary collapse
-
#byteslice_encoded(start, length, encoding: 'UTF-8') ⇒ Object
Extract substring and force specified encoding Per CSS spec, charset detection happens at byte-stream level before parsing.
-
#initialize(css_string, parser_options: {}, parent_media_sym: nil, parent_media_query_id: nil, depth: 0) ⇒ Parser
constructor
A new instance of Parser.
-
#match_ascii_ci?(str, pos, pattern) ⇒ Boolean
Helper: Case-insensitive ASCII byte comparison Compares bytes at given position with ASCII pattern (case-insensitive) Safe to use even if position is in middle of multi-byte UTF-8 characters Returns true if match, false otherwise.
- #parse ⇒ Object
Constructor Details
#initialize(css_string, parser_options: {}, parent_media_sym: nil, parent_media_query_id: nil, depth: 0) ⇒ Parser
Returns a new instance of Parser.
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/cataract/pure/parser.rb', line 62 def initialize(css_string, parser_options: {}, parent_media_sym: nil, parent_media_query_id: nil, depth: 0) # Type validation raise TypeError, "css_string must be a String, got #{css_string.class}" unless css_string.is_a?(String) # Private: Internal parsing state @_css = css_string.dup.freeze @_pos = 0 @_len = @_css.bytesize @_parent_media_sym = parent_media_sym @_parent_media_query_id = parent_media_query_id @_depth = depth # Current recursion depth (passed from parent parser) # Private: Parser options with defaults @_parser_options = { selector_lists: true, base_uri: nil, absolute_paths: false, uri_resolver: nil, raise_parse_errors: false }.merge() # Private: Extract options to ivars to avoid repeated hash lookups in hot path @_selector_lists_enabled = @_parser_options[:selector_lists] @_base_uri = @_parser_options[:base_uri] @_absolute_paths = @_parser_options[:absolute_paths] @_uri_resolver = @_parser_options[:uri_resolver] || Cataract::DEFAULT_URI_RESOLVER # Parse error handling options - extract to ivars for hot path performance @_raise_parse_errors = @_parser_options[:raise_parse_errors] if @_raise_parse_errors.is_a?(Hash) # Granular control - default all to false (opt-in) @_check_empty_values = @_raise_parse_errors[:empty_values] || false @_check_malformed_declarations = @_raise_parse_errors[:malformed_declarations] || false @_check_invalid_selectors = @_raise_parse_errors[:invalid_selectors] || false @_check_invalid_selector_syntax = @_raise_parse_errors[:invalid_selector_syntax] || false @_check_malformed_at_rules = @_raise_parse_errors[:malformed_at_rules] || false @_check_unclosed_blocks = @_raise_parse_errors[:unclosed_blocks] || false elsif @_raise_parse_errors == true # Enable all error checks @_check_empty_values = true @_check_malformed_declarations = true @_check_invalid_selectors = true @_check_invalid_selector_syntax = true @_check_malformed_at_rules = true @_check_unclosed_blocks = true else # Disabled @_check_empty_values = false @_check_malformed_declarations = false @_check_invalid_selectors = false @_check_invalid_selector_syntax = false @_check_malformed_at_rules = false @_check_unclosed_blocks = false end # Private: Internal counters @_media_query_id_counter = 0 # Next MediaQuery ID (0-indexed) @_next_selector_list_id = 0 # Counter for selector list IDs @_next_media_query_list_id = 0 # Counter for media query list IDs @_rule_id_counter = 0 # Next rule ID (0-indexed) @_media_query_count = 0 # Safety limit # Public: Parser results (returned in parse result hash) @rules = [] # Flat array of Rule structs @media_queries = [] # Array of MediaQuery objects @media_index = {} # Symbol => Array of rule IDs (for backwards compat/caching) @imports = [] # Array of ImportStatement structs @charset = nil # @charset declaration # Semi-private: Internal state exposed with _ prefix in result @_selector_lists = {} # Hash: list_id => Array of rule IDs @_media_query_lists = {} # Hash: list_id => Array of MediaQuery IDs (for "screen, print") @_has_nesting = false # Set to true if any nested rules found end |
Instance Method Details
#byteslice_encoded(start, length, encoding: 'UTF-8') ⇒ Object
Extract substring and force specified encoding Per CSS spec, charset detection happens at byte-stream level before parsing. All parsing operations treat content as UTF-8 (spec requires fallback to UTF-8). This prevents ArgumentError on broken/invalid encodings when calling string methods. Optional encoding parameter (default: 'UTF-8', use 'US-ASCII' for property names)
33 34 35 |
# File 'lib/cataract/pure/parser.rb', line 33 def byteslice_encoded(start, length, encoding: 'UTF-8') @_css.byteslice(start, length).force_encoding(encoding) end |
#match_ascii_ci?(str, pos, pattern) ⇒ Boolean
Helper: Case-insensitive ASCII byte comparison Compares bytes at given position with ASCII pattern (case-insensitive) Safe to use even if position is in middle of multi-byte UTF-8 characters Returns true if match, false otherwise
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/cataract/pure/parser.rb', line 41 def match_ascii_ci?(str, pos, pattern) pattern_len = pattern.bytesize return false if pos + pattern_len > str.bytesize i = 0 while i < pattern_len str_byte = str.getbyte(pos + i) pat_byte = pattern.getbyte(i) # Convert both to lowercase for comparison (ASCII only: A-Z -> a-z) str_byte += BYTE_CASE_DIFF if str_byte >= BYTE_UPPER_A && str_byte <= BYTE_UPPER_Z pat_byte += BYTE_CASE_DIFF if pat_byte >= BYTE_UPPER_A && pat_byte <= BYTE_UPPER_Z return false if str_byte != pat_byte i += 1 end true end |
#parse ⇒ Object
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
# File 'lib/cataract/pure/parser.rb', line 137 def parse # @import statements are now handled in parse_at_rule # They must come before all rules (except @charset) per CSS spec # Main parsing loop - char-by-char, NO REGEXP until eof? skip_ws_and_comments break if eof? # Peek at next byte to determine what to parse byte = peek_byte # Check for at-rules (@media, @charset, etc) if byte == BYTE_AT parse_at_rule next end # Must be a selector-based rule selector = parse_selector if selector.nil? || selector.empty? next end # Find the block boundaries decl_start = @_pos # Should be right after the { decl_end = find_matching_brace(decl_start) # Check if block has nested selectors if has_nested_selectors?(decl_start, decl_end) # NESTED PATH: Parse mixed declarations + nested rules # Split comma-separated selectors and parse each one selectors = split_and_validate_selectors(selector, decl_start) selectors.each do |individual_selector| next if individual_selector.empty? # Get rule ID for this selector current_rule_id = @_rule_id_counter @_rule_id_counter += 1 # Reserve parent's position in rules array (ensures parent comes before nested) parent_position = @rules.length @rules << nil # Placeholder # Parse mixed block (declarations + nested selectors) @_depth += 1 parent_declarations = parse_mixed_block(decl_start, decl_end, individual_selector, current_rule_id, @_parent_media_sym, @_parent_media_query_id) @_depth -= 1 # Create parent rule and replace placeholder rule = Rule.new( current_rule_id, individual_selector, parent_declarations, nil, # specificity nil, # parent_rule_id (top-level) nil # nesting_style ) @rules[parent_position] = rule end # Move position past the closing brace @_pos = decl_end @_pos += 1 if @_pos < @_len && @_css.getbyte(@_pos) == BYTE_RBRACE else # NON-NESTED PATH: Parse declarations only @_pos = decl_start # Reset to start of block declarations = parse_declarations # Split comma-separated selectors into individual rules selectors = split_and_validate_selectors(selector, decl_start) # Determine if we should track this as a selector list # Check boolean first to potentially avoid size() call via short-circuit evaluation list_id = nil if @_selector_lists_enabled && selectors.size > 1 list_id = @_next_selector_list_id @_next_selector_list_id += 1 @_selector_lists[list_id] = [] end selectors.each do |individual_selector| next if individual_selector.empty? rule_id = @_rule_id_counter # Dup declarations for each rule in a selector list to avoid shared state # (principle of least surprise - modifying one rule shouldn't affect others) # Must deep dup: both the array and the Declaration objects inside rule_declarations = if list_id declarations.map { |d| Declaration.new(d.property, d.value, d.important) } else declarations end # Create Rule struct (with selector_list_id as 7th parameter) rule = Rule.new( rule_id, # id individual_selector, # selector rule_declarations, # declarations nil, # specificity (calculated lazily) nil, # parent_rule_id nil, # nesting_style list_id # selector_list_id ) @rules << rule @_rule_id_counter += 1 # Track in selector list if applicable @_selector_lists[list_id] << rule_id if list_id end end end { rules: @rules, _media_index: @media_index, media_queries: @media_queries, _selector_lists: @_selector_lists, _media_query_lists: @_media_query_lists, imports: @imports, charset: @charset, _has_nesting: @_has_nesting } end |