@rsconcept/domain 1.0.0 → 1.2.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 (185) hide show
  1. package/README.md +3 -3
  2. package/dist/analyzer-DlSq3Y3r.d.ts +39 -0
  3. package/dist/arguments-extractor-1acwjQNc.d.ts +38 -0
  4. package/dist/ast-C8sIpKdL.d.ts +51 -0
  5. package/dist/ast-annotations-BiMjkKvz.d.ts +16 -0
  6. package/dist/branded-ZlzIcxzu.d.ts +9 -0
  7. package/dist/calculator-C9W2jkSx.d.ts +39 -0
  8. package/dist/cctext/index.d.ts +2 -1
  9. package/dist/cctext/index.js +2 -42
  10. package/dist/cctext/language-api.d.ts +10 -12
  11. package/dist/cctext/language-api.js +157 -227
  12. package/dist/cctext/language-api.js.map +1 -1
  13. package/dist/cctext/language.d.ts +24 -22
  14. package/dist/cctext/language.js +43 -39
  15. package/dist/cctext/language.js.map +1 -1
  16. package/dist/error-E1LVq_3w.d.ts +87 -0
  17. package/dist/graph/graph.d.ts +2 -62
  18. package/dist/graph/graph.js +339 -382
  19. package/dist/graph/graph.js.map +1 -1
  20. package/dist/graph/index.d.ts +2 -1
  21. package/dist/graph/index.js +2 -384
  22. package/dist/graph-DR8rL2o3.d.ts +64 -0
  23. package/dist/hash-Y8I4c6Al.d.ts +8 -0
  24. package/dist/index-BKZ67WMa.d.ts +1 -0
  25. package/dist/index-BVVgDSdq.d.ts +1 -0
  26. package/dist/index-DmtQKWjk.d.ts +1 -0
  27. package/dist/index-_6s0AX1B.d.ts +1 -0
  28. package/dist/index.d.ts +27 -28
  29. package/dist/index.js +23 -5851
  30. package/dist/lezer-tree-iS7LpLBJ.d.ts +14 -0
  31. package/dist/library/folder-tree.d.ts +22 -20
  32. package/dist/library/folder-tree.js +108 -130
  33. package/dist/library/folder-tree.js.map +1 -1
  34. package/dist/library/index.d.ts +8 -17
  35. package/dist/library/index.js +7 -2800
  36. package/dist/library/library-api.d.ts +3 -1
  37. package/dist/library/library-api.js +9 -8
  38. package/dist/library/library-api.js.map +1 -1
  39. package/dist/library/library.d.ts +2 -56
  40. package/dist/library/library.js +23 -19
  41. package/dist/library/library.js.map +1 -1
  42. package/dist/library/oss-api.d.ts +26 -37
  43. package/dist/library/oss-api.js +258 -1096
  44. package/dist/library/oss-api.js.map +1 -1
  45. package/dist/library/oss-layout-api.d.ts +28 -28
  46. package/dist/library/oss-layout-api.js +239 -316
  47. package/dist/library/oss-layout-api.js.map +1 -1
  48. package/dist/library/oss-layout.d.ts +2 -25
  49. package/dist/library/oss-layout.js +1 -1
  50. package/dist/library/oss.d.ts +87 -89
  51. package/dist/library/oss.js +27 -26
  52. package/dist/library/oss.js.map +1 -1
  53. package/dist/library/rsengine.d.ts +100 -106
  54. package/dist/library/rsengine.js +439 -2599
  55. package/dist/library/rsengine.js.map +1 -1
  56. package/dist/library/rsform-api.d.ts +11 -16
  57. package/dist/library/rsform-api.js +313 -825
  58. package/dist/library/rsform-api.js.map +1 -1
  59. package/dist/library/rsform.d.ts +159 -167
  60. package/dist/library/rsform.js +29 -28
  61. package/dist/library/rsform.js.map +1 -1
  62. package/dist/library/rsmodel-api.d.ts +8 -15
  63. package/dist/library/rsmodel-api.js +172 -813
  64. package/dist/library/rsmodel-api.js.map +1 -1
  65. package/dist/library/rsmodel.d.ts +27 -33
  66. package/dist/library/rsmodel.js +16 -23
  67. package/dist/library/rsmodel.js.map +1 -1
  68. package/dist/library/structure-planner.d.ts +20 -26
  69. package/dist/library/structure-planner.js +106 -474
  70. package/dist/library/structure-planner.js.map +1 -1
  71. package/dist/library-CYun28Xz.d.ts +58 -0
  72. package/dist/oss-layout-3glgAqfn.d.ts +27 -0
  73. package/dist/parser-Bwd8LxJ1.d.ts +7 -0
  74. package/dist/parsing/ast.d.ts +2 -49
  75. package/dist/parsing/ast.js +68 -76
  76. package/dist/parsing/ast.js.map +1 -1
  77. package/dist/parsing/index.d.ts +3 -3
  78. package/dist/parsing/index.js +3 -141
  79. package/dist/parsing/lezer-tree.d.ts +2 -13
  80. package/dist/parsing/lezer-tree.js +50 -43
  81. package/dist/parsing/lezer-tree.js.map +1 -1
  82. package/dist/rslang/api.d.ts +9 -14
  83. package/dist/rslang/api.js +114 -827
  84. package/dist/rslang/api.js.map +1 -1
  85. package/dist/rslang/ast-annotations.d.ts +2 -18
  86. package/dist/rslang/ast-annotations.js +34 -45
  87. package/dist/rslang/ast-annotations.js.map +1 -1
  88. package/dist/rslang/error.d.ts +2 -85
  89. package/dist/rslang/error.js +88 -150
  90. package/dist/rslang/error.js.map +1 -1
  91. package/dist/rslang/eval/calculator.d.ts +2 -43
  92. package/dist/rslang/eval/calculator.js +81 -1636
  93. package/dist/rslang/eval/calculator.js.map +1 -1
  94. package/dist/rslang/eval/evaluation-cache.d.ts +22 -26
  95. package/dist/rslang/eval/evaluation-cache.js +168 -287
  96. package/dist/rslang/eval/evaluation-cache.js.map +1 -1
  97. package/dist/rslang/eval/evaluator.d.ts +59 -63
  98. package/dist/rslang/eval/evaluator.js +602 -1509
  99. package/dist/rslang/eval/evaluator.js.map +1 -1
  100. package/dist/rslang/eval/value-api.d.ts +2 -48
  101. package/dist/rslang/eval/value-api.js +2 -490
  102. package/dist/rslang/eval/value.d.ts +2 -36
  103. package/dist/rslang/eval/value.js +2 -118
  104. package/dist/rslang/index.d.ts +14 -17
  105. package/dist/rslang/index.js +12 -4314
  106. package/dist/rslang/labels.d.ts +6 -6
  107. package/dist/rslang/labels.js +139 -305
  108. package/dist/rslang/labels.js.map +1 -1
  109. package/dist/rslang/parser/expression-generator.d.ts +5 -5
  110. package/dist/rslang/parser/expression-generator.js +248 -446
  111. package/dist/rslang/parser/expression-generator.js.map +1 -1
  112. package/dist/rslang/parser/normalize.d.ts +4 -8
  113. package/dist/rslang/parser/normalize.js +286 -481
  114. package/dist/rslang/parser/normalize.js.map +1 -1
  115. package/dist/rslang/parser/parser.d.ts +2 -5
  116. package/dist/rslang/parser/parser.js +30 -21
  117. package/dist/rslang/parser/parser.js.map +1 -1
  118. package/dist/rslang/parser/parser.terms.d.ts +43 -41
  119. package/dist/rslang/parser/parser.terms.js +44 -83
  120. package/dist/rslang/parser/parser.terms.js.map +1 -1
  121. package/dist/rslang/parser/syntax-errors.d.ts +5 -8
  122. package/dist/rslang/parser/syntax-errors.js +113 -382
  123. package/dist/rslang/parser/syntax-errors.js.map +1 -1
  124. package/dist/rslang/parser/token.d.ts +2 -79
  125. package/dist/rslang/parser/token.js +81 -93
  126. package/dist/rslang/parser/token.js.map +1 -1
  127. package/dist/rslang/semantic/analyzer.d.ts +2 -39
  128. package/dist/rslang/semantic/analyzer.js +186 -2600
  129. package/dist/rslang/semantic/analyzer.js.map +1 -1
  130. package/dist/rslang/semantic/arguments-extractor.d.ts +2 -42
  131. package/dist/rslang/semantic/arguments-extractor.js +202 -361
  132. package/dist/rslang/semantic/arguments-extractor.js.map +1 -1
  133. package/dist/rslang/semantic/type-auditor.d.ts +64 -68
  134. package/dist/rslang/semantic/type-auditor.js +594 -1564
  135. package/dist/rslang/semantic/type-auditor.js.map +1 -1
  136. package/dist/rslang/semantic/typification-api.d.ts +4 -7
  137. package/dist/rslang/semantic/typification-api.js +162 -303
  138. package/dist/rslang/semantic/typification-api.js.map +1 -1
  139. package/dist/rslang/semantic/typification-parser.d.ts +2 -12
  140. package/dist/rslang/semantic/typification-parser.js +165 -219
  141. package/dist/rslang/semantic/typification-parser.js.map +1 -1
  142. package/dist/rslang/semantic/typification.d.ts +2 -119
  143. package/dist/rslang/semantic/typification.js +66 -52
  144. package/dist/rslang/semantic/typification.js.map +1 -1
  145. package/dist/rslang/semantic/value-auditor.d.ts +32 -38
  146. package/dist/rslang/semantic/value-auditor.js +206 -518
  147. package/dist/rslang/semantic/value-auditor.js.map +1 -1
  148. package/dist/rslang/semantic/value-class.d.ts +2 -10
  149. package/dist/rslang/semantic/value-class.js +8 -7
  150. package/dist/rslang/semantic/value-class.js.map +1 -1
  151. package/dist/rslang/typification-graph.d.ts +2 -33
  152. package/dist/rslang/typification-graph.js +94 -306
  153. package/dist/rslang/typification-graph.js.map +1 -1
  154. package/dist/shared/branded.d.ts +2 -7
  155. package/dist/shared/branded.js +1 -1
  156. package/dist/shared/hash.d.ts +2 -6
  157. package/dist/shared/hash.js +13 -13
  158. package/dist/shared/hash.js.map +1 -1
  159. package/dist/shared/index.d.ts +3 -2
  160. package/dist/shared/index.js +2 -18
  161. package/dist/token-DeXAmzwr.d.ts +81 -0
  162. package/dist/typification-Dk-fisgO.d.ts +120 -0
  163. package/dist/typification-graph-6HcZ-rKH.d.ts +30 -0
  164. package/dist/typification-parser-BBVx1RxP.d.ts +13 -0
  165. package/dist/value-B8UtCqaK.js +366 -0
  166. package/dist/value-B8UtCqaK.js.map +1 -0
  167. package/dist/value-CTjX6825.d.ts +33 -0
  168. package/dist/value-api-Bw-SgaYY.d.ts +49 -0
  169. package/dist/value-class-CNI-lqXJ.d.ts +12 -0
  170. package/package.json +8 -8
  171. package/src/library/oss-api.test.ts +76 -0
  172. package/src/library/oss-api.ts +4 -1
  173. package/src/library/rsform-api.test.ts +24 -0
  174. package/src/library/rsform-api.ts +12 -4
  175. package/dist/cctext/index.js.map +0 -1
  176. package/dist/graph/index.js.map +0 -1
  177. package/dist/index.js.map +0 -1
  178. package/dist/library/index.js.map +0 -1
  179. package/dist/library/oss-layout.js.map +0 -1
  180. package/dist/parsing/index.js.map +0 -1
  181. package/dist/rslang/eval/value-api.js.map +0 -1
  182. package/dist/rslang/eval/value.js.map +0 -1
  183. package/dist/rslang/index.js.map +0 -1
  184. package/dist/shared/branded.js.map +0 -1
  185. package/dist/shared/index.js.map +0 -1
@@ -1,2604 +1,444 @@
1
- // src/rslang/ast-annotations.ts
2
- var AST_ERRORS_KEY = "rsErrors";
3
- function annotateError(node, code, params) {
4
- if (typeof node.annotation === "object" && node.annotation !== null && AST_ERRORS_KEY in node.annotation && isAstNodeErrorRef(node.annotation[AST_ERRORS_KEY])) {
5
- return;
6
- }
7
- const entry = params !== void 0 && params.length > 0 ? { code, params: [...params] } : { code };
8
- node.annotation = {
9
- ...typeof node.annotation === "object" && node.annotation !== null ? node.annotation : {},
10
- [AST_ERRORS_KEY]: entry
11
- };
12
- }
13
- function isAstNodeErrorRef(x) {
14
- if (typeof x !== "object" || x === null || !("code" in x)) {
15
- return false;
16
- }
17
- const code = x.code;
18
- if (typeof code !== "number") {
19
- return false;
20
- }
21
- if (!("params" in x)) {
22
- return true;
23
- }
24
- const p = x.params;
25
- if (p === void 0) {
26
- return true;
27
- }
28
- return Array.isArray(p) && p.every((item) => typeof item === "string");
29
- }
30
-
31
- // src/rslang/error.ts
32
- var RSErrorCode = {
33
- unknownSyntax: 33792,
34
- // 33792
35
- missingParenthesis: 33798,
36
- // 33798
37
- missingCurlyBrace: 33799,
38
- // 33799
39
- missingSquareBracket: 33800,
40
- // 33800
41
- bracketMismatch: 33801,
42
- // 33801
43
- doubleParenthesis: 33802,
44
- // 33802
45
- missingOpenBracket: 33803,
46
- // 33803
47
- expectedLocal: 33813,
48
- // 33813
49
- expectedType: 33814,
50
- // 33814
51
- localDoubleDeclare: 10241,
52
- // 10241
53
- localNotUsed: 10242,
54
- // 10242
55
- localUndeclared: 34817,
56
- // 34817
57
- localShadowing: 34818,
58
- // 34818
59
- typesNotEqual: 34819,
60
- // 34819
61
- globalNotTyped: 34820,
62
- // 34820
63
- invalidDecart: 34821,
64
- // 34821
65
- invalidBoolean: 34822,
66
- // 34822
67
- invalidTypeOperation: 34823,
68
- // 34823
69
- invalidCard: 34824,
70
- // 34824
71
- invalidDebool: 34825,
72
- // 34825
73
- globalFuncWithoutArgs: 34827,
74
- // 34827
75
- invalidReduce: 34832,
76
- // 34832
77
- invalidProjectionTuple: 34833,
78
- // 34833
79
- invalidProjectionSet: 34834,
80
- // 34834
81
- invalidEnumeration: 34835,
82
- // 34835
83
- invalidCortegeDeclare: 34836,
84
- // 34836
85
- localOutOfScope: 34837,
86
- // 34837
87
- invalidElementPredicate: 34838,
88
- // 34838
89
- invalidEmptySetUsage: 34839,
90
- // 34839
91
- invalidArgsArity: 34840,
92
- // 34840
93
- invalidArgumentType: 34841,
94
- // 34841
95
- globalStructure: 34844,
96
- // 34844
97
- radicalUsage: 34849,
98
- // 34849
99
- invalidFilterArgumentType: 34850,
100
- // 34850
101
- invalidFilterArity: 34851,
102
- // 34851
103
- arithmeticNotSupported: 34852,
104
- // 34852
105
- typesNotCompatible: 34853,
106
- // 34853
107
- orderingNotSupported: 34854,
108
- // 34854
109
- expectedLogic: 34855,
110
- // 34855
111
- expectedSetexpr: 34856,
112
- // 34856
113
- invalidArgumentCortegeDeclare: 34857,
114
- // 34857
115
- globalNoValue: 34880,
116
- // 34880
117
- invalidPropertyUsage: 34881,
118
- // 34881
119
- // Value evaluation (runtime)
120
- calcUnknownError: 33024,
121
- // 35328
122
- setOverflow: 33025,
123
- // 35329
124
- booleanBaseLimit: 33026,
125
- // 35330
126
- calcGlobalMissing: 33027,
127
- // 35331
128
- iterationsLimit: 33028,
129
- // 35332
130
- calcInvalidDebool: 33029,
131
- // 35333
132
- iterateInfinity: 33030,
133
- // 35334
134
- calculationNotSupported: 33031,
135
- // 35335
136
- cstEmptyDerived: 34913,
137
- // 34913
138
- definitionNotAllowed: 34914
139
- // 34914
140
- };
141
-
142
- // src/parsing/ast.ts
143
- var TOKEN_ERROR = 0;
144
- function getNodeText(node) {
145
- if (node.data.dataType === "string" && typeof node.data.value === "string") {
146
- return node.data.value;
147
- }
148
- return `NO DATA NODE: ${node.typeID}`;
149
- }
150
- function getNodeIndices(node) {
151
- if (node.data.dataType === "string[]" && Array.isArray(node.data.value)) {
152
- return node.data.value.map((s) => parseInt(s, 10)).filter((n) => !isNaN(n));
153
- }
154
- return [];
155
- }
156
-
157
- // src/rslang/parser/token.ts
158
- var TokenID = {
159
- // Global, local IDs and literals
160
- ERROR: TOKEN_ERROR,
161
- ID_LOCAL: 258,
162
- ID_GLOBAL: 259,
163
- ID_FUNCTION: 260,
164
- ID_PREDICATE: 261,
165
- ID_RADICAL: 262,
166
- LIT_INTEGER: 263,
167
- LIT_WHOLE_NUMBERS: 264,
168
- LIT_EMPTYSET: 265,
169
- // Arithmetic
170
- PLUS: 266,
171
- MINUS: 267,
172
- MULTIPLY: 268,
173
- // Integer predicate symbols
174
- GREATER: 269,
175
- LESSER: 270,
176
- GREATER_OR_EQ: 271,
177
- LESSER_OR_EQ: 272,
178
- // Equality comparison
179
- EQUAL: 273,
180
- NOTEQUAL: 274,
181
- // Logic predicate symbols
182
- QUANTOR_UNIVERSAL: 275,
183
- QUANTOR_EXISTS: 276,
184
- LOGIC_NOT: 277,
185
- LOGIC_EQUIVALENT: 278,
186
- LOGIC_IMPLICATION: 279,
187
- LOGIC_OR: 280,
188
- LOGIC_AND: 281,
189
- // Set theory predicate symbols
190
- SET_IN: 282,
191
- SET_NOT_IN: 283,
192
- SUBSET: 284,
193
- SUBSET_OR_EQ: 285,
194
- NOT_SUBSET: 286,
195
- // Set theory operators
196
- DECART: 287,
197
- SET_UNION: 288,
198
- SET_INTERSECTION: 289,
199
- SET_MINUS: 290,
200
- SET_SYMMETRIC_MINUS: 291,
201
- BOOLEAN: 292,
202
- // Structure operations
203
- BIGPR: 293,
204
- SMALLPR: 294,
205
- FILTER: 295,
206
- CARD: 296,
207
- BOOL: 297,
208
- DEBOOL: 298,
209
- REDUCE: 299,
210
- // Term constructions prefixes
211
- DECLARATIVE: 300,
212
- RECURSIVE: 301,
213
- IMPERATIVE: 302,
214
- ITERATE: 303,
215
- ASSIGN: 304,
216
- // Punctuation
217
- PUNCTUATION_DEFINE: 305,
218
- PUNCTUATION_STRUCT: 306,
219
- PUNCTUATION_PL: 307,
220
- PUNCTUATION_PR: 308,
221
- PUNCTUATION_CL: 309,
222
- PUNCTUATION_CR: 310,
223
- PUNCTUATION_SL: 311,
224
- PUNCTUATION_SR: 312,
225
- PUNCTUATION_BAR: 313,
226
- PUNCTUATION_COMMA: 314,
227
- PUNCTUATION_SEMICOLON: 315,
228
- // ======= Non-terminal tokens =========
229
- NT_ENUM_DECL: 316,
230
- NT_TUPLE: 317,
231
- NT_ENUMERATION: 318,
232
- NT_TUPLE_DECL: 319,
233
- NT_ARG_DECL: 320,
234
- NT_FUNC_DEFINITION: 321,
235
- NT_ARGUMENTS: 322,
236
- NT_FUNC_CALL: 323,
237
- NT_DECLARATIVE_EXPR: 324,
238
- NT_IMPERATIVE_EXPR: 325,
239
- NT_RECURSIVE_FULL: 326,
240
- NT_RECURSIVE_SHORT: 327,
241
- // ======= Helper tokens ========
242
- INTERRUPT: 328,
243
- END: 329
244
- };
245
-
246
- // src/rslang/eval/evaluation-cache.ts
247
- var EvaluationMetadata = class {
248
- byNode = /* @__PURE__ */ new WeakMap();
249
- get(node) {
250
- let info = this.byNode.get(node);
251
- if (!info) {
252
- info = analyzeNode(node, /* @__PURE__ */ new Set());
253
- this.byNode.set(node, info);
254
- }
255
- return info;
256
- }
257
- };
258
- var EvaluationCache = class {
259
- entries = /* @__PURE__ */ new Map();
260
- /** Cache hits in the current evaluation run (for tests/diagnostics). */
261
- hits = 0;
262
- /** Returns cached value, or `undefined` on miss or stamp mismatch. */
263
- lookup(structuralKey, stamp) {
264
- const entry = this.entries.get(structuralKey);
265
- if (entry?.stamp !== stamp) {
266
- return void 0;
267
- }
268
- this.hits++;
269
- return entry.value;
270
- }
271
- /** Stores one value per structural key (replaces previous stamp). */
272
- store(structuralKey, stamp, value) {
273
- this.entries.set(structuralKey, { stamp, value });
274
- }
275
- clear() {
276
- this.entries.clear();
277
- this.hits = 0;
278
- }
279
- };
280
- function analyzeNode(node, bound) {
281
- const reads = collectReads(node, bound);
282
- const structuralKey = buildStructuralKey(node);
283
- const cacheable = isCacheableNode(node);
284
- return { reads, structuralKey, cacheable };
285
- }
286
- function isCacheableNode(node) {
287
- switch (node.typeID) {
288
- case TokenID.ASSIGN:
289
- case TokenID.ITERATE:
290
- case TokenID.NT_IMPERATIVE_EXPR:
291
- case TokenID.NT_DECLARATIVE_EXPR:
292
- case TokenID.NT_RECURSIVE_FULL:
293
- case TokenID.NT_RECURSIVE_SHORT:
294
- case TokenID.QUANTOR_UNIVERSAL:
295
- case TokenID.QUANTOR_EXISTS:
296
- case TokenID.LOGIC_AND:
297
- case TokenID.LOGIC_OR:
298
- case TokenID.LOGIC_IMPLICATION:
299
- case TokenID.NT_FUNC_DEFINITION:
300
- case TokenID.LIT_INTEGER:
301
- case TokenID.LIT_EMPTYSET:
302
- case TokenID.LIT_WHOLE_NUMBERS:
303
- case TokenID.ID_LOCAL:
304
- case TokenID.ID_RADICAL:
305
- case TokenID.ID_GLOBAL:
306
- return false;
307
- default:
308
- return !node.hasError;
309
- }
310
- }
311
- function buildStructuralKey(node) {
312
- switch (node.typeID) {
313
- case TokenID.ID_GLOBAL:
314
- case TokenID.ID_LOCAL:
315
- case TokenID.ID_RADICAL:
316
- case TokenID.LIT_INTEGER:
317
- case TokenID.LIT_EMPTYSET:
318
- case TokenID.LIT_WHOLE_NUMBERS:
319
- return `${node.typeID}:${nodeTextKey(node)}`;
320
- case TokenID.NT_FUNC_CALL:
321
- return `${node.typeID}:${nodeTextKey(node.children[0])}(${node.children.slice(1).map(buildStructuralKey).join(",")})`;
322
- case TokenID.BIGPR:
323
- case TokenID.SMALLPR:
324
- case TokenID.FILTER:
325
- return `${node.typeID}:${indicesKey(node)}(${node.children.map(buildStructuralKey).join(",")})`;
326
- default:
327
- return `${node.typeID}(${node.children.map(buildStructuralKey).join(",")})`;
328
- }
329
- }
330
- function nodeTextKey(node) {
331
- if (node.data.dataType === "number") {
332
- return String(node.data.value);
333
- }
334
- return getNodeText(node);
335
- }
336
- function indicesKey(node) {
337
- return getNodeIndices(node).join(".");
338
- }
339
- function collectReads(node, bound) {
340
- const reads = /* @__PURE__ */ new Set();
341
- collectReadsImpl(node, bound, reads);
342
- return reads;
343
- }
344
- function collectReadsImpl(node, bound, reads) {
345
- switch (node.typeID) {
346
- case TokenID.ID_LOCAL:
347
- case TokenID.ID_RADICAL: {
348
- reads.add(getNodeText(node));
349
- return;
350
- }
351
- case TokenID.QUANTOR_UNIVERSAL:
352
- case TokenID.QUANTOR_EXISTS: {
353
- collectReadsImpl(node.children[1], bound, reads);
354
- const innerBound = extendBound(bound, node.children[0]);
355
- collectReadsImpl(node.children[2], innerBound, reads);
356
- return;
357
- }
358
- case TokenID.NT_DECLARATIVE_EXPR: {
359
- collectReadsImpl(node.children[1], bound, reads);
360
- const innerBound = extendBound(bound, node.children[0]);
361
- collectReadsImpl(node.children[2], innerBound, reads);
362
- return;
363
- }
364
- case TokenID.ITERATE: {
365
- collectReadsImpl(node.children[1], bound, reads);
366
- return;
367
- }
368
- case TokenID.ASSIGN: {
369
- collectReadsImpl(node.children[1], bound, reads);
370
- return;
371
- }
372
- case TokenID.NT_IMPERATIVE_EXPR: {
373
- const innerBound = new Set(bound);
374
- collectReadsImpl(node.children[0], innerBound, reads);
375
- for (let i = 1; i < node.children.length; i++) {
376
- const child = node.children[i];
377
- if (child.typeID === TokenID.ITERATE) {
378
- extendBoundInPlace(innerBound, child.children[0]);
379
- collectReadsImpl(child.children[1], innerBound, reads);
380
- } else if (child.typeID === TokenID.ASSIGN) {
381
- collectReadsImpl(child.children[1], innerBound, reads);
382
- extendBoundInPlace(innerBound, child.children[0]);
383
- } else {
384
- collectReadsImpl(child, innerBound, reads);
385
- }
386
- }
387
- return;
388
- }
389
- case TokenID.NT_RECURSIVE_FULL:
390
- case TokenID.NT_RECURSIVE_SHORT: {
391
- collectReadsImpl(node.children[1], bound, reads);
392
- const innerBound = extendBound(bound, node.children[0]);
393
- if (node.typeID === TokenID.NT_RECURSIVE_FULL) {
394
- collectReadsImpl(node.children[2], innerBound, reads);
395
- collectReadsImpl(node.children[3], innerBound, reads);
396
- } else {
397
- collectReadsImpl(node.children[2], innerBound, reads);
398
- }
399
- return;
400
- }
401
- case TokenID.NT_FUNC_DEFINITION: {
402
- const innerBound = extendBound(bound, node.children[0]);
403
- collectReadsImpl(node.children[1], innerBound, reads);
404
- return;
405
- }
406
- case TokenID.NT_FUNC_CALL: {
407
- for (let i = 1; i < node.children.length; i++) {
408
- collectReadsImpl(node.children[i], bound, reads);
409
- }
410
- return;
411
- }
412
- case TokenID.LOGIC_AND:
413
- case TokenID.LOGIC_OR:
414
- case TokenID.LOGIC_IMPLICATION: {
415
- collectReadsImpl(node.children[0], bound, reads);
416
- collectReadsImpl(node.children[1], bound, reads);
417
- return;
418
- }
419
- default:
420
- for (const child of node.children) {
421
- collectReadsImpl(child, bound, reads);
422
- }
423
- }
424
- }
425
- function extendBound(bound, declNode) {
426
- const next = new Set(bound);
427
- extendBoundInPlace(next, declNode);
428
- return next;
429
- }
430
- function extendBoundInPlace(bound, declNode) {
431
- switch (declNode.typeID) {
432
- case TokenID.ID_LOCAL:
433
- case TokenID.ID_RADICAL:
434
- bound.add(getNodeText(declNode));
435
- break;
436
- case TokenID.NT_TUPLE_DECL:
437
- case TokenID.NT_ENUM_DECL:
438
- for (const child of declNode.children) {
439
- extendBoundInPlace(bound, child);
440
- }
441
- break;
442
- case TokenID.NT_ARG_DECL:
443
- extendBoundInPlace(bound, declNode.children[0]);
444
- break;
445
- }
446
- }
447
-
448
- // src/rslang/semantic/typification.ts
449
- var TypeID = {
450
- anyTypification: 1,
451
- integer: 2,
452
- basic: 3,
453
- tuple: 4,
454
- collection: 5,
455
- logic: 6,
456
- function: 7,
457
- predicate: 8
458
- };
459
- var TypeClass = {
460
- logic: 1,
461
- typification: 2,
462
- function: 3,
463
- predicate: 4
464
- };
465
- var LogicT = { typeID: TypeID.logic };
466
- var IntegerT = {
467
- typeID: TypeID.integer,
468
- isOrdered: true,
469
- isArithmetic: true,
470
- isIntegerCompatible: true
471
- };
472
- var AnyTypificationT = { typeID: TypeID.anyTypification };
473
- var EmptySetT = bool(AnyTypificationT);
474
- function basic(alias) {
475
- return { typeID: TypeID.basic, baseID: alias };
476
- }
477
- function constant(alias) {
478
- return { typeID: TypeID.basic, baseID: alias, isOrdered: true, isArithmetic: true, isIntegerCompatible: true };
479
- }
480
- function bool(base) {
481
- return { typeID: TypeID.collection, base };
482
- }
483
-
484
- // src/rslang/eval/value-api.ts
485
- function cartesianProduct(factors) {
486
- const cardinality = factors.reduce((acc, f) => acc * f.length, 1);
487
- if (cardinality > SET_INFINITY) {
488
- return null;
489
- }
490
- if (cardinality === 0 || factors.length === 0) {
491
- return EmptySetV;
492
- }
493
- let accumulator = [[]];
494
- for (const factor of factors) {
495
- const next = [];
496
- for (const prefix of accumulator) {
497
- for (const value of factor) {
498
- next.push([...prefix, value]);
499
- }
500
- }
501
- accumulator = next;
502
- }
503
- return accumulator.map(tuple);
504
- }
505
- function boolean(base) {
506
- if (base.length > BOOL_INFINITY) {
507
- return null;
508
- }
509
- return powerset(base);
510
- }
511
- function powerset(arr) {
512
- const result = [[]];
513
- if (arr.length === 0) {
514
- return result;
515
- }
516
- let current = [[]];
517
- let maxIndex = [-1];
518
- while (current.length > 0) {
519
- const next = [];
520
- const nextMaxIndex = [];
521
- for (let i = 0; i < current.length; i++) {
522
- for (let j = maxIndex[i] + 1; j < arr.length; j++) {
523
- const subset = [...current[i], arr[j]];
524
- result.push(subset);
525
- if (j < arr.length - 1) {
526
- next.push(subset);
527
- nextMaxIndex.push(j);
528
- }
529
- }
530
- }
531
- current = next;
532
- maxIndex = nextMaxIndex;
533
- }
534
- return result;
535
- }
536
- function contains(setData, element) {
537
- let left = 0;
538
- let right = setData.length - 1;
539
- while (left <= right) {
540
- const mid = Math.floor((left + right) / 2);
541
- const cmp = compare(setData[mid], element);
542
- if (cmp === 0) {
543
- return true;
544
- } else if (cmp < 0) {
545
- left = mid + 1;
546
- } else {
547
- right = mid - 1;
548
- }
549
- }
550
- return false;
551
- }
552
- function isSubsetOrEq(a, b) {
553
- let i = 0, j = 0;
554
- while (i < a.length && j < b.length) {
555
- const cmp = compare(a[i], b[j]);
556
- if (cmp === 0) {
557
- i++;
558
- j++;
559
- } else if (cmp > 0) {
560
- j++;
561
- } else {
562
- return false;
563
- }
564
- }
565
- return i === a.length;
566
- }
567
- function reduce(target) {
568
- const result = [];
569
- for (const element of target) {
570
- result.push(...element);
571
- }
572
- return set(result);
573
- }
574
- function setUnion(set1, set2) {
575
- const result = [];
576
- let i = 0, j = 0;
577
- while (i < set1.length && j < set2.length) {
578
- const cmp = compare(set1[i], set2[j]);
579
- if (cmp < 0) {
580
- result.push(set1[i]);
581
- i++;
582
- } else if (cmp > 0) {
583
- result.push(set2[j]);
584
- j++;
585
- } else {
586
- result.push(set1[i]);
587
- i++;
588
- j++;
589
- }
590
- }
591
- while (i < set1.length) {
592
- result.push(set1[i]);
593
- i++;
594
- }
595
- while (j < set2.length) {
596
- result.push(set2[j]);
597
- j++;
598
- }
599
- return result;
600
- }
601
- function setIntersection(set1, set2) {
602
- const result = [];
603
- for (let i = 0, j = 0; i < set1.length && j < set2.length; ) {
604
- const cmp = compare(set1[i], set2[j]);
605
- if (cmp < 0) {
606
- i++;
607
- } else if (cmp > 0) {
608
- j++;
609
- } else {
610
- result.push(set1[i]);
611
- i++;
612
- j++;
613
- }
614
- }
615
- return result;
616
- }
617
- function setDiff(set1, set2) {
618
- const result = [];
619
- let i = 0, j = 0;
620
- while (i < set1.length && j < set2.length) {
621
- const cmp = compare(set1[i], set2[j]);
622
- if (cmp < 0) {
623
- result.push(set1[i]);
624
- i++;
625
- } else if (cmp > 0) {
626
- j++;
627
- } else {
628
- i++;
629
- j++;
630
- }
631
- }
632
- while (i < set1.length) {
633
- result.push(set1[i]);
634
- i++;
635
- }
636
- return result;
637
- }
638
- function setSymDiff(set1, set2) {
639
- const result = [];
640
- let i = 0, j = 0;
641
- while (i < set1.length && j < set2.length) {
642
- const cmp = compare(set1[i], set2[j]);
643
- if (cmp < 0) {
644
- result.push(set1[i]);
645
- i++;
646
- } else if (cmp > 0) {
647
- result.push(set2[j]);
648
- j++;
649
- } else {
650
- i++;
651
- j++;
652
- }
653
- }
654
- while (i < set1.length) {
655
- result.push(set1[i]);
656
- i++;
657
- }
658
- while (j < set2.length) {
659
- result.push(set2[j]);
660
- j++;
661
- }
662
- return result;
663
- }
664
- function projection(target, indices) {
665
- const projectedElements = target.map((element) => {
666
- const newComponents = indices.map((idx) => element[idx]);
667
- return indices.length === 1 ? newComponents[0] : tuple(newComponents);
668
- });
669
- return set(projectedElements);
670
- }
671
- function printValue(data) {
672
- if (!Array.isArray(data)) {
673
- return String(data);
674
- }
675
- const len = data.length;
676
- if (data.length === 0) {
677
- return "{}";
678
- }
679
- const isTuple = data[0] === TUPLE_ID;
680
- const start = isTuple ? 1 : 0;
681
- let result = isTuple ? "(" : "{";
682
- for (let i = start; i < len; i++) {
683
- if (i > start) result += ", ";
684
- result += printValue(data[i]);
685
- }
686
- result += isTuple ? ")" : "}";
687
- return result;
688
- }
689
- function isSetValue(data) {
690
- return Array.isArray(data) && (data.length === 0 || data[0] !== TUPLE_ID);
691
- }
692
- function isTupleValue(data) {
693
- return Array.isArray(data) && data.length > 1 && data[0] === TUPLE_ID;
694
- }
695
- function validateValue(value, type, basics) {
696
- switch (type.typeID) {
697
- case TypeID.integer:
698
- return typeof value === "number";
699
- case TypeID.logic: {
700
- if (typeof value !== "number") {
701
- return false;
702
- }
703
- return value === VALUE_TRUE || value === VALUE_FALSE;
704
- }
705
- case TypeID.basic: {
706
- if (typeof value !== "number") {
707
- return false;
708
- }
709
- const domain = basics.get(type.baseID);
710
- return !!domain && Array.isArray(domain) && domain.includes(value);
711
- }
712
- case TypeID.tuple: {
713
- if (!Array.isArray(value) || value.length !== type.factors.length + 1 || value[0] !== TUPLE_ID) {
714
- return false;
715
- }
716
- for (let i = 0; i < type.factors.length; i++) {
717
- if (!validateValue(value[i + 1], type.factors[i], basics)) {
718
- return false;
719
- }
720
- }
721
- return true;
722
- }
723
- case TypeID.collection: {
724
- if (!isSetValue(value)) {
725
- return false;
726
- }
727
- for (const item of value) {
728
- if (!validateValue(item, type.base, basics)) {
729
- return false;
730
- }
731
- }
732
- return true;
733
- }
734
- case TypeID.anyTypification:
735
- case TypeID.predicate:
736
- case TypeID.function:
737
- return false;
738
- }
739
- }
740
-
741
- // src/rslang/eval/value.ts
742
- var TUPLE_ID = -111;
743
- var VALUE_TRUE = 1;
744
- var VALUE_FALSE = 0;
745
- var SET_INFINITY = 1e7;
746
- var BOOL_INFINITY = 18;
747
- var EmptySetV = [];
748
- function compare(v1, v2) {
749
- const stack1 = [v1];
750
- const stack2 = [v2];
751
- while (stack1.length > 0 && stack2.length > 0) {
752
- const el1 = stack1.pop();
753
- const el2 = stack2.pop();
754
- if (el1 === el2) {
755
- continue;
756
- }
757
- const type1 = typeof el1;
758
- const type2 = typeof el2;
759
- if (type1 === "number" && type2 === "number") {
760
- const numDiff = el1 - el2;
761
- if (numDiff !== 0) return numDiff;
762
- continue;
763
- }
764
- const isArray1 = Array.isArray(el1);
765
- const isArray2 = Array.isArray(el2);
766
- if (!isArray1 || !isArray2) {
767
- throw new Error(`Cannot compare different types ${printValue(el1)} and ${printValue(el2)}`);
768
- }
769
- const arr1 = el1;
770
- const arr2 = el2;
771
- const len1 = arr1.length;
772
- const len2 = arr2.length;
773
- if (len1 !== len2) {
774
- return len1 - len2;
775
- }
776
- for (let i = len1 - 1; i >= 0; i--) {
777
- stack1.push(arr1[i]);
778
- stack2.push(arr2[i]);
779
- }
780
- }
781
- return 0;
782
- }
783
- function tuple(components) {
784
- return [TUPLE_ID, ...components];
785
- }
786
- function set(elements) {
787
- const sorted = [...elements].sort(compare);
788
- for (let i = 1; i < sorted.length; ) {
789
- if (compare(sorted[i - 1], sorted[i]) === 0) {
790
- sorted.splice(i, 1);
791
- } else {
792
- i++;
793
- }
794
- }
795
- return sorted;
796
- }
797
-
798
- // src/rslang/eval/evaluator.ts
799
- var MAX_ITERATIONS = 1e6;
800
- var TICK_PER_FUNCTION = 3;
801
- var TICK_PER_RECURSION = 3;
802
- var TICK_PER_IMPERATIVE = 1;
803
- var TICK_PER_DECLARATIVE = 1;
804
- var TICK_PER_QUANTIFIER = 1;
805
- var Evaluator = class {
806
- reporter;
807
- annotateErrors = false;
808
- disableCache = false;
809
- locals = new LocalContext();
810
- nodeMetadata = new EvaluationMetadata();
811
- evalCache = new EvaluationCache();
812
- callSiteStack = [];
813
- context;
814
- treeContext;
815
- iterationCounter = 0;
816
- /** Cache hits in the current evaluation run (for tests/diagnostics). */
817
- get cacheHits() {
818
- return this.evalCache.hits;
819
- }
820
- constructor(context, astContext) {
821
- this.treeContext = astContext;
822
- this.context = context;
823
- }
824
- run(ast, reporter, annotateErrors = false, disableCache = false) {
825
- if (ast.hasError) {
826
- return null;
827
- }
828
- this.reporter = reporter;
829
- this.annotateErrors = annotateErrors;
830
- this.disableCache = disableCache;
831
- this.clear();
832
- return this.dispatchVisit(ast);
833
- }
834
- clear() {
835
- this.locals = new LocalContext();
836
- this.evalCache.clear();
837
- this.callSiteStack = [];
838
- this.iterationCounter = 0;
839
- }
840
- errorNode(node) {
841
- if (this.callSiteStack.length > 0) {
842
- return this.callSiteStack[this.callSiteStack.length - 1];
843
- }
844
- return node;
845
- }
846
- onError(code, node, params) {
847
- const target = this.errorNode(node);
848
- this.reporter?.({ code, from: target.from, to: target.to, params });
849
- if (this.annotateErrors) {
850
- annotateError(target, code, params);
851
- }
852
- return null;
853
- }
854
- tick(node, counter = 1) {
855
- this.iterationCounter += counter;
856
- if (this.iterationCounter > MAX_ITERATIONS) {
857
- this.onError(RSErrorCode.iterationsLimit, node, [String(MAX_ITERATIONS)]);
858
- return false;
859
- }
860
- return true;
861
- }
862
- dispatchDeclare(node, value) {
863
- switch (node.typeID) {
864
- case TokenID.ID_LOCAL:
865
- return this.declareLocal(node, value);
866
- case TokenID.NT_TUPLE_DECL:
867
- return this.declareTuple(node, value);
868
- case TokenID.NT_ARG_DECL:
869
- return this.dispatchDeclare(node.children[0], value);
870
- }
871
- }
872
- declareLocal(node, value) {
873
- const alias = getNodeText(node);
874
- this.locals.setLocal(alias, value);
875
- }
876
- declareTuple(node, value) {
877
- for (let child = 0; child < node.children.length; child++) {
878
- this.dispatchDeclare(node.children[child], value[child + 1]);
879
- }
880
- }
881
- dispatchVisit(node) {
882
- const info = this.nodeMetadata.get(node);
883
- let stamp = null;
884
- if (info.cacheable && !this.disableCache) {
885
- stamp = this.locals.buildDependencyStamp(info.reads);
886
- if (stamp !== null) {
887
- const cached = this.evalCache.lookup(info.structuralKey, stamp);
888
- if (cached !== void 0) {
889
- return cached;
890
- }
891
- }
892
- }
893
- const result = this.dispatchVisitImpl(node);
894
- if (!this.disableCache && result !== null && info.cacheable && stamp !== null) {
895
- this.evalCache.store(info.structuralKey, stamp, result);
896
- }
897
- return result;
898
- }
899
- dispatchVisitImpl(node) {
900
- switch (node.typeID) {
901
- case TokenID.ID_GLOBAL:
902
- return this.visitGlobal(node);
903
- case TokenID.NT_FUNC_CALL:
904
- return this.visitFunctionCall(node);
905
- case TokenID.ID_LOCAL:
906
- case TokenID.ID_RADICAL:
907
- return this.visitLocal(node);
908
- case TokenID.LIT_INTEGER:
909
- return this.visitInteger(node);
910
- case TokenID.LIT_WHOLE_NUMBERS:
911
- return this.onError(RSErrorCode.iterateInfinity, node);
912
- case TokenID.LIT_EMPTYSET:
913
- return EmptySetV;
914
- case TokenID.PLUS:
915
- case TokenID.MINUS:
916
- case TokenID.MULTIPLY:
917
- return this.visitArithmetic(node);
918
- case TokenID.CARD:
919
- return this.visitCard(node);
920
- case TokenID.QUANTOR_UNIVERSAL:
921
- case TokenID.QUANTOR_EXISTS:
922
- return this.visitQuantifier(node);
923
- case TokenID.LOGIC_NOT:
924
- return this.visitNegation(node);
925
- case TokenID.LOGIC_AND:
926
- case TokenID.LOGIC_OR:
927
- case TokenID.LOGIC_IMPLICATION:
928
- case TokenID.LOGIC_EQUIVALENT:
929
- return this.visitLogicBinary(node);
930
- case TokenID.EQUAL:
931
- case TokenID.NOTEQUAL:
932
- return this.visitEquals(node);
933
- case TokenID.GREATER:
934
- case TokenID.LESSER:
935
- case TokenID.GREATER_OR_EQ:
936
- case TokenID.LESSER_OR_EQ:
937
- return this.visitIntegerPredicate(node);
938
- case TokenID.SET_IN:
939
- case TokenID.SET_NOT_IN:
940
- case TokenID.SUBSET:
941
- case TokenID.SUBSET_OR_EQ:
942
- case TokenID.NOT_SUBSET:
943
- return this.visitSetexprPredicate(node);
944
- case TokenID.DECART:
945
- return this.visitDecart(node);
946
- case TokenID.BOOLEAN:
947
- return this.visitBoolean(node);
948
- case TokenID.NT_TUPLE:
949
- return this.visitTuple(node);
950
- case TokenID.NT_ENUMERATION:
951
- return this.visitEnumeration(node);
952
- case TokenID.BOOL:
953
- return this.visitBool(node);
954
- case TokenID.DEBOOL:
955
- return this.visitDebool(node);
956
- case TokenID.SET_UNION:
957
- case TokenID.SET_INTERSECTION:
958
- case TokenID.SET_MINUS:
959
- case TokenID.SET_SYMMETRIC_MINUS:
960
- return this.visitSetexprBinary(node);
961
- case TokenID.BIGPR:
962
- return this.visitProjectSet(node);
963
- case TokenID.SMALLPR:
964
- return this.visitProjectTuple(node);
965
- case TokenID.FILTER:
966
- return this.visitFilter(node);
967
- case TokenID.REDUCE:
968
- return this.visitReduce(node);
969
- case TokenID.NT_DECLARATIVE_EXPR:
970
- return this.visitDeclarative(node);
971
- case TokenID.NT_IMPERATIVE_EXPR:
972
- return this.visitImperative(node);
973
- case TokenID.ASSIGN:
974
- return this.visitAssign(node);
975
- case TokenID.NT_RECURSIVE_FULL:
976
- case TokenID.NT_RECURSIVE_SHORT:
977
- return this.visitRecursion(node);
978
- case TokenID.NT_FUNC_DEFINITION:
979
- return this.onError(RSErrorCode.calculationNotSupported, node);
980
- }
981
- return null;
982
- }
983
- visitChild(node, index) {
984
- return this.dispatchVisit(node.children[index]);
985
- }
986
- visitGlobal(node) {
987
- const alias = getNodeText(node);
988
- const value = this.context.get(alias);
989
- if (value === void 0) {
990
- return this.onError(RSErrorCode.calcGlobalMissing, node, [alias]);
991
- }
992
- return value;
993
- }
994
- visitLocal(node) {
995
- const alias = getNodeText(node);
996
- return this.locals.getLocal(alias);
997
- }
998
- visitFunctionCall(node) {
999
- const funcName = getNodeText(node.children[0]);
1000
- const ast = this.treeContext.get(funcName);
1001
- if (!ast) {
1002
- return this.onError(RSErrorCode.calcGlobalMissing, node.children[0], [funcName]);
1003
- }
1004
- if (!this.tick(node, TICK_PER_FUNCTION)) {
1005
- return null;
1006
- }
1007
- const args = [];
1008
- for (let i = 1; i < node.children.length; i++) {
1009
- const arg = this.visitChild(node, i);
1010
- if (arg === null) {
1011
- return null;
1012
- }
1013
- args.push(arg);
1014
- }
1015
- this.locals.startScope();
1016
- for (let i = 0; i < args.length; i++) {
1017
- this.dispatchDeclare(ast.children[0].children[i], args[i]);
1018
- }
1019
- this.callSiteStack.push(node);
1020
- let result;
1021
- try {
1022
- result = this.visitChild(ast, 1);
1023
- } finally {
1024
- this.callSiteStack.pop();
1025
- }
1026
- this.locals.endScope();
1027
- return result;
1028
- }
1029
- visitInteger(node) {
1030
- const value = node.data.dataType === "number" ? node.data.value : Number(node.data.value);
1031
- return Math.floor(value);
1032
- }
1033
- visitArithmetic(node) {
1034
- const v1 = this.visitChild(node, 0);
1035
- const v2 = this.visitChild(node, 1);
1036
- if (v1 === null || v2 === null) {
1037
- return null;
1038
- }
1039
- const a = v1;
1040
- const b = v2;
1041
- switch (node.typeID) {
1042
- case TokenID.PLUS:
1043
- return a + b;
1044
- case TokenID.MINUS:
1045
- return a - b;
1046
- case TokenID.MULTIPLY:
1047
- return a * b;
1048
- }
1049
- return null;
1050
- }
1051
- visitCard(node) {
1052
- const base = this.visitChild(node, 0);
1053
- if (base === null || !Array.isArray(base)) {
1054
- return null;
1055
- }
1056
- return base.length;
1057
- }
1058
- visitQuantifier(node) {
1059
- const domain = this.visitChild(node, 1);
1060
- if (domain === null) {
1061
- return null;
1062
- }
1063
- const isUniversal = node.typeID === TokenID.QUANTOR_UNIVERSAL;
1064
- if (domain.length === 0) {
1065
- return isUniversal ? VALUE_TRUE : VALUE_FALSE;
1066
- }
1067
- const varNodes = node.children[0].typeID === TokenID.NT_ENUM_DECL ? node.children[0].children : [node.children[0]];
1068
- const count = domain.length;
1069
- const iterators = [];
1070
- for (const declaration of varNodes) {
1071
- iterators.push(0);
1072
- this.dispatchDeclare(declaration, domain[0]);
1073
- }
1074
- let finishIteration = false;
1075
- while (!finishIteration) {
1076
- const iterationValue = this.visitChild(node, 2);
1077
- if (iterationValue === null) {
1078
- return null;
1079
- }
1080
- if (iterationValue === VALUE_TRUE !== isUniversal) {
1081
- return !isUniversal ? VALUE_TRUE : VALUE_FALSE;
1082
- }
1083
- let incrementIndex = iterators.length - 1;
1084
- while (true) {
1085
- if (iterators[incrementIndex] < count - 1) {
1086
- iterators[incrementIndex]++;
1087
- if (!this.tick(node, TICK_PER_QUANTIFIER)) {
1088
- return null;
1089
- }
1090
- this.dispatchDeclare(varNodes[incrementIndex], domain[iterators[incrementIndex]]);
1091
- incrementIndex = iterators.length - 1;
1092
- break;
1093
- } else if (incrementIndex === 0) {
1094
- finishIteration = true;
1095
- break;
1096
- } else {
1097
- iterators[incrementIndex] = 0;
1098
- this.dispatchDeclare(varNodes[incrementIndex], domain[0]);
1099
- incrementIndex--;
1100
- }
1101
- }
1102
- }
1103
- return isUniversal ? VALUE_TRUE : VALUE_FALSE;
1104
- }
1105
- visitNegation(node) {
1106
- const value = this.visitChild(node, 0);
1107
- if (value === null) {
1108
- return null;
1109
- }
1110
- return value === VALUE_TRUE ? VALUE_FALSE : VALUE_TRUE;
1111
- }
1112
- tryEvaluateFromFirstArg(op, first) {
1113
- if (op === TokenID.LOGIC_AND && !first || op === TokenID.LOGIC_OR && first) {
1114
- return first ? VALUE_TRUE : VALUE_FALSE;
1115
- }
1116
- if (op === TokenID.LOGIC_IMPLICATION && !first) {
1117
- return VALUE_TRUE;
1118
- }
1119
- return null;
1120
- }
1121
- visitLogicBinary(node) {
1122
- const v1 = this.visitChild(node, 0);
1123
- if (v1 === null) {
1124
- return null;
1125
- }
1126
- const b1 = v1 === VALUE_TRUE;
1127
- const attempt = this.tryEvaluateFromFirstArg(node.typeID, b1);
1128
- if (attempt !== null) {
1129
- return attempt;
1130
- }
1131
- const v2 = this.visitChild(node, 1);
1132
- if (v2 === null) {
1133
- return null;
1134
- }
1135
- const b2 = v2 === VALUE_TRUE;
1136
- let result;
1137
- switch (node.typeID) {
1138
- case TokenID.LOGIC_AND:
1139
- result = b1 && b2;
1140
- break;
1141
- case TokenID.LOGIC_OR:
1142
- result = b1 || b2;
1143
- break;
1144
- case TokenID.LOGIC_IMPLICATION:
1145
- result = !b1 || b2;
1146
- break;
1147
- case TokenID.LOGIC_EQUIVALENT:
1148
- result = b1 === b2;
1149
- break;
1150
- default:
1151
- return null;
1152
- }
1153
- return result ? VALUE_TRUE : VALUE_FALSE;
1154
- }
1155
- visitEquals(node) {
1156
- const v1 = this.visitChild(node, 0);
1157
- if (v1 === null) {
1158
- return null;
1159
- }
1160
- const v2 = this.visitChild(node, 1);
1161
- if (v2 === null) {
1162
- return null;
1163
- }
1164
- const areEqual = compare(v1, v2) === 0;
1165
- return areEqual === (node.typeID !== TokenID.NOTEQUAL) ? VALUE_TRUE : VALUE_FALSE;
1166
- }
1167
- visitIntegerPredicate(node) {
1168
- const v1 = this.visitChild(node, 0);
1169
- if (v1 === null) {
1170
- return null;
1171
- }
1172
- const v2 = this.visitChild(node, 1);
1173
- if (v2 === null) {
1174
- return null;
1175
- }
1176
- const a = v1;
1177
- const b = v2;
1178
- let result;
1179
- switch (node.typeID) {
1180
- case TokenID.GREATER:
1181
- result = a > b;
1182
- break;
1183
- case TokenID.LESSER:
1184
- result = a < b;
1185
- break;
1186
- case TokenID.GREATER_OR_EQ:
1187
- result = a >= b;
1188
- break;
1189
- case TokenID.LESSER_OR_EQ:
1190
- result = a <= b;
1191
- break;
1192
- default:
1193
- return null;
1194
- }
1195
- return result ? VALUE_TRUE : VALUE_FALSE;
1196
- }
1197
- visitSetexprPredicate(node) {
1198
- const v1 = this.visitChild(node, 0);
1199
- if (v1 === null) {
1200
- return null;
1201
- }
1202
- const v2 = this.visitChild(node, 1);
1203
- if (v2 === null) {
1204
- return null;
1205
- }
1206
- let result;
1207
- switch (node.typeID) {
1208
- case TokenID.SET_IN:
1209
- result = contains(v2, v1);
1210
- break;
1211
- case TokenID.SET_NOT_IN:
1212
- result = !contains(v2, v1);
1213
- break;
1214
- case TokenID.SUBSET:
1215
- result = compare(v1, v2) !== 0 && isSubsetOrEq(v1, v2);
1216
- break;
1217
- case TokenID.NOT_SUBSET:
1218
- result = compare(v1, v2) === 0 || !isSubsetOrEq(v1, v2);
1219
- break;
1220
- case TokenID.SUBSET_OR_EQ:
1221
- result = isSubsetOrEq(v1, v2);
1222
- break;
1223
- default:
1224
- return null;
1225
- }
1226
- return result ? VALUE_TRUE : VALUE_FALSE;
1227
- }
1228
- visitDecart(node) {
1229
- const args = [];
1230
- for (let i = 0; i < node.children.length; i++) {
1231
- const component2 = this.visitChild(node, i);
1232
- if (component2 === null) {
1233
- return null;
1234
- }
1235
- if (component2.length === 0) {
1236
- return EmptySetV;
1237
- }
1238
- args.push(component2);
1239
- }
1240
- const result = cartesianProduct(args);
1241
- if (result === null) {
1242
- this.onError(RSErrorCode.setOverflow, node, [String(SET_INFINITY)]);
1243
- return null;
1244
- }
1245
- return result;
1246
- }
1247
- visitBoolean(node) {
1248
- const base = this.visitChild(node, 0);
1249
- if (base === null) {
1250
- return null;
1251
- }
1252
- const result = boolean(base);
1253
- if (result === null) {
1254
- this.onError(RSErrorCode.booleanBaseLimit, node.children[0], [String(BOOL_INFINITY)]);
1255
- return null;
1256
- }
1257
- return result;
1258
- }
1259
- visitTuple(node) {
1260
- const args = [];
1261
- for (let i = 0; i < node.children.length; i++) {
1262
- const component2 = this.visitChild(node, i);
1263
- if (component2 === null) {
1264
- return null;
1265
- }
1266
- args.push(component2);
1267
- }
1268
- return tuple(args);
1269
- }
1270
- visitEnumeration(node) {
1271
- const args = [];
1272
- for (let i = 0; i < node.children.length; i++) {
1273
- const element = this.visitChild(node, i);
1274
- if (element === null) {
1275
- return null;
1276
- }
1277
- args.push(element);
1278
- }
1279
- return set(args);
1280
- }
1281
- visitBool(node) {
1282
- const element = this.visitChild(node, 0);
1283
- if (element === null) {
1284
- return null;
1285
- }
1286
- return [element];
1287
- }
1288
- visitDebool(node) {
1289
- const target = this.visitChild(node, 0);
1290
- if (target === null) {
1291
- return null;
1292
- }
1293
- if (target.length !== 1) {
1294
- return this.onError(RSErrorCode.calcInvalidDebool, node.children[0]);
1295
- }
1296
- return target[0];
1297
- }
1298
- visitSetexprBinary(node) {
1299
- const v1 = this.visitChild(node, 0);
1300
- if (v1 === null) {
1301
- return null;
1302
- }
1303
- const v2 = this.visitChild(node, 1);
1304
- if (v2 === null) {
1305
- return null;
1306
- }
1307
- switch (node.typeID) {
1308
- case TokenID.SET_UNION:
1309
- return setUnion(v1, v2);
1310
- case TokenID.SET_INTERSECTION:
1311
- return setIntersection(v1, v2);
1312
- case TokenID.SET_MINUS:
1313
- return setDiff(v1, v2);
1314
- case TokenID.SET_SYMMETRIC_MINUS:
1315
- return setSymDiff(v1, v2);
1316
- }
1317
- return null;
1318
- }
1319
- visitProjectSet(node) {
1320
- const target = this.visitChild(node, 0);
1321
- if (target === null) {
1322
- return null;
1323
- }
1324
- const indices = getNodeIndices(node);
1325
- return projection(target, indices);
1326
- }
1327
- visitProjectTuple(node) {
1328
- const target = this.visitChild(node, 0);
1329
- if (target === null) {
1330
- return null;
1331
- }
1332
- const indices = getNodeIndices(node);
1333
- const components = indices.map((i) => target[i]);
1334
- return components.length === 1 ? components[0] : tuple(components);
1335
- }
1336
- visitFilter(node) {
1337
- const lastIdx = node.children.length - 1;
1338
- const argVal = this.visitChild(node, lastIdx);
1339
- if (argVal === null) {
1340
- return null;
1341
- }
1342
- if (argVal.length === 0) {
1343
- return EmptySetV;
1344
- }
1345
- const indices = getNodeIndices(node);
1346
- const tupleParam = indices.length === lastIdx;
1347
- if (tupleParam) {
1348
- const params = [];
1349
- for (let i = 0; i < lastIdx; i++) {
1350
- const param = this.visitChild(node, i);
1351
- if (param === null) {
1352
- return null;
1353
- }
1354
- if (param.length === 0) {
1355
- return EmptySetV;
1356
- }
1357
- params.push(param);
1358
- }
1359
- const result = [];
1360
- for (const element of argVal) {
1361
- let valid = true;
1362
- for (let j = 0; j < indices.length; j++) {
1363
- const comp = element[indices[j]];
1364
- const paramSet = params[j];
1365
- if (!contains(paramSet, comp)) {
1366
- valid = false;
1367
- break;
1368
- }
1369
- }
1370
- if (valid) {
1371
- result.push(element);
1372
- }
1373
- }
1374
- return result;
1375
- } else {
1376
- const paramVal = this.visitChild(node, 0);
1377
- if (paramVal === null) {
1378
- return null;
1379
- }
1380
- if (paramVal.length === 0) {
1381
- return EmptySetV;
1382
- }
1383
- const result = [];
1384
- for (const element of argVal) {
1385
- const comps = indices.map((i) => element[i]);
1386
- const testElement = comps.length === 1 ? comps[0] : tuple(comps);
1387
- if (contains(paramVal, testElement)) result.push(element);
1388
- }
1389
- return result;
1390
- }
1391
- }
1392
- visitReduce(node) {
1393
- const target = this.visitChild(node, 0);
1394
- if (target === null) {
1395
- return null;
1396
- }
1397
- return reduce(target);
1398
- }
1399
- visitDeclarative(node) {
1400
- const domain = this.visitChild(node, 1);
1401
- if (domain === null) {
1402
- return null;
1403
- }
1404
- const elements = [];
1405
- for (const element of domain) {
1406
- if (!this.tick(node, TICK_PER_DECLARATIVE)) {
1407
- return null;
1408
- }
1409
- this.dispatchDeclare(node.children[0], element);
1410
- const value = this.visitChild(node, 2);
1411
- if (value === null) {
1412
- return null;
1413
- }
1414
- if (value === VALUE_TRUE) {
1415
- elements.push(element);
1416
- }
1417
- }
1418
- return elements.length === 0 ? EmptySetV : elements;
1419
- }
1420
- visitImperative(node) {
1421
- const result = [];
1422
- const frames = [];
1423
- let currentChild = 1;
1424
- const advanceIterator = () => {
1425
- while (frames.length > 0) {
1426
- const top = frames[frames.length - 1];
1427
- if (top.valueID < top.domain.length - 1) {
1428
- top.valueID++;
1429
- const nextValue = top.domain[top.valueID];
1430
- if (!this.tick(node.children[top.childID], TICK_PER_IMPERATIVE)) {
1431
- return false;
1432
- }
1433
- this.dispatchDeclare(node.children[top.childID].children[0], nextValue);
1434
- currentChild = top.childID + 1;
1435
- return true;
1436
- }
1437
- frames.pop();
1438
- }
1439
- return false;
1440
- };
1441
- while (true) {
1442
- if (currentChild >= node.children.length) {
1443
- const element = this.visitChild(node, 0);
1444
- if (element === null) {
1445
- return null;
1446
- }
1447
- result.push(element);
1448
- if (!advanceIterator()) {
1449
- break;
1450
- }
1451
- continue;
1452
- }
1453
- const child = node.children[currentChild];
1454
- if (child.typeID === TokenID.ITERATE) {
1455
- const domain = this.visitChild(child, 1);
1456
- if (domain === null) {
1457
- return null;
1458
- }
1459
- if (domain.length === 0) {
1460
- if (!advanceIterator()) {
1461
- break;
1462
- }
1463
- continue;
1464
- }
1465
- if (!this.tick(child, TICK_PER_IMPERATIVE)) {
1466
- return null;
1467
- }
1468
- frames.push({
1469
- childID: currentChild,
1470
- domain,
1471
- valueID: 0
1472
- });
1473
- this.dispatchDeclare(child.children[0], domain[0]);
1474
- currentChild++;
1475
- continue;
1476
- }
1477
- const value = this.dispatchVisit(child);
1478
- if (value === null) {
1479
- return null;
1480
- }
1481
- if (value === VALUE_FALSE) {
1482
- if (!advanceIterator()) {
1483
- break;
1484
- }
1485
- continue;
1486
- }
1487
- currentChild++;
1488
- }
1489
- return set(result);
1490
- }
1491
- visitAssign(node) {
1492
- const value = this.visitChild(node, 1);
1493
- if (value === null) {
1494
- return null;
1495
- }
1496
- this.dispatchDeclare(node.children[0], value);
1497
- return VALUE_TRUE;
1498
- }
1499
- visitRecursion(node) {
1500
- const initialValue = this.visitChild(node, 1);
1501
- if (initialValue === null) {
1502
- return null;
1503
- }
1504
- const bodyIndex = node.typeID === TokenID.NT_RECURSIVE_FULL ? 3 : 2;
1505
- let current = initialValue;
1506
- while (true) {
1507
- if (!this.tick(node, TICK_PER_RECURSION)) {
1508
- return null;
1509
- }
1510
- this.dispatchDeclare(node.children[0], current);
1511
- if (node.typeID === TokenID.NT_RECURSIVE_FULL) {
1512
- const pred = this.visitChild(node, 2);
1513
- if (pred === null) {
1514
- return null;
1515
- }
1516
- if (pred !== VALUE_TRUE) {
1517
- break;
1518
- }
1519
- }
1520
- const next = this.visitChild(node, bodyIndex);
1521
- if (next === null) {
1522
- return null;
1523
- }
1524
- if (compare(current, next) === 0) {
1525
- break;
1526
- }
1527
- current = next;
1528
- }
1529
- return current;
1530
- }
1531
- };
1532
- var LocalContext = class {
1533
- nextBindingId = 1;
1534
- data = /* @__PURE__ */ new Map();
1535
- callStack = [];
1536
- startScope() {
1537
- this.callStack.push(this.data);
1538
- this.data = /* @__PURE__ */ new Map();
1539
- }
1540
- endScope() {
1541
- this.data = this.callStack.pop();
1542
- }
1543
- setLocal(alias, value) {
1544
- const existing = this.data.get(alias);
1545
- if (existing) {
1546
- existing.value = value;
1547
- existing.version++;
1548
- } else {
1549
- this.data.set(alias, { id: this.nextBindingId++, version: 0, value });
1550
- }
1551
- }
1552
- getLocal(alias) {
1553
- const binding = this.data.get(alias);
1554
- if (binding === void 0) {
1555
- throw new Error(`Local variable "${alias}" not found`);
1556
- }
1557
- return binding.value;
1558
- }
1559
- buildDependencyStamp(reads) {
1560
- if (reads.size === 0) {
1561
- return "";
1562
- }
1563
- const parts = [];
1564
- for (const alias of [...reads].sort()) {
1565
- const binding = this.data.get(alias);
1566
- if (binding === void 0) {
1567
- return null;
1568
- }
1569
- parts.push(`${binding.id}:${binding.version}`);
1570
- }
1571
- return parts.join("|");
1572
- }
1573
- };
1574
-
1575
- // src/rslang/eval/calculator.ts
1576
- var RSCalculator = class {
1577
- context = /* @__PURE__ */ new Map();
1578
- treeContext = /* @__PURE__ */ new Map();
1579
- evaluator = new Evaluator(this.context, this.treeContext);
1580
- listeners = /* @__PURE__ */ new Map();
1581
- subscribe = (alias, listener) => {
1582
- let notifyList = this.listeners.get(alias);
1583
- if (!notifyList) {
1584
- notifyList = /* @__PURE__ */ new Set();
1585
- this.listeners.set(alias, notifyList);
1586
- }
1587
- notifyList.add(listener);
1588
- return () => {
1589
- notifyList.delete(listener);
1590
- if (notifyList.size === 0) {
1591
- this.listeners.delete(alias);
1592
- }
1593
- };
1594
- };
1595
- setValue(alias, value) {
1596
- this.context.set(alias, value);
1597
- this.notify(alias);
1598
- }
1599
- resetValue(alias) {
1600
- this.context.delete(alias);
1601
- this.notify(alias);
1602
- }
1603
- clearAllAst() {
1604
- this.treeContext.clear();
1605
- }
1606
- getValue(alias) {
1607
- return this.context.get(alias) ?? null;
1608
- }
1609
- setAST(alias, ast) {
1610
- this.treeContext.set(alias, ast);
1611
- }
1612
- validate(value, type) {
1613
- return validateValue(value, type, this.context);
1614
- }
1615
- evaluateFast(ast) {
1616
- if (ast.hasError) {
1617
- return null;
1618
- }
1619
- return this.evaluator.run(ast);
1620
- }
1621
- evaluateFull(ast, options) {
1622
- const errors = [];
1623
- const reporter = (error) => {
1624
- errors.push(error);
1625
- };
1626
- if (ast.hasError) {
1627
- return { value: null, iterations: 0, cacheHits: 0, errors };
1628
- }
1629
- const value = this.evaluator.run(ast, reporter, options?.annotateErrors ?? false, options?.disableCache ?? false);
1630
- if (value === null && errors.length === 0) {
1631
- errors.push({ code: RSErrorCode.calcUnknownError, from: 0, to: 0 });
1632
- if (options?.annotateErrors) {
1633
- annotateError(ast, RSErrorCode.calcUnknownError);
1634
- }
1635
- }
1636
- return {
1637
- value,
1638
- iterations: this.evaluator.iterationCounter,
1639
- cacheHits: this.evaluator.cacheHits,
1640
- errors
1641
- };
1642
- }
1643
- notify(alias) {
1644
- const set2 = this.listeners.get(alias);
1645
- if (!set2) return;
1646
- for (const l of set2) {
1647
- l();
1648
- }
1649
- }
1650
- };
1651
-
1652
- // src/rslang/parser/parser.ts
1653
- import { LRParser } from "@lezer/lr";
1654
- var parser = LRParser.deserialize({
1655
- version: 14,
1656
- states: "2lO!sQPOOOVQPO'#CdO$qQPO'#C`O&pQPO'#C`O*bQPO'#C_Q*jQPOOO,TQPO'#C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!e!v!y#R#T#W#]#^#_#e#f#m#n#p#xRoP!scOPV]pqrstuvwxyz{|}!O!T!X!Z!]!_!`!e!v!y#R#T#W#]#^#_#e#f#m#n#p#x!rcOPV]pqrstuvwxyz{|}!O!T!X!Z!]!_!`!e!v!y#R#T#W#]#^#_#e#f#m#n#p#xR!Y^R#i#^RjOR!ciQ!biR#b#SQTO[kP]!O!T!Z!_Q!SVQ!gvQ!hpQ!iqQ!jrQ!ksQ!ltQ!muQ!nwQ!oxQ!pyQ!qzQ!r{Q!s|Q!t}Q!z!XQ!}!]Q#Q!`Q#U!eQ#W!vQ#Y!yQ#a#RQ#c#TQ#d#WQ#g#]Q#h#^Q#j#_Q#k#eQ#l#fQ#s#mQ#t#nQ#u#pR#y#xSmP!OQ!V]Q!w!TQ!{!ZR#P!_!seOPV]pqrstuvwxyz{|}!O!T!X!Z!]!_!`!e!v!y#R#T#W#]#^#_#e#f#m#n#p#x!sgOPV]pqrstuvwxyz{|}!O!T!X!Z!]!_!`!e!v!y#R#T#W#]#^#_#e#f#m#n#p#x",
1659
- nodeNames: "\u26A0 Expression Logic Logic_predicates Variable Local ) ( Tuple Expr_enum_min2 , :\u2208 := \u2208 \u2209 \u2286 \u2284 \u2282 > \u2265 < \u2264 \u2260 = Logic_unary \xAC Predicate [ ] Logic_quantor \u2200 Variable_pack \u2203 Logic_binary \u21D4 \u21D2 \u2228 & Setexpr Integer EmptySet IntegerSet Global Radical Setexpr_binary * + - \u222A \\ \u2206 \u2229 \xD7 } { Enumeration Boolean \u212C Filter_expression Filter Declarative | PrefixD PrefixI Imperative Imp_blocks ; PrefixR Recursion Function BigPr SmallPr Card Bool Debool Red Function_decl Arguments Declaration",
1660
- maxTerm: 87,
1661
- nodeProps: [
1662
- ["openedBy", 6, "(", 53, "{"],
1663
- ["closedBy", 7, ")", 54, "}"]
1664
- ],
1665
- skippedNodes: [0],
1666
- repeatNodeCount: 0,
1667
- tokenData: "6j~R!jX^%spq%svw&hxy&myz&rz{&w{|&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o+V5i6S+V~-sTT~!Q![+e#T#f+V#f#g.S#g#o+V5i6S+V~.XTT~!Q![+e#T#W+V#W#X.h#X#o+V5i6S+V~.oR!j~T~!Q![+e#T#o+V5i6S+V~.}TT~!Q![+e#T#X+V#X#Y/^#Y#o+V5i6S+V~/cTT~!Q![+e#T#U+V#U#V/r#V#o+V5i6S+V~/wTT~!Q![+e#T#c+V#c#d0W#d#o+V5i6S+V~0]TT~!Q![+e#T#c+V#c#d0l#d#o+V5i6S+V~0qTT~!Q![+e#T#`+V#`#a1Q#a#o+V5i6S+V~1XR!l~T~!Q![+e#T#o+V5i6S+V~1gTT~!Q![+e#T#f+V#f#g1v#g#o+V5i6S+V~1{ST~!Q!R+e!R![2X#T#o+V5i6S+V~2`Q!i~T~|}2f!Q![2X~2iP!R![2l~2qQ!i~|}2f!Q![2l~2|TT~!Q![+e#T#X+V#X#Y3]#Y#o+V5i6S+V~3bTT~!Q![+e#T#W+V#W#X3q#X#o+V5i6S+V~3xR!m~T~!Q![+e#T#o+V5i6S+V~4WO!W~~4]O!_~~4bO!V~~4gOi~~4lO!U~~4qO!Z~~4vOs~~4{Or~~5QOn~~5VOp~~5[Ox~~5aO!S~~5fO]~~5kO^~~5pOt~~5uO!T~~5zO!Q~~6POf~~6UOe~~6ZOc~~6`Oa~~6eO`~~6jO_~",
1668
- tokenizers: [0],
1669
- topRules: { "Expression": [0, 1] },
1670
- tokenPrec: 2679
1671
- });
1672
-
1673
- // src/rslang/parser/parser.terms.ts
1674
- var Local = 5;
1675
- var Tuple = 8;
1676
- var Predicate = 26;
1677
- var Variable_pack = 31;
1678
- var Integer = 39;
1679
- var EmptySet = 40;
1680
- var IntegerSet = 41;
1681
- var Global = 42;
1682
- var Radical = 43;
1683
- var Enumeration = 55;
1684
- var Boolean = 56;
1685
- var Filter = 59;
1686
- var Declarative = 60;
1687
- var Imperative = 64;
1688
- var Function = 69;
1689
- var BigPr = 70;
1690
- var SmallPr = 71;
1691
- var Card = 72;
1692
- var Bool = 73;
1693
- var Debool = 74;
1694
- var Red = 75;
1695
- var Function_decl = 76;
1696
- var Arguments = 77;
1697
- var Declaration = 78;
1698
-
1699
- // src/rslang/parser/normalize.ts
1700
- var idRecord = {
1701
- [Global]: TokenID.ID_GLOBAL,
1702
- [Local]: TokenID.ID_LOCAL,
1703
- [Radical]: TokenID.ID_RADICAL,
1704
- [Function]: TokenID.ID_FUNCTION,
1705
- [Predicate]: TokenID.ID_PREDICATE,
1706
- [Integer]: TokenID.LIT_INTEGER,
1707
- [EmptySet]: TokenID.LIT_EMPTYSET,
1708
- [IntegerSet]: TokenID.LIT_WHOLE_NUMBERS,
1709
- [Boolean]: TokenID.BOOLEAN,
1710
- [BigPr]: TokenID.BIGPR,
1711
- [SmallPr]: TokenID.SMALLPR,
1712
- [Filter]: TokenID.FILTER,
1713
- [Bool]: TokenID.BOOL,
1714
- [Debool]: TokenID.DEBOOL,
1715
- [Red]: TokenID.REDUCE,
1716
- [Card]: TokenID.CARD,
1717
- [Enumeration]: TokenID.NT_ENUMERATION,
1718
- [Tuple]: TokenID.NT_TUPLE,
1719
- [Arguments]: TokenID.NT_ARGUMENTS,
1720
- [Declaration]: TokenID.NT_ARG_DECL,
1721
- [Function_decl]: TokenID.NT_FUNC_DEFINITION,
1722
- [Variable_pack]: TokenID.NT_ENUM_DECL,
1723
- [Declarative]: TokenID.NT_DECLARATIVE_EXPR,
1724
- [Imperative]: TokenID.NT_IMPERATIVE_EXPR
1725
- };
1726
-
1727
- // src/rslang/labels.ts
1728
- var ANY_TYPE_NAME = "R0";
1729
- var LOGIC_TYPE_NAME = "Logic";
1730
- var labelTokenRecord = {
1731
- [TokenID.DECART]: "\xD7",
1732
- [TokenID.PUNCTUATION_PL]: "( )",
1733
- [TokenID.PUNCTUATION_SL]: "[ ]",
1734
- [TokenID.QUANTOR_UNIVERSAL]: "\u2200",
1735
- [TokenID.QUANTOR_EXISTS]: "\u2203",
1736
- [TokenID.LOGIC_NOT]: "\xAC",
1737
- [TokenID.LOGIC_AND]: "&",
1738
- [TokenID.LOGIC_OR]: "\u2228",
1739
- [TokenID.LOGIC_IMPLICATION]: "\u21D2",
1740
- [TokenID.LOGIC_EQUIVALENT]: "\u21D4",
1741
- [TokenID.LIT_EMPTYSET]: "\u2205",
1742
- [TokenID.LIT_WHOLE_NUMBERS]: "Z",
1743
- [TokenID.MULTIPLY]: "*",
1744
- [TokenID.EQUAL]: "=",
1745
- [TokenID.NOTEQUAL]: "\u2260",
1746
- [TokenID.GREATER_OR_EQ]: "\u2265",
1747
- [TokenID.LESSER_OR_EQ]: "\u2264",
1748
- [TokenID.SET_IN]: "\u2208",
1749
- [TokenID.SET_NOT_IN]: "\u2209",
1750
- [TokenID.SUBSET_OR_EQ]: "\u2286",
1751
- [TokenID.SUBSET]: "\u2282",
1752
- [TokenID.NOT_SUBSET]: "\u2284",
1753
- [TokenID.SET_INTERSECTION]: "\u2229",
1754
- [TokenID.SET_UNION]: "\u222A",
1755
- [TokenID.SET_MINUS]: "\\",
1756
- [TokenID.SET_SYMMETRIC_MINUS]: "\u2206",
1757
- [TokenID.BOOLEAN]: "\u212C()",
1758
- [TokenID.NT_DECLARATIVE_EXPR]: "D{}",
1759
- [TokenID.NT_IMPERATIVE_EXPR]: "I{}",
1760
- [TokenID.NT_RECURSIVE_FULL]: "R{}",
1761
- [TokenID.BIGPR]: "Pr1()",
1762
- [TokenID.SMALLPR]: "pr1()",
1763
- [TokenID.FILTER]: "Fi1[]()",
1764
- [TokenID.REDUCE]: "red()",
1765
- [TokenID.CARD]: "card()",
1766
- [TokenID.BOOL]: "bool()",
1767
- [TokenID.DEBOOL]: "debool()",
1768
- [TokenID.ASSIGN]: ":=",
1769
- [TokenID.ITERATE]: ":\u2208"
1770
- };
1771
- function normalizeType(type) {
1772
- if (!type) {
1773
- return "N/A";
1774
- }
1775
- switch (type.typeID) {
1776
- case TypeID.anyTypification:
1777
- return ANY_TYPE_NAME;
1778
- case TypeID.integer:
1779
- case TypeID.basic:
1780
- return "X1";
1781
- case TypeID.tuple:
1782
- return type.factors.map((factor) => factor.typeID === TypeID.tuple ? `(${normalizeType(factor)})` : normalizeType(factor)).join("\xD7");
1783
- case TypeID.collection:
1784
- return type.base.typeID === TypeID.collection ? `\u212C${normalizeType(type.base)}` : `\u212C(${normalizeType(type.base)})`;
1785
- case TypeID.logic:
1786
- return LOGIC_TYPE_NAME;
1787
- case TypeID.predicate:
1788
- case TypeID.function:
1789
- const argsText = type.args.map((arg) => normalizeType(arg.type)).join(", ");
1790
- return `[${argsText}] \u2192 ${normalizeType(type.result)}`;
1791
- }
1792
- }
1793
-
1794
- // src/rslang/semantic/typification-api.ts
1795
- var TypeIDToClass = {
1796
- [TypeID.anyTypification]: TypeClass.typification,
1797
- [TypeID.integer]: TypeClass.typification,
1798
- [TypeID.basic]: TypeClass.typification,
1799
- [TypeID.tuple]: TypeClass.typification,
1800
- [TypeID.collection]: TypeClass.typification,
1801
- [TypeID.logic]: TypeClass.logic,
1802
- [TypeID.function]: TypeClass.function,
1803
- [TypeID.predicate]: TypeClass.predicate
1804
- };
1805
-
1806
- // src/rslang/semantic/value-class.ts
1807
- var ValueClass = {
1808
- VALUE: "value",
1809
- PROPERTY: "property"
1810
- };
1811
-
1812
- // src/library/rsform.ts
1813
- var CstType = {
1814
- NOMINAL: "nominal",
1815
- BASE: "basic",
1816
- STRUCTURED: "structure",
1817
- TERM: "term",
1818
- AXIOM: "axiom",
1819
- FUNCTION: "function",
1820
- PREDICATE: "predicate",
1821
- CONSTANT: "constant",
1822
- STATEMENT: "statement"
1823
- };
1824
- var CstClass = {
1825
- NOMINAL: "nominal",
1826
- BASIC: "basic",
1827
- DERIVED: "derived",
1828
- STATEMENT: "statement",
1829
- TEMPLATE: "template"
1830
- };
1831
-
1832
- // src/library/rsform-api.ts
1833
- var CST_TYPE_PREFIX = {
1834
- [CstType.NOMINAL]: "N",
1835
- [CstType.BASE]: "X",
1836
- [CstType.CONSTANT]: "C",
1837
- [CstType.STRUCTURED]: "S",
1838
- [CstType.AXIOM]: "A",
1839
- [CstType.TERM]: "D",
1840
- [CstType.FUNCTION]: "F",
1841
- [CstType.PREDICATE]: "P",
1842
- [CstType.STATEMENT]: "T"
1843
- };
1844
- var CST_TYPE_TO_CLASS = {
1845
- [CstType.NOMINAL]: CstClass.NOMINAL,
1846
- [CstType.BASE]: CstClass.BASIC,
1847
- [CstType.CONSTANT]: CstClass.BASIC,
1848
- [CstType.STRUCTURED]: CstClass.BASIC,
1849
- [CstType.TERM]: CstClass.DERIVED,
1850
- [CstType.FUNCTION]: CstClass.DERIVED,
1851
- [CstType.AXIOM]: CstClass.STATEMENT,
1852
- [CstType.PREDICATE]: CstClass.DERIVED,
1853
- [CstType.STATEMENT]: CstClass.STATEMENT
1854
- };
1855
- function isBasicConcept(type) {
1856
- switch (type) {
1857
- case CstType.NOMINAL:
1858
- case CstType.BASE:
1859
- case CstType.CONSTANT:
1860
- case CstType.STRUCTURED:
1861
- case CstType.AXIOM:
1862
- return true;
1863
- case CstType.TERM:
1864
- case CstType.FUNCTION:
1865
- case CstType.PREDICATE:
1866
- case CstType.STATEMENT:
1867
- return false;
1868
- }
1869
- }
1870
- function isBaseSet(type) {
1871
- switch (type) {
1872
- case CstType.BASE:
1873
- case CstType.CONSTANT:
1874
- return true;
1875
- case CstType.NOMINAL:
1876
- case CstType.STRUCTURED:
1877
- case CstType.AXIOM:
1878
- case CstType.TERM:
1879
- case CstType.FUNCTION:
1880
- case CstType.PREDICATE:
1881
- case CstType.STATEMENT:
1882
- return false;
1883
- }
1884
- }
1885
- function isFunctional(type) {
1886
- switch (type) {
1887
- case CstType.FUNCTION:
1888
- case CstType.PREDICATE:
1889
- return true;
1890
- case CstType.NOMINAL:
1891
- case CstType.BASE:
1892
- case CstType.CONSTANT:
1893
- case CstType.STRUCTURED:
1894
- case CstType.AXIOM:
1895
- case CstType.TERM:
1896
- case CstType.STATEMENT:
1897
- return false;
1898
- }
1899
- }
1900
- function typeClassForCstType(cstType) {
1901
- switch (cstType) {
1902
- case CstType.NOMINAL:
1903
- case CstType.BASE:
1904
- case CstType.CONSTANT:
1905
- case CstType.STRUCTURED:
1906
- case CstType.TERM:
1907
- return TypeClass.typification;
1908
- case CstType.FUNCTION:
1909
- return TypeClass.function;
1910
- case CstType.PREDICATE:
1911
- return TypeClass.predicate;
1912
- case CstType.AXIOM:
1913
- case CstType.STATEMENT:
1914
- return TypeClass.logic;
1915
- }
1916
- }
1917
- function canHaveFormalDefinition(cstType) {
1918
- return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;
1919
- }
1920
- function getAnalysisFor(expression, cstType, schema, alias) {
1921
- if (!canHaveFormalDefinition(cstType)) {
1922
- if (expression.trim().length === 0) {
1923
- const fallbackAlias = alias && alias.length > 0 ? alias : "X0";
1924
- const type = cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias));
1925
- return {
1926
- success: true,
1927
- type,
1928
- valueClass: ValueClass.VALUE,
1929
- errors: [],
1930
- ast: null
1931
- };
1932
- }
1933
- return {
1934
- success: false,
1935
- type: null,
1936
- valueClass: null,
1937
- errors: [
1938
- {
1939
- code: RSErrorCode.definitionNotAllowed,
1940
- from: 0,
1941
- to: Math.max(0, expression.length - 1)
1942
- }
1943
- ],
1944
- ast: null
1945
- };
1946
- }
1947
- return schema.analyzer.checkFull(expression, {
1948
- expected: typeClassForCstType(cstType),
1949
- isDomain: cstType === CstType.STRUCTURED
1950
- });
1951
- }
1952
-
1953
- // src/library/rsmodel.ts
1954
- var TYPE_BASIC = "basic";
1955
- var EvalStatus = {
1956
- NO_EVAL: 1,
1957
- // не вычисляется
1958
- NOT_PROCESSED: 2,
1959
- // Интерпретация не вычислялась
1960
- INVALID_DATA: 3,
1961
- // Неверные данные
1962
- EVAL_FAIL: 4,
1963
- // Ошибка при вычислении
1964
- AXIOM_FALSE: 5,
1965
- // Значение аксиомы = FALSE
1966
- EMPTY: 6,
1967
- // Значение пусто
1968
- HAS_DATA: 7
1969
- // Интерпретация вычислена и не пуста
1970
- };
1971
-
1972
- // src/library/rsmodel-api.ts
1973
- function isInferrable(type) {
1974
- switch (type) {
1975
- case CstType.AXIOM:
1976
- case CstType.STATEMENT:
1977
- case CstType.TERM:
1978
- return true;
1979
- case CstType.NOMINAL:
1980
- case CstType.BASE:
1981
- case CstType.CONSTANT:
1982
- case CstType.STRUCTURED:
1983
- case CstType.FUNCTION:
1984
- case CstType.PREDICATE:
1985
- return false;
1986
- }
1987
- }
1988
- function inferEvalStatus(value, cstType, wasCalculated = true, isInvalid = false) {
1989
- if (isBaseSet(cstType) || cstType === CstType.STRUCTURED) {
1990
- if (isInvalid) {
1991
- return EvalStatus.INVALID_DATA;
1992
- }
1993
- if (value === null || Array.isArray(value) && value.length === 0) {
1994
- return EvalStatus.EMPTY;
1995
- }
1996
- return EvalStatus.HAS_DATA;
1997
- }
1998
- if (!isInferrable(cstType)) {
1999
- return EvalStatus.NO_EVAL;
2000
- }
2001
- if (!wasCalculated) {
2002
- return EvalStatus.NOT_PROCESSED;
2003
- }
2004
- if (value === null) {
2005
- return EvalStatus.EVAL_FAIL;
2006
- }
2007
- if (cstType === CstType.AXIOM && value !== VALUE_TRUE) {
2008
- return EvalStatus.AXIOM_FALSE;
2009
- }
2010
- if (Array.isArray(value) && value.length === 0) {
2011
- return EvalStatus.EMPTY;
2012
- }
2013
- return EvalStatus.HAS_DATA;
2014
- }
2015
- function tryFixValue(value, type, targetAlias, targetValue) {
2016
- switch (type.typeID) {
2017
- case TypeID.integer:
2018
- return false;
2019
- case TypeID.basic:
2020
- if (type.baseID !== targetAlias) {
2021
- return false;
2022
- }
2023
- if (typeof value !== "number") {
2024
- return null;
2025
- }
2026
- if (!targetValue.includes(value)) {
2027
- return null;
2028
- }
2029
- return false;
2030
- case TypeID.tuple: {
2031
- if (!isTupleValue(value)) {
2032
- return null;
2033
- }
2034
- let wasChanged2 = false;
2035
- for (let i = 0; i < type.factors.length; i++) {
2036
- const componentChanged = tryFixValue(value[i + 1], type.factors[i], targetAlias, targetValue);
2037
- if (componentChanged === null) {
2038
- return null;
2039
- }
2040
- if (componentChanged) {
2041
- wasChanged2 = true;
2042
- }
2043
- }
2044
- return wasChanged2;
2045
- }
2046
- case TypeID.collection:
2047
- if (!Array.isArray(value) || value.length > 1 && value[0] === TUPLE_ID) {
2048
- return null;
2049
- }
2050
- let wasChanged = false;
2051
- const removeElements = [];
2052
- for (const item of value) {
2053
- const elementChanged = tryFixValue(item, type.base, targetAlias, targetValue);
2054
- if (elementChanged === null || elementChanged === true) {
2055
- wasChanged = true;
2056
- if (elementChanged === null) {
2057
- removeElements.push(item);
2058
- }
2059
- }
2060
- }
2061
- for (const item of removeElements) {
2062
- const index = value.indexOf(item);
2063
- if (index !== -1) {
2064
- value.splice(index, 1);
2065
- }
2066
- }
2067
- if (wasChanged) {
2068
- value.sort((a, b) => compare(a, b));
2069
- let i = 1;
2070
- while (i < value.length) {
2071
- if (compare(value[i], value[i - 1]) === 0) {
2072
- value.splice(i, 1);
2073
- } else {
2074
- i++;
2075
- }
2076
- }
2077
- }
2078
- return wasChanged;
2079
- case TypeID.logic:
2080
- case TypeID.anyTypification:
2081
- case TypeID.predicate:
2082
- case TypeID.function:
2083
- return null;
2084
- }
2085
- }
2086
-
2087
- // src/library/rsengine.ts
2088
- var INVALID_TYPE_MARKER = "INVALID";
1
+ import { TypeID } from "../rslang/semantic/typification.js";
2
+ import { c as compare } from "../value-B8UtCqaK.js";
3
+ import { RSCalculator } from "../rslang/eval/calculator.js";
4
+ import { normalizeType } from "../rslang/labels.js";
5
+ import "../rslang/index.js";
6
+ import { CstType } from "./rsform.js";
7
+ import { getAnalysisFor, isBaseSet, isBasicConcept, isFunctional } from "./rsform-api.js";
8
+ import { TYPE_BASIC } from "./rsmodel.js";
9
+ import { inferEvalStatus, isInferrable, tryFixValue } from "./rsmodel-api.js";
10
+ //#region src/library/rsengine.ts
11
+ const INVALID_TYPE_MARKER = "INVALID";
12
+ /** Calculation engine for {@link RSModel}. */
2089
13
  var RSEngine = class {
2090
- modelID;
2091
- schema = null;
2092
- data = null;
2093
- calculator = new RSCalculator();
2094
- basics = /* @__PURE__ */ new Map();
2095
- services;
2096
- notifications;
2097
- invalidData = /* @__PURE__ */ new Set();
2098
- calculatedSet = /* @__PURE__ */ new Set();
2099
- valueSubscribers = /* @__PURE__ */ new Map();
2100
- statusSubscribers = /* @__PURE__ */ new Map();
2101
- changeSubscribers = /* @__PURE__ */ new Set();
2102
- changeGeneration = 0;
2103
- pendingChange = false;
2104
- coalescedEmitTimeout = null;
2105
- constructor(modelID, services, notifications = null) {
2106
- this.services = services;
2107
- this.notifications = notifications;
2108
- this.modelID = modelID;
2109
- }
2110
- /** Updates data for {@link RSEngine}. */
2111
- loadData(schema, model) {
2112
- const oldSchema = this.schema;
2113
- const newSchema = oldSchema !== schema;
2114
- this.schema = schema;
2115
- if (newSchema) {
2116
- const changedCst = this.collectChanged(oldSchema, schema);
2117
- this.prepareAst();
2118
- this.setupEmptySets();
2119
- this.onChangeDefinitions(changedCst);
2120
- }
2121
- if (this.data !== model) {
2122
- this.data = model;
2123
- this.prepareValues();
2124
- }
2125
- this.notifyAll();
2126
- }
2127
- /** Updates services for {@link RSEngine}. */
2128
- updateServices(services) {
2129
- this.services = services;
2130
- }
2131
- /** Updates notifications for {@link RSEngine}. */
2132
- updateNotifications(notifications) {
2133
- this.notifications = notifications;
2134
- }
2135
- /** Gets value of {@link Constituenta}. */
2136
- getCstValue(cstID) {
2137
- const cst = this.schema?.cstByID.get(cstID);
2138
- if (!cst) {
2139
- return null;
2140
- }
2141
- return this.calculator.getValue(cst.alias);
2142
- }
2143
- /** Gets status of {@link Constituenta}. */
2144
- getCstStatus(cstID) {
2145
- const cst = this.schema?.cstByID.get(cstID);
2146
- if (!cst) {
2147
- return inferEvalStatus(null, CstType.NOMINAL, false);
2148
- }
2149
- const value = this.calculator.getValue(cst.alias);
2150
- return inferEvalStatus(value, cst.cst_type, this.calculatedSet.has(cstID), this.invalidData.has(cstID));
2151
- }
2152
- /** Subscribe to value change of {@link Constituenta}. */
2153
- subscribeValue(cstID, callbackFn) {
2154
- let subs = this.valueSubscribers.get(cstID);
2155
- if (!subs) {
2156
- subs = /* @__PURE__ */ new Set();
2157
- this.valueSubscribers.set(cstID, subs);
2158
- }
2159
- subs.add(callbackFn);
2160
- return () => {
2161
- const current = this.valueSubscribers.get(cstID);
2162
- if (!current) {
2163
- return;
2164
- }
2165
- current.delete(callbackFn);
2166
- if (current.size === 0) {
2167
- this.valueSubscribers.delete(cstID);
2168
- }
2169
- };
2170
- }
2171
- /** Subscribe to status change of {@link Constituenta}. */
2172
- subscribeStatus(cstID, callbackFn) {
2173
- let subs = this.statusSubscribers.get(cstID);
2174
- if (!subs) {
2175
- subs = /* @__PURE__ */ new Set();
2176
- this.statusSubscribers.set(cstID, subs);
2177
- }
2178
- subs.add(callbackFn);
2179
- return () => {
2180
- const current = this.statusSubscribers.get(cstID);
2181
- if (!current) {
2182
- return;
2183
- }
2184
- current.delete(callbackFn);
2185
- if (current.size === 0) {
2186
- this.statusSubscribers.delete(cstID);
2187
- }
2188
- };
2189
- }
2190
- /**
2191
- * Subscribe to any engine change that can affect evaluation (values, status, or loaded data).
2192
- */
2193
- subscribeChanges(callbackFn) {
2194
- this.changeSubscribers.add(callbackFn);
2195
- return () => {
2196
- this.changeSubscribers.delete(callbackFn);
2197
- };
2198
- }
2199
- /** Monotonic counter bumped whenever the engine emits a change to {@link RSEngine.subscribeChanges} listeners. */
2200
- getChangeGeneration() {
2201
- return this.changeGeneration;
2202
- }
2203
- /**
2204
- * Runs pending {@link RSEngine.subscribeChanges} notifications immediately and clears the coalescing queue.
2205
- * Use after a synchronous batch of engine updates when listeners must observe a bumped {@link getChangeGeneration}
2206
- * in the same turn.
2207
- */
2208
- flushPendingChanges() {
2209
- if (this.coalescedEmitTimeout !== null) {
2210
- clearTimeout(this.coalescedEmitTimeout);
2211
- this.coalescedEmitTimeout = null;
2212
- }
2213
- if (!this.pendingChange) {
2214
- return;
2215
- }
2216
- this.pendingChange = false;
2217
- this.emitChange();
2218
- }
2219
- /** Sets value for {@link Constituenta} from {@link Value}. */
2220
- async setStructureValue(cstID, data) {
2221
- const cst = this.schema?.cstByID.get(cstID);
2222
- if (!this.schema || !cst || isInferrable(cst.cst_type)) {
2223
- this.notifications?.onInvalidSetValue();
2224
- return;
2225
- }
2226
- const typeStr = cst.effectiveType ? normalizeType(cst.effectiveType) : INVALID_TYPE_MARKER;
2227
- const payload = [{ target: cstID, type: typeStr, data }];
2228
- await this.services.setCstValue({ itemID: this.modelID, data: payload });
2229
- if (!cst.effectiveType || !this.calculator.validate(data, cst.effectiveType)) {
2230
- this.invalidData.add(cstID);
2231
- } else {
2232
- this.invalidData.delete(cstID);
2233
- }
2234
- this.calculator.setValue(cst.alias, data);
2235
- this.notifyCst(cstID);
2236
- this.cascadeReset([cstID]);
2237
- }
2238
- /** Sets value for {@link Constituenta} from {@link BasicBinding}. */
2239
- async setBasicValue(cstID, data) {
2240
- const cst = this.schema?.cstByID.get(cstID);
2241
- if (!this.schema || !cst || !isBaseSet(cst.cst_type)) {
2242
- this.notifications?.onInvalidSetValue();
2243
- return;
2244
- }
2245
- const oldValue = this.calculator.getValue(cst.alias);
2246
- const newValue = Object.keys(data).map(Number);
2247
- const updateList = [
2248
- { target: cstID, type: TYPE_BASIC, data }
2249
- ];
2250
- const resetList = [];
2251
- if (oldValue !== null && compare(newValue, oldValue) !== 0) {
2252
- const dependencies = this.schema.graph.expandAllOutputs([cstID]);
2253
- for (const childID of dependencies) {
2254
- const child = this.schema.cstByID.get(childID);
2255
- if (child.cst_type === CstType.STRUCTURED && !!child.effectiveType) {
2256
- const value = this.calculator.getValue(child.alias);
2257
- if (value !== null) {
2258
- const fix = tryFixValue(value, child.effectiveType, cst.alias, newValue);
2259
- if (fix === null) {
2260
- resetList.push(childID);
2261
- } else if (fix === true) {
2262
- const typeStr = normalizeType(child.effectiveType);
2263
- updateList.push({ target: childID, type: typeStr, data: [...value] });
2264
- }
2265
- }
2266
- }
2267
- }
2268
- }
2269
- if (resetList.length > 0) {
2270
- await Promise.all([
2271
- this.services.setCstValue({ itemID: this.modelID, data: updateList }),
2272
- this.services.clearValues({ itemID: this.modelID, data: { items: resetList } })
2273
- ]);
2274
- } else {
2275
- await this.services.setCstValue({ itemID: this.modelID, data: updateList });
2276
- }
2277
- const changed = [...resetList, ...updateList.map((item) => item.target)];
2278
- this.basics.set(cstID, data);
2279
- this.calculator.setValue(cst.alias, Object.keys(data).map(Number));
2280
- for (const item of resetList) {
2281
- this.calculator.resetValue(this.schema.cstByID.get(item).alias);
2282
- this.notifyCst(item);
2283
- }
2284
- for (const updateData of updateList) {
2285
- if (updateData.target !== cstID) {
2286
- this.calculator.setValue(
2287
- this.schema.cstByID.get(updateData.target).alias,
2288
- updateData.data
2289
- );
2290
- this.notifyCst(updateData.target);
2291
- }
2292
- }
2293
- for (const item of changed) {
2294
- this.notifyCst(item);
2295
- }
2296
- this.cascadeReset(changed);
2297
- }
2298
- /** Resets value for {@link Constituenta}. */
2299
- async resetValue(cstID) {
2300
- const cst = this.schema?.cstByID.get(cstID);
2301
- if (!cst) {
2302
- return;
2303
- }
2304
- await this.services.clearValues({ itemID: this.modelID, data: { items: [cstID] } });
2305
- this.calculator.resetValue(cst.alias);
2306
- this.basics.delete(cstID);
2307
- this.calculatedSet.delete(cstID);
2308
- this.invalidData.delete(cstID);
2309
- this.notifyCst(cstID);
2310
- }
2311
- /** Evaluates expression for {@link RSEngine}. */
2312
- evaluateExpression(expression, cstType) {
2313
- return getEvaluationFor(
2314
- expression,
2315
- cstType,
2316
- this.schema,
2317
- this.calculator,
2318
- (message) => this.notifications?.onEvaluationError(message)
2319
- );
2320
- }
2321
- /** Evaluates AST for {@link RSEngine}. */
2322
- evaluateAst(ast, options) {
2323
- try {
2324
- const evaluation = this.calculator.evaluateFull(ast, options);
2325
- return evaluation;
2326
- } catch (error) {
2327
- this.notifications?.onEvaluationError(error.message);
2328
- console.error(error);
2329
- return {
2330
- value: null,
2331
- iterations: 0,
2332
- cacheHits: 0,
2333
- errors: []
2334
- };
2335
- }
2336
- }
2337
- /** Calculates value for {@link Constituenta}. */
2338
- calculateCst(cstID) {
2339
- const cst = this.schema?.cstByID.get(cstID);
2340
- if (!cst || !this.schema) {
2341
- return { value: null, iterations: 0, errors: [], cacheHits: 0 };
2342
- }
2343
- if (!this.calculatedSet.has(cstID)) {
2344
- const predecessors = this.schema.graph.expandAllInputs([cstID]);
2345
- this.prepareEvaluation(predecessors);
2346
- }
2347
- const result = getEvaluationFor(
2348
- cst.definition_formal,
2349
- cst.cst_type,
2350
- this.schema,
2351
- this.calculator,
2352
- (message) => this.notifications?.onEvaluationError(message)
2353
- );
2354
- if (result.value === null) {
2355
- this.calculator.resetValue(cst.alias);
2356
- } else {
2357
- this.calculator.setValue(cst.alias, result.value);
2358
- }
2359
- this.calculatedSet.add(cstID);
2360
- this.notifyCst(cstID);
2361
- return result;
2362
- }
2363
- /** Recalculate model for all inferrable expressions. */
2364
- recalculateAll() {
2365
- const start = performance.now();
2366
- this.calculatedSet.clear();
2367
- this.recalculateInternal();
2368
- const end = performance.now();
2369
- const timeSpent = ((end - start) / 1e3).toFixed(2);
2370
- this.notifications?.onCalculationSuccess(timeSpent);
2371
- }
2372
- /** Notify subscribers about value and status change of {@link Constituenta}. */
2373
- notifyCst(cstID) {
2374
- this.notifyStatus(cstID);
2375
- this.notifyValue(cstID);
2376
- this.scheduleCoalescedEmitChange();
2377
- }
2378
- /** Notify all subscribers about value change. */
2379
- notifyValue(cstID) {
2380
- const subs = this.valueSubscribers.get(cstID);
2381
- if (subs) {
2382
- for (const cb of subs) cb();
2383
- }
2384
- }
2385
- /** Notify all subscribers about status change. */
2386
- notifyStatus(cstID) {
2387
- const subs = this.statusSubscribers.get(cstID);
2388
- if (subs) {
2389
- for (const cb of subs) cb();
2390
- }
2391
- }
2392
- /** Notify all subscribers about value and status change. */
2393
- notifyAll() {
2394
- for (const subs of this.valueSubscribers.values()) {
2395
- for (const cb of subs) cb();
2396
- }
2397
- for (const subs of this.statusSubscribers.values()) {
2398
- for (const cb of subs) cb();
2399
- }
2400
- this.scheduleCoalescedEmitChange();
2401
- }
2402
- scheduleCoalescedEmitChange() {
2403
- this.pendingChange = true;
2404
- if (this.coalescedEmitTimeout !== null) {
2405
- return;
2406
- }
2407
- this.coalescedEmitTimeout = setTimeout(
2408
- function runCoalescedEmitChange() {
2409
- this.coalescedEmitTimeout = null;
2410
- if (!this.pendingChange) {
2411
- return;
2412
- }
2413
- this.pendingChange = false;
2414
- this.emitChange();
2415
- }.bind(this),
2416
- 0
2417
- );
2418
- }
2419
- emitChange() {
2420
- this.changeGeneration += 1;
2421
- for (const cb of this.changeSubscribers) {
2422
- cb();
2423
- }
2424
- }
2425
- prepareAst() {
2426
- this.calculator.clearAllAst();
2427
- const functions = this.schema.items.filter((cst) => isFunctional(cst.cst_type) && cst.analysis?.success);
2428
- for (const cst of functions) {
2429
- const fullAnalysis = getAnalysisFor(cst.definition_formal, cst.cst_type, this.schema);
2430
- if (fullAnalysis.ast) {
2431
- this.calculator.setAST(cst.alias, fullAnalysis.ast);
2432
- }
2433
- }
2434
- }
2435
- prepareValues() {
2436
- this.basics.clear();
2437
- this.invalidData.clear();
2438
- this.calculatedSet.clear();
2439
- for (const item of this.data.items) {
2440
- const cst = this.schema.cstByID.get(item.id);
2441
- if (item.type === TYPE_BASIC) {
2442
- if (cst.cst_type !== CstType.BASE && cst.cst_type !== CstType.CONSTANT) {
2443
- throw new Error(`Invalid data for ${cst.alias}`);
2444
- }
2445
- const data = item.value;
2446
- this.basics.set(cst.id, data);
2447
- this.calculator.setValue(cst.alias, Object.keys(data).map(Number));
2448
- }
2449
- }
2450
- for (const item of this.data.items) {
2451
- const cst = this.schema.cstByID.get(item.id);
2452
- if (item.type !== TYPE_BASIC) {
2453
- this.calculator.setValue(cst.alias, item.value);
2454
- if (!cst.effectiveType || !this.calculator.validate(item.value, cst.effectiveType)) {
2455
- this.invalidData.add(item.id);
2456
- }
2457
- }
2458
- }
2459
- this.setupEmptySets();
2460
- }
2461
- setupEmptySets() {
2462
- for (const cst of this.schema.items) {
2463
- if (isBasicConcept(cst.cst_type) && this.schema.analyzer.getType(cst.alias)?.typeID === TypeID.collection) {
2464
- if (this.calculator.getValue(cst.alias) === null) {
2465
- this.calculator.setValue(cst.alias, []);
2466
- }
2467
- }
2468
- }
2469
- }
2470
- collectChanged(previousSchema, nextSchema) {
2471
- if (!previousSchema) {
2472
- return [];
2473
- }
2474
- const changedIDs = [];
2475
- for (const cst of nextSchema.items) {
2476
- const prev = previousSchema.cstByID.get(cst.id);
2477
- if (prev && (prev.definition_formal !== cst.definition_formal || prev.alias !== cst.alias)) {
2478
- changedIDs.push(cst.id);
2479
- }
2480
- }
2481
- return changedIDs;
2482
- }
2483
- onChangeDefinitions(cstIDs) {
2484
- if (!this.schema || cstIDs.length === 0) {
2485
- return;
2486
- }
2487
- for (const cstID of cstIDs) {
2488
- const cst = this.schema.cstByID.get(cstID);
2489
- if (!cst || !isInferrable(cst.cst_type)) {
2490
- continue;
2491
- }
2492
- this.calculatedSet.delete(cstID);
2493
- this.calculator.resetValue(cst.alias);
2494
- this.notifyCst(cstID);
2495
- }
2496
- this.cascadeReset(cstIDs);
2497
- }
2498
- cascadeReset(cstIDs) {
2499
- if (!this.schema) {
2500
- return;
2501
- }
2502
- const dependencies = this.schema.graph.expandAllOutputs(cstIDs);
2503
- for (const cstID of dependencies) {
2504
- const cst = this.schema.cstByID.get(cstID);
2505
- if (!cst || !isInferrable(cst.cst_type)) {
2506
- continue;
2507
- }
2508
- this.calculatedSet.delete(cstID);
2509
- this.calculator.resetValue(this.schema.cstByID.get(cstID).alias);
2510
- this.notifyCst(cstID);
2511
- }
2512
- }
2513
- prepareEvaluation(dependencies) {
2514
- for (const cstID of this.schema.graph.topologicalOrder()) {
2515
- if (dependencies.includes(cstID)) {
2516
- const cst = this.schema.cstByID.get(cstID);
2517
- if (isInferrable(cst.cst_type)) {
2518
- const value = fastEvaluation(
2519
- cst.definition_formal,
2520
- cst.cst_type,
2521
- this.schema,
2522
- this.calculator,
2523
- (message) => this.notifications?.onEvaluationError(message)
2524
- );
2525
- if (value !== null) {
2526
- this.calculator.setValue(cst.alias, value);
2527
- } else {
2528
- this.calculator.resetValue(cst.alias);
2529
- }
2530
- this.notifyCst(cstID);
2531
- }
2532
- this.calculatedSet.add(cstID);
2533
- }
2534
- }
2535
- }
2536
- recalculateInternal() {
2537
- const processedIDs = [];
2538
- for (const cst of this.schema.cstByID.values()) {
2539
- if (isInferrable(cst.cst_type)) {
2540
- this.calculator.resetValue(cst.alias);
2541
- }
2542
- }
2543
- for (const cstID of this.schema.graph.topologicalOrder()) {
2544
- processedIDs.push(cstID);
2545
- const cst = this.schema.cstByID.get(cstID);
2546
- if (isInferrable(cst.cst_type)) {
2547
- const value = fastEvaluation(cst.definition_formal, cst.cst_type, this.schema, this.calculator);
2548
- this.calculatedSet.add(cstID);
2549
- if (value !== null) {
2550
- this.calculator.setValue(cst.alias, value);
2551
- }
2552
- }
2553
- }
2554
- this.notifyAll();
2555
- }
14
+ modelID;
15
+ schema = null;
16
+ data = null;
17
+ calculator = new RSCalculator();
18
+ basics = /* @__PURE__ */ new Map();
19
+ services;
20
+ notifications;
21
+ invalidData = /* @__PURE__ */ new Set();
22
+ calculatedSet = /* @__PURE__ */ new Set();
23
+ valueSubscribers = /* @__PURE__ */ new Map();
24
+ statusSubscribers = /* @__PURE__ */ new Map();
25
+ changeSubscribers = /* @__PURE__ */ new Set();
26
+ changeGeneration = 0;
27
+ pendingChange = false;
28
+ coalescedEmitTimeout = null;
29
+ constructor(modelID, services, notifications = null) {
30
+ this.services = services;
31
+ this.notifications = notifications;
32
+ this.modelID = modelID;
33
+ }
34
+ /** Updates data for {@link RSEngine}. */
35
+ loadData(schema, model) {
36
+ const oldSchema = this.schema;
37
+ const newSchema = oldSchema !== schema;
38
+ this.schema = schema;
39
+ if (newSchema) {
40
+ const changedCst = this.collectChanged(oldSchema, schema);
41
+ this.prepareAst();
42
+ this.setupEmptySets();
43
+ this.onChangeDefinitions(changedCst);
44
+ }
45
+ if (this.data !== model) {
46
+ this.data = model;
47
+ this.prepareValues();
48
+ }
49
+ this.notifyAll();
50
+ }
51
+ /** Updates services for {@link RSEngine}. */
52
+ updateServices(services) {
53
+ this.services = services;
54
+ }
55
+ /** Updates notifications for {@link RSEngine}. */
56
+ updateNotifications(notifications) {
57
+ this.notifications = notifications;
58
+ }
59
+ /** Gets value of {@link Constituenta}. */
60
+ getCstValue(cstID) {
61
+ const cst = this.schema?.cstByID.get(cstID);
62
+ if (!cst) return null;
63
+ return this.calculator.getValue(cst.alias);
64
+ }
65
+ /** Gets status of {@link Constituenta}. */
66
+ getCstStatus(cstID) {
67
+ const cst = this.schema?.cstByID.get(cstID);
68
+ if (!cst) return inferEvalStatus(null, CstType.NOMINAL, false);
69
+ return inferEvalStatus(this.calculator.getValue(cst.alias), cst.cst_type, this.calculatedSet.has(cstID), this.invalidData.has(cstID));
70
+ }
71
+ /** Subscribe to value change of {@link Constituenta}. */
72
+ subscribeValue(cstID, callbackFn) {
73
+ let subs = this.valueSubscribers.get(cstID);
74
+ if (!subs) {
75
+ subs = /* @__PURE__ */ new Set();
76
+ this.valueSubscribers.set(cstID, subs);
77
+ }
78
+ subs.add(callbackFn);
79
+ return () => {
80
+ const current = this.valueSubscribers.get(cstID);
81
+ if (!current) return;
82
+ current.delete(callbackFn);
83
+ if (current.size === 0) this.valueSubscribers.delete(cstID);
84
+ };
85
+ }
86
+ /** Subscribe to status change of {@link Constituenta}. */
87
+ subscribeStatus(cstID, callbackFn) {
88
+ let subs = this.statusSubscribers.get(cstID);
89
+ if (!subs) {
90
+ subs = /* @__PURE__ */ new Set();
91
+ this.statusSubscribers.set(cstID, subs);
92
+ }
93
+ subs.add(callbackFn);
94
+ return () => {
95
+ const current = this.statusSubscribers.get(cstID);
96
+ if (!current) return;
97
+ current.delete(callbackFn);
98
+ if (current.size === 0) this.statusSubscribers.delete(cstID);
99
+ };
100
+ }
101
+ /**
102
+ * Subscribe to any engine change that can affect evaluation (values, status, or loaded data).
103
+ */
104
+ subscribeChanges(callbackFn) {
105
+ this.changeSubscribers.add(callbackFn);
106
+ return () => {
107
+ this.changeSubscribers.delete(callbackFn);
108
+ };
109
+ }
110
+ /** Monotonic counter bumped whenever the engine emits a change to {@link RSEngine.subscribeChanges} listeners. */
111
+ getChangeGeneration() {
112
+ return this.changeGeneration;
113
+ }
114
+ /**
115
+ * Runs pending {@link RSEngine.subscribeChanges} notifications immediately and clears the coalescing queue.
116
+ * Use after a synchronous batch of engine updates when listeners must observe a bumped {@link getChangeGeneration}
117
+ * in the same turn.
118
+ */
119
+ flushPendingChanges() {
120
+ if (this.coalescedEmitTimeout !== null) {
121
+ clearTimeout(this.coalescedEmitTimeout);
122
+ this.coalescedEmitTimeout = null;
123
+ }
124
+ if (!this.pendingChange) return;
125
+ this.pendingChange = false;
126
+ this.emitChange();
127
+ }
128
+ /** Sets value for {@link Constituenta} from {@link Value}. */
129
+ async setStructureValue(cstID, data) {
130
+ const cst = this.schema?.cstByID.get(cstID);
131
+ if (!this.schema || !cst || isInferrable(cst.cst_type)) {
132
+ this.notifications?.onInvalidSetValue();
133
+ return;
134
+ }
135
+ const payload = [{
136
+ target: cstID,
137
+ type: cst.effectiveType ? normalizeType(cst.effectiveType) : INVALID_TYPE_MARKER,
138
+ data
139
+ }];
140
+ await this.services.setCstValue({
141
+ itemID: this.modelID,
142
+ data: payload
143
+ });
144
+ if (!cst.effectiveType || !this.calculator.validate(data, cst.effectiveType)) this.invalidData.add(cstID);
145
+ else this.invalidData.delete(cstID);
146
+ this.calculator.setValue(cst.alias, data);
147
+ this.notifyCst(cstID);
148
+ this.cascadeReset([cstID]);
149
+ }
150
+ /** Sets value for {@link Constituenta} from {@link BasicBinding}. */
151
+ async setBasicValue(cstID, data) {
152
+ const cst = this.schema?.cstByID.get(cstID);
153
+ if (!this.schema || !cst || !isBaseSet(cst.cst_type)) {
154
+ this.notifications?.onInvalidSetValue();
155
+ return;
156
+ }
157
+ const oldValue = this.calculator.getValue(cst.alias);
158
+ const newValue = Object.keys(data).map(Number);
159
+ const updateList = [{
160
+ target: cstID,
161
+ type: TYPE_BASIC,
162
+ data
163
+ }];
164
+ const resetList = [];
165
+ if (oldValue !== null && compare(newValue, oldValue) !== 0) {
166
+ const dependencies = this.schema.graph.expandAllOutputs([cstID]);
167
+ for (const childID of dependencies) {
168
+ const child = this.schema.cstByID.get(childID);
169
+ if (child.cst_type === CstType.STRUCTURED && !!child.effectiveType) {
170
+ const value = this.calculator.getValue(child.alias);
171
+ if (value !== null) {
172
+ const fix = tryFixValue(value, child.effectiveType, cst.alias, newValue);
173
+ if (fix === null) resetList.push(childID);
174
+ else if (fix === true) {
175
+ const typeStr = normalizeType(child.effectiveType);
176
+ updateList.push({
177
+ target: childID,
178
+ type: typeStr,
179
+ data: [...value]
180
+ });
181
+ }
182
+ }
183
+ }
184
+ }
185
+ }
186
+ if (resetList.length > 0) await Promise.all([this.services.setCstValue({
187
+ itemID: this.modelID,
188
+ data: updateList
189
+ }), this.services.clearValues({
190
+ itemID: this.modelID,
191
+ data: { items: resetList }
192
+ })]);
193
+ else await this.services.setCstValue({
194
+ itemID: this.modelID,
195
+ data: updateList
196
+ });
197
+ const changed = [...resetList, ...updateList.map((item) => item.target)];
198
+ this.basics.set(cstID, data);
199
+ this.calculator.setValue(cst.alias, Object.keys(data).map(Number));
200
+ for (const item of resetList) {
201
+ this.calculator.resetValue(this.schema.cstByID.get(item).alias);
202
+ this.notifyCst(item);
203
+ }
204
+ for (const updateData of updateList) if (updateData.target !== cstID) {
205
+ this.calculator.setValue(this.schema.cstByID.get(updateData.target).alias, updateData.data);
206
+ this.notifyCst(updateData.target);
207
+ }
208
+ for (const item of changed) this.notifyCst(item);
209
+ this.cascadeReset(changed);
210
+ }
211
+ /** Resets value for {@link Constituenta}. */
212
+ async resetValue(cstID) {
213
+ const cst = this.schema?.cstByID.get(cstID);
214
+ if (!cst) return;
215
+ await this.services.clearValues({
216
+ itemID: this.modelID,
217
+ data: { items: [cstID] }
218
+ });
219
+ this.calculator.resetValue(cst.alias);
220
+ this.basics.delete(cstID);
221
+ this.calculatedSet.delete(cstID);
222
+ this.invalidData.delete(cstID);
223
+ this.notifyCst(cstID);
224
+ }
225
+ /** Evaluates expression for {@link RSEngine}. */
226
+ evaluateExpression(expression, cstType) {
227
+ return getEvaluationFor(expression, cstType, this.schema, this.calculator, (message) => this.notifications?.onEvaluationError(message));
228
+ }
229
+ /** Evaluates AST for {@link RSEngine}. */
230
+ evaluateAst(ast, options) {
231
+ try {
232
+ return this.calculator.evaluateFull(ast, options);
233
+ } catch (error) {
234
+ this.notifications?.onEvaluationError(error.message);
235
+ console.error(error);
236
+ return {
237
+ value: null,
238
+ iterations: 0,
239
+ cacheHits: 0,
240
+ errors: []
241
+ };
242
+ }
243
+ }
244
+ /** Calculates value for {@link Constituenta}. */
245
+ calculateCst(cstID) {
246
+ const cst = this.schema?.cstByID.get(cstID);
247
+ if (!cst || !this.schema) return {
248
+ value: null,
249
+ iterations: 0,
250
+ errors: [],
251
+ cacheHits: 0
252
+ };
253
+ if (!this.calculatedSet.has(cstID)) {
254
+ const predecessors = this.schema.graph.expandAllInputs([cstID]);
255
+ this.prepareEvaluation(predecessors);
256
+ }
257
+ const result = getEvaluationFor(cst.definition_formal, cst.cst_type, this.schema, this.calculator, (message) => this.notifications?.onEvaluationError(message));
258
+ if (result.value === null) this.calculator.resetValue(cst.alias);
259
+ else this.calculator.setValue(cst.alias, result.value);
260
+ this.calculatedSet.add(cstID);
261
+ this.notifyCst(cstID);
262
+ return result;
263
+ }
264
+ /** Recalculate model for all inferrable expressions. */
265
+ recalculateAll() {
266
+ const start = performance.now();
267
+ this.calculatedSet.clear();
268
+ this.recalculateInternal();
269
+ const timeSpent = ((performance.now() - start) / 1e3).toFixed(2);
270
+ this.notifications?.onCalculationSuccess(timeSpent);
271
+ }
272
+ /** Notify subscribers about value and status change of {@link Constituenta}. */
273
+ notifyCst(cstID) {
274
+ this.notifyStatus(cstID);
275
+ this.notifyValue(cstID);
276
+ this.scheduleCoalescedEmitChange();
277
+ }
278
+ /** Notify all subscribers about value change. */
279
+ notifyValue(cstID) {
280
+ const subs = this.valueSubscribers.get(cstID);
281
+ if (subs) for (const cb of subs) cb();
282
+ }
283
+ /** Notify all subscribers about status change. */
284
+ notifyStatus(cstID) {
285
+ const subs = this.statusSubscribers.get(cstID);
286
+ if (subs) for (const cb of subs) cb();
287
+ }
288
+ /** Notify all subscribers about value and status change. */
289
+ notifyAll() {
290
+ for (const subs of this.valueSubscribers.values()) for (const cb of subs) cb();
291
+ for (const subs of this.statusSubscribers.values()) for (const cb of subs) cb();
292
+ this.scheduleCoalescedEmitChange();
293
+ }
294
+ scheduleCoalescedEmitChange() {
295
+ this.pendingChange = true;
296
+ if (this.coalescedEmitTimeout !== null) return;
297
+ this.coalescedEmitTimeout = setTimeout(function runCoalescedEmitChange() {
298
+ this.coalescedEmitTimeout = null;
299
+ if (!this.pendingChange) return;
300
+ this.pendingChange = false;
301
+ this.emitChange();
302
+ }.bind(this), 0);
303
+ }
304
+ emitChange() {
305
+ this.changeGeneration += 1;
306
+ for (const cb of this.changeSubscribers) cb();
307
+ }
308
+ prepareAst() {
309
+ this.calculator.clearAllAst();
310
+ const functions = this.schema.items.filter((cst) => isFunctional(cst.cst_type) && cst.analysis?.success);
311
+ for (const cst of functions) {
312
+ const fullAnalysis = getAnalysisFor(cst.definition_formal, cst.cst_type, this.schema);
313
+ if (fullAnalysis.ast) this.calculator.setAST(cst.alias, fullAnalysis.ast);
314
+ }
315
+ }
316
+ prepareValues() {
317
+ this.basics.clear();
318
+ this.invalidData.clear();
319
+ this.calculatedSet.clear();
320
+ for (const item of this.data.items) {
321
+ const cst = this.schema.cstByID.get(item.id);
322
+ if (item.type === "basic") {
323
+ if (cst.cst_type !== CstType.BASE && cst.cst_type !== CstType.CONSTANT) throw new Error(`Invalid data for ${cst.alias}`);
324
+ const data = item.value;
325
+ this.basics.set(cst.id, data);
326
+ this.calculator.setValue(cst.alias, Object.keys(data).map(Number));
327
+ }
328
+ }
329
+ for (const item of this.data.items) {
330
+ const cst = this.schema.cstByID.get(item.id);
331
+ if (item.type !== "basic") {
332
+ this.calculator.setValue(cst.alias, item.value);
333
+ if (!cst.effectiveType || !this.calculator.validate(item.value, cst.effectiveType)) this.invalidData.add(item.id);
334
+ }
335
+ }
336
+ this.setupEmptySets();
337
+ }
338
+ setupEmptySets() {
339
+ for (const cst of this.schema.items) if (isBasicConcept(cst.cst_type) && this.schema.analyzer.getType(cst.alias)?.typeID === TypeID.collection) {
340
+ if (this.calculator.getValue(cst.alias) === null) this.calculator.setValue(cst.alias, []);
341
+ }
342
+ }
343
+ collectChanged(previousSchema, nextSchema) {
344
+ if (!previousSchema) return [];
345
+ const changedIDs = [];
346
+ for (const cst of nextSchema.items) {
347
+ const prev = previousSchema.cstByID.get(cst.id);
348
+ if (prev && (prev.definition_formal !== cst.definition_formal || prev.alias !== cst.alias)) changedIDs.push(cst.id);
349
+ }
350
+ return changedIDs;
351
+ }
352
+ onChangeDefinitions(cstIDs) {
353
+ if (!this.schema || cstIDs.length === 0) return;
354
+ for (const cstID of cstIDs) {
355
+ const cst = this.schema.cstByID.get(cstID);
356
+ if (!cst || !isInferrable(cst.cst_type)) continue;
357
+ this.calculatedSet.delete(cstID);
358
+ this.calculator.resetValue(cst.alias);
359
+ this.notifyCst(cstID);
360
+ }
361
+ this.cascadeReset(cstIDs);
362
+ }
363
+ cascadeReset(cstIDs) {
364
+ if (!this.schema) return;
365
+ const dependencies = this.schema.graph.expandAllOutputs(cstIDs);
366
+ for (const cstID of dependencies) {
367
+ const cst = this.schema.cstByID.get(cstID);
368
+ if (!cst || !isInferrable(cst.cst_type)) continue;
369
+ this.calculatedSet.delete(cstID);
370
+ this.calculator.resetValue(this.schema.cstByID.get(cstID).alias);
371
+ this.notifyCst(cstID);
372
+ }
373
+ }
374
+ prepareEvaluation(dependencies) {
375
+ for (const cstID of this.schema.graph.topologicalOrder()) if (dependencies.includes(cstID)) {
376
+ const cst = this.schema.cstByID.get(cstID);
377
+ if (isInferrable(cst.cst_type)) {
378
+ const value = fastEvaluation(cst.definition_formal, cst.cst_type, this.schema, this.calculator, (message) => this.notifications?.onEvaluationError(message));
379
+ if (value !== null) this.calculator.setValue(cst.alias, value);
380
+ else this.calculator.resetValue(cst.alias);
381
+ this.notifyCst(cstID);
382
+ }
383
+ this.calculatedSet.add(cstID);
384
+ }
385
+ }
386
+ recalculateInternal() {
387
+ const processedIDs = [];
388
+ for (const cst of this.schema.cstByID.values()) if (isInferrable(cst.cst_type)) this.calculator.resetValue(cst.alias);
389
+ for (const cstID of this.schema.graph.topologicalOrder()) {
390
+ processedIDs.push(cstID);
391
+ const cst = this.schema.cstByID.get(cstID);
392
+ if (isInferrable(cst.cst_type)) {
393
+ const value = fastEvaluation(cst.definition_formal, cst.cst_type, this.schema, this.calculator);
394
+ this.calculatedSet.add(cstID);
395
+ if (value !== null) this.calculator.setValue(cst.alias, value);
396
+ }
397
+ }
398
+ this.notifyAll();
399
+ }
2556
400
  };
401
+ /** Evaluates expression for {@link Constituenta}, including error handling. */
2557
402
  function getEvaluationFor(expression, cstType, schema, calculator, onEvaluationError) {
2558
- const parse = getAnalysisFor(expression, cstType, schema);
2559
- if (!parse.success || !parse.ast) {
2560
- return {
2561
- value: null,
2562
- iterations: 0,
2563
- cacheHits: 0,
2564
- errors: parse.errors
2565
- };
2566
- } else {
2567
- try {
2568
- const result = calculator.evaluateFull(parse.ast);
2569
- return {
2570
- value: result.value,
2571
- iterations: result.iterations,
2572
- cacheHits: result.cacheHits,
2573
- errors: [...parse.errors, ...result.errors]
2574
- };
2575
- } catch (error) {
2576
- onEvaluationError?.(error.message);
2577
- console.error(expression, error);
2578
- return {
2579
- value: null,
2580
- iterations: 0,
2581
- cacheHits: 0,
2582
- errors: []
2583
- };
2584
- }
2585
- }
2586
- }
403
+ const parse = getAnalysisFor(expression, cstType, schema);
404
+ if (!parse.success || !parse.ast) return {
405
+ value: null,
406
+ iterations: 0,
407
+ cacheHits: 0,
408
+ errors: parse.errors
409
+ };
410
+ else try {
411
+ const result = calculator.evaluateFull(parse.ast);
412
+ return {
413
+ value: result.value,
414
+ iterations: result.iterations,
415
+ cacheHits: result.cacheHits,
416
+ errors: [...parse.errors, ...result.errors]
417
+ };
418
+ } catch (error) {
419
+ onEvaluationError?.(error.message);
420
+ console.error(expression, error);
421
+ return {
422
+ value: null,
423
+ iterations: 0,
424
+ cacheHits: 0,
425
+ errors: []
426
+ };
427
+ }
428
+ }
429
+ /** Evaluates expression for {@link RSModel}. */
2587
430
  function fastEvaluation(expression, cstType, schema, calculator, onEvaluationError) {
2588
- const parse = getAnalysisFor(expression, cstType, schema);
2589
- if (!parse.success || !parse.ast) {
2590
- return null;
2591
- } else {
2592
- try {
2593
- return calculator.evaluateFast(parse.ast);
2594
- } catch (error) {
2595
- onEvaluationError?.(error.message);
2596
- console.error(expression, error);
2597
- return null;
2598
- }
2599
- }
2600
- }
2601
- export {
2602
- RSEngine
2603
- };
431
+ const parse = getAnalysisFor(expression, cstType, schema);
432
+ if (!parse.success || !parse.ast) return null;
433
+ else try {
434
+ return calculator.evaluateFast(parse.ast);
435
+ } catch (error) {
436
+ onEvaluationError?.(error.message);
437
+ console.error(expression, error);
438
+ return null;
439
+ }
440
+ }
441
+ //#endregion
442
+ export { RSEngine };
443
+
2604
444
  //# sourceMappingURL=rsengine.js.map