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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +33 -0
- data/README.md +4 -0
- data/benchmark/dfa_stretch.rb +149 -0
- data/benchmark/lrama_lexer.rb +79 -96
- data/benchmark/regexp_parser_corpus.rb +35 -0
- data/benchmark/regexp_parser_parity.rb +89 -0
- data/benchmark/regexp_parser_scanner.rb +159 -0
- data/docs/README.md +4 -1
- data/docs/adr/0021-ruby-34-minimum.md +23 -0
- data/docs/adr/0022-immutable-tokens-and-locations.md +22 -0
- data/docs/adr/0023-stable-explicit-firstmatch.md +21 -0
- data/docs/adr/0024-opt-in-ractor-sharing.md +24 -0
- data/docs/adr/0025-explicit-whole-token-acceleration.md +26 -0
- data/docs/adr/0026-retain-direct-dispatch.md +22 -0
- data/docs/adr/0033-action-free-recognition.md +33 -0
- data/docs/adr/0034-lexer-checkpoints.md +25 -0
- data/docs/adr/0035-parser-token-expectations.md +27 -0
- data/docs/adr/0038-replay-named-regexp-captures.md +23 -0
- data/docs/adr/0039-input-stack.md +25 -0
- data/docs/adr/0040-runtime-delimiters.md +23 -0
- data/docs/adr/0041-post-lexical-indentation.md +24 -0
- data/docs/adr/0042-capture-delegation.md +23 -0
- data/docs/adr/0043-expand-reusable-rules-explicitly.md +27 -0
- data/docs/adr/0044-import-oedipus-firstmatch.md +26 -0
- data/docs/assets/playground-absence-and-diagnostics.gif +0 -0
- data/docs/explanation/backends.md +5 -4
- data/docs/how-to/integrate-with-lrama.md +9 -8
- data/docs/how-to/integrate-with-racc.md +9 -0
- data/docs/how-to/migrate-from-oedipus-lex.md +43 -0
- data/docs/how-to/parser-driven-lexing.md +48 -0
- data/docs/how-to/try-playground-demos.md +13 -0
- data/docs/internals/regexp-parser-experiment.md +67 -0
- data/docs/perf-log.md +120 -8
- data/docs/reference/README.md +1 -1
- data/docs/reference/actions.md +106 -0
- data/docs/reference/cli.md +75 -4
- data/docs/reference/diagnostics.md +3 -9
- data/docs/reference/dsl.md +66 -3
- data/docs/reference/public-api.md +8 -1
- data/docs/reference/regexp.md +27 -4
- data/docs/reference/ruby-lsp.md +15 -0
- data/docs/reference/runtime.md +163 -2
- data/docs/tutorial/build-a-calculator-parser.md +47 -0
- data/examples/with_lrama/README.md +3 -3
- data/lib/flexr/automaton/accel.rb +1 -0
- data/lib/flexr/automaton/compiler.rb +15 -0
- data/lib/flexr/automaton/dfa.rb +0 -33
- data/lib/flexr/automaton/keyword_tables.rb +14 -8
- data/lib/flexr/automaton/reference_dfa.rb +38 -0
- data/lib/flexr/cli.rb +118 -18
- data/lib/flexr/codegen/table.rb +7 -0
- data/lib/flexr/configuration.rb +18 -1
- data/lib/flexr/dsl.rb +14 -3
- data/lib/flexr/generated.rb +4 -0
- data/lib/flexr/generator.rb +39 -7
- data/lib/flexr/importer/oedipus_lex.rb +229 -0
- data/lib/flexr/importer.rb +7 -2
- data/lib/flexr/ir.rb +1 -1
- data/lib/flexr/options.rb +3 -0
- data/lib/flexr/project_template.rb +46 -0
- data/lib/flexr/project_templates/common/.gitignore +1 -0
- data/lib/flexr/project_templates/common/lexer.flexr.rb +12 -0
- data/lib/flexr/project_templates/common/test_calculator.rb +15 -0
- data/lib/flexr/project_templates/lrama/Gemfile +9 -0
- data/lib/flexr/project_templates/lrama/README.md +17 -0
- data/lib/flexr/project_templates/lrama/Rakefile +18 -0
- data/lib/flexr/project_templates/lrama/calculator.rb +28 -0
- data/lib/flexr/project_templates/lrama/parser.y +72 -0
- data/lib/flexr/project_templates/racc/Gemfile +8 -0
- data/lib/flexr/project_templates/racc/README.md +15 -0
- data/lib/flexr/project_templates/racc/Rakefile +14 -0
- data/lib/flexr/project_templates/racc/calculator.rb +22 -0
- data/lib/flexr/project_templates/racc/parser.y +19 -0
- data/lib/flexr/regexp/ast.rb +2 -0
- data/lib/flexr/regexp/parser.rb +13 -11
- data/lib/flexr/regexp/tokenizer.rb +2 -2
- data/lib/flexr/rules.rb +53 -0
- data/lib/flexr/runtime/buffer.rb +1 -1
- data/lib/flexr/runtime/captures.rb +46 -0
- data/lib/flexr/runtime/channels.rb +2 -1
- data/lib/flexr/runtime/checkpoint.rb +116 -0
- data/lib/flexr/runtime/core.rb +55 -43
- data/lib/flexr/runtime/delegation.rb +123 -0
- data/lib/flexr/runtime/delimiters.rb +89 -0
- data/lib/flexr/runtime/firstmatch.rb +266 -0
- data/lib/flexr/runtime/indentation.rb +235 -0
- data/lib/flexr/runtime/input_stack.rb +48 -0
- data/lib/flexr/runtime/interpreter.rb +36 -314
- data/lib/flexr/runtime/recognizer.rb +106 -0
- data/lib/flexr/runtime.rb +10 -0
- data/lib/flexr/skeleton/verification.rb +103 -0
- data/lib/flexr/skeleton.rb +208 -0
- data/lib/flexr/source/fixes.rb +145 -0
- data/lib/flexr/source/prism_reader.rb +187 -25
- data/lib/flexr/testing.rb +5 -2
- data/lib/flexr/unicode/reference_regexp.rb +29 -11
- data/lib/flexr/version.rb +1 -1
- data/lib/ruby_lsp/flexr/addon.rb +88 -13
- data/lib/ruby_lsp/flexr/navigation.rb +231 -0
- data/lib/ruby_lsp/flexr/ranges.rb +40 -0
- data/sig/flexr.rbs +33 -3
- data/site/README.md +22 -7
- data/site/ruby/presets/heredoc.flexr.rb +15 -0
- data/site/ruby/presets/html_javascript.rb +12 -0
- data/site/ruby/presets/html_js.flexr.rb +14 -0
- data/site/ruby/presets/indentation.flexr.rb +14 -0
- data/site/scripts/prepare-playground.mjs +16 -6
- data/site/scripts/stable-release.mjs +4 -1
- data/site/src/content/docs/learn/parser-integration.md +23 -8
- data/site/src/content/docs/reference/cli.md +3 -0
- data/site/src/content/docs/reference/dsl.md +1 -0
- data/site/src/content/docs/reference/runtime.md +26 -0
- data/site/src/pages/playground.astro +15 -1
- data/site/src/playground/client.js +30 -1
- data/site/src/playground/issue.mjs +19 -0
- data/site/src/playground/runtime.mjs +4 -3
- data/site/src/playground/worker.mjs +1 -1
- data/site/tests/browser/playground.spec.mjs +64 -0
- data/site/tests/playground-issue.test.mjs +15 -0
- data/site/tests/playground-release.test.mjs +62 -11
- data/site/tests/playground-runtime.test.mjs +48 -0
- data/test/ruby_lsp_addon_spec.rb +174 -0
- metadata +63 -1
data/docs/reference/dsl.md
CHANGED
|
@@ -4,7 +4,7 @@ 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, channel: :default, priority: 0, &action)`
|
|
7
|
+
## `rule(pattern, skip: false, emit: nil, followed_by: nil, channel: :default, priority: 0, emits: nil, &action)`
|
|
8
8
|
|
|
9
9
|
Registers one rule. `pattern` is a `Regexp`, `String`, `Flexr::Pattern`, or an
|
|
10
10
|
array containing those values. A string is matched literally. Array members
|
|
@@ -19,10 +19,52 @@ 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
|
+
For parser-driven lexing, `emits:` declares which token types an action can
|
|
23
|
+
return. Pass one Symbol or a nonempty array of Symbols. Use `emit:` alone
|
|
24
|
+
when the rule already declares its token and emits the matched text. The
|
|
25
|
+
class-level `emits` method continues to declare the grammar's token list.
|
|
26
|
+
See [parser token expectations](runtime.md#parser-token-expectations).
|
|
27
|
+
|
|
22
28
|
`followed_by:` accepts a `Regexp`, `String`, or `Flexr::Pattern`. It
|
|
23
29
|
participates in rule selection while leaving the lookahead for the next token.
|
|
24
30
|
The method returns `nil`. Rules are numbered in source order starting at zero.
|
|
25
31
|
|
|
32
|
+
## `use(rule_set)`
|
|
33
|
+
|
|
34
|
+
Extend a module with `Flexr::Rules` and declare ordinary rules in it. A lexer
|
|
35
|
+
inserts copies of those rules where it calls `use`.
|
|
36
|
+
|
|
37
|
+
```ruby
|
|
38
|
+
module CommonTokens
|
|
39
|
+
extend Flexr::Rules
|
|
40
|
+
|
|
41
|
+
rule(/[ \t]+/, channel: :whitespace)
|
|
42
|
+
rule(/#[^\n]*/, channel: :comment)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
class Lexer < Flexr::Lexer
|
|
46
|
+
use CommonTokens
|
|
47
|
+
rule(/[a-z]+/, emit: :NAME)
|
|
48
|
+
end
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Rules introduced by `use` participate in the same longest-match and priority
|
|
52
|
+
rules as direct declarations. Equal-length matches at the same priority
|
|
53
|
+
follow the expanded source order. A `use` inside `state` or `all_states`
|
|
54
|
+
adds the rules to the active states. Action blocks retain the module's
|
|
55
|
+
lexical variables and constants and run on the consuming lexer instance.
|
|
56
|
+
|
|
57
|
+
At runtime, each call takes a snapshot of the rule declarations. Subclasses
|
|
58
|
+
start with their own rules and call `use` where they want the shared rules.
|
|
59
|
+
|
|
60
|
+
For static generation, define each rule set in a named module in the same
|
|
61
|
+
file before its first use. Use nested module declarations for namespaces
|
|
62
|
+
and pass the rule set as a constant. Write its `rule` calls directly in
|
|
63
|
+
the module body. Write state selection, EOF,
|
|
64
|
+
keywords, and other lexer configuration in the consuming lexer. The
|
|
65
|
+
generated file checks the number of declarations when it loads, so a
|
|
66
|
+
dynamic rule addition produces an error.
|
|
67
|
+
|
|
26
68
|
## `pattern(*values)`
|
|
27
69
|
|
|
28
70
|
Builds an immutable, Ractor-shareable `Flexr::Pattern` from regexps, literal
|
|
@@ -156,6 +198,22 @@ that the spelling always reaches the competing rule.
|
|
|
156
198
|
See [ADR 0030](../adr/0030-classify-keywords-after-matching.md) for the decision
|
|
157
199
|
to keep keyword spellings out of the DFA.
|
|
158
200
|
|
|
201
|
+
## `indentation(newline:, indent:, dedent:, brackets: [], tab_width: 8)`
|
|
202
|
+
|
|
203
|
+
Configure layout processing with three distinct token Symbols. Emit the
|
|
204
|
+
configured `newline` for LF or CRLF. A newline rule may also consume the
|
|
205
|
+
following spaces and tabs. Skip ordinary whitespace and comments, or send
|
|
206
|
+
them to trivia channels. Keep each layout-significant line break visible as
|
|
207
|
+
the configured newline token.
|
|
208
|
+
|
|
209
|
+
`brackets` contains two-character strings, each with an opening and a
|
|
210
|
+
closing character. Each character can appear in one pair. A recognized
|
|
211
|
+
bracket token is identified by its original matched character. Set
|
|
212
|
+
`tab_width` to a positive integer. A tab advances to the next tab stop.
|
|
213
|
+
|
|
214
|
+
See [indentation tokens](runtime.md#indentation-tokens) for the output order
|
|
215
|
+
and positions.
|
|
216
|
+
|
|
159
217
|
## `backend(name)`
|
|
160
218
|
|
|
161
219
|
Selects `:table`, `:direct`, `:auto`, or `:firstmatch`
|
|
@@ -183,8 +241,13 @@ model is valid.
|
|
|
183
241
|
Adds boolean options to the specification. Stable options include
|
|
184
242
|
`:unicode`, `:eager_columns`, and `:allow_empty_match`. `:experimental` remains
|
|
185
243
|
accepted for compatibility; it is no longer required by `:firstmatch`.
|
|
186
|
-
`:standalone` is build metadata used by standalone generation.
|
|
187
|
-
|
|
244
|
+
`:standalone` is build metadata used by standalone generation. `:input_stack`
|
|
245
|
+
includes support for external callers of `push_input` in a standalone lexer.
|
|
246
|
+
`:delegation` adds the [delegation helper](actions.md#delegate-a-capture-to-another-lexer)
|
|
247
|
+
for indirect calls. `:dynamic_delimiters` includes the
|
|
248
|
+
[delimiter helpers](actions.md#dynamic-delimiters) in a standalone lexer for
|
|
249
|
+
indirect calls. Unknown option names raise immediately so misspellings
|
|
250
|
+
cannot silently change behavior.
|
|
188
251
|
|
|
189
252
|
## `accel(value)`
|
|
190
253
|
|
|
@@ -6,9 +6,16 @@ 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::Rules` modules and [explicit rule reuse](dsl.md#userule_set).
|
|
9
10
|
- `Flexr::Pattern` values and the [pattern algebra](dsl.md#patternvalues).
|
|
10
11
|
- Runtime consumption: `initialize`, `next_token`, `tokens`, `each_token`, and
|
|
11
|
-
`racc_next_token`.
|
|
12
|
+
`racc_next_token`. See [parser token expectations](runtime.md#parser-token-expectations)
|
|
13
|
+
for the `expect:` keyword.
|
|
14
|
+
- [Runtime positioning](runtime.md#checkpoint-and-seek): `checkpoint`,
|
|
15
|
+
`restore`, `seek`, and the opaque `Flexr::Runtime::Checkpoint`.
|
|
16
|
+
- `push_input` for [included inputs](runtime.md#input-stack).
|
|
17
|
+
- `Flexr::Lexer.recognizer` and `Flexr::Recognizer#match` for
|
|
18
|
+
[action-free matching](runtime.md#action-free-recognition).
|
|
12
19
|
- Action context methods in [actions.md](actions.md).
|
|
13
20
|
- `Flexr::Runtime::Token`, `Flexr::Runtime::Location`, `Flexr::LexError`,
|
|
14
21
|
`Flexr::CompileError`, `Flexr::UnsupportedRegexpError`, and
|
data/docs/reference/regexp.md
CHANGED
|
@@ -27,7 +27,7 @@ byte-oriented automaton. All matches start at the current lexer position.
|
|
|
27
27
|
| `\X` | Unsupported | Use the ASCII-only standalone token example in `FLEXR-E014` where applicable; Unicode graphemes need separate segmentation |
|
|
28
28
|
| Lazy or possessive quantifiers | Unsupported | For unescaped single-line quoted text, use `/"[^"\n]*"/`; other patterns need a separate rewrite |
|
|
29
29
|
| Atomic groups | Unsupported | Use the delimited-text example in `FLEXR-E014` where applicable; removing atomic groups can change matches |
|
|
30
|
-
| Named
|
|
30
|
+
| Named groups `(?<name>...)` and `(?'name'...)` | Supported | Read values from `captures` in rule actions |
|
|
31
31
|
| Conditional groups | Unsupported | Use the finite alternatives shown by `FLEXR-E014` where applicable, or separate rules and state checks |
|
|
32
32
|
| Absence groups `(?~X)` | Supported | Rule patterns require a longest-match backend. See [absence groups](#absence-groups) |
|
|
33
33
|
|
|
@@ -80,6 +80,29 @@ See [ADR 0028](../adr/0028-dfa-absence-groups.md) for the compilation strategy.
|
|
|
80
80
|
|
|
81
81
|
## Captures
|
|
82
82
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
83
|
+
A rule action can read named groups from the winning regexp.
|
|
84
|
+
|
|
85
|
+
```ruby
|
|
86
|
+
rule(/(?<integer>[0-9]+)\.(?<fraction>[0-9]+)/) do
|
|
87
|
+
emit :DECIMAL, [captures[:integer], captures[:fraction]]
|
|
88
|
+
end
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`captures` returns a frozen hash with symbol keys and frozen string values.
|
|
92
|
+
An optional group that did not participate has the value `nil`.
|
|
93
|
+
Actions for other patterns and EOF receive an empty hash.
|
|
94
|
+
|
|
95
|
+
Longest-match backends select the rule and its body before Ruby's regexp
|
|
96
|
+
engine resolves the groups within that body. Ambiguous groups follow
|
|
97
|
+
Ruby's capture rules. `firstmatch` uses the captures from its selected native
|
|
98
|
+
match. If two patterns of the same rule accept the winning body, the first
|
|
99
|
+
eligible pattern supplies the captures.
|
|
100
|
+
|
|
101
|
+
The body excludes `followed_by:` and any prefix accumulated by `more`.
|
|
102
|
+
Calling `less` changes the token text and position while captures still
|
|
103
|
+
describe the original body. Groups in pattern algebra and trailing context
|
|
104
|
+
affect matching and produce no entries in `captures`.
|
|
105
|
+
|
|
106
|
+
Unnamed groups are treated as grouping syntax and produce `FLEXR-W013`.
|
|
107
|
+
Backreferences and calls to capture groups still report `FLEXR-E014`.
|
|
108
|
+
See [ADR 0038](../adr/0038-replay-named-regexp-captures.md) for the extraction strategy.
|
data/docs/reference/ruby-lsp.md
CHANGED
|
@@ -20,6 +20,21 @@ warnings, counterexamples, and overlap information. Diagnostics and hovers
|
|
|
20
20
|
use the static reader: they do not evaluate specifications or run actions.
|
|
21
21
|
Syntax errors are reported by Ruby LSP's Prism integration.
|
|
22
22
|
|
|
23
|
+
## Navigation and completion
|
|
24
|
+
|
|
25
|
+
- Go to Definition jumps from literal state names in `begin_state`, `push`,
|
|
26
|
+
`push_state`, and `self.state =` inside lexer actions to their `state` blocks.
|
|
27
|
+
- Completion suggests token symbols in `emit :PREFIX` and `emit: :PREFIX`.
|
|
28
|
+
Suggestions come from literal `emits` declarations, other shorthand
|
|
29
|
+
rules, and keyword tables in the same lexer. Ruby LSP identifies the call
|
|
30
|
+
under the cursor, so completion may omit calls with ambiguous literal
|
|
31
|
+
value arguments.
|
|
32
|
+
- The document outline shows rules and nested lexical state blocks under
|
|
33
|
+
the lexer class. Select an entry to jump to its pattern or state name.
|
|
34
|
+
|
|
35
|
+
Navigation uses the unsaved `.flexr.rb` buffer and Prism's recovered syntax
|
|
36
|
+
tree. It is available while an action is unfinished.
|
|
37
|
+
|
|
23
38
|
The add-on uses the same static specification subset as `flexr check`, so
|
|
24
39
|
dynamic Ruby DSL construction must be checked separately. Compilation is
|
|
25
40
|
cached for the most recent document contents. Timing-dependent `FLEXR-W016`
|
data/docs/reference/runtime.md
CHANGED
|
@@ -31,11 +31,11 @@ must be positive.
|
|
|
31
31
|
|
|
32
32
|
| Method | Result |
|
|
33
33
|
|---|---|
|
|
34
|
-
| `next_token` | One default-channel token, or `nil` at EOF |
|
|
34
|
+
| `next_token(expect: nil)` | One default-channel token, or `nil` at EOF |
|
|
35
35
|
| `tokens(channels: :default)` | Array containing the remaining default-channel tokens |
|
|
36
36
|
| `tokens(channels: :all)` | Array containing the remaining tokens from every channel in input order |
|
|
37
37
|
| `each_token` | Enumerator without a block; otherwise yields tokens and returns `self` |
|
|
38
|
-
| `racc_next_token` | `[type, value]`, or `[false, "$end"]` at EOF |
|
|
38
|
+
| `racc_next_token(expect: nil)` | `[type, value]`, or `[false, "$end"]` at EOF |
|
|
39
39
|
| `input` | The currently retained input string |
|
|
40
40
|
| `buffer` | Internal buffered input object; use only for integrations that need it |
|
|
41
41
|
| `filename` | The configured filename |
|
|
@@ -49,6 +49,133 @@ selected. `tokens` always returns an array of token values.
|
|
|
49
49
|
With trivia channels, `each_token` and `racc_next_token` expose the default
|
|
50
50
|
channel just like `next_token`. Collect all channels from a fresh lexer to
|
|
51
51
|
preserve the full stream. A lexer instance advances as tokens are consumed.
|
|
52
|
+
When a rule delegates, its child contributes the default-channel token stream.
|
|
53
|
+
Structured delegated tokens preserve the child's attached trivia.
|
|
54
|
+
Checkpoints include queued child tokens. Seeking clears that queue.
|
|
55
|
+
|
|
56
|
+
## Parser token expectations
|
|
57
|
+
|
|
58
|
+
Pass an array of token Symbols as `expect:` to select rules for one token
|
|
59
|
+
request. A rule with `emit:` is eligible when its type is expected. For a
|
|
60
|
+
keyword-table rule, flexr checks the exact spelling at each candidate's end
|
|
61
|
+
and uses the resulting type. A rule with `emits:` is eligible when any of its
|
|
62
|
+
declared types is expected. Skip and trivia rules and action blocks without
|
|
63
|
+
annotations remain eligible. Use `nil` to make every rule eligible.
|
|
64
|
+
|
|
65
|
+
Flexr applies the backend's usual ordering to eligible matches. For a
|
|
66
|
+
longest-match lexer this includes trailing context and the usual tie
|
|
67
|
+
breakers. A `firstmatch` lexer retains Ruby regexp alternative order and rule
|
|
68
|
+
order. If no eligible rule matches input, normal error recovery applies.
|
|
69
|
+
EOF actions also retain their normal behavior.
|
|
70
|
+
|
|
71
|
+
Expectations restrict rule selection. A dynamic action can still emit any
|
|
72
|
+
type it chooses, and a parser can validate the returned token in its current
|
|
73
|
+
state. An empty array leaves skip, trivia, and unannotated rules eligible.
|
|
74
|
+
|
|
75
|
+
In an indentation lexer, newline rules and configured bracket lexemes
|
|
76
|
+
remain eligible. When the parser requests an indent or dedent, the lexer
|
|
77
|
+
can use ordinary rule selection for the first content token of the line.
|
|
78
|
+
That token stays queued while the lexer returns the layout tokens. A later
|
|
79
|
+
expectation applies when the lexer scans new input.
|
|
80
|
+
See [Ruby slash and JavaScript template examples](../how-to/parser-driven-lexing.md).
|
|
81
|
+
|
|
82
|
+
## Indentation tokens
|
|
83
|
+
|
|
84
|
+
Use [`indentation`](dsl.md) to insert layout tokens as the lexer reads the
|
|
85
|
+
first visible token of each line. Spaces and tabs establish an indentation
|
|
86
|
+
width even when their rules skip them or send them to a trivia channel. The
|
|
87
|
+
first line starts at width zero and can introduce an indent. A dedent must
|
|
88
|
+
return to a previous width, or the lexer raises `Flexr::LexError` at the
|
|
89
|
+
first visible token of the line.
|
|
90
|
+
|
|
91
|
+
Blank lines, comment-only lines, and newlines inside configured brackets
|
|
92
|
+
yield no newline or layout tokens. A matching closing bracket resumes
|
|
93
|
+
layout processing on the next line. Trivia attached to a suppressed newline
|
|
94
|
+
carries forward to the next visible token. With `tokens(channels: :all)`,
|
|
95
|
+
trivia tokens remain visible and layout still uses the default-channel stream.
|
|
96
|
+
|
|
97
|
+
Layout tokens have a `nil` value. With `token_kind :struct`, they have a
|
|
98
|
+
zero-width location at the first visible token of the line. The lexer reads
|
|
99
|
+
that token before returning the layout tokens. At EOF, outstanding dedents
|
|
100
|
+
have a zero-width location at the end of the input and precede ordinary
|
|
101
|
+
tokens emitted by an `on_eof` action. An EOF action can emit the configured
|
|
102
|
+
newline to close the last line before the dedents. EOF adds no implicit newline.
|
|
103
|
+
|
|
104
|
+
## Checkpoint and seek
|
|
105
|
+
|
|
106
|
+
Use these methods between token reads.
|
|
107
|
+
|
|
108
|
+
| Method | Result |
|
|
109
|
+
|---|---|
|
|
110
|
+
| `checkpoint` | An immutable, opaque bookmark for this lexer |
|
|
111
|
+
| `restore(bookmark)` | Restores the bookmark and returns the lexer |
|
|
112
|
+
| `seek(byte_position)` | Moves to an absolute byte offset and returns the lexer |
|
|
113
|
+
|
|
114
|
+
A bookmark includes the cursor and its line and column, the lexical state and
|
|
115
|
+
stack, any buffered token or accumulated `more` text, and EOF and halt state.
|
|
116
|
+
Replay runs the same actions again. Application state and mutable token
|
|
117
|
+
values stay under the caller's control. Keep the input bytes unchanged while
|
|
118
|
+
using a bookmark. The work counter continues to count actual scanning work.
|
|
119
|
+
|
|
120
|
+
`seek` recalculates line, column, and start-of-line status without running
|
|
121
|
+
rules. It keeps the selected state and stack and clears the previous match,
|
|
122
|
+
pending token, accumulated text, halt state, and per-state EOF bookkeeping.
|
|
123
|
+
The next read can run an EOF action again.
|
|
124
|
+
|
|
125
|
+
For IO, both methods use the bytes the lexer already has. Checkpoints allow
|
|
126
|
+
the lexer to release bytes according to `retain_input`. Restore raises
|
|
127
|
+
`RangeError` if its cursor or accumulated text has been discarded. Seek
|
|
128
|
+
requires a retained byte offset with known coordinates. Its coordinate origin
|
|
129
|
+
is the current cursor, the beginning of the input when retained, or the start
|
|
130
|
+
of retained `more` text. Seek raises `RangeError` outside that range and
|
|
131
|
+
`ArgumentError` at an interior UTF-8 byte or a buffered edge with an
|
|
132
|
+
incomplete scalar. A bookmark from another lexer also raises `ArgumentError`.
|
|
133
|
+
On a lexer with an input stack, `seek` addresses the active input. A bookmark
|
|
134
|
+
can be restored only while its original input is active. It records the cursor
|
|
135
|
+
and playback state for that input.
|
|
136
|
+
|
|
137
|
+
An indentation lexer includes pending layout tokens and levels in its
|
|
138
|
+
checkpoint. `seek(0)` clears that layout state. Use a checkpoint to restore
|
|
139
|
+
another offset because its layout depends on preceding tokens.
|
|
140
|
+
|
|
141
|
+
## Action-free recognition
|
|
142
|
+
|
|
143
|
+
Use `Lexer.recognizer(state: :initial)` to obtain a reusable, immutable
|
|
144
|
+
`Flexr::Recognizer` for one lexical state. Runtime, generated, and
|
|
145
|
+
standalone lexers expose the same API.
|
|
146
|
+
|
|
147
|
+
```ruby
|
|
148
|
+
recognizer = GrammarLexer.recognizer
|
|
149
|
+
rule, finish = recognizer.match("word", 0) # [:IDENTIFIER, 4]
|
|
150
|
+
|
|
151
|
+
recognizer.match("word", 0) do |identity, ending|
|
|
152
|
+
consume_match(identity, ending)
|
|
153
|
+
end
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The matcher starts at the given byte offset and returns the rule identity
|
|
157
|
+
and exclusive end byte. The identity is the symbol declared with `emit:`
|
|
158
|
+
or the zero-based source-rule index for other rules, including skips.
|
|
159
|
+
Keyword classification and dynamic actions belong to token emission.
|
|
160
|
+
Recognition reads the compiled tables without running actions, updating
|
|
161
|
+
state, or constructing a lexer instance.
|
|
162
|
+
|
|
163
|
+
Longest match includes trailing context when ranking rules, and `finish`
|
|
164
|
+
excludes the lookahead. Line anchors use the original string. UTF-8
|
|
165
|
+
recognition respects full scalar boundaries. Binary recognition operates on
|
|
166
|
+
bytes. A no-match result or an offset at EOF returns `nil`. A non-EOF
|
|
167
|
+
zero-width match requires `allow_empty_match` and can return the incoming
|
|
168
|
+
offset, so the caller controls progress.
|
|
169
|
+
|
|
170
|
+
The block form yields both fields and returns the block's result. It avoids
|
|
171
|
+
allocating the result array. A recognizer is shareable across Ractors after
|
|
172
|
+
construction. Build it once and reuse it for matching.
|
|
173
|
+
|
|
174
|
+
Construction accepts `table`, `direct`, and `auto` lexers and raises
|
|
175
|
+
`ArgumentError` for `firstmatch` or an unknown state. `match` requires a
|
|
176
|
+
`String` and an `Integer` byte offset. An offset outside the input raises
|
|
177
|
+
`RangeError`. Use `Lexer.new` for streaming, recovery, and lexer-instance
|
|
178
|
+
limits.
|
|
52
179
|
|
|
53
180
|
## State and action context
|
|
54
181
|
|
|
@@ -68,3 +195,37 @@ match; `input` and `binary_input` then expose only the retained window.
|
|
|
68
195
|
oversized match. `max_lookahead_size` separately bounds trailing context, and
|
|
69
196
|
`max_buffer_size` bounds bytes retained at one time. `max_steps` and
|
|
70
197
|
`cancellation` bound CPU work cooperatively.
|
|
198
|
+
|
|
199
|
+
## Input stack
|
|
200
|
+
|
|
201
|
+
`push_input(input, filename: nil)` accepts a `String` or an object responding
|
|
202
|
+
to `read`. The lexer enters it at the next token boundary. A rule action can
|
|
203
|
+
queue an input and still emit a token using the current source and location.
|
|
204
|
+
|
|
205
|
+
```ruby
|
|
206
|
+
rule("@defaults") do
|
|
207
|
+
push_input("enabled = true\n", filename: "defaults")
|
|
208
|
+
end
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Each included input starts in `:initial` with an empty lexical state stack,
|
|
212
|
+
byte offset 0, and line and column 1. The given filename appears in its
|
|
213
|
+
token locations and lexical errors. Its normal `on_eof` action can emit
|
|
214
|
+
a token. Once that action finishes, the lexer resumes the suspended input
|
|
215
|
+
position, lexical stack, and accumulated text. If several inputs are queued
|
|
216
|
+
for the same boundary, the last one pushed is read first.
|
|
217
|
+
|
|
218
|
+
With indentation enabled, each input starts with a fresh layout stack.
|
|
219
|
+
A child emits its final dedents at its own EOF, before the lexer restores
|
|
220
|
+
the parent's indentation levels and bracket state. Any explicit child
|
|
221
|
+
EOF token follows the child's dedents, just as it does at root EOF.
|
|
222
|
+
|
|
223
|
+
Buffer and token limits apply to each input, and the work budget and error
|
|
224
|
+
policy are shared by the lexer. Invalid inputs and oversized strings fail
|
|
225
|
+
when pushed. IO is read lazily, so leave it open until the lexer has consumed
|
|
226
|
+
it. The caller owns the IO. A read error propagates while the failed input
|
|
227
|
+
is active.
|
|
228
|
+
|
|
229
|
+
Standalone generation embeds the input stack if the lexer source calls
|
|
230
|
+
`push_input`. Add `option :input_stack` when only external code or an
|
|
231
|
+
indirect call pushes inputs.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Build a calculator parser in five minutes
|
|
2
|
+
|
|
3
|
+
Start with Ruby 3.4 or later, Bundler, and a version of flexr that provides
|
|
4
|
+
`flexr new --help`. Choose one parser and run its commands in the directory
|
|
5
|
+
where you want the new project.
|
|
6
|
+
|
|
7
|
+
## Racc
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
flexr new my-calculator --parser racc
|
|
11
|
+
cd my-calculator
|
|
12
|
+
bundle install
|
|
13
|
+
bundle exec rake test
|
|
14
|
+
bundle exec ruby calculator.rb '12 + 3 - 4'
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The calculator prints `11`. Racc generates a Ruby parser that pulls one
|
|
18
|
+
token and value at a time from the Flexr lexer.
|
|
19
|
+
|
|
20
|
+
## Lrama
|
|
21
|
+
|
|
22
|
+
Install a C compiler and make it available as `cc`, or set `CC` to its
|
|
23
|
+
executable.
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
flexr new my-calculator --parser lrama
|
|
27
|
+
cd my-calculator
|
|
28
|
+
bundle install
|
|
29
|
+
bundle exec rake test
|
|
30
|
+
bundle exec ruby calculator.rb '12 + 3 - 4'
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The calculator prints `11`. Lrama generates a C parser. The Ruby driver
|
|
34
|
+
starts the compiled parser and sends it the tokens produced by Flexr.
|
|
35
|
+
This calculator accepts integer tokens and results in the signed 64-bit
|
|
36
|
+
range.
|
|
37
|
+
|
|
38
|
+
## Change the grammar
|
|
39
|
+
|
|
40
|
+
Start with `lexer.flexr.rb` to see how input becomes `INTEGER`, `PLUS`, and
|
|
41
|
+
`MINUS` tokens. Open `parser.y` to see the rules that combine those tokens
|
|
42
|
+
into an expression. When adding an operator, declare the same token name in
|
|
43
|
+
both files and add an example to `test_calculator.rb`.
|
|
44
|
+
|
|
45
|
+
Run `bundle exec rake test` after each change. It rebuilds the parser when
|
|
46
|
+
the grammar changes. Run `bundle exec rake build` to rebuild without running
|
|
47
|
+
the tests.
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## What this example demonstrates
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
The lexer declares grammar-facing names with `emits`. The example runs the
|
|
6
|
+
Ruby lexer and shows the token kinds and values available to a parser.
|
|
7
7
|
|
|
8
8
|
## Run and validate
|
|
9
9
|
|
|
@@ -14,4 +14,4 @@ flexr check examples/with_lrama/lexer.flexr.rb --format json
|
|
|
14
14
|
```
|
|
15
15
|
|
|
16
16
|
See the [Lrama integration guide](../../docs/how-to/integrate-with-lrama.md)
|
|
17
|
-
for the
|
|
17
|
+
for the C parser build flow and a complete calculator project.
|
|
@@ -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 rules.any?(&:capture_patterns)
|
|
26
27
|
return if defined?(Pattern) && rules.any? { |rule| rule.patterns.any?(Pattern) }
|
|
27
28
|
return if dfa.accepts.any? { |acceptances| acceptances.any? { |item| item.bol_only || item.end_anchor } }
|
|
28
29
|
|
|
@@ -390,6 +390,7 @@ module Flexr
|
|
|
390
390
|
next unless regexp.is_a?(::Regexp)
|
|
391
391
|
|
|
392
392
|
ast = parse_regexp(regexp)
|
|
393
|
+
prepare_capture_pattern(rule, index, regexp) unless regexp.names.empty?
|
|
393
394
|
has_absence = Regexp::AST.absence?(ast)
|
|
394
395
|
if has_absence && @spec.backend == :firstmatch
|
|
395
396
|
diagnostic = Diagnostics.error("FLEXR-E014", "absence groups in rule patterns require a longest-match backend",
|
|
@@ -407,6 +408,20 @@ module Flexr
|
|
|
407
408
|
end
|
|
408
409
|
end
|
|
409
410
|
|
|
411
|
+
def prepare_capture_pattern(rule, index, regexp)
|
|
412
|
+
encoding = regexp.encoding == Encoding::BINARY ? Encoding::BINARY : @spec.encoding
|
|
413
|
+
pattern = if @spec.backend == :firstmatch
|
|
414
|
+
regexp
|
|
415
|
+
else
|
|
416
|
+
Unicode::ReferenceRegexp.compiled(regexp, encoding: encoding, unicode: @spec.options[:unicode] == true, anchored: true)
|
|
417
|
+
end
|
|
418
|
+
(rule.capture_patterns ||= [])[index] = pattern
|
|
419
|
+
rescue RegexpError, EncodingError => e
|
|
420
|
+
diagnostic = Diagnostics.error("FLEXR-E014", "cannot replay named captures with Ruby",
|
|
421
|
+
note: e.message, help: "split the rule or use non-capturing groups")
|
|
422
|
+
raise UnsupportedRegexpError.new(diagnostic.message, diagnostic: diagnostic)
|
|
423
|
+
end
|
|
424
|
+
|
|
410
425
|
def validate_pattern_body(pattern, rule, index)
|
|
411
426
|
if @spec.backend == :firstmatch
|
|
412
427
|
diagnostic = Diagnostics.error("FLEXR-E014", "pattern values in rule bodies require a longest-match backend",
|
data/lib/flexr/automaton/dfa.rb
CHANGED
|
@@ -153,38 +153,5 @@ module Flexr
|
|
|
153
153
|
representation.freeze
|
|
154
154
|
end
|
|
155
155
|
end
|
|
156
|
-
|
|
157
|
-
class ReferenceDFA
|
|
158
|
-
def initialize(regexp, unicode: false)
|
|
159
|
-
source, options = if reference_pattern?(regexp, unicode: unicode)
|
|
160
|
-
converted = Unicode::ReferenceRegexp.compiled(
|
|
161
|
-
regexp, encoding: regexp.encoding, options: regexp.options, unicode: unicode
|
|
162
|
-
)
|
|
163
|
-
[converted.source, converted.options]
|
|
164
|
-
else
|
|
165
|
-
[regexp.source, regexp.options]
|
|
166
|
-
end
|
|
167
|
-
@regexp = ::Regexp.new("\\A(?:#{source})\\z", options)
|
|
168
|
-
end
|
|
169
|
-
|
|
170
|
-
def accept?(bytes)
|
|
171
|
-
data = bytes.dup.force_encoding(@regexp.encoding)
|
|
172
|
-
@regexp.match?(data)
|
|
173
|
-
rescue ArgumentError, EncodingError
|
|
174
|
-
false
|
|
175
|
-
end
|
|
176
|
-
|
|
177
|
-
def stats
|
|
178
|
-
{ states: 0, classes: 0, accepting_states: 0, reference: true }
|
|
179
|
-
end
|
|
180
|
-
|
|
181
|
-
private
|
|
182
|
-
|
|
183
|
-
def reference_pattern?(regexp, unicode: false)
|
|
184
|
-
return true if regexp.source.match?(/\\[pP]\{/) || regexp.source.match?(/\[:(?:\^)?[a-z]+:\]/)
|
|
185
|
-
|
|
186
|
-
unicode && regexp.encoding != Encoding::BINARY && regexp.source.match?(/\\[dDwWsS]/)
|
|
187
|
-
end
|
|
188
|
-
end
|
|
189
156
|
end
|
|
190
157
|
end
|
|
@@ -51,6 +51,19 @@ module Flexr
|
|
|
51
51
|
end
|
|
52
52
|
|
|
53
53
|
def grouping_suggestions(compiled, tables)
|
|
54
|
+
grouping_candidates(compiled, tables).map do |literals, rule|
|
|
55
|
+
among = rule.action[1]
|
|
56
|
+
spellings = literals.map { |literal| literal.patterns.first }.uniq
|
|
57
|
+
Diagnostics.info(
|
|
58
|
+
"FLEXR-I003", "#{literals.length} consecutive literal rules can share an identifier rule",
|
|
59
|
+
location: literals.first.location,
|
|
60
|
+
help: "replace them with keywords #{spellings.inspect}, among: #{among.inspect}",
|
|
61
|
+
note: "input #{spellings.first.inspect} also matches rule #{rule.index}"
|
|
62
|
+
)
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def grouping_candidates(compiled, tables)
|
|
54
67
|
pending = []
|
|
55
68
|
compiled.rules.filter_map do |rule|
|
|
56
69
|
if literal_keyword?(rule)
|
|
@@ -62,14 +75,7 @@ module Flexr
|
|
|
62
75
|
pending = []
|
|
63
76
|
next unless literals.length >= 2 && groupable?(compiled, rule, literals, tables)
|
|
64
77
|
|
|
65
|
-
|
|
66
|
-
spellings = literals.map { |literal| literal.patterns.first }.uniq
|
|
67
|
-
Diagnostics.info(
|
|
68
|
-
"FLEXR-I003", "#{literals.length} consecutive literal rules can share an identifier rule",
|
|
69
|
-
location: literals.first.location,
|
|
70
|
-
help: "replace them with keywords #{spellings.inspect}, among: #{among.inspect}",
|
|
71
|
-
note: "input #{spellings.first.inspect} also matches rule #{rule.index}"
|
|
72
|
-
)
|
|
78
|
+
[literals, rule]
|
|
73
79
|
end
|
|
74
80
|
end
|
|
75
81
|
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Flexr
|
|
4
|
+
module Automaton
|
|
5
|
+
class ReferenceDFA
|
|
6
|
+
def initialize(regexp, unicode: false)
|
|
7
|
+
source, options = if reference_pattern?(regexp, unicode: unicode)
|
|
8
|
+
converted = Unicode::ReferenceRegexp.compiled(
|
|
9
|
+
regexp, encoding: regexp.encoding, options: regexp.options, unicode: unicode
|
|
10
|
+
)
|
|
11
|
+
[converted.source, converted.options]
|
|
12
|
+
else
|
|
13
|
+
[regexp.source, regexp.options]
|
|
14
|
+
end
|
|
15
|
+
@regexp = ::Regexp.new("\\A(?:#{source})\\z", options)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def accept?(bytes)
|
|
19
|
+
data = bytes.dup.force_encoding(@regexp.encoding)
|
|
20
|
+
@regexp.match?(data)
|
|
21
|
+
rescue ArgumentError, EncodingError
|
|
22
|
+
false
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def stats
|
|
26
|
+
{ states: 0, classes: 0, accepting_states: 0, reference: true }
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def reference_pattern?(regexp, unicode: false)
|
|
32
|
+
return true if regexp.source.match?(/\\[pP]\{/) || regexp.source.match?(/\[:(?:\^)?[a-z]+:\]/)
|
|
33
|
+
|
|
34
|
+
unicode && regexp.encoding != Encoding::BINARY && regexp.source.match?(/\\[dDwWsS]/)
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|