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,57 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "stringio"
|
|
4
|
+
|
|
5
|
+
module FlexrPlayground
|
|
6
|
+
module_function
|
|
7
|
+
|
|
8
|
+
def run(request)
|
|
9
|
+
path = "/playground.flexr.rb"
|
|
10
|
+
source = request.fetch("source")
|
|
11
|
+
File.write(path, source)
|
|
12
|
+
stdout = $stdout
|
|
13
|
+
stderr = $stderr
|
|
14
|
+
$stdout = StringIO.new
|
|
15
|
+
$stderr = StringIO.new
|
|
16
|
+
options = Flexr::Options.default
|
|
17
|
+
options.set(:max_dfa_states, 1024)
|
|
18
|
+
options.set(:warn_level, :all)
|
|
19
|
+
options.color = :never
|
|
20
|
+
diagnostics = StringIO.new
|
|
21
|
+
Flexr::CLI.check(path, options, diagnostics)
|
|
22
|
+
generated = Flexr::Generator.new(path, options: options.generator_options).generate
|
|
23
|
+
parsed = Flexr::CLI.read_spec(path)
|
|
24
|
+
scope = Module.new
|
|
25
|
+
scope.module_eval(request["mode"] == "generated" ? generated : source, path, 1)
|
|
26
|
+
namespace = parsed.class_name.start_with?("::") ? Object : scope
|
|
27
|
+
klass = parsed.class_name.split("::").reject(&:empty?).inject(namespace) { |parent, name| parent.const_get(name, false) }
|
|
28
|
+
unless request["mode"] == "generated"
|
|
29
|
+
klass.__flexr_config.options[:max_dfa_states] = 1024
|
|
30
|
+
klass.__flexr_config.options[:warn_level] = :all
|
|
31
|
+
end
|
|
32
|
+
input_path = "/input.txt"
|
|
33
|
+
File.write(input_path, request.fetch("input"))
|
|
34
|
+
lexer = klass.new(request.fetch("input"), filename: input_path, max_steps: 1_000_000, max_token_size: 65_536,
|
|
35
|
+
max_lookahead_size: 65_536, max_buffer_size: 1_048_576)
|
|
36
|
+
trace = Flexr::Trace.new(lexer)
|
|
37
|
+
tokens = trace.run
|
|
38
|
+
dot = StringIO.new
|
|
39
|
+
Flexr::CLI.print_dot(path, options, dot)
|
|
40
|
+
JSON.generate(tokens: tokens, steps: trace.steps, diagnostics: diagnostics.string,
|
|
41
|
+
generated: generated, dot: dot.string, ruby_version: RUBY_VERSION,
|
|
42
|
+
prism_version: Prism::VERSION,
|
|
43
|
+
console: ($stdout.string + $stderr.string).byteslice(0, 4096).force_encoding(Encoding::UTF_8).scrub)
|
|
44
|
+
rescue StandardError, SyntaxError, LoadError, SystemExit => e
|
|
45
|
+
if e.is_a?(Flexr::LexError) && !e.diagnostic && e.byte_pos
|
|
46
|
+
diagnostic = Flexr::Diagnostics.error("FLEXR-E000", e.message,
|
|
47
|
+
location: [e.byte_pos, e.byte_pos + e.text.to_s.bytesize])
|
|
48
|
+
e = Flexr::LexError.new(e.message, diagnostic: diagnostic,
|
|
49
|
+
filename: e.filename, byte_pos: e.byte_pos, line: e.line, text: e.text)
|
|
50
|
+
end
|
|
51
|
+
JSON.generate(error: Flexr::CLI.render_error(e, options: options, path: path),
|
|
52
|
+
ruby_version: RUBY_VERSION, prism_version: defined?(Prism::VERSION) && Prism::VERSION)
|
|
53
|
+
ensure
|
|
54
|
+
$stdout = stdout
|
|
55
|
+
$stderr = stderr
|
|
56
|
+
end
|
|
57
|
+
end
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { cp, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
const site = fileURLToPath(new URL('..', import.meta.url));
|
|
6
|
+
const root = path.dirname(site);
|
|
7
|
+
const output = path.join(site, 'public/playground-runtime');
|
|
8
|
+
const files = {};
|
|
9
|
+
async function collect(directory) {
|
|
10
|
+
for (const entry of await readdir(path.join(root, directory), { withFileTypes: true })) {
|
|
11
|
+
const relative = path.posix.join(directory, entry.name);
|
|
12
|
+
if (entry.isDirectory()) await collect(relative);
|
|
13
|
+
else if (entry.name.endsWith('.rb')) files[`/app/${relative}`] = await readFile(path.join(root, relative), 'utf8');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
await collect('lib');
|
|
17
|
+
files['/app/playground.rb'] = await readFile(path.join(site, 'ruby/playground.rb'), 'utf8');
|
|
18
|
+
await mkdir(output, { recursive: true });
|
|
19
|
+
const payload = JSON.stringify({ files });
|
|
20
|
+
await writeFile(path.join(output, 'flexr.json'), payload);
|
|
21
|
+
const inputs = {
|
|
22
|
+
toml: 'title = "flexr"',
|
|
23
|
+
graphql: 'query { user(id: 12) { name } }',
|
|
24
|
+
sql: 'select name from users where id >= 12;',
|
|
25
|
+
};
|
|
26
|
+
const presets = {};
|
|
27
|
+
for (const [name, input] of Object.entries(inputs)) {
|
|
28
|
+
presets[name] = { source: await readFile(path.join(root, `examples/${name}/lexer.flexr.rb`), 'utf8'), input };
|
|
29
|
+
}
|
|
30
|
+
await writeFile(path.join(output, 'presets.json'), JSON.stringify(presets));
|
|
31
|
+
const wasm = path.join(site, 'node_modules/@ruby/4.0-wasm-wasi/dist');
|
|
32
|
+
await cp(path.join(wasm, 'ruby+stdlib.wasm'), path.join(output, 'ruby.wasm'));
|
|
33
|
+
await cp(path.join(wasm, 'LICENSE'), path.join(output, 'LICENSE'));
|
|
34
|
+
await cp(path.join(wasm, 'NOTICE'), path.join(output, 'NOTICE'));
|
|
35
|
+
console.log(`Playground: packaged ${Object.keys(files).length} Ruby files (${Buffer.byteLength(payload)} bytes).`);
|
|
@@ -10,7 +10,9 @@ const required = [
|
|
|
10
10
|
'src/content/docs/learn/generation.md',
|
|
11
11
|
'src/content/docs/reference/dsl.md',
|
|
12
12
|
'src/content/docs/reference/diagnostics.md',
|
|
13
|
-
'
|
|
13
|
+
'src/playground/client.js',
|
|
14
|
+
'src/playground/worker.mjs',
|
|
15
|
+
'ruby/playground.rb'
|
|
14
16
|
];
|
|
15
17
|
|
|
16
18
|
const missing = required.filter((file) => !existsSync(resolve(root, file)));
|
|
@@ -30,8 +32,8 @@ const requiredPhrases = [
|
|
|
30
32
|
'longest match',
|
|
31
33
|
'Runtime mode',
|
|
32
34
|
'Generated mode',
|
|
33
|
-
'
|
|
34
|
-
'
|
|
35
|
+
'separate worker',
|
|
36
|
+
'source and input stay in your browser'
|
|
35
37
|
];
|
|
36
38
|
const missingPhrases = requiredPhrases.filter((phrase) => !source.toLowerCase().includes(phrase.toLowerCase()));
|
|
37
39
|
if (missingPhrases.length) {
|
|
@@ -3,7 +3,7 @@ title: Matching semantics
|
|
|
3
3
|
description: Understand how flexr chooses a rule when several rules accept the same position.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
With the default longest-match backends, flexr selects the rule that consumes the most bytes at each input position. If multiple rules consume the same number, the rule defined first wins.
|
|
7
7
|
|
|
8
8
|
```ruby
|
|
9
9
|
rule(/==/) { emit :EQ }
|
|
@@ -12,4 +12,6 @@ rule(/=/) { emit :ASSIGN }
|
|
|
12
12
|
|
|
13
13
|
Input `==` produces `EQ`, regardless of the order above. Equal-length alternatives are resolved by definition order, so putting keyword rules before a broad identifier rule is the conventional way to reserve keywords.
|
|
14
14
|
|
|
15
|
-
The
|
|
15
|
+
The stable `firstmatch` backend instead selects the first rule with a match at the current position. Ruby regexp alternation order applies within that rule, so `/a|ab/` matches `a` on input `ab`. Select this behavior explicitly with `backend :firstmatch`.
|
|
16
|
+
|
|
17
|
+
The [playground](/flexr/playground/) shows candidates and the winner for each scan step.
|
|
@@ -12,4 +12,12 @@ flexr specifications are Ruby programs. Rule actions, `--eval`, and generated ac
|
|
|
12
12
|
- Use `flexr check` for diagnostics, not as a sandbox.
|
|
13
13
|
- Keep build-time inputs and generator versions pinned in CI.
|
|
14
14
|
|
|
15
|
-
The
|
|
15
|
+
The Playground executes real Ruby in a separate worker using a virtual filesystem.
|
|
16
|
+
The application does not upload source or input; share links store them in a URL
|
|
17
|
+
fragment and do not run automatically. Review shared source before selecting Run.
|
|
18
|
+
|
|
19
|
+
Runs have a five-second timeout and can be stopped immediately. Input size,
|
|
20
|
+
automaton construction, and output are bounded. The page restricts network access
|
|
21
|
+
and sanitizes output, but a worker is not a complete hostile-code or memory
|
|
22
|
+
sandbox. Ruby actions can modify their VM and access worker JavaScript. Parsing a
|
|
23
|
+
specification does not make its actions safe.
|
|
@@ -10,7 +10,7 @@ bundle exec flexr check lexer.flexr.rb
|
|
|
10
10
|
bundle exec flexr generate lexer.flexr.rb -o lexer.rb
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
The generator
|
|
13
|
+
The generator supports the longest-match `table`, `direct`, and `auto` backends. Select `backend :firstmatch` explicitly to use the first matching rule in definition order. This backend is stable and requires no experimental option.
|
|
14
14
|
|
|
15
15
|
## Runtime dependencies
|
|
16
16
|
|
|
@@ -10,10 +10,10 @@ description: The stable lexer specification methods and their role.
|
|
|
10
10
|
| `emits(*kinds)` | Declare token kinds for diagnostics and parser integration |
|
|
11
11
|
| `state(name)` | Define a named start condition |
|
|
12
12
|
| `all_states` | Apply a rule to every state |
|
|
13
|
-
| `backend(name)` | Choose `table`, `direct`, or `auto
|
|
13
|
+
| `backend(name)` | Choose longest-match `table`, `direct`, or `auto`, or rule-order `firstmatch` |
|
|
14
14
|
| `token_kind(name)` | Choose the token return shape |
|
|
15
15
|
| `encoding(name)` | Select the input encoding contract |
|
|
16
16
|
| `option(name)` | Enable an explicit compiler option |
|
|
17
17
|
| `accel(name)` | Configure acceleration where compatible |
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
The default backends use [longest-match semantics](/flexr/concepts/matching-semantics/); `firstmatch` selects the first matching rule. The repository's [DSL reference](https://github.com/ydah/flexr/blob/main/docs/reference/dsl.md) includes option defaults and examples.
|
|
@@ -5,11 +5,13 @@ description: Separate stable user APIs from experimental and internal implementa
|
|
|
5
5
|
|
|
6
6
|
## Public and stable
|
|
7
7
|
|
|
8
|
-
`Flexr::Lexer`, the lexer DSL, runtime token/location
|
|
8
|
+
`Flexr::Lexer`, the lexer DSL, immutable runtime token/location Data records, the documented CLI, and `Flexr::RakeTask` are the supported entry points for normal use.
|
|
9
|
+
|
|
10
|
+
The `firstmatch` backend is stable and uses rule-order semantics in runtime and generated modes. Select it explicitly with `backend :firstmatch`; no experimental option is required.
|
|
9
11
|
|
|
10
12
|
## Experimental
|
|
11
13
|
|
|
12
|
-
|
|
14
|
+
Options explicitly marked experimental may change behavior or API shape between releases.
|
|
13
15
|
|
|
14
16
|
## Internal
|
|
15
17
|
|
|
@@ -13,4 +13,7 @@ description: Return shapes, semantic values, and source positions.
|
|
|
13
13
|
|
|
14
14
|
Locations use byte offsets for the input position and track line/column as the lexer consumes text. Keep the location with the token when a parser needs useful syntax errors.
|
|
15
15
|
|
|
16
|
+
In v2, structured tokens and locations are immutable `Data` records. Read fields
|
|
17
|
+
with attribute readers or `[]`, and use `with` to create a replacement.
|
|
18
|
+
|
|
16
19
|
For exact defaults and the `Location` data structure, use the repository's [tokens and locations reference](https://github.com/ydah/flexr/blob/main/docs/reference/tokens-and-locations.md).
|
|
@@ -4,9 +4,10 @@ import '../styles/custom.css';
|
|
|
4
4
|
export interface Props {
|
|
5
5
|
title: string;
|
|
6
6
|
description: string;
|
|
7
|
+
playground?: boolean;
|
|
7
8
|
}
|
|
8
9
|
|
|
9
|
-
const { title, description } = Astro.props;
|
|
10
|
+
const { title, description, playground = false } = Astro.props;
|
|
10
11
|
const siteTitle = `${title} · flexr`;
|
|
11
12
|
const base = import.meta.env.BASE_URL.endsWith('/') ? import.meta.env.BASE_URL : `${import.meta.env.BASE_URL}/`;
|
|
12
13
|
---
|
|
@@ -17,6 +18,7 @@ const base = import.meta.env.BASE_URL.endsWith('/') ? import.meta.env.BASE_URL :
|
|
|
17
18
|
<meta name="viewport" content="width=device-width" />
|
|
18
19
|
<meta name="description" content={description} />
|
|
19
20
|
<meta name="theme-color" content="#161518" />
|
|
21
|
+
{playground && <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' blob: 'unsafe-eval' 'wasm-unsafe-eval'; worker-src 'self' blob:; connect-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; object-src 'none'; base-uri 'self'" />}
|
|
20
22
|
<meta property="og:title" content={siteTitle} />
|
|
21
23
|
<meta property="og:description" content={description} />
|
|
22
24
|
<meta property="og:type" content="website" />
|
|
@@ -3,62 +3,64 @@ import SiteLayout from '../layouts/SiteLayout.astro';
|
|
|
3
3
|
|
|
4
4
|
const base = import.meta.env.BASE_URL.endsWith('/') ? import.meta.env.BASE_URL : `${import.meta.env.BASE_URL}/`;
|
|
5
5
|
---
|
|
6
|
-
<SiteLayout
|
|
7
|
-
title="Playground"
|
|
8
|
-
description="Explore flexr's longest-match decision model with an interactive, fixture-backed lexer preview."
|
|
9
|
-
>
|
|
6
|
+
<SiteLayout title="Playground" description="Run real flexr Ruby specifications locally, inspect diagnostics and trace decisions, and generate a scanner." playground>
|
|
10
7
|
<main class="playground-shell">
|
|
11
|
-
<a class="back-link" href={base}
|
|
8
|
+
<a class="back-link" href={base}>Back to flexr</a>
|
|
12
9
|
<header class="playground-header">
|
|
13
|
-
<
|
|
14
|
-
<
|
|
15
|
-
<p>
|
|
16
|
-
Choose a fixture, edit its input, and inspect which rule wins at each position. This
|
|
17
|
-
preview is static and fixture-backed: it does not execute arbitrary Ruby in your browser.
|
|
18
|
-
Use the repository examples and CLI for full runtime and generation behavior.
|
|
19
|
-
</p>
|
|
10
|
+
<h1>Follow every match.</h1>
|
|
11
|
+
<p>Edit Ruby, run the real lexer, and inspect its decisions. Source and input stay in your browser.</p>
|
|
20
12
|
<div class="playground-notice" role="note">
|
|
21
|
-
|
|
22
|
-
|
|
13
|
+
Run executes Ruby and its actions in a separate worker. Review shared source before running it.
|
|
14
|
+
Runs stop after five seconds; Stop cancels the worker immediately. Ruby loads only on your first run.
|
|
23
15
|
</div>
|
|
24
16
|
</header>
|
|
25
|
-
|
|
26
17
|
<section class="workbench" aria-label="flexr playground workbench">
|
|
27
18
|
<div class="workbench-panel">
|
|
28
|
-
<div class="panel-heading"><
|
|
29
|
-
<select id="preset" aria-label="Choose a playground
|
|
30
|
-
<option value="longest">Longest match</option>
|
|
31
|
-
<option value="
|
|
32
|
-
<option value="json">JSON tokens</option>
|
|
19
|
+
<div class="panel-heading"><label for="spec">Ruby specification</label><small>editable</small></div>
|
|
20
|
+
<select id="preset" aria-label="Choose a playground preset">
|
|
21
|
+
<option value="longest">Longest match</option><option value="calculator">Calculator</option><option value="json">JSON tokens</option>
|
|
22
|
+
<option value="toml">TOML subset</option><option value="graphql">GraphQL subset</option><option value="sql">SQL subset</option>
|
|
33
23
|
</select>
|
|
34
|
-
<textarea id="spec" aria-label="Lexer specification"
|
|
35
|
-
<div class="workbench-actions">
|
|
36
|
-
<button class="button button-secondary" type="button" data-action="check">Check</button>
|
|
37
|
-
<button class="button button-secondary" type="button" data-action="generate">Show generated shape</button>
|
|
38
|
-
</div>
|
|
24
|
+
<textarea id="spec" aria-label="Lexer specification" spellcheck="false" maxlength="20000"></textarea>
|
|
39
25
|
</div>
|
|
40
|
-
|
|
41
26
|
<div class="workbench-panel">
|
|
42
|
-
<div class="panel-heading"><
|
|
43
|
-
<textarea id="input" class="input-area" aria-label="Input to tokenize"></textarea>
|
|
27
|
+
<div class="panel-heading"><label for="input">Input</label><small>up to 20,000 characters</small></div>
|
|
28
|
+
<textarea id="input" class="input-area" aria-label="Input to tokenize" spellcheck="false" maxlength="20000"></textarea>
|
|
29
|
+
<select id="mode" aria-label="Execution mode"><option value="runtime">Runtime mode</option><option value="generated">Generated mode</option></select>
|
|
44
30
|
<div class="workbench-actions">
|
|
45
|
-
<button class="button button-primary" type="button" data-action="run">Run
|
|
46
|
-
<button class="button button-secondary" type="button" data-action="
|
|
31
|
+
<button class="button button-primary" type="button" data-action="run">Run</button>
|
|
32
|
+
<button class="button button-secondary" type="button" data-action="stop" disabled>Stop</button>
|
|
47
33
|
<button class="button button-secondary" type="button" data-action="share">Copy share link</button>
|
|
48
34
|
</div>
|
|
49
|
-
<
|
|
35
|
+
<input id="share-link" class="share-link" aria-label="Share link" readonly hidden />
|
|
36
|
+
<p id="status" class="workbench-status" role="status" aria-live="polite">Choose a preset or write a specification, then select Run.</p>
|
|
37
|
+
<p id="metrics" class="workbench-status"></p>
|
|
50
38
|
</div>
|
|
51
|
-
|
|
52
39
|
<div class="workbench-panel full">
|
|
53
|
-
<div class="panel-heading"><span>Tokens</span
|
|
54
|
-
<
|
|
40
|
+
<div class="panel-heading"><span>Tokens</span></div>
|
|
41
|
+
<pre id="tokens" class="workbench-output">Run a specification to see its token stream.</pre>
|
|
42
|
+
</div>
|
|
43
|
+
<div class="workbench-panel full">
|
|
44
|
+
<div class="panel-heading"><span>Diagnostics</span></div>
|
|
45
|
+
<pre id="diagnostics" class="workbench-output">Compiler warnings and source locations appear here.</pre>
|
|
46
|
+
</div>
|
|
47
|
+
<div class="workbench-panel full">
|
|
48
|
+
<div class="panel-heading"><span>Match decisions</span><span id="step-position">No scan steps.</span></div>
|
|
49
|
+
<div class="workbench-actions">
|
|
50
|
+
<button class="button button-secondary" type="button" data-action="previous">Previous step</button>
|
|
51
|
+
<input id="step" type="range" min="0" max="0" value="0" aria-label="Trace step" disabled />
|
|
52
|
+
<button class="button button-secondary" type="button" data-action="next">Next step</button>
|
|
53
|
+
</div>
|
|
54
|
+
<pre id="decisions" class="workbench-output">Run a specification to inspect its decisions.</pre>
|
|
55
55
|
</div>
|
|
56
|
-
|
|
57
56
|
<div class="workbench-panel full">
|
|
58
|
-
<div class="panel-heading"><span>
|
|
59
|
-
<div id="
|
|
57
|
+
<div class="panel-heading"><span>DFA</span><button type="button" data-action="draw">Draw DFA</button></div>
|
|
58
|
+
<div id="graph" class="workbench-output graph-output">Run a specification to inspect its DFA.</div>
|
|
59
|
+
<details><summary>DOT output</summary><pre id="dot" class="workbench-output"></pre></details>
|
|
60
60
|
</div>
|
|
61
|
+
<details class="workbench-panel full"><summary>Generated Ruby</summary><pre id="generated" class="workbench-output">The real generated scanner appears after a run.</pre></details>
|
|
62
|
+
<details class="workbench-panel full"><summary>Console output</summary><pre id="console" class="workbench-output"></pre></details>
|
|
61
63
|
</section>
|
|
62
64
|
</main>
|
|
63
|
-
<script
|
|
65
|
+
<script>import '../playground/client.js';</script>
|
|
64
66
|
</SiteLayout>
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import workerUrl from './worker.mjs?worker&url';
|
|
2
|
+
import graphWorkerUrl from './graph-worker.mjs?worker&url';
|
|
3
|
+
import { PRESETS } from './presets.mjs';
|
|
4
|
+
import { decodeState, encodeState, validateState } from './share.mjs';
|
|
5
|
+
|
|
6
|
+
const source = document.querySelector('#spec');
|
|
7
|
+
const input = document.querySelector('#input');
|
|
8
|
+
const mode = document.querySelector('#mode');
|
|
9
|
+
const status = document.querySelector('#status');
|
|
10
|
+
const runButton = document.querySelector('[data-action="run"]');
|
|
11
|
+
const stopButton = document.querySelector('[data-action="stop"]');
|
|
12
|
+
const steps = document.querySelector('#step');
|
|
13
|
+
let worker;
|
|
14
|
+
let timer;
|
|
15
|
+
let graphWorker;
|
|
16
|
+
let graphTimer;
|
|
17
|
+
let trace = [];
|
|
18
|
+
let dot = '';
|
|
19
|
+
|
|
20
|
+
function show(id, text) { document.querySelector(`#${id}`).textContent = text; }
|
|
21
|
+
|
|
22
|
+
function stop(message = 'Stopped. Edit the source or input, then run again.') {
|
|
23
|
+
worker?.terminate();
|
|
24
|
+
worker = undefined;
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
runButton.disabled = false;
|
|
27
|
+
stopButton.disabled = true;
|
|
28
|
+
status.textContent = message;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function selectStep(index) {
|
|
32
|
+
steps.value = String(Math.max(0, Math.min(index, trace.length - 1)));
|
|
33
|
+
const selected = trace[Number(steps.value)];
|
|
34
|
+
show('step-position', selected ? `Step ${Number(steps.value) + 1} of ${trace.length}` : 'No scan steps.');
|
|
35
|
+
show('decisions', selected ? JSON.stringify(selected, null, 2) : 'Run a specification to inspect its decisions.');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function display(result) {
|
|
39
|
+
if (!result || typeof result !== 'object') throw new Error('The worker returned an invalid result.');
|
|
40
|
+
if (typeof result.error === 'string') {
|
|
41
|
+
show('diagnostics', result.error);
|
|
42
|
+
show('tokens', 'Execution failed.');
|
|
43
|
+
show('generated', 'Generation did not finish.');
|
|
44
|
+
show('console', 'No console output.');
|
|
45
|
+
show('graph', 'No automaton is available.');
|
|
46
|
+
show('dot', '');
|
|
47
|
+
stop('The specification or input failed. Read the diagnostic below.');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (!Array.isArray(result.tokens) || !Array.isArray(result.steps) || typeof result.generated !== 'string' || typeof result.dot !== 'string') {
|
|
51
|
+
throw new Error('The worker returned an invalid result.');
|
|
52
|
+
}
|
|
53
|
+
show('tokens', JSON.stringify(result.tokens, null, 2));
|
|
54
|
+
show('diagnostics', result.diagnostics || 'No diagnostics.');
|
|
55
|
+
show('generated', result.generated);
|
|
56
|
+
show('console', result.console || 'No console output.');
|
|
57
|
+
dot = result.dot;
|
|
58
|
+
show('dot', dot);
|
|
59
|
+
show('graph', 'Select Draw DFA to load Graphviz and render this automaton.');
|
|
60
|
+
trace = result.steps;
|
|
61
|
+
steps.max = String(Math.max(0, trace.length - 1));
|
|
62
|
+
steps.disabled = trace.length === 0;
|
|
63
|
+
selectStep(0);
|
|
64
|
+
stop(`${result.tokens.length} token${result.tokens.length === 1 ? '' : 's'}, ${trace.length} step${trace.length === 1 ? '' : 's'}. Ruby ${result.ruby_version}, Prism ${result.prism_version}.`);
|
|
65
|
+
show('metrics', `${(Number(result.wasm_bytes) / 1_048_576).toFixed(2)} MiB Ruby download; download/compile ${Math.round(Number(result.download_ms))} ms; VM and flexr startup ${Math.round(Number(result.startup_ms))} ms. Cached downloads may be faster.`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function run() {
|
|
69
|
+
stop();
|
|
70
|
+
try {
|
|
71
|
+
const state = validateState({ source: source.value, input: input.value, mode: mode.value });
|
|
72
|
+
show('tokens', 'Running…');
|
|
73
|
+
show('diagnostics', 'Compiling…');
|
|
74
|
+
show('generated', 'Generating…');
|
|
75
|
+
show('graph', 'Compiling…');
|
|
76
|
+
show('dot', 'Compiling…');
|
|
77
|
+
show('console', 'Running…');
|
|
78
|
+
graphWorker?.terminate();
|
|
79
|
+
clearTimeout(graphTimer);
|
|
80
|
+
trace = [];
|
|
81
|
+
dot = '';
|
|
82
|
+
selectStep(0);
|
|
83
|
+
const url = new URL(workerUrl, location.href).href;
|
|
84
|
+
const bootstrap = `let queued; self.onmessage=e=>{queued=e.data}; import(${JSON.stringify(url)}).then(()=>{if(queued)self.dispatchEvent(new MessageEvent('message',{data:queued}))});`;
|
|
85
|
+
const blob = URL.createObjectURL(new Blob([bootstrap], { type: 'text/javascript' }));
|
|
86
|
+
worker = new Worker(blob, { type: 'module' });
|
|
87
|
+
URL.revokeObjectURL(blob);
|
|
88
|
+
runButton.disabled = true;
|
|
89
|
+
stopButton.disabled = false;
|
|
90
|
+
status.textContent = 'Loading Ruby locally. The runtime is about 31 MiB before compression.';
|
|
91
|
+
timer = setTimeout(() => stop('Runtime loading exceeded 30 seconds. Check the connection and retry.'), 30_000);
|
|
92
|
+
worker.onerror = () => stop('The worker failed. Retry, or reduce the specification.');
|
|
93
|
+
let started = false;
|
|
94
|
+
const currentWorker = worker;
|
|
95
|
+
worker.onmessage = ({ data }) => {
|
|
96
|
+
if (currentWorker !== worker) return;
|
|
97
|
+
if (data?.phase === 'ready' && !started) {
|
|
98
|
+
started = true;
|
|
99
|
+
clearTimeout(timer);
|
|
100
|
+
status.textContent = 'Running the specification in a worker…';
|
|
101
|
+
timer = setTimeout(() => stop('Execution exceeded 5 seconds and was stopped. Reduce the specification or input.'), 5_000);
|
|
102
|
+
} else if (data?.phase === 'error') {
|
|
103
|
+
stop(String(data.error));
|
|
104
|
+
} else if (data?.phase === 'result') {
|
|
105
|
+
try { display(data.result); } catch (error) { stop(error.message); }
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const base = new URL(`${import.meta.env.BASE_URL}/playground-runtime/`.replaceAll('//', '/'), location.origin).href;
|
|
109
|
+
worker.postMessage({ state, base });
|
|
110
|
+
} catch (error) { stop(error.message); }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function safeSvg(text) {
|
|
114
|
+
const parsed = new DOMParser().parseFromString(text, 'image/svg+xml');
|
|
115
|
+
const allowed = new Set(['svg', 'g', 'title', 'polygon', 'path', 'ellipse', 'text', 'polyline', 'rect', 'line', 'circle']);
|
|
116
|
+
const attributes = new Set(['viewBox', 'width', 'height', 'fill', 'stroke', 'transform', 'points', 'd', 'rx', 'ry', 'cx', 'cy', 'x', 'y', 'font-family', 'font-size', 'text-anchor', 'stroke-width']);
|
|
117
|
+
function copy(node) {
|
|
118
|
+
if (node.nodeType === Node.TEXT_NODE) return document.createTextNode(node.textContent);
|
|
119
|
+
if (node.nodeType !== Node.ELEMENT_NODE || !allowed.has(node.localName)) return document.createTextNode('');
|
|
120
|
+
const clean = document.createElementNS('http://www.w3.org/2000/svg', node.localName);
|
|
121
|
+
for (const attribute of node.attributes) {
|
|
122
|
+
if (attributes.has(attribute.name) && !/url\s*\(/i.test(attribute.value)) clean.setAttribute(attribute.name, attribute.value);
|
|
123
|
+
}
|
|
124
|
+
for (const child of node.childNodes) clean.append(copy(child));
|
|
125
|
+
return clean;
|
|
126
|
+
}
|
|
127
|
+
if (parsed.documentElement.localName !== 'svg') throw new Error('Graphviz returned invalid SVG.');
|
|
128
|
+
return copy(parsed.documentElement);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function drawGraph() {
|
|
132
|
+
if (!dot) { show('graph', 'Run a specification first.'); return; }
|
|
133
|
+
graphWorker?.terminate();
|
|
134
|
+
clearTimeout(graphTimer);
|
|
135
|
+
show('graph', 'Drawing DFA…');
|
|
136
|
+
graphWorker = new Worker(graphWorkerUrl, { type: 'module' });
|
|
137
|
+
graphTimer = setTimeout(() => {
|
|
138
|
+
graphWorker.terminate();
|
|
139
|
+
show('graph', 'Drawing exceeded 5 seconds. Inspect the DOT output instead.');
|
|
140
|
+
}, 5000);
|
|
141
|
+
graphWorker.onmessage = ({ data }) => {
|
|
142
|
+
clearTimeout(graphTimer);
|
|
143
|
+
graphWorker.terminate();
|
|
144
|
+
try {
|
|
145
|
+
if (typeof data?.svg !== 'string' || data.svg.length > 2_000_000) throw new Error(data?.error || 'The diagram is too large. Inspect the DOT output.');
|
|
146
|
+
document.querySelector('#graph').replaceChildren(safeSvg(data.svg));
|
|
147
|
+
} catch (error) { show('graph', error.message); }
|
|
148
|
+
};
|
|
149
|
+
graphWorker.onerror = () => {
|
|
150
|
+
clearTimeout(graphTimer);
|
|
151
|
+
graphWorker.terminate();
|
|
152
|
+
show('graph', 'Graphviz could not draw this DFA. Inspect the DOT output instead.');
|
|
153
|
+
};
|
|
154
|
+
graphWorker.postMessage(dot);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let languagePresets;
|
|
158
|
+
document.querySelector('#preset').addEventListener('change', async event => {
|
|
159
|
+
stop();
|
|
160
|
+
const name = event.target.value;
|
|
161
|
+
try {
|
|
162
|
+
let preset = PRESETS[name];
|
|
163
|
+
if (!preset) {
|
|
164
|
+
status.textContent = 'Loading the repository example…';
|
|
165
|
+
languagePresets ||= fetch(`${import.meta.env.BASE_URL}/playground-runtime/presets.json`.replaceAll('//', '/'))
|
|
166
|
+
.then(response => {
|
|
167
|
+
if (!response.ok) throw new Error('The example presets could not be downloaded.');
|
|
168
|
+
return response.json();
|
|
169
|
+
});
|
|
170
|
+
preset = (await languagePresets)[name];
|
|
171
|
+
}
|
|
172
|
+
const state = validateState({ ...preset, mode: mode.value });
|
|
173
|
+
if (event.target.value !== name) return;
|
|
174
|
+
source.value = state.source;
|
|
175
|
+
input.value = state.input;
|
|
176
|
+
status.textContent = 'Preset loaded. Edit it or run it as written.';
|
|
177
|
+
} catch (error) { status.textContent = error.message; }
|
|
178
|
+
});
|
|
179
|
+
document.querySelector('[data-action="run"]').addEventListener('click', run);
|
|
180
|
+
document.querySelector('[data-action="stop"]').addEventListener('click', () => stop());
|
|
181
|
+
document.querySelector('[data-action="draw"]').addEventListener('click', drawGraph);
|
|
182
|
+
document.querySelector('[data-action="previous"]').addEventListener('click', () => selectStep(Number(steps.value) - 1));
|
|
183
|
+
document.querySelector('[data-action="next"]').addEventListener('click', () => selectStep(Number(steps.value) + 1));
|
|
184
|
+
steps.addEventListener('input', () => selectStep(Number(steps.value)));
|
|
185
|
+
document.querySelector('[data-action="share"]').addEventListener('click', async () => {
|
|
186
|
+
try {
|
|
187
|
+
const hash = encodeState({ source: source.value, input: input.value, mode: mode.value });
|
|
188
|
+
history.replaceState(null, '', `#${hash}`);
|
|
189
|
+
const link = document.querySelector('#share-link');
|
|
190
|
+
link.value = location.href;
|
|
191
|
+
link.hidden = false;
|
|
192
|
+
link.select();
|
|
193
|
+
await navigator.clipboard?.writeText(location.href);
|
|
194
|
+
status.textContent = 'Share link ready below. Opening it loads the text without running it.';
|
|
195
|
+
} catch (error) { status.textContent = error.message; }
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
source.value = PRESETS.longest.source;
|
|
199
|
+
input.value = PRESETS.longest.input;
|
|
200
|
+
function restoreShare() {
|
|
201
|
+
if (location.hash.length <= 1) return;
|
|
202
|
+
try {
|
|
203
|
+
const state = decodeState(location.hash.slice(1));
|
|
204
|
+
source.value = state.source;
|
|
205
|
+
input.value = state.input;
|
|
206
|
+
mode.value = state.mode;
|
|
207
|
+
status.textContent = 'Shared source loaded. Review it before selecting Run.';
|
|
208
|
+
} catch (error) { status.textContent = error.message; }
|
|
209
|
+
}
|
|
210
|
+
restoreShare();
|
|
211
|
+
window.addEventListener('hashchange', restoreShare);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { instance } from '@viz-js/viz';
|
|
2
|
+
|
|
3
|
+
self.onmessage = async ({ data }) => {
|
|
4
|
+
try {
|
|
5
|
+
if (typeof data !== 'string' || data.length > 500_000) throw new Error('DFA is too large to draw. Inspect its DOT output instead.');
|
|
6
|
+
const viz = await instance();
|
|
7
|
+
self.postMessage({ svg: viz.renderString(data, { format: 'svg', engine: 'dot' }) });
|
|
8
|
+
} catch (error) {
|
|
9
|
+
self.postMessage({ error: error instanceof Error ? error.message : String(error) });
|
|
10
|
+
}
|
|
11
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const PRESETS = {
|
|
2
|
+
longest: {
|
|
3
|
+
input: 'if == total',
|
|
4
|
+
source: `class Lexer < Flexr::Lexer
|
|
5
|
+
emits :EQ, :ASSIGN, :IF, :IDENT
|
|
6
|
+
rule(/[ \\t\\n]+/, skip: true)
|
|
7
|
+
rule(/==/, emit: :EQ)
|
|
8
|
+
rule(/=/, emit: :ASSIGN)
|
|
9
|
+
rule(/if/, emit: :IF)
|
|
10
|
+
rule(/[a-z_][a-z0-9_]*/, emit: :IDENT)
|
|
11
|
+
end`,
|
|
12
|
+
},
|
|
13
|
+
calculator: {
|
|
14
|
+
input: '12 + 3 * 4',
|
|
15
|
+
source: `class Lexer < Flexr::Lexer
|
|
16
|
+
emits :INTEGER, :PLUS, :STAR
|
|
17
|
+
rule(/[ \\t\\n]+/, skip: true)
|
|
18
|
+
rule(/[0-9]+/) { emit :INTEGER, text.to_i }
|
|
19
|
+
rule(/\\+/, emit: :PLUS)
|
|
20
|
+
rule(/\\*/, emit: :STAR)
|
|
21
|
+
end`,
|
|
22
|
+
},
|
|
23
|
+
json: {
|
|
24
|
+
input: '{"ok": true, "count": 2}',
|
|
25
|
+
source: `class Lexer < Flexr::Lexer
|
|
26
|
+
rule(/[ \\t\\n]+/, skip: true)
|
|
27
|
+
rule(/[{}:,\\[\\]]/) { emit text }
|
|
28
|
+
rule(/true|false|null/, emit: :KEYWORD)
|
|
29
|
+
rule(/"[^"\\n]*"/, emit: :STRING)
|
|
30
|
+
rule(/[0-9]+/) { emit :NUMBER, text.to_i }
|
|
31
|
+
end`,
|
|
32
|
+
},
|
|
33
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { DefaultRubyVM } from '@ruby/wasm-wasi/dist/browser';
|
|
2
|
+
import { validateState } from './share.mjs';
|
|
3
|
+
|
|
4
|
+
function rubyData(value) {
|
|
5
|
+
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
|
6
|
+
let binary = '';
|
|
7
|
+
for (let index = 0; index < bytes.length; index += 4096) binary += String.fromCharCode(...bytes.subarray(index, index + 4096));
|
|
8
|
+
return `JSON.parse(${JSON.stringify(btoa(binary))}.unpack1("m0"))`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function createRuntime(binary, assets) {
|
|
12
|
+
const module = await WebAssembly.compile(binary);
|
|
13
|
+
return {
|
|
14
|
+
async run(request, ready = () => {}) {
|
|
15
|
+
validateState(request);
|
|
16
|
+
const start = performance.now();
|
|
17
|
+
const { vm } = await DefaultRubyVM(module, { consolePrint: false });
|
|
18
|
+
vm.eval(`require "json"; require "fileutils"
|
|
19
|
+
${rubyData(assets.files)}.each do |path, source|
|
|
20
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
21
|
+
File.write(path, source)
|
|
22
|
+
end
|
|
23
|
+
$LOAD_PATH.unshift("/app/lib")
|
|
24
|
+
require "flexr/cli"
|
|
25
|
+
require "flexr/trace"
|
|
26
|
+
load "/app/playground.rb"
|
|
27
|
+
`);
|
|
28
|
+
const startupMs = performance.now() - start;
|
|
29
|
+
ready(startupMs);
|
|
30
|
+
const result = JSON.parse(vm.eval(`FlexrPlayground.run(${rubyData(request)})`).toString());
|
|
31
|
+
return { ...result, startup_ms: startupMs };
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|