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
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const MAX_TEXT = 20_000;
|
|
2
|
+
const MAX_HASH = 220_000;
|
|
3
|
+
|
|
4
|
+
export function validateState(value) {
|
|
5
|
+
if (!value || typeof value !== 'object' || typeof value.source !== 'string' || typeof value.input !== 'string' ||
|
|
6
|
+
!['runtime', 'generated'].includes(value.mode) || value.source.length > MAX_TEXT || value.input.length > MAX_TEXT) {
|
|
7
|
+
throw new Error(`Invalid playground state. Source and input are limited to ${MAX_TEXT} characters each.`);
|
|
8
|
+
}
|
|
9
|
+
return { source: value.source, input: value.input, mode: value.mode };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function encodeState(value) {
|
|
13
|
+
const bytes = new TextEncoder().encode(JSON.stringify(validateState(value)));
|
|
14
|
+
let binary = '';
|
|
15
|
+
for (let index = 0; index < bytes.length; index += 4096) binary += String.fromCharCode(...bytes.subarray(index, index + 4096));
|
|
16
|
+
const encoded = btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
17
|
+
if (encoded.length > MAX_HASH) throw new Error('Share link is too large. Reduce the source or input.');
|
|
18
|
+
return encoded;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function decodeState(hash) {
|
|
22
|
+
if (hash.length > MAX_HASH) throw new Error('Share link is too large.');
|
|
23
|
+
try {
|
|
24
|
+
const binary = atob(hash.replaceAll('-', '+').replaceAll('_', '/'));
|
|
25
|
+
const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
|
|
26
|
+
return validateState(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
|
27
|
+
} catch {
|
|
28
|
+
throw new Error('Invalid playground share link.');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createRuntime } from './runtime.mjs';
|
|
2
|
+
|
|
3
|
+
export async function run({ state, base }) {
|
|
4
|
+
try {
|
|
5
|
+
const start = performance.now();
|
|
6
|
+
const [response, data] = await Promise.all([fetch(`${base}ruby.wasm`), fetch(`${base}flexr.json`)]);
|
|
7
|
+
if (!response.ok || !data.ok) throw new Error('The Ruby runtime could not be downloaded. Retry when the connection is available.');
|
|
8
|
+
const binary = await response.arrayBuffer();
|
|
9
|
+
const assets = await data.json();
|
|
10
|
+
const runtime = await createRuntime(binary, assets);
|
|
11
|
+
const downloadMs = performance.now() - start;
|
|
12
|
+
for (const name of ['fetch', 'XMLHttpRequest', 'WebSocket', 'WebTransport', 'EventSource', 'Worker', 'importScripts']) {
|
|
13
|
+
for (let target = globalThis; target; target = Object.getPrototypeOf(target)) {
|
|
14
|
+
const property = Object.getOwnPropertyDescriptor(target, name);
|
|
15
|
+
if (target === globalThis || property?.configurable) {
|
|
16
|
+
Object.defineProperty(target, name, { value: undefined, configurable: false, writable: false });
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const result = await runtime.run(state, startupMs => postMessage({ phase: 'ready', startupMs }));
|
|
21
|
+
const payload = JSON.stringify({ ...result, wasm_bytes: binary.byteLength, download_ms: downloadMs });
|
|
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
|
+
postMessage({ phase: 'result', result: JSON.parse(payload) });
|
|
24
|
+
} catch (error) {
|
|
25
|
+
postMessage({ phase: 'error', error: error instanceof Error ? error.message : String(error) });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
self.onmessage = ({ data }) => run(data);
|
data/site/src/styles/custom.css
CHANGED
|
@@ -395,6 +395,14 @@ textarea {
|
|
|
395
395
|
.result-table td { color: var(--flexr-ink); }
|
|
396
396
|
.winner-text { color: var(--flexr-green-dark) !important; }
|
|
397
397
|
.workbench-status { min-height: 1.4rem; margin: 0; color: var(--flexr-muted); font-size: 0.78rem; }
|
|
398
|
+
.workbench pre { margin: 0; min-height: 4rem; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 36rem; overflow: auto; font-size: 0.78rem; }
|
|
399
|
+
.workbench summary { padding: 1rem; cursor: pointer; }
|
|
400
|
+
.workbench button:disabled { opacity: 0.55; cursor: default; }
|
|
401
|
+
.workbench input[type="range"] { flex: 1; min-width: 5rem; }
|
|
402
|
+
.workbench .share-link { box-sizing: border-box; width: 100%; padding: 0.75rem; }
|
|
403
|
+
.workbench .workbench-status { padding: 0.5rem 1rem; }
|
|
404
|
+
.graph-output { overflow: auto; max-height: 36rem; }
|
|
405
|
+
.graph-output svg { min-width: 20rem; max-width: none; }
|
|
398
406
|
.back-link { display: inline-flex; margin-bottom: 1.5rem; color: var(--flexr-green); font-family: var(--sl-font-mono); font-size: 0.72rem; }
|
|
399
407
|
|
|
400
408
|
.sl-markdown-content a,
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { test, expect } from '@playwright/test';
|
|
2
|
+
|
|
3
|
+
test('runs actual edited Ruby, steps the trace, draws the DFA, and restores a share link without running', async ({ page }, testInfo) => {
|
|
4
|
+
const wasm = [];
|
|
5
|
+
const errors = [];
|
|
6
|
+
page.context().on('request', request => { if (request.url().endsWith('ruby.wasm')) wasm.push(request.url()); });
|
|
7
|
+
page.on('pageerror', error => errors.push(error.message));
|
|
8
|
+
await page.goto('/flexr/playground/');
|
|
9
|
+
await expect(page.locator('#spec')).toContainText('');
|
|
10
|
+
await expect(page.locator('#spec')).toHaveValue(/class Lexer/);
|
|
11
|
+
expect(wasm).toHaveLength(0);
|
|
12
|
+
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
|
+
await page.locator('#spec').fill(source);
|
|
14
|
+
await page.locator('#input').fill('12 2');
|
|
15
|
+
await page.getByRole('button', { name: 'Run', exact: true }).click();
|
|
16
|
+
await expect(page.locator('#status')).toContainText('2 tokens, 3 steps', { timeout: 30_000 });
|
|
17
|
+
expect(JSON.parse(await page.locator('#tokens').textContent())).toEqual([['INT', 36], ['INT', 6]]);
|
|
18
|
+
await expect(page.locator('#metrics')).toContainText('MiB Ruby download');
|
|
19
|
+
console.log(`Playground measurement: ${await page.locator('#metrics').textContent()}; ${await page.evaluate(() => navigator.userAgent)}`);
|
|
20
|
+
await page.getByRole('button', { name: 'Next step' }).click();
|
|
21
|
+
await expect(page.locator('#decisions')).toContainText('"action": "skip"');
|
|
22
|
+
await page.getByRole('button', { name: 'Draw DFA' }).click();
|
|
23
|
+
await expect(page.locator('#graph svg')).toBeVisible({ timeout: 10_000 });
|
|
24
|
+
await page.evaluate(() => window.scrollTo(0, 0));
|
|
25
|
+
await page.screenshot({ path: testInfo.outputPath('playground-desktop.png') });
|
|
26
|
+
await expect(page.locator('#generated')).toContainText('Generated by flexr');
|
|
27
|
+
await page.locator('#mode').selectOption('generated');
|
|
28
|
+
await page.getByRole('button', { name: 'Run', exact: true }).click();
|
|
29
|
+
await expect(page.locator('#status')).toContainText('2 tokens, 3 steps', { timeout: 15_000 });
|
|
30
|
+
expect(JSON.parse(await page.locator('#tokens').textContent())).toEqual([['INT', 36], ['INT', 6]]);
|
|
31
|
+
await page.getByRole('button', { name: 'Copy share link' }).click();
|
|
32
|
+
await expect(page.locator('#share-link')).toBeVisible();
|
|
33
|
+
const link = await page.locator('#share-link').inputValue();
|
|
34
|
+
const count = wasm.length;
|
|
35
|
+
const shared = await page.context().newPage();
|
|
36
|
+
await shared.goto(link);
|
|
37
|
+
await expect(shared.locator('#spec')).toHaveValue(source);
|
|
38
|
+
await expect(shared.locator('#status')).toContainText('Review it');
|
|
39
|
+
await expect(shared.locator('#mode')).toHaveValue('generated');
|
|
40
|
+
await shared.setViewportSize({ width: 390, height: 844 });
|
|
41
|
+
await shared.screenshot({ path: testInfo.outputPath('playground-mobile.png') });
|
|
42
|
+
expect(await shared.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391);
|
|
43
|
+
expect(wasm).toHaveLength(count);
|
|
44
|
+
expect(errors).toEqual([]);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('shows source diagnostics and terminates runaway Ruby while the UI stays responsive', async ({ page }) => {
|
|
48
|
+
await page.goto('/flexr/playground/');
|
|
49
|
+
await page.locator('#spec').fill('class Lexer < Flexr::Lexer\n rule(/a(?=b)/, emit: :A)\nend');
|
|
50
|
+
await page.locator('#input').fill('ab');
|
|
51
|
+
await page.getByRole('button', { name: 'Run', exact: true }).click();
|
|
52
|
+
await expect(page.locator('#diagnostics')).toContainText('FLEXR-E014', { timeout: 30_000 });
|
|
53
|
+
await expect(page.locator('#diagnostics')).toContainText('playground.flexr.rb:2:');
|
|
54
|
+
await page.locator('#spec').fill('loop {}\nclass Lexer < Flexr::Lexer\n rule(/a/, emit: :A)\nend');
|
|
55
|
+
await page.getByRole('button', { name: 'Run', exact: true }).click();
|
|
56
|
+
await expect(page.locator('#status')).toContainText('Execution exceeded 5 seconds', { timeout: 15_000 });
|
|
57
|
+
await expect(page.getByRole('button', { name: 'Run', exact: true })).toBeEnabled();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('treats tokens and console text as text and disables worker network access', async ({ page }) => {
|
|
61
|
+
await page.goto('/flexr/playground/');
|
|
62
|
+
await page.locator('#spec').fill(`class Lexer < Flexr::Lexer
|
|
63
|
+
rule(/a/) do
|
|
64
|
+
require "js"
|
|
65
|
+
emit :TEXT, "<img src=x onerror=alert(1)>"
|
|
66
|
+
puts "<script>alert(1)</script>"
|
|
67
|
+
raise "network enabled" unless JS.global[:fetch].typeof == "undefined"
|
|
68
|
+
end
|
|
69
|
+
end`);
|
|
70
|
+
await page.locator('#input').fill('a');
|
|
71
|
+
await page.getByRole('button', { name: 'Run', exact: true }).click();
|
|
72
|
+
await expect(page.locator('#status')).toContainText('1 token, 1 step', { timeout: 30_000 });
|
|
73
|
+
await expect(page.locator('#tokens')).toContainText('<img src=x');
|
|
74
|
+
await expect(page.locator('#tokens img')).toHaveCount(0);
|
|
75
|
+
await expect(page.locator('#console script')).toHaveCount(0);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('loads the actual TOML, GraphQL, and SQL example presets', async ({ page }) => {
|
|
79
|
+
await page.goto('/flexr/playground/');
|
|
80
|
+
for (const [name, namespace] of [['toml', 'TomlExample'], ['graphql', 'GraphqlExample'], ['sql', 'SqlExample']]) {
|
|
81
|
+
await page.locator('#preset').selectOption(name);
|
|
82
|
+
await expect(page.locator('#spec')).toHaveValue(new RegExp(`module ${namespace}`));
|
|
83
|
+
await page.getByRole('button', { name: 'Run', exact: true }).click();
|
|
84
|
+
await expect(page.locator('#status')).toContainText('steps. Ruby', { timeout: 30_000 });
|
|
85
|
+
expect(JSON.parse(await page.locator('#tokens').textContent()).length).toBeGreaterThan(0);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('executes literal Unicode action values in runtime and generated modes', async ({ page }) => {
|
|
90
|
+
await page.goto('/flexr/playground/');
|
|
91
|
+
await page.locator('#spec').fill('class Lexer < Flexr::Lexer\n LABEL = "前"\n rule(/a/) { emit :TEXT, LABEL + "あ" }\n TRAILER = "後"\nend');
|
|
92
|
+
await page.locator('#input').fill('a');
|
|
93
|
+
for (const mode of ['runtime', 'generated']) {
|
|
94
|
+
await page.locator('#mode').selectOption(mode);
|
|
95
|
+
await page.getByRole('button', { name: 'Run', exact: true }).click();
|
|
96
|
+
await expect(page.locator('#status')).toContainText('1 token, 1 step', { timeout: 30_000 });
|
|
97
|
+
expect(JSON.parse(await page.locator('#tokens').textContent())).toEqual([['TEXT', '前あ']]);
|
|
98
|
+
}
|
|
99
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { createRuntime } from '../src/playground/runtime.mjs';
|
|
5
|
+
import { encodeState, decodeState } from '../src/playground/share.mjs';
|
|
6
|
+
|
|
7
|
+
const binary = await readFile(new URL('../node_modules/@ruby/4.0-wasm-wasi/dist/ruby+stdlib.wasm', import.meta.url));
|
|
8
|
+
const assets = JSON.parse(await readFile(new URL('../public/playground-runtime/flexr.json', import.meta.url), 'utf8'));
|
|
9
|
+
const runtime = await createRuntime(binary, assets);
|
|
10
|
+
|
|
11
|
+
test('executes edited Ruby actions and generates a real scanner with Prism', async () => {
|
|
12
|
+
const source = 'class Lexer < Flexr::Lexer\n emits :INT\n rule(/[0-9]+/) { emit :INT, text.to_i * 2 }\nend';
|
|
13
|
+
const request = { source, input: '12', mode: 'runtime' };
|
|
14
|
+
const result = await runtime.run(request);
|
|
15
|
+
assert.deepEqual(result.tokens, [['INT', 24]]);
|
|
16
|
+
assert.match(result.dot, /digraph flexr/);
|
|
17
|
+
assert.equal(result.steps[0].text, '12');
|
|
18
|
+
assert.match(result.generated, /Generated by flexr/);
|
|
19
|
+
assert.match(result.generated, /def scan_one/);
|
|
20
|
+
const generated = await runtime.run({ ...request, mode: 'generated' });
|
|
21
|
+
assert.deepEqual(generated.tokens, result.tokens);
|
|
22
|
+
assert.deepEqual(generated.steps, result.steps);
|
|
23
|
+
assert.equal(result.ruby_version, '4.0.0');
|
|
24
|
+
assert.equal(result.prism_version, '1.7.0');
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('renders real diagnostic source locations and rejects malformed Ruby', async () => {
|
|
28
|
+
const result = await runtime.run({ source: 'class Lexer < Flexr::Lexer\n rule(/a(?=b)/, emit: :A)\nend', input: 'ab', mode: 'runtime' });
|
|
29
|
+
assert.match(result.error, /FLEXR-E014/);
|
|
30
|
+
assert.match(result.error, /playground.flexr.rb:2:/);
|
|
31
|
+
assert.match(result.error, /\^/);
|
|
32
|
+
const syntax = await runtime.run({ source: 'class Lexer <', input: '', mode: 'runtime' });
|
|
33
|
+
assert.match(syntax.error, /FLEXR-E010/);
|
|
34
|
+
const unmatched = await runtime.run({ source: 'class Lexer < Flexr::Lexer\n rule(/a/, emit: :A)\nend', input: 'b', mode: 'runtime' });
|
|
35
|
+
assert.match(unmatched.error, /unexpected byte/);
|
|
36
|
+
assert.match(unmatched.error, /input.txt:1:/);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('each run starts a fresh Ruby VM', async () => {
|
|
40
|
+
const source = 'class ::AbsoluteLexer < Flexr::Lexer\n rule(/a/, emit: :A)\nend';
|
|
41
|
+
assert.deepEqual((await runtime.run({ source, input: 'a', mode: 'runtime' })).tokens, [['A', 'a']]);
|
|
42
|
+
assert.deepEqual((await runtime.run({ source, input: 'a', mode: 'runtime' })).tokens, [['A', 'a']]);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('console truncation preserves valid UTF-8 and emitted tokens', async () => {
|
|
46
|
+
const source = 'class Lexer < Flexr::Lexer\n rule(/a/) do\n puts 0x3042.chr(Encoding::UTF_8) * 2000\n emit :A\n end\nend';
|
|
47
|
+
for (const mode of ['runtime', 'generated']) {
|
|
48
|
+
const result = await runtime.run({ source, input: 'a', mode });
|
|
49
|
+
assert.equal(result.error, undefined, result.error);
|
|
50
|
+
assert.deepEqual(result.tokens, [['A', 'a']]);
|
|
51
|
+
assert.ok(result.console.length < 2000);
|
|
52
|
+
assert.match(result.console, /^あ+\uFFFD$/);
|
|
53
|
+
assert.doesNotThrow(() => new TextDecoder('utf-8', { fatal: true }).decode(new TextEncoder().encode(result.console)));
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('literal Unicode actions and surrounding constants survive generation', async () => {
|
|
58
|
+
const source = 'class Lexer < Flexr::Lexer\n LABEL = "前"\n rule(/a/) { emit :TEXT, LABEL + "あ" }\n TRAILER = "後"\nend';
|
|
59
|
+
for (const mode of ['runtime', 'generated']) {
|
|
60
|
+
const result = await runtime.run({ source, input: 'a', mode });
|
|
61
|
+
assert.equal(result.error, undefined, result.error);
|
|
62
|
+
assert.deepEqual(result.tokens, [['TEXT', '前あ']]);
|
|
63
|
+
assert.match(result.generated, /TRAILER = "後"/);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('share links retain Unicode source and input without running code', () => {
|
|
68
|
+
const state = { source: 'class Lexer; # café\nend', input: '日本語', mode: 'runtime' };
|
|
69
|
+
assert.deepEqual(decodeState(encodeState(state)), state);
|
|
70
|
+
assert.throws(() => decodeState('x'.repeat(300_000)), /too large/);
|
|
71
|
+
assert.throws(() => decodeState(btoa(JSON.stringify({ source: 5, input: '' }))), /Invalid/);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('language presets use the repository examples and run in both modes', async () => {
|
|
75
|
+
const presets = JSON.parse(await readFile(new URL('../public/playground-runtime/presets.json', import.meta.url), 'utf8'));
|
|
76
|
+
for (const name of ['toml', 'graphql', 'sql']) {
|
|
77
|
+
const preset = presets[name];
|
|
78
|
+
assert.equal(preset.source, await readFile(new URL(`../../examples/${name}/lexer.flexr.rb`, import.meta.url), 'utf8'));
|
|
79
|
+
const result = await runtime.run({ ...preset, mode: 'runtime' });
|
|
80
|
+
assert.equal(result.error, undefined, result.error);
|
|
81
|
+
assert.ok(result.tokens.length > 0);
|
|
82
|
+
const generated = await runtime.run({ ...preset, mode: 'generated' });
|
|
83
|
+
assert.deepEqual(generated.tokens, result.tokens);
|
|
84
|
+
}
|
|
85
|
+
});
|
data/tools/docs_verify.rb
CHANGED
|
@@ -102,8 +102,8 @@ module FlexrDocumentation
|
|
|
102
102
|
end
|
|
103
103
|
end
|
|
104
104
|
|
|
105
|
-
def command(*
|
|
106
|
-
Open3.capture3(RbConfig.ruby, "-Ilib", "exe/flexr",
|
|
105
|
+
def command(*)
|
|
106
|
+
Open3.capture3(RbConfig.ruby, "-Ilib", "exe/flexr", *, chdir: ROOT)
|
|
107
107
|
end
|
|
108
108
|
|
|
109
109
|
def ruby_json(script, path, input)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "fileutils"
|
|
5
|
+
require "json"
|
|
6
|
+
require "open3"
|
|
7
|
+
require "shellwords"
|
|
8
|
+
require "tempfile"
|
|
9
|
+
|
|
10
|
+
module FlexrVerification
|
|
11
|
+
module FailureCase
|
|
12
|
+
VERSION = 1
|
|
13
|
+
DIRECTORY = "tmp/verification-failures"
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
def abort_with_record(message, root:, task:, input:, expected:, actual:, **details)
|
|
18
|
+
warn message
|
|
19
|
+
directory = File.expand_path(ENV.fetch("FLEXR_FAILURE_DIR", DIRECTORY), root)
|
|
20
|
+
record = {
|
|
21
|
+
version: VERSION,
|
|
22
|
+
task: task,
|
|
23
|
+
revision: revision(root),
|
|
24
|
+
ruby: RUBY_DESCRIPTION,
|
|
25
|
+
unicode: Flexr::Unicode::VERSION,
|
|
26
|
+
gems: Gem.loaded_specs.slice("bundler", "flexr", "json", "prism", "rake").transform_values { |gem| gem.version.to_s },
|
|
27
|
+
**details,
|
|
28
|
+
input: encode_bytes(input),
|
|
29
|
+
expected: snapshot(expected),
|
|
30
|
+
actual: snapshot(actual)
|
|
31
|
+
}
|
|
32
|
+
FileUtils.mkdir_p(directory)
|
|
33
|
+
path = Tempfile.create(["#{task.tr(':', '-')}-", ".tmp"], directory) do |file|
|
|
34
|
+
file.write("#{JSON.pretty_generate(record)}\n")
|
|
35
|
+
file.close
|
|
36
|
+
target = "#{file.path.delete_suffix('.tmp')}.json"
|
|
37
|
+
File.rename(file.path, target)
|
|
38
|
+
target
|
|
39
|
+
end
|
|
40
|
+
warn "Saved verification failure to #{path}"
|
|
41
|
+
warn "Replay with FLEXR_FAILURE_CASE=#{Shellwords.escape(path)} bundle exec rake verification:replay"
|
|
42
|
+
abort
|
|
43
|
+
rescue SystemCallError, IOError, JSON::GeneratorError => e
|
|
44
|
+
abort "Could not save verification failure: #{e.message}"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def read(path)
|
|
48
|
+
record = JSON.parse(File.binread(path))
|
|
49
|
+
raise ArgumentError, "unsupported verification failure format" unless record.is_a?(Hash) && record["version"] == VERSION
|
|
50
|
+
|
|
51
|
+
number = record.fetch("case")
|
|
52
|
+
raise ArgumentError, "invalid case number" unless number.is_a?(Integer) && number.positive?
|
|
53
|
+
|
|
54
|
+
record
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def section(record, name)
|
|
58
|
+
value = record.fetch(name)
|
|
59
|
+
raise ArgumentError, "invalid #{name} in verification failure" unless value.is_a?(Hash)
|
|
60
|
+
|
|
61
|
+
value
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def encode_bytes(string)
|
|
65
|
+
{ encoding: string.encoding.name, hex: string.unpack1("H*") }
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def decode_bytes(record)
|
|
69
|
+
hex = record.fetch("hex")
|
|
70
|
+
encoding = record.fetch("encoding")
|
|
71
|
+
valid_hex = hex.is_a?(String) && hex.match?(/\A[0-9a-f]*\z/) && hex.length.even?
|
|
72
|
+
raise ArgumentError, "invalid encoded bytes" unless valid_hex && encoding.is_a?(String)
|
|
73
|
+
|
|
74
|
+
[hex].pack("H*").force_encoding(Encoding.find(encoding))
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def snapshot(value)
|
|
78
|
+
case value
|
|
79
|
+
when Hash then value.transform_values { |item| snapshot(item) }
|
|
80
|
+
when Array then value.map { |item| snapshot(item) }
|
|
81
|
+
when String then value.ascii_only? || (value.encoding == Encoding::UTF_8 && value.valid_encoding?) ? value : encode_bytes(value)
|
|
82
|
+
when Symbol then { symbol: snapshot(value.to_s) }
|
|
83
|
+
when Float then value.finite? ? value : { float: value.to_s }
|
|
84
|
+
when Numeric, true, false, nil then value
|
|
85
|
+
else { class: value.class.name, inspect: snapshot(value.inspect) }
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def revision(root)
|
|
90
|
+
commit = git(root, "rev-parse", "HEAD")&.strip
|
|
91
|
+
return unless commit
|
|
92
|
+
|
|
93
|
+
diff = git(root, "diff", "--binary", "--no-ext-diff", "--no-textconv", "HEAD", "--")
|
|
94
|
+
untracked = git(root, "ls-files", "--others", "--exclude-standard", "-z")
|
|
95
|
+
return { commit: commit } unless diff && untracked
|
|
96
|
+
|
|
97
|
+
digest = Digest::SHA256.new.update(diff)
|
|
98
|
+
untracked.split("\0").each do |path|
|
|
99
|
+
absolute = File.join(root, path)
|
|
100
|
+
content = if File.symlink?(absolute)
|
|
101
|
+
Digest::SHA256.hexdigest(File.readlink(absolute))
|
|
102
|
+
elsif File.file?(absolute)
|
|
103
|
+
Digest::SHA256.file(absolute).hexdigest
|
|
104
|
+
end
|
|
105
|
+
digest.update("\0#{path}\0#{content}")
|
|
106
|
+
end
|
|
107
|
+
{ commit: commit, dirty: !diff.empty? || !untracked.empty?, worktree_sha256: digest.hexdigest }
|
|
108
|
+
rescue SystemCallError
|
|
109
|
+
{ commit: commit } if commit
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def git(root, *)
|
|
113
|
+
stdout, status = Open3.capture2("git", *, chdir: root, err: File::NULL, binmode: true)
|
|
114
|
+
stdout if status.success?
|
|
115
|
+
rescue Errno::ENOENT
|
|
116
|
+
nil
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
end
|
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:
|
|
4
|
+
version: 2.0.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Yudai Takada
|
|
@@ -131,7 +131,6 @@ files:
|
|
|
131
131
|
- lib/flexr/codegen/table.rb
|
|
132
132
|
- lib/flexr/codegen/table_packer.rb
|
|
133
133
|
- lib/flexr/configuration.rb
|
|
134
|
-
- lib/flexr/deprecations.rb
|
|
135
134
|
- lib/flexr/diagnostics.rb
|
|
136
135
|
- lib/flexr/dsl.rb
|
|
137
136
|
- lib/flexr/errors.rb
|
|
@@ -160,6 +159,7 @@ files:
|
|
|
160
159
|
- lib/flexr/runtime/errors.rb
|
|
161
160
|
- lib/flexr/runtime/interpreter.rb
|
|
162
161
|
- lib/flexr/runtime/location.rb
|
|
162
|
+
- lib/flexr/runtime/record.rb
|
|
163
163
|
- lib/flexr/runtime/token.rb
|
|
164
164
|
- lib/flexr/source.rb
|
|
165
165
|
- lib/flexr/source/passthrough.rb
|
|
@@ -183,9 +183,11 @@ files:
|
|
|
183
183
|
- site/README.md
|
|
184
184
|
- site/astro.config.mjs
|
|
185
185
|
- site/package.json
|
|
186
|
+
- site/playwright.config.mjs
|
|
186
187
|
- site/pnpm-lock.yaml
|
|
187
188
|
- site/pnpm-workspace.yaml
|
|
188
|
-
- site/
|
|
189
|
+
- site/ruby/playground.rb
|
|
190
|
+
- site/scripts/prepare-playground.mjs
|
|
189
191
|
- site/scripts/verify-site.mjs
|
|
190
192
|
- site/src/content.config.ts
|
|
191
193
|
- site/src/content/docs/benchmarks.md
|
|
@@ -210,8 +212,16 @@ files:
|
|
|
210
212
|
- site/src/layouts/SiteLayout.astro
|
|
211
213
|
- site/src/pages/index.astro
|
|
212
214
|
- site/src/pages/playground.astro
|
|
215
|
+
- site/src/playground/client.js
|
|
216
|
+
- site/src/playground/graph-worker.mjs
|
|
217
|
+
- site/src/playground/presets.mjs
|
|
218
|
+
- site/src/playground/runtime.mjs
|
|
219
|
+
- site/src/playground/share.mjs
|
|
220
|
+
- site/src/playground/worker.mjs
|
|
213
221
|
- site/src/styles/custom.css
|
|
214
222
|
- site/src/styles/landing.css
|
|
223
|
+
- site/tests/browser/playground.spec.mjs
|
|
224
|
+
- site/tests/playground-runtime.test.mjs
|
|
215
225
|
- site/tsconfig.json
|
|
216
226
|
- test/ruby_lsp_addon_spec.rb
|
|
217
227
|
- tools/coverage.rb
|
|
@@ -219,15 +229,15 @@ files:
|
|
|
219
229
|
- tools/gen_unicode_tables.rb
|
|
220
230
|
- tools/golden.rb
|
|
221
231
|
- tools/regexp_tokenizer_reference.rb
|
|
222
|
-
- tools/
|
|
232
|
+
- tools/verification_failure.rb
|
|
223
233
|
homepage: https://github.com/ydah/flexr
|
|
224
234
|
licenses:
|
|
225
235
|
- MIT
|
|
226
236
|
metadata:
|
|
227
237
|
rubygems_mfa_required: 'true'
|
|
228
|
-
generator_ruby_version: ">= 3.
|
|
238
|
+
generator_ruby_version: ">= 3.4 (Prism)"
|
|
229
239
|
homepage_uri: https://github.com/ydah/flexr
|
|
230
|
-
source_code_uri: https://github.com/ydah/flexr/tree/
|
|
240
|
+
source_code_uri: https://github.com/ydah/flexr/tree/main
|
|
231
241
|
bug_tracker_uri: https://github.com/ydah/flexr/issues
|
|
232
242
|
rdoc_options: []
|
|
233
243
|
require_paths:
|
|
@@ -236,7 +246,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
|
|
|
236
246
|
requirements:
|
|
237
247
|
- - ">="
|
|
238
248
|
- !ruby/object:Gem::Version
|
|
239
|
-
version: 3.
|
|
249
|
+
version: 3.4.0
|
|
240
250
|
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
241
251
|
requirements:
|
|
242
252
|
- - ">="
|
data/lib/flexr/deprecations.rb
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module Flexr
|
|
4
|
-
module Deprecations
|
|
5
|
-
module_function
|
|
6
|
-
|
|
7
|
-
def warn(message)
|
|
8
|
-
Kernel.warn("flexr deprecated: #{message}", category: :deprecated, uplevel: 2)
|
|
9
|
-
end
|
|
10
|
-
|
|
11
|
-
def record_mutations(record)
|
|
12
|
-
record.prepend(Module.new do
|
|
13
|
-
record.members.each do |member|
|
|
14
|
-
define_method("#{member}=") do |value|
|
|
15
|
-
Deprecations.warn("#{record.name} becomes immutable in 2.0; replace the record instead of mutating it")
|
|
16
|
-
super(value)
|
|
17
|
-
end
|
|
18
|
-
end
|
|
19
|
-
define_method(:[]=) do |key, value|
|
|
20
|
-
Deprecations.warn("#{record.name} becomes immutable in 2.0; replace the record instead of mutating it")
|
|
21
|
-
super(key, value)
|
|
22
|
-
end
|
|
23
|
-
end)
|
|
24
|
-
end
|
|
25
|
-
end
|
|
26
|
-
end
|