flexr 2.0.0 → 2.1.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 (89) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +28 -0
  3. data/CONTRIBUTING.md +10 -7
  4. data/Rakefile +11 -1
  5. data/benchmark/golden/calculator_lexer.rb +6 -14
  6. data/benchmark/golden/graphql_lexer.rb +6 -14
  7. data/benchmark/golden/json_lexer.rb +18 -28
  8. data/benchmark/golden/regexp_tokenizer.rb +6 -14
  9. data/benchmark/golden/ruby_subset_lexer.rb +6 -14
  10. data/benchmark/golden/sql_lexer.rb +6 -14
  11. data/benchmark/golden/toml_lexer.rb +6 -14
  12. data/benchmark/golden/toy_lang_lexer.rb +6 -14
  13. data/benchmark/golden/with_lrama_lexer.rb +6 -14
  14. data/benchmark/golden/with_racc_lexer.rb +6 -14
  15. data/benchmark/matrix.rb +31 -4
  16. data/docs/RELEASING.md +13 -2
  17. data/docs/adr/0003-leftmost-longest.md +3 -0
  18. data/docs/adr/0019-measured-performance-floor.md +4 -9
  19. data/docs/adr/0027-per-engine-performance-targets.md +45 -0
  20. data/docs/adr/0028-dfa-absence-groups.md +28 -0
  21. data/docs/adr/0029-pattern-algebra.md +30 -0
  22. data/docs/adr/0030-classify-keywords-after-matching.md +24 -0
  23. data/docs/adr/0031-trivia-channels.md +24 -0
  24. data/docs/adr/0032-explicit-rule-priority.md +18 -0
  25. data/docs/migration-v2.md +4 -3
  26. data/docs/perf-log.md +258 -0
  27. data/docs/reference/compatibility.md +5 -0
  28. data/docs/reference/diagnostics.md +36 -7
  29. data/docs/reference/dsl.md +113 -8
  30. data/docs/reference/public-api.md +1 -0
  31. data/docs/reference/regexp.md +33 -1
  32. data/docs/reference/runtime.md +6 -2
  33. data/docs/reference/tokens-and-locations.md +33 -0
  34. data/lib/flexr/automaton/accel.rb +1 -0
  35. data/lib/flexr/automaton/analysis.rb +8 -5
  36. data/lib/flexr/automaton/compiler.rb +327 -54
  37. data/lib/flexr/automaton/dfa.rb +1 -1
  38. data/lib/flexr/automaton/dfa_operations.rb +63 -0
  39. data/lib/flexr/automaton/keyword_tables.rb +113 -0
  40. data/lib/flexr/automaton/nfa.rb +22 -1
  41. data/lib/flexr/cli.rb +64 -6
  42. data/lib/flexr/codegen/table.rb +44 -30
  43. data/lib/flexr/configuration.rb +14 -0
  44. data/lib/flexr/diagnostics.rb +1 -0
  45. data/lib/flexr/dsl.rb +28 -7
  46. data/lib/flexr/generated.rb +4 -1
  47. data/lib/flexr/generator.rb +62 -14
  48. data/lib/flexr/importer.rb +1 -1
  49. data/lib/flexr/ir.rb +9 -1
  50. data/lib/flexr/keywords.rb +65 -0
  51. data/lib/flexr/pattern.rb +76 -0
  52. data/lib/flexr/regexp/ast.rb +28 -2
  53. data/lib/flexr/regexp/normalizer.rb +35 -1
  54. data/lib/flexr/regexp/parser.rb +7 -4
  55. data/lib/flexr/regexp/tokenizer.rb +8 -16
  56. data/lib/flexr/runtime/channels.rb +70 -0
  57. data/lib/flexr/runtime/core.rb +12 -5
  58. data/lib/flexr/runtime/interpreter.rb +11 -7
  59. data/lib/flexr/runtime/token.rb +6 -0
  60. data/lib/flexr/runtime.rb +6 -3
  61. data/lib/flexr/source/prism_reader.rb +52 -10
  62. data/lib/flexr/source/static_eval.rb +19 -0
  63. data/lib/flexr/trace.rb +18 -12
  64. data/lib/flexr/version.rb +1 -1
  65. data/lib/ruby_lsp/flexr/addon.rb +30 -4
  66. data/sig/flexr.rbs +18 -4
  67. data/site/README.md +16 -0
  68. data/site/astro.config.mjs +8 -0
  69. data/site/package.json +3 -2
  70. data/site/ruby/playground.rb +9 -0
  71. data/site/ruby/presets/absence.flexr.rb +7 -0
  72. data/site/ruby/presets/keywords.flexr.rb +9 -0
  73. data/site/ruby/presets/pattern.flexr.rb +11 -0
  74. data/site/ruby/presets/priority.flexr.rb +7 -0
  75. data/site/ruby/presets/trivia.flexr.rb +8 -0
  76. data/site/scripts/prepare-docs.mjs +23 -0
  77. data/site/scripts/prepare-playground.mjs +26 -2
  78. data/site/scripts/stable-release.mjs +16 -0
  79. data/site/src/components/DocsTitle.astro +30 -0
  80. data/site/src/content/docs/benchmarks.md +11 -1
  81. data/site/src/docs-navigation.ts +14 -0
  82. data/site/src/pages/playground.astro +7 -0
  83. data/site/tests/browser/documentation-versions.spec.mjs +33 -0
  84. data/site/tests/browser/playground.spec.mjs +35 -0
  85. data/site/tests/playground-release.test.mjs +71 -0
  86. data/site/tests/playground-runtime.test.mjs +70 -0
  87. data/test/ruby_lsp_addon_spec.rb +71 -0
  88. data/tools/release_notes.rb +15 -0
  89. metadata +24 -1
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flexr
4
+ module Automaton
5
+ module KeywordTables
6
+ module_function
7
+
8
+ def diagnostics(compiled, spec)
9
+ spec.options.fetch(:keyword_tables, {}).flat_map do |among, entries|
10
+ targets = compiled.rules.select { |rule| rule.emit? && !rule.channel && rule.action[1] == among }
11
+ entries.filter_map do |spelling, (_, location)|
12
+ matched = compiled.machines.values.filter_map do |machine|
13
+ accepts = full_acceptances(machine.dfa, spelling)
14
+ candidates = targets.select do |rule|
15
+ accepts.any? { |acceptance| acceptance.rule_index == rule.index } &&
16
+ full_firstmatch?(rule, spelling, spec)
17
+ end
18
+ [accepts, candidates] unless candidates.empty?
19
+ end
20
+ if matched.empty?
21
+ Keywords.error!(
22
+ "no default-channel rule with emit: #{among.inspect} accepts the full keyword",
23
+ location: location, note: "input #{spelling.inspect}",
24
+ help: "add or widen a default-channel rule with emit: #{among.inspect} to match the entire spelling"
25
+ )
26
+ end
27
+ next unless matched.all? { |accepts, candidates| shadowed?(compiled, accepts, candidates) }
28
+
29
+ Diagnostics.warning(
30
+ "FLEXR-W022", "keyword #{spelling.inspect} never reaches emit: #{among.inspect}",
31
+ location: location, note: "a competing rule wins on input #{spelling.inspect}",
32
+ help: "remove the redundant keyword or change the competing rule"
33
+ )
34
+ end
35
+ end
36
+ end
37
+
38
+ def full_firstmatch?(rule, spelling, spec)
39
+ spec.backend != :firstmatch ||
40
+ Analysis.firstmatch_length(rule, spelling, encoding: spec.encoding, unicode: spec.options[:unicode] == true) == spelling.bytesize
41
+ end
42
+
43
+ def shadowed?(compiled, accepted, candidates)
44
+ return false if candidates.any?(&:trailing)
45
+
46
+ target = candidates.reduce { |winner, rule| winner.loses_priority_tie?(rule) ? rule : winner }
47
+ accepted.any? do |acceptance|
48
+ rule = compiled.rules.fetch(acceptance.rule_index)
49
+ !acceptance.bol_only && !acceptance.end_anchor && !rule.trailing && target.loses_priority_tie?(rule)
50
+ end
51
+ end
52
+
53
+ def grouping_suggestions(compiled, tables)
54
+ pending = []
55
+ compiled.rules.filter_map do |rule|
56
+ if literal_keyword?(rule)
57
+ pending << rule
58
+ next
59
+ end
60
+
61
+ literals = pending
62
+ pending = []
63
+ next unless literals.length >= 2 && groupable?(compiled, rule, literals, tables)
64
+
65
+ among = rule.action[1]
66
+ spellings = literals.map { |literal| literal.patterns.first }.uniq
67
+ Diagnostics.info(
68
+ "FLEXR-I003", "#{literals.length} consecutive literal rules can share an identifier rule",
69
+ location: literals.first.location,
70
+ help: "replace them with keywords #{spellings.inspect}, among: #{among.inspect}",
71
+ note: "input #{spellings.first.inspect} also matches rule #{rule.index}"
72
+ )
73
+ end
74
+ end
75
+
76
+ def literal_keyword?(rule)
77
+ spelling = rule.patterns.first
78
+ return false unless rule.emit? && !rule.channel && !rule.trailing && rule.patterns.one?
79
+ return false unless spelling.is_a?(String) && !spelling.empty?
80
+
81
+ normalized = Keywords.spelling(spelling)
82
+ normalized.valid_encoding? && rule.action[1] == normalized.upcase.to_sym
83
+ end
84
+
85
+ def groupable?(compiled, rule, literals, tables)
86
+ return false unless rule.emit? && !rule.channel && !rule.trailing && rule.patterns.all?(::Regexp)
87
+ return false unless literals.all? { |literal| literal.states == rule.states && literal.priority == rule.priority }
88
+ return false if tables&.key?(rule.action[1])
89
+ return false if tables && literals.any? { |literal| tables.key?(literal.action[1]) }
90
+ return false unless compiled.rules.one? { |entry| entry.emit? && !entry.channel && entry.action[1] == rule.action[1] }
91
+
92
+ literals.all? do |literal|
93
+ compiled.machines.values.all? do |machine|
94
+ next true unless machine.dfa.rule_ids.include?(literal.index)
95
+
96
+ full_acceptances(machine.dfa, literal.patterns.first).any? do |acceptance|
97
+ acceptance.rule_index == rule.index && !acceptance.bol_only && !acceptance.end_anchor
98
+ end
99
+ end
100
+ end
101
+ end
102
+
103
+ def full_acceptances(dfa, spelling)
104
+ state = dfa.start
105
+ spelling.each_byte do |byte|
106
+ state = dfa.transition(state, byte)
107
+ return [] unless state
108
+ end
109
+ dfa.accepts.fetch(state)
110
+ end
111
+ end
112
+ end
113
+ end
@@ -31,8 +31,9 @@ module Flexr
31
31
  end
32
32
 
33
33
  class NFABuilder
34
- def initialize
34
+ def initialize(&compile_difference)
35
35
  @nfa = NFA.new
36
+ @compile_difference = compile_difference
36
37
  end
37
38
 
38
39
  def build(patterns)
@@ -75,11 +76,31 @@ module Flexr
75
76
  repeat_fragment(node.child, 0, nil)
76
77
  when Regexp::AST::Repeat
77
78
  repeat_fragment(node.child, node.minimum, node.maximum)
79
+ when Regexp::AST::Difference
80
+ dfa_fragment(@compile_difference.call(node))
81
+ when Regexp::AST::EmbeddedDFA
82
+ dfa_fragment(node.dfa)
78
83
  else
79
84
  raise CompileError, "cannot build NFA from #{node.class}"
80
85
  end
81
86
  end
82
87
 
88
+ def dfa_fragment(dfa)
89
+ offset = @nfa.states.length
90
+ dfa.states.times { @nfa.new_state }
91
+ finish = @nfa.new_state
92
+ classes = dfa.ec.each_index.chunk { |byte| dfa.ec.fetch(byte) }.to_a
93
+ dfa.transitions.each_with_index do |row, state|
94
+ from = offset + state
95
+ classes.each do |class_id, bytes|
96
+ destination = row.fetch(class_id)
97
+ @nfa.transition(from, bytes.first, bytes.last, offset + destination) if destination
98
+ end
99
+ @nfa.epsilon(from, finish) unless dfa.accepts.fetch(state).empty?
100
+ end
101
+ [offset + dfa.start, finish]
102
+ end
103
+
83
104
  def repeat_fragment(child, minimum, maximum)
84
105
  return fragment(Regexp::AST::Empty.new(loc: nil)) if maximum&.zero?
85
106
  return star_fragment(child) if minimum.zero? && maximum.nil?
data/lib/flexr/cli.rb CHANGED
@@ -197,6 +197,11 @@ module Flexr
197
197
  options.warn_level == :all ||
198
198
  (options.warn_level == :default && diagnostic.severity != :info && diagnostic.code != "FLEXR-W016")
199
199
  end
200
+ diagnostics.concat(emit_shorthand_suggestions(parsed)) if parsed && options.warn_level == :all
201
+ if parsed && options.overrides.fetch(:backend, parsed.config[:backend]) != :firstmatch && options.warn_level != :none
202
+ tables = parsed.config.dig(:options, :keyword_tables)
203
+ diagnostics.concat(Automaton::KeywordTables.grouping_suggestions(compiled, tables))
204
+ end
200
205
  diagnostics.concat(Migration.diagnostics(parsed)) if options.target
201
206
  set = DiagnosticSet.new
202
207
  diagnostics.each { |diagnostic| set << diagnostic }
@@ -211,6 +216,18 @@ module Flexr
211
216
  EXIT_OK
212
217
  end
213
218
 
219
+ def emit_shorthand_suggestions(parsed)
220
+ parsed.rules.filter_map do |rule|
221
+ token = rule.emit_shorthand
222
+ next unless token
223
+
224
+ Diagnostics.info(
225
+ "FLEXR-I004", "rule emits #{token.inspect} with unchanged matched text",
226
+ location: rule.span, help: "use emit: #{token.inspect} on the rule"
227
+ )
228
+ end
229
+ end
230
+
214
231
  def print_stats(spec, options, out)
215
232
  compiled = compile(read_spec(spec), overrides: options.overrides)
216
233
  stats = compiled.stats.transform_keys(&:to_s).transform_values do |stat|
@@ -228,8 +245,11 @@ module Flexr
228
245
  end
229
246
 
230
247
  def print_dot(spec, options, out)
231
- compiled = compile(read_spec(spec), overrides: options.overrides)
248
+ parsed = read_spec(spec)
249
+ compiled = compile(parsed, overrides: options.overrides)
232
250
  out.puts "digraph flexr {"
251
+ labels = keyword_table_labels(parsed.config)
252
+ out.puts " graph [label=#{dot_quote(labels.join("\n"))}];" unless labels.empty?
233
253
  compiled.machines.each do |state_name, machine|
234
254
  dfa = machine.dfa
235
255
  accelerated_states = Automaton::Accel.extract(dfa).to_h { |region| [region.state, true] }
@@ -237,7 +257,12 @@ module Flexr
237
257
  node_name = "#{state_name}_#{state}"
238
258
  node = dot_quote(node_name)
239
259
  accepting = !dfa.accepts[state].empty?
240
- label = dfa.accepts[state].map(&:rule_index).uniq.join(",")
260
+ label = dfa.accepts[state].map do |acceptance|
261
+ rule = compiled.rules.fetch(acceptance.rule_index)
262
+ pattern = rule.patterns.fetch(acceptance.pattern_index)
263
+ description = pattern.is_a?(Pattern) ? "#{rule.index} #{pattern.inspect}" : rule.index
264
+ "#{description}#{channel_label(rule)}#{priority_label(rule)}"
265
+ end.uniq.join(",")
241
266
  label = "#{node_name}\naccept=#{label}" unless label.empty?
242
267
  attributes = dot_node_attributes(label, accepting: accepting, accelerated: accelerated_states[state])
243
268
  out.puts " #{node} [#{attributes}];"
@@ -278,7 +303,9 @@ module Flexr
278
303
  end
279
304
 
280
305
  def print_trace(spec, options, out)
281
- compiled = compile(read_spec(spec), overrides: options.overrides)
306
+ parsed = read_spec(spec)
307
+ compiled = compile(parsed, overrides: options.overrides)
308
+ out.puts keyword_table_labels(parsed.config)
282
309
  compiled.machines.each do |state_name, machine|
283
310
  dfa = machine.dfa
284
311
  out.puts "state #{state_name} start=#{dfa.start} classes=#{dfa.class_count}"
@@ -289,21 +316,49 @@ module Flexr
289
316
  transitions = dfa.transitions[state].each_with_index.filter_map do |destination, class_id|
290
317
  destination && [class_id, destination]
291
318
  end
292
- out.puts " #{state}: accepts=#{accepts.inspect} transitions=#{transitions.inspect}"
319
+ channels = dfa.accepts[state].map(&:rule_index).uniq.filter_map do |index|
320
+ channel = channel_label(compiled.rules.fetch(index))
321
+ "#{index}#{channel}" if channel
322
+ end
323
+ labels = " channels=[#{channels.join(', ')}]" unless channels.empty?
324
+ out.puts " #{state}: accepts=#{accepts.inspect} transitions=#{transitions.inspect}#{labels}"
293
325
  end
294
326
  end
295
327
  EXIT_OK
296
328
  end
297
329
 
298
330
  def print_explanation(spec, rule_number, out)
299
- rules = read_spec(spec).rules
331
+ parsed = read_spec(spec)
332
+ rules = parsed.rules
300
333
  rules = rules.select { |rule| rule.index == rule_number } if rule_number
301
334
  raise ArgumentError, "rule not found: #{rule_number}" if rules.empty? && rule_number
302
335
 
303
- out.puts(rules.map { |rule| "rule #{rule.index}: #{rule.patterns.inspect}" })
336
+ out.puts(rules.map { |rule| "rule #{rule.index}#{channel_label(rule)}#{priority_label(rule)}: #{rule.patterns.inspect}" })
337
+ emitted = rules.filter_map do |rule|
338
+ rule.action[1] if !rule.channel && rule.action.is_a?(Array) && rule.action.first == :emit
339
+ end
340
+ out.puts keyword_table_labels(parsed.config, among: emitted)
304
341
  EXIT_OK
305
342
  end
306
343
 
344
+ def channel_label(rule)
345
+ " channel=#{rule.channel.inspect}" if rule.channel
346
+ end
347
+
348
+ def priority_label(rule)
349
+ priority = rule.priority.to_i
350
+ priority.zero? ? "" : " (priority #{priority})"
351
+ end
352
+
353
+ def keyword_table_labels(config, among: nil)
354
+ config.fetch(:options, {}).fetch(:keyword_tables, {}).filter_map do |type, table|
355
+ next if among && !among.include?(type)
356
+
357
+ entries = table.map { |word, (token, _)| "#{word.inspect} => #{token.inspect}" }
358
+ "keywords among #{type.inspect} (#{entries.join(', ')})"
359
+ end
360
+ end
361
+
307
362
  def print_input_trace(spec, options, trace_args, out)
308
363
  require_relative "trace"
309
364
  parsed = read_spec(spec)
@@ -356,6 +411,9 @@ module Flexr
356
411
  klass.encoding(config.fetch(:encoding, Encoding::UTF_8))
357
412
  Array(config[:declared_tokens]).each { |token| klass.emits(token) }
358
413
  config_options = config.fetch(:options, {}).merge(overrides.slice(:experimental, :allow_empty_match))
414
+ if (tables = config_options[:keyword_tables])
415
+ klass.__flexr_config.options[:keyword_tables] = tables
416
+ end
359
417
  config_options.slice(*Configuration::BOOLEAN_OPTIONS).each do |name, value|
360
418
  klass.option(name) if value
361
419
  end
@@ -25,20 +25,22 @@ module Flexr
25
25
  ].join("\n")
26
26
  end
27
27
 
28
- def source(indent: " ")
28
+ def source(indent: " ", direct: false)
29
29
  lines = []
30
30
  whole_tokens = compiled.machines.values.any?(&:whole_tokens)
31
+ scan_cache = direct ? "@__flexr_generated_scan_layout" : "@__flexr_generated_scan_fast"
32
+ fast_path = direct ? "__flexr_generated_direct_layout" : "__flexr_generated_fast_path?"
31
33
  lines << "#{indent}def scan_one"
32
34
  lines << "#{indent} if @__flexr_generated_scan_state != @state"
33
35
  lines << "#{indent} machine = self.class.__flexr_compiled.machines.fetch(@state)"
34
36
  lines << "#{indent} @__flexr_generated_scan_state = @state"
35
37
  lines << "#{indent} @__flexr_generated_scan_dfa = machine.dfa"
36
38
  lines << "#{indent} @__flexr_generated_whole_tokens = machine.respond_to?(:whole_tokens) ? machine.whole_tokens : nil" if whole_tokens
37
- lines << "#{indent} @__flexr_generated_scan_fast = __flexr_generated_fast_path?(@__flexr_generated_scan_dfa)"
39
+ lines << "#{indent} #{scan_cache} = #{fast_path}(@__flexr_generated_scan_dfa)"
38
40
  lines << "#{indent} @__flexr_generated_scan_simple = __flexr_generated_simple_fast_path?(@__flexr_generated_scan_dfa)"
39
41
  lines << "#{indent} end"
40
42
  lines << "#{indent} dfa = @__flexr_generated_scan_dfa"
41
- lines << "#{indent} return Flexr::Runtime::Interpreter.new(self).scan unless @__flexr_generated_scan_fast"
43
+ lines << "#{indent} return Flexr::Runtime::Interpreter.new(self).scan unless #{scan_cache}"
42
44
  lines << "#{indent} position = byte_pos"
43
45
  lines << "#{indent} return nil unless valid_utf8_at?(position)"
44
46
  if whole_tokens
@@ -94,33 +96,31 @@ module Flexr
94
96
  lines << "#{indent} best"
95
97
  lines << "#{indent}end"
96
98
  lines << "#{indent}def __flexr_generated_scan_simple(dfa, position)"
97
- lines << "#{indent} current = dfa.start"
98
- lines << "#{indent} direct = dfa.direct"
99
- lines << "#{indent} direct_nxt = direct&.fetch(:nxt)"
100
- lines << "#{indent} direct_classes = direct&.fetch(:classes)"
101
- lines << "#{indent} ec = dfa.ec"
102
- lines << "#{indent} accepts = dfa.accepts"
103
- lines << "#{indent} rules = self.class.__flexr_rules"
99
+ if direct
100
+ lines << "#{indent} current, direct_nxt, direct_classes, ec, accepts, rules = #{scan_cache}"
101
+ else
102
+ lines << "#{indent} current = dfa.start"
103
+ lines << "#{indent} direct = dfa.direct"
104
+ lines << "#{indent} direct_nxt = direct&.fetch(:nxt)"
105
+ lines << "#{indent} direct_classes = direct&.fetch(:classes)"
106
+ lines << "#{indent} ec = dfa.ec"
107
+ lines << "#{indent} accepts = dfa.accepts"
108
+ lines << "#{indent} rules = self.class.__flexr_rules"
109
+ end
104
110
  lines << "#{indent} source = buffer.stable_source"
105
111
  lines << "#{indent} guarded_steps = scan_steps_guarded?"
106
- lines << "#{indent} token_start = more_text_start || position"
107
- lines << "#{indent} token_limit = max_token_size"
108
112
  lines << "#{indent} check_token_limit = token_limit_required?"
109
113
  lines << "#{indent} cursor = position"
110
114
  lines << "#{indent} best = nil"
111
- lines << "#{indent} accel_mode = @accel_mode"
112
- lines << "#{indent} accelerate = accel_mode != :none && !(accel_mode == :auto && @__flexr_generated_auto_accel_off)"
113
- lines << "#{indent} if source && !guarded_steps && !check_token_limit && !accelerate"
114
- lines << "#{indent} while cursor < source.bytesize"
115
- lines << "#{indent} byte = source.getbyte(cursor)"
116
- lines << "#{indent} current = if direct_nxt"
117
- lines << "#{indent} class_id = ec[byte]"
118
- lines << "#{indent} value = direct_nxt[(current * direct_classes) + class_id]"
119
- lines << "#{indent} value >= 0 ? value : nil"
120
- lines << "#{indent} else"
121
- lines << "#{indent} dfa.transition(current, byte)"
122
- lines << "#{indent} end"
123
- lines << "#{indent} break unless current"
115
+ lines << "#{indent} if source && !guarded_steps && !check_token_limit && (@accel_mode == :auto || @accel_mode == :none)"
116
+ lines << "#{indent} while (byte = source.getbyte(cursor))"
117
+ if direct
118
+ lines << "#{indent} current = direct_nxt[(current * direct_classes) + ec[byte]]"
119
+ lines << "#{indent} break if current < 0"
120
+ else
121
+ lines << "#{indent} current = dfa.transition(current, byte)"
122
+ lines << "#{indent} break unless current"
123
+ end
124
124
  lines << "#{indent} cursor += 1"
125
125
  lines << "#{indent} acceptance = accepts[current].first"
126
126
  lines << "#{indent} next unless acceptance"
@@ -133,6 +133,9 @@ module Flexr
133
133
  lines << "#{indent} end"
134
134
  lines << "#{indent} return best"
135
135
  lines << "#{indent} end"
136
+ lines << "#{indent} token_start = more_text_start || position"
137
+ lines << "#{indent} token_limit = max_token_size"
138
+ lines << "#{indent} accelerate = @accel_mode != :none && !(@accel_mode == :auto && @__flexr_generated_auto_accel_off)"
136
139
  lines << "#{indent} while cursor < (source ? source.bytesize : buffer.bytesize) || buffer.ensure_available?(cursor + 1)"
137
140
  lines << "#{indent} if accelerate"
138
141
  lines << "#{indent} region = __flexr_generated_acceleration_region(dfa, current)"
@@ -231,12 +234,22 @@ module Flexr
231
234
  lines << "#{indent} @__flexr_generated_disabled_auto_accel ||= {}"
232
235
  lines << "#{indent} @__flexr_generated_disabled_auto_accel[region] = true"
233
236
  lines << "#{indent}end"
234
- lines << "#{indent}def __flexr_generated_fast_path?(dfa)"
237
+ lines << "#{indent}def #{fast_path}(dfa)"
235
238
  lines << "#{indent} @__flexr_generated_fast_paths ||= {}"
236
239
  lines << "#{indent} return @__flexr_generated_fast_paths[dfa] if @__flexr_generated_fast_paths.key?(dfa)"
237
- lines << "#{indent} rules = dfa.rule_ids.map { |rule_index| self.class.__flexr_rules.fetch(rule_index) }"
238
- lines << "#{indent} @__flexr_generated_fast_paths[dfa] = self.class.__flexr_config.backend != :firstmatch &&"
239
- lines << "#{indent} self.class.__flexr_config.options[:allow_empty_match] != true && rules.none?(&:trailing)"
240
+ if direct
241
+ lines << "#{indent} rules = self.class.__flexr_rules"
242
+ lines << "#{indent} active_rules = dfa.rule_ids.map { |rule_index| rules.fetch(rule_index) }"
243
+ lines << "#{indent} @__flexr_generated_fast_paths[dfa] = if self.class.__flexr_config.backend != :firstmatch &&"
244
+ lines << "#{indent} self.class.__flexr_config.options[:allow_empty_match] != true && active_rules.none?(&:trailing)"
245
+ lines << "#{indent} direct = dfa.direct"
246
+ lines << "#{indent} [dfa.start, direct.fetch(:nxt), direct.fetch(:classes), dfa.ec, dfa.accepts, rules].freeze"
247
+ lines << "#{indent} end"
248
+ else
249
+ lines << "#{indent} rules = dfa.rule_ids.map { |rule_index| self.class.__flexr_rules.fetch(rule_index) }"
250
+ lines << "#{indent} @__flexr_generated_fast_paths[dfa] = self.class.__flexr_config.backend != :firstmatch &&"
251
+ lines << "#{indent} self.class.__flexr_config.options[:allow_empty_match] != true && rules.none?(&:trailing)"
252
+ end
240
253
  lines << "#{indent}end"
241
254
  lines << "#{indent}def __flexr_generated_simple_fast_path?(dfa)"
242
255
  lines << "#{indent} @__flexr_generated_simple_fast_paths ||= {}"
@@ -253,7 +266,8 @@ module Flexr
253
266
  lines << "#{indent} rule = self.class.__flexr_rules.fetch(acceptance.rule_index)"
254
267
  lines << "#{indent} next if best && cursor < best.total_end_pos"
255
268
  lines << "#{indent} next if best && cursor == best.total_end_pos &&"
256
- lines << "#{indent} rule.index > best.rule.index"
269
+ priority_check = compiled.rules.any? { |rule| !rule.priority.zero? }
270
+ lines << "#{indent} #{priority_check ? 'rule.loses_priority_tie?(best.rule)' : 'rule.index > best.rule.index'}"
257
271
  lines << "#{indent} best ||= (@__flexr_generated_match ||= Flexr::Runtime::Match.new)"
258
272
  lines << "#{indent} best.rule = rule"
259
273
  lines << "#{indent} best.start_pos = start_position"
@@ -33,6 +33,20 @@ module Flexr
33
33
  validated_symbol!(value, BOOLEAN_OPTIONS, :option)
34
34
  end
35
35
 
36
+ def rule_priority!(value)
37
+ return value if value.is_a?(Integer)
38
+
39
+ diagnostic = Diagnostics.error("FLEXR-E018", "rule priority must be an Integer")
40
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
41
+ end
42
+
43
+ def rule_channel!(value)
44
+ return value if value.is_a?(Symbol) && value != :all
45
+
46
+ diagnostic = Diagnostics.error("FLEXR-E018", "rule channel must be a Symbol other than :all")
47
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
48
+ end
49
+
36
50
  def validated_symbol!(value, allowed, name)
37
51
  symbol = value.to_sym
38
52
  return symbol if allowed.include?(symbol)
@@ -107,6 +107,7 @@ module Flexr
107
107
 
108
108
  pattern = rule.patterns.one? ? rule.patterns.first : rule.patterns
109
109
  label = "rule #{pattern.inspect}"
110
+ label += ", channel: #{rule.channel.inspect}" if rule.channel
110
111
  rule.trailing ? "#{label}, followed_by: #{rule.trailing.inspect}" : label
111
112
  end
112
113
 
data/lib/flexr/dsl.rb CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Flexr
4
4
  module DSL
5
- DSL_METHODS = %i[rule state all_states on_eof emits backend token_kind encoding option accel].freeze
5
+ DSL_METHODS = %i[rule pattern upto state all_states on_eof emits keywords backend token_kind encoding option accel].freeze
6
6
  def inherited(child)
7
7
  super
8
8
  child.__flexr_reset!
@@ -25,21 +25,29 @@ module Flexr
25
25
  @__flexr_compile_mutex = Monitor.new
26
26
  end
27
27
 
28
- def rule(pattern, skip: false, emit: nil, followed_by: nil, &action)
28
+ def rule(pattern, skip: false, emit: nil, followed_by: nil, channel: :default, priority: 0, &action)
29
29
  __flexr_mutate! do
30
30
  patterns = normalize_patterns(pattern)
31
+ channel = Configuration.rule_channel!(channel)
32
+ skip ||= channel == :skip
33
+ channel = nil if skip || channel == :default
31
34
  rule_action = ActionResolver.resolve(
32
- skip: skip, emit: emit, block: action, default: proc { emit(nil, text) }
35
+ skip: skip, emit: emit, block: action, default: channel ? [:emit, channel] : proc { emit(nil, text) }
33
36
  )
34
37
  states = @__flexr_state_stack.empty? ? [:initial] : @__flexr_state_stack.dup
35
38
  @__flexr_rules << IR::Rule.new(
36
39
  index: @__flexr_rules.length, patterns: patterns, trailing: normalize_trailing(followed_by),
37
- action: rule_action, states: states, bol_only: false, end_anchor: nil
40
+ action: rule_action, states: states, bol_only: false, end_anchor: nil, channel: channel,
41
+ priority: Configuration.rule_priority!(priority)
38
42
  )
43
+ include Runtime::Channels if channel
39
44
  end
40
45
  nil
41
46
  end
42
47
 
48
+ def pattern(*values) = Pattern.build(*values)
49
+ def upto(value) = Pattern.upto(value)
50
+
43
51
  def state(*names, inclusive: false, &block)
44
52
  raise ArgumentError, "state requires a block" unless block
45
53
  raise ArgumentError, "state requires a name" if names.empty?
@@ -118,6 +126,7 @@ module Flexr
118
126
  # The ivar is part of the generated/runtime class contract.
119
127
  @__flexr_compiled ||= begin
120
128
  compiled = Automaton::Compiler.new(__flexr_spec).compile
129
+ include Keywords::Emission if @__flexr_config.options[:keyword_tables]
121
130
  @__flexr_config.backend = auto_direct?(compiled) ? :direct : :table if @__flexr_config.backend == :auto
122
131
  freeze_specification!
123
132
  freeze_compiled!(compiled)
@@ -204,6 +213,16 @@ module Flexr
204
213
  @__flexr_eof_rules.freeze
205
214
  @__flexr_rules.freeze
206
215
  @__flexr_states.freeze
216
+ if (tables = @__flexr_config.options[:keyword_tables])
217
+ tables.each_value do |table|
218
+ table.each_value do |entry|
219
+ entry.last&.freeze
220
+ entry.freeze
221
+ end
222
+ table.freeze
223
+ end
224
+ tables.freeze
225
+ end
207
226
  @__flexr_config.options.freeze
208
227
  @__flexr_config.declared_tokens.freeze
209
228
  @__flexr_config.freeze
@@ -224,8 +243,8 @@ module Flexr
224
243
  def normalize_patterns(pattern)
225
244
  values = pattern.is_a?(Array) ? pattern : [pattern]
226
245
  values.each do |value|
227
- unless value.is_a?(::Regexp) || value.is_a?(String)
228
- diagnostic = Diagnostics.error("FLEXR-E018", "rule pattern must be a Regexp, String, or Array")
246
+ unless value.is_a?(::Regexp) || value.is_a?(String) || (defined?(Pattern) && value.is_a?(Pattern))
247
+ diagnostic = Diagnostics.error("FLEXR-E018", "rule pattern must be a Regexp, String, Pattern, or Array")
229
248
  raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
230
249
  end
231
250
  end
@@ -239,7 +258,9 @@ module Flexr
239
258
  when String
240
259
  ::Regexp.new(::Regexp.escape(value))
241
260
  else
242
- diagnostic = Diagnostics.error("FLEXR-E018", "followed_by must be a Regexp or String")
261
+ return value if defined?(Pattern) && value.is_a?(Pattern)
262
+
263
+ diagnostic = Diagnostics.error("FLEXR-E018", "followed_by must be a Regexp, String, or Pattern")
243
264
  raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
244
265
  end
245
266
  end
@@ -176,12 +176,14 @@ module Flexr
176
176
  def __flexr_add_generated_rule(definition)
177
177
  __flexr_mutate! do
178
178
  action = definition.fetch(:action)
179
+ channel = definition[:channel]
179
180
  @__flexr_rules << IR::Rule.new(
180
181
  index: definition.fetch(:index), patterns: Array(definition.fetch(:patterns)),
181
182
  trailing: normalize_trailing(definition[:trailing]), action: action,
182
183
  states: Array(definition.fetch(:states)).map(&:to_sym),
183
184
  bol_only: definition.fetch(:bol_only, false), end_anchor: definition[:end_anchor],
184
- location: definition[:span] || definition[:location],
185
+ location: definition[:span] || definition[:location], channel: channel,
186
+ priority: definition[:priority],
185
187
  trailing_dfa: definition[:trailing_dfa] && Generated.load_dfa(definition[:trailing_dfa]),
186
188
  pattern_conditions: Array(definition[:pattern_conditions]).map do |condition|
187
189
  next unless condition
@@ -190,6 +192,7 @@ module Flexr
190
192
  bol_only: condition[2], end_anchor: condition[3])
191
193
  end
192
194
  )
195
+ include Runtime::Channels if channel
193
196
  end
194
197
  rescue CompileError => e
195
198
  e.diagnostic.location ||= definition[:span] || definition[:location] if e.diagnostic