flexr 1.1.0 → 1.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 (101) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +1 -0
  3. data/CHANGELOG.md +116 -0
  4. data/CONTRIBUTING.md +13 -1
  5. data/README.md +6 -2
  6. data/Rakefile +41 -5
  7. data/Steepfile +7 -0
  8. data/benchmark/golden/calculator_lexer.rb +276 -0
  9. data/benchmark/golden/graphql_lexer.rb +310 -0
  10. data/benchmark/golden/json_lexer.rb +292 -0
  11. data/benchmark/golden/regexp_tokenizer.rb +293 -0
  12. data/benchmark/golden/ruby_subset_lexer.rb +280 -0
  13. data/benchmark/golden/sql_lexer.rb +293 -0
  14. data/benchmark/golden/toml_lexer.rb +292 -0
  15. data/benchmark/golden/toy_lang_lexer.rb +273 -0
  16. data/benchmark/golden/with_lrama_lexer.rb +264 -0
  17. data/benchmark/golden/with_racc_lexer.rb +264 -0
  18. data/benchmark/lrama_lexer.rb +165 -0
  19. data/benchmark/matrix.rb +79 -0
  20. data/benchmark/profile.rb +109 -0
  21. data/benchmark/run.rb +4 -1
  22. data/benchmark/state_dispatch.rb +78 -0
  23. data/docs/README.md +1 -2
  24. data/docs/RELEASING.md +9 -2
  25. data/docs/migration-v2.md +73 -0
  26. data/docs/perf-log.md +108 -0
  27. data/docs/reference/README.md +2 -0
  28. data/docs/reference/cli.md +71 -5
  29. data/docs/reference/compatibility.md +9 -2
  30. data/docs/reference/diagnostics.md +338 -0
  31. data/docs/reference/dsl.md +8 -5
  32. data/docs/reference/errors.md +28 -0
  33. data/docs/reference/generated-artifacts.md +11 -0
  34. data/docs/reference/public-api.md +32 -8
  35. data/docs/reference/regexp.md +19 -7
  36. data/docs/reference/ruby-lsp.md +34 -0
  37. data/docs/reference/testing.md +57 -0
  38. data/examples/graphql/README.md +14 -0
  39. data/examples/graphql/lexer.flexr.rb +29 -0
  40. data/examples/sql/README.md +16 -0
  41. data/examples/sql/lexer.flexr.rb +23 -0
  42. data/examples/toml/README.md +14 -0
  43. data/examples/toml/lexer.flexr.rb +23 -0
  44. data/gemfiles/ruby_lsp.gemfile +4 -0
  45. data/gemfiles/types.gemfile +7 -0
  46. data/lib/flexr/automaton/accel.rb +11 -1
  47. data/lib/flexr/automaton/analysis.rb +161 -7
  48. data/lib/flexr/automaton/compiler.rb +175 -24
  49. data/lib/flexr/cli.rb +117 -17
  50. data/lib/flexr/codegen/firstmatch.rb +1 -7
  51. data/lib/flexr/codegen/table.rb +2 -2
  52. data/lib/flexr/configuration.rb +8 -0
  53. data/lib/flexr/deprecations.rb +26 -0
  54. data/lib/flexr/diagnostics.rb +39 -3
  55. data/lib/flexr/dsl.rb +11 -9
  56. data/lib/flexr/errors.rb +6 -6
  57. data/lib/flexr/generated.rb +27 -15
  58. data/lib/flexr/generator.rb +44 -29
  59. data/lib/flexr/grammar.rb +41 -0
  60. data/lib/flexr/ir.rb +2 -2
  61. data/lib/flexr/migration.rb +31 -0
  62. data/lib/flexr/minitest.rb +24 -0
  63. data/lib/flexr/options.rb +4 -2
  64. data/lib/flexr/regexp/matcher.rb +26 -0
  65. data/lib/flexr/regexp/normalizer.rb +4 -8
  66. data/lib/flexr/regexp/parser.rb +127 -21
  67. data/lib/flexr/regexp/tokenizer.rb +4 -4
  68. data/lib/flexr/rspec.rb +51 -0
  69. data/lib/flexr/runtime/core.rb +21 -15
  70. data/lib/flexr/runtime/errors.rb +6 -4
  71. data/lib/flexr/runtime/interpreter.rb +47 -45
  72. data/lib/flexr/runtime/location.rb +5 -4
  73. data/lib/flexr/runtime/token.rb +1 -0
  74. data/lib/flexr/runtime.rb +6 -2
  75. data/lib/flexr/source/passthrough.rb +14 -11
  76. data/lib/flexr/source/prism_reader.rb +45 -14
  77. data/lib/flexr/testing.rb +47 -0
  78. data/lib/flexr/trace.rb +197 -0
  79. data/lib/flexr/unicode/property.rb +1 -2
  80. data/lib/flexr/unicode/reference_regexp.rb +8 -9
  81. data/lib/flexr/version.rb +1 -1
  82. data/lib/flexr.rb +1 -0
  83. data/lib/ruby_lsp/flexr/addon.rb +114 -0
  84. data/sig/flexr.rbs +185 -0
  85. data/site/src/layouts/SiteLayout.astro +8 -2
  86. data/site/src/pages/index.astro +69 -155
  87. data/site/src/styles/custom.css +4 -287
  88. data/site/src/styles/landing.css +239 -0
  89. data/test/ruby_lsp_addon_spec.rb +135 -0
  90. data/tools/docs_verify.rb +1 -0
  91. data/tools/golden.rb +54 -0
  92. data/tools/release_notes.rb +16 -0
  93. metadata +44 -11
  94. data/benchmark/golden/calculator_lexer.sha256 +0 -1
  95. data/benchmark/golden/json_lexer.sha256 +0 -1
  96. data/benchmark/golden/regexp_tokenizer.sha256 +0 -1
  97. data/benchmark/golden/ruby_subset_lexer.sha256 +0 -1
  98. data/benchmark/golden/toy_lang_lexer.sha256 +0 -1
  99. data/benchmark/golden/with_lrama_lexer.sha256 +0 -1
  100. data/benchmark/golden/with_racc_lexer.sha256 +0 -1
  101. data/docs/releases/v1.1.0.md +0 -44
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tempfile"
4
+ require "json"
5
+ require_relative "../lib/flexr/cli"
6
+
7
+ module Flexr
8
+ module Benchmarking
9
+ module LramaLexer
10
+ LINE_BREAK = /\n/
11
+ module_function
12
+
13
+ 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
24
+ end
25
+
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])
56
+ end
57
+
58
+ def adapter(native, recognizer)
59
+ Class.new(native) do
60
+ define_method(:initialize) do |file|
61
+ super(file)
62
+ @recognizer = recognizer.new(file.text)
63
+ end
64
+
65
+ define_method(:lex_token) do
66
+ loop do
67
+ if @scanner.scan(LINE_BREAK)
68
+ newline
69
+ elsif @scanner.scan(/[^\S\n]+/)
70
+ next
71
+ elsif @scanner.scan(%r{/\*})
72
+ lex_comment
73
+ elsif @scanner.scan(%r{//[^\n]*(?:\n|$)})
74
+ newline if @scanner.matched.end_with?("\n")
75
+ else
76
+ break
77
+ end
78
+ end
79
+ 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
94
+ 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
+ end
101
+ end
102
+ end
103
+
104
+ def observe(klass, source, path)
105
+ original = Lrama::Lexer
106
+ events = []
107
+ recording = Class.new(klass) do
108
+ define_method(:next_token) do
109
+ super().tap do |token|
110
+ if token
111
+ type, value = token
112
+ loc = value.location
113
+ events << [type, value.s_value, loc.first_line, loc.first_column, loc.last_line, loc.last_column]
114
+ end
115
+ end
116
+ end
117
+ end
118
+ Lrama.send(:remove_const, :Lexer)
119
+ Lrama.const_set(:Lexer, recording)
120
+ error = nil
121
+ begin
122
+ Lrama::Parser.new(source, path).parse
123
+ rescue StandardError => e
124
+ error = [e.class.name, e.message]
125
+ end
126
+ [events, error]
127
+ ensure
128
+ Lrama.send(:remove_const, :Lexer)
129
+ Lrama.const_set(:Lexer, original)
130
+ end
131
+
132
+ def run(root, iterations: 3, out: $stdout)
133
+ $LOAD_PATH.unshift(File.join(root, "lib"))
134
+ require "lrama"
135
+ native = Lrama::Lexer
136
+ candidate = adapter(native, recognizer(patterns(native, File.join(root, "lib/lrama/lexer.rb"))))
137
+ paths = Dir[File.join(root, "spec/fixtures/**/*.y")]
138
+ raise "no upstream fixture corpus" if paths.empty?
139
+
140
+ 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
154
+ 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" }
158
+ out.puts JSON.pretty_generate(result)
159
+ result
160
+ end
161
+ end
162
+ end
163
+ end
164
+
165
+ Flexr::Benchmarking::LramaLexer.run(ARGV.fetch(0)) if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require "rbconfig"
5
+ require_relative "run"
6
+
7
+ module Flexr
8
+ module Benchmarking
9
+ class RubyMatrix
10
+ ROOT = File.expand_path("..", __dir__)
11
+ FLAGS = { "interpreter" => ["--disable=yjit,zjit"], "yjit" => ["--yjit"], "zjit" => ["--zjit"] }.freeze
12
+ PROBE = <<~RUBY.lines.map(&:strip).join(";").freeze
13
+ require "json"
14
+ engine = ARGV.fetch(0)
15
+ enabled = case engine
16
+ when "interpreter"
17
+ !(defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?) && !(defined?(RubyVM::ZJIT) && RubyVM::ZJIT.enabled?)
18
+ when "yjit" then defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?
19
+ when "zjit" then defined?(RubyVM::ZJIT) && RubyVM::ZJIT.enabled?
20
+ end
21
+ puts JSON.generate(available: !!enabled, ruby: RUBY_DESCRIPTION, reason: enabled ? nil : "engine is not enabled by this Ruby build")
22
+ RUBY
23
+
24
+ def initialize(arguments: [], probe: nil, benchmark: nil)
25
+ @arguments = arguments
26
+ @probe = probe || method(:probe_engine)
27
+ @benchmark = benchmark || method(:benchmark_engine)
28
+ end
29
+
30
+ def run(engines: FLAGS.keys)
31
+ results = engines.to_h do |engine|
32
+ availability = @probe.call(engine)
33
+ result = if availability.fetch("available")
34
+ { "status" => "measured", "ruby" => availability["ruby"], "result" => @benchmark.call(engine) }
35
+ else
36
+ { "status" => "unavailable", "reason" => availability.fetch("reason") }
37
+ end
38
+ [engine, result]
39
+ end
40
+ { "schema" => 1, "engines" => results }
41
+ end
42
+
43
+ def self.command(argv, out: $stdout, err: $stderr)
44
+ options = Benchmarking.parse(argv.dup)
45
+ return Benchmarking.usage(out) if options[:help]
46
+ raise ArgumentError, "matrix results cannot share a baseline output file" if options[:write_baseline]
47
+
48
+ out.puts JSON.pretty_generate(new(arguments: argv).run)
49
+ 0
50
+ rescue ArgumentError, Errno::ENOENT => e
51
+ err.puts "matrix error: #{e.message}"
52
+ 2
53
+ rescue RuntimeError => e
54
+ err.puts "matrix error: #{e.message}"
55
+ 1
56
+ end
57
+
58
+ private
59
+
60
+ def probe_engine(engine)
61
+ stdout, stderr, status = Open3.capture3({ "RUBYOPT" => nil }, RbConfig.ruby, *FLAGS.fetch(engine),
62
+ "-e", PROBE, engine, chdir: ROOT)
63
+ return { "available" => false, "reason" => stderr.strip } unless status.success?
64
+
65
+ JSON.parse(stdout)
66
+ end
67
+
68
+ def benchmark_engine(engine)
69
+ stdout, stderr, status = Open3.capture3({ "RUBYOPT" => nil }, RbConfig.ruby, *FLAGS.fetch(engine),
70
+ "-Ilib", "benchmark/run.rb", *@arguments, "--json", chdir: ROOT)
71
+ raise "#{engine} benchmark failed (#{status.exitstatus}): #{stderr}#{stdout}" unless status.success?
72
+
73
+ JSON.parse(stdout)
74
+ end
75
+ end
76
+ end
77
+ end
78
+
79
+ exit Flexr::Benchmarking::RubyMatrix.command(ARGV) if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "run"
4
+
5
+ module Flexr
6
+ module Benchmarking
7
+ class PhaseProfiler
8
+ attr_reader :seconds, :elapsed
9
+
10
+ def initialize
11
+ @seconds = %w[scanning actions tokens locations other].to_h { |phase| [phase, 0.0] }
12
+ end
13
+
14
+ def measure(&)
15
+ stack = ["other"]
16
+ started = previous = clock
17
+ @trace = TracePoint.new(:call, :return, :c_call, :c_return) do |event|
18
+ now = clock
19
+ @seconds[stack.last] += now - previous
20
+ previous = now
21
+ if %i[call c_call].include?(event.event)
22
+ stack << (phase(event) || stack.last)
23
+ elsif stack.length > 1
24
+ stack.pop
25
+ end
26
+ end
27
+ @trace.enable(target_thread: Thread.current, &)
28
+ ensure
29
+ @trace&.disable
30
+ finished = clock
31
+ @seconds[stack.last] += finished - previous
32
+ @elapsed = finished - started
33
+ end
34
+
35
+ def enabled?
36
+ @trace&.enabled? || false
37
+ end
38
+
39
+ private
40
+
41
+ def clock
42
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
43
+ end
44
+
45
+ def phase(event)
46
+ if event.self.is_a?(Runtime::Interpreter)
47
+ return "scanning" if event.method_id == :scan
48
+ elsif event.self.is_a?(Lexer)
49
+ case event.method_id
50
+ when :scan_one then return "scanning"
51
+ when :execute then return "actions"
52
+ when :emit, :text, :next_token, :tokens then return "tokens"
53
+ when :last_location, :update_position, :advance_location! then return "locations"
54
+ end
55
+ end
56
+ nil
57
+ end
58
+ end
59
+
60
+ class ProfileRunner < Runner
61
+ def run
62
+ path = File.expand_path(@options.fetch(:spec))
63
+ input = input_for(path)
64
+ runtime = profile_class(load_runtime(path), input)
65
+ generated = profile_class(load_generated(path), input)
66
+ {
67
+ "schema" => 1, "ruby" => RUBY_DESCRIPTION,
68
+ "spec" => relative_path(path), "input_bytes" => input.bytesize,
69
+ "input_sha256" => Digest::SHA256.hexdigest(input),
70
+ "iterations" => @options.fetch(:iterations),
71
+ "note" => "TracePoint changes execution costs and disables JIT optimizations; use phase timings only to locate work, not as throughput measurements.",
72
+ "modes" => { "runtime" => runtime, "generated" => generated }
73
+ }
74
+ end
75
+
76
+ private
77
+
78
+ def profile_class(klass, input)
79
+ iterations = @options.fetch(:iterations)
80
+ klass.new(input).tokens
81
+ profiler = PhaseProfiler.new
82
+ tokens = profiler.measure do
83
+ result = nil
84
+ iterations.times { result = klass.new(input).tokens }
85
+ result
86
+ end
87
+ {
88
+ "tokens" => tokens.length,
89
+ "instrumented_elapsed_seconds" => profiler.elapsed,
90
+ "phase_seconds" => profiler.seconds
91
+ }
92
+ end
93
+ end
94
+
95
+ def self.profile(argv, out: $stdout, err: $stderr)
96
+ options = parse(argv.dup)
97
+ return usage(out) if options[:help]
98
+ raise ArgumentError, "profiling does not support baseline checks or writes" if options[:baseline] || options[:write_baseline]
99
+
100
+ out.puts JSON.pretty_generate(ProfileRunner.new(options).run)
101
+ 0
102
+ rescue ArgumentError, Errno::ENOENT => e
103
+ err.puts "profile error: #{e.message}"
104
+ 2
105
+ end
106
+ end
107
+ end
108
+
109
+ exit Flexr::Benchmarking.profile(ARGV) if $PROGRAM_NAME == __FILE__
data/benchmark/run.rb CHANGED
@@ -13,7 +13,10 @@ module Flexr
13
13
  DEFAULT_SPEC = File.expand_path("../examples/json/lexer.flexr.rb", __dir__)
14
14
  DEFAULT_INPUTS = {
15
15
  %r{/examples/json/} => ('{"answer": 42}' * 10_000).freeze,
16
- %r{/examples/toy_lang/} => ("answer + 12" * 10_000).freeze
16
+ %r{/examples/toy_lang/} => ("answer + 12" * 10_000).freeze,
17
+ %r{/examples/toml/} => ('title = "flexr" ' * 10_000).freeze,
18
+ %r{/examples/graphql/} => ('query { user(id: 12) { name } } ' * 10_000).freeze,
19
+ %r{/examples/sql/} => ('select name from users where id >= 12; ' * 10_000).freeze
17
20
  }.freeze
18
21
 
19
22
  module_function
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "run"
4
+ require_relative "../lib/flexr/cli"
5
+
6
+ module Flexr
7
+ module Benchmarking
8
+ module StateDispatch
9
+ module_function
10
+
11
+ def lexers(path)
12
+ parsed = CLI.read_spec(path)
13
+ compiled = CLI.compile(parsed, overrides: { backend: :table })
14
+ indent = Source::Passthrough.indentation(parsed.source, parsed.first_dsl_offset)
15
+ scanner = Codegen::Table.new(compiled).source(indent: indent)
16
+ replacement = scanner.gsub("dfa.transition(current, byte)", "__flexr_state_transition(current, ec[byte])")
17
+ raise "generated scanner has no table dispatch" if replacement == scanner
18
+
19
+ replacement += dispatch_source(compiled, indent)
20
+ generated = Generator.new(path, options: { backend: :table }).generate
21
+ raise "generated scanner template changed" unless generated.include?(scanner)
22
+
23
+ [generated, Generator.new(path, options: { backend: :direct }).generate,
24
+ generated.sub(scanner, replacement)].map do |source|
25
+ scope = Module.new
26
+ scope.module_eval(source, path)
27
+ parsed.class_name.split("::").reject(&:empty?).inject(scope) { |parent, name| parent.const_get(name, false) }
28
+ end
29
+ end
30
+
31
+ def dispatch_source(compiled, indent)
32
+ lines = ["def __flexr_state_transition(state, class_id)", "case @state"]
33
+ compiled.machines.each do |name, machine|
34
+ lines << "when #{name.inspect}" << "case state"
35
+ machine.dfa.transitions.each_with_index do |row, state|
36
+ if row.compact.empty?
37
+ lines << "when #{state} then nil"
38
+ next
39
+ end
40
+ lines << "when #{state}" << "case class_id"
41
+ row.each_with_index.group_by(&:first).each do |destination, pairs|
42
+ next unless destination
43
+
44
+ lines << "when #{pairs.map(&:last).join(', ')} then #{destination}"
45
+ end
46
+ lines << "else nil" << "end"
47
+ end
48
+ lines << "else nil" << "end"
49
+ end
50
+ (lines + ["else nil", "end", "end"]).map { |line| "#{indent}#{line}\n" }.join
51
+ end
52
+
53
+ def run(argv, out: $stdout)
54
+ options = Benchmarking.parse(argv.dup)
55
+ return Benchmarking.usage(out) if options[:help]
56
+ raise ArgumentError, "--baseline and --write-baseline do not apply to this experiment" if options[:baseline] || options[:write_baseline]
57
+
58
+ path = File.expand_path(options.fetch(:spec))
59
+ input = options[:input_file] ? File.binread(options[:input_file]) : Benchmarking::DEFAULT_INPUTS.find { |pattern, _| path.match?(pattern) }&.last
60
+ raise ArgumentError, "--input-file is required for this spec" unless input
61
+
62
+ table, direct, switched = lexers(path)
63
+ expected = table.new(input).tokens
64
+ raise "state dispatch changed tokens" unless [direct, switched].all? { |lexer| lexer.new(input).tokens == expected }
65
+
66
+ runner = Runner.new(options)
67
+ result = { ruby: RUBY_DESCRIPTION, input_bytes: input.bytesize, iterations: options[:iterations],
68
+ modes: { table: runner.send(:measure_class, table, input),
69
+ direct: runner.send(:measure_class, direct, input),
70
+ state_cases: runner.send(:measure_class, switched, input) } }
71
+ out.puts JSON.pretty_generate(result)
72
+ result
73
+ end
74
+ end
75
+ end
76
+ end
77
+
78
+ Flexr::Benchmarking::StateDispatch.run(ARGV) if $PROGRAM_NAME == __FILE__
data/docs/README.md CHANGED
@@ -61,5 +61,4 @@ pages explain how to use those specifications.
61
61
 
62
62
  The [performance log](perf-log.md), [architecture decisions](adr/),
63
63
  [internals notes](internals/README.md), and [release procedure](RELEASING.md)
64
- are maintainer-facing documents. Release notes are kept under
65
- [releases](releases/v1.1.0.md).
64
+ are maintainer-facing documents.
data/docs/RELEASING.md CHANGED
@@ -18,13 +18,20 @@ output as SVG and should be run before a release that changes CLI visualization.
18
18
 
19
19
  Then:
20
20
 
21
- 1. Review the commits since the previous release and update `lib/flexr/version.rb`.
21
+ 1. Review the commits since the previous release, add a version section
22
+ to [the changelog](../CHANGELOG.md), and update `lib/flexr/version.rb`.
22
23
  2. Verify the gemspec metadata URLs.
23
24
  3. Build and inspect the package with `gem build flexr.gemspec`.
24
25
  4. Confirm generated golden files and the Unicode snapshot are intentional.
25
26
  5. Create the release tag only after the working tree and CI are clean.
26
27
 
28
+ Pushing a v1 tag runs the release checks before building and publishing the
29
+ gem through RubyGems Trusted Publishing. The workflow then creates a GitHub
30
+ Release from that version's changelog, leaving the latest major release
31
+ selected on GitHub. Use the version number as the level-two changelog heading,
32
+ optionally linked to the tag comparison. GitHub records the publication date.
33
+
27
34
  Unicode snapshot changes are minor-version compatibility changes because they
28
35
  can change generated output. Stable runtime and generated-file contracts are
29
- preserved within a major version unless this document and the release commits
36
+ preserved within a major version unless this document and the changelog
30
37
  state a migration.
@@ -0,0 +1,73 @@
1
+ # Migrating to flexr 2.0
2
+
3
+ This guide describes how to upgrade to flexr 2.0. The 1.2 release line offers
4
+ opt-in deprecation warnings while keeping the 1.x runtime contracts.
5
+
6
+ Run static checks before upgrading:
7
+
8
+ ```sh
9
+ flexr check lexer.flexr.rb --target 2.0
10
+ flexr check lexer.flexr.rb --target 2.0 --format json
11
+ RUBYOPT=-W:deprecated ruby application.rb
12
+ ```
13
+
14
+ `--target 2.0` reports the new requirements and identifies structured-token
15
+ declarations. It includes migration advice even when ordinary compiler
16
+ warnings are disabled with `--warn none`. `--warn-as-error` fails for migration
17
+ warnings. The mode uses the static reader and cannot be combined with `--eval`.
18
+ It does not execute the specification or scan consumer files, dependencies,
19
+ or metaprogramming; a clean result does not prove the application is ready.
20
+
21
+ ## Ruby version
22
+
23
+ Use Ruby 3.4 or newer for the runtime, generator, and standalone lexers. Upgrade
24
+ deployment images and development tools before upgrading flexr. Loading v1 on
25
+ an older Ruby emits a notice when deprecated-category warnings are enabled.
26
+
27
+ ## Immutable tokens and locations
28
+
29
+ With `token_kind :struct`, tokens and locations become `Data` records. The
30
+ option name stays `:struct` to avoid changing lexer declarations. Attribute
31
+ readers, keyword construction, and read-only indexing remain available.
32
+ Field setters, `[]=`, and checks that require a `Struct` instance must change.
33
+ The default array token format is unaffected.
34
+
35
+ Replace mutation with a new value:
36
+
37
+ ```ruby
38
+ # Before
39
+ token.value = replacement
40
+
41
+ # After upgrading to v2
42
+ token = token.with(value: replacement)
43
+ ```
44
+
45
+ Use attribute readers or `to_h` rather than relying on Struct-specific
46
+ enumeration or the raw storage of lazy location columns. Column readers
47
+ remain available without retaining the lexer. Immutability is shallow: a
48
+ mutable object emitted as a token value remains the application's responsibility.
49
+ When deprecated-category warnings are enabled, v1 warns on record field
50
+ assignments and `[]=` calls. It does not detect mutations of nested values or
51
+ every Struct mutator, so inspect consumer code and tests as well.
52
+
53
+ ## Error policy
54
+
55
+ Only `error_mode: :raise`, `:token`, and `:panic` are valid in v2. An unknown
56
+ value raises `ArgumentError` during initialization, including for empty or
57
+ otherwise matching input. v1 warns at initialization when deprecation warnings
58
+ are enabled, while preserving its existing fallback behavior.
59
+
60
+ ## Generated artifacts
61
+
62
+ Regenerate every lexer with the new generator after upgrading. Artifact schema
63
+ and runtime ABI change to version 2; loading an incompatible old artifact
64
+ produces `FLEXR-E020` with regeneration guidance. Standalone artifacts bundle
65
+ their runtime, so regenerate them as part of deployment as well. v1 reports an
66
+ opt-in warning when loading an ABI 1 artifact. Do not edit artifact metadata by
67
+ hand to bypass compatibility checks.
68
+
69
+ ## Backends
70
+
71
+ `firstmatch` remains available with its explicit first-matching-rule semantics;
72
+ it does not acquire the longest-match behavior of `table`, `direct`, and `auto`.
73
+ No backend removal is required by this migration.
data/docs/perf-log.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # Performance log
2
2
 
3
+ ## State-specific dispatch experiment (2026-11-20)
4
+
5
+ `benchmark/state_dispatch.rb` compares generated table dispatch, the existing
6
+ flattened direct representation, and per-state Ruby `case` branches. It checks
7
+ token equality before timing. The transition test compares every state/byte pair.
8
+ It is a development experiment and does not add a public backend.
9
+
10
+ ```sh
11
+ bundle exec ruby benchmark/state_dispatch.rb --iterations 5
12
+ RUBYOPT=--yjit bundle exec ruby benchmark/state_dispatch.rb --iterations 5
13
+ RUBYOPT=--zjit bundle exec ruby benchmark/state_dispatch.rb --iterations 5
14
+ ```
15
+
16
+ Measured on Ruby 4.0.9, arm64-darwin25, built-in 140,000-byte JSON input:
17
+
18
+ | Engine | Table MB/s | Direct MB/s | State cases MB/s |
19
+ |---|---:|---:|---:|
20
+ | Interpreter | 1.170 | 1.729 | 1.709 |
21
+ | YJIT | 1.922 | 2.796 | 2.768 |
22
+ | ZJIT | 0.458 | 0.425 | 0.483 |
23
+
24
+ These short local samples are not release qualification or confidence intervals.
25
+ State cases do not improve on the existing direct representation in the
26
+ interpreter or YJIT samples, and ZJIT needs longer warm-up investigation.
27
+ Keep the existing direct backend and `auto` selection until repeatable gains
28
+ justify adding and maintaining another backend. No regression baseline changes
29
+ are warranted by this experiment.
30
+ ## Lrama standalone recognizer experiment (2026-11-20)
31
+
32
+ `benchmark/lrama_lexer.rb` builds a standalone grammar-token recognizer and
33
+ adapts Lrama's lexer to use it for normal grammar tokens. Existing trivia,
34
+ C-code scanning, identifier lookahead, token classes, locations, and parser
35
+ are retained. The adapter deliberately uses private scanner positions; this
36
+ is an experiment, not a supported Lrama integration or a production replacement.
37
+
38
+ ```sh
39
+ git clone https://github.com/ruby/lrama.git /tmp/lrama
40
+ git -C /tmp/lrama checkout 22de9d99f6402290a637627f3516a1a2db6c9aab
41
+ bundle exec ruby benchmark/lrama_lexer.rb /tmp/lrama
42
+ ```
43
+
44
+ The pinned upstream revision's 78 grammar fixtures produced identical token
45
+ kinds, values, locations, and parser errors: 77 parsed successfully, and 3,767
46
+ tokens were compared. Both paths include the same parser and event collection.
47
+ On Ruby 4.0.9, arm64-darwin25, three corpus passes took 0.0434 seconds with
48
+ Lrama's scanner and 11.9124 seconds with the standalone recognizer adapter.
49
+ These short local timings are illustrative, not a statistical benchmark.
50
+
51
+ This approach is substantially slower and adds adapter maintenance, so do not
52
+ propose it upstream. It adds no Lrama runtime dependency to flexr. The tool
53
+ checks the upstream scan layout and fails explicitly if it changes; a future
54
+ attempt should first remove per-token adapter and firstmatch overhead.
55
+
3
56
  The benchmark harness reports bytes/s, tokens/s, and allocations per token.
4
57
  Numbers are intentionally recorded only after running the harness on the
5
58
  target Ruby and hardware; no unmeasured figures are presented as guarantees.
@@ -10,6 +63,23 @@ Run:
10
63
  ruby -Ilib benchmark/run.rb
11
64
  ```
12
65
 
66
+ For independent Ruby interpreter, YJIT, and ZJIT processes, run
67
+ `bundle exec rake bench:matrix`. The JSON report checks that each engine is
68
+ actually enabled and marks unavailable builds explicitly. It does not replace
69
+ the baseline with a different engine's measurements. Use
70
+ `ruby benchmark/matrix.rb --input-file PATH --iterations 3` for a custom input.
71
+
72
+ `bundle exec rake bench:profile` provides an optional TracePoint profile without
73
+ an extra gem. It excludes class loading and compilation after a warm-up run and
74
+ reports non-overlapping time in scanning, actions, token handling, locations,
75
+ and other work for runtime and generated modes. Scanning includes the DFA byte
76
+ loop and matcher overhead; token handling includes `next_token`, `emit`, and
77
+ text materialization; locations include position updates and lazy location
78
+ construction. These are instrumented costs: TracePoint adds substantial
79
+ overhead and changes JIT behavior, so do not compare these times with normal
80
+ throughput. Use `ruby benchmark/profile.rb --input-file PATH --iterations 1`
81
+ to profile a custom input. `FLEXR_BENCHMARK_ITERATIONS` controls either rake task.
82
+
13
83
  The JSON result includes `mb_per_s`, `tokens_per_s`, and cumulative Ruby
14
84
  `allocations_per_token` for runtime, generated, and handwritten modes. JSON
15
85
  also records each Flexr mode as a ratio against the handwritten baseline.
@@ -70,3 +140,41 @@ Both the portable baseline comparison and the ordinary 0.18x performance
70
140
  floor pass in this sample. `auto` acceleration now stops trying a region after
71
141
  repeated short runs, while explicit `strscan` and `regexp` modes remain fixed
72
142
  choices for workloads that have measured long runs.
143
+
144
+ ## 2026-11-20
145
+
146
+ On Ruby 4.0.9 (`3e93b23afc`, arm64-darwin25), revision `0391a6e`, the default
147
+ 140,000-byte JSON input produced 50,000 tokens. `ruby benchmark/matrix.rb
148
+ --iterations 3` warmed each mode for three iterations, then measured three
149
+ iterations in a separate process per engine. All three engines were available.
150
+ This is one local sample from a development session, not an isolated performance
151
+ qualification or a reason to raise the regression baseline.
152
+
153
+ | Engine | Mode | MB/s | allocations/token | handwritten ratio |
154
+ |---|---|---:|---:|---:|
155
+ | Interpreter | runtime | 1.700 | 5.200 | 0.204x |
156
+ | Interpreter | generated | 1.668 | 5.210 | 0.200x |
157
+ | Interpreter | handwritten | 8.343 | 3.400 | 1.000x |
158
+ | YJIT | runtime | 4.789 | 5.200 | 0.464x |
159
+ | YJIT | generated | 2.894 | 5.210 | 0.281x |
160
+ | YJIT | handwritten | 10.316 | 3.400 | 1.000x |
161
+ | ZJIT | runtime | 1.958 | 5.200 | 0.203x |
162
+ | ZJIT | generated | 0.414 | 5.210 | 0.043x |
163
+ | ZJIT | handwritten | 9.639 | 3.400 | 1.000x |
164
+
165
+ The input SHA-256 is
166
+ `f15489cc8fa286cd365fb167b3f99d3d216dc90c0de6279fe9f36c8d2215d7a7`.
167
+ ZJIT's generated result is slow in this short run; it needs investigation with
168
+ longer warm-up before drawing conclusions about steady-state performance.
169
+
170
+ A separate `ruby benchmark/profile.rb --iterations 1` run reported the
171
+ following instrumented times:
172
+
173
+ | Mode | Scanning | Actions | Token handling | Locations | Other |
174
+ |---|---:|---:|---:|---:|---:|
175
+ | runtime | 2.495 s | 0.470 s | 1.479 s | 0.132 s | 0.002 s |
176
+ | generated | 2.669 s | 0.459 s | 1.466 s | 0.132 s | 0.001 s |
177
+
178
+ Scanning is the largest category in this instrumented sample, followed by token
179
+ handling. These categories identify work to investigate; they do not establish
180
+ uninstrumented phase percentages or prove a particular optimization will help.