meta-log-db
Version:
Native database package for Meta-Log (ProLog, DataLog, R5RS)
108 lines • 2.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DatalogEngine = void 0;
const fixed_point_js_1 = require("./fixed-point.js");
const fact_extraction_js_1 = require("./fact-extraction.js");
/**
* DataLog Engine for Meta-Log Database
*/
class DatalogEngine {
constructor() {
this.facts = [];
this.rules = [];
}
/**
* Add facts to the database
*/
addFacts(facts) {
this.facts.push(...facts);
}
/**
* Add a rule to the database
*/
addRule(rule) {
this.rules.push(rule);
}
/**
* Build DataLog program from rules
*/
buildProgram(rules) {
return {
rules: [...rules],
facts: [...this.facts]
};
}
/**
* Query the database
*/
async query(goal, program) {
const targetProgram = program || this.buildProgram(this.rules);
// Compute fixed point
const allFacts = fixed_point_js_1.FixedPoint.compute(targetProgram);
// Match goal against facts
const parsedGoal = this.parseGoal(goal);
const matchingFacts = allFacts.filter(fact => {
if (fact.predicate !== parsedGoal.predicate) {
return false;
}
if (fact.args.length !== parsedGoal.args.length) {
return false;
}
// Match arguments (variables match anything)
for (let i = 0; i < fact.args.length; i++) {
const goalArg = parsedGoal.args[i];
if (!goalArg.startsWith('?') && goalArg !== fact.args[i].toString()) {
return false;
}
}
return true;
});
return { facts: matchingFacts };
}
/**
* Compute fixed point
*/
fixedPoint(program) {
return fixed_point_js_1.FixedPoint.compute(program);
}
/**
* Extract facts from canvas objects
*/
extractFacts(objects) {
return fact_extraction_js_1.FactExtraction.extractFromCanvas(objects);
}
/**
* Parse goal string
*/
parseGoal(goal) {
const match = goal.match(/^(\w+)\((.*)\)$/);
if (match) {
const predicate = match[1];
const argsStr = match[2];
const args = argsStr ? argsStr.split(',').map(s => s.trim()) : [];
return { predicate, args };
}
return { predicate: goal, args: [] };
}
/**
* Get all facts
*/
getFacts() {
return [...this.facts];
}
/**
* Get all rules
*/
getRules() {
return [...this.rules];
}
/**
* Clear database
*/
clear() {
this.facts = [];
this.rules = [];
}
}
exports.DatalogEngine = DatalogEngine;
//# sourceMappingURL=engine.js.map