@momo-kits/native-kits 0.169.13-beta.4 → 0.169.13-beta.4-debug

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 (164) hide show
  1. package/build.gradle.kts +11 -0
  2. package/compose/build.gradle.kts +202 -0
  3. package/compose/compose.podspec +47 -0
  4. package/compose/src/androidMain/kotlin/vn/momo/kits/const/HostFont.android.kt +19 -0
  5. package/compose/src/androidMain/kotlin/vn/momo/kits/navigation/ScrollToTop.android.kt +6 -0
  6. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/BackGesture.android.kt +12 -0
  7. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/OsFontScale.android.kt +7 -0
  8. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/Platform.android.kt +154 -0
  9. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/ReduceMotion.android.kt +17 -0
  10. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/ReservedRegions.android.kt +6 -0
  11. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiActionsTest.kt +647 -0
  12. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiExprTest.kt +1411 -0
  13. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiHostTest.kt +130 -0
  14. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiKitArgsTest.kt +524 -0
  15. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiKitNodesTest.kt +559 -0
  16. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRenderPlanTest.kt +741 -0
  17. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRenderReuseTest.kt +221 -0
  18. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRendererPropsTest.kt +270 -0
  19. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiStylePlanTest.kt +849 -0
  20. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiStyleTest.kt +212 -0
  21. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiTrackingTest.kt +239 -0
  22. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiViewTest.kt +252 -0
  23. package/compose/src/commonMain/kotlin/vn/momo/kits/application/Context.kt +110 -0
  24. package/compose/src/commonMain/kotlin/vn/momo/kits/application/DesignSystemKits.kt +61 -0
  25. package/compose/src/commonMain/kotlin/vn/momo/kits/application/LiteScreen.kt +1067 -0
  26. package/compose/src/commonMain/kotlin/vn/momo/kits/application/Localize.kt +268 -0
  27. package/compose/src/commonMain/kotlin/vn/momo/kits/application/WidgetContainer.kt +56 -0
  28. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Avatar.kt +157 -0
  29. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Badge.kt +81 -0
  30. package/compose/src/commonMain/kotlin/vn/momo/kits/components/BadgeDot.kt +32 -0
  31. package/compose/src/commonMain/kotlin/vn/momo/kits/components/BadgeRibbon.kt +338 -0
  32. package/compose/src/commonMain/kotlin/vn/momo/kits/components/BaselineView.kt +175 -0
  33. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Button.kt +354 -0
  34. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Carousel.kt +115 -0
  35. package/compose/src/commonMain/kotlin/vn/momo/kits/components/CheckBox.kt +89 -0
  36. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Chip.kt +130 -0
  37. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Collapse.kt +209 -0
  38. package/compose/src/commonMain/kotlin/vn/momo/kits/components/CupertinoOverscroll.kt +482 -0
  39. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Divider.kt +49 -0
  40. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Icon.kt +86 -0
  41. package/compose/src/commonMain/kotlin/vn/momo/kits/components/IconButton.kt +125 -0
  42. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Image.kt +224 -0
  43. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Information.kt +137 -0
  44. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Input.kt +473 -0
  45. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputDropDown.kt +113 -0
  46. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputMoney.kt +262 -0
  47. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputOTP.kt +237 -0
  48. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputPhoneNumber.kt +228 -0
  49. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputSearch.kt +280 -0
  50. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputTextArea.kt +183 -0
  51. package/compose/src/commonMain/kotlin/vn/momo/kits/components/LazyColumnWithBouncing.kt +342 -0
  52. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Loader.kt +108 -0
  53. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationDot.kt +56 -0
  54. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationNumber.kt +40 -0
  55. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationScroll.kt +82 -0
  56. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationWhiteDot.kt +39 -0
  57. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PopupNotify.kt +362 -0
  58. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PopupPromotion.kt +108 -0
  59. package/compose/src/commonMain/kotlin/vn/momo/kits/components/ProgressInfo.kt +304 -0
  60. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Radio.kt +59 -0
  61. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Rating.kt +87 -0
  62. package/compose/src/commonMain/kotlin/vn/momo/kits/components/ScaleSizeScope.kt +21 -0
  63. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Skeleton.kt +88 -0
  64. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Slider.kt +308 -0
  65. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Stepper.kt +218 -0
  66. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Steps.kt +456 -0
  67. package/compose/src/commonMain/kotlin/vn/momo/kits/components/SuggestAction.kt +122 -0
  68. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Swipe.kt +205 -0
  69. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Switch.kt +89 -0
  70. package/compose/src/commonMain/kotlin/vn/momo/kits/components/TabView.kt +542 -0
  71. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Tag.kt +86 -0
  72. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Text.kt +175 -0
  73. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Title.kt +201 -0
  74. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Tooltip.kt +498 -0
  75. package/compose/src/commonMain/kotlin/vn/momo/kits/components/TrustBanner.kt +176 -0
  76. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Uploader.kt +182 -0
  77. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/DateTimePicker.kt +193 -0
  78. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/DateTimePickerTypes.kt +29 -0
  79. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/DateTimePickerUtils.kt +208 -0
  80. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/WheelPicker.kt +180 -0
  81. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Colors.kt +325 -0
  82. package/compose/src/commonMain/kotlin/vn/momo/kits/const/HostFont.kt +12 -0
  83. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Radius.kt +12 -0
  84. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Spacing.kt +16 -0
  85. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Theme.kt +194 -0
  86. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Typography.kt +291 -0
  87. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/Card.kt +54 -0
  88. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/HeaderLayout.kt +71 -0
  89. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/Item.kt +50 -0
  90. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/ModalLayout.kt +184 -0
  91. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/ScreenLayout.kt +315 -0
  92. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/Section.kt +41 -0
  93. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/AutomationId.kt +54 -0
  94. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Clickable.kt +66 -0
  95. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Conditional.kt +11 -0
  96. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/DeprecatedModifier.kt +104 -0
  97. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Shadow.kt +48 -0
  98. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Size.kt +51 -0
  99. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/BottomSheet.kt +397 -0
  100. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/HostBackGestureBridge.kt +58 -0
  101. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/ModalScreen.kt +153 -0
  102. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/Navigation.kt +118 -0
  103. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/NavigationContainer.kt +206 -0
  104. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/Navigator.kt +421 -0
  105. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/ScrollToTop.kt +8 -0
  106. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/StackScreen.kt +750 -0
  107. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/StackTransition.kt +152 -0
  108. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/SwipeBackHaptic.kt +35 -0
  109. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/BottomTab.kt +242 -0
  110. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/BottomTabBar.kt +398 -0
  111. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/CurvedContainer.kt +103 -0
  112. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/DuoBarCompression.kt +93 -0
  113. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/DuoTabBar.kt +208 -0
  114. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/TabBarMetrics.kt +133 -0
  115. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/FloatingButton.kt +167 -0
  116. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/Header.kt +446 -0
  117. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderBackground.kt +105 -0
  118. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderJourney.kt +106 -0
  119. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderLocation.kt +74 -0
  120. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderRight.kt +400 -0
  121. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderTitle.kt +39 -0
  122. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderUser.kt +363 -0
  123. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/SideBar.kt +197 -0
  124. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/SnackBar.kt +133 -0
  125. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/tracking/ScreenTracker.kt +127 -0
  126. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/BackGesture.kt +12 -0
  127. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/ComposeLottieAnimation.kt +114 -0
  128. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/OsFontScale.kt +7 -0
  129. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/Platform.kt +76 -0
  130. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/ReduceMotion.kt +7 -0
  131. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/ReservedRegions.kt +21 -0
  132. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiActions.kt +154 -0
  133. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiExpr.kt +1038 -0
  134. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiKitNodes.kt +848 -0
  135. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiLog.kt +47 -0
  136. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiModel.kt +39 -0
  137. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiPropsRenderer.kt +463 -0
  138. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiRenderer.kt +1146 -0
  139. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiStyle.kt +667 -0
  140. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiTracking.kt +240 -0
  141. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiValidate.kt +185 -0
  142. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiView.kt +200 -0
  143. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Icons.kt +1329 -0
  144. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Resources.kt +55 -0
  145. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Tracking.kt +15 -0
  146. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Utils.kt +117 -0
  147. package/compose/src/iosMain/kotlin/vn/momo/kits/const/HostFont.ios.kt +42 -0
  148. package/compose/src/iosMain/kotlin/vn/momo/kits/navigation/HostBackGesture.ios.kt +45 -0
  149. package/compose/src/iosMain/kotlin/vn/momo/kits/navigation/ScrollToTop.ios.kt +32 -0
  150. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/BackGesture.ios.kt +38 -0
  151. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/OsFontScale.ios.kt +65 -0
  152. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/Platform.ios.kt +217 -0
  153. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/ReduceMotion.ios.kt +48 -0
  154. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/ReservedRegions.ios.kt +143 -0
  155. package/gradle/libs.versions.toml +69 -0
  156. package/gradle/wrapper/gradle-wrapper.jar +0 -0
  157. package/gradle/wrapper/gradle-wrapper.properties +8 -0
  158. package/gradle.properties +24 -0
  159. package/gradlew +252 -0
  160. package/gradlew.bat +94 -0
  161. package/ios-demo/README.md +120 -0
  162. package/package.json +1 -1
  163. package/scripts/sdui-visual/README.md +64 -0
  164. package/settings.gradle.kts +64 -0
@@ -0,0 +1,1038 @@
1
+ // File: compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiExpr.kt
2
+ // Created At: 2026-10-27 12:00:00 +07:00
3
+ // Created By: AI
4
+ // AI Agent: Claude Code
5
+ // Model: claude-sonnet-5-5
6
+
7
+ package vn.momo.kits.sdui
8
+
9
+ import kotlinx.serialization.json.JsonArray
10
+ import kotlinx.serialization.json.JsonElement
11
+ import kotlinx.serialization.json.JsonNull
12
+ import kotlinx.serialization.json.JsonObject
13
+ import kotlinx.serialization.json.JsonPrimitive
14
+
15
+ internal const val SDUI_TAG = "SDUI_NATIVE"
16
+
17
+ // AI-GENERATED START: SDUI spec model (generic) + expression evaluator (JavaScript expression semantics)
18
+ /** Converts a parsed JSON tree into plain Kotlin values: Map / List / String / Long / Double / Boolean / null. */
19
+ internal fun JsonElement.toPlain(): Any? = when (this) {
20
+ is JsonNull -> null
21
+ is JsonObject -> LinkedHashMap<String, Any?>().also { m -> forEach { (k, v) -> m[k] = v.toPlain() } }
22
+ is JsonArray -> map { it.toPlain() }
23
+ is JsonPrimitive -> when {
24
+ isString -> content
25
+ content == "true" -> true
26
+ content == "false" -> false
27
+ else -> content.toLongOrNull() ?: content.toDoubleOrNull()
28
+ }
29
+ }
30
+
31
+ @Suppress("UNCHECKED_CAST")
32
+ internal fun Any?.asMap(): Map<String, Any?>? = this as? Map<String, Any?>
33
+
34
+ @Suppress("UNCHECKED_CAST")
35
+ internal fun Any?.asList(): List<Any?>? = this as? List<Any?>
36
+
37
+ internal const val NODE_ERR_EXPR_FAILED = "expr_failed"
38
+ internal const val NODE_ERR_UNKNOWN_TOKEN = "unknown_token"
39
+
40
+ /**
41
+ * Attributes failures that happen deep in value resolution (no node in sight) to a node. [forNode] wraps one resolution
42
+ * step of a given node at a given path, collects the codes [report]ed meanwhile and sends one `sdui_node_error` per
43
+ * distinct code (the session dedupes per node path / code / reason, so re-evaluating a node on recomposition reports once).
44
+ * The node and path are passed in by the caller — composables read the path from [LocalNodePath] — so attribution is
45
+ * right wherever Compose re-runs the code. [quiet] swallows failures (a parent probing a child's styles for layout: the
46
+ * child reports on its own render). Failures outside any wrapper are dropped.
47
+ */
48
+ internal class NodeErrorSink(private val session: () -> RenderSession = { RenderSession.NOOP }) {
49
+ // only set while a wrapped block runs synchronously on the composing thread
50
+ private var collecting: LinkedHashSet<String>? = null
51
+
52
+ fun report(code: String) { collecting?.add(code) }
53
+
54
+ private fun <T> collect(block: () -> T, send: (Set<String>) -> Unit): T {
55
+ val outer = collecting
56
+ val mine = LinkedHashSet<String>()
57
+ collecting = mine
58
+ try { return block() } finally {
59
+ collecting = outer
60
+ if (mine.isNotEmpty()) send(mine)
61
+ }
62
+ }
63
+
64
+ /** Resolution of [node]'s props / styles / `visible` / `repeat`, attributed to [path]; a null [path] is [quiet]. */
65
+ fun <T> forNode(node: Map<String, Any?>, path: String?, block: () -> T): T {
66
+ if (path == null) return quiet(block)
67
+ return collect(block) { codes -> reportCodes(node, path, codes) }
68
+ }
69
+
70
+ /** Runs [block] reporting nothing yet: its value and the failure codes it raised, to be reported later with [reportCodes]. */
71
+ fun <T> capture(block: () -> T): Pair<T, Set<String>> {
72
+ var codes: Set<String> = emptySet()
73
+ val v = collect(block) { codes = it }
74
+ return v to codes
75
+ }
76
+
77
+ /** Reports [codes] (from [capture]) on [node] at [path], exactly as [forNode] would have. */
78
+ fun reportCodes(node: Map<String, Any?>, path: String, codes: Set<String>) {
79
+ codes.forEach { reportOn(node, path, it, it) }
80
+ }
81
+
82
+ /** One `sdui_node_error` on [node] at [path] with its own [reason] (a spec key name or a fixed code, never a runtime value). */
83
+ fun reportOn(node: Map<String, Any?>, path: String, code: String, reason: String) {
84
+ session().nodeError(code, reason, path, node["type"] as? String, node["id"] as? String)
85
+ }
86
+
87
+ /** Runs [block] reporting nothing, also not to an enclosing [forNode]. */
88
+ fun <T> quiet(block: () -> T): T = collect(block) {}
89
+ }
90
+
91
+
92
+ /**
93
+ * Lookup scope: repeat locals win, then live state, then spec data. A `spec.data` value that is a whole `"{expr}"` is
94
+ * derived: it is evaluated in this scope (locals included) every time it is read, so it always reflects the current state
95
+ * and its state reads are seen by Compose. Values are memoised only for the duration of one top-level [evalExpr] on this
96
+ * scope instance ([resolution]), never across scopes or state changes.
97
+ */
98
+ internal class SduiScope(
99
+ val data: Map<String, Any?>,
100
+ val state: Map<String, Any?>,
101
+ val locals: Map<String, Any?> = emptyMap(),
102
+ val params: Map<String, Any?> = emptyMap(),
103
+ /** The owning view's logger (expression failures, unknown tokens). */
104
+ val log: SduiLog = SduiLog.NONE,
105
+ /** Collects expression / token failures so the renderer can attribute them to the node being composed. */
106
+ val nodeErrors: NodeErrorSink = NodeErrorSink(),
107
+ /** Parse cache and nesting budget, shared by this scope and every [with] copy of it (one SduiView's scope tree). */
108
+ val cx: ExprContext = ExprContext(),
109
+ ) {
110
+ private class Derived(val value: Any?, val failed: Boolean)
111
+
112
+ // Composition (and action dispatch) evaluate on one thread, so plain fields are enough.
113
+ private var memo: HashMap<String, Derived>? = null
114
+ private val evaluating = HashSet<String>()
115
+ private val dataView: Map<String, Any?> by lazy(LazyThreadSafetyMode.NONE) { DataView() }
116
+
117
+ fun with(name: String, value: Any?) = SduiScope(data, state, locals + (name to value), params, log, nodeErrors, cx)
118
+
119
+ fun lookup(name: String): Any? = when {
120
+ locals.containsKey(name) -> locals[name]
121
+ name == "state" -> state
122
+ name == "data" -> dataView
123
+ name == "params" -> params
124
+ state.containsKey(name) -> state[name]
125
+ data.containsKey(name) -> dataValue(name)
126
+ else -> null
127
+ }
128
+
129
+ internal fun <T> resolution(block: () -> T): T {
130
+ if (memo != null) return block()
131
+ memo = HashMap()
132
+ try { return block() } finally { memo = null }
133
+ }
134
+
135
+ /** Cycles (`a: "{b}", b: "{a}"`) read null; a failing key reports `expr_failed` on every read. */
136
+ private fun dataValue(name: String): Any? {
137
+ val raw = data[name]
138
+ val expr = (raw as? String)?.let(::unwrapBinding) ?: return raw
139
+ memo?.get(name)?.let { d ->
140
+ if (d.failed) nodeErrors.report(NODE_ERR_EXPR_FAILED)
141
+ return d.value
142
+ }
143
+ if (!evaluating.add(name)) return null
144
+ try {
145
+ var failed = false
146
+ val v = evalExpr(expr, this, dataKey = name) { failed = true }
147
+ memo?.put(name, Derived(v, failed))
148
+ return v
149
+ } finally {
150
+ evaluating.remove(name)
151
+ }
152
+ }
153
+
154
+ /** `data` as an expression value: reading a derived key evaluates it, like the bare name does. */
155
+ private inner class DataView : AbstractMap<String, Any?>() {
156
+ override val size: Int get() = data.size
157
+ override fun containsKey(key: String) = data.containsKey(key)
158
+ override fun get(key: String): Any? = if (data.containsKey(key)) dataValue(key) else null
159
+ override val entries: Set<Map.Entry<String, Any?>>
160
+ get() = data.keys.mapTo(LinkedHashSet()) { Entry(it, dataValue(it)) }
161
+
162
+ // printing must not evaluate: a derived value that holds `data` would print itself forever
163
+ override fun toString() = data.toString()
164
+ }
165
+
166
+ private class Entry(override val key: String, override val value: Any?) : Map.Entry<String, Any?> {
167
+ override fun equals(other: Any?) = other is Map.Entry<*, *> && other.key == key && other.value == value
168
+ override fun hashCode() = key.hashCode() xor (value?.hashCode() ?: 0)
169
+ override fun toString() = "$key=$value"
170
+ }
171
+ }
172
+
173
+ internal val INTERP_RE = Regex("\\{[^{}]*\\}")
174
+
175
+ /** `"{expr}"` (whole string) -> inner expr, else null. */
176
+ internal fun unwrapBinding(s: String): String? {
177
+ val t = s.trim()
178
+ if (t.length < 2 || t.first() != '{' || t.last() != '}') return null
179
+ val inner = t.substring(1, t.length - 1)
180
+ return if (inner.contains('{') || inner.contains('}')) null else inner
181
+ }
182
+
183
+ /** Whole-value binding keeps its raw type; embedded `{x}` in longer strings is interpolated (null -> ""). */
184
+ internal fun resolveString(s: String, scope: SduiScope): Any? {
185
+ unwrapBinding(s)?.let { return evalExpr(it, scope) }
186
+ if (INTERP_RE.containsMatchIn(s)) {
187
+ return INTERP_RE.replace(s) { m -> str(evalExpr(m.value.drop(1).dropLast(1), scope)) }
188
+ }
189
+ return s
190
+ }
191
+
192
+ /** Display text: JS ToString, except null shows as "" and a map keeps a readable `{k=v}` form. */
193
+ internal fun str(v: Any?): String = when (v) {
194
+ null -> ""
195
+ is Map<*, *> -> v.toString()
196
+ else -> jsString(v)
197
+ }
198
+
199
+ /** JS ToString (`String(x)`, `'' + x`): null -> "null", numbers in JS format, arrays joined by ",". */
200
+ internal fun jsString(v: Any?): String = when (v) {
201
+ null -> "null"
202
+ is String -> v
203
+ is Double -> numberToString(v)
204
+ is Float -> numberToString(v.toDouble())
205
+ is Number -> v.toString()
206
+ is List<*> -> v.joinToString(",") { if (it == null) "" else jsString(it) }
207
+ is Map<*, *> -> "[object Object]"
208
+ is Function<*> -> "function"
209
+ else -> v.toString()
210
+ }
211
+
212
+ internal fun truthy(v: Any?): Boolean = when (v) {
213
+ null -> false
214
+ is Boolean -> v
215
+ is String -> v.isNotEmpty()
216
+ is Long -> v != 0L
217
+ is Double -> v != 0.0 && !v.isNaN()
218
+ else -> true
219
+ }
220
+
221
+ /**
222
+ * Never throws: unsupported/invalid expressions evaluate to null. Running out of the nesting budget inside a nested
223
+ * evaluation (a derived `spec.data` key read by another expression) fails the outermost expression, not just the nested
224
+ * one, so a chain of derived keys cannot nest deeper than [MAX_DEPTH] in total.
225
+ */
226
+ internal fun evalExpr(expr: String, scope: SduiScope, dataKey: String? = null, onFail: () -> Unit = {}): Any? {
227
+ val outermost = scope.cx.depth == 0
228
+ return try {
229
+ val ast = scope.cx.parse(expr)
230
+ scope.resolution { ExprEval({ scope.lookup(it) }, scope.cx).eval(ast) }
231
+ } catch (e: Throwable) {
232
+ if (e is ExprTooDeep && !outermost) throw e
233
+ // a `spec.data` expression may have been filled with user strings by the backend: name the key, not the text
234
+ scope.log.w(if (dataKey != null) "expr failed in data.$dataKey" else "expr failed: $expr")
235
+ onFail()
236
+ scope.nodeErrors.report(NODE_ERR_EXPR_FAILED)
237
+ null
238
+ }
239
+ }
240
+
241
+ /** Nesting limit for parsing and evaluation: runaway recursion fails the expression instead of overflowing the stack (fatal on iOS). */
242
+ private const val MAX_DEPTH = 200
243
+ private const val PARSE_CACHE_SIZE = 512
244
+
245
+ internal class ExprTooDeep : IllegalStateException("expression nested too deeply")
246
+
247
+ /**
248
+ * Expression state of one SduiView's scope tree. It lives on the root [SduiScope] (remembered per spec) and is handed to
249
+ * every [SduiScope.with] copy, so it is only touched from the thread that composes and dispatches actions for that view:
250
+ * no locking, and no cache shared between views or threads.
251
+ *
252
+ * - [depth]: the current parse + eval nesting of the whole resolution, nested derived keys and arrow calls included.
253
+ * - [parse]: an LRU cache of parsed expressions (the AST is immutable), keyed by the expression text.
254
+ */
255
+ internal class ExprContext {
256
+ var depth = 0 // written only by [nested] (public so the inline function can reach it)
257
+ private val cache = LinkedHashMap<String, Ex>()
258
+
259
+ /** How many expressions were actually parsed (cache misses); for tests. */
260
+ var parses = 0
261
+ private set
262
+
263
+ fun parse(expr: String): Ex {
264
+ cache.remove(expr)?.let { cache[expr] = it; return it } // re-insert: most recently used goes last
265
+ val ast = ExprParser(expr, this).parseAll()
266
+ parses++
267
+ cache[expr] = ast
268
+ if (cache.size > PARSE_CACHE_SIZE) cache.remove(cache.keys.first())
269
+ return ast
270
+ }
271
+
272
+ inline fun <T> nested(block: () -> T): T {
273
+ if (++depth > MAX_DEPTH) { depth--; throw ExprTooDeep() }
274
+ try { return block() } finally { depth-- }
275
+ }
276
+ }
277
+
278
+ // ---- JS number semantics ---------------------------------------------------------------------------------------
279
+ // There is one nullish value: null (also for `undefined` and missing names). Operators convert it like JS null
280
+ // (`null + 1` = 1, `null >= 0`), and a null passed as an optional argument behaves as if it was omitted.
281
+
282
+ private const val TWO_53 = 9007199254740992.0
283
+
284
+ /** Integral results below 2^53 are Longs (exact, JS safe-integer range); everything else stays Double. */
285
+ internal fun norm(d: Double): Any = if (d % 1.0 == 0.0 && kotlin.math.abs(d) < TWO_53) d.toLong() else d
286
+
287
+ private fun isJsSpace(c: Char) = c == ' ' || c in '\t'..'\r' || c == ' ' || c == ' ' ||
288
+ c in ' '..' ' || c == '
' || c == '
' || c == ' ' || c == ' ' || c == ' ' || c == ''
289
+
290
+ internal fun jsTrim(s: String) = s.trim(::isJsSpace)
291
+
292
+ private val DECIMAL_RE = Regex("[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?")
293
+ private val FLOAT_PREFIX_RE = Regex("^[+-]?(?:Infinity|(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?)")
294
+
295
+ private fun digitOf(c: Char): Int = when (c) {
296
+ in '0'..'9' -> c - '0'
297
+ in 'a'..'z' -> c - 'a' + 10
298
+ in 'A'..'Z' -> c - 'A' + 10
299
+ else -> 99
300
+ }
301
+
302
+ private fun radixValue(digits: String, radix: Int): Double {
303
+ if (radix == 10) return digits.toDouble()
304
+ var v = 0.0
305
+ for (c in digits) v = v * radix + digitOf(c)
306
+ return v
307
+ }
308
+
309
+ /** JS ToNumber. */
310
+ internal fun toNumber(v: Any?): Double = when (v) {
311
+ null -> 0.0
312
+ is Boolean -> if (v) 1.0 else 0.0
313
+ is Number -> v.toDouble()
314
+ is String -> stringToNumber(v)
315
+ is List<*> -> stringToNumber(jsString(v))
316
+ else -> Double.NaN
317
+ }
318
+
319
+ private fun stringToNumber(s: String): Double {
320
+ val t = jsTrim(s)
321
+ if (t.isEmpty()) return 0.0
322
+ when (t) {
323
+ "Infinity", "+Infinity" -> return Double.POSITIVE_INFINITY
324
+ "-Infinity" -> return Double.NEGATIVE_INFINITY
325
+ }
326
+ if (t.length > 2 && t[0] == '0') {
327
+ val radix = when (t[1]) { 'x', 'X' -> 16; 'o', 'O' -> 8; 'b', 'B' -> 2; else -> 0 }
328
+ if (radix != 0) {
329
+ val body = t.substring(2)
330
+ return if (body.all { digitOf(it) < radix }) radixValue(body, radix) else Double.NaN
331
+ }
332
+ }
333
+ return if (DECIMAL_RE.matches(t)) t.toDouble() else Double.NaN
334
+ }
335
+
336
+ /** JS ToIntegerOrInfinity: NaN -> 0, else truncated toward zero. */
337
+ private fun toInteger(d: Double): Double = if (d.isNaN()) 0.0 else kotlin.math.truncate(d)
338
+
339
+ private fun toUint32(d: Double): Long {
340
+ if (d.isNaN() || d.isInfinite()) return 0L
341
+ val m = kotlin.math.truncate(d) % 4294967296.0
342
+ return (if (m < 0) m + 4294967296.0 else m).toLong()
343
+ }
344
+
345
+ private fun toInt32(d: Double): Int {
346
+ val u = toUint32(d)
347
+ return (if (u >= 2147483648L) u - 4294967296L else u).toInt()
348
+ }
349
+
350
+ /** JS `parseInt(string, radix)`: prefix parse after leading whitespace, `0x` prefix for radix 0/16. */
351
+ internal fun jsParseInt(input: Any?, radixArg: Any?): Double {
352
+ var s = jsTrim(jsString(input))
353
+ var sign = 1.0
354
+ if (s.startsWith('-')) { sign = -1.0; s = s.substring(1) } else if (s.startsWith('+')) s = s.substring(1)
355
+ var radix = if (radixArg == null) 0 else toInt32(toNumber(radixArg))
356
+ var stripPrefix = true
357
+ if (radix != 0) {
358
+ if (radix < 2 || radix > 36) return Double.NaN
359
+ if (radix != 16) stripPrefix = false
360
+ } else radix = 10
361
+ if (stripPrefix && s.length >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) { s = s.substring(2); radix = 16 }
362
+ val end = s.indexOfFirst { digitOf(it) >= radix }.let { if (it < 0) s.length else it }
363
+ if (end == 0) return Double.NaN
364
+ return sign * radixValue(s.substring(0, end), radix)
365
+ }
366
+
367
+ /** JS `parseFloat(string)`: the longest decimal-literal prefix after leading whitespace. */
368
+ internal fun jsParseFloat(input: Any?): Double {
369
+ val m = FLOAT_PREFIX_RE.find(jsTrim(jsString(input)))?.value ?: return Double.NaN
370
+ return when {
371
+ m.endsWith("Infinity") -> if (m.startsWith('-')) Double.NEGATIVE_INFINITY else Double.POSITIVE_INFINITY
372
+ else -> m.toDouble()
373
+ }
374
+ }
375
+
376
+ /** JS Number::toString (radix 10). The shortest round-trip digits come from the platform's Double.toString. */
377
+ internal fun numberToString(d: Double): String {
378
+ if (d.isNaN()) return "NaN"
379
+ if (d == 0.0) return "0"
380
+ if (d.isInfinite()) return if (d > 0) "Infinity" else "-Infinity"
381
+ val s = kotlin.math.abs(d).toString()
382
+ val ePos = s.indexOfFirst { it == 'E' || it == 'e' }
383
+ val mant = if (ePos < 0) s else s.substring(0, ePos)
384
+ val exp = if (ePos < 0) 0 else s.substring(ePos + 1).toInt()
385
+ val dot = mant.indexOf('.')
386
+ val intPart = if (dot < 0) mant else mant.substring(0, dot)
387
+ var digits = intPart + (if (dot < 0) "" else mant.substring(dot + 1))
388
+ var n = intPart.length + exp // value = 0.<digits> x 10^n
389
+ val lead = digits.indexOfFirst { it != '0' }
390
+ digits = digits.substring(lead).trimEnd('0')
391
+ n -= lead
392
+ // JDK 17's Double.toString can emit a non-shortest 17-digit form (and "4.9E-324"): keep the shortest that round-trips
393
+ if (digits.length >= 16 || kotlin.math.abs(d) < 2.2250738585072014E-308) {
394
+ val x = kotlin.math.abs(d)
395
+ for (p in 1 until digits.length) {
396
+ val (r, carry) = roundDigits(digits, p)
397
+ if ("${r}e${n + carry - r.length}".toDouble() == x) { digits = r.trimEnd('0'); n += carry; break }
398
+ }
399
+ }
400
+ val k = digits.length
401
+ val body = when {
402
+ n in k..21 -> digits + "0".repeat(n - k)
403
+ n in 1..21 -> digits.substring(0, n) + "." + digits.substring(n)
404
+ n in -5..0 -> "0." + "0".repeat(-n) + digits
405
+ else -> {
406
+ val e = n - 1
407
+ val es = if (e < 0) "-${-e}" else "+$e"
408
+ (if (k == 1) digits else digits[0] + "." + digits.substring(1)) + "e" + es
409
+ }
410
+ }
411
+ return if (d < 0) "-$body" else body
412
+ }
413
+
414
+ /** [digits] rounded half-up to [p] digits; the second value is 1 when rounding carried into a new leading digit. */
415
+ private fun roundDigits(digits: String, p: Int): Pair<String, Int> {
416
+ val head = digits.substring(0, p).toCharArray()
417
+ if (digits[p] >= '5') {
418
+ var i = p - 1
419
+ while (i >= 0 && head[i] == '9') { head[i] = '0'; i-- }
420
+ if (i < 0) return ("1" + head.concatToString()).dropLast(1) to 1
421
+ head[i] = head[i] + 1
422
+ }
423
+ return head.concatToString() to 0
424
+ }
425
+
426
+ /**
427
+ * ECMAScript Number.prototype.toFixed on the double's exact binary value: ties round up (away from zero), so
428
+ * `(1.45).toFixed(1)` = "1.4" (1.45 is 1.4499999...), and a negative value that rounds to zero keeps its sign ("-0.00").
429
+ */
430
+ internal fun toFixed(v: Double, digits: Int): String {
431
+ require(digits in 0..100) { "toFixed() digits out of range" }
432
+ if (v.isNaN()) return "NaN"
433
+ if (kotlin.math.abs(v) >= 1e21) return numberToString(v)
434
+ val x = kotlin.math.abs(v)
435
+ val bits = x.toRawBits()
436
+ val expField = ((bits ushr 52) and 0x7FF).toInt()
437
+ val fraction = bits and 0xFFFFFFFFFFFFFL
438
+ val mantissa = if (expField == 0) fraction else fraction or (1L shl 52)
439
+ val exp = if (expField == 0) -1074 else expField - 1075
440
+ // n = round(mantissa * 2^exp * 10^digits)
441
+ val n = BigNat(mantissa)
442
+ repeat(digits) { n.mulAdd(10, 0) }
443
+ if (exp >= 0) n.shl(exp) else {
444
+ val up = n.testBit(-exp - 1)
445
+ n.shr(-exp)
446
+ if (up) n.mulAdd(1, 1)
447
+ }
448
+ var s = n.toDecimal()
449
+ if (digits > 0) {
450
+ if (s.length <= digits) s = s.padStart(digits + 1, '0')
451
+ s = s.dropLast(digits) + "." + s.takeLast(digits)
452
+ }
453
+ return if (v < 0) "-$s" else s
454
+ }
455
+
456
+ /** Minimal unsigned big integer (little-endian 32-bit words) for [toFixed]. */
457
+ private class BigNat(v: Long) {
458
+ private val w = ArrayList<Long>()
459
+
460
+ init {
461
+ var x = v
462
+ while (x != 0L) { w += x and MASK; x = x ushr 32 }
463
+ }
464
+
465
+ fun mulAdd(k: Long, add: Long) {
466
+ var carry = add
467
+ for (i in w.indices) {
468
+ val t = w[i] * k + carry
469
+ w[i] = t and MASK; carry = t ushr 32
470
+ }
471
+ while (carry != 0L) { w += carry and MASK; carry = carry ushr 32 }
472
+ }
473
+
474
+ fun shl(bits: Int) {
475
+ val bs = bits % 32
476
+ if (bs != 0) {
477
+ var carry = 0L
478
+ for (i in w.indices) {
479
+ val t = w[i] shl bs
480
+ w[i] = (t and MASK) or carry; carry = t ushr 32
481
+ }
482
+ if (carry != 0L) w += carry
483
+ }
484
+ repeat(bits / 32) { w.add(0, 0L) }
485
+ }
486
+
487
+ fun shr(bits: Int) {
488
+ val ws = bits / 32
489
+ if (ws >= w.size) { w.clear(); return }
490
+ repeat(ws) { w.removeAt(0) }
491
+ val bs = bits % 32
492
+ if (bs != 0) {
493
+ for (i in w.indices) {
494
+ val hi = if (i + 1 < w.size) w[i + 1] else 0L
495
+ w[i] = ((w[i] ushr bs) or (hi shl (32 - bs))) and MASK
496
+ }
497
+ }
498
+ while (w.isNotEmpty() && w.last() == 0L) w.removeAt(w.size - 1)
499
+ }
500
+
501
+ fun testBit(i: Int): Boolean {
502
+ val wi = i / 32
503
+ return wi < w.size && ((w[wi] ushr (i % 32)) and 1L) == 1L
504
+ }
505
+
506
+ fun toDecimal(): String {
507
+ val a = ArrayList(w)
508
+ while (a.isNotEmpty() && a.last() == 0L) a.removeAt(a.size - 1)
509
+ if (a.isEmpty()) return "0"
510
+ val chunks = ArrayList<Long>()
511
+ while (a.isNotEmpty()) {
512
+ var rem = 0L
513
+ for (i in a.indices.reversed()) {
514
+ val cur = (rem shl 32) or a[i]
515
+ a[i] = cur / 1_000_000_000L; rem = cur % 1_000_000_000L
516
+ }
517
+ chunks += rem
518
+ while (a.isNotEmpty() && a.last() == 0L) a.removeAt(a.size - 1)
519
+ }
520
+ val sb = StringBuilder(chunks.last().toString())
521
+ for (i in chunks.size - 2 downTo 0) sb.append(chunks[i].toString().padStart(9, '0'))
522
+ return sb.toString()
523
+ }
524
+
525
+ private companion object { const val MASK = 0xFFFFFFFFL }
526
+ }
527
+
528
+ private fun isObject(v: Any?) = v is List<*> || v is Map<*, *> || v is Function<*>
529
+
530
+ /** JS ToPrimitive: arrays / objects / functions become their string form. */
531
+ private fun toPrimitive(v: Any?): Any? = if (isObject(v)) jsString(v) else v
532
+
533
+ /** JS `===` (lists / maps / functions by reference). */
534
+ internal fun strictEquals(a: Any?, b: Any?): Boolean = when {
535
+ a is Number && b is Number -> a.toDouble() == b.toDouble()
536
+ a == null || b == null -> a == null && b == null
537
+ a is String && b is String -> a == b
538
+ a is Boolean && b is Boolean -> a == b
539
+ else -> a === b
540
+ }
541
+
542
+ /** JS `==` (IsLooselyEqual). */
543
+ internal fun looseEquals(a: Any?, b: Any?): Boolean = when {
544
+ a == null || b == null -> a == null && b == null
545
+ (a is Number && b is Number) || (a is String && b is String) || (a is Boolean && b is Boolean) ||
546
+ (isObject(a) && isObject(b)) -> strictEquals(a, b)
547
+ a is Boolean -> looseEquals(toNumber(a), b)
548
+ b is Boolean -> looseEquals(a, toNumber(b))
549
+ a is Number && b is String -> a.toDouble() == toNumber(b)
550
+ a is String && b is Number -> toNumber(a) == b.toDouble()
551
+ isObject(a) -> looseEquals(toPrimitive(a), b)
552
+ isObject(b) -> looseEquals(a, toPrimitive(b))
553
+ else -> false
554
+ }
555
+
556
+ private fun sameValueZero(a: Any?, b: Any?): Boolean =
557
+ strictEquals(a, b) || (a is Number && b is Number && a.toDouble().isNaN() && b.toDouble().isNaN())
558
+
559
+ /** JS abstract relational comparison: two strings compare by UTF-16 code units, anything else numerically (NaN -> false). */
560
+ private fun relational(op: String, l: Any?, r: Any?): Boolean {
561
+ val a = toPrimitive(l)
562
+ val b = toPrimitive(r)
563
+ if (a is String && b is String) {
564
+ val c = a.compareTo(b)
565
+ return when (op) { "<" -> c < 0; ">" -> c > 0; "<=" -> c <= 0; else -> c >= 0 }
566
+ }
567
+ val x = toNumber(a)
568
+ val y = toNumber(b)
569
+ return when (op) { "<" -> x < y; ">" -> x > y; "<=" -> x <= y; else -> x >= y }
570
+ }
571
+
572
+ private fun jsRound(x: Double): Double {
573
+ if (x.isNaN() || x.isInfinite()) return x
574
+ val f = kotlin.math.floor(x)
575
+ return if (x - f >= 0.5) f + 1 else f
576
+ }
577
+
578
+ // ---- AST -------------------------------------------------------------------------------------------------------
579
+ internal sealed interface Ex {
580
+ data class Lit(val v: Any?) : Ex
581
+ data class Id(val name: String) : Ex
582
+ data class Mem(val obj: Ex, val name: String) : Ex
583
+ data class Idx(val obj: Ex, val index: Ex) : Ex
584
+ data class Call(val callee: Ex, val args: List<Ex>) : Ex
585
+ data class Un(val op: String, val arg: Ex) : Ex
586
+ data class Bin(val op: String, val l: Ex, val r: Ex) : Ex
587
+ data class Tern(val c: Ex, val a: Ex, val b: Ex) : Ex
588
+ data class Arr(val items: List<Ex>) : Ex
589
+ data class Arrow(val params: List<String>, val body: Ex) : Ex
590
+ }
591
+
592
+ private val PUNCT = listOf(
593
+ "===", "!==", "==", "!=", "<=", ">=", "&&", "||", "=>", "??", "?.",
594
+ "<", ">", "+", "-", "*", "/", "%", "!", "(", ")", "[", "]", ".", ",", "?", ":",
595
+ )
596
+
597
+ private data class Tok(val t: String, val v: Any? = null)
598
+
599
+ /** Token kinds after which `.` is member access, not the start of a decimal (`a.5` vs `.5`). */
600
+ private val VALUE_TOKS = setOf("id", "num", "str", ")", "]")
601
+
602
+ /** A string literal from [start] (the opening quote); returns its value and the index after the closing quote. */
603
+ private fun stringLiteral(src: String, start: Int): Pair<String, Int> {
604
+ val q = src[start]
605
+ val sb = StringBuilder()
606
+ var j = start + 1
607
+ while (true) {
608
+ if (j >= src.length) throw IllegalStateException("unterminated string")
609
+ val c = src[j++]
610
+ if (c == q) return sb.toString() to j
611
+ if (c != '\\') { sb.append(c); continue }
612
+ if (j >= src.length) throw IllegalStateException("unterminated string")
613
+ when (val e = src[j++]) {
614
+ 'n' -> sb.append('\n'); 't' -> sb.append('\t'); 'r' -> sb.append('\r')
615
+ 'b' -> sb.append('\b'); 'f' -> sb.append('\u000C'); 'v' -> sb.append('\u000B')
616
+ '0' -> sb.append('\u0000')
617
+ // no `\u{...}` code-point form: a `{` inside an expression's string ends the `{binding}` early, so a spec could never use it
618
+ 'x', 'u' -> {
619
+ val n = if (e == 'x') 2 else 4
620
+ val hex = src.substring(j, minOf(j + n, src.length))
621
+ if (hex.length != n || !hex.all { digitOf(it) < 16 }) throw IllegalStateException("bad escape")
622
+ sb.append(hex.toInt(16).toChar()); j += n
623
+ }
624
+ '\r' -> if (src.getOrNull(j) == '\n') j++ // line continuation
625
+ '\n', '\u2028', '\u2029' -> Unit
626
+ else -> sb.append(e) // \' \" \\ and any other char stand for themselves
627
+ }
628
+ }
629
+ }
630
+
631
+ /** Length of a valid exponent part (`e3`, `E-2`) starting at [i], else 0. */
632
+ private fun expAt(src: String, i: Int): Int {
633
+ if (src.getOrNull(i) != 'e' && src.getOrNull(i) != 'E') return 0
634
+ var k = i + 1
635
+ if (src.getOrNull(k) == '+' || src.getOrNull(k) == '-') k++
636
+ return if (src.getOrNull(k)?.isDigit() == true) k - i + 1 else 0
637
+ }
638
+
639
+ private fun tokenize(src: String): List<Tok> {
640
+ val out = ArrayList<Tok>()
641
+ var i = 0
642
+ while (i < src.length) {
643
+ val c = src[i]
644
+ if (c.isWhitespace()) { i++; continue }
645
+ if (c == '"' || c == '\'' || c == '`') {
646
+ val (v, next) = stringLiteral(src, i)
647
+ out += Tok("str", v); i = next; continue
648
+ }
649
+ val prev = out.lastOrNull()
650
+ val afterValue = prev != null && prev.t in VALUE_TOKS
651
+ // right after a `.` member access only an integer segment is read: `rows.0.1` is rows[0][1], not rows[0.1]
652
+ if (c.isDigit() && prev?.t == ".") {
653
+ var j = i
654
+ while (j < src.length && src[j].isDigit()) j++
655
+ out += Tok("id", src.substring(i, j)); i = j; continue
656
+ }
657
+ if (c.isDigit() || (c == '.' && !afterValue && src.getOrNull(i + 1)?.isDigit() == true)) {
658
+ var j = i
659
+ if (c == '.') j++
660
+ while (j < src.length && src[j].isDigit()) j++
661
+ if (c != '.' && src.getOrNull(j) == '.') {
662
+ val after = src.getOrNull(j + 1)
663
+ // `1.5`; also `1.` and `1.e3` (JS), but not `flights.0.x` (member access) nor `1.toFixed` (an error in JS)
664
+ val bareDot = after == null || !(after.isLetter() || after == '_' || after == '$') ||
665
+ (after.lowercaseChar() == 'e' && expAt(src, j + 1) > 0)
666
+ if (after?.isDigit() == true || bareDot) {
667
+ j++
668
+ while (j < src.length && src[j].isDigit()) j++
669
+ }
670
+ }
671
+ if (src.getOrNull(j) == 'e' || src.getOrNull(j) == 'E') {
672
+ var k = j + 1
673
+ if (src.getOrNull(k) == '+' || src.getOrNull(k) == '-') k++
674
+ if (src.getOrNull(k)?.isDigit() == true) {
675
+ j = k
676
+ while (j < src.length && src[j].isDigit()) j++
677
+ }
678
+ }
679
+ val t = src.substring(i, j).replace(".e", "e").replace(".E", "E").removeSuffix(".")
680
+ out += Tok("num", t.toLongOrNull() ?: norm(t.toDouble())); i = j; continue
681
+ }
682
+ if (c.isLetter() || c == '_' || c == '$') {
683
+ var j = i
684
+ while (j < src.length && (src[j].isLetterOrDigit() || src[j] == '_' || src[j] == '$')) j++
685
+ when (val w = src.substring(i, j)) {
686
+ "true" -> out += Tok("lit", true)
687
+ "false" -> out += Tok("lit", false)
688
+ "null", "undefined" -> out += Tok("lit", null)
689
+ else -> out += Tok("id", w)
690
+ }
691
+ i = j; continue
692
+ }
693
+ var p = PUNCT.firstOrNull { src.startsWith(it, i) } ?: throw IllegalStateException("bad char '$c' at $i")
694
+ // `?.` followed by a digit is `?` + a decimal (`c ?.5 : 1`), as in JS
695
+ if (p == "?." && src.getOrNull(i + 2)?.isDigit() == true) p = "?"
696
+ out += Tok(p); i += p.length
697
+ }
698
+ return out
699
+ }
700
+
701
+ private val BIN_PREC = mapOf(
702
+ "??" to 1, "||" to 2, "&&" to 3,
703
+ "==" to 4, "===" to 4, "!=" to 4, "!==" to 4,
704
+ "<" to 5, ">" to 5, "<=" to 5, ">=" to 5,
705
+ "+" to 6, "-" to 6, "*" to 7, "/" to 7, "%" to 7,
706
+ )
707
+
708
+ /** Grammar: ternary, ??, ||, &&, equality, relational, + - * / %, !, -, member/index/call, arrows. */
709
+ internal class ExprParser(src: String, private val cx: ExprContext = ExprContext()) {
710
+ private val toks = tokenize(src)
711
+ private var p = 0
712
+
713
+ fun parseAll(): Ex {
714
+ val e = ternary()
715
+ if (p != toks.size) throw IllegalStateException("trailing input")
716
+ return e
717
+ }
718
+
719
+ private fun peek(off: Int = 0) = toks.getOrNull(p + off)
720
+ private fun isP(t: String, off: Int = 0) = peek(off)?.t == t
721
+ private fun eat(t: String): Boolean { if (isP(t)) { p++; return true }; return false }
722
+ private fun expect(t: String) { if (!eat(t)) throw IllegalStateException("expected $t") }
723
+
724
+ private fun ternary(): Ex = cx.nested { ternaryInner() }
725
+
726
+ private fun ternaryInner(): Ex {
727
+ arrowAhead()?.let { return it }
728
+ val c = binary(1)
729
+ if (eat("?")) {
730
+ val a = ternary(); expect(":"); val b = ternary()
731
+ return Ex.Tern(c, a, b)
732
+ }
733
+ return c
734
+ }
735
+
736
+ /** `x => body` or `(a, b) => body` */
737
+ private fun arrowAhead(): Ex? {
738
+ val t0 = peek() ?: return null
739
+ if (t0.t == "id" && isP("=>", 1)) {
740
+ p += 2
741
+ return Ex.Arrow(listOf(t0.v as String), ternary())
742
+ }
743
+ if (t0.t == "(") {
744
+ var j = 1
745
+ val names = ArrayList<String>()
746
+ while (true) {
747
+ val t = peek(j) ?: return null
748
+ if (t.t == ")") break
749
+ if (t.t == "id") names += t.v as String else if (t.t != ",") return null
750
+ j++
751
+ }
752
+ if (isP("=>", j + 1)) {
753
+ p += j + 2
754
+ return Ex.Arrow(names, ternary())
755
+ }
756
+ }
757
+ return null
758
+ }
759
+
760
+ private fun binary(minPrec: Int): Ex {
761
+ var l = unary()
762
+ while (true) {
763
+ val op = peek()?.t ?: return l
764
+ val prec = BIN_PREC[op] ?: return l
765
+ if (prec < minPrec) return l
766
+ p++
767
+ l = Ex.Bin(op, l, binary(prec + 1))
768
+ }
769
+ }
770
+
771
+ private fun unary(): Ex {
772
+ for (op in UNARY_OPS) if (eat(op)) return Ex.Un(op, cx.nested { unary() })
773
+ return postfix()
774
+ }
775
+
776
+ private fun postfix(): Ex {
777
+ var e = primary()
778
+ while (true) {
779
+ e = when {
780
+ eat("?.") -> when {
781
+ isP("(") -> Ex.Call(e, args())
782
+ isP("[") -> { p++; val i = ternary(); expect("]"); Ex.Idx(e, i) }
783
+ else -> Ex.Mem(e, ident())
784
+ }
785
+ eat(".") -> Ex.Mem(e, memberName())
786
+ isP("[") -> { p++; val i = ternary(); expect("]"); Ex.Idx(e, i) }
787
+ isP("(") -> Ex.Call(e, args())
788
+ else -> return e
789
+ }
790
+ }
791
+ }
792
+
793
+ private fun args(): List<Ex> {
794
+ expect("(")
795
+ val out = ArrayList<Ex>()
796
+ if (!isP(")")) do { out += ternary() } while (eat(","))
797
+ expect(")")
798
+ return out
799
+ }
800
+
801
+ private fun ident(): String {
802
+ val t = peek()
803
+ if (t?.t != "id") throw IllegalStateException("identifier expected")
804
+ p++
805
+ return t.v as String
806
+ }
807
+
808
+ /** `flights.0.x` -> member "0" on a numeric key. */
809
+ private fun memberName(): String {
810
+ val t = peek() ?: throw IllegalStateException("member expected")
811
+ p++
812
+ return when (t.t) {
813
+ "id" -> t.v as String
814
+ "num" -> str(t.v)
815
+ else -> throw IllegalStateException("member expected")
816
+ }
817
+ }
818
+
819
+ private fun primary(): Ex {
820
+ val t = peek() ?: throw IllegalStateException("unexpected end")
821
+ p++
822
+ return when (t.t) {
823
+ "num", "str", "lit" -> Ex.Lit(t.v)
824
+ "id" -> Ex.Id(t.v as String)
825
+ "(" -> { val e = ternary(); expect(")"); e }
826
+ "[" -> {
827
+ val items = ArrayList<Ex>()
828
+ if (!isP("]")) do { items += ternary() } while (eat(","))
829
+ expect("]")
830
+ Ex.Arr(items)
831
+ }
832
+ else -> throw IllegalStateException("unexpected ${t.t}")
833
+ }
834
+ }
835
+ }
836
+
837
+ private val UNARY_OPS = listOf("!", "-", "+")
838
+
839
+ private typealias Fn = (List<Any?>) -> Any?
840
+
841
+ private val BLOCKED = setOf("__proto__", "constructor", "prototype")
842
+
843
+ private fun fn(f: (List<Any?>) -> Any?): Fn = f
844
+
845
+ /** An omitted numeric argument is NaN (JS undefined). */
846
+ private fun numArg(a: List<Any?>, i: Int) = if (i < a.size) toNumber(a[i]) else Double.NaN
847
+
848
+ private fun extreme(a: List<Any?>, start: Double, better: (Double, Double) -> Boolean): Double {
849
+ var r = start
850
+ for (v in a) {
851
+ val d = toNumber(v)
852
+ if (d.isNaN()) return Double.NaN
853
+ if (better(d, r)) r = d
854
+ }
855
+ return r
856
+ }
857
+
858
+ private val MATH: Map<String, Any?> = mapOf(
859
+ "round" to fn { a -> norm(jsRound(numArg(a, 0))) },
860
+ "floor" to fn { a -> norm(kotlin.math.floor(numArg(a, 0))) },
861
+ "ceil" to fn { a -> norm(kotlin.math.ceil(numArg(a, 0))) },
862
+ "abs" to fn { a -> norm(kotlin.math.abs(numArg(a, 0))) },
863
+ "max" to fn { a -> norm(extreme(a, Double.NEGATIVE_INFINITY) { x, best -> x > best }) },
864
+ "min" to fn { a -> norm(extreme(a, Double.POSITIVE_INFINITY) { x, best -> x < best }) },
865
+ )
866
+
867
+ private val GLOBALS: Map<String, Any?> = mapOf(
868
+ "Math" to MATH,
869
+ "NaN" to Double.NaN,
870
+ "Infinity" to Double.POSITIVE_INFINITY,
871
+ "Number" to fn { a -> if (a.isEmpty()) 0L else norm(toNumber(a[0])) },
872
+ "String" to fn { a -> if (a.isEmpty()) "" else jsString(a[0]) },
873
+ "Boolean" to fn { a -> truthy(a.firstOrNull()) },
874
+ "parseInt" to fn { a -> norm(jsParseInt(a.getOrElse(0) { "undefined" }, a.getOrNull(1))) },
875
+ "parseFloat" to fn { a -> norm(jsParseFloat(a.getOrElse(0) { "undefined" })) },
876
+ )
877
+
878
+ internal class ExprEval(private val lookup: (String) -> Any?, private val cx: ExprContext = ExprContext()) {
879
+ fun eval(e: Ex): Any? = cx.nested { evalNode(e) }
880
+
881
+ private fun evalNode(e: Ex): Any? = when (e) {
882
+ is Ex.Lit -> e.v
883
+ is Ex.Id -> if (e.name in BLOCKED) null else lookup(e.name) ?: GLOBALS[e.name]
884
+ is Ex.Mem -> read(eval(e.obj), e.name)
885
+ is Ex.Idx -> read(eval(e.obj), eval(e.index)?.let(::str))
886
+ is Ex.Call -> call(e)
887
+ is Ex.Un -> when (e.op) {
888
+ "!" -> !truthy(eval(e.arg))
889
+ "+" -> norm(toNumber(eval(e.arg)))
890
+ else -> norm(-toNumber(eval(e.arg)))
891
+ }
892
+ is Ex.Bin -> bin(e)
893
+ is Ex.Tern -> if (truthy(eval(e.c))) eval(e.a) else eval(e.b)
894
+ is Ex.Arr -> e.items.map(::eval)
895
+ is Ex.Arrow -> arrow(e)
896
+ }
897
+
898
+ private fun arrow(e: Ex.Arrow): Fn = { args ->
899
+ val sub = HashMap<String, Any?>()
900
+ e.params.forEachIndexed { i, n -> sub[n] = args.getOrNull(i) }
901
+ ExprEval({ n -> if (sub.containsKey(n)) sub[n] else lookup(n) }, cx).eval(e.body)
902
+ }
903
+
904
+ private fun read(obj: Any?, key: String?): Any? {
905
+ if (obj == null || key == null || key in BLOCKED) return null
906
+ return when (obj) {
907
+ is Map<*, *> -> obj[key]
908
+ is List<*> -> if (key == "length") obj.size.toLong() else arrayIndex(key)?.let { obj.getOrNull(it) }
909
+ is String -> if (key == "length") obj.length.toLong() else arrayIndex(key)?.let { obj.getOrNull(it)?.toString() }
910
+ else -> null
911
+ }
912
+ }
913
+
914
+ /** Only canonical index strings ("0", "12") address elements, as in JS ("01" and "+1" do not). */
915
+ private fun arrayIndex(key: String): Int? = key.toIntOrNull()?.takeIf { it >= 0 && it.toString() == key }
916
+
917
+ private fun call(e: Ex.Call): Any? {
918
+ val callee = e.callee
919
+ val args = e.args.map(::eval)
920
+ if (callee is Ex.Mem) {
921
+ val target = eval(callee.obj)
922
+ // a map member that is itself a function (Math.round)
923
+ if (target is Map<*, *>) return (target[callee.name] as? Fn)?.invoke(args)
924
+ return method(target, callee.name, args)
925
+ }
926
+ return (eval(callee) as? Fn)?.invoke(args)
927
+ }
928
+
929
+ private fun asFn(a: Any?): Fn? = a as? Fn
930
+
931
+ private fun method(t: Any?, name: String, a: List<Any?>): Any? = when (t) {
932
+ is List<*> -> listMethod(t, name, a)
933
+ is String -> stringMethod(t, name, a)
934
+ is Number -> if (name == "toFixed") {
935
+ val d = a.firstOrNull()?.let { toInteger(toNumber(it)) } ?: 0.0
936
+ require(d in 0.0..100.0) { "toFixed() digits out of range" }
937
+ toFixed(t.toDouble(), d.toInt())
938
+ } else null
939
+ else -> null
940
+ }
941
+
942
+ private fun listMethod(l: List<*>, name: String, a: List<Any?>): Any? {
943
+ val f = asFn(a.firstOrNull())
944
+ fun cb(g: Fn, i: Int) = g(listOf(l[i], i.toLong(), l))
945
+ return when (name) {
946
+ "filter" -> f?.let { g -> l.filterIndexed { i, _ -> truthy(cb(g, i)) } }
947
+ "find" -> f?.let { g -> l.indices.firstOrNull { truthy(cb(g, it)) }?.let { l[it] } }
948
+ "findIndex" -> f?.let { g -> l.indices.firstOrNull { truthy(cb(g, it)) }?.toLong() ?: -1L }
949
+ "some" -> f?.let { g -> l.indices.any { truthy(cb(g, it)) } }
950
+ "every" -> f?.let { g -> l.indices.all { truthy(cb(g, it)) } }
951
+ "map" -> f?.let { g -> l.indices.map { cb(g, it) } }
952
+ "slice" -> sliceRange(l.size, a).let { (s, e) -> l.subList(s, e).toList() }
953
+ "includes" -> l.any { sameValueZero(it, a.firstOrNull()) }
954
+ "indexOf" -> l.indexOfFirst { strictEquals(it, a.firstOrNull()) }.toLong()
955
+ "join" -> l.joinToString(a.firstOrNull()?.let(::jsString) ?: ",") { if (it == null) "" else jsString(it) }
956
+ "concat" -> ArrayList<Any?>(l).also { out -> a.forEach { if (it is List<*>) out.addAll(it) else out.add(it) } }
957
+ else -> null
958
+ }
959
+ }
960
+
961
+ private fun stringMethod(s: String, name: String, a: List<Any?>): Any? {
962
+ val search = if (a.isEmpty()) "undefined" else jsString(a[0])
963
+ return when (name) {
964
+ "toUpperCase" -> s.uppercase()
965
+ "toLowerCase" -> s.lowercase()
966
+ "trim" -> jsTrim(s)
967
+ "includes" -> indexOf(s, search, clampIndex(a.getOrNull(1), s.length, 0)) >= 0
968
+ "indexOf" -> indexOf(s, search, clampIndex(a.getOrNull(1), s.length, 0)).toLong()
969
+ "startsWith" -> s.startsWith(search, clampIndex(a.getOrNull(1), s.length, 0))
970
+ "endsWith" -> s.substring(0, clampIndex(a.getOrNull(1), s.length, s.length)).endsWith(search)
971
+ "split" -> split(s, a)
972
+ "slice" -> sliceRange(s.length, a).let { (b, e) -> s.substring(b, e) }
973
+ "substring" -> {
974
+ val b = clampIndex(a.getOrNull(0), s.length, 0)
975
+ val e = clampIndex(a.getOrNull(1), s.length, s.length)
976
+ s.substring(minOf(b, e), maxOf(b, e))
977
+ }
978
+ else -> null
979
+ }
980
+ }
981
+
982
+ private fun indexOf(s: String, search: String, from: Int): Int = if (search.isEmpty()) from else s.indexOf(search, from)
983
+
984
+ private fun split(s: String, a: List<Any?>): List<String> {
985
+ val limit = a.getOrNull(1)?.let { toUint32(toNumber(it)) } ?: 4294967295L
986
+ if (limit == 0L) return emptyList()
987
+ val sep = a.firstOrNull() ?: return listOf(s)
988
+ val sepStr = jsString(sep)
989
+ val parts = if (sepStr.isEmpty()) s.map { it.toString() } else s.split(sepStr)
990
+ return if (parts.size > limit) parts.take(limit.toInt()) else parts
991
+ }
992
+
993
+ /** substring-style index: NaN/negative -> 0, clamped to [0, len]; null/omitted -> [default]. */
994
+ private fun clampIndex(v: Any?, len: Int, default: Int): Int =
995
+ if (v == null) default else toInteger(toNumber(v)).coerceIn(0.0, len.toDouble()).toInt()
996
+
997
+ /** slice-style index: negative counts from the end. */
998
+ private fun relIndex(v: Any?, len: Int, default: Int): Int {
999
+ if (v == null) return default
1000
+ val d = toInteger(toNumber(v))
1001
+ return (if (d < 0) maxOf(len + d, 0.0) else minOf(d, len.toDouble())).toInt()
1002
+ }
1003
+
1004
+ private fun sliceRange(size: Int, a: List<Any?>): Pair<Int, Int> {
1005
+ val s = relIndex(a.getOrNull(0), size, 0)
1006
+ val e = relIndex(a.getOrNull(1), size, size)
1007
+ return s to maxOf(s, e)
1008
+ }
1009
+
1010
+ private fun bin(e: Ex.Bin): Any? {
1011
+ // short-circuit operators evaluate lazily
1012
+ when (e.op) {
1013
+ "&&" -> return eval(e.l).let { if (truthy(it)) eval(e.r) else it }
1014
+ "||" -> return eval(e.l).let { if (truthy(it)) it else eval(e.r) }
1015
+ "??" -> return eval(e.l) ?: eval(e.r)
1016
+ }
1017
+ val l = eval(e.l)
1018
+ val r = eval(e.r)
1019
+ return when (e.op) {
1020
+ "+" -> {
1021
+ val a = toPrimitive(l)
1022
+ val b = toPrimitive(r)
1023
+ if (a is String || b is String) jsString(a) + jsString(b) else norm(toNumber(a) + toNumber(b))
1024
+ }
1025
+ "-" -> norm(toNumber(l) - toNumber(r))
1026
+ "*" -> norm(toNumber(l) * toNumber(r))
1027
+ "/" -> norm(toNumber(l) / toNumber(r))
1028
+ "%" -> norm(toNumber(l) % toNumber(r))
1029
+ "<", ">", "<=", ">=" -> relational(e.op, l, r)
1030
+ "==" -> looseEquals(l, r)
1031
+ "!=" -> !looseEquals(l, r)
1032
+ "===" -> strictEquals(l, r)
1033
+ "!==" -> !strictEquals(l, r)
1034
+ else -> null
1035
+ }
1036
+ }
1037
+ }
1038
+ // AI-GENERATED END: SDUI spec model (generic) + expression evaluator (JavaScript expression semantics)