@native-sdk/cli 0.0.0 → 0.4.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 (367) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +50 -1
  3. package/app.zon +30 -0
  4. package/bin/native.js +156 -0
  5. package/build/app.zig +716 -0
  6. package/build.zig +2593 -0
  7. package/build.zig.zon +24 -0
  8. package/native-sdk.d.ts +615 -0
  9. package/package.json +44 -8
  10. package/skill-data/automation/SKILL.md +248 -0
  11. package/skill-data/core/SKILL.md +249 -0
  12. package/skill-data/core/references/app-model-runtime.md +141 -0
  13. package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
  14. package/skill-data/core/references/frontend-assets.md +124 -0
  15. package/skill-data/core/references/project-anatomy.md +108 -0
  16. package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
  17. package/skill-data/native-ui/SKILL.md +1080 -0
  18. package/skills/native-sdk/SKILL.md +33 -0
  19. package/src/app_runner/root.zig +740 -0
  20. package/src/assets/root.zig +20 -0
  21. package/src/automation/protocol.zig +285 -0
  22. package/src/automation/root.zig +13 -0
  23. package/src/automation/server.zig +506 -0
  24. package/src/automation/snapshot.zig +1202 -0
  25. package/src/automation/watcher.zig +165 -0
  26. package/src/bridge/root.zig +507 -0
  27. package/src/debug/root.zig +246 -0
  28. package/src/embed/app_exports.zig +11 -0
  29. package/src/embed/c_api.zig +793 -0
  30. package/src/embed/c_exports.zig +10 -0
  31. package/src/embed/chrome.zig +168 -0
  32. package/src/embed/conversions.zig +359 -0
  33. package/src/embed/host.zig +960 -0
  34. package/src/embed/root.zig +81 -0
  35. package/src/embed/tests.zig +2552 -0
  36. package/src/embed/types.zig +382 -0
  37. package/src/embed/ui_host.zig +289 -0
  38. package/src/extensions/root.zig +197 -0
  39. package/src/frontend/root.zig +48 -0
  40. package/src/js/root.zig +65 -0
  41. package/src/platform/android/NativeSdkActivity.java +1370 -0
  42. package/src/platform/android/android_host.c +696 -0
  43. package/src/platform/android/files.zig +9 -0
  44. package/src/platform/android/native_sdk_app.h +237 -0
  45. package/src/platform/ios/files.zig +8 -0
  46. package/src/platform/ios/native_sdk_app.h +289 -0
  47. package/src/platform/ios/uikit_host.m +2739 -0
  48. package/src/platform/linux/cef_host.cpp +599 -0
  49. package/src/platform/linux/gtk_host.c +5362 -0
  50. package/src/platform/linux/gtk_host.h +265 -0
  51. package/src/platform/linux/root.zig +1519 -0
  52. package/src/platform/macos/appkit_host.h +604 -0
  53. package/src/platform/macos/appkit_host.m +10392 -0
  54. package/src/platform/macos/automation_host.h +14 -0
  55. package/src/platform/macos/automation_host.m +12 -0
  56. package/src/platform/macos/cef_host.mm +3028 -0
  57. package/src/platform/macos/root.zig +2260 -0
  58. package/src/platform/null_platform.zig +2232 -0
  59. package/src/platform/null_platform_tests.zig +670 -0
  60. package/src/platform/policy_values.zig +14 -0
  61. package/src/platform/root.zig +181 -0
  62. package/src/platform/types.zig +2681 -0
  63. package/src/platform/windows/cef_host.cpp +3 -0
  64. package/src/platform/windows/root.zig +1521 -0
  65. package/src/platform/windows/webview2_host.cpp +6230 -0
  66. package/src/primitives/app_dirs/root.zig +440 -0
  67. package/src/primitives/app_manifest/root.zig +109 -0
  68. package/src/primitives/app_manifest/tests.zig +758 -0
  69. package/src/primitives/app_manifest/types.zig +587 -0
  70. package/src/primitives/app_manifest/validation.zig +828 -0
  71. package/src/primitives/assets/root.zig +520 -0
  72. package/src/primitives/canvas/a11y_audit.zig +390 -0
  73. package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
  74. package/src/primitives/canvas/app_icon.zig +1590 -0
  75. package/src/primitives/canvas/chart.zig +392 -0
  76. package/src/primitives/canvas/chart_tests.zig +751 -0
  77. package/src/primitives/canvas/commands.zig +446 -0
  78. package/src/primitives/canvas/drawing.zig +309 -0
  79. package/src/primitives/canvas/equality.zig +316 -0
  80. package/src/primitives/canvas/events.zig +696 -0
  81. package/src/primitives/canvas/font_coverage.zig +118 -0
  82. package/src/primitives/canvas/font_ttf.zig +510 -0
  83. package/src/primitives/canvas/font_ttf_tests.zig +280 -0
  84. package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
  85. package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
  86. package/src/primitives/canvas/frame.zig +679 -0
  87. package/src/primitives/canvas/frame_metrics.zig +462 -0
  88. package/src/primitives/canvas/gpu.zig +639 -0
  89. package/src/primitives/canvas/hash.zig +112 -0
  90. package/src/primitives/canvas/icons/alert.svg +1 -0
  91. package/src/primitives/canvas/icons/archive.svg +1 -0
  92. package/src/primitives/canvas/icons/arrow-down.svg +1 -0
  93. package/src/primitives/canvas/icons/arrow-right.svg +1 -0
  94. package/src/primitives/canvas/icons/arrow-up.svg +1 -0
  95. package/src/primitives/canvas/icons/check-circle.svg +1 -0
  96. package/src/primitives/canvas/icons/check.svg +1 -0
  97. package/src/primitives/canvas/icons/chevron-down.svg +1 -0
  98. package/src/primitives/canvas/icons/chevron-left.svg +1 -0
  99. package/src/primitives/canvas/icons/chevron-right.svg +1 -0
  100. package/src/primitives/canvas/icons/chevron-up.svg +1 -0
  101. package/src/primitives/canvas/icons/circle-dot.svg +1 -0
  102. package/src/primitives/canvas/icons/clock.svg +1 -0
  103. package/src/primitives/canvas/icons/copy.svg +1 -0
  104. package/src/primitives/canvas/icons/download.svg +1 -0
  105. package/src/primitives/canvas/icons/edit.svg +1 -0
  106. package/src/primitives/canvas/icons/ellipsis.svg +1 -0
  107. package/src/primitives/canvas/icons/external-link.svg +1 -0
  108. package/src/primitives/canvas/icons/eye.svg +1 -0
  109. package/src/primitives/canvas/icons/file-text.svg +1 -0
  110. package/src/primitives/canvas/icons/folder-open.svg +1 -0
  111. package/src/primitives/canvas/icons/folder.svg +1 -0
  112. package/src/primitives/canvas/icons/git-branch.svg +1 -0
  113. package/src/primitives/canvas/icons/git-merge.svg +1 -0
  114. package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
  115. package/src/primitives/canvas/icons/info.svg +1 -0
  116. package/src/primitives/canvas/icons/menu.svg +1 -0
  117. package/src/primitives/canvas/icons/missing.svg +1 -0
  118. package/src/primitives/canvas/icons/moon.svg +1 -0
  119. package/src/primitives/canvas/icons/music.svg +1 -0
  120. package/src/primitives/canvas/icons/panel-left.svg +1 -0
  121. package/src/primitives/canvas/icons/panel-right.svg +1 -0
  122. package/src/primitives/canvas/icons/pause.svg +1 -0
  123. package/src/primitives/canvas/icons/play.svg +1 -0
  124. package/src/primitives/canvas/icons/plus.svg +1 -0
  125. package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
  126. package/src/primitives/canvas/icons/repeat.svg +1 -0
  127. package/src/primitives/canvas/icons/save.svg +1 -0
  128. package/src/primitives/canvas/icons/search.svg +1 -0
  129. package/src/primitives/canvas/icons/send.svg +1 -0
  130. package/src/primitives/canvas/icons/settings.svg +1 -0
  131. package/src/primitives/canvas/icons/shuffle.svg +1 -0
  132. package/src/primitives/canvas/icons/skip-back.svg +1 -0
  133. package/src/primitives/canvas/icons/skip-forward.svg +1 -0
  134. package/src/primitives/canvas/icons/sun.svg +1 -0
  135. package/src/primitives/canvas/icons/terminal.svg +1 -0
  136. package/src/primitives/canvas/icons/trash.svg +1 -0
  137. package/src/primitives/canvas/icons/volume.svg +1 -0
  138. package/src/primitives/canvas/icons/wrench.svg +1 -0
  139. package/src/primitives/canvas/icons/x-circle.svg +1 -0
  140. package/src/primitives/canvas/icons/x.svg +1 -0
  141. package/src/primitives/canvas/icons.zig +249 -0
  142. package/src/primitives/canvas/layout_audit.zig +744 -0
  143. package/src/primitives/canvas/layout_audit_tests.zig +426 -0
  144. package/src/primitives/canvas/markdown.zig +1031 -0
  145. package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
  146. package/src/primitives/canvas/markdown_tests.zig +538 -0
  147. package/src/primitives/canvas/plan_key_index.zig +120 -0
  148. package/src/primitives/canvas/png.zig +355 -0
  149. package/src/primitives/canvas/reference.zig +1457 -0
  150. package/src/primitives/canvas/reference_blur.zig +104 -0
  151. package/src/primitives/canvas/reference_memo.zig +322 -0
  152. package/src/primitives/canvas/reference_paths.zig +184 -0
  153. package/src/primitives/canvas/reference_tests.zig +1650 -0
  154. package/src/primitives/canvas/render.zig +747 -0
  155. package/src/primitives/canvas/render_effects.zig +255 -0
  156. package/src/primitives/canvas/render_fingerprints.zig +256 -0
  157. package/src/primitives/canvas/render_generic_resources.zig +376 -0
  158. package/src/primitives/canvas/render_images.zig +247 -0
  159. package/src/primitives/canvas/render_layers.zig +260 -0
  160. package/src/primitives/canvas/render_paths.zig +347 -0
  161. package/src/primitives/canvas/render_resources.zig +51 -0
  162. package/src/primitives/canvas/render_tests.zig +3186 -0
  163. package/src/primitives/canvas/root.zig +744 -0
  164. package/src/primitives/canvas/serialization.zig +1528 -0
  165. package/src/primitives/canvas/svg_icon.zig +636 -0
  166. package/src/primitives/canvas/svg_icon_tests.zig +312 -0
  167. package/src/primitives/canvas/test_support.zig +422 -0
  168. package/src/primitives/canvas/testdata/markdown_document.md +83 -0
  169. package/src/primitives/canvas/tests.zig +30 -0
  170. package/src/primitives/canvas/text.zig +82 -0
  171. package/src/primitives/canvas/text_atlas.zig +408 -0
  172. package/src/primitives/canvas/text_batch_tests.zig +431 -0
  173. package/src/primitives/canvas/text_interaction.zig +615 -0
  174. package/src/primitives/canvas/text_layout.zig +1069 -0
  175. package/src/primitives/canvas/text_layout_cache.zig +281 -0
  176. package/src/primitives/canvas/text_layout_hash.zig +113 -0
  177. package/src/primitives/canvas/text_layout_types.zig +128 -0
  178. package/src/primitives/canvas/text_measure_cache.zig +279 -0
  179. package/src/primitives/canvas/text_metrics.zig +309 -0
  180. package/src/primitives/canvas/text_metrics_tests.zig +262 -0
  181. package/src/primitives/canvas/text_span_tests.zig +608 -0
  182. package/src/primitives/canvas/text_spans.zig +1010 -0
  183. package/src/primitives/canvas/text_tests.zig +1949 -0
  184. package/src/primitives/canvas/themes/geist.zig +470 -0
  185. package/src/primitives/canvas/tokens.zig +1522 -0
  186. package/src/primitives/canvas/ui.zig +2686 -0
  187. package/src/primitives/canvas/ui_markup.zig +3791 -0
  188. package/src/primitives/canvas/ui_markup_binary.zig +522 -0
  189. package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
  190. package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
  191. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
  192. package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
  193. package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
  194. package/src/primitives/canvas/ui_markup_edit.zig +416 -0
  195. package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
  196. package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
  197. package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
  198. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
  199. package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
  200. package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
  201. package/src/primitives/canvas/ui_markup_view.zig +2352 -0
  202. package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
  203. package/src/primitives/canvas/ui_provenance.zig +96 -0
  204. package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
  205. package/src/primitives/canvas/ui_schema.zig +825 -0
  206. package/src/primitives/canvas/ui_schema_tests.zig +128 -0
  207. package/src/primitives/canvas/ui_tests.zig +1432 -0
  208. package/src/primitives/canvas/vector.zig +919 -0
  209. package/src/primitives/canvas/vector_tests.zig +547 -0
  210. package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
  211. package/src/primitives/canvas/virtual_extents.zig +540 -0
  212. package/src/primitives/canvas/widget_access.zig +208 -0
  213. package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
  214. package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
  215. package/src/primitives/canvas/widget_invalidation.zig +748 -0
  216. package/src/primitives/canvas/widget_layout.zig +2055 -0
  217. package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
  218. package/src/primitives/canvas/widget_metrics.zig +228 -0
  219. package/src/primitives/canvas/widget_render.zig +2534 -0
  220. package/src/primitives/canvas/widget_render_controls.zig +1563 -0
  221. package/src/primitives/canvas/widget_render_scroll.zig +136 -0
  222. package/src/primitives/canvas/widget_render_style.zig +626 -0
  223. package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
  224. package/src/primitives/canvas/widget_routing.zig +475 -0
  225. package/src/primitives/canvas/widget_runtime.zig +307 -0
  226. package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
  227. package/src/primitives/canvas/widget_semantics.zig +480 -0
  228. package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
  229. package/src/primitives/canvas/widget_tests.zig +8 -0
  230. package/src/primitives/canvas/widget_text_input.zig +351 -0
  231. package/src/primitives/canvas/widget_text_select.zig +147 -0
  232. package/src/primitives/canvas/widget_tree.zig +232 -0
  233. package/src/primitives/canvas/widgets.zig +1319 -0
  234. package/src/primitives/diagnostics/root.zig +445 -0
  235. package/src/primitives/geometry/root.zig +889 -0
  236. package/src/primitives/json/root.zig +272 -0
  237. package/src/primitives/platform_info/root.zig +450 -0
  238. package/src/primitives/trace/root.zig +569 -0
  239. package/src/root.zig +165 -0
  240. package/src/runtime/api.zig +431 -0
  241. package/src/runtime/async_bridge.zig +49 -0
  242. package/src/runtime/automation_commands.zig +686 -0
  243. package/src/runtime/automation_liveness_tests.zig +140 -0
  244. package/src/runtime/automation_snapshot.zig +246 -0
  245. package/src/runtime/automation_widget_dispatch.zig +617 -0
  246. package/src/runtime/bridge_dispatch_tests.zig +202 -0
  247. package/src/runtime/bridge_payload.zig +194 -0
  248. package/src/runtime/bridge_permission_tests.zig +551 -0
  249. package/src/runtime/bridge_responses.zig +414 -0
  250. package/src/runtime/builtin_bridge.zig +554 -0
  251. package/src/runtime/canvas_budget_edge_tests.zig +415 -0
  252. package/src/runtime/canvas_font_tests.zig +410 -0
  253. package/src/runtime/canvas_fonts.zig +229 -0
  254. package/src/runtime/canvas_frame.zig +1734 -0
  255. package/src/runtime/canvas_frame_animation_tests.zig +609 -0
  256. package/src/runtime/canvas_frame_cache_tests.zig +333 -0
  257. package/src/runtime/canvas_frame_helpers.zig +414 -0
  258. package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
  259. package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
  260. package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
  261. package/src/runtime/canvas_frame_retained_tests.zig +753 -0
  262. package/src/runtime/canvas_frame_tests.zig +9 -0
  263. package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
  264. package/src/runtime/canvas_image_tests.zig +362 -0
  265. package/src/runtime/canvas_images.zig +224 -0
  266. package/src/runtime/canvas_limits.zig +317 -0
  267. package/src/runtime/canvas_screenshot_tests.zig +289 -0
  268. package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
  269. package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
  270. package/src/runtime/canvas_widget_chart_tests.zig +249 -0
  271. package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
  272. package/src/runtime/canvas_widget_context_menu.zig +318 -0
  273. package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
  274. package/src/runtime/canvas_widget_control_tests.zig +2164 -0
  275. package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
  276. package/src/runtime/canvas_widget_display.zig +677 -0
  277. package/src/runtime/canvas_widget_event_tests.zig +1779 -0
  278. package/src/runtime/canvas_widget_events.zig +1098 -0
  279. package/src/runtime/canvas_widget_floating_tests.zig +695 -0
  280. package/src/runtime/canvas_widget_layout_tests.zig +26 -0
  281. package/src/runtime/canvas_widget_runtime.zig +1335 -0
  282. package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
  283. package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
  284. package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
  285. package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
  286. package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
  287. package/src/runtime/canvas_widget_state.zig +798 -0
  288. package/src/runtime/canvas_widget_text_tests.zig +2104 -0
  289. package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
  290. package/src/runtime/clock.zig +231 -0
  291. package/src/runtime/core.zig +927 -0
  292. package/src/runtime/effects.zig +4197 -0
  293. package/src/runtime/effects_audio_tests.zig +690 -0
  294. package/src/runtime/effects_clipboard_tests.zig +317 -0
  295. package/src/runtime/effects_fetch_tests.zig +1031 -0
  296. package/src/runtime/effects_file_tests.zig +407 -0
  297. package/src/runtime/effects_tests.zig +1251 -0
  298. package/src/runtime/flow.zig +1175 -0
  299. package/src/runtime/frame_profile.zig +221 -0
  300. package/src/runtime/gpu_surface_events.zig +639 -0
  301. package/src/runtime/launch_timing.zig +59 -0
  302. package/src/runtime/markdown_app_tests.zig +224 -0
  303. package/src/runtime/native_command_event_tests.zig +431 -0
  304. package/src/runtime/platform_bridge_tests.zig +8 -0
  305. package/src/runtime/platform_config_tests.zig +392 -0
  306. package/src/runtime/root.zig +150 -0
  307. package/src/runtime/runtime_event_tests.zig +1079 -0
  308. package/src/runtime/session_journal.zig +1522 -0
  309. package/src/runtime/session_record.zig +332 -0
  310. package/src/runtime/session_replay.zig +274 -0
  311. package/src/runtime/session_state.zig +30 -0
  312. package/src/runtime/session_tests.zig +399 -0
  313. package/src/runtime/shell_layout.zig +472 -0
  314. package/src/runtime/shell_layout_tests.zig +1246 -0
  315. package/src/runtime/shell_view_tests.zig +604 -0
  316. package/src/runtime/state.zig +110 -0
  317. package/src/runtime/system_services.zig +392 -0
  318. package/src/runtime/test_support.zig +79 -0
  319. package/src/runtime/tests.zig +30 -0
  320. package/src/runtime/ui_app.zig +3290 -0
  321. package/src/runtime/ui_app_huge_model_tests.zig +351 -0
  322. package/src/runtime/ui_app_provenance.zig +370 -0
  323. package/src/runtime/ui_app_tests.zig +3254 -0
  324. package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
  325. package/src/runtime/ui_app_window_tests.zig +442 -0
  326. package/src/runtime/validation.zig +206 -0
  327. package/src/runtime/view.zig +908 -0
  328. package/src/runtime/view_canvas.zig +850 -0
  329. package/src/runtime/view_widget_control.zig +433 -0
  330. package/src/runtime/view_widget_scroll.zig +360 -0
  331. package/src/runtime/view_widget_text.zig +275 -0
  332. package/src/runtime/view_widget_tree.zig +843 -0
  333. package/src/runtime/webview_view_bridge_tests.zig +664 -0
  334. package/src/runtime/widget_bridge.zig +231 -0
  335. package/src/runtime/window_command_bridge_tests.zig +403 -0
  336. package/src/runtime/window_storage.zig +255 -0
  337. package/src/runtime/window_view_runtime.zig +727 -0
  338. package/src/runtime/window_views.zig +334 -0
  339. package/src/security/root.zig +118 -0
  340. package/src/tooling/android.zig +1172 -0
  341. package/src/tooling/assets.zig +128 -0
  342. package/src/tooling/buildgraph.zig +379 -0
  343. package/src/tooling/cef.zig +671 -0
  344. package/src/tooling/codesign.zig +172 -0
  345. package/src/tooling/components/identity_tests.zig +185 -0
  346. package/src/tooling/components/stepper.zig +113 -0
  347. package/src/tooling/components/timeline.native +27 -0
  348. package/src/tooling/components/timeline_item.zig +131 -0
  349. package/src/tooling/default_icon.icns +0 -0
  350. package/src/tooling/default_icon.png +0 -0
  351. package/src/tooling/dev.zig +172 -0
  352. package/src/tooling/doctor.zig +349 -0
  353. package/src/tooling/eject_components.zig +170 -0
  354. package/src/tooling/embedlib.zig +290 -0
  355. package/src/tooling/ios.zig +528 -0
  356. package/src/tooling/manifest.zig +1939 -0
  357. package/src/tooling/package.zig +2388 -0
  358. package/src/tooling/process_tree.zig +114 -0
  359. package/src/tooling/raw_manifest.zig +193 -0
  360. package/src/tooling/root.zig +22 -0
  361. package/src/tooling/templates.zig +3191 -0
  362. package/src/tooling/toolchain.zig +371 -0
  363. package/src/tooling/verbs.zig +204 -0
  364. package/src/tooling/web_engine.zig +135 -0
  365. package/src/tooling/xcodeproj.zig +462 -0
  366. package/src/window_state/root.zig +507 -0
  367. package/index.js +0 -2
@@ -0,0 +1,1152 @@
1
+ //! The markup expression core: one grammar, one type discipline, one
2
+ //! evaluator shared by the runtime interpreter, the comptime-compiled
3
+ //! engine, and `native markup check` (grammar reference:
4
+ //! skill-data/native-ui/SKILL.md).
5
+ //!
6
+ //! Expressions are PURE and TOTAL by construction. Pure: the only inputs
7
+ //! are literals and binding values the engines resolve before evaluation —
8
+ //! no effects, no clock, no user-defined functions (the library below is
9
+ //! closed; extending it is a toolkit change, never an app change). Total:
10
+ //! parsing builds a bounded post-order node array (every child index is
11
+ //! smaller than its parent's), so evaluation is a single forward loop over
12
+ //! at most `max_expression_nodes` nodes — termination is structural, not a
13
+ //! property anyone has to prove per expression.
14
+ //!
15
+ //! Engine seam: the parser and type checker are comptime-callable and
16
+ //! allocation-free (fixed arrays). Each engine resolves the tree's binding
17
+ //! nodes to `Value`s its own way (interpreter: scope chain at runtime;
18
+ //! compiled engine: comptime-unrolled field access), then hands them to the
19
+ //! ONE `eval` below — identical inputs through identical arithmetic and
20
+ //! formatting code, so results (floats included) are bit-for-bit equal
21
+ //! across engines by construction.
22
+ //!
23
+ //! Type discipline: teaching errors over silent coercion. Arithmetic and
24
+ //! ordering take numbers only (a string minus a number is an error, never a
25
+ //! NaN); `and`/`or`/`not` take booleans; `++` joins anything by formatting
26
+ //! it exactly like text interpolation; `==`/`!=` compare any two values
27
+ //! (different types are simply not equal, except int/float which compare
28
+ //! numerically). Division always produces a float and division by zero is
29
+ //! an error — wrap with `round()`/`floor()` for whole-number contexts and
30
+ //! guard divisors in the model. There is no short-circuit: both sides of
31
+ //! `and`/`or` always evaluate (expressions are pure, so only errors are
32
+ //! observable, and the checker stays simple).
33
+
34
+ const std = @import("std");
35
+
36
+ // ------------------------------------------------------------------ values
37
+
38
+ /// A resolved binding or expression value. Enums resolve to their tag name
39
+ /// so equality against enum-typed loop variables and literals works
40
+ /// uniformly. This is the interpreter's `Value` (re-exported there); it
41
+ /// lives here so the evaluator and both engines share one definition.
42
+ pub const Value = union(enum) {
43
+ string: []const u8,
44
+ integer: i64,
45
+ float: f32,
46
+ boolean: bool,
47
+
48
+ /// Equality across values: same-type values compare directly, integers
49
+ /// and floats compare numerically (the integer converts to f32, so
50
+ /// magnitudes past 2^24 compare at f32 precision), and any other type
51
+ /// mix is simply not equal — never an error, matching how enum tags
52
+ /// and selection states have always compared.
53
+ pub fn eql(a: Value, b: Value) bool {
54
+ return switch (a) {
55
+ .string => |sa| b == .string and std.mem.eql(u8, sa, b.string),
56
+ .integer => |ia| switch (b) {
57
+ .integer => |ib| ia == ib,
58
+ .float => |fb| @as(f32, @floatFromInt(ia)) == fb,
59
+ else => false,
60
+ },
61
+ .float => |fa| switch (b) {
62
+ .float => |fb| fa == fb,
63
+ .integer => |ib| fa == @as(f32, @floatFromInt(ib)),
64
+ else => false,
65
+ },
66
+ .boolean => |ba| b == .boolean and ba == b.boolean,
67
+ };
68
+ }
69
+
70
+ pub fn truthy(self: Value) bool {
71
+ return switch (self) {
72
+ .boolean => |value| value,
73
+ .integer => |value| value != 0,
74
+ .float => |value| value != 0,
75
+ .string => |value| value.len > 0,
76
+ };
77
+ }
78
+ };
79
+
80
+ pub const ValueKind = enum { string, integer, float, boolean };
81
+
82
+ pub fn kindOf(value: Value) ValueKind {
83
+ return switch (value) {
84
+ .string => .string,
85
+ .integer => .integer,
86
+ .float => .float,
87
+ .boolean => .boolean,
88
+ };
89
+ }
90
+
91
+ /// Append a value as display text — THE deterministic formatting for text
92
+ /// interpolation and `++` concatenation, shared by both engines (float
93
+ /// formatting is std.fmt's shortest-round-trip decimal, identical on every
94
+ /// platform).
95
+ pub fn appendValue(out: *std.ArrayListUnmanaged(u8), arena: std.mem.Allocator, value: Value) error{OutOfMemory}!void {
96
+ var buffer: [64]u8 = undefined;
97
+ switch (value) {
98
+ .string => |text| try out.appendSlice(arena, text),
99
+ .integer => |int| try out.appendSlice(arena, std.fmt.bufPrint(&buffer, "{d}", .{int}) catch return error.OutOfMemory),
100
+ .float => |float| try out.appendSlice(arena, std.fmt.bufPrint(&buffer, "{d}", .{float}) catch return error.OutOfMemory),
101
+ .boolean => |boolean| try out.appendSlice(arena, if (boolean) "true" else "false"),
102
+ }
103
+ }
104
+
105
+ // ------------------------------------------------------------------ bounds
106
+
107
+ /// Complexity bounds, taught one-past in tests: fixed, documented, loud.
108
+ /// They exist so a hostile or generated expression can never make parsing,
109
+ /// checking, or evaluation grow past a small constant — the same budget
110
+ /// philosophy as the per-view canvas limits.
111
+ pub const max_expression_bytes = 256;
112
+ pub const max_expression_nodes = 64;
113
+ pub const max_expression_depth = 16;
114
+ pub const max_expression_call_args = 4;
115
+
116
+ // ---------------------------------------------------------------- messages
117
+
118
+ pub const empty_expression_message = "empty expression";
119
+ pub const expression_too_long_message = "expression is too long (over 256 bytes) - name the logic as a model fn";
120
+ pub const expression_too_many_nodes_message = "expression is too complex (over 64 terms) - name the logic as a model fn";
121
+ pub const expression_too_deep_message = "expression nests too deeply (over 16 levels) - flatten it or name the logic as a model fn";
122
+ pub const expression_too_many_args_message = "too many arguments in a call (over 4)";
123
+ pub const comparison_chain_message = "comparisons do not chain - split a < b < c into a < b and b < c";
124
+ pub const unterminated_string_message = "unterminated string - expression strings use single quotes ('done') and have no escapes";
125
+ pub const integer_literal_overflow_message = "integer literal does not fit in 64 bits";
126
+ pub const number_literal_range_message = "number literal is out of range";
127
+ pub const unknown_function_message = "unknown expression function - the library is closed (fixed, thousands, percent, date, time, datetime, upper, lower, trim, min, max, abs, round, floor, ceil, plural, pad); anything else is a model fn";
128
+ pub const clock_function_message = "reading the clock is an effect - expressions only format model data; keep a timestamp field that update/fx maintains and format it with date()/time()/datetime()";
129
+ pub const expected_operand_message = "expected a value: a number, 'string', true/false, a binding path, a function call, or ( )";
130
+ pub const expected_operator_message = "expected an operator (+ - * / ++ == != < <= > >= and or) or the end of the expression";
131
+ pub const expected_close_paren_message = "expected ')'";
132
+ pub const call_syntax_message = "expected ',' or ')' in the argument list";
133
+
134
+ pub const arithmetic_type_message = "arithmetic takes numbers on both sides - strings never coerce (join text with ++, or fix the model type)";
135
+ pub const ordering_type_message = "< <= > >= order numbers only - compare strings with ==, or order in a model fn";
136
+ pub const logic_type_message = "and/or/not take booleans - write the comparison out (count > 0)";
137
+ pub const negate_type_message = "unary minus takes a number";
138
+ pub const division_by_zero_message = "division by zero - guard with an if, or clamp the divisor in the model";
139
+ pub const integer_overflow_message = "integer overflow in expression arithmetic";
140
+ pub const non_finite_message = "expression arithmetic produced a non-finite number - clean the value in the model";
141
+ pub const digits_range_message = "digits must be a whole number between 0 and 6";
142
+ pub const timestamp_range_message = "timestamp is outside the formattable range (years 1-9999)";
143
+ pub const round_range_message = "round/floor/ceil result does not fit in a whole number";
144
+ pub const abs_overflow_message = "abs overflows on the most negative integer";
145
+
146
+ // --------------------------------------------------------------- functions
147
+
148
+ /// The closed, curated function library. Every function is pure and total;
149
+ /// the set is part of the toolkit's contract, so growing it is a toolkit
150
+ /// change with tests and docs, never an app-side extension.
151
+ pub const FunctionId = enum {
152
+ fixed,
153
+ thousands,
154
+ percent,
155
+ date,
156
+ time,
157
+ datetime,
158
+ upper,
159
+ lower,
160
+ trim,
161
+ min,
162
+ max,
163
+ abs,
164
+ round,
165
+ floor,
166
+ ceil,
167
+ plural,
168
+ // Appended, never reordered: additive growth keeps existing ids stable.
169
+ pad,
170
+ };
171
+
172
+ pub const FunctionSpec = struct {
173
+ id: FunctionId,
174
+ name: []const u8,
175
+ min_args: u8,
176
+ max_args: u8,
177
+ /// The teaching signature used by arity and argument-type errors.
178
+ signature: []const u8,
179
+ };
180
+
181
+ pub const function_specs = [_]FunctionSpec{
182
+ .{ .id = .fixed, .name = "fixed", .min_args = 2, .max_args = 2, .signature = "fixed takes (number, digits) with digits 0-6 and returns a string with exactly that many decimals" },
183
+ .{ .id = .thousands, .name = "thousands", .min_args = 1, .max_args = 1, .signature = "thousands takes one whole number (round() a float first) and returns it with , separators" },
184
+ .{ .id = .percent, .name = "percent", .min_args = 1, .max_args = 2, .signature = "percent takes (fraction) or (fraction, digits) with digits 0-6 - 0.42 formats as 42%" },
185
+ .{ .id = .date, .name = "date", .min_args = 1, .max_args = 1, .signature = "date takes one unix timestamp in seconds (a model integer) and formats it as YYYY-MM-DD in UTC" },
186
+ .{ .id = .time, .name = "time", .min_args = 1, .max_args = 1, .signature = "time takes one unix timestamp in seconds (a model integer) and formats it as HH:MM in UTC" },
187
+ .{ .id = .datetime, .name = "datetime", .min_args = 1, .max_args = 1, .signature = "datetime takes one unix timestamp in seconds (a model integer) and formats it as YYYY-MM-DD HH:MM in UTC" },
188
+ .{ .id = .upper, .name = "upper", .min_args = 1, .max_args = 1, .signature = "upper takes one string (ASCII letters map; other characters pass through unchanged)" },
189
+ .{ .id = .lower, .name = "lower", .min_args = 1, .max_args = 1, .signature = "lower takes one string (ASCII letters map; other characters pass through unchanged)" },
190
+ .{ .id = .trim, .name = "trim", .min_args = 1, .max_args = 1, .signature = "trim takes one string and removes leading/trailing whitespace" },
191
+ .{ .id = .min, .name = "min", .min_args = 2, .max_args = 2, .signature = "min takes two numbers" },
192
+ .{ .id = .max, .name = "max", .min_args = 2, .max_args = 2, .signature = "max takes two numbers" },
193
+ .{ .id = .abs, .name = "abs", .min_args = 1, .max_args = 1, .signature = "abs takes one number" },
194
+ .{ .id = .round, .name = "round", .min_args = 1, .max_args = 1, .signature = "round takes one number and returns the nearest whole number" },
195
+ .{ .id = .floor, .name = "floor", .min_args = 1, .max_args = 1, .signature = "floor takes one number and returns the nearest whole number at or below it" },
196
+ .{ .id = .ceil, .name = "ceil", .min_args = 1, .max_args = 1, .signature = "ceil takes one number and returns the nearest whole number at or above it" },
197
+ .{ .id = .plural, .name = "plural", .min_args = 3, .max_args = 3, .signature = "plural takes (count, singular, plural) - a count of exactly 1 picks the singular" },
198
+ .{ .id = .pad, .name = "pad", .min_args = 2, .max_args = 2, .signature = "pad takes (whole number, width) with width 0-6 (round() a float first) and zero-pads on the left to width digits - a - sign does not count toward width" },
199
+ };
200
+
201
+ pub fn findFunction(name: []const u8) ?FunctionSpec {
202
+ for (function_specs) |spec| {
203
+ if (std.mem.eql(u8, spec.name, name)) return spec;
204
+ }
205
+ return null;
206
+ }
207
+
208
+ /// Names that read like clock access get the effects teaching error
209
+ /// instead of the generic unknown-function message: the current time is an
210
+ /// effect, and its home is the model.
211
+ fn clockLikeName(name: []const u8) bool {
212
+ return std.mem.eql(u8, name, "now") or std.mem.eql(u8, name, "today");
213
+ }
214
+
215
+ // ------------------------------------------------------------------- trees
216
+
217
+ pub const NodeKind = enum {
218
+ literal_int,
219
+ literal_float,
220
+ literal_string,
221
+ literal_bool,
222
+ binding,
223
+ negate,
224
+ logical_not,
225
+ add,
226
+ subtract,
227
+ multiply,
228
+ divide,
229
+ concat,
230
+ equal,
231
+ not_equal,
232
+ less,
233
+ less_equal,
234
+ greater,
235
+ greater_equal,
236
+ logical_and,
237
+ logical_or,
238
+ call,
239
+ };
240
+
241
+ pub const ExprNode = struct {
242
+ kind: NodeKind,
243
+ /// Binding path or string-literal bytes (slices the expression source).
244
+ text: []const u8 = "",
245
+ int: i64 = 0,
246
+ float: f32 = 0,
247
+ boolean: bool = false,
248
+ /// Child indices (post-order: always smaller than this node's index).
249
+ /// Unary operators use `lhs` only.
250
+ lhs: u16 = 0,
251
+ rhs: u16 = 0,
252
+ function: FunctionId = .fixed,
253
+ args: [max_expression_call_args]u16 = @splat(0),
254
+ arg_count: u8 = 0,
255
+ /// A binding used directly as a comparison operand: arena-computed
256
+ /// scalar fns are rejected there (compare source fields, or bind a
257
+ /// bool-returning fn), exactly like the original `{a == b}` rule.
258
+ comparison_operand: bool = false,
259
+ /// Byte offset in the expression source, for diagnostics.
260
+ offset: u16 = 0,
261
+ };
262
+
263
+ pub const ExprTree = struct {
264
+ nodes: [max_expression_nodes]ExprNode = undefined,
265
+ len: u16 = 0,
266
+ root: u16 = 0,
267
+ };
268
+
269
+ pub const Diagnostic = struct {
270
+ offset: usize = 0,
271
+ message: []const u8 = "",
272
+ };
273
+
274
+ // ------------------------------------------------------------------ parser
275
+
276
+ /// Parse an expression (the text INSIDE `{...}`) into `tree`. Returns
277
+ /// false with `diagnostic` set on any syntax or bounds failure. Works at
278
+ /// runtime and comptime (fixed arrays, no allocation).
279
+ pub fn parse(source: []const u8, tree: *ExprTree, diagnostic: *Diagnostic) bool {
280
+ if (source.len > max_expression_bytes) {
281
+ diagnostic.* = .{ .offset = 0, .message = expression_too_long_message };
282
+ return false;
283
+ }
284
+ tree.len = 0;
285
+ var parser = ExprParser{ .source = source, .tree = tree, .diagnostic = diagnostic };
286
+ const root = parser.parseOr() catch return false;
287
+ parser.skipWhitespace();
288
+ if (parser.index < source.len) {
289
+ diagnostic.* = .{ .offset = parser.index, .message = expected_operator_message };
290
+ return false;
291
+ }
292
+ tree.root = root;
293
+ return true;
294
+ }
295
+
296
+ const ExprParseError = error{ExprSyntax};
297
+
298
+ const ExprParser = struct {
299
+ source: []const u8,
300
+ tree: *ExprTree,
301
+ diagnostic: *Diagnostic,
302
+ index: usize = 0,
303
+ depth: usize = 0,
304
+
305
+ fn fail(self: *ExprParser, offset: usize, message: []const u8) ExprParseError {
306
+ self.diagnostic.* = .{ .offset = offset, .message = message };
307
+ return error.ExprSyntax;
308
+ }
309
+
310
+ fn addNode(self: *ExprParser, node: ExprNode) ExprParseError!u16 {
311
+ if (self.tree.len >= max_expression_nodes) {
312
+ return self.fail(node.offset, expression_too_many_nodes_message);
313
+ }
314
+ self.tree.nodes[self.tree.len] = node;
315
+ self.tree.len += 1;
316
+ return self.tree.len - 1;
317
+ }
318
+
319
+ fn enter(self: *ExprParser, offset: usize) ExprParseError!void {
320
+ self.depth += 1;
321
+ if (self.depth > max_expression_depth) {
322
+ return self.fail(offset, expression_too_deep_message);
323
+ }
324
+ }
325
+
326
+ fn leave(self: *ExprParser) void {
327
+ self.depth -= 1;
328
+ }
329
+
330
+ fn skipWhitespace(self: *ExprParser) void {
331
+ while (self.index < self.source.len) : (self.index += 1) {
332
+ switch (self.source[self.index]) {
333
+ ' ', '\t', '\r', '\n' => {},
334
+ else => return,
335
+ }
336
+ }
337
+ }
338
+
339
+ fn peekByte(self: *const ExprParser) ?u8 {
340
+ if (self.index >= self.source.len) return null;
341
+ return self.source[self.index];
342
+ }
343
+
344
+ fn startsWithAt(self: *const ExprParser, token: []const u8) bool {
345
+ return std.mem.startsWith(u8, self.source[self.index..], token);
346
+ }
347
+
348
+ /// Match a keyword operator (`and`, `or`, `not`) at the cursor: the
349
+ /// token must end at a non-identifier byte so `android` stays a path.
350
+ fn matchKeyword(self: *ExprParser, keyword: []const u8) bool {
351
+ if (!self.startsWithAt(keyword)) return false;
352
+ const end = self.index + keyword.len;
353
+ if (end < self.source.len and identifierByte(self.source[end])) return false;
354
+ self.index = end;
355
+ return true;
356
+ }
357
+
358
+ fn matchToken(self: *ExprParser, token: []const u8) bool {
359
+ if (!self.startsWithAt(token)) return false;
360
+ self.index += token.len;
361
+ return true;
362
+ }
363
+
364
+ fn parseOr(self: *ExprParser) ExprParseError!u16 {
365
+ try self.enter(self.index);
366
+ defer self.leave();
367
+ var left = try self.parseAnd();
368
+ while (true) {
369
+ self.skipWhitespace();
370
+ const offset = self.index;
371
+ if (!self.matchKeyword("or")) break;
372
+ const right = try self.parseAnd();
373
+ left = try self.addNode(.{ .kind = .logical_or, .lhs = left, .rhs = right, .offset = @intCast(offset) });
374
+ }
375
+ return left;
376
+ }
377
+
378
+ fn parseAnd(self: *ExprParser) ExprParseError!u16 {
379
+ var left = try self.parseNot();
380
+ while (true) {
381
+ self.skipWhitespace();
382
+ const offset = self.index;
383
+ if (!self.matchKeyword("and")) break;
384
+ const right = try self.parseNot();
385
+ left = try self.addNode(.{ .kind = .logical_and, .lhs = left, .rhs = right, .offset = @intCast(offset) });
386
+ }
387
+ return left;
388
+ }
389
+
390
+ fn parseNot(self: *ExprParser) ExprParseError!u16 {
391
+ self.skipWhitespace();
392
+ const offset = self.index;
393
+ if (self.matchKeyword("not")) {
394
+ try self.enter(offset);
395
+ defer self.leave();
396
+ const operand = try self.parseNot();
397
+ return self.addNode(.{ .kind = .logical_not, .lhs = operand, .offset = @intCast(offset) });
398
+ }
399
+ return self.parseComparison();
400
+ }
401
+
402
+ fn parseComparison(self: *ExprParser) ExprParseError!u16 {
403
+ const left = try self.parseAdditive();
404
+ self.skipWhitespace();
405
+ const offset = self.index;
406
+ const kind: NodeKind = blk: {
407
+ if (self.matchToken("==")) break :blk .equal;
408
+ if (self.matchToken("!=")) break :blk .not_equal;
409
+ if (self.matchToken("<=")) break :blk .less_equal;
410
+ if (self.matchToken(">=")) break :blk .greater_equal;
411
+ if (self.matchToken("<")) break :blk .less;
412
+ if (self.matchToken(">")) break :blk .greater;
413
+ return left;
414
+ };
415
+ const right = try self.parseAdditive();
416
+ // Direct binding operands of a comparison reject arena-computed
417
+ // scalars (the engines read this flag when resolving).
418
+ self.markComparisonOperand(left);
419
+ self.markComparisonOperand(right);
420
+ self.skipWhitespace();
421
+ if (self.comparisonAhead()) {
422
+ return self.fail(self.index, comparison_chain_message);
423
+ }
424
+ return self.addNode(.{ .kind = kind, .lhs = left, .rhs = right, .offset = @intCast(offset) });
425
+ }
426
+
427
+ fn comparisonAhead(self: *const ExprParser) bool {
428
+ const rest = self.source[self.index..];
429
+ if (std.mem.startsWith(u8, rest, "==")) return true;
430
+ if (std.mem.startsWith(u8, rest, "!=")) return true;
431
+ if (std.mem.startsWith(u8, rest, "<")) return true;
432
+ if (std.mem.startsWith(u8, rest, ">")) return true;
433
+ return false;
434
+ }
435
+
436
+ fn markComparisonOperand(self: *ExprParser, index: u16) void {
437
+ if (self.tree.nodes[index].kind == .binding) {
438
+ self.tree.nodes[index].comparison_operand = true;
439
+ }
440
+ }
441
+
442
+ fn parseAdditive(self: *ExprParser) ExprParseError!u16 {
443
+ var left = try self.parseMultiplicative();
444
+ while (true) {
445
+ self.skipWhitespace();
446
+ const offset = self.index;
447
+ const kind: NodeKind = blk: {
448
+ if (self.matchToken("++")) break :blk .concat;
449
+ if (self.matchToken("+")) break :blk .add;
450
+ if (self.matchToken("-")) break :blk .subtract;
451
+ break;
452
+ };
453
+ const right = try self.parseMultiplicative();
454
+ left = try self.addNode(.{ .kind = kind, .lhs = left, .rhs = right, .offset = @intCast(offset) });
455
+ }
456
+ return left;
457
+ }
458
+
459
+ fn parseMultiplicative(self: *ExprParser) ExprParseError!u16 {
460
+ var left = try self.parseUnary();
461
+ while (true) {
462
+ self.skipWhitespace();
463
+ const offset = self.index;
464
+ const kind: NodeKind = blk: {
465
+ if (self.matchToken("*")) break :blk .multiply;
466
+ if (self.matchToken("/")) break :blk .divide;
467
+ break;
468
+ };
469
+ const right = try self.parseUnary();
470
+ left = try self.addNode(.{ .kind = kind, .lhs = left, .rhs = right, .offset = @intCast(offset) });
471
+ }
472
+ return left;
473
+ }
474
+
475
+ fn parseUnary(self: *ExprParser) ExprParseError!u16 {
476
+ self.skipWhitespace();
477
+ const offset = self.index;
478
+ if (self.matchToken("-")) {
479
+ try self.enter(offset);
480
+ defer self.leave();
481
+ const operand = try self.parseUnary();
482
+ return self.addNode(.{ .kind = .negate, .lhs = operand, .offset = @intCast(offset) });
483
+ }
484
+ return self.parsePrimary();
485
+ }
486
+
487
+ fn parsePrimary(self: *ExprParser) ExprParseError!u16 {
488
+ self.skipWhitespace();
489
+ const offset = self.index;
490
+ const byte = self.peekByte() orelse return self.fail(offset, if (offset == 0) empty_expression_message else expected_operand_message);
491
+ if (byte == '(') {
492
+ self.index += 1;
493
+ const inner = try self.parseOr();
494
+ self.skipWhitespace();
495
+ if (!self.matchToken(")")) return self.fail(self.index, expected_close_paren_message);
496
+ return inner;
497
+ }
498
+ if (byte == '\'') return self.parseString(offset);
499
+ if (byte >= '0' and byte <= '9') return self.parseNumber(offset);
500
+ if (identifierStartByte(byte)) return self.parseIdentifier(offset);
501
+ return self.fail(offset, expected_operand_message);
502
+ }
503
+
504
+ fn parseString(self: *ExprParser, offset: usize) ExprParseError!u16 {
505
+ self.index += 1;
506
+ const start = self.index;
507
+ while (self.index < self.source.len) : (self.index += 1) {
508
+ if (self.source[self.index] == '\'') {
509
+ const text = self.source[start..self.index];
510
+ self.index += 1;
511
+ return self.addNode(.{ .kind = .literal_string, .text = text, .offset = @intCast(offset) });
512
+ }
513
+ }
514
+ return self.fail(offset, unterminated_string_message);
515
+ }
516
+
517
+ fn parseNumber(self: *ExprParser, offset: usize) ExprParseError!u16 {
518
+ const start = self.index;
519
+ while (self.index < self.source.len and self.source[self.index] >= '0' and self.source[self.index] <= '9') {
520
+ self.index += 1;
521
+ }
522
+ var is_float = false;
523
+ if (self.index + 1 < self.source.len and self.source[self.index] == '.' and
524
+ self.source[self.index + 1] >= '0' and self.source[self.index + 1] <= '9')
525
+ {
526
+ is_float = true;
527
+ self.index += 1;
528
+ while (self.index < self.source.len and self.source[self.index] >= '0' and self.source[self.index] <= '9') {
529
+ self.index += 1;
530
+ }
531
+ }
532
+ const text = self.source[start..self.index];
533
+ if (is_float) {
534
+ const value = std.fmt.parseFloat(f32, text) catch {
535
+ return self.fail(offset, number_literal_range_message);
536
+ };
537
+ if (!std.math.isFinite(value)) return self.fail(offset, number_literal_range_message);
538
+ return self.addNode(.{ .kind = .literal_float, .float = value, .offset = @intCast(offset) });
539
+ }
540
+ const value = std.fmt.parseInt(i64, text, 10) catch {
541
+ return self.fail(offset, integer_literal_overflow_message);
542
+ };
543
+ return self.addNode(.{ .kind = .literal_int, .int = value, .offset = @intCast(offset) });
544
+ }
545
+
546
+ fn parseIdentifier(self: *ExprParser, offset: usize) ExprParseError!u16 {
547
+ const start = self.index;
548
+ while (self.index < self.source.len and pathByte(self.source[self.index])) {
549
+ self.index += 1;
550
+ }
551
+ const token = self.source[start..self.index];
552
+ if (std.mem.eql(u8, token, "true")) {
553
+ return self.addNode(.{ .kind = .literal_bool, .boolean = true, .offset = @intCast(offset) });
554
+ }
555
+ if (std.mem.eql(u8, token, "false")) {
556
+ return self.addNode(.{ .kind = .literal_bool, .boolean = false, .offset = @intCast(offset) });
557
+ }
558
+ self.skipWhitespace();
559
+ if (self.peekByte() == '(') {
560
+ if (std.mem.indexOfScalar(u8, token, '.') != null) {
561
+ return self.fail(offset, unknown_function_message);
562
+ }
563
+ return self.parseCall(offset, token);
564
+ }
565
+ if (!isBindingPath(token)) return self.fail(offset, expected_operand_message);
566
+ return self.addNode(.{ .kind = .binding, .text = token, .offset = @intCast(offset) });
567
+ }
568
+
569
+ fn parseCall(self: *ExprParser, offset: usize, name: []const u8) ExprParseError!u16 {
570
+ const spec = findFunction(name) orelse {
571
+ if (clockLikeName(name)) return self.fail(offset, clock_function_message);
572
+ return self.fail(offset, unknown_function_message);
573
+ };
574
+ self.index += 1; // consume '('
575
+ try self.enter(offset);
576
+ defer self.leave();
577
+ var args: [max_expression_call_args]u16 = @splat(0);
578
+ var arg_count: u8 = 0;
579
+ self.skipWhitespace();
580
+ if (!self.matchToken(")")) {
581
+ while (true) {
582
+ if (arg_count >= max_expression_call_args) {
583
+ return self.fail(self.index, expression_too_many_args_message);
584
+ }
585
+ args[arg_count] = try self.parseOr();
586
+ arg_count += 1;
587
+ self.skipWhitespace();
588
+ if (self.matchToken(",")) continue;
589
+ if (self.matchToken(")")) break;
590
+ return self.fail(self.index, call_syntax_message);
591
+ }
592
+ }
593
+ if (arg_count < spec.min_args or arg_count > spec.max_args) {
594
+ return self.fail(offset, spec.signature);
595
+ }
596
+ return self.addNode(.{
597
+ .kind = .call,
598
+ .function = spec.id,
599
+ .args = args,
600
+ .arg_count = arg_count,
601
+ .offset = @intCast(offset),
602
+ });
603
+ }
604
+ };
605
+
606
+ fn identifierStartByte(byte: u8) bool {
607
+ return (byte >= 'a' and byte <= 'z') or (byte >= 'A' and byte <= 'Z') or byte == '_';
608
+ }
609
+
610
+ fn identifierByte(byte: u8) bool {
611
+ return identifierStartByte(byte) or (byte >= '0' and byte <= '9');
612
+ }
613
+
614
+ fn pathByte(byte: u8) bool {
615
+ return identifierByte(byte) or byte == '.';
616
+ }
617
+
618
+ /// A dotted binding path (`item.field`): the same rule the markup grammar
619
+ /// applies to bare `{path}` bindings.
620
+ pub fn isBindingPath(text: []const u8) bool {
621
+ if (text.len == 0) return false;
622
+ var segment_start = true;
623
+ for (text) |byte| {
624
+ if (segment_start) {
625
+ if (!identifierStartByte(byte)) return false;
626
+ segment_start = false;
627
+ continue;
628
+ }
629
+ if (byte == '.') {
630
+ segment_start = true;
631
+ continue;
632
+ }
633
+ if (!identifierByte(byte)) return false;
634
+ }
635
+ return !segment_start;
636
+ }
637
+
638
+ // ------------------------------------------------------------ type checker
639
+
640
+ /// Static type discipline over a parsed tree. `binding_kinds` is indexed
641
+ /// by node: engines fill the kind for each `.binding` node (null when the
642
+ /// type is only runtime-known, e.g. through an optional; `native markup
643
+ /// check` passes all-null because it has no model). Unknown kinds flow
644
+ /// through as null; definite mismatches return `error.ExprType` with the
645
+ /// SAME message `eval` reports at runtime, so the compiled engine's compile
646
+ /// errors, the interpreter's build diagnostics, and the checker teach with
647
+ /// one voice. Returns the expression's result kind, or null when it is
648
+ /// only runtime-known. Comptime-callable and allocation-free.
649
+ pub fn checkTypes(tree: *const ExprTree, binding_kinds: []const ?ValueKind, diagnostic: *Diagnostic) error{ExprType}!?ValueKind {
650
+ var kinds: [max_expression_nodes]?ValueKind = @splat(null);
651
+ var index: usize = 0;
652
+ while (index < tree.len) : (index += 1) {
653
+ const node = tree.nodes[index];
654
+ kinds[index] = try checkNode(tree, node, index, binding_kinds, &kinds, diagnostic);
655
+ }
656
+ return kinds[tree.root];
657
+ }
658
+
659
+ fn checkNode(
660
+ tree: *const ExprTree,
661
+ node: ExprNode,
662
+ index: usize,
663
+ binding_kinds: []const ?ValueKind,
664
+ kinds: *[max_expression_nodes]?ValueKind,
665
+ diagnostic: *Diagnostic,
666
+ ) error{ExprType}!?ValueKind {
667
+ _ = tree;
668
+ switch (node.kind) {
669
+ .literal_int => return .integer,
670
+ .literal_float => return .float,
671
+ .literal_string => return .string,
672
+ .literal_bool => return .boolean,
673
+ .binding => return binding_kinds[index],
674
+ .negate => {
675
+ const operand = kinds[node.lhs];
676
+ if (definitelyNotNumber(operand)) return failType(diagnostic, node.offset, negate_type_message);
677
+ return operand;
678
+ },
679
+ .logical_not => {
680
+ if (definitelyNotBoolean(kinds[node.lhs])) return failType(diagnostic, node.offset, logic_type_message);
681
+ return .boolean;
682
+ },
683
+ .add, .subtract, .multiply => {
684
+ const left = kinds[node.lhs];
685
+ const right = kinds[node.rhs];
686
+ if (definitelyNotNumber(left) or definitelyNotNumber(right)) {
687
+ return failType(diagnostic, node.offset, arithmetic_type_message);
688
+ }
689
+ if (left == null or right == null) return null;
690
+ if (left.? == .integer and right.? == .integer) return .integer;
691
+ return .float;
692
+ },
693
+ .divide => {
694
+ if (definitelyNotNumber(kinds[node.lhs]) or definitelyNotNumber(kinds[node.rhs])) {
695
+ return failType(diagnostic, node.offset, arithmetic_type_message);
696
+ }
697
+ return .float;
698
+ },
699
+ .concat => return .string,
700
+ .equal, .not_equal => return .boolean,
701
+ .less, .less_equal, .greater, .greater_equal => {
702
+ if (definitelyNotNumber(kinds[node.lhs]) or definitelyNotNumber(kinds[node.rhs])) {
703
+ return failType(diagnostic, node.offset, ordering_type_message);
704
+ }
705
+ return .boolean;
706
+ },
707
+ .logical_and, .logical_or => {
708
+ if (definitelyNotBoolean(kinds[node.lhs]) or definitelyNotBoolean(kinds[node.rhs])) {
709
+ return failType(diagnostic, node.offset, logic_type_message);
710
+ }
711
+ return .boolean;
712
+ },
713
+ .call => return checkCall(node, kinds, diagnostic),
714
+ }
715
+ }
716
+
717
+ fn checkCall(node: ExprNode, kinds: *[max_expression_nodes]?ValueKind, diagnostic: *Diagnostic) error{ExprType}!?ValueKind {
718
+ const signature = signatureFor(node.function);
719
+ switch (node.function) {
720
+ .fixed => {
721
+ if (definitelyNotNumber(kinds[node.args[0]])) return failType(diagnostic, node.offset, signature);
722
+ if (definitelyNotKind(kinds[node.args[1]], .integer)) return failType(diagnostic, node.offset, signature);
723
+ return .string;
724
+ },
725
+ .percent => {
726
+ if (definitelyNotNumber(kinds[node.args[0]])) return failType(diagnostic, node.offset, signature);
727
+ if (node.arg_count > 1 and definitelyNotKind(kinds[node.args[1]], .integer)) {
728
+ return failType(diagnostic, node.offset, signature);
729
+ }
730
+ return .string;
731
+ },
732
+ .thousands, .date, .time, .datetime => {
733
+ if (definitelyNotKind(kinds[node.args[0]], .integer)) return failType(diagnostic, node.offset, signature);
734
+ return .string;
735
+ },
736
+ .upper, .lower, .trim => {
737
+ if (definitelyNotKind(kinds[node.args[0]], .string)) return failType(diagnostic, node.offset, signature);
738
+ return .string;
739
+ },
740
+ .min, .max => {
741
+ const left = kinds[node.args[0]];
742
+ const right = kinds[node.args[1]];
743
+ if (definitelyNotNumber(left) or definitelyNotNumber(right)) {
744
+ return failType(diagnostic, node.offset, signature);
745
+ }
746
+ if (left == null or right == null) return null;
747
+ if (left.? == .integer and right.? == .integer) return .integer;
748
+ return .float;
749
+ },
750
+ .abs => {
751
+ const operand = kinds[node.args[0]];
752
+ if (definitelyNotNumber(operand)) return failType(diagnostic, node.offset, signature);
753
+ return operand;
754
+ },
755
+ .round, .floor, .ceil => {
756
+ if (definitelyNotNumber(kinds[node.args[0]])) return failType(diagnostic, node.offset, signature);
757
+ return .integer;
758
+ },
759
+ .plural => {
760
+ if (definitelyNotKind(kinds[node.args[0]], .integer)) return failType(diagnostic, node.offset, signature);
761
+ if (definitelyNotKind(kinds[node.args[1]], .string)) return failType(diagnostic, node.offset, signature);
762
+ if (definitelyNotKind(kinds[node.args[2]], .string)) return failType(diagnostic, node.offset, signature);
763
+ return .string;
764
+ },
765
+ .pad => {
766
+ // The value takes whole numbers like thousands; the width is an
767
+ // integer exactly like fixed's digits argument.
768
+ if (definitelyNotKind(kinds[node.args[0]], .integer)) return failType(diagnostic, node.offset, signature);
769
+ if (definitelyNotKind(kinds[node.args[1]], .integer)) return failType(diagnostic, node.offset, signature);
770
+ return .string;
771
+ },
772
+ }
773
+ }
774
+
775
+ fn signatureFor(id: FunctionId) []const u8 {
776
+ for (function_specs) |spec| {
777
+ if (spec.id == id) return spec.signature;
778
+ }
779
+ unreachable;
780
+ }
781
+
782
+ fn definitelyNotNumber(kind: ?ValueKind) bool {
783
+ const known = kind orelse return false;
784
+ return known != .integer and known != .float;
785
+ }
786
+
787
+ fn definitelyNotBoolean(kind: ?ValueKind) bool {
788
+ const known = kind orelse return false;
789
+ return known != .boolean;
790
+ }
791
+
792
+ fn definitelyNotKind(kind: ?ValueKind, expected: ValueKind) bool {
793
+ const known = kind orelse return false;
794
+ return known != expected;
795
+ }
796
+
797
+ fn failType(diagnostic: *Diagnostic, offset: u16, message: []const u8) error{ExprType} {
798
+ diagnostic.* = .{ .offset = offset, .message = message };
799
+ return error.ExprType;
800
+ }
801
+
802
+ // --------------------------------------------------------------- evaluator
803
+
804
+ pub const EvalOutcome = union(enum) {
805
+ value: Value,
806
+ /// A value-dependent failure with its teaching message (division by
807
+ /// zero, overflow, a runtime type mismatch the static pass could not
808
+ /// see). The interpreter turns it into a build diagnostic; the
809
+ /// compiled engine latches `ui.failed`.
810
+ fail: []const u8,
811
+ };
812
+
813
+ /// Evaluate a parsed tree. `values` is indexed by node: the caller fills
814
+ /// every `.binding` node's slot before the call (each engine resolves
815
+ /// bindings its own way); this loop fills the rest bottom-up — post-order
816
+ /// construction makes one forward pass total, with no recursion. `arena`
817
+ /// backs string results (concat and the formatting functions); everything
818
+ /// they produce lives exactly as long as the built view.
819
+ pub fn eval(tree: *const ExprTree, values: *[max_expression_nodes]Value, arena: std.mem.Allocator) error{OutOfMemory}!EvalOutcome {
820
+ var index: usize = 0;
821
+ while (index < tree.len) : (index += 1) {
822
+ const node = tree.nodes[index];
823
+ values[index] = switch (node.kind) {
824
+ .literal_int => .{ .integer = node.int },
825
+ .literal_float => .{ .float = node.float },
826
+ .literal_string => .{ .string = node.text },
827
+ .literal_bool => .{ .boolean = node.boolean },
828
+ .binding => continue, // resolved by the caller
829
+ .negate => switch (values[node.lhs]) {
830
+ .integer => |int| blk: {
831
+ if (int == std.math.minInt(i64)) return .{ .fail = integer_overflow_message };
832
+ break :blk .{ .integer = -int };
833
+ },
834
+ .float => |float| .{ .float = -float },
835
+ else => return .{ .fail = negate_type_message },
836
+ },
837
+ .logical_not => switch (values[node.lhs]) {
838
+ .boolean => |value| .{ .boolean = !value },
839
+ else => return .{ .fail = logic_type_message },
840
+ },
841
+ .add, .subtract, .multiply => switch (try arithmetic(node.kind, values[node.lhs], values[node.rhs])) {
842
+ .value => |value| value,
843
+ .fail => |message| return .{ .fail = message },
844
+ },
845
+ .divide => blk: {
846
+ const left = asFloat(values[node.lhs]) orelse return .{ .fail = arithmetic_type_message };
847
+ const right = asFloat(values[node.rhs]) orelse return .{ .fail = arithmetic_type_message };
848
+ if (right == 0) return .{ .fail = division_by_zero_message };
849
+ const result = left / right;
850
+ if (!std.math.isFinite(result)) return .{ .fail = non_finite_message };
851
+ break :blk .{ .float = result };
852
+ },
853
+ .concat => blk: {
854
+ var out: std.ArrayListUnmanaged(u8) = .empty;
855
+ try appendValue(&out, arena, values[node.lhs]);
856
+ try appendValue(&out, arena, values[node.rhs]);
857
+ break :blk .{ .string = out.items };
858
+ },
859
+ .equal => .{ .boolean = Value.eql(values[node.lhs], values[node.rhs]) },
860
+ .not_equal => .{ .boolean = !Value.eql(values[node.lhs], values[node.rhs]) },
861
+ .less, .less_equal, .greater, .greater_equal => blk: {
862
+ const left = asFloat(values[node.lhs]) orelse return .{ .fail = ordering_type_message };
863
+ const right = asFloat(values[node.rhs]) orelse return .{ .fail = ordering_type_message };
864
+ break :blk .{ .boolean = switch (node.kind) {
865
+ .less => left < right,
866
+ .less_equal => left <= right,
867
+ .greater => left > right,
868
+ else => left >= right,
869
+ } };
870
+ },
871
+ .logical_and, .logical_or => blk: {
872
+ // No short-circuit: expressions are pure, so both sides
873
+ // always evaluate (only errors are observable).
874
+ const left = values[node.lhs];
875
+ const right = values[node.rhs];
876
+ if (left != .boolean or right != .boolean) return .{ .fail = logic_type_message };
877
+ break :blk .{ .boolean = if (node.kind == .logical_and)
878
+ left.boolean and right.boolean
879
+ else
880
+ left.boolean or right.boolean };
881
+ },
882
+ .call => switch (try evalCall(node, values, arena)) {
883
+ .value => |value| value,
884
+ .fail => |message| return .{ .fail = message },
885
+ },
886
+ };
887
+ }
888
+ return .{ .value = values[tree.root] };
889
+ }
890
+
891
+ fn arithmetic(kind: NodeKind, left: Value, right: Value) error{OutOfMemory}!EvalOutcome {
892
+ if (left == .integer and right == .integer) {
893
+ const a = left.integer;
894
+ const b = right.integer;
895
+ const result = switch (kind) {
896
+ .add => @addWithOverflow(a, b),
897
+ .subtract => @subWithOverflow(a, b),
898
+ else => @mulWithOverflow(a, b),
899
+ };
900
+ if (result[1] != 0) return .{ .fail = integer_overflow_message };
901
+ return .{ .value = .{ .integer = result[0] } };
902
+ }
903
+ const a = asFloat(left) orelse return .{ .fail = arithmetic_type_message };
904
+ const b = asFloat(right) orelse return .{ .fail = arithmetic_type_message };
905
+ const result = switch (kind) {
906
+ .add => a + b,
907
+ .subtract => a - b,
908
+ else => a * b,
909
+ };
910
+ if (!std.math.isFinite(result)) return .{ .fail = non_finite_message };
911
+ return .{ .value = .{ .float = result } };
912
+ }
913
+
914
+ fn asFloat(value: Value) ?f32 {
915
+ return switch (value) {
916
+ .integer => |int| @floatFromInt(int),
917
+ .float => |float| float,
918
+ else => null,
919
+ };
920
+ }
921
+
922
+ // ----------------------------------------------------------- the functions
923
+
924
+ fn evalCall(node: ExprNode, values: *[max_expression_nodes]Value, arena: std.mem.Allocator) error{OutOfMemory}!EvalOutcome {
925
+ const signature = signatureFor(node.function);
926
+ const a = values[node.args[0]];
927
+ switch (node.function) {
928
+ .fixed => {
929
+ const digits = digitsArg(values[node.args[1]]) orelse return .{ .fail = digits_range_message };
930
+ return formatFixed(arena, a, digits, "", signature);
931
+ },
932
+ .percent => {
933
+ const digits: usize = if (node.arg_count > 1)
934
+ digitsArg(values[node.args[1]]) orelse return .{ .fail = digits_range_message }
935
+ else
936
+ 0;
937
+ const fraction = asFloat(a) orelse return .{ .fail = signature };
938
+ const scaled = fraction * 100;
939
+ if (!std.math.isFinite(scaled)) return .{ .fail = non_finite_message };
940
+ return formatFixed(arena, .{ .float = scaled }, digits, "%", signature);
941
+ },
942
+ .thousands => {
943
+ if (a != .integer) return .{ .fail = signature };
944
+ return .{ .value = .{ .string = try formatThousands(arena, a.integer) } };
945
+ },
946
+ .date, .time, .datetime => {
947
+ if (a != .integer) return .{ .fail = signature };
948
+ return formatTimestamp(arena, node.function, a.integer);
949
+ },
950
+ .upper, .lower => {
951
+ if (a != .string) return .{ .fail = signature };
952
+ const out = try arena.dupe(u8, a.string);
953
+ for (out) |*byte| {
954
+ byte.* = if (node.function == .upper) std.ascii.toUpper(byte.*) else std.ascii.toLower(byte.*);
955
+ }
956
+ return .{ .value = .{ .string = out } };
957
+ },
958
+ .trim => {
959
+ if (a != .string) return .{ .fail = signature };
960
+ return .{ .value = .{ .string = std.mem.trim(u8, a.string, " \t\r\n") } };
961
+ },
962
+ .min, .max => {
963
+ const b = values[node.args[1]];
964
+ if (a == .integer and b == .integer) {
965
+ const picked = if (node.function == .min) @min(a.integer, b.integer) else @max(a.integer, b.integer);
966
+ return .{ .value = .{ .integer = picked } };
967
+ }
968
+ const fa = asFloat(a) orelse return .{ .fail = signature };
969
+ const fb = asFloat(b) orelse return .{ .fail = signature };
970
+ if (std.math.isNan(fa) or std.math.isNan(fb)) return .{ .fail = non_finite_message };
971
+ return .{ .value = .{ .float = if (node.function == .min) @min(fa, fb) else @max(fa, fb) } };
972
+ },
973
+ .abs => switch (a) {
974
+ .integer => |int| {
975
+ if (int == std.math.minInt(i64)) return .{ .fail = abs_overflow_message };
976
+ return .{ .value = .{ .integer = @intCast(@abs(int)) } };
977
+ },
978
+ .float => |float| {
979
+ if (std.math.isNan(float)) return .{ .fail = non_finite_message };
980
+ return .{ .value = .{ .float = @abs(float) } };
981
+ },
982
+ else => return .{ .fail = signature },
983
+ },
984
+ .round, .floor, .ceil => switch (a) {
985
+ .integer => return .{ .value = a },
986
+ .float => |float| {
987
+ if (!std.math.isFinite(float)) return .{ .fail = non_finite_message };
988
+ const shifted = switch (node.function) {
989
+ .round => @round(float),
990
+ .floor => @floor(float),
991
+ else => @ceil(float),
992
+ };
993
+ if (shifted < -9007199254740992.0 or shifted > 9007199254740992.0) {
994
+ return .{ .fail = round_range_message };
995
+ }
996
+ return .{ .value = .{ .integer = @intFromFloat(shifted) } };
997
+ },
998
+ else => return .{ .fail = signature },
999
+ },
1000
+ .plural => {
1001
+ if (a != .integer) return .{ .fail = signature };
1002
+ const singular = values[node.args[1]];
1003
+ const plural_form = values[node.args[2]];
1004
+ if (singular != .string or plural_form != .string) return .{ .fail = signature };
1005
+ return .{ .value = .{ .string = if (a.integer == 1) singular.string else plural_form.string } };
1006
+ },
1007
+ .pad => {
1008
+ const width = digitsArg(values[node.args[1]]) orelse return .{ .fail = digits_range_message };
1009
+ if (a != .integer) return .{ .fail = signature };
1010
+ return .{ .value = .{ .string = try formatPadded(arena, a.integer, width) } };
1011
+ },
1012
+ }
1013
+ }
1014
+
1015
+ fn digitsArg(value: Value) ?usize {
1016
+ if (value != .integer) return null;
1017
+ if (value.integer < 0 or value.integer > 6) return null;
1018
+ return @intCast(value.integer);
1019
+ }
1020
+
1021
+ /// Fixed-decimal formatting: integers print exactly (digits of zeros
1022
+ /// appended); floats round through std.fmt's deterministic decimal
1023
+ /// renderer. `suffix` is the percent sign channel.
1024
+ fn formatFixed(arena: std.mem.Allocator, value: Value, digits: usize, suffix: []const u8, signature: []const u8) error{OutOfMemory}!EvalOutcome {
1025
+ var buffer: [80]u8 = undefined;
1026
+ const body = switch (value) {
1027
+ .integer => |int| std.fmt.bufPrint(&buffer, "{d}", .{int}) catch return error.OutOfMemory,
1028
+ .float => |float| blk: {
1029
+ if (!std.math.isFinite(float)) return .{ .fail = non_finite_message };
1030
+ break :blk std.fmt.float.render(&buffer, float, .{ .mode = .decimal, .precision = digits }) catch {
1031
+ return .{ .fail = non_finite_message };
1032
+ };
1033
+ },
1034
+ else => return .{ .fail = signature },
1035
+ };
1036
+ var out: std.ArrayListUnmanaged(u8) = .empty;
1037
+ try out.appendSlice(arena, body);
1038
+ if (value == .integer and digits > 0) {
1039
+ try out.append(arena, '.');
1040
+ try out.appendNTimes(arena, '0', digits);
1041
+ }
1042
+ try out.appendSlice(arena, suffix);
1043
+ return .{ .value = .{ .string = out.items } };
1044
+ }
1045
+
1046
+ fn formatThousands(arena: std.mem.Allocator, value: i64) error{OutOfMemory}![]const u8 {
1047
+ var buffer: [32]u8 = undefined;
1048
+ const digits = std.fmt.bufPrint(&buffer, "{d}", .{value}) catch return error.OutOfMemory;
1049
+ const negative = digits.len > 0 and digits[0] == '-';
1050
+ const body = if (negative) digits[1..] else digits;
1051
+ var out: std.ArrayListUnmanaged(u8) = .empty;
1052
+ if (negative) try out.append(arena, '-');
1053
+ for (body, 0..) |byte, index| {
1054
+ if (index > 0 and (body.len - index) % 3 == 0) try out.append(arena, ',');
1055
+ try out.append(arena, byte);
1056
+ }
1057
+ return out.items;
1058
+ }
1059
+
1060
+ /// Zero-pad a whole number on the left to `width` digits: pad(7, 2) is
1061
+ /// "07". The sign precedes the zeros and does not count toward the width
1062
+ /// (pad(-7, 3) is "-007"), and a number wider than `width` prints in full.
1063
+ fn formatPadded(arena: std.mem.Allocator, value: i64, width: usize) error{OutOfMemory}![]const u8 {
1064
+ var buffer: [32]u8 = undefined;
1065
+ const digits = std.fmt.bufPrint(&buffer, "{d}", .{value}) catch return error.OutOfMemory;
1066
+ const negative = digits.len > 0 and digits[0] == '-';
1067
+ const body = if (negative) digits[1..] else digits;
1068
+ var out: std.ArrayListUnmanaged(u8) = .empty;
1069
+ if (negative) try out.append(arena, '-');
1070
+ if (body.len < width) try out.appendNTimes(arena, '0', width - body.len);
1071
+ try out.appendSlice(arena, body);
1072
+ return out.items;
1073
+ }
1074
+
1075
+ /// Format a unix timestamp (seconds) in UTC. Formatting a MODEL timestamp
1076
+ /// is pure — the same input always renders the same text on every machine.
1077
+ /// Reading the current time is an effect and lives in the model/fx loop,
1078
+ /// which the parser teaches at `now()`.
1079
+ fn formatTimestamp(arena: std.mem.Allocator, function: FunctionId, seconds: i64) error{OutOfMemory}!EvalOutcome {
1080
+ const days = @divFloor(seconds, 86_400);
1081
+ const second_of_day: u32 = @intCast(@mod(seconds, 86_400));
1082
+ const date_parts = civilFromDays(days) orelse return .{ .fail = timestamp_range_message };
1083
+ const year: u32 = @intCast(date_parts.year);
1084
+ const hour = second_of_day / 3600;
1085
+ const minute = (second_of_day % 3600) / 60;
1086
+ var buffer: [24]u8 = undefined;
1087
+ const text = switch (function) {
1088
+ .date => std.fmt.bufPrint(&buffer, "{d:0>4}-{d:0>2}-{d:0>2}", .{ year, date_parts.month, date_parts.day }) catch unreachable,
1089
+ .time => std.fmt.bufPrint(&buffer, "{d:0>2}:{d:0>2}", .{ hour, minute }) catch unreachable,
1090
+ else => std.fmt.bufPrint(&buffer, "{d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2}", .{ year, date_parts.month, date_parts.day, hour, minute }) catch unreachable,
1091
+ };
1092
+ return .{ .value = .{ .string = try arena.dupe(u8, text) } };
1093
+ }
1094
+
1095
+ const CivilDate = struct { year: i64, month: u32, day: u32 };
1096
+
1097
+ /// Days-since-epoch to a proleptic Gregorian civil date (the classic
1098
+ /// era-based algorithm). Null outside years 1-9999, which keeps the
1099
+ /// formatted width fixed and refuses astronomically wrong model data.
1100
+ fn civilFromDays(days: i64) ?CivilDate {
1101
+ const shifted = days + 719_468;
1102
+ const era = @divFloor(shifted, 146_097);
1103
+ const day_of_era: u32 = @intCast(shifted - era * 146_097);
1104
+ const year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
1105
+ const year = @as(i64, year_of_era) + era * 400;
1106
+ const day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1107
+ const month_index = (5 * day_of_year + 2) / 153;
1108
+ const day = day_of_year - (153 * month_index + 2) / 5 + 1;
1109
+ const month = if (month_index < 10) month_index + 3 else month_index - 9;
1110
+ const civil_year = if (month <= 2) year + 1 else year;
1111
+ if (civil_year < 1 or civil_year > 9999) return null;
1112
+ return .{ .year = civil_year, .month = month, .day = day };
1113
+ }
1114
+
1115
+ // ---------------------------------------------------- tooling helpers
1116
+
1117
+ /// The first token in `source` that reads as a function call to a name
1118
+ /// outside the closed library: `native markup check` uses it to attach a
1119
+ /// did-you-mean to the unknown-function error (the validator itself stays
1120
+ /// allocation-free, so it cannot format the name into its message).
1121
+ pub fn firstUnknownFunction(source: []const u8) ?[]const u8 {
1122
+ var index: usize = 0;
1123
+ while (index < source.len) {
1124
+ const byte = source[index];
1125
+ if (byte == '\'') {
1126
+ // Skip string literals so quoted parens cannot fake a call.
1127
+ const close = std.mem.indexOfScalarPos(u8, source, index + 1, '\'') orelse return null;
1128
+ index = close + 1;
1129
+ continue;
1130
+ }
1131
+ if (identifierStartByte(byte)) {
1132
+ const start = index;
1133
+ while (index < source.len and pathByte(source[index])) index += 1;
1134
+ const token = source[start..index];
1135
+ var rest = index;
1136
+ while (rest < source.len and (source[rest] == ' ' or source[rest] == '\t')) rest += 1;
1137
+ if (rest < source.len and source[rest] == '(' and std.mem.indexOfScalar(u8, token, '.') == null) {
1138
+ if (findFunction(token) == null and !clockLikeName(token)) return token;
1139
+ }
1140
+ continue;
1141
+ }
1142
+ index += 1;
1143
+ }
1144
+ return null;
1145
+ }
1146
+
1147
+ /// The names of the closed function library, for did-you-mean suggestions.
1148
+ pub const known_function_names = blk: {
1149
+ var names: [function_specs.len][]const u8 = undefined;
1150
+ for (function_specs, 0..) |spec, index| names[index] = spec.name;
1151
+ break :blk names;
1152
+ };