flexr 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/README.md +4 -0
  4. data/benchmark/dfa_stretch.rb +149 -0
  5. data/benchmark/lrama_lexer.rb +79 -96
  6. data/benchmark/regexp_parser_corpus.rb +35 -0
  7. data/benchmark/regexp_parser_parity.rb +89 -0
  8. data/benchmark/regexp_parser_scanner.rb +159 -0
  9. data/docs/README.md +4 -1
  10. data/docs/adr/0021-ruby-34-minimum.md +23 -0
  11. data/docs/adr/0022-immutable-tokens-and-locations.md +22 -0
  12. data/docs/adr/0023-stable-explicit-firstmatch.md +21 -0
  13. data/docs/adr/0024-opt-in-ractor-sharing.md +24 -0
  14. data/docs/adr/0025-explicit-whole-token-acceleration.md +26 -0
  15. data/docs/adr/0026-retain-direct-dispatch.md +22 -0
  16. data/docs/adr/0033-action-free-recognition.md +33 -0
  17. data/docs/adr/0034-lexer-checkpoints.md +25 -0
  18. data/docs/adr/0035-parser-token-expectations.md +27 -0
  19. data/docs/adr/0038-replay-named-regexp-captures.md +23 -0
  20. data/docs/adr/0039-input-stack.md +25 -0
  21. data/docs/adr/0040-runtime-delimiters.md +23 -0
  22. data/docs/adr/0041-post-lexical-indentation.md +24 -0
  23. data/docs/adr/0042-capture-delegation.md +23 -0
  24. data/docs/adr/0043-expand-reusable-rules-explicitly.md +27 -0
  25. data/docs/adr/0044-import-oedipus-firstmatch.md +26 -0
  26. data/docs/assets/playground-absence-and-diagnostics.gif +0 -0
  27. data/docs/explanation/backends.md +5 -4
  28. data/docs/how-to/integrate-with-lrama.md +9 -8
  29. data/docs/how-to/integrate-with-racc.md +9 -0
  30. data/docs/how-to/migrate-from-oedipus-lex.md +43 -0
  31. data/docs/how-to/parser-driven-lexing.md +48 -0
  32. data/docs/how-to/try-playground-demos.md +13 -0
  33. data/docs/internals/regexp-parser-experiment.md +67 -0
  34. data/docs/perf-log.md +120 -8
  35. data/docs/reference/README.md +1 -1
  36. data/docs/reference/actions.md +106 -0
  37. data/docs/reference/cli.md +75 -4
  38. data/docs/reference/diagnostics.md +3 -9
  39. data/docs/reference/dsl.md +66 -3
  40. data/docs/reference/public-api.md +8 -1
  41. data/docs/reference/regexp.md +27 -4
  42. data/docs/reference/ruby-lsp.md +15 -0
  43. data/docs/reference/runtime.md +163 -2
  44. data/docs/tutorial/build-a-calculator-parser.md +47 -0
  45. data/examples/with_lrama/README.md +3 -3
  46. data/lib/flexr/automaton/accel.rb +1 -0
  47. data/lib/flexr/automaton/compiler.rb +15 -0
  48. data/lib/flexr/automaton/dfa.rb +0 -33
  49. data/lib/flexr/automaton/keyword_tables.rb +14 -8
  50. data/lib/flexr/automaton/reference_dfa.rb +38 -0
  51. data/lib/flexr/cli.rb +118 -18
  52. data/lib/flexr/codegen/table.rb +7 -0
  53. data/lib/flexr/configuration.rb +18 -1
  54. data/lib/flexr/dsl.rb +14 -3
  55. data/lib/flexr/generated.rb +4 -0
  56. data/lib/flexr/generator.rb +39 -7
  57. data/lib/flexr/importer/oedipus_lex.rb +229 -0
  58. data/lib/flexr/importer.rb +7 -2
  59. data/lib/flexr/ir.rb +1 -1
  60. data/lib/flexr/options.rb +3 -0
  61. data/lib/flexr/project_template.rb +46 -0
  62. data/lib/flexr/project_templates/common/.gitignore +1 -0
  63. data/lib/flexr/project_templates/common/lexer.flexr.rb +12 -0
  64. data/lib/flexr/project_templates/common/test_calculator.rb +15 -0
  65. data/lib/flexr/project_templates/lrama/Gemfile +9 -0
  66. data/lib/flexr/project_templates/lrama/README.md +17 -0
  67. data/lib/flexr/project_templates/lrama/Rakefile +18 -0
  68. data/lib/flexr/project_templates/lrama/calculator.rb +28 -0
  69. data/lib/flexr/project_templates/lrama/parser.y +72 -0
  70. data/lib/flexr/project_templates/racc/Gemfile +8 -0
  71. data/lib/flexr/project_templates/racc/README.md +15 -0
  72. data/lib/flexr/project_templates/racc/Rakefile +14 -0
  73. data/lib/flexr/project_templates/racc/calculator.rb +22 -0
  74. data/lib/flexr/project_templates/racc/parser.y +19 -0
  75. data/lib/flexr/regexp/ast.rb +2 -0
  76. data/lib/flexr/regexp/parser.rb +13 -11
  77. data/lib/flexr/regexp/tokenizer.rb +2 -2
  78. data/lib/flexr/rules.rb +53 -0
  79. data/lib/flexr/runtime/buffer.rb +1 -1
  80. data/lib/flexr/runtime/captures.rb +46 -0
  81. data/lib/flexr/runtime/channels.rb +2 -1
  82. data/lib/flexr/runtime/checkpoint.rb +116 -0
  83. data/lib/flexr/runtime/core.rb +55 -43
  84. data/lib/flexr/runtime/delegation.rb +123 -0
  85. data/lib/flexr/runtime/delimiters.rb +89 -0
  86. data/lib/flexr/runtime/firstmatch.rb +266 -0
  87. data/lib/flexr/runtime/indentation.rb +235 -0
  88. data/lib/flexr/runtime/input_stack.rb +48 -0
  89. data/lib/flexr/runtime/interpreter.rb +36 -314
  90. data/lib/flexr/runtime/recognizer.rb +106 -0
  91. data/lib/flexr/runtime.rb +10 -0
  92. data/lib/flexr/skeleton/verification.rb +103 -0
  93. data/lib/flexr/skeleton.rb +208 -0
  94. data/lib/flexr/source/fixes.rb +145 -0
  95. data/lib/flexr/source/prism_reader.rb +187 -25
  96. data/lib/flexr/testing.rb +5 -2
  97. data/lib/flexr/unicode/reference_regexp.rb +29 -11
  98. data/lib/flexr/version.rb +1 -1
  99. data/lib/ruby_lsp/flexr/addon.rb +88 -13
  100. data/lib/ruby_lsp/flexr/navigation.rb +231 -0
  101. data/lib/ruby_lsp/flexr/ranges.rb +40 -0
  102. data/sig/flexr.rbs +33 -3
  103. data/site/README.md +22 -7
  104. data/site/ruby/presets/heredoc.flexr.rb +15 -0
  105. data/site/ruby/presets/html_javascript.rb +12 -0
  106. data/site/ruby/presets/html_js.flexr.rb +14 -0
  107. data/site/ruby/presets/indentation.flexr.rb +14 -0
  108. data/site/scripts/prepare-playground.mjs +16 -6
  109. data/site/scripts/stable-release.mjs +4 -1
  110. data/site/src/content/docs/learn/parser-integration.md +23 -8
  111. data/site/src/content/docs/reference/cli.md +3 -0
  112. data/site/src/content/docs/reference/dsl.md +1 -0
  113. data/site/src/content/docs/reference/runtime.md +26 -0
  114. data/site/src/pages/playground.astro +15 -1
  115. data/site/src/playground/client.js +30 -1
  116. data/site/src/playground/issue.mjs +19 -0
  117. data/site/src/playground/runtime.mjs +4 -3
  118. data/site/src/playground/worker.mjs +1 -1
  119. data/site/tests/browser/playground.spec.mjs +64 -0
  120. data/site/tests/playground-issue.test.mjs +15 -0
  121. data/site/tests/playground-release.test.mjs +62 -11
  122. data/site/tests/playground-runtime.test.mjs +48 -0
  123. data/test/ruby_lsp_addon_spec.rb +174 -0
  124. metadata +63 -1
@@ -27,6 +27,9 @@ const presets = JSON.parse(await readFile(new URL('../../public/playground-runti
27
27
  {Object.hasOwn(presets, 'keywords') && <option value="keywords">Keywords and identifiers</option>}
28
28
  {Object.hasOwn(presets, 'trivia') && <option value="trivia">Comments and whitespace trivia</option>}
29
29
  {Object.hasOwn(presets, 'priority') && <option value="priority">Equal-length rule priority</option>}
30
+ {Object.hasOwn(presets, 'indentation') && <option value="indentation">Python-like indentation</option>}
31
+ {Object.hasOwn(presets, 'heredoc') && <option value="heredoc">Dynamic heredoc</option>}
32
+ {Object.hasOwn(presets, 'html-js') && <option value="html-js">HTML with embedded JavaScript</option>}
30
33
  </select>
31
34
  <textarea id="spec" aria-label="Lexer specification" spellcheck="false" maxlength="20000"></textarea>
32
35
  </div>
@@ -41,6 +44,7 @@ const presets = JSON.parse(await readFile(new URL('../../public/playground-runti
41
44
  </div>
42
45
  <input id="share-link" class="share-link" aria-label="Share link" readonly hidden />
43
46
  <p id="status" class="workbench-status" role="status" aria-live="polite">Choose a preset or write a specification, then select Run.</p>
47
+ <p id="flexr-version" class="workbench-status" hidden></p>
44
48
  <p id="metrics" class="workbench-status"></p>
45
49
  </div>
46
50
  <div class="workbench-panel full">
@@ -48,8 +52,18 @@ const presets = JSON.parse(await readFile(new URL('../../public/playground-runti
48
52
  <pre id="tokens" class="workbench-output">Run a specification to see its token stream.</pre>
49
53
  </div>
50
54
  <div class="workbench-panel full">
51
- <div class="panel-heading"><span>Diagnostics</span></div>
55
+ <div class="panel-heading">
56
+ <span>Diagnostics</span>
57
+ <button type="button" data-action="report" aria-expanded="false" aria-controls="issue-preview" disabled>Prepare issue draft</button>
58
+ </div>
52
59
  <pre id="diagnostics" class="workbench-output">Compiler warnings and source locations appear here.</pre>
60
+ <div id="issue-preview" hidden>
61
+ <label for="issue-body">Issue draft</label>
62
+ <textarea id="issue-body" rows="8" readonly></textarea>
63
+ <p>Review the source and input before opening the GitHub form.</p>
64
+ <p id="issue-manual-paste" hidden>Copy this draft and paste it into the GitHub form.</p>
65
+ <a id="issue-link" target="_blank" rel="noreferrer">Open GitHub issue form</a>
66
+ </div>
53
67
  </div>
54
68
  <div class="workbench-panel full">
55
69
  <div class="panel-heading"><span>Match decisions</span><span id="step-position">No scan steps.</span></div>
@@ -1,14 +1,18 @@
1
1
  import workerUrl from './worker.mjs?worker&url';
2
2
  import graphWorkerUrl from './graph-worker.mjs?worker&url';
3
3
  import { PRESETS } from './presets.mjs';
4
+ import { issueDraft } from './issue.mjs';
4
5
  import { decodeState, encodeState, validateState } from './share.mjs';
5
6
 
6
7
  const source = document.querySelector('#spec');
7
8
  const input = document.querySelector('#input');
8
9
  const mode = document.querySelector('#mode');
9
10
  const status = document.querySelector('#status');
11
+ const versionLabel = document.querySelector('#flexr-version');
10
12
  const runButton = document.querySelector('[data-action="run"]');
11
13
  const stopButton = document.querySelector('[data-action="stop"]');
14
+ const reportButton = document.querySelector('[data-action="report"]');
15
+ const issuePreview = document.querySelector('#issue-preview');
12
16
  const steps = document.querySelector('#step');
13
17
  let worker;
14
18
  let timer;
@@ -16,6 +20,7 @@ let graphWorker;
16
20
  let graphTimer;
17
21
  let trace = [];
18
22
  let dot = '';
23
+ let report;
19
24
 
20
25
  function show(id, text) { document.querySelector(`#${id}`).textContent = text; }
21
26
 
@@ -67,8 +72,12 @@ function display(result) {
67
72
 
68
73
  function run() {
69
74
  stop();
75
+ versionLabel.hidden = true;
70
76
  try {
71
77
  const state = validateState({ source: source.value, input: input.value, mode: mode.value });
78
+ reportButton.disabled = true;
79
+ reportButton.setAttribute('aria-expanded', 'false');
80
+ issuePreview.hidden = true;
72
81
  show('tokens', 'Running…');
73
82
  show('diagnostics', 'Compiling…');
74
83
  show('generated', 'Generating…');
@@ -91,18 +100,30 @@ function run() {
91
100
  timer = setTimeout(() => stop('Runtime loading exceeded 30 seconds. Check the connection and retry.'), 30_000);
92
101
  worker.onerror = () => stop('The worker failed. Retry, or reduce the specification.');
93
102
  let started = false;
103
+ let flexrVersion;
94
104
  const currentWorker = worker;
95
105
  worker.onmessage = ({ data }) => {
96
106
  if (currentWorker !== worker) return;
97
107
  if (data?.phase === 'ready' && !started) {
98
108
  started = true;
109
+ flexrVersion = data.flexrVersion;
99
110
  clearTimeout(timer);
111
+ versionLabel.textContent = `flexr ${data.flexrVersion}`;
112
+ versionLabel.hidden = false;
100
113
  status.textContent = 'Running the specification in a worker…';
101
114
  timer = setTimeout(() => stop('Execution exceeded 5 seconds and was stopped. Reduce the specification or input.'), 5_000);
102
115
  } else if (data?.phase === 'error') {
103
116
  stop(String(data.error));
104
117
  } else if (data?.phase === 'result') {
105
- try { display(data.result); } catch (error) { stop(error.message); }
118
+ try {
119
+ display(data.result);
120
+ if (typeof flexrVersion === 'string') {
121
+ report = {
122
+ ...state, version: flexrVersion, diagnostics: data.result.error || data.result.diagnostics || 'No diagnostics.',
123
+ };
124
+ reportButton.disabled = false;
125
+ }
126
+ } catch (error) { stop(error.message); }
106
127
  }
107
128
  };
108
129
  const base = new URL(`${import.meta.env.BASE_URL}/playground-runtime/`.replaceAll('//', '/'), location.origin).href;
@@ -179,6 +200,14 @@ document.querySelector('#preset').addEventListener('change', async event => {
179
200
  document.querySelector('[data-action="run"]').addEventListener('click', run);
180
201
  document.querySelector('[data-action="stop"]').addEventListener('click', () => stop());
181
202
  document.querySelector('[data-action="draw"]').addEventListener('click', drawGraph);
203
+ reportButton.addEventListener('click', () => {
204
+ const draft = issueDraft(report);
205
+ document.querySelector('#issue-body').value = draft.body;
206
+ document.querySelector('#issue-link').href = draft.url.href;
207
+ document.querySelector('#issue-manual-paste').hidden = !draft.manualPaste;
208
+ issuePreview.hidden = !issuePreview.hidden;
209
+ reportButton.setAttribute('aria-expanded', String(!issuePreview.hidden));
210
+ });
182
211
  document.querySelector('[data-action="previous"]').addEventListener('click', () => selectStep(Number(steps.value) - 1));
183
212
  document.querySelector('[data-action="next"]').addEventListener('click', () => selectStep(Number(steps.value) + 1));
184
213
  steps.addEventListener('input', () => selectStep(Number(steps.value)));
@@ -0,0 +1,19 @@
1
+ function section(title, text) {
2
+ const code = text.split('\n').map(line => ` ${line}`).join('\n');
3
+ return `### ${title}\n\n${code}`;
4
+ }
5
+
6
+ export function issueDraft({ source, input, mode, version, diagnostics }) {
7
+ const body = [
8
+ section('Version and mode', `flexr ${version}\n${mode}`),
9
+ section('Lexer specification', source),
10
+ section('Input', input),
11
+ section('Diagnostics', diagnostics),
12
+ ].join('\n\n');
13
+ const url = new URL('https://github.com/ydah/flexr/issues/new');
14
+ url.searchParams.set('title', 'Playground reproduction');
15
+ url.searchParams.set('body', body);
16
+ const manualPaste = url.href.length > 7500;
17
+ if (manualPaste) url.searchParams.delete('body');
18
+ return { body, url, manualPaste };
19
+ }
@@ -15,7 +15,7 @@ export async function createRuntime(binary, assets) {
15
15
  validateState(request);
16
16
  const start = performance.now();
17
17
  const { vm } = await DefaultRubyVM(module, { consolePrint: false });
18
- vm.eval(`require "json"; require "fileutils"
18
+ const flexrVersion = vm.eval(`require "json"; require "fileutils"
19
19
  ${rubyData(assets.files)}.each do |path, source|
20
20
  FileUtils.mkdir_p(File.dirname(path))
21
21
  File.write(path, source)
@@ -24,9 +24,10 @@ export async function createRuntime(binary, assets) {
24
24
  require "flexr/cli"
25
25
  require "flexr/trace"
26
26
  load "/app/playground.rb"
27
- `);
27
+ Flexr::VERSION
28
+ `).toString();
28
29
  const startupMs = performance.now() - start;
29
- ready(startupMs);
30
+ ready(startupMs, flexrVersion);
30
31
  const result = JSON.parse(vm.eval(`FlexrPlayground.run(${rubyData(request)})`).toString());
31
32
  return { ...result, startup_ms: startupMs };
32
33
  },
@@ -17,7 +17,7 @@ export async function run({ state, base }) {
17
17
  }
18
18
  }
19
19
  }
20
- const result = await runtime.run(state, startupMs => postMessage({ phase: 'ready', startupMs }));
20
+ const result = await runtime.run(state, (startupMs, flexrVersion) => postMessage({ phase: 'ready', startupMs, flexrVersion }));
21
21
  const payload = JSON.stringify({ ...result, wasm_bytes: binary.byteLength, download_ms: downloadMs });
22
22
  if (new TextEncoder().encode(payload).byteLength > 4_000_000) throw new Error('Output exceeds 4 MB. Reduce the input or number of states.');
23
23
  postMessage({ phase: 'result', result: JSON.parse(payload) });
@@ -1,5 +1,9 @@
1
+ import { readFile } from 'node:fs/promises';
1
2
  import { test, expect } from '@playwright/test';
2
3
 
4
+ const assets = JSON.parse(await readFile(new URL('../../public/playground-runtime/flexr.json', import.meta.url), 'utf8'));
5
+ const flexrVersion = assets.files['/app/lib/flexr/version.rb'].match(/VERSION = "([^"]+)"/)[1];
6
+
3
7
  test('runs actual edited Ruby, steps the trace, draws the DFA, and restores a share link without running', async ({ page }, testInfo) => {
4
8
  const wasm = [];
5
9
  const errors = [];
@@ -8,12 +12,14 @@ test('runs actual edited Ruby, steps the trace, draws the DFA, and restores a sh
8
12
  await page.goto('/flexr/playground/');
9
13
  await expect(page.locator('#spec')).toContainText('');
10
14
  await expect(page.locator('#spec')).toHaveValue(/class Lexer/);
15
+ await expect(page.locator('#flexr-version')).toBeHidden();
11
16
  expect(wasm).toHaveLength(0);
12
17
  const source = 'class Lexer < Flexr::Lexer\n emits :INT\n rule(/[0-9]+/) { emit :INT, text.to_i * 3 }\n rule(/ +/, skip: true)\nend';
13
18
  await page.locator('#spec').fill(source);
14
19
  await page.locator('#input').fill('12 2');
15
20
  await page.getByRole('button', { name: 'Run', exact: true }).click();
16
21
  await expect(page.locator('#status')).toContainText('2 tokens, 3 steps', { timeout: 30_000 });
22
+ await expect(page.getByText(`flexr ${flexrVersion}`, { exact: true })).toBeVisible();
17
23
  expect(JSON.parse(await page.locator('#tokens').textContent())).toEqual([['INT', 36], ['INT', 6]]);
18
24
  await expect(page.locator('#metrics')).toContainText('MiB Ruby download');
19
25
  console.log(`Playground measurement: ${await page.locator('#metrics').textContent()}; ${await page.evaluate(() => navigator.userAgent)}`);
@@ -36,6 +42,7 @@ test('runs actual edited Ruby, steps the trace, draws the DFA, and restores a sh
36
42
  await shared.goto(link);
37
43
  await expect(shared.locator('#spec')).toHaveValue(source);
38
44
  await expect(shared.locator('#status')).toContainText('Review it');
45
+ await expect(shared.locator('#flexr-version')).toBeHidden();
39
46
  await expect(shared.locator('#mode')).toHaveValue('generated');
40
47
  await shared.setViewportSize({ width: 390, height: 844 });
41
48
  await shared.screenshot({ path: testInfo.outputPath('playground-mobile.png') });
@@ -51,10 +58,36 @@ test('shows source diagnostics and terminates runaway Ruby while the UI stays re
51
58
  await page.getByRole('button', { name: 'Run', exact: true }).click();
52
59
  await expect(page.locator('#diagnostics')).toContainText('FLEXR-E014', { timeout: 30_000 });
53
60
  await expect(page.locator('#diagnostics')).toContainText('playground.flexr.rb:2:');
61
+ await expect(page.getByText(`flexr ${flexrVersion}`, { exact: true })).toBeVisible();
54
62
  await page.locator('#spec').fill('loop {}\nclass Lexer < Flexr::Lexer\n rule(/a/, emit: :A)\nend');
55
63
  await page.getByRole('button', { name: 'Run', exact: true }).click();
56
64
  await expect(page.locator('#status')).toContainText('Execution exceeded 5 seconds', { timeout: 15_000 });
57
65
  await expect(page.getByRole('button', { name: 'Run', exact: true })).toBeEnabled();
66
+ await expect(page.getByText(`flexr ${flexrVersion}`, { exact: true })).toBeVisible();
67
+ });
68
+
69
+ test('prepares an issue draft from the run with its exact version and diagnostics', async ({ page }) => {
70
+ await page.goto('/flexr/playground/');
71
+ const prepare = page.getByRole('button', { name: 'Prepare issue draft' });
72
+ await expect(prepare).toBeDisabled();
73
+ const source = 'class ReportLexer < Flexr::Lexer\n rule(/a(?=b)/, emit: :A)\nend';
74
+ await page.locator('#spec').fill(source);
75
+ await page.locator('#input').fill('ab');
76
+ await page.getByRole('button', { name: 'Run', exact: true }).click();
77
+ await expect(page.locator('#diagnostics')).toContainText('FLEXR-E014', { timeout: 30_000 });
78
+ await page.locator('#input').fill('a later edit');
79
+ await prepare.click();
80
+ const link = page.getByRole('link', { name: 'Open GitHub issue form' });
81
+ const url = new URL(await link.getAttribute('href'));
82
+ expect(url.origin + url.pathname).toBe('https://github.com/ydah/flexr/issues/new');
83
+ const body = url.searchParams.get('body');
84
+ expect(body).toContain(`flexr ${flexrVersion}`);
85
+ expect(body).toContain('class ReportLexer');
86
+ expect(body).toContain(' ab\n');
87
+ expect(body).toContain('FLEXR-E014');
88
+ expect(body).not.toContain('a later edit');
89
+ await expect(page.getByRole('textbox', { name: 'Issue draft' })).toHaveValue(body);
90
+ await expect(page).toHaveURL(/\/flexr\/playground\/$/);
58
91
  });
59
92
 
60
93
  test('treats tokens and console text as text and disables worker network access', async ({ page }) => {
@@ -132,3 +165,34 @@ test('runs the equal-length rule priority preset', async ({ page }) => {
132
165
  await expect(page.locator('#status')).toContainText('2 tokens', { timeout: 30_000 });
133
166
  expect(JSON.parse(await page.locator('#tokens').textContent())).toEqual([['IF', 'if'], ['IDENT', 'ifx']]);
134
167
  });
168
+
169
+ for (const mode of ['runtime', 'generated']) {
170
+ test(`runs the context presets in ${mode} mode`, async ({ page }) => {
171
+ await page.goto('/flexr/playground/');
172
+ const preset = page.getByRole('combobox', { name: 'Choose a playground preset' });
173
+ const run = page.getByRole('button', { name: 'Run', exact: true });
174
+ const status = page.locator('#status');
175
+ const tokens = page.locator('#tokens');
176
+ await page.locator('#mode').selectOption(mode);
177
+
178
+ await preset.selectOption('indentation');
179
+ await expect(page.locator('#spec')).toHaveValue(/indentation newline:/);
180
+ await run.click();
181
+ await expect(status).toContainText('13 tokens', { timeout: 30_000 });
182
+ expect(JSON.parse(await tokens.textContent()).map(token => token.type)).toEqual(expect.arrayContaining(['INDENT', 'DEDENT']));
183
+
184
+ await preset.selectOption('heredoc');
185
+ await expect(page.locator('#spec')).toHaveValue(/scan_until_line/);
186
+ await run.click();
187
+ await expect(status).toContainText('3 tokens', { timeout: 30_000 });
188
+ expect(JSON.parse(await tokens.textContent())).toEqual([['HEREDOC', 'hello\n'], ['HEREDOC', 'world\n'], ['WORD', 'next']]);
189
+
190
+ await preset.selectOption('html-js');
191
+ await expect(page.locator('#spec')).toHaveValue(/delegate PlaygroundJavaScriptLexer/);
192
+ await run.click();
193
+ await expect(status).toContainText('11 tokens', { timeout: 30_000 });
194
+ expect(JSON.parse(await tokens.textContent())[3]).toMatchObject({
195
+ type: 'JS_LET', value: 'let', location: { byte_begin: 23, line_begin: 3 },
196
+ });
197
+ });
198
+ }
@@ -0,0 +1,15 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { issueDraft } from '../src/playground/issue.mjs';
4
+
5
+ test('keeps the full local draft when the encoded URL is too long', () => {
6
+ const source = 'é'.repeat(20_000);
7
+ const { body, url, manualPaste } = issueDraft({
8
+ source, input: '<!-- example -->', mode: 'generated', version: '2.0.0', diagnostics: 'FLEXR-E014',
9
+ });
10
+ assert.ok(body.includes(source));
11
+ assert.ok(body.includes(' <!-- example -->'));
12
+ assert.equal(manualPaste, true);
13
+ assert.equal(url.searchParams.has('body'), false);
14
+ assert.equal(url.pathname, '/ydah/flexr/issues/new');
15
+ });
@@ -4,9 +4,8 @@ import { execFileSync } from 'node:child_process';
4
4
  import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
5
5
  import { devNull, tmpdir } from 'node:os';
6
6
  import path from 'node:path';
7
- import { stableReleaseTag as stableTag } from '../scripts/stable-release.mjs';
8
7
 
9
- test('packages the released lexer and presets when building the public Playground', async () => {
8
+ test('packages docs, lexer and presets from the selected release', async () => {
10
9
  const repo = await mkdtemp(path.join(tmpdir(), 'flexr-playground-release-'));
11
10
  const site = path.join(repo, 'site');
12
11
  const git = (...args) => execFileSync('git', args, {
@@ -19,21 +18,31 @@ test('packages the released lexer and presets when building the public Playgroun
19
18
  await writeFile(filename, contents);
20
19
  };
21
20
  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
- });
21
+ const prepare = (script, env = {}) => {
22
+ const cleanEnv = { ...process.env };
23
+ delete cleanEnv.FLEXR_STABLE_RELEASE_TAG;
24
+ delete cleanEnv.FLEXR_PLAYGROUND_STABLE;
25
+ execFileSync(process.execPath, [`scripts/prepare-${script}.mjs`], {
26
+ cwd: site, env: { ...cleanEnv, ...env }, stdio: 'pipe'
27
+ });
28
+ };
29
+ const docs = 'site/src/content/docs/getting-started.md';
30
+ const stableDocs = 'site/src/content/docs/stable/getting-started.md';
31
+ const fixedDocLink = 'https://github.com/ydah/flexr/blob/main/lib/flexr.rb';
26
32
 
27
33
  try {
28
34
  git('init', '-q');
29
- await write('lib/flexr/version.rb', `Flexr::VERSION = "${stableTag.slice(1)}"\n`);
35
+ await write('lib/flexr/version.rb', 'Flexr::VERSION = "2.0.0"\n');
30
36
  await write('lib/flexr.rb', '# Released lexer\n');
31
37
  for (const name of ['toml', 'graphql', 'sql']) {
32
38
  await write(`examples/${name}/lexer.flexr.rb`, `# Released ${name}\n`);
33
39
  }
34
- git('add', 'lib', 'examples');
40
+ await write('site/ruby/presets/heredoc.flexr.rb', '# Released heredoc preset\n');
41
+ await write('site/ruby/presets/html_js.flexr.rb', '# Released HTML and JS preset\n');
42
+ await write(docs, `Default release docs. [Lexer](${fixedDocLink})\n`);
43
+ git('add', 'lib', 'examples', 'site/ruby/presets', docs);
35
44
  git('-c', 'user.name=flexr test', '-c', 'user.email=flexr@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'Release');
36
- git('tag', stableTag);
45
+ git('tag', 'v2.0.0');
37
46
  await write('lib/flexr.rb', '# Main lexer\n');
38
47
  await write('lib/main-only.rb', '# Next release\n');
39
48
  await write('examples/toml/lexer.flexr.rb', '# Main TOML\n');
@@ -43,19 +52,31 @@ test('packages the released lexer and presets when building the public Playgroun
43
52
  await write('site/ruby/presets/keywords.flexr.rb', '# Main keyword preset\n');
44
53
  await write('site/ruby/presets/trivia.flexr.rb', '# Main trivia preset\n');
45
54
  await write('site/ruby/presets/priority.flexr.rb', '# Main priority preset\n');
55
+ await write('site/ruby/presets/indentation.flexr.rb', '# Main indentation preset\n');
56
+ await write('site/ruby/presets/heredoc.flexr.rb', '# Main heredoc preset\n');
57
+ await write('site/ruby/presets/html_js.flexr.rb', '# Main HTML and JS preset\n');
58
+ await write('site/ruby/presets/html_javascript.rb', '# Main JavaScript lexer\n');
46
59
  await cp(new URL('../scripts/', import.meta.url), path.join(site, 'scripts'), { recursive: true });
47
60
  for (const asset of ['ruby+stdlib.wasm', 'LICENSE', 'NOTICE']) {
48
61
  await write(`site/node_modules/@ruby/4.0-wasm-wasi/dist/${asset}`, '');
49
62
  }
50
63
 
51
- prepare(false);
64
+ prepare('playground');
52
65
  assert.equal((await readAsset('flexr.json')).files['/app/lib/flexr.rb'], '# Main lexer\n');
53
66
  assert.equal((await readAsset('presets.json')).toml.source, '# Main TOML\n');
54
67
  assert.equal((await readAsset('presets.json')).absence.source, '# Main absence preset\n');
55
68
  assert.equal((await readAsset('presets.json')).keywords.source, '# Main keyword preset\n');
56
69
  assert.equal((await readAsset('presets.json')).trivia.source, '# Main trivia preset\n');
57
70
  assert.equal((await readAsset('presets.json')).priority.source, '# Main priority preset\n');
58
- prepare(true);
71
+ assert.equal((await readAsset('presets.json')).indentation.source, '# Main indentation preset\n');
72
+ assert.equal((await readAsset('presets.json')).heredoc.source, '# Main heredoc preset\n');
73
+ assert.equal((await readAsset('presets.json'))['html-js'].source, '# Main HTML and JS preset\n');
74
+ const helper = '/app/lib/playground/html_javascript.rb';
75
+ assert.equal((await readAsset('flexr.json')).files[helper], '# Main JavaScript lexer\n');
76
+ prepare('docs');
77
+ assert.equal(await readFile(path.join(repo, stableDocs), 'utf8'),
78
+ 'Default release docs. [Lexer](https://github.com/ydah/flexr/blob/v2.0.0/lib/flexr.rb)\n');
79
+ prepare('playground', { FLEXR_PLAYGROUND_STABLE: '1' });
59
80
  const { files } = await readAsset('flexr.json');
60
81
  assert.equal(files['/app/lib/flexr.rb'], '# Released lexer\n');
61
82
  assert.equal(files['/app/lib/main-only.rb'], undefined);
@@ -65,6 +86,36 @@ test('packages the released lexer and presets when building the public Playgroun
65
86
  assert.equal((await readAsset('presets.json')).keywords, undefined);
66
87
  assert.equal((await readAsset('presets.json')).trivia, undefined);
67
88
  assert.equal((await readAsset('presets.json')).priority, undefined);
89
+ assert.equal((await readAsset('presets.json')).indentation, undefined);
90
+ assert.equal((await readAsset('presets.json')).heredoc.source, '# Released heredoc preset\n');
91
+ assert.equal((await readAsset('presets.json'))['html-js'], undefined);
92
+ assert.equal(files[helper], undefined);
93
+
94
+ await write(docs, `Selected release docs. [Lexer](${fixedDocLink})\n`);
95
+ await write('lib/flexr.rb', '# Selected release lexer\n');
96
+ await write('lib/flexr/version.rb', 'Flexr::VERSION = "2.99.0"\n');
97
+ await write('site/ruby/presets/html_javascript.rb', '# Released JavaScript lexer\n');
98
+ git('add', docs, 'lib/flexr.rb', 'lib/flexr/version.rb', 'site/ruby/presets/html_javascript.rb');
99
+ git('-c', 'user.name=flexr test', '-c', 'user.email=flexr@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'Ship the JavaScript helper');
100
+ git('tag', 'v2.99.0');
101
+ await write(docs, 'Development docs.\n');
102
+ await write('site/ruby/presets/html_javascript.rb', '# Main JavaScript lexer\n');
103
+
104
+ const selected = { FLEXR_STABLE_RELEASE_TAG: 'v2.99.0' };
105
+ prepare('docs', selected);
106
+ assert.equal(await readFile(path.join(repo, stableDocs), 'utf8'),
107
+ 'Selected release docs. [Lexer](https://github.com/ydah/flexr/blob/v2.99.0/lib/flexr.rb)\n');
108
+ prepare('playground', { ...selected, FLEXR_PLAYGROUND_STABLE: '1' });
109
+ const selectedFiles = (await readAsset('flexr.json')).files;
110
+ assert.equal(selectedFiles['/app/lib/flexr.rb'], '# Selected release lexer\n');
111
+ assert.equal(selectedFiles['/app/lib/flexr/version.rb'], 'Flexr::VERSION = "2.99.0"\n');
112
+ assert.equal(selectedFiles['/app/lib/main-only.rb'], undefined);
113
+ assert.equal((await readAsset('presets.json')).toml.source, '# Released toml\n');
114
+ assert.equal((await readAsset('presets.json'))['html-js'].source, '# Released HTML and JS preset\n');
115
+ assert.equal(selectedFiles[helper], '# Released JavaScript lexer\n');
116
+
117
+ assert.throws(() => prepare('docs', { FLEXR_STABLE_RELEASE_TAG: 'v2.98.0' }), /refs\/tags\/v2\.98\.0/);
118
+ assert.throws(() => prepare('docs', { FLEXR_STABLE_RELEASE_TAG: 'v2.99.0-rc.1' }), /FLEXR_STABLE_RELEASE_TAG/);
68
119
  } finally {
69
120
  await rm(repo, { recursive: true, force: true });
70
121
  }
@@ -8,6 +8,22 @@ const binary = await readFile(new URL('../node_modules/@ruby/4.0-wasm-wasi/dist/
8
8
  const assets = JSON.parse(await readFile(new URL('../public/playground-runtime/flexr.json', import.meta.url), 'utf8'));
9
9
  const runtime = await createRuntime(binary, assets);
10
10
 
11
+ test('reports the loaded flexr version before a Ruby action can change it', async () => {
12
+ const versionSource = assets.files['/app/lib/flexr/version.rb'];
13
+ const expected = versionSource.match(/VERSION = "([^"]+)"/)[1];
14
+ const source = `class Lexer < Flexr::Lexer
15
+ rule(/a/) do
16
+ Flexr.send(:remove_const, :VERSION)
17
+ Flexr.const_set(:VERSION, 'edited')
18
+ emit :A, Flexr::VERSION
19
+ end
20
+ end`;
21
+ const versions = [];
22
+ const result = await runtime.run({ source, input: 'a', mode: 'runtime' }, (_startupMs, version) => versions.push(version));
23
+ assert.deepEqual(result.tokens, [['A', 'edited']]);
24
+ assert.deepEqual(versions, [expected]);
25
+ });
26
+
11
27
  test('executes edited Ruby actions and generates a real scanner with Prism', async () => {
12
28
  const source = 'class Lexer < Flexr::Lexer\n emits :INT\n rule(/[0-9]+/) { emit :INT, text.to_i * 2 }\nend';
13
29
  const request = { source, input: '12', mode: 'runtime' };
@@ -118,6 +134,38 @@ test('priority changes the winner only on equal-length matches', async () => {
118
134
  }
119
135
  });
120
136
 
137
+ test('context presets emit layout, dynamic heredoc, and delegated tokens in both modes', async () => {
138
+ const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
139
+ for (const name of ['indentation', 'heredoc', 'html-js']) {
140
+ assert.ok(presets[name], `${name} preset is packaged`);
141
+ }
142
+ for (const mode of ['runtime', 'generated']) {
143
+ const layout = await runtime.run({ ...presets.indentation, mode });
144
+ assert.equal(layout.error, undefined, layout.error);
145
+ assert.deepEqual(layout.tokens.map(token => token.type), [
146
+ 'IF', 'IDENT', 'COLON', 'NEWLINE', 'INDENT', 'IDENT', 'PAREN', 'PAREN', 'NEWLINE', 'DEDENT', 'IDENT', 'PAREN', 'PAREN',
147
+ ]);
148
+ const indent = layout.tokens[4].location;
149
+ assert.deepEqual([indent.byte_begin, indent.byte_end, indent.line_begin, indent.column_begin], [14, 14, 2, 5]);
150
+ assert.equal(layout.tokens[9].location.byte_begin, 20);
151
+
152
+ const heredoc = await runtime.run({ ...presets.heredoc, mode });
153
+ assert.equal(heredoc.error, undefined, heredoc.error);
154
+ assert.deepEqual(heredoc.tokens, [['HEREDOC', 'hello\n'], ['HEREDOC', 'world\n'], ['WORD', 'next']]);
155
+
156
+ const html = await runtime.run({ ...presets['html-js'], mode });
157
+ assert.equal(html.error, undefined, html.error);
158
+ assert.deepEqual(html.tokens.map(({ type, value }) => [type, value]), [
159
+ ['HTML_TAG', '<p>'], ['HTML_TEXT', 'Before'], ['HTML_TAG', '</p>'],
160
+ ['JS_LET', 'let'], ['JS_IDENT', 'x'], ['JS_OPERATOR', '='], ['JS_NUMBER', '2'], ['JS_PUNCTUATION', ';'],
161
+ ['HTML_TAG', '<p>'], ['HTML_TEXT', 'After'], ['HTML_TAG', '</p>'],
162
+ ]);
163
+ const firstJS = html.tokens[3].location;
164
+ assert.deepEqual([firstJS.byte_begin, firstJS.byte_end, firstJS.line_begin, firstJS.column_begin], [23, 26, 3, 1]);
165
+ assert.match(html.generated, /delegate PlaygroundJavaScriptLexer, capture: :js/);
166
+ }
167
+ });
168
+
121
169
  test('pattern algebra keeps overlapping delimiters and keywords distinct', async () => {
122
170
  const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
123
171
  for (const mode of ['runtime', 'generated']) {