flexr 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +1 -0
  3. data/CHANGELOG.md +116 -0
  4. data/CONTRIBUTING.md +13 -1
  5. data/README.md +6 -2
  6. data/Rakefile +41 -5
  7. data/Steepfile +7 -0
  8. data/benchmark/golden/calculator_lexer.rb +276 -0
  9. data/benchmark/golden/graphql_lexer.rb +310 -0
  10. data/benchmark/golden/json_lexer.rb +292 -0
  11. data/benchmark/golden/regexp_tokenizer.rb +293 -0
  12. data/benchmark/golden/ruby_subset_lexer.rb +280 -0
  13. data/benchmark/golden/sql_lexer.rb +293 -0
  14. data/benchmark/golden/toml_lexer.rb +292 -0
  15. data/benchmark/golden/toy_lang_lexer.rb +273 -0
  16. data/benchmark/golden/with_lrama_lexer.rb +264 -0
  17. data/benchmark/golden/with_racc_lexer.rb +264 -0
  18. data/benchmark/lrama_lexer.rb +165 -0
  19. data/benchmark/matrix.rb +79 -0
  20. data/benchmark/profile.rb +109 -0
  21. data/benchmark/run.rb +4 -1
  22. data/benchmark/state_dispatch.rb +78 -0
  23. data/docs/README.md +1 -2
  24. data/docs/RELEASING.md +9 -2
  25. data/docs/migration-v2.md +73 -0
  26. data/docs/perf-log.md +108 -0
  27. data/docs/reference/README.md +2 -0
  28. data/docs/reference/cli.md +71 -5
  29. data/docs/reference/compatibility.md +9 -2
  30. data/docs/reference/diagnostics.md +338 -0
  31. data/docs/reference/dsl.md +8 -5
  32. data/docs/reference/errors.md +28 -0
  33. data/docs/reference/generated-artifacts.md +11 -0
  34. data/docs/reference/public-api.md +32 -8
  35. data/docs/reference/regexp.md +19 -7
  36. data/docs/reference/ruby-lsp.md +34 -0
  37. data/docs/reference/testing.md +57 -0
  38. data/examples/graphql/README.md +14 -0
  39. data/examples/graphql/lexer.flexr.rb +29 -0
  40. data/examples/sql/README.md +16 -0
  41. data/examples/sql/lexer.flexr.rb +23 -0
  42. data/examples/toml/README.md +14 -0
  43. data/examples/toml/lexer.flexr.rb +23 -0
  44. data/gemfiles/ruby_lsp.gemfile +4 -0
  45. data/gemfiles/types.gemfile +7 -0
  46. data/lib/flexr/automaton/accel.rb +11 -1
  47. data/lib/flexr/automaton/analysis.rb +161 -7
  48. data/lib/flexr/automaton/compiler.rb +175 -24
  49. data/lib/flexr/cli.rb +117 -17
  50. data/lib/flexr/codegen/firstmatch.rb +1 -7
  51. data/lib/flexr/codegen/table.rb +2 -2
  52. data/lib/flexr/configuration.rb +8 -0
  53. data/lib/flexr/deprecations.rb +26 -0
  54. data/lib/flexr/diagnostics.rb +39 -3
  55. data/lib/flexr/dsl.rb +11 -9
  56. data/lib/flexr/errors.rb +6 -6
  57. data/lib/flexr/generated.rb +27 -15
  58. data/lib/flexr/generator.rb +44 -29
  59. data/lib/flexr/grammar.rb +41 -0
  60. data/lib/flexr/ir.rb +2 -2
  61. data/lib/flexr/migration.rb +31 -0
  62. data/lib/flexr/minitest.rb +24 -0
  63. data/lib/flexr/options.rb +4 -2
  64. data/lib/flexr/regexp/matcher.rb +26 -0
  65. data/lib/flexr/regexp/normalizer.rb +4 -8
  66. data/lib/flexr/regexp/parser.rb +127 -21
  67. data/lib/flexr/regexp/tokenizer.rb +4 -4
  68. data/lib/flexr/rspec.rb +51 -0
  69. data/lib/flexr/runtime/core.rb +21 -15
  70. data/lib/flexr/runtime/errors.rb +6 -4
  71. data/lib/flexr/runtime/interpreter.rb +47 -45
  72. data/lib/flexr/runtime/location.rb +5 -4
  73. data/lib/flexr/runtime/token.rb +1 -0
  74. data/lib/flexr/runtime.rb +6 -2
  75. data/lib/flexr/source/passthrough.rb +14 -11
  76. data/lib/flexr/source/prism_reader.rb +45 -14
  77. data/lib/flexr/testing.rb +47 -0
  78. data/lib/flexr/trace.rb +197 -0
  79. data/lib/flexr/unicode/property.rb +1 -2
  80. data/lib/flexr/unicode/reference_regexp.rb +8 -9
  81. data/lib/flexr/version.rb +1 -1
  82. data/lib/flexr.rb +1 -0
  83. data/lib/ruby_lsp/flexr/addon.rb +114 -0
  84. data/sig/flexr.rbs +185 -0
  85. data/site/src/layouts/SiteLayout.astro +8 -2
  86. data/site/src/pages/index.astro +69 -155
  87. data/site/src/styles/custom.css +4 -287
  88. data/site/src/styles/landing.css +239 -0
  89. data/test/ruby_lsp_addon_spec.rb +135 -0
  90. data/tools/docs_verify.rb +1 -0
  91. data/tools/golden.rb +54 -0
  92. data/tools/release_notes.rb +16 -0
  93. metadata +44 -11
  94. data/benchmark/golden/calculator_lexer.sha256 +0 -1
  95. data/benchmark/golden/json_lexer.sha256 +0 -1
  96. data/benchmark/golden/regexp_tokenizer.sha256 +0 -1
  97. data/benchmark/golden/ruby_subset_lexer.sha256 +0 -1
  98. data/benchmark/golden/toy_lang_lexer.sha256 +0 -1
  99. data/benchmark/golden/with_lrama_lexer.sha256 +0 -1
  100. data/benchmark/golden/with_racc_lexer.sha256 +0 -1
  101. data/docs/releases/v1.1.0.md +0 -44
@@ -201,11 +201,7 @@ module Flexr
201
201
  end
202
202
 
203
203
  def reference_pattern?(pattern)
204
- return false unless pattern.is_a?(::Regexp)
205
- return true if pattern.source.match?(/\\[pP]\{/) || pattern.source.match?(/\[:(?:\^)?[a-z]+:\]/)
206
-
207
- @config.options[:unicode] == true && @lexer.utf8_input? &&
208
- pattern.source.match?(/\\[dDwWsS]/)
204
+ Regexp::Matcher.reference?(pattern, encoding: @config.encoding, unicode: @config.options[:unicode] == true)
209
205
  end
210
206
 
211
207
  def scan_firstmatch(position)
@@ -243,14 +239,33 @@ module Flexr
243
239
  def trailing_length(rule, buffer, position)
244
240
  return 0 unless rule.trailing
245
241
 
246
- regexp = rule.trailing
247
- match = streamed_match(
248
- regexp, buffer, position, reference: reference_pattern?(regexp),
249
- limit: :lookahead, rule: rule
250
- )
251
- return nil unless match&.begin(0)&.zero?
242
+ dfa = rule.trailing_dfa || trailing_dfa(rule.trailing)
243
+ state = dfa.start
244
+ cursor = position
245
+ longest = 0 if trailing_accept?(dfa, state, buffer, cursor)
246
+ while buffer.ensure_available?(cursor + 1)
247
+ state = dfa.transition(state, buffer.getbyte(cursor))
248
+ break unless state
249
+
250
+ cursor += 1
251
+ @lexer.consume_step!
252
+ size = cursor - position
253
+ @lexer.ensure_lookahead_size!(size, rule: rule)
254
+ longest = size if trailing_accept?(dfa, state, buffer, cursor)
255
+ end
256
+ longest
257
+ end
252
258
 
253
- match[0].bytesize.tap { |size| @lexer.ensure_lookahead_size!(size, rule: rule) }
259
+ def trailing_accept?(dfa, state, buffer, position)
260
+ acceptance = dfa.accepts[state].first
261
+ acceptance && (!acceptance.end_anchor || end_anchor_match?(buffer, position))
262
+ end
263
+
264
+ def trailing_dfa(pattern)
265
+ @trailing_dfas ||= {}
266
+ @trailing_dfas[pattern] ||= Flexr.compile_pattern(
267
+ pattern, encoding: @config.encoding, options: { unicode: @config.options[:unicode] == true }
268
+ )
254
269
  end
255
270
 
256
271
  def streamed_match(pattern, buffer, position, limit:, rule:, reference: false)
@@ -269,21 +284,13 @@ module Flexr
269
284
  end
270
285
  ensure_stream_limit!(limit, position, subject.bytesize, rule) unless match
271
286
  @lexer.consume_step!
272
- return match unless can_refill_match?(buffer, position, subject.bytesize, tail)
287
+ return match unless can_refill_match?(buffer)
273
288
  end
274
289
  end
275
290
 
276
291
  def match_stream_pattern(pattern, subject, reference:)
277
- if reference
278
- Unicode::ReferenceRegexp.match(
279
- pattern, subject, encoding: @config.encoding,
280
- options: pattern.options, unicode: @config.options[:unicode] == true
281
- )
282
- else
283
- pattern.match(subject, 0)
284
- end
285
- rescue ArgumentError, RegexpError
286
- nil
292
+ Regexp::Matcher.match(pattern, subject, encoding: @config.encoding,
293
+ unicode: @config.options[:unicode] == true, reference: reference)
287
294
  end
288
295
 
289
296
  def stream_subject(buffer, position)
@@ -327,13 +334,8 @@ module Flexr
327
334
  [:complete, length]
328
335
  end
329
336
 
330
- def can_refill_match?(buffer, position, subject_size, tail)
331
- target = if tail == :incomplete
332
- position + subject_size + 1
333
- else
334
- buffer.bytesize + 1
335
- end
336
- buffer.ensure_available?(target)
337
+ def can_refill_match?(buffer)
338
+ buffer.ensure_available?(buffer.bytesize + 1)
337
339
  end
338
340
 
339
341
  def minimum_match_bytes(pattern)
@@ -341,7 +343,7 @@ module Flexr
341
343
 
342
344
  ast = Regexp::Parser.new(pattern.source, options: pattern.options,
343
345
  encoding: pattern.encoding, unicode: true).parse
344
- minimum_ast_bytes(ast, ignorecase: pattern.options.anybits?(::Regexp::IGNORECASE))
346
+ minimum_ast_bytes(ast)
345
347
  rescue CompileError, RegexpError
346
348
  1
347
349
  end
@@ -352,20 +354,20 @@ module Flexr
352
354
  ::Regexp.new(::Regexp.escape(pattern.to_s))
353
355
  end
354
356
 
355
- def minimum_ast_bytes(node, ignorecase: false)
357
+ def minimum_ast_bytes(node)
356
358
  case node
357
359
  when Regexp::AST::Empty, Regexp::AST::Anchor, Regexp::AST::Fail then 0
358
360
  when Regexp::AST::ByteRange then 1
359
361
  when Regexp::AST::CodepointRange then utf8_length(node.lo)
360
362
  when Regexp::AST::CharClass
361
363
  ranges = node.ranges.flat_map do |range|
362
- range.first == Regexp::AST::Property ? property_ranges(range, ignorecase: ignorecase) : [range]
364
+ range.first == Regexp::AST::Property ? property_ranges(range, ignorecase: range[3] == true) : [range]
363
365
  end
364
366
  ranges = complement_codepoint_ranges(ranges) if node.negated
365
367
  ranges.map { |lo, _hi| utf8_length(lo) }.min || 1
366
- when Regexp::AST::Seq then node.children.sum { |child| minimum_ast_bytes(child, ignorecase: ignorecase) }
367
- when Regexp::AST::Alt then node.children.map { |child| minimum_ast_bytes(child, ignorecase: ignorecase) }.min || 0
368
- when Regexp::AST::Repeat then node.minimum * minimum_ast_bytes(node.child, ignorecase: ignorecase)
368
+ when Regexp::AST::Seq then node.children.sum { |child| minimum_ast_bytes(child) }
369
+ when Regexp::AST::Alt then node.children.map { |child| minimum_ast_bytes(child) }.min || 0
370
+ when Regexp::AST::Repeat then node.minimum * minimum_ast_bytes(node.child)
369
371
  else minimum_unknown_bytes(node)
370
372
  end
371
373
  end
@@ -382,24 +384,24 @@ module Flexr
382
384
  ast = Regexp::Parser.new(pattern.source, options: pattern.options,
383
385
  encoding: pattern.encoding, unicode: true).parse
384
386
  binary = !@lexer.utf8_input?
385
- first_byte_ranges(ast, pattern.options, binary: binary).any? { |lo, hi| byte.between?(lo, hi) }
387
+ first_byte_ranges(ast, binary: binary).any? { |lo, hi| byte.between?(lo, hi) }
386
388
  rescue CompileError, RegexpError
387
389
  true
388
390
  end
389
391
 
390
- def first_byte_ranges(node, options, binary: false)
392
+ def first_byte_ranges(node, binary: false)
391
393
  case node
392
394
  when Regexp::AST::Empty, Regexp::AST::Anchor, Regexp::AST::Fail then []
393
395
  when Regexp::AST::ByteRange then [[node.lo, node.hi]]
394
396
  when Regexp::AST::CodepointRange
395
- ranges = options.anybits?(::Regexp::IGNORECASE) ? Unicode::CaseFold.ranges(node.lo, node.hi) : [[node.lo, node.hi]]
397
+ ranges = [[node.lo, node.hi]]
396
398
  return ranges if binary
397
399
 
398
400
  ranges.flat_map { |lo, hi| Unicode::Utf8Splitter.split(lo, hi).map(&:first).map(&:first) }
399
401
  .map { |value| [value, value] }
400
402
  when Regexp::AST::CharClass
401
403
  ranges = node.ranges.flat_map do |range|
402
- range.first == Regexp::AST::Property ? property_ranges(range, ignorecase: options.anybits?(::Regexp::IGNORECASE)) : [range]
404
+ range.first == Regexp::AST::Property ? property_ranges(range, ignorecase: range[3] == true) : [range]
403
405
  end
404
406
  ranges = complement_codepoint_ranges(ranges) if node.negated
405
407
  return ranges if binary
@@ -409,14 +411,14 @@ module Flexr
409
411
  when Regexp::AST::Seq
410
412
  ranges = []
411
413
  node.children.each do |child|
412
- ranges.concat(first_byte_ranges(child, options, binary: binary))
414
+ ranges.concat(first_byte_ranges(child, binary: binary))
413
415
  break unless nullable?(child)
414
416
  end
415
417
  ranges
416
418
  when Regexp::AST::Alt
417
- node.children.flat_map { |child| first_byte_ranges(child, options, binary: binary) }
419
+ node.children.flat_map { |child| first_byte_ranges(child, binary: binary) }
418
420
  when Regexp::AST::Star, Regexp::AST::Repeat
419
- first_byte_ranges(node.child, options, binary: binary)
421
+ first_byte_ranges(node.child, binary: binary)
420
422
  else
421
423
  first_byte_fallback
422
424
  end
@@ -540,8 +542,8 @@ module Flexr
540
542
  @acceleration_scanner.pos = position
541
543
  @acceleration_scanner.skip(regexp)
542
544
  else
543
- match = regexp.match(segment, position)
544
- match&.begin(0) == position ? match.end(0) - position : nil
545
+ match = regexp.match(segment.byteslice(position..).to_s, 0)
546
+ match&.begin(0)&.zero? ? match[0].bytesize : nil
545
547
  end
546
548
  rescue ArgumentError
547
549
  nil
@@ -10,17 +10,18 @@ module Flexr
10
10
  @column_values = values.delete(:column_values)
11
11
  eager_columns = values.delete(:eager_columns)
12
12
  super(**values) # rubocop:disable Style/SuperArguments
13
- self.column_begin = @column_values.first if eager_columns && @column_values
14
- self.column_end = @column_values.last if eager_columns && @column_values
13
+ Struct.instance_method(:[]=).bind_call(self, :column_begin, @column_values.first) if eager_columns && @column_values
14
+ Struct.instance_method(:[]=).bind_call(self, :column_end, @column_values.last) if eager_columns && @column_values
15
15
  end
16
16
 
17
17
  def column_begin
18
- self[:column_begin] ||= @column_values&.first
18
+ self[:column_begin] || Struct.instance_method(:[]=).bind_call(self, :column_begin, @column_values&.first)
19
19
  end
20
20
 
21
21
  def column_end
22
- self[:column_end] ||= @column_values&.last
22
+ self[:column_end] || Struct.instance_method(:[]=).bind_call(self, :column_end, @column_values&.last)
23
23
  end
24
24
  end
25
+ Deprecations.record_mutations(Location)
25
26
  end
26
27
  end
@@ -3,5 +3,6 @@
3
3
  module Flexr
4
4
  module Runtime
5
5
  Token = Struct.new(:type, :value, :location, keyword_init: true)
6
+ Deprecations.record_mutations(Token)
6
7
  end
7
8
  end
data/lib/flexr/runtime.rb CHANGED
@@ -5,6 +5,7 @@ require "monitor"
5
5
  require_relative "version"
6
6
  require_relative "errors"
7
7
  require_relative "diagnostics"
8
+ require_relative "deprecations"
8
9
  require_relative "action_resolver"
9
10
  require_relative "configuration"
10
11
  require_relative "ir"
@@ -19,6 +20,7 @@ require_relative "unicode/data"
19
20
  require_relative "unicode/property"
20
21
  require_relative "unicode/reference_regexp"
21
22
  require_relative "unicode/case_fold"
23
+ require_relative "regexp/matcher"
22
24
  require_relative "automaton/types"
23
25
  require_relative "automaton/byte_class_set"
24
26
  require_relative "automaton/nfa"
@@ -38,11 +40,13 @@ require_relative "dsl"
38
40
  require_relative "lexer"
39
41
  require_relative "generated"
40
42
 
43
+ Flexr::Deprecations.warn("Ruby versions below 3.4 will not be supported in 2.0") if RUBY_VERSION < "3.4"
44
+
41
45
  module Flexr
42
46
  class << self
43
- def compile_pattern(pattern, options: {})
47
+ def compile_pattern(pattern, options: {}, encoding: nil)
44
48
  regexp = pattern.is_a?(::Regexp) ? pattern : ::Regexp.new(pattern.to_s)
45
- encoding = regexp.encoding == Encoding::BINARY ? Encoding::BINARY : Encoding::UTF_8
49
+ encoding ||= regexp.encoding == Encoding::BINARY ? Encoding::BINARY : Encoding::UTF_8
46
50
  rule = IR::Rule.new(index: 0, patterns: [regexp], action: :skip, states: [:initial])
47
51
  state = IR::State.new(name: :initial, inclusive: true, id: 0)
48
52
  spec = IR::Spec.new(
@@ -14,7 +14,7 @@ module Flexr
14
14
  end
15
15
 
16
16
  def rewrite(source, edits, insertion:, payload:)
17
- result = source.dup
17
+ result = source.b.dup
18
18
  normalized_edits = edits.map do |start_offset, end_offset, replacement|
19
19
  start_offset = line_start_offset(source, start_offset) if replacement.empty? && start_offset != insertion
20
20
  [start_offset, end_offset, replacement]
@@ -27,10 +27,10 @@ module Flexr
27
27
  replacement.bytesize - replaced_size
28
28
  end
29
29
  normalized_edits.sort_by(&:first).reverse_each do |start_offset, end_offset, replacement|
30
- result[start_offset...end_offset] = replacement
30
+ result[start_offset...end_offset] = replacement.b
31
31
  end
32
- result.insert(adjusted_insertion, payload)
33
- result
32
+ result.insert(adjusted_insertion, payload.b)
33
+ result.force_encoding(source.encoding)
34
34
  end
35
35
 
36
36
  def insert_after_preamble(source, payload)
@@ -46,26 +46,29 @@ module Flexr
46
46
  line, next_offset = next_line(source, offset)
47
47
  end
48
48
 
49
- source.dup.insert(offset, payload)
49
+ source.b.dup.insert(offset, payload.b).force_encoding(source.encoding)
50
50
  end
51
51
 
52
52
  def indentation(source, offset)
53
- line_start = source.rindex("\n", offset - 1)
54
- source[(line_start ? line_start + 1 : 0)...offset].to_s[/\A[ \t]*/].to_s
53
+ binary = source.b
54
+ line_start = binary.rindex("\n", offset - 1)
55
+ binary.byteslice((line_start ? line_start + 1 : 0)...offset).to_s[/\A[ \t]*/].to_s
55
56
  end
56
57
 
57
58
  def line_start_offset(source, offset)
58
- line_start = source.rindex("\n", offset - 1) unless offset.zero?
59
+ binary = source.b
60
+ line_start = binary.rindex("\n", offset - 1) unless offset.zero?
59
61
  line_start = line_start ? line_start + 1 : 0
60
- prefix = source.byteslice(line_start...offset)
62
+ prefix = binary.byteslice(line_start...offset)
61
63
  prefix&.match?(/\A[ \t]*\z/) ? line_start : offset
62
64
  end
63
65
 
64
66
  def next_line(source, offset)
65
67
  return [nil, offset] if offset >= source.bytesize
66
68
 
67
- ending = source.index("\n", offset)
68
- ending ? [source.byteslice(offset..ending), ending + 1] : [source.byteslice(offset..), source.bytesize]
69
+ binary = source.b
70
+ ending = binary.index("\n", offset)
71
+ ending ? [binary.byteslice(offset..ending), ending + 1] : [binary.byteslice(offset..), source.bytesize]
69
72
  end
70
73
 
71
74
  def magic_comment?(line)
@@ -35,18 +35,22 @@ module Flexr
35
35
  require "prism"
36
36
  Prism.parse(@source)
37
37
  rescue LoadError => e
38
- diagnostic = Diagnostics.error("FLEXR-E019", "Prism is required for source generation", note: e.message)
38
+ diagnostic = Diagnostics.error("FLEXR-E019", "Prism is required for source generation",
39
+ location: [0, 0], help: "install the generator dependency with gem install prism",
40
+ note: e.message)
39
41
  raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
40
42
  end
41
43
  unless prism.errors.empty?
42
44
  error = prism.errors.first
43
- diagnostic = Diagnostics.error("FLEXR-E010", error.message)
45
+ diagnostic = Diagnostics.error("FLEXR-E010", error.message,
46
+ location: [error.location.start_offset, error.location.end_offset])
44
47
  raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
45
48
  end
46
49
 
47
50
  klass, class_name = find_lexer_class(prism.value)
48
51
  raise CompileError, "no class inheriting from Flexr::Lexer found" unless klass
49
52
 
53
+ @states[:initial][:location] = [klass.location.start_offset, klass.location.end_offset]
50
54
  @lexer_scope = class_name.to_s.delete_prefix("::").split("::").reject(&:empty?)
51
55
  collect_constants(prism.value)
52
56
  collect_body(klass.body, [:initial])
@@ -64,7 +68,7 @@ module Flexr
64
68
  def find_lexer_class(node, namespace = [])
65
69
  candidates = lexer_class_candidates(node, namespace)
66
70
  dsl_candidates = candidates.select { |candidate, _name| lexer_has_dsl?(candidate.body) }
67
- unsupported_static!("multiple lexer classes require an explicit selection") if dsl_candidates.length > 1
71
+ unsupported_static!("multiple lexer classes require an explicit selection", dsl_candidates[1].first) if dsl_candidates.length > 1
68
72
 
69
73
  dsl_candidates.first || candidates.first
70
74
  end
@@ -174,7 +178,7 @@ module Flexr
174
178
  reject_unhandled_dsl!(node)
175
179
  return
176
180
  end
177
- record_deletion(node) unless %i[rule state all_states].include?(name)
181
+ record_deletion(node) unless %i[rule state all_states on_eof].include?(name)
178
182
  case name
179
183
  when :rule
180
184
  collect_rule(node, states)
@@ -187,7 +191,13 @@ module Flexr
187
191
  action = if action_source
188
192
  action_source.start_with?("do") ? "proc #{action_source}" : "proc#{action_source}"
189
193
  end
190
- @eof_rules[states.last.to_sym] = action if action
194
+ if action
195
+ state = states.last.to_sym
196
+ @eof_rules[state] = "proc { instance_exec(&self.class.__flexr_generated_eof_actions.fetch(#{state.inspect})) }"
197
+ record_eof_edit(node, state, action)
198
+ else
199
+ record_deletion(node)
200
+ end
191
201
  when :emits
192
202
  values = positional(node).map { |item| static(item) }.compact.flatten
193
203
  @config[:declared_tokens].concat(values.map(&:to_sym))
@@ -196,7 +206,7 @@ module Flexr
196
206
  when :token_kind
197
207
  @config[:token_kind] = Configuration.token_kind!(static(positional(node).first))
198
208
  when :encoding
199
- @config[:encoding] = static(positional(node).first)
209
+ @config[:encoding] = Configuration.encoding!(static(positional(node).first))
200
210
  when :option
201
211
  @config[:options] ||= {}
202
212
  positional(node).each { |item| @config[:options][Configuration.option!(static(item))] = true }
@@ -204,6 +214,9 @@ module Flexr
204
214
  @config[:options] ||= {}
205
215
  @config[:options][:accel] = Configuration.accelerator!(static(positional(node).first))
206
216
  end
217
+ rescue CompileError => e
218
+ e.diagnostic.location ||= [node.location.start_offset, node.location.end_offset] if e.diagnostic
219
+ raise
207
220
  end
208
221
 
209
222
  def collect_state(node, parent_states)
@@ -221,7 +234,7 @@ module Flexr
221
234
  existing = @states[name]
222
235
  raise ArgumentError, "state #{name.inspect} already declared with inclusive: #{existing[:inclusive]}" if
223
236
  existing && existing[:inclusive] != inclusive
224
- @states[name] ||= { inclusive: inclusive }
237
+ @states[name] ||= { inclusive: inclusive, location: [node.location.start_offset, node.location.end_offset] }
225
238
  end
226
239
  record_state_wrapper(node, block)
227
240
  active_states = parent_states == [:initial] ? names : (parent_states + names).uniq
@@ -233,7 +246,7 @@ module Flexr
233
246
  raise ArgumentError, "all_states requires a block" unless block
234
247
 
235
248
  validate_keywords!(node, [])
236
- unsupported_static!("all_states does not accept arguments") unless positional(node).empty?
249
+ unsupported_static!("all_states does not accept arguments", node) unless positional(node).empty?
237
250
  record_state_wrapper(node, block)
238
251
  collect_body(block.body, (parent_states + @states.keys).uniq)
239
252
  end
@@ -249,7 +262,7 @@ module Flexr
249
262
  options = keywords(node)
250
263
  validate_keywords!(node, %i[skip emit followed_by])
251
264
  action_source = node.block && source_slice(node.block)
252
- if action_source&.match?(/\breject\b/)
265
+ if action_source && reject_action?(node.block)
253
266
  diagnostic = Diagnostics.error(
254
267
  "FLEXR-E013", "reject is not supported by flexr",
255
268
  help: "use a state transition and less(n) to express the fallback"
@@ -278,7 +291,8 @@ module Flexr
278
291
 
279
292
  def static(node, scope: @lexer_scope)
280
293
  StaticEval.new(@source, constants: @constants, scope: scope).call(node)
281
- rescue StaticResolutionError
294
+ rescue StaticResolutionError => e
295
+ e.diagnostic.location ||= [node.location.start_offset, node.location.end_offset] if e.diagnostic && node
282
296
  raise unless @allow_dynamic
283
297
 
284
298
  nil
@@ -299,7 +313,7 @@ module Flexr
299
313
 
300
314
  def validate_keywords!(node, allowed)
301
315
  unknown = keywords(node).keys - allowed
302
- unsupported_static!("unknown keyword #{unknown.first.inspect} for #{node.name}") unless unknown.empty?
316
+ unsupported_static!("unknown keyword #{unknown.first.inspect} for #{node.name}", node) unless unknown.empty?
303
317
  end
304
318
 
305
319
  def record_deletion(node)
@@ -315,6 +329,22 @@ module Flexr
315
329
  @edits << [*span, replacement]
316
330
  end
317
331
 
332
+ def record_eof_edit(node, state, action)
333
+ span = [node.location.start_offset, node.location.end_offset]
334
+ @spans << span
335
+ @edits << [*span, "__flexr_bind_generated_eof(#{state.inspect}, #{action})"]
336
+ end
337
+
338
+ def reject_action?(block)
339
+ found = false
340
+ each_node_including_self(block.body) do |child|
341
+ next unless child.class.name.end_with?("CallNode") && child.name.to_sym == :reject
342
+
343
+ found ||= child.receiver.nil? || child.receiver.class.name.end_with?("SelfNode")
344
+ end
345
+ found
346
+ end
347
+
318
348
  def record_state_wrapper(node, block)
319
349
  body = block.body
320
350
  return record_deletion(node) unless body
@@ -334,12 +364,12 @@ module Flexr
334
364
  next unless child.class.name.end_with?("CallNode")
335
365
  if %i[send public_send].include?(child.name.to_sym)
336
366
  dynamic_name = dynamically_dispatched_dsl(child)
337
- unsupported_static!("dynamic dispatch of #{dynamic_name} is not statically supported") if dynamic_name
367
+ unsupported_static!("dynamic dispatch of #{dynamic_name} is not statically supported", child) if dynamic_name
338
368
  end
339
369
  next unless DSL_NAMES.include?(child.name.to_sym)
340
370
  next unless child.receiver.nil? || child.receiver.class.name.end_with?("SelfNode")
341
371
 
342
- unsupported_static!("#{child.name} must be a direct receiverless statement in a lexer or state body")
372
+ unsupported_static!("#{child.name} must be a direct receiverless statement in a lexer or state body", child)
343
373
  end
344
374
  end
345
375
 
@@ -351,9 +381,10 @@ module Flexr
351
381
  name if DSL_NAMES.include?(name)
352
382
  end
353
383
 
354
- def unsupported_static!(reason)
384
+ def unsupported_static!(reason, node)
355
385
  diagnostic = Diagnostics.error(
356
386
  "FLEXR-E017", "DSL structure is not statically supported",
387
+ location: [node.location.start_offset, node.location.end_offset],
357
388
  help: "move the DSL call to the lexer or state body, or use --eval", note: reason
358
389
  )
359
390
  raise StaticResolutionError.new(diagnostic.message, diagnostic: diagnostic)
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../flexr"
4
+
5
+ module Flexr
6
+ module Testing
7
+ module Snapshot
8
+ module_function
9
+
10
+ def render(tokens)
11
+ "#{JSON.pretty_generate(encode(tokens))}\n"
12
+ end
13
+
14
+ def expected(path, actual, update:)
15
+ File.binwrite(path, actual) if update
16
+ File.binread(path).force_encoding(Encoding::UTF_8)
17
+ end
18
+
19
+ def encode(value)
20
+ case value
21
+ when NilClass, TrueClass, FalseClass, Integer
22
+ value
23
+ when Float
24
+ raise ArgumentError, "unsupported snapshot value: non-finite Float" unless value.finite?
25
+
26
+ value
27
+ when String
28
+ utf8 = value.dup.force_encoding(Encoding::UTF_8)
29
+ utf8.valid_encoding? ? utf8 : { "bytes" => value.bytes }
30
+ when Symbol
31
+ { "symbol" => value.to_s }
32
+ when Array
33
+ value.map { |item| encode(item) }
34
+ when Hash
35
+ pairs = value.map { |key, item| [encode(key), encode(item)] }
36
+ { "hash" => pairs.sort_by { |key, _item| JSON.generate(key) } }
37
+ when Runtime::Token
38
+ { "token" => encode(value.to_h) }
39
+ when Runtime::Location
40
+ { "location" => encode(value.members.to_h { |name| [name, value.public_send(name)] }) }
41
+ else
42
+ raise ArgumentError, "unsupported snapshot value: #{value.class}; convert it to built-in values first"
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end