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
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Lexer < Flexr::Lexer
4
+ token_kind :struct
5
+ rule(/#[^\n]*/, channel: :comment)
6
+ rule(/\s+/, channel: :whitespace)
7
+ rule(/[a-z_]+/, emit: :WORD)
8
+ end
@@ -0,0 +1,23 @@
1
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { readStableFile, stableFiles, stableReleaseTag } from './stable-release.mjs';
5
+
6
+ const prefix = 'site/src/content/docs/';
7
+ const output = fileURLToPath(new URL('../src/content/docs/stable/', import.meta.url));
8
+ const files = stableFiles(prefix).filter(filename => filename.endsWith('.md'));
9
+ const slugs = new Set(files.map(filename => filename.slice(prefix.length, -3)));
10
+ if (!files.length) throw new Error(`No site documentation in ${stableReleaseTag}.`);
11
+
12
+ await rm(output, { recursive: true, force: true });
13
+ for (const filename of files) {
14
+ const source = readStableFile(filename)
15
+ .replace(/\/flexr\/([^\s)#?]+)/g, (url, target) =>
16
+ slugs.has(target.replace(/\/$/, '')) ? `/flexr/stable/${target}` : url
17
+ )
18
+ .replace(/https:\/\/github\.com\/ydah\/flexr\/(blob|tree)\/main\//g,
19
+ `https://github.com/ydah/flexr/$1/${stableReleaseTag}/`);
20
+ const target = path.join(output, filename.slice(prefix.length));
21
+ await mkdir(path.dirname(target), { recursive: true });
22
+ await writeFile(target, source);
23
+ }
@@ -1,10 +1,12 @@
1
1
  import { cp, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import path from 'node:path';
4
+ import { readStableFile, stableFiles } from './stable-release.mjs';
4
5
 
5
6
  const site = fileURLToPath(new URL('..', import.meta.url));
6
7
  const root = path.dirname(site);
7
8
  const output = path.join(site, 'public/playground-runtime');
9
+ const useStable = process.env.FLEXR_PLAYGROUND_STABLE === '1';
8
10
  const files = {};
9
11
  async function collect(directory) {
10
12
  for (const entry of await readdir(path.join(root, directory), { withFileTypes: true })) {
@@ -13,7 +15,13 @@ async function collect(directory) {
13
15
  else if (entry.name.endsWith('.rb')) files[`/app/${relative}`] = await readFile(path.join(root, relative), 'utf8');
14
16
  }
15
17
  }
16
- await collect('lib');
18
+ if (useStable) {
19
+ for (const filename of stableFiles('lib').filter(filename => filename.endsWith('.rb'))) {
20
+ files[`/app/${filename}`] = readStableFile(filename);
21
+ }
22
+ } else {
23
+ await collect('lib');
24
+ }
17
25
  files['/app/playground.rb'] = await readFile(path.join(site, 'ruby/playground.rb'), 'utf8');
18
26
  await mkdir(output, { recursive: true });
19
27
  const payload = JSON.stringify({ files });
@@ -25,7 +33,23 @@ const inputs = {
25
33
  };
26
34
  const presets = {};
27
35
  for (const [name, input] of Object.entries(inputs)) {
28
- presets[name] = { source: await readFile(path.join(root, `examples/${name}/lexer.flexr.rb`), 'utf8'), input };
36
+ const filename = `examples/${name}/lexer.flexr.rb`;
37
+ const source = useStable ? readStableFile(filename) : await readFile(path.join(root, filename), 'utf8');
38
+ presets[name] = { source, input };
39
+ }
40
+ const updatedPresets = {
41
+ absence: '/* 前 */first /* another comment */second',
42
+ pattern: 'if ifx [[ababa end',
43
+ keywords: 'if iffy else end',
44
+ trivia: '# note\nalpha \tbeta',
45
+ priority: 'if ifx',
46
+ };
47
+ const releasedPresets = useStable ? stableFiles('site/ruby/presets') : null;
48
+ for (const [name, input] of Object.entries(updatedPresets)) {
49
+ const filename = `site/ruby/presets/${name}.flexr.rb`;
50
+ if (releasedPresets && !releasedPresets.includes(filename)) continue;
51
+ const source = useStable ? readStableFile(filename) : await readFile(path.join(root, filename), 'utf8');
52
+ presets[name] = { source, input };
29
53
  }
30
54
  await writeFile(path.join(output, 'presets.json'), JSON.stringify(presets));
31
55
  const wasm = path.join(site, 'node_modules/@ruby/4.0-wasm-wasi/dist');
@@ -0,0 +1,16 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ export const stableReleaseTag = 'v2.0.0';
5
+
6
+ const root = fileURLToPath(new URL('../../', import.meta.url));
7
+ const ref = `refs/tags/${stableReleaseTag}`;
8
+
9
+ export function stableFiles(prefix) {
10
+ return execFileSync('git', ['ls-tree', '-r', '--name-only', '-z', ref, '--', prefix], { cwd: root, encoding: 'utf8' })
11
+ .split('\0').filter(Boolean);
12
+ }
13
+
14
+ export function readStableFile(filename) {
15
+ return execFileSync('git', ['show', `${ref}:${filename}`], { cwd: root, encoding: 'utf8' });
16
+ }
@@ -0,0 +1,30 @@
1
+ ---
2
+ import { getCollection } from 'astro:content';
3
+ import PageTitle from '@astrojs/starlight/components/PageTitle.astro';
4
+ import { stableReleaseTag } from '../../scripts/stable-release.mjs';
5
+
6
+ const { id } = Astro.locals.starlightRoute.entry;
7
+ const isStable = id.startsWith('stable/');
8
+ const otherId = isStable ? id.slice('stable/'.length) : `stable/${id}`;
9
+ const fallback = isStable ? 'learn/getting-started' : 'stable/learn/getting-started';
10
+ const counterpart = (await getCollection('docs')).some(entry => entry.id === otherId) ? otherId : fallback;
11
+ const base = import.meta.env.BASE_URL.replace(/\/$/, '');
12
+ ---
13
+
14
+ <PageTitle />
15
+ <nav class="documentation-version" aria-label="Documentation version">
16
+ <a href={`${base}/${isStable ? id : counterpart}/`} aria-current={isStable ? 'page' : undefined}>Stable {stableReleaseTag}</a>
17
+ <a href={`${base}/${isStable ? counterpart : id}/`} aria-current={isStable ? undefined : 'page'}>main</a>
18
+ </nav>
19
+
20
+ <style>
21
+ .documentation-version {
22
+ display: flex;
23
+ gap: 1rem;
24
+ font-size: var(--sl-text-sm);
25
+ }
26
+
27
+ [aria-current="page"] {
28
+ font-weight: 600;
29
+ }
30
+ </style>
@@ -5,4 +5,14 @@ description: Read reproducible measurements without confusing a benchmark with a
5
5
 
6
6
  Benchmark results depend on Ruby, hardware, input distribution, backend, and table shape. The repository records commands, input conditions, measurements, and limitations in [`docs/perf-log.md`](https://github.com/ydah/flexr/blob/main/docs/perf-log.md).
7
7
 
8
- Use the log to reproduce a comparison, not to select a backend from one headline number. Start with `auto`, measure your own workload, then pin a backend only when the evidence justifies the extra configuration.
8
+ ## Reference JSON
9
+
10
+ Measured on 2026-11-22 with Ruby 4.0.9 on arm64 macOS, using 140,000 bytes of input and 50,000 emitted tokens. Each row reports the run with the median generated/runtime ratio out of three runs per engine.
11
+
12
+ | Engine | Runtime / handwritten | Generated / handwritten | Generated / runtime |
13
+ |---|---:|---:|---:|
14
+ | Interpreter | 0.261x | 0.307x | 1.177x |
15
+ | YJIT | 0.717x | 0.763x | 1.064x |
16
+ | ZJIT | 0.259x | 0.274x | 1.060x |
17
+
18
+ Start with `auto` and use [the reproduction commands](https://github.com/ydah/flexr/blob/main/docs/perf-log.md#2026-11-22-cache-the-direct-scan-layout-per-dfa) to measure the workload you plan to deploy.
@@ -0,0 +1,14 @@
1
+ import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
2
+ import { stableReleaseTag } from '../scripts/stable-release.mjs';
3
+
4
+ export const onRequest = defineRouteMiddleware(({ locals }, next) => {
5
+ const route = locals.starlightRoute;
6
+ const isStable = route.entry.id.startsWith('stable/');
7
+ const prefix = `${import.meta.env.BASE_URL.replace(/\/$/, '')}/stable/`;
8
+ route.sidebar = route.sidebar.filter(item => (item.label === `Stable ${stableReleaseTag}`) === isStable);
9
+ for (const direction of ['prev', 'next'] as const) {
10
+ const link = route.pagination[direction];
11
+ if (link && link.href.startsWith(prefix) !== isStable) route.pagination[direction] = undefined;
12
+ }
13
+ return next();
14
+ });
@@ -1,7 +1,9 @@
1
1
  ---
2
+ import { readFile } from 'node:fs/promises';
2
3
  import SiteLayout from '../layouts/SiteLayout.astro';
3
4
 
4
5
  const base = import.meta.env.BASE_URL.endsWith('/') ? import.meta.env.BASE_URL : `${import.meta.env.BASE_URL}/`;
6
+ const presets = JSON.parse(await readFile(new URL('../../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
5
7
  ---
6
8
  <SiteLayout title="Playground" description="Run real flexr Ruby specifications locally, inspect diagnostics and trace decisions, and generate a scanner." playground>
7
9
  <main class="playground-shell">
@@ -20,6 +22,11 @@ const base = import.meta.env.BASE_URL.endsWith('/') ? import.meta.env.BASE_URL :
20
22
  <select id="preset" aria-label="Choose a playground preset">
21
23
  <option value="longest">Longest match</option><option value="calculator">Calculator</option><option value="json">JSON tokens</option>
22
24
  <option value="toml">TOML subset</option><option value="graphql">GraphQL subset</option><option value="sql">SQL subset</option>
25
+ {Object.hasOwn(presets, 'absence') && <option value="absence">C comments with absence</option>}
26
+ {Object.hasOwn(presets, 'pattern') && <option value="pattern">Named pattern algebra</option>}
27
+ {Object.hasOwn(presets, 'keywords') && <option value="keywords">Keywords and identifiers</option>}
28
+ {Object.hasOwn(presets, 'trivia') && <option value="trivia">Comments and whitespace trivia</option>}
29
+ {Object.hasOwn(presets, 'priority') && <option value="priority">Equal-length rule priority</option>}
23
30
  </select>
24
31
  <textarea id="spec" aria-label="Lexer specification" spellcheck="false" maxlength="20000"></textarea>
25
32
  </div>
@@ -0,0 +1,33 @@
1
+ import { test, expect } from '@playwright/test';
2
+ import { stableReleaseTag as stableTag } from '../../scripts/stable-release.mjs';
3
+
4
+ test('switches between versions of the same documentation page', async ({ page }) => {
5
+ await page.goto('/flexr/reference/runtime/');
6
+ const versions = page.getByRole('navigation', { name: 'Documentation version' });
7
+ const main = versions.getByRole('link', { name: 'main', exact: true });
8
+ const stable = versions.getByRole('link', { name: `Stable ${stableTag}`, exact: true });
9
+ await expect(main).toHaveAttribute('aria-current', 'page');
10
+ await stable.click();
11
+ await expect(page).toHaveURL(/\/flexr\/stable\/reference\/runtime\/$/);
12
+ await expect(stable).toHaveAttribute('aria-current', 'page');
13
+ await main.click();
14
+ await expect(page).toHaveURL(/\/flexr\/reference\/runtime\/$/);
15
+ });
16
+
17
+ test('keeps stable documentation links on the released version', async ({ page }) => {
18
+ await page.goto('/flexr/stable/learn/getting-started/');
19
+ await expect(page.getByRole('link', { name: 'calculator tutorial' })).toHaveAttribute(
20
+ 'href', `https://github.com/ydah/flexr/blob/${stableTag}/docs/tutorial/build-a-calculator-lexer.md`
21
+ );
22
+ await page.getByRole('link', { name: 'runtime guide' }).click();
23
+ await expect(page).toHaveURL(/\/flexr\/stable\/learn\/runtime-mode\/$/);
24
+ });
25
+
26
+ test('keeps sidebar navigation in the selected version', async ({ page }) => {
27
+ const mainNavigation = page.getByRole('navigation', { name: 'Main', exact: true });
28
+ const gettingStarted = mainNavigation.getByRole('link', { name: 'Getting started', exact: true });
29
+ await page.goto('/flexr/stable/learn/runtime-mode/');
30
+ await expect(gettingStarted).toHaveAttribute('href', '/flexr/stable/learn/getting-started/');
31
+ await page.goto('/flexr/learn/runtime-mode/');
32
+ await expect(gettingStarted).toHaveAttribute('href', '/flexr/learn/getting-started/');
33
+ });
@@ -97,3 +97,38 @@ test('executes literal Unicode action values in runtime and generated modes', as
97
97
  expect(JSON.parse(await page.locator('#tokens').textContent())).toEqual([['TEXT', '前あ']]);
98
98
  }
99
99
  });
100
+
101
+ test('offers the absence preset from the packaged lexer examples', async ({ page }) => {
102
+ await page.goto('/flexr/playground/');
103
+ await page.getByRole('combobox', { name: 'Choose a playground preset' }).selectOption('absence');
104
+ await expect(page.locator('#spec')).toHaveValue(/\(\?~/);
105
+ await expect(page.locator('#input')).toHaveValue(/first.*second/);
106
+ });
107
+
108
+ test('loads the keyword table preset from the packaged lexer examples', async ({ page }) => {
109
+ await page.goto('/flexr/playground/');
110
+ await page.getByRole('combobox', { name: 'Choose a playground preset' }).selectOption('keywords');
111
+ await expect(page.locator('#spec')).toHaveValue(/keywords %w\[if else end\]/);
112
+ await expect(page.locator('#input')).toHaveValue('if iffy else end');
113
+ });
114
+
115
+
116
+ test('shows leading trivia from the comments and whitespace preset', async ({ page }) => {
117
+ await page.goto('/flexr/playground/');
118
+ await page.getByRole('combobox', { name: 'Choose a playground preset' }).selectOption('trivia');
119
+ await expect(page.locator('#spec')).toHaveValue(/channel: :comment/);
120
+ await page.getByRole('button', { name: 'Run', exact: true }).click();
121
+ await expect(page.locator('#status')).toContainText('2 tokens', { timeout: 30_000 });
122
+ const [first] = JSON.parse(await page.locator('#tokens').textContent());
123
+ expect(first.value).toBe('alpha');
124
+ expect(first.leading_trivia.map(item => [item.channel, item.value])).toEqual([['comment', '# note'], ['whitespace', '\n']]);
125
+ });
126
+
127
+ test('runs the equal-length rule priority preset', async ({ page }) => {
128
+ await page.goto('/flexr/playground/');
129
+ await page.getByRole('combobox', { name: 'Choose a playground preset' }).selectOption('priority');
130
+ await expect(page.locator('#spec')).toHaveValue(/priority: 10/);
131
+ await page.getByRole('button', { name: 'Run', exact: true }).click();
132
+ await expect(page.locator('#status')).toContainText('2 tokens', { timeout: 30_000 });
133
+ expect(JSON.parse(await page.locator('#tokens').textContent())).toEqual([['IF', 'if'], ['IDENT', 'ifx']]);
134
+ });
@@ -0,0 +1,71 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
5
+ import { devNull, tmpdir } from 'node:os';
6
+ import path from 'node:path';
7
+ import { stableReleaseTag as stableTag } from '../scripts/stable-release.mjs';
8
+
9
+ test('packages the released lexer and presets when building the public Playground', async () => {
10
+ const repo = await mkdtemp(path.join(tmpdir(), 'flexr-playground-release-'));
11
+ const site = path.join(repo, 'site');
12
+ const git = (...args) => execFileSync('git', args, {
13
+ cwd: repo,
14
+ env: { ...process.env, GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: '1' }
15
+ });
16
+ const write = async (name, contents) => {
17
+ const filename = path.join(repo, name);
18
+ await mkdir(path.dirname(filename), { recursive: true });
19
+ await writeFile(filename, contents);
20
+ };
21
+ const readAsset = async name => JSON.parse(await readFile(path.join(site, 'public/playground-runtime', name), 'utf8'));
22
+ const prepare = stable => execFileSync(process.execPath, ['scripts/prepare-playground.mjs'], {
23
+ cwd: site,
24
+ env: { ...process.env, FLEXR_PLAYGROUND_STABLE: stable ? '1' : '' }
25
+ });
26
+
27
+ try {
28
+ git('init', '-q');
29
+ await write('lib/flexr/version.rb', `Flexr::VERSION = "${stableTag.slice(1)}"\n`);
30
+ await write('lib/flexr.rb', '# Released lexer\n');
31
+ for (const name of ['toml', 'graphql', 'sql']) {
32
+ await write(`examples/${name}/lexer.flexr.rb`, `# Released ${name}\n`);
33
+ }
34
+ git('add', 'lib', 'examples');
35
+ git('-c', 'user.name=flexr test', '-c', 'user.email=flexr@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'Release');
36
+ git('tag', stableTag);
37
+ await write('lib/flexr.rb', '# Main lexer\n');
38
+ await write('lib/main-only.rb', '# Next release\n');
39
+ await write('examples/toml/lexer.flexr.rb', '# Main TOML\n');
40
+ await write('site/ruby/playground.rb', '# Playground bridge\n');
41
+ await write('site/ruby/presets/absence.flexr.rb', '# Main absence preset\n');
42
+ await write('site/ruby/presets/pattern.flexr.rb', '# Main pattern preset\n');
43
+ await write('site/ruby/presets/keywords.flexr.rb', '# Main keyword preset\n');
44
+ await write('site/ruby/presets/trivia.flexr.rb', '# Main trivia preset\n');
45
+ await write('site/ruby/presets/priority.flexr.rb', '# Main priority preset\n');
46
+ await cp(new URL('../scripts/', import.meta.url), path.join(site, 'scripts'), { recursive: true });
47
+ for (const asset of ['ruby+stdlib.wasm', 'LICENSE', 'NOTICE']) {
48
+ await write(`site/node_modules/@ruby/4.0-wasm-wasi/dist/${asset}`, '');
49
+ }
50
+
51
+ prepare(false);
52
+ assert.equal((await readAsset('flexr.json')).files['/app/lib/flexr.rb'], '# Main lexer\n');
53
+ assert.equal((await readAsset('presets.json')).toml.source, '# Main TOML\n');
54
+ assert.equal((await readAsset('presets.json')).absence.source, '# Main absence preset\n');
55
+ assert.equal((await readAsset('presets.json')).keywords.source, '# Main keyword preset\n');
56
+ assert.equal((await readAsset('presets.json')).trivia.source, '# Main trivia preset\n');
57
+ assert.equal((await readAsset('presets.json')).priority.source, '# Main priority preset\n');
58
+ prepare(true);
59
+ const { files } = await readAsset('flexr.json');
60
+ assert.equal(files['/app/lib/flexr.rb'], '# Released lexer\n');
61
+ assert.equal(files['/app/lib/main-only.rb'], undefined);
62
+ assert.equal((await readAsset('presets.json')).toml.source, '# Released toml\n');
63
+ assert.equal((await readAsset('presets.json')).absence, undefined);
64
+ assert.equal((await readAsset('presets.json')).pattern, undefined);
65
+ assert.equal((await readAsset('presets.json')).keywords, undefined);
66
+ assert.equal((await readAsset('presets.json')).trivia, undefined);
67
+ assert.equal((await readAsset('presets.json')).priority, undefined);
68
+ } finally {
69
+ await rm(repo, { recursive: true, force: true });
70
+ }
71
+ });
@@ -64,6 +64,44 @@ test('literal Unicode actions and surrounding constants survive generation', asy
64
64
  }
65
65
  });
66
66
 
67
+ test('the absence preset ends each comment at its first terminator', async () => {
68
+ const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
69
+ assert.match(presets.absence?.source ?? '', /\(\?~/);
70
+ for (const mode of ['runtime', 'generated']) {
71
+ const result = await runtime.run({ ...presets.absence, mode });
72
+ assert.equal(result.error, undefined, result.error);
73
+ assert.deepEqual(result.tokens, [['IDENT', 'first'], ['IDENT', 'second']]);
74
+ }
75
+ });
76
+
77
+ test('trivia keeps whitespace and comments in structured token output', async () => {
78
+ const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
79
+ assert.ok(presets.trivia, 'trivia preset is packaged');
80
+ const { source, input } = presets.trivia;
81
+ for (const mode of ['runtime', 'generated']) {
82
+ const result = await runtime.run({ source, input, mode });
83
+ assert.equal(result.error, undefined, result.error);
84
+ assert.deepEqual(result.tokens.map(token => [
85
+ token.type, token.value, token.channel,
86
+ token.leading_trivia.map(item => [item.channel, item.value]),
87
+ ]), [
88
+ ['WORD', 'alpha', 'default', [['comment', '# note'], ['whitespace', '\n']]],
89
+ ['WORD', 'beta', 'default', [['whitespace', ' \t']]],
90
+ ]);
91
+ assert.equal(result.tokens[0].leading_trivia[0].location.byte_end, 6);
92
+ assert.equal(result.tokens[0].location.line_begin, 2);
93
+ const withoutTrivia = await runtime.run({ source, input: 'alpha', mode });
94
+ assert.deepEqual(withoutTrivia.tokens[0].leading_trivia, []);
95
+ }
96
+ });
97
+
98
+ test('retains the existing display for ordinary structured tokens', async () => {
99
+ const source = 'class Lexer < Flexr::Lexer\n token_kind :struct\n rule("x", emit: :WORD)\nend';
100
+ const result = await runtime.run({ source, input: 'x', mode: 'runtime' });
101
+ assert.equal(result.error, undefined, result.error);
102
+ assert.match(result.tokens[0], /^#<data Flexr::Runtime::Token type=:WORD/);
103
+ });
104
+
67
105
  test('share links retain Unicode source and input without running code', () => {
68
106
  const state = { source: 'class Lexer; # café\nend', input: '日本語', mode: 'runtime' };
69
107
  assert.deepEqual(decodeState(encodeState(state)), state);
@@ -71,6 +109,38 @@ test('share links retain Unicode source and input without running code', () => {
71
109
  assert.throws(() => decodeState(btoa(JSON.stringify({ source: 5, input: '' }))), /Invalid/);
72
110
  });
73
111
 
112
+ test('priority changes the winner only on equal-length matches', async () => {
113
+ const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
114
+ for (const mode of ['runtime', 'generated']) {
115
+ const result = await runtime.run({ ...presets.priority, mode });
116
+ assert.equal(result.error, undefined, result.error);
117
+ assert.deepEqual(result.tokens, [['IF', 'if'], ['IDENT', 'ifx']]);
118
+ }
119
+ });
120
+
121
+ test('pattern algebra keeps overlapping delimiters and keywords distinct', async () => {
122
+ const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
123
+ for (const mode of ['runtime', 'generated']) {
124
+ const result = await runtime.run({ ...presets.pattern, mode });
125
+ assert.equal(result.error, undefined, result.error);
126
+ assert.deepEqual(result.tokens, [
127
+ ['KEYWORD', 'if'], ['IDENT', 'ifx'], ['BLOCK', '[[aba'], ['IDENT', 'ba'], ['KEYWORD', 'end'],
128
+ ]);
129
+ }
130
+ });
131
+
132
+ test('the keyword preset classifies exact identifiers in both modes', async () => {
133
+ const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
134
+ assert.ok(presets.keywords, 'keyword preset is packaged');
135
+ for (const mode of ['runtime', 'generated']) {
136
+ const result = await runtime.run({ ...presets.keywords, mode });
137
+ assert.equal(result.error, undefined, result.error);
138
+ assert.deepEqual(result.tokens, [
139
+ ['IF', 'if'], ['IDENT', 'iffy'], ['ELSE', 'else'], ['END', 'end'],
140
+ ]);
141
+ }
142
+ });
143
+
74
144
  test('language presets use the repository examples and run in both modes', async () => {
75
145
  const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
76
146
  for (const name of ['toml', 'graphql', 'sql']) {
@@ -106,6 +106,77 @@ RSpec.describe "Ruby LSP flexr add-on" do
106
106
  end
107
107
  end
108
108
 
109
+ it "explains an empty absence language in the rule hover" do
110
+ source = "class EditorLexer < Flexr::Lexer\n rule(/(?~a?)/, skip: true)\nend\n"
111
+ open_server(source) do |server, uri|
112
+ server.process_message(id: 1, method: "textDocument/hover", params: {
113
+ textDocument: { uri: uri }, position: { line: 1, character: 3 }
114
+ })
115
+ hover = pop_result(server).response
116
+ expect(hover.contents.value).to include("FLEXR-W001", "language is empty")
117
+ end
118
+ end
119
+
120
+ it "explains priority and a trivia channel on the same rule hover" do
121
+ source = "class EditorLexer < Flexr::Lexer\n rule(\"if\", emit: :IF, channel: :comment, priority: 10)\nend\n"
122
+ open_server(source) do |server, uri|
123
+ server.process_message(id: 1, method: "textDocument/hover", params: {
124
+ textDocument: { uri: uri }, position: { line: 1, character: 3 }
125
+ })
126
+ value = pop_result(server).response.contents.value
127
+ expect(value).to include("priority 10", "equal-length matches", ":comment", "trivia")
128
+ end
129
+ end
130
+
131
+ it "explains hidden token channels in rule hover without warnings" do
132
+ source = <<~RUBY
133
+ class EditorLexer < Flexr::Lexer
134
+ CHANNEL = :comment
135
+ rule(/#[^\\n]*/, channel: CHANNEL)
136
+ end
137
+ RUBY
138
+ open_server(source) do |server, uri|
139
+ server.process_message(id: 1, method: "textDocument/hover", params: {
140
+ textDocument: { uri: uri }, position: { line: 2, character: 3 }
141
+ })
142
+ hover = pop_result(server).response
143
+ expect(hover&.contents&.value).to include(":comment", "trivia")
144
+ end
145
+ end
146
+
147
+ it "describes keyword remapping and identifies invalid spellings on keyword hover" do
148
+ source = <<~RUBY
149
+ class EditorLexer < Flexr::Lexer
150
+ rule(/[a-z]+/, emit: :IDENT)
151
+ keywords %w[if if!], among: :IDENT
152
+ end
153
+ RUBY
154
+ open_server(source) do |server, uri|
155
+ server.process_message(id: 1, method: "textDocument/hover", params: {
156
+ textDocument: { uri: uri }, position: { line: 2, character: 4 }
157
+ })
158
+ hover = pop_result(server).response
159
+ expect(hover.contents.value).to include("Keyword table", "FLEXR-E028", '"if!"')
160
+ end
161
+ end
162
+
163
+ it "shows named pattern subtraction with its witness on rule hover" do
164
+ source = <<~RUBY
165
+ class EditorLexer < Flexr::Lexer
166
+ NAME = pattern(/[a-z]+/)
167
+ DIGIT = pattern(/[0-9]/)
168
+ rule(NAME - DIGIT, emit: :NAME)
169
+ end
170
+ RUBY
171
+ open_server(source) do |server, uri|
172
+ server.process_message(id: 1, method: "textDocument/hover", params: {
173
+ textDocument: { uri: uri }, position: { line: 3, character: 3 }
174
+ })
175
+ hover = pop_result(server).response
176
+ expect(hover.contents.value).to include("FLEXR-W021", "NAME", "DIGIT", '"0"')
177
+ end
178
+ end
179
+
109
180
  it "does not diagnose ordinary Ruby files or execute specification code" do
110
181
  source = "raise 'must not execute'\nclass EditorLexer < Flexr::Lexer\n rule(/a(?=b)/, skip: true)\nend\n"
111
182
  open_server(source, path: "ordinary.rb") do |server, uri|
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../lib/flexr/version"
4
+
5
+ version = Flexr::VERSION
6
+ tag = ARGV.first
7
+ abort "expected release tag v#{version}, got #{tag.inspect}" unless tag == "v#{version}"
8
+
9
+ path = ARGV.fetch(1) { File.expand_path("../CHANGELOG.md", __dir__) }
10
+ heading = "## [#{version}]("
11
+ section = File.read(path).split(/(?=^## )/).find { |entry| entry.start_with?(heading) }
12
+ notes = section.to_s.lines.drop(1).join.strip
13
+ abort "missing changelog notes for #{version}" if notes.empty?
14
+
15
+ puts notes
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: flexr
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0
4
+ version: 2.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yudai Takada
@@ -55,6 +55,12 @@ files:
55
55
  - docs/adr/0018-prism-for-generator-only.md
56
56
  - docs/adr/0019-measured-performance-floor.md
57
57
  - docs/adr/0020-vendored-unicode-contract.md
58
+ - docs/adr/0027-per-engine-performance-targets.md
59
+ - docs/adr/0028-dfa-absence-groups.md
60
+ - docs/adr/0029-pattern-algebra.md
61
+ - docs/adr/0030-classify-keywords-after-matching.md
62
+ - docs/adr/0031-trivia-channels.md
63
+ - docs/adr/0032-explicit-rule-priority.md
58
64
  - docs/explanation/backends.md
59
65
  - docs/explanation/matching-semantics.md
60
66
  - docs/explanation/runtime-vs-generated.md
@@ -120,6 +126,8 @@ files:
120
126
  - lib/flexr/automaton/byte_class_set.rb
121
127
  - lib/flexr/automaton/compiler.rb
122
128
  - lib/flexr/automaton/dfa.rb
129
+ - lib/flexr/automaton/dfa_operations.rb
130
+ - lib/flexr/automaton/keyword_tables.rb
123
131
  - lib/flexr/automaton/minimizer.rb
124
132
  - lib/flexr/automaton/nfa.rb
125
133
  - lib/flexr/automaton/types.rb
@@ -139,10 +147,12 @@ files:
139
147
  - lib/flexr/grammar.rb
140
148
  - lib/flexr/importer.rb
141
149
  - lib/flexr/ir.rb
150
+ - lib/flexr/keywords.rb
142
151
  - lib/flexr/lexer.rb
143
152
  - lib/flexr/migration.rb
144
153
  - lib/flexr/minitest.rb
145
154
  - lib/flexr/options.rb
155
+ - lib/flexr/pattern.rb
146
156
  - lib/flexr/rake_task.rb
147
157
  - lib/flexr/regexp/ast.rb
148
158
  - lib/flexr/regexp/char_class.rb
@@ -155,6 +165,7 @@ files:
155
165
  - lib/flexr/rspec.rb
156
166
  - lib/flexr/runtime.rb
157
167
  - lib/flexr/runtime/buffer.rb
168
+ - lib/flexr/runtime/channels.rb
158
169
  - lib/flexr/runtime/core.rb
159
170
  - lib/flexr/runtime/errors.rb
160
171
  - lib/flexr/runtime/interpreter.rb
@@ -187,8 +198,16 @@ files:
187
198
  - site/pnpm-lock.yaml
188
199
  - site/pnpm-workspace.yaml
189
200
  - site/ruby/playground.rb
201
+ - site/ruby/presets/absence.flexr.rb
202
+ - site/ruby/presets/keywords.flexr.rb
203
+ - site/ruby/presets/pattern.flexr.rb
204
+ - site/ruby/presets/priority.flexr.rb
205
+ - site/ruby/presets/trivia.flexr.rb
206
+ - site/scripts/prepare-docs.mjs
190
207
  - site/scripts/prepare-playground.mjs
208
+ - site/scripts/stable-release.mjs
191
209
  - site/scripts/verify-site.mjs
210
+ - site/src/components/DocsTitle.astro
192
211
  - site/src/content.config.ts
193
212
  - site/src/content/docs/benchmarks.md
194
213
  - site/src/content/docs/concepts/matching-semantics.md
@@ -208,6 +227,7 @@ files:
208
227
  - site/src/content/docs/reference/regexp.md
209
228
  - site/src/content/docs/reference/runtime.md
210
229
  - site/src/content/docs/reference/tokens-and-locations.md
230
+ - site/src/docs-navigation.ts
211
231
  - site/src/env.d.ts
212
232
  - site/src/layouts/SiteLayout.astro
213
233
  - site/src/pages/index.astro
@@ -220,7 +240,9 @@ files:
220
240
  - site/src/playground/worker.mjs
221
241
  - site/src/styles/custom.css
222
242
  - site/src/styles/landing.css
243
+ - site/tests/browser/documentation-versions.spec.mjs
223
244
  - site/tests/browser/playground.spec.mjs
245
+ - site/tests/playground-release.test.mjs
224
246
  - site/tests/playground-runtime.test.mjs
225
247
  - site/tsconfig.json
226
248
  - test/ruby_lsp_addon_spec.rb
@@ -229,6 +251,7 @@ files:
229
251
  - tools/gen_unicode_tables.rb
230
252
  - tools/golden.rb
231
253
  - tools/regexp_tokenizer_reference.rb
254
+ - tools/release_notes.rb
232
255
  - tools/verification_failure.rb
233
256
  homepage: https://github.com/ydah/flexr
234
257
  licenses: