@rsconcept/domain 2.1.1 → 2.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 (57) hide show
  1. package/dist/api-Bf0f_uiI.d.ts +57 -0
  2. package/dist/{diagnostics-CY9sKggB.js → diagnostics-B1OfMra1.js} +412 -174
  3. package/dist/diagnostics-B1OfMra1.js.map +1 -0
  4. package/dist/{diagnostics-EaIt3zIw.d.ts → diagnostics-Db1F7ruF.d.ts} +3 -3
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +2 -2
  7. package/dist/library/diagnostics.d.ts +1 -1
  8. package/dist/library/diagnostics.js +1 -1
  9. package/dist/library/index.d.ts +1 -1
  10. package/dist/library/index.js +1 -1
  11. package/dist/library/oss-api.d.ts +1 -1
  12. package/dist/library/oss-api.js +3 -3
  13. package/dist/library/oss-api.js.map +1 -1
  14. package/dist/library/rsengine.d.ts +1 -1
  15. package/dist/library/rsengine.js +1 -1
  16. package/dist/library/{rsform-api.d.ts → rsform-api/index.d.ts} +109 -66
  17. package/dist/library/rsform-api/index.js +2 -0
  18. package/dist/library/rsform.d.ts +1 -1
  19. package/dist/library/rsform.js.map +1 -1
  20. package/dist/library/rsmodel-api.d.ts +1 -1
  21. package/dist/library/rsmodel-api.js +3 -1
  22. package/dist/library/rsmodel-api.js.map +1 -1
  23. package/dist/library/rsmodel.d.ts +1 -1
  24. package/dist/library/structure-planner.d.ts +1 -1
  25. package/dist/library/structure-planner.js +1 -1
  26. package/dist/rslang/api.d.ts +2 -58
  27. package/dist/rslang/api.js +1 -1
  28. package/dist/rslang/index.js +1 -1
  29. package/dist/rslang/parser/syntax-errors/index.js +1 -1
  30. package/dist/rslang/semantic/analyzer.js +2 -2
  31. package/dist/{syntax-errors-D_VV5hAM.js → syntax-errors-BN_bqTaX.js} +21 -7
  32. package/dist/syntax-errors-BN_bqTaX.js.map +1 -0
  33. package/package.json +3 -3
  34. package/src/library/oss-api.ts +5 -2
  35. package/src/library/rsform-api/alias.ts +104 -0
  36. package/src/library/rsform-api/analysis.ts +157 -0
  37. package/src/library/rsform-api/cst-type.ts +216 -0
  38. package/src/library/rsform-api/expression.ts +73 -0
  39. package/src/library/rsform-api/formal-graph.test.ts +72 -0
  40. package/src/library/rsform-api/formal-graph.ts +195 -0
  41. package/src/library/rsform-api/index.ts +32 -0
  42. package/src/library/rsform-api/semantic-relations.ts +117 -0
  43. package/src/library/rsform-api/stats.ts +170 -0
  44. package/src/library/rsform-api/structure.ts +93 -0
  45. package/src/library/rsform-api/synthesis.ts +27 -0
  46. package/src/library/rsform-api/types.ts +21 -0
  47. package/src/library/rsform.ts +2 -2
  48. package/src/library/rsmodel-api.ts +7 -1
  49. package/src/rslang/parser/parser.test.ts +15 -0
  50. package/src/rslang/parser/syntax-errors/ast-utils.ts +11 -0
  51. package/src/rslang/parser/syntax-errors/generators.ts +1 -11
  52. package/src/rslang/parser/syntax-errors/incomplete-formal.ts +20 -0
  53. package/src/rslang/parser/syntax-errors/trailing-slot.ts +12 -1
  54. package/dist/diagnostics-CY9sKggB.js.map +0 -1
  55. package/dist/library/rsform-api.js +0 -2
  56. package/dist/syntax-errors-D_VV5hAM.js.map +0 -1
  57. package/src/library/rsform-api.ts +0 -755
@@ -1,17 +1,19 @@
1
+ import { Graph } from "./graph/graph.js";
1
2
  import { TypeClass, TypeID, basic, bool, constant, isTypification } from "./rslang/semantic/typification.js";
2
3
  import { labelType } from "./rslang/labels.js";
3
4
  import { applyEntityReferenceMapping } from "./cctext/language-api.js";
4
- import { RSErrorCode } from "./rslang/error.js";
5
5
  import { generateExpressionFromAst } from "./rslang/parser/expression-generator.js";
6
- import { applyAliasMapping, applyTypificationMapping, extractGlobals, parseRSLangExpression } from "./rslang/api.js";
6
+ import { applyAliasMapping, applyTypificationMapping, extractGlobals, isSimpleExpression, parseRSLangExpression, splitTemplateDefinition } from "./rslang/api.js";
7
+ import { RSErrorCode } from "./rslang/error.js";
7
8
  import { applyPath } from "./rslang/semantic/typification-api.js";
8
9
  import { ValueClass } from "./rslang/semantic/value-class.js";
9
10
  import "./rslang/index.js";
10
11
  import { CstClass, CstStatus, CstType } from "./library/rsform.js";
12
+ import "./graph/index.js";
11
13
  import { EvalStatus } from "./library/rsmodel.js";
12
- //#region src/library/rsform-api.ts
14
+ //#region src/library/rsform-api/cst-type.ts
13
15
  /**
14
- * Module: API for formal representation for systems of concepts.
16
+ * CstType classification, prefixes, and capability predicates.
15
17
  */
16
18
  /** Record of {@link CstType} prefixes. */
17
19
  const CST_TYPE_PREFIX = {
@@ -37,48 +39,15 @@ const CST_TYPE_TO_CLASS = {
37
39
  [CstType.PREDICATE]: CstClass.DERIVED,
38
40
  [CstType.STATEMENT]: CstClass.STATEMENT
39
41
  };
40
- /** Checks if {@link Constituenta} is a schema issue. */
41
- function isSchemaIssue(cst) {
42
- return (cst.diagnostics?.length ?? 0) > 0 || cst.status === CstStatus.INCORRECT || cst.status === CstStatus.INCALCULABLE;
43
- }
44
- /** Infers the status of an expression based on parsing and value information. */
45
- function inferStatus(parse, value) {
46
- if (!parse) return CstStatus.INCORRECT;
47
- if (value === null) return CstStatus.INCALCULABLE;
48
- if (value === ValueClass.PROPERTY) return CstStatus.PROPERTY;
49
- return CstStatus.VERIFIED;
50
- }
51
- /** Infers type of constituent for a given template and arguments. */
52
- function inferTemplatedType(templateType, args) {
53
- if (args.length === 0 || args.some((arg) => !arg.value)) return templateType;
54
- else if (templateType === CstType.PREDICATE) return CstType.AXIOM;
55
- else return CstType.TERM;
56
- }
57
- /** Build alias mapping from template argument bindings. */
58
- function argumentValuesToMapping(args) {
59
- const mapping = {};
60
- for (const arg of args) if (arg.value) mapping[arg.alias] = arg.value;
61
- return mapping;
62
- }
63
- /**
64
- * Normalize a RSLang expression for duplicate comparison.
65
- *
66
- * Returns `null` for basic concepts without formal definitions. Pass a pre-parsed `ast`
67
- * when the expression was already analyzed to avoid re-parsing.
68
- */
69
- function normalizeExpression(expression, cst_type, ast) {
70
- if (isBasicConcept(cst_type) && cst_type !== CstType.AXIOM) return null;
71
- const parsed = ast ?? parseRSLangExpression(expression);
72
- let normalized = "";
73
- if (parsed && !parsed.hasError) normalized = generateExpressionFromAst(parsed, { normalize: true });
74
- else normalized = expression;
75
- normalized = normalized.replace(/\s+/g, "");
76
- return normalized === "" ? null : normalized;
42
+ /** Prefix for alias indicating {@link CstType}. */
43
+ function getCstTypePrefix(type) {
44
+ return CST_TYPE_PREFIX[type];
77
45
  }
78
- /** Checks if given expression is a template. */
79
- function inferTemplate(expression) {
80
- const match = expression.match(/R\d+/g);
81
- return (match && match?.length > 0) ?? false;
46
+ /** Guess {@link CstType} from user input hint. */
47
+ function guessCstType(hint) {
48
+ if (hint.length !== 1) return null;
49
+ for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) if (hint === prefix) return type;
50
+ return null;
82
51
  }
83
52
  /** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */
84
53
  function inferClass(type, isTemplate = false) {
@@ -89,23 +58,6 @@ function inferClass(type, isTemplate = false) {
89
58
  function isTemplateCst(cst) {
90
59
  return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;
91
60
  }
92
- /** Apply filter based on start {@link Constituenta} type. */
93
- function applyFilterCategory(start, items) {
94
- const startIndex = items.indexOf(start);
95
- if (startIndex === -1) return [];
96
- const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);
97
- return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));
98
- }
99
- /** Prefix for alias indicating {@link CstType}. */
100
- function getCstTypePrefix(type) {
101
- return CST_TYPE_PREFIX[type];
102
- }
103
- /** Guess {@link CstType} from user input hint. */
104
- function guessCstType(hint) {
105
- if (hint.length !== 1) return null;
106
- for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) if (hint === prefix) return type;
107
- return null;
108
- }
109
61
  /** Evaluate if {@link CstType} is basic concept. */
110
62
  function isBasicConcept(type) {
111
63
  switch (type) {
@@ -162,6 +114,38 @@ function isLogical(type) {
162
114
  case CstType.PREDICATE: return false;
163
115
  }
164
116
  }
117
+ /** Evaluate if {@link CstType} can have manual typification. */
118
+ function canHaveManualTypification(type) {
119
+ switch (type) {
120
+ case CstType.STRUCTURED:
121
+ case CstType.TERM:
122
+ case CstType.FUNCTION:
123
+ case CstType.PREDICATE: return true;
124
+ case CstType.NOMINAL:
125
+ case CstType.BASE:
126
+ case CstType.CONSTANT:
127
+ case CstType.AXIOM:
128
+ case CstType.STATEMENT: return false;
129
+ }
130
+ }
131
+ /** Checks whether a constituenta type supports formal definitions. */
132
+ function canHaveFormalDefinition(cstType) {
133
+ return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;
134
+ }
135
+ /** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */
136
+ function typeClassForCstType(cstType) {
137
+ switch (cstType) {
138
+ case CstType.NOMINAL:
139
+ case CstType.BASE:
140
+ case CstType.CONSTANT:
141
+ case CstType.STRUCTURED:
142
+ case CstType.TERM: return TypeClass.typification;
143
+ case CstType.FUNCTION: return TypeClass.function;
144
+ case CstType.PREDICATE: return TypeClass.predicate;
145
+ case CstType.AXIOM:
146
+ case CstType.STATEMENT: return TypeClass.logic;
147
+ }
148
+ }
165
149
  /** Evaluate if {@link Constituenta} can be used produce structure. */
166
150
  function canProduceStructure(cst) {
167
151
  switch (cst.cst_type) {
@@ -180,19 +164,21 @@ function canProduceStructure(cst) {
180
164
  if (!isTypification(cst.effectiveType)) return false;
181
165
  return typeCanProduceStructure(cst.effectiveType);
182
166
  }
183
- /** Evaluate if {@link CstType} can have manual typification. */
184
- function canHaveManualTypification(type) {
185
- switch (type) {
186
- case CstType.STRUCTURED:
187
- case CstType.TERM:
188
- case CstType.FUNCTION:
189
- case CstType.PREDICATE: return true;
190
- case CstType.NOMINAL:
191
- case CstType.BASE:
192
- case CstType.CONSTANT:
193
- case CstType.AXIOM:
194
- case CstType.STATEMENT: return false;
195
- }
167
+ function typeCanProduceStructure(type) {
168
+ if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) return false;
169
+ else if (type.typeID === TypeID.tuple) return true;
170
+ else return type.base.typeID !== TypeID.basic && type.base.typeID !== TypeID.integer && type.base.typeID !== TypeID.anyTypification;
171
+ }
172
+ //#endregion
173
+ //#region src/library/rsform-api/alias.ts
174
+ /**
175
+ * Alias generation, validation, and remapping.
176
+ */
177
+ /** Build alias mapping from template argument bindings. */
178
+ function argumentValuesToMapping(args) {
179
+ const mapping = {};
180
+ for (const arg of args) if (arg.value) mapping[arg.alias] = arg.value;
181
+ return mapping;
196
182
  }
197
183
  /** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */
198
184
  function validateAliasFormat(alias, type) {
@@ -211,11 +197,10 @@ function validateNewAlias(alias, type, schema) {
211
197
  /** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */
212
198
  function generateAlias(type, schema, takenAliases = []) {
213
199
  const prefix = getCstTypePrefix(type);
214
- if (schema.items.length <= 0) return `${prefix}1`;
215
- let index = schema.items.reduce((prev, cst, index) => {
200
+ let index = schema.items.reduce((prev, cst) => {
216
201
  if (cst.cst_type !== type) return prev;
217
- index = Number(cst.alias.slice(1 - cst.alias.length)) + 1;
218
- return Math.max(prev, index);
202
+ const next = Number(cst.alias.substring(prefix.length)) + 1;
203
+ return Math.max(prev, next);
219
204
  }, 1);
220
205
  let alias = `${prefix}${index}`;
221
206
  while (takenAliases.includes(alias)) {
@@ -225,23 +210,6 @@ function generateAlias(type, schema, takenAliases = []) {
225
210
  return alias;
226
211
  }
227
212
  /**
228
- * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:
229
- * after the last existing child of that spawner, or after the spawner itself if none.
230
- */
231
- function inferNewSpawnPosition(schema, targetId) {
232
- let last = null;
233
- for (const cst of schema.items) if (cst.spawner === targetId) last = cst.id;
234
- return last ?? targetId;
235
- }
236
- /** Sorts library items relevant for InlineSynthesis with specified {@link RSForm}. */
237
- function sortItemsForInlineSynthesis(receiver, items) {
238
- const result = items.filter((item) => item.location === receiver.location);
239
- for (const item of items) if (item.visible && item.owner === item.owner && !result.includes(item)) result.push(item);
240
- for (const item of items) if (item.visible && !result.includes(item)) result.push(item);
241
- for (const item of items) if (!result.includes(item)) result.push(item);
242
- return result;
243
- }
244
- /**
245
213
  * Remap formal expressions and terminological entity references in constituent fields.
246
214
  * Mutates each element of `items` in place; pass owned or cloned data only.
247
215
  */
@@ -256,31 +224,15 @@ function applyMappingToConstituents(items, mapping, changeAliases) {
256
224
  }
257
225
  /** Remove alias from expression. */
258
226
  function removeAliasReference(expression, alias) {
259
- const result = expression.replaceAll(new RegExp(`\\b${alias}\\b`, "g"), "DEL");
260
- return result === "DEL" ? "" : result;
227
+ const escaped = alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
228
+ return expression.replaceAll(new RegExp(`\\b${escaped}\\b`, "g"), "").trim();
261
229
  }
262
230
  /** Add alias to expression. */
263
231
  function addAliasReference(expression, alias) {
264
232
  return expression + " " + alias;
265
233
  }
266
- /** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */
267
- function typeClassForCstType(cstType) {
268
- switch (cstType) {
269
- case CstType.NOMINAL:
270
- case CstType.BASE:
271
- case CstType.CONSTANT:
272
- case CstType.STRUCTURED:
273
- case CstType.TERM: return TypeClass.typification;
274
- case CstType.FUNCTION: return TypeClass.function;
275
- case CstType.PREDICATE: return TypeClass.predicate;
276
- case CstType.AXIOM:
277
- case CstType.STATEMENT: return TypeClass.logic;
278
- }
279
- }
280
- /** Checks whether a constituenta type supports formal definitions. */
281
- function canHaveFormalDefinition(cstType) {
282
- return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;
283
- }
234
+ //#endregion
235
+ //#region src/library/rsform-api/analysis.ts
284
236
  function getAnalysisFor(expression, cstType, schema, alias) {
285
237
  if (!canHaveFormalDefinition(cstType)) {
286
238
  if (expression.trim().length === 0) {
@@ -380,57 +332,305 @@ function resolveDependencyCycleText(schema, graph, currentId, missingId) {
380
332
  if (currentId === void 0) return (schema.cstByID.get(missingId)?.diagnostics.find((item) => item.code === RSDiagnosticCode.schemaDependencyCycle))?.params?.[0] ?? null;
381
333
  return null;
382
334
  }
383
- /** Calculate statistics for {@link RSForm}. */
384
- function calculateSchemaStats(target) {
385
- const items = target.items;
335
+ //#endregion
336
+ //#region src/library/rsform-api/expression.ts
337
+ /** Infers the status of an expression based on parsing and value information. */
338
+ function inferStatus(parse, value) {
339
+ if (!parse) return CstStatus.INCORRECT;
340
+ if (value === null) return CstStatus.INCALCULABLE;
341
+ if (value === ValueClass.PROPERTY) return CstStatus.PROPERTY;
342
+ return CstStatus.VERIFIED;
343
+ }
344
+ /** Infers type of constituent for a given template and arguments. */
345
+ function inferTemplatedType(templateType, args) {
346
+ if (args.length === 0 || args.some((arg) => !arg.value)) return templateType;
347
+ else if (templateType === CstType.PREDICATE) return CstType.AXIOM;
348
+ else return CstType.TERM;
349
+ }
350
+ /**
351
+ * Normalize a RSLang expression for duplicate comparison.
352
+ *
353
+ * Returns `null` for basic concepts without formal definitions. Pass a pre-parsed `ast`
354
+ * when the expression was already analyzed to avoid re-parsing.
355
+ */
356
+ function normalizeExpression(expression, cst_type, ast) {
357
+ if (isBasicConcept(cst_type) && cst_type !== CstType.AXIOM) return null;
358
+ const parsed = ast ?? parseRSLangExpression(expression);
359
+ let normalized = "";
360
+ if (parsed && !parsed.hasError) normalized = generateExpressionFromAst(parsed, { normalize: true });
361
+ else normalized = expression;
362
+ normalized = normalized.replace(/\s+/g, "");
363
+ return normalized === "" ? null : normalized;
364
+ }
365
+ /** Checks if given expression is a template. */
366
+ function inferTemplate(expression) {
367
+ const match = expression.match(/R\d+/g);
368
+ return (match && match?.length > 0) ?? false;
369
+ }
370
+ /** Apply filter based on start {@link Constituenta} type. */
371
+ function applyFilterCategory(start, items) {
372
+ const startIndex = items.indexOf(start);
373
+ if (startIndex === -1) return [];
374
+ const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);
375
+ return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));
376
+ }
377
+ //#endregion
378
+ //#region src/library/rsform-api/semantic-relations.ts
379
+ /**
380
+ * Infer semantic parent/children used for clustering during restore order.
381
+ * Port of backend {@code SemanticInfo}.
382
+ */
383
+ function computeSemanticRelations(items, graph) {
384
+ const byId = new Map(items.map((cst) => [cst.id, cst]));
385
+ const byAlias = new Map(items.map((cst) => [cst.alias, cst]));
386
+ const isTemplate = /* @__PURE__ */ new Map();
387
+ const isSimple = /* @__PURE__ */ new Map();
388
+ const parentOf = /* @__PURE__ */ new Map();
389
+ const childrenOf = /* @__PURE__ */ new Map();
390
+ for (const cst of items) {
391
+ parentOf.set(cst.id, cst.id);
392
+ childrenOf.set(cst.id, []);
393
+ }
394
+ function needCheckHead(sources, head) {
395
+ if (sources.size === 0) return true;
396
+ if (sources.size !== 1) return false;
397
+ const base = byId.get([...sources][0]);
398
+ return !isFunctional(base.cst_type) || splitTemplateDefinition(base.definition_formal).head !== head;
399
+ }
400
+ function extractSources(target) {
401
+ const sources = /* @__PURE__ */ new Set();
402
+ if (!isFunctional(target.cst_type)) {
403
+ for (const parentId of graph.at(target.id)?.inputs ?? []) if (!(isTemplate.get(parentId) && isSimple.get(parentId))) sources.add(parentOf.get(parentId) ?? parentId);
404
+ return sources;
405
+ }
406
+ const expression = splitTemplateDefinition(target.definition_formal);
407
+ for (const alias of extractGlobals(expression.body)) {
408
+ const parent = byAlias.get(alias);
409
+ if (!parent) continue;
410
+ if (!(isTemplate.get(parent.id) && isSimple.get(parent.id))) sources.add(parentOf.get(parent.id) ?? parent.id);
411
+ }
412
+ if (needCheckHead(sources, expression.head)) for (const alias of extractGlobals(expression.head)) {
413
+ const parent = byAlias.get(alias);
414
+ if (!parent) continue;
415
+ if (!isBaseSet(parent.cst_type) && !(isTemplate.get(parent.id) && isSimple.get(parent.id))) sources.add(parentOf.get(parent.id) ?? parent.id);
416
+ }
417
+ return sources;
418
+ }
419
+ function inferSimple(target) {
420
+ if (target.cst_type === CstType.STRUCTURED || isBaseSet(target.cst_type)) return false;
421
+ if ((graph.at(target.id)?.inputs ?? []).some((id) => isTemplate.get(id) && !isSimple.get(id))) return false;
422
+ return isSimpleExpression(isFunctional(target.cst_type) ? splitTemplateDefinition(target.definition_formal).body : target.definition_formal);
423
+ }
424
+ for (const cstId of graph.topologicalOrder()) {
425
+ const cst = byId.get(cstId);
426
+ if (!cst) continue;
427
+ isTemplate.set(cstId, inferTemplate(cst.definition_formal));
428
+ isSimple.set(cstId, inferSimple(cst));
429
+ if (!isSimple.get(cstId) || cst.cst_type === CstType.STRUCTURED) continue;
430
+ const sources = extractSources(cst);
431
+ if (sources.size !== 1) continue;
432
+ const parentId = [...sources][0];
433
+ const parent = byId.get(parentId);
434
+ if (!parent || isBaseSet(parent.cst_type)) continue;
435
+ parentOf.set(cstId, parentId);
436
+ childrenOf.get(parentId).push(cstId);
437
+ }
386
438
  return {
387
- count_all: items.length,
388
- count_crucial: items.reduce((sum, cst) => sum + (cst.crucial ? 1 : 0), 0),
389
- step_complexity: items.reduce((sum, cst) => sum + calculateStepComplexity(cst), 0),
390
- count_problematic: items.reduce((sum, cst) => sum + (isSchemaIssue(cst) ? 1 : 0), 0),
391
- count_homonyms: items.reduce((sum, cst) => sum + (hasCstDiagnostic(cst, RSDiagnosticCode.schemaHomonym) ? 1 : 0), 0),
392
- count_formal_duplicates: items.reduce((sum, cst) => sum + (hasCstDiagnostic(cst, RSDiagnosticCode.schemaFormalDuplicate) ? 1 : 0), 0),
393
- count_missing_convention: items.reduce((sum, cst) => sum + (isMissingConvention(cst) ? 1 : 0), 0),
394
- count_type_mismatch: items.reduce((sum, cst) => sum + (cst.is_type_mismatch ? 1 : 0), 0),
395
- count_incorrect: items.reduce((sum, cst) => sum + (cst.status === CstStatus.INCORRECT ? 1 : 0), 0),
396
- count_property: items.reduce((sum, cst) => sum + (cst.analysis?.valueClass === ValueClass.PROPERTY ? 1 : 0), 0),
397
- count_incalculable: items.reduce((sum, cst) => sum + (cst.analysis?.success && cst.analysis.valueClass === null ? 1 : 0), 0),
398
- count_inherited: items.reduce((sum, cst) => sum + (cst.is_inherited ? 1 : 0), 0),
399
- count_text_term: items.reduce((sum, cst) => sum + (cst.term_raw ? 1 : 0), 0),
400
- count_definition: items.reduce((sum, cst) => sum + (cst.definition_raw ? 1 : 0), 0),
401
- count_convention: items.reduce((sum, cst) => sum + (isBasicConcept(cst.cst_type) && cst.convention ? 1 : 0), 0),
402
- count_comment: items.reduce((sum, cst) => sum + (!isBasicConcept(cst.cst_type) && !cst.convention ? 1 : 0), 0),
403
- count_base: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.BASE ? 1 : 0), 0),
404
- count_constant: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.CONSTANT ? 1 : 0), 0),
405
- count_structured: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STRUCTURED ? 1 : 0), 0),
406
- count_axiom: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.AXIOM ? 1 : 0), 0),
407
- count_term: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.TERM ? 1 : 0), 0),
408
- count_function: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.FUNCTION ? 1 : 0), 0),
409
- count_predicate: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.PREDICATE ? 1 : 0), 0),
410
- count_statement: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STATEMENT ? 1 : 0), 0),
411
- count_nominal: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.NOMINAL ? 1 : 0), 0)
439
+ parentOf,
440
+ childrenOf
412
441
  };
413
442
  }
414
- /** Finds {@link Constituenta} by structure path. */
415
- function findCstByStructure(schema, target, path) {
416
- for (const cst of schema.items) {
417
- if (!cst.spawner_path) continue;
418
- const absolutePath = resolveAbsoluteSpawnerPath(schema, cst, target.id);
419
- if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) return cst;
443
+ //#endregion
444
+ //#region src/library/rsform-api/formal-graph.ts
445
+ /**
446
+ * Formal dependency graph and declaration-order restore for RSForm constituents.
447
+ */
448
+ /**
449
+ * Build the formal dependency graph: supplier → dependent.
450
+ * Matches backend {@code RSForm.graph_formal}.
451
+ */
452
+ function buildFormalDependencyGraph(items) {
453
+ const graph = new Graph();
454
+ const byAlias = new Map(items.map((cst) => [cst.alias, cst]));
455
+ for (const cst of items) graph.addNode(cst.id);
456
+ for (const cst of items) for (const alias of extractGlobals(cst.definition_formal)) {
457
+ const supplier = byAlias.get(alias);
458
+ if (supplier) graph.addEdge(supplier.id, cst.id);
420
459
  }
421
- return null;
460
+ return graph;
422
461
  }
423
- /** Retrieves name for piece of target {@link Constituenta} structure. */
424
- function getStructureName(schema, target, path) {
425
- const representation = findCstByStructure(schema, target, path);
426
- if (representation) return `${representation.alias}: ${representation.term_resolved}`;
427
- if (!isTypification(target.effectiveType)) return "";
428
- const type = applyPath(target.effectiveType, path);
429
- if (type?.typeID === TypeID.basic) {
430
- const cst = schema.cstByAlias.get(type.baseID);
431
- if (cst?.term_resolved) return `${cst.alias}: ${cst.term_resolved}`;
462
+ /**
463
+ * Reorder constituents: formal topology hard, semantic children sticky when ready,
464
+ * otherwise stable against type/kernel preferred ranks.
465
+ *
466
+ * One Kahn pass over the formal dependency graph.
467
+ */
468
+ function restoreConstituentOrder(items, graph = buildFormalDependencyGraph(items), relations = computeSemanticRelations(items, graph)) {
469
+ if (items.length <= 1) return [...items];
470
+ const byId = new Map(items.map((cst) => [cst.id, cst]));
471
+ const preferred = kernelPriority(items, graph, relations.parentOf);
472
+ const rank = new Map(preferred.map((cst, index) => [cst.id, index]));
473
+ const remainingInputs = /* @__PURE__ */ new Map();
474
+ for (const cst of preferred) {
475
+ const inputs = graph.at(cst.id)?.inputs ?? [];
476
+ remainingInputs.set(cst.id, inputs.reduce((count, src) => count + (rank.has(src) ? 1 : 0), 0));
432
477
  }
433
- return "";
478
+ const ready = /* @__PURE__ */ new Set();
479
+ for (const cst of preferred) if ((remainingInputs.get(cst.id) ?? 0) === 0) ready.add(cst.id);
480
+ const children = /* @__PURE__ */ new Map();
481
+ for (const cst of preferred) children.set(cst.id, (relations.childrenOf.get(cst.id) ?? []).filter((childId) => rank.has(childId)));
482
+ const result = [];
483
+ const pendingChildren = [];
484
+ function enqueueSticky(candidateIds) {
485
+ const sticky = candidateIds.filter((childId) => ready.has(childId) && !pendingChildren.includes(childId));
486
+ sticky.sort((left, right) => (rank.get(left) ?? 0) - (rank.get(right) ?? 0));
487
+ pendingChildren.push(...sticky);
488
+ }
489
+ function pickReady() {
490
+ while (pendingChildren.length > 0) {
491
+ const childId = pendingChildren.shift();
492
+ if (ready.has(childId)) return childId;
493
+ }
494
+ let best = -1;
495
+ let bestRank = Number.POSITIVE_INFINITY;
496
+ for (const nodeId of ready) {
497
+ const nodeRank = rank.get(nodeId) ?? Number.POSITIVE_INFINITY;
498
+ if (nodeRank < bestRank) {
499
+ best = nodeId;
500
+ bestRank = nodeRank;
501
+ }
502
+ }
503
+ return best;
504
+ }
505
+ while (ready.size > 0 || pendingChildren.length > 0) {
506
+ if (ready.size === 0) {
507
+ pendingChildren.length = 0;
508
+ continue;
509
+ }
510
+ const nodeId = pickReady();
511
+ ready.delete(nodeId);
512
+ result.push(byId.get(nodeId));
513
+ for (const dependentId of graph.at(nodeId)?.outputs ?? []) {
514
+ if (!remainingInputs.has(dependentId)) continue;
515
+ const next = (remainingInputs.get(dependentId) ?? 0) - 1;
516
+ remainingInputs.set(dependentId, next);
517
+ if (next === 0) ready.add(dependentId);
518
+ }
519
+ enqueueSticky(children.get(nodeId) ?? []);
520
+ }
521
+ if (result.length < preferred.length) {
522
+ const placed = new Set(result.map((cst) => cst.id));
523
+ for (const cst of preferred) if (!placed.has(cst.id)) result.push(cst);
524
+ }
525
+ return result;
526
+ }
527
+ function kernelPriority(items, graph, parentOf) {
528
+ const byId = new Map(items.map((cst) => [cst.id, cst]));
529
+ const seen = /* @__PURE__ */ new Set();
530
+ const result = [];
531
+ function push(cst) {
532
+ if (seen.has(cst.id)) return;
533
+ seen.add(cst.id);
534
+ result.push(cst);
535
+ }
536
+ for (const cst of items) if (cst.cst_type === CstType.BASE) push(cst);
537
+ for (const cst of items) if (cst.cst_type === CstType.CONSTANT) push(cst);
538
+ for (const cst of items) if ((graph.at(cst.id)?.inputs.length ?? 0) === 0) push(cst);
539
+ const kernelSeeds = items.filter((cst) => {
540
+ const parentId = parentOf.get(cst.id) ?? cst.id;
541
+ const parent = byId.get(parentId);
542
+ return cst.cst_type === CstType.STRUCTURED || cst.cst_type === CstType.AXIOM || parent?.cst_type === CstType.STRUCTURED;
543
+ }).map((cst) => cst.id);
544
+ const kernel = /* @__PURE__ */ new Set([...kernelSeeds, ...graph.expandAllInputs(kernelSeeds)]);
545
+ for (const cst of items) if (kernel.has(cst.id)) push(cst);
546
+ for (const cst of items) push(cst);
547
+ return result;
548
+ }
549
+ //#endregion
550
+ //#region src/library/rsform-api/stats.ts
551
+ /**
552
+ * Schema-level statistics and issue flags.
553
+ */
554
+ /** Checks if {@link Constituenta} is a schema issue. */
555
+ function isSchemaIssue(cst) {
556
+ return (cst.diagnostics?.length ?? 0) > 0 || cst.status === CstStatus.INCORRECT || cst.status === CstStatus.INCALCULABLE;
557
+ }
558
+ /** Calculate statistics for {@link RSForm}. */
559
+ function calculateSchemaStats(target) {
560
+ const stats = {
561
+ count_all: target.items.length,
562
+ count_crucial: 0,
563
+ step_complexity: 0,
564
+ count_problematic: 0,
565
+ count_homonyms: 0,
566
+ count_formal_duplicates: 0,
567
+ count_missing_basic_text: 0,
568
+ count_type_mismatch: 0,
569
+ count_incorrect: 0,
570
+ count_property: 0,
571
+ count_incalculable: 0,
572
+ count_inherited: 0,
573
+ count_text_term: 0,
574
+ count_definition: 0,
575
+ count_convention: 0,
576
+ count_comment: 0,
577
+ count_base: 0,
578
+ count_constant: 0,
579
+ count_structured: 0,
580
+ count_axiom: 0,
581
+ count_term: 0,
582
+ count_function: 0,
583
+ count_predicate: 0,
584
+ count_statement: 0,
585
+ count_nominal: 0
586
+ };
587
+ for (const cst of target.items) {
588
+ if (cst.crucial) stats.count_crucial += 1;
589
+ stats.step_complexity += calculateStepComplexity(cst);
590
+ if (isSchemaIssue(cst)) stats.count_problematic += 1;
591
+ if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaHomonym)) stats.count_homonyms += 1;
592
+ if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaFormalDuplicate)) stats.count_formal_duplicates += 1;
593
+ if (isMissingBasicText(cst)) stats.count_missing_basic_text += 1;
594
+ if (cst.is_type_mismatch) stats.count_type_mismatch += 1;
595
+ if (cst.status === CstStatus.INCORRECT) stats.count_incorrect += 1;
596
+ if (cst.analysis?.valueClass === ValueClass.PROPERTY) stats.count_property += 1;
597
+ if (cst.analysis?.success && cst.analysis.valueClass === null) stats.count_incalculable += 1;
598
+ if (cst.is_inherited) stats.count_inherited += 1;
599
+ if (cst.term_raw) stats.count_text_term += 1;
600
+ if (cst.definition_raw) stats.count_definition += 1;
601
+ if (isBasicConcept(cst.cst_type) && cst.convention) stats.count_convention += 1;
602
+ if (!isBasicConcept(cst.cst_type) && !cst.convention) stats.count_comment += 1;
603
+ switch (cst.cst_type) {
604
+ case CstType.BASE:
605
+ stats.count_base += 1;
606
+ break;
607
+ case CstType.CONSTANT:
608
+ stats.count_constant += 1;
609
+ break;
610
+ case CstType.STRUCTURED:
611
+ stats.count_structured += 1;
612
+ break;
613
+ case CstType.AXIOM:
614
+ stats.count_axiom += 1;
615
+ break;
616
+ case CstType.TERM:
617
+ stats.count_term += 1;
618
+ break;
619
+ case CstType.FUNCTION:
620
+ stats.count_function += 1;
621
+ break;
622
+ case CstType.PREDICATE:
623
+ stats.count_predicate += 1;
624
+ break;
625
+ case CstType.STATEMENT:
626
+ stats.count_statement += 1;
627
+ break;
628
+ case CstType.NOMINAL:
629
+ stats.count_nominal += 1;
630
+ break;
631
+ }
632
+ }
633
+ return stats;
434
634
  }
435
635
  function calculateStepComplexity(cst) {
436
636
  if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) return 0;
@@ -455,16 +655,50 @@ function calculateTypificationComplexity(type) {
455
655
  return 0;
456
656
  }
457
657
  }
458
- function isMissingConvention(cst) {
459
- if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {
460
- if (!cst.convention || !cst.term_resolved) return true;
658
+ /** Non-logical basic concept missing convention and/or resolved term (trimmed). */
659
+ function isMissingBasicText(cst) {
660
+ if (!isBasicConcept(cst.cst_type) || isLogical(cst.cst_type)) return false;
661
+ return !cst.convention.trim() || !cst.term_resolved.trim();
662
+ }
663
+ //#endregion
664
+ //#region src/library/rsform-api/structure.ts
665
+ /**
666
+ * Structure-path helpers for spawned constituents.
667
+ */
668
+ /**
669
+ * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:
670
+ * after the last existing child of that spawner, or after the spawner itself if none.
671
+ */
672
+ function inferNewSpawnPosition(schema, targetId) {
673
+ let last = null;
674
+ for (const cst of schema.items) if (cst.spawner === targetId) last = cst.id;
675
+ return last ?? targetId;
676
+ }
677
+ /** Finds {@link Constituenta} by structure path. */
678
+ function findCstByStructure(schema, target, path) {
679
+ const byId = schema.cstByID ?? new Map(schema.items.map((item) => [item.id, item]));
680
+ for (const cst of schema.items) {
681
+ if (!cst.spawner_path) continue;
682
+ const absolutePath = resolveAbsoluteSpawnerPath(cst, target.id, byId);
683
+ if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) return cst;
461
684
  }
462
- return false;
685
+ return null;
463
686
  }
464
- function resolveAbsoluteSpawnerPath(schema, cst, targetId) {
687
+ /** Retrieves name for piece of target {@link Constituenta} structure. */
688
+ function getStructureName(schema, target, path) {
689
+ const representation = findCstByStructure(schema, target, path);
690
+ if (representation) return `${representation.alias}: ${representation.term_resolved}`;
691
+ if (!isTypification(target.effectiveType)) return "";
692
+ const type = applyPath(target.effectiveType, path);
693
+ if (type?.typeID === TypeID.basic) {
694
+ const cst = schema.cstByAlias.get(type.baseID);
695
+ if (cst?.term_resolved) return `${cst.alias}: ${cst.term_resolved}`;
696
+ }
697
+ return "";
698
+ }
699
+ function resolveAbsoluteSpawnerPath(cst, targetId, byId) {
465
700
  if (!cst.spawner_path || cst.spawner == null) return null;
466
701
  if (cst.spawner === targetId) return cst.spawner_path;
467
- const byId = schema.cstByID ?? new Map(schema.items.map((item) => [item.id, item]));
468
702
  const visited = /* @__PURE__ */ new Set([cst.id]);
469
703
  let currentPath = [...cst.spawner_path];
470
704
  let currentSpawnerId = cst.spawner;
@@ -479,11 +713,15 @@ function resolveAbsoluteSpawnerPath(schema, cst, targetId) {
479
713
  }
480
714
  return null;
481
715
  }
482
- /** Evaluate if {@link Typification} can be used to produce structure. */
483
- function typeCanProduceStructure(type) {
484
- if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) return false;
485
- else if (type.typeID === TypeID.tuple) return true;
486
- else return type.base.typeID !== TypeID.basic && type.base.typeID !== TypeID.integer && type.base.typeID !== TypeID.anyTypification;
716
+ //#endregion
717
+ //#region src/library/rsform-api/synthesis.ts
718
+ /** Sorts library items relevant for InlineSynthesis with specified {@link RSForm}. */
719
+ function sortItemsForInlineSynthesis(receiver, items) {
720
+ const result = items.filter((item) => item.location === receiver.location);
721
+ for (const item of items) if (item.visible && item.owner === receiver.owner && !result.includes(item)) result.push(item);
722
+ for (const item of items) if (item.visible && !result.includes(item)) result.push(item);
723
+ for (const item of items) if (!result.includes(item)) result.push(item);
724
+ return result;
487
725
  }
488
726
  //#endregion
489
727
  //#region src/library/diagnostics.ts
@@ -653,6 +891,6 @@ function modelStatusToCode(status, cstType) {
653
891
  }
654
892
  }
655
893
  //#endregion
656
- export { isLogical as A, inferNewSpawnPosition as C, isBaseSet as D, inferTemplatedType as E, removeAliasReference as F, sortItemsForInlineSynthesis as I, typeClassForCstType as L, isTemplateCst as M, normalizeExpression as N, isBasicConcept as O, refineAnalysisForDependencyCycles as P, validateAliasFormat as R, inferClass as S, inferTemplate as T, generateAlias as _, formatDependencyCycle as a, getStructureName as b, addAliasReference as c, argumentValuesToMapping as d, calculateSchemaStats as f, findCstByStructure as g, canProduceStructure as h, detectDependencyCycleDiagnostics as i, isSchemaIssue as j, isFunctional as k, applyFilterCategory as l, canHaveManualTypification as m, RSDiagnosticCode as n, hasCstDiagnostic as o, canHaveFormalDefinition as p, assignSchemaDiagnostics as r, modelStatusCstDiagnostic as s, DiagnosticKind as t, applyMappingToConstituents as u, getAnalysisFor as v, inferStatus as w, guessCstType as x, getCstTypePrefix as y, validateNewAlias as z };
894
+ export { canProduceStructure as A, applyMappingToConstituents as C, validateAliasFormat as D, removeAliasReference as E, isBasicConcept as F, isFunctional as I, isLogical as L, guessCstType as M, inferClass as N, validateNewAlias as O, isBaseSet as P, isTemplateCst as R, addAliasReference as S, generateAlias as T, inferTemplate as _, formatDependencyCycle as a, getAnalysisFor as b, sortItemsForInlineSynthesis as c, inferNewSpawnPosition as d, calculateSchemaStats as f, inferStatus as g, applyFilterCategory as h, detectDependencyCycleDiagnostics as i, getCstTypePrefix as j, canHaveManualTypification as k, findCstByStructure as l, restoreConstituentOrder as m, RSDiagnosticCode as n, hasCstDiagnostic as o, isSchemaIssue as p, assignSchemaDiagnostics as r, modelStatusCstDiagnostic as s, DiagnosticKind as t, getStructureName as u, inferTemplatedType as v, argumentValuesToMapping as w, refineAnalysisForDependencyCycles as x, normalizeExpression as y, typeClassForCstType as z };
657
895
 
658
- //# sourceMappingURL=diagnostics-CY9sKggB.js.map
896
+ //# sourceMappingURL=diagnostics-B1OfMra1.js.map