Upload all of experiments/ as on disk 2026-11-11 (part 4)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/tests/fixtures/records.json +0 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/tsconfig.json +15 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/vitest.config.ts +16 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/proxy.log +21 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/result.json +1 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/run.json +28 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/run.lock +0 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/stderr.log +13 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/stderr.txt +1 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/stdout.log +1 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/transcript/.claude/projects/-target/c3ea8813-5775-454d-891e-c6891c1f6cb0.jsonl +0 -0
- v2-models-effort/runs/20261111-214430-fragrant-meadow/transcript/.claude/projects/-target/c3ea8813-5775-454d-891e-c6891c1f6cb0/tool-results/bkjm0r0j4.txt +1869 -0
- v2-models-effort/runs/20261111-214430-mute-surf/credentials.log +21 -0
- v2-models-effort/runs/20261111-214430-mute-surf/git-diff.patch +0 -0
- v2-models-effort/runs/20261111-214430-mute-surf/git-sha.txt +1 -0
- v2-models-effort/runs/20261111-214430-mute-surf/manifest.json +99 -0
- v2-models-effort/runs/20261111-214430-mute-surf/memory.jsonl +107 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/.gitignore +1 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/README.md +29 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/GBNF.ts +29 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/colorize.test.ts +15 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/colorize.ts +10 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_input_as_code_points.test.ts +21 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_input_as_code_points.ts +36 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_parent_stack_id.test.ts +59 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_parent_stack_id.ts +16 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_serialized_rule_key.test.ts +61 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_serialized_rule_key.ts +38 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/grammar_graph_types.ts +65 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph.test.ts +89 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph.ts +258 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_node.test.ts +52 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_node.ts +45 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_pointer.test.ts +138 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_pointer.ts +107 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/parse_state.test.ts +81 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/parse_state.ts +62 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/pointers.ts +32 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/print.test.ts +92 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/print.ts +83 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/rule_ref.test.ts +27 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/rule_ref.ts +28 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/type_guards.test.ts +130 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/type_guards.ts +30 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_parser/build_rule_stack.test.ts +22 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_parser/build_rule_stack.ts +103 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/index.ts +6 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/rules_builder/index.ts +2 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/rules_builder/is_word_char.test.ts +26 -0
- v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/rules_builder/is_word_char.ts +1 -0
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/tests/fixtures/records.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/tsconfig.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"compilerOptions": {
|
| 3 |
+
"target": "ES2022",
|
| 4 |
+
"module": "ESNext",
|
| 5 |
+
"moduleResolution": "Bundler",
|
| 6 |
+
"strict": true,
|
| 7 |
+
"noEmit": true,
|
| 8 |
+
"allowImportingTsExtensions": true,
|
| 9 |
+
"skipLibCheck": true,
|
| 10 |
+
"types": ["vitest/globals"],
|
| 11 |
+
"baseUrl": ".",
|
| 12 |
+
"paths": { "gbnf": ["./gbnf/index.ts"], "gbnf/*": ["./gbnf/*"] }
|
| 13 |
+
},
|
| 14 |
+
"include": ["gbnf", "tests"]
|
| 15 |
+
}
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/vitest.config.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { fileURLToPath } from 'node:url';
|
| 2 |
+
import { defineConfig } from 'vitest/config';
|
| 3 |
+
|
| 4 |
+
const root = fileURLToPath(new URL('./gbnf', import.meta.url));
|
| 5 |
+
|
| 6 |
+
export default defineConfig({
|
| 7 |
+
resolve: {
|
| 8 |
+
alias: [
|
| 9 |
+
{ find: /^gbnf$/, replacement: `${root}/index.ts` },
|
| 10 |
+
{ find: /^gbnf\/(.*)$/, replacement: `${root}/$1` },
|
| 11 |
+
],
|
| 12 |
+
},
|
| 13 |
+
test: {
|
| 14 |
+
include: ['gbnf/**/*.test.ts', 'gbnf/**/*_test.ts', 'tests/**/*.test.ts', 'tests/**/*_test.ts'],
|
| 15 |
+
},
|
| 16 |
+
});
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/proxy.log
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NOTICE Nov 11 21:44:43.333 [8]: Initializing tinyproxy ...
|
| 2 |
+
NOTICE Nov 11 21:44:43.333 [8]: Reloading config file (/etc/tinyproxy/tinyproxy.conf)
|
| 3 |
+
INFO Nov 11 21:44:43.333 [8]: Added address [127.0.0.1] to listen addresses.
|
| 4 |
+
INFO Nov 11 21:44:43.333 [8]: Adding Port [443] to the list allowed by CONNECT
|
| 5 |
+
NOTICE Nov 11 21:44:43.333 [8]: Reloading config file finished
|
| 6 |
+
INFO Nov 11 21:44:43.333 [8]: listen_sock called with addr = '127.0.0.1'
|
| 7 |
+
INFO Nov 11 21:44:43.333 [8]: trying to listen on host[127.0.0.1], family[2], socktype[1], proto[6]
|
| 8 |
+
INFO Nov 11 21:44:43.333 [8]: listening on fd [3]
|
| 9 |
+
INFO Nov 11 21:44:43.333 [8]: Not running as root, so not changing UID/GID.
|
| 10 |
+
INFO Nov 11 21:44:43.333 [8]: Setting the various signals.
|
| 11 |
+
INFO Nov 11 21:44:43.333 [8]: Starting main loop. Accepting connections.
|
| 12 |
+
botbox-proxy: listening
|
| 13 |
+
CONNECT Nov 11 21:44:44.303 [8]: Connect (file descriptor 4): 127.0.0.1
|
| 14 |
+
CONNECT Nov 11 21:44:44.303 [8]: Request (file descriptor 4): CONNECT api.anthropic.com:443 HTTP/1.1
|
| 15 |
+
NOTICE Nov 11 21:44:44.303 [8]: Proxying refused on filtered url "api.anthropic.com:443"
|
| 16 |
+
CONNECT Nov 11 21:49:20.245 [8]: Connect (file descriptor 4): 127.0.0.1
|
| 17 |
+
CONNECT Nov 11 21:49:20.246 [8]: Request (file descriptor 4): CONNECT registry.npmjs.org:443 HTTP/1.1
|
| 18 |
+
NOTICE Nov 11 21:49:20.246 [8]: Proxying refused on filtered url "registry.npmjs.org:443"
|
| 19 |
+
CONNECT Nov 11 21:49:20.255 [8]: Connect (file descriptor 4): 127.0.0.1
|
| 20 |
+
CONNECT Nov 11 21:49:20.255 [8]: Request (file descriptor 4): CONNECT registry.npmjs.org:443 HTTP/1.1
|
| 21 |
+
NOTICE Nov 11 21:49:20.255 [8]: Proxying refused on filtered url "registry.npmjs.org:443"
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/result.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"duration_api_ms":359432,"stop_reason":"end_turn","session_id":"c3ea8813-5775-454d-891e-c6891c1f6cb0","total_cost_usd":2.1344278000000005,"usage":{"input_tokens":30,"cache_creation_input_tokens":125920,"cache_read_input_tokens":1246039,"output_tokens":43887,"output_tokens_details":{"thinking_tokens":8749},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":125920,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-fable-5-2":{"inputTokens":30,"outputTokens":43887,"cacheReadInputTokens":1246039,"cacheCreationInputTokens":125920,"webSearchRequests":0,"costUSD":2.1344278000000005,"contextWindow":200000,"maxOutputTokens":32000,"thinkingTokens":8749,"canonicalModel":"claude-fable-5-2","provider":"firstParty","costBasis":"unknown"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":false,"num_turns":17,"subtype":"success","api_error_status":null,"result":"The TypeScript port is in `/target/gbnf`, mirroring the Python module layout file for file. It matches the reference on 580 recorded cases (the 320 generated integration tests plus extra grammars and inputs), compared order-insensitively for parse-state rules; see the last bullet. I did not port the Python unit test files one by one; a small smoke test covers the helpers, and there was no `tsc` in the sandbox, so the code is only checked through vitest's transpile, not type-checked.\n\nThings that differ from a literal translation, which matter if your tests assume a particular shape:\n\n- **Names**: functions and methods keep their Python snake_case names (`build_rule_stack`, `parse_char`, `__get_root_node__`); standalone functions also get camelCase aliases, methods only partly (none for the `__parse__`-style internals or `parse_state`). Files are snake_case `.ts`.\n- **Imports**: `import { GBNF, RuleChar, RuleCharExclude, RuleEnd, GrammarParseError, InputParseError } from 'gbnf'` works through an alias in `vitest.config.ts`.\n- **Constructors**: rule classes take the value positionally (`new RuleChar([97])`) or as `{ value }`.\n- **Rule objects**: `RuleChar`, `RuleCharExclude` and `RuleEnd` carry an own `type` property holding the class name, matching Python's `__dict__`. A `toEqual` against a plain `{ value: [...] }` literal would therefore fail.\n- **Python operators**: `state + \"x\"` becomes `state.add(\"x\")`; states are also callable (`state(\"x\")`). `__eq__` becomes an `equals()` method.\n- **Errors**: `ValueError` becomes a plain `Error` with the same message; the two parse errors keep their classes, messages and `error_for_most_recent_input`.\n- **Dicts**: root nodes are `Map`s, so `len(root_node)` is `.size`.\n- **Out-of-range cases**: where Python raises `IndexError` on a truncated grammar (unterminated string or bracket), the port raises `GrammarParseError` instead. A grammar with no `root` rule raises `GrammarParseError` rather than Python's `KeyError`.\n- **Rule order**: Python iterates referenced nodes from a `set`, so its order is arbitrary; the port uses insertion order. On 25 recorded cases the order differs from what Python happened to produce, 12 of them in the generated suites. All 12 are in the two suites that sort before comparing; the unsorted `iteration_test` cases match exactly.\n\nRun everything with `vitest run` from `/target`; the recorded cases are in `tests/fixtures/records.json`.","ttft_ms":2059,"type":"result","duration_ms":366949,"uuid":"fd99c9b2-cfbd-468a-a8cf-33b38189df52","ttft_stream_ms":758,"time_to_request_ms":54,"first_content_frame_ms":758,"queued_turn_count":0,"result_index":0}
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/run.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"params": {
|
| 3 |
+
"source-language": "python",
|
| 4 |
+
"model": "claude-fable-5-2",
|
| 5 |
+
"effort": "low"
|
| 6 |
+
},
|
| 7 |
+
"command": "uv run --project packages/gbnf_experiment run_gbnf_experiment --include-unit-tests 1 --include-source-integration-tests 1 --include-target-integration-tests 0 --output /home/duncan/work/code/research/ports/experiments/v2-models-effort/runs/20261111-214430-fragrant-meadow --source-language python --model claude-fable-5-2 --effort low --auth subscription --memory 24g",
|
| 8 |
+
"created": "2026-11-11T21:44:30Z",
|
| 9 |
+
"ended": "2026-11-11T21:50:52Z",
|
| 10 |
+
"exit_code": 0,
|
| 11 |
+
"error": null,
|
| 12 |
+
"ended_by": null,
|
| 13 |
+
"signal": null,
|
| 14 |
+
"git": {
|
| 15 |
+
"commit": "8422439f49db061ed5b56e9b883ef244807898f8",
|
| 16 |
+
"dirty": true
|
| 17 |
+
},
|
| 18 |
+
"labnotes_version": "0.2.39.dev138",
|
| 19 |
+
"labnotes_command": "labnotes experiments v2-models-effort run --concurrency 1 --model=claude-fable-5-2 -- --auth subscription --memory 24g",
|
| 20 |
+
"args": [
|
| 21 |
+
"--auth",
|
| 22 |
+
"subscription",
|
| 23 |
+
"--memory",
|
| 24 |
+
"24g"
|
| 25 |
+
],
|
| 26 |
+
"pid": 1884821,
|
| 27 |
+
"pid_created": 1794433470.37
|
| 28 |
+
}
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/run.lock
ADDED
|
File without changes
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/stderr.log
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Using CPython [36m3.14.4[39m[36m[39m
|
| 2 |
+
Creating virtual environment at: [36mpackages/gbnf_experiment/.venv[39m
|
| 3 |
+
[36m[1mBuilding[0m[39m gbnf-experiment[2m @ file:///tmp/labnotes-ddsct2on/packages/gbnf_experiment[0m
|
| 4 |
+
[36m[1mBuilding[0m[39m port-codebase[2m @ file:///tmp/labnotes-ddsct2on/packages/port_codebase[0m
|
| 5 |
+
[36m[1mBuilding[0m[39m prompt[2m @ file:///tmp/labnotes-ddsct2on/packages/prompt[0m
|
| 6 |
+
[1m[33mwarning[39m[0m[1m:[0m [1m`build_system.requires = ["uv-build>=0.10.11,<0.11.0"]` does not contain the current uv version 0.13.5[0m
|
| 7 |
+
[32m[1mBuilt[0m[39m gbnf-experiment[2m @ file:///tmp/labnotes-ddsct2on/packages/gbnf_experiment[0m
|
| 8 |
+
[32m[1mBuilt[0m[39m prompt[2m @ file:///tmp/labnotes-ddsct2on/packages/prompt[0m
|
| 9 |
+
[32m[1mBuilt[0m[39m port-codebase[2m @ file:///tmp/labnotes-ddsct2on/packages/port_codebase[0m
|
| 10 |
+
[1m[33mwarning[39m[0m[1m:[0m [1mFailed to hardlink files; falling back to full copy. This may lead to degraded performance.
|
| 11 |
+
If the cache and target directories are on different filesystems, hardlinking may not be supported.
|
| 12 |
+
If this is intentional, set `export UV_LINK_MODE=copy` or use `--link-mode=copy` to suppress this warning.[0m
|
| 13 |
+
[2mInstalled [1m26 packages[0m [2min 87ms[0m[0m
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/stderr.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[claude-code:unrecognized_model] {"model":"claude-fable-5-2","query_source":"sdk"}
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/stdout.log
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*** auth: subscription ***
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/transcript/.claude/projects/-target/c3ea8813-5775-454d-891e-c6891c1f6cb0.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v2-models-effort/runs/20261111-214430-fragrant-meadow/transcript/.claude/projects/-target/c3ea8813-5775-454d-891e-c6891c1f6cb0/tool-results/bkjm0r0j4.txt
ADDED
|
@@ -0,0 +1,1869 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GBNF
|
| 2 |
+
|
| 3 |
+
<a href="https://pypi.org/project/gbnf"><img alt="Latest GBNF PyPI Version" src="https://badge.fury.io/py/gbnf.svg" /></a>
|
| 4 |
+
<a href="https://github.com/ambient-labs/GBNF/packages/gbnf/blob/master/LICENSE"><img alt="License for gbnf" src="https://img.shields.io/pypi/l/gbnf" /></a>
|
| 5 |
+
<a href="https://pypi.org/project/gbnf"><img alt="Downloads per week on PyPI for gbnf" src="https://img.shields.io/pypi/dw/gbnf" /></a>
|
| 6 |
+
<a href="https://github.com/ambient-labs/GBNF/packages/gbnf/actions/workflows/tests.yaml"><img src="https://github.com/ambient-labs/GBNF/packages/gbnf/actions/workflows/tests.yaml/badge.svg" alt="Status of tests for gbnf repository" /></a>
|
| 7 |
+
<a href="https://codecov.io/gh/ambient-labs/gbnf"><img alt="Code Coverage for gbnf" src="https://img.shields.io/codecov/c/github/ambient-labs/gbnf" /></a>
|
| 8 |
+
<a href="https://deepsource.io/gh/ambient-labs/gbnf/?ref=repository-badge"><img alt="DeepSource issues for gbnf" src="https://deepsource.io/gh/ambient-labs/gbnf.svg/?label=active+issues&show_trend=true" /></a>
|
| 9 |
+
|
| 10 |
+
A library for parsing `.gbnf` grammar files in Python.
|
| 11 |
+
|
| 12 |
+
## Install
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
pip install gbnf
|
| 16 |
+
```
|
| 17 |
+
[project]
|
| 18 |
+
name = "gbnf"
|
| 19 |
+
version = "0.0.30"
|
| 20 |
+
readme = "README.md"
|
| 21 |
+
requires-python = ">=3.11"
|
| 22 |
+
dependencies = [ "pytest-watcher>=0.4.3",]
|
| 23 |
+
description = "A library for parsing GBNF grammars"
|
| 24 |
+
classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent",]
|
| 25 |
+
[[project.authors]]
|
| 26 |
+
name = "Ambient Labs"
|
| 27 |
+
email = "maintainers@gbnf.dev"
|
| 28 |
+
|
| 29 |
+
[build-system]
|
| 30 |
+
requires = [ "setuptools",]
|
| 31 |
+
build-backend = "setuptools.build_meta"
|
| 32 |
+
|
| 33 |
+
[project.urls]
|
| 34 |
+
Homepage = "https://github.com/ambient-labs/GBNF/packages/gbnf"
|
| 35 |
+
"Bug Tracker" = "https://github.com/ambient-labs/GBNF/packages/gbnf/issues"
|
| 36 |
+
|
| 37 |
+
[tool.ruff]
|
| 38 |
+
line-length = 120
|
| 39 |
+
preview = true
|
| 40 |
+
|
| 41 |
+
[tool.uv]
|
| 42 |
+
dev-dependencies = [ "pytest-describe>=2.2.0", "pytest-watcher>=0.4.3", "pytest>=8.3.3",]
|
| 43 |
+
|
| 44 |
+
[tool.ruff.lint]
|
| 45 |
+
extend-select = [ "A", "ARG", "B", "BLE", "COM", "E", "F", "FA", "FIX", "FLY", "FURB", "G", "I", "ICN", "ISC", "INP", "PERF", "PGH", "PIE", "PT", "PTH", "RET", "RSE", "RUF", "SLOT", "T20", "TD", "TID", "UP", "W", "YTT",]
|
| 46 |
+
ignore = [ "TD002", "TD003", "TID252", "FIX002", "BLE001", "FLY002",]
|
| 47 |
+
fixable = [ "ALL",]
|
| 48 |
+
unfixable = []
|
| 49 |
+
|
| 50 |
+
[tool.ruff.format]
|
| 51 |
+
quote-style = "double"
|
| 52 |
+
indent-style = "space"
|
| 53 |
+
skip-magic-trailing-comma = false
|
| 54 |
+
line-ending = "auto"
|
| 55 |
+
|
| 56 |
+
[tool.pytest.ini_options]
|
| 57 |
+
minversion = "6.0"
|
| 58 |
+
testpaths = [ "gbnf/**/*_test.py",]
|
| 59 |
+
|
| 60 |
+
[tool.ruff.lint.per-file-ignores]
|
| 61 |
+
"**/*_test.py" = [ "T201", "RUF012", "PERF203", "FLY002", "ARG001", "B008", "ARG002", "A002", "A001",]
|
| 62 |
+
|
| 63 |
+
[tool.setuptools.packages.find]
|
| 64 |
+
where = [ ".",]
|
| 65 |
+
include = [ "gbnf*",]
|
| 66 |
+
SHELL := /bin/bash
|
| 67 |
+
|
| 68 |
+
init:
|
| 69 |
+
uv venv --python python3.12 && uv sync
|
| 70 |
+
|
| 71 |
+
lint:
|
| 72 |
+
uvx ruff check . --fix
|
| 73 |
+
|
| 74 |
+
copy_assets:
|
| 75 |
+
cp ../../../LICENSE ./
|
| 76 |
+
|
| 77 |
+
build_all:
|
| 78 |
+
make copy_assets && make build_package
|
| 79 |
+
|
| 80 |
+
build_package:
|
| 81 |
+
uv run --with build -m build
|
| 82 |
+
|
| 83 |
+
upgrade_dev_dependencies:
|
| 84 |
+
./upgrade_dev_dependencies.sh
|
| 85 |
+
|
| 86 |
+
build_test_writer:
|
| 87 |
+
cd ../../test-writer && pnpm build
|
| 88 |
+
|
| 89 |
+
write_integration_tests:
|
| 90 |
+
@echo "Writing integration tests..."
|
| 91 |
+
@$(MAKE) -s build_test_writer
|
| 92 |
+
@node --no-warnings ../../test-writer/dist/test-writer.mjs \
|
| 93 |
+
validation \
|
| 94 |
+
iteration/iteration \
|
| 95 |
+
--testDir ../test \
|
| 96 |
+
--targetDir ./tests/generated \
|
| 97 |
+
--language python
|
| 98 |
+
|
| 99 |
+
test_integration:
|
| 100 |
+
@$(MAKE) -s write_integration_tests
|
| 101 |
+
@$(MAKE) -s test_integration_only
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
test_integration_only:
|
| 105 |
+
uv run pytest ./tests/generated
|
| 106 |
+
|
| 107 |
+
# test_integration_watch:
|
| 108 |
+
# uv run ptw --now tests/generated
|
| 109 |
+
|
| 110 |
+
test:
|
| 111 |
+
make test_unit
|
| 112 |
+
|
| 113 |
+
test_unit:
|
| 114 |
+
uv run pytest ./gbnf/**/*_test.py
|
| 115 |
+
|
| 116 |
+
test_unit_watch:
|
| 117 |
+
uv run ptw --now .
|
| 118 |
+
=== gbnf/GBNF.py
|
| 119 |
+
from .grammar_graph.graph import Graph
|
| 120 |
+
from .grammar_graph.parse_state import ParseState
|
| 121 |
+
from .grammar_parser.build_rule_stack import build_rule_stack
|
| 122 |
+
from .rules_builder import GrammarParseError, RulesBuilder
|
| 123 |
+
|
| 124 |
+
# ValidInput = str | int | float | list[int | float]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def GBNF(grammar: str, initial_string: str = ""):
|
| 128 |
+
if not isinstance(grammar, str):
|
| 129 |
+
raise ValueError("grammar must be a string")
|
| 130 |
+
|
| 131 |
+
if not isinstance(initial_string, str):
|
| 132 |
+
raise ValueError("input must be a string")
|
| 133 |
+
|
| 134 |
+
# const grammar = typeof input === 'string' ? input : input.toString();
|
| 135 |
+
|
| 136 |
+
rules_builder = RulesBuilder(grammar)
|
| 137 |
+
rules, symbol_ids = rules_builder.rules, rules_builder.symbol_ids
|
| 138 |
+
if len(rules) == 0:
|
| 139 |
+
raise GrammarParseError(grammar, 0, "No rules were found")
|
| 140 |
+
if symbol_ids["root"] is None:
|
| 141 |
+
raise GrammarParseError(grammar, 0, "Grammar does not contain a 'root' symbol")
|
| 142 |
+
root_id: int = symbol_ids["root"]
|
| 143 |
+
|
| 144 |
+
stacked_rules = [build_rule_stack(rule) for rule in rules]
|
| 145 |
+
graph = Graph(grammar, stacked_rules, root_id)
|
| 146 |
+
return ParseState(graph, graph.add(initial_string))
|
| 147 |
+
=== gbnf/__init__.py
|
| 148 |
+
from .GBNF import GBNF as GBNF
|
| 149 |
+
from .grammar_graph.grammar_graph_types import RuleChar, RuleCharExclude, RuleEnd
|
| 150 |
+
from .utils.errors import GrammarParseError, InputParseError
|
| 151 |
+
|
| 152 |
+
__all__ = [
|
| 153 |
+
"GBNF",
|
| 154 |
+
"GrammarParseError",
|
| 155 |
+
"InputParseError",
|
| 156 |
+
"RuleChar",
|
| 157 |
+
"RuleCharExclude",
|
| 158 |
+
"RuleEnd",
|
| 159 |
+
]
|
| 160 |
+
=== gbnf/rules_builder/rules_builder_types.py
|
| 161 |
+
from dataclasses import dataclass, field
|
| 162 |
+
from typing import Any
|
| 163 |
+
|
| 164 |
+
from ..utils.validate_non_empty import validate_non_empty
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@dataclass
|
| 168 |
+
class InternalRuleDefWithNumericValue:
|
| 169 |
+
value: int
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@dataclass
|
| 173 |
+
class InternalBase:
|
| 174 |
+
def __eq__(self, other):
|
| 175 |
+
return isinstance(other, self.__class__)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@dataclass
|
| 179 |
+
class InternalBaseWithValue:
|
| 180 |
+
value: Any
|
| 181 |
+
|
| 182 |
+
def __eq__(self, other):
|
| 183 |
+
return isinstance(other, self.__class__) and self.value == other.value
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@dataclass
|
| 187 |
+
class InternalBaseWithInt(InternalBaseWithValue):
|
| 188 |
+
value: int
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@dataclass
|
| 192 |
+
class InternalBaseWithListOfInts(InternalBaseWithValue):
|
| 193 |
+
value: list[int] = field(
|
| 194 |
+
default_factory=list, metadata={"validate": validate_non_empty},
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def __post_init__(self):
|
| 198 |
+
self.value = self.value.copy()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@dataclass
|
| 202 |
+
class InternalRuleDefChar(InternalBaseWithListOfInts):
|
| 203 |
+
pass
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@dataclass
|
| 207 |
+
class InternalRuleDefCharAlt(InternalBaseWithInt):
|
| 208 |
+
pass
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class InternalRuleDefAlt(InternalBase):
|
| 212 |
+
pass
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@dataclass
|
| 216 |
+
class InternalRuleDefCharNot(InternalBaseWithListOfInts):
|
| 217 |
+
pass
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@dataclass
|
| 221 |
+
class InternalRuleDefCharRngUpper(InternalBaseWithInt):
|
| 222 |
+
pass
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@dataclass
|
| 226 |
+
class InternalRuleDefReference(InternalBaseWithInt):
|
| 227 |
+
pass
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@dataclass
|
| 231 |
+
class InternalRuleDefEnd(InternalBase):
|
| 232 |
+
pass
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@dataclass
|
| 236 |
+
class InternalRuleDefWithoutValue(InternalBase):
|
| 237 |
+
pass
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
InternalRuleDef = (
|
| 241 |
+
InternalRuleDefChar
|
| 242 |
+
| InternalRuleDefEnd
|
| 243 |
+
| InternalRuleDefReference
|
| 244 |
+
| InternalRuleDefCharNot
|
| 245 |
+
| InternalRuleDefWithNumericValue
|
| 246 |
+
| InternalRuleDefWithoutValue
|
| 247 |
+
| InternalRuleDefAlt
|
| 248 |
+
| InternalRuleDefCharRngUpper
|
| 249 |
+
| InternalRuleDefCharAlt
|
| 250 |
+
| InternalRuleDefCharAlt
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
InternalRuleDefCharOrAltChar = InternalRuleDefChar | InternalRuleDefCharAlt
|
| 254 |
+
|
| 255 |
+
SymbolIds = dict[str, int]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def is_rule_def_alt(rule):
|
| 259 |
+
return isinstance(rule, InternalRuleDefAlt)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def is_rule_def_ref(rule):
|
| 263 |
+
return isinstance(rule, InternalRuleDefReference)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def is_rule_def_end(rule):
|
| 267 |
+
return isinstance(rule, InternalRuleDefEnd)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def is_rule_def_char(rule):
|
| 271 |
+
return isinstance(rule, InternalRuleDefChar)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def is_rule_def_char_not(rule):
|
| 275 |
+
return isinstance(rule, InternalRuleDefCharNot)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def is_rule_def_char_alt(rule):
|
| 279 |
+
return isinstance(rule, InternalRuleDefCharAlt)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def is_rule_def_char_rng_upper(rule):
|
| 283 |
+
return isinstance(rule, InternalRuleDefCharRngUpper)
|
| 284 |
+
=== gbnf/rules_builder/parse_space.py
|
| 285 |
+
def parse_space(src: str, pos: int, newline_ok: bool) -> int:
|
| 286 |
+
while pos < len(src) and (
|
| 287 |
+
src[pos] == " "
|
| 288 |
+
or src[pos] == "\t"
|
| 289 |
+
or src[pos] == "#"
|
| 290 |
+
or (newline_ok and (src[pos] == "\r" or src[pos] == "\n"))
|
| 291 |
+
):
|
| 292 |
+
if src[pos] == "#":
|
| 293 |
+
while pos < len(src) and src[pos] not in ("\r", "\n"):
|
| 294 |
+
pos += 1
|
| 295 |
+
else:
|
| 296 |
+
pos += 1
|
| 297 |
+
return pos
|
| 298 |
+
=== gbnf/rules_builder/parse_char.py
|
| 299 |
+
from ..utils.errors import GrammarParseError
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def parse_char(src: str, pos: int):
|
| 303 |
+
if pos >= len(src):
|
| 304 |
+
raise GrammarParseError(
|
| 305 |
+
src,
|
| 306 |
+
pos,
|
| 307 |
+
"Unexpected end of grammar input, failed to complete parse",
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
if src[pos] == "\\":
|
| 311 |
+
if src[pos + 1] == "x":
|
| 312 |
+
return (int(src[pos + 2 : pos + 4], 16), 4)
|
| 313 |
+
if src[pos + 1] == "u":
|
| 314 |
+
return (int(src[pos + 2 : pos + 6], 16), 6)
|
| 315 |
+
if src[pos + 1] == "U":
|
| 316 |
+
return (int(src[pos + 2 : pos + 10], 16), 10)
|
| 317 |
+
if src[pos + 1] in ["t", "r", "n"]:
|
| 318 |
+
return (ord(eval(f"'\\{src[pos + 1]}'")), 2)
|
| 319 |
+
if src[pos + 1] in ['"', "[", "]", "\\"]:
|
| 320 |
+
return (ord(src[pos + 1]), 2)
|
| 321 |
+
raise GrammarParseError(src, pos, f"Unknown escape at {src[pos]}")
|
| 322 |
+
|
| 323 |
+
return (ord(src[pos]), 1)
|
| 324 |
+
=== gbnf/rules_builder/parse_name.py
|
| 325 |
+
from ..utils.errors import GrammarParseError
|
| 326 |
+
from .is_word_char import is_word_char
|
| 327 |
+
|
| 328 |
+
PARSE_NAME_ERROR = "Failed to find a valid name"
|
| 329 |
+
|
| 330 |
+
VALID_NAME_SEPARATORS = [
|
| 331 |
+
"-",
|
| 332 |
+
"_",
|
| 333 |
+
]
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def parse_name(grammar: str, pos: int) -> str:
|
| 337 |
+
name = ""
|
| 338 |
+
while pos < len(grammar) and (
|
| 339 |
+
is_word_char(grammar[pos]) or grammar[pos] in VALID_NAME_SEPARATORS
|
| 340 |
+
):
|
| 341 |
+
name += grammar[pos]
|
| 342 |
+
pos += 1
|
| 343 |
+
if not name:
|
| 344 |
+
raise GrammarParseError(grammar, pos, PARSE_NAME_ERROR)
|
| 345 |
+
return name
|
| 346 |
+
=== gbnf/rules_builder/is_word_char.py
|
| 347 |
+
import re
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def is_word_char(c: str) -> bool:
|
| 351 |
+
return re.search(r"[a-zA-Z]", c) is not None
|
| 352 |
+
=== gbnf/rules_builder/__init__.py
|
| 353 |
+
from ..utils.errors import GrammarParseError, InputParseError
|
| 354 |
+
from .rules_builder import RulesBuilder
|
| 355 |
+
|
| 356 |
+
__all__ = [
|
| 357 |
+
"GrammarParseError",
|
| 358 |
+
"InputParseError",
|
| 359 |
+
"RulesBuilder",
|
| 360 |
+
]
|
| 361 |
+
=== gbnf/rules_builder/symbol_ids.py
|
| 362 |
+
class SymbolIds:
|
| 363 |
+
__map__: dict[str, int]
|
| 364 |
+
__pos__: dict[str, int]
|
| 365 |
+
__reverse_map__: dict[int, str]
|
| 366 |
+
|
| 367 |
+
def __init__(self):
|
| 368 |
+
self.__map__ = {}
|
| 369 |
+
self.__pos__ = {}
|
| 370 |
+
self.__reverse_map__ = {}
|
| 371 |
+
|
| 372 |
+
def items(self):
|
| 373 |
+
return self.__map__.items()
|
| 374 |
+
|
| 375 |
+
def __iter__(self):
|
| 376 |
+
return iter(self.__map__.items())
|
| 377 |
+
|
| 378 |
+
def __len__(self):
|
| 379 |
+
return len(self.__map__)
|
| 380 |
+
|
| 381 |
+
def __getitem__(self, key):
|
| 382 |
+
return self.__map__[key]
|
| 383 |
+
|
| 384 |
+
def set(self, key: str, value: int, pos: int):
|
| 385 |
+
self.__map__[key] = value
|
| 386 |
+
self.__reverse_map__[value] = key
|
| 387 |
+
self.__pos__[key] = pos
|
| 388 |
+
|
| 389 |
+
def __contains__(self, key: str):
|
| 390 |
+
return key in self.__map__
|
| 391 |
+
|
| 392 |
+
def reverse_get(self, key: int):
|
| 393 |
+
val = self.__reverse_map__.get(key)
|
| 394 |
+
if val is None:
|
| 395 |
+
raise ValueError(f"SymbolIds does not contain value: {key}")
|
| 396 |
+
return val
|
| 397 |
+
|
| 398 |
+
def get_pos(self, key: str):
|
| 399 |
+
val = self.__pos__.get(key)
|
| 400 |
+
if val is None:
|
| 401 |
+
raise ValueError(f"SymbolIds does not contain key: {key}")
|
| 402 |
+
return val
|
| 403 |
+
=== gbnf/rules_builder/rules_builder.py
|
| 404 |
+
from time import perf_counter
|
| 405 |
+
|
| 406 |
+
from ..utils.errors import GrammarParseError
|
| 407 |
+
from .is_word_char import is_word_char
|
| 408 |
+
from .parse_char import parse_char
|
| 409 |
+
from .parse_name import parse_name
|
| 410 |
+
from .parse_space import parse_space
|
| 411 |
+
from .rules_builder_types import (
|
| 412 |
+
InternalRuleDef,
|
| 413 |
+
InternalRuleDefAlt,
|
| 414 |
+
InternalRuleDefChar,
|
| 415 |
+
InternalRuleDefCharAlt,
|
| 416 |
+
InternalRuleDefCharNot,
|
| 417 |
+
InternalRuleDefCharRngUpper,
|
| 418 |
+
InternalRuleDefEnd,
|
| 419 |
+
InternalRuleDefReference,
|
| 420 |
+
)
|
| 421 |
+
from .symbol_ids import SymbolIds
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def get_out_elements(
|
| 425 |
+
type_of_rule: type[InternalRuleDef],
|
| 426 |
+
startchar_value: int,
|
| 427 |
+
) -> InternalRuleDef:
|
| 428 |
+
if type_of_rule == InternalRuleDefChar:
|
| 429 |
+
return InternalRuleDefChar(value=[startchar_value])
|
| 430 |
+
if type_of_rule == InternalRuleDefCharNot:
|
| 431 |
+
return InternalRuleDefCharNot(value=[startchar_value])
|
| 432 |
+
if type_of_rule == InternalRuleDefCharRngUpper:
|
| 433 |
+
return InternalRuleDefCharRngUpper(value=startchar_value)
|
| 434 |
+
if type_of_rule == InternalRuleDefAlt:
|
| 435 |
+
return InternalRuleDefAlt()
|
| 436 |
+
if type_of_rule == InternalRuleDefEnd:
|
| 437 |
+
return InternalRuleDefEnd()
|
| 438 |
+
if type_of_rule == InternalRuleDefCharAlt:
|
| 439 |
+
return InternalRuleDefCharAlt(value=startchar_value)
|
| 440 |
+
|
| 441 |
+
raise ValueError(f"Invalid type: {type_of_rule}")
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
class RulesBuilder:
|
| 445 |
+
pos: int
|
| 446 |
+
symbol_ids: SymbolIds
|
| 447 |
+
rules: list[list[InternalRuleDef]]
|
| 448 |
+
src: str
|
| 449 |
+
start: float
|
| 450 |
+
time_limit: int
|
| 451 |
+
|
| 452 |
+
def __init__(self, src: str, limit: int = 1000):
|
| 453 |
+
self.pos = 0
|
| 454 |
+
self.symbol_ids = SymbolIds()
|
| 455 |
+
self.rules = []
|
| 456 |
+
self.src = src
|
| 457 |
+
self.start = perf_counter()
|
| 458 |
+
self.time_limit = limit
|
| 459 |
+
self.parse(src)
|
| 460 |
+
|
| 461 |
+
def parse(self, src: str) -> None:
|
| 462 |
+
self.pos = parse_space(src, 0, True)
|
| 463 |
+
while self.pos < len(src):
|
| 464 |
+
self.parse_rule(src)
|
| 465 |
+
|
| 466 |
+
# Validate the state to ensure that all rules are defined
|
| 467 |
+
for rule in self.rules:
|
| 468 |
+
for elem in rule:
|
| 469 |
+
if isinstance(elem, InternalRuleDefReference):
|
| 470 |
+
rule_exists = (
|
| 471 |
+
elem.value < len(self.rules) and len(self.rules[elem.value]) > 0
|
| 472 |
+
)
|
| 473 |
+
if not rule_exists:
|
| 474 |
+
missing_rule_name = self.symbol_ids.reverse_get(elem.value)
|
| 475 |
+
missing_rule_pos = self.symbol_ids.get_pos(missing_rule_name)
|
| 476 |
+
|
| 477 |
+
# Skip over the ::= and any whitespace
|
| 478 |
+
while missing_rule_pos < len(src) and (
|
| 479 |
+
src[missing_rule_pos] == ":"
|
| 480 |
+
or src[missing_rule_pos] == "="
|
| 481 |
+
or src[missing_rule_pos].isspace()
|
| 482 |
+
):
|
| 483 |
+
missing_rule_pos += 1
|
| 484 |
+
|
| 485 |
+
raise GrammarParseError(
|
| 486 |
+
src,
|
| 487 |
+
missing_rule_pos,
|
| 488 |
+
f'Undefined rule identifier "{missing_rule_name}"',
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
def parse_rule(self, src: str) -> None:
|
| 492 |
+
name = parse_name(src, self.pos)
|
| 493 |
+
self.pos = parse_space(src, self.pos + len(name), False)
|
| 494 |
+
rule_id = self.get_symbol_id(name, len(name))
|
| 495 |
+
|
| 496 |
+
self.pos = parse_space(src, self.pos, True)
|
| 497 |
+
if not (
|
| 498 |
+
self.pos + 2 < len(src) # Ensure the position + 2 is within bounds
|
| 499 |
+
and src[self.pos] == ":"
|
| 500 |
+
and src[self.pos + 1] == ":"
|
| 501 |
+
and src[self.pos + 2] == "="
|
| 502 |
+
):
|
| 503 |
+
raise GrammarParseError(src, self.pos, f"Expecting ::= at {self.pos}")
|
| 504 |
+
self.pos += 3
|
| 505 |
+
self.pos = parse_space(src, self.pos, True)
|
| 506 |
+
|
| 507 |
+
self.parse_alternates(name, rule_id)
|
| 508 |
+
|
| 509 |
+
# Check if self.pos is within the bounds of src before checking for a carriage return
|
| 510 |
+
if self.pos < len(src) and src[self.pos] == "\r":
|
| 511 |
+
self.pos += 2 if src[self.pos + 1] == "\n" else 1
|
| 512 |
+
elif self.pos < len(src) and src[self.pos] == "\n":
|
| 513 |
+
self.pos += 1
|
| 514 |
+
elif self.pos < len(src) and src[self.pos]:
|
| 515 |
+
raise GrammarParseError(
|
| 516 |
+
src,
|
| 517 |
+
self.pos,
|
| 518 |
+
f"Expecting newline or end at {self.pos}",
|
| 519 |
+
)
|
| 520 |
+
self.pos = parse_space(src, self.pos, True)
|
| 521 |
+
|
| 522 |
+
def get_symbol_id(self, src: str, length: int) -> int:
|
| 523 |
+
next_id = len(self.symbol_ids)
|
| 524 |
+
key = src[:length]
|
| 525 |
+
if key not in self.symbol_ids:
|
| 526 |
+
self.symbol_ids.set(key, next_id, self.pos)
|
| 527 |
+
return self.symbol_ids[key]
|
| 528 |
+
|
| 529 |
+
def generate_symbol_id(self, base_name: str) -> int:
|
| 530 |
+
next_id = len(self.symbol_ids)
|
| 531 |
+
self.symbol_ids.set(f"{base_name}_{next_id}", next_id, self.pos)
|
| 532 |
+
return next_id
|
| 533 |
+
|
| 534 |
+
def add_rule(self, rule_id: int, rule: list[InternalRuleDef]) -> None:
|
| 535 |
+
while len(self.rules) <= rule_id:
|
| 536 |
+
self.rules.append([])
|
| 537 |
+
self.rules[rule_id] = rule
|
| 538 |
+
|
| 539 |
+
def check_duration(self) -> None:
|
| 540 |
+
if perf_counter() - self.start > self.time_limit:
|
| 541 |
+
raise GrammarParseError(
|
| 542 |
+
self.src,
|
| 543 |
+
self.pos,
|
| 544 |
+
f"Duration of {self.time_limit} exceeded",
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
def parse_sequence(
|
| 548 |
+
self,
|
| 549 |
+
rule_name: str,
|
| 550 |
+
out_elements: list[InternalRuleDef],
|
| 551 |
+
depth: int = 0,
|
| 552 |
+
) -> None:
|
| 553 |
+
is_nested = depth != 0
|
| 554 |
+
src = self.src
|
| 555 |
+
last_sym_start = len(out_elements)
|
| 556 |
+
|
| 557 |
+
while self.pos < len(src):
|
| 558 |
+
if src[self.pos] == '"':
|
| 559 |
+
self.pos += 1
|
| 560 |
+
last_sym_start = len(out_elements)
|
| 561 |
+
while src[self.pos] != '"':
|
| 562 |
+
self.check_duration()
|
| 563 |
+
value, inc_pos = parse_char(src, self.pos)
|
| 564 |
+
out_elements.append(
|
| 565 |
+
InternalRuleDefChar(
|
| 566 |
+
value=[value],
|
| 567 |
+
),
|
| 568 |
+
)
|
| 569 |
+
self.pos += inc_pos
|
| 570 |
+
self.pos = parse_space(src, self.pos + 1, is_nested)
|
| 571 |
+
elif src[self.pos] == "[":
|
| 572 |
+
self.pos += 1
|
| 573 |
+
start_type: type[InternalRuleDef] = InternalRuleDefChar
|
| 574 |
+
if src[self.pos] == "^":
|
| 575 |
+
self.pos += 1
|
| 576 |
+
start_type = InternalRuleDefCharNot
|
| 577 |
+
last_sym_start = len(out_elements)
|
| 578 |
+
while src[self.pos] != "]":
|
| 579 |
+
self.check_duration()
|
| 580 |
+
type_: type[InternalRuleDef] = (
|
| 581 |
+
InternalRuleDefCharAlt
|
| 582 |
+
if last_sym_start < len(out_elements)
|
| 583 |
+
else start_type
|
| 584 |
+
)
|
| 585 |
+
startchar_value, inc_pos = parse_char(src, self.pos)
|
| 586 |
+
self.pos += inc_pos
|
| 587 |
+
out_elements.append(get_out_elements(type_, startchar_value))
|
| 588 |
+
|
| 589 |
+
if src[self.pos] == "-" and src[self.pos + 1] != "]":
|
| 590 |
+
self.pos += 1
|
| 591 |
+
endchar_value, inc_pos = parse_char(src, self.pos)
|
| 592 |
+
out_elements.append(
|
| 593 |
+
InternalRuleDefCharRngUpper(
|
| 594 |
+
value=endchar_value,
|
| 595 |
+
),
|
| 596 |
+
)
|
| 597 |
+
self.pos += inc_pos
|
| 598 |
+
self.pos = parse_space(src, self.pos + 1, is_nested)
|
| 599 |
+
elif is_word_char(src[self.pos]):
|
| 600 |
+
name = parse_name(src, self.pos)
|
| 601 |
+
ref_rule_id = self.get_symbol_id(name, len(name))
|
| 602 |
+
self.pos += len(name)
|
| 603 |
+
self.pos = parse_space(src, self.pos, is_nested)
|
| 604 |
+
|
| 605 |
+
last_sym_start = len(out_elements)
|
| 606 |
+
out_elements.append(
|
| 607 |
+
InternalRuleDefReference(
|
| 608 |
+
value=ref_rule_id,
|
| 609 |
+
),
|
| 610 |
+
)
|
| 611 |
+
elif src[self.pos] == "(":
|
| 612 |
+
self.pos = parse_space(src, self.pos + 1, True)
|
| 613 |
+
sub_rule_id = self.generate_symbol_id(rule_name)
|
| 614 |
+
self.parse_alternates(rule_name, sub_rule_id, depth + 1)
|
| 615 |
+
last_sym_start = len(out_elements)
|
| 616 |
+
out_elements.append(
|
| 617 |
+
InternalRuleDefReference(
|
| 618 |
+
value=sub_rule_id,
|
| 619 |
+
),
|
| 620 |
+
)
|
| 621 |
+
if src[self.pos] != ")":
|
| 622 |
+
raise GrammarParseError(
|
| 623 |
+
src,
|
| 624 |
+
self.pos,
|
| 625 |
+
f"Expecting ')' at {self.pos}",
|
| 626 |
+
)
|
| 627 |
+
self.pos = parse_space(src, self.pos + 1, is_nested)
|
| 628 |
+
elif src[self.pos] in "*+?":
|
| 629 |
+
if last_sym_start == len(out_elements):
|
| 630 |
+
raise GrammarParseError(
|
| 631 |
+
src,
|
| 632 |
+
self.pos,
|
| 633 |
+
f"Expecting preceding item to */+/? at {self.pos}",
|
| 634 |
+
)
|
| 635 |
+
sub_rule_id = self.generate_symbol_id(rule_name)
|
| 636 |
+
sub_rule = out_elements[last_sym_start:]
|
| 637 |
+
if src[self.pos] in "*+":
|
| 638 |
+
sub_rule.append(
|
| 639 |
+
InternalRuleDefReference(
|
| 640 |
+
value=sub_rule_id,
|
| 641 |
+
),
|
| 642 |
+
)
|
| 643 |
+
sub_rule.append(InternalRuleDefAlt())
|
| 644 |
+
if src[self.pos] == "+":
|
| 645 |
+
sub_rule.extend(out_elements[last_sym_start:])
|
| 646 |
+
sub_rule.append(InternalRuleDefEnd())
|
| 647 |
+
self.add_rule(sub_rule_id, sub_rule)
|
| 648 |
+
out_elements[last_sym_start:] = [
|
| 649 |
+
InternalRuleDefReference(
|
| 650 |
+
value=sub_rule_id,
|
| 651 |
+
),
|
| 652 |
+
]
|
| 653 |
+
self.pos = parse_space(src, self.pos + 1, is_nested)
|
| 654 |
+
else:
|
| 655 |
+
break
|
| 656 |
+
|
| 657 |
+
def parse_alternates(self, rule_name: str, rule_id: int, depth: int = 0) -> None:
|
| 658 |
+
src = self.src
|
| 659 |
+
rule = []
|
| 660 |
+
self.parse_sequence(rule_name, rule, depth)
|
| 661 |
+
# Ensure that self.pos is within bounds before checking src[self.pos]
|
| 662 |
+
while self.pos < len(src) and src[self.pos] == "|":
|
| 663 |
+
self.check_duration()
|
| 664 |
+
rule.append(InternalRuleDefAlt())
|
| 665 |
+
self.pos = parse_space(src, self.pos + 1, True)
|
| 666 |
+
self.parse_sequence(rule_name, rule, depth)
|
| 667 |
+
rule.append(InternalRuleDefEnd())
|
| 668 |
+
self.add_rule(rule_id, rule)
|
| 669 |
+
=== gbnf/grammar_graph/parse_state.py
|
| 670 |
+
from __future__ import annotations
|
| 671 |
+
|
| 672 |
+
from collections.abc import Iterable
|
| 673 |
+
from typing import TYPE_CHECKING
|
| 674 |
+
|
| 675 |
+
from .grammar_graph_types import Rule
|
| 676 |
+
from .pointers import Pointers
|
| 677 |
+
|
| 678 |
+
if TYPE_CHECKING:
|
| 679 |
+
from .grammar_graph_types import ResolvedRule
|
| 680 |
+
from .graph import Graph
|
| 681 |
+
|
| 682 |
+
import json
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class CustomJSONEncoder(json.JSONEncoder):
|
| 686 |
+
def default(self, o):
|
| 687 |
+
if isinstance(o, Rule):
|
| 688 |
+
return o
|
| 689 |
+
return super().default(o)
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
class ParseState:
|
| 693 |
+
__graph__: Graph
|
| 694 |
+
__pointers__: Pointers
|
| 695 |
+
|
| 696 |
+
def __init__(self, graph: Graph, pointers: Pointers):
|
| 697 |
+
self.__graph__ = graph
|
| 698 |
+
self.__pointers__ = pointers
|
| 699 |
+
|
| 700 |
+
def __call__(self, text: str) -> ParseState:
|
| 701 |
+
return self.add(text)
|
| 702 |
+
|
| 703 |
+
def __iter__(self) -> Iterable[ResolvedRule]:
|
| 704 |
+
yield from self.rules()
|
| 705 |
+
|
| 706 |
+
def rules(self) -> Iterable[ResolvedRule]:
|
| 707 |
+
rules = set()
|
| 708 |
+
for pointer in self.__pointers__:
|
| 709 |
+
rule = pointer.rule
|
| 710 |
+
key = json.dumps(rule.__dict__, cls=CustomJSONEncoder)
|
| 711 |
+
if key not in rules:
|
| 712 |
+
rules.add(key)
|
| 713 |
+
yield rule
|
| 714 |
+
|
| 715 |
+
def add(self, text: str) -> ParseState:
|
| 716 |
+
if not isinstance(text, str):
|
| 717 |
+
raise ValueError("input text must be of type string")
|
| 718 |
+
pointers = self.__graph__.add(text, self.__pointers__)
|
| 719 |
+
return ParseState(self.__graph__, pointers)
|
| 720 |
+
|
| 721 |
+
def __add__(self, text: str) -> ParseState:
|
| 722 |
+
return self.add(text)
|
| 723 |
+
|
| 724 |
+
@property
|
| 725 |
+
def size(self) -> int:
|
| 726 |
+
return len(list(self.rules()))
|
| 727 |
+
|
| 728 |
+
@property
|
| 729 |
+
def grammar(self) -> str:
|
| 730 |
+
return self.__graph__.grammar
|
| 731 |
+
=== gbnf/grammar_graph/graph.py
|
| 732 |
+
from __future__ import annotations
|
| 733 |
+
|
| 734 |
+
from collections.abc import Iterable
|
| 735 |
+
from typing import TYPE_CHECKING
|
| 736 |
+
|
| 737 |
+
from .pointers import Pointers
|
| 738 |
+
|
| 739 |
+
if TYPE_CHECKING:
|
| 740 |
+
from .grammar_graph_types import (
|
| 741 |
+
ResolvedGraphPointer,
|
| 742 |
+
UnresolvedRule,
|
| 743 |
+
ValidInput,
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
from collections import OrderedDict
|
| 748 |
+
|
| 749 |
+
from ..utils.errors import InputParseError
|
| 750 |
+
from ..utils.is_point_in_range import is_point_in_range
|
| 751 |
+
from .colorize import colorize
|
| 752 |
+
from .get_input_as_code_points import get_input_as_code_points
|
| 753 |
+
from .get_serialized_rule_key import get_serialized_rule_key
|
| 754 |
+
from .graph_node import GraphNode
|
| 755 |
+
from .graph_pointer import GraphPointer
|
| 756 |
+
from .rule_ref import RuleRef
|
| 757 |
+
from .type_guards import (
|
| 758 |
+
is_range,
|
| 759 |
+
is_rule_char,
|
| 760 |
+
is_rule_char_exclude,
|
| 761 |
+
is_rule_end,
|
| 762 |
+
is_rule_ref,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
RootNode = dict[int, GraphNode]
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
class Graph:
|
| 769 |
+
__roots__: OrderedDict[int, RootNode]
|
| 770 |
+
grammar: str
|
| 771 |
+
__rootNode__: RootNode | None
|
| 772 |
+
previous_code_points: list[int]
|
| 773 |
+
|
| 774 |
+
def __init__(
|
| 775 |
+
self,
|
| 776 |
+
grammar: str,
|
| 777 |
+
stacked_rules: list[list[list[UnresolvedRule]]],
|
| 778 |
+
root_id: int,
|
| 779 |
+
):
|
| 780 |
+
self.__roots__ = OrderedDict()
|
| 781 |
+
self.grammar = grammar
|
| 782 |
+
self.previous_code_points = []
|
| 783 |
+
rule_refs: list[RuleRef] = []
|
| 784 |
+
unique_rules: dict[str, UnresolvedRule] = {}
|
| 785 |
+
|
| 786 |
+
for stack_id in range(len(stacked_rules)):
|
| 787 |
+
stack = stacked_rules[stack_id]
|
| 788 |
+
nodes: dict[int, GraphNode] = {}
|
| 789 |
+
for path_id in range(len(stack)):
|
| 790 |
+
path = stack[path_id]
|
| 791 |
+
node: GraphNode | None = None
|
| 792 |
+
for step_id in range(len(path) - 1, -1, -1):
|
| 793 |
+
next_node: GraphNode | None = node
|
| 794 |
+
rule = stack[path_id][step_id]
|
| 795 |
+
unique_rules[get_serialized_rule_key(rule)] = rule
|
| 796 |
+
if is_rule_ref(rule):
|
| 797 |
+
rule_refs.append(rule)
|
| 798 |
+
# rules coming in may be identical but have different references.
|
| 799 |
+
# here, we ensure we always use the same reference for an identical rule.
|
| 800 |
+
# this makes future comparisons easier.
|
| 801 |
+
unique_rule = unique_rules.get(get_serialized_rule_key(rule))
|
| 802 |
+
if unique_rule is None:
|
| 803 |
+
raise ValueError("Could not get unique rule")
|
| 804 |
+
node = GraphNode(
|
| 805 |
+
unique_rule,
|
| 806 |
+
{
|
| 807 |
+
"stackId": stack_id,
|
| 808 |
+
"pathId": path_id,
|
| 809 |
+
"stepId": step_id,
|
| 810 |
+
},
|
| 811 |
+
next_node,
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
if node is None:
|
| 815 |
+
raise ValueError("Could not get node")
|
| 816 |
+
nodes[path_id] = node
|
| 817 |
+
self.__roots__[stack_id] = nodes
|
| 818 |
+
|
| 819 |
+
root_node = self.__roots__.get(root_id)
|
| 820 |
+
if root_node is None:
|
| 821 |
+
raise ValueError(f"Root node not found for value: {root_id}")
|
| 822 |
+
self.__rootNode__ = root_node
|
| 823 |
+
|
| 824 |
+
for rule_ref in rule_refs:
|
| 825 |
+
referenced_nodes = set()
|
| 826 |
+
referenced_nodes.update(self.__get_root_node__(rule_ref.value).values())
|
| 827 |
+
rule_ref.nodes = referenced_nodes
|
| 828 |
+
|
| 829 |
+
def __get_root_node__(self, value: int) -> RootNode:
|
| 830 |
+
root_node = self.__roots__.get(value)
|
| 831 |
+
if root_node is None:
|
| 832 |
+
raise ValueError(f"Root node not found for value: {value}")
|
| 833 |
+
return root_node
|
| 834 |
+
|
| 835 |
+
def __get_initial_pointers__(self) -> Pointers:
|
| 836 |
+
pointers = Pointers()
|
| 837 |
+
|
| 838 |
+
root_node = self.__rootNode__
|
| 839 |
+
if root_node is None:
|
| 840 |
+
raise ValueError("Root node is not defined")
|
| 841 |
+
|
| 842 |
+
for node, parent in self.__fetch_nodes_for_root_node__(root_node):
|
| 843 |
+
pointer = GraphPointer(node, parent)
|
| 844 |
+
for resolvedPointer in self.__resolve_pointer__(pointer):
|
| 845 |
+
pointers.add(resolvedPointer)
|
| 846 |
+
return pointers
|
| 847 |
+
|
| 848 |
+
def __set_valid__(self, pointers: list[GraphPointer], valid: bool):
|
| 849 |
+
for pointer in pointers:
|
| 850 |
+
pointer.valid = valid
|
| 851 |
+
|
| 852 |
+
def __parse__(self, current_pointers: Pointers, code_point: int) -> Pointers:
|
| 853 |
+
for rule, graph_pointers in self.__iterate_over_pointers__(current_pointers):
|
| 854 |
+
if is_rule_char(rule):
|
| 855 |
+
valid = False
|
| 856 |
+
for possible_code_point in rule.value:
|
| 857 |
+
if valid is True:
|
| 858 |
+
pass
|
| 859 |
+
elif is_range(possible_code_point):
|
| 860 |
+
if is_point_in_range(code_point, possible_code_point):
|
| 861 |
+
valid = True
|
| 862 |
+
elif code_point == possible_code_point:
|
| 863 |
+
valid = True
|
| 864 |
+
self.__set_valid__(graph_pointers, valid)
|
| 865 |
+
|
| 866 |
+
elif is_rule_char_exclude(rule):
|
| 867 |
+
valid = True
|
| 868 |
+
for possible_code_point in rule.value:
|
| 869 |
+
if valid is False:
|
| 870 |
+
pass
|
| 871 |
+
elif is_range(possible_code_point):
|
| 872 |
+
if is_point_in_range(code_point, possible_code_point):
|
| 873 |
+
valid = False
|
| 874 |
+
else:
|
| 875 |
+
if code_point == possible_code_point:
|
| 876 |
+
valid = False
|
| 877 |
+
self.__set_valid__(graph_pointers, valid)
|
| 878 |
+
|
| 879 |
+
elif not is_rule_end(rule):
|
| 880 |
+
raise ValueError(f"Unsupported rule: {rule}")
|
| 881 |
+
|
| 882 |
+
# a pointer's id is the sum of its node's id and its parent's id chain.
|
| 883 |
+
# if two pointers share the same id, it means they point to the same node and have identical parent chains.
|
| 884 |
+
# for the purposes of walking the graph, we only need to keep one of them.
|
| 885 |
+
next_pointers = Pointers()
|
| 886 |
+
for current_pointer in current_pointers:
|
| 887 |
+
for unresolved_next_pointer in current_pointer.fetch_next():
|
| 888 |
+
for resolved_next_pointer in self.__resolve_pointer__(
|
| 889 |
+
unresolved_next_pointer,
|
| 890 |
+
):
|
| 891 |
+
next_pointers.add(resolved_next_pointer)
|
| 892 |
+
return next_pointers
|
| 893 |
+
|
| 894 |
+
def __resolve_pointer__(
|
| 895 |
+
self,
|
| 896 |
+
unresolved_pointer: GraphPointer,
|
| 897 |
+
) -> Iterable[ResolvedGraphPointer]:
|
| 898 |
+
for resolved_pointer in unresolved_pointer.resolve():
|
| 899 |
+
if is_rule_ref(resolved_pointer.node.rule):
|
| 900 |
+
raise ValueError(
|
| 901 |
+
"Encountered a reference rule when building pointers to the graph",
|
| 902 |
+
)
|
| 903 |
+
if (
|
| 904 |
+
is_rule_end(resolved_pointer.node.rule)
|
| 905 |
+
and resolved_pointer.parent is not None
|
| 906 |
+
):
|
| 907 |
+
raise ValueError(
|
| 908 |
+
"Encountered an ending rule with a parent when building pointers to the graph",
|
| 909 |
+
)
|
| 910 |
+
yield resolved_pointer
|
| 911 |
+
|
| 912 |
+
def add(self, src: ValidInput, pointers: Pointers | None = None) -> Pointers:
|
| 913 |
+
if not isinstance(src, str):
|
| 914 |
+
raise ValueError("src must be a string in graph.add")
|
| 915 |
+
pointers = pointers or self.__get_initial_pointers__()
|
| 916 |
+
|
| 917 |
+
code_points = get_input_as_code_points(src)
|
| 918 |
+
for code_point in code_points:
|
| 919 |
+
if type(code_point) is not int:
|
| 920 |
+
raise ValueError("code_point must be an integer!")
|
| 921 |
+
|
| 922 |
+
for code_point_pos in range(len(code_points)):
|
| 923 |
+
code_point = code_points[code_point_pos]
|
| 924 |
+
pointers = self.__parse__(pointers, code_point)
|
| 925 |
+
if len(pointers) == 0:
|
| 926 |
+
raise InputParseError(
|
| 927 |
+
code_points,
|
| 928 |
+
code_point_pos,
|
| 929 |
+
self.previous_code_points,
|
| 930 |
+
)
|
| 931 |
+
self.previous_code_points.extend(code_points)
|
| 932 |
+
return pointers
|
| 933 |
+
|
| 934 |
+
# generator that yields either the node, or if a reference rule, the referenced node
|
| 935 |
+
# we need these function, as distinct from leveraging the logic in GraphPointer,
|
| 936 |
+
# because that needs a rule ref with already defined nodes; this function is used to _set_ those nodes
|
| 937 |
+
def __fetch_nodes_for_root_node__(
|
| 938 |
+
self,
|
| 939 |
+
root_nodes: dict[int, GraphNode],
|
| 940 |
+
parent: GraphPointer | None = None,
|
| 941 |
+
) -> Iterable[tuple[GraphNode, GraphPointer | None]]:
|
| 942 |
+
for node in root_nodes.values():
|
| 943 |
+
if is_rule_ref(node.rule):
|
| 944 |
+
yield from self.__fetch_nodes_for_root_node__(
|
| 945 |
+
self.__get_root_node__(node.rule.value),
|
| 946 |
+
GraphPointer(node, parent),
|
| 947 |
+
)
|
| 948 |
+
else:
|
| 949 |
+
yield node, parent
|
| 950 |
+
|
| 951 |
+
def print(self, pointers: Pointers | None = None, colors: bool = False) -> str:
|
| 952 |
+
nodes: list[list[GraphNode]] = [
|
| 953 |
+
list(root_node.values()) for root_node in self.__roots__.values()
|
| 954 |
+
]
|
| 955 |
+
if pointers is None:
|
| 956 |
+
pointers = Pointers()
|
| 957 |
+
graph_view: list[str] = []
|
| 958 |
+
for root_node in nodes:
|
| 959 |
+
for node in root_node:
|
| 960 |
+
graph_view.extend(
|
| 961 |
+
[
|
| 962 |
+
node.print(
|
| 963 |
+
{
|
| 964 |
+
"pointers": pointers,
|
| 965 |
+
"show_position": True,
|
| 966 |
+
"colorize": colorize if colors else lambda s, _: str(s),
|
| 967 |
+
},
|
| 968 |
+
),
|
| 969 |
+
],
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
return "\n".join(graph_view)
|
| 973 |
+
|
| 974 |
+
def __iterate_over_pointers__(
|
| 975 |
+
self,
|
| 976 |
+
pointers: Pointers,
|
| 977 |
+
) -> Iterable[tuple[UnresolvedRule, list[GraphPointer]]]:
|
| 978 |
+
seen_rules: OrderedDict[UnresolvedRule, list[GraphPointer]] = OrderedDict()
|
| 979 |
+
for pointer in pointers:
|
| 980 |
+
rule = pointer.rule
|
| 981 |
+
if is_rule_ref(rule):
|
| 982 |
+
raise ValueError("Encountered a reference rule in the graph")
|
| 983 |
+
|
| 984 |
+
seen_rule = seen_rules.get(rule)
|
| 985 |
+
if seen_rule is None:
|
| 986 |
+
seen_rule = [pointer]
|
| 987 |
+
seen_rules[rule] = seen_rule
|
| 988 |
+
seen_rule.append(pointer)
|
| 989 |
+
|
| 990 |
+
yield from seen_rules.items()
|
| 991 |
+
=== gbnf/grammar_graph/get_input_as_code_points.py
|
| 992 |
+
from .grammar_graph_types import ValidInput
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def get_code_point(char: str) -> int:
|
| 996 |
+
code_point = ord(char)
|
| 997 |
+
if code_point is None:
|
| 998 |
+
raise ValueError(f"Could not get code point for character: {char}")
|
| 999 |
+
if type(code_point) is not int:
|
| 1000 |
+
raise ValueError("code_point must be an integer!")
|
| 1001 |
+
return code_point
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
def get_input_as_code_points(src: ValidInput) -> list[int]:
|
| 1005 |
+
if isinstance(src, int):
|
| 1006 |
+
return [src]
|
| 1007 |
+
|
| 1008 |
+
if isinstance(src, list):
|
| 1009 |
+
for c in src:
|
| 1010 |
+
if type(c) is not int:
|
| 1011 |
+
raise ValueError(
|
| 1012 |
+
f"code_point must be an integer for {c} if src is a list",
|
| 1013 |
+
)
|
| 1014 |
+
return src
|
| 1015 |
+
|
| 1016 |
+
if isinstance(src, str):
|
| 1017 |
+
return [get_code_point(s) for s in src]
|
| 1018 |
+
|
| 1019 |
+
raise ValueError(f"Invalid input type: {type(src)}")
|
| 1020 |
+
=== gbnf/grammar_graph/pointers.py
|
| 1021 |
+
from collections import OrderedDict
|
| 1022 |
+
|
| 1023 |
+
from .graph_pointer import GraphPointer
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
class Pointers:
|
| 1027 |
+
__pointers__: OrderedDict[int, GraphPointer]
|
| 1028 |
+
|
| 1029 |
+
def __init__(self, *pointers: GraphPointer):
|
| 1030 |
+
self.__pointers__ = OrderedDict()
|
| 1031 |
+
for pointer in pointers:
|
| 1032 |
+
self.add(pointer)
|
| 1033 |
+
|
| 1034 |
+
def __repr__(self):
|
| 1035 |
+
return f"<Pointers {id(self)} {[p.node.rule for p in self]}>"
|
| 1036 |
+
|
| 1037 |
+
def add(self, pointer):
|
| 1038 |
+
self.__pointers__[pointer.id] = pointer
|
| 1039 |
+
|
| 1040 |
+
def __iter__(self):
|
| 1041 |
+
yield from self.__pointers__.values()
|
| 1042 |
+
|
| 1043 |
+
def __len__(self):
|
| 1044 |
+
return len(self.__pointers__)
|
| 1045 |
+
=== gbnf/grammar_graph/print.py
|
| 1046 |
+
from __future__ import annotations
|
| 1047 |
+
|
| 1048 |
+
from collections.abc import Callable
|
| 1049 |
+
from typing import TYPE_CHECKING
|
| 1050 |
+
|
| 1051 |
+
from .colorize import Color
|
| 1052 |
+
from .get_parent_stack_id import get_parent_stack_id
|
| 1053 |
+
|
| 1054 |
+
if TYPE_CHECKING:
|
| 1055 |
+
from .grammar_graph_types import PrintOpts
|
| 1056 |
+
from .graph_node import GraphNode
|
| 1057 |
+
from .graph_pointer import GraphPointer
|
| 1058 |
+
|
| 1059 |
+
from .type_guards import is_range, is_rule_char, is_rule_ref
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
def print_graph_pointer(pointer: GraphPointer) -> Callable[[PrintOpts], str]:
|
| 1063 |
+
def print_graph_pointer_inner(opts: PrintOpts) -> str:
|
| 1064 |
+
col = opts["colorize"]
|
| 1065 |
+
return col(
|
| 1066 |
+
f"*{get_parent_stack_id(pointer, col)}",
|
| 1067 |
+
Color.RED,
|
| 1068 |
+
)
|
| 1069 |
+
|
| 1070 |
+
return print_graph_pointer_inner
|
| 1071 |
+
|
| 1072 |
+
|
| 1073 |
+
def print_graph_node(node: GraphNode) -> Callable[[PrintOpts], str]:
|
| 1074 |
+
def print_graph_node_inner(opts: PrintOpts) -> str:
|
| 1075 |
+
pointers = opts.get("pointers", set())
|
| 1076 |
+
col = opts["colorize"]
|
| 1077 |
+
show_position = opts.get("show_position", False)
|
| 1078 |
+
rule = node.rule
|
| 1079 |
+
parts: list[str] = []
|
| 1080 |
+
if show_position:
|
| 1081 |
+
parts.extend(
|
| 1082 |
+
[col("{", Color.BLUE), col(node.id, Color.GRAY), col("}", Color.BLUE)],
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
if is_rule_char(rule):
|
| 1086 |
+
parts.extend(
|
| 1087 |
+
[
|
| 1088 |
+
col("[", Color.GRAY),
|
| 1089 |
+
col(
|
| 1090 |
+
"".join(
|
| 1091 |
+
[
|
| 1092 |
+
(
|
| 1093 |
+
"".join(
|
| 1094 |
+
[col(get_char(val), Color.YELLOW) for val in v],
|
| 1095 |
+
)
|
| 1096 |
+
if is_range(v)
|
| 1097 |
+
else get_char(v)
|
| 1098 |
+
)
|
| 1099 |
+
for v in rule.value
|
| 1100 |
+
],
|
| 1101 |
+
),
|
| 1102 |
+
Color.YELLOW,
|
| 1103 |
+
),
|
| 1104 |
+
col("]", Color.GRAY),
|
| 1105 |
+
],
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
elif is_rule_ref(rule):
|
| 1109 |
+
parts.extend(
|
| 1110 |
+
[
|
| 1111 |
+
col("Ref(", Color.GRAY),
|
| 1112 |
+
col(rule.value, Color.GREEN),
|
| 1113 |
+
col(")", Color.GRAY),
|
| 1114 |
+
],
|
| 1115 |
+
)
|
| 1116 |
+
|
| 1117 |
+
else:
|
| 1118 |
+
parts.append(col(rule.type, Color.YELLOW))
|
| 1119 |
+
|
| 1120 |
+
if pointers:
|
| 1121 |
+
for pointer in pointers:
|
| 1122 |
+
pointer_parts: list[str] = []
|
| 1123 |
+
if pointer.node == node:
|
| 1124 |
+
pointer_parts.append(pointer.print(opts))
|
| 1125 |
+
|
| 1126 |
+
if len(pointer_parts) > 0:
|
| 1127 |
+
parts.extend(
|
| 1128 |
+
[
|
| 1129 |
+
col("[", Color.GRAY),
|
| 1130 |
+
col("".join(pointer_parts), Color.YELLOW),
|
| 1131 |
+
col("]", Color.GRAY),
|
| 1132 |
+
],
|
| 1133 |
+
)
|
| 1134 |
+
|
| 1135 |
+
parts_to_return = [
|
| 1136 |
+
"".join(parts),
|
| 1137 |
+
]
|
| 1138 |
+
if node.next:
|
| 1139 |
+
parts_to_return.append(node.next.print(opts))
|
| 1140 |
+
|
| 1141 |
+
return col("-> ", Color.GRAY).join(parts_to_return)
|
| 1142 |
+
|
| 1143 |
+
return print_graph_node_inner
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
def get_char(char_code: int) -> str:
|
| 1147 |
+
char = chr(char_code)
|
| 1148 |
+
if char == "\n":
|
| 1149 |
+
return "\\n"
|
| 1150 |
+
return char
|
| 1151 |
+
=== gbnf/grammar_graph/grammar_graph_types.py
|
| 1152 |
+
from __future__ import annotations
|
| 1153 |
+
|
| 1154 |
+
from collections.abc import Callable
|
| 1155 |
+
from dataclasses import dataclass, field
|
| 1156 |
+
from typing import TYPE_CHECKING, Any, TypedDict
|
| 1157 |
+
|
| 1158 |
+
from ..utils.validate_non_empty import validate_non_empty
|
| 1159 |
+
from .rule_ref import RuleRef
|
| 1160 |
+
|
| 1161 |
+
if TYPE_CHECKING:
|
| 1162 |
+
from .pointers import Pointers
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
class PrintOpts(TypedDict):
|
| 1166 |
+
pointers: Pointers
|
| 1167 |
+
colorize: Callable[[str | int, str], str]
|
| 1168 |
+
show_position: bool
|
| 1169 |
+
|
| 1170 |
+
|
| 1171 |
+
Range = tuple[int, int]
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
class Rule:
|
| 1175 |
+
def __eq__(self, other):
|
| 1176 |
+
return isinstance(other, self.__class__)
|
| 1177 |
+
|
| 1178 |
+
def __repr__(self) -> str:
|
| 1179 |
+
return f"{self.__class__.__name__}()"
|
| 1180 |
+
|
| 1181 |
+
def __hash__(self):
|
| 1182 |
+
return id(self)
|
| 1183 |
+
|
| 1184 |
+
@property
|
| 1185 |
+
def __dict__(self):
|
| 1186 |
+
return {
|
| 1187 |
+
"type": self.__class__.__name__,
|
| 1188 |
+
}
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
@dataclass
|
| 1192 |
+
class RuleWithValue(Rule):
|
| 1193 |
+
value: Any
|
| 1194 |
+
|
| 1195 |
+
def __eq__(self, other):
|
| 1196 |
+
return isinstance(other, self.__class__) and self.value == other.value
|
| 1197 |
+
|
| 1198 |
+
def __repr__(self) -> str:
|
| 1199 |
+
return f"{self.__class__.__name__}(value={self.value})"
|
| 1200 |
+
|
| 1201 |
+
@property
|
| 1202 |
+
def __dict__(self):
|
| 1203 |
+
return {
|
| 1204 |
+
**super().__dict__,
|
| 1205 |
+
"value": self.value,
|
| 1206 |
+
}
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
@dataclass
|
| 1210 |
+
class RuleWithListOfIntsOrRanges(RuleWithValue):
|
| 1211 |
+
value: list[int | Range] = field(
|
| 1212 |
+
default_factory=list,
|
| 1213 |
+
metadata={"validate": validate_non_empty},
|
| 1214 |
+
)
|
| 1215 |
+
|
| 1216 |
+
def __post_init__(self):
|
| 1217 |
+
self.value = self.value.copy()
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
@dataclass
|
| 1221 |
+
class RuleChar(RuleWithListOfIntsOrRanges):
|
| 1222 |
+
def __hash__(self):
|
| 1223 |
+
return id(self)
|
| 1224 |
+
|
| 1225 |
+
|
| 1226 |
+
class RuleCharExclude(RuleWithListOfIntsOrRanges):
|
| 1227 |
+
def __hash__(self):
|
| 1228 |
+
return id(self)
|
| 1229 |
+
|
| 1230 |
+
|
| 1231 |
+
class RuleEnd(Rule):
|
| 1232 |
+
def __hash__(self):
|
| 1233 |
+
return id(self)
|
| 1234 |
+
|
| 1235 |
+
|
| 1236 |
+
UnresolvedRule = RuleChar | RuleCharExclude | RuleRef | RuleEnd
|
| 1237 |
+
|
| 1238 |
+
|
| 1239 |
+
# ValidInput can either be a string, or a number indicating a code point.
|
| 1240 |
+
# It CANNOT be a number representing a number; a number intended as input (like "8")
|
| 1241 |
+
# should be passed in as a string.
|
| 1242 |
+
ValidInput = str | int | list[int]
|
| 1243 |
+
|
| 1244 |
+
|
| 1245 |
+
# RuleRefs should never be exposed to the end user.
|
| 1246 |
+
ResolvedRule = RuleCharExclude | RuleChar | RuleEnd
|
| 1247 |
+
|
| 1248 |
+
if TYPE_CHECKING:
|
| 1249 |
+
from .graph_pointer import GraphPointer
|
| 1250 |
+
|
| 1251 |
+
ResolvedGraphPointer = GraphPointer[ResolvedRule]
|
| 1252 |
+
=== gbnf/grammar_graph/get_serialized_rule_key.py
|
| 1253 |
+
from __future__ import annotations
|
| 1254 |
+
|
| 1255 |
+
import json
|
| 1256 |
+
|
| 1257 |
+
from .grammar_graph_types import (
|
| 1258 |
+
RuleChar,
|
| 1259 |
+
RuleCharExclude,
|
| 1260 |
+
RuleEnd,
|
| 1261 |
+
RuleRef,
|
| 1262 |
+
UnresolvedRule,
|
| 1263 |
+
)
|
| 1264 |
+
from .type_guards import is_rule_char, is_rule_char_exclude, is_rule_end, is_rule_ref
|
| 1265 |
+
|
| 1266 |
+
KEY_TRANSLATION = {
|
| 1267 |
+
RuleEnd: 0,
|
| 1268 |
+
RuleChar: 1,
|
| 1269 |
+
RuleCharExclude: 2,
|
| 1270 |
+
}
|
| 1271 |
+
|
| 1272 |
+
|
| 1273 |
+
def get_serialized_rule_key(rule: UnresolvedRule) -> str:
|
| 1274 |
+
if is_rule_end(rule):
|
| 1275 |
+
return f"{KEY_TRANSLATION[RuleEnd]}"
|
| 1276 |
+
|
| 1277 |
+
if is_rule_char(rule):
|
| 1278 |
+
assert isinstance(rule, RuleChar)
|
| 1279 |
+
return f"{KEY_TRANSLATION[RuleChar]}-{json.dumps(rule.value)}"
|
| 1280 |
+
|
| 1281 |
+
if is_rule_char_exclude(rule):
|
| 1282 |
+
assert isinstance(rule, RuleCharExclude)
|
| 1283 |
+
return f"{KEY_TRANSLATION[RuleCharExclude]}-{json.dumps(rule.value)}"
|
| 1284 |
+
|
| 1285 |
+
if is_rule_ref(rule):
|
| 1286 |
+
assert isinstance(rule, RuleRef)
|
| 1287 |
+
return f"3-{rule.value}"
|
| 1288 |
+
|
| 1289 |
+
raise ValueError(f"Unknown rule type: {rule}")
|
| 1290 |
+
=== gbnf/grammar_graph/rule_ref.py
|
| 1291 |
+
# import type { GraphNode, } from "./graph-node.js";
|
| 1292 |
+
GraphNode = object
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
class RuleRef:
|
| 1296 |
+
__nodes__: set[GraphNode] | None = None
|
| 1297 |
+
value: int
|
| 1298 |
+
|
| 1299 |
+
def __init__(self, value: int) -> None:
|
| 1300 |
+
self.value = value
|
| 1301 |
+
|
| 1302 |
+
@property
|
| 1303 |
+
def nodes(self) -> set[GraphNode]:
|
| 1304 |
+
if self.__nodes__ is None:
|
| 1305 |
+
raise ValueError("Nodes are not set")
|
| 1306 |
+
return self.__nodes__
|
| 1307 |
+
|
| 1308 |
+
@nodes.setter
|
| 1309 |
+
def nodes(self, nodes: set[GraphNode]) -> None:
|
| 1310 |
+
self.__nodes__ = nodes
|
| 1311 |
+
|
| 1312 |
+
def __eq__(self, other: object) -> bool:
|
| 1313 |
+
return isinstance(other, RuleRef) and self.value == other.value
|
| 1314 |
+
=== gbnf/grammar_graph/__init__.py
|
| 1315 |
+
=== gbnf/grammar_graph/graph_node.py
|
| 1316 |
+
from __future__ import annotations
|
| 1317 |
+
|
| 1318 |
+
from typing import Generic, TypedDict, TypeVar
|
| 1319 |
+
|
| 1320 |
+
from .grammar_graph_types import PrintOpts, UnresolvedRule
|
| 1321 |
+
from .print import print_graph_node
|
| 1322 |
+
from .rule_ref import RuleRef
|
| 1323 |
+
|
| 1324 |
+
|
| 1325 |
+
class GraphNodeMeta(TypedDict):
|
| 1326 |
+
stackId: int
|
| 1327 |
+
pathId: int
|
| 1328 |
+
stepId: int
|
| 1329 |
+
|
| 1330 |
+
|
| 1331 |
+
T = TypeVar("T", bound=UnresolvedRule)
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
class GraphNode(Generic[T]):
|
| 1335 |
+
rule: T
|
| 1336 |
+
next: GraphNode | None
|
| 1337 |
+
meta: GraphNodeMeta
|
| 1338 |
+
__id__: str | None = None
|
| 1339 |
+
|
| 1340 |
+
def __init__(
|
| 1341 |
+
self,
|
| 1342 |
+
rule: T,
|
| 1343 |
+
meta: GraphNodeMeta | None,
|
| 1344 |
+
next_node: GraphNode | None = None,
|
| 1345 |
+
):
|
| 1346 |
+
self.rule = rule
|
| 1347 |
+
if meta is None:
|
| 1348 |
+
raise ValueError("Meta is undefined")
|
| 1349 |
+
self.meta = meta
|
| 1350 |
+
self.next = next_node
|
| 1351 |
+
|
| 1352 |
+
@property
|
| 1353 |
+
def id(self) -> str:
|
| 1354 |
+
if self.__id__ is None:
|
| 1355 |
+
self.__id__ = (
|
| 1356 |
+
f"{self.meta['stackId']},{self.meta['pathId']},{self.meta['stepId']}"
|
| 1357 |
+
)
|
| 1358 |
+
return self.__id__
|
| 1359 |
+
|
| 1360 |
+
def print(self, opts: PrintOpts) -> str:
|
| 1361 |
+
return print_graph_node(self)(opts)
|
| 1362 |
+
|
| 1363 |
+
def __repr__(self):
|
| 1364 |
+
return f"<GraphNode {id(self)} {self.rule}>"
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
GraphNodeRuleRef = GraphNode[RuleRef]
|
| 1368 |
+
=== gbnf/grammar_graph/type_guards.py
|
| 1369 |
+
from __future__ import annotations
|
| 1370 |
+
|
| 1371 |
+
from collections.abc import Callable
|
| 1372 |
+
from typing import TYPE_CHECKING, Any, TypeGuard, TypeVar
|
| 1373 |
+
|
| 1374 |
+
from .grammar_graph_types import (
|
| 1375 |
+
RuleChar,
|
| 1376 |
+
RuleCharExclude,
|
| 1377 |
+
RuleEnd,
|
| 1378 |
+
UnresolvedRule,
|
| 1379 |
+
)
|
| 1380 |
+
from .rule_ref import RuleRef
|
| 1381 |
+
|
| 1382 |
+
if TYPE_CHECKING:
|
| 1383 |
+
from .graph_pointer import GraphPointer
|
| 1384 |
+
|
| 1385 |
+
|
| 1386 |
+
T = TypeVar("T")
|
| 1387 |
+
|
| 1388 |
+
|
| 1389 |
+
def type_guard(predicate: Callable[[Any], bool]) -> Callable[[Any], TypeGuard[T]]:
|
| 1390 |
+
def wrapper(value: Any) -> TypeGuard[T]:
|
| 1391 |
+
return predicate(value)
|
| 1392 |
+
|
| 1393 |
+
return wrapper
|
| 1394 |
+
|
| 1395 |
+
|
| 1396 |
+
@type_guard
|
| 1397 |
+
def is_rule(rule: Any) -> bool:
|
| 1398 |
+
return rule is not None and isinstance(
|
| 1399 |
+
rule,
|
| 1400 |
+
(RuleChar | RuleCharExclude | RuleEnd | RuleRef),
|
| 1401 |
+
)
|
| 1402 |
+
|
| 1403 |
+
|
| 1404 |
+
@type_guard
|
| 1405 |
+
def is_rule_ref(rule: UnresolvedRule) -> bool:
|
| 1406 |
+
return isinstance(rule, RuleRef)
|
| 1407 |
+
|
| 1408 |
+
|
| 1409 |
+
@type_guard
|
| 1410 |
+
def is_rule_end(rule: UnresolvedRule) -> bool:
|
| 1411 |
+
return rule is not None and isinstance(rule, RuleEnd) and isinstance(rule, RuleEnd)
|
| 1412 |
+
|
| 1413 |
+
|
| 1414 |
+
@type_guard
|
| 1415 |
+
def is_rule_char(rule: UnresolvedRule) -> bool:
|
| 1416 |
+
return (
|
| 1417 |
+
rule is not None and isinstance(rule, RuleChar) and isinstance(rule, RuleChar)
|
| 1418 |
+
)
|
| 1419 |
+
|
| 1420 |
+
|
| 1421 |
+
@type_guard
|
| 1422 |
+
def is_rule_char_exclude(rule: UnresolvedRule) -> bool:
|
| 1423 |
+
return rule is not None and isinstance(rule, RuleCharExclude)
|
| 1424 |
+
|
| 1425 |
+
|
| 1426 |
+
@type_guard
|
| 1427 |
+
def is_range(inpt: Any) -> bool:
|
| 1428 |
+
return (
|
| 1429 |
+
isinstance(inpt, list)
|
| 1430 |
+
and len(inpt) == 2
|
| 1431 |
+
and all(isinstance(n, int) for n in inpt)
|
| 1432 |
+
)
|
| 1433 |
+
|
| 1434 |
+
|
| 1435 |
+
@type_guard
|
| 1436 |
+
def is_graph_pointer_rule_ref(pointer: GraphPointer) -> bool:
|
| 1437 |
+
return is_rule_ref(pointer.rule)
|
| 1438 |
+
|
| 1439 |
+
|
| 1440 |
+
@type_guard
|
| 1441 |
+
def is_graph_pointer_rule_end(pointer: GraphPointer) -> bool:
|
| 1442 |
+
return is_rule_end(pointer.rule)
|
| 1443 |
+
|
| 1444 |
+
|
| 1445 |
+
@type_guard
|
| 1446 |
+
def is_graph_pointer_rule_char(pointer: GraphPointer) -> bool:
|
| 1447 |
+
return is_rule_char(pointer.rule)
|
| 1448 |
+
|
| 1449 |
+
|
| 1450 |
+
@type_guard
|
| 1451 |
+
def is_graph_pointer_rule_char_exclude(pointer: GraphPointer) -> bool:
|
| 1452 |
+
return is_rule_char_exclude(pointer.rule)
|
| 1453 |
+
=== gbnf/grammar_graph/get_parent_stack_id.py
|
| 1454 |
+
from __future__ import annotations
|
| 1455 |
+
|
| 1456 |
+
from collections.abc import Callable
|
| 1457 |
+
from typing import TYPE_CHECKING
|
| 1458 |
+
|
| 1459 |
+
from .colorize import Color
|
| 1460 |
+
|
| 1461 |
+
if TYPE_CHECKING:
|
| 1462 |
+
from .graph_pointer import GraphPointer
|
| 1463 |
+
|
| 1464 |
+
|
| 1465 |
+
def get_parent_stack_id(
|
| 1466 |
+
pointer: GraphPointer,
|
| 1467 |
+
col: Callable[[str | int, str], str],
|
| 1468 |
+
) -> str:
|
| 1469 |
+
stack_ids: list[str] = []
|
| 1470 |
+
parent: GraphPointer | None = pointer.parent
|
| 1471 |
+
while parent:
|
| 1472 |
+
stack_ids.append(
|
| 1473 |
+
f"{parent.node.meta['stackId']},{parent.node.meta['pathId']},{parent.node.meta['stepId']}",
|
| 1474 |
+
)
|
| 1475 |
+
parent = parent.parent
|
| 1476 |
+
arrow = col("<-", Color.GRAY)
|
| 1477 |
+
return arrow.join([col(stack_id, Color.RED) for stack_id in stack_ids])
|
| 1478 |
+
=== gbnf/grammar_graph/colorize.py
|
| 1479 |
+
class Color:
|
| 1480 |
+
BLUE = "\x1b[34m"
|
| 1481 |
+
CYAN = "\x1b[36m"
|
| 1482 |
+
GREEN = "\x1b[32m"
|
| 1483 |
+
RED = "\x1b[31m"
|
| 1484 |
+
GRAY = "\x1b[90m"
|
| 1485 |
+
YELLOW = "\x1b[33m"
|
| 1486 |
+
|
| 1487 |
+
|
| 1488 |
+
def colorize(text: str | int, color: str) -> str:
|
| 1489 |
+
return f"{color}{text}"
|
| 1490 |
+
=== gbnf/grammar_graph/graph_pointer.py
|
| 1491 |
+
from __future__ import annotations
|
| 1492 |
+
|
| 1493 |
+
from typing import TYPE_CHECKING, Generic, TypeVar
|
| 1494 |
+
|
| 1495 |
+
from .grammar_graph_types import PrintOpts, UnresolvedRule
|
| 1496 |
+
from .graph_node import GraphNode
|
| 1497 |
+
from .print import print_graph_pointer
|
| 1498 |
+
from .type_guards import (
|
| 1499 |
+
is_graph_pointer_rule_char,
|
| 1500 |
+
is_graph_pointer_rule_char_exclude,
|
| 1501 |
+
is_graph_pointer_rule_end,
|
| 1502 |
+
is_graph_pointer_rule_ref,
|
| 1503 |
+
is_rule_end,
|
| 1504 |
+
)
|
| 1505 |
+
|
| 1506 |
+
if TYPE_CHECKING:
|
| 1507 |
+
from .graph_node import GraphNode
|
| 1508 |
+
|
| 1509 |
+
T = TypeVar("T", bound=UnresolvedRule)
|
| 1510 |
+
|
| 1511 |
+
GraphPointerKey = str
|
| 1512 |
+
|
| 1513 |
+
|
| 1514 |
+
class GraphPointer(Generic[T]):
|
| 1515 |
+
node: GraphNode[T]
|
| 1516 |
+
parent: GraphPointer | None = None
|
| 1517 |
+
id: str
|
| 1518 |
+
__valid__: bool | None = None
|
| 1519 |
+
|
| 1520 |
+
def __init__(self, node: GraphNode[T], parent: GraphPointer | None = None):
|
| 1521 |
+
if node is None:
|
| 1522 |
+
raise ValueError("Node is undefined")
|
| 1523 |
+
self.node = node
|
| 1524 |
+
self.parent = parent
|
| 1525 |
+
self.id = f"{parent.id}-{node.id}" if parent else node.id
|
| 1526 |
+
|
| 1527 |
+
@property
|
| 1528 |
+
def rule(self) -> T:
|
| 1529 |
+
return self.node.rule
|
| 1530 |
+
|
| 1531 |
+
@property
|
| 1532 |
+
def valid(self) -> bool | None:
|
| 1533 |
+
return self.__valid__
|
| 1534 |
+
|
| 1535 |
+
@valid.setter
|
| 1536 |
+
def valid(self, valid: bool) -> None:
|
| 1537 |
+
self.__valid__ = valid
|
| 1538 |
+
|
| 1539 |
+
def print(self, opts: PrintOpts):
|
| 1540 |
+
return print_graph_pointer(self)(opts)
|
| 1541 |
+
|
| 1542 |
+
def resolve(self, resolved=False):
|
| 1543 |
+
"""
|
| 1544 |
+
Resolve the graph pointer.
|
| 1545 |
+
|
| 1546 |
+
Args:
|
| 1547 |
+
resolved (bool, optional): Whether the pointer has already been resolved. Defaults to False.
|
| 1548 |
+
|
| 1549 |
+
Yields:
|
| 1550 |
+
ResolvedGraphPointer: The resolved graph pointer.
|
| 1551 |
+
"""
|
| 1552 |
+
if is_graph_pointer_rule_ref(self):
|
| 1553 |
+
if resolved:
|
| 1554 |
+
if not self.node.next:
|
| 1555 |
+
raise ValueError(f"No next node: {self.node}")
|
| 1556 |
+
yield from GraphPointer(self.node.next, self.parent).resolve()
|
| 1557 |
+
else:
|
| 1558 |
+
for node in self.node.rule.nodes:
|
| 1559 |
+
yield from GraphPointer(node, self).resolve()
|
| 1560 |
+
elif is_graph_pointer_rule_end(self):
|
| 1561 |
+
if not self.parent:
|
| 1562 |
+
yield self
|
| 1563 |
+
else:
|
| 1564 |
+
yield from self.parent.resolve(True)
|
| 1565 |
+
elif is_graph_pointer_rule_char(self) or is_graph_pointer_rule_char_exclude(
|
| 1566 |
+
self,
|
| 1567 |
+
):
|
| 1568 |
+
yield self
|
| 1569 |
+
else:
|
| 1570 |
+
raise ValueError(f"Unknown rule: {self.node.rule}")
|
| 1571 |
+
|
| 1572 |
+
def fetch_next(self):
|
| 1573 |
+
"""
|
| 1574 |
+
Fetch the next resolved graph pointer.
|
| 1575 |
+
|
| 1576 |
+
Yields:
|
| 1577 |
+
ResolvedGraphPointer: The next resolved graph pointer.
|
| 1578 |
+
"""
|
| 1579 |
+
# If this pointer is invalid, then we don't return any new pointers
|
| 1580 |
+
if not self.valid:
|
| 1581 |
+
return
|
| 1582 |
+
|
| 1583 |
+
# If this pointer is an end node, we return the parent's next node.
|
| 1584 |
+
# If no parent exists, we return nothing, since it's the end of the line.
|
| 1585 |
+
if is_rule_end(self.node.rule):
|
| 1586 |
+
if self.parent:
|
| 1587 |
+
yield from self.parent.fetch_next()
|
| 1588 |
+
else:
|
| 1589 |
+
if not self.node.next:
|
| 1590 |
+
raise ValueError(f"No next node: {self.node}")
|
| 1591 |
+
pointer = GraphPointer(self.node.next, self.parent)
|
| 1592 |
+
yield from pointer.resolve()
|
| 1593 |
+
|
| 1594 |
+
def __repr__(self):
|
| 1595 |
+
return f"<GraphPointer {id(self)} {self.node}>"
|
| 1596 |
+
=== gbnf/grammar_parser/build_rule_stack.py
|
| 1597 |
+
import json
|
| 1598 |
+
from typing import cast
|
| 1599 |
+
|
| 1600 |
+
from ..grammar_graph.grammar_graph_types import (
|
| 1601 |
+
Range,
|
| 1602 |
+
RuleChar,
|
| 1603 |
+
RuleCharExclude,
|
| 1604 |
+
RuleEnd,
|
| 1605 |
+
UnresolvedRule,
|
| 1606 |
+
)
|
| 1607 |
+
from ..grammar_graph.rule_ref import RuleRef
|
| 1608 |
+
from ..grammar_graph.type_guards import is_range, is_rule_end
|
| 1609 |
+
from ..rules_builder.rules_builder_types import (
|
| 1610 |
+
InternalRuleDef,
|
| 1611 |
+
InternalRuleDefChar,
|
| 1612 |
+
InternalRuleDefCharAlt,
|
| 1613 |
+
InternalRuleDefCharNot,
|
| 1614 |
+
InternalRuleDefCharRngUpper,
|
| 1615 |
+
InternalRuleDefReference,
|
| 1616 |
+
is_rule_def_alt,
|
| 1617 |
+
is_rule_def_char,
|
| 1618 |
+
is_rule_def_char_alt,
|
| 1619 |
+
is_rule_def_char_not,
|
| 1620 |
+
is_rule_def_char_rng_upper,
|
| 1621 |
+
is_rule_def_end,
|
| 1622 |
+
is_rule_def_ref,
|
| 1623 |
+
)
|
| 1624 |
+
|
| 1625 |
+
|
| 1626 |
+
def make_char_rule(
|
| 1627 |
+
rule_def: InternalRuleDefChar | InternalRuleDefCharNot,
|
| 1628 |
+
) -> RuleChar | RuleCharExclude:
|
| 1629 |
+
value = cast(list[int | Range], rule_def.value)
|
| 1630 |
+
if is_rule_def_char_not(rule_def):
|
| 1631 |
+
return RuleCharExclude(value=value)
|
| 1632 |
+
if is_rule_def_char(rule_def):
|
| 1633 |
+
return RuleChar(value=value)
|
| 1634 |
+
|
| 1635 |
+
raise ValueError(f"Unsupported rule type for make_char_rule: {rule_def}")
|
| 1636 |
+
|
| 1637 |
+
|
| 1638 |
+
def build_rule_stack(linear_rules: list[InternalRuleDef]) -> list[list[UnresolvedRule]]:
|
| 1639 |
+
paths: list[UnresolvedRule] = []
|
| 1640 |
+
stack: list[list[UnresolvedRule]] = []
|
| 1641 |
+
idx = 0
|
| 1642 |
+
|
| 1643 |
+
while idx < len(linear_rules):
|
| 1644 |
+
rule_def = linear_rules[idx]
|
| 1645 |
+
if is_rule_def_char(rule_def) or is_rule_def_char_not(rule_def):
|
| 1646 |
+
# this could be a single char, or a range, or a sequence of alts; we don't know until we step through it.
|
| 1647 |
+
rule_def = (
|
| 1648 |
+
cast(InternalRuleDefChar, rule_def)
|
| 1649 |
+
if is_rule_def_char(rule_def)
|
| 1650 |
+
else cast(InternalRuleDefCharNot, rule_def)
|
| 1651 |
+
)
|
| 1652 |
+
char_rule = make_char_rule(rule_def)
|
| 1653 |
+
idx += 1
|
| 1654 |
+
rule = linear_rules[idx] if idx < len(linear_rules) else None
|
| 1655 |
+
while idx < len(linear_rules) and (
|
| 1656 |
+
is_rule_def_char_rng_upper(rule) or is_rule_def_char_alt(rule)
|
| 1657 |
+
):
|
| 1658 |
+
if is_rule_def_char_rng_upper(rule):
|
| 1659 |
+
# previous rule value should be a number
|
| 1660 |
+
prev_value = char_rule.value.pop()
|
| 1661 |
+
if is_range(prev_value):
|
| 1662 |
+
raise ValueError(
|
| 1663 |
+
f"Unexpected range, expected a number but got an array: {json.dumps(prev_value)}",
|
| 1664 |
+
)
|
| 1665 |
+
if prev_value is None:
|
| 1666 |
+
raise ValueError("Unexpected undefined value")
|
| 1667 |
+
|
| 1668 |
+
char_rule.value.append(
|
| 1669 |
+
cast(
|
| 1670 |
+
Range,
|
| 1671 |
+
[prev_value, cast(InternalRuleDefCharRngUpper, rule).value],
|
| 1672 |
+
),
|
| 1673 |
+
)
|
| 1674 |
+
if is_rule_def_char_alt(rule):
|
| 1675 |
+
rule = cast(InternalRuleDefCharAlt, rule)
|
| 1676 |
+
char_rule.value.append(cast(int, rule.value))
|
| 1677 |
+
idx += 1
|
| 1678 |
+
rule = linear_rules[idx] if idx < len(linear_rules) else None
|
| 1679 |
+
paths.append(char_rule)
|
| 1680 |
+
else:
|
| 1681 |
+
if is_rule_def_alt(rule_def):
|
| 1682 |
+
if len(paths) == 0:
|
| 1683 |
+
raise ValueError("Encountered alt without anything before it")
|
| 1684 |
+
paths.append(RuleEnd())
|
| 1685 |
+
stack.append(paths)
|
| 1686 |
+
paths = []
|
| 1687 |
+
elif is_rule_def_end(rule_def):
|
| 1688 |
+
paths.append(RuleEnd())
|
| 1689 |
+
elif is_rule_def_ref(rule_def):
|
| 1690 |
+
paths.append(
|
| 1691 |
+
RuleRef(cast(int, cast(InternalRuleDefReference, rule_def).value)),
|
| 1692 |
+
)
|
| 1693 |
+
elif is_rule_def_char_alt(rule_def):
|
| 1694 |
+
raise ValueError(
|
| 1695 |
+
f"Encountered char alt, should be handled by above block: {rule_def}",
|
| 1696 |
+
)
|
| 1697 |
+
else:
|
| 1698 |
+
raise ValueError(f"Unsupported rule type: {rule_def}")
|
| 1699 |
+
idx += 1
|
| 1700 |
+
|
| 1701 |
+
if not is_rule_end(paths[-1]):
|
| 1702 |
+
paths.append(RuleEnd())
|
| 1703 |
+
|
| 1704 |
+
stack.append(paths)
|
| 1705 |
+
return stack
|
| 1706 |
+
=== gbnf/grammar_parser/__init__.py
|
| 1707 |
+
=== gbnf/utils/is_point_in_range.py
|
| 1708 |
+
def is_point_in_range(point: int, given_range: tuple[int, int]) -> bool:
|
| 1709 |
+
if type(point) is not int:
|
| 1710 |
+
raise ValueError("point must be an integer")
|
| 1711 |
+
return point >= given_range[0] and point <= given_range[1]
|
| 1712 |
+
=== gbnf/utils/__init__.py
|
| 1713 |
+
=== gbnf/utils/validate_non_empty.py
|
| 1714 |
+
def validate_non_empty(value: list[int]) -> list[int]:
|
| 1715 |
+
if not value:
|
| 1716 |
+
raise ValueError("Value cannot be empty.")
|
| 1717 |
+
return value
|
| 1718 |
+
=== gbnf/utils/errors/__init__.py
|
| 1719 |
+
from .grammar_parse_error import GrammarParseError
|
| 1720 |
+
from .input_parse_error import InputParseError
|
| 1721 |
+
|
| 1722 |
+
__all__ = [
|
| 1723 |
+
"GrammarParseError",
|
| 1724 |
+
"InputParseError",
|
| 1725 |
+
]
|
| 1726 |
+
=== gbnf/utils/errors/errors_types.py
|
| 1727 |
+
ValidInput = str | int | list[int]
|
| 1728 |
+
=== gbnf/utils/errors/get_input_as_string.py
|
| 1729 |
+
from .errors_types import ValidInput
|
| 1730 |
+
|
| 1731 |
+
|
| 1732 |
+
def get_input_as_string(src: ValidInput) -> str:
|
| 1733 |
+
if isinstance(src, str):
|
| 1734 |
+
return src
|
| 1735 |
+
if isinstance(src, int):
|
| 1736 |
+
return chr(src)
|
| 1737 |
+
return "".join(chr(cp) for cp in src)
|
| 1738 |
+
=== gbnf/utils/errors/grammar_parse_error.py
|
| 1739 |
+
from .build_error_position import build_error_position
|
| 1740 |
+
|
| 1741 |
+
|
| 1742 |
+
def GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason: str) -> str:
|
| 1743 |
+
return f"Failed to parse grammar: {reason}"
|
| 1744 |
+
|
| 1745 |
+
|
| 1746 |
+
class GrammarParseError(Exception):
|
| 1747 |
+
grammar: str
|
| 1748 |
+
pos: int
|
| 1749 |
+
reason: str
|
| 1750 |
+
|
| 1751 |
+
def __init__(self, grammar: str, pos: int, reason: str):
|
| 1752 |
+
super().__init__(
|
| 1753 |
+
"\n".join(
|
| 1754 |
+
[
|
| 1755 |
+
GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason),
|
| 1756 |
+
"",
|
| 1757 |
+
*build_error_position(grammar, pos),
|
| 1758 |
+
],
|
| 1759 |
+
),
|
| 1760 |
+
)
|
| 1761 |
+
self.grammar = grammar
|
| 1762 |
+
self.pos = pos
|
| 1763 |
+
self.reason = reason
|
| 1764 |
+
|
| 1765 |
+
def __str__(self):
|
| 1766 |
+
return "\n".join(
|
| 1767 |
+
[
|
| 1768 |
+
GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(self.reason),
|
| 1769 |
+
"",
|
| 1770 |
+
*build_error_position(self.grammar, self.pos),
|
| 1771 |
+
],
|
| 1772 |
+
)
|
| 1773 |
+
|
| 1774 |
+
def __eq__(self, other):
|
| 1775 |
+
return str(self) == str(other)
|
| 1776 |
+
=== gbnf/utils/errors/input_parse_error.py
|
| 1777 |
+
from .build_error_position import build_error_position
|
| 1778 |
+
from .errors_types import ValidInput
|
| 1779 |
+
from .get_input_as_string import get_input_as_string
|
| 1780 |
+
|
| 1781 |
+
INPUT_PARSER_ERROR_HEADER_MESSAGE = "Failed to parse input string:"
|
| 1782 |
+
|
| 1783 |
+
|
| 1784 |
+
class InputParseError(Exception):
|
| 1785 |
+
most_recent_input: ValidInput
|
| 1786 |
+
pos: int
|
| 1787 |
+
previous_input: ValidInput
|
| 1788 |
+
|
| 1789 |
+
def __init__(
|
| 1790 |
+
self,
|
| 1791 |
+
most_recent_input: ValidInput,
|
| 1792 |
+
pos: int,
|
| 1793 |
+
previous_input: ValidInput = "",
|
| 1794 |
+
):
|
| 1795 |
+
super().__init__(
|
| 1796 |
+
"\n".join(
|
| 1797 |
+
[
|
| 1798 |
+
INPUT_PARSER_ERROR_HEADER_MESSAGE,
|
| 1799 |
+
"",
|
| 1800 |
+
*build_error_position(
|
| 1801 |
+
f"{get_input_as_string(previous_input)}{get_input_as_string(most_recent_input)}",
|
| 1802 |
+
pos + len(get_input_as_string(previous_input)),
|
| 1803 |
+
),
|
| 1804 |
+
],
|
| 1805 |
+
),
|
| 1806 |
+
)
|
| 1807 |
+
self.most_recent_input = most_recent_input
|
| 1808 |
+
self.pos = pos
|
| 1809 |
+
self.previous_input = previous_input
|
| 1810 |
+
|
| 1811 |
+
@property
|
| 1812 |
+
def src(self):
|
| 1813 |
+
return f"{get_input_as_string(self.previous_input)}{get_input_as_string(self.most_recent_input)}"
|
| 1814 |
+
|
| 1815 |
+
@property
|
| 1816 |
+
def error_for_most_recent_input(self):
|
| 1817 |
+
return "\n".join(
|
| 1818 |
+
[
|
| 1819 |
+
INPUT_PARSER_ERROR_HEADER_MESSAGE,
|
| 1820 |
+
"",
|
| 1821 |
+
*build_error_position(
|
| 1822 |
+
get_input_as_string(self.most_recent_input),
|
| 1823 |
+
self.pos,
|
| 1824 |
+
),
|
| 1825 |
+
],
|
| 1826 |
+
)
|
| 1827 |
+
|
| 1828 |
+
def __str__(self):
|
| 1829 |
+
return "\n".join(
|
| 1830 |
+
[
|
| 1831 |
+
INPUT_PARSER_ERROR_HEADER_MESSAGE,
|
| 1832 |
+
"",
|
| 1833 |
+
*build_error_position(
|
| 1834 |
+
f"{get_input_as_string(self.previous_input)}{get_input_as_string(self.most_recent_input)}",
|
| 1835 |
+
self.pos + len(get_input_as_string(self.previous_input)),
|
| 1836 |
+
),
|
| 1837 |
+
],
|
| 1838 |
+
)
|
| 1839 |
+
|
| 1840 |
+
def __eq__(self, other):
|
| 1841 |
+
return str(self) == str(other)
|
| 1842 |
+
=== gbnf/utils/errors/build_error_position.py
|
| 1843 |
+
MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW = 3
|
| 1844 |
+
|
| 1845 |
+
|
| 1846 |
+
def build_error_position(src: str, pos: int) -> list[str]:
|
| 1847 |
+
if src == "":
|
| 1848 |
+
return [
|
| 1849 |
+
"No input provided",
|
| 1850 |
+
]
|
| 1851 |
+
lines = src.split("\n")
|
| 1852 |
+
|
| 1853 |
+
line_idx = 0
|
| 1854 |
+
while lines[line_idx] and pos > len(lines[line_idx]) - 1 and pos < len(src):
|
| 1855 |
+
pos -= len(lines[line_idx])
|
| 1856 |
+
line_idx += 1
|
| 1857 |
+
|
| 1858 |
+
lines_to_show = [
|
| 1859 |
+
lines[i]
|
| 1860 |
+
for i in range(
|
| 1861 |
+
max(0, line_idx - (MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW - 1)),
|
| 1862 |
+
line_idx + 1,
|
| 1863 |
+
)
|
| 1864 |
+
]
|
| 1865 |
+
|
| 1866 |
+
return [
|
| 1867 |
+
*lines_to_show,
|
| 1868 |
+
" " * pos + "^",
|
| 1869 |
+
]
|
v2-models-effort/runs/20261111-214430-mute-surf/credentials.log
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[2026-11-11 21:51:03.624][27][warning][main] [source/server/server.cc:1012] There is no configured limit to the number of allowed active downstream connections. Configure a limit in `envoy.resource_monitors.global_downstream_max_connections` resource monitor.
|
| 2 |
+
[2026-11-11T21:51:04.155Z] POST /v1/messages?beta=true 200 - 2189ms
|
| 3 |
+
[2026-11-11T21:51:06.420Z] POST /v1/messages?beta=true 200 - 2855ms
|
| 4 |
+
[2026-11-11T21:51:10.985Z] POST /v1/messages/count_tokens?beta=true 200 - 112ms
|
| 5 |
+
[2026-11-11T21:51:09.309Z] POST /v1/messages?beta=true 200 - 3197ms
|
| 6 |
+
[2026-11-11T21:51:12.530Z] POST /v1/messages?beta=true 200 - 63985ms
|
| 7 |
+
[2026-11-11T21:52:16.551Z] POST /v1/messages?beta=true 200 - 41385ms
|
| 8 |
+
[2026-11-11T21:52:57.967Z] POST /v1/messages?beta=true 200 - 32978ms
|
| 9 |
+
[2026-11-11T21:53:30.975Z] POST /v1/messages?beta=true 200 - 51121ms
|
| 10 |
+
[2026-11-11T21:54:22.132Z] POST /v1/messages?beta=true 200 - 93816ms
|
| 11 |
+
[2026-11-11T21:55:55.992Z] POST /v1/messages?beta=true 200 - 9487ms
|
| 12 |
+
[2026-11-11T21:56:05.520Z] POST /v1/messages?beta=true 200 - 14947ms
|
| 13 |
+
[2026-11-11T21:56:21.010Z] POST /v1/messages?beta=true 200 - 3037ms
|
| 14 |
+
[2026-11-11T21:56:24.127Z] POST /v1/messages?beta=true 200 - 30326ms
|
| 15 |
+
[2026-11-11T21:56:54.964Z] POST /v1/messages?beta=true 200 - 121108ms
|
| 16 |
+
[2026-11-11T21:58:56.729Z] POST /v1/messages?beta=true 200 - 23051ms
|
| 17 |
+
[2026-11-11T21:59:20.777Z] POST /v1/messages?beta=true 200 - 3250ms
|
| 18 |
+
[2026-11-11T21:59:28.089Z] POST /v1/messages?beta=true 200 - 6992ms
|
| 19 |
+
[2026-11-11T21:59:35.809Z] POST /v1/messages?beta=true 200 - 1784ms
|
| 20 |
+
[2026-11-11T21:59:37.615Z] POST /v1/messages?beta=true 200 - 7810ms
|
| 21 |
+
[2026-11-11 21:59:45.635][27][warning][main] [source/server/server.cc:981] caught ENVOY_SIGTERM
|
v2-models-effort/runs/20261111-214430-mute-surf/git-diff.patch
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v2-models-effort/runs/20261111-214430-mute-surf/git-sha.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
8422439f49db061ed5b56e9b883ef244807898f8
|
v2-models-effort/runs/20261111-214430-mute-surf/manifest.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"timestamp": "2026-11-11T21:50:52Z",
|
| 3 |
+
"completed_at": "2026-11-11T21:59:46Z",
|
| 4 |
+
"exit_code": 0,
|
| 5 |
+
"oom_killed": false,
|
| 6 |
+
"condition": {
|
| 7 |
+
"name": "source-python_unit-tests_source-integration-tests_effort-medium_model-claude-fable-5-2",
|
| 8 |
+
"source_language": "python",
|
| 9 |
+
"target_language": "javascript",
|
| 10 |
+
"include_unit_tests": true,
|
| 11 |
+
"include_source_integration_tests": true,
|
| 12 |
+
"include_target_integration_tests": false,
|
| 13 |
+
"effort": "medium",
|
| 14 |
+
"model": "claude-fable-5-2"
|
| 15 |
+
},
|
| 16 |
+
"derivation": {
|
| 17 |
+
"gbnf_commit": "13f1aca495d11e160fffd68c4ba299a2415909d8"
|
| 18 |
+
},
|
| 19 |
+
"reference_implementation": {
|
| 20 |
+
"included": [
|
| 21 |
+
"python/.gitignore",
|
| 22 |
+
"python/MANIFEST.in",
|
| 23 |
+
"python/Makefile",
|
| 24 |
+
"python/README.md",
|
| 25 |
+
"python/gbnf/GBNF.py",
|
| 26 |
+
"python/gbnf/__init__.py",
|
| 27 |
+
"python/gbnf/grammar_graph/__init__.py",
|
| 28 |
+
"python/gbnf/grammar_graph/colorize.py",
|
| 29 |
+
"python/gbnf/grammar_graph/colorize_test.py",
|
| 30 |
+
"python/gbnf/grammar_graph/get_input_as_code_points.py",
|
| 31 |
+
"python/gbnf/grammar_graph/get_input_as_code_points_test.py",
|
| 32 |
+
"python/gbnf/grammar_graph/get_parent_stack_id.py",
|
| 33 |
+
"python/gbnf/grammar_graph/get_parent_stack_id_test.py",
|
| 34 |
+
"python/gbnf/grammar_graph/get_serialized_rule_key.py",
|
| 35 |
+
"python/gbnf/grammar_graph/get_serialized_rule_key_test.py",
|
| 36 |
+
"python/gbnf/grammar_graph/grammar_graph_types.py",
|
| 37 |
+
"python/gbnf/grammar_graph/graph.py",
|
| 38 |
+
"python/gbnf/grammar_graph/graph_node.py",
|
| 39 |
+
"python/gbnf/grammar_graph/graph_node_test.py",
|
| 40 |
+
"python/gbnf/grammar_graph/graph_pointer.py",
|
| 41 |
+
"python/gbnf/grammar_graph/graph_pointer_test.py",
|
| 42 |
+
"python/gbnf/grammar_graph/graph_test.py",
|
| 43 |
+
"python/gbnf/grammar_graph/parse_state.py",
|
| 44 |
+
"python/gbnf/grammar_graph/parse_state_test.py",
|
| 45 |
+
"python/gbnf/grammar_graph/pointers.py",
|
| 46 |
+
"python/gbnf/grammar_graph/print.py",
|
| 47 |
+
"python/gbnf/grammar_graph/print_test.py",
|
| 48 |
+
"python/gbnf/grammar_graph/rule_ref.py",
|
| 49 |
+
"python/gbnf/grammar_graph/rule_ref_test.py",
|
| 50 |
+
"python/gbnf/grammar_graph/type_guards.py",
|
| 51 |
+
"python/gbnf/grammar_graph/type_guards_test.py",
|
| 52 |
+
"python/gbnf/grammar_parser/__init__.py",
|
| 53 |
+
"python/gbnf/grammar_parser/build_rule_stack.py",
|
| 54 |
+
"python/gbnf/grammar_parser/build_rule_stack_test.py",
|
| 55 |
+
"python/gbnf/rules_builder/__init__.py",
|
| 56 |
+
"python/gbnf/rules_builder/is_word_char.py",
|
| 57 |
+
"python/gbnf/rules_builder/is_word_char_test.py",
|
| 58 |
+
"python/gbnf/rules_builder/parse_char.py",
|
| 59 |
+
"python/gbnf/rules_builder/parse_char_test.py",
|
| 60 |
+
"python/gbnf/rules_builder/parse_name.py",
|
| 61 |
+
"python/gbnf/rules_builder/parse_name_test.py",
|
| 62 |
+
"python/gbnf/rules_builder/parse_space.py",
|
| 63 |
+
"python/gbnf/rules_builder/parse_space_test.py",
|
| 64 |
+
"python/gbnf/rules_builder/rules_builder.py",
|
| 65 |
+
"python/gbnf/rules_builder/rules_builder_test.py",
|
| 66 |
+
"python/gbnf/rules_builder/rules_builder_types.py",
|
| 67 |
+
"python/gbnf/rules_builder/symbol_ids.py",
|
| 68 |
+
"python/gbnf/utils/__init__.py",
|
| 69 |
+
"python/gbnf/utils/errors/__init__.py",
|
| 70 |
+
"python/gbnf/utils/errors/build_error_position.py",
|
| 71 |
+
"python/gbnf/utils/errors/build_error_position_test.py",
|
| 72 |
+
"python/gbnf/utils/errors/errors_types.py",
|
| 73 |
+
"python/gbnf/utils/errors/get_input_as_string.py",
|
| 74 |
+
"python/gbnf/utils/errors/get_input_as_string_test.py",
|
| 75 |
+
"python/gbnf/utils/errors/grammar_parse_error.py",
|
| 76 |
+
"python/gbnf/utils/errors/grammar_parse_error_test.py",
|
| 77 |
+
"python/gbnf/utils/errors/input_parse_error.py",
|
| 78 |
+
"python/gbnf/utils/errors/input_parse_error_test.py",
|
| 79 |
+
"python/gbnf/utils/is_point_in_range.py",
|
| 80 |
+
"python/gbnf/utils/is_point_in_range_test.py",
|
| 81 |
+
"python/gbnf/utils/validate_non_empty.py",
|
| 82 |
+
"python/pyproject.toml",
|
| 83 |
+
"python/requirements.txt",
|
| 84 |
+
"python/tests/generated/iteration/iteration_test.py",
|
| 85 |
+
"python/tests/generated/iteration/iteration_with_additional_strings_test.py",
|
| 86 |
+
"python/tests/generated/iteration/iteration_with_an_initial_string_test.py",
|
| 87 |
+
"python/tests/generated/validation/validate_grammar_test.py",
|
| 88 |
+
"python/tests/generated/validation/validate_input_test.py",
|
| 89 |
+
"python/uv.lock"
|
| 90 |
+
]
|
| 91 |
+
},
|
| 92 |
+
"sandbox": {
|
| 93 |
+
"image_id": "sha256:947a33363e136096f3af31c1bbbfea944d96dfcc4aecd633f928a5d50ea91c15"
|
| 94 |
+
},
|
| 95 |
+
"harness": {
|
| 96 |
+
"commit": "8422439f49db061ed5b56e9b883ef244807898f8",
|
| 97 |
+
"dirty": true
|
| 98 |
+
}
|
| 99 |
+
}
|
v2-models-effort/runs/20261111-214430-mute-surf/memory.jsonl
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"time": 1794433852.10509, "rss": 31866880, "processes": 3}
|
| 2 |
+
{"time": 1794433857.1190898, "rss": 123088896, "processes": 5}
|
| 3 |
+
{"time": 1794433862.1335764, "rss": 123404288, "processes": 5}
|
| 4 |
+
{"time": 1794433867.1478736, "rss": 384716800, "processes": 6}
|
| 5 |
+
{"time": 1794433872.163396, "rss": 408567808, "processes": 6}
|
| 6 |
+
{"time": 1794433877.1783237, "rss": 407969792, "processes": 6}
|
| 7 |
+
{"time": 1794433882.1924152, "rss": 404205568, "processes": 6}
|
| 8 |
+
{"time": 1794433887.2071776, "rss": 398254080, "processes": 6}
|
| 9 |
+
{"time": 1794433892.2215686, "rss": 394571776, "processes": 6}
|
| 10 |
+
{"time": 1794433897.237107, "rss": 394166272, "processes": 6}
|
| 11 |
+
{"time": 1794433902.2529702, "rss": 393674752, "processes": 6}
|
| 12 |
+
{"time": 1794433907.2680185, "rss": 393170944, "processes": 6}
|
| 13 |
+
{"time": 1794433912.281042, "rss": 393142272, "processes": 6}
|
| 14 |
+
{"time": 1794433917.2952132, "rss": 393142272, "processes": 6}
|
| 15 |
+
{"time": 1794433922.3093562, "rss": 392306688, "processes": 6}
|
| 16 |
+
{"time": 1794433927.3246205, "rss": 392335360, "processes": 6}
|
| 17 |
+
{"time": 1794433932.3392603, "rss": 392544256, "processes": 6}
|
| 18 |
+
{"time": 1794433937.3534436, "rss": 399233024, "processes": 6}
|
| 19 |
+
{"time": 1794433942.3684657, "rss": 397656064, "processes": 6}
|
| 20 |
+
{"time": 1794433947.3825035, "rss": 396222464, "processes": 6}
|
| 21 |
+
{"time": 1794433952.3973353, "rss": 394158080, "processes": 6}
|
| 22 |
+
{"time": 1794433957.4135728, "rss": 394457088, "processes": 6}
|
| 23 |
+
{"time": 1794433962.4287577, "rss": 394706944, "processes": 6}
|
| 24 |
+
{"time": 1794433967.4426143, "rss": 394330112, "processes": 6}
|
| 25 |
+
{"time": 1794433972.4567733, "rss": 394358784, "processes": 6}
|
| 26 |
+
{"time": 1794433977.4712405, "rss": 395649024, "processes": 6}
|
| 27 |
+
{"time": 1794433982.4856098, "rss": 399474688, "processes": 6}
|
| 28 |
+
{"time": 1794433987.499619, "rss": 399659008, "processes": 6}
|
| 29 |
+
{"time": 1794433992.5147622, "rss": 397266944, "processes": 6}
|
| 30 |
+
{"time": 1794433997.5248687, "rss": 396283904, "processes": 6}
|
| 31 |
+
{"time": 1794434002.5362365, "rss": 395157504, "processes": 6}
|
| 32 |
+
{"time": 1794434007.5497785, "rss": 394682368, "processes": 6}
|
| 33 |
+
{"time": 1794434012.5634408, "rss": 408948736, "processes": 6}
|
| 34 |
+
{"time": 1794434017.5767934, "rss": 409157632, "processes": 6}
|
| 35 |
+
{"time": 1794434022.5905242, "rss": 405553152, "processes": 6}
|
| 36 |
+
{"time": 1794434027.604847, "rss": 405549056, "processes": 6}
|
| 37 |
+
{"time": 1794434032.6194777, "rss": 400064512, "processes": 6}
|
| 38 |
+
{"time": 1794434037.633957, "rss": 399511552, "processes": 6}
|
| 39 |
+
{"time": 1794434042.6486137, "rss": 398794752, "processes": 6}
|
| 40 |
+
{"time": 1794434047.663119, "rss": 399294464, "processes": 6}
|
| 41 |
+
{"time": 1794434052.6781602, "rss": 398774272, "processes": 6}
|
| 42 |
+
{"time": 1794434057.6926033, "rss": 398741504, "processes": 6}
|
| 43 |
+
{"time": 1794434062.7075136, "rss": 418168832, "processes": 6}
|
| 44 |
+
{"time": 1794434067.7222567, "rss": 416206848, "processes": 6}
|
| 45 |
+
{"time": 1794434072.737128, "rss": 415911936, "processes": 6}
|
| 46 |
+
{"time": 1794434077.7528036, "rss": 413564928, "processes": 6}
|
| 47 |
+
{"time": 1794434082.7672853, "rss": 413028352, "processes": 6}
|
| 48 |
+
{"time": 1794434087.7814164, "rss": 412966912, "processes": 6}
|
| 49 |
+
{"time": 1794434092.7961915, "rss": 401178624, "processes": 6}
|
| 50 |
+
{"time": 1794434097.8104126, "rss": 401440768, "processes": 6}
|
| 51 |
+
{"time": 1794434102.8247976, "rss": 397418496, "processes": 6}
|
| 52 |
+
{"time": 1794434107.83953, "rss": 397463552, "processes": 6}
|
| 53 |
+
{"time": 1794434112.8535137, "rss": 397090816, "processes": 6}
|
| 54 |
+
{"time": 1794434117.867744, "rss": 396087296, "processes": 6}
|
| 55 |
+
{"time": 1794434122.883175, "rss": 396345344, "processes": 6}
|
| 56 |
+
{"time": 1794434127.8976984, "rss": 396345344, "processes": 6}
|
| 57 |
+
{"time": 1794434132.9123526, "rss": 395546624, "processes": 6}
|
| 58 |
+
{"time": 1794434137.9273484, "rss": 395730944, "processes": 6}
|
| 59 |
+
{"time": 1794434142.942551, "rss": 395722752, "processes": 6}
|
| 60 |
+
{"time": 1794434147.957407, "rss": 395984896, "processes": 6}
|
| 61 |
+
{"time": 1794434152.9722621, "rss": 395669504, "processes": 6}
|
| 62 |
+
{"time": 1794434157.9861245, "rss": 435376128, "processes": 6}
|
| 63 |
+
{"time": 1794434163.001912, "rss": 433483776, "processes": 6}
|
| 64 |
+
{"time": 1794434168.0169613, "rss": 411500544, "processes": 6}
|
| 65 |
+
{"time": 1794434173.0319579, "rss": 410423296, "processes": 6}
|
| 66 |
+
{"time": 1794434178.0461578, "rss": 405655552, "processes": 6}
|
| 67 |
+
{"time": 1794434183.060569, "rss": 418066432, "processes": 6}
|
| 68 |
+
{"time": 1794434188.0751693, "rss": 422154240, "processes": 6}
|
| 69 |
+
{"time": 1794434193.0890265, "rss": 421421056, "processes": 6}
|
| 70 |
+
{"time": 1794434198.1046512, "rss": 417992704, "processes": 6}
|
| 71 |
+
{"time": 1794434203.1195579, "rss": 417742848, "processes": 6}
|
| 72 |
+
{"time": 1794434208.1339989, "rss": 416792576, "processes": 6}
|
| 73 |
+
{"time": 1794434213.1494627, "rss": 407535616, "processes": 6}
|
| 74 |
+
{"time": 1794434218.1640623, "rss": 464547840, "processes": 6}
|
| 75 |
+
{"time": 1794434223.1790195, "rss": 462135296, "processes": 6}
|
| 76 |
+
{"time": 1794434228.1938076, "rss": 458633216, "processes": 6}
|
| 77 |
+
{"time": 1794434233.207974, "rss": 458469376, "processes": 6}
|
| 78 |
+
{"time": 1794434238.2227716, "rss": 457900032, "processes": 6}
|
| 79 |
+
{"time": 1794434243.2376316, "rss": 448315392, "processes": 6}
|
| 80 |
+
{"time": 1794434248.252438, "rss": 448831488, "processes": 6}
|
| 81 |
+
{"time": 1794434253.2678049, "rss": 447979520, "processes": 6}
|
| 82 |
+
{"time": 1794434258.282227, "rss": 448143360, "processes": 6}
|
| 83 |
+
{"time": 1794434263.297312, "rss": 448114688, "processes": 6}
|
| 84 |
+
{"time": 1794434268.3134162, "rss": 448110592, "processes": 6}
|
| 85 |
+
{"time": 1794434273.32773, "rss": 448069632, "processes": 6}
|
| 86 |
+
{"time": 1794434278.3416758, "rss": 448499712, "processes": 6}
|
| 87 |
+
{"time": 1794434283.3568234, "rss": 448110592, "processes": 6}
|
| 88 |
+
{"time": 1794434288.3721747, "rss": 448061440, "processes": 6}
|
| 89 |
+
{"time": 1794434293.3870234, "rss": 448311296, "processes": 6}
|
| 90 |
+
{"time": 1794434298.4014258, "rss": 448311296, "processes": 6}
|
| 91 |
+
{"time": 1794434303.4156055, "rss": 448507904, "processes": 6}
|
| 92 |
+
{"time": 1794434308.4305851, "rss": 448495616, "processes": 6}
|
| 93 |
+
{"time": 1794434313.4454794, "rss": 448172032, "processes": 6}
|
| 94 |
+
{"time": 1794434318.4594238, "rss": 448139264, "processes": 6}
|
| 95 |
+
{"time": 1794434323.4736876, "rss": 448102400, "processes": 6}
|
| 96 |
+
{"time": 1794434328.4886367, "rss": 447815680, "processes": 6}
|
| 97 |
+
{"time": 1794434333.5036306, "rss": 448073728, "processes": 6}
|
| 98 |
+
{"time": 1794434338.5191169, "rss": 461017088, "processes": 6}
|
| 99 |
+
{"time": 1794434343.532303, "rss": 461107200, "processes": 6}
|
| 100 |
+
{"time": 1794434348.544224, "rss": 453369856, "processes": 6}
|
| 101 |
+
{"time": 1794434353.5570378, "rss": 448593920, "processes": 6}
|
| 102 |
+
{"time": 1794434358.5702763, "rss": 446099456, "processes": 6}
|
| 103 |
+
{"time": 1794434363.5836046, "rss": 462102528, "processes": 6}
|
| 104 |
+
{"time": 1794434368.5957098, "rss": 465567744, "processes": 6}
|
| 105 |
+
{"time": 1794434373.6105032, "rss": 461979648, "processes": 6}
|
| 106 |
+
{"time": 1794434378.625723, "rss": 476520448, "processes": 6}
|
| 107 |
+
{"time": 1794434383.6412127, "rss": 474071040, "processes": 6}
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
node_modules
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/README.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GBNF
|
| 2 |
+
|
| 3 |
+
A library for parsing `.gbnf` grammar files in TypeScript. This is a port of the Python `gbnf` package; the
|
| 4 |
+
module layout and names (`gbnf/rules_builder/parse_char.ts`, `build_rule_stack`, …) mirror the Python source.
|
| 5 |
+
|
| 6 |
+
```ts
|
| 7 |
+
import { GBNF, InputParseError, RuleChar } from './gbnf/index.js';
|
| 8 |
+
|
| 9 |
+
let state = GBNF('root ::= "foo" | "bar"'); // optionally: GBNF(grammar, initial_string)
|
| 10 |
+
[...state]; // [RuleChar { value: [102] }, RuleChar { value: [98] }]
|
| 11 |
+
state = state.add('fo'); // or state('fo'); throws InputParseError on invalid input
|
| 12 |
+
state.size; // number of unique rules
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
Notes on Python → TypeScript mapping:
|
| 16 |
+
|
| 17 |
+
- `state + "text"` / `state("text")` → `state.add("text")` / `state("text")`
|
| 18 |
+
- `len(x)` → `x.length` (`Pointers`, `SymbolIds`), `symbol_ids[key]` → `symbol_ids.get(key)`
|
| 19 |
+
- `str(error)` → `String(error)` (also available as `error.message`)
|
| 20 |
+
- `rule.__dict__` → `rule.toJSON()`
|
| 21 |
+
- `ValueError`, `IndexError`, `KeyError` → `Error` subclasses of the same name (`gbnf/utils/py.ts`)
|
| 22 |
+
|
| 23 |
+
## Tests
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
vitest run # everything
|
| 27 |
+
vitest run gbnf # unit tests (colocated *.test.ts)
|
| 28 |
+
vitest run tests # integration tests (tests/generated)
|
| 29 |
+
```
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/GBNF.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Graph } from './grammar_graph/graph.js';
|
| 2 |
+
import { ParseState } from './grammar_graph/parse_state.js';
|
| 3 |
+
import { build_rule_stack } from './grammar_parser/build_rule_stack.js';
|
| 4 |
+
import { GrammarParseError, RulesBuilder } from './rules_builder/index.js';
|
| 5 |
+
import { ValueError } from './utils/py.js';
|
| 6 |
+
|
| 7 |
+
// ValidInput = str | int | float | list[int | float]
|
| 8 |
+
|
| 9 |
+
export const GBNF = (grammar: string, initial_string = ''): ParseState => {
|
| 10 |
+
if (typeof grammar !== 'string') {
|
| 11 |
+
throw new ValueError('grammar must be a string');
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
if (typeof initial_string !== 'string') {
|
| 15 |
+
throw new ValueError('input must be a string');
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
const rules_builder = new RulesBuilder(grammar);
|
| 19 |
+
const { rules, symbol_ids } = rules_builder;
|
| 20 |
+
if (rules.length === 0) {
|
| 21 |
+
throw new GrammarParseError(grammar, 0, 'No rules were found');
|
| 22 |
+
}
|
| 23 |
+
// raises if the grammar does not define a root rule
|
| 24 |
+
const root_id: number = symbol_ids.get('root');
|
| 25 |
+
|
| 26 |
+
const stacked_rules = rules.map((rule) => build_rule_stack(rule));
|
| 27 |
+
const graph = new Graph(grammar, stacked_rules, root_id);
|
| 28 |
+
return new ParseState(graph, graph.add(initial_string));
|
| 29 |
+
};
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/colorize.test.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { Color, colorize } from './colorize.js';
|
| 4 |
+
|
| 5 |
+
test('colorize strings', () => {
|
| 6 |
+
expect(colorize('hello', Color.BLUE)).toEqual('\x1b[34mhello');
|
| 7 |
+
expect(colorize('test', Color.CYAN)).toEqual('\x1b[36mtest');
|
| 8 |
+
expect(colorize('example', Color.GREEN)).toEqual('\x1b[32mexample');
|
| 9 |
+
});
|
| 10 |
+
|
| 11 |
+
test('colorize numbers', () => {
|
| 12 |
+
expect(colorize(123, Color.RED)).toEqual('\x1b[31m123');
|
| 13 |
+
expect(colorize(456, Color.GRAY)).toEqual('\x1b[90m456');
|
| 14 |
+
expect(colorize(789, Color.YELLOW)).toEqual('\x1b[33m789');
|
| 15 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/colorize.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export const Color = {
|
| 2 |
+
BLUE: '\x1b[34m',
|
| 3 |
+
CYAN: '\x1b[36m',
|
| 4 |
+
GREEN: '\x1b[32m',
|
| 5 |
+
RED: '\x1b[31m',
|
| 6 |
+
GRAY: '\x1b[90m',
|
| 7 |
+
YELLOW: '\x1b[33m',
|
| 8 |
+
} as const;
|
| 9 |
+
|
| 10 |
+
export const colorize = (text: string | number, color: string): string => `${color}${text}`;
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_input_as_code_points.test.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { get_input_as_code_points } from './get_input_as_code_points.js';
|
| 4 |
+
|
| 5 |
+
describe('get_input_as_code_points', () => {
|
| 6 |
+
test('it returns code points for string', () => {
|
| 7 |
+
expect(get_input_as_code_points('abc')).toEqual([97, 98, 99]);
|
| 8 |
+
});
|
| 9 |
+
|
| 10 |
+
test('it returns code points for astral characters', () => {
|
| 11 |
+
expect(get_input_as_code_points('a😀')).toEqual([97, 0x1f600]);
|
| 12 |
+
});
|
| 13 |
+
|
| 14 |
+
test('it returns code points for number', () => {
|
| 15 |
+
expect(get_input_as_code_points(99)).toEqual([99]);
|
| 16 |
+
});
|
| 17 |
+
|
| 18 |
+
test('it returns code points for array of number', () => {
|
| 19 |
+
expect(get_input_as_code_points([99, 100, 101])).toEqual([99, 100, 101]);
|
| 20 |
+
});
|
| 21 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_input_as_code_points.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ValueError, ord, repr } from '../utils/py.js';
|
| 2 |
+
import type { ValidInput } from './grammar_graph_types.js';
|
| 3 |
+
|
| 4 |
+
const is_int = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value);
|
| 5 |
+
|
| 6 |
+
export const get_code_point = (char: string): number => {
|
| 7 |
+
const code_point = ord(char);
|
| 8 |
+
if (code_point === undefined || code_point === null) {
|
| 9 |
+
throw new ValueError(`Could not get code point for character: ${char}`);
|
| 10 |
+
}
|
| 11 |
+
if (!is_int(code_point)) {
|
| 12 |
+
throw new ValueError('code_point must be an integer!');
|
| 13 |
+
}
|
| 14 |
+
return code_point;
|
| 15 |
+
};
|
| 16 |
+
|
| 17 |
+
export const get_input_as_code_points = (src: ValidInput): number[] => {
|
| 18 |
+
if (is_int(src)) {
|
| 19 |
+
return [src];
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
if (Array.isArray(src)) {
|
| 23 |
+
for (const c of src) {
|
| 24 |
+
if (!is_int(c)) {
|
| 25 |
+
throw new ValueError(`code_point must be an integer for ${repr(c)} if src is a list`);
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
return src;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
if (typeof src === 'string') {
|
| 32 |
+
return Array.from(src, (s) => get_code_point(s));
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
throw new ValueError(`Invalid input type: ${typeof src}`);
|
| 36 |
+
};
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_parent_stack_id.test.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { Color } from './colorize.js';
|
| 4 |
+
import { get_parent_stack_id } from './get_parent_stack_id.js';
|
| 5 |
+
import { RuleEnd } from './grammar_graph_types.js';
|
| 6 |
+
import { GraphNode } from './graph_node.js';
|
| 7 |
+
import { GraphPointer } from './graph_pointer.js';
|
| 8 |
+
|
| 9 |
+
const s = (str: string): string => JSON.stringify(str);
|
| 10 |
+
|
| 11 |
+
const mock_colorize = (text: string | number, color: string): string => `[${s(color)}]:${text}`;
|
| 12 |
+
|
| 13 |
+
const red = s(Color.RED);
|
| 14 |
+
const gray = s(Color.GRAY);
|
| 15 |
+
|
| 16 |
+
const create_mock_pointer = (
|
| 17 |
+
stack_id: number,
|
| 18 |
+
path_id: number,
|
| 19 |
+
step_id: number,
|
| 20 |
+
parent: GraphPointer | null = null,
|
| 21 |
+
): GraphPointer =>
|
| 22 |
+
new GraphPointer(
|
| 23 |
+
new GraphNode(new RuleEnd(), {
|
| 24 |
+
stackId: stack_id,
|
| 25 |
+
pathId: path_id,
|
| 26 |
+
stepId: step_id,
|
| 27 |
+
}),
|
| 28 |
+
parent,
|
| 29 |
+
);
|
| 30 |
+
|
| 31 |
+
describe('get_parent_stack_id', () => {
|
| 32 |
+
test('returns an empty string if no parents', () => {
|
| 33 |
+
const pointer = create_mock_pointer(1, 1, 1);
|
| 34 |
+
expect(get_parent_stack_id(pointer, mock_colorize)).toEqual('');
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
test('returns a single parent id colored correctly', () => {
|
| 38 |
+
const parent_pointer = create_mock_pointer(1, 1, 1);
|
| 39 |
+
const pointer = create_mock_pointer(2, 2, 2, parent_pointer);
|
| 40 |
+
expect(get_parent_stack_id(pointer, mock_colorize)).toEqual(`[${red}]:1,1,1`);
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
test('returns multiple parent ids separated by colored arrows', () => {
|
| 44 |
+
const grandparent_pointer = create_mock_pointer(0, 0, 0);
|
| 45 |
+
const parent_pointer = create_mock_pointer(1, 1, 1, grandparent_pointer);
|
| 46 |
+
const pointer = create_mock_pointer(2, 2, 2, parent_pointer);
|
| 47 |
+
expect(get_parent_stack_id(pointer, mock_colorize)).toEqual(`[${red}]:1,1,1[${gray}]:<-[${red}]:0,0,0`);
|
| 48 |
+
});
|
| 49 |
+
|
| 50 |
+
test('handles deep nesting of pointers', () => {
|
| 51 |
+
const great_grandparent_pointer = create_mock_pointer(0, 0, 0);
|
| 52 |
+
const grandparent_pointer = create_mock_pointer(1, 1, 1, great_grandparent_pointer);
|
| 53 |
+
const parent_pointer = create_mock_pointer(2, 2, 2, grandparent_pointer);
|
| 54 |
+
const pointer = create_mock_pointer(3, 3, 3, parent_pointer);
|
| 55 |
+
expect(get_parent_stack_id(pointer, mock_colorize)).toEqual(
|
| 56 |
+
`[${red}]:2,2,2[${gray}]:<-[${red}]:1,1,1[${gray}]:<-[${red}]:0,0,0`,
|
| 57 |
+
);
|
| 58 |
+
});
|
| 59 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_parent_stack_id.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Color } from './colorize.js';
|
| 2 |
+
import type { GraphPointer } from './graph_pointer.js';
|
| 3 |
+
|
| 4 |
+
export const get_parent_stack_id = (
|
| 5 |
+
pointer: GraphPointer<any>,
|
| 6 |
+
col: (text: string | number, color: string) => string,
|
| 7 |
+
): string => {
|
| 8 |
+
const stack_ids: string[] = [];
|
| 9 |
+
let parent: GraphPointer<any> | null | undefined = pointer.parent;
|
| 10 |
+
while (parent) {
|
| 11 |
+
stack_ids.push(`${parent.node.meta.stackId},${parent.node.meta.pathId},${parent.node.meta.stepId}`);
|
| 12 |
+
parent = parent.parent;
|
| 13 |
+
}
|
| 14 |
+
const arrow = col('<-', Color.GRAY);
|
| 15 |
+
return stack_ids.map((stack_id) => col(stack_id, Color.RED)).join(arrow);
|
| 16 |
+
};
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_serialized_rule_key.test.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { KEY_TRANSLATION, get_serialized_rule_key } from './get_serialized_rule_key.js';
|
| 4 |
+
import { RuleChar, RuleCharExclude, RuleEnd, RuleRef } from './grammar_graph_types.js';
|
| 5 |
+
import { is_rule_char, is_rule_char_exclude, is_rule_end, is_rule_ref } from './type_guards.js';
|
| 6 |
+
|
| 7 |
+
vi.mock('./type_guards.js', () => ({
|
| 8 |
+
is_rule_end: vi.fn(),
|
| 9 |
+
is_rule_char: vi.fn(),
|
| 10 |
+
is_rule_char_exclude: vi.fn(),
|
| 11 |
+
is_rule_ref: vi.fn(),
|
| 12 |
+
}));
|
| 13 |
+
|
| 14 |
+
describe('get_serialized_rule_key', () => {
|
| 15 |
+
beforeEach(() => {
|
| 16 |
+
vi.mocked(is_rule_end).mockReturnValue(false);
|
| 17 |
+
vi.mocked(is_rule_char).mockReturnValue(false);
|
| 18 |
+
vi.mocked(is_rule_char_exclude).mockReturnValue(false);
|
| 19 |
+
vi.mocked(is_rule_ref).mockReturnValue(false);
|
| 20 |
+
});
|
| 21 |
+
|
| 22 |
+
test('returns type for end rules', () => {
|
| 23 |
+
vi.mocked(is_rule_end).mockReturnValue(true);
|
| 24 |
+
const rule = new RuleEnd();
|
| 25 |
+
expect(get_serialized_rule_key(rule)).toEqual(`${KEY_TRANSLATION.get(RuleEnd)}`);
|
| 26 |
+
expect(get_serialized_rule_key(rule)).toEqual('0');
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
test('returns type and value for character rules', () => {
|
| 30 |
+
vi.mocked(is_rule_char).mockReturnValue(true);
|
| 31 |
+
const rule = new RuleChar([97]);
|
| 32 |
+
expect(get_serialized_rule_key(rule)).toEqual(`${KEY_TRANSLATION.get(RuleChar)}-[97]`);
|
| 33 |
+
expect(get_serialized_rule_key(rule)).toEqual('1-[97]');
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
test('serializes values like json.dumps', () => {
|
| 37 |
+
vi.mocked(is_rule_char).mockReturnValue(true);
|
| 38 |
+
const rule = new RuleChar([97, [98, 100]]);
|
| 39 |
+
expect(get_serialized_rule_key(rule)).toEqual('1-[97, [98, 100]]');
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
test('returns type and value for character exclude rules', () => {
|
| 43 |
+
vi.mocked(is_rule_char_exclude).mockReturnValue(true);
|
| 44 |
+
const rule = new RuleCharExclude([97]);
|
| 45 |
+
expect(get_serialized_rule_key(rule)).toEqual(`${KEY_TRANSLATION.get(RuleCharExclude)}-[97]`);
|
| 46 |
+
expect(get_serialized_rule_key(rule)).toEqual('2-[97]');
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
test('returns ref type with value for reference rules', () => {
|
| 50 |
+
vi.mocked(is_rule_ref).mockReturnValue(true);
|
| 51 |
+
const rule = new RuleRef(99);
|
| 52 |
+
expect(get_serialized_rule_key(rule)).toEqual('3-99');
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
test('throws error for unknown rule types', () => {
|
| 56 |
+
const rule = { type: 'UNKNOWN', value: 'something' };
|
| 57 |
+
expect(() => get_serialized_rule_key(rule as any)).toThrow(
|
| 58 |
+
"Unknown rule type: {'type': 'UNKNOWN', 'value': 'something'}",
|
| 59 |
+
);
|
| 60 |
+
});
|
| 61 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/get_serialized_rule_key.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { AssertionError, ValueError, json_dumps, repr } from '../utils/py.js';
|
| 2 |
+
import { RuleChar, RuleCharExclude, RuleEnd, RuleRef, type UnresolvedRule } from './grammar_graph_types.js';
|
| 3 |
+
import { is_rule_char, is_rule_char_exclude, is_rule_end, is_rule_ref } from './type_guards.js';
|
| 4 |
+
|
| 5 |
+
export const KEY_TRANSLATION = new Map<unknown, number>([
|
| 6 |
+
[RuleEnd, 0],
|
| 7 |
+
[RuleChar, 1],
|
| 8 |
+
[RuleCharExclude, 2],
|
| 9 |
+
]);
|
| 10 |
+
|
| 11 |
+
const assert_instance = (rule: unknown, cls: new (...args: any[]) => unknown): void => {
|
| 12 |
+
if (!(rule instanceof cls)) {
|
| 13 |
+
throw new AssertionError();
|
| 14 |
+
}
|
| 15 |
+
};
|
| 16 |
+
|
| 17 |
+
export const get_serialized_rule_key = (rule: UnresolvedRule): string => {
|
| 18 |
+
if (is_rule_end(rule)) {
|
| 19 |
+
return `${KEY_TRANSLATION.get(RuleEnd)}`;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
if (is_rule_char(rule)) {
|
| 23 |
+
assert_instance(rule, RuleChar);
|
| 24 |
+
return `${KEY_TRANSLATION.get(RuleChar)}-${json_dumps(rule.value)}`;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
if (is_rule_char_exclude(rule)) {
|
| 28 |
+
assert_instance(rule, RuleCharExclude);
|
| 29 |
+
return `${KEY_TRANSLATION.get(RuleCharExclude)}-${json_dumps((rule as RuleCharExclude).value)}`;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
if (is_rule_ref(rule)) {
|
| 33 |
+
assert_instance(rule, RuleRef);
|
| 34 |
+
return `3-${(rule as RuleRef).value}`;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
throw new ValueError(`Unknown rule type: ${repr(rule)}`);
|
| 38 |
+
};
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/grammar_graph_types.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { json_dumps } from '../utils/py.js';
|
| 2 |
+
import type { GraphPointer } from './graph_pointer.js';
|
| 3 |
+
import { RuleRef } from './rule_ref.js';
|
| 4 |
+
|
| 5 |
+
export { RuleRef };
|
| 6 |
+
|
| 7 |
+
export interface PrintOpts {
|
| 8 |
+
pointers?: Iterable<GraphPointer>;
|
| 9 |
+
colorize: (text: string | number, color: string) => string;
|
| 10 |
+
show_position?: boolean;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
export type Range = [number, number];
|
| 14 |
+
|
| 15 |
+
export class Rule {
|
| 16 |
+
// mirrors the Python `__dict__` of a rule
|
| 17 |
+
toJSON(): { type: string; value?: unknown } {
|
| 18 |
+
return { type: this.constructor.name };
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
toString(): string {
|
| 22 |
+
return `${this.constructor.name}()`;
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export class RuleWithValue<T = unknown> extends Rule {
|
| 27 |
+
value: T;
|
| 28 |
+
|
| 29 |
+
constructor(value: T) {
|
| 30 |
+
super();
|
| 31 |
+
this.value = value;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
toJSON(): { type: string; value?: unknown } {
|
| 35 |
+
return { type: this.constructor.name, value: this.value };
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
toString(): string {
|
| 39 |
+
return `${this.constructor.name}(value=${json_dumps(this.value)})`;
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export class RuleWithListOfIntsOrRanges extends RuleWithValue<(number | Range)[]> {
|
| 44 |
+
constructor(value: (number | Range)[] = []) {
|
| 45 |
+
super([...value]);
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
export class RuleChar extends RuleWithListOfIntsOrRanges {}
|
| 50 |
+
|
| 51 |
+
export class RuleCharExclude extends RuleWithListOfIntsOrRanges {}
|
| 52 |
+
|
| 53 |
+
export class RuleEnd extends Rule {}
|
| 54 |
+
|
| 55 |
+
export type UnresolvedRule = RuleChar | RuleCharExclude | RuleRef | RuleEnd;
|
| 56 |
+
|
| 57 |
+
// ValidInput can either be a string, or a number indicating a code point.
|
| 58 |
+
// It CANNOT be a number representing a number; a number intended as input (like "8")
|
| 59 |
+
// should be passed in as a string.
|
| 60 |
+
export type ValidInput = string | number | number[];
|
| 61 |
+
|
| 62 |
+
// RuleRefs should never be exposed to the end user.
|
| 63 |
+
export type ResolvedRule = RuleCharExclude | RuleChar | RuleEnd;
|
| 64 |
+
|
| 65 |
+
export type ResolvedGraphPointer = GraphPointer<ResolvedRule>;
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph.test.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { RuleChar, RuleCharExclude, RuleEnd, RuleRef, type UnresolvedRule } from './grammar_graph_types.js';
|
| 4 |
+
import { Graph } from './graph.js';
|
| 5 |
+
import { GraphNode } from './graph_node.js';
|
| 6 |
+
import { GraphPointer } from './graph_pointer.js';
|
| 7 |
+
import { Pointers } from './pointers.js';
|
| 8 |
+
import { is_rule } from './type_guards.js';
|
| 9 |
+
|
| 10 |
+
describe('Graph', () => {
|
| 11 |
+
const grammar = 'example-grammar';
|
| 12 |
+
const stackedRules: UnresolvedRule[][][] = [
|
| 13 |
+
[[new RuleChar([65, 66, 67])], [new RuleChar([68, 69, 70])]],
|
| 14 |
+
[[new RuleChar([71, 72, 73])], [new RuleChar([74, 75, 76])]],
|
| 15 |
+
];
|
| 16 |
+
const root_id = 0;
|
| 17 |
+
|
| 18 |
+
test('should create a graph instance', () => {
|
| 19 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 20 |
+
expect(graph).toBeInstanceOf(Graph);
|
| 21 |
+
expect(graph.grammar).toEqual(grammar);
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
test('should get the root node', () => {
|
| 25 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 26 |
+
const root_node = graph.__get_root_node__(root_id);
|
| 27 |
+
expect(root_node).toBeInstanceOf(Map);
|
| 28 |
+
expect(root_node.size).toEqual(2);
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
test('should raise for an unknown root node', () => {
|
| 32 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 33 |
+
expect(() => graph.__get_root_node__(5)).toThrow('Root node not found for value: 5');
|
| 34 |
+
expect(() => new Graph(grammar, stackedRules, 5)).toThrow('Root node not found for value: 5');
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
test('should get the initial pointers', () => {
|
| 38 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 39 |
+
const pointers = graph.__get_initial_pointers__();
|
| 40 |
+
expect(pointers).toBeInstanceOf(Pointers);
|
| 41 |
+
expect(pointers.length).toEqual(2);
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
test('should print the graph', () => {
|
| 45 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 46 |
+
const printed_graph = graph.print(null, true);
|
| 47 |
+
expect(typeof printed_graph).toEqual('string');
|
| 48 |
+
expect(printed_graph.length).toBeGreaterThan(0);
|
| 49 |
+
expect(graph.print()).toEqual(['{0,0,0}[ABC]', '{0,1,0}[DEF]', '{1,0,0}[GHI]', '{1,1,0}[JKL]'].join('\n'));
|
| 50 |
+
});
|
| 51 |
+
|
| 52 |
+
test('should iterate over pointers', () => {
|
| 53 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 54 |
+
const mock_pointers = new Pointers(
|
| 55 |
+
...[
|
| 56 |
+
new RuleChar([65, 66, 67]),
|
| 57 |
+
new RuleChar([68, 69, 70]),
|
| 58 |
+
new RuleChar([71, 72, 73]),
|
| 59 |
+
new RuleChar([74, 75, 76]),
|
| 60 |
+
new RuleCharExclude([1]),
|
| 61 |
+
new RuleEnd(),
|
| 62 |
+
].map((r, i) => new GraphPointer(new GraphNode(r, { stackId: i, pathId: 0, stepId: 0 }))),
|
| 63 |
+
);
|
| 64 |
+
|
| 65 |
+
const result = [...graph.__iterate_over_pointers__(mock_pointers)];
|
| 66 |
+
expect(result).toHaveLength(6);
|
| 67 |
+
for (const [rule, pointers] of result) {
|
| 68 |
+
expect(is_rule(rule)).toBe(true);
|
| 69 |
+
expect(pointers.length).toBeGreaterThanOrEqual(1);
|
| 70 |
+
for (const pointer of pointers) {
|
| 71 |
+
expect([...mock_pointers]).toContain(pointer);
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
test('should raise error on reference rule', () => {
|
| 77 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 78 |
+
const mock_pointers = [new GraphPointer(new GraphNode(new RuleRef(0), { stackId: 0, pathId: 0, stepId: 0 }))];
|
| 79 |
+
|
| 80 |
+
expect(() => [...graph.__iterate_over_pointers__(mock_pointers)]).toThrow(
|
| 81 |
+
'Encountered a reference rule in the graph',
|
| 82 |
+
);
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
test('should raise if src is not a string', () => {
|
| 86 |
+
const graph = new Graph(grammar, stackedRules, root_id);
|
| 87 |
+
expect(() => graph.add(65)).toThrow('src must be a string in graph.add');
|
| 88 |
+
});
|
| 89 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph.ts
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { InputParseError } from '../utils/errors/index.js';
|
| 2 |
+
import { is_point_in_range } from '../utils/is_point_in_range.js';
|
| 3 |
+
import { ValueError, repr } from '../utils/py.js';
|
| 4 |
+
import { colorize } from './colorize.js';
|
| 5 |
+
import { get_input_as_code_points } from './get_input_as_code_points.js';
|
| 6 |
+
import { get_serialized_rule_key } from './get_serialized_rule_key.js';
|
| 7 |
+
import type { ResolvedGraphPointer, UnresolvedRule, ValidInput } from './grammar_graph_types.js';
|
| 8 |
+
import { GraphNode } from './graph_node.js';
|
| 9 |
+
import { GraphPointer } from './graph_pointer.js';
|
| 10 |
+
import { Pointers } from './pointers.js';
|
| 11 |
+
import type { RuleRef } from './rule_ref.js';
|
| 12 |
+
import { is_range, is_rule_char, is_rule_char_exclude, is_rule_end, is_rule_ref } from './type_guards.js';
|
| 13 |
+
|
| 14 |
+
export type RootNode = Map<number, GraphNode>;
|
| 15 |
+
|
| 16 |
+
export class Graph {
|
| 17 |
+
__roots__: Map<number, RootNode>;
|
| 18 |
+
grammar: string;
|
| 19 |
+
__rootNode__: RootNode | null;
|
| 20 |
+
previous_code_points: number[];
|
| 21 |
+
|
| 22 |
+
constructor(grammar: string, stacked_rules: UnresolvedRule[][][], root_id: number) {
|
| 23 |
+
this.__roots__ = new Map();
|
| 24 |
+
this.grammar = grammar;
|
| 25 |
+
this.previous_code_points = [];
|
| 26 |
+
const rule_refs: RuleRef[] = [];
|
| 27 |
+
const unique_rules = new Map<string, UnresolvedRule>();
|
| 28 |
+
|
| 29 |
+
for (let stack_id = 0; stack_id < stacked_rules.length; stack_id++) {
|
| 30 |
+
const stack = stacked_rules[stack_id];
|
| 31 |
+
const nodes: RootNode = new Map();
|
| 32 |
+
for (let path_id = 0; path_id < stack.length; path_id++) {
|
| 33 |
+
const path = stack[path_id];
|
| 34 |
+
let node: GraphNode | null = null;
|
| 35 |
+
for (let step_id = path.length - 1; step_id >= 0; step_id--) {
|
| 36 |
+
const next_node: GraphNode | null = node;
|
| 37 |
+
const rule = stack[path_id][step_id];
|
| 38 |
+
unique_rules.set(get_serialized_rule_key(rule), rule);
|
| 39 |
+
if (is_rule_ref(rule)) {
|
| 40 |
+
rule_refs.push(rule);
|
| 41 |
+
}
|
| 42 |
+
// rules coming in may be identical but have different references.
|
| 43 |
+
// here, we ensure we always use the same reference for an identical rule.
|
| 44 |
+
// this makes future comparisons easier.
|
| 45 |
+
const unique_rule = unique_rules.get(get_serialized_rule_key(rule));
|
| 46 |
+
if (unique_rule === undefined) {
|
| 47 |
+
throw new ValueError('Could not get unique rule');
|
| 48 |
+
}
|
| 49 |
+
node = new GraphNode(
|
| 50 |
+
unique_rule,
|
| 51 |
+
{
|
| 52 |
+
stackId: stack_id,
|
| 53 |
+
pathId: path_id,
|
| 54 |
+
stepId: step_id,
|
| 55 |
+
},
|
| 56 |
+
next_node,
|
| 57 |
+
);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
if (node === null) {
|
| 61 |
+
throw new ValueError('Could not get node');
|
| 62 |
+
}
|
| 63 |
+
nodes.set(path_id, node);
|
| 64 |
+
}
|
| 65 |
+
this.__roots__.set(stack_id, nodes);
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
const root_node = this.__roots__.get(root_id);
|
| 69 |
+
if (root_node === undefined) {
|
| 70 |
+
throw new ValueError(`Root node not found for value: ${root_id}`);
|
| 71 |
+
}
|
| 72 |
+
this.__rootNode__ = root_node;
|
| 73 |
+
|
| 74 |
+
for (const rule_ref of rule_refs) {
|
| 75 |
+
const referenced_nodes = new Set<GraphNode>();
|
| 76 |
+
for (const node of this.__get_root_node__(rule_ref.value).values()) {
|
| 77 |
+
referenced_nodes.add(node);
|
| 78 |
+
}
|
| 79 |
+
rule_ref.nodes = referenced_nodes;
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
__get_root_node__(value: number): RootNode {
|
| 84 |
+
const root_node = this.__roots__.get(value);
|
| 85 |
+
if (root_node === undefined) {
|
| 86 |
+
throw new ValueError(`Root node not found for value: ${value}`);
|
| 87 |
+
}
|
| 88 |
+
return root_node;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
__get_initial_pointers__(): Pointers {
|
| 92 |
+
const pointers = new Pointers();
|
| 93 |
+
|
| 94 |
+
const root_node = this.__rootNode__;
|
| 95 |
+
if (root_node === null || root_node === undefined) {
|
| 96 |
+
throw new ValueError('Root node is not defined');
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
for (const [node, parent] of this.__fetch_nodes_for_root_node__(root_node)) {
|
| 100 |
+
const pointer = new GraphPointer(node, parent);
|
| 101 |
+
for (const resolved_pointer of this.__resolve_pointer__(pointer)) {
|
| 102 |
+
pointers.add(resolved_pointer);
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
return pointers;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
__set_valid__(pointers: Iterable<GraphPointer<any>>, valid: boolean): void {
|
| 109 |
+
for (const pointer of pointers) {
|
| 110 |
+
pointer.valid = valid;
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
__parse__(current_pointers: Pointers, code_point: number): Pointers {
|
| 115 |
+
for (const [rule, graph_pointers] of this.__iterate_over_pointers__(current_pointers)) {
|
| 116 |
+
if (is_rule_char(rule)) {
|
| 117 |
+
let valid = false;
|
| 118 |
+
for (const possible_code_point of rule.value) {
|
| 119 |
+
if (valid === true) {
|
| 120 |
+
// pass
|
| 121 |
+
} else if (is_range(possible_code_point)) {
|
| 122 |
+
if (is_point_in_range(code_point, possible_code_point)) {
|
| 123 |
+
valid = true;
|
| 124 |
+
}
|
| 125 |
+
} else if (code_point === possible_code_point) {
|
| 126 |
+
valid = true;
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
this.__set_valid__(graph_pointers, valid);
|
| 130 |
+
} else if (is_rule_char_exclude(rule)) {
|
| 131 |
+
let valid = true;
|
| 132 |
+
for (const possible_code_point of rule.value) {
|
| 133 |
+
if (valid === false) {
|
| 134 |
+
// pass
|
| 135 |
+
} else if (is_range(possible_code_point)) {
|
| 136 |
+
if (is_point_in_range(code_point, possible_code_point)) {
|
| 137 |
+
valid = false;
|
| 138 |
+
}
|
| 139 |
+
} else if (code_point === possible_code_point) {
|
| 140 |
+
valid = false;
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
this.__set_valid__(graph_pointers, valid);
|
| 144 |
+
} else if (!is_rule_end(rule)) {
|
| 145 |
+
throw new ValueError(`Unsupported rule: ${repr(rule)}`);
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
// a pointer's id is the sum of its node's id and its parent's id chain.
|
| 150 |
+
// if two pointers share the same id, it means they point to the same node and have identical parent chains.
|
| 151 |
+
// for the purposes of walking the graph, we only need to keep one of them.
|
| 152 |
+
const next_pointers = new Pointers();
|
| 153 |
+
for (const current_pointer of current_pointers) {
|
| 154 |
+
for (const unresolved_next_pointer of current_pointer.fetch_next()) {
|
| 155 |
+
for (const resolved_next_pointer of this.__resolve_pointer__(unresolved_next_pointer)) {
|
| 156 |
+
next_pointers.add(resolved_next_pointer);
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
return next_pointers;
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
*__resolve_pointer__(unresolved_pointer: GraphPointer<any>): IterableIterator<ResolvedGraphPointer> {
|
| 164 |
+
for (const resolved_pointer of unresolved_pointer.resolve()) {
|
| 165 |
+
if (is_rule_ref(resolved_pointer.node.rule)) {
|
| 166 |
+
throw new ValueError('Encountered a reference rule when building pointers to the graph');
|
| 167 |
+
}
|
| 168 |
+
if (is_rule_end(resolved_pointer.node.rule) && resolved_pointer.parent !== null) {
|
| 169 |
+
throw new ValueError('Encountered an ending rule with a parent when building pointers to the graph');
|
| 170 |
+
}
|
| 171 |
+
yield resolved_pointer;
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
add(src: ValidInput, pointers: Pointers | null = null): Pointers {
|
| 176 |
+
if (typeof src !== 'string') {
|
| 177 |
+
throw new ValueError('src must be a string in graph.add');
|
| 178 |
+
}
|
| 179 |
+
// an empty set of pointers is treated the same as no pointers at all
|
| 180 |
+
let current_pointers = pointers && pointers.length !== 0 ? pointers : this.__get_initial_pointers__();
|
| 181 |
+
|
| 182 |
+
const code_points = get_input_as_code_points(src);
|
| 183 |
+
for (const code_point of code_points) {
|
| 184 |
+
if (!Number.isInteger(code_point)) {
|
| 185 |
+
throw new ValueError('code_point must be an integer!');
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
for (let code_point_pos = 0; code_point_pos < code_points.length; code_point_pos++) {
|
| 190 |
+
const code_point = code_points[code_point_pos];
|
| 191 |
+
current_pointers = this.__parse__(current_pointers, code_point);
|
| 192 |
+
if (current_pointers.length === 0) {
|
| 193 |
+
throw new InputParseError(code_points, code_point_pos, this.previous_code_points);
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
this.previous_code_points.push(...code_points);
|
| 197 |
+
return current_pointers;
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
// generator that yields either the node, or if a reference rule, the referenced node
|
| 201 |
+
// we need these function, as distinct from leveraging the logic in GraphPointer,
|
| 202 |
+
// because that needs a rule ref with already defined nodes; this function is used to _set_ those nodes
|
| 203 |
+
*__fetch_nodes_for_root_node__(
|
| 204 |
+
root_nodes: RootNode,
|
| 205 |
+
parent: GraphPointer<any> | null = null,
|
| 206 |
+
): IterableIterator<[GraphNode, GraphPointer<any> | null]> {
|
| 207 |
+
for (const node of root_nodes.values()) {
|
| 208 |
+
if (is_rule_ref(node.rule)) {
|
| 209 |
+
yield* this.__fetch_nodes_for_root_node__(
|
| 210 |
+
this.__get_root_node__(node.rule.value),
|
| 211 |
+
new GraphPointer(node, parent),
|
| 212 |
+
);
|
| 213 |
+
} else {
|
| 214 |
+
yield [node, parent];
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
print(pointers: Pointers | null = null, colors = false): string {
|
| 220 |
+
const nodes: GraphNode[][] = [...this.__roots__.values()].map((root_node) => [...root_node.values()]);
|
| 221 |
+
const print_pointers = pointers ?? new Pointers();
|
| 222 |
+
const graph_view: string[] = [];
|
| 223 |
+
for (const root_node of nodes) {
|
| 224 |
+
for (const node of root_node) {
|
| 225 |
+
graph_view.push(
|
| 226 |
+
node.print({
|
| 227 |
+
pointers: print_pointers,
|
| 228 |
+
show_position: true,
|
| 229 |
+
colorize: colors ? colorize : (s: string | number, _: string) => String(s),
|
| 230 |
+
}),
|
| 231 |
+
);
|
| 232 |
+
}
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
return graph_view.join('\n');
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
*__iterate_over_pointers__(
|
| 239 |
+
pointers: Iterable<GraphPointer<any>>,
|
| 240 |
+
): IterableIterator<[UnresolvedRule, GraphPointer<any>[]]> {
|
| 241 |
+
const seen_rules = new Map<UnresolvedRule, GraphPointer<any>[]>();
|
| 242 |
+
for (const pointer of pointers) {
|
| 243 |
+
const rule = pointer.rule;
|
| 244 |
+
if (is_rule_ref(rule)) {
|
| 245 |
+
throw new ValueError('Encountered a reference rule in the graph');
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
let seen_rule = seen_rules.get(rule);
|
| 249 |
+
if (seen_rule === undefined) {
|
| 250 |
+
seen_rule = [pointer];
|
| 251 |
+
seen_rules.set(rule, seen_rule);
|
| 252 |
+
}
|
| 253 |
+
seen_rule.push(pointer);
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
yield* seen_rules.entries();
|
| 257 |
+
}
|
| 258 |
+
}
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_node.test.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { GraphNode, type GraphNodeMeta, type PrintOpts } from './graph_node.js';
|
| 4 |
+
import { print_graph_node } from './print.js';
|
| 5 |
+
import { RuleRef } from './rule_ref.js';
|
| 6 |
+
|
| 7 |
+
vi.mock('./print.js', () => ({
|
| 8 |
+
print_graph_node: vi.fn(),
|
| 9 |
+
print_graph_pointer: vi.fn(),
|
| 10 |
+
}));
|
| 11 |
+
|
| 12 |
+
describe('GraphNode', () => {
|
| 13 |
+
const meta: GraphNodeMeta = { stackId: 1, pathId: 2, stepId: 3 };
|
| 14 |
+
const rule = new RuleRef(42);
|
| 15 |
+
|
| 16 |
+
beforeEach(() => {
|
| 17 |
+
vi.mocked(print_graph_node).mockReset();
|
| 18 |
+
vi.mocked(print_graph_node).mockReturnValue((_opts: PrintOpts) => 'mocked_response');
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
test('construct with rule and meta', () => {
|
| 22 |
+
const node = new GraphNode(rule, meta);
|
| 23 |
+
expect(node.rule).toBe(rule);
|
| 24 |
+
expect(node.meta).toEqual(meta);
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
test('throw if meta is undefined', () => {
|
| 28 |
+
expect(() => new GraphNode(rule, null)).toThrow('Meta is undefined');
|
| 29 |
+
expect(() => new GraphNode(rule, undefined)).toThrow('Meta is undefined');
|
| 30 |
+
});
|
| 31 |
+
|
| 32 |
+
test('correctly calculate and cache its id', () => {
|
| 33 |
+
const node = new GraphNode(rule, meta);
|
| 34 |
+
expect(node.id).toEqual('1,2,3');
|
| 35 |
+
node.meta = { stackId: 4, pathId: 5, stepId: 6 };
|
| 36 |
+
expect(node.id).toEqual('1,2,3');
|
| 37 |
+
});
|
| 38 |
+
|
| 39 |
+
test('delegate print to the print_graph_node function', () => {
|
| 40 |
+
const node = new GraphNode(rule, meta);
|
| 41 |
+
const opts: PrintOpts = { colorize: (x, _y) => String(x), show_position: false };
|
| 42 |
+
expect(node.print(opts)).toEqual('mocked_response');
|
| 43 |
+
|
| 44 |
+
expect(print_graph_node).toHaveBeenCalledWith(node);
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
test('handle next node linkage', () => {
|
| 48 |
+
const nextNode = new GraphNode(new RuleRef(43), meta);
|
| 49 |
+
const node = new GraphNode(rule, meta, nextNode);
|
| 50 |
+
expect(node.next).toBe(nextNode);
|
| 51 |
+
});
|
| 52 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_node.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ValueError } from '../utils/py.js';
|
| 2 |
+
import type { PrintOpts, UnresolvedRule } from './grammar_graph_types.js';
|
| 3 |
+
import { print_graph_node } from './print.js';
|
| 4 |
+
import type { RuleRef } from './rule_ref.js';
|
| 5 |
+
|
| 6 |
+
export type { PrintOpts };
|
| 7 |
+
|
| 8 |
+
export interface GraphNodeMeta {
|
| 9 |
+
stackId: number;
|
| 10 |
+
pathId: number;
|
| 11 |
+
stepId: number;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export class GraphNode<T extends UnresolvedRule = UnresolvedRule> {
|
| 15 |
+
rule: T;
|
| 16 |
+
next: GraphNode | null;
|
| 17 |
+
meta: GraphNodeMeta;
|
| 18 |
+
#id: string | null = null;
|
| 19 |
+
|
| 20 |
+
constructor(rule: T, meta: GraphNodeMeta | null | undefined, next_node: GraphNode<any> | null = null) {
|
| 21 |
+
this.rule = rule;
|
| 22 |
+
if (meta === null || meta === undefined) {
|
| 23 |
+
throw new ValueError('Meta is undefined');
|
| 24 |
+
}
|
| 25 |
+
this.meta = meta;
|
| 26 |
+
this.next = next_node ?? null;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
get id(): string {
|
| 30 |
+
if (this.#id === null) {
|
| 31 |
+
this.#id = `${this.meta.stackId},${this.meta.pathId},${this.meta.stepId}`;
|
| 32 |
+
}
|
| 33 |
+
return this.#id;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
print(opts: PrintOpts): string {
|
| 37 |
+
return print_graph_node(this)(opts);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
toString(): string {
|
| 41 |
+
return `<GraphNode ${this.id} ${this.rule}>`;
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
export type GraphNodeRuleRef = GraphNode<RuleRef>;
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_pointer.test.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { RuleChar, RuleCharExclude, RuleEnd } from './grammar_graph_types.js';
|
| 4 |
+
import { GraphNode } from './graph_node.js';
|
| 5 |
+
import { GraphPointer } from './graph_pointer.js';
|
| 6 |
+
import {
|
| 7 |
+
is_graph_pointer_rule_char,
|
| 8 |
+
is_graph_pointer_rule_char_exclude,
|
| 9 |
+
is_graph_pointer_rule_end,
|
| 10 |
+
is_graph_pointer_rule_ref,
|
| 11 |
+
} from './type_guards.js';
|
| 12 |
+
|
| 13 |
+
vi.mock('./type_guards.js', async (importOriginal) => ({
|
| 14 |
+
...(await importOriginal<typeof import('./type_guards.js')>()),
|
| 15 |
+
is_graph_pointer_rule_ref: vi.fn(),
|
| 16 |
+
is_graph_pointer_rule_end: vi.fn(),
|
| 17 |
+
is_graph_pointer_rule_char: vi.fn(),
|
| 18 |
+
is_graph_pointer_rule_char_exclude: vi.fn(),
|
| 19 |
+
}));
|
| 20 |
+
|
| 21 |
+
const actual = await vi.importActual<typeof import('./type_guards.js')>('./type_guards.js');
|
| 22 |
+
|
| 23 |
+
describe('GraphPointer', () => {
|
| 24 |
+
beforeEach(() => {
|
| 25 |
+
vi.mocked(is_graph_pointer_rule_ref).mockReset().mockReturnValue(false);
|
| 26 |
+
vi.mocked(is_graph_pointer_rule_end).mockReset().mockReturnValue(false);
|
| 27 |
+
vi.mocked(is_graph_pointer_rule_char).mockReset().mockReturnValue(false);
|
| 28 |
+
vi.mocked(is_graph_pointer_rule_char_exclude).mockReset().mockReturnValue(false);
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
test('constructor', () => {
|
| 32 |
+
const node = new GraphNode(new RuleEnd(), { stackId: 1, pathId: 2, stepId: 3 });
|
| 33 |
+
const pointer = new GraphPointer(node);
|
| 34 |
+
expect(pointer.node).toBe(node);
|
| 35 |
+
expect(pointer.id).toEqual('1,2,3');
|
| 36 |
+
expect(pointer.parent).toBeNull();
|
| 37 |
+
});
|
| 38 |
+
|
| 39 |
+
test('it raises error if node is undefined', () => {
|
| 40 |
+
expect(() => new GraphPointer(null as any)).toThrow('Node is undefined');
|
| 41 |
+
expect(() => new GraphPointer(undefined as any)).toThrow('Node is undefined');
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
test('it initializes correctly with node and parent', () => {
|
| 45 |
+
const parent_node = new GraphNode(new RuleChar([97]), { stackId: 1, pathId: 2, stepId: 3 });
|
| 46 |
+
const child_node = new GraphNode(new RuleChar([98]), { stackId: 4, pathId: 5, stepId: 6 });
|
| 47 |
+
const parent_pointer = new GraphPointer(parent_node);
|
| 48 |
+
const child_pointer = new GraphPointer(child_node, parent_pointer);
|
| 49 |
+
expect(child_pointer.parent).toBe(parent_pointer);
|
| 50 |
+
expect(child_pointer.id).toEqual('1,2,3-4,5,6');
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
test('it tracks validity', () => {
|
| 54 |
+
const pointer = new GraphPointer(new GraphNode(new RuleChar([97]), { stackId: 1, pathId: 2, stepId: 3 }));
|
| 55 |
+
expect(pointer.valid).toBeNull();
|
| 56 |
+
pointer.valid = true;
|
| 57 |
+
expect(pointer.valid).toBe(true);
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
describe('resolve', () => {
|
| 61 |
+
test('it raises error on unknown rule types', () => {
|
| 62 |
+
const node = new GraphNode({ type: 'UNKNOWN_RULE_TYPE' } as any, { stackId: 1, pathId: 2, stepId: 3 });
|
| 63 |
+
const pointer = new GraphPointer(node);
|
| 64 |
+
expect(() => [...pointer.resolve()]).toThrow('Unknown rule');
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
test('it yields a char rule', () => {
|
| 68 |
+
vi.mocked(is_graph_pointer_rule_char).mockReturnValue(true);
|
| 69 |
+
const rule = new RuleChar([97]);
|
| 70 |
+
const node = new GraphNode(rule, { stackId: 1, pathId: 2, stepId: 3 });
|
| 71 |
+
const pointer = new GraphPointer(node);
|
| 72 |
+
const resolved = [...pointer.resolve()];
|
| 73 |
+
expect(resolved).toHaveLength(1);
|
| 74 |
+
expect(resolved[0]).toBe(pointer);
|
| 75 |
+
});
|
| 76 |
+
|
| 77 |
+
test('it yields a char excluded rule', () => {
|
| 78 |
+
vi.mocked(is_graph_pointer_rule_char_exclude).mockReturnValue(true);
|
| 79 |
+
const rule = new RuleCharExclude([97]);
|
| 80 |
+
const node = new GraphNode(rule, { stackId: 1, pathId: 2, stepId: 3 });
|
| 81 |
+
const pointer = new GraphPointer(node);
|
| 82 |
+
const resolved = [...pointer.resolve()];
|
| 83 |
+
expect(resolved).toHaveLength(1);
|
| 84 |
+
expect(resolved[0]).toBe(pointer);
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
test('it yields an end rule without a parent', () => {
|
| 88 |
+
vi.mocked(is_graph_pointer_rule_end).mockReturnValue(true);
|
| 89 |
+
const rule = new RuleEnd();
|
| 90 |
+
const node = new GraphNode(rule, { stackId: 1, pathId: 2, stepId: 3 });
|
| 91 |
+
const pointer = new GraphPointer(node);
|
| 92 |
+
const resolved = [...pointer.resolve()];
|
| 93 |
+
expect(resolved).toHaveLength(1);
|
| 94 |
+
expect(resolved[0]).toBe(pointer);
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
test('it yields an end rule with a parent', () => {
|
| 98 |
+
vi.mocked(is_graph_pointer_rule_end).mockReturnValue(true);
|
| 99 |
+
const rule = new RuleEnd();
|
| 100 |
+
const parent_node = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
|
| 101 |
+
const parent_pointer = new GraphPointer(parent_node);
|
| 102 |
+
const child_node = new GraphNode(rule, { stackId: 1, pathId: 1, stepId: 1 });
|
| 103 |
+
const child_pointer = new GraphPointer(child_node, parent_pointer);
|
| 104 |
+
const resolved = [...child_pointer.resolve()];
|
| 105 |
+
expect(resolved).toHaveLength(1);
|
| 106 |
+
expect(resolved[0]).toBe(parent_pointer);
|
| 107 |
+
});
|
| 108 |
+
|
| 109 |
+
test('it yields an end rule with a grandparent', () => {
|
| 110 |
+
vi.mocked(is_graph_pointer_rule_end).mockReturnValue(true);
|
| 111 |
+
const rule = new RuleEnd();
|
| 112 |
+
const grandparent_node = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
|
| 113 |
+
const grandparent_pointer = new GraphPointer(grandparent_node);
|
| 114 |
+
const parent_node = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
|
| 115 |
+
const parent_pointer = new GraphPointer(parent_node, grandparent_pointer);
|
| 116 |
+
const child_node = new GraphNode(rule, { stackId: 1, pathId: 1, stepId: 1 });
|
| 117 |
+
const child_pointer = new GraphPointer(child_node, parent_pointer);
|
| 118 |
+
const resolved = [...child_pointer.resolve()];
|
| 119 |
+
expect(resolved).toHaveLength(1);
|
| 120 |
+
expect(resolved[0]).toBe(grandparent_pointer);
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
test('it yields an end rule with a parent that is not an end with a grandparent', () => {
|
| 124 |
+
vi.mocked(is_graph_pointer_rule_end).mockImplementation(actual.is_graph_pointer_rule_end as any);
|
| 125 |
+
vi.mocked(is_graph_pointer_rule_char).mockImplementation(actual.is_graph_pointer_rule_char as any);
|
| 126 |
+
const rule = new RuleEnd();
|
| 127 |
+
const grandparent_node = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
|
| 128 |
+
const grandparent_pointer = new GraphPointer(grandparent_node);
|
| 129 |
+
const parent_node = new GraphNode(new RuleChar([97]), { stackId: 2, pathId: 1, stepId: 1 });
|
| 130 |
+
const parent_pointer = new GraphPointer(parent_node, grandparent_pointer);
|
| 131 |
+
const child_node = new GraphNode(rule, { stackId: 1, pathId: 1, stepId: 1 });
|
| 132 |
+
const child_pointer = new GraphPointer(child_node, parent_pointer);
|
| 133 |
+
const resolved = [...child_pointer.resolve()];
|
| 134 |
+
expect(resolved).toHaveLength(1);
|
| 135 |
+
expect(resolved[0]).toBe(parent_pointer);
|
| 136 |
+
});
|
| 137 |
+
});
|
| 138 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/graph_pointer.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ValueError, repr } from '../utils/py.js';
|
| 2 |
+
import type { PrintOpts, ResolvedGraphPointer, UnresolvedRule } from './grammar_graph_types.js';
|
| 3 |
+
import { GraphNode } from './graph_node.js';
|
| 4 |
+
import { print_graph_pointer } from './print.js';
|
| 5 |
+
import type { RuleRef } from './rule_ref.js';
|
| 6 |
+
import {
|
| 7 |
+
is_graph_pointer_rule_char,
|
| 8 |
+
is_graph_pointer_rule_char_exclude,
|
| 9 |
+
is_graph_pointer_rule_end,
|
| 10 |
+
is_graph_pointer_rule_ref,
|
| 11 |
+
is_rule_end,
|
| 12 |
+
} from './type_guards.js';
|
| 13 |
+
|
| 14 |
+
export type GraphPointerKey = string;
|
| 15 |
+
|
| 16 |
+
export class GraphPointer<T extends UnresolvedRule = UnresolvedRule> {
|
| 17 |
+
node: GraphNode<T>;
|
| 18 |
+
parent: GraphPointer<any> | null = null;
|
| 19 |
+
id: string;
|
| 20 |
+
#valid: boolean | null = null;
|
| 21 |
+
|
| 22 |
+
constructor(node: GraphNode<T>, parent: GraphPointer<any> | null = null) {
|
| 23 |
+
if (node === null || node === undefined) {
|
| 24 |
+
throw new ValueError('Node is undefined');
|
| 25 |
+
}
|
| 26 |
+
this.node = node;
|
| 27 |
+
this.parent = parent ?? null;
|
| 28 |
+
this.id = parent ? `${parent.id}-${node.id}` : node.id;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
get rule(): T {
|
| 32 |
+
return this.node.rule;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
get valid(): boolean | null {
|
| 36 |
+
return this.#valid;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
set valid(valid: boolean | null) {
|
| 40 |
+
this.#valid = valid;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
print(opts: PrintOpts): string {
|
| 44 |
+
return print_graph_pointer(this)(opts);
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/**
|
| 48 |
+
* Resolve the graph pointer.
|
| 49 |
+
*
|
| 50 |
+
* @param resolved Whether the pointer has already been resolved. Defaults to false.
|
| 51 |
+
* @yields The resolved graph pointers.
|
| 52 |
+
*/
|
| 53 |
+
*resolve(resolved = false): IterableIterator<ResolvedGraphPointer> {
|
| 54 |
+
if (is_graph_pointer_rule_ref(this)) {
|
| 55 |
+
if (resolved) {
|
| 56 |
+
if (!this.node.next) {
|
| 57 |
+
throw new ValueError(`No next node: ${this.node}`);
|
| 58 |
+
}
|
| 59 |
+
yield* new GraphPointer(this.node.next, this.parent).resolve();
|
| 60 |
+
} else {
|
| 61 |
+
for (const node of (this.node.rule as RuleRef).nodes) {
|
| 62 |
+
yield* new GraphPointer<any>(node, this).resolve();
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
} else if (is_graph_pointer_rule_end(this)) {
|
| 66 |
+
if (!this.parent) {
|
| 67 |
+
yield this as unknown as ResolvedGraphPointer;
|
| 68 |
+
} else {
|
| 69 |
+
yield* this.parent.resolve(true);
|
| 70 |
+
}
|
| 71 |
+
} else if (is_graph_pointer_rule_char(this) || is_graph_pointer_rule_char_exclude(this)) {
|
| 72 |
+
yield this as unknown as ResolvedGraphPointer;
|
| 73 |
+
} else {
|
| 74 |
+
throw new ValueError(`Unknown rule: ${repr((this as GraphPointer<any>).node.rule)}`);
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
/**
|
| 79 |
+
* Fetch the next resolved graph pointers.
|
| 80 |
+
*
|
| 81 |
+
* @yields The next resolved graph pointers.
|
| 82 |
+
*/
|
| 83 |
+
*fetch_next(): IterableIterator<ResolvedGraphPointer> {
|
| 84 |
+
// If this pointer is invalid, then we don't return any new pointers
|
| 85 |
+
if (!this.valid) {
|
| 86 |
+
return;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// If this pointer is an end node, we return the parent's next node.
|
| 90 |
+
// If no parent exists, we return nothing, since it's the end of the line.
|
| 91 |
+
if (is_rule_end(this.node.rule)) {
|
| 92 |
+
if (this.parent) {
|
| 93 |
+
yield* this.parent.fetch_next();
|
| 94 |
+
}
|
| 95 |
+
} else {
|
| 96 |
+
if (!this.node.next) {
|
| 97 |
+
throw new ValueError(`No next node: ${this.node}`);
|
| 98 |
+
}
|
| 99 |
+
const pointer = new GraphPointer(this.node.next, this.parent);
|
| 100 |
+
yield* pointer.resolve();
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
toString(): string {
|
| 105 |
+
return `<GraphPointer ${this.id} ${this.node}>`;
|
| 106 |
+
}
|
| 107 |
+
}
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/parse_state.test.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test, vi } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { RuleChar } from './grammar_graph_types.js';
|
| 4 |
+
import type { Graph } from './graph.js';
|
| 5 |
+
import { GraphNode } from './graph_node.js';
|
| 6 |
+
import { GraphPointer } from './graph_pointer.js';
|
| 7 |
+
import { ParseState } from './parse_state.js';
|
| 8 |
+
import type { Pointers } from './pointers.js';
|
| 9 |
+
|
| 10 |
+
const make_mock_graph = () =>
|
| 11 |
+
({
|
| 12 |
+
add: vi.fn((_input: string, pointers: Pointers) => pointers),
|
| 13 |
+
grammar: 'sample-grammar',
|
| 14 |
+
}) as unknown as Graph & { add: ReturnType<typeof vi.fn> };
|
| 15 |
+
|
| 16 |
+
const mock_pointers = new Set([
|
| 17 |
+
new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 1, pathId: 1, stepId: 1 })),
|
| 18 |
+
]) as unknown as Pointers;
|
| 19 |
+
|
| 20 |
+
describe('ParseState', () => {
|
| 21 |
+
test('constructs with given graph and pointers', () => {
|
| 22 |
+
const parse_state = new ParseState(make_mock_graph(), mock_pointers);
|
| 23 |
+
expect(parse_state).toBeInstanceOf(ParseState);
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
test('returns unique rules from pointers', () => {
|
| 27 |
+
const parse_state = new ParseState(make_mock_graph(), mock_pointers);
|
| 28 |
+
const rules = [...parse_state.rules()];
|
| 29 |
+
expect(rules).toHaveLength(1);
|
| 30 |
+
expect(rules[0]).toBeInstanceOf(RuleChar);
|
| 31 |
+
expect((rules[0] as RuleChar).value).toEqual([65]);
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
test('dedupes identical rules from different pointers', () => {
|
| 35 |
+
const pointers = new Set([
|
| 36 |
+
new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 1, pathId: 1, stepId: 1 })),
|
| 37 |
+
new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 2, pathId: 1, stepId: 1 })),
|
| 38 |
+
new GraphPointer(new GraphNode(new RuleChar([66]), { stackId: 3, pathId: 1, stepId: 1 })),
|
| 39 |
+
]) as unknown as Pointers;
|
| 40 |
+
const parse_state = new ParseState(make_mock_graph(), pointers);
|
| 41 |
+
expect(parse_state.size).toEqual(2);
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
test('iterates over unique rules using symbol iterator', () => {
|
| 45 |
+
const parse_state = new ParseState(make_mock_graph(), mock_pointers);
|
| 46 |
+
const rules = [...parse_state];
|
| 47 |
+
expect(rules).toHaveLength(1);
|
| 48 |
+
expect(rules[0]).toBeInstanceOf(RuleChar);
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
test('adds new input and returns new parse state with updated pointers', () => {
|
| 52 |
+
const mock_graph = make_mock_graph();
|
| 53 |
+
const parse_state = new ParseState(mock_graph, mock_pointers);
|
| 54 |
+
const new_state = parse_state.add('B');
|
| 55 |
+
expect(new_state).toBeInstanceOf(ParseState);
|
| 56 |
+
expect(mock_graph.add).toHaveBeenCalledWith('B', mock_pointers);
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
test('raises if input is not a string', () => {
|
| 60 |
+
const parse_state = new ParseState(make_mock_graph(), mock_pointers);
|
| 61 |
+
expect(() => parse_state.add(1 as unknown as string)).toThrow('input text must be of type string');
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
test('calculates the size of unique rules correctly', () => {
|
| 65 |
+
const parse_state = new ParseState(make_mock_graph(), mock_pointers);
|
| 66 |
+
expect(parse_state.size).toEqual(1);
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
test('provides access to the underlying graph grammar', () => {
|
| 70 |
+
const parse_state = new ParseState(make_mock_graph(), mock_pointers);
|
| 71 |
+
expect(parse_state.grammar).toEqual('sample-grammar');
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
test('is callable as a function', () => {
|
| 75 |
+
const mock_graph = make_mock_graph();
|
| 76 |
+
const parse_state = new ParseState(mock_graph, mock_pointers);
|
| 77 |
+
const new_state = parse_state('B');
|
| 78 |
+
expect(new_state).toBeInstanceOf(ParseState);
|
| 79 |
+
expect(mock_graph.add).toHaveBeenCalledWith('B', mock_pointers);
|
| 80 |
+
});
|
| 81 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/parse_state.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ValueError, json_dumps } from '../utils/py.js';
|
| 2 |
+
import type { ResolvedRule } from './grammar_graph_types.js';
|
| 3 |
+
import type { Graph } from './graph.js';
|
| 4 |
+
import type { GraphPointer } from './graph_pointer.js';
|
| 5 |
+
import type { Pointers } from './pointers.js';
|
| 6 |
+
|
| 7 |
+
const get_rule_key = (rule: unknown): string => {
|
| 8 |
+
const serializable = rule as { toJSON?: () => unknown } | null | undefined;
|
| 9 |
+
return json_dumps(typeof serializable?.toJSON === 'function' ? serializable.toJSON() : rule);
|
| 10 |
+
};
|
| 11 |
+
|
| 12 |
+
// A ParseState can be called directly with additional input, e.g. `state('foo')`
|
| 13 |
+
export interface ParseState {
|
| 14 |
+
(text: string): ParseState;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export class ParseState {
|
| 18 |
+
__graph__!: Graph;
|
| 19 |
+
__pointers__!: Pointers;
|
| 20 |
+
|
| 21 |
+
constructor(graph: Graph, pointers: Pointers | Iterable<GraphPointer<any>>) {
|
| 22 |
+
const self = ((text: string) => self.add(text)) as ParseState;
|
| 23 |
+
delete (self as any).name;
|
| 24 |
+
delete (self as any).length;
|
| 25 |
+
Object.setPrototypeOf(self, new.target.prototype);
|
| 26 |
+
self.__graph__ = graph;
|
| 27 |
+
self.__pointers__ = pointers as Pointers;
|
| 28 |
+
return self;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
*[Symbol.iterator](): IterableIterator<ResolvedRule> {
|
| 32 |
+
yield* this.rules();
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
*rules(): IterableIterator<ResolvedRule> {
|
| 36 |
+
const rules = new Set<string>();
|
| 37 |
+
for (const pointer of this.__pointers__) {
|
| 38 |
+
const rule = pointer.rule;
|
| 39 |
+
const key = get_rule_key(rule);
|
| 40 |
+
if (!rules.has(key)) {
|
| 41 |
+
rules.add(key);
|
| 42 |
+
yield rule;
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
add(text: string): ParseState {
|
| 48 |
+
if (typeof text !== 'string') {
|
| 49 |
+
throw new ValueError('input text must be of type string');
|
| 50 |
+
}
|
| 51 |
+
const pointers = this.__graph__.add(text, this.__pointers__);
|
| 52 |
+
return new ParseState(this.__graph__, pointers);
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
get size(): number {
|
| 56 |
+
return [...this.rules()].length;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
get grammar(): string {
|
| 60 |
+
return this.__graph__.grammar;
|
| 61 |
+
}
|
| 62 |
+
}
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/pointers.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { GraphPointer } from './graph_pointer.js';
|
| 2 |
+
|
| 3 |
+
export class Pointers {
|
| 4 |
+
__pointers__: Map<string, GraphPointer<any>>;
|
| 5 |
+
|
| 6 |
+
constructor(...pointers: GraphPointer<any>[]) {
|
| 7 |
+
this.__pointers__ = new Map();
|
| 8 |
+
for (const pointer of pointers) {
|
| 9 |
+
this.add(pointer);
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
toString(): string {
|
| 14 |
+
return `<Pointers [${[...this].map((p) => String(p.node.rule)).join(', ')}]>`;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
add(pointer: GraphPointer<any>): void {
|
| 18 |
+
this.__pointers__.set(pointer.id, pointer);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
[Symbol.iterator](): IterableIterator<GraphPointer<any>> {
|
| 22 |
+
return this.__pointers__.values();
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
get length(): number {
|
| 26 |
+
return this.__pointers__.size;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
get size(): number {
|
| 30 |
+
return this.__pointers__.size;
|
| 31 |
+
}
|
| 32 |
+
}
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/print.test.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test, vi } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { get_parent_stack_id } from './get_parent_stack_id.js';
|
| 4 |
+
import { RuleChar } from './grammar_graph_types.js';
|
| 5 |
+
import { print_graph_node, print_graph_pointer } from './print.js';
|
| 6 |
+
import { RuleRef } from './rule_ref.js';
|
| 7 |
+
|
| 8 |
+
vi.mock('./get_parent_stack_id.js', () => ({
|
| 9 |
+
get_parent_stack_id: vi.fn(),
|
| 10 |
+
}));
|
| 11 |
+
|
| 12 |
+
const COLORS: Record<string, string> = {
|
| 13 |
+
'\x1b[34m': 'BLUE',
|
| 14 |
+
'\x1b[36m': 'CYAN',
|
| 15 |
+
'\x1b[32m': 'GREEN',
|
| 16 |
+
'\x1b[31m': 'RED',
|
| 17 |
+
'\x1b[90m': 'GRAY',
|
| 18 |
+
'\x1b[33m': 'YELLOW',
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
const mock_colorize = (text: string | number, color: string): string => {
|
| 22 |
+
if (!(color in COLORS)) {
|
| 23 |
+
throw new Error(`Invalid color: ${color}`);
|
| 24 |
+
}
|
| 25 |
+
return `[${COLORS[color]}]:${text}`;
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
const create_mock_node = (id: number, rule: unknown, next: unknown = null): any => ({
|
| 29 |
+
id,
|
| 30 |
+
rule,
|
| 31 |
+
next,
|
| 32 |
+
print: (_opts: unknown) => `Node(${id})`,
|
| 33 |
+
});
|
| 34 |
+
|
| 35 |
+
const create_mock_graph_pointer = (node: any): any => ({
|
| 36 |
+
node,
|
| 37 |
+
parent: null,
|
| 38 |
+
print: (_opts: unknown) => `Pointer to ${node.id}`,
|
| 39 |
+
});
|
| 40 |
+
|
| 41 |
+
describe('print', () => {
|
| 42 |
+
describe('print_graph_pointer', () => {
|
| 43 |
+
test('it prints graph pointer details correctly', () => {
|
| 44 |
+
const mock_node = create_mock_node(1, new RuleRef(100));
|
| 45 |
+
const mock_pointer = create_mock_graph_pointer(mock_node);
|
| 46 |
+
vi.mocked(get_parent_stack_id).mockReturnValue('foo');
|
| 47 |
+
const result = print_graph_pointer(mock_pointer)({
|
| 48 |
+
colorize: mock_colorize,
|
| 49 |
+
pointers: new Set(),
|
| 50 |
+
show_position: false,
|
| 51 |
+
});
|
| 52 |
+
expect(result).toEqual('[RED]:*foo');
|
| 53 |
+
});
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
describe('print_graph_node', () => {
|
| 57 |
+
test('it prints graph node with a character rule', () => {
|
| 58 |
+
const rule_char = new RuleChar([65]);
|
| 59 |
+
const mock_node = create_mock_node(1, rule_char);
|
| 60 |
+
const result = print_graph_node(mock_node)({
|
| 61 |
+
colorize: mock_colorize,
|
| 62 |
+
show_position: false,
|
| 63 |
+
pointers: new Set(),
|
| 64 |
+
});
|
| 65 |
+
expect(result).toEqual('[GRAY]:[[YELLOW]:A[GRAY]:]');
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
test('it prints graph node with a rule reference', () => {
|
| 69 |
+
const rule_ref = new RuleRef(200);
|
| 70 |
+
const mock_node = create_mock_node(1, rule_ref);
|
| 71 |
+
const result = print_graph_node(mock_node)({
|
| 72 |
+
colorize: mock_colorize,
|
| 73 |
+
show_position: true,
|
| 74 |
+
pointers: new Set(),
|
| 75 |
+
});
|
| 76 |
+
expect(result).toEqual('[BLUE]:{[GRAY]:1[BLUE]:}[GRAY]:Ref([GREEN]:200[GRAY]:)');
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
test('it prints ranges, pointers and the next node', () => {
|
| 80 |
+
const next_node = create_mock_node(2, new RuleRef(1));
|
| 81 |
+
const mock_node = create_mock_node(1, new RuleChar([[97, 122], 10]), next_node);
|
| 82 |
+
const result = print_graph_node(mock_node)({
|
| 83 |
+
colorize: mock_colorize,
|
| 84 |
+
show_position: false,
|
| 85 |
+
pointers: new Set([create_mock_graph_pointer(mock_node), create_mock_graph_pointer(next_node)]),
|
| 86 |
+
});
|
| 87 |
+
expect(result).toEqual(
|
| 88 |
+
'[GRAY]:[[YELLOW]:[YELLOW]:a[YELLOW]:z\\n[GRAY]:][GRAY]:[[YELLOW]:Pointer to 1[GRAY]:][GRAY]:-> Node(2)',
|
| 89 |
+
);
|
| 90 |
+
});
|
| 91 |
+
});
|
| 92 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/print.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { AttributeError, KeyError, chr } from '../utils/py.js';
|
| 2 |
+
import { Color } from './colorize.js';
|
| 3 |
+
import { get_parent_stack_id } from './get_parent_stack_id.js';
|
| 4 |
+
import type { PrintOpts } from './grammar_graph_types.js';
|
| 5 |
+
import type { GraphNode } from './graph_node.js';
|
| 6 |
+
import type { GraphPointer } from './graph_pointer.js';
|
| 7 |
+
import { is_range, is_rule_char, is_rule_ref } from './type_guards.js';
|
| 8 |
+
|
| 9 |
+
const get_colorize = (opts: PrintOpts): PrintOpts['colorize'] => {
|
| 10 |
+
const col = opts.colorize;
|
| 11 |
+
if (col === undefined) {
|
| 12 |
+
throw new KeyError("'colorize'");
|
| 13 |
+
}
|
| 14 |
+
return col;
|
| 15 |
+
};
|
| 16 |
+
|
| 17 |
+
export const print_graph_pointer =
|
| 18 |
+
(pointer: GraphPointer<any>) =>
|
| 19 |
+
(opts: PrintOpts): string => {
|
| 20 |
+
const col = get_colorize(opts);
|
| 21 |
+
return col(`*${get_parent_stack_id(pointer, col)}`, Color.RED);
|
| 22 |
+
};
|
| 23 |
+
|
| 24 |
+
export const print_graph_node =
|
| 25 |
+
(node: GraphNode<any>) =>
|
| 26 |
+
(opts: PrintOpts): string => {
|
| 27 |
+
const pointers: Iterable<GraphPointer<any>> = opts.pointers ?? new Set();
|
| 28 |
+
const col = get_colorize(opts);
|
| 29 |
+
const show_position = opts.show_position ?? false;
|
| 30 |
+
const rule = node.rule;
|
| 31 |
+
const parts: string[] = [];
|
| 32 |
+
if (show_position) {
|
| 33 |
+
parts.push(col('{', Color.BLUE), col(node.id, Color.GRAY), col('}', Color.BLUE));
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
if (is_rule_char(rule)) {
|
| 37 |
+
parts.push(
|
| 38 |
+
col('[', Color.GRAY),
|
| 39 |
+
col(
|
| 40 |
+
rule.value
|
| 41 |
+
.map((v) => (is_range(v) ? v.map((val) => col(get_char(val), Color.YELLOW)).join('') : get_char(v as number)))
|
| 42 |
+
.join(''),
|
| 43 |
+
Color.YELLOW,
|
| 44 |
+
),
|
| 45 |
+
col(']', Color.GRAY),
|
| 46 |
+
);
|
| 47 |
+
} else if (is_rule_ref(rule)) {
|
| 48 |
+
parts.push(col('Ref(', Color.GRAY), col(rule.value, Color.GREEN), col(')', Color.GRAY));
|
| 49 |
+
} else {
|
| 50 |
+
// only char and ref rules can be printed, as in the reference implementation
|
| 51 |
+
const type = (rule as { type?: string } | null | undefined)?.type;
|
| 52 |
+
if (type === undefined) {
|
| 53 |
+
throw new AttributeError(`'${rule?.constructor?.name ?? typeof rule}' object has no attribute 'type'`);
|
| 54 |
+
}
|
| 55 |
+
parts.push(col(type, Color.YELLOW));
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
for (const pointer of pointers) {
|
| 59 |
+
const pointer_parts: string[] = [];
|
| 60 |
+
if (pointer.node === node) {
|
| 61 |
+
pointer_parts.push(pointer.print(opts));
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
if (pointer_parts.length > 0) {
|
| 65 |
+
parts.push(col('[', Color.GRAY), col(pointer_parts.join(''), Color.YELLOW), col(']', Color.GRAY));
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
const parts_to_return = [parts.join('')];
|
| 70 |
+
if (node.next) {
|
| 71 |
+
parts_to_return.push(node.next.print(opts));
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
return parts_to_return.join(col('-> ', Color.GRAY));
|
| 75 |
+
};
|
| 76 |
+
|
| 77 |
+
export const get_char = (char_code: number): string => {
|
| 78 |
+
const char = chr(char_code);
|
| 79 |
+
if (char === '\n') {
|
| 80 |
+
return '\\n';
|
| 81 |
+
}
|
| 82 |
+
return char;
|
| 83 |
+
};
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/rule_ref.test.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { type GraphNode, RuleRef } from './rule_ref.js';
|
| 4 |
+
|
| 5 |
+
describe('RuleRef', () => {
|
| 6 |
+
test('initializes with a given value', () => {
|
| 7 |
+
const ruleRef = new RuleRef(123);
|
| 8 |
+
expect(ruleRef.value).toEqual(123);
|
| 9 |
+
});
|
| 10 |
+
|
| 11 |
+
test('allows setting and getting nodes', () => {
|
| 12 |
+
const mockNodes = new Set<GraphNode>([1]);
|
| 13 |
+
const ruleRef = new RuleRef(123);
|
| 14 |
+
ruleRef.nodes = mockNodes;
|
| 15 |
+
expect(ruleRef.nodes).toBe(mockNodes);
|
| 16 |
+
});
|
| 17 |
+
|
| 18 |
+
test('throws an error if trying to get nodes before setting', () => {
|
| 19 |
+
const ruleRef = new RuleRef(123);
|
| 20 |
+
expect(() => ruleRef.nodes).toThrow('Nodes are not set');
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
test('compares by value', () => {
|
| 24 |
+
expect(new RuleRef(1)).toStrictEqual(new RuleRef(1));
|
| 25 |
+
expect(new RuleRef(1)).not.toEqual(new RuleRef(2));
|
| 26 |
+
});
|
| 27 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/rule_ref.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ValueError } from '../utils/py.js';
|
| 2 |
+
|
| 3 |
+
// import type { GraphNode, } from "./graph-node.js";
|
| 4 |
+
export type GraphNode = unknown;
|
| 5 |
+
|
| 6 |
+
export class RuleRef {
|
| 7 |
+
#nodes: Set<any> | null = null;
|
| 8 |
+
value: number;
|
| 9 |
+
|
| 10 |
+
constructor(value: number) {
|
| 11 |
+
this.value = value;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
get nodes(): Set<any> {
|
| 15 |
+
if (this.#nodes === null) {
|
| 16 |
+
throw new ValueError('Nodes are not set');
|
| 17 |
+
}
|
| 18 |
+
return this.#nodes;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
set nodes(nodes: Set<any>) {
|
| 22 |
+
this.#nodes = nodes;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
toJSON(): { type: string; value: number } {
|
| 26 |
+
return { type: this.constructor.name, value: this.value };
|
| 27 |
+
}
|
| 28 |
+
}
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/type_guards.test.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { RuleChar, RuleCharExclude, RuleEnd } from './grammar_graph_types.js';
|
| 4 |
+
import { GraphNode } from './graph_node.js';
|
| 5 |
+
import { GraphPointer } from './graph_pointer.js';
|
| 6 |
+
import { RuleRef } from './rule_ref.js';
|
| 7 |
+
import {
|
| 8 |
+
is_graph_pointer_rule_char,
|
| 9 |
+
is_graph_pointer_rule_char_exclude,
|
| 10 |
+
is_graph_pointer_rule_end,
|
| 11 |
+
is_graph_pointer_rule_ref,
|
| 12 |
+
is_range,
|
| 13 |
+
is_rule,
|
| 14 |
+
is_rule_char,
|
| 15 |
+
is_rule_char_exclude,
|
| 16 |
+
is_rule_end,
|
| 17 |
+
is_rule_ref,
|
| 18 |
+
} from './type_guards.js';
|
| 19 |
+
|
| 20 |
+
const meta = () => ({ stackId: 1, pathId: 2, stepId: 3 });
|
| 21 |
+
const pointer_for = (rule: RuleRef | RuleEnd | RuleChar | RuleCharExclude) =>
|
| 22 |
+
new GraphPointer(new GraphNode(rule, meta()));
|
| 23 |
+
|
| 24 |
+
describe('rule type guards', () => {
|
| 25 |
+
describe('is_graph_pointer_rule_ref', () => {
|
| 26 |
+
test('it returns true', () => {
|
| 27 |
+
expect(is_graph_pointer_rule_ref(pointer_for(new RuleRef(1)))).toBe(true);
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
test('it returns false', () => {
|
| 31 |
+
expect(is_graph_pointer_rule_ref(pointer_for(new RuleEnd()))).toBe(false);
|
| 32 |
+
});
|
| 33 |
+
});
|
| 34 |
+
|
| 35 |
+
describe('is_graph_pointer_rule_end', () => {
|
| 36 |
+
test('it returns false', () => {
|
| 37 |
+
expect(is_graph_pointer_rule_end(pointer_for(new RuleRef(1)))).toBe(false);
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
test('it returns true', () => {
|
| 41 |
+
expect(is_graph_pointer_rule_end(pointer_for(new RuleEnd()))).toBe(true);
|
| 42 |
+
});
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
describe('is_graph_pointer_rule_char', () => {
|
| 46 |
+
test('it returns true', () => {
|
| 47 |
+
expect(is_graph_pointer_rule_char(pointer_for(new RuleChar([97])))).toBe(true);
|
| 48 |
+
});
|
| 49 |
+
|
| 50 |
+
test('it returns false', () => {
|
| 51 |
+
expect(is_graph_pointer_rule_char(pointer_for(new RuleEnd()))).toBe(false);
|
| 52 |
+
});
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
describe('is_graph_pointer_rule_char_exclude', () => {
|
| 56 |
+
test('it returns true', () => {
|
| 57 |
+
expect(is_graph_pointer_rule_char_exclude(pointer_for(new RuleCharExclude([97])))).toBe(true);
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
test('it returns false', () => {
|
| 61 |
+
expect(is_graph_pointer_rule_char_exclude(pointer_for(new RuleChar([97])))).toBe(false);
|
| 62 |
+
});
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
describe('is_rule', () => {
|
| 66 |
+
test('it returns false for null', () => {
|
| 67 |
+
expect(is_rule(null)).toBe(false);
|
| 68 |
+
expect(is_rule(undefined)).toBe(false);
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
test('it returns false for a non rule', () => {
|
| 72 |
+
expect(is_rule({ type: 'invalid', value: [] })).toBe(false);
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
test('it returns true for valid rule objects', () => {
|
| 76 |
+
const ruleChar = new RuleChar([65, [66, 67]]);
|
| 77 |
+
expect(is_rule(ruleChar)).toBe(true);
|
| 78 |
+
});
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
describe('is_rule_ref', () => {
|
| 82 |
+
test('it returns true for valid rule refs', () => {
|
| 83 |
+
expect(is_rule_ref(new RuleRef(1))).toBe(true);
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
test('it returns false for invalid rule refs', () => {
|
| 87 |
+
expect(is_rule_ref(new RuleChar([65]))).toBe(false);
|
| 88 |
+
});
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
describe('is_rule_end', () => {
|
| 92 |
+
test('it returns true for valid rule ends', () => {
|
| 93 |
+
expect(is_rule_end(new RuleEnd())).toBe(true);
|
| 94 |
+
});
|
| 95 |
+
|
| 96 |
+
test('it returns false for invalid rule ends', () => {
|
| 97 |
+
expect(is_rule_end(new RuleChar([65]))).toBe(false);
|
| 98 |
+
});
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
describe('is_rule_char', () => {
|
| 102 |
+
test('it returns true for valid rule chars', () => {
|
| 103 |
+
expect(is_rule_char(new RuleChar([65]))).toBe(true);
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
test('it returns false for invalid rule chars', () => {
|
| 107 |
+
expect(is_rule_char(new RuleCharExclude([65]))).toBe(false);
|
| 108 |
+
});
|
| 109 |
+
});
|
| 110 |
+
|
| 111 |
+
describe('is_rule_char_exclude', () => {
|
| 112 |
+
test('it returns true for valid rule chars', () => {
|
| 113 |
+
expect(is_rule_char_exclude(new RuleCharExclude([65]))).toBe(true);
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
test('it returns false for invalid rule chars', () => {
|
| 117 |
+
expect(is_rule_char_exclude(new RuleChar([65]))).toBe(false);
|
| 118 |
+
});
|
| 119 |
+
});
|
| 120 |
+
|
| 121 |
+
describe('is_range', () => {
|
| 122 |
+
test('it returns true for valid ranges', () => {
|
| 123 |
+
expect(is_range([1, 10])).toBe(true);
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
test.each([[[1, '10']], [[1]], [5]])('it returns false for invalid range %j', (value) => {
|
| 127 |
+
expect(is_range(value)).toBe(false);
|
| 128 |
+
});
|
| 129 |
+
});
|
| 130 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_graph/type_guards.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { RuleChar, RuleCharExclude, RuleEnd, type Range } from './grammar_graph_types.js';
|
| 2 |
+
import type { GraphPointer } from './graph_pointer.js';
|
| 3 |
+
import { RuleRef } from './rule_ref.js';
|
| 4 |
+
|
| 5 |
+
export const is_rule = (rule: unknown): rule is RuleChar | RuleCharExclude | RuleEnd | RuleRef =>
|
| 6 |
+
rule instanceof RuleChar || rule instanceof RuleCharExclude || rule instanceof RuleEnd || rule instanceof RuleRef;
|
| 7 |
+
|
| 8 |
+
export const is_rule_ref = (rule: unknown): rule is RuleRef => rule instanceof RuleRef;
|
| 9 |
+
|
| 10 |
+
export const is_rule_end = (rule: unknown): rule is RuleEnd => rule instanceof RuleEnd;
|
| 11 |
+
|
| 12 |
+
export const is_rule_char = (rule: unknown): rule is RuleChar => rule instanceof RuleChar;
|
| 13 |
+
|
| 14 |
+
export const is_rule_char_exclude = (rule: unknown): rule is RuleCharExclude => rule instanceof RuleCharExclude;
|
| 15 |
+
|
| 16 |
+
export const is_range = (inpt: unknown): inpt is Range =>
|
| 17 |
+
Array.isArray(inpt) && inpt.length === 2 && inpt.every((n) => typeof n === 'number' && Number.isInteger(n));
|
| 18 |
+
|
| 19 |
+
export const is_graph_pointer_rule_ref = (pointer: GraphPointer<any>): pointer is GraphPointer<RuleRef> =>
|
| 20 |
+
is_rule_ref(pointer.rule);
|
| 21 |
+
|
| 22 |
+
export const is_graph_pointer_rule_end = (pointer: GraphPointer<any>): pointer is GraphPointer<RuleEnd> =>
|
| 23 |
+
is_rule_end(pointer.rule);
|
| 24 |
+
|
| 25 |
+
export const is_graph_pointer_rule_char = (pointer: GraphPointer<any>): pointer is GraphPointer<RuleChar> =>
|
| 26 |
+
is_rule_char(pointer.rule);
|
| 27 |
+
|
| 28 |
+
export const is_graph_pointer_rule_char_exclude = (
|
| 29 |
+
pointer: GraphPointer<any>,
|
| 30 |
+
): pointer is GraphPointer<RuleCharExclude> => is_rule_char_exclude(pointer.rule);
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_parser/build_rule_stack.test.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { load_fixture, revive } from '../../tests/helpers.js';
|
| 4 |
+
import { RuleChar, RuleEnd } from '../grammar_graph/grammar_graph_types.js';
|
| 5 |
+
import { InternalRuleDefAlt, InternalRuleDefChar } from '../rules_builder/rules_builder_types.js';
|
| 6 |
+
import { build_rule_stack } from './build_rule_stack.js';
|
| 7 |
+
|
| 8 |
+
const cases = load_fixture<{ name: string; input: any[]; expected: any[][] }[]>('build_rule_stack_test');
|
| 9 |
+
|
| 10 |
+
describe('build_rule_stack', () => {
|
| 11 |
+
test('it builds rule stack for a single path', () => {
|
| 12 |
+
expect(build_rule_stack([new InternalRuleDefChar([120])])).toStrictEqual([[new RuleChar([120]), new RuleEnd()]]);
|
| 13 |
+
});
|
| 14 |
+
|
| 15 |
+
test('it raises for an alt without anything before it', () => {
|
| 16 |
+
expect(() => build_rule_stack([new InternalRuleDefAlt()])).toThrow('Encountered alt without anything before it');
|
| 17 |
+
});
|
| 18 |
+
|
| 19 |
+
test.each(cases.map((c, i) => [`${i}: ${c.name}`, c] as const))('%s', (_name, { input, expected }) => {
|
| 20 |
+
expect(build_rule_stack(revive(input))).toStrictEqual(revive(expected));
|
| 21 |
+
});
|
| 22 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/grammar_parser/build_rule_stack.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {
|
| 2 |
+
type Range,
|
| 3 |
+
RuleChar,
|
| 4 |
+
RuleCharExclude,
|
| 5 |
+
RuleEnd,
|
| 6 |
+
type UnresolvedRule,
|
| 7 |
+
} from '../grammar_graph/grammar_graph_types.js';
|
| 8 |
+
import { RuleRef } from '../grammar_graph/rule_ref.js';
|
| 9 |
+
import { is_range, is_rule_end } from '../grammar_graph/type_guards.js';
|
| 10 |
+
import {
|
| 11 |
+
type InternalRuleDef,
|
| 12 |
+
type InternalRuleDefChar,
|
| 13 |
+
type InternalRuleDefCharNot,
|
| 14 |
+
is_rule_def_alt,
|
| 15 |
+
is_rule_def_char,
|
| 16 |
+
is_rule_def_char_alt,
|
| 17 |
+
is_rule_def_char_not,
|
| 18 |
+
is_rule_def_char_rng_upper,
|
| 19 |
+
is_rule_def_end,
|
| 20 |
+
is_rule_def_ref,
|
| 21 |
+
} from '../rules_builder/rules_builder_types.js';
|
| 22 |
+
import { IndexError, ValueError, json_dumps, repr } from '../utils/py.js';
|
| 23 |
+
|
| 24 |
+
export const make_char_rule = (rule_def: InternalRuleDefChar | InternalRuleDefCharNot): RuleChar | RuleCharExclude => {
|
| 25 |
+
const value = rule_def.value as (number | Range)[];
|
| 26 |
+
if (is_rule_def_char_not(rule_def)) {
|
| 27 |
+
return new RuleCharExclude(value);
|
| 28 |
+
}
|
| 29 |
+
if (is_rule_def_char(rule_def)) {
|
| 30 |
+
return new RuleChar(value);
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
throw new ValueError(`Unsupported rule type for make_char_rule: ${repr(rule_def)}`);
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
export const build_rule_stack = (linear_rules: InternalRuleDef[]): UnresolvedRule[][] => {
|
| 37 |
+
let paths: UnresolvedRule[] = [];
|
| 38 |
+
const stack: UnresolvedRule[][] = [];
|
| 39 |
+
let idx = 0;
|
| 40 |
+
|
| 41 |
+
while (idx < linear_rules.length) {
|
| 42 |
+
const rule_def = linear_rules[idx];
|
| 43 |
+
if (is_rule_def_char(rule_def) || is_rule_def_char_not(rule_def)) {
|
| 44 |
+
// this could be a single char, or a range, or a sequence of alts; we don't know until we step through it.
|
| 45 |
+
const char_rule = make_char_rule(rule_def);
|
| 46 |
+
idx += 1;
|
| 47 |
+
let rule = idx < linear_rules.length ? linear_rules[idx] : null;
|
| 48 |
+
while (idx < linear_rules.length && (is_rule_def_char_rng_upper(rule) || is_rule_def_char_alt(rule))) {
|
| 49 |
+
if (is_rule_def_char_rng_upper(rule)) {
|
| 50 |
+
// previous rule value should be a number
|
| 51 |
+
if (char_rule.value.length === 0) {
|
| 52 |
+
throw new IndexError('pop from empty list');
|
| 53 |
+
}
|
| 54 |
+
const prev_value = char_rule.value.pop();
|
| 55 |
+
if (is_range(prev_value)) {
|
| 56 |
+
throw new ValueError(
|
| 57 |
+
`Unexpected range, expected a number but got an array: ${json_dumps(prev_value)}`,
|
| 58 |
+
);
|
| 59 |
+
}
|
| 60 |
+
if (prev_value === null || prev_value === undefined) {
|
| 61 |
+
throw new ValueError('Unexpected undefined value');
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
char_rule.value.push([prev_value as number, rule.value]);
|
| 65 |
+
}
|
| 66 |
+
if (is_rule_def_char_alt(rule)) {
|
| 67 |
+
char_rule.value.push(rule.value);
|
| 68 |
+
}
|
| 69 |
+
idx += 1;
|
| 70 |
+
rule = idx < linear_rules.length ? linear_rules[idx] : null;
|
| 71 |
+
}
|
| 72 |
+
paths.push(char_rule);
|
| 73 |
+
} else {
|
| 74 |
+
if (is_rule_def_alt(rule_def)) {
|
| 75 |
+
if (paths.length === 0) {
|
| 76 |
+
throw new ValueError('Encountered alt without anything before it');
|
| 77 |
+
}
|
| 78 |
+
paths.push(new RuleEnd());
|
| 79 |
+
stack.push(paths);
|
| 80 |
+
paths = [];
|
| 81 |
+
} else if (is_rule_def_end(rule_def)) {
|
| 82 |
+
paths.push(new RuleEnd());
|
| 83 |
+
} else if (is_rule_def_ref(rule_def)) {
|
| 84 |
+
paths.push(new RuleRef(rule_def.value));
|
| 85 |
+
} else if (is_rule_def_char_alt(rule_def)) {
|
| 86 |
+
throw new ValueError(`Encountered char alt, should be handled by above block: ${repr(rule_def)}`);
|
| 87 |
+
} else {
|
| 88 |
+
throw new ValueError(`Unsupported rule type: ${repr(rule_def)}`);
|
| 89 |
+
}
|
| 90 |
+
idx += 1;
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
if (paths.length === 0) {
|
| 95 |
+
throw new IndexError('list index out of range');
|
| 96 |
+
}
|
| 97 |
+
if (!is_rule_end(paths[paths.length - 1])) {
|
| 98 |
+
paths.push(new RuleEnd());
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
stack.push(paths);
|
| 102 |
+
return stack;
|
| 103 |
+
};
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/index.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export { GBNF } from './GBNF.js';
|
| 2 |
+
export { GBNF as default } from './GBNF.js';
|
| 3 |
+
export { RuleChar, RuleCharExclude, RuleEnd } from './grammar_graph/grammar_graph_types.js';
|
| 4 |
+
export type { ResolvedRule } from './grammar_graph/grammar_graph_types.js';
|
| 5 |
+
export type { ParseState } from './grammar_graph/parse_state.js';
|
| 6 |
+
export { GrammarParseError, InputParseError } from './utils/errors/index.js';
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/rules_builder/index.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export { GrammarParseError, InputParseError } from '../utils/errors/index.js';
|
| 2 |
+
export { RulesBuilder } from './rules_builder.js';
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/rules_builder/is_word_char.test.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, test } from 'vitest';
|
| 2 |
+
|
| 3 |
+
import { is_word_char } from './is_word_char.js';
|
| 4 |
+
|
| 5 |
+
test('should return true for lowercase letters', () => {
|
| 6 |
+
expect(is_word_char('a')).toBe(true);
|
| 7 |
+
expect(is_word_char('z')).toBe(true);
|
| 8 |
+
});
|
| 9 |
+
|
| 10 |
+
test('should return true for uppercase letters', () => {
|
| 11 |
+
expect(is_word_char('A')).toBe(true);
|
| 12 |
+
expect(is_word_char('Z')).toBe(true);
|
| 13 |
+
});
|
| 14 |
+
|
| 15 |
+
test('should return false for digits', () => {
|
| 16 |
+
expect(is_word_char('0')).toBe(false);
|
| 17 |
+
expect(is_word_char('9')).toBe(false);
|
| 18 |
+
});
|
| 19 |
+
|
| 20 |
+
test('should return false for non word characters', () => {
|
| 21 |
+
expect(is_word_char('-')).toBe(false);
|
| 22 |
+
expect(is_word_char('@')).toBe(false);
|
| 23 |
+
expect(is_word_char('_')).toBe(false);
|
| 24 |
+
expect(is_word_char('?')).toBe(false);
|
| 25 |
+
expect(is_word_char(' ')).toBe(false);
|
| 26 |
+
});
|
v2-models-effort/runs/20261111-214430-mute-surf/ported_implementation/gbnf/rules_builder/is_word_char.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export const is_word_char = (c: string): boolean => /[a-zA-Z]/.test(c);
|