flexr 2.1.0 → 2.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 (124) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/README.md +4 -0
  4. data/benchmark/dfa_stretch.rb +149 -0
  5. data/benchmark/lrama_lexer.rb +79 -96
  6. data/benchmark/regexp_parser_corpus.rb +35 -0
  7. data/benchmark/regexp_parser_parity.rb +89 -0
  8. data/benchmark/regexp_parser_scanner.rb +159 -0
  9. data/docs/README.md +4 -1
  10. data/docs/adr/0021-ruby-34-minimum.md +23 -0
  11. data/docs/adr/0022-immutable-tokens-and-locations.md +22 -0
  12. data/docs/adr/0023-stable-explicit-firstmatch.md +21 -0
  13. data/docs/adr/0024-opt-in-ractor-sharing.md +24 -0
  14. data/docs/adr/0025-explicit-whole-token-acceleration.md +26 -0
  15. data/docs/adr/0026-retain-direct-dispatch.md +22 -0
  16. data/docs/adr/0033-action-free-recognition.md +33 -0
  17. data/docs/adr/0034-lexer-checkpoints.md +25 -0
  18. data/docs/adr/0035-parser-token-expectations.md +27 -0
  19. data/docs/adr/0038-replay-named-regexp-captures.md +23 -0
  20. data/docs/adr/0039-input-stack.md +25 -0
  21. data/docs/adr/0040-runtime-delimiters.md +23 -0
  22. data/docs/adr/0041-post-lexical-indentation.md +24 -0
  23. data/docs/adr/0042-capture-delegation.md +23 -0
  24. data/docs/adr/0043-expand-reusable-rules-explicitly.md +27 -0
  25. data/docs/adr/0044-import-oedipus-firstmatch.md +26 -0
  26. data/docs/assets/playground-absence-and-diagnostics.gif +0 -0
  27. data/docs/explanation/backends.md +5 -4
  28. data/docs/how-to/integrate-with-lrama.md +9 -8
  29. data/docs/how-to/integrate-with-racc.md +9 -0
  30. data/docs/how-to/migrate-from-oedipus-lex.md +43 -0
  31. data/docs/how-to/parser-driven-lexing.md +48 -0
  32. data/docs/how-to/try-playground-demos.md +13 -0
  33. data/docs/internals/regexp-parser-experiment.md +67 -0
  34. data/docs/perf-log.md +120 -8
  35. data/docs/reference/README.md +1 -1
  36. data/docs/reference/actions.md +106 -0
  37. data/docs/reference/cli.md +75 -4
  38. data/docs/reference/diagnostics.md +3 -9
  39. data/docs/reference/dsl.md +66 -3
  40. data/docs/reference/public-api.md +8 -1
  41. data/docs/reference/regexp.md +27 -4
  42. data/docs/reference/ruby-lsp.md +15 -0
  43. data/docs/reference/runtime.md +163 -2
  44. data/docs/tutorial/build-a-calculator-parser.md +47 -0
  45. data/examples/with_lrama/README.md +3 -3
  46. data/lib/flexr/automaton/accel.rb +1 -0
  47. data/lib/flexr/automaton/compiler.rb +15 -0
  48. data/lib/flexr/automaton/dfa.rb +0 -33
  49. data/lib/flexr/automaton/keyword_tables.rb +14 -8
  50. data/lib/flexr/automaton/reference_dfa.rb +38 -0
  51. data/lib/flexr/cli.rb +118 -18
  52. data/lib/flexr/codegen/table.rb +7 -0
  53. data/lib/flexr/configuration.rb +18 -1
  54. data/lib/flexr/dsl.rb +14 -3
  55. data/lib/flexr/generated.rb +4 -0
  56. data/lib/flexr/generator.rb +39 -7
  57. data/lib/flexr/importer/oedipus_lex.rb +229 -0
  58. data/lib/flexr/importer.rb +7 -2
  59. data/lib/flexr/ir.rb +1 -1
  60. data/lib/flexr/options.rb +3 -0
  61. data/lib/flexr/project_template.rb +46 -0
  62. data/lib/flexr/project_templates/common/.gitignore +1 -0
  63. data/lib/flexr/project_templates/common/lexer.flexr.rb +12 -0
  64. data/lib/flexr/project_templates/common/test_calculator.rb +15 -0
  65. data/lib/flexr/project_templates/lrama/Gemfile +9 -0
  66. data/lib/flexr/project_templates/lrama/README.md +17 -0
  67. data/lib/flexr/project_templates/lrama/Rakefile +18 -0
  68. data/lib/flexr/project_templates/lrama/calculator.rb +28 -0
  69. data/lib/flexr/project_templates/lrama/parser.y +72 -0
  70. data/lib/flexr/project_templates/racc/Gemfile +8 -0
  71. data/lib/flexr/project_templates/racc/README.md +15 -0
  72. data/lib/flexr/project_templates/racc/Rakefile +14 -0
  73. data/lib/flexr/project_templates/racc/calculator.rb +22 -0
  74. data/lib/flexr/project_templates/racc/parser.y +19 -0
  75. data/lib/flexr/regexp/ast.rb +2 -0
  76. data/lib/flexr/regexp/parser.rb +13 -11
  77. data/lib/flexr/regexp/tokenizer.rb +2 -2
  78. data/lib/flexr/rules.rb +53 -0
  79. data/lib/flexr/runtime/buffer.rb +1 -1
  80. data/lib/flexr/runtime/captures.rb +46 -0
  81. data/lib/flexr/runtime/channels.rb +2 -1
  82. data/lib/flexr/runtime/checkpoint.rb +116 -0
  83. data/lib/flexr/runtime/core.rb +55 -43
  84. data/lib/flexr/runtime/delegation.rb +123 -0
  85. data/lib/flexr/runtime/delimiters.rb +89 -0
  86. data/lib/flexr/runtime/firstmatch.rb +266 -0
  87. data/lib/flexr/runtime/indentation.rb +235 -0
  88. data/lib/flexr/runtime/input_stack.rb +48 -0
  89. data/lib/flexr/runtime/interpreter.rb +36 -314
  90. data/lib/flexr/runtime/recognizer.rb +106 -0
  91. data/lib/flexr/runtime.rb +10 -0
  92. data/lib/flexr/skeleton/verification.rb +103 -0
  93. data/lib/flexr/skeleton.rb +208 -0
  94. data/lib/flexr/source/fixes.rb +145 -0
  95. data/lib/flexr/source/prism_reader.rb +187 -25
  96. data/lib/flexr/testing.rb +5 -2
  97. data/lib/flexr/unicode/reference_regexp.rb +29 -11
  98. data/lib/flexr/version.rb +1 -1
  99. data/lib/ruby_lsp/flexr/addon.rb +88 -13
  100. data/lib/ruby_lsp/flexr/navigation.rb +231 -0
  101. data/lib/ruby_lsp/flexr/ranges.rb +40 -0
  102. data/sig/flexr.rbs +33 -3
  103. data/site/README.md +22 -7
  104. data/site/ruby/presets/heredoc.flexr.rb +15 -0
  105. data/site/ruby/presets/html_javascript.rb +12 -0
  106. data/site/ruby/presets/html_js.flexr.rb +14 -0
  107. data/site/ruby/presets/indentation.flexr.rb +14 -0
  108. data/site/scripts/prepare-playground.mjs +16 -6
  109. data/site/scripts/stable-release.mjs +4 -1
  110. data/site/src/content/docs/learn/parser-integration.md +23 -8
  111. data/site/src/content/docs/reference/cli.md +3 -0
  112. data/site/src/content/docs/reference/dsl.md +1 -0
  113. data/site/src/content/docs/reference/runtime.md +26 -0
  114. data/site/src/pages/playground.astro +15 -1
  115. data/site/src/playground/client.js +30 -1
  116. data/site/src/playground/issue.mjs +19 -0
  117. data/site/src/playground/runtime.mjs +4 -3
  118. data/site/src/playground/worker.mjs +1 -1
  119. data/site/tests/browser/playground.spec.mjs +64 -0
  120. data/site/tests/playground-issue.test.mjs +15 -0
  121. data/site/tests/playground-release.test.mjs +62 -11
  122. data/site/tests/playground-runtime.test.mjs +48 -0
  123. data/test/ruby_lsp_addon_spec.rb +174 -0
  124. metadata +63 -1
@@ -4,22 +4,25 @@ 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, :channel, :dynamic_channel, :priority, :emit_shorthand,
7
+ :pattern_conditions, :bind_action, :reads_locals, :channel, :dynamic_channel, :priority, :emit_shorthand, :emits,
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, :uses_patterns, keyword_init: true
12
+ :states, :flexr_require_spans, :dsl_edits, :uses_patterns, :uses_rule_sets, :uses_input_stack, :uses_delegation,
13
+ :uses_dynamic_delimiters, keyword_init: true
13
14
  )
14
15
 
15
16
  class PrismReader
16
- DSL_NAMES = %i[rule state all_states on_eof emits keywords backend token_kind encoding option accel].freeze
17
+ DSL_NAMES = %i[rule use state all_states on_eof emits keywords indentation backend token_kind encoding option accel].freeze
17
18
 
18
19
  def initialize(source, path: nil)
19
20
  @source = source
20
21
  @path = path
21
22
  @constants = {}
22
23
  @constant_definitions = []
24
+ @namespaces = Hash.new { |entries, name| entries[name] = [] }
25
+ @rule_set_modules = {}
23
26
  @resolved_constant_definitions = {}
24
27
  @rules = []
25
28
  @spans = []
@@ -52,19 +55,34 @@ module Flexr
52
55
 
53
56
  @states[:initial][:location] = [klass.location.start_offset, klass.location.end_offset]
54
57
  @lexer_scope = class_name.to_s.delete_prefix("::").split("::").reject(&:empty?)
58
+ @lexer_offset = klass.location.start_offset
55
59
  collect_constants(prism.value)
60
+ collect_rule_namespaces(prism.value)
56
61
  collect_body(klass.body, [:initial])
57
62
  require_spans = flexr_require_spans(prism.value)
58
63
  first_dsl_offset = @spans.map(&:first).min || class_body_offset(klass)
59
64
  @config[:eof_rules] = @eof_rules
60
65
  uses_patterns = false
66
+ uses_rule_sets = false
67
+ uses_delegation = false
68
+ uses_input_stack = false
69
+ uses_dynamic_delimiters = false
61
70
  each_node(prism.value) do |node|
62
- uses_patterns ||= node.is_a?(::Prism::CallNode) && %i[pattern upto].include?(node.name)
71
+ next unless node.is_a?(::Prism::CallNode)
72
+
73
+ uses_patterns ||= %i[pattern upto].include?(node.name)
74
+ uses_rule_sets ||= rule_set_extension?(node)
75
+ uses_delegation ||= node.name == :delegate
76
+ uses_input_stack ||= node.name == :push_input
77
+ uses_dynamic_delimiters ||= %i[scan_until scan_until_line].include?(node.name)
63
78
  end
64
79
  SpecSource.new(source: @source, path: @path, class_name: class_name, rules: @rules,
65
80
  config: @config, dsl_spans: @spans.uniq(&:first),
66
81
  first_dsl_offset: first_dsl_offset, constants: @constants, states: @states,
67
- flexr_require_spans: require_spans, dsl_edits: @edits, uses_patterns: uses_patterns)
82
+ flexr_require_spans: require_spans, dsl_edits: @edits, uses_patterns: uses_patterns,
83
+ uses_rule_sets: uses_rule_sets,
84
+ uses_input_stack: uses_input_stack, uses_delegation: uses_delegation,
85
+ uses_dynamic_delimiters: uses_dynamic_delimiters)
68
86
  end
69
87
 
70
88
  private
@@ -140,17 +158,18 @@ module Flexr
140
158
  collect_constants(node.block&.body, scope: scope)
141
159
  end
142
160
 
143
- def resolve_constants(before_offset:)
161
+ def resolve_constants(before_offset:, constants: @constants, resolved: @resolved_constant_definitions)
144
162
  @constant_definitions.sort_by(&:last).each do |name, value_node, scope, offset|
145
- next if offset >= before_offset || @resolved_constant_definitions[offset]
163
+ next if offset >= before_offset || resolved[offset]
146
164
 
147
- @resolved_constant_definitions[offset] = true
148
- value = StaticEval.new(@source, constants: @constants, scope: scope).call(value_node)
149
- @constants[name] = value
165
+ resolved[offset] = true
166
+ value = StaticEval.new(@source, constants: constants, scope: scope).call(value_node)
167
+ constants[name] = value
150
168
  rescue StaticResolutionError
151
169
  # Preserve dynamic constants as ordinary Ruby. A later DSL reference
152
170
  # still receives FLEXR-E017 instead of seeing a forward value.
153
171
  end
172
+ constants
154
173
  end
155
174
 
156
175
  def namespace_parts(node)
@@ -171,6 +190,7 @@ module Flexr
171
190
 
172
191
  def collect_call(node, states)
173
192
  return unless node
193
+ return if @rule_set_modules.key?(node.location.start_offset)
174
194
  return collect_body(node, states) if node.class.name.end_with?("StatementsNode")
175
195
  unless node.class.name.end_with?("CallNode") && node.receiver.nil?
176
196
  reject_unhandled_dsl!(node)
@@ -182,10 +202,12 @@ module Flexr
182
202
  reject_unhandled_dsl!(node)
183
203
  return
184
204
  end
185
- record_deletion(node) unless %i[rule state all_states on_eof].include?(name)
205
+ record_deletion(node) unless %i[rule use state all_states on_eof].include?(name)
186
206
  case name
187
207
  when :rule
188
208
  collect_rule(node, states)
209
+ when :use
210
+ collect_use(node, states)
189
211
  when :state
190
212
  collect_state(node, states)
191
213
  when :all_states
@@ -207,6 +229,8 @@ module Flexr
207
229
  @config[:declared_tokens].concat(values.map(&:to_sym))
208
230
  when :keywords
209
231
  collect_keywords(node)
232
+ when :indentation
233
+ collect_indentation(node)
210
234
  when :backend
211
235
  @config[:backend] = Configuration.backend!(static(positional(node).first))
212
236
  when :token_kind
@@ -225,6 +249,124 @@ module Flexr
225
249
  raise
226
250
  end
227
251
 
252
+ def collect_rule_namespaces(node, scope: [], nesting: [], qualified: false)
253
+ case node
254
+ when Prism::ProgramNode
255
+ collect_rule_namespaces(node.statements, scope: scope, nesting: nesting, qualified: qualified)
256
+ when Prism::StatementsNode
257
+ node.body.each { |child| collect_rule_namespaces(child, scope: scope, nesting: nesting, qualified: qualified) }
258
+ when Prism::ModuleNode, Prism::ClassNode
259
+ nested_scope = scope + namespace_parts(node.constant_path)
260
+ name = nested_scope.join("::")
261
+ nested_nesting = [name, *nesting]
262
+ offset = node.location.start_offset
263
+ @lexer_rule_scopes = nested_nesting if offset == @lexer_offset
264
+ @namespaces[name] << node
265
+ qualified ||= node.constant_path.is_a?(Prism::ConstantPathNode)
266
+ @rule_set_modules[offset] = [nested_scope, qualified] if
267
+ node.is_a?(Prism::ModuleNode) && node.body&.body&.any? { |child| rule_set_extension?(child) }
268
+
269
+ collect_rule_namespaces(node.body, scope: nested_scope, nesting: nested_nesting, qualified: qualified)
270
+ end
271
+ end
272
+
273
+ def rule_set_extension?(node)
274
+ return false unless node.is_a?(Prism::CallNode) && node.receiver.nil? && node.name == :extend && !node.block
275
+
276
+ arguments = Array(node.arguments&.arguments)
277
+ arguments.one? && source_slice(arguments.first).delete_prefix("::") == "Flexr::Rules"
278
+ end
279
+
280
+ def collect_use(node, states)
281
+ validate_keywords!(node, [])
282
+ args = positional(node)
283
+ unsupported_static!("use requires one named rule set without a block", node) unless args.one? && !node.block
284
+
285
+ argument = args.first
286
+ reference = source_slice(argument)
287
+ declaration, scope = resolve_rule_set(argument)
288
+ count, bindings = collect_shared_rules(declaration, states, scope)
289
+ span = [node.location.start_offset, node.location.end_offset]
290
+ @spans << span
291
+ @edits << [*span, "__flexr_bind_rule_set(#{reference}, #{count}, #{bindings.inspect})"]
292
+ end
293
+
294
+ def resolve_rule_set(argument)
295
+ reference = source_slice(argument)
296
+ offset = argument.location.start_offset
297
+ unless reference.match?(/\A(?:::)?[A-Z]\w*(?:::[A-Z]\w*)*\z/)
298
+ unsupported_static!("use requires a literal rule set constant", argument,
299
+ help: "pass the name of a module extended with Flexr::Rules")
300
+ end
301
+
302
+ first, *tail = reference.delete_prefix("::").split("::")
303
+ lexical_root = first
304
+ unless reference.start_with?("::")
305
+ [*Array(@lexer_rule_scopes), ""].each do |scope|
306
+ candidate = [scope, first].reject(&:empty?).join("::")
307
+ next unless @namespaces[candidate].any? { |node| node.location.start_offset < offset } ||
308
+ assigned_constant?(candidate, offset)
309
+
310
+ lexical_root = candidate
311
+ break
312
+ end
313
+ end
314
+
315
+ name = ([lexical_root] + tail).join("::")
316
+ declarations = @namespaces[name].select { |node| node.location.end_offset < offset }
317
+ declaration = declarations.first
318
+ scope, qualified = @rule_set_modules[declaration.location.start_offset] if declaration
319
+ if declarations.one? && scope && !assigned_constant?(lexical_root, offset) && !assigned_constant?(name, offset)
320
+ if qualified
321
+ unsupported_static!("qualified rule-set declarations can change lexical constant lookup", declaration.constant_path,
322
+ help: "declare the rule set within nested module blocks")
323
+ end
324
+ return [declaration, scope]
325
+ end
326
+
327
+ unsupported_static!("rule set could not be resolved in this file", argument,
328
+ help: "declare the module once before use and extend Flexr::Rules")
329
+ end
330
+
331
+ def assigned_constant?(name, offset)
332
+ @constant_definitions.any? { |constant_name, _, _, position| constant_name == name && position < offset }
333
+ end
334
+
335
+ def collect_shared_rules(declaration, states, scope)
336
+ entry = 0
337
+ extended = false
338
+ bindings = declaration.body.body.filter_map do |child|
339
+ if rule_set_extension?(child)
340
+ extended = true
341
+ next
342
+ end
343
+ if child.is_a?(Prism::CallNode) && child.receiver.nil? && child.name == :rule
344
+ unsupported_static!("extend Flexr::Rules before declaring rules", child) unless extended
345
+
346
+ collect_shared_rule(child, states, scope)
347
+ rule = @rules.last
348
+ binding = [rule.index, entry] if rule.bind_action
349
+ entry += 1
350
+ binding
351
+ else
352
+ reject_unhandled_dsl!(child, any_receiver: true)
353
+ nil
354
+ end
355
+ end
356
+ [entry, bindings]
357
+ end
358
+
359
+ def collect_shared_rule(node, states, scope)
360
+ saved_constants = @constants
361
+ @constants = resolve_constants(before_offset: node.location.start_offset, constants: {}, resolved: {})
362
+ collect_rule(node, states, scope: scope, shared: true)
363
+ rescue CompileError => e
364
+ e.diagnostic.location ||= [node.location.start_offset, node.location.end_offset] if e.diagnostic
365
+ raise
366
+ ensure
367
+ @constants = saved_constants
368
+ end
369
+
228
370
  def collect_keywords(node)
229
371
  validate_keywords!(node, %i[among])
230
372
  args = positional(node)
@@ -238,6 +380,16 @@ module Flexr
238
380
  Keywords.add!(@config[:options] ||= {}, @config[:declared_tokens], words, among: type, location: location)
239
381
  end
240
382
 
383
+ def collect_indentation(node)
384
+ validate_keywords!(node, %i[newline indent dedent brackets tab_width])
385
+ unsupported_static!("indentation requires keyword arguments", node) unless positional(node).empty? && !node.block
386
+
387
+ options = keywords(node).transform_values { |value| static(value, scope: @lexer_scope) }
388
+ return if @allow_dynamic && options.value?(nil)
389
+
390
+ (@config[:options] ||= {})[:indentation] = Runtime::Indentation.configuration(**options)
391
+ end
392
+
241
393
  def collect_state(node, parent_states)
242
394
  block = node.block
243
395
  raise ArgumentError, "state requires a block" unless block
@@ -270,16 +422,16 @@ module Flexr
270
422
  collect_body(block.body, (parent_states + @states.keys).uniq)
271
423
  end
272
424
 
273
- def collect_rule(node, states)
425
+ def collect_rule(node, states, scope: @lexer_scope, shared: false)
274
426
  values = positional(node)
275
- patterns = static(values.first, scope: @lexer_scope)
427
+ patterns = static(values.first, scope: scope)
276
428
  patterns = [patterns] unless patterns.is_a?(Array)
277
429
  unless (@allow_dynamic && patterns.any?(&:nil?)) || patterns.all? { |pattern| pattern.is_a?(::Regexp) || pattern.is_a?(String) || pattern.is_a?(Pattern) }
278
430
  diagnostic = Diagnostics.error("FLEXR-E018", "rule pattern must be a Regexp, String, Pattern, or Array")
279
431
  raise CompileError.new(diagnostic.message, diagnostic: diagnostic)
280
432
  end
281
433
  options = keywords(node)
282
- validate_keywords!(node, %i[skip emit followed_by channel priority])
434
+ validate_keywords!(node, %i[skip emit followed_by channel priority emits])
283
435
  action_source = node.block && source_slice(node.block)
284
436
  if action_source && reject_action?(node.block)
285
437
  diagnostic = Diagnostics.error(
@@ -291,11 +443,15 @@ module Flexr
291
443
  block_action = if action_source
292
444
  action_source.start_with?("do") ? "proc #{action_source}" : "proc#{action_source}"
293
445
  end
294
- skip = options.key?(:skip) ? static(options[:skip], scope: @lexer_scope) : false
295
- emit = options.key?(:emit) ? static(options[:emit], scope: @lexer_scope) : nil
296
- priority = options.key?(:priority) ? static(options[:priority], scope: @lexer_scope) : 0
446
+ skip = options.key?(:skip) ? static(options[:skip], scope: scope) : false
447
+ emit = options.key?(:emit) ? static(options[:emit], scope: scope) : nil
448
+ emits = options[:emits] && Configuration.rule_emits!(
449
+ static(options[:emits], scope: scope), emit: emit,
450
+ location: [options[:emits].location.start_offset, options[:emits].location.end_offset]
451
+ )
452
+ priority = options.key?(:priority) ? static(options[:priority], scope: scope) : 0
297
453
  Configuration.rule_priority!(priority) unless @allow_dynamic && priority.nil?
298
- channel = options.key?(:channel) ? static(options[:channel], scope: @lexer_scope) : :default
454
+ channel = options.key?(:channel) ? static(options[:channel], scope: scope) : :default
299
455
  dynamic_channel = @allow_dynamic && channel.nil?
300
456
  channel = dynamic_channel ? :default : Configuration.rule_channel!(channel)
301
457
  skip ||= channel == :skip
@@ -311,12 +467,18 @@ module Flexr
311
467
  end
312
468
  end
313
469
  rule_index = @rules.length
314
- record_rule_edit(node, rule_index, bind_action ? block_action : nil)
470
+ if shared
471
+ action = :__flexr_generated_method if bind_action
472
+ action_source = nil
473
+ else
474
+ record_rule_edit(node, rule_index, bind_action ? block_action : nil)
475
+ end
315
476
  @rules << RuleDefinition.new(
316
477
  index: rule_index, patterns: patterns,
317
- trailing: options[:followed_by] && static(options[:followed_by], scope: @lexer_scope),
478
+ trailing: options[:followed_by] && static(options[:followed_by], scope: scope),
318
479
  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),
480
+ emits: emits,
481
+ bol_only: false, end_anchor: nil, priority: priority, emit_shorthand: bind_action && !emits && emit_shorthand(node.block),
320
482
  span: [node.location.start_offset, node.location.end_offset], bind_action: bind_action, reads_locals: reads_locals
321
483
  )
322
484
  end
@@ -407,7 +569,7 @@ module Flexr
407
569
  @edits << [*closing, "#{closing_source}).call"]
408
570
  end
409
571
 
410
- def reject_unhandled_dsl!(node)
572
+ def reject_unhandled_dsl!(node, any_receiver: false)
411
573
  each_node_including_self(node) do |child|
412
574
  next unless child.class.name.end_with?("CallNode")
413
575
  if %i[send public_send].include?(child.name.to_sym)
@@ -415,7 +577,7 @@ module Flexr
415
577
  unsupported_static!("dynamic dispatch of #{dynamic_name} is not statically supported", child) if dynamic_name
416
578
  end
417
579
  next unless DSL_NAMES.include?(child.name.to_sym)
418
- next unless child.receiver.nil? || child.receiver.class.name.end_with?("SelfNode")
580
+ next unless any_receiver || child.receiver.nil? || child.receiver.class.name.end_with?("SelfNode")
419
581
 
420
582
  unsupported_static!("#{child.name} must be a direct receiverless statement in a lexer or state body", child)
421
583
  end
@@ -429,11 +591,11 @@ module Flexr
429
591
  name if DSL_NAMES.include?(name)
430
592
  end
431
593
 
432
- def unsupported_static!(reason, node)
594
+ def unsupported_static!(reason, node, help: "move the DSL call to the lexer or state body, or use --eval")
433
595
  diagnostic = Diagnostics.error(
434
596
  "FLEXR-E017", "DSL structure is not statically supported",
435
597
  location: [node.location.start_offset, node.location.end_offset],
436
- help: "move the DSL call to the lexer or state body, or use --eval", note: reason
598
+ help: help, note: reason
437
599
  )
438
600
  raise StaticResolutionError.new(diagnostic.message, diagnostic: diagnostic)
439
601
  end
data/lib/flexr/testing.rb CHANGED
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../flexr"
3
+ require_relative "../flexr" unless defined?(Flexr::Lexer)
4
4
 
5
5
  module Flexr
6
6
  module Testing
@@ -35,7 +35,10 @@ module Flexr
35
35
  pairs = value.map { |key, item| [encode(key), encode(item)] }
36
36
  { "hash" => pairs.sort_by { |key, _item| JSON.generate(key) } }
37
37
  when Runtime::Token
38
- { "token" => encode(value.to_h) }
38
+ data = value.to_h
39
+ data = data.merge(channel: value.channel, leading_trivia: value.leading_trivia) if
40
+ value.channel != :default || !value.leading_trivia.empty?
41
+ { "token" => encode(data) }
39
42
  when Runtime::Location
40
43
  { "location" => encode(value.members.to_h { |name| [name, value.public_send(name)] }) }
41
44
  else
@@ -14,23 +14,28 @@ module Flexr
14
14
  nil
15
15
  end
16
16
 
17
- def compiled(pattern, encoding:, options: nil, unicode: false)
17
+ def compiled(pattern, encoding:, options: nil, unicode: false, anchored: false)
18
18
  effective_options = options.nil? ? pattern.options : options
19
- key = [pattern.source, effective_options, encoding, unicode]
19
+ key = [pattern.source, effective_options, encoding, unicode, anchored]
20
20
  return CACHE[key] if CACHE.key?(key)
21
21
 
22
- parser = Regexp::Parser.new(pattern.source, options: effective_options, encoding: encoding, unicode: unicode)
23
- source = source_for(parser.parse)
22
+ captures = !pattern.names.empty?
23
+ binary = captures && encoding == Encoding::BINARY
24
+ parser = Regexp::Parser.new(pattern.source, options: effective_options, encoding: encoding, unicode: unicode,
25
+ preserve_captures: captures)
26
+ source = source_for(parser.parse, binary: binary)
27
+ source = "\\A(?:#{source})\\z" if anchored
24
28
  regexp_options = effective_options & ~::Regexp::IGNORECASE
29
+ regexp_options |= ::Regexp::NOENCODING if binary
25
30
  CACHE[key] = ::Regexp.new(source, regexp_options).freeze
26
31
  end
27
32
 
28
- def source_for(node)
33
+ def source_for(node, binary: false)
29
34
  case node
30
35
  when Regexp::AST::Empty, Regexp::AST::Anchor then ""
31
36
  when Regexp::AST::Fail then "(?!)"
32
37
  when Regexp::AST::ByteRange then byte_class([[node.lo, node.hi]])
33
- when Regexp::AST::CodepointRange then codepoint_class([[node.lo, node.hi]])
38
+ when Regexp::AST::CodepointRange then character_class([[node.lo, node.hi]], binary: binary)
34
39
  when Regexp::AST::CharClass
35
40
  ranges = node.ranges.flat_map do |range|
36
41
  if range.first == Regexp::AST::Property
@@ -42,19 +47,32 @@ module Flexr
42
47
  end
43
48
  end
44
49
  ranges = complement(ranges) if node.negated
45
- codepoint_class(ranges)
46
- when Regexp::AST::Seq then node.children.map { |child| source_for(child) }.join
50
+ character_class(ranges, binary: binary)
51
+ when Regexp::AST::Seq then node.children.map { |child| source_for(child, binary: binary) }.join
47
52
  when Regexp::AST::Alt
48
- "(?:#{node.children.map { |child| source_for(child) }.join('|')})"
49
- when Regexp::AST::Star then "(?:#{source_for(node.child)})*"
53
+ "(?:#{node.children.map { |child| source_for(child, binary: binary) }.join('|')})"
54
+ when Regexp::AST::Star then "(?:#{source_for(node.child, binary: binary)})*"
50
55
  when Regexp::AST::Repeat
51
56
  maximum = node.maximum.nil? ? "" : node.maximum
52
- "(?:#{source_for(node.child)}){#{node.minimum},#{maximum}}"
57
+ "(?:#{source_for(node.child, binary: binary)}){#{node.minimum},#{maximum}}"
58
+ when Regexp::AST::NamedCapture then "(?#{node.opening}#{source_for(node.child, binary: binary)})"
59
+ when Regexp::AST::Absence
60
+ child = source_for(node.child, binary: binary)
61
+ return "(?:(?!)#{child})" if Regexp::AST.nullable?(node.child)
62
+
63
+ "(?~(?:#{child}))"
53
64
  else
54
65
  raise CompileError, "unsupported reference AST node: #{node.class}"
55
66
  end
56
67
  end
57
68
 
69
+ def character_class(ranges, binary:)
70
+ return codepoint_class(ranges) unless binary
71
+
72
+ bytes = ranges.filter_map { |lo, hi| [lo, [hi, 255].min] if lo <= 255 }
73
+ bytes.empty? ? "(?!)" : byte_class(bytes)
74
+ end
75
+
58
76
  def byte_class(ranges)
59
77
  "[#{ranges.map { |lo, hi| byte_escape(lo, hi) }.join}]"
60
78
  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.1.0"
4
+ VERSION = "2.2.0"
5
5
  end
@@ -2,6 +2,9 @@
2
2
 
3
3
  require "ruby_lsp/addon"
4
4
  require "flexr/cli"
5
+ require "flexr/source/fixes"
6
+ require_relative "ranges"
7
+ require_relative "navigation"
5
8
 
6
9
  RubyLsp::Addon.depend_on_ruby_lsp!("~> 0.26.11")
7
10
 
@@ -12,12 +15,18 @@ module RubyLsp
12
15
  return @diagnostics if @source == source
13
16
 
14
17
  @channels = {}
18
+ @edits = []
15
19
  diagnostics = begin
16
20
  parsed = ::Flexr::Source::PrismReader.new(source).read
17
21
  parsed.rules.each { |rule| @channels[rule.span.first] = rule.channel if rule.channel }
18
22
  compiled = ::Flexr::CLI.compile(parsed, overrides: { warn_level: :all })
19
- compiled.diagnostics.reject { |diagnostic| diagnostic.code == "FLEXR-W016" }
23
+ @edits = ::Flexr::Source::Fixes.edits(parsed, compiled)
24
+ diagnostics = compiled.diagnostics.reject { |diagnostic| diagnostic.code == "FLEXR-W016" }
25
+ tables = parsed.config.dig(:options, :keyword_tables)
26
+ diagnostics.concat(::Flexr::Automaton::KeywordTables.grouping_suggestions(compiled, tables)) if @edits.any? { |edit| edit.code == "FLEXR-I003" }
27
+ diagnostics
20
28
  rescue ::Flexr::Error => e
29
+ @edits = ::Flexr::Source::Fixes.regexp_edits(parsed, e.diagnostic)
21
30
  e.diagnostic ? [e.diagnostic] : []
22
31
  rescue ArgumentError => e
23
32
  [::Flexr::Diagnostics.error("FLEXR-E017", e.message, location: [0, 0])]
@@ -30,6 +39,13 @@ module RubyLsp
30
39
  @channels[offset]
31
40
  end
32
41
 
42
+ def edits(diagnostic)
43
+ return [] unless diagnostic.location
44
+
45
+ first, last = diagnostic.location
46
+ @edits.select { |edit| edit.code == diagnostic.code && edit.range.begin.between?(first, last) }
47
+ end
48
+
33
49
  def message(diagnostic)
34
50
  [diagnostic.message, diagnostic.note,
35
51
  ("help: #{diagnostic.help}" if diagnostic.help)].compact.join("\n\n")
@@ -46,29 +62,35 @@ module RubyLsp
46
62
  return [] unless uri.path&.end_with?(".flexr.rb")
47
63
 
48
64
  source = document.source
65
+ ranges = Ranges.new(source, @encoding)
49
66
  @analysis.diagnostics(source).map do |diagnostic|
50
67
  first, last = diagnostic.location || [0, 0]
51
68
  severity = { error: Constant::DiagnosticSeverity::ERROR, warning: Constant::DiagnosticSeverity::WARNING,
52
69
  info: Constant::DiagnosticSeverity::INFORMATION }.fetch(diagnostic.severity)
53
70
  Interface::Diagnostic.new(
54
- range: Interface::Range.new(start: position(source, first), end: position(source, last)),
55
- message: @analysis.message(diagnostic), code: diagnostic.code, severity: severity, source: "flexr"
71
+ range: ranges.range(first, last),
72
+ message: @analysis.message(diagnostic), code: diagnostic.code, severity: severity, source: "flexr",
73
+ data: code_action_data(uri, document, diagnostic, ranges)
56
74
  )
57
75
  end
58
76
  end
59
77
 
60
78
  private
61
79
 
62
- def position(source, offset)
63
- prefix = source.byteslice(0, [offset, source.bytesize].min)
64
- line = prefix.count("\n")
65
- column = prefix.byteslice(((prefix.b.rindex("\n") || -1) + 1)..).delete_suffix("\r")
66
- character = case @encoding
67
- when Encoding::UTF_8 then column.bytesize
68
- when Encoding::UTF_16LE then column.encode(Encoding::UTF_16LE).bytesize / 2
69
- else column.length
80
+ def code_action_data(uri, document, diagnostic, ranges)
81
+ edits = @analysis.edits(diagnostic)
82
+ return if edits.empty?
83
+
84
+ changes = edits.map do |edit|
85
+ Interface::TextEdit.new(range: ranges.range(edit.range.begin, edit.range.end), new_text: edit.replacement)
70
86
  end
71
- Interface::Position.new(line: line, character: character)
87
+ versioned_document = Interface::OptionalVersionedTextDocumentIdentifier.new(uri: uri.to_s, version: document.version)
88
+ document_edit = Interface::TextDocumentEdit.new(text_document: versioned_document, edits: changes)
89
+ action = Interface::CodeAction.new(
90
+ title: ::Flexr::Source::Fixes::TITLES.fetch(diagnostic.code), kind: Constant::CodeActionKind::QUICK_FIX,
91
+ edit: Interface::WorkspaceEdit.new(document_changes: [document_edit])
92
+ )
93
+ { code_actions: [action] }
72
94
  end
73
95
  end
74
96
 
@@ -117,11 +139,14 @@ module RubyLsp
117
139
  class Addon < ::RubyLsp::Addon
118
140
  def activate(global_state, _message_queue)
119
141
  @analysis = Analysis.new
120
- global_state.register_formatter("flexr", Diagnostics.new(@analysis, global_state.encoding))
142
+ @encoding = global_state.encoding
143
+ @outline_builders = ObjectSpace::WeakKeyMap.new
144
+ global_state.register_formatter("flexr", Diagnostics.new(@analysis, @encoding))
121
145
  end
122
146
 
123
147
  def deactivate
124
148
  @analysis = nil
149
+ @outline_builders = nil
125
150
  end
126
151
 
127
152
  def name
@@ -135,6 +160,56 @@ module RubyLsp
135
160
  def create_hover_listener(response_builder, _node_context, dispatcher)
136
161
  Hover.new(response_builder, @analysis, dispatcher)
137
162
  end
163
+
164
+ def create_definition_listener(builder, uri, context, _dispatcher)
165
+ return unless specification_uri?(uri) && context.node && context.call_node && !context.surrounding_method
166
+
167
+ source = context.node.location.source_lines.join
168
+ specification = Navigation.specification_at(context.node, source)
169
+ locations = specification&.state_definitions(context.node, context.call_node)
170
+ return if locations.nil? || locations.empty?
171
+
172
+ ranges = Ranges.new(source, @encoding)
173
+ locations.each do |location|
174
+ builder << Interface::Location.new(uri: uri.to_s, range: ranges.location(location))
175
+ end
176
+ end
177
+
178
+ def create_completion_listener(builder, context, _dispatcher, uri)
179
+ return unless specification_uri?(uri) && context.node && context.call_node && !context.surrounding_method
180
+
181
+ source = context.node.location.source_lines.join
182
+ specification = Navigation.specification_at(context.node, source)
183
+ site = specification&.completion_site(
184
+ context.node, context.call_node, source: source, recover_utf8: @encoding == Encoding::UTF_8
185
+ )
186
+ return unless site
187
+
188
+ range = Ranges.new(source, @encoding).location(site.location)
189
+ specification.token_names(excluding: site).each do |name|
190
+ next unless name.start_with?(site.prefix)
191
+
192
+ label = name.to_sym.inspect
193
+ edit = Interface::TextEdit.new(range: range, new_text: label)
194
+ builder << Interface::CompletionItem.new(label: label, kind: Constant::CompletionItemKind::ENUM_MEMBER, text_edit: edit)
195
+ end
196
+ end
197
+
198
+ def create_document_symbol_listener(builder, dispatcher)
199
+ @outline_builders[dispatcher] = builder
200
+ end
201
+
202
+ def create_code_lens_listener(_builder, uri, dispatcher)
203
+ # Ruby LSP uses one dispatcher for these requests and passes the URI to the code lens hook.
204
+ builder = @outline_builders.delete(dispatcher)
205
+ Navigation::Outline.new(builder, dispatcher, @encoding) if builder && specification_uri?(uri)
206
+ end
207
+
208
+ private
209
+
210
+ def specification_uri?(uri)
211
+ uri.path&.end_with?(".flexr.rb")
212
+ end
138
213
  end
139
214
  end
140
215
  end