flexr 1.2.0 → 2.0.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/.rubocop.yml +1 -1
- data/CHANGELOG.md +26 -26
- data/CONTRIBUTING.md +38 -7
- data/README.md +4 -7
- data/Rakefile +150 -63
- data/benchmark/baselines/json.json +2 -2
- data/benchmark/golden/calculator_lexer.rb +15 -15
- data/benchmark/golden/graphql_lexer.rb +3 -3
- data/benchmark/golden/json_lexer.rb +25 -25
- data/benchmark/golden/regexp_tokenizer.rb +23 -23
- data/benchmark/golden/ruby_subset_lexer.rb +3 -3
- data/benchmark/golden/sql_lexer.rb +3 -3
- data/benchmark/golden/toml_lexer.rb +3 -3
- data/benchmark/golden/toy_lang_lexer.rb +9 -9
- data/benchmark/golden/with_lrama_lexer.rb +3 -3
- data/benchmark/golden/with_racc_lexer.rb +3 -3
- data/docs/RELEASING.md +1 -7
- data/docs/explanation/backends.md +17 -0
- data/docs/how-to/deploy-a-standalone-lexer.md +1 -1
- data/docs/how-to/tune-performance.md +12 -0
- data/docs/migration-v2.md +3 -2
- data/docs/perf-log.md +88 -0
- data/docs/reference/cli.md +1 -1
- data/docs/reference/compatibility.md +7 -8
- data/docs/reference/dsl.md +4 -0
- data/docs/reference/generated-artifacts.md +31 -4
- data/docs/reference/public-api.md +5 -4
- data/docs/reference/runtime.md +2 -2
- data/docs/reference/tokens-and-locations.md +8 -0
- data/examples/json/lexer.flexr.rb +6 -6
- data/lib/flexr/automaton/accel.rb +58 -0
- data/lib/flexr/automaton/compiler.rb +4 -1
- data/lib/flexr/automaton/types.rb +1 -1
- data/lib/flexr/codegen/table.rb +6 -0
- data/lib/flexr/dsl.rb +2 -1
- data/lib/flexr/generated.rb +43 -7
- data/lib/flexr/generator.rb +21 -8
- data/lib/flexr/minitest.rb +4 -4
- data/lib/flexr/regexp/tokenizer.rb +24 -24
- data/lib/flexr/runtime/core.rb +28 -4
- data/lib/flexr/runtime/interpreter.rb +8 -1
- data/lib/flexr/runtime/location.rb +35 -13
- data/lib/flexr/runtime/record.rb +14 -0
- data/lib/flexr/runtime/token.rb +7 -2
- data/lib/flexr/runtime.rb +3 -2
- data/lib/flexr/source/prism_reader.rb +8 -2
- data/lib/flexr/unicode/property.rb +1 -2
- data/lib/flexr/unicode/reference_regexp.rb +1 -2
- data/lib/flexr/version.rb +1 -1
- data/sig/flexr.rbs +18 -12
- data/site/README.md +54 -3
- data/site/astro.config.mjs +3 -1
- data/site/package.json +12 -5
- data/site/playwright.config.mjs +16 -0
- data/site/pnpm-lock.yaml +218 -88
- data/site/ruby/playground.rb +57 -0
- data/site/scripts/prepare-playground.mjs +35 -0
- data/site/scripts/verify-site.mjs +5 -3
- data/site/src/content/docs/concepts/matching-semantics.md +4 -2
- data/site/src/content/docs/concepts/security-model.md +9 -1
- data/site/src/content/docs/learn/generation.md +1 -1
- data/site/src/content/docs/reference/dsl.md +2 -2
- data/site/src/content/docs/reference/public-api.md +4 -2
- data/site/src/content/docs/reference/tokens-and-locations.md +3 -0
- data/site/src/layouts/SiteLayout.astro +3 -1
- data/site/src/pages/playground.astro +40 -38
- data/site/src/playground/client.js +211 -0
- data/site/src/playground/graph-worker.mjs +11 -0
- data/site/src/playground/presets.mjs +33 -0
- data/site/src/playground/runtime.mjs +34 -0
- data/site/src/playground/share.mjs +30 -0
- data/site/src/playground/worker.mjs +29 -0
- data/site/src/styles/custom.css +8 -0
- data/site/tests/browser/playground.spec.mjs +99 -0
- data/site/tests/playground-runtime.test.mjs +85 -0
- data/tools/docs_verify.rb +2 -2
- data/tools/verification_failure.rb +119 -0
- metadata +17 -7
- data/lib/flexr/deprecations.rb +0 -26
- data/site/public/playground.js +0 -189
- data/tools/release_notes.rb +0 -16
|
@@ -16,7 +16,7 @@ can be loaded by a Ruby process that does not have the flexr gem installed:
|
|
|
16
16
|
ruby -e 'load ARGV.fetch(0); p Lexer.new("12").tokens' lexer_standalone.rb
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
Generation still needs the flexr gem and Prism on Ruby 3.
|
|
19
|
+
Generation still needs the flexr gem and Prism on Ruby 3.4 or newer. Runtime
|
|
20
20
|
execution needs the generated file and Ruby's standard library only.
|
|
21
21
|
|
|
22
22
|
Standalone output is larger and duplicates the runtime for every artifact.
|
|
@@ -13,11 +13,23 @@ application startup. `backend :auto` compares dense memory, packed memory, and
|
|
|
13
13
|
lookup costs rather than using a fixed table-size threshold; `:table` and
|
|
14
14
|
`:direct` preserve the same longest-match semantics.
|
|
15
15
|
|
|
16
|
+
Use `emit:` for tokens whose value is the unchanged matched text. For example,
|
|
17
|
+
`rule(/:/, emit: :COLON)` avoids invoking an action block for every separator.
|
|
18
|
+
Keep blocks for value conversions and state transitions. The JSON example
|
|
19
|
+
uses this form for punctuation.
|
|
20
|
+
|
|
16
21
|
Acceleration is an optimization over the DFA, not a second matcher. `accel
|
|
17
22
|
:auto` selects an available safe path, while `:strscan`, `:regexp`, and `:none`
|
|
18
23
|
make the choice explicit. Trailing context disables region acceleration for the
|
|
19
24
|
affected rule and emits `FLEXR-W012` unless acceleration is disabled.
|
|
20
25
|
|
|
26
|
+
Explicit `accel :strscan` can also scan a complete token in one native call
|
|
27
|
+
when a conservative DFA check proves it safe. This path needs frozen String
|
|
28
|
+
input with retained bytes and no active scanning or token-size guard. Streaming
|
|
29
|
+
and mutable input, anchors, trailing context, and unproven patterns keep the DFA
|
|
30
|
+
path. Measure with your actual token lengths and Ruby/JIT configuration before
|
|
31
|
+
choosing `:strscan`; `:auto` keeps its region-selection policy.
|
|
32
|
+
|
|
21
33
|
The [performance log](../perf-log.md) records reproducible local observations,
|
|
22
34
|
and the [backend explanation](../explanation/backends.md) describes the memory
|
|
23
35
|
and compatibility trade-offs.
|
data/docs/migration-v2.md
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# Migrating to flexr 2.0
|
|
2
2
|
|
|
3
|
-
This guide describes
|
|
4
|
-
opt-in deprecation warnings
|
|
3
|
+
This guide describes the v2 prerelease. The preceding v1 preparation release
|
|
4
|
+
keeps existing behavior and offers opt-in deprecation warnings. In v2 the
|
|
5
|
+
contracts below are enforced and those preparation warnings are removed.
|
|
5
6
|
|
|
6
7
|
Run static checks before upgrading:
|
|
7
8
|
|
data/docs/perf-log.md
CHANGED
|
@@ -178,3 +178,91 @@ following instrumented times:
|
|
|
178
178
|
Scanning is the largest category in this instrumented sample, followed by token
|
|
179
179
|
handling. These categories identify work to investigate; they do not establish
|
|
180
180
|
uninstrumented phase percentages or prove a particular optimization will help.
|
|
181
|
+
## 2026-11-20: whole-token acceleration
|
|
182
|
+
|
|
183
|
+
Ruby 4.0.9 on arm64-darwin-25, the default 140,000-byte JSON corpus, 50,000
|
|
184
|
+
emitted tokens, and five warmup plus five measured iterations produced these
|
|
185
|
+
sequential local samples. The control checkout was `0391a6e`. The explicit
|
|
186
|
+
StringScanner variant adds only `accel :strscan` to the JSON specification.
|
|
187
|
+
|
|
188
|
+
| accelerator | engine | runtime MB/s before → after | generated MB/s before → after | allocations/token after, runtime / generated |
|
|
189
|
+
|---|---|---:|---:|---:|
|
|
190
|
+
| auto | interpreter | 1.739 → 1.856 | 1.645 → 1.815 | 4.200 / 4.210 |
|
|
191
|
+
| auto | YJIT | 4.967 → 5.210 | 2.977 → 3.184 | 4.200 / 4.210 |
|
|
192
|
+
| auto | ZJIT | 1.301 → 2.119 | 0.373 → 0.441 | 4.200 / 4.210 |
|
|
193
|
+
| strscan | interpreter | 1.767 → 1.973 | 0.785 → 1.090 | 4.200 / 4.610 |
|
|
194
|
+
| strscan | YJIT | 4.983 → 5.182 | 1.224 → 1.633 | 4.200 / 4.610 |
|
|
195
|
+
| strscan | ZJIT | 2.029 → 1.838 | 0.875 → 0.791 | 4.200 / 4.610 |
|
|
196
|
+
|
|
197
|
+
The default mode's change removes temporary ranges when extracting text and
|
|
198
|
+
location spans. Its allocations fell from 5.200 / 5.210. Explicit StringScanner
|
|
199
|
+
mode also uses proven whole-token scans; its generated allocations fell from
|
|
200
|
+
6.210 to 4.610. This does not meet the 4.0 or 3.4 allocation targets. Whole-token
|
|
201
|
+
scanning remains explicit because the ZJIT sample regressed; these samples do
|
|
202
|
+
not establish a universal speedup or a release performance qualification.
|
|
203
|
+
|
|
204
|
+
Reproduce the default sample with:
|
|
205
|
+
|
|
206
|
+
```sh
|
|
207
|
+
ruby -Ilib benchmark/run.rb --iterations 5 --json
|
|
208
|
+
ruby --yjit -Ilib benchmark/run.rb --iterations 5 --json
|
|
209
|
+
ruby --zjit -Ilib benchmark/run.rb --iterations 5 --json
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
To measure explicit StringScanner mode without changing the maintained example:
|
|
213
|
+
|
|
214
|
+
```sh
|
|
215
|
+
mkdir -p tmp/whole-token/examples/json
|
|
216
|
+
ruby -e 'source = File.read("examples/json/lexer.flexr.rb"); File.write("tmp/whole-token/examples/json/lexer.flexr.rb", source.sub("backend :direct", "backend :direct\n accel :strscan"))'
|
|
217
|
+
ruby -Ilib benchmark/run.rb --spec tmp/whole-token/examples/json/lexer.flexr.rb --iterations 5 --json
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Repeat the last command with `--yjit` or `--zjit` immediately after `ruby`.
|
|
221
|
+
|
|
222
|
+
### JSON punctuation with `emit:`
|
|
223
|
+
|
|
224
|
+
Replacing the JSON example's six punctuation action blocks with the existing
|
|
225
|
+
`emit:` option preserved token types and values across runtime, generated,
|
|
226
|
+
standalone, String, and one-byte IO input, including Unicode and escaped quotes.
|
|
227
|
+
The same Ruby 4.0.9 host, default corpus, and five warmup plus five measured
|
|
228
|
+
iterations produced this interpreter sample after the range-allocation change:
|
|
229
|
+
|
|
230
|
+
| mode | MB/s before → after | allocations/token before → after | handwritten ratio before → after |
|
|
231
|
+
|---|---:|---:|---:|
|
|
232
|
+
| runtime | 1.863 → 1.928 | 4.200 → 3.600 | 0.221x → 0.249x |
|
|
233
|
+
| generated | 1.794 → 1.963 | 4.210 → 3.610 | 0.213x → 0.254x |
|
|
234
|
+
|
|
235
|
+
The 4.0 allocations/token target is met for this JSON example; 3.4 and the 0.35x
|
|
236
|
+
throughput target remain unmet. This sample does not establish results for
|
|
237
|
+
other lexers or JIT engines. Conversion actions for strings, numbers, booleans,
|
|
238
|
+
and null remain blocks.
|
|
239
|
+
|
|
240
|
+
The JSON golden digest and regression baseline's source fingerprint were
|
|
241
|
+
updated for the equivalent shorthand specification. Input identity, captured
|
|
242
|
+
baseline metrics, ratio thresholds, and the 0.18x performance floor were kept.
|
|
243
|
+
Use the default benchmark commands above to reproduce the new example.
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
## 2026-11-21: combined v2 readiness sample
|
|
247
|
+
|
|
248
|
+
The integration checkout at `f9c629c` combines the v2 Data records and generated
|
|
249
|
+
method actions with whole-token scanning support and the JSON `emit:` shorthand.
|
|
250
|
+
Ruby 4.0.9 on arm64-darwin-25, without a JIT, processed the default 140,000-byte
|
|
251
|
+
JSON corpus with 50,000 emitted tokens. Five warmup and five measured iterations
|
|
252
|
+
ran after the test and browser checks finished.
|
|
253
|
+
|
|
254
|
+
| mode | MB/s | allocations/token | throughput relative to handwritten |
|
|
255
|
+
|---|---:|---:|---:|
|
|
256
|
+
| runtime | 1.906 | 3.600 | 0.235x |
|
|
257
|
+
| generated | 1.933 | 3.210 | 0.238x |
|
|
258
|
+
| handwritten | 8.118 | 3.400 | 1.000x |
|
|
259
|
+
|
|
260
|
+
Both flexr modes meet the 4.0 allocations/token target for this corpus. The
|
|
261
|
+
3.4 target is met by generated mode; runtime remains above it. Neither mode
|
|
262
|
+
meets the 0.35x handwritten throughput target. This local readiness sample is
|
|
263
|
+
not a release performance qualification and does not establish results for
|
|
264
|
+
other lexers or JIT engines.
|
|
265
|
+
|
|
266
|
+
`rake bench:regression` also passed with the existing baseline metrics, identity,
|
|
267
|
+
ratio thresholds, and 0.18x floor unchanged. Reproduce the five-iteration sample
|
|
268
|
+
with `ruby -Ilib benchmark/run.rb --iterations 5 --json`.
|
data/docs/reference/cli.md
CHANGED
|
@@ -95,7 +95,7 @@ after the action, candidate rule numbers and lengths, the selected rule, and
|
|
|
95
95
|
the action result (`emit` or `skip`). Human candidate lengths use
|
|
96
96
|
`body/total`, with trailing context included only in the total. `rule_order`
|
|
97
97
|
means several candidates tied at the winning total length; `longest` means a
|
|
98
|
-
longer candidate won. `first_match` reports the
|
|
98
|
+
longer candidate won. `first_match` reports the firstmatch backend's rule
|
|
99
99
|
priority and preserves its regexp alternation behavior. `only_match` means
|
|
100
100
|
there was one candidate. EOF actions appear with reason `eof`; recovered
|
|
101
101
|
unmatched bytes appear with reason `unmatched` and no selected rule.
|
|
@@ -4,19 +4,16 @@
|
|
|
4
4
|
|
|
5
5
|
| Surface | Requirement |
|
|
6
6
|
|---|---|
|
|
7
|
-
| Runtime gem | Ruby 3.
|
|
8
|
-
| Generator | Ruby 3.
|
|
7
|
+
| Runtime gem | Ruby 3.4+ |
|
|
8
|
+
| Generator | Ruby 3.4+ with Prism available |
|
|
9
9
|
| Standalone runtime | Compatible Ruby plus the generated file |
|
|
10
10
|
| Optional acceleration | Ruby `strscan` when available; regexp fallback remains valid |
|
|
11
11
|
|
|
12
12
|
Runtime mode does not require Prism. Generated mode uses Prism only while
|
|
13
13
|
reading the source; normal generated output does not need the generator.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
The 1.x series receives fixes for critical bugs and security issues through
|
|
18
|
-
March 31, 2027. Use the [migration guide](../migration-v2.md) to prepare an
|
|
19
|
-
upgrade to 2.0. The 1.x runtime continues to support Ruby 3.1 and later.
|
|
14
|
+
Alternate Ruby implementations must implement Ruby 3.4 before using this
|
|
15
|
+
major version. The former JRuby and TruffleRuby jobs targeting older language
|
|
16
|
+
versions are removed; this does not claim those engines have been verified.
|
|
20
17
|
|
|
21
18
|
## Matching and encoding
|
|
22
19
|
|
|
@@ -39,6 +36,8 @@ Runtime and generated-file compatibility is preserved within a major version
|
|
|
39
36
|
unless a migration is explicitly documented. Generated artifacts include a
|
|
40
37
|
payload digest and Unicode version so stale or cross-version output can be
|
|
41
38
|
detected. Do not assume that internal table layouts are stable.
|
|
39
|
+
Version 2 uses artifact schema 2 and runtime ABI 2. Regenerate v1 artifacts
|
|
40
|
+
after upgrading; incompatible metadata produces `FLEXR-E020`.
|
|
42
41
|
|
|
43
42
|
All four backends are stable. `table`, `direct`, and `auto` use longest-match
|
|
44
43
|
selection; `firstmatch` follows rule and regexp alternative order. It does not
|
data/docs/reference/dsl.md
CHANGED
|
@@ -15,6 +15,10 @@ one rule and share its action.
|
|
|
15
15
|
text as its value. Without either option, the block runs in the lexer instance;
|
|
16
16
|
if no block is given, the default action emits `[nil, text]`.
|
|
17
17
|
|
|
18
|
+
Prefer `emit:` when the value is the unchanged matched text, such as
|
|
19
|
+
`rule(/\+/, emit: :PLUS)`. This avoids executing a Ruby action block for each
|
|
20
|
+
token. Use a block when converting a value or changing lexer state.
|
|
21
|
+
|
|
18
22
|
`followed_by:` accepts a `Regexp` or `String`. It participates in rule
|
|
19
23
|
selection but is not consumed. The method returns `nil`. Rules are numbered in
|
|
20
24
|
source order starting at zero.
|
|
@@ -5,13 +5,40 @@
|
|
|
5
5
|
| Use | Build-time requirement | Runtime requirement |
|
|
6
6
|
|---|---|---|
|
|
7
7
|
| Runtime mode | None beyond the flexr gem | `flexr` gem |
|
|
8
|
-
| Normal generated mode | flexr gem and Prism on Ruby 3.
|
|
9
|
-
| Standalone generated mode | flexr gem and Prism on Ruby 3.
|
|
8
|
+
| Normal generated mode | flexr gem and Prism on Ruby 3.4+ | `flexr` gem and Ruby 3.4+ |
|
|
9
|
+
| Standalone generated mode | flexr gem and Prism on Ruby 3.4+ | Generated file and Ruby 3.4+ standard library |
|
|
10
10
|
|
|
11
|
-
The runtime gem
|
|
12
|
-
supported on Ruby 3.3 and newer. A generated file can be loaded by a compatible
|
|
11
|
+
The runtime gem and generator support Ruby 3.4 and newer. A generated file can be loaded by a compatible
|
|
13
12
|
runtime without the generator installed.
|
|
14
13
|
|
|
14
|
+
Version 2 artifacts use schema 2 and runtime ABI 2. Regenerate v1 generated
|
|
15
|
+
files with the v2 generator. Old metadata is rejected with `FLEXR-E020` when
|
|
16
|
+
loading an artifact into the new runtime.
|
|
17
|
+
|
|
18
|
+
## Ractor sharing
|
|
19
|
+
|
|
20
|
+
Load a generated class in the main Ractor, then explicitly prepare its data:
|
|
21
|
+
|
|
22
|
+
```ruby
|
|
23
|
+
load "lexer.generated.rb"
|
|
24
|
+
Flexr::Generated.shareable!(Lexer)
|
|
25
|
+
worker = Ractor.new(Lexer) { |klass| klass.new("input").tokens }
|
|
26
|
+
tokens = worker.respond_to?(:value) ? worker.value : worker.take
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
This eagerly materializes transition rows and calls `Ractor.make_shareable` on
|
|
30
|
+
the compiled data and configuration. Each Ractor creates its own lexer and
|
|
31
|
+
input. Simple `emit` blocks, `emit:` rules, and `skip:` rules use generated
|
|
32
|
+
methods. Captured closures, runtime specifications, and EOF blocks are rejected
|
|
33
|
+
by `shareable!`; arbitrary user methods must also obey Ruby's Ractor rules.
|
|
34
|
+
`firstmatch` patterns that need the Unicode reference matcher are also rejected
|
|
35
|
+
before preparation, because its shared caches are not Ractor-safe. Use `table`,
|
|
36
|
+
`direct`, or `auto` for those patterns. Local variables that shadow action
|
|
37
|
+
methods such as `text`, `line`, or `lineno` keep their closure bindings and are
|
|
38
|
+
not converted to shareable method actions.
|
|
39
|
+
Preparation may use more memory than lazy packed tables. Call it before
|
|
40
|
+
starting workers; it does not make an existing lexer instance shareable.
|
|
41
|
+
|
|
15
42
|
## Static evaluation boundary
|
|
16
43
|
|
|
17
44
|
The default generator resolves:
|
|
@@ -34,8 +34,9 @@ The gem includes RBS signatures in `sig/flexr.rbs` for the stable API above.
|
|
|
34
34
|
Steep can discover them through an application's RBS collection or an explicit
|
|
35
35
|
`library "flexr"` entry. User-defined token values and internal regexp ASTs
|
|
36
36
|
remain `untyped`; the signatures do not make internal tables stable APIs.
|
|
37
|
-
Token and location
|
|
38
|
-
|
|
37
|
+
Token and location records inherit from `Data`; fields are read-only and `with`
|
|
38
|
+
returns a replacement. Their fields are nullable because their public constructors
|
|
39
|
+
allow omitted keywords. The token representation remains a union of arrays and
|
|
39
40
|
structured tokens because `token_kind` is selected dynamically.
|
|
40
41
|
Cancellation signatures accept Procs, Methods, and callable objects taking zero
|
|
41
42
|
arguments or the lexer. `on_error=` accepts a callable returning `:skip`,
|
|
@@ -49,8 +50,8 @@ BUNDLE_GEMFILE=gemfiles/types.gemfile bundle exec rbs -I sig validate
|
|
|
49
50
|
BUNDLE_GEMFILE=gemfiles/types.gemfile bundle exec steep check
|
|
50
51
|
```
|
|
51
52
|
|
|
52
|
-
The type-checking tools
|
|
53
|
-
|
|
53
|
+
The type-checking tools run in a separate CI matrix for Ruby 3.4 and 4.0,
|
|
54
|
+
matching the runtime's supported Ruby versions. They add no runtime dependency to flexr.
|
|
54
55
|
This checks the public signatures and a typed consumer, not the entire internal
|
|
55
56
|
implementation.
|
|
56
57
|
|
data/docs/reference/runtime.md
CHANGED
|
@@ -21,8 +21,8 @@ Lexer.new(input,
|
|
|
21
21
|
|
|
22
22
|
`input` must be a `String` or an object responding to `read`. `filename` is
|
|
23
23
|
copied into locations and lexical errors. `error_mode` is `:raise`, `:token`,
|
|
24
|
-
or `:panic`; unknown values
|
|
25
|
-
|
|
24
|
+
or `:panic`; unknown values raise `ArgumentError` at initialization.
|
|
25
|
+
`max_lookahead_size` defaults to `max_token_size`. `max_steps: nil`
|
|
26
26
|
leaves the step count unbounded; `cancellation` may be a callable accepting
|
|
27
27
|
zero arguments or the lexer. Size limits are non-negative, and `chunk_size`
|
|
28
28
|
must be positive.
|
|
@@ -12,6 +12,14 @@ For `:struct`, `Token` has `type`, `value`, and `location` members. `emit(nil,
|
|
|
12
12
|
value)` is valid and produces a token whose type is `nil`. `skip` produces no
|
|
13
13
|
token.
|
|
14
14
|
|
|
15
|
+
In v2, `Token` and `Location` are immutable `Data` records. The `:struct`
|
|
16
|
+
option name is retained. Attribute readers and read-only indexing by member
|
|
17
|
+
name or index remain available; field writers and `[]=` are removed. Replace
|
|
18
|
+
values with `token.with(value: replacement)` or `location.with(...)`.
|
|
19
|
+
Immutability is shallow: custom token values can still be mutable.
|
|
20
|
+
Lazy columns use a frozen pair without mutating the record or retaining the
|
|
21
|
+
lexer; `to_h` returns the resolved columns.
|
|
22
|
+
|
|
15
23
|
## Locations
|
|
16
24
|
|
|
17
25
|
`Flexr::Runtime::Location` has these public members:
|
|
@@ -9,12 +9,12 @@ module JsonExample
|
|
|
9
9
|
:STRING, :NUMBER, :TRUE, :FALSE, :NULL
|
|
10
10
|
|
|
11
11
|
rule(/[ \t\r\n]+/, skip: true)
|
|
12
|
-
rule(/\{
|
|
13
|
-
rule(/\}
|
|
14
|
-
rule(/\[
|
|
15
|
-
rule(/\]
|
|
16
|
-
rule(
|
|
17
|
-
rule(
|
|
12
|
+
rule(/\{/, emit: :LBRACE)
|
|
13
|
+
rule(/\}/, emit: :RBRACE)
|
|
14
|
+
rule(/\[/, emit: :LBRACKET)
|
|
15
|
+
rule(/\]/, emit: :RBRACKET)
|
|
16
|
+
rule(/:/, emit: :COLON)
|
|
17
|
+
rule(/,/, emit: :COMMA)
|
|
18
18
|
rule(/true/) { emit :TRUE, true }
|
|
19
19
|
rule(/false/) { emit :FALSE, false }
|
|
20
20
|
rule(/null/) { emit :NULL, nil }
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
module Flexr
|
|
4
4
|
module Automaton
|
|
5
5
|
Region = Struct.new(:state, :bytes, :regexp, :utf8_regexp, keyword_init: true)
|
|
6
|
+
WholeToken = Struct.new(:regexp, :rule_index, keyword_init: true)
|
|
6
7
|
|
|
7
8
|
module Accel
|
|
8
9
|
module_function
|
|
@@ -20,6 +21,63 @@ module Flexr
|
|
|
20
21
|
end
|
|
21
22
|
end
|
|
22
23
|
|
|
24
|
+
def whole_token_plans(dfa, rules)
|
|
25
|
+
return if rules.any?(&:trailing) || !dfa.accepts[dfa.start].empty?
|
|
26
|
+
return if dfa.accepts.any? { |acceptances| acceptances.any? { |item| item.bol_only || item.end_anchor } }
|
|
27
|
+
|
|
28
|
+
plans = Array.new(256)
|
|
29
|
+
memo = {}
|
|
30
|
+
token_edges(dfa, dfa.start).each do |destination, bytes|
|
|
31
|
+
next if bytes.any? { |byte| byte >= 128 }
|
|
32
|
+
expression, winners = token_expression(dfa, destination, memo, [])
|
|
33
|
+
next unless expression && winners.one?
|
|
34
|
+
|
|
35
|
+
source = "[#{bytes_to_source(bytes)}]#{expression}"
|
|
36
|
+
next if source.bytesize > 4096
|
|
37
|
+
|
|
38
|
+
regexp = ::Regexp.new(source).freeze
|
|
39
|
+
plan = WholeToken.new(regexp: regexp, rule_index: winners.first).freeze
|
|
40
|
+
bytes.each { |byte| plans[byte] = plan }
|
|
41
|
+
end
|
|
42
|
+
plans.freeze unless plans.compact.empty?
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def token_expression(dfa, state, memo, ancestors)
|
|
46
|
+
return memo[state] if memo.key?(state)
|
|
47
|
+
# shortcut: cap expansion at 32 states/4 KiB, revisit for measured DFA fallback bottlenecks.
|
|
48
|
+
return [nil, []] if ancestors.include?(state) || ancestors.length >= 32
|
|
49
|
+
|
|
50
|
+
edges = token_edges(dfa, state)
|
|
51
|
+
return memo[state] = [nil, []] if edges.values.any? { |bytes| bytes.any? { |byte| byte >= 128 } }
|
|
52
|
+
|
|
53
|
+
loops = edges.delete(state)
|
|
54
|
+
winner = dfa.accepts[state].first&.rule_index
|
|
55
|
+
winners = winner ? [winner] : []
|
|
56
|
+
alternatives = edges.map do |destination, bytes|
|
|
57
|
+
tail, accepted = token_expression(dfa, destination, memo, ancestors + [state])
|
|
58
|
+
return memo[state] = [nil, []] unless tail
|
|
59
|
+
|
|
60
|
+
winners |= accepted
|
|
61
|
+
return memo[state] = [nil, []] if winners.length > 1
|
|
62
|
+
|
|
63
|
+
"[#{bytes_to_source(bytes)}]#{tail}"
|
|
64
|
+
end
|
|
65
|
+
return memo[state] = [nil, []] if alternatives.empty? && winner.nil?
|
|
66
|
+
|
|
67
|
+
tail = alternatives.empty? ? "" : "(?:#{alternatives.join('|')})#{'?' unless winner.nil?}"
|
|
68
|
+
expression = "#{"[#{bytes_to_source(loops)}]*" if loops}#{tail}"
|
|
69
|
+
return memo[state] = [nil, []] if expression.bytesize > 4096
|
|
70
|
+
|
|
71
|
+
memo[state] = [expression, winners]
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def token_edges(dfa, state)
|
|
75
|
+
(0..255).each_with_object({}) do |byte, edges|
|
|
76
|
+
destination = dfa.transition(state, byte)
|
|
77
|
+
(edges[destination] ||= []) << byte if destination
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
23
81
|
def self_loop_set(dfa, state)
|
|
24
82
|
representatives = Array.new(dfa.class_count)
|
|
25
83
|
dfa.ec.each_with_index { |class_id, byte| representatives[class_id] ||= byte }
|
|
@@ -13,7 +13,10 @@ module Flexr
|
|
|
13
13
|
state_names = effective_states
|
|
14
14
|
machines = state_names.to_h do |state_name|
|
|
15
15
|
rules = rules_for(state_name)
|
|
16
|
-
|
|
16
|
+
dfa = compile_machine(rules)
|
|
17
|
+
plans = Accel.whole_token_plans(dfa, rules) if
|
|
18
|
+
@spec.backend != :firstmatch && @spec.options[:accel] == :strscan
|
|
19
|
+
[state_name, Machine.new(dfa: dfa, state_name: state_name, whole_tokens: plans)]
|
|
17
20
|
rescue CompileError => e
|
|
18
21
|
e.diagnostic.location ||= @spec.states.fetch(state_name).location if e.diagnostic
|
|
19
22
|
raise
|
|
@@ -9,6 +9,6 @@ module Flexr
|
|
|
9
9
|
end
|
|
10
10
|
|
|
11
11
|
CompiledSpec = Struct.new(:machines, :rules, :states, :stats, :diagnostics, keyword_init: true)
|
|
12
|
-
Machine = Struct.new(:dfa, :state_name, keyword_init: true)
|
|
12
|
+
Machine = Struct.new(:dfa, :state_name, :whole_tokens, keyword_init: true)
|
|
13
13
|
end
|
|
14
14
|
end
|
data/lib/flexr/codegen/table.rb
CHANGED
|
@@ -27,11 +27,13 @@ module Flexr
|
|
|
27
27
|
|
|
28
28
|
def source(indent: " ")
|
|
29
29
|
lines = []
|
|
30
|
+
whole_tokens = compiled.machines.values.any?(&:whole_tokens)
|
|
30
31
|
lines << "#{indent}def scan_one"
|
|
31
32
|
lines << "#{indent} if @__flexr_generated_scan_state != @state"
|
|
32
33
|
lines << "#{indent} machine = self.class.__flexr_compiled.machines.fetch(@state)"
|
|
33
34
|
lines << "#{indent} @__flexr_generated_scan_state = @state"
|
|
34
35
|
lines << "#{indent} @__flexr_generated_scan_dfa = machine.dfa"
|
|
36
|
+
lines << "#{indent} @__flexr_generated_whole_tokens = machine.respond_to?(:whole_tokens) ? machine.whole_tokens : nil" if whole_tokens
|
|
35
37
|
lines << "#{indent} @__flexr_generated_scan_fast = __flexr_generated_fast_path?(@__flexr_generated_scan_dfa)"
|
|
36
38
|
lines << "#{indent} @__flexr_generated_scan_simple = __flexr_generated_simple_fast_path?(@__flexr_generated_scan_dfa)"
|
|
37
39
|
lines << "#{indent} end"
|
|
@@ -39,6 +41,10 @@ module Flexr
|
|
|
39
41
|
lines << "#{indent} return Flexr::Runtime::Interpreter.new(self).scan unless @__flexr_generated_scan_fast"
|
|
40
42
|
lines << "#{indent} position = byte_pos"
|
|
41
43
|
lines << "#{indent} return nil unless valid_utf8_at?(position)"
|
|
44
|
+
if whole_tokens
|
|
45
|
+
lines << "#{indent} match = __flexr_whole_token_match(@__flexr_generated_whole_tokens, position) if @__flexr_generated_whole_tokens"
|
|
46
|
+
lines << "#{indent} return match if match"
|
|
47
|
+
end
|
|
42
48
|
lines << "#{indent} return __flexr_generated_scan_simple(dfa, position) if @__flexr_generated_scan_simple"
|
|
43
49
|
lines << "#{indent} cursor = position"
|
|
44
50
|
lines << "#{indent} current = dfa.start"
|
data/lib/flexr/dsl.rb
CHANGED
|
@@ -112,9 +112,10 @@ module Flexr
|
|
|
112
112
|
end
|
|
113
113
|
|
|
114
114
|
def compile!
|
|
115
|
+
return @__flexr_compiled if @__flexr_compiled
|
|
116
|
+
|
|
115
117
|
@__flexr_compile_mutex.synchronize do
|
|
116
118
|
# The ivar is part of the generated/runtime class contract.
|
|
117
|
-
# rubocop:disable-next Naming/MemoizedInstanceVariableName
|
|
118
119
|
@__flexr_compiled ||= begin
|
|
119
120
|
compiled = Automaton::Compiler.new(__flexr_spec).compile
|
|
120
121
|
@__flexr_config.backend = auto_direct?(compiled) ? :direct : :table if @__flexr_config.backend == :auto
|
data/lib/flexr/generated.rb
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
module Flexr
|
|
4
4
|
module Generated
|
|
5
|
-
ARTIFACT_SCHEMA_VERSION =
|
|
6
|
-
RUNTIME_ABI_VERSION =
|
|
5
|
+
ARTIFACT_SCHEMA_VERSION = 2
|
|
6
|
+
RUNTIME_ABI_VERSION = 2
|
|
7
7
|
|
|
8
8
|
module_function
|
|
9
9
|
|
|
@@ -59,7 +59,9 @@ module Flexr
|
|
|
59
59
|
install!(klass, payload)
|
|
60
60
|
machines = payload.fetch(:compiled).fetch(:machines).transform_values do |machine|
|
|
61
61
|
dfa = load_dfa(machine.fetch(:dfa))
|
|
62
|
-
Automaton::
|
|
62
|
+
plans = Automaton::Accel.whole_token_plans(dfa, klass.__flexr_rules) if
|
|
63
|
+
klass.__flexr_config.backend != :firstmatch && klass.__flexr_config.options[:accel] == :strscan
|
|
64
|
+
Automaton::Machine.new(dfa: dfa, state_name: machine.fetch(:state_name).to_sym, whole_tokens: plans)
|
|
63
65
|
end
|
|
64
66
|
compiled = Automaton::CompiledSpec.new(
|
|
65
67
|
machines: machines,
|
|
@@ -85,10 +87,7 @@ module Flexr
|
|
|
85
87
|
}
|
|
86
88
|
mismatch = expected.find { |name, value| artifact[name] != value }
|
|
87
89
|
compiler_version = artifact[:compiler_version]
|
|
88
|
-
if mismatch.nil? && compiler_version.is_a?(String) && !compiler_version.empty?
|
|
89
|
-
Deprecations.warn("generated lexer ABI 1 will be incompatible with 2.0; regenerate it after upgrading")
|
|
90
|
-
return
|
|
91
|
-
end
|
|
90
|
+
return if mismatch.nil? && compiler_version.is_a?(String) && !compiler_version.empty?
|
|
92
91
|
|
|
93
92
|
detail = if mismatch
|
|
94
93
|
name, value = mismatch
|
|
@@ -99,6 +98,43 @@ module Flexr
|
|
|
99
98
|
incompatible_artifact!(detail)
|
|
100
99
|
end
|
|
101
100
|
|
|
101
|
+
def shareable!(klass)
|
|
102
|
+
unless klass.__flexr_generated? && klass.__flexr_rules.none? { |rule| rule.action.is_a?(Proc) } &&
|
|
103
|
+
klass.__flexr_generated_actions.empty? && klass.__flexr_spec.eof_rules.empty?
|
|
104
|
+
raise ArgumentError, "Ractor sharing requires generated method actions without captured closures or EOF blocks"
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
config = klass.__flexr_config
|
|
108
|
+
if config.backend == :firstmatch && klass.__flexr_rules.any? do |rule|
|
|
109
|
+
rule.patterns.any? do |pattern|
|
|
110
|
+
Regexp::Matcher.reference?(pattern, encoding: config.encoding, unicode: config.options[:unicode] == true)
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
raise ArgumentError, "Ractor sharing does not support firstmatch reference patterns; use table, direct, or auto"
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
original = klass.__flexr_compiled
|
|
117
|
+
rules = original.rules.map do |rule|
|
|
118
|
+
IR::Rule.new(**rule.to_h, trailing_dfa: rule.trailing_dfa && shareable_dfa(rule.trailing_dfa))
|
|
119
|
+
end
|
|
120
|
+
machines = original.machines.transform_values do |machine|
|
|
121
|
+
Automaton::Machine.new(dfa: shareable_dfa(machine.dfa), state_name: machine.state_name,
|
|
122
|
+
whole_tokens: machine.whole_tokens)
|
|
123
|
+
end
|
|
124
|
+
compiled = Automaton::CompiledSpec.new(**original.to_h, machines: machines, rules: rules)
|
|
125
|
+
Ractor.make_shareable([compiled, klass.__flexr_config, klass.__flexr_states, klass.__flexr_spec.eof_rules,
|
|
126
|
+
klass.__flexr_generated_actions, klass.__flexr_generated_eof_actions])
|
|
127
|
+
klass.instance_variable_set(:@__flexr_rules, rules)
|
|
128
|
+
klass.__flexr_set_compiled!(compiled)
|
|
129
|
+
klass
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def shareable_dfa(dfa)
|
|
133
|
+
Automaton::DFA.new(transitions: dfa.transitions.map(&:dup), accepts: dfa.accepts, ec: dfa.ec,
|
|
134
|
+
class_count: dfa.class_count, start: dfa.start, rule_ids: dfa.rule_ids,
|
|
135
|
+
direct: dfa.direct)
|
|
136
|
+
end
|
|
137
|
+
|
|
102
138
|
def incompatible_artifact!(detail)
|
|
103
139
|
diagnostic = Diagnostics.error(
|
|
104
140
|
"FLEXR-E020", "generated artifact is incompatible with this runtime",
|
data/lib/flexr/generator.rb
CHANGED
|
@@ -14,9 +14,9 @@ module Flexr
|
|
|
14
14
|
INLINE_EMIT_ARGUMENTS = /\A(?::[A-Za-z_]\w*|true|false|nil|-?\d+(?:\.\d+)?|"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|text(?:\.(?:to_f|to_i|bytesize|byteslice\([^()\n]+\)))?|lineno|line)(?:\s*,\s*(?::[A-Za-z_]\w*|true|false|nil|-?\d+(?:\.\d+)?|"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|text(?:\.(?:to_f|to_i|bytesize|byteslice\([^()\n]+\)))?|lineno|line))*\z/
|
|
15
15
|
|
|
16
16
|
RUNTIME_SOURCES = %w[
|
|
17
|
-
version.rb errors.rb diagnostics.rb
|
|
17
|
+
version.rb errors.rb diagnostics.rb action_resolver.rb configuration.rb ir.rb
|
|
18
18
|
unicode/version.rb automaton/types.rb automaton/dfa.rb automaton/accel.rb
|
|
19
|
-
runtime/location.rb runtime/token.rb runtime/buffer.rb runtime/errors.rb
|
|
19
|
+
runtime/record.rb runtime/location.rb runtime/token.rb runtime/buffer.rb runtime/errors.rb
|
|
20
20
|
runtime/interpreter.rb runtime/core.rb dsl.rb lexer.rb generated.rb
|
|
21
21
|
].freeze
|
|
22
22
|
|
|
@@ -62,6 +62,11 @@ module Flexr
|
|
|
62
62
|
install = "#{install}#{Codegen::Table.new(compiled).source(indent: indent)}"
|
|
63
63
|
install = "#{install}#{generated_action_source(parsed, indent)}"
|
|
64
64
|
edits = parsed.dsl_edits.dup
|
|
65
|
+
parsed.rules.each do |rule|
|
|
66
|
+
next unless rule.bind_action && !rule.reads_locals && inline_simple_action(rule.action_source)
|
|
67
|
+
|
|
68
|
+
edits.map! { |edit| edit.first(2) == rule.span ? [*rule.span, ""] : edit }
|
|
69
|
+
end
|
|
65
70
|
edits.concat(parsed.flexr_require_spans.map { |span| [*span, ""] }) if standalone?(parsed)
|
|
66
71
|
result = Source::Passthrough.rewrite(
|
|
67
72
|
parsed.source, edits, insertion: parsed.first_dsl_offset, payload: install
|
|
@@ -79,7 +84,7 @@ module Flexr
|
|
|
79
84
|
"# eval: #{@eval_mode}",
|
|
80
85
|
"# standalone: #{standalone?(parsed)}"
|
|
81
86
|
].join("\n")
|
|
82
|
-
prefix = standalone?(parsed) ? "
|
|
87
|
+
prefix = standalone?(parsed) ? "raise LoadError, \"flexr requires Ruby 3.4 or newer\" if RUBY_VERSION < \"3.4\"\nrequire \"json\"\nrequire \"monitor\"\n#{embedded_runtime(parsed)}\n" : ""
|
|
83
88
|
Source::Passthrough.insert_after_preamble(result, "#{header}\n#{prefix}")
|
|
84
89
|
end
|
|
85
90
|
|
|
@@ -90,7 +95,7 @@ module Flexr
|
|
|
90
95
|
end
|
|
91
96
|
"{ index: #{rule.index}, patterns: #{ruby_literal(rule.patterns)}, pattern_conditions: #{ruby_literal(conditions)}, trailing: #{ruby_literal(rule.trailing)}, " \
|
|
92
97
|
"#{trailing_dfa_expression(rule, parsed)}" \
|
|
93
|
-
"action: #{
|
|
98
|
+
"action: #{generated_rule_action(rule)}, states: #{rule.states.inspect}, " \
|
|
94
99
|
"bol_only: #{ruby_literal(rule.bol_only)}, end_anchor: #{ruby_literal(rule.end_anchor)} }"
|
|
95
100
|
end
|
|
96
101
|
"{ artifact: #{ruby_literal(artifact_metadata)}, rules: [#{definitions.join(', ')}], " \
|
|
@@ -252,15 +257,23 @@ module Flexr
|
|
|
252
257
|
"proc { emit(nil, text) }"
|
|
253
258
|
end
|
|
254
259
|
|
|
260
|
+
def generated_rule_action(rule)
|
|
261
|
+
return ruby_literal(:__flexr_generated_method) if rule.action.is_a?(String) &&
|
|
262
|
+
((!rule.bind_action && !inline_action_body(rule).nil?) || (!rule.reads_locals && inline_simple_action(rule.action_source)))
|
|
263
|
+
|
|
264
|
+
action_expression(rule.action)
|
|
265
|
+
end
|
|
266
|
+
|
|
255
267
|
def generated_action_source(parsed, indent)
|
|
256
268
|
lines = ["#{indent}def __flexr_generated_execute(rule)", "#{indent} case rule.index"]
|
|
257
269
|
parsed.rules.each do |rule|
|
|
258
270
|
lines << "#{indent} when #{rule.index}"
|
|
259
|
-
if rule.bind_action
|
|
271
|
+
body = inline_simple_action(rule.action_source) if rule.bind_action && !rule.reads_locals
|
|
272
|
+
if rule.bind_action && body.nil?
|
|
260
273
|
lines << "#{indent} instance_exec(&self.class.__flexr_generated_actions.fetch(rule.index))"
|
|
261
274
|
next
|
|
262
275
|
end
|
|
263
|
-
body
|
|
276
|
+
body ||= inline_action_body(rule)
|
|
264
277
|
if body.nil?
|
|
265
278
|
lines << "#{indent} instance_exec(&rule.action)"
|
|
266
279
|
else
|
|
@@ -325,6 +338,7 @@ module Flexr
|
|
|
325
338
|
|
|
326
339
|
def inline_simple_action(source)
|
|
327
340
|
body = source.to_s.strip
|
|
341
|
+
return if body.include?('#{') || body.match?(/text\.byteslice\([^)]*[A-Za-z_]/)
|
|
328
342
|
body = body[1...-1].strip if body.start_with?("{") && body.end_with?("}")
|
|
329
343
|
match = INLINE_EMIT.match(body)
|
|
330
344
|
return unless match
|
|
@@ -350,8 +364,7 @@ module Flexr
|
|
|
350
364
|
loader = Object.new
|
|
351
365
|
loader.define_singleton_method(:load_spec) do
|
|
352
366
|
# --eval is opt-in and intentionally executes trusted specification code.
|
|
353
|
-
# rubocop:disable
|
|
354
|
-
eval(source, TOPLEVEL_BINDING, @path, 1)
|
|
367
|
+
eval(source, TOPLEVEL_BINDING, @path, 1) # rubocop:disable Security/Eval
|
|
355
368
|
end
|
|
356
369
|
loader.instance_variable_set(:@path, @path)
|
|
357
370
|
loader.load_spec
|
data/lib/flexr/minitest.rb
CHANGED
|
@@ -6,12 +6,12 @@ require_relative "testing"
|
|
|
6
6
|
module Flexr
|
|
7
7
|
module Minitest
|
|
8
8
|
module Assertions
|
|
9
|
-
def assert_tokenize(lexer, input, expected, **
|
|
10
|
-
assert_equal expected, lexer.new(input, **
|
|
9
|
+
def assert_tokenize(lexer, input, expected, **)
|
|
10
|
+
assert_equal expected, lexer.new(input, **).tokens
|
|
11
11
|
end
|
|
12
12
|
|
|
13
|
-
def assert_token_snapshot(lexer, input, path, update: false, **
|
|
14
|
-
actual = Testing::Snapshot.render(lexer.new(input, **
|
|
13
|
+
def assert_token_snapshot(lexer, input, path, update: false, **)
|
|
14
|
+
actual = Testing::Snapshot.render(lexer.new(input, **).tokens)
|
|
15
15
|
begin
|
|
16
16
|
expected = Testing::Snapshot.expected(path, actual, update: update)
|
|
17
17
|
rescue Errno::ENOENT
|