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
@@ -59,7 +59,17 @@ module Flexr
59
59
  payload = generated_payload(parsed, compiled)
60
60
  indent = Source::Passthrough.indentation(parsed.source, parsed.first_dsl_offset)
61
61
  install = "Flexr::Generated.install_compiled!(self, #{payload})\n"
62
- install = "#{install}#{Codegen::Table.new(compiled).source(indent: indent)}"
62
+ if parsed.rules.any? { |rule| !rule.priority.to_i.zero? }
63
+ guard = 'Flexr::Generated.incompatible_artifact!("runtime does not support explicit rule priority")' \
64
+ ' unless Flexr::IR::Rule.method_defined?(:loses_priority_tie?)'
65
+ install = "#{guard}\n#{indent}#{install}"
66
+ end
67
+ if parsed.rules.any?(&:channel)
68
+ guard = 'Flexr::Generated.incompatible_artifact!("runtime does not support token channels")' \
69
+ ' unless defined?(Flexr::Runtime::Channels)'
70
+ install = "#{guard}\n#{indent}#{install}"
71
+ end
72
+ install = "#{install}#{Codegen::Table.new(compiled).source(indent: indent, direct: effective_backend(parsed) == :direct)}"
63
73
  install = "#{install}#{generated_action_source(parsed, indent)}"
64
74
  edits = parsed.dsl_edits.dup
65
75
  parsed.rules.each do |rule|
@@ -93,10 +103,13 @@ module Flexr
93
103
  conditions = Array(rule.pattern_conditions).map do |condition|
94
104
  [condition.rule_index, condition.pattern_index, condition.bol_only, condition.end_anchor]
95
105
  end
106
+ priority = ("priority: #{rule.priority}, " unless rule.priority.to_i.zero?)
107
+ channel = "channel: #{ruby_literal(rule.channel)}, " if rule.channel
96
108
  "{ index: #{rule.index}, patterns: #{ruby_literal(rule.patterns)}, pattern_conditions: #{ruby_literal(conditions)}, trailing: #{ruby_literal(rule.trailing)}, " \
97
- "#{trailing_dfa_expression(rule, parsed)}" \
109
+ "#{trailing_dfa_expression(rule, parsed, compiled.rules.fetch(rule.index).trailing_dfa)}" \
110
+ "#{priority}" \
98
111
  "action: #{generated_rule_action(rule)}, states: #{rule.states.inspect}, " \
99
- "bol_only: #{ruby_literal(rule.bol_only)}, end_anchor: #{ruby_literal(rule.end_anchor)} }"
112
+ "#{channel}bol_only: #{ruby_literal(rule.bol_only)}, end_anchor: #{ruby_literal(rule.end_anchor)} }"
100
113
  end
101
114
  "{ artifact: #{ruby_literal(artifact_metadata)}, rules: [#{definitions.join(', ')}], " \
102
115
  "backend: #{ruby_literal(effective_backend(parsed))}, " \
@@ -122,7 +135,7 @@ module Flexr
122
135
  rules = parsed.rules.map do |rule|
123
136
  IR::Rule.new(index: rule.index, patterns: rule.patterns, trailing: normalize_trailing(rule.trailing),
124
137
  action: rule.action, states: rule.states, bol_only: rule.bol_only,
125
- end_anchor: rule.end_anchor, location: rule.span)
138
+ end_anchor: rule.end_anchor, location: rule.span, channel: rule.channel, priority: rule.priority)
126
139
  rescue CompileError => e
127
140
  e.diagnostic.location ||= rule.span if e.diagnostic
128
141
  raise
@@ -157,12 +170,12 @@ module Flexr
157
170
 
158
171
  def normalize_trailing(value)
159
172
  case value
160
- when nil, ::Regexp
173
+ when nil, ::Regexp, Pattern
161
174
  value
162
175
  when String
163
176
  ::Regexp.new(::Regexp.escape(value))
164
177
  else
165
- diagnostic = Diagnostics.error("FLEXR-E018", "followed_by must be a Regexp or String")
178
+ diagnostic = Diagnostics.error("FLEXR-E018", "followed_by must be a Regexp, String, or Pattern")
166
179
  raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
167
180
  end
168
181
  end
@@ -180,11 +193,11 @@ module Flexr
180
193
  "stats: #{ruby_literal(compiled.stats)}, diagnostics: #{ruby_literal(diagnostics)} }"
181
194
  end
182
195
 
183
- def trailing_dfa_expression(rule, parsed)
196
+ def trailing_dfa_expression(rule, parsed, dfa)
184
197
  return "" unless rule.trailing
185
198
 
186
- dfa = Flexr.compile_pattern(normalize_trailing(rule.trailing), encoding: parsed.config[:encoding],
187
- options: { unicode: effective_options(parsed)[:unicode] == true })
199
+ dfa ||= Flexr.compile_pattern(normalize_trailing(rule.trailing), encoding: parsed.config[:encoding],
200
+ options: { unicode: effective_options(parsed)[:unicode] == true })
188
201
  "trailing_dfa: #{ruby_literal(dfa_data(dfa, compression: table_compression(parsed)))}, "
189
202
  rescue CompileError => e
190
203
  e.diagnostic.location ||= rule.span if e.diagnostic
@@ -232,8 +245,11 @@ module Flexr
232
245
  def embedded_runtime(parsed)
233
246
  sources = RUNTIME_SOURCES.dup
234
247
  sources.insert(6, *MATCHER_RUNTIME_SOURCES) if matcher_runtime?(parsed)
248
+ sources.insert(6, "pattern.rb") if parsed.uses_patterns ||
249
+ parsed.rules.any? { |rule| rule.trailing.is_a?(Pattern) || rule.patterns.any?(Pattern) }
250
+ sources << "runtime/channels.rb" if parsed.rules.any?(&:channel)
235
251
  sources.map do |relative|
236
- File.binread(File.expand_path(relative, __dir__))
252
+ File.binread(File.expand_path(relative, __dir__)).gsub(/\r\n?/, "\n")
237
253
  end.join("\n")
238
254
  end
239
255
 
@@ -266,6 +282,7 @@ module Flexr
266
282
 
267
283
  def generated_action_source(parsed, indent)
268
284
  lines = ["#{indent}def __flexr_generated_execute(rule)", "#{indent} case rule.index"]
285
+ keyword_tables = parsed.config.dig(:options, :keyword_tables)
269
286
  parsed.rules.each do |rule|
270
287
  lines << "#{indent} when #{rule.index}"
271
288
  body = inline_simple_action(rule.action_source) if rule.bind_action && !rule.reads_locals
@@ -273,7 +290,7 @@ module Flexr
273
290
  lines << "#{indent} instance_exec(&self.class.__flexr_generated_actions.fetch(rule.index))"
274
291
  next
275
292
  end
276
- body ||= inline_action_body(rule)
293
+ body ||= inline_action_body(rule, keyword_tables: keyword_tables)
277
294
  if body.nil?
278
295
  lines << "#{indent} instance_exec(&rule.action)"
279
296
  else
@@ -287,15 +304,18 @@ module Flexr
287
304
  lines.join("\n")
288
305
  end
289
306
 
290
- def inline_action_body(rule)
307
+ def inline_action_body(rule, keyword_tables: nil)
291
308
  action = rule.action
292
309
  case action
293
310
  when :skip
294
311
  ""
295
312
  when Array
296
- return "emit(#{ruby_literal(action.fetch(1))}, text)" if action.first == :emit
313
+ return unless action.first == :emit
314
+
315
+ type = action.fetch(1)
316
+ return keyword_action_body(type) if !rule.channel && keyword_tables&.key?(type)
297
317
 
298
- nil
318
+ "emit(#{ruby_literal(type)}, text)"
299
319
  when String
300
320
  return inline_simple_action(rule.action_source) if rule.action_source
301
321
  return unless action.start_with?("proc")
@@ -312,6 +332,17 @@ module Flexr
312
332
  end
313
333
  end
314
334
 
335
+ def keyword_action_body(type)
336
+ literal = ruby_literal(type)
337
+ <<~RUBY
338
+ value = text
339
+ lexeme = @text_start == @match_start ? value : @buffer.byteslice(@match_start...@match_end)
340
+ lexeme = lexeme.dup.force_encoding(::Encoding::UTF_8) unless lexeme.encoding == ::Encoding::UTF_8
341
+ entry = self.class.__flexr_config.options.fetch(:keyword_tables).fetch(#{literal})[lexeme]
342
+ emit(entry ? entry.first : #{literal}, value)
343
+ RUBY
344
+ end
345
+
315
346
  # Hash#inspect changed from hash rockets to keyword-style labels in Ruby
316
347
  # 4. Generated source and its golden digests must be identical on every
317
348
  # supported Ruby, so serialize the small set of Ruby literals used in the
@@ -331,6 +362,8 @@ module Flexr
331
362
  "{#{entries.join(', ')}}"
332
363
  when Array
333
364
  "[#{value.map { |item| ruby_literal(item) }.join(', ')}]"
365
+ when Pattern
366
+ "::Flexr::Pattern.__flexr_restore(#{value.operation.inspect}, #{ruby_literal(value.operands)}, #{ruby_literal(value.name)})"
334
367
  else
335
368
  value.inspect
336
369
  end
@@ -381,11 +414,26 @@ module Flexr
381
414
  # --eval is intentionally explicit; the generated file still contains
382
415
  # executable action source, but its metadata is deterministic for this run.
383
416
  parsed = klass.__flexr_spec
417
+ if (tables = parsed.options[:keyword_tables])
418
+ (passthrough.config[:options] ||= {})[:keyword_tables] = tables
419
+ passthrough.config[:declared_tokens] |= parsed.declared_tokens
420
+ end
384
421
  runtime_rules = parsed.rules.to_h { |rule| [rule.index, rule] }
385
422
  passthrough.rules.each do |rule|
386
423
  runtime_rule = runtime_rules.fetch(rule.index)
387
424
  rule.patterns = runtime_rule.patterns
388
425
  rule.trailing = runtime_rule.trailing
426
+ rule.priority = runtime_rule.priority
427
+ next unless rule.dynamic_channel || rule.channel || runtime_rule.channel
428
+
429
+ rule.channel = runtime_rule.channel
430
+ next unless runtime_rule.skip? || runtime_rule.emit?
431
+
432
+ rule.action = runtime_rule.action
433
+ next unless rule.bind_action
434
+
435
+ rule.bind_action = false
436
+ passthrough.dsl_edits.map! { |edit| edit.first(2) == rule.span ? [*rule.span, ""] : edit }
389
437
  end
390
438
  generate_static(passthrough)
391
439
  end
@@ -302,7 +302,7 @@ module Flexr
302
302
  end
303
303
 
304
304
  def render_rule_call(indent, pattern, action)
305
- prefix = "#{indent}rule(Regexp.new(#{pattern})"
305
+ prefix = "#{indent}rule(::Regexp.new(#{pattern})"
306
306
  return "#{prefix}, #{action})" unless action.start_with?("do\n")
307
307
 
308
308
  lines = action.lines.map(&:chomp)
data/lib/flexr/ir.rb CHANGED
@@ -4,7 +4,7 @@ module Flexr
4
4
  module IR
5
5
  Rule = Struct.new(
6
6
  :index, :patterns, :trailing, :action, :states, :bol_only, :end_anchor, :location,
7
- :pattern_conditions, :trailing_dfa,
7
+ :pattern_conditions, :trailing_dfa, :channel, :priority,
8
8
  keyword_init: true
9
9
  ) do
10
10
  def skip?
@@ -14,6 +14,14 @@ module Flexr
14
14
  def emit?
15
15
  action.is_a?(Array) && action.first == :emit
16
16
  end
17
+
18
+ def priority
19
+ self[:priority] || 0
20
+ end
21
+
22
+ def loses_priority_tie?(other)
23
+ priority < other.priority || (priority == other.priority && index > other.index)
24
+ end
17
25
  end
18
26
 
19
27
  State = Struct.new(:name, :inclusive, :id, :location, keyword_init: true)
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flexr
4
+ module Keywords
5
+ module_function
6
+
7
+ def add!(options, declared_tokens, words, among:, location: nil)
8
+ error!("keywords requires a base token Symbol", location: location) unless among.is_a?(Symbol)
9
+ error!("keywords requires a nonempty Array or Hash", location: location) unless (words.is_a?(Array) || words.is_a?(Hash)) && !words.empty?
10
+
11
+ tables = options.fetch(:keyword_tables, {})
12
+ table = tables.fetch(among, {}).dup
13
+ entries = words.is_a?(Hash) ? words : words.map { |word| [word, nil] }
14
+ types = entries.map do |word, type|
15
+ error!("keyword #{word.inspect} must be a nonempty String", location: location) unless word.is_a?(String) && !word.empty?
16
+
17
+ normalized = spelling(word).dup.freeze
18
+ error!("keyword #{word.b.inspect} must have valid UTF-8 spelling", location: location) unless normalized.valid_encoding?
19
+ type = normalized.upcase.to_sym if words.is_a?(Array)
20
+ error!("keyword #{word.inspect} requires a token Symbol", location: location) unless type.is_a?(Symbol)
21
+ error!("keyword #{word.inspect} has conflicting types for #{among.inspect}", location: location) if table.key?(normalized) && table.fetch(normalized).first != type
22
+
23
+ table[normalized] ||= [type, location&.freeze].freeze
24
+ type
25
+ end
26
+ options[:keyword_tables] = tables.merge(among => table.freeze).freeze
27
+ declared_tokens.push(among, *types).uniq!
28
+ end
29
+
30
+ def spelling(lexeme)
31
+ lexeme.encoding == ::Encoding::UTF_8 ? lexeme : lexeme.dup.force_encoding(::Encoding::UTF_8)
32
+ end
33
+
34
+ def error!(message, location: nil, help: nil, note: nil)
35
+ diagnostic = Diagnostics.error("FLEXR-E028", message, location: location, help: help, note: note)
36
+ raise CompileError.new(message, diagnostic: diagnostic)
37
+ end
38
+
39
+ module Emission
40
+ private
41
+
42
+ def execute(rule)
43
+ return super unless rule.emit? && !rule.channel
44
+
45
+ type = rule.action[1]
46
+ table = self.class.__flexr_config.options[:keyword_tables]&.[](type)
47
+ return super unless table
48
+
49
+ value = text
50
+ lexeme = @text_start == @match_start ? value : @buffer.byteslice(@match_start...@match_end)
51
+ entry = table[Keywords.spelling(lexeme)]
52
+ emit(entry ? entry.first : type, value)
53
+ end
54
+ end
55
+ end
56
+
57
+ module DSL
58
+ def keywords(words, among:)
59
+ __flexr_mutate! do
60
+ Keywords.add!(@__flexr_config.options, @__flexr_config.declared_tokens, words, among: among)
61
+ end
62
+ nil
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flexr
4
+ class Pattern
5
+ attr_reader :operation, :operands, :name
6
+
7
+ def self.build(*values)
8
+ operands = values.flatten.map do |value|
9
+ case value
10
+ when Pattern then value
11
+ when String, ::Regexp then new(:literal, [value])
12
+ else invalid!
13
+ end
14
+ end
15
+ invalid! if operands.empty?
16
+ operands.one? ? operands.first : new(:|, operands)
17
+ end
18
+
19
+ def self.upto(value)
20
+ new(:upto, [build(value)])
21
+ end
22
+
23
+ def self.__flexr_restore(operation, operands, name)
24
+ new(operation, operands, name)
25
+ end
26
+
27
+ def self.invalid!
28
+ diagnostic = Diagnostics.error("FLEXR-E018", "pattern requires Regexp, String, or Pattern values")
29
+ raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
30
+ end
31
+
32
+ private_class_method :new, :invalid!
33
+
34
+ def initialize(operation, operands, name = nil)
35
+ @operation = operation
36
+ @operands = operands.map do |value|
37
+ case value
38
+ when String then String.new(value).freeze
39
+ when ::Regexp then ::Regexp.new(value).freeze
40
+ else value
41
+ end
42
+ end.freeze
43
+ @name = String.new(name).freeze if name
44
+ freeze
45
+ end
46
+
47
+ def |(other) = binary(:|, other)
48
+ def +(other) = binary(:+, other)
49
+ def &(other) = binary(:&, other)
50
+ def -(other) = binary(:-, other)
51
+ def ! = Pattern.__flexr_restore(:!, [self], nil)
52
+
53
+ def __flexr_named(name)
54
+ Pattern.__flexr_restore(@operation, @operands, name)
55
+ end
56
+
57
+ def inspect
58
+ return @name if @name
59
+
60
+ case @operation
61
+ when :literal then @operands.first.inspect
62
+ when :! then "!#{@operands.first.inspect}"
63
+ when :upto then "upto(#{@operands.first.inspect})"
64
+ else "(#{@operands.map(&:inspect).join(" #{@operation} ")})"
65
+ end
66
+ end
67
+
68
+ alias to_s inspect
69
+
70
+ private
71
+
72
+ def binary(operation, other)
73
+ Pattern.__flexr_restore(operation, [self, Pattern.build(other)], nil)
74
+ end
75
+ end
76
+ end
@@ -11,6 +11,9 @@ module Flexr
11
11
  Alt = Struct.new(:children, :loc, keyword_init: true)
12
12
  Star = Struct.new(:child, :loc, keyword_init: true)
13
13
  Repeat = Struct.new(:child, :minimum, :maximum, :loc, keyword_init: true)
14
+ Absence = Struct.new(:child, :loc, keyword_init: true)
15
+ Difference = Struct.new(:left, :right, :loc, keyword_init: true)
16
+ EmbeddedDFA = Struct.new(:dfa)
14
17
  Anchor = Struct.new(:kind, :loc, keyword_init: true)
15
18
  TrailMark = Struct.new(:rule_id, :loc, keyword_init: true)
16
19
  CharClass = Struct.new(:ranges, :negated, :loc, keyword_init: true)
@@ -24,18 +27,41 @@ module Flexr
24
27
  when "ByteRange" then "ByteRange(#{lo}..#{hi})"
25
28
  when "CodepointRange" then "CodepointRange(#{lo}..#{hi})"
26
29
  when "Anchor" then "Anchor(#{kind})"
27
- when "Star" then "Star(#{child})"
30
+ when "Star", "Absence" then "#{name}(#{child})"
28
31
  when "Repeat" then "Repeat(#{child}, #{minimum}, #{maximum || '∞'})"
29
32
  when "Seq", "Alt" then "#{name}(#{children.join(', ')})"
33
+ when "Difference" then "Difference(#{left}, #{right})"
30
34
  else super
31
35
  end
32
36
  end
33
37
  end
34
38
 
35
- [Empty, Fail, ByteRange, CodepointRange, Seq, Alt, Star, Repeat, Anchor, TrailMark, CharClass].each do |node_class|
39
+ [Empty, Fail, ByteRange, CodepointRange, Seq, Alt, Star, Repeat, Absence, Difference,
40
+ Anchor, TrailMark, CharClass].each do |node_class|
36
41
  node_class.include(Formatting)
37
42
  end
38
43
 
44
+ def self.absence?(node)
45
+ case node
46
+ when Absence then true
47
+ when Seq, Alt then node.children.any? { |child| absence?(child) }
48
+ when Star, Repeat then absence?(node.child)
49
+ else false
50
+ end
51
+ end
52
+
53
+ def self.nullable?(node)
54
+ case node
55
+ when Empty, Anchor, Star then true
56
+ when Repeat then node.minimum.zero? || nullable?(node.child)
57
+ when Seq then node.children.all? { |child| nullable?(child) }
58
+ when Alt then node.children.any? { |child| nullable?(child) }
59
+ when Absence then !nullable?(node.child)
60
+ when Difference then nullable?(node.left) && !nullable?(node.right)
61
+ else false
62
+ end
63
+ end
64
+
39
65
  class Node
40
66
  attr_reader :loc
41
67
 
@@ -3,17 +3,22 @@
3
3
  module Flexr
4
4
  module Regexp
5
5
  class Normalizer
6
- def initialize(ast, encoding: Encoding::UTF_8, options: 0)
6
+ def initialize(ast, encoding: Encoding::UTF_8, options: 0, subject_encoding: encoding)
7
7
  @ast = ast
8
8
  @encoding = encoding
9
9
  @options = options
10
10
  @byte_mode = [Encoding::BINARY, Encoding::US_ASCII].include?(encoding)
11
+ @subject_byte_mode = [Encoding::BINARY, Encoding::US_ASCII].include?(subject_encoding)
11
12
  end
12
13
 
13
14
  def normalize
14
15
  normalize_node(@ast)
15
16
  end
16
17
 
18
+ def universe
19
+ @universe ||= AST::Star.new(child: universal_character, loc: nil)
20
+ end
21
+
17
22
  private
18
23
 
19
24
  def normalize_node(node)
@@ -31,6 +36,8 @@ module Flexr
31
36
  child.is_a?(AST::Fail) ? AST::Empty.new(loc: node.loc) : AST::Star.new(child: child, loc: node.loc)
32
37
  when AST::Repeat
33
38
  repeat(node)
39
+ when AST::Absence
40
+ absence(node)
34
41
  else
35
42
  raise CompileError, "unknown regexp AST node: #{node.class}"
36
43
  end
@@ -143,6 +150,33 @@ module Flexr
143
150
  AST::Repeat.new(child: child, minimum: node.minimum, maximum: node.maximum, loc: node.loc)
144
151
  end
145
152
 
153
+ def absence(node)
154
+ return AST::Fail.new(loc: node.loc) if AST.nullable?(node.child)
155
+
156
+ child = normalize_node(node.child)
157
+ AST::Difference.new(left: universe, right: sequence([universe, child, universe]), loc: node.loc)
158
+ end
159
+
160
+ def universal_character
161
+ return AST::ByteRange.new(lo: 0, hi: 255, loc: nil) if @subject_byte_mode
162
+
163
+ continuation = [0x80, 0xbf]
164
+ # Keep restricted lead bytes separate so the complement preserves scalar boundaries.
165
+ sequences = [
166
+ [[0x00, 0x7f]],
167
+ [[0xc2, 0xdf], continuation],
168
+ [[0xe0, 0xe0], [0xa0, 0xbf], continuation],
169
+ [[0xe1, 0xec], continuation, continuation],
170
+ [[0xed, 0xed], [0x80, 0x9f], continuation],
171
+ [[0xee, 0xef], continuation, continuation],
172
+ [[0xf0, 0xf0], [0x90, 0xbf], continuation, continuation],
173
+ [[0xf1, 0xf3], continuation, continuation, continuation],
174
+ [[0xf4, 0xf4], [0x80, 0x8f], continuation, continuation]
175
+ ]
176
+ @trie_cache = {}
177
+ trie(sequences, 0)
178
+ end
179
+
146
180
  def complement(ranges)
147
181
  result = []
148
182
  cursor = 0
@@ -141,6 +141,8 @@ module Flexr
141
141
  node = parse_expression
142
142
  expect(")")
143
143
  @options = saved_options if prefix
144
+ return AST::Absence.new(child: node, loc: span(starting)) if prefix == :absence
145
+
144
146
  node
145
147
  end
146
148
 
@@ -191,9 +193,10 @@ module Flexr
191
193
  raise unsupported("conditional groups",
192
194
  "for this optional-prefix conditional, rewrite rule(/(a)?(?(1)b|c)/) as rule(/(?:ab|c)/); keep the action; other conditions need separate rules or state checks")
193
195
  end
194
- if peek_prefix?("~")
195
- raise unsupported("absence groups",
196
- "when excluding a single literal, rewrite rule(/x(?~a)/) as rule(/x[^a]*/); keep the action; larger absence expressions need a separate rewrite")
196
+ if consume?("~")
197
+ raise unsupported("extended absence operators", "use an absence group (?~X) to exclude a subexpression") if peek_prefix?("|")
198
+
199
+ return :absence
197
200
  end
198
201
  raise unsupported("unsupported group syntax", "use a non-capturing group (?:...)")
199
202
  end
@@ -520,7 +523,7 @@ module Flexr
520
523
 
521
524
  def anchor_nodes(node)
522
525
  return [node] if node.is_a?(AST::Anchor)
523
- return anchor_nodes(node.child) if node.is_a?(AST::Star) || node.is_a?(AST::Repeat)
526
+ return anchor_nodes(node.child) if node.is_a?(AST::Star) || node.is_a?(AST::Repeat) || node.is_a?(AST::Absence)
524
527
  return [] unless node.respond_to?(:children)
525
528
 
526
529
  node.children.flat_map { |child| anchor_nodes(child) }
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
  # Generated by flexr. DO NOT EDIT.
3
3
  # source: lib/flexr/regexp/tokenizer.flexr.rb
4
- # spec-digest: sha256:a9c3e840a6b33c0cb45b25200a372b0ce4f578497f96cc58a591ccd751954f16
4
+ # spec-digest: sha256:6b719f311409b17d9824cf3ad9ab35a27f11e476e6b717fdbc797ca2963fdfb0
5
5
  # artifact-schema: 2
6
6
  # runtime-abi: 2
7
7
  # unicode: 15.1.0
@@ -17,7 +17,7 @@ module Flexr
17
17
  # This specification is intentionally small: it is a dogfood target for
18
18
  # the source lexer path, not the parser's implementation.
19
19
  class SourceLexer < Flexr::Lexer
20
- Flexr::Generated.install_compiled!(self, { artifact: {schema_version: 2, compiler_version: "2.0.0", runtime_abi_version: 2, unicode_version: "15.1.0"}, rules: [{ index: 0, patterns: [/[ \t\r\n]+/], pattern_conditions: [[0, 0, false, false]], trailing: nil, action: :skip, states: [:initial], bol_only: false, end_anchor: nil }, { index: 1, patterns: [/\\p\{[A-Za-z_][A-Za-z0-9_]*\}/], pattern_conditions: [[1, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 2, patterns: [/\\./], pattern_conditions: [[2, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 3, patterns: [/\[[^\]\n]*\]/], pattern_conditions: [[3, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 4, patterns: [/[?*+]|\{[0-9]+(?:,[0-9]*)?\}/], pattern_conditions: [[4, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 5, patterns: [/\|/], pattern_conditions: [[5, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 6, patterns: [/\(/], pattern_conditions: [[6, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 7, patterns: [/\)/], pattern_conditions: [[7, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 8, patterns: [/\^|\$/], pattern_conditions: [[8, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 9, patterns: [/\./], pattern_conditions: [[9, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 10, patterns: [/[^\\\[\]().|?*+{}^$ \t\r\n]/], pattern_conditions: [[10, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }], backend: :table, token_kind: :array, encoding: Encoding::BINARY, declared_tokens: [:PROPERTY, :ESCAPE, :CHAR_CLASS, :QUANTIFIER, :ALTERNATION, :GROUP_OPEN, :GROUP_CLOSE, :ANCHOR, :DOT, :LITERAL], options: {}, eof_rules: { }, states: [], inclusive_states: {initial: true}, compiled: { machines: { :initial => { state_name: :initial, dfa: {accepts: [[], [[10, 0, false, false]], [[0, 0, false, false]], [[8, 0, false, false]], [[6, 0, false, false]], [[7, 0, false, false]], [[4, 0, false, false]], [[9, 0, false, false]], [], [], [], [[5, 0, false, false]], [[3, 0, false, false]], [[2, 0, false, false]], [[2, 0, false, false]], [], [], [], [], [[1, 0, false, false]]], ec: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 8, 9, 9, 9, 10, 11, 12, 12, 13, 14, 15, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 23, 24, 25, 26, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 31, 32, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34], class_count: 35, state_count: 20, start: 0, rule_ids: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], packed: {base: [0, 0, 12, 0, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 3, 22, 15, 4, 21, 0], default: [1, nil, nil, nil, nil, nil, nil, nil, 8, 13, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil], next: [nil, 2, 2, nil, 2, nil, 2, nil, 3, nil, 4, 5, 6, 2, 2, 7, 2, 15, 2, 6, nil, 17, 8, 9, nil, 3, nil, 12, nil, nil, 14, 10, 11, nil, 16, 17, 18, 6, 18, 15, nil, 18, 18, 18, 18, 18, nil, 18, nil, 18, 18, 18, nil, nil, 19, 6], check: [nil, 0, 0, 9, 0, 8, 0, nil, 0, nil, 0, 0, 0, 2, 2, 0, 2, 10, 2, 0, nil, 17, 0, 0, 0, 0, nil, 8, nil, nil, 9, 0, 0, 0, 14, 15, 16, 17, 18, 15, nil, 16, 18, 16, 16, 16, nil, 18, nil, 18, 18, 18, nil, nil, 18, 15]}} } }, states: [:initial], stats: {initial: {states: 20, classes: 35, accepting_states: 12}}, diagnostics: [] } })
20
+ Flexr::Generated.install_compiled!(self, { artifact: {schema_version: 2, compiler_version: "2.1.0", runtime_abi_version: 2, unicode_version: "15.1.0"}, rules: [{ index: 0, patterns: [/[ \t\r\n]+/], pattern_conditions: [[0, 0, false, false]], trailing: nil, action: :skip, states: [:initial], bol_only: false, end_anchor: nil }, { index: 1, patterns: [/\\p\{[A-Za-z_][A-Za-z0-9_]*\}/], pattern_conditions: [[1, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 2, patterns: [/\\./], pattern_conditions: [[2, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 3, patterns: [/\[[^\]\n]*\]/], pattern_conditions: [[3, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 4, patterns: [/[?*+]|\{[0-9]+(?:,[0-9]*)?\}/], pattern_conditions: [[4, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 5, patterns: [/\|/], pattern_conditions: [[5, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 6, patterns: [/\(/], pattern_conditions: [[6, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 7, patterns: [/\)/], pattern_conditions: [[7, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 8, patterns: [/\^|\$/], pattern_conditions: [[8, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 9, patterns: [/\./], pattern_conditions: [[9, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }, { index: 10, patterns: [/[^\\\[\]().|?*+{}^$ \t\r\n]/], pattern_conditions: [[10, 0, false, false]], trailing: nil, action: :__flexr_generated_method, states: [:initial], bol_only: false, end_anchor: nil }], backend: :table, token_kind: :array, encoding: Encoding::BINARY, declared_tokens: [:PROPERTY, :ESCAPE, :CHAR_CLASS, :QUANTIFIER, :ALTERNATION, :GROUP_OPEN, :GROUP_CLOSE, :ANCHOR, :DOT, :LITERAL], options: {}, eof_rules: { }, states: [], inclusive_states: {initial: true}, compiled: { machines: { :initial => { state_name: :initial, dfa: {accepts: [[], [[10, 0, false, false]], [[0, 0, false, false]], [[8, 0, false, false]], [[6, 0, false, false]], [[7, 0, false, false]], [[4, 0, false, false]], [[9, 0, false, false]], [], [], [], [[5, 0, false, false]], [[3, 0, false, false]], [[2, 0, false, false]], [[2, 0, false, false]], [], [], [], [], [[1, 0, false, false]]], ec: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 8, 9, 9, 9, 10, 11, 12, 12, 13, 14, 15, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 23, 24, 25, 26, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 31, 32, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34], class_count: 35, state_count: 20, start: 0, rule_ids: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], packed: {base: [0, 0, 12, 0, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 3, 22, 15, 4, 21, 0], default: [1, nil, nil, nil, nil, nil, nil, nil, 8, 13, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil], next: [nil, 2, 2, nil, 2, nil, 2, nil, 3, nil, 4, 5, 6, 2, 2, 7, 2, 15, 2, 6, nil, 17, 8, 9, nil, 3, nil, 12, nil, nil, 14, 10, 11, nil, 16, 17, 18, 6, 18, 15, nil, 18, 18, 18, 18, 18, nil, 18, nil, 18, 18, 18, nil, nil, 19, 6], check: [nil, 0, 0, 9, 0, 8, 0, nil, 0, nil, 0, 0, 0, 2, 2, 0, 2, 10, 2, 0, nil, 17, 0, 0, 0, 0, nil, 8, nil, nil, 9, 0, 0, 0, 14, 15, 16, 17, 18, 15, nil, 16, 18, 16, 16, 16, nil, 18, nil, 18, 18, 18, nil, nil, 18, 15]}} } }, states: [:initial], stats: {initial: {states: 20, classes: 35, accepting_states: 12}}, diagnostics: [] } })
21
21
  def scan_one
22
22
  if @__flexr_generated_scan_state != @state
23
23
  machine = self.class.__flexr_compiled.machines.fetch(@state)
@@ -88,23 +88,12 @@ module Flexr
88
88
  rules = self.class.__flexr_rules
89
89
  source = buffer.stable_source
90
90
  guarded_steps = scan_steps_guarded?
91
- token_start = more_text_start || position
92
- token_limit = max_token_size
93
91
  check_token_limit = token_limit_required?
94
92
  cursor = position
95
93
  best = nil
96
- accel_mode = @accel_mode
97
- accelerate = accel_mode != :none && !(accel_mode == :auto && @__flexr_generated_auto_accel_off)
98
- if source && !guarded_steps && !check_token_limit && !accelerate
99
- while cursor < source.bytesize
100
- byte = source.getbyte(cursor)
101
- current = if direct_nxt
102
- class_id = ec[byte]
103
- value = direct_nxt[(current * direct_classes) + class_id]
104
- value >= 0 ? value : nil
105
- else
106
- dfa.transition(current, byte)
107
- end
94
+ if source && !guarded_steps && !check_token_limit && (@accel_mode == :auto || @accel_mode == :none)
95
+ while (byte = source.getbyte(cursor))
96
+ current = dfa.transition(current, byte)
108
97
  break unless current
109
98
  cursor += 1
110
99
  acceptance = accepts[current].first
@@ -118,6 +107,9 @@ module Flexr
118
107
  end
119
108
  return best
120
109
  end
110
+ token_start = more_text_start || position
111
+ token_limit = max_token_size
112
+ accelerate = @accel_mode != :none && !(@accel_mode == :auto && @__flexr_generated_auto_accel_off)
121
113
  while cursor < (source ? source.bytesize : buffer.bytesize) || buffer.ensure_available?(cursor + 1)
122
114
  if accelerate
123
115
  region = __flexr_generated_acceleration_region(dfa, current)
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flexr
4
+ module Runtime
5
+ class ChannelToken < Token
6
+ attr_reader :channel, :leading_trivia
7
+
8
+ def initialize(type:, value:, location:, channel: :default, leading_trivia: EMPTY_TRIVIA)
9
+ @channel = channel
10
+ @leading_trivia = leading_trivia.freeze
11
+ super(type: type, value: value, location: location)
12
+ end
13
+
14
+ def with(**changes)
15
+ return self if changes.empty?
16
+
17
+ self.class.new(**to_h, channel: channel, leading_trivia: leading_trivia, **changes)
18
+ end
19
+ end
20
+
21
+ module Channels
22
+ def tokens(channels: :default)
23
+ previous = @__flexr_all_channels
24
+ @__flexr_all_channels = channels == :all
25
+ super
26
+ ensure
27
+ @__flexr_all_channels = previous
28
+ end
29
+
30
+ def next_token
31
+ loop do
32
+ @__flexr_token_channel = nil
33
+ @__flexr_recovery_token = nil
34
+ token = super
35
+ unless token
36
+ @__flexr_leading_trivia = nil
37
+ return
38
+ end
39
+
40
+ if @__flexr_token_channel
41
+ if @token_kind == :struct
42
+ token = ChannelToken.new(**token.to_h, channel: @__flexr_token_channel)
43
+ (@__flexr_leading_trivia ||= []) << token
44
+ end
45
+ return token if @__flexr_all_channels
46
+ else
47
+ return token unless @__flexr_leading_trivia
48
+
49
+ trivia = @__flexr_leading_trivia
50
+ @__flexr_leading_trivia = nil
51
+ return ChannelToken.new(**token.to_h, leading_trivia: trivia)
52
+ end
53
+ end
54
+ end
55
+
56
+ def error!(message)
57
+ result = super
58
+ @__flexr_recovery_token = @pending
59
+ result
60
+ end
61
+
62
+ private
63
+
64
+ def execute(rule)
65
+ super
66
+ @__flexr_token_channel = rule.channel unless @pending.equal?(@__flexr_recovery_token)
67
+ end
68
+ end
69
+ end
70
+ end