@holoscript/core 6.0.4 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/compiler/index.d.ts +82 -0
  4. package/dist/constants.d.ts +3 -2
  5. package/dist/coordinators/index.d.ts +189 -0
  6. package/dist/index.d.ts +501 -19
  7. package/dist/paper-0c-spike/index.d.ts +29 -0
  8. package/dist/reconstruction/index.d.ts +78 -0
  9. package/dist/tools/index.d.ts +22 -1
  10. package/dist/traitDocs/traitDocs.d.ts +69 -0
  11. package/dist/traits/index.d.ts +61 -0
  12. package/package.json +105 -57
  13. package/dist/GLTFPipeline-DEN36VNK.js +0 -12
  14. package/dist/GLTFPipeline-YPCAK236.cjs +0 -33
  15. package/dist/HoloScriptPlusParser-BN6KVRCM.js +0 -692
  16. package/dist/HoloScriptPlusParser-NC5FE6AL.cjs +0 -697
  17. package/dist/USDZExporter-NTMBNTDB.js +0 -707
  18. package/dist/USDZExporter-UWGWNMMD.cjs +0 -709
  19. package/dist/chunk-27LWW5FU.cjs +0 -410
  20. package/dist/chunk-2CWOLHTE.js +0 -69
  21. package/dist/chunk-33LSUQDD.cjs +0 -835
  22. package/dist/chunk-3FJCK5XA.js +0 -2232
  23. package/dist/chunk-3FXV5S25.cjs +0 -633
  24. package/dist/chunk-3FYZOR7S.cjs +0 -69
  25. package/dist/chunk-3SAK5KFL.cjs +0 -83
  26. package/dist/chunk-4XSNJCLC.cjs +0 -1859
  27. package/dist/chunk-54FHG2MX.js +0 -655
  28. package/dist/chunk-56IF4NTA.js +0 -56
  29. package/dist/chunk-5BGSECRJ.cjs +0 -2237
  30. package/dist/chunk-5GLCTO44.js +0 -161
  31. package/dist/chunk-5O6TQC6M.cjs +0 -1871
  32. package/dist/chunk-5OEOHAAW.cjs +0 -682
  33. package/dist/chunk-5TOFIR6L.js +0 -407
  34. package/dist/chunk-5WUNN6ZN.cjs +0 -428
  35. package/dist/chunk-6TZPZCOJ.cjs +0 -1404
  36. package/dist/chunk-6UEHYZ7V.cjs +0 -773
  37. package/dist/chunk-6XSERL6L.js +0 -5678
  38. package/dist/chunk-72EQECGT.cjs +0 -908
  39. package/dist/chunk-7AGYRWKW.cjs +0 -507
  40. package/dist/chunk-7LCYLPW2.cjs +0 -663
  41. package/dist/chunk-A7PIMZGU.js +0 -263
  42. package/dist/chunk-ATSKSYVE.cjs +0 -51683
  43. package/dist/chunk-B5TCIAPQ.cjs +0 -117
  44. package/dist/chunk-BF2235SI.cjs +0 -5714
  45. package/dist/chunk-BKIGPPVM.js +0 -629
  46. package/dist/chunk-BND3ST2K.cjs +0 -662
  47. package/dist/chunk-BU7VWW2K.js +0 -2522
  48. package/dist/chunk-BWFJEM5A.js +0 -5419
  49. package/dist/chunk-CAUCGUEA.cjs +0 -130
  50. package/dist/chunk-CBJSLA2E.cjs +0 -5423
  51. package/dist/chunk-CDPGV4DN.js +0 -114
  52. package/dist/chunk-CLYEIWA5.cjs +0 -408
  53. package/dist/chunk-CS2EMTGF.js +0 -1966
  54. package/dist/chunk-DMG7C4H2.js +0 -975
  55. package/dist/chunk-DXJQDCFL.js +0 -468
  56. package/dist/chunk-E3FWRT3Z.js +0 -608
  57. package/dist/chunk-E3UALNFA.js +0 -421
  58. package/dist/chunk-EONILVMF.js +0 -762
  59. package/dist/chunk-EQV4R3EV.cjs +0 -769
  60. package/dist/chunk-F3HH56EB.cjs +0 -5538
  61. package/dist/chunk-F4IULT7N.js +0 -1488
  62. package/dist/chunk-FF3Q7ADR.js +0 -380
  63. package/dist/chunk-FFKU7BTK.cjs +0 -1046
  64. package/dist/chunk-FHQVYCH2.js +0 -70
  65. package/dist/chunk-FSF7EQVA.cjs +0 -1974
  66. package/dist/chunk-G4VZTCIB.js +0 -659
  67. package/dist/chunk-G7CT3EMP.cjs +0 -1002
  68. package/dist/chunk-GGHSW2NN.js +0 -51334
  69. package/dist/chunk-GVUR45UF.cjs +0 -777
  70. package/dist/chunk-H5Z7NASB.js +0 -9662
  71. package/dist/chunk-HE7ULERA.cjs +0 -697
  72. package/dist/chunk-HJJLD366.js +0 -1169
  73. package/dist/chunk-HPS76H7Q.js +0 -309
  74. package/dist/chunk-HQUEA5R6.cjs +0 -424
  75. package/dist/chunk-HYNTS5CP.js +0 -422
  76. package/dist/chunk-I6XZ5DZF.cjs +0 -488
  77. package/dist/chunk-IBDG74G2.cjs +0 -1219
  78. package/dist/chunk-IFNQFCTM.js +0 -3098
  79. package/dist/chunk-IHOUYQIA.js +0 -406
  80. package/dist/chunk-ILRBGFVD.cjs +0 -72
  81. package/dist/chunk-IWI6J7FX.js +0 -421
  82. package/dist/chunk-K3JDKWGI.cjs +0 -270
  83. package/dist/chunk-K6EKD26I.js +0 -630
  84. package/dist/chunk-KCQ5NDYC.cjs +0 -3172
  85. package/dist/chunk-KED34ILP.js +0 -832
  86. package/dist/chunk-KSGXLT74.cjs +0 -457
  87. package/dist/chunk-L4G4RLXX.js +0 -767
  88. package/dist/chunk-LDP5OK6G.js +0 -1216
  89. package/dist/chunk-LGGRPKTV.cjs +0 -735
  90. package/dist/chunk-LK5IAVH6.cjs +0 -1173
  91. package/dist/chunk-LSW7P7ML.js +0 -3675
  92. package/dist/chunk-LXJ4667L.cjs +0 -3874
  93. package/dist/chunk-LZ266PCM.cjs +0 -4499
  94. package/dist/chunk-MD6KDHVE.cjs +0 -237
  95. package/dist/chunk-MEASWI2Y.js +0 -126
  96. package/dist/chunk-MPXBVFHQ.js +0 -768
  97. package/dist/chunk-N5FTS757.cjs +0 -415
  98. package/dist/chunk-NCUKG4SK.cjs +0 -3075
  99. package/dist/chunk-NDQNIJEH.js +0 -1715
  100. package/dist/chunk-NOZZ46QU.js +0 -168
  101. package/dist/chunk-OFKWH2IP.js +0 -449
  102. package/dist/chunk-PHENW4MQ.js +0 -65
  103. package/dist/chunk-PMGODDJA.cjs +0 -319
  104. package/dist/chunk-Q4QX3AET.cjs +0 -1505
  105. package/dist/chunk-Q56TT7IL.js +0 -483
  106. package/dist/chunk-Q5JT3YML.cjs +0 -129
  107. package/dist/chunk-Q5SJOGHQ.cjs +0 -4256
  108. package/dist/chunk-QGKNANZ3.js +0 -3071
  109. package/dist/chunk-QLEAOI3Q.cjs +0 -424
  110. package/dist/chunk-R7MA7QWV.js +0 -732
  111. package/dist/chunk-RVYPEYPX.js +0 -678
  112. package/dist/chunk-S2N5TNMA.js +0 -1855
  113. package/dist/chunk-S565K7NK.js +0 -752
  114. package/dist/chunk-SDAMZIRE.js +0 -765
  115. package/dist/chunk-T36DDXSF.js +0 -4250
  116. package/dist/chunk-T4NKMBDL.js +0 -5474
  117. package/dist/chunk-T7LEXZUZ.cjs +0 -2526
  118. package/dist/chunk-TEWCN33Y.js +0 -694
  119. package/dist/chunk-TQSZUOW5.cjs +0 -793
  120. package/dist/chunk-TSH3MSQU.cjs +0 -129
  121. package/dist/chunk-UERJ3YJV.js +0 -504
  122. package/dist/chunk-UPJBDCVF.js +0 -1395
  123. package/dist/chunk-V3NN3HPP.js +0 -4462
  124. package/dist/chunk-VJ3L7CHT.cjs +0 -169
  125. package/dist/chunk-WB4Z63GG.js +0 -229
  126. package/dist/chunk-WDW67DZB.cjs +0 -9728
  127. package/dist/chunk-WGMEAYBG.js +0 -126
  128. package/dist/chunk-X4ZF6CNE.cjs +0 -473
  129. package/dist/chunk-X6SEAXAX.cjs +0 -3681
  130. package/dist/chunk-XCWFGZAA.js +0 -1043
  131. package/dist/chunk-XD6IYDUX.js +0 -903
  132. package/dist/chunk-XG23EUQX.cjs +0 -1717
  133. package/dist/chunk-XRKWN5PL.cjs +0 -173
  134. package/dist/chunk-XUILI4KB.cjs +0 -430
  135. package/dist/chunk-XUTX5CBW.js +0 -126
  136. package/dist/chunk-XWPNTWDN.cjs +0 -755
  137. package/dist/chunk-XXINBTZK.cjs +0 -633
  138. package/dist/chunk-YCXFCXDS.js +0 -1868
  139. package/dist/chunk-YQK5JNFK.js +0 -3725
  140. package/dist/chunk-YYXH45E2.js +0 -426
  141. package/dist/chunk-Z34RLXRA.cjs +0 -612
  142. package/dist/chunk-ZP4D3CSX.cjs +0 -72
  143. package/dist/cli/holoscript-runner.cjs +0 -2259
  144. package/dist/cli/holoscript-runner.js +0 -2234
  145. package/dist/codebase/index.cjs +0 -336
  146. package/dist/codebase/index.js +0 -331
  147. package/dist/compiler/agent-inference.cjs +0 -28
  148. package/dist/compiler/agent-inference.js +0 -5
  149. package/dist/compiler/android-xr.cjs +0 -19
  150. package/dist/compiler/android-xr.js +0 -9
  151. package/dist/compiler/android.cjs +0 -20
  152. package/dist/compiler/android.js +0 -10
  153. package/dist/compiler/ar.cjs +0 -20
  154. package/dist/compiler/ar.js +0 -8
  155. package/dist/compiler/babylon.cjs +0 -17
  156. package/dist/compiler/babylon.js +0 -11
  157. package/dist/compiler/coco.cjs +0 -27
  158. package/dist/compiler/coco.js +0 -4
  159. package/dist/compiler/domain-block-utils.cjs +0 -602
  160. package/dist/compiler/domain-block-utils.js +0 -8
  161. package/dist/compiler/dtdl.cjs +0 -24
  162. package/dist/compiler/dtdl.js +0 -8
  163. package/dist/compiler/gltf-pipeline.cjs +0 -39
  164. package/dist/compiler/gltf-pipeline.js +0 -4
  165. package/dist/compiler/godot.cjs +0 -15
  166. package/dist/compiler/godot.js +0 -9
  167. package/dist/compiler/incremental.cjs +0 -29
  168. package/dist/compiler/incremental.js +0 -4
  169. package/dist/compiler/index.cjs +0 -2578
  170. package/dist/compiler/index.js +0 -2383
  171. package/dist/compiler/ios.cjs +0 -20
  172. package/dist/compiler/ios.js +0 -10
  173. package/dist/compiler/multi-layer.cjs +0 -20
  174. package/dist/compiler/multi-layer.js +0 -11
  175. package/dist/compiler/nodetoy.cjs +0 -23
  176. package/dist/compiler/nodetoy.js +0 -4
  177. package/dist/compiler/openxr.cjs +0 -15
  178. package/dist/compiler/openxr.js +0 -9
  179. package/dist/compiler/playcanvas.cjs +0 -16
  180. package/dist/compiler/playcanvas.js +0 -10
  181. package/dist/compiler/r3f.cjs +0 -34
  182. package/dist/compiler/r3f.js +0 -12
  183. package/dist/compiler/remotion.cjs +0 -23
  184. package/dist/compiler/remotion.js +0 -4
  185. package/dist/compiler/reproducibility.cjs +0 -39
  186. package/dist/compiler/reproducibility.js +0 -4
  187. package/dist/compiler/sdf.cjs +0 -21
  188. package/dist/compiler/sdf.js +0 -9
  189. package/dist/compiler/semantic-scene.cjs +0 -31
  190. package/dist/compiler/semantic-scene.js +0 -4
  191. package/dist/compiler/state.cjs +0 -17
  192. package/dist/compiler/state.js +0 -7
  193. package/dist/compiler/trait-composition.cjs +0 -26
  194. package/dist/compiler/trait-composition.js +0 -5
  195. package/dist/compiler/unity.cjs +0 -15
  196. package/dist/compiler/unity.js +0 -9
  197. package/dist/compiler/unreal.cjs +0 -19
  198. package/dist/compiler/unreal.js +0 -9
  199. package/dist/compiler/urdf.cjs +0 -45
  200. package/dist/compiler/urdf.js +0 -9
  201. package/dist/compiler/usd-physics.cjs +0 -23
  202. package/dist/compiler/usd-physics.js +0 -6
  203. package/dist/compiler/visionos.cjs +0 -15
  204. package/dist/compiler/visionos.js +0 -9
  205. package/dist/compiler/vrchat.cjs +0 -19
  206. package/dist/compiler/vrchat.js +0 -9
  207. package/dist/compiler/vrr.cjs +0 -21
  208. package/dist/compiler/vrr.js +0 -9
  209. package/dist/compiler/wasm.cjs +0 -33
  210. package/dist/compiler/wasm.js +0 -9
  211. package/dist/compiler/webgpu.cjs +0 -15
  212. package/dist/compiler/webgpu.js +0 -9
  213. package/dist/debugger.cjs +0 -21
  214. package/dist/debugger.js +0 -8
  215. package/dist/entries/interop.cjs +0 -62
  216. package/dist/entries/interop.js +0 -5
  217. package/dist/entries/scripting.cjs +0 -68
  218. package/dist/entries/scripting.js +0 -11
  219. package/dist/index.cjs +0 -40921
  220. package/dist/index.js +0 -37763
  221. package/dist/math/vec3.cjs +0 -57
  222. package/dist/math/vec3.js +0 -4
  223. package/dist/ml-dsa-PHCWUBPX.cjs +0 -1178
  224. package/dist/ml-dsa-WYLJHJO6.js +0 -1178
  225. package/dist/parser.cjs +0 -27
  226. package/dist/parser.js +0 -10
  227. package/dist/playwright-5OSAPTNH.js +0 -98660
  228. package/dist/playwright-RL6GY4F7.cjs +0 -98673
  229. package/dist/runtime.cjs +0 -16
  230. package/dist/runtime.js +0 -7
  231. package/dist/storage/index.cjs +0 -37
  232. package/dist/storage/index.js +0 -4
  233. package/dist/traits/index.cjs +0 -14649
  234. package/dist/traits/index.js +0 -12243
  235. package/dist/type-checker.cjs +0 -18
  236. package/dist/type-checker.js +0 -5
@@ -1,4462 +0,0 @@
1
- import { ErrorRecovery, generateQuickFixes, enrichErrorWithSuggestions, LIFECYCLE_HOOKS, STRUCTURAL_DIRECTIVES } from './chunk-MPXBVFHQ.js';
2
- import { VR_TRAITS } from './chunk-NDQNIJEH.js';
3
- import * as crypto from 'crypto';
4
-
5
- // src/parser/HybridChunker.ts
6
- function countTokens(text) {
7
- return Math.ceil(text.length / 4);
8
- }
9
- function detectFileType(filePath) {
10
- const ext = filePath.split(".").pop()?.toLowerCase() || "";
11
- if (["ts", "js", "jsx", "tsx", "hs", "hsplus"].includes(ext)) {
12
- return "code";
13
- }
14
- if (["log", "txt", "csv"].includes(ext)) {
15
- return "log";
16
- }
17
- if (["md", "mdx", "markdown"].includes(ext)) {
18
- return "markdown";
19
- }
20
- return "unknown";
21
- }
22
- var StructureBasedChunker = class {
23
- constructor(options) {
24
- this.options = {
25
- maxTokens: options.maxTokens || 1024,
26
- overlapTokens: options.overlapTokens || 100,
27
- semanticThreshold: options.semanticThreshold || 0.85,
28
- debug: options.debug || false
29
- };
30
- }
31
- /**
32
- * Chunk code files by detecting structural boundaries
33
- */
34
- chunk(content, filePath) {
35
- const lines = content.split("\n");
36
- const boundaries = this.detectStructuralBoundaries(lines);
37
- if (boundaries.length === 0) {
38
- return [
39
- {
40
- id: `structure:${filePath}:0`,
41
- type: "code-block",
42
- startLine: 1,
43
- endLine: lines.length,
44
- content,
45
- tokens: countTokens(content),
46
- strategy: "structure"
47
- }
48
- ];
49
- }
50
- const chunks = [];
51
- let currentChunk = [];
52
- let currentStart = 1;
53
- let chunkIndex = 0;
54
- for (let i = 0; i < boundaries.length; i++) {
55
- const boundary = boundaries[i];
56
- const segmentContent = lines.slice(boundary.startLine - 1, boundary.endLine).join("\n");
57
- const segmentTokens = countTokens(segmentContent);
58
- if (currentChunk.length > 0 && countTokens(currentChunk.join("\n") + "\n" + segmentContent) > this.options.maxTokens) {
59
- const chunkContent = currentChunk.join("\n");
60
- chunks.push({
61
- id: `structure:${filePath}:${chunkIndex++}`,
62
- type: "code-block",
63
- startLine: currentStart,
64
- endLine: currentStart + currentChunk.length - 1,
65
- content: chunkContent,
66
- tokens: countTokens(chunkContent),
67
- strategy: "structure"
68
- });
69
- currentChunk = [];
70
- currentStart = boundary.startLine;
71
- }
72
- if (segmentTokens > this.options.maxTokens) {
73
- const subChunks = this.recursiveSplit(
74
- segmentContent,
75
- boundary.startLine,
76
- filePath,
77
- chunkIndex
78
- );
79
- chunks.push(...subChunks);
80
- chunkIndex += subChunks.length;
81
- } else {
82
- currentChunk.push(segmentContent);
83
- }
84
- }
85
- if (currentChunk.length > 0) {
86
- const chunkContent = currentChunk.join("\n");
87
- chunks.push({
88
- id: `structure:${filePath}:${chunkIndex}`,
89
- type: "code-block",
90
- startLine: currentStart,
91
- endLine: currentStart + currentChunk.length - 1,
92
- content: chunkContent,
93
- tokens: countTokens(chunkContent),
94
- strategy: "structure"
95
- });
96
- }
97
- return chunks;
98
- }
99
- /**
100
- * Detect structural boundaries (functions, classes, interfaces)
101
- */
102
- detectStructuralBoundaries(lines) {
103
- const boundaries = [];
104
- let braceDepth = 0;
105
- let currentBlock = null;
106
- for (let i = 0; i < lines.length; i++) {
107
- const line = lines[i];
108
- const trimmed = line.trim();
109
- if (!currentBlock) {
110
- const functionMatch = trimmed.match(
111
- /^(export\s+)?(async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/
112
- );
113
- const classMatch = trimmed.match(
114
- /^(export\s+)?(abstract\s+)?class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/
115
- );
116
- const interfaceMatch = trimmed.match(/^(export\s+)?interface\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/);
117
- const methodMatch = trimmed.match(
118
- /^(public|private|protected|static)?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\([^)]*\)\s*[:{]/
119
- );
120
- if (functionMatch) {
121
- currentBlock = {
122
- type: "function",
123
- name: functionMatch[3],
124
- startLine: i + 1
125
- };
126
- } else if (classMatch) {
127
- currentBlock = {
128
- type: "class",
129
- name: classMatch[3],
130
- startLine: i + 1
131
- };
132
- } else if (interfaceMatch) {
133
- currentBlock = {
134
- type: "interface",
135
- name: interfaceMatch[2],
136
- startLine: i + 1
137
- };
138
- } else if (methodMatch) {
139
- currentBlock = {
140
- type: "method",
141
- name: methodMatch[2],
142
- startLine: i + 1
143
- };
144
- }
145
- }
146
- if (currentBlock) {
147
- for (const char of line) {
148
- if (char === "{") braceDepth++;
149
- if (char === "}") braceDepth--;
150
- }
151
- if (braceDepth === 0 && trimmed.includes("}")) {
152
- boundaries.push({
153
- type: currentBlock.type,
154
- name: currentBlock.name,
155
- startLine: currentBlock.startLine,
156
- endLine: i + 1
157
- });
158
- currentBlock = null;
159
- }
160
- }
161
- }
162
- if (currentBlock) {
163
- boundaries.push({
164
- type: currentBlock.type,
165
- name: currentBlock.name,
166
- startLine: currentBlock.startLine,
167
- endLine: lines.length
168
- });
169
- }
170
- return boundaries;
171
- }
172
- /**
173
- * Recursively split large segments
174
- */
175
- recursiveSplit(content, startLine, filePath, baseIndex) {
176
- const lines = content.split("\n");
177
- const chunks = [];
178
- let currentChunk = [];
179
- let currentStart = startLine;
180
- for (let i = 0; i < lines.length; i++) {
181
- currentChunk.push(lines[i]);
182
- if (countTokens(currentChunk.join("\n")) >= this.options.maxTokens) {
183
- const chunkContent = currentChunk.join("\n");
184
- chunks.push({
185
- id: `structure:${filePath}:${baseIndex + chunks.length}`,
186
- type: "code-fragment",
187
- startLine: currentStart,
188
- endLine: currentStart + currentChunk.length - 1,
189
- content: chunkContent,
190
- tokens: countTokens(chunkContent),
191
- strategy: "structure",
192
- metadata: { splitReason: "recursive-oversized" }
193
- });
194
- currentChunk = [];
195
- currentStart = startLine + i + 1;
196
- }
197
- }
198
- if (currentChunk.length > 0) {
199
- const chunkContent = currentChunk.join("\n");
200
- chunks.push({
201
- id: `structure:${filePath}:${baseIndex + chunks.length}`,
202
- type: "code-fragment",
203
- startLine: currentStart,
204
- endLine: currentStart + currentChunk.length - 1,
205
- content: chunkContent,
206
- tokens: countTokens(chunkContent),
207
- strategy: "structure"
208
- });
209
- }
210
- return chunks;
211
- }
212
- };
213
- var FixedSizeChunker = class {
214
- constructor(options) {
215
- this.options = {
216
- maxTokens: options.maxTokens || 1024,
217
- overlapTokens: options.overlapTokens || 100,
218
- semanticThreshold: options.semanticThreshold || 0.85,
219
- debug: options.debug || false
220
- };
221
- }
222
- /**
223
- * Chunk text files into fixed-size segments with overlap
224
- */
225
- chunk(content, filePath) {
226
- const lines = content.split("\n");
227
- const chunks = [];
228
- let currentChunk = [];
229
- let currentStart = 1;
230
- let chunkIndex = 0;
231
- for (let i = 0; i < lines.length; i++) {
232
- currentChunk.push(lines[i]);
233
- const currentTokens = countTokens(currentChunk.join("\n"));
234
- if (currentTokens >= this.options.maxTokens) {
235
- const chunkContent = currentChunk.join("\n");
236
- chunks.push({
237
- id: `fixed:${filePath}:${chunkIndex++}`,
238
- type: "text-block",
239
- startLine: currentStart,
240
- endLine: currentStart + currentChunk.length - 1,
241
- content: chunkContent,
242
- tokens: currentTokens,
243
- strategy: "fixed"
244
- });
245
- const overlapLines = this.calculateOverlapLines(currentChunk);
246
- currentChunk = overlapLines;
247
- currentStart = currentStart + currentChunk.length - overlapLines.length;
248
- }
249
- }
250
- if (currentChunk.length > 0) {
251
- const chunkContent = currentChunk.join("\n");
252
- chunks.push({
253
- id: `fixed:${filePath}:${chunkIndex}`,
254
- type: "text-block",
255
- startLine: currentStart,
256
- endLine: currentStart + currentChunk.length - 1,
257
- content: chunkContent,
258
- tokens: countTokens(chunkContent),
259
- strategy: "fixed"
260
- });
261
- }
262
- return chunks;
263
- }
264
- /**
265
- * Calculate overlap lines based on token count
266
- */
267
- calculateOverlapLines(lines) {
268
- const overlapLines = [];
269
- let overlapTokens = 0;
270
- for (let i = lines.length - 1; i >= 0; i--) {
271
- const lineTokens = countTokens(lines[i]);
272
- if (overlapTokens + lineTokens > this.options.overlapTokens) {
273
- break;
274
- }
275
- overlapLines.unshift(lines[i]);
276
- overlapTokens += lineTokens;
277
- }
278
- return overlapLines;
279
- }
280
- };
281
- var SemanticChunker = class {
282
- constructor(options) {
283
- this.options = {
284
- maxTokens: options.maxTokens || 1024,
285
- overlapTokens: options.overlapTokens || 100,
286
- semanticThreshold: options.semanticThreshold || 0.85,
287
- debug: options.debug || false
288
- };
289
- }
290
- /**
291
- * Chunk markdown/docs by semantic similarity
292
- */
293
- chunk(content, filePath) {
294
- const paragraphs = this.detectParagraphs(content);
295
- if (paragraphs.length === 0) {
296
- return [
297
- {
298
- id: `semantic:${filePath}:0`,
299
- type: "document",
300
- startLine: 1,
301
- endLine: content.split("\n").length,
302
- content,
303
- tokens: countTokens(content),
304
- strategy: "semantic"
305
- }
306
- ];
307
- }
308
- const chunks = [];
309
- let currentGroup = [];
310
- let chunkIndex = 0;
311
- for (let i = 0; i < paragraphs.length; i++) {
312
- const para = paragraphs[i];
313
- if (currentGroup.length === 0) {
314
- currentGroup.push(para);
315
- continue;
316
- }
317
- const lastPara = currentGroup[currentGroup.length - 1];
318
- const similarity2 = this.computeSimilarity(lastPara.content, para.content);
319
- const groupContent = currentGroup.map((p) => p.content).join("\n\n");
320
- const groupTokens = countTokens(groupContent + "\n\n" + para.content);
321
- if (similarity2 >= this.options.semanticThreshold && groupTokens <= this.options.maxTokens) {
322
- currentGroup.push(para);
323
- } else {
324
- const chunkContent = currentGroup.map((p) => p.content).join("\n\n");
325
- chunks.push({
326
- id: `semantic:${filePath}:${chunkIndex++}`,
327
- type: "semantic-group",
328
- startLine: currentGroup[0].startLine,
329
- endLine: currentGroup[currentGroup.length - 1].endLine,
330
- content: chunkContent,
331
- tokens: countTokens(chunkContent),
332
- strategy: "semantic",
333
- metadata: {
334
- paragraphCount: currentGroup.length
335
- }
336
- });
337
- currentGroup = [para];
338
- }
339
- }
340
- if (currentGroup.length > 0) {
341
- const chunkContent = currentGroup.map((p) => p.content).join("\n\n");
342
- chunks.push({
343
- id: `semantic:${filePath}:${chunkIndex}`,
344
- type: "semantic-group",
345
- startLine: currentGroup[0].startLine,
346
- endLine: currentGroup[currentGroup.length - 1].endLine,
347
- content: chunkContent,
348
- tokens: countTokens(chunkContent),
349
- strategy: "semantic",
350
- metadata: {
351
- paragraphCount: currentGroup.length
352
- }
353
- });
354
- }
355
- return chunks;
356
- }
357
- /**
358
- * Detect paragraph boundaries in markdown
359
- */
360
- detectParagraphs(content) {
361
- const lines = content.split("\n");
362
- const paragraphs = [];
363
- let currentPara = [];
364
- let currentStart = 1;
365
- for (let i = 0; i < lines.length; i++) {
366
- const line = lines[i];
367
- const trimmed = line.trim();
368
- if (trimmed === "" || trimmed.startsWith("#") || /^[-*+]\s/.test(trimmed) || /^\d+\.\s/.test(trimmed)) {
369
- if (currentPara.length > 0) {
370
- paragraphs.push({
371
- content: currentPara.join("\n"),
372
- startLine: currentStart,
373
- endLine: i
374
- });
375
- currentPara = [];
376
- }
377
- if (trimmed !== "") {
378
- currentPara.push(line);
379
- currentStart = i + 1;
380
- } else {
381
- currentStart = i + 2;
382
- }
383
- } else {
384
- currentPara.push(line);
385
- }
386
- }
387
- if (currentPara.length > 0) {
388
- paragraphs.push({
389
- content: currentPara.join("\n"),
390
- startLine: currentStart,
391
- endLine: lines.length
392
- });
393
- }
394
- return paragraphs;
395
- }
396
- /**
397
- * Compute similarity between two text segments
398
- *
399
- * Simple heuristic: Jaccard similarity of word sets
400
- * For production: Use sentence-transformers embeddings + cosine similarity
401
- */
402
- computeSimilarity(text1, text2) {
403
- const words1 = new Set(
404
- text1.toLowerCase().split(/\s+/).filter((w) => w.length > 3)
405
- );
406
- const words2 = new Set(
407
- text2.toLowerCase().split(/\s+/).filter((w) => w.length > 3)
408
- );
409
- const intersection = new Set([...words1].filter((w) => words2.has(w)));
410
- const union = /* @__PURE__ */ new Set([...words1, ...words2]);
411
- return union.size > 0 ? intersection.size / union.size : 0;
412
- }
413
- };
414
- var HybridChunker = class {
415
- constructor(options = {}) {
416
- this.options = {
417
- maxTokens: options.maxTokens || 1024,
418
- overlapTokens: options.overlapTokens || 100,
419
- semanticThreshold: options.semanticThreshold || 0.85,
420
- debug: options.debug || false
421
- };
422
- this.structureChunker = new StructureBasedChunker(this.options);
423
- this.fixedChunker = new FixedSizeChunker(this.options);
424
- this.semanticChunker = new SemanticChunker(this.options);
425
- }
426
- /**
427
- * Chunk a file using the optimal strategy
428
- */
429
- chunk(content, filePath) {
430
- const fileType = detectFileType(filePath);
431
- this.log(`Chunking ${filePath} (type: ${fileType})`);
432
- let chunks;
433
- switch (fileType) {
434
- case "code":
435
- chunks = this.structureChunker.chunk(content, filePath);
436
- break;
437
- case "log":
438
- chunks = this.fixedChunker.chunk(content, filePath);
439
- break;
440
- case "markdown":
441
- chunks = this.semanticChunker.chunk(content, filePath);
442
- break;
443
- default:
444
- this.log(`Unknown file type for ${filePath}, using fixed-size chunking`);
445
- chunks = this.fixedChunker.chunk(content, filePath);
446
- }
447
- this.log(
448
- `Generated ${chunks.length} chunks (${chunks.reduce((sum, c) => sum + c.tokens, 0)} total tokens)`
449
- );
450
- return chunks;
451
- }
452
- /**
453
- * Get chunking statistics
454
- */
455
- getStats(chunks) {
456
- const totalTokens = chunks.reduce((sum, c) => sum + c.tokens, 0);
457
- const strategyDistribution = {};
458
- for (const chunk of chunks) {
459
- strategyDistribution[chunk.strategy] = (strategyDistribution[chunk.strategy] || 0) + 1;
460
- }
461
- return {
462
- totalChunks: chunks.length,
463
- totalTokens,
464
- avgTokensPerChunk: chunks.length > 0 ? totalTokens / chunks.length : 0,
465
- strategyDistribution
466
- };
467
- }
468
- /**
469
- * Debug logging
470
- */
471
- log(message) {
472
- if (this.options.debug) {
473
- console.log(`[HybridChunker] ${message}`);
474
- }
475
- }
476
- };
477
- function createHybridChunker(options) {
478
- return new HybridChunker(options);
479
- }
480
-
481
- // src/parser/ChunkDetector.ts
482
- var ChunkDetector = class {
483
- /**
484
- * Detects chunks in the source code based on top-level keywords
485
- *
486
- * @deprecated Use detectHybrid() for better performance with multi-strategy chunking
487
- */
488
- static detect(source) {
489
- const lines = source.split(/\r?\n/);
490
- const chunks = [];
491
- let currentChunk = null;
492
- let braceDepth = 0;
493
- for (let i = 0; i < lines.length; i++) {
494
- const line = lines[i];
495
- const trimmed = line.trim();
496
- if (!currentChunk && (!trimmed || trimmed.startsWith("//"))) {
497
- continue;
498
- }
499
- if (!currentChunk) {
500
- const orbMatch = trimmed.match(/^orb\s+([a-zA-Z0-9_#"]+)/);
501
- const templateMatch = trimmed.match(/^template\s+"([^"]+)"/);
502
- const envMatch = trimmed.startsWith("environment");
503
- const logicMatch = trimmed.startsWith("logic");
504
- const directiveMatch = trimmed.startsWith("@");
505
- if (orbMatch || templateMatch || envMatch || logicMatch || directiveMatch) {
506
- currentChunk = {
507
- startLine: i + 1,
508
- content: line
509
- };
510
- if (orbMatch) {
511
- currentChunk.type = "orb";
512
- currentChunk.name = orbMatch[1].replace(/[#"]/g, "");
513
- currentChunk.id = `orb:${currentChunk.name}`;
514
- } else if (templateMatch) {
515
- currentChunk.type = "template";
516
- currentChunk.name = templateMatch[1];
517
- currentChunk.id = `template:${currentChunk.name}`;
518
- } else if (envMatch) {
519
- currentChunk.type = "environment";
520
- currentChunk.id = `environment:${i + 1}`;
521
- } else if (logicMatch) {
522
- currentChunk.type = "logic";
523
- currentChunk.id = `logic:${i + 1}`;
524
- } else if (directiveMatch) {
525
- currentChunk.type = "directive";
526
- if (!trimmed.includes("{")) {
527
- currentChunk.endLine = i + 1;
528
- currentChunk.id = `directive:${i + 1}`;
529
- chunks.push(currentChunk);
530
- currentChunk = null;
531
- continue;
532
- }
533
- currentChunk.id = `directive:${i + 1}`;
534
- }
535
- }
536
- } else {
537
- currentChunk.content += "\n" + line;
538
- }
539
- if (currentChunk) {
540
- for (const char of line) {
541
- if (char === "{") braceDepth++;
542
- if (char === "}") braceDepth--;
543
- }
544
- if (braceDepth === 0) {
545
- currentChunk.endLine = i + 1;
546
- chunks.push(currentChunk);
547
- currentChunk = null;
548
- }
549
- }
550
- }
551
- if (currentChunk) {
552
- currentChunk.endLine = lines.length;
553
- chunks.push(currentChunk);
554
- }
555
- return chunks;
556
- }
557
- /**
558
- * Detect chunks using HybridChunker (structure-based + semantic + fixed-size)
559
- *
560
- * Routes .hs/.hsplus files to structure-based chunking for better performance.
561
- * This method provides 20-30% better parsing speed by using AST-aware boundaries.
562
- *
563
- * @param source - Source code content
564
- * @param filePath - File path for type detection (defaults to .hsplus)
565
- * @param options - Chunking options
566
- */
567
- static detectHybrid(source, filePath = "file.hsplus", options) {
568
- const hybridChunker = createHybridChunker(options);
569
- const chunks = hybridChunker.chunk(source, filePath);
570
- return chunks.map((chunk) => ({
571
- id: chunk.id,
572
- type: this.mapChunkType(chunk.type),
573
- name: chunk.name,
574
- startLine: chunk.startLine,
575
- endLine: chunk.endLine,
576
- content: chunk.content,
577
- tokens: chunk.tokens,
578
- strategy: chunk.strategy,
579
- metadata: chunk.metadata
580
- }));
581
- }
582
- /**
583
- * Map HybridChunker types to ChunkDetector types
584
- */
585
- static mapChunkType(hybridType) {
586
- if (hybridType.includes("class")) return "template";
587
- if (hybridType.includes("function")) return "logic";
588
- return "unknown";
589
- }
590
- };
591
- var ParseCache = class {
592
- constructor(maxEntries = 500) {
593
- this.cache = /* @__PURE__ */ new Map();
594
- this.evictionCount = 0;
595
- /** Monotonically increasing counter for reliable LRU ordering */
596
- this.clock = 0;
597
- this.maxEntries = maxEntries;
598
- }
599
- /**
600
- * Generates a hash for the chunk content
601
- */
602
- static hash(content) {
603
- return crypto.createHash("sha256").update(content).digest("hex");
604
- }
605
- /**
606
- * Retrieves a cached node if the hash matches
607
- */
608
- get(id, currentHash) {
609
- const cached = this.cache.get(id);
610
- if (cached && cached.hash === currentHash) {
611
- cached.lastUsed = ++this.clock;
612
- return cached.node;
613
- }
614
- return null;
615
- }
616
- /**
617
- * Stores a node in the cache
618
- */
619
- set(id, hash, node) {
620
- if (this.cache.size >= this.maxEntries) {
621
- this.evictOldest();
622
- }
623
- this.cache.set(id, {
624
- id,
625
- hash,
626
- node,
627
- lastUsed: ++this.clock
628
- });
629
- }
630
- /**
631
- * Clears the entire cache
632
- */
633
- clear() {
634
- this.cache.clear();
635
- }
636
- /**
637
- * Returns cache statistics: current size, total evictions, and capacity.
638
- */
639
- getStats() {
640
- return {
641
- size: this.cache.size,
642
- evictions: this.evictionCount,
643
- maxEntries: this.maxEntries
644
- };
645
- }
646
- evictOldest() {
647
- let oldestId = null;
648
- let oldestTime = Infinity;
649
- for (const [id, entry] of this.cache.entries()) {
650
- if (entry.lastUsed < oldestTime) {
651
- oldestTime = entry.lastUsed;
652
- oldestId = id;
653
- }
654
- }
655
- if (oldestId) {
656
- this.cache.delete(oldestId);
657
- this.evictionCount++;
658
- }
659
- }
660
- };
661
- var globalParseCache = new ParseCache();
662
-
663
- // src/parser/RichErrors.ts
664
- var HSPLUS_ERROR_CODES = {
665
- // Syntax Errors (HSP001-HSP099)
666
- HSP001: "Unexpected token",
667
- HSP002: "Expected identifier",
668
- HSP003: "Expected keyword",
669
- HSP004: "Unclosed brace - missing }",
670
- HSP005: "Unclosed bracket - missing ]",
671
- HSP006: "Unclosed parenthesis - missing )",
672
- HSP007: "Unclosed string literal",
673
- HSP008: "Invalid number format",
674
- HSP009: "Missing colon after property name",
675
- HSP010: "Missing value after colon",
676
- // Structure Errors (HSP100-HSP199)
677
- HSP100: "Invalid composition structure",
678
- HSP101: "Invalid object definition",
679
- HSP102: "Invalid template definition",
680
- HSP103: "Invalid spatial_group definition",
681
- HSP104: "Invalid environment block",
682
- HSP105: "Invalid state block",
683
- HSP106: "Invalid logic block",
684
- HSP107: "Duplicate identifier",
685
- HSP108: "Missing required property",
686
- // Trait Errors (HSP200-HSP299)
687
- HSP200: "Unknown trait",
688
- HSP201: "Invalid trait syntax",
689
- HSP202: "Missing trait argument",
690
- HSP203: "Invalid trait argument type",
691
- HSP204: "Trait not allowed in this context",
692
- HSP205: "Duplicate trait",
693
- // Expression Errors (HSP300-HSP399)
694
- HSP300: "Invalid expression",
695
- HSP301: "Undefined variable",
696
- HSP302: "Invalid operator",
697
- HSP303: "Type mismatch",
698
- HSP304: "Invalid function call",
699
- HSP305: "Missing function argument",
700
- // Import/Module Errors (HSP400-HSP499)
701
- HSP400: "Invalid import statement",
702
- HSP401: "Module not found",
703
- HSP402: "Circular import detected",
704
- // Limit Errors (HSP900-HSP999)
705
- HSP900: "Maximum nesting depth exceeded",
706
- HSP901: "Maximum array length exceeded",
707
- HSP902: "Maximum string length exceeded"
708
- };
709
- function levenshteinDistance(a, b) {
710
- const matrix = [];
711
- for (let i = 0; i <= b.length; i++) {
712
- matrix[i] = [i];
713
- }
714
- for (let j = 0; j <= a.length; j++) {
715
- matrix[0][j] = j;
716
- }
717
- for (let i = 1; i <= b.length; i++) {
718
- for (let j = 1; j <= a.length; j++) {
719
- if (b.charAt(i - 1) === a.charAt(j - 1)) {
720
- matrix[i][j] = matrix[i - 1][j - 1];
721
- } else {
722
- matrix[i][j] = Math.min(
723
- matrix[i - 1][j - 1] + 1,
724
- // substitution
725
- matrix[i][j - 1] + 1,
726
- // insertion
727
- matrix[i - 1][j] + 1
728
- // deletion
729
- );
730
- }
731
- }
732
- }
733
- return matrix[b.length][a.length];
734
- }
735
- function similarity(a, b) {
736
- const aLower = a.toLowerCase();
737
- const bLower = b.toLowerCase();
738
- if (aLower === bLower) return 1;
739
- if (bLower.startsWith(aLower) || aLower.startsWith(bLower)) {
740
- return 0.9;
741
- }
742
- const maxLen = Math.max(a.length, b.length);
743
- if (maxLen === 0) return 1;
744
- const distance = levenshteinDistance(aLower, bLower);
745
- return 1 - distance / maxLen;
746
- }
747
- function findSimilarTrait(input, threshold = 0.5) {
748
- let bestMatch;
749
- let bestScore = threshold;
750
- for (const trait of VR_TRAITS) {
751
- const score = similarity(input, trait);
752
- if (score > bestScore) {
753
- bestScore = score;
754
- bestMatch = trait;
755
- }
756
- }
757
- return bestMatch;
758
- }
759
- function findSimilarKeyword(input, threshold = 0.5) {
760
- const keywords = [
761
- "composition",
762
- "object",
763
- "template",
764
- "spatial_group",
765
- "environment",
766
- "state",
767
- "logic",
768
- "on_click",
769
- "on_hover",
770
- "on_enter",
771
- "on_exit",
772
- "position",
773
- "rotation",
774
- "scale",
775
- "color",
776
- "model",
777
- "geometry",
778
- "visible",
779
- "opacity",
780
- "material",
781
- "physics",
782
- "audio",
783
- "animation",
784
- "true",
785
- "false",
786
- "null",
787
- "if",
788
- "else",
789
- "for",
790
- "while",
791
- "function",
792
- "let",
793
- "const",
794
- "return",
795
- "import",
796
- "from",
797
- "using",
798
- "spawn",
799
- "emit"
800
- ];
801
- let bestMatch;
802
- let bestScore = threshold;
803
- for (const keyword of keywords) {
804
- const score = similarity(input, keyword);
805
- if (score > bestScore) {
806
- bestScore = score;
807
- bestMatch = keyword;
808
- }
809
- }
810
- return bestMatch;
811
- }
812
- function getSourceContext(source, line, column, contextLines = 2) {
813
- const lines = source.split("\n");
814
- const result = [];
815
- const startLine = Math.max(1, line - contextLines);
816
- const endLine = Math.min(lines.length, line + contextLines);
817
- const maxLineNum = endLine;
818
- const padding = String(maxLineNum).length;
819
- for (let i = startLine; i <= endLine; i++) {
820
- const lineContent = lines[i - 1] || "";
821
- const lineNum = String(i).padStart(padding, " ");
822
- const prefix = i === line ? ">" : " ";
823
- result.push(`${prefix} ${lineNum} | ${lineContent}`);
824
- if (i === line) {
825
- const indicator = " ".repeat(padding + 4 + Math.max(0, column - 1)) + "^";
826
- result.push(indicator);
827
- }
828
- }
829
- return result.join("\n");
830
- }
831
- function createRichError(code, message, line, column, options = {}) {
832
- const { source, suggestion, severity = "error", endLine, endColumn } = options;
833
- return {
834
- code,
835
- message: `${code}: ${message}`,
836
- line,
837
- column,
838
- endLine,
839
- endColumn,
840
- context: source ? getSourceContext(source, line, column) : void 0,
841
- suggestion,
842
- severity
843
- };
844
- }
845
- function createTraitError(traitName, line, column, source) {
846
- const similar = findSimilarTrait(traitName);
847
- const suggestion = similar ? `Did you mean '@${similar}'?` : void 0;
848
- return createRichError("HSP200", `Unknown trait '@${traitName}'`, line, column, {
849
- source,
850
- suggestion
851
- });
852
- }
853
- function createKeywordError(found, expected, line, column, source) {
854
- const similar = findSimilarKeyword(found);
855
- const suggestion = similar ? `Did you mean '${similar}'?` : `Expected '${expected}'`;
856
- return createRichError("HSP003", `Expected '${expected}' but found '${found}'`, line, column, {
857
- source,
858
- suggestion
859
- });
860
- }
861
- function formatRichError(error) {
862
- const lines = [];
863
- const icon = error.severity === "error" ? "\u274C" : error.severity === "warning" ? "\u26A0\uFE0F" : "\u2139\uFE0F";
864
- lines.push(`${icon} ${error.message}`);
865
- lines.push(` at line ${error.line}, column ${error.column}`);
866
- if (error.context) {
867
- lines.push("");
868
- lines.push(error.context);
869
- }
870
- if (error.suggestion) {
871
- lines.push("");
872
- lines.push(`\u{1F4A1} ${error.suggestion}`);
873
- }
874
- lines.push("");
875
- lines.push(`\u{1F4D6} See: https://holoscript.net/errors/${error.code}`);
876
- return lines.join("\n");
877
- }
878
- function formatRichErrors(errors) {
879
- if (errors.length === 0) {
880
- return "\u2705 No errors found";
881
- }
882
- const lines = [];
883
- const errorCount = errors.filter((e) => e.severity === "error").length;
884
- const warningCount = errors.filter((e) => e.severity === "warning").length;
885
- lines.push(`Found ${errorCount} error(s) and ${warningCount} warning(s):`);
886
- lines.push("");
887
- const displayErrors = errors.slice(0, 10);
888
- for (let i = 0; i < displayErrors.length; i++) {
889
- lines.push(`[${i + 1}/${errors.length}] \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
890
- lines.push(formatRichError(displayErrors[i]));
891
- lines.push("");
892
- }
893
- if (errors.length > 10) {
894
- lines.push(`... and ${errors.length - 10} more errors`);
895
- }
896
- return lines.join("\n");
897
- }
898
- function getErrorCodeDocumentation() {
899
- const docs = [];
900
- for (const [code, description] of Object.entries(HSPLUS_ERROR_CODES)) {
901
- let category = "General";
902
- const num = parseInt(code.replace("HSP", ""), 10);
903
- if (num < 100) category = "Syntax";
904
- else if (num < 200) category = "Structure";
905
- else if (num < 300) category = "Traits";
906
- else if (num < 400) category = "Expressions";
907
- else if (num < 500) category = "Imports";
908
- else if (num >= 900) category = "Limits";
909
- docs.push({ code, description, category });
910
- }
911
- return docs;
912
- }
913
-
914
- // src/parser/HoloScriptPlusParser.ts
915
- var Lexer = class {
916
- constructor(source) {
917
- this.pos = 0;
918
- this.line = 1;
919
- this.column = 1;
920
- this.indentStack = [0];
921
- this.tokens = [];
922
- this.pendingDedents = 0;
923
- this.source = source;
924
- }
925
- tokenize() {
926
- while (this.pos < this.source.length) {
927
- while (this.pendingDedents > 0) {
928
- this.tokens.push(this.createToken("DEDENT", ""));
929
- this.pendingDedents--;
930
- }
931
- const char = this.source[this.pos];
932
- if (char === " " || char === " ") {
933
- if (this.column === 1) {
934
- this.handleIndentation();
935
- } else {
936
- this.advance();
937
- }
938
- continue;
939
- }
940
- if (char === "/" && this.peek(1) === "/") {
941
- this.skipLineComment();
942
- continue;
943
- }
944
- if (char === "\n") {
945
- this.advance();
946
- this.tokens.push(this.createToken("NEWLINE", "\n"));
947
- this.line++;
948
- this.column = 1;
949
- continue;
950
- }
951
- if (char === "\r") {
952
- const startOff = this.pos;
953
- this.advance();
954
- if (this.peek() === "\n") {
955
- this.advance();
956
- }
957
- const token = this.createToken("NEWLINE", "\n");
958
- token.offset = startOff;
959
- this.tokens.push(token);
960
- this.line++;
961
- this.column = 1;
962
- continue;
963
- }
964
- if (char === "{") {
965
- this.advance();
966
- this.tokens.push(this.createToken("LBRACE", "{"));
967
- continue;
968
- }
969
- if (char === "}") {
970
- this.advance();
971
- this.tokens.push(this.createToken("RBRACE", "}"));
972
- continue;
973
- }
974
- if (char === "[") {
975
- this.advance();
976
- this.tokens.push(this.createToken("LBRACKET", "["));
977
- continue;
978
- }
979
- if (char === "]") {
980
- this.advance();
981
- this.tokens.push(this.createToken("RBRACKET", "]"));
982
- continue;
983
- }
984
- if (char === "(") {
985
- this.advance();
986
- this.tokens.push(this.createToken("LPAREN", "("));
987
- continue;
988
- }
989
- if (char === ")") {
990
- this.advance();
991
- this.tokens.push(this.createToken("RPAREN", ")"));
992
- continue;
993
- }
994
- if (char === ":") {
995
- this.advance();
996
- this.tokens.push(this.createToken("COLON", ":"));
997
- continue;
998
- }
999
- if (char === ",") {
1000
- this.advance();
1001
- this.tokens.push(this.createToken("COMMA", ","));
1002
- continue;
1003
- }
1004
- if (char === "@") {
1005
- this.advance();
1006
- this.tokens.push(this.createToken("AT", "@"));
1007
- continue;
1008
- }
1009
- if (char === "#") {
1010
- this.advance();
1011
- this.tokens.push(this.createToken("HASH", "#"));
1012
- continue;
1013
- }
1014
- if (char === ".") {
1015
- if (this.peek(1) === "." && this.peek(2) === ".") {
1016
- const startCol = this.column;
1017
- this.advance();
1018
- this.advance();
1019
- this.advance();
1020
- this.tokens.push(this.createToken("SPREAD", "..."));
1021
- this.tokens[this.tokens.length - 1].column = startCol;
1022
- continue;
1023
- }
1024
- this.advance();
1025
- this.tokens.push(this.createToken("DOT", "."));
1026
- continue;
1027
- }
1028
- if (char === "+") {
1029
- this.advance();
1030
- this.tokens.push(this.createToken("PLUS", "+"));
1031
- continue;
1032
- }
1033
- if (char === "-") {
1034
- if (this.peek(1) === ">") {
1035
- const startCol = this.column;
1036
- this.advance();
1037
- this.advance();
1038
- this.tokens.push(this.createToken("ARROW", "->"));
1039
- this.tokens[this.tokens.length - 1].column = startCol;
1040
- continue;
1041
- }
1042
- this.advance();
1043
- this.tokens.push(this.createToken("MINUS", "-"));
1044
- continue;
1045
- }
1046
- if (char === "*") {
1047
- this.advance();
1048
- this.tokens.push(this.createToken("ASTERISK", "*"));
1049
- continue;
1050
- }
1051
- if (char === "/") {
1052
- if (this.peek(1) === "*") {
1053
- this.skipBlockComment();
1054
- continue;
1055
- }
1056
- if (this.peek(1) === "/") {
1057
- this.skipLineComment();
1058
- continue;
1059
- }
1060
- this.advance();
1061
- this.tokens.push(this.createToken("SLASH", "/"));
1062
- continue;
1063
- }
1064
- if (char === "%") {
1065
- this.advance();
1066
- this.tokens.push(this.createToken("PERCENT", "%"));
1067
- continue;
1068
- }
1069
- if (char === "!") {
1070
- if (this.peek(1) === "=") {
1071
- const startCol = this.column;
1072
- const startOff = this.pos;
1073
- this.advance();
1074
- this.advance();
1075
- this.tokens.push(this.createToken("NOT_EQUALS", "!="));
1076
- this.tokens[this.tokens.length - 1].column = startCol;
1077
- this.tokens[this.tokens.length - 1].offset = startOff;
1078
- continue;
1079
- }
1080
- this.advance();
1081
- this.tokens.push(this.createToken("EXCLAMATION", "!"));
1082
- continue;
1083
- }
1084
- if (char === "=") {
1085
- if (this.peek(1) === ">") {
1086
- const startCol = this.column;
1087
- const startOff = this.pos;
1088
- this.advance();
1089
- this.advance();
1090
- this.tokens.push(this.createToken("ARROW", "=>"));
1091
- this.tokens[this.tokens.length - 1].column = startCol;
1092
- this.tokens[this.tokens.length - 1].offset = startOff;
1093
- continue;
1094
- }
1095
- if (this.peek(1) === "=") {
1096
- const startCol = this.column;
1097
- const startOff = this.pos;
1098
- this.advance();
1099
- this.advance();
1100
- this.tokens.push(this.createToken("DOUBLE_EQUALS", "=="));
1101
- this.tokens[this.tokens.length - 1].column = startCol;
1102
- this.tokens[this.tokens.length - 1].offset = startOff;
1103
- continue;
1104
- }
1105
- this.advance();
1106
- this.tokens.push(this.createToken("EQUALS", "="));
1107
- continue;
1108
- }
1109
- if (char === "<") {
1110
- if (this.peek(1) === "=") {
1111
- const startCol = this.column;
1112
- const startOff = this.pos;
1113
- this.advance();
1114
- this.advance();
1115
- this.tokens.push(this.createToken("LESS_EQUAL", "<="));
1116
- this.tokens[this.tokens.length - 1].column = startCol;
1117
- this.tokens[this.tokens.length - 1].offset = startOff;
1118
- continue;
1119
- }
1120
- this.advance();
1121
- this.tokens.push(this.createToken("LESS_THAN", "<"));
1122
- continue;
1123
- }
1124
- if (char === ">") {
1125
- if (this.peek(1) === "=") {
1126
- const startCol = this.column;
1127
- const startOff = this.pos;
1128
- this.advance();
1129
- this.advance();
1130
- this.tokens.push(this.createToken("GREATER_EQUAL", ">="));
1131
- this.tokens[this.tokens.length - 1].column = startCol;
1132
- this.tokens[this.tokens.length - 1].offset = startOff;
1133
- continue;
1134
- }
1135
- this.advance();
1136
- this.tokens.push(this.createToken("GREATER_THAN", ">"));
1137
- continue;
1138
- }
1139
- if (char === "-") {
1140
- if (this.peek(1) === ">") {
1141
- const startCol = this.column;
1142
- this.advance();
1143
- this.advance();
1144
- this.tokens.push(this.createToken("ARROW", "->"));
1145
- this.tokens[this.tokens.length - 1].column = startCol;
1146
- continue;
1147
- }
1148
- }
1149
- if (char === "&") {
1150
- if (this.peek(1) === "&") {
1151
- const startCol = this.column;
1152
- const startOff = this.pos;
1153
- this.advance();
1154
- this.advance();
1155
- this.tokens.push(this.createToken("AND", "&&"));
1156
- this.tokens[this.tokens.length - 1].column = startCol;
1157
- this.tokens[this.tokens.length - 1].offset = startOff;
1158
- continue;
1159
- }
1160
- this.advance();
1161
- continue;
1162
- }
1163
- if (char === "|") {
1164
- if (this.peek(1) === "|") {
1165
- const startCol = this.column;
1166
- const startOff = this.pos;
1167
- this.advance();
1168
- this.advance();
1169
- this.tokens.push(this.createToken("OR", "||"));
1170
- this.tokens[this.tokens.length - 1].column = startCol;
1171
- this.tokens[this.tokens.length - 1].offset = startOff;
1172
- continue;
1173
- }
1174
- this.advance();
1175
- this.tokens.push(this.createToken("PIPE", "|"));
1176
- continue;
1177
- }
1178
- if (char === '"' || char === "'") {
1179
- this.tokens.push(this.readString(char));
1180
- continue;
1181
- }
1182
- if (this.isDigit(char) || char === "-" && this.isDigit(this.peek(1))) {
1183
- this.tokens.push(this.readNumber());
1184
- continue;
1185
- }
1186
- if (char === "?") {
1187
- if (this.peek(1) === "?") {
1188
- if (this.peek(2) === "=") {
1189
- const startCol2 = this.column;
1190
- const startOff2 = this.pos;
1191
- this.advance();
1192
- this.advance();
1193
- this.advance();
1194
- this.tokens.push(this.createToken("NULL_COALESCE_ASSIGN", "??="));
1195
- this.tokens[this.tokens.length - 1].column = startCol2;
1196
- this.tokens[this.tokens.length - 1].offset = startOff2;
1197
- continue;
1198
- }
1199
- const startCol = this.column;
1200
- const startOff = this.pos;
1201
- this.advance();
1202
- this.advance();
1203
- this.tokens.push(this.createToken("NULL_COALESCE", "??"));
1204
- this.tokens[this.tokens.length - 1].column = startCol;
1205
- this.tokens[this.tokens.length - 1].offset = startOff;
1206
- continue;
1207
- }
1208
- if (this.peek(1) === ".") {
1209
- const startCol = this.column;
1210
- const startOff = this.pos;
1211
- this.advance();
1212
- this.advance();
1213
- this.tokens.push(this.createToken("OPTIONAL_DOT", "?."));
1214
- this.tokens[this.tokens.length - 1].column = startCol;
1215
- this.tokens[this.tokens.length - 1].offset = startOff;
1216
- continue;
1217
- }
1218
- this.advance();
1219
- this.tokens.push(this.createToken("QUESTION", "?"));
1220
- continue;
1221
- }
1222
- if (char === "`") {
1223
- this.tokens.push(this.readTemplateString());
1224
- continue;
1225
- }
1226
- if (this.isIdentifierStart(char)) {
1227
- this.tokens.push(this.readIdentifier());
1228
- continue;
1229
- }
1230
- this.advance();
1231
- }
1232
- while (this.indentStack.length > 1) {
1233
- this.tokens.push(this.createToken("DEDENT", ""));
1234
- this.indentStack.pop();
1235
- }
1236
- this.tokens.push(this.createToken("EOF", ""));
1237
- return this.tokens;
1238
- }
1239
- advance() {
1240
- const char = this.source[this.pos];
1241
- this.pos++;
1242
- this.column++;
1243
- return char;
1244
- }
1245
- peek(offset = 0) {
1246
- const pos = this.pos + offset;
1247
- return pos < this.source.length ? this.source[pos] : "";
1248
- }
1249
- createToken(type, value) {
1250
- const token = {
1251
- type,
1252
- value,
1253
- line: this.line,
1254
- column: this.column - (value.length || 0),
1255
- offset: this.pos - (value.length || 0)
1256
- };
1257
- return token;
1258
- }
1259
- handleIndentation() {
1260
- let indent = 0;
1261
- while (this.peek() === " " || this.peek() === " ") {
1262
- indent += this.peek() === " " ? 4 : 1;
1263
- this.advance();
1264
- }
1265
- if (this.peek() === "\n" || this.peek() === "\r") {
1266
- return;
1267
- }
1268
- const currentIndent = this.indentStack[this.indentStack.length - 1];
1269
- if (indent > currentIndent) {
1270
- this.indentStack.push(indent);
1271
- this.tokens.push(this.createToken("INDENT", ""));
1272
- } else if (indent < currentIndent) {
1273
- while (this.indentStack.length > 1 && indent < this.indentStack[this.indentStack.length - 1]) {
1274
- this.indentStack.pop();
1275
- this.pendingDedents++;
1276
- }
1277
- }
1278
- }
1279
- skipLineComment() {
1280
- while (this.peek() !== "\n" && this.pos < this.source.length) {
1281
- this.advance();
1282
- }
1283
- }
1284
- skipBlockComment() {
1285
- this.advance();
1286
- this.advance();
1287
- while (this.pos < this.source.length) {
1288
- if (this.peek() === "*" && this.peek(1) === "/") {
1289
- this.advance();
1290
- this.advance();
1291
- break;
1292
- }
1293
- if (this.peek() === "\n") {
1294
- this.line++;
1295
- this.column = 0;
1296
- }
1297
- this.advance();
1298
- }
1299
- }
1300
- readString(quote) {
1301
- const startLine = this.line;
1302
- const startColumn = this.column;
1303
- this.advance();
1304
- let value = "";
1305
- while (this.peek() !== quote && this.pos < this.source.length) {
1306
- if (this.peek() === "\\") {
1307
- this.advance();
1308
- const escaped = this.advance();
1309
- switch (escaped) {
1310
- case "n":
1311
- value += "\n";
1312
- break;
1313
- case "t":
1314
- value += " ";
1315
- break;
1316
- case "r":
1317
- value += "\r";
1318
- break;
1319
- case "\\":
1320
- value += "\\";
1321
- break;
1322
- case '"':
1323
- value += '"';
1324
- break;
1325
- case "'":
1326
- value += "'";
1327
- break;
1328
- default:
1329
- value += escaped;
1330
- }
1331
- } else if (this.peek() === "\n") {
1332
- this.line++;
1333
- this.column = 0;
1334
- value += this.advance();
1335
- } else {
1336
- value += this.advance();
1337
- }
1338
- }
1339
- this.advance();
1340
- const token = {
1341
- type: "STRING",
1342
- value,
1343
- line: startLine,
1344
- column: startColumn,
1345
- offset: this.pos - (value.length + 2)
1346
- // approximation for start of string
1347
- };
1348
- return token;
1349
- }
1350
- readTemplateString() {
1351
- const startLine = this.line;
1352
- const startColumn = this.column;
1353
- const startOff = this.pos;
1354
- this.advance();
1355
- let value = "";
1356
- let braceDepth = 0;
1357
- while (this.pos < this.source.length) {
1358
- const c = this.source[this.pos];
1359
- if (c === "`" && braceDepth === 0) {
1360
- this.advance();
1361
- break;
1362
- }
1363
- if (c === "$" && this.peek(1) === "{") {
1364
- braceDepth++;
1365
- value += "${";
1366
- this.advance();
1367
- this.advance();
1368
- continue;
1369
- }
1370
- if (c === "{" && braceDepth > 0) {
1371
- braceDepth++;
1372
- value += c;
1373
- this.advance();
1374
- continue;
1375
- }
1376
- if (c === "}" && braceDepth > 0) {
1377
- braceDepth--;
1378
- value += c;
1379
- this.advance();
1380
- continue;
1381
- }
1382
- if (c === "\n") {
1383
- this.line++;
1384
- this.column = 0;
1385
- }
1386
- value += c;
1387
- this.advance();
1388
- }
1389
- return {
1390
- type: "TEMPLATE_STRING",
1391
- value,
1392
- line: startLine,
1393
- column: startColumn,
1394
- offset: startOff
1395
- };
1396
- }
1397
- readNumber() {
1398
- const startColumn = this.column;
1399
- let value = "";
1400
- if (this.peek() === "-") {
1401
- value += this.advance();
1402
- }
1403
- while (this.isDigit(this.peek())) {
1404
- value += this.advance();
1405
- }
1406
- if (this.peek() === "." && this.isDigit(this.peek(1))) {
1407
- value += this.advance();
1408
- while (this.isDigit(this.peek())) {
1409
- value += this.advance();
1410
- }
1411
- }
1412
- if (this.peek() === "e" || this.peek() === "E") {
1413
- value += this.advance();
1414
- if (this.peek() === "+" || this.peek() === "-") {
1415
- value += this.advance();
1416
- }
1417
- while (this.isDigit(this.peek())) {
1418
- value += this.advance();
1419
- }
1420
- }
1421
- while (this.isAlpha(this.peek()) || this.peek() === "%") {
1422
- value += this.advance();
1423
- }
1424
- const token = {
1425
- type: "NUMBER",
1426
- value,
1427
- line: this.line,
1428
- column: startColumn,
1429
- offset: this.pos - value.length
1430
- };
1431
- return token;
1432
- }
1433
- readExpression() {
1434
- const startLine = this.line;
1435
- const startColumn = this.column;
1436
- this.advance();
1437
- this.advance();
1438
- let value = "";
1439
- let braceDepth = 1;
1440
- while (braceDepth > 0 && this.pos < this.source.length) {
1441
- if (this.peek() === "{") {
1442
- braceDepth++;
1443
- } else if (this.peek() === "}") {
1444
- braceDepth--;
1445
- if (braceDepth === 0) {
1446
- break;
1447
- }
1448
- }
1449
- if (this.peek() === "\n") {
1450
- this.line++;
1451
- this.column = 0;
1452
- }
1453
- value += this.advance();
1454
- }
1455
- this.advance();
1456
- return {
1457
- type: "EXPRESSION",
1458
- value: value.trim(),
1459
- line: startLine,
1460
- column: startColumn,
1461
- offset: this.pos - (value.length + 3)
1462
- // ${...}
1463
- };
1464
- }
1465
- readIdentifier() {
1466
- const startColumn = this.column;
1467
- let value = "";
1468
- while (this.isIdentifierPart(this.peek())) {
1469
- value += this.advance();
1470
- }
1471
- if (value === "true" || value === "false") {
1472
- return {
1473
- type: "BOOLEAN",
1474
- value,
1475
- line: this.line,
1476
- column: startColumn,
1477
- offset: this.pos - value.length
1478
- };
1479
- }
1480
- if (value === "null" || value === "none") {
1481
- return {
1482
- type: "NULL",
1483
- value,
1484
- line: this.line,
1485
- column: startColumn,
1486
- offset: this.pos - value.length
1487
- };
1488
- }
1489
- const token = {
1490
- type: "IDENTIFIER",
1491
- value,
1492
- line: this.line,
1493
- column: startColumn,
1494
- offset: this.pos - value.length
1495
- };
1496
- switch (value) {
1497
- case "state_machine":
1498
- token.type = "STATE_MACHINE";
1499
- break;
1500
- case "initial":
1501
- token.type = "INITIAL";
1502
- break;
1503
- case "state":
1504
- token.type = "STATE";
1505
- break;
1506
- case "on_entry":
1507
- token.type = "ON_ENTRY";
1508
- break;
1509
- case "on_exit":
1510
- token.type = "ON_EXIT";
1511
- break;
1512
- case "transition":
1513
- token.type = "TRANSITION";
1514
- break;
1515
- case "match":
1516
- token.type = "MATCH";
1517
- break;
1518
- case "on_error":
1519
- token.type = "ON_ERROR";
1520
- break;
1521
- case "assert":
1522
- token.type = "ASSERT";
1523
- break;
1524
- case "_":
1525
- token.type = "UNDERSCORE";
1526
- break;
1527
- }
1528
- return token;
1529
- }
1530
- isDigit(char) {
1531
- return char >= "0" && char <= "9";
1532
- }
1533
- isAlpha(char) {
1534
- return char >= "a" && char <= "z" || char >= "A" && char <= "Z";
1535
- }
1536
- isIdentifierStart(char) {
1537
- return this.isAlpha(char) || char === "_" || char === "$";
1538
- }
1539
- isIdentifierPart(char) {
1540
- return this.isIdentifierStart(char) || this.isDigit(char) || char === "-";
1541
- }
1542
- };
1543
- var HoloScriptPlusParser = class {
1544
- constructor(options = {}) {
1545
- this.tokens = [];
1546
- this.pos = 0;
1547
- this.source = "";
1548
- this.errors = [];
1549
- this.warnings = [];
1550
- this.imports = [];
1551
- this.hasState = false;
1552
- this.hasVRTraits = false;
1553
- this.hasControlFlow = false;
1554
- this.compiledExpressions = /* @__PURE__ */ new Map();
1555
- this.errorRecovery = new ErrorRecovery();
1556
- this.options = {
1557
- enableVRTraits: true,
1558
- enableTypeScriptImports: true,
1559
- strict: false,
1560
- ...options
1561
- };
1562
- }
1563
- /**
1564
- * Get quick fixes for all errors in the last parse
1565
- * Useful for IDE integrations and LSP
1566
- */
1567
- getQuickFixes() {
1568
- const fixes = /* @__PURE__ */ new Map();
1569
- for (const error of this.errors) {
1570
- const errorFixes = generateQuickFixes(
1571
- {
1572
- code: error.code,
1573
- message: error.message,
1574
- line: error.line,
1575
- column: error.column,
1576
- source: this.source
1577
- },
1578
- this.source
1579
- );
1580
- if (errorFixes.length > 0) {
1581
- fixes.set(error.line, errorFixes);
1582
- }
1583
- }
1584
- return fixes;
1585
- }
1586
- /**
1587
- * Get enriched errors with additional suggestions from ErrorRecovery
1588
- */
1589
- getEnrichedErrors() {
1590
- return this.errors.map(
1591
- (error) => enrichErrorWithSuggestions(
1592
- {
1593
- code: error.code,
1594
- message: error.message,
1595
- line: error.line,
1596
- column: error.column,
1597
- source: this.source
1598
- },
1599
- this.source
1600
- )
1601
- );
1602
- }
1603
- parse(source) {
1604
- this.source = source;
1605
- this.errors = [];
1606
- this.warnings = [];
1607
- this.imports = [];
1608
- this.hasState = false;
1609
- this.hasVRTraits = false;
1610
- this.hasControlFlow = false;
1611
- this.compiledExpressions = /* @__PURE__ */ new Map();
1612
- this.pos = 0;
1613
- this.errorRecovery.clear();
1614
- const lexer = new Lexer(source);
1615
- this.tokens = lexer.tokenize();
1616
- const root = this.parseDocument();
1617
- return this.buildResult(root);
1618
- }
1619
- /**
1620
- * Performs an incremental parse using cached nodes for unchanged chunks
1621
- */
1622
- parseIncremental(source, cache = globalParseCache) {
1623
- this.source = source;
1624
- this.errors = [];
1625
- this.warnings = [];
1626
- this.imports = [];
1627
- this.hasState = false;
1628
- this.hasVRTraits = false;
1629
- this.hasControlFlow = false;
1630
- this.compiledExpressions = /* @__PURE__ */ new Map();
1631
- const chunks = ChunkDetector.detect(source);
1632
- const topLevelNodes = [];
1633
- const globalDirectives = [];
1634
- for (const chunk of chunks) {
1635
- const hash = ParseCache.hash(chunk.content);
1636
- const cachedNode = cache.get(chunk.id, hash);
1637
- if (cachedNode) {
1638
- topLevelNodes.push(cachedNode);
1639
- } else {
1640
- const chunkResult = this.parse(chunk.content);
1641
- const chunkAst = chunkResult.ast;
1642
- const chunkFeatures = chunkResult.features;
1643
- if (chunkAst?.root) {
1644
- const node = chunkAst.root;
1645
- this.offsetNodeLoc(node, chunk.startLine - 1);
1646
- topLevelNodes.push(node);
1647
- cache.set(chunk.id, hash, node);
1648
- this.hasState = this.hasState || !!chunkFeatures?.state;
1649
- this.hasVRTraits = this.hasVRTraits || !!chunkFeatures?.vrTraits;
1650
- this.hasControlFlow = this.hasControlFlow || !!chunkFeatures?.loops || !!chunkFeatures?.conditionals;
1651
- this.imports.push(...chunkAst.imports);
1652
- }
1653
- this.errors.push(...chunkResult.errors);
1654
- this.warnings.push(...chunkResult.warnings || []);
1655
- }
1656
- }
1657
- const root = {
1658
- type: "fragment",
1659
- id: "root",
1660
- properties: {},
1661
- directives: globalDirectives,
1662
- children: topLevelNodes,
1663
- traits: /* @__PURE__ */ new Map(),
1664
- loc: {
1665
- start: { line: 1, column: 1 },
1666
- end: { line: chunks.length > 0 ? chunks[chunks.length - 1].endLine : 1, column: 1 }
1667
- },
1668
- body: topLevelNodes
1669
- };
1670
- const result = this.buildResult(root);
1671
- return result;
1672
- }
1673
- buildResult(root) {
1674
- const isFragment = root.type === "fragment";
1675
- const directives = root.directives || [];
1676
- let version;
1677
- const migrations = [];
1678
- for (const d of directives) {
1679
- if (d.type === "version") {
1680
- version = d.version;
1681
- } else if (d.type === "migrate") {
1682
- migrations.push({
1683
- type: "Migration",
1684
- fromVersion: d.fromVersion,
1685
- body: d.body
1686
- });
1687
- }
1688
- }
1689
- if (version === void 0) version = "1.0";
1690
- const ast = {
1691
- type: "Program",
1692
- id: "root",
1693
- properties: isFragment ? root.properties || {} : {},
1694
- directives,
1695
- children: isFragment ? root.children || [] : [root],
1696
- traits: isFragment ? root.traits || /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(),
1697
- loc: root.loc,
1698
- body: isFragment ? root.children || [] : [root],
1699
- version,
1700
- migrations: migrations.length > 0 ? migrations : void 0,
1701
- root,
1702
- imports: this.imports,
1703
- hasState: this.hasState,
1704
- hasVRTraits: this.hasVRTraits,
1705
- hasControlFlow: this.hasControlFlow
1706
- };
1707
- return {
1708
- success: this.errors.length === 0,
1709
- ast,
1710
- compiledExpressions: this.compiledExpressions,
1711
- requiredCompanions: this.imports.map((i) => i.path),
1712
- features: {
1713
- state: this.hasState,
1714
- vrTraits: this.hasVRTraits,
1715
- loops: this.hasControlFlow,
1716
- conditionals: this.hasControlFlow,
1717
- lifecycleHooks: (root.directives || []).some((d) => d.type === "lifecycle")
1718
- },
1719
- warnings: this.warnings,
1720
- errors: this.errors
1721
- };
1722
- }
1723
- offsetNodeLoc(node, lineOffset) {
1724
- if (node.loc) {
1725
- if (node.loc.start) node.loc.start.line += lineOffset;
1726
- if (node.loc.end) node.loc.end.line += lineOffset;
1727
- }
1728
- if (node.children) {
1729
- node.children.forEach((child) => this.offsetNodeLoc(child, lineOffset));
1730
- }
1731
- if (node.body && Array.isArray(node.body)) {
1732
- node.body.forEach((child) => this.offsetNodeLoc(child, lineOffset));
1733
- }
1734
- }
1735
- parseDocument() {
1736
- this.skipNewlines();
1737
- const topLevelNodes = [];
1738
- const globalDirectives = [];
1739
- while (!this.check("EOF")) {
1740
- const currentDirectives = [];
1741
- try {
1742
- while (this.check("AT")) {
1743
- const directive = this.parseDirective();
1744
- if (directive) {
1745
- const { type } = directive;
1746
- if (type === "version" || type === "migrate" || type === "import" || type === "export") {
1747
- globalDirectives.push(directive);
1748
- if (type === "export") {
1749
- currentDirectives.push(directive);
1750
- }
1751
- } else {
1752
- currentDirectives.push(directive);
1753
- }
1754
- }
1755
- this.skipNewlines();
1756
- }
1757
- const isNodeStart = this.check("IDENTIFIER") || this.check("STATE_MACHINE") || this.check("STATE") || this.check("TRANSITION") || this.check("INITIAL");
1758
- if (isNodeStart) {
1759
- const node = this.parseNode();
1760
- const existingDirectives = node.directives || [];
1761
- node.directives = [...currentDirectives, ...existingDirectives];
1762
- if (node.type === "template") {
1763
- for (const d of currentDirectives) {
1764
- if (d.type === "version") {
1765
- node.version = d.version;
1766
- } else if (d.type === "migrate") {
1767
- if (!node.migrations) node.migrations = [];
1768
- node.migrations.push({
1769
- type: "Migration",
1770
- fromVersion: d.fromVersion,
1771
- body: d.body
1772
- });
1773
- }
1774
- }
1775
- }
1776
- topLevelNodes.push(node);
1777
- } else {
1778
- if (currentDirectives.length > 0) {
1779
- if (this.check("EOF")) {
1780
- globalDirectives.push(...currentDirectives);
1781
- } else {
1782
- this.error(
1783
- `Expected node after directives, got ${this.current().type}. Valid nodes: orb, template, logic, object, composition, scene, group`,
1784
- "HSP003"
1785
- );
1786
- globalDirectives.push(...currentDirectives);
1787
- }
1788
- } else if (!this.check("EOF")) {
1789
- this.error(
1790
- `Unexpected token ${this.current().type} "${this.current().value}" at top level. Expected: composition, object, template, logic, or @directive`,
1791
- "HSP001"
1792
- );
1793
- throw new Error("ParseError");
1794
- }
1795
- }
1796
- if (this.check("IDENTIFIER") && this.current().value === "connect") {
1797
- const connection = this.parseConnectionStatement();
1798
- const node = {
1799
- type: "connection",
1800
- properties: connection,
1801
- directives: [],
1802
- children: [],
1803
- traits: /* @__PURE__ */ new Map(),
1804
- loc: {
1805
- start: { line: this.current().line, column: 0 },
1806
- end: { line: this.current().line, column: 0 }
1807
- }
1808
- };
1809
- topLevelNodes.push(node);
1810
- }
1811
- } catch (e) {
1812
- const errorMessage = e instanceof Error ? e.message : String(e);
1813
- if (errorMessage !== "ParseError" && errorMessage !== "Unexpected token") {
1814
- console.error(e);
1815
- }
1816
- this.synchronize();
1817
- }
1818
- this.skipNewlines();
1819
- }
1820
- if (topLevelNodes.length === 1 && globalDirectives.length === 0) {
1821
- return topLevelNodes[0];
1822
- }
1823
- return {
1824
- type: "fragment",
1825
- id: "root",
1826
- properties: {},
1827
- directives: globalDirectives,
1828
- children: topLevelNodes,
1829
- traits: /* @__PURE__ */ new Map(),
1830
- loc: {
1831
- start: { line: 1, column: 1 },
1832
- end: { line: this.current().line, column: this.current().column }
1833
- },
1834
- body: topLevelNodes
1835
- };
1836
- }
1837
- parseNode() {
1838
- const startToken = this.current();
1839
- const typeToken = this.match([
1840
- "IDENTIFIER",
1841
- "STATE_MACHINE",
1842
- "STATE",
1843
- "TRANSITION",
1844
- "INITIAL",
1845
- "ON_ENTRY",
1846
- "ON_EXIT"
1847
- ]) || this.expect("IDENTIFIER", "Expected element type");
1848
- const type = typeToken.value;
1849
- if (type === "template") {
1850
- const templateName = this.expect("STRING", "Expected template name").value;
1851
- const templateBody = this.parseBlockContent();
1852
- let version;
1853
- const migrations = [];
1854
- const directives2 = [];
1855
- const children2 = [];
1856
- for (const [key, value] of Object.entries(templateBody)) {
1857
- if (key === "@version") {
1858
- const v = value;
1859
- if (v.type === "version") version = v.version;
1860
- delete templateBody[key];
1861
- } else if (key === "@migrate") {
1862
- const m = value;
1863
- if (m.type === "migrate") {
1864
- migrations.push({
1865
- type: "Migration",
1866
- fromVersion: m.fromVersion,
1867
- body: m.body
1868
- });
1869
- }
1870
- delete templateBody[key];
1871
- } else if (key.startsWith("@")) {
1872
- directives2.push(value);
1873
- delete templateBody[key];
1874
- } else if (typeof value === "object" && value && "type" in value) {
1875
- children2.push(value);
1876
- delete templateBody[key];
1877
- }
1878
- }
1879
- return {
1880
- type: "template",
1881
- name: templateName,
1882
- properties: templateBody,
1883
- // Now contains only true properties
1884
- version,
1885
- migrations,
1886
- directives: directives2,
1887
- children: children2,
1888
- traits: /* @__PURE__ */ new Map(),
1889
- loc: {
1890
- start: { line: startToken.line, column: startToken.column },
1891
- end: { line: this.current().line, column: this.current().column }
1892
- }
1893
- };
1894
- }
1895
- if (type === "logic") {
1896
- const logicBody = this.parseLogicBlock();
1897
- return {
1898
- type: "logic",
1899
- name: "logic",
1900
- id: "logic",
1901
- properties: {},
1902
- directives: [],
1903
- children: [],
1904
- traits: /* @__PURE__ */ new Map(),
1905
- body: logicBody,
1906
- loc: {
1907
- start: { line: startToken.line, column: startToken.column },
1908
- end: { line: this.current().line, column: this.current().column }
1909
- }
1910
- };
1911
- }
1912
- if ([
1913
- "module",
1914
- "script",
1915
- "struct",
1916
- "enum",
1917
- "class",
1918
- "interface",
1919
- "action",
1920
- "function",
1921
- "async",
1922
- "on"
1923
- ].includes(type)) {
1924
- let name = "anonymous";
1925
- if (this.check("IDENTIFIER")) {
1926
- name = this.advance().value;
1927
- } else if (this.check("STRING")) {
1928
- name = this.advance().value;
1929
- }
1930
- while (this.check("DOT")) {
1931
- this.advance();
1932
- if (this.check("IDENTIFIER")) this.advance();
1933
- }
1934
- if (this.check("LPAREN")) {
1935
- this.skipParens();
1936
- }
1937
- let bodyContent = "";
1938
- if (this.check("LBRACE")) {
1939
- bodyContent = this.parseRawBlock();
1940
- }
1941
- return {
1942
- type,
1943
- name,
1944
- id: name,
1945
- properties: {},
1946
- directives: [],
1947
- children: [],
1948
- traits: /* @__PURE__ */ new Map(),
1949
- body: bodyContent,
1950
- loc: {
1951
- start: { line: startToken.line, column: startToken.column },
1952
- end: { line: this.current().line, column: this.current().column }
1953
- }
1954
- };
1955
- }
1956
- if (startToken.type === "STATE_MACHINE" || type === "state_machine") {
1957
- return this.parseStateMachine();
1958
- }
1959
- if (type === "on_error" || startToken.type === "ON_ERROR") {
1960
- return this.parseOnErrorNode();
1961
- }
1962
- if (type === "assert" || startToken.type === "ASSERT") {
1963
- return this.parseAssertNode();
1964
- }
1965
- if (type === "environment") {
1966
- const envBody = this.parseEnvironmentBlock();
1967
- return {
1968
- type: "environment",
1969
- properties: envBody.properties,
1970
- directives: envBody.directives,
1971
- children: [],
1972
- traits: /* @__PURE__ */ new Map(),
1973
- loc: {
1974
- start: { line: startToken.line, column: startToken.column },
1975
- end: { line: this.current().line, column: this.current().column }
1976
- }
1977
- };
1978
- }
1979
- if (type === "composition") {
1980
- let id2;
1981
- if (this.check("HASH")) {
1982
- this.advance();
1983
- id2 = this.expect("IDENTIFIER", "Expected ID after #").value;
1984
- }
1985
- if (this.check("STRING")) {
1986
- id2 = this.advance().value;
1987
- }
1988
- if (this.check("IDENTIFIER")) {
1989
- id2 = this.advance().value;
1990
- }
1991
- const compBody = this.parseCompositionBlock();
1992
- return {
1993
- type: "composition",
1994
- name: id2,
1995
- id: id2,
1996
- properties: compBody.properties || {},
1997
- directives: [],
1998
- children: compBody.children,
1999
- traits: /* @__PURE__ */ new Map(),
2000
- body: compBody,
2001
- loc: {
2002
- start: { line: startToken.line, column: startToken.column },
2003
- end: { line: this.current().line, column: this.current().column }
2004
- }
2005
- };
2006
- }
2007
- let id;
2008
- let templateRef;
2009
- if (this.check("HASH")) {
2010
- this.advance();
2011
- id = this.expect("IDENTIFIER", "Expected ID after #").value;
2012
- }
2013
- if (this.check("STRING")) {
2014
- id = this.advance().value;
2015
- }
2016
- if (this.check("IDENTIFIER") && this.current().value !== "using") {
2017
- id = this.advance().value;
2018
- }
2019
- if (this.check("LPAREN")) {
2020
- this.skipParens();
2021
- }
2022
- if (this.check("IDENTIFIER") && this.current().value === "using") {
2023
- this.advance();
2024
- templateRef = this.expect("STRING", "Expected template name after using").value;
2025
- }
2026
- if (this.check("COLON")) {
2027
- this.advance();
2028
- if (this.check("IDENTIFIER")) this.advance();
2029
- if (this.check("LBRACKET")) {
2030
- this.advance();
2031
- if (this.check("RBRACKET")) this.advance();
2032
- }
2033
- }
2034
- const properties = {};
2035
- const children = [];
2036
- const directives = [];
2037
- const traits = /* @__PURE__ */ new Map();
2038
- if (templateRef) {
2039
- properties.__templateRef = templateRef;
2040
- }
2041
- while (!this.check("LBRACE") && !this.check("EOF")) {
2042
- try {
2043
- if (this.check("NEWLINE")) {
2044
- this.skipNewlines();
2045
- if (this.check("LBRACE")) break;
2046
- if (!this.check("AT")) {
2047
- if (this.check("EOF")) break;
2048
- }
2049
- }
2050
- if (this.check("AT")) {
2051
- const directive = this.parseDirective();
2052
- if (directive) {
2053
- if (directive.type === "trait") {
2054
- traits.set(directive.name, directive.config);
2055
- this.hasVRTraits = true;
2056
- directives.push(directive);
2057
- } else {
2058
- directives.push(directive);
2059
- }
2060
- }
2061
- } else if (this.check("SPREAD")) {
2062
- const startToken2 = this.advance();
2063
- const targetExpr = this.parseUnary();
2064
- let target;
2065
- if (typeof targetExpr === "object" && targetExpr && "__ref" in targetExpr) {
2066
- target = targetExpr.__ref;
2067
- } else if (typeof targetExpr === "string") {
2068
- target = targetExpr;
2069
- } else {
2070
- this.error(
2071
- "Expected identifier or member expression after spread operator (...)",
2072
- "HSP002"
2073
- );
2074
- target = "unknown";
2075
- }
2076
- children.push({
2077
- type: "spread",
2078
- target,
2079
- loc: {
2080
- start: { line: startToken2.line, column: startToken2.column },
2081
- end: { line: this.current().line, column: this.current().column }
2082
- }
2083
- });
2084
- } else if (this.check("IDENTIFIER")) {
2085
- const key = this.advance().value;
2086
- let value = true;
2087
- if (this.check("COLON")) {
2088
- this.advance();
2089
- value = this.parseValue();
2090
- }
2091
- properties[key] = value;
2092
- } else {
2093
- if (!this.check("LBRACE")) {
2094
- this.error(
2095
- `Unexpected token in properties: ${this.current().type}. Expected property name, @directive, or spread (...)`,
2096
- "HSP101"
2097
- );
2098
- this.synchronizeProperty();
2099
- }
2100
- }
2101
- } catch (e) {
2102
- const errorMessage = e instanceof Error ? e.message : String(e);
2103
- if (errorMessage !== "ParseError") console.error(e);
2104
- this.synchronizeProperty();
2105
- }
2106
- }
2107
- if (this.check("LBRACE")) {
2108
- this.advance();
2109
- this.skipNewlines();
2110
- while (!this.check("RBRACE") && !this.check("EOF")) {
2111
- try {
2112
- this.skipNewlines();
2113
- if (this.check("RBRACE") || this.check("EOF")) break;
2114
- if (this.check("AT")) {
2115
- const directive = this.parseDirective();
2116
- if (directive) {
2117
- if (directive.type === "trait") {
2118
- traits.set(directive.name, directive.config);
2119
- this.hasVRTraits = true;
2120
- }
2121
- directives.push(directive);
2122
- }
2123
- } else if (this.check("SPREAD")) {
2124
- const startToken2 = this.advance();
2125
- const targetExpr = this.parseUnary();
2126
- let target;
2127
- if (typeof targetExpr === "object" && targetExpr && "__ref" in targetExpr) {
2128
- target = targetExpr.__ref;
2129
- } else if (typeof targetExpr === "string") {
2130
- target = targetExpr;
2131
- } else {
2132
- this.error(
2133
- "Expected identifier or member expression after spread operator (...)",
2134
- "HSP002"
2135
- );
2136
- target = "unknown";
2137
- }
2138
- const spreadNode = {
2139
- type: "spread",
2140
- target,
2141
- loc: {
2142
- start: { line: startToken2.line, column: startToken2.column },
2143
- end: { line: this.current().line, column: this.current().column }
2144
- }
2145
- };
2146
- children.push(spreadNode);
2147
- const key = "__spread_" + target;
2148
- properties[key] = spreadNode;
2149
- } else {
2150
- const token = this.current();
2151
- const isKeyToken = token.type === "IDENTIFIER" || token.type === "STRING" || token.type === "STATE" || token.type === "STATE_MACHINE" || token.type === "INITIAL" || token.type === "ON_ENTRY" || token.type === "ON_EXIT" || token.type === "TRANSITION";
2152
- if (isKeyToken) {
2153
- const saved = this.pos;
2154
- const name = this.advance().value;
2155
- const childNodeKeywords = [
2156
- "logic",
2157
- "template",
2158
- "environment",
2159
- "state",
2160
- "object",
2161
- "composition",
2162
- "system",
2163
- "core_config",
2164
- "narrative",
2165
- "quest",
2166
- "objective",
2167
- "dialogue",
2168
- "choice",
2169
- "visual_metadata",
2170
- "spatial_group",
2171
- "scene",
2172
- "group",
2173
- "module",
2174
- "struct",
2175
- "orb",
2176
- "on_error",
2177
- "assert",
2178
- "transition",
2179
- "on_entry",
2180
- "on_exit"
2181
- ];
2182
- if (name === "transition" && this.check("STRING")) {
2183
- const event = this.advance().value;
2184
- if (this.check("ARROW")) {
2185
- this.advance();
2186
- const targetState = this.expect("STRING", "Expected target state string").value;
2187
- let block = {};
2188
- if (this.check("LBRACE")) {
2189
- block = this.parseBlockContent();
2190
- }
2191
- children.push({
2192
- type: "transition",
2193
- name: `${event}_to_${targetState}`,
2194
- event,
2195
- target: targetState,
2196
- guard: block.guard || "",
2197
- action: block.action || "",
2198
- block
2199
- });
2200
- continue;
2201
- } else {
2202
- this.pos = saved;
2203
- }
2204
- }
2205
- if (name === "on_entry" || name === "on_exit") {
2206
- let block = "";
2207
- if (this.check("LBRACE")) {
2208
- block = this.parseCodeBlock();
2209
- } else {
2210
- while (!this.check("RBRACE") && !this.check("EOF")) this.advance();
2211
- }
2212
- children.push({
2213
- type: "method",
2214
- name,
2215
- params: [],
2216
- returnType: "unknown",
2217
- body: block
2218
- });
2219
- continue;
2220
- }
2221
- if (this.check("LPAREN")) {
2222
- const possibleMethod = saved;
2223
- this.pos = saved;
2224
- const methodName = this.advance().value;
2225
- const params = [];
2226
- this.advance();
2227
- while (!this.check("RPAREN") && !this.check("EOF") && !this.check("LBRACE")) {
2228
- if (this.check("IDENTIFIER")) {
2229
- params.push(this.advance().value);
2230
- } else {
2231
- this.advance();
2232
- }
2233
- }
2234
- if (this.check("RPAREN")) this.advance();
2235
- let returnType = "unknown";
2236
- if (this.check("COLON")) {
2237
- this.advance();
2238
- if (this.check("IDENTIFIER")) {
2239
- returnType = this.advance().value;
2240
- }
2241
- }
2242
- if (this.check("LBRACE")) {
2243
- const body = this.parseCodeBlock();
2244
- children.push({
2245
- type: "method",
2246
- name: methodName,
2247
- params,
2248
- returnType,
2249
- body
2250
- });
2251
- continue;
2252
- } else {
2253
- this.pos = possibleMethod;
2254
- this.advance();
2255
- }
2256
- }
2257
- if (this.check("COLON") || this.check("EQUALS")) {
2258
- this.advance();
2259
- properties[name] = this.parseValue();
2260
- } else if (childNodeKeywords.includes(name) && (this.check("LBRACE") || this.check("STRING"))) {
2261
- this.pos = saved;
2262
- children.push(this.parseNode());
2263
- } else if (this.current().type === "IDENTIFIER") {
2264
- this.pos = saved;
2265
- children.push(this.parseNode());
2266
- } else {
2267
- properties[name] = true;
2268
- while (this.check("LPAREN") || this.check("DOT") || this.check("LBRACE")) {
2269
- if (this.check("LPAREN")) this.skipParens();
2270
- else if (this.check("LBRACE")) this.skipBraces();
2271
- else {
2272
- this.advance();
2273
- if (this.check("IDENTIFIER")) this.advance();
2274
- }
2275
- }
2276
- }
2277
- } else if (this.check("COMMA")) {
2278
- this.advance();
2279
- } else {
2280
- this.error(
2281
- `Unexpected token ${this.current().type} "${this.current().value}" in node body`
2282
- );
2283
- this.synchronizeProperty();
2284
- }
2285
- }
2286
- this.skipNewlines();
2287
- } catch (e) {
2288
- const errorMessage = e instanceof Error ? e.message : String(e);
2289
- if (errorMessage !== "ParseError") console.error(e);
2290
- this.synchronizeProperty();
2291
- }
2292
- }
2293
- this.expect("RBRACE", "Expected }");
2294
- }
2295
- return {
2296
- type,
2297
- name: id,
2298
- // Mapping id to name for runtime compatibility
2299
- id,
2300
- properties,
2301
- directives,
2302
- children,
2303
- traits,
2304
- loc: {
2305
- start: { line: startToken.line, column: startToken.column },
2306
- end: { line: this.current().line, column: this.current().column }
2307
- }
2308
- };
2309
- }
2310
- parseDirective() {
2311
- this.expect("AT", "Expected @");
2312
- const nameToken = this.current();
2313
- const isKeyword = ["STATE_MACHINE", "STATE", "ON_ENTRY", "ON_EXIT", "TRANSITION"].includes(
2314
- nameToken.type
2315
- );
2316
- if (nameToken.type !== "IDENTIFIER" && !isKeyword) {
2317
- this.error(
2318
- `Expected directive name, got ${nameToken.type}. Directives start with @ followed by name (e.g., @grabbable)`,
2319
- "HSP201"
2320
- );
2321
- return null;
2322
- }
2323
- this.advance();
2324
- const name = nameToken.value;
2325
- if (name === "version") {
2326
- this.expect("LPAREN", "Expected ( after @version");
2327
- const versionToken = this.expect("NUMBER", "Expected version number");
2328
- const version = Number(versionToken.value);
2329
- this.expect("RPAREN", "Expected ) after version number");
2330
- return { type: "version", version };
2331
- }
2332
- if (name === "migrate") {
2333
- const fromToken = this.expect("IDENTIFIER", 'Expected "from" after @migrate');
2334
- if (fromToken.value !== "from") {
2335
- this.error('Expected "from" after @migrate');
2336
- }
2337
- this.expect("LPAREN", "Expected ( after from");
2338
- const fromVersionToken = this.expect("NUMBER", "Expected version number");
2339
- const fromVersion = Number(fromVersionToken.value);
2340
- this.expect("RPAREN", "Expected ) after version number");
2341
- const body = this.check("LBRACE") ? this.parseCodeBlock() : "";
2342
- return { type: "migrate", fromVersion, body };
2343
- }
2344
- if (VR_TRAITS.includes(name)) {
2345
- if (!this.options.enableVRTraits) {
2346
- this.warn(`VR trait @${name} is disabled`);
2347
- return null;
2348
- }
2349
- let config2 = {};
2350
- if (this.check("LPAREN")) {
2351
- config2 = this.parseTraitConfig();
2352
- } else if (this.check("LBRACE")) {
2353
- config2 = this.parseBlockContent();
2354
- }
2355
- return { type: "trait", name, config: config2 };
2356
- }
2357
- if (LIFECYCLE_HOOKS.includes(name)) {
2358
- const params = [];
2359
- if (this.check("LPAREN")) {
2360
- this.advance();
2361
- while (!this.check("RPAREN") && !this.check("EOF")) {
2362
- params.push(this.expect("IDENTIFIER", "Expected parameter name").value);
2363
- if (this.check("COLON")) {
2364
- this.advance();
2365
- this.expect("IDENTIFIER", "Expected type");
2366
- }
2367
- if (this.check("COMMA")) this.advance();
2368
- }
2369
- this.expect("RPAREN", "Expected )");
2370
- }
2371
- if (this.check("COLON")) {
2372
- this.advance();
2373
- if (this.check("LPAREN")) this.skipParens();
2374
- if (this.check("ARROW")) this.advance();
2375
- }
2376
- let body = "";
2377
- if (this.check("ARROW")) {
2378
- this.advance();
2379
- body = this.parseInlineExpression();
2380
- } else if (this.check("LBRACE")) {
2381
- body = this.parseCodeBlock();
2382
- }
2383
- return {
2384
- type: "lifecycle",
2385
- hook: name,
2386
- params,
2387
- body
2388
- };
2389
- }
2390
- if (name === "state") {
2391
- this.hasState = true;
2392
- const body = this.parseStateBlock();
2393
- return { type: "state", body };
2394
- }
2395
- if (name === "bindings") {
2396
- const bindings = this.parseBindingsBlock();
2397
- return { type: "bindings", bindings };
2398
- }
2399
- if (name === "for") {
2400
- this.hasControlFlow = true;
2401
- const variable = this.expect("IDENTIFIER", "Expected variable name").value;
2402
- this.expect("IDENTIFIER", 'Expected "in"');
2403
- const iterable = this.parseInlineExpression();
2404
- const body = this.parseControlFlowBody();
2405
- return { type: "for", variable, iterable, body };
2406
- }
2407
- if (name === "forEach") {
2408
- this.hasControlFlow = true;
2409
- const variable = this.expect("IDENTIFIER", "Expected variable name").value;
2410
- this.expect("IDENTIFIER", 'Expected "in"');
2411
- const collection = this.parseInlineExpression();
2412
- const body = this.parseControlFlowBody();
2413
- return { type: "forEach", variable, collection, body };
2414
- }
2415
- if (name === "while") {
2416
- this.hasControlFlow = true;
2417
- const condition = this.parseInlineExpression();
2418
- const body = this.parseControlFlowBody();
2419
- return { type: "while", condition, body };
2420
- }
2421
- if (name === "if") {
2422
- this.hasControlFlow = true;
2423
- const condition = this.parseInlineExpression();
2424
- const body = this.parseControlFlowBody();
2425
- let elseBody;
2426
- this.skipNewlines();
2427
- if (this.check("AT")) {
2428
- const saved = this.pos;
2429
- this.advance();
2430
- if (this.check("IDENTIFIER") && this.current().value === "else") {
2431
- this.advance();
2432
- elseBody = this.parseControlFlowBody();
2433
- } else {
2434
- this.pos = saved;
2435
- }
2436
- }
2437
- return { type: "if", condition, body, else: elseBody };
2438
- }
2439
- if (name === "import") {
2440
- if (!this.options.enableTypeScriptImports) {
2441
- this.warn("@import is disabled");
2442
- return null;
2443
- }
2444
- let namedImports;
2445
- let isWildcard = false;
2446
- if (this.check("LBRACE")) {
2447
- this.advance();
2448
- namedImports = [];
2449
- while (!this.check("RBRACE") && !this.check("EOF")) {
2450
- if (this.check("IDENTIFIER")) {
2451
- namedImports.push(this.advance().value);
2452
- }
2453
- if (this.check("COMMA")) this.advance();
2454
- }
2455
- this.expect("RBRACE", "Expected } in named import list");
2456
- if (this.check("IDENTIFIER") && this.current().value === "from") {
2457
- this.advance();
2458
- } else {
2459
- this.warn("Expected 'from' after named import specifiers");
2460
- }
2461
- }
2462
- if (this.check("ASTERISK") || this.check("IDENTIFIER") && this.current().value === "*") {
2463
- this.advance();
2464
- isWildcard = true;
2465
- if (this.check("IDENTIFIER") && this.current().value === "as") {
2466
- this.advance();
2467
- }
2468
- }
2469
- const path = this.expect("STRING", "Expected import path string").value;
2470
- let alias = path.split("/").pop()?.replace(/\.[^.]+$/, "") || "import";
2471
- if (!namedImports && this.check("IDENTIFIER") && this.current().value === "as") {
2472
- this.advance();
2473
- alias = this.expect("IDENTIFIER", "Expected alias after as").value;
2474
- }
2475
- if (isWildcard && this.check("IDENTIFIER") && this.current().value !== "from") {
2476
- alias = this.advance().value;
2477
- if (this.check("IDENTIFIER") && this.current().value === "from") {
2478
- this.advance();
2479
- }
2480
- }
2481
- this.imports.push({ path, alias, namedImports, isWildcard });
2482
- return {
2483
- type: "import",
2484
- path,
2485
- alias,
2486
- namedImports,
2487
- isWildcard
2488
- };
2489
- }
2490
- if (name === "export") {
2491
- let exportKind = "any";
2492
- if (this.check("IDENTIFIER")) {
2493
- const kindToken = this.current();
2494
- const knownKinds = ["template", "object", "composition", "trait", "group", "scene"];
2495
- if (knownKinds.includes(kindToken.value)) {
2496
- exportKind = this.advance().value;
2497
- }
2498
- }
2499
- let exportName;
2500
- if (this.check("STRING")) {
2501
- exportName = this.advance().value;
2502
- } else if (this.check("IDENTIFIER")) {
2503
- exportName = this.advance().value;
2504
- }
2505
- return {
2506
- type: "export",
2507
- exportKind,
2508
- exportName
2509
- };
2510
- }
2511
- if (name === "manifest") {
2512
- let config2 = {};
2513
- let manifestName = "default";
2514
- if (this.check("LPAREN")) {
2515
- this.advance();
2516
- if (this.check("STRING")) {
2517
- manifestName = this.advance().value;
2518
- }
2519
- while (!this.check("RPAREN") && !this.check("EOF")) this.advance();
2520
- this.expect("RPAREN", "Expected )");
2521
- } else if (this.check("STRING")) {
2522
- manifestName = this.advance().value;
2523
- }
2524
- if (this.check("LBRACE")) {
2525
- const block = this.parseBlockContent();
2526
- config2 = { ...config2, ...block };
2527
- }
2528
- return { type: "manifest", name: manifestName, ...config2 };
2529
- }
2530
- if (name === "asset") {
2531
- if (this.check("LPAREN")) {
2532
- const config2 = this.parseTraitConfig();
2533
- return { ...config2, type: "asset" };
2534
- }
2535
- const assetId = this.expect("STRING", "Expected asset ID").value;
2536
- return { type: "asset", id: assetId };
2537
- }
2538
- if (name === "semantic") {
2539
- const semanticName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected semantic name").value;
2540
- const config2 = this.parseBlockContent();
2541
- return { ...config2, type: "semantic", name: semanticName };
2542
- }
2543
- if (name === "annotate") {
2544
- const annotateName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected annotation type").value;
2545
- let config2 = {};
2546
- if (this.check("COMMA")) {
2547
- this.advance();
2548
- config2 = this.parseValue();
2549
- if (this.check("RPAREN")) this.advance();
2550
- } else if (this.check("RPAREN")) {
2551
- this.advance();
2552
- }
2553
- return { type: "annotate", annotationType: annotateName, config: config2 };
2554
- }
2555
- if (name === "semantic_ref") {
2556
- const refName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected semantic reference").value;
2557
- return { type: "semantic_ref", ref: refName };
2558
- }
2559
- if (name === "bindings") {
2560
- const bindings = this.parseBindingsBlock();
2561
- return { type: "bindings", bindings };
2562
- }
2563
- if (name === "world_metadata") {
2564
- const config2 = this.parseBlockContent();
2565
- return { ...config2, type: "world_metadata" };
2566
- }
2567
- if (name === "world_config") {
2568
- const config2 = this.parseBlockContent();
2569
- return { ...config2, type: "world_config" };
2570
- }
2571
- if (name === "zones") {
2572
- const zones = this.parseNamedBlockList("zone");
2573
- return { type: "zones", zones };
2574
- }
2575
- if (name === "spawn_points") {
2576
- const spawns = this.parseNamedBlockList("spawn");
2577
- return { type: "spawn_points", spawns };
2578
- }
2579
- if (name === "skybox") {
2580
- const config2 = this.parseBlockContent();
2581
- return { ...config2, type: "skybox" };
2582
- }
2583
- if (name === "ambient_light") {
2584
- const config2 = this.parseBlockContent();
2585
- return { ...config2, type: "ambient_light" };
2586
- }
2587
- if (name === "directional_light") {
2588
- let lightName = "default";
2589
- if (this.check("LPAREN")) {
2590
- lightName = this.parseParenString();
2591
- }
2592
- const config2 = this.parseBlockContent();
2593
- return { ...config2, type: "directional_light", name: lightName };
2594
- }
2595
- if (name === "fog") {
2596
- const config2 = this.parseBlockContent();
2597
- return { ...config2, type: "fog" };
2598
- }
2599
- if (name === "artwork_metadata") {
2600
- const config2 = this.parseBlockContent();
2601
- return { ...config2, type: "artwork_metadata" };
2602
- }
2603
- if (name === "npc_behavior") {
2604
- const config2 = this.parseBlockContent();
2605
- return { ...config2, type: "npc_behavior" };
2606
- }
2607
- if (name === "interactive") {
2608
- const config2 = this.parseBlockContent();
2609
- return { ...config2, type: "interactive" };
2610
- }
2611
- if (name === "lod") {
2612
- const config2 = this.parseBlockContent();
2613
- return { ...config2, type: "lod" };
2614
- }
2615
- if (name === "external_api") {
2616
- let externalApiName = "default";
2617
- if (this.check("STRING")) {
2618
- externalApiName = this.advance().value;
2619
- } else if (this.check("IDENTIFIER")) {
2620
- externalApiName = this.advance().value;
2621
- }
2622
- const config2 = this.check("LBRACE") ? this.parseBlockContent() : this.parseTraitConfig();
2623
- return {
2624
- type: "external_api",
2625
- name: externalApiName,
2626
- ...config2
2627
- };
2628
- }
2629
- if (name === "generate") {
2630
- const config2 = this.parseTraitConfig();
2631
- const prompt = config2.prompt || "";
2632
- const context = config2.context || "";
2633
- const target = config2.target || "children";
2634
- return { type: "generate", prompt, context, target };
2635
- }
2636
- if (name === "npc") {
2637
- const npcName = this.expect("STRING", "Expected NPC name").value;
2638
- const props = this.parsePropsBlock();
2639
- return { type: "npc", name: npcName, props };
2640
- }
2641
- if (name === "dialog") {
2642
- const dialogName = this.expect("STRING", "Expected dialog name").value;
2643
- const { props, options } = this.parseDialogBlock();
2644
- return { type: "dialog", name: dialogName, props, options };
2645
- }
2646
- if (name === "hololand") {
2647
- if (this.check("DOT")) {
2648
- this.advance();
2649
- const eventName = this.expect("IDENTIFIER", "Expected event name").value;
2650
- const params = [];
2651
- if (this.check("LPAREN")) {
2652
- this.advance();
2653
- while (!this.check("RPAREN") && !this.check("EOF")) {
2654
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
2655
- if (this.check("COLON")) {
2656
- this.advance();
2657
- this.expect("IDENTIFIER", "Expected type");
2658
- }
2659
- if (this.check("COMMA")) this.advance();
2660
- }
2661
- this.expect("RPAREN", "Expected )");
2662
- }
2663
- return { type: "hololand_event", event: eventName, params };
2664
- }
2665
- }
2666
- if (STRUCTURAL_DIRECTIVES.includes(name)) {
2667
- let nodeName;
2668
- if (this.check("STRING")) {
2669
- nodeName = this.advance().value;
2670
- }
2671
- const config2 = this.check("LBRACE") ? this.parseBlockContent() : this.parseTraitConfig();
2672
- return { ...config2, type: name, name: nodeName };
2673
- }
2674
- if (this.options.strict) {
2675
- this.traitError(name);
2676
- } else {
2677
- this.warn(`Unknown directive @${name}`);
2678
- }
2679
- let config = {};
2680
- if (this.check("LPAREN")) {
2681
- config = this.parseTraitConfig();
2682
- } else if (this.check("LBRACE")) {
2683
- config = this.parseBlockContent();
2684
- }
2685
- if (this.check("COLON")) {
2686
- this.advance();
2687
- if (this.check("LPAREN")) this.skipParens();
2688
- if (this.check("ARROW")) this.advance();
2689
- if (this.check("LBRACE")) {
2690
- config.body = this.parseCodeBlock();
2691
- }
2692
- }
2693
- return { type: "trait", name, config };
2694
- }
2695
- /**
2696
- * Parse a string inside parentheses: ("name")
2697
- */
2698
- parseParenString() {
2699
- this.expect("LPAREN", "Expected (");
2700
- const value = this.expect("STRING", "Expected string").value;
2701
- this.expect("RPAREN", "Expected )");
2702
- return value;
2703
- }
2704
- parseConnectionStatement() {
2705
- this.expect("IDENTIFIER", "Expected connect");
2706
- const from = this.expect("IDENTIFIER", "Expected from name").value;
2707
- this.expect("IDENTIFIER", "Expected to");
2708
- const to = this.expect("IDENTIFIER", "Expected to name").value;
2709
- return { from, to };
2710
- }
2711
- /**
2712
- * Parse block content: { key: value, ... }
2713
- */
2714
- parseBlockContent() {
2715
- const content = {};
2716
- if (!this.check("LBRACE")) {
2717
- return content;
2718
- }
2719
- this.advance();
2720
- this.skipNewlines();
2721
- while (!this.check("RBRACE") && !this.check("EOF")) {
2722
- this.skipNewlines();
2723
- if (this.check("RBRACE") || this.check("EOF")) break;
2724
- this.skipNewlines();
2725
- if (this.check("RBRACE") || this.check("EOF")) break;
2726
- const token = this.current();
2727
- const isKeyToken = token.type === "IDENTIFIER" || token.type === "STRING" || token.type === "STATE" || token.type === "STATE_MACHINE" || token.type === "INITIAL" || token.type === "ON_ENTRY" || token.type === "ON_EXIT" || token.type === "TRANSITION";
2728
- if (isKeyToken) {
2729
- const next = this.peek(1);
2730
- if (next.type === "COLON" || next.type === "EQUALS") {
2731
- const key = this.advance().value;
2732
- this.advance();
2733
- content[key] = this.parseValue();
2734
- } else if (next.type === "STRING" || next.type === "LBRACE" || next.type === "IDENTIFIER") {
2735
- const node = this.parseNode();
2736
- const type = node.type;
2737
- const name = node.name || `unnamed_${type}_${Object.keys(content).length}`;
2738
- content[name] = node;
2739
- } else {
2740
- const key = this.advance().value;
2741
- content[key] = true;
2742
- }
2743
- } else if (this.check("SPREAD")) {
2744
- this.advance();
2745
- const val = this.parseValue();
2746
- const spreadKey = `__spread_${Object.keys(content).length}`;
2747
- content[spreadKey] = { type: "spread", argument: val };
2748
- } else if (this.check("AT")) {
2749
- const directive = this.parseDirective();
2750
- if (directive) {
2751
- const dirKey = ("name" in directive ? directive.name : void 0) || directive.type;
2752
- content[`@${dirKey}`] = directive;
2753
- }
2754
- } else if (this.check("LBRACE")) {
2755
- let depth = 1;
2756
- this.advance();
2757
- while (depth > 0 && !this.check("EOF")) {
2758
- if (this.check("LBRACE")) depth++;
2759
- if (this.check("RBRACE")) depth--;
2760
- this.advance();
2761
- }
2762
- } else if (this.check("LPAREN")) {
2763
- this.skipParens();
2764
- } else {
2765
- this.advance();
2766
- }
2767
- if (this.check("COMMA")) this.advance();
2768
- this.skipNewlines();
2769
- }
2770
- this.expect("RBRACE", "Expected }");
2771
- return content;
2772
- }
2773
- /**
2774
- * Parse bindings block: { bind(expr) -> target, ... }
2775
- */
2776
- parseBindingsBlock() {
2777
- const bindings = [];
2778
- if (!this.check("LBRACE")) {
2779
- return bindings;
2780
- }
2781
- this.advance();
2782
- this.skipNewlines();
2783
- while (!this.check("RBRACE") && !this.check("EOF")) {
2784
- this.skipNewlines();
2785
- if (this.check("RBRACE") || this.check("EOF")) break;
2786
- if (this.check("IDENTIFIER") && this.current().value === "bind") {
2787
- this.advance();
2788
- if (this.check("LPAREN")) {
2789
- this.advance();
2790
- let source = "";
2791
- let parenDepth = 1;
2792
- while (parenDepth > 0 && !this.check("EOF")) {
2793
- if (this.check("LPAREN")) parenDepth++;
2794
- if (this.check("RPAREN")) {
2795
- parenDepth--;
2796
- if (parenDepth === 0) break;
2797
- }
2798
- source += this.advance().value + " ";
2799
- }
2800
- this.expect("RPAREN", "Expected )");
2801
- source = source.trim();
2802
- if (this.check("ARROW")) {
2803
- this.advance();
2804
- }
2805
- let target = "";
2806
- while (!this.check("NEWLINE") && !this.check("RBRACE") && !this.check("EOF")) {
2807
- target += this.advance().value;
2808
- }
2809
- target = target.trim();
2810
- bindings.push({ source, target });
2811
- }
2812
- } else {
2813
- while (!this.check("NEWLINE") && !this.check("RBRACE") && !this.check("EOF")) {
2814
- this.advance();
2815
- }
2816
- }
2817
- this.skipNewlines();
2818
- }
2819
- this.expect("RBRACE", "Expected }");
2820
- return bindings;
2821
- }
2822
- /**
2823
- * Parse named block list: zone "name" { ... } or spawn "name" { ... }
2824
- */
2825
- parseNamedBlockList(blockType) {
2826
- const blocks = [];
2827
- if (!this.check("LBRACE")) {
2828
- return blocks;
2829
- }
2830
- this.advance();
2831
- this.skipNewlines();
2832
- while (!this.check("RBRACE") && !this.check("EOF")) {
2833
- this.skipNewlines();
2834
- if (this.check("RBRACE") || this.check("EOF")) break;
2835
- if (this.check("IDENTIFIER") && this.current().value === blockType) {
2836
- this.advance();
2837
- const blockName = this.expect("STRING", `Expected ${blockType} name`).value;
2838
- const config = this.parseBlockContent();
2839
- blocks.push({ name: blockName, config });
2840
- } else {
2841
- this.advance();
2842
- }
2843
- this.skipNewlines();
2844
- }
2845
- this.expect("RBRACE", "Expected }");
2846
- return blocks;
2847
- }
2848
- /**
2849
- * Parse composition block: composition "Name" { ... }
2850
- */
2851
- parseCompositionBlock() {
2852
- const result = {
2853
- systems: [],
2854
- configs: [],
2855
- children: [],
2856
- properties: {}
2857
- };
2858
- if (!this.check("LBRACE")) {
2859
- return result;
2860
- }
2861
- this.advance();
2862
- this.skipNewlines();
2863
- const childNodeKeywords = [
2864
- "logic",
2865
- "template",
2866
- "environment",
2867
- "state",
2868
- "object",
2869
- "composition",
2870
- "system",
2871
- "core_config",
2872
- "narrative",
2873
- "quest",
2874
- "objective",
2875
- "dialogue",
2876
- "choice",
2877
- "visual_metadata",
2878
- "spatial_group",
2879
- "scene",
2880
- "group",
2881
- "module",
2882
- "struct",
2883
- "orb",
2884
- "on_error",
2885
- "assert",
2886
- "topic",
2887
- "channel",
2888
- "config",
2889
- "zone",
2890
- "audio",
2891
- "light",
2892
- "npc",
2893
- "camera",
2894
- "timeline"
2895
- ];
2896
- while (!this.check("RBRACE") && !this.check("EOF")) {
2897
- const currentDirectives = [];
2898
- this.skipNewlines();
2899
- if (this.check("RBRACE") || this.check("EOF")) break;
2900
- while (this.check("AT")) {
2901
- const directive = this.parseDirective();
2902
- if (directive) {
2903
- currentDirectives.push(directive);
2904
- }
2905
- this.skipNewlines();
2906
- }
2907
- const isNodeStart = this.check("IDENTIFIER") || this.check("STATE_MACHINE") || this.check("STATE") || this.check("TRANSITION") || this.check("INITIAL");
2908
- if (isNodeStart) {
2909
- const token = this.current();
2910
- const next = this.peek(1);
2911
- if (next.type === "COLON" || next.type === "EQUALS") {
2912
- const key = this.advance().value;
2913
- this.advance();
2914
- result.properties[key] = this.parseValue();
2915
- } else if (childNodeKeywords.includes(token.value) && (next.type === "LBRACE" || next.type === "STRING" || next.type === "IDENTIFIER")) {
2916
- const keyword = this.current().value;
2917
- const node = this.parseNode();
2918
- node.directives = [...currentDirectives, ...node.directives || []];
2919
- if (keyword === "system" || node.type === "system") {
2920
- result.systems.push(node);
2921
- } else if (keyword === "core_config" || node.type === "core_config") {
2922
- result.configs.push(node);
2923
- } else {
2924
- result.children.push(node);
2925
- }
2926
- } else if (!childNodeKeywords.includes(token.value) && (next.type === "STRING" || next.type === "NUMBER" || next.type === "BOOLEAN" || next.type === "NULL")) {
2927
- const key = this.advance().value;
2928
- result.properties[key] = this.parseValue();
2929
- } else if (next.type === "LBRACE" || next.type === "IDENTIFIER" || next.type === "STRING") {
2930
- const keyword = this.current().value;
2931
- const node = this.parseNode();
2932
- node.directives = [...currentDirectives, ...node.directives || []];
2933
- if (keyword === "system" || node.type === "system") {
2934
- result.systems.push(node);
2935
- } else if (keyword === "core_config" || node.type === "core_config") {
2936
- result.configs.push(node);
2937
- } else {
2938
- result.children.push(node);
2939
- }
2940
- } else if (next.type === "LPAREN") {
2941
- const possibleMethod = this.pos;
2942
- const methodName = this.advance().value;
2943
- const params = [];
2944
- this.advance();
2945
- while (!this.check("RPAREN") && !this.check("EOF") && !this.check("LBRACE")) {
2946
- if (this.check("IDENTIFIER")) {
2947
- params.push(this.advance().value);
2948
- } else {
2949
- this.advance();
2950
- }
2951
- }
2952
- if (this.check("RPAREN")) this.advance();
2953
- let returnType = "unknown";
2954
- if (this.check("COLON")) {
2955
- this.advance();
2956
- if (this.check("IDENTIFIER")) {
2957
- returnType = this.advance().value;
2958
- }
2959
- }
2960
- if (this.check("LBRACE")) {
2961
- const body = this.parseCodeBlock();
2962
- result.children.push({
2963
- type: "method",
2964
- name: methodName,
2965
- params,
2966
- returnType,
2967
- body
2968
- });
2969
- } else {
2970
- this.pos = possibleMethod;
2971
- const key = this.advance().value;
2972
- result.properties[key] = true;
2973
- }
2974
- } else {
2975
- const key = this.advance().value;
2976
- result.properties[key] = true;
2977
- }
2978
- } else if (currentDirectives.length > 0) {
2979
- const fragment = {
2980
- type: "fragment",
2981
- directives: currentDirectives,
2982
- children: [],
2983
- traits: /* @__PURE__ */ new Map(),
2984
- properties: {}
2985
- };
2986
- result.children.push(fragment);
2987
- } else if (this.check("COMMA")) {
2988
- this.advance();
2989
- } else if (this.check("LBRACKET")) {
2990
- let depth = 1;
2991
- this.advance();
2992
- while (depth > 0 && !this.check("EOF")) {
2993
- if (this.check("LBRACKET")) depth++;
2994
- else if (this.check("RBRACKET")) depth--;
2995
- this.advance();
2996
- }
2997
- } else if (this.check("LBRACE")) {
2998
- let depth = 1;
2999
- this.advance();
3000
- while (depth > 0 && !this.check("EOF")) {
3001
- if (this.check("LBRACE")) depth++;
3002
- else if (this.check("RBRACE")) depth--;
3003
- this.advance();
3004
- }
3005
- } else {
3006
- if (!this.check("RBRACE") && !this.check("EOF")) {
3007
- this.error(
3008
- `Unexpected token ${this.current().type} "${this.current().value}" in composition body. Expected property name, @directive, or child node`,
3009
- "HSP101"
3010
- );
3011
- this.advance();
3012
- }
3013
- }
3014
- this.skipNewlines();
3015
- }
3016
- this.expect("RBRACE", "Expected }");
3017
- return result;
3018
- }
3019
- /**
3020
- * Parse logic block: logic { function..., on_tick..., on_scene_load... }
3021
- */
3022
- parseLogicBlock() {
3023
- const result = {
3024
- functions: [],
3025
- eventHandlers: [],
3026
- tickHandlers: []
3027
- };
3028
- if (!this.check("LBRACE")) {
3029
- return result;
3030
- }
3031
- this.advance();
3032
- this.skipNewlines();
3033
- while (!this.check("RBRACE") && !this.check("EOF")) {
3034
- this.skipNewlines();
3035
- if (this.check("RBRACE") || this.check("EOF")) break;
3036
- if (this.check("IDENTIFIER")) {
3037
- const keyword = this.current().value;
3038
- if (keyword === "function") {
3039
- this.advance();
3040
- const funcName = this.expect("IDENTIFIER", "Expected function name").value;
3041
- const params = [];
3042
- if (this.check("LPAREN")) {
3043
- this.advance();
3044
- while (!this.check("RPAREN") && !this.check("EOF")) {
3045
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3046
- if (this.check("COLON")) {
3047
- this.advance();
3048
- this.expect("IDENTIFIER", "Expected type");
3049
- }
3050
- if (this.check("COMMA")) this.advance();
3051
- }
3052
- this.expect("RPAREN", "Expected )");
3053
- }
3054
- if (this.check("COLON")) {
3055
- this.advance();
3056
- this.expect("IDENTIFIER", "Expected return type");
3057
- }
3058
- const body = this.parseCodeBlock();
3059
- result.functions.push({ name: funcName, params, body });
3060
- } else if (keyword === "on_tick") {
3061
- this.advance();
3062
- let interval = 1;
3063
- if (this.check("LPAREN")) {
3064
- this.advance();
3065
- const intervalToken = this.expect("NUMBER", "Expected interval");
3066
- interval = parseFloat(intervalToken.value);
3067
- this.expect("RPAREN", "Expected )");
3068
- }
3069
- const body = this.parseCodeBlock();
3070
- result.tickHandlers.push({ interval, body });
3071
- } else if (keyword === "on_scene_load") {
3072
- this.advance();
3073
- const body = this.parseCodeBlock();
3074
- result.eventHandlers.push({ event: "scene_load", params: [], body });
3075
- } else if (keyword === "on") {
3076
- this.advance();
3077
- let eventName = "";
3078
- if (this.check("AT")) {
3079
- this.advance();
3080
- eventName = this.expect("IDENTIFIER", "Expected event namespace").value;
3081
- if (this.check("DOT")) {
3082
- this.advance();
3083
- eventName += "." + this.expect("IDENTIFIER", "Expected event name").value;
3084
- }
3085
- } else {
3086
- eventName = this.expect("IDENTIFIER", "Expected event name").value;
3087
- }
3088
- const params = [];
3089
- if (this.check("LPAREN")) {
3090
- this.advance();
3091
- while (!this.check("RPAREN") && !this.check("EOF")) {
3092
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3093
- if (this.check("COLON")) {
3094
- this.advance();
3095
- this.expect("IDENTIFIER", "Expected type");
3096
- }
3097
- if (this.check("COMMA")) this.advance();
3098
- }
3099
- this.expect("RPAREN", "Expected )");
3100
- }
3101
- const body = this.parseCodeBlock();
3102
- result.eventHandlers.push({ event: eventName, params, body });
3103
- } else if (keyword === "on_start") {
3104
- this.advance();
3105
- const params = [];
3106
- if (this.check("LPAREN")) {
3107
- this.advance();
3108
- while (!this.check("RPAREN") && !this.check("EOF")) {
3109
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3110
- if (this.check("COMMA")) this.advance();
3111
- }
3112
- this.expect("RPAREN", "Expected )");
3113
- }
3114
- const body = this.parseCodeBlock();
3115
- result.eventHandlers.push({ event: "start", params, body });
3116
- } else if (keyword === "on_event") {
3117
- this.advance();
3118
- let eventName = "";
3119
- const params = [];
3120
- if (this.check("LPAREN")) {
3121
- this.advance();
3122
- if (this.check("STRING")) {
3123
- eventName = this.advance().value;
3124
- } else {
3125
- eventName = this.expect("IDENTIFIER", "Expected event name").value;
3126
- }
3127
- if (this.check("COMMA")) {
3128
- this.advance();
3129
- while (!this.check("RPAREN") && !this.check("EOF")) {
3130
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3131
- if (this.check("COMMA")) this.advance();
3132
- }
3133
- }
3134
- this.expect("RPAREN", "Expected )");
3135
- }
3136
- const body = this.parseCodeBlock();
3137
- result.eventHandlers.push({ event: eventName, params, body });
3138
- } else {
3139
- this.advance();
3140
- if (this.check("LPAREN")) this.skipParens();
3141
- if (this.check("LBRACE")) this.skipBraces();
3142
- while (!this.check("RBRACE") && !this.check("EOF") && !this.check("NEWLINE")) {
3143
- this.advance();
3144
- }
3145
- }
3146
- } else {
3147
- this.advance();
3148
- }
3149
- this.skipNewlines();
3150
- }
3151
- this.expect("RBRACE", "Expected }");
3152
- return result;
3153
- }
3154
- /**
3155
- * Parse environment block with lighting directives
3156
- */
3157
- parseEnvironmentBlock() {
3158
- const properties = {};
3159
- const directives = [];
3160
- if (!this.check("LBRACE")) {
3161
- return { properties, directives };
3162
- }
3163
- this.advance();
3164
- this.skipNewlines();
3165
- while (!this.check("RBRACE") && !this.check("EOF")) {
3166
- this.skipNewlines();
3167
- if (this.check("RBRACE") || this.check("EOF")) break;
3168
- if (this.check("AT")) {
3169
- const directive = this.parseDirective();
3170
- if (directive) {
3171
- directives.push(directive);
3172
- }
3173
- } else if (this.check("IDENTIFIER")) {
3174
- const key = this.advance().value;
3175
- if (this.check("COLON") || this.check("EQUALS")) {
3176
- this.advance();
3177
- properties[key] = this.parseValue();
3178
- } else {
3179
- properties[key] = true;
3180
- }
3181
- } else {
3182
- this.advance();
3183
- }
3184
- this.skipNewlines();
3185
- }
3186
- this.expect("RBRACE", "Expected }");
3187
- return { properties, directives };
3188
- }
3189
- parsePropsBlock() {
3190
- this.skipNewlines();
3191
- const props = {};
3192
- if (this.check("LBRACE")) {
3193
- this.advance();
3194
- this.skipNewlines();
3195
- while (!this.check("RBRACE") && !this.check("EOF")) {
3196
- if (this.check("SPREAD")) {
3197
- this.advance();
3198
- const val = this.parseValue();
3199
- const spreadKey = `__spread_${Object.keys(props).length}`;
3200
- props[spreadKey] = { type: "spread", argument: val };
3201
- this.skipNewlines();
3202
- if (this.check("COMMA")) this.advance();
3203
- this.skipNewlines();
3204
- continue;
3205
- }
3206
- const key = this.expect("IDENTIFIER", "Expected property name").value;
3207
- if (this.check("COLON") || this.check("EQUALS")) {
3208
- this.advance();
3209
- props[key] = this.parseValue();
3210
- } else {
3211
- props[key] = true;
3212
- }
3213
- this.skipNewlines();
3214
- if (this.check("COMMA")) this.advance();
3215
- this.skipNewlines();
3216
- }
3217
- this.expect("RBRACE", "Expected }");
3218
- }
3219
- return props;
3220
- }
3221
- parseDialogBlock() {
3222
- this.skipNewlines();
3223
- const props = {};
3224
- const options = [];
3225
- if (this.check("LBRACE")) {
3226
- this.advance();
3227
- this.skipNewlines();
3228
- while (!this.check("RBRACE") && !this.check("EOF")) {
3229
- if (this.check("IDENTIFIER") && this.current().value === "option") {
3230
- this.advance();
3231
- const text = this.expect("STRING", "Expected option text").value;
3232
- this.expect("ARROW", "Expected ->");
3233
- let target;
3234
- if (this.check("AT")) {
3235
- const d = this.parseDirective();
3236
- target = { type: "directive", value: d };
3237
- } else {
3238
- target = this.expect("STRING", "Expected target ID").value;
3239
- }
3240
- options.push({ text, target });
3241
- } else {
3242
- const key = this.expect("IDENTIFIER", "Expected property name").value;
3243
- if (this.check("COLON") || this.check("EQUALS")) {
3244
- this.advance();
3245
- props[key] = this.parseValue();
3246
- } else {
3247
- props[key] = true;
3248
- }
3249
- }
3250
- this.skipNewlines();
3251
- }
3252
- this.expect("RBRACE", "Expected }");
3253
- }
3254
- return { props, options };
3255
- }
3256
- parseTraitConfig() {
3257
- const config = {};
3258
- if (this.check("LPAREN")) {
3259
- this.advance();
3260
- this.skipNewlines();
3261
- if (this.check("STRING") && (this.peek(1).type === "RPAREN" || this.peek(1).type === "COMMA")) {
3262
- config["default"] = this.advance().value;
3263
- if (this.check("COMMA")) this.advance();
3264
- this.skipNewlines();
3265
- }
3266
- while (!this.check("RPAREN") && !this.check("EOF")) {
3267
- this.skipNewlines();
3268
- if (this.check("RPAREN") || this.check("EOF")) break;
3269
- if (!this.check("IDENTIFIER")) {
3270
- this.advance();
3271
- continue;
3272
- }
3273
- const key = this.expect("IDENTIFIER", "Expected property name").value;
3274
- if (this.check("COLON") || this.check("EQUALS")) {
3275
- this.advance();
3276
- config[key] = this.parseValue();
3277
- } else {
3278
- config[key] = true;
3279
- }
3280
- if (this.check("COMMA")) this.advance();
3281
- this.skipNewlines();
3282
- }
3283
- this.expect("RPAREN", "Expected )");
3284
- }
3285
- return config;
3286
- }
3287
- parseStateBlock() {
3288
- const state = {};
3289
- if (this.check("LBRACE")) {
3290
- this.advance();
3291
- this.skipNewlines();
3292
- while (!this.check("RBRACE") && !this.check("EOF")) {
3293
- this.skipNewlines();
3294
- if (this.check("RBRACE") || this.check("EOF")) break;
3295
- if (this.check("SPREAD")) {
3296
- this.advance();
3297
- const spreadArg = this.parseValue();
3298
- if (spreadArg === null) {
3299
- this.error("Expected expression after spread operator (...) in state block", "HSP300");
3300
- } else {
3301
- const spreadKey = `__spread_${Object.keys(state).length}`;
3302
- state[spreadKey] = { type: "spread", argument: spreadArg };
3303
- }
3304
- this.skipNewlines();
3305
- continue;
3306
- }
3307
- const key = this.expect("IDENTIFIER", "Expected state variable name").value;
3308
- if (this.check("COLON") || this.check("EQUALS")) {
3309
- this.advance();
3310
- state[key] = this.parseValue();
3311
- } else {
3312
- state[key] = true;
3313
- }
3314
- this.skipNewlines();
3315
- }
3316
- this.expect("RBRACE", "Expected }");
3317
- }
3318
- return state;
3319
- }
3320
- /**
3321
- * Parse spatial state machine (Phase 13)
3322
- */
3323
- parseStateMachine() {
3324
- const startToken = this.current();
3325
- if (startToken.type === "STATE_MACHINE") {
3326
- this.advance();
3327
- }
3328
- const name = this.expect("IDENTIFIER", "Expected state machine name").value;
3329
- const states = [];
3330
- const transitions = [];
3331
- let initialState = "";
3332
- this.expect("LBRACE", "Expected { after state machine name");
3333
- this.skipNewlines();
3334
- while (!this.check("RBRACE") && !this.check("EOF")) {
3335
- this.skipNewlines();
3336
- if (this.check("RBRACE") || this.check("EOF")) break;
3337
- const current = this.current();
3338
- if (current.type === "INITIAL" || current.value === "initial") {
3339
- this.advance();
3340
- this.expect("COLON", "Expected : after initial");
3341
- initialState = this.expect("STRING", "Expected initial state name").value;
3342
- } else if (current.type === "STATE" || current.value === "state") {
3343
- states.push(this.parseStateNode());
3344
- } else if (current.type === "TRANSITION" || current.value === "transitions") {
3345
- transitions.push(...this.parseTransitionsBlock());
3346
- } else {
3347
- this.advance();
3348
- }
3349
- this.skipNewlines();
3350
- }
3351
- this.expect("RBRACE", "Expected } at end of state machine");
3352
- return {
3353
- type: "state-machine",
3354
- name,
3355
- initialState,
3356
- states,
3357
- transitions,
3358
- loc: {
3359
- start: { line: startToken.line, column: startToken.column },
3360
- end: { line: this.current().line, column: this.current().column }
3361
- }
3362
- };
3363
- }
3364
- parseStateNode() {
3365
- this.advance();
3366
- const name = this.expect("IDENTIFIER", "Expected state name").value;
3367
- let onEntry;
3368
- let onExit;
3369
- this.expect("LBRACE", "Expected { after state name");
3370
- this.skipNewlines();
3371
- while (!this.check("RBRACE") && !this.check("EOF")) {
3372
- this.skipNewlines();
3373
- if (this.check("RBRACE") || this.check("EOF")) break;
3374
- const current = this.current();
3375
- if (current.type === "ON_ENTRY" || current.value === "on_entry") {
3376
- this.advance();
3377
- onEntry = this.parseCodeBlock();
3378
- } else if (current.type === "ON_EXIT" || current.value === "on_exit") {
3379
- this.advance();
3380
- onExit = this.parseCodeBlock();
3381
- } else {
3382
- this.advance();
3383
- }
3384
- this.skipNewlines();
3385
- }
3386
- this.expect("RBRACE", "Expected }");
3387
- return { name, onEntry, onExit };
3388
- }
3389
- parseOnErrorNode() {
3390
- const startToken = this.previous();
3391
- const body = this.parseControlFlowBody();
3392
- return {
3393
- type: "on_error",
3394
- body,
3395
- loc: {
3396
- start: { line: startToken.line, column: startToken.column },
3397
- end: { line: this.current().line, column: this.current().column }
3398
- }
3399
- };
3400
- }
3401
- parseAssertNode() {
3402
- const startToken = this.previous();
3403
- this.expect("LPAREN", "Expected (");
3404
- const condition = this.parseExpression();
3405
- let message = "";
3406
- if (this.match(["COMMA"])) {
3407
- message = String(this.parseValue());
3408
- }
3409
- this.expect("RPAREN", "Expected )");
3410
- return {
3411
- type: "assert",
3412
- condition,
3413
- message,
3414
- loc: {
3415
- start: { line: startToken.line, column: startToken.column },
3416
- end: { line: this.current().line, column: this.current().column }
3417
- }
3418
- };
3419
- }
3420
- parseTransitionsBlock() {
3421
- const transitions = [];
3422
- this.advance();
3423
- this.expect("LBRACE", "Expected {");
3424
- this.skipNewlines();
3425
- while (!this.check("RBRACE") && !this.check("EOF")) {
3426
- this.skipNewlines();
3427
- if (this.check("RBRACE") || this.check("EOF")) break;
3428
- const from = this.expect("IDENTIFIER", "Expected source state").value;
3429
- this.expect("ARROW", "Expected ->");
3430
- const to = this.expect("IDENTIFIER", "Expected target state").value;
3431
- this.expect("COLON", "Expected :");
3432
- const event = this.expect("IDENTIFIER", "Expected event name").value;
3433
- transitions.push({ from, to, event });
3434
- this.skipNewlines();
3435
- }
3436
- this.expect("RBRACE", "Expected }");
3437
- return transitions;
3438
- }
3439
- parseControlFlowBody() {
3440
- const nodes = [];
3441
- if (this.check("LBRACE")) {
3442
- this.advance();
3443
- this.skipNewlines();
3444
- while (!this.check("RBRACE") && !this.check("EOF")) {
3445
- this.skipNewlines();
3446
- if (this.check("RBRACE") || this.check("EOF")) break;
3447
- if (this.check("AT")) {
3448
- const directive = this.parseDirective();
3449
- if (directive) {
3450
- if (directive.type === "for" || directive.type === "while" || directive.type === "if" || directive.type === "forEach") {
3451
- nodes.push({
3452
- type: "fragment",
3453
- directives: [directive],
3454
- children: [],
3455
- traits: /* @__PURE__ */ new Map(),
3456
- properties: {}
3457
- });
3458
- } else if (directive.type === "trait") {
3459
- this.warn(`Standalone trait @${directive.name} in block`);
3460
- } else {
3461
- nodes.push({
3462
- type: "fragment",
3463
- directives: [directive],
3464
- children: [],
3465
- traits: /* @__PURE__ */ new Map(),
3466
- properties: {}
3467
- });
3468
- }
3469
- }
3470
- } else if (this.check("IDENTIFIER")) {
3471
- nodes.push(this.parseNode());
3472
- } else {
3473
- this.advance();
3474
- }
3475
- this.skipNewlines();
3476
- }
3477
- this.expect("RBRACE", "Expected }");
3478
- }
3479
- return nodes;
3480
- }
3481
- parseCodeBlock() {
3482
- let code = "";
3483
- let braceDepth = 0;
3484
- if (this.check("LBRACE")) {
3485
- this.advance();
3486
- braceDepth = 1;
3487
- try {
3488
- while (braceDepth > 0 && !this.check("EOF")) {
3489
- const token = this.advance();
3490
- if (token.type === "LBRACE") {
3491
- braceDepth++;
3492
- code += "{";
3493
- } else if (token.type === "RBRACE") {
3494
- braceDepth--;
3495
- if (braceDepth > 0) {
3496
- code += "}";
3497
- }
3498
- } else if (token.type === "STRING") {
3499
- code += `"${token.value}"`;
3500
- code += " ";
3501
- } else {
3502
- code += token.value;
3503
- if (token.type === "NEWLINE") {
3504
- code += "\n";
3505
- } else {
3506
- code += " ";
3507
- }
3508
- }
3509
- }
3510
- } catch (e) {
3511
- const errorMessage = e instanceof Error ? e.message : String(e);
3512
- if (errorMessage !== "ParseError") console.error(e);
3513
- this.synchronize();
3514
- }
3515
- }
3516
- return code.trim();
3517
- }
3518
- parseInlineExpression() {
3519
- let expr = "";
3520
- while (!this.check("NEWLINE") && !this.check("LBRACE") && !this.check("EOF")) {
3521
- const token = this.advance();
3522
- expr += token.value + " ";
3523
- }
3524
- return expr.trim();
3525
- }
3526
- /**
3527
- * Parse any value or expression (Entry Point)
3528
- * Handles operators like ?? and unary operators like ...
3529
- */
3530
- parseValue() {
3531
- return this.parseAssignment();
3532
- }
3533
- /**
3534
- * Parse assignment expressions (??=)
3535
- * Much lower precedence than ternary/null-coalesce
3536
- * Example: x ??= value → x = x ?? value
3537
- */
3538
- parseAssignment() {
3539
- const expr = this.parseExpression();
3540
- if (this.check("NULL_COALESCE_ASSIGN")) {
3541
- const isAssignable = typeof expr === "string" || typeof expr === "object" && expr && "__ref" in expr || // identifier or member expression
3542
- typeof expr === "object" && expr && "type" in expr && expr.type === "member";
3543
- if (isAssignable) {
3544
- this.advance();
3545
- const value = this.parseExpression();
3546
- return {
3547
- type: "nullCoalescingAssignment",
3548
- target: expr,
3549
- value
3550
- };
3551
- } else {
3552
- throw new Error(
3553
- `Cannot use ??= on non-assignable expression at line ${this.current().line}`
3554
- );
3555
- }
3556
- }
3557
- return expr;
3558
- }
3559
- /**
3560
- * Parse expression (Entry Point for operators)
3561
- * Handles Ternary Operators: cond ? true : false
3562
- */
3563
- parseExpression() {
3564
- const condition = this.parseNullCoalesce();
3565
- if (this.check("QUESTION")) {
3566
- this.advance();
3567
- const trueValue = this.parseExpression();
3568
- this.expect("COLON", "Expected : in ternary operator");
3569
- const falseValue = this.parseExpression();
3570
- return { type: "ternary", condition, trueValue, falseValue };
3571
- }
3572
- return condition;
3573
- }
3574
- /**
3575
- * Parse binary expressions: ?? (null coalesce) — lower precedence than logical OR
3576
- */
3577
- parseNullCoalesce() {
3578
- let left = this.parseLogicalOr();
3579
- while (this.check("NULL_COALESCE")) {
3580
- this.advance();
3581
- const right = this.parseLogicalOr();
3582
- left = { type: "binary", operator: "??", left, right };
3583
- }
3584
- return left;
3585
- }
3586
- /** Parse logical OR: a || b */
3587
- parseLogicalOr() {
3588
- let left = this.parseLogicalAnd();
3589
- while (this.check("OR")) {
3590
- this.advance();
3591
- const right = this.parseLogicalAnd();
3592
- left = { type: "binary", operator: "||", left, right };
3593
- }
3594
- return left;
3595
- }
3596
- /** Parse logical AND: a && b */
3597
- parseLogicalAnd() {
3598
- let left = this.parseEquality();
3599
- while (this.check("AND")) {
3600
- this.advance();
3601
- const right = this.parseEquality();
3602
- left = { type: "binary", operator: "&&", left, right };
3603
- }
3604
- return left;
3605
- }
3606
- /** Parse equality: a == b, a != b */
3607
- parseEquality() {
3608
- let left = this.parseComparison();
3609
- while (this.check("DOUBLE_EQUALS") || this.check("NOT_EQUALS")) {
3610
- const operator = this.current().value;
3611
- this.advance();
3612
- const right = this.parseComparison();
3613
- left = { type: "binary", operator, left, right };
3614
- }
3615
- return left;
3616
- }
3617
- /** Parse comparison: a < b, a > b, a <= b, a >= b */
3618
- parseComparison() {
3619
- let left = this.parseAdditive();
3620
- while (this.check("LESS_THAN") || this.check("GREATER_THAN") || this.check("LESS_EQUAL") || this.check("GREATER_EQUAL")) {
3621
- const operator = this.current().value;
3622
- this.advance();
3623
- const right = this.parseAdditive();
3624
- left = { type: "binary", operator, left, right };
3625
- }
3626
- return left;
3627
- }
3628
- /** Parse additive: a + b, a - b */
3629
- parseAdditive() {
3630
- let left = this.parseMultiplicative();
3631
- while (this.check("PLUS") || this.check("MINUS")) {
3632
- const operator = this.current().value;
3633
- this.advance();
3634
- const right = this.parseMultiplicative();
3635
- left = { type: "binary", operator, left, right };
3636
- }
3637
- return left;
3638
- }
3639
- /** Parse multiplicative: a * b, a / b, a % b */
3640
- parseMultiplicative() {
3641
- let left = this.parseUnary();
3642
- while (this.check("ASTERISK") || this.check("SLASH") || this.check("PERCENT")) {
3643
- const operator = this.current().value;
3644
- this.advance();
3645
- const right = this.parseUnary();
3646
- left = { type: "binary", operator, left, right };
3647
- }
3648
- return left;
3649
- }
3650
- /**
3651
- * Parse unary prefix expressions (!, spread, unary minus, unary plus)
3652
- */
3653
- parseUnary() {
3654
- if (this.check("SPREAD")) {
3655
- this.advance();
3656
- const arg = this.parseUnary();
3657
- return { type: "spread", argument: arg };
3658
- }
3659
- if (this.check("EXCLAMATION")) {
3660
- this.advance();
3661
- const arg = this.parseUnary();
3662
- return { type: "unary", operator: "!", argument: arg };
3663
- }
3664
- if (this.check("MINUS") || this.check("PLUS")) {
3665
- const operator = this.current().type === "MINUS" ? "-" : "+";
3666
- this.advance();
3667
- const arg = this.parseUnary();
3668
- if (typeof arg === "number") {
3669
- return operator === "-" ? -arg : arg;
3670
- }
3671
- return { type: "unary", operator, argument: arg };
3672
- }
3673
- return this.parsePrimary();
3674
- }
3675
- /**
3676
- * Parse a primary value (literal, identifier, parenthesis, etc.)
3677
- */
3678
- parsePrimary() {
3679
- const token = this.current();
3680
- if (token.type === "STRING") {
3681
- this.advance();
3682
- return token.value;
3683
- }
3684
- if (token.type === "NUMBER") {
3685
- this.advance();
3686
- const match = token.value.match(/^(-?\d+(?:\.\d+)?(?:e[+-]?\d+)?)(.*)?$/i);
3687
- if (match) {
3688
- const num = parseFloat(match[1]);
3689
- const unit = match[2];
3690
- if (unit) {
3691
- return `${num}${unit}`;
3692
- }
3693
- return num;
3694
- }
3695
- return parseFloat(token.value);
3696
- }
3697
- if (token.type === "BOOLEAN") {
3698
- this.advance();
3699
- return token.value === "true";
3700
- }
3701
- if (token.type === "NULL") {
3702
- this.advance();
3703
- return null;
3704
- }
3705
- if (token.type === "EXPRESSION") {
3706
- this.advance();
3707
- const exprId = `expr_${this.compiledExpressions.size}`;
3708
- this.compiledExpressions.set(exprId, token.value);
3709
- return { __expr: exprId, __raw: token.value };
3710
- }
3711
- if (token.type === "TEMPLATE_STRING") {
3712
- this.advance();
3713
- return { type: "templateLiteral", value: token.value };
3714
- }
3715
- if (token.type === "LBRACKET") {
3716
- return this.parseArray();
3717
- }
3718
- if (token.type === "LBRACE") {
3719
- return this.parseBlockContent();
3720
- }
3721
- if (token.type === "HASH") {
3722
- this.advance();
3723
- const nextToken = this.current();
3724
- if (nextToken.type === "IDENTIFIER" || nextToken.type === "NUMBER") {
3725
- const hexValue = this.advance().value;
3726
- return `#${hexValue}`;
3727
- }
3728
- return `#`;
3729
- }
3730
- if (token.type === "THIS") {
3731
- this.advance();
3732
- let ref = "this";
3733
- while (this.check("DOT")) {
3734
- this.advance();
3735
- const part = this.expect("IDENTIFIER", "Expected property name").value;
3736
- ref += "." + part;
3737
- }
3738
- return { __ref: ref };
3739
- }
3740
- if (token.type === "LPAREN") {
3741
- let isArrow = false;
3742
- let i = 1;
3743
- let parenDepth = 1;
3744
- while (this.peek(i).type !== "EOF") {
3745
- const t = this.peek(i);
3746
- if (t.type === "LPAREN") parenDepth++;
3747
- if (t.type === "RPAREN") {
3748
- parenDepth--;
3749
- if (parenDepth === 0) {
3750
- const next = this.peek(i + 1);
3751
- if (next.type === "ARROW") isArrow = true;
3752
- if (next.type === "COLON") {
3753
- let j = i + 2;
3754
- while (this.peek(j).type === "IDENTIFIER" || this.peek(j).type === "LBRACKET" || this.peek(j).type === "RBRACKET")
3755
- j++;
3756
- if (this.peek(j).type === "ARROW") isArrow = true;
3757
- }
3758
- break;
3759
- }
3760
- }
3761
- i++;
3762
- }
3763
- if (isArrow) {
3764
- return this.parseArrowFunction();
3765
- }
3766
- return this.parseParenExpression();
3767
- }
3768
- if (token.type === "MATCH") {
3769
- return this.parseMatchExpression();
3770
- }
3771
- const isIdentifierLike = token.type === "IDENTIFIER" || token.type === "STATE" || token.type === "INITIAL" || token.type === "STATE_MACHINE" || token.type === "TRANSITION" || token.type === "ON_ENTRY" || token.type === "ON_EXIT";
3772
- if (isIdentifierLike) {
3773
- if (this.peek(1).type === "ARROW") {
3774
- return this.parseArrowFunction();
3775
- }
3776
- this.advance();
3777
- let ref = token.value;
3778
- while (this.check("DOT") || this.check("OPTIONAL_DOT") || this.check("LBRACKET")) {
3779
- if (this.check("OPTIONAL_DOT")) {
3780
- this.advance();
3781
- const nextToken = this.current();
3782
- const isPropertyName = nextToken.type === "IDENTIFIER" || nextToken.type === "STATE" || nextToken.type === "INITIAL" || nextToken.type === "STATE_MACHINE" || nextToken.type === "TRANSITION" || nextToken.type === "ON_ENTRY" || nextToken.type === "ON_EXIT";
3783
- if (isPropertyName) {
3784
- ref += "?." + this.advance().value;
3785
- } else {
3786
- this.error("Expected property name after optional chaining (?.)", "HSP002");
3787
- }
3788
- } else if (this.check("LBRACKET")) {
3789
- this.advance();
3790
- const indexExpr = this.parseValue();
3791
- this.expect("RBRACKET", "Expected ]");
3792
- const base = ref;
3793
- return { type: "computedMember", object: { __ref: base }, property: indexExpr };
3794
- } else {
3795
- this.advance();
3796
- const nextToken = this.current();
3797
- const isPropertyName = nextToken.type === "IDENTIFIER" || nextToken.type === "STATE" || nextToken.type === "INITIAL" || nextToken.type === "STATE_MACHINE" || nextToken.type === "TRANSITION" || nextToken.type === "ON_ENTRY" || nextToken.type === "ON_EXIT";
3798
- if (isPropertyName) {
3799
- ref += "." + this.advance().value;
3800
- } else {
3801
- this.error("Expected property name after dot (.)", "HSP002");
3802
- }
3803
- }
3804
- }
3805
- if (this.check("LPAREN")) {
3806
- const args = this.parseParenExpression();
3807
- return { type: "call", callee: ref, args };
3808
- }
3809
- return { __ref: ref };
3810
- }
3811
- if (this.check("AT")) {
3812
- const dir = this.parseDirective();
3813
- return dir;
3814
- }
3815
- this.error(
3816
- `Unexpected token in expression: ${token.type} "${token.value}". Expected value, identifier, or expression`,
3817
- "HSP300"
3818
- );
3819
- const err = new Error("ParseError");
3820
- err.message = "ParseError";
3821
- throw err;
3822
- }
3823
- parseParenExpression() {
3824
- this.expect("LPAREN", "Expected (");
3825
- const items = [];
3826
- while (!this.check("RPAREN") && !this.check("EOF")) {
3827
- items.push(this.parseValue());
3828
- if (this.check("COMMA")) this.advance();
3829
- }
3830
- this.expect("RPAREN", "Expected )");
3831
- return items.length === 1 ? items[0] : items;
3832
- }
3833
- parseArrowFunction() {
3834
- const params = [];
3835
- if (this.check("LPAREN")) {
3836
- this.advance();
3837
- while (!this.check("RPAREN") && !this.check("EOF")) {
3838
- if (this.check("SPREAD")) {
3839
- this.advance();
3840
- const name2 = this.expect("IDENTIFIER", "Expected parameter name after ...").value;
3841
- let type2 = null;
3842
- if (this.check("COLON")) {
3843
- this.advance();
3844
- type2 = this.expect("IDENTIFIER", "Expected type").value;
3845
- }
3846
- params.push({ name: name2, type: type2, rest: true });
3847
- if (this.check("COMMA")) this.advance();
3848
- break;
3849
- }
3850
- const name = this.expect("IDENTIFIER", "Expected parameter name").value;
3851
- let type = null;
3852
- if (this.check("COLON")) {
3853
- this.advance();
3854
- type = this.expect("IDENTIFIER", "Expected type").value;
3855
- }
3856
- params.push({ name, type });
3857
- if (this.check("COMMA")) this.advance();
3858
- }
3859
- this.expect("RPAREN", "Expected )");
3860
- } else {
3861
- if (this.check("SPREAD")) {
3862
- this.advance();
3863
- const name = this.expect("IDENTIFIER", "Expected parameter name after ...").value;
3864
- params.push({ name, type: null, rest: true });
3865
- } else {
3866
- const name = this.expect("IDENTIFIER", "Expected parameter name").value;
3867
- params.push({ name, type: null });
3868
- }
3869
- }
3870
- let returnType = null;
3871
- if (this.check("COLON")) {
3872
- this.advance();
3873
- returnType = this.expect("IDENTIFIER", "Expected return type").value;
3874
- }
3875
- this.expect("ARROW", "Expected =>");
3876
- let body;
3877
- if (this.check("LBRACE")) {
3878
- body = this.parseCodeBlock();
3879
- } else {
3880
- body = this.parseInlineExpression();
3881
- }
3882
- return { type: "arrow_function", params, returnType, body };
3883
- }
3884
- parseArray() {
3885
- const arr = [];
3886
- this.expect("LBRACKET", "Expected [");
3887
- this.skipNewlines();
3888
- while (!this.check("RBRACKET") && !this.check("EOF")) {
3889
- const beforePos = this.pos;
3890
- this.skipNewlines();
3891
- if (this.check("RBRACKET") || this.check("EOF")) break;
3892
- if (this.check("SPREAD")) {
3893
- this.advance();
3894
- const spreadArg = this.parseValue();
3895
- if (spreadArg === null) {
3896
- this.error(
3897
- "Expected expression after spread operator (...) in array. Example: [...items]",
3898
- "HSP300"
3899
- );
3900
- } else {
3901
- arr.push({ type: "spread", argument: spreadArg });
3902
- }
3903
- } else {
3904
- const value = this.parseValue();
3905
- if (value !== null) {
3906
- arr.push(value);
3907
- } else if (this.pos === beforePos) {
3908
- this.advance();
3909
- }
3910
- }
3911
- if (this.check("COMMA")) this.advance();
3912
- this.skipNewlines();
3913
- }
3914
- this.expect("RBRACKET", "Expected ]");
3915
- return arr;
3916
- }
3917
- parseObject() {
3918
- const obj = {};
3919
- this.expect("LBRACE", "Expected {");
3920
- this.skipNewlines();
3921
- while (!this.check("RBRACE") && !this.check("EOF")) {
3922
- this.skipNewlines();
3923
- if (this.check("RBRACE") || this.check("EOF")) break;
3924
- if (this.check("SPREAD")) {
3925
- this.advance();
3926
- const spreadArg = this.parseValue();
3927
- if (spreadArg === null) {
3928
- this.error(
3929
- "Expected expression after spread operator (...) in object. Example: {...template}",
3930
- "HSP300"
3931
- );
3932
- } else {
3933
- const spreadKey = `__spread_${Object.keys(obj).length}`;
3934
- obj[spreadKey] = { type: "spread", argument: spreadArg };
3935
- }
3936
- } else if (this.check("IDENTIFIER")) {
3937
- const key = this.advance().value;
3938
- if (this.check("COLON") || this.check("EQUALS")) {
3939
- this.advance();
3940
- obj[key] = this.parseValue();
3941
- } else {
3942
- obj[key] = true;
3943
- }
3944
- } else {
3945
- this.advance();
3946
- continue;
3947
- }
3948
- if (this.check("COMMA")) this.advance();
3949
- this.skipNewlines();
3950
- }
3951
- this.expect("RBRACE", "Expected }");
3952
- return obj;
3953
- }
3954
- /**
3955
- * Parse a match expression: match subject { pattern => body, ... }
3956
- * Supports:
3957
- * - Literal patterns: "idle", 42, true
3958
- * - Wildcard pattern: _
3959
- * - Binding patterns: x (captures value)
3960
- * - Guard clauses: pattern if condition => body
3961
- */
3962
- parseMatchExpression() {
3963
- const startToken = this.current();
3964
- this.expect("MATCH", "Expected match keyword");
3965
- const subject = this.parseValue();
3966
- if (subject === null) {
3967
- this.error("Expected expression after match keyword", "HSP300");
3968
- return null;
3969
- }
3970
- this.expect("LBRACE", "Expected { after match subject");
3971
- this.skipNewlines();
3972
- const cases = [];
3973
- let hasWildcard = false;
3974
- while (!this.check("RBRACE") && !this.check("EOF")) {
3975
- this.skipNewlines();
3976
- if (this.check("RBRACE")) break;
3977
- const caseNode = this.parseMatchCase();
3978
- if (caseNode) {
3979
- cases.push(caseNode);
3980
- if (caseNode.pattern && caseNode.pattern.type === "wildcard-pattern") {
3981
- hasWildcard = true;
3982
- }
3983
- }
3984
- if (this.check("COMMA")) this.advance();
3985
- this.skipNewlines();
3986
- }
3987
- this.expect("RBRACE", "Expected } to close match expression");
3988
- return {
3989
- type: "match",
3990
- subject,
3991
- cases,
3992
- hasWildcard,
3993
- sourceLocation: {
3994
- line: startToken.line,
3995
- column: startToken.column
3996
- }
3997
- };
3998
- }
3999
- /**
4000
- * Parse a single match case: pattern [if guard] => body
4001
- */
4002
- parseMatchCase() {
4003
- const pattern = this.parseMatchPattern();
4004
- if (!pattern) {
4005
- return null;
4006
- }
4007
- let guard;
4008
- if (this.check("IDENTIFIER") && this.current().value === "if") {
4009
- this.advance();
4010
- let guardExpr = "";
4011
- while (!this.check("ARROW") && !this.check("EOF") && !this.check("RBRACE")) {
4012
- guardExpr += this.current().value + " ";
4013
- this.advance();
4014
- }
4015
- guard = guardExpr.trim();
4016
- }
4017
- this.expect("ARROW", "Expected => after match pattern");
4018
- let body;
4019
- if (this.check("LBRACE")) {
4020
- body = this.parseBlockContent();
4021
- } else {
4022
- body = this.parseValue();
4023
- }
4024
- return {
4025
- type: "match-case",
4026
- pattern,
4027
- body,
4028
- guard
4029
- };
4030
- }
4031
- /**
4032
- * Parse a match pattern:
4033
- * - Literal: "string", 42, true
4034
- * - Wildcard: _
4035
- * - Binding: identifier
4036
- */
4037
- parseMatchPattern() {
4038
- const token = this.current();
4039
- if (token.type === "UNDERSCORE" || token.type === "IDENTIFIER" && token.value === "_") {
4040
- this.advance();
4041
- return {
4042
- type: "wildcard-pattern",
4043
- symbol: "_"
4044
- };
4045
- }
4046
- if (token.type === "STRING") {
4047
- this.advance();
4048
- return {
4049
- type: "literal-pattern",
4050
- value: token.value
4051
- };
4052
- }
4053
- if (token.type === "NUMBER") {
4054
- this.advance();
4055
- return {
4056
- type: "literal-pattern",
4057
- value: parseFloat(token.value)
4058
- };
4059
- }
4060
- if (token.type === "BOOLEAN") {
4061
- this.advance();
4062
- return {
4063
- type: "literal-pattern",
4064
- value: token.value === "true"
4065
- };
4066
- }
4067
- if (token.type === "IDENTIFIER") {
4068
- this.advance();
4069
- return {
4070
- type: "binding-pattern",
4071
- name: token.value
4072
- };
4073
- }
4074
- if (token.type === "NULL") {
4075
- this.advance();
4076
- return {
4077
- type: "literal-pattern",
4078
- value: null
4079
- };
4080
- }
4081
- this.error(`Expected match pattern (literal, identifier, or _), got ${token.type}`, "HSP300");
4082
- return null;
4083
- }
4084
- current() {
4085
- return this.tokens[this.pos] || { type: "EOF", value: "", line: 0, column: 0 };
4086
- }
4087
- peek(offset = 0) {
4088
- return this.tokens[this.pos + offset] || { type: "EOF", value: "", line: 0, column: 0 };
4089
- }
4090
- check(type) {
4091
- return this.current().type === type;
4092
- }
4093
- advance() {
4094
- const token = this.current();
4095
- if (this.pos < this.tokens.length) {
4096
- this.pos++;
4097
- }
4098
- return token;
4099
- }
4100
- previous() {
4101
- return this.tokens[this.pos - 1] || this.current();
4102
- }
4103
- match(types) {
4104
- for (const type of types) {
4105
- if (this.check(type)) {
4106
- return this.advance();
4107
- }
4108
- }
4109
- return null;
4110
- }
4111
- expect(type, message) {
4112
- if (!this.check(type)) {
4113
- const current = this.current();
4114
- const fullMessage = `${message}. Got ${current.type} "${current.value}"`;
4115
- let errorCode = "HSP001";
4116
- let suggestion;
4117
- switch (type) {
4118
- case "RBRACE":
4119
- errorCode = "HSP004";
4120
- suggestion = "Check for matching opening brace { and ensure all blocks are properly closed";
4121
- break;
4122
- case "RBRACKET":
4123
- errorCode = "HSP005";
4124
- suggestion = "Check for matching opening bracket [ and ensure all arrays are properly closed";
4125
- break;
4126
- case "RPAREN":
4127
- errorCode = "HSP006";
4128
- suggestion = "Check for matching opening parenthesis ( and ensure all expressions are properly closed";
4129
- break;
4130
- case "COLON":
4131
- errorCode = "HSP009";
4132
- suggestion = "Properties use colon syntax: propertyName: value";
4133
- break;
4134
- case "IDENTIFIER":
4135
- errorCode = "HSP002";
4136
- if (current.type === "IDENTIFIER") {
4137
- const similar = findSimilarKeyword(current.value);
4138
- if (similar) {
4139
- suggestion = `Did you mean '${similar}'?`;
4140
- }
4141
- }
4142
- break;
4143
- case "LBRACE":
4144
- errorCode = "HSP100";
4145
- suggestion = "Expected opening brace { to start block";
4146
- break;
4147
- default:
4148
- errorCode = "HSP001";
4149
- }
4150
- if (suggestion) {
4151
- this.errorWithSuggestion(fullMessage, suggestion, errorCode);
4152
- } else {
4153
- this.error(fullMessage, errorCode);
4154
- }
4155
- if (type === "RBRACE" || type === "LBRACE" || type === "IDENTIFIER") {
4156
- this.synchronize();
4157
- }
4158
- return current;
4159
- }
4160
- return this.advance();
4161
- }
4162
- skipNewlines() {
4163
- while (this.check("NEWLINE") || this.check("INDENT") || this.check("DEDENT")) {
4164
- this.advance();
4165
- }
4166
- }
4167
- /** Skip a balanced parenthesised list ( ... ) including nested parens */
4168
- skipParens() {
4169
- if (!this.check("LPAREN")) return;
4170
- this.advance();
4171
- let depth = 1;
4172
- while (depth > 0 && !this.check("EOF")) {
4173
- if (this.check("LPAREN")) depth++;
4174
- if (this.check("RPAREN")) depth--;
4175
- this.advance();
4176
- }
4177
- }
4178
- skipBraces() {
4179
- if (!this.check("LBRACE")) return;
4180
- this.advance();
4181
- let depth = 1;
4182
- while (depth > 0 && !this.check("EOF")) {
4183
- if (this.check("LBRACE")) depth++;
4184
- if (this.check("RBRACE")) depth--;
4185
- this.advance();
4186
- }
4187
- }
4188
- error(message, code = "HSP001") {
4189
- const token = this.current();
4190
- const line = token.line;
4191
- const column = token.column;
4192
- let suggestion;
4193
- if (token.type === "IDENTIFIER") {
4194
- const similar = findSimilarKeyword(token.value);
4195
- if (similar) {
4196
- suggestion = `Did you mean '${similar}'?`;
4197
- }
4198
- }
4199
- this.errors.push(
4200
- createRichError(code, message, line, column, {
4201
- source: this.source,
4202
- suggestion,
4203
- severity: "error"
4204
- })
4205
- );
4206
- }
4207
- errorWithSuggestion(message, suggestion, code = "HSP001") {
4208
- const token = this.current();
4209
- this.errors.push(
4210
- createRichError(code, message, token.line, token.column, {
4211
- source: this.source,
4212
- suggestion,
4213
- severity: "error"
4214
- })
4215
- );
4216
- }
4217
- traitError(traitName) {
4218
- const token = this.current();
4219
- this.errors.push(createTraitError(traitName, token.line, token.column, this.source));
4220
- }
4221
- warn(message, code = "HSP001") {
4222
- const token = this.current();
4223
- this.warnings.push(
4224
- createRichError(code, message, token.line, token.column, {
4225
- source: this.source,
4226
- severity: "warning"
4227
- })
4228
- );
4229
- }
4230
- /**
4231
- * Detect common mistakes and provide context-aware error messages
4232
- */
4233
- detectCommonMistake() {
4234
- const current = this.current();
4235
- const prev = this.pos > 0 ? this.tokens[this.pos - 1] : null;
4236
- const next = this.pos + 1 < this.tokens.length ? this.tokens[this.pos + 1] : null;
4237
- if (current.type === "EQUALS" && prev?.type === "IDENTIFIER") {
4238
- return {
4239
- message: `Unexpected '=' after property name '${prev.value}'`,
4240
- suggestion: "Use ':' instead of '=' for property assignment. Example: propertyName: value",
4241
- code: "HSP009"
4242
- };
4243
- }
4244
- if (current.value === ";") {
4245
- return {
4246
- message: "Unexpected semicolon",
4247
- suggestion: "HoloScript does not require semicolons. Remove the semicolon to continue.",
4248
- code: "HSP001"
4249
- };
4250
- }
4251
- if (current.type === "IDENTIFIER" && VR_TRAITS.includes(current.value)) {
4252
- if (prev?.type !== "AT") {
4253
- return {
4254
- message: `'${current.value}' is a trait and requires '@' prefix`,
4255
- suggestion: `Use '@${current.value}' to apply this trait`,
4256
- code: "HSP200"
4257
- };
4258
- }
4259
- }
4260
- if (current.type === "STRING" && next?.type === "COLON") {
4261
- return {
4262
- message: "Property names should not be quoted in HoloScript",
4263
- suggestion: `Remove quotes: use ${current.value.replace(/['"]/g, "")}: instead of "${current.value}":`,
4264
- code: "HSP101"
4265
- };
4266
- }
4267
- if (current.value === "function" && prev?.type === "COLON") {
4268
- return {
4269
- message: "Unexpected 'function' keyword",
4270
- suggestion: "Use arrow function syntax: handler: (args) => { ... }",
4271
- code: "HSP300"
4272
- };
4273
- }
4274
- if (current.type === "SPREAD" && next && (next.type === "RBRACE" || next.type === "RBRACKET" || next.type === "COMMA" || next.type === "NEWLINE")) {
4275
- return {
4276
- message: "Spread operator (...) requires a target expression",
4277
- suggestion: "Provide an expression to spread: ...targetObject or ...targetArray",
4278
- code: "HSP002"
4279
- };
4280
- }
4281
- return null;
4282
- }
4283
- /**
4284
- * Enhanced error reporting with common mistake detection
4285
- */
4286
- errorWithContext(message, code = "HSP001") {
4287
- const commonMistake = this.detectCommonMistake();
4288
- if (commonMistake) {
4289
- this.errorWithSuggestion(commonMistake.message, commonMistake.suggestion, commonMistake.code);
4290
- return;
4291
- }
4292
- this.error(message, code);
4293
- }
4294
- /**
4295
- * Synchronize parser state after an error
4296
- * Skips tokens until a potential recovery point (newline followed by keyword/directive)
4297
- */
4298
- synchronize() {
4299
- this.advance();
4300
- while (!this.check("EOF")) {
4301
- if (this.check("RBRACE")) {
4302
- return;
4303
- }
4304
- if (this.check("IDENTIFIER") && ["orb", "template", "logic", "object", "composition", "scene", "group"].includes(
4305
- this.current().value
4306
- )) {
4307
- return;
4308
- }
4309
- if (this.check("AT")) {
4310
- return;
4311
- }
4312
- this.advance();
4313
- }
4314
- }
4315
- /**
4316
- * Mini-sync for property lists: skips until next line or comma
4317
- */
4318
- synchronizeProperty() {
4319
- this.advance();
4320
- while (!this.check("EOF")) {
4321
- if (this.check("RBRACE") || this.check("LBRACE")) {
4322
- return;
4323
- }
4324
- if (this.check("IDENTIFIER") || this.check("STRING") || this.check("SPREAD") || this.check("AT")) {
4325
- return;
4326
- }
4327
- if (this.check("NEWLINE")) {
4328
- this.advance();
4329
- this.skipNewlines();
4330
- if (this.check("IDENTIFIER") || this.check("STRING") || this.check("SPREAD") || this.check("AT")) {
4331
- return;
4332
- }
4333
- }
4334
- if (this.check("COMMA")) {
4335
- this.advance();
4336
- return;
4337
- }
4338
- this.advance();
4339
- }
4340
- }
4341
- /**
4342
- * Synchronize for array context: skip to next valid array element or closing bracket
4343
- */
4344
- synchronizeArray() {
4345
- while (!this.check("EOF")) {
4346
- if (this.check("RBRACKET")) {
4347
- return;
4348
- }
4349
- if (this.check("COMMA")) {
4350
- this.advance();
4351
- this.skipNewlines();
4352
- return;
4353
- }
4354
- if (this.check("NEWLINE")) {
4355
- this.advance();
4356
- this.skipNewlines();
4357
- if (this.check("RBRACKET") || this.isLikelyValue(this.current()) || this.check("SPREAD")) {
4358
- return;
4359
- }
4360
- }
4361
- this.advance();
4362
- }
4363
- }
4364
- /**
4365
- * Synchronize for expression context: skip to end of expression
4366
- */
4367
- synchronizeExpression() {
4368
- let parenDepth = 0;
4369
- let braceDepth = 0;
4370
- let bracketDepth = 0;
4371
- while (!this.check("EOF")) {
4372
- const token = this.current();
4373
- if (token.type === "LPAREN") parenDepth++;
4374
- else if (token.type === "RPAREN") {
4375
- if (parenDepth === 0) return;
4376
- parenDepth--;
4377
- } else if (token.type === "LBRACE") braceDepth++;
4378
- else if (token.type === "RBRACE") {
4379
- if (braceDepth === 0) return;
4380
- braceDepth--;
4381
- } else if (token.type === "LBRACKET") bracketDepth++;
4382
- else if (token.type === "RBRACKET") {
4383
- if (bracketDepth === 0) return;
4384
- bracketDepth--;
4385
- }
4386
- if (parenDepth === 0 && braceDepth === 0 && bracketDepth === 0) {
4387
- if (this.check("NEWLINE") || this.check("COMMA")) {
4388
- return;
4389
- }
4390
- }
4391
- this.advance();
4392
- }
4393
- }
4394
- /**
4395
- * Attempt to recover from missing colon by looking ahead
4396
- * Returns true if recovery was successful
4397
- */
4398
- tryRecoverMissingColon() {
4399
- if (this.check("IDENTIFIER")) {
4400
- const nextPos = this.pos + 1;
4401
- if (nextPos < this.tokens.length) {
4402
- const nextToken = this.tokens[nextPos];
4403
- if (this.isLikelyValue(nextToken) || nextToken.type === "IDENTIFIER") {
4404
- this.warn(
4405
- `Missing colon after property "${this.current().value}". Consider adding ':' between property name and value`,
4406
- "HSP009"
4407
- );
4408
- return true;
4409
- }
4410
- }
4411
- }
4412
- return false;
4413
- }
4414
- /**
4415
- * Helper to check if current token is a natural boundary after a value
4416
- */
4417
- isValueBoundary() {
4418
- return this.check("NEWLINE") || this.check("RBRACE") || this.check("COMMA") || this.check("IDENTIFIER") || this.check("SPREAD") || this.check("AT") || this.check("EOF");
4419
- }
4420
- /**
4421
- * Helper to check if a token is likely the start of a value
4422
- */
4423
- isLikelyValue(token) {
4424
- return token.type === "STRING" || token.type === "NUMBER" || token.type === "LBRACKET" || token.type === "LBRACE" || token.type === "BOOLEAN" || token.type === "NULL" || token.type === "TEMPLATE_STRING";
4425
- }
4426
- /**
4427
- * Parse a block of raw code (balanced braces)
4428
- */
4429
- parseRawBlock() {
4430
- const startToken = this.expect("LBRACE", "Expected {");
4431
- const startOffset = startToken.offset + 1;
4432
- let braceDepth = 1;
4433
- let endOffset = startOffset;
4434
- while (braceDepth > 0 && this.pos < this.tokens.length) {
4435
- const token = this.current();
4436
- if (token.type === "EOF") break;
4437
- if (token.type === "LBRACE") {
4438
- braceDepth++;
4439
- } else if (token.type === "RBRACE") {
4440
- braceDepth--;
4441
- if (braceDepth === 0) {
4442
- endOffset = token.offset;
4443
- break;
4444
- }
4445
- }
4446
- this.advance();
4447
- }
4448
- this.expect("RBRACE", "Expected }");
4449
- return this.source.substring(startOffset, endOffset).trim();
4450
- }
4451
- };
4452
- function createParser(options) {
4453
- return new HoloScriptPlusParser(options);
4454
- }
4455
- function parse(source, options) {
4456
- const parser = createParser(options);
4457
- return parser.parse(source);
4458
- }
4459
-
4460
- export { ChunkDetector, HSPLUS_ERROR_CODES, HoloScriptPlusParser, ParseCache, createKeywordError, createParser, createRichError, createTraitError, findSimilarKeyword, findSimilarTrait, formatRichError, formatRichErrors, getErrorCodeDocumentation, getSourceContext, globalParseCache, parse };
4461
- //# sourceMappingURL=chunk-V3NN3HPP.js.map
4462
- //# sourceMappingURL=chunk-V3NN3HPP.js.map