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
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "dfa_operations"
4
+ require_relative "keyword_tables"
5
+
3
6
  module Flexr
4
7
  module Automaton
5
8
  class Compiler
@@ -9,6 +12,17 @@ module Flexr
9
12
 
10
13
  def compile
11
14
  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
15
+ @regexp_asts = {}
16
+ @differences = {}
17
+ @empty_absence_rules = {}
18
+ @priorities = @spec.rules.to_h { |rule| [rule.index, rule.priority] }
19
+ @pattern_dfas = {}
20
+ @pattern_stats = {}
21
+ @pattern_diagnostics = []
22
+ @pattern_universe = nil
23
+ @pattern_universe_dfa = nil
24
+ @state_limit = @spec.options.fetch(:max_dfa_states, 100_000)
25
+ @state_limit = 100_000 unless @state_limit.is_a?(Integer) && @state_limit.positive?
12
26
  validate_rules
13
27
  state_names = effective_states
14
28
  machines = state_names.to_h do |state_name|
@@ -21,9 +35,16 @@ module Flexr
21
35
  e.diagnostic.location ||= @spec.states.fetch(state_name).location if e.diagnostic
22
36
  raise
23
37
  end
24
- stats = machines.transform_values { |machine| machine.dfa.stats }
38
+ stats = machines.to_h do |name, machine|
39
+ stat = machine.dfa.stats
40
+ operations = rules_for(name).flat_map { |rule| @pattern_stats.fetch(rule.index, []) } unless @pattern_stats.empty?
41
+ stat[:pattern_operations] = operations.freeze if operations&.any?
42
+ [name, stat]
43
+ end
25
44
  compiled = CompiledSpec.new(machines: machines, rules: @spec.rules, states: state_names, stats: stats)
26
- compiled.diagnostics = diagnostics_for(compiled, Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at)
45
+ compiled.diagnostics = diagnostics_for(compiled, Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at) +
46
+ @pattern_diagnostics
47
+ compiled.diagnostics.concat(KeywordTables.diagnostics(compiled, @spec)) if @spec.options.key?(:keyword_tables)
27
48
  compiled
28
49
  end
29
50
 
@@ -51,28 +72,169 @@ module Flexr
51
72
  normalized = []
52
73
  rules.each do |rule|
53
74
  rule.pattern_conditions = []
75
+ first_pattern = normalized.length
76
+ contains_absence = false
54
77
  rule.patterns.each_with_index do |pattern, pattern_index|
55
- regexp = pattern.is_a?(::Regexp) ? pattern : ::Regexp.new(::Regexp.escape(pattern.to_s))
56
- encoding = regexp.encoding == Encoding::BINARY ? Encoding::BINARY : @spec.encoding
57
- parser = Regexp::Parser.new(regexp.source, options: regexp.options, encoding: encoding,
58
- unicode: @spec.options[:unicode] == true)
59
- ast = parser.parse
60
- ast, bol_only, end_anchor = strip_anchors(ast)
78
+ if pattern.is_a?(Pattern)
79
+ body = Regexp::AST::EmbeddedDFA.new(@pattern_dfas.fetch([rule.index, pattern_index]))
80
+ bol_only = end_anchor = false
81
+ else
82
+ regexp = pattern_regexp(pattern)
83
+ ast = parse_regexp(regexp)
84
+ contains_absence ||= Regexp::AST.absence?(ast)
85
+ ast, bol_only, end_anchor = strip_anchors(ast)
86
+ body = normalize_regexp(regexp, ast)
87
+ end
61
88
  condition = Acceptance.new(rule_index: rule.index, pattern_index: pattern_index,
62
89
  bol_only: bol_only, end_anchor: end_anchor)
63
90
  rule.pattern_conditions[pattern_index] = condition
64
- normalized_ast = Regexp::Normalizer.new(ast, encoding: encoding, options: regexp.options).normalize
65
- normalized << [normalized_ast, condition]
91
+ normalized << [body, condition]
66
92
  end
93
+ @empty_absence_rules[rule.index] = true if
94
+ contains_absence && normalized[first_pattern..].all? { |ast, _| ast.is_a?(Regexp::AST::Fail) }
67
95
  rescue CompileError => e
68
96
  e.diagnostic.location ||= rule.location if e.diagnostic
69
97
  raise
70
98
  end
71
99
  return empty_dfa if normalized.empty?
72
100
 
73
- nfa = NFABuilder.new.build(normalized)
101
+ determinize(normalized)
102
+ end
103
+
104
+ def determinize(patterns, operation: nil)
105
+ nfa = NFABuilder.new(&method(:compile_difference)).build(patterns)
74
106
  ec, class_count = nfa.byte_classes.build
75
- subset_construction(nfa, ec, class_count)
107
+ subset_construction(nfa, ec, class_count, operation: operation)
108
+ end
109
+
110
+ def compile_difference(node)
111
+ @differences[node] ||= begin
112
+ accept = Acceptance.new(rule_index: 0, pattern_index: 0)
113
+ left = determinize([[node.left, accept]], operation: "absence group")
114
+ right = determinize([[node.right, accept]], operation: "absence group")
115
+ difference = DFAOperations.difference(left, right) { |state| enforce_state_limit!(state, "absence group") }
116
+ Minimizer.minimize(difference)
117
+ end
118
+ end
119
+
120
+ def compile_pattern_value(pattern, rule)
121
+ @active_rules = [rule]
122
+ value_dfa(normalized_value(pattern, rule), "pattern #{pattern.inspect}")
123
+ end
124
+
125
+ def normalized_value(pattern, rule)
126
+ case pattern.operation
127
+ when :literal
128
+ regexp = pattern_regexp(pattern.operands.first)
129
+ ast = parse_regexp(regexp)
130
+ if contains_anchor?(ast)
131
+ diagnostic = Diagnostics.error("FLEXR-E009", "anchors are not allowed inside pattern values",
132
+ help: "use an anchored regexp directly as a rule pattern")
133
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
134
+ end
135
+ normalize_regexp(regexp, ast)
136
+ when :|, :+
137
+ children = pattern.operands.map { |operand| normalized_value(operand, rule) }
138
+ klass = pattern.operation == :| ? Regexp::AST::Alt : Regexp::AST::Seq
139
+ klass.new(children: children, loc: nil)
140
+ else
141
+ Regexp::AST::EmbeddedDFA.new(compile_pattern_operation(pattern, rule))
142
+ end
143
+ end
144
+
145
+ def compile_pattern_operation(pattern, rule)
146
+ expression = pattern.inspect
147
+ operands = pattern.operands.map { |operand| normalized_value(operand, rule) }
148
+ case pattern.operation
149
+ when :&, :-
150
+ operation = pattern.operation == :& ? :intersection : :difference
151
+ left, right = operands.map { |operand| value_dfa(operand, expression) }
152
+ when :!
153
+ operation = :complement
154
+ left = pattern_universe_dfa(expression)
155
+ right = value_dfa(operands.first, expression)
156
+ when :upto
157
+ operation = :upto
158
+ left = pattern_universe_dfa(expression)
159
+ ending = Regexp::AST::Seq.new(children: [pattern_universe, operands.first], loc: nil)
160
+ right = value_dfa(ending, expression)
161
+ end
162
+ product, overlap = DFAOperations.product(left, right, intersection: %i[intersection upto].include?(operation)) do |state|
163
+ enforce_state_limit!(state, expression)
164
+ end
165
+ result = Minimizer.minimize(operation == :upto ? DFAOperations.first_ending(product) : product)
166
+ record_pattern_operation(rule, operation, expression, left, right, product, result, overlap)
167
+ result
168
+ end
169
+
170
+ def pattern_universe
171
+ @pattern_universe ||= Regexp::Normalizer.new(nil, encoding: @spec.encoding).universe
172
+ end
173
+
174
+ def pattern_universe_dfa(expression)
175
+ @pattern_universe_dfa ||= value_dfa(pattern_universe, expression)
176
+ end
177
+
178
+ def value_dfa(node, expression)
179
+ return node.dfa if node.is_a?(Regexp::AST::EmbeddedDFA)
180
+
181
+ accept = Acceptance.new(rule_index: 0, pattern_index: 0)
182
+ determinize([[node, accept]], operation: expression)
183
+ end
184
+
185
+ def record_pattern_operation(rule, operation, expression, left, right, product, result, overlap)
186
+ if %i[intersection difference upto].include?(operation) && result.rule_ids.empty?
187
+ message = if operation == :difference
188
+ "pattern difference #{expression} is empty because the right operand covers the left operand"
189
+ else
190
+ "pattern #{operation} #{expression} is empty"
191
+ end
192
+ label = operation == :upto ? "subject alphabet" : "left operand"
193
+ note = language_example(left, label)
194
+ note = [note, language_example(right, "right operand")].compact.join(". ") if operation == :intersection
195
+ diagnostic = Diagnostics.error("FLEXR-E029", message, location: rule.location, note: note)
196
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
197
+ end
198
+ if operation == :difference && !overlap
199
+ @pattern_diagnostics << Diagnostics.warning(
200
+ "FLEXR-W021", "pattern subtraction #{expression} removes no input",
201
+ location: rule.location, note: language_example(right, "right operand")
202
+ )
203
+ end
204
+
205
+ sizes = [left.states, right.states].freeze
206
+ (@pattern_stats[rule.index] ||= []) << {
207
+ operation: operation, expression: expression.freeze, operand_states: sizes,
208
+ product_states: product.states, result_states: result.states
209
+ }.freeze
210
+ return unless product.states >= 16 && product.states > sizes.max * 2
211
+
212
+ @pattern_diagnostics << Diagnostics.warning(
213
+ "FLEXR-W011", "pattern #{operation} #{expression} expands the DFA",
214
+ location: rule.location,
215
+ note: "operands have #{sizes.join(' and ')} states. The product visits #{product.states} states and minimizes to #{result.states}"
216
+ )
217
+ end
218
+
219
+ def language_example(dfa, label)
220
+ sample = Analysis.shortest_input(dfa)
221
+ return "#{label} accepts no input" unless sample
222
+
223
+ "#{label} accepts #{sample.force_encoding(@spec.encoding).inspect}"
224
+ end
225
+
226
+ def pattern_regexp(pattern)
227
+ pattern.is_a?(::Regexp) ? pattern : ::Regexp.new(::Regexp.escape(pattern.to_s))
228
+ end
229
+
230
+ def enforce_state_limit!(state, operation)
231
+ return if state < @state_limit
232
+
233
+ labels = @active_rules.map { |rule| Diagnostics.rule_label(rule) }.join(", ")
234
+ subject = operation ? "#{operation} in #{labels}" : labels
235
+ diagnostic = Diagnostics.error("FLEXR-E006", "DFA state limit exceeded while compiling #{subject}",
236
+ help: "raise max_dfa_states or split the listed rules")
237
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
76
238
  end
77
239
 
78
240
  def empty_dfa
@@ -106,13 +268,14 @@ module Flexr
106
268
 
107
269
  def contains_anchor?(node)
108
270
  return true if node.is_a?(Regexp::AST::Anchor)
109
- return contains_anchor?(node.child) if node.is_a?(Regexp::AST::Repeat) || node.is_a?(Regexp::AST::Star)
271
+ return contains_anchor?(node.child) if
272
+ node.is_a?(Regexp::AST::Repeat) || node.is_a?(Regexp::AST::Star) || node.is_a?(Regexp::AST::Absence)
110
273
  return false unless node.respond_to?(:children)
111
274
 
112
275
  node.children.any? { |child| contains_anchor?(child) }
113
276
  end
114
277
 
115
- def subset_construction(nfa, ec, class_count)
278
+ def subset_construction(nfa, ec, class_count, operation:)
116
279
  closures = {}
117
280
  closure_for = lambda do |state|
118
281
  closures[state] ||= epsilon_closure_for(nfa, state)
@@ -125,9 +288,6 @@ module Flexr
125
288
  accepts = []
126
289
  queue = [start_set]
127
290
  queue_index = 0
128
- limit = @spec.options.fetch(:max_dfa_states, 100_000)
129
- limit = 100_000 unless limit.is_a?(Integer) && limit.positive?
130
-
131
291
  while queue_index < queue.length
132
292
  set = queue.fetch(queue_index)
133
293
  queue_index += 1
@@ -138,12 +298,7 @@ module Flexr
138
298
  destination = ids[closure]
139
299
  unless destination
140
300
  destination = sets.length
141
- if destination >= limit
142
- message = "DFA state limit exceeded while compiling #{@active_rules.map { |rule| Diagnostics.rule_label(rule) }.join(', ')}"
143
- diagnostic = Diagnostics.error("FLEXR-E006", message,
144
- help: "raise max_dfa_states or split the listed rules")
145
- raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
146
- end
301
+ enforce_state_limit!(destination, operation) if destination >= @state_limit
147
302
  ids[closure] = destination
148
303
  sets << closure
149
304
  queue << closure
@@ -199,7 +354,9 @@ module Flexr
199
354
  rules = each_state_id(set).with_object([]) do |state, result|
200
355
  result.concat(nfa.states[state].accepts)
201
356
  end
202
- rules.uniq.sort_by { |acceptance| [acceptance.rule_index, acceptance.pattern_index] }
357
+ rules.uniq.sort_by do |acceptance|
358
+ [-@priorities.fetch(acceptance.rule_index, 0), acceptance.rule_index, acceptance.pattern_index]
359
+ end
203
360
  end
204
361
 
205
362
  def each_state_id(set)
@@ -216,16 +373,33 @@ module Flexr
216
373
  def validate_rules
217
374
  @spec.rules.each do |rule|
218
375
  raise CompileError, "rule #{rule.index} has no pattern" if rule.patterns.empty?
219
- parse_regexp(rule.trailing) if rule.trailing.is_a?(::Regexp)
220
- next if @spec.options[:allow_empty_match]
376
+ if @spec.backend == :firstmatch && !rule.priority.zero?
377
+ diagnostic = Diagnostics.error("FLEXR-E018", "explicit priority requires a longest-match backend",
378
+ help: "use backend :table, :direct, or :auto")
379
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
380
+ end
381
+ validate_trailing(rule) if rule.trailing
382
+
383
+ rule.patterns.each_with_index do |pattern, index|
384
+ if pattern.is_a?(Pattern)
385
+ validate_pattern_body(pattern, rule, index)
386
+ next
387
+ end
221
388
 
222
- rule.patterns.each do |pattern|
223
389
  regexp = pattern.is_a?(String) ? ::Regexp.new(::Regexp.escape(pattern)) : pattern
224
- parse_regexp(regexp) if regexp.is_a?(::Regexp)
225
- next unless regexp.is_a?(::Regexp) && regexp.match?("")
390
+ next unless regexp.is_a?(::Regexp)
391
+
392
+ ast = parse_regexp(regexp)
393
+ has_absence = Regexp::AST.absence?(ast)
394
+ if has_absence && @spec.backend == :firstmatch
395
+ diagnostic = Diagnostics.error("FLEXR-E014", "absence groups in rule patterns require a longest-match backend",
396
+ help: "use backend :table, :direct, or :auto")
397
+ raise UnsupportedRegexpError.new(diagnostic.message, diagnostic: diagnostic)
398
+ end
399
+ next if @spec.options[:allow_empty_match]
400
+ next unless has_absence ? Regexp::AST.nullable?(ast) : regexp.match?("")
226
401
 
227
- diagnostic = Diagnostics.error("FLEXR-E005", "#{Diagnostics.rule_label(rule)} can match an empty string")
228
- raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
402
+ reject_empty_match!(Diagnostics.rule_label(rule))
229
403
  end
230
404
  rescue CompileError => e
231
405
  e.diagnostic.location ||= rule.location if e.diagnostic
@@ -233,16 +407,57 @@ module Flexr
233
407
  end
234
408
  end
235
409
 
410
+ def validate_pattern_body(pattern, rule, index)
411
+ if @spec.backend == :firstmatch
412
+ diagnostic = Diagnostics.error("FLEXR-E014", "pattern values in rule bodies require a longest-match backend",
413
+ help: "use backend :table, :direct, or :auto")
414
+ raise UnsupportedRegexpError.new(diagnostic.message, diagnostic: diagnostic)
415
+ end
416
+ dfa = compile_pattern_value(pattern, rule)
417
+ reject_empty_match!(Diagnostics.rule_label(rule)) if
418
+ !@spec.options[:allow_empty_match] && dfa.accepts.fetch(dfa.start).any?
419
+ @pattern_dfas[[rule.index, index]] = dfa
420
+ end
421
+
422
+ def validate_trailing(rule)
423
+ if rule.trailing.is_a?(Pattern)
424
+ rule.trailing_dfa = compile_pattern_value(rule.trailing, rule)
425
+ reject_empty_match!("trailing context for #{Diagnostics.rule_label(rule)}") if
426
+ rule.trailing_dfa.accepts.fetch(rule.trailing_dfa.start).any?
427
+ return
428
+ end
429
+ return unless rule.trailing.is_a?(::Regexp)
430
+
431
+ ast = parse_regexp(rule.trailing)
432
+ return unless Regexp::AST.absence?(ast)
433
+
434
+ reject_empty_match!("trailing context for #{Diagnostics.rule_label(rule)}") if Regexp::AST.nullable?(ast)
435
+ @active_rules = [rule]
436
+ body, bol_only, end_anchor = strip_anchors(ast)
437
+ condition = Acceptance.new(rule_index: 0, pattern_index: 0, bol_only: bol_only, end_anchor: end_anchor)
438
+ rule.trailing_dfa = determinize([[normalize_regexp(rule.trailing, body), condition]])
439
+ end
440
+
441
+ def reject_empty_match!(label)
442
+ diagnostic = Diagnostics.error("FLEXR-E005", "#{label} can match an empty string")
443
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
444
+ end
445
+
236
446
  def parse_regexp(regexp)
237
447
  encoding = regexp.encoding == Encoding::BINARY ? Encoding::BINARY : @spec.encoding
238
- Regexp::Parser.new(regexp.source, options: regexp.options, encoding: encoding,
239
- unicode: @spec.options[:unicode] == true).parse
448
+ @regexp_asts[regexp] ||= Regexp::Parser.new(regexp.source, options: regexp.options, encoding: encoding,
449
+ unicode: @spec.options[:unicode] == true).parse
450
+ end
451
+
452
+ def normalize_regexp(regexp, ast)
453
+ encoding = regexp.encoding == Encoding::BINARY ? Encoding::BINARY : @spec.encoding
454
+ Regexp::Normalizer.new(ast, encoding: encoding, subject_encoding: @spec.encoding, options: regexp.options).normalize
240
455
  end
241
456
 
242
457
  def diagnostics_for(compiled, elapsed)
243
458
  diagnostics = []
244
459
  present = compiled.machines.values.flat_map do |machine|
245
- machine.dfa.accepts.filter_map { |acceptances| acceptances.min_by(&:rule_index)&.rule_index }
460
+ machine.dfa.accepts.filter_map { |acceptances| acceptances.first&.rule_index }
246
461
  end
247
462
  shadowers = shadowed_rules(compiled)
248
463
  rules_by_index = @spec.rules.to_h { |rule| [rule.index, rule] }
@@ -257,7 +472,7 @@ module Flexr
257
472
  suffix = winners.empty? ? "" : " (shadowed by #{winners.join(', ')})"
258
473
  Diagnostics.warning("FLEXR-W001", "#{Diagnostics.rule_label(rule)} is unreachable#{suffix}", location: rule.location,
259
474
  help: "remove it, reorder the rules, or make its language distinct",
260
- note: example&.fetch(:note))
475
+ note: example&.fetch(:note) || empty_absence_note(rule))
261
476
  end)
262
477
  diagnostics.concat(overlap_diagnostics(compiled, rules_by_index)) if @spec.options[:warn_level] == :all
263
478
 
@@ -331,6 +546,12 @@ module Flexr
331
546
  diagnostics
332
547
  end
333
548
 
549
+ def empty_absence_note(rule)
550
+ return unless @empty_absence_rules[rule.index]
551
+
552
+ 'this language is empty; an absence group that excludes "" cannot match because every string contains ""'
553
+ end
554
+
334
555
  def overlap_diagnostics(compiled, rules_by_index)
335
556
  # shortcut: verify one shortest body and trailing candidate per rule; search alternatives if rejected examples need coverage.
336
557
  compiled.machines.flat_map do |state_name, machine|
@@ -367,20 +588,27 @@ module Flexr
367
588
 
368
589
  winner, length = result
369
590
  end
370
- selected = Diagnostics.rule_label(rules_by_index.fetch(winner))
591
+ winner_rule = rules_by_index.fetch(winner)
592
+ selected = Diagnostics.rule_label(winner_rule)
371
593
  state = state_name == :initial ? "" : " in state #{state_name.inspect}"
372
594
  size = "#{length} #{length == 1 ? 'byte' : 'bytes'}"
595
+ tie = priority_tie_reason(winner_rule, rule)
373
596
  reason = if has_trailing
374
- priority = @spec.backend == :firstmatch ? "first match wins" : "same total length, earlier rule wins"
375
- "#{priority}; matched #{size}, looked ahead #{lookahead} #{lookahead == 1 ? 'byte' : 'bytes'}"
597
+ selection = @spec.backend == :firstmatch ? "first match wins" : "same total length, #{tie}"
598
+ "#{selection}; matched #{size}, looked ahead #{lookahead} #{lookahead == 1 ? 'byte' : 'bytes'}"
376
599
  elsif @spec.backend == :firstmatch
377
600
  "first match wins, matched #{size}"
378
601
  else
379
- "#{size}, earlier rule wins"
602
+ "#{size}, #{tie}"
380
603
  end
381
604
  match_size = has_trailing ? "total length" : "length"
605
+ help = if winner_rule.priority == rule.priority
606
+ "reorder the rules if the later rule should take priority"
607
+ else
608
+ "raise the losing rule's priority if it should win equal-length matches"
609
+ end
382
610
  Diagnostics.info("FLEXR-I001", "#{Diagnostics.rule_label(rule)} overlaps #{selected} at the same #{match_size}",
383
- location: rule.location, help: "reorder the rules if the later rule should take priority",
611
+ location: rule.location, help: help,
384
612
  note: "example: #{input.inspect} selects #{selected}#{state} (#{reason})")
385
613
  end
386
614
  end
@@ -431,21 +659,35 @@ module Flexr
431
659
  examples[index] = [input, winner, state_name, length, lookahead]
432
660
  end
433
661
  end
434
- examples.transform_values do |input, winner, state_name, length, lookahead|
662
+ examples.to_h do |index, (input, winner, state_name, length, lookahead)|
663
+ winner_rule = rules_by_index.fetch(winner)
664
+ rule = rules_by_index.fetch(index)
435
665
  state = state_name == :initial ? "" : " in state #{state_name.inspect}"
436
666
  reason = if @spec.backend == :firstmatch
437
667
  "first match wins, matched #{length} #{length == 1 ? 'byte' : 'bytes'}"
438
668
  elsif lookahead
439
- "longest total match, then rule order; matched #{length} #{length == 1 ? 'byte' : 'bytes'}"
669
+ size = "#{length} #{length == 1 ? 'byte' : 'bytes'}"
670
+ selection = if winner_rule.priority == rule.priority
671
+ "longest total match, then rule order"
672
+ else
673
+ "longest total match, then priority #{winner_rule.priority} and rule order"
674
+ end
675
+ "#{selection}; matched #{size}"
440
676
  else
441
- "same length, earlier rule wins"
677
+ "same length, #{priority_tie_reason(winner_rule, rule)}"
442
678
  end
443
679
  reason += ", looked ahead #{lookahead} #{lookahead == 1 ? 'byte' : 'bytes'}" if lookahead
444
- note = "example: #{input.inspect} selects #{Diagnostics.rule_label(rules_by_index.fetch(winner))}#{state} (#{reason})"
445
- { note: note, winner: winner }
680
+ note = "example: #{input.inspect} selects #{Diagnostics.rule_label(winner_rule)}#{state} (#{reason})"
681
+ [index, { note: note, winner: winner }]
446
682
  end
447
683
  end
448
684
 
685
+ def priority_tie_reason(winner, loser)
686
+ return "earlier rule wins" if winner.priority == loser.priority
687
+
688
+ "priority #{winner.priority} beats #{loser.priority}"
689
+ end
690
+
449
691
  def diagnostic_trailing_dfas(rules)
450
692
  rules.select(&:trailing).to_h do |rule|
451
693
  dfa = rule.trailing_dfa || Flexr.compile_pattern(rule.trailing, encoding: @spec.encoding,
@@ -461,7 +703,7 @@ module Flexr
461
703
  shadowers = Hash.new { |hash, key| hash[key] = [] }
462
704
  compiled.machines.each_value do |machine|
463
705
  machine.dfa.accepts.each do |acceptances|
464
- winner = acceptances.min_by(&:rule_index)&.rule_index
706
+ winner = acceptances.first&.rule_index
465
707
  next unless winner
466
708
 
467
709
  acceptances.each do |acceptance|
@@ -481,12 +723,13 @@ module Flexr
481
723
  end
482
724
 
483
725
  def capture_rules
484
- @spec.rules.select do |rule|
485
- rule.patterns.any? do |pattern|
486
- source = pattern.respond_to?(:source) ? pattern.source : pattern.to_s
487
- capturing_group?(source)
488
- end
489
- end
726
+ @spec.rules.select { |rule| rule.patterns.any? { |pattern| pattern_capture?(pattern) } }
727
+ end
728
+
729
+ def pattern_capture?(pattern)
730
+ return pattern.operands.any? { |operand| pattern_capture?(operand) } if pattern.is_a?(Pattern)
731
+
732
+ pattern.is_a?(::Regexp) && capturing_group?(pattern.source)
490
733
  end
491
734
 
492
735
  def capturing_group?(source)
@@ -515,6 +758,8 @@ module Flexr
515
758
  return {} if declared.empty?
516
759
 
517
760
  emitted = @spec.rules.each_with_object({}) do |rule, rules_by_token|
761
+ next if rule.channel
762
+
518
763
  action = rule.action
519
764
  tokens = if action.is_a?(Array) && action.first == :emit
520
765
  [action.last]
@@ -537,10 +782,38 @@ module Flexr
537
782
  end
538
783
 
539
784
  def variable_pattern?(pattern)
540
- source = pattern.respond_to?(:source) ? pattern.source : pattern.to_s
541
- source = source.gsub(/\\./, "")
785
+ return variable_algebra?(pattern) if pattern.is_a?(Pattern)
786
+ return false unless pattern.is_a?(::Regexp)
787
+ return true if Regexp::AST.absence?(@regexp_asts[pattern])
788
+
789
+ source = pattern.source.gsub(/\\./, "")
542
790
  source.match?(/[+*]|\{\d+,\d*\}/)
543
791
  end
792
+
793
+ def variable_algebra?(pattern)
794
+ operands = pattern.operands
795
+ case pattern.operation
796
+ when :literal, :+
797
+ operands.any? { |operand| variable_pattern?(operand) }
798
+ when :|
799
+ operands.any? { |operand| variable_pattern?(operand) } ||
800
+ operands.filter_map { |operand| literal_width(operand) }.uniq.length > 1
801
+ when :&
802
+ operands.all? { |operand| variable_pattern?(operand) }
803
+ when :-
804
+ variable_pattern?(operands.first)
805
+ else
806
+ true
807
+ end
808
+ end
809
+
810
+ def literal_width(pattern)
811
+ return pattern.bytesize if pattern.is_a?(String)
812
+ return unless pattern.is_a?(Pattern) && %i[literal +].include?(pattern.operation)
813
+
814
+ widths = pattern.operands.map { |operand| literal_width(operand) }
815
+ widths.sum unless widths.include?(nil)
816
+ end
544
817
  end
545
818
  end
546
819
  end
@@ -124,7 +124,7 @@ module Flexr
124
124
 
125
125
  def packed_transition(state, class_id)
126
126
  cursor = state
127
- loop do
127
+ while cursor
128
128
  index = @packed.fetch(:base).fetch(cursor) + class_id
129
129
  return @packed.fetch(:next).fetch(index) if @packed.fetch(:check)[index] == cursor
130
130
 
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flexr
4
+ module Automaton
5
+ module DFAOperations
6
+ module_function
7
+
8
+ def difference(left, right, &)
9
+ product(left, right, intersection: false, &).first
10
+ end
11
+
12
+ def product(left, right, intersection:)
13
+ classes = {}
14
+ ec = left.ec.zip(right.ec).map { |pair| classes[pair] ||= classes.length }
15
+ left_classes, right_classes = classes.keys.transpose
16
+ states = [[left.start, right.start]]
17
+ ids = { states.first => 0 }
18
+ transitions = []
19
+ accepts = []
20
+ overlap = false
21
+ cursor = 0
22
+ while cursor < states.length
23
+ left_state, right_state = states.fetch(cursor)
24
+ a = left.transitions.fetch(left_state)
25
+ # A missing transition on the right enters a rejecting sink.
26
+ b = right.transitions.fetch(right_state) if right_state
27
+ transitions << left_classes.each_with_index.map do |class_id, index|
28
+ next_left = a.fetch(class_id)
29
+ next unless next_left
30
+
31
+ next_right = right_state && b.fetch(right_classes.fetch(index))
32
+ next if intersection && !next_right
33
+
34
+ next_pair = [next_left, next_right]
35
+ ids[next_pair] ||= begin
36
+ id = states.length
37
+ yield id
38
+ states << next_pair
39
+ id
40
+ end
41
+ end
42
+ left_accept = left.accepts.fetch(left_state)
43
+ right_accept = !right_state.nil? && !right.accepts.fetch(right_state).empty?
44
+ overlap ||= right_accept && !left_accept.empty?
45
+ accepts << (right_accept == intersection ? left_accept : [])
46
+ cursor += 1
47
+ end
48
+
49
+ dfa = DFA.new(transitions: transitions, accepts: accepts, ec: ec, class_count: classes.length,
50
+ start: 0, rule_ids: left.rule_ids)
51
+ [dfa, overlap]
52
+ end
53
+
54
+ def first_ending(dfa)
55
+ transitions = dfa.transitions.each_with_index.map do |row, state|
56
+ dfa.accepts.fetch(state).empty? ? row : Array.new(dfa.class_count)
57
+ end
58
+ DFA.new(transitions: transitions, accepts: dfa.accepts, ec: dfa.ec, class_count: dfa.class_count,
59
+ start: dfa.start, rule_ids: dfa.rule_ids)
60
+ end
61
+ end
62
+ end
63
+ end