@rsconcept/domain 3.1.0 → 3.1.1
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/{diagnostics-D1Cp21nP.js → diagnostics-D_4TpAH4.js} +4 -5
- package/dist/{diagnostics-D1Cp21nP.js.map → diagnostics-D_4TpAH4.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/library/diagnostics.js +1 -1
- package/dist/library/index.js +1 -1
- package/dist/library/oss-api.js +2 -4
- package/dist/library/oss-api.js.map +1 -1
- package/dist/library/oss.js +1 -1
- package/dist/library/rsengine.js +4 -3
- package/dist/library/rsengine.js.map +1 -1
- package/dist/library/rsform-api/index.js +1 -1
- package/dist/library/rsmodel-api.js +6 -4
- package/dist/library/rsmodel-api.js.map +1 -1
- package/dist/library/structure-planner.js +1 -1
- package/dist/parsing/lezer-tree.js.map +1 -1
- package/dist/rslang/api.js +9 -6
- package/dist/rslang/api.js.map +1 -1
- package/dist/rslang/eval/calculator.js +1 -1
- package/dist/rslang/eval/evaluation-cache.js +1 -3
- package/dist/rslang/eval/evaluation-cache.js.map +1 -1
- package/dist/rslang/eval/evaluator.js +5 -3
- package/dist/rslang/eval/evaluator.js.map +1 -1
- package/dist/rslang/eval/value-api.js +1 -1
- package/dist/rslang/eval/value.js +1 -1
- package/dist/rslang/index.js +1 -1
- package/dist/rslang/parser/normalize.js.map +1 -1
- package/dist/rslang/parser/parser.terms.js.map +1 -1
- package/dist/rslang/semantic/arguments-extractor.js +6 -4
- package/dist/rslang/semantic/arguments-extractor.js.map +1 -1
- package/dist/rslang/semantic/type-auditor.js +20 -16
- package/dist/rslang/semantic/type-auditor.js.map +1 -1
- package/dist/rslang/semantic/typification-api.js +10 -9
- package/dist/rslang/semantic/typification-api.js.map +1 -1
- package/dist/rslang/semantic/typification-parser.js +4 -1
- package/dist/rslang/semantic/typification-parser.js.map +1 -1
- package/dist/{value-COprb2Je.js → value-BDISzQqI.js} +3 -2
- package/dist/{value-COprb2Je.js.map → value-BDISzQqI.js.map} +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oss-api.js","names":[],"sources":["../../src/library/oss-api.ts"],"sourcesContent":["/**\n * Module: API for OperationSystem.\n */\n\nimport { Graph } from '../graph';\nimport { type AliasMapping, applyAliasMapping, applyTypificationMapping, isSetTypification } from '../rslang/api';\nimport { labelType } from '../rslang/labels';\nimport { extractBases } from '../rslang/semantic/typification-api';\n\nimport { formatDependencyCycle } from './diagnostics';\nimport { type LibraryItem } from './library';\nimport { NodeType, type OperationSchema, type SubstitutionErrorDescription, SubstitutionErrorType } from './oss';\nimport { type Constituenta, CstClass, CstType, type RSForm, type Substitution } from './rsform';\nimport { type FormalOrderFields } from './rsform-api';\n\nconst STARTING_SUB_INDEX = 900; // max semantic index for starting substitution\n\nexport function constructNodeID(type: NodeType, itemID: number): string {\n return type === NodeType.OPERATION ? 'o' + String(itemID) : 'b' + String(itemID);\n}\n\n/** Sorts library items relevant for the specified {@link OperationSchema}. */\nexport function sortItemsForOSS(oss: OperationSchema, items: readonly LibraryItem[]): LibraryItem[] {\n const result = items.filter(item => item.location === oss.location);\n for (const item of items) {\n if (item.visible && item.owner === oss.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\ntype CrossMapping = Map<number, AliasMapping>;\n\n/** Validator for Substitution table. */\nexport class SubstitutionValidator {\n public errors: SubstitutionErrorDescription[] = [];\n public suggestions: Substitution[] = [];\n\n private schemas: RSForm[];\n private substitutions: Substitution[];\n private constituents = new Set<number>();\n private originals = new Set<number>();\n private mapping: CrossMapping = new Map();\n\n private cstByID = new Map<number, Constituenta>();\n private schemaByID = new Map<number, RSForm>();\n private schemaByCst = new Map<number, RSForm>();\n\n constructor(schemas: RSForm[], substitutions: Substitution[]) {\n this.schemas = schemas;\n this.substitutions = substitutions;\n if (schemas.length === 0) {\n return;\n }\n\n for (const schema of schemas) {\n this.schemaByID.set(schema.id, schema);\n this.mapping.set(schema.id, {});\n for (const item of schema.items) {\n this.cstByID.set(item.id, item);\n this.schemaByCst.set(item.id, schema);\n }\n }\n if (substitutions.length === 0) {\n return;\n }\n let index = STARTING_SUB_INDEX;\n for (const item of substitutions) {\n this.constituents.add(item.original);\n this.constituents.add(item.substitution);\n this.originals.add(item.original);\n const original = this.cstByID.get(item.original);\n const substitution = this.cstByID.get(item.substitution);\n if (!original || !substitution) {\n return;\n }\n index++;\n const newAlias = `${substitution.alias[0]}${index}`;\n this.mapping.get(original.schema)![original.alias] = newAlias;\n this.mapping.get(substitution.schema)![substitution.alias] = newAlias;\n }\n }\n\n public validate(): boolean {\n this.errors = [];\n this.suggestions = [];\n this.calculateSuggestions();\n if (this.substitutions.length === 0) {\n return true;\n }\n if (!this.checkTypes()) {\n return false;\n }\n if (!this.checkTypificationCycles()) {\n return false;\n }\n if (!this.checkDefinitionCycles()) {\n return false;\n }\n if (!this.checkSubstitutions()) {\n return false;\n }\n return true;\n }\n\n private calculateSuggestions(): void {\n const candidates = new Map<number, string>();\n const minors = new Set<number>();\n const schemaByCst = new Map<number, RSForm>();\n for (const schema of this.schemas) {\n for (const cst of schema.items) {\n if (this.originals.has(cst.id)) {\n continue;\n }\n if (cst.cst_class === CstClass.BASIC || cst.definition_formal.length === 0) {\n continue;\n }\n const inputs = schema.graph.at(cst.id)!.inputs;\n if (inputs.some(id => !this.constituents.has(id))) {\n continue;\n }\n if (inputs.some(id => this.originals.has(id))) {\n minors.add(cst.id);\n }\n candidates.set(\n cst.id,\n applyAliasMapping(cst.definition_formal, this.mapping.get(schema.id)!).replace(/\\s+/g, '')\n );\n schemaByCst.set(cst.id, schema);\n }\n }\n for (const [key1, value1] of candidates) {\n for (const [key2, value2] of candidates) {\n if (key1 >= key2) {\n continue;\n }\n if (schemaByCst.get(key1) === schemaByCst.get(key2)) {\n continue;\n }\n if (value1 != value2) {\n continue;\n }\n if (minors.has(key2)) {\n this.suggestions.push({\n original: key2,\n substitution: key1\n });\n } else {\n this.suggestions.push({\n original: key1,\n substitution: key2\n });\n }\n }\n }\n }\n\n private checkTypes(): boolean {\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original);\n const substitution = this.cstByID.get(item.substitution);\n if (!original || !substitution) {\n return this.reportError(SubstitutionErrorType.invalidIDs, []);\n }\n if (\n substitution.analysis &&\n original.analysis &&\n (!original.analysis.success || !substitution.analysis.success)\n ) {\n return this.reportError(SubstitutionErrorType.incorrectCst, [substitution.alias, original.alias]);\n }\n switch (substitution.cst_type) {\n case CstType.NOMINAL: {\n if (original.cst_type !== CstType.NOMINAL) {\n return this.reportError(SubstitutionErrorType.invalidNominal, [substitution.alias, original.alias]);\n }\n break;\n }\n case CstType.BASE: {\n if (\n original.cst_type !== CstType.BASE &&\n original.cst_type !== CstType.CONSTANT &&\n original.cst_type !== CstType.NOMINAL\n ) {\n return this.reportError(SubstitutionErrorType.invalidBasic, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.CONSTANT: {\n if (original.cst_type !== CstType.CONSTANT) {\n return this.reportError(SubstitutionErrorType.invalidConstant, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.AXIOM:\n case CstType.STATEMENT: {\n if (original.cst_type !== CstType.AXIOM && original.cst_type !== CstType.STATEMENT) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.FUNCTION: {\n if (original.cst_type !== CstType.FUNCTION) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n case CstType.PREDICATE: {\n if (original.cst_type !== CstType.PREDICATE) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.TERM:\n case CstType.STRUCTURED: {\n if (\n original.cst_type !== CstType.TERM &&\n original.cst_type !== CstType.STRUCTURED &&\n original.cst_type !== CstType.BASE\n ) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n }\n }\n return true;\n }\n\n /**\n * Detect cycles among base/constant sets implied by typifications of non-base\n * constituents under the substitution table.\n */\n private checkTypificationCycles(): boolean {\n const graph = new Graph();\n for (const schema of this.schemas) {\n for (const cst of schema.items) {\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT) {\n graph.addNode(cst.id);\n }\n }\n }\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original)!;\n const substitution = this.cstByID.get(item.substitution)!;\n for (const cst of [original, substitution]) {\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT) {\n continue;\n }\n graph.addNode(cst.id);\n if (cst.effectiveType === null) {\n continue;\n }\n const parents = extractBases(cst.effectiveType);\n if (parents.size === 0) {\n continue;\n }\n const schema = this.schemaByID.get(cst.schema)!;\n for (const alias of parents) {\n const parent = schema.cstByAlias.get(alias);\n if (parent) {\n graph.addEdge(parent.id, cst.id);\n }\n }\n }\n graph.addEdge(substitution.id, original.id);\n }\n const cycle = graph.findCycle();\n if (cycle !== null) {\n const cycleMsg = cycle\n .map(id => {\n const cst = this.cstByID.get(id)!;\n const schema = this.schemaByID.get(cst.schema)!;\n return `[${schema.alias}]-${cst.alias}`;\n })\n .join(', ');\n return this.reportError(SubstitutionErrorType.typificationCycle, [cycleMsg]);\n }\n return true;\n }\n\n /**\n * Detect logical cycles in formal definitions after applying the substitution table\n * (e.g. D16 := F2[D15] with identification D15 → D16 yields D16 := F2[D16]).\n */\n private checkDefinitionCycles(): boolean {\n const graph = new Graph();\n for (const schema of this.schemas) {\n for (const [id, node] of schema.graph.nodes) {\n graph.addNode(id);\n for (const output of node.outputs) {\n graph.addEdge(id, output);\n }\n }\n }\n\n const deleted = new Map<number, number>();\n for (const item of this.substitutions) {\n deleted.set(item.original, item.substitution);\n }\n const resolve = (id: number): number => deleted.get(id) ?? id;\n\n const result = new Graph();\n for (const id of graph.nodes.keys()) {\n if (!deleted.has(id)) {\n result.addNode(id);\n }\n }\n for (const substitutionId of deleted.values()) {\n result.addNode(substitutionId);\n }\n\n for (const [id, node] of graph.nodes) {\n for (const output of node.outputs) {\n if (deleted.has(output)) {\n continue;\n }\n result.addEdge(resolve(id), output);\n }\n }\n\n const cycle = result.findCycle();\n if (cycle !== null) {\n const aliases = cycle.map(id => {\n const cst = this.cstByID.get(id);\n if (!cst) {\n return String(id);\n }\n if (this.schemas.length > 1) {\n const schema = this.schemaByID.get(cst.schema);\n return schema ? `[${schema.alias}]-${cst.alias}` : cst.alias;\n }\n return cst.alias;\n });\n return this.reportError(SubstitutionErrorType.definitionCycle, [formatDependencyCycle(aliases)]);\n }\n return true;\n }\n\n private checkSubstitutions(): boolean {\n const baseMappings = this.prepareBaseMappings();\n const typeMappings = this.calculateSubstituteMappings(baseMappings);\n if (typeMappings === null) {\n return false;\n }\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original)!;\n if (\n original.cst_type === CstType.BASE ||\n original.cst_type === CstType.CONSTANT ||\n original.cst_type === CstType.NOMINAL\n ) {\n continue;\n }\n const substitution = this.cstByID.get(item.substitution)!;\n if (original.cst_type === substitution.cst_type && original.cst_class !== CstClass.BASIC) {\n if (!this.checkEqual(original, substitution)) {\n this.reportError(SubstitutionErrorType.unequalExpressions, [substitution.alias, original.alias]);\n // Note: do not interrupt the validation process. Only warn about the problem.\n }\n }\n\n if (original.analysis.success !== substitution.analysis.success) {\n return this.reportError(SubstitutionErrorType.unequalTypification, [substitution.alias, original.alias]);\n }\n if (!original.analysis.success || !substitution.analysis.success) {\n continue;\n }\n\n const originalType = applyTypificationMapping(\n applyAliasMapping(labelType(original.effectiveType), baseMappings.get(original.schema)!),\n typeMappings\n );\n const substitutionType = applyTypificationMapping(\n applyAliasMapping(labelType(substitution.effectiveType), baseMappings.get(substitution.schema)!),\n typeMappings\n );\n if (originalType !== substitutionType) {\n return this.reportError(SubstitutionErrorType.unequalTypification, [substitution.alias, original.alias]);\n }\n }\n return true;\n }\n\n private prepareBaseMappings(): CrossMapping {\n const result: CrossMapping = new Map();\n let baseCount = 0;\n let constCount = 0;\n for (const schema of this.schemas) {\n const mapping: AliasMapping = {};\n for (const cst of schema.items) {\n if (cst.cst_type === CstType.BASE) {\n baseCount++;\n mapping[cst.alias] = `X${baseCount}`;\n } else if (cst.cst_type === CstType.CONSTANT) {\n constCount++;\n mapping[cst.alias] = `C${constCount}`;\n }\n result.set(schema.id, mapping);\n }\n }\n return result;\n }\n\n private calculateSubstituteMappings(baseMappings: CrossMapping): AliasMapping | null {\n const result: AliasMapping = {};\n const processed = new Set<string>();\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original)!;\n if (original.cst_type !== CstType.BASE && original.cst_type !== CstType.CONSTANT) {\n continue;\n }\n const originalAlias = baseMappings.get(original.schema)![original.alias];\n\n const substitution = this.cstByID.get(item.substitution)!;\n let substitutionText = '';\n if (substitution.cst_type === original.cst_type || !substitution.effectiveType) {\n substitutionText = baseMappings.get(substitution.schema)![substitution.alias];\n } else {\n const typeText = labelType(substitution.effectiveType);\n substitutionText = applyAliasMapping(typeText, baseMappings.get(substitution.schema)!);\n substitutionText = applyTypificationMapping(substitutionText, result);\n if (!isSetTypification(substitutionText)) {\n this.reportError(SubstitutionErrorType.baseSubstitutionNotSet, [substitution.alias, typeText]);\n return null;\n }\n if (substitutionText.includes('×') || substitutionText.startsWith('ℬℬ')) {\n substitutionText = substitutionText.slice(1);\n } else {\n substitutionText = substitutionText.slice(2, -1);\n }\n }\n for (const prevAlias of processed) {\n result[prevAlias] = applyTypificationMapping(result[prevAlias], { [originalAlias]: substitutionText });\n }\n result[originalAlias] = substitutionText;\n processed.add(originalAlias);\n }\n return result;\n }\n\n private checkEqual(\n left: FormalOrderFields & { schema: number },\n right: FormalOrderFields & { schema: number }\n ): boolean {\n const schema1 = this.schemaByID.get(left.schema)!;\n const inputs1 = schema1.graph.at(left.id)!.inputs;\n if (inputs1.some(id => !this.constituents.has(id))) {\n return false;\n }\n const schema2 = this.schemaByID.get(right.schema)!;\n const inputs2 = schema2.graph.at(right.id)!.inputs;\n if (inputs2.some(id => !this.constituents.has(id))) {\n return false;\n }\n const expression1 = applyAliasMapping(left.definition_formal, this.mapping.get(schema1.id)!);\n const expression2 = applyAliasMapping(right.definition_formal, this.mapping.get(schema2.id)!);\n return expression1.replace(/\\s+/g, '') === expression2.replace(/\\s+/g, '');\n }\n\n private reportError(code: SubstitutionErrorType, params: string[]): boolean {\n this.errors.push({\n code,\n params\n });\n return false;\n }\n}\n\n/** Filter relocate candidates from gives schema. */\nexport function getRelocateCandidates(\n source: number,\n destination: number,\n schema: RSForm,\n oss: OperationSchema\n): Constituenta[] {\n const destinationSchema = oss.operationByID.get(destination)?.result;\n if (!destinationSchema) {\n return [];\n }\n const node = oss.graph.at(source);\n if (!node) {\n return [];\n }\n\n if (node.outputs.includes(destination)) {\n return schema.items;\n }\n\n const addedCst = schema.items.filter(item => !item.is_inherited).map(cst => cst.id);\n\n const unreachableBases: number[] = [];\n for (const cst of schema.items.filter(item => item.is_inherited)) {\n if (cst.parent_schema == destinationSchema) {\n continue;\n }\n const parent = schema.inheritance.find(item => item.child === cst.id && item.child_source === cst.schema)?.parent;\n if (parent) {\n const original = oss.substitutions.find(sub => sub.substitution === parent)?.original;\n if (original) {\n continue;\n }\n }\n unreachableBases.push(cst.id);\n }\n const unreachable = schema.graph.expandAllOutputs(unreachableBases);\n return schema.items.filter(\n cst => cst.parent_schema === destinationSchema || (addedCst.includes(cst.id) && !unreachable.includes(cst.id))\n );\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,qBAAqB;AAE3B,SAAgB,gBAAgB,MAAgB,QAAwB;CACtE,OAAO,SAAS,SAAS,YAAY,MAAM,OAAO,MAAM,IAAI,MAAM,OAAO,MAAM;AACjF;;AAGA,SAAgB,gBAAgB,KAAsB,OAA8C;CAClG,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AAO;CACT;AACF;;AAGA,SAAgB,sBACd,QACA,aACA,QACA,KACgB;CAChB,MAAM,oBAAoB,IAAI,cAAc,IAAI,WAAW,CAAC,EAAE;CAC9D,IAAI,CAAC,mBACH,OAAO,CAAC;CAEV,MAAM,OAAO,IAAI,MAAM,GAAG,MAAM;CAChC,IAAI,CAAC,MACH,OAAO,CAAC;CAGV,IAAI,KAAK,QAAQ,SAAS,WAAW,GACnC,OAAO,OAAO;CAGhB,MAAM,WAAW,OAAO,MAAM,QAAO,SAAQ,CAAC,KAAK,YAAY,CAAC,CAAC,KAAI,QAAO,IAAI,EAAE;CAElF,MAAM,mBAA6B,CAAC;CACpC,KAAK,MAAM,OAAO,OAAO,MAAM,QAAO,SAAQ,KAAK,YAAY,GAAG;EAChE,IAAI,IAAI,iBAAiB,mBACvB;EAEF,MAAM,SAAS,OAAO,YAAY,MAAK,SAAQ,KAAK,UAAU,IAAI,MAAM,KAAK,iBAAiB,IAAI,MAAM,CAAC,EAAE;EAC3G,IAAI,QAEF;OADiB,IAAI,cAAc,MAAK,QAAO,IAAI,iBAAiB,MAAM,CAAC,EAAE,UAE3E;EACF;EAEF,iBAAiB,KAAK,IAAI,EAAE;CAC9B;CACA,MAAM,cAAc,OAAO,MAAM,iBAAiB,gBAAgB;CAClE,OAAO,OAAO,MAAM,QAClB,QAAO,IAAI,kBAAkB,qBAAsB,SAAS,SAAS,IAAI,EAAE,KAAK,CAAC,YAAY,SAAS,IAAI,EAAE,CAC9G;AACF"}
|
|
1
|
+
{"version":3,"file":"oss-api.js","names":[],"sources":["../../src/library/oss-api.ts"],"sourcesContent":["/**\n * Module: API for OperationSystem.\n */\n\nimport { Graph } from '../graph';\nimport { type AliasMapping, applyAliasMapping, applyTypificationMapping, isSetTypification } from '../rslang/api';\nimport { labelType } from '../rslang/labels';\nimport { extractBases } from '../rslang/semantic/typification-api';\n\nimport { formatDependencyCycle } from './diagnostics';\nimport { type LibraryItem } from './library';\nimport { NodeType, type OperationSchema, type SubstitutionErrorDescription, SubstitutionErrorType } from './oss';\nimport { type Constituenta, CstClass, CstType, type RSForm, type Substitution } from './rsform';\nimport { type FormalOrderFields } from './rsform-api';\n\nconst STARTING_SUB_INDEX = 900; // max semantic index for starting substitution\n\nexport function constructNodeID(type: NodeType, itemID: number): string {\n return type === NodeType.OPERATION ? 'o' + String(itemID) : 'b' + String(itemID);\n}\n\n/** Sorts library items relevant for the specified {@link OperationSchema}. */\nexport function sortItemsForOSS(oss: OperationSchema, items: readonly LibraryItem[]): LibraryItem[] {\n const result = items.filter(item => item.location === oss.location);\n for (const item of items) {\n if (item.visible && item.owner === oss.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\ntype CrossMapping = Map<number, AliasMapping>;\n\n/** Validator for Substitution table. */\nexport class SubstitutionValidator {\n public errors: SubstitutionErrorDescription[] = [];\n public suggestions: Substitution[] = [];\n\n private schemas: RSForm[];\n private substitutions: Substitution[];\n private constituents = new Set<number>();\n private originals = new Set<number>();\n private mapping: CrossMapping = new Map();\n\n private cstByID = new Map<number, Constituenta>();\n private schemaByID = new Map<number, RSForm>();\n private schemaByCst = new Map<number, RSForm>();\n\n constructor(schemas: RSForm[], substitutions: Substitution[]) {\n this.schemas = schemas;\n this.substitutions = substitutions;\n if (schemas.length === 0) {\n return;\n }\n\n for (const schema of schemas) {\n this.schemaByID.set(schema.id, schema);\n this.mapping.set(schema.id, {});\n for (const item of schema.items) {\n this.cstByID.set(item.id, item);\n this.schemaByCst.set(item.id, schema);\n }\n }\n if (substitutions.length === 0) {\n return;\n }\n let index = STARTING_SUB_INDEX;\n for (const item of substitutions) {\n this.constituents.add(item.original);\n this.constituents.add(item.substitution);\n this.originals.add(item.original);\n const original = this.cstByID.get(item.original);\n const substitution = this.cstByID.get(item.substitution);\n if (!original || !substitution) {\n return;\n }\n index++;\n const newAlias = `${substitution.alias[0]}${index}`;\n this.mapping.get(original.schema)![original.alias] = newAlias;\n this.mapping.get(substitution.schema)![substitution.alias] = newAlias;\n }\n }\n\n public validate(): boolean {\n this.errors = [];\n this.suggestions = [];\n this.calculateSuggestions();\n if (this.substitutions.length === 0) {\n return true;\n }\n if (!this.checkTypes()) {\n return false;\n }\n if (!this.checkTypificationCycles()) {\n return false;\n }\n if (!this.checkDefinitionCycles()) {\n return false;\n }\n if (!this.checkSubstitutions()) {\n return false;\n }\n return true;\n }\n\n private calculateSuggestions(): void {\n const candidates = new Map<number, string>();\n const minors = new Set<number>();\n const schemaByCst = new Map<number, RSForm>();\n for (const schema of this.schemas) {\n for (const cst of schema.items) {\n if (this.originals.has(cst.id)) {\n continue;\n }\n if (cst.cst_class === CstClass.BASIC || cst.definition_formal.length === 0) {\n continue;\n }\n const inputs = schema.graph.at(cst.id)!.inputs;\n if (inputs.some(id => !this.constituents.has(id))) {\n continue;\n }\n if (inputs.some(id => this.originals.has(id))) {\n minors.add(cst.id);\n }\n candidates.set(\n cst.id,\n applyAliasMapping(cst.definition_formal, this.mapping.get(schema.id)!).replace(/\\s+/g, '')\n );\n schemaByCst.set(cst.id, schema);\n }\n }\n for (const [key1, value1] of candidates) {\n for (const [key2, value2] of candidates) {\n if (key1 >= key2) {\n continue;\n }\n if (schemaByCst.get(key1) === schemaByCst.get(key2)) {\n continue;\n }\n if (value1 != value2) {\n continue;\n }\n if (minors.has(key2)) {\n this.suggestions.push({\n original: key2,\n substitution: key1\n });\n } else {\n this.suggestions.push({\n original: key1,\n substitution: key2\n });\n }\n }\n }\n }\n\n private checkTypes(): boolean {\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original);\n const substitution = this.cstByID.get(item.substitution);\n if (!original || !substitution) {\n return this.reportError(SubstitutionErrorType.invalidIDs, []);\n }\n if (\n substitution.analysis &&\n original.analysis &&\n (!original.analysis.success || !substitution.analysis.success)\n ) {\n return this.reportError(SubstitutionErrorType.incorrectCst, [substitution.alias, original.alias]);\n }\n switch (substitution.cst_type) {\n case CstType.NOMINAL: {\n if (original.cst_type !== CstType.NOMINAL) {\n return this.reportError(SubstitutionErrorType.invalidNominal, [substitution.alias, original.alias]);\n }\n break;\n }\n case CstType.BASE: {\n if (\n original.cst_type !== CstType.BASE &&\n original.cst_type !== CstType.CONSTANT &&\n original.cst_type !== CstType.NOMINAL\n ) {\n return this.reportError(SubstitutionErrorType.invalidBasic, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.CONSTANT: {\n if (original.cst_type !== CstType.CONSTANT) {\n return this.reportError(SubstitutionErrorType.invalidConstant, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.AXIOM:\n case CstType.STATEMENT: {\n if (original.cst_type !== CstType.AXIOM && original.cst_type !== CstType.STATEMENT) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.FUNCTION: {\n if (original.cst_type !== CstType.FUNCTION) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n case CstType.PREDICATE: {\n if (original.cst_type !== CstType.PREDICATE) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n\n case CstType.TERM:\n case CstType.STRUCTURED: {\n if (\n original.cst_type !== CstType.TERM &&\n original.cst_type !== CstType.STRUCTURED &&\n original.cst_type !== CstType.BASE\n ) {\n return this.reportError(SubstitutionErrorType.invalidClasses, [substitution.alias, original.alias]);\n }\n break;\n }\n }\n }\n return true;\n }\n\n /**\n * Detect cycles among base/constant sets implied by typifications of non-base\n * constituents under the substitution table.\n */\n private checkTypificationCycles(): boolean {\n const graph = new Graph();\n for (const schema of this.schemas) {\n for (const cst of schema.items) {\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT) {\n graph.addNode(cst.id);\n }\n }\n }\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original)!;\n const substitution = this.cstByID.get(item.substitution)!;\n for (const cst of [original, substitution]) {\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT) {\n continue;\n }\n graph.addNode(cst.id);\n if (cst.effectiveType === null) {\n continue;\n }\n const parents = extractBases(cst.effectiveType);\n if (parents.size === 0) {\n continue;\n }\n const schema = this.schemaByID.get(cst.schema)!;\n for (const alias of parents) {\n const parent = schema.cstByAlias.get(alias);\n if (parent) {\n graph.addEdge(parent.id, cst.id);\n }\n }\n }\n graph.addEdge(substitution.id, original.id);\n }\n const cycle = graph.findCycle();\n if (cycle !== null) {\n const cycleMsg = cycle\n .map(id => {\n const cst = this.cstByID.get(id)!;\n const schema = this.schemaByID.get(cst.schema)!;\n return `[${schema.alias}]-${cst.alias}`;\n })\n .join(', ');\n return this.reportError(SubstitutionErrorType.typificationCycle, [cycleMsg]);\n }\n return true;\n }\n\n /**\n * Detect logical cycles in formal definitions after applying the substitution table\n * (e.g. D16 := F2[D15] with identification D15 → D16 yields D16 := F2[D16]).\n */\n private checkDefinitionCycles(): boolean {\n const graph = new Graph();\n for (const schema of this.schemas) {\n for (const [id, node] of schema.graph.nodes) {\n graph.addNode(id);\n for (const output of node.outputs) {\n graph.addEdge(id, output);\n }\n }\n }\n\n const deleted = new Map<number, number>();\n for (const item of this.substitutions) {\n deleted.set(item.original, item.substitution);\n }\n const resolve = (id: number): number => deleted.get(id) ?? id;\n\n const result = new Graph();\n for (const id of graph.nodes.keys()) {\n if (!deleted.has(id)) {\n result.addNode(id);\n }\n }\n for (const substitutionId of deleted.values()) {\n result.addNode(substitutionId);\n }\n\n for (const [id, node] of graph.nodes) {\n for (const output of node.outputs) {\n if (deleted.has(output)) {\n continue;\n }\n result.addEdge(resolve(id), output);\n }\n }\n\n const cycle = result.findCycle();\n if (cycle !== null) {\n const aliases = cycle.map(id => {\n const cst = this.cstByID.get(id);\n if (!cst) {\n return String(id);\n }\n if (this.schemas.length > 1) {\n const schema = this.schemaByID.get(cst.schema);\n return schema ? `[${schema.alias}]-${cst.alias}` : cst.alias;\n }\n return cst.alias;\n });\n return this.reportError(SubstitutionErrorType.definitionCycle, [formatDependencyCycle(aliases)]);\n }\n return true;\n }\n\n private checkSubstitutions(): boolean {\n const baseMappings = this.prepareBaseMappings();\n const typeMappings = this.calculateSubstituteMappings(baseMappings);\n if (typeMappings === null) {\n return false;\n }\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original)!;\n if (\n original.cst_type === CstType.BASE ||\n original.cst_type === CstType.CONSTANT ||\n original.cst_type === CstType.NOMINAL\n ) {\n continue;\n }\n const substitution = this.cstByID.get(item.substitution)!;\n if (original.cst_type === substitution.cst_type && original.cst_class !== CstClass.BASIC) {\n if (!this.checkEqual(original, substitution)) {\n this.reportError(SubstitutionErrorType.unequalExpressions, [substitution.alias, original.alias]);\n // Note: do not interrupt the validation process. Only warn about the problem.\n }\n }\n\n if (original.analysis.success !== substitution.analysis.success) {\n return this.reportError(SubstitutionErrorType.unequalTypification, [substitution.alias, original.alias]);\n }\n if (!original.analysis.success || !substitution.analysis.success) {\n continue;\n }\n\n const originalType = applyTypificationMapping(\n applyAliasMapping(labelType(original.effectiveType), baseMappings.get(original.schema)!),\n typeMappings\n );\n const substitutionType = applyTypificationMapping(\n applyAliasMapping(labelType(substitution.effectiveType), baseMappings.get(substitution.schema)!),\n typeMappings\n );\n if (originalType !== substitutionType) {\n return this.reportError(SubstitutionErrorType.unequalTypification, [substitution.alias, original.alias]);\n }\n }\n return true;\n }\n\n private prepareBaseMappings(): CrossMapping {\n const result: CrossMapping = new Map();\n let baseCount = 0;\n let constCount = 0;\n for (const schema of this.schemas) {\n const mapping: AliasMapping = {};\n for (const cst of schema.items) {\n if (cst.cst_type === CstType.BASE) {\n baseCount++;\n mapping[cst.alias] = `X${baseCount}`;\n } else if (cst.cst_type === CstType.CONSTANT) {\n constCount++;\n mapping[cst.alias] = `C${constCount}`;\n }\n result.set(schema.id, mapping);\n }\n }\n return result;\n }\n\n private calculateSubstituteMappings(baseMappings: CrossMapping): AliasMapping | null {\n const result: AliasMapping = {};\n const processed = new Set<string>();\n for (const item of this.substitutions) {\n const original = this.cstByID.get(item.original)!;\n if (original.cst_type !== CstType.BASE && original.cst_type !== CstType.CONSTANT) {\n continue;\n }\n const originalAlias = baseMappings.get(original.schema)![original.alias];\n\n const substitution = this.cstByID.get(item.substitution)!;\n let substitutionText = '';\n if (substitution.cst_type === original.cst_type || !substitution.effectiveType) {\n substitutionText = baseMappings.get(substitution.schema)![substitution.alias];\n } else {\n const typeText = labelType(substitution.effectiveType);\n substitutionText = applyAliasMapping(typeText, baseMappings.get(substitution.schema)!);\n substitutionText = applyTypificationMapping(substitutionText, result);\n if (!isSetTypification(substitutionText)) {\n this.reportError(SubstitutionErrorType.baseSubstitutionNotSet, [substitution.alias, typeText]);\n return null;\n }\n if (substitutionText.includes('×') || substitutionText.startsWith('ℬℬ')) {\n substitutionText = substitutionText.slice(1);\n } else {\n substitutionText = substitutionText.slice(2, -1);\n }\n }\n for (const prevAlias of processed) {\n result[prevAlias] = applyTypificationMapping(result[prevAlias], { [originalAlias]: substitutionText });\n }\n result[originalAlias] = substitutionText;\n processed.add(originalAlias);\n }\n return result;\n }\n\n private checkEqual(\n left: FormalOrderFields & { schema: number },\n right: FormalOrderFields & { schema: number }\n ): boolean {\n const schema1 = this.schemaByID.get(left.schema)!;\n const inputs1 = schema1.graph.at(left.id)!.inputs;\n if (inputs1.some(id => !this.constituents.has(id))) {\n return false;\n }\n const schema2 = this.schemaByID.get(right.schema)!;\n const inputs2 = schema2.graph.at(right.id)!.inputs;\n if (inputs2.some(id => !this.constituents.has(id))) {\n return false;\n }\n const expression1 = applyAliasMapping(left.definition_formal, this.mapping.get(schema1.id)!);\n const expression2 = applyAliasMapping(right.definition_formal, this.mapping.get(schema2.id)!);\n return expression1.replace(/\\s+/g, '') === expression2.replace(/\\s+/g, '');\n }\n\n private reportError(code: SubstitutionErrorType, params: string[]): boolean {\n this.errors.push({\n code,\n params\n });\n return false;\n }\n}\n\n/** Filter relocate candidates from gives schema. */\nexport function getRelocateCandidates(\n source: number,\n destination: number,\n schema: RSForm,\n oss: OperationSchema\n): Constituenta[] {\n const destinationSchema = oss.operationByID.get(destination)?.result;\n if (!destinationSchema) {\n return [];\n }\n const node = oss.graph.at(source);\n if (!node) {\n return [];\n }\n\n if (node.outputs.includes(destination)) {\n return schema.items;\n }\n\n const addedCst = schema.items.filter(item => !item.is_inherited).map(cst => cst.id);\n\n const unreachableBases: number[] = [];\n for (const cst of schema.items.filter(item => item.is_inherited)) {\n if (cst.parent_schema == destinationSchema) {\n continue;\n }\n const parent = schema.inheritance.find(item => item.child === cst.id && item.child_source === cst.schema)?.parent;\n if (parent) {\n const original = oss.substitutions.find(sub => sub.substitution === parent)?.original;\n if (original) {\n continue;\n }\n }\n unreachableBases.push(cst.id);\n }\n const unreachable = schema.graph.expandAllOutputs(unreachableBases);\n return schema.items.filter(\n cst => cst.parent_schema === destinationSchema || (addedCst.includes(cst.id) && !unreachable.includes(cst.id))\n );\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,qBAAqB;AAE3B,SAAgB,gBAAgB,MAAgB,QAAwB;CACtE,OAAO,SAAS,SAAS,YAAY,MAAM,OAAO,MAAM,IAAI,MAAM,OAAO,MAAM;AACjF;;AAGA,SAAgB,gBAAgB,KAAsB,OAA8C;CAClG,MAAM,SAAS,MAAM,QAAO,SAAQ,KAAK,aAAa,IAAI,QAAQ;CAClE,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,WAAW,KAAK,UAAU,IAAI,SAAS,CAAC,OAAO,SAAS,IAAI,GACnE,OAAO,KAAK,IAAI;CAGpB,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,WAAW,CAAC,OAAO,SAAS,IAAI,GACvC,OAAO,KAAK,IAAI;CAGpB,KAAK,MAAM,QAAQ,OACjB,IAAI,CAAC,OAAO,SAAS,IAAI,GACvB,OAAO,KAAK,IAAI;CAGpB,OAAO;AACT;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AM,mBAA6B,CAAC;CACpC,KAAK,MAAM,OAAO,OAAO,MAAM,QAAO,SAAQ,KAAK,YAAY,GAAG;EAChE,IAAI,IAAI,iBAAiB,mBACvB;EAEF,MAAM,SAAS,OAAO,YAAY,MAAK,SAAQ,KAAK,UAAU,IAAI,MAAM,KAAK,iBAAiB,IAAI,MAAM,CAAC,EAAE;EAC3G,IAAI,QAEF;OADiB,IAAI,cAAc,MAAK,QAAO,IAAI,iBAAiB,MAAM,CAAC,EAAE,UAE3E;EACF;EAEF,iBAAiB,KAAK,IAAI,EAAE;CAC9B;CACA,MAAM,cAAc,OAAO,MAAM,iBAAiB,gBAAgB;CAClE,OAAO,OAAO,MAAM,QAClB,QAAO,IAAI,kBAAkB,qBAAsB,SAAS,SAAS,IAAI,EAAE,KAAK,CAAC,YAAY,SAAS,IAAI,EAAE,CAC9G;AACF"}
|
package/dist/library/oss.js
CHANGED
package/dist/library/rsengine.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { TypeID } from "../rslang/semantic/typification.js";
|
|
2
2
|
import { normalizeType } from "../rslang/labels.js";
|
|
3
3
|
import { CstType } from "./rsform.js";
|
|
4
|
-
import { l as compare } from "../value-
|
|
4
|
+
import { l as compare } from "../value-BDISzQqI.js";
|
|
5
5
|
import { RSCalculator } from "../rslang/eval/calculator.js";
|
|
6
6
|
import "../rslang/index.js";
|
|
7
|
-
import { $ as isFunctional, P as getAnalysisFor, Q as isBasicConcept, Z as isBaseSet } from "../diagnostics-
|
|
7
|
+
import { $ as isFunctional, P as getAnalysisFor, Q as isBasicConcept, Z as isBaseSet } from "../diagnostics-D_4TpAH4.js";
|
|
8
8
|
import { TYPE_BASIC } from "./rsmodel.js";
|
|
9
9
|
import { inferEvalStatus, isInferrable, tryFixValue } from "./rsmodel-api.js";
|
|
10
10
|
//#region src/library/rsengine.ts
|
|
@@ -66,7 +66,8 @@ var RSEngine = class {
|
|
|
66
66
|
getCstStatus(cstID) {
|
|
67
67
|
const cst = this.schema?.cstByID.get(cstID);
|
|
68
68
|
if (!cst) return inferEvalStatus(null, CstType.NOMINAL, false);
|
|
69
|
-
|
|
69
|
+
const value = this.calculator.getValue(cst.alias);
|
|
70
|
+
return inferEvalStatus(value, cst.cst_type, this.calculatedSet.has(cstID), this.invalidData.has(cstID));
|
|
70
71
|
}
|
|
71
72
|
/** Subscribe to value change of {@link Constituenta}. */
|
|
72
73
|
subscribeValue(cstID, callbackFn) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsengine.js","names":[],"sources":["../../src/library/rsengine.ts"],"sourcesContent":["import { type AstNode } from '../parsing';\nimport { type CalculatorEvaluateOptions, type CalculatorResult, RSCalculator, TypeID, type Value } from '../rslang';\nimport { compare } from '../rslang/eval/value';\nimport { normalizeType } from '../rslang/labels';\n\nimport { CstType, type RSForm } from './rsform';\nimport { getAnalysisFor, isBaseSet, isBasicConcept, isFunctional } from './rsform-api';\nimport { type BasicBinding, type BasicsContext, type EvalStatus, type RSModel, TYPE_BASIC } from './rsmodel';\nimport { inferEvalStatus, isInferrable, tryFixValue } from './rsmodel-api';\n\nconst INVALID_TYPE_MARKER = 'INVALID';\n\n/** Services for {@link RSEngine}. */\nexport interface RSEngineServices {\n setCstValue: (args: {\n itemID: number;\n data: { target: number; type: string; data: Value | BasicBinding }[];\n }) => Promise<unknown>;\n clearValues: (args: { itemID: number; data: { items: number[] } }) => Promise<unknown>;\n}\n\n/** Notifications for {@link RSEngine}. */\nexport interface RSEngineNotifications {\n onInvalidSetValue: () => void;\n onCalculationSuccess: (timeSpent: string) => void;\n}\n\n/** Calculation engine for {@link RSModel}. */\nexport class RSEngine {\n public modelID: number;\n public schema: RSForm | null = null;\n public data: RSModel | null = null;\n public calculator = new RSCalculator();\n public basics: BasicsContext = new Map<number, BasicBinding>();\n\n private services: RSEngineServices;\n private notifications: RSEngineNotifications | null;\n private invalidData = new Set<number>();\n private calculatedSet = new Set<number>();\n private valueSubscribers = new Map<number, Set<() => void>>();\n private statusSubscribers = new Map<number, Set<() => void>>();\n private changeSubscribers = new Set<() => void>();\n private changeGeneration = 0;\n private pendingChange = false;\n private coalescedEmitTimeout: ReturnType<typeof setTimeout> | null = null;\n\n constructor(modelID: number, services: RSEngineServices, notifications: RSEngineNotifications | null = null) {\n this.services = services;\n this.notifications = notifications;\n this.modelID = modelID;\n }\n\n /** Updates data for {@link RSEngine}. */\n public loadData(schema: RSForm, model: RSModel): void {\n const oldSchema = this.schema;\n const newSchema = oldSchema !== schema;\n this.schema = schema;\n if (newSchema) {\n const changedCst = this.collectChanged(oldSchema, schema);\n this.prepareAst();\n this.setupEmptySets();\n this.onChangeDefinitions(changedCst);\n }\n if (this.data !== model) {\n this.data = model;\n this.prepareValues();\n }\n this.notifyAll();\n }\n\n /** Updates services for {@link RSEngine}. */\n public updateServices(services: RSEngineServices): void {\n this.services = services;\n }\n\n /** Updates notifications for {@link RSEngine}. */\n public updateNotifications(notifications: RSEngineNotifications | null): void {\n this.notifications = notifications;\n }\n\n /** Gets value of {@link Constituenta}. */\n public getCstValue(cstID: number): Value | null {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst) {\n return null;\n }\n return this.calculator.getValue(cst.alias);\n }\n\n /** Gets status of {@link Constituenta}. */\n public getCstStatus(cstID: number): EvalStatus {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst) {\n return inferEvalStatus(null, CstType.NOMINAL, false);\n }\n const value = this.calculator.getValue(cst.alias);\n return inferEvalStatus(value, cst.cst_type, this.calculatedSet.has(cstID), this.invalidData.has(cstID));\n }\n\n /** Subscribe to value change of {@link Constituenta}. */\n public subscribeValue(cstID: number, callbackFn: () => void): () => void {\n let subs = this.valueSubscribers.get(cstID);\n if (!subs) {\n subs = new Set();\n this.valueSubscribers.set(cstID, subs);\n }\n subs.add(callbackFn);\n return () => {\n const current = this.valueSubscribers.get(cstID);\n if (!current) {\n return;\n }\n current.delete(callbackFn);\n if (current.size === 0) {\n this.valueSubscribers.delete(cstID);\n }\n };\n }\n\n /** Subscribe to status change of {@link Constituenta}. */\n public subscribeStatus(cstID: number, callbackFn: () => void): () => void {\n let subs = this.statusSubscribers.get(cstID);\n if (!subs) {\n subs = new Set();\n this.statusSubscribers.set(cstID, subs);\n }\n subs.add(callbackFn);\n return () => {\n const current = this.statusSubscribers.get(cstID);\n if (!current) {\n return;\n }\n current.delete(callbackFn);\n if (current.size === 0) {\n this.statusSubscribers.delete(cstID);\n }\n };\n }\n\n /**\n * Subscribe to any engine change that can affect evaluation (values, status, or loaded data).\n */\n public subscribeChanges(callbackFn: () => void): () => void {\n this.changeSubscribers.add(callbackFn);\n return () => {\n this.changeSubscribers.delete(callbackFn);\n };\n }\n\n /** Monotonic counter bumped whenever the engine emits a change to {@link RSEngine.subscribeChanges} listeners. */\n public getChangeGeneration(): number {\n return this.changeGeneration;\n }\n\n /**\n * Runs pending {@link RSEngine.subscribeChanges} notifications immediately and clears the coalescing queue.\n * Use after a synchronous batch of engine updates when listeners must observe a bumped {@link getChangeGeneration}\n * in the same turn.\n */\n public flushPendingChanges(): void {\n if (this.coalescedEmitTimeout !== null) {\n clearTimeout(this.coalescedEmitTimeout);\n this.coalescedEmitTimeout = null;\n }\n if (!this.pendingChange) {\n return;\n }\n this.pendingChange = false;\n this.emitChange();\n }\n\n /** Sets value for {@link Constituenta} from {@link Value}. */\n public async setStructureValue(cstID: number, data: Value): Promise<void> {\n const cst = this.schema?.cstByID.get(cstID);\n if (!this.schema || !cst || isInferrable(cst.cst_type)) {\n this.notifications?.onInvalidSetValue();\n return;\n }\n\n const typeStr = cst.effectiveType ? normalizeType(cst.effectiveType) : INVALID_TYPE_MARKER;\n const payload = [{ target: cstID, type: typeStr, data }];\n await this.services.setCstValue({ itemID: this.modelID, data: payload });\n\n if (!cst.effectiveType || !this.calculator.validate(data, cst.effectiveType)) {\n this.invalidData.add(cstID);\n } else {\n this.invalidData.delete(cstID);\n }\n this.calculator.setValue(cst.alias, data);\n this.notifyCst(cstID);\n this.cascadeReset([cstID]);\n }\n\n /** Sets value for {@link Constituenta} from {@link BasicBinding}. */\n public async setBasicValue(cstID: number, data: BasicBinding): Promise<void> {\n const cst = this.schema?.cstByID.get(cstID);\n if (!this.schema || !cst || !isBaseSet(cst.cst_type)) {\n this.notifications?.onInvalidSetValue();\n return;\n }\n const oldValue = this.calculator.getValue(cst.alias);\n const newValue = Object.keys(data).map(Number);\n\n const updateList: Parameters<RSEngineServices['setCstValue']>[0]['data'] = [\n { target: cstID, type: TYPE_BASIC, data }\n ];\n const resetList: number[] = [];\n\n if (oldValue !== null && compare(newValue, oldValue) !== 0) {\n const dependencies = this.schema.graph.expandAllOutputs([cstID]);\n for (const childID of dependencies) {\n const child = this.schema.cstByID.get(childID)!;\n if (child.cst_type === CstType.STRUCTURED && !!child.effectiveType) {\n const value = this.calculator.getValue(child.alias);\n if (value !== null) {\n const fix = tryFixValue(value, child.effectiveType, cst.alias, newValue);\n if (fix === null) {\n resetList.push(childID);\n } else if (fix === true) {\n const typeStr = normalizeType(child.effectiveType);\n updateList.push({ target: childID, type: typeStr, data: [...(value as Value[])] });\n }\n }\n }\n }\n }\n\n if (resetList.length > 0) {\n await Promise.all([\n this.services.setCstValue({ itemID: this.modelID, data: updateList }),\n this.services.clearValues({ itemID: this.modelID, data: { items: resetList } })\n ]);\n } else {\n await this.services.setCstValue({ itemID: this.modelID, data: updateList });\n }\n const changed = [...resetList, ...updateList.map(item => item.target)];\n\n this.basics.set(cstID, data);\n this.calculator.setValue(cst.alias, Object.keys(data).map(Number));\n\n for (const item of resetList) {\n this.calculator.resetValue(this.schema.cstByID.get(item)!.alias);\n this.notifyCst(item);\n }\n for (const updateData of updateList) {\n if (updateData.target !== cstID) {\n this.calculator.setValue(\n this.schema.cstByID.get(updateData.target)!.alias,\n updateData.data as unknown as Value\n );\n this.notifyCst(updateData.target);\n }\n }\n for (const item of changed) {\n this.notifyCst(item);\n }\n this.cascadeReset(changed);\n }\n\n /** Resets value for {@link Constituenta}. */\n public async resetValue(cstID: number): Promise<void> {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst) {\n return;\n }\n await this.services.clearValues({ itemID: this.modelID, data: { items: [cstID] } });\n this.calculator.resetValue(cst.alias);\n this.basics.delete(cstID);\n this.calculatedSet.delete(cstID);\n this.invalidData.delete(cstID);\n this.notifyCst(cstID);\n }\n\n /** Evaluates expression for {@link RSEngine}. */\n public evaluateExpression(expression: string, cstType: CstType): CalculatorResult {\n return getEvaluationFor(expression, cstType, this.schema!, this.calculator);\n }\n\n /** Evaluates AST for {@link RSEngine}. */\n public evaluateAst(ast: AstNode, options?: CalculatorEvaluateOptions): CalculatorResult {\n return this.calculator.evaluateFull(ast, options);\n }\n\n /** Calculates value for {@link Constituenta}. */\n public calculateCst(cstID: number): CalculatorResult {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst || !this.schema) {\n return { value: null, iterations: 0, errors: [], cacheHits: 0 };\n }\n\n if (!this.calculatedSet.has(cstID)) {\n const predecessors = this.schema.graph.expandAllInputs([cstID]);\n this.prepareEvaluation(predecessors);\n }\n const result = getEvaluationFor(cst.definition_formal, cst.cst_type, this.schema, this.calculator);\n\n if (result.value === null) {\n this.calculator.resetValue(cst.alias);\n } else {\n this.calculator.setValue(cst.alias, result.value);\n }\n\n this.calculatedSet.add(cstID);\n this.notifyCst(cstID);\n\n return result;\n }\n\n /** Recalculate model for all inferrable expressions. */\n recalculateAll(): void {\n const start = performance.now();\n this.calculatedSet.clear();\n this.recalculateInternal();\n const end = performance.now();\n const timeSpent = ((end - start) / 1000).toFixed(2);\n this.notifications?.onCalculationSuccess(timeSpent);\n }\n\n /** Notify subscribers about value and status change of {@link Constituenta}. */\n private notifyCst(cstID: number) {\n this.notifyStatus(cstID);\n this.notifyValue(cstID);\n this.scheduleCoalescedEmitChange();\n }\n\n /** Notify all subscribers about value change. */\n private notifyValue(cstID: number) {\n const subs = this.valueSubscribers.get(cstID);\n if (subs) {\n for (const cb of subs) cb();\n }\n }\n\n /** Notify all subscribers about status change. */\n private notifyStatus(cstID: number) {\n const subs = this.statusSubscribers.get(cstID);\n if (subs) {\n for (const cb of subs) cb();\n }\n }\n\n /** Notify all subscribers about value and status change. */\n private notifyAll(): void {\n for (const subs of this.valueSubscribers.values()) {\n for (const cb of subs) cb();\n }\n for (const subs of this.statusSubscribers.values()) {\n for (const cb of subs) cb();\n }\n this.scheduleCoalescedEmitChange();\n }\n\n private scheduleCoalescedEmitChange(): void {\n this.pendingChange = true;\n if (this.coalescedEmitTimeout !== null) {\n return;\n }\n this.coalescedEmitTimeout = setTimeout(\n function runCoalescedEmitChange(this: RSEngine) {\n this.coalescedEmitTimeout = null;\n if (!this.pendingChange) {\n return;\n }\n this.pendingChange = false;\n this.emitChange();\n }.bind(this),\n 0\n );\n }\n\n private emitChange(): void {\n this.changeGeneration += 1;\n for (const cb of this.changeSubscribers) {\n cb();\n }\n }\n\n private prepareAst(): void {\n this.calculator.clearAllAst();\n const functions = this.schema!.items.filter(cst => isFunctional(cst.cst_type) && cst.analysis?.success);\n for (const cst of functions) {\n const fullAnalysis = getAnalysisFor(cst.definition_formal, cst.cst_type, this.schema!);\n if (fullAnalysis.ast) {\n this.calculator.setAST(cst.alias, fullAnalysis.ast);\n }\n }\n }\n\n private prepareValues(): void {\n this.basics.clear();\n this.invalidData.clear();\n this.calculatedSet.clear();\n\n for (const item of this.data!.items) {\n const cst = this.schema!.cstByID.get(item.id)!;\n if (item.type === TYPE_BASIC) {\n if (cst.cst_type !== CstType.BASE && cst.cst_type !== CstType.CONSTANT) {\n throw new Error(`Invalid data for ${cst.alias}`);\n }\n const data = item.value as BasicBinding;\n this.basics.set(cst.id, data);\n this.calculator.setValue(cst.alias, Object.keys(data).map(Number));\n }\n }\n for (const item of this.data!.items) {\n const cst = this.schema!.cstByID.get(item.id)!;\n if (item.type !== TYPE_BASIC) {\n this.calculator.setValue(cst.alias, item.value as Value);\n if (!cst.effectiveType || !this.calculator.validate(item.value as Value, cst.effectiveType)) {\n this.invalidData.add(item.id);\n }\n }\n }\n this.setupEmptySets();\n }\n\n private setupEmptySets(): void {\n for (const cst of this.schema!.items) {\n if (isBasicConcept(cst.cst_type) && this.schema!.analyzer.getType(cst.alias)?.typeID === TypeID.collection) {\n if (this.calculator.getValue(cst.alias) === null) {\n this.calculator.setValue(cst.alias, []);\n }\n }\n }\n }\n\n private collectChanged(previousSchema: RSForm | null, nextSchema: RSForm): number[] {\n if (!previousSchema) {\n return [];\n }\n const changedIDs: number[] = [];\n for (const cst of nextSchema.items) {\n const prev = previousSchema.cstByID.get(cst.id);\n if (prev && (prev.definition_formal !== cst.definition_formal || prev.alias !== cst.alias)) {\n changedIDs.push(cst.id);\n }\n }\n return changedIDs;\n }\n\n private onChangeDefinitions(cstIDs: number[]): void {\n if (!this.schema || cstIDs.length === 0) {\n return;\n }\n for (const cstID of cstIDs) {\n const cst = this.schema.cstByID.get(cstID);\n if (!cst || !isInferrable(cst.cst_type)) {\n continue;\n }\n this.calculatedSet.delete(cstID);\n this.calculator.resetValue(cst.alias);\n this.notifyCst(cstID);\n }\n this.cascadeReset(cstIDs);\n }\n\n private cascadeReset(cstIDs: number[]): void {\n if (!this.schema) {\n return;\n }\n const dependencies = this.schema.graph.expandAllOutputs(cstIDs);\n for (const cstID of dependencies) {\n const cst = this.schema.cstByID.get(cstID);\n if (!cst || !isInferrable(cst.cst_type)) {\n continue;\n }\n this.calculatedSet.delete(cstID);\n this.calculator.resetValue(this.schema.cstByID.get(cstID)!.alias);\n this.notifyCst(cstID);\n }\n }\n\n private prepareEvaluation(dependencies: number[]): void {\n for (const cstID of this.schema!.graph.topologicalOrder()) {\n if (dependencies.includes(cstID)) {\n const cst = this.schema!.cstByID.get(cstID)!;\n if (isInferrable(cst.cst_type)) {\n const value = fastEvaluation(cst.definition_formal, cst.cst_type, this.schema!, this.calculator);\n if (value !== null) {\n this.calculator.setValue(cst.alias, value);\n } else {\n this.calculator.resetValue(cst.alias);\n }\n this.notifyCst(cstID);\n }\n this.calculatedSet.add(cstID);\n }\n }\n }\n\n private recalculateInternal(): void {\n const processedIDs = [];\n for (const cst of this.schema!.cstByID.values()) {\n if (isInferrable(cst.cst_type)) {\n this.calculator.resetValue(cst.alias);\n }\n }\n\n for (const cstID of this.schema!.graph.topologicalOrder()) {\n processedIDs.push(cstID);\n const cst = this.schema!.cstByID.get(cstID)!;\n if (isInferrable(cst.cst_type)) {\n const value = fastEvaluation(cst.definition_formal, cst.cst_type, this.schema!, this.calculator);\n this.calculatedSet.add(cstID);\n if (value !== null) {\n this.calculator.setValue(cst.alias, value);\n }\n }\n }\n this.notifyAll();\n }\n}\n\n// ==== Internal functions ==== /\n\n/** Evaluates expression for {@link Constituenta}, including error handling. */\nfunction getEvaluationFor(\n expression: string,\n cstType: CstType,\n schema: RSForm,\n calculator: RSCalculator\n): CalculatorResult {\n const parse = getAnalysisFor(expression, cstType, schema);\n if (!parse.success || !parse.ast) {\n return {\n value: null,\n iterations: 0,\n cacheHits: 0,\n errors: parse.errors\n };\n }\n const result = calculator.evaluateFull(parse.ast);\n return {\n value: result.value,\n iterations: result.iterations,\n cacheHits: result.cacheHits,\n errors: [...parse.errors, ...result.errors]\n };\n}\n\n/** Evaluates expression for {@link RSModel}. */\nfunction fastEvaluation(expression: string, cstType: CstType, schema: RSForm, calculator: RSCalculator): Value | null {\n const parse = getAnalysisFor(expression, cstType, schema);\n if (!parse.success || !parse.ast) {\n return null;\n }\n return calculator.evaluateFast(parse.ast);\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,sBAAsB;;AAkB5B,IAAa,WAAb,MAAsB;CACpB;CACA,SAA+B;CAC/B,OAA8B;CAC9B,aAAoB,IAAI,aAAa;CACrC,yBAA+B,IAAI,IAA0B;CAE7D;CACA;CACA,8BAAsB,IAAI,IAAY;CACtC,gCAAwB,IAAI,IAAY;CACxC,mCAA2B,IAAI,IAA6B;CAC5D,oCAA4B,IAAI,IAA6B;CAC7D,oCAA4B,IAAI,IAAgB;CAChD,mBAA2B;CAC3B,gBAA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,KAAK;GAC1C,IAAI,aAAa,IAAI,QAAQ,GAAG;IAC9B,MAAM,QAAQ,eAAe,IAAI,mBAAmB,IAAI,UAAU,KAAK,QAAS,KAAK,UAAU;IAC/F,KAAK,cAAc,IAAI,KAAK;IAC5B,IAAI,UAAU,MACZ,KAAK,WAAW,SAAS,IAAI,OAAO,KAAK;GAE7C;EACF;EACA,KAAK,UAAU;CACjB;AACF;;AAKA,SAAS,iBACP,YACA,SACA,QACA,YACkB;CAClB,MAAM,QAAQ,eAAe,YAAY,SAAS,MAAM;CACxD,IAAI,CAAC,MAAM,WAAW,CAAC,MAAM,KAC3B,OAAO;EACL,OAAO;EACP,YAAY;EACZ,WAAW;EACX,QAAQ,MAAM;CAChB;CAEF,MAAM,SAAS,WAAW,aAAa,MAAM,GAAG;CAChD,OAAO;EACL,OAAO,OAAO;EACd,YAAY,OAAO;EACnB,WAAW,OAAO;EAClB,QAAQ,CAAC,GAAG,MAAM,QAAQ,GAAG,OAAO,MAAM;CAC5C;AACF;;AAGA,SAAS,eAAe,YAAoB,SAAkB,QAAgB,YAAwC;CACpH,MAAM,QAAQ,eAAe,YAAY,SAAS,MAAM;CACxD,IAAI,CAAC,MAAM,WAAW,CAAC,MAAM,KAC3B,OAAO;CAET,OAAO,WAAW,aAAa,MAAM,GAAG;AAC1C"}
|
|
1
|
+
{"version":3,"file":"rsengine.js","names":[],"sources":["../../src/library/rsengine.ts"],"sourcesContent":["import { type AstNode } from '../parsing';\nimport { type CalculatorEvaluateOptions, type CalculatorResult, RSCalculator, TypeID, type Value } from '../rslang';\nimport { compare } from '../rslang/eval/value';\nimport { normalizeType } from '../rslang/labels';\n\nimport { CstType, type RSForm } from './rsform';\nimport { getAnalysisFor, isBaseSet, isBasicConcept, isFunctional } from './rsform-api';\nimport { type BasicBinding, type BasicsContext, type EvalStatus, type RSModel, TYPE_BASIC } from './rsmodel';\nimport { inferEvalStatus, isInferrable, tryFixValue } from './rsmodel-api';\n\nconst INVALID_TYPE_MARKER = 'INVALID';\n\n/** Services for {@link RSEngine}. */\nexport interface RSEngineServices {\n setCstValue: (args: {\n itemID: number;\n data: { target: number; type: string; data: Value | BasicBinding }[];\n }) => Promise<unknown>;\n clearValues: (args: { itemID: number; data: { items: number[] } }) => Promise<unknown>;\n}\n\n/** Notifications for {@link RSEngine}. */\nexport interface RSEngineNotifications {\n onInvalidSetValue: () => void;\n onCalculationSuccess: (timeSpent: string) => void;\n}\n\n/** Calculation engine for {@link RSModel}. */\nexport class RSEngine {\n public modelID: number;\n public schema: RSForm | null = null;\n public data: RSModel | null = null;\n public calculator = new RSCalculator();\n public basics: BasicsContext = new Map<number, BasicBinding>();\n\n private services: RSEngineServices;\n private notifications: RSEngineNotifications | null;\n private invalidData = new Set<number>();\n private calculatedSet = new Set<number>();\n private valueSubscribers = new Map<number, Set<() => void>>();\n private statusSubscribers = new Map<number, Set<() => void>>();\n private changeSubscribers = new Set<() => void>();\n private changeGeneration = 0;\n private pendingChange = false;\n private coalescedEmitTimeout: ReturnType<typeof setTimeout> | null = null;\n\n constructor(modelID: number, services: RSEngineServices, notifications: RSEngineNotifications | null = null) {\n this.services = services;\n this.notifications = notifications;\n this.modelID = modelID;\n }\n\n /** Updates data for {@link RSEngine}. */\n public loadData(schema: RSForm, model: RSModel): void {\n const oldSchema = this.schema;\n const newSchema = oldSchema !== schema;\n this.schema = schema;\n if (newSchema) {\n const changedCst = this.collectChanged(oldSchema, schema);\n this.prepareAst();\n this.setupEmptySets();\n this.onChangeDefinitions(changedCst);\n }\n if (this.data !== model) {\n this.data = model;\n this.prepareValues();\n }\n this.notifyAll();\n }\n\n /** Updates services for {@link RSEngine}. */\n public updateServices(services: RSEngineServices): void {\n this.services = services;\n }\n\n /** Updates notifications for {@link RSEngine}. */\n public updateNotifications(notifications: RSEngineNotifications | null): void {\n this.notifications = notifications;\n }\n\n /** Gets value of {@link Constituenta}. */\n public getCstValue(cstID: number): Value | null {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst) {\n return null;\n }\n return this.calculator.getValue(cst.alias);\n }\n\n /** Gets status of {@link Constituenta}. */\n public getCstStatus(cstID: number): EvalStatus {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst) {\n return inferEvalStatus(null, CstType.NOMINAL, false);\n }\n const value = this.calculator.getValue(cst.alias);\n return inferEvalStatus(value, cst.cst_type, this.calculatedSet.has(cstID), this.invalidData.has(cstID));\n }\n\n /** Subscribe to value change of {@link Constituenta}. */\n public subscribeValue(cstID: number, callbackFn: () => void): () => void {\n let subs = this.valueSubscribers.get(cstID);\n if (!subs) {\n subs = new Set();\n this.valueSubscribers.set(cstID, subs);\n }\n subs.add(callbackFn);\n return () => {\n const current = this.valueSubscribers.get(cstID);\n if (!current) {\n return;\n }\n current.delete(callbackFn);\n if (current.size === 0) {\n this.valueSubscribers.delete(cstID);\n }\n };\n }\n\n /** Subscribe to status change of {@link Constituenta}. */\n public subscribeStatus(cstID: number, callbackFn: () => void): () => void {\n let subs = this.statusSubscribers.get(cstID);\n if (!subs) {\n subs = new Set();\n this.statusSubscribers.set(cstID, subs);\n }\n subs.add(callbackFn);\n return () => {\n const current = this.statusSubscribers.get(cstID);\n if (!current) {\n return;\n }\n current.delete(callbackFn);\n if (current.size === 0) {\n this.statusSubscribers.delete(cstID);\n }\n };\n }\n\n /**\n * Subscribe to any engine change that can affect evaluation (values, status, or loaded data).\n */\n public subscribeChanges(callbackFn: () => void): () => void {\n this.changeSubscribers.add(callbackFn);\n return () => {\n this.changeSubscribers.delete(callbackFn);\n };\n }\n\n /** Monotonic counter bumped whenever the engine emits a change to {@link RSEngine.subscribeChanges} listeners. */\n public getChangeGeneration(): number {\n return this.changeGeneration;\n }\n\n /**\n * Runs pending {@link RSEngine.subscribeChanges} notifications immediately and clears the coalescing queue.\n * Use after a synchronous batch of engine updates when listeners must observe a bumped {@link getChangeGeneration}\n * in the same turn.\n */\n public flushPendingChanges(): void {\n if (this.coalescedEmitTimeout !== null) {\n clearTimeout(this.coalescedEmitTimeout);\n this.coalescedEmitTimeout = null;\n }\n if (!this.pendingChange) {\n return;\n }\n this.pendingChange = false;\n this.emitChange();\n }\n\n /** Sets value for {@link Constituenta} from {@link Value}. */\n public async setStructureValue(cstID: number, data: Value): Promise<void> {\n const cst = this.schema?.cstByID.get(cstID);\n if (!this.schema || !cst || isInferrable(cst.cst_type)) {\n this.notifications?.onInvalidSetValue();\n return;\n }\n\n const typeStr = cst.effectiveType ? normalizeType(cst.effectiveType) : INVALID_TYPE_MARKER;\n const payload = [{ target: cstID, type: typeStr, data }];\n await this.services.setCstValue({ itemID: this.modelID, data: payload });\n\n if (!cst.effectiveType || !this.calculator.validate(data, cst.effectiveType)) {\n this.invalidData.add(cstID);\n } else {\n this.invalidData.delete(cstID);\n }\n this.calculator.setValue(cst.alias, data);\n this.notifyCst(cstID);\n this.cascadeReset([cstID]);\n }\n\n /** Sets value for {@link Constituenta} from {@link BasicBinding}. */\n public async setBasicValue(cstID: number, data: BasicBinding): Promise<void> {\n const cst = this.schema?.cstByID.get(cstID);\n if (!this.schema || !cst || !isBaseSet(cst.cst_type)) {\n this.notifications?.onInvalidSetValue();\n return;\n }\n const oldValue = this.calculator.getValue(cst.alias);\n const newValue = Object.keys(data).map(Number);\n\n const updateList: Parameters<RSEngineServices['setCstValue']>[0]['data'] = [\n { target: cstID, type: TYPE_BASIC, data }\n ];\n const resetList: number[] = [];\n\n if (oldValue !== null && compare(newValue, oldValue) !== 0) {\n const dependencies = this.schema.graph.expandAllOutputs([cstID]);\n for (const childID of dependencies) {\n const child = this.schema.cstByID.get(childID)!;\n if (child.cst_type === CstType.STRUCTURED && !!child.effectiveType) {\n const value = this.calculator.getValue(child.alias);\n if (value !== null) {\n const fix = tryFixValue(value, child.effectiveType, cst.alias, newValue);\n if (fix === null) {\n resetList.push(childID);\n } else if (fix === true) {\n const typeStr = normalizeType(child.effectiveType);\n updateList.push({ target: childID, type: typeStr, data: [...(value as Value[])] });\n }\n }\n }\n }\n }\n\n if (resetList.length > 0) {\n await Promise.all([\n this.services.setCstValue({ itemID: this.modelID, data: updateList }),\n this.services.clearValues({ itemID: this.modelID, data: { items: resetList } })\n ]);\n } else {\n await this.services.setCstValue({ itemID: this.modelID, data: updateList });\n }\n const changed = [...resetList, ...updateList.map(item => item.target)];\n\n this.basics.set(cstID, data);\n this.calculator.setValue(cst.alias, Object.keys(data).map(Number));\n\n for (const item of resetList) {\n this.calculator.resetValue(this.schema.cstByID.get(item)!.alias);\n this.notifyCst(item);\n }\n for (const updateData of updateList) {\n if (updateData.target !== cstID) {\n this.calculator.setValue(\n this.schema.cstByID.get(updateData.target)!.alias,\n updateData.data as unknown as Value\n );\n this.notifyCst(updateData.target);\n }\n }\n for (const item of changed) {\n this.notifyCst(item);\n }\n this.cascadeReset(changed);\n }\n\n /** Resets value for {@link Constituenta}. */\n public async resetValue(cstID: number): Promise<void> {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst) {\n return;\n }\n await this.services.clearValues({ itemID: this.modelID, data: { items: [cstID] } });\n this.calculator.resetValue(cst.alias);\n this.basics.delete(cstID);\n this.calculatedSet.delete(cstID);\n this.invalidData.delete(cstID);\n this.notifyCst(cstID);\n }\n\n /** Evaluates expression for {@link RSEngine}. */\n public evaluateExpression(expression: string, cstType: CstType): CalculatorResult {\n return getEvaluationFor(expression, cstType, this.schema!, this.calculator);\n }\n\n /** Evaluates AST for {@link RSEngine}. */\n public evaluateAst(ast: AstNode, options?: CalculatorEvaluateOptions): CalculatorResult {\n return this.calculator.evaluateFull(ast, options);\n }\n\n /** Calculates value for {@link Constituenta}. */\n public calculateCst(cstID: number): CalculatorResult {\n const cst = this.schema?.cstByID.get(cstID);\n if (!cst || !this.schema) {\n return { value: null, iterations: 0, errors: [], cacheHits: 0 };\n }\n\n if (!this.calculatedSet.has(cstID)) {\n const predecessors = this.schema.graph.expandAllInputs([cstID]);\n this.prepareEvaluation(predecessors);\n }\n const result = getEvaluationFor(cst.definition_formal, cst.cst_type, this.schema, this.calculator);\n\n if (result.value === null) {\n this.calculator.resetValue(cst.alias);\n } else {\n this.calculator.setValue(cst.alias, result.value);\n }\n\n this.calculatedSet.add(cstID);\n this.notifyCst(cstID);\n\n return result;\n }\n\n /** Recalculate model for all inferrable expressions. */\n recalculateAll(): void {\n const start = performance.now();\n this.calculatedSet.clear();\n this.recalculateInternal();\n const end = performance.now();\n const timeSpent = ((end - start) / 1000).toFixed(2);\n this.notifications?.onCalculationSuccess(timeSpent);\n }\n\n /** Notify subscribers about value and status change of {@link Constituenta}. */\n private notifyCst(cstID: number) {\n this.notifyStatus(cstID);\n this.notifyValue(cstID);\n this.scheduleCoalescedEmitChange();\n }\n\n /** Notify all subscribers about value change. */\n private notifyValue(cstID: number) {\n const subs = this.valueSubscribers.get(cstID);\n if (subs) {\n for (const cb of subs) cb();\n }\n }\n\n /** Notify all subscribers about status change. */\n private notifyStatus(cstID: number) {\n const subs = this.statusSubscribers.get(cstID);\n if (subs) {\n for (const cb of subs) cb();\n }\n }\n\n /** Notify all subscribers about value and status change. */\n private notifyAll(): void {\n for (const subs of this.valueSubscribers.values()) {\n for (const cb of subs) cb();\n }\n for (const subs of this.statusSubscribers.values()) {\n for (const cb of subs) cb();\n }\n this.scheduleCoalescedEmitChange();\n }\n\n private scheduleCoalescedEmitChange(): void {\n this.pendingChange = true;\n if (this.coalescedEmitTimeout !== null) {\n return;\n }\n this.coalescedEmitTimeout = setTimeout(\n function runCoalescedEmitChange(this: RSEngine) {\n this.coalescedEmitTimeout = null;\n if (!this.pendingChange) {\n return;\n }\n this.pendingChange = false;\n this.emitChange();\n }.bind(this),\n 0\n );\n }\n\n private emitChange(): void {\n this.changeGeneration += 1;\n for (const cb of this.changeSubscribers) {\n cb();\n }\n }\n\n private prepareAst(): void {\n this.calculator.clearAllAst();\n const functions = this.schema!.items.filter(cst => isFunctional(cst.cst_type) && cst.analysis?.success);\n for (const cst of functions) {\n const fullAnalysis = getAnalysisFor(cst.definition_formal, cst.cst_type, this.schema!);\n if (fullAnalysis.ast) {\n this.calculator.setAST(cst.alias, fullAnalysis.ast);\n }\n }\n }\n\n private prepareValues(): void {\n this.basics.clear();\n this.invalidData.clear();\n this.calculatedSet.clear();\n\n for (const item of this.data!.items) {\n const cst = this.schema!.cstByID.get(item.id)!;\n if (item.type === TYPE_BASIC) {\n if (cst.cst_type !== CstType.BASE && cst.cst_type !== CstType.CONSTANT) {\n throw new Error(`Invalid data for ${cst.alias}`);\n }\n const data = item.value as BasicBinding;\n this.basics.set(cst.id, data);\n this.calculator.setValue(cst.alias, Object.keys(data).map(Number));\n }\n }\n for (const item of this.data!.items) {\n const cst = this.schema!.cstByID.get(item.id)!;\n if (item.type !== TYPE_BASIC) {\n this.calculator.setValue(cst.alias, item.value as Value);\n if (!cst.effectiveType || !this.calculator.validate(item.value as Value, cst.effectiveType)) {\n this.invalidData.add(item.id);\n }\n }\n }\n this.setupEmptySets();\n }\n\n private setupEmptySets(): void {\n for (const cst of this.schema!.items) {\n if (isBasicConcept(cst.cst_type) && this.schema!.analyzer.getType(cst.alias)?.typeID === TypeID.collection) {\n if (this.calculator.getValue(cst.alias) === null) {\n this.calculator.setValue(cst.alias, []);\n }\n }\n }\n }\n\n private collectChanged(previousSchema: RSForm | null, nextSchema: RSForm): number[] {\n if (!previousSchema) {\n return [];\n }\n const changedIDs: number[] = [];\n for (const cst of nextSchema.items) {\n const prev = previousSchema.cstByID.get(cst.id);\n if (prev && (prev.definition_formal !== cst.definition_formal || prev.alias !== cst.alias)) {\n changedIDs.push(cst.id);\n }\n }\n return changedIDs;\n }\n\n private onChangeDefinitions(cstIDs: number[]): void {\n if (!this.schema || cstIDs.length === 0) {\n return;\n }\n for (const cstID of cstIDs) {\n const cst = this.schema.cstByID.get(cstID);\n if (!cst || !isInferrable(cst.cst_type)) {\n continue;\n }\n this.calculatedSet.delete(cstID);\n this.calculator.resetValue(cst.alias);\n this.notifyCst(cstID);\n }\n this.cascadeReset(cstIDs);\n }\n\n private cascadeReset(cstIDs: number[]): void {\n if (!this.schema) {\n return;\n }\n const dependencies = this.schema.graph.expandAllOutputs(cstIDs);\n for (const cstID of dependencies) {\n const cst = this.schema.cstByID.get(cstID);\n if (!cst || !isInferrable(cst.cst_type)) {\n continue;\n }\n this.calculatedSet.delete(cstID);\n this.calculator.resetValue(this.schema.cstByID.get(cstID)!.alias);\n this.notifyCst(cstID);\n }\n }\n\n private prepareEvaluation(dependencies: number[]): void {\n for (const cstID of this.schema!.graph.topologicalOrder()) {\n if (dependencies.includes(cstID)) {\n const cst = this.schema!.cstByID.get(cstID)!;\n if (isInferrable(cst.cst_type)) {\n const value = fastEvaluation(cst.definition_formal, cst.cst_type, this.schema!, this.calculator);\n if (value !== null) {\n this.calculator.setValue(cst.alias, value);\n } else {\n this.calculator.resetValue(cst.alias);\n }\n this.notifyCst(cstID);\n }\n this.calculatedSet.add(cstID);\n }\n }\n }\n\n private recalculateInternal(): void {\n const processedIDs = [];\n for (const cst of this.schema!.cstByID.values()) {\n if (isInferrable(cst.cst_type)) {\n this.calculator.resetValue(cst.alias);\n }\n }\n\n for (const cstID of this.schema!.graph.topologicalOrder()) {\n processedIDs.push(cstID);\n const cst = this.schema!.cstByID.get(cstID)!;\n if (isInferrable(cst.cst_type)) {\n const value = fastEvaluation(cst.definition_formal, cst.cst_type, this.schema!, this.calculator);\n this.calculatedSet.add(cstID);\n if (value !== null) {\n this.calculator.setValue(cst.alias, value);\n }\n }\n }\n this.notifyAll();\n }\n}\n\n// ==== Internal functions ==== /\n\n/** Evaluates expression for {@link Constituenta}, including error handling. */\nfunction getEvaluationFor(\n expression: string,\n cstType: CstType,\n schema: RSForm,\n calculator: RSCalculator\n): CalculatorResult {\n const parse = getAnalysisFor(expression, cstType, schema);\n if (!parse.success || !parse.ast) {\n return {\n value: null,\n iterations: 0,\n cacheHits: 0,\n errors: parse.errors\n };\n }\n const result = calculator.evaluateFull(parse.ast);\n return {\n value: result.value,\n iterations: result.iterations,\n cacheHits: result.cacheHits,\n errors: [...parse.errors, ...result.errors]\n };\n}\n\n/** Evaluates expression for {@link RSModel}. */\nfunction fastEvaluation(expression: string, cstType: CstType, schema: RSForm, calculator: RSCalculator): Value | null {\n const parse = getAnalysisFor(expression, cstType, schema);\n if (!parse.success || !parse.ast) {\n return null;\n }\n return calculator.evaluateFast(parse.ast);\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,sBAAsB;;AAkB5B,IAAa,WAAb,MAAsB;CACpB;CACA,SAA+B;CAC/B,OAA8B;CAC9B,aAAoB,IAAI,aAAa;CACrC,yBAA+B,IAAI,IAA0B;CAE7D;CACA;CACA,8BAAsB,IAAI,IAAY;CACtC,gCAAwB,IAAI,IAAY;CACxC,mCAA2B,IAAI,IAA6B;CAC5D,oCAA4B,IAAI,IAA6B;CAC7D,oCAA4B,IAAI,IAAgB;CAChD,mBAA2B;CAC3B,gBAAwB;CACxB,uBAAqE;CAErE,YAAY,SAAiB,UAA4B,gBAA8C,MAAM;EAC3G,KAAK,WAAW;EAChB,KAAK,gBAAgB;EACrB,KAAK,UAAU;CACjB;;CAGA,SAAgB,QAAgB,OAAsB;EACpD,MAAM,YAAY,KAAK;EACvB,MAAM,YAAY,cAAc;EAChC,KAAK,SAAS;EACd,IAAI,WAAW;GACb,MAAM,aAAa,KAAK,eAAe,WAAW,MAAM;GACxD,KAAK,WAAW;GAChB,KAAK,eAAe;GACpB,KAAK,oBAAoB,UAAU;EACrC;EACA,IAAI,KAAK,SAAS,OAAO;GACvB,KAAK,OAAO;GACZ,KAAK,cAAc;EACrB;EACA,KAAK,UAAU;CACjB;;CAGA,eAAsB,UAAkC;EACtD,KAAK,WAAW;CAClB;;CAGA,oBAA2B,eAAmD;EAC5E,KAAK,gBAAgB;CACvB;;CAGA,YAAmB,OAA6B;EAC9C,MAAM,MAAM,KAAK,QAAQ,QAAQ,IAAI,KAAK;EAC1C,IAAI,CAAC,KACH,OAAO;EAET,OAAO,KAAK,WAAW,SAAS,IAAI,KAAK;CAC3C;;CAGA,aAAoB,OAA2B;EAC7C,MAA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,YAAY,SAAS,MAAM;CACxD,IAAI,CAAC,MAAM,WAAW,CAAC,MAAM,KAC3B,OAAO;CAET,OAAO,WAAW,aAAa,MAAM,GAAG;AAC1C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as isFunctional, A as normalizeExpression, B as buildSequentialAliasMapping, C as isSchemaIssue, D as inferStatus, E as applyFilterCategory, F as refineAnalysisForDependencyCycles, G as validateNewAlias, H as maxAliasIndex, I as addAliasReference, J as getCstTypePrefix, K as canHaveManualTypification, L as allocateImportAliases, M as importAttributions, N as remapAttributionsUnderSubstitution, O as inferTemplate, P as getAnalysisFor, Q as isBasicConcept, R as applyMappingToConstituents, S as calculateSchemaStats, T as restoreConstituentOrder, U as removeAliasReference, V as generateAlias, W as validateAliasFormat, X as inferClass, Y as guessCstType, Z as isBaseSet, _ as applyConstituentSubstitutions, b as getStructureName, c as insertItemAfter, d as inlineSynthesis, et as isLogical, f as sortItemsForInlineSynthesis, g as resolveConstituentTextChange, h as resolveAllConstituentTexts, j as filterAttributions, k as inferTemplatedType, l as moveIdsInOrder, m as buildTermReferenceGraph, nt as typeClassForCstType, p as buildDefinitionReferenceGraph, q as canProduceStructure, tt as isTemplateCst, u as reorderItemsByIds, v as remapSubstitutionsAfterImport, w as buildFormalDependencyGraph, x as inferNewSpawnPosition, y as findCstByStructure, z as argumentValuesToMapping } from "../../diagnostics-
|
|
1
|
+
import { $ as isFunctional, A as normalizeExpression, B as buildSequentialAliasMapping, C as isSchemaIssue, D as inferStatus, E as applyFilterCategory, F as refineAnalysisForDependencyCycles, G as validateNewAlias, H as maxAliasIndex, I as addAliasReference, J as getCstTypePrefix, K as canHaveManualTypification, L as allocateImportAliases, M as importAttributions, N as remapAttributionsUnderSubstitution, O as inferTemplate, P as getAnalysisFor, Q as isBasicConcept, R as applyMappingToConstituents, S as calculateSchemaStats, T as restoreConstituentOrder, U as removeAliasReference, V as generateAlias, W as validateAliasFormat, X as inferClass, Y as guessCstType, Z as isBaseSet, _ as applyConstituentSubstitutions, b as getStructureName, c as insertItemAfter, d as inlineSynthesis, et as isLogical, f as sortItemsForInlineSynthesis, g as resolveConstituentTextChange, h as resolveAllConstituentTexts, j as filterAttributions, k as inferTemplatedType, l as moveIdsInOrder, m as buildTermReferenceGraph, nt as typeClassForCstType, p as buildDefinitionReferenceGraph, q as canProduceStructure, tt as isTemplateCst, u as reorderItemsByIds, v as remapSubstitutionsAfterImport, w as buildFormalDependencyGraph, x as inferNewSpawnPosition, y as findCstByStructure, z as argumentValuesToMapping } from "../../diagnostics-D_4TpAH4.js";
|
|
2
2
|
export { addAliasReference, allocateImportAliases, applyConstituentSubstitutions, applyFilterCategory, applyMappingToConstituents, argumentValuesToMapping, buildDefinitionReferenceGraph, buildFormalDependencyGraph, buildSequentialAliasMapping, buildTermReferenceGraph, calculateSchemaStats, canHaveManualTypification, canProduceStructure, filterAttributions, findCstByStructure, generateAlias, getAnalysisFor, getCstTypePrefix, getStructureName, guessCstType, importAttributions, inferClass, inferNewSpawnPosition, inferStatus, inferTemplate, inferTemplatedType, inlineSynthesis, insertItemAfter, isBaseSet, isBasicConcept, isFunctional, isLogical, isSchemaIssue, isTemplateCst, maxAliasIndex, moveIdsInOrder, normalizeExpression, refineAnalysisForDependencyCycles, remapAttributionsUnderSubstitution, remapSubstitutionsAfterImport, removeAliasReference, reorderItemsByIds, resolveAllConstituentTexts, resolveConstituentTextChange, restoreConstituentOrder, sortItemsForInlineSynthesis, typeClassForCstType, validateAliasFormat, validateNewAlias };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { TypeID } from "../rslang/semantic/typification.js";
|
|
2
2
|
import { CstType } from "./rsform.js";
|
|
3
|
-
import { O as setNestedValue, _ as extractValue, b as isTupleValue, d as set, f as tuple, l as compare, x as makeDefaultValue } from "../value-
|
|
3
|
+
import { O as setNestedValue, _ as extractValue, b as isTupleValue, d as set, f as tuple, l as compare, x as makeDefaultValue } from "../value-BDISzQqI.js";
|
|
4
4
|
import "../rslang/index.js";
|
|
5
|
-
import { Q as isBasicConcept, S as calculateSchemaStats, Z as isBaseSet, s as modelStatusCstDiagnostic } from "../diagnostics-
|
|
5
|
+
import { Q as isBasicConcept, S as calculateSchemaStats, Z as isBaseSet, s as modelStatusCstDiagnostic } from "../diagnostics-D_4TpAH4.js";
|
|
6
6
|
import { EvalStatus } from "./rsmodel.js";
|
|
7
7
|
//#region src/library/rsmodel-api.ts
|
|
8
8
|
const RANDOM_INTEGER_MIN = -100;
|
|
@@ -181,11 +181,13 @@ function deleteValueElement(value, path, type, target) {
|
|
|
181
181
|
if (path.length === 0 && type.typeID !== TypeID.collection) return null;
|
|
182
182
|
const arrayValue = extractValue(value, path);
|
|
183
183
|
if (!Array.isArray(arrayValue)) return null;
|
|
184
|
-
|
|
184
|
+
const updatedArray = [...arrayValue.slice(0, target), ...arrayValue.slice(target + 1)];
|
|
185
|
+
return setNestedValue(value, path, updatedArray);
|
|
185
186
|
}
|
|
186
187
|
function addValueElement(value, path, type, currentType) {
|
|
187
188
|
if (path.length === 0 && type.typeID !== TypeID.collection) return makeDefaultValue(type);
|
|
188
|
-
|
|
189
|
+
const updatedArray = [makeDefaultValue(currentType.base), ...extractValue(value, path) ?? []];
|
|
190
|
+
return setNestedValue(value, path, updatedArray);
|
|
189
191
|
}
|
|
190
192
|
function canGenerateRandomValue(type, basics, cstByAlias) {
|
|
191
193
|
switch (type.typeID) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsmodel-api.js","names":[],"sources":["../../src/library/rsmodel-api.ts"],"sourcesContent":["import { type ExpressionType, TypeID, type Typification, type Value } from '../rslang';\nimport { compare, set, tuple, TUPLE_ID, VALUE_TRUE, type ValuePath } from '../rslang/eval/value';\nimport { extractValue, isTupleValue, makeDefaultValue, setNestedValue } from '../rslang/eval/value-api';\nimport { type EchelonCollection } from '../rslang/semantic/typification';\n\nimport { modelStatusCstDiagnostic } from './diagnostics';\nimport { type RSEngine } from './rsengine';\nimport { CstType, type RSForm } from './rsform';\nimport { calculateSchemaStats, isBaseSet, isBasicConcept, type ModelEvalFields } from './rsform-api';\nimport { type BasicBinding, EvalStatus, type RSModelStats } from './rsmodel';\n\nconst RANDOM_INTEGER_MIN = -100;\nconst RANDOM_INTEGER_MAX = 100;\nconst DEFAULT_RANDOM_SET_ELEMENTS_COUNT = 5;\n\n/** Evaluate if parsed data is a basic binding data. */\nexport function validateBasicBindingData(data: unknown): data is Record<string, string> {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n return false;\n }\n return Object.entries(data).every(([key, value]) => typeof value === 'string' && Number.isInteger(Number(key)));\n}\n\n/** Convert parsed data to a basic binding. */\nexport function toBasicBinding(data: Record<string | number, string>): BasicBinding {\n const result: BasicBinding = {};\n for (const [k, v] of Object.entries(data)) {\n result[Number(k)] = v;\n }\n return result;\n}\n\n/** Evaluate if parsed data is a {@link Value} data. */\nexport function validateValueData(data: unknown): data is Value {\n if (typeof data === 'number') {\n return Number.isFinite(data);\n }\n if (!Array.isArray(data)) {\n return false;\n }\n return data.every(item => validateValueData(item));\n}\n\nexport function generateRandomValue(\n type: Typification,\n basics: Map<number, BasicBinding>,\n cstByAlias: Map<string, { id: number }>,\n setElementsCount: number = DEFAULT_RANDOM_SET_ELEMENTS_COUNT\n): Value | null {\n switch (type.typeID) {\n case TypeID.integer:\n return Math.floor(Math.random() * (RANDOM_INTEGER_MAX - RANDOM_INTEGER_MIN + 1)) + RANDOM_INTEGER_MIN;\n case TypeID.basic: {\n const cst = cstByAlias.get(type.baseID);\n const binding = cst ? basics.get(cst.id) : undefined;\n const ids = Object.keys(binding ?? {}).map(Number);\n if (ids.length === 0) {\n return null;\n }\n return ids[Math.floor(Math.random() * ids.length)];\n }\n case TypeID.tuple: {\n const factors: Value[] = [];\n for (const factor of type.factors) {\n const sample = generateRandomValue(factor, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n factors.push(sample);\n }\n return tuple(factors);\n }\n case TypeID.collection: {\n // Empty set is a valid sample only when the element domain itself is generatable.\n // When the count happens to be 0 we would otherwise skip sampling and miss empty basics.\n if (!canGenerateRandomValue(type.base, basics, cstByAlias)) {\n return null;\n }\n const result: Value[] = [];\n const randomElementsCount = Math.floor(Math.random() * (setElementsCount + 1));\n for (let i = 0; i < randomElementsCount; i++) {\n const sample = generateRandomValue(type.base, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n result.push(sample);\n }\n // Sets must be unique; sampling with replacement can produce duplicates.\n return set(result);\n }\n case TypeID.anyTypification:\n return null;\n }\n}\n\n/** Calculate statistics for {@link RSModel}. */\nexport function calculateModelStats(schema: RSForm, engine: RSEngine, _engineGeneration?: number): RSModelStats {\n const items = schema.items;\n const statusByID = new Map<number, EvalStatus>();\n for (const cst of items) {\n statusByID.set(cst.id, engine.getCstStatus(cst.id));\n }\n return {\n ...calculateSchemaStats(schema),\n base_elements: items.reduce((sum, cst) => sum + countBaseElements(cst, engine), 0),\n count_missing_base: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && isBasicConcept(cst.cst_type) ? 1 : 0),\n 0\n ),\n count_false_axioms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.AXIOM_FALSE ? 1 : 0),\n 0\n ),\n count_invalid_data: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.INVALID_DATA ? 1 : 0),\n 0\n ),\n count_invalid_calculations: items.reduce(\n (sum, cst) =>\n sum +\n (statusByID.get(cst.id) === EvalStatus.EVAL_FAIL || statusByID.get(cst.id) === EvalStatus.NOT_PROCESSED\n ? 1\n : 0),\n 0\n ),\n count_empty_terms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && cst.cst_type === CstType.TERM ? 1 : 0),\n 0\n )\n };\n}\n\n/** Checks whether evaluation status contributes to model status issues. */\nexport function isModelIssue(engine: RSEngine, cst: ModelEvalFields): boolean {\n return modelStatusCstDiagnostic(engine.getCstStatus(cst.id), cst.cst_type) !== null;\n}\n\n/** Filters items whose evaluation status contributes to model issues. */\nexport function getEvalIssueItems(items: readonly ModelEvalFields[], engine: RSEngine): ModelEvalFields[] {\n return items.filter(cst => isModelIssue(engine, cst));\n}\n\n/** Evaluate if {@link CstType} is interpretable. */\nexport function isInterpretable(type: CstType): boolean {\n switch (type) {\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 true;\n\n case CstType.NOMINAL:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is inferrable. */\nexport function isInferrable(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.TERM:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Infers status of a given {@link Value} and {@link CstType}. */\nexport function inferEvalStatus(\n value: Value | null,\n cstType: CstType,\n wasCalculated: boolean = true,\n isInvalid: boolean = false\n): EvalStatus {\n if (isBaseSet(cstType) || cstType === CstType.STRUCTURED) {\n if (isInvalid) {\n return EvalStatus.INVALID_DATA;\n }\n if (value === null || (Array.isArray(value) && value.length === 0)) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n }\n if (!isInferrable(cstType)) {\n return EvalStatus.NO_EVAL;\n }\n if (!wasCalculated) {\n return EvalStatus.NOT_PROCESSED;\n }\n if (value === null) {\n return EvalStatus.EVAL_FAIL;\n }\n if (cstType === CstType.AXIOM && value !== VALUE_TRUE) {\n return EvalStatus.AXIOM_FALSE;\n }\n if (Array.isArray(value) && value.length === 0) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n}\n\n/** Tries to fix value removing invalid base elements not present in the target value.\n * returns null if no fixing is possible.\n * returns true if fixing was successful.\n * returns false if fixing was not needed.\n */\nexport function tryFixValue(\n value: Value,\n type: ExpressionType,\n targetAlias: string,\n targetValue: Value[]\n): boolean | null {\n switch (type.typeID) {\n case TypeID.integer:\n return false;\n case TypeID.basic:\n if (type.baseID !== targetAlias) {\n return false;\n }\n if (typeof value !== 'number') {\n return null;\n }\n if (!targetValue.includes(value)) {\n return null;\n }\n return false;\n case TypeID.tuple: {\n if (!isTupleValue(value)) {\n return null;\n }\n let wasChanged = false;\n for (let i = 0; i < type.factors.length; i++) {\n const componentChanged = tryFixValue(value[i + 1], type.factors[i], targetAlias, targetValue);\n if (componentChanged === null) {\n return null;\n }\n if (componentChanged) {\n wasChanged = true;\n }\n }\n return wasChanged;\n }\n case TypeID.collection:\n if (!Array.isArray(value) || (value.length > 1 && value[0] === TUPLE_ID)) {\n return null;\n }\n let wasChanged = false;\n const removeElements: Value[] = [];\n for (const item of value) {\n const elementChanged = tryFixValue(item, type.base, targetAlias, targetValue);\n if (elementChanged === null || elementChanged === true) {\n wasChanged = true;\n if (elementChanged === null) {\n removeElements.push(item);\n }\n }\n }\n for (const item of removeElements) {\n const index = value.indexOf(item);\n if (index !== -1) {\n value.splice(index, 1);\n }\n }\n if (wasChanged) {\n value.sort((a, b) => compare(a, b));\n let i = 1;\n while (i < value.length) {\n if (compare(value[i], value[i - 1]) === 0) {\n value.splice(i, 1);\n } else {\n i++;\n }\n }\n }\n return wasChanged;\n\n case TypeID.logic:\n case TypeID.anyTypification:\n case TypeID.predicate:\n case TypeID.function:\n return null;\n }\n}\n\nexport function updateValueElement(value: Value | null, path: ValuePath, newValue: number): Value | null {\n return setNestedValue(value, path, newValue);\n}\n\nexport function deleteValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n target: number\n): Value | null {\n if (value === null) {\n return null;\n }\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return null;\n }\n\n const arrayValue = extractValue(value, path);\n if (!Array.isArray(arrayValue)) {\n return null;\n }\n const updatedArray = [...arrayValue.slice(0, target), ...arrayValue.slice(target + 1)];\n return setNestedValue(value, path, updatedArray);\n}\n\nexport function addValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n currentType: Typification\n): Value | null {\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return makeDefaultValue(type);\n }\n\n const newElem = makeDefaultValue((currentType as EchelonCollection).base);\n const arrayValue = (extractValue(value!, path) as Value[] | null) ?? [];\n const updatedArray = [newElem, ...arrayValue];\n return setNestedValue(value, path, updatedArray);\n}\n\n// ========= Internal functions ==========\n\nfunction canGenerateRandomValue(\n type: Typification,\n basics: Map<number, BasicBinding>,\n cstByAlias: Map<string, { id: number }>\n): boolean {\n switch (type.typeID) {\n case TypeID.integer:\n return true;\n case TypeID.basic: {\n const cst = cstByAlias.get(type.baseID);\n const binding = cst ? basics.get(cst.id) : undefined;\n return Object.keys(binding ?? {}).length > 0;\n }\n case TypeID.tuple:\n return type.factors.every(factor => canGenerateRandomValue(factor, basics, cstByAlias));\n case TypeID.collection:\n return canGenerateRandomValue(type.base, basics, cstByAlias);\n case TypeID.anyTypification:\n return false;\n }\n}\n\nfunction countBaseElements(cst: ModelEvalFields, engine: RSEngine): number {\n if (!isBasicConcept(cst.cst_type)) {\n return 0;\n }\n const value = engine.getCstValue(cst.id);\n if (value === null) {\n return 0;\n }\n if (!Array.isArray(value) || value[0] === TUPLE_ID) {\n return 1;\n }\n return value.length;\n}\n"],"mappings":";;;;;;;AAWA,MAAM,qBAAqB;AAE3B,MAAM,oCAAoC;;AAG1C,SAAgB,yBAAyB,MAA+C;CACtF,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACzD,OAAO;CAET,OAAO,OAAO,QAAQ,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,WAAW,OAAO,UAAU,YAAY,OAAO,UAAU,OAAO,GAAG,CAAC,CAAC;AAChH;;AAGA,SAAgB,eAAe,MAAqD;CAClF,MAAM,SAAuB,CAAC;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AAK,MAAM,OAAA,MACjC,OAAO;CAET,OAAO,MAAM;AACf"}
|
|
1
|
+
{"version":3,"file":"rsmodel-api.js","names":[],"sources":["../../src/library/rsmodel-api.ts"],"sourcesContent":["import { type ExpressionType, TypeID, type Typification, type Value } from '../rslang';\nimport { compare, set, tuple, TUPLE_ID, VALUE_TRUE, type ValuePath } from '../rslang/eval/value';\nimport { extractValue, isTupleValue, makeDefaultValue, setNestedValue } from '../rslang/eval/value-api';\nimport { type EchelonCollection } from '../rslang/semantic/typification';\n\nimport { modelStatusCstDiagnostic } from './diagnostics';\nimport { type RSEngine } from './rsengine';\nimport { CstType, type RSForm } from './rsform';\nimport { calculateSchemaStats, isBaseSet, isBasicConcept, type ModelEvalFields } from './rsform-api';\nimport { type BasicBinding, EvalStatus, type RSModelStats } from './rsmodel';\n\nconst RANDOM_INTEGER_MIN = -100;\nconst RANDOM_INTEGER_MAX = 100;\nconst DEFAULT_RANDOM_SET_ELEMENTS_COUNT = 5;\n\n/** Evaluate if parsed data is a basic binding data. */\nexport function validateBasicBindingData(data: unknown): data is Record<string, string> {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n return false;\n }\n return Object.entries(data).every(([key, value]) => typeof value === 'string' && Number.isInteger(Number(key)));\n}\n\n/** Convert parsed data to a basic binding. */\nexport function toBasicBinding(data: Record<string | number, string>): BasicBinding {\n const result: BasicBinding = {};\n for (const [k, v] of Object.entries(data)) {\n result[Number(k)] = v;\n }\n return result;\n}\n\n/** Evaluate if parsed data is a {@link Value} data. */\nexport function validateValueData(data: unknown): data is Value {\n if (typeof data === 'number') {\n return Number.isFinite(data);\n }\n if (!Array.isArray(data)) {\n return false;\n }\n return data.every(item => validateValueData(item));\n}\n\nexport function generateRandomValue(\n type: Typification,\n basics: Map<number, BasicBinding>,\n cstByAlias: Map<string, { id: number }>,\n setElementsCount: number = DEFAULT_RANDOM_SET_ELEMENTS_COUNT\n): Value | null {\n switch (type.typeID) {\n case TypeID.integer:\n return Math.floor(Math.random() * (RANDOM_INTEGER_MAX - RANDOM_INTEGER_MIN + 1)) + RANDOM_INTEGER_MIN;\n case TypeID.basic: {\n const cst = cstByAlias.get(type.baseID);\n const binding = cst ? basics.get(cst.id) : undefined;\n const ids = Object.keys(binding ?? {}).map(Number);\n if (ids.length === 0) {\n return null;\n }\n return ids[Math.floor(Math.random() * ids.length)];\n }\n case TypeID.tuple: {\n const factors: Value[] = [];\n for (const factor of type.factors) {\n const sample = generateRandomValue(factor, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n factors.push(sample);\n }\n return tuple(factors);\n }\n case TypeID.collection: {\n // Empty set is a valid sample only when the element domain itself is generatable.\n // When the count happens to be 0 we would otherwise skip sampling and miss empty basics.\n if (!canGenerateRandomValue(type.base, basics, cstByAlias)) {\n return null;\n }\n const result: Value[] = [];\n const randomElementsCount = Math.floor(Math.random() * (setElementsCount + 1));\n for (let i = 0; i < randomElementsCount; i++) {\n const sample = generateRandomValue(type.base, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n result.push(sample);\n }\n // Sets must be unique; sampling with replacement can produce duplicates.\n return set(result);\n }\n case TypeID.anyTypification:\n return null;\n }\n}\n\n/** Calculate statistics for {@link RSModel}. */\nexport function calculateModelStats(schema: RSForm, engine: RSEngine, _engineGeneration?: number): RSModelStats {\n const items = schema.items;\n const statusByID = new Map<number, EvalStatus>();\n for (const cst of items) {\n statusByID.set(cst.id, engine.getCstStatus(cst.id));\n }\n return {\n ...calculateSchemaStats(schema),\n base_elements: items.reduce((sum, cst) => sum + countBaseElements(cst, engine), 0),\n count_missing_base: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && isBasicConcept(cst.cst_type) ? 1 : 0),\n 0\n ),\n count_false_axioms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.AXIOM_FALSE ? 1 : 0),\n 0\n ),\n count_invalid_data: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.INVALID_DATA ? 1 : 0),\n 0\n ),\n count_invalid_calculations: items.reduce(\n (sum, cst) =>\n sum +\n (statusByID.get(cst.id) === EvalStatus.EVAL_FAIL || statusByID.get(cst.id) === EvalStatus.NOT_PROCESSED\n ? 1\n : 0),\n 0\n ),\n count_empty_terms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && cst.cst_type === CstType.TERM ? 1 : 0),\n 0\n )\n };\n}\n\n/** Checks whether evaluation status contributes to model status issues. */\nexport function isModelIssue(engine: RSEngine, cst: ModelEvalFields): boolean {\n return modelStatusCstDiagnostic(engine.getCstStatus(cst.id), cst.cst_type) !== null;\n}\n\n/** Filters items whose evaluation status contributes to model issues. */\nexport function getEvalIssueItems(items: readonly ModelEvalFields[], engine: RSEngine): ModelEvalFields[] {\n return items.filter(cst => isModelIssue(engine, cst));\n}\n\n/** Evaluate if {@link CstType} is interpretable. */\nexport function isInterpretable(type: CstType): boolean {\n switch (type) {\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 true;\n\n case CstType.NOMINAL:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is inferrable. */\nexport function isInferrable(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.TERM:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Infers status of a given {@link Value} and {@link CstType}. */\nexport function inferEvalStatus(\n value: Value | null,\n cstType: CstType,\n wasCalculated: boolean = true,\n isInvalid: boolean = false\n): EvalStatus {\n if (isBaseSet(cstType) || cstType === CstType.STRUCTURED) {\n if (isInvalid) {\n return EvalStatus.INVALID_DATA;\n }\n if (value === null || (Array.isArray(value) && value.length === 0)) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n }\n if (!isInferrable(cstType)) {\n return EvalStatus.NO_EVAL;\n }\n if (!wasCalculated) {\n return EvalStatus.NOT_PROCESSED;\n }\n if (value === null) {\n return EvalStatus.EVAL_FAIL;\n }\n if (cstType === CstType.AXIOM && value !== VALUE_TRUE) {\n return EvalStatus.AXIOM_FALSE;\n }\n if (Array.isArray(value) && value.length === 0) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n}\n\n/** Tries to fix value removing invalid base elements not present in the target value.\n * returns null if no fixing is possible.\n * returns true if fixing was successful.\n * returns false if fixing was not needed.\n */\nexport function tryFixValue(\n value: Value,\n type: ExpressionType,\n targetAlias: string,\n targetValue: Value[]\n): boolean | null {\n switch (type.typeID) {\n case TypeID.integer:\n return false;\n case TypeID.basic:\n if (type.baseID !== targetAlias) {\n return false;\n }\n if (typeof value !== 'number') {\n return null;\n }\n if (!targetValue.includes(value)) {\n return null;\n }\n return false;\n case TypeID.tuple: {\n if (!isTupleValue(value)) {\n return null;\n }\n let wasChanged = false;\n for (let i = 0; i < type.factors.length; i++) {\n const componentChanged = tryFixValue(value[i + 1], type.factors[i], targetAlias, targetValue);\n if (componentChanged === null) {\n return null;\n }\n if (componentChanged) {\n wasChanged = true;\n }\n }\n return wasChanged;\n }\n case TypeID.collection:\n if (!Array.isArray(value) || (value.length > 1 && value[0] === TUPLE_ID)) {\n return null;\n }\n let wasChanged = false;\n const removeElements: Value[] = [];\n for (const item of value) {\n const elementChanged = tryFixValue(item, type.base, targetAlias, targetValue);\n if (elementChanged === null || elementChanged === true) {\n wasChanged = true;\n if (elementChanged === null) {\n removeElements.push(item);\n }\n }\n }\n for (const item of removeElements) {\n const index = value.indexOf(item);\n if (index !== -1) {\n value.splice(index, 1);\n }\n }\n if (wasChanged) {\n value.sort((a, b) => compare(a, b));\n let i = 1;\n while (i < value.length) {\n if (compare(value[i], value[i - 1]) === 0) {\n value.splice(i, 1);\n } else {\n i++;\n }\n }\n }\n return wasChanged;\n\n case TypeID.logic:\n case TypeID.anyTypification:\n case TypeID.predicate:\n case TypeID.function:\n return null;\n }\n}\n\nexport function updateValueElement(value: Value | null, path: ValuePath, newValue: number): Value | null {\n return setNestedValue(value, path, newValue);\n}\n\nexport function deleteValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n target: number\n): Value | null {\n if (value === null) {\n return null;\n }\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return null;\n }\n\n const arrayValue = extractValue(value, path);\n if (!Array.isArray(arrayValue)) {\n return null;\n }\n const updatedArray = [...arrayValue.slice(0, target), ...arrayValue.slice(target + 1)];\n return setNestedValue(value, path, updatedArray);\n}\n\nexport function addValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n currentType: Typification\n): Value | null {\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return makeDefaultValue(type);\n }\n\n const newElem = makeDefaultValue((currentType as EchelonCollection).base);\n const arrayValue = (extractValue(value!, path) as Value[] | null) ?? [];\n const updatedArray = [newElem, ...arrayValue];\n return setNestedValue(value, path, updatedArray);\n}\n\n// ========= Internal functions ==========\n\nfunction canGenerateRandomValue(\n type: Typification,\n basics: Map<number, BasicBinding>,\n cstByAlias: Map<string, { id: number }>\n): boolean {\n switch (type.typeID) {\n case TypeID.integer:\n return true;\n case TypeID.basic: {\n const cst = cstByAlias.get(type.baseID);\n const binding = cst ? basics.get(cst.id) : undefined;\n return Object.keys(binding ?? {}).length > 0;\n }\n case TypeID.tuple:\n return type.factors.every(factor => canGenerateRandomValue(factor, basics, cstByAlias));\n case TypeID.collection:\n return canGenerateRandomValue(type.base, basics, cstByAlias);\n case TypeID.anyTypification:\n return false;\n }\n}\n\nfunction countBaseElements(cst: ModelEvalFields, engine: RSEngine): number {\n if (!isBasicConcept(cst.cst_type)) {\n return 0;\n }\n const value = engine.getCstValue(cst.id);\n if (value === null) {\n return 0;\n }\n if (!Array.isArray(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AW,CAAC,CAAC,CAAC,CAAC,SAAS;EAC7C;EACA,KAAK,OAAO,OACV,OAAO,KAAK,QAAQ,OAAM,WAAU,uBAAuB,QAAQ,QAAQ,UAAU,CAAC;EACxF,KAAK,OAAO,YACV,OAAO,uBAAuB,KAAK,MAAM,QAAQ,UAAU;EAC7D,KAAK,OAAO,iBACV,OAAO;CACX;AACF;AAEA,SAAS,kBAAkB,KAAsB,QAA0B;CACzE,IAAI,CAAC,eAAe,IAAI,QAAQ,GAC9B,OAAO;CAET,MAAM,QAAQ,OAAO,YAAY,IAAI,EAAE;CACvC,IAAI,UAAU,MACZ,OAAO;CAET,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAA,MACjC,OAAO;CAET,OAAO,MAAM;AACf"}
|
|
@@ -3,7 +3,7 @@ import { labelType } from "../rslang/labels.js";
|
|
|
3
3
|
import { splitTemplateDefinition } from "../rslang/api.js";
|
|
4
4
|
import { CstType } from "./rsform.js";
|
|
5
5
|
import "../rslang/index.js";
|
|
6
|
-
import { y as findCstByStructure } from "../diagnostics-
|
|
6
|
+
import { y as findCstByStructure } from "../diagnostics-D_4TpAH4.js";
|
|
7
7
|
//#region src/library/structure-planner.ts
|
|
8
8
|
/** Structure planner for {@link Constituenta}. */
|
|
9
9
|
var StructurePlanner = class {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lezer-tree.js","names":[],"sources":["../../src/parsing/lezer-tree.ts"],"sourcesContent":["import { type NodeType, type Tree, type TreeCursor } from '@lezer/common';\nexport { type TreeCursor } from '@lezer/common';\n\n/** Represents syntax tree node data. */\nexport interface CMSyntaxNode {\n type: NodeType;\n from: number;\n to: number;\n}\n\n/** Prints tree to compact string. */\nexport function printTree(tree: Tree): string {\n const state = {\n output: '',\n prefixes: [] as string[]\n };\n traverseTree(tree, {\n onEnter: node => {\n state.output += '[';\n state.output += node.type.name;\n },\n onLeave: () => {\n state.output += ']';\n }\n });\n return state.output;\n}\n\n// ======== Internals ========\n\ninterface CursorNode extends CMSyntaxNode {\n isLeaf: boolean;\n}\n\nfunction cursorNode({ type, from, to }: TreeCursor, isLeaf = false): CursorNode {\n return { type, from, to, isLeaf };\n}\n\ninterface TreeTraversalOptions {\n beforeEnter?: (cursor: TreeCursor) => void;\n onEnter: (node: CursorNode) => false | void;\n onLeave?: (node: CursorNode) => false | void;\n}\n\n/** Implements depth-first traversal. */\nfunction traverseTree(tree: Tree, { beforeEnter, onEnter, onLeave }: TreeTraversalOptions) {\n const cursor = tree.cursor();\n for (;;) {\n let node = cursorNode(cursor);\n let leave = false;\n const enter = !node.type.isAnonymous;\n if (enter && beforeEnter) beforeEnter(cursor);\n node.isLeaf = !cursor.firstChild();\n if (enter) {\n leave = true;\n if (onEnter(node) === false) return;\n }\n if (!node.isLeaf) continue;\n for (;;) {\n node = cursorNode(cursor, node.isLeaf);\n if (leave && onLeave) if (onLeave(node) === false) return;\n leave = cursor.type.isAnonymous;\n node.isLeaf = false;\n if (cursor.nextSibling()) break;\n if (!cursor.parent()) return;\n leave = true;\n }\n }\n}\n"],"mappings":";;AAWA,SAAgB,UAAU,MAAoB;CAC5C,MAAM,QAAQ;EACZ,QAAQ;EACR,UAAU,CAAC;CACb;CACA,aAAa,MAAM;EACjB,UAAS,SAAQ;GACf,MAAM,UAAU;GAChB,MAAM,UAAU,KAAK,KAAK;EAC5B;EACA,eAAe;GACb,MAAM,UAAU;EAClB;CACF,CAAC;CACD,OAAO,MAAM;AACf;AAQA,SAAS,WAAW,EAAE,MAAM,MAAM,MAAkB,SAAS,OAAmB;CAC9E,OAAO;EAAE;EAAM;EAAM;EAAI;CAAO;AAClC;;AASA,SAAS,aAAa,MAAY,EAAE,aAAa,SAAS,WAAiC;CACzF,MAAM,SAAS,KAAK,OAAO;CAC3B,SAAS;EACP,IAAI,OAAO,WAAW,MAAM;EAC5B,IAAI,QAAQ;EACZ,MAAM,QAAQ,CAAC,KAAK,KAAK;EACzB,IAAI,SAAS,aAAa,YAAY,MAAM;EAC5C,KAAK,SAAS,CAAC,OAAO,WAAW;EACjC,IAAI,OAAO;GACT,QAAQ;GACR,IAAI,QAAQ,IAAI,MAAM,OAAO;EAC/B;EACA,IAAI,CAAC,KAAK,QAAQ;EAClB,SAAS;GACP,OAAO,WAAW,QAAQ,KAAK,MAAM;GACrC,IAAI,SAAS;
|
|
1
|
+
{"version":3,"file":"lezer-tree.js","names":[],"sources":["../../src/parsing/lezer-tree.ts"],"sourcesContent":["import { type NodeType, type Tree, type TreeCursor } from '@lezer/common';\nexport { type TreeCursor } from '@lezer/common';\n\n/** Represents syntax tree node data. */\nexport interface CMSyntaxNode {\n type: NodeType;\n from: number;\n to: number;\n}\n\n/** Prints tree to compact string. */\nexport function printTree(tree: Tree): string {\n const state = {\n output: '',\n prefixes: [] as string[]\n };\n traverseTree(tree, {\n onEnter: node => {\n state.output += '[';\n state.output += node.type.name;\n },\n onLeave: () => {\n state.output += ']';\n }\n });\n return state.output;\n}\n\n// ======== Internals ========\n\ninterface CursorNode extends CMSyntaxNode {\n isLeaf: boolean;\n}\n\nfunction cursorNode({ type, from, to }: TreeCursor, isLeaf = false): CursorNode {\n return { type, from, to, isLeaf };\n}\n\ninterface TreeTraversalOptions {\n beforeEnter?: (cursor: TreeCursor) => void;\n onEnter: (node: CursorNode) => false | void;\n onLeave?: (node: CursorNode) => false | void;\n}\n\n/** Implements depth-first traversal. */\nfunction traverseTree(tree: Tree, { beforeEnter, onEnter, onLeave }: TreeTraversalOptions) {\n const cursor = tree.cursor();\n for (;;) {\n let node = cursorNode(cursor);\n let leave = false;\n const enter = !node.type.isAnonymous;\n if (enter && beforeEnter) beforeEnter(cursor);\n node.isLeaf = !cursor.firstChild();\n if (enter) {\n leave = true;\n if (onEnter(node) === false) return;\n }\n if (!node.isLeaf) continue;\n for (;;) {\n node = cursorNode(cursor, node.isLeaf);\n if (leave && onLeave) if (onLeave(node) === false) return;\n leave = cursor.type.isAnonymous;\n node.isLeaf = false;\n if (cursor.nextSibling()) break;\n if (!cursor.parent()) return;\n leave = true;\n }\n }\n}\n"],"mappings":";;AAWA,SAAgB,UAAU,MAAoB;CAC5C,MAAM,QAAQ;EACZ,QAAQ;EACR,UAAU,CAAC;CACb;CACA,aAAa,MAAM;EACjB,UAAS,SAAQ;GACf,MAAM,UAAU;GAChB,MAAM,UAAU,KAAK,KAAK;EAC5B;EACA,eAAe;GACb,MAAM,UAAU;EAClB;CACF,CAAC;CACD,OAAO,MAAM;AACf;AAQA,SAAS,WAAW,EAAE,MAAM,MAAM,MAAkB,SAAS,OAAmB;CAC9E,OAAO;EAAE;EAAM;EAAM;EAAI;CAAO;AAClC;;AASA,SAAS,aAAa,MAAY,EAAE,aAAa,SAAS,WAAiC;CACzF,MAAM,SAAS,KAAK,OAAO;CAC3B,SAAS;EACP,IAAI,OAAO,WAAW,MAAM;EAC5B,IAAI,QAAQ;EACZ,MAAM,QAAQ,CAAC,KAAK,KAAK;EACzB,IAAI,SAAS,aAAa,YAAY,MAAM;EAC5C,KAAK,SAAS,CAAC,OAAO,WAAW;EACjC,IAAI,OAAO;GACT,QAAQ;GACR,IAAI,QAAQ,IAAI,MAAM,OAAO;EAC/B;EACA,IAAI,CAAC,KAAK,QAAQ;EAClB,SAAS;GACP,OAAO,WAAW,QAAQ,KAAK,MAAM;GACrC,IAAI,SAAS,SAAa;QAAA,QAAQ,IAAI,MAAM,OAAO;GAAA;GACnD,QAAQ,OAAO,KAAK;GACpB,KAAK,SAAS;GACd,IAAI,OAAO,YAAY,GAAG;GAC1B,IAAI,CAAC,OAAO,OAAO,GAAG;GACtB,QAAQ;EACV;CACF;AACF"}
|
package/dist/rslang/api.js
CHANGED
|
@@ -26,7 +26,8 @@ function isGlobalAlias(value) {
|
|
|
26
26
|
*/
|
|
27
27
|
function parseRSLangExpression(expression) {
|
|
28
28
|
if (!expression.trim()) return null;
|
|
29
|
-
const
|
|
29
|
+
const tree = parser.parse(expression);
|
|
30
|
+
const ast = buildTree(tree.cursor());
|
|
30
31
|
normalizeAST(ast, expression);
|
|
31
32
|
return ast;
|
|
32
33
|
}
|
|
@@ -65,11 +66,13 @@ function splitTemplateDefinition(target) {
|
|
|
65
66
|
for (; start < target.length && target[start] !== "["; ++start);
|
|
66
67
|
if (start < target.length) {
|
|
67
68
|
for (let counter = 0, end = start + 1; end < target.length; ++end) if (target[end] === "[") ++counter;
|
|
68
|
-
else if (target[end] === "]")
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
69
|
+
else if (target[end] === "]") {
|
|
70
|
+
if (counter !== 0) --counter;
|
|
71
|
+
else return {
|
|
72
|
+
head: target.substring(start + 1, end).trim(),
|
|
73
|
+
body: target.substring(end + 1).trim()
|
|
74
|
+
};
|
|
75
|
+
}
|
|
73
76
|
}
|
|
74
77
|
return {
|
|
75
78
|
head: "",
|
package/dist/rslang/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","names":["rslangParser"],"sources":["../../src/rslang/api.ts"],"sourcesContent":["/**\n * Module: API for RSLanguage.\n */\nimport { type AstNode, buildTree } from '../parsing';\n\nimport { normalizeAST } from './parser/normalize';\nimport { parser as rslangParser } from './parser/parser';\nimport { ArgumentsExtractor, type ArgumentsType } from './semantic/arguments-extractor';\nexport { generateExpressionFromAst } from './parser/expression-generator';\n\n/** Represents alias mapping. */\nexport type AliasMapping = Record<string, string>;\n\n// cspell:disable\nconst LOCALS_REGEXP = /[_a-zα-ω][a-zα-ω]*\\d*/g;\nconst GLOBAL_ALIAS_SOURCE = '[XCSADFPTN]\\\\d+';\nconst GLOBALS_REGEXP = new RegExp(GLOBAL_ALIAS_SOURCE, 'g');\nconst GLOBAL_ALIAS_ANCHORED_REGEXP = new RegExp(`^${GLOBAL_ALIAS_SOURCE}$`);\nconst COMPLEX_SYMBOLS_REGEXP = /[∀∃×ℬ;|:]/g;\nconst TYPIFICATION_SET = /^ℬ+\\([ℬ\\(((X|C)\\d+|Z)\\)×]*\\)$/g;\n// cspell:enable\n\n/** Whether {@link value} is a single schema global alias (e.g. `X1`, `F42`). */\nexport function isGlobalAlias(value: string): boolean {\n return GLOBAL_ALIAS_ANCHORED_REGEXP.test(value);\n}\n\n/**\n * Parse a RSLang expression into a normalized AST.\n *\n * Returns `null` for blank input. Parses the original `expression` string so node\n * offsets match the source text (required for slice-based AST walks).\n */\nexport function parseRSLangExpression(expression: string): AstNode | null {\n if (!expression.trim()) {\n return null;\n }\n const tree = rslangParser.parse(expression);\n const ast = buildTree(tree.cursor());\n normalizeAST(ast, expression);\n return ast;\n}\n\n/** Extract arguments from AST. */\nexport function extractArguments(ast: AstNode): ArgumentsType[] {\n return new ArgumentsExtractor().run(ast);\n}\n\n/** Extracts global variable names from a given expression. */\nexport function extractGlobals(expression: string): Set<string> {\n return new Set(expression.match(GLOBALS_REGEXP) ?? []);\n}\n\n/** Check if expression is simple derivation. */\nexport function isSimpleExpression(text: string): boolean {\n return !text.match(COMPLEX_SYMBOLS_REGEXP);\n}\n\n/** Check if expression is set typification. */\nexport function isSetTypification(text: string): boolean {\n return !!text.match(TYPIFICATION_SET);\n}\n\n/**\n * Splits a string containing a template definition into its head and body parts.\n *\n * A template definition is expected to have the following format: `[head] body`.\n * If the input string does not contain the opening square bracket '[', the entire\n * string is treated as the body, and an empty string is assigned to the head.\n * If the opening bracket is present, the function attempts to find the matching\n * closing bracket ']' to determine the head and body parts.\n *\n * @example\n * const template = '[header] body content';\n * const result = splitTemplateDefinition(template);\n * // result: `{ head: 'header', body: 'body content' }`\n */\nexport function splitTemplateDefinition(target: string) {\n let start = 0;\n for (; start < target.length && target[start] !== '['; ++start);\n if (start < target.length) {\n for (let counter = 0, end = start + 1; end < target.length; ++end) {\n if (target[end] === '[') {\n ++counter;\n } else if (target[end] === ']') {\n if (counter !== 0) {\n --counter;\n } else {\n return {\n head: target.substring(start + 1, end).trim(),\n body: target.substring(end + 1).trim()\n };\n }\n }\n }\n }\n return {\n head: '',\n body: target\n };\n}\n\n/**\n * Substitutes values for template arguments in a given expression.\n *\n * This function takes an input mathematical expression and a list of argument values.\n * It replaces template argument placeholders in the expression with their corresponding values\n * from the provided arguments.\n */\nexport function substituteTemplateArgs(expression: string, mapping: AliasMapping): string {\n if (Object.keys(mapping).length === 0) {\n return expression;\n }\n let { head, body } = splitTemplateDefinition(expression);\n body = applyPattern(body, mapping, LOCALS_REGEXP);\n const argTexts = head.split(',').map(text => text.trim());\n head = argTexts\n .filter(arg => [...arg.matchAll(LOCALS_REGEXP)].every(local => local.every(match => !(match in mapping))))\n .join(', ');\n\n if (!head) {\n return body;\n } else {\n return `[${head}] ${body}`;\n }\n}\n\n/** Substitute local parameter aliases in an expression fragment. */\nexport function substituteLocalAliases(expression: string, mapping: AliasMapping): string {\n return applyPattern(expression, mapping, LOCALS_REGEXP);\n}\n\n/** Apply alias mapping. */\nexport function applyAliasMapping(target: string, mapping: AliasMapping): string {\n return applyPattern(target, mapping, GLOBALS_REGEXP);\n}\n\n/** Apply alias typification mapping. */\nexport function applyTypificationMapping(target: string, mapping: AliasMapping): string {\n const modified = applyAliasMapping(target, mapping);\n if (modified === target) {\n return target;\n }\n\n const deleteBrackets: number[] = [];\n const positions: number[] = [];\n const booleans: number[] = [];\n let boolCount: number = 0;\n let stackSize: number = 0;\n\n for (let i = 0; i < modified.length; i++) {\n const char = modified[i];\n if (char === 'ℬ') {\n boolCount++;\n continue;\n }\n if (char === '(') {\n stackSize++;\n positions.push(i);\n booleans.push(boolCount);\n }\n boolCount = 0;\n if (char === ')') {\n if (\n i < modified.length - 1 &&\n modified[i + 1] === ')' &&\n stackSize > 1 &&\n positions[stackSize - 2] + booleans[stackSize - 1] + 1 === positions[stackSize - 1]\n ) {\n deleteBrackets.push(i);\n deleteBrackets.push(positions[stackSize - 2]);\n }\n if (i === modified.length - 1 && stackSize === 1 && positions[0] === 0) {\n deleteBrackets.push(i);\n deleteBrackets.push(positions[0]);\n }\n stackSize--;\n positions.pop();\n booleans.pop();\n }\n }\n\n let result = '';\n for (let i = 0; i < modified.length; i++) {\n if (!deleteBrackets.includes(i)) {\n result += modified[i];\n }\n }\n\n return result;\n}\n\n// ====== Internals =========\n/** Text substitution guided by mapping and regular expression. */\nfunction applyPattern(text: string, mapping: AliasMapping, pattern: RegExp): string {\n if (text === '' || pattern === null) {\n return text;\n }\n let posInput = 0;\n let output = '';\n const patternMatches = text.matchAll(pattern);\n for (const segment of patternMatches) {\n const entity = segment[0];\n const start = segment.index ?? 0;\n if (entity in mapping) {\n output += text.substring(posInput, start);\n output += mapping[entity];\n posInput = start + segment[0].length;\n }\n }\n output += text.substring(posInput);\n return output;\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAM,gBAAgB;AACtB,MAAM,sBAAsB;AAC5B,MAAM,iBAAiB,IAAI,OAAO,qBAAqB,GAAG;AAC1D,MAAM,+BAA+B,IAAI,OAAO,IAAI,oBAAoB,EAAE;AAC1E,MAAM,yBAAyB;AAC/B,MAAM,mBAAmB;;AAIzB,SAAgB,cAAc,OAAwB;CACpD,OAAO,6BAA6B,KAAK,KAAK;AAChD;;;;;;;AAQA,SAAgB,sBAAsB,YAAoC;CACxE,IAAI,CAAC,WAAW,KAAK,GACnB,OAAO;
|
|
1
|
+
{"version":3,"file":"api.js","names":["rslangParser"],"sources":["../../src/rslang/api.ts"],"sourcesContent":["/**\n * Module: API for RSLanguage.\n */\nimport { type AstNode, buildTree } from '../parsing';\n\nimport { normalizeAST } from './parser/normalize';\nimport { parser as rslangParser } from './parser/parser';\nimport { ArgumentsExtractor, type ArgumentsType } from './semantic/arguments-extractor';\nexport { generateExpressionFromAst } from './parser/expression-generator';\n\n/** Represents alias mapping. */\nexport type AliasMapping = Record<string, string>;\n\n// cspell:disable\nconst LOCALS_REGEXP = /[_a-zα-ω][a-zα-ω]*\\d*/g;\nconst GLOBAL_ALIAS_SOURCE = '[XCSADFPTN]\\\\d+';\nconst GLOBALS_REGEXP = new RegExp(GLOBAL_ALIAS_SOURCE, 'g');\nconst GLOBAL_ALIAS_ANCHORED_REGEXP = new RegExp(`^${GLOBAL_ALIAS_SOURCE}$`);\nconst COMPLEX_SYMBOLS_REGEXP = /[∀∃×ℬ;|:]/g;\nconst TYPIFICATION_SET = /^ℬ+\\([ℬ\\(((X|C)\\d+|Z)\\)×]*\\)$/g;\n// cspell:enable\n\n/** Whether {@link value} is a single schema global alias (e.g. `X1`, `F42`). */\nexport function isGlobalAlias(value: string): boolean {\n return GLOBAL_ALIAS_ANCHORED_REGEXP.test(value);\n}\n\n/**\n * Parse a RSLang expression into a normalized AST.\n *\n * Returns `null` for blank input. Parses the original `expression` string so node\n * offsets match the source text (required for slice-based AST walks).\n */\nexport function parseRSLangExpression(expression: string): AstNode | null {\n if (!expression.trim()) {\n return null;\n }\n const tree = rslangParser.parse(expression);\n const ast = buildTree(tree.cursor());\n normalizeAST(ast, expression);\n return ast;\n}\n\n/** Extract arguments from AST. */\nexport function extractArguments(ast: AstNode): ArgumentsType[] {\n return new ArgumentsExtractor().run(ast);\n}\n\n/** Extracts global variable names from a given expression. */\nexport function extractGlobals(expression: string): Set<string> {\n return new Set(expression.match(GLOBALS_REGEXP) ?? []);\n}\n\n/** Check if expression is simple derivation. */\nexport function isSimpleExpression(text: string): boolean {\n return !text.match(COMPLEX_SYMBOLS_REGEXP);\n}\n\n/** Check if expression is set typification. */\nexport function isSetTypification(text: string): boolean {\n return !!text.match(TYPIFICATION_SET);\n}\n\n/**\n * Splits a string containing a template definition into its head and body parts.\n *\n * A template definition is expected to have the following format: `[head] body`.\n * If the input string does not contain the opening square bracket '[', the entire\n * string is treated as the body, and an empty string is assigned to the head.\n * If the opening bracket is present, the function attempts to find the matching\n * closing bracket ']' to determine the head and body parts.\n *\n * @example\n * const template = '[header] body content';\n * const result = splitTemplateDefinition(template);\n * // result: `{ head: 'header', body: 'body content' }`\n */\nexport function splitTemplateDefinition(target: string) {\n let start = 0;\n for (; start < target.length && target[start] !== '['; ++start);\n if (start < target.length) {\n for (let counter = 0, end = start + 1; end < target.length; ++end) {\n if (target[end] === '[') {\n ++counter;\n } else if (target[end] === ']') {\n if (counter !== 0) {\n --counter;\n } else {\n return {\n head: target.substring(start + 1, end).trim(),\n body: target.substring(end + 1).trim()\n };\n }\n }\n }\n }\n return {\n head: '',\n body: target\n };\n}\n\n/**\n * Substitutes values for template arguments in a given expression.\n *\n * This function takes an input mathematical expression and a list of argument values.\n * It replaces template argument placeholders in the expression with their corresponding values\n * from the provided arguments.\n */\nexport function substituteTemplateArgs(expression: string, mapping: AliasMapping): string {\n if (Object.keys(mapping).length === 0) {\n return expression;\n }\n let { head, body } = splitTemplateDefinition(expression);\n body = applyPattern(body, mapping, LOCALS_REGEXP);\n const argTexts = head.split(',').map(text => text.trim());\n head = argTexts\n .filter(arg => [...arg.matchAll(LOCALS_REGEXP)].every(local => local.every(match => !(match in mapping))))\n .join(', ');\n\n if (!head) {\n return body;\n } else {\n return `[${head}] ${body}`;\n }\n}\n\n/** Substitute local parameter aliases in an expression fragment. */\nexport function substituteLocalAliases(expression: string, mapping: AliasMapping): string {\n return applyPattern(expression, mapping, LOCALS_REGEXP);\n}\n\n/** Apply alias mapping. */\nexport function applyAliasMapping(target: string, mapping: AliasMapping): string {\n return applyPattern(target, mapping, GLOBALS_REGEXP);\n}\n\n/** Apply alias typification mapping. */\nexport function applyTypificationMapping(target: string, mapping: AliasMapping): string {\n const modified = applyAliasMapping(target, mapping);\n if (modified === target) {\n return target;\n }\n\n const deleteBrackets: number[] = [];\n const positions: number[] = [];\n const booleans: number[] = [];\n let boolCount: number = 0;\n let stackSize: number = 0;\n\n for (let i = 0; i < modified.length; i++) {\n const char = modified[i];\n if (char === 'ℬ') {\n boolCount++;\n continue;\n }\n if (char === '(') {\n stackSize++;\n positions.push(i);\n booleans.push(boolCount);\n }\n boolCount = 0;\n if (char === ')') {\n if (\n i < modified.length - 1 &&\n modified[i + 1] === ')' &&\n stackSize > 1 &&\n positions[stackSize - 2] + booleans[stackSize - 1] + 1 === positions[stackSize - 1]\n ) {\n deleteBrackets.push(i);\n deleteBrackets.push(positions[stackSize - 2]);\n }\n if (i === modified.length - 1 && stackSize === 1 && positions[0] === 0) {\n deleteBrackets.push(i);\n deleteBrackets.push(positions[0]);\n }\n stackSize--;\n positions.pop();\n booleans.pop();\n }\n }\n\n let result = '';\n for (let i = 0; i < modified.length; i++) {\n if (!deleteBrackets.includes(i)) {\n result += modified[i];\n }\n }\n\n return result;\n}\n\n// ====== Internals =========\n/** Text substitution guided by mapping and regular expression. */\nfunction applyPattern(text: string, mapping: AliasMapping, pattern: RegExp): string {\n if (text === '' || pattern === null) {\n return text;\n }\n let posInput = 0;\n let output = '';\n const patternMatches = text.matchAll(pattern);\n for (const segment of patternMatches) {\n const entity = segment[0];\n const start = segment.index ?? 0;\n if (entity in mapping) {\n output += text.substring(posInput, start);\n output += mapping[entity];\n posInput = start + segment[0].length;\n }\n }\n output += text.substring(posInput);\n return output;\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAM,gBAAgB;AACtB,MAAM,sBAAsB;AAC5B,MAAM,iBAAiB,IAAI,OAAO,qBAAqB,GAAG;AAC1D,MAAM,+BAA+B,IAAI,OAAO,IAAI,oBAAoB,EAAE;AAC1E,MAAM,yBAAyB;AAC/B,MAAM,mBAAmB;;AAIzB,SAAgB,cAAc,OAAwB;CACpD,OAAO,6BAA6B,KAAK,KAAK;AAChD;;;;;;;AAQA,SAAgB,sBAAsB,YAAoC;CACxE,IAAI,CAAC,WAAW,KAAK,GACnB,OAAO;CAET,MAAM,OAAOA,OAAa,MAAM,UAAU;CAC1C,MAAM,MAAM,UAAU,KAAK,OAAO,CAAC;CACnC,aAAa,KAAK,UAAU;CAC5B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,KAA+B;CAC9D,OAAO,IAAI,mBAAmB,CAAC,CAAC,IAAI,GAAG;AACzC;;AAGA,SAAgB,eAAe,YAAiC;CAC9D,OAAO,IAAI,IAAI,WAAW,MAAM,cAAc,KAAK,CAAC,CAAC;AACvD;;AAGA,SAAgB,m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,QAAQ;EACvB,MAAM,QAAQ,QAAQ,SAAS;EAC/B,IAAI,UAAU,SAAS;GACrB,UAAU,KAAK,UAAU,UAAU,KAAK;GACxC,UAAU,QAAQ;GAClB,WAAW,QAAQ,QAAQ,EAAE,CAAC;EAChC;CACF;CACA,UAAU,KAAK,UAAU,QAAQ;CACjC,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { annotateError } from "../ast-annotations.js";
|
|
2
2
|
import { RSErrorCode } from "../error.js";
|
|
3
|
-
import { M as validateValue } from "../../value-
|
|
3
|
+
import { M as validateValue } from "../../value-BDISzQqI.js";
|
|
4
4
|
import { Evaluator } from "./evaluator.js";
|
|
5
5
|
//#region src/rslang/eval/calculator.ts
|
|
6
6
|
/** AST calculator - evaluates RS expressions via visitor pattern and provides updates via listeners. */
|
|
@@ -180,9 +180,7 @@ function extendBoundInPlace(bound, declNode) {
|
|
|
180
180
|
case TokenID.NT_ENUM_DECL:
|
|
181
181
|
for (const child of declNode.children) extendBoundInPlace(bound, child);
|
|
182
182
|
break;
|
|
183
|
-
case TokenID.NT_ARG_DECL:
|
|
184
|
-
extendBoundInPlace(bound, declNode.children[0]);
|
|
185
|
-
break;
|
|
183
|
+
case TokenID.NT_ARG_DECL: extendBoundInPlace(bound, declNode.children[0]);
|
|
186
184
|
}
|
|
187
185
|
}
|
|
188
186
|
//#endregion
|