flexr 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/README.md +4 -0
  4. data/benchmark/dfa_stretch.rb +149 -0
  5. data/benchmark/lrama_lexer.rb +79 -96
  6. data/benchmark/regexp_parser_corpus.rb +35 -0
  7. data/benchmark/regexp_parser_parity.rb +89 -0
  8. data/benchmark/regexp_parser_scanner.rb +159 -0
  9. data/docs/README.md +4 -1
  10. data/docs/adr/0021-ruby-34-minimum.md +23 -0
  11. data/docs/adr/0022-immutable-tokens-and-locations.md +22 -0
  12. data/docs/adr/0023-stable-explicit-firstmatch.md +21 -0
  13. data/docs/adr/0024-opt-in-ractor-sharing.md +24 -0
  14. data/docs/adr/0025-explicit-whole-token-acceleration.md +26 -0
  15. data/docs/adr/0026-retain-direct-dispatch.md +22 -0
  16. data/docs/adr/0033-action-free-recognition.md +33 -0
  17. data/docs/adr/0034-lexer-checkpoints.md +25 -0
  18. data/docs/adr/0035-parser-token-expectations.md +27 -0
  19. data/docs/adr/0038-replay-named-regexp-captures.md +23 -0
  20. data/docs/adr/0039-input-stack.md +25 -0
  21. data/docs/adr/0040-runtime-delimiters.md +23 -0
  22. data/docs/adr/0041-post-lexical-indentation.md +24 -0
  23. data/docs/adr/0042-capture-delegation.md +23 -0
  24. data/docs/adr/0043-expand-reusable-rules-explicitly.md +27 -0
  25. data/docs/adr/0044-import-oedipus-firstmatch.md +26 -0
  26. data/docs/assets/playground-absence-and-diagnostics.gif +0 -0
  27. data/docs/explanation/backends.md +5 -4
  28. data/docs/how-to/integrate-with-lrama.md +9 -8
  29. data/docs/how-to/integrate-with-racc.md +9 -0
  30. data/docs/how-to/migrate-from-oedipus-lex.md +43 -0
  31. data/docs/how-to/parser-driven-lexing.md +48 -0
  32. data/docs/how-to/try-playground-demos.md +13 -0
  33. data/docs/internals/regexp-parser-experiment.md +67 -0
  34. data/docs/perf-log.md +120 -8
  35. data/docs/reference/README.md +1 -1
  36. data/docs/reference/actions.md +106 -0
  37. data/docs/reference/cli.md +75 -4
  38. data/docs/reference/diagnostics.md +3 -9
  39. data/docs/reference/dsl.md +66 -3
  40. data/docs/reference/public-api.md +8 -1
  41. data/docs/reference/regexp.md +27 -4
  42. data/docs/reference/ruby-lsp.md +15 -0
  43. data/docs/reference/runtime.md +163 -2
  44. data/docs/tutorial/build-a-calculator-parser.md +47 -0
  45. data/examples/with_lrama/README.md +3 -3
  46. data/lib/flexr/automaton/accel.rb +1 -0
  47. data/lib/flexr/automaton/compiler.rb +15 -0
  48. data/lib/flexr/automaton/dfa.rb +0 -33
  49. data/lib/flexr/automaton/keyword_tables.rb +14 -8
  50. data/lib/flexr/automaton/reference_dfa.rb +38 -0
  51. data/lib/flexr/cli.rb +118 -18
  52. data/lib/flexr/codegen/table.rb +7 -0
  53. data/lib/flexr/configuration.rb +18 -1
  54. data/lib/flexr/dsl.rb +14 -3
  55. data/lib/flexr/generated.rb +4 -0
  56. data/lib/flexr/generator.rb +39 -7
  57. data/lib/flexr/importer/oedipus_lex.rb +229 -0
  58. data/lib/flexr/importer.rb +7 -2
  59. data/lib/flexr/ir.rb +1 -1
  60. data/lib/flexr/options.rb +3 -0
  61. data/lib/flexr/project_template.rb +46 -0
  62. data/lib/flexr/project_templates/common/.gitignore +1 -0
  63. data/lib/flexr/project_templates/common/lexer.flexr.rb +12 -0
  64. data/lib/flexr/project_templates/common/test_calculator.rb +15 -0
  65. data/lib/flexr/project_templates/lrama/Gemfile +9 -0
  66. data/lib/flexr/project_templates/lrama/README.md +17 -0
  67. data/lib/flexr/project_templates/lrama/Rakefile +18 -0
  68. data/lib/flexr/project_templates/lrama/calculator.rb +28 -0
  69. data/lib/flexr/project_templates/lrama/parser.y +72 -0
  70. data/lib/flexr/project_templates/racc/Gemfile +8 -0
  71. data/lib/flexr/project_templates/racc/README.md +15 -0
  72. data/lib/flexr/project_templates/racc/Rakefile +14 -0
  73. data/lib/flexr/project_templates/racc/calculator.rb +22 -0
  74. data/lib/flexr/project_templates/racc/parser.y +19 -0
  75. data/lib/flexr/regexp/ast.rb +2 -0
  76. data/lib/flexr/regexp/parser.rb +13 -11
  77. data/lib/flexr/regexp/tokenizer.rb +2 -2
  78. data/lib/flexr/rules.rb +53 -0
  79. data/lib/flexr/runtime/buffer.rb +1 -1
  80. data/lib/flexr/runtime/captures.rb +46 -0
  81. data/lib/flexr/runtime/channels.rb +2 -1
  82. data/lib/flexr/runtime/checkpoint.rb +116 -0
  83. data/lib/flexr/runtime/core.rb +55 -43
  84. data/lib/flexr/runtime/delegation.rb +123 -0
  85. data/lib/flexr/runtime/delimiters.rb +89 -0
  86. data/lib/flexr/runtime/firstmatch.rb +266 -0
  87. data/lib/flexr/runtime/indentation.rb +235 -0
  88. data/lib/flexr/runtime/input_stack.rb +48 -0
  89. data/lib/flexr/runtime/interpreter.rb +36 -314
  90. data/lib/flexr/runtime/recognizer.rb +106 -0
  91. data/lib/flexr/runtime.rb +10 -0
  92. data/lib/flexr/skeleton/verification.rb +103 -0
  93. data/lib/flexr/skeleton.rb +208 -0
  94. data/lib/flexr/source/fixes.rb +145 -0
  95. data/lib/flexr/source/prism_reader.rb +187 -25
  96. data/lib/flexr/testing.rb +5 -2
  97. data/lib/flexr/unicode/reference_regexp.rb +29 -11
  98. data/lib/flexr/version.rb +1 -1
  99. data/lib/ruby_lsp/flexr/addon.rb +88 -13
  100. data/lib/ruby_lsp/flexr/navigation.rb +231 -0
  101. data/lib/ruby_lsp/flexr/ranges.rb +40 -0
  102. data/sig/flexr.rbs +33 -3
  103. data/site/README.md +22 -7
  104. data/site/ruby/presets/heredoc.flexr.rb +15 -0
  105. data/site/ruby/presets/html_javascript.rb +12 -0
  106. data/site/ruby/presets/html_js.flexr.rb +14 -0
  107. data/site/ruby/presets/indentation.flexr.rb +14 -0
  108. data/site/scripts/prepare-playground.mjs +16 -6
  109. data/site/scripts/stable-release.mjs +4 -1
  110. data/site/src/content/docs/learn/parser-integration.md +23 -8
  111. data/site/src/content/docs/reference/cli.md +3 -0
  112. data/site/src/content/docs/reference/dsl.md +1 -0
  113. data/site/src/content/docs/reference/runtime.md +26 -0
  114. data/site/src/pages/playground.astro +15 -1
  115. data/site/src/playground/client.js +30 -1
  116. data/site/src/playground/issue.mjs +19 -0
  117. data/site/src/playground/runtime.mjs +4 -3
  118. data/site/src/playground/worker.mjs +1 -1
  119. data/site/tests/browser/playground.spec.mjs +64 -0
  120. data/site/tests/playground-issue.test.mjs +15 -0
  121. data/site/tests/playground-release.test.mjs +62 -11
  122. data/site/tests/playground-runtime.test.mjs +48 -0
  123. data/test/ruby_lsp_addon_spec.rb +174 -0
  124. metadata +63 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c9f29243c0399d336c8a00ebf358ba0f6586f1cbf84d54a30913b7aef431926c
4
- data.tar.gz: 7b0d2ef0f5a6812f5dd46f8d9c01a2c85afbcb34808ff5a7e5f4bc5d65a0ff86
3
+ metadata.gz: c6d99beb52e8731963e132e0abc2ef6860abf571efb45a11c0dd4f338b1c09f4
4
+ data.tar.gz: 2910a2302db592fd57bd9b5f57222c17b95b77213207e1638a432ba290aa70cd
5
5
  SHA512:
6
- metadata.gz: 889086c628ade02d5239e754ca174b3e2a6e930011e6efce4ec6291623ea4ecf90c01bcc6adb7507431a41b80bf076be06bc631430ba89d83c011fc378e138e3
7
- data.tar.gz: 72857d5415c72b010b4abe48693a9f351fb3133909e68084f67d018068cc099328a3143b0ca09c3445a6fe0c1c0b5e657d6f0060f91e0fcbc3d23a274407b158
6
+ metadata.gz: 6b33cb822aa92e92f784691a446c9a4fcebff02f9dc04dd95cc084a94ee19ec982fbc482d379330ab2d1dce5b5202a8a70fdc76844537698a44f01981a318e9d
7
+ data.tar.gz: b72cc2c24d3de67935645a61c0d7778f1694ab6d8d8e8d4afe4c51bbb0ef4507bc2dcca6fa8c54f0318496566758675127c3c162c92d9466a675e531e4899d3c
data/CHANGELOG.md CHANGED
@@ -3,6 +3,39 @@
3
3
  Notable changes to flexr, newest first. Release dates use Japan Standard Time
4
4
  (UTC+09:00).
5
5
 
6
+ ## [2.2.0](https://github.com/ydah/flexr/compare/v2.1.0...v2.2.0)
7
+
8
+ ### Added
9
+
10
+ - Read named regexp groups from `captures` in a rule action. Delegate a
11
+ capture to another lexer with `delegate(ChildLexer, capture: :name)` while
12
+ preserving the child tokens' locations in the parent source.
13
+ - Match a compiled DFA at a byte offset with `Lexer.recognizer` without
14
+ running rule actions. Use `checkpoint`, `restore`, and `seek` to resume
15
+ a lexer between token reads.
16
+ - Pass `expect:` to `next_token` or `racc_next_token` to let the parser
17
+ restrict eligible token rules for the current read.
18
+ - Emit indent and dedent tokens for indentation-sensitive languages, pause
19
+ the current source with `push_input` to scan an included file, and read
20
+ runtime delimiters with `scan_until` or `scan_until_line`.
21
+ - Reuse named lexer rule sets with `use`, including in lexical states.
22
+ - Preview and apply supported diagnostic fixes with `flexr fix`. Ruby LSP
23
+ offers the same fixes and adds state navigation, token symbol completion,
24
+ and a rule and state outline for `.flexr.rb` files.
25
+ - Generate shortest inputs for DFA transitions with `flexr skeleton` and
26
+ optionally verify scanner parity across runtime, generated, and standalone
27
+ modes. Start a Racc or Lrama project with `flexr new --parser`.
28
+ - Import supported oedipus_lex `.rex` declarations with
29
+ `flexr import --from oedipus_lex`, preserving first-match rule order.
30
+ - Try indentation, heredoc, and embedded JavaScript in the Playground when
31
+ its runtime supports them. Copy a GitHub issue draft with the exact
32
+ specification, input, runtime version, and diagnostics from a run.
33
+
34
+ ### Upgrade notes
35
+
36
+ - Generated lexers using named regexp captures or lexer delegation require
37
+ flexr 2.2 or later at runtime. Standalone files include their runtime.
38
+
6
39
  ## [2.1.0](https://github.com/ydah/flexr/compare/v2.0.0...v2.1.0)
7
40
 
8
41
  ### Added
data/README.md CHANGED
@@ -12,6 +12,10 @@ Write one specification, run it directly while developing, or generate Ruby
12
12
  for deployment when startup cost and build reproducibility matter. Both modes
13
13
  use the same rules and actions.
14
14
 
15
+ ![Playground scans two separate comments with an absence group, then shows the input that shadows an if rule.](docs/assets/playground-absence-and-diagnostics.gif)
16
+
17
+ [Open the specifications from the demo](docs/how-to/try-playground-demos.md).
18
+
15
19
  ## Why flexr?
16
20
 
17
21
  - Ordinary Ruby DSL; no separate lexer language is required.
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../lib/flexr"
5
+
6
+ module DFAStretch
7
+ module_function
8
+
9
+ def check(actual, expected)
10
+ raise "expected #{expected.inspect}, got #{actual.inspect}" unless actual == expected
11
+
12
+ actual
13
+ end
14
+
15
+ def initial_dfa(lexer)
16
+ lexer.compile!.machines.fetch(:initial).dfa
17
+ end
18
+
19
+ def acceptance_history(dfa, input)
20
+ raise ArgumentError, "this probe requires ASCII input" unless input.ascii_only?
21
+
22
+ state = dfa.start
23
+ history = []
24
+ input.each_byte.with_index(1) do |byte, ending|
25
+ state = dfa.transition(state, byte)
26
+ break unless state
27
+
28
+ dfa.accepts.fetch(state).each do |acceptance|
29
+ raise ArgumentError, "this probe requires unanchored patterns" if acceptance.bol_only || acceptance.end_anchor
30
+
31
+ history << [ending, acceptance.rule_index, acceptance.pattern_index]
32
+ end
33
+ end
34
+ history
35
+ end
36
+
37
+ def selection_probe
38
+ effects = []
39
+ grammar = Class.new(Flexr::Lexer) do
40
+ rule("a", emit: :SINGLE)
41
+ rule(/a+/, emits: :RUN) do
42
+ effects << [:run, text]
43
+ push :inside
44
+ emit :RUN
45
+ end
46
+ rule("aa", emit: :PAIR, priority: 10)
47
+ state(:inside) { rule("!", emit: :BANG) }
48
+ end
49
+ input = "aaa!"
50
+ dfa = initial_dfa(grammar)
51
+ names = %i[SINGLE RUN PAIR]
52
+ history = acceptance_history(dfa, input).map { |ending, rule, _| [names.fetch(rule), ending] }
53
+ check(history, [[:SINGLE, 1], [:RUN, 1], [:PAIR, 2], [:RUN, 2], [:RUN, 3]])
54
+ reject_order = history.chunk(&:last).to_a.reverse.flat_map(&:last)
55
+ check(reject_order, [[:RUN, 3], [:PAIR, 2], [:RUN, 2], [:SINGLE, 1], [:RUN, 1]])
56
+
57
+ scanner = grammar.new(input)
58
+ checkpoint = scanner.checkpoint
59
+ longest = check(scanner.next_token, [:RUN, "aaa"])
60
+ state_after = check([scanner.state, scanner.byte_pos], [:inside, 3])
61
+ scanner.restore(checkpoint)
62
+ restored = check([scanner.state, scanner.byte_pos], [:initial, 0])
63
+ alternative = check(scanner.next_token(expect: [:PAIR]), [:PAIR, "aa"])
64
+ check(effects, [[:run, "aaa"]])
65
+ counts = [1, 8, 64, 1024].to_h { |size| [size, acceptance_history(dfa, "a" * size).size] }
66
+ check(counts.values, [2, 10, 66, 1026])
67
+
68
+ trailing = Class.new(Flexr::Lexer) do
69
+ rule("a", followed_by: "bcd", emit: :CONTEXT)
70
+ rule("ab", emit: :PAIR)
71
+ end
72
+ body_ends = check(acceptance_history(initial_dfa(trailing), "abcd"), [[1, 0, 0], [2, 1, 0]])
73
+ ranked = check(trailing.recognizer.match("abcd", 0), [:CONTEXT, 1])
74
+
75
+ firstmatch = Class.new(Flexr::Lexer) do
76
+ backend :firstmatch
77
+ rule(/a+/, emit: :RUN)
78
+ rule("a", emit: :SINGLE)
79
+ end
80
+ firstmatch_shortest = check(acceptance_history(initial_dfa(firstmatch), input).first, [1, 0, 0])
81
+ native_token = check(firstmatch.new(input).next_token, [:RUN, "aaa"])
82
+ {
83
+ shortest: history.first, longest: reject_order.first, actual_token: longest,
84
+ firstmatch: { shortest: [:RUN, firstmatch_shortest.first], native_token: native_token },
85
+ reject_order: reject_order, history_counts: counts,
86
+ position_after_action: state_after, restored_position: restored, filtered_token: alternative, surviving_effects: effects,
87
+ trailing_context: { body_ends: body_ends.map(&:first), ranking_ends: [4, 2], current_match: ranked }
88
+ }
89
+ end
90
+
91
+ def dfa_signature(dfa)
92
+ [dfa.start, dfa.accepts, dfa.states.times.map { |state| 256.times.map { |byte| dfa.transition(state, byte) } }]
93
+ end
94
+
95
+ def bounded_capture_ranges(input, widths, lanes)
96
+ states = widths.map { |width| lanes.fetch(width).start }
97
+ split = finish = nil
98
+ input.each_byte.with_index(1) do |byte, ending|
99
+ states.map!.with_index do |state, index|
100
+ state && lanes.fetch(widths.fetch(index)).transition(state, byte)
101
+ end
102
+ break if states.none?
103
+
104
+ winning_lane = states.each_index.find do |index|
105
+ state = states.fetch(index)
106
+ state && !lanes.fetch(widths.fetch(index)).accepts.fetch(state).empty?
107
+ end
108
+ next unless winning_lane
109
+
110
+ split = widths.fetch(winning_lane)
111
+ finish = ending
112
+ end
113
+ [0...split, split...finish] if finish
114
+ end
115
+
116
+ def captures_probe
117
+ variants = { /(?<head>a|aa)(?<tail>a+)/ => [1, 2], /(?<head>aa|a)(?<tail>a+)/ => [2, 1] }
118
+ grammars = variants.keys.map do |pattern|
119
+ Class.new(Flexr::Lexer) do
120
+ rule(pattern) { emit :CAPTURE, captures.values_at(:head, :tail) }
121
+ end
122
+ end
123
+ dfa, other = grammars.map { |grammar| initial_dfa(grammar) }
124
+ check(dfa_signature(dfa), dfa_signature(other))
125
+
126
+ lanes = { 1 => Flexr.compile_pattern(/aa+/), 2 => Flexr.compile_pattern(/aaa+/) }
127
+ inputs = (2..64).map { |size| "#{'a' * size}!" }
128
+ examples = grammars.zip(variants.values).map do |grammar, widths|
129
+ inputs.each do |input|
130
+ ranges = bounded_capture_ranges(input, widths, lanes)
131
+ check(ranges.last.end, grammar.recognizer.match(input, 0).last)
132
+ check(ranges.map { |range| input.byteslice(range) }, grammar.new(input).next_token.last)
133
+ end
134
+ ranges = bounded_capture_ranges("aaa!", widths, lanes)
135
+ { order: widths, ranges: ranges.map { |range| [range.begin, range.end] },
136
+ replay: grammar.new("aaa!").next_token.last }
137
+ end
138
+ ["", "a", "!aaa"].each do |input|
139
+ grammars.zip(variants.values).each do |grammar, widths|
140
+ check(bounded_capture_ranges(input, widths, lanes), nil)
141
+ check(grammar.recognizer.match(input, 0), nil)
142
+ end
143
+ end
144
+ check(examples.map { |example| example.fetch(:replay) }, [%w[a aa], %w[aa a]])
145
+ { identical_dfa: true, states: dfa.states, examples: examples, compared: (inputs.size + 3) * variants.size }
146
+ end
147
+ end
148
+
149
+ puts JSON.pretty_generate(ruby: RUBY_DESCRIPTION, selection: DFAStretch.selection_probe, captures: DFAStretch.captures_probe) if $PROGRAM_NAME == __FILE__
@@ -1,108 +1,71 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "tempfile"
4
3
  require "json"
5
- require_relative "../lib/flexr/cli"
4
+ require_relative "../lib/flexr"
6
5
 
7
6
  module Flexr
8
7
  module Benchmarking
9
8
  module LramaLexer
10
- LINE_BREAK = /\n/
11
9
  module_function
12
10
 
13
11
  def recognizer(patterns)
14
- source = +"class GrammarRecognizer < Flexr::Lexer\nbackend :firstmatch\noption :experimental, :standalone\n"
15
- patterns.each { |pattern, kind| source << "rule(#{pattern.inspect}, emit: #{kind.inspect})\n" }
16
- source << "end\n"
17
- Tempfile.create(["lrama-recognizer-", ".flexr.rb"]) do |file|
18
- file.write(source)
19
- file.flush
20
- scope = Module.new
21
- scope.module_eval(Generator.new(file.path).generate, file.path)
22
- scope.const_get(:GrammarRecognizer, false)
23
- end
12
+ Class.new(Flexr::Lexer) do
13
+ encoding Encoding::BINARY
14
+ patterns.each { |pattern, kind| rule(pattern, emit: kind) }
15
+ end.recognizer
24
16
  end
25
17
 
26
- def patterns(native, path)
27
- require "prism"
28
- method = nil
29
- visit = lambda do |node|
30
- method = node if node.is_a?(Prism::DefNode) && node.name == :lex_token
31
- node.compact_child_nodes.each { |child| visit.call(child) }
32
- end
33
- visit.call(Prism.parse_file(path).value)
34
- raise "upstream lex_token was not found" unless method
35
-
36
- scans = []
37
- visit = lambda do |node|
38
- if node.is_a?(Prism::CallNode) && node.name == :scan &&
39
- node.receiver.is_a?(Prism::InstanceVariableReadNode) && node.receiver.name == :@scanner
40
- argument = node.arguments.arguments.first
41
- scans << case argument
42
- when Prism::RegularExpressionNode then ::Regexp.new(argument.unescaped, argument.options)
43
- when Prism::ConstantReadNode then native.const_get(argument.name)
44
- else raise "unsupported upstream scan argument"
45
- end
46
- end
47
- node.compact_child_nodes.each { |child| visit.call(child) }
48
- end
49
- visit.call(method)
50
- raise "upstream lex_token scan layout changed" unless scans.length == 12
51
-
52
- scans = scans.drop(4)
53
- scans[0] = ::Regexp.union(native::SYMBOLS.map { |symbol| symbol.gsub(/\\(.)/, '\1') })
54
- scans[1] = ::Regexp.union(native::PERCENT_TOKENS)
55
- scans.zip(%i[SYMBOL DIRECTIVE SYMBOL TAG CHARACTER STRING INTEGER IDENTIFIER])
18
+ def patterns(native)
19
+ symbols = native::SYMBOLS.map { |symbol| [symbol.delete_prefix("\\"), :SYMBOL] }
20
+ symbols + [[/[?+*]/, :SYMBOL], [/[0-9]+/, :INTEGER], [native::IDENTIFIER_PATTERN, :IDENTIFIER]]
56
21
  end
57
22
 
58
23
  def adapter(native, recognizer)
59
24
  Class.new(native) do
60
25
  define_method(:initialize) do |file|
61
26
  super(file)
62
- @recognizer = recognizer.new(file.text)
27
+ @recognizer_input = file.text if file.text.encoding.ascii_compatible? && file.text.valid_encoding?
63
28
  end
64
29
 
65
30
  define_method(:lex_token) do
66
- loop do
67
- if @scanner.scan(LINE_BREAK)
31
+ return super() unless @recognizer_input
32
+
33
+ until @scanner.eos?
34
+ if @scanner.scan("\n")
68
35
  newline
69
36
  elsif @scanner.scan(/[^\S\n]+/)
70
37
  next
71
38
  elsif @scanner.scan(%r{/\*})
72
39
  lex_comment
73
- elsif @scanner.scan(%r{//[^\n]*(?:\n|$)})
74
- newline if @scanner.matched.end_with?("\n")
40
+ elsif @scanner.scan(%r{//.*(?<newline>\n)?})
41
+ newline if @scanner[:newline]
75
42
  else
76
43
  break
77
44
  end
78
45
  end
46
+
47
+ start = @scanner.pos
48
+ match = recognizer.match(@recognizer_input, start)
49
+ return super() unless match
50
+
51
+ kind, ending = match
79
52
  reset_first_position
80
- return if @scanner.eos?
81
-
82
- @recognizer.instance_variable_set(:@position, @scanner.pos)
83
- kind, text = @recognizer.next_token
84
- raise ::ParseError, location.generate_error_message("Unexpected token") if
85
- kind == :DIRECTIVE && @scanner.string.byteslice(@recognizer.byte_pos, 1)&.match?(/[-A-Za-z0-9_.]/)
86
- @scanner.pos = @recognizer.byte_pos
87
- types = { TAG: :Tag, CHARACTER: :Char, STRING: :Str, INTEGER: :Int, IDENTIFIER: :Ident }
88
- token_class = native::Token.const_get(types.fetch(kind, :Token))
89
- value = kind == :INTEGER ? Integer(text) : text
90
- type = case kind
91
- when :SYMBOL, :DIRECTIVE then text
92
- when :IDENTIFIER then identifier_colon? ? :IDENT_COLON : :IDENTIFIER
93
- else kind
53
+ @scanner.pos = ending
54
+ text = @recognizer_input.byteslice(start, ending - start)
55
+ case kind
56
+ when :SYMBOL
57
+ [text, native::Token::Token.new(s_value: text, location: location)]
58
+ when :INTEGER
59
+ [:INTEGER, native::Token::Int.new(s_value: Integer(text), location: location)]
60
+ when :IDENTIFIER
61
+ token = native::Token::Ident.new(s_value: text, location: location)
62
+ [identifier_colon? ? :IDENT_COLON : :IDENTIFIER, token]
94
63
  end
95
- [type, token_class.new(s_value: value, location: location)]
96
- rescue StandardError => e
97
- raise unless e.class.name&.end_with?("LexError")
98
-
99
- raise ::ParseError, location.generate_error_message("Unexpected token")
100
64
  end
101
65
  end
102
66
  end
103
67
 
104
- def observe(klass, source, path)
105
- original = Lrama::Lexer
68
+ def observe(klass, inputs)
106
69
  events = []
107
70
  recording = Class.new(klass) do
108
71
  define_method(:next_token) do
@@ -110,51 +73,71 @@ module Flexr
110
73
  if token
111
74
  type, value = token
112
75
  loc = value.location
113
- events << [type, value.s_value, loc.first_line, loc.first_column, loc.last_line, loc.last_column]
76
+ events << [type, value.class, value.s_value, loc.first_line, loc.first_column, loc.last_line, loc.last_column]
114
77
  end
115
78
  end
116
79
  end
117
80
  end
81
+ with_lexer(recording) do
82
+ inputs.map do |path, source|
83
+ events = []
84
+ error = parse(source, path)
85
+ [events, error]
86
+ end
87
+ end
88
+ end
89
+
90
+ def parse(source, path)
91
+ Lrama::Parser.new(source, path).parse
92
+ nil
93
+ rescue StandardError => e
94
+ [e.class.name, e.message]
95
+ end
96
+
97
+ def with_lexer(klass)
98
+ original = Lrama::Lexer
99
+ return yield if klass == original
100
+
118
101
  Lrama.send(:remove_const, :Lexer)
119
- Lrama.const_set(:Lexer, recording)
120
- error = nil
102
+ Lrama.const_set(:Lexer, klass)
121
103
  begin
122
- Lrama::Parser.new(source, path).parse
123
- rescue StandardError => e
124
- error = [e.class.name, e.message]
104
+ yield
105
+ ensure
106
+ Lrama.send(:remove_const, :Lexer)
107
+ Lrama.const_set(:Lexer, original)
108
+ end
109
+ end
110
+
111
+ def measure(klass, inputs, iterations)
112
+ with_lexer(klass) do
113
+ 3.times { inputs.each { |path, source| parse(source, path) } }
114
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
115
+ iterations.times { inputs.each { |path, source| parse(source, path) } }
116
+ Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
125
117
  end
126
- [events, error]
127
- ensure
128
- Lrama.send(:remove_const, :Lexer)
129
- Lrama.const_set(:Lexer, original)
130
118
  end
131
119
 
132
120
  def run(root, iterations: 3, out: $stdout)
133
121
  $LOAD_PATH.unshift(File.join(root, "lib"))
134
122
  require "lrama"
135
123
  native = Lrama::Lexer
136
- candidate = adapter(native, recognizer(patterns(native, File.join(root, "lib/lrama/lexer.rb"))))
124
+ candidate = adapter(native, recognizer(patterns(native)))
137
125
  paths = Dir[File.join(root, "spec/fixtures/**/*.y")]
138
126
  raise "no upstream fixture corpus" if paths.empty?
139
127
 
140
128
  inputs = paths.map { |path| [path, File.read(path)] }
141
- successful_parses = 0
142
- tokens = 0
143
- inputs.each do |path, source|
144
- expected = observe(native, source, path)
145
- actual = observe(candidate, source, path)
146
- raise "lexer mismatch: #{path}" unless actual == expected
147
- successful_parses += 1 unless expected.last
148
- tokens += expected.first.length
149
- end
150
- timings = { native: native, standalone: candidate }.transform_values do |klass|
151
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
152
- iterations.times { inputs.each { |path, source| observe(klass, source, path) } }
153
- Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
129
+ expected = observe(native, inputs)
130
+ actual = observe(candidate, inputs)
131
+ mismatch = expected.each_index.find { |index| expected[index] != actual[index] }
132
+ raise "lexer mismatch: #{paths.fetch(mismatch)}" if mismatch
133
+
134
+ timings = { native: native, embedded: candidate }.transform_values do |klass|
135
+ measure(klass, inputs, iterations)
154
136
  end
155
- result = { ruby: RUBY_DESCRIPTION, fixtures: paths.length, successful_parses: successful_parses,
156
- tokens_compared: tokens, iterations: iterations, seconds: timings,
157
- scope: "normal grammar tokens; existing trivia, C-code scanning, locations, and parser retained" }
137
+ result = { ruby: RUBY_DESCRIPTION, fixtures: paths.length, successful_parses: expected.count { |_, error| error.nil? },
138
+ tokens_compared: expected.sum { |events, _| events.length }, iterations: iterations, seconds: timings,
139
+ relative_to_native: timings[:embedded] / timings[:native],
140
+ scope: "symbols, integers, and identifiers; other tokens and parser use native Lrama" }
158
141
  out.puts JSON.pretty_generate(result)
159
142
  result
160
143
  end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loaded by upstream RSpec before spec_helper loads regexp_parser.
4
+ require "json"
5
+
6
+ gem "regexp_parser", ENV.fetch("FLEXR_REGEXP_PARSER_VERSION")
7
+ module RegexpParserCorpus
8
+ class << self
9
+ attr_reader :requests, :calls
10
+
11
+ def record(input, options)
12
+ @calls += 1
13
+ source, flags = input.is_a?(Regexp) ? [input.source, input.options] : [input, nil]
14
+ @requests[[source.unpack1("H*"), source.encoding.name, flags, options]] = true
15
+ end
16
+ end
17
+
18
+ @requests = {}
19
+ @calls = 0
20
+
21
+ module Observer
22
+ def scan(input, options: nil, **, &)
23
+ RegexpParserCorpus.record(input, options) if !defined?(Ractor) || Ractor.current == Ractor.main
24
+ super
25
+ end
26
+ end
27
+ end
28
+
29
+ RSpec.configure do |config|
30
+ config.before(:suite) { Regexp::Scanner.prepend(RegexpParserCorpus::Observer) }
31
+ config.after(:suite) do
32
+ data = [RegexpParserCorpus.calls, RegexpParserCorpus.requests.keys]
33
+ File.write(ENV.fetch("FLEXR_REGEXP_PARSER_CORPUS"), JSON.generate(data))
34
+ end
35
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "rbconfig"
5
+ require "tmpdir"
6
+ require_relative "regexp_parser_scanner"
7
+
8
+ module RegexpParserParity
9
+ VERSION = "2.13.4"
10
+
11
+ def self.run(upstream, suite: "spec")
12
+ upstream = File.expand_path(upstream)
13
+ gem "regexp_parser", VERSION
14
+ require "regexp_parser"
15
+ abort "Expected regexp_parser #{VERSION}, got #{Regexp::Parser::VERSION}" unless Regexp::Parser::VERSION == VERSION
16
+
17
+ calls, cases = corpus(upstream, suite)
18
+ results = { exact: 0, unsupported: 0, token_mismatch: 0, upstream_error: 0 }
19
+ findings = {}
20
+ cases.sort_by { |input, options| [input.inspect.length, input.inspect, options.to_i] }.each do |input, options|
21
+ kind, reason, difference = compare(input, options)
22
+ results[kind] += 1
23
+ next if kind == :exact
24
+
25
+ finding = findings[[kind, reason]] ||= {
26
+ result: kind, reason: reason, count: 0,
27
+ sample: { input: input.inspect, encoding: input.encoding.name, options: options }, difference: difference
28
+ }
29
+ finding[:count] += 1
30
+ end
31
+ {
32
+ regexp_parser: VERSION, ruby: RUBY_VERSION, suite: suite, scanner_calls: calls, unique_requests: cases.length,
33
+ results: results, findings: findings.values.sort_by { |row| [row[:result].to_s, row[:reason]] }
34
+ }
35
+ end
36
+
37
+ def self.corpus(upstream, suite)
38
+ observer = File.expand_path("regexp_parser_corpus.rb", __dir__)
39
+ Dir.mktmpdir("flexr-regexp-parser") do |directory|
40
+ path = File.join(directory, "requests")
41
+ success = system({ "FLEXR_REGEXP_PARSER_CORPUS" => path, "FLEXR_REGEXP_PARSER_VERSION" => VERSION },
42
+ RbConfig.ruby, "-S", "rspec", "-I", File.join(upstream, "spec"), "--require", observer, File.join(upstream, suite),
43
+ chdir: directory, out: $stderr)
44
+ abort "Upstream RSpec failed" unless success
45
+
46
+ calls, requests = JSON.parse(File.read(path))
47
+ cases = requests.map do |hex, encoding, flags, options|
48
+ source = [hex].pack("H*").force_encoding(encoding)
49
+ [flags.nil? ? source : Regexp.new(source, flags), options]
50
+ end
51
+ abort "Upstream RSpec did not exercise Regexp::Scanner" if cases.empty?
52
+
53
+ [calls, cases]
54
+ end
55
+ end
56
+
57
+ def self.compare(input, options)
58
+ expected = reference(input, options)
59
+ actual = begin
60
+ Scanner.scan(input, options)
61
+ rescue Unsupported => e
62
+ e
63
+ end
64
+ if expected.is_a?(StandardError)
65
+ outcome = actual.is_a?(Unsupported) ? "prototype rejected" : "prototype accepted"
66
+ return [:upstream_error, "#{expected.class.name} (#{outcome})", { message: expected.message }]
67
+ end
68
+ return [:unsupported, actual.message] if actual.is_a?(Unsupported)
69
+
70
+ index = [expected.size, actual.size].max.times.find do |i|
71
+ expected[i] != actual[i] || expected[i][2].encoding != actual[i][2].encoding
72
+ end
73
+ return [:exact] if index.nil?
74
+
75
+ [:token_mismatch, "first differing token", { index: index, upstream: expected[index], flexr: actual[index] }]
76
+ end
77
+
78
+ def self.reference(input, options)
79
+ Regexp::Scanner.scan(input, options: options)
80
+ rescue Regexp::Scanner::ScannerError, ArgumentError => e
81
+ e
82
+ end
83
+ end
84
+
85
+ if $PROGRAM_NAME == __FILE__
86
+ abort "Usage: ruby -Ilib benchmark/regexp_parser_parity.rb UPSTREAM_CHECKOUT [SPEC_PATH]" unless (1..2).cover?(ARGV.size)
87
+
88
+ puts JSON.pretty_generate(RegexpParserParity.run(ARGV[0], suite: ARGV.fetch(1, "spec")))
89
+ end