thekevinscott commited on
Commit
4bf9774
·
verified ·
1 Parent(s): 813e9c1

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

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/graph-pointer.ts +100 -0
  2. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/graph.test.ts +122 -0
  3. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/graph.ts +235 -0
  4. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/parse-state.test.ts +63 -0
  5. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/parse-state.ts +46 -0
  6. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/pointers.test.ts +22 -0
  7. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/pointers.ts +28 -0
  8. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/print.test.ts +89 -0
  9. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/print.ts +83 -0
  10. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/rule-ref.test.ts +25 -0
  11. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/rule-ref.ts +26 -0
  12. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/type-guards.test.ts +119 -0
  13. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/type-guards.ts +31 -0
  14. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-parser/build-rule-stack.test.ts +483 -0
  15. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-parser/build-rule-stack.ts +86 -0
  16. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/index.ts +8 -0
  17. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/index.ts +4 -0
  18. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/is-word-char.test.ts +25 -0
  19. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/is-word-char.ts +1 -0
  20. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-char.test.ts +47 -0
  21. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-char.ts +50 -0
  22. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-name.test.ts +25 -0
  23. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-name.ts +18 -0
  24. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-space.test.ts +34 -0
  25. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-space.ts +18 -0
  26. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/rules-builder-types.ts +82 -0
  27. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/rules-builder.test.ts +1411 -0
  28. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/rules-builder.ts +256 -0
  29. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/symbol-ids.test.ts +26 -0
  30. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/symbol-ids.ts +47 -0
  31. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/build-error-position.test.ts +32 -0
  32. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/build-error-position.ts +21 -0
  33. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/errors-types.ts +2 -0
  34. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/get-input-as-string.test.ts +15 -0
  35. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/get-input-as-string.ts +11 -0
  36. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/grammar-parse-error.test.ts +24 -0
  37. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/grammar-parse-error.ts +29 -0
  38. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/index.ts +3 -0
  39. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/input-parse-error.test.ts +28 -0
  40. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/input-parse-error.ts +40 -0
  41. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/is-point-in-range.test.ts +18 -0
  42. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/is-point-in-range.ts +8 -0
  43. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/validate-non-empty.test.ts +12 -0
  44. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/validate-non-empty.ts +6 -0
  45. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/iteration/iteration-with-additional-strings.test.ts +289 -0
  46. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/iteration/iteration-with-an-initial-string.test.ts +333 -0
  47. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/iteration/iteration.test.ts +95 -0
  48. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/validation/validate-grammar.test.ts +54 -0
  49. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/validation/validate-input.test.ts +96 -0
  50. v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tsconfig.json +17 -0
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/graph-pointer.ts ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { PrintOpts, ResolvedGraphPointer, UnresolvedRule } from './grammar-graph-types.js';
2
+ import type { GraphNode } from './graph-node.js';
3
+ import { printGraphPointer } from './print.js';
4
+ import {
5
+ isGraphPointerRuleChar,
6
+ isGraphPointerRuleCharExclude,
7
+ isGraphPointerRuleEnd,
8
+ isGraphPointerRuleRef,
9
+ isRuleEnd,
10
+ } from './type-guards.js';
11
+
12
+ export type GraphPointerKey = string;
13
+
14
+ export class GraphPointer<T extends UnresolvedRule = UnresolvedRule> {
15
+ node: GraphNode<T>;
16
+ parent: GraphPointer | undefined;
17
+ id: GraphPointerKey;
18
+ private _valid: boolean | undefined = undefined;
19
+
20
+ constructor(node: GraphNode<T>, parent?: GraphPointer) {
21
+ if (node === undefined || node === null) {
22
+ throw new Error('Node is undefined');
23
+ }
24
+ this.node = node;
25
+ this.parent = parent;
26
+ this.id = parent ? `${parent.id}-${node.id}` : node.id;
27
+ }
28
+
29
+ get rule(): T {
30
+ return this.node.rule;
31
+ }
32
+
33
+ get valid(): boolean | undefined {
34
+ return this._valid;
35
+ }
36
+
37
+ set valid(valid: boolean) {
38
+ this._valid = valid;
39
+ }
40
+
41
+ print(opts: PrintOpts): string {
42
+ return printGraphPointer(this)(opts);
43
+ }
44
+
45
+ /**
46
+ * Resolve the graph pointer: follow references into their referenced nodes and
47
+ * climb out of end rules into the parent's next node.
48
+ *
49
+ * @param resolved Whether the pointer has already been resolved (i.e. we are returning from a reference).
50
+ */
51
+ *resolve(resolved = false): Generator<ResolvedGraphPointer> {
52
+ const self = this as GraphPointer;
53
+ if (isGraphPointerRuleRef(self)) {
54
+ if (resolved) {
55
+ if (!self.node.next) {
56
+ throw new Error(`No next node: ${String(self.node)}`);
57
+ }
58
+ yield* new GraphPointer(self.node.next, self.parent).resolve();
59
+ } else {
60
+ for (const node of self.node.rule.nodes) {
61
+ yield* new GraphPointer(node, self).resolve();
62
+ }
63
+ }
64
+ } else if (isGraphPointerRuleEnd(self)) {
65
+ if (!self.parent) {
66
+ yield self as ResolvedGraphPointer;
67
+ } else {
68
+ yield* self.parent.resolve(true);
69
+ }
70
+ } else if (isGraphPointerRuleChar(self) || isGraphPointerRuleCharExclude(self)) {
71
+ yield self as ResolvedGraphPointer;
72
+ } else {
73
+ throw new Error(`Unknown rule: ${JSON.stringify(self.node.rule)}`);
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Fetch the next resolved graph pointers, following this pointer's node.
79
+ */
80
+ *fetchNext(): Generator<ResolvedGraphPointer> {
81
+ // If this pointer is invalid, then we don't return any new pointers
82
+ if (!this.valid) {
83
+ return;
84
+ }
85
+
86
+ // If this pointer is an end node, we return the parent's next node.
87
+ // If no parent exists, we return nothing, since it's the end of the line.
88
+ if (isRuleEnd(this.node.rule)) {
89
+ if (this.parent) {
90
+ yield* this.parent.fetchNext();
91
+ }
92
+ } else {
93
+ if (!this.node.next) {
94
+ throw new Error(`No next node: ${String(this.node)}`);
95
+ }
96
+ const pointer = new GraphPointer(this.node.next, this.parent);
97
+ yield* pointer.resolve();
98
+ }
99
+ }
100
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/graph.test.ts ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from './grammar-graph-types.js';
3
+ import { Graph } from './graph.js';
4
+ import { GraphNode } from './graph-node.js';
5
+ import { GraphPointer } from './graph-pointer.js';
6
+ import { Pointers } from './pointers.js';
7
+ import { RuleRef } from './rule-ref.js';
8
+ import { isRule } from './type-guards.js';
9
+
10
+ describe('Graph', () => {
11
+ const grammar = 'example-grammar';
12
+ const stackedRules: UnresolvedRule[][][] = [
13
+ [[new RuleChar([65, 66, 67])], [new RuleChar([68, 69, 70])]],
14
+ [[new RuleChar([71, 72, 73])], [new RuleChar([74, 75, 76])]],
15
+ ];
16
+ const rootId = 0;
17
+ const meta = { stackId: 0, pathId: 0, stepId: 0 };
18
+
19
+ test('it creates a graph instance', () => {
20
+ const graph = new Graph(grammar, stackedRules, rootId);
21
+ expect(graph).toBeInstanceOf(Graph);
22
+ expect(graph.grammar).toBe(grammar);
23
+ });
24
+
25
+ test('it gets the root node', () => {
26
+ const graph = new Graph(grammar, stackedRules, rootId);
27
+ const rootNode = graph.getRootNode(rootId);
28
+ expect(rootNode).toBeInstanceOf(Map);
29
+ expect(rootNode.size).toBe(2);
30
+ });
31
+
32
+ test('it throws for an unknown root', () => {
33
+ expect(() => new Graph(grammar, stackedRules, 5)).toThrow('Root node not found for value: 5');
34
+ expect(() => new Graph(grammar, stackedRules, rootId).getRootNode(9)).toThrow('Root node not found for value: 9');
35
+ });
36
+
37
+ test('it prints the graph', () => {
38
+ const graph = new Graph(grammar, stackedRules, rootId);
39
+ const printedGraph = graph.print(undefined, true);
40
+ expect(typeof printedGraph).toBe('string');
41
+ expect(printedGraph.length).toBeGreaterThan(0);
42
+ expect(graph.print()).toBe(['{0,0,0}[ABC]', '{0,1,0}[DEF]', '{1,0,0}[GHI]', '{1,1,0}[JKL]'].join('\n'));
43
+ });
44
+
45
+ test('it iterates over pointers', () => {
46
+ const graph = new Graph(grammar, stackedRules, rootId);
47
+ const mockPointers = new Pointers(
48
+ ...[
49
+ new RuleChar([65, 66, 67]),
50
+ new RuleChar([68, 69, 70]),
51
+ new RuleChar([71, 72, 73]),
52
+ new RuleChar([74, 75, 76]),
53
+ new RuleCharExclude([1]),
54
+ new RuleEnd(),
55
+ ].map((r, i) => new GraphPointer(new GraphNode(r, { ...meta, stepId: i }))),
56
+ );
57
+
58
+ const result = [...graph.iterateOverPointers(mockPointers)];
59
+ expect(result).toHaveLength(6);
60
+ for (const [rule, pointers] of result) {
61
+ expect(isRule(rule)).toBe(true);
62
+ expect(pointers.length).toBeGreaterThanOrEqual(1);
63
+ for (const pointer of pointers) {
64
+ expect(mockPointers.has(pointer)).toBe(true);
65
+ }
66
+ }
67
+ });
68
+
69
+ test('it groups pointers sharing the same rule instance', () => {
70
+ const graph = new Graph(grammar, stackedRules, rootId);
71
+ const rule = new RuleChar([65]);
72
+ const a = new GraphPointer(new GraphNode(rule, { ...meta, stepId: 0 }));
73
+ const b = new GraphPointer(new GraphNode(rule, { ...meta, stepId: 1 }));
74
+ const result = [...graph.iterateOverPointers(new Pointers(a, b))];
75
+ expect(result).toEqual([[rule, [a, b]]]);
76
+ });
77
+
78
+ test('it raises an error on a reference rule', () => {
79
+ const graph = new Graph(grammar, stackedRules, rootId);
80
+ const mockPointers = [new GraphPointer(new GraphNode(new RuleRef(0), meta))];
81
+ expect(() => [...graph.iterateOverPointers(mockPointers)]).toThrow('Encountered a reference rule in the graph');
82
+ });
83
+
84
+ test('it shares a single rule instance across identical rules', () => {
85
+ const graph = new Graph(
86
+ grammar,
87
+ [
88
+ [
89
+ [new RuleChar([65]), new RuleEnd()],
90
+ [new RuleChar([65]), new RuleEnd()],
91
+ ],
92
+ ],
93
+ 0,
94
+ );
95
+ const [first, second] = [...graph.getRootNode(0).values()];
96
+ expect(first.rule).toBe(second.rule);
97
+ expect(first.next?.rule).toBe(second.next?.rule);
98
+ });
99
+
100
+ test('it walks references and tracks previous code points', () => {
101
+ const ref = new RuleRef(1);
102
+ const graph = new Graph(
103
+ grammar,
104
+ [
105
+ [[ref, new RuleChar([98]), new RuleEnd()]],
106
+ [[new RuleChar([97]), new RuleEnd()]],
107
+ ],
108
+ 0,
109
+ );
110
+ let pointers = graph.add('a');
111
+ expect([...pointers].map((p) => p.rule)).toEqual([new RuleChar([98])]);
112
+ pointers = graph.add('b', pointers);
113
+ expect([...pointers].map((p) => p.rule)).toEqual([new RuleEnd()]);
114
+ expect(graph.previousCodePoints).toEqual([97, 98]);
115
+ expect(() => graph.add('c', pointers)).toThrow('Failed to parse input string:');
116
+ });
117
+
118
+ test('it rejects non-string input', () => {
119
+ const graph = new Graph(grammar, stackedRules, rootId);
120
+ expect(() => graph.add(65 as unknown as string)).toThrow('src must be a string in graph.add');
121
+ });
122
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/graph.ts ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { ResolvedGraphPointer, UnresolvedRule, ValidInput } from './grammar-graph-types.js';
7
+ import { GraphNode } from './graph-node.js';
8
+ import { GraphPointer } from './graph-pointer.js';
9
+ import { Pointers } from './pointers.js';
10
+ import type { RuleRef } from './rule-ref.js';
11
+ import { isRange, isRuleChar, isRuleCharExclude, isRuleEnd, isRuleRef } from './type-guards.js';
12
+
13
+ export type RootNode = Map<number, GraphNode>;
14
+
15
+ export class Graph {
16
+ private readonly roots: Map<number, RootNode>;
17
+ grammar: string;
18
+ private readonly rootNode: RootNode;
19
+ previousCodePoints: number[];
20
+
21
+ constructor(grammar: string, stackedRules: UnresolvedRule[][][], rootId: number) {
22
+ this.roots = new Map();
23
+ this.grammar = grammar;
24
+ this.previousCodePoints = [];
25
+ const ruleRefs: RuleRef[] = [];
26
+ const uniqueRules = new Map<string, UnresolvedRule>();
27
+
28
+ for (let stackId = 0; stackId < stackedRules.length; stackId++) {
29
+ const stack = stackedRules[stackId];
30
+ const nodes: RootNode = new Map();
31
+ for (let pathId = 0; pathId < stack.length; pathId++) {
32
+ const path = stack[pathId];
33
+ let node: GraphNode | undefined = undefined;
34
+ for (let stepId = path.length - 1; stepId >= 0; stepId--) {
35
+ const nextNode: GraphNode | undefined = node;
36
+ const rule = stack[pathId][stepId];
37
+ const key = getSerializedRuleKey(rule);
38
+ if (!uniqueRules.has(key)) {
39
+ uniqueRules.set(key, rule);
40
+ }
41
+ if (isRuleRef(rule)) {
42
+ ruleRefs.push(rule);
43
+ }
44
+ // rules coming in may be identical but have different references.
45
+ // here, we ensure we always use the same reference for an identical rule.
46
+ // this makes future comparisons easier.
47
+ const uniqueRule = uniqueRules.get(key);
48
+ if (uniqueRule === undefined) {
49
+ throw new Error('Could not get unique rule');
50
+ }
51
+ node = new GraphNode(uniqueRule, { stackId, pathId, stepId }, nextNode);
52
+ }
53
+
54
+ if (node === undefined) {
55
+ throw new Error('Could not get node');
56
+ }
57
+ nodes.set(pathId, node);
58
+ }
59
+ this.roots.set(stackId, nodes);
60
+ }
61
+
62
+ const rootNode = this.roots.get(rootId);
63
+ if (rootNode === undefined) {
64
+ throw new Error(`Root node not found for value: ${rootId}`);
65
+ }
66
+ this.rootNode = rootNode;
67
+
68
+ for (const ruleRef of ruleRefs) {
69
+ ruleRef.nodes = new Set(this.getRootNode(ruleRef.value).values());
70
+ }
71
+ }
72
+
73
+ getRootNode(value: number): RootNode {
74
+ const rootNode = this.roots.get(value);
75
+ if (rootNode === undefined) {
76
+ throw new Error(`Root node not found for value: ${value}`);
77
+ }
78
+ return rootNode;
79
+ }
80
+
81
+ private getInitialPointers(): Pointers {
82
+ const pointers = new Pointers();
83
+ for (const [node, parent] of this.fetchNodesForRootNode(this.rootNode)) {
84
+ const pointer = new GraphPointer(node, parent);
85
+ for (const resolvedPointer of this.resolvePointer(pointer)) {
86
+ pointers.add(resolvedPointer);
87
+ }
88
+ }
89
+ return pointers;
90
+ }
91
+
92
+ private setValid(pointers: GraphPointer[], valid: boolean): void {
93
+ for (const pointer of pointers) {
94
+ pointer.valid = valid;
95
+ }
96
+ }
97
+
98
+ private parse(currentPointers: Pointers, codePoint: number): Pointers {
99
+ for (const [rule, graphPointers] of this.iterateOverPointers(currentPointers)) {
100
+ if (isRuleChar(rule)) {
101
+ let valid = false;
102
+ for (const possibleCodePoint of rule.value) {
103
+ if (valid) {
104
+ continue;
105
+ }
106
+ if (isRange(possibleCodePoint)) {
107
+ if (isPointInRange(codePoint, possibleCodePoint)) {
108
+ valid = true;
109
+ }
110
+ } else if (codePoint === possibleCodePoint) {
111
+ valid = true;
112
+ }
113
+ }
114
+ this.setValid(graphPointers, valid);
115
+ } else if (isRuleCharExclude(rule)) {
116
+ let valid = true;
117
+ for (const possibleCodePoint of rule.value) {
118
+ if (!valid) {
119
+ continue;
120
+ }
121
+ if (isRange(possibleCodePoint)) {
122
+ if (isPointInRange(codePoint, possibleCodePoint)) {
123
+ valid = false;
124
+ }
125
+ } else if (codePoint === possibleCodePoint) {
126
+ valid = false;
127
+ }
128
+ }
129
+ this.setValid(graphPointers, valid);
130
+ } else if (!isRuleEnd(rule)) {
131
+ throw new Error(`Unsupported rule: ${JSON.stringify(rule)}`);
132
+ }
133
+ }
134
+
135
+ // a pointer's id is the sum of its node's id and its parent's id chain.
136
+ // if two pointers share the same id, it means they point to the same node and have identical parent chains.
137
+ // for the purposes of walking the graph, we only need to keep one of them.
138
+ const nextPointers = new Pointers();
139
+ for (const currentPointer of currentPointers) {
140
+ for (const unresolvedNextPointer of currentPointer.fetchNext()) {
141
+ for (const resolvedNextPointer of this.resolvePointer(unresolvedNextPointer)) {
142
+ nextPointers.add(resolvedNextPointer);
143
+ }
144
+ }
145
+ }
146
+ return nextPointers;
147
+ }
148
+
149
+ private *resolvePointer(unresolvedPointer: GraphPointer): Generator<ResolvedGraphPointer> {
150
+ for (const resolvedPointer of unresolvedPointer.resolve()) {
151
+ if (isRuleRef(resolvedPointer.node.rule)) {
152
+ throw new Error('Encountered a reference rule when building pointers to the graph');
153
+ }
154
+ if (isRuleEnd(resolvedPointer.node.rule) && resolvedPointer.parent !== undefined) {
155
+ throw new Error('Encountered an ending rule with a parent when building pointers to the graph');
156
+ }
157
+ yield resolvedPointer;
158
+ }
159
+ }
160
+
161
+ add(src: ValidInput, pointers?: Pointers): Pointers {
162
+ if (typeof src !== 'string') {
163
+ throw new Error('src must be a string in graph.add');
164
+ }
165
+ let currentPointers = pointers ?? this.getInitialPointers();
166
+
167
+ const codePoints = getInputAsCodePoints(src);
168
+ for (const codePoint of codePoints) {
169
+ if (!Number.isInteger(codePoint)) {
170
+ throw new Error('code_point must be an integer!');
171
+ }
172
+ }
173
+
174
+ for (let codePointPos = 0; codePointPos < codePoints.length; codePointPos++) {
175
+ const codePoint = codePoints[codePointPos];
176
+ currentPointers = this.parse(currentPointers, codePoint);
177
+ if (currentPointers.size === 0) {
178
+ throw new InputParseError(codePoints, codePointPos, this.previousCodePoints);
179
+ }
180
+ }
181
+ this.previousCodePoints.push(...codePoints);
182
+ return currentPointers;
183
+ }
184
+
185
+ // generator that yields either the node, or if a reference rule, the referenced node
186
+ // we need this function, as distinct from leveraging the logic in GraphPointer,
187
+ // because that needs a rule ref with already defined nodes; this function is used to _set_ those nodes
188
+ private *fetchNodesForRootNode(
189
+ rootNodes: RootNode,
190
+ parent?: GraphPointer,
191
+ ): Generator<[GraphNode, GraphPointer | undefined]> {
192
+ for (const node of rootNodes.values()) {
193
+ if (isRuleRef(node.rule)) {
194
+ yield* this.fetchNodesForRootNode(this.getRootNode(node.rule.value), new GraphPointer(node, parent));
195
+ } else {
196
+ yield [node, parent];
197
+ }
198
+ }
199
+ }
200
+
201
+ print(pointers?: Pointers, colors = false): string {
202
+ const nodes: GraphNode[][] = [...this.roots.values()].map((rootNode) => [...rootNode.values()]);
203
+ const printPointers = pointers ?? new Pointers();
204
+ const graphView: string[] = [];
205
+ for (const rootNode of nodes) {
206
+ for (const node of rootNode) {
207
+ graphView.push(
208
+ node.print({
209
+ pointers: printPointers,
210
+ showPosition: true,
211
+ colorize: colors ? colorize : (s) => String(s),
212
+ }),
213
+ );
214
+ }
215
+ }
216
+ return graphView.join('\n');
217
+ }
218
+
219
+ *iterateOverPointers(pointers: Iterable<GraphPointer>): Generator<[UnresolvedRule, GraphPointer[]]> {
220
+ const seenRules = new Map<UnresolvedRule, GraphPointer[]>();
221
+ for (const pointer of pointers) {
222
+ const rule = pointer.rule;
223
+ if (isRuleRef(rule)) {
224
+ throw new Error('Encountered a reference rule in the graph');
225
+ }
226
+ const seenRule = seenRules.get(rule);
227
+ if (seenRule === undefined) {
228
+ seenRules.set(rule, [pointer]);
229
+ } else {
230
+ seenRule.push(pointer);
231
+ }
232
+ }
233
+ yield* seenRules.entries();
234
+ }
235
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/parse-state.test.ts ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test, vi } from 'vitest';
2
+ import { RuleChar } from './grammar-graph-types.js';
3
+ import type { Graph } from './graph.js';
4
+ import { GraphNode } from './graph-node.js';
5
+ import { GraphPointer } from './graph-pointer.js';
6
+ import { ParseState } from './parse-state.js';
7
+ import { Pointers } from './pointers.js';
8
+
9
+ const makeMockGraph = () => {
10
+ const graph = {
11
+ add: vi.fn((_input: string, pointers: Pointers) => pointers),
12
+ grammar: 'sample-grammar',
13
+ };
14
+ return graph as unknown as Graph & typeof graph;
15
+ };
16
+
17
+ const mockPointers = new Pointers(
18
+ new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 1, pathId: 1, stepId: 1 })),
19
+ new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 1, pathId: 1, stepId: 2 })),
20
+ );
21
+
22
+ describe('ParseState', () => {
23
+ test('it constructs with the given graph and pointers', () => {
24
+ expect(new ParseState(makeMockGraph(), mockPointers)).toBeInstanceOf(ParseState);
25
+ });
26
+
27
+ test('it returns unique rules from pointers', () => {
28
+ const rules = [...new ParseState(makeMockGraph(), mockPointers).rules()];
29
+ expect(rules).toHaveLength(1);
30
+ expect(rules[0]).toBeInstanceOf(RuleChar);
31
+ expect((rules[0] as RuleChar).value).toEqual([65]);
32
+ });
33
+
34
+ test('it iterates over unique rules using the iterator protocol', () => {
35
+ const rules = [...new ParseState(makeMockGraph(), mockPointers)];
36
+ expect(rules).toHaveLength(1);
37
+ expect(rules[0]).toBeInstanceOf(RuleChar);
38
+ });
39
+
40
+ test('it adds new input and returns a new parse state with updated pointers', () => {
41
+ const mockGraph = makeMockGraph();
42
+ const newPointers = new Pointers();
43
+ mockGraph.add.mockReturnValue(newPointers);
44
+ const parseState = new ParseState(mockGraph, mockPointers);
45
+ const newState = parseState.add('B');
46
+ expect(newState).toBeInstanceOf(ParseState);
47
+ expect(newState).not.toBe(parseState);
48
+ expect(mockGraph.add).toHaveBeenCalledWith('B', mockPointers);
49
+ });
50
+
51
+ test('it rejects non-string input', () => {
52
+ const parseState = new ParseState(makeMockGraph(), mockPointers);
53
+ expect(() => parseState.add(1 as unknown as string)).toThrow('input text must be of type string');
54
+ });
55
+
56
+ test('it calculates the size of unique rules correctly', () => {
57
+ expect(new ParseState(makeMockGraph(), mockPointers).size).toBe(1);
58
+ });
59
+
60
+ test('it provides access to the underlying graph grammar', () => {
61
+ expect(new ParseState(makeMockGraph(), mockPointers).grammar).toBe('sample-grammar');
62
+ });
63
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/parse-state.ts ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 implements Iterable<ResolvedRule> {
6
+ private readonly graph: Graph;
7
+ private readonly pointers: Pointers;
8
+
9
+ constructor(graph: Graph, pointers: Pointers) {
10
+ this.graph = graph;
11
+ this.pointers = pointers;
12
+ }
13
+
14
+ *[Symbol.iterator](): Generator<ResolvedRule> {
15
+ yield* this.rules();
16
+ }
17
+
18
+ // Yields the unique set of rules the current pointers point at.
19
+ *rules(): Generator<ResolvedRule> {
20
+ const seen = new Set<string>();
21
+ for (const pointer of this.pointers) {
22
+ const rule = pointer.rule as ResolvedRule;
23
+ const key = JSON.stringify(rule);
24
+ if (!seen.has(key)) {
25
+ seen.add(key);
26
+ yield rule;
27
+ }
28
+ }
29
+ }
30
+
31
+ add(text: string): ParseState {
32
+ if (typeof text !== 'string') {
33
+ throw new Error('input text must be of type string');
34
+ }
35
+ const pointers = this.graph.add(text, this.pointers);
36
+ return new ParseState(this.graph, pointers);
37
+ }
38
+
39
+ get size(): number {
40
+ return [...this.rules()].length;
41
+ }
42
+
43
+ get grammar(): string {
44
+ return this.graph.grammar;
45
+ }
46
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/pointers.test.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { RuleChar } from './grammar-graph-types.js';
3
+ import { GraphNode } from './graph-node.js';
4
+ import { GraphPointer } from './graph-pointer.js';
5
+ import { Pointers } from './pointers.js';
6
+
7
+ const makePointer = (stepId: number) =>
8
+ new GraphPointer(new GraphNode(new RuleChar([97]), { stackId: 0, pathId: 0, stepId }));
9
+
10
+ describe('Pointers', () => {
11
+ test('it keeps insertion order and de-duplicates by id', () => {
12
+ const a = makePointer(0);
13
+ const b = makePointer(1);
14
+ const aDuplicate = makePointer(0);
15
+ const pointers = new Pointers(a, b);
16
+ pointers.add(aDuplicate);
17
+ expect(pointers.size).toBe(2);
18
+ expect([...pointers]).toEqual([aDuplicate, b]);
19
+ expect(pointers.has(aDuplicate)).toBe(true);
20
+ expect(pointers.has(a)).toBe(false);
21
+ });
22
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/pointers.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphPointer } from './graph-pointer.js';
2
+
3
+ // An insertion-ordered set of pointers, de-duplicated by pointer id.
4
+ export class Pointers {
5
+ private readonly pointers = new Map<string, GraphPointer>();
6
+
7
+ constructor(...pointers: GraphPointer[]) {
8
+ for (const pointer of pointers) {
9
+ this.add(pointer);
10
+ }
11
+ }
12
+
13
+ add(pointer: GraphPointer): void {
14
+ this.pointers.set(pointer.id, pointer);
15
+ }
16
+
17
+ has(pointer: GraphPointer): boolean {
18
+ return this.pointers.get(pointer.id) === pointer;
19
+ }
20
+
21
+ *[Symbol.iterator](): IterableIterator<GraphPointer> {
22
+ yield* this.pointers.values();
23
+ }
24
+
25
+ get size(): number {
26
+ return this.pointers.size;
27
+ }
28
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/print.test.ts ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { beforeEach, describe, expect, test, vi } from 'vitest';
2
+ import { getParentStackId } from './get-parent-stack-id.js';
3
+ import { RuleChar, RuleEnd, type UnresolvedRule } from './grammar-graph-types.js';
4
+ import { type PrintableNode, type PrintablePointer, printGraphNode, printGraphPointer } from './print.js';
5
+ import { RuleRef } from './rule-ref.js';
6
+
7
+ vi.mock('./get-parent-stack-id.js', () => ({
8
+ getParentStackId: vi.fn(() => ''),
9
+ }));
10
+
11
+ const COLORS: Record<string, string> = {
12
+ '\x1b[34m': 'BLUE',
13
+ '\x1b[36m': 'CYAN',
14
+ '\x1b[32m': 'GREEN',
15
+ '\x1b[31m': 'RED',
16
+ '\x1b[90m': 'GRAY',
17
+ '\x1b[33m': 'YELLOW',
18
+ };
19
+
20
+ const mockColorize = (text: string | number, color: string): string => {
21
+ if (!(color in COLORS)) {
22
+ throw new Error(`Invalid color: ${color}`);
23
+ }
24
+ return `[${COLORS[color]}]:${text}`;
25
+ };
26
+
27
+ const createMockNode = (id: number, rule: UnresolvedRule, next?: PrintableNode): PrintableNode => ({
28
+ id,
29
+ rule,
30
+ next,
31
+ print: () => `Node(${id})`,
32
+ });
33
+
34
+ const createMockGraphPointer = (node: PrintableNode): PrintablePointer => ({
35
+ node,
36
+ parent: undefined,
37
+ print: () => `Pointer to ${node.id}`,
38
+ });
39
+
40
+ describe('print', () => {
41
+ beforeEach(() => {
42
+ vi.mocked(getParentStackId).mockReset();
43
+ });
44
+
45
+ describe('printGraphPointer', () => {
46
+ test('it prints graph pointer details correctly', () => {
47
+ const mockPointer = createMockGraphPointer(createMockNode(1, new RuleRef(100)));
48
+ vi.mocked(getParentStackId).mockReturnValue('foo');
49
+ const result = printGraphPointer(mockPointer)({ colorize: mockColorize, pointers: [], showPosition: false });
50
+ expect(result).toBe('[RED]:*foo');
51
+ });
52
+ });
53
+
54
+ describe('printGraphNode', () => {
55
+ test('it prints a graph node with a character rule', () => {
56
+ const mockNode = createMockNode(1, new RuleChar([65]));
57
+ const result = printGraphNode(mockNode)({ colorize: mockColorize, showPosition: false, pointers: [] });
58
+ expect(result).toBe('[GRAY]:[[YELLOW]:A[GRAY]:]');
59
+ });
60
+
61
+ test('it prints a graph node with a range', () => {
62
+ const mockNode = createMockNode(1, new RuleChar([[97, 122]]));
63
+ const result = printGraphNode(mockNode)({ colorize: mockColorize });
64
+ expect(result).toBe('[GRAY]:[[YELLOW]:[YELLOW]:a[YELLOW]:z[GRAY]:]');
65
+ });
66
+
67
+ test('it prints a graph node with a rule reference', () => {
68
+ const mockNode = createMockNode(1, new RuleRef(200));
69
+ const result = printGraphNode(mockNode)({ colorize: mockColorize, showPosition: true, pointers: [] });
70
+ expect(result).toBe('[BLUE]:{[GRAY]:1[BLUE]:}[GRAY]:Ref([GREEN]:200[GRAY]:)');
71
+ });
72
+
73
+ test('it prints an end rule by type', () => {
74
+ const mockNode = createMockNode(1, new RuleEnd());
75
+ expect(printGraphNode(mockNode)({ colorize: mockColorize })).toBe('[YELLOW]:end');
76
+ });
77
+
78
+ test('it prints pointers on the node and chains to the next node', () => {
79
+ const next = createMockNode(2, new RuleEnd());
80
+ const mockNode = createMockNode(1, new RuleChar([65]), next);
81
+ const pointer = createMockGraphPointer(mockNode);
82
+ const result = printGraphNode(mockNode)({
83
+ colorize: mockColorize,
84
+ pointers: [pointer as unknown as import('./graph-pointer.js').GraphPointer],
85
+ });
86
+ expect(result).toBe('[GRAY]:[[YELLOW]:A[GRAY]:][GRAY]:[[YELLOW]:Pointer to 1[GRAY]:][GRAY]:-> Node(2)');
87
+ });
88
+ });
89
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/print.ts ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Color } from './colorize.js';
2
+ import { getParentStackId } from './get-parent-stack-id.js';
3
+ import type { PrintOpts, UnresolvedRule } from './grammar-graph-types.js';
4
+ import type { GraphNode } from './graph-node.js';
5
+ import type { GraphPointer } from './graph-pointer.js';
6
+ import { isRange, isRuleChar, isRuleRef } from './type-guards.js';
7
+
8
+ // The minimal shape of a node that printing needs; allows duck-typed nodes in tests.
9
+ export interface PrintableNode {
10
+ id: string | number;
11
+ rule: UnresolvedRule;
12
+ next?: PrintableNode | GraphNode | null;
13
+ print: (opts: PrintOpts) => string;
14
+ }
15
+
16
+ export interface PrintablePointer {
17
+ node: PrintableNode | GraphNode;
18
+ parent?: GraphPointer | null;
19
+ print: (opts: PrintOpts) => string;
20
+ }
21
+
22
+ export const printGraphPointer =
23
+ (pointer: PrintablePointer) =>
24
+ (opts: PrintOpts): string => {
25
+ const col = opts.colorize;
26
+ return col(`*${getParentStackId(pointer as Pick<GraphPointer, 'parent'>, col)}`, Color.RED);
27
+ };
28
+
29
+ export const getChar = (charCode: number): string => {
30
+ const char = String.fromCodePoint(charCode);
31
+ if (char === '\n') {
32
+ return '\\n';
33
+ }
34
+ return char;
35
+ };
36
+
37
+ export const printGraphNode =
38
+ (node: PrintableNode) =>
39
+ (opts: PrintOpts): string => {
40
+ const pointers = opts.pointers ?? [];
41
+ const col = opts.colorize;
42
+ const showPosition = opts.showPosition ?? false;
43
+ const rule = node.rule;
44
+ const parts: string[] = [];
45
+ if (showPosition) {
46
+ parts.push(col('{', Color.BLUE), col(node.id, Color.GRAY), col('}', Color.BLUE));
47
+ }
48
+
49
+ if (isRuleChar(rule)) {
50
+ parts.push(
51
+ col('[', Color.GRAY),
52
+ col(
53
+ rule.value
54
+ .map((v) => (isRange(v) ? v.map((val) => col(getChar(val), Color.YELLOW)).join('') : getChar(v)))
55
+ .join(''),
56
+ Color.YELLOW,
57
+ ),
58
+ col(']', Color.GRAY),
59
+ );
60
+ } else if (isRuleRef(rule)) {
61
+ parts.push(col('Ref(', Color.GRAY), col(rule.value, Color.GREEN), col(')', Color.GRAY));
62
+ } else {
63
+ parts.push(col(rule.type, Color.YELLOW));
64
+ }
65
+
66
+ for (const pointer of pointers) {
67
+ const pointerParts: string[] = [];
68
+ if ((pointer as PrintablePointer).node === node) {
69
+ pointerParts.push(pointer.print(opts));
70
+ }
71
+
72
+ if (pointerParts.length > 0) {
73
+ parts.push(col('[', Color.GRAY), col(pointerParts.join(''), Color.YELLOW), col(']', Color.GRAY));
74
+ }
75
+ }
76
+
77
+ const partsToReturn = [parts.join('')];
78
+ if (node.next) {
79
+ partsToReturn.push(node.next.print(opts));
80
+ }
81
+
82
+ return partsToReturn.join(col('-> ', Color.GRAY));
83
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/rule-ref.test.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import type { GraphNode } from './graph-node.js';
3
+ import { RuleRef } from './rule-ref.js';
4
+
5
+ describe('RuleRef', () => {
6
+ test('it initializes with a given value', () => {
7
+ expect(new RuleRef(123).value).toBe(123);
8
+ });
9
+
10
+ test('it allows setting and getting nodes', () => {
11
+ const mockNodes = new Set<GraphNode>([{} as GraphNode]);
12
+ const ruleRef = new RuleRef(123);
13
+ ruleRef.nodes = mockNodes;
14
+ expect(ruleRef.nodes).toBe(mockNodes);
15
+ });
16
+
17
+ test('it throws an error if trying to get nodes before setting', () => {
18
+ const ruleRef = new RuleRef(123);
19
+ expect(() => ruleRef.nodes).toThrow('Nodes are not set');
20
+ });
21
+
22
+ test('it serializes to type and value only', () => {
23
+ expect(JSON.stringify(new RuleRef(4))).toBe('{"type":"ref","value":4}');
24
+ });
25
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/rule-ref.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphNode } from './graph-node.js';
2
+
3
+ export class RuleRef {
4
+ readonly type = 'ref' as const;
5
+ value: number;
6
+ private _nodes: Set<GraphNode> | undefined = undefined;
7
+
8
+ constructor(value: number) {
9
+ this.value = value;
10
+ }
11
+
12
+ get nodes(): Set<GraphNode> {
13
+ if (this._nodes === undefined) {
14
+ throw new Error('Nodes are not set');
15
+ }
16
+ return this._nodes;
17
+ }
18
+
19
+ set nodes(nodes: Set<GraphNode>) {
20
+ this._nodes = nodes;
21
+ }
22
+
23
+ toJSON(): { type: string; value: number } {
24
+ return { type: this.type, value: this.value };
25
+ }
26
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/type-guards.test.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { RuleChar, RuleCharExclude, RuleEnd } from './grammar-graph-types.js';
3
+ import { GraphNode } from './graph-node.js';
4
+ import { GraphPointer } from './graph-pointer.js';
5
+ import { RuleRef } from './rule-ref.js';
6
+ import {
7
+ isGraphPointerRuleChar,
8
+ isGraphPointerRuleCharExclude,
9
+ isGraphPointerRuleEnd,
10
+ isGraphPointerRuleRef,
11
+ isRange,
12
+ isRule,
13
+ isRuleChar,
14
+ isRuleCharExclude,
15
+ isRuleEnd,
16
+ isRuleRef,
17
+ } from './type-guards.js';
18
+
19
+ const meta = { stackId: 1, pathId: 2, stepId: 3 };
20
+
21
+ describe('rule type guards', () => {
22
+ describe('isGraphPointerRuleRef', () => {
23
+ test('it returns true', () => {
24
+ expect(isGraphPointerRuleRef(new GraphPointer(new GraphNode(new RuleRef(1), meta)))).toBe(true);
25
+ });
26
+ test('it returns false', () => {
27
+ expect(isGraphPointerRuleRef(new GraphPointer(new GraphNode(new RuleEnd(), meta)))).toBe(false);
28
+ });
29
+ });
30
+
31
+ describe('isGraphPointerRuleEnd', () => {
32
+ test('it returns false', () => {
33
+ expect(isGraphPointerRuleEnd(new GraphPointer(new GraphNode(new RuleRef(1), meta)))).toBe(false);
34
+ });
35
+ test('it returns true', () => {
36
+ expect(isGraphPointerRuleEnd(new GraphPointer(new GraphNode(new RuleEnd(), meta)))).toBe(true);
37
+ });
38
+ });
39
+
40
+ describe('isGraphPointerRuleChar', () => {
41
+ test('it returns true', () => {
42
+ expect(isGraphPointerRuleChar(new GraphPointer(new GraphNode(new RuleChar([97]), meta)))).toBe(true);
43
+ });
44
+ test('it returns false', () => {
45
+ expect(isGraphPointerRuleChar(new GraphPointer(new GraphNode(new RuleEnd(), meta)))).toBe(false);
46
+ });
47
+ });
48
+
49
+ describe('isGraphPointerRuleCharExclude', () => {
50
+ test('it returns true', () => {
51
+ expect(isGraphPointerRuleCharExclude(new GraphPointer(new GraphNode(new RuleCharExclude([97]), meta)))).toBe(
52
+ true,
53
+ );
54
+ });
55
+ test('it returns false', () => {
56
+ expect(isGraphPointerRuleCharExclude(new GraphPointer(new GraphNode(new RuleChar([97]), meta)))).toBe(false);
57
+ });
58
+ });
59
+
60
+ describe('isRule', () => {
61
+ test('it returns false for null and undefined', () => {
62
+ expect(isRule(null)).toBe(false);
63
+ expect(isRule(undefined)).toBe(false);
64
+ });
65
+ test('it returns false for a non rule', () => {
66
+ expect(isRule({ type: 'invalid', value: [] })).toBe(false);
67
+ });
68
+ test('it returns true for valid rule objects', () => {
69
+ expect(isRule(new RuleChar([65, [66, 67]]))).toBe(true);
70
+ expect(isRule(new RuleRef(1))).toBe(true);
71
+ expect(isRule(new RuleEnd())).toBe(true);
72
+ });
73
+ });
74
+
75
+ describe('isRuleRef', () => {
76
+ test('it returns true for valid rule refs', () => {
77
+ expect(isRuleRef(new RuleRef(1))).toBe(true);
78
+ });
79
+ test('it returns false for invalid rule refs', () => {
80
+ expect(isRuleRef(new RuleChar([65]))).toBe(false);
81
+ });
82
+ });
83
+
84
+ describe('isRuleEnd', () => {
85
+ test('it returns true for valid rule ends', () => {
86
+ expect(isRuleEnd(new RuleEnd())).toBe(true);
87
+ });
88
+ test('it returns false for invalid rule ends', () => {
89
+ expect(isRuleEnd(new RuleChar([65]))).toBe(false);
90
+ });
91
+ });
92
+
93
+ describe('isRuleChar', () => {
94
+ test('it returns true for valid rule chars', () => {
95
+ expect(isRuleChar(new RuleChar([65]))).toBe(true);
96
+ });
97
+ test('it returns false for invalid rule chars', () => {
98
+ expect(isRuleChar(new RuleCharExclude([65]))).toBe(false);
99
+ });
100
+ });
101
+
102
+ describe('isRuleCharExclude', () => {
103
+ test('it returns true for valid rule char excludes', () => {
104
+ expect(isRuleCharExclude(new RuleCharExclude([65]))).toBe(true);
105
+ });
106
+ test('it returns false for invalid rule char excludes', () => {
107
+ expect(isRuleCharExclude(new RuleChar([65]))).toBe(false);
108
+ });
109
+ });
110
+
111
+ describe('isRange', () => {
112
+ test('it returns true for valid ranges', () => {
113
+ expect(isRange([1, 10])).toBe(true);
114
+ });
115
+ test.each<unknown>([[1, '10'], [1], 5, [1, 2, 3]])('it returns false for invalid range %j', (value) => {
116
+ expect(isRange(value)).toBe(false);
117
+ });
118
+ });
119
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-graph/type-guards.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { type Range, RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from './grammar-graph-types.js';
2
+ import type { GraphPointer } from './graph-pointer.js';
3
+ import { RuleRef } from './rule-ref.js';
4
+
5
+ export const isRule = (rule: unknown): rule is UnresolvedRule =>
6
+ rule !== null &&
7
+ rule !== undefined &&
8
+ (rule instanceof RuleChar || rule instanceof RuleCharExclude || rule instanceof RuleEnd || rule instanceof RuleRef);
9
+
10
+ export const isRuleRef = (rule: unknown): rule is RuleRef => rule instanceof RuleRef;
11
+
12
+ export const isRuleEnd = (rule: unknown): rule is RuleEnd => rule instanceof RuleEnd;
13
+
14
+ export const isRuleChar = (rule: unknown): rule is RuleChar => rule instanceof RuleChar;
15
+
16
+ export const isRuleCharExclude = (rule: unknown): rule is RuleCharExclude => rule instanceof RuleCharExclude;
17
+
18
+ export const isRange = (inpt: unknown): inpt is Range =>
19
+ Array.isArray(inpt) && inpt.length === 2 && inpt.every((n) => Number.isInteger(n));
20
+
21
+ export const isGraphPointerRuleRef = (pointer: GraphPointer): pointer is GraphPointer<RuleRef> =>
22
+ isRuleRef(pointer.rule);
23
+
24
+ export const isGraphPointerRuleEnd = (pointer: GraphPointer): pointer is GraphPointer<RuleEnd> =>
25
+ isRuleEnd(pointer.rule);
26
+
27
+ export const isGraphPointerRuleChar = (pointer: GraphPointer): pointer is GraphPointer<RuleChar> =>
28
+ isRuleChar(pointer.rule);
29
+
30
+ export const isGraphPointerRuleCharExclude = (pointer: GraphPointer): pointer is GraphPointer<RuleCharExclude> =>
31
+ isRuleCharExclude(pointer.rule);
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-parser/build-rule-stack.test.ts ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated from the Python unit tests (build_rule_stack_test.py); do not edit by hand.
2
+ import { describe, expect, test } from 'vitest';
3
+ import { RuleChar, RuleCharExclude, RuleEnd } from '../grammar-graph/grammar-graph-types.js';
4
+ import { RuleRef } from '../grammar-graph/rule-ref.js';
5
+ import {
6
+ InternalRuleDefAlt,
7
+ InternalRuleDefChar,
8
+ InternalRuleDefCharAlt,
9
+ InternalRuleDefCharNot,
10
+ InternalRuleDefCharRngUpper,
11
+ InternalRuleDefEnd,
12
+ InternalRuleDefReference,
13
+ } from '../rules-builder/rules-builder-types.js';
14
+ import { buildRuleStack } from './build-rule-stack.js';
15
+
16
+ const ord = (c: string): number => c.codePointAt(0) as number;
17
+ const ichar = (value: number[]) => new InternalRuleDefChar(value);
18
+ const icharAlt = (value: number) => new InternalRuleDefCharAlt(value);
19
+ const icharRngUpper = (value: number) => new InternalRuleDefCharRngUpper(value);
20
+ const icharNot = (value: number[]) => new InternalRuleDefCharNot(value);
21
+ const ialt = () => new InternalRuleDefAlt();
22
+ const iend = () => new InternalRuleDefEnd();
23
+ const iref = (value: number) => new InternalRuleDefReference(value);
24
+
25
+ describe('buildRuleStack', () => {
26
+ test("it builds rule stack for a single path", () => {
27
+ expect(
28
+ buildRuleStack([
29
+ ichar([ord("x")]),
30
+ ]),
31
+ ).toStrictEqual([
32
+ [
33
+ new RuleChar([ord("x")]),
34
+ new RuleEnd(),
35
+ ],
36
+ ]);
37
+ });
38
+
39
+ test("it builds rule stack for two alternate paths", () => {
40
+ expect(
41
+ buildRuleStack([
42
+ ichar([ord("x")]),
43
+ ialt(),
44
+ ichar([ord("y")]),
45
+ ]),
46
+ ).toStrictEqual([
47
+ [
48
+ new RuleChar([ord("x")]),
49
+ new RuleEnd(),
50
+ ],
51
+ [
52
+ new RuleChar([ord("y")]),
53
+ new RuleEnd(),
54
+ ],
55
+ ]);
56
+ });
57
+
58
+ test("it builds rule stack for three alternate paths", () => {
59
+ expect(
60
+ buildRuleStack([
61
+ ichar([ord("x")]),
62
+ ialt(),
63
+ ichar([ord("y")]),
64
+ ialt(),
65
+ ichar([ord("z")]),
66
+ ]),
67
+ ).toStrictEqual([
68
+ [
69
+ new RuleChar([ord("x")]),
70
+ new RuleEnd(),
71
+ ],
72
+ [
73
+ new RuleChar([ord("y")]),
74
+ new RuleEnd(),
75
+ ],
76
+ [
77
+ new RuleChar([ord("z")]),
78
+ new RuleEnd(),
79
+ ],
80
+ ]);
81
+ });
82
+
83
+ test("it builds rule stack for char not", () => {
84
+ expect(
85
+ buildRuleStack([
86
+ icharNot([ord("x")]),
87
+ ialt(),
88
+ icharNot([ord("y")]),
89
+ ialt(),
90
+ icharNot([ord("z")]),
91
+ ]),
92
+ ).toStrictEqual([
93
+ [
94
+ new RuleCharExclude([ord("x")]),
95
+ new RuleEnd(),
96
+ ],
97
+ [
98
+ new RuleCharExclude([ord("y")]),
99
+ new RuleEnd(),
100
+ ],
101
+ [
102
+ new RuleCharExclude([ord("z")]),
103
+ new RuleEnd(),
104
+ ],
105
+ ]);
106
+ });
107
+
108
+ test("it builds rule stack for mixed char and char not", () => {
109
+ expect(
110
+ buildRuleStack([
111
+ icharNot([ord("x")]),
112
+ ialt(),
113
+ ichar([ord("y")]),
114
+ ialt(),
115
+ icharNot([ord("z")]),
116
+ ]),
117
+ ).toStrictEqual([
118
+ [
119
+ new RuleCharExclude([ord("x")]),
120
+ new RuleEnd(),
121
+ ],
122
+ [
123
+ new RuleChar([ord("y")]),
124
+ new RuleEnd(),
125
+ ],
126
+ [
127
+ new RuleCharExclude([ord("z")]),
128
+ new RuleEnd(),
129
+ ],
130
+ ]);
131
+ });
132
+
133
+ test("it builds rule stack for char not with two characters and a range", () => {
134
+ expect(
135
+ buildRuleStack([
136
+ icharNot([ord("x")]),
137
+ icharAlt(ord("y")),
138
+ icharAlt(ord("z")),
139
+ icharRngUpper(130),
140
+ ]),
141
+ ).toStrictEqual([
142
+ [
143
+ new RuleCharExclude([ord("x"), ord("y"), [ord("z"), 130]]),
144
+ new RuleEnd(),
145
+ ],
146
+ ]);
147
+ });
148
+
149
+ test("it builds rule stack for a char with no modifiers ([a)", () => {
150
+ expect(
151
+ buildRuleStack([
152
+ ichar([ord("a")]),
153
+ icharRngUpper(ord("z")),
154
+ iend(),
155
+ ]),
156
+ ).toStrictEqual([
157
+ [
158
+ new RuleChar([[ord("a"), ord("z")]]),
159
+ new RuleEnd(),
160
+ ],
161
+ ]);
162
+ });
163
+
164
+ test("it builds rule stack for a char with no modifiers ([a)", () => {
165
+ expect(
166
+ buildRuleStack([
167
+ ichar([ord("a")]),
168
+ icharRngUpper(ord("z")),
169
+ icharAlt(ord("A")),
170
+ icharRngUpper(ord("Z")),
171
+ iend(),
172
+ ]),
173
+ ).toStrictEqual([
174
+ [
175
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")]]),
176
+ new RuleEnd(),
177
+ ],
178
+ ]);
179
+ });
180
+
181
+ test("it builds rule stack for a char with no modifiers ([a)", () => {
182
+ expect(
183
+ buildRuleStack([
184
+ ichar([ord("a")]),
185
+ icharRngUpper(ord("z")),
186
+ icharAlt(ord("A")),
187
+ icharRngUpper(ord("Z")),
188
+ icharAlt(ord("0")),
189
+ icharRngUpper(ord("9")),
190
+ iend(),
191
+ ]),
192
+ ).toStrictEqual([
193
+ [
194
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")], [ord("0"), ord("9")]]),
195
+ new RuleEnd(),
196
+ ],
197
+ ]);
198
+ });
199
+
200
+ test("it builds rule stack for a char with question mark modifier ([a)", () => {
201
+ expect(
202
+ buildRuleStack([
203
+ ichar([ord("a")]),
204
+ icharRngUpper(ord("z")),
205
+ ialt(),
206
+ iend(),
207
+ ]),
208
+ ).toStrictEqual([
209
+ [
210
+ new RuleChar([[ord("a"), ord("z")]]),
211
+ new RuleEnd(),
212
+ ],
213
+ [
214
+ new RuleEnd(),
215
+ ],
216
+ ]);
217
+ });
218
+
219
+ test("it builds rule stack for a char with question mark modifier ([a)", () => {
220
+ expect(
221
+ buildRuleStack([
222
+ ichar([ord("a")]),
223
+ icharRngUpper(ord("z")),
224
+ icharAlt(ord("A")),
225
+ icharRngUpper(ord("Z")),
226
+ ialt(),
227
+ iend(),
228
+ ]),
229
+ ).toStrictEqual([
230
+ [
231
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")]]),
232
+ new RuleEnd(),
233
+ ],
234
+ [
235
+ new RuleEnd(),
236
+ ],
237
+ ]);
238
+ });
239
+
240
+ test("it builds rule stack for a char with question mark modifier ([a)", () => {
241
+ expect(
242
+ buildRuleStack([
243
+ ichar([ord("a")]),
244
+ icharRngUpper(ord("z")),
245
+ icharAlt(ord("A")),
246
+ icharRngUpper(ord("Z")),
247
+ icharAlt(ord("0")),
248
+ icharRngUpper(ord("9")),
249
+ ialt(),
250
+ iend(),
251
+ ]),
252
+ ).toStrictEqual([
253
+ [
254
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")], [ord("0"), ord("9")]]),
255
+ new RuleEnd(),
256
+ ],
257
+ [
258
+ new RuleEnd(),
259
+ ],
260
+ ]);
261
+ });
262
+
263
+ test("it builds rule stack for a char with plus modifier ([a)", () => {
264
+ expect(
265
+ buildRuleStack([
266
+ ichar([ord("a")]),
267
+ icharRngUpper(ord("z")),
268
+ iref(1),
269
+ ialt(),
270
+ ichar([ord("a")]),
271
+ icharRngUpper(ord("z")),
272
+ iend(),
273
+ ]),
274
+ ).toStrictEqual([
275
+ [
276
+ new RuleChar([[ord("a"), ord("z")]]),
277
+ new RuleRef(1),
278
+ new RuleEnd(),
279
+ ],
280
+ [
281
+ new RuleChar([[ord("a"), ord("z")]]),
282
+ new RuleEnd(),
283
+ ],
284
+ ]);
285
+ });
286
+
287
+ test("it builds rule stack for a char with plus modifier ([a)", () => {
288
+ expect(
289
+ buildRuleStack([
290
+ ichar([ord("a")]),
291
+ icharRngUpper(ord("z")),
292
+ icharAlt(ord("A")),
293
+ icharRngUpper(ord("Z")),
294
+ iref(1),
295
+ ialt(),
296
+ ichar([ord("a")]),
297
+ icharRngUpper(ord("z")),
298
+ icharAlt(ord("A")),
299
+ icharRngUpper(ord("Z")),
300
+ iend(),
301
+ ]),
302
+ ).toStrictEqual([
303
+ [
304
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")]]),
305
+ new RuleRef(1),
306
+ new RuleEnd(),
307
+ ],
308
+ [
309
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")]]),
310
+ new RuleEnd(),
311
+ ],
312
+ ]);
313
+ });
314
+
315
+ test("it builds rule stack for a char with plus modifier ([a)", () => {
316
+ expect(
317
+ buildRuleStack([
318
+ ichar([ord("a")]),
319
+ icharRngUpper(ord("z")),
320
+ icharAlt(ord("A")),
321
+ icharRngUpper(ord("Z")),
322
+ icharAlt(ord("0")),
323
+ icharRngUpper(ord("9")),
324
+ iref(1),
325
+ ialt(),
326
+ ichar([ord("a")]),
327
+ icharRngUpper(ord("z")),
328
+ icharAlt(ord("A")),
329
+ icharRngUpper(ord("Z")),
330
+ icharAlt(ord("0")),
331
+ icharRngUpper(ord("9")),
332
+ iend(),
333
+ ]),
334
+ ).toStrictEqual([
335
+ [
336
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")], [ord("0"), ord("9")]]),
337
+ new RuleRef(1),
338
+ new RuleEnd(),
339
+ ],
340
+ [
341
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")], [ord("0"), ord("9")]]),
342
+ new RuleEnd(),
343
+ ],
344
+ ]);
345
+ });
346
+
347
+ test("it builds rule stack for a char with asterisk modifier ([a)", () => {
348
+ expect(
349
+ buildRuleStack([
350
+ ichar([ord("a")]),
351
+ icharRngUpper(ord("z")),
352
+ iref(1),
353
+ ialt(),
354
+ iend(),
355
+ ]),
356
+ ).toStrictEqual([
357
+ [
358
+ new RuleChar([[ord("a"), ord("z")]]),
359
+ new RuleRef(1),
360
+ new RuleEnd(),
361
+ ],
362
+ [
363
+ new RuleEnd(),
364
+ ],
365
+ ]);
366
+ });
367
+
368
+ test("it builds rule stack for a char with asterisk modifier ([a)", () => {
369
+ expect(
370
+ buildRuleStack([
371
+ ichar([ord("a")]),
372
+ icharRngUpper(ord("z")),
373
+ icharAlt(ord("A")),
374
+ icharRngUpper(ord("Z")),
375
+ iref(1),
376
+ ialt(),
377
+ iend(),
378
+ ]),
379
+ ).toStrictEqual([
380
+ [
381
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")]]),
382
+ new RuleRef(1),
383
+ new RuleEnd(),
384
+ ],
385
+ [
386
+ new RuleEnd(),
387
+ ],
388
+ ]);
389
+ });
390
+
391
+ test("it builds rule stack for a char with asterisk modifier ([a)", () => {
392
+ expect(
393
+ buildRuleStack([
394
+ ichar([ord("a")]),
395
+ icharRngUpper(ord("z")),
396
+ icharAlt(ord("A")),
397
+ icharRngUpper(ord("Z")),
398
+ icharAlt(ord("0")),
399
+ icharRngUpper(ord("9")),
400
+ iref(1),
401
+ ialt(),
402
+ iend(),
403
+ ]),
404
+ ).toStrictEqual([
405
+ [
406
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")], [ord("0"), ord("9")]]),
407
+ new RuleRef(1),
408
+ new RuleEnd(),
409
+ ],
410
+ [
411
+ new RuleEnd(),
412
+ ],
413
+ ]);
414
+ });
415
+
416
+ test("char with range", () => {
417
+ expect(
418
+ buildRuleStack([
419
+ ichar([ord("a")]),
420
+ icharRngUpper(ord("z")),
421
+ icharAlt(ord("A")),
422
+ icharRngUpper(ord("Z")),
423
+ icharAlt(ord("_")),
424
+ iend(),
425
+ ]),
426
+ ).toStrictEqual([
427
+ [
428
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")], ord("_")]),
429
+ new RuleEnd(),
430
+ ],
431
+ ]);
432
+ });
433
+
434
+ test("it builds rule stack for situation root ws plus newline ws star", () => {
435
+ expect(
436
+ buildRuleStack([
437
+ ichar([32]),
438
+ icharAlt(92),
439
+ icharAlt(ord("n")),
440
+ iref(4),
441
+ ialt(),
442
+ iend(),
443
+ ]),
444
+ ).toStrictEqual([
445
+ [
446
+ new RuleChar([32, 92, ord("n")]),
447
+ new RuleRef(4),
448
+ new RuleEnd(),
449
+ ],
450
+ [
451
+ new RuleEnd(),
452
+ ],
453
+ ]);
454
+ });
455
+
456
+ test("it builds rule stack for situation root char plus char range", () => {
457
+ expect(
458
+ buildRuleStack([
459
+ ichar([ord("a")]),
460
+ icharRngUpper(ord("z")),
461
+ icharAlt(ord("A")),
462
+ icharRngUpper(ord("Z")),
463
+ iref(1),
464
+ ialt(),
465
+ ichar([ord("a")]),
466
+ icharRngUpper(ord("z")),
467
+ icharAlt(ord("A")),
468
+ icharRngUpper(ord("Z")),
469
+ iend(),
470
+ ]),
471
+ ).toStrictEqual([
472
+ [
473
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")]]),
474
+ new RuleRef(1),
475
+ new RuleEnd(),
476
+ ],
477
+ [
478
+ new RuleChar([[ord("a"), ord("z")], [ord("A"), ord("Z")]]),
479
+ new RuleEnd(),
480
+ ],
481
+ ]);
482
+ });
483
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/grammar-parser/build-rule-stack.ts ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { type Range, RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from '../grammar-graph/grammar-graph-types.js';
2
+ import { RuleRef } from '../grammar-graph/rule-ref.js';
3
+ import { isRange, isRuleEnd } from '../grammar-graph/type-guards.js';
4
+ import {
5
+ type InternalRuleDef,
6
+ type InternalRuleDefChar,
7
+ type InternalRuleDefCharNot,
8
+ isRuleDefAlt,
9
+ isRuleDefChar,
10
+ isRuleDefCharAlt,
11
+ isRuleDefCharNot,
12
+ isRuleDefCharRngUpper,
13
+ isRuleDefEnd,
14
+ isRuleDefRef,
15
+ } from '../rules-builder/rules-builder-types.js';
16
+
17
+ export const makeCharRule = (ruleDef: InternalRuleDefChar | InternalRuleDefCharNot): RuleChar | RuleCharExclude => {
18
+ const value: (number | Range)[] = [...ruleDef.value];
19
+ if (isRuleDefCharNot(ruleDef)) {
20
+ return new RuleCharExclude(value);
21
+ }
22
+ if (isRuleDefChar(ruleDef)) {
23
+ return new RuleChar(value);
24
+ }
25
+ throw new Error(`Unsupported rule type for make_char_rule: ${JSON.stringify(ruleDef)}`);
26
+ };
27
+
28
+ export const buildRuleStack = (linearRules: InternalRuleDef[]): UnresolvedRule[][] => {
29
+ let paths: UnresolvedRule[] = [];
30
+ const stack: UnresolvedRule[][] = [];
31
+ let idx = 0;
32
+
33
+ while (idx < linearRules.length) {
34
+ const ruleDef = linearRules[idx];
35
+ if (isRuleDefChar(ruleDef) || isRuleDefCharNot(ruleDef)) {
36
+ // this could be a single char, or a range, or a sequence of alts; we don't know until we step through it.
37
+ const charRule = makeCharRule(ruleDef);
38
+ idx += 1;
39
+ let rule: InternalRuleDef | undefined = linearRules[idx];
40
+ while (idx < linearRules.length && (isRuleDefCharRngUpper(rule) || isRuleDefCharAlt(rule))) {
41
+ if (isRuleDefCharRngUpper(rule)) {
42
+ // previous rule value should be a number
43
+ const prevValue = charRule.value.pop();
44
+ if (isRange(prevValue)) {
45
+ throw new Error(`Unexpected range, expected a number but got an array: ${JSON.stringify(prevValue)}`);
46
+ }
47
+ if (prevValue === undefined) {
48
+ throw new Error('Unexpected undefined value');
49
+ }
50
+ charRule.value.push([prevValue, rule.value]);
51
+ }
52
+ if (isRuleDefCharAlt(rule)) {
53
+ charRule.value.push(rule.value);
54
+ }
55
+ idx += 1;
56
+ rule = linearRules[idx];
57
+ }
58
+ paths.push(charRule);
59
+ } else {
60
+ if (isRuleDefAlt(ruleDef)) {
61
+ if (paths.length === 0) {
62
+ throw new Error('Encountered alt without anything before it');
63
+ }
64
+ paths.push(new RuleEnd());
65
+ stack.push(paths);
66
+ paths = [];
67
+ } else if (isRuleDefEnd(ruleDef)) {
68
+ paths.push(new RuleEnd());
69
+ } else if (isRuleDefRef(ruleDef)) {
70
+ paths.push(new RuleRef(ruleDef.value));
71
+ } else if (isRuleDefCharAlt(ruleDef)) {
72
+ throw new Error(`Encountered char alt, should be handled by above block: ${JSON.stringify(ruleDef)}`);
73
+ } else {
74
+ throw new Error(`Unsupported rule type: ${JSON.stringify(ruleDef)}`);
75
+ }
76
+ idx += 1;
77
+ }
78
+ }
79
+
80
+ if (paths.length === 0 || !isRuleEnd(paths[paths.length - 1])) {
81
+ paths.push(new RuleEnd());
82
+ }
83
+
84
+ stack.push(paths);
85
+ return stack;
86
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/index.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import { GBNF } from './GBNF.js';
2
+
3
+ export { GBNF };
4
+ export default GBNF;
5
+ export { RuleChar, RuleCharExclude, RuleEnd, RuleType } from './grammar-graph/grammar-graph-types.js';
6
+ export type { Range, ResolvedRule, ValidInput } from './grammar-graph/grammar-graph-types.js';
7
+ export { ParseState } from './grammar-graph/parse-state.js';
8
+ export { GrammarParseError, InputParseError } from './utils/errors/index.js';
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/index.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export { RulesBuilder } from './rules-builder.js';
2
+ export { GrammarParseError, InputParseError } from '../utils/errors/index.js';
3
+ export * from './rules-builder-types.js';
4
+ export { SymbolIds } from './symbol-ids.js';
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/is-word-char.test.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { isWordChar } from './is-word-char.js';
3
+
4
+ describe('isWordChar', () => {
5
+ test('it returns true for lowercase letters', () => {
6
+ expect(isWordChar('a')).toBe(true);
7
+ expect(isWordChar('z')).toBe(true);
8
+ });
9
+
10
+ test('it returns true for uppercase letters', () => {
11
+ expect(isWordChar('A')).toBe(true);
12
+ expect(isWordChar('Z')).toBe(true);
13
+ });
14
+
15
+ test('it returns false for digits', () => {
16
+ expect(isWordChar('0')).toBe(false);
17
+ expect(isWordChar('9')).toBe(false);
18
+ });
19
+
20
+ test('it returns false for non word characters', () => {
21
+ for (const c of ['-', '@', '_', '?', ' ']) {
22
+ expect(isWordChar(c)).toBe(false);
23
+ }
24
+ });
25
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/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);
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-char.test.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { GrammarParseError } from '../utils/errors/index.js';
3
+ import { parseChar } from './parse-char.js';
4
+
5
+ const ord = (c: string): number => c.codePointAt(0) as number;
6
+
7
+ describe('parseChar', () => {
8
+ test.each<[string, string, number]>([
9
+ ['unescaped letter', 'a', ord('a')],
10
+ ['unescaped digit', '9', ord('9')],
11
+ ])('it parses a simple char (%s)', (_description, char, codePoint) => {
12
+ const grammar = `root ::= "${char}" "foo"`;
13
+ expect(parseChar(grammar, 'root ::= "'.length)).toEqual([codePoint, 1]);
14
+ });
15
+
16
+ test.each<[string, string, number, number]>([
17
+ ['escaped 8-bit unicode char', '\\x2A', ord('\x2A'), 4],
18
+ ['escaped 16-bit unicode char', '\\u006F', ord('\u006F'), 6],
19
+ ['escaped 32-bit unicode char', '\\U0001F4A9', 128169, 10],
20
+ ['escaped tab char', '\\t', ord('\t'), 2],
21
+ ['escaped new line char', '\\n', ord('\n'), 2],
22
+ ['escaped \\r char', '\\r', ord('\r'), 2],
23
+ ['escaped quote char', '\\"', ord('"'), 2],
24
+ ['escaped [ char', '\\[', ord('['), 2],
25
+ ['escaped ] char', '\\]', ord(']'), 2],
26
+ ['escaped \\ char', '\\\\', ord('\\'), 2],
27
+ ])('it parses a complex char (%s)', (_description, escapedChar, codePoint, incPos) => {
28
+ const grammar = `root ::= "${escapedChar}" "foo"`;
29
+ expect(parseChar(grammar, 'root ::= "'.length)).toEqual([codePoint, incPos]);
30
+ });
31
+
32
+ test('it parses an astral character as a single code point', () => {
33
+ expect(parseChar('💩', 0)).toEqual([128169, 2]);
34
+ });
35
+
36
+ test.each<[string, number]>([
37
+ ['', 0],
38
+ ['a', 1],
39
+ ['a', 2],
40
+ ])('it throws for input %j at pos %i', (input, pos) => {
41
+ expect(() => parseChar(input, pos)).toThrow(GrammarParseError);
42
+ });
43
+
44
+ test('it throws for an unknown escape', () => {
45
+ expect(() => parseChar('\\q', 0)).toThrow(GrammarParseError);
46
+ });
47
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-char.ts ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GrammarParseError } from '../utils/errors/index.js';
2
+
3
+ const SIMPLE_ESCAPES: Record<string, number> = {
4
+ t: '\t'.charCodeAt(0),
5
+ r: '\r'.charCodeAt(0),
6
+ n: '\n'.charCodeAt(0),
7
+ '"': '"'.charCodeAt(0),
8
+ '[': '['.charCodeAt(0),
9
+ ']': ']'.charCodeAt(0),
10
+ '\\': '\\'.charCodeAt(0),
11
+ };
12
+
13
+ const parseHex = (src: string, pos: number, start: number, end: number): number => {
14
+ const hex = src.slice(pos + start, pos + end);
15
+ if (hex.length !== end - start || !/^[0-9a-fA-F]+$/.test(hex)) {
16
+ throw new GrammarParseError(src, pos, `Invalid hex escape at ${pos}`);
17
+ }
18
+ return parseInt(hex, 16);
19
+ };
20
+
21
+ // Returns the code point at `pos` along with the number of characters consumed.
22
+ export const parseChar = (src: string, pos: number): [number, number] => {
23
+ if (pos >= src.length) {
24
+ throw new GrammarParseError(src, pos, 'Unexpected end of grammar input, failed to complete parse');
25
+ }
26
+
27
+ if (src[pos] === '\\') {
28
+ const next = src[pos + 1];
29
+ if (next === 'x') {
30
+ return [parseHex(src, pos, 2, 4), 4];
31
+ }
32
+ if (next === 'u') {
33
+ return [parseHex(src, pos, 2, 6), 6];
34
+ }
35
+ if (next === 'U') {
36
+ return [parseHex(src, pos, 2, 10), 10];
37
+ }
38
+ if (next !== undefined && next in SIMPLE_ESCAPES) {
39
+ return [SIMPLE_ESCAPES[next], 2];
40
+ }
41
+ throw new GrammarParseError(src, pos, `Unknown escape at ${src[pos]}`);
42
+ }
43
+
44
+ // Use code points so that astral characters in the grammar are handled as a single unit.
45
+ const codePoint = src.codePointAt(pos);
46
+ if (codePoint === undefined) {
47
+ throw new GrammarParseError(src, pos, 'Unexpected end of grammar input, failed to complete parse');
48
+ }
49
+ return [codePoint, codePoint > 0xffff ? 2 : 1];
50
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-name.test.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { GrammarParseError } from '../utils/errors/index.js';
3
+ import { PARSE_NAME_ERROR, parseName } from './parse-name.js';
4
+
5
+ describe('parseName', () => {
6
+ test('it returns the correct name when encountering a valid name', () => {
7
+ expect(parseName('validName', 0)).toBe('validName');
8
+ });
9
+
10
+ test('it returns the correct name when starting at a non-zero position', () => {
11
+ expect(parseName('123validName', 3)).toBe('validName');
12
+ });
13
+
14
+ test('it throws an error when encountering an invalid name', () => {
15
+ const src = '123';
16
+ let err: unknown;
17
+ try {
18
+ parseName(src, 0);
19
+ } catch (e) {
20
+ err = e;
21
+ }
22
+ expect(err).toBeInstanceOf(GrammarParseError);
23
+ expect(String(err)).toBe(String(new GrammarParseError(src, 0, PARSE_NAME_ERROR)));
24
+ });
25
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-name.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (pos < grammar.length && (isWordChar(grammar[pos]) || VALID_NAME_SEPARATORS.includes(grammar[pos]))) {
11
+ name += grammar[pos];
12
+ pos += 1;
13
+ }
14
+ if (!name) {
15
+ throw new GrammarParseError(grammar, pos, PARSE_NAME_ERROR);
16
+ }
17
+ return name;
18
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-space.test.ts ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { parseSpace } from './parse-space.js';
3
+
4
+ describe('parseSpace', () => {
5
+ test.each<[string, string, boolean, string]>([
6
+ ['returns input string when no whitespace or comments', 'abcdefghijk', true, 'abcdefghijk'],
7
+ ['skips leading spaces and tabs', ' \t abcdefghijk', true, 'abcdefghijk'],
8
+ ['skips leading newline characters when newlineOk is true', '\n\n\r\n\r\nabcdefghijk', true, 'abcdefghijk'],
9
+ [
10
+ 'does not skip leading newline characters when newlineOk is false',
11
+ '\n\n\r\n\r\nabcdefghijk',
12
+ false,
13
+ '\n\n\r\n\r\nabcdefghijk',
14
+ ],
15
+ ['skips comments and leading spaces', ' # This is a comment\n\t abcdefghijk', true, 'abcdefghijk'],
16
+ [
17
+ 'skips comments and leading newline characters when newlineOk is true',
18
+ '\n\n # This is a comment\n\r\n\r\nabcdefghijk',
19
+ true,
20
+ 'abcdefghijk',
21
+ ],
22
+ [
23
+ 'does not skip comments and leading newline characters when newlineOk is false',
24
+ '\n\n # This is a comment\n\r\n\r\nabcdefghijk',
25
+ false,
26
+ '\n\n # This is a comment\n\r\n\r\nabcdefghijk',
27
+ ],
28
+ ['returns empty string if input is all whitespace and comments', ' \t# Comment\n# Another comment\n\n', true, ''],
29
+ ['returns empty string for empty input string', '', true, ''],
30
+ ])('it %s', (_description, input, newlineOk, expected) => {
31
+ const pos = parseSpace(input, 0, newlineOk);
32
+ expect(input.slice(pos)).toBe(expected);
33
+ });
34
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/parse-space.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const parseSpace = (src: string, pos: number, newlineOk: boolean): number => {
2
+ while (
3
+ pos < src.length &&
4
+ (src[pos] === ' ' ||
5
+ src[pos] === '\t' ||
6
+ src[pos] === '#' ||
7
+ (newlineOk && (src[pos] === '\r' || src[pos] === '\n')))
8
+ ) {
9
+ if (src[pos] === '#') {
10
+ while (pos < src.length && src[pos] !== '\r' && src[pos] !== '\n') {
11
+ pos += 1;
12
+ }
13
+ } else {
14
+ pos += 1;
15
+ }
16
+ }
17
+ return pos;
18
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/rules-builder-types.ts ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { validateNonEmpty } from '../utils/validate-non-empty.js';
2
+
3
+ export enum InternalRuleType {
4
+ CHAR = 'CHAR',
5
+ CHAR_NOT = 'CHAR_NOT',
6
+ CHAR_ALT = 'CHAR_ALT',
7
+ CHAR_RNG_UPPER = 'CHAR_RNG_UPPER',
8
+ ALT = 'ALT',
9
+ END = 'END',
10
+ RULE_REF = 'RULE_REF',
11
+ }
12
+
13
+ export class InternalRuleDefChar {
14
+ readonly type = InternalRuleType.CHAR;
15
+ value: number[];
16
+ constructor(value: number[]) {
17
+ this.value = [...validateNonEmpty(value)];
18
+ }
19
+ }
20
+
21
+ export class InternalRuleDefCharNot {
22
+ readonly type = InternalRuleType.CHAR_NOT;
23
+ value: number[];
24
+ constructor(value: number[]) {
25
+ this.value = [...validateNonEmpty(value)];
26
+ }
27
+ }
28
+
29
+ export class InternalRuleDefCharAlt {
30
+ readonly type = InternalRuleType.CHAR_ALT;
31
+ value: number;
32
+ constructor(value: number) {
33
+ this.value = value;
34
+ }
35
+ }
36
+
37
+ export class InternalRuleDefCharRngUpper {
38
+ readonly type = InternalRuleType.CHAR_RNG_UPPER;
39
+ value: number;
40
+ constructor(value: number) {
41
+ this.value = value;
42
+ }
43
+ }
44
+
45
+ export class InternalRuleDefReference {
46
+ readonly type = InternalRuleType.RULE_REF;
47
+ value: number;
48
+ constructor(value: number) {
49
+ this.value = value;
50
+ }
51
+ }
52
+
53
+ export class InternalRuleDefAlt {
54
+ readonly type = InternalRuleType.ALT;
55
+ }
56
+
57
+ export class InternalRuleDefEnd {
58
+ readonly type = InternalRuleType.END;
59
+ }
60
+
61
+ export type InternalRuleDef =
62
+ | InternalRuleDefChar
63
+ | InternalRuleDefCharNot
64
+ | InternalRuleDefCharAlt
65
+ | InternalRuleDefCharRngUpper
66
+ | InternalRuleDefReference
67
+ | InternalRuleDefAlt
68
+ | InternalRuleDefEnd;
69
+
70
+ export type InternalRuleDefCharOrAltChar = InternalRuleDefChar | InternalRuleDefCharAlt;
71
+
72
+ export const isRuleDefAlt = (rule: unknown): rule is InternalRuleDefAlt => rule instanceof InternalRuleDefAlt;
73
+ export const isRuleDefRef = (rule: unknown): rule is InternalRuleDefReference =>
74
+ rule instanceof InternalRuleDefReference;
75
+ export const isRuleDefEnd = (rule: unknown): rule is InternalRuleDefEnd => rule instanceof InternalRuleDefEnd;
76
+ export const isRuleDefChar = (rule: unknown): rule is InternalRuleDefChar => rule instanceof InternalRuleDefChar;
77
+ export const isRuleDefCharNot = (rule: unknown): rule is InternalRuleDefCharNot =>
78
+ rule instanceof InternalRuleDefCharNot;
79
+ export const isRuleDefCharAlt = (rule: unknown): rule is InternalRuleDefCharAlt =>
80
+ rule instanceof InternalRuleDefCharAlt;
81
+ export const isRuleDefCharRngUpper = (rule: unknown): rule is InternalRuleDefCharRngUpper =>
82
+ rule instanceof InternalRuleDefCharRngUpper;
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/rules-builder.test.ts ADDED
@@ -0,0 +1,1411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated from the Python unit tests (rules_builder_test.py); do not edit by hand.
2
+ import { describe, expect, test } from 'vitest';
3
+ import { RulesBuilder } from './rules-builder.js';
4
+ import {
5
+ type InternalRuleDef,
6
+ InternalRuleDefAlt,
7
+ InternalRuleDefChar,
8
+ InternalRuleDefCharAlt,
9
+ InternalRuleDefCharNot,
10
+ InternalRuleDefCharRngUpper,
11
+ InternalRuleDefEnd,
12
+ InternalRuleDefReference,
13
+ } from './rules-builder-types.js';
14
+
15
+ const ord = (c: string): number => c.codePointAt(0) as number;
16
+
17
+ type TestCase = [key: string, grammar: string, expected: [symbolIds: [string, number][], rules: InternalRuleDef[][]]];
18
+
19
+ const testCases: TestCase[] = [
20
+ [
21
+ "single-string",
22
+ "root ::= \"foo\"",
23
+ [
24
+ [["root", 0]],
25
+ [
26
+ [
27
+ new InternalRuleDefChar([ord("f")]),
28
+ new InternalRuleDefChar([ord("o")]),
29
+ new InternalRuleDefChar([ord("o")]),
30
+ new InternalRuleDefEnd(),
31
+ ],
32
+ ],
33
+ ],
34
+ ],
35
+ [
36
+ "quote character",
37
+ "root ::= \"\\\"\"",
38
+ [
39
+ [["root", 0]],
40
+ [
41
+ [
42
+ new InternalRuleDefChar([34]),
43
+ new InternalRuleDefEnd(),
44
+ ],
45
+ ],
46
+ ],
47
+ ],
48
+ [
49
+ "two-lines-referencing-expression",
50
+ "root ::= foo\n foo ::= \"bar\"",
51
+ [
52
+ [["root", 0], ["foo", 1]],
53
+ [
54
+ [
55
+ new InternalRuleDefReference(1),
56
+ new InternalRuleDefEnd(),
57
+ ],
58
+ [
59
+ new InternalRuleDefChar([ord("b")]),
60
+ new InternalRuleDefChar([ord("a")]),
61
+ new InternalRuleDefChar([ord("r")]),
62
+ new InternalRuleDefEnd(),
63
+ ],
64
+ ],
65
+ ],
66
+ ],
67
+ [
68
+ "expression with dash",
69
+ "root ::= foo-bar\n foo-bar ::= \"bar\"",
70
+ [
71
+ [["root", 0], ["foo-bar", 1]],
72
+ [
73
+ [
74
+ new InternalRuleDefReference(1),
75
+ new InternalRuleDefEnd(),
76
+ ],
77
+ [
78
+ new InternalRuleDefChar([ord("b")]),
79
+ new InternalRuleDefChar([ord("a")]),
80
+ new InternalRuleDefChar([ord("r")]),
81
+ new InternalRuleDefEnd(),
82
+ ],
83
+ ],
84
+ ],
85
+ ],
86
+ [
87
+ "simple-grammar",
88
+ "\n root ::= (expr \"=\" term \"\n\")+\n expr ::= term ([-+*/] term)*\n term ::= [0-9]+\n ",
89
+ [
90
+ [["root", 0], ["root_1", 1], ["expr", 2], ["term", 3], ["root_4", 4], ["expr_5", 5], ["expr_6", 6], ["term_7", 7]],
91
+ [
92
+ [
93
+ new InternalRuleDefReference(4),
94
+ new InternalRuleDefEnd(),
95
+ ],
96
+ [
97
+ new InternalRuleDefReference(2),
98
+ new InternalRuleDefChar([ord("=")]),
99
+ new InternalRuleDefReference(3),
100
+ new InternalRuleDefChar([10]),
101
+ new InternalRuleDefEnd(),
102
+ ],
103
+ [
104
+ new InternalRuleDefReference(3),
105
+ new InternalRuleDefReference(6),
106
+ new InternalRuleDefEnd(),
107
+ ],
108
+ [
109
+ new InternalRuleDefReference(7),
110
+ new InternalRuleDefEnd(),
111
+ ],
112
+ [
113
+ new InternalRuleDefReference(1),
114
+ new InternalRuleDefReference(4),
115
+ new InternalRuleDefAlt(),
116
+ new InternalRuleDefReference(1),
117
+ new InternalRuleDefEnd(),
118
+ ],
119
+ [
120
+ new InternalRuleDefChar([ord("-")]),
121
+ new InternalRuleDefCharAlt(ord("+")),
122
+ new InternalRuleDefCharAlt(ord("*")),
123
+ new InternalRuleDefCharAlt(ord("/")),
124
+ new InternalRuleDefReference(3),
125
+ new InternalRuleDefEnd(),
126
+ ],
127
+ [
128
+ new InternalRuleDefReference(5),
129
+ new InternalRuleDefReference(6),
130
+ new InternalRuleDefAlt(),
131
+ new InternalRuleDefEnd(),
132
+ ],
133
+ [
134
+ new InternalRuleDefChar([ord("0")]),
135
+ new InternalRuleDefCharRngUpper(ord("9")),
136
+ new InternalRuleDefReference(7),
137
+ new InternalRuleDefAlt(),
138
+ new InternalRuleDefChar([ord("0")]),
139
+ new InternalRuleDefCharRngUpper(ord("9")),
140
+ new InternalRuleDefEnd(),
141
+ ],
142
+ ],
143
+ ],
144
+ ],
145
+ [
146
+ "longer-grammar",
147
+ "\n root ::= (expr \"=\" ws term \"\n\")+\n expr ::= term ([-+*/] term)*\n term ::= ident | num | \"(\" ws expr \")\" ws\n ident ::= [a-z] [a-z0-9_]* ws\n num ::= [0-9]+ ws\n ws ::= [ \t\n]*\n ",
148
+ [
149
+ [["root", 0], ["root_1", 1], ["expr", 2], ["ws", 3], ["term", 4], ["root_5", 5], ["expr_6", 6], ["expr_7", 7], ["ident", 8], ["num", 9], ["ident_10", 10], ["num_11", 11], ["ws_12", 12]],
150
+ [
151
+ [
152
+ new InternalRuleDefReference(5),
153
+ new InternalRuleDefEnd(),
154
+ ],
155
+ [
156
+ new InternalRuleDefReference(2),
157
+ new InternalRuleDefChar([ord("=")]),
158
+ new InternalRuleDefReference(3),
159
+ new InternalRuleDefReference(4),
160
+ new InternalRuleDefChar([10]),
161
+ new InternalRuleDefEnd(),
162
+ ],
163
+ [
164
+ new InternalRuleDefReference(4),
165
+ new InternalRuleDefReference(7),
166
+ new InternalRuleDefEnd(),
167
+ ],
168
+ [
169
+ new InternalRuleDefReference(12),
170
+ new InternalRuleDefEnd(),
171
+ ],
172
+ [
173
+ new InternalRuleDefReference(8),
174
+ new InternalRuleDefAlt(),
175
+ new InternalRuleDefReference(9),
176
+ new InternalRuleDefAlt(),
177
+ new InternalRuleDefChar([ord("(")]),
178
+ new InternalRuleDefReference(3),
179
+ new InternalRuleDefReference(2),
180
+ new InternalRuleDefChar([ord(")")]),
181
+ new InternalRuleDefReference(3),
182
+ new InternalRuleDefEnd(),
183
+ ],
184
+ [
185
+ new InternalRuleDefReference(1),
186
+ new InternalRuleDefReference(5),
187
+ new InternalRuleDefAlt(),
188
+ new InternalRuleDefReference(1),
189
+ new InternalRuleDefEnd(),
190
+ ],
191
+ [
192
+ new InternalRuleDefChar([ord("-")]),
193
+ new InternalRuleDefCharAlt(ord("+")),
194
+ new InternalRuleDefCharAlt(ord("*")),
195
+ new InternalRuleDefCharAlt(ord("/")),
196
+ new InternalRuleDefReference(4),
197
+ new InternalRuleDefEnd(),
198
+ ],
199
+ [
200
+ new InternalRuleDefReference(6),
201
+ new InternalRuleDefReference(7),
202
+ new InternalRuleDefAlt(),
203
+ new InternalRuleDefEnd(),
204
+ ],
205
+ [
206
+ new InternalRuleDefChar([ord("a")]),
207
+ new InternalRuleDefCharRngUpper(ord("z")),
208
+ new InternalRuleDefReference(10),
209
+ new InternalRuleDefReference(3),
210
+ new InternalRuleDefEnd(),
211
+ ],
212
+ [
213
+ new InternalRuleDefReference(11),
214
+ new InternalRuleDefReference(3),
215
+ new InternalRuleDefEnd(),
216
+ ],
217
+ [
218
+ new InternalRuleDefChar([ord("a")]),
219
+ new InternalRuleDefCharRngUpper(ord("z")),
220
+ new InternalRuleDefCharAlt(ord("0")),
221
+ new InternalRuleDefCharRngUpper(ord("9")),
222
+ new InternalRuleDefCharAlt(ord("_")),
223
+ new InternalRuleDefReference(10),
224
+ new InternalRuleDefAlt(),
225
+ new InternalRuleDefEnd(),
226
+ ],
227
+ [
228
+ new InternalRuleDefChar([ord("0")]),
229
+ new InternalRuleDefCharRngUpper(ord("9")),
230
+ new InternalRuleDefReference(11),
231
+ new InternalRuleDefAlt(),
232
+ new InternalRuleDefChar([ord("0")]),
233
+ new InternalRuleDefCharRngUpper(ord("9")),
234
+ new InternalRuleDefEnd(),
235
+ ],
236
+ [
237
+ new InternalRuleDefChar([32]),
238
+ new InternalRuleDefCharAlt(9),
239
+ new InternalRuleDefCharAlt(10),
240
+ new InternalRuleDefReference(12),
241
+ new InternalRuleDefAlt(),
242
+ new InternalRuleDefEnd(),
243
+ ],
244
+ ],
245
+ ],
246
+ ],
247
+ [
248
+ "character unicode grammar",
249
+ "root ::= [ぁ-ゟ]",
250
+ [
251
+ [["root", 0]],
252
+ [
253
+ [
254
+ new InternalRuleDefChar([12353]),
255
+ new InternalRuleDefCharRngUpper(12447),
256
+ new InternalRuleDefEnd(),
257
+ ],
258
+ ],
259
+ ],
260
+ ],
261
+ [
262
+ "character alts grammar",
263
+ "root ::= [az]",
264
+ [
265
+ [["root", 0]],
266
+ [
267
+ [
268
+ new InternalRuleDefChar([ord("a")]),
269
+ new InternalRuleDefCharAlt(ord("z")),
270
+ new InternalRuleDefEnd(),
271
+ ],
272
+ ],
273
+ ],
274
+ ],
275
+ [
276
+ "character range grammar",
277
+ "root ::= [a-zA-Z0-9]",
278
+ [
279
+ [["root", 0]],
280
+ [
281
+ [
282
+ new InternalRuleDefChar([ord("a")]),
283
+ new InternalRuleDefCharRngUpper(ord("z")),
284
+ new InternalRuleDefCharAlt(ord("A")),
285
+ new InternalRuleDefCharRngUpper(ord("Z")),
286
+ new InternalRuleDefCharAlt(ord("0")),
287
+ new InternalRuleDefCharRngUpper(ord("9")),
288
+ new InternalRuleDefEnd(),
289
+ ],
290
+ ],
291
+ ],
292
+ ],
293
+ [
294
+ "character range grammar with dash at end",
295
+ "root ::= [a-z-]",
296
+ [
297
+ [["root", 0]],
298
+ [
299
+ [
300
+ new InternalRuleDefChar([ord("a")]),
301
+ new InternalRuleDefCharRngUpper(ord("z")),
302
+ new InternalRuleDefCharAlt(ord("-")),
303
+ new InternalRuleDefEnd(),
304
+ ],
305
+ ],
306
+ ],
307
+ ],
308
+ [
309
+ "grouping",
310
+ "root ::= \"f\" (\"b\" | \"a\")",
311
+ [
312
+ [["root", 0], ["root_1", 1]],
313
+ [
314
+ [
315
+ new InternalRuleDefChar([ord("f")]),
316
+ new InternalRuleDefReference(1),
317
+ new InternalRuleDefEnd(),
318
+ ],
319
+ [
320
+ new InternalRuleDefChar([ord("b")]),
321
+ new InternalRuleDefAlt(),
322
+ new InternalRuleDefChar([ord("a")]),
323
+ new InternalRuleDefEnd(),
324
+ ],
325
+ ],
326
+ ],
327
+ ],
328
+ [
329
+ "optional",
330
+ "root ::= \"f\"?",
331
+ [
332
+ [["root", 0], ["root_1", 1]],
333
+ [
334
+ [
335
+ new InternalRuleDefReference(1),
336
+ new InternalRuleDefEnd(),
337
+ ],
338
+ [
339
+ new InternalRuleDefChar([ord("f")]),
340
+ new InternalRuleDefAlt(),
341
+ new InternalRuleDefEnd(),
342
+ ],
343
+ ],
344
+ ],
345
+ ],
346
+ [
347
+ "repeating",
348
+ "root ::= \"f\"*",
349
+ [
350
+ [["root", 0], ["root_1", 1]],
351
+ [
352
+ [
353
+ new InternalRuleDefReference(1),
354
+ new InternalRuleDefEnd(),
355
+ ],
356
+ [
357
+ new InternalRuleDefChar([ord("f")]),
358
+ new InternalRuleDefReference(1),
359
+ new InternalRuleDefAlt(),
360
+ new InternalRuleDefEnd(),
361
+ ],
362
+ ],
363
+ ],
364
+ ],
365
+ [
366
+ "repeating-at-least-once",
367
+ "root ::= \"f\"+",
368
+ [
369
+ [["root", 0], ["root_1", 1]],
370
+ [
371
+ [
372
+ new InternalRuleDefReference(1),
373
+ new InternalRuleDefEnd(),
374
+ ],
375
+ [
376
+ new InternalRuleDefChar([ord("f")]),
377
+ new InternalRuleDefReference(1),
378
+ new InternalRuleDefAlt(),
379
+ new InternalRuleDefChar([ord("f")]),
380
+ new InternalRuleDefEnd(),
381
+ ],
382
+ ],
383
+ ],
384
+ ],
385
+ [
386
+ "character range with optional repeating",
387
+ "root ::= [a-zA-Z0-9]*",
388
+ [
389
+ [["root", 0], ["root_1", 1]],
390
+ [
391
+ [
392
+ new InternalRuleDefReference(1),
393
+ new InternalRuleDefEnd(),
394
+ ],
395
+ [
396
+ new InternalRuleDefChar([ord("a")]),
397
+ new InternalRuleDefCharRngUpper(ord("z")),
398
+ new InternalRuleDefCharAlt(ord("A")),
399
+ new InternalRuleDefCharRngUpper(ord("Z")),
400
+ new InternalRuleDefCharAlt(ord("0")),
401
+ new InternalRuleDefCharRngUpper(ord("9")),
402
+ new InternalRuleDefReference(1),
403
+ new InternalRuleDefAlt(),
404
+ new InternalRuleDefEnd(),
405
+ ],
406
+ ],
407
+ ],
408
+ ],
409
+ [
410
+ "grouping-repeating",
411
+ "root ::= \"f\" (\"b\" | \"a\")*",
412
+ [
413
+ [["root", 0], ["root_1", 1], ["root_2", 2]],
414
+ [
415
+ [
416
+ new InternalRuleDefChar([ord("f")]),
417
+ new InternalRuleDefReference(2),
418
+ new InternalRuleDefEnd(),
419
+ ],
420
+ [
421
+ new InternalRuleDefChar([ord("b")]),
422
+ new InternalRuleDefAlt(),
423
+ new InternalRuleDefChar([ord("a")]),
424
+ new InternalRuleDefEnd(),
425
+ ],
426
+ [
427
+ new InternalRuleDefReference(1),
428
+ new InternalRuleDefReference(2),
429
+ new InternalRuleDefAlt(),
430
+ new InternalRuleDefEnd(),
431
+ ],
432
+ ],
433
+ ],
434
+ ],
435
+ [
436
+ "negation",
437
+ "root ::= [^\\n]",
438
+ [
439
+ [["root", 0]],
440
+ [
441
+ [
442
+ new InternalRuleDefCharNot([10]),
443
+ new InternalRuleDefEnd(),
444
+ ],
445
+ ],
446
+ ],
447
+ ],
448
+ [
449
+ "negation of range",
450
+ "root ::= [^0-9]",
451
+ [
452
+ [["root", 0]],
453
+ [
454
+ [
455
+ new InternalRuleDefCharNot([ord("0")]),
456
+ new InternalRuleDefCharRngUpper(ord("9")),
457
+ new InternalRuleDefEnd(),
458
+ ],
459
+ ],
460
+ ],
461
+ ],
462
+ [
463
+ "negation with after",
464
+ "root ::= [^\\n]+ \"\\n\"",
465
+ [
466
+ [["root", 0], ["root_1", 1]],
467
+ [
468
+ [
469
+ new InternalRuleDefReference(1),
470
+ new InternalRuleDefChar([10]),
471
+ new InternalRuleDefEnd(),
472
+ ],
473
+ [
474
+ new InternalRuleDefCharNot([10]),
475
+ new InternalRuleDefReference(1),
476
+ new InternalRuleDefAlt(),
477
+ new InternalRuleDefCharNot([10]),
478
+ new InternalRuleDefEnd(),
479
+ ],
480
+ ],
481
+ ],
482
+ ],
483
+ [
484
+ "longer negation",
485
+ "root ::= \"\\\"\" ( [^\"abcdefgh])* ",
486
+ [
487
+ [["root", 0], ["root_1", 1], ["root_2", 2]],
488
+ [
489
+ [
490
+ new InternalRuleDefChar([34]),
491
+ new InternalRuleDefReference(2),
492
+ new InternalRuleDefEnd(),
493
+ ],
494
+ [
495
+ new InternalRuleDefCharNot([34]),
496
+ new InternalRuleDefCharAlt(ord("a")),
497
+ new InternalRuleDefCharAlt(ord("b")),
498
+ new InternalRuleDefCharAlt(ord("c")),
499
+ new InternalRuleDefCharAlt(ord("d")),
500
+ new InternalRuleDefCharAlt(ord("e")),
501
+ new InternalRuleDefCharAlt(ord("f")),
502
+ new InternalRuleDefCharAlt(ord("g")),
503
+ new InternalRuleDefCharAlt(ord("h")),
504
+ new InternalRuleDefEnd(),
505
+ ],
506
+ [
507
+ new InternalRuleDefReference(1),
508
+ new InternalRuleDefReference(2),
509
+ new InternalRuleDefAlt(),
510
+ new InternalRuleDefEnd(),
511
+ ],
512
+ ],
513
+ ],
514
+ ],
515
+ [
516
+ "longer negation with a range",
517
+ "root ::= \"\\\"\" ( [^\"abcdefghA-Z])* ",
518
+ [
519
+ [["root", 0], ["root_1", 1], ["root_2", 2]],
520
+ [
521
+ [
522
+ new InternalRuleDefChar([34]),
523
+ new InternalRuleDefReference(2),
524
+ new InternalRuleDefEnd(),
525
+ ],
526
+ [
527
+ new InternalRuleDefCharNot([34]),
528
+ new InternalRuleDefCharAlt(ord("a")),
529
+ new InternalRuleDefCharAlt(ord("b")),
530
+ new InternalRuleDefCharAlt(ord("c")),
531
+ new InternalRuleDefCharAlt(ord("d")),
532
+ new InternalRuleDefCharAlt(ord("e")),
533
+ new InternalRuleDefCharAlt(ord("f")),
534
+ new InternalRuleDefCharAlt(ord("g")),
535
+ new InternalRuleDefCharAlt(ord("h")),
536
+ new InternalRuleDefCharAlt(ord("A")),
537
+ new InternalRuleDefCharRngUpper(ord("Z")),
538
+ new InternalRuleDefEnd(),
539
+ ],
540
+ [
541
+ new InternalRuleDefReference(1),
542
+ new InternalRuleDefReference(2),
543
+ new InternalRuleDefAlt(),
544
+ new InternalRuleDefEnd(),
545
+ ],
546
+ ],
547
+ ],
548
+ ],
549
+ [
550
+ "escaped 8-bit unicode char",
551
+ "root ::= \"\\x2A\"",
552
+ [
553
+ [["root", 0]],
554
+ [
555
+ [
556
+ new InternalRuleDefChar([ord("*")]),
557
+ new InternalRuleDefEnd(),
558
+ ],
559
+ ],
560
+ ],
561
+ ],
562
+ [
563
+ "escaped 16-bit unicode char",
564
+ "root ::= \"\\u006F\"",
565
+ [
566
+ [["root", 0]],
567
+ [
568
+ [
569
+ new InternalRuleDefChar([ord("o")]),
570
+ new InternalRuleDefEnd(),
571
+ ],
572
+ ],
573
+ ],
574
+ ],
575
+ [
576
+ "escaped 32-bit unicode char",
577
+ "root ::= \"\\U0001F4A9\"",
578
+ [
579
+ [["root", 0]],
580
+ [
581
+ [
582
+ new InternalRuleDefChar([128169]),
583
+ new InternalRuleDefEnd(),
584
+ ],
585
+ ],
586
+ ],
587
+ ],
588
+ [
589
+ "escaped tab char",
590
+ "root ::= \"\\t\"",
591
+ [
592
+ [["root", 0]],
593
+ [
594
+ [
595
+ new InternalRuleDefChar([9]),
596
+ new InternalRuleDefEnd(),
597
+ ],
598
+ ],
599
+ ],
600
+ ],
601
+ [
602
+ "escaped new line char",
603
+ "root ::= \"\\n\"",
604
+ [
605
+ [["root", 0]],
606
+ [
607
+ [
608
+ new InternalRuleDefChar([10]),
609
+ new InternalRuleDefEnd(),
610
+ ],
611
+ ],
612
+ ],
613
+ ],
614
+ [
615
+ "escaped \r char",
616
+ "root ::= \"\\r\"",
617
+ [
618
+ [["root", 0]],
619
+ [
620
+ [
621
+ new InternalRuleDefChar([13]),
622
+ new InternalRuleDefEnd(),
623
+ ],
624
+ ],
625
+ ],
626
+ ],
627
+ [
628
+ "escaped quote char",
629
+ "root ::= \"\\\"\"",
630
+ [
631
+ [["root", 0]],
632
+ [
633
+ [
634
+ new InternalRuleDefChar([34]),
635
+ new InternalRuleDefEnd(),
636
+ ],
637
+ ],
638
+ ],
639
+ ],
640
+ [
641
+ "escaped [ char",
642
+ "root ::= \"\\[\"",
643
+ [
644
+ [["root", 0]],
645
+ [
646
+ [
647
+ new InternalRuleDefChar([ord("[")]),
648
+ new InternalRuleDefEnd(),
649
+ ],
650
+ ],
651
+ ],
652
+ ],
653
+ [
654
+ "escaped ] char",
655
+ "root ::= \"\\]\"",
656
+ [
657
+ [["root", 0]],
658
+ [
659
+ [
660
+ new InternalRuleDefChar([ord("]")]),
661
+ new InternalRuleDefEnd(),
662
+ ],
663
+ ],
664
+ ],
665
+ ],
666
+ [
667
+ "escaped \\ char",
668
+ "root ::= \"\\\\\"",
669
+ [
670
+ [["root", 0]],
671
+ [
672
+ [
673
+ new InternalRuleDefChar([92]),
674
+ new InternalRuleDefEnd(),
675
+ ],
676
+ ],
677
+ ],
678
+ ],
679
+ [
680
+ "simple arithmetic",
681
+ "\n root ::= (expr \"=\" term \"\\n\")+\n expr ::= term ([-+*/] term)*\n term ::= [0-9]+\n ",
682
+ [
683
+ [["root", 0], ["root_1", 1], ["expr", 2], ["term", 3], ["root_4", 4], ["expr_5", 5], ["expr_6", 6], ["term_7", 7]],
684
+ [
685
+ [
686
+ new InternalRuleDefReference(4),
687
+ new InternalRuleDefEnd(),
688
+ ],
689
+ [
690
+ new InternalRuleDefReference(2),
691
+ new InternalRuleDefChar([ord("=")]),
692
+ new InternalRuleDefReference(3),
693
+ new InternalRuleDefChar([10]),
694
+ new InternalRuleDefEnd(),
695
+ ],
696
+ [
697
+ new InternalRuleDefReference(3),
698
+ new InternalRuleDefReference(6),
699
+ new InternalRuleDefEnd(),
700
+ ],
701
+ [
702
+ new InternalRuleDefReference(7),
703
+ new InternalRuleDefEnd(),
704
+ ],
705
+ [
706
+ new InternalRuleDefReference(1),
707
+ new InternalRuleDefReference(4),
708
+ new InternalRuleDefAlt(),
709
+ new InternalRuleDefReference(1),
710
+ new InternalRuleDefEnd(),
711
+ ],
712
+ [
713
+ new InternalRuleDefChar([ord("-")]),
714
+ new InternalRuleDefCharAlt(ord("+")),
715
+ new InternalRuleDefCharAlt(ord("*")),
716
+ new InternalRuleDefCharAlt(ord("/")),
717
+ new InternalRuleDefReference(3),
718
+ new InternalRuleDefEnd(),
719
+ ],
720
+ [
721
+ new InternalRuleDefReference(5),
722
+ new InternalRuleDefReference(6),
723
+ new InternalRuleDefAlt(),
724
+ new InternalRuleDefEnd(),
725
+ ],
726
+ [
727
+ new InternalRuleDefChar([ord("0")]),
728
+ new InternalRuleDefCharRngUpper(ord("9")),
729
+ new InternalRuleDefReference(7),
730
+ new InternalRuleDefAlt(),
731
+ new InternalRuleDefChar([ord("0")]),
732
+ new InternalRuleDefCharRngUpper(ord("9")),
733
+ new InternalRuleDefEnd(),
734
+ ],
735
+ ],
736
+ ],
737
+ ],
738
+ [
739
+ "ranges with chars",
740
+ "\n root ::= [a-z0-9_]*\n ",
741
+ [
742
+ [["root", 0], ["root_1", 1]],
743
+ [
744
+ [
745
+ new InternalRuleDefReference(1),
746
+ new InternalRuleDefEnd(),
747
+ ],
748
+ [
749
+ new InternalRuleDefChar([ord("a")]),
750
+ new InternalRuleDefCharRngUpper(ord("z")),
751
+ new InternalRuleDefCharAlt(ord("0")),
752
+ new InternalRuleDefCharRngUpper(ord("9")),
753
+ new InternalRuleDefCharAlt(ord("_")),
754
+ new InternalRuleDefReference(1),
755
+ new InternalRuleDefAlt(),
756
+ new InternalRuleDefEnd(),
757
+ ],
758
+ ],
759
+ ],
760
+ ],
761
+ [
762
+ "nested ranges with chars",
763
+ "\n root ::= [a-z] [a-z0-9_]*\n ",
764
+ [
765
+ [["root", 0], ["root_1", 1]],
766
+ [
767
+ [
768
+ new InternalRuleDefChar([ord("a")]),
769
+ new InternalRuleDefCharRngUpper(ord("z")),
770
+ new InternalRuleDefReference(1),
771
+ new InternalRuleDefEnd(),
772
+ ],
773
+ [
774
+ new InternalRuleDefChar([ord("a")]),
775
+ new InternalRuleDefCharRngUpper(ord("z")),
776
+ new InternalRuleDefCharAlt(ord("0")),
777
+ new InternalRuleDefCharRngUpper(ord("9")),
778
+ new InternalRuleDefCharAlt(ord("_")),
779
+ new InternalRuleDefReference(1),
780
+ new InternalRuleDefAlt(),
781
+ new InternalRuleDefEnd(),
782
+ ],
783
+ ],
784
+ ],
785
+ ],
786
+ [
787
+ "expression with nested range with chars",
788
+ "\n root ::= ident\n ident ::= [a-z] [a-z0-9_]* ws\n ws ::= [ \\t\\n]*\n ",
789
+ [
790
+ [["root", 0], ["ident", 1], ["ident_2", 2], ["ws", 3], ["ws_4", 4]],
791
+ [
792
+ [
793
+ new InternalRuleDefReference(1),
794
+ new InternalRuleDefEnd(),
795
+ ],
796
+ [
797
+ new InternalRuleDefChar([ord("a")]),
798
+ new InternalRuleDefCharRngUpper(ord("z")),
799
+ new InternalRuleDefReference(2),
800
+ new InternalRuleDefReference(3),
801
+ new InternalRuleDefEnd(),
802
+ ],
803
+ [
804
+ new InternalRuleDefChar([ord("a")]),
805
+ new InternalRuleDefCharRngUpper(ord("z")),
806
+ new InternalRuleDefCharAlt(ord("0")),
807
+ new InternalRuleDefCharRngUpper(ord("9")),
808
+ new InternalRuleDefCharAlt(ord("_")),
809
+ new InternalRuleDefReference(2),
810
+ new InternalRuleDefAlt(),
811
+ new InternalRuleDefEnd(),
812
+ ],
813
+ [
814
+ new InternalRuleDefReference(4),
815
+ new InternalRuleDefEnd(),
816
+ ],
817
+ [
818
+ new InternalRuleDefChar([32]),
819
+ new InternalRuleDefCharAlt(9),
820
+ new InternalRuleDefCharAlt(10),
821
+ new InternalRuleDefReference(4),
822
+ new InternalRuleDefAlt(),
823
+ new InternalRuleDefEnd(),
824
+ ],
825
+ ],
826
+ ],
827
+ ],
828
+ [
829
+ "lots of escapes",
830
+ "root ::= \"\\x2A\" \"\\u006F\" \"\\U0001F4A9\" \"\\t\" \"\\n\" \"\\r\" \"\\\"\" \"\\[\" \"\\]\" \"\\\\\"",
831
+ [
832
+ [["root", 0]],
833
+ [
834
+ [
835
+ new InternalRuleDefChar([ord("*")]),
836
+ new InternalRuleDefChar([ord("o")]),
837
+ new InternalRuleDefChar([128169]),
838
+ new InternalRuleDefChar([9]),
839
+ new InternalRuleDefChar([10]),
840
+ new InternalRuleDefChar([13]),
841
+ new InternalRuleDefChar([34]),
842
+ new InternalRuleDefChar([ord("[")]),
843
+ new InternalRuleDefChar([ord("]")]),
844
+ new InternalRuleDefChar([92]),
845
+ new InternalRuleDefEnd(),
846
+ ],
847
+ ],
848
+ ],
849
+ ],
850
+ [
851
+ "lots of escape and alternate escapes",
852
+ "root ::= \"\\x2A\" \"\\u006F\" \"\\U0001F4A9\" \"\\t\" \"\\n\" \"\\r\" \"\\\"\" \"\\[\" \"\\]\" \"\\\\\" (\n \"\\x2A\" | \"\\u006F\" | \"\\U0001F4A9\" | \"\\t\" | \"\\n\" | \"\\r\" | \"\\\"\" | \"\\[\" | \"\\]\" | \"\\\\\" )",
853
+ [
854
+ [["root", 0], ["root_1", 1]],
855
+ [
856
+ [
857
+ new InternalRuleDefChar([ord("*")]),
858
+ new InternalRuleDefChar([ord("o")]),
859
+ new InternalRuleDefChar([128169]),
860
+ new InternalRuleDefChar([9]),
861
+ new InternalRuleDefChar([10]),
862
+ new InternalRuleDefChar([13]),
863
+ new InternalRuleDefChar([34]),
864
+ new InternalRuleDefChar([ord("[")]),
865
+ new InternalRuleDefChar([ord("]")]),
866
+ new InternalRuleDefChar([92]),
867
+ new InternalRuleDefReference(1),
868
+ new InternalRuleDefEnd(),
869
+ ],
870
+ [
871
+ new InternalRuleDefChar([ord("*")]),
872
+ new InternalRuleDefAlt(),
873
+ new InternalRuleDefChar([ord("o")]),
874
+ new InternalRuleDefAlt(),
875
+ new InternalRuleDefChar([128169]),
876
+ new InternalRuleDefAlt(),
877
+ new InternalRuleDefChar([9]),
878
+ new InternalRuleDefAlt(),
879
+ new InternalRuleDefChar([10]),
880
+ new InternalRuleDefAlt(),
881
+ new InternalRuleDefChar([13]),
882
+ new InternalRuleDefAlt(),
883
+ new InternalRuleDefChar([34]),
884
+ new InternalRuleDefAlt(),
885
+ new InternalRuleDefChar([ord("[")]),
886
+ new InternalRuleDefAlt(),
887
+ new InternalRuleDefChar([ord("]")]),
888
+ new InternalRuleDefAlt(),
889
+ new InternalRuleDefChar([92]),
890
+ new InternalRuleDefEnd(),
891
+ ],
892
+ ],
893
+ ],
894
+ ],
895
+ [
896
+ "arithmetic",
897
+ "\n root ::= (expr \"=\" ws term \"\\n\")+\n expr ::= term ([-+*/] term)*\n term ::= ident | num | \"(\" ws expr \")\" ws\n ident ::= [a-z] [a-z0-9_]* ws\n num ::= [0-9]+ ws\n ws ::= [ \\t\\n]*\n ",
898
+ [
899
+ [["root", 0], ["root_1", 1], ["expr", 2], ["ws", 3], ["term", 4], ["root_5", 5], ["expr_6", 6], ["expr_7", 7], ["ident", 8], ["num", 9], ["ident_10", 10], ["num_11", 11], ["ws_12", 12]],
900
+ [
901
+ [
902
+ new InternalRuleDefReference(5),
903
+ new InternalRuleDefEnd(),
904
+ ],
905
+ [
906
+ new InternalRuleDefReference(2),
907
+ new InternalRuleDefChar([ord("=")]),
908
+ new InternalRuleDefReference(3),
909
+ new InternalRuleDefReference(4),
910
+ new InternalRuleDefChar([10]),
911
+ new InternalRuleDefEnd(),
912
+ ],
913
+ [
914
+ new InternalRuleDefReference(4),
915
+ new InternalRuleDefReference(7),
916
+ new InternalRuleDefEnd(),
917
+ ],
918
+ [
919
+ new InternalRuleDefReference(12),
920
+ new InternalRuleDefEnd(),
921
+ ],
922
+ [
923
+ new InternalRuleDefReference(8),
924
+ new InternalRuleDefAlt(),
925
+ new InternalRuleDefReference(9),
926
+ new InternalRuleDefAlt(),
927
+ new InternalRuleDefChar([ord("(")]),
928
+ new InternalRuleDefReference(3),
929
+ new InternalRuleDefReference(2),
930
+ new InternalRuleDefChar([ord(")")]),
931
+ new InternalRuleDefReference(3),
932
+ new InternalRuleDefEnd(),
933
+ ],
934
+ [
935
+ new InternalRuleDefReference(1),
936
+ new InternalRuleDefReference(5),
937
+ new InternalRuleDefAlt(),
938
+ new InternalRuleDefReference(1),
939
+ new InternalRuleDefEnd(),
940
+ ],
941
+ [
942
+ new InternalRuleDefChar([ord("-")]),
943
+ new InternalRuleDefCharAlt(ord("+")),
944
+ new InternalRuleDefCharAlt(ord("*")),
945
+ new InternalRuleDefCharAlt(ord("/")),
946
+ new InternalRuleDefReference(4),
947
+ new InternalRuleDefEnd(),
948
+ ],
949
+ [
950
+ new InternalRuleDefReference(6),
951
+ new InternalRuleDefReference(7),
952
+ new InternalRuleDefAlt(),
953
+ new InternalRuleDefEnd(),
954
+ ],
955
+ [
956
+ new InternalRuleDefChar([ord("a")]),
957
+ new InternalRuleDefCharRngUpper(ord("z")),
958
+ new InternalRuleDefReference(10),
959
+ new InternalRuleDefReference(3),
960
+ new InternalRuleDefEnd(),
961
+ ],
962
+ [
963
+ new InternalRuleDefReference(11),
964
+ new InternalRuleDefReference(3),
965
+ new InternalRuleDefEnd(),
966
+ ],
967
+ [
968
+ new InternalRuleDefChar([ord("a")]),
969
+ new InternalRuleDefCharRngUpper(ord("z")),
970
+ new InternalRuleDefCharAlt(ord("0")),
971
+ new InternalRuleDefCharRngUpper(ord("9")),
972
+ new InternalRuleDefCharAlt(ord("_")),
973
+ new InternalRuleDefReference(10),
974
+ new InternalRuleDefAlt(),
975
+ new InternalRuleDefEnd(),
976
+ ],
977
+ [
978
+ new InternalRuleDefChar([ord("0")]),
979
+ new InternalRuleDefCharRngUpper(ord("9")),
980
+ new InternalRuleDefReference(11),
981
+ new InternalRuleDefAlt(),
982
+ new InternalRuleDefChar([ord("0")]),
983
+ new InternalRuleDefCharRngUpper(ord("9")),
984
+ new InternalRuleDefEnd(),
985
+ ],
986
+ [
987
+ new InternalRuleDefChar([32]),
988
+ new InternalRuleDefCharAlt(9),
989
+ new InternalRuleDefCharAlt(10),
990
+ new InternalRuleDefReference(12),
991
+ new InternalRuleDefAlt(),
992
+ new InternalRuleDefEnd(),
993
+ ],
994
+ ],
995
+ ],
996
+ ],
997
+ [
998
+ "json.gbnf (string)",
999
+ "\n root ::=\n \"\\\"\" (\n [^\"\\\\\\x7F\\x00-\\x1F] |\n \"\\\\\" ([\"\\\\/bfnrt] | \"u\" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes\n )* \"\\\"\"\n ",
1000
+ [
1001
+ [["root", 0], ["root_1", 1], ["root_2", 2], ["root_3", 3]],
1002
+ [
1003
+ [
1004
+ new InternalRuleDefChar([34]),
1005
+ new InternalRuleDefReference(3),
1006
+ new InternalRuleDefChar([34]),
1007
+ new InternalRuleDefEnd(),
1008
+ ],
1009
+ [
1010
+ new InternalRuleDefCharNot([34]),
1011
+ new InternalRuleDefCharAlt(92),
1012
+ new InternalRuleDefCharAlt(127),
1013
+ new InternalRuleDefCharAlt(0),
1014
+ new InternalRuleDefCharRngUpper(31),
1015
+ new InternalRuleDefAlt(),
1016
+ new InternalRuleDefChar([92]),
1017
+ new InternalRuleDefReference(2),
1018
+ new InternalRuleDefEnd(),
1019
+ ],
1020
+ [
1021
+ new InternalRuleDefChar([34]),
1022
+ new InternalRuleDefCharAlt(92),
1023
+ new InternalRuleDefCharAlt(ord("/")),
1024
+ new InternalRuleDefCharAlt(ord("b")),
1025
+ new InternalRuleDefCharAlt(ord("f")),
1026
+ new InternalRuleDefCharAlt(ord("n")),
1027
+ new InternalRuleDefCharAlt(ord("r")),
1028
+ new InternalRuleDefCharAlt(ord("t")),
1029
+ new InternalRuleDefAlt(),
1030
+ new InternalRuleDefChar([ord("u")]),
1031
+ new InternalRuleDefChar([ord("0")]),
1032
+ new InternalRuleDefCharRngUpper(ord("9")),
1033
+ new InternalRuleDefCharAlt(ord("a")),
1034
+ new InternalRuleDefCharRngUpper(ord("f")),
1035
+ new InternalRuleDefCharAlt(ord("A")),
1036
+ new InternalRuleDefCharRngUpper(ord("F")),
1037
+ new InternalRuleDefChar([ord("0")]),
1038
+ new InternalRuleDefCharRngUpper(ord("9")),
1039
+ new InternalRuleDefCharAlt(ord("a")),
1040
+ new InternalRuleDefCharRngUpper(ord("f")),
1041
+ new InternalRuleDefCharAlt(ord("A")),
1042
+ new InternalRuleDefCharRngUpper(ord("F")),
1043
+ new InternalRuleDefChar([ord("0")]),
1044
+ new InternalRuleDefCharRngUpper(ord("9")),
1045
+ new InternalRuleDefCharAlt(ord("a")),
1046
+ new InternalRuleDefCharRngUpper(ord("f")),
1047
+ new InternalRuleDefCharAlt(ord("A")),
1048
+ new InternalRuleDefCharRngUpper(ord("F")),
1049
+ new InternalRuleDefChar([ord("0")]),
1050
+ new InternalRuleDefCharRngUpper(ord("9")),
1051
+ new InternalRuleDefCharAlt(ord("a")),
1052
+ new InternalRuleDefCharRngUpper(ord("f")),
1053
+ new InternalRuleDefCharAlt(ord("A")),
1054
+ new InternalRuleDefCharRngUpper(ord("F")),
1055
+ new InternalRuleDefEnd(),
1056
+ ],
1057
+ [
1058
+ new InternalRuleDefReference(1),
1059
+ new InternalRuleDefReference(3),
1060
+ new InternalRuleDefAlt(),
1061
+ new InternalRuleDefEnd(),
1062
+ ],
1063
+ ],
1064
+ ],
1065
+ ],
1066
+ [
1067
+ "json.gbnf (full)",
1068
+ "\n root ::= object\n value ::= object | array | string | number | (\"true\" | \"false\" | \"null\") ws\n object ::=\n \"{\" ws (\n string \":\" ws value\n (\",\" ws string \":\" ws value)*\n )? \"}\" ws\n array ::=\n \"[\" ws (\n value\n (\",\" ws value)*\n )? \"]\" ws\n string ::=\n \"\\\"\" (\n [^\"\\\\\\x7F\\x00-\\x1F] |\n \"\\\\\" ([\"\\\\/bfnrt] | \"u\" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes\n )* \"\\\"\" ws\n number ::= (\"-\"? ([0-9] | [1-9] [0-9]*)) (\".\" [0-9]+)? ([eE] [-+]? [0-9]+)? ws\n # Optional space: by convention, applied in this grammar after literal chars when allowed\n ws ::= ([ \\t\\n] ws)?\n ",
1069
+ [
1070
+ [["root", 0], ["object", 1], ["value", 2], ["array", 3], ["string", 4], ["number", 5], ["value_6", 6], ["ws", 7], ["object_8", 8], ["object_9", 9], ["object_10", 10], ["object_11", 11], ["array_12", 12], ["array_13", 13], ["array_14", 14], ["array_15", 15], ["string_16", 16], ["string_17", 17], ["string_18", 18], ["number_19", 19], ["number_20", 20], ["number_21", 21], ["number_22", 22], ["number_23", 23], ["number_24", 24], ["number_25", 25], ["number_26", 26], ["number_27", 27], ["number_28", 28], ["number_29", 29], ["ws_30", 30], ["ws_31", 31]],
1071
+ [
1072
+ [
1073
+ new InternalRuleDefReference(1),
1074
+ new InternalRuleDefEnd(),
1075
+ ],
1076
+ [
1077
+ new InternalRuleDefChar([ord("{")]),
1078
+ new InternalRuleDefReference(7),
1079
+ new InternalRuleDefReference(11),
1080
+ new InternalRuleDefChar([ord("}")]),
1081
+ new InternalRuleDefReference(7),
1082
+ new InternalRuleDefEnd(),
1083
+ ],
1084
+ [
1085
+ new InternalRuleDefReference(1),
1086
+ new InternalRuleDefAlt(),
1087
+ new InternalRuleDefReference(3),
1088
+ new InternalRuleDefAlt(),
1089
+ new InternalRuleDefReference(4),
1090
+ new InternalRuleDefAlt(),
1091
+ new InternalRuleDefReference(5),
1092
+ new InternalRuleDefAlt(),
1093
+ new InternalRuleDefReference(6),
1094
+ new InternalRuleDefReference(7),
1095
+ new InternalRuleDefEnd(),
1096
+ ],
1097
+ [
1098
+ new InternalRuleDefChar([ord("[")]),
1099
+ new InternalRuleDefReference(7),
1100
+ new InternalRuleDefReference(15),
1101
+ new InternalRuleDefChar([ord("]")]),
1102
+ new InternalRuleDefReference(7),
1103
+ new InternalRuleDefEnd(),
1104
+ ],
1105
+ [
1106
+ new InternalRuleDefChar([34]),
1107
+ new InternalRuleDefReference(18),
1108
+ new InternalRuleDefChar([34]),
1109
+ new InternalRuleDefReference(7),
1110
+ new InternalRuleDefEnd(),
1111
+ ],
1112
+ [
1113
+ new InternalRuleDefReference(19),
1114
+ new InternalRuleDefReference(25),
1115
+ new InternalRuleDefReference(29),
1116
+ new InternalRuleDefReference(7),
1117
+ new InternalRuleDefEnd(),
1118
+ ],
1119
+ [
1120
+ new InternalRuleDefChar([ord("t")]),
1121
+ new InternalRuleDefChar([ord("r")]),
1122
+ new InternalRuleDefChar([ord("u")]),
1123
+ new InternalRuleDefChar([ord("e")]),
1124
+ new InternalRuleDefAlt(),
1125
+ new InternalRuleDefChar([ord("f")]),
1126
+ new InternalRuleDefChar([ord("a")]),
1127
+ new InternalRuleDefChar([ord("l")]),
1128
+ new InternalRuleDefChar([ord("s")]),
1129
+ new InternalRuleDefChar([ord("e")]),
1130
+ new InternalRuleDefAlt(),
1131
+ new InternalRuleDefChar([ord("n")]),
1132
+ new InternalRuleDefChar([ord("u")]),
1133
+ new InternalRuleDefChar([ord("l")]),
1134
+ new InternalRuleDefChar([ord("l")]),
1135
+ new InternalRuleDefEnd(),
1136
+ ],
1137
+ [
1138
+ new InternalRuleDefReference(31),
1139
+ new InternalRuleDefEnd(),
1140
+ ],
1141
+ [
1142
+ new InternalRuleDefReference(4),
1143
+ new InternalRuleDefChar([ord(":")]),
1144
+ new InternalRuleDefReference(7),
1145
+ new InternalRuleDefReference(2),
1146
+ new InternalRuleDefReference(10),
1147
+ new InternalRuleDefEnd(),
1148
+ ],
1149
+ [
1150
+ new InternalRuleDefChar([ord(",")]),
1151
+ new InternalRuleDefReference(7),
1152
+ new InternalRuleDefReference(4),
1153
+ new InternalRuleDefChar([ord(":")]),
1154
+ new InternalRuleDefReference(7),
1155
+ new InternalRuleDefReference(2),
1156
+ new InternalRuleDefEnd(),
1157
+ ],
1158
+ [
1159
+ new InternalRuleDefReference(9),
1160
+ new InternalRuleDefReference(10),
1161
+ new InternalRuleDefAlt(),
1162
+ new InternalRuleDefEnd(),
1163
+ ],
1164
+ [
1165
+ new InternalRuleDefReference(8),
1166
+ new InternalRuleDefAlt(),
1167
+ new InternalRuleDefEnd(),
1168
+ ],
1169
+ [
1170
+ new InternalRuleDefReference(2),
1171
+ new InternalRuleDefReference(14),
1172
+ new InternalRuleDefEnd(),
1173
+ ],
1174
+ [
1175
+ new InternalRuleDefChar([ord(",")]),
1176
+ new InternalRuleDefReference(7),
1177
+ new InternalRuleDefReference(2),
1178
+ new InternalRuleDefEnd(),
1179
+ ],
1180
+ [
1181
+ new InternalRuleDefReference(13),
1182
+ new InternalRuleDefReference(14),
1183
+ new InternalRuleDefAlt(),
1184
+ new InternalRuleDefEnd(),
1185
+ ],
1186
+ [
1187
+ new InternalRuleDefReference(12),
1188
+ new InternalRuleDefAlt(),
1189
+ new InternalRuleDefEnd(),
1190
+ ],
1191
+ [
1192
+ new InternalRuleDefCharNot([34]),
1193
+ new InternalRuleDefCharAlt(92),
1194
+ new InternalRuleDefCharAlt(127),
1195
+ new InternalRuleDefCharAlt(0),
1196
+ new InternalRuleDefCharRngUpper(31),
1197
+ new InternalRuleDefAlt(),
1198
+ new InternalRuleDefChar([92]),
1199
+ new InternalRuleDefReference(17),
1200
+ new InternalRuleDefEnd(),
1201
+ ],
1202
+ [
1203
+ new InternalRuleDefChar([34]),
1204
+ new InternalRuleDefCharAlt(92),
1205
+ new InternalRuleDefCharAlt(ord("/")),
1206
+ new InternalRuleDefCharAlt(ord("b")),
1207
+ new InternalRuleDefCharAlt(ord("f")),
1208
+ new InternalRuleDefCharAlt(ord("n")),
1209
+ new InternalRuleDefCharAlt(ord("r")),
1210
+ new InternalRuleDefCharAlt(ord("t")),
1211
+ new InternalRuleDefAlt(),
1212
+ new InternalRuleDefChar([ord("u")]),
1213
+ new InternalRuleDefChar([ord("0")]),
1214
+ new InternalRuleDefCharRngUpper(ord("9")),
1215
+ new InternalRuleDefCharAlt(ord("a")),
1216
+ new InternalRuleDefCharRngUpper(ord("f")),
1217
+ new InternalRuleDefCharAlt(ord("A")),
1218
+ new InternalRuleDefCharRngUpper(ord("F")),
1219
+ new InternalRuleDefChar([ord("0")]),
1220
+ new InternalRuleDefCharRngUpper(ord("9")),
1221
+ new InternalRuleDefCharAlt(ord("a")),
1222
+ new InternalRuleDefCharRngUpper(ord("f")),
1223
+ new InternalRuleDefCharAlt(ord("A")),
1224
+ new InternalRuleDefCharRngUpper(ord("F")),
1225
+ new InternalRuleDefChar([ord("0")]),
1226
+ new InternalRuleDefCharRngUpper(ord("9")),
1227
+ new InternalRuleDefCharAlt(ord("a")),
1228
+ new InternalRuleDefCharRngUpper(ord("f")),
1229
+ new InternalRuleDefCharAlt(ord("A")),
1230
+ new InternalRuleDefCharRngUpper(ord("F")),
1231
+ new InternalRuleDefChar([ord("0")]),
1232
+ new InternalRuleDefCharRngUpper(ord("9")),
1233
+ new InternalRuleDefCharAlt(ord("a")),
1234
+ new InternalRuleDefCharRngUpper(ord("f")),
1235
+ new InternalRuleDefCharAlt(ord("A")),
1236
+ new InternalRuleDefCharRngUpper(ord("F")),
1237
+ new InternalRuleDefEnd(),
1238
+ ],
1239
+ [
1240
+ new InternalRuleDefReference(16),
1241
+ new InternalRuleDefReference(18),
1242
+ new InternalRuleDefAlt(),
1243
+ new InternalRuleDefEnd(),
1244
+ ],
1245
+ [
1246
+ new InternalRuleDefReference(20),
1247
+ new InternalRuleDefReference(21),
1248
+ new InternalRuleDefEnd(),
1249
+ ],
1250
+ [
1251
+ new InternalRuleDefChar([ord("-")]),
1252
+ new InternalRuleDefAlt(),
1253
+ new InternalRuleDefEnd(),
1254
+ ],
1255
+ [
1256
+ new InternalRuleDefChar([ord("0")]),
1257
+ new InternalRuleDefCharRngUpper(ord("9")),
1258
+ new InternalRuleDefAlt(),
1259
+ new InternalRuleDefChar([ord("1")]),
1260
+ new InternalRuleDefCharRngUpper(ord("9")),
1261
+ new InternalRuleDefReference(22),
1262
+ new InternalRuleDefEnd(),
1263
+ ],
1264
+ [
1265
+ new InternalRuleDefChar([ord("0")]),
1266
+ new InternalRuleDefCharRngUpper(ord("9")),
1267
+ new InternalRuleDefReference(22),
1268
+ new InternalRuleDefAlt(),
1269
+ new InternalRuleDefEnd(),
1270
+ ],
1271
+ [
1272
+ new InternalRuleDefChar([ord(".")]),
1273
+ new InternalRuleDefReference(24),
1274
+ new InternalRuleDefEnd(),
1275
+ ],
1276
+ [
1277
+ new InternalRuleDefChar([ord("0")]),
1278
+ new InternalRuleDefCharRngUpper(ord("9")),
1279
+ new InternalRuleDefReference(24),
1280
+ new InternalRuleDefAlt(),
1281
+ new InternalRuleDefChar([ord("0")]),
1282
+ new InternalRuleDefCharRngUpper(ord("9")),
1283
+ new InternalRuleDefEnd(),
1284
+ ],
1285
+ [
1286
+ new InternalRuleDefReference(23),
1287
+ new InternalRuleDefAlt(),
1288
+ new InternalRuleDefEnd(),
1289
+ ],
1290
+ [
1291
+ new InternalRuleDefChar([ord("e")]),
1292
+ new InternalRuleDefCharAlt(ord("E")),
1293
+ new InternalRuleDefReference(27),
1294
+ new InternalRuleDefReference(28),
1295
+ new InternalRuleDefEnd(),
1296
+ ],
1297
+ [
1298
+ new InternalRuleDefChar([ord("-")]),
1299
+ new InternalRuleDefCharAlt(ord("+")),
1300
+ new InternalRuleDefAlt(),
1301
+ new InternalRuleDefEnd(),
1302
+ ],
1303
+ [
1304
+ new InternalRuleDefChar([ord("0")]),
1305
+ new InternalRuleDefCharRngUpper(ord("9")),
1306
+ new InternalRuleDefReference(28),
1307
+ new InternalRuleDefAlt(),
1308
+ new InternalRuleDefChar([ord("0")]),
1309
+ new InternalRuleDefCharRngUpper(ord("9")),
1310
+ new InternalRuleDefEnd(),
1311
+ ],
1312
+ [
1313
+ new InternalRuleDefReference(26),
1314
+ new InternalRuleDefAlt(),
1315
+ new InternalRuleDefEnd(),
1316
+ ],
1317
+ [
1318
+ new InternalRuleDefChar([32]),
1319
+ new InternalRuleDefCharAlt(9),
1320
+ new InternalRuleDefCharAlt(10),
1321
+ new InternalRuleDefReference(7),
1322
+ new InternalRuleDefEnd(),
1323
+ ],
1324
+ [
1325
+ new InternalRuleDefReference(30),
1326
+ new InternalRuleDefAlt(),
1327
+ new InternalRuleDefEnd(),
1328
+ ],
1329
+ ],
1330
+ ],
1331
+ ],
1332
+ [
1333
+ "japanese",
1334
+ "\n # A probably incorrect grammar for Japanese\n root ::= jp-char+ ([ \\t\\n] jp-char+)*\n jp-char ::= hiragana | katakana | punctuation | cjk\n hiragana ::= [ぁ-ゟ]\n katakana ::= [ァ-ヿ]\n punctuation ::= [、-〾]\n cjk ::= [一-鿿]\n ",
1335
+ [
1336
+ [["root", 0], ["jp-char", 1], ["root_2", 2], ["root_3", 3], ["root_4", 4], ["root_5", 5], ["hiragana", 6], ["katakana", 7], ["punctuation", 8], ["cjk", 9]],
1337
+ [
1338
+ [
1339
+ new InternalRuleDefReference(2),
1340
+ new InternalRuleDefReference(5),
1341
+ new InternalRuleDefEnd(),
1342
+ ],
1343
+ [
1344
+ new InternalRuleDefReference(6),
1345
+ new InternalRuleDefAlt(),
1346
+ new InternalRuleDefReference(7),
1347
+ new InternalRuleDefAlt(),
1348
+ new InternalRuleDefReference(8),
1349
+ new InternalRuleDefAlt(),
1350
+ new InternalRuleDefReference(9),
1351
+ new InternalRuleDefEnd(),
1352
+ ],
1353
+ [
1354
+ new InternalRuleDefReference(1),
1355
+ new InternalRuleDefReference(2),
1356
+ new InternalRuleDefAlt(),
1357
+ new InternalRuleDefReference(1),
1358
+ new InternalRuleDefEnd(),
1359
+ ],
1360
+ [
1361
+ new InternalRuleDefChar([32]),
1362
+ new InternalRuleDefCharAlt(9),
1363
+ new InternalRuleDefCharAlt(10),
1364
+ new InternalRuleDefReference(4),
1365
+ new InternalRuleDefEnd(),
1366
+ ],
1367
+ [
1368
+ new InternalRuleDefReference(1),
1369
+ new InternalRuleDefReference(4),
1370
+ new InternalRuleDefAlt(),
1371
+ new InternalRuleDefReference(1),
1372
+ new InternalRuleDefEnd(),
1373
+ ],
1374
+ [
1375
+ new InternalRuleDefReference(3),
1376
+ new InternalRuleDefReference(5),
1377
+ new InternalRuleDefAlt(),
1378
+ new InternalRuleDefEnd(),
1379
+ ],
1380
+ [
1381
+ new InternalRuleDefChar([12353]),
1382
+ new InternalRuleDefCharRngUpper(12447),
1383
+ new InternalRuleDefEnd(),
1384
+ ],
1385
+ [
1386
+ new InternalRuleDefChar([12449]),
1387
+ new InternalRuleDefCharRngUpper(12543),
1388
+ new InternalRuleDefEnd(),
1389
+ ],
1390
+ [
1391
+ new InternalRuleDefChar([12289]),
1392
+ new InternalRuleDefCharRngUpper(12350),
1393
+ new InternalRuleDefEnd(),
1394
+ ],
1395
+ [
1396
+ new InternalRuleDefChar([19968]),
1397
+ new InternalRuleDefCharRngUpper(40959),
1398
+ new InternalRuleDefEnd(),
1399
+ ],
1400
+ ],
1401
+ ],
1402
+ ],
1403
+ ];
1404
+
1405
+ describe('RulesBuilder', () => {
1406
+ test.each(testCases)('it parses %s', (_key, grammar, [expectedSymbolIds, expectedRules]) => {
1407
+ const { rules, symbolIds } = new RulesBuilder(grammar);
1408
+ expect([...symbolIds]).toStrictEqual(expectedSymbolIds);
1409
+ expect(rules).toStrictEqual(expectedRules);
1410
+ });
1411
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/rules-builder.ts ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ type InternalRuleDef,
8
+ InternalRuleDefAlt,
9
+ InternalRuleDefChar,
10
+ InternalRuleDefCharAlt,
11
+ InternalRuleDefCharNot,
12
+ InternalRuleDefCharRngUpper,
13
+ InternalRuleDefEnd,
14
+ InternalRuleDefReference,
15
+ isRuleDefRef,
16
+ } from './rules-builder-types.js';
17
+ import { SymbolIds } from './symbol-ids.js';
18
+
19
+ type InternalRuleDefConstructor =
20
+ | typeof InternalRuleDefChar
21
+ | typeof InternalRuleDefCharNot
22
+ | typeof InternalRuleDefCharRngUpper
23
+ | typeof InternalRuleDefAlt
24
+ | typeof InternalRuleDefEnd
25
+ | typeof InternalRuleDefCharAlt;
26
+
27
+ export const getOutElements = (typeOfRule: InternalRuleDefConstructor, startcharValue: number): InternalRuleDef => {
28
+ if (typeOfRule === InternalRuleDefChar) {
29
+ return new InternalRuleDefChar([startcharValue]);
30
+ }
31
+ if (typeOfRule === InternalRuleDefCharNot) {
32
+ return new InternalRuleDefCharNot([startcharValue]);
33
+ }
34
+ if (typeOfRule === InternalRuleDefCharRngUpper) {
35
+ return new InternalRuleDefCharRngUpper(startcharValue);
36
+ }
37
+ if (typeOfRule === InternalRuleDefAlt) {
38
+ return new InternalRuleDefAlt();
39
+ }
40
+ if (typeOfRule === InternalRuleDefEnd) {
41
+ return new InternalRuleDefEnd();
42
+ }
43
+ if (typeOfRule === InternalRuleDefCharAlt) {
44
+ return new InternalRuleDefCharAlt(startcharValue);
45
+ }
46
+ throw new Error(`Invalid type: ${String(typeOfRule)}`);
47
+ };
48
+
49
+ const now = (): number => performance.now() / 1000;
50
+
51
+ export class RulesBuilder {
52
+ pos: number;
53
+ symbolIds: SymbolIds;
54
+ rules: InternalRuleDef[][];
55
+ src: string;
56
+ start: number;
57
+ timeLimit: number;
58
+
59
+ /**
60
+ * @param src The grammar source.
61
+ * @param limit Maximum parsing duration in seconds before aborting.
62
+ */
63
+ constructor(src: string, limit = 1000) {
64
+ this.pos = 0;
65
+ this.symbolIds = new SymbolIds();
66
+ this.rules = [];
67
+ this.src = src;
68
+ this.start = now();
69
+ this.timeLimit = limit;
70
+ this.parse(src);
71
+ }
72
+
73
+ private parse(src: string): void {
74
+ this.pos = parseSpace(src, 0, true);
75
+ while (this.pos < src.length) {
76
+ this.parseRule(src);
77
+ }
78
+
79
+ // Validate the state to ensure that all rules are defined
80
+ for (const rule of this.rules) {
81
+ for (const elem of rule) {
82
+ if (isRuleDefRef(elem)) {
83
+ const ruleExists = elem.value < this.rules.length && this.rules[elem.value].length > 0;
84
+ if (!ruleExists) {
85
+ const missingRuleName = this.symbolIds.reverseGet(elem.value);
86
+ let missingRulePos = this.symbolIds.getPos(missingRuleName);
87
+
88
+ // Skip over the ::= and any whitespace
89
+ while (
90
+ missingRulePos < src.length &&
91
+ (src[missingRulePos] === ':' || src[missingRulePos] === '=' || /\s/.test(src[missingRulePos]))
92
+ ) {
93
+ missingRulePos += 1;
94
+ }
95
+
96
+ throw new GrammarParseError(src, missingRulePos, `Undefined rule identifier "${missingRuleName}"`);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ }
102
+
103
+ private parseRule(src: string): void {
104
+ const name = parseName(src, this.pos);
105
+ this.pos = parseSpace(src, this.pos + name.length, false);
106
+ const ruleId = this.getSymbolId(name, name.length);
107
+
108
+ this.pos = parseSpace(src, this.pos, true);
109
+ if (
110
+ !(
111
+ this.pos + 2 < src.length && // Ensure the position + 2 is within bounds
112
+ src[this.pos] === ':' &&
113
+ src[this.pos + 1] === ':' &&
114
+ src[this.pos + 2] === '='
115
+ )
116
+ ) {
117
+ throw new GrammarParseError(src, this.pos, `Expecting ::= at ${this.pos}`);
118
+ }
119
+ this.pos += 3;
120
+ this.pos = parseSpace(src, this.pos, true);
121
+
122
+ this.parseAlternates(name, ruleId);
123
+
124
+ if (this.pos < src.length && src[this.pos] === '\r') {
125
+ this.pos += src[this.pos + 1] === '\n' ? 2 : 1;
126
+ } else if (this.pos < src.length && src[this.pos] === '\n') {
127
+ this.pos += 1;
128
+ } else if (this.pos < src.length) {
129
+ throw new GrammarParseError(src, this.pos, `Expecting newline or end at ${this.pos}`);
130
+ }
131
+ this.pos = parseSpace(src, this.pos, true);
132
+ }
133
+
134
+ private getSymbolId(src: string, length: number): number {
135
+ const nextId = this.symbolIds.size;
136
+ const key = src.slice(0, length);
137
+ if (!this.symbolIds.has(key)) {
138
+ this.symbolIds.set(key, nextId, this.pos);
139
+ }
140
+ return this.symbolIds.get(key) as number;
141
+ }
142
+
143
+ private generateSymbolId(baseName: string): number {
144
+ const nextId = this.symbolIds.size;
145
+ this.symbolIds.set(`${baseName}_${nextId}`, nextId, this.pos);
146
+ return nextId;
147
+ }
148
+
149
+ private addRule(ruleId: number, rule: InternalRuleDef[]): void {
150
+ while (this.rules.length <= ruleId) {
151
+ this.rules.push([]);
152
+ }
153
+ this.rules[ruleId] = rule;
154
+ }
155
+
156
+ private checkDuration(): void {
157
+ if (now() - this.start > this.timeLimit) {
158
+ throw new GrammarParseError(this.src, this.pos, `Duration of ${this.timeLimit} exceeded`);
159
+ }
160
+ }
161
+
162
+ private parseSequence(ruleName: string, outElements: InternalRuleDef[], depth = 0): void {
163
+ const isNested = depth !== 0;
164
+ const src = this.src;
165
+ let lastSymStart = outElements.length;
166
+
167
+ while (this.pos < src.length) {
168
+ if (src[this.pos] === '"') {
169
+ this.pos += 1;
170
+ lastSymStart = outElements.length;
171
+ while (src[this.pos] !== '"') {
172
+ this.checkDuration();
173
+ const [value, incPos] = parseChar(src, this.pos);
174
+ outElements.push(new InternalRuleDefChar([value]));
175
+ this.pos += incPos;
176
+ }
177
+ this.pos = parseSpace(src, this.pos + 1, isNested);
178
+ } else if (src[this.pos] === '[') {
179
+ this.pos += 1;
180
+ let startType: InternalRuleDefConstructor = InternalRuleDefChar;
181
+ if (src[this.pos] === '^') {
182
+ this.pos += 1;
183
+ startType = InternalRuleDefCharNot;
184
+ }
185
+ lastSymStart = outElements.length;
186
+ while (src[this.pos] !== ']') {
187
+ this.checkDuration();
188
+ const type: InternalRuleDefConstructor =
189
+ lastSymStart < outElements.length ? InternalRuleDefCharAlt : startType;
190
+ const [startcharValue, incPos] = parseChar(src, this.pos);
191
+ this.pos += incPos;
192
+ outElements.push(getOutElements(type, startcharValue));
193
+
194
+ if (src[this.pos] === '-' && src[this.pos + 1] !== ']') {
195
+ this.pos += 1;
196
+ const [endcharValue, endIncPos] = parseChar(src, this.pos);
197
+ outElements.push(new InternalRuleDefCharRngUpper(endcharValue));
198
+ this.pos += endIncPos;
199
+ }
200
+ }
201
+ this.pos = parseSpace(src, this.pos + 1, isNested);
202
+ } else if (isWordChar(src[this.pos])) {
203
+ const name = parseName(src, this.pos);
204
+ const refRuleId = this.getSymbolId(name, name.length);
205
+ this.pos += name.length;
206
+ this.pos = parseSpace(src, this.pos, isNested);
207
+
208
+ lastSymStart = outElements.length;
209
+ outElements.push(new InternalRuleDefReference(refRuleId));
210
+ } else if (src[this.pos] === '(') {
211
+ this.pos = parseSpace(src, this.pos + 1, true);
212
+ const subRuleId = this.generateSymbolId(ruleName);
213
+ this.parseAlternates(ruleName, subRuleId, depth + 1);
214
+ lastSymStart = outElements.length;
215
+ outElements.push(new InternalRuleDefReference(subRuleId));
216
+ if (src[this.pos] !== ')') {
217
+ throw new GrammarParseError(src, this.pos, `Expecting ')' at ${this.pos}`);
218
+ }
219
+ this.pos = parseSpace(src, this.pos + 1, isNested);
220
+ } else if (src[this.pos] === '*' || src[this.pos] === '+' || src[this.pos] === '?') {
221
+ if (lastSymStart === outElements.length) {
222
+ throw new GrammarParseError(src, this.pos, `Expecting preceding item to */+/? at ${this.pos}`);
223
+ }
224
+ const subRuleId = this.generateSymbolId(ruleName);
225
+ const subRule: InternalRuleDef[] = outElements.slice(lastSymStart);
226
+ if (src[this.pos] === '*' || src[this.pos] === '+') {
227
+ subRule.push(new InternalRuleDefReference(subRuleId));
228
+ }
229
+ subRule.push(new InternalRuleDefAlt());
230
+ if (src[this.pos] === '+') {
231
+ subRule.push(...outElements.slice(lastSymStart));
232
+ }
233
+ subRule.push(new InternalRuleDefEnd());
234
+ this.addRule(subRuleId, subRule);
235
+ outElements.splice(lastSymStart, outElements.length - lastSymStart, new InternalRuleDefReference(subRuleId));
236
+ this.pos = parseSpace(src, this.pos + 1, isNested);
237
+ } else {
238
+ break;
239
+ }
240
+ }
241
+ }
242
+
243
+ private parseAlternates(ruleName: string, ruleId: number, depth = 0): void {
244
+ const src = this.src;
245
+ const rule: InternalRuleDef[] = [];
246
+ this.parseSequence(ruleName, rule, depth);
247
+ while (this.pos < src.length && src[this.pos] === '|') {
248
+ this.checkDuration();
249
+ rule.push(new InternalRuleDefAlt());
250
+ this.pos = parseSpace(src, this.pos + 1, true);
251
+ this.parseSequence(ruleName, rule, depth);
252
+ }
253
+ rule.push(new InternalRuleDefEnd());
254
+ this.addRule(ruleId, rule);
255
+ }
256
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/symbol-ids.test.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { SymbolIds } from './symbol-ids.js';
3
+
4
+ describe('SymbolIds', () => {
5
+ test('it stores keys, values, and positions', () => {
6
+ const ids = new SymbolIds();
7
+ ids.set('root', 0, 5);
8
+ ids.set('foo', 1, 10);
9
+ expect(ids.size).toBe(2);
10
+ expect(ids.has('root')).toBe(true);
11
+ expect(ids.has('bar')).toBe(false);
12
+ expect(ids.get('foo')).toBe(1);
13
+ expect(ids.reverseGet(1)).toBe('foo');
14
+ expect(ids.getPos('root')).toBe(5);
15
+ expect([...ids]).toEqual([
16
+ ['root', 0],
17
+ ['foo', 1],
18
+ ]);
19
+ });
20
+
21
+ test('it throws for unknown values and keys', () => {
22
+ const ids = new SymbolIds();
23
+ expect(() => ids.reverseGet(3)).toThrow('SymbolIds does not contain value: 3');
24
+ expect(() => ids.getPos('nope')).toThrow('SymbolIds does not contain key: nope');
25
+ });
26
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/rules-builder/symbol-ids.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export class SymbolIds {
2
+ private readonly map = new Map<string, number>();
3
+ private readonly pos = new Map<string, number>();
4
+ private readonly reverseMap = new Map<number, string>();
5
+
6
+ items(): IterableIterator<[string, number]> {
7
+ return this.map.entries();
8
+ }
9
+
10
+ [Symbol.iterator](): 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
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/build-error-position.test.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { buildErrorPosition } from './build-error-position.js';
3
+
4
+ describe('buildErrorPosition', () => {
5
+ test.each<[string, number, [string, string]]>([
6
+ ['root ::= "foo"', 1, ['root ::= "foo"', ' ^']],
7
+ ['root ::= "foo"', 5, ['root ::= "foo"', ' ^']],
8
+ // multi line grammars with pos on first line
9
+ ['aa\\nbb', 1, ['aa', ' ^']],
10
+ // multi line grammars with pos on second line, first character
11
+ ['aa\\nbb', 2, ['aa\\nbb', '^']],
12
+ // multi line grammars with pos on second line, second character
13
+ ['aa\\nbb', 2 + 1, ['aa\\nbb', ' ^']],
14
+ // multi line grammars beyond error with pos on second line
15
+ ['aa\\nbb\\ncc', 2 + 1, ['aa\\nbb', ' ^']],
16
+ // multi line grammars beyond error with pos on third line, first char
17
+ ['aa\\nbb\\ncc', 2 + 2 + 0, ['aa\\nbb\\ncc', '^']],
18
+ // multi line grammars beyond error with pos on third line, second char
19
+ ['aa\\nbb\\ncc', 2 + 2 + 1, ['aa\\nbb\\ncc', ' ^']],
20
+ // multi line grammars beyond error with pos on fourth line, first char
21
+ ['aa\\nbb\\ncc\\ndd', 2 + 2 + 2 + 0, ['bb\\ncc\\ndd', '^']],
22
+ // multi line grammars beyond error with pos on fifth line, second char
23
+ ['aa\\nbb\\ncc\\ndd\\nee', 2 + 2 + 2 + 2 + 1, ['cc\\ndd\\nee', ' ^']],
24
+ ])('it correctly shows position for grammar %s at pos %i', (grammar, pos, [grammarOut, posOut]) => {
25
+ const result = buildErrorPosition(grammar.split('\\n').join('\n'), pos);
26
+ expect(result).toEqual([...grammarOut.split('\\n'), posOut]);
27
+ });
28
+
29
+ test('it renders a message for empty input', () => {
30
+ expect(buildErrorPosition('', 0)).toEqual(['No input provided']);
31
+ });
32
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/build-error-position.ts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW = 3;
2
+
3
+ export const buildErrorPosition = (src: string, pos: number): string[] => {
4
+ if (src === '') {
5
+ return ['No input provided'];
6
+ }
7
+ const lines = src.split('\n');
8
+
9
+ let lineIdx = 0;
10
+ while (lines[lineIdx] && pos > lines[lineIdx].length - 1 && pos < src.length) {
11
+ pos -= lines[lineIdx].length;
12
+ lineIdx += 1;
13
+ }
14
+
15
+ const linesToShow = lines.slice(
16
+ Math.max(0, lineIdx - (MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW - 1)),
17
+ lineIdx + 1,
18
+ );
19
+
20
+ return [...linesToShow, `${' '.repeat(pos)}^`];
21
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/errors-types.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ // ValidInput can either be a string, a number indicating a code point, or a list of code points.
2
+ export type ValidInput = string | number | number[];
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/get-input-as-string.test.ts ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import type { ValidInput } from './errors-types.js';
3
+ import { getInputAsString } from './get-input-as-string.js';
4
+
5
+ describe('getInputAsString', () => {
6
+ test.each<[ValidInput, string]>([
7
+ ['hello', 'hello'],
8
+ [[104, 101, 108, 108, 111], 'hello'],
9
+ [104, 'h'],
10
+ [0x1f600, '😀'],
11
+ [[0x1f600, 0x1f601], '😀😁'],
12
+ ])('it correctly converts %j to a string', (input, expected) => {
13
+ expect(getInputAsString(input)).toBe(expected);
14
+ });
15
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/get-input-as-string.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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((cp) => String.fromCodePoint(cp)).join('');
11
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/grammar-parse-error.test.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { GRAMMAR_PARSER_ERROR_HEADER_MESSAGE, GrammarParseError } from './grammar-parse-error.js';
3
+
4
+ describe('GrammarParseError', () => {
5
+ test('it renders a message', () => {
6
+ const grammar = 'aa\\nbb\\ncc\\ndd\\nee';
7
+ const pos = 5;
8
+ const reason = 'reason';
9
+ const err = new GrammarParseError(grammar.split('\\n').join('\n'), pos, reason);
10
+ const expected = [GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason), '', 'aa', 'bb', 'cc', ' ^'].join('\n');
11
+ expect(err.message).toBe(expected);
12
+ expect(String(err)).toBe(expected);
13
+ expect(err).toBeInstanceOf(Error);
14
+ expect(err.pos).toBe(pos);
15
+ expect(err.reason).toBe(reason);
16
+ });
17
+
18
+ test('it compares equal to an error with the same rendering', () => {
19
+ const a = new GrammarParseError('root', 1, 'x');
20
+ const b = new GrammarParseError('root', 1, 'x');
21
+ expect(a.equals(b)).toBe(true);
22
+ expect(a.equals(new GrammarParseError('root', 2, 'x'))).toBe(false);
23
+ });
24
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/grammar-parse-error.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason), '', ...buildErrorPosition(grammar, pos)].join('\n');
8
+
9
+ export class GrammarParseError extends Error {
10
+ grammar: string;
11
+ pos: number;
12
+ reason: string;
13
+
14
+ constructor(grammar: string, pos: number, reason: string) {
15
+ super(buildMessage(grammar, pos, reason));
16
+ this.name = 'GrammarParseError';
17
+ this.grammar = grammar;
18
+ this.pos = pos;
19
+ this.reason = reason;
20
+ }
21
+
22
+ toString(): string {
23
+ return buildMessage(this.grammar, this.pos, this.reason);
24
+ }
25
+
26
+ equals(other: unknown): boolean {
27
+ return this.toString() === String(other);
28
+ }
29
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/index.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export { GrammarParseError, GRAMMAR_PARSER_ERROR_HEADER_MESSAGE } from './grammar-parse-error.js';
2
+ export { InputParseError, INPUT_PARSER_ERROR_HEADER_MESSAGE } from './input-parse-error.js';
3
+ export type { ValidInput } from './errors-types.js';
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/input-parse-error.test.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { INPUT_PARSER_ERROR_HEADER_MESSAGE, InputParseError } from './input-parse-error.js';
3
+
4
+ describe('InputParseError', () => {
5
+ test('it renders a message', () => {
6
+ const input = 'some input';
7
+ const err = new InputParseError(input, 1);
8
+ expect(err.message).toBe([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', input, ' ^'].join('\n'));
9
+ });
10
+
11
+ test('it renders a message for code point', () => {
12
+ const err = new InputParseError('a', 0);
13
+ expect(err.message).toBe([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', 'a', '^'].join('\n'));
14
+ });
15
+
16
+ test('it renders a message for code points', () => {
17
+ const err = new InputParseError('abcd', 2);
18
+ expect(err.message).toBe([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', 'abcd', ' ^'].join('\n'));
19
+ });
20
+
21
+ test('it accounts for previous input', () => {
22
+ const err = new InputParseError([122], 0, [98, 97]);
23
+ expect(err.src).toBe('baz');
24
+ expect(String(err)).toBe([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', 'baz', ' ^'].join('\n'));
25
+ expect(err.errorForMostRecentInput).toBe([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', 'z', '^'].join('\n'));
26
+ expect(err.equals(new InputParseError('z', 0, 'ba'))).toBe(true);
27
+ });
28
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/errors/input-parse-error.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { buildErrorPosition } from './build-error-position.js';
2
+ import type { ValidInput } from './errors-types.js';
3
+ import { getInputAsString } from './get-input-as-string.js';
4
+
5
+ export const INPUT_PARSER_ERROR_HEADER_MESSAGE = 'Failed to parse input string:';
6
+
7
+ const buildMessage = (src: string, pos: number): string =>
8
+ [INPUT_PARSER_ERROR_HEADER_MESSAGE, '', ...buildErrorPosition(src, pos)].join('\n');
9
+
10
+ export class InputParseError extends Error {
11
+ mostRecentInput: ValidInput;
12
+ pos: number;
13
+ previousInput: ValidInput;
14
+
15
+ constructor(mostRecentInput: ValidInput, pos: number, previousInput: ValidInput = '') {
16
+ const previous = getInputAsString(previousInput);
17
+ super(buildMessage(`${previous}${getInputAsString(mostRecentInput)}`, pos + previous.length));
18
+ this.name = 'InputParseError';
19
+ this.mostRecentInput = mostRecentInput;
20
+ this.pos = pos;
21
+ this.previousInput = previousInput;
22
+ }
23
+
24
+ get src(): string {
25
+ return `${getInputAsString(this.previousInput)}${getInputAsString(this.mostRecentInput)}`;
26
+ }
27
+
28
+ get errorForMostRecentInput(): string {
29
+ return buildMessage(getInputAsString(this.mostRecentInput), this.pos);
30
+ }
31
+
32
+ toString(): string {
33
+ const previous = getInputAsString(this.previousInput);
34
+ return buildMessage(`${previous}${getInputAsString(this.mostRecentInput)}`, this.pos + previous.length);
35
+ }
36
+
37
+ equals(other: unknown): boolean {
38
+ return this.toString() === String(other);
39
+ }
40
+ }
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/is-point-in-range.test.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { isPointInRange } from './is-point-in-range.js';
3
+
4
+ describe('isPointInRange', () => {
5
+ test.each<[number, [number, number], boolean]>([
6
+ [96, [97, 122], false],
7
+ [97, [97, 122], true],
8
+ [98, [97, 122], true],
9
+ [122, [97, 122], true],
10
+ [123, [97, 122], false],
11
+ ])('it checks if point %i is in range %j', (point, range, expectation) => {
12
+ expect(isPointInRange(point, range)).toBe(expectation);
13
+ });
14
+
15
+ test('it throws for a non-integer point', () => {
16
+ expect(() => isPointInRange(1.5, [0, 2])).toThrow('point must be an integer');
17
+ });
18
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/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
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/validate-non-empty.test.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+ import { validateNonEmpty } from './validate-non-empty.js';
3
+
4
+ describe('validateNonEmpty', () => {
5
+ test('it returns the value when non-empty', () => {
6
+ expect(validateNonEmpty([1])).toEqual([1]);
7
+ });
8
+
9
+ test('it throws for an empty list', () => {
10
+ expect(() => validateNonEmpty([])).toThrow('Value cannot be empty.');
11
+ });
12
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/src/utils/validate-non-empty.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export const validateNonEmpty = <T>(value: T[]): T[] => {
2
+ if (!value || value.length === 0) {
3
+ throw new Error('Value cannot be empty.');
4
+ }
5
+ return value;
6
+ };
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/iteration/iteration-with-additional-strings.test.ts ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated from the Python integration tests; do not edit by hand.
2
+ import { describe, expect, test } from 'vitest';
3
+ import { GBNF, InputParseError, RuleChar, RuleCharExclude, RuleEnd } from '../../../src/index.js';
4
+
5
+ const ord = (c: string): number => c.codePointAt(0) as number;
6
+
7
+ type ExpectedRule = { type: string; value?: (number | [number, number])[] };
8
+ const transformExpected = (e: ExpectedRule) => {
9
+ if (e.type === 'char') return new RuleChar(e.value as (number | [number, number])[]);
10
+ if (e.type === 'char_exclude') return new RuleCharExclude(e.value as (number | [number, number])[]);
11
+ if (e.type === 'end') return new RuleEnd();
12
+ throw new Error(`Unknown type found in expectation array: ${e.type}`);
13
+ };
14
+ const sortKey = (r: { toJSON(): unknown }) => JSON.stringify(r.toJSON());
15
+ const sorted = <T extends { toJSON(): unknown }>(l: T[]) => [...l].sort((a, b) => sortKey(a).localeCompare(sortKey(b)));
16
+
17
+ describe('iteration', () => {
18
+ test.each<[string, string, string]>([
19
+ ["root ::= \"foo\"", "f", "1"],
20
+ ["root ::= \"foo\"", "f", "b"],
21
+ ["root ::= \"foo\"", "f", "o1"],
22
+ ["root ::= \"foo\"", "f", "ooo"],
23
+ ["root ::= \"foo\"", "f", "ooooooo"],
24
+ ["root ::= \"foo\" | \"bar\"", "f", "1"],
25
+ ["root ::= \"foo\" | \"bar\"", "b", "1"],
26
+ ["root ::= \"foo\" | \"bar\"", "f", "o1"],
27
+ ["root ::= \"foo\" | \"bar\"", "b", "a1"],
28
+ ["root ::= \"foo\" | \"bar\"", "f", "ooo"],
29
+ ["root ::= \"foo\" | \"bar\"", "b", "arrr"],
30
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "f", "1"],
31
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "f", "z"],
32
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "b", "b1"],
33
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "f", "o1"],
34
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "b", "al"],
35
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "f", "ooo"],
36
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "b", "azrr"],
37
+ ["root ::= foo\nfoo ::=\"foo\"", "f", "1"],
38
+ ["root ::= foo\nfoo ::=\"foo\"", "f", "b"],
39
+ ["root ::= foo\nfoo ::=\"foo\"", "f", "o1"],
40
+ ["root ::= foo\nfoo ::=\"foo\"", "f", "ooo"],
41
+ ["root::=foo|\"bar\"\nfoo::=\"foo\"", "f", "1"],
42
+ ["root::=foo|\"bar\"\nfoo::=\"foo\"", "f", "z"],
43
+ ["root::=foo|\"bar\"\nfoo::=\"foo\"", "b", "b1"],
44
+ ["root::=foo|\"bar\"\nfoo::=\"foo\"", "f", "o1"],
45
+ ["root::=foo|\"bar\"\nfoo::=\"foo\"", "f", "ooo"],
46
+ ["root::=foo|\"bar\"\nfoo::=\"foo\"", "b", "arr"],
47
+ ["root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "f", "1"],
48
+ ["root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "f", "z"],
49
+ ["root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "b", "1"],
50
+ ["root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "f", "o1"],
51
+ ["root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "f", "ooo"],
52
+ ["root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "b", "arr"],
53
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "f", "1"],
54
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "f", "z"],
55
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "b", "1"],
56
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "f", "o1"],
57
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "f", "ooo"],
58
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "b", "arr"],
59
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "b", "azr"],
60
+ ["root ::= [a-z]", "a", "A"],
61
+ ["root ::= [a-z]", "a", "0"],
62
+ ["root ::= [a-z]", "a", "az"],
63
+ ["root ::= [a-z]?", "a", "A"],
64
+ ["root ::= [a-z]?", "a", "0"],
65
+ ["root ::= [a-z]?", "a", "az"],
66
+ ["root ::= [a-z]+", "a", "A"],
67
+ ["root ::= [a-z]+", "a", "0"],
68
+ ["root ::= [a-z]+", "a", "z0"],
69
+ ["root ::= [a-z]*", "a", "A"],
70
+ ["root ::= [a-z]*", "a", "0"],
71
+ ["root ::= [a-z]*", "a", "z0"],
72
+ ])('it raises if encountering grammar %s with starting %s and additional %s', (grammar, starting, additional) => {
73
+ const state = GBNF(grammar, starting);
74
+ expect(() => state.add(additional)).toThrow(InputParseError);
75
+ });
76
+
77
+ test.each<[string, string, string, ExpectedRule[]]>([
78
+ ["root ::= \"foo\"", "", "f", [
79
+ { type: "char", value: [ord("o")] },
80
+ ]],
81
+ ["root ::= \"foo\"", "f", "o", [
82
+ { type: "char", value: [ord("o")] },
83
+ ]],
84
+ ["root ::= \"foo\"", "fo", "o", [
85
+ { type: "end" },
86
+ ]],
87
+ ["root ::= \"foo\" | \"bar\" ", "", "f", [
88
+ { type: "char", value: [ord("o")] },
89
+ ]],
90
+ ["root ::= \"foo\" | \"bar\" ", "f", "o", [
91
+ { type: "char", value: [ord("o")] },
92
+ ]],
93
+ ["root ::= \"foo\" | \"bar\" ", "fo", "o", [
94
+ { type: "end" },
95
+ ]],
96
+ ["root ::= \"foo\" | \"bar\" ", "", "b", [
97
+ { type: "char", value: [ord("a")] },
98
+ ]],
99
+ ["root ::= \"foo\" | \"bar\" ", "b", "a", [
100
+ { type: "char", value: [ord("r")] },
101
+ ]],
102
+ ["root ::= \"foo\" | \"bar\" ", "ba", "r", [
103
+ { type: "end" },
104
+ ]],
105
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "b", "a", [
106
+ { type: "char", value: [ord("r")] },
107
+ { type: "char", value: [ord("z")] },
108
+ ]],
109
+ ["root ::= [^f] \"o\"", "g", "o", [
110
+ { type: "end" },
111
+ ]],
112
+ ["root ::= [^A-Z]", "", "a", [
113
+ { type: "end" },
114
+ ]],
115
+ ["root ::= [^A-Z0-9]", "", "a", [
116
+ { type: "end" },
117
+ ]],
118
+ ["root ::= [^A-Z0-9_-]", "", "a", [
119
+ { type: "end" },
120
+ ]],
121
+ ["root ::= foo\nfoo ::= \"foo\"", "", "f", [
122
+ { type: "char", value: [ord("o")] },
123
+ ]],
124
+ ["root ::= foo\nfoo ::= \"foo\"", "f", "o", [
125
+ { type: "char", value: [ord("o")] },
126
+ ]],
127
+ ["root ::= foo\nfoo ::= \"foo\"", "fo", "o", [
128
+ { type: "end" },
129
+ ]],
130
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "", "f", [
131
+ { type: "char", value: [ord("o")] },
132
+ ]],
133
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "f", "o", [
134
+ { type: "char", value: [ord("o")] },
135
+ ]],
136
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "fo", "o", [
137
+ { type: "end" },
138
+ ]],
139
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "", "b", [
140
+ { type: "char", value: [ord("a")] },
141
+ ]],
142
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "b", "a", [
143
+ { type: "char", value: [ord("r")] },
144
+ ]],
145
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "ba", "r", [
146
+ { type: "end" },
147
+ ]],
148
+ ["root ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "", "f", [
149
+ { type: "char", value: [ord("o")] },
150
+ ]],
151
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "f", "o", [
152
+ { type: "char", value: [ord("o")] },
153
+ ]],
154
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "fo", "o", [
155
+ { type: "end" },
156
+ ]],
157
+ ["root ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "", "b", [
158
+ { type: "char", value: [ord("a")] },
159
+ ]],
160
+ ["root ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "b", "a", [
161
+ { type: "char", value: [ord("r")] },
162
+ ]],
163
+ ["root ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "ba", "r", [
164
+ { type: "end" },
165
+ ]],
166
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "", "f", [
167
+ { type: "char", value: [ord("o")] },
168
+ ]],
169
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "f", "o", [
170
+ { type: "char", value: [ord("o")] },
171
+ ]],
172
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "fo", "o", [
173
+ { type: "end" },
174
+ ]],
175
+ ["root ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "", "b", [
176
+ { type: "char", value: [ord("a")] },
177
+ ]],
178
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "b", "a", [
179
+ { type: "char", value: [ord("r")] },
180
+ { type: "char", value: [ord("z")] },
181
+ ]],
182
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "ba", "r", [
183
+ { type: "end" },
184
+ ]],
185
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "ba", "z", [
186
+ { type: "end" },
187
+ ]],
188
+ ["root ::= [a-z]", "", "a", [
189
+ { type: "end" },
190
+ ]],
191
+ ["root ::= [a-z]", "", "m", [
192
+ { type: "end" },
193
+ ]],
194
+ ["root ::= [a-z]", "", "z", [
195
+ { type: "end" },
196
+ ]],
197
+ ["root ::= [a-zA-Z]", "", "a", [
198
+ { type: "end" },
199
+ ]],
200
+ ["root ::= [a-zA-Z]", "", "Z", [
201
+ { type: "end" },
202
+ ]],
203
+ ["root ::= [a-zA-Z0-9]", "", "Z", [
204
+ { type: "end" },
205
+ ]],
206
+ ["root ::= [a-zA-Z0-9]", "", "0", [
207
+ { type: "end" },
208
+ ]],
209
+ ["root ::= [a-zA-Z0-9]", "", "9", [
210
+ { type: "end" },
211
+ ]],
212
+ ["root ::= [a-z]?", "", "a", [
213
+ { type: "end" },
214
+ ]],
215
+ ["root ::= [a-zA-Z]?", "", "Z", [
216
+ { type: "end" },
217
+ ]],
218
+ ["root ::= [a-zA-Z0-9]?", "", "0", [
219
+ { type: "end" },
220
+ ]],
221
+ ["root ::= [a-z]+", "", "a", [
222
+ { type: "char", value: [[ord("a"), ord("z")]] },
223
+ { type: "end" },
224
+ ]],
225
+ ["root ::= [a-zA-Z]+", "", "Z", [
226
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
227
+ { type: "end" },
228
+ ]],
229
+ ["root ::= [a-zA-Z]+", "azA", "Z", [
230
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
231
+ { type: "end" },
232
+ ]],
233
+ ["root ::= [a-z]*", "", "a", [
234
+ { type: "char", value: [[ord("a"), ord("z")]] },
235
+ { type: "end" },
236
+ ]],
237
+ ["root ::= [a-zA-Z]+", "", "Z", [
238
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
239
+ { type: "end" },
240
+ ]],
241
+ ["root ::= [a-zA-Z]+", "acczABC", "Z", [
242
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
243
+ { type: "end" },
244
+ ]],
245
+ ["root ::= \"foo\" | \"bar\" | \"baz\" | \"bazaar\" | \"barrington\" ", "baza", "a", [
246
+ { type: "char", value: [ord("r")] },
247
+ ]],
248
+ ["root ::= [^f]+ \"o\"", "aaa", "a", [
249
+ { type: "char_exclude", value: [ord("f")] },
250
+ { type: "char", value: [ord("o")] },
251
+ ]],
252
+ ["root ::= [^A-Z]+", "abc", "d", [
253
+ { type: "char_exclude", value: [[ord("A"), ord("Z")]] },
254
+ { type: "end" },
255
+ ]],
256
+ ["root ::= [^A-Z0-9]*", "abc", "d", [
257
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")]] },
258
+ { type: "end" },
259
+ ]],
260
+ ["root ::= [^A-Z0-9_-]*", "abc", "d", [
261
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")], ord("_"), ord("-")] },
262
+ { type: "end" },
263
+ ]],
264
+ ])('it parses a grammar %s with starting %s and additional %s', (grammar, starting, additional, expected) => {
265
+ let state = GBNF(grammar, starting);
266
+ state = state.add(additional);
267
+ expect(sorted([...state])).toStrictEqual(sorted(expected.map(transformExpected)));
268
+ });
269
+
270
+ test.each([false, true])('it raises a particular error (errorForMostRecentInput: %s)', (errorForMostRecentInput) => {
271
+ const grammar = 'root ::= "bar"';
272
+ let state = GBNF(grammar);
273
+ state = state.add('b');
274
+ state = state.add('a');
275
+ let err: unknown;
276
+ try {
277
+ state.add('z');
278
+ } catch (e) {
279
+ err = e;
280
+ }
281
+ expect(err).toBeInstanceOf(InputParseError);
282
+ const expectedError = new InputParseError('z', 0, 'ba');
283
+ if (errorForMostRecentInput) {
284
+ expect((err as InputParseError).errorForMostRecentInput).toBe(expectedError.errorForMostRecentInput);
285
+ } else {
286
+ expect(String(err)).toBe(String(expectedError));
287
+ }
288
+ });
289
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/iteration/iteration-with-an-initial-string.test.ts ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated from the Python integration tests; do not edit by hand.
2
+ import { describe, expect, test } from 'vitest';
3
+ import { GBNF, RuleChar, RuleCharExclude, RuleEnd } from '../../../src/index.js';
4
+
5
+ const ord = (c: string): number => c.codePointAt(0) as number;
6
+
7
+ type ExpectedRule = { type: string; value?: (number | [number, number])[] };
8
+ const transformExpected = (e: ExpectedRule) => {
9
+ if (e.type === 'char') return new RuleChar(e.value as (number | [number, number])[]);
10
+ if (e.type === 'char_exclude') return new RuleCharExclude(e.value as (number | [number, number])[]);
11
+ if (e.type === 'end') return new RuleEnd();
12
+ throw new Error(`Unknown type found in expectation array: ${e.type}`);
13
+ };
14
+ const sortKey = (r: { toJSON(): unknown }) => JSON.stringify(r.toJSON());
15
+ const sorted = <T extends { toJSON(): unknown }>(l: T[]) => [...l].sort((a, b) => sortKey(a).localeCompare(sortKey(b)));
16
+
17
+ describe('iteration', () => {
18
+ test.each<[string, string, ExpectedRule[]]>([
19
+ ["root ::= \"foo\"", "", [
20
+ { type: "char", value: [ord("f")] },
21
+ ]],
22
+ ["root ::= \"foo\"", "f", [
23
+ { type: "char", value: [ord("o")] },
24
+ ]],
25
+ ["root ::= \"foo\"", "fo", [
26
+ { type: "char", value: [ord("o")] },
27
+ ]],
28
+ ["root ::= \"foo\"", "foo", [
29
+ { type: "end" },
30
+ ]],
31
+ ["root ::= \"foo\" | \"bar\" ", "", [
32
+ { type: "char", value: [ord("f")] },
33
+ { type: "char", value: [ord("b")] },
34
+ ]],
35
+ ["root ::= \"foo\" | \"bar\" ", "f", [
36
+ { type: "char", value: [ord("o")] },
37
+ ]],
38
+ ["root ::= \"foo\" | \"bar\" ", "fo", [
39
+ { type: "char", value: [ord("o")] },
40
+ ]],
41
+ ["root ::= \"foo\" | \"bar\" ", "foo", [
42
+ { type: "end" },
43
+ ]],
44
+ ["root ::= \"foo\" | \"bar\" ", "b", [
45
+ { type: "char", value: [ord("a")] },
46
+ ]],
47
+ ["root ::= \"foo\" | \"bar\" ", "ba", [
48
+ { type: "char", value: [ord("r")] },
49
+ ]],
50
+ ["root ::= \"foo\" | \"bar\" ", "bar", [
51
+ { type: "end" },
52
+ ]],
53
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "ba", [
54
+ { type: "char", value: [ord("r")] },
55
+ { type: "char", value: [ord("z")] },
56
+ ]],
57
+ ["root ::= \"[\"", "[", [
58
+ { type: "end" },
59
+ ]],
60
+ ["root ::= \"]\"", "]", [
61
+ { type: "end" },
62
+ ]],
63
+ ["root ::= \"[]\"", "[]", [
64
+ { type: "end" },
65
+ ]],
66
+ ["root ::= \"{\"", "{", [
67
+ { type: "end" },
68
+ ]],
69
+ ["root ::= \"}\"", "}", [
70
+ { type: "end" },
71
+ ]],
72
+ ["root ::= \"{}\"", "{}", [
73
+ { type: "end" },
74
+ ]],
75
+ ["root ::= \"[{}]\"", "[{}]", [
76
+ { type: "end" },
77
+ ]],
78
+ ["root ::= [^f] \"o\"", "", [
79
+ { type: "char_exclude", value: [ord("f")] },
80
+ ]],
81
+ ["root ::= [^f] \"o\"", "a", [
82
+ { type: "char", value: [ord("o")] },
83
+ ]],
84
+ ["root ::= [^A-Z]", "", [
85
+ { type: "char_exclude", value: [[ord("A"), ord("Z")]] },
86
+ ]],
87
+ ["root ::= [^A-Z0-9]", "", [
88
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")]] },
89
+ ]],
90
+ ["root ::= [^A-Z0-9_-]", "", [
91
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")], ord("_"), ord("-")] },
92
+ ]],
93
+ ["\nroot ::= foo\nfoo ::= \"foo\"", "", [
94
+ { type: "char", value: [ord("f")] },
95
+ ]],
96
+ ["root ::= foo\nfoo ::= \"foo\"\n", "f", [
97
+ { type: "char", value: [ord("o")] },
98
+ ]],
99
+ ["\nroot ::= foo\nfoo ::= \"foo\"\n", "fo", [
100
+ { type: "char", value: [ord("o")] },
101
+ ]],
102
+ ["root ::= foo\nfoo ::= \"foo\"", "foo", [
103
+ { type: "end" },
104
+ ]],
105
+ ["root ::= f\nf ::= foo\nfoo ::= \"foo\"", "", [
106
+ { type: "char", value: [ord("f")] },
107
+ ]],
108
+ ["\nroot ::= foo | \"bar\"\nfoo ::= \"foo\"\n", "", [
109
+ { type: "char", value: [ord("f")] },
110
+ { type: "char", value: [ord("b")] },
111
+ ]],
112
+ ["\nroot ::= foo | \"bar\"\nfoo ::= \"foo\"", "f", [
113
+ { type: "char", value: [ord("o")] },
114
+ ]],
115
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "fo", [
116
+ { type: "char", value: [ord("o")] },
117
+ ]],
118
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "foo", [
119
+ { type: "end" },
120
+ ]],
121
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "b", [
122
+ { type: "char", value: [ord("a")] },
123
+ ]],
124
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "ba", [
125
+ { type: "char", value: [ord("r")] },
126
+ ]],
127
+ ["root ::= foo | \"bar\"\nfoo ::= \"foo\"", "bar", [
128
+ { type: "end" },
129
+ ]],
130
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "", [
131
+ { type: "char", value: [ord("f")] },
132
+ { type: "char", value: [ord("b")] },
133
+ ]],
134
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "f", [
135
+ { type: "char", value: [ord("o")] },
136
+ ]],
137
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "fo", [
138
+ { type: "char", value: [ord("o")] },
139
+ ]],
140
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "foo", [
141
+ { type: "end" },
142
+ ]],
143
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "b", [
144
+ { type: "char", value: [ord("a")] },
145
+ ]],
146
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "ba", [
147
+ { type: "char", value: [ord("r")] },
148
+ ]],
149
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"", "bar", [
150
+ { type: "end" },
151
+ ]],
152
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "", [
153
+ { type: "char", value: [ord("f")] },
154
+ { type: "char", value: [ord("b")] },
155
+ ]],
156
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "f", [
157
+ { type: "char", value: [ord("o")] },
158
+ ]],
159
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "fo", [
160
+ { type: "char", value: [ord("o")] },
161
+ ]],
162
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "foo", [
163
+ { type: "end" },
164
+ ]],
165
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "b", [
166
+ { type: "char", value: [ord("a")] },
167
+ ]],
168
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "ba", [
169
+ { type: "char", value: [ord("r")] },
170
+ { type: "char", value: [ord("z")] },
171
+ ]],
172
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "bar", [
173
+ { type: "end" },
174
+ ]],
175
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"", "baz", [
176
+ { type: "end" },
177
+ ]],
178
+ ["root ::= [a-z]", "", [
179
+ { type: "char", value: [[ord("a"), ord("z")]] },
180
+ ]],
181
+ ["root ::= [a-zA-Z]", "", [
182
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
183
+ ]],
184
+ ["root ::= [a-z]", "a", [
185
+ { type: "end" },
186
+ ]],
187
+ ["root ::= [a-z]", "m", [
188
+ { type: "end" },
189
+ ]],
190
+ ["root ::= [a-z]", "z", [
191
+ { type: "end" },
192
+ ]],
193
+ ["root ::= [a-zA-Z]", "a", [
194
+ { type: "end" },
195
+ ]],
196
+ ["root ::= [a-zA-Z]", "Z", [
197
+ { type: "end" },
198
+ ]],
199
+ ["root ::= [a-zA-Z0-9]", "Z", [
200
+ { type: "end" },
201
+ ]],
202
+ ["root ::= [a-zA-Z0-9]", "0", [
203
+ { type: "end" },
204
+ ]],
205
+ ["root ::= [a-zA-Z0-9]", "9", [
206
+ { type: "end" },
207
+ ]],
208
+ ["root ::= [a-z]?", "", [
209
+ { type: "char", value: [[ord("a"), ord("z")]] },
210
+ { type: "end" },
211
+ ]],
212
+ ["root ::= [a-z]?", "a", [
213
+ { type: "end" },
214
+ ]],
215
+ ["root ::= [a-zA-Z]?", "Z", [
216
+ { type: "end" },
217
+ ]],
218
+ ["root ::= [a-zA-Z0-9]?", "0", [
219
+ { type: "end" },
220
+ ]],
221
+ ["root ::= [a-z]+", "", [
222
+ { type: "char", value: [[ord("a"), ord("z")]] },
223
+ ]],
224
+ ["root ::= [a-z]+", "l", [
225
+ { type: "char", value: [[ord("a"), ord("z")]] },
226
+ { type: "end" },
227
+ ]],
228
+ ["root ::= [a-zA-Z]+", "Z", [
229
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
230
+ { type: "end" },
231
+ ]],
232
+ ["root ::= [a-zA-Z]+", "aZ", [
233
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
234
+ { type: "end" },
235
+ ]],
236
+ ["root ::= [a-zA-Z]+", "azAZ", [
237
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
238
+ { type: "end" },
239
+ ]],
240
+ ["root ::= [a-z]*", "", [
241
+ { type: "char", value: [[ord("a"), ord("z")]] },
242
+ { type: "end" },
243
+ ]],
244
+ ["root ::= [a-z]*", "a", [
245
+ { type: "char", value: [[ord("a"), ord("z")]] },
246
+ { type: "end" },
247
+ ]],
248
+ ["root ::= [a-zA-Z]+", "Z", [
249
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
250
+ { type: "end" },
251
+ ]],
252
+ ["root ::= [a-zA-Z]+", "abczABCZ", [
253
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
254
+ { type: "end" },
255
+ ]],
256
+ ["root ::= [^f]+ \"o\"", "aaa", [
257
+ { type: "char_exclude", value: [ord("f")] },
258
+ { type: "char", value: [ord("o")] },
259
+ ]],
260
+ ["root ::= [^A-Z]+", "abc", [
261
+ { type: "char_exclude", value: [[ord("A"), ord("Z")]] },
262
+ { type: "end" },
263
+ ]],
264
+ ["root ::= [^A-Z0-9]*", "abc", [
265
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")]] },
266
+ { type: "end" },
267
+ ]],
268
+ ["root ::= [^A-Z0-9_-]*", "abc", [
269
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")], ord("_"), ord("-")] },
270
+ { type: "end" },
271
+ ]],
272
+ ["\nroot ::= [a-z] | xyx\nxyx ::= \"foo\"", "f", [
273
+ { type: "end" },
274
+ { type: "char", value: [ord("o")] },
275
+ ]],
276
+ ["root ::= \"foo\" | \"bar\" | \"baz\" | \"bazaar\" | \"barrington\" ", "bazaa", [
277
+ { type: "char", value: [ord("r")] },
278
+ ]],
279
+ ["root ::= (\"bar\" | \"foo\") \"zyx\"", "bar", [
280
+ { type: "char", value: [ord("z")] },
281
+ ]],
282
+ ["root ::= \"z\" (\"bar\" | \"foo\") \"zzzz\"", "z", [
283
+ { type: "char", value: [ord("b")] },
284
+ { type: "char", value: [ord("f")] },
285
+ ]],
286
+ ["root ::= \"z\" (\"bar\" | \"foo\") \"zzz\"", "zbar", [
287
+ { type: "char", value: [ord("z")] },
288
+ ]],
289
+ ["\nroot ::= termz ([-+*/] termz)* \ntermz ::= [0-9]+", "1", [
290
+ { type: "char", value: [[ord("0"), ord("9")]] },
291
+ { type: "char", value: [ord("-"), ord("+"), ord("*"), ord("/")] },
292
+ { type: "end" },
293
+ ]],
294
+ ["\nroot ::= expr \"=\" termy \nexpr ::= termy ([-+*/] termy)*\ntermy ::= [0-9]+", "1", [
295
+ { type: "char", value: [[ord("0"), ord("9")]] },
296
+ { type: "char", value: [ord("-"), ord("+"), ord("*"), ord("/")] },
297
+ { type: "char", value: [ord("=")] },
298
+ ]],
299
+ ["\nroot ::= (expr \"=\" terma \"\n\")+\nexpr ::= terma ([-+*/] terma)*\nterma ::= [0-9]+", "1", [
300
+ { type: "char", value: [[ord("0"), ord("9")]] },
301
+ { type: "char", value: [ord("-"), ord("+"), ord("*"), ord("/")] },
302
+ { type: "char", value: [ord("=")] },
303
+ ]],
304
+ ["root ::= (expr \"=\" termb \"\n\")+\nexpr ::= termb ([-+*/] termb)*\ntermb ::= [0-9]+", "1+", [
305
+ { type: "char", value: [[ord("0"), ord("9")]] },
306
+ ]],
307
+ ["\nroot ::= (expr \"=\" termc \"\n\")+\nexpr ::= termc ([-+*/] termc)*\ntermc ::= [0-9]+", "1=", [
308
+ { type: "char", value: [[ord("0"), ord("9")]] },
309
+ ]],
310
+ ["root ::= (expr \"=\" termd \"\n\")+\nexpr ::= termd ([-+*/] termd)*\ntermd ::= [0-9]+", "1+1", [
311
+ { type: "char", value: [[ord("0"), ord("9")]] },
312
+ { type: "char", value: [ord("-"), ord("+"), ord("*"), ord("/")] },
313
+ { type: "char", value: [ord("=")] },
314
+ ]],
315
+ ["root ::= (expr \"=\" term \"\n\")+\nexpr ::= term ([-+*/] term)*\nterm ::= [0-9]+", "1=1", [
316
+ { type: "char", value: [[ord("0"), ord("9")]] },
317
+ { type: "char", value: [10] },
318
+ ]],
319
+ ["root ::= \"\\\"\" ( [^\\\"abcdefghA-Z])* ", "\"is not only in its lyrism, its vow to sustin it in its poo-sion, its r,v:l'y, it's tory,", [
320
+ { type: "char_exclude", value: [34, ord("a"), ord("b"), ord("c"), ord("d"), ord("e"), ord("f"), ord("g"), ord("h"), [ord("A"), ord("Z")]] },
321
+ { type: "end" },
322
+ ]],
323
+ ["root ::= ( [^abcdefgh] | [b-z])* ", "bcdefghzyxw0123ABCZ", [
324
+ { type: "char_exclude", value: [ord("a"), ord("b"), ord("c"), ord("d"), ord("e"), ord("f"), ord("g"), ord("h")] },
325
+ { type: "char", value: [[ord("b"), ord("z")]] },
326
+ { type: "end" },
327
+ ]],
328
+ ])('it returns parse state for grammar %s and initial string %s', (grammar, inputString, expected) => {
329
+ let state = GBNF(grammar);
330
+ state = state.add(inputString);
331
+ expect(sorted([...state])).toStrictEqual(sorted(expected.map(transformExpected)));
332
+ });
333
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/iteration/iteration.test.ts ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated from the Python integration tests; do not edit by hand.
2
+ import { describe, expect, test } from 'vitest';
3
+ import { GBNF, RuleChar, RuleCharExclude, RuleEnd } from '../../../src/index.js';
4
+
5
+ const ord = (c: string): number => c.codePointAt(0) as number;
6
+
7
+ type ExpectedRule = { type: string; value?: (number | [number, number])[] };
8
+ const transformExpected = (e: ExpectedRule) => {
9
+ if (e.type === 'char') return new RuleChar(e.value as (number | [number, number])[]);
10
+ if (e.type === 'char_exclude') return new RuleCharExclude(e.value as (number | [number, number])[]);
11
+ if (e.type === 'end') return new RuleEnd();
12
+ throw new Error(`Unknown type found in expectation array: ${e.type}`);
13
+ };
14
+ const sortKey = (r: { toJSON(): unknown }) => JSON.stringify(r.toJSON());
15
+ const sorted = <T extends { toJSON(): unknown }>(l: T[]) => [...l].sort((a, b) => sortKey(a).localeCompare(sortKey(b)));
16
+
17
+ describe('iteration', () => {
18
+ test.each<[string, ExpectedRule[]]>([
19
+ ["root ::= \"foo\"", [
20
+ { type: "char", value: [ord("f")] },
21
+ ]],
22
+ ["root ::= \"foo\" | \"bar\" ", [
23
+ { type: "char", value: [ord("f")] },
24
+ { type: "char", value: [ord("b")] },
25
+ ]],
26
+ ["root ::= \"foo\" | \"bar\" | \"gaz\"", [
27
+ { type: "char", value: [ord("f")] },
28
+ { type: "char", value: [ord("b")] },
29
+ { type: "char", value: [ord("g")] },
30
+ ]],
31
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", [
32
+ { type: "char", value: [ord("f")] },
33
+ { type: "char", value: [ord("b")] },
34
+ ]],
35
+ ["root ::= [^x]", [
36
+ { type: "char_exclude", value: [ord("x")] },
37
+ ]],
38
+ ["root ::= [^f] \"o\"", [
39
+ { type: "char_exclude", value: [ord("f")] },
40
+ ]],
41
+ ["root ::= [^A-Z]", [
42
+ { type: "char_exclude", value: [[ord("A"), ord("Z")]] },
43
+ ]],
44
+ ["root ::= [^A-Z0-9]", [
45
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")]] },
46
+ ]],
47
+ ["root ::= [^A-Z0-9_-]", [
48
+ { type: "char_exclude", value: [[ord("A"), ord("Z")], [ord("0"), ord("9")], ord("_"), ord("-")] },
49
+ ]],
50
+ ["\nroot ::= foo\nfoo ::= \"foo\"\n ", [
51
+ { type: "char", value: [ord("f")] },
52
+ ]],
53
+ ["\nroot ::= f\nf ::= foo\nfoo ::= \"foo\"\n ", [
54
+ { type: "char", value: [ord("f")] },
55
+ ]],
56
+ ["\nroot ::= foo | \"bar\"\nfoo ::= \"foo\"", [
57
+ { type: "char", value: [ord("f")] },
58
+ { type: "char", value: [ord("b")] },
59
+ ]],
60
+ ["\nroot ::= foo | bar\nfoo ::= \"foo\"\nbar ::= \"bar\"\n ", [
61
+ { type: "char", value: [ord("f")] },
62
+ { type: "char", value: [ord("b")] },
63
+ ]],
64
+ ["\nroot ::= f | b\nf ::= fo\nb ::= ba\nfo ::= foo\nba ::= bar | baz\nfoo ::= \"foo\"\nbar ::= \"bar\"\nbaz ::= \"baz\"\n ", [
65
+ { type: "char", value: [ord("f")] },
66
+ { type: "char", value: [ord("b")] },
67
+ ]],
68
+ ["root ::= [a-z]", [
69
+ { type: "char", value: [[ord("a"), ord("z")]] },
70
+ ]],
71
+ ["root ::= [a-zA-Z]", [
72
+ { type: "char", value: [[ord("a"), ord("z")], [ord("A"), ord("Z")]] },
73
+ ]],
74
+ ["root ::= [a-z]?", [
75
+ { type: "char", value: [[ord("a"), ord("z")]] },
76
+ { type: "end" },
77
+ ]],
78
+ ["root ::= [a-z]+", [
79
+ { type: "char", value: [[ord("a"), ord("z")]] },
80
+ ]],
81
+ ["root ::= [a-z]*", [
82
+ { type: "char", value: [[ord("a"), ord("z")]] },
83
+ { type: "end" },
84
+ ]],
85
+ ["\n root ::= \"foo\"\n foo ::= \"foo\"", [
86
+ { type: "char", value: [ord("f")] },
87
+ ]],
88
+ ["\n root ::= (expr \"=\" term \"\")+\n expr ::= term ([-+*/] term)*\n term ::= [0-9]+\n ", [
89
+ { type: "char", value: [[ord("0"), ord("9")]] },
90
+ ]],
91
+ ])('it returns parse state for grammar %s', (grammar, expected) => {
92
+ const state = [...GBNF(grammar)];
93
+ expect(state).toStrictEqual(expected.map(transformExpected));
94
+ });
95
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/validation/validate-grammar.test.ts ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated from the Python integration tests; do not edit by hand.
2
+ import { describe, expect, test } from 'vitest';
3
+ import { GBNF, GrammarParseError } from '../../../src/index.js';
4
+
5
+ const ord = (c: string): number => c.codePointAt(0) as number;
6
+
7
+ describe('validate grammar', () => {
8
+ test.each<string>([
9
+ "root ::= \"foo\"",
10
+ "root ::= \"foo\" | \"bar\"",
11
+ "root ::= (\"foo\" | \"bar\")",
12
+ "root ::= (\"foo\" | \"bar\")?",
13
+ "root ::= (\"foo\" | \"bar\")*",
14
+ "root ::= (\"foo\" | \"bar\")+",
15
+ "root ::= [a-z]",
16
+ "root ::= [a-zA-Z]",
17
+ "root ::= [a-zA-Z0-9]",
18
+ "root ::= [a-zA-Z0-9]*",
19
+ "root ::= [a-zA-Z0-9]?",
20
+ "root ::= [a-z]+",
21
+ "root ::= [a-zA-Z0-9]+",
22
+ "root ::= ([a-zA-Z0-9])*",
23
+ "root ::= ([a-zA-Z0-9])?",
24
+ "root ::= ([a-zA-Z0-9])+",
25
+ "\n root ::= foo\n foo ::= \"foo\"",
26
+ "\n root ::= foo\n foo ::= \"foo\" | \"bar\" | ([a-z])?\n ",
27
+ ])('it parses a grammar %s', (grammar) => {
28
+ expect(() => GBNF(grammar)).not.toThrow();
29
+ });
30
+
31
+ test.each<[string, number, string]>([
32
+ ["", 0, "No rules were found"],
33
+ ["root = \"foo\"", 5, "Expecting ::= at 5"],
34
+ ["root ::= foo\nfoo := \"foo\"\n ", 17, "Expecting ::= at 17"],
35
+ ["root ::= foo", 9, "Undefined rule identifier \"foo\""],
36
+ ["root ::= foo\nbar ::= \"bar\"\n ", 9, "Undefined rule identifier \"foo\""],
37
+ ["root ::= foo\nfoo ::= baz\nbar ::= \"bar\"\n ", 21, "Undefined rule identifier \"baz\""],
38
+ ["root ::= foo ::= bar", 13, "Expecting newline or end at 13"],
39
+ ["root ::= ([a-z]\nfoo ::= \"foo\"\n ", 20, "Expecting ')' at 20"],
40
+ ])('it reports an error for an invalid grammar %s', (grammar, errorPos, errorReason) => {
41
+ const expected = new GrammarParseError(grammar, errorPos, errorReason);
42
+ let err: unknown;
43
+ try {
44
+ GBNF(grammar);
45
+ } catch (e) {
46
+ err = e;
47
+ }
48
+ expect(err).toBeInstanceOf(GrammarParseError);
49
+ expect(String(err)).toBe(String(expected));
50
+ expect((err as GrammarParseError).message).toBe(expected.message);
51
+ expect((err as GrammarParseError).pos).toBe(errorPos);
52
+ expect((err as GrammarParseError).reason).toBe(errorReason);
53
+ });
54
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tests/generated/validation/validate-input.test.ts ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated from the Python integration tests; do not edit by hand.
2
+ import { describe, expect, test } from 'vitest';
3
+ import { GBNF, InputParseError } from '../../../src/index.js';
4
+
5
+ const ord = (c: string): number => c.codePointAt(0) as number;
6
+
7
+ describe('validate input', () => {
8
+ test.each<[string, string]>([
9
+ ["root ::= \"foo\"", "f"],
10
+ ])('it parses a grammar %s with input %s', (grammar, input) => {
11
+ const graph = GBNF(grammar, input);
12
+ expect(Boolean(graph)).toBe(true);
13
+ });
14
+
15
+ test.each<[string, string, number]>([
16
+ ["root ::= \"foo\"", "2", 0],
17
+ ["root ::= \"foo\"", "b", 0],
18
+ ["root ::= \"foo\"", "f1", 1],
19
+ ["root ::= \"foo\"", "fo1", 2],
20
+ ["root ::= \"foo\"", "fooo", 3],
21
+ ["root ::= \"foo\"", "fooooooo", 3],
22
+ ["root ::= \"foo\" | \"bar\"", "1", 0],
23
+ ["root ::= \"foo\" | \"bar\"", "z", 0],
24
+ ["root ::= \"foo\" | \"bar\"", "f1", 1],
25
+ ["root ::= \"foo\" | \"bar\"", "b1", 1],
26
+ ["root ::= \"foo\" | \"bar\"", "fo1", 2],
27
+ ["root ::= \"foo\" | \"bar\"", "ba1", 2],
28
+ ["root ::= \"foo\" | \"bar\"", "fooo", 3],
29
+ ["root ::= \"foo\" | \"bar\"", "barrr", 3],
30
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "1", 0],
31
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "z", 0],
32
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "f1", 1],
33
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "b1", 1],
34
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "fo1", 2],
35
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "bal", 2],
36
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "fooo", 3],
37
+ ["root ::= \"foo\" | \"bar\" | \"baz\"", "bazrr", 3],
38
+ ["root ::= [^a]", "a", 0],
39
+ ["root ::= [^abc]", "b", 0],
40
+ ["root ::= [^a-z]", "z", 0],
41
+ ["root ::= [^a-zA-Z]", "X", 0],
42
+ ["root ::= [^a-zA-Z0-9]", "8", 0],
43
+ ["\n root ::= foo\n foo ::= \"foo\"", "1", 0],
44
+ ["\n root ::= foo\n foo ::= \"foo\"", "b", 0],
45
+ ["\n root ::= foo\n foo ::= \"foo\"", "f1", 1],
46
+ ["\n root ::= foo\n foo ::= \"foo\"", "fo1", 2],
47
+ ["\n root ::= foo\n foo ::= \"foo\"", "fooo", 3],
48
+ ["\n root::=foo|\"bar\"\n foo::=\"foo\"", "1", 0],
49
+ ["\n root::=foo|\"bar\"\n foo::=\"foo\"", "z", 0],
50
+ ["\n root::=foo|\"bar\"\n foo::=\"foo\"", "f1", 1],
51
+ ["\n root::=foo|\"bar\"\n foo::=\"foo\"", "b1", 1],
52
+ ["\n root::=foo|\"bar\"\n foo::=\"foo\"", "fo1", 2],
53
+ ["\n root::=foo|\"bar\"\n foo::=\"foo\"", "fooo", 3],
54
+ ["\n root::=foo|\"bar\"\n foo::=\"foo\"", "barr", 3],
55
+ ["\n root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "1", 0],
56
+ ["\n root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "z", 0],
57
+ ["\n root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "f1", 1],
58
+ ["\n root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "b1", 1],
59
+ ["\n root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "fo1", 2],
60
+ ["\n root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "fooo", 3],
61
+ ["\n root::= foo | bar\n foo::=\"foo\"\n bar::=\"bar\"", "barr", 3],
62
+ ["\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 ", "1", 0],
63
+ ["\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\"", "z", 0],
64
+ ["\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\"", "f1", 1],
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\"", "b1", 1],
66
+ ["\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\"", "fo1", 2],
67
+ ["\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\"", "fooo", 3],
68
+ ["\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\"", "barr", 3],
69
+ ["\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\"", "bazr", 3],
70
+ ["root ::= [a-z]", "A", 0],
71
+ ["root ::= [a-z]", "0", 0],
72
+ ["root ::= [a-z]", "az", 1],
73
+ ["root ::= [a-z]?", "A", 0],
74
+ ["root ::= [a-z]?", "0", 0],
75
+ ["root ::= [a-z]?", "az", 1],
76
+ ["root ::= [a-z]+", "A", 0],
77
+ ["root ::= [a-z]+", "0", 0],
78
+ ["root ::= [a-z]+", "az0", 2],
79
+ ["root ::= [a-z]*", "A", 0],
80
+ ["root ::= [a-z]*", "0", 0],
81
+ ["root ::= [a-z]*", "az0", 2],
82
+ ["root ::= ( [^abcdefgh] | [b-z])*", "a", 0],
83
+ ])('it reports an error for an invalid input: grammar %s, input %s', (grammar, inputText, errorPos) => {
84
+ const graph = GBNF(grammar);
85
+ const expected = new InputParseError(inputText, errorPos);
86
+ let err: unknown;
87
+ try {
88
+ graph.add(inputText);
89
+ } catch (e) {
90
+ err = e;
91
+ }
92
+ expect(err).toBeInstanceOf(InputParseError);
93
+ expect(String(err)).toBe(String(expected));
94
+ expect((err as InputParseError).pos).toBe(errorPos);
95
+ });
96
+ });
v2-models-effort/runs/20261026-020726-plain-darkness/ported_implementation/tsconfig.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "lib": ["ES2022"],
7
+ "strict": true,
8
+ "noImplicitOverride": true,
9
+ "noUncheckedIndexedAccess": false,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "noEmit": true,
13
+ "allowImportingTsExtensions": true,
14
+ "types": ["vitest/globals"]
15
+ },
16
+ "include": ["src", "tests"]
17
+ }