thekevinscott commited on
Commit
fad33ea
·
verified ·
1 Parent(s): 71fbfd7

Upload all of experiments/ as on disk 2026-11-11 (part 3)

Browse files
Files changed (46) hide show
  1. v2-models-effort/runs/20261111-214430-fragrant-meadow/credentials.log +18 -0
  2. v2-models-effort/runs/20261111-214430-fragrant-meadow/git-diff.patch +0 -0
  3. v2-models-effort/runs/20261111-214430-fragrant-meadow/git-sha.txt +1 -0
  4. v2-models-effort/runs/20261111-214430-fragrant-meadow/manifest.json +99 -0
  5. v2-models-effort/runs/20261111-214430-fragrant-meadow/memory.jsonl +77 -0
  6. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/README.md +15 -0
  7. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/GBNF.ts +30 -0
  8. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/colorize.ts +12 -0
  9. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/get_input_as_code_points.ts +33 -0
  10. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/get_parent_stack_id.ts +18 -0
  11. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/get_serialized_rule_key.ts +31 -0
  12. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/grammar_graph_types.ts +99 -0
  13. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/graph.ts +281 -0
  14. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/graph_node.ts +44 -0
  15. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/graph_pointer.ts +102 -0
  16. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/index.ts +12 -0
  17. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/parse_state.ts +65 -0
  18. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/pointers.ts +40 -0
  19. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/print.ts +75 -0
  20. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/rule_ref.ts +29 -0
  21. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/type_guards.ts +58 -0
  22. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_parser/build_rule_stack.ts +101 -0
  23. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_parser/index.ts +1 -0
  24. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/index.ts +5 -0
  25. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/index.ts +2 -0
  26. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/is_word_char.ts +5 -0
  27. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/parse_char.ts +47 -0
  28. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/parse_name.ts +22 -0
  29. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/parse_space.ts +23 -0
  30. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/rules_builder.ts +292 -0
  31. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/rules_builder_types.ts +114 -0
  32. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/symbol_ids.ts +71 -0
  33. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/smoke.test.ts +76 -0
  34. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/build_error_position.ts +36 -0
  35. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/errors_types.ts +1 -0
  36. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/get_input_as_string.ts +13 -0
  37. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/grammar_parse_error.ts +35 -0
  38. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/index.ts +2 -0
  39. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/input_parse_error.ts +67 -0
  40. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/index.ts +2 -0
  41. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/is_point_in_range.ts +8 -0
  42. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/py.ts +77 -0
  43. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/validate_non_empty.ts +8 -0
  44. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/node_modules/.vite/vitest/results.json +1 -0
  45. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/package.json +15 -0
  46. v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/tests/differential.test.ts +58 -0
v2-models-effort/runs/20261111-214430-fragrant-meadow/credentials.log ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [2026-11-11 21:44:43.709][22][warning][main] [source/server/server.cc:1012] There is no configured limit to the number of allowed active downstream connections. Configure a limit in `envoy.resource_monitors.global_downstream_max_connections` resource monitor.
2
+ [2026-11-11T21:44:44.489Z] POST /v1/messages?beta=true 200 - 1998ms
3
+ [2026-11-11T21:44:46.555Z] POST /v1/messages?beta=true 200 - 1708ms
4
+ [2026-11-11T21:44:49.836Z] POST /v1/messages/count_tokens?beta=true 200 - 132ms
5
+ [2026-11-11T21:44:48.292Z] POST /v1/messages?beta=true 200 - 2390ms
6
+ [2026-11-11T21:44:50.707Z] POST /v1/messages?beta=true 200 - 6039ms
7
+ [2026-11-11T21:44:56.774Z] POST /v1/messages?beta=true 200 - 71908ms
8
+ [2026-11-11T21:46:08.707Z] POST /v1/messages?beta=true 200 - 87425ms
9
+ [2026-11-11T21:47:36.173Z] POST /v1/messages?beta=true 200 - 103695ms
10
+ [2026-11-11T21:49:20.273Z] POST /v1/messages?beta=true 200 - 14143ms
11
+ [2026-11-11T21:49:35.104Z] POST /v1/messages?beta=true 200 - 14193ms
12
+ [2026-11-11T21:49:50.531Z] POST /v1/messages?beta=true 200 - 5066ms
13
+ [2026-11-11T21:49:57.358Z] POST /v1/messages?beta=true 200 - 8852ms
14
+ [2026-11-11T21:50:08.471Z] POST /v1/messages?beta=true 200 - 5197ms
15
+ [2026-11-11T21:50:13.745Z] POST /v1/messages?beta=true 200 - 21746ms
16
+ [2026-11-11T21:50:36.016Z] POST /v1/messages?beta=true 200 - 4785ms
17
+ [2026-11-11T21:50:41.304Z] POST /v1/messages?beta=true 200 - 10072ms
18
+ [2026-11-11 21:50:51.578][22][warning][main] [source/server/server.cc:981] caught ENVOY_SIGTERM
v2-models-effort/runs/20261111-214430-fragrant-meadow/git-diff.patch ADDED
The diff for this file is too large to render. See raw diff
 
v2-models-effort/runs/20261111-214430-fragrant-meadow/git-sha.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 8422439f49db061ed5b56e9b883ef244807898f8
v2-models-effort/runs/20261111-214430-fragrant-meadow/manifest.json ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2026-11-11T21:44:30Z",
3
+ "completed_at": "2026-11-11T21:50:51Z",
4
+ "exit_code": 0,
5
+ "oom_killed": false,
6
+ "condition": {
7
+ "name": "source-python_unit-tests_source-integration-tests_effort-low_model-claude-fable-5-2",
8
+ "source_language": "python",
9
+ "target_language": "javascript",
10
+ "include_unit_tests": true,
11
+ "include_source_integration_tests": true,
12
+ "include_target_integration_tests": false,
13
+ "effort": "low",
14
+ "model": "claude-fable-5-2"
15
+ },
16
+ "derivation": {
17
+ "gbnf_commit": "13f1aca495d11e160fffd68c4ba299a2415909d8"
18
+ },
19
+ "reference_implementation": {
20
+ "included": [
21
+ "python/.gitignore",
22
+ "python/MANIFEST.in",
23
+ "python/Makefile",
24
+ "python/README.md",
25
+ "python/gbnf/GBNF.py",
26
+ "python/gbnf/__init__.py",
27
+ "python/gbnf/grammar_graph/__init__.py",
28
+ "python/gbnf/grammar_graph/colorize.py",
29
+ "python/gbnf/grammar_graph/colorize_test.py",
30
+ "python/gbnf/grammar_graph/get_input_as_code_points.py",
31
+ "python/gbnf/grammar_graph/get_input_as_code_points_test.py",
32
+ "python/gbnf/grammar_graph/get_parent_stack_id.py",
33
+ "python/gbnf/grammar_graph/get_parent_stack_id_test.py",
34
+ "python/gbnf/grammar_graph/get_serialized_rule_key.py",
35
+ "python/gbnf/grammar_graph/get_serialized_rule_key_test.py",
36
+ "python/gbnf/grammar_graph/grammar_graph_types.py",
37
+ "python/gbnf/grammar_graph/graph.py",
38
+ "python/gbnf/grammar_graph/graph_node.py",
39
+ "python/gbnf/grammar_graph/graph_node_test.py",
40
+ "python/gbnf/grammar_graph/graph_pointer.py",
41
+ "python/gbnf/grammar_graph/graph_pointer_test.py",
42
+ "python/gbnf/grammar_graph/graph_test.py",
43
+ "python/gbnf/grammar_graph/parse_state.py",
44
+ "python/gbnf/grammar_graph/parse_state_test.py",
45
+ "python/gbnf/grammar_graph/pointers.py",
46
+ "python/gbnf/grammar_graph/print.py",
47
+ "python/gbnf/grammar_graph/print_test.py",
48
+ "python/gbnf/grammar_graph/rule_ref.py",
49
+ "python/gbnf/grammar_graph/rule_ref_test.py",
50
+ "python/gbnf/grammar_graph/type_guards.py",
51
+ "python/gbnf/grammar_graph/type_guards_test.py",
52
+ "python/gbnf/grammar_parser/__init__.py",
53
+ "python/gbnf/grammar_parser/build_rule_stack.py",
54
+ "python/gbnf/grammar_parser/build_rule_stack_test.py",
55
+ "python/gbnf/rules_builder/__init__.py",
56
+ "python/gbnf/rules_builder/is_word_char.py",
57
+ "python/gbnf/rules_builder/is_word_char_test.py",
58
+ "python/gbnf/rules_builder/parse_char.py",
59
+ "python/gbnf/rules_builder/parse_char_test.py",
60
+ "python/gbnf/rules_builder/parse_name.py",
61
+ "python/gbnf/rules_builder/parse_name_test.py",
62
+ "python/gbnf/rules_builder/parse_space.py",
63
+ "python/gbnf/rules_builder/parse_space_test.py",
64
+ "python/gbnf/rules_builder/rules_builder.py",
65
+ "python/gbnf/rules_builder/rules_builder_test.py",
66
+ "python/gbnf/rules_builder/rules_builder_types.py",
67
+ "python/gbnf/rules_builder/symbol_ids.py",
68
+ "python/gbnf/utils/__init__.py",
69
+ "python/gbnf/utils/errors/__init__.py",
70
+ "python/gbnf/utils/errors/build_error_position.py",
71
+ "python/gbnf/utils/errors/build_error_position_test.py",
72
+ "python/gbnf/utils/errors/errors_types.py",
73
+ "python/gbnf/utils/errors/get_input_as_string.py",
74
+ "python/gbnf/utils/errors/get_input_as_string_test.py",
75
+ "python/gbnf/utils/errors/grammar_parse_error.py",
76
+ "python/gbnf/utils/errors/grammar_parse_error_test.py",
77
+ "python/gbnf/utils/errors/input_parse_error.py",
78
+ "python/gbnf/utils/errors/input_parse_error_test.py",
79
+ "python/gbnf/utils/is_point_in_range.py",
80
+ "python/gbnf/utils/is_point_in_range_test.py",
81
+ "python/gbnf/utils/validate_non_empty.py",
82
+ "python/pyproject.toml",
83
+ "python/requirements.txt",
84
+ "python/tests/generated/iteration/iteration_test.py",
85
+ "python/tests/generated/iteration/iteration_with_additional_strings_test.py",
86
+ "python/tests/generated/iteration/iteration_with_an_initial_string_test.py",
87
+ "python/tests/generated/validation/validate_grammar_test.py",
88
+ "python/tests/generated/validation/validate_input_test.py",
89
+ "python/uv.lock"
90
+ ]
91
+ },
92
+ "sandbox": {
93
+ "image_id": "sha256:90f87ffdea5ca8edc25424506b4d45721e7ae8dcad3d82aa9eecdd219b7708d6"
94
+ },
95
+ "harness": {
96
+ "commit": "8422439f49db061ed5b56e9b883ef244807898f8",
97
+ "dirty": true
98
+ }
99
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/memory.jsonl ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"time": 1794433470.4889321, "rss": 24653824, "processes": 2}
2
+ {"time": 1794433475.5017717, "rss": 147599360, "processes": 5}
3
+ {"time": 1794433480.515477, "rss": 147447808, "processes": 5}
4
+ {"time": 1794433485.5258312, "rss": 400936960, "processes": 6}
5
+ {"time": 1794433490.5382075, "rss": 412086272, "processes": 6}
6
+ {"time": 1794433495.5511174, "rss": 430649344, "processes": 6}
7
+ {"time": 1794433500.5642323, "rss": 429645824, "processes": 6}
8
+ {"time": 1794433505.5781078, "rss": 428163072, "processes": 6}
9
+ {"time": 1794433510.5912294, "rss": 419749888, "processes": 6}
10
+ {"time": 1794433515.6055596, "rss": 418459648, "processes": 6}
11
+ {"time": 1794433520.6205182, "rss": 418185216, "processes": 6}
12
+ {"time": 1794433525.6343303, "rss": 417665024, "processes": 6}
13
+ {"time": 1794433530.648951, "rss": 417169408, "processes": 6}
14
+ {"time": 1794433535.6632133, "rss": 417153024, "processes": 6}
15
+ {"time": 1794433540.677995, "rss": 417038336, "processes": 6}
16
+ {"time": 1794433545.6927946, "rss": 416870400, "processes": 6}
17
+ {"time": 1794433550.708167, "rss": 416542720, "processes": 6}
18
+ {"time": 1794433555.7232313, "rss": 416768000, "processes": 6}
19
+ {"time": 1794433560.7377863, "rss": 417021952, "processes": 6}
20
+ {"time": 1794433565.7521656, "rss": 416526336, "processes": 6}
21
+ {"time": 1794433570.7664685, "rss": 422858752, "processes": 6}
22
+ {"time": 1794433575.7809844, "rss": 422502400, "processes": 6}
23
+ {"time": 1794433580.7954123, "rss": 421625856, "processes": 6}
24
+ {"time": 1794433585.8102984, "rss": 419205120, "processes": 6}
25
+ {"time": 1794433590.824539, "rss": 417808384, "processes": 6}
26
+ {"time": 1794433595.839248, "rss": 417779712, "processes": 6}
27
+ {"time": 1794433600.8537602, "rss": 417464320, "processes": 6}
28
+ {"time": 1794433605.8689892, "rss": 417624064, "processes": 6}
29
+ {"time": 1794433610.883709, "rss": 417267712, "processes": 6}
30
+ {"time": 1794433615.8986654, "rss": 417792000, "processes": 6}
31
+ {"time": 1794433620.9138985, "rss": 416899072, "processes": 6}
32
+ {"time": 1794433625.9291172, "rss": 415956992, "processes": 6}
33
+ {"time": 1794433630.9435859, "rss": 415727616, "processes": 6}
34
+ {"time": 1794433635.958528, "rss": 416116736, "processes": 6}
35
+ {"time": 1794433640.9728837, "rss": 416403456, "processes": 6}
36
+ {"time": 1794433645.9876628, "rss": 415842304, "processes": 6}
37
+ {"time": 1794433651.002623, "rss": 416858112, "processes": 6}
38
+ {"time": 1794433656.0172708, "rss": 416079872, "processes": 6}
39
+ {"time": 1794433661.0320191, "rss": 453791744, "processes": 6}
40
+ {"time": 1794433666.0464506, "rss": 453300224, "processes": 6}
41
+ {"time": 1794433671.0607305, "rss": 453120000, "processes": 6}
42
+ {"time": 1794433676.0758939, "rss": 449896448, "processes": 6}
43
+ {"time": 1794433681.0899942, "rss": 424529920, "processes": 6}
44
+ {"time": 1794433686.108639, "rss": 424058880, "processes": 6}
45
+ {"time": 1794433691.1232927, "rss": 422199296, "processes": 6}
46
+ {"time": 1794433696.1379418, "rss": 421322752, "processes": 6}
47
+ {"time": 1794433701.1528432, "rss": 420495360, "processes": 6}
48
+ {"time": 1794433706.1678307, "rss": 419979264, "processes": 6}
49
+ {"time": 1794433711.1826844, "rss": 419979264, "processes": 6}
50
+ {"time": 1794433716.197176, "rss": 420241408, "processes": 6}
51
+ {"time": 1794433721.2118044, "rss": 419418112, "processes": 6}
52
+ {"time": 1794433726.2266214, "rss": 419332096, "processes": 6}
53
+ {"time": 1794433731.2413292, "rss": 419315712, "processes": 6}
54
+ {"time": 1794433736.255258, "rss": 419315712, "processes": 6}
55
+ {"time": 1794433741.2698836, "rss": 419835904, "processes": 6}
56
+ {"time": 1794433746.2844667, "rss": 419512320, "processes": 6}
57
+ {"time": 1794433751.2991893, "rss": 419434496, "processes": 6}
58
+ {"time": 1794433756.313875, "rss": 419508224, "processes": 6}
59
+ {"time": 1794433761.328287, "rss": 491966464, "processes": 6}
60
+ {"time": 1794433766.3428683, "rss": 490377216, "processes": 6}
61
+ {"time": 1794433771.3582811, "rss": 456945664, "processes": 6}
62
+ {"time": 1794433776.3727274, "rss": 470147072, "processes": 6}
63
+ {"time": 1794433781.3866544, "rss": 465334272, "processes": 6}
64
+ {"time": 1794433786.4012554, "rss": 461369344, "processes": 6}
65
+ {"time": 1794433791.4164572, "rss": 481361920, "processes": 6}
66
+ {"time": 1794433796.4315376, "rss": 1215127552, "processes": 6}
67
+ {"time": 1794433801.446253, "rss": 483012608, "processes": 6}
68
+ {"time": 1794433806.467779, "rss": 1077223424, "processes": 6}
69
+ {"time": 1794433811.481916, "rss": 484290560, "processes": 6}
70
+ {"time": 1794433816.4961386, "rss": 485703680, "processes": 6}
71
+ {"time": 1794433821.5104642, "rss": 485265408, "processes": 6}
72
+ {"time": 1794433826.525486, "rss": 481705984, "processes": 6}
73
+ {"time": 1794433831.5366752, "rss": 479334400, "processes": 6}
74
+ {"time": 1794433836.5464625, "rss": 489525248, "processes": 6}
75
+ {"time": 1794433841.5574312, "rss": 493383680, "processes": 6}
76
+ {"time": 1794433846.5702002, "rss": 490106880, "processes": 6}
77
+ {"time": 1794433851.5827103, "rss": 213237760, "processes": 6}
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GBNF (TypeScript)
2
+
3
+ TypeScript port of the Python `gbnf` package. Sources live in `gbnf/`, mirroring the Python module layout
4
+ (`gbnf/grammar_graph/graph.ts` ↔ `gbnf/grammar_graph/graph.py`, …). Functions keep their snake_case names and
5
+ also have camelCase aliases.
6
+
7
+ ```ts
8
+ import { GBNF, InputParseError } from 'gbnf';
9
+
10
+ let state = GBNF('root ::= "foo" | "bar"');
11
+ state = state.add('f'); // or state('f')
12
+ console.log([...state]); // [RuleChar { type: 'RuleChar', value: [111] }]
13
+ ```
14
+
15
+ Run tests with `vitest run`.
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/GBNF.ts ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Graph } from './grammar_graph/graph.ts';
2
+ import { ParseState } from './grammar_graph/parse_state.ts';
3
+ import { build_rule_stack } from './grammar_parser/build_rule_stack.ts';
4
+ import { GrammarParseError, RulesBuilder } from './rules_builder/index.ts';
5
+
6
+ export function GBNF(grammar: string, initial_string = ''): ParseState {
7
+ if (typeof grammar !== 'string') {
8
+ throw new Error('grammar must be a string');
9
+ }
10
+
11
+ if (typeof initial_string !== 'string') {
12
+ throw new Error('input must be a string');
13
+ }
14
+
15
+ const rules_builder = new RulesBuilder(grammar);
16
+ const { rules, symbol_ids } = rules_builder;
17
+ if (rules.length === 0) {
18
+ throw new GrammarParseError(grammar, 0, 'No rules were found');
19
+ }
20
+ const root_id = symbol_ids.get('root');
21
+ if (root_id === undefined) {
22
+ throw new GrammarParseError(grammar, 0, "Grammar does not contain a 'root' symbol");
23
+ }
24
+
25
+ const stacked_rules = rules.map((rule) => build_rule_stack(rule));
26
+ const graph = new Graph(grammar, stacked_rules, root_id);
27
+ return new ParseState(graph, graph.add(initial_string));
28
+ }
29
+
30
+ export default GBNF;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/colorize.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const Color = {
2
+ BLUE: '\x1b[34m',
3
+ CYAN: '\x1b[36m',
4
+ GREEN: '\x1b[32m',
5
+ RED: '\x1b[31m',
6
+ GRAY: '\x1b[90m',
7
+ YELLOW: '\x1b[33m',
8
+ } as const;
9
+
10
+ export function colorize(text: string | number, color: string): string {
11
+ return `${color}${text}`;
12
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/get_input_as_code_points.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ValidInput } from './grammar_graph_types.ts';
2
+
3
+ export function get_code_point(char: string): number {
4
+ const code_point = char.codePointAt(0);
5
+ if (code_point === undefined) {
6
+ throw new Error(`Could not get code point for character: ${char}`);
7
+ }
8
+ return code_point;
9
+ }
10
+
11
+ export function get_input_as_code_points(src: ValidInput): number[] {
12
+ if (typeof src === 'number' && Number.isInteger(src)) {
13
+ return [src];
14
+ }
15
+
16
+ if (Array.isArray(src)) {
17
+ for (const c of src) {
18
+ if (typeof c !== 'number' || !Number.isInteger(c)) {
19
+ throw new Error(`code_point must be an integer for ${c} if src is a list`);
20
+ }
21
+ }
22
+ return src;
23
+ }
24
+
25
+ if (typeof src === 'string') {
26
+ return Array.from(src, get_code_point);
27
+ }
28
+
29
+ throw new Error(`Invalid input type: ${typeof src}`);
30
+ }
31
+
32
+ export const getCodePoint = get_code_point;
33
+ export const getInputAsCodePoints = get_input_as_code_points;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/get_parent_stack_id.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Color } from './colorize.ts';
2
+ import type { GraphPointer } from './graph_pointer.ts';
3
+
4
+ export function get_parent_stack_id(
5
+ pointer: GraphPointer<any>,
6
+ col: (text: string | number, color: string) => string,
7
+ ): string {
8
+ const stack_ids: string[] = [];
9
+ let parent: GraphPointer<any> | null | undefined = pointer.parent;
10
+ while (parent) {
11
+ stack_ids.push(`${parent.node.meta.stackId},${parent.node.meta.pathId},${parent.node.meta.stepId}`);
12
+ parent = parent.parent;
13
+ }
14
+ const arrow = col('<-', Color.GRAY);
15
+ return stack_ids.map((stack_id) => col(stack_id, Color.RED)).join(arrow);
16
+ }
17
+
18
+ export const getParentStackId = get_parent_stack_id;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/get_serialized_rule_key.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { py_json, py_repr } from '../utils/py.ts';
2
+ import { RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from './grammar_graph_types.ts';
3
+ import { is_rule_char, is_rule_char_exclude, is_rule_end, is_rule_ref } from './type_guards.ts';
4
+
5
+ export const KEY_TRANSLATION = new Map<unknown, number>([
6
+ [RuleEnd, 0],
7
+ [RuleChar, 1],
8
+ [RuleCharExclude, 2],
9
+ ]);
10
+
11
+ export function get_serialized_rule_key(rule: UnresolvedRule): string {
12
+ if (is_rule_end(rule)) {
13
+ return `${KEY_TRANSLATION.get(RuleEnd)}`;
14
+ }
15
+
16
+ if (is_rule_char(rule)) {
17
+ return `${KEY_TRANSLATION.get(RuleChar)}-${py_json((rule as RuleChar).value)}`;
18
+ }
19
+
20
+ if (is_rule_char_exclude(rule)) {
21
+ return `${KEY_TRANSLATION.get(RuleCharExclude)}-${py_json((rule as RuleCharExclude).value)}`;
22
+ }
23
+
24
+ if (is_rule_ref(rule)) {
25
+ return `3-${(rule as { value: number }).value}`;
26
+ }
27
+
28
+ throw new Error(`Unknown rule type: ${py_repr(rule)}`);
29
+ }
30
+
31
+ export const getSerializedRuleKey = get_serialized_rule_key;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/grammar_graph_types.ts ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { py_json } from '../utils/py.ts';
2
+ import type { GraphPointer } from './graph_pointer.ts';
3
+ import type { Pointers } from './pointers.ts';
4
+ import { RuleRef } from './rule_ref.ts';
5
+
6
+ export { RuleRef };
7
+
8
+ export interface PrintOpts {
9
+ pointers?: Iterable<GraphPointer>;
10
+ colorize: (text: string | number, color: string) => string;
11
+ show_position?: boolean;
12
+ showPosition?: boolean;
13
+ }
14
+
15
+ export type Range = [number, number];
16
+
17
+ const values_equal = (a: unknown, b: unknown): boolean => {
18
+ if (Array.isArray(a) && Array.isArray(b)) {
19
+ return a.length === b.length && a.every((v, i) => values_equal(v, b[i]));
20
+ }
21
+ return a === b;
22
+ };
23
+
24
+ // Accepts either a positional value or a python style `{ value }` keyword object.
25
+ const unwrap = <T>(value: T | { value: T }): T =>
26
+ value !== null && typeof value === 'object' && !Array.isArray(value) && 'value' in value ? value.value : value;
27
+
28
+ export class Rule {
29
+ type: string;
30
+
31
+ constructor() {
32
+ this.type = this.constructor.name;
33
+ }
34
+
35
+ equals(other: unknown): boolean {
36
+ return other instanceof this.constructor;
37
+ }
38
+
39
+ toString(): string {
40
+ return `${this.constructor.name}()`;
41
+ }
42
+
43
+ get __dict__(): Record<string, unknown> {
44
+ return {
45
+ type: this.constructor.name,
46
+ };
47
+ }
48
+ }
49
+
50
+ export class RuleWithValue<T = unknown> extends Rule {
51
+ value: T;
52
+
53
+ constructor(value: T | { value: T }) {
54
+ super();
55
+ this.value = unwrap(value);
56
+ }
57
+
58
+ equals(other: unknown): boolean {
59
+ return other instanceof this.constructor && values_equal(this.value, (other as RuleWithValue).value);
60
+ }
61
+
62
+ toString(): string {
63
+ return `${this.constructor.name}(value=${py_json(this.value)})`;
64
+ }
65
+
66
+ get __dict__(): Record<string, unknown> {
67
+ return {
68
+ type: this.constructor.name,
69
+ value: this.value,
70
+ };
71
+ }
72
+ }
73
+
74
+ export class RuleWithListOfIntsOrRanges extends RuleWithValue<(number | Range)[]> {
75
+ constructor(value: (number | Range | number[])[] | { value: (number | Range | number[])[] } = []) {
76
+ super(value as (number | Range)[]);
77
+ this.value = [...this.value];
78
+ }
79
+ }
80
+
81
+ export class RuleChar extends RuleWithListOfIntsOrRanges {}
82
+
83
+ export class RuleCharExclude extends RuleWithListOfIntsOrRanges {}
84
+
85
+ export class RuleEnd extends Rule {}
86
+
87
+ export type UnresolvedRule = RuleChar | RuleCharExclude | RuleRef | RuleEnd;
88
+
89
+ // ValidInput can either be a string, or a number indicating a code point.
90
+ // It CANNOT be a number representing a number; a number intended as input (like "8")
91
+ // should be passed in as a string.
92
+ export type ValidInput = string | number | number[];
93
+
94
+ // RuleRefs should never be exposed to the end user.
95
+ export type ResolvedRule = RuleCharExclude | RuleChar | RuleEnd;
96
+
97
+ export type ResolvedGraphPointer = GraphPointer<ResolvedRule>;
98
+
99
+ export type { Pointers };
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/graph.ts ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { InputParseError } from '../utils/errors/index.ts';
2
+ import { is_point_in_range } from '../utils/is_point_in_range.ts';
3
+ import { py_repr } from '../utils/py.ts';
4
+ import { colorize } from './colorize.ts';
5
+ import { get_input_as_code_points } from './get_input_as_code_points.ts';
6
+ import { get_serialized_rule_key } from './get_serialized_rule_key.ts';
7
+ import type { ResolvedGraphPointer, UnresolvedRule, ValidInput } from './grammar_graph_types.ts';
8
+ import { GraphNode } from './graph_node.ts';
9
+ import { GraphPointer } from './graph_pointer.ts';
10
+ import { Pointers } from './pointers.ts';
11
+ import type { RuleRef } from './rule_ref.ts';
12
+ import { is_range, is_rule_char, is_rule_char_exclude, is_rule_end, is_rule_ref } from './type_guards.ts';
13
+
14
+ export type RootNode = Map<number, GraphNode>;
15
+
16
+ const pointers_length = (pointers: unknown): number | undefined => {
17
+ const p = pointers as { length?: unknown; size?: unknown };
18
+ if (typeof p.length === 'number') {
19
+ return p.length;
20
+ }
21
+ if (typeof p.size === 'number') {
22
+ return p.size;
23
+ }
24
+ return undefined;
25
+ };
26
+
27
+ export class Graph {
28
+ __roots__: Map<number, RootNode>;
29
+ grammar: string;
30
+ __rootNode__: RootNode | null;
31
+ previous_code_points: number[];
32
+
33
+ constructor(grammar: string, stacked_rules: UnresolvedRule[][][], root_id: number) {
34
+ this.__roots__ = new Map();
35
+ this.grammar = grammar;
36
+ this.previous_code_points = [];
37
+ const rule_refs: RuleRef[] = [];
38
+ const unique_rules: Map<string, UnresolvedRule> = new Map();
39
+
40
+ for (let stack_id = 0; stack_id < stacked_rules.length; stack_id++) {
41
+ const stack = stacked_rules[stack_id];
42
+ const nodes: RootNode = new Map();
43
+ for (let path_id = 0; path_id < stack.length; path_id++) {
44
+ const path = stack[path_id];
45
+ let node: GraphNode | null = null;
46
+ for (let step_id = path.length - 1; step_id >= 0; step_id--) {
47
+ const next_node: GraphNode | null = node;
48
+ const rule = stack[path_id][step_id];
49
+ unique_rules.set(get_serialized_rule_key(rule), rule);
50
+ if (is_rule_ref(rule)) {
51
+ rule_refs.push(rule);
52
+ }
53
+ // rules coming in may be identical but have different references.
54
+ // here, we ensure we always use the same reference for an identical rule.
55
+ // this makes future comparisons easier.
56
+ const unique_rule = unique_rules.get(get_serialized_rule_key(rule));
57
+ if (unique_rule === undefined || unique_rule === null) {
58
+ throw new Error('Could not get unique rule');
59
+ }
60
+ node = new GraphNode(
61
+ unique_rule,
62
+ {
63
+ stackId: stack_id,
64
+ pathId: path_id,
65
+ stepId: step_id,
66
+ },
67
+ next_node,
68
+ );
69
+ }
70
+
71
+ if (node === null) {
72
+ throw new Error('Could not get node');
73
+ }
74
+ nodes.set(path_id, node);
75
+ }
76
+ this.__roots__.set(stack_id, nodes);
77
+ }
78
+
79
+ const root_node = this.__roots__.get(root_id);
80
+ if (root_node === undefined) {
81
+ throw new Error(`Root node not found for value: ${root_id}`);
82
+ }
83
+ this.__rootNode__ = root_node;
84
+
85
+ for (const rule_ref of rule_refs) {
86
+ rule_ref.nodes = new Set(this.__get_root_node__(rule_ref.value).values());
87
+ }
88
+ }
89
+
90
+ get previousCodePoints(): number[] {
91
+ return this.previous_code_points;
92
+ }
93
+
94
+ __get_root_node__(value: number): RootNode {
95
+ const root_node = this.__roots__.get(value);
96
+ if (root_node === undefined) {
97
+ throw new Error(`Root node not found for value: ${value}`);
98
+ }
99
+ return root_node;
100
+ }
101
+
102
+ __get_initial_pointers__(): Pointers {
103
+ const pointers = new Pointers();
104
+
105
+ const root_node = this.__rootNode__;
106
+ if (root_node === null || root_node === undefined) {
107
+ throw new Error('Root node is not defined');
108
+ }
109
+
110
+ for (const [node, parent] of this.__fetch_nodes_for_root_node__(root_node)) {
111
+ const pointer = new GraphPointer(node, parent);
112
+ for (const resolvedPointer of this.__resolve_pointer__(pointer)) {
113
+ pointers.add(resolvedPointer);
114
+ }
115
+ }
116
+ return pointers;
117
+ }
118
+
119
+ __set_valid__(pointers: GraphPointer<any>[], valid: boolean): void {
120
+ for (const pointer of pointers) {
121
+ pointer.valid = valid;
122
+ }
123
+ }
124
+
125
+ __parse__(current_pointers: Pointers, code_point: number): Pointers {
126
+ for (const [rule, graph_pointers] of this.__iterate_over_pointers__(current_pointers)) {
127
+ if (is_rule_char(rule)) {
128
+ let valid = false;
129
+ for (const possible_code_point of rule.value) {
130
+ if (valid) {
131
+ // already matched
132
+ } else if (is_range(possible_code_point)) {
133
+ if (is_point_in_range(code_point, possible_code_point)) {
134
+ valid = true;
135
+ }
136
+ } else if (code_point === possible_code_point) {
137
+ valid = true;
138
+ }
139
+ }
140
+ this.__set_valid__(graph_pointers, valid);
141
+ } else if (is_rule_char_exclude(rule)) {
142
+ let valid = true;
143
+ for (const possible_code_point of rule.value) {
144
+ if (!valid) {
145
+ // already excluded
146
+ } else if (is_range(possible_code_point)) {
147
+ if (is_point_in_range(code_point, possible_code_point)) {
148
+ valid = false;
149
+ }
150
+ } else if (code_point === possible_code_point) {
151
+ valid = false;
152
+ }
153
+ }
154
+ this.__set_valid__(graph_pointers, valid);
155
+ } else if (!is_rule_end(rule)) {
156
+ throw new Error(`Unsupported rule: ${py_repr(rule)}`);
157
+ }
158
+ }
159
+
160
+ // a pointer's id is the sum of its node's id and its parent's id chain.
161
+ // if two pointers share the same id, it means they point to the same node and have identical parent chains.
162
+ // for the purposes of walking the graph, we only need to keep one of them.
163
+ const next_pointers = new Pointers();
164
+ for (const current_pointer of current_pointers) {
165
+ for (const unresolved_next_pointer of current_pointer.fetch_next()) {
166
+ for (const resolved_next_pointer of this.__resolve_pointer__(unresolved_next_pointer)) {
167
+ next_pointers.add(resolved_next_pointer);
168
+ }
169
+ }
170
+ }
171
+ return next_pointers;
172
+ }
173
+
174
+ *__resolve_pointer__(unresolved_pointer: GraphPointer<any>): IterableIterator<ResolvedGraphPointer> {
175
+ for (const resolved_pointer of unresolved_pointer.resolve()) {
176
+ if (is_rule_ref(resolved_pointer.node.rule)) {
177
+ throw new Error('Encountered a reference rule when building pointers to the graph');
178
+ }
179
+ if (is_rule_end(resolved_pointer.node.rule) && resolved_pointer.parent !== null) {
180
+ throw new Error('Encountered an ending rule with a parent when building pointers to the graph');
181
+ }
182
+ yield resolved_pointer;
183
+ }
184
+ }
185
+
186
+ add(src: ValidInput, pointers?: Pointers | null): Pointers {
187
+ if (typeof src !== 'string') {
188
+ throw new Error('src must be a string in graph.add');
189
+ }
190
+ // an empty set of pointers is treated the same as no pointers
191
+ let current: Pointers =
192
+ pointers && pointers_length(pointers) !== 0 ? pointers : this.__get_initial_pointers__();
193
+
194
+ const code_points = get_input_as_code_points(src);
195
+
196
+ for (let code_point_pos = 0; code_point_pos < code_points.length; code_point_pos++) {
197
+ const code_point = code_points[code_point_pos];
198
+ current = this.__parse__(current, code_point);
199
+ if (current.length === 0) {
200
+ throw new InputParseError(code_points, code_point_pos, this.previous_code_points);
201
+ }
202
+ }
203
+ this.previous_code_points.push(...code_points);
204
+ return current;
205
+ }
206
+
207
+ // generator that yields either the node, or if a reference rule, the referenced node
208
+ // we need these function, as distinct from leveraging the logic in GraphPointer,
209
+ // because that needs a rule ref with already defined nodes; this function is used to _set_ those nodes
210
+ *__fetch_nodes_for_root_node__(
211
+ root_nodes: RootNode,
212
+ parent: GraphPointer<any> | null = null,
213
+ ): IterableIterator<[GraphNode, GraphPointer<any> | null]> {
214
+ for (const node of root_nodes.values()) {
215
+ if (is_rule_ref(node.rule)) {
216
+ yield* this.__fetch_nodes_for_root_node__(
217
+ this.__get_root_node__(node.rule.value),
218
+ new GraphPointer(node, parent),
219
+ );
220
+ } else {
221
+ yield [node, parent];
222
+ }
223
+ }
224
+ }
225
+
226
+ print(pointers?: Pointers | { pointers?: Pointers | null; colors?: boolean } | null, colors = false): string {
227
+ if (pointers && !(Symbol.iterator in pointers)) {
228
+ colors = pointers.colors ?? colors;
229
+ pointers = pointers.pointers;
230
+ }
231
+ const nodes: GraphNode[][] = [...this.__roots__.values()].map((root_node) => [...root_node.values()]);
232
+ const print_pointers = (pointers as Pointers | null | undefined) ?? new Pointers();
233
+ const graph_view: string[] = [];
234
+ for (const root_node of nodes) {
235
+ for (const node of root_node) {
236
+ graph_view.push(
237
+ node.print({
238
+ pointers: print_pointers,
239
+ show_position: true,
240
+ colorize: colors ? colorize : (s) => String(s),
241
+ }),
242
+ );
243
+ }
244
+ }
245
+
246
+ return graph_view.join('\n');
247
+ }
248
+
249
+ *__iterate_over_pointers__(
250
+ pointers: Iterable<GraphPointer<any>>,
251
+ ): IterableIterator<[UnresolvedRule, GraphPointer<any>[]]> {
252
+ const seen_rules: Map<UnresolvedRule, GraphPointer<any>[]> = new Map();
253
+ for (const pointer of pointers) {
254
+ const rule = pointer.rule;
255
+ if (is_rule_ref(rule)) {
256
+ throw new Error('Encountered a reference rule in the graph');
257
+ }
258
+
259
+ let seen_rule = seen_rules.get(rule);
260
+ if (seen_rule === undefined) {
261
+ seen_rule = [pointer];
262
+ seen_rules.set(rule, seen_rule);
263
+ }
264
+ seen_rule.push(pointer);
265
+ }
266
+
267
+ yield* seen_rules.entries();
268
+ }
269
+
270
+ getRootNode(value: number): RootNode {
271
+ return this.__get_root_node__(value);
272
+ }
273
+
274
+ getInitialPointers(): Pointers {
275
+ return this.__get_initial_pointers__();
276
+ }
277
+
278
+ iterateOverPointers(pointers: Iterable<GraphPointer<any>>): IterableIterator<[UnresolvedRule, GraphPointer<any>[]]> {
279
+ return this.__iterate_over_pointers__(pointers);
280
+ }
281
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/graph_node.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { PrintOpts, UnresolvedRule } from './grammar_graph_types.ts';
2
+ import { print_graph_node } from './print.ts';
3
+ import type { RuleRef } from './rule_ref.ts';
4
+
5
+ export type { PrintOpts };
6
+
7
+ export interface GraphNodeMeta {
8
+ stackId: number;
9
+ pathId: number;
10
+ stepId: number;
11
+ }
12
+
13
+ export class GraphNode<T extends UnresolvedRule = UnresolvedRule> {
14
+ rule: T;
15
+ next: GraphNode | null;
16
+ meta: GraphNodeMeta;
17
+ #id: string | null = null;
18
+
19
+ constructor(rule: T, meta: GraphNodeMeta | null | undefined, next_node: GraphNode | null = null) {
20
+ this.rule = rule;
21
+ if (meta === null || meta === undefined) {
22
+ throw new Error('Meta is undefined');
23
+ }
24
+ this.meta = meta;
25
+ this.next = next_node ?? null;
26
+ }
27
+
28
+ get id(): string {
29
+ if (this.#id === null) {
30
+ this.#id = `${this.meta.stackId},${this.meta.pathId},${this.meta.stepId}`;
31
+ }
32
+ return this.#id;
33
+ }
34
+
35
+ print(opts: PrintOpts): string {
36
+ return print_graph_node(this)(opts);
37
+ }
38
+
39
+ toString(): string {
40
+ return `<GraphNode ${this.id} ${this.rule}>`;
41
+ }
42
+ }
43
+
44
+ export type GraphNodeRuleRef = GraphNode<RuleRef>;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/graph_pointer.ts ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { PrintOpts, ResolvedGraphPointer, UnresolvedRule } from './grammar_graph_types.ts';
2
+ import { GraphNode } from './graph_node.ts';
3
+ import { print_graph_pointer } from './print.ts';
4
+ import type { RuleRef } from './rule_ref.ts';
5
+ import {
6
+ is_graph_pointer_rule_char,
7
+ is_graph_pointer_rule_char_exclude,
8
+ is_graph_pointer_rule_end,
9
+ is_graph_pointer_rule_ref,
10
+ is_rule_end,
11
+ } from './type_guards.ts';
12
+
13
+ export type GraphPointerKey = string;
14
+
15
+ export class GraphPointer<T extends UnresolvedRule = UnresolvedRule> {
16
+ node: GraphNode<T>;
17
+ parent: GraphPointer<any> | null;
18
+ id: string;
19
+ #valid: boolean | null = null;
20
+
21
+ constructor(node: GraphNode<T>, parent: GraphPointer<any> | null = null) {
22
+ if (node === null || node === undefined) {
23
+ throw new Error('Node is undefined');
24
+ }
25
+ this.node = node;
26
+ this.parent = parent ?? null;
27
+ this.id = parent ? `${parent.id}-${node.id}` : node.id;
28
+ }
29
+
30
+ get rule(): T {
31
+ return this.node.rule;
32
+ }
33
+
34
+ get valid(): boolean | null {
35
+ return this.#valid;
36
+ }
37
+
38
+ set valid(valid: boolean | null) {
39
+ this.#valid = valid;
40
+ }
41
+
42
+ print(opts: PrintOpts): string {
43
+ return print_graph_pointer(this)(opts);
44
+ }
45
+
46
+ // Resolve the graph pointer.
47
+ // `resolved` indicates whether the pointer has already been resolved.
48
+ *resolve(resolved = false): IterableIterator<ResolvedGraphPointer> {
49
+ if (is_graph_pointer_rule_ref(this)) {
50
+ if (resolved) {
51
+ if (!this.node.next) {
52
+ throw new Error(`No next node: ${this.node}`);
53
+ }
54
+ yield* new GraphPointer(this.node.next, this.parent).resolve();
55
+ } else {
56
+ for (const node of (this.node.rule as unknown as RuleRef).nodes) {
57
+ yield* new GraphPointer(node, this).resolve();
58
+ }
59
+ }
60
+ } else if (is_graph_pointer_rule_end(this)) {
61
+ if (!this.parent) {
62
+ yield this as unknown as ResolvedGraphPointer;
63
+ } else {
64
+ yield* this.parent.resolve(true);
65
+ }
66
+ } else if (is_graph_pointer_rule_char(this) || is_graph_pointer_rule_char_exclude(this)) {
67
+ yield this as unknown as ResolvedGraphPointer;
68
+ } else {
69
+ throw new Error(`Unknown rule: ${(this as GraphPointer<any>).node.rule}`);
70
+ }
71
+ }
72
+
73
+ // Fetch the next resolved graph pointers.
74
+ *fetch_next(): IterableIterator<ResolvedGraphPointer> {
75
+ // If this pointer is invalid, then we don't return any new pointers
76
+ if (!this.valid) {
77
+ return;
78
+ }
79
+
80
+ // If this pointer is an end node, we return the parent's next node.
81
+ // If no parent exists, we return nothing, since it's the end of the line.
82
+ if (is_rule_end(this.node.rule)) {
83
+ if (this.parent) {
84
+ yield* this.parent.fetch_next();
85
+ }
86
+ } else {
87
+ if (!this.node.next) {
88
+ throw new Error(`No next node: ${this.node}`);
89
+ }
90
+ const pointer = new GraphPointer(this.node.next, this.parent);
91
+ yield* pointer.resolve();
92
+ }
93
+ }
94
+
95
+ fetchNext(): IterableIterator<ResolvedGraphPointer> {
96
+ return this.fetch_next();
97
+ }
98
+
99
+ toString(): string {
100
+ return `<GraphPointer ${this.id} ${this.node}>`;
101
+ }
102
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/index.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export * from './colorize.ts';
2
+ export * from './get_input_as_code_points.ts';
3
+ export * from './get_parent_stack_id.ts';
4
+ export * from './get_serialized_rule_key.ts';
5
+ export * from './grammar_graph_types.ts';
6
+ export * from './graph.ts';
7
+ export * from './graph_node.ts';
8
+ export * from './graph_pointer.ts';
9
+ export * from './parse_state.ts';
10
+ export * from './pointers.ts';
11
+ export * from './print.ts';
12
+ export * from './type_guards.ts';
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/parse_state.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ResolvedRule } from './grammar_graph_types.ts';
2
+ import type { Graph } from './graph.ts';
3
+ import type { Pointers } from './pointers.ts';
4
+
5
+ // Instances are callable: `state("foo")` is equivalent to `state.add("foo")`.
6
+ export interface ParseState {
7
+ (text: string): ParseState;
8
+ }
9
+
10
+ export class ParseState {
11
+ __graph__!: Graph;
12
+ __pointers__!: Pointers;
13
+
14
+ constructor(graph: Graph, pointers: Pointers) {
15
+ const self = ((text: string): ParseState => self.add(text)) as unknown as ParseState;
16
+ Object.setPrototypeOf(self, new.target.prototype);
17
+ for (const [key, value] of [
18
+ ['__graph__', graph],
19
+ ['__pointers__', pointers],
20
+ ] as const) {
21
+ Object.defineProperty(self, key, { value, writable: true, configurable: true, enumerable: false });
22
+ }
23
+ return self;
24
+ }
25
+
26
+ *[Symbol.iterator](): IterableIterator<ResolvedRule> {
27
+ yield* this.rules();
28
+ }
29
+
30
+ *rules(): IterableIterator<ResolvedRule> {
31
+ const rules = new Set<string>();
32
+ for (const pointer of this.__pointers__) {
33
+ const rule = pointer.rule as ResolvedRule;
34
+ const key = JSON.stringify(rule.__dict__);
35
+ if (!rules.has(key)) {
36
+ rules.add(key);
37
+ yield rule;
38
+ }
39
+ }
40
+ }
41
+
42
+ add(text: string): ParseState {
43
+ if (typeof text !== 'string') {
44
+ throw new Error('input text must be of type string');
45
+ }
46
+ const pointers = this.__graph__.add(text, this.__pointers__);
47
+ return new ParseState(this.__graph__, pointers);
48
+ }
49
+
50
+ __add__(text: string): ParseState {
51
+ return this.add(text);
52
+ }
53
+
54
+ __call__(text: string): ParseState {
55
+ return this.add(text);
56
+ }
57
+
58
+ get size(): number {
59
+ return [...this.rules()].length;
60
+ }
61
+
62
+ get grammar(): string {
63
+ return this.__graph__.grammar;
64
+ }
65
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/pointers.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphPointer } from './graph_pointer.ts';
2
+
3
+ export class Pointers {
4
+ __pointers__: Map<string, GraphPointer<any>> = new Map();
5
+
6
+ constructor(...pointers: GraphPointer<any>[]) {
7
+ for (const pointer of pointers) {
8
+ this.add(pointer);
9
+ }
10
+ }
11
+
12
+ toString(): string {
13
+ return `<Pointers [${[...this].map((p) => String(p.node.rule)).join(', ')}]>`;
14
+ }
15
+
16
+ add(pointer: GraphPointer<any>): void {
17
+ this.__pointers__.set(pointer.id, pointer);
18
+ }
19
+
20
+ has(pointer: GraphPointer<any>): boolean {
21
+ for (const p of this.__pointers__.values()) {
22
+ if (p === pointer) {
23
+ return true;
24
+ }
25
+ }
26
+ return false;
27
+ }
28
+
29
+ *[Symbol.iterator](): IterableIterator<GraphPointer<any>> {
30
+ yield* this.__pointers__.values();
31
+ }
32
+
33
+ get length(): number {
34
+ return this.__pointers__.size;
35
+ }
36
+
37
+ get size(): number {
38
+ return this.__pointers__.size;
39
+ }
40
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/print.ts ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Color } from './colorize.ts';
2
+ import { get_parent_stack_id } from './get_parent_stack_id.ts';
3
+ import type { PrintOpts } from './grammar_graph_types.ts';
4
+ import type { GraphNode } from './graph_node.ts';
5
+ import type { GraphPointer } from './graph_pointer.ts';
6
+ import { is_range, is_rule_char, is_rule_ref } from './type_guards.ts';
7
+
8
+ export function print_graph_pointer(pointer: GraphPointer<any>): (opts: PrintOpts) => string {
9
+ return (opts: PrintOpts): string => {
10
+ const col = opts.colorize;
11
+ return col(`*${get_parent_stack_id(pointer, col)}`, Color.RED);
12
+ };
13
+ }
14
+
15
+ export function print_graph_node(node: GraphNode<any>): (opts: PrintOpts) => string {
16
+ return (opts: PrintOpts): string => {
17
+ const pointers = opts.pointers;
18
+ const col = opts.colorize;
19
+ const show_position = opts.show_position ?? opts.showPosition ?? false;
20
+ const rule = node.rule;
21
+ const parts: string[] = [];
22
+ if (show_position) {
23
+ parts.push(col('{', Color.BLUE), col(node.id, Color.GRAY), col('}', Color.BLUE));
24
+ }
25
+
26
+ if (is_rule_char(rule)) {
27
+ parts.push(
28
+ col('[', Color.GRAY),
29
+ col(
30
+ rule.value
31
+ .map((v) => (is_range(v) ? v.map((val) => col(get_char(val), Color.YELLOW)).join('') : get_char(v)))
32
+ .join(''),
33
+ Color.YELLOW,
34
+ ),
35
+ col(']', Color.GRAY),
36
+ );
37
+ } else if (is_rule_ref(rule)) {
38
+ parts.push(col('Ref(', Color.GRAY), col(rule.value, Color.GREEN), col(')', Color.GRAY));
39
+ } else {
40
+ parts.push(col(rule.type, Color.YELLOW));
41
+ }
42
+
43
+ if (pointers) {
44
+ for (const pointer of pointers) {
45
+ const pointer_parts: string[] = [];
46
+ if (pointer.node === node) {
47
+ pointer_parts.push(pointer.print(opts));
48
+ }
49
+
50
+ if (pointer_parts.length > 0) {
51
+ parts.push(col('[', Color.GRAY), col(pointer_parts.join(''), Color.YELLOW), col(']', Color.GRAY));
52
+ }
53
+ }
54
+ }
55
+
56
+ const parts_to_return = [parts.join('')];
57
+ if (node.next) {
58
+ parts_to_return.push(node.next.print(opts));
59
+ }
60
+
61
+ return parts_to_return.join(col('-> ', Color.GRAY));
62
+ };
63
+ }
64
+
65
+ export function get_char(char_code: number): string {
66
+ const char = String.fromCodePoint(char_code);
67
+ if (char === '\n') {
68
+ return '\\n';
69
+ }
70
+ return char;
71
+ }
72
+
73
+ export const printGraphPointer = print_graph_pointer;
74
+ export const printGraphNode = print_graph_node;
75
+ export const getChar = get_char;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/rule_ref.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GraphNode } from './graph_node.ts';
2
+
3
+ export class RuleRef {
4
+ #nodes: Set<GraphNode> | null = null;
5
+ value: number;
6
+
7
+ constructor(value: number | { value: number }) {
8
+ this.value = value !== null && typeof value === 'object' ? value.value : value;
9
+ }
10
+
11
+ get nodes(): Set<GraphNode> {
12
+ if (this.#nodes === null || this.#nodes === undefined) {
13
+ throw new Error('Nodes are not set');
14
+ }
15
+ return this.#nodes;
16
+ }
17
+
18
+ set nodes(nodes: Set<GraphNode>) {
19
+ this.#nodes = nodes;
20
+ }
21
+
22
+ equals(other: unknown): boolean {
23
+ return other instanceof RuleRef && this.value === other.value;
24
+ }
25
+
26
+ toString(): string {
27
+ return `RuleRef(value=${this.value})`;
28
+ }
29
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_graph/type_guards.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { type Range, RuleChar, RuleCharExclude, RuleEnd } from './grammar_graph_types.ts';
2
+ import type { GraphPointer } from './graph_pointer.ts';
3
+ import { RuleRef } from './rule_ref.ts';
4
+
5
+ export function is_rule(rule: unknown): rule is RuleChar | RuleCharExclude | RuleEnd | RuleRef {
6
+ return (
7
+ rule instanceof RuleChar || rule instanceof RuleCharExclude || rule instanceof RuleEnd || rule instanceof RuleRef
8
+ );
9
+ }
10
+
11
+ export function is_rule_ref(rule: unknown): rule is RuleRef {
12
+ return rule instanceof RuleRef;
13
+ }
14
+
15
+ export function is_rule_end(rule: unknown): rule is RuleEnd {
16
+ return rule instanceof RuleEnd;
17
+ }
18
+
19
+ export function is_rule_char(rule: unknown): rule is RuleChar {
20
+ return rule instanceof RuleChar;
21
+ }
22
+
23
+ export function is_rule_char_exclude(rule: unknown): rule is RuleCharExclude {
24
+ return rule instanceof RuleCharExclude;
25
+ }
26
+
27
+ export function is_range(inpt: unknown): inpt is Range {
28
+ return Array.isArray(inpt) && inpt.length === 2 && inpt.every((n) => typeof n === 'number' && Number.isInteger(n));
29
+ }
30
+
31
+ export function is_graph_pointer_rule_ref(pointer: GraphPointer<any>): pointer is GraphPointer<RuleRef> {
32
+ return is_rule_ref(pointer.rule);
33
+ }
34
+
35
+ export function is_graph_pointer_rule_end(pointer: GraphPointer<any>): pointer is GraphPointer<RuleEnd> {
36
+ return is_rule_end(pointer.rule);
37
+ }
38
+
39
+ export function is_graph_pointer_rule_char(pointer: GraphPointer<any>): pointer is GraphPointer<RuleChar> {
40
+ return is_rule_char(pointer.rule);
41
+ }
42
+
43
+ export function is_graph_pointer_rule_char_exclude(
44
+ pointer: GraphPointer<any>,
45
+ ): pointer is GraphPointer<RuleCharExclude> {
46
+ return is_rule_char_exclude(pointer.rule);
47
+ }
48
+
49
+ export const isRule = is_rule;
50
+ export const isRuleRef = is_rule_ref;
51
+ export const isRuleEnd = is_rule_end;
52
+ export const isRuleChar = is_rule_char;
53
+ export const isRuleCharExclude = is_rule_char_exclude;
54
+ export const isRange = is_range;
55
+ export const isGraphPointerRuleRef = is_graph_pointer_rule_ref;
56
+ export const isGraphPointerRuleEnd = is_graph_pointer_rule_end;
57
+ export const isGraphPointerRuleChar = is_graph_pointer_rule_char;
58
+ export const isGraphPointerRuleCharExclude = is_graph_pointer_rule_char_exclude;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_parser/build_rule_stack.ts ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ type Range,
3
+ RuleChar,
4
+ RuleCharExclude,
5
+ RuleEnd,
6
+ type UnresolvedRule,
7
+ } from '../grammar_graph/grammar_graph_types.ts';
8
+ import { RuleRef } from '../grammar_graph/rule_ref.ts';
9
+ import { is_range, is_rule_end } from '../grammar_graph/type_guards.ts';
10
+ import {
11
+ type InternalRuleDef,
12
+ type InternalRuleDefChar,
13
+ type InternalRuleDefCharNot,
14
+ is_rule_def_alt,
15
+ is_rule_def_char,
16
+ is_rule_def_char_alt,
17
+ is_rule_def_char_not,
18
+ is_rule_def_char_rng_upper,
19
+ is_rule_def_end,
20
+ is_rule_def_ref,
21
+ } from '../rules_builder/rules_builder_types.ts';
22
+ import { py_json, py_repr } from '../utils/py.ts';
23
+
24
+ export function make_char_rule(rule_def: InternalRuleDefChar | InternalRuleDefCharNot): RuleChar | RuleCharExclude {
25
+ const value = rule_def.value as (number | Range)[];
26
+ if (is_rule_def_char_not(rule_def)) {
27
+ return new RuleCharExclude(value);
28
+ }
29
+ if (is_rule_def_char(rule_def)) {
30
+ return new RuleChar(value);
31
+ }
32
+
33
+ throw new Error(`Unsupported rule type for make_char_rule: ${py_repr(rule_def)}`);
34
+ }
35
+
36
+ export function build_rule_stack(linear_rules: InternalRuleDef[]): UnresolvedRule[][] {
37
+ let paths: UnresolvedRule[] = [];
38
+ const stack: UnresolvedRule[][] = [];
39
+ let idx = 0;
40
+
41
+ while (idx < linear_rules.length) {
42
+ const rule_def = linear_rules[idx];
43
+ if (is_rule_def_char(rule_def) || is_rule_def_char_not(rule_def)) {
44
+ // this could be a single char, or a range, or a sequence of alts; we don't know until we step through it.
45
+ const char_rule = make_char_rule(rule_def);
46
+ idx += 1;
47
+ let rule = idx < linear_rules.length ? linear_rules[idx] : null;
48
+ while (idx < linear_rules.length && (is_rule_def_char_rng_upper(rule) || is_rule_def_char_alt(rule))) {
49
+ if (is_rule_def_char_rng_upper(rule)) {
50
+ // previous rule value should be a number
51
+ const prev_value = char_rule.value.pop();
52
+ if (is_range(prev_value)) {
53
+ throw new Error(`Unexpected range, expected a number but got an array: ${py_json(prev_value)}`);
54
+ }
55
+ if (prev_value === undefined || prev_value === null) {
56
+ throw new Error('Unexpected undefined value');
57
+ }
58
+
59
+ char_rule.value.push([prev_value as number, rule.value]);
60
+ }
61
+ if (is_rule_def_char_alt(rule)) {
62
+ char_rule.value.push(rule.value);
63
+ }
64
+ idx += 1;
65
+ rule = idx < linear_rules.length ? linear_rules[idx] : null;
66
+ }
67
+ paths.push(char_rule);
68
+ } else {
69
+ if (is_rule_def_alt(rule_def)) {
70
+ if (paths.length === 0) {
71
+ throw new Error('Encountered alt without anything before it');
72
+ }
73
+ paths.push(new RuleEnd());
74
+ stack.push(paths);
75
+ paths = [];
76
+ } else if (is_rule_def_end(rule_def)) {
77
+ paths.push(new RuleEnd());
78
+ } else if (is_rule_def_ref(rule_def)) {
79
+ paths.push(new RuleRef(rule_def.value));
80
+ } else if (is_rule_def_char_alt(rule_def)) {
81
+ throw new Error(`Encountered char alt, should be handled by above block: ${py_repr(rule_def)}`);
82
+ } else {
83
+ throw new Error(`Unsupported rule type: ${py_repr(rule_def)}`);
84
+ }
85
+ idx += 1;
86
+ }
87
+ }
88
+
89
+ if (paths.length === 0) {
90
+ throw new RangeError('list index out of range');
91
+ }
92
+ if (!is_rule_end(paths[paths.length - 1])) {
93
+ paths.push(new RuleEnd());
94
+ }
95
+
96
+ stack.push(paths);
97
+ return stack;
98
+ }
99
+
100
+ export const makeCharRule = make_char_rule;
101
+ export const buildRuleStack = build_rule_stack;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/grammar_parser/index.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ export * from './build_rule_stack.ts';
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/index.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ export { GBNF } from './GBNF.ts';
2
+ export { GBNF as default } from './GBNF.ts';
3
+ export { RuleChar, RuleCharExclude, RuleEnd } from './grammar_graph/grammar_graph_types.ts';
4
+ export { ParseState } from './grammar_graph/parse_state.ts';
5
+ export { GrammarParseError, InputParseError } from './utils/errors/index.ts';
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/index.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ export { GrammarParseError, InputParseError } from '../utils/errors/index.ts';
2
+ export { RulesBuilder } from './rules_builder.ts';
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/is_word_char.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ export function is_word_char(c: string): boolean {
2
+ return /[a-zA-Z]/.test(c);
3
+ }
4
+
5
+ export const isWordChar = is_word_char;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/parse_char.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GrammarParseError } from '../utils/errors/index.ts';
2
+ import { code_points, slice_src, type Src } from '../utils/py.ts';
3
+
4
+ const parse_hex = (chars: Src, start: number, end: number): number => {
5
+ const hex = slice_src(chars, start, end).trim().replace(/^[+-]?0[xX]/, (m) => m.replace(/0[xX]/, ''));
6
+ if (!/^[+-]?[0-9a-fA-F]+(_[0-9a-fA-F]+)*$/.test(hex)) {
7
+ throw new Error(`invalid literal for int() with base 16: '${slice_src(chars, start, end)}'`);
8
+ }
9
+ return parseInt(hex.replace(/_/g, ''), 16);
10
+ };
11
+
12
+ const ESCAPES: Record<string, string> = { t: '\t', r: '\r', n: '\n' };
13
+
14
+ export function parse_char(src: Src, pos: number): [number, number] {
15
+ const grammar = typeof src === 'string' ? src : src.join('');
16
+ const chars = code_points(src);
17
+ if (pos >= chars.length) {
18
+ throw new GrammarParseError(grammar, pos, 'Unexpected end of grammar input, failed to complete parse');
19
+ }
20
+
21
+ if (chars[pos] === '\\') {
22
+ const next = chars[pos + 1];
23
+ if (next === undefined) {
24
+ throw new RangeError('string index out of range');
25
+ }
26
+ if (next === 'x') {
27
+ return [parse_hex(chars, pos + 2, pos + 4), 4];
28
+ }
29
+ if (next === 'u') {
30
+ return [parse_hex(chars, pos + 2, pos + 6), 6];
31
+ }
32
+ if (next === 'U') {
33
+ return [parse_hex(chars, pos + 2, pos + 10), 10];
34
+ }
35
+ if (next in ESCAPES) {
36
+ return [ESCAPES[next].codePointAt(0) as number, 2];
37
+ }
38
+ if (next === '"' || next === '[' || next === ']' || next === '\\') {
39
+ return [next.codePointAt(0) as number, 2];
40
+ }
41
+ throw new GrammarParseError(grammar, pos, `Unknown escape at ${chars[pos]}`);
42
+ }
43
+
44
+ return [chars[pos].codePointAt(0) as number, 1];
45
+ }
46
+
47
+ export const parseChar = parse_char;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/parse_name.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GrammarParseError } from '../utils/errors/index.ts';
2
+ import { code_points, type Src } from '../utils/py.ts';
3
+ import { is_word_char } from './is_word_char.ts';
4
+
5
+ export const PARSE_NAME_ERROR = 'Failed to find a valid name';
6
+
7
+ export const VALID_NAME_SEPARATORS = ['-', '_'];
8
+
9
+ export function parse_name(grammar: Src, pos: number): string {
10
+ const chars = code_points(grammar);
11
+ let name = '';
12
+ while (pos < chars.length && (is_word_char(chars[pos]) || VALID_NAME_SEPARATORS.includes(chars[pos]))) {
13
+ name += chars[pos];
14
+ pos += 1;
15
+ }
16
+ if (!name) {
17
+ throw new GrammarParseError(typeof grammar === 'string' ? grammar : grammar.join(''), pos, PARSE_NAME_ERROR);
18
+ }
19
+ return name;
20
+ }
21
+
22
+ export const parseName = parse_name;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/parse_space.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { code_points, type Src } from '../utils/py.ts';
2
+
3
+ export function parse_space(src: Src, pos: number, newline_ok: boolean): number {
4
+ src = code_points(src);
5
+ while (
6
+ pos < src.length &&
7
+ (src[pos] === ' ' ||
8
+ src[pos] === '\t' ||
9
+ src[pos] === '#' ||
10
+ (newline_ok && (src[pos] === '\r' || src[pos] === '\n')))
11
+ ) {
12
+ if (src[pos] === '#') {
13
+ while (pos < src.length && src[pos] !== '\r' && src[pos] !== '\n') {
14
+ pos += 1;
15
+ }
16
+ } else {
17
+ pos += 1;
18
+ }
19
+ }
20
+ return pos;
21
+ }
22
+
23
+ export const parseSpace = parse_space;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/rules_builder.ts ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GrammarParseError } from '../utils/errors/index.ts';
2
+ import { code_points, type Src } from '../utils/py.ts';
3
+ import { is_word_char } from './is_word_char.ts';
4
+ import { parse_char } from './parse_char.ts';
5
+ import { parse_name } from './parse_name.ts';
6
+ import { parse_space } from './parse_space.ts';
7
+ import {
8
+ type InternalRuleDef,
9
+ InternalRuleDefAlt,
10
+ InternalRuleDefChar,
11
+ InternalRuleDefCharAlt,
12
+ InternalRuleDefCharNot,
13
+ InternalRuleDefCharRngUpper,
14
+ InternalRuleDefEnd,
15
+ InternalRuleDefReference,
16
+ } from './rules_builder_types.ts';
17
+ import { SymbolIds } from './symbol_ids.ts';
18
+
19
+ type RuleDefType = new (...args: any[]) => InternalRuleDef;
20
+
21
+ const perf_counter = (): number => performance.now() / 1000;
22
+
23
+ export function get_out_elements(type_of_rule: RuleDefType, startchar_value: number): InternalRuleDef {
24
+ if (type_of_rule === InternalRuleDefChar) {
25
+ return new InternalRuleDefChar([startchar_value]);
26
+ }
27
+ if (type_of_rule === InternalRuleDefCharNot) {
28
+ return new InternalRuleDefCharNot([startchar_value]);
29
+ }
30
+ if (type_of_rule === InternalRuleDefCharRngUpper) {
31
+ return new InternalRuleDefCharRngUpper(startchar_value);
32
+ }
33
+ if (type_of_rule === InternalRuleDefAlt) {
34
+ return new InternalRuleDefAlt();
35
+ }
36
+ if (type_of_rule === InternalRuleDefEnd) {
37
+ return new InternalRuleDefEnd();
38
+ }
39
+ if (type_of_rule === InternalRuleDefCharAlt) {
40
+ return new InternalRuleDefCharAlt(startchar_value);
41
+ }
42
+
43
+ throw new Error(`Invalid type: ${(type_of_rule as { name?: string })?.name ?? type_of_rule}`);
44
+ }
45
+
46
+ export const getOutElements = get_out_elements;
47
+
48
+ export class RulesBuilder {
49
+ pos: number;
50
+ symbol_ids: SymbolIds;
51
+ rules: InternalRuleDef[][];
52
+ src: string;
53
+ start: number;
54
+ time_limit: number;
55
+ // the source, indexable by code point
56
+ private chars: Src;
57
+
58
+ constructor(src: string, limit = 1000) {
59
+ this.pos = 0;
60
+ this.symbol_ids = new SymbolIds();
61
+ this.rules = [];
62
+ this.src = src;
63
+ this.chars = code_points(src);
64
+ this.start = perf_counter();
65
+ this.time_limit = limit;
66
+ this.parse(src);
67
+ }
68
+
69
+ get symbolIds(): SymbolIds {
70
+ return this.symbol_ids;
71
+ }
72
+
73
+ get timeLimit(): number {
74
+ return this.time_limit;
75
+ }
76
+
77
+ parse(source: string): void {
78
+ const src = code_points(source);
79
+ this.pos = parse_space(src, 0, true);
80
+ while (this.pos < src.length) {
81
+ this.parse_rule(source);
82
+ }
83
+
84
+ // Validate the state to ensure that all rules are defined
85
+ for (const rule of this.rules) {
86
+ for (const elem of rule) {
87
+ if (elem instanceof InternalRuleDefReference) {
88
+ const rule_exists = elem.value < this.rules.length && this.rules[elem.value].length > 0;
89
+ if (!rule_exists) {
90
+ const missing_rule_name = this.symbol_ids.reverse_get(elem.value);
91
+ let missing_rule_pos = this.symbol_ids.get_pos(missing_rule_name);
92
+
93
+ // Skip over the ::= and any whitespace
94
+ while (
95
+ missing_rule_pos < src.length &&
96
+ (src[missing_rule_pos] === ':' || src[missing_rule_pos] === '=' || /^\s$/u.test(src[missing_rule_pos]))
97
+ ) {
98
+ missing_rule_pos += 1;
99
+ }
100
+
101
+ throw new GrammarParseError(source, missing_rule_pos, `Undefined rule identifier "${missing_rule_name}"`);
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
107
+
108
+ parse_rule(source: string): void {
109
+ const src = code_points(source);
110
+ const name = parse_name(src, this.pos);
111
+ this.pos = parse_space(src, this.pos + name.length, false);
112
+ const rule_id = this.get_symbol_id(name, name.length);
113
+
114
+ this.pos = parse_space(src, this.pos, true);
115
+ if (
116
+ !(
117
+ this.pos + 2 < src.length && // Ensure the position + 2 is within bounds
118
+ src[this.pos] === ':' &&
119
+ src[this.pos + 1] === ':' &&
120
+ src[this.pos + 2] === '='
121
+ )
122
+ ) {
123
+ throw new GrammarParseError(source, this.pos, `Expecting ::= at ${this.pos}`);
124
+ }
125
+ this.pos += 3;
126
+ this.pos = parse_space(src, this.pos, true);
127
+
128
+ this.parse_alternates(name, rule_id);
129
+
130
+ // Check if this.pos is within the bounds of src before checking for a carriage return
131
+ if (this.pos < src.length && src[this.pos] === '\r') {
132
+ this.pos += src[this.pos + 1] === '\n' ? 2 : 1;
133
+ } else if (this.pos < src.length && src[this.pos] === '\n') {
134
+ this.pos += 1;
135
+ } else if (this.pos < src.length && src[this.pos]) {
136
+ throw new GrammarParseError(source, this.pos, `Expecting newline or end at ${this.pos}`);
137
+ }
138
+ this.pos = parse_space(src, this.pos, true);
139
+ }
140
+
141
+ get_symbol_id(src: string, length: number): number {
142
+ const next_id = this.symbol_ids.length;
143
+ const key = src.slice(0, length);
144
+ if (!this.symbol_ids.has(key)) {
145
+ this.symbol_ids.set(key, next_id, this.pos);
146
+ }
147
+ return this.symbol_ids.get(key) as number;
148
+ }
149
+
150
+ generate_symbol_id(base_name: string): number {
151
+ const next_id = this.symbol_ids.length;
152
+ this.symbol_ids.set(`${base_name}_${next_id}`, next_id, this.pos);
153
+ return next_id;
154
+ }
155
+
156
+ add_rule(rule_id: number, rule: InternalRuleDef[]): void {
157
+ while (this.rules.length <= rule_id) {
158
+ this.rules.push([]);
159
+ }
160
+ this.rules[rule_id] = rule;
161
+ }
162
+
163
+ check_duration(): void {
164
+ if (perf_counter() - this.start > this.time_limit) {
165
+ throw new GrammarParseError(this.src, this.pos, `Duration of ${this.time_limit} exceeded`);
166
+ }
167
+ }
168
+
169
+ parse_sequence(rule_name: string, out_elements: InternalRuleDef[], depth = 0): void {
170
+ const is_nested = depth !== 0;
171
+ const src = this.chars;
172
+ let last_sym_start = out_elements.length;
173
+
174
+ while (this.pos < src.length) {
175
+ const c = src[this.pos];
176
+ if (c === '"') {
177
+ this.pos += 1;
178
+ last_sym_start = out_elements.length;
179
+ while (src[this.pos] !== '"') {
180
+ this.check_duration();
181
+ const [value, inc_pos] = parse_char(src, this.pos);
182
+ out_elements.push(new InternalRuleDefChar([value]));
183
+ this.pos += inc_pos;
184
+ }
185
+ this.pos = parse_space(src, this.pos + 1, is_nested);
186
+ } else if (c === '[') {
187
+ this.pos += 1;
188
+ let start_type: RuleDefType = InternalRuleDefChar;
189
+ if (src[this.pos] === '^') {
190
+ this.pos += 1;
191
+ start_type = InternalRuleDefCharNot;
192
+ }
193
+ last_sym_start = out_elements.length;
194
+ while (src[this.pos] !== ']') {
195
+ this.check_duration();
196
+ const type_: RuleDefType = last_sym_start < out_elements.length ? InternalRuleDefCharAlt : start_type;
197
+ const [startchar_value, inc_pos] = parse_char(src, this.pos);
198
+ this.pos += inc_pos;
199
+ out_elements.push(get_out_elements(type_, startchar_value));
200
+
201
+ if (src[this.pos] === '-' && src[this.pos + 1] !== ']') {
202
+ this.pos += 1;
203
+ const [endchar_value, end_inc_pos] = parse_char(src, this.pos);
204
+ out_elements.push(new InternalRuleDefCharRngUpper(endchar_value));
205
+ this.pos += end_inc_pos;
206
+ }
207
+ }
208
+ this.pos = parse_space(src, this.pos + 1, is_nested);
209
+ } else if (is_word_char(c)) {
210
+ const name = parse_name(src, this.pos);
211
+ const ref_rule_id = this.get_symbol_id(name, name.length);
212
+ this.pos += name.length;
213
+ this.pos = parse_space(src, this.pos, is_nested);
214
+
215
+ last_sym_start = out_elements.length;
216
+ out_elements.push(new InternalRuleDefReference(ref_rule_id));
217
+ } else if (c === '(') {
218
+ this.pos = parse_space(src, this.pos + 1, true);
219
+ const sub_rule_id = this.generate_symbol_id(rule_name);
220
+ this.parse_alternates(rule_name, sub_rule_id, depth + 1);
221
+ last_sym_start = out_elements.length;
222
+ out_elements.push(new InternalRuleDefReference(sub_rule_id));
223
+ if (src[this.pos] !== ')') {
224
+ throw new GrammarParseError(this.src, this.pos, `Expecting ')' at ${this.pos}`);
225
+ }
226
+ this.pos = parse_space(src, this.pos + 1, is_nested);
227
+ } else if (c === '*' || c === '+' || c === '?') {
228
+ if (last_sym_start === out_elements.length) {
229
+ throw new GrammarParseError(this.src, this.pos, `Expecting preceding item to */+/? at ${this.pos}`);
230
+ }
231
+ const sub_rule_id = this.generate_symbol_id(rule_name);
232
+ const sub_rule = out_elements.slice(last_sym_start);
233
+ if (c === '*' || c === '+') {
234
+ sub_rule.push(new InternalRuleDefReference(sub_rule_id));
235
+ }
236
+ sub_rule.push(new InternalRuleDefAlt());
237
+ if (c === '+') {
238
+ sub_rule.push(...out_elements.slice(last_sym_start));
239
+ }
240
+ sub_rule.push(new InternalRuleDefEnd());
241
+ this.add_rule(sub_rule_id, sub_rule);
242
+ out_elements.splice(last_sym_start, out_elements.length - last_sym_start, new InternalRuleDefReference(sub_rule_id));
243
+ this.pos = parse_space(src, this.pos + 1, is_nested);
244
+ } else {
245
+ break;
246
+ }
247
+ }
248
+ }
249
+
250
+ parse_alternates(rule_name: string, rule_id: number, depth = 0): void {
251
+ const src = this.chars;
252
+ const rule: InternalRuleDef[] = [];
253
+ this.parse_sequence(rule_name, rule, depth);
254
+ // Ensure that this.pos is within bounds before checking src[this.pos]
255
+ while (this.pos < src.length && src[this.pos] === '|') {
256
+ this.check_duration();
257
+ rule.push(new InternalRuleDefAlt());
258
+ this.pos = parse_space(src, this.pos + 1, true);
259
+ this.parse_sequence(rule_name, rule, depth);
260
+ }
261
+ rule.push(new InternalRuleDefEnd());
262
+ this.add_rule(rule_id, rule);
263
+ }
264
+
265
+ parseRule(src: string): void {
266
+ this.parse_rule(src);
267
+ }
268
+
269
+ getSymbolId(src: string, length: number): number {
270
+ return this.get_symbol_id(src, length);
271
+ }
272
+
273
+ generateSymbolId(base_name: string): number {
274
+ return this.generate_symbol_id(base_name);
275
+ }
276
+
277
+ addRule(rule_id: number, rule: InternalRuleDef[]): void {
278
+ this.add_rule(rule_id, rule);
279
+ }
280
+
281
+ checkDuration(): void {
282
+ this.check_duration();
283
+ }
284
+
285
+ parseSequence(rule_name: string, out_elements: InternalRuleDef[], depth = 0): void {
286
+ this.parse_sequence(rule_name, out_elements, depth);
287
+ }
288
+
289
+ parseAlternates(rule_name: string, rule_id: number, depth = 0): void {
290
+ this.parse_alternates(rule_name, rule_id, depth);
291
+ }
292
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/rules_builder_types.ts ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const values_equal = (a: unknown, b: unknown): boolean => {
2
+ if (Array.isArray(a) && Array.isArray(b)) {
3
+ return a.length === b.length && a.every((v, i) => values_equal(v, b[i]));
4
+ }
5
+ return a === b;
6
+ };
7
+
8
+ // Accepts either a positional value or a python style `{ value }` keyword object.
9
+ const unwrap = <T>(value: T | { value: T }): T =>
10
+ value !== null && typeof value === 'object' && !Array.isArray(value) && 'value' in value ? value.value : value;
11
+
12
+ export class InternalRuleDefWithNumericValue {
13
+ value: number;
14
+
15
+ constructor(value: number | { value: number }) {
16
+ this.value = unwrap(value);
17
+ }
18
+
19
+ equals(other: unknown): boolean {
20
+ return other instanceof InternalRuleDefWithNumericValue && values_equal(this.value, other.value);
21
+ }
22
+ }
23
+
24
+ export class InternalBase {
25
+ equals(other: unknown): boolean {
26
+ return other instanceof this.constructor;
27
+ }
28
+ }
29
+
30
+ export class InternalBaseWithValue<T = unknown> {
31
+ value: T;
32
+
33
+ constructor(value: T | { value: T }) {
34
+ this.value = unwrap(value);
35
+ }
36
+
37
+ equals(other: unknown): boolean {
38
+ return other instanceof this.constructor && values_equal(this.value, (other as InternalBaseWithValue).value);
39
+ }
40
+ }
41
+
42
+ export class InternalBaseWithInt extends InternalBaseWithValue<number> {}
43
+
44
+ export class InternalBaseWithListOfInts extends InternalBaseWithValue<number[]> {
45
+ constructor(value: number[] | { value: number[] } = []) {
46
+ super(value);
47
+ this.value = [...this.value];
48
+ }
49
+ }
50
+
51
+ export class InternalRuleDefChar extends InternalBaseWithListOfInts {}
52
+
53
+ export class InternalRuleDefCharAlt extends InternalBaseWithInt {}
54
+
55
+ export class InternalRuleDefAlt extends InternalBase {}
56
+
57
+ export class InternalRuleDefCharNot extends InternalBaseWithListOfInts {}
58
+
59
+ export class InternalRuleDefCharRngUpper extends InternalBaseWithInt {}
60
+
61
+ export class InternalRuleDefReference extends InternalBaseWithInt {}
62
+
63
+ export class InternalRuleDefEnd extends InternalBase {}
64
+
65
+ export class InternalRuleDefWithoutValue extends InternalBase {}
66
+
67
+ export type InternalRuleDef =
68
+ | InternalRuleDefChar
69
+ | InternalRuleDefEnd
70
+ | InternalRuleDefReference
71
+ | InternalRuleDefCharNot
72
+ | InternalRuleDefWithNumericValue
73
+ | InternalRuleDefWithoutValue
74
+ | InternalRuleDefAlt
75
+ | InternalRuleDefCharRngUpper
76
+ | InternalRuleDefCharAlt;
77
+
78
+ export type InternalRuleDefCharOrAltChar = InternalRuleDefChar | InternalRuleDefCharAlt;
79
+
80
+ export function is_rule_def_alt(rule: unknown): rule is InternalRuleDefAlt {
81
+ return rule instanceof InternalRuleDefAlt;
82
+ }
83
+
84
+ export function is_rule_def_ref(rule: unknown): rule is InternalRuleDefReference {
85
+ return rule instanceof InternalRuleDefReference;
86
+ }
87
+
88
+ export function is_rule_def_end(rule: unknown): rule is InternalRuleDefEnd {
89
+ return rule instanceof InternalRuleDefEnd;
90
+ }
91
+
92
+ export function is_rule_def_char(rule: unknown): rule is InternalRuleDefChar {
93
+ return rule instanceof InternalRuleDefChar;
94
+ }
95
+
96
+ export function is_rule_def_char_not(rule: unknown): rule is InternalRuleDefCharNot {
97
+ return rule instanceof InternalRuleDefCharNot;
98
+ }
99
+
100
+ export function is_rule_def_char_alt(rule: unknown): rule is InternalRuleDefCharAlt {
101
+ return rule instanceof InternalRuleDefCharAlt;
102
+ }
103
+
104
+ export function is_rule_def_char_rng_upper(rule: unknown): rule is InternalRuleDefCharRngUpper {
105
+ return rule instanceof InternalRuleDefCharRngUpper;
106
+ }
107
+
108
+ export const isRuleDefAlt = is_rule_def_alt;
109
+ export const isRuleDefRef = is_rule_def_ref;
110
+ export const isRuleDefEnd = is_rule_def_end;
111
+ export const isRuleDefChar = is_rule_def_char;
112
+ export const isRuleDefCharNot = is_rule_def_char_not;
113
+ export const isRuleDefCharAlt = is_rule_def_char_alt;
114
+ export const isRuleDefCharRngUpper = is_rule_def_char_rng_upper;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/rules_builder/symbol_ids.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export class SymbolIds {
2
+ __map__: Map<string, number> = new Map();
3
+ __pos__: Map<string, number> = new Map();
4
+ __reverse_map__: Map<number, string> = new Map();
5
+
6
+ items(): [string, number][] {
7
+ return [...this.__map__.entries()];
8
+ }
9
+
10
+ entries(): [string, number][] {
11
+ return this.items();
12
+ }
13
+
14
+ keys(): string[] {
15
+ return [...this.__map__.keys()];
16
+ }
17
+
18
+ values(): number[] {
19
+ return [...this.__map__.values()];
20
+ }
21
+
22
+ [Symbol.iterator](): IterableIterator<[string, number]> {
23
+ return this.__map__.entries();
24
+ }
25
+
26
+ get length(): number {
27
+ return this.__map__.size;
28
+ }
29
+
30
+ get size(): number {
31
+ return this.__map__.size;
32
+ }
33
+
34
+ get(key: string): number | undefined {
35
+ return this.__map__.get(key);
36
+ }
37
+
38
+ set(key: string, value: number, pos: number): void {
39
+ this.__map__.set(key, value);
40
+ this.__reverse_map__.set(value, key);
41
+ this.__pos__.set(key, pos);
42
+ }
43
+
44
+ has(key: string): boolean {
45
+ return this.__map__.has(key);
46
+ }
47
+
48
+ reverse_get(key: number): string {
49
+ const val = this.__reverse_map__.get(key);
50
+ if (val === undefined) {
51
+ throw new Error(`SymbolIds does not contain value: ${key}`);
52
+ }
53
+ return val;
54
+ }
55
+
56
+ reverseGet(key: number): string {
57
+ return this.reverse_get(key);
58
+ }
59
+
60
+ get_pos(key: string): number {
61
+ const val = this.__pos__.get(key);
62
+ if (val === undefined) {
63
+ throw new Error(`SymbolIds does not contain key: ${key}`);
64
+ }
65
+ return val;
66
+ }
67
+
68
+ getPos(key: string): number {
69
+ return this.get_pos(key);
70
+ }
71
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/smoke.test.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test, vi } from 'vitest';
2
+ import { GBNF, GrammarParseError, InputParseError, RuleChar, RuleCharExclude, RuleEnd } from './index.ts';
3
+ import { Color, colorize } from './grammar_graph/colorize.ts';
4
+ import { get_input_as_code_points } from './grammar_graph/get_input_as_code_points.ts';
5
+ import { get_serialized_rule_key, KEY_TRANSLATION } from './grammar_graph/get_serialized_rule_key.ts';
6
+ import { Graph } from './grammar_graph/graph.ts';
7
+ import { GraphNode } from './grammar_graph/graph_node.ts';
8
+ import { GraphPointer } from './grammar_graph/graph_pointer.ts';
9
+ import { ParseState } from './grammar_graph/parse_state.ts';
10
+ import { Pointers } from './grammar_graph/pointers.ts';
11
+ import { print_graph_node, print_graph_pointer } from './grammar_graph/print.ts';
12
+ import { RuleRef } from './grammar_graph/rule_ref.ts';
13
+ import { is_range, is_rule } from './grammar_graph/type_guards.ts';
14
+ import { parse_char } from './rules_builder/parse_char.ts';
15
+ import { PARSE_NAME_ERROR, parse_name } from './rules_builder/parse_name.ts';
16
+ import { build_error_position } from './utils/errors/build_error_position.ts';
17
+ import { get_input_as_string } from './utils/errors/get_input_as_string.ts';
18
+
19
+ vi.mock('./grammar_graph/get_parent_stack_id.ts', () => ({ get_parent_stack_id: () => 'foo' }));
20
+
21
+ const meta = { stackId: 1, pathId: 2, stepId: 3 };
22
+
23
+ describe('smoke', () => {
24
+ test('GBNF', () => {
25
+ expect([...GBNF('root ::= "foo" | [^a-c]')]).toEqual([new RuleChar([102]), new RuleCharExclude([[97, 99]])]);
26
+ const state = GBNF('root ::= "bar"');
27
+ expect(state).toBeInstanceOf(ParseState);
28
+ expect([...state('bar')]).toEqual([new RuleEnd()]);
29
+ expect(state.add('b').size).toBe(1);
30
+ expect(state.grammar).toBe('root ::= "bar"');
31
+ expect(() => GBNF('root ::= "bar"').add('ba').add('z')).toThrow(new InputParseError('z', 0, 'ba'));
32
+ expect(() => GBNF('root = "foo"')).toThrow(new GrammarParseError('root = "foo"', 5, 'Expecting ::= at 5'));
33
+ expect(() => GBNF(1 as any)).toThrow('grammar must be a string');
34
+ });
35
+
36
+ test('graph', () => {
37
+ const graph = new Graph('g', [[[new RuleChar([65, 66, 67])], [new RuleChar([68, [69, 70]])]]], 0);
38
+ expect(graph.__get_root_node__(0).size).toBe(2);
39
+ expect(graph.print(undefined, true)).toBe(
40
+ '\x1b[34m{\x1b[90m0,0,0\x1b[34m}\x1b[90m[\x1b[33mABC\x1b[90m]\n\x1b[34m{\x1b[90m0,1,0\x1b[34m}\x1b[90m[\x1b[33mD\x1b[33mE\x1b[33mF\x1b[90m]',
41
+ );
42
+ const ptrs = new Pointers(new GraphPointer(new GraphNode(new RuleEnd(), meta)));
43
+ expect([...graph.__iterate_over_pointers__(ptrs)].length).toBe(1);
44
+ expect(() => [...graph.__iterate_over_pointers__([new GraphPointer(new GraphNode(new RuleRef(0), meta))])]).toThrow(
45
+ 'Encountered a reference rule in the graph',
46
+ );
47
+ });
48
+
49
+ test('misc', () => {
50
+ expect(colorize(123, Color.RED)).toBe('\x1b[31m123');
51
+ expect(get_input_as_code_points('a😀')).toEqual([97, 0x1f600]);
52
+ expect(get_input_as_string([0x1f600, 0x1f601])).toBe('😀😁');
53
+ expect(get_serialized_rule_key(new RuleChar([97, [1, 2]]))).toBe(`${KEY_TRANSLATION.get(RuleChar)}-[97, [1, 2]]`);
54
+ expect(() => get_serialized_rule_key({ type: 'UNKNOWN', value: 'something' } as any)).toThrow(
55
+ "Unknown rule type: {'type': 'UNKNOWN', 'value': 'something'}",
56
+ );
57
+ expect(() => new GraphNode(new RuleRef(1), null)).toThrow('Meta is undefined');
58
+ expect(() => new GraphPointer(null as any)).toThrow('Node is undefined');
59
+ expect(() => new RuleRef(1).nodes).toThrow('Nodes are not set');
60
+ const parent = new GraphPointer(new GraphNode(new RuleChar([97]), meta));
61
+ expect(new GraphPointer(new GraphNode(new RuleChar([98]), { stackId: 4, pathId: 5, stepId: 6 }), parent).id).toBe(
62
+ '1,2,3-4,5,6',
63
+ );
64
+ expect(is_range([1, '10'])).toBe(false);
65
+ expect(is_rule({ type: 'invalid', value: [] })).toBe(false);
66
+ expect(parse_char('root ::= "\\U0001F4A9"', 10)).toEqual([128169, 10]);
67
+ expect(() => parse_char('a', 2)).toThrow(GrammarParseError);
68
+ expect(() => parse_name('123', 0)).toThrow(new GrammarParseError('123', 0, PARSE_NAME_ERROR));
69
+ expect(build_error_position('aa\nbb\ncc\ndd\nee', 9)).toEqual(['cc', 'dd', 'ee', ' ^']);
70
+ const col = (t: string | number, c: string) => `[${c === Color.RED ? 'RED' : c === Color.GRAY ? 'GRAY' : c === Color.BLUE ? 'BLUE' : 'OTHER'}]:${t}`;
71
+ expect(print_graph_pointer({} as any)({ colorize: col })).toBe('[RED]:*foo');
72
+ expect(print_graph_node({ id: 1, rule: new RuleRef(200) } as any)({ colorize: col, show_position: true })).toBe(
73
+ '[BLUE]:{[GRAY]:1[BLUE]:}[GRAY]:Ref([OTHER]:200[GRAY]:)',
74
+ );
75
+ });
76
+ });
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/build_error_position.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW = 3;
2
+
3
+ // lengths and positions are measured in code points
4
+ const len = (s: string): number => {
5
+ let n = 0;
6
+ for (const _ of s) {
7
+ n += 1;
8
+ }
9
+ return n;
10
+ };
11
+
12
+ export function build_error_position(src: string, pos: number): string[] {
13
+ if (src === '') {
14
+ return ['No input provided'];
15
+ }
16
+ const lines = src.split('\n');
17
+ const srcLength = len(src);
18
+
19
+ let line_idx = 0;
20
+ while (lines[line_idx] && pos > len(lines[line_idx]) - 1 && pos < srcLength) {
21
+ pos -= len(lines[line_idx]);
22
+ line_idx += 1;
23
+ }
24
+ if (line_idx >= lines.length) {
25
+ throw new RangeError('list index out of range');
26
+ }
27
+
28
+ const lines_to_show: string[] = [];
29
+ for (let i = Math.max(0, line_idx - (MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW - 1)); i < line_idx + 1; i++) {
30
+ lines_to_show.push(lines[i]);
31
+ }
32
+
33
+ return [...lines_to_show, `${' '.repeat(Math.max(0, pos))}^`];
34
+ }
35
+
36
+ export const buildErrorPosition = build_error_position;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/errors_types.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ export type ValidInput = string | number | number[];
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/get_input_as_string.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ValidInput } from './errors_types.ts';
2
+
3
+ export function get_input_as_string(src: ValidInput): string {
4
+ if (typeof src === 'string') {
5
+ return src;
6
+ }
7
+ if (typeof src === 'number') {
8
+ return String.fromCodePoint(src);
9
+ }
10
+ return src.map((cp) => String.fromCodePoint(cp)).join('');
11
+ }
12
+
13
+ export const getInputAsString = get_input_as_string;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/grammar_parse_error.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { build_error_position } from './build_error_position.ts';
2
+
3
+ export function GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason: string): string {
4
+ return `Failed to parse grammar: ${reason}`;
5
+ }
6
+
7
+ export class GrammarParseError extends Error {
8
+ grammar: string;
9
+ pos: number;
10
+ reason: string;
11
+
12
+ constructor(grammar: string, pos: number, reason: string) {
13
+ super([GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason), '', ...build_error_position(grammar, pos)].join('\n'));
14
+ this.name = 'GrammarParseError';
15
+ this.grammar = grammar;
16
+ this.pos = pos;
17
+ this.reason = reason;
18
+ }
19
+
20
+ get args(): string[] {
21
+ return [this.message];
22
+ }
23
+
24
+ toString(): string {
25
+ return [
26
+ GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(this.reason),
27
+ '',
28
+ ...build_error_position(this.grammar, this.pos),
29
+ ].join('\n');
30
+ }
31
+
32
+ equals(other: unknown): boolean {
33
+ return this.toString() === String(other);
34
+ }
35
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/index.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ export { GrammarParseError } from './grammar_parse_error.ts';
2
+ export { InputParseError } from './input_parse_error.ts';
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/errors/input_parse_error.ts ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { build_error_position } from './build_error_position.ts';
2
+ import type { ValidInput } from './errors_types.ts';
3
+ import { get_input_as_string } from './get_input_as_string.ts';
4
+
5
+ export const INPUT_PARSER_ERROR_HEADER_MESSAGE = 'Failed to parse input string:';
6
+
7
+ const len = (s: string): number => Array.from(s).length;
8
+
9
+ const build_message = (most_recent_input: ValidInput, pos: number, previous_input: ValidInput): string =>
10
+ [
11
+ INPUT_PARSER_ERROR_HEADER_MESSAGE,
12
+ '',
13
+ ...build_error_position(
14
+ `${get_input_as_string(previous_input)}${get_input_as_string(most_recent_input)}`,
15
+ pos + len(get_input_as_string(previous_input)),
16
+ ),
17
+ ].join('\n');
18
+
19
+ export class InputParseError extends Error {
20
+ most_recent_input: ValidInput;
21
+ pos: number;
22
+ previous_input: ValidInput;
23
+
24
+ constructor(most_recent_input: ValidInput, pos: number, previous_input: ValidInput = '') {
25
+ super(build_message(most_recent_input, pos, previous_input));
26
+ this.name = 'InputParseError';
27
+ this.most_recent_input = most_recent_input;
28
+ this.pos = pos;
29
+ this.previous_input = previous_input;
30
+ }
31
+
32
+ get args(): string[] {
33
+ return [this.message];
34
+ }
35
+
36
+ get mostRecentInput(): ValidInput {
37
+ return this.most_recent_input;
38
+ }
39
+
40
+ get previousInput(): ValidInput {
41
+ return this.previous_input;
42
+ }
43
+
44
+ get src(): string {
45
+ return `${get_input_as_string(this.previous_input)}${get_input_as_string(this.most_recent_input)}`;
46
+ }
47
+
48
+ get error_for_most_recent_input(): string {
49
+ return [
50
+ INPUT_PARSER_ERROR_HEADER_MESSAGE,
51
+ '',
52
+ ...build_error_position(get_input_as_string(this.most_recent_input), this.pos),
53
+ ].join('\n');
54
+ }
55
+
56
+ get errorForMostRecentInput(): string {
57
+ return this.error_for_most_recent_input;
58
+ }
59
+
60
+ toString(): string {
61
+ return build_message(this.most_recent_input, this.pos, this.previous_input);
62
+ }
63
+
64
+ equals(other: unknown): boolean {
65
+ return this.toString() === String(other);
66
+ }
67
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/index.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ export * from './is_point_in_range.ts';
2
+ export * from './validate_non_empty.ts';
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/is_point_in_range.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ export function is_point_in_range(point: number, given_range: [number, number] | number[]): boolean {
2
+ if (typeof point !== 'number' || !Number.isInteger(point)) {
3
+ throw new Error('point must be an integer');
4
+ }
5
+ return point >= given_range[0] && point <= given_range[1];
6
+ }
7
+
8
+ export const isPointInRange = is_point_in_range;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/py.ts ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Helpers for mirroring Python semantics (code point indexed strings, repr, json.dumps).
2
+
3
+ export type Src = string | string[];
4
+
5
+ let lastString: string | undefined;
6
+ let lastChars: Src = '';
7
+
8
+ // Python strings are indexed by code point; JS strings by UTF-16 code unit.
9
+ // Returns something indexable by code point: the string itself when it has no
10
+ // surrogate pairs, otherwise an array of single code point strings.
11
+ export function code_points(src: Src): Src {
12
+ if (typeof src !== 'string') {
13
+ return src;
14
+ }
15
+ if (src !== lastString) {
16
+ lastString = src;
17
+ lastChars = /[\ud800-\udfff]/.test(src) ? Array.from(src) : src;
18
+ }
19
+ return lastChars;
20
+ }
21
+
22
+ export function slice_src(src: Src, start: number, end?: number): string {
23
+ const sliced = src.slice(start, end);
24
+ return typeof sliced === 'string' ? sliced : sliced.join('');
25
+ }
26
+
27
+ export function is_int(value: unknown): value is number {
28
+ return typeof value === 'number' && Number.isInteger(value);
29
+ }
30
+
31
+ // json.dumps with Python's default separators
32
+ export function py_json(value: unknown): string {
33
+ if (Array.isArray(value)) {
34
+ return `[${value.map(py_json).join(', ')}]`;
35
+ }
36
+ if (value !== null && typeof value === 'object') {
37
+ return `{${Object.entries(value)
38
+ .map(([k, v]) => `${JSON.stringify(k)}: ${py_json(v)}`)
39
+ .join(', ')}}`;
40
+ }
41
+ return JSON.stringify(value) ?? 'null';
42
+ }
43
+
44
+ export function py_repr(value: unknown): string {
45
+ if (value === null || value === undefined) {
46
+ return 'None';
47
+ }
48
+ if (typeof value === 'boolean') {
49
+ return value ? 'True' : 'False';
50
+ }
51
+ if (typeof value === 'string') {
52
+ const quote = value.includes("'") && !value.includes('"') ? '"' : "'";
53
+ const escaped = value
54
+ .replace(/\\/g, '\\\\')
55
+ .replace(/\n/g, '\\n')
56
+ .replace(/\r/g, '\\r')
57
+ .replace(/\t/g, '\\t')
58
+ .replace(new RegExp(quote, 'g'), `\\${quote}`);
59
+ return `${quote}${escaped}${quote}`;
60
+ }
61
+ if (Array.isArray(value)) {
62
+ return `[${value.map(py_repr).join(', ')}]`;
63
+ }
64
+ if (typeof value === 'object') {
65
+ const proto = Object.getPrototypeOf(value);
66
+ if (proto === Object.prototype || proto === null) {
67
+ return `{${Object.entries(value)
68
+ .map(([k, v]) => `${py_repr(k)}: ${py_repr(v)}`)
69
+ .join(', ')}}`;
70
+ }
71
+ }
72
+ return String(value);
73
+ }
74
+
75
+ export const codePoints = code_points;
76
+ export const pyJson = py_json;
77
+ export const pyRepr = py_repr;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/gbnf/utils/validate_non_empty.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ export function validate_non_empty(value: number[]): number[] {
2
+ if (!value || value.length === 0) {
3
+ throw new Error('Value cannot be empty.');
4
+ }
5
+ return value;
6
+ }
7
+
8
+ export const validateNonEmpty = validate_non_empty;
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/node_modules/.vite/vitest/results.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":"2.1.3","results":[[":gbnf/smoke.test.ts",{"duration":4.375501999999983,"failed":false}],[":tests/differential.test.ts",{"duration":72.13208999999998,"failed":false}]]}
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/package.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gbnf",
3
+ "version": "0.0.30",
4
+ "description": "A library for parsing GBNF grammars",
5
+ "type": "module",
6
+ "main": "./gbnf/index.ts",
7
+ "types": "./gbnf/index.ts",
8
+ "exports": {
9
+ ".": "./gbnf/index.ts",
10
+ "./*": "./gbnf/*"
11
+ },
12
+ "scripts": {
13
+ "test": "vitest run"
14
+ }
15
+ }
v2-models-effort/runs/20261111-214430-fragrant-meadow/ported_implementation/tests/differential.test.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Replays cases recorded from the reference implementation (tests/fixtures/records.json).
2
+ import { readFileSync } from 'node:fs';
3
+ import { describe, expect, test } from 'vitest';
4
+ import { GBNF } from 'gbnf';
5
+ import { build_rule_stack } from 'gbnf/grammar_parser/build_rule_stack.ts';
6
+ import { RulesBuilder } from 'gbnf/rules_builder/rules_builder.ts';
7
+
8
+ const records: any[] = JSON.parse(readFileSync(new URL('./fixtures/records.json', import.meta.url), 'utf8'));
9
+
10
+ // the reference iterates referenced nodes in (unordered) set order, so compare order-insensitively
11
+ const sorted = (rules: any[]) => rules.map((r) => JSON.stringify(r)).sort();
12
+ const dump = (state: Iterable<any>) => sorted([...state].map((r) => r.__dict__));
13
+ const ser = (d: any) => [d.constructor.name, d.value ?? null];
14
+
15
+ describe('differential', () => {
16
+ test.each(records.map((r, i) => [i, r] as const))('record %i', (_i, rec) => {
17
+ if (rec.rb) {
18
+ const rb = new RulesBuilder(rec.grammar);
19
+ expect(rb.symbol_ids.items()).toEqual(rec.rb.symbols);
20
+ expect(rb.rules.map((r) => r.map(ser))).toEqual(rec.rb.rules);
21
+ expect(rb.rules.map((r) => build_rule_stack(r).map((p) => p.map(ser)))).toEqual(rec.stack);
22
+ }
23
+ let state: any;
24
+ if (rec.error) {
25
+ let caught: any;
26
+ try {
27
+ GBNF(rec.grammar, rec.initial);
28
+ } catch (e) {
29
+ caught = e;
30
+ }
31
+ expect(caught, 'expected an error').toBeDefined();
32
+ if (['GrammarParseError', 'InputParseError'].includes(rec.error.cls)) {
33
+ expect(caught.constructor.name).toBe(rec.error.cls);
34
+ expect(String(caught)).toBe(rec.error.str);
35
+ expect(caught.message).toBe(rec.error.str);
36
+ }
37
+ return;
38
+ }
39
+ state = GBNF(rec.grammar, rec.initial);
40
+ expect(dump(state)).toEqual(sorted(rec.rules));
41
+ for (const step of rec.steps) {
42
+ if (step.error) {
43
+ let caught: any;
44
+ try {
45
+ state.add(step.text);
46
+ } catch (e) {
47
+ caught = e;
48
+ }
49
+ expect(caught?.constructor.name).toBe(step.error.cls);
50
+ expect(String(caught)).toBe(step.error.str);
51
+ expect(caught.error_for_most_recent_input).toBe(step.error.efmri);
52
+ break;
53
+ }
54
+ state = state(step.text);
55
+ expect(dump(state)).toEqual(sorted(step.rules));
56
+ }
57
+ });
58
+ });