@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,3791 @@
1
+ //! Markup front-end for the declarative ui builder (grammar reference:
2
+ //! skill-data/native-ui/SKILL.md).
3
+ //!
4
+ //! This module owns the grammar: an HTML-like element tree with kebab-case
5
+ //! element and attribute names, `{binding}` expressions, `on-*` message
6
+ //! dispatch (`msg` or `msg:{arg}`), and `for`/`if`/`else` structure tags.
7
+ //! Parsing is type-agnostic; binding and message validation against a
8
+ //! concrete Model/Msg happens in the interpreter layer.
9
+ //!
10
+ //! The parser is deliberately strict: unknown syntax is an error with a
11
+ //! line/column position, never a silent skip — fast, specific failure is
12
+ //! the feedback loop markup authors (human or agent) rely on.
13
+
14
+ const std = @import("std");
15
+ const builtin = @import("builtin");
16
+ const font_coverage = @import("font_coverage.zig");
17
+
18
+ /// The vocabulary registry: elements, attributes, and events with stable
19
+ /// codes, structural predicates, and rule-hook attachments — the one
20
+ /// authoritative statement every `known_*` list below derives from (see
21
+ /// ui_schema.zig).
22
+ pub const schema = @import("ui_schema.zig");
23
+
24
+ /// The expression core: grammar, bounds, type discipline, and the one
25
+ /// evaluator both engines share (see ui_markup_expr.zig).
26
+ pub const expr = @import("ui_markup_expr.zig");
27
+
28
+ /// NSUI, the canonical document's serialized form: deterministic binary
29
+ /// with registry codes, the document hash journals anchor on, and the
30
+ /// derived JSON dump (see ui_markup_binary.zig).
31
+ pub const binary = @import("ui_markup_binary.zig");
32
+
33
+ /// The model–view contract: comptime reflection of Model/Msg into a
34
+ /// serializable artifact, the check-time verifier of markup against it
35
+ /// (both directions), and the emit/parse plumbing `native check` and the
36
+ /// per-app `zig build model-contract` step share (ui_markup_contract.zig).
37
+ pub const contract = @import("ui_markup_contract.zig");
38
+
39
+ /// Minimal-diff edit operations (write-back's write half): typed ops on a
40
+ /// parsed document that change only bytes inside the target node's span,
41
+ /// validated by reparse + structural diff before any file write
42
+ /// (ui_markup_edit.zig).
43
+ pub const edit = @import("ui_markup_edit.zig");
44
+
45
+ pub const MarkupErrorInfo = struct {
46
+ line: usize = 0,
47
+ column: usize = 0,
48
+ message: []const u8 = "",
49
+ /// Source file the position refers to, relative to the markup root
50
+ /// (the root view file's directory). Empty for single-file documents;
51
+ /// import resolution stamps it so errors inside imported component
52
+ /// files name the right file.
53
+ path: []const u8 = "",
54
+ };
55
+
56
+ pub const MarkupNodeKind = enum {
57
+ element,
58
+ text,
59
+ for_block,
60
+ if_block,
61
+ else_block,
62
+ template_block,
63
+ use_block,
64
+ import_block,
65
+ slot_block,
66
+ };
67
+
68
+ /// A half-open byte range into the SOURCE FILE the owning node was parsed
69
+ /// from (`MarkupNode.src_path` names the file after import resolution).
70
+ /// Spans are the write-back anchor: a tool edits exactly these bytes and
71
+ /// nothing else. The classic line/column positions on nodes, attributes,
72
+ /// and diagnostics are derived from the same scan (`positionAt` recomputes
73
+ /// one from the other; a conformance test holds them equal).
74
+ pub const Span = struct {
75
+ start: usize = 0,
76
+ end: usize = 0,
77
+ };
78
+
79
+ pub const MarkupAttr = struct {
80
+ name: []const u8,
81
+ value: []const u8,
82
+ line: usize,
83
+ column: usize,
84
+ /// Byte range of the attribute NAME in its source file.
85
+ name_span: Span = .{},
86
+ /// Byte range of the attribute VALUE (inside the quotes); an empty
87
+ /// range at the name's end for value-less attributes — which is also
88
+ /// the insertion point a writer would use.
89
+ value_span: Span = .{},
90
+ /// The value parsed ONCE into its typed form, stamped by the
91
+ /// canonicalization pass (`canonicalize`/`canonicalizeComptime`).
92
+ /// Null on a freshly parsed document; consumers go through
93
+ /// `attrTyped`, which classifies on the fly when the pass has not
94
+ /// run, so canonicalization changes cost, never meaning.
95
+ typed: ?*const TypedAttrValue = null,
96
+ };
97
+
98
+ pub const MarkupNode = struct {
99
+ kind: MarkupNodeKind,
100
+ /// Element name for `element` nodes ("row", "text-field", ...).
101
+ name: []const u8 = "",
102
+ attrs: []const MarkupAttr = &.{},
103
+ children: []const MarkupNode = &.{},
104
+ /// Raw text content (may contain `{...}` interpolations).
105
+ text: []const u8 = "",
106
+ line: usize = 0,
107
+ column: usize = 0,
108
+ /// Byte range of the whole node in its source file: `<` through the
109
+ /// closing `>` for elements (self-closing included), the trimmed
110
+ /// visible bytes for text runs.
111
+ span: Span = .{},
112
+ /// For text runs that interpolate (`{...}` present): the run split
113
+ /// ONCE into literal/binding/expression segments by canonicalization.
114
+ /// Null on a freshly parsed document or a plain-literal run.
115
+ typed_text: ?[]const TypedTextSegment = null,
116
+ /// Source file this node came from, relative to the markup root.
117
+ /// Empty for single-file documents; import resolution stamps every
118
+ /// node of every resolved file so diagnostics name the right file.
119
+ src_path: []const u8 = "",
120
+
121
+ pub fn attr(self: MarkupNode, name: []const u8) ?[]const u8 {
122
+ for (self.attrs) |attribute| {
123
+ if (std.mem.eql(u8, attribute.name, name)) return attribute.value;
124
+ }
125
+ return null;
126
+ }
127
+
128
+ pub fn attrEntry(self: MarkupNode, name: []const u8) ?MarkupAttr {
129
+ for (self.attrs) |attribute| {
130
+ if (std.mem.eql(u8, attribute.name, name)) return attribute;
131
+ }
132
+ return null;
133
+ }
134
+ };
135
+
136
+ pub const MarkupDocument = struct {
137
+ /// Top-level `<import src="..."/>` nodes, in file order, before the
138
+ /// templates. Import resolution (`resolveImports` /
139
+ /// `resolveImportsComptime`) consumes them into `templates` and leaves
140
+ /// this empty; a non-empty list marks the document unresolved.
141
+ imports: []const MarkupNode = &.{},
142
+ /// Top-level `<template name="..." args="...">` definitions, in file
143
+ /// order (after import resolution: imported templates first, in import
144
+ /// order, then the file's own). `<use>` sites reference them by name;
145
+ /// a use inside a template body may only reference templates defined
146
+ /// earlier in this list (which also rules out recursion structurally).
147
+ templates: []const MarkupNode = &.{},
148
+ /// The view root element. Null for a component file — a file that is
149
+ /// all templates is valid as an import target, but an app view needs
150
+ /// a root, which the engines enforce with a teaching error.
151
+ root: ?MarkupNode = null,
152
+
153
+ pub fn templateIndex(self: MarkupDocument, name: []const u8) ?usize {
154
+ for (self.templates, 0..) |template_node, index| {
155
+ const template_name = template_node.attr("name") orelse continue;
156
+ if (std.mem.eql(u8, template_name, name)) return index;
157
+ }
158
+ return null;
159
+ }
160
+ };
161
+
162
+ /// One declared template arg: the name, and the default literal when the
163
+ /// declaration used the `name=default` form (`args="title trend=flat"`).
164
+ pub const TemplateArg = struct {
165
+ name: []const u8,
166
+ default: ?[]const u8 = null,
167
+ };
168
+
169
+ /// Split one `args` token into name and optional default. Defaults are
170
+ /// literals only — a default cannot see any scope — which `validate`
171
+ /// enforces with a teaching error.
172
+ pub fn parseTemplateArg(token: []const u8) TemplateArg {
173
+ const eq = std.mem.indexOfScalar(u8, token, '=') orelse return .{ .name = token };
174
+ return .{ .name = token[0..eq], .default = token[eq + 1 ..] };
175
+ }
176
+
177
+ /// Iterate a template's declared args (the space-separated `args`
178
+ /// attribute; each token is `name` or `name=default`). Works at runtime
179
+ /// and comptime.
180
+ pub fn templateArgs(template_node: MarkupNode) std.mem.TokenIterator(u8, .scalar) {
181
+ return std.mem.tokenizeScalar(u8, template_node.attr("args") orelse "", ' ');
182
+ }
183
+
184
+ pub fn templateDeclaresArg(template_node: MarkupNode, name: []const u8) bool {
185
+ var args = templateArgs(template_node);
186
+ while (args.next()) |token| {
187
+ if (std.mem.eql(u8, parseTemplateArg(token).name, name)) return true;
188
+ }
189
+ return false;
190
+ }
191
+
192
+ /// The single `<slot/>` in a template body, or null. Does not descend into
193
+ /// `<use>` children: content passed onward belongs to the inner template's
194
+ /// slot, and a literal slot there is rejected by `validate` (v1 has no
195
+ /// slot forwarding).
196
+ pub fn templateSlot(template_node: MarkupNode) ?MarkupNode {
197
+ if (template_node.children.len != 1) return null;
198
+ return findSlot(template_node.children[0]);
199
+ }
200
+
201
+ fn findSlot(node: MarkupNode) ?MarkupNode {
202
+ if (node.kind == .slot_block) return node;
203
+ if (node.kind == .use_block) return null;
204
+ for (node.children) |child| {
205
+ if (findSlot(child)) |found| return found;
206
+ }
207
+ return null;
208
+ }
209
+
210
+ pub const ParseError = error{ MarkupSyntax, OutOfMemory };
211
+
212
+ pub const Parser = struct {
213
+ source: []const u8,
214
+ index: usize = 0,
215
+ line: usize = 1,
216
+ column: usize = 1,
217
+ arena: std.mem.Allocator,
218
+ diagnostic: MarkupErrorInfo = .{},
219
+
220
+ pub fn init(arena: std.mem.Allocator, source: []const u8) Parser {
221
+ return .{ .arena = arena, .source = source };
222
+ }
223
+
224
+ /// Parse a document: comments and whitespace around zero or more
225
+ /// top-level `<import>` nodes, then zero or more `<template>`
226
+ /// definitions, then at most one root element. A file that is all
227
+ /// templates (a component file) parses with a null root — it is valid
228
+ /// as an import target; the engines require a root for a view.
229
+ pub fn parse(self: *Parser) ParseError!MarkupDocument {
230
+ var imports: std.ArrayListUnmanaged(MarkupNode) = .empty;
231
+ var templates: std.ArrayListUnmanaged(MarkupNode) = .empty;
232
+ while (true) {
233
+ self.skipWhitespaceAndComments();
234
+ if (self.index >= self.source.len) {
235
+ if (imports.items.len == 0 and templates.items.len == 0) {
236
+ return self.fail(empty_document_message);
237
+ }
238
+ return .{ .imports = imports.items, .templates = templates.items, .root = null };
239
+ }
240
+ const node = try self.parseElement();
241
+ if (node.kind == .import_block) {
242
+ if (templates.items.len > 0) {
243
+ return self.failAt(node.line, node.column, import_top_level_message);
244
+ }
245
+ try imports.append(self.arena, node);
246
+ continue;
247
+ }
248
+ if (node.kind == .template_block) {
249
+ if (templates.items.len >= max_document_templates) {
250
+ return self.failAt(node.line, node.column, max_templates_message);
251
+ }
252
+ try templates.append(self.arena, node);
253
+ continue;
254
+ }
255
+ self.skipWhitespaceAndComments();
256
+ if (self.index < self.source.len) {
257
+ return self.fail("expected end of file after the root element");
258
+ }
259
+ return .{ .imports = imports.items, .templates = templates.items, .root = node };
260
+ }
261
+ }
262
+
263
+ fn parseElement(self: *Parser) ParseError!MarkupNode {
264
+ const start_line = self.line;
265
+ const start_column = self.column;
266
+ const start_offset = self.index;
267
+ if (!self.consumeByte('<')) return self.fail("expected '<' to open an element");
268
+ const name = try self.parseName("element name");
269
+
270
+ var attrs: std.ArrayListUnmanaged(MarkupAttr) = .empty;
271
+ while (true) {
272
+ self.skipWhitespace();
273
+ const byte = self.peek() orelse return self.fail("unterminated element tag");
274
+ if (byte == '/' or byte == '>') break;
275
+ const attr_line = self.line;
276
+ const attr_column = self.column;
277
+ const name_start = self.index;
278
+ const attr_name = try self.parseName("attribute name");
279
+ const name_end = self.index;
280
+ var value: []const u8 = "";
281
+ var value_span = Span{ .start = name_end, .end = name_end };
282
+ self.skipWhitespace();
283
+ if (self.consumeByte('=')) {
284
+ self.skipWhitespace();
285
+ value = try self.parseQuotedValue();
286
+ value_span = .{ .start = self.index - value.len - 1, .end = self.index - 1 };
287
+ }
288
+ try attrs.append(self.arena, .{
289
+ .name = attr_name,
290
+ .value = value,
291
+ .line = attr_line,
292
+ .column = attr_column,
293
+ .name_span = .{ .start = name_start, .end = name_end },
294
+ .value_span = value_span,
295
+ });
296
+ }
297
+
298
+ var node = MarkupNode{
299
+ .kind = nodeKindForName(name),
300
+ .name = name,
301
+ .attrs = attrs.items,
302
+ .line = start_line,
303
+ .column = start_column,
304
+ .span = .{ .start = start_offset, .end = start_offset },
305
+ };
306
+
307
+ if (self.consumeByte('/')) {
308
+ if (!self.consumeByte('>')) return self.fail("expected '>' after '/' in a self-closing tag");
309
+ node.span.end = self.index;
310
+ return node;
311
+ }
312
+ if (!self.consumeByte('>')) return self.fail("expected '>' to close the element tag");
313
+
314
+ var children: std.ArrayListUnmanaged(MarkupNode) = .empty;
315
+ while (true) {
316
+ self.skipComments();
317
+ const byte = self.peek() orelse return self.failAt(start_line, start_column, "element was never closed");
318
+ if (byte == '<') {
319
+ if (self.peekAt(1) == '/') {
320
+ try self.parseClosingTag(name);
321
+ break;
322
+ }
323
+ try children.append(self.arena, try self.parseElement());
324
+ continue;
325
+ }
326
+ // Record the position of the run's first VISIBLE byte, so
327
+ // messages that point into text content (the tofu guard)
328
+ // land on the character, not the run's end.
329
+ const text_line = self.line;
330
+ const text_column = self.column;
331
+ const text_offset = self.index;
332
+ const text = self.takeText();
333
+ const trimmed = std.mem.trim(u8, text, " \t\r\n");
334
+ if (trimmed.len > 0) {
335
+ var line = text_line;
336
+ var column = text_column;
337
+ for (text[0..textLeadingTrim(text)]) |lead_byte| {
338
+ if (lead_byte == '\n') {
339
+ line += 1;
340
+ column = 1;
341
+ } else {
342
+ column += 1;
343
+ }
344
+ }
345
+ const visible_start = text_offset + textLeadingTrim(text);
346
+ try children.append(self.arena, .{
347
+ .kind = .text,
348
+ .text = trimmed,
349
+ .line = line,
350
+ .column = column,
351
+ .span = .{ .start = visible_start, .end = visible_start + trimmed.len },
352
+ });
353
+ }
354
+ }
355
+
356
+ node.children = children.items;
357
+ if (std.mem.eql(u8, name, "text")) {
358
+ node.children = try self.spliceInlineSeparators(node.children);
359
+ }
360
+ node.span.end = self.index;
361
+ return node;
362
+ }
363
+
364
+ /// Whitespace between a span paragraph's inline children is STRUCTURE:
365
+ /// the parser trims every text run, so "value <span>42</span>" would
366
+ /// otherwise render "value42". When a <text> holds span children, any
367
+ /// source whitespace between two adjacent content children collapses
368
+ /// to ONE single-space text node spliced between them — materialized
369
+ /// here, at parse time, so the spacing is ordinary text content that
370
+ /// serializes, hashes, and round-trips like any other run (the NSUI
371
+ /// document hash strips spans, so spacing can never live in byte
372
+ /// gaps). Runs written with no whitespace between them abut, which is
373
+ /// how a mono run takes trailing punctuation. Span-less text keeps
374
+ /// the classic trim exactly as before.
375
+ fn spliceInlineSeparators(self: *Parser, children: []const MarkupNode) ParseError![]const MarkupNode {
376
+ if (!childrenIncludeSpan(children)) return children;
377
+ var separators: usize = 0;
378
+ for (children[1..], children[0 .. children.len - 1]) |next, previous| {
379
+ if (gapHasInlineSpace(self.source, previous.span.end, next.span.start)) separators += 1;
380
+ }
381
+ if (separators == 0) return children;
382
+ const out = try self.arena.alloc(MarkupNode, children.len + separators);
383
+ var len: usize = 0;
384
+ for (children, 0..) |child, index| {
385
+ if (index > 0 and gapHasInlineSpace(self.source, children[index - 1].span.end, child.span.start)) {
386
+ out[len] = inlineSeparatorNode(self.source, children[index - 1].span.end, child.span.start);
387
+ len += 1;
388
+ }
389
+ out[len] = child;
390
+ len += 1;
391
+ }
392
+ return out[0..len];
393
+ }
394
+
395
+ fn parseClosingTag(self: *Parser, open_name: []const u8) ParseError!void {
396
+ const line = self.line;
397
+ const column = self.column;
398
+ _ = self.consumeByte('<');
399
+ _ = self.consumeByte('/');
400
+ const name = try self.parseName("closing tag name");
401
+ self.skipWhitespace();
402
+ if (!self.consumeByte('>')) return self.fail("expected '>' in closing tag");
403
+ if (!std.mem.eql(u8, name, open_name)) {
404
+ return self.failAt(line, column, "closing tag does not match the open element");
405
+ }
406
+ }
407
+
408
+ fn parseName(self: *Parser, what: []const u8) ParseError![]const u8 {
409
+ const start = self.index;
410
+ while (self.peek()) |byte| {
411
+ const valid = (byte >= 'a' and byte <= 'z') or (byte >= '0' and byte <= '9') or byte == '-' or byte == '_';
412
+ if (!valid) break;
413
+ self.advance();
414
+ }
415
+ if (self.index == start) {
416
+ self.diagnostic = .{ .line = self.line, .column = self.column, .message = what };
417
+ return self.fail("expected a lowercase kebab-case name");
418
+ }
419
+ return self.source[start..self.index];
420
+ }
421
+
422
+ fn parseQuotedValue(self: *Parser) ParseError![]const u8 {
423
+ if (!self.consumeByte('"')) return self.fail("expected '\"' to open an attribute value");
424
+ const start = self.index;
425
+ while (self.peek()) |byte| {
426
+ if (byte == '"') {
427
+ const value = self.source[start..self.index];
428
+ self.advance();
429
+ return value;
430
+ }
431
+ if (byte == '\n') return self.fail("attribute values may not contain newlines");
432
+ self.advance();
433
+ }
434
+ return self.fail("unterminated attribute value");
435
+ }
436
+
437
+ fn takeText(self: *Parser) []const u8 {
438
+ const start = self.index;
439
+ while (self.peek()) |byte| {
440
+ if (byte == '<') break;
441
+ self.advance();
442
+ }
443
+ return self.source[start..self.index];
444
+ }
445
+
446
+ fn skipWhitespaceAndComments(self: *Parser) void {
447
+ while (true) {
448
+ const before = self.index;
449
+ self.skipWhitespace();
450
+ self.skipComments();
451
+ if (self.index == before) return;
452
+ }
453
+ }
454
+
455
+ fn skipComments(self: *Parser) void {
456
+ while (std.mem.startsWith(u8, self.source[self.index..], "<!--")) {
457
+ const end = std.mem.indexOfPos(u8, self.source, self.index + 4, "-->") orelse {
458
+ // Unterminated comment: consume to EOF; parse loop reports it.
459
+ while (self.peek() != null) self.advance();
460
+ return;
461
+ };
462
+ while (self.index < end + 3) self.advance();
463
+ }
464
+ }
465
+
466
+ fn skipWhitespace(self: *Parser) void {
467
+ while (self.peek()) |byte| {
468
+ if (byte != ' ' and byte != '\t' and byte != '\r' and byte != '\n') return;
469
+ self.advance();
470
+ }
471
+ }
472
+
473
+ fn peek(self: *const Parser) ?u8 {
474
+ if (self.index >= self.source.len) return null;
475
+ return self.source[self.index];
476
+ }
477
+
478
+ fn peekAt(self: *const Parser, offset: usize) ?u8 {
479
+ if (self.index + offset >= self.source.len) return null;
480
+ return self.source[self.index + offset];
481
+ }
482
+
483
+ fn consumeByte(self: *Parser, byte: u8) bool {
484
+ if (self.peek() == byte) {
485
+ self.advance();
486
+ return true;
487
+ }
488
+ return false;
489
+ }
490
+
491
+ fn advance(self: *Parser) void {
492
+ if (self.source[self.index] == '\n') {
493
+ self.line += 1;
494
+ self.column = 1;
495
+ } else {
496
+ self.column += 1;
497
+ }
498
+ self.index += 1;
499
+ }
500
+
501
+ fn fail(self: *Parser, message: []const u8) ParseError {
502
+ return self.failAt(self.line, self.column, message);
503
+ }
504
+
505
+ fn failAt(self: *Parser, line: usize, column: usize, message: []const u8) ParseError {
506
+ self.diagnostic = .{ .line = line, .column = column, .message = message };
507
+ return error.MarkupSyntax;
508
+ }
509
+ };
510
+
511
+ pub const Position = struct { line: usize, column: usize };
512
+
513
+ /// Line/column (1-based; columns count bytes, matching the parser) of a
514
+ /// byte offset in a source. This is the DERIVATION diagnostics rest on:
515
+ /// spans are the authoritative positions, line/column their display form,
516
+ /// and a conformance test holds the parser's stamped line/column equal to
517
+ /// `positionAt(source, span.start)` for every node and attribute.
518
+ pub fn positionAt(source: []const u8, offset: usize) Position {
519
+ var line: usize = 1;
520
+ var column: usize = 1;
521
+ const clamped = @min(offset, source.len);
522
+ for (source[0..clamped]) |byte| {
523
+ if (byte == '\n') {
524
+ line += 1;
525
+ column = 1;
526
+ } else {
527
+ column += 1;
528
+ }
529
+ }
530
+ return .{ .line = line, .column = column };
531
+ }
532
+
533
+ fn nodeKindForName(name: []const u8) MarkupNodeKind {
534
+ if (std.mem.eql(u8, name, "for")) return .for_block;
535
+ if (std.mem.eql(u8, name, "if")) return .if_block;
536
+ if (std.mem.eql(u8, name, "else")) return .else_block;
537
+ if (std.mem.eql(u8, name, "template")) return .template_block;
538
+ if (std.mem.eql(u8, name, "use")) return .use_block;
539
+ if (std.mem.eql(u8, name, "import")) return .import_block;
540
+ if (std.mem.eql(u8, name, "slot")) return .slot_block;
541
+ return .element;
542
+ }
543
+
544
+ // ------------------------------------------------------- comptime parsing
545
+
546
+ /// Comptime counterpart of `Parser.parse` for `@embedFile`d sources: the
547
+ /// same `Parser` token-level helpers drive the scan (single source of truth
548
+ /// for the grammar), but attribute/child accumulation uses comptime slice
549
+ /// concatenation instead of an arena, and any syntax error becomes a
550
+ /// compile error carrying the line/column and message that the runtime
551
+ /// diagnostic would carry.
552
+ pub fn parseComptime(comptime source: []const u8) MarkupDocument {
553
+ comptime {
554
+ @setEvalBranchQuota(comptime_parse_quota_base + source.len * comptime_parse_quota_per_byte);
555
+ var parser = Parser.init(undefined, source);
556
+ var imports: []const MarkupNode = &.{};
557
+ var templates: []const MarkupNode = &.{};
558
+ while (true) {
559
+ parser.skipWhitespaceAndComments();
560
+ if (parser.index >= parser.source.len) {
561
+ if (imports.len == 0 and templates.len == 0) {
562
+ failComptime(&parser, parser.fail(empty_document_message));
563
+ }
564
+ return .{ .imports = imports, .templates = templates, .root = null };
565
+ }
566
+ const node = parseElementComptime(&parser);
567
+ if (node.kind == .import_block) {
568
+ if (templates.len > 0) {
569
+ failComptime(&parser, parser.failAt(node.line, node.column, import_top_level_message));
570
+ }
571
+ imports = imports ++ &[_]MarkupNode{node};
572
+ continue;
573
+ }
574
+ if (node.kind == .template_block) {
575
+ if (templates.len >= max_document_templates) {
576
+ failComptime(&parser, parser.failAt(node.line, node.column, max_templates_message));
577
+ }
578
+ templates = templates ++ &[_]MarkupNode{node};
579
+ continue;
580
+ }
581
+ parser.skipWhitespaceAndComments();
582
+ if (parser.index < parser.source.len) {
583
+ failComptime(&parser, parser.fail("expected end of file after the root element"));
584
+ }
585
+ return .{ .imports = imports, .templates = templates, .root = node };
586
+ }
587
+ }
588
+ }
589
+
590
+ /// Comptime parsing walks every byte through the shared scanner helpers, so
591
+ /// the branch quota scales with the source: a handful of comptime branches
592
+ /// per byte, with generous headroom for nesting.
593
+ const comptime_parse_quota_base = 20_000;
594
+ const comptime_parse_quota_per_byte = 200;
595
+
596
+ /// Comptime mirror of `Parser.parseElement`: identical control flow, with
597
+ /// `attrs ++`/`children ++` in place of the arena-backed lists.
598
+ fn parseElementComptime(comptime parser: *Parser) MarkupNode {
599
+ const start_line = parser.line;
600
+ const start_column = parser.column;
601
+ const start_offset = parser.index;
602
+ if (!parser.consumeByte('<')) failComptime(parser, parser.fail("expected '<' to open an element"));
603
+ const name = parser.parseName("element name") catch |err| failComptime(parser, err);
604
+
605
+ var attrs: []const MarkupAttr = &.{};
606
+ while (true) {
607
+ parser.skipWhitespace();
608
+ const byte = parser.peek() orelse failComptime(parser, parser.fail("unterminated element tag"));
609
+ if (byte == '/' or byte == '>') break;
610
+ const attr_line = parser.line;
611
+ const attr_column = parser.column;
612
+ const name_start = parser.index;
613
+ const attr_name = parser.parseName("attribute name") catch |err| failComptime(parser, err);
614
+ const name_end = parser.index;
615
+ var value: []const u8 = "";
616
+ var value_span = Span{ .start = name_end, .end = name_end };
617
+ parser.skipWhitespace();
618
+ if (parser.consumeByte('=')) {
619
+ parser.skipWhitespace();
620
+ value = parser.parseQuotedValue() catch |err| failComptime(parser, err);
621
+ value_span = .{ .start = parser.index - value.len - 1, .end = parser.index - 1 };
622
+ }
623
+ attrs = attrs ++ &[_]MarkupAttr{.{
624
+ .name = attr_name,
625
+ .value = value,
626
+ .line = attr_line,
627
+ .column = attr_column,
628
+ .name_span = .{ .start = name_start, .end = name_end },
629
+ .value_span = value_span,
630
+ }};
631
+ }
632
+
633
+ var node = MarkupNode{
634
+ .kind = nodeKindForName(name),
635
+ .name = name,
636
+ .attrs = attrs,
637
+ .line = start_line,
638
+ .column = start_column,
639
+ .span = .{ .start = start_offset, .end = start_offset },
640
+ };
641
+
642
+ if (parser.consumeByte('/')) {
643
+ if (!parser.consumeByte('>')) failComptime(parser, parser.fail("expected '>' after '/' in a self-closing tag"));
644
+ node.span.end = parser.index;
645
+ return node;
646
+ }
647
+ if (!parser.consumeByte('>')) failComptime(parser, parser.fail("expected '>' to close the element tag"));
648
+
649
+ var children: []const MarkupNode = &.{};
650
+ while (true) {
651
+ parser.skipComments();
652
+ const byte = parser.peek() orelse failComptime(parser, parser.failAt(start_line, start_column, "element was never closed"));
653
+ if (byte == '<') {
654
+ if (parser.peekAt(1) == '/') {
655
+ parser.parseClosingTag(name) catch |err| failComptime(parser, err);
656
+ break;
657
+ }
658
+ children = children ++ &[_]MarkupNode{parseElementComptime(parser)};
659
+ continue;
660
+ }
661
+ const text_line = parser.line;
662
+ const text_column = parser.column;
663
+ const text_offset = parser.index;
664
+ const text = parser.takeText();
665
+ const trimmed = std.mem.trim(u8, text, " \t\r\n");
666
+ if (trimmed.len > 0) {
667
+ var line = text_line;
668
+ var column = text_column;
669
+ for (text[0..textLeadingTrim(text)]) |lead_byte| {
670
+ if (lead_byte == '\n') {
671
+ line += 1;
672
+ column = 1;
673
+ } else {
674
+ column += 1;
675
+ }
676
+ }
677
+ const visible_start = text_offset + textLeadingTrim(text);
678
+ children = children ++ &[_]MarkupNode{.{
679
+ .kind = .text,
680
+ .text = trimmed,
681
+ .line = line,
682
+ .column = column,
683
+ .span = .{ .start = visible_start, .end = visible_start + trimmed.len },
684
+ }};
685
+ }
686
+ }
687
+
688
+ node.children = children;
689
+ if (std.mem.eql(u8, name, "text")) {
690
+ node.children = spliceInlineSeparatorsComptime(parser.source, node.children);
691
+ }
692
+ node.span.end = parser.index;
693
+ return node;
694
+ }
695
+
696
+ /// Comptime mirror of `Parser.spliceInlineSeparators`: identical gap
697
+ /// predicate and separator shape, with comptime slice concatenation in
698
+ /// place of the arena — both engines see one materialized document.
699
+ fn spliceInlineSeparatorsComptime(comptime source: []const u8, comptime children: []const MarkupNode) []const MarkupNode {
700
+ comptime {
701
+ if (!childrenIncludeSpan(children)) return children;
702
+ var out: []const MarkupNode = &.{};
703
+ for (children, 0..) |child, index| {
704
+ if (index > 0 and gapHasInlineSpace(source, children[index - 1].span.end, child.span.start)) {
705
+ out = out ++ &[_]MarkupNode{inlineSeparatorNode(source, children[index - 1].span.end, child.span.start)};
706
+ }
707
+ out = out ++ &[_]MarkupNode{child};
708
+ }
709
+ return out;
710
+ }
711
+ }
712
+
713
+ /// Surface the parser's diagnostic (already positioned by the shared
714
+ /// helpers) as a compile error. The error value parameter exists so call
715
+ /// sites read like the runtime parser's `try`/`return self.fail(...)`.
716
+ fn failComptime(comptime parser: *const Parser, comptime err: ParseError) noreturn {
717
+ _ = err;
718
+ @compileError(std.fmt.comptimePrint("markup error at line {d}, column {d}: {s}", .{
719
+ parser.diagnostic.line,
720
+ parser.diagnostic.column,
721
+ parser.diagnostic.message,
722
+ }));
723
+ }
724
+
725
+ // ------------------------------------------------------------ expressions
726
+
727
+ pub const Expression = union(enum) {
728
+ literal: []const u8,
729
+ binding: []const u8,
730
+ equals: struct { left: []const u8, right: []const u8 },
731
+ /// Any other `{...}` content: the total expression grammar
732
+ /// (arithmetic, comparisons, boolean logic, `++` concatenation, and
733
+ /// the closed function library — see ui_markup_expr.zig). The payload
734
+ /// is the raw inner text; classification does not parse it, so
735
+ /// consumers (the validator via `attrExpressionError`, the engines via
736
+ /// their evaluators) surface the specific teaching message themselves.
737
+ expression: []const u8,
738
+ };
739
+
740
+ /// Parse an attribute value: a plain literal, or exactly one brace-wrapped
741
+ /// expression — a bare `{path}` binding, the legacy `{a == b}` path
742
+ /// equality, or the full expression grammar. Mixed literal and binding
743
+ /// text is only allowed in text content (interpolation), not in attribute
744
+ /// values.
745
+ pub fn parseAttrExpression(value: []const u8) ?Expression {
746
+ if (value.len == 0 or value[0] != '{') return .{ .literal = value };
747
+ if (value[value.len - 1] != '}') return null;
748
+ const inner = std.mem.trim(u8, value[1 .. value.len - 1], " ");
749
+ if (inner.len == 0) return null;
750
+ if (std.mem.indexOf(u8, inner, "==")) |eq| {
751
+ const left = std.mem.trim(u8, inner[0..eq], " ");
752
+ const right = std.mem.trim(u8, inner[eq + 2 ..], " ");
753
+ if (isBindingPath(left) and isBindingPath(right)) {
754
+ return .{ .equals = .{ .left = left, .right = right } };
755
+ }
756
+ }
757
+ if (isBindingPath(inner)) return .{ .binding = inner };
758
+ return .{ .expression = inner };
759
+ }
760
+
761
+ /// Structural check of an attribute expression, shared by the validator
762
+ /// (what `native markup check` runs, with no model in hand): syntax,
763
+ /// bounds, function names and arity, and the type discipline over the
764
+ /// parts whose types are already known (literals and operators). Binding
765
+ /// types are the engines' job. Returns the teaching message, or null when
766
+ /// the value is fine; `fallback` is the caller's message for values that
767
+ /// do not even classify (unterminated braces, empty `{}`).
768
+ pub fn attrExpressionError(value: []const u8, fallback: []const u8) ?[]const u8 {
769
+ const expression = parseAttrExpression(value) orelse return fallback;
770
+ if (expression != .expression) return null;
771
+ return expressionTextError(expression.expression);
772
+ }
773
+
774
+ /// The structural check for one expression's inner text (also used for
775
+ /// text-interpolation segments).
776
+ pub fn expressionTextError(inner: []const u8) ?[]const u8 {
777
+ var tree: expr.ExprTree = .{};
778
+ var diagnostic: expr.Diagnostic = .{};
779
+ if (!expr.parse(inner, &tree, &diagnostic)) return diagnostic.message;
780
+ const unknown: [expr.max_expression_nodes]?expr.ValueKind = @splat(null);
781
+ _ = expr.checkTypes(&tree, &unknown, &diagnostic) catch return diagnostic.message;
782
+ return null;
783
+ }
784
+
785
+ /// First uncovered codepoint inside an expression's STRING LITERALS: the
786
+ /// tofu guard for text an expression can inject into a rendered label
787
+ /// (`{plural(n, 'item', 'items')}`). Binding values stay the runtime
788
+ /// Debug warning's job, exactly like plain `{binding}` spans.
789
+ pub fn expressionStringCoverageError(inner: []const u8) bool {
790
+ var tree: expr.ExprTree = .{};
791
+ var diagnostic: expr.Diagnostic = .{};
792
+ if (!expr.parse(inner, &tree, &diagnostic)) return false;
793
+ for (tree.nodes[0..tree.len]) |node| {
794
+ if (node.kind != .literal_string) continue;
795
+ if (firstUncoveredCodepoint(node.text) != null) return true;
796
+ }
797
+ return false;
798
+ }
799
+
800
+ pub const MessageExpression = struct {
801
+ tag: []const u8,
802
+ /// Binding path for the payload, empty when the message carries none.
803
+ payload: []const u8 = "",
804
+ };
805
+
806
+ /// Parse an `on-*` attribute value: `msg` or `msg:{path}`.
807
+ pub fn parseMessageExpression(value: []const u8) ?MessageExpression {
808
+ if (std.mem.indexOfScalar(u8, value, ':')) |colon| {
809
+ const tag = value[0..colon];
810
+ const payload = value[colon + 1 ..];
811
+ if (!isBindingPath(tag)) return null;
812
+ if (payload.len < 3 or payload[0] != '{' or payload[payload.len - 1] != '}') return null;
813
+ const path = payload[1 .. payload.len - 1];
814
+ if (!isBindingPath(path)) return null;
815
+ return .{ .tag = tag, .payload = path };
816
+ }
817
+ if (!isBindingPath(value)) return null;
818
+ return .{ .tag = value };
819
+ }
820
+
821
+ pub const isBindingPath = expr.isBindingPath;
822
+
823
+ // --------------------------------------------------- typed document pass
824
+ //
825
+ // The canonical form of an attribute value or interpolated text run: raw
826
+ // strings classified and parsed ONCE, at document level, instead of at
827
+ // every use by every engine on every frame. `canonicalize` (runtime) and
828
+ // `canonicalizeComptime` (the compiled engine's path) stamp these onto a
829
+ // parsed/resolved document; `attrTyped` is the accessor every consumer
830
+ // reads, with an on-the-fly classification fallback for documents the
831
+ // pass has not touched — canonicalization can only change cost, never
832
+ // meaning, which is what keeps the two engines' parity suites authoritative
833
+ // over this pass.
834
+
835
+ /// A full `{expression}`: the inner text plus its tree, parsed once. The
836
+ /// tree is null when the text does not parse — the engines re-run the
837
+ /// parser at the use site to surface the exact teaching diagnostic, so a
838
+ /// broken expression fails identically with or without canonicalization.
839
+ pub const TypedExprRef = struct {
840
+ inner: []const u8,
841
+ tree: ?*const expr.ExprTree = null,
842
+ };
843
+
844
+ pub const TypedAttrValue = union(enum) {
845
+ literal: []const u8,
846
+ binding: []const u8,
847
+ equals: struct { left: []const u8, right: []const u8 },
848
+ expression: TypedExprRef,
849
+ /// `on-*` attributes: the message tag plus optional payload path.
850
+ message: MessageExpression,
851
+ /// The value did not classify (unterminated braces, empty `{}`, a
852
+ /// malformed message expression); the engines surface their
853
+ /// context-specific teaching message at the use site.
854
+ invalid,
855
+ };
856
+
857
+ /// One segment of an interpolating text run.
858
+ pub const TypedTextSegment = union(enum) {
859
+ literal: []const u8,
860
+ binding: []const u8,
861
+ expression: TypedExprRef,
862
+ /// An unterminated `{`: preserved so the engines report the same
863
+ /// "unterminated interpolation" error they always did.
864
+ unterminated,
865
+ };
866
+
867
+ /// Classify one attribute value into its typed form (no expression-tree
868
+ /// parse; trees are the canonicalization passes' job). The attribute NAME
869
+ /// picks the grammar: `on-*` values are message expressions, everything
870
+ /// else is the attr-expression grammar — exactly the split both engines
871
+ /// already applied per use.
872
+ pub fn classifyAttrValue(name: []const u8, value: []const u8) TypedAttrValue {
873
+ if (std.mem.startsWith(u8, name, "on-")) {
874
+ const message = parseMessageExpression(value) orelse return .invalid;
875
+ return .{ .message = message };
876
+ }
877
+ const expression = parseAttrExpression(value) orelse return .invalid;
878
+ return switch (expression) {
879
+ .literal => |text| .{ .literal = text },
880
+ .binding => |path| .{ .binding = path },
881
+ .equals => |sides| .{ .equals = .{ .left = sides.left, .right = sides.right } },
882
+ .expression => |inner| .{ .expression = .{ .inner = inner } },
883
+ };
884
+ }
885
+
886
+ /// The typed value of an attribute: the canonicalized form when present,
887
+ /// else an on-the-fly classification with identical semantics (minus the
888
+ /// pre-parsed tree).
889
+ pub fn attrTyped(attribute: MarkupAttr) TypedAttrValue {
890
+ if (attribute.typed) |typed| return typed.*;
891
+ return classifyAttrValue(attribute.name, attribute.value);
892
+ }
893
+
894
+ /// Canonicalize a parsed (and, for imports, resolved) document: every
895
+ /// attribute value and interpolating text run parses once into its typed
896
+ /// form. Nodes are copied; the input document stays valid.
897
+ pub fn canonicalize(arena: std.mem.Allocator, document: MarkupDocument) error{OutOfMemory}!MarkupDocument {
898
+ var out = document;
899
+ if (document.templates.len > 0) {
900
+ const templates = try arena.alloc(MarkupNode, document.templates.len);
901
+ for (document.templates, 0..) |template_node, index| {
902
+ templates[index] = try canonicalizeNode(arena, template_node);
903
+ }
904
+ out.templates = templates;
905
+ }
906
+ if (document.root) |root| {
907
+ out.root = try canonicalizeNode(arena, root);
908
+ }
909
+ return out;
910
+ }
911
+
912
+ fn canonicalizeNode(arena: std.mem.Allocator, node: MarkupNode) error{OutOfMemory}!MarkupNode {
913
+ var out = node;
914
+ if (node.attrs.len > 0) {
915
+ const attrs = try arena.alloc(MarkupAttr, node.attrs.len);
916
+ for (node.attrs, 0..) |attribute, index| {
917
+ attrs[index] = attribute;
918
+ const slot = try arena.create(TypedAttrValue);
919
+ slot.* = typedValueOf(arena, attribute) catch |err| switch (err) {
920
+ error.OutOfMemory => return error.OutOfMemory,
921
+ };
922
+ attrs[index].typed = slot;
923
+ }
924
+ out.attrs = attrs;
925
+ }
926
+ if (node.kind == .text and std.mem.indexOfScalar(u8, node.text, '{') != null) {
927
+ out.typed_text = try typedTextSegments(arena, node.text);
928
+ }
929
+ if (node.children.len > 0) {
930
+ const children = try arena.alloc(MarkupNode, node.children.len);
931
+ for (node.children, 0..) |child, index| {
932
+ children[index] = try canonicalizeNode(arena, child);
933
+ }
934
+ out.children = children;
935
+ }
936
+ return out;
937
+ }
938
+
939
+ fn typedValueOf(arena: std.mem.Allocator, attribute: MarkupAttr) error{OutOfMemory}!TypedAttrValue {
940
+ var typed = classifyAttrValue(attribute.name, attribute.value);
941
+ if (typed == .expression) {
942
+ typed.expression.tree = try parsedTree(arena, typed.expression.inner);
943
+ }
944
+ return typed;
945
+ }
946
+
947
+ /// Parse one expression's tree into the arena; null when it does not
948
+ /// parse (the engines re-derive the diagnostic at the use site).
949
+ fn parsedTree(arena: std.mem.Allocator, inner: []const u8) error{OutOfMemory}!?*const expr.ExprTree {
950
+ const tree = try arena.create(expr.ExprTree);
951
+ tree.* = .{};
952
+ var diagnostic: expr.Diagnostic = .{};
953
+ if (!expr.parse(inner, tree, &diagnostic)) return null;
954
+ return tree;
955
+ }
956
+
957
+ /// Split an interpolating text run into typed segments, mirroring the
958
+ /// engines' scan byte for byte: literal chunks between braces, `{path}`
959
+ /// bindings, full expressions, and the unterminated tail case.
960
+ fn typedTextSegments(arena: std.mem.Allocator, text: []const u8) error{OutOfMemory}![]const TypedTextSegment {
961
+ var segments: std.ArrayListUnmanaged(TypedTextSegment) = .empty;
962
+ var rest = text;
963
+ while (std.mem.indexOfScalar(u8, rest, '{')) |open| {
964
+ if (open > 0) try segments.append(arena, .{ .literal = rest[0..open] });
965
+ const close = std.mem.indexOfScalarPos(u8, rest, open, '}') orelse {
966
+ try segments.append(arena, .unterminated);
967
+ return segments.items;
968
+ };
969
+ const inner = std.mem.trim(u8, rest[open + 1 .. close], " ");
970
+ if (isBindingPath(inner)) {
971
+ try segments.append(arena, .{ .binding = inner });
972
+ } else {
973
+ try segments.append(arena, .{ .expression = .{ .inner = inner, .tree = try parsedTree(arena, inner) } });
974
+ }
975
+ rest = rest[close + 1 ..];
976
+ }
977
+ if (rest.len > 0) try segments.append(arena, .{ .literal = rest });
978
+ return segments.items;
979
+ }
980
+
981
+ /// Comptime mirror of `canonicalize` for the compiled engine's documents:
982
+ /// same classification, same segment scan, with comptime consts in place
983
+ /// of arena allocations. The branch quota scales with the tree it walks.
984
+ pub fn canonicalizeComptime(comptime document: MarkupDocument) MarkupDocument {
985
+ comptime {
986
+ @setEvalBranchQuota(comptime_parse_quota_base +
987
+ (documentByteSize(document) + 1) * comptime_canonicalize_quota_per_byte);
988
+ var out = document;
989
+ var templates: []const MarkupNode = &.{};
990
+ for (document.templates) |template_node| {
991
+ templates = templates ++ &[_]MarkupNode{canonicalizeNodeComptime(template_node)};
992
+ }
993
+ out.templates = templates;
994
+ if (document.root) |root| out.root = canonicalizeNodeComptime(root);
995
+ return out;
996
+ }
997
+ }
998
+
999
+ const comptime_canonicalize_quota_per_byte = 400;
1000
+
1001
+ fn documentByteSize(comptime document: MarkupDocument) usize {
1002
+ comptime {
1003
+ var total: usize = 0;
1004
+ for (document.templates) |template_node| total += nodeByteSize(template_node);
1005
+ if (document.root) |root| total += nodeByteSize(root);
1006
+ return total;
1007
+ }
1008
+ }
1009
+
1010
+ fn nodeByteSize(comptime node: MarkupNode) usize {
1011
+ comptime {
1012
+ var total: usize = node.text.len + node.name.len;
1013
+ for (node.attrs) |attribute| total += attribute.name.len + attribute.value.len;
1014
+ for (node.children) |child| total += nodeByteSize(child);
1015
+ return total;
1016
+ }
1017
+ }
1018
+
1019
+ fn canonicalizeNodeComptime(comptime node: MarkupNode) MarkupNode {
1020
+ comptime {
1021
+ var out = node;
1022
+ if (node.attrs.len > 0) {
1023
+ var attrs: []const MarkupAttr = &.{};
1024
+ for (node.attrs) |attribute| {
1025
+ var stamped = attribute;
1026
+ const frozen: TypedAttrValue = typedValueComptime(attribute);
1027
+ stamped.typed = &frozen;
1028
+ attrs = attrs ++ &[_]MarkupAttr{stamped};
1029
+ }
1030
+ out.attrs = attrs;
1031
+ }
1032
+ if (node.kind == .text and std.mem.indexOfScalar(u8, node.text, '{') != null) {
1033
+ out.typed_text = typedTextSegmentsComptime(node.text);
1034
+ }
1035
+ if (node.children.len > 0) {
1036
+ var children: []const MarkupNode = &.{};
1037
+ for (node.children) |child| {
1038
+ children = children ++ &[_]MarkupNode{canonicalizeNodeComptime(child)};
1039
+ }
1040
+ out.children = children;
1041
+ }
1042
+ return out;
1043
+ }
1044
+ }
1045
+
1046
+ fn typedValueComptime(comptime attribute: MarkupAttr) TypedAttrValue {
1047
+ comptime {
1048
+ var typed = classifyAttrValue(attribute.name, attribute.value);
1049
+ if (typed == .expression) {
1050
+ typed.expression.tree = parsedTreeComptime(typed.expression.inner);
1051
+ }
1052
+ return typed;
1053
+ }
1054
+ }
1055
+
1056
+ fn parsedTreeComptime(comptime inner: []const u8) ?*const expr.ExprTree {
1057
+ comptime {
1058
+ var tree: expr.ExprTree = .{};
1059
+ var diagnostic: expr.Diagnostic = .{};
1060
+ if (!expr.parse(inner, &tree, &diagnostic)) return null;
1061
+ const frozen = tree;
1062
+ return &frozen;
1063
+ }
1064
+ }
1065
+
1066
+ fn typedTextSegmentsComptime(comptime text: []const u8) []const TypedTextSegment {
1067
+ comptime {
1068
+ var segments: []const TypedTextSegment = &.{};
1069
+ var rest = text;
1070
+ while (std.mem.indexOfScalar(u8, rest, '{')) |open| {
1071
+ if (open > 0) segments = segments ++ &[_]TypedTextSegment{.{ .literal = rest[0..open] }};
1072
+ const close = std.mem.indexOfScalarPos(u8, rest, open, '}') orelse {
1073
+ return segments ++ &[_]TypedTextSegment{.unterminated};
1074
+ };
1075
+ const inner = std.mem.trim(u8, rest[open + 1 .. close], " ");
1076
+ if (isBindingPath(inner)) {
1077
+ segments = segments ++ &[_]TypedTextSegment{.{ .binding = inner }};
1078
+ } else {
1079
+ segments = segments ++ &[_]TypedTextSegment{.{ .expression = .{ .inner = inner, .tree = parsedTreeComptime(inner) } }};
1080
+ }
1081
+ rest = rest[close + 1 ..];
1082
+ }
1083
+ if (rest.len > 0) segments = segments ++ &[_]TypedTextSegment{.{ .literal = rest }};
1084
+ return segments;
1085
+ }
1086
+ }
1087
+
1088
+ // ------------------------------------------------------------ validation
1089
+
1090
+ /// Element names the interpreter accepts, derived from the registry
1091
+ /// (ui_schema.zig; the registry↔engine conformance tests live in
1092
+ /// ui_markup_view_tests.zig). Covers every built-in component whose shape
1093
+ /// fits the closed grammar; the deliberate exclusions (image,
1094
+ /// icon-button, data-grid, popover, menu-surface, segmented-control) are
1095
+ /// documented next to the widget-kind coverage test in
1096
+ /// ui_markup_view_tests.zig — write those as Zig view functions.
1097
+ pub const known_element_names = schema.element_names;
1098
+
1099
+ /// Elements whose content is a single run of text (with `{}`
1100
+ /// interpolation) and that take no element children. Registry-derived;
1101
+ /// held equal to the interpreter's `elementTakesText` by a conformance
1102
+ /// test in ui_markup_view_tests.zig.
1103
+ pub const known_text_leaf_element_names = schema.text_leaf_element_names;
1104
+
1105
+ /// Text-taking elements that ALSO accept element children in place of the
1106
+ /// text run (the list-row composite: children flow inside the element's
1107
+ /// own chrome). Registry-derived; held equal to the interpreter's
1108
+ /// `elementTakesChildren` by a conformance test in
1109
+ /// ui_markup_view_tests.zig.
1110
+ pub const known_text_or_children_element_names = schema.text_or_children_element_names;
1111
+
1112
+ /// The generic option attributes (registry-derived; the order is the
1113
+ /// did-you-mean/completion display order).
1114
+ pub const known_option_attrs = schema.option_attr_names;
1115
+
1116
+ /// The event vocabulary (registry-derived; markup spells these `on-*`).
1117
+ pub const known_events = schema.event_names;
1118
+
1119
+ pub const on_scroll_element_message = "on-scroll is only supported on scroll - the runtime emits scroll offsets for scroll containers, so the handler belongs on the scroll element itself";
1120
+ pub const on_reach_end_element_message = "on-reach-end is only supported on scroll - the runtime emits the approach-end signal for scroll containers, so the handler belongs on the scroll element itself";
1121
+ pub const on_scroll_payload_message = "on-scroll takes a bare Msg tag whose payload is the post-scroll state (a canvas.ScrollState variant, like activity_scrolled: canvas.ScrollState)";
1122
+
1123
+ pub const on_resize_element_message = "on-resize is only supported on split - the runtime emits fraction changes for split dividers, so the handler belongs on the split element itself";
1124
+ pub const on_resize_payload_message = "on-resize takes a bare Msg tag whose payload is the new first-pane fraction (an f32 variant, like sidebar_resized: f32)";
1125
+ pub const split_children_message = "split takes exactly two element children (the panes) - put conditional or repeated content inside a pane container, and nest splits for more panes";
1126
+
1127
+ /// Elements the runtime's dismissal machinery closes (Escape, click
1128
+ /// outside, automation/accessibility dismiss) — the markup subset of the
1129
+ /// engine's dismissible-surface kinds (`canvas.widgetKindDismissibleSurface`;
1130
+ /// popover/menu-surface/tooltip stay Zig views or leaves).
1131
+ /// Registry-derived from the `dismissible` element predicate.
1132
+ pub const known_dismiss_element_names = schema.dismiss_element_names;
1133
+
1134
+ pub const on_dismiss_element_message = "on-dismiss is only supported on dismissible surfaces (dialog, drawer, sheet, dropdown-menu) - Escape and click-outside dismiss those, and the Msg lets the model own the close (clear the open flag in update)";
1135
+
1136
+ /// Elements that may float as anchored surfaces. dropdown-menu is the
1137
+ /// markup channel; popover/menu-surface stay Zig views (documented
1138
+ /// exclusions) and dialogs/drawers/sheets place themselves.
1139
+ /// Registry-derived from the `anchorable` element predicate.
1140
+ pub const known_anchor_element_names = schema.anchor_element_names;
1141
+
1142
+ pub const anchor_element_message = "anchor is only supported on dropdown-menu - it floats the surface against its PARENT's frame (put the dropdown beside its trigger inside a stack); dialogs, drawers, and sheets place themselves";
1143
+ pub const anchor_value_message = "anchor takes a literal placement: below or above (either side flips automatically when the surface does not fit and the other side has more room)";
1144
+ pub const anchor_alignment_value_message = "anchor-alignment takes a literal alignment: start, end, or stretch (stretch also widens the surface to at least the anchor's width)";
1145
+ pub const anchor_offset_value_message = "anchor-offset takes a literal number: the gap in points between the anchor edge and the surface";
1146
+ pub const anchor_dependent_attr_message = "anchor-alignment and anchor-offset only apply together with anchor - add anchor=\"below\" (or \"above\") to float this surface";
1147
+
1148
+ /// Elements whose widget KIND the engine never hit-tests: layout and
1149
+ /// decoration only. A bound `on-press`/`on-toggle` makes any element a
1150
+ /// hit target (widget-level: the handler stamps the press/toggle action,
1151
+ /// and presses on non-interactive content inside it fall through to it),
1152
+ /// so those two are legal everywhere; the remaining value/text handlers
1153
+ /// (`on-change`/`on-submit`/`on-input`) have no behavior to bind to on
1154
+ /// these elements and stay validation errors. Registry-derived from the
1155
+ /// `hit_target` element predicate, which mirrors the engine's kind
1156
+ /// predicate (`canvas.widgetKindHitTarget` in widget_access.zig); a
1157
+ /// conformance test in ui_markup_view_tests.zig keeps the registry and
1158
+ /// that predicate in lockstep so drift is impossible.
1159
+ pub const known_non_hit_target_element_names = schema.non_hit_target_element_names;
1160
+
1161
+ /// The handlers that stay dead on layout/decoration elements: press and
1162
+ /// toggle make any element pressable, scroll has its own element-scoped
1163
+ /// rule (`on_scroll_element_message`), and the registry's
1164
+ /// `dead_on_non_hit_target` events bind control/text behavior the element
1165
+ /// does not have.
1166
+ pub fn deadHandlerOnNonHitTarget(attr_name: []const u8) bool {
1167
+ if (!std.mem.startsWith(u8, attr_name, "on-")) return false;
1168
+ const entry = schema.eventByName(attr_name[3..]) orelse return false;
1169
+ return entry.dead_on_non_hit_target;
1170
+ }
1171
+
1172
+ pub const autofocus_element_message = "autofocus is only supported on focusable controls (text fields, buttons, checkboxes, ...) - it moves keyboard focus to the element when it mounts or when the flag turns on, and nothing about this element can take focus";
1173
+
1174
+ pub const non_hit_target_handler_message = "on-change/on-submit/on-input never fire here: this element has no control or text behavior - put them on a control (input, checkbox, slider) inside it (on-press/on-toggle are fine anywhere: a bound press handler makes any element pressable, and clicks on plain text or icons inside it fall through to it)";
1175
+
1176
+ /// Elements whose widget kind layers its children on top of each other
1177
+ /// (every child gets the full content box), so `gap` can never space
1178
+ /// them. The validator rejects `gap` here instead of letting it silently
1179
+ /// do nothing. Registry-derived from the `stacks_children` element
1180
+ /// predicate, which mirrors the engine's stacking predicate
1181
+ /// (`canvas.widgetKindStacksChildren` in widget_layout.zig); a
1182
+ /// conformance test in ui_markup_view_tests.zig keeps the registry and
1183
+ /// that predicate in lockstep so drift is impossible. (`spacer` shares
1184
+ /// the stack widget kind; `scroll` and `accordion` stack children too but
1185
+ /// consume `gap`, so they are excluded there and here.)
1186
+ pub const known_stack_container_element_names = schema.stack_container_element_names;
1187
+
1188
+ pub const stack_container_gap_message = "gap does nothing here: this container layers its children on top of each other - wrap them in a column (or row) inside it for flow, or drop the gap";
1189
+
1190
+ pub const wrap_element_message = "wrap is only supported on text - only plain text leaves take a line policy (wrap=\"true\" word-wraps and reserves height; wrap=\"false\" and unset paint one honest line whose overflow follows the overflow attribute, trailing ellipsis by default); put wrap on the text leaf itself, or size the container so content fits (rows and columns never flow-wrap their children)";
1191
+
1192
+ pub const overflow_element_message = "overflow is only supported on text - it names a single-line text leaf's policy for content that does not fit (ellipsis elides behind a trailing \u{2026}, clip hard-cuts at the frame); put overflow on the text leaf itself, or size the container so content fits";
1193
+
1194
+ /// The `overflow` attribute's closed value vocabulary: the member names
1195
+ /// of `canvas.TextOverflow`, mirrored as data here (this layer stays
1196
+ /// std-only) with a lockstep test in ui_markup_view_tests.zig holding the
1197
+ /// mirror equal to the live enum.
1198
+ pub const overflow_value_names = [_][]const u8{ "ellipsis", "clip" };
1199
+
1200
+ pub const overflow_value_message = "unknown overflow value - text takes ellipsis (the default: elide overflow behind a trailing \u{2026}) or clip (hard-cut at the frame, for fixed-format content like a duration column); overflow-visible is not offered because painting past the frame is the bug class the layout audit exists to catch";
1201
+
1202
+ /// The `size` attribute's control-scale values (every sized element) and
1203
+ /// its typography rungs (text only). Registry-derived; lockstep tests in
1204
+ /// ui_markup_view_tests.zig hold the mirrors equal to `canvas.WidgetSize`.
1205
+ pub const known_control_size_value_names = schema.control_size_value_names;
1206
+ pub const known_text_size_value_names = schema.text_size_value_names;
1207
+
1208
+ pub const size_value_message = "unknown size value - controls take default, sm, lg, or icon, and text also takes heading or display (the typography rungs above title); numeric sizes are not accepted by design - retheme the typography tokens (TypographyTokenOverrides) to move the whole scale";
1209
+
1210
+ pub const text_size_element_message = "heading and display are typography rungs only text takes - they name themable typography token steps (heading_size, display_size), a different axis from the control scale; put the size on the text element itself, or use the control scale here (default, sm, lg, icon)";
1211
+
1212
+ pub const grid_columns_element_message = "columns is only supported on grid - it fixes the grid's column count (omit it for the derived near-square grid)";
1213
+
1214
+ pub const overscroll_element_message = "overscroll is only supported on scroll - it names a scroll region's edge behavior (none pins at the content edges, rubber_band lets the region bounce past them, default follows the ScrollPhysics.overscroll token); anywhere else it would be silently inert";
1215
+
1216
+ /// The `overscroll` attribute's closed value vocabulary: the member names
1217
+ /// of `canvas.WidgetOverscroll`, mirrored as data here (this layer stays
1218
+ /// std-only) with a lockstep test in ui_markup_view_tests.zig holding the
1219
+ /// mirror equal to the live enum.
1220
+ pub const overscroll_value_names = [_][]const u8{ "default", "none", "rubber_band" };
1221
+
1222
+ pub const overscroll_value_message = "unknown overscroll value - scroll takes default (follow the ScrollPhysics.overscroll token, off unless a theme flips it), none (pin at the content edges), or rubber_band (bounce past them)";
1223
+
1224
+ pub const resize_duration_element_message = "resize-duration is only supported on split - it declares the split's layout tween (milliseconds; 0 snaps, the default): a rebuild that moves the bound value eases the rendered fraction there instead of snapping; anywhere else it would be silently inert";
1225
+
1226
+ pub const resize_easing_element_message = "resize-easing is only supported on split - it names the easing curve of the split's layout tween (linear, standard, emphasized, spring); anywhere else it would be silently inert";
1227
+
1228
+ /// The `resize-easing` attribute's closed value vocabulary: the member
1229
+ /// names of `canvas.Easing`, mirrored as data here (this layer stays
1230
+ /// std-only) with a lockstep test in ui_markup_view_tests.zig holding the
1231
+ /// mirror equal to the live enum.
1232
+ pub const resize_easing_value_names = [_][]const u8{ "linear", "standard", "emphasized", "spring" };
1233
+
1234
+ pub const resize_easing_value_message = "unknown resize-easing value - split takes linear, standard (the default), emphasized, or spring";
1235
+
1236
+ pub const resize_easing_dependent_attr_message = "resize-easing needs a nonzero resize-duration on the same split - without a duration the split snaps and the easing is silently inert";
1237
+
1238
+ pub const resize_origin_element_message = "resize-origin is only supported on split - it names the fraction a freshly mounted split's pane boundary slides in from (its children keep the declared value's pose); anywhere else it would be silently inert";
1239
+
1240
+ pub const resize_origin_dependent_attr_message = "resize-origin needs a nonzero resize-duration on the same split - without a duration a mount lands on its value and the origin is silently inert";
1241
+
1242
+ pub const avatar_image_message = "image takes one {binding} to a u64 ImageId the app registered at runtime (fx.registerImageBytes) - runtime image ids are model data, not markup literals; 0 renders the initials fallback";
1243
+ pub const avatar_image_element_message = "image is only supported on avatar - the other image-bearing widgets (image, icon-button) stay Zig views (ui.image with ElementOptions.image)";
1244
+
1245
+ /// The built-in vector icon vocabulary behind `<icon name="..."/>`.
1246
+ /// Registry section mirroring `canvas.icons.known_icon_names` (the
1247
+ /// comptime-parsed registry; this layer stays std-only); a test in
1248
+ /// ui_markup_view_tests.zig keeps the two in lockstep so a new icon
1249
+ /// cannot ship without its markup name.
1250
+ pub const known_icon_names = schema.icon_names;
1251
+
1252
+ pub const icon_name_message = "name takes a built-in icon name (see canvas.icons.known_icon_names, e.g. search, plus, x, check, chevron-down, settings, trash), an app-registered app:<name> (canvas.icons.registerAppIcons), or one {binding} resolving to such a name";
1253
+ pub const icon_name_element_message = "name is only supported on icon - it selects a built-in vector icon";
1254
+ pub const icon_missing_name_message = "icon requires a name attribute selecting a built-in vector icon (e.g. <icon name=\"search\"/>)";
1255
+ pub const icon_children_message = "icon is a leaf - it takes no children";
1256
+
1257
+ pub const button_icon_message = "icon takes a built-in icon name drawn inside the element (see canvas.icons.known_icon_names, e.g. save, plus, refresh-cw), an app-registered app:<name> (canvas.icons.registerAppIcons), or one {binding} resolving to such a name";
1258
+ pub const button_icon_element_message = "icon is only supported on button, toggle-button, list-item, menu-item, and badge - it draws a vector icon inside the element as one hit target; for a bare icon use <icon name=\"...\"/>";
1259
+
1260
+ /// The `app:` icon namespace: the markup channel into the app's OWN
1261
+ /// registered vector icons (`canvas.icons.registerAppIcons`). Bare names
1262
+ /// stay the closed built-in vocabulary the engines prove at build time;
1263
+ /// `app:` names are structurally accepted here (registration is a
1264
+ /// boot-time act no static pass can see) and verified against the
1265
+ /// registered set by `native check` through the model contract's
1266
+ /// `app_icons` list.
1267
+ pub const app_icon_prefix = "app:";
1268
+
1269
+ pub const app_icon_shape_message = "app: takes a registered icon name after the colon, spelled like a built-in (lowercase words joined by dashes, e.g. app:wave-pulse) - the name is the one the app passed to canvas.icons.registerAppIcons";
1270
+ pub const icon_namespace_message = "unknown icon namespace - app: is the only one (app:<name> draws an icon the app registered with canvas.icons.registerAppIcons); built-in names are bare (see canvas.icons.known_icon_names)";
1271
+
1272
+ /// One icon-valued attribute, structurally classified. Shared by the
1273
+ /// validator and BOTH engines (comptime-callable) so the accepted forms
1274
+ /// can never drift: a bare literal must be a built-in, an `app:` literal
1275
+ /// must be well-shaped (its registration is checked later, by `native
1276
+ /// check` against the contract and by the draw path's missing-icon
1277
+ /// fallback), and one `{binding}` defers the whole choice to model data.
1278
+ pub const IconValue = union(enum) {
1279
+ /// A validated built-in name (`canvas.icons.known_icon_names`).
1280
+ builtin: []const u8,
1281
+ /// The full `app:<name>` spelling, shape-checked; carried verbatim so
1282
+ /// draw-time resolution and diagnostics name exactly what the markup
1283
+ /// said.
1284
+ app: []const u8,
1285
+ /// The raw attribute value of a `{binding}` (or richer expression)
1286
+ /// producing the icon name at view build time.
1287
+ binding: []const u8,
1288
+ /// The teaching message for a value in none of those forms.
1289
+ invalid: []const u8,
1290
+ };
1291
+
1292
+ /// Classify an icon attribute value; `base_message` is the caller's
1293
+ /// teaching message for its own attribute (name vs icon), used for the
1294
+ /// generic failures (not a name at all, an unknown bare literal).
1295
+ pub fn iconValueOf(raw: []const u8, base_message: []const u8) IconValue {
1296
+ const expression = parseAttrExpression(raw) orelse return .{ .invalid = base_message };
1297
+ switch (expression) {
1298
+ .literal => |literal| {
1299
+ if (std.mem.startsWith(u8, literal, app_icon_prefix)) {
1300
+ const bare = literal[app_icon_prefix.len..];
1301
+ if (!wellShapedIconName(bare)) return .{ .invalid = app_icon_shape_message };
1302
+ return .{ .app = literal };
1303
+ }
1304
+ if (std.mem.indexOfScalar(u8, literal, ':') != null) {
1305
+ return .{ .invalid = icon_namespace_message };
1306
+ }
1307
+ if (!nameInList(literal, &known_icon_names)) return .{ .invalid = base_message };
1308
+ return .{ .builtin = literal };
1309
+ },
1310
+ .binding => return .{ .binding = raw },
1311
+ // Icon choice is one name: a literal or one binding. Computed
1312
+ // names (concatenation, conditionals) belong in the model, where
1313
+ // the contract can type them.
1314
+ .equals, .expression => return .{ .invalid = base_message },
1315
+ }
1316
+ }
1317
+
1318
+ /// The shape every icon name has (built-in and registered alike):
1319
+ /// lowercase words of letters and digits joined by single dashes.
1320
+ fn wellShapedIconName(name: []const u8) bool {
1321
+ if (name.len == 0) return false;
1322
+ if (name[0] == '-' or name[name.len - 1] == '-') return false;
1323
+ var previous_dash = false;
1324
+ for (name) |char| {
1325
+ const word_char = (char >= 'a' and char <= 'z') or (char >= '0' and char <= '9');
1326
+ if (word_char) {
1327
+ previous_dash = false;
1328
+ continue;
1329
+ }
1330
+ if (char != '-' or previous_dash) return false;
1331
+ previous_dash = true;
1332
+ }
1333
+ return true;
1334
+ }
1335
+
1336
+ /// Elements whose `icon` attribute draws an inline vector icon as part
1337
+ /// of the element's OWN rendering (one hit target, one tint following
1338
+ /// enabled/disabled state). Registry-derived from the `icon_attr` element
1339
+ /// predicate; mirrors the engine kinds that consume `Widget.icon`:
1340
+ /// buttons and toggle-buttons draw it before the label (tab strips are
1341
+ /// toggle-button children, so tabs get icons through this), list items
1342
+ /// and menu items draw it as a leading slot.
1343
+ pub const known_icon_attr_element_names = schema.icon_attr_element_names;
1344
+
1345
+ pub fn iconAttrElement(name: []const u8) bool {
1346
+ return nameInList(name, &known_icon_attr_element_names);
1347
+ }
1348
+
1349
+ pub fn anchorElement(name: []const u8) bool {
1350
+ return nameInList(name, &known_anchor_element_names);
1351
+ }
1352
+
1353
+ pub fn dismissEventElement(name: []const u8) bool {
1354
+ return nameInList(name, &known_dismiss_element_names);
1355
+ }
1356
+
1357
+ // ----------------------------------------------------------- a11y lint
1358
+ //
1359
+ // The accessible-name and role lint. Severity rubric (stated once, at the
1360
+ // registry's `A11yNameRule`): a finding is an ERROR when a screen reader
1361
+ // user is FULLY BLOCKED (an unnamed interactive control cannot be
1362
+ // operated blind; a role that cannot mean what it says lies to the
1363
+ // bridge), and a WARNING when the experience degrades but remains
1364
+ // navigable (an unnamed image, a label duplicating the text it shadows).
1365
+ // Which elements are controls/editables/images is registry data
1366
+ // (`schema.ElementInfo.a11y_name`); the judgment about name sources and
1367
+ // severities lives here. Both engines and the validator call the same
1368
+ // predicates, so the lint cannot drift between check time and build time.
1369
+
1370
+ pub const a11y_unlabeled_control_message = "this control has no accessible name - a screen reader announces an unnamed control that cannot be operated blind; give it visible text (element content or text=\"...\") or label=\"...\" naming the action (assistive tech and automation snapshots read the label)";
1371
+
1372
+ pub const a11y_icon_only_message = "icon-only control: the icon name is a drawing instruction, not a label - a screen reader announces an unnamed control; add label=\"...\" naming the action (e.g. <button icon=\"trash\" label=\"Delete\"/>)";
1373
+
1374
+ pub const a11y_unlabeled_editable_message = "this text control has no accessible name - a screen reader user cannot tell what to type; add label=\"...\" (or placeholder=\"...\", which the accessibility bridges announce as the fallback name)";
1375
+
1376
+ pub const a11y_unknown_role_message = "unknown role: role takes a canvas.WidgetRole name (button, link, tree, treeitem, list, listitem, tab, checkbox, ...)";
1377
+
1378
+ pub const a11y_container_role_message = "this role promises child structure (rows, items, cells) that this element can never hold - put the role on the container element around it, or drop it";
1379
+
1380
+ pub const a11y_unlabeled_image_message = "this image has no alt-equivalent label - a screen reader announces an unnamed image; add label=\"...\" describing it, or the explicit label=\"\" to mark it decorative";
1381
+
1382
+ pub const a11y_redundant_label_message = "this label duplicates the element's text content - the text is already the accessible name; drop the label so the two can never drift apart";
1383
+
1384
+ /// The accessible-name ERROR for an element node, or null when the
1385
+ /// element is named (or carries no name requirement). Name sources are
1386
+ /// nonblank literals or `{bindings}` (a binding that resolves empty at
1387
+ /// runtime is the tree-level audit's finding, not markup's). Shared by
1388
+ /// the validator and both engines; comptime-callable.
1389
+ pub fn a11yNameError(node: MarkupNode) ?[]const u8 {
1390
+ const entry = schema.elementByName(node.name) orelse return null;
1391
+ switch (entry.a11y_name) {
1392
+ .none, .image => return null,
1393
+ .control => {
1394
+ if (a11yNodeHasName(node)) return null;
1395
+ if (node.attr("icon") != null) return a11y_icon_only_message;
1396
+ return a11y_unlabeled_control_message;
1397
+ },
1398
+ .editable => {
1399
+ // On text-entry controls the `text` attribute is the live
1400
+ // VALUE, not a name (hearing the content does not say what
1401
+ // to type), so the name must be a label or a placeholder.
1402
+ // `select` is the one editable TEXT LEAF: its text channel
1403
+ // (content or `text=`) is the face it shows, so it counts.
1404
+ if (attrNonBlank(node, "label") or attrNonBlank(node, "placeholder")) return null;
1405
+ if (entry.takes_text and a11yNodeHasName(node)) return null;
1406
+ return a11y_unlabeled_editable_message;
1407
+ },
1408
+ }
1409
+ }
1410
+
1411
+ /// The role-misuse ERROR for an element node: an unknown literal role, or
1412
+ /// a container role on an element that provably cannot hold the children
1413
+ /// the role promises. Dynamic role values (`role="{binding}"`) resolve at
1414
+ /// runtime, where the engines still reject unknown names. Shared by the
1415
+ /// validator and both engines; comptime-callable.
1416
+ pub fn a11yRoleError(node: MarkupNode) ?[]const u8 {
1417
+ const entry = schema.elementByName(node.name) orelse return null;
1418
+ const value = node.attr("role") orelse return null;
1419
+ const expression = parseAttrExpression(value) orelse return null;
1420
+ if (expression != .literal) return null;
1421
+ const literal = expression.literal;
1422
+ if (!nameInList(literal, &schema.role_names)) return a11y_unknown_role_message;
1423
+ if (nameInList(literal, &schema.container_role_names) and !schema.elementHoldsChildren(entry)) {
1424
+ return a11y_container_role_message;
1425
+ }
1426
+ return null;
1427
+ }
1428
+
1429
+ /// Whether the node carries element content (elements or structure tags,
1430
+ /// as opposed to text runs) — the list-row composite discriminator.
1431
+ /// Shared by the validator and both engines; comptime-callable.
1432
+ /// A `context-menu` child is metadata, not content — it lowers onto the
1433
+ /// PARENT's declared menu items and never renders in the parent's flow —
1434
+ /// so it does not make an element "have children" here.
1435
+ pub fn nodeHasElementContent(node: MarkupNode) bool {
1436
+ for (node.children) |child| {
1437
+ if (child.kind != .text and !nodeIsContextMenu(child)) return true;
1438
+ }
1439
+ return false;
1440
+ }
1441
+
1442
+ /// A `<context-menu>` element child: consumed by its parent (lowered to
1443
+ /// the parent's declared context-menu items), skipped by every content
1444
+ /// rule and child build. Shared by the validator and both engines;
1445
+ /// comptime-callable.
1446
+ pub fn nodeIsContextMenu(node: MarkupNode) bool {
1447
+ return node.kind == .element and std.mem.eql(u8, node.name, "context-menu");
1448
+ }
1449
+
1450
+ /// A `<span>` element child: consumed by its parent `<text>` (lowered
1451
+ /// into the paragraph's flat span list, never built on its own). Shared
1452
+ /// by the validator and both engines; comptime-callable.
1453
+ pub fn nodeIsSpan(node: MarkupNode) bool {
1454
+ return node.kind == .element and std.mem.eql(u8, node.name, "span");
1455
+ }
1456
+
1457
+ /// A `<reactions>` element child: consumed by its parent `<bubble>`
1458
+ /// (its run lowers onto the bubble widget's chrome-text channel, never
1459
+ /// built on its own). Shared by the validator and both engines;
1460
+ /// comptime-callable.
1461
+ pub fn nodeIsReactions(node: MarkupNode) bool {
1462
+ return node.kind == .element and std.mem.eql(u8, node.name, "reactions");
1463
+ }
1464
+
1465
+ /// Whether a text element's content is a span paragraph (any inline
1466
+ /// `<span>` child): the discriminator both engines use to pick the
1467
+ /// paragraph lowering over the plain single-run path. Comptime-callable.
1468
+ pub fn nodeHasSpanChildren(node: MarkupNode) bool {
1469
+ for (node.children) |child| {
1470
+ if (nodeIsSpan(child)) return true;
1471
+ }
1472
+ return false;
1473
+ }
1474
+
1475
+ fn childrenIncludeSpan(children: []const MarkupNode) bool {
1476
+ for (children) |child| {
1477
+ if (nodeIsSpan(child)) return true;
1478
+ }
1479
+ return false;
1480
+ }
1481
+
1482
+ /// Whether the source bytes between two adjacent inline children contain
1483
+ /// whitespace (comments are transparent: their bytes never count), i.e.
1484
+ /// whether the author separated the runs. Comptime-callable; both
1485
+ /// parsers splice separators through this one predicate.
1486
+ fn gapHasInlineSpace(source: []const u8, start: usize, end: usize) bool {
1487
+ var index = start;
1488
+ while (index < @min(end, source.len)) {
1489
+ if (std.mem.startsWith(u8, source[index..], "<!--")) {
1490
+ const close = std.mem.indexOfPos(u8, source, index + 4, "-->") orelse return false;
1491
+ index = close + 3;
1492
+ continue;
1493
+ }
1494
+ switch (source[index]) {
1495
+ ' ', '\t', '\r', '\n' => return true,
1496
+ else => index += 1,
1497
+ }
1498
+ }
1499
+ return false;
1500
+ }
1501
+
1502
+ /// The single-space separator text node spliced between two inline
1503
+ /// children whose source gap held whitespace. Its span covers the gap
1504
+ /// (write-back anchors stay honest) and its position derives from the
1505
+ /// gap's first byte, keeping the span↔position conformance law.
1506
+ fn inlineSeparatorNode(source: []const u8, start: usize, end: usize) MarkupNode {
1507
+ const position = positionAt(source, start);
1508
+ return .{
1509
+ .kind = .text,
1510
+ .text = " ",
1511
+ .line = position.line,
1512
+ .column = position.column,
1513
+ .span = .{ .start = start, .end = end },
1514
+ };
1515
+ }
1516
+
1517
+ /// Whether an element can HOST a context-menu: right-click resolution
1518
+ /// walks the hit route, so the host must be a hit target — or carry a
1519
+ /// bound on-press/on-hold, which makes any element pressable. Shared by
1520
+ /// the validator and both engines; comptime-callable.
1521
+ pub fn contextMenuHostEligible(node: MarkupNode) bool {
1522
+ if (!nameInList(node.name, &known_non_hit_target_element_names)) return true;
1523
+ return node.attr("on-press") != null or node.attr("on-hold") != null;
1524
+ }
1525
+
1526
+ fn a11yNodeHasName(node: MarkupNode) bool {
1527
+ if (attrNonBlank(node, "label")) return true;
1528
+ if (attrNonBlank(node, "text")) return true;
1529
+ return nodeTextContentNonBlank(node);
1530
+ }
1531
+
1532
+ fn nodeTextContentNonBlank(node: MarkupNode) bool {
1533
+ for (node.children) |child| {
1534
+ if (child.kind == .text and !allBlank(child.text)) return true;
1535
+ }
1536
+ return false;
1537
+ }
1538
+
1539
+ fn attrNonBlank(node: MarkupNode, name: []const u8) bool {
1540
+ const value = node.attr(name) orelse return false;
1541
+ return !allBlank(value);
1542
+ }
1543
+
1544
+ fn allBlank(text: []const u8) bool {
1545
+ for (text) |byte| {
1546
+ switch (byte) {
1547
+ ' ', '\t', '\r', '\n' => {},
1548
+ else => return false,
1549
+ }
1550
+ }
1551
+ return true;
1552
+ }
1553
+
1554
+ /// Findings reported per warnings pass; a document with more distinct
1555
+ /// a11y warnings than this is already unreviewable, so the collector
1556
+ /// keeps the first ones and the count stays honest via the slice length.
1557
+ pub const max_a11y_warnings = 64;
1558
+
1559
+ /// The a11y WARNINGS for a document (see the severity rubric above):
1560
+ /// unnamed images and redundant labels. Callers that surface warnings
1561
+ /// (`native markup check`, the LSP) run this after `validate` is green;
1562
+ /// the engines stay silent about warnings because they have no channel
1563
+ /// that is not a build failure.
1564
+ pub fn collectA11yWarnings(document: MarkupDocument, storage: []MarkupErrorInfo) []const MarkupErrorInfo {
1565
+ var len: usize = 0;
1566
+ for (document.templates) |template_node| {
1567
+ collectNodeA11yWarnings(template_node, storage, &len);
1568
+ }
1569
+ if (document.root) |root| {
1570
+ collectNodeA11yWarnings(root, storage, &len);
1571
+ }
1572
+ return storage[0..len];
1573
+ }
1574
+
1575
+ fn collectNodeA11yWarnings(node: MarkupNode, storage: []MarkupErrorInfo, len: *usize) void {
1576
+ if (node.kind == .element) {
1577
+ if (a11yImageWarning(node)) |message| {
1578
+ appendWarning(storage, len, errorAt(node, message));
1579
+ }
1580
+ if (a11yRedundantLabel(node)) |attribute| {
1581
+ appendWarning(storage, len, attrError(node, attribute, a11y_redundant_label_message));
1582
+ }
1583
+ }
1584
+ for (node.children) |child| {
1585
+ collectNodeA11yWarnings(child, storage, len);
1586
+ }
1587
+ }
1588
+
1589
+ /// The a11y ERRORS for a document, all of them: the same findings
1590
+ /// `validate` fails on one at a time (unnamed controls, icon-only
1591
+ /// controls, unnamed text entry, and role misuse), collected per node so
1592
+ /// a checker can report every offender in one pass instead of one per
1593
+ /// re-run. Positions match `validate`'s emission exactly: the element
1594
+ /// for name errors, the role attribute for role errors.
1595
+ pub fn collectA11yErrors(document: MarkupDocument, storage: []MarkupErrorInfo) []const MarkupErrorInfo {
1596
+ var len: usize = 0;
1597
+ for (document.templates) |template_node| {
1598
+ collectNodeA11yErrors(template_node, storage, &len);
1599
+ }
1600
+ if (document.root) |root| {
1601
+ collectNodeA11yErrors(root, storage, &len);
1602
+ }
1603
+ return storage[0..len];
1604
+ }
1605
+
1606
+ fn collectNodeA11yErrors(node: MarkupNode, storage: []MarkupErrorInfo, len: *usize) void {
1607
+ if (node.kind == .element) {
1608
+ if (a11yNameError(node)) |message| {
1609
+ appendWarning(storage, len, errorAt(node, message));
1610
+ }
1611
+ if (a11yRoleError(node)) |message| {
1612
+ appendWarning(storage, len, attrError(node, node.attrEntry("role").?, message));
1613
+ }
1614
+ }
1615
+ for (node.children) |child| {
1616
+ collectNodeA11yErrors(child, storage, len);
1617
+ }
1618
+ }
1619
+
1620
+ fn appendWarning(storage: []MarkupErrorInfo, len: *usize, info: MarkupErrorInfo) void {
1621
+ if (len.* >= storage.len) return;
1622
+ storage[len.*] = info;
1623
+ len.* += 1;
1624
+ }
1625
+
1626
+ fn a11yImageWarning(node: MarkupNode) ?[]const u8 {
1627
+ const entry = schema.elementByName(node.name) orelse return null;
1628
+ if (entry.a11y_name != .image) return null;
1629
+ // An explicit label attribute — even the empty decorative marker —
1630
+ // is a declaration; only its ABSENCE is the unnamed-image warning.
1631
+ if (node.attrEntry("label") != null) return null;
1632
+ if (a11yNodeHasName(node)) return null;
1633
+ return a11y_unlabeled_image_message;
1634
+ }
1635
+
1636
+ /// The `label` attribute when its literal value duplicates the element's
1637
+ /// literal name from content or `text` (dynamic values never compare).
1638
+ fn a11yRedundantLabel(node: MarkupNode) ?MarkupAttr {
1639
+ const attribute = node.attrEntry("label") orelse return null;
1640
+ const label = trimBlank(attribute.value);
1641
+ if (label.len == 0) return null;
1642
+ if (std.mem.indexOfScalar(u8, label, '{') != null) return null;
1643
+ if (node.attr("text")) |text| {
1644
+ if (std.mem.eql(u8, label, trimBlank(text))) return attribute;
1645
+ }
1646
+ for (node.children) |child| {
1647
+ if (child.kind != .text) continue;
1648
+ if (std.mem.indexOfScalar(u8, child.text, '{') != null) continue;
1649
+ if (std.mem.eql(u8, label, trimBlank(child.text))) return attribute;
1650
+ }
1651
+ return null;
1652
+ }
1653
+
1654
+ fn trimBlank(text: []const u8) []const u8 {
1655
+ return std.mem.trim(u8, text, " \t\r\n");
1656
+ }
1657
+
1658
+ pub const font_coverage_message = "this text contains a character outside the bundled font's coverage - it renders as a tofu box on the reference/screenshot and mobile paths; use a vector icon (<icon name=\"...\"/> or the icon attribute) or plain words";
1659
+
1660
+ pub const UncoveredCodepoint = struct {
1661
+ /// Byte offset of the codepoint within the scanned literal.
1662
+ offset: usize,
1663
+ /// The codepoint's bytes (a slice of the scanned literal).
1664
+ bytes: []const u8,
1665
+ codepoint: u21,
1666
+ };
1667
+
1668
+ /// First codepoint in a markup literal that the bundled face cannot
1669
+ /// render: the tofu guard's shared predicate. `{...}` binding
1670
+ /// spans are skipped — dynamic values are the runtime Debug warning's
1671
+ /// job — and control characters are layout, not glyphs. Invalid UTF-8
1672
+ /// reports as U+FFFD at the offending byte. Comptime-callable, so the
1673
+ /// compiled engine names the character in its compile error.
1674
+ pub fn firstUncoveredCodepoint(text: []const u8) ?UncoveredCodepoint {
1675
+ var index: usize = 0;
1676
+ while (index < text.len) {
1677
+ if (text[index] == '{') {
1678
+ const close = std.mem.indexOfScalarPos(u8, text, index + 1, '}') orelse text.len;
1679
+ index = @min(text.len, close + 1);
1680
+ continue;
1681
+ }
1682
+ const len = std.unicode.utf8ByteSequenceLength(text[index]) catch {
1683
+ return .{ .offset = index, .bytes = text[index .. index + 1], .codepoint = 0xFFFD };
1684
+ };
1685
+ if (index + len > text.len) {
1686
+ return .{ .offset = index, .bytes = text[index..], .codepoint = 0xFFFD };
1687
+ }
1688
+ const codepoint = std.unicode.utf8Decode(text[index .. index + len]) catch {
1689
+ return .{ .offset = index, .bytes = text[index .. index + len], .codepoint = 0xFFFD };
1690
+ };
1691
+ if (codepoint >= 0x20 and codepoint != 0x7F and !font_coverage.covers(codepoint)) {
1692
+ return .{ .offset = index, .bytes = text[index .. index + len], .codepoint = codepoint };
1693
+ }
1694
+ index += len;
1695
+ }
1696
+ return null;
1697
+ }
1698
+
1699
+ /// Markup attributes whose literal values are rendered as text (so the
1700
+ /// tofu guard applies): labels, placeholders, control text, and the
1701
+ /// timeline item's copy channels. Registry-derived from the
1702
+ /// `rendered_text` attribute flag.
1703
+ pub const known_text_attr_names = schema.rendered_text_attr_names;
1704
+
1705
+ fn textNodeCoverageError(node: MarkupNode) ?MarkupErrorInfo {
1706
+ const found = firstUncoveredCodepoint(node.text) orelse return null;
1707
+ var line = node.line;
1708
+ var column = node.column;
1709
+ for (node.text[0..found.offset]) |byte| {
1710
+ if (byte == '\n') {
1711
+ line += 1;
1712
+ column = 1;
1713
+ } else {
1714
+ column += 1;
1715
+ }
1716
+ }
1717
+ return .{ .line = line, .column = column, .message = font_coverage_message, .path = node.src_path };
1718
+ }
1719
+
1720
+ fn attrCoverageError(node: MarkupNode, attribute: MarkupAttr) ?MarkupErrorInfo {
1721
+ if (!nameInList(attribute.name, &known_text_attr_names)) return null;
1722
+ const expression = parseAttrExpression(attribute.value) orelse return null;
1723
+ switch (expression) {
1724
+ .literal => |literal| {
1725
+ if (firstUncoveredCodepoint(literal) == null) return null;
1726
+ return attrError(node, attribute, font_coverage_message);
1727
+ },
1728
+ // Expression string literals are markup-authored text too: they
1729
+ // can land in a rendered label, so they ride the same guard.
1730
+ .expression => |inner| {
1731
+ if (!expressionStringCoverageError(inner)) return null;
1732
+ return attrError(node, attribute, font_coverage_message);
1733
+ },
1734
+ else => return null,
1735
+ }
1736
+ }
1737
+
1738
+ /// Structural check of a text run's `{...}` interpolations: unterminated
1739
+ /// braces, and every non-path segment through the expression grammar
1740
+ /// (syntax, bounds, function names/arity, literal type discipline) plus
1741
+ /// the tofu guard over expression string literals. Positions point at the
1742
+ /// segment's opening brace.
1743
+ fn textInterpolationError(node: MarkupNode) ?MarkupErrorInfo {
1744
+ var rest = node.text;
1745
+ var consumed: usize = 0;
1746
+ while (std.mem.indexOfScalar(u8, rest, '{')) |open| {
1747
+ const close = std.mem.indexOfScalarPos(u8, rest, open, '}') orelse {
1748
+ return textErrorAtOffset(node, consumed + open, unterminated_interpolation_message);
1749
+ };
1750
+ const inner = std.mem.trim(u8, rest[open + 1 .. close], " ");
1751
+ if (!isBindingPath(inner)) {
1752
+ if (expressionTextError(inner)) |message| {
1753
+ return textErrorAtOffset(node, consumed + open, message);
1754
+ }
1755
+ if (expressionStringCoverageError(inner)) {
1756
+ return textErrorAtOffset(node, consumed + open, font_coverage_message);
1757
+ }
1758
+ }
1759
+ consumed += close + 1;
1760
+ rest = rest[close + 1 ..];
1761
+ }
1762
+ return null;
1763
+ }
1764
+
1765
+ /// An error positioned at a byte offset within a text run (mirrors the
1766
+ /// tofu guard's position walk).
1767
+ fn textErrorAtOffset(node: MarkupNode, offset: usize, message: []const u8) MarkupErrorInfo {
1768
+ var line = node.line;
1769
+ var column = node.column;
1770
+ for (node.text[0..offset]) |byte| {
1771
+ if (byte == '\n') {
1772
+ line += 1;
1773
+ column = 1;
1774
+ } else {
1775
+ column += 1;
1776
+ }
1777
+ }
1778
+ return .{ .line = line, .column = column, .message = message, .path = node.src_path };
1779
+ }
1780
+
1781
+ /// Markup attributes that reference a color design token by name. Values
1782
+ /// must be literal `ColorTokens` field names (`known_color_token_names`);
1783
+ /// the builder resolves them against live tokens in `finalizeWithTokens`.
1784
+ /// `border-color` (not bare `border`) keeps the name free for a future
1785
+ /// border-width shorthand. Registry-derived from the style-color group.
1786
+ pub const known_color_style_attrs = schema.color_style_attr_names;
1787
+
1788
+ /// The field names of `canvas.ColorTokens` (registry token section; kept
1789
+ /// in sync by a test in ui_markup_view_tests.zig — this module stays
1790
+ /// std-only).
1791
+ pub const known_color_token_names = schema.color_token_names;
1792
+
1793
+ /// The field names of `canvas.RadiusTokens` (same sync test).
1794
+ pub const known_radius_token_names = schema.radius_token_names;
1795
+
1796
+ pub const style_token_literal_message = "style token attributes take a literal token name - dynamic styling stays in Zig";
1797
+ pub const unknown_color_token_message = "unknown color token: color style attributes take a canvas ColorTokens field name (background, surface, surface_subtle, surface_pressed, text, text_muted, border, accent, accent_text, destructive, destructive_text, success, success_text, warning, warning_text, info, info_text, focus_ring, shadow, scrim, disabled)";
1798
+ pub const unknown_radius_token_message = "unknown radius token: radius takes a canvas RadiusTokens field name (sm, md, lg, xl)";
1799
+
1800
+ pub const for_children_message = "for takes one or more element children (elements, use, if/else, or a nested for) - text content is only allowed inside text-bearing elements";
1801
+ pub const else_placement_message = "else must directly follow an if (renders when the test is false) or a for (renders when the iterable is empty)";
1802
+
1803
+ pub const invalid_expression_message = "invalid expression: values are a literal or one {expression} - a binding path, arithmetic, comparisons, and/or/not, ++ concatenation, and the built-in formatting functions (stateful logic stays a model function)";
1804
+ pub const if_test_expression_message = "invalid expression: test takes one {expression} - a binding, a comparison, or boolean logic";
1805
+ pub const unterminated_interpolation_message = "unterminated interpolation";
1806
+ pub const arena_scalar_equality_message = "arena-computed bindings cannot be compared with == - compare the source fields directly, or bind a pub fn returning bool";
1807
+ pub const binding_text_buffer_message = "this binding names a TextBuffer field - the buffer is the edit model, not the text; bind a pub fn returning its text (pub fn draft(model: *const Model) []const u8 { return model.draft_buffer.text(); })";
1808
+ pub const markdown_source_message = "markdown requires a source attribute with one {binding} naming the markdown text (a []const u8 field or fn - arena fns work)";
1809
+ pub const markdown_children_message = "markdown takes no children or text content - the source binding provides the markdown";
1810
+ pub const markdown_attr_message = "unknown attribute for markdown - it takes source, on-link, on-details, details-expanded, and issue-link-base";
1811
+ pub const markdown_issue_link_base_message = "issue-link-base takes a literal URL prefix or one {binding} producing it - '#123' refs become links to base ++ number (like ghissue:// or https://github.com/owner/repo/issues/)";
1812
+ pub const markdown_on_link_message = "on-link takes a bare Msg tag whose payload is the pressed link URL (a []const u8 variant, like open_url: []const u8)";
1813
+ pub const markdown_on_details_message = "on-details takes a bare Msg tag whose payload is the details block index (a usize variant, like toggle_details: usize)";
1814
+ pub const markdown_details_expanded_message = "details-expanded takes one {binding} naming a []const bool iterable (a model field, pub decl, or fn - the same sources for each accepts)";
1815
+ pub const stepper_active_message = "stepper requires an active attribute (a number or one {binding}) naming the active step index";
1816
+ pub const stepper_attr_message = "unknown attribute for stepper - it takes active, key, global-key, and label";
1817
+ pub const stepper_children_message = "stepper takes only step children (each step is a text leaf: <step>Work</step>)";
1818
+ pub const step_parent_message = "step is only allowed inside a stepper";
1819
+ pub const step_attr_message = "step takes no attributes - its content is the label text";
1820
+ pub const timeline_attr_message = "unknown attribute for timeline - it takes gap, grow, key, global-key, and label";
1821
+ pub const timeline_item_parent_message = "timeline-item is only allowed inside a timeline (structure tags in between are fine)";
1822
+ pub const timeline_item_title_message = "timeline-item requires a title attribute (a literal or one {binding})";
1823
+ pub const timeline_item_attr_message = "unknown attribute for timeline-item - it takes title, description, meta, indicator, icon, variant, connector, selected, on-press, key, and global-key";
1824
+ pub const timeline_item_text_attr_message = "title, description, meta, and indicator expect text (a literal or one {binding})";
1825
+ pub const timeline_item_children_message = "timeline-item takes no children - the title, description, and meta attributes provide the content";
1826
+ pub const timeline_item_press_only_message = "timeline-item dispatches presses only - use on-press (other on-* events have no surface here)";
1827
+ pub const chart_attr_message = "unknown attribute for chart - it takes y-min, y-max, grid-lines, baseline, x-labels, y-labels, hover-details, stroke-width, width, height, grow, padding, key, global-key, and label";
1828
+ pub const chart_x_labels_message = "chart x-labels expects a {binding} naming a model iterable of strings (one category label per sample, oldest first)";
1829
+ pub const chart_children_message = "chart takes only series children - one <series values=\"{binding}\"/> per plotted series; the series set is static (vary the DATA through bindings), and dynamic series composition stays with the Zig builder (ui.chart)";
1830
+ pub const chart_series_required_message = "chart requires at least one series child (<series values=\"{history}\"/>)";
1831
+ pub const chart_display_only_message = "chart is display-only - presses fall through it like text, so on-* handlers have no surface here; put on-press on a container around it";
1832
+ pub const series_parent_message = "series is only allowed inside a chart";
1833
+ pub const series_attr_message = "unknown attribute for series - it takes kind, values, color, and label";
1834
+ pub const series_kind_message = "series kind takes a literal: line, area, or bar (area is a line filled to the baseline; band envelopes need a paired lower-edge slice per point and stay with the Zig builder, ui.chart)";
1835
+ pub const series_values_message = "series requires a values attribute with one {binding} naming a []const f32 iterable (a model field, pub decl, or fn - the same sources for each accepts); pad the window's leading gap with NaN samples, which draw nothing";
1836
+ pub const series_color_message = "series color takes a literal color token name (a canvas ColorTokens field, e.g. accent, info, success, text_muted)";
1837
+ pub const series_label_message = "series label expects text (a literal or one {binding}) - it names the series in the chart's semantics summary";
1838
+ pub const series_children_message = "series is a leaf - it takes no children; the values binding carries its data";
1839
+ pub const context_menu_parent_message = "context-menu must be a DIRECT child of the element whose right-click it answers - a conditional menu goes inside: wrap the menu-items in if/else, not the context-menu itself";
1840
+ pub const context_menu_host_message = "context-menu attaches to the element that takes the right-click, and this element is never a hit target - put the menu on the pressable element (list-item, button, panel, ...) or bind on-press on this one";
1841
+ pub const context_menu_single_message = "an element takes at most one context-menu - one right-click, one menu; swap its items with if/else INSIDE the menu";
1842
+ pub const context_menu_attrs_message = "context-menu takes no attributes - presentation belongs to the platform (the OS menu where the host has one, the anchored fallback surface elsewhere)";
1843
+ pub const context_menu_children_message = "context-menu takes menu-item and separator children (if/else/for around them are fine) - the items present through the platform's menu, so other elements cannot render there";
1844
+ pub const context_menu_empty_message = "context-menu requires at least one menu-item child";
1845
+ pub const context_menu_item_press_message = "every menu-item in a context-menu needs on-press - selecting the item dispatches that Msg, and an item without one is dead";
1846
+ pub const context_menu_item_attr_message = "unknown attribute for a context-menu menu-item - it takes on-press and disabled; the platform menu renders labels, separators, and enabled state only";
1847
+ pub const context_menu_item_label_message = "a context-menu menu-item's content is its label - give it one run of text";
1848
+ pub const context_menu_separator_message = "separator inside a context-menu is a bare divider - it takes no attributes or children";
1849
+ pub const input_group_attr_message = "unknown attribute for input-group - it takes label, width, height, min-width, grow, key, and global-key";
1850
+ pub const input_group_children_message = "input-group wraps exactly one textarea, then an optional input-group-actions row - other content lives outside the group";
1851
+ pub const input_group_textarea_message = "input-group requires a textarea child (the text entry the group wraps) before any input-group-actions";
1852
+ pub const input_group_actions_parent_message = "input-group-actions is only allowed inside an input-group, after its textarea";
1853
+ pub const input_group_actions_attr_message = "unknown attribute for input-group-actions - it takes gap, key, and global-key";
1854
+ pub const input_group_actions_children_message = "input-group-actions takes element children (buttons, spacers - if/else/for around them are fine) - text content is only allowed inside text-bearing elements";
1855
+ pub const text_leaf_children_message = "this element takes text content only - wrap element children in a container (row, column, stack)";
1856
+ pub const text_leaf_single_run_message = "text elements take a single run of text";
1857
+ pub const text_inline_children_message = "text takes one run of text and inline span children only - wrap other elements in a container (row, column, stack)";
1858
+ pub const span_parent_message = "span is only allowed inside text - it styles one run of the enclosing paragraph, so it needs a <text> parent";
1859
+ pub const span_text_only_message = "span is only supported inside text - the other text-bearing elements draw one single-style label; put the styled runs in a <text> paragraph composed next to this element";
1860
+ pub const span_attr_message = "unknown attribute for span - it takes weight (regular, medium, bold), mono, italic, scale, underline, and foreground; spans are visual runs, so events, keys, and layout stay on the enclosing text";
1861
+ pub const span_weight_value_message = "unknown weight value - span takes regular, medium (the semibold rung), or bold";
1862
+ pub const span_scale_value_message = "scale takes a positive number - the run draws at the paragraph's base size (the text element's size rung included) times this multiplier, so 1.5 reads half again as large; zero, negative, and non-finite multipliers have no rendering - drop the attribute to inherit the base size";
1863
+ pub const span_content_message = "span takes a single run of text (a literal, {bindings}, or both) - spans do not nest and hold no element children (the paragraph lowers to one flat run list)";
1864
+ pub const span_paragraph_wrap_message = "wrap and overflow do not apply to a span paragraph - inline spans always word-wrap and the paragraph reserves its wrapped height; drop the attribute (or the spans)";
1865
+
1866
+ /// The span `weight` attribute's closed value vocabulary: the member
1867
+ /// names of `canvas.TextSpanWeight`, mirrored as data here (this layer
1868
+ /// stays std-only) with a lockstep test in ui_markup_view_tests.zig
1869
+ /// holding the mirror equal to the live enum. `medium` is the semibold
1870
+ /// rung: the reserved medium sans face sits between regular and bold.
1871
+ pub const span_weight_value_names = [_][]const u8{ "regular", "medium", "bold" };
1872
+
1873
+ pub const reactions_parent_message = "reactions is only allowed inside bubble - it is the enclosing chat bubble's reaction pill (docked on the bubble's bottom edge), so it needs a <bubble> parent";
1874
+ pub const reactions_single_message = "a bubble takes at most one reactions child - it draws ONE pill; put every reaction in that pill's text run";
1875
+ pub const reactions_attr_message = "unknown attribute for reactions - it takes text-alignment only (start, center, or end; end is the default trailing dock); the pill is bubble chrome, so events, keys, and layout stay on the enclosing bubble";
1876
+ pub const reactions_alignment_value_message = "unknown text-alignment value for reactions - the pill docks at the bubble's start, center, or end (end is the default: the trailing dock reactions conventionally hang from); a literal name, so the dock is a static design choice";
1877
+ pub const reactions_content_message = "reactions takes a single run of text (a literal, {bindings}, or both) - it draws ONE pill and holds no element children";
1878
+ pub const bubble_text_attr_message = "text does nothing on bubble - the message is the bubble's children, and the reaction pill is declared with a <reactions> child (its run lands on the bubble's chrome-text channel); for an accessible name use label";
1879
+
1880
+ /// The reactions `text-alignment` vocabulary: where the pill docks along
1881
+ /// the bubble's bottom edge. The names are the `canvas.TextAlign`
1882
+ /// members on purpose — the pill is the bubble's chrome text, so its
1883
+ /// dock rides the existing text-alignment attribute (code 19) instead
1884
+ /// of minting a new one.
1885
+ pub const reactions_alignment_value_names = [_][]const u8{ "start", "center", "end" };
1886
+ pub const text_or_children_content_message = "this element takes either one run of text or element children - not both; move the text into a <text> child (and keep label= for the accessible name)";
1887
+ pub const table_row_parent_message = "table-row is only allowed inside a table (structure tags in between are fine)";
1888
+ pub const table_cell_parent_message = "table-cell is only allowed inside a table-row (structure tags in between are fine)";
1889
+ pub const template_top_level_message = "template definitions are only allowed at the top of the file, before the view root";
1890
+ pub const template_name_message = "template requires a name attribute";
1891
+ pub const template_unique_name_message = "template names must be unique";
1892
+ pub const template_args_message = "template args must be space-separated names, each optionally with a literal default (args=\"title cards trend=flat\")";
1893
+ pub const template_default_literal_message = "template arg defaults are literals only - a default cannot see any scope ({bindings} are rejected); pass the value at the use site instead";
1894
+ pub const template_default_quoted_message = "quotes are literal in template arg defaults - write args=\"name=fallback\" (bare name= declares an empty-string default)";
1895
+ pub const template_attrs_message = "template takes only name and args attributes";
1896
+ pub const template_one_child_message = "template takes exactly one element child (wrap siblings in a container)";
1897
+ pub const template_one_slot_message = "a template body takes at most one <slot/> (one unnamed slot; named slots are not supported yet)";
1898
+ pub const use_template_attr_message = "use requires a template attribute naming a template defined at the top of the file";
1899
+ pub const use_undefined_template_message = "use references an undefined template (define <template name=\"...\"> before the view root, or import the file that defines it)";
1900
+ pub const use_earlier_template_message = "use may only reference templates defined earlier in the file";
1901
+ pub const use_missing_arg_message = "use is missing an argument the template declares in args (only args declared with a default, like trend=flat, may be omitted)";
1902
+ pub const use_extra_arg_message = "use passes an argument the template does not declare in args";
1903
+ pub const use_children_without_slot_message = "this template has no <slot/> - use-site children need an insertion point; add <slot/> to the template body or remove the children";
1904
+ pub const slot_outside_template_message = "slot is only allowed inside a template body - it marks where use-site children are inserted";
1905
+ pub const slot_in_use_children_message = "a slot cannot sit inside use-site children - slot forwarding is not supported; each template body declares its own slot";
1906
+ pub const slot_attrs_message = "slot takes no attributes (one unnamed slot; named slots are not supported yet)";
1907
+ pub const slot_children_message = "slot is a leaf - it takes no children; the use site provides the content";
1908
+ pub const empty_document_message = "markup file is empty - define templates (a component file), a view root, or both";
1909
+ pub const component_file_view_message = "this file defines templates only (a component file) - a view needs a root element after the templates; import this file from a view instead";
1910
+ pub const import_top_level_message = "import is only allowed at the top of the file, before the template definitions and the view root";
1911
+ pub const import_src_message = "import requires a src attribute naming a .native file, relative to this file (subdirectories allowed)";
1912
+ pub const import_attrs_message = "import takes only a src attribute";
1913
+ pub const import_children_message = "import is a leaf - it takes no children";
1914
+ pub const import_src_extension_message = "import src must name a .native file";
1915
+ pub const import_src_absolute_message = "import src must be a relative path (resolved against the importing file) - absolute paths are rejected so markup stays portable";
1916
+ pub const import_src_separator_message = "import src uses forward slashes only";
1917
+ pub const import_src_escape_message = "import src escapes the markup root (the root view file's directory) - keep component files under it";
1918
+ pub const import_src_too_long_message = "import src is too long (over 200 bytes)";
1919
+ pub const import_view_root_message = "imported files define templates only - this file has a view root element; move the view to its own file and import just the templates";
1920
+ pub const import_depth_message = "imports nest too deeply (over 8 levels) - flatten the component hierarchy";
1921
+ pub const import_count_message = "too many imported files (over 32)";
1922
+ pub const import_unresolved_message = "this markup imports other files - resolve imports before building (the app runtime, native markup check, and CompiledMarkupImports all do; a bare MarkupView needs resolveImports first)";
1923
+ pub const max_templates_message = "too many templates (over 256 in one document, imports included) - split the view or drop generated definitions";
1924
+
1925
+ /// Bound on templates per document (also enforced across the resolved
1926
+ /// import closure), so a hostile file cannot drive the validator's
1927
+ /// quadratic duplicate-name scan or comptime expansion checks unbounded.
1928
+ pub const max_document_templates = 256;
1929
+
1930
+ /// Where a `<slot/>` node is legal at the current validation position.
1931
+ /// Template bodies allow one; use-site children forbid it (no slot
1932
+ /// forwarding); everywhere else it is outside any template.
1933
+ const SlotRule = enum { forbidden, template_body, use_children };
1934
+
1935
+ /// Model-agnostic structural validation: unknown elements or attributes,
1936
+ /// malformed expressions, misshapen structure tags, and template/use/slot
1937
+ /// wiring. Binding paths and message tags are checked against the concrete
1938
+ /// Model/Msg by the interpreter; this pass is what
1939
+ /// `native markup check` runs. On a document with UNRESOLVED imports
1940
+ /// (per-file checking) references to templates the imports may provide are
1941
+ /// not flagged; the resolved (merged) document gets the strict pass.
1942
+ pub fn validate(document: MarkupDocument) ?MarkupErrorInfo {
1943
+ for (document.imports) |import_node| {
1944
+ if (validateImport(import_node)) |info| return info;
1945
+ }
1946
+ for (document.templates, 0..) |template_node, index| {
1947
+ if (validateTemplate(document, template_node, index)) |info| return info;
1948
+ }
1949
+ const root = document.root orelse return null;
1950
+ return validateNode(document, root, null, document.templates.len, .forbidden);
1951
+ }
1952
+
1953
+ /// Shape-only import checks; existence, cycles, and duplicates are the
1954
+ /// resolver's job (it has the other files).
1955
+ fn validateImport(node: MarkupNode) ?MarkupErrorInfo {
1956
+ if (node.children.len > 0) return errorAt(node.children[0], import_children_message);
1957
+ var has_src = false;
1958
+ for (node.attrs) |attribute| {
1959
+ if (!std.mem.eql(u8, attribute.name, "src")) {
1960
+ return attrError(node, attribute, import_attrs_message);
1961
+ }
1962
+ has_src = true;
1963
+ if (importSrcShapeError(attribute.value)) |message| {
1964
+ return attrError(node, attribute, message);
1965
+ }
1966
+ }
1967
+ if (!has_src) return errorAt(node, import_src_message);
1968
+ return null;
1969
+ }
1970
+
1971
+ /// Path-shape rules a src must satisfy before resolution even starts.
1972
+ /// Escapes past the markup root need the importing file's directory and
1973
+ /// are checked during resolution.
1974
+ pub fn importSrcShapeError(src: []const u8) ?[]const u8 {
1975
+ if (src.len == 0) return import_src_message;
1976
+ if (src.len > max_import_path_len) return import_src_too_long_message;
1977
+ if (src[0] == '/') return import_src_absolute_message;
1978
+ if (std.mem.indexOfScalar(u8, src, ':') != null) return import_src_absolute_message;
1979
+ if (std.mem.indexOfScalar(u8, src, '\\') != null) return import_src_separator_message;
1980
+ if (!hasMarkupExtension(src)) return import_src_extension_message;
1981
+ return null;
1982
+ }
1983
+
1984
+ /// The Native markup file extension.
1985
+ pub const markup_extension = ".native";
1986
+
1987
+ /// True for the one markup extension.
1988
+ pub fn hasMarkupExtension(path: []const u8) bool {
1989
+ return std.mem.endsWith(u8, path, markup_extension);
1990
+ }
1991
+
1992
+ fn validateTemplate(document: MarkupDocument, node: MarkupNode, index: usize) ?MarkupErrorInfo {
1993
+ const name = node.attr("name") orelse return errorAt(node, template_name_message);
1994
+ if (!isTemplateName(name)) return errorAt(node, template_name_message);
1995
+ for (document.templates[0..index]) |earlier| {
1996
+ const earlier_name = earlier.attr("name") orelse continue;
1997
+ if (std.mem.eql(u8, earlier_name, name)) return errorAt(node, template_unique_name_message);
1998
+ }
1999
+ for (node.attrs) |attribute| {
2000
+ if (std.mem.eql(u8, attribute.name, "name")) continue;
2001
+ if (std.mem.eql(u8, attribute.name, "args")) {
2002
+ var args = templateArgs(node);
2003
+ while (args.next()) |token| {
2004
+ const arg = parseTemplateArg(token);
2005
+ if (!isBindingName(arg.name)) {
2006
+ return attrError(node, attribute, template_args_message);
2007
+ }
2008
+ if (arg.default) |default| {
2009
+ // Literals only: a default evaluates in no scope, so a
2010
+ // binding (or equality) there could never resolve.
2011
+ if (std.mem.indexOfScalar(u8, default, '{') != null) {
2012
+ return attrError(node, attribute, template_default_literal_message);
2013
+ }
2014
+ // Quotes are not string delimiters here - the default
2015
+ // is already text, so quote characters would render
2016
+ // verbatim in the expanded template.
2017
+ if (default.len > 0 and (default[0] == '\'' or default[0] == '"')) {
2018
+ return attrError(node, attribute, template_default_quoted_message);
2019
+ }
2020
+ }
2021
+ }
2022
+ continue;
2023
+ }
2024
+ return attrError(node, attribute, template_attrs_message);
2025
+ }
2026
+ if (node.children.len != 1 or node.children[0].kind != .element) {
2027
+ return errorAt(node, template_one_child_message);
2028
+ }
2029
+ if (templateSecondSlot(node.children[0])) |second| {
2030
+ return errorAt(second, template_one_slot_message);
2031
+ }
2032
+ // The body sees templates defined before this one, which also rules
2033
+ // out recursion. The body root has no known parent element, so
2034
+ // parent-scoped rules (table-row in table) are checked at use sites of
2035
+ // the surrounding markup, not here.
2036
+ return validateNode(document, node.children[0], null, index, .template_body);
2037
+ }
2038
+
2039
+ /// The second `<slot/>` in a template body, if any: the one-slot rule's
2040
+ /// witness, shared by the validator and both engines (comptime-callable).
2041
+ pub fn templateSecondSlot(body: MarkupNode) ?MarkupNode {
2042
+ var count: usize = 0;
2043
+ return secondSlot(body, &count);
2044
+ }
2045
+
2046
+ /// Slots inside use children are rejected by their own error instead.
2047
+ fn secondSlot(node: MarkupNode, count: *usize) ?MarkupNode {
2048
+ if (node.kind == .slot_block) {
2049
+ count.* += 1;
2050
+ if (count.* > 1) return node;
2051
+ return null;
2052
+ }
2053
+ if (node.kind == .use_block) return null;
2054
+ for (node.children) |child| {
2055
+ if (secondSlot(child, count)) |found| return found;
2056
+ }
2057
+ return null;
2058
+ }
2059
+
2060
+ fn validateUse(document: MarkupDocument, node: MarkupNode, template_limit: usize) ?MarkupErrorInfo {
2061
+ const name = node.attr("template") orelse return errorAt(node, use_template_attr_message);
2062
+ const index = document.templateIndex(name) orelse {
2063
+ // Unresolved imports may provide the template; the resolved pass
2064
+ // and the engines still catch a genuinely undefined name.
2065
+ if (document.imports.len > 0) return validateUseChildren(document, node, template_limit);
2066
+ return errorAt(node, use_undefined_template_message);
2067
+ };
2068
+ if (index >= template_limit) return errorAt(node, use_earlier_template_message);
2069
+ const template_node = document.templates[index];
2070
+ if (node.children.len != 0 and templateSlot(template_node) == null) {
2071
+ return errorAt(node.children[0], use_children_without_slot_message);
2072
+ }
2073
+ var args = templateArgs(template_node);
2074
+ while (args.next()) |token| {
2075
+ const arg = parseTemplateArg(token);
2076
+ if (node.attr(arg.name) == null and arg.default == null) {
2077
+ return errorAt(node, use_missing_arg_message);
2078
+ }
2079
+ }
2080
+ for (node.attrs) |attribute| {
2081
+ if (std.mem.eql(u8, attribute.name, "template")) continue;
2082
+ if (!templateDeclaresArg(template_node, attribute.name)) {
2083
+ return attrError(node, attribute, use_extra_arg_message);
2084
+ }
2085
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2086
+ return attrError(node, attribute, message);
2087
+ }
2088
+ }
2089
+ return validateUseChildren(document, node, template_limit);
2090
+ }
2091
+
2092
+ /// Use-site children (slot content) build in the consumer's scope, so they
2093
+ /// validate like the surrounding markup — except a literal `<slot/>` is
2094
+ /// rejected (no forwarding), which `.use_children` teaches. The insertion
2095
+ /// point's parent element is template-side and unknown here, so
2096
+ /// parent-scoped rules (table-row in table) are not checked.
2097
+ fn validateUseChildren(document: MarkupDocument, node: MarkupNode, template_limit: usize) ?MarkupErrorInfo {
2098
+ var previous_kind: ?MarkupNodeKind = null;
2099
+ for (node.children) |child| {
2100
+ if (child.kind == .else_block and previous_kind != .if_block and previous_kind != .for_block) {
2101
+ return errorAt(child, else_placement_message);
2102
+ }
2103
+ if (child.kind == .text) {
2104
+ return errorAt(child, "text content is only allowed inside text-bearing elements");
2105
+ }
2106
+ if (validateNode(document, child, null, template_limit, .use_children)) |info| return info;
2107
+ previous_kind = child.kind;
2108
+ }
2109
+ return null;
2110
+ }
2111
+
2112
+ /// `<markdown>` is a leaf whose content comes entirely from its `source`
2113
+ /// binding: no children, a closed attribute set, and bare message tags for
2114
+ /// `on-link`/`on-details` (the runtime supplies their payloads). Whether
2115
+ /// the bindings and tags exist on the concrete Model/Msg is the engines'
2116
+ /// check, exactly like ordinary bindings.
2117
+ fn validateMarkdown(node: MarkupNode) ?MarkupErrorInfo {
2118
+ for (node.children) |child| {
2119
+ return errorAt(child, markdown_children_message);
2120
+ }
2121
+ var has_source = false;
2122
+ for (node.attrs) |attribute| {
2123
+ if (std.mem.eql(u8, attribute.name, "source")) {
2124
+ has_source = true;
2125
+ const expression = parseAttrExpression(attribute.value);
2126
+ if (expression == null or expression.? != .binding) {
2127
+ return attrError(node, attribute, markdown_source_message);
2128
+ }
2129
+ continue;
2130
+ }
2131
+ if (std.mem.eql(u8, attribute.name, "on-link")) {
2132
+ const expression = parseMessageExpression(attribute.value);
2133
+ if (expression == null or expression.?.payload.len != 0) {
2134
+ return attrError(node, attribute, markdown_on_link_message);
2135
+ }
2136
+ continue;
2137
+ }
2138
+ if (std.mem.eql(u8, attribute.name, "on-details")) {
2139
+ const expression = parseMessageExpression(attribute.value);
2140
+ if (expression == null or expression.?.payload.len != 0) {
2141
+ return attrError(node, attribute, markdown_on_details_message);
2142
+ }
2143
+ continue;
2144
+ }
2145
+ if (std.mem.eql(u8, attribute.name, "details-expanded")) {
2146
+ const expression = parseAttrExpression(attribute.value);
2147
+ if (expression == null or expression.? != .binding) {
2148
+ return attrError(node, attribute, markdown_details_expanded_message);
2149
+ }
2150
+ continue;
2151
+ }
2152
+ if (std.mem.eql(u8, attribute.name, "issue-link-base")) {
2153
+ const expression = parseAttrExpression(attribute.value);
2154
+ if (expression == null or expression.? == .equals) {
2155
+ return attrError(node, attribute, markdown_issue_link_base_message);
2156
+ }
2157
+ continue;
2158
+ }
2159
+ return attrError(node, attribute, markdown_attr_message);
2160
+ }
2161
+ if (!has_source) return errorAt(node, markdown_source_message);
2162
+ return null;
2163
+ }
2164
+
2165
+ /// `<stepper active="{index}">` takes only `<step>` text-leaf children:
2166
+ /// each step's state (completed/active/pending) derives from its position
2167
+ /// against the active index, so steps carry no attributes of their own.
2168
+ fn validateStepper(node: MarkupNode) ?MarkupErrorInfo {
2169
+ var has_active = false;
2170
+ for (node.attrs) |attribute| {
2171
+ if (std.mem.eql(u8, attribute.name, "active")) {
2172
+ has_active = true;
2173
+ if (attrExpressionError(attribute.value, stepper_active_message)) |message| {
2174
+ return attrError(node, attribute, message);
2175
+ }
2176
+ continue;
2177
+ }
2178
+ if (std.mem.eql(u8, attribute.name, "key") or std.mem.eql(u8, attribute.name, "global-key") or std.mem.eql(u8, attribute.name, "label")) {
2179
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2180
+ return attrError(node, attribute, message);
2181
+ }
2182
+ continue;
2183
+ }
2184
+ return attrError(node, attribute, stepper_attr_message);
2185
+ }
2186
+ if (!has_active) return errorAt(node, stepper_active_message);
2187
+ for (node.children) |child| {
2188
+ if (child.kind != .element or !std.mem.eql(u8, child.name, "step")) {
2189
+ return errorAt(child, stepper_children_message);
2190
+ }
2191
+ for (child.attrs) |attribute| {
2192
+ return attrError(child, attribute, step_attr_message);
2193
+ }
2194
+ var text_runs: usize = 0;
2195
+ for (child.children) |run| {
2196
+ if (run.kind != .text) return errorAt(run, text_leaf_children_message);
2197
+ text_runs += 1;
2198
+ if (text_runs > 1) return errorAt(run, text_leaf_single_run_message);
2199
+ if (textInterpolationError(run)) |info| return info;
2200
+ if (textNodeCoverageError(run)) |info| return info;
2201
+ }
2202
+ }
2203
+ return null;
2204
+ }
2205
+
2206
+ /// `<timeline>` is a list container with a closed attribute set; its
2207
+ /// children (timeline-item elements, plus structure tags) validate
2208
+ /// through the ordinary pass so `for`/`if` work inside it.
2209
+ fn validateTimeline(document: MarkupDocument, node: MarkupNode, template_limit: usize, slot_rule: SlotRule) ?MarkupErrorInfo {
2210
+ for (node.attrs) |attribute| {
2211
+ const known = std.mem.eql(u8, attribute.name, "gap") or
2212
+ std.mem.eql(u8, attribute.name, "grow") or
2213
+ std.mem.eql(u8, attribute.name, "key") or
2214
+ std.mem.eql(u8, attribute.name, "global-key") or
2215
+ std.mem.eql(u8, attribute.name, "label");
2216
+ if (!known) {
2217
+ return attrError(node, attribute, timeline_attr_message);
2218
+ }
2219
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2220
+ return attrError(node, attribute, message);
2221
+ }
2222
+ }
2223
+ var previous_kind: ?MarkupNodeKind = null;
2224
+ for (node.children) |child| {
2225
+ if (child.kind == .else_block and previous_kind != .if_block and previous_kind != .for_block) {
2226
+ return errorAt(child, else_placement_message);
2227
+ }
2228
+ if (validateNode(document, child, "timeline", template_limit, slot_rule)) |info| return info;
2229
+ previous_kind = child.kind;
2230
+ }
2231
+ return null;
2232
+ }
2233
+
2234
+ /// `<timeline-item>` is a leaf: attributes carry the content (title,
2235
+ /// description, meta, indicator) and the one supported event is on-press.
2236
+ fn validateTimelineItem(node: MarkupNode) ?MarkupErrorInfo {
2237
+ for (node.children) |child| {
2238
+ return errorAt(child, timeline_item_children_message);
2239
+ }
2240
+ var has_title = false;
2241
+ for (node.attrs) |attribute| {
2242
+ if (std.mem.eql(u8, attribute.name, "title")) {
2243
+ has_title = true;
2244
+ if (attrExpressionError(attribute.value, timeline_item_title_message)) |message| {
2245
+ return attrError(node, attribute, message);
2246
+ }
2247
+ if (attrCoverageError(node, attribute)) |info| return info;
2248
+ continue;
2249
+ }
2250
+ if (std.mem.eql(u8, attribute.name, "on-press")) {
2251
+ if (parseMessageExpression(attribute.value) == null) {
2252
+ return attrError(node, attribute, "invalid message expression: on-* takes a Msg tag (\"add\") or tag with one binding payload (\"toggle:{item.id}\")");
2253
+ }
2254
+ continue;
2255
+ }
2256
+ if (std.mem.startsWith(u8, attribute.name, "on-")) {
2257
+ return attrError(node, attribute, timeline_item_press_only_message);
2258
+ }
2259
+ if (std.mem.eql(u8, attribute.name, "icon")) {
2260
+ // Vector icon indicator: the shared icon value grammar
2261
+ // (built-in literal, app:<name>, or one {binding}) — symbols
2262
+ // belong on the icon channel, not in text glyphs.
2263
+ switch (iconValueOf(attribute.value, button_icon_message)) {
2264
+ .invalid => |message| return attrError(node, attribute, message),
2265
+ else => {},
2266
+ }
2267
+ continue;
2268
+ }
2269
+ const known = std.mem.eql(u8, attribute.name, "description") or
2270
+ std.mem.eql(u8, attribute.name, "meta") or
2271
+ std.mem.eql(u8, attribute.name, "indicator") or
2272
+ std.mem.eql(u8, attribute.name, "variant") or
2273
+ std.mem.eql(u8, attribute.name, "connector") or
2274
+ std.mem.eql(u8, attribute.name, "selected") or
2275
+ std.mem.eql(u8, attribute.name, "key") or
2276
+ std.mem.eql(u8, attribute.name, "global-key");
2277
+ if (!known) {
2278
+ return attrError(node, attribute, timeline_item_attr_message);
2279
+ }
2280
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2281
+ return attrError(node, attribute, message);
2282
+ }
2283
+ if (attrCoverageError(node, attribute)) |info| return info;
2284
+ }
2285
+ if (!has_title) return errorAt(node, timeline_item_title_message);
2286
+ return null;
2287
+ }
2288
+
2289
+ /// The series kinds the markup `<chart>` accepts, in teaching order.
2290
+ /// `area` is the markup spelling of a filled line (`ChartSeries.fill` on a
2291
+ /// `.line` series — one blessed spelling, no separate fill flag); `band`
2292
+ /// needs a paired lower-edge slice per point and stays with the Zig
2293
+ /// builder (`ui.chart`). Shared by the validator and both engines.
2294
+ pub const chart_series_kind_names = [_][]const u8{ "line", "area", "bar" };
2295
+
2296
+ /// `<chart>` is the data-visualization composite: a closed attribute set
2297
+ /// mirroring `Ui.ChartOptions`, and only `<series>` children whose values
2298
+ /// bind model iterables of f32. The series SET is static — data varies
2299
+ /// through bindings — so structure tags inside a chart are a teaching
2300
+ /// error naming the Zig builder as the home for dynamic composition.
2301
+ /// One `<context-menu>` on its host element: attribute-less, holding
2302
+ /// menu-item and separator children (structure tags around them are
2303
+ /// transparent, so a menu can swap or repeat items). The host's
2304
+ /// eligibility (hit target or bound press) is checked at the host, where
2305
+ /// the parent node is in hand. Pub and comptime-callable: the validator
2306
+ /// and BOTH engines run this one shape check, so the closed item
2307
+ /// vocabulary is stated once.
2308
+ pub fn contextMenuShapeError(node: MarkupNode) ?MarkupErrorInfo {
2309
+ for (node.attrs) |attribute| {
2310
+ return attrError(node, attribute, context_menu_attrs_message);
2311
+ }
2312
+ var item_count: usize = 0;
2313
+ if (validateContextMenuChildren(node, &item_count)) |info| return info;
2314
+ if (item_count == 0) return errorAt(node, context_menu_empty_message);
2315
+ return null;
2316
+ }
2317
+
2318
+ /// The context-menu content walk, transparent through structure tags:
2319
+ /// `for`/`if`/`else` keep their generic shape rules, and every element
2320
+ /// they can ever produce is a menu-item or separator.
2321
+ fn validateContextMenuChildren(node: MarkupNode, item_count: *usize) ?MarkupErrorInfo {
2322
+ var previous_kind: ?MarkupNodeKind = null;
2323
+ for (node.children) |child| {
2324
+ switch (child.kind) {
2325
+ .element => {
2326
+ if (std.mem.eql(u8, child.name, "menu-item")) {
2327
+ item_count.* += 1;
2328
+ if (validateContextMenuItem(child)) |info| return info;
2329
+ } else if (std.mem.eql(u8, child.name, "separator")) {
2330
+ if (child.attrs.len > 0 or child.children.len > 0) {
2331
+ return errorAt(child, context_menu_separator_message);
2332
+ }
2333
+ item_count.* += 1;
2334
+ } else {
2335
+ return errorAt(child, context_menu_children_message);
2336
+ }
2337
+ },
2338
+ .for_block => {
2339
+ if (child.attr("each") == null) return errorAt(child, "for requires an each attribute");
2340
+ if (child.attr("as") == null) return errorAt(child, "for requires an as attribute");
2341
+ if (child.children.len == 0) return errorAt(child, for_children_message);
2342
+ // Repeated items count as content even though the model
2343
+ // may produce none at runtime (same optimism as the
2344
+ // engines' empty-menu handling).
2345
+ var repeated: usize = 0;
2346
+ if (validateContextMenuChildren(child, &repeated)) |info| return info;
2347
+ if (repeated == 0) return errorAt(child, context_menu_children_message);
2348
+ item_count.* += repeated;
2349
+ },
2350
+ .if_block => {
2351
+ const test_value = child.attr("test") orelse return errorAt(child, "if requires a test attribute");
2352
+ if (attrExpressionError(test_value, if_test_expression_message)) |message| {
2353
+ return errorAt(child, message);
2354
+ }
2355
+ if (validateContextMenuChildren(child, item_count)) |info| return info;
2356
+ },
2357
+ .else_block => {
2358
+ if (previous_kind != .if_block and previous_kind != .for_block) {
2359
+ return errorAt(child, else_placement_message);
2360
+ }
2361
+ if (validateContextMenuChildren(child, item_count)) |info| return info;
2362
+ },
2363
+ else => return errorAt(child, context_menu_children_message),
2364
+ }
2365
+ previous_kind = child.kind;
2366
+ }
2367
+ return null;
2368
+ }
2369
+
2370
+ /// One `<menu-item>` inside a context-menu: a closed attribute set
2371
+ /// (on-press and disabled — the platform item carries label, enabled
2372
+ /// state, and separators only) around one run of label text.
2373
+ fn validateContextMenuItem(node: MarkupNode) ?MarkupErrorInfo {
2374
+ var has_press = false;
2375
+ for (node.attrs) |attribute| {
2376
+ if (std.mem.eql(u8, attribute.name, "on-press")) {
2377
+ has_press = true;
2378
+ if (parseMessageExpression(attribute.value) == null) {
2379
+ return attrError(node, attribute, "invalid message expression: on-* takes a Msg tag (\"add\") or tag with one binding payload (\"toggle:{item.id}\")");
2380
+ }
2381
+ } else if (std.mem.eql(u8, attribute.name, "disabled")) {
2382
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2383
+ return attrError(node, attribute, message);
2384
+ }
2385
+ } else {
2386
+ return attrError(node, attribute, context_menu_item_attr_message);
2387
+ }
2388
+ }
2389
+ if (!has_press) return errorAt(node, context_menu_item_press_message);
2390
+ var text_runs: usize = 0;
2391
+ for (node.children) |child| {
2392
+ if (child.kind != .text) return errorAt(child, context_menu_item_label_message);
2393
+ text_runs += 1;
2394
+ if (text_runs > 1) return errorAt(child, text_leaf_single_run_message);
2395
+ if (textInterpolationError(child)) |info| return info;
2396
+ if (textNodeCoverageError(child)) |info| return info;
2397
+ }
2398
+ if (text_runs == 0) return errorAt(node, context_menu_item_label_message);
2399
+ return null;
2400
+ }
2401
+
2402
+ fn validateChart(node: MarkupNode) ?MarkupErrorInfo {
2403
+ for (node.attrs) |attribute| {
2404
+ if (std.mem.startsWith(u8, attribute.name, "on-")) {
2405
+ return attrError(node, attribute, chart_display_only_message);
2406
+ }
2407
+ if (std.mem.eql(u8, attribute.name, "x-labels")) {
2408
+ // Like series values: the data channel is a binding, never
2409
+ // a literal — labels vary with the model.
2410
+ const expression = parseAttrExpression(attribute.value);
2411
+ if (expression == null or expression.? != .binding) {
2412
+ return attrError(node, attribute, chart_x_labels_message);
2413
+ }
2414
+ continue;
2415
+ }
2416
+ const known = std.mem.eql(u8, attribute.name, "y-min") or
2417
+ std.mem.eql(u8, attribute.name, "y-max") or
2418
+ std.mem.eql(u8, attribute.name, "grid-lines") or
2419
+ std.mem.eql(u8, attribute.name, "baseline") or
2420
+ std.mem.eql(u8, attribute.name, "y-labels") or
2421
+ std.mem.eql(u8, attribute.name, "hover-details") or
2422
+ std.mem.eql(u8, attribute.name, "stroke-width") or
2423
+ std.mem.eql(u8, attribute.name, "width") or
2424
+ std.mem.eql(u8, attribute.name, "height") or
2425
+ std.mem.eql(u8, attribute.name, "grow") or
2426
+ std.mem.eql(u8, attribute.name, "padding") or
2427
+ std.mem.eql(u8, attribute.name, "key") or
2428
+ std.mem.eql(u8, attribute.name, "global-key") or
2429
+ std.mem.eql(u8, attribute.name, "label");
2430
+ if (!known) {
2431
+ return attrError(node, attribute, chart_attr_message);
2432
+ }
2433
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2434
+ return attrError(node, attribute, message);
2435
+ }
2436
+ if (attrCoverageError(node, attribute)) |info| return info;
2437
+ }
2438
+ var series_count: usize = 0;
2439
+ for (node.children) |child| {
2440
+ if (child.kind != .element or !std.mem.eql(u8, child.name, "series")) {
2441
+ return errorAt(child, chart_children_message);
2442
+ }
2443
+ if (validateSeries(child)) |info| return info;
2444
+ series_count += 1;
2445
+ }
2446
+ if (series_count == 0) return errorAt(node, chart_series_required_message);
2447
+ return null;
2448
+ }
2449
+
2450
+ /// One `<series>` inside a chart: a leaf whose data is the `values`
2451
+ /// binding. Kind and color are closed literal vocabularies (a typo can
2452
+ /// never rot silently), label is ordinary text.
2453
+ fn validateSeries(node: MarkupNode) ?MarkupErrorInfo {
2454
+ for (node.children) |child| {
2455
+ return errorAt(child, series_children_message);
2456
+ }
2457
+ var has_values = false;
2458
+ for (node.attrs) |attribute| {
2459
+ if (std.mem.eql(u8, attribute.name, "kind")) {
2460
+ const expression = parseAttrExpression(attribute.value);
2461
+ const literal = if (expression) |value|
2462
+ (if (value == .literal) value.literal else null)
2463
+ else
2464
+ null;
2465
+ if (literal == null or !nameInList(literal.?, &chart_series_kind_names)) {
2466
+ return attrError(node, attribute, series_kind_message);
2467
+ }
2468
+ continue;
2469
+ }
2470
+ if (std.mem.eql(u8, attribute.name, "values")) {
2471
+ has_values = true;
2472
+ const expression = parseAttrExpression(attribute.value);
2473
+ if (expression == null or expression.? != .binding) {
2474
+ return attrError(node, attribute, series_values_message);
2475
+ }
2476
+ continue;
2477
+ }
2478
+ if (std.mem.eql(u8, attribute.name, "color")) {
2479
+ const expression = parseAttrExpression(attribute.value);
2480
+ const literal = if (expression) |value|
2481
+ (if (value == .literal) value.literal else null)
2482
+ else
2483
+ null;
2484
+ if (literal == null or !nameInList(literal.?, &known_color_token_names)) {
2485
+ return attrError(node, attribute, series_color_message);
2486
+ }
2487
+ continue;
2488
+ }
2489
+ if (std.mem.eql(u8, attribute.name, "label")) {
2490
+ if (attrExpressionError(attribute.value, series_label_message)) |message| {
2491
+ return attrError(node, attribute, message);
2492
+ }
2493
+ continue;
2494
+ }
2495
+ return attrError(node, attribute, series_attr_message);
2496
+ }
2497
+ if (!has_values) return errorAt(node, series_values_message);
2498
+ return null;
2499
+ }
2500
+
2501
+ /// `<input-group>` — the composer-grade grouped input: ONE bordered
2502
+ /// field wrapping exactly one `<textarea>` (first, so document order is
2503
+ /// focus order) plus an optional `<input-group-actions>` accessory row.
2504
+ /// The group's own attribute set is closed and small — the text entry's
2505
+ /// behavior (text, placeholder, on-input, autofocus, ...) belongs to the
2506
+ /// textarea child, which validates through the ordinary pass.
2507
+ fn validateInputGroup(document: MarkupDocument, node: MarkupNode, template_limit: usize, slot_rule: SlotRule) ?MarkupErrorInfo {
2508
+ for (node.attrs) |attribute| {
2509
+ const known = std.mem.eql(u8, attribute.name, "label") or
2510
+ std.mem.eql(u8, attribute.name, "width") or
2511
+ std.mem.eql(u8, attribute.name, "height") or
2512
+ std.mem.eql(u8, attribute.name, "min-width") or
2513
+ std.mem.eql(u8, attribute.name, "grow") or
2514
+ std.mem.eql(u8, attribute.name, "key") or
2515
+ std.mem.eql(u8, attribute.name, "global-key");
2516
+ if (!known) {
2517
+ return attrError(node, attribute, input_group_attr_message);
2518
+ }
2519
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2520
+ return attrError(node, attribute, message);
2521
+ }
2522
+ if (attrCoverageError(node, attribute)) |info| return info;
2523
+ }
2524
+ // The child shape is static: the textarea first, then at most one
2525
+ // actions row. Conditional/repeated content belongs INSIDE the
2526
+ // actions row (structure tags work there), never at the group level.
2527
+ var textarea_count: usize = 0;
2528
+ var actions_count: usize = 0;
2529
+ for (node.children) |child| {
2530
+ if (child.kind != .element) return errorAt(child, input_group_children_message);
2531
+ if (std.mem.eql(u8, child.name, "textarea")) {
2532
+ if (textarea_count > 0 or actions_count > 0) return errorAt(child, input_group_children_message);
2533
+ textarea_count += 1;
2534
+ if (validateNode(document, child, "input-group", template_limit, slot_rule)) |info| return info;
2535
+ continue;
2536
+ }
2537
+ if (std.mem.eql(u8, child.name, "input-group-actions")) {
2538
+ if (textarea_count == 0) return errorAt(child, input_group_textarea_message);
2539
+ if (actions_count > 0) return errorAt(child, input_group_children_message);
2540
+ actions_count += 1;
2541
+ if (validateInputGroupActions(document, child, template_limit, slot_rule)) |info| return info;
2542
+ continue;
2543
+ }
2544
+ return errorAt(child, input_group_children_message);
2545
+ }
2546
+ if (textarea_count == 0) return errorAt(node, input_group_textarea_message);
2547
+ return null;
2548
+ }
2549
+
2550
+ /// `<input-group-actions>` — the accessory row pinned inside the group's
2551
+ /// border, under the textarea: a closed attribute set around ordinary
2552
+ /// row content (buttons, spacers; `for`/`if` work), validated through
2553
+ /// the generic pass.
2554
+ fn validateInputGroupActions(document: MarkupDocument, node: MarkupNode, template_limit: usize, slot_rule: SlotRule) ?MarkupErrorInfo {
2555
+ for (node.attrs) |attribute| {
2556
+ const known = std.mem.eql(u8, attribute.name, "gap") or
2557
+ std.mem.eql(u8, attribute.name, "key") or
2558
+ std.mem.eql(u8, attribute.name, "global-key");
2559
+ if (!known) {
2560
+ return attrError(node, attribute, input_group_actions_attr_message);
2561
+ }
2562
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2563
+ return attrError(node, attribute, message);
2564
+ }
2565
+ }
2566
+ var previous_kind: ?MarkupNodeKind = null;
2567
+ for (node.children) |child| {
2568
+ if (child.kind == .text) return errorAt(child, input_group_actions_children_message);
2569
+ if (child.kind == .else_block and previous_kind != .if_block and previous_kind != .for_block) {
2570
+ return errorAt(child, else_placement_message);
2571
+ }
2572
+ if (validateNode(document, child, "input-group-actions", template_limit, slot_rule)) |info| return info;
2573
+ previous_kind = child.kind;
2574
+ }
2575
+ return null;
2576
+ }
2577
+
2578
+ /// One `<span>` inside a text paragraph: a closed attribute set (weight,
2579
+ /// mono, italic, scale, underline, foreground — the span model's markup
2580
+ /// channels) around exactly one run of text. Spans do not nest: the
2581
+ /// engine's paragraph is a FLAT run list, so nesting would invent a
2582
+ /// cascade the renderer does not have. Pub and comptime-callable: the
2583
+ /// validator and BOTH engines run this one shape check, so the closed
2584
+ /// vocabulary is stated once.
2585
+ pub fn spanShapeError(node: MarkupNode) ?MarkupErrorInfo {
2586
+ for (node.attrs) |attribute| {
2587
+ if (std.mem.eql(u8, attribute.name, "weight")) {
2588
+ // Closed literal vocabulary; bindings resolve at build, where
2589
+ // the engines enforce the same set.
2590
+ if (parseAttrExpression(attribute.value)) |expression| {
2591
+ if (expression == .literal and !nameInList(expression.literal, &span_weight_value_names)) {
2592
+ return attrError(node, attribute, span_weight_value_message);
2593
+ }
2594
+ }
2595
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2596
+ return attrError(node, attribute, message);
2597
+ }
2598
+ continue;
2599
+ }
2600
+ if (std.mem.eql(u8, attribute.name, "scale")) {
2601
+ // The engine only scales for positive finite multipliers
2602
+ // (anything else silently draws at the base size), so markup
2603
+ // requires exactly that instead of letting a dead value rot.
2604
+ // Literals are checked here; bindings resolve at build, where
2605
+ // the engines enforce the same bound.
2606
+ if (parseAttrExpression(attribute.value)) |expression| {
2607
+ if (expression == .literal) {
2608
+ const multiplier = std.fmt.parseFloat(f32, expression.literal) catch {
2609
+ return attrError(node, attribute, span_scale_value_message);
2610
+ };
2611
+ if (!std.math.isFinite(multiplier) or multiplier <= 0) {
2612
+ return attrError(node, attribute, span_scale_value_message);
2613
+ }
2614
+ }
2615
+ }
2616
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2617
+ return attrError(node, attribute, message);
2618
+ }
2619
+ continue;
2620
+ }
2621
+ if (std.mem.eql(u8, attribute.name, "mono") or std.mem.eql(u8, attribute.name, "italic") or std.mem.eql(u8, attribute.name, "underline")) {
2622
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2623
+ return attrError(node, attribute, message);
2624
+ }
2625
+ continue;
2626
+ }
2627
+ if (std.mem.eql(u8, attribute.name, "foreground")) {
2628
+ // The existing color token channel: a literal ColorTokens
2629
+ // field name, exactly like foreground anywhere else.
2630
+ if (!nameInList(attribute.value, &known_color_token_names)) {
2631
+ const message = if (parseAttrExpression(attribute.value)) |expression|
2632
+ (if (expression == .literal) unknown_color_token_message else style_token_literal_message)
2633
+ else
2634
+ style_token_literal_message;
2635
+ return attrError(node, attribute, message);
2636
+ }
2637
+ continue;
2638
+ }
2639
+ return attrError(node, attribute, span_attr_message);
2640
+ }
2641
+ var text_runs: usize = 0;
2642
+ for (node.children) |child| {
2643
+ if (child.kind != .text) return errorAt(child, span_content_message);
2644
+ text_runs += 1;
2645
+ if (text_runs > 1) return errorAt(child, text_leaf_single_run_message);
2646
+ }
2647
+ if (text_runs == 0) return errorAt(node, span_content_message);
2648
+ return null;
2649
+ }
2650
+
2651
+ /// The validator's span pass: the shared shape check plus the source-text
2652
+ /// guards (interpolation grammar and tofu) over the span's run.
2653
+ fn validateSpan(node: MarkupNode) ?MarkupErrorInfo {
2654
+ if (spanShapeError(node)) |info| return info;
2655
+ for (node.children) |child| {
2656
+ if (textInterpolationError(child)) |info| return info;
2657
+ if (textNodeCoverageError(child)) |info| return info;
2658
+ }
2659
+ return null;
2660
+ }
2661
+
2662
+ /// One `<reactions>` inside a bubble: a closed attribute set (only a
2663
+ /// literal `text-alignment` naming the dock — the pill is a static
2664
+ /// design choice, like anchor placement) around one run of pill text.
2665
+ /// Pub and comptime-callable: the validator and BOTH engines run this
2666
+ /// one shape check, so the pill's closed shape is stated once.
2667
+ pub fn reactionsShapeError(node: MarkupNode) ?MarkupErrorInfo {
2668
+ for (node.attrs) |attribute| {
2669
+ if (std.mem.eql(u8, attribute.name, "text-alignment")) {
2670
+ if (!nameInList(attribute.value, &reactions_alignment_value_names)) {
2671
+ return attrError(node, attribute, reactions_alignment_value_message);
2672
+ }
2673
+ continue;
2674
+ }
2675
+ return attrError(node, attribute, reactions_attr_message);
2676
+ }
2677
+ var text_runs: usize = 0;
2678
+ for (node.children) |child| {
2679
+ if (child.kind != .text) return errorAt(child, reactions_content_message);
2680
+ text_runs += 1;
2681
+ if (text_runs > 1) return errorAt(child, text_leaf_single_run_message);
2682
+ }
2683
+ if (text_runs == 0) return errorAt(node, reactions_content_message);
2684
+ return null;
2685
+ }
2686
+
2687
+ /// The validator's reactions pass (run at the HOST bubble, where the
2688
+ /// parent node is in hand): the shared shape check plus the source-text
2689
+ /// guards (interpolation grammar and tofu) over the pill's run — the
2690
+ /// same pairing spans get.
2691
+ fn validateReactions(node: MarkupNode) ?MarkupErrorInfo {
2692
+ if (reactionsShapeError(node)) |info| return info;
2693
+ for (node.children) |child| {
2694
+ if (textInterpolationError(child)) |info| return info;
2695
+ if (textNodeCoverageError(child)) |info| return info;
2696
+ }
2697
+ return null;
2698
+ }
2699
+
2700
+ /// The rule hooks the composite registry entries name. A registry entry
2701
+ /// whose hook this table does not implement is a compile error (below),
2702
+ /// so attachment and implementation can never drift.
2703
+ const rule_hook_names = [_][]const u8{ "markdown", "stepper", "step", "timeline", "timeline-item", "chart", "series", "context-menu", "input-group", "input-group-actions", "span", "reactions" };
2704
+
2705
+ comptime {
2706
+ for (schema.elements) |entry| {
2707
+ const hook = entry.rule_hook orelse continue;
2708
+ var known = false;
2709
+ for (rule_hook_names) |name| {
2710
+ if (std.mem.eql(u8, name, hook)) known = true;
2711
+ }
2712
+ if (!known) @compileError("registry rule hook has no validator: " ++ hook);
2713
+ }
2714
+ }
2715
+
2716
+ /// Composite-element validation, dispatched by the registry's rule-hook
2717
+ /// name. Vocabulary is data; judgment stays code: forcing these shapes
2718
+ /// (markdown's closed attribute set, the stepper's step children, the
2719
+ /// timeline's parent scoping) into declarative registry data would breed
2720
+ /// a worse inner language than plain Zig.
2721
+ fn validateRuleHook(hook: []const u8, document: MarkupDocument, node: MarkupNode, parent_element: ?[]const u8, template_limit: usize, slot_rule: SlotRule) ?MarkupErrorInfo {
2722
+ if (std.mem.eql(u8, hook, "markdown")) return validateMarkdown(node);
2723
+ if (std.mem.eql(u8, hook, "stepper")) return validateStepper(node);
2724
+ if (std.mem.eql(u8, hook, "step")) {
2725
+ // Steps inside a stepper are consumed by validateStepper; one
2726
+ // reaching the generic pass sits outside a stepper.
2727
+ return errorAt(node, step_parent_message);
2728
+ }
2729
+ if (std.mem.eql(u8, hook, "timeline")) return validateTimeline(document, node, template_limit, slot_rule);
2730
+ if (std.mem.eql(u8, hook, "timeline-item")) {
2731
+ if (parent_element) |parent_name| {
2732
+ if (!std.mem.eql(u8, parent_name, "timeline")) {
2733
+ return errorAt(node, timeline_item_parent_message);
2734
+ }
2735
+ }
2736
+ return validateTimelineItem(node);
2737
+ }
2738
+ if (std.mem.eql(u8, hook, "chart")) return validateChart(node);
2739
+ if (std.mem.eql(u8, hook, "series")) {
2740
+ // Series inside a chart are consumed by validateChart; one
2741
+ // reaching the generic pass sits outside a chart.
2742
+ return errorAt(node, series_parent_message);
2743
+ }
2744
+ if (std.mem.eql(u8, hook, "context-menu")) {
2745
+ // Direct context-menu element children are consumed by their
2746
+ // host element's validation; one reaching the generic pass sits
2747
+ // at the root or behind a structure tag.
2748
+ return errorAt(node, context_menu_parent_message);
2749
+ }
2750
+ if (std.mem.eql(u8, hook, "input-group")) return validateInputGroup(document, node, template_limit, slot_rule);
2751
+ if (std.mem.eql(u8, hook, "input-group-actions")) {
2752
+ // Actions rows inside an input-group are consumed by
2753
+ // validateInputGroup; one reaching the generic pass sits outside
2754
+ // an input-group.
2755
+ return errorAt(node, input_group_actions_parent_message);
2756
+ }
2757
+ if (std.mem.eql(u8, hook, "span")) {
2758
+ // Spans inside a text paragraph are consumed by the text leaf's
2759
+ // content pass; one reaching the generic pass sits outside a
2760
+ // text leaf.
2761
+ return errorAt(node, span_parent_message);
2762
+ }
2763
+ if (std.mem.eql(u8, hook, "reactions")) {
2764
+ // Reactions inside a bubble are consumed by the bubble's host
2765
+ // pass; one reaching the generic pass sits outside a bubble.
2766
+ return errorAt(node, reactions_parent_message);
2767
+ }
2768
+ // The comptime check above proves every registry hook lands in one of
2769
+ // the branches; a name reaching here is not a registry hook at all.
2770
+ unreachable;
2771
+ }
2772
+
2773
+ /// `parent_element` is the name of the nearest enclosing element, looking
2774
+ /// through structure tags (`for`/`if`/`else`), or null at the view root and
2775
+ /// at a template body root.
2776
+ fn validateNode(document: MarkupDocument, node: MarkupNode, parent_element: ?[]const u8, template_limit: usize, slot_rule: SlotRule) ?MarkupErrorInfo {
2777
+ switch (node.kind) {
2778
+ // Literal text content rides the tofu guard (a codepoint the
2779
+ // bundled face cannot render is a teaching error at its exact
2780
+ // position) and the interpolation check (every `{...}` segment
2781
+ // is a path or a valid expression).
2782
+ .text => {
2783
+ if (textInterpolationError(node)) |info| return info;
2784
+ return textNodeCoverageError(node);
2785
+ },
2786
+ .template_block => return errorAt(node, template_top_level_message),
2787
+ .import_block => return errorAt(node, import_top_level_message),
2788
+ .use_block => return validateUse(document, node, template_limit),
2789
+ .slot_block => {
2790
+ switch (slot_rule) {
2791
+ .forbidden => return errorAt(node, slot_outside_template_message),
2792
+ .use_children => return errorAt(node, slot_in_use_children_message),
2793
+ .template_body => {},
2794
+ }
2795
+ for (node.attrs) |attribute| {
2796
+ return attrError(node, attribute, slot_attrs_message);
2797
+ }
2798
+ if (node.children.len > 0) return errorAt(node.children[0], slot_children_message);
2799
+ return null;
2800
+ },
2801
+ .element => {
2802
+ // Composite elements: the registry states WHICH elements
2803
+ // carry bespoke rules (their rule-hook attachment is data);
2804
+ // the rules themselves stay code, dispatched by hook name.
2805
+ if (schema.elementByName(node.name)) |entry| {
2806
+ if (entry.rule_hook) |hook| {
2807
+ return validateRuleHook(hook, document, node, parent_element, template_limit, slot_rule);
2808
+ }
2809
+ }
2810
+ if (!nameInList(node.name, &known_element_names)) {
2811
+ return errorAt(node, "unknown element");
2812
+ }
2813
+ // Direct context-menu children attach to THIS element (the
2814
+ // rule hook rejects any other placement), so the host's
2815
+ // eligibility — right-click resolution walks the hit route —
2816
+ // is checked here, where the host node is in hand.
2817
+ var context_menu_count: usize = 0;
2818
+ for (node.children) |child| {
2819
+ if (!nodeIsContextMenu(child)) continue;
2820
+ context_menu_count += 1;
2821
+ if (context_menu_count > 1) return errorAt(child, context_menu_single_message);
2822
+ if (!contextMenuHostEligible(node)) return errorAt(child, context_menu_host_message);
2823
+ if (contextMenuShapeError(child)) |info| return info;
2824
+ }
2825
+ // Direct reactions children attach to THIS element the same
2826
+ // way (the pill is bubble chrome, not content), so the
2827
+ // bubble-scoped checks run here, where the host node is in
2828
+ // hand. Off a bubble the placement error lands immediately
2829
+ // instead of waiting for the rule-hook pass.
2830
+ var reactions_count: usize = 0;
2831
+ for (node.children) |child| {
2832
+ if (!nodeIsReactions(child)) continue;
2833
+ reactions_count += 1;
2834
+ if (!std.mem.eql(u8, node.name, "bubble")) return errorAt(child, reactions_parent_message);
2835
+ if (reactions_count > 1) return errorAt(child, reactions_single_message);
2836
+ if (validateReactions(child)) |info| return info;
2837
+ }
2838
+ if (std.mem.eql(u8, node.name, "bubble")) {
2839
+ // The bubble's chrome-text channel belongs to the
2840
+ // reaction pill (declared with a <reactions> child); a
2841
+ // bare text attribute would silently do nothing, so it
2842
+ // is a teaching error (same policy as gap on stacking
2843
+ // containers).
2844
+ if (node.attrEntry("text")) |attribute| {
2845
+ return attrError(node, attribute, bubble_text_attr_message);
2846
+ }
2847
+ }
2848
+ if (std.mem.eql(u8, node.name, "table-row")) {
2849
+ if (parent_element) |parent_name| {
2850
+ if (!std.mem.eql(u8, parent_name, "table")) return errorAt(node, table_row_parent_message);
2851
+ }
2852
+ }
2853
+ if (std.mem.eql(u8, node.name, "table-cell")) {
2854
+ if (parent_element) |parent_name| {
2855
+ if (!std.mem.eql(u8, parent_name, "table-row")) return errorAt(node, table_cell_parent_message);
2856
+ }
2857
+ }
2858
+ if (nameInList(node.name, &known_text_leaf_element_names)) {
2859
+ // Elements that also take children (the list-row
2860
+ // composite) hold EITHER one text run OR element
2861
+ // children; mixing the two is a teaching error. Pure
2862
+ // text keeps the classic single-run rule — except the
2863
+ // text element itself, whose runs may interleave with
2864
+ // inline <span> children (the span paragraph).
2865
+ const is_text = std.mem.eql(u8, node.name, "text");
2866
+ const has_spans = is_text and nodeHasSpanChildren(node);
2867
+ const takes_children = nameInList(node.name, &known_text_or_children_element_names);
2868
+ const has_elements = takes_children and nodeHasElementContent(node);
2869
+ var text_runs: usize = 0;
2870
+ for (node.children) |child| {
2871
+ if (child.kind != .text) {
2872
+ // A context-menu child is metadata on the host,
2873
+ // not content: it never renders in the flow, so
2874
+ // the content-model rules look through it.
2875
+ if (nodeIsContextMenu(child)) continue;
2876
+ if (nodeIsSpan(child)) {
2877
+ // Inline spans belong to the text paragraph;
2878
+ // the other single-style labels cannot split
2879
+ // their run. Text-or-children hosts
2880
+ // (list-item) flow spans to the generic child
2881
+ // walk, whose placement hook teaches the
2882
+ // <text> home — the same path both engines
2883
+ // take.
2884
+ if (is_text) {
2885
+ if (validateSpan(child)) |info| return info;
2886
+ continue;
2887
+ }
2888
+ if (!takes_children) return errorAt(child, span_text_only_message);
2889
+ continue;
2890
+ }
2891
+ if (is_text) return errorAt(child, text_inline_children_message);
2892
+ if (!takes_children) return errorAt(child, text_leaf_children_message);
2893
+ continue;
2894
+ }
2895
+ if (has_elements) return errorAt(child, text_or_children_content_message);
2896
+ text_runs += 1;
2897
+ if (text_runs > 1 and !has_spans) return errorAt(child, text_leaf_single_run_message);
2898
+ }
2899
+ if (has_spans) {
2900
+ // A span paragraph always word-wraps (builder parity),
2901
+ // so the single-line policies are dead data here —
2902
+ // rejected instead of silently inert.
2903
+ for (node.attrs) |attribute| {
2904
+ if (std.mem.eql(u8, attribute.name, "wrap") or std.mem.eql(u8, attribute.name, "overflow")) {
2905
+ return attrError(node, attribute, span_paragraph_wrap_message);
2906
+ }
2907
+ }
2908
+ }
2909
+ }
2910
+ if (std.mem.eql(u8, node.name, "icon")) {
2911
+ if (node.attr("name") == null) return errorAt(node, icon_missing_name_message);
2912
+ if (node.children.len > 0) return errorAt(node.children[0], icon_children_message);
2913
+ }
2914
+ if (std.mem.eql(u8, node.name, "split")) {
2915
+ // Exactly two pane children, statically: the divider sits
2916
+ // between fixed panes, so conditional/repeated content
2917
+ // belongs inside a pane container.
2918
+ var pane_count: usize = 0;
2919
+ for (node.children) |child| {
2920
+ if (nodeIsContextMenu(child)) continue;
2921
+ switch (child.kind) {
2922
+ .element, .use_block => pane_count += 1,
2923
+ else => return errorAt(child, split_children_message),
2924
+ }
2925
+ }
2926
+ if (pane_count != 2) return errorAt(node, split_children_message);
2927
+ }
2928
+ // The a11y lint's error half: unnamed interactive controls
2929
+ // and role misuse block a screen reader user outright, so
2930
+ // they are validation errors (the warning half rides
2931
+ // `collectA11yWarnings`). Mirrored by both engines.
2932
+ if (a11yNameError(node)) |message| return errorAt(node, message);
2933
+ if (a11yRoleError(node)) |message| {
2934
+ return attrError(node, node.attrEntry("role").?, message);
2935
+ }
2936
+ for (node.attrs) |attribute| {
2937
+ if (std.mem.startsWith(u8, attribute.name, "on-")) {
2938
+ if (!nameInList(attribute.name[3..], &known_events)) {
2939
+ return attrError(node, attribute, "unknown event attribute");
2940
+ }
2941
+ if (std.mem.eql(u8, attribute.name, "on-scroll")) {
2942
+ // The runtime emits scroll offsets for scroll
2943
+ // containers only; anywhere else the handler could
2944
+ // never fire.
2945
+ if (!std.mem.eql(u8, node.name, "scroll")) {
2946
+ return attrError(node, attribute, on_scroll_element_message);
2947
+ }
2948
+ } else if (std.mem.eql(u8, attribute.name, "on-dismiss")) {
2949
+ // Only dismissible surfaces are ever dismissed by
2950
+ // the runtime; anywhere else the Msg could never
2951
+ // fire.
2952
+ if (!nameInList(node.name, &known_dismiss_element_names)) {
2953
+ return attrError(node, attribute, on_dismiss_element_message);
2954
+ }
2955
+ } else if (std.mem.eql(u8, attribute.name, "on-reach-end")) {
2956
+ // The approach-end signal (infinite-scroll fetch)
2957
+ // is emitted for scroll containers only.
2958
+ if (!std.mem.eql(u8, node.name, "scroll")) {
2959
+ return attrError(node, attribute, on_reach_end_element_message);
2960
+ }
2961
+ } else if (std.mem.eql(u8, attribute.name, "on-resize")) {
2962
+ // The runtime emits fraction changes for split
2963
+ // dividers only; anywhere else the handler could
2964
+ // never fire.
2965
+ if (!std.mem.eql(u8, node.name, "split")) {
2966
+ return attrError(node, attribute, on_resize_element_message);
2967
+ }
2968
+ } else if (nameInList(node.name, &known_non_hit_target_element_names) and deadHandlerOnNonHitTarget(attribute.name)) {
2969
+ return attrError(node, attribute, non_hit_target_handler_message);
2970
+ }
2971
+ if (parseMessageExpression(attribute.value) == null) {
2972
+ return attrError(node, attribute, "invalid message expression: on-* takes a Msg tag (\"add\") or tag with one binding payload (\"toggle:{item.id}\")");
2973
+ }
2974
+ continue;
2975
+ }
2976
+ if (nameInList(attribute.name, &known_color_style_attrs)) {
2977
+ if (!nameInList(attribute.value, &known_color_token_names)) {
2978
+ const message = if (parseAttrExpression(attribute.value)) |expression|
2979
+ (if (expression == .literal) unknown_color_token_message else style_token_literal_message)
2980
+ else
2981
+ style_token_literal_message;
2982
+ return attrError(node, attribute, message);
2983
+ }
2984
+ continue;
2985
+ }
2986
+ if (std.mem.eql(u8, attribute.name, "radius")) {
2987
+ if (!nameInList(attribute.value, &known_radius_token_names)) {
2988
+ const message = if (parseAttrExpression(attribute.value)) |expression|
2989
+ (if (expression == .literal) unknown_radius_token_message else style_token_literal_message)
2990
+ else
2991
+ style_token_literal_message;
2992
+ return attrError(node, attribute, message);
2993
+ }
2994
+ continue;
2995
+ }
2996
+ if (std.mem.eql(u8, attribute.name, "name")) {
2997
+ // Vector icon selector, icon-scoped: the shared icon
2998
+ // value grammar — built-in literals never rot (a
2999
+ // closed vocabulary), app:<name> and {binding} defer
3000
+ // to the registered set and the model.
3001
+ if (!std.mem.eql(u8, node.name, "icon")) {
3002
+ return attrError(node, attribute, icon_name_element_message);
3003
+ }
3004
+ switch (iconValueOf(attribute.value, icon_name_message)) {
3005
+ .invalid => |message| return attrError(node, attribute, message),
3006
+ else => {},
3007
+ }
3008
+ continue;
3009
+ }
3010
+ if (std.mem.eql(u8, attribute.name, "autofocus")) {
3011
+ // A focus request needs a focusable element; layout
3012
+ // and decoration kinds can never take the keyboard.
3013
+ if (nameInList(node.name, &known_non_hit_target_element_names)) {
3014
+ return attrError(node, attribute, autofocus_element_message);
3015
+ }
3016
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
3017
+ return attrError(node, attribute, message);
3018
+ }
3019
+ continue;
3020
+ }
3021
+ if (std.mem.eql(u8, attribute.name, "icon")) {
3022
+ // Inline vector icon, scoped to the labeled
3023
+ // interactive elements that render it themselves
3024
+ // (`known_icon_attr_element_names`): the same icon
3025
+ // value grammar as <icon name>, drawn inside the
3026
+ // element so icon + label are one hit target with one
3027
+ // tint.
3028
+ if (!iconAttrElement(node.name)) {
3029
+ return attrError(node, attribute, button_icon_element_message);
3030
+ }
3031
+ switch (iconValueOf(attribute.value, button_icon_message)) {
3032
+ .invalid => |message| return attrError(node, attribute, message),
3033
+ else => {},
3034
+ }
3035
+ continue;
3036
+ }
3037
+ if (std.mem.eql(u8, attribute.name, "image")) {
3038
+ // Runtime image binding, avatar-scoped: ids are model
3039
+ // data the app registered, never markup literals.
3040
+ if (!std.mem.eql(u8, node.name, "avatar")) {
3041
+ return attrError(node, attribute, avatar_image_element_message);
3042
+ }
3043
+ const expression = parseAttrExpression(attribute.value);
3044
+ if (expression == null or expression.? != .binding) {
3045
+ return attrError(node, attribute, avatar_image_message);
3046
+ }
3047
+ continue;
3048
+ }
3049
+ if (std.mem.eql(u8, attribute.name, "anchor")) {
3050
+ // Anchored floating placement, dropdown-menu-scoped:
3051
+ // a literal side so the compiled engine resolves it
3052
+ // at comptime (flip is automatic either way).
3053
+ if (!nameInList(node.name, &known_anchor_element_names)) {
3054
+ return attrError(node, attribute, anchor_element_message);
3055
+ }
3056
+ if (!std.mem.eql(u8, attribute.value, "below") and !std.mem.eql(u8, attribute.value, "above")) {
3057
+ return attrError(node, attribute, anchor_value_message);
3058
+ }
3059
+ continue;
3060
+ }
3061
+ if (std.mem.eql(u8, attribute.name, "anchor-alignment")) {
3062
+ if (!nameInList(node.name, &known_anchor_element_names)) {
3063
+ return attrError(node, attribute, anchor_element_message);
3064
+ }
3065
+ if (node.attr("anchor") == null) {
3066
+ return attrError(node, attribute, anchor_dependent_attr_message);
3067
+ }
3068
+ if (!std.mem.eql(u8, attribute.value, "start") and !std.mem.eql(u8, attribute.value, "end") and !std.mem.eql(u8, attribute.value, "stretch")) {
3069
+ return attrError(node, attribute, anchor_alignment_value_message);
3070
+ }
3071
+ continue;
3072
+ }
3073
+ if (std.mem.eql(u8, attribute.name, "anchor-offset")) {
3074
+ if (!nameInList(node.name, &known_anchor_element_names)) {
3075
+ return attrError(node, attribute, anchor_element_message);
3076
+ }
3077
+ if (node.attr("anchor") == null) {
3078
+ return attrError(node, attribute, anchor_dependent_attr_message);
3079
+ }
3080
+ _ = std.fmt.parseFloat(f32, attribute.value) catch {
3081
+ return attrError(node, attribute, anchor_offset_value_message);
3082
+ };
3083
+ continue;
3084
+ }
3085
+ if (std.mem.eql(u8, attribute.name, "gap") and nameInList(node.name, &known_stack_container_element_names)) {
3086
+ return attrError(node, attribute, stack_container_gap_message);
3087
+ }
3088
+ if (std.mem.eql(u8, attribute.name, "columns") and !std.mem.eql(u8, node.name, "grid")) {
3089
+ // Only the grid layout reads a column count; anywhere
3090
+ // else it would silently do nothing (same policy as
3091
+ // gap on stacking containers).
3092
+ return attrError(node, attribute, grid_columns_element_message);
3093
+ }
3094
+ if (std.mem.eql(u8, attribute.name, "wrap") and !std.mem.eql(u8, node.name, "text")) {
3095
+ // Only plain text leaves word-wrap; on a container the
3096
+ // option is silently inert and has shipped with
3097
+ // comments asserting wrapping that never happened
3098
+ // (same policy as gap on stacking containers).
3099
+ return attrError(node, attribute, wrap_element_message);
3100
+ }
3101
+ if (std.mem.eql(u8, attribute.name, "overflow")) {
3102
+ // Overflow policy exists only where a single line can
3103
+ // overflow: a plain text leaf. Anywhere else the
3104
+ // option is silently inert (same policy as wrap).
3105
+ if (!std.mem.eql(u8, node.name, "text")) {
3106
+ return attrError(node, attribute, overflow_element_message);
3107
+ }
3108
+ // The closed value vocabulary, checked on literals
3109
+ // here so the teaching error lands at validation
3110
+ // (bindings resolve at build, where the engines
3111
+ // enforce the same set).
3112
+ if (parseAttrExpression(attribute.value)) |expression| {
3113
+ if (expression == .literal and !nameInList(expression.literal, &overflow_value_names)) {
3114
+ return attrError(node, attribute, overflow_value_message);
3115
+ }
3116
+ }
3117
+ }
3118
+ if (std.mem.eql(u8, attribute.name, "overscroll")) {
3119
+ // Edge behavior exists only where the runtime scrolls:
3120
+ // anywhere but a scroll container the option is
3121
+ // silently inert (same policy as columns off grid).
3122
+ if (!std.mem.eql(u8, node.name, "scroll")) {
3123
+ return attrError(node, attribute, overscroll_element_message);
3124
+ }
3125
+ // The closed value vocabulary, checked on literals
3126
+ // here so the teaching error lands at validation
3127
+ // (bindings resolve at build, where the engines
3128
+ // enforce the same set).
3129
+ if (parseAttrExpression(attribute.value)) |expression| {
3130
+ if (expression == .literal and !nameInList(expression.literal, &overscroll_value_names)) {
3131
+ return attrError(node, attribute, overscroll_value_message);
3132
+ }
3133
+ }
3134
+ }
3135
+ if (std.mem.eql(u8, attribute.name, "resize-duration")) {
3136
+ // The layout tween exists only where a fraction can
3137
+ // move: anywhere but a split the option is silently
3138
+ // inert (same policy as overscroll off scroll).
3139
+ if (!std.mem.eql(u8, node.name, "split")) {
3140
+ return attrError(node, attribute, resize_duration_element_message);
3141
+ }
3142
+ }
3143
+ if (std.mem.eql(u8, attribute.name, "resize-easing")) {
3144
+ if (!std.mem.eql(u8, node.name, "split")) {
3145
+ return attrError(node, attribute, resize_easing_element_message);
3146
+ }
3147
+ // Easing shapes a ramp that exists only while a
3148
+ // nonzero duration declares one: easing alone (or
3149
+ // beside a literal 0 duration) is silently inert, so
3150
+ // it is a teaching error (same policy as
3151
+ // anchor-alignment without anchor). A binding-valued
3152
+ // duration resolves at build and stays legal here.
3153
+ const duration_raw = node.attr("resize-duration") orelse {
3154
+ return attrError(node, attribute, resize_easing_dependent_attr_message);
3155
+ };
3156
+ if (parseAttrExpression(duration_raw)) |duration_expression| {
3157
+ if (duration_expression == .literal) {
3158
+ const duration = std.fmt.parseInt(u32, duration_expression.literal, 10) catch 1;
3159
+ if (duration == 0) {
3160
+ return attrError(node, attribute, resize_easing_dependent_attr_message);
3161
+ }
3162
+ }
3163
+ }
3164
+ // The closed value vocabulary, checked on literals
3165
+ // here so the teaching error lands at validation
3166
+ // (bindings resolve at build, where the engines
3167
+ // enforce the same set).
3168
+ if (parseAttrExpression(attribute.value)) |expression| {
3169
+ if (expression == .literal and !nameInList(expression.literal, &resize_easing_value_names)) {
3170
+ return attrError(node, attribute, resize_easing_value_message);
3171
+ }
3172
+ }
3173
+ }
3174
+ if (std.mem.eql(u8, attribute.name, "resize-origin")) {
3175
+ if (!std.mem.eql(u8, node.name, "split")) {
3176
+ return attrError(node, attribute, resize_origin_element_message);
3177
+ }
3178
+ // An origin shapes an enter slide that exists only
3179
+ // while a nonzero duration declares one: origin
3180
+ // alone (or beside a literal 0 duration) is
3181
+ // silently inert, so it is a teaching error — the
3182
+ // resize-easing dependency policy exactly.
3183
+ const duration_raw = node.attr("resize-duration") orelse {
3184
+ return attrError(node, attribute, resize_origin_dependent_attr_message);
3185
+ };
3186
+ if (parseAttrExpression(duration_raw)) |duration_expression| {
3187
+ if (duration_expression == .literal) {
3188
+ const duration = std.fmt.parseInt(u32, duration_expression.literal, 10) catch 1;
3189
+ if (duration == 0) {
3190
+ return attrError(node, attribute, resize_origin_dependent_attr_message);
3191
+ }
3192
+ }
3193
+ }
3194
+ }
3195
+ if (std.mem.eql(u8, attribute.name, "size")) {
3196
+ // The size register's closed literal vocabulary
3197
+ // (bindings resolve at build): the control scale
3198
+ // everywhere, plus the typography rungs on text only
3199
+ // - two axes one attribute names, kept apart with a
3200
+ // teaching error instead of a silently inert option.
3201
+ // Numeric literals are refused on purpose: type
3202
+ // sizes are themable token steps, never per-element
3203
+ // numbers.
3204
+ if (parseAttrExpression(attribute.value)) |expression| {
3205
+ if (expression == .literal) {
3206
+ if (nameInList(expression.literal, &known_text_size_value_names)) {
3207
+ if (!std.mem.eql(u8, node.name, "text")) {
3208
+ return attrError(node, attribute, text_size_element_message);
3209
+ }
3210
+ } else if (!nameInList(expression.literal, &known_control_size_value_names)) {
3211
+ return attrError(node, attribute, size_value_message);
3212
+ }
3213
+ }
3214
+ }
3215
+ }
3216
+ if (!nameInList(attribute.name, &known_option_attrs)) {
3217
+ return attrError(node, attribute, "unknown attribute");
3218
+ }
3219
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
3220
+ return attrError(node, attribute, message);
3221
+ }
3222
+ if (attrCoverageError(node, attribute)) |info| return info;
3223
+ }
3224
+ },
3225
+ .for_block => {
3226
+ if (parent_element == null) return errorAt(node, "for is only allowed inside an element");
3227
+ if (node.attr("each") == null) return errorAt(node, "for requires an each attribute");
3228
+ if (node.attr("as") == null) return errorAt(node, "for requires an as attribute");
3229
+ if (node.children.len == 0) return errorAt(node, for_children_message);
3230
+ for (node.children) |child| {
3231
+ switch (child.kind) {
3232
+ .element, .use_block, .for_block, .if_block, .else_block, .slot_block => {},
3233
+ else => return errorAt(child, for_children_message),
3234
+ }
3235
+ }
3236
+ },
3237
+ .if_block => {
3238
+ if (parent_element == null) return errorAt(node, "if is only allowed inside an element");
3239
+ const test_value = node.attr("test") orelse return errorAt(node, "if requires a test attribute");
3240
+ if (attrExpressionError(test_value, if_test_expression_message)) |message| {
3241
+ return errorAt(node, message);
3242
+ }
3243
+ },
3244
+ .else_block => {},
3245
+ }
3246
+ // Structure tags are transparent for parent-scoped rules: their
3247
+ // children still sit inside the enclosing element.
3248
+ const child_parent: ?[]const u8 = switch (node.kind) {
3249
+ .element => node.name,
3250
+ .for_block, .if_block, .else_block => parent_element,
3251
+ else => null,
3252
+ };
3253
+ var previous_kind: ?MarkupNodeKind = null;
3254
+ for (node.children) |child| {
3255
+ if (child.kind == .else_block and previous_kind != .if_block and previous_kind != .for_block) {
3256
+ return errorAt(child, else_placement_message);
3257
+ }
3258
+ // A direct context-menu child was already validated by its host
3259
+ // element above; recursing would fire the placement hook. Span
3260
+ // children of a text paragraph were consumed by the text leaf's
3261
+ // content pass the same way.
3262
+ if (node.kind == .element and nodeIsContextMenu(child)) {
3263
+ previous_kind = child.kind;
3264
+ continue;
3265
+ }
3266
+ if (node.kind == .element and std.mem.eql(u8, node.name, "text") and nodeIsSpan(child)) {
3267
+ previous_kind = child.kind;
3268
+ continue;
3269
+ }
3270
+ // Reactions children of a bubble were consumed by the bubble's
3271
+ // host pass the same way.
3272
+ if (node.kind == .element and std.mem.eql(u8, node.name, "bubble") and nodeIsReactions(child)) {
3273
+ previous_kind = child.kind;
3274
+ continue;
3275
+ }
3276
+ if (validateNode(document, child, child_parent, template_limit, slot_rule)) |info| {
3277
+ return info;
3278
+ }
3279
+ previous_kind = child.kind;
3280
+ }
3281
+ return null;
3282
+ }
3283
+
3284
+ /// A single undotted binding-path segment: template arg names (they must
3285
+ /// be resolvable as binding heads).
3286
+ fn isBindingName(text: []const u8) bool {
3287
+ return isBindingPath(text) and std.mem.indexOfScalar(u8, text, '.') == null;
3288
+ }
3289
+
3290
+ /// A lowercase kebab-case name, like element names: template names
3291
+ /// ("board-column") are referenced by `use`, never by bindings.
3292
+ fn isTemplateName(text: []const u8) bool {
3293
+ if (text.len == 0) return false;
3294
+ if (!(text[0] >= 'a' and text[0] <= 'z')) return false;
3295
+ for (text) |byte| {
3296
+ const valid = (byte >= 'a' and byte <= 'z') or (byte >= '0' and byte <= '9') or byte == '-' or byte == '_';
3297
+ if (!valid) return false;
3298
+ }
3299
+ return true;
3300
+ }
3301
+
3302
+ /// Length of the leading whitespace `std.mem.trim` removes from a text
3303
+ /// run (comptime-callable; the comptime parser cannot do pointer math).
3304
+ fn textLeadingTrim(text: []const u8) usize {
3305
+ var lead: usize = 0;
3306
+ while (lead < text.len) : (lead += 1) {
3307
+ switch (text[lead]) {
3308
+ ' ', '\t', '\r', '\n' => {},
3309
+ else => break,
3310
+ }
3311
+ }
3312
+ return lead;
3313
+ }
3314
+
3315
+ /// Membership in a name-list vocabulary (comptime-callable; both engines
3316
+ /// reuse it for the shared closed vocabularies).
3317
+ pub fn nameInList(name: []const u8, list: []const []const u8) bool {
3318
+ for (list) |candidate| {
3319
+ if (std.mem.eql(u8, name, candidate)) return true;
3320
+ }
3321
+ return false;
3322
+ }
3323
+
3324
+ fn errorAt(node: MarkupNode, message: []const u8) MarkupErrorInfo {
3325
+ return .{ .line = node.line, .column = node.column, .message = message, .path = node.src_path };
3326
+ }
3327
+
3328
+ /// An error positioned at an attribute; the enclosing node carries the
3329
+ /// source path (attributes do not).
3330
+ fn attrError(node: MarkupNode, attribute: MarkupAttr, message: []const u8) MarkupErrorInfo {
3331
+ return .{ .line = attribute.line, .column = attribute.column, .message = message, .path = node.src_path };
3332
+ }
3333
+
3334
+ // ---------------------------------------------------------------- imports
3335
+ //
3336
+ // THE RESOLVER SEAM. An import maps a root-relative path to markup source
3337
+ // text; everything else — grammar, ordering, cycles, duplicates, merging —
3338
+ // lives here once, and each engine supplies only the mapping:
3339
+ //
3340
+ // - compiled engine (`canvas.CompiledMarkupImports`): a comptime source
3341
+ // set the app assembles with `@embedFile` -> `resolveImportsComptime`.
3342
+ // - runtime interpreter (ui_app): the same embedded set for the first
3343
+ // build of a markup-only app, and the file system rooted at the
3344
+ // watched file's directory for hot reload -> `resolveImports` with the
3345
+ // matching `ImportLoader`.
3346
+ // - `native markup check`: the file system rooted at the checked file's
3347
+ // directory -> `resolveImports`.
3348
+ //
3349
+ // Resolution splices imported templates BEFORE the importing file's own,
3350
+ // depth-first in import order (a file's transitive imports land before its
3351
+ // own templates) — exactly as if each imported file were pasted at its
3352
+ // import site. The merged document is a plain single-file document
3353
+ // (`imports` empty), so the engines' template machinery — define-before-use
3354
+ // ordering, expansion, structural ids — is untouched: widget ids hash as
3355
+ // if every template were defined locally, and the two engines stay in
3356
+ // parity by construction. Every node is stamped with its source path so
3357
+ // diagnostics name the right file.
3358
+
3359
+ /// One markup file in an embedded source set: `path` is relative to the
3360
+ /// markup root (the root view file's directory), forward slashes.
3361
+ pub const SourceFile = struct {
3362
+ path: []const u8,
3363
+ source: []const u8,
3364
+ };
3365
+
3366
+ /// Registration handle for the runtime's fragment hot-reload watch: a
3367
+ /// hybrid app (Zig builder root embedding compiled markup fragments)
3368
+ /// hands the runtime one of these per fragment — obtained from the
3369
+ /// compiled type's `fragment(path)` — so editing that fragment's
3370
+ /// `.native` source in a dev run reloads it in place. Debug-shaped on
3371
+ /// purpose: outside Debug the struct is empty and `fragment(path)`
3372
+ /// returns nothing, so release binaries carry no source paths, no
3373
+ /// embedded-baseline references, and no watch plumbing.
3374
+ pub const MarkupFragment = if (builtin.mode == .Debug) struct {
3375
+ /// Identity of the compiled fragment type (the address of its
3376
+ /// comptime document), matched by the engine's build-time override
3377
+ /// lookup — registration and lookup derive it from the same type,
3378
+ /// so they cannot disagree. A pointer, not an integer, so a
3379
+ /// registration list can live in a file-scope const (global
3380
+ /// addresses are comptime-representable; their integer values are
3381
+ /// not).
3382
+ key: ?*const anyopaque = null,
3383
+ /// On-disk source file to watch, relative to the process cwd (the
3384
+ /// dev flow runs apps from the app root). Imports resolve against
3385
+ /// this file's directory, exactly like the single-root watch.
3386
+ path: []const u8 = "",
3387
+ /// The embedded root source the fragment was compiled from — the
3388
+ /// baseline the watched file is compared against, so an unchanged
3389
+ /// disk file never triggers a phantom reload.
3390
+ source: []const u8 = "",
3391
+ /// The embedded import closure (`CompiledMarkupImports` source set);
3392
+ /// empty for single-file fragments.
3393
+ sources: []const SourceFile = &.{},
3394
+ } else struct {};
3395
+
3396
+ /// Runtime source access for `resolveImports`: returns the source for a
3397
+ /// root-relative path, or null when it cannot be read (the resolver turns
3398
+ /// that into a teaching error at the import site).
3399
+ pub const ImportLoader = struct {
3400
+ context: *const anyopaque,
3401
+ load: *const fn (context: *const anyopaque, arena: std.mem.Allocator, path: []const u8) ?[]const u8,
3402
+ };
3403
+
3404
+ /// Loader over an embedded source set (the runtime mirror of the compiled
3405
+ /// engine's comptime lookup). Keep the struct alive for the duration of
3406
+ /// the resolve call; `loader()` captures a pointer to it.
3407
+ pub const SourceSetLoader = struct {
3408
+ set: []const SourceFile,
3409
+
3410
+ pub fn loader(self: *const SourceSetLoader) ImportLoader {
3411
+ return .{ .context = @ptrCast(self), .load = load };
3412
+ }
3413
+
3414
+ fn load(context: *const anyopaque, arena: std.mem.Allocator, path: []const u8) ?[]const u8 {
3415
+ _ = arena;
3416
+ const self: *const SourceSetLoader = @ptrCast(@alignCast(context));
3417
+ for (self.set) |file| {
3418
+ if (std.mem.eql(u8, file.path, path)) return file.source;
3419
+ }
3420
+ return null;
3421
+ }
3422
+ };
3423
+
3424
+ pub const max_import_path_len = 200;
3425
+ pub const max_import_path_segments = 24;
3426
+ pub const max_import_depth = 8;
3427
+ pub const max_imported_files = 32;
3428
+
3429
+ pub const ResolveError = error{ MarkupSyntax, MarkupImport, OutOfMemory };
3430
+
3431
+ /// Resolve a root document's import closure into one merged document.
3432
+ /// `root_name` names the root file for diagnostics AND anchors relative
3433
+ /// resolution: imports resolve against the importing file's directory, and
3434
+ /// nothing may escape `dirname(root_name)` (the markup root). Failures set
3435
+ /// `diagnostic` — position, message, and the source path of the file the
3436
+ /// position refers to.
3437
+ pub fn resolveImports(
3438
+ arena: std.mem.Allocator,
3439
+ root_name: []const u8,
3440
+ root_source: []const u8,
3441
+ loader: ImportLoader,
3442
+ diagnostic: *MarkupErrorInfo,
3443
+ ) ResolveError!MarkupDocument {
3444
+ var resolver = ImportResolver{
3445
+ .arena = arena,
3446
+ .root_dir = dirnamePath(root_name),
3447
+ .loader = loader,
3448
+ .diagnostic = diagnostic,
3449
+ };
3450
+ const root = try resolver.visit(root_name, root_source, 0);
3451
+ return .{ .imports = &.{}, .templates = resolver.templates.items, .root = root };
3452
+ }
3453
+
3454
+ const ImportResolver = struct {
3455
+ arena: std.mem.Allocator,
3456
+ root_dir: []const u8,
3457
+ loader: ImportLoader,
3458
+ diagnostic: *MarkupErrorInfo,
3459
+ templates: std.ArrayListUnmanaged(MarkupNode) = .empty,
3460
+ /// Fully resolved files (dedupe: two files importing the same
3461
+ /// component resolve it once, so its templates splice once).
3462
+ visited: std.ArrayListUnmanaged([]const u8) = .empty,
3463
+ /// The in-progress import chain, for cycle reporting.
3464
+ chain: [max_import_depth][]const u8 = undefined,
3465
+ file_count: usize = 0,
3466
+
3467
+ /// Parse one file, resolve its imports depth-first, splice its
3468
+ /// templates, and return its stamped view root (null for a component
3469
+ /// file). Only the root file (depth 0) may have a view root.
3470
+ fn visit(self: *ImportResolver, path: []const u8, source: []const u8, depth: usize) ResolveError!?MarkupNode {
3471
+ self.chain[depth] = path;
3472
+ var parser = Parser.init(self.arena, source);
3473
+ const document = parser.parse() catch |err| {
3474
+ if (err == error.MarkupSyntax) {
3475
+ self.diagnostic.* = parser.diagnostic;
3476
+ self.diagnostic.path = path;
3477
+ }
3478
+ return err;
3479
+ };
3480
+ for (document.imports) |import_node| {
3481
+ if (validateImport(import_node)) |info| {
3482
+ self.diagnostic.* = info;
3483
+ self.diagnostic.path = path;
3484
+ return error.MarkupImport;
3485
+ }
3486
+ const src = import_node.attr("src").?;
3487
+ var buffer: [max_import_path_len]u8 = undefined;
3488
+ const resolved = switch (resolveImportPath(self.root_dir, path, src, &buffer)) {
3489
+ .path => |normalized| try self.arena.dupe(u8, normalized),
3490
+ .message => |message| return self.fail(path, import_node, message),
3491
+ };
3492
+ var cycle_start: ?usize = null;
3493
+ for (self.chain[0 .. depth + 1], 0..) |ancestor, index| {
3494
+ if (std.mem.eql(u8, ancestor, resolved)) cycle_start = index;
3495
+ }
3496
+ if (cycle_start) |start| {
3497
+ return self.fail(path, import_node, try self.cycleMessage(start, depth, resolved));
3498
+ }
3499
+ if (self.wasVisited(resolved)) continue;
3500
+ if (depth + 1 >= max_import_depth) return self.fail(path, import_node, import_depth_message);
3501
+ self.file_count += 1;
3502
+ if (self.file_count > max_imported_files) return self.fail(path, import_node, import_count_message);
3503
+ const child_source = self.loader.load(self.loader.context, self.arena, resolved) orelse {
3504
+ const message = try std.fmt.allocPrint(self.arena, "unable to read imported file \"{s}\"", .{resolved});
3505
+ return self.fail(path, import_node, message);
3506
+ };
3507
+ _ = try self.visit(resolved, child_source, depth + 1);
3508
+ try self.visited.append(self.arena, resolved);
3509
+ }
3510
+ for (document.templates) |template_node| {
3511
+ if (self.templates.items.len >= max_document_templates) {
3512
+ return self.fail(path, template_node, max_templates_message);
3513
+ }
3514
+ if (template_node.attr("name")) |name| {
3515
+ for (self.templates.items) |existing| {
3516
+ const existing_name = existing.attr("name") orelse continue;
3517
+ if (std.mem.eql(u8, existing_name, name)) {
3518
+ const message = try std.fmt.allocPrint(
3519
+ self.arena,
3520
+ "duplicate template name \"{s}\" - also defined at {s}:{d}:{d}; template names are document-wide once imports resolve, so rename one (imports never shadow silently)",
3521
+ .{ name, existing.src_path, existing.line, existing.column },
3522
+ );
3523
+ return self.fail(path, template_node, message);
3524
+ }
3525
+ }
3526
+ }
3527
+ try self.templates.append(self.arena, try stampSourcePath(self.arena, template_node, path));
3528
+ }
3529
+ if (document.root) |root_node| {
3530
+ if (depth > 0) {
3531
+ self.diagnostic.* = .{
3532
+ .line = root_node.line,
3533
+ .column = root_node.column,
3534
+ .message = import_view_root_message,
3535
+ .path = path,
3536
+ };
3537
+ return error.MarkupImport;
3538
+ }
3539
+ return try stampSourcePath(self.arena, root_node, path);
3540
+ }
3541
+ return null;
3542
+ }
3543
+
3544
+ fn fail(self: *ImportResolver, path: []const u8, node: MarkupNode, message: []const u8) ResolveError {
3545
+ self.diagnostic.* = .{ .line = node.line, .column = node.column, .message = message, .path = path };
3546
+ return error.MarkupImport;
3547
+ }
3548
+
3549
+ fn wasVisited(self: *const ImportResolver, path: []const u8) bool {
3550
+ for (self.visited.items) |seen| {
3551
+ if (std.mem.eql(u8, seen, path)) return true;
3552
+ }
3553
+ return false;
3554
+ }
3555
+
3556
+ /// "import cycle: a.native -> b.native -> a.native" — the chain from the first
3557
+ /// occurrence of the re-imported file down to the import that closes
3558
+ /// the loop.
3559
+ fn cycleMessage(self: *ImportResolver, start: usize, depth: usize, resolved: []const u8) error{OutOfMemory}![]const u8 {
3560
+ var out: std.ArrayListUnmanaged(u8) = .empty;
3561
+ try out.appendSlice(self.arena, "import cycle: ");
3562
+ for (self.chain[start .. depth + 1]) |link| {
3563
+ try out.appendSlice(self.arena, link);
3564
+ try out.appendSlice(self.arena, " -> ");
3565
+ }
3566
+ try out.appendSlice(self.arena, resolved);
3567
+ return out.items;
3568
+ }
3569
+ };
3570
+
3571
+ fn stampSourcePath(arena: std.mem.Allocator, node: MarkupNode, path: []const u8) error{OutOfMemory}!MarkupNode {
3572
+ // An anonymous root (single-file resolution) keeps diagnostics
3573
+ // path-less, exactly like the unresolved parse — no copy needed.
3574
+ if (path.len == 0) return node;
3575
+ var out = node;
3576
+ out.src_path = path;
3577
+ if (node.children.len > 0) {
3578
+ const children = try arena.alloc(MarkupNode, node.children.len);
3579
+ for (node.children, 0..) |child, index| {
3580
+ children[index] = try stampSourcePath(arena, child, path);
3581
+ }
3582
+ out.children = children;
3583
+ }
3584
+ return out;
3585
+ }
3586
+
3587
+ pub const ImportPathResult = union(enum) {
3588
+ path: []const u8,
3589
+ message: []const u8,
3590
+ };
3591
+
3592
+ /// Lexically join `src` against the importing file's directory and
3593
+ /// normalize it: "." segments drop, ".." pops, subdirectories stay. The
3594
+ /// result must remain under `root_dir` (the markup root — the root view
3595
+ /// file's directory); escapes and absolute paths come back as teaching
3596
+ /// messages. Comptime-callable; the returned path slices `buffer`.
3597
+ pub fn resolveImportPath(root_dir: []const u8, importer_path: []const u8, src: []const u8, buffer: []u8) ImportPathResult {
3598
+ if (importSrcShapeError(src)) |message| return .{ .message = message };
3599
+ // Tokenizing drops the leading "/" of an absolute importer path, so
3600
+ // remember it and restore it when the path is rebuilt below. Without
3601
+ // this, checking a view by absolute path rebuilds imports as relative
3602
+ // strings, and the escape check against the absolute markup root
3603
+ // rejects every import (and the loader would read the wrong file).
3604
+ const absolute = importer_path.len > 0 and importer_path[0] == '/';
3605
+ var segments: [max_import_path_segments][]const u8 = undefined;
3606
+ var count: usize = 0;
3607
+ var dir_it = std.mem.tokenizeScalar(u8, dirnamePath(importer_path), '/');
3608
+ while (dir_it.next()) |segment| {
3609
+ if (count >= segments.len) return .{ .message = import_src_too_long_message };
3610
+ segments[count] = segment;
3611
+ count += 1;
3612
+ }
3613
+ var src_it = std.mem.tokenizeScalar(u8, src, '/');
3614
+ while (src_it.next()) |segment| {
3615
+ if (std.mem.eql(u8, segment, ".")) continue;
3616
+ if (std.mem.eql(u8, segment, "..")) {
3617
+ if (count == 0) return .{ .message = import_src_escape_message };
3618
+ count -= 1;
3619
+ continue;
3620
+ }
3621
+ if (count >= segments.len) return .{ .message = import_src_too_long_message };
3622
+ segments[count] = segment;
3623
+ count += 1;
3624
+ }
3625
+ var len: usize = 0;
3626
+ if (absolute) {
3627
+ if (buffer.len == 0) return .{ .message = import_src_too_long_message };
3628
+ buffer[0] = '/';
3629
+ len = 1;
3630
+ }
3631
+ for (segments[0..count], 0..) |segment, index| {
3632
+ const extra = segment.len + @intFromBool(index > 0);
3633
+ if (len + extra > buffer.len) return .{ .message = import_src_too_long_message };
3634
+ if (index > 0) {
3635
+ buffer[len] = '/';
3636
+ len += 1;
3637
+ }
3638
+ @memcpy(buffer[len .. len + segment.len], segment);
3639
+ len += segment.len;
3640
+ }
3641
+ const path = buffer[0..len];
3642
+ if (!pathWithinRoot(root_dir, path)) return .{ .message = import_src_escape_message };
3643
+ return .{ .path = path };
3644
+ }
3645
+
3646
+ fn pathWithinRoot(root_dir: []const u8, path: []const u8) bool {
3647
+ if (root_dir.len == 0) return true;
3648
+ if (!std.mem.startsWith(u8, path, root_dir)) return false;
3649
+ return path.len > root_dir.len and path[root_dir.len] == '/';
3650
+ }
3651
+
3652
+ fn dirnamePath(path: []const u8) []const u8 {
3653
+ const index = std.mem.lastIndexOfScalar(u8, path, '/') orelse return "";
3654
+ return path[0..index];
3655
+ }
3656
+
3657
+ // ------------------------------------------------ comptime import resolve
3658
+
3659
+ /// Comptime mirror of `resolveImports` for the compiled engine: the source
3660
+ /// mapping is an embedded set the app assembles with `@embedFile` (paths
3661
+ /// relative to the root file's directory), and every resolution failure is
3662
+ /// a compile error carrying the same teaching message the runtime resolver
3663
+ /// would report, prefixed with the offending file.
3664
+ pub fn resolveImportsComptime(comptime root_name: []const u8, comptime sources: []const SourceFile) MarkupDocument {
3665
+ comptime {
3666
+ var total_len: usize = 0;
3667
+ for (sources) |file| total_len += file.source.len;
3668
+ @setEvalBranchQuota(comptime_parse_quota_base + total_len * comptime_parse_quota_per_byte + (sources.len + 1) * 50_000);
3669
+ const root_source = findSourceComptime(sources, root_name) orelse
3670
+ @compileError("markup import: no embedded source for the root file \"" ++ root_name ++
3671
+ "\" - the source set passed to CompiledMarkupImports must contain it (.{ .path = \"" ++ root_name ++ "\", .source = @embedFile(\"" ++ root_name ++ "\") })");
3672
+ var templates: []const MarkupNode = &.{};
3673
+ var visited: []const []const u8 = &.{};
3674
+ const root = visitComptime(root_name, root_source, sources, dirnamePath(root_name), &templates, &visited, &.{});
3675
+ return .{ .imports = &.{}, .templates = templates, .root = root };
3676
+ }
3677
+ }
3678
+
3679
+ fn visitComptime(
3680
+ comptime path: []const u8,
3681
+ comptime source: []const u8,
3682
+ comptime sources: []const SourceFile,
3683
+ comptime root_dir: []const u8,
3684
+ comptime templates: *[]const MarkupNode,
3685
+ comptime visited: *[]const []const u8,
3686
+ comptime chain: []const []const u8,
3687
+ ) ?MarkupNode {
3688
+ comptime {
3689
+ const document = parseComptime(source);
3690
+ for (document.imports) |import_node| {
3691
+ if (validateImport(import_node)) |info| failResolveComptime(path, info.line, info.column, info.message);
3692
+ const src = import_node.attr("src").?;
3693
+ var buffer: [max_import_path_len]u8 = undefined;
3694
+ const resolved = switch (resolveImportPath(root_dir, path, src, &buffer)) {
3695
+ .path => |normalized| freezePathComptime(normalized),
3696
+ .message => |message| failResolveComptime(path, import_node.line, import_node.column, message),
3697
+ };
3698
+ var cycle_start: ?usize = null;
3699
+ const full_chain = chain ++ &[_][]const u8{path};
3700
+ for (full_chain, 0..) |ancestor, index| {
3701
+ if (std.mem.eql(u8, ancestor, resolved)) cycle_start = index;
3702
+ }
3703
+ if (cycle_start) |start| {
3704
+ var message: []const u8 = "import cycle: ";
3705
+ for (full_chain[start..]) |link| message = message ++ link ++ " -> ";
3706
+ failResolveComptime(path, import_node.line, import_node.column, message ++ resolved);
3707
+ }
3708
+ if (containsPathComptime(visited.*, resolved)) continue;
3709
+ if (chain.len + 1 >= max_import_depth) failResolveComptime(path, import_node.line, import_node.column, import_depth_message);
3710
+ if (visited.len >= max_imported_files) failResolveComptime(path, import_node.line, import_node.column, import_count_message);
3711
+ const child_source = findSourceComptime(sources, resolved) orelse
3712
+ @compileError("markup import: no embedded source for \"" ++ resolved ++
3713
+ "\" (imported by " ++ path ++ ") - add .{ .path = \"" ++ resolved ++ "\", .source = @embedFile(\"" ++ resolved ++ "\") } to the markup source set");
3714
+ _ = visitComptime(resolved, child_source, sources, root_dir, templates, visited, full_chain);
3715
+ visited.* = visited.* ++ &[_][]const u8{resolved};
3716
+ }
3717
+ for (document.templates) |template_node| {
3718
+ if (templates.len >= max_document_templates) {
3719
+ failResolveComptime(path, template_node.line, template_node.column, max_templates_message);
3720
+ }
3721
+ if (template_node.attr("name")) |name| {
3722
+ for (templates.*) |existing| {
3723
+ const existing_name = existing.attr("name") orelse continue;
3724
+ if (std.mem.eql(u8, existing_name, name)) {
3725
+ failResolveComptime(path, template_node.line, template_node.column, std.fmt.comptimePrint(
3726
+ "duplicate template name \"{s}\" - also defined at {s}:{d}:{d}; template names are document-wide once imports resolve, so rename one (imports never shadow silently)",
3727
+ .{ name, existing.src_path, existing.line, existing.column },
3728
+ ));
3729
+ }
3730
+ }
3731
+ }
3732
+ templates.* = templates.* ++ &[_]MarkupNode{stampSourcePathComptime(template_node, path)};
3733
+ }
3734
+ if (document.root) |root_node| {
3735
+ if (chain.len > 0) {
3736
+ failResolveComptime(path, root_node.line, root_node.column, import_view_root_message);
3737
+ }
3738
+ return stampSourcePathComptime(root_node, path);
3739
+ }
3740
+ return null;
3741
+ }
3742
+ }
3743
+
3744
+ fn findSourceComptime(comptime sources: []const SourceFile, comptime path: []const u8) ?[]const u8 {
3745
+ comptime {
3746
+ for (sources) |file| {
3747
+ if (std.mem.eql(u8, file.path, path)) return file.source;
3748
+ }
3749
+ return null;
3750
+ }
3751
+ }
3752
+
3753
+ fn containsPathComptime(comptime paths: []const []const u8, comptime path: []const u8) bool {
3754
+ comptime {
3755
+ for (paths) |candidate| {
3756
+ if (std.mem.eql(u8, candidate, path)) return true;
3757
+ }
3758
+ return false;
3759
+ }
3760
+ }
3761
+
3762
+ /// Copy a buffer-backed comptime path into interned comptime memory (the
3763
+ /// scratch buffer it slices is mutated by the next resolution).
3764
+ fn freezePathComptime(comptime path: []const u8) []const u8 {
3765
+ comptime {
3766
+ var out: [path.len]u8 = undefined;
3767
+ @memcpy(&out, path);
3768
+ const frozen = out;
3769
+ return &frozen;
3770
+ }
3771
+ }
3772
+
3773
+ fn stampSourcePathComptime(comptime node: MarkupNode, comptime path: []const u8) MarkupNode {
3774
+ comptime {
3775
+ if (path.len == 0) return node;
3776
+ var out = node;
3777
+ out.src_path = path;
3778
+ if (node.children.len > 0) {
3779
+ var children: []const MarkupNode = &.{};
3780
+ for (node.children) |child| {
3781
+ children = children ++ &[_]MarkupNode{stampSourcePathComptime(child, path)};
3782
+ }
3783
+ out.children = children;
3784
+ }
3785
+ return out;
3786
+ }
3787
+ }
3788
+
3789
+ fn failResolveComptime(comptime path: []const u8, comptime line: usize, comptime column: usize, comptime message: []const u8) noreturn {
3790
+ @compileError(std.fmt.comptimePrint("markup error in {s} at line {d}, column {d}: {s}", .{ path, line, column, message }));
3791
+ }