thekevinscott commited on
Commit
f596990
·
verified ·
1 Parent(s): a413d88

Upload experiments v1, v2-models-effort, v2-tests-configuration as on disk 2026-11-11 (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. v1/runs/20260909T015142Z_f8ca89ff/transcript/-workspace/8658e7af-459d-4482-a62e-7a5987d49cc3.jsonl +0 -0
  2. v1/runs/20260909T020947Z_ffb57550/manifest.json +23 -0
  3. v1/runs/20260909T020947Z_ffb57550/ported_implementation/README.md +48 -0
  4. v1/runs/20260909T020947Z_ffb57550/ported_implementation/package.json +14 -0
  5. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/GBNF.ts +32 -0
  6. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/colorize.ts +11 -0
  7. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/get-input-as-code-points.ts +32 -0
  8. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/get-parent-stack-id.ts +18 -0
  9. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/get-serialized-rule-key.ts +35 -0
  10. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/grammar-graph-types.ts +55 -0
  11. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/graph-node.ts +41 -0
  12. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/graph-pointer.ts +106 -0
  13. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/graph.ts +280 -0
  14. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/parse-state.ts +45 -0
  15. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/pointers.ts +23 -0
  16. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/print.ts +86 -0
  17. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/rule-ref.ts +23 -0
  18. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/rule-type.ts +6 -0
  19. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/type-guards.ts +55 -0
  20. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-parser/build-rule-stack.ts +111 -0
  21. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/index.ts +24 -0
  22. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/is-word-char.ts +1 -0
  23. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/parse-char.ts +45 -0
  24. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/parse-name.ts +21 -0
  25. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/parse-space.ts +22 -0
  26. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/rules-builder-types.ts +119 -0
  27. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/rules-builder.ts +275 -0
  28. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/symbol-ids.ts +47 -0
  29. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/build-error-position.ts +28 -0
  30. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/errors-types.ts +1 -0
  31. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/get-input-as-string.ts +16 -0
  32. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/grammar-parse-error.ts +26 -0
  33. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/index.ts +3 -0
  34. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/input-parse-error.ts +56 -0
  35. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/is-point-in-range.ts +8 -0
  36. v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/validate-non-empty.ts +6 -0
  37. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/README.md +13 -0
  38. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/grammars.test.ts +0 -0
  39. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/iteration-with-additional-strings.test.ts +394 -0
  40. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/iteration-with-an-initial-string.test.ts +447 -0
  41. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/iteration.test.ts +108 -0
  42. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/validation/validate-grammar.test.ts +49 -0
  43. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/validation/validate-input.test.ts +122 -0
  44. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/vitest.config.unit.ts +17 -0
  45. v1/runs/20260909T020947Z_ffb57550/ported_implementation/tsconfig.json +15 -0
  46. v1/runs/20260909T020947Z_ffb57550/ported_implementation/vitest.config.unit.ts +17 -0
  47. v1/runs/20260909T020947Z_ffb57550/proxy.log +62 -0
  48. v1/runs/20260909T020947Z_ffb57550/result.json +1 -0
  49. v1/runs/20260909T020947Z_ffb57550/transcript/-workspace/cff45a82-8ac1-4e8e-87fe-be8d30ab6e86.jsonl +0 -0
  50. v1/runs/20260909T020947Z_ffb57550/transcript/-workspace/cff45a82-8ac1-4e8e-87fe-be8d30ab6e86/tool-results/bxo19mfrs.txt +1752 -0
v1/runs/20260909T015142Z_f8ca89ff/transcript/-workspace/8658e7af-459d-4482-a62e-7a5987d49cc3.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
v1/runs/20260909T020947Z_ffb57550/manifest.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2026-09-09T02:09:47Z",
3
+ "completed_at": "2026-09-09T02:22:16Z",
4
+ "condition": {
5
+ "name": "source-python_typescript-tests_python-tests_effort-high_model-claude-opus-5",
6
+ "source_language": "python",
7
+ "target_language": "typescript",
8
+ "include_python_tests": true,
9
+ "include_typescript_tests": true,
10
+ "effort": "high",
11
+ "model": "claude-opus-5"
12
+ },
13
+ "derivation": {
14
+ "gbnf_commit": "13f1aca495d11e160fffd68c4ba299a2415909d8"
15
+ },
16
+ "sandbox": {
17
+ "image_id": "sha256:92a34a188eeb62fa90196a1156a1d80407121d137af9c44e697d01c2f7a0cfd1"
18
+ },
19
+ "harness": {
20
+ "commit": "7f09c9ba503d957788ae4b07a04227f28c5f78b6",
21
+ "dirty": true
22
+ }
23
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/README.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gbnf (TypeScript)
2
+
3
+ A TypeScript port of `reference_implementation/` (the Python `gbnf` package).
4
+
5
+ ```ts
6
+ import GBNF, { GrammarParseError, InputParseError, RuleType } from 'gbnf';
7
+
8
+ let state = GBNF('root ::= "foo"');
9
+ state = state.add('f');
10
+ [...state]; // [{ type: 'char', value: [111] }]
11
+ ```
12
+
13
+ `GBNF(grammar, initialString?)` builds the grammar graph and returns a `ParseState`.
14
+ Iterating a `ParseState` yields the deduplicated set of rules that may match next
15
+ (`{ type: 'char' | 'char_exclude', value }` or `{ type: 'end' }`). `state.add(text)`
16
+ advances the parse and returns a new `ParseState`, throwing `InputParseError` when the
17
+ text cannot be matched; invalid grammars throw `GrammarParseError`.
18
+
19
+ ## Layout
20
+
21
+ The module layout mirrors the reference implementation, with Python `snake_case`
22
+ filenames rendered as `kebab-case`:
23
+
24
+ | Python | TypeScript |
25
+ | --- | --- |
26
+ | `gbnf/GBNF.py` | `src/GBNF.ts` |
27
+ | `gbnf/__init__.py` | `src/index.ts` |
28
+ | `gbnf/grammar_graph/*` | `src/grammar-graph/*` |
29
+ | `gbnf/grammar_parser/*` | `src/grammar-parser/*` |
30
+ | `gbnf/rules_builder/*` | `src/rules-builder/*` |
31
+ | `gbnf/utils/*` | `src/utils/*` |
32
+
33
+ Notable translations:
34
+
35
+ - Rules are plain tagged objects (`{ type: RuleType.CHAR, value }`) rather than
36
+ dataclasses; `RuleRef` stays a class because its `nodes` are patched in after the
37
+ graph is built.
38
+ - Python's generators, `OrderedDict`, and `set` map to JS generators, `Map`, and `Set`,
39
+ all of which preserve insertion order — which is what fixes the order rules are
40
+ yielded in.
41
+ - Input is decoded to code points with `Array.from`, matching Python's per-code-point
42
+ string iteration.
43
+
44
+ ## Tests
45
+
46
+ ```sh
47
+ npx vitest run --config vitest.config.unit.ts
48
+ ```
v1/runs/20260909T020947Z_ffb57550/ported_implementation/package.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gbnf",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript port of the GBNF grammar parser",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "scripts": {
12
+ "test": "vitest run --config vitest.config.unit.ts"
13
+ }
14
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/GBNF.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Graph } from './grammar-graph/graph.js';
2
+ import { ParseState } from './grammar-graph/parse-state.js';
3
+ import { buildRuleStack } from './grammar-parser/build-rule-stack.js';
4
+ import { RulesBuilder } from './rules-builder/rules-builder.js';
5
+ import { GrammarParseError } from './utils/errors/index.js';
6
+
7
+ export const GBNF = (grammar: string, initialString = ''): ParseState => {
8
+ if (typeof grammar !== 'string') {
9
+ throw new Error('grammar must be a string');
10
+ }
11
+
12
+ if (typeof initialString !== 'string') {
13
+ throw new Error('input must be a string');
14
+ }
15
+
16
+ const { rules, symbolIds } = new RulesBuilder(grammar);
17
+ if (rules.length === 0) {
18
+ throw new GrammarParseError(grammar, 0, 'No rules were found');
19
+ }
20
+ const rootId = symbolIds.get('root');
21
+ if (rootId === undefined) {
22
+ throw new GrammarParseError(
23
+ grammar,
24
+ 0,
25
+ "Grammar does not contain a 'root' symbol",
26
+ );
27
+ }
28
+
29
+ const stackedRules = rules.map((rule) => buildRuleStack(rule));
30
+ const graph = new Graph(grammar, stackedRules, rootId);
31
+ return new ParseState(graph, graph.add(initialString));
32
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/colorize.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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 =>
11
+ `${color}${text}`;
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/get-input-as-code-points.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ValidInput } from './grammar-graph-types.js';
2
+
3
+ export const getCodePoint = (char: string): number => {
4
+ const codePoint = char.codePointAt(0);
5
+ if (codePoint === undefined) {
6
+ throw new Error(`Could not get code point for character: ${char}`);
7
+ }
8
+ return codePoint;
9
+ };
10
+
11
+ export const getInputAsCodePoints = (src: ValidInput): number[] => {
12
+ if (typeof src === 'number') {
13
+ return [src];
14
+ }
15
+
16
+ if (Array.isArray(src)) {
17
+ for (const c of src) {
18
+ if (!Number.isInteger(c)) {
19
+ throw new Error(
20
+ `code_point must be an integer for ${c} if src is a list`,
21
+ );
22
+ }
23
+ }
24
+ return src;
25
+ }
26
+
27
+ if (typeof src === 'string') {
28
+ return Array.from(src).map(getCodePoint);
29
+ }
30
+
31
+ throw new Error(`Invalid input type: ${typeof src}`);
32
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/get-parent-stack-id.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Color } from './colorize.js';
2
+ import type { Colorize } from './grammar-graph-types.js';
3
+ import type { GraphPointer } from './graph-pointer.js';
4
+
5
+ export const getParentStackId = (
6
+ pointer: GraphPointer,
7
+ col: Colorize,
8
+ ): string => {
9
+ const stackIds: string[] = [];
10
+ let parent: GraphPointer | undefined = pointer.parent;
11
+ while (parent) {
12
+ const { stackId, pathId, stepId } = parent.node.meta;
13
+ stackIds.push(`${stackId},${pathId},${stepId}`);
14
+ parent = parent.parent;
15
+ }
16
+ const arrow = col('<-', Color.GRAY);
17
+ return stackIds.map((stackId) => col(stackId, Color.RED)).join(arrow);
18
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/get-serialized-rule-key.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { UnresolvedRule } from './grammar-graph-types.js';
2
+ import { RuleType } from './rule-type.js';
3
+ import {
4
+ isRuleChar,
5
+ isRuleCharExclude,
6
+ isRuleEnd,
7
+ isRuleRef,
8
+ } from './type-guards.js';
9
+
10
+ const KEY_TRANSLATION = {
11
+ [RuleType.END]: 0,
12
+ [RuleType.CHAR]: 1,
13
+ [RuleType.CHAR_EXCLUDE]: 2,
14
+ [RuleType.REF]: 3,
15
+ } as const;
16
+
17
+ export const getSerializedRuleKey = (rule: UnresolvedRule): string => {
18
+ if (isRuleEnd(rule)) {
19
+ return `${KEY_TRANSLATION[RuleType.END]}`;
20
+ }
21
+
22
+ if (isRuleChar(rule)) {
23
+ return `${KEY_TRANSLATION[RuleType.CHAR]}-${JSON.stringify(rule.value)}`;
24
+ }
25
+
26
+ if (isRuleCharExclude(rule)) {
27
+ return `${KEY_TRANSLATION[RuleType.CHAR_EXCLUDE]}-${JSON.stringify(rule.value)}`;
28
+ }
29
+
30
+ if (isRuleRef(rule)) {
31
+ return `${KEY_TRANSLATION[RuleType.REF]}-${rule.value}`;
32
+ }
33
+
34
+ throw new Error(`Unknown rule type: ${JSON.stringify(rule)}`);
35
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/grammar-graph-types.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { validateNonEmpty } from '../utils/validate-non-empty.js';
2
+ import type { GraphPointer } from './graph-pointer.js';
3
+ import type { Pointers } from './pointers.js';
4
+ import type { RuleRef } from './rule-ref.js';
5
+ import { RuleType } from './rule-type.js';
6
+
7
+ export type Colorize = (text: string | number, color: string) => string;
8
+
9
+ export interface PrintOpts {
10
+ pointers?: Pointers;
11
+ colorize: Colorize;
12
+ showPosition?: boolean;
13
+ }
14
+
15
+ export type Range = [number, number];
16
+
17
+ export interface RuleChar {
18
+ type: RuleType.CHAR;
19
+ value: (number | Range)[];
20
+ }
21
+
22
+ export interface RuleCharExclude {
23
+ type: RuleType.CHAR_EXCLUDE;
24
+ value: (number | Range)[];
25
+ }
26
+
27
+ export interface RuleEnd {
28
+ type: RuleType.END;
29
+ }
30
+
31
+ export const ruleChar = (value: (number | Range)[]): RuleChar => ({
32
+ type: RuleType.CHAR,
33
+ value: validateNonEmpty([...value]),
34
+ });
35
+
36
+ export const ruleCharExclude = (
37
+ value: (number | Range)[],
38
+ ): RuleCharExclude => ({
39
+ type: RuleType.CHAR_EXCLUDE,
40
+ value: validateNonEmpty([...value]),
41
+ });
42
+
43
+ export const ruleEnd = (): RuleEnd => ({ type: RuleType.END });
44
+
45
+ export type UnresolvedRule = RuleChar | RuleCharExclude | RuleRef | RuleEnd;
46
+
47
+ // RuleRefs should never be exposed to the end user.
48
+ export type ResolvedRule = RuleCharExclude | RuleChar | RuleEnd;
49
+
50
+ // ValidInput can either be a string, or a number indicating a code point.
51
+ // It CANNOT be a number representing a number; a number intended as input (like "8")
52
+ // should be passed in as a string.
53
+ export type ValidInput = string | number | number[];
54
+
55
+ export type ResolvedGraphPointer = GraphPointer<ResolvedRule>;
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/graph-node.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { PrintOpts, UnresolvedRule } from './grammar-graph-types.js';
2
+ import { printGraphNode } from './print.js';
3
+
4
+ export interface GraphNodeMeta {
5
+ stackId: number;
6
+ pathId: number;
7
+ stepId: number;
8
+ }
9
+
10
+ export class GraphNode<T extends UnresolvedRule = UnresolvedRule> {
11
+ // `rule` is readonly so that `GraphNode` stays covariant in `T`; a mutable
12
+ // property would make narrowed nodes unassignable to `GraphNode`.
13
+ readonly rule: T;
14
+ readonly next: GraphNode | undefined;
15
+ readonly meta: GraphNodeMeta;
16
+ #id: string | undefined = undefined;
17
+
18
+ constructor(
19
+ rule: T,
20
+ meta: GraphNodeMeta | undefined,
21
+ nextNode?: GraphNode | undefined,
22
+ ) {
23
+ this.rule = rule;
24
+ if (meta === undefined) {
25
+ throw new Error('Meta is undefined');
26
+ }
27
+ this.meta = meta;
28
+ this.next = nextNode;
29
+ }
30
+
31
+ get id(): string {
32
+ if (this.#id === undefined) {
33
+ this.#id = `${this.meta.stackId},${this.meta.pathId},${this.meta.stepId}`;
34
+ }
35
+ return this.#id;
36
+ }
37
+
38
+ print(opts: PrintOpts): string {
39
+ return printGraphNode(this)(opts);
40
+ }
41
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/graph-pointer.ts ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type {
2
+ PrintOpts,
3
+ ResolvedGraphPointer,
4
+ UnresolvedRule,
5
+ } from './grammar-graph-types.js';
6
+ import { GraphNode } from './graph-node.js';
7
+ import { printGraphPointer } from './print.js';
8
+ import {
9
+ isGraphPointerRuleChar,
10
+ isGraphPointerRuleCharExclude,
11
+ isGraphPointerRuleEnd,
12
+ isGraphPointerRuleRef,
13
+ isRuleEnd,
14
+ } from './type-guards.js';
15
+
16
+ export type GraphPointerKey = string;
17
+
18
+ export class GraphPointer<T extends UnresolvedRule = UnresolvedRule> {
19
+ readonly node: GraphNode<T>;
20
+ readonly parent: GraphPointer | undefined;
21
+ readonly id: GraphPointerKey;
22
+ #valid: boolean | undefined = undefined;
23
+
24
+ constructor(node: GraphNode<T>, parent?: GraphPointer | undefined) {
25
+ if (node === undefined) {
26
+ throw new Error('Node is undefined');
27
+ }
28
+ this.node = node;
29
+ this.parent = parent;
30
+ this.id = parent ? `${parent.id}-${node.id}` : node.id;
31
+ }
32
+
33
+ get rule(): T {
34
+ return this.node.rule;
35
+ }
36
+
37
+ get valid(): boolean | undefined {
38
+ return this.#valid;
39
+ }
40
+
41
+ set valid(valid: boolean) {
42
+ this.#valid = valid;
43
+ }
44
+
45
+ print(opts: PrintOpts): string {
46
+ return printGraphPointer(this)(opts);
47
+ }
48
+
49
+ /**
50
+ * Resolve the graph pointer.
51
+ *
52
+ * @param resolved Whether the pointer has already been resolved.
53
+ */
54
+ *resolve(resolved = false): Generator<ResolvedGraphPointer> {
55
+ const pointer: GraphPointer = this;
56
+ if (isGraphPointerRuleRef(pointer)) {
57
+ if (resolved) {
58
+ if (!pointer.node.next) {
59
+ throw new Error(`No next node: ${pointer.node.id}`);
60
+ }
61
+ yield* new GraphPointer(pointer.node.next, pointer.parent).resolve();
62
+ } else {
63
+ for (const node of pointer.rule.nodes) {
64
+ yield* new GraphPointer(node, pointer).resolve();
65
+ }
66
+ }
67
+ } else if (isGraphPointerRuleEnd(pointer)) {
68
+ if (!pointer.parent) {
69
+ yield pointer;
70
+ } else {
71
+ yield* pointer.parent.resolve(true);
72
+ }
73
+ } else if (
74
+ isGraphPointerRuleChar(pointer) ||
75
+ isGraphPointerRuleCharExclude(pointer)
76
+ ) {
77
+ yield pointer;
78
+ } else {
79
+ throw new Error(`Unknown rule: ${JSON.stringify(pointer.node.rule)}`);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Fetch the next resolved graph pointer.
85
+ */
86
+ *fetchNext(): Generator<GraphPointer> {
87
+ // If this pointer is invalid, then we don't return any new pointers
88
+ if (!this.valid) {
89
+ return;
90
+ }
91
+
92
+ // If this pointer is an end node, we return the parent's next node.
93
+ // If no parent exists, we return nothing, since it's the end of the line.
94
+ if (isRuleEnd(this.node.rule)) {
95
+ if (this.parent) {
96
+ yield* this.parent.fetchNext();
97
+ }
98
+ } else {
99
+ if (!this.node.next) {
100
+ throw new Error(`No next node: ${this.node.id}`);
101
+ }
102
+ const pointer = new GraphPointer(this.node.next, this.parent);
103
+ yield* pointer.resolve();
104
+ }
105
+ }
106
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/graph.ts ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { InputParseError } from '../utils/errors/index.js';
2
+ import { isPointInRange } from '../utils/is-point-in-range.js';
3
+ import { colorize } from './colorize.js';
4
+ import { getInputAsCodePoints } from './get-input-as-code-points.js';
5
+ import { getSerializedRuleKey } from './get-serialized-rule-key.js';
6
+ import type {
7
+ ResolvedGraphPointer,
8
+ UnresolvedRule,
9
+ ValidInput,
10
+ } from './grammar-graph-types.js';
11
+ import { GraphNode } from './graph-node.js';
12
+ import { GraphPointer } from './graph-pointer.js';
13
+ import { Pointers } from './pointers.js';
14
+ import type { RuleRef } from './rule-ref.js';
15
+ import {
16
+ isRange,
17
+ isRuleChar,
18
+ isRuleCharExclude,
19
+ isRuleEnd,
20
+ isRuleRef,
21
+ } from './type-guards.js';
22
+
23
+ export type RootNode = Map<number, GraphNode>;
24
+
25
+ export class Graph {
26
+ #roots = new Map<number, RootNode>();
27
+ #rootNode: RootNode;
28
+ grammar: string;
29
+ previousCodePoints: number[] = [];
30
+
31
+ constructor(
32
+ grammar: string,
33
+ stackedRules: UnresolvedRule[][][],
34
+ rootId: number,
35
+ ) {
36
+ this.grammar = grammar;
37
+ const ruleRefs: RuleRef[] = [];
38
+ const uniqueRules = new Map<string, UnresolvedRule>();
39
+
40
+ for (let stackId = 0; stackId < stackedRules.length; stackId++) {
41
+ const stack = stackedRules[stackId];
42
+ const nodes: RootNode = new Map();
43
+ for (let pathId = 0; pathId < stack.length; pathId++) {
44
+ const path = stack[pathId];
45
+ let node: GraphNode | undefined = undefined;
46
+ for (let stepId = path.length - 1; stepId >= 0; stepId--) {
47
+ const nextNode: GraphNode | undefined = node;
48
+ const rule = stack[pathId][stepId];
49
+ uniqueRules.set(getSerializedRuleKey(rule), rule);
50
+ if (isRuleRef(rule)) {
51
+ ruleRefs.push(rule);
52
+ }
53
+ // rules coming in may be identical but have different references.
54
+ // here, we ensure we always use the same reference for an identical rule.
55
+ // this makes future comparisons easier.
56
+ const uniqueRule = uniqueRules.get(getSerializedRuleKey(rule));
57
+ if (uniqueRule === undefined) {
58
+ throw new Error('Could not get unique rule');
59
+ }
60
+ node = new GraphNode(
61
+ uniqueRule,
62
+ { stackId, pathId, stepId },
63
+ nextNode,
64
+ );
65
+ }
66
+
67
+ if (node === undefined) {
68
+ throw new Error('Could not get node');
69
+ }
70
+ nodes.set(pathId, node);
71
+ }
72
+ this.#roots.set(stackId, nodes);
73
+ }
74
+
75
+ const rootNode = this.#roots.get(rootId);
76
+ if (rootNode === undefined) {
77
+ throw new Error(`Root node not found for value: ${rootId}`);
78
+ }
79
+ this.#rootNode = rootNode;
80
+
81
+ for (const ruleRef of ruleRefs) {
82
+ ruleRef.nodes = new Set(this.#getRootNode(ruleRef.value).values());
83
+ }
84
+ }
85
+
86
+ #getRootNode(value: number): RootNode {
87
+ const rootNode = this.#roots.get(value);
88
+ if (rootNode === undefined) {
89
+ throw new Error(`Root node not found for value: ${value}`);
90
+ }
91
+ return rootNode;
92
+ }
93
+
94
+ #getInitialPointers(): Pointers {
95
+ const pointers = new Pointers();
96
+
97
+ const rootNode = this.#rootNode;
98
+ if (rootNode === undefined) {
99
+ throw new Error('Root node is not defined');
100
+ }
101
+
102
+ for (const [node, parent] of this.#fetchNodesForRootNode(rootNode)) {
103
+ const pointer = new GraphPointer(node, parent);
104
+ for (const resolvedPointer of this.#resolvePointer(pointer)) {
105
+ pointers.add(resolvedPointer);
106
+ }
107
+ }
108
+ return pointers;
109
+ }
110
+
111
+ #setValid(pointers: GraphPointer[], valid: boolean): void {
112
+ for (const pointer of pointers) {
113
+ pointer.valid = valid;
114
+ }
115
+ }
116
+
117
+ #parse(currentPointers: Pointers, codePoint: number): Pointers {
118
+ for (const [rule, graphPointers] of this.#iterateOverPointers(
119
+ currentPointers,
120
+ )) {
121
+ if (isRuleChar(rule)) {
122
+ let valid = false;
123
+ for (const possibleCodePoint of rule.value) {
124
+ if (valid === true) {
125
+ // already valid; nothing left to check
126
+ } else if (isRange(possibleCodePoint)) {
127
+ if (isPointInRange(codePoint, possibleCodePoint)) {
128
+ valid = true;
129
+ }
130
+ } else if (codePoint === possibleCodePoint) {
131
+ valid = true;
132
+ }
133
+ }
134
+ this.#setValid(graphPointers, valid);
135
+ } else if (isRuleCharExclude(rule)) {
136
+ let valid = true;
137
+ for (const possibleCodePoint of rule.value) {
138
+ if (valid === false) {
139
+ // already invalid; nothing left to check
140
+ } else if (isRange(possibleCodePoint)) {
141
+ if (isPointInRange(codePoint, possibleCodePoint)) {
142
+ valid = false;
143
+ }
144
+ } else if (codePoint === possibleCodePoint) {
145
+ valid = false;
146
+ }
147
+ }
148
+ this.#setValid(graphPointers, valid);
149
+ } else if (!isRuleEnd(rule)) {
150
+ throw new Error(`Unsupported rule: ${JSON.stringify(rule)}`);
151
+ }
152
+ }
153
+
154
+ // a pointer's id is the sum of its node's id and its parent's id chain.
155
+ // if two pointers share the same id, it means they point to the same node and have identical parent chains.
156
+ // for the purposes of walking the graph, we only need to keep one of them.
157
+ const nextPointers = new Pointers();
158
+ for (const currentPointer of currentPointers) {
159
+ for (const unresolvedNextPointer of currentPointer.fetchNext()) {
160
+ for (const resolvedNextPointer of this.#resolvePointer(
161
+ unresolvedNextPointer,
162
+ )) {
163
+ nextPointers.add(resolvedNextPointer);
164
+ }
165
+ }
166
+ }
167
+ return nextPointers;
168
+ }
169
+
170
+ *#resolvePointer(
171
+ unresolvedPointer: GraphPointer,
172
+ ): Generator<ResolvedGraphPointer> {
173
+ for (const resolvedPointer of unresolvedPointer.resolve()) {
174
+ if (isRuleRef(resolvedPointer.node.rule)) {
175
+ throw new Error(
176
+ 'Encountered a reference rule when building pointers to the graph',
177
+ );
178
+ }
179
+ if (
180
+ isRuleEnd(resolvedPointer.node.rule) &&
181
+ resolvedPointer.parent !== undefined
182
+ ) {
183
+ throw new Error(
184
+ 'Encountered an ending rule with a parent when building pointers to the graph',
185
+ );
186
+ }
187
+ yield resolvedPointer;
188
+ }
189
+ }
190
+
191
+ add(src: ValidInput, pointers?: Pointers): Pointers {
192
+ if (typeof src !== 'string') {
193
+ throw new Error('src must be a string in graph.add');
194
+ }
195
+ let currentPointers =
196
+ pointers && pointers.size > 0 ? pointers : this.#getInitialPointers();
197
+
198
+ const codePoints = getInputAsCodePoints(src);
199
+ for (const codePoint of codePoints) {
200
+ if (!Number.isInteger(codePoint)) {
201
+ throw new Error('code_point must be an integer!');
202
+ }
203
+ }
204
+
205
+ for (let codePointPos = 0; codePointPos < codePoints.length; codePointPos++) {
206
+ const codePoint = codePoints[codePointPos];
207
+ currentPointers = this.#parse(currentPointers, codePoint);
208
+ if (currentPointers.size === 0) {
209
+ throw new InputParseError(
210
+ codePoints,
211
+ codePointPos,
212
+ this.previousCodePoints,
213
+ );
214
+ }
215
+ }
216
+ this.previousCodePoints.push(...codePoints);
217
+ return currentPointers;
218
+ }
219
+
220
+ // generator that yields either the node, or if a reference rule, the referenced node
221
+ // we need this function, as distinct from leveraging the logic in GraphPointer,
222
+ // because that needs a rule ref with already defined nodes; this function is used to _set_ those nodes
223
+ *#fetchNodesForRootNode(
224
+ rootNodes: RootNode,
225
+ parent?: GraphPointer | undefined,
226
+ ): Generator<[GraphNode, GraphPointer | undefined]> {
227
+ for (const node of rootNodes.values()) {
228
+ const rule = node.rule;
229
+ if (isRuleRef(rule)) {
230
+ yield* this.#fetchNodesForRootNode(
231
+ this.#getRootNode(rule.value),
232
+ new GraphPointer(node, parent),
233
+ );
234
+ } else {
235
+ yield [node, parent];
236
+ }
237
+ }
238
+ }
239
+
240
+ print(pointers?: Pointers, colors = false): string {
241
+ const nodes: GraphNode[][] = [...this.#roots.values()].map((rootNode) => [
242
+ ...rootNode.values(),
243
+ ]);
244
+ const graphView: string[] = [];
245
+ for (const rootNode of nodes) {
246
+ for (const node of rootNode) {
247
+ graphView.push(
248
+ node.print({
249
+ pointers: pointers ?? new Pointers(),
250
+ showPosition: true,
251
+ colorize: colors ? colorize : (s) => `${s}`,
252
+ }),
253
+ );
254
+ }
255
+ }
256
+
257
+ return graphView.join('\n');
258
+ }
259
+
260
+ *#iterateOverPointers(
261
+ pointers: Pointers,
262
+ ): Generator<[UnresolvedRule, GraphPointer[]]> {
263
+ const seenRules = new Map<UnresolvedRule, GraphPointer[]>();
264
+ for (const pointer of pointers) {
265
+ const rule = pointer.rule;
266
+ if (isRuleRef(rule)) {
267
+ throw new Error('Encountered a reference rule in the graph');
268
+ }
269
+
270
+ let seenRule = seenRules.get(rule);
271
+ if (seenRule === undefined) {
272
+ seenRule = [];
273
+ seenRules.set(rule, seenRule);
274
+ }
275
+ seenRule.push(pointer);
276
+ }
277
+
278
+ yield* seenRules;
279
+ }
280
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/parse-state.ts ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ResolvedRule } from './grammar-graph-types.js';
2
+ import type { Graph } from './graph.js';
3
+ import type { Pointers } from './pointers.js';
4
+
5
+ export class ParseState {
6
+ #graph: Graph;
7
+ #pointers: Pointers;
8
+
9
+ constructor(graph: Graph, pointers: Pointers) {
10
+ this.#graph = graph;
11
+ this.#pointers = pointers;
12
+ }
13
+
14
+ *[Symbol.iterator](): IterableIterator<ResolvedRule> {
15
+ yield* this.rules();
16
+ }
17
+
18
+ *rules(): Generator<ResolvedRule> {
19
+ const rules = new Set<string>();
20
+ for (const pointer of this.#pointers) {
21
+ const rule = pointer.rule as ResolvedRule;
22
+ const key = JSON.stringify(rule);
23
+ if (!rules.has(key)) {
24
+ rules.add(key);
25
+ yield rule;
26
+ }
27
+ }
28
+ }
29
+
30
+ add(text: string): ParseState {
31
+ if (typeof text !== 'string') {
32
+ throw new Error('input text must be of type string');
33
+ }
34
+ const pointers = this.#graph.add(text, this.#pointers);
35
+ return new ParseState(this.#graph, pointers);
36
+ }
37
+
38
+ get size(): number {
39
+ return [...this.rules()].length;
40
+ }
41
+
42
+ get grammar(): string {
43
+ return this.#graph.grammar;
44
+ }
45
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/pointers.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphPointer, GraphPointerKey } from './graph-pointer.js';
2
+
3
+ export class Pointers {
4
+ #pointers = new Map<GraphPointerKey, GraphPointer>();
5
+
6
+ constructor(...pointers: GraphPointer[]) {
7
+ for (const pointer of pointers) {
8
+ this.add(pointer);
9
+ }
10
+ }
11
+
12
+ add(pointer: GraphPointer): void {
13
+ this.#pointers.set(pointer.id, pointer);
14
+ }
15
+
16
+ *[Symbol.iterator](): IterableIterator<GraphPointer> {
17
+ yield* this.#pointers.values();
18
+ }
19
+
20
+ get size(): number {
21
+ return this.#pointers.size;
22
+ }
23
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/print.ts ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Color } from './colorize.js';
2
+ import type { PrintOpts } from './grammar-graph-types.js';
3
+ import type { GraphNode } from './graph-node.js';
4
+ import type { GraphPointer } from './graph-pointer.js';
5
+ import { getParentStackId } from './get-parent-stack-id.js';
6
+ import { isRange, isRuleChar, isRuleRef } from './type-guards.js';
7
+
8
+ export const printGraphPointer =
9
+ (pointer: GraphPointer) =>
10
+ (opts: PrintOpts): string => {
11
+ const col = opts.colorize;
12
+ return col(`*${getParentStackId(pointer, col)}`, Color.RED);
13
+ };
14
+
15
+ export const printGraphNode =
16
+ (node: GraphNode) =>
17
+ (opts: PrintOpts): string => {
18
+ const { pointers, colorize: col } = opts;
19
+ const showPosition = opts.showPosition ?? false;
20
+ const rule = node.rule;
21
+ const parts: string[] = [];
22
+ if (showPosition) {
23
+ parts.push(
24
+ col('{', Color.BLUE),
25
+ col(node.id, Color.GRAY),
26
+ col('}', Color.BLUE),
27
+ );
28
+ }
29
+
30
+ if (isRuleChar(rule)) {
31
+ parts.push(
32
+ col('[', Color.GRAY),
33
+ col(
34
+ rule.value
35
+ .map((v) =>
36
+ isRange(v)
37
+ ? v.map((val) => col(getChar(val), Color.YELLOW)).join('')
38
+ : getChar(v),
39
+ )
40
+ .join(''),
41
+ Color.YELLOW,
42
+ ),
43
+ col(']', Color.GRAY),
44
+ );
45
+ } else if (isRuleRef(rule)) {
46
+ parts.push(
47
+ col('Ref(', Color.GRAY),
48
+ col(rule.value, Color.GREEN),
49
+ col(')', Color.GRAY),
50
+ );
51
+ } else {
52
+ parts.push(col(rule.type, Color.YELLOW));
53
+ }
54
+
55
+ if (pointers && pointers.size > 0) {
56
+ for (const pointer of pointers) {
57
+ const pointerParts: string[] = [];
58
+ if (pointer.node === node) {
59
+ pointerParts.push(pointer.print(opts));
60
+ }
61
+
62
+ if (pointerParts.length > 0) {
63
+ parts.push(
64
+ col('[', Color.GRAY),
65
+ col(pointerParts.join(''), Color.YELLOW),
66
+ col(']', Color.GRAY),
67
+ );
68
+ }
69
+ }
70
+ }
71
+
72
+ const partsToReturn = [parts.join('')];
73
+ if (node.next) {
74
+ partsToReturn.push(node.next.print(opts));
75
+ }
76
+
77
+ return partsToReturn.join(col('-> ', Color.GRAY));
78
+ };
79
+
80
+ export const getChar = (charCode: number): string => {
81
+ const char = String.fromCodePoint(charCode);
82
+ if (char === '\n') {
83
+ return '\\n';
84
+ }
85
+ return char;
86
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/rule-ref.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphNode } from './graph-node.js';
2
+ import { RuleType } from './rule-type.js';
3
+
4
+ export class RuleRef {
5
+ readonly type = RuleType.REF;
6
+ value: number;
7
+ #nodes: Set<GraphNode> | undefined = undefined;
8
+
9
+ constructor(value: number) {
10
+ this.value = value;
11
+ }
12
+
13
+ get nodes(): Set<GraphNode> {
14
+ if (this.#nodes === undefined) {
15
+ throw new Error('Nodes are not set');
16
+ }
17
+ return this.#nodes;
18
+ }
19
+
20
+ set nodes(nodes: Set<GraphNode>) {
21
+ this.#nodes = nodes;
22
+ }
23
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/rule-type.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export enum RuleType {
2
+ CHAR = 'char',
3
+ CHAR_EXCLUDE = 'char_exclude',
4
+ REF = 'ref',
5
+ END = 'end',
6
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-graph/type-guards.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type {
2
+ Range,
3
+ RuleChar,
4
+ RuleCharExclude,
5
+ RuleEnd,
6
+ UnresolvedRule,
7
+ } from './grammar-graph-types.js';
8
+ import type { GraphPointer } from './graph-pointer.js';
9
+ import type { RuleRef } from './rule-ref.js';
10
+ import { RuleType } from './rule-type.js';
11
+
12
+ export const isRule = (rule: unknown): rule is UnresolvedRule =>
13
+ typeof rule === 'object' &&
14
+ rule !== null &&
15
+ 'type' in rule &&
16
+ [
17
+ RuleType.CHAR,
18
+ RuleType.CHAR_EXCLUDE,
19
+ RuleType.END,
20
+ RuleType.REF,
21
+ ].includes((rule as UnresolvedRule).type);
22
+
23
+ export const isRuleRef = (rule?: UnresolvedRule): rule is RuleRef =>
24
+ rule?.type === RuleType.REF;
25
+
26
+ export const isRuleEnd = (rule?: UnresolvedRule): rule is RuleEnd =>
27
+ rule?.type === RuleType.END;
28
+
29
+ export const isRuleChar = (rule?: UnresolvedRule): rule is RuleChar =>
30
+ rule?.type === RuleType.CHAR;
31
+
32
+ export const isRuleCharExclude = (
33
+ rule?: UnresolvedRule,
34
+ ): rule is RuleCharExclude => rule?.type === RuleType.CHAR_EXCLUDE;
35
+
36
+ export const isRange = (input: unknown): input is Range =>
37
+ Array.isArray(input) &&
38
+ input.length === 2 &&
39
+ input.every((n) => Number.isInteger(n));
40
+
41
+ export const isGraphPointerRuleRef = (
42
+ pointer: GraphPointer,
43
+ ): pointer is GraphPointer<RuleRef> => isRuleRef(pointer.rule);
44
+
45
+ export const isGraphPointerRuleEnd = (
46
+ pointer: GraphPointer,
47
+ ): pointer is GraphPointer<RuleEnd> => isRuleEnd(pointer.rule);
48
+
49
+ export const isGraphPointerRuleChar = (
50
+ pointer: GraphPointer,
51
+ ): pointer is GraphPointer<RuleChar> => isRuleChar(pointer.rule);
52
+
53
+ export const isGraphPointerRuleCharExclude = (
54
+ pointer: GraphPointer,
55
+ ): pointer is GraphPointer<RuleCharExclude> => isRuleCharExclude(pointer.rule);
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/grammar-parser/build-rule-stack.ts ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type {
2
+ Range,
3
+ RuleChar,
4
+ RuleCharExclude,
5
+ UnresolvedRule,
6
+ } from '../grammar-graph/grammar-graph-types.js';
7
+ import {
8
+ ruleChar,
9
+ ruleCharExclude,
10
+ ruleEnd,
11
+ } from '../grammar-graph/grammar-graph-types.js';
12
+ import { RuleRef } from '../grammar-graph/rule-ref.js';
13
+ import { isRange, isRuleEnd } from '../grammar-graph/type-guards.js';
14
+ import {
15
+ isRuleDefAlt,
16
+ isRuleDefChar,
17
+ isRuleDefCharAlt,
18
+ isRuleDefCharNot,
19
+ isRuleDefCharRngUpper,
20
+ isRuleDefEnd,
21
+ isRuleDefRef,
22
+ type InternalRuleDef,
23
+ type InternalRuleDefChar,
24
+ type InternalRuleDefCharNot,
25
+ } from '../rules-builder/rules-builder-types.js';
26
+
27
+ export const makeCharRule = (
28
+ ruleDef: InternalRuleDefChar | InternalRuleDefCharNot,
29
+ ): RuleChar | RuleCharExclude => {
30
+ const value = ruleDef.value as (number | Range)[];
31
+ if (isRuleDefCharNot(ruleDef)) {
32
+ return ruleCharExclude(value);
33
+ }
34
+ if (isRuleDefChar(ruleDef)) {
35
+ return ruleChar(value);
36
+ }
37
+
38
+ throw new Error(
39
+ `Unsupported rule type for make_char_rule: ${JSON.stringify(ruleDef)}`,
40
+ );
41
+ };
42
+
43
+ export const buildRuleStack = (
44
+ linearRules: InternalRuleDef[],
45
+ ): UnresolvedRule[][] => {
46
+ let paths: UnresolvedRule[] = [];
47
+ const stack: UnresolvedRule[][] = [];
48
+ let idx = 0;
49
+
50
+ while (idx < linearRules.length) {
51
+ const ruleDef = linearRules[idx];
52
+ if (isRuleDefChar(ruleDef) || isRuleDefCharNot(ruleDef)) {
53
+ // this could be a single char, or a range, or a sequence of alts; we don't know until we step through it.
54
+ const charRule = makeCharRule(ruleDef);
55
+ idx += 1;
56
+ let rule: InternalRuleDef | undefined = linearRules[idx];
57
+ while (
58
+ idx < linearRules.length &&
59
+ (isRuleDefCharRngUpper(rule) || isRuleDefCharAlt(rule))
60
+ ) {
61
+ if (isRuleDefCharRngUpper(rule)) {
62
+ // previous rule value should be a number
63
+ const prevValue = charRule.value.pop();
64
+ if (isRange(prevValue)) {
65
+ throw new Error(
66
+ `Unexpected range, expected a number but got an array: ${JSON.stringify(prevValue)}`,
67
+ );
68
+ }
69
+ if (prevValue === undefined) {
70
+ throw new Error('Unexpected undefined value');
71
+ }
72
+
73
+ charRule.value.push([prevValue, rule.value]);
74
+ }
75
+ if (isRuleDefCharAlt(rule)) {
76
+ charRule.value.push(rule.value);
77
+ }
78
+ idx += 1;
79
+ rule = linearRules[idx];
80
+ }
81
+ paths.push(charRule);
82
+ } else {
83
+ if (isRuleDefAlt(ruleDef)) {
84
+ if (paths.length === 0) {
85
+ throw new Error('Encountered alt without anything before it');
86
+ }
87
+ paths.push(ruleEnd());
88
+ stack.push(paths);
89
+ paths = [];
90
+ } else if (isRuleDefEnd(ruleDef)) {
91
+ paths.push(ruleEnd());
92
+ } else if (isRuleDefRef(ruleDef)) {
93
+ paths.push(new RuleRef(ruleDef.value));
94
+ } else if (isRuleDefCharAlt(ruleDef)) {
95
+ throw new Error(
96
+ `Encountered char alt, should be handled by above block: ${JSON.stringify(ruleDef)}`,
97
+ );
98
+ } else {
99
+ throw new Error(`Unsupported rule type: ${JSON.stringify(ruleDef)}`);
100
+ }
101
+ idx += 1;
102
+ }
103
+ }
104
+
105
+ if (!isRuleEnd(paths[paths.length - 1])) {
106
+ paths.push(ruleEnd());
107
+ }
108
+
109
+ stack.push(paths);
110
+ return stack;
111
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/index.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GBNF } from './GBNF.js';
2
+
3
+ export default GBNF;
4
+ export { GBNF };
5
+
6
+ export { GrammarParseError, InputParseError } from './utils/errors/index.js';
7
+ export { RuleType } from './grammar-graph/rule-type.js';
8
+ export { RuleRef } from './grammar-graph/rule-ref.js';
9
+ export { ParseState } from './grammar-graph/parse-state.js';
10
+ export { Graph } from './grammar-graph/graph.js';
11
+ export { GraphNode } from './grammar-graph/graph-node.js';
12
+ export { GraphPointer } from './grammar-graph/graph-pointer.js';
13
+ export { Pointers } from './grammar-graph/pointers.js';
14
+ export { RulesBuilder } from './rules-builder/rules-builder.js';
15
+ export { buildRuleStack } from './grammar-parser/build-rule-stack.js';
16
+ export type {
17
+ Range,
18
+ ResolvedRule,
19
+ RuleChar,
20
+ RuleCharExclude,
21
+ RuleEnd,
22
+ UnresolvedRule,
23
+ ValidInput,
24
+ } from './grammar-graph/grammar-graph-types.js';
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/is-word-char.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ export const isWordChar = (c: string): boolean => /[a-zA-Z]/.test(c);
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/parse-char.ts ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GrammarParseError } from '../utils/errors/index.js';
2
+
3
+ const ESCAPE_SEQUENCES: Record<string, number> = {
4
+ t: 9,
5
+ r: 13,
6
+ n: 10,
7
+ };
8
+
9
+ const LITERAL_ESCAPES = ['"', '[', ']', '\\'];
10
+
11
+ export const parseChar = (src: string, pos: number): [number, number] => {
12
+ if (pos >= src.length) {
13
+ throw new GrammarParseError(
14
+ src,
15
+ pos,
16
+ 'Unexpected end of grammar input, failed to complete parse',
17
+ );
18
+ }
19
+
20
+ if (src[pos] === '\\') {
21
+ const next = src[pos + 1];
22
+ if (next === 'x') {
23
+ return [parseInt(src.slice(pos + 2, pos + 4), 16), 4];
24
+ }
25
+ if (next === 'u') {
26
+ return [parseInt(src.slice(pos + 2, pos + 6), 16), 6];
27
+ }
28
+ if (next === 'U') {
29
+ return [parseInt(src.slice(pos + 2, pos + 10), 16), 10];
30
+ }
31
+ if (next in ESCAPE_SEQUENCES) {
32
+ return [ESCAPE_SEQUENCES[next], 2];
33
+ }
34
+ if (LITERAL_ESCAPES.includes(next)) {
35
+ return [next.charCodeAt(0), 2];
36
+ }
37
+ throw new GrammarParseError(src, pos, `Unknown escape at ${src[pos]}`);
38
+ }
39
+
40
+ const codePoint = src.codePointAt(pos);
41
+ if (codePoint === undefined) {
42
+ throw new GrammarParseError(src, pos, `Unknown character at ${pos}`);
43
+ }
44
+ return [codePoint, 1];
45
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/parse-name.ts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GrammarParseError } from '../utils/errors/index.js';
2
+ import { isWordChar } from './is-word-char.js';
3
+
4
+ export const PARSE_NAME_ERROR = 'Failed to find a valid name';
5
+
6
+ export const VALID_NAME_SEPARATORS = ['-', '_'];
7
+
8
+ export const parseName = (grammar: string, pos: number): string => {
9
+ let name = '';
10
+ while (
11
+ pos < grammar.length &&
12
+ (isWordChar(grammar[pos]) || VALID_NAME_SEPARATORS.includes(grammar[pos]))
13
+ ) {
14
+ name += grammar[pos];
15
+ pos += 1;
16
+ }
17
+ if (!name) {
18
+ throw new GrammarParseError(grammar, pos, PARSE_NAME_ERROR);
19
+ }
20
+ return name;
21
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/parse-space.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const parseSpace = (
2
+ src: string,
3
+ pos: number,
4
+ newlineOk: boolean,
5
+ ): number => {
6
+ while (
7
+ pos < src.length &&
8
+ (src[pos] === ' ' ||
9
+ src[pos] === '\t' ||
10
+ src[pos] === '#' ||
11
+ (newlineOk && (src[pos] === '\r' || src[pos] === '\n')))
12
+ ) {
13
+ if (src[pos] === '#') {
14
+ while (pos < src.length && src[pos] !== '\r' && src[pos] !== '\n') {
15
+ pos += 1;
16
+ }
17
+ } else {
18
+ pos += 1;
19
+ }
20
+ }
21
+ return pos;
22
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/rules-builder-types.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export enum InternalRuleType {
2
+ CHAR = 'char',
3
+ CHAR_RNG_UPPER = 'char_rng_upper',
4
+ CHAR_ALT = 'char_alt',
5
+ CHAR_NOT = 'char_not',
6
+ REF = 'ref',
7
+ ALT = 'alt',
8
+ END = 'end',
9
+ }
10
+
11
+ export interface InternalRuleDefChar {
12
+ type: InternalRuleType.CHAR;
13
+ value: number[];
14
+ }
15
+
16
+ export interface InternalRuleDefCharNot {
17
+ type: InternalRuleType.CHAR_NOT;
18
+ value: number[];
19
+ }
20
+
21
+ export interface InternalRuleDefCharAlt {
22
+ type: InternalRuleType.CHAR_ALT;
23
+ value: number;
24
+ }
25
+
26
+ export interface InternalRuleDefCharRngUpper {
27
+ type: InternalRuleType.CHAR_RNG_UPPER;
28
+ value: number;
29
+ }
30
+
31
+ export interface InternalRuleDefReference {
32
+ type: InternalRuleType.REF;
33
+ value: number;
34
+ }
35
+
36
+ export interface InternalRuleDefAlt {
37
+ type: InternalRuleType.ALT;
38
+ }
39
+
40
+ export interface InternalRuleDefEnd {
41
+ type: InternalRuleType.END;
42
+ }
43
+
44
+ export type InternalRuleDef =
45
+ | InternalRuleDefChar
46
+ | InternalRuleDefCharNot
47
+ | InternalRuleDefCharAlt
48
+ | InternalRuleDefCharRngUpper
49
+ | InternalRuleDefReference
50
+ | InternalRuleDefAlt
51
+ | InternalRuleDefEnd;
52
+
53
+ export type InternalRuleDefCharOrAltChar =
54
+ | InternalRuleDefChar
55
+ | InternalRuleDefCharAlt;
56
+
57
+ export const internalRuleDefChar = (value: number[]): InternalRuleDefChar => ({
58
+ type: InternalRuleType.CHAR,
59
+ value: [...value],
60
+ });
61
+
62
+ export const internalRuleDefCharNot = (
63
+ value: number[],
64
+ ): InternalRuleDefCharNot => ({
65
+ type: InternalRuleType.CHAR_NOT,
66
+ value: [...value],
67
+ });
68
+
69
+ export const internalRuleDefCharAlt = (
70
+ value: number,
71
+ ): InternalRuleDefCharAlt => ({ type: InternalRuleType.CHAR_ALT, value });
72
+
73
+ export const internalRuleDefCharRngUpper = (
74
+ value: number,
75
+ ): InternalRuleDefCharRngUpper => ({
76
+ type: InternalRuleType.CHAR_RNG_UPPER,
77
+ value,
78
+ });
79
+
80
+ export const internalRuleDefReference = (
81
+ value: number,
82
+ ): InternalRuleDefReference => ({ type: InternalRuleType.REF, value });
83
+
84
+ export const internalRuleDefAlt = (): InternalRuleDefAlt => ({
85
+ type: InternalRuleType.ALT,
86
+ });
87
+
88
+ export const internalRuleDefEnd = (): InternalRuleDefEnd => ({
89
+ type: InternalRuleType.END,
90
+ });
91
+
92
+ export const isRuleDefAlt = (
93
+ rule?: InternalRuleDef,
94
+ ): rule is InternalRuleDefAlt => rule?.type === InternalRuleType.ALT;
95
+
96
+ export const isRuleDefRef = (
97
+ rule?: InternalRuleDef,
98
+ ): rule is InternalRuleDefReference => rule?.type === InternalRuleType.REF;
99
+
100
+ export const isRuleDefEnd = (
101
+ rule?: InternalRuleDef,
102
+ ): rule is InternalRuleDefEnd => rule?.type === InternalRuleType.END;
103
+
104
+ export const isRuleDefChar = (
105
+ rule?: InternalRuleDef,
106
+ ): rule is InternalRuleDefChar => rule?.type === InternalRuleType.CHAR;
107
+
108
+ export const isRuleDefCharNot = (
109
+ rule?: InternalRuleDef,
110
+ ): rule is InternalRuleDefCharNot => rule?.type === InternalRuleType.CHAR_NOT;
111
+
112
+ export const isRuleDefCharAlt = (
113
+ rule?: InternalRuleDef,
114
+ ): rule is InternalRuleDefCharAlt => rule?.type === InternalRuleType.CHAR_ALT;
115
+
116
+ export const isRuleDefCharRngUpper = (
117
+ rule?: InternalRuleDef,
118
+ ): rule is InternalRuleDefCharRngUpper =>
119
+ rule?.type === InternalRuleType.CHAR_RNG_UPPER;
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/rules-builder.ts ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GrammarParseError } from '../utils/errors/index.js';
2
+ import { isWordChar } from './is-word-char.js';
3
+ import { parseChar } from './parse-char.js';
4
+ import { parseName } from './parse-name.js';
5
+ import { parseSpace } from './parse-space.js';
6
+ import {
7
+ InternalRuleType,
8
+ internalRuleDefAlt,
9
+ internalRuleDefChar,
10
+ internalRuleDefCharAlt,
11
+ internalRuleDefCharNot,
12
+ internalRuleDefCharRngUpper,
13
+ internalRuleDefEnd,
14
+ internalRuleDefReference,
15
+ isRuleDefRef,
16
+ type InternalRuleDef,
17
+ } from './rules-builder-types.js';
18
+ import { SymbolIds } from './symbol-ids.js';
19
+
20
+ export const getOutElements = (
21
+ typeOfRule: InternalRuleType,
22
+ startcharValue: number,
23
+ ): InternalRuleDef => {
24
+ switch (typeOfRule) {
25
+ case InternalRuleType.CHAR:
26
+ return internalRuleDefChar([startcharValue]);
27
+ case InternalRuleType.CHAR_NOT:
28
+ return internalRuleDefCharNot([startcharValue]);
29
+ case InternalRuleType.CHAR_RNG_UPPER:
30
+ return internalRuleDefCharRngUpper(startcharValue);
31
+ case InternalRuleType.ALT:
32
+ return internalRuleDefAlt();
33
+ case InternalRuleType.END:
34
+ return internalRuleDefEnd();
35
+ case InternalRuleType.CHAR_ALT:
36
+ return internalRuleDefCharAlt(startcharValue);
37
+ default:
38
+ throw new Error(`Invalid type: ${typeOfRule}`);
39
+ }
40
+ };
41
+
42
+ export class RulesBuilder {
43
+ pos = 0;
44
+ symbolIds = new SymbolIds();
45
+ rules: InternalRuleDef[][] = [];
46
+ src: string;
47
+ start: number;
48
+ timeLimit: number;
49
+
50
+ constructor(src: string, limit = 1000) {
51
+ this.src = src;
52
+ this.start = performance.now() / 1000;
53
+ this.timeLimit = limit;
54
+ this.parse(src);
55
+ }
56
+
57
+ parse(src: string): void {
58
+ this.pos = parseSpace(src, 0, true);
59
+ while (this.pos < src.length) {
60
+ this.parseRule(src);
61
+ }
62
+
63
+ // Validate the state to ensure that all rules are defined
64
+ for (const rule of this.rules) {
65
+ for (const elem of rule) {
66
+ if (isRuleDefRef(elem)) {
67
+ const ruleExists =
68
+ elem.value < this.rules.length && this.rules[elem.value].length > 0;
69
+ if (!ruleExists) {
70
+ const missingRuleName = this.symbolIds.reverseGet(elem.value);
71
+ let missingRulePos = this.symbolIds.getPos(missingRuleName);
72
+
73
+ // Skip over the ::= and any whitespace
74
+ while (
75
+ missingRulePos < src.length &&
76
+ (src[missingRulePos] === ':' ||
77
+ src[missingRulePos] === '=' ||
78
+ /\s/.test(src[missingRulePos]))
79
+ ) {
80
+ missingRulePos += 1;
81
+ }
82
+
83
+ throw new GrammarParseError(
84
+ src,
85
+ missingRulePos,
86
+ `Undefined rule identifier "${missingRuleName}"`,
87
+ );
88
+ }
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ parseRule(src: string): void {
95
+ const name = parseName(src, this.pos);
96
+ this.pos = parseSpace(src, this.pos + name.length, false);
97
+ const ruleId = this.getSymbolId(name, name.length);
98
+
99
+ this.pos = parseSpace(src, this.pos, true);
100
+ if (
101
+ !(
102
+ this.pos + 2 < src.length && // Ensure the position + 2 is within bounds
103
+ src[this.pos] === ':' &&
104
+ src[this.pos + 1] === ':' &&
105
+ src[this.pos + 2] === '='
106
+ )
107
+ ) {
108
+ throw new GrammarParseError(src, this.pos, `Expecting ::= at ${this.pos}`);
109
+ }
110
+ this.pos += 3;
111
+ this.pos = parseSpace(src, this.pos, true);
112
+
113
+ this.parseAlternates(name, ruleId);
114
+
115
+ // Check if this.pos is within the bounds of src before checking for a carriage return
116
+ if (this.pos < src.length && src[this.pos] === '\r') {
117
+ this.pos += src[this.pos + 1] === '\n' ? 2 : 1;
118
+ } else if (this.pos < src.length && src[this.pos] === '\n') {
119
+ this.pos += 1;
120
+ } else if (this.pos < src.length && src[this.pos]) {
121
+ throw new GrammarParseError(
122
+ src,
123
+ this.pos,
124
+ `Expecting newline or end at ${this.pos}`,
125
+ );
126
+ }
127
+ this.pos = parseSpace(src, this.pos, true);
128
+ }
129
+
130
+ getSymbolId(src: string, length: number): number {
131
+ const nextId = this.symbolIds.size;
132
+ const key = src.slice(0, length);
133
+ if (!this.symbolIds.has(key)) {
134
+ this.symbolIds.set(key, nextId, this.pos);
135
+ }
136
+ return this.symbolIds.get(key) as number;
137
+ }
138
+
139
+ generateSymbolId(baseName: string): number {
140
+ const nextId = this.symbolIds.size;
141
+ this.symbolIds.set(`${baseName}_${nextId}`, nextId, this.pos);
142
+ return nextId;
143
+ }
144
+
145
+ addRule(ruleId: number, rule: InternalRuleDef[]): void {
146
+ while (this.rules.length <= ruleId) {
147
+ this.rules.push([]);
148
+ }
149
+ this.rules[ruleId] = rule;
150
+ }
151
+
152
+ checkDuration(): void {
153
+ if (performance.now() / 1000 - this.start > this.timeLimit) {
154
+ throw new GrammarParseError(
155
+ this.src,
156
+ this.pos,
157
+ `Duration of ${this.timeLimit} exceeded`,
158
+ );
159
+ }
160
+ }
161
+
162
+ parseSequence(
163
+ ruleName: string,
164
+ outElements: InternalRuleDef[],
165
+ depth = 0,
166
+ ): void {
167
+ const isNested = depth !== 0;
168
+ const src = this.src;
169
+ let lastSymStart = outElements.length;
170
+
171
+ while (this.pos < src.length) {
172
+ if (src[this.pos] === '"') {
173
+ this.pos += 1;
174
+ lastSymStart = outElements.length;
175
+ while (src[this.pos] !== '"') {
176
+ this.checkDuration();
177
+ const [value, incPos] = parseChar(src, this.pos);
178
+ outElements.push(internalRuleDefChar([value]));
179
+ this.pos += incPos;
180
+ }
181
+ this.pos = parseSpace(src, this.pos + 1, isNested);
182
+ } else if (src[this.pos] === '[') {
183
+ this.pos += 1;
184
+ let startType = InternalRuleType.CHAR;
185
+ if (src[this.pos] === '^') {
186
+ this.pos += 1;
187
+ startType = InternalRuleType.CHAR_NOT;
188
+ }
189
+ lastSymStart = outElements.length;
190
+ while (src[this.pos] !== ']') {
191
+ this.checkDuration();
192
+ const type =
193
+ lastSymStart < outElements.length
194
+ ? InternalRuleType.CHAR_ALT
195
+ : startType;
196
+ const [startcharValue, incPos] = parseChar(src, this.pos);
197
+ this.pos += incPos;
198
+ outElements.push(getOutElements(type, startcharValue));
199
+
200
+ if (src[this.pos] === '-' && src[this.pos + 1] !== ']') {
201
+ this.pos += 1;
202
+ const [endcharValue, endIncPos] = parseChar(src, this.pos);
203
+ outElements.push(internalRuleDefCharRngUpper(endcharValue));
204
+ this.pos += endIncPos;
205
+ }
206
+ }
207
+ this.pos = parseSpace(src, this.pos + 1, isNested);
208
+ } else if (isWordChar(src[this.pos])) {
209
+ const name = parseName(src, this.pos);
210
+ const refRuleId = this.getSymbolId(name, name.length);
211
+ this.pos += name.length;
212
+ this.pos = parseSpace(src, this.pos, isNested);
213
+
214
+ lastSymStart = outElements.length;
215
+ outElements.push(internalRuleDefReference(refRuleId));
216
+ } else if (src[this.pos] === '(') {
217
+ this.pos = parseSpace(src, this.pos + 1, true);
218
+ const subRuleId = this.generateSymbolId(ruleName);
219
+ this.parseAlternates(ruleName, subRuleId, depth + 1);
220
+ lastSymStart = outElements.length;
221
+ outElements.push(internalRuleDefReference(subRuleId));
222
+ if (src[this.pos] !== ')') {
223
+ throw new GrammarParseError(
224
+ src,
225
+ this.pos,
226
+ `Expecting ')' at ${this.pos}`,
227
+ );
228
+ }
229
+ this.pos = parseSpace(src, this.pos + 1, isNested);
230
+ } else if ('*+?'.includes(src[this.pos])) {
231
+ if (lastSymStart === outElements.length) {
232
+ throw new GrammarParseError(
233
+ src,
234
+ this.pos,
235
+ `Expecting preceding item to */+/? at ${this.pos}`,
236
+ );
237
+ }
238
+ const subRuleId = this.generateSymbolId(ruleName);
239
+ const subRule = outElements.slice(lastSymStart);
240
+ if ('*+'.includes(src[this.pos])) {
241
+ subRule.push(internalRuleDefReference(subRuleId));
242
+ }
243
+ subRule.push(internalRuleDefAlt());
244
+ if (src[this.pos] === '+') {
245
+ subRule.push(...outElements.slice(lastSymStart));
246
+ }
247
+ subRule.push(internalRuleDefEnd());
248
+ this.addRule(subRuleId, subRule);
249
+ outElements.splice(
250
+ lastSymStart,
251
+ outElements.length - lastSymStart,
252
+ internalRuleDefReference(subRuleId),
253
+ );
254
+ this.pos = parseSpace(src, this.pos + 1, isNested);
255
+ } else {
256
+ break;
257
+ }
258
+ }
259
+ }
260
+
261
+ parseAlternates(ruleName: string, ruleId: number, depth = 0): void {
262
+ const src = this.src;
263
+ const rule: InternalRuleDef[] = [];
264
+ this.parseSequence(ruleName, rule, depth);
265
+ // Ensure that this.pos is within bounds before checking src[this.pos]
266
+ while (this.pos < src.length && src[this.pos] === '|') {
267
+ this.checkDuration();
268
+ rule.push(internalRuleDefAlt());
269
+ this.pos = parseSpace(src, this.pos + 1, true);
270
+ this.parseSequence(ruleName, rule, depth);
271
+ }
272
+ rule.push(internalRuleDefEnd());
273
+ this.addRule(ruleId, rule);
274
+ }
275
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/rules-builder/symbol-ids.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export class SymbolIds {
2
+ #map = new Map<string, number>();
3
+ #pos = new Map<string, number>();
4
+ #reverseMap = new Map<number, string>();
5
+
6
+ *[Symbol.iterator](): IterableIterator<[string, number]> {
7
+ yield* this.#map;
8
+ }
9
+
10
+ entries(): IterableIterator<[string, number]> {
11
+ return this.#map.entries();
12
+ }
13
+
14
+ get size(): number {
15
+ return this.#map.size;
16
+ }
17
+
18
+ get(key: string): number | undefined {
19
+ return this.#map.get(key);
20
+ }
21
+
22
+ set(key: string, value: number, pos: number): void {
23
+ this.#map.set(key, value);
24
+ this.#reverseMap.set(value, key);
25
+ this.#pos.set(key, pos);
26
+ }
27
+
28
+ has(key: string): boolean {
29
+ return this.#map.has(key);
30
+ }
31
+
32
+ reverseGet(key: number): string {
33
+ const val = this.#reverseMap.get(key);
34
+ if (val === undefined) {
35
+ throw new Error(`SymbolIds does not contain value: ${key}`);
36
+ }
37
+ return val;
38
+ }
39
+
40
+ getPos(key: string): number {
41
+ const val = this.#pos.get(key);
42
+ if (val === undefined) {
43
+ throw new Error(`SymbolIds does not contain key: ${key}`);
44
+ }
45
+ return val;
46
+ }
47
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/build-error-position.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getLengthInCodePoints } from './get-input-as-string.js';
2
+
3
+ export const MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW = 3;
4
+
5
+ export const buildErrorPosition = (src: string, pos: number): string[] => {
6
+ if (src === '') {
7
+ return ['No input provided'];
8
+ }
9
+ const lines = src.split('\n');
10
+ const srcLength = getLengthInCodePoints(src);
11
+
12
+ let lineIdx = 0;
13
+ while (
14
+ lines[lineIdx] &&
15
+ pos > getLengthInCodePoints(lines[lineIdx]) - 1 &&
16
+ pos < srcLength
17
+ ) {
18
+ pos -= getLengthInCodePoints(lines[lineIdx]);
19
+ lineIdx += 1;
20
+ }
21
+
22
+ const linesToShow = lines.slice(
23
+ Math.max(0, lineIdx - (MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW - 1)),
24
+ lineIdx + 1,
25
+ );
26
+
27
+ return [...linesToShow, `${' '.repeat(Math.max(0, pos))}^`];
28
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/errors-types.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ export type ValidInput = string | number | number[];
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/get-input-as-string.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ValidInput } from './errors-types.js';
2
+
3
+ export const getInputAsString = (src: ValidInput): string => {
4
+ if (typeof src === 'string') {
5
+ return src;
6
+ }
7
+ if (typeof src === 'number') {
8
+ return String.fromCodePoint(src);
9
+ }
10
+ return src.map((codePoint) => String.fromCodePoint(codePoint)).join('');
11
+ };
12
+
13
+ // Lengths and positions are counted in code points, matching how the parser
14
+ // walks its input.
15
+ export const getLengthInCodePoints = (src: string): number =>
16
+ Array.from(src).length;
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/grammar-parse-error.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { buildErrorPosition } from './build-error-position.js';
2
+
3
+ export const GRAMMAR_PARSER_ERROR_HEADER_MESSAGE = (reason: string): string =>
4
+ `Failed to parse grammar: ${reason}`;
5
+
6
+ const buildMessage = (grammar: string, pos: number, reason: string): string =>
7
+ [
8
+ GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason),
9
+ '',
10
+ ...buildErrorPosition(grammar, pos),
11
+ ].join('\n');
12
+
13
+ export class GrammarParseError extends Error {
14
+ grammar: string;
15
+ pos: number;
16
+ reason: string;
17
+
18
+ constructor(grammar: string, pos: number, reason: string) {
19
+ super(buildMessage(grammar, pos, reason));
20
+ Object.setPrototypeOf(this, GrammarParseError.prototype);
21
+ this.name = 'GrammarParseError';
22
+ this.grammar = grammar;
23
+ this.pos = pos;
24
+ this.reason = reason;
25
+ }
26
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/index.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export { GrammarParseError } from './grammar-parse-error.js';
2
+ export { InputParseError } from './input-parse-error.js';
3
+ export type { ValidInput } from './errors-types.js';
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/errors/input-parse-error.ts ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { buildErrorPosition } from './build-error-position.js';
2
+ import type { ValidInput } from './errors-types.js';
3
+ import {
4
+ getInputAsString,
5
+ getLengthInCodePoints,
6
+ } from './get-input-as-string.js';
7
+
8
+ export const INPUT_PARSER_ERROR_HEADER_MESSAGE =
9
+ 'Failed to parse input string:';
10
+
11
+ const buildMessage = (
12
+ mostRecentInput: ValidInput,
13
+ pos: number,
14
+ previousInput: ValidInput,
15
+ ): string => {
16
+ const previous = getInputAsString(previousInput);
17
+ return [
18
+ INPUT_PARSER_ERROR_HEADER_MESSAGE,
19
+ '',
20
+ ...buildErrorPosition(
21
+ `${previous}${getInputAsString(mostRecentInput)}`,
22
+ pos + getLengthInCodePoints(previous),
23
+ ),
24
+ ].join('\n');
25
+ };
26
+
27
+ export class InputParseError extends Error {
28
+ mostRecentInput: ValidInput;
29
+ pos: number;
30
+ previousInput: ValidInput;
31
+
32
+ constructor(
33
+ mostRecentInput: ValidInput,
34
+ pos: number,
35
+ previousInput: ValidInput = '',
36
+ ) {
37
+ super(buildMessage(mostRecentInput, pos, previousInput));
38
+ Object.setPrototypeOf(this, InputParseError.prototype);
39
+ this.name = 'InputParseError';
40
+ this.mostRecentInput = mostRecentInput;
41
+ this.pos = pos;
42
+ this.previousInput = previousInput;
43
+ }
44
+
45
+ get src(): string {
46
+ return `${getInputAsString(this.previousInput)}${getInputAsString(this.mostRecentInput)}`;
47
+ }
48
+
49
+ get errorForMostRecentInput(): string {
50
+ return [
51
+ INPUT_PARSER_ERROR_HEADER_MESSAGE,
52
+ '',
53
+ ...buildErrorPosition(getInputAsString(this.mostRecentInput), this.pos),
54
+ ].join('\n');
55
+ }
56
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/is-point-in-range.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import type { Range } from '../grammar-graph/grammar-graph-types.js';
2
+
3
+ export const isPointInRange = (point: number, givenRange: Range): boolean => {
4
+ if (!Number.isInteger(point)) {
5
+ throw new Error('point must be an integer');
6
+ }
7
+ return point >= givenRange[0] && point <= givenRange[1];
8
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/src/utils/validate-non-empty.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export const validateNonEmpty = <T>(value: T[]): T[] => {
2
+ if (!value.length) {
3
+ throw new Error('Value cannot be empty.');
4
+ }
5
+ return value;
6
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated JavaScript test suite
2
+
3
+ Copy the suite and its config into the ported implementation, then run it:
4
+
5
+ ```sh
6
+ cd /workspace/ported_implementation
7
+ cp -r /workspace/tests/javascript tests
8
+ cp tests/vitest.config.unit.ts .
9
+ npx vitest run --config vitest.config.unit.ts
10
+ ```
11
+
12
+ The config aliases `gbnf` to `/workspace/ported_implementation/src/index.ts`. Repoint it if
13
+ your entry file differs.
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/grammars.test.ts ADDED
The diff for this file is too large to render. See raw diff
 
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/iteration-with-additional-strings.test.ts ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, test, expect } from 'vitest';
2
+ import GBNF, { RuleType, InputParseError } from 'gbnf';
3
+
4
+ describe('Iteration', () => {
5
+ test.for([
6
+ ['root ::= "foo"', 'f', '1'],
7
+ ['root ::= "foo"', 'f', 'b'],
8
+ ['root ::= "foo"', 'f', 'o1'],
9
+ ['root ::= "foo"', 'f', 'ooo'],
10
+ ['root ::= "foo"', 'f', 'ooooooo'],
11
+ ['root ::= "foo" | "bar"', 'f', '1'],
12
+ ['root ::= "foo" | "bar"', 'b', '1'],
13
+ ['root ::= "foo" | "bar"', 'f', 'o1'],
14
+ ['root ::= "foo" | "bar"', 'b', 'a1'],
15
+ ['root ::= "foo" | "bar"', 'f', 'ooo'],
16
+ ['root ::= "foo" | "bar"', 'b', 'arrr'],
17
+ ['root ::= "foo" | "bar" | "baz"', 'f', '1'],
18
+ ['root ::= "foo" | "bar" | "baz"', 'f', 'z'],
19
+ ['root ::= "foo" | "bar" | "baz"', 'b', 'b1'],
20
+ ['root ::= "foo" | "bar" | "baz"', 'f', 'o1'],
21
+ ['root ::= "foo" | "bar" | "baz"', 'b', 'al'],
22
+ ['root ::= "foo" | "bar" | "baz"', 'f', 'ooo'],
23
+ ['root ::= "foo" | "bar" | "baz"', 'b', 'azrr'],
24
+ ['root ::= foo\nfoo ::="foo"', 'f', '1'],
25
+ ['root ::= foo\nfoo ::="foo"', 'f', 'b'],
26
+ ['root ::= foo\nfoo ::="foo"', 'f', 'o1'],
27
+ ['root ::= foo\nfoo ::="foo"', 'f', 'ooo'],
28
+ ['root::=foo|"bar"\nfoo::="foo"', 'f', '1'],
29
+ ['root::=foo|"bar"\nfoo::="foo"', 'f', 'z'],
30
+ ['root::=foo|"bar"\nfoo::="foo"', 'b', 'b1'],
31
+ ['root::=foo|"bar"\nfoo::="foo"', 'f', 'o1'],
32
+ ['root::=foo|"bar"\nfoo::="foo"', 'f', 'ooo'],
33
+ ['root::=foo|"bar"\nfoo::="foo"', 'b', 'arr'],
34
+ ['root::= foo | bar\n foo::="foo"\n bar::="bar"', 'f', '1'],
35
+ ['root::= foo | bar\n foo::="foo"\n bar::="bar"', 'f', 'z'],
36
+ ['root::= foo | bar\n foo::="foo"\n bar::="bar"', 'b', '1'],
37
+ ['root::= foo | bar\n foo::="foo"\n bar::="bar"', 'f', 'o1'],
38
+ ['root::= foo | bar\n foo::="foo"\n bar::="bar"', 'f', 'ooo'],
39
+ ['root::= foo | bar\n foo::="foo"\n bar::="bar"', 'b', 'arr'],
40
+ [
41
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
42
+ 'f',
43
+ '1',
44
+ ],
45
+ [
46
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
47
+ 'f',
48
+ 'z',
49
+ ],
50
+ [
51
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
52
+ 'b',
53
+ '1',
54
+ ],
55
+ [
56
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
57
+ 'f',
58
+ 'o1',
59
+ ],
60
+ [
61
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
62
+ 'f',
63
+ 'ooo',
64
+ ],
65
+ [
66
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
67
+ 'b',
68
+ 'arr',
69
+ ],
70
+ [
71
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
72
+ 'b',
73
+ 'azr',
74
+ ],
75
+ ['root ::= [a-z]', 'a', 'A'],
76
+ ['root ::= [a-z]', 'a', '0'],
77
+ ['root ::= [a-z]', 'a', 'az'],
78
+ ['root ::= [a-z]?', 'a', 'A'],
79
+ ['root ::= [a-z]?', 'a', '0'],
80
+ ['root ::= [a-z]?', 'a', 'az'],
81
+ ['root ::= [a-z]+', 'a', 'A'],
82
+ ['root ::= [a-z]+', 'a', '0'],
83
+ ['root ::= [a-z]+', 'a', 'z0'],
84
+ ['root ::= [a-z]*', 'a', 'A'],
85
+ ['root ::= [a-z]*', 'a', '0'],
86
+ ['root ::= [a-z]*', 'a', 'z0'],
87
+ ] as [string, string, string][])(
88
+ '(%#) It throws if encountering a grammar `%s` with starting `%s` and additional `%s`',
89
+ ([grammar, starting, additional]) => {
90
+ const graph = GBNF(grammar, starting);
91
+ expect(() => {
92
+ graph.add(additional);
93
+ }).toThrow();
94
+ }
95
+ );
96
+
97
+ test.for([
98
+ ['root ::= "foo"', '', 'f', [{ type: 'char', value: [111] }]],
99
+ ['root ::= "foo"', 'f', 'o', [{ type: 'char', value: [111] }]],
100
+ ['root ::= "foo"', 'fo', 'o', [{ type: 'end' }]],
101
+ ['root ::= "foo" | "bar" ', '', 'f', [{ type: 'char', value: [111] }]],
102
+ ['root ::= "foo" | "bar" ', 'f', 'o', [{ type: 'char', value: [111] }]],
103
+ ['root ::= "foo" | "bar" ', 'fo', 'o', [{ type: 'end' }]],
104
+ ['root ::= "foo" | "bar" ', '', 'b', [{ type: 'char', value: [97] }]],
105
+ ['root ::= "foo" | "bar" ', 'b', 'a', [{ type: 'char', value: [114] }]],
106
+ ['root ::= "foo" | "bar" ', 'ba', 'r', [{ type: 'end' }]],
107
+ [
108
+ 'root ::= "foo" | "bar" | "baz"',
109
+ 'b',
110
+ 'a',
111
+ [
112
+ { type: 'char', value: [114] },
113
+ { type: 'char', value: [122] },
114
+ ],
115
+ ],
116
+ ['root ::= [^f] "o"', 'g', 'o', [{ type: 'end' }]],
117
+ ['root ::= [^A-Z]', '', 'a', [{ type: 'end' }]],
118
+ ['root ::= [^A-Z0-9]', '', 'a', [{ type: 'end' }]],
119
+ ['root ::= [^A-Z0-9_-]', '', 'a', [{ type: 'end' }]],
120
+ ['root ::= foo\nfoo ::= "foo"', '', 'f', [{ type: 'char', value: [111] }]],
121
+ ['root ::= foo\nfoo ::= "foo"', 'f', 'o', [{ type: 'char', value: [111] }]],
122
+ ['root ::= foo\nfoo ::= "foo"', 'fo', 'o', [{ type: 'end' }]],
123
+ [
124
+ 'root ::= foo | "bar"\nfoo ::= "foo"',
125
+ '',
126
+ 'f',
127
+ [{ type: 'char', value: [111] }],
128
+ ],
129
+ [
130
+ 'root ::= foo | "bar"\nfoo ::= "foo"',
131
+ 'f',
132
+ 'o',
133
+ [{ type: 'char', value: [111] }],
134
+ ],
135
+ ['root ::= foo | "bar"\nfoo ::= "foo"', 'fo', 'o', [{ type: 'end' }]],
136
+ [
137
+ 'root ::= foo | "bar"\nfoo ::= "foo"',
138
+ '',
139
+ 'b',
140
+ [{ type: 'char', value: [97] }],
141
+ ],
142
+ [
143
+ 'root ::= foo | "bar"\nfoo ::= "foo"',
144
+ 'b',
145
+ 'a',
146
+ [{ type: 'char', value: [114] }],
147
+ ],
148
+ ['root ::= foo | "bar"\nfoo ::= "foo"', 'ba', 'r', [{ type: 'end' }]],
149
+ [
150
+ 'root ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
151
+ '',
152
+ 'f',
153
+ [{ type: 'char', value: [111] }],
154
+ ],
155
+ [
156
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
157
+ 'f',
158
+ 'o',
159
+ [{ type: 'char', value: [111] }],
160
+ ],
161
+ [
162
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
163
+ 'fo',
164
+ 'o',
165
+ [{ type: 'end' }],
166
+ ],
167
+ [
168
+ 'root ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
169
+ '',
170
+ 'b',
171
+ [{ type: 'char', value: [97] }],
172
+ ],
173
+ [
174
+ 'root ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
175
+ 'b',
176
+ 'a',
177
+ [{ type: 'char', value: [114] }],
178
+ ],
179
+ [
180
+ 'root ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
181
+ 'ba',
182
+ 'r',
183
+ [{ type: 'end' }],
184
+ ],
185
+ [
186
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
187
+ '',
188
+ 'f',
189
+ [{ type: 'char', value: [111] }],
190
+ ],
191
+ [
192
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
193
+ 'f',
194
+ 'o',
195
+ [{ type: 'char', value: [111] }],
196
+ ],
197
+ [
198
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
199
+ 'fo',
200
+ 'o',
201
+ [{ type: 'end' }],
202
+ ],
203
+ [
204
+ 'root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
205
+ '',
206
+ 'b',
207
+ [{ type: 'char', value: [97] }],
208
+ ],
209
+ [
210
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
211
+ 'b',
212
+ 'a',
213
+ [
214
+ { type: 'char', value: [114] },
215
+ { type: 'char', value: [122] },
216
+ ],
217
+ ],
218
+ [
219
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
220
+ 'ba',
221
+ 'r',
222
+ [{ type: 'end' }],
223
+ ],
224
+ [
225
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
226
+ 'ba',
227
+ 'z',
228
+ [{ type: 'end' }],
229
+ ],
230
+ ['root ::= [a-z]', '', 'a', [{ type: 'end' }]],
231
+ ['root ::= [a-z]', '', 'm', [{ type: 'end' }]],
232
+ ['root ::= [a-z]', '', 'z', [{ type: 'end' }]],
233
+ ['root ::= [a-zA-Z]', '', 'a', [{ type: 'end' }]],
234
+ ['root ::= [a-zA-Z]', '', 'Z', [{ type: 'end' }]],
235
+ ['root ::= [a-zA-Z0-9]', '', 'Z', [{ type: 'end' }]],
236
+ ['root ::= [a-zA-Z0-9]', '', '0', [{ type: 'end' }]],
237
+ ['root ::= [a-zA-Z0-9]', '', '9', [{ type: 'end' }]],
238
+ ['root ::= [a-z]?', '', 'a', [{ type: 'end' }]],
239
+ ['root ::= [a-zA-Z]?', '', 'Z', [{ type: 'end' }]],
240
+ ['root ::= [a-zA-Z0-9]?', '', '0', [{ type: 'end' }]],
241
+ [
242
+ 'root ::= [a-z]+',
243
+ '',
244
+ 'a',
245
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
246
+ ],
247
+ [
248
+ 'root ::= [a-zA-Z]+',
249
+ '',
250
+ 'Z',
251
+ [
252
+ {
253
+ type: 'char',
254
+ value: [
255
+ [97, 122],
256
+ [65, 90],
257
+ ],
258
+ },
259
+ { type: 'end' },
260
+ ],
261
+ ],
262
+ [
263
+ 'root ::= [a-zA-Z]+',
264
+ 'azA',
265
+ 'Z',
266
+ [
267
+ {
268
+ type: 'char',
269
+ value: [
270
+ [97, 122],
271
+ [65, 90],
272
+ ],
273
+ },
274
+ { type: 'end' },
275
+ ],
276
+ ],
277
+ [
278
+ 'root ::= [a-z]*',
279
+ '',
280
+ 'a',
281
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
282
+ ],
283
+ [
284
+ 'root ::= [a-zA-Z]+',
285
+ '',
286
+ 'Z',
287
+ [
288
+ {
289
+ type: 'char',
290
+ value: [
291
+ [97, 122],
292
+ [65, 90],
293
+ ],
294
+ },
295
+ { type: 'end' },
296
+ ],
297
+ ],
298
+ [
299
+ 'root ::= [a-zA-Z]+',
300
+ 'acczABC',
301
+ 'Z',
302
+ [
303
+ {
304
+ type: 'char',
305
+ value: [
306
+ [97, 122],
307
+ [65, 90],
308
+ ],
309
+ },
310
+ { type: 'end' },
311
+ ],
312
+ ],
313
+ [
314
+ 'root ::= "foo" | "bar" | "baz" | "bazaar" | "barrington" ',
315
+ 'baza',
316
+ 'a',
317
+ [{ type: 'char', value: [114] }],
318
+ ],
319
+ [
320
+ 'root ::= [^f]+ "o"',
321
+ 'aaa',
322
+ 'a',
323
+ [
324
+ { type: 'char_exclude', value: [102] },
325
+ { type: 'char', value: [111] },
326
+ ],
327
+ ],
328
+ [
329
+ 'root ::= [^A-Z]+',
330
+ 'abc',
331
+ 'd',
332
+ [{ type: 'char_exclude', value: [[65, 90]] }, { type: 'end' }],
333
+ ],
334
+ [
335
+ 'root ::= [^A-Z0-9]*',
336
+ 'abc',
337
+ 'd',
338
+ [
339
+ {
340
+ type: 'char_exclude',
341
+ value: [
342
+ [65, 90],
343
+ [48, 57],
344
+ ],
345
+ },
346
+ { type: 'end' },
347
+ ],
348
+ ],
349
+ [
350
+ 'root ::= [^A-Z0-9_-]*',
351
+ 'abc',
352
+ 'd',
353
+ [
354
+ { type: 'char_exclude', value: [[65, 90], [48, 57], 95, 45] },
355
+ { type: 'end' },
356
+ ],
357
+ ],
358
+ ] as [string, string, string, { type: string; value: number[] }[]][])(
359
+ '(%#) It parses a grammar `%s` with starting `%s` and additional `%s`',
360
+ async ([grammar, starting, additional, expected]) => {
361
+ let state = GBNF(grammar, starting);
362
+ state = state.add(additional);
363
+ expect([...state]).toEqual(expected);
364
+ }
365
+ );
366
+
367
+ test.for([false, true] as boolean[])(
368
+ '(%#) It throws a particular error',
369
+ async (errorForMostRecentInput) => {
370
+ const grammar = 'root ::= "bar"';
371
+ let state = GBNF(grammar);
372
+ state = state.add('b');
373
+ state = state.add('a');
374
+ try {
375
+ state.add('z');
376
+ throw new Error('Expected an error to be thrown');
377
+ } catch (err) {
378
+ if (!(err instanceof InputParseError)) {
379
+ throw new Error(
380
+ 'Expected an error of type InputParseError to be thrown'
381
+ );
382
+ }
383
+ const expectedErr = new InputParseError('z', 0, 'ba');
384
+ if (errorForMostRecentInput) {
385
+ expect(err.errorForMostRecentInput).toEqual(
386
+ expectedErr.errorForMostRecentInput
387
+ );
388
+ } else {
389
+ expect(err.message).toEqual(expectedErr.message);
390
+ }
391
+ }
392
+ }
393
+ );
394
+ });
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/iteration-with-an-initial-string.test.ts ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, test, expect } from 'vitest';
2
+ import GBNF, { RuleType } from 'gbnf';
3
+
4
+ describe('Iteration', () => {
5
+ test.for([
6
+ ['root ::= "foo"', '', [{ type: 'char', value: [102] }]],
7
+ ['root ::= "foo"', 'f', [{ type: 'char', value: [111] }]],
8
+ ['root ::= "foo"', 'fo', [{ type: 'char', value: [111] }]],
9
+ ['root ::= "foo"', 'foo', [{ type: 'end' }]],
10
+ [
11
+ 'root ::= "foo" | "bar" ',
12
+ '',
13
+ [
14
+ { type: 'char', value: [102] },
15
+ { type: 'char', value: [98] },
16
+ ],
17
+ ],
18
+ ['root ::= "foo" | "bar" ', 'f', [{ type: 'char', value: [111] }]],
19
+ ['root ::= "foo" | "bar" ', 'fo', [{ type: 'char', value: [111] }]],
20
+ ['root ::= "foo" | "bar" ', 'foo', [{ type: 'end' }]],
21
+ ['root ::= "foo" | "bar" ', 'b', [{ type: 'char', value: [97] }]],
22
+ ['root ::= "foo" | "bar" ', 'ba', [{ type: 'char', value: [114] }]],
23
+ ['root ::= "foo" | "bar" ', 'bar', [{ type: 'end' }]],
24
+ [
25
+ 'root ::= "foo" | "bar" | "baz"',
26
+ 'ba',
27
+ [
28
+ { type: 'char', value: [114] },
29
+ { type: 'char', value: [122] },
30
+ ],
31
+ ],
32
+ ['root ::= "["', '[', [{ type: 'end' }]],
33
+ ['root ::= "]"', ']', [{ type: 'end' }]],
34
+ ['root ::= "[]"', '[]', [{ type: 'end' }]],
35
+ ['root ::= "{"', '{', [{ type: 'end' }]],
36
+ ['root ::= "}"', '}', [{ type: 'end' }]],
37
+ ['root ::= "{}"', '{}', [{ type: 'end' }]],
38
+ ['root ::= "[{}]"', '[{}]', [{ type: 'end' }]],
39
+ ['root ::= [^f] "o"', '', [{ type: 'char_exclude', value: [102] }]],
40
+ ['root ::= [^f] "o"', 'a', [{ type: 'char', value: [111] }]],
41
+ ['root ::= [^A-Z]', '', [{ type: 'char_exclude', value: [[65, 90]] }]],
42
+ [
43
+ 'root ::= [^A-Z0-9]',
44
+ '',
45
+ [
46
+ {
47
+ type: 'char_exclude',
48
+ value: [
49
+ [65, 90],
50
+ [48, 57],
51
+ ],
52
+ },
53
+ ],
54
+ ],
55
+ [
56
+ 'root ::= [^A-Z0-9_-]',
57
+ '',
58
+ [{ type: 'char_exclude', value: [[65, 90], [48, 57], 95, 45] }],
59
+ ],
60
+ ['\nroot ::= foo\nfoo ::= "foo"', '', [{ type: 'char', value: [102] }]],
61
+ ['root ::= foo\nfoo ::= "foo"\n', 'f', [{ type: 'char', value: [111] }]],
62
+ ['\nroot ::= foo\nfoo ::= "foo"\n', 'fo', [{ type: 'char', value: [111] }]],
63
+ ['root ::= foo\nfoo ::= "foo"', 'foo', [{ type: 'end' }]],
64
+ [
65
+ 'root ::= f\nf ::= foo\nfoo ::= "foo"',
66
+ '',
67
+ [{ type: 'char', value: [102] }],
68
+ ],
69
+ [
70
+ '\nroot ::= foo | "bar"\nfoo ::= "foo"\n',
71
+ '',
72
+ [
73
+ { type: 'char', value: [102] },
74
+ { type: 'char', value: [98] },
75
+ ],
76
+ ],
77
+ [
78
+ '\nroot ::= foo | "bar"\nfoo ::= "foo"',
79
+ 'f',
80
+ [{ type: 'char', value: [111] }],
81
+ ],
82
+ [
83
+ 'root ::= foo | "bar"\nfoo ::= "foo"',
84
+ 'fo',
85
+ [{ type: 'char', value: [111] }],
86
+ ],
87
+ ['root ::= foo | "bar"\nfoo ::= "foo"', 'foo', [{ type: 'end' }]],
88
+ [
89
+ 'root ::= foo | "bar"\nfoo ::= "foo"',
90
+ 'b',
91
+ [{ type: 'char', value: [97] }],
92
+ ],
93
+ [
94
+ 'root ::= foo | "bar"\nfoo ::= "foo"',
95
+ 'ba',
96
+ [{ type: 'char', value: [114] }],
97
+ ],
98
+ ['root ::= foo | "bar"\nfoo ::= "foo"', 'bar', [{ type: 'end' }]],
99
+ [
100
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
101
+ '',
102
+ [
103
+ { type: 'char', value: [102] },
104
+ { type: 'char', value: [98] },
105
+ ],
106
+ ],
107
+ [
108
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
109
+ 'f',
110
+ [{ type: 'char', value: [111] }],
111
+ ],
112
+ [
113
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
114
+ 'fo',
115
+ [{ type: 'char', value: [111] }],
116
+ ],
117
+ [
118
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
119
+ 'foo',
120
+ [{ type: 'end' }],
121
+ ],
122
+ [
123
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
124
+ 'b',
125
+ [{ type: 'char', value: [97] }],
126
+ ],
127
+ [
128
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
129
+ 'ba',
130
+ [{ type: 'char', value: [114] }],
131
+ ],
132
+ [
133
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"',
134
+ 'bar',
135
+ [{ type: 'end' }],
136
+ ],
137
+ [
138
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
139
+ '',
140
+ [
141
+ { type: 'char', value: [102] },
142
+ { type: 'char', value: [98] },
143
+ ],
144
+ ],
145
+ [
146
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
147
+ 'f',
148
+ [{ type: 'char', value: [111] }],
149
+ ],
150
+ [
151
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
152
+ 'fo',
153
+ [{ type: 'char', value: [111] }],
154
+ ],
155
+ [
156
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
157
+ 'foo',
158
+ [{ type: 'end' }],
159
+ ],
160
+ [
161
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
162
+ 'b',
163
+ [{ type: 'char', value: [97] }],
164
+ ],
165
+ [
166
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
167
+ 'ba',
168
+ [
169
+ { type: 'char', value: [114] },
170
+ { type: 'char', value: [122] },
171
+ ],
172
+ ],
173
+ [
174
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
175
+ 'bar',
176
+ [{ type: 'end' }],
177
+ ],
178
+ [
179
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"',
180
+ 'baz',
181
+ [{ type: 'end' }],
182
+ ],
183
+ ['root ::= [a-z]', '', [{ type: 'char', value: [[97, 122]] }]],
184
+ [
185
+ 'root ::= [a-zA-Z]',
186
+ '',
187
+ [
188
+ {
189
+ type: 'char',
190
+ value: [
191
+ [97, 122],
192
+ [65, 90],
193
+ ],
194
+ },
195
+ ],
196
+ ],
197
+ ['root ::= [a-z]', 'a', [{ type: 'end' }]],
198
+ ['root ::= [a-z]', 'm', [{ type: 'end' }]],
199
+ ['root ::= [a-z]', 'z', [{ type: 'end' }]],
200
+ ['root ::= [a-zA-Z]', 'a', [{ type: 'end' }]],
201
+ ['root ::= [a-zA-Z]', 'Z', [{ type: 'end' }]],
202
+ ['root ::= [a-zA-Z0-9]', 'Z', [{ type: 'end' }]],
203
+ ['root ::= [a-zA-Z0-9]', '0', [{ type: 'end' }]],
204
+ ['root ::= [a-zA-Z0-9]', '9', [{ type: 'end' }]],
205
+ [
206
+ 'root ::= [a-z]?',
207
+ '',
208
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
209
+ ],
210
+ ['root ::= [a-z]?', 'a', [{ type: 'end' }]],
211
+ ['root ::= [a-zA-Z]?', 'Z', [{ type: 'end' }]],
212
+ ['root ::= [a-zA-Z0-9]?', '0', [{ type: 'end' }]],
213
+ ['root ::= [a-z]+', '', [{ type: 'char', value: [[97, 122]] }]],
214
+ [
215
+ 'root ::= [a-z]+',
216
+ 'l',
217
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
218
+ ],
219
+ [
220
+ 'root ::= [a-zA-Z]+',
221
+ 'Z',
222
+ [
223
+ {
224
+ type: 'char',
225
+ value: [
226
+ [97, 122],
227
+ [65, 90],
228
+ ],
229
+ },
230
+ { type: 'end' },
231
+ ],
232
+ ],
233
+ [
234
+ 'root ::= [a-zA-Z]+',
235
+ 'aZ',
236
+ [
237
+ {
238
+ type: 'char',
239
+ value: [
240
+ [97, 122],
241
+ [65, 90],
242
+ ],
243
+ },
244
+ { type: 'end' },
245
+ ],
246
+ ],
247
+ [
248
+ 'root ::= [a-zA-Z]+',
249
+ 'azAZ',
250
+ [
251
+ {
252
+ type: 'char',
253
+ value: [
254
+ [97, 122],
255
+ [65, 90],
256
+ ],
257
+ },
258
+ { type: 'end' },
259
+ ],
260
+ ],
261
+ [
262
+ 'root ::= [a-z]*',
263
+ '',
264
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
265
+ ],
266
+ [
267
+ 'root ::= [a-z]*',
268
+ 'a',
269
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
270
+ ],
271
+ [
272
+ 'root ::= [a-zA-Z]+',
273
+ 'Z',
274
+ [
275
+ {
276
+ type: 'char',
277
+ value: [
278
+ [97, 122],
279
+ [65, 90],
280
+ ],
281
+ },
282
+ { type: 'end' },
283
+ ],
284
+ ],
285
+ [
286
+ 'root ::= [a-zA-Z]+',
287
+ 'abczABCZ',
288
+ [
289
+ {
290
+ type: 'char',
291
+ value: [
292
+ [97, 122],
293
+ [65, 90],
294
+ ],
295
+ },
296
+ { type: 'end' },
297
+ ],
298
+ ],
299
+ [
300
+ 'root ::= [^f]+ "o"',
301
+ 'aaa',
302
+ [
303
+ { type: 'char_exclude', value: [102] },
304
+ { type: 'char', value: [111] },
305
+ ],
306
+ ],
307
+ [
308
+ 'root ::= [^A-Z]+',
309
+ 'abc',
310
+ [{ type: 'char_exclude', value: [[65, 90]] }, { type: 'end' }],
311
+ ],
312
+ [
313
+ 'root ::= [^A-Z0-9]*',
314
+ 'abc',
315
+ [
316
+ {
317
+ type: 'char_exclude',
318
+ value: [
319
+ [65, 90],
320
+ [48, 57],
321
+ ],
322
+ },
323
+ { type: 'end' },
324
+ ],
325
+ ],
326
+ [
327
+ 'root ::= [^A-Z0-9_-]*',
328
+ 'abc',
329
+ [
330
+ { type: 'char_exclude', value: [[65, 90], [48, 57], 95, 45] },
331
+ { type: 'end' },
332
+ ],
333
+ ],
334
+ [
335
+ '\nroot ::= [a-z] | xyx\nxyx ::= "foo"',
336
+ 'f',
337
+ [{ type: 'end' }, { type: 'char', value: [111] }],
338
+ ],
339
+ [
340
+ 'root ::= "foo" | "bar" | "baz" | "bazaar" | "barrington" ',
341
+ 'bazaa',
342
+ [{ type: 'char', value: [114] }],
343
+ ],
344
+ ['root ::= ("bar" | "foo") "zyx"', 'bar', [{ type: 'char', value: [122] }]],
345
+ [
346
+ 'root ::= "z" ("bar" | "foo") "zzzz"',
347
+ 'z',
348
+ [
349
+ { type: 'char', value: [98] },
350
+ { type: 'char', value: [102] },
351
+ ],
352
+ ],
353
+ [
354
+ 'root ::= "z" ("bar" | "foo") "zzz"',
355
+ 'zbar',
356
+ [{ type: 'char', value: [122] }],
357
+ ],
358
+ [
359
+ '\nroot ::= termz ([-+*/] termz)* \ntermz ::= [0-9]+',
360
+ '1',
361
+ [
362
+ { type: 'char', value: [[48, 57]] },
363
+ { type: 'char', value: [45, 43, 42, 47] },
364
+ { type: 'end' },
365
+ ],
366
+ ],
367
+ [
368
+ '\nroot ::= expr "=" termy \nexpr ::= termy ([-+*/] termy)*\ntermy ::= [0-9]+',
369
+ '1',
370
+ [
371
+ { type: 'char', value: [[48, 57]] },
372
+ { type: 'char', value: [45, 43, 42, 47] },
373
+ { type: 'char', value: [61] },
374
+ ],
375
+ ],
376
+ [
377
+ '\nroot ::= (expr "=" terma "\n")+\nexpr ::= terma ([-+*/] terma)*\nterma ::= [0-9]+',
378
+ '1',
379
+ [
380
+ { type: 'char', value: [[48, 57]] },
381
+ { type: 'char', value: [45, 43, 42, 47] },
382
+ { type: 'char', value: [61] },
383
+ ],
384
+ ],
385
+ [
386
+ 'root ::= (expr "=" termb "\n")+\nexpr ::= termb ([-+*/] termb)*\ntermb ::= [0-9]+',
387
+ '1+',
388
+ [{ type: 'char', value: [[48, 57]] }],
389
+ ],
390
+ [
391
+ '\nroot ::= (expr "=" termc "\n")+\nexpr ::= termc ([-+*/] termc)*\ntermc ::= [0-9]+',
392
+ '1=',
393
+ [{ type: 'char', value: [[48, 57]] }],
394
+ ],
395
+ [
396
+ 'root ::= (expr "=" termd "\n")+\nexpr ::= termd ([-+*/] termd)*\ntermd ::= [0-9]+',
397
+ '1+1',
398
+ [
399
+ { type: 'char', value: [[48, 57]] },
400
+ { type: 'char', value: [45, 43, 42, 47] },
401
+ { type: 'char', value: [61] },
402
+ ],
403
+ ],
404
+ [
405
+ 'root ::= (expr "=" term "\n")+\nexpr ::= term ([-+*/] term)*\nterm ::= [0-9]+',
406
+ '1=1',
407
+ [
408
+ { type: 'char', value: [[48, 57]] },
409
+ { type: 'char', value: [10] },
410
+ ],
411
+ ],
412
+ [
413
+ 'root ::= "\\"" ( [^\\"abcdefghA-Z])* ',
414
+ "\"is not only in its lyrism, its vow to sustin it in its poo-sion, its r,v:l'y, it's tory,",
415
+ [
416
+ {
417
+ type: 'char_exclude',
418
+ value: [34, 97, 98, 99, 100, 101, 102, 103, 104, [65, 90]],
419
+ },
420
+ { type: 'end' },
421
+ ],
422
+ ],
423
+ [
424
+ 'root ::= ( [^abcdefgh] | [b-z])* ',
425
+ 'bcdefghzyxw0123ABCZ',
426
+ [
427
+ { type: 'char_exclude', value: [97, 98, 99, 100, 101, 102, 103, 104] },
428
+ { type: 'char', value: [[98, 122]] },
429
+ { type: 'end' },
430
+ ],
431
+ ],
432
+ ] as [
433
+ string,
434
+ string,
435
+ {
436
+ type: string;
437
+ value: number[];
438
+ }[],
439
+ ][])(
440
+ 'It returns parse state for a grammar and initial string (%#): `%s` `%s`',
441
+ ([grammar, input, expected]) => {
442
+ let state = GBNF(grammar);
443
+ state = state.add(input);
444
+ expect([...state]).toEqual(expected);
445
+ }
446
+ );
447
+ });
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/iteration/iteration.test.ts ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, test, expect } from 'vitest';
2
+ import GBNF, { RuleType } from 'gbnf';
3
+
4
+ describe('Iteration', () => {
5
+ test.for([
6
+ ['root ::= "foo"', [{ type: 'char', value: [102] }]],
7
+ [
8
+ 'root ::= "foo" | "bar" ',
9
+ [
10
+ { type: 'char', value: [102] },
11
+ { type: 'char', value: [98] },
12
+ ],
13
+ ],
14
+ [
15
+ 'root ::= "foo" | "bar" | "gaz"',
16
+ [
17
+ { type: 'char', value: [102] },
18
+ { type: 'char', value: [98] },
19
+ { type: 'char', value: [103] },
20
+ ],
21
+ ],
22
+ [
23
+ 'root ::= "foo" | "bar" | "baz"',
24
+ [
25
+ { type: 'char', value: [102] },
26
+ { type: 'char', value: [98] },
27
+ ],
28
+ ],
29
+ ['root ::= [^x]', [{ type: 'char_exclude', value: [120] }]],
30
+ ['root ::= [^f] "o"', [{ type: 'char_exclude', value: [102] }]],
31
+ ['root ::= [^A-Z]', [{ type: 'char_exclude', value: [[65, 90]] }]],
32
+ [
33
+ 'root ::= [^A-Z0-9]',
34
+ [
35
+ {
36
+ type: 'char_exclude',
37
+ value: [
38
+ [65, 90],
39
+ [48, 57],
40
+ ],
41
+ },
42
+ ],
43
+ ],
44
+ [
45
+ 'root ::= [^A-Z0-9_-]',
46
+ [{ type: 'char_exclude', value: [[65, 90], [48, 57], 95, 45] }],
47
+ ],
48
+ ['\nroot ::= foo\nfoo ::= "foo"\n ', [{ type: 'char', value: [102] }]],
49
+ [
50
+ '\nroot ::= f\nf ::= foo\nfoo ::= "foo"\n ',
51
+ [{ type: 'char', value: [102] }],
52
+ ],
53
+ [
54
+ '\nroot ::= foo | "bar"\nfoo ::= "foo"',
55
+ [
56
+ { type: 'char', value: [102] },
57
+ { type: 'char', value: [98] },
58
+ ],
59
+ ],
60
+ [
61
+ '\nroot ::= foo | bar\nfoo ::= "foo"\nbar ::= "bar"\n ',
62
+ [
63
+ { type: 'char', value: [102] },
64
+ { type: 'char', value: [98] },
65
+ ],
66
+ ],
67
+ [
68
+ '\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= "foo"\nbar ::= "bar"\nbaz ::= "baz"\n ',
69
+ [
70
+ { type: 'char', value: [102] },
71
+ { type: 'char', value: [98] },
72
+ ],
73
+ ],
74
+ ['root ::= [a-z]', [{ type: 'char', value: [[97, 122]] }]],
75
+ [
76
+ 'root ::= [a-zA-Z]',
77
+ [
78
+ {
79
+ type: 'char',
80
+ value: [
81
+ [97, 122],
82
+ [65, 90],
83
+ ],
84
+ },
85
+ ],
86
+ ],
87
+ [
88
+ 'root ::= [a-z]?',
89
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
90
+ ],
91
+ ['root ::= [a-z]+', [{ type: 'char', value: [[97, 122]] }]],
92
+ [
93
+ 'root ::= [a-z]*',
94
+ [{ type: 'char', value: [[97, 122]] }, { type: 'end' }],
95
+ ],
96
+ ['\n root ::= "foo"\n foo ::= "foo"', [{ type: 'char', value: [102] }]],
97
+ [
98
+ '\n root ::= (expr "=" term "\\n")+\n expr ::= term ([-+*/] term)*\n term ::= [0-9]+\n ',
99
+ [{ type: 'char', value: [[48, 57]] }],
100
+ ],
101
+ ] as [string, { type: string; value: number[] }[]][])(
102
+ 'It returns parse state for a grammar (%#): `%s`',
103
+ ([grammar, expected]) => {
104
+ let state = GBNF(grammar);
105
+ expect([...state]).toEqual(expected);
106
+ }
107
+ );
108
+ });
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/validation/validate-grammar.test.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, test, expect } from 'vitest';
2
+ import GBNF, { GrammarParseError } from 'gbnf';
3
+
4
+ describe('Validate Grammar', () => {
5
+ test.for([
6
+ 'root ::= "foo"',
7
+ 'root ::= "foo" | "bar"',
8
+ 'root ::= ("foo" | "bar")',
9
+ 'root ::= ("foo" | "bar")?',
10
+ 'root ::= ("foo" | "bar")*',
11
+ 'root ::= ("foo" | "bar")+',
12
+ 'root ::= [a-z]',
13
+ 'root ::= [a-zA-Z]',
14
+ 'root ::= [a-zA-Z0-9]',
15
+ 'root ::= [a-zA-Z0-9]*',
16
+ 'root ::= [a-zA-Z0-9]?',
17
+ 'root ::= [a-z]+',
18
+ 'root ::= [a-zA-Z0-9]+',
19
+ 'root ::= ([a-zA-Z0-9])*',
20
+ 'root ::= ([a-zA-Z0-9])?',
21
+ 'root ::= ([a-zA-Z0-9])+',
22
+ '\n root ::= foo\n foo ::= "foo"',
23
+ '\n root ::= foo\n foo ::= "foo" | "bar" | ([a-z])?\n ',
24
+ ])('It parses a grammar (%#): `%s`', (grammar) => {
25
+ expect(GBNF(grammar)).toBeTruthy();
26
+ });
27
+
28
+ test.for([
29
+ ['', 0, 'No rules were found'],
30
+ ['root = "foo"', 5, 'Expecting ::= at 5'],
31
+ ['root ::= foo\nfoo := "foo"\n ', 17, 'Expecting ::= at 17'],
32
+ ['root ::= foo', 9, 'Undefined rule identifier "foo"'],
33
+ ['root ::= foo\nbar ::= "bar"\n ', 9, 'Undefined rule identifier "foo"'],
34
+ [
35
+ 'root ::= foo\nfoo ::= baz\nbar ::= "bar"\n ',
36
+ 21,
37
+ 'Undefined rule identifier "baz"',
38
+ ],
39
+ ['root ::= foo ::= bar', 13, 'Expecting newline or end at 13'],
40
+ ['root ::= ([a-z]\nfoo ::= "foo"\n ', 20, "Expecting ')' at 20"],
41
+ ] as [string, number, string][])(
42
+ 'It reports an error for an invalid grammar (%#): `%s`',
43
+ ([grammar, errorPos, errorReason]) => {
44
+ expect(() => {
45
+ GBNF(grammar);
46
+ }).toThrowError(new GrammarParseError(grammar, errorPos, errorReason));
47
+ }
48
+ );
49
+ });
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/validation/validate-input.test.ts ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, test, expect } from 'vitest';
2
+ import GBNF, { InputParseError } from 'gbnf';
3
+
4
+ describe('Validate Input', () => {
5
+ test.for([['root ::= "foo"', 'f']] as [string, string][])(
6
+ 'It parses a grammar and input (%#): `%s` `%s`',
7
+ ([grammar, input]) => {
8
+ expect(GBNF(grammar, input)).toBeTruthy();
9
+ }
10
+ );
11
+
12
+ test.for([
13
+ ['root ::= "foo"', '2', 0],
14
+ ['root ::= "foo"', 'b', 0],
15
+ ['root ::= "foo"', 'f1', 1],
16
+ ['root ::= "foo"', 'fo1', 2],
17
+ ['root ::= "foo"', 'fooo', 3],
18
+ ['root ::= "foo"', 'fooooooo', 3],
19
+ ['root ::= "foo" | "bar"', '1', 0],
20
+ ['root ::= "foo" | "bar"', 'z', 0],
21
+ ['root ::= "foo" | "bar"', 'f1', 1],
22
+ ['root ::= "foo" | "bar"', 'b1', 1],
23
+ ['root ::= "foo" | "bar"', 'fo1', 2],
24
+ ['root ::= "foo" | "bar"', 'ba1', 2],
25
+ ['root ::= "foo" | "bar"', 'fooo', 3],
26
+ ['root ::= "foo" | "bar"', 'barrr', 3],
27
+ ['root ::= "foo" | "bar" | "baz"', '1', 0],
28
+ ['root ::= "foo" | "bar" | "baz"', 'z', 0],
29
+ ['root ::= "foo" | "bar" | "baz"', 'f1', 1],
30
+ ['root ::= "foo" | "bar" | "baz"', 'b1', 1],
31
+ ['root ::= "foo" | "bar" | "baz"', 'fo1', 2],
32
+ ['root ::= "foo" | "bar" | "baz"', 'bal', 2],
33
+ ['root ::= "foo" | "bar" | "baz"', 'fooo', 3],
34
+ ['root ::= "foo" | "bar" | "baz"', 'bazrr', 3],
35
+ ['root ::= [^a]', 'a', 0],
36
+ ['root ::= [^abc]', 'b', 0],
37
+ ['root ::= [^a-z]', 'z', 0],
38
+ ['root ::= [^a-zA-Z]', 'X', 0],
39
+ ['root ::= [^a-zA-Z0-9]', '8', 0],
40
+ ['\n root ::= foo\n foo ::= "foo"', '1', 0],
41
+ ['\n root ::= foo\n foo ::= "foo"', 'b', 0],
42
+ ['\n root ::= foo\n foo ::= "foo"', 'f1', 1],
43
+ ['\n root ::= foo\n foo ::= "foo"', 'fo1', 2],
44
+ ['\n root ::= foo\n foo ::= "foo"', 'fooo', 3],
45
+ ['\n root::=foo|"bar"\n foo::="foo"', '1', 0],
46
+ ['\n root::=foo|"bar"\n foo::="foo"', 'z', 0],
47
+ ['\n root::=foo|"bar"\n foo::="foo"', 'f1', 1],
48
+ ['\n root::=foo|"bar"\n foo::="foo"', 'b1', 1],
49
+ ['\n root::=foo|"bar"\n foo::="foo"', 'fo1', 2],
50
+ ['\n root::=foo|"bar"\n foo::="foo"', 'fooo', 3],
51
+ ['\n root::=foo|"bar"\n foo::="foo"', 'barr', 3],
52
+ ['\n root::= foo | bar\n foo::="foo"\n bar::="bar"', '1', 0],
53
+ ['\n root::= foo | bar\n foo::="foo"\n bar::="bar"', 'z', 0],
54
+ ['\n root::= foo | bar\n foo::="foo"\n bar::="bar"', 'f1', 1],
55
+ ['\n root::= foo | bar\n foo::="foo"\n bar::="bar"', 'b1', 1],
56
+ ['\n root::= foo | bar\n foo::="foo"\n bar::="bar"', 'fo1', 2],
57
+ ['\n root::= foo | bar\n foo::="foo"\n bar::="bar"', 'fooo', 3],
58
+ ['\n root::= foo | bar\n foo::="foo"\n bar::="bar"', 'barr', 3],
59
+ [
60
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"\n ',
61
+ '1',
62
+ 0,
63
+ ],
64
+ [
65
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"',
66
+ 'z',
67
+ 0,
68
+ ],
69
+ [
70
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"',
71
+ 'f1',
72
+ 1,
73
+ ],
74
+ [
75
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"',
76
+ 'b1',
77
+ 1,
78
+ ],
79
+ [
80
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"',
81
+ 'fo1',
82
+ 2,
83
+ ],
84
+ [
85
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"',
86
+ 'fooo',
87
+ 3,
88
+ ],
89
+ [
90
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"',
91
+ 'barr',
92
+ 3,
93
+ ],
94
+ [
95
+ '\n root ::= f | b\n f ::= fo\n b ::= ba\n fo ::= foo\n ba ::= bar | baz\n foo ::= "foo"\n bar ::= "bar"\n baz ::= "baz"',
96
+ 'bazr',
97
+ 3,
98
+ ],
99
+ ['root ::= [a-z]', 'A', 0],
100
+ ['root ::= [a-z]', '0', 0],
101
+ ['root ::= [a-z]', 'az', 1],
102
+ ['root ::= [a-z]?', 'A', 0],
103
+ ['root ::= [a-z]?', '0', 0],
104
+ ['root ::= [a-z]?', 'az', 1],
105
+ ['root ::= [a-z]+', 'A', 0],
106
+ ['root ::= [a-z]+', '0', 0],
107
+ ['root ::= [a-z]+', 'az0', 2],
108
+ ['root ::= [a-z]*', 'A', 0],
109
+ ['root ::= [a-z]*', '0', 0],
110
+ ['root ::= [a-z]*', 'az0', 2],
111
+ ['root ::= ( [^abcdefgh] | [b-z])*', 'a', 0],
112
+ ] as [string, string, number][])(
113
+ 'It reports an error for an invalid input (%#): `%s`',
114
+ ([grammar, input, errorPos]) => {
115
+ const error = new InputParseError(input, errorPos, '');
116
+ expect(() => {
117
+ const graph = GBNF(grammar);
118
+ graph.add(input);
119
+ }).toThrowError(error);
120
+ }
121
+ );
122
+ });
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tests/vitest.config.unit.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The alias is absolute because vitest rejects relative ones.
2
+ export default {
3
+ test: {
4
+ include: [
5
+ 'tests/**/*.test.ts',
6
+ ],
7
+ watchExclude: [
8
+ 'tmp/**/*',
9
+ ],
10
+ globals: true,
11
+ },
12
+ resolve: {
13
+ alias: {
14
+ gbnf: '/workspace/ported_implementation/src/index.ts',
15
+ },
16
+ },
17
+ };
v1/runs/20260909T020947Z_ffb57550/ported_implementation/tsconfig.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022", "DOM"],
7
+ "strict": true,
8
+ "noUncheckedIndexedAccess": false,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "noEmit": true,
12
+ "verbatimModuleSyntax": true
13
+ },
14
+ "include": ["src"]
15
+ }
v1/runs/20260909T020947Z_ffb57550/ported_implementation/vitest.config.unit.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The alias is absolute because vitest rejects relative ones.
2
+ export default {
3
+ test: {
4
+ include: [
5
+ 'tests/**/*.test.ts',
6
+ ],
7
+ watchExclude: [
8
+ 'tmp/**/*',
9
+ ],
10
+ globals: true,
11
+ },
12
+ resolve: {
13
+ alias: {
14
+ gbnf: '/workspace/ported_implementation/src/index.ts',
15
+ },
16
+ },
17
+ };
v1/runs/20260909T020947Z_ffb57550/proxy.log ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NOTICE Sep 09 02:09:49.402 [1]: Initializing tinyproxy ...
2
+ NOTICE Sep 09 02:09:49.402 [1]: Reloading config file (/etc/tinyproxy/tinyproxy.conf)
3
+ INFO Sep 09 02:09:49.402 [1]: Added address [0.0.0.0] to listen addresses.
4
+ INFO Sep 09 02:09:49.402 [1]: Adding Port [443] to the list allowed by CONNECT
5
+ NOTICE Sep 09 02:09:49.402 [1]: Reloading config file finished
6
+ INFO Sep 09 02:09:49.402 [1]: listen_sock called with addr = '0.0.0.0'
7
+ INFO Sep 09 02:09:49.402 [1]: trying to listen on host[0.0.0.0], family[2], socktype[1], proto[6]
8
+ INFO Sep 09 02:09:49.402 [1]: listening on fd [3]
9
+ INFO Sep 09 02:09:49.402 [1]: Not running as root, so not changing UID/GID.
10
+ INFO Sep 09 02:09:49.402 [1]: Setting the various signals.
11
+ INFO Sep 09 02:09:49.402 [1]: Starting main loop. Accepting connections.
12
+ CONNECT Sep 09 02:09:49.661 [1]: Connect (file descriptor 4): 172.20.0.3
13
+ CONNECT Sep 09 02:09:49.661 [1]: Request (file descriptor 4): CONNECT api.anthropic.com:443 HTTP/1.1
14
+ INFO Sep 09 02:09:49.661 [1]: No upstream proxy for api.anthropic.com
15
+ INFO Sep 09 02:09:49.661 [1]: opensock: opening connection to api.anthropic.com:443
16
+ INFO Sep 09 02:09:49.662 [1]: opensock: getaddrinfo returned for api.anthropic.com:443
17
+ CONNECT Sep 09 02:09:49.666 [1]: Established connection to host "api.anthropic.com" using file descriptor 5.
18
+ INFO Sep 09 02:09:49.666 [1]: Not sending client headers to remote machine
19
+ CONNECT Sep 09 02:09:49.695 [1]: Connect (file descriptor 6): 172.20.0.3
20
+ CONNECT Sep 09 02:09:49.697 [1]: Request (file descriptor 6): CONNECT api.anthropic.com:443 HTTP/1.1
21
+ INFO Sep 09 02:09:49.697 [1]: No upstream proxy for api.anthropic.com
22
+ INFO Sep 09 02:09:49.697 [1]: opensock: opening connection to api.anthropic.com:443
23
+ INFO Sep 09 02:09:49.698 [1]: opensock: getaddrinfo returned for api.anthropic.com:443
24
+ CONNECT Sep 09 02:09:49.703 [1]: Established connection to host "api.anthropic.com" using file descriptor 7.
25
+ INFO Sep 09 02:09:49.703 [1]: Not sending client headers to remote machine
26
+ CONNECT Sep 09 02:09:49.754 [1]: Connect (file descriptor 8): 172.20.0.3
27
+ CONNECT Sep 09 02:09:49.754 [1]: Request (file descriptor 8): CONNECT api.anthropic.com:443 HTTP/1.1
28
+ INFO Sep 09 02:09:49.754 [1]: No upstream proxy for api.anthropic.com
29
+ INFO Sep 09 02:09:49.754 [1]: opensock: opening connection to api.anthropic.com:443
30
+ INFO Sep 09 02:09:49.755 [1]: opensock: getaddrinfo returned for api.anthropic.com:443
31
+ CONNECT Sep 09 02:09:49.759 [1]: Established connection to host "api.anthropic.com" using file descriptor 9.
32
+ INFO Sep 09 02:09:49.759 [1]: Not sending client headers to remote machine
33
+ INFO Sep 09 02:09:49.902 [1]: Closed connection between local client (fd:4) and remote client (fd:5)
34
+ INFO Sep 09 02:09:49.916 [1]: Closed connection between local client (fd:6) and remote client (fd:7)
35
+ CONNECT Sep 09 02:09:49.930 [1]: Connect (file descriptor 4): 172.20.0.3
36
+ CONNECT Sep 09 02:09:49.930 [1]: Request (file descriptor 4): CONNECT mcp-proxy.anthropic.com:443 HTTP/1.1
37
+ NOTICE Sep 09 02:09:49.930 [1]: Proxying refused on filtered domain "mcp-proxy.anthropic.com"
38
+ CONNECT Sep 09 02:09:49.930 [1]: Connect (file descriptor 5): 172.20.0.3
39
+ CONNECT Sep 09 02:09:49.930 [1]: Request (file descriptor 5): CONNECT mcp-proxy.anthropic.com:443 HTTP/1.1
40
+ CONNECT Sep 09 02:09:49.930 [1]: Connect (file descriptor 6): 172.20.0.3
41
+ NOTICE Sep 09 02:09:49.930 [1]: Proxying refused on filtered domain "mcp-proxy.anthropic.com"
42
+ CONNECT Sep 09 02:09:49.930 [1]: Request (file descriptor 6): CONNECT mcp-proxy.anthropic.com:443 HTTP/1.1
43
+ NOTICE Sep 09 02:09:49.930 [1]: Proxying refused on filtered domain "mcp-proxy.anthropic.com"
44
+ CONNECT Sep 09 02:11:21.436 [1]: Connect (file descriptor 4): 172.20.0.3
45
+ CONNECT Sep 09 02:11:21.437 [1]: Request (file descriptor 4): CONNECT registry.npmjs.org:443 HTTP/1.1
46
+ NOTICE Sep 09 02:11:21.437 [1]: Proxying refused on filtered domain "registry.npmjs.org"
47
+ CONNECT Sep 09 02:11:24.705 [1]: Connect (file descriptor 4): 172.20.0.3
48
+ CONNECT Sep 09 02:11:24.705 [1]: Request (file descriptor 4): CONNECT registry.npmjs.org:443 HTTP/1.1
49
+ NOTICE Sep 09 02:11:24.705 [1]: Proxying refused on filtered domain "registry.npmjs.org"
50
+ ERROR Sep 09 02:14:25.529 [1]: read_buffer: read() failed on fd 8: Connection reset by peer
51
+ INFO Sep 09 02:14:25.529 [1]: Closed connection between local client (fd:8) and remote client (fd:9)
52
+ CONNECT Sep 09 02:14:25.543 [1]: Connect (file descriptor 4): 172.20.0.3
53
+ CONNECT Sep 09 02:14:25.543 [1]: Request (file descriptor 4): CONNECT api.anthropic.com:443 HTTP/1.1
54
+ INFO Sep 09 02:14:25.543 [1]: No upstream proxy for api.anthropic.com
55
+ INFO Sep 09 02:14:25.543 [1]: opensock: opening connection to api.anthropic.com:443
56
+ INFO Sep 09 02:14:25.543 [1]: opensock: getaddrinfo returned for api.anthropic.com:443
57
+ CONNECT Sep 09 02:14:25.617 [1]: Established connection to host "api.anthropic.com" using file descriptor 5.
58
+ INFO Sep 09 02:14:25.617 [1]: Not sending client headers to remote machine
59
+ CONNECT Sep 09 02:20:17.958 [1]: Connect (file descriptor 6): 172.20.0.3
60
+ CONNECT Sep 09 02:20:17.958 [1]: Request (file descriptor 6): CONNECT registry.npmjs.org:443 HTTP/1.1
61
+ NOTICE Sep 09 02:20:17.958 [1]: Proxying refused on filtered domain "registry.npmjs.org"
62
+ INFO Sep 09 02:22:15.778 [1]: Closed connection between local client (fd:4) and remote client (fd:5)
v1/runs/20260909T020947Z_ffb57550/result.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"duration_api_ms":741207,"stop_reason":"end_turn","session_id":"session_redacted_10","total_cost_usd":4.843498499999999,"usage":{"input_tokens":108,"cache_creation_input_tokens":113976,"cache_read_input_tokens":4689373,"output_tokens":45113,"output_tokens_details":{"thinking_tokens":15213},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":113976,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[],"speed":"standard"},"modelUsage":{"claude-opus-5":{"inputTokens":110,"outputTokens":52798,"cacheReadInputTokens":4766477,"cacheCreationInputTokens":113976,"webSearchRequests":0,"costUSD":4.843498499999999,"contextWindow":1000000,"maxOutputTokens":64000,"thinkingTokens":22749,"canonicalModel":"claude-opus-5","provider":"firstParty","costBasis":"list"}},"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":{}},"is_error":false,"num_turns":55,"subtype":"success","api_error_status":null,"result":"Done. **773/773 tests pass** (`npx vitest run --config vitest.config.unit.ts` in `/workspace/ported_implementation`).\n\n## What I built\n\nA module-for-module TypeScript port in `ported_implementation/src/`, mirroring the Python package layout (`snake_case` → `kebab-case`):\n\n- `GBNF.ts`, `index.ts` — entry point + public exports (`GBNF` default/named, `GrammarParseError`, `InputParseError`, `RuleType`)\n- `grammar-graph/` — `graph.ts`, `graph-node.ts`, `graph-pointer.ts`, `parse-state.ts`, `pointers.ts`, `rule-ref.ts`, `rule-type.ts`, `type-guards.ts`, `print.ts`, `colorize.ts`, and the three helpers\n- `grammar-parser/build-rule-stack.ts`\n- `rules-builder/` — `rules-builder.ts`, `symbol-ids.ts`, `parse-char.ts`, `parse-name.ts`, `parse-space.ts`, `is-word-char.ts`, types\n- `utils/` — `errors/` (both error classes, `build-error-position`, `get-input-as-string`), `is-point-in-range`, `validate-non-empty`\n\nPlus `package.json`, `tsconfig.json`, `README.md`, and the copied suite at `tests/` with `vitest.config.unit.ts` (whose alias already points at `src/index.ts`).\n\n## Porting decisions worth knowing\n\n- **Rules are plain tagged objects** (`{ type: 'char', value }`), not dataclasses — the JS suite asserts exactly that shape via `toEqual`. `RuleRef` stays a class since its `nodes` are patched in after graph construction.\n- **Ordering.** Python's `set` of referenced nodes is unordered; the tests assert an exact rule order, so I used a JS `Set`/`Map` throughout, whose insertion order is the natural path order. That's what makes cases like `[char_exclude, char, end]` come out right.\n- **Code points.** Input is decoded with `Array.from`, and error-position lengths are counted in code points, matching Python's per-code-point string semantics. Grammar-source scanning uses plain string indexing (all BMP in practice, as the reference's own indexing assumes).\n- **Variance.** `GraphNode.rule` and `GraphPointer.node`/`parent` are `readonly` so narrowed pointers (`GraphPointer<RuleEnd>`) stay assignable to `GraphPointer` — otherwise the generic would be invariant and `resolve()` wouldn't type-check.\n\nTwo caveats to flag: **no `tsc` is available** in this environment (npm registry is blocked, TypeScript isn't installed), so types are hand-reviewed only — vitest's esbuild transform strips types without checking them. And I ported the library, not the Python `*_test.py` unit tests colocated with the reference source; `tests/` is the generated suite, which is what the task pointed at.","ttft_ms":1231,"type":"result","duration_ms":746035,"uuid":"ebdb4597-8dbc-4ed2-979d-48e8ba88914d","ttft_stream_ms":718,"time_to_request_ms":27,"first_content_frame_ms":719,"queued_turn_count":0}
v1/runs/20260909T020947Z_ffb57550/transcript/-workspace/cff45a82-8ac1-4e8e-87fe-be8d30ab6e86.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
v1/runs/20260909T020947Z_ffb57550/transcript/-workspace/cff45a82-8ac1-4e8e-87fe-be8d30ab6e86/tool-results/bxo19mfrs.txt ADDED
@@ -0,0 +1,1752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ════ gbnf/GBNF.py ════
2
+ 1 from .grammar_graph.graph import Graph
3
+ 2 from .grammar_graph.parse_state import ParseState
4
+ 3 from .grammar_parser.build_rule_stack import build_rule_stack
5
+ 4 from .rules_builder import GrammarParseError, RulesBuilder
6
+ 5
7
+ 6 # ValidInput = str | int | float | list[int | float]
8
+ 7
9
+ 8
10
+ 9 def GBNF(grammar: str, initial_string: str = ""):
11
+ 10 if not isinstance(grammar, str):
12
+ 11 raise ValueError("grammar must be a string")
13
+ 12
14
+ 13 if not isinstance(initial_string, str):
15
+ 14 raise ValueError("input must be a string")
16
+ 15
17
+ 16 # const grammar = typeof input === 'string' ? input : input.toString();
18
+ 17
19
+ 18 rules_builder = RulesBuilder(grammar)
20
+ 19 rules, symbol_ids = rules_builder.rules, rules_builder.symbol_ids
21
+ 20 if len(rules) == 0:
22
+ 21 raise GrammarParseError(grammar, 0, "No rules were found")
23
+ 22 if symbol_ids["root"] is None:
24
+ 23 raise GrammarParseError(grammar, 0, "Grammar does not contain a 'root' symbol")
25
+ 24 root_id: int = symbol_ids["root"]
26
+ 25
27
+ 26 stacked_rules = [build_rule_stack(rule) for rule in rules]
28
+ 27 graph = Graph(grammar, stacked_rules, root_id)
29
+ 28 return ParseState(graph, graph.add(initial_string))
30
+ ════ gbnf/__init__.py ════
31
+ 1 from .GBNF import GBNF as GBNF
32
+ 2 from .grammar_graph.grammar_graph_types import RuleChar, RuleCharExclude, RuleEnd
33
+ 3 from .utils.errors import GrammarParseError, InputParseError
34
+ 4
35
+ 5 __all__ = [
36
+ 6 "GBNF",
37
+ 7 "GrammarParseError",
38
+ 8 "InputParseError",
39
+ 9 "RuleChar",
40
+ 10 "RuleCharExclude",
41
+ 11 "RuleEnd",
42
+ 12 ]
43
+ ════ gbnf/grammar_graph/__init__.py ════
44
+ ════ gbnf/grammar_graph/colorize.py ════
45
+ 1 class Color:
46
+ 2 BLUE = "\x1b[34m"
47
+ 3 CYAN = "\x1b[36m"
48
+ 4 GREEN = "\x1b[32m"
49
+ 5 RED = "\x1b[31m"
50
+ 6 GRAY = "\x1b[90m"
51
+ 7 YELLOW = "\x1b[33m"
52
+ 8
53
+ 9
54
+ 10 def colorize(text: str | int, color: str) -> str:
55
+ 11 return f"{color}{text}"
56
+ ════ gbnf/grammar_graph/get_input_as_code_points.py ════
57
+ 1 from .grammar_graph_types import ValidInput
58
+ 2
59
+ 3
60
+ 4 def get_code_point(char: str) -> int:
61
+ 5 code_point = ord(char)
62
+ 6 if code_point is None:
63
+ 7 raise ValueError(f"Could not get code point for character: {char}")
64
+ 8 if type(code_point) is not int:
65
+ 9 raise ValueError("code_point must be an integer!")
66
+ 10 return code_point
67
+ 11
68
+ 12
69
+ 13 def get_input_as_code_points(src: ValidInput) -> list[int]:
70
+ 14 if isinstance(src, int):
71
+ 15 return [src]
72
+ 16
73
+ 17 if isinstance(src, list):
74
+ 18 for c in src:
75
+ 19 if type(c) is not int:
76
+ 20 raise ValueError(
77
+ 21 f"code_point must be an integer for {c} if src is a list",
78
+ 22 )
79
+ 23 return src
80
+ 24
81
+ 25 if isinstance(src, str):
82
+ 26 return [get_code_point(s) for s in src]
83
+ 27
84
+ 28 raise ValueError(f"Invalid input type: {type(src)}")
85
+ ════ gbnf/grammar_graph/get_parent_stack_id.py ════
86
+ 1 from __future__ import annotations
87
+ 2
88
+ 3 from collections.abc import Callable
89
+ 4 from typing import TYPE_CHECKING
90
+ 5
91
+ 6 from .colorize import Color
92
+ 7
93
+ 8 if TYPE_CHECKING:
94
+ 9 from .graph_pointer import GraphPointer
95
+ 10
96
+ 11
97
+ 12 def get_parent_stack_id(
98
+ 13 pointer: GraphPointer,
99
+ 14 col: Callable[[str | int, str], str],
100
+ 15 ) -> str:
101
+ 16 stack_ids: list[str] = []
102
+ 17 parent: GraphPointer | None = pointer.parent
103
+ 18 while parent:
104
+ 19 stack_ids.append(
105
+ 20 f"{parent.node.meta['stackId']},{parent.node.meta['pathId']},{parent.node.meta['stepId']}",
106
+ 21 )
107
+ 22 parent = parent.parent
108
+ 23 arrow = col("<-", Color.GRAY)
109
+ 24 return arrow.join([col(stack_id, Color.RED) for stack_id in stack_ids])
110
+ ════ gbnf/grammar_graph/get_serialized_rule_key.py ════
111
+ 1 from __future__ import annotations
112
+ 2
113
+ 3 import json
114
+ 4
115
+ 5 from .grammar_graph_types import (
116
+ 6 RuleChar,
117
+ 7 RuleCharExclude,
118
+ 8 RuleEnd,
119
+ 9 RuleRef,
120
+ 10 UnresolvedRule,
121
+ 11 )
122
+ 12 from .type_guards import is_rule_char, is_rule_char_exclude, is_rule_end, is_rule_ref
123
+ 13
124
+ 14 KEY_TRANSLATION = {
125
+ 15 RuleEnd: 0,
126
+ 16 RuleChar: 1,
127
+ 17 RuleCharExclude: 2,
128
+ 18 }
129
+ 19
130
+ 20
131
+ 21 def get_serialized_rule_key(rule: UnresolvedRule) -> str:
132
+ 22 if is_rule_end(rule):
133
+ 23 return f"{KEY_TRANSLATION[RuleEnd]}"
134
+ 24
135
+ 25 if is_rule_char(rule):
136
+ 26 assert isinstance(rule, RuleChar)
137
+ 27 return f"{KEY_TRANSLATION[RuleChar]}-{json.dumps(rule.value)}"
138
+ 28
139
+ 29 if is_rule_char_exclude(rule):
140
+ 30 assert isinstance(rule, RuleCharExclude)
141
+ 31 return f"{KEY_TRANSLATION[RuleCharExclude]}-{json.dumps(rule.value)}"
142
+ 32
143
+ 33 if is_rule_ref(rule):
144
+ 34 assert isinstance(rule, RuleRef)
145
+ 35 return f"3-{rule.value}"
146
+ 36
147
+ 37 raise ValueError(f"Unknown rule type: {rule}")
148
+ ════ gbnf/grammar_graph/grammar_graph_types.py ════
149
+ 1 from __future__ import annotations
150
+ 2
151
+ 3 from collections.abc import Callable
152
+ 4 from dataclasses import dataclass, field
153
+ 5 from typing import TYPE_CHECKING, Any, TypedDict
154
+ 6
155
+ 7 from ..utils.validate_non_empty import validate_non_empty
156
+ 8 from .rule_ref import RuleRef
157
+ 9
158
+ 10 if TYPE_CHECKING:
159
+ 11 from .pointers import Pointers
160
+ 12
161
+ 13
162
+ 14 class PrintOpts(TypedDict):
163
+ 15 pointers: Pointers
164
+ 16 colorize: Callable[[str | int, str], str]
165
+ 17 show_position: bool
166
+ 18
167
+ 19
168
+ 20 Range = tuple[int, int]
169
+ 21
170
+ 22
171
+ 23 class Rule:
172
+ 24 def __eq__(self, other):
173
+ 25 return isinstance(other, self.__class__)
174
+ 26
175
+ 27 def __repr__(self) -> str:
176
+ 28 return f"{self.__class__.__name__}()"
177
+ 29
178
+ 30 def __hash__(self):
179
+ 31 return id(self)
180
+ 32
181
+ 33 @property
182
+ 34 def __dict__(self):
183
+ 35 return {
184
+ 36 "type": self.__class__.__name__,
185
+ 37 }
186
+ 38
187
+ 39
188
+ 40 @dataclass
189
+ 41 class RuleWithValue(Rule):
190
+ 42 value: Any
191
+ 43
192
+ 44 def __eq__(self, other):
193
+ 45 return isinstance(other, self.__class__) and self.value == other.value
194
+ 46
195
+ 47 def __repr__(self) -> str:
196
+ 48 return f"{self.__class__.__name__}(value={self.value})"
197
+ 49
198
+ 50 @property
199
+ 51 def __dict__(self):
200
+ 52 return {
201
+ 53 **super().__dict__,
202
+ 54 "value": self.value,
203
+ 55 }
204
+ 56
205
+ 57
206
+ 58 @dataclass
207
+ 59 class RuleWithListOfIntsOrRanges(RuleWithValue):
208
+ 60 value: list[int | Range] = field(
209
+ 61 default_factory=list,
210
+ 62 metadata={"validate": validate_non_empty},
211
+ 63 )
212
+ 64
213
+ 65 def __post_init__(self):
214
+ 66 self.value = self.value.copy()
215
+ 67
216
+ 68
217
+ 69 @dataclass
218
+ 70 class RuleChar(RuleWithListOfIntsOrRanges):
219
+ 71 def __hash__(self):
220
+ 72 return id(self)
221
+ 73
222
+ 74
223
+ 75 class RuleCharExclude(RuleWithListOfIntsOrRanges):
224
+ 76 def __hash__(self):
225
+ 77 return id(self)
226
+ 78
227
+ 79
228
+ 80 class RuleEnd(Rule):
229
+ 81 def __hash__(self):
230
+ 82 return id(self)
231
+ 83
232
+ 84
233
+ 85 UnresolvedRule = RuleChar | RuleCharExclude | RuleRef | RuleEnd
234
+ 86
235
+ 87
236
+ 88 # ValidInput can either be a string, or a number indicating a code point.
237
+ 89 # It CANNOT be a number representing a number; a number intended as input (like "8")
238
+ 90 # should be passed in as a string.
239
+ 91 ValidInput = str | int | list[int]
240
+ 92
241
+ 93
242
+ 94 # RuleRefs should never be exposed to the end user.
243
+ 95 ResolvedRule = RuleCharExclude | RuleChar | RuleEnd
244
+ 96
245
+ 97 if TYPE_CHECKING:
246
+ 98 from .graph_pointer import GraphPointer
247
+ 99
248
+ 100 ResolvedGraphPointer = GraphPointer[ResolvedRule]
249
+ ════ gbnf/grammar_graph/graph.py ════
250
+ 1 from __future__ import annotations
251
+ 2
252
+ 3 from collections.abc import Iterable
253
+ 4 from typing import TYPE_CHECKING
254
+ 5
255
+ 6 from .pointers import Pointers
256
+ 7
257
+ 8 if TYPE_CHECKING:
258
+ 9 from .grammar_graph_types import (
259
+ 10 ResolvedGraphPointer,
260
+ 11 UnresolvedRule,
261
+ 12 ValidInput,
262
+ 13 )
263
+ 14
264
+ 15
265
+ 16 from collections import OrderedDict
266
+ 17
267
+ 18 from ..utils.errors import InputParseError
268
+ 19 from ..utils.is_point_in_range import is_point_in_range
269
+ 20 from .colorize import colorize
270
+ 21 from .get_input_as_code_points import get_input_as_code_points
271
+ 22 from .get_serialized_rule_key import get_serialized_rule_key
272
+ 23 from .graph_node import GraphNode
273
+ 24 from .graph_pointer import GraphPointer
274
+ 25 from .rule_ref import RuleRef
275
+ 26 from .type_guards import (
276
+ 27 is_range,
277
+ 28 is_rule_char,
278
+ 29 is_rule_char_exclude,
279
+ 30 is_rule_end,
280
+ 31 is_rule_ref,
281
+ 32 )
282
+ 33
283
+ 34 RootNode = dict[int, GraphNode]
284
+ 35
285
+ 36
286
+ 37 class Graph:
287
+ 38 __roots__: OrderedDict[int, RootNode]
288
+ 39 grammar: str
289
+ 40 __rootNode__: RootNode | None
290
+ 41 previous_code_points: list[int]
291
+ 42
292
+ 43 def __init__(
293
+ 44 self,
294
+ 45 grammar: str,
295
+ 46 stacked_rules: list[list[list[UnresolvedRule]]],
296
+ 47 root_id: int,
297
+ 48 ):
298
+ 49 self.__roots__ = OrderedDict()
299
+ 50 self.grammar = grammar
300
+ 51 self.previous_code_points = []
301
+ 52 rule_refs: list[RuleRef] = []
302
+ 53 unique_rules: dict[str, UnresolvedRule] = {}
303
+ 54
304
+ 55 for stack_id in range(len(stacked_rules)):
305
+ 56 stack = stacked_rules[stack_id]
306
+ 57 nodes: dict[int, GraphNode] = {}
307
+ 58 for path_id in range(len(stack)):
308
+ 59 path = stack[path_id]
309
+ 60 node: GraphNode | None = None
310
+ 61 for step_id in range(len(path) - 1, -1, -1):
311
+ 62 next_node: GraphNode | None = node
312
+ 63 rule = stack[path_id][step_id]
313
+ 64 unique_rules[get_serialized_rule_key(rule)] = rule
314
+ 65 if is_rule_ref(rule):
315
+ 66 rule_refs.append(rule)
316
+ 67 # rules coming in may be identical but have different references.
317
+ 68 # here, we ensure we always use the same reference for an identical rule.
318
+ 69 # this makes future comparisons easier.
319
+ 70 unique_rule = unique_rules.get(get_serialized_rule_key(rule))
320
+ 71 if unique_rule is None:
321
+ 72 raise ValueError("Could not get unique rule")
322
+ 73 node = GraphNode(
323
+ 74 unique_rule,
324
+ 75 {
325
+ 76 "stackId": stack_id,
326
+ 77 "pathId": path_id,
327
+ 78 "stepId": step_id,
328
+ 79 },
329
+ 80 next_node,
330
+ 81 )
331
+ 82
332
+ 83 if node is None:
333
+ 84 raise ValueError("Could not get node")
334
+ 85 nodes[path_id] = node
335
+ 86 self.__roots__[stack_id] = nodes
336
+ 87
337
+ 88 root_node = self.__roots__.get(root_id)
338
+ 89 if root_node is None:
339
+ 90 raise ValueError(f"Root node not found for value: {root_id}")
340
+ 91 self.__rootNode__ = root_node
341
+ 92
342
+ 93 for rule_ref in rule_refs:
343
+ 94 referenced_nodes = set()
344
+ 95 referenced_nodes.update(self.__get_root_node__(rule_ref.value).values())
345
+ 96 rule_ref.nodes = referenced_nodes
346
+ 97
347
+ 98 def __get_root_node__(self, value: int) -> RootNode:
348
+ 99 root_node = self.__roots__.get(value)
349
+ 100 if root_node is None:
350
+ 101 raise ValueError(f"Root node not found for value: {value}")
351
+ 102 return root_node
352
+ 103
353
+ 104 def __get_initial_pointers__(self) -> Pointers:
354
+ 105 pointers = Pointers()
355
+ 106
356
+ 107 root_node = self.__rootNode__
357
+ 108 if root_node is None:
358
+ 109 raise ValueError("Root node is not defined")
359
+ 110
360
+ 111 for node, parent in self.__fetch_nodes_for_root_node__(root_node):
361
+ 112 pointer = GraphPointer(node, parent)
362
+ 113 for resolvedPointer in self.__resolve_pointer__(pointer):
363
+ 114 pointers.add(resolvedPointer)
364
+ 115 return pointers
365
+ 116
366
+ 117 def __set_valid__(self, pointers: list[GraphPointer], valid: bool):
367
+ 118 for pointer in pointers:
368
+ 119 pointer.valid = valid
369
+ 120
370
+ 121 def __parse__(self, current_pointers: Pointers, code_point: int) -> Pointers:
371
+ 122 for rule, graph_pointers in self.__iterate_over_pointers__(current_pointers):
372
+ 123 if is_rule_char(rule):
373
+ 124 valid = False
374
+ 125 for possible_code_point in rule.value:
375
+ 126 if valid is True:
376
+ 127 pass
377
+ 128 elif is_range(possible_code_point):
378
+ 129 if is_point_in_range(code_point, possible_code_point):
379
+ 130 valid = True
380
+ 131 elif code_point == possible_code_point:
381
+ 132 valid = True
382
+ 133 self.__set_valid__(graph_pointers, valid)
383
+ 134
384
+ 135 elif is_rule_char_exclude(rule):
385
+ 136 valid = True
386
+ 137 for possible_code_point in rule.value:
387
+ 138 if valid is False:
388
+ 139 pass
389
+ 140 elif is_range(possible_code_point):
390
+ 141 if is_point_in_range(code_point, possible_code_point):
391
+ 142 valid = False
392
+ 143 else:
393
+ 144 if code_point == possible_code_point:
394
+ 145 valid = False
395
+ 146 self.__set_valid__(graph_pointers, valid)
396
+ 147
397
+ 148 elif not is_rule_end(rule):
398
+ 149 raise ValueError(f"Unsupported rule: {rule}")
399
+ 150
400
+ 151 # a pointer's id is the sum of its node's id and its parent's id chain.
401
+ 152 # if two pointers share the same id, it means they point to the same node and have identical parent chains.
402
+ 153 # for the purposes of walking the graph, we only need to keep one of them.
403
+ 154 next_pointers = Pointers()
404
+ 155 for current_pointer in current_pointers:
405
+ 156 for unresolved_next_pointer in current_pointer.fetch_next():
406
+ 157 for resolved_next_pointer in self.__resolve_pointer__(
407
+ 158 unresolved_next_pointer,
408
+ 159 ):
409
+ 160 next_pointers.add(resolved_next_pointer)
410
+ 161 return next_pointers
411
+ 162
412
+ 163 def __resolve_pointer__(
413
+ 164 self,
414
+ 165 unresolved_pointer: GraphPointer,
415
+ 166 ) -> Iterable[ResolvedGraphPointer]:
416
+ 167 for resolved_pointer in unresolved_pointer.resolve():
417
+ 168 if is_rule_ref(resolved_pointer.node.rule):
418
+ 169 raise ValueError(
419
+ 170 "Encountered a reference rule when building pointers to the graph",
420
+ 171 )
421
+ 172 if (
422
+ 173 is_rule_end(resolved_pointer.node.rule)
423
+ 174 and resolved_pointer.parent is not None
424
+ 175 ):
425
+ 176 raise ValueError(
426
+ 177 "Encountered an ending rule with a parent when building pointers to the graph",
427
+ 178 )
428
+ 179 yield resolved_pointer
429
+ 180
430
+ 181 def add(self, src: ValidInput, pointers: Pointers | None = None) -> Pointers:
431
+ 182 if not isinstance(src, str):
432
+ 183 raise ValueError("src must be a string in graph.add")
433
+ 184 pointers = pointers or self.__get_initial_pointers__()
434
+ 185
435
+ 186 code_points = get_input_as_code_points(src)
436
+ 187 for code_point in code_points:
437
+ 188 if type(code_point) is not int:
438
+ 189 raise ValueError("code_point must be an integer!")
439
+ 190
440
+ 191 for code_point_pos in range(len(code_points)):
441
+ 192 code_point = code_points[code_point_pos]
442
+ 193 pointers = self.__parse__(pointers, code_point)
443
+ 194 if len(pointers) == 0:
444
+ 195 raise InputParseError(
445
+ 196 code_points,
446
+ 197 code_point_pos,
447
+ 198 self.previous_code_points,
448
+ 199 )
449
+ 200 self.previous_code_points.extend(code_points)
450
+ 201 return pointers
451
+ 202
452
+ 203 # generator that yields either the node, or if a reference rule, the referenced node
453
+ 204 # we need these function, as distinct from leveraging the logic in GraphPointer,
454
+ 205 # because that needs a rule ref with already defined nodes; this function is used to _set_ those nodes
455
+ 206 def __fetch_nodes_for_root_node__(
456
+ 207 self,
457
+ 208 root_nodes: dict[int, GraphNode],
458
+ 209 parent: GraphPointer | None = None,
459
+ 210 ) -> Iterable[tuple[GraphNode, GraphPointer | None]]:
460
+ 211 for node in root_nodes.values():
461
+ 212 if is_rule_ref(node.rule):
462
+ 213 yield from self.__fetch_nodes_for_root_node__(
463
+ 214 self.__get_root_node__(node.rule.value),
464
+ 215 GraphPointer(node, parent),
465
+ 216 )
466
+ 217 else:
467
+ 218 yield node, parent
468
+ 219
469
+ 220 def print(self, pointers: Pointers | None = None, colors: bool = False) -> str:
470
+ 221 nodes: list[list[GraphNode]] = [
471
+ 222 list(root_node.values()) for root_node in self.__roots__.values()
472
+ 223 ]
473
+ 224 if pointers is None:
474
+ 225 pointers = Pointers()
475
+ 226 graph_view: list[str] = []
476
+ 227 for root_node in nodes:
477
+ 228 for node in root_node:
478
+ 229 graph_view.extend(
479
+ 230 [
480
+ 231 node.print(
481
+ 232 {
482
+ 233 "pointers": pointers,
483
+ 234 "show_position": True,
484
+ 235 "colorize": colorize if colors else lambda s, _: str(s),
485
+ 236 },
486
+ 237 ),
487
+ 238 ],
488
+ 239 )
489
+ 240
490
+ 241 return "\n".join(graph_view)
491
+ 242
492
+ 243 def __iterate_over_pointers__(
493
+ 244 self,
494
+ 245 pointers: Pointers,
495
+ 246 ) -> Iterable[tuple[UnresolvedRule, list[GraphPointer]]]:
496
+ 247 seen_rules: OrderedDict[UnresolvedRule, list[GraphPointer]] = OrderedDict()
497
+ 248 for pointer in pointers:
498
+ 249 rule = pointer.rule
499
+ 250 if is_rule_ref(rule):
500
+ 251 raise ValueError("Encountered a reference rule in the graph")
501
+ 252
502
+ 253 seen_rule = seen_rules.get(rule)
503
+ 254 if seen_rule is None:
504
+ 255 seen_rule = [pointer]
505
+ 256 seen_rules[rule] = seen_rule
506
+ 257 seen_rule.append(pointer)
507
+ 258
508
+ 259 yield from seen_rules.items()
509
+ ════ gbnf/grammar_graph/graph_node.py ════
510
+ 1 from __future__ import annotations
511
+ 2
512
+ 3 from typing import Generic, TypedDict, TypeVar
513
+ 4
514
+ 5 from .grammar_graph_types import PrintOpts, UnresolvedRule
515
+ 6 from .print import print_graph_node
516
+ 7 from .rule_ref import RuleRef
517
+ 8
518
+ 9
519
+ 10 class GraphNodeMeta(TypedDict):
520
+ 11 stackId: int
521
+ 12 pathId: int
522
+ 13 stepId: int
523
+ 14
524
+ 15
525
+ 16 T = TypeVar("T", bound=UnresolvedRule)
526
+ 17
527
+ 18
528
+ 19 class GraphNode(Generic[T]):
529
+ 20 rule: T
530
+ 21 next: GraphNode | None
531
+ 22 meta: GraphNodeMeta
532
+ 23 __id__: str | None = None
533
+ 24
534
+ 25 def __init__(
535
+ 26 self,
536
+ 27 rule: T,
537
+ 28 meta: GraphNodeMeta | None,
538
+ 29 next_node: GraphNode | None = None,
539
+ 30 ):
540
+ 31 self.rule = rule
541
+ 32 if meta is None:
542
+ 33 raise ValueError("Meta is undefined")
543
+ 34 self.meta = meta
544
+ 35 self.next = next_node
545
+ 36
546
+ 37 @property
547
+ 38 def id(self) -> str:
548
+ 39 if self.__id__ is None:
549
+ 40 self.__id__ = (
550
+ 41 f"{self.meta['stackId']},{self.meta['pathId']},{self.meta['stepId']}"
551
+ 42 )
552
+ 43 return self.__id__
553
+ 44
554
+ 45 def print(self, opts: PrintOpts) -> str:
555
+ 46 return print_graph_node(self)(opts)
556
+ 47
557
+ 48 def __repr__(self):
558
+ 49 return f"<GraphNode {id(self)} {self.rule}>"
559
+ 50
560
+ 51
561
+ 52 GraphNodeRuleRef = GraphNode[RuleRef]
562
+ ════ gbnf/grammar_graph/graph_pointer.py ════
563
+ 1 from __future__ import annotations
564
+ 2
565
+ 3 from typing import TYPE_CHECKING, Generic, TypeVar
566
+ 4
567
+ 5 from .grammar_graph_types import PrintOpts, UnresolvedRule
568
+ 6 from .graph_node import GraphNode
569
+ 7 from .print import print_graph_pointer
570
+ 8 from .type_guards import (
571
+ 9 is_graph_pointer_rule_char,
572
+ 10 is_graph_pointer_rule_char_exclude,
573
+ 11 is_graph_pointer_rule_end,
574
+ 12 is_graph_pointer_rule_ref,
575
+ 13 is_rule_end,
576
+ 14 )
577
+ 15
578
+ 16 if TYPE_CHECKING:
579
+ 17 from .graph_node import GraphNode
580
+ 18
581
+ 19 T = TypeVar("T", bound=UnresolvedRule)
582
+ 20
583
+ 21 GraphPointerKey = str
584
+ 22
585
+ 23
586
+ 24 class GraphPointer(Generic[T]):
587
+ 25 node: GraphNode[T]
588
+ 26 parent: GraphPointer | None = None
589
+ 27 id: str
590
+ 28 __valid__: bool | None = None
591
+ 29
592
+ 30 def __init__(self, node: GraphNode[T], parent: GraphPointer | None = None):
593
+ 31 if node is None:
594
+ 32 raise ValueError("Node is undefined")
595
+ 33 self.node = node
596
+ 34 self.parent = parent
597
+ 35 self.id = f"{parent.id}-{node.id}" if parent else node.id
598
+ 36
599
+ 37 @property
600
+ 38 def rule(self) -> T:
601
+ 39 return self.node.rule
602
+ 40
603
+ 41 @property
604
+ 42 def valid(self) -> bool | None:
605
+ 43 return self.__valid__
606
+ 44
607
+ 45 @valid.setter
608
+ 46 def valid(self, valid: bool) -> None:
609
+ 47 self.__valid__ = valid
610
+ 48
611
+ 49 def print(self, opts: PrintOpts):
612
+ 50 return print_graph_pointer(self)(opts)
613
+ 51
614
+ 52 def resolve(self, resolved=False):
615
+ 53 """
616
+ 54 Resolve the graph pointer.
617
+ 55
618
+ 56 Args:
619
+ 57 resolved (bool, optional): Whether the pointer has already been resolved. Defaults to False.
620
+ 58
621
+ 59 Yields:
622
+ 60 ResolvedGraphPointer: The resolved graph pointer.
623
+ 61 """
624
+ 62 if is_graph_pointer_rule_ref(self):
625
+ 63 if resolved:
626
+ 64 if not self.node.next:
627
+ 65 raise ValueError(f"No next node: {self.node}")
628
+ 66 yield from GraphPointer(self.node.next, self.parent).resolve()
629
+ 67 else:
630
+ 68 for node in self.node.rule.nodes:
631
+ 69 yield from GraphPointer(node, self).resolve()
632
+ 70 elif is_graph_pointer_rule_end(self):
633
+ 71 if not self.parent:
634
+ 72 yield self
635
+ 73 else:
636
+ 74 yield from self.parent.resolve(True)
637
+ 75 elif is_graph_pointer_rule_char(self) or is_graph_pointer_rule_char_exclude(
638
+ 76 self,
639
+ 77 ):
640
+ 78 yield self
641
+ 79 else:
642
+ 80 raise ValueError(f"Unknown rule: {self.node.rule}")
643
+ 81
644
+ 82 def fetch_next(self):
645
+ 83 """
646
+ 84 Fetch the next resolved graph pointer.
647
+ 85
648
+ 86 Yields:
649
+ 87 ResolvedGraphPointer: The next resolved graph pointer.
650
+ 88 """
651
+ 89 # If this pointer is invalid, then we don't return any new pointers
652
+ 90 if not self.valid:
653
+ 91 return
654
+ 92
655
+ 93 # If this pointer is an end node, we return the parent's next node.
656
+ 94 # If no parent exists, we return nothing, since it's the end of the line.
657
+ 95 if is_rule_end(self.node.rule):
658
+ 96 if self.parent:
659
+ 97 yield from self.parent.fetch_next()
660
+ 98 else:
661
+ 99 if not self.node.next:
662
+ 100 raise ValueError(f"No next node: {self.node}")
663
+ 101 pointer = GraphPointer(self.node.next, self.parent)
664
+ 102 yield from pointer.resolve()
665
+ 103
666
+ 104 def __repr__(self):
667
+ 105 return f"<GraphPointer {id(self)} {self.node}>"
668
+ ════ gbnf/grammar_graph/parse_state.py ════
669
+ 1 from __future__ import annotations
670
+ 2
671
+ 3 from collections.abc import Iterable
672
+ 4 from typing import TYPE_CHECKING
673
+ 5
674
+ 6 from .grammar_graph_types import Rule
675
+ 7 from .pointers import Pointers
676
+ 8
677
+ 9 if TYPE_CHECKING:
678
+ 10 from .grammar_graph_types import ResolvedRule
679
+ 11 from .graph import Graph
680
+ 12
681
+ 13 import json
682
+ 14
683
+ 15
684
+ 16 class CustomJSONEncoder(json.JSONEncoder):
685
+ 17 def default(self, o):
686
+ 18 if isinstance(o, Rule):
687
+ 19 return o
688
+ 20 return super().default(o)
689
+ 21
690
+ 22
691
+ 23 class ParseState:
692
+ 24 __graph__: Graph
693
+ 25 __pointers__: Pointers
694
+ 26
695
+ 27 def __init__(self, graph: Graph, pointers: Pointers):
696
+ 28 self.__graph__ = graph
697
+ 29 self.__pointers__ = pointers
698
+ 30
699
+ 31 def __call__(self, text: str) -> ParseState:
700
+ 32 return self.add(text)
701
+ 33
702
+ 34 def __iter__(self) -> Iterable[ResolvedRule]:
703
+ 35 yield from self.rules()
704
+ 36
705
+ 37 def rules(self) -> Iterable[ResolvedRule]:
706
+ 38 rules = set()
707
+ 39 for pointer in self.__pointers__:
708
+ 40 rule = pointer.rule
709
+ 41 key = json.dumps(rule.__dict__, cls=CustomJSONEncoder)
710
+ 42 if key not in rules:
711
+ 43 rules.add(key)
712
+ 44 yield rule
713
+ 45
714
+ 46 def add(self, text: str) -> ParseState:
715
+ 47 if not isinstance(text, str):
716
+ 48 raise ValueError("input text must be of type string")
717
+ 49 pointers = self.__graph__.add(text, self.__pointers__)
718
+ 50 return ParseState(self.__graph__, pointers)
719
+ 51
720
+ 52 def __add__(self, text: str) -> ParseState:
721
+ 53 return self.add(text)
722
+ 54
723
+ 55 @property
724
+ 56 def size(self) -> int:
725
+ 57 return len(list(self.rules()))
726
+ 58
727
+ 59 @property
728
+ 60 def grammar(self) -> str:
729
+ 61 return self.__graph__.grammar
730
+ ════ gbnf/grammar_graph/pointers.py ════
731
+ 1 from collections import OrderedDict
732
+ 2
733
+ 3 from .graph_pointer import GraphPointer
734
+ 4
735
+ 5
736
+ 6 class Pointers:
737
+ 7 __pointers__: OrderedDict[int, GraphPointer]
738
+ 8
739
+ 9 def __init__(self, *pointers: GraphPointer):
740
+ 10 self.__pointers__ = OrderedDict()
741
+ 11 for pointer in pointers:
742
+ 12 self.add(pointer)
743
+ 13
744
+ 14 def __repr__(self):
745
+ 15 return f"<Pointers {id(self)} {[p.node.rule for p in self]}>"
746
+ 16
747
+ 17 def add(self, pointer):
748
+ 18 self.__pointers__[pointer.id] = pointer
749
+ 19
750
+ 20 def __iter__(self):
751
+ 21 yield from self.__pointers__.values()
752
+ 22
753
+ 23 def __len__(self):
754
+ 24 return len(self.__pointers__)
755
+ ════ gbnf/grammar_graph/print.py ════
756
+ 1 from __future__ import annotations
757
+ 2
758
+ 3 from collections.abc import Callable
759
+ 4 from typing import TYPE_CHECKING
760
+ 5
761
+ 6 from .colorize import Color
762
+ 7 from .get_parent_stack_id import get_parent_stack_id
763
+ 8
764
+ 9 if TYPE_CHECKING:
765
+ 10 from .grammar_graph_types import PrintOpts
766
+ 11 from .graph_node import GraphNode
767
+ 12 from .graph_pointer import GraphPointer
768
+ 13
769
+ 14 from .type_guards import is_range, is_rule_char, is_rule_ref
770
+ 15
771
+ 16
772
+ 17 def print_graph_pointer(pointer: GraphPointer) -> Callable[[PrintOpts], str]:
773
+ 18 def print_graph_pointer_inner(opts: PrintOpts) -> str:
774
+ 19 col = opts["colorize"]
775
+ 20 return col(
776
+ 21 f"*{get_parent_stack_id(pointer, col)}",
777
+ 22 Color.RED,
778
+ 23 )
779
+ 24
780
+ 25 return print_graph_pointer_inner
781
+ 26
782
+ 27
783
+ 28 def print_graph_node(node: GraphNode) -> Callable[[PrintOpts], str]:
784
+ 29 def print_graph_node_inner(opts: PrintOpts) -> str:
785
+ 30 pointers = opts.get("pointers", set())
786
+ 31 col = opts["colorize"]
787
+ 32 show_position = opts.get("show_position", False)
788
+ 33 rule = node.rule
789
+ 34 parts: list[str] = []
790
+ 35 if show_position:
791
+ 36 parts.extend(
792
+ 37 [col("{", Color.BLUE), col(node.id, Color.GRAY), col("}", Color.BLUE)],
793
+ 38 )
794
+ 39
795
+ 40 if is_rule_char(rule):
796
+ 41 parts.extend(
797
+ 42 [
798
+ 43 col("[", Color.GRAY),
799
+ 44 col(
800
+ 45 "".join(
801
+ 46 [
802
+ 47 (
803
+ 48 "".join(
804
+ 49 [col(get_char(val), Color.YELLOW) for val in v],
805
+ 50 )
806
+ 51 if is_range(v)
807
+ 52 else get_char(v)
808
+ 53 )
809
+ 54 for v in rule.value
810
+ 55 ],
811
+ 56 ),
812
+ 57 Color.YELLOW,
813
+ 58 ),
814
+ 59 col("]", Color.GRAY),
815
+ 60 ],
816
+ 61 )
817
+ 62
818
+ 63 elif is_rule_ref(rule):
819
+ 64 parts.extend(
820
+ 65 [
821
+ 66 col("Ref(", Color.GRAY),
822
+ 67 col(rule.value, Color.GREEN),
823
+ 68 col(")", Color.GRAY),
824
+ 69 ],
825
+ 70 )
826
+ 71
827
+ 72 else:
828
+ 73 parts.append(col(rule.type, Color.YELLOW))
829
+ 74
830
+ 75 if pointers:
831
+ 76 for pointer in pointers:
832
+ 77 pointer_parts: list[str] = []
833
+ 78 if pointer.node == node:
834
+ 79 pointer_parts.append(pointer.print(opts))
835
+ 80
836
+ 81 if len(pointer_parts) > 0:
837
+ 82 parts.extend(
838
+ 83 [
839
+ 84 col("[", Color.GRAY),
840
+ 85 col("".join(pointer_parts), Color.YELLOW),
841
+ 86 col("]", Color.GRAY),
842
+ 87 ],
843
+ 88 )
844
+ 89
845
+ 90 parts_to_return = [
846
+ 91 "".join(parts),
847
+ 92 ]
848
+ 93 if node.next:
849
+ 94 parts_to_return.append(node.next.print(opts))
850
+ 95
851
+ 96 return col("-> ", Color.GRAY).join(parts_to_return)
852
+ 97
853
+ 98 return print_graph_node_inner
854
+ 99
855
+ 100
856
+ 101 def get_char(char_code: int) -> str:
857
+ 102 char = chr(char_code)
858
+ 103 if char == "\n":
859
+ 104 return "\\n"
860
+ 105 return char
861
+ ════ gbnf/grammar_graph/rule_ref.py ════
862
+ 1 # import type { GraphNode, } from "./graph-node.js";
863
+ 2 GraphNode = object
864
+ 3
865
+ 4
866
+ 5 class RuleRef:
867
+ 6 __nodes__: set[GraphNode] | None = None
868
+ 7 value: int
869
+ 8
870
+ 9 def __init__(self, value: int) -> None:
871
+ 10 self.value = value
872
+ 11
873
+ 12 @property
874
+ 13 def nodes(self) -> set[GraphNode]:
875
+ 14 if self.__nodes__ is None:
876
+ 15 raise ValueError("Nodes are not set")
877
+ 16 return self.__nodes__
878
+ 17
879
+ 18 @nodes.setter
880
+ 19 def nodes(self, nodes: set[GraphNode]) -> None:
881
+ 20 self.__nodes__ = nodes
882
+ 21
883
+ 22 def __eq__(self, other: object) -> bool:
884
+ 23 return isinstance(other, RuleRef) and self.value == other.value
885
+ ════ gbnf/grammar_graph/type_guards.py ════
886
+ 1 from __future__ import annotations
887
+ 2
888
+ 3 from collections.abc import Callable
889
+ 4 from typing import TYPE_CHECKING, Any, TypeGuard, TypeVar
890
+ 5
891
+ 6 from .grammar_graph_types import (
892
+ 7 RuleChar,
893
+ 8 RuleCharExclude,
894
+ 9 RuleEnd,
895
+ 10 UnresolvedRule,
896
+ 11 )
897
+ 12 from .rule_ref import RuleRef
898
+ 13
899
+ 14 if TYPE_CHECKING:
900
+ 15 from .graph_pointer import GraphPointer
901
+ 16
902
+ 17
903
+ 18 T = TypeVar("T")
904
+ 19
905
+ 20
906
+ 21 def type_guard(predicate: Callable[[Any], bool]) -> Callable[[Any], TypeGuard[T]]:
907
+ 22 def wrapper(value: Any) -> TypeGuard[T]:
908
+ 23 return predicate(value)
909
+ 24
910
+ 25 return wrapper
911
+ 26
912
+ 27
913
+ 28 @type_guard
914
+ 29 def is_rule(rule: Any) -> bool:
915
+ 30 return rule is not None and isinstance(
916
+ 31 rule,
917
+ 32 (RuleChar | RuleCharExclude | RuleEnd | RuleRef),
918
+ 33 )
919
+ 34
920
+ 35
921
+ 36 @type_guard
922
+ 37 def is_rule_ref(rule: UnresolvedRule) -> bool:
923
+ 38 return isinstance(rule, RuleRef)
924
+ 39
925
+ 40
926
+ 41 @type_guard
927
+ 42 def is_rule_end(rule: UnresolvedRule) -> bool:
928
+ 43 return rule is not None and isinstance(rule, RuleEnd) and isinstance(rule, RuleEnd)
929
+ 44
930
+ 45
931
+ 46 @type_guard
932
+ 47 def is_rule_char(rule: UnresolvedRule) -> bool:
933
+ 48 return (
934
+ 49 rule is not None and isinstance(rule, RuleChar) and isinstance(rule, RuleChar)
935
+ 50 )
936
+ 51
937
+ 52
938
+ 53 @type_guard
939
+ 54 def is_rule_char_exclude(rule: UnresolvedRule) -> bool:
940
+ 55 return rule is not None and isinstance(rule, RuleCharExclude)
941
+ 56
942
+ 57
943
+ 58 @type_guard
944
+ 59 def is_range(inpt: Any) -> bool:
945
+ 60 return (
946
+ 61 isinstance(inpt, list)
947
+ 62 and len(inpt) == 2
948
+ 63 and all(isinstance(n, int) for n in inpt)
949
+ 64 )
950
+ 65
951
+ 66
952
+ 67 @type_guard
953
+ 68 def is_graph_pointer_rule_ref(pointer: GraphPointer) -> bool:
954
+ 69 return is_rule_ref(pointer.rule)
955
+ 70
956
+ 71
957
+ 72 @type_guard
958
+ 73 def is_graph_pointer_rule_end(pointer: GraphPointer) -> bool:
959
+ 74 return is_rule_end(pointer.rule)
960
+ 75
961
+ 76
962
+ 77 @type_guard
963
+ 78 def is_graph_pointer_rule_char(pointer: GraphPointer) -> bool:
964
+ 79 return is_rule_char(pointer.rule)
965
+ 80
966
+ 81
967
+ 82 @type_guard
968
+ 83 def is_graph_pointer_rule_char_exclude(pointer: GraphPointer) -> bool:
969
+ 84 return is_rule_char_exclude(pointer.rule)
970
+ ════ gbnf/grammar_parser/__init__.py ════
971
+ ════ gbnf/grammar_parser/build_rule_stack.py ════
972
+ 1 import json
973
+ 2 from typing import cast
974
+ 3
975
+ 4 from ..grammar_graph.grammar_graph_types import (
976
+ 5 Range,
977
+ 6 RuleChar,
978
+ 7 RuleCharExclude,
979
+ 8 RuleEnd,
980
+ 9 UnresolvedRule,
981
+ 10 )
982
+ 11 from ..grammar_graph.rule_ref import RuleRef
983
+ 12 from ..grammar_graph.type_guards import is_range, is_rule_end
984
+ 13 from ..rules_builder.rules_builder_types import (
985
+ 14 InternalRuleDef,
986
+ 15 InternalRuleDefChar,
987
+ 16 InternalRuleDefCharAlt,
988
+ 17 InternalRuleDefCharNot,
989
+ 18 InternalRuleDefCharRngUpper,
990
+ 19 InternalRuleDefReference,
991
+ 20 is_rule_def_alt,
992
+ 21 is_rule_def_char,
993
+ 22 is_rule_def_char_alt,
994
+ 23 is_rule_def_char_not,
995
+ 24 is_rule_def_char_rng_upper,
996
+ 25 is_rule_def_end,
997
+ 26 is_rule_def_ref,
998
+ 27 )
999
+ 28
1000
+ 29
1001
+ 30 def make_char_rule(
1002
+ 31 rule_def: InternalRuleDefChar | InternalRuleDefCharNot,
1003
+ 32 ) -> RuleChar | RuleCharExclude:
1004
+ 33 value = cast(list[int | Range], rule_def.value)
1005
+ 34 if is_rule_def_char_not(rule_def):
1006
+ 35 return RuleCharExclude(value=value)
1007
+ 36 if is_rule_def_char(rule_def):
1008
+ 37 return RuleChar(value=value)
1009
+ 38
1010
+ 39 raise ValueError(f"Unsupported rule type for make_char_rule: {rule_def}")
1011
+ 40
1012
+ 41
1013
+ 42 def build_rule_stack(linear_rules: list[InternalRuleDef]) -> list[list[UnresolvedRule]]:
1014
+ 43 paths: list[UnresolvedRule] = []
1015
+ 44 stack: list[list[UnresolvedRule]] = []
1016
+ 45 idx = 0
1017
+ 46
1018
+ 47 while idx < len(linear_rules):
1019
+ 48 rule_def = linear_rules[idx]
1020
+ 49 if is_rule_def_char(rule_def) or is_rule_def_char_not(rule_def):
1021
+ 50 # this could be a single char, or a range, or a sequence of alts; we don't know until we step through it.
1022
+ 51 rule_def = (
1023
+ 52 cast(InternalRuleDefChar, rule_def)
1024
+ 53 if is_rule_def_char(rule_def)
1025
+ 54 else cast(InternalRuleDefCharNot, rule_def)
1026
+ 55 )
1027
+ 56 char_rule = make_char_rule(rule_def)
1028
+ 57 idx += 1
1029
+ 58 rule = linear_rules[idx] if idx < len(linear_rules) else None
1030
+ 59 while idx < len(linear_rules) and (
1031
+ 60 is_rule_def_char_rng_upper(rule) or is_rule_def_char_alt(rule)
1032
+ 61 ):
1033
+ 62 if is_rule_def_char_rng_upper(rule):
1034
+ 63 # previous rule value should be a number
1035
+ 64 prev_value = char_rule.value.pop()
1036
+ 65 if is_range(prev_value):
1037
+ 66 raise ValueError(
1038
+ 67 f"Unexpected range, expected a number but got an array: {json.dumps(prev_value)}",
1039
+ 68 )
1040
+ 69 if prev_value is None:
1041
+ 70 raise ValueError("Unexpected undefined value")
1042
+ 71
1043
+ 72 char_rule.value.append(
1044
+ 73 cast(
1045
+ 74 Range,
1046
+ 75 [prev_value, cast(InternalRuleDefCharRngUpper, rule).value],
1047
+ 76 ),
1048
+ 77 )
1049
+ 78 if is_rule_def_char_alt(rule):
1050
+ 79 rule = cast(InternalRuleDefCharAlt, rule)
1051
+ 80 char_rule.value.append(cast(int, rule.value))
1052
+ 81 idx += 1
1053
+ 82 rule = linear_rules[idx] if idx < len(linear_rules) else None
1054
+ 83 paths.append(char_rule)
1055
+ 84 else:
1056
+ 85 if is_rule_def_alt(rule_def):
1057
+ 86 if len(paths) == 0:
1058
+ 87 raise ValueError("Encountered alt without anything before it")
1059
+ 88 paths.append(RuleEnd())
1060
+ 89 stack.append(paths)
1061
+ 90 paths = []
1062
+ 91 elif is_rule_def_end(rule_def):
1063
+ 92 paths.append(RuleEnd())
1064
+ 93 elif is_rule_def_ref(rule_def):
1065
+ 94 paths.append(
1066
+ 95 RuleRef(cast(int, cast(InternalRuleDefReference, rule_def).value)),
1067
+ 96 )
1068
+ 97 elif is_rule_def_char_alt(rule_def):
1069
+ 98 raise ValueError(
1070
+ 99 f"Encountered char alt, should be handled by above block: {rule_def}",
1071
+ 100 )
1072
+ 101 else:
1073
+ 102 raise ValueError(f"Unsupported rule type: {rule_def}")
1074
+ 103 idx += 1
1075
+ 104
1076
+ 105 if not is_rule_end(paths[-1]):
1077
+ 106 paths.append(RuleEnd())
1078
+ 107
1079
+ 108 stack.append(paths)
1080
+ 109 return stack
1081
+ ════ gbnf/rules_builder/__init__.py ════
1082
+ 1 from ..utils.errors import GrammarParseError, InputParseError
1083
+ 2 from .rules_builder import RulesBuilder
1084
+ 3
1085
+ 4 __all__ = [
1086
+ 5 "GrammarParseError",
1087
+ 6 "InputParseError",
1088
+ 7 "RulesBuilder",
1089
+ 8 ]
1090
+ ════ gbnf/rules_builder/is_word_char.py ════
1091
+ 1 import re
1092
+ 2
1093
+ 3
1094
+ 4 def is_word_char(c: str) -> bool:
1095
+ 5 return re.search(r"[a-zA-Z]", c) is not None
1096
+ ════ gbnf/rules_builder/parse_char.py ════
1097
+ 1 from ..utils.errors import GrammarParseError
1098
+ 2
1099
+ 3
1100
+ 4 def parse_char(src: str, pos: int):
1101
+ 5 if pos >= len(src):
1102
+ 6 raise GrammarParseError(
1103
+ 7 src,
1104
+ 8 pos,
1105
+ 9 "Unexpected end of grammar input, failed to complete parse",
1106
+ 10 )
1107
+ 11
1108
+ 12 if src[pos] == "\\":
1109
+ 13 if src[pos + 1] == "x":
1110
+ 14 return (int(src[pos + 2 : pos + 4], 16), 4)
1111
+ 15 if src[pos + 1] == "u":
1112
+ 16 return (int(src[pos + 2 : pos + 6], 16), 6)
1113
+ 17 if src[pos + 1] == "U":
1114
+ 18 return (int(src[pos + 2 : pos + 10], 16), 10)
1115
+ 19 if src[pos + 1] in ["t", "r", "n"]:
1116
+ 20 return (ord(eval(f"'\\{src[pos + 1]}'")), 2)
1117
+ 21 if src[pos + 1] in ['"', "[", "]", "\\"]:
1118
+ 22 return (ord(src[pos + 1]), 2)
1119
+ 23 raise GrammarParseError(src, pos, f"Unknown escape at {src[pos]}")
1120
+ 24
1121
+ 25 return (ord(src[pos]), 1)
1122
+ ════ gbnf/rules_builder/parse_name.py ════
1123
+ 1 from ..utils.errors import GrammarParseError
1124
+ 2 from .is_word_char import is_word_char
1125
+ 3
1126
+ 4 PARSE_NAME_ERROR = "Failed to find a valid name"
1127
+ 5
1128
+ 6 VALID_NAME_SEPARATORS = [
1129
+ 7 "-",
1130
+ 8 "_",
1131
+ 9 ]
1132
+ 10
1133
+ 11
1134
+ 12 def parse_name(grammar: str, pos: int) -> str:
1135
+ 13 name = ""
1136
+ 14 while pos < len(grammar) and (
1137
+ 15 is_word_char(grammar[pos]) or grammar[pos] in VALID_NAME_SEPARATORS
1138
+ 16 ):
1139
+ 17 name += grammar[pos]
1140
+ 18 pos += 1
1141
+ 19 if not name:
1142
+ 20 raise GrammarParseError(grammar, pos, PARSE_NAME_ERROR)
1143
+ 21 return name
1144
+ ════ gbnf/rules_builder/parse_space.py ════
1145
+ 1 def parse_space(src: str, pos: int, newline_ok: bool) -> int:
1146
+ 2 while pos < len(src) and (
1147
+ 3 src[pos] == " "
1148
+ 4 or src[pos] == "\t"
1149
+ 5 or src[pos] == "#"
1150
+ 6 or (newline_ok and (src[pos] == "\r" or src[pos] == "\n"))
1151
+ 7 ):
1152
+ 8 if src[pos] == "#":
1153
+ 9 while pos < len(src) and src[pos] not in ("\r", "\n"):
1154
+ 10 pos += 1
1155
+ 11 else:
1156
+ 12 pos += 1
1157
+ 13 return pos
1158
+ ════ gbnf/rules_builder/rules_builder.py ════
1159
+ 1 from time import perf_counter
1160
+ 2
1161
+ 3 from ..utils.errors import GrammarParseError
1162
+ 4 from .is_word_char import is_word_char
1163
+ 5 from .parse_char import parse_char
1164
+ 6 from .parse_name import parse_name
1165
+ 7 from .parse_space import parse_space
1166
+ 8 from .rules_builder_types import (
1167
+ 9 InternalRuleDef,
1168
+ 10 InternalRuleDefAlt,
1169
+ 11 InternalRuleDefChar,
1170
+ 12 InternalRuleDefCharAlt,
1171
+ 13 InternalRuleDefCharNot,
1172
+ 14 InternalRuleDefCharRngUpper,
1173
+ 15 InternalRuleDefEnd,
1174
+ 16 InternalRuleDefReference,
1175
+ 17 )
1176
+ 18 from .symbol_ids import SymbolIds
1177
+ 19
1178
+ 20
1179
+ 21 def get_out_elements(
1180
+ 22 type_of_rule: type[InternalRuleDef],
1181
+ 23 startchar_value: int,
1182
+ 24 ) -> InternalRuleDef:
1183
+ 25 if type_of_rule == InternalRuleDefChar:
1184
+ 26 return InternalRuleDefChar(value=[startchar_value])
1185
+ 27 if type_of_rule == InternalRuleDefCharNot:
1186
+ 28 return InternalRuleDefCharNot(value=[startchar_value])
1187
+ 29 if type_of_rule == InternalRuleDefCharRngUpper:
1188
+ 30 return InternalRuleDefCharRngUpper(value=startchar_value)
1189
+ 31 if type_of_rule == InternalRuleDefAlt:
1190
+ 32 return InternalRuleDefAlt()
1191
+ 33 if type_of_rule == InternalRuleDefEnd:
1192
+ 34 return InternalRuleDefEnd()
1193
+ 35 if type_of_rule == InternalRuleDefCharAlt:
1194
+ 36 return InternalRuleDefCharAlt(value=startchar_value)
1195
+ 37
1196
+ 38 raise ValueError(f"Invalid type: {type_of_rule}")
1197
+ 39
1198
+ 40
1199
+ 41 class RulesBuilder:
1200
+ 42 pos: int
1201
+ 43 symbol_ids: SymbolIds
1202
+ 44 rules: list[list[InternalRuleDef]]
1203
+ 45 src: str
1204
+ 46 start: float
1205
+ 47 time_limit: int
1206
+ 48
1207
+ 49 def __init__(self, src: str, limit: int = 1000):
1208
+ 50 self.pos = 0
1209
+ 51 self.symbol_ids = SymbolIds()
1210
+ 52 self.rules = []
1211
+ 53 self.src = src
1212
+ 54 self.start = perf_counter()
1213
+ 55 self.time_limit = limit
1214
+ 56 self.parse(src)
1215
+ 57
1216
+ 58 def parse(self, src: str) -> None:
1217
+ 59 self.pos = parse_space(src, 0, True)
1218
+ 60 while self.pos < len(src):
1219
+ 61 self.parse_rule(src)
1220
+ 62
1221
+ 63 # Validate the state to ensure that all rules are defined
1222
+ 64 for rule in self.rules:
1223
+ 65 for elem in rule:
1224
+ 66 if isinstance(elem, InternalRuleDefReference):
1225
+ 67 rule_exists = (
1226
+ 68 elem.value < len(self.rules) and len(self.rules[elem.value]) > 0
1227
+ 69 )
1228
+ 70 if not rule_exists:
1229
+ 71 missing_rule_name = self.symbol_ids.reverse_get(elem.value)
1230
+ 72 missing_rule_pos = self.symbol_ids.get_pos(missing_rule_name)
1231
+ 73
1232
+ 74 # Skip over the ::= and any whitespace
1233
+ 75 while missing_rule_pos < len(src) and (
1234
+ 76 src[missing_rule_pos] == ":"
1235
+ 77 or src[missing_rule_pos] == "="
1236
+ 78 or src[missing_rule_pos].isspace()
1237
+ 79 ):
1238
+ 80 missing_rule_pos += 1
1239
+ 81
1240
+ 82 raise GrammarParseError(
1241
+ 83 src,
1242
+ 84 missing_rule_pos,
1243
+ 85 f'Undefined rule identifier "{missing_rule_name}"',
1244
+ 86 )
1245
+ 87
1246
+ 88 def parse_rule(self, src: str) -> None:
1247
+ 89 name = parse_name(src, self.pos)
1248
+ 90 self.pos = parse_space(src, self.pos + len(name), False)
1249
+ 91 rule_id = self.get_symbol_id(name, len(name))
1250
+ 92
1251
+ 93 self.pos = parse_space(src, self.pos, True)
1252
+ 94 if not (
1253
+ 95 self.pos + 2 < len(src) # Ensure the position + 2 is within bounds
1254
+ 96 and src[self.pos] == ":"
1255
+ 97 and src[self.pos + 1] == ":"
1256
+ 98 and src[self.pos + 2] == "="
1257
+ 99 ):
1258
+ 100 raise GrammarParseError(src, self.pos, f"Expecting ::= at {self.pos}")
1259
+ 101 self.pos += 3
1260
+ 102 self.pos = parse_space(src, self.pos, True)
1261
+ 103
1262
+ 104 self.parse_alternates(name, rule_id)
1263
+ 105
1264
+ 106 # Check if self.pos is within the bounds of src before checking for a carriage return
1265
+ 107 if self.pos < len(src) and src[self.pos] == "\r":
1266
+ 108 self.pos += 2 if src[self.pos + 1] == "\n" else 1
1267
+ 109 elif self.pos < len(src) and src[self.pos] == "\n":
1268
+ 110 self.pos += 1
1269
+ 111 elif self.pos < len(src) and src[self.pos]:
1270
+ 112 raise GrammarParseError(
1271
+ 113 src,
1272
+ 114 self.pos,
1273
+ 115 f"Expecting newline or end at {self.pos}",
1274
+ 116 )
1275
+ 117 self.pos = parse_space(src, self.pos, True)
1276
+ 118
1277
+ 119 def get_symbol_id(self, src: str, length: int) -> int:
1278
+ 120 next_id = len(self.symbol_ids)
1279
+ 121 key = src[:length]
1280
+ 122 if key not in self.symbol_ids:
1281
+ 123 self.symbol_ids.set(key, next_id, self.pos)
1282
+ 124 return self.symbol_ids[key]
1283
+ 125
1284
+ 126 def generate_symbol_id(self, base_name: str) -> int:
1285
+ 127 next_id = len(self.symbol_ids)
1286
+ 128 self.symbol_ids.set(f"{base_name}_{next_id}", next_id, self.pos)
1287
+ 129 return next_id
1288
+ 130
1289
+ 131 def add_rule(self, rule_id: int, rule: list[InternalRuleDef]) -> None:
1290
+ 132 while len(self.rules) <= rule_id:
1291
+ 133 self.rules.append([])
1292
+ 134 self.rules[rule_id] = rule
1293
+ 135
1294
+ 136 def check_duration(self) -> None:
1295
+ 137 if perf_counter() - self.start > self.time_limit:
1296
+ 138 raise GrammarParseError(
1297
+ 139 self.src,
1298
+ 140 self.pos,
1299
+ 141 f"Duration of {self.time_limit} exceeded",
1300
+ 142 )
1301
+ 143
1302
+ 144 def parse_sequence(
1303
+ 145 self,
1304
+ 146 rule_name: str,
1305
+ 147 out_elements: list[InternalRuleDef],
1306
+ 148 depth: int = 0,
1307
+ 149 ) -> None:
1308
+ 150 is_nested = depth != 0
1309
+ 151 src = self.src
1310
+ 152 last_sym_start = len(out_elements)
1311
+ 153
1312
+ 154 while self.pos < len(src):
1313
+ 155 if src[self.pos] == '"':
1314
+ 156 self.pos += 1
1315
+ 157 last_sym_start = len(out_elements)
1316
+ 158 while src[self.pos] != '"':
1317
+ 159 self.check_duration()
1318
+ 160 value, inc_pos = parse_char(src, self.pos)
1319
+ 161 out_elements.append(
1320
+ 162 InternalRuleDefChar(
1321
+ 163 value=[value],
1322
+ 164 ),
1323
+ 165 )
1324
+ 166 self.pos += inc_pos
1325
+ 167 self.pos = parse_space(src, self.pos + 1, is_nested)
1326
+ 168 elif src[self.pos] == "[":
1327
+ 169 self.pos += 1
1328
+ 170 start_type: type[InternalRuleDef] = InternalRuleDefChar
1329
+ 171 if src[self.pos] == "^":
1330
+ 172 self.pos += 1
1331
+ 173 start_type = InternalRuleDefCharNot
1332
+ 174 last_sym_start = len(out_elements)
1333
+ 175 while src[self.pos] != "]":
1334
+ 176 self.check_duration()
1335
+ 177 type_: type[InternalRuleDef] = (
1336
+ 178 InternalRuleDefCharAlt
1337
+ 179 if last_sym_start < len(out_elements)
1338
+ 180 else start_type
1339
+ 181 )
1340
+ 182 startchar_value, inc_pos = parse_char(src, self.pos)
1341
+ 183 self.pos += inc_pos
1342
+ 184 out_elements.append(get_out_elements(type_, startchar_value))
1343
+ 185
1344
+ 186 if src[self.pos] == "-" and src[self.pos + 1] != "]":
1345
+ 187 self.pos += 1
1346
+ 188 endchar_value, inc_pos = parse_char(src, self.pos)
1347
+ 189 out_elements.append(
1348
+ 190 InternalRuleDefCharRngUpper(
1349
+ 191 value=endchar_value,
1350
+ 192 ),
1351
+ 193 )
1352
+ 194 self.pos += inc_pos
1353
+ 195 self.pos = parse_space(src, self.pos + 1, is_nested)
1354
+ 196 elif is_word_char(src[self.pos]):
1355
+ 197 name = parse_name(src, self.pos)
1356
+ 198 ref_rule_id = self.get_symbol_id(name, len(name))
1357
+ 199 self.pos += len(name)
1358
+ 200 self.pos = parse_space(src, self.pos, is_nested)
1359
+ 201
1360
+ 202 last_sym_start = len(out_elements)
1361
+ 203 out_elements.append(
1362
+ 204 InternalRuleDefReference(
1363
+ 205 value=ref_rule_id,
1364
+ 206 ),
1365
+ 207 )
1366
+ 208 elif src[self.pos] == "(":
1367
+ 209 self.pos = parse_space(src, self.pos + 1, True)
1368
+ 210 sub_rule_id = self.generate_symbol_id(rule_name)
1369
+ 211 self.parse_alternates(rule_name, sub_rule_id, depth + 1)
1370
+ 212 last_sym_start = len(out_elements)
1371
+ 213 out_elements.append(
1372
+ 214 InternalRuleDefReference(
1373
+ 215 value=sub_rule_id,
1374
+ 216 ),
1375
+ 217 )
1376
+ 218 if src[self.pos] != ")":
1377
+ 219 raise GrammarParseError(
1378
+ 220 src,
1379
+ 221 self.pos,
1380
+ 222 f"Expecting ')' at {self.pos}",
1381
+ 223 )
1382
+ 224 self.pos = parse_space(src, self.pos + 1, is_nested)
1383
+ 225 elif src[self.pos] in "*+?":
1384
+ 226 if last_sym_start == len(out_elements):
1385
+ 227 raise GrammarParseError(
1386
+ 228 src,
1387
+ 229 self.pos,
1388
+ 230 f"Expecting preceding item to */+/? at {self.pos}",
1389
+ 231 )
1390
+ 232 sub_rule_id = self.generate_symbol_id(rule_name)
1391
+ 233 sub_rule = out_elements[last_sym_start:]
1392
+ 234 if src[self.pos] in "*+":
1393
+ 235 sub_rule.append(
1394
+ 236 InternalRuleDefReference(
1395
+ 237 value=sub_rule_id,
1396
+ 238 ),
1397
+ 239 )
1398
+ 240 sub_rule.append(InternalRuleDefAlt())
1399
+ 241 if src[self.pos] == "+":
1400
+ 242 sub_rule.extend(out_elements[last_sym_start:])
1401
+ 243 sub_rule.append(InternalRuleDefEnd())
1402
+ 244 self.add_rule(sub_rule_id, sub_rule)
1403
+ 245 out_elements[last_sym_start:] = [
1404
+ 246 InternalRuleDefReference(
1405
+ 247 value=sub_rule_id,
1406
+ 248 ),
1407
+ 249 ]
1408
+ 250 self.pos = parse_space(src, self.pos + 1, is_nested)
1409
+ 251 else:
1410
+ 252 break
1411
+ 253
1412
+ 254 def parse_alternates(self, rule_name: str, rule_id: int, depth: int = 0) -> None:
1413
+ 255 src = self.src
1414
+ 256 rule = []
1415
+ 257 self.parse_sequence(rule_name, rule, depth)
1416
+ 258 # Ensure that self.pos is within bounds before checking src[self.pos]
1417
+ 259 while self.pos < len(src) and src[self.pos] == "|":
1418
+ 260 self.check_duration()
1419
+ 261 rule.append(InternalRuleDefAlt())
1420
+ 262 self.pos = parse_space(src, self.pos + 1, True)
1421
+ 263 self.parse_sequence(rule_name, rule, depth)
1422
+ 264 rule.append(InternalRuleDefEnd())
1423
+ 265 self.add_rule(rule_id, rule)
1424
+ ════ gbnf/rules_builder/rules_builder_types.py ════
1425
+ 1 from dataclasses import dataclass, field
1426
+ 2 from typing import Any
1427
+ 3
1428
+ 4 from ..utils.validate_non_empty import validate_non_empty
1429
+ 5
1430
+ 6
1431
+ 7 @dataclass
1432
+ 8 class InternalRuleDefWithNumericValue:
1433
+ 9 value: int
1434
+ 10
1435
+ 11
1436
+ 12 @dataclass
1437
+ 13 class InternalBase:
1438
+ 14 def __eq__(self, other):
1439
+ 15 return isinstance(other, self.__class__)
1440
+ 16
1441
+ 17
1442
+ 18 @dataclass
1443
+ 19 class InternalBaseWithValue:
1444
+ 20 value: Any
1445
+ 21
1446
+ 22 def __eq__(self, other):
1447
+ 23 return isinstance(other, self.__class__) and self.value == other.value
1448
+ 24
1449
+ 25
1450
+ 26 @dataclass
1451
+ 27 class InternalBaseWithInt(InternalBaseWithValue):
1452
+ 28 value: int
1453
+ 29
1454
+ 30
1455
+ 31 @dataclass
1456
+ 32 class InternalBaseWithListOfInts(InternalBaseWithValue):
1457
+ 33 value: list[int] = field(
1458
+ 34 default_factory=list, metadata={"validate": validate_non_empty},
1459
+ 35 )
1460
+ 36
1461
+ 37 def __post_init__(self):
1462
+ 38 self.value = self.value.copy()
1463
+ 39
1464
+ 40
1465
+ 41 @dataclass
1466
+ 42 class InternalRuleDefChar(InternalBaseWithListOfInts):
1467
+ 43 pass
1468
+ 44
1469
+ 45
1470
+ 46 @dataclass
1471
+ 47 class InternalRuleDefCharAlt(InternalBaseWithInt):
1472
+ 48 pass
1473
+ 49
1474
+ 50
1475
+ 51 class InternalRuleDefAlt(InternalBase):
1476
+ 52 pass
1477
+ 53
1478
+ 54
1479
+ 55 @dataclass
1480
+ 56 class InternalRuleDefCharNot(InternalBaseWithListOfInts):
1481
+ 57 pass
1482
+ 58
1483
+ 59
1484
+ 60 @dataclass
1485
+ 61 class InternalRuleDefCharRngUpper(InternalBaseWithInt):
1486
+ 62 pass
1487
+ 63
1488
+ 64
1489
+ 65 @dataclass
1490
+ 66 class InternalRuleDefReference(InternalBaseWithInt):
1491
+ 67 pass
1492
+ 68
1493
+ 69
1494
+ 70 @dataclass
1495
+ 71 class InternalRuleDefEnd(InternalBase):
1496
+ 72 pass
1497
+ 73
1498
+ 74
1499
+ 75 @dataclass
1500
+ 76 class InternalRuleDefWithoutValue(InternalBase):
1501
+ 77 pass
1502
+ 78
1503
+ 79
1504
+ 80 InternalRuleDef = (
1505
+ 81 InternalRuleDefChar
1506
+ 82 | InternalRuleDefEnd
1507
+ 83 | InternalRuleDefReference
1508
+ 84 | InternalRuleDefCharNot
1509
+ 85 | InternalRuleDefWithNumericValue
1510
+ 86 | InternalRuleDefWithoutValue
1511
+ 87 | InternalRuleDefAlt
1512
+ 88 | InternalRuleDefCharRngUpper
1513
+ 89 | InternalRuleDefCharAlt
1514
+ 90 | InternalRuleDefCharAlt
1515
+ 91 )
1516
+ 92
1517
+ 93 InternalRuleDefCharOrAltChar = InternalRuleDefChar | InternalRuleDefCharAlt
1518
+ 94
1519
+ 95 SymbolIds = dict[str, int]
1520
+ 96
1521
+ 97
1522
+ 98 def is_rule_def_alt(rule):
1523
+ 99 return isinstance(rule, InternalRuleDefAlt)
1524
+ 100
1525
+ 101
1526
+ 102 def is_rule_def_ref(rule):
1527
+ 103 return isinstance(rule, InternalRuleDefReference)
1528
+ 104
1529
+ 105
1530
+ 106 def is_rule_def_end(rule):
1531
+ 107 return isinstance(rule, InternalRuleDefEnd)
1532
+ 108
1533
+ 109
1534
+ 110 def is_rule_def_char(rule):
1535
+ 111 return isinstance(rule, InternalRuleDefChar)
1536
+ 112
1537
+ 113
1538
+ 114 def is_rule_def_char_not(rule):
1539
+ 115 return isinstance(rule, InternalRuleDefCharNot)
1540
+ 116
1541
+ 117
1542
+ 118 def is_rule_def_char_alt(rule):
1543
+ 119 return isinstance(rule, InternalRuleDefCharAlt)
1544
+ 120
1545
+ 121
1546
+ 122 def is_rule_def_char_rng_upper(rule):
1547
+ 123 return isinstance(rule, InternalRuleDefCharRngUpper)
1548
+ ════ gbnf/rules_builder/symbol_ids.py ════
1549
+ 1 class SymbolIds:
1550
+ 2 __map__: dict[str, int]
1551
+ 3 __pos__: dict[str, int]
1552
+ 4 __reverse_map__: dict[int, str]
1553
+ 5
1554
+ 6 def __init__(self):
1555
+ 7 self.__map__ = {}
1556
+ 8 self.__pos__ = {}
1557
+ 9 self.__reverse_map__ = {}
1558
+ 10
1559
+ 11 def items(self):
1560
+ 12 return self.__map__.items()
1561
+ 13
1562
+ 14 def __iter__(self):
1563
+ 15 return iter(self.__map__.items())
1564
+ 16
1565
+ 17 def __len__(self):
1566
+ 18 return len(self.__map__)
1567
+ 19
1568
+ 20 def __getitem__(self, key):
1569
+ 21 return self.__map__[key]
1570
+ 22
1571
+ 23 def set(self, key: str, value: int, pos: int):
1572
+ 24 self.__map__[key] = value
1573
+ 25 self.__reverse_map__[value] = key
1574
+ 26 self.__pos__[key] = pos
1575
+ 27
1576
+ 28 def __contains__(self, key: str):
1577
+ 29 return key in self.__map__
1578
+ 30
1579
+ 31 def reverse_get(self, key: int):
1580
+ 32 val = self.__reverse_map__.get(key)
1581
+ 33 if val is None:
1582
+ 34 raise ValueError(f"SymbolIds does not contain value: {key}")
1583
+ 35 return val
1584
+ 36
1585
+ 37 def get_pos(self, key: str):
1586
+ 38 val = self.__pos__.get(key)
1587
+ 39 if val is None:
1588
+ 40 raise ValueError(f"SymbolIds does not contain key: {key}")
1589
+ 41 return val
1590
+ ════ gbnf/utils/__init__.py ════
1591
+ ════ gbnf/utils/errors/__init__.py ════
1592
+ 1 from .grammar_parse_error import GrammarParseError
1593
+ 2 from .input_parse_error import InputParseError
1594
+ 3
1595
+ 4 __all__ = [
1596
+ 5 "GrammarParseError",
1597
+ 6 "InputParseError",
1598
+ 7 ]
1599
+ ════ gbnf/utils/errors/build_error_position.py ════
1600
+ 1 MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW = 3
1601
+ 2
1602
+ 3
1603
+ 4 def build_error_position(src: str, pos: int) -> list[str]:
1604
+ 5 if src == "":
1605
+ 6 return [
1606
+ 7 "No input provided",
1607
+ 8 ]
1608
+ 9 lines = src.split("\n")
1609
+ 10
1610
+ 11 line_idx = 0
1611
+ 12 while lines[line_idx] and pos > len(lines[line_idx]) - 1 and pos < len(src):
1612
+ 13 pos -= len(lines[line_idx])
1613
+ 14 line_idx += 1
1614
+ 15
1615
+ 16 lines_to_show = [
1616
+ 17 lines[i]
1617
+ 18 for i in range(
1618
+ 19 max(0, line_idx - (MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW - 1)),
1619
+ 20 line_idx + 1,
1620
+ 21 )
1621
+ 22 ]
1622
+ 23
1623
+ 24 return [
1624
+ 25 *lines_to_show,
1625
+ 26 " " * pos + "^",
1626
+ 27 ]
1627
+ ════ gbnf/utils/errors/errors_types.py ════
1628
+ 1 ValidInput = str | int | list[int]
1629
+ ════ gbnf/utils/errors/get_input_as_string.py ════
1630
+ 1 from .errors_types import ValidInput
1631
+ 2
1632
+ 3
1633
+ 4 def get_input_as_string(src: ValidInput) -> str:
1634
+ 5 if isinstance(src, str):
1635
+ 6 return src
1636
+ 7 if isinstance(src, int):
1637
+ 8 return chr(src)
1638
+ 9 return "".join(chr(cp) for cp in src)
1639
+ ════ gbnf/utils/errors/grammar_parse_error.py ════
1640
+ 1 from .build_error_position import build_error_position
1641
+ 2
1642
+ 3
1643
+ 4 def GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason: str) -> str:
1644
+ 5 return f"Failed to parse grammar: {reason}"
1645
+ 6
1646
+ 7
1647
+ 8 class GrammarParseError(Exception):
1648
+ 9 grammar: str
1649
+ 10 pos: int
1650
+ 11 reason: str
1651
+ 12
1652
+ 13 def __init__(self, grammar: str, pos: int, reason: str):
1653
+ 14 super().__init__(
1654
+ 15 "\n".join(
1655
+ 16 [
1656
+ 17 GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason),
1657
+ 18 "",
1658
+ 19 *build_error_position(grammar, pos),
1659
+ 20 ],
1660
+ 21 ),
1661
+ 22 )
1662
+ 23 self.grammar = grammar
1663
+ 24 self.pos = pos
1664
+ 25 self.reason = reason
1665
+ 26
1666
+ 27 def __str__(self):
1667
+ 28 return "\n".join(
1668
+ 29 [
1669
+ 30 GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(self.reason),
1670
+ 31 "",
1671
+ 32 *build_error_position(self.grammar, self.pos),
1672
+ 33 ],
1673
+ 34 )
1674
+ 35
1675
+ 36 def __eq__(self, other):
1676
+ 37 return str(self) == str(other)
1677
+ ════ gbnf/utils/errors/input_parse_error.py ════
1678
+ 1 from .build_error_position import build_error_position
1679
+ 2 from .errors_types import ValidInput
1680
+ 3 from .get_input_as_string import get_input_as_string
1681
+ 4
1682
+ 5 INPUT_PARSER_ERROR_HEADER_MESSAGE = "Failed to parse input string:"
1683
+ 6
1684
+ 7
1685
+ 8 class InputParseError(Exception):
1686
+ 9 most_recent_input: ValidInput
1687
+ 10 pos: int
1688
+ 11 previous_input: ValidInput
1689
+ 12
1690
+ 13 def __init__(
1691
+ 14 self,
1692
+ 15 most_recent_input: ValidInput,
1693
+ 16 pos: int,
1694
+ 17 previous_input: ValidInput = "",
1695
+ 18 ):
1696
+ 19 super().__init__(
1697
+ 20 "\n".join(
1698
+ 21 [
1699
+ 22 INPUT_PARSER_ERROR_HEADER_MESSAGE,
1700
+ 23 "",
1701
+ 24 *build_error_position(
1702
+ 25 f"{get_input_as_string(previous_input)}{get_input_as_string(most_recent_input)}",
1703
+ 26 pos + len(get_input_as_string(previous_input)),
1704
+ 27 ),
1705
+ 28 ],
1706
+ 29 ),
1707
+ 30 )
1708
+ 31 self.most_recent_input = most_recent_input
1709
+ 32 self.pos = pos
1710
+ 33 self.previous_input = previous_input
1711
+ 34
1712
+ 35 @property
1713
+ 36 def src(self):
1714
+ 37 return f"{get_input_as_string(self.previous_input)}{get_input_as_string(self.most_recent_input)}"
1715
+ 38
1716
+ 39 @property
1717
+ 40 def error_for_most_recent_input(self):
1718
+ 41 return "\n".join(
1719
+ 42 [
1720
+ 43 INPUT_PARSER_ERROR_HEADER_MESSAGE,
1721
+ 44 "",
1722
+ 45 *build_error_position(
1723
+ 46 get_input_as_string(self.most_recent_input),
1724
+ 47 self.pos,
1725
+ 48 ),
1726
+ 49 ],
1727
+ 50 )
1728
+ 51
1729
+ 52 def __str__(self):
1730
+ 53 return "\n".join(
1731
+ 54 [
1732
+ 55 INPUT_PARSER_ERROR_HEADER_MESSAGE,
1733
+ 56 "",
1734
+ 57 *build_error_position(
1735
+ 58 f"{get_input_as_string(self.previous_input)}{get_input_as_string(self.most_recent_input)}",
1736
+ 59 self.pos + len(get_input_as_string(self.previous_input)),
1737
+ 60 ),
1738
+ 61 ],
1739
+ 62 )
1740
+ 63
1741
+ 64 def __eq__(self, other):
1742
+ 65 return str(self) == str(other)
1743
+ ════ gbnf/utils/is_point_in_range.py ════
1744
+ 1 def is_point_in_range(point: int, given_range: tuple[int, int]) -> bool:
1745
+ 2 if type(point) is not int:
1746
+ 3 raise ValueError("point must be an integer")
1747
+ 4 return point >= given_range[0] and point <= given_range[1]
1748
+ ════ gbnf/utils/validate_non_empty.py ════
1749
+ 1 def validate_non_empty(value: list[int]) -> list[int]:
1750
+ 2 if not value:
1751
+ 3 raise ValueError("Value cannot be empty.")
1752
+ 4 return value