thekevinscott commited on
Commit
ff97c0e
·
verified ·
1 Parent(s): 870ccb6

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

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-191627-snowy-star/transcript/.claude/projects/-target/0fa09b3c-7f30-4b4e-ad57-8d8f9aab695a.jsonl +0 -0
  2. v2-models-effort/runs/20261026-191627-tight-wave/manifest.json +98 -0
  3. v2-models-effort/runs/20261026-191627-tight-wave/memory.jsonl +231 -0
  4. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/.gitignore +3 -0
  5. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/README.md +88 -0
  6. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/node_modules/.vite/vitest/results.json +1 -0
  7. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/package.json +39 -0
  8. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/GBNF.test.ts +55 -0
  9. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/GBNF.ts +35 -0
  10. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/colorize.test.ts +16 -0
  11. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/colorize.ts +13 -0
  12. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-input-as-code-points.test.ts +38 -0
  13. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-input-as-code-points.ts +33 -0
  14. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-parent-stack-id.test.ts +46 -0
  15. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-parent-stack-id.ts +14 -0
  16. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-serialized-rule-key.integration.test.ts +13 -0
  17. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-serialized-rule-key.test.ts +46 -0
  18. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-serialized-rule-key.ts +29 -0
  19. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/grammar-graph-types.test.ts +27 -0
  20. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/grammar-graph-types.ts +60 -0
  21. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-node.test.ts +45 -0
  22. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-node.ts +41 -0
  23. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-pointer.integration.test.ts +59 -0
  24. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-pointer.test.ts +129 -0
  25. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-pointer.ts +103 -0
  26. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph.test.ts +167 -0
  27. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph.ts +249 -0
  28. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/index.ts +20 -0
  29. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/parse-state.test.ts +80 -0
  30. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/parse-state.ts +51 -0
  31. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/pointers.test.ts +31 -0
  32. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/pointers.ts +30 -0
  33. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/print.test.ts +107 -0
  34. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/print.ts +69 -0
  35. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/rule-ref.test.ts +29 -0
  36. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/rule-ref.ts +27 -0
  37. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/type-guards.test.ts +131 -0
  38. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/type-guards.ts +31 -0
  39. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-parser/build-rule-stack.test.ts +212 -0
  40. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-parser/build-rule-stack.ts +100 -0
  41. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-parser/index.ts +1 -0
  42. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/index.test.ts +25 -0
  43. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/index.ts +6 -0
  44. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/index.ts +4 -0
  45. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/is-word-char.test.ts +27 -0
  46. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/is-word-char.ts +3 -0
  47. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/parse-char.test.ts +52 -0
  48. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/parse-char.ts +50 -0
  49. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/parse-name.test.ts +25 -0
  50. v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/parse-name.ts +18 -0
v2-models-effort/runs/20261026-191627-snowy-star/transcript/.claude/projects/-target/0fa09b3c-7f30-4b4e-ad57-8d8f9aab695a.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
v2-models-effort/runs/20261026-191627-tight-wave/manifest.json ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2026-10-26T21:00:08Z",
3
+ "completed_at": "2026-10-26T21:19:21Z",
4
+ "exit_code": 0,
5
+ "condition": {
6
+ "name": "source-python_unit-tests_source-integration-tests_effort-high_model-claude-fable-5-1",
7
+ "source_language": "python",
8
+ "target_language": "javascript",
9
+ "include_unit_tests": true,
10
+ "include_source_integration_tests": true,
11
+ "include_target_integration_tests": false,
12
+ "effort": "high",
13
+ "model": "claude-fable-5-1"
14
+ },
15
+ "derivation": {
16
+ "gbnf_commit": "13f1aca495d11e160fffd68c4ba299a2415909d8"
17
+ },
18
+ "reference_implementation": {
19
+ "included": [
20
+ "python/.gitignore",
21
+ "python/MANIFEST.in",
22
+ "python/Makefile",
23
+ "python/README.md",
24
+ "python/gbnf/GBNF.py",
25
+ "python/gbnf/__init__.py",
26
+ "python/gbnf/grammar_graph/__init__.py",
27
+ "python/gbnf/grammar_graph/colorize.py",
28
+ "python/gbnf/grammar_graph/colorize_test.py",
29
+ "python/gbnf/grammar_graph/get_input_as_code_points.py",
30
+ "python/gbnf/grammar_graph/get_input_as_code_points_test.py",
31
+ "python/gbnf/grammar_graph/get_parent_stack_id.py",
32
+ "python/gbnf/grammar_graph/get_parent_stack_id_test.py",
33
+ "python/gbnf/grammar_graph/get_serialized_rule_key.py",
34
+ "python/gbnf/grammar_graph/get_serialized_rule_key_test.py",
35
+ "python/gbnf/grammar_graph/grammar_graph_types.py",
36
+ "python/gbnf/grammar_graph/graph.py",
37
+ "python/gbnf/grammar_graph/graph_node.py",
38
+ "python/gbnf/grammar_graph/graph_node_test.py",
39
+ "python/gbnf/grammar_graph/graph_pointer.py",
40
+ "python/gbnf/grammar_graph/graph_pointer_test.py",
41
+ "python/gbnf/grammar_graph/graph_test.py",
42
+ "python/gbnf/grammar_graph/parse_state.py",
43
+ "python/gbnf/grammar_graph/parse_state_test.py",
44
+ "python/gbnf/grammar_graph/pointers.py",
45
+ "python/gbnf/grammar_graph/print.py",
46
+ "python/gbnf/grammar_graph/print_test.py",
47
+ "python/gbnf/grammar_graph/rule_ref.py",
48
+ "python/gbnf/grammar_graph/rule_ref_test.py",
49
+ "python/gbnf/grammar_graph/type_guards.py",
50
+ "python/gbnf/grammar_graph/type_guards_test.py",
51
+ "python/gbnf/grammar_parser/__init__.py",
52
+ "python/gbnf/grammar_parser/build_rule_stack.py",
53
+ "python/gbnf/grammar_parser/build_rule_stack_test.py",
54
+ "python/gbnf/rules_builder/__init__.py",
55
+ "python/gbnf/rules_builder/is_word_char.py",
56
+ "python/gbnf/rules_builder/is_word_char_test.py",
57
+ "python/gbnf/rules_builder/parse_char.py",
58
+ "python/gbnf/rules_builder/parse_char_test.py",
59
+ "python/gbnf/rules_builder/parse_name.py",
60
+ "python/gbnf/rules_builder/parse_name_test.py",
61
+ "python/gbnf/rules_builder/parse_space.py",
62
+ "python/gbnf/rules_builder/parse_space_test.py",
63
+ "python/gbnf/rules_builder/rules_builder.py",
64
+ "python/gbnf/rules_builder/rules_builder_test.py",
65
+ "python/gbnf/rules_builder/rules_builder_types.py",
66
+ "python/gbnf/rules_builder/symbol_ids.py",
67
+ "python/gbnf/utils/__init__.py",
68
+ "python/gbnf/utils/errors/__init__.py",
69
+ "python/gbnf/utils/errors/build_error_position.py",
70
+ "python/gbnf/utils/errors/build_error_position_test.py",
71
+ "python/gbnf/utils/errors/errors_types.py",
72
+ "python/gbnf/utils/errors/get_input_as_string.py",
73
+ "python/gbnf/utils/errors/get_input_as_string_test.py",
74
+ "python/gbnf/utils/errors/grammar_parse_error.py",
75
+ "python/gbnf/utils/errors/grammar_parse_error_test.py",
76
+ "python/gbnf/utils/errors/input_parse_error.py",
77
+ "python/gbnf/utils/errors/input_parse_error_test.py",
78
+ "python/gbnf/utils/is_point_in_range.py",
79
+ "python/gbnf/utils/is_point_in_range_test.py",
80
+ "python/gbnf/utils/validate_non_empty.py",
81
+ "python/pyproject.toml",
82
+ "python/requirements.txt",
83
+ "python/tests/generated/iteration/iteration_test.py",
84
+ "python/tests/generated/iteration/iteration_with_additional_strings_test.py",
85
+ "python/tests/generated/iteration/iteration_with_an_initial_string_test.py",
86
+ "python/tests/generated/validation/validate_grammar_test.py",
87
+ "python/tests/generated/validation/validate_input_test.py",
88
+ "python/uv.lock"
89
+ ]
90
+ },
91
+ "sandbox": {
92
+ "image_id": "sha256:6c1f598082037bfda8094b50764d66c1d0c3edd448363d9def05880e5665e0d1"
93
+ },
94
+ "harness": {
95
+ "commit": "6ca596d4f8cf34dc7f032a665f085d47d223d21a",
96
+ "dirty": true
97
+ }
98
+ }
v2-models-effort/runs/20261026-191627-tight-wave/memory.jsonl ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"time": 1793048408.059076, "rss": 24956928, "processes": 2}
2
+ {"time": 1793048413.0691607, "rss": 130789376, "processes": 5}
3
+ {"time": 1793048418.0792909, "rss": 130924544, "processes": 5}
4
+ {"time": 1793048423.0892534, "rss": 116436992, "processes": 5}
5
+ {"time": 1793048428.101071, "rss": 116436992, "processes": 5}
6
+ {"time": 1793048433.112091, "rss": 116436992, "processes": 5}
7
+ {"time": 1793048438.1225812, "rss": 116436992, "processes": 5}
8
+ {"time": 1793048443.133617, "rss": 116436992, "processes": 5}
9
+ {"time": 1793048448.1444159, "rss": 116436992, "processes": 5}
10
+ {"time": 1793048453.155387, "rss": 116473856, "processes": 5}
11
+ {"time": 1793048458.1658165, "rss": 116473856, "processes": 5}
12
+ {"time": 1793048463.1768079, "rss": 116473856, "processes": 5}
13
+ {"time": 1793048468.1888592, "rss": 116473856, "processes": 5}
14
+ {"time": 1793048473.2, "rss": 116473856, "processes": 5}
15
+ {"time": 1793048478.2105603, "rss": 116473856, "processes": 5}
16
+ {"time": 1793048483.2206416, "rss": 116473856, "processes": 5}
17
+ {"time": 1793048488.2330544, "rss": 116473856, "processes": 5}
18
+ {"time": 1793048493.2449527, "rss": 116473856, "processes": 5}
19
+ {"time": 1793048498.2559705, "rss": 116473856, "processes": 5}
20
+ {"time": 1793048503.2667403, "rss": 116473856, "processes": 5}
21
+ {"time": 1793048508.2771523, "rss": 116473856, "processes": 5}
22
+ {"time": 1793048513.287724, "rss": 116473856, "processes": 5}
23
+ {"time": 1793048518.2994423, "rss": 116473856, "processes": 5}
24
+ {"time": 1793048523.3111315, "rss": 116473856, "processes": 5}
25
+ {"time": 1793048528.3219504, "rss": 116473856, "processes": 5}
26
+ {"time": 1793048533.332522, "rss": 116473856, "processes": 5}
27
+ {"time": 1793048538.3428118, "rss": 116473856, "processes": 5}
28
+ {"time": 1793048543.3535304, "rss": 116473856, "processes": 5}
29
+ {"time": 1793048548.3646958, "rss": 116473856, "processes": 5}
30
+ {"time": 1793048553.3758013, "rss": 116473856, "processes": 5}
31
+ {"time": 1793048558.3877885, "rss": 116473856, "processes": 5}
32
+ {"time": 1793048563.4001772, "rss": 116473856, "processes": 5}
33
+ {"time": 1793048568.41063, "rss": 116473856, "processes": 5}
34
+ {"time": 1793048573.4210057, "rss": 116977664, "processes": 5}
35
+ {"time": 1793048578.4322157, "rss": 116977664, "processes": 5}
36
+ {"time": 1793048583.4439437, "rss": 116977664, "processes": 5}
37
+ {"time": 1793048588.4538465, "rss": 116977664, "processes": 5}
38
+ {"time": 1793048593.462926, "rss": 116977664, "processes": 5}
39
+ {"time": 1793048598.4703298, "rss": 116977664, "processes": 5}
40
+ {"time": 1793048603.477878, "rss": 116977664, "processes": 5}
41
+ {"time": 1793048608.4865327, "rss": 116977664, "processes": 5}
42
+ {"time": 1793048613.4973197, "rss": 116977664, "processes": 5}
43
+ {"time": 1793048618.5080287, "rss": 116977664, "processes": 5}
44
+ {"time": 1793048623.5190153, "rss": 116977664, "processes": 5}
45
+ {"time": 1793048628.5293458, "rss": 116977664, "processes": 5}
46
+ {"time": 1793048633.5408154, "rss": 116977664, "processes": 5}
47
+ {"time": 1793048638.551375, "rss": 116977664, "processes": 5}
48
+ {"time": 1793048643.5618904, "rss": 116977664, "processes": 5}
49
+ {"time": 1793048648.573564, "rss": 116977664, "processes": 5}
50
+ {"time": 1793048653.5840378, "rss": 116977664, "processes": 5}
51
+ {"time": 1793048658.5960598, "rss": 116977664, "processes": 5}
52
+ {"time": 1793048663.6061125, "rss": 116977664, "processes": 5}
53
+ {"time": 1793048668.6179066, "rss": 116977664, "processes": 5}
54
+ {"time": 1793048673.6285233, "rss": 116977664, "processes": 5}
55
+ {"time": 1793048678.6398542, "rss": 116977664, "processes": 5}
56
+ {"time": 1793048683.650702, "rss": 116977664, "processes": 5}
57
+ {"time": 1793048688.6611447, "rss": 116977664, "processes": 5}
58
+ {"time": 1793048693.6720998, "rss": 117239808, "processes": 5}
59
+ {"time": 1793048698.6824474, "rss": 117239808, "processes": 5}
60
+ {"time": 1793048703.6931958, "rss": 117239808, "processes": 5}
61
+ {"time": 1793048708.7036493, "rss": 117239808, "processes": 5}
62
+ {"time": 1793048713.714633, "rss": 117239808, "processes": 5}
63
+ {"time": 1793048718.725439, "rss": 117239808, "processes": 5}
64
+ {"time": 1793048723.7363346, "rss": 117239808, "processes": 5}
65
+ {"time": 1793048728.7466927, "rss": 117239808, "processes": 5}
66
+ {"time": 1793048733.7571683, "rss": 117239808, "processes": 5}
67
+ {"time": 1793048738.7675297, "rss": 117239808, "processes": 5}
68
+ {"time": 1793048743.7787976, "rss": 117239808, "processes": 5}
69
+ {"time": 1793048748.7895088, "rss": 117239808, "processes": 5}
70
+ {"time": 1793048753.8002844, "rss": 116109312, "processes": 5}
71
+ {"time": 1793048758.8113387, "rss": 116109312, "processes": 5}
72
+ {"time": 1793048763.822201, "rss": 116109312, "processes": 5}
73
+ {"time": 1793048768.832426, "rss": 116109312, "processes": 5}
74
+ {"time": 1793048773.843335, "rss": 116109312, "processes": 5}
75
+ {"time": 1793048778.8542917, "rss": 116109312, "processes": 5}
76
+ {"time": 1793048783.865416, "rss": 116109312, "processes": 5}
77
+ {"time": 1793048788.8759491, "rss": 116109312, "processes": 5}
78
+ {"time": 1793048793.886179, "rss": 116109312, "processes": 5}
79
+ {"time": 1793048798.8963695, "rss": 116109312, "processes": 5}
80
+ {"time": 1793048803.9068677, "rss": 116109312, "processes": 5}
81
+ {"time": 1793048808.918087, "rss": 116109312, "processes": 5}
82
+ {"time": 1793048813.9288712, "rss": 116326400, "processes": 5}
83
+ {"time": 1793048818.9400334, "rss": 116326400, "processes": 5}
84
+ {"time": 1793048823.950826, "rss": 116326400, "processes": 5}
85
+ {"time": 1793048828.9622066, "rss": 116326400, "processes": 5}
86
+ {"time": 1793048833.9713933, "rss": 116326400, "processes": 5}
87
+ {"time": 1793048838.9821556, "rss": 116326400, "processes": 5}
88
+ {"time": 1793048843.9926438, "rss": 116326400, "processes": 5}
89
+ {"time": 1793048849.0025027, "rss": 116326400, "processes": 5}
90
+ {"time": 1793048854.0120983, "rss": 116326400, "processes": 5}
91
+ {"time": 1793048859.0228643, "rss": 116326400, "processes": 5}
92
+ {"time": 1793048864.033431, "rss": 116326400, "processes": 5}
93
+ {"time": 1793048869.0443506, "rss": 116326400, "processes": 5}
94
+ {"time": 1793048874.0538871, "rss": 116031488, "processes": 5}
95
+ {"time": 1793048879.06415, "rss": 116031488, "processes": 5}
96
+ {"time": 1793048884.0751615, "rss": 116031488, "processes": 5}
97
+ {"time": 1793048889.087186, "rss": 116031488, "processes": 5}
98
+ {"time": 1793048894.0980356, "rss": 116031488, "processes": 5}
99
+ {"time": 1793048899.108427, "rss": 116031488, "processes": 5}
100
+ {"time": 1793048904.1185238, "rss": 116031488, "processes": 5}
101
+ {"time": 1793048909.1274192, "rss": 116031488, "processes": 5}
102
+ {"time": 1793048914.138369, "rss": 116031488, "processes": 5}
103
+ {"time": 1793048919.1488707, "rss": 116031488, "processes": 5}
104
+ {"time": 1793048924.1594634, "rss": 116031488, "processes": 5}
105
+ {"time": 1793048929.1723113, "rss": 116031488, "processes": 5}
106
+ {"time": 1793048934.1817925, "rss": 116068352, "processes": 5}
107
+ {"time": 1793048939.1939507, "rss": 116068352, "processes": 5}
108
+ {"time": 1793048944.2036905, "rss": 116068352, "processes": 5}
109
+ {"time": 1793048949.21466, "rss": 116068352, "processes": 5}
110
+ {"time": 1793048954.2240856, "rss": 116068352, "processes": 5}
111
+ {"time": 1793048959.2373068, "rss": 116068352, "processes": 5}
112
+ {"time": 1793048964.2473664, "rss": 116068352, "processes": 5}
113
+ {"time": 1793048969.258211, "rss": 116068352, "processes": 5}
114
+ {"time": 1793048974.2675784, "rss": 116068352, "processes": 5}
115
+ {"time": 1793048979.278141, "rss": 116068352, "processes": 5}
116
+ {"time": 1793048984.2893682, "rss": 116068352, "processes": 5}
117
+ {"time": 1793048989.3011024, "rss": 116068352, "processes": 5}
118
+ {"time": 1793048994.3122458, "rss": 116068352, "processes": 5}
119
+ {"time": 1793048999.3225937, "rss": 116068352, "processes": 5}
120
+ {"time": 1793049004.3346112, "rss": 116068352, "processes": 5}
121
+ {"time": 1793049009.34524, "rss": 116068352, "processes": 5}
122
+ {"time": 1793049014.3571746, "rss": 116068352, "processes": 5}
123
+ {"time": 1793049019.3674881, "rss": 116068352, "processes": 5}
124
+ {"time": 1793049024.3783545, "rss": 116068352, "processes": 5}
125
+ {"time": 1793049029.389256, "rss": 116068352, "processes": 5}
126
+ {"time": 1793049034.4004931, "rss": 116068352, "processes": 5}
127
+ {"time": 1793049039.410925, "rss": 116068352, "processes": 5}
128
+ {"time": 1793049044.4218624, "rss": 116068352, "processes": 5}
129
+ {"time": 1793049049.4323673, "rss": 116068352, "processes": 5}
130
+ {"time": 1793049054.4430485, "rss": 116195328, "processes": 5}
131
+ {"time": 1793049059.451735, "rss": 116195328, "processes": 5}
132
+ {"time": 1793049064.459198, "rss": 116195328, "processes": 5}
133
+ {"time": 1793049069.466495, "rss": 116195328, "processes": 5}
134
+ {"time": 1793049074.4740496, "rss": 116195328, "processes": 5}
135
+ {"time": 1793049079.481698, "rss": 116195328, "processes": 5}
136
+ {"time": 1793049084.490045, "rss": 116195328, "processes": 5}
137
+ {"time": 1793049089.5006506, "rss": 116195328, "processes": 5}
138
+ {"time": 1793049094.510736, "rss": 116195328, "processes": 5}
139
+ {"time": 1793049099.5204508, "rss": 116195328, "processes": 5}
140
+ {"time": 1793049104.5314648, "rss": 116195328, "processes": 5}
141
+ {"time": 1793049109.5426676, "rss": 116195328, "processes": 5}
142
+ {"time": 1793049114.554424, "rss": 116195328, "processes": 5}
143
+ {"time": 1793049119.564603, "rss": 116195328, "processes": 5}
144
+ {"time": 1793049124.575805, "rss": 116195328, "processes": 5}
145
+ {"time": 1793049129.5866435, "rss": 116195328, "processes": 5}
146
+ {"time": 1793049134.5976946, "rss": 116195328, "processes": 5}
147
+ {"time": 1793049139.6089714, "rss": 116195328, "processes": 5}
148
+ {"time": 1793049144.619358, "rss": 116195328, "processes": 5}
149
+ {"time": 1793049149.630177, "rss": 116195328, "processes": 5}
150
+ {"time": 1793049154.6408288, "rss": 116195328, "processes": 5}
151
+ {"time": 1793049159.6515353, "rss": 116195328, "processes": 5}
152
+ {"time": 1793049164.6623075, "rss": 116195328, "processes": 5}
153
+ {"time": 1793049169.6730516, "rss": 116195328, "processes": 5}
154
+ {"time": 1793049174.6842093, "rss": 116203520, "processes": 5}
155
+ {"time": 1793049179.699516, "rss": 116203520, "processes": 5}
156
+ {"time": 1793049184.7106853, "rss": 116203520, "processes": 5}
157
+ {"time": 1793049189.7233112, "rss": 116203520, "processes": 5}
158
+ {"time": 1793049194.7347777, "rss": 116203520, "processes": 5}
159
+ {"time": 1793049199.7466245, "rss": 116203520, "processes": 5}
160
+ {"time": 1793049204.7583697, "rss": 116203520, "processes": 5}
161
+ {"time": 1793049209.7706695, "rss": 116203520, "processes": 5}
162
+ {"time": 1793049214.7818387, "rss": 116203520, "processes": 5}
163
+ {"time": 1793049219.7931528, "rss": 116203520, "processes": 5}
164
+ {"time": 1793049224.8051188, "rss": 116203520, "processes": 5}
165
+ {"time": 1793049229.8156624, "rss": 116203520, "processes": 5}
166
+ {"time": 1793049234.8269036, "rss": 116072448, "processes": 5}
167
+ {"time": 1793049239.838031, "rss": 116072448, "processes": 5}
168
+ {"time": 1793049244.8489954, "rss": 116072448, "processes": 5}
169
+ {"time": 1793049249.8597288, "rss": 116072448, "processes": 5}
170
+ {"time": 1793049254.8704672, "rss": 116072448, "processes": 5}
171
+ {"time": 1793049259.8817577, "rss": 116072448, "processes": 5}
172
+ {"time": 1793049264.8938255, "rss": 116072448, "processes": 5}
173
+ {"time": 1793049269.9051247, "rss": 116072448, "processes": 5}
174
+ {"time": 1793049274.9155142, "rss": 116072448, "processes": 5}
175
+ {"time": 1793049279.9270847, "rss": 116072448, "processes": 5}
176
+ {"time": 1793049284.9376733, "rss": 116072448, "processes": 5}
177
+ {"time": 1793049289.949566, "rss": 116072448, "processes": 5}
178
+ {"time": 1793049294.9602668, "rss": 116170752, "processes": 5}
179
+ {"time": 1793049299.9709122, "rss": 116170752, "processes": 5}
180
+ {"time": 1793049304.9830484, "rss": 116170752, "processes": 5}
181
+ {"time": 1793049309.994251, "rss": 116170752, "processes": 5}
182
+ {"time": 1793049315.005183, "rss": 116170752, "processes": 5}
183
+ {"time": 1793049320.0168498, "rss": 116170752, "processes": 5}
184
+ {"time": 1793049325.0291295, "rss": 116170752, "processes": 5}
185
+ {"time": 1793049330.0415118, "rss": 116170752, "processes": 5}
186
+ {"time": 1793049335.051768, "rss": 116170752, "processes": 5}
187
+ {"time": 1793049340.061417, "rss": 116170752, "processes": 5}
188
+ {"time": 1793049345.0722108, "rss": 116170752, "processes": 5}
189
+ {"time": 1793049350.0829833, "rss": 116170752, "processes": 5}
190
+ {"time": 1793049355.0936189, "rss": 116170752, "processes": 5}
191
+ {"time": 1793049360.1043768, "rss": 116170752, "processes": 5}
192
+ {"time": 1793049365.1153493, "rss": 116170752, "processes": 5}
193
+ {"time": 1793049370.12529, "rss": 116170752, "processes": 5}
194
+ {"time": 1793049375.1364083, "rss": 116170752, "processes": 5}
195
+ {"time": 1793049380.147232, "rss": 116170752, "processes": 5}
196
+ {"time": 1793049385.1583204, "rss": 116170752, "processes": 5}
197
+ {"time": 1793049390.1694796, "rss": 116170752, "processes": 5}
198
+ {"time": 1793049395.1832898, "rss": 116170752, "processes": 5}
199
+ {"time": 1793049400.194548, "rss": 116170752, "processes": 5}
200
+ {"time": 1793049405.2055051, "rss": 116170752, "processes": 5}
201
+ {"time": 1793049410.2168307, "rss": 116170752, "processes": 5}
202
+ {"time": 1793049415.227459, "rss": 116178944, "processes": 5}
203
+ {"time": 1793049420.238158, "rss": 116178944, "processes": 5}
204
+ {"time": 1793049425.2490208, "rss": 116178944, "processes": 5}
205
+ {"time": 1793049430.2603068, "rss": 116178944, "processes": 5}
206
+ {"time": 1793049435.2725856, "rss": 116178944, "processes": 5}
207
+ {"time": 1793049440.2851107, "rss": 116178944, "processes": 5}
208
+ {"time": 1793049445.295773, "rss": 116178944, "processes": 5}
209
+ {"time": 1793049450.306596, "rss": 116178944, "processes": 5}
210
+ {"time": 1793049455.317608, "rss": 116178944, "processes": 5}
211
+ {"time": 1793049460.3300972, "rss": 116178944, "processes": 5}
212
+ {"time": 1793049465.341751, "rss": 116178944, "processes": 5}
213
+ {"time": 1793049470.3526847, "rss": 116178944, "processes": 5}
214
+ {"time": 1793049475.3640845, "rss": 116178944, "processes": 5}
215
+ {"time": 1793049480.3752599, "rss": 116178944, "processes": 5}
216
+ {"time": 1793049485.3860307, "rss": 116178944, "processes": 5}
217
+ {"time": 1793049490.3968875, "rss": 116178944, "processes": 5}
218
+ {"time": 1793049495.4076867, "rss": 116178944, "processes": 5}
219
+ {"time": 1793049500.4197857, "rss": 116178944, "processes": 5}
220
+ {"time": 1793049505.4304304, "rss": 116178944, "processes": 5}
221
+ {"time": 1793049510.4418185, "rss": 116178944, "processes": 5}
222
+ {"time": 1793049515.4518173, "rss": 116178944, "processes": 5}
223
+ {"time": 1793049520.462055, "rss": 116178944, "processes": 5}
224
+ {"time": 1793049525.4713857, "rss": 116178944, "processes": 5}
225
+ {"time": 1793049530.4808831, "rss": 116178944, "processes": 5}
226
+ {"time": 1793049535.490585, "rss": 116211712, "processes": 5}
227
+ {"time": 1793049540.499341, "rss": 116211712, "processes": 5}
228
+ {"time": 1793049545.5082343, "rss": 116211712, "processes": 5}
229
+ {"time": 1793049550.5182788, "rss": 116211712, "processes": 5}
230
+ {"time": 1793049555.528551, "rss": 116211712, "processes": 5}
231
+ {"time": 1793049560.5387843, "rss": 116211712, "processes": 5}
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ node_modules
2
+ dist
3
+ coverage
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/README.md ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GBNF
2
+
3
+ A library for parsing `.gbnf` grammar files in TypeScript.
4
+
5
+ This is a TypeScript port of the `gbnf` Python package. It parses a GBNF grammar (the grammar
6
+ format used by llama.cpp) into a graph, and lets you walk that graph character by character to
7
+ find out which characters may legally come next, or whether a given string is accepted.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install gbnf
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { GBNF, InputParseError, RuleType } from 'gbnf';
19
+
20
+ const state = GBNF(`
21
+ root ::= "foo" | "bar"
22
+ `);
23
+
24
+ // Each parse state is iterable: it yields the unique rules that may come next.
25
+ for (const rule of state) {
26
+ console.log(rule); // RuleChar { type: 'char', value: [102] }, RuleChar { type: 'char', value: [98] }
27
+ }
28
+
29
+ // Adding input returns a new parse state; the original is untouched.
30
+ const next = state.add('fo');
31
+ console.log([...next]); // [ RuleChar { type: 'char', value: [111] } ]
32
+
33
+ // A RuleEnd indicates the grammar may terminate here.
34
+ console.log([...next.add('o')]); // [ RuleEnd { type: 'end' } ]
35
+
36
+ // Invalid input throws an InputParseError that points at the offending character.
37
+ try {
38
+ next.add('x');
39
+ } catch (err) {
40
+ if (err instanceof InputParseError) {
41
+ console.log(err.message);
42
+ // Failed to parse input string:
43
+ //
44
+ // fox
45
+ // ^
46
+ }
47
+ }
48
+
49
+ // An initial string can also be passed directly.
50
+ const parsed = GBNF('root ::= [a-z]+', 'abc');
51
+ ```
52
+
53
+ ### Rules
54
+
55
+ A parse state yields three kinds of rules:
56
+
57
+ | Rule | `type` | Meaning |
58
+ | ----------------- | ---------------- | ----------------------------------------------------------------------- |
59
+ | `RuleChar` | `'char'` | The next character must be one of `value` (code points or `[lo, hi]` ranges). |
60
+ | `RuleCharExclude` | `'char_exclude'` | The next character must *not* be one of `value`. |
61
+ | `RuleEnd` | `'end'` | The input may end here. |
62
+
63
+ `value` entries are Unicode code points (as produced by `String.prototype.codePointAt`), and
64
+ ranges are inclusive `[lower, upper]` pairs.
65
+
66
+ ### Errors
67
+
68
+ - `GrammarParseError` is thrown by `GBNF()` when the grammar itself is invalid. It exposes
69
+ `grammar`, `pos` (the index into the grammar string), and `reason`.
70
+ - `InputParseError` is thrown when input is not accepted by the grammar. It exposes
71
+ `mostRecentInput`, `pos` (the code point index into the most recent input), `previousInput`,
72
+ `src`, and `errorForMostRecentInput`.
73
+
74
+ Both errors render a message that shows the surrounding source and a caret under the failing
75
+ position.
76
+
77
+ ## Development
78
+
79
+ ```bash
80
+ npm test # unit + integration tests (vitest)
81
+ npm run test:unit # colocated unit tests under src/
82
+ npm run test:integration # generated integration tests under tests/generated/
83
+ npm run typecheck # tsc --noEmit
84
+ npm run build # emit dist/
85
+ ```
86
+
87
+ The tests under `tests/generated/` mirror the shared cross-language integration suite used by
88
+ the Python package.
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/node_modules/.vite/vitest/results.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":"2.1.3","results":[[":src/rules-builder/rules-builder.test.ts",{"duration":11.697068000000002,"failed":false}],[":tests/generated/iteration/iteration-with-an-initial-string.test.ts",{"duration":34.70383199999998,"failed":false}],[":tests/generated/iteration/iteration-with-additional-strings.test.ts",{"duration":21.83576000000005,"failed":false}],[":src/grammar-parser/build-rule-stack.test.ts",{"duration":6.236175000000003,"failed":false}],[":src/grammar-graph/graph.test.ts",{"duration":7.8819030000000225,"failed":false}],[":src/grammar-graph/graph-pointer.test.ts",{"duration":4.262887000000035,"failed":false}],[":tests/generated/validation/validate-input.test.ts",{"duration":17.049589999999966,"failed":false}],[":src/grammar-graph/print.test.ts",{"duration":3.214443000000017,"failed":false}],[":src/grammar-graph/type-guards.test.ts",{"duration":4.790779000000043,"failed":false}],[":src/grammar-graph/parse-state.test.ts",{"duration":5.545322999999996,"failed":false}],[":tests/generated/iteration/iteration.test.ts",{"duration":7.829792999999995,"failed":false}],[":src/grammar-graph/graph-pointer.integration.test.ts",{"duration":4.456388000000004,"failed":false}],[":src/utils/errors/input-parse-error.test.ts",{"duration":2.3529589999999985,"failed":false}],[":src/GBNF.test.ts",{"duration":6.9079380000000015,"failed":false}],[":src/rules-builder/parse-space.test.ts",{"duration":1.8215869999999938,"failed":false}],[":tests/generated/validation/validate-grammar.test.ts",{"duration":10.649862999999982,"failed":false}],[":src/grammar-graph/get-parent-stack-id.test.ts",{"duration":2.129339000000016,"failed":false}],[":src/rules-builder/rules-builder-types.test.ts",{"duration":2.038027999999997,"failed":false}],[":src/rules-builder/parse-char.test.ts",{"duration":3.6970359999999687,"failed":false}],[":src/grammar-graph/get-serialized-rule-key.test.ts",{"duration":1.8965479999999957,"failed":false}],[":src/utils/errors/build-error-position.test.ts",{"duration":1.9176980000000015,"failed":false}],[":src/grammar-graph/graph-node.test.ts",{"duration":3.1590030000000127,"failed":false}],[":src/utils/errors/grammar-parse-error.test.ts",{"duration":1.7887669999999787,"failed":false}],[":src/grammar-graph/get-input-as-code-points.test.ts",{"duration":2.237679000000014,"failed":false}],[":src/grammar-graph/grammar-graph-types.test.ts",{"duration":1.6031169999999975,"failed":false}],[":src/grammar-graph/pointers.test.ts",{"duration":2.2488199999999665,"failed":false}],[":src/rules-builder/symbol-ids.test.ts",{"duration":1.7950069999999982,"failed":false}],[":src/grammar-graph/rule-ref.test.ts",{"duration":2.0291179999999827,"failed":false}],[":src/rules-builder/parse-name.test.ts",{"duration":2.38677899999999,"failed":false}],[":src/rules-builder/is-word-char.test.ts",{"duration":1.4332160000000158,"failed":false}],[":src/utils/is-point-in-range.test.ts",{"duration":2.103098999999986,"failed":false}],[":src/grammar-graph/get-serialized-rule-key.integration.test.ts",{"duration":1.276724999999999,"failed":false}],[":src/index.test.ts",{"duration":1.3877259999999865,"failed":false}],[":src/grammar-graph/colorize.test.ts",{"duration":2.0045789999999926,"failed":false}],[":src/utils/errors/get-input-as-string.test.ts",{"duration":1.8483579999999904,"failed":false}]]}
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/package.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gbnf",
3
+ "version": "0.0.30",
4
+ "description": "A library for parsing GBNF grammars",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.build.json",
21
+ "test": "vitest run",
22
+ "test:unit": "vitest run src",
23
+ "test:integration": "vitest run tests/generated",
24
+ "test:watch": "vitest",
25
+ "typecheck": "tsc -p tsconfig.json"
26
+ },
27
+ "author": {
28
+ "name": "Ambient Labs",
29
+ "email": "maintainers@gbnf.dev"
30
+ },
31
+ "homepage": "https://github.com/ambient-labs/GBNF/packages/gbnf",
32
+ "bugs": {
33
+ "url": "https://github.com/ambient-labs/GBNF/packages/gbnf/issues"
34
+ },
35
+ "devDependencies": {
36
+ "typescript": "^5.6.0",
37
+ "vitest": "^2.1.3"
38
+ }
39
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/GBNF.test.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { GBNF } from './GBNF.js';
3
+ import { ParseState } from './grammar-graph/parse-state.js';
4
+ import { GrammarParseError, InputParseError } from './utils/errors/index.js';
5
+ import { RuleChar, RuleEnd } from './grammar-graph/grammar-graph-types.js';
6
+
7
+ describe('GBNF', () => {
8
+ it('returns a ParseState', () => {
9
+ const state = GBNF('root ::= "foo"');
10
+ expect(state).toBeInstanceOf(ParseState);
11
+ expect(state.grammar).toBe('root ::= "foo"');
12
+ expect([...state]).toEqual([new RuleChar([102])]);
13
+ });
14
+
15
+ it('consumes an initial string', () => {
16
+ const state = GBNF('root ::= "foo"', 'foo');
17
+ expect([...state]).toEqual([new RuleEnd()]);
18
+ });
19
+
20
+ it('throws an InputParseError for an invalid initial string', () => {
21
+ expect(() => GBNF('root ::= "foo"', 'fox')).toThrow(InputParseError);
22
+ });
23
+
24
+ it('throws if the grammar is not a string', () => {
25
+ expect(() => GBNF(42 as unknown as string)).toThrow('grammar must be a string');
26
+ });
27
+
28
+ it('throws if the initial string is not a string', () => {
29
+ expect(() => GBNF('root ::= "foo"', 42 as unknown as string)).toThrow('input must be a string');
30
+ });
31
+
32
+ it('throws if no rules were found', () => {
33
+ expect(() => GBNF('')).toThrow(new GrammarParseError('', 0, 'No rules were found').message);
34
+ expect(() => GBNF('# just a comment\n')).toThrow('No rules were found');
35
+ });
36
+
37
+ it('throws if the grammar does not contain a root symbol', () => {
38
+ expect(() => GBNF('foo ::= "foo"')).toThrow("Grammar does not contain a 'root' symbol");
39
+ expect(() => GBNF('foo ::= "foo"')).toThrow(GrammarParseError);
40
+ });
41
+
42
+ it('keeps parse states immutable', () => {
43
+ const state = GBNF('root ::= "ab"');
44
+ const next = state.add('a');
45
+ expect([...state]).toEqual([new RuleChar([97])]);
46
+ expect([...next]).toEqual([new RuleChar([98])]);
47
+ });
48
+
49
+ it('matches astral characters by code point', () => {
50
+ const state = GBNF('root ::= "💩" | [😀-😂]');
51
+ expect([...state]).toEqual([new RuleChar([128169]), new RuleChar([[128512, 128514]])]);
52
+ expect([...state.add('😁')]).toEqual([new RuleEnd()]);
53
+ expect(() => state.add('😃')).toThrow(InputParseError);
54
+ });
55
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/GBNF.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Graph } from './grammar-graph/graph.js';
2
+ import { ParseState } from './grammar-graph/parse-state.js';
3
+ import { buildRuleStack } from './grammar-parser/build-rule-stack.js';
4
+ import { GrammarParseError, RulesBuilder } from './rules-builder/index.js';
5
+
6
+ /**
7
+ * Parse a GBNF grammar, optionally consuming an initial input string, and return the
8
+ * resulting parse state.
9
+ *
10
+ * @throws GrammarParseError if the grammar is invalid.
11
+ * @throws InputParseError if the initial string is not accepted by the grammar.
12
+ */
13
+ export function GBNF(grammar: string, initialString = ''): ParseState {
14
+ if (typeof grammar !== 'string') {
15
+ throw new TypeError('grammar must be a string');
16
+ }
17
+
18
+ if (typeof initialString !== 'string') {
19
+ throw new TypeError('input must be a string');
20
+ }
21
+
22
+ const rulesBuilder = new RulesBuilder(grammar);
23
+ const { rules, symbolIds } = rulesBuilder;
24
+ if (rules.length === 0) {
25
+ throw new GrammarParseError(grammar, 0, 'No rules were found');
26
+ }
27
+ const rootId = symbolIds.get('root');
28
+ if (rootId === undefined) {
29
+ throw new GrammarParseError(grammar, 0, "Grammar does not contain a 'root' symbol");
30
+ }
31
+
32
+ const stackedRules = rules.map((rule) => buildRuleStack(rule));
33
+ const graph = new Graph(grammar, stackedRules, rootId);
34
+ return new ParseState(graph, graph.add(initialString));
35
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/colorize.test.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { Color, colorize } from './colorize.js';
3
+
4
+ describe('colorize', () => {
5
+ it('colorizes strings', () => {
6
+ expect(colorize('hello', Color.BLUE)).toBe('\x1b[34mhello');
7
+ expect(colorize('test', Color.CYAN)).toBe('\x1b[36mtest');
8
+ expect(colorize('example', Color.GREEN)).toBe('\x1b[32mexample');
9
+ });
10
+
11
+ it('colorizes numbers', () => {
12
+ expect(colorize(123, Color.RED)).toBe('\x1b[31m123');
13
+ expect(colorize(456, Color.GRAY)).toBe('\x1b[90m456');
14
+ expect(colorize(789, Color.YELLOW)).toBe('\x1b[33m789');
15
+ });
16
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/colorize.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const Color = {
2
+ BLUE: '\x1b[34m',
3
+ CYAN: '\x1b[36m',
4
+ GREEN: '\x1b[32m',
5
+ RED: '\x1b[31m',
6
+ GRAY: '\x1b[90m',
7
+ YELLOW: '\x1b[33m',
8
+ } as const;
9
+ export type Color = (typeof Color)[keyof typeof Color];
10
+
11
+ export function colorize(text: string | number, color: string): string {
12
+ return `${color}${text}`;
13
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-input-as-code-points.test.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { getCodePoint, getInputAsCodePoints } from './get-input-as-code-points.js';
3
+
4
+ describe('getInputAsCodePoints', () => {
5
+ it('returns code points for string', () => {
6
+ expect(getInputAsCodePoints('abc')).toEqual([97, 98, 99]);
7
+ });
8
+
9
+ it('returns code points for number', () => {
10
+ expect(getInputAsCodePoints(99)).toEqual([99]);
11
+ });
12
+
13
+ it('returns code points for array of numbers', () => {
14
+ expect(getInputAsCodePoints([99, 100, 101])).toEqual([99, 100, 101]);
15
+ });
16
+
17
+ it('returns a single code point for astral characters', () => {
18
+ expect(getInputAsCodePoints('a😀b')).toEqual([97, 0x1f600, 98]);
19
+ });
20
+
21
+ it('throws for arrays containing non-integers', () => {
22
+ expect(() => getInputAsCodePoints([99, 1.5])).toThrow('code_point must be an integer for 1.5 if src is a list');
23
+ });
24
+
25
+ it('throws for invalid input types', () => {
26
+ expect(() => getInputAsCodePoints({} as unknown as string)).toThrow('Invalid input type: object');
27
+ });
28
+ });
29
+
30
+ describe('getCodePoint', () => {
31
+ it('returns the code point of a character', () => {
32
+ expect(getCodePoint('a')).toBe(97);
33
+ });
34
+
35
+ it('throws for an empty string', () => {
36
+ expect(() => getCodePoint('')).toThrow('Could not get code point for character: ');
37
+ });
38
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-input-as-code-points.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ValidInput } from './grammar-graph-types.js';
2
+
3
+ export function getCodePoint(char: string): number {
4
+ const codePoint = char.codePointAt(0);
5
+ if (codePoint === undefined) {
6
+ throw new Error(`Could not get code point for character: ${char}`);
7
+ }
8
+ if (!Number.isInteger(codePoint)) {
9
+ throw new Error('code_point must be an integer!');
10
+ }
11
+ return codePoint;
12
+ }
13
+
14
+ export function getInputAsCodePoints(src: ValidInput): number[] {
15
+ if (typeof src === 'number') {
16
+ return [src];
17
+ }
18
+
19
+ if (Array.isArray(src)) {
20
+ for (const c of src) {
21
+ if (!Number.isInteger(c)) {
22
+ throw new Error(`code_point must be an integer for ${c} if src is a list`);
23
+ }
24
+ }
25
+ return src;
26
+ }
27
+
28
+ if (typeof src === 'string') {
29
+ return Array.from(src, getCodePoint);
30
+ }
31
+
32
+ throw new Error(`Invalid input type: ${typeof src}`);
33
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-parent-stack-id.test.ts ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { Color } from './colorize.js';
3
+ import { getParentStackId } from './get-parent-stack-id.js';
4
+ import { RuleEnd } from './grammar-graph-types.js';
5
+ import { GraphNode } from './graph-node.js';
6
+ import { GraphPointer } from './graph-pointer.js';
7
+
8
+ const s = (str: string): string => JSON.stringify(str);
9
+
10
+ const mockColorize = (text: string | number, color: string): string => `[${s(color)}]:${text}`;
11
+
12
+ const red = s(Color.RED);
13
+ const gray = s(Color.GRAY);
14
+
15
+ const createMockPointer = (stackId: number, pathId: number, stepId: number, parent?: GraphPointer): GraphPointer =>
16
+ new GraphPointer(new GraphNode(new RuleEnd(), { stackId, pathId, stepId }), parent);
17
+
18
+ describe('getParentStackId', () => {
19
+ it('returns an empty string if no parents', () => {
20
+ const pointer = createMockPointer(1, 1, 1);
21
+ expect(getParentStackId(pointer, mockColorize)).toBe('');
22
+ });
23
+
24
+ it('returns a single parent id colored correctly', () => {
25
+ const parentPointer = createMockPointer(1, 1, 1);
26
+ const pointer = createMockPointer(2, 2, 2, parentPointer);
27
+ expect(getParentStackId(pointer, mockColorize)).toBe(`[${red}]:1,1,1`);
28
+ });
29
+
30
+ it('returns multiple parent ids separated by colored arrows', () => {
31
+ const grandparentPointer = createMockPointer(0, 0, 0);
32
+ const parentPointer = createMockPointer(1, 1, 1, grandparentPointer);
33
+ const pointer = createMockPointer(2, 2, 2, parentPointer);
34
+ expect(getParentStackId(pointer, mockColorize)).toBe(`[${red}]:1,1,1[${gray}]:<-[${red}]:0,0,0`);
35
+ });
36
+
37
+ it('handles deep nesting of pointers', () => {
38
+ const greatGrandparentPointer = createMockPointer(0, 0, 0);
39
+ const grandparentPointer = createMockPointer(1, 1, 1, greatGrandparentPointer);
40
+ const parentPointer = createMockPointer(2, 2, 2, grandparentPointer);
41
+ const pointer = createMockPointer(3, 3, 3, parentPointer);
42
+ expect(getParentStackId(pointer, mockColorize)).toBe(
43
+ `[${red}]:2,2,2[${gray}]:<-[${red}]:1,1,1[${gray}]:<-[${red}]:0,0,0`,
44
+ );
45
+ });
46
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-parent-stack-id.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Color } from './colorize.js';
2
+ import type { Colorize } from './grammar-graph-types.js';
3
+ import type { GraphPointer } from './graph-pointer.js';
4
+
5
+ export function getParentStackId(pointer: GraphPointer, col: Colorize): string {
6
+ const stackIds: string[] = [];
7
+ let parent: GraphPointer | undefined = pointer.parent;
8
+ while (parent) {
9
+ stackIds.push(`${parent.node.meta.stackId},${parent.node.meta.pathId},${parent.node.meta.stepId}`);
10
+ parent = parent.parent;
11
+ }
12
+ const arrow = col('<-', Color.GRAY);
13
+ return stackIds.map((stackId) => col(stackId, Color.RED)).join(arrow);
14
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-serialized-rule-key.integration.test.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { getSerializedRuleKey } from './get-serialized-rule-key.js';
3
+ import { RuleChar, RuleCharExclude, RuleEnd } from './grammar-graph-types.js';
4
+ import { RuleRef } from './rule-ref.js';
5
+
6
+ describe('getSerializedRuleKey (unmocked)', () => {
7
+ it('produces distinct keys per rule type and value', () => {
8
+ expect(getSerializedRuleKey(new RuleEnd())).toBe('0');
9
+ expect(getSerializedRuleKey(new RuleChar([97, [98, 99]]))).toBe('1-[97,[98,99]]');
10
+ expect(getSerializedRuleKey(new RuleCharExclude([97]))).toBe('2-[97]');
11
+ expect(getSerializedRuleKey(new RuleRef(4))).toBe('3-4');
12
+ });
13
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-serialized-rule-key.test.ts ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { KEY_TRANSLATION, getSerializedRuleKey } from './get-serialized-rule-key.js';
3
+ import { RuleChar, RuleCharExclude, RuleEnd, RuleType, type UnresolvedRule } from './grammar-graph-types.js';
4
+ import { RuleRef } from './rule-ref.js';
5
+ import { isRuleChar, isRuleCharExclude, isRuleEnd, isRuleRef } from './type-guards.js';
6
+
7
+ vi.mock('./type-guards.js', () => ({
8
+ isRuleEnd: vi.fn(() => false),
9
+ isRuleChar: vi.fn(() => false),
10
+ isRuleCharExclude: vi.fn(() => false),
11
+ isRuleRef: vi.fn(() => false),
12
+ }));
13
+
14
+ describe('getSerializedRuleKey', () => {
15
+ beforeEach(() => {
16
+ vi.mocked(isRuleEnd).mockReturnValue(false);
17
+ vi.mocked(isRuleChar).mockReturnValue(false);
18
+ vi.mocked(isRuleCharExclude).mockReturnValue(false);
19
+ vi.mocked(isRuleRef).mockReturnValue(false);
20
+ });
21
+
22
+ it('returns type for end rules', () => {
23
+ vi.mocked(isRuleEnd).mockReturnValue(true);
24
+ expect(getSerializedRuleKey(new RuleEnd())).toBe(`${KEY_TRANSLATION[RuleType.END]}`);
25
+ });
26
+
27
+ it('returns type and value for character rules', () => {
28
+ vi.mocked(isRuleChar).mockReturnValue(true);
29
+ expect(getSerializedRuleKey(new RuleChar([97]))).toBe(`${KEY_TRANSLATION[RuleType.CHAR]}-[97]`);
30
+ });
31
+
32
+ it('returns type and value for character exclude rules', () => {
33
+ vi.mocked(isRuleCharExclude).mockReturnValue(true);
34
+ expect(getSerializedRuleKey(new RuleCharExclude([97]))).toBe(`${KEY_TRANSLATION[RuleType.CHAR_EXCLUDE]}-[97]`);
35
+ });
36
+
37
+ it('returns ref type with value for reference rules', () => {
38
+ vi.mocked(isRuleRef).mockReturnValue(true);
39
+ expect(getSerializedRuleKey(new RuleRef(99))).toBe('3-99');
40
+ });
41
+
42
+ it('throws error for unknown rule types', () => {
43
+ const rule = { type: 'UNKNOWN', value: 'something' } as unknown as UnresolvedRule;
44
+ expect(() => getSerializedRuleKey(rule)).toThrow('Unknown rule type: {"type":"UNKNOWN","value":"something"}');
45
+ });
46
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/get-serialized-rule-key.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { RuleType, type UnresolvedRule } from './grammar-graph-types.js';
2
+ import { isRuleChar, isRuleCharExclude, isRuleEnd, isRuleRef } from './type-guards.js';
3
+
4
+ export const KEY_TRANSLATION = {
5
+ [RuleType.END]: 0,
6
+ [RuleType.CHAR]: 1,
7
+ [RuleType.CHAR_EXCLUDE]: 2,
8
+ [RuleType.REF]: 3,
9
+ } as const;
10
+
11
+ export function getSerializedRuleKey(rule: UnresolvedRule): string {
12
+ if (isRuleEnd(rule)) {
13
+ return `${KEY_TRANSLATION[RuleType.END]}`;
14
+ }
15
+
16
+ if (isRuleChar(rule)) {
17
+ return `${KEY_TRANSLATION[RuleType.CHAR]}-${JSON.stringify(rule.value)}`;
18
+ }
19
+
20
+ if (isRuleCharExclude(rule)) {
21
+ return `${KEY_TRANSLATION[RuleType.CHAR_EXCLUDE]}-${JSON.stringify(rule.value)}`;
22
+ }
23
+
24
+ if (isRuleRef(rule)) {
25
+ return `${KEY_TRANSLATION[RuleType.REF]}-${rule.value}`;
26
+ }
27
+
28
+ throw new Error(`Unknown rule type: ${JSON.stringify(rule)}`);
29
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/grammar-graph-types.test.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RuleChar, RuleCharExclude, RuleEnd, RuleType } from './grammar-graph-types.js';
3
+
4
+ describe('rule types', () => {
5
+ it('copies values on construction', () => {
6
+ const value: (number | [number, number])[] = [1, [2, 3]];
7
+ const rule = new RuleChar(value);
8
+ value.push(4);
9
+ expect(rule.value).toEqual([1, [2, 3]]);
10
+ expect(rule.type).toBe(RuleType.CHAR);
11
+ expect(new RuleCharExclude(value).type).toBe(RuleType.CHAR_EXCLUDE);
12
+ expect(new RuleEnd().type).toBe(RuleType.END);
13
+ });
14
+
15
+ it('compares structurally', () => {
16
+ expect(new RuleChar([1])).toEqual(new RuleChar([1]));
17
+ expect(new RuleChar([1])).not.toEqual(new RuleChar([2]));
18
+ expect(new RuleChar([1])).not.toEqual(new RuleCharExclude([1]));
19
+ expect(new RuleEnd()).toEqual(new RuleEnd());
20
+ expect(new RuleEnd()).not.toEqual(new RuleChar([1]));
21
+ });
22
+
23
+ it('serializes to JSON with a type tag', () => {
24
+ expect(JSON.parse(JSON.stringify(new RuleChar([1, [2, 3]])))).toEqual({ type: 'char', value: [1, [2, 3]] });
25
+ expect(JSON.parse(JSON.stringify(new RuleEnd()))).toEqual({ type: 'end' });
26
+ });
27
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/grammar-graph-types.ts ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphPointer } from './graph-pointer.js';
2
+ import type { RuleRef } from './rule-ref.js';
3
+
4
+ export const RuleType = {
5
+ CHAR: 'char',
6
+ CHAR_EXCLUDE: 'char_exclude',
7
+ END: 'end',
8
+ REF: 'ref',
9
+ } as const;
10
+ export type RuleType = (typeof RuleType)[keyof typeof RuleType];
11
+
12
+ export type Colorize = (text: string | number, color: string) => string;
13
+
14
+ export interface PrintOpts {
15
+ pointers?: Iterable<GraphPointer>;
16
+ colorize: Colorize;
17
+ showPosition?: boolean;
18
+ }
19
+
20
+ /** An inclusive range of code points: `[lower, upper]`. */
21
+ export type Range = [number, number];
22
+
23
+ /** A rule matching any one of a set of code points or code point ranges. */
24
+ export class RuleChar {
25
+ readonly type = RuleType.CHAR;
26
+ value: (number | Range)[];
27
+
28
+ constructor(value: (number | Range)[]) {
29
+ this.value = [...value];
30
+ }
31
+ }
32
+
33
+ /** A rule matching any code point that is *not* in a set of code points or code point ranges. */
34
+ export class RuleCharExclude {
35
+ readonly type = RuleType.CHAR_EXCLUDE;
36
+ value: (number | Range)[];
37
+
38
+ constructor(value: (number | Range)[]) {
39
+ this.value = [...value];
40
+ }
41
+ }
42
+
43
+ /** A rule indicating that the grammar may terminate at this point. */
44
+ export class RuleEnd {
45
+ readonly type = RuleType.END;
46
+ }
47
+
48
+ export type UnresolvedRule = RuleChar | RuleCharExclude | RuleRef | RuleEnd;
49
+
50
+ /**
51
+ * ValidInput can either be a string, or a number indicating a code point.
52
+ * It CANNOT be a number representing a number; a number intended as input (like "8")
53
+ * should be passed in as a string.
54
+ */
55
+ export type ValidInput = string | number | number[];
56
+
57
+ /** RuleRefs should never be exposed to the end user. */
58
+ export type ResolvedRule = RuleCharExclude | RuleChar | RuleEnd;
59
+
60
+ export type ResolvedGraphPointer = GraphPointer<ResolvedRule>;
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-node.test.ts ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import type { PrintOpts } from './grammar-graph-types.js';
3
+ import { GraphNode, type GraphNodeMeta } from './graph-node.js';
4
+ import { printGraphNode } from './print.js';
5
+ import { RuleRef } from './rule-ref.js';
6
+
7
+ vi.mock('./print.js', () => ({
8
+ printGraphNode: vi.fn(() => (_opts: PrintOpts) => 'mocked_response'),
9
+ }));
10
+
11
+ describe('GraphNode', () => {
12
+ const meta: GraphNodeMeta = { stackId: 1, pathId: 2, stepId: 3 };
13
+ const rule = new RuleRef(42);
14
+
15
+ it('constructs with rule and meta', () => {
16
+ const node = new GraphNode(rule, meta);
17
+ expect(node.rule).toBe(rule);
18
+ expect(node.meta).toBe(meta);
19
+ expect(node.next).toBeUndefined();
20
+ });
21
+
22
+ it('throws if meta is undefined', () => {
23
+ expect(() => new GraphNode(rule, undefined)).toThrow('Meta is undefined');
24
+ });
25
+
26
+ it('correctly calculates and caches its id', () => {
27
+ const node = new GraphNode(rule, meta);
28
+ expect(node.id).toBe('1,2,3');
29
+ node.meta = { stackId: 4, pathId: 5, stepId: 6 };
30
+ expect(node.id).toBe('1,2,3');
31
+ });
32
+
33
+ it('delegates print to the printGraphNode function', () => {
34
+ const node = new GraphNode(rule, meta);
35
+ const opts: PrintOpts = { colorize: (x) => String(x), showPosition: false };
36
+ expect(node.print(opts)).toBe('mocked_response');
37
+ expect(printGraphNode).toHaveBeenCalledWith(node);
38
+ });
39
+
40
+ it('handles next node linkage', () => {
41
+ const nextNode = new GraphNode(new RuleRef(43), meta);
42
+ const node = new GraphNode(rule, meta, nextNode);
43
+ expect(node.next).toBe(nextNode);
44
+ });
45
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-node.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { PrintOpts, UnresolvedRule } from './grammar-graph-types.js';
2
+ import { printGraphNode } from './print.js';
3
+ import type { RuleRef } from './rule-ref.js';
4
+
5
+ export interface GraphNodeMeta {
6
+ stackId: number;
7
+ pathId: number;
8
+ stepId: number;
9
+ }
10
+
11
+ /**
12
+ * A single step within a path of a rule. Nodes form a singly linked list via `next`.
13
+ */
14
+ export class GraphNode<T extends UnresolvedRule = UnresolvedRule> {
15
+ rule: T;
16
+ next: GraphNode | undefined;
17
+ meta: GraphNodeMeta;
18
+ #id: string | undefined = undefined;
19
+
20
+ constructor(rule: T, meta: GraphNodeMeta | undefined, nextNode?: GraphNode) {
21
+ this.rule = rule;
22
+ if (meta === undefined || meta === null) {
23
+ throw new Error('Meta is undefined');
24
+ }
25
+ this.meta = meta;
26
+ this.next = nextNode;
27
+ }
28
+
29
+ get id(): string {
30
+ if (this.#id === undefined) {
31
+ this.#id = `${this.meta.stackId},${this.meta.pathId},${this.meta.stepId}`;
32
+ }
33
+ return this.#id;
34
+ }
35
+
36
+ print(opts: PrintOpts): string {
37
+ return printGraphNode(this)(opts);
38
+ }
39
+ }
40
+
41
+ export type GraphNodeRuleRef = GraphNode<RuleRef>;
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-pointer.integration.test.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RuleChar, 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
+
7
+ const meta = (stackId: number, pathId: number, stepId: number) => ({ stackId, pathId, stepId });
8
+
9
+ describe('GraphPointer (unmocked)', () => {
10
+ // ref rule 1 ::= "a"
11
+ const charNode = new GraphNode(new RuleChar([97]), meta(1, 0, 0), new GraphNode(new RuleEnd(), meta(1, 0, 1)));
12
+ const ruleRef = new RuleRef(1);
13
+ ruleRef.nodes = new Set([charNode]);
14
+ // root ::= ref "b"
15
+ const bNode = new GraphNode(new RuleChar([98]), meta(0, 0, 1), new GraphNode(new RuleEnd(), meta(0, 0, 2)));
16
+ const refNode = new GraphNode(ruleRef, meta(0, 0, 0), bNode);
17
+
18
+ it('resolves references down into the referenced rule', () => {
19
+ const resolved = [...new GraphPointer(refNode).resolve()];
20
+ expect(resolved).toHaveLength(1);
21
+ expect(resolved[0].node).toBe(charNode);
22
+ expect(resolved[0].parent?.node).toBe(refNode);
23
+ expect(resolved[0].id).toBe('0,0,0-1,0,0');
24
+ });
25
+
26
+ it('resolves the end of a referenced rule up to the next node of the referencing rule', () => {
27
+ const [charPointer] = [...new GraphPointer(refNode).resolve()];
28
+ charPointer.valid = true;
29
+ const next = [...charPointer.fetchNext()];
30
+ expect(next).toHaveLength(1);
31
+ expect(next[0].node).toBe(bNode);
32
+ expect(next[0].parent).toBeUndefined();
33
+ });
34
+
35
+ it('fetches nothing for an invalid pointer', () => {
36
+ const [charPointer] = [...new GraphPointer(refNode).resolve()];
37
+ charPointer.valid = false;
38
+ expect([...charPointer.fetchNext()]).toEqual([]);
39
+ });
40
+
41
+ it('fetches nothing for a terminal end pointer', () => {
42
+ const endPointer = new GraphPointer(new GraphNode(new RuleEnd(), meta(0, 0, 0)));
43
+ endPointer.valid = true;
44
+ expect([...endPointer.fetchNext()]).toEqual([]);
45
+ });
46
+
47
+ it('throws when a non-end node has no next node', () => {
48
+ const pointer = new GraphPointer(new GraphNode(new RuleChar([97]), meta(0, 0, 0)));
49
+ pointer.valid = true;
50
+ expect(() => [...pointer.fetchNext()]).toThrow('No next node');
51
+ });
52
+
53
+ it('throws when resolving a reference with no next node', () => {
54
+ const danglingRef = new GraphNode(ruleRef, meta(0, 0, 0));
55
+ const [charPointer] = [...new GraphPointer(danglingRef).resolve()];
56
+ charPointer.valid = true;
57
+ expect(() => [...charPointer.fetchNext()]).toThrow('No next node');
58
+ });
59
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-pointer.test.ts ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from './grammar-graph-types.js';
3
+ import { GraphNode } from './graph-node.js';
4
+ import { GraphPointer } from './graph-pointer.js';
5
+ import {
6
+ isGraphPointerRuleChar,
7
+ isGraphPointerRuleCharExclude,
8
+ isGraphPointerRuleEnd,
9
+ isGraphPointerRuleRef,
10
+ } from './type-guards.js';
11
+
12
+ vi.mock('./type-guards.js', async (importOriginal) => {
13
+ const actual = await importOriginal<typeof import('./type-guards.js')>();
14
+ return {
15
+ ...actual,
16
+ isGraphPointerRuleRef: vi.fn(() => false),
17
+ isGraphPointerRuleEnd: vi.fn(() => false),
18
+ isGraphPointerRuleChar: vi.fn(() => false),
19
+ isGraphPointerRuleCharExclude: vi.fn(() => false),
20
+ };
21
+ });
22
+
23
+ const actualGuards = await vi.importActual<typeof import('./type-guards.js')>('./type-guards.js');
24
+
25
+ describe('GraphPointer', () => {
26
+ beforeEach(() => {
27
+ vi.mocked(isGraphPointerRuleRef).mockReset().mockReturnValue(false);
28
+ vi.mocked(isGraphPointerRuleEnd).mockReset().mockReturnValue(false);
29
+ vi.mocked(isGraphPointerRuleChar).mockReset().mockReturnValue(false);
30
+ vi.mocked(isGraphPointerRuleCharExclude).mockReset().mockReturnValue(false);
31
+ });
32
+
33
+ it('constructs with a node', () => {
34
+ const node = new GraphNode(new RuleEnd(), { stackId: 1, pathId: 2, stepId: 3 });
35
+ const pointer = new GraphPointer(node);
36
+ expect(pointer.node).toBe(node);
37
+ expect(pointer.id).toBe('1,2,3');
38
+ expect(pointer.parent).toBeUndefined();
39
+ expect(pointer.rule).toBe(node.rule);
40
+ });
41
+
42
+ it('throws an error if node is undefined', () => {
43
+ expect(() => new GraphPointer(undefined as unknown as GraphNode)).toThrow('Node is undefined');
44
+ });
45
+
46
+ it('initializes correctly with node and parent', () => {
47
+ const parentNode = new GraphNode(new RuleChar([97]), { stackId: 1, pathId: 2, stepId: 3 });
48
+ const childNode = new GraphNode(new RuleChar([98]), { stackId: 4, pathId: 5, stepId: 6 });
49
+ const parentPointer = new GraphPointer(parentNode);
50
+ const childPointer = new GraphPointer(childNode, parentPointer);
51
+ expect(childPointer.parent).toBe(parentPointer);
52
+ expect(childPointer.id).toBe('1,2,3-4,5,6');
53
+ });
54
+
55
+ it('tracks validity', () => {
56
+ const pointer = new GraphPointer(new GraphNode(new RuleEnd(), { stackId: 1, pathId: 2, stepId: 3 }));
57
+ expect(pointer.valid).toBeUndefined();
58
+ pointer.valid = true;
59
+ expect(pointer.valid).toBe(true);
60
+ });
61
+
62
+ describe('resolve', () => {
63
+ it('throws an error on unknown rule types', () => {
64
+ const node = new GraphNode({ type: 'UNKNOWN_RULE_TYPE' } as unknown as UnresolvedRule, {
65
+ stackId: 1,
66
+ pathId: 2,
67
+ stepId: 3,
68
+ });
69
+ const pointer = new GraphPointer(node);
70
+ expect(() => [...pointer.resolve()]).toThrow('Unknown rule');
71
+ });
72
+
73
+ it('yields a char rule', () => {
74
+ vi.mocked(isGraphPointerRuleChar).mockReturnValue(true);
75
+ const node = new GraphNode(new RuleChar([97]), { stackId: 1, pathId: 2, stepId: 3 });
76
+ const pointer = new GraphPointer(node);
77
+ expect([...pointer.resolve()]).toEqual([pointer]);
78
+ });
79
+
80
+ it('yields a char excluded rule', () => {
81
+ vi.mocked(isGraphPointerRuleCharExclude).mockReturnValue(true);
82
+ const node = new GraphNode(new RuleCharExclude([97]), { stackId: 1, pathId: 2, stepId: 3 });
83
+ const pointer = new GraphPointer(node);
84
+ expect([...pointer.resolve()]).toEqual([pointer]);
85
+ });
86
+
87
+ it('yields an end rule without a parent', () => {
88
+ vi.mocked(isGraphPointerRuleEnd).mockReturnValue(true);
89
+ const node = new GraphNode(new RuleEnd(), { stackId: 1, pathId: 2, stepId: 3 });
90
+ const pointer = new GraphPointer(node);
91
+ expect([...pointer.resolve()]).toEqual([pointer]);
92
+ });
93
+
94
+ it('yields an end rule with a parent', () => {
95
+ vi.mocked(isGraphPointerRuleEnd).mockReturnValue(true);
96
+ const rule = new RuleEnd();
97
+ const parentNode = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
98
+ const parentPointer = new GraphPointer(parentNode);
99
+ const childNode = new GraphNode(rule, { stackId: 1, pathId: 1, stepId: 1 });
100
+ const childPointer = new GraphPointer(childNode, parentPointer);
101
+ expect([...childPointer.resolve()]).toEqual([parentPointer]);
102
+ });
103
+
104
+ it('yields an end rule with a grandparent', () => {
105
+ vi.mocked(isGraphPointerRuleEnd).mockReturnValue(true);
106
+ const rule = new RuleEnd();
107
+ const grandparentNode = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
108
+ const grandparentPointer = new GraphPointer(grandparentNode);
109
+ const parentNode = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
110
+ const parentPointer = new GraphPointer(parentNode, grandparentPointer);
111
+ const childNode = new GraphNode(rule, { stackId: 1, pathId: 1, stepId: 1 });
112
+ const childPointer = new GraphPointer(childNode, parentPointer);
113
+ expect([...childPointer.resolve()]).toEqual([grandparentPointer]);
114
+ });
115
+
116
+ it('yields an end rule with a parent that is not an end with a grandparent', () => {
117
+ vi.mocked(isGraphPointerRuleEnd).mockImplementation(actualGuards.isGraphPointerRuleEnd);
118
+ vi.mocked(isGraphPointerRuleChar).mockImplementation(actualGuards.isGraphPointerRuleChar);
119
+ const rule = new RuleEnd();
120
+ const grandparentNode = new GraphNode(rule, { stackId: 2, pathId: 1, stepId: 1 });
121
+ const grandparentPointer = new GraphPointer(grandparentNode);
122
+ const parentNode = new GraphNode(new RuleChar([97]), { stackId: 2, pathId: 1, stepId: 1 });
123
+ const parentPointer = new GraphPointer(parentNode, grandparentPointer);
124
+ const childNode = new GraphNode(rule, { stackId: 1, pathId: 1, stepId: 1 });
125
+ const childPointer = new GraphPointer(childNode, parentPointer);
126
+ expect([...childPointer.resolve()]).toEqual([parentPointer]);
127
+ });
128
+ });
129
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph-pointer.ts ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ /**
15
+ * A position within the graph: a node, plus the chain of referencing nodes that led to it.
16
+ */
17
+ export class GraphPointer<T extends UnresolvedRule = UnresolvedRule> {
18
+ readonly node: GraphNode<T>;
19
+ readonly parent: GraphPointer | undefined;
20
+ readonly id: GraphPointerKey;
21
+ #valid: boolean | undefined = undefined;
22
+
23
+ constructor(node: GraphNode<T>, parent?: GraphPointer) {
24
+ if (node === undefined || node === null) {
25
+ throw new Error('Node is undefined');
26
+ }
27
+ this.node = node;
28
+ this.parent = parent;
29
+ this.id = parent ? `${parent.id}-${node.id}` : node.id;
30
+ }
31
+
32
+ get rule(): T {
33
+ return this.node.rule;
34
+ }
35
+
36
+ get valid(): boolean | undefined {
37
+ return this.#valid;
38
+ }
39
+
40
+ set valid(valid: boolean) {
41
+ this.#valid = valid;
42
+ }
43
+
44
+ print(opts: PrintOpts): string {
45
+ return printGraphPointer(this)(opts);
46
+ }
47
+
48
+ /**
49
+ * Resolve the graph pointer: follow references down into referenced rules, and
50
+ * end rules up into the parent's next node, until only char, char-exclude, or
51
+ * terminal end pointers remain.
52
+ *
53
+ * @param resolved Whether the pointer has already been resolved.
54
+ */
55
+ *resolve(resolved = false): Generator<ResolvedGraphPointer> {
56
+ if (isGraphPointerRuleRef(this)) {
57
+ if (resolved) {
58
+ if (!this.node.next) {
59
+ throw new Error(`No next node: ${this.node.id}`);
60
+ }
61
+ yield* new GraphPointer(this.node.next, this.parent).resolve();
62
+ } else {
63
+ for (const node of this.node.rule.nodes) {
64
+ yield* new GraphPointer(node, this).resolve();
65
+ }
66
+ }
67
+ } else if (isGraphPointerRuleEnd(this)) {
68
+ if (!this.parent) {
69
+ yield this as unknown as ResolvedGraphPointer;
70
+ } else {
71
+ yield* this.parent.resolve(true);
72
+ }
73
+ } else if (isGraphPointerRuleChar(this) || isGraphPointerRuleCharExclude(this)) {
74
+ yield this as unknown as ResolvedGraphPointer;
75
+ } else {
76
+ throw new Error(`Unknown rule: ${JSON.stringify(this.node.rule)}`);
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Fetch the next resolved graph pointers, assuming this pointer was marked valid.
82
+ */
83
+ *fetchNext(): Generator<ResolvedGraphPointer> {
84
+ // If this pointer is invalid, then we don't return any new pointers
85
+ if (!this.valid) {
86
+ return;
87
+ }
88
+
89
+ // If this pointer is an end node, we return the parent's next node.
90
+ // If no parent exists, we return nothing, since it's the end of the line.
91
+ if (isRuleEnd(this.node.rule)) {
92
+ if (this.parent) {
93
+ yield* this.parent.fetchNext();
94
+ }
95
+ } else {
96
+ if (!this.node.next) {
97
+ throw new Error(`No next node: ${this.node.id}`);
98
+ }
99
+ const pointer = new GraphPointer(this.node.next, this.parent);
100
+ yield* pointer.resolve();
101
+ }
102
+ }
103
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph.test.ts ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } 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
+ import { InputParseError } from '../utils/errors/index.js';
10
+
11
+ const meta = { stackId: 0, pathId: 0, stepId: 0 };
12
+
13
+ describe('Graph', () => {
14
+ const grammar = 'example-grammar';
15
+ const stackedRules: UnresolvedRule[][][] = [
16
+ [[new RuleChar([65, 66, 67])], [new RuleChar([68, 69, 70])]],
17
+ [[new RuleChar([71, 72, 73])], [new RuleChar([74, 75, 76])]],
18
+ ];
19
+ const rootId = 0;
20
+
21
+ it('creates a graph instance', () => {
22
+ const graph = new Graph(grammar, stackedRules, rootId);
23
+ expect(graph).toBeInstanceOf(Graph);
24
+ expect(graph.grammar).toBe(grammar);
25
+ });
26
+
27
+ it('gets the root node', () => {
28
+ const graph = new Graph(grammar, stackedRules, rootId);
29
+ const rootNode = graph.getRootNode(rootId);
30
+ expect(rootNode).toBeInstanceOf(Map);
31
+ expect(rootNode.size).toBe(2);
32
+ });
33
+
34
+ it('throws if the root node is missing', () => {
35
+ expect(() => new Graph(grammar, stackedRules, 5)).toThrow('Root node not found for value: 5');
36
+ const graph = new Graph(grammar, stackedRules, rootId);
37
+ expect(() => graph.getRootNode(7)).toThrow('Root node not found for value: 7');
38
+ });
39
+
40
+ it('prints the graph', () => {
41
+ const graph = new Graph(grammar, stackedRules, rootId);
42
+ const printedGraph = graph.print(undefined, true);
43
+ expect(typeof printedGraph).toBe('string');
44
+ expect(printedGraph.length).toBeGreaterThan(0);
45
+ });
46
+
47
+ it('prints the graph without colors', () => {
48
+ const graph = new Graph(
49
+ grammar,
50
+ [[[new RuleRef(1), new RuleEnd()]], [[new RuleChar([65, [66, 67]]), new RuleEnd()], [new RuleEnd()]]],
51
+ rootId,
52
+ );
53
+ expect(graph.print()).toBe(['{0,0,0}Ref(1)-> {0,0,1}end', '{1,0,0}[ABC]-> {1,0,1}end', '{1,1,0}end'].join('\n'));
54
+ });
55
+
56
+ it('prints pointers alongside the nodes they point at', () => {
57
+ const graph = new Graph(
58
+ grammar,
59
+ [[[new RuleRef(1), new RuleEnd()]], [[new RuleChar([65]), new RuleEnd()]]],
60
+ rootId,
61
+ );
62
+ const pointers = graph.add('');
63
+ expect(graph.print(pointers)).toBe(['{0,0,0}Ref(1)-> {0,0,1}end', '{1,0,0}[A][*0,0,0]-> {1,0,1}end'].join('\n'));
64
+ });
65
+
66
+ it('iterates over pointers', () => {
67
+ const graph = new Graph(grammar, stackedRules, rootId);
68
+ const mockPointers = new Pointers(
69
+ ...[
70
+ new RuleChar([65, 66, 67]),
71
+ new RuleChar([68, 69, 70]),
72
+ new RuleChar([71, 72, 73]),
73
+ new RuleChar([74, 75, 76]),
74
+ new RuleCharExclude([1]),
75
+ new RuleEnd(),
76
+ ].map((r, i) => new GraphPointer(new GraphNode(r, { stackId: i, pathId: 0, stepId: 0 }))),
77
+ );
78
+
79
+ const result = [...graph.iterateOverPointers(mockPointers)];
80
+ expect(result).toHaveLength(6);
81
+ for (const [rule, pointers] of result) {
82
+ expect(isRule(rule)).toBe(true);
83
+ expect(pointers.length).toBeGreaterThanOrEqual(1);
84
+ for (const pointer of pointers) {
85
+ expect(mockPointers.has(pointer)).toBe(true);
86
+ }
87
+ }
88
+ });
89
+
90
+ it('groups pointers sharing the same rule instance', () => {
91
+ const graph = new Graph(grammar, stackedRules, rootId);
92
+ const rule = new RuleChar([65]);
93
+ const a = new GraphPointer(new GraphNode(rule, { stackId: 0, pathId: 0, stepId: 0 }));
94
+ const b = new GraphPointer(new GraphNode(rule, { stackId: 1, pathId: 0, stepId: 0 }));
95
+ const result = [...graph.iterateOverPointers([a, b])];
96
+ expect(result).toEqual([[rule, [a, b]]]);
97
+ });
98
+
99
+ it('throws an error on a reference rule', () => {
100
+ const graph = new Graph(grammar, stackedRules, rootId);
101
+ const mockPointers = [new GraphPointer(new GraphNode(new RuleRef(0), meta))];
102
+ expect(() => [...graph.iterateOverPointers(mockPointers)]).toThrow('Encountered a reference rule in the graph');
103
+ });
104
+
105
+ it('shares a single rule instance between identical rules', () => {
106
+ const graph = new Graph(
107
+ grammar,
108
+ [[[new RuleChar([65]), new RuleChar([65]), new RuleEnd()]]],
109
+ rootId,
110
+ );
111
+ const [first] = graph.getRootNode(0).values();
112
+ expect(first.rule).toBe(first.next?.rule);
113
+ });
114
+
115
+ describe('add', () => {
116
+ // root ::= "ab" | ref ; ref ::= [c-d]
117
+ const buildGraph = () =>
118
+ new Graph(
119
+ 'root ::= "ab" | ref\nref ::= [c-d]',
120
+ [
121
+ [
122
+ [new RuleChar([97]), new RuleChar([98]), new RuleEnd()],
123
+ [new RuleRef(1), new RuleEnd()],
124
+ ],
125
+ [[new RuleChar([[99, 100]]), new RuleEnd()]],
126
+ ],
127
+ 0,
128
+ );
129
+
130
+ it('returns the initial pointers for empty input', () => {
131
+ const pointers = buildGraph().add('');
132
+ expect([...pointers].map((p) => p.rule)).toEqual([new RuleChar([97]), new RuleChar([[99, 100]])]);
133
+ });
134
+
135
+ it('advances pointers through the input', () => {
136
+ const graph = buildGraph();
137
+ const pointers = graph.add('a');
138
+ expect([...pointers].map((p) => p.rule)).toEqual([new RuleChar([98])]);
139
+ const next = graph.add('b', pointers);
140
+ expect([...next].map((p) => p.rule)).toEqual([new RuleEnd()]);
141
+ expect(graph.previousCodePoints).toEqual([97, 98]);
142
+ });
143
+
144
+ it('resolves references and ranges', () => {
145
+ const pointers = buildGraph().add('d');
146
+ expect([...pointers].map((p) => p.rule)).toEqual([new RuleEnd()]);
147
+ });
148
+
149
+ it('throws an InputParseError including previous input', () => {
150
+ const graph = buildGraph();
151
+ const pointers = graph.add('a');
152
+ let caught: unknown;
153
+ try {
154
+ graph.add('x', pointers);
155
+ } catch (err) {
156
+ caught = err;
157
+ }
158
+ expect(caught).toBeInstanceOf(InputParseError);
159
+ expect((caught as InputParseError).message).toBe(new InputParseError('x', 0, 'a').message);
160
+ expect(graph.previousCodePoints).toEqual([97]);
161
+ });
162
+
163
+ it('rejects non-string input', () => {
164
+ expect(() => buildGraph().add(97 as unknown as string)).toThrow('src must be a string in graph.add');
165
+ });
166
+ });
167
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/graph.ts ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 } 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
+ /** The entry nodes of each path of a rule, keyed by path id. */
14
+ export type RootNode = Map<number, GraphNode>;
15
+
16
+ /**
17
+ * The grammar, compiled into a graph of linked nodes, which can be walked by feeding it input.
18
+ */
19
+ export class Graph {
20
+ readonly #roots = new Map<number, RootNode>();
21
+ readonly grammar: string;
22
+ readonly #rootNode: RootNode;
23
+ readonly previousCodePoints: number[] = [];
24
+
25
+ constructor(grammar: string, stackedRules: UnresolvedRule[][][], rootId: number) {
26
+ this.grammar = grammar;
27
+ const ruleRefs: RuleRef[] = [];
28
+ const uniqueRules = new Map<string, UnresolvedRule>();
29
+
30
+ for (let stackId = 0; stackId < stackedRules.length; stackId++) {
31
+ const stack = stackedRules[stackId];
32
+ const nodes: RootNode = new Map();
33
+ for (let pathId = 0; pathId < stack.length; pathId++) {
34
+ const path = stack[pathId];
35
+ let node: GraphNode | undefined = undefined;
36
+ for (let stepId = path.length - 1; stepId >= 0; stepId--) {
37
+ const nextNode: GraphNode | undefined = node;
38
+ const rule = path[stepId];
39
+ const key = getSerializedRuleKey(rule);
40
+ // rules coming in may be identical but have different references.
41
+ // here, we ensure we always use the same reference for an identical rule.
42
+ // this makes future comparisons easier.
43
+ if (!uniqueRules.has(key)) {
44
+ uniqueRules.set(key, rule);
45
+ }
46
+ const uniqueRule = uniqueRules.get(key);
47
+ if (uniqueRule === undefined) {
48
+ throw new Error('Could not get unique rule');
49
+ }
50
+ if (isRuleRef(uniqueRule)) {
51
+ ruleRefs.push(uniqueRule);
52
+ }
53
+ node = new GraphNode(uniqueRule, { stackId, pathId, stepId }, nextNode);
54
+ }
55
+
56
+ if (node === undefined) {
57
+ throw new Error('Could not get node');
58
+ }
59
+ nodes.set(pathId, node);
60
+ }
61
+ this.#roots.set(stackId, nodes);
62
+ }
63
+
64
+ const rootNode = this.#roots.get(rootId);
65
+ if (rootNode === undefined) {
66
+ throw new Error(`Root node not found for value: ${rootId}`);
67
+ }
68
+ this.#rootNode = rootNode;
69
+
70
+ for (const ruleRef of ruleRefs) {
71
+ ruleRef.nodes = new Set(this.getRootNode(ruleRef.value).values());
72
+ }
73
+ }
74
+
75
+ /** @internal */
76
+ getRootNode(value: number): RootNode {
77
+ const rootNode = this.#roots.get(value);
78
+ if (rootNode === undefined) {
79
+ throw new Error(`Root node not found for value: ${value}`);
80
+ }
81
+ return rootNode;
82
+ }
83
+
84
+ #getInitialPointers(): Pointers {
85
+ const pointers = new Pointers();
86
+
87
+ for (const [node, parent] of this.#fetchNodesForRootNode(this.#rootNode)) {
88
+ const pointer = new GraphPointer(node, parent);
89
+ for (const resolvedPointer of this.#resolvePointer(pointer)) {
90
+ pointers.add(resolvedPointer);
91
+ }
92
+ }
93
+ return pointers;
94
+ }
95
+
96
+ #setValid(pointers: GraphPointer[], valid: boolean): void {
97
+ for (const pointer of pointers) {
98
+ pointer.valid = valid;
99
+ }
100
+ }
101
+
102
+ #parse(currentPointers: Pointers, codePoint: number): Pointers {
103
+ for (const [rule, graphPointers] of this.iterateOverPointers(currentPointers)) {
104
+ if (isRuleChar(rule)) {
105
+ let valid = false;
106
+ for (const possibleCodePoint of rule.value) {
107
+ if (valid) {
108
+ break;
109
+ }
110
+ if (isRange(possibleCodePoint)) {
111
+ if (isPointInRange(codePoint, possibleCodePoint)) {
112
+ valid = true;
113
+ }
114
+ } else if (codePoint === possibleCodePoint) {
115
+ valid = true;
116
+ }
117
+ }
118
+ this.#setValid(graphPointers, valid);
119
+ } else if (isRuleCharExclude(rule)) {
120
+ let valid = true;
121
+ for (const possibleCodePoint of rule.value) {
122
+ if (!valid) {
123
+ break;
124
+ }
125
+ if (isRange(possibleCodePoint)) {
126
+ if (isPointInRange(codePoint, possibleCodePoint)) {
127
+ valid = false;
128
+ }
129
+ } else if (codePoint === possibleCodePoint) {
130
+ valid = false;
131
+ }
132
+ }
133
+ this.#setValid(graphPointers, valid);
134
+ } else if (!isRuleEnd(rule)) {
135
+ throw new Error(`Unsupported rule: ${JSON.stringify(rule)}`);
136
+ }
137
+ }
138
+
139
+ // a pointer's id is the sum of its node's id and its parent's id chain.
140
+ // if two pointers share the same id, it means they point to the same node and have identical parent chains.
141
+ // for the purposes of walking the graph, we only need to keep one of them.
142
+ const nextPointers = new Pointers();
143
+ for (const currentPointer of currentPointers) {
144
+ for (const unresolvedNextPointer of currentPointer.fetchNext()) {
145
+ for (const resolvedNextPointer of this.#resolvePointer(unresolvedNextPointer)) {
146
+ nextPointers.add(resolvedNextPointer);
147
+ }
148
+ }
149
+ }
150
+ return nextPointers;
151
+ }
152
+
153
+ *#resolvePointer(unresolvedPointer: GraphPointer): Generator<ResolvedGraphPointer> {
154
+ for (const resolvedPointer of unresolvedPointer.resolve()) {
155
+ if (isRuleRef(resolvedPointer.node.rule)) {
156
+ throw new Error('Encountered a reference rule when building pointers to the graph');
157
+ }
158
+ if (isRuleEnd(resolvedPointer.node.rule) && resolvedPointer.parent !== undefined) {
159
+ throw new Error('Encountered an ending rule with a parent when building pointers to the graph');
160
+ }
161
+ yield resolvedPointer;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Walk the graph with the given input, starting from `pointers` (or from the root rule if omitted).
167
+ *
168
+ * @throws InputParseError if the input cannot be matched by the grammar.
169
+ */
170
+ add(src: string, pointers?: Pointers): Pointers {
171
+ if (typeof src !== 'string') {
172
+ throw new TypeError('src must be a string in graph.add');
173
+ }
174
+ let currentPointers = pointers ?? this.#getInitialPointers();
175
+
176
+ const codePoints = getInputAsCodePoints(src);
177
+ for (const codePoint of codePoints) {
178
+ if (!Number.isInteger(codePoint)) {
179
+ throw new Error('code_point must be an integer!');
180
+ }
181
+ }
182
+
183
+ for (let codePointPos = 0; codePointPos < codePoints.length; codePointPos++) {
184
+ const codePoint = codePoints[codePointPos];
185
+ currentPointers = this.#parse(currentPointers, codePoint);
186
+ if (currentPointers.size === 0) {
187
+ throw new InputParseError(codePoints, codePointPos, [...this.previousCodePoints]);
188
+ }
189
+ }
190
+ this.previousCodePoints.push(...codePoints);
191
+ return currentPointers;
192
+ }
193
+
194
+ // generator that yields either the node, or if a reference rule, the referenced node
195
+ // we need these function, as distinct from leveraging the logic in GraphPointer,
196
+ // because that needs a rule ref with already defined nodes; this function is used to _set_ those nodes
197
+ *#fetchNodesForRootNode(
198
+ rootNodes: RootNode,
199
+ parent?: GraphPointer,
200
+ ): Generator<[GraphNode, GraphPointer | undefined]> {
201
+ for (const node of rootNodes.values()) {
202
+ if (isRuleRef(node.rule)) {
203
+ yield* this.#fetchNodesForRootNode(this.getRootNode(node.rule.value), new GraphPointer(node, parent));
204
+ } else {
205
+ yield [node, parent];
206
+ }
207
+ }
208
+ }
209
+
210
+ print(pointers?: Pointers, colors = false): string {
211
+ const graphView: string[] = [];
212
+ for (const rootNode of this.#roots.values()) {
213
+ for (const node of rootNode.values()) {
214
+ graphView.push(
215
+ node.print({
216
+ pointers: pointers ?? new Pointers(),
217
+ showPosition: true,
218
+ colorize: colors ? colorize : (s) => String(s),
219
+ }),
220
+ );
221
+ }
222
+ }
223
+
224
+ return graphView.join('\n');
225
+ }
226
+
227
+ /**
228
+ * Groups pointers by the rule they point at, so that validity can be computed once per rule.
229
+ * @internal
230
+ */
231
+ *iterateOverPointers(pointers: Iterable<GraphPointer>): Generator<[UnresolvedRule, GraphPointer[]]> {
232
+ const seenRules = new Map<UnresolvedRule, GraphPointer[]>();
233
+ for (const pointer of pointers) {
234
+ const rule = pointer.rule;
235
+ if (isRuleRef(rule)) {
236
+ throw new Error('Encountered a reference rule in the graph');
237
+ }
238
+
239
+ const seenRule = seenRules.get(rule);
240
+ if (seenRule === undefined) {
241
+ seenRules.set(rule, [pointer]);
242
+ } else {
243
+ seenRule.push(pointer);
244
+ }
245
+ }
246
+
247
+ yield* seenRules.entries();
248
+ }
249
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/index.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export { Graph } from './graph.js';
2
+ export type { RootNode } from './graph.js';
3
+ export { GraphNode } from './graph-node.js';
4
+ export type { GraphNodeMeta, GraphNodeRuleRef } from './graph-node.js';
5
+ export { GraphPointer } from './graph-pointer.js';
6
+ export { ParseState } from './parse-state.js';
7
+ export { Pointers } from './pointers.js';
8
+ export { RuleRef } from './rule-ref.js';
9
+ export { RuleChar, RuleCharExclude, RuleEnd, RuleType } from './grammar-graph-types.js';
10
+ export type {
11
+ Colorize,
12
+ PrintOpts,
13
+ Range,
14
+ ResolvedGraphPointer,
15
+ ResolvedRule,
16
+ UnresolvedRule,
17
+ ValidInput,
18
+ } from './grammar-graph-types.js';
19
+ export { Color, colorize } from './colorize.js';
20
+ export * from './type-guards.js';
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/parse-state.test.ts ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { RuleChar, RuleEnd } 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 add = vi.fn((_input: string, pointers: Pointers) => pointers);
11
+ return { add, grammar: 'sample-grammar', graph: { add, grammar: 'sample-grammar' } as unknown as Graph };
12
+ };
13
+
14
+ const mockPointers = new Pointers(
15
+ new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 1, pathId: 1, stepId: 1 })),
16
+ );
17
+
18
+ describe('ParseState', () => {
19
+ it('constructs with given graph and pointers', () => {
20
+ const parseState = new ParseState(makeMockGraph().graph, mockPointers);
21
+ expect(parseState).toBeInstanceOf(ParseState);
22
+ });
23
+
24
+ it('returns unique rules from pointers', () => {
25
+ const parseState = new ParseState(makeMockGraph().graph, mockPointers);
26
+ const rules = [...parseState.rules()];
27
+ expect(rules).toHaveLength(1);
28
+ expect(rules[0]).toBeInstanceOf(RuleChar);
29
+ expect((rules[0] as RuleChar).value).toEqual([65]);
30
+ });
31
+
32
+ it('iterates over unique rules using the iterator', () => {
33
+ const parseState = new ParseState(makeMockGraph().graph, mockPointers);
34
+ const rules = [...parseState];
35
+ expect(rules).toHaveLength(1);
36
+ expect(rules[0]).toBeInstanceOf(RuleChar);
37
+ });
38
+
39
+ it('de-duplicates rules with identical values at different nodes', () => {
40
+ const pointers = new Pointers(
41
+ new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 1, pathId: 1, stepId: 1 })),
42
+ new GraphPointer(new GraphNode(new RuleChar([65]), { stackId: 2, pathId: 1, stepId: 1 })),
43
+ new GraphPointer(new GraphNode(new RuleEnd(), { stackId: 3, pathId: 1, stepId: 1 })),
44
+ new GraphPointer(new GraphNode(new RuleEnd(), { stackId: 4, pathId: 1, stepId: 1 })),
45
+ );
46
+ const parseState = new ParseState(makeMockGraph().graph, pointers);
47
+ expect([...parseState]).toEqual([new RuleChar([65]), new RuleEnd()]);
48
+ expect(parseState.size).toBe(2);
49
+ });
50
+
51
+ it('adds new input and returns new parse state with updated pointers', () => {
52
+ const { add, graph } = makeMockGraph();
53
+ const newPointers = new Pointers(
54
+ new GraphPointer(new GraphNode(new RuleChar([66]), { stackId: 1, pathId: 1, stepId: 1 })),
55
+ );
56
+ add.mockReturnValue(newPointers);
57
+
58
+ const parseState = new ParseState(graph, mockPointers);
59
+ const newState = parseState.add('B');
60
+ expect(newState).toBeInstanceOf(ParseState);
61
+ expect(newState).not.toBe(parseState);
62
+ expect(add).toHaveBeenCalledWith('B', mockPointers);
63
+ expect([...newState]).toEqual([new RuleChar([66])]);
64
+ });
65
+
66
+ it('rejects non-string input', () => {
67
+ const parseState = new ParseState(makeMockGraph().graph, mockPointers);
68
+ expect(() => parseState.add(66 as unknown as string)).toThrow('input text must be of type string');
69
+ });
70
+
71
+ it('calculates the size of unique rules correctly', () => {
72
+ const parseState = new ParseState(makeMockGraph().graph, mockPointers);
73
+ expect(parseState.size).toBe(1);
74
+ });
75
+
76
+ it('provides access to the underlying graph grammar', () => {
77
+ const parseState = new ParseState(makeMockGraph().graph, mockPointers);
78
+ expect(parseState.grammar).toBe('sample-grammar');
79
+ });
80
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/parse-state.ts ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ /**
6
+ * An immutable snapshot of a parse: the set of rules that may legally come next.
7
+ *
8
+ * Iterating a ParseState yields the unique rules at the current position. Adding input
9
+ * returns a new ParseState advanced past that input.
10
+ */
11
+ export class ParseState implements Iterable<ResolvedRule> {
12
+ readonly #graph: Graph;
13
+ readonly #pointers: Pointers;
14
+
15
+ constructor(graph: Graph, pointers: Pointers) {
16
+ this.#graph = graph;
17
+ this.#pointers = pointers;
18
+ }
19
+
20
+ *[Symbol.iterator](): IterableIterator<ResolvedRule> {
21
+ yield* this.rules();
22
+ }
23
+
24
+ *rules(): IterableIterator<ResolvedRule> {
25
+ const seen = new Set<string>();
26
+ for (const pointer of this.#pointers) {
27
+ const rule = pointer.rule as ResolvedRule;
28
+ const key = JSON.stringify(rule);
29
+ if (!seen.has(key)) {
30
+ seen.add(key);
31
+ yield rule;
32
+ }
33
+ }
34
+ }
35
+
36
+ add(text: string): ParseState {
37
+ if (typeof text !== 'string') {
38
+ throw new TypeError('input text must be of type string');
39
+ }
40
+ const pointers = this.#graph.add(text, this.#pointers);
41
+ return new ParseState(this.#graph, pointers);
42
+ }
43
+
44
+ get size(): number {
45
+ return [...this.rules()].length;
46
+ }
47
+
48
+ get grammar(): string {
49
+ return this.#graph.grammar;
50
+ }
51
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/pointers.test.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } 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 = (stackId: number) =>
8
+ new GraphPointer(new GraphNode(new RuleChar([65]), { stackId, pathId: 0, stepId: 0 }));
9
+
10
+ describe('Pointers', () => {
11
+ it('stores pointers in insertion order', () => {
12
+ const a = makePointer(0);
13
+ const b = makePointer(1);
14
+ const pointers = new Pointers(b, a);
15
+ expect([...pointers]).toEqual([b, a]);
16
+ expect(pointers.size).toBe(2);
17
+ expect(pointers.has(a)).toBe(true);
18
+ expect(pointers.has(makePointer(2))).toBe(false);
19
+ });
20
+
21
+ it('de-duplicates pointers by id, keeping the latest', () => {
22
+ const a = makePointer(0);
23
+ const aAgain = makePointer(0);
24
+ const pointers = new Pointers(a);
25
+ pointers.add(aAgain);
26
+ expect(pointers.size).toBe(1);
27
+ expect([...pointers]).toEqual([aAgain]);
28
+ expect(pointers.has(a)).toBe(false);
29
+ expect(pointers.has(aAgain)).toBe(true);
30
+ });
31
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/pointers.ts ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphPointer } from './graph-pointer.js';
2
+
3
+ /**
4
+ * An insertion-ordered set of graph pointers, de-duplicated by pointer id.
5
+ */
6
+ export class Pointers implements Iterable<GraphPointer> {
7
+ readonly #pointers = new Map<string, GraphPointer>();
8
+
9
+ constructor(...pointers: GraphPointer[]) {
10
+ for (const pointer of pointers) {
11
+ this.add(pointer);
12
+ }
13
+ }
14
+
15
+ add(pointer: GraphPointer): void {
16
+ this.#pointers.set(pointer.id, pointer);
17
+ }
18
+
19
+ has(pointer: GraphPointer): boolean {
20
+ return this.#pointers.get(pointer.id) === pointer;
21
+ }
22
+
23
+ *[Symbol.iterator](): IterableIterator<GraphPointer> {
24
+ yield* this.#pointers.values();
25
+ }
26
+
27
+ get size(): number {
28
+ return this.#pointers.size;
29
+ }
30
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/print.test.ts ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { getParentStackId } from './get-parent-stack-id.js';
3
+ import { RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from './grammar-graph-types.js';
4
+ import type { GraphNode } from './graph-node.js';
5
+ import type { GraphPointer } from './graph-pointer.js';
6
+ import { getChar, printGraphNode, printGraphPointer } from './print.js';
7
+ import { RuleRef } from './rule-ref.js';
8
+
9
+ vi.mock('./get-parent-stack-id.js', () => ({
10
+ getParentStackId: vi.fn(),
11
+ }));
12
+
13
+ const COLORS: Record<string, string> = {
14
+ '\x1b[34m': 'BLUE',
15
+ '\x1b[36m': 'CYAN',
16
+ '\x1b[32m': 'GREEN',
17
+ '\x1b[31m': 'RED',
18
+ '\x1b[90m': 'GRAY',
19
+ '\x1b[33m': 'YELLOW',
20
+ };
21
+
22
+ const mockColorize = (text: string | number, color: string): string => {
23
+ if (!(color in COLORS)) {
24
+ throw new Error(`Invalid color: ${color}`);
25
+ }
26
+ return `[${COLORS[color]}]:${text}`;
27
+ };
28
+
29
+ const createMockNode = (id: number, rule: UnresolvedRule, next?: GraphNode): GraphNode =>
30
+ ({
31
+ id: String(id),
32
+ rule,
33
+ next,
34
+ meta: { stackId: id, pathId: 0, stepId: 0 },
35
+ print: () => `Node(${id})`,
36
+ }) as unknown as GraphNode;
37
+
38
+ const createMockGraphPointer = (node: GraphNode): GraphPointer =>
39
+ ({
40
+ node,
41
+ parent: undefined,
42
+ print: () => `Pointer to ${node.id}`,
43
+ }) as unknown as GraphPointer;
44
+
45
+ describe('print', () => {
46
+ describe('printGraphPointer', () => {
47
+ it('prints graph pointer details correctly', () => {
48
+ const mockNode = createMockNode(1, new RuleRef(100));
49
+ const mockPointer = createMockGraphPointer(mockNode);
50
+ vi.mocked(getParentStackId).mockReturnValue('foo');
51
+ const result = printGraphPointer(mockPointer)({ colorize: mockColorize, pointers: [], showPosition: false });
52
+ expect(result).toBe('[RED]:*foo');
53
+ });
54
+ });
55
+
56
+ describe('printGraphNode', () => {
57
+ it('prints graph node with a character rule', () => {
58
+ const mockNode = createMockNode(1, new RuleChar([65]));
59
+ const result = printGraphNode(mockNode)({ colorize: mockColorize, showPosition: false, pointers: [] });
60
+ expect(result).toBe('[GRAY]:[[YELLOW]:A[GRAY]:]');
61
+ });
62
+
63
+ it('prints graph node with a character rule containing a range', () => {
64
+ const mockNode = createMockNode(1, new RuleChar([65, [66, 67]]));
65
+ const result = printGraphNode(mockNode)({ colorize: mockColorize });
66
+ expect(result).toBe('[GRAY]:[[YELLOW]:A[YELLOW]:B[YELLOW]:C[GRAY]:]');
67
+ });
68
+
69
+ it('prints graph node with a rule reference', () => {
70
+ const mockNode = createMockNode(1, new RuleRef(200));
71
+ const result = printGraphNode(mockNode)({ colorize: mockColorize, showPosition: true, pointers: [] });
72
+ expect(result).toBe('[BLUE]:{[GRAY]:1[BLUE]:}[GRAY]:Ref([GREEN]:200[GRAY]:)');
73
+ });
74
+
75
+ it('prints graph node with an end rule and a char exclude rule', () => {
76
+ expect(printGraphNode(createMockNode(1, new RuleEnd()))({ colorize: mockColorize })).toBe('[YELLOW]:end');
77
+ expect(printGraphNode(createMockNode(1, new RuleCharExclude([65])))({ colorize: mockColorize })).toBe(
78
+ '[YELLOW]:char_exclude',
79
+ );
80
+ });
81
+
82
+ it('prints the next node joined by an arrow', () => {
83
+ const nextNode = createMockNode(2, new RuleEnd());
84
+ const mockNode = createMockNode(1, new RuleChar([65]), nextNode);
85
+ const result = printGraphNode(mockNode)({ colorize: mockColorize });
86
+ expect(result).toBe('[GRAY]:[[YELLOW]:A[GRAY]:][GRAY]:-> Node(2)');
87
+ });
88
+
89
+ it('prints pointers that point at the node', () => {
90
+ const mockNode = createMockNode(1, new RuleChar([65]));
91
+ const otherNode = createMockNode(2, new RuleChar([66]));
92
+ const result = printGraphNode(mockNode)({
93
+ colorize: mockColorize,
94
+ pointers: [createMockGraphPointer(mockNode), createMockGraphPointer(otherNode)],
95
+ });
96
+ expect(result).toBe('[GRAY]:[[YELLOW]:A[GRAY]:][GRAY]:[[YELLOW]:Pointer to 1[GRAY]:]');
97
+ });
98
+ });
99
+
100
+ describe('getChar', () => {
101
+ it('escapes newlines', () => {
102
+ expect(getChar(10)).toBe('\\n');
103
+ expect(getChar(65)).toBe('A');
104
+ expect(getChar(0x1f600)).toBe('😀');
105
+ });
106
+ });
107
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/print.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Color } from './colorize.js';
2
+ import { getParentStackId } from './get-parent-stack-id.js';
3
+ import type { PrintOpts } 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
+ export const printGraphPointer =
9
+ (pointer: GraphPointer) =>
10
+ (opts: PrintOpts): string => {
11
+ const col = opts.colorize;
12
+ return col(`*${getParentStackId(pointer, col)}`, Color.RED);
13
+ };
14
+
15
+ export const printGraphNode =
16
+ (node: GraphNode) =>
17
+ (opts: PrintOpts): string => {
18
+ const pointers = opts.pointers ?? [];
19
+ const col = opts.colorize;
20
+ const showPosition = opts.showPosition ?? false;
21
+ const rule = node.rule;
22
+ const parts: string[] = [];
23
+ if (showPosition) {
24
+ parts.push(col('{', Color.BLUE), col(node.id, Color.GRAY), col('}', Color.BLUE));
25
+ }
26
+
27
+ if (isRuleChar(rule)) {
28
+ parts.push(
29
+ col('[', Color.GRAY),
30
+ col(
31
+ rule.value
32
+ .map((v) => (isRange(v) ? v.map((val) => col(getChar(val), Color.YELLOW)).join('') : getChar(v)))
33
+ .join(''),
34
+ Color.YELLOW,
35
+ ),
36
+ col(']', Color.GRAY),
37
+ );
38
+ } else if (isRuleRef(rule)) {
39
+ parts.push(col('Ref(', Color.GRAY), col(rule.value, Color.GREEN), col(')', Color.GRAY));
40
+ } else {
41
+ parts.push(col(rule.type, Color.YELLOW));
42
+ }
43
+
44
+ for (const pointer of pointers) {
45
+ const pointerParts: string[] = [];
46
+ if (pointer.node === node) {
47
+ pointerParts.push(pointer.print(opts));
48
+ }
49
+
50
+ if (pointerParts.length > 0) {
51
+ parts.push(col('[', Color.GRAY), col(pointerParts.join(''), Color.YELLOW), col(']', Color.GRAY));
52
+ }
53
+ }
54
+
55
+ const partsToReturn = [parts.join('')];
56
+ if (node.next) {
57
+ partsToReturn.push(node.next.print(opts));
58
+ }
59
+
60
+ return partsToReturn.join(col('-> ', Color.GRAY));
61
+ };
62
+
63
+ export function getChar(charCode: number): string {
64
+ const char = String.fromCodePoint(charCode);
65
+ if (char === '\n') {
66
+ return '\\n';
67
+ }
68
+ return char;
69
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/rule-ref.test.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RuleType } from './grammar-graph-types.js';
3
+ import type { GraphNode } from './graph-node.js';
4
+ import { RuleRef } from './rule-ref.js';
5
+
6
+ describe('RuleRef', () => {
7
+ it('initializes with a given value', () => {
8
+ const ruleRef = new RuleRef(123);
9
+ expect(ruleRef.value).toBe(123);
10
+ expect(ruleRef.type).toBe(RuleType.REF);
11
+ });
12
+
13
+ it('allows setting and getting nodes', () => {
14
+ const mockNodes = new Set<GraphNode>([1 as unknown as GraphNode]);
15
+ const ruleRef = new RuleRef(123);
16
+ ruleRef.nodes = mockNodes;
17
+ expect(ruleRef.nodes).toBe(mockNodes);
18
+ });
19
+
20
+ it('throws an error if trying to get nodes before setting', () => {
21
+ const ruleRef = new RuleRef(123);
22
+ expect(() => ruleRef.nodes).toThrow('Nodes are not set');
23
+ });
24
+
25
+ it('compares structurally by value', () => {
26
+ expect(new RuleRef(1)).toEqual(new RuleRef(1));
27
+ expect(new RuleRef(1)).not.toEqual(new RuleRef(2));
28
+ });
29
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/rule-ref.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { RuleType } from './grammar-graph-types.js';
2
+ import type { GraphNode } from './graph-node.js';
3
+
4
+ /**
5
+ * A reference to another rule, by id. Once the graph is built, `nodes` holds the
6
+ * entry nodes of every path of the referenced rule.
7
+ */
8
+ export class RuleRef {
9
+ readonly type = RuleType.REF;
10
+ value: number;
11
+ #nodes: Set<GraphNode> | undefined = undefined;
12
+
13
+ constructor(value: number) {
14
+ this.value = value;
15
+ }
16
+
17
+ get nodes(): Set<GraphNode> {
18
+ if (this.#nodes === undefined) {
19
+ throw new Error('Nodes are not set');
20
+ }
21
+ return this.#nodes;
22
+ }
23
+
24
+ set nodes(nodes: Set<GraphNode>) {
25
+ this.#nodes = nodes;
26
+ }
27
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-graph/type-guards.test.ts ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } 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
+ it('returns true', () => {
24
+ expect(isGraphPointerRuleRef(new GraphPointer(new GraphNode(new RuleRef(1), meta)))).toBe(true);
25
+ });
26
+
27
+ it('returns false', () => {
28
+ expect(isGraphPointerRuleRef(new GraphPointer(new GraphNode(new RuleEnd(), meta)))).toBe(false);
29
+ });
30
+ });
31
+
32
+ describe('isGraphPointerRuleEnd', () => {
33
+ it('returns false', () => {
34
+ expect(isGraphPointerRuleEnd(new GraphPointer(new GraphNode(new RuleRef(1), meta)))).toBe(false);
35
+ });
36
+
37
+ it('returns true', () => {
38
+ expect(isGraphPointerRuleEnd(new GraphPointer(new GraphNode(new RuleEnd(), meta)))).toBe(true);
39
+ });
40
+ });
41
+
42
+ describe('isGraphPointerRuleChar', () => {
43
+ it('returns true', () => {
44
+ expect(isGraphPointerRuleChar(new GraphPointer(new GraphNode(new RuleChar([97]), meta)))).toBe(true);
45
+ });
46
+
47
+ it('returns false', () => {
48
+ expect(isGraphPointerRuleChar(new GraphPointer(new GraphNode(new RuleEnd(), meta)))).toBe(false);
49
+ });
50
+ });
51
+
52
+ describe('isGraphPointerRuleCharExclude', () => {
53
+ it('returns true', () => {
54
+ expect(isGraphPointerRuleCharExclude(new GraphPointer(new GraphNode(new RuleCharExclude([97]), meta)))).toBe(
55
+ true,
56
+ );
57
+ });
58
+
59
+ it('returns false', () => {
60
+ expect(isGraphPointerRuleCharExclude(new GraphPointer(new GraphNode(new RuleChar([97]), meta)))).toBe(false);
61
+ });
62
+ });
63
+
64
+ describe('isRule', () => {
65
+ it('returns false for null and undefined', () => {
66
+ expect(isRule(null)).toBe(false);
67
+ expect(isRule(undefined)).toBe(false);
68
+ });
69
+
70
+ it('returns false for a non-rule', () => {
71
+ expect(isRule({ type: 'invalid', value: [] })).toBe(false);
72
+ });
73
+
74
+ it('returns true for valid rule objects', () => {
75
+ expect(isRule(new RuleChar([65, [66, 67]]))).toBe(true);
76
+ expect(isRule(new RuleCharExclude([65]))).toBe(true);
77
+ expect(isRule(new RuleEnd())).toBe(true);
78
+ expect(isRule(new RuleRef(1))).toBe(true);
79
+ });
80
+ });
81
+
82
+ describe('isRuleRef', () => {
83
+ it('returns true for valid rule refs', () => {
84
+ expect(isRuleRef(new RuleRef(1))).toBe(true);
85
+ });
86
+
87
+ it('returns false for invalid rule refs', () => {
88
+ expect(isRuleRef(new RuleChar([65]))).toBe(false);
89
+ });
90
+ });
91
+
92
+ describe('isRuleEnd', () => {
93
+ it('returns true for valid rule ends', () => {
94
+ expect(isRuleEnd(new RuleEnd())).toBe(true);
95
+ });
96
+
97
+ it('returns false for invalid rule ends', () => {
98
+ expect(isRuleEnd(new RuleChar([65]))).toBe(false);
99
+ });
100
+ });
101
+
102
+ describe('isRuleChar', () => {
103
+ it('returns true for valid rule chars', () => {
104
+ expect(isRuleChar(new RuleChar([65]))).toBe(true);
105
+ });
106
+
107
+ it('returns false for invalid rule chars', () => {
108
+ expect(isRuleChar(new RuleCharExclude([65]))).toBe(false);
109
+ });
110
+ });
111
+
112
+ describe('isRuleCharExclude', () => {
113
+ it('returns true for valid rule char excludes', () => {
114
+ expect(isRuleCharExclude(new RuleCharExclude([65]))).toBe(true);
115
+ });
116
+
117
+ it('returns false for invalid rule char excludes', () => {
118
+ expect(isRuleCharExclude(new RuleChar([65]))).toBe(false);
119
+ });
120
+ });
121
+
122
+ describe('isRange', () => {
123
+ it('returns true for valid ranges', () => {
124
+ expect(isRange([1, 10])).toBe(true);
125
+ });
126
+
127
+ it.each<[unknown]>([[[1, '10']], [[1]], [5], [[1, 2, 3]], [[1.5, 2]]])('returns false for invalid range %s', (value) => {
128
+ expect(isRange(value)).toBe(false);
129
+ });
130
+ });
131
+ });
v2-models-effort/runs/20261026-191627-tight-wave/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-191627-tight-wave/ported_implementation/src/grammar-parser/build-rule-stack.test.ts ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RuleChar, RuleCharExclude, RuleEnd } from '../grammar-graph/grammar-graph-types.js';
3
+ import { RuleRef } from '../grammar-graph/rule-ref.js';
4
+ import {
5
+ type InternalRuleDef,
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
+ type Case = [string, InternalRuleDef[], (RuleChar | RuleCharExclude | RuleEnd | RuleRef)[][]];
17
+
18
+ const noModifierCases: Case[] = [
19
+ ["[a-z]", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefEnd()], [[new RuleChar([[97, 122]]), new RuleEnd()]]],
20
+ ["[a-zA-Z]", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90]]), new RuleEnd()]]],
21
+ ["[a-zA-Z0-9]", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefCharAlt(48), new InternalRuleDefCharRngUpper(57), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90], [48, 57]]), new RuleEnd()]]],
22
+ ];
23
+
24
+ const questionMarkCases: Case[] = [
25
+ ["[a-z]?", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefAlt(), new InternalRuleDefEnd()], [[new RuleChar([[97, 122]]), new RuleEnd()], [new RuleEnd()]]],
26
+ ["[a-zA-Z]?", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefAlt(), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90]]), new RuleEnd()], [new RuleEnd()]]],
27
+ ["[a-zA-Z0-9]?", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefCharAlt(48), new InternalRuleDefCharRngUpper(57), new InternalRuleDefAlt(), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90], [48, 57]]), new RuleEnd()], [new RuleEnd()]]],
28
+ ];
29
+
30
+ const plusCases: Case[] = [
31
+ ["[a-z]+", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefReference(1), new InternalRuleDefAlt(), new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefEnd()], [[new RuleChar([[97, 122]]), new RuleRef(1), new RuleEnd()], [new RuleChar([[97, 122]]), new RuleEnd()]]],
32
+ ["[a-zA-Z]+", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefReference(1), new InternalRuleDefAlt(), new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90]]), new RuleRef(1), new RuleEnd()], [new RuleChar([[97, 122], [65, 90]]), new RuleEnd()]]],
33
+ ["[a-zA-Z0-9]+", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefCharAlt(48), new InternalRuleDefCharRngUpper(57), new InternalRuleDefReference(1), new InternalRuleDefAlt(), new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefCharAlt(48), new InternalRuleDefCharRngUpper(57), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90], [48, 57]]), new RuleRef(1), new RuleEnd()], [new RuleChar([[97, 122], [65, 90], [48, 57]]), new RuleEnd()]]],
34
+ ];
35
+
36
+ const asteriskCases: Case[] = [
37
+ ["[a-z]*", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefReference(1), new InternalRuleDefAlt(), new InternalRuleDefEnd()], [[new RuleChar([[97, 122]]), new RuleRef(1), new RuleEnd()], [new RuleEnd()]]],
38
+ ["[a-zA-Z]*", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefReference(1), new InternalRuleDefAlt(), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90]]), new RuleRef(1), new RuleEnd()], [new RuleEnd()]]],
39
+ ["[a-zA-Z0-9]*", [new InternalRuleDefChar([97]), new InternalRuleDefCharRngUpper(122), new InternalRuleDefCharAlt(65), new InternalRuleDefCharRngUpper(90), new InternalRuleDefCharAlt(48), new InternalRuleDefCharRngUpper(57), new InternalRuleDefReference(1), new InternalRuleDefAlt(), new InternalRuleDefEnd()], [[new RuleChar([[97, 122], [65, 90], [48, 57]]), new RuleRef(1), new RuleEnd()], [new RuleEnd()]]],
40
+ ];
41
+
42
+
43
+ describe('buildRuleStack', () => {
44
+ it('builds rule stack for a single path', () => {
45
+ expect(buildRuleStack([new InternalRuleDefChar([120])])).toEqual([[new RuleChar([120]), new RuleEnd()]]);
46
+ });
47
+
48
+ it('builds rule stack for two alternate paths', () => {
49
+ expect(
50
+ buildRuleStack([new InternalRuleDefChar([120]), new InternalRuleDefAlt(), new InternalRuleDefChar([121])]),
51
+ ).toEqual([
52
+ [new RuleChar([120]), new RuleEnd()],
53
+ [new RuleChar([121]), new RuleEnd()],
54
+ ]);
55
+ });
56
+
57
+ it('builds rule stack for three alternate paths', () => {
58
+ expect(
59
+ buildRuleStack([
60
+ new InternalRuleDefChar([120]),
61
+ new InternalRuleDefAlt(),
62
+ new InternalRuleDefChar([121]),
63
+ new InternalRuleDefAlt(),
64
+ new InternalRuleDefChar([122]),
65
+ ]),
66
+ ).toEqual([
67
+ [new RuleChar([120]), new RuleEnd()],
68
+ [new RuleChar([121]), new RuleEnd()],
69
+ [new RuleChar([122]), new RuleEnd()],
70
+ ]);
71
+ });
72
+
73
+ it('builds rule stack for char not', () => {
74
+ expect(
75
+ buildRuleStack([
76
+ new InternalRuleDefCharNot([120]),
77
+ new InternalRuleDefAlt(),
78
+ new InternalRuleDefCharNot([121]),
79
+ new InternalRuleDefAlt(),
80
+ new InternalRuleDefCharNot([122]),
81
+ ]),
82
+ ).toEqual([
83
+ [new RuleCharExclude([120]), new RuleEnd()],
84
+ [new RuleCharExclude([121]), new RuleEnd()],
85
+ [new RuleCharExclude([122]), new RuleEnd()],
86
+ ]);
87
+ });
88
+
89
+ it('builds rule stack for mixed char and char not', () => {
90
+ expect(
91
+ buildRuleStack([
92
+ new InternalRuleDefCharNot([120]),
93
+ new InternalRuleDefAlt(),
94
+ new InternalRuleDefChar([121]),
95
+ new InternalRuleDefAlt(),
96
+ new InternalRuleDefCharNot([122]),
97
+ ]),
98
+ ).toEqual([
99
+ [new RuleCharExclude([120]), new RuleEnd()],
100
+ [new RuleChar([121]), new RuleEnd()],
101
+ [new RuleCharExclude([122]), new RuleEnd()],
102
+ ]);
103
+ });
104
+
105
+ it('builds rule stack for char not with two characters and a range', () => {
106
+ expect(
107
+ buildRuleStack([
108
+ new InternalRuleDefCharNot([120]),
109
+ new InternalRuleDefCharAlt(121),
110
+ new InternalRuleDefCharAlt(122),
111
+ new InternalRuleDefCharRngUpper(130),
112
+ ]),
113
+ ).toEqual([[new RuleCharExclude([120, 121, [122, 130]]), new RuleEnd()]]);
114
+ });
115
+
116
+ describe('ranges', () => {
117
+ it.each(noModifierCases)('builds rule stack for a char with no modifiers: %s', (_grammar, input, expected) => {
118
+ expect(buildRuleStack(input)).toEqual(expected);
119
+ });
120
+ });
121
+
122
+ it.each(questionMarkCases)('builds rule stack for a char with question mark modifier: %s', (_grammar, input, expected) => {
123
+ expect(buildRuleStack(input)).toEqual(expected);
124
+ });
125
+
126
+ it.each(plusCases)('builds rule stack for a char with plus modifier: %s', (_grammar, input, expected) => {
127
+ expect(buildRuleStack(input)).toEqual(expected);
128
+ });
129
+
130
+ it.each(asteriskCases)('builds rule stack for a char with asterisk modifier: %s', (_grammar, input, expected) => {
131
+ expect(buildRuleStack(input)).toEqual(expected);
132
+ });
133
+
134
+ it('builds rule stack for char with range', () => {
135
+ const input: InternalRuleDef[] = [
136
+ new InternalRuleDefChar([97]),
137
+ new InternalRuleDefCharRngUpper(122),
138
+ new InternalRuleDefCharAlt(65),
139
+ new InternalRuleDefCharRngUpper(90),
140
+ new InternalRuleDefCharAlt(95),
141
+ new InternalRuleDefEnd(),
142
+ ];
143
+ expect(buildRuleStack(input)).toEqual([
144
+ [new RuleChar([[97, 122], [65, 90], 95]), new RuleEnd()],
145
+ ]);
146
+ });
147
+
148
+ it('builds rule stack for situation root ws plus newline ws star', () => {
149
+ const input: InternalRuleDef[] = [
150
+ new InternalRuleDefChar([32]),
151
+ new InternalRuleDefCharAlt(92),
152
+ new InternalRuleDefCharAlt(110),
153
+ new InternalRuleDefReference(4),
154
+ new InternalRuleDefAlt(),
155
+ new InternalRuleDefEnd(),
156
+ ];
157
+ expect(buildRuleStack(input)).toEqual([
158
+ [new RuleChar([32, 92, 110]), new RuleRef(4), new RuleEnd()],
159
+ [new RuleEnd()],
160
+ ]);
161
+ });
162
+
163
+ it('builds rule stack for situation root char plus char range', () => {
164
+ const input: InternalRuleDef[] = [
165
+ new InternalRuleDefChar([97]),
166
+ new InternalRuleDefCharRngUpper(122),
167
+ new InternalRuleDefCharAlt(65),
168
+ new InternalRuleDefCharRngUpper(90),
169
+ new InternalRuleDefReference(1),
170
+ new InternalRuleDefAlt(),
171
+ new InternalRuleDefChar([97]),
172
+ new InternalRuleDefCharRngUpper(122),
173
+ new InternalRuleDefCharAlt(65),
174
+ new InternalRuleDefCharRngUpper(90),
175
+ new InternalRuleDefEnd(),
176
+ ];
177
+ expect(buildRuleStack(input)).toEqual([
178
+ [new RuleChar([[97, 122], [65, 90]]), new RuleRef(1), new RuleEnd()],
179
+ [new RuleChar([[97, 122], [65, 90]]), new RuleEnd()],
180
+ ]);
181
+ });
182
+
183
+ it('does not mutate the input rule definition values', () => {
184
+ const charDef = new InternalRuleDefChar([97]);
185
+ buildRuleStack([charDef, new InternalRuleDefCharRngUpper(122), new InternalRuleDefEnd()]);
186
+ expect(charDef.value).toEqual([97]);
187
+ });
188
+
189
+ it('throws when encountering an alt without anything before it', () => {
190
+ expect(() => buildRuleStack([new InternalRuleDefAlt(), new InternalRuleDefEnd()])).toThrow(
191
+ 'Encountered alt without anything before it',
192
+ );
193
+ });
194
+
195
+ it('throws when a range upper follows a range', () => {
196
+ expect(() =>
197
+ buildRuleStack([
198
+ new InternalRuleDefChar([97]),
199
+ new InternalRuleDefCharRngUpper(122),
200
+ new InternalRuleDefCharRngUpper(90),
201
+ ]),
202
+ ).toThrow('Unexpected range, expected a number but got an array');
203
+ });
204
+
205
+ it('throws when encountering a char alt outside of a char sequence', () => {
206
+ expect(() => buildRuleStack([new InternalRuleDefCharAlt(97)])).toThrow('Encountered char alt');
207
+ });
208
+
209
+ it('throws for unsupported rule types', () => {
210
+ expect(() => buildRuleStack([{ type: 'BOGUS' } as unknown as InternalRuleDef])).toThrow('Unsupported rule type');
211
+ });
212
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-parser/build-rule-stack.ts ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ type Range,
3
+ RuleChar,
4
+ RuleCharExclude,
5
+ RuleEnd,
6
+ type UnresolvedRule,
7
+ } from '../grammar-graph/grammar-graph-types.js';
8
+ import { RuleRef } from '../grammar-graph/rule-ref.js';
9
+ import { isRange, isRuleEnd } from '../grammar-graph/type-guards.js';
10
+ import {
11
+ type InternalRuleDef,
12
+ type InternalRuleDefChar,
13
+ type InternalRuleDefCharNot,
14
+ isRuleDefAlt,
15
+ isRuleDefChar,
16
+ isRuleDefCharAlt,
17
+ isRuleDefCharNot,
18
+ isRuleDefCharRngUpper,
19
+ isRuleDefEnd,
20
+ isRuleDefRef,
21
+ } from '../rules-builder/rules-builder-types.js';
22
+
23
+ const makeCharRule = (ruleDef: InternalRuleDefChar | InternalRuleDefCharNot): RuleChar | RuleCharExclude => {
24
+ if (isRuleDefCharNot(ruleDef)) {
25
+ return new RuleCharExclude(ruleDef.value);
26
+ }
27
+ if (isRuleDefChar(ruleDef)) {
28
+ return new RuleChar(ruleDef.value);
29
+ }
30
+
31
+ throw new Error(`Unsupported rule type for makeCharRule: ${JSON.stringify(ruleDef)}`);
32
+ };
33
+
34
+ /**
35
+ * Converts the flat, linear list of internal rule definitions for a single rule into a
36
+ * "stack" of paths: one list of rules per alternate, each terminated by a RuleEnd.
37
+ *
38
+ * Adjacent CHAR / CHAR_ALT / CHAR_RNG_UPPER definitions are folded into a single
39
+ * RuleChar (or RuleCharExclude) whose value holds code points and `[lower, upper]` ranges.
40
+ */
41
+ export function buildRuleStack(linearRules: InternalRuleDef[]): UnresolvedRule[][] {
42
+ let paths: UnresolvedRule[] = [];
43
+ const stack: UnresolvedRule[][] = [];
44
+ let idx = 0;
45
+
46
+ while (idx < linearRules.length) {
47
+ const ruleDef = linearRules[idx];
48
+ if (isRuleDefChar(ruleDef) || isRuleDefCharNot(ruleDef)) {
49
+ // this could be a single char, or a range, or a sequence of alts; we don't know until we step through it.
50
+ const charRule = makeCharRule(ruleDef);
51
+ idx += 1;
52
+ let rule: InternalRuleDef | undefined = idx < linearRules.length ? linearRules[idx] : undefined;
53
+ while (idx < linearRules.length && (isRuleDefCharRngUpper(rule) || isRuleDefCharAlt(rule))) {
54
+ if (isRuleDefCharRngUpper(rule)) {
55
+ // previous rule value should be a number
56
+ const prevValue = charRule.value.pop();
57
+ if (isRange(prevValue)) {
58
+ throw new Error(`Unexpected range, expected a number but got an array: ${JSON.stringify(prevValue)}`);
59
+ }
60
+ if (prevValue === undefined) {
61
+ throw new Error('Unexpected undefined value');
62
+ }
63
+
64
+ charRule.value.push([prevValue, rule.value] as Range);
65
+ }
66
+ if (isRuleDefCharAlt(rule)) {
67
+ charRule.value.push(rule.value);
68
+ }
69
+ idx += 1;
70
+ rule = idx < linearRules.length ? linearRules[idx] : undefined;
71
+ }
72
+ paths.push(charRule);
73
+ } else {
74
+ if (isRuleDefAlt(ruleDef)) {
75
+ if (paths.length === 0) {
76
+ throw new Error('Encountered alt without anything before it');
77
+ }
78
+ paths.push(new RuleEnd());
79
+ stack.push(paths);
80
+ paths = [];
81
+ } else if (isRuleDefEnd(ruleDef)) {
82
+ paths.push(new RuleEnd());
83
+ } else if (isRuleDefRef(ruleDef)) {
84
+ paths.push(new RuleRef(ruleDef.value));
85
+ } else if (isRuleDefCharAlt(ruleDef)) {
86
+ throw new Error(`Encountered char alt, should be handled by above block: ${JSON.stringify(ruleDef)}`);
87
+ } else {
88
+ throw new Error(`Unsupported rule type: ${JSON.stringify(ruleDef)}`);
89
+ }
90
+ idx += 1;
91
+ }
92
+ }
93
+
94
+ if (paths.length === 0 || !isRuleEnd(paths[paths.length - 1])) {
95
+ paths.push(new RuleEnd());
96
+ }
97
+
98
+ stack.push(paths);
99
+ return stack;
100
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/grammar-parser/index.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ export { buildRuleStack } from './build-rule-stack.js';
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/index.test.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import GBNFDefault, {
3
+ GBNF,
4
+ GrammarParseError,
5
+ InputParseError,
6
+ ParseState,
7
+ RuleChar,
8
+ RuleCharExclude,
9
+ RuleEnd,
10
+ RuleType,
11
+ } from './index.js';
12
+
13
+ describe('index', () => {
14
+ it('exports the public API', () => {
15
+ expect(GBNFDefault).toBe(GBNF);
16
+ expect(typeof GBNF).toBe('function');
17
+ expect(GrammarParseError).toBeDefined();
18
+ expect(InputParseError).toBeDefined();
19
+ expect(ParseState).toBeDefined();
20
+ expect(RuleChar).toBeDefined();
21
+ expect(RuleCharExclude).toBeDefined();
22
+ expect(RuleEnd).toBeDefined();
23
+ expect(RuleType.CHAR).toBe('char');
24
+ });
25
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/index.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export { GBNF } from './GBNF.js';
2
+ export { GBNF as default } from './GBNF.js';
3
+ export { RuleChar, RuleCharExclude, RuleEnd, RuleType } from './grammar-graph/grammar-graph-types.js';
4
+ export type { Range, ResolvedRule, ValidInput } from './grammar-graph/grammar-graph-types.js';
5
+ export { ParseState } from './grammar-graph/parse-state.js';
6
+ export { GrammarParseError, InputParseError } from './utils/errors/index.js';
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/index.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export { GrammarParseError, InputParseError } from '../utils/errors/index.js';
2
+ export { RulesBuilder } from './rules-builder.js';
3
+ export { SymbolIds } from './symbol-ids.js';
4
+ export * from './rules-builder-types.js';
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/is-word-char.test.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { isWordChar } from './is-word-char.js';
3
+
4
+ describe('isWordChar', () => {
5
+ it('returns true for lowercase letters', () => {
6
+ expect(isWordChar('a')).toBe(true);
7
+ expect(isWordChar('z')).toBe(true);
8
+ });
9
+
10
+ it('returns true for uppercase letters', () => {
11
+ expect(isWordChar('A')).toBe(true);
12
+ expect(isWordChar('Z')).toBe(true);
13
+ });
14
+
15
+ it('returns false for digits', () => {
16
+ expect(isWordChar('0')).toBe(false);
17
+ expect(isWordChar('9')).toBe(false);
18
+ });
19
+
20
+ it('returns false for non-word characters', () => {
21
+ expect(isWordChar('-')).toBe(false);
22
+ expect(isWordChar('@')).toBe(false);
23
+ expect(isWordChar('_')).toBe(false);
24
+ expect(isWordChar('?')).toBe(false);
25
+ expect(isWordChar(' ')).toBe(false);
26
+ });
27
+ });
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/is-word-char.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export function isWordChar(c: string): boolean {
2
+ return /[a-zA-Z]/.test(c);
3
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/parse-char.test.ts ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } 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
+ it.each<[string, string, number]>([
9
+ ['simple char', 'a', ord('a')],
10
+ ['simple digit', '9', ord('9')],
11
+ ])('parses a %s', (_description, char, codePoint) => {
12
+ const grammar = `root ::= "${char}" "foo"`;
13
+ expect(parseChar(grammar, 'root ::= "'.length)).toEqual([codePoint, 1]);
14
+ });
15
+
16
+ it.each<[string, string, number, number]>([
17
+ ['escaped 8-bit unicode char', '\\x2A', ord('\x2A'), 4],
18
+ ['escaped 16-bit unicode char', '\\u006F', ord('o'), 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
+ ])('parses an %s', (_description, escapedChar, codePoint, incPos) => {
28
+ const grammar = `root ::= "${escapedChar}" "foo"`;
29
+ expect(parseChar(grammar, 'root ::= "'.length)).toEqual([codePoint, incPos]);
30
+ });
31
+
32
+ it('parses an astral character as a single code point spanning two indices', () => {
33
+ expect(parseChar('root ::= "💩"', 'root ::= "'.length)).toEqual([128169, 2]);
34
+ });
35
+
36
+ it.each<[string, number]>([
37
+ ['', 0],
38
+ ['a', 1],
39
+ ['a', 2],
40
+ ])('throws for input %s at position %s', (input, pos) => {
41
+ expect(() => parseChar(input, pos)).toThrow(GrammarParseError);
42
+ });
43
+
44
+ it('throws for an unknown escape', () => {
45
+ expect(() => parseChar('\\q', 0)).toThrow(GrammarParseError);
46
+ });
47
+
48
+ it('throws for an invalid hex escape', () => {
49
+ expect(() => parseChar('\\xZZ', 0)).toThrow(GrammarParseError);
50
+ expect(() => parseChar('\\x2', 0)).toThrow(GrammarParseError);
51
+ });
52
+ });
v2-models-effort/runs/20261026-191627-tight-wave/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: 0x09,
5
+ r: 0x0d,
6
+ n: 0x0a,
7
+ '"': 0x22,
8
+ '[': 0x5b,
9
+ ']': 0x5d,
10
+ '\\': 0x5c,
11
+ };
12
+
13
+ const parseHex = (src: string, pos: number, start: number, end: number): number => {
14
+ const hex = src.slice(start, end);
15
+ if (hex.length !== end - start || !/^[0-9a-fA-F]+$/.test(hex)) {
16
+ throw new GrammarParseError(src, pos, `Invalid escape sequence at ${pos}`);
17
+ }
18
+ return parseInt(hex, 16);
19
+ };
20
+
21
+ /**
22
+ * Parses a single (possibly escaped) character at `pos`.
23
+ *
24
+ * Returns the code point of the character, and the number of string indices to advance by.
25
+ */
26
+ export function parseChar(src: string, pos: number): [number, number] {
27
+ if (pos >= src.length) {
28
+ throw new GrammarParseError(src, pos, 'Unexpected end of grammar input, failed to complete parse');
29
+ }
30
+
31
+ if (src[pos] === '\\') {
32
+ const escape = src[pos + 1];
33
+ if (escape === 'x') {
34
+ return [parseHex(src, pos, pos + 2, pos + 4), 4];
35
+ }
36
+ if (escape === 'u') {
37
+ return [parseHex(src, pos, pos + 2, pos + 6), 6];
38
+ }
39
+ if (escape === 'U') {
40
+ return [parseHex(src, pos, pos + 2, pos + 10), 10];
41
+ }
42
+ if (escape !== undefined && escape in SIMPLE_ESCAPES) {
43
+ return [SIMPLE_ESCAPES[escape], 2];
44
+ }
45
+ throw new GrammarParseError(src, pos, `Unknown escape at ${src[pos]}`);
46
+ }
47
+
48
+ const codePoint = src.codePointAt(pos) as number;
49
+ return [codePoint, codePoint > 0xffff ? 2 : 1];
50
+ }
v2-models-effort/runs/20261026-191627-tight-wave/ported_implementation/src/rules-builder/parse-name.test.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } 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
+ it('returns the correct name when encountering a valid name', () => {
7
+ const src = 'validName';
8
+ expect(parseName(src, 0)).toBe(src);
9
+ });
10
+
11
+ it('returns the correct name when encountering a valid name starting at a non-zero position', () => {
12
+ const src = '123validName';
13
+ expect(parseName(src, 3)).toBe('validName');
14
+ });
15
+
16
+ it('includes dashes and underscores in names', () => {
17
+ expect(parseName('foo-bar_baz ::=', 0)).toBe('foo-bar_baz');
18
+ });
19
+
20
+ it('throws an error when encountering an invalid name', () => {
21
+ const src = '123';
22
+ expect(() => parseName(src, 0)).toThrow(GrammarParseError);
23
+ expect(() => parseName(src, 0)).toThrow(new GrammarParseError(src, 0, PARSE_NAME_ERROR).message);
24
+ });
25
+ });
v2-models-effort/runs/20261026-191627-tight-wave/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 function 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
+ }