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
@@ -4,11 +4,11 @@ The DSL is extended onto a subclass of `Flexr::Lexer`. Class bodies are normal
4
4
  Ruby and may contain constants, methods, requires, comments, and ordinary
5
5
  expressions.
6
6
 
7
- ## `rule(pattern, skip: false, emit: nil, followed_by: nil, &action)`
7
+ ## `rule(pattern, skip: false, emit: nil, followed_by: nil, channel: :default, priority: 0, &action)`
8
8
 
9
- Registers one rule. `pattern` is a `Regexp`, `String`, or an array containing
10
- those values. A string is matched literally. Array members are alternatives of
11
- one rule and share its action.
9
+ Registers one rule. `pattern` is a `Regexp`, `String`, `Flexr::Pattern`, or an
10
+ array containing those values. A string is matched literally. Array members
11
+ are alternatives of one rule and share its action.
12
12
 
13
13
  `skip: true` discards the match and takes precedence over `emit` and the block.
14
14
  `emit: :TOKEN` installs a simple action that emits the token with the matched
@@ -19,9 +19,83 @@ Prefer `emit:` when the value is the unchanged matched text, such as
19
19
  `rule(/\+/, emit: :PLUS)`. This avoids executing a Ruby action block for each
20
20
  token. Use a block when converting a value or changing lexer state.
21
21
 
22
- `followed_by:` accepts a `Regexp` or `String`. It participates in rule
23
- selection but is not consumed. The method returns `nil`. Rules are numbered in
24
- source order starting at zero.
22
+ `followed_by:` accepts a `Regexp`, `String`, or `Flexr::Pattern`. It
23
+ participates in rule selection while leaving the lookahead for the next token.
24
+ The method returns `nil`. Rules are numbered in source order starting at zero.
25
+
26
+ ## `pattern(*values)`
27
+
28
+ Builds an immutable, Ractor-shareable `Flexr::Pattern` from regexps, literal
29
+ strings, existing pattern values, and arrays of those values. Multiple values
30
+ form alternatives. Assign a pattern to a constant to reuse it in other
31
+ patterns and in rules.
32
+
33
+ ```ruby
34
+ class Words < Flexr::Lexer
35
+ IDENT = pattern(/[a-z_][a-z0-9_]*/)
36
+ KEYWORD = pattern(%w[if else end while])
37
+ SHORT = pattern(/.{1,8}/)
38
+
39
+ rule(KEYWORD, emit: :KEYWORD)
40
+ rule((IDENT & SHORT) - KEYWORD, emit: :SHORT_IDENT)
41
+ rule(!pattern(/.*__.*/) & IDENT, emit: :IDENT)
42
+ end
43
+ ```
44
+
45
+ | Operator | Language |
46
+ |---|---|
47
+ | `a \| b` | Strings matched by either operand |
48
+ | `a + b` | A match of `a` followed by a match of `b` |
49
+ | `a & b` | Strings matched by both operands |
50
+ | `a - b` | Strings matched by `a` and excluded by `b` |
51
+ | `!a` | All strings in the subject alphabet outside `a` |
52
+
53
+ Complement is relative to valid Unicode scalar strings in a UTF-8 lexer and
54
+ all byte strings in a binary lexer. Use line anchors in a plain rule regexp.
55
+ Pattern operations and earlier constant definitions are resolved by the static
56
+ generator. `flexr explain` and `flexr dot` display the constant names used
57
+ in a rule.
58
+
59
+ Use `table`, `direct`, or `auto` for rule bodies built from pattern values.
60
+ All backends can use pattern values as trailing context. Runtime and generated
61
+ scanners keep the usual longest-match and rule order policies. Whole-token
62
+ acceleration is disabled in states that contain pattern values.
63
+
64
+ ## `upto(terminator)`
65
+
66
+ Returns a pattern that ends at the first completed match of `terminator`,
67
+ including that match. The terminator uses the same input forms as `pattern`.
68
+ An occurrence can start anywhere in the span, and an absent terminator gives
69
+ no match. If the terminator can match the empty string, its first occurrence
70
+ ends immediately. A whole rule that can match without consuming input
71
+ reports `FLEXR-E005` unless empty matches are enabled.
72
+
73
+ ```ruby
74
+ rule(pattern("/*") + upto("*/"), skip: true)
75
+ ```
76
+
77
+ For an overlapping terminator such as `"aba"`, `upto("aba")` consumes
78
+ three bytes from `"ababa"`. Further rules can consume the remaining text.
79
+
80
+ See [pattern diagnostics](diagnostics.md#pattern-operations) and
81
+ [ADR 0029](../adr/0029-pattern-algebra.md).
82
+
83
+ `channel:` accepts a symbol. The default is `:default`; other named
84
+ channels preserve tokens as trivia for `tokens(channels: :all)`.
85
+ `channel: :skip` is equivalent to `skip: true`, which discards the match
86
+ in every consumer. `:all` selects channels when collecting tokens.
87
+ With a trivia channel and no explicit action or `emit:`, the channel name
88
+ becomes the token type and the matched text becomes the value.
89
+ Static generation requires a symbol literal or a statically resolvable
90
+ symbol constant for the channel name. With `--eval`, a Ruby expression can
91
+ compute that symbol.
92
+
93
+ `priority:` accepts an integer and defaults to zero. On longest-match
94
+ backends, the highest priority wins among rules with the same total match
95
+ length, including any trailing context. Source order breaks ties between
96
+ equal priorities. For example, a later `rule("if", emit: :IF, priority: 10)`
97
+ can win over an identifier rule on `if`, while the identifier rule still
98
+ wins on `ifx`.
25
99
 
26
100
  ## `state(*names, inclusive: false, &block)`
27
101
 
@@ -47,10 +121,41 @@ state, or do nothing. It runs at most once per state for a lexer instance.
47
121
 
48
122
  ## `emits(*tokens)`
49
123
 
50
- Declares token names for diagnostics and parser integration. Arguments are
124
+ Declares default-channel token names for diagnostics and parser integration. Arguments are
51
125
  flattened and converted to symbols. Duplicate names are removed. The method
52
126
  does not restrict `emit` at runtime.
53
127
 
128
+ ## `keywords(words, among:)`
129
+
130
+ Remaps the token type of a winning default-channel rule declared with
131
+ `emit: :TOKEN`. Pass the base type as `among:` and a nonempty array of exact
132
+ UTF-8 spellings.
133
+ Each spelling maps to its uppercase symbol. Use a hash of strings to symbols
134
+ to choose names or assign the same type to several spellings.
135
+
136
+ ```ruby
137
+ rule(/[a-z_][a-z0-9_]*/, emit: :IDENT)
138
+ keywords %w[if else end], among: :IDENT
139
+ keywords({ "yes" => :TRUE, "true" => :TRUE }, among: :IDENT)
140
+ ```
141
+
142
+ `if` produces `[:IF, "if"]` and `ifx` produces `[:IDENT, "ifx"]`.
143
+ The lookup is case-sensitive and runs after rule selection. Token text and
144
+ locations stay the same, including text accumulated by `more`. The lookup
145
+ uses the winning rule's own lexeme. Action blocks keep control of their
146
+ emitted types. The table applies to matching default-channel `emit:` rules
147
+ across lexical states. Trivia rules can still win under normal rule selection.
148
+
149
+ The base and mapped types are added to `emits` and checked by
150
+ `check --grammar`. Multiple declarations can extend a table. A spelling
151
+ may have only one mapped type within that table. Every spelling must
152
+ match the full body of a default-channel rule with the base type, or compilation reports
153
+ `FLEXR-E028`. A competing rule may win on the same spelling by priority or
154
+ source order. The compiler reports `FLEXR-W022` when the DFA can prove
155
+ that the spelling always reaches the competing rule.
156
+ See [ADR 0030](../adr/0030-classify-keywords-after-matching.md) for the decision
157
+ to keep keyword spellings out of the DFA.
158
+
54
159
  ## `backend(name)`
55
160
 
56
161
  Selects `:table`, `:direct`, `:auto`, or `:firstmatch`
@@ -6,6 +6,7 @@ else may change between releases without a deprecation cycle.
6
6
  ## Public and stable
7
7
 
8
8
  - `Flexr::Lexer` and the DSL methods in [dsl.md](dsl.md).
9
+ - `Flexr::Pattern` values and the [pattern algebra](dsl.md#patternvalues).
9
10
  - Runtime consumption: `initialize`, `next_token`, `tokens`, `each_token`, and
10
11
  `racc_next_token`.
11
12
  - Action context methods in [actions.md](actions.md).
@@ -29,7 +29,7 @@ byte-oriented automaton. All matches start at the current lexer position.
29
29
  | Atomic groups | Unsupported | Use the delimited-text example in `FLEXR-E014` where applicable; removing atomic groups can change matches |
30
30
  | Named captures | Unsupported | Use `(?:...)` when only grouping is needed; capture-dependent patterns need a separate rewrite |
31
31
  | Conditional groups | Unsupported | Use the finite alternatives shown by `FLEXR-E014` where applicable, or separate rules and state checks |
32
- | Absence groups `(?~...)` | Unsupported | For a single excluded literal, use the negated character class shown by `FLEXR-E014`; larger expressions need a separate rewrite |
32
+ | Absence groups `(?~X)` | Supported | Rule patterns require a longest-match backend. See [absence groups](#absence-groups) |
33
33
 
34
34
  Malformed syntax produces `FLEXR-E001`. Unsupported constructs produce
35
35
  `FLEXR-E014`; the diagnostic help normally names the supported replacement.
@@ -46,6 +46,38 @@ Repetition remains a symbolic AST node until NFA construction, avoiding large
46
46
  intermediate trees. In `{n,m}`, `m` must be at least `n`; explicit bounds may
47
47
  not exceed 1000. `{n,}` uses an unbounded loop after the required copies.
48
48
 
49
+ ## Absence groups
50
+
51
+ `(?~X)` matches text containing no substring matched by `X`. The group
52
+ can consume line feeds. In UTF-8 it consumes complete Unicode scalars, and
53
+ in binary mode it consumes bytes. For example, this rule skips C-style
54
+ comments through the first closing delimiter.
55
+
56
+ ```ruby
57
+ rule(%r{/\*(?~\*/)\*/}, skip: true)
58
+ ```
59
+
60
+ Each occurrence of the forbidden expression must fit within the group's
61
+ own span. The normal longest-match rule still applies to the surrounding
62
+ pattern, including delimiters that can overlap themselves.
63
+
64
+ If `X` can match the empty string, the group has an empty language because
65
+ every string contains the empty string. Otherwise the group can itself
66
+ match empty input, so a rule consisting of `(?~X)` alone reports
67
+ `FLEXR-E005` unless empty matches are enabled.
68
+
69
+ The compiled automaton uses this language definition in runtime, generated,
70
+ and standalone modes. Ruby 4.0.9's regexp matcher, for example, accepts
71
+ empty input for `\A(?~a?)\z`; flexr's `(?~a?)` has an empty language.
72
+ Likewise, flexr parses `X` as an ordinary alternation in `(?~a|b)`.
73
+
74
+ Use `table`, `direct`, or `auto` for rule patterns that use absence.
75
+ All backends support non-nullable absence expressions in `followed_by:`
76
+ because trailing context is evaluated by a DFA. Extended `(?~|...)`
77
+ forms report `FLEXR-E014`. Anchors inside `X` report `FLEXR-E009`.
78
+
79
+ See [ADR 0028](../adr/0028-dfa-absence-groups.md) for the compilation strategy.
80
+
49
81
  ## Captures
50
82
 
51
83
  Unnamed capturing parentheses do not expose match groups to actions. They are treated
@@ -31,8 +31,9 @@ must be positive.
31
31
 
32
32
  | Method | Result |
33
33
  |---|---|
34
- | `next_token` | One token, or `nil` at EOF |
35
- | `tokens` | Array containing every token until EOF |
34
+ | `next_token` | One default-channel token, or `nil` at EOF |
35
+ | `tokens(channels: :default)` | Array containing the remaining default-channel tokens |
36
+ | `tokens(channels: :all)` | Array containing the remaining tokens from every channel in input order |
36
37
  | `each_token` | Enumerator without a block; otherwise yields tokens and returns `self` |
37
38
  | `racc_next_token` | `[type, value]`, or `[false, "$end"]` at EOF |
38
39
  | `input` | The currently retained input string |
@@ -45,6 +46,9 @@ must be positive.
45
46
 
46
47
  `each_token` yields two arguments instead of one when `token_kind :yield` is
47
48
  selected. `tokens` always returns an array of token values.
49
+ With trivia channels, `each_token` and `racc_next_token` expose the default
50
+ channel just like `next_token`. Collect all channels from a fresh lexer to
51
+ preserve the full stream. A lexer instance advances as tokens are consumed.
48
52
 
49
53
  ## State and action context
50
54
 
@@ -20,6 +20,39 @@ Immutability is shallow: custom token values can still be mutable.
20
20
  Lazy columns use a frozen pair without mutating the record or retaining the
21
21
  lexer; `to_h` returns the resolved columns.
22
22
 
23
+ ## Trivia channels
24
+
25
+ Retain whitespace and comments in named channels when writing a formatter or
26
+ source tool alongside a parser.
27
+
28
+ ```ruby
29
+ class Lexer < Flexr::Lexer
30
+ token_kind :struct
31
+ rule(/#[^\n]*/, channel: :comment)
32
+ rule(/[ \t\n]+/, channel: :whitespace)
33
+ rule(/[a-z_][a-z0-9_]*/, emit: :IDENT)
34
+ end
35
+
36
+ input = "# note\nname"
37
+ token = Lexer.new(input).next_token
38
+ token.leading_trivia.map(&:channel) # => [:comment, :whitespace]
39
+ Lexer.new(input).tokens(channels: :all).map(&:value).join == input # => true
40
+ ```
41
+
42
+ Structured tokens expose their `channel` and a frozen `leading_trivia` array
43
+ of structured tokens. The array contains the trivia between this token
44
+ and the previous default-channel token. An emitted EOF token can carry
45
+ any trailing trivia. Use `tokens(channels: :all)` to collect trailing trivia
46
+ when there is no EOF token. Lexical error recovery tokens and EOF emissions
47
+ use the default channel. For `more`, the rule that emits the combined text
48
+ determines its channel. `Token#with` preserves this metadata, and its
49
+ three data members stay the same. Array and yield tokens retain their
50
+ two-element shape.
51
+
52
+ Joining values reconstructs the original input when rules preserve the
53
+ matched text, retain every byte, and emit it once. Discard rules, actions
54
+ that change values, and synthesized tokens can alter the reconstructed text.
55
+
23
56
  ## Locations
24
57
 
25
58
  `Flexr::Runtime::Location` has these public members:
@@ -23,6 +23,7 @@ module Flexr
23
23
 
24
24
  def whole_token_plans(dfa, rules)
25
25
  return if rules.any?(&:trailing) || !dfa.accepts[dfa.start].empty?
26
+ return if defined?(Pattern) && rules.any? { |rule| rule.patterns.any?(Pattern) }
26
27
  return if dfa.accepts.any? { |acceptances| acceptances.any? { |item| item.bol_only || item.end_anchor } }
27
28
 
28
29
  plans = Array.new(256)
@@ -78,10 +78,10 @@ module Flexr
78
78
  while cursor < queue.length
79
79
  state = queue.fetch(cursor).first
80
80
  accepts = dfa.accepts.fetch(state)
81
- winner = accepts.min_by(&:rule_index)&.rule_index
81
+ winner = accepts.first&.rule_index
82
82
  if (include_empty || cursor.positive?) && winner
83
83
  shadowed = accepts.map(&:rule_index).uniq.select do |index|
84
- (include_unshadowed || index > winner) && remaining.key?(index)
84
+ (include_unshadowed || index != winner) && remaining.key?(index)
85
85
  end
86
86
  unless shadowed.empty?
87
87
  input = example_input(queue, cursor)
@@ -149,7 +149,7 @@ module Flexr
149
149
  matches = {}
150
150
  lengths.each do |index, length|
151
151
  trailing = trailing_dfas[index]
152
- lookahead = trailing ? dfa_match_lengths(trailing, input, offset: length).map(&:last).max : 0
152
+ lookahead = trailing ? dfa_match_lengths(trailing, input, offset: length, encoding: encoding).map(&:last).max : 0
153
153
  next unless lookahead
154
154
 
155
155
  total = length + lookahead
@@ -159,7 +159,8 @@ module Flexr
159
159
  end
160
160
  return unless matches.key?(target.index)
161
161
 
162
- winner, (length, total) = matches.max_by { |index, (_, size)| firstmatch ? -index : [size, -index] }
162
+ priorities = rules.to_h { |rule| [rule.index, rule.priority] }
163
+ winner, (length, total) = matches.max_by { |index, (_, size)| firstmatch ? -index : [size, priorities.fetch(index), -index] }
163
164
  return if same_length && total != matches.fetch(target.index).last
164
165
 
165
166
  [winner, length, total - length]
@@ -171,9 +172,11 @@ module Flexr
171
172
  state = dfa.start
172
173
  cursor = offset
173
174
  matches = []
175
+ at_line_start = offset.zero? || input.getbyte(offset - 1) == 0x0a
174
176
  loop do
175
- if encoding != Encoding::UTF_8 || input.byteslice(0, cursor).valid_encoding?
177
+ if encoding != Encoding::UTF_8 || input.byteslice(0, cursor).force_encoding(encoding).valid_encoding?
176
178
  dfa.accepts.fetch(state).each do |acceptance|
179
+ next if acceptance.bol_only && !at_line_start
177
180
  next if acceptance.end_anchor && cursor < input.bytesize && input.getbyte(cursor) != 0x0a
178
181
 
179
182
  matches << [acceptance.rule_index, cursor - offset]