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
@@ -75,10 +75,7 @@ module Flexr
75
75
  end
76
76
 
77
77
  def next_token
78
- return nil if @halted
79
-
80
- loop do
81
- return nil if @halted
78
+ until @halted
82
79
  consume_step! if scan_steps_guarded?
83
80
 
84
81
  if eof? && @pending.nil?
@@ -143,6 +140,8 @@ module Flexr
143
140
  @pending = nil
144
141
  return token if token
145
142
  end
143
+ rescue StopIteration => e
144
+ e.result
146
145
  end
147
146
 
148
147
  def each_token
@@ -161,7 +160,9 @@ module Flexr
161
160
  self
162
161
  end
163
162
 
164
- def tokens
163
+ def tokens(channels: :default)
164
+ raise ArgumentError, "channels must be :default or :all" unless %i[default all].include?(channels)
165
+
165
166
  result = []
166
167
  while (token = next_token)
167
168
  result << token
@@ -285,6 +286,10 @@ module Flexr
285
286
  @bol
286
287
  end
287
288
 
289
+ def __flexr_beginning_of_line_at?(position, scan_start)
290
+ position == scan_start ? beginning_of_line? : @buffer.getbyte(position - 1) == 0x0a
291
+ end
292
+
288
293
  def binary_input
289
294
  source = @buffer.source
290
295
  source.encoding == ::Encoding::BINARY ? source : source.b
@@ -453,6 +458,8 @@ module Flexr
453
458
  end
454
459
 
455
460
  def update_position
461
+ return if @match_end == @match_start
462
+
456
463
  if @simple_location_input
457
464
  @column += @match_end - @match_start
458
465
  @bol = @match_end.zero?
@@ -104,7 +104,7 @@ module Flexr
104
104
  next unless acceptance
105
105
 
106
106
  rule = rules.fetch(acceptance.rule_index)
107
- next if best && cursor == best.total_end_pos && rule.index > best.rule.index
107
+ next if best && cursor == best.total_end_pos && rule.loses_priority_tie?(best.rule)
108
108
 
109
109
  best ||= (@match ||= Match.new)
110
110
  best.rule = rule
@@ -136,7 +136,7 @@ module Flexr
136
136
  next unless acceptance
137
137
 
138
138
  rule = rules.fetch(acceptance.rule_index)
139
- next if best && cursor == best.total_end_pos && rule.index > best.rule.index
139
+ next if best && cursor == best.total_end_pos && rule.loses_priority_tie?(best.rule)
140
140
 
141
141
  best ||= (@match ||= Match.new)
142
142
  best.rule = rule
@@ -249,7 +249,7 @@ module Flexr
249
249
  dfa = rule.trailing_dfa || trailing_dfa(rule.trailing)
250
250
  state = dfa.start
251
251
  cursor = position
252
- longest = 0 if trailing_accept?(dfa, state, buffer, cursor)
252
+ longest = 0 if trailing_accept?(dfa, state, buffer, cursor, position)
253
253
  while buffer.ensure_available?(cursor + 1)
254
254
  state = dfa.transition(state, buffer.getbyte(cursor))
255
255
  break unless state
@@ -258,14 +258,18 @@ module Flexr
258
258
  @lexer.consume_step!
259
259
  size = cursor - position
260
260
  @lexer.ensure_lookahead_size!(size, rule: rule)
261
- longest = size if trailing_accept?(dfa, state, buffer, cursor)
261
+ longest = size if trailing_accept?(dfa, state, buffer, cursor, position)
262
262
  end
263
263
  longest
264
264
  end
265
265
 
266
- def trailing_accept?(dfa, state, buffer, position)
266
+ def trailing_accept?(dfa, state, buffer, ending, starting)
267
267
  acceptance = dfa.accepts[state].first
268
- acceptance && (!acceptance.end_anchor || end_anchor_match?(buffer, position))
268
+ return false unless acceptance
269
+ return false if acceptance.bol_only && !@lexer.__flexr_beginning_of_line_at?(starting, @lexer.byte_pos)
270
+ return false unless @lexer.utf8_boundary?(ending)
271
+
272
+ !acceptance.end_anchor || end_anchor_match?(buffer, ending)
269
273
  end
270
274
 
271
275
  def trailing_dfa(pattern)
@@ -486,7 +490,7 @@ module Flexr
486
490
 
487
491
  total_end = cursor + (trailing_size || 0)
488
492
  next if best && total_end < best.total_end_pos
489
- next if best && total_end == best.total_end_pos && acceptance.rule_index > best.rule.index
493
+ next if best && total_end == best.total_end_pos && candidate.loses_priority_tie?(best.rule)
490
494
 
491
495
  ensure_token_size!(cursor, position, rule: candidate)
492
496
  best = @match ||= Match.new
@@ -2,12 +2,18 @@
2
2
 
3
3
  module Flexr
4
4
  module Runtime
5
+ EMPTY_TRIVIA = [].freeze
6
+
5
7
  Token = Data.define(:type, :value, :location) do
6
8
  include Record
7
9
 
8
10
  def initialize(type: nil, value: nil, location: nil)
9
11
  super
10
12
  end
13
+
14
+ def channel = :default
15
+
16
+ def leading_trivia = EMPTY_TRIVIA
11
17
  end
12
18
  end
13
19
  end
data/lib/flexr/runtime.rb CHANGED
@@ -10,6 +10,7 @@ require_relative "diagnostics"
10
10
  require_relative "action_resolver"
11
11
  require_relative "configuration"
12
12
  require_relative "ir"
13
+ require_relative "pattern"
13
14
  require_relative "unicode/version"
14
15
  require_relative "regexp/ast"
15
16
  require_relative "regexp/parser"
@@ -38,7 +39,9 @@ require_relative "runtime/buffer"
38
39
  require_relative "runtime/errors"
39
40
  require_relative "runtime/interpreter"
40
41
  require_relative "runtime/core"
42
+ require_relative "runtime/channels"
41
43
  require_relative "dsl"
44
+ require_relative "keywords"
42
45
  require_relative "lexer"
43
46
  require_relative "generated"
44
47
 
@@ -46,9 +49,9 @@ require_relative "generated"
46
49
  module Flexr
47
50
  class << self
48
51
  def compile_pattern(pattern, options: {}, encoding: nil)
49
- regexp = pattern.is_a?(::Regexp) ? pattern : ::Regexp.new(pattern.to_s)
50
- encoding ||= regexp.encoding == Encoding::BINARY ? Encoding::BINARY : Encoding::UTF_8
51
- rule = IR::Rule.new(index: 0, patterns: [regexp], action: :skip, states: [:initial])
52
+ pattern = ::Regexp.new(pattern.to_s) unless pattern.is_a?(::Regexp) || pattern.is_a?(Pattern)
53
+ encoding ||= pattern.is_a?(::Regexp) && pattern.encoding == Encoding::BINARY ? Encoding::BINARY : Encoding::UTF_8
54
+ rule = IR::Rule.new(index: 0, patterns: [pattern], action: :skip, states: [:initial])
52
55
  state = IR::State.new(name: :initial, inclusive: true, id: 0)
53
56
  spec = IR::Spec.new(
54
57
  class_name: "Pattern", backend: :table, token_kind: :array,
@@ -4,16 +4,16 @@ module Flexr
4
4
  module Source
5
5
  RuleDefinition = Struct.new(
6
6
  :index, :patterns, :trailing, :action_source, :action, :states, :bol_only, :end_anchor,
7
- :pattern_conditions, :bind_action, :reads_locals,
7
+ :pattern_conditions, :bind_action, :reads_locals, :channel, :dynamic_channel, :priority, :emit_shorthand,
8
8
  :span, keyword_init: true
9
9
  )
10
10
  SpecSource = Struct.new(
11
11
  :source, :path, :class_name, :rules, :config, :dsl_spans, :first_dsl_offset, :constants,
12
- :states, :flexr_require_spans, :dsl_edits, keyword_init: true
12
+ :states, :flexr_require_spans, :dsl_edits, :uses_patterns, keyword_init: true
13
13
  )
14
14
 
15
15
  class PrismReader
16
- DSL_NAMES = %i[rule state all_states on_eof emits backend token_kind encoding option accel].freeze
16
+ DSL_NAMES = %i[rule state all_states on_eof emits keywords backend token_kind encoding option accel].freeze
17
17
 
18
18
  def initialize(source, path: nil)
19
19
  @source = source
@@ -57,10 +57,14 @@ module Flexr
57
57
  require_spans = flexr_require_spans(prism.value)
58
58
  first_dsl_offset = @spans.map(&:first).min || class_body_offset(klass)
59
59
  @config[:eof_rules] = @eof_rules
60
+ uses_patterns = false
61
+ each_node(prism.value) do |node|
62
+ uses_patterns ||= node.is_a?(::Prism::CallNode) && %i[pattern upto].include?(node.name)
63
+ end
60
64
  SpecSource.new(source: @source, path: @path, class_name: class_name, rules: @rules,
61
65
  config: @config, dsl_spans: @spans.uniq(&:first),
62
66
  first_dsl_offset: first_dsl_offset, constants: @constants, states: @states,
63
- flexr_require_spans: require_spans, dsl_edits: @edits)
67
+ flexr_require_spans: require_spans, dsl_edits: @edits, uses_patterns: uses_patterns)
64
68
  end
65
69
 
66
70
  private
@@ -201,6 +205,8 @@ module Flexr
201
205
  when :emits
202
206
  values = positional(node).map { |item| static(item) }.compact.flatten
203
207
  @config[:declared_tokens].concat(values.map(&:to_sym))
208
+ when :keywords
209
+ collect_keywords(node)
204
210
  when :backend
205
211
  @config[:backend] = Configuration.backend!(static(positional(node).first))
206
212
  when :token_kind
@@ -219,6 +225,19 @@ module Flexr
219
225
  raise
220
226
  end
221
227
 
228
+ def collect_keywords(node)
229
+ validate_keywords!(node, %i[among])
230
+ args = positional(node)
231
+ among = keyword(node, :among)
232
+ location = [node.location.start_offset, node.location.end_offset]
233
+ Keywords.error!("keywords requires words and among:", location: location) unless args.one? && among && !node.block
234
+ words = static(args.first)
235
+ type = static(among)
236
+ return if @allow_dynamic && (words.nil? || type.nil?)
237
+
238
+ Keywords.add!(@config[:options] ||= {}, @config[:declared_tokens], words, among: type, location: location)
239
+ end
240
+
222
241
  def collect_state(node, parent_states)
223
242
  block = node.block
224
243
  raise ArgumentError, "state requires a block" unless block
@@ -255,12 +274,12 @@ module Flexr
255
274
  values = positional(node)
256
275
  patterns = static(values.first, scope: @lexer_scope)
257
276
  patterns = [patterns] unless patterns.is_a?(Array)
258
- unless (@allow_dynamic && patterns.any?(&:nil?)) || patterns.all? { |pattern| pattern.is_a?(::Regexp) || pattern.is_a?(String) }
259
- diagnostic = Diagnostics.error("FLEXR-E018", "rule pattern must be a Regexp, String, or Array")
277
+ unless (@allow_dynamic && patterns.any?(&:nil?)) || patterns.all? { |pattern| pattern.is_a?(::Regexp) || pattern.is_a?(String) || pattern.is_a?(Pattern) }
278
+ diagnostic = Diagnostics.error("FLEXR-E018", "rule pattern must be a Regexp, String, Pattern, or Array")
260
279
  raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
261
280
  end
262
281
  options = keywords(node)
263
- validate_keywords!(node, %i[skip emit followed_by])
282
+ validate_keywords!(node, %i[skip emit followed_by channel priority])
264
283
  action_source = node.block && source_slice(node.block)
265
284
  if action_source && reject_action?(node.block)
266
285
  diagnostic = Diagnostics.error(
@@ -274,8 +293,15 @@ module Flexr
274
293
  end
275
294
  skip = options.key?(:skip) ? static(options[:skip], scope: @lexer_scope) : false
276
295
  emit = options.key?(:emit) ? static(options[:emit], scope: @lexer_scope) : nil
296
+ priority = options.key?(:priority) ? static(options[:priority], scope: @lexer_scope) : 0
297
+ Configuration.rule_priority!(priority) unless @allow_dynamic && priority.nil?
298
+ channel = options.key?(:channel) ? static(options[:channel], scope: @lexer_scope) : :default
299
+ dynamic_channel = @allow_dynamic && channel.nil?
300
+ channel = dynamic_channel ? :default : Configuration.rule_channel!(channel)
301
+ skip ||= channel == :skip
302
+ channel = nil if skip || channel == :default
277
303
  action = ActionResolver.resolve(
278
- skip: skip, emit: emit, block: block_action, default: "proc { emit(nil, text) }"
304
+ skip: skip, emit: emit, block: block_action, default: channel ? [:emit, channel] : "proc { emit(nil, text) }"
279
305
  )
280
306
  bind_action = !block_action.nil? && action.equal?(block_action)
281
307
  reads_locals = false
@@ -289,12 +315,28 @@ module Flexr
289
315
  @rules << RuleDefinition.new(
290
316
  index: rule_index, patterns: patterns,
291
317
  trailing: options[:followed_by] && static(options[:followed_by], scope: @lexer_scope),
292
- action_source: action_source, action: action, states: states.dup,
293
- bol_only: false, end_anchor: nil,
318
+ action_source: action_source, action: action, states: states.dup, channel: channel, dynamic_channel: dynamic_channel,
319
+ bol_only: false, end_anchor: nil, priority: priority, emit_shorthand: bind_action && emit_shorthand(node.block),
294
320
  span: [node.location.start_offset, node.location.end_offset], bind_action: bind_action, reads_locals: reads_locals
295
321
  )
296
322
  end
297
323
 
324
+ def emit_shorthand(block)
325
+ return if block.parameters || !block.body.is_a?(Prism::StatementsNode) || !block.body.body.one?
326
+
327
+ call = block.body.body.first
328
+ return unless call.is_a?(Prism::CallNode) && call.name == :emit && call.receiver.nil? && call.block.nil?
329
+
330
+ arguments = Array(call.arguments&.arguments)
331
+ return unless (1..2).cover?(arguments.length) && arguments.first.is_a?(Prism::SymbolNode)
332
+
333
+ value = arguments[1]
334
+ return unless value.nil? || (value.is_a?(Prism::CallNode) && value.name == :text &&
335
+ value.receiver.nil? && value.arguments.nil? && value.block.nil?)
336
+
337
+ arguments.first.value.to_sym
338
+ end
339
+
298
340
  def static(node, scope: @lexer_scope)
299
341
  StaticEval.new(@source, constants: @constants, scope: scope).call(node)
300
342
  rescue StaticResolutionError => e
@@ -102,6 +102,7 @@ module Flexr
102
102
 
103
103
  candidates.uniq.each do |candidate|
104
104
  value = constant_value(candidate)
105
+ return value.__flexr_named(parts.join("::")) if value.is_a?(Pattern)
105
106
  return value unless value.equal?(MISSING)
106
107
  end
107
108
 
@@ -127,8 +128,26 @@ module Flexr
127
128
  end
128
129
 
129
130
  def evaluate_call(node)
131
+ if !node.block && %i[pattern upto].include?(node.name) && node.receiver.nil?
132
+ arguments = Array(node.arguments&.arguments)
133
+ return Pattern.build(*arguments.map { |argument| evaluate(argument) }) if node.name == :pattern
134
+ return Pattern.upto(evaluate(arguments.first)) if arguments.one? && !arguments.first.is_a?(::Prism::SplatNode)
135
+ end
136
+ if !node.block && node.receiver && %i[| + & - !].include?(node.name)
137
+ value = evaluate(node.receiver)
138
+ arguments = Array(node.arguments&.arguments)
139
+ if value.is_a?(Pattern) && arguments.size == (node.name == :! ? 0 : 1) &&
140
+ arguments.none?(::Prism::SplatNode)
141
+ return value.public_send(node.name, *arguments.map { |argument| evaluate(argument) })
142
+ end
143
+ end
130
144
  return evaluate(node.receiver).freeze if node.receiver && node.name == :freeze
131
145
  return ::Regexp.union(positional_arguments(node).map { |argument| evaluate(argument) }) if node.receiver && node.name == :union && constant_name(node.receiver) == "Regexp"
146
+ if node.receiver && node.name == :new && source_slice(node.receiver) == "::Regexp"
147
+ arguments = Array(node.arguments&.arguments)
148
+ return ::Regexp.new(arguments.first.unescaped) if !node.block && arguments.one? && arguments.first.is_a?(::Prism::StringNode)
149
+ end
150
+
132
151
  raise_resolution("method call #{node.name} is not statically supported")
133
152
  end
134
153
 
data/lib/flexr/trace.rb CHANGED
@@ -50,22 +50,25 @@ module Flexr
50
50
  state = @lexer.state
51
51
  candidates = candidates_at(start)
52
52
  selected = candidates.find { |candidate| candidate[:rule] == rule.index }
53
+ ties = selected ? candidates.select { |candidate| candidate[:total_length] == selected[:total_length] } : []
53
54
  reason = if @config.backend == :firstmatch
54
55
  "first_match"
55
56
  elsif candidates.length == 1
56
57
  "only_match"
57
- elsif selected && candidates.count { |candidate| candidate[:total_length] == selected[:total_length] } > 1
58
- "rule_order"
58
+ elsif ties.length > 1
59
+ ties.count { |candidate| candidate.fetch(:priority, 0) == rule.priority } > 1 ? "rule_order" : "priority"
59
60
  else
60
61
  "longest"
61
62
  end
62
63
  yield
63
64
  pending = @lexer.instance_variable_get(:@pending)
64
65
  bytes = @lexer.buffer.byteslice(start...ending)
65
- @steps << { byte_begin: start, byte_end: ending, next_byte: @lexer.byte_pos, state: state, next_state: @lexer.state,
66
- text: display_text(bytes), bytes: bytes.bytes, candidates: candidates,
67
- rule: rule.index, patterns: rule.patterns.map(&:inspect), reason: reason,
68
- action: pending ? "emit" : "skip", token: pending&.inspect }
66
+ step = { byte_begin: start, byte_end: ending, next_byte: @lexer.byte_pos, state: state, next_state: @lexer.state,
67
+ text: display_text(bytes), bytes: bytes.bytes, candidates: candidates,
68
+ rule: rule.index, patterns: rule.patterns.map(&:inspect), reason: reason,
69
+ action: pending ? "emit" : "skip", token: pending&.inspect }
70
+ step[:channel] = rule.channel if rule.channel
71
+ @steps << step
69
72
  end
70
73
 
71
74
  def record_eof
@@ -96,6 +99,7 @@ module Flexr
96
99
  "rule #{candidate[:rule]}(#{candidate[:length]}/#{candidate[:total_length]})"
97
100
  end.join(" ")
98
101
  target = step[:rule] ? "rule #{step[:rule]}" : step[:reason]
102
+ target += " channel=#{step[:channel].inspect}" if step[:channel]
99
103
  "@#{step[:byte_begin]} #{step[:text].inspect} state=#{step[:state]} " \
100
104
  "candidates: #{candidates} -> #{target} #{step[:action]} (#{step[:reason]}) " \
101
105
  "state=#{step[:next_state]}#{step[:token] && " #{step[:token]}"}"
@@ -112,8 +116,6 @@ module Flexr
112
116
  dfa = @compiled.machines.fetch(@lexer.state).dfa
113
117
  best = {}
114
118
  walk(dfa, start) do |acceptance, ending|
115
- next if acceptance.bol_only && !@lexer.beginning_of_line?
116
-
117
119
  rule = @rules.fetch(acceptance.rule_index)
118
120
  candidate = candidate_for(rule, start, ending)
119
121
  next unless candidate
@@ -159,23 +161,27 @@ module Flexr
159
161
  rule.trailing, encoding: @config.encoding, options: { unicode: @config.options[:unicode] == true }
160
162
  )
161
163
  longest = nil
162
- walk(dfa, ending) { |_acceptance, cursor| longest = cursor - ending }
164
+ walk(dfa, ending, scan_start: start) { |_acceptance, cursor| longest = cursor - ending }
163
165
  longest
164
166
  else
165
167
  0
166
168
  end
167
169
  return if trailing.nil?
168
170
 
169
- { rule: rule.index, patterns: rule.patterns.map(&:inspect), length: ending - start,
170
- trailing_length: trailing, total_length: ending - start + trailing }
171
+ candidate = { rule: rule.index, patterns: rule.patterns.map(&:inspect), length: ending - start,
172
+ trailing_length: trailing, total_length: ending - start + trailing }
173
+ candidate[:priority] = rule.priority unless rule.priority.zero?
174
+ candidate
171
175
  end
172
176
 
173
- def walk(dfa, start)
177
+ def walk(dfa, start, scan_start: start)
174
178
  state = dfa.start
175
179
  cursor = start
176
180
  loop do
177
181
  if @lexer.utf8_boundary?(cursor)
178
182
  dfa.accepts[state].each do |acceptance|
183
+ next if acceptance.bol_only && !@lexer.__flexr_beginning_of_line_at?(start, scan_start)
184
+
179
185
  yield acceptance, cursor unless acceptance.end_anchor && !end_anchor?(cursor)
180
186
  end
181
187
  end
data/lib/flexr/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Flexr
4
- VERSION = "2.0.0"
4
+ VERSION = "2.1.0"
5
5
  end
@@ -11,8 +11,10 @@ module RubyLsp
11
11
  def diagnostics(source)
12
12
  return @diagnostics if @source == source
13
13
 
14
+ @channels = {}
14
15
  diagnostics = begin
15
16
  parsed = ::Flexr::Source::PrismReader.new(source).read
17
+ parsed.rules.each { |rule| @channels[rule.span.first] = rule.channel if rule.channel }
16
18
  compiled = ::Flexr::CLI.compile(parsed, overrides: { warn_level: :all })
17
19
  compiled.diagnostics.reject { |diagnostic| diagnostic.code == "FLEXR-W016" }
18
20
  rescue ::Flexr::Error => e
@@ -24,6 +26,10 @@ module RubyLsp
24
26
  @diagnostics = diagnostics
25
27
  end
26
28
 
29
+ def channel_at(offset)
30
+ @channels[offset]
31
+ end
32
+
27
33
  def message(diagnostic)
28
34
  [diagnostic.message, diagnostic.note,
29
35
  ("help: #{diagnostic.help}" if diagnostic.help)].compact.join("\n\n")
@@ -74,17 +80,37 @@ module RubyLsp
74
80
  end
75
81
 
76
82
  def on_call_node_enter(node)
77
- return unless node.name == :rule && node.receiver.nil?
83
+ return unless %i[rule keywords].include?(node.name) && node.receiver.nil?
78
84
 
79
85
  source = node.location.source_lines.join
80
86
  diagnostics = @analysis.diagnostics(source).select do |diagnostic|
81
87
  diagnostic.location &&
82
88
  (node.location.start_offset...node.location.end_offset).cover?(diagnostic.location.first)
83
89
  end
84
- return if diagnostics.empty?
85
-
86
90
  text = diagnostics.map { |diagnostic| "#{diagnostic.code}: #{@analysis.message(diagnostic)}" }.join("\n\n")
87
- @builder.push("```text\n#{text}\n```", category: :documentation)
91
+ sections = []
92
+ sections << "Keyword table. Exact spellings select a token type after a matching emit: rule wins." if node.name == :keywords
93
+ channel = @analysis.channel_at(node.location.start_offset)
94
+ if channel
95
+ sections << "Channel `#{channel.inspect}` preserves trivia. " \
96
+ "Read it with `tokens(channels: :all)` or `leading_trivia` on structured tokens."
97
+ end
98
+ hint = priority_hint(node) if node.name == :rule
99
+ sections << hint if hint
100
+ sections << "```text\n#{text}\n```" unless text.empty?
101
+ @builder.push(sections.join("\n\n"), category: :documentation) unless sections.empty?
102
+ end
103
+
104
+ private
105
+
106
+ def priority_hint(node)
107
+ keywords = Array(node.arguments&.arguments).grep(Prism::KeywordHashNode).flat_map(&:elements)
108
+ pair = keywords.grep(Prism::AssocNode).find do |option|
109
+ option.key.is_a?(Prism::SymbolNode) && option.key.value == "priority"
110
+ end
111
+ return unless pair&.value.is_a?(Prism::IntegerNode)
112
+
113
+ "priority #{pair.value.value} breaks equal-length matches. Higher priority wins, then source order."
88
114
  end
89
115
  end
90
116
 
data/sig/flexr.rbs CHANGED
@@ -1,7 +1,8 @@
1
1
  module Flexr
2
2
  VERSION: String
3
3
 
4
- type pattern = String | ::Regexp
4
+ type pattern = String | ::Regexp | Pattern
5
+ type pattern_operand = pattern | Array[pattern_operand]
5
6
  type token = [untyped, untyped] | Runtime::Token
6
7
  type source_location = [Integer, Integer]
7
8
  type cancellation = (^() -> untyped) | (^(Lexer) -> untyped) | _Cancellation | _ContextCancellation
@@ -29,14 +30,25 @@ module Flexr
29
30
  end
30
31
 
31
32
  def self.compile_pattern: (pattern, ?options: Hash[Symbol, untyped], ?encoding: Encoding?) -> _CompiledPattern
32
- def self.parse_pattern: (pattern, ?options: Hash[Symbol, untyped]) -> untyped
33
+ def self.parse_pattern: ((String | ::Regexp), ?options: Hash[Symbol, untyped]) -> untyped
34
+
35
+ class Pattern
36
+ def |: (pattern_operand) -> Pattern
37
+ def +: (pattern_operand) -> Pattern
38
+ def &: (pattern_operand) -> Pattern
39
+ def -: (pattern_operand) -> Pattern
40
+ def !: () -> Pattern
41
+ end
33
42
 
34
43
  module DSL
35
- def rule: (pattern | Array[pattern], ?skip: bool, ?emit: untyped, ?followed_by: pattern?) ?{ () [self: Lexer] -> untyped } -> nil
44
+ def rule: (pattern | Array[pattern], ?skip: bool, ?emit: untyped, ?followed_by: pattern?, ?channel: Symbol, ?priority: Integer) ?{ () [self: Lexer] -> untyped } -> nil
45
+ def pattern: (*pattern_operand) -> Pattern
46
+ def upto: (pattern_operand) -> Pattern
36
47
  def state: (*(Symbol | String), ?inclusive: bool) { () [self: singleton(Lexer)] -> untyped } -> void
37
48
  def all_states: () { () [self: singleton(Lexer)] -> untyped } -> void
38
49
  def on_eof: () { () [self: Lexer] -> untyped } -> void
39
50
  def emits: (*untyped) -> void
51
+ def keywords: (Array[String] | Hash[String, Symbol], among: Symbol) -> nil
40
52
  def backend: (:table | :direct | :auto | :firstmatch | String) -> void
41
53
  def token_kind: (:array | :struct | :yield | String) -> void
42
54
  def encoding: (Encoding | String) -> void
@@ -49,7 +61,7 @@ module Flexr
49
61
 
50
62
  def initialize: (String | _Input, ?filename: String?, ?error_mode: Symbol, ?max_token_size: Integer, ?max_lookahead_size: Integer?, ?max_buffer_size: Integer, ?max_state_stack: Integer, ?max_steps: Integer?, ?cancellation: cancellation?, ?retain_input: bool, ?chunk_size: Integer) -> void
51
63
  def next_token: () -> token?
52
- def tokens: () -> Array[token]
64
+ def tokens: (?channels: (:default | :all)) -> Array[token]
53
65
  def each_token: () -> Enumerator[token, self]
54
66
  | () { (untyped, ?untyped) -> untyped } -> self
55
67
  def racc_next_token: () -> [untyped, untyped]
@@ -90,6 +102,8 @@ module Flexr
90
102
  attr_reader type: untyped
91
103
  attr_reader value: untyped
92
104
  attr_reader location: Location?
105
+ def channel: () -> Symbol
106
+ def leading_trivia: () -> Array[Token]
93
107
  def []: (:location | "location") -> Location?
94
108
  | (Integer | Symbol | String) -> untyped
95
109
  def with: (?type: untyped, ?value: untyped, ?location: Location?) -> self
data/site/README.md CHANGED
@@ -3,6 +3,22 @@
3
3
  This directory contains the Astro/Starlight product site for flexr. The Playground
4
4
  runs real Ruby and flexr locally through a pinned ruby.wasm runtime.
5
5
 
6
+ ## Documentation versions
7
+
8
+ The existing documentation URLs describe `main`. The version links on each
9
+ page switch to the same topic under `/flexr/stable/` when that topic exists in
10
+ the release. If a topic is available in only one version, the link opens
11
+ Getting started in the other version.
12
+
13
+ `pnpm dev` and `pnpm build` copy the pinned release's Markdown from Git into
14
+ the ignored `src/content/docs/stable/` directory. Fetch the release tag with
15
+ `git fetch --tags` if it is missing from your clone. GitHub Pages also uses
16
+ that tag's Ruby library and example presets for the public Playground.
17
+
18
+ After a new stable gem is public on RubyGems and its Git tag is available,
19
+ update `stableReleaseTag` in `scripts/stable-release.mjs`. Run
20
+ `FLEXR_PLAYGROUND_STABLE=1 pnpm build` to reproduce the deployment build.
21
+
6
22
  ## Local development
7
23
 
8
24
  ```sh
@@ -1,5 +1,6 @@
1
1
  import { defineConfig, passthroughImageService } from 'astro/config';
2
2
  import starlight from '@astrojs/starlight';
3
+ import { stableReleaseTag } from './scripts/stable-release.mjs';
3
4
 
4
5
  export default defineConfig({
5
6
  site: 'https://ydah.github.io',
@@ -11,6 +12,8 @@ export default defineConfig({
11
12
  title: 'flexr',
12
13
  description: 'A Ruby-native lexer generator for parser authors.',
13
14
  customCss: ['./src/styles/custom.css'],
15
+ components: { PageTitle: './src/components/DocsTitle.astro' },
16
+ routeMiddleware: './src/docs-navigation.ts',
14
17
  sidebar: [
15
18
  {
16
19
  label: 'Learn',
@@ -49,6 +52,11 @@ export default defineConfig({
49
52
  { label: 'Examples', slug: 'examples' },
50
53
  { label: 'Benchmarks', slug: 'benchmarks' }
51
54
  ]
55
+ },
56
+ {
57
+ label: `Stable ${stableReleaseTag}`,
58
+ autogenerate: { directory: 'stable' },
59
+ collapsed: true
52
60
  }
53
61
  ],
54
62
  social: [
data/site/package.json CHANGED
@@ -3,9 +3,10 @@
3
3
  "private": true,
4
4
  "type": "module",
5
5
  "scripts": {
6
+ "prepare:docs": "node scripts/prepare-docs.mjs",
6
7
  "prepare:playground": "node scripts/prepare-playground.mjs",
7
- "dev": "pnpm prepare:playground && astro dev",
8
- "build": "pnpm prepare:playground && astro check && astro build",
8
+ "dev": "pnpm prepare:docs && pnpm prepare:playground && astro dev",
9
+ "build": "pnpm prepare:docs && pnpm prepare:playground && astro check && astro build",
9
10
  "preview": "astro preview",
10
11
  "verify": "node scripts/verify-site.mjs",
11
12
  "test": "pnpm prepare:playground && node --test tests/*.test.mjs",
@@ -35,6 +35,11 @@ module FlexrPlayground
35
35
  max_lookahead_size: 65_536, max_buffer_size: 1_048_576)
36
36
  trace = Flexr::Trace.new(lexer)
37
37
  tokens = trace.run
38
+ if klass.__flexr_config.token_kind == :struct && klass.__flexr_rules.any? { |rule| rule.respond_to?(:channel) && rule.channel }
39
+ tokens = tokens.map do |token|
40
+ token_fields(token).merge(leading_trivia: token.leading_trivia.map { |trivia| token_fields(trivia) })
41
+ end
42
+ end
38
43
  dot = StringIO.new
39
44
  Flexr::CLI.print_dot(path, options, dot)
40
45
  JSON.generate(tokens: tokens, steps: trace.steps, diagnostics: diagnostics.string,
@@ -54,4 +59,8 @@ module FlexrPlayground
54
59
  $stdout = stdout
55
60
  $stderr = stderr
56
61
  end
62
+
63
+ def token_fields(token)
64
+ token.to_h.merge(channel: token.channel, location: token.location&.to_h)
65
+ end
57
66
  end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Lexer < Flexr::Lexer
4
+ rule(%r{/\*(?~\*/)\*/}, skip: true)
5
+ rule(/[ \t\r\n]+/, skip: true)
6
+ rule(/[a-z][a-z0-9_]*/, emit: :IDENT)
7
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Lexer < Flexr::Lexer
4
+ IDENTIFIER = pattern(/[a-z_][a-z0-9_]*/)
5
+
6
+ rule(/[ \t\n]+/, skip: true)
7
+ rule(IDENTIFIER, emit: :IDENT)
8
+ keywords %w[if else end], among: :IDENT
9
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Lexer < Flexr::Lexer
4
+ IDENT = pattern(/[a-z]+/)
5
+ KEYWORD = pattern("if", "end")
6
+
7
+ rule(/[ \t\n]+/, skip: true)
8
+ rule(IDENT - KEYWORD, emit: :IDENT)
9
+ rule(KEYWORD, emit: :KEYWORD)
10
+ rule(pattern("[[") + upto("aba"), emit: :BLOCK)
11
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Lexer < Flexr::Lexer
4
+ rule(/[ \t\n]+/, skip: true)
5
+ rule(/[a-z]+/, emit: :IDENT)
6
+ rule("if", emit: :IF, priority: 10)
7
+ end