semantifold 0.5.0 → 0.6.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 (182) hide show
  1. package/README.md +10 -7
  2. package/build/src/backends/android.js +7 -3
  3. package/build/src/backends/identifiers.d.ts +6 -0
  4. package/build/src/backends/identifiers.d.ts.map +1 -1
  5. package/build/src/backends/identifiers.js +24 -1
  6. package/build/src/backends/ios.js +2 -2
  7. package/build/src/backends/native-validation.d.ts +2 -2
  8. package/build/src/backends/native-validation.d.ts.map +1 -1
  9. package/build/src/backends/native-validation.js +2 -2
  10. package/build/src/backends/scalars.d.ts.map +1 -1
  11. package/build/src/backends/scalars.js +2 -1
  12. package/build/src/backends/shared.js +4 -4
  13. package/build/src/backends/zig-runtime.d.ts +5 -0
  14. package/build/src/backends/zig-runtime.d.ts.map +1 -0
  15. package/build/src/backends/zig-runtime.js +92 -0
  16. package/build/src/backends/zig-validation.d.ts +9 -0
  17. package/build/src/backends/zig-validation.d.ts.map +1 -0
  18. package/build/src/backends/zig-validation.js +73 -0
  19. package/build/src/backends/zig.d.ts +42 -0
  20. package/build/src/backends/zig.d.ts.map +1 -0
  21. package/build/src/backends/zig.js +584 -0
  22. package/build/src/frontends/scalars.d.ts.map +1 -1
  23. package/build/src/frontends/scalars.js +2 -1
  24. package/build/src/frontends/zig-parser.d.ts +31 -0
  25. package/build/src/frontends/zig-parser.d.ts.map +1 -0
  26. package/build/src/frontends/zig-parser.js +17 -0
  27. package/build/src/frontends/zig.d.ts +14 -0
  28. package/build/src/frontends/zig.d.ts.map +1 -0
  29. package/build/src/frontends/zig.js +970 -0
  30. package/build/src/language-registry.d.ts.map +1 -1
  31. package/build/src/language-registry.js +30 -1
  32. package/build/src/mapping.js +2 -2
  33. package/build/src/semantic/provenance.js +3 -3
  34. package/build/src/semantic/types.d.ts +2 -2
  35. package/build/src/semantic/types.d.ts.map +1 -1
  36. package/build/src/semantic/types.js +2 -2
  37. package/build/src/semantic/validate.js +2 -2
  38. package/build/src/toolchains.d.ts +6 -0
  39. package/build/src/toolchains.d.ts.map +1 -1
  40. package/build/src/toolchains.js +2 -1
  41. package/build/src/zig-bindings.d.ts +10 -0
  42. package/build/src/zig-bindings.d.ts.map +1 -0
  43. package/build/src/zig-bindings.js +54 -0
  44. package/docs/android.md +2 -2
  45. package/docs/architecture.md +11 -5
  46. package/docs/goals.md +1 -1
  47. package/docs/language-support.md +8 -4
  48. package/docs/parser-qualification.md +31 -1
  49. package/docs/source-maps.md +5 -3
  50. package/docs/testing.md +26 -4
  51. package/docs/zig.md +33 -0
  52. package/node_modules/semantifold-tree-sitter-zig-internal/LICENSE +15 -0
  53. package/node_modules/semantifold-tree-sitter-zig-internal/README.md +5 -0
  54. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/LICENSE +21 -0
  55. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/README.md +21 -0
  56. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/binding.gyp +29 -0
  57. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/bindings/node/binding.cc +20 -0
  58. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/bindings/node/binding_test.js +9 -0
  59. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/bindings/node/index.d.ts +28 -0
  60. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/bindings/node/index.js +11 -0
  61. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/grammar.js +900 -0
  62. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/package.json +57 -0
  63. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/prebuilds/darwin-arm64/@tree-sitter-grammars+tree-sitter-zig.node +0 -0
  64. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/prebuilds/darwin-x64/@tree-sitter-grammars+tree-sitter-zig.node +0 -0
  65. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/prebuilds/linux-arm64/@tree-sitter-grammars+tree-sitter-zig.node +0 -0
  66. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/prebuilds/linux-x64/@tree-sitter-grammars+tree-sitter-zig.node +0 -0
  67. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/prebuilds/win32-arm64/@tree-sitter-grammars+tree-sitter-zig.node +0 -0
  68. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/prebuilds/win32-x64/@tree-sitter-grammars+tree-sitter-zig.node +0 -0
  69. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/queries/folds.scm +23 -0
  70. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/queries/highlights.scm +291 -0
  71. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/queries/indents.scm +22 -0
  72. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/queries/injections.scm +10 -0
  73. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/src/grammar.json +6570 -0
  74. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/src/node-types.json +3178 -0
  75. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/src/parser.c +169829 -0
  76. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/src/tree_sitter/alloc.h +54 -0
  77. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/src/tree_sitter/array.h +291 -0
  78. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/src/tree_sitter/parser.h +266 -0
  79. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/tree-sitter-zig.wasm +0 -0
  80. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/@tree-sitter-grammars/tree-sitter-zig/tree-sitter.json +38 -0
  81. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/LICENSE +21 -0
  82. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/README.md +128 -0
  83. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/binding.gyp +80 -0
  84. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/index.js +916 -0
  85. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/package.json +76 -0
  86. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/prebuilds/darwin-arm64/tree-sitter.node +0 -0
  87. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/prebuilds/darwin-x64/tree-sitter.node +0 -0
  88. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/prebuilds/linux-arm64/tree-sitter.node +0 -0
  89. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/prebuilds/linux-x64/tree-sitter.node +0 -0
  90. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/prebuilds/win32-arm64/tree-sitter.node +0 -0
  91. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/prebuilds/win32-x64/tree-sitter.node +0 -0
  92. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/addon_data.h +47 -0
  93. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/binding.cc +35 -0
  94. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/conversions.cc +140 -0
  95. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/conversions.h +22 -0
  96. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/language.cc +106 -0
  97. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/language.h +17 -0
  98. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/logger.cc +70 -0
  99. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/logger.h +19 -0
  100. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/lookaheaditerator.cc +122 -0
  101. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/lookaheaditerator.h +33 -0
  102. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/node.cc +1088 -0
  103. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/node.h +30 -0
  104. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/parser.cc +306 -0
  105. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/parser.h +35 -0
  106. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/query.cc +397 -0
  107. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/query.h +40 -0
  108. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/tree.cc +316 -0
  109. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/tree.h +45 -0
  110. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/tree_cursor.cc +213 -0
  111. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/src/tree_cursor.h +52 -0
  112. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/tree-sitter.d.ts +1042 -0
  113. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/include/tree_sitter/api.h +1318 -0
  114. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/alloc.c +48 -0
  115. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/alloc.h +41 -0
  116. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/array.h +291 -0
  117. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/atomic.h +68 -0
  118. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/clock.h +146 -0
  119. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/error_costs.h +11 -0
  120. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/get_changed_ranges.c +501 -0
  121. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/get_changed_ranges.h +36 -0
  122. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/host.h +21 -0
  123. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/language.c +223 -0
  124. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/language.h +297 -0
  125. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/length.h +52 -0
  126. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/lexer.c +435 -0
  127. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/lexer.h +49 -0
  128. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/lib.c +12 -0
  129. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/node.c +920 -0
  130. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/parser.c +2165 -0
  131. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/parser.h +266 -0
  132. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/point.h +62 -0
  133. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/portable/endian.h +206 -0
  134. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/query.c +4187 -0
  135. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/reduce_action.h +34 -0
  136. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/reusable_node.h +95 -0
  137. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/stack.c +899 -0
  138. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/stack.h +130 -0
  139. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/subtree.c +1066 -0
  140. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/subtree.h +399 -0
  141. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/tree.c +170 -0
  142. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/tree.h +31 -0
  143. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/tree_cursor.c +712 -0
  144. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/tree_cursor.h +48 -0
  145. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/ts_assert.h +11 -0
  146. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/ICU_SHA +1 -0
  147. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/LICENSE +414 -0
  148. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/README.md +29 -0
  149. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/ptypes.h +1 -0
  150. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/umachine.h +448 -0
  151. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/urename.h +1 -0
  152. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/utf.h +1 -0
  153. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/utf16.h +733 -0
  154. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode/utf8.h +881 -0
  155. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/unicode.h +83 -0
  156. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/wasm/stdlib-symbols.txt +24 -0
  157. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/wasm/stdlib.c +109 -0
  158. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/wasm/wasm-stdlib.h +1302 -0
  159. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/wasm_store.c +1859 -0
  160. package/node_modules/semantifold-tree-sitter-zig-internal/node_modules/tree-sitter/vendor/tree-sitter/lib/src/wasm_store.h +31 -0
  161. package/node_modules/semantifold-tree-sitter-zig-internal/package.json +21 -0
  162. package/node_modules/semantifold-tree-sitter-zig-internal/src/zig.js +134 -0
  163. package/package.json +11 -6
  164. package/src/backends/android.js +6 -2
  165. package/src/backends/identifiers.js +24 -0
  166. package/src/backends/ios.js +1 -1
  167. package/src/backends/native-validation.js +1 -1
  168. package/src/backends/scalars.js +1 -0
  169. package/src/backends/shared.js +3 -3
  170. package/src/backends/zig-runtime.js +93 -0
  171. package/src/backends/zig-validation.js +68 -0
  172. package/src/backends/zig.js +579 -0
  173. package/src/frontends/scalars.js +1 -0
  174. package/src/frontends/zig-parser.js +20 -0
  175. package/src/frontends/zig.js +994 -0
  176. package/src/language-registry.js +30 -0
  177. package/src/mapping.js +1 -1
  178. package/src/semantic/provenance.js +2 -2
  179. package/src/semantic/types.js +1 -1
  180. package/src/semantic/validate.js +1 -1
  181. package/src/toolchains.js +1 -0
  182. package/src/zig-bindings.js +46 -0
@@ -0,0 +1,579 @@
1
+ // @ts-check
2
+
3
+ import {createHash} from "node:crypto"
4
+ import {unsupportedCapability} from "../diagnostic.js"
5
+ import {finalizeMapping, toSourceMapV3} from "../mapping.js"
6
+ import {parseZigCst} from "../frontends/zig-parser.js"
7
+ import {validateNativeGraph} from "./native-validation.js"
8
+ import {emitScalarType} from "./scalars.js"
9
+ import {validateBackendModule} from "./shared.js"
10
+ import {SourceWriter} from "./writer.js"
11
+ import {zigBuild, zigRuntime} from "./zig-runtime.js"
12
+ import {maximumZigSourceLength, validateZigValues} from "./zig-validation.js"
13
+ import {collectZigBindingUsage} from "../zig-bindings.js"
14
+
15
+ /** @typedef {import("../semantic/types.js").SemanticModule} SemanticModule */
16
+ /** @typedef {import("../semantic/types.js").SemanticNode} SemanticNode */
17
+ /** @typedef {import("../semantic/types.js").Expression} Expression */
18
+ /** @typedef {import("../semantic/types.js").Statement} Statement */
19
+ /** @typedef {import("../semantic/types.js").FunctionReturnTypeName} Scalar */
20
+ /** @typedef {{expression: Expression, path: string, type: Scalar, name?: string}} ZigPlannedValue */
21
+ /** @typedef {{result: ZigPlannedValue, operands: ZigPlannedValue[], rightSteps?: ZigPlannedStep[]}} ZigPlannedStep */
22
+ /** @typedef {{id: string, steps: ZigPlannedStep[], terminal?: ZigPlannedStep, value?: ZigPlannedValue}} ZigStatementPlan */
23
+
24
+ const operators = new Map([
25
+ ["IntegerAdd", "semantifold_integer_add"], ["IntegerSubtract", "semantifold_integer_subtract"],
26
+ ["IntegerMultiply", "semantifold_integer_multiply"], ["IntegerEqual", "=="], ["IntegerNotEqual", "!="],
27
+ ["IntegerLessThan", "<"], ["IntegerLessThanOrEqual", "<="], ["IntegerGreaterThan", ">"], ["IntegerGreaterThanOrEqual", ">="],
28
+ ["BooleanEqual", "=="], ["BooleanNotEqual", "!="], ["BooleanAnd", "and"], ["BooleanOr", "or"],
29
+ ["StringConcat", "semantifold_string_concat"], ["StringEqual", "semantifold_string_equal"],
30
+ ["StringNotEqual", "semantifold_string_not_equal"]
31
+ ])
32
+
33
+ /** Plans scalar operations by occurrence without rewriting caller-owned semantic values. */
34
+ class ZigExpressionPlanner {
35
+ /**
36
+ * Creates a planner for one validated scalar module.
37
+ * @param {SemanticModule} module - Validated module.
38
+ */
39
+ constructor(module) {
40
+ this.functions = new Map(module.functions.map(declaration => [declaration.name, zigType(declaration.returnType, declaration.location)]))
41
+ this.nextTemporary = 1
42
+ }
43
+
44
+ /**
45
+ * Resolves one already-validated expression type.
46
+ * @param {Expression} expression - Expression occurrence.
47
+ * @param {Map<string, Scalar>} bindings - Visible scalar bindings.
48
+ * @returns {Scalar} Exact result type.
49
+ */
50
+ type(expression, bindings) {
51
+ if (expression.kind == "IntegerLiteral") return "integer"
52
+ if (expression.kind == "BooleanLiteral") return "boolean"
53
+ if (expression.kind == "StringLiteral") return "string"
54
+ if (expression.kind == "UnaryExpression" || expression.kind == "BinaryExpression") return expression.type
55
+ if (expression.kind != "CallExpression" && expression.kind != "IdentifierExpression") {
56
+ return unsupportedCapability("zig", "collection expression reached scalar planning", expression.location)
57
+ }
58
+ const type = expression.kind == "CallExpression" ? this.functions.get(expression.callee) : bindings.get(expression.name)
59
+
60
+ if (!type) return unsupportedCapability("zig", "unresolved expression type", expression.location)
61
+ return type
62
+ }
63
+
64
+ /**
65
+ * Plans one value expression in semantic left-to-right order.
66
+ * @param {Expression} expression - Expression occurrence.
67
+ * @param {string} path - Canonical occurrence path.
68
+ * @param {Map<string, Scalar>} bindings - Visible scalar bindings.
69
+ * @param {ZigPlannedStep[]} steps - Ordered enclosing prelude.
70
+ * @returns {ZigPlannedValue} Pure final value.
71
+ */
72
+ plan(expression, path, bindings, steps) {
73
+ const result = {expression, path, type: this.type(expression, bindings)}
74
+
75
+ if (!["CallExpression", "UnaryExpression", "BinaryExpression"].includes(expression.kind)) return result
76
+ const operands = []
77
+ /** @type {ZigPlannedStep[] | undefined} */
78
+ let rightSteps
79
+
80
+ if (expression.kind == "CallExpression") {
81
+ for (const [index, argument] of expression.arguments.entries()) operands.push(this.plan(argument, `${path}/arguments/${index}`, bindings, steps))
82
+ } else if (expression.kind == "UnaryExpression") operands.push(this.plan(expression.operand, `${path}/operand`, bindings, steps))
83
+ else if (expression.kind == "BinaryExpression") {
84
+ operands.push(this.plan(expression.left, `${path}/left`, bindings, steps))
85
+ if (expression.operation == "BooleanAnd" || expression.operation == "BooleanOr") {
86
+ const planned = {...result, name: this.allocate(expression)}
87
+
88
+ rightSteps = []
89
+ operands.push(this.plan(expression.right, `${path}/right`, bindings, rightSteps))
90
+ steps.push({operands, result: planned, rightSteps})
91
+ return planned
92
+ }
93
+ operands.push(this.plan(expression.right, `${path}/right`, bindings, steps))
94
+ }
95
+ if (result.type == "void") throw new Error("Void Zig call reached value planning.")
96
+ const planned = {...result, name: this.allocate(expression)}
97
+
98
+ steps.push({operands, result: planned})
99
+ return planned
100
+ }
101
+
102
+ /**
103
+ * Plans the arguments of one terminal void call without inventing a void temporary.
104
+ * @param {Expression} expression - Terminal expression occurrence.
105
+ * @param {string} path - Canonical occurrence path.
106
+ * @param {Map<string, Scalar>} bindings - Visible scalar bindings.
107
+ * @param {ZigPlannedStep[]} steps - Ordered enclosing prelude.
108
+ * @returns {ZigPlannedStep} Terminal direct-call step.
109
+ */
110
+ terminal(expression, path, bindings, steps) {
111
+ if (expression.kind != "CallExpression" || this.type(expression, bindings) != "void") {
112
+ throw new Error("Non-void expression reached Zig terminal-call planning.")
113
+ }
114
+ const result = {expression, path, type: /** @type {const} */ ("void")}
115
+ const operands = expression.arguments.map((argument, index) => this.plan(argument, `${path}/arguments/${index}`, bindings, steps))
116
+
117
+ return {operands, result}
118
+ }
119
+
120
+ /**
121
+ * Allocates one bounded deterministic occurrence name.
122
+ * @param {Expression} expression - Related semantic occurrence.
123
+ * @returns {string} Reserved occurrence name.
124
+ */
125
+ allocate(expression) {
126
+ if (this.nextTemporary > 999999) return unsupportedCapability("zig", "ordered-expression occurrence limit", expression.location)
127
+ return `semantifold_ordered_${String(this.nextTemporary++).padStart(6, "0")}`
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Plans every Zig statement before writer construction or artifact exposure.
133
+ * @param {SemanticModule} module - Validated module.
134
+ * @returns {Map<string, ZigStatementPlan>} Plans by semantic occurrence path.
135
+ */
136
+ function planZigModule(module) {
137
+ const planner = new ZigExpressionPlanner(module)
138
+ /** @type {Map<string, ZigStatementPlan>} */
139
+ const plans = new Map()
140
+ /**
141
+ * Plans one lexical block with independent branch environments.
142
+ * @param {import("../semantic/types.js").Block} block - Block to plan.
143
+ * @param {string} path - Canonical block path.
144
+ * @param {Map<string, Scalar>} inherited - Visible scalar bindings.
145
+ */
146
+ const visit = (block, path, inherited) => {
147
+ const bindings = new Map(inherited)
148
+
149
+ block.statements.forEach((statement, index) => {
150
+ const statementPath = `${path}/statements/${index}`
151
+ const field = statement.kind == "IfStatement" ? "condition" : statement.kind == "LocalDeclaration" ? "initializer" : "expression"
152
+ const expression = statement.kind == "IfStatement" ? statement.condition : statement.kind == "LocalDeclaration" ? statement.initializer :
153
+ statement.kind == "AssignmentStatement" || statement.kind == "ExpressionStatement" || statement.kind == "PrintStatement" ? statement.expression :
154
+ statement.kind == "ReturnStatement" ? statement.expression : undefined
155
+ /** @type {ZigPlannedStep[]} */
156
+ const steps = []
157
+ /** @type {ZigStatementPlan} */
158
+ const plan = {id: String(plans.size + 1).padStart(6, "0"), steps}
159
+
160
+ if (statement.kind == "ExpressionStatement") plan.terminal = planner.terminal(statement.expression, `${statementPath}/${field}`, bindings, steps)
161
+ else if (expression) plan.value = planner.plan(expression, `${statementPath}/${field}`, bindings, steps)
162
+ plans.set(statementPath, plan)
163
+ if (statement.kind == "LocalDeclaration") bindings.set(statement.name, zigType(statement.type, statement.location))
164
+ if (statement.kind == "IfStatement") {
165
+ visit(statement.consequent, `${statementPath}/consequent`, bindings)
166
+ if (statement.alternate) visit(statement.alternate, `${statementPath}/alternate`, bindings)
167
+ }
168
+ })
169
+ }
170
+
171
+ module.functions.forEach((declaration, index) => visit(declaration.body, `/functions/${index}/body`,
172
+ new Map(declaration.parameters.map(parameter => [parameter.name, zigType(parameter.type, parameter.location)]))))
173
+ visit(module.entryPoint.body, "/entryPoint/body", new Map())
174
+ return plans
175
+ }
176
+
177
+ /**
178
+ * Binds an ordered region to its exact semantic consumer and expression.
179
+ * @param {Statement} statement - Semantic statement occurrence.
180
+ * @returns {string} Stable scaffold signature.
181
+ */
182
+ function zigStatementSignature(statement) {
183
+ const consumer = statement.kind == "LocalDeclaration" ? [statement.kind, statement.name,
184
+ zigType(statement.type, statement.location), statement.mutable] :
185
+ statement.kind == "AssignmentStatement" ? [statement.kind, statement.target.name] : [statement.kind]
186
+ const expression = statement.kind == "IfStatement" ? statement.condition : statement.kind == "LocalDeclaration" ? statement.initializer :
187
+ statement.kind == "AssignmentStatement" || statement.kind == "ExpressionStatement" || statement.kind == "PrintStatement" ? statement.expression :
188
+ statement.kind == "ReturnStatement" ? statement.expression : undefined
189
+
190
+ return createHash("sha256").update(JSON.stringify([consumer, expression ? zigExpressionSignature(expression) : null])).digest("hex")
191
+ }
192
+
193
+ /**
194
+ * Serializes only the closed semantic expression fields.
195
+ * @param {Expression} expression - Closed scalar expression.
196
+ * @returns {unknown[]} Stable signature data.
197
+ */
198
+ function zigExpressionSignature(expression) {
199
+ if (expression.kind == "IdentifierExpression") return [expression.kind, expression.name]
200
+ if (expression.kind == "IntegerLiteral" || expression.kind == "BooleanLiteral" || expression.kind == "StringLiteral") {
201
+ return [expression.kind, expression.value]
202
+ }
203
+ if (expression.kind == "CallExpression") return [expression.kind, expression.callee, ...expression.arguments.map(zigExpressionSignature)]
204
+ if (expression.kind == "UnaryExpression") return [expression.kind, expression.operation, expression.type, zigExpressionSignature(expression.operand)]
205
+ if (expression.kind == "BinaryExpression") {
206
+ return [expression.kind, expression.operation, expression.type, zigExpressionSignature(expression.left), zigExpressionSignature(expression.right)]
207
+ }
208
+ return [expression.kind]
209
+ }
210
+
211
+ /**
212
+ * Produces a deterministic dependency-free Zig 0.15.2 native project after complete preflight.
213
+ * @param {{filename?: string, mapDirective?: unknown, module: SemanticModule, sourceMapFilename?: unknown, sources?: {filename: string, content: string, language?: import("../semantic/types.js").SemanticLanguage}[]}} input - Artifact request.
214
+ * @returns {{artifacts: import("../semantic/types.js").GeneratedSetArtifact[], target: string}} Candidate project.
215
+ */
216
+ export function generateZigProject({filename, mapDirective, module, sourceMapFilename, sources}) {
217
+ validateNativeGraph(module, "zig")
218
+ validateBackendModule(module, "zig")
219
+ validateZigValues(module)
220
+ if (filename !== undefined && filename != "src/main.zig") unsupportedCapability("zig", "artifact filename other than src/main.zig", module.location)
221
+ if (mapDirective !== undefined || sourceMapFilename !== undefined) unsupportedCapability("zig", "source-map filename or directive option", module.location)
222
+ new ZigEmitter(module).program(module)
223
+ const writer = new SourceWriter({filename: "src/main.zig", language: "zig", module, sources})
224
+
225
+ new ZigEmitter(module, writer).program(module)
226
+ const mapping = finalizeMapping(writer.finish())
227
+ validateGeneratedZig(mapping.generated.content, module.location)
228
+ const root = mapping.nodes.find(node => node.path == "")
229
+
230
+ if (!root) throw new Error("Validated Zig module omitted root provenance.")
231
+ const origin = root.origin
232
+ const relatedOrigins = origin.kind == "source" ? [{location: origin.location, nodeId: root.id, role: "module", sourceId: origin.sourceId}] :
233
+ (origin.kind == "derived" ? origin.origins : origin.relatedOrigins).map(item => ({...item, nodeId: item.nodeId ?? root.id, role: item.role ?? "module"}))
234
+
235
+ return {target: "zig", artifacts: [{
236
+ path: "build.zig", role: "manifest", ownership: "generated", contentKind: "text", mediaType: "text/x-zig", content: zigBuild,
237
+ provenance: {kind: "synthetic", reason: "Fixed dependency-free Zig 0.15.2 native-host project with caller-selected Debug, ReleaseSafe, or ReleaseFast optimization.", relatedOrigins}
238
+ }, {
239
+ path: "src/main.zig", role: "entry", ownership: "generated", contentKind: "text", mediaType: "text/x-zig", content: mapping.generated.content,
240
+ provenance: {kind: "text", mapping, sourceMap: toSourceMapV3(mapping)}
241
+ }]}
242
+ }
243
+
244
+ /** Emits exact Zig support and Tasks 001-005 semantic occurrences. */
245
+ class ZigEmitter {
246
+ /**
247
+ * Creates a validation-only or writing emitter for one module.
248
+ * @param {SemanticModule} module - Validated semantic module.
249
+ * @param {SourceWriter} [writer] - Optional provenance-aware output writer.
250
+ */
251
+ constructor(module, writer) {
252
+ this.writer = writer
253
+ this.plans = planZigModule(module)
254
+ this.length = 0
255
+ this.location = module.location
256
+ this.usage = {reads: new Set(), writes: new Set()}
257
+ }
258
+
259
+ /**
260
+ * Accounts for generated size before any text becomes observable.
261
+ * @param {string} text - Text about to be emitted.
262
+ * @param {SemanticNode} node - Owning semantic occurrence.
263
+ */
264
+ checkSize(text, node) {
265
+ this.length += text.length
266
+ if (this.length > maximumZigSourceLength) unsupportedCapability("zig", "generated source exceeds the 1000000 UTF-16 input limit", "location" in node ? node.location : this.location)
267
+ }
268
+
269
+ /**
270
+ * Emits synthetic Zig syntax when a writer is present.
271
+ * @param {string} text - Text to emit.
272
+ * @param {SemanticNode} node - Related semantic node.
273
+ * @param {string} path - Canonical semantic path.
274
+ * @param {string} [reason] - Synthetic provenance reason.
275
+ */
276
+ synthetic(text, node, path, reason = "Zig declaration and expression syntax") {
277
+ this.checkSize(text, node)
278
+ this.writer?.synthetic(text, reason, [node], [path])
279
+ }
280
+
281
+ /**
282
+ * Emits an exact or anchored semantic occurrence when a writer is present.
283
+ * @param {string} text - Text to emit.
284
+ * @param {SemanticNode} node - Owning semantic node.
285
+ * @param {string} path - Canonical semantic path.
286
+ * @param {string} [role] - Exact parser-token role when available.
287
+ */
288
+ mapped(text, node, path, role) {
289
+ this.checkSize(text, node)
290
+ this.writer?.mapped(text, {mappingKind: role ? "exact" : "anchor", node, path, ...(role ? {role} : {})})
291
+ }
292
+
293
+ /**
294
+ * Validates or emits the complete deterministic entry source.
295
+ * @param {SemanticModule} module - Semantic module to process.
296
+ */
297
+ program(module) {
298
+ this.synthetic(zigRuntime, module, "", "Exact Zig arena, UTF-8, output, comparison, and checked-arithmetic support")
299
+ this.synthetic("// semantifold:program:zig:v1\n", module, "", "Exact generated Zig ordered-expression profile marker")
300
+ module.functions.forEach((declaration, index) => {
301
+ const path = `/functions/${index}`
302
+
303
+ this.synthetic("\n", declaration, path)
304
+ this.mapped("fn", declaration, path)
305
+ this.synthetic(" ", declaration, path)
306
+ this.mapped(declaration.name, declaration, path, "name")
307
+ this.synthetic("(", declaration, path)
308
+ declaration.parameters.forEach((parameter, parameterIndex) => {
309
+ const parameterPath = `${path}/parameters/${parameterIndex}`
310
+
311
+ if (parameterIndex) this.synthetic(", ", parameter, parameterPath)
312
+ this.mapped(parameter.name, parameter, parameterPath, "name")
313
+ this.synthetic(": ", parameter, parameterPath)
314
+ this.mapped(emitScalarType("zig", parameter.type), parameter.type, `${parameterPath}/type`, "type")
315
+ })
316
+ this.synthetic(") ", declaration, path)
317
+ this.mapped(emitScalarType("zig", declaration.returnType), declaration.returnType, `${path}/returnType`, "type")
318
+ this.synthetic(" {\n", declaration, path)
319
+ this.usage = collectZigBindingUsage(declaration.body)
320
+ declaration.parameters.forEach((parameter, parameterIndex) => {
321
+ const parameterPath = `${path}/parameters/${parameterIndex}`
322
+
323
+ if (!this.usage.reads.has(parameter.name)) {
324
+ this.synthetic(" _ = ", parameter, parameterPath, "Zig explicit unused-parameter scaffold")
325
+ this.mapped(parameter.name, parameter, parameterPath, "name")
326
+ this.synthetic(";\n", parameter, parameterPath, "Zig explicit unused-parameter scaffold")
327
+ }
328
+ })
329
+ this.block(declaration.body, `${path}/body`, " ")
330
+ this.synthetic("}\n", declaration, path)
331
+ })
332
+ this.usage = collectZigBindingUsage(module.entryPoint.body)
333
+ this.synthetic("\npub fn main() void {\n defer semantifold_arena.deinit();\n", module.entryPoint, "/entryPoint", "Zig generated entry and arena lifetime shell")
334
+ this.block(module.entryPoint.body, "/entryPoint/body", " ")
335
+ this.synthetic("}\n", module.entryPoint, "/entryPoint", "Zig generated entry shell")
336
+ }
337
+
338
+ /**
339
+ * Emits one lexical block and compiler-required binding scaffolds.
340
+ * @param {import("../semantic/types.js").Block} block - Semantic block.
341
+ * @param {string} path - Canonical block path.
342
+ * @param {string} indent - Current output indentation.
343
+ */
344
+ block(block, path, indent) {
345
+ block.statements.forEach((statement, index) => {
346
+ this.statement(statement, `${path}/statements/${index}`, indent)
347
+ })
348
+ }
349
+
350
+ /**
351
+ * Emits one complete paired ordered region and its pure final consumer.
352
+ * @param {import("../semantic/types.js").Statement} statement - Statement to emit.
353
+ * @param {string} path - Canonical statement path.
354
+ * @param {string} indent - Current output indentation.
355
+ */
356
+ statement(statement, path, indent) {
357
+ const plan = this.plans.get(path)
358
+
359
+ if (!plan) throw new Error("Missing validated Zig statement plan.")
360
+ const marker = "semantifold:ordered-expression:zig:v1"
361
+ const signature = zigStatementSignature(statement)
362
+
363
+ this.synthetic(`${indent}// ${marker} begin ${plan.id} ${signature}\n`, statement, path, "Zig ordered-expression region marker")
364
+ this.steps(plan.steps, indent)
365
+ this.synthetic(indent, statement, path, "indentation")
366
+ if (statement.kind == "LocalDeclaration") {
367
+ this.mapped(statement.mutable ? "var" : "const", statement, path)
368
+ this.synthetic(" ", statement, path)
369
+ this.mapped(statement.name, statement, path, "name")
370
+ this.synthetic(": ", statement, path)
371
+ this.mapped(emitScalarType("zig", statement.type), statement.type, `${path}/type`, "type")
372
+ this.synthetic(" ", statement, path)
373
+ this.mapped("=", statement, path, "operator")
374
+ this.synthetic(" ", statement, path)
375
+ this.value(requiredPlanValue(plan, statement))
376
+ } else if (statement.kind == "AssignmentStatement") {
377
+ this.mapped(statement.target.name, statement.target, `${path}/target`, "name")
378
+ this.synthetic(" ", statement, path)
379
+ this.mapped("=", statement, path, "operator")
380
+ this.synthetic(" ", statement, path)
381
+ this.value(requiredPlanValue(plan, statement))
382
+ } else if (statement.kind == "ReturnStatement") {
383
+ this.mapped("return", statement, path)
384
+ if (statement.expression) {
385
+ this.synthetic(" ", statement, path)
386
+ this.value(requiredPlanValue(plan, statement))
387
+ }
388
+ } else if (statement.kind == "PrintStatement") {
389
+ const value = requiredPlanValue(plan, statement)
390
+
391
+ this.mapped(`semantifold_print_${value.type}`, statement, path)
392
+ this.synthetic("(", statement, path)
393
+ this.value(value)
394
+ this.synthetic(")", statement, path)
395
+ } else if (statement.kind == "ExpressionStatement") {
396
+ if (!plan.terminal) throw new Error("Missing validated Zig terminal call.")
397
+ this.operation(plan.terminal)
398
+ } else if (statement.kind == "IfStatement") {
399
+ this.mapped("if", statement, path)
400
+ this.synthetic(" (", statement, path)
401
+ this.value(requiredPlanValue(plan, statement))
402
+ this.synthetic(") {\n", statement, path)
403
+ this.block(statement.consequent, `${path}/consequent`, indent + " ")
404
+ this.synthetic(indent + "}", statement, path)
405
+ if (statement.alternate) {
406
+ this.mapped(" else", statement, path)
407
+ this.synthetic(" {\n", statement, path)
408
+ this.block(statement.alternate, `${path}/alternate`, indent + " ")
409
+ this.synthetic(indent + "}", statement, path)
410
+ }
411
+ this.synthetic("\n", statement, path)
412
+ } else throw new TypeError("Unsupported Zig statement reached emission after preflight.")
413
+ if (statement.kind != "IfStatement") this.synthetic(";\n", statement, path)
414
+ if (statement.kind == "LocalDeclaration") {
415
+ const unmutated = statement.mutable && !this.usage.writes.has(statement.name)
416
+ const unread = !statement.mutable && !this.usage.reads.has(statement.name)
417
+
418
+ if (unmutated || unread) {
419
+ this.synthetic(indent + "_ = ", statement, path, "Zig explicit local binding scaffold")
420
+ if (unmutated) this.synthetic("&", statement, path, "Zig explicit unmutated-var scaffold")
421
+ this.mapped(statement.name, statement, path, "name")
422
+ this.synthetic(";\n", statement, path, "Zig explicit local binding scaffold")
423
+ }
424
+ }
425
+ this.synthetic(`${indent}// ${marker} end ${plan.id} ${signature}\n`, statement, path, "Zig ordered-expression region marker")
426
+ }
427
+
428
+ /**
429
+ * Emits eager steps in semantic order and keeps a Boolean RHS conditional.
430
+ * @param {ZigPlannedStep[]} steps - Ordered private steps.
431
+ * @param {string} indent - Current indentation.
432
+ */
433
+ steps(steps, indent) {
434
+ for (const step of steps) {
435
+ const {expression, path, name, type} = step.result
436
+
437
+ if (!name || type == "void") throw new Error("Invalid Zig ordered value step.")
438
+ this.synthetic(`${indent}${step.rightSteps ? "var" : "const"} ${name}: ${emitScalarType("zig", {kind: "TypeReference", name: type})} = `,
439
+ expression, path, "Zig typed ordered-expression temporary")
440
+ if (step.rightSteps) {
441
+ this.value(step.operands[0])
442
+ this.synthetic(`;\n${indent}if (`, expression, path, "Zig conditional ordered-expression RHS")
443
+ if (expression.kind != "BinaryExpression") throw new Error("Invalid Zig conditional ordered plan.")
444
+ this.synthetic(`${expression.operation == "BooleanOr" ? "!" : ""}${name}) {\n`, expression, path,
445
+ "Zig conditional ordered-expression RHS")
446
+ this.steps(step.rightSteps, indent + " ")
447
+ this.synthetic(`${indent} ${name} = ${name} `, expression, path, "Zig conditional ordered-expression result")
448
+ this.mapped(expression.operation == "BooleanOr" ? "or" : "and", expression, path, "operator")
449
+ this.synthetic(" ", expression, path)
450
+ this.value(step.operands[1])
451
+ this.synthetic(`;\n${indent}}\n`, expression, path, "Zig conditional ordered-expression RHS")
452
+ } else {
453
+ this.operation(step)
454
+ this.synthetic(";\n", expression, path)
455
+ }
456
+ }
457
+ }
458
+
459
+ /**
460
+ * Emits one operation whose operands are already pure.
461
+ * @param {ZigPlannedStep} step - Planned operation.
462
+ */
463
+ operation({result: {expression, path}, operands}) {
464
+ if (expression.kind == "CallExpression") {
465
+ this.mapped(expression.callee, expression, path, "callee")
466
+ this.synthetic("(", expression, path)
467
+ operands.forEach((operand, index) => {
468
+ if (index) this.synthetic(", ", expression, path)
469
+ this.value(operand)
470
+ })
471
+ this.synthetic(")", expression, path)
472
+ } else if (expression.kind == "UnaryExpression") {
473
+ this.mapped(expression.operation == "IntegerNegate" ? "semantifold_integer_negate" : "!", expression, path, "operator")
474
+ this.synthetic("(", expression, path)
475
+ this.value(operands[0])
476
+ this.synthetic(")", expression, path)
477
+ } else if (expression.kind == "BinaryExpression") {
478
+ const token = operators.get(expression.operation)
479
+
480
+ if (!token) throw new Error("Unsupported operation passed Zig validation.")
481
+ const helper = token.startsWith("semantifold_")
482
+
483
+ if (helper) this.mapped(token, expression, path, "operator")
484
+ this.synthetic("(", expression, path)
485
+ this.value(operands[0])
486
+ if (helper) this.synthetic(", ", expression, path)
487
+ else {
488
+ this.synthetic(" ", expression, path)
489
+ this.mapped(token, expression, path, "operator")
490
+ this.synthetic(" ", expression, path)
491
+ }
492
+ this.value(operands[1])
493
+ this.synthetic(")", expression, path)
494
+ } else throw new Error("Pure value reached Zig operation emission.")
495
+ }
496
+
497
+ /**
498
+ * Emits one pure literal, binding, or ordered temporary use.
499
+ * @param {ZigPlannedValue} value - Planned pure value.
500
+ * @returns {void} Text is emitted through the configured writer.
501
+ */
502
+ value({expression, path, name}) {
503
+ if (name) return this.synthetic(name, expression, path, "Zig ordered-expression temporary use")
504
+ if (expression.kind == "IdentifierExpression") return this.mapped(expression.name, expression, path, "name")
505
+ if (expression.kind == "BooleanLiteral") return this.mapped(String(expression.value), expression, path, "literal")
506
+ if (expression.kind == "IntegerLiteral") return this.mapped(String(expression.value), expression, path, "literal")
507
+ if (expression.kind == "StringLiteral") return this.mapped(zigString(expression.value), expression, path, "literal")
508
+ throw new Error("Unsequenced expression passed Zig emission.")
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Requires the final pure value owned by a non-void statement plan.
514
+ * @param {ZigStatementPlan} plan - Statement plan.
515
+ * @param {Statement} statement - Owning semantic statement.
516
+ * @returns {ZigPlannedValue} Required planned value.
517
+ */
518
+ function requiredPlanValue(plan, statement) {
519
+ if (!plan.value) throw new Error(`Missing validated Zig value for ${statement.kind}.`)
520
+ return plan.value
521
+ }
522
+
523
+ /**
524
+ * Narrows an already validated semantic type to the Zig scalar cohort.
525
+ * @param {import("../semantic/types.js").SemanticFunctionReturnType} type - Semantic type.
526
+ * @param {import("../semantic/types.js").SourceLocation} location - Diagnostic location.
527
+ * @returns {Scalar} Scalar type name.
528
+ */
529
+ function zigType(type, location) {
530
+ if (type.kind != "TypeReference") return unsupportedCapability("zig", "collection type reached scalar emission", location)
531
+ return type.name
532
+ }
533
+
534
+ /**
535
+ * Encodes a Unicode scalar string as a canonical Zig literal.
536
+ * @param {string} value - Semantic string value.
537
+ * @returns {string} Zig literal spelling.
538
+ */
539
+ function zigString(value) {
540
+ let literal = '"'
541
+
542
+ for (const character of value) {
543
+ const scalar = /** @type {number} */ (character.codePointAt(0))
544
+
545
+ if (character == '"') literal += '\\"'
546
+ else if (character == "\\") literal += "\\\\"
547
+ else if (scalar < 32 || scalar == 127) literal += `\\x${scalar.toString(16).padStart(2, "0")}`
548
+ else if (scalar == 0x2028 || scalar == 0x2029) literal += `\\u{${scalar.toString(16)}}`
549
+ else literal += character
550
+ }
551
+ return literal + '"'
552
+ }
553
+
554
+ /**
555
+ * Reparses the complete generated source and rejects recovery or excessive depth.
556
+ * @param {string} source - Generated Zig source.
557
+ * @param {import("../semantic/types.js").SourceLocation} location - Module diagnostic location.
558
+ * @returns {void} Returns only after the complete CST is accepted.
559
+ */
560
+ function validateGeneratedZig(source, location) {
561
+ let snapshot
562
+
563
+ try {
564
+ snapshot = parseZigCst(source)
565
+ } catch (error) {
566
+ return unsupportedCapability("zig", `generated source could not be reparsed: ${error instanceof Error ? error.message : error}`, location)
567
+ }
568
+ /**
569
+ * Validates one generated CST subtree.
570
+ * @param {import("../frontends/zig-parser.js").CstNode} node - Current parser node.
571
+ * @param {number} depth - Current nesting depth.
572
+ */
573
+ const visit = (node, depth) => {
574
+ if (depth > 512 || node.error || node.missing || node.hasError) unsupportedCapability("zig", "generated source contains parser recovery or exceeds the CST depth limit", location)
575
+ for (const {node: child} of node.children) visit(child, depth + 1)
576
+ }
577
+
578
+ visit(snapshot.root, 0)
579
+ }
@@ -15,6 +15,7 @@ function sourceTypeMap(entries) {
15
15
 
16
16
  /** @type {Readonly<Record<import("../semantic/types.js").SemanticLanguage, Map<string, import("../semantic/types.js").SemanticTypeName>>>} */
17
17
  const sourceScalarTypes = Object.freeze({
18
+ zig: sourceTypeMap([["i64", "integer"], ["bool", "boolean"], ["[]const u8", "string"]]),
18
19
  dart: sourceTypeMap([["int", "integer"], ["bool", "boolean"], ["String", "string"]]),
19
20
  swift: sourceTypeMap([["Int64", "integer"], ["Bool", "boolean"], ["String", "string"]]),
20
21
  rust: sourceTypeMap([["i64", "integer"], ["bool", "boolean"], ["String", "string"]]),
@@ -0,0 +1,20 @@
1
+ // @ts-check
2
+
3
+ import {createRequire} from "node:module"
4
+
5
+ /** @typedef {Readonly<{row: number, column: number}>} CstPosition */
6
+ /** @typedef {Readonly<{field: string | null, node: CstNode}>} CstChild */
7
+ /** @typedef {Readonly<{type: string, named: boolean, extra: boolean, error: boolean, missing: boolean, hasError: boolean, startIndex: number, endIndex: number, startPosition: CstPosition, endPosition: CstPosition, children: readonly CstChild[]}>} CstNode */
8
+ /** @typedef {Readonly<{root: CstNode}>} CstSnapshot */
9
+
10
+ const require = createRequire(import.meta.url)
11
+ const boundary = /** @type {{parseCst: (source: string) => CstSnapshot}} */ (require("semantifold-tree-sitter-zig-internal"))
12
+
13
+ /**
14
+ * Receives only frozen parser-neutral data from the qualified isolated Zig grammar.
15
+ * @param {string} source - Exact caller-owned Zig source.
16
+ * @returns {CstSnapshot} Complete Zig CST snapshot.
17
+ */
18
+ export function parseZigCst(source) {
19
+ return boundary.parseCst(source)
20
+ }