@rsconcept/domain 1.7.2 → 1.7.4
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/cctext/language-api.d.ts +3 -1
- package/dist/cctext/language-api.js +20 -1
- package/dist/cctext/language-api.js.map +1 -1
- package/dist/expression-generator-CoucLIkE.d.ts +10 -0
- package/dist/library/rsform-api.d.ts +15 -1
- package/dist/library/rsform-api.js +16 -1
- package/dist/library/rsform-api.js.map +1 -1
- package/dist/library/structure-planner.js +1 -1
- package/dist/rslang/api.d.ts +1 -1
- package/dist/rslang/parser/expression-generator.d.ts +2 -10
- package/package.json +1 -1
- package/src/cctext/language-api.test.ts +16 -0
- package/src/cctext/language-api.ts +23 -0
- package/src/library/rsform-api.test.ts +39 -1
- package/src/library/rsform-api.ts +31 -0
|
@@ -30,6 +30,8 @@ declare function parseEntityReference(text: string): EntityReference;
|
|
|
30
30
|
declare function parseSyntacticReference(text: string): SyntacticReference;
|
|
31
31
|
/** Extracts a validated reference from string representation. */
|
|
32
32
|
declare function parseReference(text: string): IReference | null;
|
|
33
|
+
/** Apply alias mapping to entity references in terminological text. */
|
|
34
|
+
declare function applyEntityReferenceMapping(text: string, mapping: Record<string, string>): string;
|
|
33
35
|
/** Extracts unique entity aliases referenced by text. */
|
|
34
36
|
declare function extractEntities(text: string): string[];
|
|
35
37
|
/** Resolves text references using nominal terms and optional manually edited forms. */
|
|
@@ -37,5 +39,5 @@ declare function resolveTextReferences(text: string, context: TermContext): stri
|
|
|
37
39
|
/** Transforms {@link IReference} to string representation. */
|
|
38
40
|
declare function referenceToString(ref: IReference): string;
|
|
39
41
|
//#endregion
|
|
40
|
-
export { Lexeme, extractEntities, generateNominalLexeme, parseEntityReference, parseGrammemes, parseReference, parseSyntacticReference, referenceToString, resolveTextReferences, wordFormEquals };
|
|
42
|
+
export { Lexeme, applyEntityReferenceMapping, extractEntities, generateNominalLexeme, parseEntityReference, parseGrammemes, parseReference, parseSyntacticReference, referenceToString, resolveTextReferences, wordFormEquals };
|
|
41
43
|
//# sourceMappingURL=language-api.d.ts.map
|
|
@@ -71,6 +71,25 @@ function parseReference(text) {
|
|
|
71
71
|
}
|
|
72
72
|
};
|
|
73
73
|
}
|
|
74
|
+
/** Apply alias mapping to entity references in terminological text. */
|
|
75
|
+
function applyEntityReferenceMapping(text, mapping) {
|
|
76
|
+
if (text === "" || Object.keys(mapping).length === 0) return text;
|
|
77
|
+
let posInput = 0;
|
|
78
|
+
let output = "";
|
|
79
|
+
for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {
|
|
80
|
+
const entity = segment[1];
|
|
81
|
+
const entityKey = entity.trim();
|
|
82
|
+
const start = segment.index ?? 0;
|
|
83
|
+
if (entityKey in mapping) {
|
|
84
|
+
output += text.substring(posInput, start + 2);
|
|
85
|
+
output += mapping[entityKey];
|
|
86
|
+
output += text.substring(start + 2 + entity.length, start + segment[0].length);
|
|
87
|
+
posInput = start + segment[0].length;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
output += text.substring(posInput);
|
|
91
|
+
return output;
|
|
92
|
+
}
|
|
74
93
|
/** Extracts unique entity aliases referenced by text. */
|
|
75
94
|
function extractEntities(text) {
|
|
76
95
|
const result = [];
|
|
@@ -177,6 +196,6 @@ function findSyntacticMaster(offset, index, references) {
|
|
|
177
196
|
}
|
|
178
197
|
}
|
|
179
198
|
//#endregion
|
|
180
|
-
export { extractEntities, generateNominalLexeme, parseEntityReference, parseGrammemes, parseReference, parseSyntacticReference, referenceToString, resolveTextReferences, wordFormEquals };
|
|
199
|
+
export { applyEntityReferenceMapping, extractEntities, generateNominalLexeme, parseEntityReference, parseGrammemes, parseReference, parseSyntacticReference, referenceToString, resolveTextReferences, wordFormEquals };
|
|
181
200
|
|
|
182
201
|
//# sourceMappingURL=language-api.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"language-api.js","names":[],"sources":["../../src/cctext/language-api.ts"],"sourcesContent":["/**\n * Module: Natural language model API.\n */\n\nimport {\n Case,\n type EntityReference,\n Grammeme,\n type IReference,\n Plurality,\n ReferenceType,\n type SyntacticReference,\n type TermContext,\n type TermContextItem,\n type WordForm\n} from './language';\n\ninterface Position {\n from: number;\n to: number;\n}\n\ninterface ResolvedReference {\n ref: IReference;\n resolved: string;\n posInput: Position;\n}\n\nconst REFERENCE_PATTERN = /@{[^{}]*?}/g;\nconst ENTITY_REFERENCE_PATTERN = /@{([^0-9\\-][^}|{]*?)\\|([^}|{]*?)}/g;\n\n/** Represents generated lexeme forms. */\nexport interface Lexeme {\n items: { text: string; grams: string }[];\n}\n\n/** Equality comparator for {@link WordForm}. Compares a set of Grammemes attached to wordforms. */\nexport function wordFormEquals(left: WordForm, right: WordForm): boolean {\n if (left.grams.length !== right.grams.length) {\n return false;\n }\n for (let index = 0; index < left.grams.length; ++index) {\n if (left.grams[index] !== right.grams[index]) {\n return false;\n }\n }\n return true;\n}\n\n/** Transforms {@link Grammeme} enumeration to {@link Grammeme}. */\nexport function parseGrammemes(termForm: string): Grammeme[] {\n const result: Grammeme[] = [];\n for (const chunk of termForm.split(',')) {\n const gram = chunk.trim();\n if (gram !== '') {\n result.push(gram as Grammeme);\n }\n }\n return result.sort(grammemeCompare);\n}\n\n/** Generates all supported noun forms using nominal text for every form. */\nexport function generateNominalLexeme(data: { text: string }): Lexeme {\n return {\n items: Plurality.flatMap(plurality =>\n Case.map(gramCase => ({\n text: data.text,\n grams: `${plurality},${gramCase}`\n }))\n )\n };\n}\n\n/**\n * Extracts {@link EntityReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{GLOBAL_ID|GRAMMEMES\\}'\n */\nexport function parseEntityReference(text: string): EntityReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.ENTITY) {\n throw new Error(`Invalid entity reference: ${text}`);\n }\n return ref.data as EntityReference;\n}\n\n/**\n * Extracts {@link SyntacticReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{OFFSET|NOMINAL_FORM\\}'\n */\nexport function parseSyntacticReference(text: string): SyntacticReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.SYNTACTIC) {\n throw new Error(`Invalid syntactic reference: ${text}`);\n }\n return ref.data as SyntacticReference;\n}\n\n/** Extracts a validated reference from string representation. */\nexport function parseReference(text: string): IReference | null {\n if (text.length < 4 || !text.startsWith('@{') || !text.endsWith('}')) {\n return null;\n }\n\n const blocks = text\n .slice(2, text.length - 1)\n .split('|')\n .map(block => block.trim());\n if (blocks.length !== 2 || blocks[0] === '' || blocks[0].startsWith('0')) {\n return null;\n }\n\n if (blocks[0].startsWith('-') || /^[1-9]/.test(blocks[0])) {\n const offset = Number(blocks[0]);\n if (!Number.isInteger(offset) || offset === 0 || blocks[1] === '') {\n return null;\n }\n return {\n type: ReferenceType.SYNTACTIC,\n data: { offset, nominal: blocks[1] }\n };\n }\n\n return {\n type: ReferenceType.ENTITY,\n data: { entity: blocks[0], tags: parseGrammemes(blocks[1].replaceAll(' ', '')) }\n };\n}\n\n/** Extracts unique entity aliases referenced by text. */\nexport function extractEntities(text: string): string[] {\n const result: string[] = [];\n for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {\n const entity = segment[1].trim();\n if (!result.includes(entity)) {\n result.push(entity);\n }\n }\n return result;\n}\n\n/** Resolves text references using nominal terms and optional manually edited forms. */\nexport function resolveTextReferences(text: string, context: TermContext): string {\n const references = parseReferences(text);\n if (references.length === 0) {\n return text;\n }\n\n for (const ref of references) {\n if (ref.ref.type === ReferenceType.ENTITY) {\n ref.resolved = resolveEntity(ref.ref.data as EntityReference, context);\n }\n }\n references.forEach((ref, index) => {\n if (ref.ref.type === ReferenceType.SYNTACTIC) {\n ref.resolved = resolveSyntactic(ref.ref.data as SyntacticReference, index, references);\n }\n });\n\n let posInput = 0;\n let output = '';\n for (const ref of references) {\n output += text.substring(posInput, ref.posInput.from);\n output += ref.resolved;\n posInput = ref.posInput.to;\n }\n output += text.substring(posInput);\n return output;\n}\n\n/** Transforms {@link IReference} to string representation. */\nexport function referenceToString(ref: IReference): string {\n switch (ref.type) {\n case ReferenceType.ENTITY: {\n const entity = ref.data as EntityReference;\n return `@{${entity.entity}|${entity.tags.join(',')}}`;\n }\n case ReferenceType.SYNTACTIC: {\n const syntactic = ref.data as SyntacticReference;\n return `@{${syntactic.offset}|${syntactic.nominal}}`;\n }\n }\n}\n\n// ===== Internals =======\n\n/** Compares {@link Grammeme} based on Grammeme enum and alpha order for strings. */\nfunction grammemeCompare(left: Grammeme, right: Grammeme): number {\n const indexLeft = Object.values(Grammeme).findIndex(gram => gram === left);\n const indexRight = Object.values(Grammeme).findIndex(gram => gram === right);\n if (indexLeft === -1 && indexRight === -1) {\n return left.localeCompare(right);\n } else if (indexLeft === -1 && indexRight !== -1) {\n return 1;\n } else if (indexLeft !== -1 && indexRight === -1) {\n return -1;\n } else {\n return indexLeft - indexRight;\n }\n}\n\nfunction parseReferences(text: string): ResolvedReference[] {\n const result: ResolvedReference[] = [];\n for (const segment of text.matchAll(REFERENCE_PATTERN)) {\n const ref = parseReference(segment[0]);\n if (ref) {\n result.push({\n ref,\n resolved: '',\n posInput: { from: segment.index ?? 0, to: (segment.index ?? 0) + segment[0].length }\n });\n }\n }\n return result;\n}\n\nfunction resolveEntity(ref: EntityReference, context: TermContext): string {\n const entity = context[ref.entity];\n if (!entity) {\n return `!Неизвестная сущность: ${ref.entity}!`;\n }\n\n const resolved = getEntityForm(entity, ref.tags);\n return resolved === '' ? `!Отсутствует термин: ${ref.entity}!` : resolved;\n}\n\nfunction getEntityForm(entity: TermContextItem, grams: Grammeme[]): string {\n if (grams.length === 0) {\n return entity.nominal;\n }\n\n const manual = entity.forms?.find(form => matchGrams(grams, form.grams));\n return manual?.text ?? entity.nominal;\n}\n\nfunction matchGrams(query: Grammeme[], candidate: Grammeme[]): boolean {\n for (const gram of candidate) {\n if (!query.includes(gram)) {\n return false;\n }\n }\n return true;\n}\n\nfunction resolveSyntactic(ref: SyntacticReference, index: number, references: ResolvedReference[]): string {\n const master = findSyntacticMaster(ref.offset, index, references);\n if (!master) {\n return `!Некорректное смещение: ${ref.offset}!`;\n }\n return ref.nominal;\n}\n\nfunction findSyntacticMaster(\n offset: number,\n index: number,\n references: ResolvedReference[]\n): ResolvedReference | undefined {\n if (offset > 0) {\n let position = index + 1;\n let left = offset;\n while (position < references.length) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === 1) {\n return references[position];\n }\n left -= 1;\n }\n position += 1;\n }\n } else {\n let position = index - 1;\n let left = offset;\n while (position >= 0) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === -1) {\n return references[position];\n }\n left += 1;\n }\n position -= 1;\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;AA4BA,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B;;AAQjC,SAAgB,eAAe,MAAgB,OAA0B;CACvE,IAAI,KAAK,MAAM,WAAW,MAAM,MAAM,QACpC,OAAO;CAET,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,MAAM,QAAQ,EAAE,OAC/C,IAAI,KAAK,MAAM,WAAW,MAAM,MAAM,QACpC,OAAO;CAGX,OAAO;AACT;;AAGA,SAAgB,eAAe,UAA8B;CAC3D,MAAM,SAAqB,CAAC;CAC5B,KAAK,MAAM,SAAS,SAAS,MAAM,GAAG,GAAG;EACvC,MAAM,OAAO,MAAM,KAAK;EACxB,IAAI,SAAS,IACX,OAAO,KAAK,IAAgB;CAEhC;CACA,OAAO,OAAO,KAAK,eAAe;AACpC;;AAGA,SAAgB,sBAAsB,MAAgC;CACpE,OAAO,EACL,OAAO,UAAU,SAAQ,cACvB,KAAK,KAAI,cAAa;EACpB,MAAM,KAAK;EACX,OAAO,GAAG,UAAU,GAAG;CACzB,EAAE,CACJ,EACF;AACF;;;;;;AAOA,SAAgB,qBAAqB,MAA+B;CAClE,MAAM,MAAM,eAAe,IAAI;CAC/B,IAAI,KAAK,SAAS,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AAI,OAAO;EACX,OAAO,YAAY,GAAG;GACpB,IAAI,WAAW,SAAS,CAAC,IAAI,SAAS,cAAc,QAAQ;IAC1D,IAAI,SAAS,IACX,OAAO,WAAW;IAEpB,QAAQ;GACV;GACA,YAAY;EACd;CACF;AAEF"}
|
|
1
|
+
{"version":3,"file":"language-api.js","names":[],"sources":["../../src/cctext/language-api.ts"],"sourcesContent":["/**\n * Module: Natural language model API.\n */\n\nimport {\n Case,\n type EntityReference,\n Grammeme,\n type IReference,\n Plurality,\n ReferenceType,\n type SyntacticReference,\n type TermContext,\n type TermContextItem,\n type WordForm\n} from './language';\n\ninterface Position {\n from: number;\n to: number;\n}\n\ninterface ResolvedReference {\n ref: IReference;\n resolved: string;\n posInput: Position;\n}\n\nconst REFERENCE_PATTERN = /@{[^{}]*?}/g;\nconst ENTITY_REFERENCE_PATTERN = /@{([^0-9\\-][^}|{]*?)\\|([^}|{]*?)}/g;\n\n/** Represents generated lexeme forms. */\nexport interface Lexeme {\n items: { text: string; grams: string }[];\n}\n\n/** Equality comparator for {@link WordForm}. Compares a set of Grammemes attached to wordforms. */\nexport function wordFormEquals(left: WordForm, right: WordForm): boolean {\n if (left.grams.length !== right.grams.length) {\n return false;\n }\n for (let index = 0; index < left.grams.length; ++index) {\n if (left.grams[index] !== right.grams[index]) {\n return false;\n }\n }\n return true;\n}\n\n/** Transforms {@link Grammeme} enumeration to {@link Grammeme}. */\nexport function parseGrammemes(termForm: string): Grammeme[] {\n const result: Grammeme[] = [];\n for (const chunk of termForm.split(',')) {\n const gram = chunk.trim();\n if (gram !== '') {\n result.push(gram as Grammeme);\n }\n }\n return result.sort(grammemeCompare);\n}\n\n/** Generates all supported noun forms using nominal text for every form. */\nexport function generateNominalLexeme(data: { text: string }): Lexeme {\n return {\n items: Plurality.flatMap(plurality =>\n Case.map(gramCase => ({\n text: data.text,\n grams: `${plurality},${gramCase}`\n }))\n )\n };\n}\n\n/**\n * Extracts {@link EntityReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{GLOBAL_ID|GRAMMEMES\\}'\n */\nexport function parseEntityReference(text: string): EntityReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.ENTITY) {\n throw new Error(`Invalid entity reference: ${text}`);\n }\n return ref.data as EntityReference;\n}\n\n/**\n * Extracts {@link SyntacticReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{OFFSET|NOMINAL_FORM\\}'\n */\nexport function parseSyntacticReference(text: string): SyntacticReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.SYNTACTIC) {\n throw new Error(`Invalid syntactic reference: ${text}`);\n }\n return ref.data as SyntacticReference;\n}\n\n/** Extracts a validated reference from string representation. */\nexport function parseReference(text: string): IReference | null {\n if (text.length < 4 || !text.startsWith('@{') || !text.endsWith('}')) {\n return null;\n }\n\n const blocks = text\n .slice(2, text.length - 1)\n .split('|')\n .map(block => block.trim());\n if (blocks.length !== 2 || blocks[0] === '' || blocks[0].startsWith('0')) {\n return null;\n }\n\n if (blocks[0].startsWith('-') || /^[1-9]/.test(blocks[0])) {\n const offset = Number(blocks[0]);\n if (!Number.isInteger(offset) || offset === 0 || blocks[1] === '') {\n return null;\n }\n return {\n type: ReferenceType.SYNTACTIC,\n data: { offset, nominal: blocks[1] }\n };\n }\n\n return {\n type: ReferenceType.ENTITY,\n data: { entity: blocks[0], tags: parseGrammemes(blocks[1].replaceAll(' ', '')) }\n };\n}\n\n/** Apply alias mapping to entity references in terminological text. */\nexport function applyEntityReferenceMapping(text: string, mapping: Record<string, string>): string {\n if (text === '' || Object.keys(mapping).length === 0) {\n return text;\n }\n\n let posInput = 0;\n let output = '';\n for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {\n const entity = segment[1];\n const entityKey = entity.trim();\n const start = segment.index ?? 0;\n if (entityKey in mapping) {\n output += text.substring(posInput, start + 2);\n output += mapping[entityKey];\n output += text.substring(start + 2 + entity.length, start + segment[0].length);\n posInput = start + segment[0].length;\n }\n }\n output += text.substring(posInput);\n return output;\n}\n\n/** Extracts unique entity aliases referenced by text. */\nexport function extractEntities(text: string): string[] {\n const result: string[] = [];\n for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {\n const entity = segment[1].trim();\n if (!result.includes(entity)) {\n result.push(entity);\n }\n }\n return result;\n}\n\n/** Resolves text references using nominal terms and optional manually edited forms. */\nexport function resolveTextReferences(text: string, context: TermContext): string {\n const references = parseReferences(text);\n if (references.length === 0) {\n return text;\n }\n\n for (const ref of references) {\n if (ref.ref.type === ReferenceType.ENTITY) {\n ref.resolved = resolveEntity(ref.ref.data as EntityReference, context);\n }\n }\n references.forEach((ref, index) => {\n if (ref.ref.type === ReferenceType.SYNTACTIC) {\n ref.resolved = resolveSyntactic(ref.ref.data as SyntacticReference, index, references);\n }\n });\n\n let posInput = 0;\n let output = '';\n for (const ref of references) {\n output += text.substring(posInput, ref.posInput.from);\n output += ref.resolved;\n posInput = ref.posInput.to;\n }\n output += text.substring(posInput);\n return output;\n}\n\n/** Transforms {@link IReference} to string representation. */\nexport function referenceToString(ref: IReference): string {\n switch (ref.type) {\n case ReferenceType.ENTITY: {\n const entity = ref.data as EntityReference;\n return `@{${entity.entity}|${entity.tags.join(',')}}`;\n }\n case ReferenceType.SYNTACTIC: {\n const syntactic = ref.data as SyntacticReference;\n return `@{${syntactic.offset}|${syntactic.nominal}}`;\n }\n }\n}\n\n// ===== Internals =======\n\n/** Compares {@link Grammeme} based on Grammeme enum and alpha order for strings. */\nfunction grammemeCompare(left: Grammeme, right: Grammeme): number {\n const indexLeft = Object.values(Grammeme).findIndex(gram => gram === left);\n const indexRight = Object.values(Grammeme).findIndex(gram => gram === right);\n if (indexLeft === -1 && indexRight === -1) {\n return left.localeCompare(right);\n } else if (indexLeft === -1 && indexRight !== -1) {\n return 1;\n } else if (indexLeft !== -1 && indexRight === -1) {\n return -1;\n } else {\n return indexLeft - indexRight;\n }\n}\n\nfunction parseReferences(text: string): ResolvedReference[] {\n const result: ResolvedReference[] = [];\n for (const segment of text.matchAll(REFERENCE_PATTERN)) {\n const ref = parseReference(segment[0]);\n if (ref) {\n result.push({\n ref,\n resolved: '',\n posInput: { from: segment.index ?? 0, to: (segment.index ?? 0) + segment[0].length }\n });\n }\n }\n return result;\n}\n\nfunction resolveEntity(ref: EntityReference, context: TermContext): string {\n const entity = context[ref.entity];\n if (!entity) {\n return `!Неизвестная сущность: ${ref.entity}!`;\n }\n\n const resolved = getEntityForm(entity, ref.tags);\n return resolved === '' ? `!Отсутствует термин: ${ref.entity}!` : resolved;\n}\n\nfunction getEntityForm(entity: TermContextItem, grams: Grammeme[]): string {\n if (grams.length === 0) {\n return entity.nominal;\n }\n\n const manual = entity.forms?.find(form => matchGrams(grams, form.grams));\n return manual?.text ?? entity.nominal;\n}\n\nfunction matchGrams(query: Grammeme[], candidate: Grammeme[]): boolean {\n for (const gram of candidate) {\n if (!query.includes(gram)) {\n return false;\n }\n }\n return true;\n}\n\nfunction resolveSyntactic(ref: SyntacticReference, index: number, references: ResolvedReference[]): string {\n const master = findSyntacticMaster(ref.offset, index, references);\n if (!master) {\n return `!Некорректное смещение: ${ref.offset}!`;\n }\n return ref.nominal;\n}\n\nfunction findSyntacticMaster(\n offset: number,\n index: number,\n references: ResolvedReference[]\n): ResolvedReference | undefined {\n if (offset > 0) {\n let position = index + 1;\n let left = offset;\n while (position < references.length) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === 1) {\n return references[position];\n }\n left -= 1;\n }\n position += 1;\n }\n } else {\n let position = index - 1;\n let left = offset;\n while (position >= 0) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === -1) {\n return references[position];\n }\n left += 1;\n }\n position -= 1;\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;AA4BA,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B;;AAQjC,SAAgB,eAAe,MAAgB,OAA0B;CACvE,IAAI,KAAK,MAAM,WAAW,MAAM,MAAM,QACpC,OAA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SAAS,cAAc,QAAQ;IAC1D,IAAI,SAAS,IACX,OAAO,WAAW;IAEpB,QAAQ;GACV;GACA,YAAY;EACd;CACF;AAEF"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { t as AstNode } from "./ast-C8sIpKdL.js";
|
|
2
|
+
//#region src/rslang/parser/expression-generator.d.ts
|
|
3
|
+
interface ExpressionGeneratorOptions {
|
|
4
|
+
normalize?: boolean;
|
|
5
|
+
}
|
|
6
|
+
/** Generates Math-syntax RS expression from AST, with optional identifier normalization. */
|
|
7
|
+
declare function generateExpressionFromAst(ast: AstNode, options?: ExpressionGeneratorOptions): string;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { generateExpressionFromAst as t };
|
|
10
|
+
//# sourceMappingURL=expression-generator-CoucLIkE.d.ts.map
|
|
@@ -3,6 +3,7 @@ import { g as TypeClass, y as TypePath } from "../typification-Dk-fisgO.js";
|
|
|
3
3
|
import { t as ValueClass } from "../value-class-CNI-lqXJ.js";
|
|
4
4
|
import { r as AnalysisFull } from "../analyzer-QxWs73gP.js";
|
|
5
5
|
import { ArgumentValue, Constituenta, CstClass, CstStatus, CstType, RSForm, RSFormStats } from "./rsform.js";
|
|
6
|
+
import { AliasMapping } from "../rslang/api.js";
|
|
6
7
|
|
|
7
8
|
//#region src/library/rsform-api.d.ts
|
|
8
9
|
/** Checks if {@link Constituenta} is a schema issue. */
|
|
@@ -48,6 +49,19 @@ declare function generateAlias(type: CstType, schema: RSForm, takenAliases?: str
|
|
|
48
49
|
declare function inferNewSpawnPosition(schema: RSForm, targetId: number): number;
|
|
49
50
|
/** Sorts library items relevant for InlineSynthesis with specified {@link RSForm}. */
|
|
50
51
|
declare function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly LibraryItem[]): LibraryItem[];
|
|
52
|
+
/** Fields of {@link Constituenta} updated in place by alias mapping. */
|
|
53
|
+
interface ConstituentaMappableFields {
|
|
54
|
+
alias: string;
|
|
55
|
+
definition_formal: string;
|
|
56
|
+
typification_manual: string;
|
|
57
|
+
term_raw: string;
|
|
58
|
+
definition_raw: string;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Remap formal expressions and terminological entity references in constituent fields.
|
|
62
|
+
* Mutates each element of `items` in place; pass owned or cloned data only.
|
|
63
|
+
*/
|
|
64
|
+
declare function applyMappingToConstituents<T extends ConstituentaMappableFields>(items: T[], mapping: AliasMapping, changeAliases: boolean): void;
|
|
51
65
|
/** Remove alias from expression. */
|
|
52
66
|
declare function removeAliasReference(expression: string, alias: string): string;
|
|
53
67
|
/** Add alias to expression. */
|
|
@@ -65,5 +79,5 @@ declare function findCstByStructure(schema: RSForm, target: Constituenta, path:
|
|
|
65
79
|
/** Retrieves name for piece of target {@link Constituenta} structure. */
|
|
66
80
|
declare function getStructureName(schema: RSForm, target: Constituenta, path: TypePath): string;
|
|
67
81
|
//#endregion
|
|
68
|
-
export { addAliasReference, applyFilterCategory, calculateSchemaStats, canHaveFormalDefinition, canHaveManualTypification, canProduceStructure, findCstByStructure, generateAlias, getAnalysisFor, getCstTypePrefix, getStructureName, guessCstType, inferClass, inferNewSpawnPosition, inferStatus, inferTemplate, inferTemplatedType, isBaseSet, isBasicConcept, isFunctional, isLogical, isSchemaIssue, isTemplateCst, removeAliasReference, sortItemsForInlineSynthesis, typeClassForCstType, validateAliasFormat, validateNewAlias };
|
|
82
|
+
export { ConstituentaMappableFields, addAliasReference, applyFilterCategory, applyMappingToConstituents, calculateSchemaStats, canHaveFormalDefinition, canHaveManualTypification, canProduceStructure, findCstByStructure, generateAlias, getAnalysisFor, getCstTypePrefix, getStructureName, guessCstType, inferClass, inferNewSpawnPosition, inferStatus, inferTemplate, inferTemplatedType, isBaseSet, isBasicConcept, isFunctional, isLogical, isSchemaIssue, isTemplateCst, removeAliasReference, sortItemsForInlineSynthesis, typeClassForCstType, validateAliasFormat, validateNewAlias };
|
|
69
83
|
//# sourceMappingURL=rsform-api.d.ts.map
|
|
@@ -4,6 +4,8 @@ import { applyPath } from "../rslang/semantic/typification-api.js";
|
|
|
4
4
|
import { ValueClass } from "../rslang/semantic/value-class.js";
|
|
5
5
|
import "../rslang/index.js";
|
|
6
6
|
import { CstClass, CstStatus, CstType } from "./rsform.js";
|
|
7
|
+
import { applyEntityReferenceMapping } from "../cctext/language-api.js";
|
|
8
|
+
import { applyAliasMapping, applyTypificationMapping } from "../rslang/api.js";
|
|
7
9
|
//#region src/library/rsform-api.ts
|
|
8
10
|
/**
|
|
9
11
|
* Module: API for formal representation for systems of concepts.
|
|
@@ -219,6 +221,19 @@ function sortItemsForInlineSynthesis(receiver, items) {
|
|
|
219
221
|
for (const item of items) if (!result.includes(item)) result.push(item);
|
|
220
222
|
return result;
|
|
221
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Remap formal expressions and terminological entity references in constituent fields.
|
|
226
|
+
* Mutates each element of `items` in place; pass owned or cloned data only.
|
|
227
|
+
*/
|
|
228
|
+
function applyMappingToConstituents(items, mapping, changeAliases) {
|
|
229
|
+
for (const cst of items) {
|
|
230
|
+
if (changeAliases && cst.alias in mapping) cst.alias = mapping[cst.alias];
|
|
231
|
+
cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);
|
|
232
|
+
cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);
|
|
233
|
+
cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);
|
|
234
|
+
cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
222
237
|
/** Remove alias from expression. */
|
|
223
238
|
function removeAliasReference(expression, alias) {
|
|
224
239
|
const result = expression.replaceAll(new RegExp(`\\b${alias}\\b`, "g"), "DEL");
|
|
@@ -363,6 +378,6 @@ function typeCanProduceStructure(type) {
|
|
|
363
378
|
else return type.base.typeID !== TypeID.basic && type.base.typeID !== TypeID.integer && type.base.typeID !== TypeID.anyTypification;
|
|
364
379
|
}
|
|
365
380
|
//#endregion
|
|
366
|
-
export { addAliasReference, applyFilterCategory, calculateSchemaStats, canHaveFormalDefinition, canHaveManualTypification, canProduceStructure, findCstByStructure, generateAlias, getAnalysisFor, getCstTypePrefix, getStructureName, guessCstType, inferClass, inferNewSpawnPosition, inferStatus, inferTemplate, inferTemplatedType, isBaseSet, isBasicConcept, isFunctional, isLogical, isSchemaIssue, isTemplateCst, removeAliasReference, sortItemsForInlineSynthesis, typeClassForCstType, validateAliasFormat, validateNewAlias };
|
|
381
|
+
export { addAliasReference, applyFilterCategory, applyMappingToConstituents, calculateSchemaStats, canHaveFormalDefinition, canHaveManualTypification, canProduceStructure, findCstByStructure, generateAlias, getAnalysisFor, getCstTypePrefix, getStructureName, guessCstType, inferClass, inferNewSpawnPosition, inferStatus, inferTemplate, inferTemplatedType, isBaseSet, isBasicConcept, isFunctional, isLogical, isSchemaIssue, isTemplateCst, removeAliasReference, sortItemsForInlineSynthesis, typeClassForCstType, validateAliasFormat, validateNewAlias };
|
|
367
382
|
|
|
368
383
|
//# sourceMappingURL=rsform-api.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsform-api.js","names":[],"sources":["../../src/library/rsform-api.ts"],"sourcesContent":["/**\n * Module: API for formal representation for systems of concepts.\n */\n\nimport {\n type AnalysisFull,\n RSErrorCode,\n TypeClass,\n TypeID,\n type TypePath,\n type Typification,\n ValueClass\n} from '../rslang';\nimport { basic, bool, constant, type EchelonFunctional, isTypification } from '../rslang/semantic/typification';\nimport { applyPath } from '../rslang/semantic/typification-api';\n\nimport { type LibraryItem } from './library';\nimport {\n type ArgumentValue,\n type Constituenta,\n CstClass,\n CstStatus,\n CstType,\n type RSForm,\n type RSFormStats\n} from './rsform';\n\n/** Record of {@link CstType} prefixes. */\nconst CST_TYPE_PREFIX: Record<CstType, string> = {\n [CstType.NOMINAL]: 'N',\n [CstType.BASE]: 'X',\n [CstType.CONSTANT]: 'C',\n [CstType.STRUCTURED]: 'S',\n [CstType.AXIOM]: 'A',\n [CstType.TERM]: 'D',\n [CstType.FUNCTION]: 'F',\n [CstType.PREDICATE]: 'P',\n [CstType.STATEMENT]: 'T'\n};\n\n/** Record of {@link CstType} to {@link CstClass} mapping. */\nconst CST_TYPE_TO_CLASS: Record<CstType, CstClass> = {\n [CstType.NOMINAL]: CstClass.NOMINAL,\n [CstType.BASE]: CstClass.BASIC,\n [CstType.CONSTANT]: CstClass.BASIC,\n [CstType.STRUCTURED]: CstClass.BASIC,\n [CstType.TERM]: CstClass.DERIVED,\n [CstType.FUNCTION]: CstClass.DERIVED,\n [CstType.AXIOM]: CstClass.STATEMENT,\n [CstType.PREDICATE]: CstClass.DERIVED,\n [CstType.STATEMENT]: CstClass.STATEMENT\n};\n\n/** Checks if {@link Constituenta} is a schema issue. */\nexport function isSchemaIssue(cst: Constituenta): boolean {\n if (\n cst.homonyms.length > 0 ||\n cst.formalDuplicates.length > 0 ||\n cst.status === CstStatus.INCORRECT ||\n cst.status === CstStatus.INCALCULABLE ||\n cst.is_type_mismatch\n ) {\n return true;\n }\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention || !cst.term_resolved) {\n return true;\n }\n }\n return false;\n}\n\n/** Infers the status of an expression based on parsing and value information. */\nexport function inferStatus(parse: boolean, value?: ValueClass | null): CstStatus {\n if (!parse) {\n return CstStatus.INCORRECT;\n }\n if (value === null) {\n return CstStatus.INCALCULABLE;\n }\n if (value === ValueClass.PROPERTY) {\n return CstStatus.PROPERTY;\n }\n return CstStatus.VERIFIED;\n}\n\n/** Infers type of constituent for a given template and arguments. */\nexport function inferTemplatedType(templateType: CstType, args: ArgumentValue[]): CstType {\n if (args.length === 0 || args.some(arg => !arg.value)) {\n return templateType;\n } else if (templateType === CstType.PREDICATE) {\n return CstType.AXIOM;\n } else {\n return CstType.TERM;\n }\n}\n\n/** Checks if given expression is a template. */\nexport function inferTemplate(expression: string): boolean {\n const match = expression.match(/R\\d+/g);\n return (match && match?.length > 0) ?? false;\n}\n\n/** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */\nexport function inferClass(type: CstType, isTemplate: boolean = false): CstClass {\n if (isTemplate) {\n return CstClass.TEMPLATE;\n }\n return CST_TYPE_TO_CLASS[type];\n}\n\n/** Check if {@link Constituenta} is a template or a category. */\nexport function isTemplateCst(cst: Constituenta): boolean {\n return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;\n}\n\n/** Apply filter based on start {@link Constituenta} type. */\nexport function applyFilterCategory(start: Constituenta, items: Constituenta[]): Constituenta[] {\n const startIndex = items.indexOf(start);\n if (startIndex === -1) {\n return [];\n }\n const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);\n\n return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));\n}\n\n/** Prefix for alias indicating {@link CstType}. */\nexport function getCstTypePrefix(type: CstType): string {\n return CST_TYPE_PREFIX[type];\n}\n\n/** Guess {@link CstType} from user input hint. */\nexport function guessCstType(hint: string): CstType | null {\n if (hint.length !== 1) {\n return null;\n }\n for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) {\n if (hint === prefix) {\n return type as CstType;\n }\n }\n return null;\n}\n\n/** Evaluate if {@link CstType} is basic concept. */\nexport function isBasicConcept(type: CstType): boolean {\n switch (type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n return true;\n\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is base set or constant set. */\nexport function isBaseSet(type: CstType): boolean {\n switch (type) {\n case CstType.BASE:\n case CstType.CONSTANT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is a function. */\nexport function isFunctional(type: CstType): boolean {\n switch (type) {\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is logical. */\nexport function isLogical(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link Constituenta} can be used produce structure. */\nexport function canProduceStructure(cst: Constituenta): boolean {\n switch (cst.cst_type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.PREDICATE:\n return false;\n }\n if (!cst.effectiveType) {\n return false;\n }\n if (cst.cst_type === CstType.FUNCTION) {\n const result = (cst.effectiveType as EchelonFunctional).result;\n return typeCanProduceStructure(result);\n }\n if (!isTypification(cst.effectiveType)) {\n return false;\n }\n return typeCanProduceStructure(cst.effectiveType as Typification);\n}\n\n/** Evaluate if {@link CstType} can have manual typification. */\nexport function canHaveManualTypification(type: CstType): boolean {\n switch (type) {\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */\nexport function validateAliasFormat(alias: string, type: CstType): boolean {\n if (alias.length < 2) {\n return false;\n }\n const prefix = getCstTypePrefix(type);\n if (!alias.startsWith(prefix)) {\n return false;\n }\n if (!/^\\d+$/.exec(alias.substring(prefix.length))) {\n return false;\n }\n return true;\n}\n\n/** Validate new alias against {@link CstType} and {@link RSForm}. */\nexport function validateNewAlias(alias: string, type: CstType, schema: RSForm): boolean {\n if (!validateAliasFormat(alias, type)) {\n return false;\n }\n if (schema.cstByAlias.has(alias)) {\n return false;\n }\n return true;\n}\n\n/** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */\nexport function generateAlias(type: CstType, schema: RSForm, takenAliases: string[] = []): string {\n const prefix = getCstTypePrefix(type);\n if (schema.items.length <= 0) {\n return `${prefix}1`;\n }\n let index = schema.items.reduce((prev, cst, index) => {\n if (cst.cst_type !== type) {\n return prev;\n }\n index = Number(cst.alias.slice(1 - cst.alias.length)) + 1;\n return Math.max(prev, index);\n }, 1);\n let alias = `${prefix}${index}`;\n while (takenAliases.includes(alias)) {\n index = index + 1;\n alias = `${prefix}${index}`;\n }\n return alias;\n}\n\n/**\n * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:\n * after the last existing child of that spawner, or after the spawner itself if none.\n */\nexport function inferNewSpawnPosition(schema: RSForm, targetId: number): number {\n let last: number | null = null;\n for (const cst of schema.items) {\n if (cst.spawner === targetId) {\n last = cst.id;\n }\n }\n return last ?? targetId;\n}\n\n/** Sorts library items relevant for InlineSynthesis with specified {@link RSForm}. */\nexport function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly LibraryItem[]): LibraryItem[] {\n const result = items.filter(item => item.location === receiver.location);\n for (const item of items) {\n if (item.visible && item.owner === item.owner && !result.includes(item)) {\n result.push(item);\n }\n }\n for (const item of items) {\n if (item.visible && !result.includes(item)) {\n result.push(item);\n }\n }\n for (const item of items) {\n if (!result.includes(item)) {\n result.push(item);\n }\n }\n return result;\n}\n\n/** Remove alias from expression. */\nexport function removeAliasReference(expression: string, alias: string): string {\n const result = expression.replaceAll(new RegExp(`\\\\b${alias}\\\\b`, 'g'), 'DEL');\n return result === 'DEL' ? '' : result;\n}\n\n/** Add alias to expression. */\nexport function addAliasReference(expression: string, alias: string): string {\n return expression + ' ' + alias;\n}\n\n/** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */\nexport function typeClassForCstType(cstType: CstType): TypeClass {\n switch (cstType) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n return TypeClass.typification;\n case CstType.FUNCTION:\n return TypeClass.function;\n case CstType.PREDICATE:\n return TypeClass.predicate;\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return TypeClass.logic;\n }\n}\n\n/** Checks whether a constituenta type supports formal definitions. */\nexport function canHaveFormalDefinition(cstType: CstType): boolean {\n return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;\n}\n\n/** Analyze expression for {@link RSForm}. */\nexport function getAnalysisFor(expression: string, cstType: CstType, schema: RSForm, alias?: string): AnalysisFull {\n if (!canHaveFormalDefinition(cstType)) {\n if (expression.trim().length === 0) {\n const fallbackAlias = alias && alias.length > 0 ? alias : 'X0';\n const type = cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias));\n return {\n success: true,\n type,\n valueClass: ValueClass.VALUE,\n errors: [],\n ast: null\n };\n }\n return {\n success: false,\n type: null,\n valueClass: null,\n errors: [\n {\n code: RSErrorCode.definitionNotAllowed,\n from: 0,\n to: Math.max(expression.length, 1),\n params: [cstType, alias ?? '']\n }\n ],\n ast: null\n };\n }\n return schema.analyzer.checkFull(expression, {\n expected: typeClassForCstType(cstType),\n isDomain: cstType === CstType.STRUCTURED\n });\n}\n\n/** Calculate statistics for {@link RSForm}. */\nexport function calculateSchemaStats(target: RSForm): RSFormStats {\n const items = target.items;\n return {\n count_all: items.length,\n count_crucial: items.reduce((sum, cst) => sum + (cst.crucial ? 1 : 0), 0),\n\n step_complexity: items.reduce((sum, cst) => sum + calculateStepComplexity(cst), 0),\n\n count_problematic: items.reduce((sum, cst) => sum + (isSchemaIssue(cst) ? 1 : 0), 0),\n count_homonyms: items.reduce((sum, cst) => sum + (cst.homonyms.length > 0 ? 1 : 0), 0),\n count_formal_duplicates: items.reduce((sum, cst) => sum + (cst.formalDuplicates.length > 0 ? 1 : 0), 0),\n count_missing_convention: items.reduce((sum, cst) => sum + (isMissingConvention(cst) ? 1 : 0), 0),\n count_type_mismatch: items.reduce((sum, cst) => sum + (cst.is_type_mismatch ? 1 : 0), 0),\n\n count_incorrect: items.reduce((sum, cst) => sum + (cst.status === CstStatus.INCORRECT ? 1 : 0), 0),\n count_property: items.reduce((sum, cst) => sum + (cst.analysis?.valueClass === ValueClass.PROPERTY ? 1 : 0), 0),\n count_incalculable: items.reduce(\n (sum, cst) => sum + (cst.analysis?.success && cst.analysis.valueClass === null ? 1 : 0),\n 0\n ),\n count_inherited: items.reduce((sum, cst) => sum + (cst.is_inherited ? 1 : 0), 0),\n\n count_text_term: items.reduce((sum, cst) => sum + (cst.term_raw ? 1 : 0), 0),\n count_definition: items.reduce((sum, cst) => sum + (cst.definition_raw ? 1 : 0), 0),\n count_convention: items.reduce((sum, cst) => sum + (isBasicConcept(cst.cst_type) && cst.convention ? 1 : 0), 0),\n count_comment: items.reduce((sum, cst) => sum + (!isBasicConcept(cst.cst_type) && !cst.convention ? 1 : 0), 0),\n\n count_base: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.BASE ? 1 : 0), 0),\n count_constant: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.CONSTANT ? 1 : 0), 0),\n count_structured: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STRUCTURED ? 1 : 0), 0),\n count_axiom: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.AXIOM ? 1 : 0), 0),\n count_term: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.TERM ? 1 : 0), 0),\n count_function: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.FUNCTION ? 1 : 0), 0),\n count_predicate: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.PREDICATE ? 1 : 0), 0),\n count_statement: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STATEMENT ? 1 : 0), 0),\n count_nominal: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.NOMINAL ? 1 : 0), 0)\n };\n}\n\n/** Finds {@link Constituenta} by structure path. */\nexport function findCstByStructure(schema: RSForm, target: Constituenta, path: TypePath): Constituenta | null {\n for (const cst of schema.items) {\n if (cst.spawner === target.id && cst.spawner_path) {\n if (cst.spawner_path.length === path.length && cst.spawner_path.every((v, i) => v === path[i])) {\n return cst;\n }\n }\n }\n return null;\n}\n\n/** Retrieves name for piece of target {@link Constituenta} structure. */\nexport function getStructureName(schema: RSForm, target: Constituenta, path: TypePath): string {\n const representation = findCstByStructure(schema, target, path);\n if (representation) {\n return `${representation.alias}: ${representation.term_resolved}`;\n }\n if (!isTypification(target.effectiveType)) {\n return '';\n }\n const type = applyPath(target.effectiveType as Typification, path);\n if (type?.typeID === TypeID.basic) {\n const cst = schema.cstByAlias.get(type.baseID);\n if (cst?.term_resolved) {\n return `${cst.alias}: ${cst.term_resolved}`;\n }\n }\n return '';\n}\n\n// ========= Internals =====\nfunction calculateStepComplexity(cst: Constituenta): number {\n if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) {\n return 0;\n }\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT || !cst.effectiveType) {\n return 1;\n }\n\n const type = cst.effectiveType as Typification;\n return calculateTypificationComplexity(type) + 1;\n}\n\nfunction calculateTypificationComplexity(type: Typification): number {\n switch (type.typeID) {\n case TypeID.basic:\n case TypeID.integer:\n case TypeID.anyTypification:\n return 0;\n case TypeID.tuple:\n return (\n type.factors.length + type.factors.reduce((sum, factor) => sum + calculateTypificationComplexity(factor), 0)\n );\n case TypeID.collection:\n if (type.base.typeID === TypeID.tuple) {\n let sum = 0;\n type.base.factors.forEach(factor => {\n sum += calculateTypificationComplexity(factor);\n });\n return sum + type.base.factors.length;\n } else if (type.base.typeID === TypeID.collection) {\n return calculateTypificationComplexity(type.base) + 1;\n }\n return 0;\n }\n}\n\nfunction isMissingConvention(cst: Constituenta): boolean {\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention || !cst.term_resolved) {\n return true;\n }\n }\n return false;\n}\n\n/** Evaluate if {@link Typification} can be used to produce structure. */\nfunction typeCanProduceStructure(type: Typification): boolean {\n if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) {\n return false;\n } else if (type.typeID === TypeID.tuple) {\n return true;\n } else {\n return (\n type.base.typeID !== TypeID.basic &&\n type.base.typeID !== TypeID.integer &&\n type.base.typeID !== TypeID.anyTypification\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AA4BA,MAAM,kBAA2C;EAC9C,QAAQ,UAAU;EAClB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,aAAa;EACrB,QAAQ,QAAQ;EAChB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,YAAY;EACpB,QAAQ,YAAY;AACvB;;AAGA,MAAM,oBAA+C;EAClD,QAAQ,UAAU,SAAS;EAC3B,QAAQ,OAAO,SAAS;EACxB,QAAQ,WAAW,SAAS;EAC5B,QAAQ,aAAa,SAAS;EAC9B,QAAQ,OAAO,SAAS;EACxB,QAAQ,WAAW,SAAS;EAC5B,QAAQ,QAAQ,SAAS;EACzB,QAAQ,YAAY,SAAS;EAC7B,QAAQ,YAAY,SAAS;AAChC;;AAGA,SAAgB,cAAc,KAA4B;CACxD,IACE,IAAI,SAAS,SAAS,KACtB,IAAI,iBAAiB,SAAS,KAC9B,IAAI,WAAW,UAAU,aACzB,IAAI,WAAW,UAAU,gBACzB,IAAI,kBAEJ,OAAO;CAET,IAAI,eAAe,IAAI,QAAQ,KAAK,CAAC,UAAU,IAAI,QAAQ,GACzD;MAAI,CAAC,IAAI,cAAc,CAAC,IAAI,eAC1B,OAAO;CACT;CAEF,OAAO;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7E,OAAO;CAGT,MAAM,OAAO,IAAI;CACjB,OAAO,gCAAgC,IAAI,IAAI;AACjD;AAEA,SAAS,gCAAgC,MAA4B;CACnE,QAAQ,KAAK,QAAb;EACE,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,OAAO,iBACV,OAAO;EACT,KAAK,OAAO,OACV,OACE,KAAK,QAAQ,SAAS,KAAK,QAAQ,QAAQ,KAAK,WAAW,MAAM,gCAAgC,MAAM,GAAG,CAAC;EAE/G,KAAK,OAAO;GACV,IAAI,KAAK,KAAK,WAAW,OAAO,OAAO;IACrC,IAAI,MAAM;IACV,KAAK,KAAK,QAAQ,SAAQ,WAAU;KAClC,OAAO,gCAAgC,MAAM;IAC/C,CAAC;IACD,OAAO,MAAM,KAAK,KAAK,QAAQ;GACjC,OAAO,IAAI,KAAK,KAAK,WAAW,OAAO,YACrC,OAAO,gCAAgC,KAAK,IAAI,IAAI;GAEtD,OAAO;CACX;AACF;AAEA,SAAS,oBAAoB,KAA4B;CACvD,IAAI,eAAe,IAAI,QAAQ,KAAK,CAAC,UAAU,IAAI,QAAQ,GACzD;MAAI,CAAC,IAAI,cAAc,CAAC,IAAI,eAC1B,OAAO;CACT;CAEF,OAAO;AACT;;AAGA,SAAS,wBAAwB,MAA6B;CAC5D,IAAI,KAAK,WAAW,OAAO,SAAS,KAAK,WAAW,OAAO,WAAW,KAAK,WAAW,OAAO,iBAC3F,OAAO;MACF,IAAI,KAAK,WAAW,OAAO,OAChC,OAAO;MAEP,OACE,KAAK,KAAK,WAAW,OAAO,SAC5B,KAAK,KAAK,WAAW,OAAO,WAC5B,KAAK,KAAK,WAAW,OAAO;AAGlC"}
|
|
1
|
+
{"version":3,"file":"rsform-api.js","names":[],"sources":["../../src/library/rsform-api.ts"],"sourcesContent":["/**\n * Module: API for formal representation for systems of concepts.\n */\n\nimport { applyEntityReferenceMapping } from '../cctext/language-api';\nimport {\n type AnalysisFull,\n RSErrorCode,\n TypeClass,\n TypeID,\n type TypePath,\n type Typification,\n ValueClass\n} from '../rslang';\nimport { type AliasMapping, applyAliasMapping, applyTypificationMapping } from '../rslang/api';\nimport { basic, bool, constant, type EchelonFunctional, isTypification } from '../rslang/semantic/typification';\nimport { applyPath } from '../rslang/semantic/typification-api';\n\nimport { type LibraryItem } from './library';\nimport {\n type ArgumentValue,\n type Constituenta,\n CstClass,\n CstStatus,\n CstType,\n type RSForm,\n type RSFormStats\n} from './rsform';\n\n/** Record of {@link CstType} prefixes. */\nconst CST_TYPE_PREFIX: Record<CstType, string> = {\n [CstType.NOMINAL]: 'N',\n [CstType.BASE]: 'X',\n [CstType.CONSTANT]: 'C',\n [CstType.STRUCTURED]: 'S',\n [CstType.AXIOM]: 'A',\n [CstType.TERM]: 'D',\n [CstType.FUNCTION]: 'F',\n [CstType.PREDICATE]: 'P',\n [CstType.STATEMENT]: 'T'\n};\n\n/** Record of {@link CstType} to {@link CstClass} mapping. */\nconst CST_TYPE_TO_CLASS: Record<CstType, CstClass> = {\n [CstType.NOMINAL]: CstClass.NOMINAL,\n [CstType.BASE]: CstClass.BASIC,\n [CstType.CONSTANT]: CstClass.BASIC,\n [CstType.STRUCTURED]: CstClass.BASIC,\n [CstType.TERM]: CstClass.DERIVED,\n [CstType.FUNCTION]: CstClass.DERIVED,\n [CstType.AXIOM]: CstClass.STATEMENT,\n [CstType.PREDICATE]: CstClass.DERIVED,\n [CstType.STATEMENT]: CstClass.STATEMENT\n};\n\n/** Checks if {@link Constituenta} is a schema issue. */\nexport function isSchemaIssue(cst: Constituenta): boolean {\n if (\n cst.homonyms.length > 0 ||\n cst.formalDuplicates.length > 0 ||\n cst.status === CstStatus.INCORRECT ||\n cst.status === CstStatus.INCALCULABLE ||\n cst.is_type_mismatch\n ) {\n return true;\n }\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention || !cst.term_resolved) {\n return true;\n }\n }\n return false;\n}\n\n/** Infers the status of an expression based on parsing and value information. */\nexport function inferStatus(parse: boolean, value?: ValueClass | null): CstStatus {\n if (!parse) {\n return CstStatus.INCORRECT;\n }\n if (value === null) {\n return CstStatus.INCALCULABLE;\n }\n if (value === ValueClass.PROPERTY) {\n return CstStatus.PROPERTY;\n }\n return CstStatus.VERIFIED;\n}\n\n/** Infers type of constituent for a given template and arguments. */\nexport function inferTemplatedType(templateType: CstType, args: ArgumentValue[]): CstType {\n if (args.length === 0 || args.some(arg => !arg.value)) {\n return templateType;\n } else if (templateType === CstType.PREDICATE) {\n return CstType.AXIOM;\n } else {\n return CstType.TERM;\n }\n}\n\n/** Checks if given expression is a template. */\nexport function inferTemplate(expression: string): boolean {\n const match = expression.match(/R\\d+/g);\n return (match && match?.length > 0) ?? false;\n}\n\n/** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */\nexport function inferClass(type: CstType, isTemplate: boolean = false): CstClass {\n if (isTemplate) {\n return CstClass.TEMPLATE;\n }\n return CST_TYPE_TO_CLASS[type];\n}\n\n/** Check if {@link Constituenta} is a template or a category. */\nexport function isTemplateCst(cst: Constituenta): boolean {\n return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;\n}\n\n/** Apply filter based on start {@link Constituenta} type. */\nexport function applyFilterCategory(start: Constituenta, items: Constituenta[]): Constituenta[] {\n const startIndex = items.indexOf(start);\n if (startIndex === -1) {\n return [];\n }\n const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);\n\n return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));\n}\n\n/** Prefix for alias indicating {@link CstType}. */\nexport function getCstTypePrefix(type: CstType): string {\n return CST_TYPE_PREFIX[type];\n}\n\n/** Guess {@link CstType} from user input hint. */\nexport function guessCstType(hint: string): CstType | null {\n if (hint.length !== 1) {\n return null;\n }\n for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) {\n if (hint === prefix) {\n return type as CstType;\n }\n }\n return null;\n}\n\n/** Evaluate if {@link CstType} is basic concept. */\nexport function isBasicConcept(type: CstType): boolean {\n switch (type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n return true;\n\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is base set or constant set. */\nexport function isBaseSet(type: CstType): boolean {\n switch (type) {\n case CstType.BASE:\n case CstType.CONSTANT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is a function. */\nexport function isFunctional(type: CstType): boolean {\n switch (type) {\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is logical. */\nexport function isLogical(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link Constituenta} can be used produce structure. */\nexport function canProduceStructure(cst: Constituenta): boolean {\n switch (cst.cst_type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.PREDICATE:\n return false;\n }\n if (!cst.effectiveType) {\n return false;\n }\n if (cst.cst_type === CstType.FUNCTION) {\n const result = (cst.effectiveType as EchelonFunctional).result;\n return typeCanProduceStructure(result);\n }\n if (!isTypification(cst.effectiveType)) {\n return false;\n }\n return typeCanProduceStructure(cst.effectiveType as Typification);\n}\n\n/** Evaluate if {@link CstType} can have manual typification. */\nexport function canHaveManualTypification(type: CstType): boolean {\n switch (type) {\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */\nexport function validateAliasFormat(alias: string, type: CstType): boolean {\n if (alias.length < 2) {\n return false;\n }\n const prefix = getCstTypePrefix(type);\n if (!alias.startsWith(prefix)) {\n return false;\n }\n if (!/^\\d+$/.exec(alias.substring(prefix.length))) {\n return false;\n }\n return true;\n}\n\n/** Validate new alias against {@link CstType} and {@link RSForm}. */\nexport function validateNewAlias(alias: string, type: CstType, schema: RSForm): boolean {\n if (!validateAliasFormat(alias, type)) {\n return false;\n }\n if (schema.cstByAlias.has(alias)) {\n return false;\n }\n return true;\n}\n\n/** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */\nexport function generateAlias(type: CstType, schema: RSForm, takenAliases: string[] = []): string {\n const prefix = getCstTypePrefix(type);\n if (schema.items.length <= 0) {\n return `${prefix}1`;\n }\n let index = schema.items.reduce((prev, cst, index) => {\n if (cst.cst_type !== type) {\n return prev;\n }\n index = Number(cst.alias.slice(1 - cst.alias.length)) + 1;\n return Math.max(prev, index);\n }, 1);\n let alias = `${prefix}${index}`;\n while (takenAliases.includes(alias)) {\n index = index + 1;\n alias = `${prefix}${index}`;\n }\n return alias;\n}\n\n/**\n * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:\n * after the last existing child of that spawner, or after the spawner itself if none.\n */\nexport function inferNewSpawnPosition(schema: RSForm, targetId: number): number {\n let last: number | null = null;\n for (const cst of schema.items) {\n if (cst.spawner === targetId) {\n last = cst.id;\n }\n }\n return last ?? targetId;\n}\n\n/** Sorts library items relevant for InlineSynthesis with specified {@link RSForm}. */\nexport function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly LibraryItem[]): LibraryItem[] {\n const result = items.filter(item => item.location === receiver.location);\n for (const item of items) {\n if (item.visible && item.owner === item.owner && !result.includes(item)) {\n result.push(item);\n }\n }\n for (const item of items) {\n if (item.visible && !result.includes(item)) {\n result.push(item);\n }\n }\n for (const item of items) {\n if (!result.includes(item)) {\n result.push(item);\n }\n }\n return result;\n}\n\n/** Fields of {@link Constituenta} updated in place by alias mapping. */\nexport interface ConstituentaMappableFields {\n alias: string;\n definition_formal: string;\n typification_manual: string;\n term_raw: string;\n definition_raw: string;\n}\n\n/**\n * Remap formal expressions and terminological entity references in constituent fields.\n * Mutates each element of `items` in place; pass owned or cloned data only.\n */\nexport function applyMappingToConstituents<T extends ConstituentaMappableFields>(\n items: T[],\n mapping: AliasMapping,\n changeAliases: boolean\n): void {\n for (const cst of items) {\n if (changeAliases && cst.alias in mapping) {\n cst.alias = mapping[cst.alias];\n }\n cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);\n cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);\n cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);\n cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);\n }\n}\n\n/** Remove alias from expression. */\nexport function removeAliasReference(expression: string, alias: string): string {\n const result = expression.replaceAll(new RegExp(`\\\\b${alias}\\\\b`, 'g'), 'DEL');\n return result === 'DEL' ? '' : result;\n}\n\n/** Add alias to expression. */\nexport function addAliasReference(expression: string, alias: string): string {\n return expression + ' ' + alias;\n}\n\n/** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */\nexport function typeClassForCstType(cstType: CstType): TypeClass {\n switch (cstType) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n return TypeClass.typification;\n case CstType.FUNCTION:\n return TypeClass.function;\n case CstType.PREDICATE:\n return TypeClass.predicate;\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return TypeClass.logic;\n }\n}\n\n/** Checks whether a constituenta type supports formal definitions. */\nexport function canHaveFormalDefinition(cstType: CstType): boolean {\n return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;\n}\n\n/** Analyze expression for {@link RSForm}. */\nexport function getAnalysisFor(expression: string, cstType: CstType, schema: RSForm, alias?: string): AnalysisFull {\n if (!canHaveFormalDefinition(cstType)) {\n if (expression.trim().length === 0) {\n const fallbackAlias = alias && alias.length > 0 ? alias : 'X0';\n const type = cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias));\n return {\n success: true,\n type,\n valueClass: ValueClass.VALUE,\n errors: [],\n ast: null\n };\n }\n return {\n success: false,\n type: null,\n valueClass: null,\n errors: [\n {\n code: RSErrorCode.definitionNotAllowed,\n from: 0,\n to: Math.max(expression.length, 1),\n params: [cstType, alias ?? '']\n }\n ],\n ast: null\n };\n }\n return schema.analyzer.checkFull(expression, {\n expected: typeClassForCstType(cstType),\n isDomain: cstType === CstType.STRUCTURED\n });\n}\n\n/** Calculate statistics for {@link RSForm}. */\nexport function calculateSchemaStats(target: RSForm): RSFormStats {\n const items = target.items;\n return {\n count_all: items.length,\n count_crucial: items.reduce((sum, cst) => sum + (cst.crucial ? 1 : 0), 0),\n\n step_complexity: items.reduce((sum, cst) => sum + calculateStepComplexity(cst), 0),\n\n count_problematic: items.reduce((sum, cst) => sum + (isSchemaIssue(cst) ? 1 : 0), 0),\n count_homonyms: items.reduce((sum, cst) => sum + (cst.homonyms.length > 0 ? 1 : 0), 0),\n count_formal_duplicates: items.reduce((sum, cst) => sum + (cst.formalDuplicates.length > 0 ? 1 : 0), 0),\n count_missing_convention: items.reduce((sum, cst) => sum + (isMissingConvention(cst) ? 1 : 0), 0),\n count_type_mismatch: items.reduce((sum, cst) => sum + (cst.is_type_mismatch ? 1 : 0), 0),\n\n count_incorrect: items.reduce((sum, cst) => sum + (cst.status === CstStatus.INCORRECT ? 1 : 0), 0),\n count_property: items.reduce((sum, cst) => sum + (cst.analysis?.valueClass === ValueClass.PROPERTY ? 1 : 0), 0),\n count_incalculable: items.reduce(\n (sum, cst) => sum + (cst.analysis?.success && cst.analysis.valueClass === null ? 1 : 0),\n 0\n ),\n count_inherited: items.reduce((sum, cst) => sum + (cst.is_inherited ? 1 : 0), 0),\n\n count_text_term: items.reduce((sum, cst) => sum + (cst.term_raw ? 1 : 0), 0),\n count_definition: items.reduce((sum, cst) => sum + (cst.definition_raw ? 1 : 0), 0),\n count_convention: items.reduce((sum, cst) => sum + (isBasicConcept(cst.cst_type) && cst.convention ? 1 : 0), 0),\n count_comment: items.reduce((sum, cst) => sum + (!isBasicConcept(cst.cst_type) && !cst.convention ? 1 : 0), 0),\n\n count_base: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.BASE ? 1 : 0), 0),\n count_constant: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.CONSTANT ? 1 : 0), 0),\n count_structured: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STRUCTURED ? 1 : 0), 0),\n count_axiom: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.AXIOM ? 1 : 0), 0),\n count_term: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.TERM ? 1 : 0), 0),\n count_function: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.FUNCTION ? 1 : 0), 0),\n count_predicate: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.PREDICATE ? 1 : 0), 0),\n count_statement: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STATEMENT ? 1 : 0), 0),\n count_nominal: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.NOMINAL ? 1 : 0), 0)\n };\n}\n\n/** Finds {@link Constituenta} by structure path. */\nexport function findCstByStructure(schema: RSForm, target: Constituenta, path: TypePath): Constituenta | null {\n for (const cst of schema.items) {\n if (cst.spawner === target.id && cst.spawner_path) {\n if (cst.spawner_path.length === path.length && cst.spawner_path.every((v, i) => v === path[i])) {\n return cst;\n }\n }\n }\n return null;\n}\n\n/** Retrieves name for piece of target {@link Constituenta} structure. */\nexport function getStructureName(schema: RSForm, target: Constituenta, path: TypePath): string {\n const representation = findCstByStructure(schema, target, path);\n if (representation) {\n return `${representation.alias}: ${representation.term_resolved}`;\n }\n if (!isTypification(target.effectiveType)) {\n return '';\n }\n const type = applyPath(target.effectiveType as Typification, path);\n if (type?.typeID === TypeID.basic) {\n const cst = schema.cstByAlias.get(type.baseID);\n if (cst?.term_resolved) {\n return `${cst.alias}: ${cst.term_resolved}`;\n }\n }\n return '';\n}\n\n// ========= Internals =====\nfunction calculateStepComplexity(cst: Constituenta): number {\n if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) {\n return 0;\n }\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT || !cst.effectiveType) {\n return 1;\n }\n\n const type = cst.effectiveType as Typification;\n return calculateTypificationComplexity(type) + 1;\n}\n\nfunction calculateTypificationComplexity(type: Typification): number {\n switch (type.typeID) {\n case TypeID.basic:\n case TypeID.integer:\n case TypeID.anyTypification:\n return 0;\n case TypeID.tuple:\n return (\n type.factors.length + type.factors.reduce((sum, factor) => sum + calculateTypificationComplexity(factor), 0)\n );\n case TypeID.collection:\n if (type.base.typeID === TypeID.tuple) {\n let sum = 0;\n type.base.factors.forEach(factor => {\n sum += calculateTypificationComplexity(factor);\n });\n return sum + type.base.factors.length;\n } else if (type.base.typeID === TypeID.collection) {\n return calculateTypificationComplexity(type.base) + 1;\n }\n return 0;\n }\n}\n\nfunction isMissingConvention(cst: Constituenta): boolean {\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention || !cst.term_resolved) {\n return true;\n }\n }\n return false;\n}\n\n/** Evaluate if {@link Typification} can be used to produce structure. */\nfunction typeCanProduceStructure(type: Typification): boolean {\n if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) {\n return false;\n } else if (type.typeID === TypeID.tuple) {\n return true;\n } else {\n return (\n type.base.typeID !== TypeID.basic &&\n type.base.typeID !== TypeID.integer &&\n type.base.typeID !== TypeID.anyTypification\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,MAAM,kBAA2C;EAC9C,QAAQ,UAAU;EAClB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,aAAa;EACrB,QAAQ,QAAQ;EAChB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,YAAY;EACpB,QAAQ,YAAY;AACvB;;AAGA,MAAM,oBAA+C;EAClD,QAAQ,UAAU,SAAS;EAC3B,QAAQ,OAAO,SAAS;EACxB,QAAQ,WAAW,SAAS;EAC5B,QAAQ,aAAa,SAAS;EAC9B,QAAQ,OAAO,SAAS;EACxB,QAAQ,WAAW,SAAS;EAC5B,QAAQ,QAAQ,SAAS;EACzB,QAAQ,YAAY,SAAS;EAC7B,QAAQ,YAAY,SAAS;AAChC;;AAGA,SAAgB,cAAc,KAA4B;CACxD,IACE,IAAI,SAAS,SAAS,KACtB,IAAI,iBAAiB,SAAS,KAC9B,IAAI,WAAW,UAAU,aACzB,IAAI,WAAW,UAAU,gBACzB,IAAI,kBAEJ,OAAO;CAET,IAAI,eAAe,IAAI,QAAQ,KAAK,CAAC,UAAU,IAAI,QAAQ,GACzD;MAAI,CAAC,IAAI,cAAc,CAAC,IAAI,eAC1B,OAAO;CACT;CAEF,OAAO;AACT;;AAGA,SAAgB,YAAY,OAAgB,OAAsC;CAChF,IAAI,CAAC,OACH,OAAO,UAAU;CAEnB,IAAI,UAAU,MACZ,OAAO,UAAU;CAEnB,IAAI,UAAU,WAAW,UACvB,OAAO,UAAU;CAEnB,OAAO,UAAU;AACnB;;AAGA,SAAgB,mBAAmB,cAAuB,MAAgC;CACxF,IAAI,KAAK,WAAW,KAAK,KAAK,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
import "../rslang/index.js";
|
|
4
4
|
import { CstType } from "./rsform.js";
|
|
5
|
-
import { findCstByStructure } from "./rsform-api.js";
|
|
6
5
|
import { splitTemplateDefinition } from "../rslang/api.js";
|
|
6
|
+
import { findCstByStructure } from "./rsform-api.js";
|
|
7
7
|
//#region src/library/structure-planner.ts
|
|
8
8
|
/** Structure planner for {@link Constituenta}. */
|
|
9
9
|
var StructurePlanner = class {
|
package/dist/rslang/api.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as AstNode } from "../ast-C8sIpKdL.js";
|
|
2
2
|
import { n as ArgumentsType } from "../arguments-extractor-1acwjQNc.js";
|
|
3
|
-
import { generateExpressionFromAst } from "
|
|
3
|
+
import { t as generateExpressionFromAst } from "../expression-generator-CoucLIkE.js";
|
|
4
4
|
|
|
5
5
|
//#region src/rslang/api.d.ts
|
|
6
6
|
/** Represents alias mapping. */
|
|
@@ -1,10 +1,2 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
|
|
3
|
-
interface ExpressionGeneratorOptions {
|
|
4
|
-
normalize?: boolean;
|
|
5
|
-
}
|
|
6
|
-
/** Generates Math-syntax RS expression from AST, with optional identifier normalization. */
|
|
7
|
-
declare function generateExpressionFromAst(ast: AstNode, options?: ExpressionGeneratorOptions): string;
|
|
8
|
-
//#endregion
|
|
9
|
-
export { generateExpressionFromAst };
|
|
10
|
-
//# sourceMappingURL=expression-generator.d.ts.map
|
|
1
|
+
import { t as generateExpressionFromAst } from "../../expression-generator-CoucLIkE.js";
|
|
2
|
+
export { generateExpressionFromAst };
|
package/package.json
CHANGED
|
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
|
|
|
2
2
|
|
|
3
3
|
import { Grammeme } from './language';
|
|
4
4
|
import {
|
|
5
|
+
applyEntityReferenceMapping,
|
|
5
6
|
extractEntities,
|
|
6
7
|
generateNominalLexeme,
|
|
7
8
|
parseEntityReference,
|
|
@@ -114,6 +115,21 @@ describe('Testing reference parsing', () => {
|
|
|
114
115
|
});
|
|
115
116
|
});
|
|
116
117
|
|
|
118
|
+
describe('applyEntityReferenceMapping', () => {
|
|
119
|
+
it('replaces entity aliases in terminological references', () => {
|
|
120
|
+
expect(applyEntityReferenceMapping('@{X1|sing}', { X1: 'X3' })).toBe('@{X3|sing}');
|
|
121
|
+
expect(applyEntityReferenceMapping('@{X1|sing} and @{X2|plur}', { X1: 'X3', X2: 'X4' })).toBe(
|
|
122
|
+
'@{X3|sing} and @{X4|plur}'
|
|
123
|
+
);
|
|
124
|
+
expect(applyEntityReferenceMapping('', { X1: 'X3' })).toBe('');
|
|
125
|
+
expect(applyEntityReferenceMapping('plain text', { X1: 'X3' })).toBe('plain text');
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('trims padded entity names when resolving aliases', () => {
|
|
129
|
+
expect(applyEntityReferenceMapping('@{ X1 |sing}', { X1: 'X3' })).toBe('@{X3|sing}');
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
117
133
|
describe('Testing reference resolution', () => {
|
|
118
134
|
it('extracts entity references', () => {
|
|
119
135
|
expect(extractEntities('@{X1|} and @{1|nominal} and @{X2|sing,gent} and @{X1|plur,nomn}')).toStrictEqual([
|
|
@@ -128,6 +128,29 @@ export function parseReference(text: string): IReference | null {
|
|
|
128
128
|
};
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
/** Apply alias mapping to entity references in terminological text. */
|
|
132
|
+
export function applyEntityReferenceMapping(text: string, mapping: Record<string, string>): string {
|
|
133
|
+
if (text === '' || Object.keys(mapping).length === 0) {
|
|
134
|
+
return text;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
let posInput = 0;
|
|
138
|
+
let output = '';
|
|
139
|
+
for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {
|
|
140
|
+
const entity = segment[1];
|
|
141
|
+
const entityKey = entity.trim();
|
|
142
|
+
const start = segment.index ?? 0;
|
|
143
|
+
if (entityKey in mapping) {
|
|
144
|
+
output += text.substring(posInput, start + 2);
|
|
145
|
+
output += mapping[entityKey];
|
|
146
|
+
output += text.substring(start + 2 + entity.length, start + segment[0].length);
|
|
147
|
+
posInput = start + segment[0].length;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
output += text.substring(posInput);
|
|
151
|
+
return output;
|
|
152
|
+
}
|
|
153
|
+
|
|
131
154
|
/** Extracts unique entity aliases referenced by text. */
|
|
132
155
|
export function extractEntities(text: string): string[] {
|
|
133
156
|
const result: string[] = [];
|
|
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
|
|
|
3
3
|
import { RSErrorCode } from '../rslang/error';
|
|
4
4
|
|
|
5
5
|
import { CstType, type RSForm } from './rsform';
|
|
6
|
-
import { getAnalysisFor, validateAliasFormat } from './rsform-api';
|
|
6
|
+
import { applyMappingToConstituents, getAnalysisFor, validateAliasFormat } from './rsform-api';
|
|
7
7
|
|
|
8
8
|
const emptySchema = {} as RSForm;
|
|
9
9
|
|
|
@@ -50,3 +50,41 @@ describe('getAnalysisFor', () => {
|
|
|
50
50
|
});
|
|
51
51
|
});
|
|
52
52
|
});
|
|
53
|
+
|
|
54
|
+
describe('applyMappingToConstituents', () => {
|
|
55
|
+
it('updates formal expressions and terminological references', () => {
|
|
56
|
+
const items = [
|
|
57
|
+
{
|
|
58
|
+
alias: 'X3',
|
|
59
|
+
definition_formal: 'X1 = X2',
|
|
60
|
+
typification_manual: 'ℬ(X1)',
|
|
61
|
+
term_raw: '@{X1|sing}',
|
|
62
|
+
definition_raw: '@{X2|sing}'
|
|
63
|
+
}
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
applyMappingToConstituents(items, { X1: 'X3', X2: 'X4' }, false);
|
|
67
|
+
|
|
68
|
+
expect(items[0].definition_formal).toBe('X3 = X4');
|
|
69
|
+
expect(items[0].typification_manual).toBe('ℬ(X3)');
|
|
70
|
+
expect(items[0].term_raw).toBe('@{X3|sing}');
|
|
71
|
+
expect(items[0].definition_raw).toBe('@{X4|sing}');
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('updates aliases when changeAliases is true', () => {
|
|
75
|
+
const items = [
|
|
76
|
+
{
|
|
77
|
+
alias: 'X1',
|
|
78
|
+
definition_formal: 'X1',
|
|
79
|
+
typification_manual: '',
|
|
80
|
+
term_raw: '',
|
|
81
|
+
definition_raw: ''
|
|
82
|
+
}
|
|
83
|
+
];
|
|
84
|
+
|
|
85
|
+
applyMappingToConstituents(items, { X1: 'X3' }, true);
|
|
86
|
+
|
|
87
|
+
expect(items[0].alias).toBe('X3');
|
|
88
|
+
expect(items[0].definition_formal).toBe('X3');
|
|
89
|
+
});
|
|
90
|
+
});
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Module: API for formal representation for systems of concepts.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import { applyEntityReferenceMapping } from '../cctext/language-api';
|
|
5
6
|
import {
|
|
6
7
|
type AnalysisFull,
|
|
7
8
|
RSErrorCode,
|
|
@@ -11,6 +12,7 @@ import {
|
|
|
11
12
|
type Typification,
|
|
12
13
|
ValueClass
|
|
13
14
|
} from '../rslang';
|
|
15
|
+
import { type AliasMapping, applyAliasMapping, applyTypificationMapping } from '../rslang/api';
|
|
14
16
|
import { basic, bool, constant, type EchelonFunctional, isTypification } from '../rslang/semantic/typification';
|
|
15
17
|
import { applyPath } from '../rslang/semantic/typification-api';
|
|
16
18
|
|
|
@@ -339,6 +341,35 @@ export function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly Li
|
|
|
339
341
|
return result;
|
|
340
342
|
}
|
|
341
343
|
|
|
344
|
+
/** Fields of {@link Constituenta} updated in place by alias mapping. */
|
|
345
|
+
export interface ConstituentaMappableFields {
|
|
346
|
+
alias: string;
|
|
347
|
+
definition_formal: string;
|
|
348
|
+
typification_manual: string;
|
|
349
|
+
term_raw: string;
|
|
350
|
+
definition_raw: string;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Remap formal expressions and terminological entity references in constituent fields.
|
|
355
|
+
* Mutates each element of `items` in place; pass owned or cloned data only.
|
|
356
|
+
*/
|
|
357
|
+
export function applyMappingToConstituents<T extends ConstituentaMappableFields>(
|
|
358
|
+
items: T[],
|
|
359
|
+
mapping: AliasMapping,
|
|
360
|
+
changeAliases: boolean
|
|
361
|
+
): void {
|
|
362
|
+
for (const cst of items) {
|
|
363
|
+
if (changeAliases && cst.alias in mapping) {
|
|
364
|
+
cst.alias = mapping[cst.alias];
|
|
365
|
+
}
|
|
366
|
+
cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);
|
|
367
|
+
cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);
|
|
368
|
+
cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);
|
|
369
|
+
cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
342
373
|
/** Remove alias from expression. */
|
|
343
374
|
export function removeAliasReference(expression: string, alias: string): string {
|
|
344
375
|
const result = expression.replaceAll(new RegExp(`\\b${alias}\\b`, 'g'), 'DEL');
|