@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,755 +0,0 @@
1
- /**
2
- * Module: API for formal representation for systems of concepts.
3
- */
4
-
5
- import { applyEntityReferenceMapping } from '../cctext/language-api';
6
- import { type Graph } from '../graph';
7
- import { type AstNode } from '../parsing';
8
- import {
9
- type AnalysisFull,
10
- RSErrorCode,
11
- TypeClass,
12
- TypeID,
13
- type TypePath,
14
- type Typification,
15
- ValueClass
16
- } from '../rslang';
17
- import {
18
- type AliasMapping,
19
- applyAliasMapping,
20
- applyTypificationMapping,
21
- extractGlobals,
22
- generateExpressionFromAst,
23
- parseRSLangExpression
24
- } from '../rslang/api';
25
- import { basic, bool, constant, type EchelonFunctional, isTypification } from '../rslang/semantic/typification';
26
- import { applyPath } from '../rslang/semantic/typification-api';
27
-
28
- import { formatDependencyCycle, hasCstDiagnostic, RSDiagnosticCode } from './diagnostics';
29
- import { type LibraryItem } from './library';
30
- import {
31
- type ArgumentValue,
32
- type Constituenta,
33
- CstClass,
34
- CstStatus,
35
- CstType,
36
- type RSForm,
37
- type RSFormStats
38
- } from './rsform';
39
-
40
- /** Record of {@link CstType} prefixes. */
41
- const CST_TYPE_PREFIX: Record<CstType, string> = {
42
- [CstType.NOMINAL]: 'N',
43
- [CstType.BASE]: 'X',
44
- [CstType.CONSTANT]: 'C',
45
- [CstType.STRUCTURED]: 'S',
46
- [CstType.AXIOM]: 'A',
47
- [CstType.TERM]: 'D',
48
- [CstType.FUNCTION]: 'F',
49
- [CstType.PREDICATE]: 'P',
50
- [CstType.STATEMENT]: 'T'
51
- };
52
-
53
- /** Record of {@link CstType} to {@link CstClass} mapping. */
54
- const CST_TYPE_TO_CLASS: Record<CstType, CstClass> = {
55
- [CstType.NOMINAL]: CstClass.NOMINAL,
56
- [CstType.BASE]: CstClass.BASIC,
57
- [CstType.CONSTANT]: CstClass.BASIC,
58
- [CstType.STRUCTURED]: CstClass.BASIC,
59
- [CstType.TERM]: CstClass.DERIVED,
60
- [CstType.FUNCTION]: CstClass.DERIVED,
61
- [CstType.AXIOM]: CstClass.STATEMENT,
62
- [CstType.PREDICATE]: CstClass.DERIVED,
63
- [CstType.STATEMENT]: CstClass.STATEMENT
64
- };
65
-
66
- /** Checks if {@link Constituenta} is a schema issue. */
67
- export function isSchemaIssue(cst: Constituenta): boolean {
68
- return (
69
- (cst.diagnostics?.length ?? 0) > 0 || cst.status === CstStatus.INCORRECT || cst.status === CstStatus.INCALCULABLE
70
- );
71
- }
72
-
73
- /** Infers the status of an expression based on parsing and value information. */
74
- export function inferStatus(parse: boolean, value?: ValueClass | null): CstStatus {
75
- if (!parse) {
76
- return CstStatus.INCORRECT;
77
- }
78
- if (value === null) {
79
- return CstStatus.INCALCULABLE;
80
- }
81
- if (value === ValueClass.PROPERTY) {
82
- return CstStatus.PROPERTY;
83
- }
84
- return CstStatus.VERIFIED;
85
- }
86
-
87
- /** Infers type of constituent for a given template and arguments. */
88
- export function inferTemplatedType(templateType: CstType, args: ArgumentValue[]): CstType {
89
- if (args.length === 0 || args.some(arg => !arg.value)) {
90
- return templateType;
91
- } else if (templateType === CstType.PREDICATE) {
92
- return CstType.AXIOM;
93
- } else {
94
- return CstType.TERM;
95
- }
96
- }
97
-
98
- /** Build alias mapping from template argument bindings. */
99
- export function argumentValuesToMapping(args: ArgumentValue[]): AliasMapping {
100
- const mapping: AliasMapping = {};
101
- for (const arg of args) {
102
- if (arg.value) {
103
- mapping[arg.alias] = arg.value;
104
- }
105
- }
106
- return mapping;
107
- }
108
-
109
- /**
110
- * Normalize a RSLang expression for duplicate comparison.
111
- *
112
- * Returns `null` for basic concepts without formal definitions. Pass a pre-parsed `ast`
113
- * when the expression was already analyzed to avoid re-parsing.
114
- */
115
- export function normalizeExpression(expression: string, cst_type: CstType, ast?: AstNode | null): string | null {
116
- if (isBasicConcept(cst_type) && cst_type !== CstType.AXIOM) {
117
- return null;
118
- }
119
- const parsed = ast ?? parseRSLangExpression(expression);
120
- let normalized = '';
121
- if (parsed && !parsed.hasError) {
122
- normalized = generateExpressionFromAst(parsed, { normalize: true });
123
- } else {
124
- normalized = expression;
125
- }
126
- normalized = normalized.replace(/\s+/g, '');
127
- return normalized === '' ? null : normalized;
128
- }
129
-
130
- /** Checks if given expression is a template. */
131
- export function inferTemplate(expression: string): boolean {
132
- const match = expression.match(/R\d+/g);
133
- return (match && match?.length > 0) ?? false;
134
- }
135
-
136
- /** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */
137
- export function inferClass(type: CstType, isTemplate: boolean = false): CstClass {
138
- if (isTemplate) {
139
- return CstClass.TEMPLATE;
140
- }
141
- return CST_TYPE_TO_CLASS[type];
142
- }
143
-
144
- /** Check if {@link Constituenta} is a template or a category. */
145
- export function isTemplateCst(cst: Constituenta): boolean {
146
- return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;
147
- }
148
-
149
- /** Apply filter based on start {@link Constituenta} type. */
150
- export function applyFilterCategory(start: Constituenta, items: Constituenta[]): Constituenta[] {
151
- const startIndex = items.indexOf(start);
152
- if (startIndex === -1) {
153
- return [];
154
- }
155
- const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);
156
-
157
- return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));
158
- }
159
-
160
- /** Prefix for alias indicating {@link CstType}. */
161
- export function getCstTypePrefix(type: CstType): string {
162
- return CST_TYPE_PREFIX[type];
163
- }
164
-
165
- /** Guess {@link CstType} from user input hint. */
166
- export function guessCstType(hint: string): CstType | null {
167
- if (hint.length !== 1) {
168
- return null;
169
- }
170
- for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) {
171
- if (hint === prefix) {
172
- return type as CstType;
173
- }
174
- }
175
- return null;
176
- }
177
-
178
- /** Evaluate if {@link CstType} is basic concept. */
179
- export function isBasicConcept(type: CstType): boolean {
180
- switch (type) {
181
- case CstType.NOMINAL:
182
- case CstType.BASE:
183
- case CstType.CONSTANT:
184
- case CstType.STRUCTURED:
185
- case CstType.AXIOM:
186
- return true;
187
-
188
- case CstType.TERM:
189
- case CstType.FUNCTION:
190
- case CstType.PREDICATE:
191
- case CstType.STATEMENT:
192
- return false;
193
- }
194
- }
195
-
196
- /** Evaluate if {@link CstType} is base set or constant set. */
197
- export function isBaseSet(type: CstType): boolean {
198
- switch (type) {
199
- case CstType.BASE:
200
- case CstType.CONSTANT:
201
- return true;
202
-
203
- case CstType.NOMINAL:
204
- case CstType.STRUCTURED:
205
- case CstType.AXIOM:
206
- case CstType.TERM:
207
- case CstType.FUNCTION:
208
- case CstType.PREDICATE:
209
- case CstType.STATEMENT:
210
- return false;
211
- }
212
- }
213
-
214
- /** Evaluate if {@link CstType} is a function. */
215
- export function isFunctional(type: CstType): boolean {
216
- switch (type) {
217
- case CstType.FUNCTION:
218
- case CstType.PREDICATE:
219
- return true;
220
-
221
- case CstType.NOMINAL:
222
- case CstType.BASE:
223
- case CstType.CONSTANT:
224
- case CstType.STRUCTURED:
225
- case CstType.AXIOM:
226
- case CstType.TERM:
227
- case CstType.STATEMENT:
228
- return false;
229
- }
230
- }
231
-
232
- /** Evaluate if {@link CstType} is logical. */
233
- export function isLogical(type: CstType): boolean {
234
- switch (type) {
235
- case CstType.AXIOM:
236
- case CstType.STATEMENT:
237
- return true;
238
-
239
- case CstType.NOMINAL:
240
- case CstType.BASE:
241
- case CstType.CONSTANT:
242
- case CstType.STRUCTURED:
243
- case CstType.TERM:
244
- case CstType.FUNCTION:
245
- case CstType.PREDICATE:
246
- return false;
247
- }
248
- }
249
-
250
- /** Evaluate if {@link Constituenta} can be used produce structure. */
251
- export function canProduceStructure(cst: Constituenta): boolean {
252
- switch (cst.cst_type) {
253
- case CstType.NOMINAL:
254
- case CstType.BASE:
255
- case CstType.CONSTANT:
256
- case CstType.AXIOM:
257
- case CstType.STATEMENT:
258
- case CstType.PREDICATE:
259
- return false;
260
- }
261
- if (!cst.effectiveType) {
262
- return false;
263
- }
264
- if (cst.cst_type === CstType.FUNCTION) {
265
- const result = (cst.effectiveType as EchelonFunctional).result;
266
- return typeCanProduceStructure(result);
267
- }
268
- if (!isTypification(cst.effectiveType)) {
269
- return false;
270
- }
271
- return typeCanProduceStructure(cst.effectiveType as Typification);
272
- }
273
-
274
- /** Evaluate if {@link CstType} can have manual typification. */
275
- export function canHaveManualTypification(type: CstType): boolean {
276
- switch (type) {
277
- case CstType.STRUCTURED:
278
- case CstType.TERM:
279
- case CstType.FUNCTION:
280
- case CstType.PREDICATE:
281
- return true;
282
-
283
- case CstType.NOMINAL:
284
- case CstType.BASE:
285
- case CstType.CONSTANT:
286
- case CstType.AXIOM:
287
- case CstType.STATEMENT:
288
- return false;
289
- }
290
- }
291
-
292
- /** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */
293
- export function validateAliasFormat(alias: string, type: CstType): boolean {
294
- if (alias.length < 2) {
295
- return false;
296
- }
297
- const prefix = getCstTypePrefix(type);
298
- if (!alias.startsWith(prefix)) {
299
- return false;
300
- }
301
- if (!/^\d+$/.exec(alias.substring(prefix.length))) {
302
- return false;
303
- }
304
- return true;
305
- }
306
-
307
- /** Validate new alias against {@link CstType} and {@link RSForm}. */
308
- export function validateNewAlias(alias: string, type: CstType, schema: RSForm): boolean {
309
- if (!validateAliasFormat(alias, type)) {
310
- return false;
311
- }
312
- if (schema.cstByAlias.has(alias)) {
313
- return false;
314
- }
315
- return true;
316
- }
317
-
318
- /** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */
319
- export function generateAlias(type: CstType, schema: RSForm, takenAliases: string[] = []): string {
320
- const prefix = getCstTypePrefix(type);
321
- if (schema.items.length <= 0) {
322
- return `${prefix}1`;
323
- }
324
- let index = schema.items.reduce((prev, cst, index) => {
325
- if (cst.cst_type !== type) {
326
- return prev;
327
- }
328
- index = Number(cst.alias.slice(1 - cst.alias.length)) + 1;
329
- return Math.max(prev, index);
330
- }, 1);
331
- let alias = `${prefix}${index}`;
332
- while (takenAliases.includes(alias)) {
333
- index = index + 1;
334
- alias = `${prefix}${index}`;
335
- }
336
- return alias;
337
- }
338
-
339
- /**
340
- * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:
341
- * after the last existing child of that spawner, or after the spawner itself if none.
342
- */
343
- export function inferNewSpawnPosition(schema: RSForm, targetId: number): number {
344
- let last: number | null = null;
345
- for (const cst of schema.items) {
346
- if (cst.spawner === targetId) {
347
- last = cst.id;
348
- }
349
- }
350
- return last ?? targetId;
351
- }
352
-
353
- /** Sorts library items relevant for InlineSynthesis with specified {@link RSForm}. */
354
- export function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly LibraryItem[]): LibraryItem[] {
355
- const result = items.filter(item => item.location === receiver.location);
356
- for (const item of items) {
357
- if (item.visible && item.owner === item.owner && !result.includes(item)) {
358
- result.push(item);
359
- }
360
- }
361
- for (const item of items) {
362
- if (item.visible && !result.includes(item)) {
363
- result.push(item);
364
- }
365
- }
366
- for (const item of items) {
367
- if (!result.includes(item)) {
368
- result.push(item);
369
- }
370
- }
371
- return result;
372
- }
373
-
374
- /** Fields of {@link Constituenta} updated in place by alias mapping. */
375
- export interface ConstituentaMappableFields {
376
- alias: string;
377
- definition_formal: string;
378
- typification_manual: string;
379
- term_raw: string;
380
- definition_raw: string;
381
- }
382
-
383
- /**
384
- * Remap formal expressions and terminological entity references in constituent fields.
385
- * Mutates each element of `items` in place; pass owned or cloned data only.
386
- */
387
- export function applyMappingToConstituents<T extends ConstituentaMappableFields>(
388
- items: T[],
389
- mapping: AliasMapping,
390
- changeAliases: boolean
391
- ): void {
392
- for (const cst of items) {
393
- if (changeAliases && cst.alias in mapping) {
394
- cst.alias = mapping[cst.alias];
395
- }
396
- cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);
397
- cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);
398
- cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);
399
- cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);
400
- }
401
- }
402
-
403
- /** Remove alias from expression. */
404
- export function removeAliasReference(expression: string, alias: string): string {
405
- const result = expression.replaceAll(new RegExp(`\\b${alias}\\b`, 'g'), 'DEL');
406
- return result === 'DEL' ? '' : result;
407
- }
408
-
409
- /** Add alias to expression. */
410
- export function addAliasReference(expression: string, alias: string): string {
411
- return expression + ' ' + alias;
412
- }
413
-
414
- /** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */
415
- export function typeClassForCstType(cstType: CstType): TypeClass {
416
- switch (cstType) {
417
- case CstType.NOMINAL:
418
- case CstType.BASE:
419
- case CstType.CONSTANT:
420
- case CstType.STRUCTURED:
421
- case CstType.TERM:
422
- return TypeClass.typification;
423
- case CstType.FUNCTION:
424
- return TypeClass.function;
425
- case CstType.PREDICATE:
426
- return TypeClass.predicate;
427
- case CstType.AXIOM:
428
- case CstType.STATEMENT:
429
- return TypeClass.logic;
430
- }
431
- }
432
-
433
- /** Checks whether a constituenta type supports formal definitions. */
434
- export function canHaveFormalDefinition(cstType: CstType): boolean {
435
- return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;
436
- }
437
-
438
- export function getAnalysisFor(expression: string, cstType: CstType, schema: RSForm, alias?: string): AnalysisFull {
439
- if (!canHaveFormalDefinition(cstType)) {
440
- if (expression.trim().length === 0) {
441
- const fallbackAlias = alias && alias.length > 0 ? alias : 'X0';
442
- const type = cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias));
443
- return {
444
- success: true,
445
- type,
446
- valueClass: ValueClass.VALUE,
447
- errors: [],
448
- ast: null
449
- };
450
- }
451
- return {
452
- success: false,
453
- type: null,
454
- valueClass: null,
455
- errors: [
456
- {
457
- code: RSErrorCode.definitionNotAllowed,
458
- from: 0,
459
- to: Math.max(expression.length, 1),
460
- params: [cstType, alias ?? '']
461
- }
462
- ],
463
- ast: null
464
- };
465
- }
466
- const analysis = schema.analyzer.checkFull(expression, {
467
- expected: typeClassForCstType(cstType),
468
- isDomain: cstType === CstType.STRUCTURED
469
- });
470
- return refineAnalysisForDependencyCycles(analysis, expression, schema, alias);
471
- }
472
-
473
- /**
474
- * When an untyped / bare F·P reference names a constituent on a definition cycle with the
475
- * current expression, replace that error with {@link RSDiagnosticCode.schemaDependencyCycle}.
476
- *
477
- * Covers both semantic `globalNotTyped` (e.g. `F3[σ]`) and parser `globalFuncWithoutArgs`
478
- * (bare `P1` / `F1` treated as a call without arguments).
479
- *
480
- * Uses a draft dependency graph: incoming edges of the edited constituent are taken from
481
- * `expression`, so Check works before Save.
482
- */
483
- export function refineAnalysisForDependencyCycles(
484
- analysis: AnalysisFull,
485
- expression: string,
486
- schema: RSForm,
487
- alias?: string
488
- ): AnalysisFull {
489
- if (analysis.errors.length === 0 || !schema.graph) {
490
- return analysis;
491
- }
492
-
493
- const currentId = alias ? schema.cstByAlias.get(alias)?.id : undefined;
494
- const expressionGlobals = extractGlobals(expression);
495
- const draftGraph =
496
- currentId !== undefined ? buildDraftDependencyGraph(schema, currentId, expressionGlobals) : schema.graph;
497
-
498
- let changed = false;
499
- const errors = analysis.errors.map(error => {
500
- if (error.code !== RSErrorCode.globalNotTyped && error.code !== RSErrorCode.globalFuncWithoutArgs) {
501
- return error;
502
- }
503
- const missingAlias = error.params?.[0];
504
- if (!missingAlias) {
505
- return error;
506
- }
507
- const missing = schema.cstByAlias.get(missingAlias);
508
- if (!missing) {
509
- return error;
510
- }
511
- const cycleText = resolveDependencyCycleText(schema, draftGraph, currentId, missing.id);
512
- if (!cycleText) {
513
- return error;
514
- }
515
- changed = true;
516
- return {
517
- ...error,
518
- code: RSErrorCode.schemaDependencyCycle,
519
- params: [cycleText]
520
- };
521
- });
522
- return changed ? { ...analysis, errors } : analysis;
523
- }
524
-
525
- /**
526
- * Clone the schema graph and replace dependencies of `currentId` with globals from the
527
- * expression under check (unsaved draft).
528
- */
529
- function buildDraftDependencyGraph(schema: RSForm, currentId: number, expressionGlobals: ReadonlySet<string>): Graph {
530
- const graph = schema.graph.clone();
531
- const node = graph.at(currentId);
532
- if (node) {
533
- for (const parentId of [...node.inputs]) {
534
- graph.removeEdge(parentId, currentId);
535
- }
536
- } else {
537
- graph.addNode(currentId);
538
- }
539
- for (const globalAlias of expressionGlobals) {
540
- const source = schema.cstByAlias.get(globalAlias);
541
- if (source) {
542
- graph.addEdge(source.id, currentId);
543
- }
544
- }
545
- return graph;
546
- }
547
-
548
- /**
549
- * Resolve formatted cycle text for an untyped global reference in analysis.
550
- *
551
- * Uses `graph` (often a draft graph built from the expression under check). When
552
- * `currentId` is omitted, falls back to schema diagnostics on `missingId`.
553
- *
554
- * @returns Closed alias path such as `F3 → P1 → F3`, or `null` when no shared cycle exists.
555
- */
556
- function resolveDependencyCycleText(
557
- schema: RSForm,
558
- graph: Graph,
559
- currentId: number | undefined,
560
- missingId: number
561
- ): string | null {
562
- for (const cycle of graph.findCycles()) {
563
- const members = new Set(cycle);
564
- if (!members.has(missingId)) {
565
- continue;
566
- }
567
- if (currentId !== undefined && !members.has(currentId)) {
568
- continue;
569
- }
570
- return formatDependencyCycle(cycle.map(id => schema.cstByID.get(id)?.alias ?? String(id)));
571
- }
572
-
573
- if (currentId === undefined) {
574
- const cycleDiag = schema.cstByID
575
- .get(missingId)
576
- ?.diagnostics.find(item => item.code === RSDiagnosticCode.schemaDependencyCycle);
577
- return cycleDiag?.params?.[0] ?? null;
578
- }
579
-
580
- return null;
581
- }
582
-
583
- /** Calculate statistics for {@link RSForm}. */
584
- export function calculateSchemaStats(target: RSForm): RSFormStats {
585
- const items = target.items;
586
- return {
587
- count_all: items.length,
588
- count_crucial: items.reduce((sum, cst) => sum + (cst.crucial ? 1 : 0), 0),
589
-
590
- step_complexity: items.reduce((sum, cst) => sum + calculateStepComplexity(cst), 0),
591
-
592
- count_problematic: items.reduce((sum, cst) => sum + (isSchemaIssue(cst) ? 1 : 0), 0),
593
- count_homonyms: items.reduce(
594
- (sum, cst) => sum + (hasCstDiagnostic(cst, RSDiagnosticCode.schemaHomonym) ? 1 : 0),
595
- 0
596
- ),
597
- count_formal_duplicates: items.reduce(
598
- (sum, cst) => sum + (hasCstDiagnostic(cst, RSDiagnosticCode.schemaFormalDuplicate) ? 1 : 0),
599
- 0
600
- ),
601
- count_missing_convention: items.reduce((sum, cst) => sum + (isMissingConvention(cst) ? 1 : 0), 0),
602
- count_type_mismatch: items.reduce((sum, cst) => sum + (cst.is_type_mismatch ? 1 : 0), 0),
603
-
604
- count_incorrect: items.reduce((sum, cst) => sum + (cst.status === CstStatus.INCORRECT ? 1 : 0), 0),
605
- count_property: items.reduce((sum, cst) => sum + (cst.analysis?.valueClass === ValueClass.PROPERTY ? 1 : 0), 0),
606
- count_incalculable: items.reduce(
607
- (sum, cst) => sum + (cst.analysis?.success && cst.analysis.valueClass === null ? 1 : 0),
608
- 0
609
- ),
610
- count_inherited: items.reduce((sum, cst) => sum + (cst.is_inherited ? 1 : 0), 0),
611
-
612
- count_text_term: items.reduce((sum, cst) => sum + (cst.term_raw ? 1 : 0), 0),
613
- count_definition: items.reduce((sum, cst) => sum + (cst.definition_raw ? 1 : 0), 0),
614
- count_convention: items.reduce((sum, cst) => sum + (isBasicConcept(cst.cst_type) && cst.convention ? 1 : 0), 0),
615
- count_comment: items.reduce((sum, cst) => sum + (!isBasicConcept(cst.cst_type) && !cst.convention ? 1 : 0), 0),
616
-
617
- count_base: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.BASE ? 1 : 0), 0),
618
- count_constant: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.CONSTANT ? 1 : 0), 0),
619
- count_structured: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STRUCTURED ? 1 : 0), 0),
620
- count_axiom: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.AXIOM ? 1 : 0), 0),
621
- count_term: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.TERM ? 1 : 0), 0),
622
- count_function: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.FUNCTION ? 1 : 0), 0),
623
- count_predicate: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.PREDICATE ? 1 : 0), 0),
624
- count_statement: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STATEMENT ? 1 : 0), 0),
625
- count_nominal: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.NOMINAL ? 1 : 0), 0)
626
- };
627
- }
628
-
629
- /** Finds {@link Constituenta} by structure path. */
630
- export function findCstByStructure(schema: RSForm, target: Constituenta, path: TypePath): Constituenta | null {
631
- for (const cst of schema.items) {
632
- if (!cst.spawner_path) {
633
- continue;
634
- }
635
- const absolutePath = resolveAbsoluteSpawnerPath(schema, cst, target.id);
636
- if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) {
637
- return cst;
638
- }
639
- }
640
- return null;
641
- }
642
-
643
- /** Retrieves name for piece of target {@link Constituenta} structure. */
644
- export function getStructureName(schema: RSForm, target: Constituenta, path: TypePath): string {
645
- const representation = findCstByStructure(schema, target, path);
646
- if (representation) {
647
- return `${representation.alias}: ${representation.term_resolved}`;
648
- }
649
- if (!isTypification(target.effectiveType)) {
650
- return '';
651
- }
652
- const type = applyPath(target.effectiveType as Typification, path);
653
- if (type?.typeID === TypeID.basic) {
654
- const cst = schema.cstByAlias.get(type.baseID);
655
- if (cst?.term_resolved) {
656
- return `${cst.alias}: ${cst.term_resolved}`;
657
- }
658
- }
659
- return '';
660
- }
661
-
662
- // ========= Internals =====
663
- function calculateStepComplexity(cst: Constituenta): number {
664
- if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) {
665
- return 0;
666
- }
667
- if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT || !cst.effectiveType) {
668
- return 1;
669
- }
670
-
671
- const type = cst.effectiveType as Typification;
672
- return calculateTypificationComplexity(type) + 1;
673
- }
674
-
675
- function calculateTypificationComplexity(type: Typification): number {
676
- switch (type.typeID) {
677
- case TypeID.basic:
678
- case TypeID.integer:
679
- case TypeID.anyTypification:
680
- return 0;
681
- case TypeID.tuple:
682
- return (
683
- type.factors.length + type.factors.reduce((sum, factor) => sum + calculateTypificationComplexity(factor), 0)
684
- );
685
- case TypeID.collection:
686
- if (type.base.typeID === TypeID.tuple) {
687
- let sum = 0;
688
- type.base.factors.forEach(factor => {
689
- sum += calculateTypificationComplexity(factor);
690
- });
691
- return sum + type.base.factors.length;
692
- } else if (type.base.typeID === TypeID.collection) {
693
- return calculateTypificationComplexity(type.base) + 1;
694
- }
695
- return 0;
696
- }
697
- }
698
-
699
- function isMissingConvention(cst: Constituenta): boolean {
700
- if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {
701
- if (!cst.convention || !cst.term_resolved) {
702
- return true;
703
- }
704
- }
705
- return false;
706
- }
707
-
708
- function resolveAbsoluteSpawnerPath(schema: RSForm, cst: Constituenta, targetId: number): TypePath | null {
709
- if (!cst.spawner_path || cst.spawner == null) {
710
- return null;
711
- }
712
- if (cst.spawner === targetId) {
713
- return cst.spawner_path;
714
- }
715
-
716
- const byId = schema.cstByID ?? new Map(schema.items.map(item => [item.id, item]));
717
- const visited = new Set<number>([cst.id]);
718
- let currentPath: number[] = [...cst.spawner_path];
719
- let currentSpawnerId: number | null = cst.spawner;
720
-
721
- while (currentSpawnerId != null) {
722
- if (currentSpawnerId === targetId) {
723
- return currentPath as TypePath;
724
- }
725
- if (visited.has(currentSpawnerId)) {
726
- return null;
727
- }
728
- visited.add(currentSpawnerId);
729
-
730
- const parent = byId.get(currentSpawnerId);
731
- if (!parent?.spawner_path || parent.spawner == null) {
732
- return null;
733
- }
734
-
735
- currentPath = [...parent.spawner_path, ...currentPath];
736
- currentSpawnerId = parent.spawner;
737
- }
738
-
739
- return null;
740
- }
741
-
742
- /** Evaluate if {@link Typification} can be used to produce structure. */
743
- function typeCanProduceStructure(type: Typification): boolean {
744
- if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) {
745
- return false;
746
- } else if (type.typeID === TypeID.tuple) {
747
- return true;
748
- } else {
749
- return (
750
- type.base.typeID !== TypeID.basic &&
751
- type.base.typeID !== TypeID.integer &&
752
- type.base.typeID !== TypeID.anyTypification
753
- );
754
- }
755
- }