@rsconcept/domain 2.1.2 → 2.3.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.
- package/dist/api-Bf0f_uiI.d.ts +57 -0
- package/dist/diagnostics-CljEzVBV.js +1245 -0
- package/dist/diagnostics-CljEzVBV.js.map +1 -0
- package/dist/{diagnostics-EaIt3zIw.d.ts → diagnostics-Dac5sJhO.d.ts} +4 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/library/diagnostics.d.ts +1 -1
- package/dist/library/diagnostics.js +1 -1
- package/dist/library/index.d.ts +2 -2
- package/dist/library/index.js +1 -1
- package/dist/library/oss-api.d.ts +1 -1
- package/dist/library/oss-api.js +4 -4
- package/dist/library/oss-api.js.map +1 -1
- package/dist/library/rsengine.d.ts +1 -1
- package/dist/library/rsengine.js +2 -2
- package/dist/library/rsform-api/index.d.ts +299 -0
- package/dist/library/rsform-api/index.js +2 -0
- package/dist/library/rsform.d.ts +2 -2
- package/dist/library/rsform.js.map +1 -1
- package/dist/library/rsmodel-api.d.ts +1 -1
- package/dist/library/rsmodel-api.js +4 -2
- package/dist/library/rsmodel-api.js.map +1 -1
- package/dist/library/rsmodel.d.ts +1 -1
- package/dist/library/structure-planner.d.ts +1 -1
- package/dist/library/structure-planner.js +2 -2
- package/dist/rslang/api.d.ts +2 -58
- package/dist/rslang/api.js +1 -1
- package/dist/rslang/index.js +1 -1
- package/dist/rslang/parser/syntax-errors/index.js +1 -1
- package/dist/rslang/semantic/analyzer.js +2 -2
- package/dist/{syntax-errors-DwPXhpVe.js → syntax-errors-BN_bqTaX.js} +2 -2
- package/dist/{syntax-errors-DwPXhpVe.js.map → syntax-errors-BN_bqTaX.js.map} +1 -1
- package/package.json +3 -3
- package/src/index.ts +1 -0
- package/src/library/index.ts +1 -0
- package/src/library/oss-api.ts +5 -2
- package/src/library/rsform-api/alias.ts +160 -0
- package/src/library/rsform-api/analysis.ts +157 -0
- package/src/library/rsform-api/attribution.ts +87 -0
- package/src/library/rsform-api/cst-type.ts +216 -0
- package/src/library/rsform-api/expression.ts +73 -0
- package/src/library/rsform-api/formal-graph.test.ts +72 -0
- package/src/library/rsform-api/formal-graph.ts +195 -0
- package/src/library/rsform-api/index.ts +53 -0
- package/src/library/rsform-api/semantic-relations.ts +117 -0
- package/src/library/rsform-api/stats.ts +170 -0
- package/src/library/rsform-api/structure.ts +93 -0
- package/src/library/rsform-api/substitution.ts +82 -0
- package/src/library/rsform-api/synthesis.test.ts +126 -0
- package/src/library/rsform-api/synthesis.ts +166 -0
- package/src/library/rsform-api/text-resolution.test.ts +86 -0
- package/src/library/rsform-api/text-resolution.ts +152 -0
- package/src/library/rsform-api/transforms.test.ts +161 -0
- package/src/library/rsform-api/transforms.ts +42 -0
- package/src/library/rsform-api/types.ts +38 -0
- package/src/library/rsform.ts +3 -3
- package/src/library/rsmodel-api.ts +7 -1
- package/dist/diagnostics-CY9sKggB.js +0 -658
- package/dist/diagnostics-CY9sKggB.js.map +0 -1
- package/dist/library/rsform-api.d.ts +0 -103
- package/dist/library/rsform-api.js +0 -2
- package/src/library/rsform-api.ts +0 -755
|
@@ -0,0 +1,1245 @@
|
|
|
1
|
+
import { Graph } from "./graph/graph.js";
|
|
2
|
+
import { TypeClass, TypeID, basic, bool, constant, isTypification } from "./rslang/semantic/typification.js";
|
|
3
|
+
import { labelType } from "./rslang/labels.js";
|
|
4
|
+
import { applyEntityReferenceMapping, extractEntities, parseGrammemes, resolveTextReferences } from "./cctext/language-api.js";
|
|
5
|
+
import { generateExpressionFromAst } from "./rslang/parser/expression-generator.js";
|
|
6
|
+
import { applyAliasMapping, applyTypificationMapping, extractGlobals, isSimpleExpression, parseRSLangExpression, splitTemplateDefinition } from "./rslang/api.js";
|
|
7
|
+
import { CstClass, CstStatus, CstType } from "./library/rsform.js";
|
|
8
|
+
import { RSErrorCode } from "./rslang/error.js";
|
|
9
|
+
import { applyPath } from "./rslang/semantic/typification-api.js";
|
|
10
|
+
import { ValueClass } from "./rslang/semantic/value-class.js";
|
|
11
|
+
import "./rslang/index.js";
|
|
12
|
+
import "./graph/index.js";
|
|
13
|
+
import { EvalStatus } from "./library/rsmodel.js";
|
|
14
|
+
//#region src/library/rsform-api/cst-type.ts
|
|
15
|
+
/**
|
|
16
|
+
* CstType classification, prefixes, and capability predicates.
|
|
17
|
+
*/
|
|
18
|
+
/** Record of {@link CstType} prefixes. */
|
|
19
|
+
const CST_TYPE_PREFIX = {
|
|
20
|
+
[CstType.NOMINAL]: "N",
|
|
21
|
+
[CstType.BASE]: "X",
|
|
22
|
+
[CstType.CONSTANT]: "C",
|
|
23
|
+
[CstType.STRUCTURED]: "S",
|
|
24
|
+
[CstType.AXIOM]: "A",
|
|
25
|
+
[CstType.TERM]: "D",
|
|
26
|
+
[CstType.FUNCTION]: "F",
|
|
27
|
+
[CstType.PREDICATE]: "P",
|
|
28
|
+
[CstType.STATEMENT]: "T"
|
|
29
|
+
};
|
|
30
|
+
/** Record of {@link CstType} to {@link CstClass} mapping. */
|
|
31
|
+
const CST_TYPE_TO_CLASS = {
|
|
32
|
+
[CstType.NOMINAL]: CstClass.NOMINAL,
|
|
33
|
+
[CstType.BASE]: CstClass.BASIC,
|
|
34
|
+
[CstType.CONSTANT]: CstClass.BASIC,
|
|
35
|
+
[CstType.STRUCTURED]: CstClass.BASIC,
|
|
36
|
+
[CstType.TERM]: CstClass.DERIVED,
|
|
37
|
+
[CstType.FUNCTION]: CstClass.DERIVED,
|
|
38
|
+
[CstType.AXIOM]: CstClass.STATEMENT,
|
|
39
|
+
[CstType.PREDICATE]: CstClass.DERIVED,
|
|
40
|
+
[CstType.STATEMENT]: CstClass.STATEMENT
|
|
41
|
+
};
|
|
42
|
+
/** Prefix for alias indicating {@link CstType}. */
|
|
43
|
+
function getCstTypePrefix(type) {
|
|
44
|
+
return CST_TYPE_PREFIX[type];
|
|
45
|
+
}
|
|
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;
|
|
51
|
+
}
|
|
52
|
+
/** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */
|
|
53
|
+
function inferClass(type, isTemplate = false) {
|
|
54
|
+
if (isTemplate) return CstClass.TEMPLATE;
|
|
55
|
+
return CST_TYPE_TO_CLASS[type];
|
|
56
|
+
}
|
|
57
|
+
/** Check if {@link Constituenta} is a template or a category. */
|
|
58
|
+
function isTemplateCst(cst) {
|
|
59
|
+
return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;
|
|
60
|
+
}
|
|
61
|
+
/** Evaluate if {@link CstType} is basic concept. */
|
|
62
|
+
function isBasicConcept(type) {
|
|
63
|
+
switch (type) {
|
|
64
|
+
case CstType.NOMINAL:
|
|
65
|
+
case CstType.BASE:
|
|
66
|
+
case CstType.CONSTANT:
|
|
67
|
+
case CstType.STRUCTURED:
|
|
68
|
+
case CstType.AXIOM: return true;
|
|
69
|
+
case CstType.TERM:
|
|
70
|
+
case CstType.FUNCTION:
|
|
71
|
+
case CstType.PREDICATE:
|
|
72
|
+
case CstType.STATEMENT: return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Evaluate if {@link CstType} is base set or constant set. */
|
|
76
|
+
function isBaseSet(type) {
|
|
77
|
+
switch (type) {
|
|
78
|
+
case CstType.BASE:
|
|
79
|
+
case CstType.CONSTANT: return true;
|
|
80
|
+
case CstType.NOMINAL:
|
|
81
|
+
case CstType.STRUCTURED:
|
|
82
|
+
case CstType.AXIOM:
|
|
83
|
+
case CstType.TERM:
|
|
84
|
+
case CstType.FUNCTION:
|
|
85
|
+
case CstType.PREDICATE:
|
|
86
|
+
case CstType.STATEMENT: return false;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** Evaluate if {@link CstType} is a function. */
|
|
90
|
+
function isFunctional(type) {
|
|
91
|
+
switch (type) {
|
|
92
|
+
case CstType.FUNCTION:
|
|
93
|
+
case CstType.PREDICATE: return true;
|
|
94
|
+
case CstType.NOMINAL:
|
|
95
|
+
case CstType.BASE:
|
|
96
|
+
case CstType.CONSTANT:
|
|
97
|
+
case CstType.STRUCTURED:
|
|
98
|
+
case CstType.AXIOM:
|
|
99
|
+
case CstType.TERM:
|
|
100
|
+
case CstType.STATEMENT: return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Evaluate if {@link CstType} is logical. */
|
|
104
|
+
function isLogical(type) {
|
|
105
|
+
switch (type) {
|
|
106
|
+
case CstType.AXIOM:
|
|
107
|
+
case CstType.STATEMENT: return true;
|
|
108
|
+
case CstType.NOMINAL:
|
|
109
|
+
case CstType.BASE:
|
|
110
|
+
case CstType.CONSTANT:
|
|
111
|
+
case CstType.STRUCTURED:
|
|
112
|
+
case CstType.TERM:
|
|
113
|
+
case CstType.FUNCTION:
|
|
114
|
+
case CstType.PREDICATE: return false;
|
|
115
|
+
}
|
|
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
|
+
}
|
|
149
|
+
/** Evaluate if {@link Constituenta} can be used produce structure. */
|
|
150
|
+
function canProduceStructure(cst) {
|
|
151
|
+
switch (cst.cst_type) {
|
|
152
|
+
case CstType.NOMINAL:
|
|
153
|
+
case CstType.BASE:
|
|
154
|
+
case CstType.CONSTANT:
|
|
155
|
+
case CstType.AXIOM:
|
|
156
|
+
case CstType.STATEMENT:
|
|
157
|
+
case CstType.PREDICATE: return false;
|
|
158
|
+
}
|
|
159
|
+
if (!cst.effectiveType) return false;
|
|
160
|
+
if (cst.cst_type === CstType.FUNCTION) {
|
|
161
|
+
const result = cst.effectiveType.result;
|
|
162
|
+
return typeCanProduceStructure(result);
|
|
163
|
+
}
|
|
164
|
+
if (!isTypification(cst.effectiveType)) return false;
|
|
165
|
+
return typeCanProduceStructure(cst.effectiveType);
|
|
166
|
+
}
|
|
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;
|
|
182
|
+
}
|
|
183
|
+
/** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */
|
|
184
|
+
function validateAliasFormat(alias, type) {
|
|
185
|
+
if (alias.length < 2) return false;
|
|
186
|
+
const prefix = getCstTypePrefix(type);
|
|
187
|
+
if (!alias.startsWith(prefix)) return false;
|
|
188
|
+
if (!/^\d+$/.exec(alias.substring(prefix.length))) return false;
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
/** Validate new alias against {@link CstType} and {@link RSForm}. */
|
|
192
|
+
function validateNewAlias(alias, type, schema) {
|
|
193
|
+
if (!validateAliasFormat(alias, type)) return false;
|
|
194
|
+
if (schema.cstByAlias.has(alias)) return false;
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
/** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */
|
|
198
|
+
function generateAlias(type, schema, takenAliases = []) {
|
|
199
|
+
const prefix = getCstTypePrefix(type);
|
|
200
|
+
let index = schema.items.reduce((prev, cst) => {
|
|
201
|
+
if (cst.cst_type !== type) return prev;
|
|
202
|
+
const next = Number(cst.alias.substring(prefix.length)) + 1;
|
|
203
|
+
return Math.max(prev, next);
|
|
204
|
+
}, 1);
|
|
205
|
+
let alias = `${prefix}${index}`;
|
|
206
|
+
while (takenAliases.includes(alias)) {
|
|
207
|
+
index = index + 1;
|
|
208
|
+
alias = `${prefix}${index}`;
|
|
209
|
+
}
|
|
210
|
+
return alias;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Remap formal expressions and terminological entity references in constituent fields.
|
|
214
|
+
* Mutates each element of `items` in place; pass owned or cloned data only.
|
|
215
|
+
*/
|
|
216
|
+
function applyMappingToConstituents(items, mapping, changeAliases) {
|
|
217
|
+
for (const cst of items) {
|
|
218
|
+
if (changeAliases && cst.alias in mapping) cst.alias = mapping[cst.alias];
|
|
219
|
+
cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);
|
|
220
|
+
cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);
|
|
221
|
+
cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);
|
|
222
|
+
cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** Highest numeric alias suffix for {@link type} among {@link items} (0 when none). */
|
|
226
|
+
function maxAliasIndex(items, type) {
|
|
227
|
+
const prefix = getCstTypePrefix(type);
|
|
228
|
+
return items.reduce((max, cst) => {
|
|
229
|
+
if (cst.cst_type !== type) return max;
|
|
230
|
+
const index = Number(cst.alias.slice(prefix.length));
|
|
231
|
+
return Number.isFinite(index) ? Math.max(max, index) : max;
|
|
232
|
+
}, 0);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Build alias → new-alias mapping that renumbers each type sequentially in list order.
|
|
236
|
+
* Matches backend {@code RSFormCached.reset_aliases}.
|
|
237
|
+
*/
|
|
238
|
+
function buildSequentialAliasMapping(items) {
|
|
239
|
+
const counts = {};
|
|
240
|
+
for (const value of Object.values(CstType)) counts[value] = 1;
|
|
241
|
+
const mapping = {};
|
|
242
|
+
for (const cst of items) {
|
|
243
|
+
const alias = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;
|
|
244
|
+
counts[cst.cst_type] += 1;
|
|
245
|
+
if (cst.alias !== alias) mapping[cst.alias] = alias;
|
|
246
|
+
}
|
|
247
|
+
return mapping;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Allocate fresh aliases for {@link source} constituents being imported into a non-empty receiver.
|
|
251
|
+
* Returns an empty mapping when the receiver has no items (aliases kept as-is).
|
|
252
|
+
*/
|
|
253
|
+
function allocateImportAliases(receiver, source) {
|
|
254
|
+
if (receiver.length === 0) return {};
|
|
255
|
+
const counts = {};
|
|
256
|
+
for (const value of Object.values(CstType)) counts[value] = maxAliasIndex(receiver, value);
|
|
257
|
+
const mapping = {};
|
|
258
|
+
for (const cst of source) {
|
|
259
|
+
counts[cst.cst_type] += 1;
|
|
260
|
+
mapping[cst.alias] = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;
|
|
261
|
+
}
|
|
262
|
+
return mapping;
|
|
263
|
+
}
|
|
264
|
+
/** Remove alias from expression. */
|
|
265
|
+
function removeAliasReference(expression, alias) {
|
|
266
|
+
const escaped = alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
267
|
+
return expression.replaceAll(new RegExp(`\\b${escaped}\\b`, "g"), "").trim();
|
|
268
|
+
}
|
|
269
|
+
/** Add alias to expression. */
|
|
270
|
+
function addAliasReference(expression, alias) {
|
|
271
|
+
return expression + " " + alias;
|
|
272
|
+
}
|
|
273
|
+
//#endregion
|
|
274
|
+
//#region src/library/rsform-api/analysis.ts
|
|
275
|
+
function getAnalysisFor(expression, cstType, schema, alias) {
|
|
276
|
+
if (!canHaveFormalDefinition(cstType)) {
|
|
277
|
+
if (expression.trim().length === 0) {
|
|
278
|
+
const fallbackAlias = alias && alias.length > 0 ? alias : "X0";
|
|
279
|
+
return {
|
|
280
|
+
success: true,
|
|
281
|
+
type: cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias)),
|
|
282
|
+
valueClass: ValueClass.VALUE,
|
|
283
|
+
errors: [],
|
|
284
|
+
ast: null
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
return {
|
|
288
|
+
success: false,
|
|
289
|
+
type: null,
|
|
290
|
+
valueClass: null,
|
|
291
|
+
errors: [{
|
|
292
|
+
code: RSErrorCode.definitionNotAllowed,
|
|
293
|
+
from: 0,
|
|
294
|
+
to: Math.max(expression.length, 1),
|
|
295
|
+
params: [cstType, alias ?? ""]
|
|
296
|
+
}],
|
|
297
|
+
ast: null
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
return refineAnalysisForDependencyCycles(schema.analyzer.checkFull(expression, {
|
|
301
|
+
expected: typeClassForCstType(cstType),
|
|
302
|
+
isDomain: cstType === CstType.STRUCTURED
|
|
303
|
+
}), expression, schema, alias);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* When an untyped / bare F·P reference names a constituent on a definition cycle with the
|
|
307
|
+
* current expression, replace that error with {@link RSDiagnosticCode.schemaDependencyCycle}.
|
|
308
|
+
*
|
|
309
|
+
* Covers both semantic `globalNotTyped` (e.g. `F3[σ]`) and parser `globalFuncWithoutArgs`
|
|
310
|
+
* (bare `P1` / `F1` treated as a call without arguments).
|
|
311
|
+
*
|
|
312
|
+
* Uses a draft dependency graph: incoming edges of the edited constituent are taken from
|
|
313
|
+
* `expression`, so Check works before Save.
|
|
314
|
+
*/
|
|
315
|
+
function refineAnalysisForDependencyCycles(analysis, expression, schema, alias) {
|
|
316
|
+
if (analysis.errors.length === 0 || !schema.graph) return analysis;
|
|
317
|
+
const currentId = alias ? schema.cstByAlias.get(alias)?.id : void 0;
|
|
318
|
+
const expressionGlobals = extractGlobals(expression);
|
|
319
|
+
const draftGraph = currentId !== void 0 ? buildDraftDependencyGraph(schema, currentId, expressionGlobals) : schema.graph;
|
|
320
|
+
let changed = false;
|
|
321
|
+
const errors = analysis.errors.map((error) => {
|
|
322
|
+
if (error.code !== RSErrorCode.globalNotTyped && error.code !== RSErrorCode.globalFuncWithoutArgs) return error;
|
|
323
|
+
const missingAlias = error.params?.[0];
|
|
324
|
+
if (!missingAlias) return error;
|
|
325
|
+
const missing = schema.cstByAlias.get(missingAlias);
|
|
326
|
+
if (!missing) return error;
|
|
327
|
+
const cycleText = resolveDependencyCycleText(schema, draftGraph, currentId, missing.id);
|
|
328
|
+
if (!cycleText) return error;
|
|
329
|
+
changed = true;
|
|
330
|
+
return {
|
|
331
|
+
...error,
|
|
332
|
+
code: RSErrorCode.schemaDependencyCycle,
|
|
333
|
+
params: [cycleText]
|
|
334
|
+
};
|
|
335
|
+
});
|
|
336
|
+
return changed ? {
|
|
337
|
+
...analysis,
|
|
338
|
+
errors
|
|
339
|
+
} : analysis;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Clone the schema graph and replace dependencies of `currentId` with globals from the
|
|
343
|
+
* expression under check (unsaved draft).
|
|
344
|
+
*/
|
|
345
|
+
function buildDraftDependencyGraph(schema, currentId, expressionGlobals) {
|
|
346
|
+
const graph = schema.graph.clone();
|
|
347
|
+
const node = graph.at(currentId);
|
|
348
|
+
if (node) for (const parentId of [...node.inputs]) graph.removeEdge(parentId, currentId);
|
|
349
|
+
else graph.addNode(currentId);
|
|
350
|
+
for (const globalAlias of expressionGlobals) {
|
|
351
|
+
const source = schema.cstByAlias.get(globalAlias);
|
|
352
|
+
if (source) graph.addEdge(source.id, currentId);
|
|
353
|
+
}
|
|
354
|
+
return graph;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Resolve formatted cycle text for an untyped global reference in analysis.
|
|
358
|
+
*
|
|
359
|
+
* Uses `graph` (often a draft graph built from the expression under check). When
|
|
360
|
+
* `currentId` is omitted, falls back to schema diagnostics on `missingId`.
|
|
361
|
+
*
|
|
362
|
+
* @returns Closed alias path such as `F3 → P1 → F3`, or `null` when no shared cycle exists.
|
|
363
|
+
*/
|
|
364
|
+
function resolveDependencyCycleText(schema, graph, currentId, missingId) {
|
|
365
|
+
for (const cycle of graph.findCycles()) {
|
|
366
|
+
const members = new Set(cycle);
|
|
367
|
+
if (!members.has(missingId)) continue;
|
|
368
|
+
if (currentId !== void 0 && !members.has(currentId)) continue;
|
|
369
|
+
return formatDependencyCycle(cycle.map((id) => schema.cstByID.get(id)?.alias ?? String(id)));
|
|
370
|
+
}
|
|
371
|
+
if (currentId === void 0) return (schema.cstByID.get(missingId)?.diagnostics.find((item) => item.code === RSDiagnosticCode.schemaDependencyCycle))?.params?.[0] ?? null;
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/library/rsform-api/attribution.ts
|
|
376
|
+
function attributionKey(attr) {
|
|
377
|
+
return `${attr.container}:${attr.attribute}`;
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Remap attributions when constituents are substituted (original → replacement).
|
|
381
|
+
* Drops self-loops and duplicates. Matches sandbox / backend substitute attribution rewrite.
|
|
382
|
+
*/
|
|
383
|
+
function remapAttributionsUnderSubstitution(attributions, origToSub) {
|
|
384
|
+
const result = [];
|
|
385
|
+
const seen = /* @__PURE__ */ new Set();
|
|
386
|
+
for (const attr of attributions) {
|
|
387
|
+
if (!origToSub.has(attr.container) && !origToSub.has(attr.attribute)) {
|
|
388
|
+
const key = attributionKey(attr);
|
|
389
|
+
if (!seen.has(key)) {
|
|
390
|
+
seen.add(key);
|
|
391
|
+
result.push({ ...attr });
|
|
392
|
+
}
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
const container = origToSub.get(attr.container) ?? attr.container;
|
|
396
|
+
const attribute = origToSub.get(attr.attribute) ?? attr.attribute;
|
|
397
|
+
if (container === attribute) continue;
|
|
398
|
+
const key = `${container}:${attribute}`;
|
|
399
|
+
if (seen.has(key)) continue;
|
|
400
|
+
seen.add(key);
|
|
401
|
+
result.push({
|
|
402
|
+
container,
|
|
403
|
+
attribute
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
return result;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Copy attributions whose both endpoints are in {@link sourceIdSet}, remapping ids via {@link idMap}.
|
|
410
|
+
* Appends onto a clone of {@link existing} with dedupe. Used by schema embedding / insert.
|
|
411
|
+
*/
|
|
412
|
+
function importAttributions(sourceAttributions, sourceIdSet, idMap, existing = []) {
|
|
413
|
+
const result = existing.map((attr) => ({ ...attr }));
|
|
414
|
+
const seen = new Set(result.map(attributionKey));
|
|
415
|
+
for (const attr of sourceAttributions) {
|
|
416
|
+
if (!sourceIdSet.has(attr.container) || !sourceIdSet.has(attr.attribute)) continue;
|
|
417
|
+
const container = idMap[attr.container];
|
|
418
|
+
const attribute = idMap[attr.attribute];
|
|
419
|
+
if (container === void 0 || attribute === void 0 || container === attribute) continue;
|
|
420
|
+
const key = `${container}:${attribute}`;
|
|
421
|
+
if (seen.has(key)) continue;
|
|
422
|
+
seen.add(key);
|
|
423
|
+
result.push({
|
|
424
|
+
container,
|
|
425
|
+
attribute
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
return result;
|
|
429
|
+
}
|
|
430
|
+
/** Drop attributions that reference any id in {@link deletedIds}. */
|
|
431
|
+
function filterAttributions(attributions, deletedIds) {
|
|
432
|
+
return attributions.filter((attr) => !deletedIds.has(attr.container) && !deletedIds.has(attr.attribute));
|
|
433
|
+
}
|
|
434
|
+
//#endregion
|
|
435
|
+
//#region src/library/rsform-api/expression.ts
|
|
436
|
+
/** Infers the status of an expression based on parsing and value information. */
|
|
437
|
+
function inferStatus(parse, value) {
|
|
438
|
+
if (!parse) return CstStatus.INCORRECT;
|
|
439
|
+
if (value === null) return CstStatus.INCALCULABLE;
|
|
440
|
+
if (value === ValueClass.PROPERTY) return CstStatus.PROPERTY;
|
|
441
|
+
return CstStatus.VERIFIED;
|
|
442
|
+
}
|
|
443
|
+
/** Infers type of constituent for a given template and arguments. */
|
|
444
|
+
function inferTemplatedType(templateType, args) {
|
|
445
|
+
if (args.length === 0 || args.some((arg) => !arg.value)) return templateType;
|
|
446
|
+
else if (templateType === CstType.PREDICATE) return CstType.AXIOM;
|
|
447
|
+
else return CstType.TERM;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Normalize a RSLang expression for duplicate comparison.
|
|
451
|
+
*
|
|
452
|
+
* Returns `null` for basic concepts without formal definitions. Pass a pre-parsed `ast`
|
|
453
|
+
* when the expression was already analyzed to avoid re-parsing.
|
|
454
|
+
*/
|
|
455
|
+
function normalizeExpression(expression, cst_type, ast) {
|
|
456
|
+
if (isBasicConcept(cst_type) && cst_type !== CstType.AXIOM) return null;
|
|
457
|
+
const parsed = ast ?? parseRSLangExpression(expression);
|
|
458
|
+
let normalized = "";
|
|
459
|
+
if (parsed && !parsed.hasError) normalized = generateExpressionFromAst(parsed, { normalize: true });
|
|
460
|
+
else normalized = expression;
|
|
461
|
+
normalized = normalized.replace(/\s+/g, "");
|
|
462
|
+
return normalized === "" ? null : normalized;
|
|
463
|
+
}
|
|
464
|
+
/** Checks if given expression is a template. */
|
|
465
|
+
function inferTemplate(expression) {
|
|
466
|
+
const match = expression.match(/R\d+/g);
|
|
467
|
+
return (match && match?.length > 0) ?? false;
|
|
468
|
+
}
|
|
469
|
+
/** Apply filter based on start {@link Constituenta} type. */
|
|
470
|
+
function applyFilterCategory(start, items) {
|
|
471
|
+
const startIndex = items.indexOf(start);
|
|
472
|
+
if (startIndex === -1) return [];
|
|
473
|
+
const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);
|
|
474
|
+
return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));
|
|
475
|
+
}
|
|
476
|
+
//#endregion
|
|
477
|
+
//#region src/library/rsform-api/semantic-relations.ts
|
|
478
|
+
/**
|
|
479
|
+
* Infer semantic parent/children used for clustering during restore order.
|
|
480
|
+
* Port of backend {@code SemanticInfo}.
|
|
481
|
+
*/
|
|
482
|
+
function computeSemanticRelations(items, graph) {
|
|
483
|
+
const byId = new Map(items.map((cst) => [cst.id, cst]));
|
|
484
|
+
const byAlias = new Map(items.map((cst) => [cst.alias, cst]));
|
|
485
|
+
const isTemplate = /* @__PURE__ */ new Map();
|
|
486
|
+
const isSimple = /* @__PURE__ */ new Map();
|
|
487
|
+
const parentOf = /* @__PURE__ */ new Map();
|
|
488
|
+
const childrenOf = /* @__PURE__ */ new Map();
|
|
489
|
+
for (const cst of items) {
|
|
490
|
+
parentOf.set(cst.id, cst.id);
|
|
491
|
+
childrenOf.set(cst.id, []);
|
|
492
|
+
}
|
|
493
|
+
function needCheckHead(sources, head) {
|
|
494
|
+
if (sources.size === 0) return true;
|
|
495
|
+
if (sources.size !== 1) return false;
|
|
496
|
+
const base = byId.get([...sources][0]);
|
|
497
|
+
return !isFunctional(base.cst_type) || splitTemplateDefinition(base.definition_formal).head !== head;
|
|
498
|
+
}
|
|
499
|
+
function extractSources(target) {
|
|
500
|
+
const sources = /* @__PURE__ */ new Set();
|
|
501
|
+
if (!isFunctional(target.cst_type)) {
|
|
502
|
+
for (const parentId of graph.at(target.id)?.inputs ?? []) if (!(isTemplate.get(parentId) && isSimple.get(parentId))) sources.add(parentOf.get(parentId) ?? parentId);
|
|
503
|
+
return sources;
|
|
504
|
+
}
|
|
505
|
+
const expression = splitTemplateDefinition(target.definition_formal);
|
|
506
|
+
for (const alias of extractGlobals(expression.body)) {
|
|
507
|
+
const parent = byAlias.get(alias);
|
|
508
|
+
if (!parent) continue;
|
|
509
|
+
if (!(isTemplate.get(parent.id) && isSimple.get(parent.id))) sources.add(parentOf.get(parent.id) ?? parent.id);
|
|
510
|
+
}
|
|
511
|
+
if (needCheckHead(sources, expression.head)) for (const alias of extractGlobals(expression.head)) {
|
|
512
|
+
const parent = byAlias.get(alias);
|
|
513
|
+
if (!parent) continue;
|
|
514
|
+
if (!isBaseSet(parent.cst_type) && !(isTemplate.get(parent.id) && isSimple.get(parent.id))) sources.add(parentOf.get(parent.id) ?? parent.id);
|
|
515
|
+
}
|
|
516
|
+
return sources;
|
|
517
|
+
}
|
|
518
|
+
function inferSimple(target) {
|
|
519
|
+
if (target.cst_type === CstType.STRUCTURED || isBaseSet(target.cst_type)) return false;
|
|
520
|
+
if ((graph.at(target.id)?.inputs ?? []).some((id) => isTemplate.get(id) && !isSimple.get(id))) return false;
|
|
521
|
+
return isSimpleExpression(isFunctional(target.cst_type) ? splitTemplateDefinition(target.definition_formal).body : target.definition_formal);
|
|
522
|
+
}
|
|
523
|
+
for (const cstId of graph.topologicalOrder()) {
|
|
524
|
+
const cst = byId.get(cstId);
|
|
525
|
+
if (!cst) continue;
|
|
526
|
+
isTemplate.set(cstId, inferTemplate(cst.definition_formal));
|
|
527
|
+
isSimple.set(cstId, inferSimple(cst));
|
|
528
|
+
if (!isSimple.get(cstId) || cst.cst_type === CstType.STRUCTURED) continue;
|
|
529
|
+
const sources = extractSources(cst);
|
|
530
|
+
if (sources.size !== 1) continue;
|
|
531
|
+
const parentId = [...sources][0];
|
|
532
|
+
const parent = byId.get(parentId);
|
|
533
|
+
if (!parent || isBaseSet(parent.cst_type)) continue;
|
|
534
|
+
parentOf.set(cstId, parentId);
|
|
535
|
+
childrenOf.get(parentId).push(cstId);
|
|
536
|
+
}
|
|
537
|
+
return {
|
|
538
|
+
parentOf,
|
|
539
|
+
childrenOf
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
//#endregion
|
|
543
|
+
//#region src/library/rsform-api/formal-graph.ts
|
|
544
|
+
/**
|
|
545
|
+
* Formal dependency graph and declaration-order restore for RSForm constituents.
|
|
546
|
+
*/
|
|
547
|
+
/**
|
|
548
|
+
* Build the formal dependency graph: supplier → dependent.
|
|
549
|
+
* Matches backend {@code RSForm.graph_formal}.
|
|
550
|
+
*/
|
|
551
|
+
function buildFormalDependencyGraph(items) {
|
|
552
|
+
const graph = new Graph();
|
|
553
|
+
const byAlias = new Map(items.map((cst) => [cst.alias, cst]));
|
|
554
|
+
for (const cst of items) graph.addNode(cst.id);
|
|
555
|
+
for (const cst of items) for (const alias of extractGlobals(cst.definition_formal)) {
|
|
556
|
+
const supplier = byAlias.get(alias);
|
|
557
|
+
if (supplier) graph.addEdge(supplier.id, cst.id);
|
|
558
|
+
}
|
|
559
|
+
return graph;
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Reorder constituents: formal topology hard, semantic children sticky when ready,
|
|
563
|
+
* otherwise stable against type/kernel preferred ranks.
|
|
564
|
+
*
|
|
565
|
+
* One Kahn pass over the formal dependency graph.
|
|
566
|
+
*/
|
|
567
|
+
function restoreConstituentOrder(items, graph = buildFormalDependencyGraph(items), relations = computeSemanticRelations(items, graph)) {
|
|
568
|
+
if (items.length <= 1) return [...items];
|
|
569
|
+
const byId = new Map(items.map((cst) => [cst.id, cst]));
|
|
570
|
+
const preferred = kernelPriority(items, graph, relations.parentOf);
|
|
571
|
+
const rank = new Map(preferred.map((cst, index) => [cst.id, index]));
|
|
572
|
+
const remainingInputs = /* @__PURE__ */ new Map();
|
|
573
|
+
for (const cst of preferred) {
|
|
574
|
+
const inputs = graph.at(cst.id)?.inputs ?? [];
|
|
575
|
+
remainingInputs.set(cst.id, inputs.reduce((count, src) => count + (rank.has(src) ? 1 : 0), 0));
|
|
576
|
+
}
|
|
577
|
+
const ready = /* @__PURE__ */ new Set();
|
|
578
|
+
for (const cst of preferred) if ((remainingInputs.get(cst.id) ?? 0) === 0) ready.add(cst.id);
|
|
579
|
+
const children = /* @__PURE__ */ new Map();
|
|
580
|
+
for (const cst of preferred) children.set(cst.id, (relations.childrenOf.get(cst.id) ?? []).filter((childId) => rank.has(childId)));
|
|
581
|
+
const result = [];
|
|
582
|
+
const pendingChildren = [];
|
|
583
|
+
function enqueueSticky(candidateIds) {
|
|
584
|
+
const sticky = candidateIds.filter((childId) => ready.has(childId) && !pendingChildren.includes(childId));
|
|
585
|
+
sticky.sort((left, right) => (rank.get(left) ?? 0) - (rank.get(right) ?? 0));
|
|
586
|
+
pendingChildren.push(...sticky);
|
|
587
|
+
}
|
|
588
|
+
function pickReady() {
|
|
589
|
+
while (pendingChildren.length > 0) {
|
|
590
|
+
const childId = pendingChildren.shift();
|
|
591
|
+
if (ready.has(childId)) return childId;
|
|
592
|
+
}
|
|
593
|
+
let best = -1;
|
|
594
|
+
let bestRank = Number.POSITIVE_INFINITY;
|
|
595
|
+
for (const nodeId of ready) {
|
|
596
|
+
const nodeRank = rank.get(nodeId) ?? Number.POSITIVE_INFINITY;
|
|
597
|
+
if (nodeRank < bestRank) {
|
|
598
|
+
best = nodeId;
|
|
599
|
+
bestRank = nodeRank;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
return best;
|
|
603
|
+
}
|
|
604
|
+
while (ready.size > 0 || pendingChildren.length > 0) {
|
|
605
|
+
if (ready.size === 0) {
|
|
606
|
+
pendingChildren.length = 0;
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
const nodeId = pickReady();
|
|
610
|
+
ready.delete(nodeId);
|
|
611
|
+
result.push(byId.get(nodeId));
|
|
612
|
+
for (const dependentId of graph.at(nodeId)?.outputs ?? []) {
|
|
613
|
+
if (!remainingInputs.has(dependentId)) continue;
|
|
614
|
+
const next = (remainingInputs.get(dependentId) ?? 0) - 1;
|
|
615
|
+
remainingInputs.set(dependentId, next);
|
|
616
|
+
if (next === 0) ready.add(dependentId);
|
|
617
|
+
}
|
|
618
|
+
enqueueSticky(children.get(nodeId) ?? []);
|
|
619
|
+
}
|
|
620
|
+
if (result.length < preferred.length) {
|
|
621
|
+
const placed = new Set(result.map((cst) => cst.id));
|
|
622
|
+
for (const cst of preferred) if (!placed.has(cst.id)) result.push(cst);
|
|
623
|
+
}
|
|
624
|
+
return result;
|
|
625
|
+
}
|
|
626
|
+
function kernelPriority(items, graph, parentOf) {
|
|
627
|
+
const byId = new Map(items.map((cst) => [cst.id, cst]));
|
|
628
|
+
const seen = /* @__PURE__ */ new Set();
|
|
629
|
+
const result = [];
|
|
630
|
+
function push(cst) {
|
|
631
|
+
if (seen.has(cst.id)) return;
|
|
632
|
+
seen.add(cst.id);
|
|
633
|
+
result.push(cst);
|
|
634
|
+
}
|
|
635
|
+
for (const cst of items) if (cst.cst_type === CstType.BASE) push(cst);
|
|
636
|
+
for (const cst of items) if (cst.cst_type === CstType.CONSTANT) push(cst);
|
|
637
|
+
for (const cst of items) if ((graph.at(cst.id)?.inputs.length ?? 0) === 0) push(cst);
|
|
638
|
+
const kernelSeeds = items.filter((cst) => {
|
|
639
|
+
const parentId = parentOf.get(cst.id) ?? cst.id;
|
|
640
|
+
const parent = byId.get(parentId);
|
|
641
|
+
return cst.cst_type === CstType.STRUCTURED || cst.cst_type === CstType.AXIOM || parent?.cst_type === CstType.STRUCTURED;
|
|
642
|
+
}).map((cst) => cst.id);
|
|
643
|
+
const kernel = /* @__PURE__ */ new Set([...kernelSeeds, ...graph.expandAllInputs(kernelSeeds)]);
|
|
644
|
+
for (const cst of items) if (kernel.has(cst.id)) push(cst);
|
|
645
|
+
for (const cst of items) push(cst);
|
|
646
|
+
return result;
|
|
647
|
+
}
|
|
648
|
+
//#endregion
|
|
649
|
+
//#region src/library/rsform-api/stats.ts
|
|
650
|
+
/**
|
|
651
|
+
* Schema-level statistics and issue flags.
|
|
652
|
+
*/
|
|
653
|
+
/** Checks if {@link Constituenta} is a schema issue. */
|
|
654
|
+
function isSchemaIssue(cst) {
|
|
655
|
+
return (cst.diagnostics?.length ?? 0) > 0 || cst.status === CstStatus.INCORRECT || cst.status === CstStatus.INCALCULABLE;
|
|
656
|
+
}
|
|
657
|
+
/** Calculate statistics for {@link RSForm}. */
|
|
658
|
+
function calculateSchemaStats(target) {
|
|
659
|
+
const stats = {
|
|
660
|
+
count_all: target.items.length,
|
|
661
|
+
count_crucial: 0,
|
|
662
|
+
step_complexity: 0,
|
|
663
|
+
count_problematic: 0,
|
|
664
|
+
count_homonyms: 0,
|
|
665
|
+
count_formal_duplicates: 0,
|
|
666
|
+
count_missing_basic_text: 0,
|
|
667
|
+
count_type_mismatch: 0,
|
|
668
|
+
count_incorrect: 0,
|
|
669
|
+
count_property: 0,
|
|
670
|
+
count_incalculable: 0,
|
|
671
|
+
count_inherited: 0,
|
|
672
|
+
count_text_term: 0,
|
|
673
|
+
count_definition: 0,
|
|
674
|
+
count_convention: 0,
|
|
675
|
+
count_comment: 0,
|
|
676
|
+
count_base: 0,
|
|
677
|
+
count_constant: 0,
|
|
678
|
+
count_structured: 0,
|
|
679
|
+
count_axiom: 0,
|
|
680
|
+
count_term: 0,
|
|
681
|
+
count_function: 0,
|
|
682
|
+
count_predicate: 0,
|
|
683
|
+
count_statement: 0,
|
|
684
|
+
count_nominal: 0
|
|
685
|
+
};
|
|
686
|
+
for (const cst of target.items) {
|
|
687
|
+
if (cst.crucial) stats.count_crucial += 1;
|
|
688
|
+
stats.step_complexity += calculateStepComplexity(cst);
|
|
689
|
+
if (isSchemaIssue(cst)) stats.count_problematic += 1;
|
|
690
|
+
if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaHomonym)) stats.count_homonyms += 1;
|
|
691
|
+
if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaFormalDuplicate)) stats.count_formal_duplicates += 1;
|
|
692
|
+
if (isMissingBasicText(cst)) stats.count_missing_basic_text += 1;
|
|
693
|
+
if (cst.is_type_mismatch) stats.count_type_mismatch += 1;
|
|
694
|
+
if (cst.status === CstStatus.INCORRECT) stats.count_incorrect += 1;
|
|
695
|
+
if (cst.analysis?.valueClass === ValueClass.PROPERTY) stats.count_property += 1;
|
|
696
|
+
if (cst.analysis?.success && cst.analysis.valueClass === null) stats.count_incalculable += 1;
|
|
697
|
+
if (cst.is_inherited) stats.count_inherited += 1;
|
|
698
|
+
if (cst.term_raw) stats.count_text_term += 1;
|
|
699
|
+
if (cst.definition_raw) stats.count_definition += 1;
|
|
700
|
+
if (isBasicConcept(cst.cst_type) && cst.convention) stats.count_convention += 1;
|
|
701
|
+
if (!isBasicConcept(cst.cst_type) && !cst.convention) stats.count_comment += 1;
|
|
702
|
+
switch (cst.cst_type) {
|
|
703
|
+
case CstType.BASE:
|
|
704
|
+
stats.count_base += 1;
|
|
705
|
+
break;
|
|
706
|
+
case CstType.CONSTANT:
|
|
707
|
+
stats.count_constant += 1;
|
|
708
|
+
break;
|
|
709
|
+
case CstType.STRUCTURED:
|
|
710
|
+
stats.count_structured += 1;
|
|
711
|
+
break;
|
|
712
|
+
case CstType.AXIOM:
|
|
713
|
+
stats.count_axiom += 1;
|
|
714
|
+
break;
|
|
715
|
+
case CstType.TERM:
|
|
716
|
+
stats.count_term += 1;
|
|
717
|
+
break;
|
|
718
|
+
case CstType.FUNCTION:
|
|
719
|
+
stats.count_function += 1;
|
|
720
|
+
break;
|
|
721
|
+
case CstType.PREDICATE:
|
|
722
|
+
stats.count_predicate += 1;
|
|
723
|
+
break;
|
|
724
|
+
case CstType.STATEMENT:
|
|
725
|
+
stats.count_statement += 1;
|
|
726
|
+
break;
|
|
727
|
+
case CstType.NOMINAL:
|
|
728
|
+
stats.count_nominal += 1;
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return stats;
|
|
733
|
+
}
|
|
734
|
+
function calculateStepComplexity(cst) {
|
|
735
|
+
if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) return 0;
|
|
736
|
+
if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT || !cst.effectiveType) return 1;
|
|
737
|
+
const type = cst.effectiveType;
|
|
738
|
+
return calculateTypificationComplexity(type) + 1;
|
|
739
|
+
}
|
|
740
|
+
function calculateTypificationComplexity(type) {
|
|
741
|
+
switch (type.typeID) {
|
|
742
|
+
case TypeID.basic:
|
|
743
|
+
case TypeID.integer:
|
|
744
|
+
case TypeID.anyTypification: return 0;
|
|
745
|
+
case TypeID.tuple: return type.factors.length + type.factors.reduce((sum, factor) => sum + calculateTypificationComplexity(factor), 0);
|
|
746
|
+
case TypeID.collection:
|
|
747
|
+
if (type.base.typeID === TypeID.tuple) {
|
|
748
|
+
let sum = 0;
|
|
749
|
+
type.base.factors.forEach((factor) => {
|
|
750
|
+
sum += calculateTypificationComplexity(factor);
|
|
751
|
+
});
|
|
752
|
+
return sum + type.base.factors.length;
|
|
753
|
+
} else if (type.base.typeID === TypeID.collection) return calculateTypificationComplexity(type.base) + 1;
|
|
754
|
+
return 0;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
/** Non-logical basic concept missing convention and/or resolved term (trimmed). */
|
|
758
|
+
function isMissingBasicText(cst) {
|
|
759
|
+
if (!isBasicConcept(cst.cst_type) || isLogical(cst.cst_type)) return false;
|
|
760
|
+
return !cst.convention.trim() || !cst.term_resolved.trim();
|
|
761
|
+
}
|
|
762
|
+
//#endregion
|
|
763
|
+
//#region src/library/rsform-api/structure.ts
|
|
764
|
+
/**
|
|
765
|
+
* Structure-path helpers for spawned constituents.
|
|
766
|
+
*/
|
|
767
|
+
/**
|
|
768
|
+
* Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:
|
|
769
|
+
* after the last existing child of that spawner, or after the spawner itself if none.
|
|
770
|
+
*/
|
|
771
|
+
function inferNewSpawnPosition(schema, targetId) {
|
|
772
|
+
let last = null;
|
|
773
|
+
for (const cst of schema.items) if (cst.spawner === targetId) last = cst.id;
|
|
774
|
+
return last ?? targetId;
|
|
775
|
+
}
|
|
776
|
+
/** Finds {@link Constituenta} by structure path. */
|
|
777
|
+
function findCstByStructure(schema, target, path) {
|
|
778
|
+
const byId = schema.cstByID ?? new Map(schema.items.map((item) => [item.id, item]));
|
|
779
|
+
for (const cst of schema.items) {
|
|
780
|
+
if (!cst.spawner_path) continue;
|
|
781
|
+
const absolutePath = resolveAbsoluteSpawnerPath(cst, target.id, byId);
|
|
782
|
+
if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) return cst;
|
|
783
|
+
}
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
/** Retrieves name for piece of target {@link Constituenta} structure. */
|
|
787
|
+
function getStructureName(schema, target, path) {
|
|
788
|
+
const representation = findCstByStructure(schema, target, path);
|
|
789
|
+
if (representation) return `${representation.alias}: ${representation.term_resolved}`;
|
|
790
|
+
if (!isTypification(target.effectiveType)) return "";
|
|
791
|
+
const type = applyPath(target.effectiveType, path);
|
|
792
|
+
if (type?.typeID === TypeID.basic) {
|
|
793
|
+
const cst = schema.cstByAlias.get(type.baseID);
|
|
794
|
+
if (cst?.term_resolved) return `${cst.alias}: ${cst.term_resolved}`;
|
|
795
|
+
}
|
|
796
|
+
return "";
|
|
797
|
+
}
|
|
798
|
+
function resolveAbsoluteSpawnerPath(cst, targetId, byId) {
|
|
799
|
+
if (!cst.spawner_path || cst.spawner == null) return null;
|
|
800
|
+
if (cst.spawner === targetId) return cst.spawner_path;
|
|
801
|
+
const visited = /* @__PURE__ */ new Set([cst.id]);
|
|
802
|
+
let currentPath = [...cst.spawner_path];
|
|
803
|
+
let currentSpawnerId = cst.spawner;
|
|
804
|
+
while (currentSpawnerId != null) {
|
|
805
|
+
if (currentSpawnerId === targetId) return currentPath;
|
|
806
|
+
if (visited.has(currentSpawnerId)) return null;
|
|
807
|
+
visited.add(currentSpawnerId);
|
|
808
|
+
const parent = byId.get(currentSpawnerId);
|
|
809
|
+
if (!parent?.spawner_path || parent.spawner == null) return null;
|
|
810
|
+
currentPath = [...parent.spawner_path, ...currentPath];
|
|
811
|
+
currentSpawnerId = parent.spawner;
|
|
812
|
+
}
|
|
813
|
+
return null;
|
|
814
|
+
}
|
|
815
|
+
//#endregion
|
|
816
|
+
//#region src/library/rsform-api/substitution.ts
|
|
817
|
+
/**
|
|
818
|
+
* Apply constituenta substitutions: remap attributions, drop originals, rewrite aliases in survivors.
|
|
819
|
+
* Does not resolve texts — call {@link resolveAllConstituentTexts} afterwards.
|
|
820
|
+
*/
|
|
821
|
+
function applyConstituentSubstitutions(items, attributions, substitutions) {
|
|
822
|
+
if (substitutions.length === 0) return {
|
|
823
|
+
items: [...items],
|
|
824
|
+
attributions: attributions.map((attr) => ({ ...attr })),
|
|
825
|
+
deletedIds: /* @__PURE__ */ new Set(),
|
|
826
|
+
replacementIds: []
|
|
827
|
+
};
|
|
828
|
+
const byId = new Map(items.map((cst) => [cst.id, cst]));
|
|
829
|
+
const mapping = {};
|
|
830
|
+
const deletedIds = /* @__PURE__ */ new Set();
|
|
831
|
+
const origToSub = /* @__PURE__ */ new Map();
|
|
832
|
+
const replacementIds = [];
|
|
833
|
+
for (const { original, substitution } of substitutions) {
|
|
834
|
+
const originalCst = byId.get(original);
|
|
835
|
+
const substitutionCst = byId.get(substitution);
|
|
836
|
+
if (!originalCst || !substitutionCst) throw new Error(`applyConstituentSubstitutions: unknown constituenta ${original} -> ${substitution}`);
|
|
837
|
+
mapping[originalCst.alias] = substitutionCst.alias;
|
|
838
|
+
deletedIds.add(original);
|
|
839
|
+
origToSub.set(original, substitution);
|
|
840
|
+
replacementIds.push(substitution);
|
|
841
|
+
}
|
|
842
|
+
const nextItems = items.filter((cst) => !deletedIds.has(cst.id));
|
|
843
|
+
applyMappingToConstituents(nextItems, mapping, false);
|
|
844
|
+
return {
|
|
845
|
+
items: nextItems,
|
|
846
|
+
attributions: remapAttributionsUnderSubstitution(attributions, origToSub),
|
|
847
|
+
deletedIds,
|
|
848
|
+
replacementIds
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Remap substitution endpoints after source constituents were inserted under new ids.
|
|
853
|
+
* If {@link original} was imported, map it; otherwise map {@link substitution}.
|
|
854
|
+
*/
|
|
855
|
+
function remapSubstitutionsAfterImport(substitutions, sourceIdSet, idMap) {
|
|
856
|
+
return substitutions.map((sub) => {
|
|
857
|
+
if (sourceIdSet.has(sub.original)) return {
|
|
858
|
+
original: idMap[sub.original],
|
|
859
|
+
substitution: sub.substitution
|
|
860
|
+
};
|
|
861
|
+
return {
|
|
862
|
+
original: sub.original,
|
|
863
|
+
substitution: idMap[sub.substitution]
|
|
864
|
+
};
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
//#endregion
|
|
868
|
+
//#region src/library/rsform-api/text-resolution.ts
|
|
869
|
+
/** Build term-reference graph: referenced constituent → dependent (backend {@code graph_term}). */
|
|
870
|
+
function buildTermReferenceGraph(items) {
|
|
871
|
+
return buildReferenceGraph(items, "term_raw");
|
|
872
|
+
}
|
|
873
|
+
/** Build definition-reference graph: referenced constituent → dependent (backend {@code graph_text}). */
|
|
874
|
+
function buildDefinitionReferenceGraph(items) {
|
|
875
|
+
return buildReferenceGraph(items, "definition_raw");
|
|
876
|
+
}
|
|
877
|
+
/** Resolve all term and definition texts in topological order. Mutates items in place. */
|
|
878
|
+
function resolveAllConstituentTexts(items) {
|
|
879
|
+
const graphTerm = buildTermReferenceGraph(items);
|
|
880
|
+
const idToItem = new Map(items.map((item) => [item.id, item]));
|
|
881
|
+
const context = buildTermContext(items);
|
|
882
|
+
for (const id of graphTerm.topologicalOrder()) {
|
|
883
|
+
const row = idToItem.get(id);
|
|
884
|
+
if (!row) continue;
|
|
885
|
+
const resolved = resolveTextReferences(row.term_raw, context);
|
|
886
|
+
if (resolved !== row.term_resolved) {
|
|
887
|
+
row.term_resolved = resolved;
|
|
888
|
+
row.term_forms = [];
|
|
889
|
+
context[row.alias] = {
|
|
890
|
+
nominal: row.term_resolved,
|
|
891
|
+
forms: []
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
for (const row of items) row.definition_resolved = resolveTextReferences(row.definition_raw, context);
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Resolve texts after a single constituent change, cascading dependents when the term changed.
|
|
899
|
+
* Mutates items in place.
|
|
900
|
+
*/
|
|
901
|
+
function resolveConstituentTextChange(items, targetID, options) {
|
|
902
|
+
const idToItem = new Map(items.map((item) => [item.id, item]));
|
|
903
|
+
const target = idToItem.get(targetID);
|
|
904
|
+
if (!target) throw new Error(`resolveConstituentTextChange: unknown target ${targetID}`);
|
|
905
|
+
const context = buildTermContext(items);
|
|
906
|
+
if (options.termRawChanged) {
|
|
907
|
+
target.term_resolved = resolveTextReferences(target.term_raw, context);
|
|
908
|
+
if (options.clearTargetForms) target.term_forms = [];
|
|
909
|
+
context[target.alias] = toContextItem(target);
|
|
910
|
+
} else if (options.termChanged) context[target.alias] = toContextItem(target);
|
|
911
|
+
if (options.definitionRawChanged && !options.termChanged) target.definition_resolved = resolveTextReferences(target.definition_raw, context);
|
|
912
|
+
if (!options.termChanged) return;
|
|
913
|
+
const graphTerm = buildTermReferenceGraph(items);
|
|
914
|
+
const graphText = buildDefinitionReferenceGraph(items);
|
|
915
|
+
const expansion = graphTerm.expandAllOutputs([targetID]);
|
|
916
|
+
const expansionSet = new Set(expansion);
|
|
917
|
+
for (const id of graphTerm.topologicalOrder()) {
|
|
918
|
+
if (!expansionSet.has(id)) continue;
|
|
919
|
+
const expanded = idToItem.get(id);
|
|
920
|
+
if (!expanded) continue;
|
|
921
|
+
const resolved = resolveTextReferences(expanded.term_raw, context);
|
|
922
|
+
if (resolved !== expanded.term_resolved) {
|
|
923
|
+
expanded.term_resolved = resolved;
|
|
924
|
+
expanded.term_forms = [];
|
|
925
|
+
context[expanded.alias] = {
|
|
926
|
+
nominal: expanded.term_resolved,
|
|
927
|
+
forms: []
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
const updateDefs = /* @__PURE__ */ new Set([
|
|
932
|
+
targetID,
|
|
933
|
+
...expansion,
|
|
934
|
+
...graphText.expandAllOutputs([targetID, ...expansion])
|
|
935
|
+
]);
|
|
936
|
+
for (const item of items) if (updateDefs.has(item.id)) item.definition_resolved = resolveTextReferences(item.definition_raw, context);
|
|
937
|
+
}
|
|
938
|
+
function buildReferenceGraph(items, field) {
|
|
939
|
+
const graph = new Graph();
|
|
940
|
+
const idByAlias = new Map(items.map((row) => [row.alias, row.id]));
|
|
941
|
+
for (const row of items) graph.addNode(row.id);
|
|
942
|
+
for (const row of items) for (const entity of extractEntities(row[field])) {
|
|
943
|
+
const source = idByAlias.get(entity);
|
|
944
|
+
if (source !== void 0) graph.addEdge(source, row.id);
|
|
945
|
+
}
|
|
946
|
+
return graph;
|
|
947
|
+
}
|
|
948
|
+
function buildTermContext(items) {
|
|
949
|
+
const context = {};
|
|
950
|
+
for (const row of items) context[row.alias] = toContextItem(row);
|
|
951
|
+
return context;
|
|
952
|
+
}
|
|
953
|
+
function toContextItem(row) {
|
|
954
|
+
return {
|
|
955
|
+
nominal: row.term_resolved,
|
|
956
|
+
forms: row.term_forms.map((form) => ({
|
|
957
|
+
text: form.text,
|
|
958
|
+
grams: parseGrammemes(form.tags)
|
|
959
|
+
}))
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
//#endregion
|
|
963
|
+
//#region src/library/rsform-api/synthesis.ts
|
|
964
|
+
/**
|
|
965
|
+
* Embed {@link InlineSynthesisInput.sourceItems} into the receiver and apply substitutions.
|
|
966
|
+
* Resolves term/definition entity references on the result.
|
|
967
|
+
* Does not mutate inputs.
|
|
968
|
+
*/
|
|
969
|
+
function inlineSynthesis(input) {
|
|
970
|
+
const sourceItems = input.sourceItems;
|
|
971
|
+
if (sourceItems.length === 0) return {
|
|
972
|
+
items: input.receiverItems.map((item) => structuredClone(item)),
|
|
973
|
+
attributions: (input.receiverAttributions ?? []).map((attr) => ({ ...attr })),
|
|
974
|
+
nextId: input.nextId,
|
|
975
|
+
idMap: {},
|
|
976
|
+
aliasMapping: {},
|
|
977
|
+
deletedIds: /* @__PURE__ */ new Set(),
|
|
978
|
+
insertedIds: [],
|
|
979
|
+
replacementIds: []
|
|
980
|
+
};
|
|
981
|
+
const receiverItems = input.receiverItems.map((item) => structuredClone(item));
|
|
982
|
+
let attributions = (input.receiverAttributions ?? []).map((attr) => ({ ...attr }));
|
|
983
|
+
const aliasMapping = allocateImportAliases(receiverItems, sourceItems);
|
|
984
|
+
const idMap = {};
|
|
985
|
+
const inserted = [];
|
|
986
|
+
const sourceIdSet = new Set(sourceItems.map((cst) => cst.id));
|
|
987
|
+
let nextId = input.nextId;
|
|
988
|
+
for (const cst of sourceItems) {
|
|
989
|
+
const newId = nextId;
|
|
990
|
+
nextId += 1;
|
|
991
|
+
idMap[cst.id] = newId;
|
|
992
|
+
const cloned = structuredClone(cst);
|
|
993
|
+
cloned.id = newId;
|
|
994
|
+
if (Object.keys(aliasMapping).length > 0) {
|
|
995
|
+
cloned.alias = aliasMapping[cst.alias];
|
|
996
|
+
applyMappingToConstituents([cloned], aliasMapping, false);
|
|
997
|
+
}
|
|
998
|
+
inserted.push(cloned);
|
|
999
|
+
}
|
|
1000
|
+
attributions = importAttributions(input.sourceAttributions ?? [], sourceIdSet, idMap, attributions);
|
|
1001
|
+
const items = receiverItems.concat(inserted);
|
|
1002
|
+
resolveAllConstituentTexts(items);
|
|
1003
|
+
const substitutions = input.substitutions ?? [];
|
|
1004
|
+
if (substitutions.length === 0) return {
|
|
1005
|
+
items,
|
|
1006
|
+
attributions,
|
|
1007
|
+
nextId,
|
|
1008
|
+
idMap,
|
|
1009
|
+
aliasMapping,
|
|
1010
|
+
deletedIds: /* @__PURE__ */ new Set(),
|
|
1011
|
+
insertedIds: inserted.map((cst) => cst.id),
|
|
1012
|
+
replacementIds: []
|
|
1013
|
+
};
|
|
1014
|
+
const remapped = remapSubstitutionsAfterImport(substitutions, sourceIdSet, idMap);
|
|
1015
|
+
const substituted = applyConstituentSubstitutions(items, attributions, remapped);
|
|
1016
|
+
resolveAllConstituentTexts(substituted.items);
|
|
1017
|
+
return {
|
|
1018
|
+
items: substituted.items,
|
|
1019
|
+
attributions: substituted.attributions,
|
|
1020
|
+
nextId,
|
|
1021
|
+
idMap,
|
|
1022
|
+
aliasMapping,
|
|
1023
|
+
deletedIds: substituted.deletedIds,
|
|
1024
|
+
insertedIds: inserted.map((cst) => cst.id),
|
|
1025
|
+
replacementIds: substituted.replacementIds
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
/** Sorts library items relevant for schema embedding with specified {@link RSForm}. */
|
|
1029
|
+
function sortItemsForInlineSynthesis(receiver, items) {
|
|
1030
|
+
const result = items.filter((item) => item.location === receiver.location);
|
|
1031
|
+
for (const item of items) if (item.visible && item.owner === receiver.owner && !result.includes(item)) result.push(item);
|
|
1032
|
+
for (const item of items) if (item.visible && !result.includes(item)) result.push(item);
|
|
1033
|
+
for (const item of items) if (!result.includes(item)) result.push(item);
|
|
1034
|
+
return result;
|
|
1035
|
+
}
|
|
1036
|
+
//#endregion
|
|
1037
|
+
//#region src/library/rsform-api/transforms.ts
|
|
1038
|
+
/**
|
|
1039
|
+
* Pure constituenta list transforms: reorder, move, insert position.
|
|
1040
|
+
*/
|
|
1041
|
+
/** Rebuild an item list following {@link orderedIds}. Throws if an id is missing. */
|
|
1042
|
+
function reorderItemsByIds(items, orderedIds) {
|
|
1043
|
+
const byId = new Map(items.map((item) => [item.id, item]));
|
|
1044
|
+
return orderedIds.map((id) => {
|
|
1045
|
+
const item = byId.get(id);
|
|
1046
|
+
if (!item) throw new Error(`reorderItemsByIds: missing id ${id}`);
|
|
1047
|
+
return item;
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Move a subset of ids within an ordered id list.
|
|
1052
|
+
* {@link moveTo} is clamped to `[0, rest.length]` (index among non-moving items).
|
|
1053
|
+
*/
|
|
1054
|
+
function moveIdsInOrder(ids, moving, moveTo) {
|
|
1055
|
+
const movingSet = new Set(moving);
|
|
1056
|
+
const rest = ids.filter((id) => !movingSet.has(id));
|
|
1057
|
+
const movingItems = ids.filter((id) => movingSet.has(id));
|
|
1058
|
+
const clamped = Math.max(0, Math.min(moveTo, rest.length));
|
|
1059
|
+
return [
|
|
1060
|
+
...rest.slice(0, clamped),
|
|
1061
|
+
...movingItems,
|
|
1062
|
+
...rest.slice(clamped)
|
|
1063
|
+
];
|
|
1064
|
+
}
|
|
1065
|
+
/** Insert {@link item} after {@link insertAfter}, or append when null/undefined/missing. Mutates {@link items}. */
|
|
1066
|
+
function insertItemAfter(items, item, insertAfter) {
|
|
1067
|
+
if (insertAfter === null || insertAfter === void 0) {
|
|
1068
|
+
items.push(item);
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
const idx = items.findIndex((row) => row.id === insertAfter);
|
|
1072
|
+
const insertAt = idx === -1 ? items.length : idx + 1;
|
|
1073
|
+
items.splice(insertAt, 0, item);
|
|
1074
|
+
}
|
|
1075
|
+
//#endregion
|
|
1076
|
+
//#region src/library/diagnostics.ts
|
|
1077
|
+
/** Origin of a diagnostic. */
|
|
1078
|
+
const DiagnosticKind = {
|
|
1079
|
+
EXPRESSION: "expression",
|
|
1080
|
+
SCHEMA: "schema",
|
|
1081
|
+
MODEL: "model"
|
|
1082
|
+
};
|
|
1083
|
+
/** Schema and model diagnostic codes (same numeric format as {@link RSErrorCode}). */
|
|
1084
|
+
const RSDiagnosticCode = {
|
|
1085
|
+
schemaHomonym: 35073,
|
|
1086
|
+
schemaFormalDuplicate: 35074,
|
|
1087
|
+
schemaMissingConvention: 35075,
|
|
1088
|
+
schemaMissingTerm: 35076,
|
|
1089
|
+
schemaTypeMismatch: 35077,
|
|
1090
|
+
schemaDependencyCycle: 35078,
|
|
1091
|
+
modelEmpty: 35088,
|
|
1092
|
+
modelAxiomFalse: 35089,
|
|
1093
|
+
modelInvalidData: 35090,
|
|
1094
|
+
modelEvalFail: 35091
|
|
1095
|
+
};
|
|
1096
|
+
/** Whether a constituent has a schema/model diagnostic with the given code. */
|
|
1097
|
+
function hasCstDiagnostic(cst, code) {
|
|
1098
|
+
return cst.diagnostics?.some((item) => item.code === code) ?? false;
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch, cycles).
|
|
1102
|
+
*
|
|
1103
|
+
* Requires normalized formal definitions for duplicate detection (same as Portal loader).
|
|
1104
|
+
* When `graph` is provided, dependency cycles are reported as {@link RSDiagnosticCode.schemaDependencyCycle}.
|
|
1105
|
+
*/
|
|
1106
|
+
function assignSchemaDiagnostics(items, resolveAlias, normalizedDefinitions, graph) {
|
|
1107
|
+
const homonymById = detectHomonymDiagnostics(items, resolveAlias);
|
|
1108
|
+
const duplicateById = detectFormalDuplicateDiagnostics(items, resolveAlias, normalizedDefinitions);
|
|
1109
|
+
const cycleById = graph ? detectDependencyCycleDiagnostics(graph, resolveAlias) : /* @__PURE__ */ new Map();
|
|
1110
|
+
for (const cst of items) {
|
|
1111
|
+
const diagnostics = [];
|
|
1112
|
+
const cycle = cycleById.get(cst.id);
|
|
1113
|
+
if (cycle) diagnostics.push(cycle);
|
|
1114
|
+
const homonym = homonymById.get(cst.id);
|
|
1115
|
+
if (homonym) diagnostics.push(homonym);
|
|
1116
|
+
const duplicate = duplicateById.get(cst.id);
|
|
1117
|
+
if (duplicate) diagnostics.push(duplicate);
|
|
1118
|
+
diagnostics.push(...collectLocalSchemaDiagnostics(cst));
|
|
1119
|
+
cst.diagnostics = diagnostics;
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Format a closed dependency cycle as `A → B → A`.
|
|
1124
|
+
*
|
|
1125
|
+
* Rotates the path to start at the lexicographically smallest alias so the same
|
|
1126
|
+
* cycle always renders identically regardless of graph traversal order.
|
|
1127
|
+
*
|
|
1128
|
+
* @param aliases Closed or open alias path from {@link Graph.findCycles}.
|
|
1129
|
+
* @returns Human-readable cycle text joined with ` → `.
|
|
1130
|
+
*/
|
|
1131
|
+
function formatDependencyCycle(aliases) {
|
|
1132
|
+
if (aliases.length < 2) return aliases.join(" → ");
|
|
1133
|
+
const closed = aliases[0] === aliases[aliases.length - 1];
|
|
1134
|
+
const open = closed ? aliases.slice(0, -1) : [...aliases];
|
|
1135
|
+
if (open.length === 0) return aliases.join(" → ");
|
|
1136
|
+
let bestStart = 0;
|
|
1137
|
+
for (let index = 1; index < open.length; index++) {
|
|
1138
|
+
const alias = open[index];
|
|
1139
|
+
const bestAlias = open[bestStart];
|
|
1140
|
+
if (alias !== void 0 && bestAlias !== void 0 && alias < bestAlias) bestStart = index;
|
|
1141
|
+
}
|
|
1142
|
+
const rotated = [...open.slice(bestStart), ...open.slice(0, bestStart)];
|
|
1143
|
+
if (closed) {
|
|
1144
|
+
const first = rotated[0];
|
|
1145
|
+
if (first !== void 0) rotated.push(first);
|
|
1146
|
+
}
|
|
1147
|
+
return rotated.join(" → ");
|
|
1148
|
+
}
|
|
1149
|
+
/**
|
|
1150
|
+
* Map each node id that participates in a dependency cycle to a schema diagnostic.
|
|
1151
|
+
*
|
|
1152
|
+
* `params[0]` is the closed cycle path (`F3 → P1 → F3`).
|
|
1153
|
+
*
|
|
1154
|
+
* @param graph Constituent dependency graph (provider → dependent edges).
|
|
1155
|
+
* @param resolveAlias Maps node id to display alias for cycle formatting.
|
|
1156
|
+
* @returns One {@link CstDiagnostic} per node on each cyclic SCC.
|
|
1157
|
+
*/
|
|
1158
|
+
function detectDependencyCycleDiagnostics(graph, resolveAlias) {
|
|
1159
|
+
const result = /* @__PURE__ */ new Map();
|
|
1160
|
+
for (const cycle of graph.findCycles()) {
|
|
1161
|
+
if (cycle.length < 2) continue;
|
|
1162
|
+
const cycleText = formatDependencyCycle(cycle.map((id) => resolveAlias(id)));
|
|
1163
|
+
const memberIds = new Set(cycle);
|
|
1164
|
+
for (const id of memberIds) result.set(id, {
|
|
1165
|
+
kind: DiagnosticKind.SCHEMA,
|
|
1166
|
+
code: RSDiagnosticCode.schemaDependencyCycle,
|
|
1167
|
+
params: [cycleText]
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
return result;
|
|
1171
|
+
}
|
|
1172
|
+
/** Map a model evaluation status to a compact diagnostic, or `null` when not an issue. */
|
|
1173
|
+
function modelStatusCstDiagnostic(status, cstType) {
|
|
1174
|
+
const code = modelStatusToCode(status, cstType);
|
|
1175
|
+
if (code === null) return null;
|
|
1176
|
+
return {
|
|
1177
|
+
kind: DiagnosticKind.MODEL,
|
|
1178
|
+
code,
|
|
1179
|
+
params: [String(status)]
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
function collectLocalSchemaDiagnostics(cst) {
|
|
1183
|
+
const result = [];
|
|
1184
|
+
if (cst.is_type_mismatch) result.push({
|
|
1185
|
+
kind: DiagnosticKind.SCHEMA,
|
|
1186
|
+
code: RSDiagnosticCode.schemaTypeMismatch,
|
|
1187
|
+
params: [cst.typification_manual, labelType(cst.analysis.type)]
|
|
1188
|
+
});
|
|
1189
|
+
if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {
|
|
1190
|
+
if (!cst.convention.trim()) result.push({
|
|
1191
|
+
kind: DiagnosticKind.SCHEMA,
|
|
1192
|
+
code: RSDiagnosticCode.schemaMissingConvention
|
|
1193
|
+
});
|
|
1194
|
+
if (!cst.term_resolved.trim()) result.push({
|
|
1195
|
+
kind: DiagnosticKind.SCHEMA,
|
|
1196
|
+
code: RSDiagnosticCode.schemaMissingTerm
|
|
1197
|
+
});
|
|
1198
|
+
}
|
|
1199
|
+
return result;
|
|
1200
|
+
}
|
|
1201
|
+
function detectGroupedAliasDiagnostics(items, resolveAlias, groupKey, code) {
|
|
1202
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1203
|
+
for (const cst of items) {
|
|
1204
|
+
const key = groupKey(cst);
|
|
1205
|
+
if (!key) continue;
|
|
1206
|
+
const group = groups.get(key) ?? [];
|
|
1207
|
+
group.push(cst);
|
|
1208
|
+
groups.set(key, group);
|
|
1209
|
+
}
|
|
1210
|
+
const result = /* @__PURE__ */ new Map();
|
|
1211
|
+
for (const group of groups.values()) {
|
|
1212
|
+
if (group.length <= 1) continue;
|
|
1213
|
+
for (const cst of group) {
|
|
1214
|
+
const aliases = group.filter((other) => other.id !== cst.id).map((other) => resolveAlias(other.id)).join(", ");
|
|
1215
|
+
result.set(cst.id, {
|
|
1216
|
+
kind: DiagnosticKind.SCHEMA,
|
|
1217
|
+
code,
|
|
1218
|
+
params: [aliases]
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
return result;
|
|
1223
|
+
}
|
|
1224
|
+
function detectHomonymDiagnostics(items, resolveAlias) {
|
|
1225
|
+
return detectGroupedAliasDiagnostics(items, resolveAlias, (cst) => {
|
|
1226
|
+
const key = cst.term_resolved.trim().toLocaleLowerCase();
|
|
1227
|
+
return key === "" ? void 0 : key;
|
|
1228
|
+
}, RSDiagnosticCode.schemaHomonym);
|
|
1229
|
+
}
|
|
1230
|
+
function detectFormalDuplicateDiagnostics(items, resolveAlias, normalizedDefinitions) {
|
|
1231
|
+
return detectGroupedAliasDiagnostics(items, resolveAlias, (cst) => normalizedDefinitions.get(cst.id), RSDiagnosticCode.schemaFormalDuplicate);
|
|
1232
|
+
}
|
|
1233
|
+
function modelStatusToCode(status, cstType) {
|
|
1234
|
+
switch (status) {
|
|
1235
|
+
case EvalStatus.EMPTY: return isBasicConcept(cstType) ? RSDiagnosticCode.modelEmpty : null;
|
|
1236
|
+
case EvalStatus.AXIOM_FALSE: return RSDiagnosticCode.modelAxiomFalse;
|
|
1237
|
+
case EvalStatus.INVALID_DATA: return RSDiagnosticCode.modelInvalidData;
|
|
1238
|
+
case EvalStatus.EVAL_FAIL: return RSDiagnosticCode.modelEvalFail;
|
|
1239
|
+
default: return null;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
//#endregion
|
|
1243
|
+
export { isFunctional as $, normalizeExpression as A, buildSequentialAliasMapping as B, isSchemaIssue as C, inferStatus as D, applyFilterCategory as E, refineAnalysisForDependencyCycles as F, validateNewAlias as G, maxAliasIndex as H, addAliasReference as I, getCstTypePrefix as J, canHaveManualTypification as K, allocateImportAliases as L, importAttributions as M, remapAttributionsUnderSubstitution as N, inferTemplate as O, getAnalysisFor as P, isBasicConcept as Q, applyMappingToConstituents as R, calculateSchemaStats as S, restoreConstituentOrder as T, removeAliasReference as U, generateAlias as V, validateAliasFormat as W, inferClass as X, guessCstType as Y, isBaseSet as Z, applyConstituentSubstitutions as _, formatDependencyCycle as a, getStructureName as b, insertItemAfter as c, inlineSynthesis as d, isLogical as et, sortItemsForInlineSynthesis as f, resolveConstituentTextChange as g, resolveAllConstituentTexts as h, detectDependencyCycleDiagnostics as i, filterAttributions as j, inferTemplatedType as k, moveIdsInOrder as l, buildTermReferenceGraph as m, RSDiagnosticCode as n, typeClassForCstType as nt, hasCstDiagnostic as o, buildDefinitionReferenceGraph as p, canProduceStructure as q, assignSchemaDiagnostics as r, modelStatusCstDiagnostic as s, DiagnosticKind as t, isTemplateCst as tt, reorderItemsByIds as u, remapSubstitutionsAfterImport as v, buildFormalDependencyGraph as w, inferNewSpawnPosition as x, findCstByStructure as y, argumentValuesToMapping as z };
|
|
1244
|
+
|
|
1245
|
+
//# sourceMappingURL=diagnostics-CljEzVBV.js.map
|