Module: Ibex::Runtime::GeneratedLexer
- Defined in:
- lib/ibex/runtime/generated_lexer.rb,
sig/ibex/runtime/generated_lexer.rbs
Overview
Runtime contract mixed into parser classes that declare a lexer. rubocop:disable Metrics/ModuleLength -- matching, actions, state, and positions share one session invariant.
Constant Summary collapse
- NO_EMISSION =
Object.new.freeze
- EMPTY_GREEN_TRIVIA =
empty_green_trivia.freeze
Instance Method Summary collapse
- #advance_lexer_position(lexeme) ⇒ void
- #apply_lexer_rule(rule, lexeme, location) ⇒ [ untyped, untyped, Hash[Symbol, untyped] ]?
- #attach_cst_trivia(location) ⇒ Hash[Symbol, untyped]
- #configure_lexer_cst ⇒ void
- #consume_lexer_match(input, lexeme) ⇒ Hash[Symbol, untyped]
- #cst_source_text ⇒ CST::SourceText
- #cst_trivia_kind(text) ⇒ Integer
- #cst_trivia_policy ⇒ Symbol
-
#emit(token, value = NO_EMISSION) ⇒ Object
Emit a token from a lexer action.
- #ensure_lexer_data?(input) ⇒ Boolean
- #green_trivia_values(values) ⇒ Array[CST::GreenTrivia]
-
#lex(source, file: "(input)") ⇒ self
Reset the generated lexer to the beginning of an input.
-
#lexeme ⇒ String?
Return the text consumed by the active lexer action.
- #lexer_position ⇒ Hash[Symbol, Integer]
- #lexer_rules ⇒ Array[Hash[Symbol, untyped]]
-
#lexer_state ⇒ Symbol
Return the current named lexer state.
-
#lexer_state=(state) ⇒ Symbol
Replace the current named lexer state.
- #lexer_zero_width_location ⇒ Hash[Symbol, untyped]
-
#next_token ⇒ [ untyped, untyped, Hash[Symbol, untyped] ]
Pull one token using longest match and declaration-order tie breaking.
-
#parse(source, file: "(input)") ⇒ Object
Lex and parse one String, IO, or Fiber source.
-
#parse_syntax(source, file: "(input)") ⇒ CST::SyntaxResult
Parse without executing parser production actions.
- #parse_syntax_with_cache(source_text, cache) ⇒ CST::SyntaxResult
-
#parse_with_syntax(source, file: "(input)") ⇒ CST::ParseResult
Parse one generated-lexer source and return its semantic and syntax results.
-
#pop_state ⇒ Symbol
Pop the current named lexer state.
-
#push_state(state) ⇒ Symbol
Push a named lexer state.
- #raise_lexer_no_match(input) ⇒ bot
- #replace_previous_scanned_trailing(tokens, location, cache) ⇒ void
- #retain_cst_trivia(text, _location) ⇒ void
-
#scan_syntax_with_cache(source_text, cache) ⇒ CST::LexedSyntax
Run the generated lexer once and materialize its exact Green token stream.
- #scanned_green_token(token_id, value, location, cache) ⇒ CST::GreenToken
- #scanned_green_trivia(location, key) ⇒ Array[CST::GreenTrivia]
-
#select_lexer_match(input) ⇒ [ Hash[Symbol, untyped]?, String? ]
rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
-
#skip ⇒ nil
Suppress the current match from a lexer action.
- #split_balanced_trivia(trivia) ⇒ [ Array[CST::GreenTrivia], Array[CST::GreenTrivia] ]
- #take_cst_pending_green_trivia ⇒ Array[CST::GreenTrivia]
- #validate_lexer_state(state) ⇒ String
Instance Method Details
#advance_lexer_position(lexeme) ⇒ void
This method returns an undefined value.
497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 497 def advance_lexer_position(lexeme) lexeme.scan(/\X/).each do |value| grapheme = value.is_a?(String) ? value : value.join @lexer_byte_offset += grapheme.bytesize if grapheme.include?("\n") @lexer_line += 1 @lexer_column = 1 @lexer_byte_column = 1 else @lexer_column += 1 @lexer_byte_column += grapheme.bytesize end end end |
#apply_lexer_rule(rule, lexeme, location) ⇒ [ untyped, untyped, Hash[Symbol, untyped] ]?
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 280 def apply_lexer_rule(rule, lexeme, location) @lexer_lexeme = lexeme @lexer_emission = NO_EMISSION @lexer_skip_requested = rule.fetch(:kind) == :skip action = rule[:action] value = action ? __send__(action, lexeme) : lexeme emission = @lexer_emission if emission.is_a?(Array) location[:ibex_cst_text] = lexeme attached = attach_cst_trivia(location) @lexer_has_token = true return [emission.fetch(0), emission.fetch(1), attached.freeze] end if @lexer_skip_requested retain_cst_trivia(lexeme, location.freeze) return nil end if rule.fetch(:kind) == :token location[:ibex_cst_text] = lexeme attached = attach_cst_trivia(location) @lexer_has_token = true return [rule.fetch(:token), value, attached.freeze] end location.freeze raise ParseError, "#{location.fetch(:file)}:#{location.fetch(:line)}:" \ "#{location.fetch(:column)}: on lexer rule did not emit or skip" ensure @lexer_lexeme = nil end |
#attach_cst_trivia(location) ⇒ Hash[Symbol, untyped]
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 348 def attach_cst_trivia(location) policy = cst_trivia_policy trivia = @lexer_pending_green_trivia return location if trivia.empty? || policy == :drop @lexer_pending_green_trivia = [] if policy == :balanced && @lexer_has_token trailing, leading = split_balanced_trivia(trivia) else leading = trivia.freeze trailing = EMPTY_GREEN_TRIVIA end location[:leading_trivia] = leading.freeze location[:cst_previous_trailing] = trailing.freeze location end |
#configure_lexer_cst ⇒ void
This method returns an undefined value.
389 390 391 392 393 394 395 396 397 398 399 400 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 389 def configure_lexer_cst tables = parser_tables config = tables[:cst] if config.is_a?(Hash) @lexer_cst_trivia_policy = config.fetch(:trivia_policy) @lexer_cst_trivia_kinds = config.fetch(:kinds).fetch(:trivia) return end @lexer_cst_trivia_policy = :drop @lexer_cst_trivia_kinds = nil end |
#consume_lexer_match(input, lexeme) ⇒ Hash[Symbol, untyped]
263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 263 def consume_lexer_match(input, lexeme) start = lexer_position input.consume(lexeme) advance_lexer_position(lexeme) finish = lexer_position { file: @lexer_file, line: start.fetch(:line), column: start.fetch(:column), grapheme_column: start.fetch(:column), byte_column: start.fetch(:byte_column), end_line: finish.fetch(:line), end_column: finish.fetch(:column), end_grapheme_column: finish.fetch(:column), end_byte_column: finish.fetch(:byte_column), start_byte: start.fetch(:byte), end_byte: finish.fetch(:byte), source_line: input.source_line(start.fetch(:line)) } end |
#cst_source_text ⇒ CST::SourceText
431 432 433 434 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 431 def cst_source_text input = @lexer_input || raise(ParseError, "(lexer):1:1: lexer input is unavailable") CST::SourceText.new(input.source_bytes.byteslice(0, @lexer_byte_offset || 0) || "".b, file: @lexer_file) end |
#cst_trivia_kind(text) ⇒ Integer
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 372 def cst_trivia_kind(text) kinds = @lexer_cst_trivia_kinds || raise(ParseError, "(lexer):1:1: CST trivia kinds are unavailable") name = if text.include?("\n") "newline" elsif text.match?(/\A[[:space:]]+\z/) "whitespace" elsif text.start_with?("//", "#") "line_comment" elsif text.start_with?("/*") "block_comment" else "custom_skip" end kinds.fetch(name) end |
#cst_trivia_policy ⇒ Symbol
366 367 368 369 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 366 def cst_trivia_policy configure_lexer_cst unless defined?(@lexer_cst_trivia_policy) @lexer_cst_trivia_policy end |
#emit(token, value = NO_EMISSION) ⇒ Object
Emit a token from a lexer action.
314 315 316 317 318 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 314 def emit(token, value = NO_EMISSION) actual = value.equal?(NO_EMISSION) ? @lexer_lexeme : value @lexer_emission = [token, actual] actual end |
#ensure_lexer_data?(input) ⇒ Boolean
214 215 216 217 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 214 def ensure_lexer_data?(input) input.read_more? while input.buffer.empty? && !input.eof? !input.buffer.empty? end |
#green_trivia_values(values) ⇒ Array[CST::GreenTrivia]
444 445 446 447 448 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 444 def green_trivia_values(values) result = [] #: Array[CST::GreenTrivia] values.each { |item| result << item if item.is_a?(CST::GreenTrivia) } result end |
#lex(source, file: "(input)") ⇒ self
Reset the generated lexer to the beginning of an input.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 33 def lex(source, file: "(input)") @lexer_input = LexerInput.new(source) @lexer_file = file @lexer_states = ["INITIAL"] @lexer_line = 1 @lexer_column = 1 @lexer_byte_column = 1 @lexer_byte_offset = 0 @lexer_lexeme = nil @lexer_emission = NO_EMISSION @lexer_skip_requested = false @lexer_pending_green_trivia = [] configure_lexer_cst @lexer_has_token = false self end |
#lexeme ⇒ String?
Return the text consumed by the active lexer action.
329 330 331 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 329 def lexeme @lexer_lexeme end |
#lexer_position ⇒ Hash[Symbol, Integer]
477 478 479 480 481 482 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 477 def lexer_position { line: @lexer_line || 1, column: @lexer_column || 1, byte_column: @lexer_byte_column || 1, byte: @lexer_byte_offset || 0 } end |
#lexer_rules ⇒ Array[Hash[Symbol, untyped]]
242 243 244 245 246 247 248 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 242 def lexer_rules tables = self.class.const_get(:LEXER_RULES_BY_STATE) rules = tables[lexer_state] return rules if rules raise ParseError, "(lexer):1:1: missing rules for lexer state #{lexer_state}" end |
#lexer_state ⇒ Symbol
Return the current named lexer state.
87 88 89 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 87 def lexer_state (@lexer_states || ["INITIAL"]).last.to_sym end |
#lexer_state=(state) ⇒ Symbol
Replace the current named lexer state.
93 94 95 96 97 98 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 93 def lexer_state=(state) name = validate_lexer_state(state) states = @lexer_states ||= ["INITIAL"] states[-1] = name name.to_sym end |
#lexer_zero_width_location ⇒ Hash[Symbol, untyped]
485 486 487 488 489 490 491 492 493 494 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 485 def lexer_zero_width_location position = lexer_position { file: @lexer_file || "(input)", line: position.fetch(:line), column: position.fetch(:column), grapheme_column: position.fetch(:column), byte_column: position.fetch(:byte_column), end_line: position.fetch(:line), end_column: position.fetch(:column), end_grapheme_column: position.fetch(:column), end_byte_column: position.fetch(:byte_column), start_byte: position.fetch(:byte), end_byte: position.fetch(:byte) } end |
#next_token ⇒ [ untyped, untyped, Hash[Symbol, untyped] ]
Pull one token using longest match and declaration-order tie breaking.
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 102 def next_token input = @lexer_input raise ParseError, "(lexer):1:1: call parse or lex before next_token" unless input loop do unless ensure_lexer_data?(input) location = lexer_zero_width_location location[:ibex_lexer_start_state] = lexer_state location = attach_cst_trivia(location) if cst_enabled? return [nil, nil, location.freeze] end rule, lexeme = select_lexer_match(input) raise_lexer_no_match(input) unless rule && lexeme location = consume_lexer_match(input, lexeme) location[:ibex_lexer_start_state] = lexer_state emitted = apply_lexer_rule(rule, lexeme, location) return emitted if emitted end end |
#parse(source, file: "(input)") ⇒ Object
Lex and parse one String, IO, or Fiber source.
52 53 54 55 56 57 58 59 60 61 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 52 def parse(source, file: "(input)") lex(source, file: file) parser = self #: Parser parser.do_parse rescue ParseError => e raise unless parser_tables[:cst].is_a?(Hash) parser = self #: Parser parser.__send__(:cst_lexical_failure, e) end |
#parse_syntax(source, file: "(input)") ⇒ CST::SyntaxResult
Parse without executing parser production actions. Lexer actions still run because they define tokenization and lexer state.
81 82 83 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 81 def parse_syntax(source, file: "(input)") parse_syntax_with_cache(CST::SourceText.new(source, file: file), CST::NodeCache.new) end |
#parse_syntax_with_cache(source_text, cache) ⇒ CST::SyntaxResult
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 127 def parse_syntax_with_cache(source_text, cache) parser = self #: Parser parser.__send__(:with_syntax_only, cache) do lex(source_text.text, file: source_text.file || "(input)") value = begin parser.do_parse rescue ParseError => e raise unless parser_tables[:cst].is_a?(Hash) parser.__send__(:cst_lexical_failure, e) end parsed = parser.__send__(:syntax_parse_result, value) CST::SyntaxResult.new( syntax_root: parsed.syntax_root, diagnostics: parsed.diagnostics, reused_ratio: 0.0 ) end end |
#parse_with_syntax(source, file: "(input)") ⇒ CST::ParseResult
Parse one generated-lexer source and return its semantic and syntax results.
65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 65 def parse_with_syntax(source, file: "(input)") lex(source, file: file) parser = self #: Parser value = parser.do_parse parser.__send__(:syntax_parse_result, value) rescue ParseError => e raise unless parser_tables[:cst].is_a?(Hash) parser = self #: Parser value = parser.__send__(:cst_lexical_failure, e) parser.__send__(:syntax_parse_result, value) end |
#pop_state ⇒ Symbol
Pop the current named lexer state.
460 461 462 463 464 465 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 460 def pop_state states = @lexer_states ||= ["INITIAL"] raise ParseError, "(lexer):1:1: cannot pop the INITIAL lexer state" if states.one? (states.pop || "INITIAL").to_sym end |
#push_state(state) ⇒ Symbol
Push a named lexer state.
452 453 454 455 456 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 452 def push_state(state) name = validate_lexer_state(state) (@lexer_states ||= ["INITIAL"]) << name name.to_sym end |
#raise_lexer_no_match(input) ⇒ bot
251 252 253 254 255 256 257 258 259 260 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 251 def raise_lexer_no_match(input) location = lexer_zero_width_location location[:ibex_cst_unmatched_text] = input.buffer.dup.freeze location.freeze excerpt = input.buffer.slice(0, 16) raise ParseError.new( token_name: "lexer input", token_value: excerpt, location: location, detail: "no lexer rule matches #{excerpt.inspect} in state #{lexer_state}" ) end |
#replace_previous_scanned_trailing(tokens, location, cache) ⇒ void
This method returns an undefined value.
190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 190 def replace_previous_scanned_trailing(tokens, location, cache) trailing = scanned_green_trivia(location, :cst_previous_trailing) previous = tokens.last return if trailing.empty? || !previous tokens[-1] = cache.intern_token_fields( kind: previous.kind, text: previous.text, leading: previous.leading, trailing: previous.trailing + trailing, flags: previous.flags, expected_kind: previous.expected_kind ) end |
#retain_cst_trivia(text, _location) ⇒ void
This method returns an undefined value.
334 335 336 337 338 339 340 341 342 343 344 345 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 334 def retain_cst_trivia(text, _location) return if cst_trivia_policy == :drop kind = cst_trivia_kind(text) cache = @green_cache value = if cache cache.intern_trivia_fields(kind: kind, text: text) else CST::GreenTrivia.new(kind: kind, text: text) end @lexer_pending_green_trivia << value end |
#scan_syntax_with_cache(source_text, cache) ⇒ CST::LexedSyntax
Run the generated lexer once and materialize its exact Green token stream.
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 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 149 def scan_syntax_with_cache(source_text, cache) lex(source_text.text, file: source_text.file || "(input)") raw_tokens = [] #: Array[Array[untyped]] green_tokens = [] #: Array[CST::GreenToken] states = [] #: Array[Symbol] loop do external, value, location = next_token replace_previous_scanned_trailing(green_tokens, location, cache) token_id = external.nil? || external == false ? Parser::EOF_TOKEN : __send__(:internal_token_id, external) green = scanned_green_token(token_id, value, location, cache) raw_tokens << [external, value, location] green_tokens << green state = location[:ibex_lexer_start_state] if location.is_a?(Hash) states << (state ? state.to_sym : :INITIAL) break if token_id == Parser::EOF_TOKEN end offsets = [] #: Array[Integer] offset = 0 green_tokens.each do |token| offsets << offset offset += token.full_width end memo = CST::TokenMemo.new(tokens: green_tokens, offsets: offsets, states: states) CST::LexedSyntax.new(raw_tokens: raw_tokens, memo: memo) end |
#scanned_green_token(token_id, value, location, cache) ⇒ CST::GreenToken
176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 176 def scanned_green_token(token_id, value, location, cache) leading = scanned_green_trivia(location, :leading_trivia) text = if location.is_a?(Hash) && location[:ibex_cst_text].is_a?(String) location.fetch(:ibex_cst_text) elsif value.is_a?(String) value else "" end text = "" if token_id == Parser::EOF_TOKEN cache.intern_token_fields(kind: token_id, text: text, leading: leading) end |
#scanned_green_trivia(location, key) ⇒ Array[CST::GreenTrivia]
206 207 208 209 210 211 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 206 def scanned_green_trivia(location, key) return [] unless location.is_a?(Hash) value = location[key] value.is_a?(Array) ? value.grep(CST::GreenTrivia) : [] end |
#select_lexer_match(input) ⇒ [ Hash[Symbol, untyped]?, String? ]
rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 221 def select_lexer_match(input) loop do matches = lexer_rules.filter_map do |rule| match = rule.fetch(:regexp).match(input.buffer) [rule, match[0]] if match&.begin(0)&.zero? end #: Array[[Hash[Symbol, untyped], String]] boundary_match = matches.any? { |_rule, lexeme| lexeme.length == input.buffer.length } if !input.eof? && (matches.empty? || boundary_match) input.read_more? next end selected = matches.max_by { |rule, lexeme| [lexeme.bytesize, -rule.fetch(:id)] } return [nil, nil] unless selected return selected end end |
#skip ⇒ nil
Suppress the current match from a lexer action.
322 323 324 325 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 322 def skip @lexer_skip_requested = true nil end |
#split_balanced_trivia(trivia) ⇒ [ Array[CST::GreenTrivia], Array[CST::GreenTrivia] ]
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 403 def split_balanced_trivia(trivia) return [trivia.freeze, EMPTY_GREEN_TRIVIA] unless trivia.any? { |item| item.text.include?("\n".b) } before = [] #: Array[CST::GreenTrivia] after = [] #: Array[CST::GreenTrivia] found = false trivia.each do |item| if found after << item next end newline = item.text.index("\n".b) unless newline before << item next end boundary = newline + 1 before_text = item.text.byteslice(0, boundary) || "".b after_text = item.text.byteslice(boundary, item.text.bytesize - boundary) || "".b before << CST::GreenTrivia.new(kind: cst_trivia_kind(before_text), text: before_text) after << CST::GreenTrivia.new(kind: cst_trivia_kind(after_text), text: after_text) unless after_text.empty? found = true end [before, after] end |
#take_cst_pending_green_trivia ⇒ Array[CST::GreenTrivia]
437 438 439 440 441 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 437 def take_cst_pending_green_trivia values = @lexer_pending_green_trivia @lexer_pending_green_trivia = [] values.freeze end |
#validate_lexer_state(state) ⇒ String
468 469 470 471 472 473 474 |
# File 'lib/ibex/runtime/generated_lexer.rb', line 468 def validate_lexer_state(state) name = state.to_s known = self.class.const_get(:LEXER_STATES) raise ArgumentError, "unknown lexer state #{state.inspect}" unless known.include?(name) name end |