From 4a8119afddda0bae555a7c1720808c237e82825b Mon Sep 17 00:00:00 2001 From: vishalkrishnaag Date: Wed, 2 Sep 2026 15:20:18 +0000 Subject: [PATCH 1/6] core bump fixes --- CMakeLists.txt | 3 + README.md | 18 +- core/exception.fx | 6 +- datasets/examples/schools.fx | 3 + datasets/tokenizer/felidae-tokenizer-v1.jsonl | 6 +- docs/about.fx | 3 +- docs/basics.fx | 2 +- docs/builtin-docs.json | 241 +---------- docs/docs_search.fx | 2 +- docs/facts.fx | 2 +- docs/html_components.fx | 3 +- docs/libraries.fx | 2 +- docs/library_pages.fx | 17 +- docs/methods.fx | 4 +- docs/overview.fx | 2 +- docs/playground.fx | 2 +- docs/queries.fx | 4 +- docs/syntax.fx | 2 +- docs/testing.fx | 4 +- docs_language.md | 144 +++---- emacs-extension | 2 +- intellij-idea-extension | 2 +- notepad-plus-plus-extension | 2 +- src/AST.h | 78 +++- src/BuiltinRegistry.cpp | 50 +-- src/BuiltinRegistry.h | 4 + src/CompilerFrontend.cpp | 162 ++++++- src/FelidaeGrammar.h | 4 - src/FelidaeIr.h | 3 + src/IntegerParser.cpp | 105 ++++- src/IntegerParser.h | 2 + src/IrCodeGenerator.cpp | 406 ++++++++++++------ src/form/BinaryIr.cpp | 10 + src/form/BuiltinOperation.h | 87 +++- src/form/IrModule.cpp | 14 + src/form/IrModule.h | 1 + src/form/NumericOperation.h | 5 +- src/form/RegisterVm.cpp | 267 ++++++++++-- src/form/RegisterVm.h | 56 ++- src/form/RuntimeStateModel.cpp | 179 +++++++- src/form/RuntimeStateModel.h | 13 +- src/form/RuntimeTraining.cpp | 159 ++++++- src/form/RuntimeTraining.h | 12 +- src/form/SemanticOperation.h | 6 + src/form/libs/Builtin.cpp | 145 +++++++ src/form/libs/Db.cpp | 24 +- src/form/libs/Db.h | 7 +- tests/FelidaeIrTest.cpp | 50 +++ tests/FormDbCsvTest.cpp | 23 +- tests/MixfixStateModelTest.cpp | 39 +- tests/SentencePieceModelTest.cpp | 12 +- tests/SentencePiecePipelineTest.cpp | 207 ++++++++- tools/BuildRuntimeTrainingDataset.cpp | 1 + tools/ExtractMixfixDataset.cpp | 4 +- tools/TrainRuntimeGru.cpp | 57 ++- .../animal_fact_similarity_evidence.fx | 2 +- v2_examples/deep_fact_reasoning_analysis.fx | 4 +- v2_examples/direct_ancestor_analysis.fx | 6 +- v2_examples/fact_search_analysis.fx | 6 +- .../fact_similarity_requires_ancestry.fx | 2 +- v2_examples/felidae_language_tour.fx | 16 +- v2_examples/fx_fact_database.fx | 14 + .../mixfix_multi_ancestor_fact_analysis.fx | 2 +- v2_examples/operator_expression_inventory.fx | 2 +- vs-code-extension | 2 +- 65 files changed, 2012 insertions(+), 712 deletions(-) create mode 100644 datasets/examples/schools.fx create mode 100644 v2_examples/fx_fact_database.fx diff --git a/CMakeLists.txt b/CMakeLists.txt index 164f7f7..5c90d89 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -805,6 +805,7 @@ if(FELIDAE_BUILD_TESTS) numeric_operations json_csv_operations csv_fact_database + fx_fact_database group_operations set_operations degree_profiles @@ -842,6 +843,8 @@ if(FELIDAE_BUILD_TESTS) # gets ".0". set_tests_properties(felidae_example_csv_fact_database PROPERTIES PASS_REGULAR_EXPRESSION "all_count: 4, active_central_count: 2.*deleted: 1.0") + set_tests_properties(felidae_example_fx_fact_database PROPERTIES + PASS_REGULAR_EXPRESSION "count: 2, students: 770") set_tests_properties(felidae_example_group_operations PROPERTIES PASS_REGULAR_EXPRESSION "abelian: 1.0") set_tests_properties(felidae_example_set_operations PROPERTIES diff --git a/README.md b/README.md index 1c53651..5e3d659 100644 --- a/README.md +++ b/README.md @@ -602,7 +602,7 @@ main() => activeCentral := School.where(district: "central", active: 1.0) .limit(records: 100) discovered := School.search(field: "name", query: "%north%", - mode: "like", case: "insensitive") + type: "like", case: "insensitive") names := School.select(fields: ["name"], match: {active: 1.0}) return (all: allSchools, selected: activeCentral, names: names, count: School.count()) @@ -632,8 +632,10 @@ changed := School.where(name: "North") ``` Insert, update, and delete persist automatically when affected facts have CSV -source ownership. Each source is staged and replaced independently; an -in-memory fact has no implicit disk side effect. See +source ownership or were linked from a fact-only `.fx` database import. Each +source is staged and replaced independently; an in-memory fact has no implicit +disk side effect. The compiler links `.fx` rows and ownership into IR; the VM +does not parse source files. See `v2_examples/csv_fact_database.fx` for the complete import, query, aggregate, and automatic write-back flow. @@ -641,7 +643,9 @@ Updates and deletes are deliberately conditional: they must be chained after `where`, `AndWhere`, or `OrWhere`. Direct type-wide mutation is rejected. Joins must provide both `left` and `right` key fields, so the normal `Type.join(...)` operation is an explicit inner equijoin rather than a -conditionless Cartesian join. +conditionless Cartesian join. Pass `kind: "left"`, `kind: "right"`, or +`kind: "outer"` to the same operation when unmatched rows are required; +separate `leftJoin`, `rightJoin`, and `OuterJoin` methods do not exist. Because child types are assignable to their parents, a parent query can work with the hierarchy rather than only one exact concrete type. @@ -926,6 +930,11 @@ This model is not used automatically for ordinary arithmetic, boolean logic, fac Semantic evaluation must be explicitly represented. +Application scoring uses `ssm.suggest(input: value)`. It returns an ordinary +finite floating-point score and may be negative or greater than `1.0`; the VM +does not normalize it or treat it as implicit truth. Deterministic arithmetic, +queries, joins, and hierarchy traversal never invoke the model automatically. + --- ## Why separate them? @@ -2371,7 +2380,6 @@ docs/syntax.fx docs/facts.fx docs/queries.fx -docs/probability.fx docs/methods.fx docs/native_modules.fx diff --git a/core/exception.fx b/core/exception.fx index 8548f55..2dd532d 100644 --- a/core/exception.fx +++ b/core/exception.fx @@ -9,12 +9,12 @@ Exception(kind: string, message: string, source: string) => () Result(ok: bool, value: any, error: any) => () exception.ok(value: any) => - return {__type: "Result", ok: true, value: value, error: nil} + return {__type: "Result", ok: 1.0, value: value, error: nil} exception.failure(kind: string, message: string, source: string) => return { __type: "Result", - ok: false, + ok: 0.0, value: nil, error: { __type: "Exception", @@ -28,4 +28,4 @@ exception.from(value: any, error: any) => if error == nil then return exception.ok(value: value) else - return {__type: "Result", ok: false, value: value, error: error} + return {__type: "Result", ok: 0.0, value: value, error: error} diff --git a/datasets/examples/schools.fx b/datasets/examples/schools.fx new file mode 100644 index 0000000..a414aa2 --- /dev/null +++ b/datasets/examples/schools.fx @@ -0,0 +1,3 @@ +School(id: 1, name: "North", city: "BLR", students: 420, active: 1.0) +School(id: 2, name: "West", city: "MYS", students: 280, active: 0.0) +School(id: 3, name: "Lake", city: "BLR", students: 350, active: 1.0) diff --git a/datasets/tokenizer/felidae-tokenizer-v1.jsonl b/datasets/tokenizer/felidae-tokenizer-v1.jsonl index ea22cdf..930b63e 100644 --- a/datasets/tokenizer/felidae-tokenizer-v1.jsonl +++ b/datasets/tokenizer/felidae-tokenizer-v1.jsonl @@ -82,5 +82,9 @@ {"schema_version":1,"id":"fact-query-chain","family":"queries","source":"School(name: \"North\", city: \"BLR\", active: 1.0)\nmain() => return School.where(active: 1.0).AndWhere(city: \"BLR\").limit(records: 100)"} {"schema_version":1,"id":"fact-query-or","family":"queries","source":"School(name: \"North\", city: \"BLR\")\nmain() => return School.where(city: \"BLR\").OrWhere(name: \"West\")"} {"schema_version":1,"id":"fact-dml","family":"persistence","source":"School(id: 1, active: 1.0)\nmain() =>\n inserted := School.insert(values: {id: 2, active: 1.0})\n updated := School.where(id: 1).update(values: {active: 0.0})\n return School.where(id: 2).delete()\nend"} -{"schema_version":1,"id":"fact-joins","family":"queries","source":"School(id: 1)\nTeacher(school_id: 1)\nmain() => return School.leftJoin(type: Teacher, left: \"id\", right: \"school_id\").limit(records: 100)"} +{"schema_version":1,"id":"fact-fx-database-import","family":"persistence","source":"import \"schools.fx\"\nmain() =>\n changed := School.where(id: 1).update(values: {score: 3.432})\n return changed\nend"} +{"schema_version":1,"id":"fact-joins","family":"queries","source":"School(id: 1)\nTeacher(school_id: 1)\nmain() => return School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"left\").limit(records: 100)"} +{"schema_version":1,"id":"fact-search","family":"queries","source":"Catalog(title: \"Alpha Guide\", confidence: 0.82)\nmain() =>\n titles := Catalog.search(field: \"title\", query: \"%guide\", type: \"like\", case: \"insensitive\")\n confident := Catalog.search(field: \"confidence\", type: \"degree\", minimum: 0.70, maximum: 0.90)\n return (titles: titles, confident: confident)\nend"} {"schema_version":1,"id":"numeric-float-operations","family":"numeric","source":"main() => return (average: avg(3.432, -2.302), bounded: clamp(-345.345, -500.0, 500.0), blended: lerp(-2.302, 3.432, 0.25), valid: in_range(3.432, -10.0, 10.0), weighted: weighted_avg(10.0, 20.0, 1.0, 3.0))"} +{"schema_version":1,"id":"fact-class-schema","family":"facts","source":"class Animal\n name: string\n index(name)\nend\nclass Human extend Animal\n age: number\n index(name, age)\n eligible(minimumAge: number) =>\n where age >= minimumAge\n return 1.0\n else\n return 0.0\n end\nend\nHuman(name: \"Ada\", age: 32)"} +{"schema_version":1,"id":"runtime-ssm-suggest","family":"reasoning","source":"main() =>\n score := ssm.suggest(input: AncestorRelevance(candidate: Mammal, purpose: \"medical similarity\"))\n where score >= 4.5\n return score\nelse\n return 0.0\nend"} diff --git a/docs/about.fx b/docs/about.fx index c138aec..e3310c4 100644 --- a/docs/about.fx +++ b/docs/about.fx @@ -10,5 +10,4 @@ DocsAbout() => part2 := str.concat(left: part1, right: editors), part3 := str.concat(left: part2, right: follow), content := RenderGrid(content: part3), - return (HtmlRichSectionData(id: "about", title: "About Felidae", p: "Felidae is designed for explicit logic dataflow, typed facts, local fact databases, and native modules for heavy work. It is similar in spirit to logic/data languages such as Logica, but it keeps its own Felidae syntax and runtime contract.", p2: "The documentation site is intentionally implemented in Felidae: routes are component records, code examples are copyable, the playground is a Felidae fact, and the server renders everything at startup.", content: content, code: "FactDatabase() =>\n facts := db.types(),\n return (types: facts).\n\nDocsAbout() =>\n return (HtmlRichSectionData(id: \"about\", title: \"About Felidae\", content: \"...\" )).", note: "Follow the repository for language, runtime, Celidae, VS Code extension, IntelliJ plugin, and docs-site updates.", code2: "Repository:\nhttps://github.com/xnvtserver/Felidae\n\nDocs command:\n./build/felidae docs/server.fx")). - + return (HtmlRichSectionData(id: "about", title: "About Felidae", p: "Felidae is designed for explicit logic dataflow, typed facts, local fact databases, and verified VM operations for heavy work.", p2: "Facts are first-class queryable database rows; hierarchy and graded numeric evidence support expert-system analysis without forcing every result into 0.0 or 1.0.", content: content, code: "School(name: \"North\", score: 3.432).\n\nmain() =>\n return School.all()\nend", note: "Follow the repository for compiler, VM, debugger, editor, and documentation updates.", code2: "Repository:\nhttps://github.com/xnvtserver/Felidae")). diff --git a/docs/basics.fx b/docs/basics.fx index d57e589..4065b12 100644 --- a/docs/basics.fx +++ b/docs/basics.fx @@ -10,7 +10,7 @@ DocsBasics() => guidance := RenderGuidance(doText: "Model durable knowledge as facts with named fields, then write main() to collect, filter, aggregate, and return the answer as a tuple.", dontText: "Do not hide important application behavior only in command-line queries. CLI queries are useful for inspection, but they are not a substitute for repeatable program output.", recommendText: "Start every learning example with a tiny fact database, one method or rule, and a main() return value. That pattern makes examples easy to test, document, and serve."), arithmeticCode := "CartLine(item: \"book\", qty: 2, price: 15).\nCartLine(item: \"pen\", qty: 5, price: 2).\n\nLineTotal(line: any) =>\n subtotal := line.qty * line.price,\n discounted := subtotal - 1,\n return (item: line.item, subtotal: subtotal, discounted: discounted).\n\nmain() =>\n lines := lambda(CartLine, line => LineTotal(line: line)),\n totals := lambda(lines, line => line.subtotal),\n return (add: 2 + 3, multiply: 2 * 3, grouped: (2 + 3) * 4, precedence: 2 + 3 * 4, cartTotal: sum(totals), lines: lines).", arithmeticExample := RenderExampleBlock(title: "Arithmetic: totals and precedence", text: "Arithmetic expressions can be returned directly, assigned to locals, or used inside filters. Parentheses make the intent visible when precedence could surprise a reader.", code: arithmeticCode), - logicCode := "Person(name: \"Ada\", role: \"Engineer\", active: \"true\", score: 91).\nPerson(name: \"Mina\", role: \"Designer\", active: \"true\", score: 72).\nPerson(name: \"Ravi\", role: \"Engineer\", active: \"false\", score: 65).\n\nEligible(person: any) =>\n person.active == \"true\",\n person.score >= 80,\n return (name: person.name, eligible: \"true\")\nelse\n return (name: person.name, eligible: \"false\").\n\nmain() =>\n engineers := lambda(Person, p => p.role == \"Engineer\"),\n checks := lambda(Person, p => Eligible(person: p)),\n activeHigh := lambda(checks, row => row.eligible == \"true\"),\n return (engineers: count(engineers), activeHigh: count(activeHigh), checks: checks).", + logicCode := "Person(name: \"Ada\", role: \"Engineer\", active: 1.0, score: 91).\nPerson(name: \"ReRemostu\", role: \"Designer\", active: 1.0, score: 72).\nPerson(name: \"Ravi\", role: \"Engineer\", active: 0.0, score: 65).\n\nEligible(person: any) =>\n person.active == 1.0,\n person.score >= 80,\n return (name: person.name, eligible: 1.0)\nelse\n return (name: person.name, eligible: 0.0).\n\nmain() =>\n engineers := lambda(Person, p => p.role == \"Engineer\"),\n checks := lambda(Person, p => Eligible(person: p)),\n activeHigh := lambda(checks, row => row.eligible == 1.0),\n return (engineers: count(engineers), activeHigh: count(activeHigh), checks: checks).", logicExample := RenderExampleBlock(title: "Logic: filters and eligibility", text: "Logical checks are ordinary conditions. Use comma-separated conditions as AND, comparison operators for filtering, and fallback branches or | rules when there are alternatives.", code: logicCode), part1 := str.concat(left: facts, right: rules), part2 := str.concat(left: part1, right: queries), diff --git a/docs/builtin-docs.json b/docs/builtin-docs.json index 65368c7..155f41c 100644 --- a/docs/builtin-docs.json +++ b/docs/builtin-docs.json @@ -190,237 +190,6 @@ } ] }, - "probability:mean": { - "heading": "probability.mean", - "description": "Returns the arithmetic mean of a numeric array.", - "example": "average := probability.mean(data: [2, 4, 6])", - "params": [ - { - "name": "data" - } - ] - }, - "probability:variance": { - "heading": "probability.variance", - "description": "Returns the variance of a numeric array.", - "example": "spread := probability.variance(data: values)", - "params": [ - { - "name": "data" - } - ] - }, - "probability:stddev": { - "heading": "probability.stddev", - "description": "Returns the standard deviation of a numeric array.", - "example": "spread := probability.stddev(data: values)", - "params": [ - { - "name": "data" - } - ] - }, - "probability:normalize": { - "heading": "probability.normalize", - "description": "Scales a numeric array so its values sum to 1, producing a probability distribution.", - "example": "distribution := probability.normalize(data: values)", - "params": [ - { - "name": "data" - } - ] - }, - "probability:entropy": { - "heading": "probability.entropy", - "description": "Returns the Shannon entropy of a probability distribution array.", - "example": "spread := probability.entropy(data: distribution)", - "params": [ - { - "name": "data" - } - ] - }, - "probability:covariance": { - "heading": "probability.covariance", - "description": "Returns the covariance between two numeric arrays of equal length.", - "example": "value := probability.covariance(left: xs, right: ys)", - "params": [ - { - "name": "left" - }, - { - "name": "right" - } - ] - }, - "probability:correlation": { - "heading": "probability.correlation", - "description": "Returns the Pearson correlation coefficient between two numeric arrays of equal length.", - "example": "value := probability.correlation(left: xs, right: ys)", - "params": [ - { - "name": "left" - }, - { - "name": "right" - } - ] - }, - "probability:bernoulli": { - "heading": "probability.bernoulli", - "description": "Samples a Bernoulli trial with success probability p, returning 1 or 0.", - "example": "outcome := probability.bernoulli(p: 0.5)", - "params": [ - { - "name": "p" - } - ] - }, - "probability:binomialPmf": { - "heading": "probability.binomialPmf", - "description": "Returns the binomial probability mass function value for the given trials, successes, and success probability.", - "example": "value := probability.binomialPmf(trials: 10, successes: 4, p: 0.5)", - "params": [ - { - "name": "trials" - }, - { - "name": "successes" - }, - { - "name": "p" - } - ] - }, - "probability:binomialCdf": { - "heading": "probability.binomialCdf", - "description": "Returns the binomial cumulative distribution function value for the given trials, successes, and success probability.", - "example": "value := probability.binomialCdf(trials: 10, successes: 4, p: 0.5)", - "params": [ - { - "name": "trials" - }, - { - "name": "successes" - }, - { - "name": "p" - } - ] - }, - "probability:poissonPmf": { - "heading": "probability.poissonPmf", - "description": "Returns the Poisson probability mass function value for the given rate and event count.", - "example": "value := probability.poissonPmf(lambda: 3, events: 2)", - "params": [ - { - "name": "lambda" - }, - { - "name": "events" - } - ] - }, - "probability:poissonCdf": { - "heading": "probability.poissonCdf", - "description": "Returns the Poisson cumulative distribution function value for the given rate and event count.", - "example": "value := probability.poissonCdf(lambda: 3, events: 2)", - "params": [ - { - "name": "lambda" - }, - { - "name": "events" - } - ] - }, - "probability:normalPdf": { - "heading": "probability.normalPdf", - "description": "Returns the normal distribution probability density at x for the given mean and standard deviation.", - "example": "value := probability.normalPdf(x: 1, mean: 0, stddev: 1)", - "params": [ - { - "name": "x" - }, - { - "name": "mean" - }, - { - "name": "stddev" - } - ] - }, - "probability:normalCdf": { - "heading": "probability.normalCdf", - "description": "Returns the normal distribution cumulative probability at x for the given mean and standard deviation.", - "example": "value := probability.normalCdf(x: 1, mean: 0, stddev: 1)", - "params": [ - { - "name": "x" - }, - { - "name": "mean" - }, - { - "name": "stddev" - } - ] - }, - "probability:uniformPdf": { - "heading": "probability.uniformPdf", - "description": "Returns the uniform distribution probability density at x within the given min/max range.", - "example": "value := probability.uniformPdf(x: 5, min: 0, max: 10)", - "params": [ - { - "name": "x" - }, - { - "name": "min" - }, - { - "name": "max" - } - ] - }, - "probability:uniformCdf": { - "heading": "probability.uniformCdf", - "description": "Returns the uniform distribution cumulative probability at x within the given min/max range.", - "example": "value := probability.uniformCdf(x: 5, min: 0, max: 10)", - "params": [ - { - "name": "x" - }, - { - "name": "min" - }, - { - "name": "max" - } - ] - }, - "probability:sample": { - "heading": "probability.sample", - "description": "Returns one value chosen uniformly at random from the array.", - "example": "value := probability.sample(data: values)", - "params": [ - { - "name": "data" - } - ] - }, - "probability:weightedChoice": { - "heading": "probability.weightedChoice", - "description": "Returns one value chosen at random from the array, weighted by the parallel weights array.", - "example": "value := probability.weightedChoice(data: values, weights: weights)", - "params": [ - { - "name": "data" - }, - { - "name": "weights" - } - ] - }, "str:len": { "heading": "str.len", "description": "Unifies the output argument with the length of a string.", @@ -530,7 +299,7 @@ }, "str:startsWith": { "heading": "str.startsWith", - "description": "Returns \"true\" when a string starts with the requested prefix.", + "description": "Returns 1.0 when a string starts with the requested prefix, otherwise 0.0.", "example": "ok := str.startsWith(data: \"Alice\", prefix: \"Al\")", "params": [ { @@ -543,7 +312,7 @@ }, "str:endsWith": { "heading": "str.endsWith", - "description": "Returns \"true\" when a string ends with the requested suffix.", + "description": "Returns 1.0 when a string ends with the requested suffix, otherwise 0.0.", "example": "ok := str.endsWith(data: \"Alice\", suffix: \"ice\")", "params": [ { @@ -692,7 +461,7 @@ }, "json:has": { "heading": "json.has", - "description": "Returns \"true\" when a JSON/map value contains the requested key.", + "description": "Returns 1.0 when a JSON/map value contains the requested key, otherwise 0.0.", "example": "ok := json.has(data: object, key: \"name\")", "params": [ { @@ -908,7 +677,7 @@ }, "file:exists": { "heading": "file.exists", - "description": "Returns \"true\" when a path exists, otherwise \"false\".", + "description": "Returns 1.0 when a path exists, otherwise 0.0.", "example": "ok := file.exists(path: \"data.txt\")", "params": [ { @@ -918,7 +687,7 @@ }, "file:deleteFile": { "heading": "file.deleteFile", - "description": "Deletes a file and returns \"true\" when a file was removed.", + "description": "Deletes a file and returns 1.0 when a file was removed, otherwise 0.0.", "example": "removed := file.deleteFile(path: \"data.txt\")", "params": [ { diff --git a/docs/docs_search.fx b/docs/docs_search.fx index b6144d7..08a71a8 100644 --- a/docs/docs_search.fx +++ b/docs/docs_search.fx @@ -21,7 +21,7 @@ DocSearchEntry(id: "lib-math", title: "Library: math", route: "#lib-math", tags: DocSearchEntry(id: "lib-system", title: "Library: system", route: "#lib-system", tags: "system print type runtime", summary: "Runtime print and type inspection helpers.", searchText: "library system print type instanceof runtime output"). DocSearchEntry(id: "lib-console", title: "Library: console", route: "#lib-console", tags: "console terminal interactive", summary: "Interactive terminal input and output.", searchText: "library console readLine write writeLine terminal interactive"). DocSearchEntry(id: "lib-thread", title: "Library: thread", route: "#lib-thread", tags: "thread create start pause stop status result", summary: "Thread handles for independent method execution.", searchText: "library thread createThread start pause stop status result worker handle"). -DocSearchEntry(id: "native", title: "Native Modules", route: "#native", tags: "native modules c++ bridge performance", summary: "Native modules keep heavy work behind stable Felidae declarations while C++ handles implementation details.", searchText: "native modules bridge cpp performance runtime implementation"). +DocSearchEntry(id: "native", title: "Runtime Libraries", route: "#native", tags: "runtime libraries builtin ir c++ performance", summary: "Verified Builtin IR keeps runtime-library calls explicit while typed C++ handles their implementation.", searchText: "runtime libraries builtin ir cpp performance implementation"). DocSearchEntry(id: "debugging", title: "Debugging And Editor Diagnostics", route: "#debugging", tags: "debugging diagnostics celidae vscode lsp graph", summary: "felidae_debug owns AST diagnostics and LSP; Celidae owns fact graph visualization.", searchText: "debugging diagnostics celidae vscode intellij lsp graph visualization check json"). DocSearchEntry(id: "hosting", title: "Documentation Hosting", route: "#hosting", tags: "hosting documentation server html components", summary: "The docs site is a Felidae program that renders documentation facts into HTML at startup.", searchText: "hosting documentation server html components render startup generated static"). DocSearchEntry(id: "server", title: "Server Features", route: "#server", tags: "server routes navigation spa copy playground search", summary: "The server renders a single-page app with routing, navigation, code copy, playground, and generated docs.", searchText: "server features routes navigation spa copy playground search static response"). diff --git a/docs/facts.fx b/docs/facts.fx index b778e15..487f8de 100644 --- a/docs/facts.fx +++ b/docs/facts.fx @@ -4,4 +4,4 @@ DocsFacts() => guidance := RenderGuidance(doText: "Keep facts stable, named, and queryable. Use repeated fields for list-shaped values and nested objects for properties that belong together, such as an order item with sku, quantity, and price.", dontText: "Do not flatten related values into unclear names like item1Qty or item2Price. That makes filtering, aggregation, JSON export, and documentation search harder.", recommendText: "Treat a fact declaration as a small database row. Put repeatable queries in main() or named methods, and reserve command-line queries for quick inspection."), simulation := RenderNote(text: "Fact DB examples in the browser are a simulation of the storage model: Felidae can represent a database as .fx facts, similar to SQLite using a file or a graph database using graph-shaped records. The docs/db programs remain available for native interpreter workflows."), content := str.concat(left: guidance, right: simulation), - return (HtmlRichSectionData(id: "facts", title: "Facts As Database", p: "Facts are the primary database layer. Named fields behave like logical properties, and repeated fields represent multi-valued properties. Repeated fields materialize as arrays inside methods, so nested fact data can be mapped, filtered, counted, sorted, and aggregated without SQL.", p2: "Use direct declarations for durable knowledge, globals for computed data, and methods when a value must be derived from input. Child facts can extend parent facts, and child fields override parent defaults. The db module exposes the loaded no-SQL fact store without asking users to write SQL or BigQuery.", content: content, code: "import \"db\".\n\nCustomer(id: \"c-1\", name: \"Ada\", city: \"SEA\", tag: \"active\", tag: \"enterprise\").\nCustomer(id: \"c-2\", name: \"Mina\", city: \"BLR\", tag: \"active\").\nOrder(id: \"o-1\", customer: \"c-1\", item: {sku: \"book\", qty: 2, price: 15}, item: {sku: \"pen\", qty: 5, price: 2}).\n\nmain() =>\n customer := db.first(type: \"Customer\", field: \"id\", equals: \"c-1\"),\n order := db.first(type: \"Order\", field: \"customer\", equals: customer.id),\n quantities := lambda(order.item, item => item.qty),\n return (customer: customer.name, tags: customer.tag, itemCount: count(order.item), totalUnits: sum(quantities)).", note: "The fact is the database row and the source code at the same time. Browser examples show the generated fact-file shape for learning; production file I/O should use the native Felidae interpreter.", code2: "Animal(kind: \"cat\", legs: 4).\nPet extend Animal(name: \"Lilly\", kind: \"cat\").\n\nmain() =>\n pets := lambda(Pet, p => p.kind == \"cat\"),\n return (cats: pets, count: count(pets)).")). + return (HtmlRichSectionData(id: "facts", title: "Facts As Database", p: "Facts are the primary database layer. Named fields behave like logical properties, and repeated fields represent multi-valued properties.", p2: "Query a type directly with all, where, select, search, count, aggregates, conditional mutations, and keyed joins. Child facts remain assignable to parent queries.", content: content, code: "Customer(id: \"c-1\", name: \"Ada\", city: \"SEA\", active: 1.0).\nCustomer(id: \"c-2\", name: \"Mina\", city: \"BLR\", active: 1.0).\nOrder(id: \"o-1\", customer: \"c-1\", total: 40).\n\nmain() =>\n customer := Customer.where(id: \"c-1\")\n orders := Order.where(customer: \"c-1\")\n return (customer: customer, orders: orders)\nend", note: "A fact-only .fx import is compiler-linked DDL. Conditional DML persists owned CSV and .fx rows automatically.", code2: "Animal(kind: \"cat\", legs: 4).\nPet extend Animal(name: \"Lilly\", kind: \"cat\").\n\nmain() =>\n return Animal.where(kind: \"cat\")\nend")). diff --git a/docs/html_components.fx b/docs/html_components.fx index 43472ee..8e5e111 100644 --- a/docs/html_components.fx +++ b/docs/html_components.fx @@ -554,8 +554,7 @@ RenderNavBar() => RenderNavItem(input: navItem(label: "Reference", href: "#reference", order: 10, icon: "book")), RenderNavItem(input: navItem(label: "Stdlib", href: "#stdlib", order: 11, icon: "cube")), RenderNavItem(input: navItem(label: "Libraries", href: "#libraries", order: 12, icon: "cube")), - RenderNavItem(input: navItem(label: "Probability", href: "#probability", order: 13, icon: "chart")), - RenderNavItem(input: navItem(label: "Native", href: "#native", order: 14, icon: "cpu")), + RenderNavItem(input: navItem(label: "Runtime Libraries", href: "#native", order: 14, icon: "cpu")), RenderNavItem(input: navItem(label: "Debugging", href: "#debugging", order: 15, icon: "bug")), RenderNavItem(input: navItem(label: "Hosting", href: "#hosting", order: 16, icon: "cloud")), RenderNavItem(input: navItem(label: "Server", href: "#server", order: 17, icon: "server")), diff --git a/docs/libraries.fx b/docs/libraries.fx index 8a1547f..fb6c595 100644 --- a/docs/libraries.fx +++ b/docs/libraries.fx @@ -19,4 +19,4 @@ DocsLibraries() => LibraryLinkCard(title: "thread", text: "Independent method execution with thread handles.", href: "#lib-thread") ], delimiter: ""), content := str.concat(left: overview, right: RenderModuleGrid(content: cards)), - return (HtmlRichSectionData(id: "libraries", title: "Library Index", p: "Felidae library documentation is organized one subject at a time. The index is only a chooser; the focused module page carries the signatures, examples, notes, and risks for that module.", p2: "This keeps the docs straightforward: open json for JSON, csv for CSV, file for file I/O, and so on. Cross-cutting workflows such as native modules keep their own pages.", content: content, code: "# Reading flow\n# 1. Standard Library: understand the module map\n# 2. Library Index: choose one module\n# 3. Module page: read one API surface\n# 4. Copy, download, or run the focused example", note: "Avoid mixed module pages. They make examples look convenient, but they hide which import owns which behavior.", code2: "import \"json\".\n\nPerson(name: \"\").\n\nmain() =>\n rows := Person.all(),\n names := lambda(rows, p => p.name),\n return (json: json.toText(data: names))")). + return (HtmlRichSectionData(id: "libraries", title: "Library Index", p: "Felidae library documentation is organized one subject at a time. The index is only a chooser; the focused module page carries the signatures, examples, notes, and risks for that module.", p2: "This keeps the docs straightforward: open json for JSON, csv for CSV, file for file I/O, and so on. Cross-cutting runtime-library behavior has its own page.", content: content, code: "# Reading flow\n# 1. Standard Library: understand the module map\n# 2. Library Index: choose one module\n# 3. Module page: read one API surface\n# 4. Copy, download, or run the focused example", note: "Avoid mixed module pages. They make examples look convenient, but they hide which import owns which behavior.", code2: "import \"json\".\n\nPerson(name: \"\").\n\nmain() =>\n rows := Person.all(),\n names := lambda(rows, p => p.name),\n return (json: json.toText(data: names))")). diff --git a/docs/library_pages.fx b/docs/library_pages.fx index 52c7708..f5073e1 100644 --- a/docs/library_pages.fx +++ b/docs/library_pages.fx @@ -14,11 +14,11 @@ DocsLibraryArray() => RenderMiniCard(input: HtmlCardData(title: "Measure", text: "array.len returns the number of values.")), RenderMiniCard(input: HtmlCardData(title: "Build", text: "array.push returns a new array with one added value.")) ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-array", title: "Library: array", p: "The array module is intentionally small. Arrays are ordered values, while facts remain the preferred shape for durable named knowledge.", p2: "Use array helpers when order matters or when a native module returns a list. For filtering and projection, prefer lambda(data, row => ...) so the transformation stays visible.", content: cards, code: "import \"array\".\n\nmain() =>\n names := [\"Ada\", \"Mina\", \"Ravi\"],\n first := array.get(data: names, position: 0),\n total := array.len(data: names),\n extended := array.push(data: names, value: \"Nia\"),\n return (first: first, total: total, extended: extended).", note: "Use facts when fields need names. Use arrays when order is the important part of the data.", code2: "scores := [91, 72, 65]\npassing := lambda(scores, value => value >= 70)\ncount(passing)")). + return (HtmlRichSectionData(id: "lib-array", title: "Library: array", p: "The array module is intentionally small. Arrays are ordered values, while facts remain the preferred shape for durable named knowledge.", p2: "Use array helpers when order matters or when a runtime-library operation returns a list. For filtering and projection, prefer lambda(data, row => ...) so the transformation stays visible.", content: cards, code: "import \"array\".\n\nmain() =>\n names := [\"Ada\", \"Mina\", \"Ravi\"],\n first := array.get(data: names, position: 0),\n total := array.len(data: names),\n extended := array.push(data: names, value: \"Nia\"),\n return (first: first, total: total, extended: extended).", note: "Use facts when fields need names. Use arrays when order is the important part of the data.", code2: "scores := [91, 72, 65]\npassing := lambda(scores, value => value >= 70)\ncount(passing)")). DocsLibraryDb() => - guidance := RenderGuidance(doText: "Keep fact queries inside main() or named methods, and return named tuples so the result is testable and documentable.", dontText: "Do not use db helpers as hidden global state inside unrelated helpers. Pass data into methods when the method should be reusable.", recommendText: "Use db.first for one expected record, db.find for filtered rows, and db.all when the fact type is the dataset."), - return (HtmlRichSectionData(id: "lib-db", title: "Library: db", p: "The db module treats loaded facts as the database. It is the no-SQL query surface for facts already loaded into the interpreter: direct facts, imported facts, and facts created through ordinary Felidae source.", p2: "db helpers are explicit. A method does not silently scan every fact; use db.all, db.find, db.first, db.count, db.types, or db.fields when fact database access is intended.", content: guidance, code: "import \"db\".\n\nCustomer(name: \"Ada\", city: \"SEA\", status: \"active\").\nCustomer(name: \"Mina\", city: \"BLR\", status: \"active\").\n\nmain() =>\n rows := db.find(type: \"Customer\", field: \"status\", equals: \"active\"),\n names := lambda(rows, row => row.name),\n return (count: count(rows), names: names).", note: "db is critical because it defines the fact database contract. Keep field names stable and clear.", code2: "db.all(type: \"Customer\")\ndb.first(type: \"Customer\", field: \"name\", equals: \"Ada\")\ndb.count(type: \"Customer\")\ndb.fields(type: \"Customer\")")). + guidance := RenderGuidance(doText: "Keep Type.where queries inside main() or named methods, and return named tuples so the result is testable and documentable.", dontText: "Do not hide fact-store scans behind a second db namespace. Query the fact type directly.", recommendText: "Use Type.where for filtered rows, Type.all for the dataset, and Type.count for totals."), + return (HtmlRichSectionData(id: "lib-db", title: "First-class fact database", p: "A fact type is its own SQL-like query surface. Direct facts, CSV facts, and compiler-linked .fx database rows share one VmFactStore.", p2: "Use Type.all, Type.where, Type.select, Type.count, aggregates, conditional mutations, and keyed joins. There is no public db helper namespace.", content: guidance, code: "Customer(name: \"Ada\", city: \"SEA\", active: 1.0).\nCustomer(name: \"Mina\", city: \"BLR\", active: 1.0).\n\nmain() =>\n rows := Customer.where(active: 1.0)\n return (count: count(data: rows), rows: rows)\nend", note: "Facts define the database contract directly. Keep type and field names stable and clear.", code2: "Customer.all()\nCustomer.where(name: \"Ada\")\nCustomer.count(match: {active: 1.0})\nCustomer.select(fields: [\"name\"], match: {active: 1.0})")). DocsLibraryJson() => cards := RenderModuleGrid(content: str.join(data: [ @@ -50,22 +50,21 @@ DocsLibraryMath() => RenderMiniCard(input: HtmlCardData(title: "Numeric", text: "abs, floor, ceil, round, sqrt, pow, log, log10, exp.")), RenderMiniCard(input: HtmlCardData(title: "Trigonometry", text: "sin, cos, tan, asin, acos, atan, atan2.")) ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-math", title: "Library: math", p: "The math module contains scalar numeric helpers. Use it for deterministic calculations around values already derived from facts or arrays.", p2: "Keep numeric inputs visible near the call. If the values come from facts, derive the numeric array first, then call math functions in a named method or main().", content: cards, code: "import \"math\".\n\nmain() =>\n root := math.sqrt(value: 16),\n distance := math.abs(value: -12),\n power := math.pow(base: 2, exponent: 5),\n rounded := math.round(value: 3.6),\n return (root: root, distance: distance, power: power, rounded: rounded).", note: "math works on scalar numbers. Use probability for distributions and ml for vector scoring.", code2: "angle := math.atan2(y: 1, x: 1)\nwave := math.sin(value: angle)\nrandom := math.random(min: 1, max: 10)")). + return (HtmlRichSectionData(id: "lib-math", title: "Library: math", p: "The math module contains scalar numeric helpers. Use it for deterministic calculations around values already derived from facts or arrays.", p2: "Keep numeric inputs visible near the call. If the values come from facts, derive the numeric array first, then call math functions in a named method or main().", content: cards, code: "import \"math\".\n\nmain() =>\n root := math.sqrt(value: 16),\n distance := math.abs(value: -12),\n power := math.pow(base: 2, exponent: 5),\n rounded := math.round(value: 3.6),\n return (root: root, distance: distance, power: power, rounded: rounded).", note: "Numeric results remain ordinary floating-point values and are not normalized to a truth range. Use ml only for its documented LibTorch operations.", code2: "angle := math.atan2(y: 1, x: 1)\nwave := math.sin(value: angle)\nrandom := math.random(min: 1, max: 10)")). DocsLibraryMl() => cards := RenderModuleGrid(content: str.join(data: [ RenderMiniCard(input: HtmlCardData(title: "Activation", text: "sigmoid and relu transform one numeric value.")), - RenderMiniCard(input: HtmlCardData(title: "Vectors", text: "dot compares two vectors by multiplication and sum.")), - RenderMiniCard(input: HtmlCardData(title: "Fact Mining", text: "profile_facts, cluster_facts, and discover_associations analyze key-value facts.")), - RenderMiniCard(input: HtmlCardData(title: "Models", text: "train_decision_tree and train_linear_regression return inspectable Felidae model facts.")) + RenderMiniCard(input: HtmlCardData(title: "Vectors", text: "dot computes a vector dot product.")), + RenderMiniCard(input: HtmlCardData(title: "Error", text: "meanSquaredError compares equally shaped numeric arrays.")) ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-ml", title: "Library: ml", p: "The ml module treats Felidae facts as an analyzable fact database. Use it for lightweight data mining: numeric profiling, k-means clustering, key-value association discovery, classification, and numeric prediction.", p2: "Models are returned as structured values with model_fx source text, so trained output can be saved as a .fx file and inspected like ordinary Felidae code/data.", content: cards, code: "import \"ml\".\n\nmain() =>\n customers := [\n {age: 24, spend: 120, visits: 3, segment: \"starter\", region: \"south\"},\n {age: 45, spend: 820, visits: 13, segment: \"premium\", region: \"west\"}\n ],\n profile := ml.profile_facts(facts: customers, features: [\"age\", \"spend\", \"visits\"]),\n clusters := ml.cluster_facts(facts: customers, features: [\"age\", \"spend\", \"visits\"], clusters: 2),\n model := ml.train_decision_tree(facts: customers, target: \"segment\", features: [\"age\", \"spend\", \"visits\"]),\n prediction := ml.predict(model: model, input: {age: 42, spend: 780, visits: 12}),\n return (profile: profile, clusters: clusters, prediction: prediction).", note: "Keep source facts visible near the model call. Use ml.save_model only when writing an explicit generated .fx model artifact is part of the workflow.", code2: "ml.correlate_facts(facts: rows, left: \"visits\", right: \"spend\")\nml.train_linear_regression(facts: rows, target: \"revenue\", feature: \"visitors\")\nml.predict_numeric_fact(facts: rows, input: {visitors: 220}, target: \"revenue\", feature: \"visitors\")")). + return (HtmlRichSectionData(id: "lib-ml", title: "Library: ml", p: "The ml module exposes the small set of deterministic LibTorch operations implemented by the runtime: sigmoid, relu, dot, and meanSquaredError.", p2: "These operations evaluate directly in RegisterVm. They do not train a model and do not force ordinary numeric results into the 0.0-to-1.0 range.", content: cards, code: "import \"ml\".\n\nmain() =>\n activation := ml.relu(value: -2.5),\n score := ml.dot(left: [1.5, -2.0, 3.0], right: [4.0, 0.5, -1.0]),\n loss := ml.meanSquaredError(left: [1.0, 2.0], right: [1.5, 1.0]),\n return (activation: activation, score: score, loss: loss).", note: "Only documented operations are available. A missing LibTorch backend raises an explicit runtime error.", code2: "ml.sigmoid(value: -3.0)\nml.relu(value: 4.25)\nml.dot(left: [1, 2], right: [3, 4])\nml.meanSquaredError(left: [1, 2], right: [1, 3])")). DocsLibrarySystem() => return (HtmlRichSectionData(id: "lib-system", title: "Library: system", p: "The system module provides low-level runtime inspection and development output helpers.", p2: "Prefer returning structured data from main() for stable program behavior. Use system.print for startup messages, service logs, or temporary development feedback.", content: "", code: "import \"system\".\n\nmain() =>\n system.print(value: \"checking docs\"),\n return (status: \"printed\").", note: "Printed output is useful for humans, but returned tuples are easier for docs, tests, and automation to verify.", code2: "type(value: [1, 2, 3], name: kind)\ninstanceof(value: 42, type: \"number\")")). DocsLibraryConsole() => - return (HtmlRichSectionData(id: "lib-console", title: "Library: console", p: "The console module provides interactive terminal input and output helpers.", p2: "Use console helpers for interactive scripts. Documentation and automated examples should usually return data from main() instead of requiring user input.", content: "", code: "import \"console\".\n\nTenCheck(x: number) =>\n x == 10,\n return (matched: true, message: \"x is ten\")\nelse\n return (matched: false, message: \"x is not ten\").\n\nmain() =>\n x := console.inputNumber(print: \"enter x: \"),\n return (x: x, check: TenCheck(x: x)).", note: "console.input returns text. Use console.inputNumber when the next condition should compare against a number such as x == 10.", code2: "name := console.input(print: \"enter name: \")\nconsole.write(value: \"Hello, \")\nconsole.writeLine(value: name)\nraw := console.readLine()")). + return (HtmlRichSectionData(id: "lib-console", title: "Library: console", p: "The console module provides interactive terminal input and output helpers.", p2: "Use console helpers for interactive scripts. Documentation and automated examples should usually return data from main() instead of requiring user input.", content: "", code: "import \"console\".\n\nTenCheck(x: number) =>\n x == 10,\n return (matched: 1.0, message: \"x is ten\")\nelse\n return (matched: 0.0, message: \"x is not ten\").\n\nmain() =>\n x := console.inputNumber(print: \"enter x: \"),\n return (x: x, check: TenCheck(x: x)).", note: "console.input returns text. Use console.inputNumber when the next condition should compare against a number such as x == 10.", code2: "name := console.input(print: \"enter name: \")\nconsole.write(value: \"Hello, \")\nconsole.writeLine(value: name)\nraw := console.readLine()")). DocsLibraryProcess() => guidance := RenderGuidance(doText: "Use process.platform for OS-aware tooling and keep process.exec commands explicit.", dontText: "Do not use process.exec for ordinary logic examples, docs rendering, or hidden application behavior.", recommendText: "When a command must run, return the command and output together so tests can audit it."), diff --git a/docs/methods.fx b/docs/methods.fx index c0d0bbb..7018e1d 100644 --- a/docs/methods.fx +++ b/docs/methods.fx @@ -1,5 +1,5 @@ import "html_components.fx". DocsMethods() => - guidance := RenderGuidance(doText: "Pass inputs into methods with named arguments, keep local values immutable with :=, and return named tuples that can be inspected by users and tests.", dontText: "Do not write a method as if a bare fact pattern inside it will magically scan every fact row. Make scans explicit with db.find, db.all, or lambda(FactType, row => ...).", recommendText: "Use main() as the public workflow. Put reusable transformations in named methods, then call those methods from main() so examples and server responses stay deterministic."), - return (HtmlRichSectionData(id: "methods", title: "Rules, Methods, And Returns", p: "Rules describe relationships that can be satisfied by facts. Methods are the best place to write application queries: collect fact rows, filter them, aggregate them, and return a named tuple from main() or another method. This makes the query repeatable instead of leaving it only as a terminal command.", p2: "Methods use strict named arguments and immutable values. A method processes the inputs passed to it; it does not implicitly iterate over the fact database. Use db helpers or lambda(Type, item => ...) when you intentionally want fact iteration. Fallback branches are ordered logic alternatives, and the first branch that returns a result wins.", content: guidance, code: "Person(name: \"Ada\", role: \"Engineer\").\nPerson(name: \"Mina\", role: \"Designer\").\n\nIsEngineer(person: any) =>\n person.role == \"Engineer\",\n return (name: person.name, allowed: \"true\")\nelse\n return (name: person.name, allowed: \"false\").\n\nmain() =>\n checks := lambda(Person, p => IsEngineer(person: p)),\n allowed := lambda(checks, row => row.allowed == \"true\"),\n return (total: count(checks), engineers: allowed).", note: "Use command-line queries when you want to inspect facts quickly. Use main() when the query is part of the program, an example, a test, or a documentation page.", code2: "Score(input: any) =>\n where input.value >= 10,\n return (label: \"high\", value: input.value)\nelse\n return (label: \"low\", value: input.value).\n\nmain() =>\n result := Score(input: {value: 12}),\n message := str.concat(left: result.label, right: \" score\"),\n return (message: message, score: result).")). + guidance := RenderGuidance(doText: "Pass inputs into methods with named arguments, keep local values immutable with :=, and return named tuples that can be inspected by users and tests.", dontText: "Do not write a method as if a bare fact pattern inside it will magically scan every fact row. Make scans explicit with Type.where(...), Type.all(), or lambda(Type, row => ...).", recommendText: "Use main() as the public workflow. Put reusable transformations in named methods, then call those methods from main() so examples and server responses stay deterministic."), + return (HtmlRichSectionData(id: "methods", title: "Rules, Methods, And Returns", p: "Rules describe relationships that can be satisfied by facts. Methods are the best place to write application queries: collect fact rows, filter them, aggregate them, and return a named tuple from main() or another method. This makes the query repeatable instead of leaving it only as a terminal command.", p2: "Methods use strict named arguments and immutable values. A method processes the inputs passed to it; it does not implicitly iterate over the fact database. Use Type queries or lambda(Type, item => ...) when you intentionally want fact iteration. Fallback branches are ordered logic alternatives, and the first branch that returns a result wins.", content: guidance, code: "Person(name: \"Ada\", role: \"Engineer\").\nPerson(name: \"Mina\", role: \"Designer\").\n\nIsEngineer(person: any) =>\n person.role == \"Engineer\",\n return (name: person.name, allowed: 1.0)\nelse\n return (name: person.name, allowed: 0.0).\n\nmain() =>\n checks := lambda(Person, p => IsEngineer(person: p)),\n allowed := lambda(checks, row => row.allowed == 1.0),\n return (total: count(checks), engineers: allowed).", note: "Use command-line queries when you want to inspect facts quickly. Use main() when the query is part of the program, an example, a test, or a documentation page.", code2: "Score(input: any) =>\n where input.value >= 10,\n return (label: \"high\", value: input.value)\nelse\n return (label: \"low\", value: input.value).\n\nmain() =>\n result := Score(input: {value: 12}),\n message := str.concat(left: result.label, right: \" score\"),\n return (message: message, score: result).")). diff --git a/docs/overview.fx b/docs/overview.fx index e324359..9f05a1c 100644 --- a/docs/overview.fx +++ b/docs/overview.fx @@ -1,5 +1,5 @@ import "html_components.fx". DocsOverview() => - guidance := RenderGuidance(doText: "Read facts as both source code and data rows. Keep examples runnable, and return useful results from main() so users can verify behavior immediately.", dontText: "Do not describe Felidae as a SQL wrapper. The database is the loaded fact base, and queries are ordinary Felidae methods, rules, lambdas, and aggregates.", recommendText: "For first-time users, follow this path: Basics, Start, Syntax, Facts DB, Queries, Methods, Probability, Server, Debugging, then Download."), + guidance := RenderGuidance(doText: "Read facts as both source code and data rows. Keep examples runnable, and return useful results from main() so users can verify behavior immediately.", dontText: "Do not describe Felidae as a SQL wrapper. The database is the loaded fact base, and queries are ordinary Felidae methods, rules, lambdas, and aggregates.", recommendText: "For first-time users, follow this path: Basics, Start, Syntax, Facts DB, Queries, Methods, Libraries, Server, Debugging, then Download."), return (HtmlRichSectionData(id: "overview", title: "Overview", p: "Felidae is a functional logic language where code and data share the same shape. Facts are executable knowledge: they can be queried, transformed, aggregated, searched, rendered into documentation, and analyzed by libraries without translating them into SQL.", p2: "If you are new, read Basics, Start, Syntax, Facts DB, Queries, and Methods first. Use Standard Library and Library Index when choosing APIs, then open the focused module page for signatures, examples, and operational cautions.", content: guidance, code: "Person(name: \"Alice\", role: \"Engineer\", office: \"SEA\").\nPerson(name: \"Mina\", role: \"Designer\", office: \"BLR\").\nPerson(name: \"Ravi\", role: \"Engineer\", office: \"BLR\").\n\nmain() =>\n engineers := lambda(Person, p => p.role == \"Engineer\"),\n offices := sort(lambda(engineers, p => p.office)),\n return (engineerCount: count(engineers), offices: offices).", note: "The overview stays stable and short. Detailed API risks, host access warnings, and module-specific behavior belong on the relevant module page.", code2: "DocsOverview() =>\n return (HtmlSectionData(\n id: \"overview\",\n title: \"Overview\",\n p: \"Felidae facts are executable data.\",\n code: \"Person(name: \\\"Alice\\\").\"\n )).\n\nDocSearchEntry(id: \"overview\", title: \"Overview\", route: \"#overview\").")). diff --git a/docs/playground.fx b/docs/playground.fx index 18bda45..1d13fc7 100644 --- a/docs/playground.fx +++ b/docs/playground.fx @@ -1,4 +1,4 @@ import "html_components.fx". DocsPlayground() => - return (HtmlPlaygroundData(id: "playground", title: "Playground", p: "Edit a Felidae sample and run it in the browser through the WASM interpreter generated from the C++ runtime. You can still copy or download the same source and run it with the native CLI.", example: "import (\"db\", \"probability\").\n\nRain(month: \"August\", day: {id: \"monday\", chance: 5.2}, day: {id: \"tuesday\", chance: 0.3}, day: {id: \"wednesday\", chance: 2.4}).\nCat1(name: \"kitten\").\nCat1(name: \"tiger\").\nCat1(name: \"lilly\").\nCat1(name: \"sony\").\nCat2(name: \"joy\").\nCat2(name: \"teddy\").\nCat2(name: \"snowbell\").\n\nCompareCats() =>\n leftRows := db.all(type: \"Cat1\"),\n rightRows := db.all(type: \"Cat2\"),\n total := count(leftRows) + count(rightRows),\n return (leftShare: count(leftRows) / total, rightShare: count(rightRows) / total, difference: (count(leftRows) - count(rightRows)) / total).\n\nmain() =>\n rain := db.first(type: \"Rain\", field: \"month\", equals: \"August\"),\n chances := lambda(rain.day, d => d.chance),\n distribution := probability.normalize(data: chances),\n return (month: rain.month, rainDistribution: distribution, cats: CompareCats()).", command: "./build/felidae felidae-snippet.fx", note: "Run loads docs/wasm/felidae_wasm.js. Build those assets with .\\build\\felidae.exe examples/wasm/wasm.fx on Windows or ./build/felidae examples/wasm/wasm.fx on Linux/macOS, then refresh the docs page.")). + return (HtmlPlaygroundData(id: "playground", title: "Playground", p: "Edit a Felidae sample and run it in the browser through the WASM interpreter generated from the C++ runtime. You can still copy or download the same source and run it with the native CLI.", example: "RainDay(month: \"August\", day: \"monday\", chance: 5.2).\nRainDay(month: \"August\", day: \"tuesday\", chance: 0.3).\nRainDay(month: \"August\", day: \"wednesday\", chance: 2.4).\nCat1(name: \"kitten\").\nCat1(name: \"tiger\").\nCat1(name: \"lilly\").\nCat1(name: \"sony\").\nCat2(name: \"joy\").\nCat2(name: \"teddy\").\nCat2(name: \"snowbell\").\n\nCompareCats() =>\n leftCount := Cat1.count(),\n rightCount := Cat2.count(),\n total := leftCount + rightCount,\n return (leftShare: leftCount / total, rightShare: rightCount / total, difference: (leftCount - rightCount) / total).\n\nmain() =>\n august := RainDay.where(month: \"August\"),\n averageChance := RainDay.average(field: \"chance\", match: {month: \"August\"}),\n return (days: august, averageChance: averageChance, cats: CompareCats()).", command: "./build/debug/felidae_vm build/debug/felidae-snippet.bin", note: "Compile the snippet into build/debug first. The browser version loads docs/wasm/felidae_wasm.js; build those assets in a named build subdirectory, then refresh the page." )). diff --git a/docs/queries.fx b/docs/queries.fx index 33df775..8adcac4 100644 --- a/docs/queries.fx +++ b/docs/queries.fx @@ -1,5 +1,5 @@ import "html_components.fx". DocsQueries() => - guidance := RenderGuidance(doText: "Put production queries in main() or named methods, return named tuples, and keep aggregate inputs visible near the aggregate call.", dontText: "Do not rely on a terminal query as the only record of business logic. Also avoid implicit fact iteration inside methods; use lambda(Type, row => ...) or db helpers intentionally.", recommendText: "Use CLI queries in parallel while developing, then move the final workflow into the .fx file so Celidae, docs, tests, and users all see the same behavior."), - return (HtmlRichSectionData(id: "queries", title: "Queries And Aggregates", p: "Prefer writing reusable queries inside main() or named methods. That keeps the program accountable: inputs, derived facts, aggregate calls, and return values all live in the same .fx file and can be checked by Celidae. Command-line queries are still supported, but they are best for quick inspection of loaded facts.", p2: "Inside methods, queries are explicit: use lambda(Type, item => ...) for fact iteration or the db module for no-SQL fact-store access. Available aggregate-style helpers include count, average, sum, min, max, sort, search, contains, lower, upper, and length. The db module exposes db.all, db.find, db.first, db.count, db.types, and db.fields.", content: guidance, code: "Customer(name: \"Ada\", city: \"SEA\", status: \"active\").\nCustomer(name: \"Mina\", city: \"BLR\", status: \"active\").\nCustomer(name: \"Ravi\", city: \"SEA\", status: \"inactive\").\n\nmain() =>\n sea := db.find(type: \"Customer\", field: \"city\", equals: \"SEA\"),\n activeSea := lambda(sea, row => row.status == \"active\"),\n names := sort(lambda(activeSea, row => row.name)),\n return (count: count(activeSea), names: names).", note: "CLI query mode stays useful for ad hoc inspection, for example ./build/felidae customers.fx '? Customer(name: Name, city: \"SEA\")'. For application behavior and documentation examples, prefer main() or named methods.", code2: "./build/felidae docs/server.fx '? DocSearchEntry(id: Id, title: Title)'\n\nSearchDocumentation(query: string) =>\n normalized := str.lower(data: query),\n matches := lambda(DocSearchEntry, entry => SearchDocumentationResult(entry: entry, query: normalized)),\n return (query: query, count: count(matches), results: matches).")). + guidance := RenderGuidance(doText: "Put production queries in main() or named methods, return named tuples, and keep aggregate inputs visible near the aggregate call.", dontText: "Do not rely on a terminal query as the only record of business logic or route facts through a retired db namespace.", recommendText: "Use Type.where for exact fields and Type.search for text, regex, hierarchy, or degree matching."), + return (HtmlRichSectionData(id: "queries", title: "Queries And Aggregates", p: "Reusable queries keep inputs, derived facts, aggregates, and returned evidence together in the .fx program.", p2: "Fact types expose all, where, select, search, count, numeric aggregates, conditional mutations, and keyed joins directly.", content: guidance, code: "Customer(name: \"Ada\", city: \"SEA\", active: 1.0).\nCustomer(name: \"Mina\", city: \"BLR\", active: 1.0).\nCustomer(name: \"Ravi\", city: \"SEA\", active: 0.0).\n\nmain() =>\n activeSea := Customer.where(city: \"SEA\").AndWhere(active: 1.0)\n return (count: count(data: activeSea), rows: activeSea)\nend", note: "Updates and deletes must follow a conditional where chain; joins require both key fields.", code2: "Customer.where(city: \"SEA\").limit(records: 100)\nCustomer.search(field: \"name\", query: \"%ad%\", type: \"like\")\nCustomer.average(field: \"score\", match: {active: 1.0})")). diff --git a/docs/syntax.fx b/docs/syntax.fx index 42cb660..50f9052 100644 --- a/docs/syntax.fx +++ b/docs/syntax.fx @@ -8,4 +8,4 @@ DocsSyntax() => comparisonsPanel := RenderExampleBlock(title: "Comparisons and fallback branches", text: "Comparisons can be used in where clauses, lambdas, and rule bodies. Return the boolean-shaped result so users can see exactly what matched.", code: comparisonsCode), panels := str.concat(left: callsPanel, right: comparisonsPanel), content := str.concat(left: guidance, right: panels), - return (HtmlRichSectionData(id: "syntax", title: "Syntax Essentials", p: "Felidae uses explicit named fields so data remains readable as both code and database rows. Bind locals with immutable :=, call modules with ., pass named arguments with :, terminate declarations with ., and prefer named arguments over positional guessing.", p2: "Use . for package calls and field access, for example array.get(...) and person.name. Use : for named arguments and local namespaces. :: is not part of current Felidae syntax. For string concatenation, use str.concat(left: value, right: suffix); both sides should be strings, so convert structured or numeric values first when needed.", content: content, code: "import (\"db\", \"json\", \"probability\", \"str\").\nPerson(name: \"Ravi\", age: 30, role: \"Engineer\").\n\nmain() =>\n ages := lambda(Person, p => p.age),\n average := probability.mean(data: ages),\n averageText := json.toText(data: average),\n label := str.concat(left: \"Average age: \", right: averageText),\n return (averageAge: average, label: label).", note: "Strict named fields are the bridge between logic syntax and fact-database readability. If the reader cannot tell what a value means from the field name, the fact probably needs a clearer shape.", code2: "Person(name: \"Alice\").\nvalue := array.get(data: [1, 2, 3], position: 0).\nx == person.name.\ntext := str.concat(left: \"hello\", right: \" world\").")). + return (HtmlRichSectionData(id: "syntax", title: "Syntax Essentials", p: "Felidae uses explicit named fields so data remains readable as both code and database rows. Bind locals with immutable :=, call modules with ., pass named arguments with :, terminate declarations with ., and prefer named arguments over positional guessing.", p2: "Use . for package calls and field access, for example array.get(...) and person.name. Use : for named arguments and local namespaces. :: is not part of current Felidae syntax. For string concatenation, use str.concat(left: value, right: suffix); both sides should be strings, so convert structured or numeric values first when needed.", content: content, code: "import (\"json\", \"str\").\nPerson(name: \"Ravi\", age: 30, role: \"Engineer\").\nPerson(name: \"Ada\", age: 42, role: \"Engineer\").\n\nmain() =>\n average := Person.average(field: \"age\"),\n averageText := json.toText(data: average),\n label := str.concat(left: \"Average age: \", right: averageText),\n return (averageAge: average, label: label).", note: "Strict named fields are the bridge between logic syntax and fact-database readability. If the reader cannot tell what a value means from the field name, the fact probably needs a clearer shape.", code2: "Person(name: \"Alice\").\nvalue := array.get(data: [1, 2, 3], position: 0).\nx == person.name.\ntext := str.concat(left: \"hello\", right: \" world\").")). diff --git a/docs/testing.fx b/docs/testing.fx index 21f0f1d..502390c 100644 --- a/docs/testing.fx +++ b/docs/testing.fx @@ -8,6 +8,6 @@ DocsTesting() => part1 := str.concat(left: smoke, right: unit), part2 := str.concat(left: part1, right: negative), cards := RenderGrid(content: str.concat(left: part2, right: ci)), - guidance := RenderGuidance(doText: "Test through main(), named methods, and stable returned tuples. Keep the expected value near the input data so a failed test reads like a small story.", dontText: "Do not rely only on one-off command-line queries for regression coverage. CLI queries are useful while debugging, but tests should be repeatable from a file.", recommendText: "Use examples/felidae_test_suite.fx as the current project-style test runner: it calls Felidae/Celidae, asserts output with str.contains, and records every case in one returned tuple."), + guidance := RenderGuidance(doText: "Test through main(), named methods, and stable returned tuples. Keep the expected value near the input data so a failed test reads like a small story.", dontText: "Do not rely only on one-off command-line queries for regression coverage. CLI queries are useful while debugging, but tests should be repeatable from a file.", recommendText: "Register representative v2_examples with CTest so each program is compiled to verified IR, executed by RegisterVm, and checked against a stable result."), content := str.concat(left: cards, right: guidance), - return (HtmlRichSectionData(id: "testing", title: "Testing Felidae Programs", p: "Felidae tests should look like Felidae programs. Put the behavior under test in named facts and methods, call it from main(), and return a tuple that contains the case name, expected value, actual value, and status. This keeps tests readable by people and easy to run from automation.", p2: "Use two layers: pure unit-style checks inside the language for data transformations, and process-based smoke tests when you need to verify interpreter commands, imports, diagnostics, native modules, file I/O, or examples. felidae_debug should own syntax and AST diagnostic checks through --check-json.", content: content, code: "AssertEquals(name: string, expected: any, actual: any) =>\n where expected == actual,\n return (name: name, status: \"passed\", expected: expected, actual: actual)\nelse\n return (name: name, status: \"failed\", expected: expected, actual: actual).\n\nAddTax(amount: number, rate: number) =>\n return (amount + (amount * rate)).\n\nmain() =>\n case1 := AssertEquals(name: \"adds tax\", expected: 110, actual: AddTax(amount: 100, rate: 0.10)),\n case2 := AssertEquals(name: \"keeps zero tax\", expected: 80, actual: AddTax(amount: 80, rate: 0)),\n failures := lambda([case1, case2], row => row.status == \"failed\"),\n return (status: \"tested\", passed: count([case1, case2]) - count(failures), failed: count(failures), cases: [case1, case2]).", note: "Best practice: keep application examples and tests centered on main(). CLI queries are still supported, but main() is what docs, CI, felidae_debug checks, and users can repeat.", code2: "import (\"process\", \"str\").\n\nAssertContains(name: string, output: string, expected: string) =>\n ok := str.contains(data: output, needle: expected),\n where ok == \"true\",\n return (name: name, status: \"passed\").\n\nRunCase(name: string, command: string, expected: string) =>\n output := process.exec(command: command),\n return (AssertContains(name: name, output: output, expected: expected)).\n\nmain() =>\n docsCheck := RunCase(name: \"docs syntax\", command: \"build\\\\felidae_debug.exe docs\\\\server.fx --check-json\", expected: \"ok\"),\n basics := RunCase(name: \"arithmetic example\", command: \"build\\\\felidae.exe examples\\\\arithmetic_and_boolean.fx\", expected: \"status\"),\n return (status: \"smoke\", cases: [docsCheck, basics]).")). + return (HtmlRichSectionData(id: "testing", title: "Testing Felidae Programs", p: "Felidae tests should look like Felidae programs. Put the behavior under test in named facts and methods, call it from main(), and return a tuple that contains the case name, expected value, actual value, and status. This keeps tests readable by people and easy to run from automation.", p2: "Use two layers: pure unit-style checks inside the language and CTest integration cases that compile v2 examples to binary IR and execute them with RegisterVm. felidae_debug owns syntax and compiler-high-level-IR diagnostics through --check-json.", content: content, code: "AssertEquals(name: string, expected: any, actual: any) =>\n where expected == actual\n return (name: name, status: \"passed\", expected: expected, actual: actual)\nelse\n return (name: name, status: \"failed\", expected: expected, actual: actual)\nend\n\nAddTax(amount: number, rate: number) =>\n return amount + amount * rate\nend\n\nmain() =>\n case1 := AssertEquals(name: \"adds tax\", expected: 110, actual: AddTax(amount: 100, rate: 0.10))\n case2 := AssertEquals(name: \"keeps zero tax\", expected: 80, actual: AddTax(amount: 80, rate: 0.0))\n failures := lambda([case1, case2], row => row.status == \"failed\")\n return (status: \"tested\", passed: count([case1, case2]) - count(failures), failed: count(failures), cases: [case1, case2])\nend", note: "Keep application examples and tests centered on main(). That is the repeatable contract used by documentation, CTest, the compiler, and RegisterVm.", code2: "# Run registered source-to-VM examples from the build tree:\nctest --test-dir build/debug -L examples --output-on-failure" )). diff --git a/docs_language.md b/docs_language.md index ffe06b8..9489ffe 100644 --- a/docs_language.md +++ b/docs_language.md @@ -79,7 +79,7 @@ import "directory" import "directory/*" import ("one.fx", "two.fx") import "math" -import ("file", "math", "ml", "db", "probability") +import ("file", "math", "ml", "db") import "system" # optional; system is available automatically ``` @@ -229,6 +229,31 @@ Person(name: "Default", age: 0, country: "India") Employee extend Person(name: "Ravi", age: 30, role: "Engineer") ``` +For an explicit reusable schema, declare a compiler-level fact class. Classes +and methods nested inside them require `end`; instances remain ordinary facts: + +```Felidae +class Person + name: string + age: number + index(name) + index(name, age) + + adult(minimumAge: number) => + where age >= minimumAge + return 1.0 + else + return 0.0 + end +end + +Person(name: "Ada", age: 32) +``` + +Class fields constrain source fact rows, inherited fields are accepted, and +index declarations are carried in the existing executable fact-type metadata. +There is no runtime class object or second interpreter. + ## Hierarchical Fact Queries Facts are first-class values. Query their declared type directly; no synthetic @@ -240,7 +265,7 @@ limited := active.limit(records: 100) teachers := School.join(type: Teacher, left: "id", right: "school_id") changed := School.where(city: "BLR").update(values: {active: 0.0}) removed := School.where(active: 0.0).delete() -titles := School.search(field: "name", query: "%academy%", mode: "like", +titles := School.search(field: "name", query: "%academy%", type: "like", case: "insensitive") ``` @@ -259,51 +284,19 @@ ranges or closeness. Text search supports exact/prefix/suffix/contains, SQL LIKE (`%` and `_`), and regular-expression modes. Degree search preserves intermediate values and returns the matching facts in creation order. -Use `.depends(on: Fact(...))` for hard existential requirements and -`.relate(to: Fact(...), as: Relationship(...), degree: ..., confidence: ...)` -for generic relationship evidence. Dependencies are AND requirements for a -stored fact and produce an `unresolved` comparison result when absent. -Relationship names, degree combination, and domain judgment remain data and -target-family rule decisions; the runtime does not impose similarity meaning. -Relationship evidence is queried as ordinary typed facts. Guards produce -numeric truth (`0.0` or `1.0`). - -### Dynamic method references - -`.references(by: owner::method, factor: ..., as: Reference(...))` attaches a -pure executable derivation to one stored fact. It is neither a hard dependency -nor a semantic relationship. Evaluate it explicitly with -`Fact.references(input: fact)`; this returns ordered `ReferenceResult` values -whose `result` field is a typed fact. A temporary `factor:` supplied to -`Fact.references` is an ephemeral override and never replaces the attachment's -default-factor canonical result. - -Referenced methods must declare compatible typed `input` and `factor` -parameters, return `ReferenceResult(result: TypedFact(...))`, and use only -pure operations (typed exceptions may propagate). Reference results are kept -outside ordinary fact lookup, unification, and dependencies; user rules must -retrieve and consume them deliberately. - -```logic -motion.references( - by: Physics::velocity, - factor: Time(seconds: 2.0), - as: Reference(name: "velocity") -) -velocity := Fact.references(input: motion, as: Reference(name: "velocity")) -``` +Relationships and dependency evidence are ordinary typed facts, not hidden +verbs or a second relationship runtime. For example, declare +`Relationship(from: ..., to: ..., name: ..., degree: ...)`, query it with +`Relationship.where(...)`, and join it to the relevant entity type by explicit +keys. Domain rules decide how graded evidence is combined. Facts, maps, arrays, +strings, and arbitrary numbers are not implicitly Boolean: use an explicit +comparison in `where` or `if` when a branch requires numeric truth. -The callable must be declared or imported before the attachment. Constructors, -normal rule matching, Celidae, and debugger inspection never evaluate -references. - -Comparison values can be passed through `then` and compared again. The built-in -core `Comparison.membership` method provides the standard `previous*` -micro-fact projection and returns `nil` for `unresolved` or `incomparable` -results. A domain may declare its own normal `Comparison.membership` method -before execution when it needs a different chained projection. Comparison -facts, maps, arrays, strings, and numbers are not implicitly Boolean: use an -explicit field comparison in `where` or `if`. +`commonAncestors(left:, right:)` returns the complete deterministic candidate +set in stable order. Felidae does not expose context-free “lowest” or “highest” +ancestor choices. When an application needs a contextual score, it explicitly +calls `ssm.suggest(input:)`; that result is a finite, unrestricted `double`, +not a degree clamped to `[0, 1]`, and branching must compare it explicitly. Use `type(value: item, name: TypeName)` to read a value's concrete type, and `instanceof(value: item, type: Person)` to check whether a value is an instance @@ -314,9 +307,9 @@ directly with `:=`: ```Felidae CheckPerson(input: any) => instanceof(value: input, type: Person) - return (ok: true) + return (ok: 1.0) else - return (ok: false) + return (ok: 0.0) ``` `lambda(Type, item => condition)` filters facts of a type, and @@ -404,27 +397,26 @@ and branching without a separate `where`: main() => x := 10 if x == 10 - return (ok: true) + return (ok: 1.0) else - return (ok: false) + return (ok: 0.0) ``` ### Calling Conventions -A method or native module call can be used two ways. The safest and most -uniform is direct assignment, capturing the whole return tuple (or the single -returned value, for a bare `return expr`): +A method or compiler-known runtime-library call can be used in direct +assignment, capturing the whole return tuple (or the single returned value, +for a bare `return expr`): ```Felidae s := math.sin(value: 0) result := HotAdd(value: 1) ``` -User-defined predicates (and native module calls resolved by name rather than -by a fixed builtin token) also accept an output-binding convenience: add a -named argument whose name matches a field of the callee's `return` tuple and -whose value is a fresh, not-yet-declared variable. That variable is bound to -the matching field after the call: +User-defined predicates also accept an output-binding convenience: add a named +argument whose name matches a field of the callee's `return` tuple and whose +value is a fresh, not-yet-declared variable. That variable is bound to the +matching field after the call: ```Felidae HotAdd(value: int) => @@ -510,7 +502,7 @@ import "exception" CalculatorActions.handle(result: Result) => if result.error.kind == "DivisionByZero" then - return exception.ok(value: {quotient: 0, recovered: true}) + return exception.ok(value: {quotient: 0, recovered: 1.0}) else return result @@ -574,8 +566,6 @@ name := "Felidae" system.printf("Hello {name}\n") math.sqrt(value: 81) math.pow(base: 2, exponent: 8) -probability.mean(data: [2, 4, 6, 8]) -probability.binomialPmf(trials: 10, successes: 3, p: 0.5) ml.dot(left: [1, 2, 3], right: [4, 5, 6]) ml.meanSquaredError(left: [1, 2, 3], right: [1, 2, 5]) http.get(url: "https://example.com") @@ -602,17 +592,27 @@ immediately participate in hierarchy queries and concrete type operations: There is no synthetic `Fact.*` namespace or lazy `FactSelection` value. There is no public `db.sync()` operation. Facts imported from CSV with a source -path retain that ownership. `Type.insert`, `Type.update`, and `Type.delete` -automatically persist each affected CSV source through atomic replacement; -compiler parsing never performs database I/O. Inserts without an inferred or -explicit source remain in memory. - -`probability.fx` adds common probability and statistics helpers including -mean, variance, standard deviation, normalization, entropy, covariance, -correlation, Bernoulli, binomial, Poisson, normal, uniform, sample, and weighted -choice. -`ml.dot` and `ml.meanSquaredError` use Eigen when it is available at build time, -with a portable C++ fallback for MVP builds. +path retain that ownership. A source file may also import a fact-only `.fx` +database; the compiler links its rows into executable IR and records their +source ownership without adding a runtime parser: + +```Felidae +import "schools.fx" + +main() => + changed := School.where(id: 7).update(values: {active: 0.0}) + return changed +end +``` + +`Type.insert`, `Type.update`, and `Type.delete` automatically persist each +affected CSV or `.fx` source through atomic replacement. Compiler parsing +never writes a database. Inserts without an inferred or explicit source remain +in memory. + +`ml.sigmoid`, `ml.relu`, `ml.dot`, and `ml.meanSquaredError` execute through the +real LibTorch tensor backend. A build without that backend reports an explicit +runtime error instead of substituting a fake or portable implementation. `thread.fx` declares the cooperative concurrency API. `thread.createThread`, `thread.start`, `thread.status`, and `thread.result` run methods on immutable diff --git a/emacs-extension b/emacs-extension index 9c6d71c..f97dd35 160000 --- a/emacs-extension +++ b/emacs-extension @@ -1 +1 @@ -Subproject commit 9c6d71cff04b67cd9399bc86e7d03034c76ba4ec +Subproject commit f97dd3584feb085b1756c7b857788e7994adcb31 diff --git a/intellij-idea-extension b/intellij-idea-extension index d054ea7..2a00947 160000 --- a/intellij-idea-extension +++ b/intellij-idea-extension @@ -1 +1 @@ -Subproject commit d054ea7e34613d7af0f58112c0af81be8feac247 +Subproject commit 2a0094796563da167d01e475b4dca0c1f642d313 diff --git a/notepad-plus-plus-extension b/notepad-plus-plus-extension index f8dc6fd..7a8f494 160000 --- a/notepad-plus-plus-extension +++ b/notepad-plus-plus-extension @@ -1 +1 @@ -Subproject commit f8dc6fdebf168c89aa52be4a8aafcda6ae5db9c2 +Subproject commit 7a8f49415c8807e927af21601b637246a6dd12de diff --git a/src/AST.h b/src/AST.h index d8bc6ac..893997f 100644 --- a/src/AST.h +++ b/src/AST.h @@ -47,7 +47,7 @@ enum class GoalKind { Or }; -enum class StatementKind { Import, Clause, GlobalBinding }; +enum class StatementKind { Import, Clause, GlobalBinding, Class }; enum class ClauseKind { Fact, Rule, Method, NativeDeclaration, EntryCall }; @@ -943,6 +943,11 @@ class ClauseStmt final : public Statement { bool emptyDeclaration = false; ClauseKind clauseKind = ClauseKind::Rule; std::string module; + // Non-empty only for a fact row linked from a fact-only .fx database. + // Compiler lowering carries these already-encoded path pieces into + // MakeFact; the AST itself remains compiler-only and the VM never parses a + // source file to recover ownership. + std::shared_ptr> persistenceSource; // An annotation is a normal method application evaluated against this // declaration. Built-in annotations and user annotations share this AST. std::vector annotations; @@ -1009,12 +1014,78 @@ class GlobalBindingStmt final : public Statement { } }; +struct ClassFieldDecl { + std::string name; + SymbolId nameId = 0; + std::string typeName; + SourceSpan sourceSpan; +}; + +struct ClassIndexDecl { + std::vector fields; + std::vector fieldIds; + SourceSpan sourceSpan; +}; + +// Compiler-only fact schema. It lowers into the existing IrFactType table; +// RegisterVm never receives or interprets this syntax-shaped declaration. +class ClassStmt final : public Statement { +public: + ClassStmt(std::string name, SymbolId nameId, + std::vector parentNames, + std::vector fields, + std::vector indexes = {}, + std::vector> methods = {}) + : name(std::move(name)), nameId(nameId), + parentNames(std::move(parentNames)), fields(std::move(fields)), + indexes(std::move(indexes)), + methods(std::move(methods)) {} + + std::string name; + SymbolId nameId = 0; + std::vector parentNames; + std::vector fields; + std::vector indexes; + std::vector> methods; + + StatementKind kind() const override { return StatementKind::Class; } + std::string debug() const override { + std::ostringstream oss; + oss << "class " << name; + if (!parentNames.empty()) { + oss << " extend "; + for (std::size_t i = 0; i < parentNames.size(); ++i) { + if (i) + oss << ", "; + oss << parentNames[i]; + } + } + oss << '\n'; + for (const auto &field : fields) + oss << " " << field.name << ": " << field.typeName << '\n'; + for (const auto &index : indexes) { + oss << " index("; + for (std::size_t i = 0; i < index.fields.size(); ++i) { + if (i) + oss << ", "; + oss << index.fields[i]; + } + oss << ")\n"; + } + for (const auto &method : methods) + oss << " " << method->debug() << '\n'; + oss << "end"; + return oss.str(); + } +}; + class Program final : public AstNode { public: std::vector> statements; std::vector> imports; std::vector> clauses; std::vector> globals; + std::vector> classes; void addStatement(std::shared_ptr statement) { switch (statement->kind()) { @@ -1027,6 +1098,11 @@ class Program final : public AstNode { case StatementKind::GlobalBinding: globals.push_back(std::static_pointer_cast(statement)); break; + case StatementKind::Class: + classes.push_back(std::static_pointer_cast(statement)); + for (const auto &method : classes.back()->methods) + clauses.push_back(method); + break; } statements.push_back(std::move(statement)); } diff --git a/src/BuiltinRegistry.cpp b/src/BuiltinRegistry.cpp index 784ac68..af68e1c 100644 --- a/src/BuiltinRegistry.cpp +++ b/src/BuiltinRegistry.cpp @@ -2,6 +2,8 @@ #include "SentencePieceModel.h" +#include +#include #include #include #include @@ -12,6 +14,10 @@ namespace Felidae { namespace { +constexpr std::array kBuiltinModules{ + "json", "csv", "group", "set", "ml", "array", "math", "str", "file", + "system"}; + constexpr BuiltinInfo kBuiltinInfos[] = { {BuiltinId::Unknown, "", BuiltinEffect::Volatile}, {BuiltinId::Throw, "throw", BuiltinEffect::WritesExternalState}, @@ -79,17 +85,11 @@ constexpr BuiltinInfo kBuiltinInfos[] = { {BuiltinId::FileDeleteFile, "file:deleteFile", BuiltinEffect::WritesExternalState}, {BuiltinId::CommonAncestors, "commonAncestors", BuiltinEffect::Pure}, - {BuiltinId::LowestCommonAncestor, "lowestCommonAncestor", - BuiltinEffect::Pure}, - {BuiltinId::HighestCommonAncestor, "highestCommonAncestor", - BuiltinEffect::Pure}, {BuiltinId::AncestorAnalysis, "ancestorAnalysis", BuiltinEffect::Pure}, // Mutates the fact store (see the RegisterVm.cpp dispatch case) -- // WritesExternalState because it mutates the retained fact store. {BuiltinId::PropagateFact, "propagateFact", BuiltinEffect::WritesExternalState}, - {BuiltinId::DependencySatisfied, "Dependency:satisfied", - BuiltinEffect::Pure}, {BuiltinId::JsonObject, "json:object", BuiltinEffect::Pure}, {BuiltinId::JsonParse, "json:parse", BuiltinEffect::Pure}, {BuiltinId::JsonGet, "json:get", BuiltinEffect::Pure}, @@ -135,39 +135,6 @@ constexpr BuiltinInfo kBuiltinInfos[] = { {BuiltinId::MathMul, "math:mul", BuiltinEffect::Pure}, {BuiltinId::MathDiv, "math:div", BuiltinEffect::Pure}, {BuiltinId::MathMod, "math:mod", BuiltinEffect::Pure}, - {BuiltinId::ProbabilityMean, "probability:mean", BuiltinEffect::Pure}, - {BuiltinId::ProbabilityVariance, "probability:variance", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityStddev, "probability:stddev", BuiltinEffect::Pure}, - {BuiltinId::ProbabilityNormalize, "probability:normalize", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityEntropy, "probability:entropy", BuiltinEffect::Pure}, - {BuiltinId::ProbabilityCovariance, "probability:covariance", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityCorrelation, "probability:correlation", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityBernoulli, "probability:bernoulli", - BuiltinEffect::Volatile}, - {BuiltinId::ProbabilityBinomialPmf, "probability:binomialPmf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityBinomialCdf, "probability:binomialCdf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityPoissonPmf, "probability:poissonPmf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityPoissonCdf, "probability:poissonCdf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityNormalPdf, "probability:normalPdf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityNormalCdf, "probability:normalCdf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityUniformPdf, "probability:uniformPdf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilityUniformCdf, "probability:uniformCdf", - BuiltinEffect::Pure}, - {BuiltinId::ProbabilitySample, "probability:sample", - BuiltinEffect::Volatile}, - {BuiltinId::ProbabilityWeightedChoice, "probability:weightedChoice", - BuiltinEffect::Volatile}, {BuiltinId::ReasoningContrary, "Reasoning:contrary", BuiltinEffect::WritesExternalState}, {BuiltinId::ReasoningProve, "Reasoning:prove", @@ -319,6 +286,11 @@ builtinsByPieceIds() { } // namespace +bool isBuiltinModuleName(std::string_view name) { + return std::find(kBuiltinModules.begin(), kBuiltinModules.end(), name) != + kBuiltinModules.end(); +} + BuiltinId builtinIdForName(const std::string &name) { return builtinIdForName(std::string_view(name)); } diff --git a/src/BuiltinRegistry.h b/src/BuiltinRegistry.h index 080b824..66385ca 100644 --- a/src/BuiltinRegistry.h +++ b/src/BuiltinRegistry.h @@ -34,6 +34,10 @@ BuiltinEffect builtinEffect(BuiltinId id); BuiltinEffect builtinEffect(const std::string& name); bool isBuiltinPure(BuiltinId id); bool isBuiltinPure(const std::string& name); +// Compiler-known namespaces do not identify source files and need no module +// linking. Keep this decision beside the builtin registry so frontend import +// resolution and IR lowering cannot maintain divergent allowlists. +bool isBuiltinModuleName(std::string_view name); // Every registered builtin except the Unknown sentinel, in table order. const std::vector& allBuiltins(); diff --git a/src/CompilerFrontend.cpp b/src/CompilerFrontend.cpp index d85fe09..a1648e4 100644 --- a/src/CompilerFrontend.cpp +++ b/src/CompilerFrontend.cpp @@ -1,5 +1,6 @@ #include "CompilerFrontend.h" +#include "BuiltinRegistry.h" #include "IntegerParser.h" #include "IntegerTokenList.h" #include "IrCodeGenerator.h" @@ -18,6 +19,7 @@ #include #include #include +#include #include #include @@ -106,10 +108,146 @@ Program parseProgramFile(const fs::path &path, const CompilerOptions &options) { options); } -IrModule compileProgramTextToIr(std::string text, - const CompilerOptions &options) { - auto module = - IrCodeGenerator{}.compile(parseProgramText(std::move(text), options)); +namespace { + +PieceSequence encodePersistenceSource(const fs::path &path) { + std::vector encoded; + const auto spelling = path.string(); + const auto status = felidaeSentencePieceModel().Encode(spelling, &encoded); + if (!status.ok() || encoded.empty()) { + throw IntegerParserError("fact database path cannot be encoded: " + + spelling); + } + PieceSequence pieces; + pieces.reserve(encoded.size()); + for (const int piece : encoded) { + if (piece < 0) + throw IntegerParserError( + "SentencePiece emitted an invalid fact database path piece"); + pieces.push_back(static_cast(piece)); + } + return pieces; +} + +fs::path resolveFactDatabasePath(const fs::path &importer, + std::string_view imported) { + fs::path candidate{std::string(imported)}; + if (candidate.is_relative()) + candidate = importer.parent_path() / candidate; + candidate = fs::absolute(candidate).lexically_normal(); + std::error_code error; + if (!fs::is_regular_file(candidate, error)) { + throw IntegerParserError("fact database import is not a file: " + + candidate.string()); + } + const auto canonical = fs::weakly_canonical(candidate, error); + return error ? candidate : canonical; +} + +class FactDatabaseLinker { +public: + explicit FactDatabaseLinker(const CompilerOptions &options) + : options_(options) {} + + void link(const fs::path &path) { + const auto key = path.string(); + if (linked_.contains(key)) + return; + if (!visiting_.insert(key).second) + throw IntegerParserError("cyclic fact database import: " + key); + + Program database; + try { + database = parseProgramText(readSourceFile(path), options_); + } catch (const std::exception &error) { + visiting_.erase(key); + throw IntegerParserError("cannot parse fact database '" + key + + "': " + error.what()); + } + for (const auto &import : database.imports) { + if (!import) + throw IntegerParserError("invalid import in fact database: " + key); + for (const auto &name : import->paths) { + if (isBuiltinModuleName(name)) + continue; + if (fs::path(name).extension() != ".fx") { + throw IntegerParserError("unsupported fact database import '" + + name + "' in " + key); + } + link(resolveFactDatabasePath(path, name)); + } + } + if (!database.globals.empty()) { + throw IntegerParserError("fact database must not declare globals: " + + key); + } + const auto owner = std::make_shared( + encodePersistenceSource(path)); + for (auto &clause : database.clauses) { + if (!clause || !clause->isFact() || !clause->annotations.empty()) { + throw IntegerParserError( + "fact database may contain only unannotated fact rows: " + key); + } + clause->persistenceSource = owner; + facts_.push_back(std::move(clause)); + } + visiting_.erase(key); + linked_.insert(key); + } + + std::vector> takeFacts() { + return std::move(facts_); + } + +private: + const CompilerOptions &options_; + std::unordered_set visiting_; + std::unordered_set linked_; + std::vector> facts_; +}; + +Program linkFactDatabases(Program program, const fs::path &entry, + const CompilerOptions &options) { + FactDatabaseLinker linker(options); + std::vector> remainingImports; + for (const auto &import : program.imports) { + if (!import) + throw IntegerParserError("invalid source import"); + std::vector remainingPaths; + for (const auto &name : import->paths) { + if (fs::path(name).extension() == ".fx") + linker.link(resolveFactDatabasePath(entry, name)); + else + remainingPaths.push_back(name); + } + if (!remainingPaths.empty()) + remainingImports.push_back( + std::make_shared(std::move(remainingPaths))); + } + + Program linked; + for (auto &import : remainingImports) + linked.addStatement(std::move(import)); + for (auto &fact : linker.takeFacts()) + linked.addStatement(std::move(fact)); + for (auto &global : program.globals) + linked.addStatement(std::move(global)); + std::unordered_set classMethods; + for (const auto &declaration : program.classes) + for (const auto &method : declaration->methods) + classMethods.insert(method.get()); + for (auto &declaration : program.classes) + linked.addStatement(std::move(declaration)); + for (auto &clause : program.clauses) + if (!classMethods.contains(clause.get())) + linked.addStatement(std::move(clause)); + return linked; +} + +} // namespace + +static IrModule compileProgramToIr(Program program) { + auto module = IrCodeGenerator{}.compile(std::move(program)); std::vector symbols; const auto collectProgram = [&](const FelidaeIr &program) { symbols.insert(symbols.end(), program.symbols.begin(), @@ -128,6 +266,8 @@ IrModule compileProgramTextToIr(std::string text, for (const auto &type : module.factTypes) { symbols.push_back(type.symbol); symbols.insert(symbols.end(), type.parents.begin(), type.parents.end()); + for (const auto &index : type.indexes) + symbols.insert(symbols.end(), index.begin(), index.end()); } std::sort(symbols.begin(), symbols.end()); symbols.erase(std::unique(symbols.begin(), symbols.end()), symbols.end()); @@ -183,15 +323,25 @@ IrModule compileProgramTextToIr(std::string text, remap(type.symbol); for (auto &parent : type.parents) remap(parent); + for (auto &index : type.indexes) + for (auto &field : index) + remap(field); } module.sentencePieceModelIdentity = felidaeSentencePieceModelIdentity(); return module; } +IrModule compileProgramTextToIr(std::string text, + const CompilerOptions &options) { + return compileProgramToIr(parseProgramText(std::move(text), options)); +} + IrModule compileProgramFileToIr(const fs::path &path, const CompilerOptions &options) { - return compileProgramTextToIr(readSourceFile(resolveProgramEntryPath(path)), - options); + const auto entry = resolveProgramEntryPath(path); + auto program = parseProgramText(readSourceFile(entry), options); + return compileProgramToIr(linkFactDatabases(std::move(program), entry, + options)); } std::optional tryCompileExpressionTextToIr(const std::string &text) { diff --git a/src/FelidaeGrammar.h b/src/FelidaeGrammar.h index 0b154c8..da5571d 100644 --- a/src/FelidaeGrammar.h +++ b/src/FelidaeGrammar.h @@ -165,8 +165,6 @@ inline constexpr BuiltinTokenDefinition kBuiltinTokens[] = { {"where", "WHERE"}, {"extend", "EXTEND"}, {"lambda", "LAMBDA"}, - {"true", "TRUE"}, - {"false", "FALSE"}, {"nil", "NIL"}, {"(", "LPAREN"}, {")", "RPAREN"}, @@ -270,8 +268,6 @@ inline constexpr bool isKeywordWordTokenId(TokenId::Id id) { case TokenId::WHERE: case TokenId::EXTEND: case TokenId::LAMBDA: - case TokenId::TRUE: - case TokenId::FALSE: case TokenId::NIL: return true; default: diff --git a/src/FelidaeIr.h b/src/FelidaeIr.h index 1fbe323..5212caf 100644 --- a/src/FelidaeIr.h +++ b/src/FelidaeIr.h @@ -30,6 +30,9 @@ enum class IrOpcode : std::uint8_t { CallNamed, Builtin, SemanticEval, + // [opcode, destination, type-symbol-table index, source-text index]. The + // source index is one-based; zero creates an in-memory fact. A nonzero + // source is emitted only for compiler-linked fact-only .fx database rows. MakeFact, MakeArray, MakeMap, diff --git a/src/IntegerParser.cpp b/src/IntegerParser.cpp index 76efc32..dfbc9f4 100644 --- a/src/IntegerParser.cpp +++ b/src/IntegerParser.cpp @@ -48,8 +48,6 @@ bool isFragmentableBuiltin(TokenId::Id id) { case TokenId::WHERE: case TokenId::EXTEND: case TokenId::LAMBDA: - case TokenId::TRUE: - case TokenId::FALSE: case TokenId::NIL: return true; default: @@ -999,6 +997,7 @@ IntegerParser::parseGoalList(TokenId::Id terminator) { } std::shared_ptr IntegerParser::parseStatement() { + lastClauseUsedBlockEnd_ = false; skipTrivia(); const std::size_t begin = byte_; std::vector annotations; @@ -1008,6 +1007,14 @@ std::shared_ptr IntegerParser::parseStatement() { } for (const auto &annotation : annotations) prepareOperatorAnnotation(annotation); + if (annotations.empty() && atNameRange()) { + const auto savedByte = byte_; + const auto savedPiece = piece_; + if (consumeNameRange() == "class") + return parseClassStatement(begin); + byte_ = savedByte; + piece_ = savedPiece; + } if (match(TokenId::IMPORT)) { if (!annotations.empty()) throw IntegerParserError( @@ -1087,7 +1094,7 @@ std::shared_ptr IntegerParser::parseStatement() { } fallbackBranches.push_back(std::move(branch)); } - (void)matchBlockEnd(); + lastClauseUsedBlockEnd_ = matchBlockEnd(); } } consumeStatementTerminator(begin); @@ -1117,6 +1124,88 @@ std::shared_ptr IntegerParser::parseStatement() { return result; } +std::shared_ptr +IntegerParser::parseClassStatement(std::size_t begin) { + const auto className = consumeQualifiedName(false); + if (!className.isCapitalized) + throw IntegerParserError("Class names must begin with an uppercase letter"); + + std::vector parents; + if (match(TokenId::EXTEND)) { + do { + parents.push_back(consumeQualifiedName().spelling); + } while (match(TokenId::COMMA)); + } + if (!lineBreakBeforeNextSignificantPiece()) + throw IntegerParserError("Expected newline after class declaration"); + + std::vector fields; + std::vector indexes; + std::vector> methods; + std::unordered_set fieldIds; + while (!atEnd() && !atBlockEnd()) { + const auto fieldBegin = byte_; + const auto fieldPiece = piece_; + const auto field = consumeQualifiedName(false); + if (field.spelling == "index" && at(TokenId::LPAREN)) { + (void)match(TokenId::LPAREN); + ClassIndexDecl index; + do { + const auto indexedField = consumeQualifiedName(false); + index.fields.push_back(indexedField.spelling); + index.fieldIds.push_back(indexedField.nameId); + } while (match(TokenId::COMMA)); + require(TokenId::RPAREN, "Expected ')' after class index fields"); + if (index.fields.empty()) + throw IntegerParserError("Class index requires at least one field"); + consumeStatementTerminator(fieldBegin); + index.sourceSpan = span(fieldBegin, byte_); + indexes.push_back(std::move(index)); + continue; + } + if (at(TokenId::LPAREN)) { + byte_ = fieldBegin; + piece_ = fieldPiece; + auto statement = parseStatement(); + auto method = std::dynamic_pointer_cast(statement); + if (!method || method->clauseKind != ClauseKind::Method) + throw IntegerParserError("Expected a method declaration in class '" + + className.spelling + "'"); + if (!lastClauseUsedBlockEnd_) + throw IntegerParserError("Class method '" + method->head.name + + "' must end with 'end'"); + method->head.args.insert( + method->head.args.begin(), + Arg("self", symbolIdForName("self"), + std::make_shared(className.spelling, + className.nameId))); + method->head.name = className.spelling + "." + method->head.name; + method->head.nameId = symbolIdForName(method->head.name); + methods.push_back(std::move(method)); + continue; + } + require(TokenId::COLON, "Expected ':' after class field name"); + const auto type = consumeQualifiedName(); + if (!isFelidaeLikelyTypeName(type.spelling)) + throw IntegerParserError("Expected a type name for class field '" + + field.spelling + "'"); + if (!fieldIds.insert(field.nameId).second) + throw IntegerParserError("Duplicate class field '" + field.spelling + + "'"); + consumeStatementTerminator(fieldBegin); + ClassFieldDecl declaration{field.spelling, field.nameId, type.spelling, + span(fieldBegin, byte_)}; + fields.push_back(std::move(declaration)); + } + if (!matchBlockEnd()) + throw IntegerParserError("Expected 'end' after class declaration"); + auto result = std::make_shared( + className.spelling, className.nameId, std::move(parents), + std::move(fields), std::move(indexes), std::move(methods)); + stamp(result, begin, byte_); + return result; +} + Program IntegerParser::parseProgram() { #ifndef NDEBUG if (parserTraceEnabled()) @@ -1208,16 +1297,6 @@ std::shared_ptr IntegerParser::parsePrimary() { stamp(result, begin, byte_); return result; } - if (match(TokenId::TRUE)) { - auto result = std::make_shared(true); - stamp(result, begin, byte_); - return result; - } - if (match(TokenId::FALSE)) { - auto result = std::make_shared(false); - stamp(result, begin, byte_); - return result; - } if (match(TokenId::NIL)) { auto result = std::make_shared(); stamp(result, begin, byte_); diff --git a/src/IntegerParser.h b/src/IntegerParser.h index b53d3cf..21e9f57 100644 --- a/src/IntegerParser.h +++ b/src/IntegerParser.h @@ -76,6 +76,7 @@ class IntegerParser { std::size_t piece_ = 0; std::size_t byte_ = 0; std::size_t recursionDepth_ = 0; + bool lastClauseUsedBlockEnd_ = false; IntegerParserMetrics metrics_; std::vector lineStarts_; static constexpr std::size_t kMaximumRecursionDepth = 512; @@ -120,6 +121,7 @@ class IntegerParser { std::shared_ptr parseGoal(); std::vector> parseGoalList(TokenId::Id terminator); std::shared_ptr parseStatement(); + std::shared_ptr parseClassStatement(std::size_t begin); Call parseAnnotation(); void prepareOperatorAnnotation(const Call& annotation); void registerOperatorImplementation(const Call& annotation, const ClauseStmt& method); diff --git a/src/IrCodeGenerator.cpp b/src/IrCodeGenerator.cpp index f623e6a..06d4a9b 100644 --- a/src/IrCodeGenerator.cpp +++ b/src/IrCodeGenerator.cpp @@ -1,5 +1,6 @@ #include "IrCodeGenerator.h" +#include "BuiltinRegistry.h" #include "IntegerParser.h" #include "OperatorAnnotation.h" #include "Symbol.h" @@ -7,9 +8,12 @@ #include #include +#include #include #include +#include #include +#include #include #include @@ -110,7 +114,7 @@ void desugarWhereGuardedClauses(Program &program) { } // Defined later in this file, alongside resolveScopedAccess whose traversal -// shape it mirrors; forward-declared here for FactQueryNormalizer::iteration(). +// shape it mirrors; forward-declared here for FactDmlLowerer::iteration(). std::shared_ptr substituteCaptures( const std::shared_ptr &expression, const std::string &rowParameter, SymbolId rowParameterId, const std::string &capturesVariable, @@ -122,9 +126,15 @@ std::shared_ptr substituteCaptures( // operation. Each predicate becomes an ordinary compiler-generated procedure; // RegisterVm therefore retains one iteration/call path for both lambda(...) // and concrete type methods such as School.all() and School.select(...). -class FactQueryNormalizer { +class FactDmlLowerer { public: - explicit FactQueryNormalizer(const Program &program) { + explicit FactDmlLowerer(const Program &program) { + for (const auto &declaration : program.classes) { + if (!declaration) + continue; + occupied_.insert(declaration->nameId); + factTypes_.emplace(declaration->name, declaration->nameId); + } for (const auto &clause : program.clauses) { if (!clause) continue; @@ -347,51 +357,6 @@ class FactQueryNormalizer { } for (auto &argument : term->args) argument.value = expression(argument.value); - if (term->name == "ancestorAnalysis") { - // A source convenience over the three already-real hierarchy - // intrinsics (commonAncestors/lowestCommonAncestor/ - // highestCommonAncestor, each its own dedicated IrOpcode -- see - // IrOpcode::HierarchyCommonAncestors and friends), combined into one - // fact instead of a bespoke analysis opcode. Facts carry more - // reasoning context than a bare map, matching how every other - // multi-value result in this file returns a labeled record. - if (term->args.size() != 2) - throw IntegerParserError( - "ancestorAnalysis requires left and right arguments"); - std::shared_ptr leftArg; - std::shared_ptr rightArg; - for (const auto &argument : term->args) { - if (argument.name == "left") - leftArg = argument.value; - else if (argument.name == "right") - rightArg = argument.value; - } - if (!leftArg || !rightArg) { - throw IntegerParserError( - "ancestorAnalysis requires named left and right arguments"); - } - const auto hierarchyCall = [&](std::string name) { - std::vector callArgs; - callArgs.emplace_back("left", symbolIdForName("left"), leftArg); - callArgs.emplace_back("right", symbolIdForName("right"), rightArg); - auto call = std::make_shared(std::move(name), - std::move(callArgs)); - call->sourceSpan = term->sourceSpan; - return call; - }; - std::vector factArgs; - factArgs.emplace_back("common", symbolIdForName("common"), - hierarchyCall("commonAncestors")); - factArgs.emplace_back("lowest", symbolIdForName("lowest"), - hierarchyCall("lowestCommonAncestor")); - factArgs.emplace_back("highest", symbolIdForName("highest"), - hierarchyCall("highestCommonAncestor")); - auto result = std::make_shared( - "AncestorAnalysis", symbolIdForName("AncestorAnalysis"), - std::move(factArgs), BuiltinId::Unknown, /*capitalized=*/true); - result->sourceSpan = term->sourceSpan; - return result; - } const auto separator = term->name.rfind('.'); if (separator == std::string::npos) return value; @@ -429,12 +394,13 @@ class FactQueryNormalizer { }; if (method == "search") { const auto field = std::dynamic_pointer_cast(named("field")); - const auto mode = std::dynamic_pointer_cast(named("mode")); - if (!field || !mode) + const auto searchType = + std::dynamic_pointer_cast(named("type")); + if (!field || !searchType) throw IntegerParserError(typeName + - ".search requires text field and mode"); + ".search requires text field and type"); static const std::unordered_set allowedArguments{ - "field", "query", "mode", "case", + "field", "query", "type", "case", "direction", "includeSelf", "minimum", "maximum", "tolerance"}; for (const auto &argument : term->args) @@ -443,7 +409,7 @@ class FactQueryNormalizer { ".search has an unknown argument " + argument.name); - const auto textMode = mode->value; + const auto textMode = searchType->value; const bool textSearch = textMode == "exact" || textMode == "prefix" || textMode == "suffix" || textMode == "contains" || @@ -461,7 +427,7 @@ class FactQueryNormalizer { } else if (textMode == "hierarchy") { if (!named("query")) throw IntegerParserError(typeName + - ".search hierarchy mode requires query"); + ".search hierarchy type requires query"); const auto direction = std::dynamic_pointer_cast(named("direction")); if (!direction || @@ -476,9 +442,9 @@ class FactQueryNormalizer { if (closeness == range) throw IntegerParserError( typeName + - ".search degree mode requires either query+tolerance or a range"); + ".search degree type requires either query+tolerance or a range"); } else { - throw IntegerParserError(typeName + ".search mode is invalid"); + throw IntegerParserError(typeName + ".search type is invalid"); } std::vector optionEntries; @@ -529,21 +495,37 @@ class FactQueryNormalizer { throw IntegerParserError(typeName + ".delete must follow a where condition"); } - if (method == "join" || method == "leftJoin" || - method == "rightJoin" || method == "OuterJoin") { + if (method == "join") { const auto other = std::dynamic_pointer_cast(named("type")); const auto left = std::dynamic_pointer_cast(named("left")); const auto right = std::dynamic_pointer_cast(named("right")); + const auto kindArgument = named("kind"); if (!other || !factTypes_.contains(other->name) || !left || !right || - term->args.size() != 3) + term->args.size() != (kindArgument ? 4u : 3u)) throw IntegerParserError(typeName + - "." + method + - " requires type, left, and right"); - const auto kind = std::make_shared( - method == "join" ? 0.0 - : method == "leftJoin" ? 1.0 - : method == "rightJoin" ? 2.0 - : 3.0); + ".join requires type, left, right, and an " + "optional kind"); + double kindValue = 0.0; + if (kindArgument) { + const auto kind = + std::dynamic_pointer_cast(kindArgument); + if (!kind) + throw IntegerParserError(typeName + + ".join kind must be text"); + if (kind->value == "inner") + kindValue = 0.0; + else if (kind->value == "left") + kindValue = 1.0; + else if (kind->value == "right") + kindValue = 2.0; + else if (kind->value == "outer") + kindValue = 3.0; + else + throw IntegerParserError( + typeName + + ".join kind must be inner, left, right, or outer"); + } + const auto kind = std::make_shared(kindValue); auto leftRows = std::make_shared(typeName + ".all", std::vector{}); auto rightRows = std::make_shared(other->name + ".all", @@ -733,8 +715,8 @@ class FactQueryNormalizer { std::size_t nextProcedure_ = 0; }; -void normalizeFactQueries(Program &program) { - FactQueryNormalizer(program).normalize(program); +void lowerFactDml(Program &program) { + FactDmlLowerer(program).normalize(program); } // The integer parser preserves a dotted identifier as one symbol because the @@ -744,13 +726,23 @@ void normalizeFactQueries(Program &program) { // is a visible binding. Unscoped qualified symbols stay untouched. std::shared_ptr resolveScopedAccess(const std::shared_ptr &expression, - const std::unordered_set &visible) { + const std::unordered_set &visible, + const std::unordered_set *implicitFields = nullptr) { if (!expression) return expression; if (const auto variable = std::dynamic_pointer_cast(expression)) { const auto dot = variable->name.find('.'); - if (dot == std::string::npos) + if (dot == std::string::npos) { + if (implicitFields && implicitFields->contains(variable->nameId)) { + auto access = std::make_shared( + std::make_shared("self", symbolIdForName("self")), + variable->name); + access->keyId = variable->nameId; + access->sourceSpan = variable->sourceSpan; + return access; + } return expression; + } const auto baseName = variable->name.substr(0, dot); if (!visible.contains(symbolIdForName(baseName))) return expression; @@ -775,17 +767,17 @@ resolveScopedAccess(const std::shared_ptr &expression, } if (const auto array = std::dynamic_pointer_cast(expression)) { for (auto &item : array->items) - item = resolveScopedAccess(item, visible); + item = resolveScopedAccess(item, visible, implicitFields); } else if (const auto map = std::dynamic_pointer_cast(expression)) { for (auto &item : map->entries) - item.value = resolveScopedAccess(item.value, visible); + item.value = resolveScopedAccess(item.value, visible, implicitFields); } else if (const auto access = std::dynamic_pointer_cast(expression)) { - access->target = resolveScopedAccess(access->target, visible); + access->target = resolveScopedAccess(access->target, visible, implicitFields); } else if (const auto term = std::dynamic_pointer_cast(expression)) { for (auto &argument : term->args) - argument.value = resolveScopedAccess(argument.value, visible); + argument.value = resolveScopedAccess(argument.value, visible, implicitFields); } else if (const auto operation = std::dynamic_pointer_cast(expression)) { std::shared_ptr rewritten; @@ -795,7 +787,8 @@ resolveScopedAccess(const std::shared_ptr &expression, for (std::size_t index = 0; index < operation->captureCount(); ++index) { captures.emplace_back( std::string(operation->captureName(index)), - resolveScopedAccess(operation->capture(index), visible)); + resolveScopedAccess(operation->capture(index), visible, + implicitFields)); } rewritten = std::make_shared( operation->operatorId, operation->patternId, std::move(captures), @@ -803,12 +796,12 @@ resolveScopedAccess(const std::shared_ptr &expression, } else if (operation->captureCount() == 1) { rewritten = std::make_shared( operation->coreOperator, - resolveScopedAccess(operation->capture(0), visible)); + resolveScopedAccess(operation->capture(0), visible, implicitFields)); } else { rewritten = std::make_shared( operation->coreOperator, - resolveScopedAccess(operation->capture(0), visible), - resolveScopedAccess(operation->capture(1), visible)); + resolveScopedAccess(operation->capture(0), visible, implicitFields), + resolveScopedAccess(operation->capture(1), visible, implicitFields)); } rewritten->module = operation->module; rewritten->sourceSpan = operation->sourceSpan; @@ -821,7 +814,7 @@ resolveScopedAccess(const std::shared_ptr &expression, // VarExpr other than the row parameter itself) into a read from the // synthesized callback's captures map, and records each one captured // (deduplicated, first-seen order) into `captured`. Used by -// FactQueryNormalizer::iteration() -- see the comment there for why this +// FactDmlLowerer::iteration() -- see the comment there for why this // exists. Mirrors resolveScopedAccess's traversal shape immediately above. std::shared_ptr substituteCaptures( const std::shared_ptr &expression, const std::string &rowParameter, @@ -905,26 +898,59 @@ std::shared_ptr substituteCaptures( } void resolveScopedAccessesInGoals(std::vector> &goals, - std::unordered_set visible) { + std::unordered_set visible, + const std::unordered_set *implicitFields = nullptr) { for (auto &goal : goals) { - if (const auto assignment = std::dynamic_pointer_cast(goal)) { - assignment->expr = resolveScopedAccess(assignment->expr, visible); + const auto expression = [&](std::shared_ptr value) { + return resolveScopedAccess(value, visible, implicitFields); + }; + const auto call = [&](Call &value) { + for (auto &argument : value.args) + argument.value = expression(argument.value); + }; + if (const auto called = std::dynamic_pointer_cast(goal)) { + call(called->call); + } else if (const auto negated = std::dynamic_pointer_cast(goal)) { + call(negated->call); + } else if (const auto assignment = + std::dynamic_pointer_cast(goal)) { + assignment->expr = + expression(assignment->expr); visible.insert(assignment->nameId); + } else if (const auto assignment = + std::dynamic_pointer_cast(goal)) { + assignment->expr = expression(assignment->expr); + for (const auto &target : assignment->targets) + visible.insert(target.nameId); } else if (const auto returned = std::dynamic_pointer_cast(goal)) { for (auto &field : returned->fields) - field.value = resolveScopedAccess(field.value, visible); + field.value = resolveScopedAccess(field.value, visible, implicitFields); } else if (const auto binary = std::dynamic_pointer_cast(goal)) { - binary->left = resolveScopedAccess(binary->left, visible); - binary->right = resolveScopedAccess(binary->right, visible); + binary->left = expression(binary->left); + binary->right = expression(binary->right); + } else if (const auto where = + std::dynamic_pointer_cast(goal)) { + std::vector> condition{where->condition}; + resolveScopedAccessesInGoals(condition, visible, implicitFields); + where->condition = condition.front(); } else if (const auto conditional = std::dynamic_pointer_cast(goal)) { std::vector> condition{conditional->condition}; - resolveScopedAccessesInGoals(condition, visible); + resolveScopedAccessesInGoals(condition, visible, implicitFields); conditional->condition = condition.front(); - resolveScopedAccessesInGoals(conditional->thenBranch, visible); - resolveScopedAccessesInGoals(conditional->elseBranch, visible); + resolveScopedAccessesInGoals(conditional->thenBranch, visible, + implicitFields); + resolveScopedAccessesInGoals(conditional->elseBranch, visible, + implicitFields); + } else if (const auto group = + std::dynamic_pointer_cast(goal)) { + resolveScopedAccessesInGoals(group->goals, visible, implicitFields); + } else if (const auto alternatives = + std::dynamic_pointer_cast(goal)) { + for (auto &branch : alternatives->branches) + resolveScopedAccessesInGoals(branch, visible, implicitFields); } } } @@ -1112,9 +1138,7 @@ bool isDirectDeterministicExpression( term->nameId == symbolIdForName("similarity") || term->nameId == symbolIdForName("membership") || term->nameId == symbolIdForName("isA") || - term->nameId == symbolIdForName("commonAncestors") || - term->nameId == symbolIdForName("lowestCommonAncestor") || - term->nameId == symbolIdForName("highestCommonAncestor"); + term->nameId == symbolIdForName("commonAncestors"); if (fuzzyIntrinsic) { const auto expected = term->nameId == symbolIdForName("similarity") ? 2u : 2u; @@ -1140,7 +1164,7 @@ bool isDirectDeterministicExpression( } if (term->nameId == symbolIdForName("for_each_fact")) { // The third argument (a captures map) is optional: only - // FactQueryNormalizer::iteration()'s generated calls provide one, for + // FactDmlLowerer::iteration()'s generated calls provide one, for // predicates closing over an outer-scope value; a raw, hand-written // for_each_fact(type, callback) call stays exactly as it was. if (term->args.size() != 2 && term->args.size() != 3) @@ -1275,9 +1299,7 @@ firstUnsupportedExpression(const std::shared_ptr &expression, if ((term->nameId == symbolIdForName("similarity") || term->nameId == symbolIdForName("membership") || term->nameId == symbolIdForName("isA") || - term->nameId == symbolIdForName("commonAncestors") || - term->nameId == symbolIdForName("lowestCommonAncestor") || - term->nameId == symbolIdForName("highestCommonAncestor")) && + term->nameId == symbolIdForName("commonAncestors")) && term->args.size() == 2) { for (const auto &argument : term->args) { if (!isDirectDeterministicExpression(argument.value, definedSymbols, @@ -1563,7 +1585,10 @@ void appendFragment(FelidaeIr &target, FelidaeIr fragment, case IrOpcode::MakeFact: reg(fragment.words[pc + 1]); symbol(fragment.words[pc + 2]); - width = 3; + // Source ownership is a one-based text index (zero means in-memory). + if (fragment.words[pc + 3] != 0) + fragment.words[pc + 3] += textBase; + width = 4; break; case IrOpcode::Return: reg(fragment.words[pc + 1]); @@ -1680,6 +1705,23 @@ void appendFragment(FelidaeIr &target, FelidaeIr fragment, target.registerCount += fragment.registerCount; } +void attachFactPersistenceSource(FelidaeIr &program, std::size_t wordBegin, + RegisterId result, IrWord sourceIndex) { + bool attached = false; + for (std::size_t pc = wordBegin; pc < program.words.size();) { + const auto opcode = static_cast(program.words[pc]); + if (opcode == IrOpcode::MakeFact && program.words[pc + 1] == result) { + if (attached) + throw IntegerParserError("fact IR has ambiguous source ownership"); + program.words[pc + 3] = sourceIndex; + attached = true; + } + pc += irInstructionWidth(program, pc); + } + if (!attached) + throw IntegerParserError("fact IR has no source-owning value"); +} + CoreOperator directConditionOperator(TokenId::Id token) { switch (token) { case TokenId::EQUAL: @@ -2040,7 +2082,7 @@ FelidaeIr IrCodeGenerator::lowerExpression( } else if (term->nameId == symbolIdForName("for_each_fact")) { // The third argument (a captures map) is optional -- see the // isDirectDeterministicExpression case above and - // FactQueryNormalizer::iteration() in this file. A raw two-argument + // FactDmlLowerer::iteration() in this file. A raw two-argument // call gets an empty map so IrOpcode::ForEachFact's fifth operand // (see RegisterVm.cpp) is always a valid register either way. if (term->args.size() != 2 && term->args.size() != 3) { @@ -2079,9 +2121,7 @@ FelidaeIr IrCodeGenerator::lowerExpression( ir.words.end(), {static_cast(IrOpcode::Similarity), result, left, right}); } else if (term->nameId == symbolIdForName("isA") || - term->nameId == symbolIdForName("commonAncestors") || - term->nameId == symbolIdForName("lowestCommonAncestor") || - term->nameId == symbolIdForName("highestCommonAncestor")) { + term->nameId == symbolIdForName("commonAncestors")) { if (term->args.size() != 2) { throw IntegerParserError(term->name + " requires exactly two hierarchy arguments"); @@ -2090,11 +2130,7 @@ FelidaeIr IrCodeGenerator::lowerExpression( const auto right = self(self, term->args[1].value); const auto opcode = term->nameId == symbolIdForName("isA") ? IrOpcode::HierarchyIsA - : term->nameId == symbolIdForName("commonAncestors") - ? IrOpcode::HierarchyCommonAncestors - : term->nameId == symbolIdForName("lowestCommonAncestor") - ? IrOpcode::HierarchyLeastCommonAncestors - : IrOpcode::HierarchyMostGeneralAncestors; + : IrOpcode::HierarchyCommonAncestors; ir.words.insert(ir.words.end(), {static_cast(opcode), result, left, right}); } else if (term->nameId == symbolIdForName("temporalRank")) { @@ -2179,7 +2215,7 @@ FelidaeIr IrCodeGenerator::lowerExpression( ir.symbols.push_back(term->nameId); ir.words.insert(ir.words.end(), {static_cast(IrOpcode::MakeFact), result, - static_cast(ir.symbols.size() - 1)}); + static_cast(ir.symbols.size() - 1), 0}); std::vector> fields; fields.reserve(arguments.size()); for (std::size_t index = 0; index < arguments.size(); ++index) { @@ -2238,7 +2274,7 @@ FelidaeIr IrCodeGenerator::lowerExpression( ir.symbols.push_back(symbolIdForName(map->factType)); ir.words.insert(ir.words.end(), {static_cast(IrOpcode::MakeFact), result, - static_cast(ir.symbols.size() - 1)}); + static_cast(ir.symbols.size() - 1), 0}); emitFactFields(result, entries); } } else if (const auto access = @@ -2509,7 +2545,7 @@ FelidaeIr IrCodeGenerator::lowerEntryMethod( IrModule IrCodeGenerator::compile(Program program) const { desugarWhereGuardedClauses(program); - normalizeFactQueries(program); + lowerFactDml(program); IrModule module; // The strict compiler accepts only constructs that lower to verified IR. // Unsupported constructs are rejected with a source span; there is no @@ -2517,6 +2553,18 @@ IrModule IrCodeGenerator::compile(Program program) const { std::unordered_set directSymbols; std::unordered_set procedureSymbols; std::unordered_set factTypes; + std::unordered_map classSchemas; + for (const auto &declaration : program.classes) { + if (!declaration || declaration->name.empty() || + !factTypes.insert(declaration->nameId).second) { + throw IntegerParserError( + "duplicate or invalid class declaration at " + + std::to_string(declaration ? declaration->sourceSpan.startLine : 1) + + ":" + + std::to_string(declaration ? declaration->sourceSpan.startColumn : 1)); + } + classSchemas.emplace(declaration->nameId, declaration.get()); + } for (const auto &clause : program.clauses) { if (!clause) continue; @@ -2536,6 +2584,66 @@ IrModule IrCodeGenerator::compile(Program program) const { if (clause->isFact()) factTypes.insert(clause->head.nameId); } + + // A declared schema constrains source fact rows while runtime facts remain + // ordinary first-class maps. Inherited fields are resolved after the class + // hierarchy has been validated below. + std::function &, + std::unordered_set &)> + collectFields; + collectFields = [&](SymbolId type, std::unordered_set &result, + std::unordered_set &visiting) { + const auto schema = classSchemas.find(type); + if (schema == classSchemas.end()) + return; + if (!visiting.insert(type).second) + throw IntegerParserError("cyclic class hierarchy for '" + + schema->second->name + "'"); + for (const auto &parent : schema->second->parentNames) { + const auto parentId = symbolIdForName(parent); + if (!factTypes.contains(parentId)) + throw IntegerParserError("unknown class parent '" + parent + "'"); + collectFields(parentId, result, visiting); + } + for (const auto &field : schema->second->fields) + result.insert(field.nameId); + visiting.erase(type); + }; + for (const auto &clause : program.clauses) { + if (!clause || !clause->isFact() || + !classSchemas.contains(clause->head.nameId)) + continue; + std::unordered_set fields; + std::unordered_set visiting; + collectFields(clause->head.nameId, fields, visiting); + for (const auto &argument : clause->head.args) { + if (argument.name.empty() || !fields.contains(argument.nameId)) { + throw IntegerParserError( + "fact field '" + argument.name + "' is not declared by class '" + + clause->head.name + "' at " + + std::to_string(clause->sourceSpan.startLine) + ":" + + std::to_string(clause->sourceSpan.startColumn)); + } + } + } + std::unordered_map> classMethodFields; + for (const auto &declaration : program.classes) { + std::unordered_set fields; + std::unordered_set visiting; + collectFields(declaration->nameId, fields, visiting); + for (const auto &method : declaration->methods) + classMethodFields.emplace(method->head.nameId, fields); + std::set> uniqueIndexes; + for (const auto &index : declaration->indexes) { + if (std::any_of(index.fieldIds.begin(), index.fieldIds.end(), + [&](SymbolId field) { return !fields.contains(field); })) + throw IntegerParserError("class index references an undeclared field in '" + + declaration->name + "'"); + if (!uniqueIndexes.insert(index.fieldIds).second) + throw IntegerParserError("duplicate class index in '" + + declaration->name + "'"); + } + } for (const auto &clause : program.clauses) { if (!clause) continue; @@ -2590,9 +2698,32 @@ IrModule IrCodeGenerator::compile(Program program) const { auto visible = globalSymbols; for (const auto parameter : procedureParameters(*clause)) visible.insert(parameter); - resolveScopedAccessesInGoals(clause->body, std::move(visible)); + const auto classFields = classMethodFields.find(clause->head.nameId); + resolveScopedAccessesInGoals( + clause->body, std::move(visible), + classFields == classMethodFields.end() ? nullptr : &classFields->second); } std::unordered_map factTypeIndexes; + for (const auto &declaration : program.classes) { + std::vector parents; + parents.reserve(declaration->parentNames.size()); + for (const auto &parent : declaration->parentNames) { + const auto parentSymbol = symbolIdForName(parent); + if (!factTypes.contains(parentSymbol)) + throw IntegerParserError("unknown class parent '" + parent + "'"); + parents.push_back(parentSymbol); + } + std::vector> indexes; + indexes.reserve(declaration->indexes.size()); + for (const auto &index : declaration->indexes) + indexes.emplace_back(index.fieldIds.begin(), index.fieldIds.end()); + factTypeIndexes.emplace(declaration->nameId, module.factTypes.size()); + module.factTypes.push_back( + {declaration->nameId, std::move(parents), std::move(indexes), + {declaration->sourceSpan.startLine, + declaration->sourceSpan.startColumn, + declaration->sourceSpan.endLine, declaration->sourceSpan.endColumn}}); + } for (const auto &clause : program.clauses) { if (!clause || !clause->isFact()) continue; @@ -2613,9 +2744,11 @@ IrModule IrCodeGenerator::compile(Program program) const { module.factTypes.push_back( {clause->head.nameId, std::move(parents), + {}, {clause->sourceSpan.startLine, clause->sourceSpan.startColumn, clause->sourceSpan.endLine, clause->sourceSpan.endColumn}}); - } else if (module.factTypes[existing->second].parents != parents) { + } else if (!parents.empty() && + module.factTypes[existing->second].parents != parents) { throw IntegerParserError( "not yet lowered to IR: inconsistent fact hierarchy at " + std::to_string(clause->sourceSpan.startLine) + ":" + @@ -2628,7 +2761,7 @@ IrModule IrCodeGenerator::compile(Program program) const { // parser/execution path. Other imports remain explicitly unsupported until // they have a verified IR module-linking contract. // - // This list previously omitted array/math/str/file/db/system even though + // This list previously omitted array/math/str/file/system even though // every one of their declared calls (array.get, math:sqrt, str:upper, // file.readFile, system.print, ...) already compiles and runs // fine with no import statement at all -- an explicit `import "array"` @@ -2640,18 +2773,11 @@ IrModule IrCodeGenerator::compile(Program program) const { // silently return nil, which is worse than the current explicit rejection. const bool builtinImports = std::all_of( program.imports.begin(), program.imports.end(), [](const auto &import) { - return import && std::all_of(import->paths.begin(), import->paths.end(), - [](const std::string &path) { - return path == "json" || path == "csv" || - path == "group" || - path == "set" || path == "ml" || - path == "array" || - path == "math" || - path == "str" || - path == "file" || - path == "db" || - path == "system"; - }); + return import && + std::all_of(import->paths.begin(), import->paths.end(), + [](const std::string &path) { + return isBuiltinModuleName(path); + }); }); bool directGlobals = builtinImports && !program.clauses.empty(); for (const auto &binding : program.globals) { @@ -2688,6 +2814,7 @@ IrModule IrCodeGenerator::compile(Program program) const { IrCodeGenerator::lowerGlobalBinding(*binding, factTypes), true); } + std::map persistenceSources; for (const auto &clause : program.clauses) { if (!clause || !clause->isFact() || clause->emptyDeclaration) continue; @@ -2701,9 +2828,36 @@ IrModule IrCodeGenerator::compile(Program program) const { std::to_string(clause->sourceSpan.startLine) + ":" + std::to_string(clause->sourceSpan.startColumn)); } - appendFragment( - module.ir, - IrCodeGenerator::lowerExpression(std::move(fact), factTypes), true); + auto factIr = IrCodeGenerator::lowerExpression(std::move(fact), factTypes); + if (factIr.words.size() < 4 || + factIr.words[factIr.words.size() - 4] != + static_cast(IrOpcode::Return)) { + throw IntegerParserError( + "fact IR fragment does not have a terminal return"); + } + const auto result = static_cast( + module.ir.registerCount + factIr.words[factIr.words.size() - 3]); + const auto wordBegin = module.ir.words.size(); + appendFragment(module.ir, std::move(factIr), true); + if (clause->persistenceSource && + !clause->persistenceSource->empty()) { + auto [source, inserted] = persistenceSources.try_emplace( + *clause->persistenceSource, 0); + if (inserted) { + const auto existing = + std::find(module.ir.texts.begin(), module.ir.texts.end(), + *clause->persistenceSource); + if (existing == module.ir.texts.end()) { + module.ir.texts.push_back(*clause->persistenceSource); + source->second = static_cast(module.ir.texts.size()); + } else { + source->second = static_cast( + std::distance(module.ir.texts.begin(), existing) + 1); + } + } + attachFactPersistenceSource(module.ir, wordBegin, result, + source->second); + } } for (const auto &clause : program.clauses) { if (clause->isFact()) diff --git a/src/form/BinaryIr.cpp b/src/form/BinaryIr.cpp index d68cce7..9896663 100644 --- a/src/form/BinaryIr.cpp +++ b/src/form/BinaryIr.cpp @@ -207,6 +207,10 @@ void writeBinaryIr(const std::filesystem::path &path, for (const auto &type : module.factTypes) { writeLe(out, static_cast(type.symbol)); writeSymbols(out, type.parents); + writeLe(out, + count(type.indexes.size(), "fact index count")); + for (const auto &index : type.indexes) + writeSymbols(out, index); writeSpan(out, type.sourceSpan); } for (const auto &pieces : module.symbolTable) @@ -288,6 +292,12 @@ loadBinaryIr(const std::filesystem::path &path, IrFactType type; type.symbol = readLe(in); type.parents = readSymbols(in); + const auto indexCount = readLe(in); + if (indexCount > kMaximumItems) + throw IrError("FELBIR fact index count is invalid"); + type.indexes.reserve(indexCount); + for (std::uint32_t item = 0; item < indexCount; ++item) + type.indexes.push_back(readSymbols(in)); type.sourceSpan = readSpan(in); module.factTypes.push_back(std::move(type)); } diff --git a/src/form/BuiltinOperation.h b/src/form/BuiltinOperation.h index 1e069e2..4b848fa 100644 --- a/src/form/BuiltinOperation.h +++ b/src/form/BuiltinOperation.h @@ -69,7 +69,6 @@ enum class BuiltinId : std::uint16_t { HighestCommonAncestor, AncestorAnalysis, PropagateFact, - DependencySatisfied, JsonObject, JsonParse, JsonGet, @@ -109,24 +108,6 @@ enum class BuiltinId : std::uint16_t { MathMul, MathDiv, MathMod, - ProbabilityMean, - ProbabilityVariance, - ProbabilityStddev, - ProbabilityNormalize, - ProbabilityEntropy, - ProbabilityCovariance, - ProbabilityCorrelation, - ProbabilityBernoulli, - ProbabilityBinomialPmf, - ProbabilityBinomialCdf, - ProbabilityPoissonPmf, - ProbabilityPoissonCdf, - ProbabilityNormalPdf, - ProbabilityNormalCdf, - ProbabilityUniformPdf, - ProbabilityUniformCdf, - ProbabilitySample, - ProbabilityWeightedChoice, ReasoningContrary, ReasoningProve, ReasoningGrade, @@ -198,6 +179,13 @@ builtinOperationArity(BuiltinId operation) noexcept { case BuiltinId::Min: case BuiltinId::Max: case BuiltinId::Sort: + case BuiltinId::Lower: + case BuiltinId::Upper: + case BuiltinId::Length: + case BuiltinId::StrLen: + case BuiltinId::StrLower: + case BuiltinId::StrUpper: + case BuiltinId::StrTrim: case BuiltinId::ArrayLen: case BuiltinId::FileReadFile: case BuiltinId::JsonParse: @@ -231,6 +219,15 @@ builtinOperationArity(BuiltinId operation) noexcept { case BuiltinId::FactDelete: return 1; case BuiltinId::ArrayGet: + case BuiltinId::ArrayPush: + case BuiltinId::Search: + case BuiltinId::Contains: + case BuiltinId::StrContains: + case BuiltinId::StrConcat: + case BuiltinId::StrJoin: + case BuiltinId::StrSplit: + case BuiltinId::StrStartsWith: + case BuiltinId::StrEndsWith: case BuiltinId::JsonGet: case BuiltinId::JsonHas: case BuiltinId::JsonRemove: @@ -248,6 +245,7 @@ builtinOperationArity(BuiltinId operation) noexcept { case BuiltinId::SetContains: case BuiltinId::ArrayLimit: case BuiltinId::FactUpdate: + case BuiltinId::AncestorAnalysis: case BuiltinId::FactProject: case BuiltinId::MathRandom: case BuiltinId::MathPow: @@ -261,6 +259,7 @@ builtinOperationArity(BuiltinId operation) noexcept { case BuiltinId::FactJoin: return 5; case BuiltinId::JsonSet: + case BuiltinId::StrReplace: case BuiltinId::GroupValidate: case BuiltinId::GroupIdentity: case BuiltinId::GroupInverse: @@ -289,6 +288,14 @@ builtinOperationArgumentIndex(BuiltinId operation, case BuiltinId::Sort: case BuiltinId::ArrayLen: return name == "data" ? std::optional{0} : std::nullopt; + case BuiltinId::Lower: + case BuiltinId::Upper: + case BuiltinId::Length: + case BuiltinId::StrLen: + case BuiltinId::StrLower: + case BuiltinId::StrUpper: + case BuiltinId::StrTrim: + return name == "data" ? std::optional{0} : std::nullopt; case BuiltinId::FileReadFile: return name == "file" ? std::optional{0} : std::nullopt; case BuiltinId::ArrayGet: @@ -296,6 +303,44 @@ builtinOperationArgumentIndex(BuiltinId operation, return 0; return name == "position" ? std::optional{1} : std::nullopt; + case BuiltinId::ArrayPush: + if (name == "data") + return 0; + return name == "value" ? std::optional{1} : std::nullopt; + case BuiltinId::Search: + case BuiltinId::Contains: + if (name == "data" || name == "value") + return 0; + return name == "query" ? std::optional{1} : std::nullopt; + case BuiltinId::StrContains: + if (name == "data") + return 0; + return name == "needle" ? std::optional{1} : std::nullopt; + case BuiltinId::StrConcat: + if (name == "left") + return 0; + return name == "right" ? std::optional{1} : std::nullopt; + case BuiltinId::StrJoin: + case BuiltinId::StrSplit: + if (name == "data") + return 0; + return name == "delimiter" ? std::optional{1} + : std::nullopt; + case BuiltinId::StrStartsWith: + if (name == "data") + return 0; + return name == "prefix" ? std::optional{1} : std::nullopt; + case BuiltinId::StrEndsWith: + if (name == "data") + return 0; + return name == "suffix" ? std::optional{1} : std::nullopt; + case BuiltinId::StrReplace: + if (name == "data") + return 0; + if (name == "search") + return 1; + return name == "replacement" ? std::optional{2} + : std::nullopt; case BuiltinId::JsonParse: case BuiltinId::CsvParse: return name == "data" ? std::optional{0} : std::nullopt; @@ -392,6 +437,10 @@ builtinOperationArgumentIndex(BuiltinId operation, if (name == "y") return 0; return name == "x" ? std::optional{1} : std::nullopt; + case BuiltinId::AncestorAnalysis: + if (name == "left") + return 0; + return name == "right" ? std::optional{1} : std::nullopt; case BuiltinId::PropagateFact: if (name == "parent") return 0; diff --git a/src/form/IrModule.cpp b/src/form/IrModule.cpp index 98be893..e19cee6 100644 --- a/src/form/IrModule.cpp +++ b/src/form/IrModule.cpp @@ -1,5 +1,6 @@ #include "IrModule.h" +#include #include #include #include @@ -51,6 +52,9 @@ static void validateIrModule(const IrModule &module) { requireSymbol(type.symbol); for (const auto parent : type.parents) requireSymbol(parent); + for (const auto &index : type.indexes) + for (const auto field : index) + requireSymbol(field); } IrVerifier::verify(module.ir); if (module.entryProcedure == 0 || @@ -97,6 +101,16 @@ static void validateIrModule(const IrModule &module) { if (parent == 0 || parent == type.symbol || !types.contains(parent) || !parents.insert(parent).second) throw IrError("compiler IR hierarchy parent is invalid"); + std::set> indexes; + for (const auto &index : type.indexes) { + std::unordered_set fields; + if (index.empty() || + !std::all_of(index.begin(), index.end(), [&](IrSymbolRef field) { + return field != 0 && fields.insert(field).second; + }) || + !indexes.insert(index).second) + throw IrError("compiler IR fact index is invalid or duplicated"); + } } std::unordered_set visiting, visited; const auto visit = [&](auto &&self, IrSymbolRef type) -> void { diff --git a/src/form/IrModule.h b/src/form/IrModule.h index 0bebaa6..43296cd 100644 --- a/src/form/IrModule.h +++ b/src/form/IrModule.h @@ -11,6 +11,7 @@ namespace Felidae { struct IrFactType { IrSymbolRef symbol = 0; std::vector parents; + std::vector> indexes; IrSourceMapEntry::Span sourceSpan; }; diff --git a/src/form/NumericOperation.h b/src/form/NumericOperation.h index 933a19d..0dd7bfd 100644 --- a/src/form/NumericOperation.h +++ b/src/form/NumericOperation.h @@ -7,8 +7,9 @@ namespace Felidae { -// Stable operand selector for the executable IR Numeric instruction. Boolean -// classifiers still return the VM's numeric truth values 0.0 and 1.0. +// Stable operand selector for the executable IR Numeric instruction. Ordinary +// operations preserve unrestricted floating-point results; only explicit +// predicates return the VM's numeric truth values 0.0 and 1.0. enum class NumericOperation : std::uint8_t { Min = 0, Max, diff --git a/src/form/RegisterVm.cpp b/src/form/RegisterVm.cpp index dec5f60..2cfb61e 100644 --- a/src/form/RegisterVm.cpp +++ b/src/form/RegisterVm.cpp @@ -68,7 +68,6 @@ std::size_t irInstructionWidth(const FelidaeIr &ir, std::size_t pc) { case IrOpcode::StoreSymbol: case IrOpcode::Move: case IrOpcode::JumpIfFalse: - case IrOpcode::MakeFact: case IrOpcode::Return: return bounded(3); case IrOpcode::Add: @@ -84,12 +83,13 @@ std::size_t irInstructionWidth(const FelidaeIr &ir, std::size_t pc) { case IrOpcode::HierarchyLeastCommonAncestors: case IrOpcode::HierarchyMostGeneralAncestors: case IrOpcode::TemporalRank: + case IrOpcode::MakeFact: return bounded(4); // One extra operand beyond type/callback: a register holding a map of // outer-scope values the callback's predicate closes over (0 = none). The // callback procedure itself still takes only the row parameter plus this // one capture map, not one parameter per captured name -- see - // FactQueryNormalizer::iteration() in IrCodeGenerator.cpp. + // FactDmlLowerer::iteration() in IrCodeGenerator.cpp. case IrOpcode::ForEachFact: return bounded(5); case IrOpcode::Compare: @@ -240,7 +240,7 @@ bool vmValuesEqualAtDepth(const VmValue &left, const VmValue &right, throw IrError("VM equality received an unsupported value variant"); } -bool vmValuesEqual(const VmValue &left, const VmValue &right) { +bool vmValuesEqualInternal(const VmValue &left, const VmValue &right) { return vmValuesEqualAtDepth(left, right, 0); } @@ -504,6 +504,8 @@ bool validSemanticInputs(std::uint16_t operation, case SemanticOperationId::EvaluateDegree: return std::holds_alternative(inputs.front()) || std::holds_alternative(inputs.front()); + case SemanticOperationId::Suggest: + return true; } return false; } @@ -522,6 +524,10 @@ bool validSemanticOutput(std::uint16_t operation, std::holds_alternative(output); case SemanticOperationId::EvaluateDegree: return std::holds_alternative(output); + case SemanticOperationId::Suggest: { + const auto score = std::get_if(&output); + return score && std::isfinite(*score); + } } return false; } @@ -675,6 +681,10 @@ void verifyControlFlowInitialization( } } // namespace +bool vmValuesEqual(const VmValue &left, const VmValue &right) { + return vmValuesEqualInternal(left, right); +} + std::string vmValueToDisplayString(const VmValue &value, const VmDisplayContext &context) { const auto renderNumber = [](double number) { @@ -807,12 +817,13 @@ bool VmFactStore::isAssignableToLocked(IrSymbolRef candidate, } void VmFactStore::registerType(IrSymbolRef type, - std::vector parents) { + std::vector parents, + std::vector> indexes) { if (type == 0) throw IrError("fact hierarchy type is invalid"); std::lock_guard lock(mutex_); if (const auto existing = parents_.find(type); existing != parents_.end()) { - if (existing->second != parents) + if (existing->second != parents || declaredIndexes_.at(type) != indexes) throw IrError("fact hierarchy type has conflicting parents"); return; } @@ -826,6 +837,7 @@ void VmFactStore::registerType(IrSymbolRef type, throw IrError("fact hierarchy contains a cycle"); } parents_.emplace(type, std::move(parents)); + declaredIndexes_.emplace(type, std::move(indexes)); ++hierarchyRevision_; ++knowledgeRevision_; } @@ -1093,6 +1105,43 @@ VmFactStore::hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) const { return {}; } +std::vector> +VmFactStore::hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor) const { + constexpr std::size_t kMaximumProofPaths = 4096; + std::lock_guard lock(mutex_); + if (child == 0 || ancestor == 0 || + !isAssignableToLocked(child, ancestor)) + return {}; + std::vector> result; + std::vector path{child}; + const auto visit = [&](const auto &self, IrSymbolRef current) -> void { + if (result.size() == kMaximumProofPaths) + throw IrError("fact hierarchy proof-path limit exceeded"); + if (current == ancestor) { + result.push_back(path); + return; + } + const auto found = parents_.find(current); + if (found == parents_.end()) + return; + auto parents = found->second; + std::sort(parents.begin(), parents.end()); + for (const auto parent : parents) { + path.push_back(parent); + self(self, parent); + path.pop_back(); + } + }; + visit(visit, child); + std::sort(result.begin(), result.end(), [](const auto &left, + const auto &right) { + if (left.size() != right.size()) + return left.size() < right.size(); + return left < right; + }); + return result; +} + std::vector VmFactStore::commonAncestors(IrSymbolRef left, IrSymbolRef right) const { std::lock_guard lock(mutex_); @@ -1112,6 +1161,24 @@ std::vector VmFactStore::commonAncestors(IrSymbolRef left, return result; } +std::vector +VmFactStore::commonAncestorEvidence(IrSymbolRef left, + IrSymbolRef right) const { + std::vector result; + for (const auto ancestor : commonAncestors(left, right)) { + auto leftProofs = hierarchyProofs(left, ancestor); + auto rightProofs = hierarchyProofs(right, ancestor); + if (leftProofs.empty() || rightProofs.empty()) + continue; + result.push_back( + {ancestor, std::move(leftProofs), std::move(rightProofs), 0, 0}); + auto &evidence = result.back(); + evidence.leftDistance = evidence.leftProofs.front().size() - 1; + evidence.rightDistance = evidence.rightProofs.front().size() - 1; + } + return result; +} + std::vector VmFactStore::leastCommonAncestors(IrSymbolRef left, IrSymbolRef right) const { const auto common = commonAncestors(left, right); @@ -1205,6 +1272,13 @@ VmFactStore::snapshotAssignableTo(IrSymbolRef type) const { return result; } +std::vector VmFactStore::parentsOf(IrSymbolRef type) const { + std::lock_guard lock(mutex_); + const auto found = parents_.find(type); + return found == parents_.end() ? std::vector{} + : found->second; +} + std::vector VmFactStore::snapshotByField(IrSymbolRef field) const { std::lock_guard lock(mutex_); const auto found = byField_.find(field); @@ -1323,6 +1397,16 @@ VmFactPtr FelidaeKnowledgeRuntime::retainFact(const VmFactPtr &fact) { return factStore_->retain(fact); } +VmFactPtr FelidaeKnowledgeRuntime::retainPersistentFact( + const VmFactPtr &fact, std::span source) { + const auto path = decodeText(source); + if (path.empty()) + throw IrError("persistent fact source path must not be empty"); + auto retained = factStore_->retain(fact); + factStore_->recordSource(retained->id, path); + return retained; +} + VmFactPtr FelidaeKnowledgeRuntime::mutateFact(const VmFactPtr &fact, IrSymbolRef field, const VmValue &value) { @@ -1377,9 +1461,11 @@ VmFactPtr FelidaeKnowledgeRuntime::insertFact( fact->type = internRuntimeSymbol(PieceSequence(type.begin(), type.end())); fact->fields = values->entries; std::optional owner; - if (source) + if (source) { owner = decodeText(*source); - else { + if (owner->empty()) + throw IrError("fact insertion source path must not be empty"); + } else { const auto known = factStore_->sourcesForType(fact->type); if (known.size() == 1) owner = known.front(); @@ -1392,7 +1478,7 @@ VmFactPtr FelidaeKnowledgeRuntime::insertFact( if (owner && !owner->empty()) { factStore_->recordSource(retained->id, *owner); try { - (void)syncDatabase(encodeText(*owner)); + (void)persistDatabaseSource(*owner); } catch (...) { (void)factStore_->erase(std::array{retained}); factStore_->rollbackJournal(journal); @@ -1431,7 +1517,7 @@ VmValue FelidaeKnowledgeRuntime::updateFacts( const auto journal = factStore_->journalMark(); apply(owned); try { - (void)syncDatabase(encodeText(source)); + (void)persistDatabaseSource(source); } catch (const std::exception &error) { for (const auto &previous : owned) { const auto current = updatedById.at(previous->id); @@ -1509,11 +1595,17 @@ double FelidaeKnowledgeRuntime::aggregateFacts( return 0.0; throw IrError("fact aggregate requires at least one matching fact"); } - if (operation == 0) - return std::accumulate(values.begin(), values.end(), 0.0); - if (operation == 1) - return std::accumulate(values.begin(), values.end(), 0.0) / - static_cast(values.size()); + if (operation == 0 || operation == 1) { + const auto total = std::accumulate( + values.begin(), values.end(), 0.0L, + [](long double sum, double value) { return sum + value; }); + const auto result = static_cast( + operation == 0 ? total + : total / static_cast(values.size())); + if (!std::isfinite(result)) + throw IrError("fact aggregate produced a non-finite result"); + return result; + } if (operation == 2) return *std::min_element(values.begin(), values.end()); return *std::max_element(values.begin(), values.end()); @@ -1608,7 +1700,7 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( return previous[value.size()] != 0; }; - const auto mode = *textOption("mode", true); + const auto searchType = *textOption("type", true); auto result = std::make_shared(); result->values.reserve(facts.size()); const auto appendMatching = [&](const auto &matches) { @@ -1623,8 +1715,9 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( } }; - if (mode == "exact" || mode == "prefix" || mode == "suffix" || - mode == "contains" || mode == "like" || mode == "regex") { + if (searchType == "exact" || searchType == "prefix" || + searchType == "suffix" || searchType == "contains" || + searchType == "like" || searchType == "regex") { auto query = *textOption("query", true); const auto caseMode = textOption("case", false).value_or("sensitive"); if (caseMode != "sensitive" && caseMode != "insensitive") @@ -1632,11 +1725,11 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( if (query.size() > 1024) throw IrError("fact search pattern exceeds 1024 bytes"); const bool insensitive = caseMode == "insensitive"; - const bool foldText = insensitive && mode != "regex"; + const bool foldText = insensitive && searchType != "regex"; if (foldText) query = asciiLower(std::move(query)); std::optional expression; - if (mode == "regex") { + if (searchType == "regex") { try { auto flags = std::regex_constants::ECMAScript | std::regex_constants::optimize; @@ -1656,25 +1749,25 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( throw IrError("fact search text exceeds 64 KiB"); if (foldText) candidate = asciiLower(std::move(candidate)); - if (mode == "exact") + if (searchType == "exact") return candidate == query; - if (mode == "prefix") + if (searchType == "prefix") return candidate.starts_with(query); - if (mode == "suffix") + if (searchType == "suffix") return candidate.ends_with(query); - if (mode == "contains") + if (searchType == "contains") return candidate.find(query) != std::string::npos; - if (mode == "like") + if (searchType == "like") return like(candidate, query); return std::regex_search(candidate, *expression); }); return result; } - if (mode == "hierarchy") { + if (searchType == "hierarchy") { const auto *query = option("query"); if (!query) - throw IrError("fact search hierarchy mode requires query"); + throw IrError("fact search hierarchy type requires query"); const auto queryType = valueType(*query); if (!queryType) throw IrError("fact search hierarchy query must be a type or fact"); @@ -1697,7 +1790,7 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( return result; } - if (mode == "degree") { + if (searchType == "degree") { const auto query = numberOption("query"); const auto tolerance = numberOption("tolerance"); const auto minimum = numberOption("minimum"); @@ -1739,7 +1832,7 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( return result; } - throw IrError("fact search mode is invalid"); + throw IrError("fact search type is invalid"); } VmValue FelidaeKnowledgeRuntime::joinFacts( @@ -1801,8 +1894,9 @@ VmValue FelidaeKnowledgeRuntime::joinFacts( } void FelidaeKnowledgeRuntime::registerFactType( - IrSymbolRef type, std::vector parents) { - factStore_->registerType(type, std::move(parents)); + IrSymbolRef type, std::vector parents, + std::vector> indexes) { + factStore_->registerType(type, std::move(parents), std::move(indexes)); registeredFactTypes_.insert(type); } @@ -1816,10 +1910,61 @@ FelidaeKnowledgeRuntime::hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) { return factStore_->hierarchyProof(child, ancestor); } + +std::vector> +FelidaeKnowledgeRuntime::hierarchyProofs(IrSymbolRef child, + IrSymbolRef ancestor) { + return factStore_->hierarchyProofs(child, ancestor); +} std::vector FelidaeKnowledgeRuntime::commonAncestors(IrSymbolRef left, IrSymbolRef right) { return factStore_->commonAncestors(left, right); } + +std::vector +FelidaeKnowledgeRuntime::commonAncestorEvidence(IrSymbolRef left, + IrSymbolRef right) { + return factStore_->commonAncestorEvidence(left, right); +} + +VmValue FelidaeKnowledgeRuntime::ancestorAnalysis(IrSymbolRef left, + IrSymbolRef right) { + const auto candidateType = internRuntimeSymbol(encodeText("AncestorCandidate")); + const auto ancestorField = internRuntimeSymbol(encodeText("ancestor")); + const auto leftProofsField = internRuntimeSymbol(encodeText("leftProofs")); + const auto rightProofsField = internRuntimeSymbol(encodeText("rightProofs")); + const auto leftDistanceField = internRuntimeSymbol(encodeText("leftDistance")); + const auto rightDistanceField = + internRuntimeSymbol(encodeText("rightDistance")); + const auto paths = [](const std::vector> &proofs) { + auto result = std::make_shared(); + result->values.reserve(proofs.size()); + for (const auto &proof : proofs) { + auto path = std::make_shared(); + path->values.reserve(proof.size()); + for (const auto symbol : proof) + path->values.emplace_back(VmSymbol{symbol}); + result->values.emplace_back(std::move(path)); + } + return result; + }; + auto result = std::make_shared(); + const auto evidence = factStore_->commonAncestorEvidence(left, right); + result->values.reserve(evidence.size()); + for (const auto &candidate : evidence) { + auto fact = std::make_shared(); + fact->type = candidateType; + fact->origin = VmFact::Origin::Derived; + fact->fields = { + {ancestorField, VmSymbol{candidate.ancestor}}, + {leftProofsField, paths(candidate.leftProofs)}, + {rightProofsField, paths(candidate.rightProofs)}, + {leftDistanceField, static_cast(candidate.leftDistance)}, + {rightDistanceField, static_cast(candidate.rightDistance)}}; + result->values.emplace_back(std::move(fact)); + } + return result; +} std::vector FelidaeKnowledgeRuntime::leastCommonAncestors(IrSymbolRef left, IrSymbolRef right) { @@ -2024,11 +2169,6 @@ VmValue FelidaeKnowledgeRuntime::importCsvFacts( return result; } -double FelidaeKnowledgeRuntime::syncDatabase( - std::span path) { - return persistDatabaseSource(decodeText(path)); -} - double FelidaeKnowledgeRuntime::persistDatabaseSource( std::string_view source, const VmFactPtr &emptySchema) { const VmTextDecoder decoder = [this](std::span pieces) { @@ -2039,7 +2179,10 @@ double FelidaeKnowledgeRuntime::persistDatabaseSource( // different files can share one fact type (see VmFactStore::recordSource). Form::Db::sync(std::filesystem::path(source), factStore_->snapshotBySource(source), runtimeSymbolTable_, - decoder, emptySchema); + decoder, emptySchema, + [this](IrSymbolRef type) { + return factStore_->parentsOf(type); + }); return 1.0; } @@ -2389,8 +2532,13 @@ void IrVerifier::verify(const FelidaeIr &ir) { requireRegister(ir, ir.words[pc + 1]); if (ir.words[pc + 2] >= ir.symbols.size()) throw IrError("IR fact references an invalid symbol"); + if (ir.words[pc + 3] > ir.texts.size()) + throw IrError("IR fact references an invalid source text"); + if (ir.words[pc + 3] != 0 && + ir.texts[ir.words[pc + 3] - 1].empty()) + throw IrError("IR fact source text must not be empty"); initialized[ir.words[pc + 1]] = true; - pc += 3; + pc += 4; break; case IrOpcode::GetField: requireRegister(ir, ir.words[pc + 1]); @@ -2460,6 +2608,11 @@ VmFactPtr VmRuntime::retainFact(const VmFactPtr &) { throw IrError("IR fact retention is unavailable in this runtime"); } +VmFactPtr VmRuntime::retainPersistentFact(const VmFactPtr &, + std::span) { + throw IrError("persistent IR fact retention is unavailable in this runtime"); +} + VmFactPtr VmRuntime::mutateFact(const VmFactPtr &, IrSymbolRef, const VmValue &) { throw IrError("IR fact mutation is unavailable in this runtime"); @@ -2502,7 +2655,8 @@ VmValue VmRuntime::joinFacts(std::span, throw IrError("IR fact join is unavailable in this runtime"); } -void VmRuntime::registerFactType(IrSymbolRef, std::vector) { +void VmRuntime::registerFactType(IrSymbolRef, std::vector, + std::vector>) { throw IrError("IR fact hierarchy is unavailable in this runtime"); } @@ -2513,9 +2667,20 @@ std::vector VmRuntime::snapshotFacts(IrSymbolRef) { std::vector VmRuntime::hierarchyProof(IrSymbolRef, IrSymbolRef) { throw IrError("IR hierarchy is unavailable in this runtime"); } +std::vector> +VmRuntime::hierarchyProofs(IrSymbolRef, IrSymbolRef) { + throw IrError("IR hierarchy is unavailable in this runtime"); +} std::vector VmRuntime::commonAncestors(IrSymbolRef, IrSymbolRef) { throw IrError("IR hierarchy is unavailable in this runtime"); } +std::vector +VmRuntime::commonAncestorEvidence(IrSymbolRef, IrSymbolRef) { + throw IrError("IR hierarchy is unavailable in this runtime"); +} +VmValue VmRuntime::ancestorAnalysis(IrSymbolRef, IrSymbolRef) { + throw IrError("IR hierarchy is unavailable in this runtime"); +} std::vector VmRuntime::leastCommonAncestors(IrSymbolRef, IrSymbolRef) { throw IrError("IR hierarchy is unavailable in this runtime"); @@ -2569,10 +2734,6 @@ VmValue VmRuntime::importCsvFacts(std::span, throw IrError("VM CSV fact service is absent"); } -double VmRuntime::syncDatabase(std::span) { - throw IrError("VM fact database service is absent"); -} - void VmRuntime::beginExecution() {} void VmRuntime::endExecution() noexcept {} @@ -2599,8 +2760,16 @@ VmValue RegisterVm::executeMain(const VerifiedIrModule &verified, parents.reserve(type.parents.size()); for (const auto parent : type.parents) parents.push_back(runtime.resolveSymbol(parent)); + std::vector> indexes; + indexes.reserve(type.indexes.size()); + for (const auto &index : type.indexes) { + auto &resolved = indexes.emplace_back(); + resolved.reserve(index.size()); + for (const auto field : index) + resolved.push_back(runtime.resolveSymbol(field)); + } runtime.registerFactType(runtime.resolveSymbol(type.symbol), - std::move(parents)); + std::move(parents), std::move(indexes)); } runtime.beginExecution(); struct Scope { @@ -2859,6 +3028,9 @@ VmValue RegisterVm::executeIrProgram(const IrModule &module, source = sourceText->pieces; } result = runtime.importCsvFacts(data->pieces, type->pieces, source); + } else if (operation == BuiltinId::AncestorAnalysis) { + result = runtime.ancestorAnalysis(typeSymbol(inputs[0]), + typeSymbol(inputs[1])); } else if (operation == BuiltinId::PropagateFact) { // Registered in BuiltinRegistry with no arity entry and no case here // at all -- the same dead-registration pattern as sort/throw/math @@ -3093,7 +3265,12 @@ VmValue RegisterVm::executeIrProgram(const IrModule &module, case IrOpcode::MakeFact: { auto fact = std::make_shared(); fact->type = symbol(program.words.at(pc + 2)); - registers.at(program.words.at(pc + 1)) = runtime.retainFact(fact); + const auto source = program.words.at(pc + 3); + registers.at(program.words.at(pc + 1)) = + source == 0 + ? runtime.retainFact(fact) + : runtime.retainPersistentFact(fact, + program.texts.at(source - 1)); break; } case IrOpcode::MakeArray: { @@ -3182,7 +3359,7 @@ VmValue RegisterVm::executeIrProgram(const IrModule &module, // caller's own scope where they are actually defined, then threaded // through to every invocation -- the synthesized callback procedure // itself has no access to the caller's registers otherwise. See - // FactQueryNormalizer::iteration() in IrCodeGenerator.cpp. A callback + // FactDmlLowerer::iteration() in IrCodeGenerator.cpp. A callback // written directly against the raw for_each_fact(type, callback) form // (not through that sugar) still takes only the row parameter, so the // captures argument is included only when the target actually diff --git a/src/form/RegisterVm.h b/src/form/RegisterVm.h index 0c09227..0b84a06 100644 --- a/src/form/RegisterVm.h +++ b/src/form/RegisterVm.h @@ -104,6 +104,10 @@ struct VmTensor { std::vector shape; }; using VmTensorPtr = std::shared_ptr; +// `double` is Felidae's unrestricted numeric value. Never normalize or clamp +// it merely because the value is used by this non-Boolean language. Only +// operations whose contract is a truth result (comparisons and predicates) +// return exactly 0.0 or 1.0. VmDegree is a distinct, explicitly bounded value. using VmValue = std::variant; @@ -117,6 +121,10 @@ static_assert( // Public runtime spelling for canonical VM values. using Value = VmValue; +// One authoritative structural equality implementation shared by VM opcode +// dispatch and direct runtime-library operations such as array membership. +bool vmValuesEqual(const VmValue &left, const VmValue &right); + // Stable model/dataset contract. Do not persist VmValue::index(): changing // the in-memory variant layout must never reinterpret an existing corpus or // model artifact. @@ -218,13 +226,22 @@ struct VmFactStoreJournalMark { std::size_t provenance = 0; }; +struct VmCommonAncestorEvidence { + IrSymbolRef ancestor = 0; + std::vector> leftProofs; + std::vector> rightProofs; + std::size_t leftDistance = 0; + std::size_t rightDistance = 0; +}; + // Process-resident append-only fact memory. It belongs to the Form runtime, // not to AST/parser services, and is shared by repeated VM executions in a // daemon. Type and field indexes are authoritative; callers must not mutate a // retained fact directly. class VmFactStore { public: - void registerType(IrSymbolRef type, std::vector parents); + void registerType(IrSymbolRef type, std::vector parents, + std::vector> indexes = {}); VmFactPtr retain(const VmFactPtr &fact); void recordInsert(IrFactRef fact); VmFactPtr mutate(const VmFactPtr &fact, IrSymbolRef field, @@ -236,10 +253,15 @@ class VmFactStore { std::vector snapshot() const; std::vector snapshot(IrSymbolRef type) const; std::vector snapshotAssignableTo(IrSymbolRef type) const; + std::vector parentsOf(IrSymbolRef type) const; std::vector hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) const; + std::vector> + hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor) const; std::vector commonAncestors(IrSymbolRef left, IrSymbolRef right) const; + std::vector + commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right) const; std::vector leastCommonAncestors(IrSymbolRef left, IrSymbolRef right) const; std::vector mostGeneralCommonAncestors(IrSymbolRef left, @@ -269,8 +291,9 @@ class VmFactStore { // store -- it must never infer ownership from fact type alone, since two // different files can share one fact type. A fact with no recorded // source is simply excluded from any snapshotBySource() result; only - // CSV import and explicitly/inferred persistent insert are the only paths - // that establish ownership. Queries and updates never invent it. + // CSV import, compiler-linked fact-only .fx rows, and explicit/inferred + // persistent insert are the only paths that establish ownership. Queries + // and updates never invent it. void recordSource(IrFactRef fact, std::string source); std::optional sourceOf(IrFactRef fact) const; std::vector sourcesForType(IrSymbolRef type) const; @@ -294,6 +317,8 @@ class VmFactStore { std::unordered_map> byType_; std::unordered_map> byField_; std::unordered_map> parents_; + std::unordered_map>> + declaredIndexes_; std::unordered_map factSource_; std::vector mutations_; std::vector provenance_; @@ -359,6 +384,11 @@ class VmRuntime { virtual VmValue loadSymbol(IrSymbolRef symbol); virtual void storeSymbol(IrSymbolRef symbol, const VmValue &value); virtual VmFactPtr retainFact(const VmFactPtr &fact); + // Establishes persistent ownership for a compiler-linked fact database + // row. The base runtime rejects it; only a runtime with a fact store and a + // text codec may accept source-owned facts. + virtual VmFactPtr retainPersistentFact(const VmFactPtr &fact, + std::span source); virtual VmFactPtr mutateFact(const VmFactPtr &fact, IrSymbolRef field, const VmValue &value); virtual double deleteFacts(std::span facts); @@ -382,12 +412,18 @@ class VmRuntime { std::uint8_t kind, IrSymbolRef joinedType, IrSymbolRef joinedLeft, IrSymbolRef joinedRight); virtual void registerFactType(IrSymbolRef type, - std::vector parents); + std::vector parents, + std::vector> indexes = {}); virtual std::vector snapshotFacts(IrSymbolRef type); virtual std::vector hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor); + virtual std::vector> + hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor); virtual std::vector commonAncestors(IrSymbolRef left, IrSymbolRef right); + virtual std::vector + commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right); + virtual VmValue ancestorAnalysis(IrSymbolRef left, IrSymbolRef right); virtual std::vector leastCommonAncestors(IrSymbolRef left, IrSymbolRef right); virtual std::vector @@ -414,7 +450,6 @@ class VmRuntime { virtual VmValue importCsvFacts(std::span data, std::span type, std::span source); - virtual double syncDatabase(std::span path); virtual void beginExecution(); virtual void endExecution() noexcept; virtual RuntimeContext makeRuntimeContext(const VmValue &systemInput) const; @@ -442,6 +477,8 @@ class FelidaeKnowledgeRuntime final : public VmRuntime { VmValue loadSymbol(IrSymbolRef symbol) override; void storeSymbol(IrSymbolRef symbol, const VmValue &value) override; VmFactPtr retainFact(const VmFactPtr &fact) override; + VmFactPtr retainPersistentFact(const VmFactPtr &fact, + std::span source) override; VmFactPtr mutateFact(const VmFactPtr &fact, IrSymbolRef field, const VmValue &value) override; double deleteFacts(std::span facts) override; @@ -464,12 +501,18 @@ class FelidaeKnowledgeRuntime final : public VmRuntime { IrSymbolRef joinedType, IrSymbolRef joinedLeft, IrSymbolRef joinedRight) override; void registerFactType(IrSymbolRef type, - std::vector parents) override; + std::vector parents, + std::vector> indexes = {}) override; std::vector snapshotFacts(IrSymbolRef type) override; std::vector hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) override; + std::vector> + hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor) override; std::vector commonAncestors(IrSymbolRef left, IrSymbolRef right) override; + std::vector + commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right) override; + VmValue ancestorAnalysis(IrSymbolRef left, IrSymbolRef right) override; std::vector leastCommonAncestors(IrSymbolRef left, IrSymbolRef right) override; std::vector @@ -491,7 +534,6 @@ class FelidaeKnowledgeRuntime final : public VmRuntime { VmValue importCsvFacts(std::span data, std::span type, std::span source) override; - double syncDatabase(std::span path) override; void beginExecution() override; void endExecution() noexcept override; RuntimeContext makeRuntimeContext(const VmValue &systemInput) const override; diff --git a/src/form/RuntimeStateModel.cpp b/src/form/RuntimeStateModel.cpp index b52c316..c55b307 100644 --- a/src/form/RuntimeStateModel.cpp +++ b/src/form/RuntimeStateModel.cpp @@ -5,6 +5,7 @@ #include "SemanticOperation.h" #include "../ModelStore.h" +#include #include #include #include @@ -19,6 +20,7 @@ namespace Felidae { namespace { std::vector runtimeInputIds( std::uint16_t operation, std::span inputKinds, + std::span> inputValues, std::span factTypes, std::span> factTypeCounts, std::span> hierarchyEdges, @@ -29,6 +31,23 @@ std::vector runtimeInputIds( const auto structural = [&](std::int64_t value) { return vocabularySize - kRuntimeStructuralInputTokens + value; }; + const auto appendValueTokens = [&](std::vector &ids, + const auto &tokens) { + constexpr std::uint32_t kStructuralBit = 0x80000000u; + for (const auto token : tokens) { + if ((token & kStructuralBit) != 0) { + const auto marker = token & ~kStructuralBit; + if (marker >= kRuntimeStructuralInputTokens) + throw IrError("runtime GRU value marker exceeds its vocabulary"); + ids.push_back(structural(marker)); + } else { + if (token >= static_cast( + vocabularySize - kRuntimeStructuralInputTokens)) + throw IrError("runtime GRU value PieceId exceeds its vocabulary"); + ids.push_back(token); + } + } + }; const auto appendPieces = [&](std::vector &ids, const PieceSequence &pieces) { if (pieces.empty()) @@ -41,11 +60,12 @@ std::vector runtimeInputIds( ids.push_back(piece); } }; - const auto kFactTypesMarker = structural(4); - const auto kHierarchyMarker = structural(5); - const auto kInputsMarker = structural(6); + const auto kFactTypesMarker = structural(8); + const auto kHierarchyMarker = structural(9); + const auto kInputsMarker = structural(10); if (!isKnownSemanticOperation(operation) || !semanticOperationAcceptsArity(operation, inputKinds.size()) || + (!inputValues.empty() && inputValues.size() != inputKinds.size()) || inputKinds.size() > kMaximumContextItems || factTypes.size() > kMaximumContextItems || factTypeCounts.size() > kMaximumContextItems || @@ -68,6 +88,8 @@ std::vector runtimeInputIds( throw IrError("runtime GRU degree operation requires a numeric input"); } break; + case SemanticOperationId::Suggest: + break; } std::vector ids; ids.reserve(2 + inputKinds.size() + factTypes.size() + @@ -78,10 +100,10 @@ std::vector runtimeInputIds( appendPieces(ids, type); // Counts distinguish current fact population while keeping a fixed // integer vocabulary: one, two-to-four, and five-or-more facts. - const auto kFactCountsMarker = structural(7); - const auto kOneFactMarker = structural(8); - const auto kSeveralFactsMarker = structural(9); - const auto kManyFactsMarker = structural(10); + const auto kFactCountsMarker = structural(11); + const auto kOneFactMarker = structural(12); + const auto kSeveralFactsMarker = structural(13); + const auto kManyFactsMarker = structural(14); ids.push_back(kFactCountsMarker); for (const auto &[type, count] : factTypeCounts) { appendPieces(ids, type); @@ -99,8 +121,12 @@ std::vector runtimeInputIds( if (kind < RuntimeValueKind::Nil || kind > RuntimeValueKind::TextMap) { throw IrError("runtime GRU input value kind is invalid"); } - ids.push_back(structural(11 + static_cast(kind))); + ids.push_back(structural(15 + static_cast(kind))); } + for (const auto &value : inputValues) + appendValueTokens(ids, value); + if (ids.size() > 4096) + throw IrError("runtime GRU input sequence exceeds its bound"); return ids; } } // namespace @@ -141,10 +167,13 @@ class GruRuntimeStateModel::Implementation { projection = register_module( "projection", torch::nn::Linear(c.hiddenSize, c.outputVocabularySize)); + scoreProjection = register_module("score_projection", + torch::nn::Linear(c.hiddenSize, 1)); } torch::nn::Embedding embedding{nullptr}; torch::nn::GRU recurrent{nullptr}; torch::nn::Linear projection{nullptr}; + torch::nn::Linear scoreProjection{nullptr}; }; struct ExecutionState { torch::Tensor hidden; @@ -177,13 +206,15 @@ class GruRuntimeStateModel::Implementation { torch::zeros({1, 1}, torch::TensorOptions().dtype(torch::kInt64)); const auto hidden = torch::zeros({c.layerCount, 1, c.hiddenSize}); const auto output = production->forward({input, hidden}).toTuple(); - if (output->elements().size() != 2) { + if (output->elements().size() != 3) { throw IrError( "runtime production artifact has an incompatible forward contract"); } const auto logits = output->elements()[0].toTensor(); - const auto nextHidden = output->elements()[1].toTensor(); + const auto score = output->elements()[1].toTensor(); + const auto nextHidden = output->elements()[2].toTensor(); if (logits.dim() != 1 || logits.size(0) != c.outputVocabularySize || + score.numel() != 1 || nextHidden.dim() != 3 || nextHidden.size(0) != c.layerCount || nextHidden.size(1) != 1 || nextHidden.size(2) != c.hiddenSize) { throw IrError( @@ -277,7 +308,7 @@ GruRuntimeStateModel GruRuntimeStateModel::loadVersioned( requireManifestValue(manifest, "opcode_vocabulary_version", "felidae-ir-v13", modelName); requireManifestValue(manifest, "training_schema", - "felidae-runtime-operation-v8", modelName); + "felidae-runtime-operation-v9", modelName); if (manifestInteger(manifest, "input_vocabulary", modelName) != c.inputVocabularySize || manifestInteger(manifest, "output_vocabulary", modelName) != @@ -319,14 +350,20 @@ Value GruRuntimeStateModel::evaluate(const RuntimeOperation &operation, context.symbolTable ? std::span(*context.symbolTable) : std::span{}; const auto knowledge = runtimeKnowledgePieces(context.knowledge, symbols); + std::vector> inputValues; + inputValues.reserve(inputs.size()); + for (const auto &value : inputs) + inputValues.push_back(runtimeValueEncoding(value, symbols)); const auto ids = runtimeInputIds( - operation.id, inputKinds, knowledge.factTypes, knowledge.factTypeCounts, - knowledge.hierarchyEdges, configuration_.inputVocabularySize); + operation.id, inputKinds, inputValues, knowledge.factTypes, + knowledge.factTypeCounts, knowledge.hierarchyEdges, + configuration_.inputVocabularySize); torch::InferenceMode guard; const auto input = torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) .reshape({-1, 1}); torch::Tensor logits; + torch::Tensor score; if (implementation_->production) { if (!state->hidden.defined()) state->hidden = torch::zeros( @@ -334,7 +371,8 @@ Value GruRuntimeStateModel::evaluate(const RuntimeOperation &operation, auto output = implementation_->production->forward({input, state->hidden}).toTuple(); logits = output->elements().at(0).toTensor(); - state->hidden = output->elements().at(1).toTensor().detach(); + score = output->elements().at(1).toTensor(); + state->hidden = output->elements().at(2).toTensor().detach(); } else { const auto result = state->hidden.defined() @@ -344,10 +382,17 @@ Value GruRuntimeStateModel::evaluate(const RuntimeOperation &operation, : implementation_->network->recurrent->forward( implementation_->network->embedding->forward(input)); state->hidden = std::get<1>(result).detach(); - logits = implementation_->network->projection->forward( - std::get<0>(result) - .select(0, std::get<0>(result).size(0) - 1) - .select(0, 0)); + const auto last = std::get<0>(result) + .select(0, std::get<0>(result).size(0) - 1) + .select(0, 0); + logits = implementation_->network->projection->forward(last); + score = implementation_->network->scoreProjection->forward(last); + } + if (operation.id == static_cast(SemanticOperationId::Suggest)) { + const auto value = score.item(); + if (!std::isfinite(value)) + throw IrError("runtime GRU scoring head produced a non-finite value"); + return value; } const auto outputId = logits.argmax().item(); if (outputId < 0 || @@ -371,6 +416,8 @@ Value GruRuntimeStateModel::evaluate(const RuntimeOperation &operation, return inferred; } case RuntimeOutputTokenKind::DegreeMilli: + if (operation.id == static_cast(SemanticOperationId::Suggest)) + return static_cast(token.value) / 1000.0; return VmDegree(static_cast(token.value) / 1000.0); case RuntimeOutputTokenKind::Nil: return VmNil{}; @@ -395,7 +442,8 @@ GruRuntimeStateModel::trainTeacherForced(const RuntimeTrainingRecord &record, if (targetToken >= outputVocabulary_.size() || learningRate <= 0.0) throw IrError("runtime GRU training target or learning rate is invalid"); const auto ids = - runtimeInputIds(record.operationId, record.inputKinds, record.factTypes, + runtimeInputIds(record.operationId, record.inputKinds, record.inputValues, + record.factTypes, record.factTypeCounts, record.hierarchyEdges, configuration_.inputVocabularySize); if (ids.size() > 4096) @@ -429,6 +477,49 @@ GruRuntimeStateModel::trainTeacherForced(const RuntimeTrainingRecord &record, #endif } +double GruRuntimeStateModel::trainScore(const RuntimeTrainingRecord &record, + double learningRate) { +#ifdef FELIDAE_HAS_TORCH + verifyRuntimeTrainingRecord(record); + if (record.operationId != + static_cast(SemanticOperationId::Suggest) || + record.targetKind != RuntimeTrainingTargetKind::Score || + !std::isfinite(record.targetScore) || learningRate <= 0.0) + throw IrError("runtime GRU score target or learning rate is invalid"); + const auto ids = runtimeInputIds( + record.operationId, record.inputKinds, record.inputValues, record.factTypes, + record.factTypeCounts, record.hierarchyEdges, + configuration_.inputVocabularySize); + implementation_->prepareOptimizer(learningRate); + implementation_->network->train(); + implementation_->optimizer->zero_grad(); + const auto input = + torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) + .reshape({-1, 1}); + const auto recurrent = implementation_->network->recurrent->forward( + implementation_->network->embedding->forward(input)); + const auto last = std::get<0>(recurrent) + .select(0, std::get<0>(recurrent).size(0) - 1) + .select(0, 0); + const auto predicted = + implementation_->network->scoreProjection->forward(last).reshape({}); + const auto expected = + torch::tensor(record.targetScore, predicted.options()); + const auto loss = torch::mse_loss(predicted, expected); + const auto lossValue = loss.item(); + if (!std::isfinite(lossValue)) + throw IrError("runtime GRU score training produced non-finite loss"); + loss.backward(); + implementation_->optimizer->step(); + implementation_->network->eval(); + return lossValue; +#else + (void)record; + (void)learningRate; + throw IrError("runtime GRU score training requires FELIDAE_ENABLE_LIBTORCH=ON"); +#endif +} + std::size_t GruRuntimeStateModel::predictTeacherToken( const RuntimeTrainingRecord &record) const { #ifdef FELIDAE_HAS_TORCH @@ -436,7 +527,8 @@ std::size_t GruRuntimeStateModel::predictTeacherToken( throw IrError("runtime teacher prediction requires a training model"); verifyRuntimeTrainingRecord(record); const auto ids = - runtimeInputIds(record.operationId, record.inputKinds, record.factTypes, + runtimeInputIds(record.operationId, record.inputKinds, record.inputValues, + record.factTypes, record.factTypeCounts, record.hierarchyEdges, configuration_.inputVocabularySize); torch::InferenceMode guard; @@ -463,6 +555,38 @@ std::size_t GruRuntimeStateModel::predictTeacherToken( #endif } +double GruRuntimeStateModel::predictScore( + const RuntimeTrainingRecord &record) const { +#ifdef FELIDAE_HAS_TORCH + if (!implementation_->network || + record.operationId != + static_cast(SemanticOperationId::Suggest)) + throw IrError("runtime score prediction requires a Suggest training record"); + verifyRuntimeTrainingRecord(record); + const auto ids = runtimeInputIds( + record.operationId, record.inputKinds, record.inputValues, record.factTypes, + record.factTypeCounts, record.hierarchyEdges, + configuration_.inputVocabularySize); + torch::InferenceMode guard; + const auto input = + torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) + .reshape({-1, 1}); + const auto recurrent = implementation_->network->recurrent->forward( + implementation_->network->embedding->forward(input)); + const auto value = implementation_->network->scoreProjection + ->forward(std::get<0>(recurrent) + .select(0, std::get<0>(recurrent).size(0) - 1) + .select(0, 0)) + .item(); + if (!std::isfinite(value)) + throw IrError("runtime GRU scoring head produced a non-finite value"); + return value; +#else + (void)record; + throw IrError("runtime GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); +#endif +} + void GruRuntimeStateModel::saveCheckpoint( const std::filesystem::path &artifactPath) const { #ifdef FELIDAE_HAS_TORCH @@ -513,6 +637,13 @@ void GruRuntimeStateModel::exportTorchScript( module.register_parameter( "projection_bias", implementation_->network->projection->bias.detach().clone(), false); + module.register_parameter( + "score_projection_weight", + implementation_->network->scoreProjection->weight.detach().clone(), + false); + module.register_parameter( + "score_projection_bias", + implementation_->network->scoreProjection->bias.detach().clone(), false); std::ostringstream parameters; bool first = true; for (const auto ¶meter : @@ -526,14 +657,16 @@ void GruRuntimeStateModel::exportTorchScript( } std::ostringstream source; source << "def forward(self, input_ids: Tensor, hidden: Tensor) -> " - "Tuple[Tensor, Tensor]:\n" + "Tuple[Tensor, Tensor, Tensor]:\n" << " embedded = torch.embedding(self.embedding, input_ids)\n" << " recurrent = torch.gru(embedded, hidden, [" << parameters.str() << "], True, " << configuration_.layerCount << ", 0.0, False, False, False)\n" << " logits = torch.linear(recurrent[0][-1][0], " "self.projection_weight, self.projection_bias)\n" - << " return logits, recurrent[1]\n"; + << " score = torch.linear(recurrent[0][-1][0], " + "self.score_projection_weight, self.score_projection_bias)\n" + << " return logits, score, recurrent[1]\n"; module.define(source.str()); module.eval(); module.save(artifactPath.string()); @@ -549,7 +682,7 @@ void GruRuntimeStateModel::exportTorchScript( << "\ndecoder_contract=" << kRuntimeDecoderContract << "\nir_binary_version=" << LANGUAGE_VERSION << "\nopcode_vocabulary_version=felidae-ir-v13\ntraining_schema=" - "felidae-runtime-operation-v8\ninput_vocabulary=" + "felidae-runtime-operation-v9\ninput_vocabulary=" << configuration_.inputVocabularySize << "\noutput_vocabulary=" << configuration_.outputVocabularySize << "\nembedding_size=" << configuration_.embeddingSize diff --git a/src/form/RuntimeStateModel.h b/src/form/RuntimeStateModel.h index 7271371..25a860f 100644 --- a/src/form/RuntimeStateModel.h +++ b/src/form/RuntimeStateModel.h @@ -31,15 +31,15 @@ struct RuntimeOutputToken { // a finite decoder vocabulary and every selected position is range-checked // against the current operation inputs before it enters a VM register. inline constexpr std::size_t kRuntimeModelReferenceLimit = 16; -inline constexpr std::int64_t kRuntimeStructuralInputTokens = 32; -inline constexpr std::string_view kRuntimeArtifactFormatVersion = "1"; +inline constexpr std::int64_t kRuntimeStructuralInputTokens = 48; +inline constexpr std::string_view kRuntimeArtifactFormatVersion = "2"; inline constexpr std::string_view kRuntimeModelFamily = "felidae-vm-runtime-gru"; -inline constexpr std::string_view kRuntimeModelVersion = "runtime-gru-v1"; +inline constexpr std::string_view kRuntimeModelVersion = "runtime-gru-v2"; inline constexpr std::string_view kRuntimeTokenizerContract = - "sentencepiece-id-sequence-v1"; + "sentencepiece-structured-values-v2"; inline constexpr std::string_view kRuntimeDecoderContract = - "operation-sequence-hidden-state-v1"; + "typed-actions-plus-finite-score-v2"; // Single production vocabulary contract used by both the VM loader and the // C++ trainer. A manifest's output_vocabulary is checked against this list. @@ -73,9 +73,12 @@ class GruRuntimeStateModel final : public RuntimeStateModel { RuntimeContext& context) override; double trainTeacherForced(const RuntimeTrainingRecord& record, std::size_t targetToken, double learningRate); + double trainScore(const RuntimeTrainingRecord& record, + double learningRate); // Deterministic validation path for a persisted JSONL record. It returns // a finite vocabulary index without constructing a runtime VmValue. std::size_t predictTeacherToken(const RuntimeTrainingRecord& record) const; + double predictScore(const RuntimeTrainingRecord& record) const; void saveCheckpoint(const std::filesystem::path& checkpointPath) const; void exportTorchScript(const std::filesystem::path& artifactPath, std::string_view sentencePieceIdentity) const; diff --git a/src/form/RuntimeTraining.cpp b/src/form/RuntimeTraining.cpp index 63a0259..53a3b99 100644 --- a/src/form/RuntimeTraining.cpp +++ b/src/form/RuntimeTraining.cpp @@ -5,8 +5,11 @@ #include #include +#include +#include #include #include +#include #include #include @@ -15,6 +18,10 @@ namespace { using Json = nlohmann::json; constexpr std::size_t kMaximumRecords = 1'000'000; constexpr std::size_t kMaximumItems = 1'000'000; +constexpr std::uint32_t kStructuralEncodingBit = 0x80000000u; +constexpr std::uint32_t structural(std::uint32_t marker) { + return kStructuralEncodingBit | marker; +} void requireJsonlPath(const std::filesystem::path &path) { if (path.extension() != ".jsonl") @@ -54,7 +61,7 @@ RuntimeTrainingTargetKind targetKind(std::uint64_t value) { if (value < static_cast( RuntimeTrainingTargetKind::InputReference) || value > - static_cast(RuntimeTrainingTargetKind::NumericTruth)) { + static_cast(RuntimeTrainingTargetKind::Score)) { throw IrError("runtime JSONL has an invalid target kind"); } return static_cast(value); @@ -80,6 +87,8 @@ RuntimeValueKind targetValueKind(const RuntimeTrainingRecord &record) { return RuntimeValueKind::Nil; case RuntimeTrainingTargetKind::NumericTruth: return RuntimeValueKind::Number; + case RuntimeTrainingTargetKind::Score: + return RuntimeValueKind::Number; } throw IrError("runtime JSONL target kind is invalid"); } @@ -111,6 +120,11 @@ void validateTrainingContract(const RuntimeTrainingRecord &record) { throw IrError("runtime degree-operation teacher has invalid kinds"); } return; + case SemanticOperationId::Suggest: + if (record.targetKind != RuntimeTrainingTargetKind::Score || + output != RuntimeValueKind::Number) + throw IrError("runtime Suggest teacher must describe a numeric score"); + return; } throw IrError("runtime JSONL semantic operation ID is invalid"); } @@ -212,8 +226,113 @@ factTypeCounts(const Json &object) { } } // namespace +std::vector +runtimeValueEncoding(const VmValue &value, + std::span symbolTable) { + constexpr std::size_t kMaximumEncodedTokens = 4096; + std::vector result; + const auto appendSymbol = [&](IrSymbolRef symbol) { + const auto pieces = irSymbolPieces(symbolTable, symbol); + result.insert(result.end(), pieces.begin(), pieces.end()); + }; + const auto orderedFields = [&](const auto &fields) { + std::vector order(fields.size()); + std::iota(order.begin(), order.end(), 0); + std::sort(order.begin(), order.end(), [&](std::size_t left, + std::size_t right) { + const auto leftPieces = irSymbolPieces(symbolTable, fields[left].first); + const auto rightPieces = irSymbolPieces(symbolTable, fields[right].first); + return std::lexicographical_compare( + leftPieces.begin(), leftPieces.end(), rightPieces.begin(), + rightPieces.end()); + }); + return order; + }; + const auto appendNumber = [&](double number, std::uint32_t marker) { + result.push_back(structural(marker)); + const auto bits = std::bit_cast(number); + for (int bit = 63; bit >= 0; --bit) + result.push_back(structural((bits & (std::uint64_t{1} << bit)) ? 39 : 38)); + }; + const auto append = [&](const auto &self, const VmValue &item, + std::size_t depth) -> void { + if (depth > 32 || result.size() > kMaximumEncodedTokens) + throw IrError("runtime SSM value encoding exceeds its bound"); + if (std::holds_alternative(item)) { + result.push_back(structural(28)); + } else if (const auto number = std::get_if(&item)) { + appendNumber(*number, 29); + } else if (const auto degree = std::get_if(&item)) { + appendNumber(degree->value, 30); + } else if (const auto text = std::get_if(&item)) { + result.push_back(structural(31)); + result.insert(result.end(), text->pieces.begin(), text->pieces.end()); + } else if (const auto symbol = std::get_if(&item)) { + result.push_back(structural(32)); + appendSymbol(symbol->value); + } else if (const auto array = std::get_if(&item)) { + if (!*array) + throw IrError("runtime SSM cannot encode a null array"); + result.push_back(structural(33)); + for (const auto &value : (*array)->values) + self(self, value, depth + 1); + result.push_back(structural(27)); + } else if (const auto map = std::get_if(&item)) { + if (!*map) + throw IrError("runtime SSM cannot encode a null map"); + result.push_back(structural(34)); + for (const auto index : orderedFields((*map)->entries)) { + const auto &[field, value] = (*map)->entries[index]; + result.push_back(structural(40)); + appendSymbol(field); + self(self, value, depth + 1); + } + result.push_back(structural(27)); + } else if (const auto fact = std::get_if(&item)) { + if (!*fact) + throw IrError("runtime SSM cannot encode a null fact"); + result.push_back(structural(35)); + appendSymbol((*fact)->type); + for (const auto index : orderedFields((*fact)->fields)) { + const auto &[field, value] = (*fact)->fields[index]; + result.push_back(structural(40)); + appendSymbol(field); + self(self, value, depth + 1); + } + result.push_back(structural(27)); + } else if (const auto tensor = std::get_if(&item)) { + if (!*tensor || !(*tensor)->storage) + throw IrError("runtime SSM cannot encode a null tensor"); + throw IrError("runtime SSM tensor inputs are unsupported; pass an " + "explicit fact or numeric summary"); + } else if (const auto map = std::get_if(&item)) { + if (!*map) + throw IrError("runtime SSM cannot encode a null text map"); + result.push_back(structural(37)); + auto entries = (*map)->entries; + std::sort(entries.begin(), entries.end(), + [](const auto &left, const auto &right) { + return left.first < right.first; + }); + for (const auto &[key, value] : entries) { + result.push_back(structural(40)); + result.insert(result.end(), key.begin(), key.end()); + self(self, value, depth + 1); + } + result.push_back(structural(27)); + } + if (result.size() > kMaximumEncodedTokens) + throw IrError("runtime SSM value encoding exceeds its bound"); + }; + result.push_back(structural(26)); + append(append, value, 0); + result.push_back(structural(27)); + return result; +} + void verifyRuntimeTrainingRecord(const RuntimeTrainingRecord &record) { if (record.inputKinds.size() > kMaximumItems || + record.inputValues.size() != record.inputKinds.size() || record.factTypes.size() > kMaximumItems || record.factTypeCounts.size() > kMaximumItems || record.hierarchyEdges.size() > kMaximumItems) { @@ -222,6 +341,9 @@ void verifyRuntimeTrainingRecord(const RuntimeTrainingRecord &record) { for (const auto kind : record.inputKinds) { (void)valueKind(static_cast(kind), "input value kind"); } + for (const auto &value : record.inputValues) + if (value.empty() || value.size() > 4096) + throw IrError("runtime JSONL input value encoding is invalid"); const auto validSequence = [](const PieceSequence &pieces) { if (pieces.empty()) throw IrError("runtime JSONL symbol has no SentencePiece IDs"); @@ -252,6 +374,9 @@ void verifyRuntimeTrainingRecord(const RuntimeTrainingRecord &record) { record.targetValue > 1000)) { throw IrError("runtime JSONL target value is invalid"); } + if (target == RuntimeTrainingTargetKind::Score && + !std::isfinite(record.targetScore)) + throw IrError("runtime JSONL score target must be finite"); validateTrainingContract(record); } @@ -295,6 +420,9 @@ void writeRuntimeTrainingDataset( Json inputKinds = Json::array(); for (const auto kind : record.inputKinds) inputKinds.push_back(static_cast(kind)); + Json inputValues = Json::array(); + for (const auto &value : record.inputValues) + inputValues.push_back(value); Json factTypes = Json::array(); for (const auto &type : record.factTypes) factTypes.push_back(type); @@ -304,17 +432,19 @@ void writeRuntimeTrainingDataset( Json edges = Json::array(); for (const auto &[child, parent] : record.hierarchyEdges) edges.push_back({child, parent}); - output << Json{{"schema_version", kRuntimeTrainingSchemaVersion}, + Json serialized{{"schema_version", kRuntimeTrainingSchemaVersion}, {"operation_id", record.operationId}, {"input_kinds", std::move(inputKinds)}, + {"input_values", std::move(inputValues)}, {"fact_types", std::move(factTypes)}, {"fact_type_counts", std::move(typeCounts)}, {"hierarchy_edges", std::move(edges)}, {"target_kind", static_cast(record.targetKind)}, - {"target_value", record.targetValue}} - .dump() - << '\n'; + {"target_value", record.targetValue}}; + if (record.targetKind == RuntimeTrainingTargetKind::Score) + serialized["target_score"] = record.targetScore; + output << serialized.dump() << '\n'; if (!output) throw IrError("cannot write runtime JSONL dataset"); } @@ -355,12 +485,31 @@ loadRuntimeTrainingDataset(const std::filesystem::path &path) { const auto rawInputKinds = ids(object, "input_kinds"); for (const auto kind : rawInputKinds) record.inputKinds.push_back(valueKind(kind, "input value kind")); + if (!object.contains("input_values") || + !object.at("input_values").is_array()) + throw IrError("runtime JSONL record requires array input_values"); + for (const auto &encoded : object.at("input_values")) { + if (!encoded.is_array()) + throw IrError("runtime JSONL input value must be an ID array"); + std::vector value; + value.reserve(encoded.size()); + for (const auto &token : encoded) + value.push_back(bounded( + unsignedValue(token, "input_values"), "input_values")); + record.inputValues.push_back(std::move(value)); + } record.factTypes = pieceSequences(object, "fact_types"); record.factTypeCounts = factTypeCounts(object); record.hierarchyEdges = hierarchyEdges(object); record.targetKind = targetKind(member(object, "target_kind")); record.targetValue = bounded( member(object, "target_value"), "target_value"); + if (record.targetKind == RuntimeTrainingTargetKind::Score) { + if (!object.contains("target_score") || + !object.at("target_score").is_number()) + throw IrError("runtime JSONL score record requires target_score"); + record.targetScore = object.at("target_score").get(); + } verifyRuntimeTrainingRecord(record); records.push_back(std::move(record)); if (records.size() > kMaximumRecords) diff --git a/src/form/RuntimeTraining.h b/src/form/RuntimeTraining.h index 1a496cf..668817b 100644 --- a/src/form/RuntimeTraining.h +++ b/src/form/RuntimeTraining.h @@ -15,6 +15,7 @@ enum class RuntimeTrainingTargetKind : std::uint8_t { DegreeMilli = 3, Nil = 4, NumericTruth = 5, + Score = 6, }; // One verified runtime operation, represented exactly as the current GRU @@ -23,13 +24,22 @@ enum class RuntimeTrainingTargetKind : std::uint8_t { struct RuntimeTrainingRecord { std::uint16_t operationId = 0; std::vector inputKinds; + // Canonical value sequences: SentencePiece IDs are stored directly; + // structural markers use the high bit and are relocated to the model's + // reserved tail vocabulary by RuntimeStateModel. + std::vector> inputValues; std::vector factTypes; std::vector> factTypeCounts; std::vector> hierarchyEdges; RuntimeTrainingTargetKind targetKind = RuntimeTrainingTargetKind::Nil; std::uint32_t targetValue = 0; + double targetScore = 0.0; }; +std::vector +runtimeValueEncoding(const VmValue &value, + std::span symbolTable); + struct RuntimeKnowledgePieces { std::vector factTypes; std::vector> factTypeCounts; @@ -46,7 +56,7 @@ RuntimeKnowledgePieces runtimeKnowledgePieces( // JSON Lines v8: one self-describing, integer-only record per line. The // schema value is repeated deliberately: lines can be validated or streamed // independently and no legacy binary header needs to be retained. -inline constexpr std::uint32_t kRuntimeTrainingSchemaVersion = 8; +inline constexpr std::uint32_t kRuntimeTrainingSchemaVersion = 9; void verifyRuntimeTrainingRecord(const RuntimeTrainingRecord& record); void writeRuntimeTrainingDataset(const std::filesystem::path& path, std::span records); diff --git a/src/form/SemanticOperation.h b/src/form/SemanticOperation.h index a41b75d..c6def6f 100644 --- a/src/form/SemanticOperation.h +++ b/src/form/SemanticOperation.h @@ -13,6 +13,9 @@ enum class SemanticOperationId : std::uint16_t { SelectFact = 0x0002, DeriveFact = 0x0003, EvaluateDegree = 0x0004, + // Explicit application-facing scoring hook. Unlike EvaluateDegree, its + // result is an ordinary finite double and is never clamped to [0, 1]. + Suggest = 0x0005, }; inline bool isKnownSemanticOperation(std::uint16_t operation) noexcept { @@ -21,6 +24,7 @@ inline bool isKnownSemanticOperation(std::uint16_t operation) noexcept { case SemanticOperationId::SelectFact: case SemanticOperationId::DeriveFact: case SemanticOperationId::EvaluateDegree: + case SemanticOperationId::Suggest: return true; } return false; @@ -41,6 +45,8 @@ semanticOperationForName(std::string_view name) noexcept { return SemanticOperationId::DeriveFact; if (name == "semantic_evaluate_degree") return SemanticOperationId::EvaluateDegree; + if (name == "ssm.suggest" || name == "ssm:suggest") + return SemanticOperationId::Suggest; return std::nullopt; } diff --git a/src/form/libs/Builtin.cpp b/src/form/libs/Builtin.cpp index 7c7cd79..6ff12ba 100644 --- a/src/form/libs/Builtin.cpp +++ b/src/form/libs/Builtin.cpp @@ -7,6 +7,7 @@ #include "form/IrModule.h" #include +#include #include #include #include @@ -45,6 +46,21 @@ double numberValue(const VmValue &value, std::string_view operation) { return *number; } +std::string asciiCase(std::string text, bool upper) { + std::transform(text.begin(), text.end(), text.begin(), [upper](char byte) { + const auto value = static_cast(byte); + return static_cast(upper ? std::toupper(value) : std::tolower(value)); + }); + return text; +} + +double textLength(std::string_view text) { + return static_cast( + std::count_if(text.begin(), text.end(), [](char byte) { + return (static_cast(byte) & 0xc0U) != 0x80U; + })); +} + } // namespace Json::Value vmValueToJson(const VmValue &value, @@ -143,6 +159,15 @@ VmValue evaluateBuiltin(BuiltinId operation, std::span inputs, } return (*array)->values[static_cast(*position)]; } + case BuiltinId::ArrayPush: { + const auto array = std::get_if(&inputs[0]); + if (!array || !*array) + throw IrError("array.push requires an array"); + auto result = std::make_shared(); + result->values = (*array)->values; + result->values.push_back(inputs[1]); + return result; + } case BuiltinId::Count: case BuiltinId::ArrayLen: { const auto array = std::get_if(&inputs[0]); @@ -223,6 +248,126 @@ VmValue evaluateBuiltin(BuiltinId operation, std::span inputs, result->values.emplace_back(value); return result; } + case BuiltinId::Length: + if (const auto text = std::get_if(&inputs[0])) + return textLength(decodeText(text->pieces, codec)); + else if (const auto array = std::get_if(&inputs[0]); + array && *array) + return static_cast((*array)->values.size()); + throw IrError("length requires text or an array"); + case BuiltinId::StrLen: + return textLength(textValue(inputs[0], codec, "str.len")); + case BuiltinId::Lower: + case BuiltinId::StrLower: + return VmText{encodeText( + asciiCase(textValue(inputs[0], codec, "lower"), false), codec)}; + case BuiltinId::Upper: + case BuiltinId::StrUpper: + return VmText{encodeText( + asciiCase(textValue(inputs[0], codec, "upper"), true), codec)}; + case BuiltinId::Contains: + if (const auto text = std::get_if(&inputs[0])) { + const auto data = decodeText(text->pieces, codec); + const auto query = textValue(inputs[1], codec, "contains"); + return data.find(query) == std::string::npos ? 0.0 : 1.0; + } else if (const auto array = std::get_if(&inputs[0]); + array && *array) { + return std::any_of((*array)->values.begin(), (*array)->values.end(), + [&](const VmValue &item) { + return vmValuesEqual(item, inputs[1]); + }) + ? 1.0 + : 0.0; + } + throw IrError("contains requires text or an array"); + case BuiltinId::Search: { + const auto array = std::get_if(&inputs[0]); + if (!array || !*array) + throw IrError("search requires an array of text"); + const auto query = textValue(inputs[1], codec, "search"); + auto result = std::make_shared(); + for (const auto &item : (*array)->values) { + const auto text = std::get_if(&item); + if (!text) + throw IrError("search requires an array of text"); + if (decodeText(text->pieces, codec).find(query) != std::string::npos) + result->values.push_back(item); + } + return result; + } + case BuiltinId::StrContains: { + const auto data = textValue(inputs[0], codec, "str.contains"); + const auto needle = textValue(inputs[1], codec, "str.contains"); + return data.find(needle) == std::string::npos ? 0.0 : 1.0; + } + case BuiltinId::StrConcat: + return VmText{encodeText(textValue(inputs[0], codec, "str.concat") + + textValue(inputs[1], codec, "str.concat"), + codec)}; + case BuiltinId::StrJoin: { + const auto array = std::get_if(&inputs[0]); + if (!array || !*array) + throw IrError("str.join requires an array of text"); + const auto delimiter = textValue(inputs[1], codec, "str.join"); + std::string result; + for (std::size_t index = 0; index < (*array)->values.size(); ++index) { + if (index != 0) + result += delimiter; + result += textValue((*array)->values[index], codec, "str.join"); + } + return VmText{encodeText(result, codec)}; + } + case BuiltinId::StrTrim: { + auto text = textValue(inputs[0], codec, "str.trim"); + const auto whitespace = [](char byte) { + return std::isspace(static_cast(byte)) != 0; + }; + const auto first = std::find_if_not(text.begin(), text.end(), whitespace); + const auto last = + std::find_if_not(text.rbegin(), text.rend(), whitespace).base(); + return VmText{encodeText(first < last ? std::string(first, last) + : std::string{}, + codec)}; + } + case BuiltinId::StrSplit: { + const auto data = textValue(inputs[0], codec, "str.split"); + const auto delimiter = textValue(inputs[1], codec, "str.split"); + if (delimiter.empty()) + throw IrError("str.split delimiter must not be empty"); + auto result = std::make_shared(); + std::size_t begin = 0; + for (;;) { + const auto end = data.find(delimiter, begin); + result->values.emplace_back( + VmText{encodeText(data.substr(begin, end - begin), codec)}); + if (end == std::string::npos) + break; + begin = end + delimiter.size(); + } + return result; + } + case BuiltinId::StrReplace: { + auto data = textValue(inputs[0], codec, "str.replace"); + const auto search = textValue(inputs[1], codec, "str.replace"); + const auto replacement = textValue(inputs[2], codec, "str.replace"); + if (search.empty()) + throw IrError("str.replace search must not be empty"); + std::size_t position = 0; + while ((position = data.find(search, position)) != std::string::npos) { + data.replace(position, search.size(), replacement); + position += replacement.size(); + } + return VmText{encodeText(data, codec)}; + } + case BuiltinId::StrStartsWith: + case BuiltinId::StrEndsWith: { + const auto data = textValue(inputs[0], codec, "string boundary check"); + const auto part = textValue(inputs[1], codec, "string boundary check"); + return (operation == BuiltinId::StrStartsWith ? data.starts_with(part) + : data.ends_with(part)) + ? 1.0 + : 0.0; + } case BuiltinId::JsonParse: return jsonToVmValue( Json::parse(textValue(inputs[0], codec, "json.parse")), codec); diff --git a/src/form/libs/Db.cpp b/src/form/libs/Db.cpp index e549e5c..b17d137 100644 --- a/src/form/libs/Db.cpp +++ b/src/form/libs/Db.cpp @@ -132,11 +132,22 @@ std::string mapText(const Entries &entries, KeyText keyText, std::string factText(const VmFact &fact, std::span symbolTable, const VmTextDecoder &decodeText, std::size_t indent, - std::size_t depth) { + std::size_t depth, + std::span parents = {}) { const auto type = sourceName(decodeText(irSymbolPieces(symbolTable, fact.type))); std::ostringstream output; - output << type << '('; + output << type; + if (!parents.empty()) { + output << " extend "; + for (std::size_t index = 0; index < parents.size(); ++index) { + if (index != 0) + output << ", "; + output << sourceName( + decodeText(irSymbolPieces(symbolTable, parents[index]))); + } + } + output << '('; if (!fact.fields.empty()) { output << '\n'; for (std::size_t index = 0; index < fact.fields.size(); ++index) { @@ -284,7 +295,8 @@ void sync(const std::filesystem::path &path, std::span facts, std::span symbolTable, const VmTextDecoder &decodeText, - const VmFactPtr &emptySchema) { + const VmFactPtr &emptySchema, + const FactParentLookup &parentsOf) { if (path.empty() || (path.extension() != ".fx" && path.extension() != ".csv")) throw IrError("fact persistence requires a non-empty .fx or .csv path"); @@ -299,7 +311,11 @@ void sync(const std::filesystem::path &path, for (const auto &fact : facts) { if (!fact) throw IrError("fact database contains an invalid retained fact"); - source << '\n' << factText(*fact, symbolTable, decodeText, 0, 0) << '\n'; + const auto parents = parentsOf ? parentsOf(fact->type) + : std::vector{}; + source << '\n' + << factText(*fact, symbolTable, decodeText, 0, 0, parents) + << '\n'; } content = source.str(); } diff --git a/src/form/libs/Db.h b/src/form/libs/Db.h index 2c4ce56..9470422 100644 --- a/src/form/libs/Db.h +++ b/src/form/libs/Db.h @@ -3,15 +3,20 @@ #include "form/RegisterVm.h" #include +#include namespace Felidae::Form::Db { +using FactParentLookup = + std::function(IrSymbolRef type)>; + // Internal automatic-persistence helper. Rewrites one database from immutable // VM fact snapshots; it has no source-language builtin. void sync(const std::filesystem::path &path, std::span facts, std::span symbolTable, const VmTextDecoder &decodeText, - const VmFactPtr &emptySchema = {}); + const VmFactPtr &emptySchema = {}, + const FactParentLookup &parentsOf = {}); } // namespace Felidae::Form::Db diff --git a/tests/FelidaeIrTest.cpp b/tests/FelidaeIrTest.cpp index a87aa82..8a0204a 100644 --- a/tests/FelidaeIrTest.cpp +++ b/tests/FelidaeIrTest.cpp @@ -212,6 +212,7 @@ double executeKeyedEquality(bool facts) { if (facts) { program.words.insert(program.words.end(), {static_cast(IrOpcode::MakeFact), + 0, 0, 0, static_cast(IrOpcode::SetField), @@ -225,6 +226,7 @@ double executeKeyedEquality(bool facts) { static_cast(IrOpcode::MakeFact), 1, 0, + 0, static_cast(IrOpcode::SetField), 1, 2, @@ -264,11 +266,41 @@ int main() { assert(rejects([&] { (void)unsupportedRuntime.resolveSymbol(1); })); assert(rejects( [&] { unsupportedRuntime.retainFact(std::make_shared()); })); + assert(rejects([&] { + const std::array source{1}; + unsupportedRuntime.retainPersistentFact(std::make_shared(), + source); + })); assert(rejects([&] { unsupportedRuntime.mutateFact(std::make_shared(), 1, 1.0); })); assert(rejects([&] { unsupportedRuntime.registerFactType(1, {}); })); + // Fact averages use an extended accumulator, so two individually finite + // large values do not overflow merely while being averaged. A sum whose + // final double result is genuinely non-finite is rejected. + { + FelidaeKnowledgeRuntime aggregateRuntime; + IrModule module; + module.symbolTable = {{1}, {2}}; + aggregateRuntime.installIrModule(module); + const auto type = aggregateRuntime.resolveSymbol(1); + const auto field = aggregateRuntime.resolveSymbol(2); + aggregateRuntime.registerFactType(type, {}); + const auto makeLarge = [&] { + auto fact = std::make_shared(); + fact->type = type; + fact->fields = {{field, std::numeric_limits::max()}}; + return aggregateRuntime.retainFact(fact); + }; + const std::array facts{makeLarge(), makeLarge()}; + const PieceSequence fieldPieces{2}; + assert(aggregateRuntime.aggregateFacts(facts, fieldPieces, 1) == + std::numeric_limits::max()); + assert(rejects( + [&] { (void)aggregateRuntime.aggregateFacts(facts, fieldPieces, 0); })); + } + VmFactStore hierarchy; hierarchy.registerType(1, {}); hierarchy.registerType(2, {1}); @@ -296,6 +328,24 @@ int main() { assert((hierarchy.hierarchyProof(3, 1) == std::vector{3, 2, 1})); assert((hierarchy.commonAncestors(2, 3) == std::vector{1, 2})); assert((hierarchy.leastCommonAncestors(2, 3) == std::vector{2})); + + VmFactStore diamond; + diamond.registerType(1, {}); + diamond.registerType(2, {1}); + diamond.registerType(3, {1}); + diamond.registerType(4, {3, 2}); + diamond.registerType(5, {2}); + assert((diamond.hierarchyProofs(4, 1) == + std::vector>{{4, 2, 1}, {4, 3, 1}})); + const auto evidence = diamond.commonAncestorEvidence(4, 5); + assert(evidence.size() == 2); + assert(evidence[0].ancestor == 1); + assert(evidence[0].leftProofs.size() == 2); + assert(evidence[0].leftDistance == 2 && evidence[0].rightDistance == 2); + assert(evidence[1].ancestor == 2); + assert((evidence[1].leftProofs == + std::vector>{{4, 2}})); + assert(evidence[1].leftDistance == 1 && evidence[1].rightDistance == 1); assert((hierarchy.mostGeneralCommonAncestors(2, 3) == std::vector{1})); // Prime the per-type closure before adding type 5. Registering hierarchy diff --git a/tests/FormDbCsvTest.cpp b/tests/FormDbCsvTest.cpp index f6b3861..0aca7ea 100644 --- a/tests/FormDbCsvTest.cpp +++ b/tests/FormDbCsvTest.cpp @@ -73,6 +73,16 @@ VmFactPtr makeFact(IrSymbolRef type, return fact; } +void persistThroughDml(FelidaeKnowledgeRuntime &runtime, + const VmArrayPtr &rows) { + assert(rows && !rows->values.empty()); + const auto fact = std::get(rows->values.front()); + assert(fact && !fact->fields.empty()); + auto unchanged = std::make_shared(); + unchanged->entries.push_back(fact->fields.front()); + (void)runtime.updateFacts(std::array{fact}, unchanged); +} + } // namespace int main() { @@ -159,7 +169,7 @@ int main() { codec.decode, codec.encode); const std::vector names{ "Catalog", "title", "confidence", "category", - "mode", "query", "case", "direction", + "type", "query", "case", "direction", "includeSelf", "minimum", "maximum", "tolerance", "Publication", "Book", "Magazine"}; IrModule module; @@ -241,8 +251,7 @@ int main() { const auto importedArray = std::get(imported); assert(importedArray && importedArray->values.size() == 3); - const auto saved = runtime.syncDatabase(sourcePieces); - assert(saved == 1.0); + persistThroughDml(runtime, importedArray); assert(std::filesystem::exists(path)); const auto writtenText = readFile(path); @@ -296,8 +305,8 @@ int main() { assert(std::get(schoolsImported)->values.size() == 2); assert(std::get(teachersImported)->values.size() == 3); - runtime.syncDatabase(schoolsSource); - runtime.syncDatabase(teachersSource); + persistThroughDml(runtime, std::get(schoolsImported)); + persistThroughDml(runtime, std::get(teachersImported)); const auto schoolsRows = Form::Csv::parse(readFile(schoolsPath)); const auto teachersRows = Form::Csv::parse(readFile(teachersPath)); @@ -460,6 +469,10 @@ int main() { runtime.registerFactType(/*type=*/1, /*parents=*/{}); auto values = std::make_shared(); values->entries.emplace_back(2, VmText{codec.encode("North")}); + const auto emptySource = codec.encode(""); + assert(rejects( + [&] { (void)runtime.insertFact(codec.encode("School"), values, + emptySource); })); const auto invalidSource = codec.encode((outDir / "insert.txt").string()); assert(rejects( [&] { (void)runtime.insertFact(codec.encode("School"), values, diff --git a/tests/MixfixStateModelTest.cpp b/tests/MixfixStateModelTest.cpp index 6e044c6..50ca090 100644 --- a/tests/MixfixStateModelTest.cpp +++ b/tests/MixfixStateModelTest.cpp @@ -427,6 +427,8 @@ int main() { runtimeGruConfiguration, {{RuntimeOutputTokenKind::InputReference, 0}}); RuntimeContext runtimeGruContext; runtimeGruContext.executionState = runtimeGru.createExecutionState(); + const std::vector runtimeSymbols{{42}}; + runtimeGruContext.symbolTable = &runtimeSymbols; const VmValue runtimeText = VmText{{101, 102, 103}}; assert(std::get( runtimeGru.evaluate(RuntimeOperation{static_cast( @@ -434,13 +436,13 @@ int main() { {&runtimeText, 1}, runtimeGruContext)) .pieces == PieceSequence({101, 102, 103})); auto runtimeFact = std::make_shared(); - runtimeFact->type = 42; + runtimeFact->type = 1; const VmValue runtimeFactValue = runtimeFact; assert(std::get( runtimeGru.evaluate(RuntimeOperation{static_cast( SemanticOperationId::SelectFact)}, {&runtimeFactValue, 1}, runtimeGruContext)) - ->type == 42); + ->type == 1); GruRuntimeStateModel softRuntimeGru( runtimeGruConfiguration, {{RuntimeOutputTokenKind::DegreeMilli, 725}}); RuntimeContext softRuntimeContext; @@ -451,6 +453,15 @@ int main() { SemanticOperationId::EvaluateDegree)}, {°reeInput, 1}, softRuntimeContext); assert(std::get(softResult).value == 0.725); + RuntimeContext suggestContext; + suggestContext.executionState = runtimeGru.createExecutionState(); + suggestContext.symbolTable = &runtimeSymbols; + const auto suggested = runtimeGru.evaluate( + RuntimeOperation{static_cast( + SemanticOperationId::Suggest)}, + {&runtimeFactValue, 1}, suggestContext); + assert(std::holds_alternative(suggested)); + assert(std::isfinite(std::get(suggested))); // Production artifacts are genuine TorchScript modules. Native training // checkpoints remain separate and must not load through the inference @@ -549,6 +560,7 @@ int main() { identityTeacher.operationId = static_cast(SemanticOperationId::Identity); identityTeacher.inputKinds = {RuntimeValueKind::Number}; + identityTeacher.inputValues = {runtimeValueEncoding(VmValue{42.0}, {})}; identityTeacher.targetKind = RuntimeTrainingTargetKind::InputReference; identityTeacher.targetValue = 0; verifyRuntimeTrainingRecord(identityTeacher); @@ -556,17 +568,31 @@ int main() { serializedTeacher.factTypes = {{10, 11}}; serializedTeacher.factTypeCounts = {{{10, 11}, 2}}; serializedTeacher.hierarchyEdges = {{{10, 11}, {12}}}; + RuntimeTrainingRecord scoreTeacher; + scoreTeacher.operationId = + static_cast(SemanticOperationId::Suggest); + scoreTeacher.inputKinds = {RuntimeValueKind::Number}; + scoreTeacher.inputValues = {runtimeValueEncoding(VmValue{3.432}, {})}; + assert(scoreTeacher.inputValues.front() != + runtimeValueEncoding(VmValue{-2.302}, {})); + scoreTeacher.targetKind = RuntimeTrainingTargetKind::Score; + scoreTeacher.targetScore = -212.421; + verifyRuntimeTrainingRecord(scoreTeacher); const auto runtimeDataset = std::filesystem::path(FELIDAE_MODEL_TEST_OUTPUT_DIR) / "runtime-sequence-roundtrip.jsonl"; - writeRuntimeTrainingDataset(runtimeDataset, {&serializedTeacher, 1}); + const std::array runtimeTeachers{ + serializedTeacher, scoreTeacher}; + writeRuntimeTrainingDataset(runtimeDataset, runtimeTeachers); const auto loadedTeachers = loadRuntimeTrainingDataset(runtimeDataset); - assert(loadedTeachers.size() == 1); + assert(loadedTeachers.size() == 2); assert(loadedTeachers.front().factTypes == serializedTeacher.factTypes); assert(loadedTeachers.front().factTypeCounts == serializedTeacher.factTypeCounts); assert(loadedTeachers.front().hierarchyEdges == serializedTeacher.hierarchyEdges); + assert(loadedTeachers[1].targetKind == RuntimeTrainingTargetKind::Score); + assert(loadedTeachers[1].targetScore == -212.421); std::filesystem::remove(runtimeDataset); auto invalidTeacher = identityTeacher; invalidTeacher.operationId = 0xffffu; @@ -679,6 +705,7 @@ int main() { static_cast(IrOpcode::MakeFact), 0, 0, + 0, static_cast(IrOpcode::LoadConst), 1, 0, @@ -691,6 +718,9 @@ int main() { 0, static_cast(IrOpcode::End), }; + auto invalidFactSource = factProgram; + invalidFactSource.words[3] = 1; + assert(rejects([&] { IrVerifier::verify(invalidFactSource); })); const auto factValue = executeDirect(factProgram, noRuntime); const auto fact = std::get(factValue); assert(fact->type == 50 && fact->fields.size() == 1); @@ -860,6 +890,7 @@ int main() { static_cast(IrOpcode::MakeFact), 0, 0, + 0, static_cast(IrOpcode::SemanticEval), 1, static_cast(SemanticOperationId::Identity), diff --git a/tests/SentencePieceModelTest.cpp b/tests/SentencePieceModelTest.cpp index f18604d..5cee785 100644 --- a/tests/SentencePieceModelTest.cpp +++ b/tests/SentencePieceModelTest.cpp @@ -178,10 +178,10 @@ int main() { } const Felidae::IntegerTokenList expressionTokens( - model, "# ignored\n[\"value\", café, (true)]"); + model, "# ignored\n[\"value\", café, (1.0)]"); Felidae::IntegerParser integerParser(expressionTokens); const auto expression = integerParser.parseExpressionText(); - assert(expression->debug() == "[\"value\", café, true]"); + assert(expression->debug() == "[\"value\", café, 1]"); assert(integerParser.metrics().sourceEncodeCount == 2); assert(integerParser.metrics().tokenCount == expressionTokens.entries().size()); assert(integerParser.metrics().iterations > 0); @@ -306,14 +306,14 @@ int main() { assert(decodedQuery && decodedQuery->value == queryText); const Felidae::IntegerTokenList conditionalTokens( - model, "choose(value: number) =>\n if value > 0 then\n return (result: true)\n else\n return (result: false)\n"); + model, "choose(value: number) =>\n if value > 0 then\n return (result: 1.0)\n else\n return (result: 0.0)\n"); Felidae::IntegerParser conditionalParser(conditionalTokens); const auto conditionalProgram = conditionalParser.parseProgram(); assert(conditionalProgram.clauses.size() == 1); assert(!conditionalProgram.clauses.front()->body.empty()); const Felidae::IntegerTokenList fallbackTokens( - model, "choose() =>\n return (result: true)\nelse\n return (result: false)\n"); + model, "choose() =>\n return (result: 1.0)\nelse\n return (result: 0.0)\n"); Felidae::IntegerParser fallbackParser(fallbackTokens); const auto fallbackProgram = fallbackParser.parseProgram(); assert(fallbackProgram.clauses.size() == 1); @@ -382,9 +382,9 @@ int main() { const Felidae::IntegerTokenList sameAnchorTokens(model, "@mixfix(pattern: \"plan {name: string} using {strategy: string} with {budget: number}\")\n" "longPlan() => return (value: name)\n" - "@mixfix(pattern: \"plan {value: number} using {enabled: bool}\")\n" + "@mixfix(pattern: \"plan {value: number} using {enabled: number}\")\n" "shortPlan() => return (value: value)\n" - "main() => return (long: plan \"x\" using \"y\" with 1, short: plan 7 using true)\n"); + "main() => return (long: plan \"x\" using \"y\" with 1, short: plan 7 using 1.0)\n"); Felidae::IntegerParser sameAnchorParser(sameAnchorTokens, sameAnchorOperators); const auto sameAnchorProgram = sameAnchorParser.parseProgram(); assert(sameAnchorProgram.clauses.size() == 3); diff --git a/tests/SentencePiecePipelineTest.cpp b/tests/SentencePiecePipelineTest.cpp index 1a8649e..1fbbe6a 100644 --- a/tests/SentencePiecePipelineTest.cpp +++ b/tests/SentencePiecePipelineTest.cpp @@ -93,6 +93,13 @@ int main() { display.symbolDecoder = [](Felidae::IrSymbolRef symbol) { return Felidae::symbolNameForId(symbol); }; + const Felidae::VmTextEncoder textEncoder = [](std::string_view text) { + std::vector encoded; + assert(Felidae::felidaeSentencePieceModel() + .Encode(std::string(text), &encoded) + .ok()); + return Felidae::PieceSequence(encoded.begin(), encoded.end()); + }; const auto displayModuleValue = [&](const Felidae::IrModule &module, const Felidae::VmValue &value) { const auto verified = Felidae::verifyIrModule(Felidae::IrModule(module)); @@ -567,7 +574,7 @@ int main() { // explicit schema declaration. They remain typed facts after a binary // round-trip rather than being mis-lowered as an unknown call. const auto adHocFactModule = Felidae::compileProgramTextToIr( - "main() => return Plan(name: \"procedure\", enabled: true)\n"); + "main() => return Plan(name: \"procedure\", enabled: 1.0)\n"); const auto adHocFact = std::get(executeModule(adHocFactModule)); assert(adHocFact && adHocFact->fields.size() == 2); @@ -754,8 +761,8 @@ int main() { // guarding branch. const auto shortCircuitModule = Felidae::compileProgramTextToIr( "explode(divisor: number) => return 1 / divisor.\n" - "main() => return (both: false and explode(divisor: 0), " - "either: true or explode(divisor: 0)).\n"); + "main() => return (both: 0.0 and explode(divisor: 0), " + "either: 1.0 or explode(divisor: 0)).\n"); Felidae::FelidaeKnowledgeRuntime shortCircuitRuntime; const auto shortCircuitResult = executeModuleDirect(shortCircuitModule, shortCircuitRuntime); @@ -809,14 +816,18 @@ int main() { " alternatives := School.where(city: \"MYS\").OrWhere(name: \"Lake\")\n" " projected := School.select(fields: [\"name\", \"city\"], match: {active: 1.0})\n" " projected_limited := School.select(fields: [\"name\"], match: {active: 1.0}).limit(records: 1)\n" - " joined := School.leftJoin(type: Teacher, left: \"id\", right: \"school_id\")\n" + " inner_joined := School.join(type: Teacher, left: \"id\", right: \"school_id\")\n" + " joined := School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"left\")\n" + " right_joined := School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"right\")\n" + " outer_joined := School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"outer\")\n" " joined_limited := School.join(type: Teacher, left: \"id\", right: \"school_id\").limit(records: 2)\n" " none := School.all().limit(records: 0)\n" " inserted := School.insert(values: {id: 4, name: \"Hill\", city: \"BLR\", students: 100, active: 1.0})\n" " updated := School.where(id: 2).AndWhere(city: \"MYS\").update(values: {active: 1.0})\n" " deleted := School.where(id: 3).delete()\n" " return (limited: count(data: limited), all_limited: count(data: all_limited), alternatives: count(data: alternatives), " - "projected: projected, projected_limited: count(data: projected_limited), joined: count(data: joined), " + "projected: projected, projected_limited: count(data: projected_limited), inner_joined: count(data: inner_joined), joined: count(data: joined), " + "right_joined: count(data: right_joined), outer_joined: count(data: outer_joined), " "joined_limited: count(data: joined_limited), none: count(data: none), inserted: inserted, " "updated: count(data: updated), deleted: deleted, remaining: School.count(), " "total: School.sum(field: \"students\"), average: School.average(field: \"students\"))\n" @@ -828,14 +839,128 @@ int main() { assert(factDmlResult.find("all_limited: 2") != std::string::npos); assert(factDmlResult.find("alternatives: 2") != std::string::npos); assert(factDmlResult.find("projected_limited: 1.0") != std::string::npos); + assert(factDmlResult.find("inner_joined: 1.0") != std::string::npos); assert(factDmlResult.find("joined: 3") != std::string::npos); - assert(factDmlResult.find("joined_limited: 2") != std::string::npos); + assert(factDmlResult.find("right_joined: 2") != std::string::npos); + assert(factDmlResult.find("outer_joined: 4") != std::string::npos); + assert(factDmlResult.find("joined_limited: 1.0") != std::string::npos); assert(factDmlResult.find("none: 0.0") != std::string::npos); assert(factDmlResult.find("updated: 1.0") != std::string::npos); assert(factDmlResult.find("deleted: 1.0") != std::string::npos); assert(factDmlResult.find("remaining: 3") != std::string::npos); assert(factDmlResult.find("total: 800") != std::string::npos); + // A fact-only .fx import is compile-time DDL. Its rows enter ordinary + // MakeFact IR with source ownership, so the existing DML transactions + // persist them without a runtime source parser or public db.sync call. + const auto ownedDatabase = testOutputDirectory / "owned-schools.fx"; + const auto ownedProgram = testOutputDirectory / "owned-schools-main.fx"; + { + std::ofstream out(ownedDatabase, std::ios::trunc); + out << "Entity(id: 0, name: \"root\", students: 0)\n" + "School extend Entity(id: 1, name: \"North\", students: 420)\n" + "School extend Entity(id: 2, name: \"West\", students: 280)\n"; + } + { + std::ofstream out(ownedProgram, std::ios::trunc); + out << "import \"owned-schools.fx\"\n" + "main() =>\n" + " updated := School.where(id: 1).update(values: {students: 425})\n" + " inserted := School.insert(values: {id: 3, name: \"Hill\", students: 100})\n" + " deleted := School.where(id: 2).delete()\n" + " return (updated: count(data: updated), inserted: inserted, deleted: deleted, remaining: School.count())\n" + "end\n"; + } + const auto ownedModule = Felidae::compileProgramFileToIr(ownedProgram); + Felidae::IrWord ownedSource = 0; + std::size_t ownedFactCount = 0; + for (std::size_t pc = 0; pc < ownedModule.ir.words.size(); + pc += Felidae::irInstructionWidth(ownedModule.ir, pc)) { + if (ownedModule.ir.words[pc] == + static_cast(Felidae::IrOpcode::MakeFact) && + ownedModule.ir.words[pc + 3] != 0) { + if (ownedSource == 0) + ownedSource = ownedModule.ir.words[pc + 3]; + assert(ownedModule.ir.words[pc + 3] == ownedSource); + ++ownedFactCount; + } + } + assert(ownedFactCount == 3); + Felidae::FelidaeKnowledgeRuntime ownedRuntime( + nullptr, 1024, 256, {}, nullptr, display.textDecoder, textEncoder); + const auto ownedResult = displayModuleValue( + ownedModule, executeModuleDirect(ownedModule, ownedRuntime)); + assert(ownedResult.find("updated: 1.0") != std::string::npos); + assert(ownedResult.find("deleted: 1.0") != std::string::npos); + assert(ownedResult.find("remaining: 2") != std::string::npos); + const auto persistedDatabase = Felidae::readSourceFile(ownedDatabase); + assert(persistedDatabase.find("students: 425.0") != std::string::npos); + assert(persistedDatabase.find("Hill") != std::string::npos); + assert(persistedDatabase.find("West") == std::string::npos); + assert(persistedDatabase.find("School extend Entity") != std::string::npos); + // The transaction writer's .fx output remains valid compiler input and + // retains hierarchy assignability after a fresh compile/runtime boundary. + { + std::ofstream out(ownedProgram, std::ios::trunc); + out << "import \"owned-schools.fx\"\n" + "main() => return (entities: Entity.count(), schools: School.count())\n" + "end\n"; + } + const auto reloadedModule = Felidae::compileProgramFileToIr(ownedProgram); + Felidae::FelidaeKnowledgeRuntime reloadedRuntime( + nullptr, 1024, 256, {}, nullptr, display.textDecoder, textEncoder); + const auto reloadedResult = displayModuleValue( + reloadedModule, executeModuleDirect(reloadedModule, reloadedRuntime)); + assert(reloadedResult == "{entities: 3, schools: 2}"); + + const auto invalidDatabase = testOutputDirectory / "invalid-database.fx"; + const auto invalidProgram = testOutputDirectory / "invalid-database-main.fx"; + { + std::ofstream out(invalidDatabase, std::ios::trunc); + out << "helper() => return 1\nend\n"; + } + { + std::ofstream out(invalidProgram, std::ios::trunc); + out << "import \"invalid-database.fx\"\nmain() => return 0.0\nend\n"; + } + bool nonFactDatabaseRejected = false; + try { + (void)Felidae::compileProgramFileToIr(invalidProgram); + } catch (const Felidae::IntegerParserError &) { + nonFactDatabaseRejected = true; + } + assert(nonFactDatabaseRejected); + + const auto cyclicA = testOutputDirectory / "cyclic-a.fx"; + const auto cyclicB = testOutputDirectory / "cyclic-b.fx"; + { + std::ofstream out(cyclicA, std::ios::trunc); + out << "import \"cyclic-b.fx\"\nA(id: 1)\n"; + } + { + std::ofstream out(cyclicB, std::ios::trunc); + out << "import \"cyclic-a.fx\"\nB(id: 1)\n"; + } + { + std::ofstream out(invalidProgram, std::ios::trunc); + out << "import \"cyclic-a.fx\"\nmain() => return 0.0\nend\n"; + } + bool cyclicDatabaseRejected = false; + try { + (void)Felidae::compileProgramFileToIr(invalidProgram); + } catch (const Felidae::IntegerParserError &) { + cyclicDatabaseRejected = true; + } + assert(cyclicDatabaseRejected); + + removeTemporary(ownedProgram); + removeTemporary(ownedDatabase); + removeTemporary(ownedDatabase.string() + ".lock"); + removeTemporary(invalidProgram); + removeTemporary(invalidDatabase); + removeTemporary(cyclicA); + removeTemporary(cyclicB); + // Mutations are intentionally conditional: a direct type-wide update or // delete is rejected before IR generation. Joins likewise require both // key fields, preventing an accidental Cartesian operation. @@ -856,6 +981,14 @@ int main() { assert(rejectsFactSource( "School(id: 1)\nTeacher(school_id: 1)\n" "main() => return School.join(type: Teacher)\nend\n")); + assert(rejectsFactSource( + "School(id: 1)\nTeacher(school_id: 1)\n" + "main() => return School.join(type: Teacher, left: \"id\", " + "right: \"school_id\", kind: \"cross\")\nend\n")); + assert(rejectsFactSource( + "School(id: 1)\nTeacher(school_id: 1)\n" + "main() => return School.leftJoin(type: Teacher, left: \"id\", " + "right: \"school_id\")\nend\n")); const auto rejectsLimitAtRuntime = [](std::string records) { const auto module = Felidae::compileProgramTextToIr( @@ -880,12 +1013,12 @@ int main() { "Catalog(title: \"beta guide\", confidence: 0.74, category: Magazine)\n" "Catalog(title: \"Reference\", confidence: 0.40, category: Publication)\n" "main() =>\n" - " exact := Catalog.search(field: \"title\", query: \"alpha guide\", mode: \"exact\", case: \"insensitive\")\n" - " liked := Catalog.search(field: \"title\", query: \"%guide\", mode: \"like\", case: \"insensitive\")\n" - " regexed := Catalog.search(field: \"title\", query: \"^[ab].*guide$\", mode: \"regex\", case: \"insensitive\")\n" - " descendants := Catalog.search(field: \"category\", query: Publication, mode: \"hierarchy\", direction: \"descendants\", includeSelf: 0.0)\n" - " ranged := Catalog.search(field: \"confidence\", mode: \"degree\", minimum: 0.70, maximum: 0.90)\n" - " close := Catalog.search(field: \"confidence\", query: 0.80, tolerance: 0.08, mode: \"degree\")\n" + " exact := Catalog.search(field: \"title\", query: \"alpha guide\", type: \"exact\", case: \"insensitive\")\n" + " liked := Catalog.search(field: \"title\", query: \"%guide\", type: \"like\", case: \"insensitive\")\n" + " regexed := Catalog.search(field: \"title\", query: \"^[ab].*guide$\", type: \"regex\", case: \"insensitive\")\n" + " descendants := Catalog.search(field: \"category\", query: Publication, type: \"hierarchy\", direction: \"descendants\", includeSelf: 0.0)\n" + " ranged := Catalog.search(field: \"confidence\", type: \"degree\", minimum: 0.70, maximum: 0.90)\n" + " close := Catalog.search(field: \"confidence\", query: 0.80, tolerance: 0.08, type: \"degree\")\n" " return (exact: count(data: exact), liked: count(data: liked), regexed: count(data: regexed), descendants: count(data: descendants), ranged: count(data: ranged), close: count(data: close))\n" "end\n"); Felidae::FelidaeKnowledgeRuntime factSearchRuntime; @@ -906,6 +1039,32 @@ int main() { repeatedFieldsRuntime)) == "[[warm, primary], [cool, primary]]"); + // Classes are compiler-only schemas over the existing fact type table. + // Both the class and its nested methods require explicit end boundaries; + // RegisterVm still receives only ordinary fact/procedure IR. + const auto classModule = Felidae::compileProgramTextToIr( + "class Animal\n" + " name: string\n" + " index(name)\n" + "end\n" + "class Human extend Animal\n" + " age: number\n" + " index(name, age)\n" + " eligible(minimumAge: number) =>\n" + " where age >= minimumAge\n" + " return 1.0\n" + " else\n" + " return 0.0\n" + " end\n" + "end\n" + "Human(name: \"Ada\", age: 32)\n" + "main() => return Human.all()\n" + "end\n"); + Felidae::FelidaeKnowledgeRuntime classRuntime; + assert(displayModuleValue(classModule, + executeModuleDirect(classModule, classRuntime)) == + "[{name: Ada, age: 32}]"); + // Real source semantic intrinsic -> structured compiler IR // operation ID -> typed runtime-model result. No tokenizer or symbol ID // crosses the semantic execution boundary. @@ -928,6 +1087,26 @@ int main() { Felidae::FelidaeKnowledgeRuntime semanticRuntime(&identityModel); assert(std::get(Felidae::RegisterVm{}.executeMain( semanticIr, semanticRuntime)) == 42.0); + + const auto suggestModule = Felidae::compileProgramTextToIr( + "Candidate(name: \"Mammal\")\n" + "main() => return ssm.suggest(input: Candidate.all())\n" + "end\n"); + class SuggestRuntimeModel final : public Felidae::RuntimeStateModel { + public: + Felidae::VmValue evaluate(const Felidae::RuntimeOperation &operation, + std::span inputs, + Felidae::RuntimeContext &) override { + assert(operation.id == static_cast( + Felidae::SemanticOperationId::Suggest)); + assert(inputs.size() == 1); + return -212.421; + } + } suggestModel; + Felidae::FelidaeKnowledgeRuntime suggestRuntime(&suggestModel); + assert(std::get(Felidae::RegisterVm{}.executeMain( + Felidae::verifyIrModule(Felidae::IrModule(suggestModule)), + suggestRuntime)) == -212.421); const auto executeBinaryModule = [&](const Felidae::IrModule &candidate) { const auto path = testOutputDirectory / "felidae_pipeline_feature_roundtrip.bin"; @@ -1069,7 +1248,7 @@ int main() { assert(comparisonIr); assert(std::get(executeIrDirect(*comparisonIr, noRuntime)) == 1.0); const auto logicIr = - Felidae::tryCompileExpressionTextToIr("not false and true"); + Felidae::tryCompileExpressionTextToIr("not 0.0 and 1.0"); assert(logicIr); assert(std::get(executeIrDirect(*logicIr, noRuntime)) == 1.0); const auto moduloIr = Felidae::tryCompileExpressionTextToIr("17 % 5"); @@ -1097,7 +1276,7 @@ int main() { assert(array && array->values.size() == 3 && std::get(array->values[2]) == 3.0); const auto mapIr = - Felidae::tryCompileExpressionTextToIr("{answer: 42, enabled: true}"); + Felidae::tryCompileExpressionTextToIr("{answer: 42, enabled: 1.0}"); assert(mapIr); const auto map = std::get(executeIrDirect(*mapIr, noRuntime)); diff --git a/tools/BuildRuntimeTrainingDataset.cpp b/tools/BuildRuntimeTrainingDataset.cpp index 0951421..2ab7580 100644 --- a/tools/BuildRuntimeTrainingDataset.cpp +++ b/tools/BuildRuntimeTrainingDataset.cpp @@ -20,6 +20,7 @@ makeIdentityTeacher(const VmValue &value, const VmKnowledgeSnapshot &knowledge, record.operationId = static_cast(SemanticOperationId::Identity); record.inputKinds = {runtimeValueKind(value)}; + record.inputValues = {runtimeValueEncoding(value, symbolTable)}; auto encoded = runtimeKnowledgePieces(knowledge, symbolTable); record.factTypes = std::move(encoded.factTypes); record.factTypeCounts = std::move(encoded.factTypeCounts); diff --git a/tools/ExtractMixfixDataset.cpp b/tools/ExtractMixfixDataset.cpp index aec0e1f..7d40619 100644 --- a/tools/ExtractMixfixDataset.cpp +++ b/tools/ExtractMixfixDataset.cpp @@ -398,7 +398,7 @@ main() => for (std::size_t seed = 1; seed <= 24; ++seed) { result.emplace_back("generated-plan-" + std::to_string(seed), std::string(plan) + "plan " + std::to_string(seed * 3) + - " using " + (seed % 2 == 0 ? "true\n" : "false\n")); + " using " + (seed % 2 == 0 ? "1.0\n" : "0.0\n")); } for (std::size_t seed = 1; seed <= 16; ++seed) { std::string expression = std::to_string(seed + 7); @@ -426,7 +426,7 @@ main() => // abstention teachers, not fabricated calls to either implementation. result.emplace_back("generated-typed-abstain-" + std::to_string(seed), std::string(typed) + "classify candidate using " + - (seed % 2 == 0 ? "true\n" : "false\n")); + (seed % 2 == 0 ? "1.0\n" : "0.0\n")); } return result; } diff --git a/tools/TrainRuntimeGru.cpp b/tools/TrainRuntimeGru.cpp index f7cfb07..8cf9f1f 100644 --- a/tools/TrainRuntimeGru.cpp +++ b/tools/TrainRuntimeGru.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -30,6 +31,8 @@ std::size_t targetFor(const RuntimeTrainingRecord &record, return token.kind == RuntimeOutputTokenKind::Nil; case RuntimeTrainingTargetKind::NumericTruth: return token.kind == RuntimeOutputTokenKind::NumericTruth; + case RuntimeTrainingTargetKind::Score: + return false; } return false; }; @@ -79,7 +82,9 @@ int Felidae::runRuntimeGruTraining(int argc, char **argv) { std::map> families; for (std::size_t index = 0; index < records.size(); ++index) { families[{records[index].operationId, records[index].inputKinds, - targetFor(records[index], vocabulary)}] + records[index].targetKind == RuntimeTrainingTargetKind::Score + ? vocabulary.size() + : targetFor(records[index], vocabulary)}] .push_back(index); } if (families.size() < 3) @@ -115,15 +120,27 @@ int Felidae::runRuntimeGruTraining(int argc, char **argv) { double totalLoss = 0.0; for (const auto index : training) { const auto &record = records[index]; - totalLoss += model.trainTeacherForced( - record, targetFor(record, vocabulary), rate); + totalLoss += record.targetKind == RuntimeTrainingTargetKind::Score + ? model.trainScore(record, rate) + : model.trainTeacherForced( + record, targetFor(record, vocabulary), rate); } std::size_t correct = 0; + std::size_t validationClassifications = 0; + std::size_t scoreCount = 0; + double scoreAbsoluteError = 0.0; std::map> bucketMetrics; for (const auto index : validation) { const auto &record = records[index]; + if (record.targetKind == RuntimeTrainingTargetKind::Score) { + scoreAbsoluteError += + std::abs(model.predictScore(record) - record.targetScore); + ++scoreCount; + continue; + } const auto target = targetFor(record, vocabulary); + ++validationClassifications; const auto predicted = model.predictTeacherToken(record); auto &metric = bucketMetrics[{record.operationId, target}]; ++metric.second; @@ -138,7 +155,12 @@ int Felidae::runRuntimeGruTraining(int argc, char **argv) { std::cout << "epoch=" << (epoch + 1) << " train_loss=" << (totalLoss / training.size()) << " validation_accuracy=" - << (static_cast(correct) / validation.size()) + << (validationClassifications + ? static_cast(correct) / + validationClassifications + : 0.0) + << " validation_score_mae=" + << (scoreCount ? scoreAbsoluteError / scoreCount : 0.0) << " seconds=" << epochSeconds << " train_samples_per_second=" << (epochSeconds > 0.0 ? static_cast(training.size()) / epochSeconds @@ -152,16 +174,31 @@ int Felidae::runRuntimeGruTraining(int argc, char **argv) { } } std::size_t testCorrect = 0; + std::size_t testClassifications = 0; + std::size_t testScores = 0; + double testScoreAbsoluteError = 0.0; for (const auto index : test) { const auto &record = records[index]; - testCorrect += - model.predictTeacherToken(record) == targetFor(record, vocabulary) - ? 1u - : 0u; + if (record.targetKind == RuntimeTrainingTargetKind::Score) { + testScoreAbsoluteError += + std::abs(model.predictScore(record) - record.targetScore); + ++testScores; + } else { + ++testClassifications; + testCorrect += + model.predictTeacherToken(record) == targetFor(record, vocabulary) + ? 1u + : 0u; + } } std::cout << "test_accuracy=" - << (static_cast(testCorrect) / test.size()) - << " correct=" << testCorrect << '/' << test.size() << "\n"; + << (testClassifications + ? static_cast(testCorrect) / testClassifications + : 0.0) + << " correct=" << testCorrect << '/' << testClassifications + << " test_score_mae=" + << (testScores ? testScoreAbsoluteError / testScores : 0.0) + << " score_records=" << testScores << "\n"; const std::filesystem::path output(argv[2]); std::filesystem::create_directories(output); model.saveCheckpoint(output / "runtime-gru.ckpt"); diff --git a/v2_examples/animal_fact_similarity_evidence.fx b/v2_examples/animal_fact_similarity_evidence.fx index f1fc3b6..635a231 100644 --- a/v2_examples/animal_fact_similarity_evidence.fx +++ b/v2_examples/animal_fact_similarity_evidence.fx @@ -109,7 +109,7 @@ compareMammals() => return AnimalSimilarityEvidence( left_type: type(left), right_type: type(right), - common_ancestor: lowestCommonAncestor(left, right), + common_ancestors: ancestors, score: score, ancestor_similarity: array.len(data: ancestors) > 0, property_similarity: score, diff --git a/v2_examples/deep_fact_reasoning_analysis.fx b/v2_examples/deep_fact_reasoning_analysis.fx index f7107a6..e8aa469 100644 --- a/v2_examples/deep_fact_reasoning_analysis.fx +++ b/v2_examples/deep_fact_reasoning_analysis.fx @@ -104,8 +104,8 @@ main() => confidence: 0.91 ) - tied_lineage := lowestCommonAncestor(left: tiger_female, right: cat_female) - broad_lineage := highestCommonAncestor(left: tiger_female, right: cat_female) + tied_lineage := commonAncestors(left: tiger_female, right: cat_female) + broad_lineage := tied_lineage tiger_cat_lineage := ancestorAnalysis(left: tiger_female, right: cat_female) tiger_dog_lineage := commonAncestors(left: tiger_male, right: dog_male) habitat_propagation := propagateFact( diff --git a/v2_examples/direct_ancestor_analysis.fx b/v2_examples/direct_ancestor_analysis.fx index 7c80d71..5434145 100644 --- a/v2_examples/direct_ancestor_analysis.fx +++ b/v2_examples/direct_ancestor_analysis.fx @@ -12,10 +12,6 @@ main() => right := Right(name: "right") common := commonAncestors(left: left, right: right) - lowest := lowestCommonAncestor(left: left, right: right) - highest := highestCommonAncestor(left: left, right: right) return ( - common: common, - lowest: lowest, - highest: highest + common: common ) diff --git a/v2_examples/fact_search_analysis.fx b/v2_examples/fact_search_analysis.fx index 67b20d0..8964ca5 100644 --- a/v2_examples/fact_search_analysis.fx +++ b/v2_examples/fact_search_analysis.fx @@ -12,19 +12,19 @@ main() => guides := Catalog.search( field: "title", query: "%guide", - mode: "like", + type: "like", case: "insensitive" ) related := Catalog.search( field: "category", query: Publication, - mode: "hierarchy", + type: "hierarchy", direction: "descendants", includeSelf: 0.0 ) confident := Catalog.search( field: "confidence", - mode: "degree", + type: "degree", minimum: 0.70, maximum: 0.90 ) diff --git a/v2_examples/fact_similarity_requires_ancestry.fx b/v2_examples/fact_similarity_requires_ancestry.fx index d630263..bbe7d44 100644 --- a/v2_examples/fact_similarity_requires_ancestry.fx +++ b/v2_examples/fact_similarity_requires_ancestry.fx @@ -23,6 +23,6 @@ main() => property_similarity: propertySimilarity, ancestor_similarity: 0.0, similarity: propertySimilarity, - common_ancestor: lowestCommonAncestor(cat, machine), + common_ancestors: ancestors, ancestor_evidence: ancestors ) diff --git a/v2_examples/felidae_language_tour.fx b/v2_examples/felidae_language_tour.fx index 1e0d4b3..1b911a1 100644 --- a/v2_examples/felidae_language_tour.fx +++ b/v2_examples/felidae_language_tour.fx @@ -77,13 +77,14 @@ aggregateExamples() => largest: School.max(field: "students") ) -# --- 6. Joins: join / leftJoin / rightJoin / OuterJoin ----------------------- +# --- 6. Joins --------------------------------------------------------------- # A join result is ephemeral: it never enters fact storage on its own, so # joining never inflates School.count() or Teacher.count(). Only an explicit -# .insert() persists anything. +# .insert() persists anything. join() is inner by default; kind selects an +# outer variant without creating parallel method names. joinExamples() => inner := School.join(type: Teacher, left: "id", right: "school_id") - left := School.leftJoin(type: Teacher, left: "id", right: "school_id") + left := School.join(type: Teacher, left: "id", right: "school_id", kind: "left") return (inner_count: count(data: inner), left_count: count(data: left)) # --- 7. DML: insert / update / delete ---------------------------------------- @@ -100,16 +101,13 @@ mutationExamples() => ) # --- 8. Ancestry reasoning --------------------------------------------------- -# commonAncestors/lowestCommonAncestor/highestCommonAncestor read the -# `extend` graph declared in section 1: Mammal and Reptile both resolve back -# to Animal without any fact-level relationship being declared between them. +# commonAncestors reads the `extend` graph declared in section 1. Selecting +# one candidate as contextually best belongs to the application or SSM. ancestryExamples() => cat := Mammal(name: "cat") lizard := Reptile(name: "lizard") return ( - common: commonAncestors(left: cat, right: lizard), - lowest: lowestCommonAncestor(left: cat, right: lizard), - highest: highestCommonAncestor(left: cat, right: lizard) + common: commonAncestors(left: cat, right: lizard) ) # --- 9. Mixfix syntax -------------------------------------------------------- diff --git a/v2_examples/fx_fact_database.fx b/v2_examples/fx_fact_database.fx new file mode 100644 index 0000000..3081006 --- /dev/null +++ b/v2_examples/fx_fact_database.fx @@ -0,0 +1,14 @@ +# A fact-only .fx file is DDL data linked by the compiler. Imported rows keep +# source ownership, so conditional insert/update/delete operations can persist +# them automatically. This example is read-only to keep the checked-in dataset +# deterministic; copy the database under build/ before experimenting with DML. +import "../datasets/examples/schools.fx" + +main() => + active := School.where(active: 1.0).limit(records: 100) + return ( + rows: active, + count: count(data: active), + students: School.sum(field: "students", match: {active: 1.0}) + ) +end diff --git a/v2_examples/mixfix_multi_ancestor_fact_analysis.fx b/v2_examples/mixfix_multi_ancestor_fact_analysis.fx index 37e43f3..4893ed9 100644 --- a/v2_examples/mixfix_multi_ancestor_fact_analysis.fx +++ b/v2_examples/mixfix_multi_ancestor_fact_analysis.fx @@ -76,7 +76,7 @@ buildSimilarityReport(left: Mammal, right: Mammal, context: string) => context: context, left_type: type(left), right_type: type(right), - common_ancestor: lowestCommonAncestor(left, right), + common_ancestors: ancestors, score: score, evidence: [ ancestorAnalysis(left: left, right: right), diff --git a/v2_examples/operator_expression_inventory.fx b/v2_examples/operator_expression_inventory.fx index 4e664a5..42df42b 100644 --- a/v2_examples/operator_expression_inventory.fx +++ b/v2_examples/operator_expression_inventory.fx @@ -22,7 +22,7 @@ main() => point := {x: 3, y: 4} record := {owner: {name: "Ava"}, scores: [10, 20, 30]} # lambda(...) is fact-query sugar over a declared fact type (see - # FactQueryNormalizer) -- there is no generic array-map lambda over an + # FactDmlLowerer) -- there is no generic array-map lambda over an # arbitrary array like record.scores, so indexing it directly here. first := array.get(data: record.scores, position: 0) piped := increment(value: first) diff --git a/vs-code-extension b/vs-code-extension index 1f0ee36..93a9437 160000 --- a/vs-code-extension +++ b/vs-code-extension @@ -1 +1 @@ -Subproject commit 1f0ee3669e1342582c128e60f05ea3f32c70c8ba +Subproject commit 93a943747f062bc8c681cc91394ea55fc244ab10 From dbddf94766a6f22c088feae139fe31012e64013c Mon Sep 17 00:00:00 2001 From: vishalkrishnaag Date: Fri, 11 Sep 2026 04:16:04 +0000 Subject: [PATCH 2/6] before rocks --- CMakeLists.txt | 112 +- README.md | 101 +- build.sh | 16 +- datasets/tokenizer/felidae-tokenizer-v1.jsonl | 6 +- datasets/vm/README.md | 30 +- docs_language.md | 89 +- intellij-idea-extension | 2 +- src/CompilerFrontend.cpp | 4 +- src/FelidaeIr.h | 6 +- src/IntegerParser.cpp | 58 +- src/IntegerParser.h | 1 + src/IntegerTokenList.cpp | 98 +- src/IntegerTokenList.h | 21 +- src/IrCodeGenerator.cpp | 94 +- src/VmMain.cpp | 39 +- src/form/BuiltinOperation.h | 2 - src/form/RegisterVm.cpp | 1478 ++++++++++++++--- src/form/RegisterVm.h | 116 +- src/form/RuntimeStateModel.cpp | 44 +- src/form/RuntimeTraining.cpp | 49 +- src/form/RuntimeTraining.h | 40 +- src/form/libs/ExecutionVectorMemory.cpp | 45 + src/form/libs/ExecutionVectorMemory.h | 26 + src/form/libs/FactStorageCodec.cpp | 438 +++++ src/form/libs/FactStorageCodec.h | 44 + src/form/libs/RocksDb.cpp | 145 ++ src/form/libs/RocksDb.h | 54 + tests/ExecutionVectorMemoryTest.cpp | 35 + tests/FelidaeIrTest.cpp | 60 +- tests/RocksDbTest.cpp | 489 ++++++ tests/SentencePieceModelTest.cpp | 52 +- tests/SentencePiecePipelineTest.cpp | 203 ++- tools/FactStoreBenchmark.cpp | 145 ++ tree-sitter-felidae | 2 +- v2_examples/array_object.fx | 8 + v2_examples/class_association_reasoning.fx | 43 + vim-extension | 2 +- vs-code-extension | 2 +- 38 files changed, 3715 insertions(+), 484 deletions(-) create mode 100644 src/form/libs/ExecutionVectorMemory.cpp create mode 100644 src/form/libs/ExecutionVectorMemory.h create mode 100644 src/form/libs/FactStorageCodec.cpp create mode 100644 src/form/libs/FactStorageCodec.h create mode 100644 src/form/libs/RocksDb.cpp create mode 100644 src/form/libs/RocksDb.h create mode 100644 tests/ExecutionVectorMemoryTest.cpp create mode 100644 tests/RocksDbTest.cpp create mode 100644 tools/FactStoreBenchmark.cpp create mode 100644 v2_examples/array_object.fx create mode 100644 v2_examples/class_association_reasoning.fx diff --git a/CMakeLists.txt b/CMakeLists.txt index 5c90d89..48a72d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,12 +46,60 @@ option(FELIDAE_ENABLE_LIBTORCH ${FELIDAE_LIBTORCH_DEFAULT}) option(FELIDAE_ENABLE_TRAINING "Build explicit compiler and VM C++ model-training commands" OFF) +option(FELIDAE_ENABLE_FAISS + "Retain execution-local SSM hidden vectors in real Faiss indexes" OFF) +if(FELIDAE_ENABLE_FAISS) + if(NOT FELIDAE_ENABLE_LIBTORCH) + message(FATAL_ERROR "FELIDAE_ENABLE_FAISS requires FELIDAE_ENABLE_LIBTORCH=ON") + endif() + find_package(OpenMP REQUIRED COMPONENTS CXX) + find_package(faiss CONFIG REQUIRED) + add_library(felidae_execution_vectors STATIC src/form/libs/ExecutionVectorMemory.cpp) + target_include_directories(felidae_execution_vectors PUBLIC src) + target_compile_features(felidae_execution_vectors PUBLIC cxx_std_20) + target_compile_definitions(felidae_execution_vectors INTERFACE FELIDAE_HAS_FAISS=1) + target_link_libraries(felidae_execution_vectors PRIVATE faiss) +endif() +if(ANDROID) + set(FELIDAE_ROCKSDB_DEFAULT OFF) +else() + set(FELIDAE_ROCKSDB_DEFAULT ON) +endif() +option(FELIDAE_ENABLE_ROCKSDB + "Enable the disk-backed ordered Felidae fact-store driver" + ${FELIDAE_ROCKSDB_DEFAULT}) if(FELIDAE_ENABLE_TRAINING AND NOT FELIDAE_ENABLE_LIBTORCH) message(FATAL_ERROR "FELIDAE_ENABLE_TRAINING requires FELIDAE_ENABLE_LIBTORCH=ON") endif() +if(FELIDAE_ENABLE_ROCKSDB) + find_package(PkgConfig QUIET) + if(PkgConfig_FOUND) + pkg_check_modules(FELIDAE_ROCKSDB QUIET IMPORTED_TARGET rocksdb) + endif() + if(TARGET PkgConfig::FELIDAE_ROCKSDB) + set(FELIDAE_ROCKSDB_TARGET PkgConfig::FELIDAE_ROCKSDB) + else() + find_path(FELIDAE_ROCKSDB_INCLUDE_DIR rocksdb/db.h) + find_library(FELIDAE_ROCKSDB_LIBRARY NAMES rocksdb) + if(FELIDAE_ROCKSDB_INCLUDE_DIR AND FELIDAE_ROCKSDB_LIBRARY) + add_library(felidae_rocksdb UNKNOWN IMPORTED) + set_target_properties(felidae_rocksdb PROPERTIES + IMPORTED_LOCATION "${FELIDAE_ROCKSDB_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${FELIDAE_ROCKSDB_INCLUDE_DIR}") + set(FELIDAE_ROCKSDB_TARGET felidae_rocksdb) + else() + message(FATAL_ERROR + "FELIDAE_ENABLE_ROCKSDB=ON requires RocksDB development files. " + "On Debian/Ubuntu install librocksdb-dev; on macOS install " + "rocksdb with Homebrew; or configure Android/unsupported " + "targets with -DFELIDAE_ENABLE_ROCKSDB=OFF.") + endif() + endif() +endif() + # Keep the lexical model native and reproducible: SentencePiece is pinned as a # git submodule instead of being found from an arbitrary system installation. set(SPM_BUILD_TEST OFF CACHE BOOL "" FORCE) @@ -375,14 +423,32 @@ add_library(felidae_form STATIC src/form/libs/Builtin.cpp src/form/libs/Csv.cpp src/form/libs/Db.cpp + src/form/libs/FactStorageCodec.cpp src/form/libs/Group.cpp src/form/libs/Json.cpp src/form/libs/Set.cpp) +if(FELIDAE_ENABLE_ROCKSDB) + target_sources(felidae_form PRIVATE src/form/libs/RocksDb.cpp) + target_compile_definitions(felidae_form PUBLIC FELIDAE_HAS_ROCKSDB=1) + target_link_libraries(felidae_form PRIVATE ${FELIDAE_ROCKSDB_TARGET}) +endif() target_include_directories(felidae_form PUBLIC src) target_link_libraries(felidae_form PRIVATE nlohmann_json::nlohmann_json) felidae_enable_static_analysis(felidae_form) felidae_enable_msvc_exceptions(felidae_form) +if(FELIDAE_ENABLE_ROCKSDB) + add_executable(felidae_fact_store_benchmark EXCLUDE_FROM_ALL + tools/FactStoreBenchmark.cpp) + target_link_libraries(felidae_fact_store_benchmark PRIVATE felidae_form) + target_compile_definitions(felidae_fact_store_benchmark PRIVATE + FELIDAE_BENCHMARK_OUTPUT_DIR="${CMAKE_BINARY_DIR}/benchmarks") + felidae_enable_static_analysis(felidae_fact_store_benchmark) + felidae_enable_msvc_exceptions(felidae_fact_store_benchmark) + set_target_properties(felidae_fact_store_benchmark PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() + if(TARGET felidae_mixfix_torch) target_link_libraries(felidae_mixfix_torch PRIVATE felidae_form) endif() @@ -406,6 +472,11 @@ set_target_properties(felidae_vm PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}" RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}") felidae_enable_static_analysis(felidae_vm) +if(FELIDAE_ENABLE_FAISS) + felidae_enable_msvc_exceptions(felidae_execution_vectors) + felidae_enable_static_analysis(felidae_execution_vectors) + target_link_libraries(felidae_vm PRIVATE felidae_execution_vectors) +endif() if(FELIDAE_ENABLE_LIBTORCH) # The daemon owns an optional runtime-only GRU. Form itself remains free @@ -584,6 +655,7 @@ if(FELIDAE_BUILD_TESTS) add_executable(felidae_sentencepiece_model_test tests/SentencePieceModelTest.cpp src/MixfixStateModel.cpp + src/IrCodeGenerator.cpp src/SentencePieceModel.cpp src/IntegerTokenList.cpp src/IntegerParser.cpp @@ -667,6 +739,17 @@ if(FELIDAE_BUILD_TESTS) tests/MixfixStateModelTest.cpp src/form/RuntimeStateModel.cpp) target_include_directories(felidae_mixfix_state_model_test PRIVATE src) + if(FELIDAE_ENABLE_FAISS) + target_link_libraries(felidae_mixfix_state_model_test PRIVATE felidae_execution_vectors) + add_executable(felidae_execution_vectors_test tests/ExecutionVectorMemoryTest.cpp) + target_link_libraries(felidae_execution_vectors_test PRIVATE felidae_execution_vectors) + target_compile_options(felidae_execution_vectors_test PRIVATE + $<$:-UNDEBUG> + $<$:/UNDEBUG>) + felidae_enable_msvc_exceptions(felidae_execution_vectors_test) + add_test(NAME felidae_execution_vectors COMMAND felidae_execution_vectors_test) + set_tests_properties(felidae_execution_vectors PROPERTIES TIMEOUT 10) + endif() if(FELIDAE_ENABLE_LIBTORCH) target_sources(felidae_mixfix_state_model_test PRIVATE src/CompilerFrontend.cpp @@ -796,6 +879,21 @@ if(FELIDAE_BUILD_TESTS) add_test(NAME felidae_db_csv COMMAND felidae_db_csv_test) set_tests_properties(felidae_db_csv PROPERTIES TIMEOUT 30) + if(FELIDAE_ENABLE_ROCKSDB) + add_executable(felidae_rocksdb_test tests/RocksDbTest.cpp) + target_link_libraries(felidae_rocksdb_test PRIVATE felidae_form nlohmann_json::nlohmann_json) + target_compile_definitions(felidae_rocksdb_test PRIVATE + FELIDAE_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/test-artifacts/rocksdb") + target_compile_options(felidae_rocksdb_test PRIVATE + $<$:-UNDEBUG> + $<$:/UNDEBUG>) + felidae_enable_msvc_exceptions(felidae_rocksdb_test) + add_test(NAME felidae_rocksdb COMMAND felidae_rocksdb_test) + set_tests_properties(felidae_rocksdb PROPERTIES + TIMEOUT 30 + LABELS "storage") + endif() + # Exercise representative user programs through the public compiler and # VM executables. Keep generated .bin files in the active build tree. # External-service, training, and stress fixtures have separate @@ -803,6 +901,7 @@ if(FELIDAE_BUILD_TESTS) set(FELIDAE_RUNNABLE_V2_EXAMPLES form_core_concepts numeric_operations + array_object json_csv_operations csv_fact_database fx_fact_database @@ -821,7 +920,8 @@ if(FELIDAE_BUILD_TESTS) standard_search_algorithms deep_fact_reasoning_analysis fact_search_analysis - selective_relationship_reasoning) + selective_relationship_reasoning + class_association_reasoning) foreach(example IN LISTS FELIDAE_RUNNABLE_V2_EXAMPLES) add_test(NAME felidae_example_${example} COMMAND "${CMAKE_COMMAND}" @@ -837,6 +937,8 @@ if(FELIDAE_BUILD_TESTS) endforeach() set_tests_properties(felidae_example_json_csv_operations PROPERTIES PASS_REGULAR_EXPRESSION "name: Ada") + set_tests_properties(felidae_example_array_object PROPERTIES + PASS_REGULAR_EXPRESSION "first: Ada, count: 2") # renderNumber() only forces a trailing .0 on exactly 0.0/1.0 (the # boolean convention); an ordinary whole number like this count prints # without one, so the assertion must match that, not assume every number @@ -859,6 +961,8 @@ if(FELIDAE_BUILD_TESTS) PASS_REGULAR_EXPRESSION "guides: 2, related: 2, confident: 2") set_tests_properties(felidae_example_selective_relationship_reasoning PROPERTIES PASS_REGULAR_EXPRESSION "connected_via_signal: 1.0\\}") + set_tests_properties(felidae_example_class_association_reasoning PROPERTIES + PASS_REGULAR_EXPRESSION "relation: works at, strength: 3.421") set_tests_properties(felidae_example_where_guard_chain PROPERTIES PASS_REGULAR_EXPRESSION "passes: 82, lowScore: 0.0, inactive: 0.0") set_tests_properties(felidae_example_optional_end_blocks PROPERTIES @@ -880,6 +984,12 @@ if(FELIDAE_BUILD_TESTS) if(TARGET felidae_libtorch_smoke_test) list(APPEND FELIDAE_TEST_TARGETS felidae_libtorch_smoke_test) endif() + if(TARGET felidae_rocksdb_test) + list(APPEND FELIDAE_TEST_TARGETS felidae_rocksdb_test) + endif() + if(TARGET felidae_execution_vectors_test) + list(APPEND FELIDAE_TEST_TARGETS felidae_execution_vectors_test) + endif() foreach(test_target IN LISTS FELIDAE_TEST_TARGETS) set_property(TARGET ${test_target} PROPERTY EXCLUDE_FROM_ALL TRUE) endforeach() diff --git a/README.md b/README.md index 5e3d659..67d57bb 100644 --- a/README.md +++ b/README.md @@ -609,17 +609,23 @@ main() => end ``` -`Type.all()` and `Type.where(...)` compile to the same verified fact-iteration -IR used by `lambda(Type, ...)`; `select` projects named fields. Conditions may -be extended with `.AndWhere(...)` and `.OrWhere(...)`. Hierarchy traversal +`Type.where(...)` compiles directly to verified indexed-query IR. Declared +single/composite class indexes are inherited, leading composite prefixes are +usable, and remaining conditions are checked as residual predicates. A small +unindexed table may use a bounded scan; a large one reports that an index is +required. `Type.all()` and `where(using:)` retain the established fact- +iteration path, while `select` projects named fields. Conditions may be +extended with `.AndWhere(...)` and `.OrWhere(...)`. Hierarchy traversal includes assignable child facts. Exact truth values are numeric `0.0` and `1.0`. `where` and `search` have different contracts. `where` performs structured equality filtering or invokes a verified predicate. `search` discovers facts through text (`exact`, `prefix`, `suffix`, `contains`, SQL `like`, or `regex`), -hierarchy (`ancestors`, `descendants`, or `related`), or bounded degree -matching. Search never changes a graded value into Boolean truth. See +hierarchy (`ancestors`, `descendants`, or `related`), or finite numeric +range/closeness matching. Numeric search accepts negative values and values +greater than `1.0`; only its tolerance is constrained to be non-negative. +Search never changes a graded value into Boolean truth. See `v2_examples/fact_search_analysis.fx`. CSV rows can enter that same native fact store and be synchronized from the VM: @@ -646,9 +652,16 @@ Joins must provide both `left` and `right` key fields, so the normal conditionless Cartesian join. Pass `kind: "left"`, `kind: "right"`, or `kind: "outer"` to the same operation when unmatched rows are required; separate `leftJoin`, `rightJoin`, and `OuterJoin` methods do not exist. +The VM builds one ordered right-key lookup and probes it in stable left order, +including every duplicate-key match; it does not execute a nested Cartesian +scan. Because child types are assignable to their parents, a parent query can work with the hierarchy rather than only one exact concrete type. +Classes and ordinary fact declarations use the same hierarchy table: class → +class, class → fact, fact → class, and fact → fact extension are all valid. +Only classes add reusable field/index schema metadata; neither form creates a +runtime class object. This gives Felidae a natural path for: @@ -1528,6 +1541,14 @@ Example: felidae_vm --serve program.bin ``` +To retain the VM fact store across restarts, provide a RocksDB directory. The +directory is data, so keep it under an application-owned location rather than +inside the source tree: + +```bash +felidae_vm --serve --fact-store build/runtime/facts.rocksdb program.bin +``` + The current server mode supports commands around concepts such as: ```text @@ -1539,7 +1560,7 @@ field history -proof +proof load @@ -1550,6 +1571,9 @@ quit This allows the VM to remain alive instead of starting a completely new process for every interaction. +`proof` prints every bounded hierarchy proof path in deterministic order, not +only one arbitrarily selected ancestor route. + The feature is particularly relevant to future reasoning and fact-oriented workflows. --- @@ -1768,6 +1792,65 @@ PyTorch's native C++ distribution. LibTorch is not kept as an ordinary source submodule in the same way as the lightweight dependencies; developers provide an appropriate platform package. +### Faiss execution memory + +Optional `FELIDAE_ENABLE_FAISS=ON` retains actual runtime SSM hidden vectors in +an execution-owned CPU Faiss index. It requires LibTorch and the Faiss C++ CMake +package. It does not index facts or SentencePiece IDs, change scores, train a +model, or feed retrieved states back into execution. Retrieval is not exposed +yet. Ordinary numeric expressions do not invoke the SSM to manufacture vectors. + +Each completed SSM evaluation stores one flattened hidden tensor, including all +recurrent layers. Capacity follows the existing execution semantic-step limit; +overflow raises an error rather than evicting states silently. Separate top-level +executions have separate indexes, including requests in a long-lived VM process. +All retained vectors are released with their execution state, with no disk writes. +RocksDB remains independent and continues to own persistent facts. + +After installing Faiss development files, enable and verify with: + +```bash +cmake -S . -B build/debug -DFELIDAE_ENABLE_FAISS=ON +cmake --build build/debug --target felidae_vm felidae_execution_vectors_test felidae_mixfix_state_model_test --parallel 8 +ctest --test-dir build/debug -R '^felidae_(execution_vectors|mixfix_state_model)$' --output-on-failure +``` + +### RocksDB + +RocksDB provides the ordered, durable key/value boundary used by scalable fact +storage and keyset pagination. It is enabled by default on desktop builds and +disabled by default on Android, where the platform package is normally absent. + +On Debian or Ubuntu: + +```bash +sudo apt-get update +sudo apt-get install -y librocksdb-dev +``` + +On macOS with Homebrew: + +```bash +brew install rocksdb +``` + +Disable it explicitly only for a platform without RocksDB: + +```bash +./build.sh --rocksdb OFF +``` + +An opt-in fact-store benchmark generates its synthetic database only under the +selected build tree. It reports ingestion rate, reopen time, cold and warm +indexed lookup latency, requested/returned page size, RocksDB index-reader +memory, estimated live/SST bytes, total storage size, and the cache assumptions. +It does not make a trillion-scale claim. Build and run it explicitly: + +```bash +cmake --build build/debug --target felidae_fact_store_benchmark --parallel 8 +./build/debug/felidae_fact_store_benchmark --records 100000 --page 100 --warm 100 +``` + --- # Testing @@ -2032,6 +2115,12 @@ Felidae intentionally represents source language tokens using integer IDs. SentencePiece provides the project's tokenizer representation. +The compiler feeds SentencePiece complete dot-terminated statement spans, not +individual physical lines. This keeps multiline expressions and `then` chains +in one integer-token stream. Decimal points, adjacent member access, strings, +and comments are distinguished before a terminator boundary is selected; +source offsets remain attached to every emitted token for diagnostics. + A simplified view is: ```text diff --git a/build.sh b/build.sh index 7a64148..3f744ee 100755 --- a/build.sh +++ b/build.sh @@ -6,6 +6,7 @@ set -euo pipefail MODE="${FELIDAE_MODE:-test}" # test | release ENABLE_TRAINING="${FELIDAE_ENABLE_TRAINING:-OFF}" # ON | OFF ENABLE_LIBTORCH="${FELIDAE_ENABLE_LIBTORCH:-auto}" # auto | ON | OFF +ENABLE_ROCKSDB="${FELIDAE_ENABLE_ROCKSDB:-auto}" # auto | ON | OFF PLATFORM="${FELIDAE_PLATFORM:-auto}" # auto | linux | macos | windows | android | generic ARCHITECTURE="${FELIDAE_ARCH:-auto}" # auto | x86_64 | arm64 | armv7 ANDROID_API="${FELIDAE_ANDROID_API:-24}" @@ -15,7 +16,7 @@ SANITIZE=0 ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" usage() { - echo "usage: ./build.sh [--mode test|release] [--training ON|OFF] [--libtorch ON|OFF]" + echo "usage: ./build.sh [--mode test|release] [--training ON|OFF] [--libtorch ON|OFF] [--rocksdb ON|OFF]" echo " [--platform auto|linux|macos|windows|android|generic]" echo " [--arch auto|x86_64|arm64|armv7] [--android-api N]" echo " [--jobs N|auto] [--sanitize]" @@ -34,6 +35,7 @@ while [[ $# -gt 0 ]]; do --mode) MODE="${2:-}"; shift 2 ;; --training) ENABLE_TRAINING="${2:-}"; shift 2 ;; --libtorch) ENABLE_LIBTORCH="${2:-}"; shift 2 ;; + --rocksdb) ENABLE_ROCKSDB="${2:-}"; shift 2 ;; --platform) PLATFORM="${2:-}"; shift 2 ;; --arch) ARCHITECTURE="${2:-}"; shift 2 ;; --android-api) ANDROID_API="${2:-}"; shift 2 ;; @@ -109,6 +111,15 @@ if [[ "${ENABLE_LIBTORCH,,}" == auto ]]; then else ENABLE_LIBTORCH="$(normalize_boolean "$ENABLE_LIBTORCH")" fi +if [[ "${ENABLE_ROCKSDB,,}" == auto ]]; then + if [[ "$PLATFORM" == android ]]; then + ENABLE_ROCKSDB=OFF + else + ENABLE_ROCKSDB=ON + fi +else + ENABLE_ROCKSDB="$(normalize_boolean "$ENABLE_ROCKSDB")" +fi if [[ "${JOBS,,}" == auto ]]; then if command -v getconf >/dev/null 2>&1; then JOBS="$(getconf _NPROCESSORS_ONLN)" @@ -140,6 +151,7 @@ CMAKE_ARGS=( "-DFELIDAE_BUILD_TESTS=${BUILD_TESTS}" "-DFELIDAE_ENABLE_LIBTORCH=${ENABLE_LIBTORCH}" "-DFELIDAE_ENABLE_TRAINING=${ENABLE_TRAINING}" + "-DFELIDAE_ENABLE_ROCKSDB=${ENABLE_ROCKSDB}" ) CAN_RUN_TESTS=1 case "$PLATFORM" in @@ -188,7 +200,7 @@ if [[ "$SANITIZE" -eq 1 ]]; then CMAKE_ARGS+=("-DFELIDAE_ENABLE_SANITIZERS=ON") fi -echo "Felidae platform=${PLATFORM} arch=${ARCHITECTURE} mode=${MODE} configuration=${CONFIGURATION} training=${ENABLE_TRAINING} libtorch=${ENABLE_LIBTORCH} jobs=${JOBS}" +echo "Felidae platform=${PLATFORM} arch=${ARCHITECTURE} mode=${MODE} configuration=${CONFIGURATION} training=${ENABLE_TRAINING} libtorch=${ENABLE_LIBTORCH} rocksdb=${ENABLE_ROCKSDB} jobs=${JOBS}" cmake "${CMAKE_ARGS[@]}" if [[ "$MODE" == test ]]; then diff --git a/datasets/tokenizer/felidae-tokenizer-v1.jsonl b/datasets/tokenizer/felidae-tokenizer-v1.jsonl index 930b63e..1f5b23b 100644 --- a/datasets/tokenizer/felidae-tokenizer-v1.jsonl +++ b/datasets/tokenizer/felidae-tokenizer-v1.jsonl @@ -69,7 +69,7 @@ {"schema_version":1,"id":"aggregation-sort","family":"aggregation","source":"main() =>\n values := [3, 1, 2]\n return sort(data: values)"} {"schema_version":1,"id":"aggregation-average","family":"aggregation","source":"main() =>\n values := [2, 4, 6]\n return average(data: values)"} {"schema_version":1,"id":"hierarchy-common-ancestors","family":"hierarchy","source":"Animal(name: \"root\")\nMammal extend Animal(name: \"mammal\")\nCat extend Mammal(name: \"cat\")\nDog extend Mammal(name: \"dog\")\nmain() => return commonAncestors(left: Cat(name: \"a\"), right: Dog(name: \"b\"))"} -{"schema_version":1,"id":"hierarchy-lowest-common-ancestor","family":"hierarchy","source":"main() => return lowestCommonAncestor(left: Cat(name: \"a\"), right: Dog(name: \"b\"))"} +{"schema_version":1,"id":"hierarchy-ancestor-analysis","family":"hierarchy","source":"main() => return ancestorAnalysis(left: Cat(name: \"a\"), right: Dog(name: \"b\"))"} {"schema_version":1,"id":"hierarchy-propagate-fact","family":"hierarchy","source":"main() => return propagateFact(parent: Mammal(name: \"m\"), child: Cat(name: \"c\"), changes: {habitat: \"wild\"})"} {"schema_version":1,"id":"mixfix-multi-capture","family":"mixfix","source":"@mixfix(pattern: \"{value:number} may be Above {minimum:number}\")\nkeepWhenAbove() => return value > minimum\nmain() => return 7 maybeAbove 5"} {"schema_version":1,"id":"mixfix-natural-query","family":"mixfix","source":"@mixfix(pattern: \"what is {subject:obj}\")\nexplain() => return subject.text\nmain() => return what is felidae"} @@ -84,7 +84,9 @@ {"schema_version":1,"id":"fact-dml","family":"persistence","source":"School(id: 1, active: 1.0)\nmain() =>\n inserted := School.insert(values: {id: 2, active: 1.0})\n updated := School.where(id: 1).update(values: {active: 0.0})\n return School.where(id: 2).delete()\nend"} {"schema_version":1,"id":"fact-fx-database-import","family":"persistence","source":"import \"schools.fx\"\nmain() =>\n changed := School.where(id: 1).update(values: {score: 3.432})\n return changed\nend"} {"schema_version":1,"id":"fact-joins","family":"queries","source":"School(id: 1)\nTeacher(school_id: 1)\nmain() => return School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"left\").limit(records: 100)"} -{"schema_version":1,"id":"fact-search","family":"queries","source":"Catalog(title: \"Alpha Guide\", confidence: 0.82)\nmain() =>\n titles := Catalog.search(field: \"title\", query: \"%guide\", type: \"like\", case: \"insensitive\")\n confident := Catalog.search(field: \"confidence\", type: \"degree\", minimum: 0.70, maximum: 0.90)\n return (titles: titles, confident: confident)\nend"} +{"schema_version":1,"id":"fact-search","family":"queries","source":"Catalog(title: \"Alpha Guide\", score: -212.421)\nmain() =>\n titles := Catalog.search(field: \"title\", query: \"%guide\", type: \"like\", case: \"insensitive\")\n scores := Catalog.search(field: \"score\", type: \"degree\", minimum: -300, maximum: 90.024)\n return (titles: titles, scores: scores)\nend"} {"schema_version":1,"id":"numeric-float-operations","family":"numeric","source":"main() => return (average: avg(3.432, -2.302), bounded: clamp(-345.345, -500.0, 500.0), blended: lerp(-2.302, 3.432, 0.25), valid: in_range(3.432, -10.0, 10.0), weighted: weighted_avg(10.0, 20.0, 1.0, 3.0))"} {"schema_version":1,"id":"fact-class-schema","family":"facts","source":"class Animal\n name: string\n index(name)\nend\nclass Human extend Animal\n age: number\n index(name, age)\n eligible(minimumAge: number) =>\n where age >= minimumAge\n return 1.0\n else\n return 0.0\n end\nend\nHuman(name: \"Ada\", age: 32)"} +{"schema_version":1,"id":"mixed-class-fact-hierarchy","family":"hierarchy","source":"FactBase(id: 0)\nFactChild extend FactBase(id: 1)\nclass ClassFromFact extend FactBase\n name: string\nend\nclass ClassChild extend ClassFromFact\n score: number\nend\nFactFromClass extend ClassFromFact(name: \"row\")"} +{"schema_version":1,"id":"mixfix-association-fact","family":"mixfix","source":"@mixfix(pattern: \"{person: Person} works at {company: Company}\")\nworksAt() =>\n return Association(left: person, right: company, relation: \"works_at\", strength: 3.421)\nend\nmain() =>\n return Person(name: \"Ada\") works at Company(name: \"Felidae\")\nend"} {"schema_version":1,"id":"runtime-ssm-suggest","family":"reasoning","source":"main() =>\n score := ssm.suggest(input: AncestorRelevance(candidate: Mammal, purpose: \"medical similarity\"))\n where score >= 4.5\n return score\nelse\n return 0.0\nend"} diff --git a/datasets/vm/README.md b/datasets/vm/README.md index 7c7edd9..608d832 100644 --- a/datasets/vm/README.md +++ b/datasets/vm/README.md @@ -1,24 +1,32 @@ # VM SSM corpus -The current reusable baseline is `runtime-context-v1.jsonl`. It is generated -from verified deterministic `.bin` results built from `v2_examples`. +`runtime-context-v1.jsonl` is generated from verified deterministic `.bin` +results built from `v2_examples`. Regenerate it with the current +`felidae_build_runtime_dataset` whenever the tokenizer or this schema changes; +schema-v8 records are intentionally rejected rather than silently training a +model with different inputs. -The dataset is JSON Lines schema v8, with one operation-level record per line: -`operation_id`, ordered `input_kinds`, sorted `fact_types`, sorted -`fact_type_counts`, sorted `hierarchy_edges`, `target_kind`, and `target_value`. Those fields are exactly -the finite information the current GRU sees at inference; it must not store -whole-program results or train-only features. +The dataset is JSON Lines schema v9, with one operation-level record per line: +`operation_id`, ordered `input_kinds`, canonical `input_values`, sorted +`fact_types`, sorted `fact_type_counts`, sorted `hierarchy_edges`, +`target_kind`, and either `target_value` or `target_score`. Those fields are +exactly the bounded information the current GRU sees at inference; it must not +store whole-program results or train-only features. Stable `input_kinds` values are nil `1`, number `2`, Degree `3`, text `4`, array `5`, map `6`, fact `7`, symbol `8`, tensor `9`, and dynamic text-keyed -map `10`. Existing schema-v8 -records remain valid because the tensor kind extends rather than renumbers the -contract. +map `10`. +`input_values` stores SentencePiece IDs directly and uses the documented +reserved structural-token tail for value boundaries, kinds, fields, and exact +floating-point bits. Training and live inference use the same encoder. Every symbol in the three fact/hierarchy fields is its complete SentencePiece ID sequence. Module-local indexes, hashes, and source spellings are not model identity and must never be written to this dataset. -`target_value` must name an action in the production vocabulary: input/fact +For finite action teachers, `target_value` must name an action in the production vocabulary: input/fact references `0..15`, numeric truth `0` or `1`, nil `0`, or Degree milli-values `0`, `250`, `500`, `750`, and `1000`. +An `ssm.suggest` teacher instead uses the score target kind and a finite +`target_score`; validation reports mean absolute error separately from action +accuracy. The baseline currently contains 15 deterministic records across the existing typed runtime fixtures and trains only the permanent `SemanticOperationId::Identity` value diff --git a/docs_language.md b/docs_language.md index 9489ffe..8884fbb 100644 --- a/docs_language.md +++ b/docs_language.md @@ -3,52 +3,57 @@ Felidae is a functional logic language for typed facts, explicit dataflow, and native stdlib calls. This document describes the current ("v2") grammar and runtime behavior, verified against the interpreter in `src/`. The reference -programs for this grammar live in `v2_examples/`. The `examples/` directory -still contains legacy programs written for the older dot-terminated grammar -and is being migrated separately; don't copy syntax from it. +programs for this grammar live in `v2_examples/`. The `examples/` directory is +legacy material and is being migrated separately; don't copy syntax from it. ## Statement Termination -Statements end at a newline, not at a trailing `.`: +Use `.` to give an ordinary statement an explicit boundary: ```Felidae -import "math" +import "math". -Person(name: "Alice", role: "Engineer") -Person(name: "Bob", role: "Manager") +Person(name: "Alice", role: "Engineer"). +Person(name: "Bob", role: "Manager"). Greeting(name: string) => - return (message: name) + return (message: name). ``` -`.` still means two things, both scoped to a single line: +The tokenizer encodes a complete dot-terminated statement as one span. A +statement can therefore cross physical lines, including a `then` pipeline: ```Felidae -pi := 3.01 # decimal point -result := a.b.c # member access, only valid when target and field share a line +result := prepare(value: input) + then normalize(value: system.result) + then finish(value: system.result). ``` -A trailing `.` at the end of a fact, rule, import, or global binding is no -longer valid syntax and raises a parse error (`Expected a newline after -fact/rule ..., found .`). Blank lines between statements are fine. +Dots inside a quoted string, a decimal (`3.01`), or adjacent member access +(`a.b.c`) are not terminators. `end` closes a class or method block and is +written without `.`. An annotation is attached to the declaration following +it and is not a separate statement. + +The beta parser still accepts a newline boundary in older unambiguous source, +but new and migrated programs should use explicit dots. SentencePiece itself +does not tokenize line by line; newlines are formatting inside the current +statement span. ## Goal Separators -Inside a rule or method body, goals can be separated by a comma, a newline, -or both — they're interchangeable: +Inside a rule or method body, commas express conjunction. A newline formats a +goal but does not replace an explicit statement boundary in new code: ```Felidae HotAdd(value: int) => doubled := value + value, - return (result: doubled) + return (result: doubled). HotAddNoCommas(value: int) => - doubled := value + value - return (result: doubled) + doubled := value + value. + return (result: doubled). ``` -Existing comma-separated code keeps working; commas are simply optional now. - ## Memory Model Facts and rules are stored by predicate name: @@ -181,14 +186,13 @@ array:get(data: [1, 2, 3], position: 0, access: value) ## Logic Operators -`,` is conjunction, same as a plain newline between goals. It means AND and -every goal in the sequence must hold: +`,` is conjunction. It means AND and every goal in the sequence must hold: ```Felidae EngineerInSEA(employee: e, name: Name) => - Name == e.name - e.role == "Engineer" - e.office == "SEA" + Name == e.name, + e.role == "Engineer", + e.office == "SEA". ``` `|` is disjunction. It means OR between goal branches: @@ -252,7 +256,17 @@ Person(name: "Ada", age: 32) Class fields constrain source fact rows, inherited fields are accepted, and index declarations are carried in the existing executable fact-type metadata. -There is no runtime class object or second interpreter. +The VM maintains exact single/composite indexes for those declarations; +`where` selects the widest fully covered inherited index and applies remaining +predicates as residual checks. Unindexed scans are bounded and large queries +report which corrective action is required. There is no runtime class object +or second interpreter. + +Classes and fact declarations share this one hierarchy. All combinations are +valid when the named parent exists: a fact may extend a fact or class, and a +class may extend a fact or class. A class contributes schema fields and index +metadata; an ordinary fact parent contributes hierarchy membership without +creating a second class runtime. ## Hierarchical Fact Queries @@ -282,7 +296,9 @@ requirements prevent accidental blind updates, deletes, and Cartesian joins. discovery operation for text patterns, hierarchy-valued properties, and degree ranges or closeness. Text search supports exact/prefix/suffix/contains, SQL LIKE (`%` and `_`), and regular-expression modes. Degree search preserves -intermediate values and returns the matching facts in creation order. +intermediate values—including negative values and values greater than `1.0`— +and returns the matching facts in creation order. Its tolerance must be +non-negative; no search result is implicitly normalized into truth. Relationships and dependency evidence are ordinary typed facts, not hidden verbs or a second relationship runtime. For example, declare @@ -292,11 +308,28 @@ keys. Domain rules decide how graded evidence is combined. Facts, maps, arrays, strings, and arbitrary numbers are not implicitly Boolean: use an explicit comparison in `where` or `if` when a branch requires numeric truth. +When a domain relationship has mixfix syntax, invoke that relationship using +the declared expression itself: + +```Felidae +association := person works at company +``` + +`Association.where(...)` is a later database query over association facts; it +is not a substitute for evaluating the `works at` relationship. + +Joins build an ordered lookup from the declared right key and probe it from +the left input. They preserve fact-creation order and duplicate-key matches; +the runtime does not execute a Cartesian nested scan. + `commonAncestors(left:, right:)` returns the complete deterministic candidate set in stable order. Felidae does not expose context-free “lowest” or “highest” ancestor choices. When an application needs a contextual score, it explicitly calls `ssm.suggest(input:)`; that result is a finite, unrestricted `double`, not a degree clamped to `[0, 1]`, and branching must compare it explicitly. +`ancestorAnalysis(left:, right:)` returns each candidate together with every +bounded proof path and the shortest distance from both subjects. The VM +service command `proof ` likewise prints all paths. Use `type(value: item, name: TypeName)` to read a value's concrete type, and `instanceof(value: item, type: Person)` to check whether a value is an instance diff --git a/intellij-idea-extension b/intellij-idea-extension index 2a00947..7427e72 160000 --- a/intellij-idea-extension +++ b/intellij-idea-extension @@ -1 +1 @@ -Subproject commit 2a0094796563da167d01e475b4dca0c1f642d313 +Subproject commit 7427e72bb718e3a547fbf336029674eaa98ce5fb diff --git a/src/CompilerFrontend.cpp b/src/CompilerFrontend.cpp index a1648e4..8f686e6 100644 --- a/src/CompilerFrontend.cpp +++ b/src/CompilerFrontend.cpp @@ -97,8 +97,8 @@ Program parseProgramText(std::string text, if (!operators) throw std::invalid_argument("parser operator registry must not be null"); IntegerTokenList input(felidaeSentencePieceModel(), std::move(text)); - // Mixfix declarations and uses share one parser-owned registry while each - // physical source line is independently SentencePiece-encoded. + // Mixfix declarations and uses share one parser-owned registry. SentencePiece + // receives complete dot-terminated statements, including multiline chains. IntegerParser parser(input, std::move(operators), options.mixfixModel); return parser.parseProgram(); } diff --git a/src/FelidaeIr.h b/src/FelidaeIr.h index 5212caf..f00eaf9 100644 --- a/src/FelidaeIr.h +++ b/src/FelidaeIr.h @@ -41,11 +41,13 @@ enum class IrOpcode : std::uint8_t { Similarity, Membership, ForEachFact, + // [opcode, destination, fact-type-symbol index, predicate-map register]. + // Exact named-field filtering uses VmFactStore's declared index planner; + // no runtime query-object representation is introduced. + FactWhere, FactJoin, HierarchyIsA, HierarchyCommonAncestors, - HierarchyLeastCommonAncestors, - HierarchyMostGeneralAncestors, TemporalRank, Numeric, Tensor, diff --git a/src/IntegerParser.cpp b/src/IntegerParser.cpp index dfbc9f4..9d6bc2c 100644 --- a/src/IntegerParser.cpp +++ b/src/IntegerParser.cpp @@ -274,6 +274,22 @@ bool IntegerParser::match(TokenId::Id id) { return true; } +bool IntegerParser::matchBindingOperator() { + if (match(TokenId::ASSIGN)) + return true; + const auto savedByte = byte_; + const auto savedPiece = piece_; + // Both global and local obj declarations use ordinary bindings. The + // initializer determines the existing VM value type; no object wrapper. + if (match(TokenId::COLON) && atNameRange() && consumeNameRange() == "obj") { + require(TokenId::EQUAL, "Expected '=' after object declaration"); + return true; + } + byte_ = savedByte; + piece_ = savedPiece; + return false; +} + bool IntegerParser::atBlockEnd() { const auto savedByte = byte_; const auto savedPiece = piece_; @@ -533,7 +549,10 @@ double IntegerParser::consumeNumber() { byte_ = input_.entry(piece_++).end; consumed = true; } - if (at(TokenId::DOT) && input_.has(piece_ + 1) && + const auto integerEnd = byte_; + if (at(TokenId::DOT) && input_.entry(piece_).begin == integerEnd && + input_.has(piece_ + 1) && + input_.entry(piece_).end == input_.entry(piece_ + 1).begin && isDecimalDigitId(input_.entry(piece_ + 1).id)) { match(TokenId::DOT); double scale = 0.1; @@ -648,11 +667,12 @@ IntegerParser::consumeQualifiedName(bool allowNamespaceSeparators) { const auto separator = input_.entry(piece_).id; match(separator); const auto separatorEnd = byte_; - // A separator is never followed by the start of a new statement, so a - // keyword spelling standing entirely alone here (School.where, - // Type.all, Type.select, ...) is unambiguously a name segment. + // A dot followed immediately by a name continues a qualified name. + // Whitespace after it instead leaves a statement terminator for the + // caller. Keyword members such as School.where remain valid names. if (!atNameRange(/*allowLoneKeyword=*/true) || - sourceContainsLineBreak(separatorEnd, byte_)) { + (separator == TokenId::DOT ? byte_ != separatorEnd + : sourceContainsLineBreak(separatorEnd, byte_))) { byte_ = beforeByte; piece_ = beforePiece; break; @@ -890,7 +910,7 @@ std::shared_ptr IntegerParser::parseGoal() { const auto startPiece = piece_; if (atNameRange()) { const auto name = consumeNameRange(); - if (match(TokenId::ASSIGN)) { + if (matchBindingOperator()) { auto result = std::make_shared(name, parseExpression()); stamp(result, begin, byte_); return result; @@ -1039,7 +1059,7 @@ std::shared_ptr IntegerParser::parseStatement() { const auto checkpointPiece = piece_; if (atNameRange()) { const auto name = consumeNameRange(); - if (match(TokenId::ASSIGN)) { + if (matchBindingOperator()) { if (!annotations.empty()) throw IntegerParserError( "Annotations can only be applied to method declarations"); @@ -1328,6 +1348,14 @@ std::shared_ptr IntegerParser::parsePrimary() { if (atNameRange()) { const auto name = consumeQualifiedName(); if (at(TokenId::LPAREN)) { + if (name.spelling == "array") { + require(TokenId::LPAREN, "Expected '(' after array"); + require(TokenId::RPAREN, "array() creates an empty array; use [...] for elements"); + auto result = std::make_shared( + std::vector>{}); + stamp(result, begin, byte_); + return result; + } auto result = std::make_shared(name.spelling, name.nameId, parseArguments(), name.builtinId, name.isCapitalized); @@ -1492,9 +1520,9 @@ std::shared_ptr IntegerParser::tryParseLeadingPattern() { } auto candidate = std::make_shared( pattern.operatorId, pattern.patternId, std::move(captures)); - candidateParsed = true; stamp(candidate, startByte, byte_); candidate->resolvedMethodId = resolveMixfixMethod(*candidate); + candidateParsed = true; if (candidate->resolvedMethodId == 0 && mixfixModel_) { candidate->resolvedMethodId = resolveModelMixfixMethod(candidate); } @@ -1589,9 +1617,9 @@ IntegerParser::tryParseTrailingPattern(std::shared_ptr left, if (!immediate || byte_ > immediateByte) { immediate = std::make_shared( pattern.operatorId, pattern.patternId, std::move(captures)); - candidateParsed = true; stampTrailing(immediate, byte_); immediate->resolvedMethodId = resolveMixfixMethod(*immediate); + candidateParsed = true; if (immediate->resolvedMethodId == 0 && mixfixModel_) { immediate->resolvedMethodId = resolveModelMixfixMethod(immediate); } @@ -1678,9 +1706,9 @@ IntegerParser::tryParseTrailingPattern(std::shared_ptr left, if (!deferred || byte_ > deferredByte) { deferred = std::make_shared( pattern->operatorId, pattern->patternId, std::move(captures)); - candidateParsed = true; stampTrailing(deferred, byte_); deferred->resolvedMethodId = resolveMixfixMethod(*deferred); + candidateParsed = true; if (deferred->resolvedMethodId == 0 && mixfixModel_) { deferred->resolvedMethodId = resolveModelMixfixMethod(deferred); } @@ -1771,7 +1799,9 @@ std::shared_ptr IntegerParser::parseUnary() { const auto separator = input_.entry(piece_).id; match(separator); const auto separatorEnd = byte_; - if (!atNameRange() || sourceContainsLineBreak(separatorEnd, byte_)) { + if (!atNameRange() || + (separator == TokenId::DOT ? byte_ != separatorEnd + : sourceContainsLineBreak(separatorEnd, byte_))) { byte_ = beforeByte; piece_ = beforePiece; break; @@ -2155,7 +2185,11 @@ IntegerParser::resolveMixfixMethod(const OperatorExpression &expression) const { matches.push_back(candidate); } if (highestSpecificity < 0) - throw IntegerParserError("mixfix expression has no compatible overload"); + throw IntegerParserError( + "mixfix expression has no compatible overload at " + + std::to_string(expression.sourceSpan.startLine) + ":" + + std::to_string(expression.sourceSpan.startColumn) + ": " + + expression.debug()); return matches.size() == 1 ? matches.front()->methodId : 0; } diff --git a/src/IntegerParser.h b/src/IntegerParser.h index 21e9f57..c302a3e 100644 --- a/src/IntegerParser.h +++ b/src/IntegerParser.h @@ -96,6 +96,7 @@ class IntegerParser { std::size_t builtinSequenceLength(TokenId::Id id) const; bool at(TokenId::Id id); bool match(TokenId::Id id); + bool matchBindingOperator(); bool atBlockEnd(); bool matchBlockEnd(); void require(TokenId::Id id, const char* message); diff --git a/src/IntegerTokenList.cpp b/src/IntegerTokenList.cpp index 643382a..2757f65 100644 --- a/src/IntegerTokenList.cpp +++ b/src/IntegerTokenList.cpp @@ -6,35 +6,79 @@ #include namespace Felidae { +namespace { + +std::size_t statementEnd(std::string_view source, std::size_t begin) { + bool quoted = false; + bool escaped = false; + bool comment = false; + for (std::size_t index = begin; index < source.size(); ++index) { + const char byte = source[index]; + if (comment) { + if (byte == '\n' || byte == '\r') + comment = false; + continue; + } + if (quoted) { + if (escaped) + escaped = false; + else if (byte == '\\') + escaped = true; + else if (byte == '"') + quoted = false; + continue; + } + if (byte == '"') { + quoted = true; + continue; + } + if (byte == '#') { + comment = true; + continue; + } + if (byte != '.') + continue; + // Decimal points and adjacent member access are grammar punctuation, not + // framing. An explicit terminator is followed by trivia or end of input. + const auto next = index + 1; + if (next == source.size() || source[next] == ' ' || source[next] == '\t' || + source[next] == '\r' || source[next] == '\n' || source[next] == '#') { + auto end = next; + for (;;) { + while (end < source.size() && + (source[end] == ' ' || source[end] == '\t' || + source[end] == '\r' || source[end] == '\n')) + ++end; + if (end == source.size() || source[end] != '#') + return end; + while (end < source.size() && source[end] != '\r' && source[end] != '\n') + ++end; + } + } + } + return source.size(); +} + +} // namespace IntegerTokenList::IntegerTokenList( const sentencepiece::SentencePieceProcessor &processor, std::string source) : source_(std::move(source)), processor_(&processor), complete_(source_.empty()) { if (!complete_) - encodeNextLine(); + encodeNextStatement(); } -void IntegerTokenList::encodeNextLine() const { +void IntegerTokenList::encodeNextStatement() const { if (complete_) return; - if (!processor_) - throw std::runtime_error("SentencePiece processor is unavailable"); - const auto lineBegin = nextLineBegin_; - const auto lineNumber = nextLineNumber_; - const auto newline = source_.find_first_of("\r\n", lineBegin); - auto lineEnd = newline == std::string::npos ? source_.size() : newline + 1; - if (newline != std::string::npos && source_[newline] == '\r' && - lineEnd < source_.size() && source_[lineEnd] == '\n') { - ++lineEnd; - } - const absl::string_view line(source_.data() + lineBegin, - lineEnd - lineBegin); + const auto begin = nextStatementBegin_; + const auto end = statementEnd(source_, begin); + const absl::string_view statement(source_.data() + begin, end - begin); sentencepiece::SentencePieceText encoded; - const auto status = processor_->Encode(line, &encoded); + const auto status = processor_->Encode(statement, &encoded); if (!status.ok()) { - throw std::runtime_error("SentencePiece encoding failed on source line " + - std::to_string(lineNumber) + ": " + + throw std::runtime_error("SentencePiece source encoding failed: " + status.ToString()); } ++encodeCount_; @@ -43,25 +87,19 @@ void IntegerTokenList::encodeNextLine() const { for (const auto &piece : encoded.pieces()) { const auto relativeBegin = static_cast(piece.begin()); const auto relativeEnd = static_cast(piece.end()); - if (relativeBegin > relativeEnd || relativeEnd > line.size()) { - throw std::runtime_error( - "SentencePiece returned an invalid offset on source line " + - std::to_string(lineNumber)); - } + if (relativeBegin > relativeEnd || relativeEnd > statement.size()) + throw std::runtime_error("SentencePiece returned an invalid source offset"); const auto id = static_cast(piece.id()); entries_.push_back( - Entry{id, lineBegin + relativeBegin, lineBegin + relativeEnd}); + Entry{id, begin + relativeBegin, begin + relativeEnd}); } - // lineEnd is strictly greater than lineBegin whenever complete_ is false, - // including blank and CRLF lines, so every lazy-load call advances. - nextLineBegin_ = lineEnd; - ++nextLineNumber_; - complete_ = nextLineBegin_ >= source_.size(); + nextStatementBegin_ = end; + complete_ = end == source_.size(); } bool IntegerTokenList::has(std::size_t index) const { while (index >= entries_.size() && !complete_) - encodeNextLine(); + encodeNextStatement(); return index < entries_.size(); } @@ -74,7 +112,7 @@ IntegerTokenList::entry(std::size_t index) const { const std::vector &IntegerTokenList::entries() const { while (!complete_) - encodeNextLine(); + encodeNextStatement(); return entries_; } diff --git a/src/IntegerTokenList.h b/src/IntegerTokenList.h index 44daed5..a3a237f 100644 --- a/src/IntegerTokenList.h +++ b/src/IntegerTokenList.h @@ -12,16 +12,14 @@ class SentencePieceProcessor; namespace Felidae { -// The sole source-tokenization result. Each physical source line is encoded -// independently so no learned piece can cross a statement line. Newline bytes -// remain in the encoded slice and all returned offsets are rebased to the -// original source. This type assigns no secondary token categories. +// The sole source-tokenization result. SentencePiece encodes complete +// dot-terminated statement spans, so multiline statements and `then` chains +// have one stable token stream. Newlines are formatting inside a span. // // `end` is a parser boundary, not a tokenizer boundary: discovering a safe -// block requires first distinguishing syntax from strings, comments, and -// mixfix anchors. Keep that decision in IntegerParser rather than duplicating -// a partial parser here. Lazy line loading also bounds work after an early -// syntax error while preserving one stable PieceId sequence per source line. +// block requires first distinguishing syntax from strings, comments, decimal +// points, member access, and mixfix anchors. Keep that decision in +// IntegerParser rather than duplicating a partial parser here. class IntegerTokenList { public: struct Entry { @@ -35,8 +33,6 @@ class IntegerTokenList { std::string source); const std::string &source() const noexcept { return source_; } - // Parser-facing lazy access. Requesting the first token beyond the loaded - // line encodes exactly the next physical line. bool has(std::size_t index) const; const Entry &entry(std::size_t index) const; std::size_t loadedSize() const noexcept { return entries_.size(); } @@ -45,12 +41,11 @@ class IntegerTokenList { std::size_t encodeCount() const noexcept { return encodeCount_; } private: - void encodeNextLine() const; + void encodeNextStatement() const; std::string source_; const sentencepiece::SentencePieceProcessor *processor_ = nullptr; mutable std::vector entries_; - mutable std::size_t nextLineBegin_ = 0; - mutable std::size_t nextLineNumber_ = 1; + mutable std::size_t nextStatementBegin_ = 0; mutable std::size_t encodeCount_ = 0; mutable bool complete_ = false; }; diff --git a/src/IrCodeGenerator.cpp b/src/IrCodeGenerator.cpp index 06d4a9b..84824ef 100644 --- a/src/IrCodeGenerator.cpp +++ b/src/IrCodeGenerator.cpp @@ -635,21 +635,21 @@ class FactDmlLowerer { throw IntegerParserError(typeName + "." + method + " requires named field values"); } - std::shared_ptr predicate; - for (const auto &argument : term->args) { - auto field = std::make_shared( - std::make_shared(rowName, rowId), argument.name); - field->keyId = argument.nameId; - auto comparison = std::make_shared( - CoreOperator::StrictEqual, std::move(field), argument.value); - predicate = predicate - ? std::make_shared( - CoreOperator::LogicalAnd, std::move(predicate), - std::move(comparison)) - : std::move(comparison); - } - return iteration(typeName, type->second, rowName, rowId, - std::move(predicate), term->sourceSpan); + std::vector predicates; + predicates.reserve(term->args.size()); + for (const auto &argument : term->args) + predicates.emplace_back(argument.name, argument.nameId, + argument.value); + auto predicateMap = std::make_shared(std::move(predicates)); + predicateMap->sourceSpan = term->sourceSpan; + auto result = std::make_shared( + "__fact:where", + std::vector{ + Arg(std::string{}, + std::make_shared(typeName, type->second)), + Arg(std::string{}, std::move(predicateMap))}); + result->sourceSpan = term->sourceSpan; + return result; } } else if (const auto operation = std::dynamic_pointer_cast(value)) { @@ -778,6 +778,24 @@ resolveScopedAccess(const std::shared_ptr &expression, std::dynamic_pointer_cast(expression)) { for (auto &argument : term->args) argument.value = resolveScopedAccess(argument.value, visible, implicitFields); + const auto dot = term->name.rfind('.'); + const auto firstDot = term->name.find('.'); + if (dot != std::string::npos && + visible.contains(symbolIdForName(term->name.substr(0, firstDot)))) { + const auto operation = builtinIdForName("array:" + term->name.substr(dot + 1)); + if (operation == BuiltinId::ArrayGet || operation == BuiltinId::ArrayLen || + operation == BuiltinId::ArrayPush) { + auto receiver = std::make_shared(term->name.substr(0, dot)); + receiver->sourceSpan = term->sourceSpan; + auto arguments = term->args; + arguments.insert(arguments.begin(), Arg("data", + resolveScopedAccess(receiver, visible, implicitFields))); + auto result = std::make_shared(builtinName(operation), + std::move(arguments), operation); + result->sourceSpan = term->sourceSpan; + return result; + } + } } else if (const auto operation = std::dynamic_pointer_cast(expression)) { std::shared_ptr rewritten; @@ -905,8 +923,16 @@ void resolveScopedAccessesInGoals(std::vector> &goals, return resolveScopedAccess(value, visible, implicitFields); }; const auto call = [&](Call &value) { - for (auto &argument : value.args) - argument.value = expression(argument.value); + // Calls used as statements share receiver and argument resolution with + // calls used as values; they must not retain a separate dotted-name path. + auto term = std::make_shared(value.name, value.nameId, + value.args, value.builtinId); + term->sourceSpan = value.sourceSpan; + const auto resolved = std::static_pointer_cast(expression(term)); + value.name = resolved->name; + value.nameId = resolved->nameId; + value.builtinId = resolved->builtinId; + value.args = std::move(resolved->args); }; if (const auto called = std::dynamic_pointer_cast(goal)) { call(called->call); @@ -1058,6 +1084,15 @@ bool isDirectDeterministicExpression( return definedSymbols.contains(variable->nameId); } if (const auto term = std::dynamic_pointer_cast(expression)) { + if (term->name == "__fact:where" && term->args.size() == 2) { + const auto type = + std::dynamic_pointer_cast(term->args[0].value); + return type && context.factTypes.contains(type->nameId) && + static_cast( + std::dynamic_pointer_cast(term->args[1].value)) && + isDirectDeterministicExpression(term->args[1].value, + definedSymbols, context); + } if (const auto operation = numericOperationForName(term->name); operation && term->args.size() == numericOperationArity(*operation) && std::all_of(term->args.begin(), term->args.end(), @@ -1590,6 +1625,12 @@ void appendFragment(FelidaeIr &target, FelidaeIr fragment, fragment.words[pc + 3] += textBase; width = 4; break; + case IrOpcode::FactWhere: + reg(fragment.words[pc + 1]); + symbol(fragment.words[pc + 2]); + reg(fragment.words[pc + 3]); + width = 4; + break; case IrOpcode::Return: reg(fragment.words[pc + 1]); width = 3; @@ -1602,8 +1643,6 @@ void appendFragment(FelidaeIr &target, FelidaeIr fragment, case IrOpcode::Similarity: case IrOpcode::HierarchyIsA: case IrOpcode::HierarchyCommonAncestors: - case IrOpcode::HierarchyLeastCommonAncestors: - case IrOpcode::HierarchyMostGeneralAncestors: reg(fragment.words[pc + 1]); reg(fragment.words[pc + 2]); reg(fragment.words[pc + 3]); @@ -1908,7 +1947,22 @@ FelidaeIr IrCodeGenerator::lowerExpression( {static_cast(IrOpcode::LoadSymbol), result, static_cast(ir.symbols.size() - 1)}); } else if (const auto term = std::dynamic_pointer_cast(value)) { - if (term->builtinId == BuiltinId::CsvToFacts && + if (term->name == "__fact:where") { + if (term->args.size() != 2) + throw IntegerParserError("fact where lowering requires type and predicates"); + const auto type = + std::dynamic_pointer_cast(term->args[0].value); + const auto predicates = + std::dynamic_pointer_cast(term->args[1].value); + if (!type || !predicates) + throw IntegerParserError("fact where lowering received invalid operands"); + const auto predicateRegister = self(self, predicates); + ir.symbols.push_back(type->nameId); + ir.words.insert(ir.words.end(), + {static_cast(IrOpcode::FactWhere), result, + static_cast(ir.symbols.size() - 1), + predicateRegister}); + } else if (term->builtinId == BuiltinId::CsvToFacts && (term->args.size() == 2 || term->args.size() == 3)) { // Mirrors the generic builtin-lowering block below, except the // arity itself varies (2 or 3, matching the isDirectDeterministicExpression diff --git a/src/VmMain.cpp b/src/VmMain.cpp index 487c1dc..02d8fc7 100644 --- a/src/VmMain.cpp +++ b/src/VmMain.cpp @@ -24,6 +24,7 @@ struct Options { fs::path input; bool serve = false; std::optional modelDirectory; + std::optional factStoreDirectory; }; std::optional parseInput(int argc, char **argv) { @@ -42,6 +43,12 @@ std::optional parseInput(int argc, char **argv) { options.modelDirectory = fs::path(argv[index]); continue; } + if (argument == "--fact-store") { + if (++index == argc) + throw std::runtime_error("--fact-store requires a RocksDB directory"); + options.factStoreDirectory = fs::path(argv[index]); + continue; + } if (!options.input.empty()) throw std::runtime_error( "felidae_vm accepts exactly one verified .bin IR file"); @@ -56,13 +63,14 @@ void printHelp() { std::cout << LANGUAGE_NAME << " Form VM v" << LANGUAGE_VERSION << "\n\n" << "Usage: felidae_vm program.bin\n" - << " felidae_vm [--serve] [--model models/runtime] program.bin\n" + << " felidae_vm [--serve] [--model models/runtime] " + "[--fact-store path] program.bin\n" << " felidae_vm --train datasets/vm/runtime-context-v1.jsonl " "--store-model build|dist [--epochs N] [--learning-rate R]\n" << "Loads, verifies once, and executes Felidae IR. --serve keeps one VM " "and " "its fact memory resident; use run, facts [type-id], field , " - "history, proof , load , " + "history, proof (all paths), load , " "modules, or quit on stdin.\n"; } @@ -148,6 +156,11 @@ int main(int argc, char **argv) { }; auto module = loadBinaryIr(binary, felidaeSentencePieceModelIdentity()); auto display = makeIrDisplayContext(module, decoder); + auto factStore = options->factStoreDirectory + ? std::make_shared( + fs::absolute(*options->factStoreDirectory) + .lexically_normal()) + : std::make_shared(); #ifdef FELIDAE_HAS_TORCH std::unique_ptr model; if (options->modelDirectory) { @@ -167,13 +180,15 @@ int main(int argc, char **argv) { display.tensorDecoder = [&](const VmTensor &tensor) { return tensorRuntime.displayTensor(tensor); }; - FelidaeKnowledgeRuntime runtime(model.get(), 1024, 256, {}, &tensorRuntime, + FelidaeKnowledgeRuntime runtime(model.get(), 1024, 256, + std::move(factStore), &tensorRuntime, decoder, encoder); #else if (options->modelDirectory) throw std::runtime_error( "this VM build has no LibTorch runtime SSM support"); - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, {}, nullptr, decoder, + FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, + std::move(factStore), nullptr, decoder, encoder); #endif RegisterVm vm; @@ -222,11 +237,19 @@ int main(int argc, char **argv) { } else if (verb == "proof") { const auto child = readSymbol(words, "proof"); const auto ancestor = readSymbol(words, "proof"); - const auto path = runtime.factStore()->hierarchyProof(child, ancestor); - for (std::size_t index = 0; index < path.size(); ++index) { - if (index != 0) + const auto paths = + runtime.factStore()->hierarchyProofs(child, ancestor); + for (std::size_t pathIndex = 0; pathIndex < paths.size(); ++pathIndex) { + if (pathIndex != 0) std::cout << ' '; - std::cout << path[index]; + std::cout << '['; + const auto &path = paths[pathIndex]; + for (std::size_t index = 0; index < path.size(); ++index) { + if (index != 0) + std::cout << ' '; + std::cout << path[index]; + } + std::cout << ']'; } std::cout << "\n"; } else if (verb == "quit") diff --git a/src/form/BuiltinOperation.h b/src/form/BuiltinOperation.h index 4b848fa..1c0d5b3 100644 --- a/src/form/BuiltinOperation.h +++ b/src/form/BuiltinOperation.h @@ -65,8 +65,6 @@ enum class BuiltinId : std::uint16_t { FileExists, FileDeleteFile, CommonAncestors, - LowestCommonAncestor, - HighestCommonAncestor, AncestorAnalysis, PropagateFact, JsonObject, diff --git a/src/form/RegisterVm.cpp b/src/form/RegisterVm.cpp index 2cfb61e..305a006 100644 --- a/src/form/RegisterVm.cpp +++ b/src/form/RegisterVm.cpp @@ -5,9 +5,14 @@ #include "libs/Builtin.h" #include "libs/Csv.h" #include "libs/Db.h" +#include "libs/FactStorageCodec.h" +#ifdef FELIDAE_HAS_ROCKSDB +#include "libs/RocksDb.h" +#endif #include #include +#include #include #include #include @@ -16,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -80,11 +86,11 @@ std::size_t irInstructionWidth(const FelidaeIr &ir, std::size_t pc) { case IrOpcode::Similarity: case IrOpcode::HierarchyIsA: case IrOpcode::HierarchyCommonAncestors: - case IrOpcode::HierarchyLeastCommonAncestors: - case IrOpcode::HierarchyMostGeneralAncestors: case IrOpcode::TemporalRank: case IrOpcode::MakeFact: return bounded(4); + case IrOpcode::FactWhere: + return bounded(4); // One extra operand beyond type/callback: a register holding a map of // outer-scope values the callback's predicate closes over (0 = none). The // callback procedure itself still takes only the row parameter plus this @@ -244,6 +250,53 @@ bool vmValuesEqualInternal(const VmValue &left, const VmValue &right) { return vmValuesEqualAtDepth(left, right, 0); } +using Form::StoredValueKey; + +std::optional +factIndexKey(const VmFactPtr &fact, std::span fields, + std::span symbols) { + if (!fact) + return std::nullopt; + StoredValueKey result; + result.push_back(static_cast(fields.size())); + for (const auto field : fields) { + const auto found = std::find_if( + fact->fields.begin(), fact->fields.end(), + [&](const auto &entry) { return entry.first == field; }); + if (found == fact->fields.end()) + return std::nullopt; + auto value = Form::encodeStoredValueKey(found->second, symbols); + result.push_back(static_cast(value.size())); + result.insert(result.end(), value.begin(), value.end()); + } + return result; +} + +StoredValueKey predicateIndexKey( + std::span indexFields, std::size_t coveredFields, + std::span> predicates, + std::span symbols) { + if (coveredFields == 0 || coveredFields > indexFields.size()) + throw IrError("fact query planner selected an invalid index prefix"); + StoredValueKey result; + // Keep the declared field count first so one index's key space cannot be a + // prefix of another. Only the leading covered fields follow for a range + // lookup over a composite index. + result.push_back(static_cast(indexFields.size())); + for (std::size_t index = 0; index < coveredFields; ++index) { + const auto field = indexFields[index]; + const auto found = std::find_if( + predicates.begin(), predicates.end(), + [&](const auto &entry) { return entry.first == field; }); + if (found == predicates.end()) + throw IrError("fact query planner selected an uncovered index"); + auto value = Form::encodeStoredValueKey(found->second, symbols); + result.push_back(static_cast(value.size())); + result.insert(result.end(), value.begin(), value.end()); + } + return result; +} + double evaluateNumericOperation(NumericOperation operation, std::span operands) { if (operation >= NumericOperation::Count || @@ -577,6 +630,10 @@ void verifyControlFlowInitialization( requireFlowRead(state, ir.words[pc + 4]); write(ir.words[pc + 1]); break; + case IrOpcode::FactWhere: + requireFlowRead(state, ir.words[pc + 3]); + write(ir.words[pc + 1]); + break; case IrOpcode::FactJoin: requireFlowRead(state, ir.words[pc + 2]); requireFlowRead(state, ir.words[pc + 3]); @@ -601,8 +658,6 @@ void verifyControlFlowInitialization( case IrOpcode::Membership: case IrOpcode::HierarchyIsA: case IrOpcode::HierarchyCommonAncestors: - case IrOpcode::HierarchyLeastCommonAncestors: - case IrOpcode::HierarchyMostGeneralAncestors: case IrOpcode::Compare: requireFlowRead(state, ir.words[pc + 2]); requireFlowRead(state, ir.words[pc + 3]); @@ -681,6 +736,180 @@ void verifyControlFlowInitialization( } } // namespace +namespace { + +void appendBigEndian64(std::string &key, std::uint64_t value) { + for (int shift = 56; shift >= 0; shift -= 8) + key.push_back(static_cast((value >> shift) & 0xffU)); +} + +void appendPieceKey(std::string &key, std::span pieces) { + appendBigEndian64(key, pieces.size()); + for (const auto piece : pieces) + appendBigEndian64(key, piece); +} + +std::string storedFactKey(IrFactRef id) { + std::string key{"F", 1}; + appendBigEndian64(key, id); + return key; +} + +std::string storedTypeKey(std::span pieces) { + std::string key{"Y", 1}; + appendPieceKey(key, pieces); + return key; +} + +void appendOrderedKey(std::string &key, + std::span values) { + for (const auto value : values) + appendBigEndian64(key, value); +} + +void appendFactOrder(std::string &key, const VmFact &fact) { + appendBigEndian64(key, fact.createdSequence); + appendBigEndian64(key, fact.id); +} + +std::string storedTypeIndexPrefix(std::span type) { + std::string key{"IT", 2}; + appendPieceKey(key, type); + return key; +} + +std::string storedConcreteTypeIndexPrefix(std::span type) { + std::string key{"IC", 2}; + appendPieceKey(key, type); + return key; +} + +std::string storedFieldIndexPrefix(std::span field) { + std::string key{"IF", 2}; + appendPieceKey(key, field); + return key; +} + +std::string storedSourceIndexPrefix(std::string_view source) { + std::string key{"IS", 2}; + appendBigEndian64(key, source.size()); + key.append(source); + return key; +} + +std::string storedExactIndexPrefix( + std::span owner, + std::span> indexes, std::size_t ordinal, + std::span symbols) { + if (ordinal >= indexes.size()) + throw IrError("persistent fact index ordinal is invalid"); + std::string key{"IE", 2}; + appendPieceKey(key, owner); + appendBigEndian64(key, indexes[ordinal].size()); + for (const auto field : indexes[ordinal]) + appendPieceKey(key, irSymbolPieces(symbols, field)); + return key; +} + +} // namespace + +class VmFactStore::Persistence { +public: +#ifdef FELIDAE_HAS_ROCKSDB + explicit Persistence(const std::filesystem::path &directory) + : database(directory) { + if (const auto stored = database.get("M/revision")) { + if (stored->size() != sizeof(revision)) + throw IrError("RocksDB revision metadata is malformed"); + for (const unsigned char byte : *stored) + revision = (revision << 8U) | byte; + } + } + // The store mutex serializes callers. Publish the next revision only after + // its atomic data/index batch commits; failed writes cannot advance it. + void commit(std::span mutations) { + if (mutations.empty()) + return; + if (revision == std::numeric_limits::max()) + throw IrError("RocksDB fact-store revision exhausted"); + std::vector batch(mutations.begin(), mutations.end()); + std::string encoded; + appendBigEndian64(encoded, revision + 1); + batch.push_back({Form::RocksDb::Mutation::Kind::Put, "M/revision", + std::move(encoded)}); + database.write(batch); + ++revision; + } + Form::RocksDb database; + std::uint64_t revision = 0; +#else + explicit Persistence(const std::filesystem::path &) { + throw IrError("this VM build has no RocksDB fact-store support"); + } +#endif + bool loading = false; +}; + +VmFactStore::VmFactStore() = default; + +VmFactStore::VmFactStore(const std::filesystem::path &directory) + : persistence_(std::make_unique(directory)) { +#ifdef FELIDAE_HAS_ROCKSDB + persistence_->loading = true; + // Allocation watermarks outlive deleted rows. Commit them with insertion + // so a restart cannot recycle an identity referenced by an older snapshot. + const auto allocation = persistence_->database.get("M/allocation"); + if (allocation) { + if (allocation->size() != 16) + throw IrError("RocksDB allocation metadata is malformed"); + std::uint64_t counters[2]{}; + for (std::size_t i = 0; i < allocation->size(); ++i) + counters[i / 8] = (counters[i / 8] << 8U) | + static_cast((*allocation)[i]); + if (counters[0] == 0 || counters[1] == 0 || + counters[0] > std::numeric_limits::max()) + throw IrError("RocksDB allocation metadata is outside its range"); + nextId_ = static_cast(counters[0]); + nextSequence_ = counters[1]; + } + const auto readAll = [&](std::string_view prefix, const auto &consume) { + std::optional after; + while (true) { + const auto page = persistence_->database.scanPrefix( + prefix, + after ? std::optional{*after} : std::nullopt, + 4096); + for (const auto &[key, value] : page.rows) + consume(key, value); + if (!page.hasMore || page.rows.empty()) + break; + after = page.rows.back().first; + } + }; + readAll(std::string_view{"Y", 1}, [&](std::string_view key, std::string_view value) { + const auto record = Form::decodeStoredFactType( + value, [this](PieceSequence pieces) { + return internSymbol(std::move(pieces)); + }); + if (key != storedTypeKey(irSymbolPieces(symbolTable_, record.type))) + throw IrError("RocksDB type record identity is inconsistent"); + registerType(record.type, record.parents, record.indexes); + }); + // Facts remain on disk and are decoded through their selected index page. + // Allocation metadata is mandatory once any fact exists; recovering it by + // scanning all rows would make VM startup proportional to database size. + if (!allocation && + !persistence_->database.scanPrefix(std::string_view{"F", 1}, + std::nullopt, 1).rows.empty()) + throw IrError("RocksDB facts exist without allocation metadata"); + persistence_->loading = false; +#else + (void)directory; +#endif +} + +VmFactStore::~VmFactStore() = default; + bool vmValuesEqual(const VmValue &left, const VmValue &right) { return vmValuesEqualInternal(left, right); } @@ -816,6 +1045,221 @@ bool VmFactStore::isAssignableToLocked(IrSymbolRef candidate, return ancestorClosureLocked(candidate).contains(expected); } +void VmFactStore::validateDeclaredIndexKeysLocked(const VmFactPtr &fact) const { + for (const auto &[owner, indexes] : exactIndexes_) { + if (!isAssignableToLocked(fact->type, owner)) + continue; + for (const auto &index : indexes) + (void)factIndexKey(fact, index.fields, symbolTable_); + } +} + +void VmFactStore::addToDeclaredIndexesLocked(const VmFactPtr &fact) { + // Persistent rows are committed atomically by persistentIndexKeysLocked. + // Keep only their declarations here, not a second process-resident index. + if (persistence_) + return; + for (auto &[owner, indexes] : exactIndexes_) { + if (!isAssignableToLocked(fact->type, owner)) + continue; + for (auto &index : indexes) { + if (auto key = factIndexKey(fact, index.fields, symbolTable_)) { + auto &rows = index.rows[std::move(*key)]; + const auto position = std::lower_bound( + rows.begin(), rows.end(), fact, + [](const auto &left, const auto &right) { + if (left->createdSequence != right->createdSequence) + return left->createdSequence < right->createdSequence; + return left->id < right->id; + }); + rows.insert(position, fact); + } + } + } +} + +void VmFactStore::removeFromDeclaredIndexesLocked(const VmFactPtr &fact) { + if (persistence_) + return; + for (auto &[owner, indexes] : exactIndexes_) { + if (!isAssignableToLocked(fact->type, owner)) + continue; + for (auto &index : indexes) { + const auto key = factIndexKey(fact, index.fields, symbolTable_); + if (!key) + continue; + const auto found = index.rows.find(*key); + if (found == index.rows.end()) + throw IrError("declared fact index is inconsistent"); + std::erase(found->second, fact); + if (found->second.empty()) + index.rows.erase(found); + } + } +} + +std::vector VmFactStore::persistentIndexKeysLocked( + const VmFactPtr &fact, std::optional source) const { + if (!fact) + throw IrError("persistent fact index requires a fact"); + std::vector result; + { + auto key = storedConcreteTypeIndexPrefix( + irSymbolPieces(symbolTable_, fact->type)); + appendFactOrder(key, *fact); + result.push_back(std::move(key)); + } + std::vector types(ancestorClosureLocked(fact->type).begin(), + ancestorClosureLocked(fact->type).end()); + std::sort(types.begin(), types.end()); + for (const auto type : types) { + auto key = storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)); + appendFactOrder(key, *fact); + result.push_back(std::move(key)); + } + + std::vector fields; + fields.reserve(fact->fields.size()); + for (const auto &[field, _] : fact->fields) + fields.push_back(field); + std::sort(fields.begin(), fields.end()); + fields.erase(std::unique(fields.begin(), fields.end()), fields.end()); + for (const auto field : fields) { + auto key = storedFieldIndexPrefix(irSymbolPieces(symbolTable_, field)); + appendFactOrder(key, *fact); + result.push_back(std::move(key)); + } + + if (source) { + auto key = storedSourceIndexPrefix(*source); + appendFactOrder(key, *fact); + result.push_back(std::move(key)); + } + + for (const auto &[owner, indexes] : declaredIndexes_) { + if (!isAssignableToLocked(fact->type, owner)) + continue; + for (std::size_t ordinal = 0; ordinal < indexes.size(); ++ordinal) { + const auto value = factIndexKey(fact, indexes[ordinal], symbolTable_); + if (!value) + continue; + auto key = storedExactIndexPrefix( + irSymbolPieces(symbolTable_, owner), indexes, ordinal, symbolTable_); + appendOrderedKey(key, *value); + appendFactOrder(key, *fact); + result.push_back(std::move(key)); + } + } + std::sort(result.begin(), result.end()); + result.erase(std::unique(result.begin(), result.end()), result.end()); + return result; +} + +std::vector VmFactStore::persistentFactsLocked( + std::string_view prefix, std::size_t maximum, bool *hasMore, + std::optional after, std::string *lastKey, + std::vector *keys) const { +#ifdef FELIDAE_HAS_ROCKSDB + if (!persistence_) + throw IrError("persistent fact query requires a RocksDB store"); + const auto page = + persistence_->database.scanPrefix(prefix, after, maximum); + if (lastKey && !page.rows.empty()) + *lastKey = page.rows.back().first; + if (hasMore) + *hasMore = page.hasMore; + std::vector result; + result.reserve(page.rows.size()); + for (const auto &[key, _] : page.rows) { + if (keys) + keys->push_back(key); + if (key.size() < sizeof(std::uint64_t)) + throw IrError("RocksDB fact index contains a truncated key"); + std::uint64_t id = 0; + for (std::size_t index = key.size() - sizeof(std::uint64_t); + index < key.size(); ++index) + id = (id << 8U) | static_cast(key[index]); + const auto record = persistence_->database.get(storedFactKey(id)); + if (!record) + throw IrError("RocksDB fact index references a missing fact"); + const auto decoded = Form::decodeStoredFact( + *record, [this](PieceSequence pieces) { + return internSymbolLocked(std::move(pieces)); + }); + if (!decoded.fact || decoded.fact->id != id) + throw IrError("RocksDB fact index identity is inconsistent"); + result.push_back(decoded.fact); + } + return result; +#else + (void)prefix; + (void)maximum; + (void)hasMore; + (void)after; + (void)lastKey; + (void)keys; + throw IrError("this VM build has no RocksDB fact-store support"); +#endif +} + +VmFactStore::StoredSnapshot +VmFactStore::persistentSnapshotLocked(IrFactRef fact) const { +#ifdef FELIDAE_HAS_ROCKSDB + if (!persistence_ || fact == 0) + throw IrError("persistent fact lookup has no valid store or identity"); + const auto bytes = persistence_->database.get(storedFactKey(fact)); + if (!bytes) + throw IrError("fact targets an identity outside this knowledge runtime"); + auto record = Form::decodeStoredFact( + *bytes, [this](PieceSequence pieces) { + return internSymbolLocked(std::move(pieces)); + }); + if (!record.fact || record.fact->id != fact || + !parents_.contains(record.fact->type) || + record.fact->createdSequence == 0 || + record.fact->createdSequence == std::numeric_limits::max()) + throw IrError("RocksDB contains an invalid fact record"); + validateDeclaredIndexKeysLocked(record.fact); + return {std::move(record.fact), std::move(record.source)}; +#else + (void)fact; + throw IrError("this VM build has no RocksDB fact-store support"); +#endif +} + +IrSymbolRef VmFactStore::internSymbol(PieceSequence pieces) { + if (pieces.empty()) + throw IrError("runtime symbol must contain SentencePiece IDs"); + std::lock_guard lock(mutex_); + return internSymbolLocked(std::move(pieces)); +} + +IrSymbolRef VmFactStore::internSymbolLocked(PieceSequence pieces) const { + const auto found = symbolIds_.find(pieces); + if (found != symbolIds_.end()) + return found->second; + if (symbolTable_.size() == + static_cast(std::numeric_limits::max())) + throw IrError("runtime symbol table exhausted its ID space"); + symbolTable_.push_back(std::move(pieces)); + const auto symbol = static_cast(symbolTable_.size()); + symbolIds_.emplace(symbolTable_.back(), symbol); + return symbol; +} + +std::optional +VmFactStore::findSymbol(std::span pieces) const { + std::lock_guard lock(mutex_); + const PieceSequence key(pieces.begin(), pieces.end()); + const auto found = symbolIds_.find(key); + return found == symbolIds_.end() ? std::nullopt + : std::optional{found->second}; +} + +const std::vector &VmFactStore::symbolTable() const noexcept { + return symbolTable_; +} + void VmFactStore::registerType(IrSymbolRef type, std::vector parents, std::vector> indexes) { @@ -836,8 +1280,23 @@ void VmFactStore::registerType(IrSymbolRef type, if (isAssignableToLocked(parent, type)) throw IrError("fact hierarchy contains a cycle"); } +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_ && !persistence_->loading) { + const auto value = Form::encodeStoredFactType( + type, parents, indexes, symbolTable_); + const std::array mutation{{ + {Form::RocksDb::Mutation::Kind::Put, + storedTypeKey(irSymbolPieces(symbolTable_, type)), value}}}; + persistence_->commit(mutation); + } +#endif parents_.emplace(type, std::move(parents)); - declaredIndexes_.emplace(type, std::move(indexes)); + auto [declaration, _] = + declaredIndexes_.emplace(type, std::move(indexes)); + auto &runtimeIndexes = exactIndexes_[type]; + runtimeIndexes.reserve(declaration->second.size()); + for (const auto &fields : declaration->second) + runtimeIndexes.push_back(ExactIndex{fields, {}}); ++hierarchyRevision_; ++knowledgeRevision_; } @@ -846,7 +1305,11 @@ VmFactPtr VmFactStore::retain(const VmFactPtr &fact) { if (!fact || !validVmValue(VmValue{fact})) throw IrError("fact store cannot retain an invalid fact"); std::lock_guard lock(mutex_); + if (!parents_.contains(fact->type)) + throw IrError("fact store cannot retain an unregistered fact type"); if (fact->id != 0) { + if (persistence_) + return currentSnapshotLocked(fact); if (std::ranges::find(facts_, fact) == facts_.end()) throw IrError("fact already belongs to another knowledge runtime"); return fact; @@ -854,12 +1317,38 @@ VmFactPtr VmFactStore::retain(const VmFactPtr &fact) { if (nextId_ == std::numeric_limits::max()) throw IrError("fact store exhausted its fact ID space"); auto retained = std::make_shared(*fact); - retained->id = nextId_++; - retained->createdSequence = nextSequence_++; - facts_.push_back(retained); - byType_[retained->type].push_back(retained); - for (const auto &[field, _] : retained->fields) - byField_[field].push_back(retained); + validateDeclaredIndexKeysLocked(retained); + if (nextSequence_ == std::numeric_limits::max()) + throw IrError("fact store exhausted its creation-order space"); + retained->id = nextId_; + retained->createdSequence = nextSequence_; +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + const auto value = + Form::encodeStoredFact(*retained, std::nullopt, symbolTable_); + std::vector mutation{ + {Form::RocksDb::Mutation::Kind::Put, storedFactKey(retained->id), + value}}; + for (auto &key : persistentIndexKeysLocked(retained)) + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); + std::string allocation; + appendBigEndian64(allocation, nextId_ + 1); + appendBigEndian64(allocation, nextSequence_ + 1); + mutation.push_back({Form::RocksDb::Mutation::Kind::Put, "M/allocation", + std::move(allocation)}); + persistence_->commit(mutation); + } +#endif + ++nextId_; + ++nextSequence_; + if (!persistence_) { + facts_.push_back(retained); + byType_[retained->type].push_back(retained); + for (const auto &[field, _] : retained->fields) + byField_[field].push_back(retained); + } + addToDeclaredIndexesLocked(retained); provenance_.push_back( VmFactProvenance{retained->id, 0, retained->origin == VmFact::Origin::Derived}); @@ -870,7 +1359,11 @@ VmFactPtr VmFactStore::retain(const VmFactPtr &fact) { void VmFactStore::recordInsert(IrFactRef fact) { std::lock_guard lock(mutex_); - if (fact == 0 || std::none_of(facts_.begin(), facts_.end(), + if (fact == 0) + throw IrError("fact insertion record targets an unknown fact"); + if (persistence_) + (void)persistentSnapshotLocked(fact); + else if (std::none_of(facts_.begin(), facts_.end(), [&](const auto &item) { return item->id == fact; })) @@ -879,18 +1372,36 @@ void VmFactStore::recordInsert(IrFactRef fact) { VmFactMutationKind::Insert}); } -VmFactPtr VmFactStore::mutate(const VmFactPtr &fact, IrSymbolRef field, - const VmValue &value, IrSymbolRef procedure) { - if (!fact || fact->id == 0 || field == 0 || !validVmValue(value)) - throw IrError("fact mutation is invalid"); - std::lock_guard lock(mutex_); +namespace { +void requireMatchingSnapshot(const VmFactPtr ¤t, const VmFactPtr &snapshot) { + if (!vmValuesEqualInternal(VmValue{current}, VmValue{snapshot})) + throw IrError("fact mutation uses a stale fact snapshot"); +} +} // namespace + +VmFactPtr VmFactStore::currentSnapshotLocked(const VmFactPtr &fact) const { + if (persistence_) { + auto stored = persistentSnapshotLocked(fact->id).fact; + requireMatchingSnapshot(stored, fact); + return stored; + } const auto known = std::find_if(facts_.begin(), facts_.end(), - [&](const auto &item) { return item == fact; }); + [&](const auto &item) { return item->id == fact->id; }); if (known == facts_.end()) throw IrError( "fact mutation targets a fact outside this knowledge runtime"); - auto updated = std::make_shared(*fact); + requireMatchingSnapshot(*known, fact); + return *known; +} + +VmFactPtr VmFactStore::mutate(const VmFactPtr &fact, IrSymbolRef field, + const VmValue &value, IrSymbolRef procedure) { + if (!fact || fact->id == 0 || field == 0 || !validVmValue(value)) + throw IrError("fact mutation is invalid"); + std::lock_guard lock(mutex_); + const auto current = currentSnapshotLocked(fact); + auto updated = std::make_shared(*current); bool hadField = false; for (auto &[existing, previous] : updated->fields) { if (existing == field) { @@ -902,18 +1413,49 @@ VmFactPtr VmFactStore::mutate(const VmFactPtr &fact, IrSymbolRef field, if (!hadField) { updated->fields.emplace_back(field, value); } - const auto replace = [&](auto &items) { - const auto item = std::ranges::find(items, fact); - if (item == items.end()) - throw IrError("fact store index is inconsistent"); - *item = updated; - }; - replace(facts_); - replace(byType_.at(fact->type)); - for (const auto &[indexedField, _] : fact->fields) - replace(byField_.at(indexedField)); - if (!hadField) - byField_[field].push_back(updated); + validateDeclaredIndexKeysLocked(updated); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + const auto source = persistentSnapshotLocked(fact->id).source; + const auto value = Form::encodeStoredFact( + *updated, + source ? std::optional{*source} + : std::optional{}, + symbolTable_); + std::vector mutation{ + {Form::RocksDb::Mutation::Kind::Put, storedFactKey(updated->id), + value}}; + const std::optional sourceView = + source ? std::optional{*source} + : std::optional{}; + for (auto &key : persistentIndexKeysLocked(current, sourceView)) + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); + for (auto &key : persistentIndexKeysLocked(updated, sourceView)) + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); + persistence_->commit(mutation); + } +#endif + if (!persistence_) { + removeFromDeclaredIndexesLocked(current); + const auto replace = [&](auto &items) { + const auto item = + std::find_if(items.begin(), items.end(), [&](const auto &entry) { + return entry->id == current->id; + }); + if (item == items.end()) + throw IrError("fact store index is inconsistent"); + *item = updated; + }; + replace(facts_); + replace(byType_.at(current->type)); + for (const auto &[indexedField, _] : current->fields) + replace(byField_.at(indexedField)); + if (!hadField) + byField_[field].push_back(updated); + addToDeclaredIndexesLocked(updated); + } mutations_.push_back(VmFactMutation{nextSequence_++, fact->id, field, VmFactMutationKind::Update}); provenance_.push_back(VmFactProvenance{ @@ -924,35 +1466,75 @@ VmFactPtr VmFactStore::mutate(const VmFactPtr &fact, IrSymbolRef field, std::size_t VmFactStore::erase(std::span facts) { std::lock_guard lock(mutex_); - std::unordered_set requested; - for (const auto &fact : facts) - if (fact && fact->id != 0) - requested.insert(fact->id); + std::unordered_map requested; + for (const auto &fact : facts) { + if (fact && fact->id != 0) { + const auto [entry, inserted] = requested.emplace(fact->id, fact); + if (!inserted) + requireMatchingSnapshot(entry->second, fact); + } + } if (requested.empty()) return 0; std::vector removed; - for (const auto &fact : facts_) { - if (requested.contains(fact->id)) - removed.push_back(fact); + std::unordered_map> removedSources; + if (persistence_) { + removed.reserve(requested.size()); + for (const auto &[id, requestedFact] : requested) { + auto stored = persistentSnapshotLocked(id); + requireMatchingSnapshot(stored.fact, requestedFact); + removed.push_back(std::move(stored.fact)); + removedSources.emplace(id, std::move(stored.source)); + } + } else { + for (const auto &fact : facts_) { + if (const auto found = requested.find(fact->id); found != requested.end()) { + requireMatchingSnapshot(fact, found->second); + removed.push_back(fact); + } + } } if (removed.size() != requested.size()) throw IrError("fact deletion targets a fact outside this knowledge runtime"); - const auto removeIds = [&](auto &items) { - std::erase_if(items, [&](const auto &item) { - return item && requested.contains(item->id); - }); - }; - removeIds(facts_); - for (auto &[_, items] : byType_) - removeIds(items); - for (auto &[_, items] : byField_) - removeIds(items); - std::erase_if(byType_, [](const auto &entry) { return entry.second.empty(); }); - std::erase_if(byField_, [](const auto &entry) { return entry.second.empty(); }); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + std::vector mutations; + mutations.reserve(removed.size()); + for (const auto &fact : removed) { + mutations.push_back({Form::RocksDb::Mutation::Kind::Erase, + storedFactKey(fact->id), {}}); + const auto &source = removedSources.at(fact->id); + const std::optional sourceView = + source ? std::optional{*source} + : std::optional{}; + for (auto &key : persistentIndexKeysLocked(fact, sourceView)) + mutations.push_back( + {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); + } + persistence_->commit(mutations); + } +#endif + if (!persistence_) { + for (const auto &fact : removed) + removeFromDeclaredIndexesLocked(fact); + const auto removeIds = [&](auto &items) { + std::erase_if(items, [&](const auto &item) { + return item && requested.contains(item->id); + }); + }; + removeIds(facts_); + for (auto &[_, items] : byType_) + removeIds(items); + for (auto &[_, items] : byField_) + removeIds(items); + std::erase_if(byType_, [](const auto &entry) { return entry.second.empty(); }); + std::erase_if(byField_, [](const auto &entry) { return entry.second.empty(); }); + } for (const auto &fact : removed) { - factSource_.erase(fact->id); + if (!persistence_) + factSource_.erase(fact->id); mutations_.push_back(VmFactMutation{nextSequence_++, fact->id, 0, VmFactMutationKind::Delete}); } @@ -967,23 +1549,54 @@ void VmFactStore::restore(const VmFactPtr ¤t, current->id != previous->id || current->type != previous->type) throw IrError("fact rollback snapshots are incompatible"); std::lock_guard lock(mutex_); - const auto replaceById = [&](auto &items) { - const auto found = std::find_if(items.begin(), items.end(), [&](const auto &item) { - return item && item->id == current->id; - }); - if (found == items.end()) - throw IrError("fact rollback target is absent"); - *found = previous; - }; - replaceById(facts_); - replaceById(byType_.at(current->type)); - for (auto &[_, items] : byField_) - std::erase_if(items, [&](const auto &item) { - return item && item->id == current->id; - }); - for (const auto &[field, _] : previous->fields) - byField_[field].push_back(previous); - std::erase_if(byField_, [](const auto &entry) { return entry.second.empty(); }); + const auto stored = currentSnapshotLocked(current); + validateDeclaredIndexKeysLocked(previous); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + const auto source = persistentSnapshotLocked(previous->id).source; + const auto value = Form::encodeStoredFact( + *previous, + source ? std::optional{*source} + : std::optional{}, + symbolTable_); + std::vector mutation{ + {Form::RocksDb::Mutation::Kind::Put, storedFactKey(previous->id), + value}}; + const std::optional sourceView = + source ? std::optional{*source} + : std::optional{}; + for (auto &key : persistentIndexKeysLocked(stored, sourceView)) + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); + for (auto &key : persistentIndexKeysLocked(previous, sourceView)) + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); + persistence_->commit(mutation); + } +#endif + if (!persistence_) { + removeFromDeclaredIndexesLocked(stored); + const auto replaceById = [&](auto &items) { + const auto found = + std::find_if(items.begin(), items.end(), [&](const auto &item) { + return item && item->id == current->id; + }); + if (found == items.end()) + throw IrError("fact rollback target is absent"); + *found = previous; + }; + replaceById(facts_); + replaceById(byType_.at(current->type)); + for (auto &[_, items] : byField_) + std::erase_if(items, [&](const auto &item) { + return item && item->id == current->id; + }); + for (const auto &[field, _] : previous->fields) + byField_[field].push_back(previous); + addToDeclaredIndexesLocked(previous); + std::erase_if(byField_, + [](const auto &entry) { return entry.second.empty(); }); + } ++contentRevision_; ++knowledgeRevision_; } @@ -993,36 +1606,86 @@ void VmFactStore::restoreErased(const VmFactPtr &fact, if (!fact || fact->id == 0) throw IrError("deleted fact rollback snapshot is invalid"); std::lock_guard lock(mutex_); - if (std::any_of(facts_.begin(), facts_.end(), [&](const auto &existing) { - return existing->id == fact->id; - })) + validateDeclaredIndexKeysLocked(fact); + if (persistence_) { +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_->database.get(storedFactKey(fact->id))) + throw IrError("deleted fact rollback would duplicate fact identity"); +#endif + } else if (std::any_of(facts_.begin(), facts_.end(), + [&](const auto &existing) { + return existing->id == fact->id; + })) { throw IrError("deleted fact rollback would duplicate fact identity"); - facts_.push_back(fact); - byType_[fact->type].push_back(fact); - for (const auto &[field, _] : fact->fields) - byField_[field].push_back(fact); - if (source) - factSource_[fact->id] = std::move(*source); - const auto order = [](auto &items) { - std::sort(items.begin(), items.end(), [](const auto &left, const auto &right) { - return left->createdSequence < right->createdSequence; - }); - }; - order(facts_); - order(byType_[fact->type]); - for (const auto &[field, _] : fact->fields) - order(byField_[field]); + } +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + const auto value = Form::encodeStoredFact( + *fact, + source ? std::optional{*source} + : std::optional{}, + symbolTable_); + std::vector mutation{ + {Form::RocksDb::Mutation::Kind::Put, storedFactKey(fact->id), value}}; + const std::optional sourceView = + source ? std::optional{*source} + : std::optional{}; + for (auto &key : persistentIndexKeysLocked(fact, sourceView)) + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); + persistence_->commit(mutation); + } +#endif + if (!persistence_) { + facts_.push_back(fact); + byType_[fact->type].push_back(fact); + for (const auto &[field, _] : fact->fields) + byField_[field].push_back(fact); + addToDeclaredIndexesLocked(fact); + if (source) + factSource_[fact->id] = std::move(*source); + const auto order = [](auto &items) { + std::sort(items.begin(), items.end(), + [](const auto &left, const auto &right) { + return left->createdSequence < right->createdSequence; + }); + }; + order(facts_); + order(byType_[fact->type]); + for (const auto &[field, _] : fact->fields) + order(byField_[field]); + } ++membershipRevision_; ++knowledgeRevision_; } std::vector VmFactStore::snapshot() const { std::lock_guard lock(mutex_); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + bool more = false; + auto result = persistentFactsLocked(std::string_view{"F", 1}, 10'001, &more); + if (more || result.size() > 10'000) + throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); + return result; + } +#endif return facts_; } std::vector VmFactStore::snapshot(IrSymbolRef type) const { std::lock_guard lock(mutex_); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + bool more = false; + auto result = persistentFactsLocked( + storedConcreteTypeIndexPrefix(irSymbolPieces(symbolTable_, type)), + 10'001, &more); + if (more || result.size() > 10'000) + throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); + return result; + } +#endif const auto found = byType_.find(type); return found == byType_.end() ? std::vector{} : found->second; } @@ -1031,17 +1694,48 @@ void VmFactStore::recordSource(IrFactRef fact, std::string source) { if (fact == 0) throw IrError("fact source cannot be recorded for an invalid fact"); std::lock_guard lock(mutex_); - const auto found = std::find_if( - facts_.begin(), facts_.end(), - [&](const auto &item) { return item->id == fact; }); - if (found == facts_.end()) - throw IrError( - "fact source recorded for a fact outside this knowledge runtime"); - factSource_[fact] = std::move(source); + VmFactPtr stored; + std::optional previousSource; + if (persistence_) { + auto record = persistentSnapshotLocked(fact); + stored = std::move(record.fact); + previousSource = std::move(record.source); + } else { + const auto found = std::find_if( + facts_.begin(), facts_.end(), + [&](const auto &item) { return item->id == fact; }); + if (found == facts_.end()) + throw IrError( + "fact source recorded for a fact outside this knowledge runtime"); + stored = *found; + } +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + const auto value = Form::encodeStoredFact( + *stored, std::optional{source}, symbolTable_); + std::vector mutation{ + {Form::RocksDb::Mutation::Kind::Put, storedFactKey(fact), value}}; + if (previousSource) { + auto key = storedSourceIndexPrefix(*previousSource); + appendFactOrder(key, *stored); + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); + } + auto key = storedSourceIndexPrefix(source); + appendFactOrder(key, *stored); + mutation.push_back( + {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); + persistence_->commit(mutation); + } +#endif + if (!persistence_) + factSource_[fact] = std::move(source); } std::optional VmFactStore::sourceOf(IrFactRef fact) const { std::lock_guard lock(mutex_); + if (persistence_) + return persistentSnapshotLocked(fact).source; const auto found = factSource_.find(fact); if (found == factSource_.end()) return std::nullopt; @@ -1051,6 +1745,26 @@ std::optional VmFactStore::sourceOf(IrFactRef fact) const { std::vector VmFactStore::sourcesForType(IrSymbolRef type) const { std::lock_guard lock(mutex_); std::set unique; +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + const auto prefix = + storedConcreteTypeIndexPrefix(irSymbolPieces(symbolTable_, type)); + std::optional after; + bool more = false; + do { + std::string lastKey; + const auto rows = persistentFactsLocked( + prefix, 4096, &more, + after ? std::optional{*after} : std::nullopt, + &lastKey); + for (const auto &fact : rows) + if (const auto source = persistentSnapshotLocked(fact->id).source) + unique.insert(*source); + after = std::move(lastKey); + } while (more && unique.size() < 2); + return {unique.begin(), unique.end()}; + } +#endif const auto found = byType_.find(type); if (found != byType_.end()) { for (const auto &fact : found->second) { @@ -1066,6 +1780,24 @@ std::vector VmFactStore::snapshotBySource(std::string_view source) const { std::lock_guard lock(mutex_); std::vector result; +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + const auto prefix = storedSourceIndexPrefix(source); + std::optional after; + bool more = false; + do { + std::string lastKey; + auto rows = persistentFactsLocked(prefix, 4096, &more, + after ? std::optional{*after} : std::nullopt, + &lastKey); + result.insert(result.end(), rows.begin(), rows.end()); + after = std::move(lastKey); + } while (more); + // File persistence rewrites the complete owning source, not a query page. + // Only that source's index is scanned; unrelated facts are never loaded. + return result; + } +#endif for (const auto &fact : facts_) { const auto found = factSource_.find(fact->id); if (found != factSource_.end() && found->second == source) @@ -1108,31 +1840,48 @@ VmFactStore::hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) const { std::vector> VmFactStore::hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor) const { constexpr std::size_t kMaximumProofPaths = 4096; + constexpr std::size_t kMaximumProofDepth = 4096; std::lock_guard lock(mutex_); if (child == 0 || ancestor == 0 || !isAssignableToLocked(child, ancestor)) return {}; std::vector> result; + struct Frame { + std::vector parents; + std::size_t next = 0; + }; + const auto frame = [&](IrSymbolRef current) { + Frame result; + if (const auto found = parents_.find(current); found != parents_.end()) + result.parents = found->second; + std::sort(result.parents.begin(), result.parents.end()); + return result; + }; std::vector path{child}; - const auto visit = [&](const auto &self, IrSymbolRef current) -> void { - if (result.size() == kMaximumProofPaths) - throw IrError("fact hierarchy proof-path limit exceeded"); - if (current == ancestor) { + std::vector stack{frame(child)}; + while (!path.empty()) { + if (path.size() > kMaximumProofDepth) + throw IrError("fact hierarchy proof depth exceeds its limit"); + if (path.back() == ancestor) { + if (result.size() == kMaximumProofPaths) + throw IrError("fact hierarchy proof-path limit exceeded"); result.push_back(path); - return; + path.pop_back(); + stack.pop_back(); + continue; } - const auto found = parents_.find(current); - if (found == parents_.end()) - return; - auto parents = found->second; - std::sort(parents.begin(), parents.end()); - for (const auto parent : parents) { - path.push_back(parent); - self(self, parent); + auto ¤t = stack.back(); + if (current.next == current.parents.size()) { path.pop_back(); + stack.pop_back(); + continue; } - }; - visit(visit, child); + const auto parent = current.parents[current.next++]; + if (std::ranges::find(path, parent) != path.end()) + throw IrError("fact hierarchy cycle reached proof enumeration"); + path.push_back(parent); + stack.push_back(frame(parent)); + } std::sort(result.begin(), result.end(), [](const auto &left, const auto &right) { if (left.size() != right.size()) @@ -1179,47 +1928,6 @@ VmFactStore::commonAncestorEvidence(IrSymbolRef left, return result; } -std::vector -VmFactStore::leastCommonAncestors(IrSymbolRef left, IrSymbolRef right) const { - const auto common = commonAncestors(left, right); - std::vector result; - for (const auto candidate : common) { - bool hasMoreSpecificCommon = false; - for (const auto other : common) { - if (candidate == other) - continue; - if (!hierarchyProof(other, candidate).empty()) { - hasMoreSpecificCommon = true; - break; - } - } - if (!hasMoreSpecificCommon) - result.push_back(candidate); - } - return result; -} - -std::vector -VmFactStore::mostGeneralCommonAncestors(IrSymbolRef left, - IrSymbolRef right) const { - const auto common = commonAncestors(left, right); - std::vector result; - for (const auto candidate : common) { - bool hasMoreGeneralCommon = false; - for (const auto other : common) { - if (candidate == other) - continue; - if (!hierarchyProof(candidate, other).empty()) { - hasMoreGeneralCommon = true; - break; - } - } - if (!hasMoreGeneralCommon) - result.push_back(candidate); - } - return result; -} - std::vector VmFactStore::rankByTimeAndPriority(IrSymbolRef effectiveAtField, IrSymbolRef priorityField) const { @@ -1240,8 +1948,12 @@ VmFactStore::rankByTimeAndPriority(IrSymbolRef effectiveAtField, return *number; }; std::vector ranked; - ranked.reserve(facts_.size()); - for (const auto &fact : facts_) + const auto candidates = persistence_ ? persistentFactsLocked( + std::string_view{"F", 1}, 10'001) : facts_; + if (candidates.size() > 10'000) + throw IrError("fact ranking exceeds 10000 rows; filter before ranking"); + ranked.reserve(candidates.size()); + for (const auto &fact : candidates) ranked.push_back({fact, numberField(fact, effectiveAtField, "effective-at"), numberField(fact, priorityField, "priority")}); std::sort(ranked.begin(), ranked.end(), @@ -1258,6 +1970,17 @@ VmFactStore::rankByTimeAndPriority(IrSymbolRef effectiveAtField, std::vector VmFactStore::snapshotAssignableTo(IrSymbolRef type) const { std::lock_guard lock(mutex_); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + bool more = false; + auto result = persistentFactsLocked( + storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)), 10'001, + &more); + if (more || result.size() > 10'000) + throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); + return result; + } +#endif std::vector result; for (const auto &[candidate, facts] : byType_) { if (isAssignableToLocked(candidate, type)) @@ -1272,6 +1995,233 @@ VmFactStore::snapshotAssignableTo(IrSymbolRef type) const { return result; } +VmFactStore::Page VmFactStore::pageAssignableTo( + IrSymbolRef type, std::size_t records, + const std::optional &after) const { + return pageMatching(type, {}, records, after); +} + +VmFactStore::Page VmFactStore::pageMatching( + IrSymbolRef type, + std::span> predicates, + std::size_t records, const std::optional &after) const { + if (records > 10'000) + throw IrError("fact page exceeds the 10000 row limit"); + std::lock_guard lock(mutex_); +#ifdef FELIDAE_HAS_ROCKSDB + if (!persistence_) + throw IrError("indexed fact pagination requires a RocksDB store"); + const auto plan = equalityPlanLocked(type, predicates); + auto prefix = storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)); + if (plan.index) { + prefix = storedExactIndexPrefix(irSymbolPieces(symbolTable_, plan.owner), + declaredIndexes_.at(plan.owner), plan.ordinal, symbolTable_); + appendOrderedKey(prefix, predicateIndexKey(plan.index->fields, plan.covered, + predicates, symbolTable_)); + } + // Bind residual predicates and requested subtype as well as the physical + // index. Canonical map encoding makes argument order irrelevant. + auto predicateMap = std::make_shared(); + predicateMap->entries.assign(predicates.begin(), predicates.end()); + std::string query; + appendPieceKey(query, irSymbolPieces(symbolTable_, type)); + appendOrderedKey(query, Form::encodeStoredValueKey(predicateMap, symbolTable_)); + const auto identity = persistence_->database.identity(); + if (after) { + if (after->database != identity || after->index != prefix || + after->query != query) + throw IrError("fact cursor belongs to another database or query index"); + if (after->revision != persistence_->revision) + throw IrError("fact cursor snapshot expired after a store mutation"); + // A partially covered composite key also contains remaining field values. + if (after->lastKey.size() < prefix.size() + 16 || + !after->lastKey.starts_with(prefix) || + !persistence_->database.get(after->lastKey)) + throw IrError("fact cursor has an invalid continuation key"); + } + Page result; + result.revision = persistence_->revision; + std::optional lastKey = after + ? std::optional{after->lastKey} : std::nullopt; + std::optional continuation = lastKey; + // One lookahead matching row establishes hasMore. Residual filtering is + // bounded independently of output size, so sparse queries cannot run forever. + std::size_t examined = 0; + while (!result.hasMore) { + std::vector keys; + const auto count = std::min(256, records - result.rows.size() + 1); + const auto rows = persistentFactsLocked(prefix, count, nullptr, + lastKey ? std::optional{*lastKey} : std::nullopt, + nullptr, &keys); + if (rows.empty()) + break; + for (std::size_t i = 0; i < rows.size(); ++i) { + if (++examined > 10'001) + throw IrError("fact page candidate limit exceeded; use a more selective index"); + lastKey = keys[i]; + if (!matchesLocked(rows[i], type, predicates)) + continue; + if (result.rows.size() == records) { + result.hasMore = true; + break; + } + result.rows.push_back(rows[i]); + continuation = keys[i]; + } + } + if (result.hasMore && continuation) + result.next = Cursor{identity, prefix, query, std::move(*continuation), + result.revision}; + return result; +#else + (void)type; + (void)predicates; + (void)after; + throw IrError("this VM build has no RocksDB fact-store support"); +#endif +} + +VmFactStore::EqualityPlan VmFactStore::equalityPlanLocked( + IrSymbolRef type, + std::span> predicates) const { + if (!parents_.contains(type)) + throw IrError("fact query references an unregistered type"); + std::unordered_set predicateFields; + for (const auto &[field, value] : predicates) { + if (field == 0 || !predicateFields.insert(field).second || + !validVmValue(value)) + throw IrError("fact query contains an invalid or duplicate predicate"); + } + + EqualityPlan plan; + for (const auto &[owner, indexes] : exactIndexes_) { + if (!isAssignableToLocked(type, owner)) + continue; + for (std::size_t ordinal = 0; ordinal < indexes.size(); ++ordinal) { + const auto &index = indexes[ordinal]; + std::size_t covered = 0; + while (covered < index.fields.size() && + predicateFields.contains(index.fields[covered])) + ++covered; + const auto winsTie = [&] { + if (!plan.index || covered != plan.covered || + index.fields.size() != plan.index->fields.size()) + return false; + // Runtime handles may change when a database is reopened. Durable + // plans must break equal-coverage ties by canonical index identity, + // never unordered-map iteration or process-local symbol numbering. + if (persistence_) + return storedExactIndexPrefix(irSymbolPieces(symbolTable_, owner), + declaredIndexes_.at(owner), ordinal, symbolTable_) < + storedExactIndexPrefix(irSymbolPieces(symbolTable_, plan.owner), + declaredIndexes_.at(plan.owner), plan.ordinal, symbolTable_); + return std::pair{owner, ordinal} < std::pair{plan.owner, plan.ordinal}; + }; + if (covered != 0 && + (covered > plan.covered || + (covered == plan.covered && plan.index && + index.fields.size() < plan.index->fields.size()) || winsTie())) { + plan = {&index, owner, ordinal, covered}; + } + } + } + return plan; +} + +std::vector VmFactStore::snapshotMatching( + IrSymbolRef type, + std::span> predicates) const { + constexpr std::size_t kMaximumUnindexedScan = 10'000; + if (predicates.empty()) + throw IrError("fact query requires at least one predicate"); + std::lock_guard lock(mutex_); + const auto plan = equalityPlanLocked(type, predicates); + const auto *selected = plan.index; + const auto selectedFields = plan.covered; + + std::vector candidates; + if (selected) { + const auto prefix = predicateIndexKey(selected->fields, selectedFields, + predicates, symbolTable_); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + auto storagePrefix = storedExactIndexPrefix( + irSymbolPieces(symbolTable_, plan.owner), + declaredIndexes_.at(plan.owner), plan.ordinal, symbolTable_); + appendOrderedKey(storagePrefix, prefix); + bool more = false; + candidates = persistentFactsLocked(storagePrefix, 10'001, &more); + if (more || candidates.size() > 10'000) + throw IrError( + "fact query exceeds 10000 rows; use page(records:, after:)"); + } else +#endif + if (selectedFields == selected->fields.size()) { + const auto found = selected->rows.find(prefix); + if (found != selected->rows.end()) + candidates = found->second; + } else { + for (auto found = selected->rows.lower_bound(prefix); + found != selected->rows.end() && found->first.size() >= prefix.size() && + std::equal(prefix.begin(), prefix.end(), found->first.begin()); + ++found) { + candidates.insert(candidates.end(), found->second.begin(), + found->second.end()); + } + } + } else { + const auto oversizedScan = [] { + throw IrError("fact query exceeds the bounded unindexed scan; declare " + "an index covering its equality fields"); + }; +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + bool more = false; + candidates = persistentFactsLocked( + storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)), + kMaximumUnindexedScan + 1, &more); + if (more || candidates.size() > kMaximumUnindexedScan) + oversizedScan(); + } else +#endif + { + for (const auto &[candidateType, rows] : byType_) { + if (!isAssignableToLocked(candidateType, type)) + continue; + // Bound before copying, not after allocating the entire candidate set. + if (rows.size() > kMaximumUnindexedScan - candidates.size()) + oversizedScan(); + candidates.insert(candidates.end(), rows.begin(), rows.end()); + } + } + } + + std::erase_if(candidates, [&](const auto &fact) { + return !matchesLocked(fact, type, predicates); + }); + std::sort(candidates.begin(), candidates.end(), + [](const auto &left, const auto &right) { + if (left->createdSequence != right->createdSequence) + return left->createdSequence < right->createdSequence; + return left->id < right->id; + }); + return candidates; +} + +bool VmFactStore::matchesLocked( + const VmFactPtr &fact, IrSymbolRef type, + std::span> predicates) const { + if (!fact || !isAssignableToLocked(fact->type, type)) + return false; + return std::all_of(predicates.begin(), predicates.end(), + [&](const auto &predicate) { + const auto found = std::find_if(fact->fields.begin(), fact->fields.end(), + [&](const auto &entry) { return entry.first == predicate.first; }); + return found != fact->fields.end() && + vmValuesEqualInternal(found->second, predicate.second); + }); +} + std::vector VmFactStore::parentsOf(IrSymbolRef type) const { std::lock_guard lock(mutex_); const auto found = parents_.find(type); @@ -1281,6 +2231,17 @@ std::vector VmFactStore::parentsOf(IrSymbolRef type) const { std::vector VmFactStore::snapshotByField(IrSymbolRef field) const { std::lock_guard lock(mutex_); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + bool more = false; + auto result = persistentFactsLocked( + storedFieldIndexPrefix(irSymbolPieces(symbolTable_, field)), 10'001, + &more); + if (more || result.size() > 10'000) + throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); + return result; + } +#endif const auto found = byField_.find(field); return found == byField_.end() ? std::vector{} : found->second; } @@ -1321,15 +2282,42 @@ void VmFactStore::refreshKnowledgeSnapshot(std::uint64_t &knownRevision, if (knownRevision == knowledgeRevision_) return; result = {}; - result.factTypes.reserve(byType_.size()); - result.factTypeCounts.reserve(byType_.size()); - for (const auto &[type, facts] : byType_) { - result.factTypes.push_back(type); - result.factTypeCounts.emplace_back( - type, - static_cast(std::min( - facts.size(), static_cast( - std::numeric_limits::max())))); + if (persistence_) { +#ifdef FELIDAE_HAS_ROCKSDB + for (const auto &[type, _] : parents_) { + const auto prefix = storedConcreteTypeIndexPrefix( + irSymbolPieces(symbolTable_, type)); + std::optional after; + std::uint64_t count = 0; + bool more = false; + do { + const auto page = persistence_->database.scanPrefix( + prefix, + after ? std::optional{*after} : std::nullopt, + Form::RocksDb::maximumScanRecords); + count += page.rows.size(); + more = page.hasMore; + if (!page.rows.empty()) + after = page.rows.back().first; + } while (more && count <= std::numeric_limits::max()); + if (count == 0) + continue; + result.factTypes.push_back(type); + result.factTypeCounts.emplace_back( + type, static_cast(std::min( + count, std::numeric_limits::max()))); + } +#endif + } else { + result.factTypes.reserve(byType_.size()); + result.factTypeCounts.reserve(byType_.size()); + for (const auto &[type, facts] : byType_) { + result.factTypes.push_back(type); + result.factTypeCounts.emplace_back( + type, static_cast(std::min( + facts.size(), static_cast( + std::numeric_limits::max())))); + } } std::sort(result.factTypes.begin(), result.factTypes.end()); std::sort(result.factTypeCounts.begin(), result.factTypeCounts.end()); @@ -1348,6 +2336,26 @@ VmFactStoreRevisions VmFactStore::revisions() const { std::size_t VmFactStore::size() const { std::lock_guard lock(mutex_); +#ifdef FELIDAE_HAS_ROCKSDB + if (persistence_) { + std::optional after; + std::size_t count = 0; + bool more = false; + do { + const auto page = persistence_->database.scanPrefix( + std::string_view{"F", 1}, + after ? std::optional{*after} : std::nullopt, + Form::RocksDb::maximumScanRecords); + if (page.rows.size() > std::numeric_limits::max() - count) + throw IrError("fact store size exceeds this platform's range"); + count += page.rows.size(); + more = page.hasMore; + if (!page.rows.empty()) + after = page.rows.back().first; + } while (more); + return count; + } +#endif return facts_.size(); } @@ -1800,19 +2808,12 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( if (closeness == range || (query.has_value() != tolerance.has_value())) throw IrError( "fact search degree requires query+tolerance or range bounds"); - const auto requireDegree = [](double value, std::string_view name) { - if (value < 0.0 || value > 1.0) - throw IrError("fact search " + std::string(name) + - " must be within [0.0, 1.0]"); - }; - if (query) - requireDegree(*query, "query"); - if (tolerance) - requireDegree(*tolerance, "tolerance"); - if (minimum) - requireDegree(*minimum, "minimum"); - if (maximum) - requireDegree(*maximum, "maximum"); + // "degree" selects numeric closeness/range discovery; it is not an + // implicit truth conversion. Ordinary number fields therefore retain the + // language's unrestricted finite-double domain. VmDegree values remain + // bounded by their own constructor/type contract. + if (tolerance && *tolerance < 0.0) + throw IrError("fact search tolerance must be non-negative"); if (minimum && maximum && *minimum > *maximum) throw IrError("fact search degree minimum exceeds maximum"); appendMatching([&](const VmValue &value) { @@ -1821,8 +2822,7 @@ VmValue FelidaeKnowledgeRuntime::searchFacts( candidate = *number; else if (const auto degree = std::get_if(&value)) candidate = degree->value; - if (!candidate || !std::isfinite(*candidate) || *candidate < 0.0 || - *candidate > 1.0) + if (!candidate || !std::isfinite(*candidate)) return false; if (closeness) return std::fabs(*candidate - *query) <= *tolerance; @@ -1864,6 +2864,12 @@ VmValue FelidaeKnowledgeRuntime::joinFacts( }; auto result = std::make_shared(); std::vector matchedRight(right.size(), false); + std::map> rightIndex; + for (std::size_t index = 0; index < right.size(); ++index) { + if (const auto *value = read(right[index], rightKey)) + rightIndex[Form::encodeStoredValueKey(*value, runtimeSymbolTable())] + .push_back(index); + } const auto append = [&](VmValue leftValue, VmValue rightValue) { auto joined = std::make_shared(); joined->type = joinedType; @@ -1874,14 +2880,21 @@ VmValue FelidaeKnowledgeRuntime::joinFacts( for (const auto &leftFact : left) { const auto *leftValue = read(leftFact, leftKey); bool matchedLeft = false; - for (std::size_t index = 0; leftValue && index < right.size(); ++index) { - const auto &rightFact = right[index]; - const auto *rightValue = read(rightFact, rightKey); - if (!rightValue || !vmValuesEqual(*leftValue, *rightValue)) - continue; - matchedLeft = true; - matchedRight[index] = true; - append(leftFact, rightFact); + if (leftValue) { + const auto found = rightIndex.find( + Form::encodeStoredValueKey(*leftValue, runtimeSymbolTable())); + if (found != rightIndex.end()) { + for (const auto index : found->second) { + // The canonical key is designed to agree with structural equality; + // retain the authoritative equality check at this trust boundary. + const auto *rightValue = read(right[index], rightKey); + if (!rightValue || !vmValuesEqual(*leftValue, *rightValue)) + continue; + matchedLeft = true; + matchedRight[index] = true; + append(leftFact, right[index]); + } + } } if (!matchedLeft && (kind == 1 || kind == 3)) append(leftFact, VmNil{}); @@ -1905,6 +2918,12 @@ FelidaeKnowledgeRuntime::snapshotFacts(IrSymbolRef type) { return factStore_->snapshotAssignableTo(type); } +std::vector FelidaeKnowledgeRuntime::snapshotMatchingFacts( + IrSymbolRef type, + std::span> predicates) { + return factStore_->snapshotMatching(type, predicates); +} + std::vector FelidaeKnowledgeRuntime::hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) { @@ -1965,16 +2984,6 @@ VmValue FelidaeKnowledgeRuntime::ancestorAnalysis(IrSymbolRef left, } return result; } -std::vector -FelidaeKnowledgeRuntime::leastCommonAncestors(IrSymbolRef left, - IrSymbolRef right) { - return factStore_->leastCommonAncestors(left, right); -} -std::vector -FelidaeKnowledgeRuntime::mostGeneralCommonAncestors(IrSymbolRef left, - IrSymbolRef right) { - return factStore_->mostGeneralCommonAncestors(left, right); -} std::vector FelidaeKnowledgeRuntime::rankFacts(IrSymbolRef effectiveAtField, IrSymbolRef priorityField) { @@ -1985,29 +2994,13 @@ void FelidaeKnowledgeRuntime::installIrModule(const IrModule &module) { module_ = {}; module_.symbolTable = module.symbolTable; module_.runtimeSymbols.reserve(module.symbolTable.size()); - for (const auto &pieces : module.symbolTable) { - const auto found = runtimeSymbolIds_.find(pieces); - if (found != runtimeSymbolIds_.end()) { - module_.runtimeSymbols.push_back(found->second); - continue; - } + for (const auto &pieces : module.symbolTable) module_.runtimeSymbols.push_back(internRuntimeSymbol(pieces)); - } } IrSymbolRef FelidaeKnowledgeRuntime::internRuntimeSymbol(PieceSequence pieces) { - const auto found = runtimeSymbolIds_.find(pieces); - if (found != runtimeSymbolIds_.end()) - return found->second; - if (runtimeSymbolTable_.size() == - static_cast(std::numeric_limits::max())) { - throw IrError("runtime symbol table exhausted its ID space"); - } - runtimeSymbolTable_.push_back(std::move(pieces)); - const auto symbol = static_cast(runtimeSymbolTable_.size()); - runtimeSymbolIds_.emplace(runtimeSymbolTable_.back(), symbol); - return symbol; + return factStore_->internSymbol(std::move(pieces)); } IrSymbolRef @@ -2021,7 +3014,7 @@ FelidaeKnowledgeRuntime::resolveSymbol(IrSymbolRef moduleSymbol) const { std::span FelidaeKnowledgeRuntime::runtimeSymbolTable() const { - return runtimeSymbolTable_; + return factStore_->symbolTable(); } void FelidaeKnowledgeRuntime::enterProcedure( @@ -2131,9 +3124,8 @@ VmValue FelidaeKnowledgeRuntime::importCsvFacts( std::span data, std::span type, std::span source) { const auto typePieces = encodeText(decodeText(type)); - const auto knownType = runtimeSymbolIds_.find(typePieces); - if (knownType == runtimeSymbolIds_.end() || - !registeredFactTypes_.contains(knownType->second)) { + const auto knownType = factStore_->findSymbol(typePieces); + if (!knownType || !registeredFactTypes_.contains(*knownType)) { throw IrError("csv.toFacts type must be declared in the IR module"); } @@ -2152,7 +3144,7 @@ VmValue FelidaeKnowledgeRuntime::importCsvFacts( if (!row.is_object()) throw IrError("csv.toFacts requires object rows"); auto fact = std::make_shared(); - fact->type = knownType->second; + fact->type = *knownType; fact->origin = VmFact::Origin::Asserted; fact->fields.reserve(row.size()); for (const auto &[name, value] : row.items()) { @@ -2178,7 +3170,7 @@ double FelidaeKnowledgeRuntime::persistDatabaseSource( // whole store, and never inferred from fact type alone, since two // different files can share one fact type (see VmFactStore::recordSource). Form::Db::sync(std::filesystem::path(source), - factStore_->snapshotBySource(source), runtimeSymbolTable_, + factStore_->snapshotBySource(source), factStore_->symbolTable(), decoder, emptySchema, [this](IrSymbolRef type) { return factStore_->parentsOf(type); @@ -2209,7 +3201,7 @@ FelidaeKnowledgeRuntime::makeRuntimeContext(const VmValue &) const { context.maximumSemanticSteps = maximumSemanticSteps_; context.executionState = executionState_; context.sharedSemanticSteps = sharedSemanticSteps_; - context.symbolTable = &runtimeSymbolTable_; + context.symbolTable = &factStore_->symbolTable(); factStore_->refreshKnowledgeSnapshot(context.knowledgeRevision, context.knowledge); return context; @@ -2322,6 +3314,15 @@ void IrVerifier::verify(const FelidaeIr &ir) { initialized[ir.words[pc + 1]] = true; pc += 10; break; + case IrOpcode::FactWhere: + requireRegister(ir, ir.words[pc + 1]); + if (ir.words[pc + 2] >= ir.symbols.size()) + throw IrError("IR fact where references an invalid type symbol"); + requireRegister(ir, ir.words[pc + 3]); + requireInitialized(initialized, ir.words[pc + 3]); + initialized[ir.words[pc + 1]] = true; + pc += 4; + break; case IrOpcode::Add: case IrOpcode::Sub: case IrOpcode::Mul: @@ -2338,8 +3339,6 @@ void IrVerifier::verify(const FelidaeIr &ir) { case IrOpcode::Similarity: case IrOpcode::HierarchyIsA: case IrOpcode::HierarchyCommonAncestors: - case IrOpcode::HierarchyLeastCommonAncestors: - case IrOpcode::HierarchyMostGeneralAncestors: requireRegister(ir, ir.words[pc + 1]); requireRegister(ir, ir.words[pc + 2]); requireRegister(ir, ir.words[pc + 3]); @@ -2663,6 +3662,11 @@ void VmRuntime::registerFactType(IrSymbolRef, std::vector, std::vector VmRuntime::snapshotFacts(IrSymbolRef) { throw IrError("IR fact iteration is unavailable in this runtime"); } +std::vector VmRuntime::snapshotMatchingFacts( + IrSymbolRef, + std::span>) { + throw IrError("IR indexed fact queries are unavailable in this runtime"); +} std::vector VmRuntime::hierarchyProof(IrSymbolRef, IrSymbolRef) { throw IrError("IR hierarchy is unavailable in this runtime"); @@ -2681,14 +3685,6 @@ VmRuntime::commonAncestorEvidence(IrSymbolRef, IrSymbolRef) { VmValue VmRuntime::ancestorAnalysis(IrSymbolRef, IrSymbolRef) { throw IrError("IR hierarchy is unavailable in this runtime"); } -std::vector VmRuntime::leastCommonAncestors(IrSymbolRef, - IrSymbolRef) { - throw IrError("IR hierarchy is unavailable in this runtime"); -} -std::vector VmRuntime::mostGeneralCommonAncestors(IrSymbolRef, - IrSymbolRef) { - throw IrError("IR hierarchy is unavailable in this runtime"); -} std::vector VmRuntime::rankFacts(IrSymbolRef, IrSymbolRef) { throw IrError("IR temporal ranking is unavailable in this runtime"); } @@ -3351,6 +4347,20 @@ VmValue RegisterVm::executeIrProgram(const IrModule &module, number(2), {number(3), number(4), number(5)})); break; } + case IrOpcode::FactWhere: { + const auto predicates = + std::get_if(®isters.at(program.words.at(pc + 3))); + if (!predicates || !*predicates || (*predicates)->entries.empty()) + throw IrError("IR fact where requires a non-empty predicate map"); + const auto facts = runtime.snapshotMatchingFacts( + symbol(program.words.at(pc + 2)), (*predicates)->entries); + auto values = std::make_shared(); + values->values.reserve(facts.size()); + for (const auto &fact : facts) + values->values.emplace_back(fact); + registers.at(program.words.at(pc + 1)) = std::move(values); + break; + } case IrOpcode::ForEachFact: { const auto facts = runtime.snapshotFacts(symbol(program.words.at(pc + 2))); @@ -3441,18 +4451,6 @@ VmValue RegisterVm::executeIrProgram(const IrModule &module, typeSymbol(registers.at(program.words.at(pc + 2))), typeSymbol(registers.at(program.words.at(pc + 3))))); break; - case IrOpcode::HierarchyLeastCommonAncestors: - registers.at(program.words.at(pc + 1)) = - symbolArray(runtime.leastCommonAncestors( - typeSymbol(registers.at(program.words.at(pc + 2))), - typeSymbol(registers.at(program.words.at(pc + 3))))); - break; - case IrOpcode::HierarchyMostGeneralAncestors: - registers.at(program.words.at(pc + 1)) = - symbolArray(runtime.mostGeneralCommonAncestors( - typeSymbol(registers.at(program.words.at(pc + 2))), - typeSymbol(registers.at(program.words.at(pc + 3))))); - break; case IrOpcode::TemporalRank: { const auto ranked = runtime.rankFacts(symbol(program.words.at(pc + 2)), symbol(program.words.at(pc + 3))); diff --git a/src/form/RegisterVm.h b/src/form/RegisterVm.h index 0b84a06..c44583a 100644 --- a/src/form/RegisterVm.h +++ b/src/form/RegisterVm.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -234,12 +235,26 @@ struct VmCommonAncestorEvidence { std::size_t rightDistance = 0; }; -// Process-resident append-only fact memory. It belongs to the Form runtime, -// not to AST/parser services, and is shared by repeated VM executions in a -// daemon. Type and field indexes are authoritative; callers must not mutate a -// retained fact directly. +// Process-resident fact storage used by the portable runtime. It belongs to +// Form, not to AST/parser services, and is shared by repeated VM executions in +// a daemon. Mutations go through this owner so fact identity, creation order, +// indexes, provenance, source ownership, and revisions stay synchronized. +// A disk-backed implementation must preserve this contract; this class alone +// is not presented as trillion-scale storage. class VmFactStore { public: + VmFactStore(); + explicit VmFactStore(const std::filesystem::path &directory); + ~VmFactStore(); + VmFactStore(const VmFactStore &) = delete; + VmFactStore &operator=(const VmFactStore &) = delete; + // Numeric symbol references are process-local handles. The complete + // SentencePiece sequence stored here is their authoritative identity and + // is what a durable backend encodes. + IrSymbolRef internSymbol(PieceSequence pieces); + std::optional + findSymbol(std::span pieces) const; + const std::vector &symbolTable() const noexcept; void registerType(IrSymbolRef type, std::vector parents, std::vector> indexes = {}); VmFactPtr retain(const VmFactPtr &fact); @@ -253,6 +268,33 @@ class VmFactStore { std::vector snapshot() const; std::vector snapshot(IrSymbolRef type) const; std::vector snapshotAssignableTo(IrSymbolRef type) const; + // Storage continuation metadata, not a VM query-object value. Any committed + // mutation expires the cursor. Keys and database identity survive reopening. + struct Cursor { + std::string database; + std::string index; + std::string query; + std::string lastKey; + std::uint64_t revision = 0; + }; + struct Page { + std::vector rows; + std::optional next; + bool hasMore = false; + std::uint64_t revision = 0; + }; + Page pageAssignableTo(IrSymbolRef type, std::size_t records, + const std::optional &after = std::nullopt) const; + Page pageMatching(IrSymbolRef type, + std::span> predicates, + std::size_t records, + const std::optional &after = std::nullopt) const; + // Plans exact predicates against the widest fully-covered declared index. + // Small unindexed stores may use a bounded scan; large stores fail with an + // actionable index diagnostic instead of silently becoming unbounded. + std::vector snapshotMatching( + IrSymbolRef type, + std::span> predicates) const; std::vector parentsOf(IrSymbolRef type) const; std::vector hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) const; @@ -262,10 +304,6 @@ class VmFactStore { IrSymbolRef right) const; std::vector commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right) const; - std::vector leastCommonAncestors(IrSymbolRef left, - IrSymbolRef right) const; - std::vector mostGeneralCommonAncestors(IrSymbolRef left, - IrSymbolRef right) const; // Sorts facts by descending effective time, then descending priority, // then stable fact identity. Missing/non-numeric fields are rejected. std::vector @@ -306,19 +344,63 @@ class VmFactStore { const VmGaussianProfile &profile); private: + class Persistence; + struct StoredSnapshot { + VmFactPtr fact; + std::optional source; + }; + IrSymbolRef internSymbolLocked(PieceSequence pieces) const; + StoredSnapshot persistentSnapshotLocked(IrFactRef fact) const; + VmFactPtr currentSnapshotLocked(const VmFactPtr &snapshot) const; const std::unordered_set & ancestorClosureLocked(IrSymbolRef type) const; bool isAssignableToLocked(IrSymbolRef candidate, IrSymbolRef expected) const; + void validateDeclaredIndexKeysLocked(const VmFactPtr &fact) const; + void addToDeclaredIndexesLocked(const VmFactPtr &fact); + void removeFromDeclaredIndexesLocked(const VmFactPtr &fact); + std::vector persistentIndexKeysLocked( + const VmFactPtr &fact, + std::optional source = std::nullopt) const; + std::vector persistentFactsLocked( + std::string_view prefix, std::size_t maximum, + bool *hasMore = nullptr, + std::optional after = std::nullopt, + std::string *lastKey = nullptr, + std::vector *keys = nullptr) const; + + struct ExactIndex { + std::vector fields; + // Rows belong only to the memory backend. RocksDB stores retain the + // declaration for shared planning but load candidates from durable keys. + std::map, std::vector> rows; + }; + struct EqualityPlan { + const ExactIndex *index = nullptr; + IrSymbolRef owner = 0; + std::size_t ordinal = 0; + std::size_t covered = 0; + }; + EqualityPlan equalityPlanLocked( + IrSymbolRef type, + std::span> predicates) const; + bool matchesLocked( + const VmFactPtr &fact, IrSymbolRef type, + std::span> predicates) const; mutable std::mutex mutex_; + std::unique_ptr persistence_; + mutable std::map symbolIds_; + mutable std::vector symbolTable_; IrFactRef nextId_ = 1; std::uint64_t nextSequence_ = 1; std::vector facts_; std::unordered_map> byType_; + // Memory backend only; persistent field-presence lookups use the IF index. std::unordered_map> byField_; std::unordered_map> parents_; std::unordered_map>> declaredIndexes_; + std::unordered_map> exactIndexes_; std::unordered_map factSource_; std::vector mutations_; std::vector provenance_; @@ -415,6 +497,9 @@ class VmRuntime { std::vector parents, std::vector> indexes = {}); virtual std::vector snapshotFacts(IrSymbolRef type); + virtual std::vector snapshotMatchingFacts( + IrSymbolRef type, + std::span> predicates); virtual std::vector hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor); virtual std::vector> @@ -424,10 +509,6 @@ class VmRuntime { virtual std::vector commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right); virtual VmValue ancestorAnalysis(IrSymbolRef left, IrSymbolRef right); - virtual std::vector leastCommonAncestors(IrSymbolRef left, - IrSymbolRef right); - virtual std::vector - mostGeneralCommonAncestors(IrSymbolRef left, IrSymbolRef right); virtual std::vector rankFacts(IrSymbolRef effectiveAtField, IrSymbolRef priorityField); // Modules are independently verified before this hook. A long-lived @@ -504,6 +585,9 @@ class FelidaeKnowledgeRuntime final : public VmRuntime { std::vector parents, std::vector> indexes = {}) override; std::vector snapshotFacts(IrSymbolRef type) override; + std::vector snapshotMatchingFacts( + IrSymbolRef type, + std::span> predicates) override; std::vector hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) override; std::vector> @@ -513,10 +597,6 @@ class FelidaeKnowledgeRuntime final : public VmRuntime { std::vector commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right) override; VmValue ancestorAnalysis(IrSymbolRef left, IrSymbolRef right) override; - std::vector leastCommonAncestors(IrSymbolRef left, - IrSymbolRef right) override; - std::vector - mostGeneralCommonAncestors(IrSymbolRef left, IrSymbolRef right) override; std::vector rankFacts(IrSymbolRef effectiveAtField, IrSymbolRef priorityField) override; void installIrModule(const IrModule &module) override; @@ -561,14 +641,12 @@ class FelidaeKnowledgeRuntime final : public VmRuntime { std::unordered_map globals; std::vector symbolTable; // One entry per module-local symbol. Values are one-based indexes into - // runtimeSymbolTable_, which remains stable across installed modules. + // VmFactStore's symbol table, which remains stable across installed modules. std::vector runtimeSymbols; }; // Module globals are process-resident knowledge-runtime state. Registers, // call frames and recurrent state are deliberately excluded. VmModuleState module_; - std::map runtimeSymbolIds_; - std::vector runtimeSymbolTable_; std::unordered_set registeredFactTypes_; std::shared_ptr factStore_; RuntimeStateModel *semanticModel_ = nullptr; diff --git a/src/form/RuntimeStateModel.cpp b/src/form/RuntimeStateModel.cpp index c55b307..5d3b9a2 100644 --- a/src/form/RuntimeStateModel.cpp +++ b/src/form/RuntimeStateModel.cpp @@ -4,6 +4,9 @@ #include "RuntimeTraining.h" #include "SemanticOperation.h" #include "../ModelStore.h" +#ifdef FELIDAE_HAS_FAISS +#include "libs/ExecutionVectorMemory.h" +#endif #include #include @@ -33,10 +36,9 @@ std::vector runtimeInputIds( }; const auto appendValueTokens = [&](std::vector &ids, const auto &tokens) { - constexpr std::uint32_t kStructuralBit = 0x80000000u; for (const auto token : tokens) { - if ((token & kStructuralBit) != 0) { - const auto marker = token & ~kStructuralBit; + if ((token & kRuntimeStructuralEncodingBit) != 0) { + const auto marker = token & ~kRuntimeStructuralEncodingBit; if (marker >= kRuntimeStructuralInputTokens) throw IrError("runtime GRU value marker exceeds its vocabulary"); ids.push_back(structural(marker)); @@ -60,9 +62,12 @@ std::vector runtimeInputIds( ids.push_back(piece); } }; - const auto kFactTypesMarker = structural(8); - const auto kHierarchyMarker = structural(9); - const auto kInputsMarker = structural(10); + const auto marker = [&](RuntimeStructuralToken token) { + return structural(static_cast(token)); + }; + const auto kFactTypesMarker = marker(RuntimeStructuralToken::FactTypes); + const auto kHierarchyMarker = marker(RuntimeStructuralToken::Hierarchy); + const auto kInputsMarker = marker(RuntimeStructuralToken::Inputs); if (!isKnownSemanticOperation(operation) || !semanticOperationAcceptsArity(operation, inputKinds.size()) || (!inputValues.empty() && inputValues.size() != inputKinds.size()) || @@ -100,10 +105,10 @@ std::vector runtimeInputIds( appendPieces(ids, type); // Counts distinguish current fact population while keeping a fixed // integer vocabulary: one, two-to-four, and five-or-more facts. - const auto kFactCountsMarker = structural(11); - const auto kOneFactMarker = structural(12); - const auto kSeveralFactsMarker = structural(13); - const auto kManyFactsMarker = structural(14); + const auto kFactCountsMarker = marker(RuntimeStructuralToken::FactCounts); + const auto kOneFactMarker = marker(RuntimeStructuralToken::OneFact); + const auto kSeveralFactsMarker = marker(RuntimeStructuralToken::SeveralFacts); + const auto kManyFactsMarker = marker(RuntimeStructuralToken::ManyFacts); ids.push_back(kFactCountsMarker); for (const auto &[type, count] : factTypeCounts) { appendPieces(ids, type); @@ -121,7 +126,9 @@ std::vector runtimeInputIds( if (kind < RuntimeValueKind::Nil || kind > RuntimeValueKind::TextMap) { throw IrError("runtime GRU input value kind is invalid"); } - ids.push_back(structural(15 + static_cast(kind))); + ids.push_back(structural( + static_cast(RuntimeStructuralToken::InputKindBase) + + static_cast(kind))); } for (const auto &value : inputValues) appendValueTokens(ids, value); @@ -177,6 +184,9 @@ class GruRuntimeStateModel::Implementation { }; struct ExecutionState { torch::Tensor hidden; +#ifdef FELIDAE_HAS_FAISS + std::unique_ptr vectors; +#endif }; explicit Implementation(const Configuration &c, const std::filesystem::path &artifact) { @@ -388,6 +398,16 @@ Value GruRuntimeStateModel::evaluate(const RuntimeOperation &operation, logits = implementation_->network->projection->forward(last); score = implementation_->network->scoreProjection->forward(last); } +#ifdef FELIDAE_HAS_FAISS + // Flatten all recurrent layers from this evaluation, not token IDs or + // projected scores. Faiss copies the data; no tensor/autograd graph is held. + const auto vector = state->hidden.to(torch::kCPU, torch::kFloat32).contiguous(); + const auto dimensions = static_cast(vector.numel()); + if (!state->vectors) + state->vectors = std::make_unique( + dimensions, context.maximumSemanticSteps); + state->vectors->append({vector.data_ptr(), dimensions}); +#endif if (operation.id == static_cast(SemanticOperationId::Suggest)) { const auto value = score.item(); if (!std::isfinite(value)) @@ -416,8 +436,6 @@ Value GruRuntimeStateModel::evaluate(const RuntimeOperation &operation, return inferred; } case RuntimeOutputTokenKind::DegreeMilli: - if (operation.id == static_cast(SemanticOperationId::Suggest)) - return static_cast(token.value) / 1000.0; return VmDegree(static_cast(token.value) / 1000.0); case RuntimeOutputTokenKind::Nil: return VmNil{}; diff --git a/src/form/RuntimeTraining.cpp b/src/form/RuntimeTraining.cpp index 53a3b99..dd7d7a2 100644 --- a/src/form/RuntimeTraining.cpp +++ b/src/form/RuntimeTraining.cpp @@ -18,10 +18,6 @@ namespace { using Json = nlohmann::json; constexpr std::size_t kMaximumRecords = 1'000'000; constexpr std::size_t kMaximumItems = 1'000'000; -constexpr std::uint32_t kStructuralEncodingBit = 0x80000000u; -constexpr std::uint32_t structural(std::uint32_t marker) { - return kStructuralEncodingBit | marker; -} void requireJsonlPath(const std::filesystem::path &path) { if (path.extension() != ".jsonl") @@ -249,57 +245,62 @@ runtimeValueEncoding(const VmValue &value, return order; }; const auto appendNumber = [&](double number, std::uint32_t marker) { - result.push_back(structural(marker)); + result.push_back(kRuntimeStructuralEncodingBit | marker); const auto bits = std::bit_cast(number); for (int bit = 63; bit >= 0; --bit) - result.push_back(structural((bits & (std::uint64_t{1} << bit)) ? 39 : 38)); + result.push_back(runtimeStructuralToken( + (bits & (std::uint64_t{1} << bit)) + ? RuntimeStructuralToken::NumberBitOne + : RuntimeStructuralToken::NumberBitZero)); }; const auto append = [&](const auto &self, const VmValue &item, std::size_t depth) -> void { if (depth > 32 || result.size() > kMaximumEncodedTokens) throw IrError("runtime SSM value encoding exceeds its bound"); if (std::holds_alternative(item)) { - result.push_back(structural(28)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Nil)); } else if (const auto number = std::get_if(&item)) { - appendNumber(*number, 29); + appendNumber(*number, + static_cast(RuntimeStructuralToken::Number)); } else if (const auto degree = std::get_if(&item)) { - appendNumber(degree->value, 30); + appendNumber(degree->value, + static_cast(RuntimeStructuralToken::Degree)); } else if (const auto text = std::get_if(&item)) { - result.push_back(structural(31)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Text)); result.insert(result.end(), text->pieces.begin(), text->pieces.end()); } else if (const auto symbol = std::get_if(&item)) { - result.push_back(structural(32)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Symbol)); appendSymbol(symbol->value); } else if (const auto array = std::get_if(&item)) { if (!*array) throw IrError("runtime SSM cannot encode a null array"); - result.push_back(structural(33)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Array)); for (const auto &value : (*array)->values) self(self, value, depth + 1); - result.push_back(structural(27)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); } else if (const auto map = std::get_if(&item)) { if (!*map) throw IrError("runtime SSM cannot encode a null map"); - result.push_back(structural(34)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Map)); for (const auto index : orderedFields((*map)->entries)) { const auto &[field, value] = (*map)->entries[index]; - result.push_back(structural(40)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Field)); appendSymbol(field); self(self, value, depth + 1); } - result.push_back(structural(27)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); } else if (const auto fact = std::get_if(&item)) { if (!*fact) throw IrError("runtime SSM cannot encode a null fact"); - result.push_back(structural(35)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Fact)); appendSymbol((*fact)->type); for (const auto index : orderedFields((*fact)->fields)) { const auto &[field, value] = (*fact)->fields[index]; - result.push_back(structural(40)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Field)); appendSymbol(field); self(self, value, depth + 1); } - result.push_back(structural(27)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); } else if (const auto tensor = std::get_if(&item)) { if (!*tensor || !(*tensor)->storage) throw IrError("runtime SSM cannot encode a null tensor"); @@ -308,25 +309,25 @@ runtimeValueEncoding(const VmValue &value, } else if (const auto map = std::get_if(&item)) { if (!*map) throw IrError("runtime SSM cannot encode a null text map"); - result.push_back(structural(37)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::TextMap)); auto entries = (*map)->entries; std::sort(entries.begin(), entries.end(), [](const auto &left, const auto &right) { return left.first < right.first; }); for (const auto &[key, value] : entries) { - result.push_back(structural(40)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Field)); result.insert(result.end(), key.begin(), key.end()); self(self, value, depth + 1); } - result.push_back(structural(27)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); } if (result.size() > kMaximumEncodedTokens) throw IrError("runtime SSM value encoding exceeds its bound"); }; - result.push_back(structural(26)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueStart)); append(append, value, 0); - result.push_back(structural(27)); + result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); return result; } diff --git a/src/form/RuntimeTraining.h b/src/form/RuntimeTraining.h index 668817b..bc34a6e 100644 --- a/src/form/RuntimeTraining.h +++ b/src/form/RuntimeTraining.h @@ -2,11 +2,49 @@ #include "RegisterVm.h" +#include #include #include namespace Felidae { +// Structural tokens share the runtime model's input vocabulary with raw +// SentencePiece IDs. Encoded values set the high bit; RuntimeStateModel +// relocates the low marker into the reserved vocabulary tail. Keep this list +// authoritative for both dataset generation and live inference. +inline constexpr std::uint32_t kRuntimeStructuralEncodingBit = 0x80000000u; +enum class RuntimeStructuralToken : std::uint32_t { + FactTypes = 8, + Hierarchy = 9, + Inputs = 10, + FactCounts = 11, + OneFact = 12, + SeveralFacts = 13, + ManyFacts = 14, + InputKindBase = 15, + ValueStart = 26, + ValueEnd = 27, + Nil = 28, + Number = 29, + Degree = 30, + Text = 31, + Symbol = 32, + Array = 33, + Map = 34, + Fact = 35, + TextMap = 37, + NumberBitZero = 38, + NumberBitOne = 39, + Field = 40, +}; + +constexpr std::uint32_t runtimeStructuralToken(RuntimeStructuralToken token) { + return kRuntimeStructuralEncodingBit | + static_cast(token); +} +static_assert(static_cast(RuntimeStructuralToken::Field) < 48, + "runtime structural token exceeds the reserved vocabulary"); + // Stable semantic actions produced by the finite runtime GRU vocabulary. // This is deliberately not VmValue::index() or a model-logit index. enum class RuntimeTrainingTargetKind : std::uint8_t { @@ -53,7 +91,7 @@ RuntimeKnowledgePieces runtimeKnowledgePieces( const VmKnowledgeSnapshot& knowledge, std::span symbolTable); -// JSON Lines v8: one self-describing, integer-only record per line. The +// JSON Lines v9: one self-describing record per line. The // schema value is repeated deliberately: lines can be validated or streamed // independently and no legacy binary header needs to be retained. inline constexpr std::uint32_t kRuntimeTrainingSchemaVersion = 9; diff --git a/src/form/libs/ExecutionVectorMemory.cpp b/src/form/libs/ExecutionVectorMemory.cpp new file mode 100644 index 0000000..ef4b4bf --- /dev/null +++ b/src/form/libs/ExecutionVectorMemory.cpp @@ -0,0 +1,45 @@ +#include "ExecutionVectorMemory.h" + +#include "form/IrModule.h" +#include + +#include +#include +#include + +namespace Felidae::Form { + +class ExecutionVectorMemory::Implementation { +public: + Implementation(std::size_t dimensions, std::size_t maximum) + : index(static_cast(dimensions)), capacity(maximum) {} + faiss::IndexFlatL2 index; + std::size_t capacity; +}; + +ExecutionVectorMemory::ExecutionVectorMemory(std::size_t dimensions, + std::size_t capacity) { + if (dimensions == 0 || dimensions > static_cast( + std::numeric_limits::max()) || capacity == 0 || + capacity > std::numeric_limits::max() / sizeof(float) / dimensions) + throw IrError("invalid execution vector memory dimensions or capacity"); + implementation_ = std::make_unique(dimensions, capacity); +} + +ExecutionVectorMemory::~ExecutionVectorMemory() = default; + +void ExecutionVectorMemory::append(std::span state) { + auto &memory = *implementation_; + if (state.size() != static_cast(memory.index.d) || + !std::all_of(state.begin(), state.end(), [](float v) { return std::isfinite(v); })) + throw IrError("execution hidden state has invalid dimensions or non-finite values"); + if (size() == memory.capacity) + throw IrError("execution vector memory reached its semantic-step capacity"); + memory.index.add(1, state.data()); +} + +std::size_t ExecutionVectorMemory::size() const { + return static_cast(implementation_->index.ntotal); +} + +} // namespace Felidae::Form diff --git a/src/form/libs/ExecutionVectorMemory.h b/src/form/libs/ExecutionVectorMemory.h new file mode 100644 index 0000000..e66ddc4 --- /dev/null +++ b/src/form/libs/ExecutionVectorMemory.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +namespace Felidae::Form { + +// Owns real numeric hidden-state vectors, never facts or SentencePiece IDs. +// One instance belongs to one execution; there is no serialization or global +// cache. Destroying it releases every retained vector. No training is needed. +class ExecutionVectorMemory { +public: + ExecutionVectorMemory(std::size_t dimensions, std::size_t capacity); + ~ExecutionVectorMemory(); + ExecutionVectorMemory(const ExecutionVectorMemory &) = delete; + ExecutionVectorMemory &operator=(const ExecutionVectorMemory &) = delete; + void append(std::span state); + std::size_t size() const; + +private: + class Implementation; + std::unique_ptr implementation_; +}; + +} // namespace Felidae::Form diff --git a/src/form/libs/FactStorageCodec.cpp b/src/form/libs/FactStorageCodec.cpp new file mode 100644 index 0000000..92c3822 --- /dev/null +++ b/src/form/libs/FactStorageCodec.cpp @@ -0,0 +1,438 @@ +#include "form/libs/FactStorageCodec.h" + +#include "form/IrModule.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae::Form { +namespace { + +using Json = nlohmann::ordered_json; +constexpr std::size_t kMaximumStorageDepth = 64; +constexpr std::size_t kMaximumStorageItems = 1'000'000; +constexpr std::uint64_t kFactStorageVersion = 1; +constexpr std::uint64_t kFactTypeStorageVersion = 1; + +void appendValueKey(const VmValue &value, + std::span symbols, + StoredValueKey &key, std::size_t depth = 0) { + if (depth > kMaximumStorageDepth) + throw IrError("fact index key exceeds its nesting limit"); + key.push_back(static_cast(runtimeValueKind(value))); + const auto appendSize = [&](std::size_t size) { + key.push_back(static_cast(size)); + }; + const auto appendPieces = [&](std::span value) { + appendSize(value.size()); + for (const auto piece : value) + key.push_back(static_cast(piece)); + }; + const auto appendEntries = [&](const auto &entries) { + std::vector order(entries.size()); + std::iota(order.begin(), order.end(), 0); + std::sort(order.begin(), order.end(), [&](std::size_t left, + std::size_t right) { + // Field order must survive a different symbol-interning order after + // reopening storage. Only SentencePiece sequences define that order. + if constexpr (std::is_same_v< + std::remove_cvref_t, + PieceSequence>) { + return entries[left].first < entries[right].first; + } else { + const auto a = irSymbolPieces(symbols, entries[left].first); + const auto b = irSymbolPieces(symbols, entries[right].first); + return std::lexicographical_compare(a.begin(), a.end(), + b.begin(), b.end()); + } + }); + appendSize(order.size()); + for (const auto index : order) { + const auto &[field, item] = entries[index]; + if constexpr (std::is_same_v, + PieceSequence>) + appendPieces(field); + else + appendPieces(irSymbolPieces(symbols, field)); + appendValueKey(item, symbols, key, depth + 1); + } + }; + if (std::holds_alternative(value)) + return; + if (const auto number = std::get_if(&value)) { + if (!std::isfinite(*number)) + throw IrError("fact index key must be finite"); + key.push_back(std::bit_cast(*number == 0.0 ? 0.0 : *number)); + return; + } + if (const auto degree = std::get_if(&value)) { + key.push_back(std::bit_cast(degree->value)); + return; + } + if (const auto text = std::get_if(&value)) { + appendPieces(text->pieces); + return; + } + if (const auto symbol = std::get_if(&value)) { + appendPieces(irSymbolPieces(symbols, symbol->value)); + return; + } + if (const auto array = std::get_if(&value)) { + if (!*array) + throw IrError("fact index key contains a null array"); + appendSize((*array)->values.size()); + for (const auto &item : (*array)->values) + appendValueKey(item, symbols, key, depth + 1); + return; + } + if (const auto map = std::get_if(&value)) { + if (!*map) + throw IrError("fact index key contains a null map"); + appendEntries((*map)->entries); + return; + } + if (const auto fact = std::get_if(&value)) { + if (!*fact) + throw IrError("fact index key contains a null fact"); + appendPieces(irSymbolPieces(symbols, (*fact)->type)); + appendEntries((*fact)->fields); + return; + } + if (std::holds_alternative(value)) + throw IrError("tensor values cannot be fact index keys"); + const auto &map = std::get(value); + if (!map) + throw IrError("fact index key contains a null text map"); + appendEntries(map->entries); +} + +Json pieces(std::span value) { + Json result = Json::array(); + for (const auto piece : value) + result.push_back(piece); + return result; +} + +// CBOR is an external boundary: JSON numeric conversions otherwise truncate +// fractions and narrow oversized integers before the caller can validate them. +std::uint64_t readUnsigned(const Json &value, + std::uint64_t maximum = UINT64_MAX) { + if (!value.is_number_integer() || + (!value.is_number_unsigned() && value.get() < 0)) + throw IrError("stored fact contains an invalid unsigned integer"); + const auto number = value.get(); + if (number > maximum) + throw IrError("stored fact integer is outside its range"); + return number; +} + +PieceSequence readPieces(const Json &value, bool allowEmpty = false) { + if (!value.is_array() || (!allowEmpty && value.empty()) || + value.size() > kMaximumStorageItems) + throw IrError("stored fact contains an invalid SentencePiece sequence"); + PieceSequence result; + result.reserve(value.size()); + for (const auto &piece : value) { + const auto number = readUnsigned(piece, std::numeric_limits::max()); + result.push_back(static_cast(number)); + } + return result; +} + +Json encodeValue(const VmValue &value, + std::span symbols, std::size_t depth); + +Json encodeEntries( + std::span> entries, + std::span symbols, std::size_t depth) { + if (entries.size() > kMaximumStorageItems) + throw IrError("fact storage entry count exceeds its limit"); + Json result = Json::array(); + for (const auto &[field, value] : entries) + result.push_back( + Json::array({pieces(irSymbolPieces(symbols, field)), + encodeValue(value, symbols, depth + 1)})); + return result; +} + +Json encodeFact(const VmFact &fact, std::span symbols, + std::size_t depth) { + if (fact.type == 0) + throw IrError("fact storage cannot encode an untyped fact"); + return Json::array( + {fact.id, pieces(irSymbolPieces(symbols, fact.type)), + static_cast(fact.origin), fact.createdSequence, + encodeEntries(fact.fields, symbols, depth)}); +} + +Json encodeValue(const VmValue &value, + std::span symbols, std::size_t depth) { + if (depth > kMaximumStorageDepth) + throw IrError("fact storage value nesting exceeds its limit"); + const auto kind = runtimeValueKind(value); + switch (kind) { + case RuntimeValueKind::Nil: + return Json::array({static_cast(kind)}); + case RuntimeValueKind::Number: { + const auto number = std::get(value); + if (!std::isfinite(number)) + throw IrError("fact storage cannot encode a non-finite number"); + return Json::array({static_cast(kind), number}); + } + case RuntimeValueKind::Degree: + return Json::array({static_cast(kind), + std::get(value).value}); + case RuntimeValueKind::Text: + return Json::array({static_cast(kind), + pieces(std::get(value).pieces)}); + case RuntimeValueKind::Symbol: + return Json::array( + {static_cast(kind), + pieces(irSymbolPieces(symbols, std::get(value).value))}); + case RuntimeValueKind::Array: { + const auto &array = std::get(value); + if (!array || array->values.size() > kMaximumStorageItems) + throw IrError("fact storage cannot encode an invalid array"); + Json items = Json::array(); + for (const auto &item : array->values) + items.push_back(encodeValue(item, symbols, depth + 1)); + return Json::array({static_cast(kind), std::move(items)}); + } + case RuntimeValueKind::Map: { + const auto &map = std::get(value); + if (!map) + throw IrError("fact storage cannot encode an invalid map"); + return Json::array({static_cast(kind), + encodeEntries(map->entries, symbols, depth)}); + } + case RuntimeValueKind::Fact: { + const auto &fact = std::get(value); + if (!fact) + throw IrError("fact storage cannot encode an invalid nested fact"); + return Json::array({static_cast(kind), + encodeFact(*fact, symbols, depth + 1)}); + } + case RuntimeValueKind::TextMap: { + const auto &map = std::get(value); + if (!map || map->entries.size() > kMaximumStorageItems) + throw IrError("fact storage cannot encode an invalid text map"); + Json entries = Json::array(); + for (const auto &[field, item] : map->entries) + entries.push_back(Json::array( + {pieces(field), encodeValue(item, symbols, depth + 1)})); + return Json::array({static_cast(kind), std::move(entries)}); + } + case RuntimeValueKind::Tensor: + throw IrError("fact storage cannot persist a LibTorch tensor value"); + } + throw IrError("fact storage encountered an unknown value kind"); +} + +void requireArray(const Json &value, std::size_t size, + std::string_view description) { + if (!value.is_array() || value.size() != size) + throw IrError("stored fact has invalid " + std::string(description)); +} + +VmValue decodeValue(const Json &value, const StoredSymbolInterner &intern, + std::size_t depth); + +std::vector> +decodeEntries(const Json &value, const StoredSymbolInterner &intern, + std::size_t depth) { + if (!value.is_array() || value.size() > kMaximumStorageItems) + throw IrError("stored fact has an invalid field collection"); + std::vector> result; + result.reserve(value.size()); + for (const auto &entry : value) { + requireArray(entry, 2, "field entry"); + result.emplace_back(intern(readPieces(entry[0])), + decodeValue(entry[1], intern, depth + 1)); + } + return result; +} + +VmFactPtr decodeFact(const Json &value, const StoredSymbolInterner &intern, + std::size_t depth) { + requireArray(value, 5, "fact record"); + auto fact = std::make_shared(); + fact->id = readUnsigned(value[0], std::numeric_limits::max()); + fact->type = intern(readPieces(value[1])); + const auto origin = readUnsigned(value[2], + static_cast(VmFact::Origin::Derived)); + fact->origin = static_cast(origin); + fact->createdSequence = readUnsigned(value[3]); + fact->fields = decodeEntries(value[4], intern, depth); + return fact; +} + +VmValue decodeValue(const Json &value, const StoredSymbolInterner &intern, + std::size_t depth) { + if (depth > kMaximumStorageDepth || !value.is_array() || value.empty()) + throw IrError("stored fact contains an invalid nested value"); + const auto kind = static_cast(readUnsigned(value[0], UINT8_MAX)); + switch (kind) { + case RuntimeValueKind::Nil: + requireArray(value, 1, "nil value"); + return VmNil{}; + case RuntimeValueKind::Number: { + requireArray(value, 2, "number value"); + const auto number = value[1].get(); + if (!std::isfinite(number)) + throw IrError("stored fact contains a non-finite number"); + return number; + } + case RuntimeValueKind::Degree: + requireArray(value, 2, "degree value"); + return VmDegree(value[1].get()); + case RuntimeValueKind::Text: + requireArray(value, 2, "text value"); + return VmText{readPieces(value[1], true)}; + case RuntimeValueKind::Symbol: + requireArray(value, 2, "symbol value"); + return VmSymbol{intern(readPieces(value[1]))}; + case RuntimeValueKind::Array: { + requireArray(value, 2, "array value"); + if (!value[1].is_array() || value[1].size() > kMaximumStorageItems) + throw IrError("stored fact contains an invalid array"); + auto result = std::make_shared(); + result->values.reserve(value[1].size()); + for (const auto &item : value[1]) + result->values.push_back(decodeValue(item, intern, depth + 1)); + return result; + } + case RuntimeValueKind::Map: { + requireArray(value, 2, "map value"); + auto result = std::make_shared(); + result->entries = decodeEntries(value[1], intern, depth); + return result; + } + case RuntimeValueKind::Fact: + requireArray(value, 2, "nested fact value"); + return decodeFact(value[1], intern, depth + 1); + case RuntimeValueKind::TextMap: { + requireArray(value, 2, "text-map value"); + if (!value[1].is_array() || value[1].size() > kMaximumStorageItems) + throw IrError("stored fact contains an invalid text map"); + auto result = std::make_shared(); + result->entries.reserve(value[1].size()); + for (const auto &entry : value[1]) { + requireArray(entry, 2, "text-map entry"); + result->entries.emplace_back( + readPieces(entry[0], true), decodeValue(entry[1], intern, depth + 1)); + } + return result; + } + case RuntimeValueKind::Tensor: + throw IrError("stored fact contains an unsupported tensor value"); + } + throw IrError("stored fact contains an unknown value kind"); +} + +} // namespace + +StoredValueKey encodeStoredValueKey( + const VmValue &value, std::span symbols) { + StoredValueKey result; + appendValueKey(value, symbols, result); + return result; +} + +std::string encodeStoredFact(const VmFact &fact, + std::optional source, + std::span symbols) { + const Json record = Json::array( + {kFactStorageVersion, encodeFact(fact, symbols, 0), + source ? Json(*source) : Json(nullptr)}); + const auto bytes = Json::to_cbor(record); + return std::string(reinterpret_cast(bytes.data()), bytes.size()); +} + +StoredFactRecord decodeStoredFact(std::string_view bytes, + const StoredSymbolInterner &intern) { + if (!intern || bytes.empty()) + throw IrError("stored fact record is empty or has no symbol interner"); + try { + const auto *begin = reinterpret_cast(bytes.data()); + const Json record = Json::from_cbor(begin, begin + bytes.size()); + requireArray(record, 3, "storage envelope"); + if (readUnsigned(record[0]) != kFactStorageVersion) + throw IrError("stored fact schema version is unsupported"); + StoredFactRecord result; + result.fact = decodeFact(record[1], intern, 0); + if (!record[2].is_null()) + result.source = record[2].get(); + return result; + } catch (const IrError &) { + throw; + } catch (const std::exception &error) { + throw IrError("cannot decode stored fact record: " + + std::string(error.what())); + } +} + +std::string encodeStoredFactType( + IrSymbolRef type, std::span parents, + std::span> indexes, + std::span symbols) { + Json encodedParents = Json::array(); + for (const auto parent : parents) + encodedParents.push_back(pieces(irSymbolPieces(symbols, parent))); + Json encodedIndexes = Json::array(); + for (const auto &index : indexes) { + Json fields = Json::array(); + for (const auto field : index) + fields.push_back(pieces(irSymbolPieces(symbols, field))); + encodedIndexes.push_back(std::move(fields)); + } + const Json record = Json::array( + {kFactTypeStorageVersion, pieces(irSymbolPieces(symbols, type)), + std::move(encodedParents), std::move(encodedIndexes)}); + const auto bytes = Json::to_cbor(record); + return std::string(reinterpret_cast(bytes.data()), bytes.size()); +} + +StoredFactTypeRecord decodeStoredFactType( + std::string_view bytes, const StoredSymbolInterner &intern) { + if (!intern || bytes.empty()) + throw IrError("stored fact-type record is empty or has no symbol interner"); + try { + const auto *begin = reinterpret_cast(bytes.data()); + const Json record = Json::from_cbor(begin, begin + bytes.size()); + requireArray(record, 4, "fact-type storage envelope"); + if (readUnsigned(record[0]) != kFactTypeStorageVersion) + throw IrError("stored fact-type schema version is unsupported"); + StoredFactTypeRecord result; + result.type = intern(readPieces(record[1])); + if (!record[2].is_array() || record[2].size() > kMaximumStorageItems || + !record[3].is_array() || record[3].size() > kMaximumStorageItems) + throw IrError("stored fact-type metadata is invalid"); + for (const auto &parent : record[2]) + result.parents.push_back(intern(readPieces(parent))); + for (const auto &encodedIndex : record[3]) { + if (!encodedIndex.is_array() || encodedIndex.empty() || + encodedIndex.size() > kMaximumStorageItems) + throw IrError("stored fact-type index is invalid"); + std::vector index; + index.reserve(encodedIndex.size()); + for (const auto &field : encodedIndex) + index.push_back(intern(readPieces(field))); + result.indexes.push_back(std::move(index)); + } + return result; + } catch (const IrError &) { + throw; + } catch (const std::exception &error) { + throw IrError("cannot decode stored fact-type record: " + + std::string(error.what())); + } +} + +} // namespace Felidae::Form diff --git a/src/form/libs/FactStorageCodec.h b/src/form/libs/FactStorageCodec.h new file mode 100644 index 0000000..883a271 --- /dev/null +++ b/src/form/libs/FactStorageCodec.h @@ -0,0 +1,44 @@ +#pragma once + +#include "form/RegisterVm.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae::Form { + +struct StoredFactRecord { + VmFactPtr fact; + std::optional source; +}; + +struct StoredFactTypeRecord { + IrSymbolRef type = 0; + std::vector parents; + std::vector> indexes; +}; + +using StoredSymbolInterner = std::function; +using StoredValueKey = std::vector; + +StoredValueKey encodeStoredValueKey( + const VmValue &value, std::span symbols); + +std::string encodeStoredFact(const VmFact &fact, + std::optional source, + std::span symbols); +StoredFactRecord decodeStoredFact(std::string_view bytes, + const StoredSymbolInterner &intern); +std::string encodeStoredFactType( + IrSymbolRef type, std::span parents, + std::span> indexes, + std::span symbols); +StoredFactTypeRecord decodeStoredFactType( + std::string_view bytes, const StoredSymbolInterner &intern); + +} // namespace Felidae::Form diff --git a/src/form/libs/RocksDb.cpp b/src/form/libs/RocksDb.cpp new file mode 100644 index 0000000..f0fa299 --- /dev/null +++ b/src/form/libs/RocksDb.cpp @@ -0,0 +1,145 @@ +#include "form/libs/RocksDb.h" + +#include "form/IrModule.h" + +#include +#include +#include + +#include + +namespace Felidae::Form { +namespace { + +[[noreturn]] void fail(std::string_view operation, + const rocksdb::Status &status) { + throw IrError("RocksDB " + std::string(operation) + " failed: " + + status.ToString()); +} + +bool hasPrefix(std::string_view value, std::string_view prefix) { + return value.size() >= prefix.size() && + value.compare(0, prefix.size(), prefix) == 0; +} + +} // namespace + +class RocksDb::Implementation { +public: + std::unique_ptr database; +}; + +RocksDb::RocksDb(const std::filesystem::path &directory) + : implementation_(std::make_unique()) { + if (directory.empty()) + throw IrError("RocksDB directory must not be empty"); + std::error_code error; + std::filesystem::create_directories(directory, error); + if (error) + throw IrError("cannot create RocksDB directory: " + error.message()); + + rocksdb::Options options; + options.create_if_missing = true; + rocksdb::DB *database = nullptr; + const auto status = rocksdb::DB::Open(options, directory.string(), &database); + if (!status.ok()) + fail("open", status); + implementation_->database.reset(database); +} + +RocksDb::~RocksDb() = default; +RocksDb::RocksDb(RocksDb &&) noexcept = default; +RocksDb &RocksDb::operator=(RocksDb &&) noexcept = default; + +std::string RocksDb::identity() const { + std::string result; + const auto status = implementation_->database->GetDbIdentity(result); + if (!status.ok()) + fail("identity", status); + return result; +} + +std::optional RocksDb::get(std::string_view key) const { + if (key.empty()) + throw IrError("RocksDB key must not be empty"); + std::string value; + const auto status = implementation_->database->Get( + rocksdb::ReadOptions{}, rocksdb::Slice(key.data(), key.size()), &value); + if (status.IsNotFound()) + return std::nullopt; + if (!status.ok()) + fail("read", status); + return value; +} + +std::optional +RocksDb::integerProperty(std::string_view name) const { + if (name.empty()) + throw IrError("RocksDB property name must not be empty"); + std::uint64_t value = 0; + if (!implementation_->database->GetIntProperty( + rocksdb::Slice(name.data(), name.size()), &value)) + return std::nullopt; + return value; +} + +void RocksDb::write(std::span mutations) { + if (mutations.empty()) + return; + rocksdb::WriteBatch batch; + for (const auto &mutation : mutations) { + if (mutation.key.empty()) + throw IrError("RocksDB mutation key must not be empty"); + rocksdb::Status status; + if (mutation.kind == Mutation::Kind::Put) { + status = batch.Put(mutation.key, mutation.value); + } else { + status = batch.Delete(mutation.key); + } + if (!status.ok()) + fail("batch construction", status); + } + rocksdb::WriteOptions options; + options.sync = true; + const auto status = implementation_->database->Write(options, &batch); + if (!status.ok()) + fail("batch commit", status); +} + +RocksDb::Scan RocksDb::scanPrefix( + std::string_view prefix, std::optional after, + std::size_t records) const { + if (prefix.empty()) + throw IrError("RocksDB scan prefix must not be empty"); + if (after && !hasPrefix(*after, prefix)) + throw IrError("RocksDB cursor does not belong to the requested prefix"); + if (records > maximumScanRecords) + throw IrError("RocksDB scan record limit is too large"); + + rocksdb::ReadOptions options; + options.total_order_seek = false; + std::unique_ptr iterator( + implementation_->database->NewIterator(options)); + const auto seek = after.value_or(prefix); + iterator->Seek(rocksdb::Slice(seek.data(), seek.size())); + if (after && iterator->Valid() && iterator->key().ToStringView() == *after) + iterator->Next(); + + Scan result; + result.rows.reserve(records); + while (iterator->Valid() && + hasPrefix(iterator->key().ToStringView(), prefix)) { + if (result.rows.size() == records) { + result.hasMore = true; + break; + } + result.rows.emplace_back(iterator->key().ToString(), + iterator->value().ToString()); + iterator->Next(); + } + if (!iterator->status().ok()) + fail("scan", iterator->status()); + return result; +} + +} // namespace Felidae::Form diff --git a/src/form/libs/RocksDb.h b/src/form/libs/RocksDb.h new file mode 100644 index 0000000..39ac5b6 --- /dev/null +++ b/src/form/libs/RocksDb.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae::Form { + +// Thin ownership boundary around RocksDB. Higher VM layers own Felidae value +// encoding and index layout; this class owns only durable ordered bytes, +// atomic batches, and bounded keyset scans. +class RocksDb { +public: + // A maximum-size VM page plus one lookahead row. Larger reads must page. + static constexpr std::size_t maximumScanRecords = 10'001; + struct Mutation { + enum class Kind { Put, Erase } kind = Kind::Put; + std::string key; + std::string value; + }; + + struct Scan { + std::vector> rows; + bool hasMore = false; + }; + + explicit RocksDb(const std::filesystem::path &directory); + ~RocksDb(); + RocksDb(RocksDb &&) noexcept; + RocksDb &operator=(RocksDb &&) noexcept; + RocksDb(const RocksDb &) = delete; + RocksDb &operator=(const RocksDb &) = delete; + + std::optional get(std::string_view key) const; + std::optional integerProperty(std::string_view name) const; + std::string identity() const; + void write(std::span mutations); + Scan scanPrefix(std::string_view prefix, + std::optional after, + std::size_t records) const; + +private: + class Implementation; + std::unique_ptr implementation_; +}; + +} // namespace Felidae::Form diff --git a/tests/ExecutionVectorMemoryTest.cpp b/tests/ExecutionVectorMemoryTest.cpp new file mode 100644 index 0000000..5e512ea --- /dev/null +++ b/tests/ExecutionVectorMemoryTest.cpp @@ -0,0 +1,35 @@ +#include "form/libs/ExecutionVectorMemory.h" +#include "form/IrModule.h" + +#include +#include +#include + +int main() { + using Felidae::Form::ExecutionVectorMemory; + const auto rejects = [](auto action) { + try { action(); } catch (const Felidae::IrError &) { return true; } + return false; + }; + assert(rejects([] { ExecutionVectorMemory invalid(0, 2); })); + assert(rejects([] { ExecutionVectorMemory invalid(2, 0); })); + { + ExecutionVectorMemory first(2, 2), second(2, 2); + std::array state{-212.421f, 3.5f}; + first.append(state); + assert(first.size() == 1 && second.size() == 0); + assert(rejects([&] { first.append(std::span(state).first(1)); })); + for (const float invalid : {std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + state[0] = invalid; + assert(rejects([&] { first.append(state); })); + assert(first.size() == 1); + } + state = {0.0f, -0.25f}; + first.append(state); + assert(first.size() == 2); + assert(rejects([&] { first.append(state); })); + } + ExecutionVectorMemory nextExecution(2, 2); + assert(nextExecution.size() == 0); +} diff --git a/tests/FelidaeIrTest.cpp b/tests/FelidaeIrTest.cpp index 8a0204a..7c383b3 100644 --- a/tests/FelidaeIrTest.cpp +++ b/tests/FelidaeIrTest.cpp @@ -198,6 +198,8 @@ double executeKeyedEquality(bool facts) { using namespace Felidae; auto module = returning(encodeIrNumber(1.0), IrConstantKind::Number); module.symbolTable = {{1}, {2}, {3}}; + if (facts) + module.factTypes.push_back(IrFactType{.symbol = 1}); auto &program = module.procedures.at(1).ir; program.registerCount = 5; program.constants = { @@ -302,7 +304,7 @@ int main() { } VmFactStore hierarchy; - hierarchy.registerType(1, {}); + hierarchy.registerType(1, {}, {{10}}); hierarchy.registerType(2, {1}); hierarchy.registerType(3, {2}); hierarchy.registerType(3, {2}); @@ -325,9 +327,11 @@ int main() { const auto assignable = hierarchy.snapshotAssignableTo(1); assert(assignable.size() == 2); assert(assignable[0]->id < assignable[1]->id); + const std::array, 1> exact42{{{10, 42.0}}}; + assert(hierarchy.snapshotMatching(1, exact42) == + std::vector{indexedFact}); assert((hierarchy.hierarchyProof(3, 1) == std::vector{3, 2, 1})); assert((hierarchy.commonAncestors(2, 3) == std::vector{1, 2})); - assert((hierarchy.leastCommonAncestors(2, 3) == std::vector{2})); VmFactStore diamond; diamond.registerType(1, {}); @@ -346,8 +350,12 @@ int main() { assert((evidence[1].leftProofs == std::vector>{{4, 2}})); assert(evidence[1].leftDistance == 1 && evidence[1].rightDistance == 1); - assert((hierarchy.mostGeneralCommonAncestors(2, 3) == - std::vector{1})); + VmFactStore deepHierarchy; + deepHierarchy.registerType(1, {}); + for (IrSymbolRef type = 2; type <= 512; ++type) + deepHierarchy.registerType(type, {static_cast(type - 1)}); + const auto deepProofs = deepHierarchy.hierarchyProofs(512, 1); + assert(deepProofs.size() == 1 && deepProofs.front().size() == 512); // Prime the per-type closure before adding type 5. Registering hierarchy // edges must invalidate only that cache domain and expose the new path. assert(hierarchy.hierarchyProof(5, 1).empty()); @@ -391,8 +399,41 @@ int main() { assert(std::get(updatedIndexedFact->fields.front().second) == 44.0); assert(hierarchy.snapshotByField(10).front() == updatedIndexedFact); assert(hierarchy.snapshotAssignableTo(1).front() == updatedIndexedFact); + assert(hierarchy.snapshotMatching(1, exact42).empty()); + const std::array, 1> exact44{{{10, 44.0}}}; + assert(hierarchy.snapshotMatching(1, exact44) == + std::vector{updatedIndexedFact}); assert(rejects([&] { (void)hierarchy.mutate(indexedFact, 10, 45.0, 0); })); + VmFactStore compositeIndex; + compositeIndex.registerType(30, {}, {{31, 32}}); + compositeIndex.registerType(33, {30}); + auto compositeBuilder = std::make_shared(); + compositeBuilder->type = 30; + compositeBuilder->fields = {{31, 7.0}, {32, VmText{{9, 10}}}}; + const auto compositeFact = compositeIndex.retain(compositeBuilder); + const std::array, 2> compositePredicates{{ + {32, VmText{{9, 10}}}, {31, 7.0}}}; + assert(compositeIndex.snapshotMatching(30, compositePredicates) == + std::vector{compositeFact}); + const std::array, 1> prefixPredicate{{ + {31, 7.0}}}; + assert(compositeIndex.snapshotMatching(30, prefixPredicate) == + std::vector{compositeFact}); + auto inheritedBuilder = std::make_shared(); + inheritedBuilder->type = 33; + inheritedBuilder->fields = {{31, 7.0}, {32, VmText{{11}}}}; + const auto inheritedFact = compositeIndex.retain(inheritedBuilder); + assert(compositeIndex.snapshotMatching(33, prefixPredicate) == + std::vector{inheritedFact}); + assert(compositeIndex.snapshotMatching(30, prefixPredicate) == + (std::vector{compositeFact, inheritedFact})); + assert(compositeIndex.erase(std::array{compositeFact}) == 1); + assert(compositeIndex.snapshotMatching(30, compositePredicates).empty()); + compositeIndex.restoreErased(compositeFact, std::nullopt); + assert(compositeIndex.snapshotMatching(30, compositePredicates) == + std::vector{compositeFact}); + VmFactStore concurrentFacts; concurrentFacts.registerType(20, {}); auto concurrentBuilder = std::make_shared(); @@ -809,6 +850,17 @@ int main() { invalid.procedures.at(1).ir.words[1] = 99; assert(rejects([&] { (void)verifyIrModule(std::move(invalid)); })); + // Classes and ordinary facts share IrFactType, so the authoritative IR + // verifier must reject cycles across that mixed hierarchy just as it does + // cycles containing only one source declaration form. + auto cyclicTypes = returning(encodeIrNumber(1.0), IrConstantKind::Number); + cyclicTypes.symbolTable = {{1}, {2}, {3}}; + cyclicTypes.factTypes = { + IrFactType{.symbol = 2, .parents = {3}}, + IrFactType{.symbol = 3, .parents = {2}}, + }; + assert(rejects([&] { (void)verifyIrModule(std::move(cyclicTypes)); })); + IrModule loop; loop.sentencePieceModelIdentity = "sha256:test"; loop.symbolTable = {{1}}; diff --git a/tests/RocksDbTest.cpp b/tests/RocksDbTest.cpp new file mode 100644 index 0000000..d6ef865 --- /dev/null +++ b/tests/RocksDbTest.cpp @@ -0,0 +1,489 @@ +#include "form/libs/RocksDb.h" +#include "form/libs/FactStorageCodec.h" +#include + +#include +#include +#include +#include +#include +#include +#include + +int main() { + namespace fs = std::filesystem; + using Felidae::Form::RocksDb; + + // Corrupt CBOR numbers must not wrap/truncate into valid IDs or tags. + { + using Json = nlohmann::ordered_json; + Felidae::VmFact fact; + fact.type = 1; + fact.fields = {{1, 3.5}}; + const std::vector symbols{{11}}; + const auto bytes = Felidae::Form::encodeStoredFact(fact, std::nullopt, symbols); + const auto original = Json::from_cbor(bytes); + const auto rejectsRecord = [&](const Json &record) { + const auto encoded = Json::to_cbor(record); + try { + (void)Felidae::Form::decodeStoredFact( + std::string_view(reinterpret_cast(encoded.data()), encoded.size()), + [](Felidae::PieceSequence) { return Felidae::IrSymbolRef{1}; }); + } catch (const Felidae::IrError &) { return true; } + return false; + }; + for (const Json invalid : {Json(-1), Json(1.5), Json(true)}) { + for (const auto field : {0, 2, 3}) { + auto record = original; + record[1][field] = invalid; + assert(rejectsRecord(record)); + } + } + auto record = original; + record[1][2] = 256; + assert(rejectsRecord(record)); + record = original; + record[1][4][0][1][0] = original[1][4][0][1][0].get() + 256; + assert(rejectsRecord(record)); + record = original; + record[0] = 1.5; + assert(rejectsRecord(record)); + } + + // Reopening may intern symbols in another order. Equivalent nested fact + // keys must remain byte-for-byte identical across those runtime mappings. + { + const std::vector first{{90}, {10}, {20}}; + const std::vector second{{20}, {90}, {10}}; + auto left = std::make_shared(); + left->type = 1; + left->fields = {{2, 3.5}, {3, Felidae::VmSymbol{1}}}; + auto right = std::make_shared(); + right->type = 2; + right->fields = {{1, Felidae::VmSymbol{2}}, {3, 3.5}}; + assert(Felidae::Form::encodeStoredValueKey(Felidae::VmFactPtr{left}, first) == + Felidae::Form::encodeStoredValueKey(Felidae::VmFactPtr{right}, second)); + auto leftMap = std::make_shared(); + leftMap->entries = left->fields; + auto rightMap = std::make_shared(); + rightMap->entries = right->fields; + assert(Felidae::Form::encodeStoredValueKey(leftMap, first) == + Felidae::Form::encodeStoredValueKey(rightMap, second)); + } + + const fs::path database = + fs::path(FELIDAE_TEST_OUTPUT_DIR) / "ordered-driver.rocksdb"; + std::error_code error; + fs::remove_all(database, error); + assert(!error); + + { + RocksDb store(database); + const std::vector symbols{{11}, {12, 13}, {14}}; + auto nested = std::make_shared(); + nested->type = 1; + nested->fields = {{2, Felidae::VmText{{21, 22}}}}; + Felidae::VmFact fact; + fact.id = 42; + fact.type = 1; + fact.createdSequence = 7; + fact.origin = Felidae::VmFact::Origin::Derived; + auto values = std::make_shared(); + auto emptyKeyMap = std::make_shared(); + emptyKeyMap->entries = {{Felidae::PieceSequence{}, Felidae::VmText{}}}; + values->values = {-212.421, Felidae::VmDegree(0.75), + Felidae::VmFactPtr{nested}, Felidae::VmText{}, emptyKeyMap}; + fact.fields = {{2, values}, {3, Felidae::VmSymbol{1}}}; + const auto encoded = Felidae::Form::encodeStoredFact( + fact, std::string_view("facts/source.fx"), symbols); + const std::vector parents{3}; + const std::vector> indexes{{2}, {2, 3}}; + const auto encodedType = Felidae::Form::encodeStoredFactType( + 1, parents, indexes, symbols); + const std::vector initial{ + {RocksDb::Mutation::Kind::Put, "fact/type/A/0001", "one"}, + {RocksDb::Mutation::Kind::Put, "fact/type/A/0002", "two"}, + {RocksDb::Mutation::Kind::Put, "fact/type/A/0003", "three"}, + {RocksDb::Mutation::Kind::Put, "fact/type/B/0001", "other"}, + {RocksDb::Mutation::Kind::Put, "record/00000042", encoded}, + {RocksDb::Mutation::Kind::Put, "type/primary", encodedType}, + }; + store.write(initial); + assert(store.get("fact/type/A/0002") == "two"); + assert(!store.get("fact/type/A/missing")); + bool oversizedScanRejected = false; + try { + (void)store.scanPrefix("fact/type/A/", std::nullopt, + RocksDb::maximumScanRecords + 1); + } catch (const Felidae::IrError &) { oversizedScanRejected = true; } + assert(oversizedScanRejected); + const auto zero = store.scanPrefix("fact/type/A/", std::nullopt, 0); + assert(zero.rows.empty() && zero.hasMore); + const auto maximum = store.scanPrefix("fact/type/A/", std::nullopt, + RocksDb::maximumScanRecords); + assert(maximum.rows.size() == 3 && !maximum.hasMore); + + const auto first = store.scanPrefix("fact/type/A/", std::nullopt, 2); + assert(first.rows.size() == 2 && first.hasMore); + assert(first.rows[0].second == "one" && first.rows[1].second == "two"); + const auto second = store.scanPrefix( + "fact/type/A/", first.rows.back().first, 2); + assert(second.rows.size() == 1 && !second.hasMore); + assert(second.rows.front().second == "three"); + + const std::vector replacement{ + {RocksDb::Mutation::Kind::Put, "fact/type/A/0002", "updated"}, + {RocksDb::Mutation::Kind::Erase, "fact/type/A/0001", {}}, + }; + store.write(replacement); + } + + // Closing and reopening proves this is durable storage, not an in-memory + // test double hidden behind the driver interface. + { + RocksDb reopened(database); + assert(!reopened.get("fact/type/A/0001")); + assert(reopened.get("fact/type/A/0002") == "updated"); + const auto rows = reopened.scanPrefix("fact/type/A/", std::nullopt, 8); + assert(rows.rows.size() == 2 && !rows.hasMore); + std::map interned; + const auto decoded = Felidae::Form::decodeStoredFact( + *reopened.get("record/00000042"), + [&](Felidae::PieceSequence pieces) { + const auto [found, _] = interned.emplace( + std::move(pieces), + static_cast(interned.size() + 1)); + return found->second; + }); + assert(decoded.source == "facts/source.fx"); + assert(decoded.fact && decoded.fact->id == 42 && + decoded.fact->createdSequence == 7 && + decoded.fact->origin == Felidae::VmFact::Origin::Derived); + const auto decodedValues = + std::get(decoded.fact->fields.front().second); + assert(decodedValues && decodedValues->values.size() == 5); + assert(std::get(decodedValues->values[0]) == -212.421); + assert(std::get(decodedValues->values[1]).value == 0.75); + assert(std::get(decodedValues->values[2])); + assert(std::get(decodedValues->values[3]).pieces.empty()); + const auto emptyMap = + std::get(decodedValues->values[4]); + assert(emptyMap && emptyMap->entries.size() == 1); + assert(emptyMap->entries.front().first.empty()); + assert(std::get(emptyMap->entries.front().second) + .pieces.empty()); + const auto decodedType = Felidae::Form::decodeStoredFactType( + *reopened.get("type/primary"), + [&](Felidae::PieceSequence pieces) { + const auto [found, _] = interned.emplace( + std::move(pieces), + static_cast(interned.size() + 1)); + return found->second; + }); + assert(decodedType.type != 0 && decodedType.parents.size() == 1); + assert(decodedType.indexes.size() == 2 && + decodedType.indexes[1].size() == 2); + } + + const fs::path factDatabase = + fs::path(FELIDAE_TEST_OUTPUT_DIR) / "vm-facts.rocksdb"; + fs::remove_all(factDatabase, error); + assert(!error); + Felidae::IrFactRef storedId = 0; + { + Felidae::VmFactStore facts(factDatabase); + const auto type = facts.internSymbol({101}); + const auto field = facts.internSymbol({102}); + facts.registerType(type, {}, {{field}}); + auto builder = std::make_shared(); + builder->type = type; + builder->fields = {{field, -212.421}}; + auto retained = facts.retain(builder); + storedId = retained->id; + facts.recordSource(storedId, "facts/persistent.fx"); + retained = facts.mutate(retained, field, 89.024, 0); + assert(std::get(retained->fields.front().second) == 89.024); + } + { + RocksDb raw(factDatabase); + // Type registration, insertion, ownership, and update each commit once. + assert(raw.get("M/revision") == std::string("\0\0\0\0\0\0\0\4", 8)); + assert(raw.scanPrefix(std::string_view{"IT", 2}, std::nullopt, 8) + .rows.size() == 1); + assert(raw.scanPrefix(std::string_view{"IF", 2}, std::nullopt, 8) + .rows.size() == 1); + assert(raw.scanPrefix(std::string_view{"IS", 2}, std::nullopt, 8) + .rows.size() == 1); + assert(raw.scanPrefix(std::string_view{"IE", 2}, std::nullopt, 8) + .rows.size() == 1); + } + { + Felidae::VmFactStore reopened(factDatabase); + const auto type = reopened.findSymbol(std::array{101}); + const auto field = reopened.findSymbol(std::array{102}); + assert(type && field); + const std::array, 1> + predicate{{{*field, 89.024}}}; + const auto rows = reopened.snapshotMatching(*type, predicate); + assert(rows.size() == 1 && rows.front()->id == storedId); + assert(reopened.sourceOf(storedId) == "facts/persistent.fx"); + const auto updated = reopened.mutate(rows.front(), *field, -3.0, 0); + assert(std::get(updated->fields.front().second) == -3.0); + bool staleRejected = false; + try { + (void)reopened.mutate(rows.front(), *field, 5.0, 0); + } catch (const Felidae::IrError &) { + staleRejected = true; + } + assert(staleRejected); + assert(reopened.erase(std::array{updated}) == 1); + } + { + Felidae::VmFactStore reopened(factDatabase); + assert(reopened.size() == 0); + auto replacement = std::make_shared(); + replacement->type = reopened.internSymbol({101}); + replacement->fields = {{reopened.internSymbol({102}), 7.0}}; + const auto retained = reopened.retain(replacement); + assert(retained->id > storedId); + assert(retained->createdSequence > 1); + } + { + RocksDb raw(factDatabase); + // Reopening and the rejected stale update must not advance the revision. + // The successful update, deletion, and replacement add three commits. + assert(raw.get("M/revision") == std::string("\0\0\0\0\0\0\0\7", 8)); + const std::array malformed{{ + {RocksDb::Mutation::Kind::Put, "M/revision", "invalid"}}}; + raw.write(malformed); + } + bool malformedRevisionRejected = false; + try { + Felidae::VmFactStore reopened(factDatabase); + } catch (const Felidae::IrError &) { + malformedRevisionRejected = true; + } + assert(malformedRevisionRejected); + + const fs::path pageDatabase = + fs::path(FELIDAE_TEST_OUTPUT_DIR) / "paged-facts.rocksdb"; + fs::remove_all(pageDatabase, error); + assert(!error); + std::optional cursor; + std::vector expected; + { + Felidae::VmFactStore store(pageDatabase); + const auto parent = store.internSymbol({201}); + const auto child = store.internSymbol({202}); + const auto field = store.internSymbol({203}); + const auto residual = store.internSymbol({204}); + store.registerType(parent, {}, {{field}}); + store.registerType(child, {parent}); + for (int i = 0; i < 5; ++i) { + auto fact = std::make_shared(); + fact->type = i % 2 ? child : parent; + fact->fields = {{field, 7.0}, {residual, i % 2 ? 0.0 : 1.0}}; + expected.push_back(store.retain(fact)->id); + } + const auto zero = store.pageAssignableTo(parent, 0); + assert(zero.rows.empty() && zero.hasMore); + const auto first = store.pageAssignableTo(parent, 2); + assert(first.rows.size() == 2 && first.hasMore && first.next); + assert(first.rows[0]->id == expected[0]); + assert(first.rows[1]->id == expected[1]); + cursor = first.next; + const auto rejects = [](const auto &action) { + try { action(); } catch (const Felidae::IrError &) { return true; } + return false; + }; + assert(rejects([&] { (void)store.pageAssignableTo(child, 2, cursor); })); + auto foreign = cursor; + foreign->database += "other"; + assert(rejects([&] { (void)store.pageAssignableTo(parent, 2, foreign); })); + auto invalid = cursor; + invalid->lastKey.pop_back(); + assert(rejects([&] { (void)store.pageAssignableTo(parent, 2, invalid); })); + assert(rejects([&] { (void)store.pageAssignableTo(parent, 10'001); })); + std::vector> predicates{ + {field, 7.0}, {residual, 1.0}}; + const auto matched = store.pageMatching(parent, predicates, 2); + assert(matched.rows.size() == 2 && matched.next && matched.hasMore); + assert(matched.rows[0]->id == expected[0]); + assert(matched.rows[1]->id == expected[2]); + // Equivalent argument order must retain the same cursor query identity. + std::reverse(predicates.begin(), predicates.end()); + const auto remaining = store.pageMatching(parent, predicates, 2, matched.next); + assert(remaining.rows.size() == 1 && !remaining.hasMore); + assert(remaining.rows[0]->id == expected[4]); + predicates[0].second = 0.0; + assert(rejects([&] { + (void)store.pageMatching(parent, predicates, 2, matched.next); + })); + assert(store.pageMatching(child, predicates, 2).rows.size() == 2); + predicates[1].second = 8.0; + assert(store.pageMatching(parent, predicates, 2).rows.empty()); + } + { + Felidae::VmFactStore store(pageDatabase); + const auto parent = store.internSymbol({201}); + const auto second = store.pageAssignableTo(parent, 2, cursor); + assert(second.rows.size() == 2 && second.hasMore && second.next); + assert(second.rows[0]->id == expected[2]); + assert(second.rows[1]->id == expected[3]); + const auto last = store.pageAssignableTo(parent, 2, second.next); + assert(last.rows.size() == 1 && !last.hasMore && !last.next); + assert(last.rows[0]->id == expected[4]); + store.erase(last.rows); + bool stale = false; + try { (void)store.pageAssignableTo(parent, 2, cursor); } + catch (const Felidae::IrError &) { stale = true; } + assert(stale); + } + + const fs::path inheritedDatabase = + fs::path(FELIDAE_TEST_OUTPUT_DIR) / "inherited-index-pages.rocksdb"; + fs::remove_all(inheritedDatabase, error); + assert(!error); + std::optional inheritedCursor; + Felidae::IrSymbolRef previousChild = 0; + { + Felidae::VmFactStore store(inheritedDatabase); + // Deliberately intern out of canonical storage order. + const auto child = store.internSymbol({901}); + previousChild = child; + const auto first = store.internSymbol({801}); + const auto second = store.internSymbol({701}); + const auto field = store.internSymbol({601}); + store.registerType(first, {}, {{field}}); + store.registerType(second, {}, {{field}}); + store.registerType(child, {first, second}); + for (int i = 0; i < 3; ++i) { + auto fact = std::make_shared(); + fact->type = child; + fact->fields = {{field, 5.0}}; + (void)store.retain(fact); + } + const std::array, 1> + predicates{{{field, 5.0}}}; + const auto page = store.pageMatching(child, predicates, 1); + assert(page.rows.size() == 1 && page.next && page.hasMore); + inheritedCursor = page.next; + } + { + Felidae::VmFactStore store(inheritedDatabase); + const auto child = store.internSymbol({901}); + const auto field = store.internSymbol({601}); + assert(child != previousChild); + const std::array, 1> + predicates{{{field, 5.0}}}; + const auto next = store.pageMatching(child, predicates, 2, inheritedCursor); + assert(next.rows.size() == 2 && !next.hasMore); + assert(next.rows[0]->id == 2 && next.rows[1]->id == 3); + } + { + RocksDb raw(inheritedDatabase); + const std::string firstKey("F\0\0\0\0\0\0\0\1", 9); + const auto record = raw.get(firstKey); + assert(record); + const std::array misplaced{{ + {RocksDb::Mutation::Kind::Put, + std::string("F\0\0\0\0\0\0\0\11", 9), *record}}}; + raw.write(misplaced); + } + bool misplacedRecordRejected = false; + try { + Felidae::VmFactStore store(inheritedDatabase); + (void)store.snapshot(); + } + catch (const Felidae::IrError &) { misplacedRecordRejected = true; } + assert(misplacedRecordRejected); + + const auto checkRollback = [](Felidae::VmFactStore &store) { + const auto type = store.internSymbol({1001}); + const auto field = store.internSymbol({1002}); + store.registerType(type, {}, {{field}}); + auto fact = std::make_shared(); + fact->type = type; + fact->fields = {{field, 1.0}}; + const auto original = store.retain(fact); + assert(store.snapshotByField(field).size() == 1); + const auto updated = store.mutate(original, field, 2.0, 0); + const auto other = store.retain(fact); + bool staleDeleteRejected = false; + try { + store.erase(std::array{other, original}); + } catch (const Felidae::IrError &) { staleDeleteRejected = true; } + assert(staleDeleteRejected); + assert(store.size() == 2); // Validate the whole batch before removing any row. + assert(store.erase(std::array{other, other}) == 1); + // Deserialized snapshots are equivalent values, not identical pointers. + const Felidae::VmFactPtr fresh = std::make_shared(*updated); + store.restore(fresh, original); + const std::array, 1> + oldPredicate{{{field, 1.0}}}, newPredicate{{{field, 2.0}}}; + assert(store.snapshotMatching(type, oldPredicate).size() == 1); + assert(store.snapshotMatching(type, newPredicate).empty()); + assert(std::get(store.snapshotByField(field).front()->fields.front().second) == 1.0); + bool staleRejected = false; + try { store.restore(updated, original); } + catch (const Felidae::IrError &) { staleRejected = true; } + assert(staleRejected); + store.erase(std::array{original}); + bool absentRejected = false; + try { store.restore(original, original); } + catch (const Felidae::IrError &) { absentRejected = true; } + assert(absentRejected); + assert(store.snapshot().empty()); + assert(store.snapshotByField(field).empty()); + }; + { + Felidae::VmFactStore memory; + checkRollback(memory); + } + const fs::path rollbackDatabase = + fs::path(FELIDAE_TEST_OUTPUT_DIR) / "rollback-facts.rocksdb"; + fs::remove_all(rollbackDatabase, error); + assert(!error); + { + Felidae::VmFactStore persistent(rollbackDatabase); + checkRollback(persistent); + } + { + Felidae::VmFactStore reopened(rollbackDatabase); + assert(reopened.snapshot().empty()); + } + + const fs::path ownershipDatabase = + fs::path(FELIDAE_TEST_OUTPUT_DIR) / "ownership-facts.rocksdb"; + fs::remove_all(ownershipDatabase, error); + assert(!error); + { + Felidae::VmFactStore store(ownershipDatabase); + const auto type = store.internSymbol({1101}); + store.registerType(type, {}); + auto builder = std::make_shared(); + builder->type = type; + const auto first = store.retain(builder); + const auto second = store.retain(builder); + (void)store.retain(builder); // In-memory ownership: excluded from both files. + store.recordSource(first->id, "a.csv"); + store.recordSource(second->id, "b.csv"); + assert(store.snapshotBySource("a.csv").size() == 1); + assert(store.snapshotBySource("b.csv").size() == 1); + store.recordSource(first->id, "b.csv"); + assert(store.snapshotBySource("a.csv").empty()); + auto rows = store.snapshotBySource("b.csv"); + assert(rows.size() == 2 && rows[0]->id == first->id && + rows[1]->id == second->id); + store.erase(std::array{first}); + assert(store.snapshotBySource("b.csv").size() == 1); + store.restoreErased(first, "b.csv"); + } + { + Felidae::VmFactStore reopened(ownershipDatabase); + assert(reopened.snapshotBySource("a.csv").empty()); + const auto rows = reopened.snapshotBySource("b.csv"); + assert(rows.size() == 2 && rows[0]->id == 1 && rows[1]->id == 2); + assert(reopened.snapshotBySource("missing.csv").empty()); + } +} diff --git a/tests/SentencePieceModelTest.cpp b/tests/SentencePieceModelTest.cpp index 5cee785..a17b481 100644 --- a/tests/SentencePieceModelTest.cpp +++ b/tests/SentencePieceModelTest.cpp @@ -82,12 +82,12 @@ int main() { std::filesystem::remove_all(datasetTestDirectory); assert(Felidae::felidaeSentencePieceModelIdentity() == - "sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8"); + "sha256:9f5a24275dacac172f145a776434c5b8a49375e4354c682dc52fbc0675114f4b"); sentencepiece::SentencePieceProcessor model; const auto loaded = model.Load(FELIDAE_SENTENCEPIECE_MODEL_PATH); assert(loaded.ok()); assert(Felidae::kFelidaeTokenizerDatasetSchemaVersion == 1); - assert(Felidae::kFelidaeTokenizerDatasetRecordCount == 32); + assert(Felidae::kFelidaeTokenizerDatasetRecordCount == 92); assert(Felidae::kFelidaeSentencePieceVocabularySize == static_cast(model.GetPieceSize())); assert(model.GetPieceSize() <= 1024 && model.GetPieceSize() > 512); @@ -154,24 +154,20 @@ int main() { const std::string completeSource = "# comment\n" "café(value: \"hello\") => return value\n"; - const Felidae::IntegerTokenList lazyLines(model, "first\nsecond\nthird\n"); - assert(lazyLines.encodeCount() == 1); - assert(lazyLines.has(lazyLines.loadedSize())); - assert(lazyLines.encodeCount() == 2); - assert(lazyLines.has(lazyLines.loadedSize())); - assert(lazyLines.encodeCount() == 3); - const Felidae::IntegerTokenList firstLine(model, "first\n"); - const auto &lazyEntries = lazyLines.entries(); - const auto &firstEntries = firstLine.entries(); - assert(lazyEntries.size() >= firstEntries.size()); - for (std::size_t index = 0; index < firstEntries.size(); ++index) { - assert(lazyEntries[index].id == firstEntries[index].id); - assert(lazyEntries[index].begin == firstEntries[index].begin); - assert(lazyEntries[index].end == firstEntries[index].end); - } + const Felidae::IntegerTokenList blockTokens(model, "first\nsecond\nthird\n"); + assert(blockTokens.encodeCount() == 1); + assert(!blockTokens.entries().empty()); + const Felidae::IntegerTokenList statementTokens( + model, + "value := pipeline(\n" + " input: \"a.b\", weight: 1.25\n" + ") then worker(value: system.result). # completed\n" + "next := value.member.\n"); + (void)statementTokens.entries(); + assert(statementTokens.encodeCount() == 2); const Felidae::IntegerTokenList sourceTokens(model, completeSource); assert(!sourceTokens.entries().empty()); - assert(sourceTokens.encodeCount() == 2); + assert(sourceTokens.encodeCount() == 1); for (const auto& entry : sourceTokens.entries()) { assert(entry.begin <= entry.end); assert(entry.end <= completeSource.size()); @@ -182,7 +178,7 @@ int main() { Felidae::IntegerParser integerParser(expressionTokens); const auto expression = integerParser.parseExpressionText(); assert(expression->debug() == "[\"value\", café, 1]"); - assert(integerParser.metrics().sourceEncodeCount == 2); + assert(integerParser.metrics().sourceEncodeCount == 1); assert(integerParser.metrics().tokenCount == expressionTokens.entries().size()); assert(integerParser.metrics().iterations > 0); assert(integerParser.metrics().peakRecursionDepth > 0); @@ -192,7 +188,7 @@ int main() { Felidae::IntegerParser structuredParser(structuredTokens); const auto structured = structuredParser.parseExpressionText(); assert(structured->debug() == "worker(task: {name: \"café\"}):result + 2 * 3"); - assert(structuredParser.metrics().sourceEncodeCount == 2); + assert(structuredParser.metrics().sourceEncodeCount == 1); const Felidae::IntegerTokenList programTokens( model, "import \"core.fx\".\nthreshold := 2 + 3.\nPerson(name: \"Ada\", age: threshold)."); @@ -263,8 +259,8 @@ int main() { assert(dottedLabelProgram.clauses.size() == 1); assert(dottedLabelProgram.clauses.front()->head.args.front().name == "fx.effective_at"); - // Moderate-size program regression: every physical line is encoded once - // and repeated SentencePiece word fragments never merge statements. + // Moderate-size program regression: explicit statements are encoded once + // each rather than being split by their physical line layout. std::string largeSource; largeSource.reserve(12'000); for (int index = 0; index < 512; ++index) { @@ -326,7 +322,7 @@ int main() { auto operators = std::make_shared(); const Felidae::IntegerTokenList mixfixDeclarationTokens(model, "@mixfix(pattern: \"choose {value: expr}\")\n" - "choose() => return (value)\n"); + "choose() => return (value).\n"); Felidae::IntegerParser mixfixDeclarationParser(mixfixDeclarationTokens, operators); const auto mixfixDeclarationProgram = mixfixDeclarationParser.parseProgram(); assert(mixfixDeclarationProgram.clauses.size() == 1); @@ -352,7 +348,7 @@ int main() { const Felidae::IntegerTokenList nestedMixfixDeclarationTokens(model, "@mixfix(pattern: \"wrap {value: expr} end\")\n" - "wrap() => return (value)\n"); + "wrap() => return (value).\n"); Felidae::IntegerParser nestedMixfixDeclarationParser(nestedMixfixDeclarationTokens, operators); (void)nestedMixfixDeclarationParser.parseProgram(); const Felidae::IntegerTokenList nestedMixfixUseTokens(model, "wrap choose 7 end"); @@ -365,7 +361,7 @@ int main() { const Felidae::IntegerTokenList trailingMixfixDeclarationTokens(model, "@mixfix(pattern: \"{left: expr} combines {right: expr}\")\n" - "combines() => return (left)\n"); + "combines() => return (left).\n"); Felidae::IntegerParser trailingMixfixDeclarationParser(trailingMixfixDeclarationTokens, operators); (void)trailingMixfixDeclarationParser.parseProgram(); const Felidae::IntegerTokenList trailingMixfixUseTokens(model, "1 combines 2"); @@ -381,10 +377,10 @@ int main() { auto sameAnchorOperators = std::make_shared(); const Felidae::IntegerTokenList sameAnchorTokens(model, "@mixfix(pattern: \"plan {name: string} using {strategy: string} with {budget: number}\")\n" - "longPlan() => return (value: name)\n" + "longPlan() => return (value: name).\n" "@mixfix(pattern: \"plan {value: number} using {enabled: number}\")\n" - "shortPlan() => return (value: value)\n" - "main() => return (long: plan \"x\" using \"y\" with 1, short: plan 7 using 1.0)\n"); + "shortPlan() => return (value: value).\n" + "main() => return (long: plan \"x\" using \"y\" with 1, short: plan 7 using 1.0).\n"); Felidae::IntegerParser sameAnchorParser(sameAnchorTokens, sameAnchorOperators); const auto sameAnchorProgram = sameAnchorParser.parseProgram(); assert(sameAnchorProgram.clauses.size() == 3); diff --git a/tests/SentencePiecePipelineTest.cpp b/tests/SentencePiecePipelineTest.cpp index 1fbbe6a..fe38c89 100644 --- a/tests/SentencePiecePipelineTest.cpp +++ b/tests/SentencePiecePipelineTest.cpp @@ -114,6 +114,43 @@ int main() { }; const auto numericModule = Felidae::compileProgramFileToIr(FELIDAE_NUMERIC_OPERATIONS_FIXTURE_PATH); + const auto objectArray = Felidae::compileProgramTextToIr( + "main() =>\n" + " people:obj = array()\n" + " return people\n" + "end\n"); + const auto objectArrayResult = + std::get(executeModule(objectArray)); + assert(objectArrayResult && objectArrayResult->values.empty()); + const auto objectReceiver = Felidae::compileProgramTextToIr( + "main() =>\n" + " people:obj = array()\n" + " people := people.push(value: 42)\n" + " people.len()\n" + " return (first: people.get(position: 0), size: people.len())\n" + "end\n"); + const auto receiverResult = + std::get(executeModule(objectReceiver)); + assert(receiverResult && receiverResult->entries.size() == 2); + assert(std::get(receiverResult->entries[0].second) == 42.0); + assert(std::get(receiverResult->entries[1].second) == 1.0); + const auto globalObject = Felidae::compileProgramTextToIr( + "people:obj = [42].\n" + "main() => return people.get(position: 0)\nend\n"); + assert(std::get(executeModule(globalObject)) == 42.0); + const auto sameLineStatements = Felidae::compileProgramTextToIr( + "left := 1.25. right := left. main() => return right."); + assert(std::get(executeModule(sameLineStatements)) == 1.25); + for (const auto *source : { + "main() => people:obj array()\nreturn people\nend\n", + "value := 1 .25. main() => return value.", + "main() => people:obj = array(42)\nreturn people\nend\n", + "main() => people:obj = [42]\nreturn people.get()\nend\n"}) { + bool rejected = false; + try { (void)Felidae::compileProgramTextToIr(source); } + catch (const Felidae::IntegerParserError &) { rejected = true; } + assert(rejected); + } const auto numericResult = std::get(executeModule(numericModule)); const std::array expectedNumeric{ @@ -174,12 +211,12 @@ int main() { assert(std::get(executeModule(directMixfixModule)) == 42.0); const auto thenPipelineModule = Felidae::compileProgramTextToIr( - "increment(value: number) => return value + 1\n" - "double(value: number) => return value * 2\n" + "increment(value: number) => return value + 1.\n" + "double(value: number) => return value * 2.\n" "main() =>\n" " return increment(value: 9)\n" " then double(value: system.result)\n" - " then increment(value: system.result)\n"); + " then increment(value: system.result).\n"); assert(std::get(executeModule(thenPipelineModule)) == 21.0); const auto nestedThenPipelineModule = Felidae::compileProgramTextToIr( @@ -277,6 +314,25 @@ int main() { std::get(executeModule(queriedHierarchyModule)); assert(queriedFacts && queriedFacts->values.size() == 2); + const auto hierarchyEvidenceModule = Felidae::compileProgramTextToIr( + "Root(name: \"root\")\n" + "Left extend Root(name: \"left\")\n" + "Right extend Root(name: \"right\")\n" + "Diamond extend Left, Right(name: \"diamond\")\n" + "Other extend Root(name: \"other\")\n" + "main() => return ancestorAnalysis(left: Diamond(name: \"diamond\"), " + "right: Other(name: \"other\"))\n" + "end\n"); + const auto hierarchyEvidence = displayModuleValue( + hierarchyEvidenceModule, executeModule(hierarchyEvidenceModule)); + assert(hierarchyEvidence.find( + "leftProofs: [[Diamond, Left, Root], [Diamond, Right, Root]]") != + std::string::npos); + assert(hierarchyEvidence.find("rightProofs: [[Other, Root]]") != + std::string::npos); + assert(hierarchyEvidence.find("leftDistance: 2") != std::string::npos); + assert(hierarchyEvidence.find("rightDistance: 1.0") != std::string::npos); + const auto temporalModule = Felidae::compileProgramTextToIr( "Event(name: \"first\", effective_at: 10, priority: 1)\n" "Event(name: \"second\", effective_at: 20, priority: 2)\n" @@ -809,6 +865,7 @@ int main() { "School(id: 2, name: \"West\", city: \"MYS\", students: 280, active: 0.0)\n" "School(id: 3, name: \"Lake\", city: \"BLR\", students: 350, active: 1.0)\n" "Teacher(name: \"Ada\", school_id: 1)\n" + "Teacher(name: \"Lin\", school_id: 1)\n" "Teacher(name: \"Grace\", school_id: 9)\n" "main() =>\n" " limited := School.where(active: 1.0).AndWhere(city: \"BLR\").limit(records: 1)\n" @@ -832,6 +889,17 @@ int main() { "updated: count(data: updated), deleted: deleted, remaining: School.count(), " "total: School.sum(field: \"students\"), average: School.average(field: \"students\"))\n" "end\n"); + bool usesIndexedWhere = false; + for (const auto &[_, procedure] : factDmlModule.procedures) { + for (std::size_t pc = 0; pc < procedure.ir.words.size(); + pc += Felidae::irInstructionWidth(procedure.ir, pc)) { + usesIndexedWhere = + usesIndexedWhere || + procedure.ir.words[pc] == + static_cast(Felidae::IrOpcode::FactWhere); + } + } + assert(usesIndexedWhere); Felidae::FelidaeKnowledgeRuntime factDmlRuntime; const auto factDmlResult = displayModuleValue( factDmlModule, executeModuleDirect(factDmlModule, factDmlRuntime)); @@ -839,11 +907,11 @@ int main() { assert(factDmlResult.find("all_limited: 2") != std::string::npos); assert(factDmlResult.find("alternatives: 2") != std::string::npos); assert(factDmlResult.find("projected_limited: 1.0") != std::string::npos); - assert(factDmlResult.find("inner_joined: 1.0") != std::string::npos); - assert(factDmlResult.find("joined: 3") != std::string::npos); - assert(factDmlResult.find("right_joined: 2") != std::string::npos); - assert(factDmlResult.find("outer_joined: 4") != std::string::npos); - assert(factDmlResult.find("joined_limited: 1.0") != std::string::npos); + assert(factDmlResult.find("inner_joined: 2") != std::string::npos); + assert(factDmlResult.find("joined: 4") != std::string::npos); + assert(factDmlResult.find("right_joined: 3") != std::string::npos); + assert(factDmlResult.find("outer_joined: 5") != std::string::npos); + assert(factDmlResult.find("joined_limited: 2") != std::string::npos); assert(factDmlResult.find("none: 0.0") != std::string::npos); assert(factDmlResult.find("updated: 1.0") != std::string::npos); assert(factDmlResult.find("deleted: 1.0") != std::string::npos); @@ -1012,6 +1080,8 @@ int main() { "Catalog(title: \"Alpha Guide\", confidence: 0.82, category: Book)\n" "Catalog(title: \"beta guide\", confidence: 0.74, category: Magazine)\n" "Catalog(title: \"Reference\", confidence: 0.40, category: Publication)\n" + "Catalog(title: \"Outlier\", confidence: -212.421, category: Publication)\n" + "Catalog(title: \"Strong\", confidence: 89.024, category: Publication)\n" "main() =>\n" " exact := Catalog.search(field: \"title\", query: \"alpha guide\", type: \"exact\", case: \"insensitive\")\n" " liked := Catalog.search(field: \"title\", query: \"%guide\", type: \"like\", case: \"insensitive\")\n" @@ -1019,14 +1089,16 @@ int main() { " descendants := Catalog.search(field: \"category\", query: Publication, type: \"hierarchy\", direction: \"descendants\", includeSelf: 0.0)\n" " ranged := Catalog.search(field: \"confidence\", type: \"degree\", minimum: 0.70, maximum: 0.90)\n" " close := Catalog.search(field: \"confidence\", query: 0.80, tolerance: 0.08, type: \"degree\")\n" - " return (exact: count(data: exact), liked: count(data: liked), regexed: count(data: regexed), descendants: count(data: descendants), ranged: count(data: ranged), close: count(data: close))\n" + " unrestricted := Catalog.search(field: \"confidence\", type: \"degree\", minimum: -300, maximum: -200)\n" + " large := Catalog.search(field: \"confidence\", query: 90, tolerance: 1.0, type: \"degree\")\n" + " return (exact: count(data: exact), liked: count(data: liked), regexed: count(data: regexed), descendants: count(data: descendants), ranged: count(data: ranged), close: count(data: close), unrestricted: count(data: unrestricted), large: count(data: large))\n" "end\n"); Felidae::FelidaeKnowledgeRuntime factSearchRuntime; const auto factSearchResult = displayModuleValue( factSearchModule, executeModuleDirect(factSearchModule, factSearchRuntime)); assert(factSearchResult == - "{exact: 1.0, liked: 2, regexed: 2, descendants: 2, ranged: 2, close: 2}"); + "{exact: 1.0, liked: 2, regexed: 2, descendants: 2, ranged: 2, close: 2, unrestricted: 1.0, large: 1.0}"); const auto repeatedFieldsModule = Felidae::compileProgramTextToIr( "Color(value: \"red\", tag: \"warm\", tag: \"primary\").\n" @@ -1065,6 +1137,88 @@ int main() { executeModuleDirect(classModule, classRuntime)) == "[{name: Ada, age: 32}]"); + // Multiple inheritance is retained in the ordinary type table, and a + // class method is an ordinary lowered procedure with an explicit `self` + // argument. This exercises the method body instead of merely accepting its + // declaration. + const auto classMethodModule = Felidae::compileProgramTextToIr( + "class Named\n" + " name: string\n" + "end\n" + "class Active\n" + " active: number\n" + "end\n" + "class Student extend Named, Active\n" + " score: number\n" + " passes(minimum: number) =>\n" + " where active == 1.0 and score >= minimum\n" + " return score\n" + " else\n" + " return 0.0\n" + " end\n" + "end\n" + "Student(name: \"Ada\", active: 1.0, score: 82)\n" + "main() =>\n" + " rows := Student.all()\n" + " student := array.get(data: rows, position: 0)\n" + " return Student.passes(self: student, minimum: 70)\n" + "end\n"); + Felidae::FelidaeKnowledgeRuntime classMethodRuntime; + assert(std::get(Felidae::RegisterVm{}.executeMain( + Felidae::verifyIrModule(Felidae::IrModule(classMethodModule)), + classMethodRuntime)) == 82.0); + + // Classes and legacy fact declarations occupy one fact-type hierarchy. + // Every direction is legal: fact->fact, fact->class, class->fact, and + // class->class. Classes remain compiler schemas rather than a parallel + // runtime hierarchy. + const auto mixedHierarchyModule = Felidae::compileProgramTextToIr( + "FactBase(id: 0)\n" + "FactChild extend FactBase(id: 1)\n" + "class ClassFromFact extend FactBase\n" + " name: string\n" + "end\n" + "class ClassChild extend ClassFromFact\n" + " score: number\n" + "end\n" + "FactFromClass extend ClassFromFact(name: \"row\")\n" + "main() =>\n" + " fact_fact := isA(left: FactChild(id: 2), right: FactBase(id: 0))\n" + " class_fact := isA(left: ClassFromFact(name: \"a\"), right: FactBase(id: 0))\n" + " class_class := isA(left: ClassChild(name: \"b\", score: 4.2), right: ClassFromFact(name: \"a\"))\n" + " fact_class := isA(left: FactFromClass(name: \"row\"), right: ClassFromFact(name: \"a\"))\n" + " return [fact_fact, class_fact, class_class, fact_class]\n" + "end\n"); + Felidae::FelidaeKnowledgeRuntime mixedHierarchyRuntime; + assert(displayModuleValue( + mixedHierarchyModule, + executeModuleDirect(mixedHierarchyModule, + mixedHierarchyRuntime)) == + "[1.0, 1.0, 1.0, 1.0]"); + + // Mixfix relationship methods return ordinary Association facts. No + // relationship-only runtime representation or compare builtin is involved. + const auto associationModule = Felidae::compileProgramTextToIr( + "Person(name: \"Ada\")\n" + "Company(name: \"Felidae\")\n" + "@mixfix(pattern: \"{left: Person} works at {right: Company}\")\n" + "worksAt() =>\n" + " return Association(left: left, right: right, relation: \"works at\", strength: 3.421)\n" + "end\n" + "main() =>\n" + " people := Person.all()\n" + " companies := Company.all()\n" + " person := array.get(data: people, position: 0)\n" + " company := array.get(data: companies, position: 0)\n" + " return person works at company\n" + "end\n"); + Felidae::FelidaeKnowledgeRuntime associationRuntime; + assert(displayModuleValue( + associationModule, + executeModuleDirect(associationModule, associationRuntime)) == + "{left: {name: Ada}, right: {name: Felidae}, relation: works at, " + "strength: 3.421}"); + // Real source semantic intrinsic -> structured compiler IR // operation ID -> typed runtime-model result. No tokenizer or symbol ID // crosses the semantic execution boundary. @@ -1094,19 +1248,44 @@ int main() { "end\n"); class SuggestRuntimeModel final : public Felidae::RuntimeStateModel { public: + explicit SuggestRuntimeModel(double score) : score_(score) {} + Felidae::VmValue evaluate(const Felidae::RuntimeOperation &operation, std::span inputs, Felidae::RuntimeContext &) override { assert(operation.id == static_cast( Felidae::SemanticOperationId::Suggest)); assert(inputs.size() == 1); - return -212.421; + return score_; } - } suggestModel; + private: + double score_; + } suggestModel(-212.421); Felidae::FelidaeKnowledgeRuntime suggestRuntime(&suggestModel); assert(std::get(Felidae::RegisterVm{}.executeMain( Felidae::verifyIrModule(Felidae::IrModule(suggestModule)), suggestRuntime)) == -212.421); + SuggestRuntimeModel largeSuggestModel(89.024); + Felidae::FelidaeKnowledgeRuntime largeSuggestRuntime(&largeSuggestModel); + assert(std::get(Felidae::RegisterVm{}.executeMain( + Felidae::verifyIrModule(Felidae::IrModule(suggestModule)), + largeSuggestRuntime)) == 89.024); + const auto thresholdModule = Felidae::compileProgramTextToIr( + "Candidate(name: \"Mammal\")\n" + "main() =>\n" + " score := ssm.suggest(input: Candidate.all())\n" + " where score >= 4.5\n" + " return score\n" + "else\n" + " return 0.0\n" + "end\n"); + assert(std::get(Felidae::RegisterVm{}.executeMain( + Felidae::verifyIrModule(Felidae::IrModule(thresholdModule)), + largeSuggestRuntime)) == 89.024); + Felidae::FelidaeKnowledgeRuntime negativeThresholdRuntime(&suggestModel); + assert(std::get(Felidae::RegisterVm{}.executeMain( + Felidae::verifyIrModule(Felidae::IrModule(thresholdModule)), + negativeThresholdRuntime)) == 0.0); const auto executeBinaryModule = [&](const Felidae::IrModule &candidate) { const auto path = testOutputDirectory / "felidae_pipeline_feature_roundtrip.bin"; diff --git a/tools/FactStoreBenchmark.cpp b/tools/FactStoreBenchmark.cpp new file mode 100644 index 0000000..80bdb7f --- /dev/null +++ b/tools/FactStoreBenchmark.cpp @@ -0,0 +1,145 @@ +#include "form/RegisterVm.h" +#include "form/libs/RocksDb.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +std::size_t argument(char **begin, char **end, std::string_view name, + std::size_t fallback) { + for (auto current = begin; current != end; ++current) { + if (*current != name || current + 1 == end) + continue; + const std::string_view value(*++current); + std::size_t parsed = 0; + try { + const auto number = std::stoull(std::string(value), &parsed); + if (parsed != value.size() || number == 0 || + number > std::numeric_limits::max()) + throw std::invalid_argument("range"); + return static_cast(number); + } catch (const std::exception &) { + throw Felidae::IrError(std::string(name) + " requires a positive integer"); + } + } + return fallback; +} + +double milliseconds(std::chrono::steady_clock::duration duration) { + return std::chrono::duration(duration).count(); +} + +std::uintmax_t directoryBytes(const std::filesystem::path &directory) { + std::uintmax_t result = 0; + std::error_code error; + for (std::filesystem::recursive_directory_iterator iterator(directory, error), end; + !error && iterator != end; iterator.increment(error)) { + if (iterator->is_regular_file(error)) + result += iterator->file_size(error); + } + if (error) + throw Felidae::IrError("cannot measure benchmark storage: " + error.message()); + return result; +} + +} // namespace + +int main(int argc, char **argv) try { + using Clock = std::chrono::steady_clock; + const auto records = argument(argv + 1, argv + argc, "--records", 10'000); + const auto pageSize = argument(argv + 1, argv + argc, "--page", 100); + const auto warmIterations = argument(argv + 1, argv + argc, "--warm", 100); + if (pageSize > 10'000) + throw Felidae::IrError("--page exceeds the 10000 row runtime limit"); + + const std::filesystem::path database = + std::filesystem::path(FELIDAE_BENCHMARK_OUTPUT_DIR) / + ("fact-store-" + std::to_string(records) + ".rocksdb"); + std::error_code error; + std::filesystem::remove_all(database, error); + if (error) + throw Felidae::IrError("cannot clear benchmark database: " + error.message()); + + const Felidae::PieceSequence typePieces{101}; + const Felidae::PieceSequence fieldPieces{102}; + const auto ingestBegin = Clock::now(); + { + Felidae::VmFactStore store(database); + const auto type = store.internSymbol(typePieces); + const auto field = store.internSymbol(fieldPieces); + store.registerType(type, {}, {{field}}); + for (std::size_t index = 0; index < records; ++index) { + auto fact = std::make_shared(); + fact->type = type; + fact->fields = {{field, static_cast(index % 100)}}; + (void)store.retain(fact); + } + } + const auto ingestEnd = Clock::now(); + + double reopenMilliseconds = 0.0; + double coldMilliseconds = 0.0; + double warmMeanMilliseconds = 0.0; + std::size_t returnedRows = 0; + bool hasMore = false; + std::size_t observedRows = 0; + { + const auto openBegin = Clock::now(); + Felidae::VmFactStore store(database); + const auto type = *store.findSymbol(typePieces); + const auto field = *store.findSymbol(fieldPieces); + const std::pair predicate{field, 42.0}; + const auto openEnd = Clock::now(); + const auto coldBegin = Clock::now(); + const auto cold = store.pageMatching(type, {&predicate, 1}, pageSize); + const auto coldEnd = Clock::now(); + const auto warmBegin = Clock::now(); + for (std::size_t index = 0; index < warmIterations; ++index) + observedRows += store.pageMatching(type, {&predicate, 1}, pageSize).rows.size(); + const auto warmEnd = Clock::now(); + reopenMilliseconds = milliseconds(openEnd - openBegin); + coldMilliseconds = milliseconds(coldEnd - coldBegin); + warmMeanMilliseconds = + milliseconds(warmEnd - warmBegin) / static_cast(warmIterations); + returnedRows = cold.rows.size(); + hasMore = cold.hasMore; + } + Felidae::Form::RocksDb metrics(database); + const auto indexReaderBytes = + metrics.integerProperty("rocksdb.estimate-table-readers-mem"); + const auto liveDataBytes = + metrics.integerProperty("rocksdb.estimate-live-data-size"); + const auto sstBytes = metrics.integerProperty("rocksdb.total-sst-files-size"); + + const auto ingestSeconds = + std::chrono::duration(ingestEnd - ingestBegin).count(); + std::cout << "{\n" + << " \"records\": " << records << ",\n" + << " \"requested_page_size\": " << pageSize << ",\n" + << " \"returned_page_size\": " << returnedRows << ",\n" + << " \"has_more\": " << (hasMore ? "1.0" : "0.0") << ",\n" + << " \"ingestion_records_per_second\": " + << static_cast(records) / ingestSeconds << ",\n" + << " \"reopen_milliseconds\": " << reopenMilliseconds << ",\n" + << " \"cold_lookup_milliseconds\": " << coldMilliseconds << ",\n" + << " \"warm_lookup_mean_milliseconds\": " << warmMeanMilliseconds << ",\n" + << " \"warm_observed_rows\": " << observedRows << ",\n" + << " \"index_reader_memory_bytes\": " << indexReaderBytes.value_or(0) << ",\n" + << " \"estimated_live_data_bytes\": " << liveDataBytes.value_or(0) << ",\n" + << " \"sst_storage_bytes\": " << sstBytes.value_or(0) << ",\n" + << " \"storage_size_bytes\": " << directoryBytes(database) << ",\n" + << " \"cache_state_cold\": \"database reopened; operating-system cache not flushed\",\n" + << " \"cache_state_warm\": \"same process and query repeated\",\n" + << " \"claim\": \"measured local dataset only; no trillion-scale guarantee\"\n" + << "}\n"; + return 0; +} catch (const std::exception &error) { + std::cerr << "error: " << error.what() << '\n'; + return 1; +} diff --git a/tree-sitter-felidae b/tree-sitter-felidae index 58e0f58..114bfc0 160000 --- a/tree-sitter-felidae +++ b/tree-sitter-felidae @@ -1 +1 @@ -Subproject commit 58e0f58a819464c8038c24db387518b6cf0a42cf +Subproject commit 114bfc02f3ad6900c1bc16cccd4513bcbdbb979b diff --git a/v2_examples/array_object.fx b/v2_examples/array_object.fx new file mode 100644 index 0000000..7ff0129 --- /dev/null +++ b/v2_examples/array_object.fx @@ -0,0 +1,8 @@ +// Receiver calls reuse the existing array operations. +// push returns a new array, so retain its result explicitly. +main() => + people:obj = array() + people := people.push(value: "Ada") + people := people.push(value: "Grace") + return (first: people.get(position: 0), count: people.len()) +end diff --git a/v2_examples/class_association_reasoning.fx b/v2_examples/class_association_reasoning.fx new file mode 100644 index 0000000..c4bce32 --- /dev/null +++ b/v2_examples/class_association_reasoning.fx @@ -0,0 +1,43 @@ +# Classes are compiler-only fact schemas. Mixfix methods produce ordinary +# Association facts that remain queryable through the standard fact DML API. +class Person + id: number + name: string + index(id) +end + +class Company + id: number + name: string + index(id) +end + +class Association + left_id: number + right_id: number + relation: string + strength: number + index(left_id, relation) + index(right_id, relation) +end + +Person(id: 1, name: "Ada") +Company(id: 7, name: "Felidae") + +@mixfix(pattern: "{person: Person} works at {company: Company}") +worksAt() => + return Association( + left_id: person.id, + right_id: company.id, + relation: "works at", + strength: 3.421 + ) +end + +main() => + people := fx.cast_(Person.all()) + companies := fx.cast_(Company.all()) + person := people.get(position: 0) + company := companies.get(position: 0) + return person works at company +end diff --git a/vim-extension b/vim-extension index 7973698..e2fe2ec 160000 --- a/vim-extension +++ b/vim-extension @@ -1 +1 @@ -Subproject commit 7973698ec0a98a0b751df54e80f1cca4e68ac9ff +Subproject commit e2fe2ec18eb782494e31b5f65a09d0f900c9d6b4 diff --git a/vs-code-extension b/vs-code-extension index 93a9437..dc0bf43 160000 --- a/vs-code-extension +++ b/vs-code-extension @@ -1 +1 @@ -Subproject commit 93a943747f062bc8c681cc91394ea55fc244ab10 +Subproject commit dc0bf4347d4d2aaa478e141f556fc5f7a5f248ab From e32c679bddb18fcb7d80a3870d6926e622ffd675 Mon Sep 17 00:00:00 2001 From: vishalkrishnaag Date: Fri, 11 Sep 2026 16:17:34 +0000 Subject: [PATCH 3/6] vm and unwanted tooling removed --- CMakeLists.txt | 1039 ------ src/Env.cpp | 236 ++ src/Env.h | 174 + src/FelidaeRuntime.cpp | 331 ++ src/FelidaeRuntime.h | 53 + src/Interpreter.cpp | 2745 ++++++++++++++ src/Interpreter.h | 478 +++ src/Memory.cpp | 1754 +++++++++ src/Memory.h | 402 ++ src/NativeRuntime.cpp | 301 ++ src/NativeRuntime.h | 83 + src/ParserMetrics.h | 29 + src/form/BinaryIr.cpp | 347 -- src/form/BinaryIr.h | 26 - src/form/BuiltinOperation.h | 477 --- src/form/IrModule.cpp | 135 - src/form/IrModule.h | 51 - src/form/LibTorchTensorRuntime.cpp | 169 - src/form/LibTorchTensorRuntime.h | 18 - src/form/NumericOperation.h | 118 - src/form/RegisterVm.cpp | 4473 ----------------------- src/form/RegisterVm.h | 678 ---- src/form/RuntimeStateModel.cpp | 716 ---- src/form/RuntimeStateModel.h | 98 - src/form/RuntimeTraining.cpp | 530 --- src/form/RuntimeTraining.h | 103 - src/form/RuntimeTrainingCommand.h | 9 - src/form/SemanticOperation.h | 53 - src/form/TensorOperation.h | 126 - src/form/libs/Builtin.cpp | 565 --- src/form/libs/Builtin.h | 24 - src/form/libs/Csv.cpp | 226 -- src/form/libs/Csv.h | 18 - src/form/libs/Db.cpp | 327 -- src/form/libs/Db.h | 22 - src/form/libs/ExecutionVectorMemory.cpp | 45 - src/form/libs/ExecutionVectorMemory.h | 26 - src/form/libs/FactStorageCodec.cpp | 438 --- src/form/libs/FactStorageCodec.h | 44 - src/form/libs/Group.cpp | 166 - src/form/libs/Group.h | 14 - src/form/libs/Json.cpp | 57 - src/form/libs/Json.h | 21 - src/form/libs/RocksDb.cpp | 145 - src/form/libs/RocksDb.h | 54 - src/form/libs/Set.cpp | 201 - src/form/libs/Set.h | 14 - src/main.cpp | 386 +- src/tooling/SourceParser.cpp | 243 -- src/tooling/SourceParser.h | 38 - 50 files changed, 6867 insertions(+), 11959 deletions(-) delete mode 100644 CMakeLists.txt create mode 100644 src/Env.cpp create mode 100644 src/Env.h create mode 100644 src/FelidaeRuntime.cpp create mode 100644 src/FelidaeRuntime.h create mode 100644 src/Interpreter.cpp create mode 100644 src/Interpreter.h create mode 100644 src/Memory.cpp create mode 100644 src/Memory.h create mode 100644 src/NativeRuntime.cpp create mode 100644 src/NativeRuntime.h create mode 100644 src/ParserMetrics.h delete mode 100644 src/form/BinaryIr.cpp delete mode 100644 src/form/BinaryIr.h delete mode 100644 src/form/BuiltinOperation.h delete mode 100644 src/form/IrModule.cpp delete mode 100644 src/form/IrModule.h delete mode 100644 src/form/LibTorchTensorRuntime.cpp delete mode 100644 src/form/LibTorchTensorRuntime.h delete mode 100644 src/form/NumericOperation.h delete mode 100644 src/form/RegisterVm.cpp delete mode 100644 src/form/RegisterVm.h delete mode 100644 src/form/RuntimeStateModel.cpp delete mode 100644 src/form/RuntimeStateModel.h delete mode 100644 src/form/RuntimeTraining.cpp delete mode 100644 src/form/RuntimeTraining.h delete mode 100644 src/form/RuntimeTrainingCommand.h delete mode 100644 src/form/SemanticOperation.h delete mode 100644 src/form/TensorOperation.h delete mode 100644 src/form/libs/Builtin.cpp delete mode 100644 src/form/libs/Builtin.h delete mode 100644 src/form/libs/Csv.cpp delete mode 100644 src/form/libs/Csv.h delete mode 100644 src/form/libs/Db.cpp delete mode 100644 src/form/libs/Db.h delete mode 100644 src/form/libs/ExecutionVectorMemory.cpp delete mode 100644 src/form/libs/ExecutionVectorMemory.h delete mode 100644 src/form/libs/FactStorageCodec.cpp delete mode 100644 src/form/libs/FactStorageCodec.h delete mode 100644 src/form/libs/Group.cpp delete mode 100644 src/form/libs/Group.h delete mode 100644 src/form/libs/Json.cpp delete mode 100644 src/form/libs/Json.h delete mode 100644 src/form/libs/RocksDb.cpp delete mode 100644 src/form/libs/RocksDb.h delete mode 100644 src/form/libs/Set.cpp delete mode 100644 src/form/libs/Set.h delete mode 100644 src/tooling/SourceParser.cpp delete mode 100644 src/tooling/SourceParser.h diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 48a72d7..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,1039 +0,0 @@ -cmake_minimum_required(VERSION 3.21) -project(felidae LANGUAGES CXX) - -set(FELIDAE_VERSION "0.2.3-beta.1" CACHE STRING - "Version recorded in staged Felidae distributions") - -# Keep all generated CMake state under one ignored repository directory. -# Supported layouts include build/ itself and named configurations such as -# build/debug, build/asan, and build/release. -get_filename_component(FELIDAE_BUILD_ROOT "${CMAKE_SOURCE_DIR}/build" ABSOLUTE) -get_filename_component(FELIDAE_BINARY_DIR "${CMAKE_BINARY_DIR}" ABSOLUTE) -string(FIND "${FELIDAE_BINARY_DIR}/" "${FELIDAE_BUILD_ROOT}/" - FELIDAE_BUILD_ROOT_POSITION) -if(NOT FELIDAE_BUILD_ROOT_POSITION EQUAL 0) - message(FATAL_ERROR - "Felidae build directories must be inside ${FELIDAE_BUILD_ROOT}. " - "Use -B build/ (for example, -B build/debug).") -endif() - -set(CMAKE_CXX_STANDARD 20) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -option(FELIDAE_ENABLE_SANITIZERS - "Build compiler, register VM, and tooling with address/undefined-behavior sanitizers" OFF) -option(FELIDAE_BUILD_TESTS "Build Felidae regression tests" ON) -option(FELIDAE_ENABLE_STRICT_WARNINGS - "Enable strict warnings for Felidae-owned targets only" OFF) -option(FELIDAE_ENABLE_MSVC_STATIC_ANALYSIS - "Enable MSVC /analyze on compiler and Form VM targets" OFF) -option(FELIDAE_ENABLE_CCACHE "Reuse native compilation results with ccache" ON) -if(FELIDAE_ENABLE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER) - find_program(FELIDAE_CCACHE_PROGRAM ccache) - if(FELIDAE_CCACHE_PROGRAM) - set(CMAKE_CXX_COMPILER_LAUNCHER - "${CMAKE_COMMAND};-E;env;CCACHE_DIR=${CMAKE_BINARY_DIR}/ccache;${FELIDAE_CCACHE_PROGRAM}") - endif() -endif() -if(ANDROID) - set(FELIDAE_LIBTORCH_DEFAULT OFF) -else() - set(FELIDAE_LIBTORCH_DEFAULT ON) -endif() -option(FELIDAE_ENABLE_LIBTORCH - "Enable mandatory desktop LibTorch support; disable only on targets where LibTorch is unavailable" - ${FELIDAE_LIBTORCH_DEFAULT}) -option(FELIDAE_ENABLE_TRAINING - "Build explicit compiler and VM C++ model-training commands" OFF) -option(FELIDAE_ENABLE_FAISS - "Retain execution-local SSM hidden vectors in real Faiss indexes" OFF) -if(FELIDAE_ENABLE_FAISS) - if(NOT FELIDAE_ENABLE_LIBTORCH) - message(FATAL_ERROR "FELIDAE_ENABLE_FAISS requires FELIDAE_ENABLE_LIBTORCH=ON") - endif() - find_package(OpenMP REQUIRED COMPONENTS CXX) - find_package(faiss CONFIG REQUIRED) - add_library(felidae_execution_vectors STATIC src/form/libs/ExecutionVectorMemory.cpp) - target_include_directories(felidae_execution_vectors PUBLIC src) - target_compile_features(felidae_execution_vectors PUBLIC cxx_std_20) - target_compile_definitions(felidae_execution_vectors INTERFACE FELIDAE_HAS_FAISS=1) - target_link_libraries(felidae_execution_vectors PRIVATE faiss) -endif() -if(ANDROID) - set(FELIDAE_ROCKSDB_DEFAULT OFF) -else() - set(FELIDAE_ROCKSDB_DEFAULT ON) -endif() -option(FELIDAE_ENABLE_ROCKSDB - "Enable the disk-backed ordered Felidae fact-store driver" - ${FELIDAE_ROCKSDB_DEFAULT}) - -if(FELIDAE_ENABLE_TRAINING AND NOT FELIDAE_ENABLE_LIBTORCH) - message(FATAL_ERROR - "FELIDAE_ENABLE_TRAINING requires FELIDAE_ENABLE_LIBTORCH=ON") -endif() - -if(FELIDAE_ENABLE_ROCKSDB) - find_package(PkgConfig QUIET) - if(PkgConfig_FOUND) - pkg_check_modules(FELIDAE_ROCKSDB QUIET IMPORTED_TARGET rocksdb) - endif() - if(TARGET PkgConfig::FELIDAE_ROCKSDB) - set(FELIDAE_ROCKSDB_TARGET PkgConfig::FELIDAE_ROCKSDB) - else() - find_path(FELIDAE_ROCKSDB_INCLUDE_DIR rocksdb/db.h) - find_library(FELIDAE_ROCKSDB_LIBRARY NAMES rocksdb) - if(FELIDAE_ROCKSDB_INCLUDE_DIR AND FELIDAE_ROCKSDB_LIBRARY) - add_library(felidae_rocksdb UNKNOWN IMPORTED) - set_target_properties(felidae_rocksdb PROPERTIES - IMPORTED_LOCATION "${FELIDAE_ROCKSDB_LIBRARY}" - INTERFACE_INCLUDE_DIRECTORIES "${FELIDAE_ROCKSDB_INCLUDE_DIR}") - set(FELIDAE_ROCKSDB_TARGET felidae_rocksdb) - else() - message(FATAL_ERROR - "FELIDAE_ENABLE_ROCKSDB=ON requires RocksDB development files. " - "On Debian/Ubuntu install librocksdb-dev; on macOS install " - "rocksdb with Homebrew; or configure Android/unsupported " - "targets with -DFELIDAE_ENABLE_ROCKSDB=OFF.") - endif() - endif() -endif() - -# Keep the lexical model native and reproducible: SentencePiece is pinned as a -# git submodule instead of being found from an arbitrary system installation. -set(SPM_BUILD_TEST OFF CACHE BOOL "" FORCE) -set(SPM_ENABLE_SHARED OFF CACHE BOOL "" FORCE) -set(SPM_ENABLE_TCMALLOC OFF CACHE BOOL "" FORCE) -set(FELIDAE_HOST_PROTOC "" CACHE FILEPATH - "Native protoc used while cross-compiling SentencePiece") -if(FELIDAE_HOST_PROTOC) - if(NOT EXISTS "${FELIDAE_HOST_PROTOC}") - message(FATAL_ERROR "FELIDAE_HOST_PROTOC does not exist") - endif() - set(SPM_PROTOC_EXECUTABLE "${FELIDAE_HOST_PROTOC}" CACHE FILEPATH "" FORCE) -elseif(CMAKE_CROSSCOMPILING) - message(FATAL_ERROR - "Cross-compiling requires -DFELIDAE_HOST_PROTOC=/path/to/native/protoc") -endif() -# SentencePiece otherwise fetches these sources while configuring. Use their -# pinned submodules when initialized; an archive/source-only checkout retains -# SentencePiece's normal FetchContent behavior instead of referring to a -# nonexistent local path. FetchContent preserves the dependency hyphen. -if(EXISTS "${CMAKE_SOURCE_DIR}/third_party/abseil-cpp/CMakeLists.txt") - set("FETCHCONTENT_SOURCE_DIR_ABSEIL-CPP" "${CMAKE_SOURCE_DIR}/third_party/abseil-cpp" - CACHE PATH "Pinned Abseil source used by SentencePiece" FORCE) -endif() -if(EXISTS "${CMAKE_SOURCE_DIR}/third_party/protobuf/CMakeLists.txt") - set(FETCHCONTENT_SOURCE_DIR_PROTOBUF "${CMAKE_SOURCE_DIR}/third_party/protobuf" - CACHE PATH "Pinned Protobuf source used by SentencePiece" FORCE) -endif() -add_subdirectory(third_party/sentencepiece EXCLUDE_FROM_ALL) -add_subdirectory(third_party/nlohmann_json EXCLUDE_FROM_ALL) - -# SentencePiece's generated public headers include Protobuf headers such as -# google/protobuf/port_def.inc. Its vendored CMake build keeps the Protobuf -# dependency private, so downstream Felidae targets otherwise compile without -# the pinned Protobuf include directory. Export only the required header path -# through the two SentencePiece targets that Felidae consumes. -foreach(FELIDAE_SENTENCEPIECE_TARGET sentencepiece-static sentencepiece_train-static) - if(TARGET ${FELIDAE_SENTENCEPIECE_TARGET}) - target_include_directories(${FELIDAE_SENTENCEPIECE_TARGET} SYSTEM INTERFACE - "${CMAKE_SOURCE_DIR}/third_party/protobuf/src") - endif() -endforeach() -find_package(OpenMP) -if(FELIDAE_BUILD_TESTS) - find_package(Threads REQUIRED) -endif() - -# These paths are also part of the isolated LibTorch trainer's manifest -# contract, so define them before that target is created. -set(FELIDAE_SENTENCEPIECE_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/models") -set(FELIDAE_SENTENCEPIECE_MODEL_PATH "${FELIDAE_SENTENCEPIECE_GENERATED_DIR}/felidae.model") -set(FELIDAE_SENTENCEPIECE_IDS_HEADER - "${FELIDAE_SENTENCEPIECE_GENERATED_DIR}/FelidaeSentencePieceIds.h") -set(FELIDAE_SENTENCEPIECE_DATASET - "${CMAKE_CURRENT_SOURCE_DIR}/datasets/tokenizer/felidae-tokenizer-v1.jsonl") - -# SentencePiece owns the pinned Protobuf target used by the project. Find -# LibTorch afterwards so its bundled dependency discovery cannot create a -# second protobuf::libprotobuf target on Windows. -if(FELIDAE_ENABLE_LIBTORCH) - find_package(Torch REQUIRED) - # Shared LibTorch embeds the Protobuf implementation used by - # libtorch_cpu. Its Caffe2 package normally supplies a dummy - # protobuf::libprotobuf interface target, but SentencePiece has already - # created that target for its pinned frontend dependency by the time - # TorchConfig is loaded. Caffe2 then accidentally propagates Felidae's - # full static Protobuf through torch_cpu, placing both libprotobuf and - # libprotobuf-lite in the compiler link. Remove exactly that unintended - # interface edge; SentencePiece keeps its own required lite dependency, - # and LibTorch continues to use the implementation embedded in its shared - # library. - if(TARGET torch_cpu) - get_target_property(FELIDAE_TORCH_CPU_LINK_LIBRARIES - torch_cpu INTERFACE_LINK_LIBRARIES) - if(FELIDAE_TORCH_CPU_LINK_LIBRARIES) - # CMake/LibTorch versions may wrap this entry in $; - # filter by target spelling rather than relying on an exact item. - list(FILTER FELIDAE_TORCH_CPU_LINK_LIBRARIES EXCLUDE REGEX - "protobuf::libprotobuf") - set_target_properties(torch_cpu PROPERTIES - INTERFACE_LINK_LIBRARIES - "${FELIDAE_TORCH_CPU_LINK_LIBRARIES}") - endif() - endif() - # The prebuilt Windows LibTorch distribution is Release-only. Linking it - # into a Debug MSVC binary corrupts STL-owned module registration state at - # runtime (typically an access violation in std::vector). Fail during - # configuration with the corrective command instead of emitting a binary - # that can crash while constructing a GRU. - if(MSVC AND CMAKE_BUILD_TYPE STREQUAL "Debug") - message(FATAL_ERROR - "FELIDAE_ENABLE_LIBTORCH requires a Release CMAKE_BUILD_TYPE with the installed LibTorch package. Reconfigure the existing build directory with -DCMAKE_BUILD_TYPE=Release.") - endif() - - # Keep LibTorch's bundled Protobuf headers out of every translation unit - # that includes SentencePiece's generated Protobuf classes. The backend - # communicates with the compiler through integer IDs and typed model - # interfaces, so it can be compiled as a clean dependency island. - add_library(felidae_mixfix_torch STATIC src/MixfixStateModel.cpp) - if(FELIDAE_ENABLE_TRAINING) - target_sources(felidae_mixfix_torch PRIVATE tools/TrainMixfixGru.cpp) - endif() - target_include_directories(felidae_mixfix_torch PRIVATE src) - target_include_directories(felidae_mixfix_torch SYSTEM PRIVATE - third_party - third_party/nlohmann_json/include - ${TORCH_INCLUDE_DIRS}) - target_compile_definitions(felidae_mixfix_torch PRIVATE - FELIDAE_HAS_TORCH=1 - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") - target_link_libraries(felidae_mixfix_torch PRIVATE ${TORCH_LIBRARIES}) -endif() - -add_executable(felidae_sentencepiece_model_generator EXCLUDE_FROM_ALL - tools/GenerateSentencePieceModel.cpp) -target_include_directories(felidae_sentencepiece_model_generator PRIVATE src) -target_compile_definitions(felidae_sentencepiece_model_generator PRIVATE - FELIDAE_GENERATING_MODEL=1) -target_include_directories(felidae_sentencepiece_model_generator BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_include_directories(felidae_sentencepiece_model_generator SYSTEM PRIVATE - third_party/nlohmann_json/include) -target_link_libraries(felidae_sentencepiece_model_generator PRIVATE sentencepiece_train) -target_link_libraries(felidae_sentencepiece_model_generator PRIVATE nlohmann_json::nlohmann_json) -if(TARGET OpenMP::OpenMP_CXX) - target_link_libraries(felidae_sentencepiece_model_generator PRIVATE OpenMP::OpenMP_CXX) -endif() - -# The lexical model and matching ID header are versioned release inputs, but -# models/*.model and models/FelidaeSentencePieceIds.h are also .gitignore'd -# (see .gitignore) rather than committed, so a fresh clone or a cleared -# models/ directory legitimately has neither -- there is nothing to "restore -# from Git". Generate them as a normal, ordered step of the build graph -# instead of failing configure: felidae_sentencepiece_model_generator is -# built first, then run once against the authoritative grammar/dataset -# inputs below, and only then do targets that need the model (anything using -# felidae_use_sentencepiece_model()) build. A single normal -# `cmake --build ... --target felidae_compiler felidae_vm` therefore works -# unattended on a machine that has never had models/ populated. -# -# A configure-time `if(NOT EXISTS ...) message(FATAL_ERROR ...)` guard used -# to sit here instead. It made the project unrecoverable through CMake alone -# whenever these files were missing: configure aborted before -# felidae_regenerate_sentencepiece_model (the target that would have fixed -# it) was even defined, and every subsequent configure attempt hit the same -# FATAL_ERROR before reaching it. Do not reintroduce a configure-time -# existence check here for that reason -- the OUTPUT-based custom command -# below is the correct place to encode "build these files if missing". -add_custom_command( - OUTPUT "${FELIDAE_SENTENCEPIECE_MODEL_PATH}" "${FELIDAE_SENTENCEPIECE_IDS_HEADER}" - COMMAND "${CMAKE_COMMAND}" -E make_directory "${FELIDAE_SENTENCEPIECE_GENERATED_DIR}" - COMMAND $ - "${FELIDAE_SENTENCEPIECE_MODEL_PATH}" "${FELIDAE_SENTENCEPIECE_IDS_HEADER}" - "${FELIDAE_SENTENCEPIECE_DATASET}" - DEPENDS felidae_sentencepiece_model_generator - tools/GenerateSentencePieceModel.cpp src/FelidaeGrammar.h - "${FELIDAE_SENTENCEPIECE_DATASET}" - COMMENT "Generating the Felidae SentencePiece model and token IDs (runs only when missing or stale)" - VERBATIM) -add_custom_target(felidae_sentencepiece_model - DEPENDS "${FELIDAE_SENTENCEPIECE_MODEL_PATH}" "${FELIDAE_SENTENCEPIECE_IDS_HEADER}") - -# Explicit alias for a maintainer who wants to force regeneration by name -# (e.g. after intentionally editing the grammar or dataset) without having to -# know the underlying OUTPUT paths. Behaves identically to building -# felidae_sentencepiece_model; kept as a separate name for that discoverability. -add_custom_target(felidae_regenerate_sentencepiece_model - DEPENDS "${FELIDAE_SENTENCEPIECE_MODEL_PATH}" "${FELIDAE_SENTENCEPIECE_IDS_HEADER}") - -function(felidae_use_sentencepiece_model target) - add_dependencies(${target} felidae_sentencepiece_model) - # SentencePiece's checked-in generated protobuf classes must see the - # matching pinned protobuf API before LibTorch's bundled protobuf headers. - # A normal -I path precedes every -isystem path on GCC/Clang, including - # /opt/libtorch, while remaining scoped to SentencePiece consumers. - target_include_directories(${target} BEFORE PRIVATE - "${CMAKE_SOURCE_DIR}/third_party/protobuf/src" - "${FELIDAE_SENTENCEPIECE_GENERATED_DIR}") - target_compile_definitions(${target} PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") -endfunction() - -# Explicit opt-in only: it never runs during normal builds or tests. -add_executable(felidae_integer_parser_benchmark EXCLUDE_FROM_ALL - tools/IntegerParserBenchmark.cpp - src/MixfixStateModel.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp) -target_include_directories(felidae_integer_parser_benchmark PRIVATE src) -target_include_directories(felidae_integer_parser_benchmark BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_compile_definitions(felidae_integer_parser_benchmark PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") -target_link_libraries(felidae_integer_parser_benchmark PRIVATE felidae_form sentencepiece) -felidae_use_sentencepiece_model(felidae_integer_parser_benchmark) - -# Explicit, bounded source -> verified executable IR -> VM capability benchmark. -# It is excluded from ALL so routine builds never build benchmark workloads. -add_executable(felidae_reasoning_benchmark EXCLUDE_FROM_ALL - tools/ReasoningBenchmark.cpp - src/CompilerFrontend.cpp - src/MixfixStateModel.cpp - src/IrCodeGenerator.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp) -target_include_directories(felidae_reasoning_benchmark PRIVATE src) -target_include_directories(felidae_reasoning_benchmark BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_include_directories(felidae_reasoning_benchmark SYSTEM PRIVATE third_party) -target_link_libraries(felidae_reasoning_benchmark PRIVATE felidae_form sentencepiece) -felidae_use_sentencepiece_model(felidae_reasoning_benchmark) -target_compile_options(felidae_reasoning_benchmark PRIVATE - $<$:-Wall -Wextra -Wnon-virtual-dtor -Wold-style-cast -Woverloaded-virtual> - $<$:/W4>) -if(MSVC) - target_compile_options(felidae_reasoning_benchmark PRIVATE /EHsc) -endif() -set_target_properties(felidae_reasoning_benchmark PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}") - -# Corpus extraction reuses the source parser and deterministic IR lowering as -# its only teacher. It is explicit: normal builds never create or retrain ML -# artifacts. -add_executable(felidae_extract_mixfix_dataset EXCLUDE_FROM_ALL - tools/ExtractMixfixDataset.cpp - src/CompilerFrontend.cpp - src/IrCodeGenerator.cpp - src/MixfixStateModel.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp) -target_include_directories(felidae_extract_mixfix_dataset PRIVATE src) -target_include_directories(felidae_extract_mixfix_dataset BEFORE PRIVATE - third_party/sentencepiece third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_include_directories(felidae_extract_mixfix_dataset SYSTEM PRIVATE third_party) -target_compile_definitions(felidae_extract_mixfix_dataset PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") -target_link_libraries(felidae_extract_mixfix_dataset PRIVATE felidae_form sentencepiece nlohmann_json::nlohmann_json) -if(MSVC) - target_compile_options(felidae_extract_mixfix_dataset PRIVATE /EHsc) -endif() -felidae_use_sentencepiece_model(felidae_extract_mixfix_dataset) - -function(felidae_enable_sanitizers target) - if(NOT FELIDAE_ENABLE_SANITIZERS) - return() - endif() - if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - target_compile_options(${target} PRIVATE /fsanitize=address /Zi) - target_link_options(${target} PRIVATE /INCREMENTAL:NO) - elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU") - target_compile_options(${target} PRIVATE - -fsanitize=address,undefined -fno-omit-frame-pointer) - target_link_options(${target} PRIVATE - -fsanitize=address,undefined -fno-omit-frame-pointer) - else() - message(FATAL_ERROR - "FELIDAE_ENABLE_SANITIZERS is unsupported by ${CMAKE_CXX_COMPILER_ID}") - endif() -endfunction() - -function(felidae_enable_quality_warnings target) - if(NOT FELIDAE_ENABLE_STRICT_WARNINGS) - return() - endif() - if(MSVC) - target_compile_options(${target} PRIVATE /W4 /EHsc /permissive-) - elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU") - target_compile_options(${target} PRIVATE - -Wconversion -Wsign-conversion -Wformat=2 -Wformat-overflow=2 - -Wformat-truncation=2 -Wstringop-overflow=4 -Wstringop-truncation - -Warray-bounds=2 -Walloc-zero -Walloca -Wcast-align -Wcast-qual - -Wdouble-promotion -Wduplicated-cond -Wduplicated-branches -Wlogical-op - -Wnull-dereference -Wpointer-arith -Wredundant-decls -Wswitch-enum - -Wundef -Wuninitialized -Wmaybe-uninitialized -Wuse-after-free=3 -Wvla - -Wunused -Wunused-function -Wunused-variable -Wunused-parameter) - endif() -endfunction() - -function(felidae_enable_static_analysis target) - if(MSVC AND FELIDAE_ENABLE_MSVC_STATIC_ANALYSIS) - target_compile_options(${target} PRIVATE /analyze /analyze:external-) - endif() -endfunction() - -function(felidae_enable_msvc_exceptions target) - if(MSVC) - # Source, IR, and binary diagnostics use exceptions. Scope this to - # Felidae targets so dependency builds retain their upstream flags. - target_compile_options(${target} PRIVATE /EHsc) - endif() -endfunction() - -if(TARGET felidae_mixfix_torch) - felidae_enable_msvc_exceptions(felidae_mixfix_torch) - felidae_enable_static_analysis(felidae_mixfix_torch) -endif() - -# Form is the AST/parser-free executable IR, binary, and register-VM boundary. Keeping it -# as one library prevents the compiler and standalone VM from compiling two -# subtly different copies of the runtime. -add_library(felidae_form STATIC - src/form/BinaryIr.cpp - src/form/IrModule.cpp - src/form/RegisterVm.cpp - src/form/RuntimeTraining.cpp - src/form/libs/Builtin.cpp - src/form/libs/Csv.cpp - src/form/libs/Db.cpp - src/form/libs/FactStorageCodec.cpp - src/form/libs/Group.cpp - src/form/libs/Json.cpp - src/form/libs/Set.cpp) -if(FELIDAE_ENABLE_ROCKSDB) - target_sources(felidae_form PRIVATE src/form/libs/RocksDb.cpp) - target_compile_definitions(felidae_form PUBLIC FELIDAE_HAS_ROCKSDB=1) - target_link_libraries(felidae_form PRIVATE ${FELIDAE_ROCKSDB_TARGET}) -endif() -target_include_directories(felidae_form PUBLIC src) -target_link_libraries(felidae_form PRIVATE nlohmann_json::nlohmann_json) -felidae_enable_static_analysis(felidae_form) -felidae_enable_msvc_exceptions(felidae_form) - -if(FELIDAE_ENABLE_ROCKSDB) - add_executable(felidae_fact_store_benchmark EXCLUDE_FROM_ALL - tools/FactStoreBenchmark.cpp) - target_link_libraries(felidae_fact_store_benchmark PRIVATE felidae_form) - target_compile_definitions(felidae_fact_store_benchmark PRIVATE - FELIDAE_BENCHMARK_OUTPUT_DIR="${CMAKE_BINARY_DIR}/benchmarks") - felidae_enable_static_analysis(felidae_fact_store_benchmark) - felidae_enable_msvc_exceptions(felidae_fact_store_benchmark) - set_target_properties(felidae_fact_store_benchmark PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") -endif() - -if(TARGET felidae_mixfix_torch) - target_link_libraries(felidae_mixfix_torch PRIVATE felidae_form) -endif() - -add_executable(felidae_vm - src/VmMain.cpp - src/SentencePieceModel.cpp) -target_link_libraries(felidae_vm PRIVATE felidae_form sentencepiece) -target_include_directories(felidae_vm BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_compile_definitions(felidae_vm PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") -felidae_use_sentencepiece_model(felidae_vm) -felidae_enable_msvc_exceptions(felidae_vm) -set_target_properties(felidae_vm PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}") -felidae_enable_static_analysis(felidae_vm) -if(FELIDAE_ENABLE_FAISS) - felidae_enable_msvc_exceptions(felidae_execution_vectors) - felidae_enable_static_analysis(felidae_execution_vectors) - target_link_libraries(felidae_vm PRIVATE felidae_execution_vectors) -endif() - -if(FELIDAE_ENABLE_LIBTORCH) - # The daemon owns an optional runtime-only GRU. Form itself remains free - # of LibTorch and all compiler/parser dependencies. - target_sources(felidae_vm PRIVATE - src/form/LibTorchTensorRuntime.cpp - src/form/RuntimeStateModel.cpp) - if(FELIDAE_ENABLE_TRAINING) - target_sources(felidae_vm PRIVATE tools/TrainRuntimeGru.cpp) - target_compile_definitions(felidae_vm PRIVATE FELIDAE_HAS_TRAINING=1) - endif() - target_compile_definitions(felidae_vm PRIVATE FELIDAE_HAS_TORCH=1) - target_include_directories(felidae_vm SYSTEM PRIVATE ${TORCH_INCLUDE_DIRS}) - target_link_libraries(felidae_vm PRIVATE ${TORCH_LIBRARIES}) -endif() - -# Portable shipping folder. Release staging is a build product and therefore -# remains inside the selected build tree instead of modifying the source tree. -set(FELIDAE_DIST_DIR "${CMAKE_BINARY_DIR}/dist") -set(FELIDAE_DIST_COMMAND - "${CMAKE_COMMAND}" - "-DFELIDAE_DIST_DIR=${FELIDAE_DIST_DIR}" - "-DFELIDAE_DIST_BUILD_DIR=${CMAKE_BINARY_DIR}" - "-DFELIDAE_DIST_CONFIG=$" - "-DFELIDAE_DIST_EXECUTABLE_SUFFIX=${CMAKE_EXECUTABLE_SUFFIX}" - "-DFELIDAE_DIST_MODEL_DIR=${CMAKE_SOURCE_DIR}/models" - "-DFELIDAE_DIST_LICENSE_DIR=${CMAKE_SOURCE_DIR}/third_party" - "-DFELIDAE_DIST_VERSION=${FELIDAE_VERSION}") -if(FELIDAE_ENABLE_LIBTORCH) - list(APPEND FELIDAE_DIST_COMMAND "-DFELIDAE_DIST_HAS_LIBTORCH=1") - list(APPEND FELIDAE_DIST_COMMAND - "-DFELIDAE_DIST_TORCH_ROOT=${TORCH_INSTALL_PREFIX}") -else() - list(APPEND FELIDAE_DIST_COMMAND "-DFELIDAE_DIST_HAS_LIBTORCH=0") -endif() -list(APPEND FELIDAE_DIST_COMMAND "-P" "${CMAKE_SOURCE_DIR}/cmake/StageDistribution.cmake") -add_custom_target(felidae_dist - COMMAND ${FELIDAE_DIST_COMMAND} - DEPENDS felidae_compiler felidae_vm felidae_debugger felidae_sentencepiece_model - COMMENT "Staging portable Felidae distribution in ${FELIDAE_DIST_DIR}") - -# Explicit runtime-corpus boundary. The tool accepts only verified .bin input -# and emits a unary Identity teacher for its typed result. Symbol context is -# stored as complete SentencePiece ID sequences. It never -# hashes source names into semantic operation IDs or invents context queries. -add_executable(felidae_build_runtime_dataset EXCLUDE_FROM_ALL - tools/BuildRuntimeTrainingDataset.cpp - src/SentencePieceModel.cpp) -target_link_libraries(felidae_build_runtime_dataset PRIVATE felidae_form sentencepiece) -target_include_directories(felidae_build_runtime_dataset BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_compile_definitions(felidae_build_runtime_dataset PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") -felidae_use_sentencepiece_model(felidae_build_runtime_dataset) -felidae_enable_msvc_exceptions(felidae_build_runtime_dataset) -set_target_properties(felidae_build_runtime_dataset PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}") - -if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 8) - message(FATAL_ERROR "Felidae requires GCC 8 or newer for std::filesystem. Use GCC 8+, Clang 7+, AppleClang 10+, or MSVC 2019+.") -endif() - -add_executable(felidae_compiler - src/main.cpp - src/CompilerFrontend.cpp - src/IrCodeGenerator.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp -) -# The command-line entry point has a stable location on every generator. -# In particular, Visual Studio's multi-config generator otherwise places it -# below build\\Debug or build\\Release, which makes build.cmd/build.ps1 -# unexpectedly fail to leave build\\felidae_compiler.exe behind. -set_target_properties(felidae_compiler PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}") - -target_include_directories(felidae_compiler PRIVATE src) -target_include_directories(felidae_compiler BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_include_directories(felidae_compiler SYSTEM PRIVATE third_party) -target_compile_definitions(felidae_compiler PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") -felidae_enable_msvc_exceptions(felidae_compiler) -target_link_libraries(felidae_compiler PRIVATE felidae_form sentencepiece nlohmann_json::nlohmann_json) -if(FELIDAE_ENABLE_LIBTORCH) - target_compile_definitions(felidae_compiler PRIVATE FELIDAE_HAS_TORCH=1) - if(FELIDAE_ENABLE_TRAINING) - target_compile_definitions(felidae_compiler PRIVATE FELIDAE_HAS_TRAINING=1) - endif() - target_link_libraries(felidae_compiler PRIVATE felidae_mixfix_torch) - # Training is an explicit subcommand of felidae_compiler/felidae_vm. Do - # not create separate trainer executables in build/. -else() - target_sources(felidae_compiler PRIVATE src/MixfixStateModel.cpp) -endif() -if(FELIDAE_ENABLE_LIBTORCH) - foreach(FELIDAE_TORCH_EXECUTABLE felidae_compiler felidae_vm) - add_custom_command(TARGET ${FELIDAE_TORCH_EXECUTABLE} POST_BUILD - COMMAND "${CMAKE_COMMAND}" - "-DFELIDAE_EXECUTABLE=$" - "-DFELIDAE_TORCH_LIB_DIR=${TORCH_INSTALL_PREFIX}/lib" - "-DFELIDAE_OUTPUT_DIR=$" - "-DFELIDAE_RUNTIME_MANIFEST=${CMAKE_BINARY_DIR}/felidae-torch-runtime-${FELIDAE_TORCH_EXECUTABLE}.txt" - -P "${CMAKE_SOURCE_DIR}/cmake/StageTorchRuntime.cmake" - COMMENT "Staging resolved LibTorch DLLs beside ${FELIDAE_TORCH_EXECUTABLE}") - endforeach() -endif() -felidae_use_sentencepiece_model(felidae_compiler) -target_compile_options(felidae_compiler PRIVATE - $<$:-Wall -Wextra -Wnon-virtual-dtor -Wold-style-cast -Woverloaded-virtual> - $<$:/W4> -) -if(UNIX AND NOT APPLE) - target_link_libraries(felidae_compiler PRIVATE dl) -endif() -felidae_enable_sanitizers(felidae_compiler) -felidae_enable_static_analysis(felidae_compiler) - -set(FELIDAE_DEBUG_SOURCES - src/debugger/main.cpp - src/debugger/AstAnalyzer.cpp - src/tooling/SourceParser.cpp - src/CompilerFrontend.cpp - src/IrCodeGenerator.cpp - src/MixfixStateModel.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp -) - -# The source debugger is an explicit developer tool. Leaving it out of ALL -# prevents a normal Debug/RelWithDebInfo build from compiling a second copy of -# the compiler frontend. -add_executable(felidae_debugger EXCLUDE_FROM_ALL ${FELIDAE_DEBUG_SOURCES}) -set_target_properties(felidae_debugger PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}" - RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}") -target_include_directories(felidae_debugger PRIVATE src) -target_include_directories(felidae_debugger BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) -target_include_directories(felidae_debugger SYSTEM PRIVATE third_party) -target_compile_definitions(felidae_debugger PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}") -target_link_libraries(felidae_debugger PRIVATE felidae_form sentencepiece - nlohmann_json::nlohmann_json) -felidae_use_sentencepiece_model(felidae_debugger) -if(TARGET OpenMP::OpenMP_CXX) - target_link_libraries(felidae_debugger PRIVATE OpenMP::OpenMP_CXX) -endif() -target_compile_options(felidae_debugger PRIVATE - $<$:-Wall -Wextra -Wpedantic -Wshadow -Wnon-virtual-dtor -Wold-style-cast -Woverloaded-virtual> - $<$:/W4> -) -felidae_enable_sanitizers(felidae_debugger) - -if(FELIDAE_BUILD_TESTS) - enable_testing() - add_executable(felidae_sentencepiece_model_test - tests/SentencePieceModelTest.cpp - src/MixfixStateModel.cpp - src/IrCodeGenerator.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp) - target_include_directories(felidae_sentencepiece_model_test PRIVATE src) - target_include_directories(felidae_sentencepiece_model_test BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) - target_include_directories(felidae_sentencepiece_model_test SYSTEM PRIVATE third_party) - target_compile_definitions(felidae_sentencepiece_model_test PRIVATE - FELIDAE_SENTENCEPIECE_MODEL_PATH="${FELIDAE_SENTENCEPIECE_MODEL_PATH}" - FELIDAE_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/test-artifacts/sentencepiece-model") - # The regression executable intentionally uses assertions. Keep them - # active even when the rest of Felidae is built in Release mode. - target_compile_options(felidae_sentencepiece_model_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_sentencepiece_model_test) - # This frontend regression compiles executable IR and exercises the same - # verifier implementation linked by the runtime-only felidae_form library. - target_link_libraries(felidae_sentencepiece_model_test PRIVATE felidae_form sentencepiece) - felidae_use_sentencepiece_model(felidae_sentencepiece_model_test) - if(TARGET OpenMP::OpenMP_CXX) - target_link_libraries(felidae_sentencepiece_model_test PRIVATE OpenMP::OpenMP_CXX) - endif() - add_test(NAME felidae_sentencepiece_model COMMAND felidae_sentencepiece_model_test) - - # The tokenizer is a production compiler command, not a helper executable. - # Assert its machine-readable, integer-only output at the CLI boundary. - add_test(NAME felidae_compiler_tokenize_cli - COMMAND $ --tokenize - ${CMAKE_SOURCE_DIR}/v2_examples/mixfix_nested_expression.fx) - set_tests_properties(felidae_compiler_tokenize_cli PROPERTIES - TIMEOUT 30 - PASS_REGULAR_EXPRESSION "^\\[[0-9,]+\\]" - ENVIRONMENT "PATH=${TORCH_INSTALL_PREFIX}/lib;$ENV{PATH}") - - add_executable(felidae_sentencepiece_pipeline_test - tests/SentencePiecePipelineTest.cpp - src/CompilerFrontend.cpp - src/MixfixStateModel.cpp - src/IrCodeGenerator.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp) - target_include_directories(felidae_sentencepiece_pipeline_test PRIVATE src) - target_include_directories(felidae_sentencepiece_pipeline_test BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) - target_include_directories(felidae_sentencepiece_pipeline_test SYSTEM PRIVATE third_party) - target_compile_definitions(felidae_sentencepiece_pipeline_test PRIVATE - FELIDAE_PIPELINE_FIXTURE_PATH="${CMAKE_SOURCE_DIR}/v2_examples/sentencepiece_pipeline.fx" - FELIDAE_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/test-artifacts/sentencepiece-pipeline" - FELIDAE_FACT_EXPRESSION_FIXTURE_PATH="${CMAKE_SOURCE_DIR}/v2_examples/fact_expression_result_contract.fx" - FELIDAE_COFFEE_REASONING_FIXTURE_PATH="${CMAKE_SOURCE_DIR}/v2_examples/coffee_vending_theorem_solver.fx" - FELIDAE_HVAC_REASONING_FIXTURE_PATH="${CMAKE_SOURCE_DIR}/v2_examples/air_conditioner_theorem_solver.fx") - target_compile_definitions(felidae_sentencepiece_pipeline_test PRIVATE - FELIDAE_NUMERIC_OPERATIONS_FIXTURE_PATH="${CMAKE_SOURCE_DIR}/v2_examples/numeric_operations.fx") - target_compile_options(felidae_sentencepiece_pipeline_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_sentencepiece_pipeline_test) - target_link_libraries(felidae_sentencepiece_pipeline_test PRIVATE felidae_form sentencepiece) - felidae_use_sentencepiece_model(felidae_sentencepiece_pipeline_test) - if(TARGET OpenMP::OpenMP_CXX) - target_link_libraries(felidae_sentencepiece_pipeline_test PRIVATE OpenMP::OpenMP_CXX) - endif() - if(UNIX AND NOT APPLE) - target_link_libraries(felidae_sentencepiece_pipeline_test PRIVATE dl) - endif() - add_test(NAME felidae_sentencepiece_pipeline COMMAND felidae_sentencepiece_pipeline_test) - set_tests_properties(felidae_sentencepiece_pipeline PROPERTIES TIMEOUT 30) - # Avoid stale Windows handle contention from an interrupted prior test run. - set_target_properties(felidae_sentencepiece_pipeline_test PROPERTIES - OUTPUT_NAME felidae_sentencepiece_pipeline_ir_test) - - add_executable(felidae_mixfix_state_model_test - tests/MixfixStateModelTest.cpp - src/form/RuntimeStateModel.cpp) - target_include_directories(felidae_mixfix_state_model_test PRIVATE src) - if(FELIDAE_ENABLE_FAISS) - target_link_libraries(felidae_mixfix_state_model_test PRIVATE felidae_execution_vectors) - add_executable(felidae_execution_vectors_test tests/ExecutionVectorMemoryTest.cpp) - target_link_libraries(felidae_execution_vectors_test PRIVATE felidae_execution_vectors) - target_compile_options(felidae_execution_vectors_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_execution_vectors_test) - add_test(NAME felidae_execution_vectors COMMAND felidae_execution_vectors_test) - set_tests_properties(felidae_execution_vectors PROPERTIES TIMEOUT 10) - endif() - if(FELIDAE_ENABLE_LIBTORCH) - target_sources(felidae_mixfix_state_model_test PRIVATE - src/CompilerFrontend.cpp - src/IrCodeGenerator.cpp - src/SentencePieceModel.cpp - src/IntegerTokenList.cpp - src/IntegerParser.cpp - src/BuiltinRegistry.cpp) - target_include_directories(felidae_mixfix_state_model_test BEFORE PRIVATE - third_party/sentencepiece - third_party/sentencepiece/src - ${CMAKE_BINARY_DIR}/third_party/sentencepiece/src) - target_include_directories(felidae_mixfix_state_model_test SYSTEM PRIVATE third_party) - target_link_libraries(felidae_mixfix_state_model_test PRIVATE sentencepiece) - felidae_use_sentencepiece_model(felidae_mixfix_state_model_test) - # SentencePiece and LibTorch remain separate translation-unit - # dependency islands even in this combined E2E test. The real compiler - # also emits this FELBIR fixture under build/, after which the test - # loads it through the production binary verifier and executes its - # SemanticEval instruction with a trained, exported, and reloaded - # TorchScript backend. - set(FELIDAE_RUNTIME_SSM_E2E_SOURCE - "${CMAKE_SOURCE_DIR}/v2_examples/runtime_ssm_e2e.fx") - set(FELIDAE_RUNTIME_SSM_E2E_BINARY - "${CMAKE_BINARY_DIR}/runtime_ssm_e2e.bin") - add_custom_command( - OUTPUT "${FELIDAE_RUNTIME_SSM_E2E_BINARY}" - COMMAND $ - "${FELIDAE_RUNTIME_SSM_E2E_SOURCE}" - DEPENDS felidae_compiler "${FELIDAE_RUNTIME_SSM_E2E_SOURCE}" - WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" - COMMENT "Compiling runtime SSM end-to-end FELBIR fixture" - VERBATIM) - add_custom_target(felidae_runtime_ssm_e2e_binary - DEPENDS "${FELIDAE_RUNTIME_SSM_E2E_BINARY}") - add_dependencies(felidae_mixfix_state_model_test - felidae_runtime_ssm_e2e_binary) - target_compile_definitions(felidae_mixfix_state_model_test PRIVATE - FELIDAE_RUNTIME_SSM_E2E_BINARY="${FELIDAE_RUNTIME_SSM_E2E_BINARY}" - FELIDAE_MODEL_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/model-tests") - endif() - target_compile_options(felidae_mixfix_state_model_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_mixfix_state_model_test) - if(FELIDAE_ENABLE_LIBTORCH) - target_compile_definitions(felidae_mixfix_state_model_test PRIVATE FELIDAE_HAS_TORCH=1) - target_include_directories(felidae_mixfix_state_model_test SYSTEM PRIVATE ${TORCH_INCLUDE_DIRS}) - target_link_libraries(felidae_mixfix_state_model_test PRIVATE felidae_mixfix_torch ${TORCH_LIBRARIES}) - add_executable(felidae_libtorch_smoke_test - tests/LibTorchSmoke.cpp - src/form/LibTorchTensorRuntime.cpp) - target_include_directories(felidae_libtorch_smoke_test PRIVATE src) - target_include_directories(felidae_libtorch_smoke_test SYSTEM PRIVATE ${TORCH_INCLUDE_DIRS}) - target_link_libraries(felidae_libtorch_smoke_test PRIVATE felidae_form ${TORCH_LIBRARIES}) - target_compile_options(felidae_libtorch_smoke_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - add_test(NAME felidae_libtorch_smoke COMMAND felidae_libtorch_smoke_test) - set_tests_properties(felidae_libtorch_smoke PROPERTIES - TIMEOUT 30 - ENVIRONMENT "PATH=${TORCH_INSTALL_PREFIX}/lib;$ENV{PATH}") - else() - target_sources(felidae_mixfix_state_model_test PRIVATE src/MixfixStateModel.cpp) - endif() - add_test(NAME felidae_mixfix_state_model COMMAND felidae_mixfix_state_model_test) - if(FELIDAE_ENABLE_LIBTORCH) - set_tests_properties(felidae_mixfix_state_model PROPERTIES - TIMEOUT 30 - ENVIRONMENT "PATH=${TORCH_INSTALL_PREFIX}/lib;$ENV{PATH}") - else() - set_tests_properties(felidae_mixfix_state_model PROPERTIES TIMEOUT 30) - endif() -endif() - -if(FELIDAE_BUILD_TESTS) - # This round-trip test uses the compiler-only lowerer to construct its - # fixture. The isolation test below proves the VM-only link boundary. - add_executable(felidae_form_binary_test tests/FormBinaryIrTest.cpp) - target_link_libraries(felidae_form_binary_test PRIVATE felidae_form) - target_compile_definitions(felidae_form_binary_test PRIVATE - FELIDAE_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/test-artifacts/form-binary") - target_compile_options(felidae_form_binary_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_form_binary_test) - target_link_libraries(felidae_mixfix_state_model_test PRIVATE felidae_form) - add_test(NAME felidae_form_binary COMMAND felidae_form_binary_test) - set_tests_properties(felidae_form_binary PROPERTIES TIMEOUT 30) - - # This target includes only Form headers and links only felidae_form. It - # prevents AST/parser/SentencePiece headers from leaking across the VM - # boundary as the repository is refactored. - add_executable(felidae_form_isolation_test tests/FormIsolationTest.cpp) - target_link_libraries(felidae_form_isolation_test PRIVATE felidae_form) - target_compile_options(felidae_form_isolation_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_form_isolation_test) - add_test(NAME felidae_form_isolation COMMAND felidae_form_isolation_test) - set_tests_properties(felidae_form_isolation PROPERTIES TIMEOUT 30) - - add_executable(felidae_ir_test tests/FelidaeIrTest.cpp) - target_link_libraries(felidae_ir_test PRIVATE felidae_form Threads::Threads - nlohmann_json::nlohmann_json) - target_compile_definitions(felidae_ir_test PRIVATE - FELIDAE_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/test-artifacts/ir") - target_compile_options(felidae_ir_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_ir_test) - add_test(NAME felidae_ir COMMAND felidae_ir_test) - set_tests_properties(felidae_ir PROPERTIES TIMEOUT 30) - - # CSV <-> Fact, round trip, ownership, and atomic automatic persistence - # against real files in a temporary output directory (no mocked - # persistence). - add_executable(felidae_db_csv_test tests/FormDbCsvTest.cpp) - target_link_libraries(felidae_db_csv_test PRIVATE felidae_form - nlohmann_json::nlohmann_json) - target_compile_definitions(felidae_db_csv_test PRIVATE - FELIDAE_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/test-artifacts/db-csv") - target_compile_options(felidae_db_csv_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_db_csv_test) - add_test(NAME felidae_db_csv COMMAND felidae_db_csv_test) - set_tests_properties(felidae_db_csv PROPERTIES TIMEOUT 30) - - if(FELIDAE_ENABLE_ROCKSDB) - add_executable(felidae_rocksdb_test tests/RocksDbTest.cpp) - target_link_libraries(felidae_rocksdb_test PRIVATE felidae_form nlohmann_json::nlohmann_json) - target_compile_definitions(felidae_rocksdb_test PRIVATE - FELIDAE_TEST_OUTPUT_DIR="${CMAKE_BINARY_DIR}/test-artifacts/rocksdb") - target_compile_options(felidae_rocksdb_test PRIVATE - $<$:-UNDEBUG> - $<$:/UNDEBUG>) - felidae_enable_msvc_exceptions(felidae_rocksdb_test) - add_test(NAME felidae_rocksdb COMMAND felidae_rocksdb_test) - set_tests_properties(felidae_rocksdb PROPERTIES - TIMEOUT 30 - LABELS "storage") - endif() - - # Exercise representative user programs through the public compiler and - # VM executables. Keep generated .bin files in the active build tree. - # External-service, training, and stress fixtures have separate - # prerequisites and therefore do not belong in this ordinary smoke set. - set(FELIDAE_RUNNABLE_V2_EXAMPLES - form_core_concepts - numeric_operations - array_object - json_csv_operations - csv_fact_database - fx_fact_database - group_operations - set_operations - degree_profiles - hierarchical_fact_filter - fact_expression_result_contract - where_guard_chain - optional_end_blocks - end_then_pipeline - coffee_vending_theorem_solver - air_conditioner_theorem_solver - mixfix_ir_roundtrip - operator_expression_inventory - standard_search_algorithms - deep_fact_reasoning_analysis - fact_search_analysis - selective_relationship_reasoning - class_association_reasoning) - foreach(example IN LISTS FELIDAE_RUNNABLE_V2_EXAMPLES) - add_test(NAME felidae_example_${example} - COMMAND "${CMAKE_COMMAND}" - "-DFELIDAE_COMPILER=$" - "-DFELIDAE_VM=$" - "-DFELIDAE_EXAMPLE=${CMAKE_SOURCE_DIR}/v2_examples/${example}.fx" - "-DFELIDAE_BINARY_DIR=$" - "-DFELIDAE_RUNTIME_WORKING_DIRECTORY=${CMAKE_SOURCE_DIR}" - -P "${CMAKE_SOURCE_DIR}/cmake/RunFelidaeExample.cmake") - set_tests_properties(felidae_example_${example} PROPERTIES - TIMEOUT 30 - LABELS "examples;integration") - endforeach() - set_tests_properties(felidae_example_json_csv_operations PROPERTIES - PASS_REGULAR_EXPRESSION "name: Ada") - set_tests_properties(felidae_example_array_object PROPERTIES - PASS_REGULAR_EXPRESSION "first: Ada, count: 2") - # renderNumber() only forces a trailing .0 on exactly 0.0/1.0 (the - # boolean convention); an ordinary whole number like this count prints - # without one, so the assertion must match that, not assume every number - # gets ".0". - set_tests_properties(felidae_example_csv_fact_database PROPERTIES - PASS_REGULAR_EXPRESSION "all_count: 4, active_central_count: 2.*deleted: 1.0") - set_tests_properties(felidae_example_fx_fact_database PROPERTIES - PASS_REGULAR_EXPRESSION "count: 2, students: 770") - set_tests_properties(felidae_example_group_operations PROPERTIES - PASS_REGULAR_EXPRESSION "abelian: 1.0") - set_tests_properties(felidae_example_set_operations PROPERTIES - PASS_REGULAR_EXPRESSION "contains: 1.0") - set_tests_properties(felidae_example_operator_expression_inventory PROPERTIES - PASS_REGULAR_EXPRESSION "precedence: 14, grouped: 20, unary: -7, ordered: 1.0, unequal: 1.0, eligible: 1.0, member: Ava, pipeline: 22") - set_tests_properties(felidae_example_standard_search_algorithms PROPERTIES - PASS_REGULAR_EXPRESSION "linear_last: 63, binary_last: 63, missing: \\{linear: -1, binary: -1\\}") - set_tests_properties(felidae_example_deep_fact_reasoning_analysis PROPERTIES - PASS_REGULAR_EXPRESSION "directed_cat_tiger: \\[\\], symmetric_tiger_cat: \\[\\{from:") - set_tests_properties(felidae_example_fact_search_analysis PROPERTIES - PASS_REGULAR_EXPRESSION "guides: 2, related: 2, confident: 2") - set_tests_properties(felidae_example_selective_relationship_reasoning PROPERTIES - PASS_REGULAR_EXPRESSION "connected_via_signal: 1.0\\}") - set_tests_properties(felidae_example_class_association_reasoning PROPERTIES - PASS_REGULAR_EXPRESSION "relation: works at, strength: 3.421") - set_tests_properties(felidae_example_where_guard_chain PROPERTIES - PASS_REGULAR_EXPRESSION "passes: 82, lowScore: 0.0, inactive: 0.0") - set_tests_properties(felidae_example_optional_end_blocks PROPERTIES - PASS_REGULAR_EXPRESSION "high: 2, middle: 1.0, low: 0.0") - set_tests_properties(felidae_example_end_then_pipeline PROPERTIES - PASS_REGULAR_EXPRESSION "accepted: 10, rejected: 0.0") - - # Tests are deliberately opt-in at build time. A normal IDE build should - # compile only the two production executables and their required - # dependencies; `--target felidae_tests` builds the complete test suite. - set(FELIDAE_TEST_TARGETS - felidae_sentencepiece_model_test - felidae_sentencepiece_pipeline_test - felidae_mixfix_state_model_test - felidae_form_binary_test - felidae_form_isolation_test - felidae_ir_test - felidae_db_csv_test) - if(TARGET felidae_libtorch_smoke_test) - list(APPEND FELIDAE_TEST_TARGETS felidae_libtorch_smoke_test) - endif() - if(TARGET felidae_rocksdb_test) - list(APPEND FELIDAE_TEST_TARGETS felidae_rocksdb_test) - endif() - if(TARGET felidae_execution_vectors_test) - list(APPEND FELIDAE_TEST_TARGETS felidae_execution_vectors_test) - endif() - foreach(test_target IN LISTS FELIDAE_TEST_TARGETS) - set_property(TARGET ${test_target} PROPERTY EXCLUDE_FROM_ALL TRUE) - endforeach() - add_custom_target(felidae_tests - DEPENDS ${FELIDAE_TEST_TARGETS} felidae_compiler felidae_vm felidae_debugger) -endif() - -if(EXISTS "${CMAKE_SOURCE_DIR}/third_party/Eigen/Eigen/Core") - # Eigen is header-only. Expose the pinned submodule through the canonical - # target without configuring Eigen's upstream test/probe project. - add_library(felidae_eigen INTERFACE) - target_include_directories(felidae_eigen INTERFACE - "${CMAKE_SOURCE_DIR}/third_party/Eigen") - add_library(Eigen3::Eigen ALIAS felidae_eigen) - target_compile_definitions(felidae_compiler PRIVATE FELIDAE_HAS_EIGEN=1) - target_link_libraries(felidae_compiler PRIVATE Eigen3::Eigen) -endif() - -foreach(felidae_quality_target IN ITEMS - felidae_sentencepiece_model_generator felidae_integer_parser_benchmark - felidae_extract_mixfix_dataset - felidae_form felidae_mixfix_torch felidae_compiler felidae_vm felidae_debugger - felidae_sentencepiece_model_test felidae_sentencepiece_pipeline_test - felidae_mixfix_state_model_test) - if(TARGET ${felidae_quality_target}) - felidae_enable_quality_warnings(${felidae_quality_target}) - endif() -endforeach() - -if(FELIDAE_BUILD_TESTS) - # Release gate: build the portable distribution, run the focused IR/VM - # regression suite, then execute a compiler->.bin->VM smoke through the - # staged binaries themselves. It never creates a second build tree. - add_custom_target(felidae_beta - COMMAND "${CMAKE_CTEST_COMMAND}" --test-dir "${CMAKE_BINARY_DIR}" - -R felidae_ - --output-on-failure - COMMAND "${CMAKE_COMMAND}" - "-DFELIDAE_BETA_DIST_DIR=${FELIDAE_DIST_DIR}" - "-DFELIDAE_BETA_BUILD_DIR=${CMAKE_BINARY_DIR}" - "-DFELIDAE_BETA_EXAMPLE=${CMAKE_SOURCE_DIR}/v2_examples/mixfix_deep_ir_nesting.fx" - -P "${CMAKE_SOURCE_DIR}/cmake/BetaReleaseCheck.cmake" - DEPENDS felidae_dist felidae_sentencepiece_model_test felidae_sentencepiece_pipeline_test - felidae_mixfix_state_model_test felidae_form_binary_test - felidae_form_isolation_test felidae_ir_test - COMMENT "Running Felidae beta release gate") -endif() diff --git a/src/Env.cpp b/src/Env.cpp new file mode 100644 index 0000000..01e9aa7 --- /dev/null +++ b/src/Env.cpp @@ -0,0 +1,236 @@ +#include "Env.h" +#include "Symbol.h" + +namespace Felidae { + +namespace { + +constexpr std::size_t kMaxPooledEnvBuckets = 4096; + +} + +void BindingTrail::assign(Env& env, SymbolId id, std::shared_ptr value) { + const auto found = env.values_.find(id); + entries_.push_back(Entry{ + &env, + id, + found != env.values_.end(), + found == env.values_.end() ? nullptr : found->second}); + env.values_[id] = std::move(value); +} + +void BindingTrail::rollback(Checkpoint checkpoint) { + while (entries_.size() > checkpoint) { + Entry entry = std::move(entries_.back()); + entries_.pop_back(); + if (!entry.env) continue; + if (entry.existed) entry.env->values_[entry.id] = std::move(entry.previous); + else entry.env->values_.erase(entry.id); + } +} + +Env cloneEnv(const Env& env) { + // Runtime values are immutable. A branch needs its own binding directory, + // not deep copies of every bound value graph. + return env; +} + +std::shared_ptr findEnvValue(const Env& env, const std::string& name) { + auto found = env.find(name); + if (found == env.end() || !found->second) return nullptr; + return found->second; +} + +std::shared_ptr findReturnValue(const Env& env) { + return findEnvValue(env, internalSymbolString(InternalSymbolKind::Return)); +} + +bool bindEnvValue(Env& env, const std::string& name, const std::shared_ptr& value) { + if (!value) return false; + env[name] = value; + return true; +} + +size_t GlobalEnv::count(const std::string& name) const { + return values_.count(name); +} + +size_t GlobalEnv::count(SymbolId id) const { return values_.find(id) != values_.end(); } + +GlobalEnv::iterator GlobalEnv::find(const std::string& name) { + return values_.find(name); +} + +GlobalEnv::iterator GlobalEnv::find(SymbolId id) { return values_.find(id); } + +GlobalEnv::const_iterator GlobalEnv::find(const std::string& name) const { + return values_.find(name); +} + +GlobalEnv::const_iterator GlobalEnv::find(SymbolId id) const { return values_.find(id); } + +GlobalEnv::iterator GlobalEnv::end() { + return values_.end(); +} + +GlobalEnv::const_iterator GlobalEnv::end() const { + return values_.end(); +} + +GlobalEnv::iterator GlobalEnv::begin() { + return values_.begin(); +} + +GlobalEnv::const_iterator GlobalEnv::begin() const { + return values_.begin(); +} + +std::shared_ptr& GlobalEnv::operator[](const std::string& name) { + return values_[name]; +} + +std::shared_ptr& GlobalEnv::operator[](SymbolId id) { return values_[id]; } + +void GlobalEnv::bind(const std::string& name, + const std::shared_ptr& value, + std::filesystem::path origin) { + values_[name] = value ? value->clone() : nullptr; + if (!origin.empty()) origins_[symbolIdForName(name)] = std::move(origin); +} + +void GlobalEnv::setOrigin(const std::string& name, std::filesystem::path origin) { + if (origin.empty()) return; + origins_[symbolIdForName(name)] = std::move(origin); +} + +void GlobalEnv::erase(const std::string& name) { + values_.erase(name); + origins_.erase(symbolIdForName(name)); +} + +void GlobalEnv::eraseOrigin(const std::filesystem::path& origin) { + if (origin.empty()) return; + for (auto it = origins_.begin(); it != origins_.end();) { + if (it->second == origin) { + values_.erase(it->first); + it = origins_.erase(it); + } else { + ++it; + } + } +} + +void GlobalEnv::replaceValues(Env values) { + values_ = std::move(values); + origins_.clear(); +} + +const GlobalEnv::Map& GlobalEnv::values() const { + return values_; +} + +EnvFrame::EnvFrame(EnvFramePool* pool, Env* env) : pool_(pool), env_(env) {} + +EnvFrame::EnvFrame(EnvFrame&& other) noexcept : pool_(other.pool_), env_(other.env_) { + other.pool_ = nullptr; + other.env_ = nullptr; +} + +EnvFrame& EnvFrame::operator=(EnvFrame&& other) noexcept { + if (this != &other) { + reset(); + pool_ = other.pool_; + env_ = other.env_; + other.pool_ = nullptr; + other.env_ = nullptr; + } + return *this; +} + +EnvFrame::~EnvFrame() { + reset(); +} + +Env& EnvFrame::get() { + return *env_; +} + +const Env& EnvFrame::get() const { + return *env_; +} + +Env* EnvFrame::operator->() { + return env_; +} + +Env& EnvFrame::operator*() { + return *env_; +} + +EnvFrame::operator bool() const { + return env_ != nullptr; +} + +void EnvFrame::reset() { + if (pool_ && env_) { + pool_->recycle(env_); + } + pool_ = nullptr; + env_ = nullptr; +} + +EnvFrame EnvFramePool::acquire() { + if (free_.empty()) { + ++created_; + return EnvFrame(this, new Env()); + } + std::unique_ptr env = std::move(free_.back()); + free_.pop_back(); + return EnvFrame(this, env.release()); +} + +EnvFrame EnvFramePool::acquireCopy(const Env& source) { + ++copies_; + EnvFrame frame = acquire(); + Env& env = frame.get(); + env.clear(); + env.reserve(source.size()); + env.insert(source.begin(), source.end()); + return frame; +} + +EnvFrame EnvFramePool::acquireMove(Env&& source) { + EnvFrame frame = acquire(); + frame.get() = std::move(source); + return frame; +} + +void EnvFramePool::recycle(Env* env) { + if (!env) return; + env->clear(); + if (env->bucket_count() > kMaxPooledEnvBuckets) { + delete env; + return; + } + free_.push_back(std::unique_ptr(env)); +} + +void EnvFramePool::collectGarbage(std::size_t maxCachedFrames) { + while (free_.size() > maxCachedFrames) { + free_.pop_back(); + } +} + +std::size_t EnvFramePool::created() const { + return created_; +} + +std::size_t EnvFramePool::cached() const { + return free_.size(); +} + +std::size_t EnvFramePool::copies() const { + return copies_; +} + +} // namespace Felidae diff --git a/src/Env.h b/src/Env.h new file mode 100644 index 0000000..8fa9c21 --- /dev/null +++ b/src/Env.h @@ -0,0 +1,174 @@ +#pragma once + +#include "AST.h" +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +// Runtime bindings are keyed by collision-free SymbolId rather than repeated +// heap strings. Source spellings stay on AST nodes; binding lookup converts a +// spelling once through the shared symbol interner. +class Env { +public: + using Map = std::unordered_map>; + using key_type = Map::key_type; + using mapped_type = Map::mapped_type; + using value_type = Map::value_type; + using iterator = Map::iterator; + using const_iterator = Map::const_iterator; + + Env() = default; + Env(const Env&) = default; + Env(Env&&) noexcept = default; + Env& operator=(const Env&) = default; + Env& operator=(Env&&) noexcept = default; + + std::size_t count(const std::string& name) const { + return values_.count(symbolIdForName(name)); + } + iterator find(const std::string& name) { + return values_.find(symbolIdForName(name)); + } + const_iterator find(const std::string& name) const { + return values_.find(symbolIdForName(name)); + } + iterator find(SymbolId id) { return values_.find(id); } + const_iterator find(SymbolId id) const { return values_.find(id); } + iterator begin() { return values_.begin(); } + const_iterator begin() const { return values_.begin(); } + iterator end() { return values_.end(); } + const_iterator end() const { return values_.end(); } + std::shared_ptr& operator[](const std::string& name) { + return values_[symbolIdForName(name)]; + } + std::shared_ptr& operator[](SymbolId id) { + return values_[id]; + } + std::size_t erase(const std::string& name) { + return values_.erase(symbolIdForName(name)); + } + std::size_t erase(SymbolId id) { + return values_.erase(id); + } + void clear() { values_.clear(); } + void reserve(std::size_t size) { values_.reserve(size); } + template + void insert(Iterator begin, Iterator end) { + values_.insert(begin, end); + } + std::size_t size() const { return values_.size(); } + std::size_t bucket_count() const { return values_.bucket_count(); } + +private: + friend class BindingTrail; + Map values_; +}; + +// Reversible bindings for recursive search. Values remain shared and +// immutable; only changed symbol slots are recorded. +class BindingTrail { +public: + using Checkpoint = std::size_t; + + Checkpoint checkpoint() const { return entries_.size(); } + void assign(Env& env, SymbolId id, std::shared_ptr value); + void rollback(Checkpoint checkpoint); + +private: + struct Entry { + Env* env = nullptr; + SymbolId id = 0; + bool existed = false; + std::shared_ptr previous; + }; + std::vector entries_; +}; + +class GlobalEnv { +public: + using Map = Env; + using iterator = Map::iterator; + using const_iterator = Map::const_iterator; + + size_t count(const std::string& name) const; + size_t count(SymbolId id) const; + iterator find(const std::string& name); + iterator find(SymbolId id); + const_iterator find(const std::string& name) const; + const_iterator find(SymbolId id) const; + iterator end(); + const_iterator end() const; + iterator begin(); + const_iterator begin() const; + std::shared_ptr& operator[](const std::string& name); + std::shared_ptr& operator[](SymbolId id); + void bind(const std::string& name, + const std::shared_ptr& value, + std::filesystem::path origin = {}); + void setOrigin(const std::string& name, std::filesystem::path origin); + void erase(const std::string& name); + void eraseOrigin(const std::filesystem::path& origin); + void replaceValues(Env values); + const Map& values() const; + +private: + Map values_; + std::unordered_map origins_; +}; + +struct Solution { + Env env; +}; + +Env cloneEnv(const Env& env); +std::shared_ptr findEnvValue(const Env& env, const std::string& name); +std::shared_ptr findReturnValue(const Env& env); +bool bindEnvValue(Env& env, const std::string& name, const std::shared_ptr& value); + +class EnvFramePool; + +class EnvFrame { +public: + EnvFrame() = default; + EnvFrame(EnvFramePool* pool, Env* env); + EnvFrame(const EnvFrame&) = delete; + EnvFrame& operator=(const EnvFrame&) = delete; + EnvFrame(EnvFrame&& other) noexcept; + EnvFrame& operator=(EnvFrame&& other) noexcept; + ~EnvFrame(); + + Env& get(); + const Env& get() const; + Env* operator->(); + Env& operator*(); + explicit operator bool() const; + void reset(); + +private: + EnvFramePool* pool_ = nullptr; + Env* env_ = nullptr; +}; + +class EnvFramePool { +public: + EnvFrame acquire(); + EnvFrame acquireCopy(const Env& source); + EnvFrame acquireMove(Env&& source); + void recycle(Env* env); + void collectGarbage(std::size_t maxCachedFrames); + std::size_t created() const; + std::size_t cached() const; + std::size_t copies() const; + +private: + std::vector> free_; + std::size_t created_ = 0; + std::size_t copies_ = 0; +}; + +} // namespace Felidae diff --git a/src/FelidaeRuntime.cpp b/src/FelidaeRuntime.cpp new file mode 100644 index 0000000..15a0e78 --- /dev/null +++ b/src/FelidaeRuntime.cpp @@ -0,0 +1,331 @@ +#include "FelidaeRuntime.h" + +#include "IntegerParser.h" +#include "SentencePieceModel.h" +#include "Symbol.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace Felidae { + +namespace { + +constexpr std::uintmax_t kStreamingReadThresholdBytes = 10ull * 1024ull * 1024ull; +constexpr std::size_t kReadChunkBytes = 1024ull * 1024ull; +} // namespace + +std::string readSourceFile(const fs::path& path) { + std::ifstream in(path, std::ios::binary); + if (!in) throw std::runtime_error("Cannot open file: " + path.string()); + + std::error_code ec; + const auto size = fs::file_size(path, ec); + if (!ec && size <= kStreamingReadThresholdBytes) { + std::string text; + text.resize(static_cast(size)); + if (!text.empty()) { + in.read(&text[0], static_cast(text.size())); + if (!in && !in.eof()) throw std::runtime_error("Cannot read file: " + path.string()); + } + return text; + } + + std::string text; + if (!ec) text.reserve(static_cast(std::min(size, kStreamingReadThresholdBytes))); + std::vector buffer(kReadChunkBytes); + while (in) { + in.read(buffer.data(), static_cast(buffer.size())); + const auto read = in.gcount(); + if (read > 0) text.append(buffer.data(), static_cast(read)); + } + if (!in.eof()) throw std::runtime_error("Cannot read file: " + path.string()); + return text; +} + +void readSourceLines(const fs::path& path, const std::function& onLine) { + std::ifstream in(path, std::ios::binary); + if (!in) throw std::runtime_error("Cannot open file: " + path.string()); + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + onLine(line); + } + if (!in.eof()) throw std::runtime_error("Cannot read file: " + path.string()); +} + +std::filesystem::path resolveProgramEntryPath(const fs::path& path) { + fs::path normalized = fs::absolute(path).lexically_normal(); + std::error_code ec; + if (fs::is_directory(normalized, ec)) { + fs::path mainFile = normalized / "main.fx"; + if (fs::exists(mainFile, ec) && fs::is_regular_file(mainFile, ec)) { + return mainFile.lexically_normal(); + } + throw std::runtime_error("Project directory does not contain main.fx: " + normalized.string()); + } + return normalized; +} + +Program parseProgramFile(const fs::path& path) { + std::error_code ec; + const auto normalized = resolveProgramEntryPath(path); + return parseProgramText(readSourceFile(normalized)); +} + +Program parseProgramText(std::string text) { + IntegerTokenList input(felidaeSentencePieceModel(), std::move(text)); + return IntegerParser(input).parseProgram(); +} + +void parseProgramFileStatements( + const fs::path& path, + const std::function)>& consume, + std::shared_ptr operators, + ParserMetrics* metrics) { + const fs::path normalized = resolveProgramEntryPath(path); + IntegerTokenList input(felidaeSentencePieceModel(), readSourceFile(normalized)); + IntegerParser parser(input, std::move(operators)); + Program program = parser.parseProgram(); + for (auto& statement : program.statements) consume(std::move(statement)); + if (metrics) { + metrics->tokensLexed += input.entries().size(); + metrics->iterations += parser.metrics().iterations; + metrics->peakRecursionDepth = std::max(metrics->peakRecursionDepth, + parser.metrics().peakRecursionDepth); + metrics->backtrackingAttempts += parser.metrics().backtrackingAttempts; + } +} + +void parseProgramFileChunks(const fs::path& path, + const std::function& consume, + std::size_t statementsPerChunk) { + if (statementsPerChunk == 0) statementsPerChunk = 1; + Program chunk; + parseProgramFileStatements(path, [&](std::shared_ptr statement) { + chunk.addStatement(std::move(statement)); + if (chunk.statements.size() >= statementsPerChunk) { + consume(std::move(chunk)); + chunk = Program{}; + } + }); + if (!chunk.statements.empty()) consume(std::move(chunk)); +} + +void loadProgramRoot(const fs::path& file, Interpreter& interpreter) { + loadProgramRoot(file, interpreter, {}); +} + +void loadProgramRoot(const fs::path& file, + Interpreter& interpreter, + const std::function& afterChunk) { + fs::path normalized = resolveProgramEntryPath(file); + fs::path baseDir = normalized.parent_path(); + const auto streamStarted = std::chrono::steady_clock::now(); + ParserMetrics parserMetrics; + interpreter.beginModuleTransaction(); + try { + if (afterChunk) { + parseProgramFileChunks(normalized, [&](Program&& program) { + for (const auto& imp : program.imports) { + for (const auto& path : imp->paths) interpreter.addImport(baseDir, path); + } + interpreter.addProgram(program); + afterChunk(program); + }); + } else { + parseProgramFileStatements(normalized, [&](std::shared_ptr statement) { + if (statement->kind() == StatementKind::Import) { + const auto import = std::static_pointer_cast(statement); + for (const auto& path : import->paths) interpreter.addImport(baseDir, path); + return; + } + interpreter.addStreamedStatement(std::move(statement)); + }, interpreter.operatorRegistry(), &parserMetrics); + } + interpreter.commitModuleTransaction(); + interpreter.recordStreamedModuleMicros(static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now() - streamStarted).count())); + interpreter.recordParserMetrics(parserMetrics); + } catch (...) { + interpreter.rollbackModuleTransaction(); + throw; + } +} + +void loadProgramRoot(const fs::path& file, + const Program& program, + Interpreter& interpreter) { + fs::path normalized = fs::absolute(file).lexically_normal(); + fs::path baseDir = normalized.parent_path(); + + interpreter.beginModuleTransaction(); + try { + for (const auto& imp : program.imports) { + for (const auto& path : imp->paths) { + interpreter.addImport(baseDir, path); + } + } + interpreter.addProgram(program); + interpreter.commitModuleTransaction(); + } catch (...) { + interpreter.rollbackModuleTransaction(); + throw; + } +} + +std::vector listCoreLibraries(const fs::path& startDir) { + std::vector names; + std::error_code ec; + fs::path current = fs::absolute(startDir, ec).lexically_normal(); + if (ec) return names; + + fs::path coreDir; + while (true) { + fs::path candidate = current / "core"; + if (fs::exists(candidate, ec) && fs::is_directory(candidate, ec)) { + coreDir = candidate; + break; + } + fs::path parent = current.parent_path(); + if (parent == current) break; + current = parent; + } + if (coreDir.empty()) return names; + + for (const auto& entry : fs::directory_iterator(coreDir, ec)) { + if (ec) break; + if (!entry.is_regular_file()) continue; + if (entry.path().extension() != ".fx") continue; + names.push_back(entry.path().stem().string()); + } + std::sort(names.begin(), names.end()); + return names; +} + +std::vector> parseQueryText(const std::string& query) { + IntegerTokenList input(felidaeSentencePieceModel(), query); + return IntegerParser(input).parseQuery(); +} + +static void collectVarsExpr(const std::shared_ptr& expr, std::vector& vars) { + if (auto v = std::dynamic_pointer_cast(expr)) { + if (v->nameId != InternalSymbol::SystemResultId && + !isInternalGeneratedSymbolId(v->nameId) && + std::find(vars.begin(), vars.end(), v->nameId) == vars.end()) { + vars.push_back(v->nameId); + } + } else if (auto term = std::dynamic_pointer_cast(expr)) { + for (const auto& arg : term->args) collectVarsExpr(arg.value, vars); + } else if (auto lambda = std::dynamic_pointer_cast(expr)) { + collectVarsExpr(lambda->source, vars); + collectVarsExpr(lambda->body, vars); + if (lambda->right) collectVarsExpr(lambda->right, vars); + } else if (auto array = std::dynamic_pointer_cast(expr)) { + for (const auto& item : array->items) collectVarsExpr(item, vars); + } else if (auto map = std::dynamic_pointer_cast(expr)) { + for (const auto& entry : map->entries) collectVarsExpr(entry.value, vars); + } else if (auto access = std::dynamic_pointer_cast(expr)) { + auto targetVar = std::dynamic_pointer_cast(access->target); + if (access->keyId == InternalSymbol::ResultId && targetVar && targetVar->nameId == InternalSymbol::SystemId) return; + collectVarsExpr(access->target, vars); + } else if (auto op = std::dynamic_pointer_cast(expr)) { + for (size_t i = 0; i < op->captureCount(); ++i) collectVarsExpr(op->capture(i), vars); + } +} + +static void collectVarsGoal(const std::shared_ptr& goal, std::vector& vars) { + if (auto cg = std::dynamic_pointer_cast(goal)) { + for (const auto& arg : cg->call.args) collectVarsExpr(arg.value, vars); + } else if (auto ag = std::dynamic_pointer_cast(goal)) { + if (std::find(vars.begin(), vars.end(), ag->nameId) == vars.end()) { + vars.push_back(ag->nameId); + } + if (ag->expr) collectVarsExpr(ag->expr, vars); + } else if (auto bg = std::dynamic_pointer_cast(goal)) { + collectVarsExpr(bg->left, vars); + collectVarsExpr(bg->right, vars); + } else if (auto wg = std::dynamic_pointer_cast(goal)) { + collectVarsGoal(wg->condition, vars); + } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { + collectVarsGoal(ifGoal->condition, vars); + for (const auto& branchGoal : ifGoal->thenBranch) collectVarsGoal(branchGoal, vars); + for (const auto& branchGoal : ifGoal->elseBranch) collectVarsGoal(branchGoal, vars); + } else if (auto rg = std::dynamic_pointer_cast(goal)) { + for (const auto& field : rg->fields) collectVarsExpr(field.value, vars); + } else if (auto gg = std::dynamic_pointer_cast(goal)) { + for (const auto& groupedGoal : gg->goals) collectVarsGoal(groupedGoal, vars); + } else if (auto og = std::dynamic_pointer_cast(goal)) { + for (const auto& branch : og->branches) { + for (const auto& branchGoal : branch) collectVarsGoal(branchGoal, vars); + } + } +} + +static std::vector collectQueryVars(const std::vector>& goals) { + std::vector vars; + for (const auto& g : goals) collectVarsGoal(g, vars); + return vars; +} + +void printSolutions(Interpreter& interpreter, + const std::vector>& queryGoals, + const std::vector& solutions, + std::ostream& out) { + auto queryVars = collectQueryVars(queryGoals); + if (solutions.empty()) { + out << "false\n"; + return; + } + if (queryVars.empty()) { + out << "true\n"; + return; + } + for (size_t i = 0; i < solutions.size(); ++i) { + out << "Solution " << (i + 1) << ": "; + for (size_t j = 0; j < queryVars.size(); ++j) { + if (j) out << ", "; + const auto name = symbolNameForId(queryVars[j]); + auto varExpr = std::make_shared(name, queryVars[j]); + out << name << " = " << interpreter.exprToString(varExpr, solutions[i].env); + } + out << "\n"; + } +} + +std::shared_ptr makeSystemInput(const std::vector& args) { + std::vector> argValues; + argValues.reserve(args.size()); + for (const auto& arg : args) argValues.push_back(std::make_shared(arg)); + return std::make_shared(std::vector{ + MapEntry{"args", std::make_shared(std::move(argValues))}, + MapEntry{"text", std::make_shared("")} + }); +} + +std::string trim(const std::string& text) { + size_t start = 0; + while (start < text.size() && std::isspace(static_cast(text[start]))) start++; + size_t end = text.size(); + while (end > start && std::isspace(static_cast(text[end - 1]))) end--; + return text.substr(start, end - start); +} + +bool isBareIdentifier(const std::string& text) { + if (text.empty() || !(std::isalpha(static_cast(text[0])) || text[0] == '_')) return false; + for (char ch : text) { + if (!(std::isalnum(static_cast(ch)) || ch == '_')) return false; + } + return true; +} + +} // namespace Felidae diff --git a/src/FelidaeRuntime.h b/src/FelidaeRuntime.h new file mode 100644 index 0000000..1fc3fc3 --- /dev/null +++ b/src/FelidaeRuntime.h @@ -0,0 +1,53 @@ +#pragma once + +#include "AST.h" +#include "Interpreter.h" +#include "ParserMetrics.h" + +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +Program parseProgramFile(const std::filesystem::path& path); +Program parseProgramText(std::string text); +void parseProgramFileChunks( + const std::filesystem::path& path, + const std::function& consume, + std::size_t statementsPerChunk = 1); +void parseProgramFileStatements( + const std::filesystem::path& path, + const std::function)>& consume, + std::shared_ptr operators = {}, + ParserMetrics* metrics = nullptr); +std::string readSourceFile(const std::filesystem::path& path); +void readSourceLines(const std::filesystem::path& path, + const std::function& onLine); +std::filesystem::path resolveProgramEntryPath(const std::filesystem::path& path); +void loadProgramRoot(const std::filesystem::path& file, Interpreter& interpreter); +void loadProgramRoot( + const std::filesystem::path& file, + Interpreter& interpreter, + const std::function& afterChunk); +void loadProgramRoot(const std::filesystem::path& file, + const Program& program, + Interpreter& interpreter); +std::vector> parseQueryText(const std::string& query); +void printSolutions(Interpreter& interpreter, + const std::vector>& queryGoals, + const std::vector& solutions, + std::ostream& out); +std::shared_ptr makeSystemInput(const std::vector& args); +std::string trim(const std::string& text); +bool isBareIdentifier(const std::string& text); + +// Bare-import library names resolvable from `startDir` (the directory a +// program is loaded from), i.e. the set of valid `import "name"` values that +// resolve to a declaration file under `core/`. +std::vector listCoreLibraries(const std::filesystem::path& startDir); + +} // namespace Felidae diff --git a/src/Interpreter.cpp b/src/Interpreter.cpp new file mode 100644 index 0000000..2cc7fb0 --- /dev/null +++ b/src/Interpreter.cpp @@ -0,0 +1,2745 @@ +Warning: truncated output (original token count: 109819) +Total output lines: 9128 + +#include "Interpreter.h" +#include "BuiltinRegistry.h" +#include "IntegerParser.h" +#include "SentencePieceModel.h" +#include "FelidaeRuntime.h" +#include "OperatorAnnotation.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef FELIDAE_HAS_EIGEN +#include +#endif + +namespace Felidae { +namespace fs = std::filesystem; + +namespace { + +constexpr size_t kMaxCachedEnvFrames = 4096; +constexpr size_t kHotMethodPrepareThreshold = 2; +// A non-tail call expands through solver, value evaluation, and unification +// frames. Keep this deliberately below the platform stack danger zone until +// Tail calls unwind through TailCallSignal. Non-tail calls still use the +// native stack until the method-aware frame engine lands, so this deliberately +// conservative bound turns excessive recursion into a Felidae error first. +// Relational recursion is scheduled on solveIterative's work stack. Methods +// still have a small native continuation boundary, so keep a conservative +// hard ceiling rather than allowing user recursion to consume the process +// stack. This is intentionally independent from the iterative goal limit. +constexpr size_t kMaxNativeMethodCallDepth = 8; +constexpr size_t kMaxNativeGoalFrameDepth = 256; + +class CounterScope { +public: + explicit CounterScope(size_t& counter) : counter_(counter) { ++counter_; } + ~CounterScope() { --counter_; } +private: + size_t& counter_; +}; + +class PipelineResultClearScope { +public: + explicit PipelineResultClearScope(std::vector>& results) + : results_(results), saved_(std::move(results)) { + results_.clear(); + } + + ~PipelineResultClearScope() { + results_ = std::move(saved_); + } + +private: + std::vector>& results_; + std::vector> saved_; +}; + +class TailCallSignal { +public: + TailCallSignal(TermExpr next, Env environment) + : term(std::move(next)), env(std::move(environment)) {} + TermExpr term; + Env env; +}; + +class PipelineResultValueScope { +public: + PipelineResultValueScope(std::vector>& results, + const std::shared_ptr& value) + : results_(results) { + results_.push_back(value->clone()); + } + + ~PipelineResultValueScope() { + results_.pop_back(); + } + +private: + std::vector>& results_; +}; + +} + +static std::string jsonEscape(const std::string& value) { + std::ostringstream out; + for (char c : value) { + switch (c) { + case '\\': out << "\\\\"; break; + case '"': out << "\\\""; break; + case '\n': out << "\\n"; break; + case '\r': out << "\\r"; break; + case '\t': out << "\\t"; break; + default: + if (static_cast(c) < 0x20) { + out << "\\u"; + out << std::hex << std::uppercase << std::setw(4) << std::setfill('0') + << static_cast(static_cast(c)); + out << std::dec << std::nouppercase; + } else { + out << c; + } + } + } + return out.str(); +} + +static bool argAsNumber(const std::shared_ptr& expr, double& out) { + if (auto n = std::dynamic_pointer_cast(expr)) { + out = n->value; + return true; + } + return false; +} + +static bool argAsString(const std::shared_ptr& expr, std::string& out) { + if (auto s = std::dynamic_pointer_cast(expr)) { + out = s->value; + return true; + } + return false; +} + +static std::vector> termArgs(const std::shared_ptr& expr, + BuiltinId id) { + if (auto t = std::dynamic_pointer_cast(expr)) { + if (t->builtinId == id) { + std::vector> out; + for (const auto& arg : t->args) out.push_back(arg.value); + return out; + } + } + if (id == BuiltinId::FnArray) { + if (auto a = std::dynamic_pointer_cast(expr)) return a->items; + } + return {}; +} + +static std::shared_ptr findMapValue(const std::shared_ptr& expr, + const std::string& key) { + if (const auto ast = std::dynamic_pointer_cast(expr)) { + if (key == "text") { + return std::make_shared(ast->sourceText()); + } + if (key == "nodeKind") { + return std::make_shared(ast->nodeKind); + } + return {}; + } + if (auto selection = std::dynamic_pointer_cast(expr)) { + if (key == internalSymbolName(InternalSymbolKind::Type)) { + return std::make_shared("FactSelection"); + } + if (key == "fact_type") { + return std::make_shared(selection->factType); + } + if (key == "source") return std::make_shared("memory"); + if (key == "snapshot_generation") { + return std::make_shared( + static_cast(selection->snapshotGeneration)); + } + if (key == "field" && !selection->field.empty()) { + return std::make_shared(selection->field); + } + if (key == "equals") return selection->equals; + if (key == "designation" && selection->designations.size() == 1) { + return std::make_shared(selection->designations.front()); + } + return {}; + } + const SymbolId keyId = symbolIdForName(key); + if (auto m = std::dynamic_pointer_cast(expr)) { + for (const auto& entry : m->entries) { + if (entry.keyId == keyId) return entry.value; + } + } + if (auto t = std::dynamic_pointer_cast(expr)) { + if (t->builtinId == BuiltinId::JsonObject) { + for (const auto& field : t->args) { + auto pair = termArgs(field.value, BuiltinId::FnPair); + std::string fieldName; + if (pair.size() == 2 && argAsString(pair[0], fieldName) && + symbolIdForName(fieldName) == keyId) { + return pair[1]; + } + } + } + } + return {}; +} + +static std::string publicValueString(const std::shared_ptr& value) { + if (!value) return "nil"; + if (const auto array = std::dynamic_pointer_cast(value)) { + std::ostringstream out; + out << "["; + for (size_t index = 0; index < array->items.size(); ++index) { + if (index) out << ", "; + out << publicValueString(array->items[index]); + } + out << "]"; + return out.str(); + } + if (const auto map = std::dynamic_pointer_cast(value)) { + const bool fact = !map->factType.empty(); + std::ostringstream out; + out << (fact ? map->factType + "(" : "{"); + bool first = true; + for (const auto& entry : map->entries) { + if (fact && (entry.keyId == InternalSymbol::TypeId || + entry.keyId == InternalSymbol::ParentId)) { + continue; + } + if (!first) out << ", "; + first = false; + out << entry.key << ": " << publicValueString(entry.value); + } + out << (fact ? ")" : "}"); + return out.str(); + } + if (const auto term = std::dynamic_pointer_cast(value)) { + std::ostringstream out; + out << term->name << "("; + for (size_t index = 0; index < term->args.size(); ++index) { + if (index) out << ", "; + if (!term->args[index].name.empty()) out << term->args[index].name << ": "; + out << publicValueString(term->args[index].value); + } + out << ")"; + return out.str(); + } + return value->debug(); +} + +static bool isStructuredPublicValue(const std::shared_ptr& value) { + return std::dynamic_pointer_cast(value) || + std::dynamic_pointer_cast(value); +} + +static std::string publicDisplayString(const std::shared_ptr& value, size_t indent = 0) { + if (!value) return "nil"; + const std::string compact = publicValueString(value); + const bool structured = isStructuredPublicValue(value); + if (!structured || compact.size() + indent <= 96) return compact; + + const std::string padding(indent, ' '); + const std::string childPadding(indent + 2, ' '); + if (const auto array = std::dynamic_pointer_cast(value)) { + std::ostringstream out; + out << "[\n"; + for (size_t index = 0; index < array->items.size(); ++index) { + out << childPadding << publicDisplayString(array->items[index], indent + 2); + if (index + 1 < array->items.size()) out << ","; + out << "\n"; + } + out << padding << "]"; + return out.str(); + } + + const auto map = std::dynamic_pointer_cast(value); + const bool fact = !map->factType.empty(); + std::vector entries; + entries.reserve(map->entries.size()); + for (const auto& entry : map->entries) { + if (fact && (entry.keyId == InternalSymbol::TypeId || + entry.keyId == InternalSymbol::ParentId)) { + continue; + } + entries.push_back(&entry); + } + std::ostringstream out; + out << (fact ? map->factType + "(\n" : "{\n"); + for (size_t index = 0; index < entries.size(); ++index) { + out << childPadding << entries[index]->key << ": " + << publicDisplayString(entries[index]->value, indent + 2); + if (index + 1 < entries.size()) out << ","; + out << "\n"; + } + out << padding << (fact ? ")" : "}"); + return out.str(); +} +static std::vector cloneEntries(const std::vector& entries) { + std::vector copied; + copied.reserve(entries.size()); + for (const auto& entry : entries) copied.push_back(MapEntry{entry.key, entry.value->clone()}); + return copied; +} + +static std::shared_ptr cloneExprOrNil(const std::shared_ptr& value) { + if (value) return value->clone(); + return std::make_shared(); +} + +static bool exprAsMapEntries(const std::shared_ptr& expr, std::vector& out) { + if (auto map = std::dynamic_pointer_cast(expr)) { + out = cloneEntries(map->entries); + return true; + } + if (auto term = std::dynamic_pointer_cast(expr)) { + if (term->builtinId == BuiltinId::JsonObject) { + out.clear(); + for (const auto& field : term->args) { + auto pair = termArgs(field.value, BuiltinId::FnPair); + std::string key; + if (pair.size() != 2 || !argAsString(pair[0], key)) return false; + out.push_back(MapEntry{key, pair[1]->clone()}); + } + return true; + } + } + return false; +} + +static bool exprAsArrayItems(const std::shared_ptr& expr, std::vector>& out) { + if (auto array = std::dynamic_pointer_cast(expr)) { + out.clear(); + out.reserve(array->items.size()); + for (const auto& item : array->items) out.push_back(cloneExprOrNil(item)); + return true; + } + if (auto term = std::dynamic_pointer_cast(expr)) { + if (term->builtinId == BuiltinId::FnArray) { + out.clear(); + for (const auto& arg : term->args) { + if (arg.nameId == symbolIdForName("data")) { + auto data = std::dynamic_pointer_cast(arg.value); + if (!data) return false; + for (const auto& item : data->items) out.push_back(cloneExprOrNil(item)); + return true; + } + out.push_back(cloneExprOrNil(arg.value)); + } + return true; + } + } + return false; +} + +static double requireNumber(const std::shared_ptr& expr, const std::string& fn, const std::string& arg); + +static std::vector requireNumberArray(const std::shared_ptr& expr, const std::string& fn, const std::string& arg) { + std::vector> items; + if (!exprAsArrayItems(expr, items)) throw InterpreterError(fn + " expects numeric array argument '" + arg + "'"); + std::vector numbers; + numbers.reserve(items.size()); + for (const auto& item : items) numbers.push_back(requireNumber(item, fn, arg)); + return numbers; +} + +static std::shared_ptr numbersToArray(const std::vector& values) { + std::vector> items; + items.reserve(values.size()); + for (double value : values) items.push_back(std::make_shared(value)); + return std::make_shared(std::move(items)); +} + +static double factorialTerm(double n, const std::string& fn, const std::string& arg) { + if (n < 0 || std::floor(n) != n) throw InterpreterError(fn + " expects non-negative integer argument '" + arg + "'"); + return n; +} + +static void upsertEntry(std::vector& entries, const std::string& key, std::shared_ptr value) { + const SymbolId keyId = symbolIdForName(key); + for (auto& entry : entries) { + if (entry.keyId == keyId) { + entry.value = std::move(value); + return; + } + } + entries.push_back(MapEntry{key, std::move(value)}); +} + +static bool removeEntry(std::vector& entries, const std::string& key) { + auto oldSize = entries.size(); + const SymbolId keyId = symbolIdForName(key); + entries.erase(std::remove_if(entries.begin(), entries.end(), + [&](const MapEntry& entry) { return entry.keyId == keyId; }), entries.end()); + return entries.size() != oldSize; +} + +static std::string exprTextValue(const std::shared_ptr& expr) { + if (auto str = std::dynamic_pointer_cast(expr)) return str->value; + return expr ? expr->debug() : "nil"; +} + +static bool exprEqualsLiteral(const std::shared_ptr& a, const std::shared_ptr& b) { + if (auto sa = std::dynamic_pointer_cast(a)) { + auto sb = std::dynamic_pointer_cast(b); + return sb && sa->value == sb->value; + } + if (auto ba = std::dynamic_pointer_cast(a)) { + auto bb = std::dynamic_pointer_cast(b); + return bb && ba->value == bb->value; + } + if (auto na = std::dynamic_pointer_cast(a)) { + auto nb = std::dynamic_pointer_cast(b); + return nb && std::fabs(na->value - nb->value) < 1e-12; + } + if (std::dynamic_pointer_cast(a) || std::dynamic_pointer_cast(b)) { + return static_cast(std::dynamic_pointer_cast(a)) && + static_cast(std::dynamic_pointer_cast(b)); + } + return a->debug() == b->debug(); +} + +static bool exprContainsLiteral(const std::shared_ptr& haystack, const std::shared_ptr& needle) { + if (exprEqualsLiteral(haystack, needle)) return true; + std::vector> items; + if (!exprAsArrayItems(haystack, items)) return false; + for (const auto& item : items) { + if (exprEqualsLiteral(item, needle)) return true; + } + return false; +} + +static bool isMethodTruthTupleWithFalse(const std::shared_ptr& expr) { + auto tuple = std::dynamic_pointer_cast(expr); + if (!tuple || tuple->builtinId != BuiltinId::FnTuple || tuple->args.empty()) return false; + for (const auto& arg : tuple->args) { + const auto value = std::dynamic_pointer_cast(arg.value); + if (!value) return false; + if (!value->value) return true; + } + return false; +} + +static std::string lowerText(std::string text) { + for (char& ch : text) ch = static_cast(std::tolower(static_cast(ch))); + return text; +} + +static std::string upperText(std::string text) { + for (char& ch : text) ch = static_cast(std::toupper(static_cast(ch))); + return text; +} + +static const Arg* findTermArgByNameOrIndex(const TermExpr& term, const std::string& name, size_t index) { + const SymbolId nameId = name.empty() ? 0 : symbolIdForName(name); + for (const auto& arg : term.args) { + if (arg.nameId == nameId) return &arg; + } + if (index < term.args.size()) return &term.args[index]; + return nullptr; +} + +static bool exprAsArray(const std::shared_ptr& expr, std::vector>& out) { + if (auto array = std::dynamic_pointer_cast(expr)) { + out = array->items; + return true; + } + if (auto term = std::dynamic_pointer_cast(expr)) { + if (term->builtinId == BuiltinId::FnArray) { + out.clear(); + for (const auto& arg : term->args) { + if (arg.nameId == symbolIdForName("data")) { + auto data = std::dynamic_pointer_cast(arg.value); + if (!data) return false; + out = data->items; + return true; + } + } + } + } + return false; +} + +static std::string astNodeKind(const std::shared_ptr& node) { + if (std::dynamic_pointer_cast(node)) return "func_call"; + if (auto op = std::dynamic_pointer_cast(node)) { + if (isComparisonOperator(op->coreOperator) || + op->coreOperator == CoreOperator::LogicalAnd || + op->coreOperator == CoreOperator::LogicalOr || + op->coreOperator == CoreOperator::LogicalNot) return "logical"; + if (op->coreOperator == CoreOperator::Add || + op->coreOperator == CoreOperator::Subtract || + op->coreOperator == CoreOperator::Multiply || + op->coreOperator == CoreOperator::Divide || + op->coreOperator == CoreOperator::Modulo || + op->coreOperator == CoreOperator::UnaryPlus || + op->coreOperator == CoreOperator::UnaryMinus) return "arithmetic"; + return "expr"; + } + if (std::dynamic_pointer_cast(node)) return "lambda"; + if (std::dynamic_pointer_cast(node)) return "member_access"; + if (std::dynamic_pointer_cast(node)) return "map"; + if (std::dynamic_pointer_cast(node)) return "array"; + if (std::dynamic_pointer_cast(node)) return "string_literal"; + if (std::dynamic_pointer_cast(node)) return "number_literal"; + if (std::dynamic_pointer_cast(node)) return "bool_literal"; + if (std::dynamic_pointer_cast(node)) return "nil_literal"; + if (std::dynamic_pointer_cast(node)) return "variable"; + if (auto clause = std::dynamic_pointer_cast(node)) { + if (clause->clauseKind == ClauseKind::Fact) return "fact"; + if (clause->clauseKind == ClauseKind::NativeDeclaration) return "native"; + if (clause->clauseKind == ClauseKind::EntryCall) return "entry"; + return "func"; + } + if (std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node) || + std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node)) return "stmt"; + if (std::dynamic_pointer_cast(node)) return "stmts"; + if (std::dynamic_pointer_cast(node)) return "stmts"; + return "expr"; +} + +static bool valueMatchesBuiltinType(const std::shared_ptr& value, + LanguageTypeId type) { + switch (type) { + case LanguageTypeId::Any: + return true; + case LanguageTypeId::Fact: { + const auto fact = std::dynamic_pointer_cast(value); + return fact && !fact->factType.empty(); + } + case LanguageTypeId::Number: + case LanguageTypeId::Decimal: + case LanguageTypeId::Double: + case LanguageTypeId::Float: + return static_cast(std::dynamic_pointer_cast(value)); + case LanguageTypeId::Int: { + const auto number = std::dynamic_pointer_cast(value); + return number && + std::fabs(number->value - std::round(number->value)) < 1e-12; + } + case LanguageTypeId::String: + return static_cast(std::dynamic_pointer_cast(value)); + case LanguageTypeId::Array: { + std::vector> items; + return exprAsArray(value, items); + } + case LanguageTypeId::Expr: + case LanguageTypeId::Stmt: + case LanguageTypeId::Statements: { + const auto ast = std::dynamic_pointer_cast(value); + if (!ast) return false; + if (type == LanguageTypeId::Expr) { + return ast->valueKind == AstValueKind::Expression; + } + if (type == LanguageTypeId::Stmt) { + return ast->valueKind == AstValueKind::Statement; + } + return ast->valueKind == AstValueKind::Statements; + } + // mixfix is matched from retained OperatorExpression metadata during + // overload selection; it is not a runtime value category. + case LanguageTypeId::Mixfix: + return false; + case LanguageTypeId::Bool: + case LanguageTypeId::Boolean: + return static_cast(std::dynamic_pointer_cast(value)); + case LanguageTypeId::Unknown: + return false; + } + return false; +} + +static bool valueMatchesBuiltinType(const std::shared_ptr& value, + const std::string& type) { + return valueMatchesBuiltinType(value, languageTypeIdForName(type)); +} + +static double requireNumber(const std::shared_ptr& expr, const std::string& fn, const std::string& arg) { + double number = 0.0; + if (!argAsNumber(expr, number)) throw InterpreterError(fn + " expects numeric argument '" + arg + "'"); + return number; +} + +static std::string requireString(const std::shared_ptr& expr, const std::string& fn, const std::string& arg) { + std::string text; + if (!argAsString(expr, text)) throw InterpreterError(fn + " expects string argument '" + arg + "'"); + return text; +} + +static fs::path sourceRootFromBase(const fs::path& baseDir) { + fs::path current = fs::absolute(baseDir).lexically_normal(); + while (!current.empty()) { + if (fs::exists(current / "core") && fs::is_directory(current / "core")) return current; + fs::path parent = current.parent_path(); + if (parent == current) break; + current = parent; + } + return fs::current_path(); +} + +static bool isBareModuleImport(const std::string& pattern) { + if (pattern.empty()) return false; + fs::path raw(pattern); + if (raw.is_absolute() || raw.has_parent_path() || raw.has_extension()) return false; + return pattern.find('*') == std::string::npos; +} + +static bool validateNativePackageRegistry(const fs::path& libraryFile, + const NativeModuleManifest& manifest, + std::string& error) { + const fs::path registryFile = sourceRootFromBase(libraryFile.parent_path()) / "core" / "package.fx"; + if (!fs::is_regular_file(registryFile)) { + error = "missing authoritative package registry '" + registryFile.string() + "'"; + return false; + } + try { + const Program registry = parseProgramText(readSourceFile(registryFile)); + for (const auto& statement : registry.statements) { + if (statement->kind() != StatementKind::Clause) continue; + const auto package = std::static_pointer_cast(statement); + if (!package->isFact() || package->head.name != "NativePackage") continue; + const auto argument = [&](const char* name) -> std::shared_ptr { + for (const auto& arg : package->head.args) { + if (arg.name == name) return arg.value; + } + return {}; + }; + const auto name = std::dynamic_pointer_cast(argument("name")); + const auto wrapper = std::dynamic_pointer_cast(argument("wrapper")); + const auto declaration = std::dynamic_pointer_cast(argument("declaration")); + const auto abi = std::dynamic_pointer_cast(argument("abi")); + const auto requiredManifest = std::dynamic_pointer_cast(argument("manifest")); + if (!name || !abi || !requiredManifest || name->value != manifest.moduleName) continue; + if (!requiredManifest->value || abi->value != static_cast(manifest.abiVersion)) { + error = "registry contract does not permit manifest ABI " + std::to_string(manifest.abiVersion) + + " for package '" + manifest.moduleName + "'"; + return false; + } + const fs::path root = sourceRootFromBase(registryFile.parent_path()); + if (!wrapper || !declaration || wrapper->value.empty() || declaration->value.empty() || + !fs::is_regular_file(root / wrapper->value) || + !fs::is_regular_file(root / declaration->value)) { + error = "registry wrapper/declaration files are invalid for package '" + manifest.moduleName + "'"; + return false; + } + std::unordered_set allowed; + if (const auto capabilities = std::dynamic_pointer_cast(argument("capabilities"))) { + for (const auto& item : capabilities->items) { + const auto capability = std::dynamic_pointer_cast(item); + if (!capability) { + error = "registry capabilities must be strings for package '" + manifest.moduleName + "'"; + return false; + } + allowed.insert(capability->value); + } + } + const auto requireAllowed = [&](bool enabled, const char* capability) -> bool { + if (!enabled || allowed.count(capability)) return true; + error = "manifest capability '" + std::string(capability) + + " is not approved for package '" + manifest.moduleName + "'"; + return false; + }; + const auto validateContract = [&](const NativeContract& contract) -> bool { + const auto& caps = contract.capabilities; + return requireAllowed(caps.pure, "pure") && + requireAllowed(caps.threadSafe, "thread_safe") && + requireAllowed(caps.supportsBatch, "batch") && + requireAllowed(caps.acceptsFactSelections, "fact_selections") && + requireAllowed(caps.needsFactProjection, "fact_projection") && + requireAllowed(caps.needsFactHierarchy, "fact_hierarchy"); + }; + if (!validateContract(manifest.defaultContract)) return false; + for (const auto& function : manifest.functions) { + if (!validateContract(function.second)) return false; + } + return true; + } + error = "package '" + manifest.moduleName + "' is not allowlisted"; + return false; + } catch (const std::exception& ex) { + error = "cannot read package registry: " + std::string(ex.what()); + return false; + } +} + +static fs::path resolveCoreImport(const fs::path& baseDir, const std::string& pattern) { + fs::path root = sourceRootFromBase(baseDir); + return fs::absolute(root / "core" / (pattern + ".fx")).lexically_normal(); +} + +static std::string exprToJson(const std::shared_ptr& expr) { + if (auto s = std::dynamic_pointer_cast(expr)) return "\"" + jsonEscape(s->value) + "\""; + if (auto b = std::dynamic_pointer_cast(expr)) return b->value ? "true" : "false"; + if (auto n = std::dynamic_pointer_cast(expr)) { + std::ostringstream out; + out << std::setprecision(15) << n->value; + return out.str(); + } + if (std::dynamic_pointer_cast(expr)) return "null"; + if (auto selection = + std::dynamic_pointer_cast(expr)) { + std::ostringstream out; + out << "{\"__type\":\"FactSelection\",\"fact_type\":\"" + << jsonEscape(selection->factType) + << "\",\"source\":\"memory\",\"snapshot_generation\":" + << selection->snapshotGeneration; + if (!selection->field.empty()) { + out << ",\"field\":\"" << jsonEscape(selection->field) << "\""; + if (selection->equals) { + out << ",\"equals\":" << exprToJson(selection->equals); + } + } + if (!selection->designations.empty()) { + out << ",\"designations\":["; + for (size_t i = 0; i < selection->designations.size(); ++i) { + if (i) out << ","; + out << "\"" << jsonEscape(selection->designations[i]) << "\""; + } + out << "]"; + } + out << "}"; + return out.str(); + } + if (auto a = std::dynamic_pointer_cast(expr)) { + std::ostringstream out; + out << "["; + for (size_t i = 0; i < a->items.size(); ++i) { + if (i) out << ","; + out << exprToJson(a->items[i]); + } + out << "]"; + return out.str(); + } + if (auto m = std::dynamic_pointer_cast(expr)) { + std::ostringstream out; + out << "{"; + for (size_t i = 0; i < m->entries.size(); ++i) { + if (i) out << ","; + out << "\"" << jsonEscape(m->entries[i].key) << "\":" << exprToJson(m->entries[i].value); + } + out << "}"; + return out.str(); + } + if (auto t = std::dynamic_pointer_cast(expr)) { + std::vector entries; + entries.push_back(MapEntry{"__term", std::make_shared(t->name)}); + for (size_t i = 0; i < t->args.size(); ++i) { + const auto& arg = t->args[i]; + entries.push_back(MapEntry{arg.name.empty() ? ("arg" + std::to_string(i)) : arg.name, arg.value}); + } + return exprToJson(std::make_shared(std::move(entries))); + } + return "\"" + jsonEscape(expr ? expr->debug() : "") + "\""; +} + +static void skipJsonWs(const std::string& text, size_t& pos) { + while (pos < text.size() && std::isspace(static_cast(text[pos]))) pos++; +} + +static bool parseJsonString(const std::string& text, size_t& pos, std::string& out) { + skipJsonWs(text, pos); + if (pos >= text.size() || text[pos] != '"') return false; + pos++; + out.clear(); + while (pos < text.size() && text[pos] != '"') { + char c = text[pos++]; + if (c == '\\' && pos < text.size()) { + char esc = text[pos++]; + switch (esc) { + case 'n': out.push_back('\n'); break; + case 't': out.push_back('\t'); break; + case 'r': out.push_back('\r'); break; + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + default: out.push_back(esc); break; + } + } else { + out.push_back(c); + } + } + if (pos >= text.size() || text[pos] != '"') return false; + pos++; + return true; +} + +static bool parseJsonValue(const std::string& text, size_t& pos, std::shared_ptr& out); + +static bool parseJsonObjectValue(const std::string& text, size_t& pos, std::shared_ptr& out) { + skipJsonWs(text, pos); + if (pos >= text.size() || text[pos] != '{') return false; + pos++; + std::vector entries; + skipJsonWs(text, pos); + if (pos < text.size() && text[pos] == '}') { + pos++; + out = std::make_shared(std::move(entries)); + return true; + } + while (pos < text.size()) { + std::string key; + std::shared_ptr value; + if (!parseJsonString(text, pos, key)) return false; + skipJsonWs(text, pos); + if (pos >= text.size() || text[pos] != ':') return false; + pos++; + if (!parseJsonValue(text, pos, value)) return false; + entries.push_back(MapEntry{key, value}); + skipJsonWs(text, pos); + if (pos < text.size() && text[pos] == ',') { + pos++; + continue; + } + if (pos < text.size() && text[pos] == '}') { + pos++; + out = std::make_shared(std::move(entries)); + return true; + } + return false; + } + return false; +} + +static bool parseJsonArrayValue(const std::string& text, size_t& pos, std::shared_ptr& out) { + skipJsonWs(text, pos); + if (pos >= text.size() || text[pos] != '[') return false; + pos++; + std::vector> items; + skipJsonWs(text, pos); + if (pos < text.size() && text[pos] == ']') { + pos++; + out = std::make_shared(std::move(items)); + return true; + } + while (pos < text.size()) { + std::shared_ptr value; + if (!parseJsonValue(text, pos, value)) return false; + items.push_back(value); + skipJsonWs(text, pos); + if (pos < text.size() && text[pos] == ',') { + pos++; + continue; + } + if (pos < text.size() && text[pos] == ']') { + pos++; + out = std::make_shared(std::move(items)); + return true; + } + return false; + } + return false; +} + +static bool parseJsonValue(const std::string& text, size_t& pos, std::shared_ptr& out) { + skipJsonWs(text, pos); + if (pos >= text.size()) return false; + if (text.compare(pos, 4, "null") == 0) { + pos += 4; + out = std::make_shared(); + return true; + } + if (text.compare(pos, 4, "true") == 0) { + pos += 4; + out = std::make_shared(true); + return true; + } + if (text.compare(pos, 5, "false") == 0) { + pos += 5; + out = std::make_shared(false); + return true; + } + if (text[pos] == '{') return parseJsonObjectValue(text, pos, out); + if (text[pos] == '[') return parseJsonArrayValue(text, pos, out); + if (text[pos] == '"') { + std::string value; + if (!parseJsonString(text, pos, value)) return false; + out = std::make_shared(value); + return true; + } + size_t start = pos; + if (text[pos] == '-') pos++; + while (pos < text.size() && std::isdigit(static_cast(text[pos]))) pos++; + if (pos < text.size() && text[pos] == '.') { + pos++; + while (pos < text.size() && std::isdigit(static_cast(text[pos]))) pos++; + } + if (start == pos || (start + 1 == pos && text[start] == '-')) return false; + out = std::make_shared(std::stod(text.substr(start, pos - start))); + return true; +} + +static bool parseFlatJsonObject(const std::string& text, std::shared_ptr& out) { + size_t pos = 0; + if (!parseJsonValue(text, pos, out)) return false; + skipJsonWs(text, pos); + return pos == text.size(); +} + +Interpreter::~Interpreter() { + joinThreads(); + closeNativeLibraries(); +} + +void Interpreter::closeNativeLibraries() { + for (auto& library : nativeLibraries_) closeSharedLibrary(library.handle); + nativeLibraries_.clear(); + nativeLibraryPaths_.clear(); +} + +void Interpreter::beginModuleTransaction() { + if (moduleTransaction_) { + throw InterpreterError("Nested module transactions are not supported"); + } + auto transaction = std::make_unique(); + // Clause objects are immutable and shared; the bucket topology is not. + // Keep an independent bucket table for rollback so normal streamed + // registration does not invalidate live ClauseList pointers through COW. + transaction->clauses = std::make_shared(*clauses_); + transaction->operators = std::make_shared(*operators_); + transaction->operatorClauses = operatorClauses_; + transaction->autoEntryCalls = autoEntryCalls_; + transaction->autoEntryResults = autoEntryResults_; + transaction->memory = memory_; + transaction->globals = globals_; + transaction->referencesBySource = referencesBySource_; + transaction->nextReferenceAttachmentId = nextReferenceAttachmentId_; + transaction->nextReferenceCreationOrder = nextReferenceCreationOrder_; + transaction->referenceEvaluationGeneration = referenceEvaluationGeneration_; + transaction->loadedFiles = loadedFiles_; + transaction->packageDiscoveryAttempts = packageDiscoveryAttempts_; + transaction->clauseOrigins = clauseOrigins_; + transaction->programGeneration = programGeneration_; + transaction->symbolGenerations = symbolGenerations_; + transaction->moduleLoads = moduleLoads_; + transaction->cacheInvalidationDepth = cacheInvalidationDepth_; + transaction->pendingCacheInvalidation = pendingCacheInvalidation_; + transaction->contraries = contraries_; + moduleTransaction_ = std::move(transaction); +} + +void Interpreter::commitModuleTransaction() { + if (!moduleTransaction_) { + throw InterpreterError("No module transaction is active"); + } + moduleTransaction_.reset(); + // The staged clause catalog can have moved buckets while it was being + // populated. These caches retain raw clause pointers, so publish only + // after dropping all staging-era lookup/preparation entries. + clauseLookupCache_.clear(); + methodRuntimeCache_.clear(); +} + +void Interpreter::rollbackModuleTransaction() { + if (!moduleTransaction_) return; + const ModuleTransactionState& transaction = *moduleTransaction_; + clauses_ = transaction.clauses; + operators_ = transaction.operators; + operatorClauses_ = transaction.operatorClauses; + autoEntryCalls_ = transaction.autoEntryCalls; + autoEntryResults_ = transaction.autoEntryResults; + memory_ = transaction.memory; + globals_ = transaction.globals; + referencesBySource_ = transaction.referencesBySource; + nextReferenceAttachmentId_ = transaction.nextReferenceAttachmentId; + nextReferenceCreationOrder_ = transaction.nextReferenceCreationOrder; + referenceEvaluationGeneration_ = transaction.referenceEvaluationGeneration; + loadedFiles_ = transaction.loadedFiles; + packageDiscoveryAttempts_ = transaction.packageDiscoveryAttempts; + clauseOrigins_ = transaction.clauseOrigins; + programGeneration_ = transaction.programGeneration; + symbolGenerations_ = transaction.symbolGenerations; + moduleLoads_ = transaction.moduleLoads; + cacheInvalidationDepth_ = transaction.cacheInvalidationDepth; + pendingCacheInvalidation_ = transaction.pendingCacheInvalidation; + contraries_ = transaction.contraries; + moduleTransaction_.reset(); + // Plans can hold pointers into the staged clause table, so restore them + // only through the normal cache boundary after the roots are replaced. + clearCachesNow(); +} + +void Interpreter::joinThreads() { + std::vector> tasks; + { + std::lock_guard lock(threadMutex_); + tasks.reserve(threadTasks_.size()); + for (const auto& entry : threadTasks_) tasks.push_back(entry.second); + } + for (const auto& task : tasks) { + if (task && task->worker.joinable()) task->worker.join(); + } +} + +std::shared_ptr Interpreter::makeThreadHandle(const std::string& id) const { + return std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), std::make_shared("Thread")}, + {"id", std::make_shared(id)} + }); +} + +std::shared_ptr Interpreter::threadTaskFromHandle(const std::shared_ptr& handle) { + auto typeValue = findMapValue(handle, internalSymbolString(InternalSymbolKind::Type)); + auto idValue = findMapValue(handle, "id"); + auto type = std::dynamic_pointer_cast(typeValue); + auto id = std::dynamic_pointer_cast(idValue); + if (!type || type->value != "Thread" || !id || id->value.empty()) { + throw InterpreterError("thread API expects a valid thread handle"); + } + std::lock_guard lock(threadMutex_); + auto it = threadTasks_.find(id->value); + if (it == threadTasks_.end()) throw InterpreterError("Unknown thread handle: " + id->value); + return it->second; +} + +std::string Interpreter::createThreadTask(const std::string& functionName) { + if (functionName.empty()) throw InterpreterError("thread.createThread expects non-empty function name"); + if (!hasMethod(functionName)) { + throw InterpreterError("Thread function '" + functionName + "' not found"); + } + std::lock_guard lock(threadMutex_); + std::string id = "thread-" + std::to_string(++threadCounter_); + threadTasks_[id] = std::make_shared(functionName); + return id; +} + +std::string Interpreter::startThreadTask(const std::shared_ptr& handle) { + auto task = threadTaskFromHandle(handle); + { + std::lock_guard lock(threadMutex_); + if (task->started) return task->status; + task->started = true; + task->status = "running"; + } + + auto clausesSnapshot = clauses_; + auto operatorsSnapshot = operators_; + auto operatorClausesSnapshot = operatorClauses_; + auto memorySnapshot = memory_; + auto globalsSnapshot = cloneEnv(globals_.values()); + auto loadedFilesSnapshot = loadedFiles_; + auto packageDiscoveryAttemptsSnapshot = packageDiscoveryAttempts_; + auto currentLoadingFileSnapshot = currentLoadingFile_; + auto nativeLibraryPathsSnapshot = nativeLibraryPaths_; + auto contrariesSnapshot = contraries_; + auto functionName = task->functionName; + + task->worker = std::thread([this, + task, + functionName, + clausesSnapshot = std::move(clausesSnapshot), + operatorsSnapshot = std::move(operatorsSnapshot), + operatorClausesSnapshot = std::move(operatorClausesSnapshot), + memorySnapshot = std::move(memorySnapshot), + globalsSnapshot = std::move(globalsSnapshot), + loadedFilesSnapshot = std::move(loadedFilesSnapshot), + packageDiscoveryAttemptsSnapshot = + std::move(packageDiscoveryAttemptsSnapshot), + currentLoadingFileSnapshot = std::move(currentLoadingFileSnapshot), + nativeLibraryPathsSnapshot = std::move(nativeLibraryPathsSnapshot), + contrariesSnapshot = std::move(contrariesSnapshot)]() mutable { + try { + Interpreter child; + child.clauses_ = std::move(clausesSnapshot); + child.operators_ = std::move(operatorsSnapshot); + child.operatorClauses_ = std::move(operatorClausesSnapshot); + child.memory_ = std::move(memorySnapshot); + child.globals_.replaceValues(std::move(globalsSnapshot)); + child.loadedFiles_ = std::move(loadedFilesSnapshot); + child.packageDiscoveryAttempts_ = std::move(packageDiscoveryAttemptsSnapshot); + child.currentLoadingFile_ = std::move(currentLoadingFileSnapshot); + child.contraries_ = std::move(contrariesSnapshot); + for (const auto& nativePath : nativeLibraryPathsSnapshot) { + child.loadNativeLibrary(nativePath); + } + + if (!child.hasMethod(functionName)) { + throw InterpreterError("Thread function '" + functionName + "' not found"); + } + + Call call(functionName, {}); + std::vector solutions; + auto* clauses = child.findClauses(functionName, symbolIdForName(functionName)); + if (clauses) { + for (const auto& clause : *clauses) { + if (!child.isMethodClause(*clause)) continue; + child.solveMethodCall(call, clause, Env{}, solutions, 1, 0); + if (!solutions.empty()) break; + } + } + + std::string result = "false"; + if (!solutions.empty()) { + auto returned = findReturnValue(solutions.front().env); + result = !returned + ? "true" + : child.valueToString(returned); + } + + std::lock_guard lock(threadMutex_); + task->result = result; + task->status = "finished"; + } catch (const std::exception& ex) { + std::lock_guard lock(threadMutex_); + task->error = ex.what(); + task->status = "error"; + } + }); + + return "started"; +} + +std::string Interpreter::threadTaskStatus(const std::shared_ptr& handle) { + auto task = threadTaskFromHandle(handle); + std::lock_guard lock(threadMutex_); + return task->status; +} + +std::shared_ptr Interpreter::threadTaskResult(const std::shared_ptr& handle) { + auto task = threadTaskFromHandle(handle); + if (task->worker.joinable()) task->worker.join(); + std::lock_guard lock(threadMutex_); + if (!task->error.empty()) throw InterpreterError("Thread failed: " + task->error); + if (!task->started) throw InterpreterError("Thread has not been started"); + return std::make_shared(task->result); +} + +void Interpreter::collectExecutionGarbage() { + envFramePool_.collectGarbage(kMaxCachedEnvFrames); +} + +Env Interpreter::copyExecutionEnvironment(const Env& source) { + ++environmentCopies_; + return cloneEnv(source); +} + +void Interpreter::loadNativeLibrary(const std::filesystem::path& file) { + fs::path normalized = fs::absolute(file).lexically_normal(); + if (nativeLibraryPaths_.count(normalized)) return; + void* handle = openSharedLibrary(normalized); + if (!handle) { + throw InterpreterError("Cannot load native module library '" + normalized.string() + "': " + sharedLibraryError()); + } + auto call = reinterpret_cast(findSharedLibrarySymbol(handle, "felidae_native_call")); + auto free = reinterpret_cast(findSharedLibrarySymbol(handle, "felidae_native_free")); + auto manifestFn = reinterpret_cast(findSharedLibrarySymbol(handle, "felidae_native_manifest_v1")); + if (!call || !free || !manifestFn) { + closeSharedLibrary(handle); + throw InterpreterError("Native module library '" + normalized.string() + + "' must export felidae_native_call, felidae_native_free, and felidae_native_manifest_v1"); + } + const char* rawManifest = manifestFn(); + if (!rawManifest) { + closeSharedLibrary(handle); + throw InterpreterError("Native module library '" + normalized.string() + "' returned a null manifest"); + } + NativeModuleManifest manifest; + std::string manifestError; + if (!parseNativeModuleManifest(rawManifest, manifest, manifestError)) { + closeSharedLibrary(handle); + throw InterpreterError("Native module library '" + normalized.string() + + "' has an invalid manifest: " + manifestError); + } + if (!validateNativePackageRegistry(normalized, manifest, manifestError)) { + closeSharedLibrary(handle); + throw InterpreterError("Native module library '" + normalized.string() + + "' is not approved by core/package.fx: " + manifestError); + } + const std::string expectedModule = nativeModuleNameFromPath(normalized); + if (manifest.moduleName != expectedModule) { + closeSharedLibrary(handle); + throw InterpreterError("Native module manifest names '" + manifest.moduleName + + "' but library path resolves to '" + expectedModule + "'"); + } + nativeLibraries_.push_back(NativeLibrary{normalized, manifest.moduleName, handle, call, free, std::move(manifest)}); + nativeLibraryPaths_.insert(normalized); +} + +void Interpreter::addProgram(const Program& program) { + validateNegationStratification(program); + beginCacheInvalidationBatch(); + try { + for (const auto& statement : program.statements) { + switch (statement->kind()) { + case StatementKind::Import: + break; + case StatementKind::Clause: { + auto clause = std::static_pointer_cast(statement); + if (clause->clauseKind == ClauseKind::EntryCall) { + autoEntryCalls_.push_back(clause->head); + autoEntryResults_.push_back(executeEntryCall(clause->head)); + break; + } + addClause(clause); + break; + } + case StatementKind::GlobalBinding: { + auto binding = std::static_pointer_cast(statement); + if (globals_.count(binding->name) || findClauses(binding->name, symbolIdForName(binding->name))) { + throw InterpreterError("Global '" + binding->name + "' is already defined and immutable"); + } + Env env; + std::shared_ptr value; + if (!evalExprValue(binding->expr, env, value)) { + throw InterpreterError("Cannot evaluate global binding '" + binding->name + "'"); + } + globals_.bind(binding->name, value, currentLoadingFile_); + Call head(binding->name, std::vector{{"value", value->clone()}}); + addClause(std::make_shared(std::move(head), std::vector>{})); + break; + } + } + } + } catch (...) { + endCacheInvalidationBatch(); + throw; + } + endCacheInvalidationBatch(); +} + +void Interpreter::addStreamedStatement(std::shared_ptr statement) { + if (!statement || statement->kind() == StatementKind::Import) return; + if (statement->kind() == StatementKind::Clause) { + // Keep statement alive for the validated rule path below. Moving it + // into the cast made non-fact clauses become null before they were + // wrapped in the singleton Program. + auto clause = std::static_pointer_cast(statement); + if (clause->clauseKind == ClauseKind::EntryCall) { + autoEntryCalls_.push_back(clause->head); + autoEntryResults_.push_back(executeEntryCall(clause->head)); + return; + } + // Facts cannot introduce rule dependency edges, globals, or method + // behavior. Register them directly while parsing so a large fact + // module does not allocate one temporary Program per fact. + if (clause->isFact()) { + addClause(std::move(clause)); + return; + } + } + + // Rule/global registration retains the established validation path. In a + // module transaction an error restores all roots, including facts already + // streamed before this statement. + Program singleton; + singleton.addStatement(std::move(statement)); + addProgram(singleton); +} + +void Interpreter::validateNegationStratification(const Program& program) const { + // Fact-only streaming chunks cannot add rule-dependency edges. Skipping + // them is essential for large fact imports: otherwise every chunk would + // rescan all prior facts merely to rebuild an empty rule graph. + bool containsRelationalRule = false; + for (const auto& statement : program.statements) { + if (statement->kind() != StatementKind::Clause) continue; + const auto clause = std::static_pointer_cast(statement); + if (!clause->isFact() && !isMethodClause(*clause)) { + containsRelationalRule = true; + break; + } + } + if (!containsRelationalRule) return; + + struct Edge { + std::string target; + bool negative = false; + }; + std::unordered_map> graph; + + const auto collectGoals = [&](const auto& self, + const std::string& source, + const std::vector>& goals) -> void { + for (const auto& goal : goals) { + if (auto call = std::dynamic_pointer_cast(goal)) { + graph[source].push_back(Edge{call->call.name, false}); + } else if (auto negated = std::dynamic_pointer_cast(goal)) { + graph[source].push_back(Edge{negated->call.name, true}); + } else if (auto group = std::dynamic_pointer_cast(goal)) { + self(self, source, group->goals); + } else if (auto disjunction = std::dynamic_pointer_cast(goal)) { + for (const auto& branch : disjunction->branches) self(self, source, branch); + } else if (auto conditional = std::dynamic_pointer_cast(goal)) { + self(self, source, std::vector>{conditional->condition}); + self(self, source, conditional->thenBranch); + self(self, source, conditional->elseBranch); + } + } + }; + const auto addClause = [&](const std::shared_ptr& clause) { + if (!clause || clause->isFact() || isMethodClause(*clause)) return; + auto& edges = graph[clause->head.name]; + (void)edges; + collectGoals(collectGoals, clause->head.name, clause->body); + for (const auto& branch : clause->fallbackBranches) collectGoals(collectGoals, clause->head.name, branch); + }; + + for (const auto& bucket : *clauses_) { + for (const auto& nameBucket : bucket.second) { + for (const auto& clause : nameBucket.clauses) addClause(clause); + } + } + for (const auto& statement : program.statements) { + if (statement->kind() != StatementKind::Clause) continue; + addClause(std::static_pointer_cast(statement)); + } + + const auto reaches = [&](const auto& self, + const std::string& current, + const std::string& target, + std::unordered_set& visited) -> bool { + if (current == target) return true; + if (!visited.insert(current).second) return false; + const auto edges = graph.find(current); + if (edges == graph.end()) return false; + for (const auto& edge : edges->second) { + if (self(self, edge.target, target, visited)) return true; + } + return false; + }; + for (const auto& node : graph) { + for (const auto& edge : node.second) { + if (!edge.negative) continue; + std::unordered_set visited; + if (reaches(reaches, edge.target, node.first, visited)) { + throw InterpreterError("Unstratified negative dependency cycle involving '" + node.first + "'"); + } + } + } +} + +void Interpreter::addClause(std::shared_ptr clause) { + const std::string clauseName = clause->head.name; + for (const auto& annotation : clause->annotations) { + if (annotation.builtinId != BuiltinId::OverloadAnnotation && + annotation.builtinId != BuiltinId::MatcherAnnotation && + annotation.builtinId != BuiltinId::MixfixAnnotation) { + if (!hasMethod(annotation.name) && !nativeDeclarationFor(annotation.name)) { + throw InterpreterError("Annotation method '" + annotation.name + + "' is not declared before '" + clauseName + "'"); + } + TermExpr invocation(annotation.name, {}, annotation.builtinId); + invocation.nameId = annotation.nameId; + invocation.args.reserve(annotation.args.size()); + for (const auto& argument : annotation.args) { + invocation.args.push_back(Arg{argument.name, argument.nameId, argument.value->clone()}); + } + if (const auto* annotationClauses = findClauses(annotation.name, annotation.nameId)) { + for (const auto& annotationClause : *annotationClauses) { + if (!isMethodClause(*annotationClause)) continue; + const auto plans = buildMethodParamPlan(*annotationClause); + for (std::size_t i = 0; i < plans.size(); ++i) { + const auto& plan = plans[i]; + if (plan.typeId != LanguageTypeId::Stmt && + plan.typeId != LanguageTypeId::Statements) continue; + const bool supplied = std::any_of( + invocation.args.begin(), invocation.args.end(), [&](const Arg& argument) { + return argument.name == annotationClause->head.args[i].name; + }); + if (supplied) continue; + std::vector> nodes; + AstValueKind valueKind = AstValueKind::Statement; + std::string nodeKind; + if (plan.typeId == LanguageTypeId::Stmt) { + nodes.push_back(clause); + nodeKind = astNodeKind(clause); + } else { + valueKind = AstValueKind::Statements; + for (const auto& goal : clause->body) nodes.push_back(goal); + for (const auto& branch : clause->fallbackBranches) { + for (const auto& goal : branch) nodes.push_back(goal); + } + nodeKind = "stmts"; + } + invocation.args.push_back(Arg{ + annotationClause->head.args[i].name, + std::make_shared( + valueKind, std::move(nodes), std::move(nodeKind))}); + } + break; + } + } + std::shared_ptr ignored; + if (!evalCallAsValue(invocation, Env{}, ignored)) { + throw InterpreterError("Annotation method '" + annotation.name + + "' produced no result for declaration '" + clauseName + "'"); + } + continue; + } + ParsedOperatorAnnotation parsed; + try { + parsed = decodeOperatorAnnotation(annotation); + } catch (const std::runtime_error& error) { + throw InterpreterError(error.what()); + } + const auto* pa…79819 tokens truncated…dynamic_pointer_cast(ra)) { + auto nb = std::dynamic_pointer_cast(rb); + return nb && std::fabs(na->value - nb->value) < 1e-12; + } + if (auto ba = std::dynamic_pointer_cast(ra)) { + auto bb = std::dynamic_pointer_cast(rb); + if (bb) return ba->value == bb->value; + auto sb = std::dynamic_pointer_cast(rb); + return sb && sb->value == (ba->value ? "true" : "false"); + } + if (auto bb = std::dynamic_pointer_cast(rb)) { + auto sa = std::dynamic_pointer_cast(ra); + return sa && sa->value == (bb->value ? "true" : "false"); + } + if (std::dynamic_pointer_cast(ra) || std::dynamic_pointer_cast(rb)) { + return static_cast(std::dynamic_pointer_cast(ra)) && + static_cast(std::dynamic_pointer_cast(rb)); + } + if (auto ta = std::dynamic_pointer_cast(ra)) { + auto tb = std::dynamic_pointer_cast(rb); + if (!tb || ta->nameId != tb->nameId || ta->args.size() != tb->args.size()) return false; + for (size_t i = 0; i < ta->args.size(); ++i) { + if (!unifyExpr(ta->args[i].value, tb->args[i].value, env)) return false; + } + return true; + } + if (auto aa = std::dynamic_pointer_cast(ra)) { + auto ab = std::dynamic_pointer_cast(rb); + if (!ab || aa->items.size() != ab->items.size()) return false; + for (size_t i = 0; i < aa->items.size(); ++i) { + if (!unifyExpr(aa->items[i], ab->items[i], env)) return false; + } + return true; + } + if (auto ma = std::dynamic_pointer_cast(ra)) { + auto mb = std::dynamic_pointer_cast(rb); + if (!mb || ma->entries.size() != mb->entries.size()) return false; + for (const auto& entry : ma->entries) { + auto other = findMapValue(rb, entry.key); + if (!other || !unifyExpr(entry.value, other, env)) return false; + } + return true; + } + + return false; +} + +std::shared_ptr Interpreter::resolveExpr(const std::shared_ptr& expr, const Env& env) const { + auto var = std::dynamic_pointer_cast(expr); + if (var && var->nameId == InternalSymbol::SystemResultId) { + if (pipelineResults_.empty()) { + throw InterpreterError("system.result is only available inside a then pipeline"); + } + return pipelineResults_.back()->clone(); + } + if (!var) { + if (auto access = std::dynamic_pointer_cast(expr)) { + if (access->keyId == InternalSymbol::ResultId) { + auto targetVar = std::dynamic_pointer_cast(access->target); + if (targetVar && targetVar->nameId == InternalSymbol::SystemId) { + if (pipelineResults_.empty()) { + throw InterpreterError("system.result is only available inside a then pipeline"); + } + return pipelineResults_.back()->clone(); + } + } + std::shared_ptr target; + if (!const_cast(this)->evalExprValue(access->target, env, target)) return expr; + auto value = findMapValue(target, access->key); + if (!value) return expr; + return resolveExpr(value, env); + } + return expr; + } + + auto it = env.find(var->nameId); + if (it == env.end()) { + auto globalIt = globals_.find(var->nameId); + if (globalIt != globals_.end()) return resolveExpr(globalIt->second, env); + return expr; + } + + // Follow standardized variable aliases to their resolved value. + return resolveExpr(it->second, env); +} + +std::string Interpreter::exprToString(const std::shared_ptr& expr, const Env& env) const { + auto resolved = resolveExpr(expr, env); + std::shared_ptr value; + if (const_cast(this)->evalExprValue(resolved, env, value)) { + return value->debug(); + } + return resolved->debug(); +} + +std::shared_ptr Interpreter::standardizeApart(const std::shared_ptr& originalClause) { + const ClauseStmt& clause = *originalClause; + const auto cachedRequirement = clauseRenameRequirements_.find(originalClause.get()); + if (cachedRequirement != clauseRenameRequirements_.end() && !cachedRequirement->second) { + return originalClause; + } + const auto goalNeedsRename = [&](const auto& self, const std::shared_ptr& goal) -> bool { + switch (goal->kind()) { + case GoalKind::Call: + for (const auto& arg : std::static_pointer_cast(goal)->call.args) { + if (exprNeedsRename(arg.value)) return true; + } + return false; + case GoalKind::Not: + for (const auto& arg : std::static_pointer_cast(goal)->call.args) { + if (exprNeedsRename(arg.value)) return true; + } + return false; + case GoalKind::Assign: + case GoalKind::MultiAssign: + return true; + case GoalKind::Binary: { + const auto binary = std::static_pointer_cast(goal); + return exprNeedsRename(binary->left) || exprNeedsRename(binary->right); + } + case GoalKind::Where: + return self(self, std::static_pointer_cast(goal)->condition); + case GoalKind::Return: + for (const auto& field : std::static_pointer_cast(goal)->fields) { + if (exprNeedsRename(field.value)) return true; + } + return false; + case GoalKind::Group: + for (const auto& nested : std::static_pointer_cast(goal)->goals) { + if (self(self, nested)) return true; + } + return false; + case GoalKind::Or: + for (const auto& branch : std::static_pointer_cast(goal)->branches) { + for (const auto& nested : branch) if (self(self, nested)) return true; + } + return false; + case GoalKind::If: { + const auto conditional = std::static_pointer_cast(goal); + if (self(self, conditional->condition)) return true; + for (const auto& nested : conditional->thenBranch) if (self(self, nested)) return true; + for (const auto& nested : conditional->elseBranch) if (self(self, nested)) return true; + return false; + } + } + return true; + }; + bool needsRename = false; + for (const auto& arg : clause.head.args) { + if (exprNeedsRename(arg.value)) { needsRename = true; break; } + } + if (!needsRename) { + for (const auto& goal : clause.body) { + if (goalNeedsRename(goalNeedsRename, goal)) { needsRename = true; break; } + } + } + if (!needsRename) { + for (const auto& branch : clause.fallbackBranches) { + for (const auto& goal : branch) { + if (goalNeedsRename(goalNeedsRename, goal)) { needsRename = true; break; } + } + if (needsRename) break; + } + } + clauseRenameRequirements_[originalClause.get()] = needsRename; + if (!needsRename) return originalClause; + ++standardizedClauses_; + RenameMap names; + Call head; + head.name = clause.head.name; + head.nameId = clause.head.nameId; + head.builtinId = clause.head.builtinId; + bool methodHead = isMethodClause(clause); + for (const auto& arg : clause.head.args) { + auto typeExpr = std::dynamic_pointer_cast(arg.value); + if (methodHead && typeExpr && isFelidaeTypeAnnotationName(typeExpr->name)) { + head.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + } else { + head.args.push_back(Arg{arg.name, arg.nameId, renameExpr(arg.value, names)}); + } + } + std::vector> body; + body.reserve(clause.body.size()); + for (const auto& g : clause.body) body.push_back(renameGoal(g, names)); + std::vector>> fallbackBranches; + fallbackBranches.reserve(clause.fallbackBranches.size()); + for (const auto& branch : clause.fallbackBranches) { + std::vector> renamedBranch; + renamedBranch.reserve(branch.size()); + for (const auto& goal : branch) renamedBranch.push_back(renameGoal(goal, names)); + fallbackBranches.push_back(std::move(renamedBranch)); + } + return std::make_shared( + std::move(head), + clause.parentNames, + std::move(body), + std::move(fallbackBranches), + clause.emptyDeclaration, + clause.clauseKind); +} + +SymbolId Interpreter::renamedId(SymbolId original, RenameMap& names) { + const auto found = names.find(original); + if (found != names.end()) return found->second; + const SymbolId generated = symbolInterner().makeGenerated(); + names.emplace(original, generated); + return generated; +} + +Call Interpreter::renameCall(const Call& call, RenameMap& names) { + Call out; + out.name = call.name; + out.nameId = call.nameId; + out.builtinId = call.builtinId; + for (const auto& a : call.args) { + if ((call.builtinId == BuiltinId::Throw && a.name == "target") || + (call.builtinId == BuiltinId::Instanceof && + (a.name == "type" || a.name == "parent" || a.name == "of"))) { + out.args.push_back(Arg{a.name, a.nameId, a.value->clone()}); + continue; + } + out.args.push_back(Arg{a.name, a.nameId, renameExpr(a.value, names)}); + } + return out; +} + +std::shared_ptr Interpreter::renameGoal(const std::shared_ptr& goal, RenameMap& names) { + switch (goal->kind()) { + case GoalKind::Call: { + auto cg = std::static_pointer_cast(goal); + return std::make_shared(renameCall(cg->call, names)); + } + case GoalKind::Not: { + auto ng = std::static_pointer_cast(goal); + return std::make_shared(renameCall(ng->call, names)); + } + case GoalKind::Assign: { + auto ag = std::static_pointer_cast(goal); + const SymbolId id = renamedId(ag->nameId, names); + return std::make_shared(symbolNameForId(id), id, renameExpr(ag->expr, names)); + } + case GoalKind::MultiAssign: { + auto mag = std::static_pointer_cast(goal); + std::vector targets; + targets.reserve(mag->targets.size()); + for (const auto& target : mag->targets) { + const SymbolId id = renamedId(target.nameId, names); + targets.emplace_back(symbolNameForId(id), id, target.type); + } + return std::make_shared(std::move(targets), renameExpr(mag->expr, names)); + } + case GoalKind::Binary: { + auto bg = std::static_pointer_cast(goal); + return std::make_shared(renameExpr(bg->left, names), bg->op, renameExpr(bg->right, names)); + } + case GoalKind::Where: { + auto wg = std::static_pointer_cast(goal); + return std::make_shared(renameGoal(wg->condition, names)); + } + case GoalKind::If: { + auto ifGoal = std::static_pointer_cast(goal); + std::vector> thenBranch; + thenBranch.reserve(ifGoal->thenBranch.size()); + for (const auto& branchGoal : ifGoal->thenBranch) thenBranch.push_back(renameGoal(branchGoal, names)); + std::vector> elseBranch; + elseBranch.reserve(ifGoal->elseBranch.size()); + for (const auto& branchGoal : ifGoal->elseBranch) elseBranch.push_back(renameGoal(branchGoal, names)); + return std::make_shared( + renameGoal(ifGoal->condition, names), + std::move(thenBranch), + std::move(elseBranch)); + } + case GoalKind::Return: { + auto rg = std::static_pointer_cast(goal); + std::vector fields; + fields.reserve(rg->fields.size()); + for (const auto& field : rg->fields) fields.push_back(Arg{field.name, field.nameId, renameExpr(field.value, names)}); + return std::make_shared(std::move(fields)); + } + case GoalKind::Group: { + auto gg = std::static_pointer_cast(goal); + std::vector> goals; + goals.reserve(gg->goals.size()); + for (const auto& groupedGoal : gg->goals) goals.push_back(renameGoal(groupedGoal, names)); + return std::make_shared(std::move(goals)); + } + case GoalKind::Or: { + auto og = std::static_pointer_cast(goal); + std::vector>> branches; + branches.reserve(og->branches.size()); + for (const auto& branch : og->branches) { + std::vector> renamedBranch; + renamedBranch.reserve(branch.size()); + for (const auto& branchGoal : branch) renamedBranch.push_back(renameGoal(branchGoal, names)); + branches.push_back(std::move(renamedBranch)); + } + return std::make_shared(std::move(branches)); + } + } + throw InterpreterError("Unknown goal while renaming"); +} + +std::shared_ptr Interpreter::renameExpr(const std::shared_ptr& expr, RenameMap& names) { + if (!expr) return nullptr; + if (!exprNeedsRename(expr)) return expr; + switch (expr->kind()) { + case ExprKind::String: + case ExprKind::Number: + case ExprKind::Bool: + case ExprKind::Nil: + return expr; + default: + break; + } + if (auto v = std::dynamic_pointer_cast(expr)) { + if (v->nameId == InternalSymbol::SystemResultId) return v->clone(); + if (globals_.count(v->nameId) > 0) return v->clone(); + const SymbolId id = renamedId(v->nameId, names); + return std::make_shared(symbolNameForId(id), id); + } + if (auto term = std::dynamic_pointer_cast(expr)) { + std::vector args; + args.reserve(term->args.size()); + for (const auto& arg : term->args) args.push_back(Arg{arg.name, arg.nameId, renameExpr(arg.value, names)}); + return std::make_shared(term->name, std::move(args), term->builtinId); + } + if (auto array = std::dynamic_pointer_cast(expr)) { + std::vector> items; + items.reserve(array->items.size()); + for (const auto& item : array->items) items.push_back(renameExpr(item, names)); + return std::make_shared(std::move(items)); + } + if (auto map = std::dynamic_pointer_cast(expr)) { + std::vector entries; + entries.reserve(map->entries.size()); + for (const auto& entry : map->entries) { + entries.push_back(MapEntry{entry.key, renameExpr(entry.value, names)}); + } + return std::make_shared(std::move(entries)); + } + if (auto access = std::dynamic_pointer_cast(expr)) { + auto targetVar = std::dynamic_pointer_cast(access->target); + if (access->keyId == InternalSymbol::ResultId && targetVar && targetVar->nameId == InternalSymbol::SystemId) { + return access->clone(); + } + return std::make_shared(renameExpr(access->target, names), access->key); + } + if (auto lambda = std::dynamic_pointer_cast(expr)) { + const SymbolId variableId = renamedId(lambda->variableId, names); + return std::make_shared( + renameExpr(lambda->source, names), + symbolNameForId(variableId), variableId, + renameExpr(lambda->body, names), + lambda->op, + lambda->right ? renameExpr(lambda->right, names) : nullptr); + } + if (auto op = std::dynamic_pointer_cast(expr)) { + std::shared_ptr renamed; + if (op->coreOperator != CoreOperator::Unknown) { + renamed = op->captureCount() == 1 + ? std::make_shared(op->coreOperator, renameExpr(op->capture(0), names)) + : std::make_shared( + op->coreOperator, + renameExpr(op->capture(0), names), + renameExpr(op->capture(1), names)); + } else { + std::vector captures; + captures.reserve(op->captureCount()); + for (size_t i = 0; i < op->captureCount(); ++i) { + captures.emplace_back(std::string(op->captureName(i)), renameExpr(op->capture(i), names)); + } + renamed = std::make_shared( + op->operatorId, op->patternId, std::move(captures), op->explicitlyGrouped); + } + renamed->operatorId = op->operatorId; + renamed->patternId = op->patternId; + renamed->module = op->module; + return renamed; + } + return expr; +} + +bool Interpreter::exprNeedsRename(const std::shared_ptr& expr) const { + if (!expr) return false; + if (auto variable = std::dynamic_pointer_cast(expr)) { + return variable->nameId != InternalSymbol::SystemResultId && globals_.count(variable->nameId) == 0; + } + if (auto term = std::dynamic_pointer_cast(expr)) { + for (const auto& arg : term->args) { + if (exprNeedsRename(arg.value)) return true; + } + return false; + } + if (auto array = std::dynamic_pointer_cast(expr)) { + for (const auto& item : array->items) { + if (exprNeedsRename(item)) return true; + } + return false; + } + if (auto map = std::dynamic_pointer_cast(expr)) { + for (const auto& entry : map->entries) { + if (exprNeedsRename(entry.value)) return true; + } + return false; + } + if (auto access = std::dynamic_pointer_cast(expr)) { + return exprNeedsRename(access->target); + } + if (auto op = std::dynamic_pointer_cast(expr)) { + for (size_t i = 0; i < op->captureCount(); ++i) { + if (exprNeedsRename(op->capture(i))) return true; + } + return false; + } + // Lambda parameter names are invocation-local even when their current + // source/body happens not to mention another ordinary variable. + if (std::dynamic_pointer_cast(expr)) return true; + return false; +} + +bool Interpreter::isSameVariable(const std::shared_ptr& a, const std::shared_ptr& b) const { + auto va = std::dynamic_pointer_cast(a); + auto vb = std::dynamic_pointer_cast(b); + return va && vb && va->nameId == vb->nameId; +} + +bool Interpreter::isGroundLiteral(const std::shared_ptr& expr) const { + return static_cast(std::dynamic_pointer_cast(expr)) || + static_cast(std::dynamic_pointer_cast(expr)) || + static_cast(std::dynamic_pointer_cast(expr)) || + static_cast(std::dynamic_pointer_cast(expr)); +} + +bool Interpreter::isCacheableQuery(const std::vector>& goals) const { + for (const auto& goal : goals) { + if (goalMayHaveSideEffects(goal)) return false; + } + return true; +} + +bool Interpreter::goalMayHaveSideEffects(const std::shared_ptr& goal) const { + if (!goal) return false; + if (auto call = std::dynamic_pointer_cast(goal)) { + if (nativeDeclarationFor(call->call.name)) return true; + if (call->call.builtinId != BuiltinId::Unknown && !isBuiltinPure(call->call.builtinId)) return true; + for (const auto& arg : call->call.args) { + if (exprMayHaveSideEffects(arg.value)) return true; + } + return false; + } + if (auto notGoal = std::dynamic_pointer_cast(goal)) { + for (const auto& arg : notGoal->call.args) { + if (exprMayHaveSideEffects(arg.value)) return true; + } + return false; + } + if (auto assign = std::dynamic_pointer_cast(goal)) { + return exprMayHaveSideEffects(assign->expr); + } + if (auto multi = std::dynamic_pointer_cast(goal)) { + return exprMayHaveSideEffects(multi->expr); + } + if (auto binary = std::dynamic_pointer_cast(goal)) { + return exprMayHaveSideEffects(binary->left) || exprMayHaveSideEffects(binary->right); + } + if (auto where = std::dynamic_pointer_cast(goal)) { + return goalMayHaveSideEffects(where->condition); + } + if (auto ifGoal = std::dynamic_pointer_cast(goal)) { + if (goalMayHaveSideEffects(ifGoal->condition)) return true; + for (const auto& nested : ifGoal->thenBranch) { + if (goalMayHaveSideEffects(nested)) return true; + } + for (const auto& nested : ifGoal->elseBranch) { + if (goalMayHaveSideEffects(nested)) return true; + } + return false; + } + if (auto ret = std::dynamic_pointer_cast(goal)) { + for (const auto& field : ret->fields) { + if (exprMayHaveSideEffects(field.value)) return true; + } + return false; + } + if (auto group = std::dynamic_pointer_cast(goal)) { + for (const auto& nested : group->goals) { + if (goalMayHaveSideEffects(nested)) return true; + } + return false; + } + if (auto orGoal = std::dynamic_pointer_cast(goal)) { + for (const auto& branch : orGoal->branches) { + for (const auto& nested : branch) { + if (goalMayHaveSideEffects(nested)) return true; + } + } + } + return false; +} + +bool Interpreter::exprMayHaveSideEffects(const std::shared_ptr& expr) const { + if (!expr) return false; + if (auto term = std::dynamic_pointer_cast(expr)) { + if (nativeDeclarationFor(term->name)) return true; + if (term->builtinId != BuiltinId::Unknown && !isBuiltinPure(term->builtinId)) return true; + for (const auto& arg : term->args) { + if (exprMayHaveSideEffects(arg.value)) return true; + } + return false; + } + if (auto array = std::dynamic_pointer_cast(expr)) { + for (const auto& item : array->items) { + if (exprMayHaveSideEffects(item)) return true; + } + return false; + } + if (auto map = std::dynamic_pointer_cast(expr)) { + for (const auto& entry : map->entries) { + if (exprMayHaveSideEffects(entry.value)) return true; + } + return false; + } + if (auto access = std::dynamic_pointer_cast(expr)) { + return exprMayHaveSideEffects(access->target); + } + if (auto op = std::dynamic_pointer_cast(expr)) { + for (size_t i = 0; i < op->captureCount(); ++i) { + if (exprMayHaveSideEffects(op->capture(i))) return true; + } + return false; + } + if (auto lambda = std::dynamic_pointer_cast(expr)) { + return exprMayHaveSideEffects(lambda->source) || + exprMayHaveSideEffects(lambda->body) || + exprMayHaveSideEffects(lambda->right); + } + return false; +} + +bool Interpreter::isMethodClause(const ClauseStmt& clause) const { + return clause.clauseKind == ClauseKind::Method || + clause.clauseKind == ClauseKind::NativeDeclaration; +} + +bool Interpreter::methodMetadataCacheEligible(const ClauseStmt& clause) const { + if (clause.isFact()) return false; + if (clause.head.name == "main") return true; + if (!clause.body.empty() || !clause.fallbackBranches.empty()) return true; + return false; +} + +Interpreter::MethodParamPlan Interpreter::makeMethodParamPlan(const Arg& param) const { + MethodParamPlan plan; + plan.localName = param.name; + auto typeExpr = std::dynamic_pointer_cast(param.value); + plan.typedParam = typeExpr && isFelidaeTypeAnnotationName(typeExpr->name); + if (typeExpr && !plan.typedParam && !typeExpr->name.empty() && + !isInternalGeneratedSymbolId(typeExpr->nameId)) { + plan.localName = typeExpr->name; + } + if (plan.typedParam) { + plan.typeName = typeExpr->name; + plan.typeId = languageTypeIdForName(typeExpr->name); + plan.builtinType = isFelidaeBuiltinTypeName(typeExpr->name); + } + return plan; +} + +std::vector Interpreter::buildMethodParamPlan(const ClauseStmt& clause) const { + std::vector params; + params.reserve(clause.head.args.size()); + for (const auto& param : clause.head.args) params.push_back(makeMethodParamPlan(param)); + return params; +} + +const std::vector* Interpreter::hotMethodParamPlan( + const std::shared_ptr& clause) { + if (!methodMetadataCacheEligible(*clause)) return nullptr; + auto& info = methodRuntimeCache_[clause.get()]; + info.cacheEligible = true; + ++info.callCount; + if (info.paramsPrepared) return &info.params; + if (info.callCount < kHotMethodPrepareThreshold) return nullptr; + info.params = buildMethodParamPlan(*clause); + info.paramsPrepared = true; + return &info.params; +} + +Interpreter::FactMaterialization Interpreter::factToMap(const ClauseStmt& clause) { + std::vector entries; + std::vector temporalEntries; + std::vector inheritedFields; + std::vector parentFactIds; + const auto parentNames = clause.parentNames.empty() + ? std::vector{clause.parentName} + : clause.parentNames; + const bool requirementSchema = std::any_of( + parentNames.begin(), parentNames.end(), [&](const std::string& parent) { + return parent == "OperatorRequirement" || + memory_.isCompatibleType(parent, "OperatorRequirement"); + }); + std::set childFields; + for (const auto& arg : clause.head.args) childFields.insert(arg.name); + for (const auto& parentType : parentNames) { + if (parentType.empty()) continue; + const auto parentIndexes = memory_.compatibleFactIndexes(parentType); + const auto parent = std::find_if(parentIndexes.begin(), parentIndexes.end(), [&](size_t index) { + const auto& fact = memory_.fact(index); + return fact.type == parentType && fact.active; + }); + if (parent == parentIndexes.end()) { + if (parentType == "OperatorRequirement") continue; + throw InterpreterError("Unknown parent fact/type '" + parentType + "'"); + } + const auto parentValue = memory_.factValue(*parent); + if (!parentValue) { + throw InterpreterError("Cannot materialize parent fact/type '" + parentType + "'"); + } + parentFactIds.push_back(memory_.fact(*parent).id); + for (const auto& inherited : parentValue->entries) { + if (inherited.key == internalSymbolString(InternalSymbolKind::Type) || + inherited.key == internalSymbolString(InternalSymbolKind::Parent)) { + continue; + } + const auto existing = std::find_if(inheritedFields.begin(), inheritedFields.end(), [&](const MapEntry& entry) { + return entry.keyId == inherited.keyId && entry.key == inherited.key; + }); + if (existing == inheritedFields.end()) { + inheritedFields.push_back(MapEntry{inherited.key, inherited.value->clone()}); + } else if (!exprEqualsLiteral(existing->value, inherited.value) && + !childFields.count(inherited.key)) { + throw InterpreterError( + "Ambiguous inherited field '" + inherited.key + "' for " + clause.head.name + + "; provide an explicit value in the child fact"); + } + } + } + upsertEntry(entries, internalSymbolString(InternalSymbolKind::Type), std::make_shared(clause.head.name)); + if (!parentNames.empty() && !parentNames.front().empty()) { + upsertEntry(entries, internalSymbolString(InternalSymbolKind::Parent), + std::make_shared(parentNames.front())); + } + Env env; + for (const auto& arg : clause.head.args) { + std::shared_ptr value; + if (!evalExprValue(arg.value, env, value)) { + const auto declaredType = std::dynamic_pointer_cast(arg.value); + if (requirementSchema && declaredType && + isFelidaeTypeAnnotationName(declaredType->name)) { + value = std::make_shared(declaredType->name); + } else { + throw InterpreterError("Cannot evaluate fact field '" + arg.name + "' for " + clause.head.name); + } + } + // Explicit child fields always override inherited values. This also + // supplies the required disambiguation for two parents that expose + // the same field with different values. + if (arg.name.rfind("fx:", 0) == 0) { + upsertEntry(temporalEntries, arg.name, value->clone()); + } else { + upsertEntry(entries, arg.name, value->clone()); + } + } + auto fact = std::make_shared(std::move(entries)); + fact->factType = clause.head.name; + auto temporal = temporalEntries.empty() + ? std::shared_ptr{} + : std::make_shared(std::move(temporalEntries)); + return FactMaterialization{std::move(fact), std::move(temporal), std::move(parentFactIds)}; +} + +std::vector> Interpreter::valuesForLambdaSource(const std::shared_ptr& source, + const Env& env) { + auto var = std::dynamic_pointer_cast(source); + // A string source is an explicit dynamic fact-type selector. It keeps + // multi-model .fx databases usable through normal lambda queries even + // when a model name is lowercase and therefore indistinguishable from a + // local variable in source syntax. + if (const auto typeName = std::dynamic_pointer_cast(source)) { + ensurePredicateLoaded(typeName->value); + std::vector> values; + for (size_t factIndex : memory_.currentFactIndexes(memory_.compatibleFactIndexes(typeName->value))) { + if (const auto value = memory_.factValue(factIndex)) values.push_back(value); + } + return values; + } + if (var) { + auto globalIt = globals_.find(var->name); + if (globalIt != globals_.end()) { + std::shared_ptr value; + if (!evalExprValue(globalIt->second, env, value)) return {}; + if (auto array = std::dynamic_pointer_cast(value)) return array->items; + return {value}; + } + const SymbolId designationId = symbolIdForName(var->name); + if (memory_.hasDesignation(designationId)) { + std::vector> values; + for (const size_t factIndex : memory_.currentFactIndexes(memory_.designationIndexes({designationId}))) { + if (const auto value = memory_.factValue(factIndex)) values.push_back(value); + } + return values; + } + } + if (var && var->isCapitalized) { + ensurePredicateLoaded(var->name); + std::vector> values; + for (size_t factIndex : memory_.currentFactIndexes(memory_.compatibleFactIndexes(var->name))) { + if (const auto value = memory_.factValue(factIndex)) values.push_back(value); + } + return values; + } + + std::shared_ptr value; + if (!evalExprValue(source, env, value)) return {}; + if (auto array = std::dynamic_pointer_cast(value)) return array->items; + if (std::dynamic_pointer_cast(value)) { + return materializeFactSelection(value)->items; + } + return {value}; +} + +const Arg* Interpreter::findArgByNameOrIndex(const Call& call, const std::string& name, size_t index) const { + if (!name.empty()) { + const SymbolId nameId = symbolIdForName(name); + for (const auto& arg : call.args) { + if (arg.nameId == nameId) return &arg; + } + } + if (index < call.args.size()) return &call.args[index]; + return nullptr; +} + +Interpreter::ClauseList* Interpreter::findClauses(const std::string& name, SymbolId nameId) { + if (cacheInvalidationDepth_ == 0) { + auto cached = clauseLookupCache_.find(name); + if (cached != clauseLookupCache_.end()) { + ++dispatchCacheHits_; + return cached->second; + } + ++dispatchCacheMisses_; + } + if (nameId == 0) nameId = symbolIdForName(name); + auto found = clauses_->find(nameId); + if (found == clauses_->end()) return nullptr; + for (auto& bucket : found->second) { + if (bucket.name == name) { + auto* clauses = &bucket.clauses; + if (cacheInvalidationDepth_ == 0) clauseLookupCache_[name] = clauses; + return clauses; + } + } + return nullptr; +} + +const Interpreter::ClauseList* Interpreter::findClauses(const std::string& name, SymbolId nameId) const { + if (cacheInvalidationDepth_ == 0) { + auto cached = clauseLookupCache_.find(name); + if (cached != clauseLookupCache_.end()) { + ++dispatchCacheHits_; + return cached->second; + } + ++dispatchCacheMisses_; + } + if (nameId == 0) nameId = symbolIdForName(name); + auto found = clauses_->find(nameId); + if (found == clauses_->end()) return nullptr; + for (const auto& bucket : found->second) { + if (bucket.name == name) { + auto* clauses = const_cast(&bucket.clauses); + if (cacheInvalidationDepth_ == 0) clauseLookupCache_[name] = clauses; + return clauses; + } + } + return nullptr; +} + +Interpreter::ClauseList& Interpreter::getOrCreateClauseList(const std::string& name, SymbolId nameId) { + if (nameId == 0) nameId = symbolIdForName(name); + ensureClauseTableUnique(); + auto& buckets = (*clauses_)[nameId]; + for (auto& bucket : buckets) { + if (bucket.name == name) return bucket.clauses; + } + buckets.push_back(ClauseBucket{name, {}}); + return buckets.back().clauses; +} + +void Interpreter::removeClauseBucket(const std::string& name, SymbolId nameId) { + if (nameId == 0) nameId = symbolIdForName(name); + ensureClauseTableUnique(); + auto found = clauses_->find(nameId); + if (found == clauses_->end()) return; + auto& buckets = found->second; + buckets.erase( + std::remove_if(buckets.begin(), buckets.end(), [&](const ClauseBucket& bucket) { + return bucket.name == name; + }), + buckets.end()); + if (buckets.empty()) clauses_->erase(found); +} + +void Interpreter::ensureClauseTableUnique() { + if (clauses_.use_count() != 1) { + clauses_ = std::make_shared(*clauses_); + // Lookup entries hold ClauseList pointers. Copy-on-write publication + // changes their owning table, so no cached pointer may survive it. + clauseLookupCache_.clear(); + } +} + +std::string Interpreter::solveCacheKey(const std::vector>& goals, + size_t maxSolutions) const { + std::ostringstream out; + // Immutable program and fact generations make cached answers valid only + // for the state that produced them; unrelated registrations no longer + // require clearing every cached query. + out << programGeneration_ << '|' << memory_.generation() << '|' << maxSolutions << '|'; + for (const auto& goal : goals) { + out << goal->debug() << ';'; + } + return out.str(); +} + +std::size_t Interpreter::estimateCachedSolutionsBytes( + const std::string& key, + const std::vector& solutions) const { + std::size_t bytes = sizeof(SolveCacheEntry) + key.capacity(); + bytes += solutions.capacity() * sizeof(Solution); + for (const auto& solution : solutions) { + bytes += solution.env.size() * sizeof(Env::value_type); + } + return bytes; +} + +void Interpreter::storeCachedSolutions(const std::string& key, + const std::vector& solutions) { + constexpr std::size_t MaxCacheEntries = 128; + constexpr std::size_t MaxCacheBytes = std::size_t{8} * 1024 * 1024; + + auto existing = solveCache_.find(key); + if (existing != solveCache_.end()) { + solveCacheBytes_ -= existing->second.estimatedBytes; + solveCacheRecency_.erase(existing->second.recency); + solveCache_.erase(existing); + } + + const std::size_t estimatedBytes = estimateCachedSolutionsBytes(key, solutions); + if (estimatedBytes > MaxCacheBytes) return; + + solveCacheRecency_.push_front(key); + auto recency = solveCacheRecency_.begin(); + auto inserted = solveCache_.emplace( + *recency, + SolveCacheEntry{solutions, recency, estimatedBytes}); + if (!inserted.second) { + solveCacheRecency_.pop_front(); + return; + } + solveCacheBytes_ += estimatedBytes; + + while (solveCache_.size() > MaxCacheEntries || solveCacheBytes_ > MaxCacheBytes) { + const std::string& oldestKey = solveCacheRecency_.back(); + auto oldest = solveCache_.find(oldestKey); + if (oldest != solveCache_.end()) { + solveCacheBytes_ -= oldest->second.estimatedBytes; + solveCache_.erase(oldest); + } + solveCacheRecency_.pop_back(); + } +} + +void Interpreter::invalidateCaches() { + ++programGeneration_; +} + +void Interpreter::beginCacheInvalidationBatch() { + ++cacheInvalidationDepth_; +} + +void Interpreter::endCacheInvalidationBatch() { + if (cacheInvalidationDepth_ == 0) return; + --cacheInvalidationDepth_; + if (cacheInvalidationDepth_ == 0) pendingCacheInvalidation_ = false; +} + +void Interpreter::clearCachesNow() { + memory_.invalidateCaches(); + solveCache_.clear(); + solveCacheRecency_.clear(); + solveCacheBytes_ = 0; + methodRuntimeCache_.clear(); + clauseLookupCache_.clear(); + typeAncestryCache_.clear(); + typeAncestorDistanceCache_.clear(); + typeHierarchyDepthCache_.clear(); + ancestryCacheGeneration_ = 0; + comparisonDispatchCache_.clear(); + tableCache_.clear(); +} + +bool Interpreter::ensurePredicateLoaded(const std::string& predicate) { + const SymbolId predicateId = symbolIdForName(predicate); + if (findClauses(predicate, predicateId)) return true; + const size_t namespaceEnd = predicate.find(':'); + if (namespaceEnd != std::string::npos && namespaceEnd != 0) { + const std::string moduleName = predicate.substr(0, namespaceEnd); + if (packageDiscoveryAttempts_.insert(moduleName).second) { + const fs::path baseDir = currentLoadingFile_.empty() + ? fs::current_path() + : currentLoadingFile_.parent_path(); + const fs::path packageFile = + sourceRootFromBase(baseDir) / "core" / (moduleName + ".fx"); + if (fs::is_regular_file(packageFile)) loadProgramFile(packageFile); + } + } + return findClauses(predicate, predicateId) != nullptr; +} + +void Interpreter::loadProgramFile(const std::filesystem::path& file) { + fs::path normalized = fs::absolute(file).lexically_normal(); + if (loadedFiles_.count(normalized)) return; + const bool ownsTransaction = !moduleTransaction_; + if (ownsTransaction) beginModuleTransaction(); + loadedFiles_.insert(normalized); + ++moduleLoads_; + + fs::path baseDir = normalized.parent_path(); + fs::path previous = currentLoadingFile_; + currentLoadingFile_ = normalized; + try { + const auto streamStarted = std::chrono::steady_clock::now(); + parseProgramFileStatements(normalized, [&](std::shared_ptr statement) { + if (statement->kind() == StatementKind::Import) { + const auto import = std::static_pointer_cast(statement); + for (const auto& path : import->paths) addImport(baseDir, path); + return; + } + addStreamedStatement(std::move(statement)); + }, operators_); + streamedModuleMicros_ += static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now() - streamStarted).count()); + currentLoadingFile_ = previous; + if (ownsTransaction) commitModuleTransaction(); + } catch (...) { + currentLoadingFile_ = previous; + if (ownsTransaction) rollbackModuleTransaction(); + throw; + } +} + +std::shared_ptr Interpreter::materializeFactSelection( + const std::shared_ptr& selection) { + if (const auto lazy = + std::dynamic_pointer_cast(selection)) { + const auto indexes = lazy->designationIds.empty() + ? memory_.selectionIndexes( + lazy->factType, + lazy->field, + lazy->equals && isGroundLiteral(lazy->equals) + ? lazy->equals : nullptr, + lazy->snapshotGeneration) + : memory_.designationIndexes(lazy->designationIds, lazy->snapshotGeneration); + std::vector> rows; + rows.reserve(indexes.size()); + const auto appendMatches = [&](const std::vector& candidates, + bool allowHistorical) { + for (const auto index : candidates) { + const auto& record = memory_.snapshotFact(lazy->snapshotGeneration, index); + if ((!allowHistorical && !record.active) || (!lazy->factType.empty() && + !memory_.isCompatibleType(record.type, lazy->factType))) { + continue; + } + if (!lazy->designationIds.empty() && !std::all_of( + lazy->designationIds.begin(), lazy->designationIds.end(), + [&](SymbolId designation) { + return std::find(record.designations.begin(), record.designations.end(), designation) != + record.designations.end(); + })) continue; + const auto fact = + memory_.factValue(index, lazy->snapshotGeneration); + if (!fact) continue; + if (!lazy->field.empty()) { + const auto actual = findMapValue(fact, lazy->field); + if (!actual || !lazy->equals || !exprContainsLiteral(actual, lazy->equals)) continue; + } + bool matches = true; + for (const auto& filter : lazy->filters) { + const auto actual = findMapValue(fact, filter.field); + if (!actual || !filter.value) { + matches = false; + break; + } + if (filter.op == TokenId::EQUAL) { + matches = exprContainsLiteral(actual, filter.value); + } else if (filter.op == TokenId::NOT_EQUAL) { + matches = !exprContainsLiteral(actual, filter.value); + } else { + matches = compareResolved(actual, filter.op, filter.value); + } + if (!matches) break; + } + if (!matches) continue; + ++factCandidates_; + rows.push_back(fact); + } + }; + appendMatches(memory_.currentFactIndexes(indexes, lazy->snapshotGeneration), false); + if (rows.empty()) { + appendMatches(memory_.relevantPastFactIndexes( + lazy->factType.empty() ? "Fact" : lazy->factType, + lazy->factTypeId, + lazy->snapshotGeneration), true); + } + return std::make_shared(std::move(rows)); + } + const auto kind = std::dynamic_pointer_cast( + findMapValue(selection, internalSymbolString(InternalSymbolKind::Type))); + const auto selectedType = std::dynamic_pointer_cast(findMapValue(selection, "fact_type")); + if (!kind || kind->value != "FactSelection" || !selectedType) { + throw InterpreterError("Expected a FactSelection"); + } + std::uint64_t snapshotGeneration = 0; + if (const auto snapshot = std::dynamic_pointer_cast( + findMapValue(selection, "snapshot_generation"))) { + if (snapshot->value < 0 || std::floor(snapshot->value) != snapshot->value) { + throw InterpreterError("FactSelection has an invalid snapshot generation"); + } + snapshotGeneration = static_cast(snapshot->value); + } + std::string field; + std::shared_ptr equals; + if (const auto fieldValue = std::dynamic_pointer_cast(findMapValue(selection, "field"))) { + field = fieldValue->value; + equals = findMapValue(selection, "equals"); + } + const auto indexes = memory_.selectionIndexes( + selectedType->value, + field, + equals && isGroundLiteral(equals) ? equals : nullptr, + snapshotGeneration); + std::vector> rows; + rows.reserve(indexes.size()); + for (const auto index : indexes) { + const auto fact = memory_.factValue(index, snapshotGeneration); + if (!fact) continue; + if (!field.empty()) { + const auto actual = findMapValue(fact, field); + if (!actual || !equals || !exprContainsLiteral(actual, equals)) continue; + } + ++factCandidates_; + rows.push_back(fact); + } + return std::make_shared(std::move(rows)); +} + +std::size_t Interpreter::syncFactSource(const std::filesystem::path& file) { + const fs::path normalized = fs::absolute(file).lexically_normal(); + if (!fs::exists(normalized) || !fs::is_regular_file(normalized)) { + throw InterpreterError("db.sync cannot read fact source: " + normalized.string()); + } + + // Sync is intentionally restricted to fact-only files. Reloading method + // declarations or globals could duplicate executable definitions and + // violate ordered immediate execution semantics. + struct StagedFact { + std::string type; + std::string parentType; + std::shared_ptr value; + std::shared_ptr temporalMetadata; + std::vector parentFactIds; + std::vector designationIds; + }; + std::vector staged; + parseProgramFileChunks(normalized, [&](Program&& program) { + for (const auto& statement : program.statements) { + if (statement->kind() != StatementKind::Clause || + !std::static_pointer_cast(statement)->isFact()) { + throw InterpreterError("db.sync accepts fact-only .fx sources: " + normalized.string()); + } + const auto clause = std::static_pointer_cast(statement); + auto materialized = factToMap(*clause); + staged.push_back(StagedFact{ + clause->head.name, + clause->parentName, + std::move(materialized.value), + std::move(materialized.temporalMetadata), + std::move(materialized.parentFactIds), + clause->designationIds}); + } + }); + + // Match staged rows before mutation without inferring an application + // schema. An unchanged source fact has a structural source identity. A + // changed fact that lacks a runtime FactId is intentionally modelled as a + // delete plus insert: guessing identity from names such as "id" or + // "orderId" corrupts arbitrary user schemas. + struct ExistingFact { + std::uint64_t id = 0; + std::uint64_t rowVersion = 1; + }; + std::unordered_map> existingByValue; + const auto structuralSourceKey = [](const std::string& type, + const std::shared_ptr& value) { + return type + "\x1f" + (value ? value->debug() : std::string{}); + }; + for (const size_t index : memory_.factIndexesFromOrigin(normalized)) { + const auto& fact = memory_.fact(index); + if (!fact.active) continue; + const auto value = memory_.factValue(index); + if (!value) continue; + ExistingFact existing{fact.id, fact.rowVersion}; + existingByValue[structuralSourceKey(fact.type, value)].push_back(existing); + } + std::unordered_set reusedIds; + + // Validate the complete replacement before publishing. FactMemory itself + // is copy-on-write, so rollback restores the previous generation without + // rebuilding unrelated relations. + FactMemory previousMemory = memory_; + try { + beginCacheInvalidationBatch(); + memory_.removeOrigin(normalized); + for (const auto& row : staged) { + std::optional existing; + const auto found = existingByValue.find(structuralSourceKey(row.type, row.value)); + if (found != existingByValue.end()) { + for (const auto& candidate : found->second) { + if (!reusedIds.count(candidate.id)) { + existing = candidate; + break; + } + } + } + if (existing && !reusedIds.insert(existing->id).second) { + throw InterpreterError("db.sync source identity resolves to the same fact more than once"); + } + memory_.addFact( + row.type, + row.parentType, + row.value, + normalized, + existing ? std::optional(existing->id) : std::nullopt, + existing ? existing->rowVersion + 1 : 1, + std::move(row.parentFactIds), + std::move(row.designationIds), + std::move(row.temporalMetadata)); + if (!row.parentType.empty()) { + memory_.setParent(row.type, row.parentType, normalized); + } + } + endCacheInvalidationBatch(); + } catch (...) { + memory_ = std::move(previousMemory); + clearCachesNow(); + endCacheInvalidationBatch(); + throw; + } + return memory_.factIndexesFromOrigin(normalized).size(); +} + +std::string Interpreter::runtimeMetricsJson() const { + const FactMemoryStats factStats = memory_.stats(); + std::ostringstream out; + out << "{" + << "\"clauseAttempts\":" << clauseAttempts_ << "," + << "\"unificationAttempts\":" << unificationAttempts_ << "," + << "\"factCandidates\":" << factCandidates_ << "," + << "\"relationshipCandidates\":" << relationshipCandidates_ << "," + << "\"relationshipCandidatesPruned\":" << relationshipCandidatesPruned_ << "," + << "\"solutionMaterializations\":" << solutionMaterializations_ << "," + << "\"environmentFramesCreated\":" << envFramePool_.created() << "," + << "\"environmentCopies\":" << environmentCopies_ << "," + << "\"environmentFramesCached\":" << envFramePool_.cached() << "," + << "\"standardizedClauses\":" << standardizedClauses_ << "," + << "\"moduleLoads\":" << moduleLoads_ << "," + << "\"nativeCalls\":" << nativeCalls_ << "," + << "\"nativeFactProjectionCalls\":" << nativeFactProjectionCalls_ << "," + << "\"nativeRequestBytes\":" << nativeRequestBytes_ << "," + << "\"nativeFactProjectionBytes\":" << nativeFactProjectionBytes_ << "," + << "\"nativeSerializationMicros\":" << nativeSerializationMicros_ << "," + << "\"streamedModuleMicros\":" << streamedModuleMicros_ << "," + << "\"parserTokensLexed\":" << parserMetrics_.tokensLexed << "," + << "\"parserIterations\":" << parserMetrics_.iterations << "," + << "\"parserPeakRecursionDepth\":" << parserMetrics_.peakRecursionDepth << "," + << "\"parserBacktrackingAttempts\":" << parserMetrics_.backtrackingAttempts << "," + << "\"parserOperatorCandidateLookups\":" << parserMetrics_.operatorCandidateLookups << "," + << "\"parserOperatorCandidatesScored\":" << parserMetrics_.operatorCandidatesScored << "," + << "\"factRegistrationMicros\":" << factRegistrationMicros_ << "," + << "\"dispatchCacheHits\":" << dispatchCacheHits_ << "," + << "\"dispatchCacheMisses\":" << dispatchCacheMisses_ << "," + << "\"tableCacheHits\":" << tableCacheHits_ << "," + << "\"tableCacheMisses\":" << tableCacheMisses_ << "," + << "\"tableRounds\":" << tableRounds_ << "," + << "\"tableDeltaAnswers\":" << tableDeltaAnswers_ << "," + << "\"provenanceNodes\":" << provenanceNodes_ << "," + << "\"factStoreGeneration\":" << factStats.generation << "," + << "\"activeFacts\":" << factStats.activeFacts << "," + << "\"tombstonedFacts\":" << factStats.tombstonedFacts << "," + << "\"factRowVersions\":" << factStats.rowVersions << "," + << "\"temporalLineages\":" << factStats.temporalLineages << "," + << "\"temporalPastFacts\":" << factStats.temporalPastFacts << "," + << "\"temporalFutureFacts\":" << factStats.temporalFutureFacts << "," + << "\"factRelations\":" << factStats.relations << "," + << "\"relationRows\":" << factStats.relationRows << "," + << "\"relationColumnValues\":" << factStats.relationColumnValues << "," + << "\"internedValues\":" << factStats.internedValues << "," + << "\"adaptiveEqualityIndexes\":" << factStats.adaptiveEqualityIndexes << "," + << "\"adaptiveIndexBuildMicros\":" << factStats.adaptiveIndexBuildMicros << "," + << "\"liveFactSnapshots\":" << factStats.snapshots + << "}"; + return out.str(); +} + +void Interpreter::recordStreamedModuleMicros(std::size_t micros) { + streamedModuleMicros_ += micros; +} + +void Interpreter::recordParserMetrics(const ParserMetrics& metrics) { + parserMetrics_ += metrics; +} + +std::vector Interpreter::expandImportPattern(const std::filesystem::path& baseDir, + const std::string& pattern) const { + std::vector files; + if (isBareModuleImport(pattern)) { + fs::path coreFile = resolveCoreImport(baseDir, pattern); + if (fs::exists(coreFile) && fs::is_regular_file(coreFile)) { + files.push_back(coreFile); + return files; + } + fs::path nativeFile = resolveNativeImport(baseDir, pattern); + if (!nativeFile.empty()) return files; + std::ostringstream message; + message << "Module '" << pattern << "' not found. Looked for " + << coreFile.string() << " or native library files"; + for (const auto& fileName : nativeLibraryFileNames(pattern)) message << " " << fileName; + throw InterpreterError(message.str()); + } + + fs::path raw(pattern); + if (pattern.rfind("system.flibrary.", 0) == 0 && pattern.find('*') == std::string::npos) { + std::string moduleName = pattern.substr(std::string("system.flibrary.").size()); + fs::path coreFile = fs::absolute(sourceRootFromBase(baseDir) / "core" / "system" / "flibrary" / (moduleName + ".fx")).lexically_normal(); + if (fs::exists(coreFile) && fs::is_regular_file(coreFile)) { + files.push_back(coreFile); + return files; + } + } + fs::path target = raw.is_absolute() ? raw : (baseDir / raw); + target = fs::absolute(target).lexically_normal(); + + if (pattern.size() >= 2 && pattern.substr(pattern.size() - 2) == "/*") { + fs::path dir = fs::absolute(baseDir / pattern.substr(0, pattern.size() - 2)).lexically_normal(); + if (!fs::exists(dir) || !fs::is_directory(dir)) { + throw InterpreterError("Import directory not found: " + dir.string()); + } + for (const auto& entry : fs::directory_iterator(dir)) { + if (entry.is_regular_file() && entry.path().extension() == ".fx") { + files.push_back(entry.path()); + } + } + return files; + } + + if (fs::exists(target) && fs::is_directory(target)) { + for (const auto& entry : fs::recursive_directory_iterator(target)) { + if (entry.is_regular_file() && entry.path().extension() == ".fx") { + files.push_back(entry.path()); + } + } + return files; + } + + if (!fs::exists(target)) { + if (!raw.has_parent_path() && raw.extension() == ".fx") { + fs::path coreFile = fs::absolute(sourceRootFromBase(baseDir) / "core" / raw.filename()).lexically_normal(); + if (fs::exists(coreFile) && fs::is_regular_file(coreFile)) { + files.push_back(coreFile); + return files; + } + } + fs::path nativeFile = resolveNativeImport(baseDir, pattern); + if (!nativeFile.empty()) return files; + throw InterpreterError("Import file not found: " + target.string()); + } + if (fs::is_regular_file(target) && hasNativeLibraryExtension(target)) { + return files; + } + files.push_back(target); + return files; +} + +std::filesystem::path Interpreter::resolveNativeImport(const std::filesystem::path& baseDir, + const std::string& pattern) const { + fs::path raw(pattern); + std::vector candidates; + + auto addCandidate = [&](const fs::path& candidate) { + candidates.push_back(fs::absolute(candidate).lexically_normal()); + }; + + if (raw.has_extension() && hasNativeLibraryExtension(raw)) { + addCandidate(raw.is_absolute() ? raw : (baseDir / raw)); + } + + fs::path root = sourceRootFromBase(baseDir); + std::string moduleName = raw.stem().string(); + if (isBareModuleImport(pattern)) { + moduleName = pattern; + } + if (pattern.rfind("system.flibrary.", 0) == 0) { + moduleName = pattern.substr(std::string("system.flibrary.").size()); + } + if (pattern.rfind("system:flibrary:", 0) == 0) { + size_t moduleStart = std::string("system:flibrary:").size(); + size_t moduleEnd = pattern.find(':', moduleStart); + moduleName = pattern.substr(moduleStart, moduleEnd == std::string::npos ? std::string::npos : moduleEnd - moduleStart); + } + if (!moduleName.empty() && moduleName.find('*') == std::string::npos) { +#if defined(NDEBUG) + constexpr const char* nativeConfiguration = "Release"; +#else + constexpr const char* nativeConfiguration = "Debug"; +#endif + for (const auto& fileName : nativeLibraryFileNames(moduleName)) { + addCandidate(baseDir / fileName); + addCandidate( + baseDir / "native_modules" / moduleName / + nativeConfiguration / fileName); + addCandidate(baseDir / "native_modules" / moduleName / fileName); + addCandidate( + root / "native_modules" / moduleName / + nativeConfiguration / fileName); + addCandidate(root / "native_modules" / moduleName / fileName); + addCandidate(root / "modules" / moduleName / fileName); + } + } + + for (const auto& candidate : candidates) { + if (fs::exists(candidate) && fs::is_regular_file(candidate)) return candidate; + } + + return {}; +} + +} // namespace Felidae diff --git a/src/Interpreter.h b/src/Interpreter.h new file mode 100644 index 0000000..be91954 --- /dev/null +++ b/src/Interpreter.h @@ -0,0 +1,478 @@ +#pragma once + +#include "AST.h" +#include "Env.h" +#include "Memory.h" +#include "NativeRuntime.h" +#include "ParserMetrics.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +class InterpreterError : public std::runtime_error { +public: + explicit InterpreterError(const std::string& msg) : std::runtime_error(msg) {} +}; + +class Interpreter { +public: + using ClauseList = std::vector>; + + ~Interpreter(); + + void addProgram(const Program& program); + // Fast registration boundary for a parser that emits one statement at a + // time. Facts do not need a transient Program/AST container; rules and + // globals still use addProgram so complete validation remains identical. + void addStreamedStatement(std::shared_ptr statement); + void addClause(std::shared_ptr clause); + void addImport(const std::filesystem::path& baseDir, const std::string& pattern); + // Streaming module publication is transactional: callers may register + // statements one at a time and either publish the complete module or + // restore the previous immutable roots without retaining a module AST. + void beginModuleTransaction(); + void commitModuleTransaction(); + void rollbackModuleTransaction(); + + std::vector solve(const std::vector>& queryGoals, + size_t maxSolutions = 1000); + + std::shared_ptr resolveExpr(const std::shared_ptr& expr, const Env& env) const; + std::string exprToString(const std::shared_ptr& expr, const Env& env) const; + bool hasMethod(const std::string& name); + bool hasAutoEntryCall() const; + bool hasGlobal(const std::string& name) const; + std::shared_ptr evaluateGlobal(const std::string& name) const; + std::shared_ptr evaluateExpressionText(const std::string& text); + std::shared_ptr callMain(const std::shared_ptr& systemInput); + std::shared_ptr callAutoEntry(); + std::string valueToString(const std::shared_ptr& value) const; + std::string valueToDisplayString(const std::shared_ptr& value) const; + std::string runtimeMetricsJson() const; + void recordStreamedModuleMicros(std::size_t micros); + void recordParserMetrics(const ParserMetrics& metrics); + std::size_t syncFactSource(const std::filesystem::path& file); + std::shared_ptr operatorRegistry() const { return operators_; } + +private: + struct ThreadTask { + explicit ThreadTask(std::string functionName) : functionName(std::move(functionName)) {} + std::string functionName; + std::thread worker; + std::string status = "created"; + std::string result; + std::string error; + bool started = false; + }; + struct MethodParamPlan { + std::string localName; + std::string typeName; + LanguageTypeId typeId = LanguageTypeId::Unknown; + bool typedParam = false; + bool builtinType = false; + }; + struct MethodRuntimeInfo { + size_t callCount = 0; + bool paramsPrepared = false; + bool cacheEligible = false; + std::vector params; + }; + struct SolveCacheEntry { + std::vector solutions; + std::list::iterator recency; + std::size_t estimatedBytes = 0; + }; + struct ComparisonDispatchKey { + SymbolId sourceTypeId = 0; + SymbolId targetTypeId = 0; + std::string sourceType; + std::string targetType; + + bool operator==(const ComparisonDispatchKey& other) const { + return sourceTypeId == other.sourceTypeId && targetTypeId == other.targetTypeId && + sourceType == other.sourceType && targetType == other.targetType; + } + }; + struct ComparisonDispatchKeyHash { + std::size_t operator()(const ComparisonDispatchKey& key) const { + std::size_t seed = std::hash{}(key.sourceTypeId); + seed ^= std::hash{}(key.targetTypeId) + 0x9e3779b9U + + (seed << 6U) + (seed >> 2U); + seed ^= std::hash{}(key.sourceType) + 0x9e3779b9U + + (seed << 6U) + (seed >> 2U); + return seed ^ (std::hash{}(key.targetType) + 0x9e3779b9U + + (seed << 6U) + (seed >> 2U)); + } + }; + struct ComparisonDispatchPlan { + std::shared_ptr membershipClause; + std::shared_ptr comparisonClause; + std::string membershipName; + std::string comparisonName; + std::string targetFamily; + }; + struct ReferenceAttachment { + std::uint64_t id = 0; + std::uint64_t sourceFactId = 0; + std::string callableName; + std::shared_ptr callable; + std::shared_ptr defaultFactor; + std::shared_ptr descriptor; + std::size_t creationOrder = 0; + std::shared_ptr canonicalResult; + std::uint64_t canonicalGeneration = 0; + bool dirty = true; + }; + struct ClauseBucket { + std::string name; + ClauseList clauses; + }; + using ClauseTable = std::unordered_map>; + + struct ProvenanceNode { + enum class Kind { Fact, Rule }; + Kind kind = Kind::Fact; + std::uint64_t factId = 0; + std::string rule; + SourceSpan span; + std::vector parents; + }; + struct TableAnswer { + Call call; + std::vector provenance; + }; + struct PredicateTable { + std::string name; + SymbolId nameId = 0; + std::vector answers; + std::vector delta; + std::unordered_map answerByKey; + }; + struct TableEvaluation { + SymbolId rootId = 0; + std::string rootName; + std::uint64_t hierarchyGeneration = 0; + std::unordered_map callableGenerations; + std::unordered_map relationGenerations; + std::unordered_map predicates; + std::vector provenance; + std::size_t rounds = 0; + std::size_t deltaAnswers = 0; + }; + struct TableBinding { + Env env; + std::vector provenance; + }; + + struct ModuleTransactionState { + std::shared_ptr clauses; + std::shared_ptr operators; + std::unordered_map>> operatorClauses; + std::vector autoEntryCalls; + std::vector> autoEntryResults; + FactMemory memory; + GlobalEnv globals; + std::unordered_map> referencesBySource; + std::uint64_t nextReferenceAttachmentId = 1; + std::size_t nextReferenceCreationOrder = 0; + std::uint64_t referenceEvaluationGeneration = 0; + std::set loadedFiles; + std::unordered_set packageDiscoveryAttempts; + std::unordered_map clauseOrigins; + std::uint64_t programGeneration = 1; + std::unordered_map symbolGenerations; + std::size_t moduleLoads = 0; + std::size_t cacheInvalidationDepth = 0; + bool pendingCacheInvalidation = false; + std::unordered_map contraries; + }; + + std::shared_ptr clauses_ = std::make_shared(); + std::shared_ptr operators_ = std::make_shared(); + std::unordered_map>> operatorClauses_; + std::unique_ptr moduleTransaction_; + std::vector autoEntryCalls_; + std::vector> autoEntryResults_; + FactMemory memory_; + GlobalEnv globals_; + std::unordered_map solveCache_; + std::list solveCacheRecency_; + std::size_t solveCacheBytes_ = 0; + mutable std::unordered_map methodRuntimeCache_; + mutable std::unordered_map clauseLookupCache_; + mutable std::unordered_map> typeAncestryCache_; + mutable std::unordered_map> typeAncestorDistanceCache_; + mutable std::unordered_map typeHierarchyDepthCache_; + // These closures are valid only for one immutable hierarchy generation. + // Fact mutations retain query indexes, but hierarchy changes must never + // let a previous ancestry answer leak into a later analysis. + mutable std::uint64_t ancestryCacheGeneration_ = 0; + std::unordered_map comparisonDispatchCache_; + std::unordered_map> referencesBySource_; + std::uint64_t nextReferenceAttachmentId_ = 1; + std::size_t nextReferenceCreationOrder_ = 0; + std::uint64_t referenceEvaluationGeneration_ = 0; + std::unordered_set activeReferenceEvaluations_; + std::unordered_set activeNegatedPredicates_; + std::unordered_map contraries_; + std::unordered_map> tableCache_; + std::set loadedFiles_; + std::unordered_set packageDiscoveryAttempts_; + std::unordered_map clauseOrigins_; + std::filesystem::path currentLoadingFile_; + std::vector nativeLibraries_; + std::unordered_map nativeLibraryByModule_; + std::set nativeLibraryPaths_; + std::unordered_map> threadTasks_; + mutable std::mutex threadMutex_; + EnvFramePool envFramePool_; + BindingTrail* activeBindingTrail_ = nullptr; + size_t solveEpoch_ = 0; + std::uint64_t programGeneration_ = 1; + std::unordered_map symbolGenerations_; + size_t threadCounter_ = 0; + size_t cacheInvalidationDepth_ = 0; + bool pendingCacheInvalidation_ = false; + bool strictValueFailures_ = false; + bool valueCallMode_ = false; + size_t valueCallTrampolineDepth_ = 0; + size_t methodCallDepth_ = 0; + std::unordered_set activeComparisons_; + std::vector> pipelineResults_; + std::size_t clauseAttempts_ = 0; + std::size_t unificationAttempts_ = 0; + std::size_t factCandidates_ = 0; + std::size_t relationshipCandidates_ = 0; + std::size_t relationshipCandidatesPruned_ = 0; + std::size_t solutionMaterializations_ = 0; + std::size_t environmentCopies_ = 0; + std::size_t standardizedClauses_ = 0; + std::unordered_map clauseRenameRequirements_; + std::size_t moduleLoads_ = 0; + std::size_t nativeCalls_ = 0; + std::size_t nativeFactProjectionCalls_ = 0; + std::size_t nativeRequestBytes_ = 0; + std::size_t nativeFactProjectionBytes_ = 0; + std::size_t nativeSerializationMicros_ = 0; + std::size_t streamedModuleMicros_ = 0; + ParserMetrics parserMetrics_; + std::size_t factRegistrationMicros_ = 0; + mutable std::size_t dispatchCacheHits_ = 0; + mutable std::size_t dispatchCacheMisses_ = 0; + std::size_t tableCacheHits_ = 0; + std::size_t tableCacheMisses_ = 0; + std::size_t tableRounds_ = 0; + std::size_t tableDeltaAnswers_ = 0; + std::size_t provenanceNodes_ = 0; + + void solveRecursive(const std::vector>& goals, + Env env, + std::vector& out, + size_t maxSolutions, + size_t depth); + void solveIterative(const std::vector>& goals, + Env env, + std::vector& out, + size_t maxSolutions, + size_t depth); + bool solveAssignGoal(const AssignGoal& goal, Env& env); + bool solveMultiAssignGoal(const MultiAssignGoal& goal, Env& env); + bool solveBinaryGoal(const BinaryGoal& goal, Env& env); + bool solveWhereGoal(const WhereGoal& goal, Env& env); + bool solveReturnGoal(const ReturnGoal& goal, Env& env); + bool solveNotGoal(const NotGoal& goal, Env& env, size_t depth); + bool bodyHasReturnGoal(const std::vector>& goals) const; + bool evaluateGoalTruth(const std::shared_ptr& goal, Env& env); + std::shared_ptr evaluateGoalTruthTuple(const std::vector>& goals, Env env); + std::shared_ptr executeGoalTruthTuple(const std::vector>& goals, Env env, Env& outEnv); + bool solveMethodCall(const Call& call, + const std::shared_ptr& clause, + Env env, + std::vector& out, + size_t maxSolutions, + size_t depth); + bool solveBuiltin(const Call& call, Env& env); + bool solveNativeCall(const Call& call, Env& env); + bool evalBuiltinTerm(const TermExpr& term, const Env& env, std::shared_ptr& out); + bool evalAncestorAnalysis(const Call& call, const Env& env, std::shared_ptr& out); + bool evalFactPropagation(const Call& call, const Env& env, std::shared_ptr& out); + bool evalRelationCompare(const Call& call, const Env& env, std::shared_ptr& out); + bool evalRelationFind(const Call& call, const Env& env, std::shared_ptr& out); + bool evalDependencySatisfied(const Call& call, const Env& env, std::shared_ptr& out); + bool evalFactReferences(const Call& call, const Env& env, std::shared_ptr& out); + bool evalReasoningBuiltin(const TermExpr& term, + const Env& env, + std::shared_ptr& out); + bool evalReasoningContrary(const TermExpr& term, + const Env& env, + std::shared_ptr& out); + bool evalReasoningProve(const TermExpr& term, + const Env& env, + std::shared_ptr& out); + bool evalReasoningGrade(const TermExpr& term, + const Env& env, + std::shared_ptr& out, + const std::shared_ptr& exact = {}); + bool solveFactAttachment(const Call& call, Env& env); + bool attachFactReference(const Call& call, Env& env, std::uint64_t sourceFactId); + std::shared_ptr resolveReferenceCallable(const std::shared_ptr& callable, + const std::shared_ptr& source, + const std::shared_ptr& factor, + std::string& normalizedName); + bool validateReferenceResult(const std::shared_ptr& value, + std::shared_ptr& result) const; + bool isReferenceMethodPure(const std::shared_ptr& clause, + std::unordered_set& visiting, + std::string& reason) const; + bool referenceValueMatchesType(const std::shared_ptr& value, + const MethodParamPlan& parameter) const; + std::shared_ptr referenceEffectiveFactor(const ReferenceAttachment& attachment) const; + bool invokeComparisonMethod(const std::shared_ptr& clause, + const Call& call, + const Env& env, + std::shared_ptr& out); + bool evalCallAsValue(const TermExpr& term, const Env& env, std::shared_ptr& out); + bool evalCallAsValueOnce(const TermExpr& term, const Env& env, std::shared_ptr& out); + bool evalOperatorExpr(const OperatorExpression& expression, + const Env& env, + std::shared_ptr& out); + bool evalCustomOperatorExpr(const OperatorExpression& expression, + const Env& env, + std::shared_ptr& out, + bool* matched = nullptr); + bool evalExprValue(const std::shared_ptr& expr, const Env& env, std::shared_ptr& out); + std::shared_ptr executeEntryCall(const Call& entryCall); + bool compareResolved(const std::shared_ptr& left, + TokenId::Id op, + const std::shared_ptr& right) const; + + bool unifyCall(const Call& goal, const Call& head, Env& env); + std::vector unifyCallAlternatives(const Call& goal, const Call& head, const Env& env); + bool unifyExpr(const std::shared_ptr& a, + const std::shared_ptr& b, + Env& env); + + const Arg* findArg(const Call& call, const Arg& wanted, size_t index) const; + const Arg* findArgByNameOrIndex(const Call& call, const std::string& name, size_t index) const; + ClauseList* findClauses(const std::string& name, SymbolId nameId); + const ClauseList* findClauses(const std::string& name, SymbolId nameId) const; + ClauseList& getOrCreateClauseList(const std::string& name, SymbolId nameId); + void removeClauseBucket(const std::string& name, SymbolId nameId); + void ensureClauseTableUnique(); + std::string solveCacheKey(const std::vector>& goals, size_t maxSolutions) const; + std::size_t estimateCachedSolutionsBytes(const std::string& key, + const std::vector& solutions) const; + void storeCachedSolutions(const std::string& key, const std::vector& solutions); + void invalidateCaches(); + void beginCacheInvalidationBatch(); + void endCacheInvalidationBatch(); + void clearCachesNow(); + + void validateNegationStratification(const Program& program) const; + bool isTableEligiblePredicate(const std::string& name, + SymbolId nameId, + std::unordered_set& visiting, + std::unordered_set& checked, + bool& recursive) const; + bool isTableEligibleGoal(const std::shared_ptr& goal, + SymbolId root, + std::unordered_set& visiting, + std::unordered_set& checked, + bool& recursive) const; + std::shared_ptr tableEvaluationFor( + const std::string& name, + SymbolId nameId, + bool requireRecursive); + std::shared_ptr buildTableEvaluation( + const std::string& name, + SymbolId nameId); + bool tableEvaluationValid(const TableEvaluation& evaluation) const; + bool tableCallAnswers(const Call& call, + const Env& env, + std::vector& bindings, + std::shared_ptr* evaluation = nullptr, + bool requireRecursive = true); + std::vector evaluateTableGoals( + const std::vector>& goals, + std::vector inputs, + const TableEvaluation& evaluation, + std::optional> deltaPivot); + std::shared_ptr materializeDerivationResult( + const Call& query, + const std::vector& supporting, + const std::vector& opposing, + const std::shared_ptr& positiveEvaluation, + const std::shared_ptr& negativeEvaluation) const; + + std::shared_ptr standardizeApart(const std::shared_ptr& clause); + Env copyExecutionEnvironment(const Env& source); + bool exprNeedsRename(const std::shared_ptr& expr) const; + using RenameMap = std::unordered_map; + SymbolId renamedId(SymbolId original, RenameMap& names); + Call renameCall(const Call& call, RenameMap& names); + std::shared_ptr renameGoal(const std::shared_ptr& goal, RenameMap& names); + std::shared_ptr renameExpr(const std::shared_ptr& expr, RenameMap& names); + + bool isSameVariable(const std::shared_ptr& a, const std::shared_ptr& b) const; + bool isGroundLiteral(const std::shared_ptr& expr) const; + bool isCacheableQuery(const std::vector>& goals) const; + bool goalMayHaveSideEffects(const std::shared_ptr& goal) const; + bool exprMayHaveSideEffects(const std::shared_ptr& expr) const; + bool isMethodClause(const ClauseStmt& clause) const; + bool methodMetadataCacheEligible(const ClauseStmt& clause) const; + MethodParamPlan makeMethodParamPlan(const Arg& param) const; + std::vector buildMethodParamPlan(const ClauseStmt& clause) const; + const std::vector* hotMethodParamPlan(const std::shared_ptr& clause); + struct FactMaterialization { + std::shared_ptr value; + // Interpreter metadata is carried alongside a fact, never as part of + // its public property map. + std::shared_ptr temporalMetadata; + std::vector parentFactIds; + }; + FactMaterialization factToMap(const ClauseStmt& clause); + std::shared_ptr materializeFactSelection(const std::shared_ptr& selection); + void refreshAncestryCaches() const; + const std::vector& typeAncestry(const std::string& type) const; + const std::unordered_map& typeAncestorDistances( + const std::string& type) const; + double typeHierarchyDepth(const std::string& type) const; + std::vector> valuesForLambdaSource(const std::shared_ptr& source, const Env& env); + + bool ensurePredicateLoaded(const std::string& predicate); + void loadProgramFile(const std::filesystem::path& file); + void loadNativeLibrary(const std::filesystem::path& file); + void closeNativeLibraries(); + void joinThreads(); + std::shared_ptr makeThreadHandle(const std::string& id) const; + std::shared_ptr threadTaskFromHandle(const std::shared_ptr& handle); + std::string createThreadTask(const std::string& functionName); + std::string startThreadTask(const std::shared_ptr& handle); + std::string threadTaskStatus(const std::shared_ptr& handle); + std::shared_ptr threadTaskResult(const std::shared_ptr& handle); + void collectExecutionGarbage(); + const ClauseStmt* nativeDeclarationFor(const std::string& name) const; + void validateNativeCallTypes(const Call& call, + const ClauseStmt& declaration, + const Env& env, + bool requireDeclaredInputs = false); + std::vector expandImportPattern(const std::filesystem::path& baseDir, + const std::string& pattern) const; + std::filesystem::path resolveNativeImport(const std::filesystem::path& baseDir, + const std::string& pattern) const; +}; + +} // namespace Felidae diff --git a/src/Memory.cpp b/src/Memory.cpp new file mode 100644 index 0000000..3d99d55 --- /dev/null +++ b/src/Memory.cpp @@ -0,0 +1,1754 @@ +#include "Memory.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +FactMemory::FactMemory() : data_(std::make_shared()) {} + +FactMemory::FactMemory(const FactMemory& other) + : data_(other.data_), + snapshots_{}, + compatibleFactCache_{}, + propertyQueryCache_{}, + adaptiveEqualityIndexes_(0), + adaptiveIndexBuildMicros_(0) {} + +FactMemory& FactMemory::operator=(const FactMemory& other) { + if (this != &other) { + data_ = other.data_; + snapshots_.clear(); + invalidateCaches(); + adaptiveEqualityIndexes_ = 0; + adaptiveIndexBuildMicros_ = 0; + } + return *this; +} + +const FactRecord& FactMemory::FactRows::at(std::size_t index) const { + if (index >= count) throw std::out_of_range("Fact row index out of range"); + const std::size_t batchIndex = index / BatchSize; + const std::size_t offset = index % BatchSize; + return batches.at(batchIndex)->at(offset); +} + +FactRecord& FactMemory::FactRows::mutableAt(std::size_t index) { + if (index >= count) throw std::out_of_range("Fact row index out of range"); + const std::size_t batchIndex = index / BatchSize; + const std::size_t offset = index % BatchSize; + auto& batch = batches.at(batchIndex); + if (batch.use_count() != 1) batch = std::make_shared>(*batch); + return batch->at(offset); +} + +FactRecord& FactMemory::FactRows::append(FactRecord record) { + const std::size_t batchIndex = count / BatchSize; + if (batchIndex == batches.size()) { + batches.push_back(std::make_shared>()); + } else if (batches[batchIndex].use_count() != 1) { + batches[batchIndex] = std::make_shared>(*batches[batchIndex]); + } + auto& batch = *batches[batchIndex]; + batch.push_back(std::move(record)); + ++count; + return batch.back(); +} + +std::optional FactMemory::FactIdDirectory::find(std::uint64_t id) const { + if (id == 0) return std::nullopt; + const std::size_t pageIndex = static_cast((id - 1) / PageSize); + const std::size_t offset = static_cast((id - 1) % PageSize); + if (pageIndex >= pages.size() || !pages[pageIndex]) return std::nullopt; + const std::size_t row = pages[pageIndex]->at(offset); + return row == Missing ? std::nullopt : std::optional(row); +} + +void FactMemory::FactIdDirectory::assign(std::uint64_t id, std::size_t row) { + if (id == 0) throw std::invalid_argument("FactId must be non-zero"); + const std::size_t pageIndex = static_cast((id - 1) / PageSize); + const std::size_t offset = static_cast((id - 1) % PageSize); + if (pageIndex >= pages.size()) pages.resize(pageIndex + 1); + auto& page = pages[pageIndex]; + if (!page) { + page = std::make_shared>(PageSize, Missing); + } else if (page.use_count() != 1) { + page = std::make_shared>(*page); + } + page->at(offset) = row; +} + +const FactRecord& FactMemory::fact(size_t index) const { + return data_->facts.at(index); +} + +std::shared_ptr FactMemory::materializeFact( + const Data& store, + std::size_t index) const { + const auto& record = store.facts.at(index); + const auto relation = store.relations.find(record.typeId); + if (relation == store.relations.end() || !relation->second) return {}; + const auto& root = *relation->second; + if (record.relationOrdinal >= root.fieldOrderOffsets.size() || + record.relationOrdinal >= root.fieldOrderCounts.size()) return {}; + + std::vector entries; + entries.emplace_back( + internalSymbolString(InternalSymbolKind::Type), + std::make_shared(record.type)); + if (!record.parentType.empty()) { + entries.emplace_back( + internalSymbolString(InternalSymbolKind::Parent), + std::make_shared(record.parentType)); + } + + const std::size_t offset = root.fieldOrderOffsets[record.relationOrdinal]; + const std::size_t count = root.fieldOrderCounts[record.relationOrdinal]; + std::unordered_map consumed; + entries.reserve(entries.size() + count); + for (std::size_t position = 0; position < count; ++position) { + const std::size_t orderIndex = offset + position; + const SymbolId fieldId = root.fieldOrder[orderIndex]; + const auto name = root.fieldNames.find(fieldId); + const auto column = root.columns.find(fieldId); + if (name == root.fieldNames.end() || column == root.columns.end()) continue; + const std::size_t first = consumed[fieldId]; + const std::size_t valueCount = + orderIndex < root.fieldValueCounts.size() + ? root.fieldValueCounts[orderIndex] : 1; + std::vector> values; + values.reserve(valueCount); + std::size_t current = 0; + column->second.forRow(index, [&](const std::shared_ptr& value) { + if (current >= first && current < first + valueCount && value) { + values.push_back(std::const_pointer_cast(value)->clone()); + } + ++current; + }); + consumed[fieldId] += valueCount; + const bool wasArray = + orderIndex < root.fieldArrayFlags.size() && + root.fieldArrayFlags[orderIndex] != 0; + if (wasArray) { + entries.emplace_back(name->second, std::make_shared(std::move(values))); + } else if (!values.empty()) { + entries.emplace_back(name->second, std::move(values.front())); + } + } + + // Inherited values are a resolved view, never duplicated into the child + // relation. The first active row of each declared parent remains the + // language's type-default fact, matching the prior constructor behavior. + std::vector parentTypes; + const auto primaryParent = store.parentOf.find(record.type); + if (primaryParent != store.parentOf.end()) { + parentTypes.push_back(primaryParent->second); + } else if (!record.parentType.empty()) { + parentTypes.push_back(record.parentType); + } + const auto additionalParents = + store.additionalParentsOf.find(record.type); + if (additionalParents != store.additionalParentsOf.end()) { + parentTypes.insert( + parentTypes.end(), + additionalParents->second.begin(), + additionalParents->second.end()); + } + for (std::size_t parentIndex = 0; parentIndex < parentTypes.size(); ++parentIndex) { + const auto& parentType = parentTypes[parentIndex]; + const SymbolId parentId = symbolIdForName(parentType); + const auto parentRelation = store.relations.find(parentId); + if (parentRelation == store.relations.end() || + !parentRelation->second) continue; + std::optional explicitParentRow; + if (parentIndex < record.parentFactIds.size()) { + const auto parentIdRow = store.factIndexById.find(record.parentFactIds[parentIndex]); + if (parentIdRow && *parentIdRow < store.facts.size() && + store.facts.at(*parentIdRow).active && + store.facts.at(*parentIdRow).type == parentType) { + explicitParentRow = *parentIdRow; + } + } + const auto parentRow = explicitParentRow ? + parentRelation->second->rows.end() : std::find_if( + parentRelation->second->rows.begin(), + parentRelation->second->rows.end(), + [&](const std::size_t candidate) { + return candidate < store.facts.size() && + store.facts.at(candidate).active && + store.facts.at(candidate).type == parentType; + }); + if (!explicitParentRow && parentRow == parentRelation->second->rows.end()) continue; + const auto parent = materializeFact(store, + explicitParentRow ? *explicitParentRow : *parentRow); + if (!parent) continue; + for (const auto& inherited : parent->entries) { + if (inherited.keyId == InternalSymbol::TypeId || + inherited.keyId == InternalSymbol::ParentId) continue; + const auto existing = std::find_if( + entries.begin(), entries.end(), + [&](const MapEntry& entry) { + return entry.keyId == inherited.keyId && + entry.key == inherited.key; + }); + if (existing == entries.end()) { + entries.emplace_back( + inherited.key, inherited.value->clone()); + } + } + } + auto result = std::make_shared(std::move(entries)); + result->factIdentity = record.id; + result->factType = record.type; + return result; +} + +std::shared_ptr FactMemory::factValue( + size_t index, + std::uint64_t snapshotGeneration) const { + return materializeFact(dataForSnapshot(snapshotGeneration), index); +} + +std::vector FactMemory::factArguments(size_t index) const { + const auto& record = data_->facts.at(index); + if (!record.parentType.empty() || + data_->parentOf.count(record.type) != 0 || + data_->additionalParentsOf.count(record.type) != 0) { + const auto resolved = materializeFact(*data_, index); + std::vector args; + if (!resolved) return args; + for (const auto& entry : resolved->entries) { + if (entry.keyId == InternalSymbol::TypeId || + entry.keyId == InternalSymbol::ParentId) continue; + if (const auto array = + std::dynamic_pointer_cast(entry.value)) { + for (const auto& item : array->items) { + args.emplace_back(entry.key, entry.keyId, item); + } + } else { + args.emplace_back(entry.key, entry.keyId, entry.value); + } + } + return args; + } + const auto relation = data_->relations.find(record.typeId); + if (relation == data_->relations.end() || !relation->second || + record.relationOrdinal >= relation->second->fieldOrderOffsets.size() || + record.relationOrdinal >= relation->second->fieldOrderCounts.size()) return {}; + const std::size_t offset = + relation->second->fieldOrderOffsets[record.relationOrdinal]; + const std::size_t count = + relation->second->fieldOrderCounts[record.relationOrdinal]; + std::vector args; + args.reserve(count); + std::unordered_map consumed; + for (std::size_t position = 0; position < count; ++position) { + const std::size_t orderIndex = offset + position; + const SymbolId fieldId = relation->second->fieldOrder[orderIndex]; + const auto name = relation->second->fieldNames.find(fieldId); + const auto column = relation->second->columns.find(fieldId); + if (name == relation->second->fieldNames.end() || + column == relation->second->columns.end()) continue; + const std::size_t first = consumed[fieldId]; + const std::size_t valueCount = + orderIndex < relation->second->fieldValueCounts.size() + ? relation->second->fieldValueCounts[orderIndex] : 1; + std::size_t current = 0; + column->second.forRow(index, [&](const std::shared_ptr& value) { + if (current >= first && current < first + valueCount && value) { + args.push_back(Arg{name->second, std::const_pointer_cast(value)}); + } + ++current; + }); + consumed[fieldId] += valueCount; + } + return args; +} + +bool FactMemory::isActive(size_t index) const { + return index < data_->facts.size() && data_->facts.at(index).active; +} + +std::vector FactMemory::activeFactIndexes() const { + std::vector indexes; + indexes.reserve(data_->facts.size()); + for (size_t index = 0; index < data_->facts.size(); ++index) { + if (data_->facts.at(index).active) indexes.push_back(index); + } + return indexes; +} + +bool FactMemory::hasActiveRelation(const std::string& type, SymbolId typeId) const { + if (typeId == 0) typeId = symbolIdForName(type); + const auto relation = data_->relations.find(typeId); + if (relation == data_->relations.end() || !relation->second) return false; + return std::any_of(relation->second->rows.begin(), relation->second->rows.end(), + [&](size_t index) { return index < data_->facts.size() && data_->facts.at(index).active; }); +} + +std::uint64_t FactMemory::generation() const { + return data_->generation; +} + +std::uint64_t FactMemory::relationGeneration( + const std::string& type, + SymbolId typeId) const { + if (typeId == 0) typeId = symbolIdForName(type); + const auto relation = data_->relations.find(typeId); + if (relation == data_->relations.end() || !relation->second) return 0; + return relation->second->generation; +} + +std::uint64_t FactMemory::hierarchyGeneration() const { + return data_->hierarchyGeneration; +} + +FactMemoryStats FactMemory::stats() const { + FactMemoryStats result; + result.relations = data_->relations.size(); + result.snapshots = snapshots_.size(); + result.generation = data_->generation; + result.adaptiveEqualityIndexes = adaptiveEqualityIndexes_; + result.adaptiveIndexBuildMicros = adaptiveIndexBuildMicros_; + result.temporalLineages = data_->temporalLineageIndexes.size(); + for (std::size_t index = 0; index < data_->facts.size(); ++index) { + const auto& fact = data_->facts.at(index); + ++result.rowVersions; + if (fact.active) ++result.activeFacts; + else ++result.tombstonedFacts; + const auto state = temporalStateInData(*data_, index, static_cast(std::time(nullptr))); + if (state == TemporalState::Past) ++result.temporalPastFacts; + else if (state == TemporalState::Future) ++result.temporalFutureFacts; + } + for (const auto& entry : data_->relations) { + if (!entry.second) continue; + result.relationRows += entry.second->rows.size(); + for (const auto& column : entry.second->columns) { + result.relationColumnValues += column.second.values.size(); + } + } + if (data_->valueArena) { + result.internedValues = data_->valueArena->valueCount; + } + return result; +} + +std::uint64_t FactMemory::captureSnapshot() { + const std::uint64_t snapshot = data_->generation; + snapshots_[snapshot] = data_; + return snapshot; +} + +bool FactMemory::releaseSnapshot(std::uint64_t snapshotGeneration) { + if (snapshotGeneration == 0) return false; + const bool released = snapshots_.erase(snapshotGeneration) != 0; + if (released) compactInactiveIfSafe(); + return released; +} + +const FactMemory::Data& FactMemory::dataForSnapshot(std::uint64_t snapshotGeneration) const { + if (snapshotGeneration == 0 || snapshotGeneration == data_->generation) return *data_; + const auto found = snapshots_.find(snapshotGeneration); + if (found == snapshots_.end()) { + throw std::runtime_error("FactSelection snapshot expired; materialize or recreate the selection"); + } + return *found->second; +} + +bool FactMemory::parseTemporalValue(const std::shared_ptr& value, std::int64_t& out) { + if (const auto number = std::dynamic_pointer_cast(value)) { + if (!std::isfinite(number->value) || std::floor(number->value) != number->value) return false; + const auto raw = static_cast(number->value); + // A four-digit numeric value is commonly a calendar year. Larger + // values are already Unix seconds (or milliseconds) and retain their + // original temporal ordering. + if (raw >= 1900 && raw <= 9999) { + const auto daysFromCivil = [](int year, unsigned month, unsigned day) { + year -= month <= 2; + const int era = (year >= 0 ? year : year - 399) / 400; + const unsigned yoe = static_cast(year - era * 400); + const unsigned doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1; + const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return static_cast(era * 146097 + static_cast(doe) - 719468); + }; + out = daysFromCivil(static_cast(raw), 1, 1) * 86400; + } else if (std::llabs(raw) > 100000000000LL) { + out = raw / 1000; + } else { + out = raw; + } + return true; + } + const auto text = std::dynamic_pointer_cast(value); + if (!text || text->value.size() < 10) return false; + const auto parseDigits = [&](size_t offset, size_t count, int& parsed) { + if (offset + count > text->value.size()) return false; + parsed = 0; + for (size_t i = 0; i < count; ++i) { + const unsigned char c = static_cast(text->value[offset + i]); + if (!std::isdigit(c)) return false; + parsed = parsed * 10 + static_cast(c - '0'); + } + return true; + }; + int year = 0; + int monthValue = 0; + int dayValue = 0; + if (text->value[4] != '-' || text->value[7] != '-' || + !parseDigits(0, 4, year) || !parseDigits(5, 2, monthValue) || + !parseDigits(8, 2, dayValue) || year < 1 || monthValue < 1 || + monthValue > 12 || dayValue < 1 || dayValue > 31) { + return false; + } + const auto daysFromCivil = [](int y, unsigned m, unsigned d) { + y -= m <= 2; + const int era = (y >= 0 ? y : y - 399) / 400; + const unsigned yoe = static_cast(y - era * 400); + const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; + const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return static_cast(era * 146097 + static_cast(doe) - 719468); + }; + std::int64_t seconds = daysFromCivil( + year, static_cast(monthValue), static_cast(dayValue)) * 86400; + int hour = 0; + int minute = 0; + int second = 0; + if (text->value.size() >= 19) { + if ((text->value[10] != 'T' && text->value[10] != ' ') || + text->value[13] != ':' || text->value[16] != ':' || + !parseDigits(11, 2, hour) || !parseDigits(14, 2, minute) || + !parseDigits(17, 2, second)) return false; + if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) return false; + seconds += hour * 3600 + minute * 60 + second; + } + out = seconds; + return true; +} + +TemporalOrigin FactMemory::temporalOriginFor(const std::shared_ptr& value) { + if (!value) return TemporalOrigin::Observed; + for (const auto& entry : value->entries) { + if (entry.key != "fx:provenance") { + continue; + } + const auto text = std::dynamic_pointer_cast(entry.value); + if (!text) continue; + std::string origin = text->value; + std::transform(origin.begin(), origin.end(), origin.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + if (origin == "scheduled") return TemporalOrigin::Scheduled; + if (origin == "derived") return TemporalOrigin::Derived; + if (origin == "predicted" || origin == "prediction") return TemporalOrigin::Predicted; + if (origin == "required") return TemporalOrigin::Required; + } + return TemporalOrigin::Observed; +} + +FactTemporalMetadata FactMemory::temporalMetadataFor( + const std::string& type, + std::uint64_t logicalId, + const std::shared_ptr& value, + const std::shared_ptr& temporalMetadata, + std::int64_t registrationTime, + std::uint64_t registrationSequence) { + FactTemporalMetadata metadata; + metadata.registrationTime = registrationTime; + metadata.effectiveTime = registrationTime; + metadata.registrationSequence = registrationSequence; + metadata.origin = temporalOriginFor(temporalMetadata); + std::string lineagePart; + if (logicalId != 0) lineagePart = "fact:" + std::to_string(logicalId); + if (temporalMetadata) { + for (const auto& entry : temporalMetadata->entries) { + if (entry.key == "fx:effective_at" || entry.key == "fx:effective_time" || + entry.key == "fx:timestamp" || entry.key == "fx:time") { + std::int64_t parsed = 0; + if (parseTemporalValue(entry.value, parsed)) { + metadata.effectiveTime = parsed; + metadata.hasExplicitEffectiveTime = true; + break; + } + } + } + } + // Public identity determines lineage. Metadata only controls time and + // provenance, never the fact's semantic identity. + for (const auto& entry : value->entries) { + if (entry.key == "fx:effective_at" || entry.key == "fx:effective_time" || + entry.key == "fx:timestamp" || entry.key == "fx:time") { + continue; + } + if (lineagePart.empty() && + (entry.key == "id" || entry.key == "uuid" || entry.key == "identity" || entry.key == "key")) { + lineagePart = entry.key + ":" + (entry.value ? entry.value->debug() : std::string("nil")); + } + } + if (lineagePart.empty()) lineagePart = "row:" + std::to_string(registrationSequence); + metadata.lineageKey = type + "\x1f" + lineagePart; + return metadata; +} + +TemporalState FactMemory::temporalStateInData(const Data& store, + size_t index, + std::int64_t reasoningTime) const { + if (index >= store.facts.size()) return TemporalState::Past; + if (reasoningTime == 0) reasoningTime = static_cast(std::time(nullptr)); + const auto& record = store.facts.at(index); + if (record.temporal.effectiveTime > reasoningTime) return TemporalState::Future; + const auto lineage = store.temporalLineageIndexes.find(record.temporal.lineageKey); + if (lineage == store.temporalLineageIndexes.end() || !lineage->second) return TemporalState::Current; + const FactRecord* current = nullptr; + for (const size_t row : *lineage->second) { + if (row >= store.facts.size()) continue; + const auto& candidate = store.facts.at(row); + if (candidate.temporal.effectiveTime > reasoningTime) continue; + if (!current || candidate.temporal.effectiveTime > current->temporal.effectiveTime || + (candidate.temporal.effectiveTime == current->temporal.effectiveTime && + candidate.temporal.registrationSequence > current->temporal.registrationSequence)) { + current = &candidate; + } + } + return current == &record ? TemporalState::Current : TemporalState::Past; +} + +TemporalState FactMemory::temporalState(size_t index, + std::int64_t reasoningTime, + std::uint64_t snapshotGeneration) const { + return temporalStateInData(dataForSnapshot(snapshotGeneration), index, reasoningTime); +} + +std::vector FactMemory::currentFactIndexes(const std::vector& candidates, + std::uint64_t snapshotGeneration) const { + const Data& store = dataForSnapshot(snapshotGeneration); + std::vector current; + current.reserve(candidates.size()); + for (const size_t index : candidates) { + if (index >= store.facts.size() || !store.facts.at(index).active) continue; + if (temporalStateInData(store, index, 0) == TemporalState::Current) current.push_back(index); + } + return current; +} + +std::vector FactMemory::relevantPastFactIndexes(const std::string& type, + SymbolId typeId, + std::uint64_t snapshotGeneration) const { + const Data& store = dataForSnapshot(snapshotGeneration); + std::vector past; + for (size_t index = 0; index < store.facts.size(); ++index) { + const auto& record = store.facts.at(index); + if (!isCompatibleTypeInData(store, record.type, type)) continue; + if (temporalStateInData(store, index, 0) == TemporalState::Past) past.push_back(index); + } + (void)typeId; + return past; +} + +const FactRecord& FactMemory::snapshotFact(std::uint64_t snapshotGeneration, size_t index) const { + return dataForSnapshot(snapshotGeneration).facts.at(index); +} + +bool FactMemory::structurallyEqual(const std::shared_ptr& left, + const std::shared_ptr& right) { + if (!left || !right || left->kind() != right->kind()) return false; + if (const auto l = std::dynamic_pointer_cast(left)) { + return l->value == std::static_pointer_cast(right)->value; + } + if (const auto l = std::dynamic_pointer_cast(left)) { + return l->value == std::static_pointer_cast(right)->value; + } + if (const auto l = std::dynamic_pointer_cast(left)) { + return l->value == std::static_pointer_cast(right)->value; + } + if (std::dynamic_pointer_cast(left)) return true; + if (const auto l = std::dynamic_pointer_cast(left)) { + const auto r = std::static_pointer_cast(right); + if (l->items.size() != r->items.size()) return false; + for (std::size_t index = 0; index < l->items.size(); ++index) { + if (!structurallyEqual(l->items[index], r->items[index])) return false; + } + return true; + } + if (const auto l = std::dynamic_pointer_cast(left)) { + const auto r = std::static_pointer_cast(right); + if (l->entries.size() != r->entries.size()) return false; + for (const auto& wanted : l->entries) { + const auto found = std::find_if( + r->entries.begin(), r->entries.end(), + [&](const MapEntry& item) { + return wanted.keyId == item.keyId; + }); + if (found == r->entries.end() || + !structurallyEqual(wanted.value, found->value)) return false; + } + return true; + } + if (const auto l = std::dynamic_pointer_cast(left)) { + const auto r = std::static_pointer_cast(right); + if (l->nameId != r->nameId || l->args.size() != r->args.size()) return false; + for (std::size_t index = 0; index < l->args.size(); ++index) { + if (l->args[index].nameId != r->args[index].nameId || + !structurallyEqual( + l->args[index].value, r->args[index].value)) return false; + } + return true; + } + return left->debug() == right->debug(); +} + +bool FactMemory::factSatisfiesPattern(const MapExpr& fact, const MapExpr& pattern) { + for (const auto& wanted : pattern.entries) { + if (wanted.key == internalSymbolString(InternalSymbolKind::Parent)) continue; + bool matched = false; + for (const auto& actual : fact.entries) { + if (actual.keyId != wanted.keyId || actual.key != wanted.key) continue; + matched = structurallyEqual(actual.value, wanted.value); + break; + } + if (!matched) return false; + } + return true; +} + +std::optional FactMemory::logicalFactId(const std::shared_ptr& value) const { + const auto pattern = std::dynamic_pointer_cast(value); + if (!pattern) return std::nullopt; + if (pattern->factIdentity != 0) { + const auto indexed = data_->factIndexById.find(pattern->factIdentity); + if (!indexed || !data_->facts.at(*indexed).active) { + return std::nullopt; + } + return pattern->factIdentity; + } + const auto typeValue = std::dynamic_pointer_cast( + [&]() -> std::shared_ptr { + for (const auto& entry : pattern->entries) { + if (entry.key == internalSymbolString(InternalSymbolKind::Type)) return entry.value; + } + return nullptr; + }()); + if (!typeValue || typeValue->value == "Comparison") return std::nullopt; + + // Choose the most selective literal predicate without assigning semantic + // meaning to any user field name. `id` is not special in Felidae: every + // fact schema is free to use its own fields or no scalar key at all. + std::vector rows; + bool hasLiteralPredicate = false; + for (const auto& entry : pattern->entries) { + if (entry.key == internalSymbolString(InternalSymbolKind::Type) || + entry.key == internalSymbolString(InternalSymbolKind::Parent)) continue; + std::string ignored; + if (!literalIndexKey(entry.value, ignored)) continue; + const auto candidates = selectionIndexes(typeValue->value, entry.key, entry.value); + if (!hasLiteralPredicate || candidates.size() < rows.size()) rows = candidates; + hasLiteralPredicate = true; + } + if (!hasLiteralPredicate) rows = selectionIndexes(typeValue->value); + std::optional matched; + for (size_t index : rows) { + const auto& fact = data_->facts.at(index); + if (!fact.active) continue; + const auto materialized = materializeFact(*data_, index); + if (!materialized || !factSatisfiesPattern(*materialized, *pattern)) continue; + // A reconstructed map has no durable reference to one of several + // structurally equal rows. Refuse to choose arbitrarily: callers can + // obtain a fact through Fact.all/select, which carries this hidden id. + if (matched) return std::nullopt; + matched = fact.id; + } + return matched; +} + +std::shared_ptr FactMemory::factValueById(std::uint64_t id) const { + const auto indexed = data_->factIndexById.find(id); + if (!indexed) return {}; + const auto& fact = data_->facts.at(*indexed); + if (!fact.active) return {}; + return materializeFact(*data_, *indexed); +} + +std::optional FactMemory::factIndexById( + std::uint64_t id, + std::uint64_t snapshotGeneration) const { + const Data& store = dataForSnapshot(snapshotGeneration); + return store.factIndexById.find(id); +} + +std::vector FactMemory::temporalLineageIndexesForFact( + size_t index, + std::uint64_t snapshotGeneration) const { + const Data& store = dataForSnapshot(snapshotGeneration); + if (index >= store.facts.size()) return {}; + const auto found = store.temporalLineageIndexes.find(store.facts.at(index).temporal.lineageKey); + if (found == store.temporalLineageIndexes.end() || !found->second) return {}; + return *found->second; +} + +bool FactMemory::addDependency(std::uint64_t sourceId, std::shared_ptr required) { + if (sourceId == 0 || !required) return false; + ensureUnique(); + ensureAttachmentsUnique(); + auto& dependencies = data_->attachments->dependenciesBySource[sourceId]; + for (const auto& dependency : dependencies) { + if (structurallyEqual(dependency.required, required)) return true; + } + dependencies.push_back(FactDependency{std::move(required)}); + ++data_->generation; + return true; +} + +bool FactMemory::addRelationship(std::uint64_t sourceId, + std::uint64_t targetId, + std::shared_ptr relationship, + std::shared_ptr degree, + std::shared_ptr confidence) { + if (sourceId == 0 || targetId == 0 || !relationship) return false; + ensureUnique(); + ensureAttachmentsUnique(); + auto& outgoing = data_->attachments->relationshipsBySource[sourceId]; + for (const auto& existing : outgoing) { + if (existing.targetId == targetId && + structurallyEqual(existing.relationship, relationship) && + structurallyEqual(existing.degree, degree) && + structurallyEqual(existing.confidence, confidence)) { + return true; + } + } + FactRelationship record{sourceId, targetId, std::move(relationship), std::move(degree), std::move(confidence)}; + outgoing.push_back(record); + data_->attachments->relationshipsByTarget[targetId].push_back(record); + ++data_->generation; + return true; +} + +std::vector> FactMemory::missingDependencies(std::uint64_t sourceId) const { + std::vector> missing; + const auto found = data_->attachments->dependenciesBySource.find(sourceId); + if (found == data_->attachments->dependenciesBySource.end()) return missing; + for (const auto& dependency : found->second) { + bool satisfied = false; + std::string requiredType; + for (const auto& entry : dependency.required->entries) { + if (entry.key == internalSymbolString(InternalSymbolKind::Type)) { + if (const auto type = std::dynamic_pointer_cast(entry.value)) { + requiredType = type->value; + } + } + } + std::vector candidates; + bool hasLiteralPredicate = false; + for (const auto& entry : dependency.required->entries) { + if (entry.key == internalSymbolString(InternalSymbolKind::Type)) continue; + if (entry.key == internalSymbolString(InternalSymbolKind::Parent)) continue; + std::string ignored; + if (!literalIndexKey(entry.value, ignored)) continue; + if (requiredType.empty()) continue; + const auto indexed = selectionIndexes(requiredType, entry.key, entry.value); + if (!hasLiteralPredicate || indexed.size() < candidates.size()) candidates = indexed; + hasLiteralPredicate = true; + } + if (!hasLiteralPredicate) { + candidates = requiredType.empty() ? activeFactIndexes() : selectionIndexes(requiredType); + } + for (size_t candidate : candidates) { + const auto& fact = data_->facts.at(candidate); + const auto materialized = + fact.active ? materializeFact(*data_, candidate) : nullptr; + if (materialized && + factSatisfiesPattern(*materialized, *dependency.required)) { + satisfied = true; + break; + } + } + if (!satisfied) { + missing.push_back(std::static_pointer_cast(dependency.required->clone())); + } + } + return missing; +} + +bool FactMemory::hasDependencyCycle(std::uint64_t sourceId) const { + std::unordered_map byId; + byId.reserve(data_->facts.size()); + for (std::size_t index = 0; index < data_->facts.size(); ++index) { + const auto& fact = data_->facts.at(index); + if (fact.active) byId.emplace(fact.id, &fact); + } + std::unordered_set visiting; + std::unordered_set visited; + std::function visit = [&](std::uint64_t current) { + if (!visiting.insert(current).second) return true; + if (visited.count(current)) { + visiting.erase(current); + return false; + } + const auto dependencies = data_->attachments->dependenciesBySource.find(current); + if (dependencies != data_->attachments->dependenciesBySource.end()) { + for (const auto& dependency : dependencies->second) { + for (const auto& candidate : byId) { + const auto row = data_->factIndexById.find(candidate.first); + const auto materialized = + row ? materializeFact(*data_, *row) : nullptr; + if (materialized && + factSatisfiesPattern(*materialized, *dependency.required) && + visit(candidate.first)) { + return true; + } + } + } + } + visiting.erase(current); + visited.insert(current); + return false; + }; + return visit(sourceId); +} + +std::vector FactMemory::relationshipsFor(std::uint64_t factId) const { + std::vector result; + const auto outgoing = data_->attachments->relationshipsBySource.find(factId); + if (outgoing != data_->attachments->relationshipsBySource.end()) { + result.insert(result.end(), outgoing->second.begin(), outgoing->second.end()); + } + const auto incoming = data_->attachments->relationshipsByTarget.find(factId); + if (incoming != data_->attachments->relationshipsByTarget.end()) { + result.insert(result.end(), incoming->second.begin(), incoming->second.end()); + } + return result; +} + +const std::vector& FactMemory::outgoingRelationships( + std::uint64_t factId) const { + static const std::vector empty; + const auto it = data_->attachments->relationshipsBySource.find(factId); + return it == data_->attachments->relationshipsBySource.end() ? empty : it->second; +} + +const std::vector& FactMemory::incomingRelationships( + std::uint64_t factId) const { + static const std::vector empty; + const auto it = data_->attachments->relationshipsByTarget.find(factId); + return it == data_->attachments->relationshipsByTarget.end() ? empty : it->second; +} + +std::vector FactMemory::selectionIndexes(const std::string& type, + const std::string& property, + const std::shared_ptr& value, + std::uint64_t snapshotGeneration) const { + const Data& store = dataForSnapshot(snapshotGeneration); + const SymbolId typeId = symbolIdForName(type); + const SymbolId propertyId = property.empty() ? 0 : symbolIdForName(property); + std::size_t valueHash = 0; + const bool useEqualityIndex = !property.empty() && value && literalIndexHash(value, valueHash); + + std::vector result; + std::unordered_set seenRows; + std::deque pending; + std::unordered_set seenTypes; + pending.push_back(typeId); + while (!pending.empty()) { + const SymbolId current = pending.front(); + pending.pop_front(); + if (!seenTypes.insert(current).second) continue; + + const auto relation = store.relations.find(current); + if (relation != store.relations.end()) { + std::optional indexedCandidates; + const std::vector* candidates = &relation->second->rows; + if (useEqualityIndex) { + const auto column = relation->second->columns.find(propertyId); + const bool inheritsFields = + store.parentOf.count(relation->second->type) != 0 || + store.additionalParentsOf.count( + relation->second->type) != 0; + if (column == relation->second->columns.end() || + inheritsFields) { + // A missing direct column can still resolve through the + // hierarchy. Likewise, an index over explicit overrides + // cannot exclude rows that inherit the requested value. + candidates = &relation->second->rows; + } + else { + const auto started = std::chrono::steady_clock::now(); + const auto equality = column->second.equalityIndex; + std::lock_guard lock(equality->mutex); + ++equality->queryCount; + // A one-off analytical predicate is cheaper as a compact + // column scan. Build the retained equality index only + // after repeated demand demonstrates reuse. + constexpr std::size_t EqualityIndexBuildThreshold = 3; + if (!equality->built && + equality->queryCount >= EqualityIndexBuildThreshold) { + for (std::size_t offset = 0; + offset < column->second.values.size(); + ++offset) { + std::size_t hash = 0; + const auto& item = column->second.values[offset]; + if (item && literalIndexHash( + std::const_pointer_cast(item), hash)) { + equality->rowsByHash[hash].append( + column->second.rows[offset]); + } + } + equality->built = true; + ++adaptiveEqualityIndexes_; + adaptiveIndexBuildMicros_ += static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now() - started).count()); + } + if (equality->built) { + const auto matches = + equality->rowsByHash.find(valueHash); + if (matches == equality->rowsByHash.end()) { + candidates = nullptr; + } else { + indexedCandidates = matches->second; + } + } else { + // A cold equality query still scans the compact column, + // not every relation row followed by a binary search + // back into that column. The latter turns an O(n) + // cold lookup into O(n log n) and dominated million-row + // startup queries. + Data::Relation::RowList matches; + for (std::size_t offset = 0; + offset < column->second.values.size(); + ++offset) { + std::size_t hash = 0; + const auto& item = column->second.values[offset]; + if (item && literalIndexHash( + std::const_pointer_cast(item), hash) && + hash == valueHash) { + matches.append(column->second.rows[offset]); + } + } + indexedCandidates = std::move(matches); + } + } + } + const auto visitCandidate = [&](size_t index) { + if (index >= store.facts.size()) return; + const auto& fact = store.facts.at(index); + if (!fact.active || !isCompatibleTypeInData(store, fact.type, type)) return; + if (!property.empty()) { + const auto column = relation->second->columns.find(propertyId); + bool exact = !value; + if (column != relation->second->columns.end()) { + column->second.forRow(index, [&](const std::shared_ptr& item) { + if (exact) return; + if (static_cast(item) && + (!value || structurallyEqual( + std::const_pointer_cast(item), value))) { + exact = true; + } + }); + } + if (!exact) { + const auto resolved = + materializeFact(store, index); + if (resolved) { + const auto field = std::find_if( + resolved->entries.begin(), + resolved->entries.end(), + [&](const MapEntry& entry) { + return entry.keyId == propertyId && + entry.key == property; + }); + exact = field != resolved->entries.end() && + (!value || structurallyEqual( + field->value, value)); + } + } + if (!exact) return; + } + if (seenRows.insert(index).second) result.push_back(index); + }; + if (indexedCandidates) indexedCandidates->forEach(visitCandidate); + else if (candidates) for (size_t index : *candidates) visitCandidate(index); + } + const auto children = store.childrenByParent.find(current); + if (children != store.childrenByParent.end()) { + for (SymbolId child : children->second) pending.push_back(child); + } + } + return result; +} + +size_t FactMemory::addFact(std::string type, + std::string parentType, + std::shared_ptr value, + std::filesystem::path origin, + std::optional logicalId, + std::uint64_t rowVersion, + std::vector parentFactIds, + std::vector designations, + std::shared_ptr temporalMetadata) { + if (!value) throw std::invalid_argument("Fact value cannot be null"); + const SymbolId typeId = symbolIdForName(type); + const SymbolId parentTypeId = parentType.empty() ? 0 : symbolIdForName(parentType); + const std::size_t structuralHash = stableExprHash(value); + ensureUnique(); + // Designations are semantic metadata, not fact identity. Repeating an + // otherwise identical declaration enriches one canonical fact row rather + // than creating a second database fact solely for another designation. + if (!logicalId && !designations.empty()) { + const auto relation = data_->relations.find(typeId); + if (relation != data_->relations.end() && relation->second) { + for (const size_t candidateIndex : relation->second->rows) { + auto& candidate = data_->facts.mutableAt(candidateIndex); + if (!candidate.active || candidate.stableHash != structuralHash || + candidate.parentTypeId != parentTypeId || + candidate.parentFactIds != parentFactIds || + !structurallyEqual(materializeFact(*data_, candidateIndex), value)) { + continue; + } + bool changed = false; + for (const SymbolId designation : designations) { + if (designation == 0 || std::find( + candidate.designations.begin(), candidate.designations.end(), designation) != + candidate.designations.end()) { + continue; + } + candidate.designations.push_back(designation); + auto& rows = data_->designationIndexes[designation]; + if (!rows) rows = std::make_shared>(); + else if (rows.use_count() != 1) { + rows = std::make_shared>(*rows); + } + rows->push_back(candidateIndex); + changed = true; + } + if (changed) { + ++data_->generation; + invalidateCachesForFact(candidate, value); + } + return candidateIndex; + } + } + } + const std::uint64_t factId = logicalId ? *logicalId : data_->nextFactId++; + if (logicalId && *logicalId >= data_->nextFactId) data_->nextFactId = *logicalId + 1; + const auto temporal = temporalMetadataFor( + type, + logicalId.value_or(0), + value, + temporalMetadata, + static_cast(std::time(nullptr)), + data_->nextTemporalSequence++); + auto& record = data_->facts.append(FactRecord{ + factId, + std::move(type), + typeId, + std::move(parentType), + parentTypeId, + std::move(parentFactIds), + std::move(designations), + std::move(origin), + structuralHash, + rowVersion, + data_->generation + 1, + temporal, + 0, + true}); + const size_t index = data_->facts.size() - 1; + value->factIdentity = record.id; + indexFact(index, value); + ++data_->generation; + invalidateCachesForFact(record, value); + return index; +} + +std::vector FactMemory::designationIndexes( + const std::vector& designations, + std::uint64_t snapshotGeneration) const { + if (designations.empty()) return {}; + const Data& store = dataForSnapshot(snapshotGeneration); + const std::vector* smallest = nullptr; + for (const SymbolId designation : designations) { + if (designation == 0) return {}; + const auto found = store.designationIndexes.find(designation); + if (found == store.designationIndexes.end() || !found->second) return {}; + const auto& rows = *found->second; + if (!smallest || rows.size() < smallest->size()) smallest = &rows; + } + if (!smallest) return {}; + + std::vector selected; + selected.reserve(smallest->size()); + for (const size_t index : *smallest) { + if (index >= store.facts.size()) continue; + const auto& fact = store.facts.at(index); + if (!fact.active) continue; + bool matches = true; + for (const SymbolId designation : designations) { + if (std::find(fact.designations.begin(), fact.designations.end(), designation) == + fact.designations.end()) { + matches = false; + break; + } + } + if (matches) selected.push_back(index); + } + return selected; +} + +bool FactMemory::hasDesignation(SymbolId designation, + std::uint64_t snapshotGeneration) const { + if (designation == 0) return false; + const Data& store = dataForSnapshot(snapshotGeneration); + const auto found = store.designationIndexes.find(designation); + if (found == store.designationIndexes.end() || !found->second) return false; + return std::any_of(found->second->begin(), found->second->end(), [&](size_t index) { + return index < store.facts.size() && store.facts.at(index).active; + }); +} + +void FactMemory::setParent(const std::string& child, const std::string& parent) { + if (child.empty() || parent.empty()) return; + ensureUnique(); + const auto existing = parentsOf(child); + if (std::find(existing.begin(), existing.end(), parent) != existing.end()) return; + if (child == parent || isCompatibleType(parent, child)) { + throw std::invalid_argument("Inheritance cycle: '" + child + "' cannot extend '" + parent + "'"); + } + const SymbolId childId = symbolIdForName(child); + const SymbolId parentId = symbolIdForName(parent); + rememberTypeName(childId, child); + rememberTypeName(parentId, parent); + if (!data_->parentOf.count(child)) data_->parentOf[child] = parent; + else data_->additionalParentsOf[child].push_back(parent); + auto& children = data_->childrenByParent[parentId]; + if (std::find(children.begin(), children.end(), childId) == children.end()) { + children.push_back(childId); + } + auto& parents = data_->parentsByChild[childId]; + if (std::find(parents.begin(), parents.end(), parentId) == parents.end()) { + parents.push_back(parentId); + } + ++data_->hierarchyGeneration; + ++data_->generation; + // A parent declaration changes which rows match both type and property + // queries. The child fact may have been registered before this edge was + // known, so cached property candidates for the parent are stale too. + invalidateCaches(); +} + +void FactMemory::setParent(const std::string& child, + const std::string& parent, + std::filesystem::path origin) { + setParent(child, parent); + if (origin.empty()) return; + if (data_->parentOf[child] == parent) data_->parentOrigin[child] = std::move(origin); + else data_->additionalParentOrigins[child + "\x1f" + parent] = std::move(origin); +} + +const std::unordered_map& FactMemory::parents() const { + return data_->parentOf; +} + +std::vector FactMemory::parentsOf(const std::string& child) const { + std::vector result; + const auto primary = data_->parentOf.find(child); + if (primary != data_->parentOf.end()) result.push_back(primary->second); + const auto additional = data_->additionalParentsOf.find(child); + if (additional != data_->additionalParentsOf.end()) { + result.insert(result.end(), additional->second.begin(), additional->second.end()); + } + return result; +} + +const std::vector& FactMemory::parentsOf(SymbolId childId) const { + static const std::vector empty; + const auto found = data_->parentsByChild.find(childId); + return found == data_->parentsByChild.end() ? empty : found->second; +} + +std::vector> FactMemory::hierarchyEdges() const { + std::vector> result; + for (const auto& entry : data_->parentOf) result.emplace_back(entry.first, entry.second); + for (const auto& entry : data_->additionalParentsOf) { + for (const auto& parent : entry.second) result.emplace_back(entry.first, parent); + } + return result; +} + +const std::unordered_map& FactMemory::parentOrigins() const { + return data_->parentOrigin; +} + +std::vector FactMemory::factIndexesFromOrigin(const std::filesystem::path& origin) const { + auto found = data_->factsByOrigin.find(origin); + if (found == data_->factsByOrigin.end() || !found->second) return {}; + return *found->second; +} + +bool FactMemory::hasOrigin(const std::filesystem::path& origin) const { + return data_->factsByOrigin.count(origin) > 0; +} + +void FactMemory::removeOrigin(const std::filesystem::path& origin) { + if (origin.empty()) return; + ensureUnique(); + const auto found = data_->factsByOrigin.find(origin); + if (found != data_->factsByOrigin.end()) { + // Rows are immutable once published. Removing a source marks its + // rows inactive, preserving stable ids held by any live selection. + // New facts from a sync are appended as a new generation. + for (size_t index : *found->second) deactivateFact(index); + data_->factsByOrigin.erase(found); + } + for (auto it = data_->additionalParentOrigins.begin(); it != data_->additionalParentOrigins.end();) { + if (it->second == origin) { + const std::string edge = it->first; + const size_t separator = edge.find('\x1f'); + if (separator != std::string::npos) { + const std::string child = edge.substr(0, separator); + const std::string parent = edge.substr(separator + 1); + auto additional = data_->additionalParentsOf.find(child); + if (additional != data_->additionalParentsOf.end()) { + auto& values = additional->second; + values.erase(std::remove(values.begin(), values.end(), parent), values.end()); + if (values.empty()) data_->additionalParentsOf.erase(additional); + } + } + it = data_->additionalParentOrigins.erase(it); + } else { + ++it; + } + } + for (auto it = data_->parentOrigin.begin(); it != data_->parentOrigin.end();) { + if (it->second == origin) { + const std::string child = it->first; + data_->parentOf.erase(child); + it = data_->parentOrigin.erase(it); + const auto additional = data_->additionalParentsOf.find(child); + if (additional != data_->additionalParentsOf.end() && !additional->second.empty()) { + const std::string promoted = additional->second.front(); + additional->second.erase(additional->second.begin()); + data_->parentOf[child] = promoted; + const std::string key = child + "\x1f" + promoted; + const auto promotedOrigin = data_->additionalParentOrigins.find(key); + if (promotedOrigin != data_->additionalParentOrigins.end()) { + data_->parentOrigin[child] = promotedOrigin->second; + data_->additionalParentOrigins.erase(promotedOrigin); + } + if (additional->second.empty()) data_->additionalParentsOf.erase(additional); + } + } else { + ++it; + } + } + data_->childrenByParent.clear(); + data_->parentsByChild.clear(); + for (const auto& entry : data_->parentOf) { + const SymbolId childId = symbolIdForName(entry.first); + const SymbolId parentId = symbolIdForName(entry.second); + data_->childrenByParent[parentId].push_back(childId); + data_->parentsByChild[childId].push_back(parentId); + } + for (const auto& entry : data_->additionalParentsOf) { + const SymbolId childId = symbolIdForName(entry.first); + for (const auto& parent : entry.second) { + data_->childrenByParent[symbolIdForName(parent)].push_back(childId); + } + } + ++data_->generation; + ++data_->hierarchyGeneration; + invalidateCaches(); + compactInactiveIfSafe(); +} + +bool FactMemory::isCompatibleType(const std::string& actual, const std::string& expected) const { + return isCompatibleTypeInData(*data_, actual, expected); +} + +bool FactMemory::isCompatibleTypeInData(const Data& data, + const std::string& actual, + const std::string& expected) { + return isCompatibleTypeIdInData(data, symbolIdForName(actual), symbolIdForName(expected)); +} + +bool FactMemory::isCompatibleTypeIdInData(const Data& data, + SymbolId actual, + SymbolId expected) { + if (actual == 0 || expected == 0) return false; + if (expected == symbolIdForName("Fact")) return true; + if (actual == expected) return true; + std::unordered_set seen; + std::vector pending{actual}; + for (size_t index = 0; index < pending.size(); ++index) { + // Copy before appending parents: vector growth must not invalidate the + // current node while multi-parent traversal is expanding its frontier. + const SymbolId current = pending[index]; + if (!seen.insert(current).second) continue; + const auto parents = data.parentsByChild.find(current); + if (parents == data.parentsByChild.end()) continue; + for (const SymbolId parent : parents->second) { + if (parent == expected) return true; + pending.push_back(parent); + } + } + return false; +} + +const std::vector& FactMemory::compatibleFactIndexes(const std::string& type, SymbolId typeId) { + if (typeId == 0) typeId = symbolIdForName(type); + const auto cached = compatibleFactCache_.find(typeId); + if (cached != compatibleFactCache_.end()) return cached->second; + + std::vector indexes; + std::deque pending; + std::unordered_set seenTypes; + pending.push_back(typeId); + while (!pending.empty()) { + const SymbolId current = pending.front(); + pending.pop_front(); + if (!seenTypes.insert(current).second) continue; + + const auto direct = data_->relations.find(current); + if (direct != data_->relations.end() && direct->second) { + for (size_t index : direct->second->rows) { + if (!isActive(index)) continue; + if (isCompatibleTypeIdInData(*data_, data_->facts.at(index).typeId, typeId)) { + indexes.push_back(index); + } + } + } + auto children = data_->childrenByParent.find(current); + if (children != data_->childrenByParent.end()) { + for (SymbolId child : children->second) pending.push_back(child); + } + } + return compatibleFactCache_.emplace(typeId, std::move(indexes)).first->second; +} + +const std::vector& FactMemory::propertyFactIndexes( + const std::string& type, + SymbolId typeId, + const std::string& property, + SymbolId propertyId, + const std::shared_ptr& value) { + static const std::vector empty; + std::string valueKey; + if (!literalIndexKey(value, valueKey)) return empty; + std::size_t ignoredHash = 0; + if (!literalIndexHash(value, ignoredHash)) return empty; + if (typeId == 0) typeId = symbolIdForName(type); + if (propertyId == 0) propertyId = symbolIdForName(property); + + PropertyQueryKey queryKey{typeId, propertyId, valueKey}; + auto cached = propertyQueryCache_.find(queryKey); + if (cached != propertyQueryCache_.end()) return cached->second; + + // selectionIndexes owns adaptive index construction and structural + // confirmation. Keep this cache as the stable query-plan result only. + std::vector indexes = + selectionIndexes(type, property, value); + auto inserted = propertyQueryCache_.emplace(std::move(queryKey), std::move(indexes)); + return inserted.first->second; +} + +void FactMemory::invalidateCaches() { + compatibleFactCache_.clear(); + propertyQueryCache_.clear(); +} + +void FactMemory::rebuildIndexes( + const std::vector>& values) { + data_->factIndexById.clear(); + data_->factsByOrigin.clear(); + data_->designationIndexes.clear(); + data_->temporalLineageIndexes.clear(); + data_->typeNamesById.clear(); + data_->relations.clear(); + for (size_t index = 0; index < data_->facts.size(); ++index) { + if (data_->facts.at(index).active && index < values.size()) { + indexFact(index, values[index]); + } + } + // Inactive rows retained for a live lineage are temporal history, not + // ordinary query/index rows. Keep only their lineage membership here. + for (size_t index = 0; index < data_->facts.size(); ++index) { + const auto& fact = data_->facts.at(index); + if (fact.active) continue; + auto& lineageRows = data_->temporalLineageIndexes[fact.temporal.lineageKey]; + if (!lineageRows) lineageRows = std::make_shared>(); + else if (lineageRows.use_count() != 1) { + lineageRows = std::make_shared>(*lineageRows); + } + lineageRows->push_back(index); + } + data_->childrenByParent.clear(); + for (const auto& entry : data_->parentOf) { + const SymbolId childId = symbolIdForName(entry.first); + const SymbolId parentId = symbolIdForName(entry.second); + rememberTypeName(childId, entry.first); + rememberTypeName(parentId, entry.second); + data_->childrenByParent[parentId].push_back(childId); + } + for (const auto& entry : data_->additionalParentsOf) { + const SymbolId childId = symbolIdForName(entry.first); + for (const auto& parent : entry.second) { + const SymbolId parentId = symbolIdForName(parent); + rememberTypeName(parentId, parent); + data_->childrenByParent[parentId].push_back(childId); + data_->parentsByChild[childId].push_back(parentId); + } + } + invalidateCaches(); +} + +std::size_t FactMemory::PropertyQueryKeyHash::operator()(const PropertyQueryKey& key) const { + std::size_t seed = std::hash{}(key.typeId); + seed ^= std::hash{}(key.propertyId) + 0x9e3779b9U + (seed << 6U) + (seed >> 2U); + seed ^= std::hash{}(key.value) + 0x9e3779b9U + (seed << 6U) + (seed >> 2U); + return seed; +} + +bool FactMemory::literalIndexKey(const std::shared_ptr& value, std::string& out) { + if (!value) return false; + switch (value->kind()) { + case ExprKind::String: + out = "s:" + static_cast(*value).value; + return true; + case ExprKind::Number: { + std::ostringstream text; + text << "n:" << std::setprecision(17) << static_cast(*value).value; + out = text.str(); + return true; + } + case ExprKind::Bool: + out = static_cast(*value).value ? "b:1" : "b:0"; + return true; + case ExprKind::Nil: + out = "z:"; + return true; + default: + return false; + } +} + +bool FactMemory::literalIndexHash( + const std::shared_ptr& value, + std::size_t& out) { + if (!value) return false; + constexpr std::size_t offset = + sizeof(std::size_t) == 8 ? 1469598103934665603ULL : 2166136261U; + constexpr std::size_t prime = + sizeof(std::size_t) == 8 ? 1099511628211ULL : 16777619U; + auto mix = [&](const void* data, std::size_t size, unsigned char kind) { + std::size_t hash = (offset ^ kind) * prime; + const auto* bytes = static_cast(data); + for (std::size_t i = 0; i < size; ++i) hash = (hash ^ bytes[i]) * prime; + out = hash; + }; + switch (value->kind()) { + case ExprKind::String: { + const auto& text = static_cast(*value).value; + mix(text.data(), text.size(), 1); + return true; + } + case ExprKind::Number: { + const double number = static_cast(*value).value; + std::uint64_t bits = 0; + std::memcpy(&bits, &number, sizeof(bits)); + mix(&bits, sizeof(bits), 2); + return true; + } + case ExprKind::Bool: { + const bool boolean = static_cast(*value).value; + mix(&boolean, sizeof(boolean), 3); + return true; + } + case ExprKind::Nil: + mix(nullptr, 0, 4); + return true; + default: + return false; + } +} + +std::size_t FactMemory::stableExprHash(const std::shared_ptr& value) { + if (!value) return 0; + std::size_t literal = 0; + if (literalIndexHash(value, literal)) return literal; + std::size_t seed = static_cast(value->kind()) + 0x9e3779b9U; + auto combine = [&](std::size_t hash) { + seed ^= hash + 0x9e3779b97f4a7c15ULL + (seed << 6U) + (seed >> 2U); + }; + if (auto array = std::dynamic_pointer_cast(value)) { + for (const auto& item : array->items) combine(stableExprHash(item)); + } else if (auto map = std::dynamic_pointer_cast(value)) { + for (const auto& entry : map->entries) { + combine(std::hash{}(entry.keyId)); + combine(stableExprHash(entry.value)); + } + } else if (auto term = std::dynamic_pointer_cast(value)) { + combine(std::hash{}(term->nameId)); + for (const auto& argument : term->args) { + combine(std::hash{}(argument.nameId)); + combine(stableExprHash(argument.value)); + } + } else { + combine(std::hash{}(value->debug())); + } + return seed; +} + +void FactMemory::rememberTypeName(SymbolId id, const std::string& name) { + auto& names = data_->typeNamesById[id]; + if (std::find(names.begin(), names.end(), name) == names.end()) names.push_back(name); +} + +std::shared_ptr FactMemory::internValue( + const std::shared_ptr& value) { + if (!value) return {}; + // Numeric columns in analytical stores are commonly high-cardinality + // measures and identifiers. Hash-consing those values adds a hash-table + // node and lock/search work without producing sharing. + if (value->kind() == ExprKind::Number) { + return std::shared_ptr(value->clone()); + } + if (!data_->valueArena) data_->valueArena = std::make_shared(); + const std::size_t hash = stableExprHash(value); + auto& candidates = data_->valueArena->valuesByHash[hash]; + for (const auto& candidate : candidates) { + if (candidate && structurallyEqual( + std::const_pointer_cast(candidate), value)) { + return candidate; + } + } + auto stored = std::shared_ptr(value->clone()); + candidates.push_back(stored); + ++data_->valueArena->valueCount; + return stored; +} + +void FactMemory::indexFact( + size_t index, + const std::shared_ptr& value) { + auto& fact = data_->facts.mutableAt(index); + if (!fact.active || !value) return; + if (fact.typeId == 0) fact.typeId = symbolIdForName(fact.type); + if (fact.parentTypeId == 0 && !fact.parentType.empty()) { + fact.parentTypeId = symbolIdForName(fact.parentType); + } + rememberTypeName(fact.typeId, fact.type); + data_->factIndexById.assign(fact.id, index); + auto& lineageRows = data_->temporalLineageIndexes[fact.temporal.lineageKey]; + if (!lineageRows) lineageRows = std::make_shared>(); + else if (lineageRows.use_count() != 1) { + lineageRows = std::make_shared>(*lineageRows); + } + lineageRows->push_back(index); + for (const SymbolId designation : fact.designations) { + if (designation == 0) continue; + auto& rows = data_->designationIndexes[designation]; + if (!rows) rows = std::make_shared>(); + else if (rows.use_count() != 1) rows = std::make_shared>(*rows); + rows->push_back(index); + } + if (!fact.origin.empty()) { + auto& rows = data_->factsByOrigin[fact.origin]; + if (!rows) rows = std::make_shared>(); + else if (rows.use_count() != 1) rows = std::make_shared>(*rows); + rows->push_back(index); + } + auto& relation = writableRelation(fact.typeId); + if (relation.type.empty()) { + relation.typeId = fact.typeId; + relation.type = fact.type; + } + relation.generation = data_->generation + 1; + fact.relationOrdinal = relation.rows.size(); + relation.rows.push_back(index); + relation.fieldOrderOffsets.push_back(relation.fieldOrder.size()); + std::size_t visibleFieldCount = 0; + for (const auto& entry : value->entries) { + if (entry.keyId == InternalSymbol::TypeId || entry.keyId == InternalSymbol::ParentId) continue; + ++visibleFieldCount; + relation.fieldNames.emplace(entry.keyId, entry.key); + relation.fieldOrder.push_back(entry.keyId); + std::vector> items; + const auto array = std::dynamic_pointer_cast(entry.value); + if (array) { + items = array->items; + } else { + items.push_back(entry.value); + } + relation.fieldValueCounts.push_back(items.size()); + relation.fieldArrayFlags.push_back(array ? 1U : 0U); + auto& column = relation.columns[entry.keyId]; + const std::size_t presenceWord = fact.relationOrdinal / 64; + if (column.presence.size() <= presenceWord) { + column.presence.resize(presenceWord + 1, 0); + } + column.presence[presenceWord] |= + std::uint64_t{1} << (fact.relationOrdinal % 64); + for (const auto& item : items) { + const auto stored = internValue(item); + column.rows.push_back(index); + column.values.push_back(stored); + const auto observedKind = [&]() { + if (!stored) return Data::Relation::ColumnKind::Empty; + switch (stored->kind()) { + case ExprKind::String: return Data::Relation::ColumnKind::String; + case ExprKind::Number: return Data::Relation::ColumnKind::Number; + case ExprKind::Bool: return Data::Relation::ColumnKind::Bool; + case ExprKind::Nil: return Data::Relation::ColumnKind::Nil; + default: return Data::Relation::ColumnKind::Structured; + } + }(); + if (column.kind == Data::Relation::ColumnKind::Empty) { + column.kind = observedKind; + } else if (observedKind != Data::Relation::ColumnKind::Empty && + column.kind != observedKind) { + column.kind = Data::Relation::ColumnKind::Mixed; + } + if (column.equalityIndex && + column.equalityIndex.use_count() != 1) { + auto detached = + std::make_shared(); + { + std::lock_guard lock( + column.equalityIndex->mutex); + detached->built = column.equalityIndex->built; + detached->queryCount = + column.equalityIndex->queryCount; + detached->rowsByHash = + column.equalityIndex->rowsByHash; + } + column.equalityIndex = std::move(detached); + } + if (column.equalityIndex && column.equalityIndex->built) { + std::size_t valueHash = 0; + if (literalIndexHash( + std::const_pointer_cast(stored), valueHash)) { + column.equalityIndex->rowsByHash[valueHash].append(index); + } + } + } + } + relation.fieldOrderCounts.push_back(visibleFieldCount); +} + +void FactMemory::deactivateFact(size_t index) { + if (!isActive(index)) return; + FactRecord& fact = data_->facts.mutableAt(index); + invalidateCachesForFact(fact, materializeFact(*data_, index)); + fact.active = false; +} + +void FactMemory::compactInactiveIfSafe() { + // Selections refer to vector positions in their captured Data. Never + // compact while a snapshot is retained; db.release makes that lifetime + // explicit for callers that keep long-lived selections. + if (!snapshots_.empty()) return; + std::size_t tombstones = 0; + for (std::size_t index = 0; index < data_->facts.size(); ++index) { + if (!data_->facts.at(index).active) ++tombstones; + } + if (tombstones == 0) return; + constexpr std::size_t MinTombstonesBeforeCompaction = 128; + if (tombstones < MinTombstonesBeforeCompaction && + tombstones * 2 < data_->facts.size()) return; + + ensureUnique(); + std::unordered_set liveLineages; + for (std::size_t index = 0; index < data_->facts.size(); ++index) { + const auto& fact = data_->facts.at(index); + if (fact.active) liveLineages.insert(fact.temporal.lineageKey); + } + FactRows compacted; + std::vector> compactedValues; + compactedValues.reserve(data_->facts.size() - tombstones); + for (std::size_t index = 0; index < data_->facts.size(); ++index) { + const auto& fact = data_->facts.at(index); + if (fact.active || liveLineages.count(fact.temporal.lineageKey) > 0) { + compactedValues.push_back(materializeFact(*data_, index)); + compacted.append(fact); + } + } + data_->facts = std::move(compacted); + ++data_->generation; + rebuildIndexes(compactedValues); +} + +void FactMemory::invalidateCachesForFact( + const FactRecord& fact, + const std::shared_ptr& value) { + invalidateCachesForType(fact.type, fact.typeId); + + // Property selections are precise enough to invalidate only queries for + // values present in the changed fact. Queries for other fields/values + // remain reusable across fact registrations. + for (auto cache = propertyQueryCache_.begin(); cache != propertyQueryCache_.end();) { + const auto& key = cache->first; + if (!isCompatibleTypeIdInData(*data_, fact.typeId, key.typeId) || !value) { + ++cache; + continue; + } + bool matches = false; + for (const auto& entry : value->entries) { + if (entry.keyId != key.propertyId) continue; + std::vector> values; + if (auto array = std::dynamic_pointer_cast(entry.value)) values = array->items; + else values.push_back(entry.value); + for (const auto& itemValue : values) { + std::string literal; + if (literalIndexKey(itemValue, literal) && literal == key.value) { + matches = true; + break; + } + } + if (matches) break; + } + if (matches) cache = propertyQueryCache_.erase(cache); + else ++cache; + } +} + +void FactMemory::invalidateCachesForType(const std::string& type, SymbolId typeId) { + (void)type; + (void)typeId; + // The cache is keyed solely by collision-free SymbolId. Hierarchy writes + // are uncommon and can affect descendants in either direction, so a + // complete invalidation is simpler and avoids a parallel spelling walk. + compatibleFactCache_.clear(); +} + +void FactMemory::ensureUnique() { + if (data_.use_count() != 1) data_ = std::make_shared(*data_); +} + +void FactMemory::ensureAttachmentsUnique() { + if (!data_->attachments) { + data_->attachments = std::make_shared(); + } else if (data_->attachments.use_count() != 1) { + data_->attachments = std::make_shared(*data_->attachments); + } +} + +FactMemory::Data::Relation& FactMemory::writableRelation(SymbolId typeId) { + auto& relation = data_->relations[typeId]; + if (!relation) { + relation = std::make_shared(); + } else if (relation.use_count() != 1) { + relation = std::make_shared(*relation); + } + return *relation; +} + +} // namespace Felidae diff --git a/src/Memory.h b/src/Memory.h new file mode 100644 index 0000000..fdafee0 --- /dev/null +++ b/src/Memory.h @@ -0,0 +1,402 @@ +#pragma once + +#include "AST.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +enum class TemporalState : std::uint8_t { + Past, + Current, + Future +}; + +enum class TemporalOrigin : std::uint8_t { + Observed, + Scheduled, + Derived, + Predicted, + Required +}; + +struct FactTemporalMetadata { + // Effective time is Unix seconds when explicitly supplied by a recognized + // field, otherwise registration time. Sequence makes same-second writes + // deterministic without altering the user-visible fact schema. + std::int64_t effectiveTime = 0; + std::int64_t registrationTime = 0; + std::uint64_t registrationSequence = 0; + bool hasExplicitEffectiveTime = false; + TemporalOrigin origin = TemporalOrigin::Observed; + std::string lineageKey; +}; + +struct FactRecord { + // Fact ids are append-only and never reused. Vector positions are an + // implementation detail; retaining this id makes source reloads, + // selections and future external stores independent of compaction. + std::uint64_t id = 0; + std::string type; + SymbolId typeId = 0; + std::string parentType; + SymbolId parentTypeId = 0; + std::vector parentFactIds; + std::vector designations; + std::filesystem::path origin; + std::size_t stableHash = 0; + // Logical identity and physical row version are intentionally separate. + // Updating a fact retains id and publishes a later immutable row version. + std::uint64_t rowVersion = 1; + std::uint64_t visibleGeneration = 0; + FactTemporalMetadata temporal; + // Stable position inside the immutable relation root. This is distinct + // from the global row index and lets column access remain contiguous. + std::size_t relationOrdinal = 0; + bool active = true; +}; + +struct FactMemoryStats { + std::size_t activeFacts = 0; + std::size_t tombstonedFacts = 0; + std::size_t relations = 0; + std::size_t snapshots = 0; + std::size_t relationRows = 0; + std::size_t relationColumnValues = 0; + std::size_t internedValues = 0; + std::size_t adaptiveEqualityIndexes = 0; + std::size_t adaptiveIndexBuildMicros = 0; + std::size_t rowVersions = 0; + std::size_t temporalLineages = 0; + std::size_t temporalPastFacts = 0; + std::size_t temporalFutureFacts = 0; + std::uint64_t generation = 0; +}; + +// Attachments deliberately live beside facts rather than in their serialized +// MapExpr values. That keeps structural equality/source export unchanged +// while aliases of the same logical fact observe the same knowledge. +struct FactDependency { + std::shared_ptr required; +}; + +struct FactRelationship { + std::uint64_t sourceId = 0; + std::uint64_t targetId = 0; + std::shared_ptr relationship; + std::shared_ptr degree; + std::shared_ptr confidence; +}; + +class FactMemory { +public: + FactMemory(); + FactMemory(const FactMemory& other); + FactMemory& operator=(const FactMemory& other); + FactMemory(FactMemory&&) noexcept = default; + FactMemory& operator=(FactMemory&&) noexcept = default; + + const FactRecord& fact(size_t index) const; + std::shared_ptr factValue(size_t index, + std::uint64_t snapshotGeneration = 0) const; + std::vector factArguments(size_t index) const; + bool isActive(size_t index) const; + std::vector activeFactIndexes() const; + bool hasActiveRelation(const std::string& type, SymbolId typeId = 0) const; + std::uint64_t generation() const; + std::uint64_t relationGeneration(const std::string& type, + SymbolId typeId = 0) const; + std::uint64_t hierarchyGeneration() const; + FactMemoryStats stats() const; + // A selection captures an immutable logical view. It remains valid + // until explicitly released by the runtime/library owner. + std::uint64_t captureSnapshot(); + bool releaseSnapshot(std::uint64_t snapshotGeneration); + std::vector selectionIndexes(const std::string& type, + const std::string& property = {}, + const std::shared_ptr& value = nullptr, + std::uint64_t snapshotGeneration = 0) const; + const FactRecord& snapshotFact(std::uint64_t snapshotGeneration, size_t index) const; + + std::optional logicalFactId(const std::shared_ptr& value) const; + std::shared_ptr factValueById(std::uint64_t id) const; + std::optional factIndexById(std::uint64_t id, + std::uint64_t snapshotGeneration = 0) const; + std::vector temporalLineageIndexesForFact(size_t index, + std::uint64_t snapshotGeneration = 0) const; + bool addDependency(std::uint64_t sourceId, std::shared_ptr required); + bool addRelationship(std::uint64_t sourceId, + std::uint64_t targetId, + std::shared_ptr relationship, + std::shared_ptr degree, + std::shared_ptr confidence); + std::vector> missingDependencies(std::uint64_t sourceId) const; + bool hasDependencyCycle(std::uint64_t sourceId) const; + std::vector relationshipsFor(std::uint64_t factId) const; + const std::vector& outgoingRelationships(std::uint64_t factId) const; + const std::vector& incomingRelationships(std::uint64_t factId) const; + + size_t addFact(std::string type, + std::string parentType, + std::shared_ptr value, + std::filesystem::path origin = {}, + std::optional logicalId = std::nullopt, + std::uint64_t rowVersion = 1, + std::vector parentFactIds = {}, + std::vector designations = {}, + std::shared_ptr temporalMetadata = {}); + std::vector designationIndexes(const std::vector& designations, + std::uint64_t snapshotGeneration = 0) const; + bool hasDesignation(SymbolId designation, + std::uint64_t snapshotGeneration = 0) const; + TemporalState temporalState(size_t index, + std::int64_t reasoningTime = 0, + std::uint64_t snapshotGeneration = 0) const; + std::vector currentFactIndexes(const std::vector& candidates, + std::uint64_t snapshotGeneration = 0) const; + std::vector relevantPastFactIndexes(const std::string& type, + SymbolId typeId = 0, + std::uint64_t snapshotGeneration = 0) const; + void setParent(const std::string& child, const std::string& parent); + void setParent(const std::string& child, + const std::string& parent, + std::filesystem::path origin); + const std::unordered_map& parents() const; + std::vector parentsOf(const std::string& child) const; + const std::vector& parentsOf(SymbolId childId) const; + std::vector> hierarchyEdges() const; + const std::unordered_map& parentOrigins() const; + std::vector factIndexesFromOrigin(const std::filesystem::path& origin) const; + bool hasOrigin(const std::filesystem::path& origin) const; + void removeOrigin(const std::filesystem::path& origin); + bool isCompatibleType(const std::string& actual, const std::string& expected) const; + const std::vector& compatibleFactIndexes(const std::string& type, SymbolId typeId = 0); + const std::vector& propertyFactIndexes(const std::string& type, + SymbolId typeId, + const std::string& property, + SymbolId propertyId, + const std::shared_ptr& value); + // Prefer the automatic, relation-aware invalidation performed by the + // mutation API. This remains for callers that intentionally replace a + // whole logical store. + void invalidateCaches(); + +private: + struct PropertyQueryKey { + SymbolId typeId = 0; + SymbolId propertyId = 0; + std::string value; + + bool operator==(const PropertyQueryKey& other) const { + return typeId == other.typeId && + propertyId == other.propertyId && + value == other.value; + } + }; + struct PropertyQueryKeyHash { + std::size_t operator()(const PropertyQueryKey& key) const; + }; + + // Copying a store catalog must not copy its fact rows. The catalog keeps + // a small directory of fixed-size immutable batches; a writer detaches + // only the batch it appends to or changes. Snapshot catalogs retain the + // previous batch pointers, so row positions remain valid for their full + // lifetime. + struct FactRows { + static constexpr std::size_t BatchSize = 1024; + + std::vector>> batches; + std::size_t count = 0; + + std::size_t size() const { return count; } + const FactRecord& at(std::size_t index) const; + FactRecord& mutableAt(std::size_t index); + FactRecord& append(FactRecord record); + }; + + // Fact ids are monotonic, so a paged directory is both cheaper than a + // hash table and naturally copy-on-write at page granularity. It maps a + // stable FactId to the row position visible in this catalog generation. + struct FactIdDirectory { + static constexpr std::size_t PageSize = 1024; + static constexpr std::size_t Missing = static_cast(-1); + + std::vector>> pages; + + std::optional find(std::uint64_t id) const; + void assign(std::uint64_t id, std::size_t row); + void clear() { pages.clear(); } + }; + + struct AttachmentData { + std::unordered_map> dependenciesBySource; + std::unordered_map> relationshipsBySource; + std::unordered_map> relationshipsByTarget; + }; + + struct Data { + struct ValueArena { + std::unordered_map>> valuesByHash; + std::size_t valueCount = 0; + }; + + struct Relation { + struct RowList { + static constexpr std::size_t Missing = static_cast(-1); + std::size_t first = Missing; + std::vector additional; + + void append(std::size_t row) { + if (first == Missing) first = row; + else additional.push_back(row); + } + template + void forEach(const Callback& callback) const { + if (first != Missing) callback(first); + for (std::size_t row : additional) callback(row); + } + }; + + enum class ColumnKind : std::uint8_t { + Empty, + String, + Number, + Bool, + Nil, + Structured, + Mixed + }; + + struct FieldColumn { + struct EqualityIndex { + std::mutex mutex; + bool built = false; + std::size_t queryCount = 0; + std::unordered_map rowsByHash; + }; + + ColumnKind kind = ColumnKind::Empty; + // Rows are append ordered. Repeated field values (including + // array projections) repeat the row index and occupy adjacent + // positions, so lookup is a cache-friendly equal range. + std::vector rows; + std::vector> values; + std::vector presence; + // This derived cache is built only after a query demonstrates + // demand. It is separate from immutable column data and is + // detached before a changed relation updates a warm index. + std::shared_ptr equalityIndex = + std::make_shared(); + + template + void forRow(std::size_t row, const Callback& callback) const { + const auto begin = std::lower_bound(rows.begin(), rows.end(), row); + for (auto current = begin; current != rows.end() && *current == row; ++current) { + const auto offset = static_cast(current - rows.begin()); + callback(values[offset]); + } + } + + bool present(std::size_t relationOrdinal) const { + const std::size_t word = relationOrdinal / 64; + const std::size_t bit = relationOrdinal % 64; + return word < presence.size() && + (presence[word] & (std::uint64_t{1} << bit)) != 0; + } + }; + + SymbolId typeId = 0; + std::string type; + std::uint64_t generation = 0; + std::vector rows; + std::unordered_map fieldNames; + std::unordered_map columns; + // Source field order is kept in one relation-local packed vector. + // Each row stores only an offset/count pair. + std::vector fieldOrderOffsets; + std::vector fieldOrderCounts; + std::vector fieldOrder; + std::vector fieldValueCounts; + std::vector fieldArrayFlags; + }; + + FactRows facts; + std::uint64_t nextFactId = 1; + std::uint64_t nextTemporalSequence = 1; + std::uint64_t generation = 1; + std::uint64_t hierarchyGeneration = 1; + FactIdDirectory factIndexById; + std::unordered_map>> factsByOrigin; + std::unordered_map parentOf; + std::unordered_map parentOrigin; + std::unordered_map> additionalParentsOf; + std::unordered_map additionalParentOrigins; + std::unordered_map> childrenByParent; + std::unordered_map> parentsByChild; + std::unordered_map> typeNamesById; + std::unordered_map>> designationIndexes; + std::unordered_map>> temporalLineageIndexes; + // Relation roots are independently copy-on-write. Publishing a + // change to one fact type keeps every other relation's columns and + // indexes shared with existing snapshots. + std::unordered_map> relations; + std::shared_ptr attachments = std::make_shared(); + std::shared_ptr valueArena = std::make_shared(); + }; + + std::shared_ptr data_; + std::unordered_map> snapshots_; + std::unordered_map> compatibleFactCache_; + std::unordered_map, PropertyQueryKeyHash> propertyQueryCache_; + mutable std::size_t adaptiveEqualityIndexes_ = 0; + mutable std::size_t adaptiveIndexBuildMicros_ = 0; + + static bool literalIndexKey(const std::shared_ptr& value, std::string& out); + static bool literalIndexHash(const std::shared_ptr& value, std::size_t& out); + static std::size_t stableExprHash(const std::shared_ptr& value); + static bool structurallyEqual(const std::shared_ptr& left, + const std::shared_ptr& right); + static bool factSatisfiesPattern(const MapExpr& fact, const MapExpr& pattern); + static FactTemporalMetadata temporalMetadataFor(const std::string& type, + std::uint64_t logicalId, + const std::shared_ptr& value, + const std::shared_ptr& temporalMetadata, + std::int64_t registrationTime, + std::uint64_t registrationSequence); + static bool parseTemporalValue(const std::shared_ptr& value, std::int64_t& out); + static TemporalOrigin temporalOriginFor(const std::shared_ptr& value); + TemporalState temporalStateInData(const Data& store, + size_t index, + std::int64_t reasoningTime) const; + static bool isCompatibleTypeInData(const Data& data, + const std::string& actual, + const std::string& expected); + static bool isCompatibleTypeIdInData(const Data& data, + SymbolId actual, + SymbolId expected); + const Data& dataForSnapshot(std::uint64_t snapshotGeneration) const; + void ensureUnique(); + void ensureAttachmentsUnique(); + std::shared_ptr internValue(const std::shared_ptr& value); + std::shared_ptr materializeFact(const Data& store, std::size_t index) const; + Data::Relation& writableRelation(SymbolId typeId); + void indexFact(size_t index, const std::shared_ptr& value); + void deactivateFact(size_t index); + void compactInactiveIfSafe(); + void invalidateCachesForFact(const FactRecord& fact, + const std::shared_ptr& value = {}); + void invalidateCachesForType(const std::string& type, SymbolId typeId); + void rememberTypeName(SymbolId id, const std::string& name); + void rebuildIndexes(const std::vector>& values); +}; + +} // namespace Felidae diff --git a/src/NativeRuntime.cpp b/src/NativeRuntime.cpp new file mode 100644 index 0000000..af81e26 --- /dev/null +++ b/src/NativeRuntime.cpp @@ -0,0 +1,301 @@ +#include "NativeRuntime.h" + +#include "../native_modules/common/NativeJson.h" + +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace Felidae { + +namespace { + +std::string lowerText(std::string text) { + for (char& ch : text) { + ch = static_cast(std::tolower(static_cast(ch))); + } + return text; +} + +} // namespace + +const NativeContract& NativeModuleManifest::contractFor(const std::string& functionName) const { + const auto exact = functions.find(functionName); + if (exact != functions.end()) return exact->second; + const size_t separator = functionName.rfind(':'); + if (separator != std::string::npos) { + const auto shortName = functions.find(functionName.substr(separator + 1)); + if (shortName != functions.end()) return shortName->second; + } + return defaultContract; +} + +bool parseNativeModuleManifest(const std::string& json, + NativeModuleManifest& manifest, + std::string& error) { + using Felidae::NativeJson::Value; + size_t position = 0; + Value root; + if (!Felidae::NativeJson::parseValue(json, position, root)) { + error = "invalid JSON"; + return false; + } + Felidae::NativeJson::skipWhitespace(json, position); + if (position != json.size() || root.kind != Value::Kind::Object) { + error = "manifest must be one JSON object"; + return false; + } + const auto field = [](const Value& object, const char* name) -> const Value* { + const auto it = object.fields.find(name); + return it == object.fields.end() ? nullptr : &it->second; + }; + const auto text = [&](const Value& object, const char* name, std::string& out) -> bool { + const Value* value = field(object, name); + if (!value || value->kind != Value::Kind::String || value->text.empty()) return false; + out = value->text; + return true; + }; + const Value* schema = field(root, "schema_version"); + const Value* abi = field(root, "abi_version"); + std::string module; + if (!schema || schema->kind != Value::Kind::Number || schema->number != 1.0 || + !abi || abi->kind != Value::Kind::Number || abi->number != 1.0 || + !text(root, "module", module)) { + error = "manifest requires schema_version 1, abi_version 1, and a module name"; + return false; + } + + const auto parseContract = [&](const Value* object, NativeContract& contract) -> bool { + if (!object) return true; + if (object->kind != Value::Kind::Object) return false; + const auto boolean = [&](const char* name, bool& target) -> bool { + const Value* value = field(*object, name); + if (!value) return true; + if (value->kind != Value::Kind::Bool) return false; + target = value->boolean; + return true; + }; + auto& capabilities = contract.capabilities; + if (!boolean("pure", capabilities.pure) || + !boolean("thread_safe", capabilities.threadSafe) || + !boolean("supports_batch", capabilities.supportsBatch) || + !boolean("accepts_fact_selections", capabilities.acceptsFactSelections) || + !boolean("selection_cardinality", capabilities.selectionCardinality) || + !boolean("needs_fact_projection", capabilities.needsFactProjection) || + !boolean("needs_fact_hierarchy", capabilities.needsFactHierarchy)) { + return false; + } + const Value* types = field(*object, "requested_fact_types"); + if (types) { + if (types->kind != Value::Kind::Array) return false; + capabilities.requestedFactTypes.clear(); + capabilities.requestedFactTypes.reserve(types->items.size()); + for (const Value& item : types->items) { + if (item.kind != Value::Kind::String || item.text.empty()) return false; + capabilities.requestedFactTypes.push_back(item.text); + } + } + const Value* fields = field(*object, "requested_fact_fields"); + if (fields) { + if (fields->kind != Value::Kind::Array) return false; + capabilities.requestedFactFields.clear(); + capabilities.requestedFactFields.reserve(fields->items.size()); + for (const Value& item : fields->items) { + if (item.kind != Value::Kind::String || item.text.empty()) return false; + capabilities.requestedFactFields.push_back(item.text); + } + } + const Value* maximumRows = field(*object, "maximum_projected_rows"); + if (maximumRows) { + if (maximumRows->kind != Value::Kind::Number || + maximumRows->number < 0.0 || + maximumRows->number > + static_cast(std::numeric_limits::max()) || + std::floor(maximumRows->number) != maximumRows->number) { + return false; + } + capabilities.maximumProjectedRows = + static_cast(maximumRows->number); + } + if (capabilities.needsFactProjection && + (capabilities.requestedFactTypes.empty() || + capabilities.maximumProjectedRows == 0)) { + return false; + } + const Value* constraints = field(*object, "argument_constraints"); + if (constraints) { + if (constraints->kind != Value::Kind::Array) return false; + contract.argumentConstraints.clear(); + contract.argumentConstraints.reserve(constraints->items.size()); + for (const Value& item : constraints->items) { + if (item.kind != Value::Kind::Object) return false; + std::string name; + std::string kind; + const Value* index = field(item, "index"); + if (!text(item, "name", name) || !text(item, "kind", kind) || + !index || index->kind != Value::Kind::Number || + index->number < 0.0 || index->number > static_cast(std::numeric_limits::max()) || + std::floor(index->number) != index->number) { + return false; + } + NativeArgumentConstraint constraint; + constraint.name = std::move(name); + constraint.positionalIndex = static_cast(index->number); + if (kind == "string_option") constraint.kind = NativeArgumentConstraintKind::StringOption; + else if (kind == "unit_interval") constraint.kind = NativeArgumentConstraintKind::UnitInterval; + else if (kind == "positive_finite") constraint.kind = NativeArgumentConstraintKind::PositiveFinite; + else if (kind == "string_array") constraint.kind = NativeArgumentConstraintKind::StringArray; + else if (kind == "boolean_text") constraint.kind = NativeArgumentConstraintKind::BooleanText; + else return false; + const Value* required = field(item, "required"); + if (required) { + if (required->kind != Value::Kind::Bool) return false; + constraint.required = required->boolean; + } + const Value* values = field(item, "values"); + if (values) { + if (values->kind != Value::Kind::Array) return false; + constraint.allowedValues.reserve(values->items.size()); + for (const Value& value : values->items) { + if (value.kind != Value::Kind::String || value.text.empty()) return false; + constraint.allowedValues.push_back(value.text); + } + } + if (constraint.kind == NativeArgumentConstraintKind::StringOption && + constraint.allowedValues.empty()) return false; + contract.argumentConstraints.push_back(std::move(constraint)); + } + } + return true; + }; + + NativeModuleManifest parsed; + parsed.moduleName = std::move(module); + parsed.abiVersion = 1; + if (!parseContract(field(root, "capabilities"), parsed.defaultContract)) { + error = "invalid capabilities"; + return false; + } + const Value* functions = field(root, "functions"); + if (functions) { + if (functions->kind != Value::Kind::Object) { + error = "functions must be an object"; + return false; + } + for (const auto& item : functions->fields) { + if (item.first.empty()) { + error = "function name cannot be empty"; + return false; + } + NativeContract contract = parsed.defaultContract; + if (!parseContract(&item.second, contract)) { + error = "invalid function contract for '" + item.first + "'"; + return false; + } + parsed.functions.emplace(item.first, std::move(contract)); + } + } + manifest = std::move(parsed); + return true; +} + +#if 0 // Obsolete hard-coded native option contract; manifests own this metadata. + option("lexical_algorithm", 3, {"path", "wup", "wu_palmer", "Wu-Palmer", "Wu Palmer", "resnik", "jiang_conrath", "Jiang-Conrath", "Jiang Conrath", "lin", "edit", "Leacock-Chodorow", "Leacock–Chodorow", "Leacock Chodorow", "leacock_chodorow", "lch"}); +#endif +std::vector nativeLibraryFileNames(const std::string& moduleName) { +#if defined(_WIN32) + return {moduleName + ".dll", "felidae_" + moduleName + ".dll"}; +#elif defined(__APPLE__) + return {"lib" + moduleName + ".dylib", "libfelidae_" + moduleName + ".dylib", moduleName + ".dylib"}; +#else + return {"lib" + moduleName + ".so", "libfelidae_" + moduleName + ".so", moduleName + ".so"}; +#endif +} + +bool hasNativeLibraryExtension(const std::filesystem::path& path) { + std::string extension = lowerText(path.extension().string()); +#if defined(_WIN32) + return extension == ".dll"; +#elif defined(__APPLE__) + return extension == ".dylib" || extension == ".so"; +#else + return extension == ".so"; +#endif +} + +void* openSharedLibrary(const std::filesystem::path& path) { +#if defined(__EMSCRIPTEN__) + (void)path; + return nullptr; +#elif defined(_WIN32) + HMODULE handle = LoadLibraryW(path.wstring().c_str()); + return reinterpret_cast(handle); +#else + return dlopen(path.string().c_str(), RTLD_NOW | RTLD_LOCAL); +#endif +} + +std::string sharedLibraryError() { +#if defined(__EMSCRIPTEN__) + return "native packages are unsupported in the Felidae WASM runtime"; +#elif defined(_WIN32) + DWORD code = GetLastError(); + if (code == 0) return "unknown loader error"; + LPSTR buffer = nullptr; + DWORD size = FormatMessageA( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + code, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&buffer), + 0, + nullptr); + std::string message = size && buffer ? std::string(buffer, size) : ("Windows loader error " + std::to_string(code)); + if (buffer) LocalFree(buffer); + return message; +#else + const char* error = dlerror(); + return error ? std::string(error) : "unknown loader error"; +#endif +} + +void closeSharedLibrary(void* handle) { + if (!handle) return; +#if defined(_WIN32) + FreeLibrary(reinterpret_cast(handle)); +#else + dlclose(handle); +#endif +} + +void* findSharedLibrarySymbol(void* handle, const char* name) { + if (!handle) return nullptr; +#if defined(_WIN32) + return reinterpret_cast(GetProcAddress(reinterpret_cast(handle), name)); +#else + return dlsym(handle, name); +#endif +} + +std::string nativeModuleNameFromPath(const std::filesystem::path& path) { + std::string stem = path.stem().string(); + const std::string felidaePrefix = "felidae_"; + const std::string libFelidaePrefix = "libfelidae_"; + const std::string libPrefix = "lib"; + if (stem.rfind(libFelidaePrefix, 0) == 0) return stem.substr(libFelidaePrefix.size()); + if (stem.rfind(felidaePrefix, 0) == 0) return stem.substr(felidaePrefix.size()); + if (stem.rfind(libPrefix, 0) == 0) return stem.substr(libPrefix.size()); + return stem; +} + +} // namespace Felidae diff --git a/src/NativeRuntime.h b/src/NativeRuntime.h new file mode 100644 index 0000000..5966189 --- /dev/null +++ b/src/NativeRuntime.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Felidae { + +using NativeCallFn = char* (*)(const char*, const char*); +using NativeFreeFn = void (*)(char*); +using NativeManifestFn = const char* (*)(); + +struct NativeCapabilities { + bool needsFactProjection = false; + bool needsFactHierarchy = false; + bool pure = false; + bool threadSafe = false; + bool supportsBatch = false; + // Whether this contract can consume a FactSelection cursor. The JSON + // ABI still receives a bounded materialized projection; keeping this on + // the contract prevents the interpreter from guessing from module names. + bool acceptsFactSelections = false; + // A selection cardinality request can be answered from its cursor without + // materializing the selected facts for the native boundary. + bool selectionCardinality = false; + std::vector requestedFactTypes; + std::vector requestedFactFields; + std::size_t maximumProjectedRows = 0; +}; + +enum class NativeArgumentConstraintKind { + StringOption, + UnitInterval, + PositiveFinite, + StringArray, + BooleanText, +}; + +struct NativeArgumentConstraint { + std::string name; + std::size_t positionalIndex = 0; + NativeArgumentConstraintKind kind = NativeArgumentConstraintKind::StringOption; + bool required = false; + std::vector allowedValues; +}; + +struct NativeContract { + NativeCapabilities capabilities; + std::vector argumentConstraints; +}; + +struct NativeModuleManifest { + std::string moduleName; + std::uint32_t abiVersion = 0; + NativeContract defaultContract; + std::unordered_map functions; + + const NativeContract& contractFor(const std::string& functionName) const; +}; + +struct NativeLibrary { + std::filesystem::path path; + std::string moduleName; + void* handle = nullptr; + NativeCallFn call = nullptr; + NativeFreeFn free = nullptr; + NativeModuleManifest manifest; +}; + +bool parseNativeModuleManifest(const std::string& json, + NativeModuleManifest& manifest, + std::string& error); +std::vector nativeLibraryFileNames(const std::string& moduleName); +bool hasNativeLibraryExtension(const std::filesystem::path& path); +void* openSharedLibrary(const std::filesystem::path& path); +std::string sharedLibraryError(); +void closeSharedLibrary(void* handle); +void* findSharedLibrarySymbol(void* handle, const char* name); +std::string nativeModuleNameFromPath(const std::filesystem::path& path); + +} // namespace Felidae diff --git a/src/ParserMetrics.h b/src/ParserMetrics.h new file mode 100644 index 0000000..7a935f2 --- /dev/null +++ b/src/ParserMetrics.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include + +namespace Felidae { + +// Runtime counters shared by direct integer parse entry points. They are +// intentionally independent of any token-classification implementation. +struct ParserMetrics { + std::size_t tokensLexed = 0; + std::size_t iterations = 0; + std::size_t peakRecursionDepth = 0; + std::size_t backtrackingAttempts = 0; + std::size_t operatorCandidateLookups = 0; + std::size_t operatorCandidatesScored = 0; + + ParserMetrics& operator+=(const ParserMetrics& other) { + tokensLexed += other.tokensLexed; + iterations += other.iterations; + peakRecursionDepth = std::max(peakRecursionDepth, other.peakRecursionDepth); + backtrackingAttempts += other.backtrackingAttempts; + operatorCandidateLookups += other.operatorCandidateLookups; + operatorCandidatesScored += other.operatorCandidatesScored; + return *this; + } +}; + +} // namespace Felidae diff --git a/src/form/BinaryIr.cpp b/src/form/BinaryIr.cpp deleted file mode 100644 index 9896663..0000000 --- a/src/form/BinaryIr.cpp +++ /dev/null @@ -1,347 +0,0 @@ -#include "BinaryIr.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae { -namespace { - -constexpr std::array kMagic{'F', 'E', 'L', 'B', 'I', 'R', '\0', '\0'}; -constexpr std::uint32_t kEndian = 0x01020304u; -constexpr std::uint32_t kMaximumItems = 1u << 24; -constexpr std::uint64_t kMaximumBytes = 256ull * 1024ull * 1024ull; -constexpr std::size_t kMinimumHeaderBytes = 8 + 4 + 4 + 4 + 4 + 4 + 4 + 4; - -template void writeLe(std::ostream &out, T value) { - static_assert(std::is_integral_v); - using U = std::make_unsigned_t; - const auto raw = static_cast(value); - for (std::size_t index = 0; index < sizeof(T); ++index) { - out.put(static_cast((raw >> (index * 8u)) & 0xffu)); - } - if (!out) - throw IrError("cannot write FELBIR"); -} - -template T readLe(std::istream &in) { - static_assert(std::is_integral_v); - using U = std::make_unsigned_t; - U raw = 0; - for (std::size_t index = 0; index < sizeof(T); ++index) { - const auto byte = in.get(); - if (byte == EOF) - throw IrError("FELBIR is truncated"); - raw |= static_cast(static_cast(byte)) << (index * 8u); - } - return static_cast(raw); -} - -std::uint32_t count(std::size_t value, const char *name) { - if (value > kMaximumItems) - throw IrError(std::string("FELBIR ") + name + " exceeds its limit"); - return static_cast(value); -} - -void writePieces(std::ostream &out, std::span pieces) { - writeLe(out, count(pieces.size(), "piece count")); - for (const auto piece : pieces) - writeLe(out, piece); -} - -PieceSequence readPieces(std::istream &in, bool requireNonempty) { - const auto size = readLe(in); - if ((requireNonempty && size == 0) || size > kMaximumItems) { - throw IrError("FELBIR PieceId sequence is invalid"); - } - PieceSequence pieces; - pieces.reserve(size); - for (std::uint32_t index = 0; index < size; ++index) - pieces.push_back(readLe(in)); - return pieces; -} - -void writeSpan(std::ostream &out, const IrSourceMapEntry::Span &span) { - writeLe(out, span.startLine); - writeLe(out, span.startColumn); - writeLe(out, span.endLine); - writeLe(out, span.endColumn); -} - -IrSourceMapEntry::Span readSpan(std::istream &in) { - return {readLe(in), readLe(in), - readLe(in), readLe(in)}; -} - -void writeSymbols(std::ostream &out, std::span symbols) { - writeLe(out, count(symbols.size(), "symbol count")); - for (const auto symbol : symbols) - writeLe(out, static_cast(symbol)); -} - -std::vector readSymbols(std::istream &in) { - const auto size = readLe(in); - if (size > kMaximumItems) - throw IrError("FELBIR symbol count exceeds its limit"); - std::vector symbols; - symbols.reserve(size); - for (std::uint32_t index = 0; index < size; ++index) - symbols.push_back(readLe(in)); - return symbols; -} - -void writeProgram(std::ostream &out, const FelidaeIr &program) { - writeLe(out, count(program.registerCount, "register count")); - writeLe(out, count(program.words.size(), "code word count")); - writeLe(out, - count(program.constants.size(), "constant count")); - writeLe(out, count(program.texts.size(), "text count")); - writeLe(out, count(program.symbols.size(), "symbol count")); - writeLe(out, - count(program.sourceMap.size(), "source-map count")); - for (const auto word : program.words) - writeLe(out, word); - for (const auto &constant : program.constants) { - writeLe(out, static_cast(constant.kind)); - writeLe(out, constant.value); - } - for (const auto &text : program.texts) - writePieces(out, text); - for (const auto symbol : program.symbols) - writeLe(out, static_cast(symbol)); - for (const auto &entry : program.sourceMap) { - writeLe(out, - count(entry.instructionWord, "source-map offset")); - writeSpan(out, entry.sourceSpan); - } -} - -FelidaeIr readProgram(std::istream &in) { - FelidaeIr program; - program.registerCount = readLe(in); - const auto codeCount = readLe(in); - const auto constantCount = readLe(in); - const auto textCount = readLe(in); - const auto symbolCount = readLe(in); - const auto sourceCount = readLe(in); - if (codeCount > kMaximumItems || constantCount > kMaximumItems || - textCount > kMaximumItems || symbolCount > kMaximumItems || - sourceCount > kMaximumItems) { - throw IrError("FELBIR program table exceeds its limit"); - } - program.words.reserve(codeCount); - for (std::uint32_t index = 0; index < codeCount; ++index) - program.words.push_back(readLe(in)); - program.constants.reserve(constantCount); - for (std::uint32_t index = 0; index < constantCount; ++index) { - const auto rawKind = readLe(in); - if (rawKind > static_cast(IrConstantKind::Text)) - throw IrError("FELBIR constant kind is invalid"); - program.constants.push_back( - {static_cast(rawKind), readLe(in)}); - } - program.texts.reserve(textCount); - for (std::uint32_t index = 0; index < textCount; ++index) - program.texts.push_back(readPieces(in, false)); - program.symbols.reserve(symbolCount); - for (std::uint32_t index = 0; index < symbolCount; ++index) - program.symbols.push_back(readLe(in)); - program.sourceMap.reserve(sourceCount); - for (std::uint32_t index = 0; index < sourceCount; ++index) - program.sourceMap.push_back({readLe(in), readSpan(in)}); - return program; -} - -} // namespace - -void writeBinaryIr(const std::filesystem::path &path, - const VerifiedIrModule &verified) { - const auto &module = verified.get(); - const auto temporary = - path.string() + ".tmp." + - std::to_string( - std::chrono::steady_clock::now().time_since_epoch().count()); - try { - std::ofstream out(temporary, std::ios::binary | std::ios::trunc); - if (!out) - throw IrError("cannot create temporary FELBIR"); - out.write(kMagic.data(), static_cast(kMagic.size())); - constexpr std::string_view languageVersion = LANGUAGE_VERSION; - writeLe( - out, count(languageVersion.size(), "language version size")); - out.write(languageVersion.data(), - static_cast(languageVersion.size())); - writeLe(out, kEndian); - writeLe(out, count(module.sentencePieceModelIdentity.size(), - "model identity size")); - out.write( - module.sentencePieceModelIdentity.data(), - static_cast(module.sentencePieceModelIdentity.size())); - writeLe(out, - static_cast(module.entryProcedure)); - writeLe(out, - count(module.procedures.size(), "procedure count")); - writeLe(out, - count(module.factTypes.size(), "fact-type count")); - writeLe( - out, count(module.symbolTable.size(), "symbol table count")); - writeProgram(out, module.ir); - std::vector procedures; - procedures.reserve(module.procedures.size()); - for (const auto &[symbol, _] : module.procedures) - procedures.push_back(symbol); - std::sort(procedures.begin(), procedures.end()); - for (const auto symbol : procedures) { - const auto &procedure = module.procedures.at(symbol); - writeLe(out, static_cast(symbol)); - writeSymbols(out, procedure.positionalParameters); - writeSymbols(out, procedure.namedParameters); - writeSpan(out, procedure.sourceSpan); - writeProgram(out, procedure.ir); - } - for (const auto &type : module.factTypes) { - writeLe(out, static_cast(type.symbol)); - writeSymbols(out, type.parents); - writeLe(out, - count(type.indexes.size(), "fact index count")); - for (const auto &index : type.indexes) - writeSymbols(out, index); - writeSpan(out, type.sourceSpan); - } - for (const auto &pieces : module.symbolTable) - writePieces(out, pieces); - out.close(); - if (!out) - throw IrError("cannot write FELBIR"); - std::error_code error; - std::filesystem::rename(temporary, path, error); - if (error) - throw IrError("cannot replace FELBIR: " + error.message()); - } catch (...) { - std::error_code ignored; - std::filesystem::remove(temporary, ignored); - throw; - } -} - -VerifiedIrModule -loadBinaryIr(const std::filesystem::path &path, - const std::string &expectedSentencePieceModelIdentity) { - std::ifstream in(path, std::ios::binary); - if (!in) - throw IrError("cannot open FELBIR: " + path.string()); - in.seekg(0, std::ios::end); - const auto end = in.tellg(); - if (end < 0 || static_cast(end) < kMinimumHeaderBytes) - throw IrError("FELBIR is truncated"); - if (static_cast(end) > kMaximumBytes) - throw IrError("FELBIR exceeds its byte limit"); - in.seekg(0); - std::array magic{}; - in.read(magic.data(), static_cast(magic.size())); - if (magic != kMagic) - throw IrError("FELBIR magic is invalid"); - const auto versionSize = readLe(in); - if (versionSize == 0 || versionSize > 64) - throw IrError("FELBIR version field is invalid"); - std::string fileVersion(versionSize, '\0'); - in.read(fileVersion.data(), versionSize); - if (!in) - throw IrError("FELBIR version field is truncated"); - if (fileVersion != LANGUAGE_VERSION) - throw IrError("FELBIR version is unsupported"); - if (readLe(in) != kEndian) - throw IrError("FELBIR endian marker is invalid"); - const auto identitySize = readLe(in); - if (identitySize == 0 || identitySize > 256) - throw IrError("FELBIR model identity is invalid"); - std::string modelIdentity(identitySize, '\0'); - in.read(modelIdentity.data(), identitySize); - if (!in) - throw IrError("FELBIR model identity is truncated"); - if (modelIdentity != expectedSentencePieceModelIdentity) - throw IrError("FELBIR SentencePiece model identity does not match this VM"); - IrModule module; - module.sentencePieceModelIdentity = std::move(modelIdentity); - module.entryProcedure = readLe(in); - const auto procedureCount = readLe(in); - const auto factCount = readLe(in); - const auto symbolCount = readLe(in); - if (procedureCount == 0 || procedureCount > kMaximumItems || - factCount > kMaximumItems || symbolCount == 0 || - symbolCount > kMaximumItems) - throw IrError("FELBIR module count is invalid"); - module.ir = readProgram(in); - for (std::uint32_t index = 0; index < procedureCount; ++index) { - const auto symbol = readLe(in); - IrProcedure procedure; - procedure.positionalParameters = readSymbols(in); - procedure.namedParameters = readSymbols(in); - procedure.sourceSpan = readSpan(in); - procedure.ir = readProgram(in); - if (!module.procedures.emplace(symbol, std::move(procedure)).second) - throw IrError("FELBIR procedure is duplicated"); - } - module.factTypes.reserve(factCount); - for (std::uint32_t index = 0; index < factCount; ++index) { - IrFactType type; - type.symbol = readLe(in); - type.parents = readSymbols(in); - const auto indexCount = readLe(in); - if (indexCount > kMaximumItems) - throw IrError("FELBIR fact index count is invalid"); - type.indexes.reserve(indexCount); - for (std::uint32_t item = 0; item < indexCount; ++item) - type.indexes.push_back(readSymbols(in)); - type.sourceSpan = readSpan(in); - module.factTypes.push_back(std::move(type)); - } - module.symbolTable.reserve(symbolCount); - for (std::uint32_t index = 0; index < symbolCount; ++index) - module.symbolTable.push_back(readPieces(in, true)); - if (in.peek() != EOF) - throw IrError("FELBIR has trailing data"); - return verifyIrModule(std::move(module)); -} - -bool containsRuntimeSemanticOperation(const VerifiedIrModule &verified) { - const auto &module = verified.get(); - const auto contains = [](const FelidaeIr &program) { - for (std::size_t pc = 0; pc < program.words.size(); - pc += irInstructionWidth(program, pc)) { - if (static_cast(program.words[pc]) == IrOpcode::SemanticEval) - return true; - } - return false; - }; - if (contains(module.ir)) - return true; - for (const auto &[_, procedure] : module.procedures) - if (contains(procedure.ir)) - return true; - return false; -} - -VmDisplayContext makeIrDisplayContext(const VerifiedIrModule &verified, - VmTextDecoder decoder) { - VmDisplayContext context; - context.textDecoder = decoder; - context.symbolDecoder = [module = verified, - decoder = std::move(decoder)](IrSymbolRef symbol) { - if (!decoder) - return std::string{}; - try { - return decoder(irSymbolPieces(module.get(), symbol)); - } catch (const IrError &) { - return std::string{}; - } - }; - return context; -} - -} // namespace Felidae diff --git a/src/form/BinaryIr.h b/src/form/BinaryIr.h deleted file mode 100644 index 0a378cb..0000000 --- a/src/form/BinaryIr.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include "IrModule.h" -#include "../Version.h" - -#include - -namespace Felidae { - -inline constexpr const char kBinaryIrExtension[] = ".bin"; -// FELBIR embeds and checks LANGUAGE_VERSION (Version.h) directly as its -// compatibility marker. There is no separate binary-format version number to -// keep in sync -- Version.h is the one source of truth for every version -// this project reports, including this one. - -// The writer consumes a module already verified by the compiler boundary. -// The loader parses hostile bytes, checks the exact SentencePiece identity, -// verifies once, and returns the executable module. -void writeBinaryIr(const std::filesystem::path& path, const VerifiedIrModule& module); -VerifiedIrModule loadBinaryIr(const std::filesystem::path& path, - const std::string& expectedSentencePieceModelIdentity); -bool containsRuntimeSemanticOperation(const VerifiedIrModule& module); -VmDisplayContext makeIrDisplayContext(const VerifiedIrModule& module, - VmTextDecoder decoder); - -} // namespace Felidae diff --git a/src/form/BuiltinOperation.h b/src/form/BuiltinOperation.h deleted file mode 100644 index 1c0d5b3..0000000 --- a/src/form/BuiltinOperation.h +++ /dev/null @@ -1,477 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace Felidae { - -// Stable semantic IDs shared by the parser, executable IR, verifier, and VM. -// These values identify operations; source spelling remains SentencePiece -// data and is resolved only by the compiler. -enum class BuiltinId : std::uint16_t { - Unknown = 0, - Throw, - Type, - Instanceof, - Count, - Sum, - Average, - Min, - Max, - Sort, - Search, - Contains, - Lower, - Upper, - Length, - ParseDoc, - StrLen, - StrContains, - StrConcat, - StrJoin, - StrLower, - StrUpper, - StrTrim, - StrSplit, - StrReplace, - StrStartsWith, - StrEndsWith, - ArrayGet, - ArrayLen, - ArrayPush, - FnArray, - FnPair, - FnTuple, - PairFirst, - PairSecond, - ConsoleReadLine, - ConsoleInput, - ConsoleInputNumber, - ConsoleWriteLine, - ConsoleWrite, - SystemPrint, - SystemPrintf, - SystemRun, - FileReadFile, - FileReadLines, - FileReadLine, - FileWriteFile, - FileWriteLines, - FileAppendFile, - FileExists, - FileDeleteFile, - CommonAncestors, - AncestorAnalysis, - PropagateFact, - JsonObject, - JsonParse, - JsonGet, - JsonHas, - JsonKeys, - JsonSet, - JsonRemove, - JsonToText, - VisualizeGraphJson, - ThreadCreateThread, - ThreadStart, - ThreadPause, - ThreadStop, - ThreadStatus, - ThreadResult, - MathPi, - MathE, - MathRandom, - MathPow, - MathAtan2, - MathSqrt, - MathSin, - MathCos, - MathTan, - MathAsin, - MathAcos, - MathAtan, - MathLog, - MathLog10, - MathExp, - MathAbs, - MathFloor, - MathCeil, - MathRound, - MathAdd, - MathSub, - MathMul, - MathDiv, - MathMod, - ReasoningContrary, - ReasoningProve, - ReasoningGrade, - ReasoningDecide, - MlSigmoid, - MlRelu, - MlDot, - MlMeanSquaredError, - OverloadAnnotation, - MatcherAnnotation, - MixfixAnnotation, - CsvParse, - CsvToFacts, - CsvToText, - CsvToFelidaeFacts, - GroupValidate, - GroupClosed, - GroupAssociative, - GroupIdentity, - GroupInverse, - GroupCommutative, - GroupAbelian, - SetUnion, - SetIntersection, - SetIntersectionBy, - SetDifference, - SetDifferenceBy, - SetSymmetricDifference, - SetSymmetricDifferenceBy, - SetEquals, - SetEqualsBy, - SetSubset, - SetSubsetBy, - SetSuperset, - SetDisjoint, - SetDisjointBy, - SetCardinality, - SetContains, - SetContainsBy, - // Compiler-only fact/query operations. These have no public free-function - // spelling; Type.* lowering emits them directly into verified IR. - ArrayLimit, - FactInsert, - FactUpdate, - FactDelete, - FactJoin, - FactProject, - FactAggregate, - FactSearch, - FactSetCombine, - // Compiler-synthesized only (see desugarWhereGuardedClauses in - // IrCodeGenerator.cpp): a where-guarded clause with no `else` compiles its - // implicit else branch to this call instead of a compile-time rejection, - // so a failed guard throws a clear runtime error rather than falling - // through silently. Never spelled directly in source. - WhereGuardFailed, - Last = WhereGuardFailed -}; - -// Operations currently executed as direct RegisterVm library calls. This -// table is the shared arity/name contract for compiler lowering and IR -// verification; extending it must be accompanied by a real implementation. -constexpr std::optional -builtinOperationArity(BuiltinId operation) noexcept { - switch (operation) { - case BuiltinId::Count: - case BuiltinId::Sum: - case BuiltinId::Average: - case BuiltinId::Min: - case BuiltinId::Max: - case BuiltinId::Sort: - case BuiltinId::Lower: - case BuiltinId::Upper: - case BuiltinId::Length: - case BuiltinId::StrLen: - case BuiltinId::StrLower: - case BuiltinId::StrUpper: - case BuiltinId::StrTrim: - case BuiltinId::ArrayLen: - case BuiltinId::FileReadFile: - case BuiltinId::JsonParse: - case BuiltinId::JsonKeys: - case BuiltinId::JsonToText: - case BuiltinId::CsvParse: - case BuiltinId::CsvToText: - case BuiltinId::SetUnion: - case BuiltinId::SetIntersection: - case BuiltinId::SetDifference: - case BuiltinId::SetSymmetricDifference: - case BuiltinId::SetEquals: - case BuiltinId::SetSubset: - case BuiltinId::SetSuperset: - case BuiltinId::SetDisjoint: - case BuiltinId::SetCardinality: - case BuiltinId::MathSqrt: - case BuiltinId::MathSin: - case BuiltinId::MathCos: - case BuiltinId::MathTan: - case BuiltinId::MathAsin: - case BuiltinId::MathAcos: - case BuiltinId::MathAtan: - case BuiltinId::MathLog: - case BuiltinId::MathLog10: - case BuiltinId::MathExp: - case BuiltinId::MathAbs: - case BuiltinId::MathFloor: - case BuiltinId::MathCeil: - case BuiltinId::MathRound: - case BuiltinId::FactDelete: - return 1; - case BuiltinId::ArrayGet: - case BuiltinId::ArrayPush: - case BuiltinId::Search: - case BuiltinId::Contains: - case BuiltinId::StrContains: - case BuiltinId::StrConcat: - case BuiltinId::StrJoin: - case BuiltinId::StrSplit: - case BuiltinId::StrStartsWith: - case BuiltinId::StrEndsWith: - case BuiltinId::JsonGet: - case BuiltinId::JsonHas: - case BuiltinId::JsonRemove: - case BuiltinId::CsvToFacts: - case BuiltinId::CsvToFelidaeFacts: - case BuiltinId::GroupClosed: - case BuiltinId::GroupAssociative: - case BuiltinId::GroupCommutative: - case BuiltinId::SetIntersectionBy: - case BuiltinId::SetDifferenceBy: - case BuiltinId::SetSymmetricDifferenceBy: - case BuiltinId::SetEqualsBy: - case BuiltinId::SetSubsetBy: - case BuiltinId::SetDisjointBy: - case BuiltinId::SetContains: - case BuiltinId::ArrayLimit: - case BuiltinId::FactUpdate: - case BuiltinId::AncestorAnalysis: - case BuiltinId::FactProject: - case BuiltinId::MathRandom: - case BuiltinId::MathPow: - case BuiltinId::MathAtan2: - return 2; - case BuiltinId::FactInsert: - case BuiltinId::FactAggregate: - case BuiltinId::FactSearch: - case BuiltinId::FactSetCombine: - return 3; - case BuiltinId::FactJoin: - return 5; - case BuiltinId::JsonSet: - case BuiltinId::StrReplace: - case BuiltinId::GroupValidate: - case BuiltinId::GroupIdentity: - case BuiltinId::GroupInverse: - case BuiltinId::GroupAbelian: - case BuiltinId::SetContainsBy: - case BuiltinId::PropagateFact: - return 3; - case BuiltinId::WhereGuardFailed: - case BuiltinId::MathPi: - case BuiltinId::MathE: - return 0; - default: - return std::nullopt; - } -} - -constexpr std::optional -builtinOperationArgumentIndex(BuiltinId operation, - std::string_view name) noexcept { - switch (operation) { - case BuiltinId::Count: - case BuiltinId::Sum: - case BuiltinId::Average: - case BuiltinId::Min: - case BuiltinId::Max: - case BuiltinId::Sort: - case BuiltinId::ArrayLen: - return name == "data" ? std::optional{0} : std::nullopt; - case BuiltinId::Lower: - case BuiltinId::Upper: - case BuiltinId::Length: - case BuiltinId::StrLen: - case BuiltinId::StrLower: - case BuiltinId::StrUpper: - case BuiltinId::StrTrim: - return name == "data" ? std::optional{0} : std::nullopt; - case BuiltinId::FileReadFile: - return name == "file" ? std::optional{0} : std::nullopt; - case BuiltinId::ArrayGet: - if (name == "data") - return 0; - return name == "position" ? std::optional{1} - : std::nullopt; - case BuiltinId::ArrayPush: - if (name == "data") - return 0; - return name == "value" ? std::optional{1} : std::nullopt; - case BuiltinId::Search: - case BuiltinId::Contains: - if (name == "data" || name == "value") - return 0; - return name == "query" ? std::optional{1} : std::nullopt; - case BuiltinId::StrContains: - if (name == "data") - return 0; - return name == "needle" ? std::optional{1} : std::nullopt; - case BuiltinId::StrConcat: - if (name == "left") - return 0; - return name == "right" ? std::optional{1} : std::nullopt; - case BuiltinId::StrJoin: - case BuiltinId::StrSplit: - if (name == "data") - return 0; - return name == "delimiter" ? std::optional{1} - : std::nullopt; - case BuiltinId::StrStartsWith: - if (name == "data") - return 0; - return name == "prefix" ? std::optional{1} : std::nullopt; - case BuiltinId::StrEndsWith: - if (name == "data") - return 0; - return name == "suffix" ? std::optional{1} : std::nullopt; - case BuiltinId::StrReplace: - if (name == "data") - return 0; - if (name == "search") - return 1; - return name == "replacement" ? std::optional{2} - : std::nullopt; - case BuiltinId::JsonParse: - case BuiltinId::CsvParse: - return name == "data" ? std::optional{0} : std::nullopt; - case BuiltinId::JsonGet: - case BuiltinId::JsonHas: - case BuiltinId::JsonRemove: - if (name == "data") - return 0; - return name == "key" ? std::optional{1} : std::nullopt; - case BuiltinId::JsonKeys: - case BuiltinId::JsonToText: - return name == "data" ? std::optional{0} : std::nullopt; - case BuiltinId::JsonSet: - if (name == "data") - return 0; - if (name == "key") - return 1; - return name == "value" ? std::optional{2} : std::nullopt; - case BuiltinId::CsvToText: - return name == "data" ? std::optional{0} : std::nullopt; - case BuiltinId::CsvToFacts: - case BuiltinId::CsvToFelidaeFacts: - if (name == "data") - return 0; - return name == "type" ? std::optional{1} : std::nullopt; - case BuiltinId::GroupClosed: - case BuiltinId::GroupAssociative: - case BuiltinId::GroupCommutative: - case BuiltinId::GroupValidate: - case BuiltinId::GroupIdentity: - case BuiltinId::GroupInverse: - case BuiltinId::GroupAbelian: - if (name == "set") - return 0; - if (name == "table") - return 1; - return name == "identity" && - builtinOperationArity(operation).value_or(0) == 3 - ? std::optional{2} - : std::nullopt; - case BuiltinId::SetUnion: - case BuiltinId::SetIntersection: - case BuiltinId::SetDifference: - case BuiltinId::SetSymmetricDifference: - case BuiltinId::SetEquals: - case BuiltinId::SetSubset: - case BuiltinId::SetSuperset: - case BuiltinId::SetDisjoint: - return name == "sets" ? std::optional{0} : std::nullopt; - case BuiltinId::SetCardinality: - return name == "set" ? std::optional{0} : std::nullopt; - case BuiltinId::SetIntersectionBy: - case BuiltinId::SetDifferenceBy: - case BuiltinId::SetSymmetricDifferenceBy: - case BuiltinId::SetEqualsBy: - case BuiltinId::SetSubsetBy: - case BuiltinId::SetDisjointBy: - if (name == "sets") - return 0; - return name == "fields" ? std::optional{1} : std::nullopt; - case BuiltinId::SetContains: - case BuiltinId::SetContainsBy: - if (name == "set") - return 0; - if (name == "value") - return 1; - return operation == BuiltinId::SetContainsBy && name == "fields" - ? std::optional{2} - : std::nullopt; - case BuiltinId::MathSqrt: - case BuiltinId::MathSin: - case BuiltinId::MathCos: - case BuiltinId::MathTan: - case BuiltinId::MathAsin: - case BuiltinId::MathAcos: - case BuiltinId::MathAtan: - case BuiltinId::MathLog: - case BuiltinId::MathLog10: - case BuiltinId::MathExp: - case BuiltinId::MathAbs: - case BuiltinId::MathFloor: - case BuiltinId::MathCeil: - case BuiltinId::MathRound: - return name == "value" ? std::optional{0} : std::nullopt; - case BuiltinId::MathRandom: - if (name == "min") - return 0; - return name == "max" ? std::optional{1} : std::nullopt; - case BuiltinId::MathPow: - if (name == "base") - return 0; - return name == "exponent" ? std::optional{1} : std::nullopt; - case BuiltinId::MathAtan2: - if (name == "y") - return 0; - return name == "x" ? std::optional{1} : std::nullopt; - case BuiltinId::AncestorAnalysis: - if (name == "left") - return 0; - return name == "right" ? std::optional{1} : std::nullopt; - case BuiltinId::PropagateFact: - if (name == "parent") - return 0; - if (name == "child") - return 1; - return name == "changes" ? std::optional{2} : std::nullopt; - default: - return std::nullopt; - } -} - -inline std::optional> -builtinOperationArgumentOrder(BuiltinId operation, - std::span names) { - const auto arity = builtinOperationArity(operation); - if (!arity || names.size() != *arity) - return std::nullopt; - const bool named = !names.empty() && !names.front().empty(); - std::vector order; - order.reserve(*arity); - std::vector seen(*arity); - for (std::size_t index = 0; index < *arity; ++index) { - if (named != !names[index].empty()) - return std::nullopt; - const auto target = - named ? builtinOperationArgumentIndex(operation, names[index]) - : std::optional{index}; - if (!target || seen[*target]) - return std::nullopt; - seen[*target] = true; - order.push_back(*target); - } - return order; -} - -} // namespace Felidae diff --git a/src/form/IrModule.cpp b/src/form/IrModule.cpp deleted file mode 100644 index e19cee6..0000000 --- a/src/form/IrModule.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include "IrModule.h" - -#include -#include -#include -#include - -namespace Felidae { - -std::span irSymbolPieces(std::span symbols, - IrSymbolRef symbol) { - if (symbol == 0 || symbol > symbols.size()) { - throw IrError("IR module symbol index is outside its PieceId table"); - } - return symbols[static_cast(symbol - 1)]; -} - -std::span irSymbolPieces(const IrModule &module, - IrSymbolRef symbol) { - return irSymbolPieces(module.symbolTable, symbol); -} - -static void validateIrModule(const IrModule &module) { - if (module.symbolTable.empty()) - throw IrError("IR module has no SentencePiece symbol table"); - if (module.sentencePieceModelIdentity.empty()) - throw IrError("IR module has no SentencePiece model identity"); - std::set uniqueSymbols; - for (const auto &pieces : module.symbolTable) { - if (pieces.empty() || !uniqueSymbols.insert(pieces).second) { - throw IrError("IR module symbol table is empty or duplicated"); - } - } - const auto requireSymbol = [&](IrSymbolRef symbol) { - (void)irSymbolPieces(module, symbol); - }; - const auto verifyProgramSymbols = [&](const FelidaeIr &ir) { - for (const auto symbol : ir.symbols) - requireSymbol(symbol); - }; - verifyProgramSymbols(module.ir); - requireSymbol(module.entryProcedure); - for (const auto &[symbol, procedure] : module.procedures) { - requireSymbol(symbol); - verifyProgramSymbols(procedure.ir); - for (const auto parameter : procedure.positionalParameters) - requireSymbol(parameter); - for (const auto parameter : procedure.namedParameters) - requireSymbol(parameter); - } - for (const auto &type : module.factTypes) { - requireSymbol(type.symbol); - for (const auto parent : type.parents) - requireSymbol(parent); - for (const auto &index : type.indexes) - for (const auto field : index) - requireSymbol(field); - } - IrVerifier::verify(module.ir); - if (module.entryProcedure == 0 || - !module.procedures.contains(module.entryProcedure)) - throw IrError("compiler IR entry procedure is invalid"); - const auto verifyCalls = [&](const FelidaeIr &ir) { - for (std::size_t pc = 0; pc < ir.words.size();) { - const auto opcode = static_cast(ir.words[pc]); - if (opcode == IrOpcode::Call || opcode == IrOpcode::CallNamed || - opcode == IrOpcode::ForEachFact) { - const auto operand = opcode == IrOpcode::ForEachFact ? 3u : 2u; - const auto index = static_cast(ir.words[pc + operand]); - if (index >= ir.symbols.size() || - !module.procedures.contains(ir.symbols[index])) - throw IrError("compiler IR call references an unknown procedure"); - } - pc += irInstructionWidth(ir, pc); - } - }; - verifyCalls(module.ir); - for (const auto &[symbol, procedure] : module.procedures) { - if (symbol == 0) - throw IrError("compiler IR procedure symbol is invalid"); - if (procedure.positionalParameters.size() != - procedure.namedParameters.size()) - throw IrError("compiler IR procedure parameter metadata is inconsistent"); - std::unordered_set positional, named; - for (const auto parameter : procedure.positionalParameters) - if (parameter == 0 || !positional.insert(parameter).second) - throw IrError("compiler IR positional parameter metadata is invalid"); - for (const auto parameter : procedure.namedParameters) - if (parameter == 0 || !named.insert(parameter).second) - throw IrError("compiler IR named parameter metadata is invalid"); - IrVerifier::verify(procedure.ir); - verifyCalls(procedure.ir); - } - std::unordered_map types; - for (const auto &type : module.factTypes) - if (type.symbol == 0 || !types.emplace(type.symbol, &type).second) - throw IrError("compiler IR fact type is invalid or duplicated"); - for (const auto &type : module.factTypes) { - std::unordered_set parents; - for (const auto parent : type.parents) - if (parent == 0 || parent == type.symbol || !types.contains(parent) || - !parents.insert(parent).second) - throw IrError("compiler IR hierarchy parent is invalid"); - std::set> indexes; - for (const auto &index : type.indexes) { - std::unordered_set fields; - if (index.empty() || - !std::all_of(index.begin(), index.end(), [&](IrSymbolRef field) { - return field != 0 && fields.insert(field).second; - }) || - !indexes.insert(index).second) - throw IrError("compiler IR fact index is invalid or duplicated"); - } - } - std::unordered_set visiting, visited; - const auto visit = [&](auto &&self, IrSymbolRef type) -> void { - if (visited.contains(type)) - return; - if (!visiting.insert(type).second) - throw IrError("compiler IR hierarchy contains a cycle"); - for (const auto parent : types.at(type)->parents) - self(self, parent); - visiting.erase(type); - visited.insert(type); - }; - for (const auto &[symbol, _] : types) - visit(visit, symbol); -} - -VerifiedIrModule verifyIrModule(IrModule &&module) { - validateIrModule(module); - return VerifiedIrModule(std::move(module)); -} - -} // namespace Felidae diff --git a/src/form/IrModule.h b/src/form/IrModule.h deleted file mode 100644 index 43296cd..0000000 --- a/src/form/IrModule.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include "../FelidaeIr.h" - -#include -#include -#include - -namespace Felidae { - -struct IrFactType { - IrSymbolRef symbol = 0; - std::vector parents; - std::vector> indexes; - IrSourceMapEntry::Span sourceSpan; -}; - -// AST-free executable module shared by compiler, FELBIR writer, and VM. -struct IrModule { - FelidaeIr ir; // module initializer - std::unordered_map procedures; - std::vector factTypes; - // One-based runtime SymbolIndex values address this table. Each entry is - // the complete SentencePiece sequence; hashes are never symbol identity. - std::vector symbolTable; - std::string sentencePieceModelIdentity; - IrSymbolRef entryProcedure = 0; -}; - -class VerifiedIrModule { -public: - const IrModule &get() const noexcept { return *module_; } - const IrModule *operator->() const noexcept { return module_.get(); } - -private: - explicit VerifiedIrModule(IrModule module) - : module_(std::make_shared(std::move(module))) {} - std::shared_ptr module_; - friend VerifiedIrModule verifyIrModule(IrModule &&module); -}; - -// Authoritative executable-IR instruction decoder. It validates both fixed -// and variable-width instructions before returning their encoded word count. -std::size_t irInstructionWidth(const FelidaeIr &ir, std::size_t pc); -std::span irSymbolPieces(std::span symbols, - IrSymbolRef symbol); -std::span irSymbolPieces(const IrModule &module, - IrSymbolRef symbol); -VerifiedIrModule verifyIrModule(IrModule &&module); - -} // namespace Felidae diff --git a/src/form/LibTorchTensorRuntime.cpp b/src/form/LibTorchTensorRuntime.cpp deleted file mode 100644 index 800755d..0000000 --- a/src/form/LibTorchTensorRuntime.cpp +++ /dev/null @@ -1,169 +0,0 @@ -#include "LibTorchTensorRuntime.h" - -#include "TensorOperation.h" - -#include - -#include -#include -#include - -namespace Felidae { -namespace { - -torch::Tensor tensorFromValue(const VmValue &value) { - if (const auto tensor = std::get_if(&value)) { - if (!*tensor || !(*tensor)->storage) - throw IrError("tensor value has no LibTorch storage"); - return *(*tensor)->storage; - } - if (const auto number = std::get_if(&value)) { - if (!std::isfinite(*number)) - throw IrError("tensor numeric value must be finite"); - return torch::tensor(*number, - torch::TensorOptions().dtype(torch::kFloat64)); - } - if (const auto degree = std::get_if(&value)) - return torch::tensor(degree->value, - torch::TensorOptions().dtype(torch::kFloat64)); - if (const auto array = std::get_if(&value); array && *array) { - if ((*array)->values.empty()) - throw IrError("tensor array must not be empty"); - std::vector rows; - rows.reserve((*array)->values.size()); - for (const auto &item : (*array)->values) - rows.push_back(tensorFromValue(item)); - const auto shape = rows.front().sizes().vec(); - for (const auto &row : rows) - if (row.sizes().vec() != shape) - throw IrError("tensor array must be rectangular"); - return torch::stack(rows); - } - - throw IrError("tensor operation requires numeric data or a tensor value"); -} - -VmValue arrayFromTensor(const torch::Tensor &source) { - const auto tensor = source.to(torch::kCPU).to(torch::kFloat64).contiguous(); - if (!tensor.isfinite().all().item()) - throw IrError("tensor operation produced a non-finite result"); - if (tensor.dim() == 0) - return tensor.item(); - auto result = std::make_shared(); - result->values.reserve(static_cast(tensor.size(0))); - for (std::int64_t index = 0; index < tensor.size(0); ++index) - result->values.push_back(arrayFromTensor(tensor[index])); - return result; -} - -VmValue tensorValue(const torch::Tensor &source) { - auto tensor = source.to(torch::kCPU).to(torch::kFloat64).contiguous(); - if (!tensor.isfinite().all().item()) - throw IrError("tensor operation produced a non-finite result"); - auto result = std::make_shared(); - result->shape = tensor.sizes().vec(); - result->storage = std::make_shared(std::move(tensor)); - return result; -} - -VmValue shapeValue(const torch::Tensor &tensor) { - auto shape = std::make_shared(); - shape->values.reserve(static_cast(tensor.dim())); - for (const auto dimension : tensor.sizes()) - shape->values.emplace_back(static_cast(dimension)); - return shape; -} - -void requireEqualShapes(const torch::Tensor &left, const torch::Tensor &right, - std::string_view operation) { - if (left.sizes().vec() != right.sizes().vec()) - throw IrError(std::string(operation) + " requires equal tensor shapes"); -} - -} // namespace - -Value LibTorchTensorRuntime::evaluateTensor(TensorOperation operation, - std::span inputs, - std::span) { - if (operation >= TensorOperation::Count || - inputs.size() != tensorOperationArity(operation)) - throw IrError("tensor operation has an invalid operation ID or arity"); - - torch::InferenceMode guard; - const auto left = tensorFromValue(inputs[0]); - switch (operation) { - case TensorOperation::Size: - return static_cast(left.numel()); - case TensorOperation::Shape: - return shapeValue(left); - case TensorOperation::Dimensions: - return static_cast(left.dim()); - case TensorOperation::Sigmoid: - return tensorValue(torch::sigmoid(left)); - case TensorOperation::Relu: - return tensorValue(torch::relu(left)); - case TensorOperation::Transpose: - if (left.dim() != 2) - throw IrError("tensor.transpose requires a rank-2 tensor"); - return tensorValue(left.transpose(0, 1)); - case TensorOperation::IsSymmetric: - if (left.dim() != 2 || left.size(0) != left.size(1)) - return 0.0; - return left.equal(left.transpose(0, 1)) ? 1.0 : 0.0; - case TensorOperation::Clone: - return tensorValue(left.clone()); - case TensorOperation::Dot: { - const auto right = tensorFromValue(inputs[1]); - if (left.dim() != 1 || right.dim() != 1 || - left.sizes().vec() != right.sizes().vec()) - throw IrError("ml.dot requires equal-length rank-1 tensors"); - const auto result = torch::dot(left, right).item(); - if (!std::isfinite(result)) - throw IrError("ml.dot produced a non-finite result"); - return result; - } - case TensorOperation::MeanSquaredError: { - const auto right = tensorFromValue(inputs[1]); - requireEqualShapes(left, right, "ml.meanSquaredError"); - const auto result = torch::mse_loss(left, right).item(); - if (!std::isfinite(result)) - throw IrError("ml.meanSquaredError produced a non-finite result"); - return result; - } - case TensorOperation::Difference: { - const auto right = tensorFromValue(inputs[1]); - requireEqualShapes(left, right, "tensor.difference"); - return tensorValue(torch::abs(left - right)); - } - case TensorOperation::CosineSimilarity: { - const auto right = tensorFromValue(inputs[1]); - if (left.dim() != 1 || right.dim() != 1) - throw IrError("tensor.cosineSimilarity requires rank-1 tensors"); - requireEqualShapes(left, right, "tensor.cosineSimilarity"); - const auto denominator = - left.norm().item() * right.norm().item(); - if (denominator == 0.0) - throw IrError("tensor.cosineSimilarity requires non-zero tensors"); - const auto result = torch::dot(left, right).item() / denominator; - if (!std::isfinite(result)) - throw IrError("tensor.cosineSimilarity produced a non-finite result"); - return result; - } - case TensorOperation::Count: - break; - } - throw IrError("tensor operation is invalid"); -} - -Value LibTorchTensorRuntime::materializeTensor(const VmTensor &tensor) const { - if (!tensor.storage) - throw IrError("tensor value has no LibTorch storage"); - torch::InferenceMode guard; - return arrayFromTensor(*tensor.storage); -} - -std::string LibTorchTensorRuntime::displayTensor(const VmTensor &tensor) const { - return vmValueToDisplayString(materializeTensor(tensor)); -} - -} // namespace Felidae diff --git a/src/form/LibTorchTensorRuntime.h b/src/form/LibTorchTensorRuntime.h deleted file mode 100644 index 5d24d8f..0000000 --- a/src/form/LibTorchTensorRuntime.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "RegisterVm.h" - -namespace Felidae { - -// LibTorch implementation of RegisterVm's tensor boundary. The core VM keeps -// Torch headers out of its public value representation and remains buildable -// on explicitly unsupported targets. -class LibTorchTensorRuntime final : public TensorRuntime { -public: - Value evaluateTensor(TensorOperation operation, std::span inputs, - std::span symbolTable) override; - Value materializeTensor(const VmTensor &tensor) const; - std::string displayTensor(const VmTensor &tensor) const; -}; - -} // namespace Felidae diff --git a/src/form/NumericOperation.h b/src/form/NumericOperation.h deleted file mode 100644 index 0dd7bfd..0000000 --- a/src/form/NumericOperation.h +++ /dev/null @@ -1,118 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace Felidae { - -// Stable operand selector for the executable IR Numeric instruction. Ordinary -// operations preserve unrestricted floating-point results; only explicit -// predicates return the VM's numeric truth values 0.0 and 1.0. -enum class NumericOperation : std::uint8_t { - Min = 0, - Max, - Abs, - Diff, - Average, - WeightedAverage, - Clamp, - Floor, - Ceil, - Round, - Trunc, - Sqrt, - Cbrt, - Pow, - Exp, - Log, - Log10, - Lerp, - Sign, - Reciprocal, - Square, - Cube, - InRange, - IsFinite, - IsNan, - Count -}; - -constexpr std::size_t numericOperationArity(NumericOperation operation) { - switch (operation) { - case NumericOperation::Abs: - case NumericOperation::Floor: - case NumericOperation::Ceil: - case NumericOperation::Round: - case NumericOperation::Trunc: - case NumericOperation::Sqrt: - case NumericOperation::Cbrt: - case NumericOperation::Exp: - case NumericOperation::Log: - case NumericOperation::Log10: - case NumericOperation::Sign: - case NumericOperation::Reciprocal: - case NumericOperation::Square: - case NumericOperation::Cube: - case NumericOperation::IsFinite: - case NumericOperation::IsNan: - return 1; - case NumericOperation::Min: - case NumericOperation::Max: - case NumericOperation::Diff: - case NumericOperation::Average: - case NumericOperation::Pow: - return 2; - case NumericOperation::Clamp: - case NumericOperation::Lerp: - case NumericOperation::InRange: - return 3; - case NumericOperation::WeightedAverage: - return 4; - case NumericOperation::Count: - break; - } - return 0; -} - -inline std::optional -numericOperationForName(std::string_view name) { - struct Entry { - std::string_view name; - NumericOperation operation; - }; - static constexpr Entry entries[] = { - {"min", NumericOperation::Min}, - {"max", NumericOperation::Max}, - {"abs", NumericOperation::Abs}, - {"diff", NumericOperation::Diff}, - {"avg", NumericOperation::Average}, - {"weighted_avg", NumericOperation::WeightedAverage}, - {"clamp", NumericOperation::Clamp}, - {"floor", NumericOperation::Floor}, - {"ceil", NumericOperation::Ceil}, - {"round", NumericOperation::Round}, - {"trunc", NumericOperation::Trunc}, - {"sqrt", NumericOperation::Sqrt}, - {"cbrt", NumericOperation::Cbrt}, - {"pow", NumericOperation::Pow}, - {"exp", NumericOperation::Exp}, - {"log", NumericOperation::Log}, - {"log10", NumericOperation::Log10}, - {"lerp", NumericOperation::Lerp}, - {"sign", NumericOperation::Sign}, - {"reciprocal", NumericOperation::Reciprocal}, - {"square", NumericOperation::Square}, - {"cube", NumericOperation::Cube}, - {"in_range", NumericOperation::InRange}, - {"is_finite", NumericOperation::IsFinite}, - {"is_nan", NumericOperation::IsNan}, - }; - for (const auto &entry : entries) - if (entry.name == name) - return entry.operation; - return std::nullopt; -} - -} // namespace Felidae diff --git a/src/form/RegisterVm.cpp b/src/form/RegisterVm.cpp deleted file mode 100644 index 305a006..0000000 --- a/src/form/RegisterVm.cpp +++ /dev/null @@ -1,4473 +0,0 @@ -#include "RegisterVm.h" - -#include "IrModule.h" -#include "SemanticOperation.h" -#include "libs/Builtin.h" -#include "libs/Csv.h" -#include "libs/Db.h" -#include "libs/FactStorageCodec.h" -#ifdef FELIDAE_HAS_ROCKSDB -#include "libs/RocksDb.h" -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae { - -RuntimeValueKind runtimeValueKind(const VmValue &value) noexcept { - if (std::holds_alternative(value)) - return RuntimeValueKind::Nil; - if (std::holds_alternative(value)) - return RuntimeValueKind::Number; - if (std::holds_alternative(value)) - return RuntimeValueKind::Degree; - if (std::holds_alternative(value)) - return RuntimeValueKind::Text; - if (std::holds_alternative(value)) - return RuntimeValueKind::Symbol; - if (std::holds_alternative(value)) - return RuntimeValueKind::Array; - if (std::holds_alternative(value)) - return RuntimeValueKind::Map; - if (std::holds_alternative(value)) - return RuntimeValueKind::Fact; - if (std::holds_alternative(value)) - return RuntimeValueKind::Tensor; - return RuntimeValueKind::TextMap; -} - -std::size_t irInstructionWidth(const FelidaeIr &ir, std::size_t pc) { - if (pc >= ir.words.size() || ir.words[pc] >= kIrOpcodeCount) { - throw IrError("IR contains an invalid opcode"); - } - const auto bounded = [&](std::size_t width) { - if (width > ir.words.size() - pc) - throw IrError("IR instruction is truncated"); - return width; - }; - const auto opcode = static_cast(ir.words[pc]); - switch (opcode) { - case IrOpcode::End: - return bounded(1); - case IrOpcode::Jump: - return bounded(2); - case IrOpcode::LoadConst: - case IrOpcode::LoadSymbol: - case IrOpcode::StoreSymbol: - case IrOpcode::Move: - case IrOpcode::JumpIfFalse: - case IrOpcode::Return: - return bounded(3); - case IrOpcode::Add: - case IrOpcode::Sub: - case IrOpcode::Mul: - case IrOpcode::Div: - case IrOpcode::Mod: - case IrOpcode::GetField: - case IrOpcode::SetField: - case IrOpcode::Similarity: - case IrOpcode::HierarchyIsA: - case IrOpcode::HierarchyCommonAncestors: - case IrOpcode::TemporalRank: - case IrOpcode::MakeFact: - return bounded(4); - case IrOpcode::FactWhere: - return bounded(4); - // One extra operand beyond type/callback: a register holding a map of - // outer-scope values the callback's predicate closes over (0 = none). The - // callback procedure itself still takes only the row parameter plus this - // one capture map, not one parameter per captured name -- see - // FactDmlLowerer::iteration() in IrCodeGenerator.cpp. - case IrOpcode::ForEachFact: - return bounded(5); - case IrOpcode::Compare: - return bounded(5); - // result, five operand registers (left/right rows, left/right field - // text, kind), three symbol operands for the ephemeral "Joined" - // fact's synthesized type/left/right names -- see the FactJoin case in - // IrCodeGenerator.cpp's lowering. - case IrOpcode::FactJoin: - return bounded(10); - case IrOpcode::Membership: - return bounded(6); - case IrOpcode::Call: - case IrOpcode::Builtin: - case IrOpcode::SemanticEval: - case IrOpcode::Numeric: - case IrOpcode::Tensor: - case IrOpcode::MakeArray: - case IrOpcode::CallNamed: - case IrOpcode::MakeMap: { - bounded(4); - const auto stride = - opcode == IrOpcode::CallNamed || opcode == IrOpcode::MakeMap ? 2u : 1u; - const auto count = ir.words[pc + 3]; - if (count > (ir.words.size() - pc - 4) / stride) { - throw IrError("IR dynamic instruction is truncated"); - } - return 4 + static_cast(count) * stride; - } - case IrOpcode::Count: - break; - } - throw IrError("IR contains an invalid opcode"); -} - -VmDegree::VmDegree(double value) : value(value) { - if (!std::isfinite(value) || value < 0.0 || value > 1.0) - throw IrError("Degree must be finite and within [0,1]"); -} -namespace { - -#ifndef NDEBUG -bool vmTraceEnabled() { - static const bool enabled = [] { - const auto *value = std::getenv("FELIDAE_TRACE"); - return value != nullptr && *value != '\0' && std::string_view(value) != "0"; - }(); - return enabled; -} -#endif - -constexpr std::size_t kMaximumIrWords = 1'000'000; -constexpr std::size_t kMaximumRegisters = 65'536; -constexpr std::size_t kMaximumIrTableEntries = 1'000'000; -constexpr std::size_t kMaximumTextBytes = 16ull * 1024ull * 1024ull; - -IrOpcode opcodeAt(const FelidaeIr &ir, std::size_t index) { - if (ir.words[index] >= kIrOpcodeCount) { - throw IrError("IR contains an invalid opcode"); - } - return static_cast(ir.words[index]); -} - -void requireRegister(const FelidaeIr &ir, IrWord word) { - if (word >= ir.registerCount) - throw IrError("IR references an invalid register"); -} - -void requireInitialized(const std::vector &initialized, IrWord word) { - if (!initialized[word]) - throw IrError("IR reads an uninitialized register"); -} - -void requireFlowRead(const std::vector &initialized, IrWord registerId) { - if (!initialized[registerId]) - throw IrError("IR control-flow path reads an uninitialized register"); -} -constexpr std::size_t kMaximumVmValueDepth = 256; - -bool vmValuesEqualAtDepth(const VmValue &left, const VmValue &right, - std::size_t depth) { - if (depth > kMaximumVmValueDepth) { - throw IrError("VM value comparison exceeds its nesting limit"); - } - const auto keyedEqual = [&](const auto &leftEntries, - const auto &rightEntries) { - if (leftEntries.size() != rightEntries.size()) - return false; - return std::all_of( - leftEntries.begin(), leftEntries.end(), [&](const auto &leftEntry) { - const auto matching = std::find_if( - rightEntries.begin(), rightEntries.end(), [&](const auto &entry) { - return entry.first == leftEntry.first; - }); - return matching != rightEntries.end() && - vmValuesEqualAtDepth(leftEntry.second, matching->second, - depth + 1); - }); - }; - if (left.index() != right.index()) - return false; - if (std::holds_alternative(left)) - return true; - if (const auto *value = std::get_if(&left)) - return *value == std::get(right); - if (const auto *value = std::get_if(&left)) - return *value == std::get(right); - if (const auto *value = std::get_if(&left)) - return *value == std::get(right); - if (const auto *value = std::get_if(&left)) - return *value == std::get(right); - if (const auto *leftArray = std::get_if(&left)) { - const auto &rightArray = std::get(right); - if (!*leftArray || !rightArray) - return *leftArray == rightArray; - if ((*leftArray)->values.size() != rightArray->values.size()) - return false; - for (std::size_t index = 0; index < (*leftArray)->values.size(); ++index) { - if (!vmValuesEqualAtDepth((*leftArray)->values[index], - rightArray->values[index], depth + 1)) - return false; - } - return true; - } - if (const auto *leftMap = std::get_if(&left)) { - const auto &rightMap = std::get(right); - if (!*leftMap || !rightMap) - return *leftMap == rightMap; - return keyedEqual((*leftMap)->entries, rightMap->entries); - } - if (const auto *leftFact = std::get_if(&left)) { - const auto &rightFact = std::get(right); - if (!*leftFact || !rightFact) - return *leftFact == rightFact; - return (*leftFact)->type == rightFact->type && - keyedEqual((*leftFact)->fields, rightFact->fields); - } - if (const auto *leftTensor = std::get_if(&left)) { - const auto &rightTensor = std::get(right); - return *leftTensor == rightTensor; - } - if (const auto *leftMap = std::get_if(&left)) { - const auto &rightMap = std::get(right); - if (!*leftMap || !rightMap) - return *leftMap == rightMap; - return keyedEqual((*leftMap)->entries, rightMap->entries); - } - throw IrError("VM equality received an unsupported value variant"); -} - -bool vmValuesEqualInternal(const VmValue &left, const VmValue &right) { - return vmValuesEqualAtDepth(left, right, 0); -} - -using Form::StoredValueKey; - -std::optional -factIndexKey(const VmFactPtr &fact, std::span fields, - std::span symbols) { - if (!fact) - return std::nullopt; - StoredValueKey result; - result.push_back(static_cast(fields.size())); - for (const auto field : fields) { - const auto found = std::find_if( - fact->fields.begin(), fact->fields.end(), - [&](const auto &entry) { return entry.first == field; }); - if (found == fact->fields.end()) - return std::nullopt; - auto value = Form::encodeStoredValueKey(found->second, symbols); - result.push_back(static_cast(value.size())); - result.insert(result.end(), value.begin(), value.end()); - } - return result; -} - -StoredValueKey predicateIndexKey( - std::span indexFields, std::size_t coveredFields, - std::span> predicates, - std::span symbols) { - if (coveredFields == 0 || coveredFields > indexFields.size()) - throw IrError("fact query planner selected an invalid index prefix"); - StoredValueKey result; - // Keep the declared field count first so one index's key space cannot be a - // prefix of another. Only the leading covered fields follow for a range - // lookup over a composite index. - result.push_back(static_cast(indexFields.size())); - for (std::size_t index = 0; index < coveredFields; ++index) { - const auto field = indexFields[index]; - const auto found = std::find_if( - predicates.begin(), predicates.end(), - [&](const auto &entry) { return entry.first == field; }); - if (found == predicates.end()) - throw IrError("fact query planner selected an uncovered index"); - auto value = Form::encodeStoredValueKey(found->second, symbols); - result.push_back(static_cast(value.size())); - result.insert(result.end(), value.begin(), value.end()); - } - return result; -} - -double evaluateNumericOperation(NumericOperation operation, - std::span operands) { - if (operation >= NumericOperation::Count || - operands.size() != numericOperationArity(operation)) { - throw IrError("numeric operation has an invalid operation ID or arity"); - } - if (operation == NumericOperation::IsFinite) - return std::isfinite(operands[0]) ? 1.0 : 0.0; - if (operation == NumericOperation::IsNan) - return std::isnan(operands[0]) ? 1.0 : 0.0; - if (!std::all_of(operands.begin(), operands.end(), - [](double value) { return std::isfinite(value); })) { - throw IrError("numeric operation requires finite operands"); - } - - double result = 0.0; - switch (operation) { - case NumericOperation::Min: - result = std::min(operands[0], operands[1]); - break; - case NumericOperation::Max: - result = std::max(operands[0], operands[1]); - break; - case NumericOperation::Abs: - result = std::abs(operands[0]); - break; - case NumericOperation::Diff: - result = std::abs(operands[0] - operands[1]); - break; - case NumericOperation::Average: - result = std::midpoint(operands[0], operands[1]); - break; - case NumericOperation::WeightedAverage: { - const long double totalWeight = - static_cast(operands[2]) + operands[3]; - if (totalWeight == 0.0L) - throw IrError("weighted_avg total weight must not be zero"); - const long double weighted = - static_cast(operands[2]) * operands[0] + - static_cast(operands[3]) * operands[1]; - result = static_cast(weighted / totalWeight); - break; - } - case NumericOperation::Clamp: - if (operands[1] > operands[2]) - throw IrError("clamp minimum must not exceed maximum"); - result = std::clamp(operands[0], operands[1], operands[2]); - break; - case NumericOperation::Floor: - result = std::floor(operands[0]); - break; - case NumericOperation::Ceil: - result = std::ceil(operands[0]); - break; - case NumericOperation::Round: - result = std::round(operands[0]); - break; - case NumericOperation::Trunc: - result = std::trunc(operands[0]); - break; - case NumericOperation::Sqrt: - if (operands[0] < 0.0) - throw IrError("sqrt operand must not be negative"); - result = std::sqrt(operands[0]); - break; - case NumericOperation::Cbrt: - result = std::cbrt(operands[0]); - break; - case NumericOperation::Pow: - result = std::pow(operands[0], operands[1]); - break; - case NumericOperation::Exp: - result = std::exp(operands[0]); - break; - case NumericOperation::Log: - case NumericOperation::Log10: - if (operands[0] <= 0.0) - throw IrError("log operand must be greater than zero"); - result = operation == NumericOperation::Log ? std::log(operands[0]) - : std::log10(operands[0]); - break; - case NumericOperation::Lerp: - result = std::lerp(operands[0], operands[1], operands[2]); - break; - case NumericOperation::Sign: - result = static_cast((0.0 < operands[0]) - (operands[0] < 0.0)); - break; - case NumericOperation::Reciprocal: - if (operands[0] == 0.0) - throw IrError("reciprocal operand must not be zero"); - result = 1.0 / operands[0]; - break; - case NumericOperation::Square: - result = operands[0] * operands[0]; - break; - case NumericOperation::Cube: - result = operands[0] * operands[0] * operands[0]; - break; - case NumericOperation::InRange: - if (operands[1] > operands[2]) - throw IrError("in_range minimum must not exceed maximum"); - result = - operands[0] >= operands[1] && operands[0] <= operands[2] ? 1.0 : 0.0; - break; - case NumericOperation::IsFinite: - case NumericOperation::IsNan: - case NumericOperation::Count: - break; - } - if (!std::isfinite(result)) - throw IrError("numeric operation produced a non-finite result"); - return result; -} - -double similarityDegreeAtDepth(const VmValue &left, const VmValue &right, - std::size_t depth) { - if (depth > kMaximumVmValueDepth) { - throw IrError("VM similarity exceeds its nesting limit"); - } - const auto keyedSimilarity = [&](const auto &leftEntries, - const auto &rightEntries) { - const auto limit = std::max(leftEntries.size(), rightEntries.size()); - if (limit == 0) - return 1.0; - double sum = 0.0; - for (const auto &[key, value] : leftEntries) { - const auto matching = - std::find_if(rightEntries.begin(), rightEntries.end(), - [&](const auto &entry) { return entry.first == key; }); - if (matching != rightEntries.end()) - sum += similarityDegreeAtDepth(value, matching->second, depth + 1); - } - return sum / static_cast(limit); - }; - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) - return 1.0 / (1.0 + std::abs(*a - *b)); - } - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) - return 1.0 - std::abs(a->value - b->value); - } - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) - return a->pieces == b->pieces ? 1.0 : 0.0; - } - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) - return a->value == b->value ? 1.0 : 0.0; - } - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) { - if (!*a || !*b) - return *a == *b ? 1.0 : 0.0; - const auto limit = std::max((*a)->values.size(), (*b)->values.size()); - if (limit == 0) - return 1.0; - double sum = 0.0; - for (std::size_t i = 0; - i < std::min((*a)->values.size(), (*b)->values.size()); ++i) - sum += similarityDegreeAtDepth((*a)->values[i], (*b)->values[i], - depth + 1); - return sum / static_cast(limit); - } - } - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) { - if (!*a || !*b) - return *a == *b ? 1.0 : 0.0; - return keyedSimilarity((*a)->entries, (*b)->entries); - } - } - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) { - if (!*a || !*b) - return *a == *b ? 1.0 : 0.0; - return keyedSimilarity((*a)->entries, (*b)->entries); - } - } - if (const auto a = std::get_if(&left)) { - if (const auto b = std::get_if(&right)) { - if (!*a || !*b) - return *a == *b ? 1.0 : 0.0; - const double type = (*a)->type == (*b)->type ? 1.0 : 0.0; - return 0.25 * type + 0.75 * keyedSimilarity((*a)->fields, (*b)->fields); - } - } - return vmValuesEqualAtDepth(left, right, depth) ? 1.0 : 0.0; -} - -double similarityDegree(const VmValue &left, const VmValue &right) { - return similarityDegreeAtDepth(left, right, 0); -} - -bool validVmValue(const VmValue &value, std::size_t depth = 0) { - if (depth > kMaximumVmValueDepth) - return false; - if (const auto number = std::get_if(&value)) - return std::isfinite(*number); - if (const auto degree = std::get_if(&value)) - return std::isfinite(degree->value) && degree->value >= 0.0 && - degree->value <= 1.0; - if (const auto *array = std::get_if(&value)) { - if (!*array) - return false; - return std::all_of( - (*array)->values.begin(), (*array)->values.end(), - [&](const VmValue &item) { return validVmValue(item, depth + 1); }); - } - if (const auto *map = std::get_if(&value)) { - if (!*map) - return false; - std::unordered_set keys; - return std::all_of( - (*map)->entries.begin(), (*map)->entries.end(), [&](const auto &entry) { - return entry.first != 0 && keys.insert(entry.first).second && - validVmValue(entry.second, depth + 1); - }); - } - if (const auto *fact = std::get_if(&value)) { - if (!*fact || (*fact)->type == 0) - return false; - std::unordered_set fields; - return std::all_of( - (*fact)->fields.begin(), (*fact)->fields.end(), [&](const auto &entry) { - return entry.first != 0 && fields.insert(entry.first).second && - validVmValue(entry.second, depth + 1); - }); - } - if (const auto *tensor = std::get_if(&value)) - return *tensor && static_cast((*tensor)->storage); - if (const auto *map = std::get_if(&value)) { - if (!*map) - return false; - std::set keys; - return std::all_of( - (*map)->entries.begin(), (*map)->entries.end(), [&](const auto &entry) { - return !entry.first.empty() && keys.insert(entry.first).second && - validVmValue(entry.second, depth + 1); - }); - } - return true; -} - -bool validSemanticInputs(std::uint16_t operation, - std::span inputs) { - if (!semanticOperationAcceptsArity(operation, inputs.size()) || - !validVmValue(inputs.front())) - return false; - switch (static_cast(operation)) { - case SemanticOperationId::Identity: - return true; - case SemanticOperationId::SelectFact: - case SemanticOperationId::DeriveFact: { - const auto fact = std::get_if(&inputs.front()); - return fact && static_cast(*fact); - } - case SemanticOperationId::EvaluateDegree: - return std::holds_alternative(inputs.front()) || - std::holds_alternative(inputs.front()); - case SemanticOperationId::Suggest: - return true; - } - return false; -} - -bool validSemanticOutput(std::uint16_t operation, - std::span inputs, - const VmValue &output) { - if (!validVmValue(output)) - return false; - switch (static_cast(operation)) { - case SemanticOperationId::Identity: - return runtimeValueKind(output) == runtimeValueKind(inputs.front()); - case SemanticOperationId::SelectFact: - case SemanticOperationId::DeriveFact: - return std::holds_alternative(output) || - std::holds_alternative(output); - case SemanticOperationId::EvaluateDegree: - return std::holds_alternative(output); - case SemanticOperationId::Suggest: { - const auto score = std::get_if(&output); - return score && std::isfinite(*score); - } - } - return false; -} -void verifyControlFlowInitialization( - const FelidaeIr &ir, const std::unordered_set &boundaries) { - std::vector>> incoming(ir.words.size()); - std::deque pending; - incoming[0] = std::vector(ir.registerCount, false); - pending.push_back(0); - const auto enqueue = - [&](std::size_t target, const std::vector &state, - std::deque &queue, - std::vector>> &states) { - if (!boundaries.contains(target)) - return; - if (!states[target]) { - states[target] = state; - queue.push_back(target); - return; - } - auto merged = *states[target]; - bool changed = false; - for (std::size_t index = 0; index < merged.size(); ++index) { - const bool value = merged[index] && state[index]; - changed = changed || value != merged[index]; - merged[index] = value; - } - if (changed) { - states[target] = std::move(merged); - queue.push_back(target); - } - }; - while (!pending.empty()) { - const auto pc = pending.front(); - pending.pop_front(); - auto state = *incoming[pc]; - const auto op = static_cast(ir.words[pc]); - const auto next = pc + irInstructionWidth(ir, pc); - auto write = [&](IrWord target) { state[target] = true; }; - switch (op) { - case IrOpcode::LoadConst: - case IrOpcode::LoadSymbol: - case IrOpcode::TemporalRank: - write(ir.words[pc + 1]); - break; - case IrOpcode::ForEachFact: - requireFlowRead(state, ir.words[pc + 4]); - write(ir.words[pc + 1]); - break; - case IrOpcode::FactWhere: - requireFlowRead(state, ir.words[pc + 3]); - write(ir.words[pc + 1]); - break; - case IrOpcode::FactJoin: - requireFlowRead(state, ir.words[pc + 2]); - requireFlowRead(state, ir.words[pc + 3]); - requireFlowRead(state, ir.words[pc + 4]); - requireFlowRead(state, ir.words[pc + 5]); - requireFlowRead(state, ir.words[pc + 6]); - write(ir.words[pc + 1]); - break; - case IrOpcode::StoreSymbol: - requireFlowRead(state, ir.words[pc + 2]); - break; - case IrOpcode::Move: - requireFlowRead(state, ir.words[pc + 2]); - write(ir.words[pc + 1]); - break; - case IrOpcode::Add: - case IrOpcode::Sub: - case IrOpcode::Mul: - case IrOpcode::Div: - case IrOpcode::Mod: - case IrOpcode::Similarity: - case IrOpcode::Membership: - case IrOpcode::HierarchyIsA: - case IrOpcode::HierarchyCommonAncestors: - case IrOpcode::Compare: - requireFlowRead(state, ir.words[pc + 2]); - requireFlowRead(state, ir.words[pc + 3]); - write(ir.words[pc + 1]); - break; - case IrOpcode::JumpIfFalse: - requireFlowRead(state, ir.words[pc + 1]); - break; - case IrOpcode::Call: - for (std::size_t i = 0; i < ir.words[pc + 3]; ++i) - requireFlowRead(state, ir.words[pc + 4 + i]); - write(ir.words[pc + 1]); - break; - case IrOpcode::SemanticEval: - for (std::size_t i = 0; i < ir.words[pc + 3]; ++i) - requireFlowRead(state, ir.words[pc + 4 + i]); - write(ir.words[pc + 1]); - break; - case IrOpcode::Numeric: - case IrOpcode::Tensor: - for (std::size_t i = 0; i < ir.words[pc + 3]; ++i) - requireFlowRead(state, ir.words[pc + 4 + i]); - write(ir.words[pc + 1]); - break; - case IrOpcode::CallNamed: - for (std::size_t i = 0; i < ir.words[pc + 3]; ++i) - requireFlowRead(state, ir.words[pc + 5 + 2 * i]); - write(ir.words[pc + 1]); - break; - case IrOpcode::MakeArray: - for (std::size_t i = 0; i < ir.words[pc + 3]; ++i) - requireFlowRead(state, ir.words[pc + 4 + i]); - write(ir.words[pc + 1]); - break; - case IrOpcode::MakeMap: - for (std::size_t i = 0; i < ir.words[pc + 3]; ++i) - requireFlowRead(state, ir.words[pc + 5 + 2 * i]); - write(ir.words[pc + 1]); - break; - case IrOpcode::GetField: - requireFlowRead(state, ir.words[pc + 2]); - write(ir.words[pc + 1]); - break; - case IrOpcode::SetField: - requireFlowRead(state, ir.words[pc + 1]); - requireFlowRead(state, ir.words[pc + 3]); - break; - case IrOpcode::Return: - requireFlowRead(state, ir.words[pc + 1]); - break; - case IrOpcode::Builtin: - for (std::size_t i = 0; i < ir.words[pc + 3]; ++i) - requireFlowRead(state, ir.words[pc + 4 + i]); - write(ir.words[pc + 1]); - break; - case IrOpcode::MakeFact: - write(ir.words[pc + 1]); - break; - case IrOpcode::End: - case IrOpcode::Jump: - break; - case IrOpcode::Count: - throw IrError("IR control-flow scan found an invalid opcode"); - } - if (op == IrOpcode::End || op == IrOpcode::Return) - continue; - if (op == IrOpcode::Jump) { - enqueue(ir.words[pc + 1], state, pending, incoming); - } else if (op == IrOpcode::JumpIfFalse) { - enqueue(ir.words[pc + 2], state, pending, incoming); - enqueue(next, state, pending, incoming); - } else { - enqueue(next, state, pending, incoming); - } - } -} -} // namespace - -namespace { - -void appendBigEndian64(std::string &key, std::uint64_t value) { - for (int shift = 56; shift >= 0; shift -= 8) - key.push_back(static_cast((value >> shift) & 0xffU)); -} - -void appendPieceKey(std::string &key, std::span pieces) { - appendBigEndian64(key, pieces.size()); - for (const auto piece : pieces) - appendBigEndian64(key, piece); -} - -std::string storedFactKey(IrFactRef id) { - std::string key{"F", 1}; - appendBigEndian64(key, id); - return key; -} - -std::string storedTypeKey(std::span pieces) { - std::string key{"Y", 1}; - appendPieceKey(key, pieces); - return key; -} - -void appendOrderedKey(std::string &key, - std::span values) { - for (const auto value : values) - appendBigEndian64(key, value); -} - -void appendFactOrder(std::string &key, const VmFact &fact) { - appendBigEndian64(key, fact.createdSequence); - appendBigEndian64(key, fact.id); -} - -std::string storedTypeIndexPrefix(std::span type) { - std::string key{"IT", 2}; - appendPieceKey(key, type); - return key; -} - -std::string storedConcreteTypeIndexPrefix(std::span type) { - std::string key{"IC", 2}; - appendPieceKey(key, type); - return key; -} - -std::string storedFieldIndexPrefix(std::span field) { - std::string key{"IF", 2}; - appendPieceKey(key, field); - return key; -} - -std::string storedSourceIndexPrefix(std::string_view source) { - std::string key{"IS", 2}; - appendBigEndian64(key, source.size()); - key.append(source); - return key; -} - -std::string storedExactIndexPrefix( - std::span owner, - std::span> indexes, std::size_t ordinal, - std::span symbols) { - if (ordinal >= indexes.size()) - throw IrError("persistent fact index ordinal is invalid"); - std::string key{"IE", 2}; - appendPieceKey(key, owner); - appendBigEndian64(key, indexes[ordinal].size()); - for (const auto field : indexes[ordinal]) - appendPieceKey(key, irSymbolPieces(symbols, field)); - return key; -} - -} // namespace - -class VmFactStore::Persistence { -public: -#ifdef FELIDAE_HAS_ROCKSDB - explicit Persistence(const std::filesystem::path &directory) - : database(directory) { - if (const auto stored = database.get("M/revision")) { - if (stored->size() != sizeof(revision)) - throw IrError("RocksDB revision metadata is malformed"); - for (const unsigned char byte : *stored) - revision = (revision << 8U) | byte; - } - } - // The store mutex serializes callers. Publish the next revision only after - // its atomic data/index batch commits; failed writes cannot advance it. - void commit(std::span mutations) { - if (mutations.empty()) - return; - if (revision == std::numeric_limits::max()) - throw IrError("RocksDB fact-store revision exhausted"); - std::vector batch(mutations.begin(), mutations.end()); - std::string encoded; - appendBigEndian64(encoded, revision + 1); - batch.push_back({Form::RocksDb::Mutation::Kind::Put, "M/revision", - std::move(encoded)}); - database.write(batch); - ++revision; - } - Form::RocksDb database; - std::uint64_t revision = 0; -#else - explicit Persistence(const std::filesystem::path &) { - throw IrError("this VM build has no RocksDB fact-store support"); - } -#endif - bool loading = false; -}; - -VmFactStore::VmFactStore() = default; - -VmFactStore::VmFactStore(const std::filesystem::path &directory) - : persistence_(std::make_unique(directory)) { -#ifdef FELIDAE_HAS_ROCKSDB - persistence_->loading = true; - // Allocation watermarks outlive deleted rows. Commit them with insertion - // so a restart cannot recycle an identity referenced by an older snapshot. - const auto allocation = persistence_->database.get("M/allocation"); - if (allocation) { - if (allocation->size() != 16) - throw IrError("RocksDB allocation metadata is malformed"); - std::uint64_t counters[2]{}; - for (std::size_t i = 0; i < allocation->size(); ++i) - counters[i / 8] = (counters[i / 8] << 8U) | - static_cast((*allocation)[i]); - if (counters[0] == 0 || counters[1] == 0 || - counters[0] > std::numeric_limits::max()) - throw IrError("RocksDB allocation metadata is outside its range"); - nextId_ = static_cast(counters[0]); - nextSequence_ = counters[1]; - } - const auto readAll = [&](std::string_view prefix, const auto &consume) { - std::optional after; - while (true) { - const auto page = persistence_->database.scanPrefix( - prefix, - after ? std::optional{*after} : std::nullopt, - 4096); - for (const auto &[key, value] : page.rows) - consume(key, value); - if (!page.hasMore || page.rows.empty()) - break; - after = page.rows.back().first; - } - }; - readAll(std::string_view{"Y", 1}, [&](std::string_view key, std::string_view value) { - const auto record = Form::decodeStoredFactType( - value, [this](PieceSequence pieces) { - return internSymbol(std::move(pieces)); - }); - if (key != storedTypeKey(irSymbolPieces(symbolTable_, record.type))) - throw IrError("RocksDB type record identity is inconsistent"); - registerType(record.type, record.parents, record.indexes); - }); - // Facts remain on disk and are decoded through their selected index page. - // Allocation metadata is mandatory once any fact exists; recovering it by - // scanning all rows would make VM startup proportional to database size. - if (!allocation && - !persistence_->database.scanPrefix(std::string_view{"F", 1}, - std::nullopt, 1).rows.empty()) - throw IrError("RocksDB facts exist without allocation metadata"); - persistence_->loading = false; -#else - (void)directory; -#endif -} - -VmFactStore::~VmFactStore() = default; - -bool vmValuesEqual(const VmValue &left, const VmValue &right) { - return vmValuesEqualInternal(left, right); -} - -std::string vmValueToDisplayString(const VmValue &value, - const VmDisplayContext &context) { - const auto renderNumber = [](double number) { - std::ostringstream out; - out.precision(15); - out << number; - auto result = out.str(); - if ((number == 0.0 || number == 1.0) && - result.find_first_of(".eE") == std::string::npos) { - result += ".0"; - } - return result; - }; - const auto render = [&](const auto &self, - const VmValue &item) -> std::string { - if (std::holds_alternative(item)) - return "nil"; - if (const auto number = std::get_if(&item)) - return renderNumber(*number); - if (const auto degree = std::get_if(&item)) - return renderNumber(degree->value); - if (const auto text = std::get_if(&item)) { - if (!context.textDecoder) - return "pieces.size()) + " pieces>"; - return context.textDecoder(text->pieces); - } - if (const auto symbol = std::get_if(&item)) { - auto name = context.symbolDecoder ? context.symbolDecoder(symbol->value) - : std::string{}; - return name.empty() ? "#" + std::to_string(symbol->value) : name; - } - if (const auto tensor = std::get_if(&item)) { - if (!*tensor || !(*tensor)->storage) - throw IrError("VM display received an invalid tensor value"); - if (context.tensorDecoder) - return context.tensorDecoder(**tensor); - std::ostringstream out; - out << "tensor(shape=["; - for (std::size_t index = 0; index < (*tensor)->shape.size(); ++index) { - if (index) - out << ", "; - out << (*tensor)->shape[index]; - } - return out << "])", out.str(); - } - if (const auto array = std::get_if(&item)) { - if (!*array) - throw IrError("VM display received an invalid array value"); - std::ostringstream out; - out << "["; - for (std::size_t index = 0; index < (*array)->values.size(); ++index) { - if (index) - out << ", "; - out << self(self, (*array)->values[index]); - } - return out << "]", out.str(); - } - if (const auto map = std::get_if(&item)) { - if (!*map) - throw IrError("VM display received an invalid text-keyed map"); - std::ostringstream out; - out << "{"; - for (std::size_t index = 0; index < (*map)->entries.size(); ++index) { - if (index) - out << ", "; - const auto &[key, value] = (*map)->entries[index]; - out << (context.textDecoder - ? context.textDecoder(key) - : "") - << ": " << self(self, value); - } - return out << "}", out.str(); - } - const auto renderFields = [&](const auto &fields) { - std::ostringstream out; - out << "{"; - for (std::size_t index = 0; index < fields.size(); ++index) { - if (index) - out << ", "; - auto name = context.symbolDecoder - ? context.symbolDecoder(fields[index].first) - : std::string{}; - if (name.empty()) - name = "#" + std::to_string(fields[index].first); - out << name << ": " << self(self, fields[index].second); - } - return out << "}", out.str(); - }; - if (const auto map = std::get_if(&item)) { - if (!*map) - throw IrError("VM display received an invalid map value"); - return renderFields((*map)->entries); - } - if (const auto fact = std::get_if(&item)) { - if (!*fact) - throw IrError("VM display received an invalid fact value"); - return renderFields((*fact)->fields); - } - throw IrError("Direct VM result cannot display an opaque runtime value"); - }; - return render(render, value); -} - -const std::unordered_set & -VmFactStore::ancestorClosureLocked(IrSymbolRef type) const { - const auto cached = ancestorClosureCache_.find(type); - if (cached != ancestorClosureCache_.end() && - cached->second.first == hierarchyRevision_) { - return cached->second.second; - } - std::unordered_set closure; - std::vector pending{type}; - while (!pending.empty()) { - const auto current = pending.back(); - pending.pop_back(); - if (!closure.insert(current).second) - continue; - if (const auto found = parents_.find(current); found != parents_.end()) { - pending.insert(pending.end(), found->second.begin(), found->second.end()); - } - } - auto &entry = ancestorClosureCache_[type]; - entry = {hierarchyRevision_, std::move(closure)}; - return entry.second; -} - -bool VmFactStore::isAssignableToLocked(IrSymbolRef candidate, - IrSymbolRef expected) const { - return ancestorClosureLocked(candidate).contains(expected); -} - -void VmFactStore::validateDeclaredIndexKeysLocked(const VmFactPtr &fact) const { - for (const auto &[owner, indexes] : exactIndexes_) { - if (!isAssignableToLocked(fact->type, owner)) - continue; - for (const auto &index : indexes) - (void)factIndexKey(fact, index.fields, symbolTable_); - } -} - -void VmFactStore::addToDeclaredIndexesLocked(const VmFactPtr &fact) { - // Persistent rows are committed atomically by persistentIndexKeysLocked. - // Keep only their declarations here, not a second process-resident index. - if (persistence_) - return; - for (auto &[owner, indexes] : exactIndexes_) { - if (!isAssignableToLocked(fact->type, owner)) - continue; - for (auto &index : indexes) { - if (auto key = factIndexKey(fact, index.fields, symbolTable_)) { - auto &rows = index.rows[std::move(*key)]; - const auto position = std::lower_bound( - rows.begin(), rows.end(), fact, - [](const auto &left, const auto &right) { - if (left->createdSequence != right->createdSequence) - return left->createdSequence < right->createdSequence; - return left->id < right->id; - }); - rows.insert(position, fact); - } - } - } -} - -void VmFactStore::removeFromDeclaredIndexesLocked(const VmFactPtr &fact) { - if (persistence_) - return; - for (auto &[owner, indexes] : exactIndexes_) { - if (!isAssignableToLocked(fact->type, owner)) - continue; - for (auto &index : indexes) { - const auto key = factIndexKey(fact, index.fields, symbolTable_); - if (!key) - continue; - const auto found = index.rows.find(*key); - if (found == index.rows.end()) - throw IrError("declared fact index is inconsistent"); - std::erase(found->second, fact); - if (found->second.empty()) - index.rows.erase(found); - } - } -} - -std::vector VmFactStore::persistentIndexKeysLocked( - const VmFactPtr &fact, std::optional source) const { - if (!fact) - throw IrError("persistent fact index requires a fact"); - std::vector result; - { - auto key = storedConcreteTypeIndexPrefix( - irSymbolPieces(symbolTable_, fact->type)); - appendFactOrder(key, *fact); - result.push_back(std::move(key)); - } - std::vector types(ancestorClosureLocked(fact->type).begin(), - ancestorClosureLocked(fact->type).end()); - std::sort(types.begin(), types.end()); - for (const auto type : types) { - auto key = storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)); - appendFactOrder(key, *fact); - result.push_back(std::move(key)); - } - - std::vector fields; - fields.reserve(fact->fields.size()); - for (const auto &[field, _] : fact->fields) - fields.push_back(field); - std::sort(fields.begin(), fields.end()); - fields.erase(std::unique(fields.begin(), fields.end()), fields.end()); - for (const auto field : fields) { - auto key = storedFieldIndexPrefix(irSymbolPieces(symbolTable_, field)); - appendFactOrder(key, *fact); - result.push_back(std::move(key)); - } - - if (source) { - auto key = storedSourceIndexPrefix(*source); - appendFactOrder(key, *fact); - result.push_back(std::move(key)); - } - - for (const auto &[owner, indexes] : declaredIndexes_) { - if (!isAssignableToLocked(fact->type, owner)) - continue; - for (std::size_t ordinal = 0; ordinal < indexes.size(); ++ordinal) { - const auto value = factIndexKey(fact, indexes[ordinal], symbolTable_); - if (!value) - continue; - auto key = storedExactIndexPrefix( - irSymbolPieces(symbolTable_, owner), indexes, ordinal, symbolTable_); - appendOrderedKey(key, *value); - appendFactOrder(key, *fact); - result.push_back(std::move(key)); - } - } - std::sort(result.begin(), result.end()); - result.erase(std::unique(result.begin(), result.end()), result.end()); - return result; -} - -std::vector VmFactStore::persistentFactsLocked( - std::string_view prefix, std::size_t maximum, bool *hasMore, - std::optional after, std::string *lastKey, - std::vector *keys) const { -#ifdef FELIDAE_HAS_ROCKSDB - if (!persistence_) - throw IrError("persistent fact query requires a RocksDB store"); - const auto page = - persistence_->database.scanPrefix(prefix, after, maximum); - if (lastKey && !page.rows.empty()) - *lastKey = page.rows.back().first; - if (hasMore) - *hasMore = page.hasMore; - std::vector result; - result.reserve(page.rows.size()); - for (const auto &[key, _] : page.rows) { - if (keys) - keys->push_back(key); - if (key.size() < sizeof(std::uint64_t)) - throw IrError("RocksDB fact index contains a truncated key"); - std::uint64_t id = 0; - for (std::size_t index = key.size() - sizeof(std::uint64_t); - index < key.size(); ++index) - id = (id << 8U) | static_cast(key[index]); - const auto record = persistence_->database.get(storedFactKey(id)); - if (!record) - throw IrError("RocksDB fact index references a missing fact"); - const auto decoded = Form::decodeStoredFact( - *record, [this](PieceSequence pieces) { - return internSymbolLocked(std::move(pieces)); - }); - if (!decoded.fact || decoded.fact->id != id) - throw IrError("RocksDB fact index identity is inconsistent"); - result.push_back(decoded.fact); - } - return result; -#else - (void)prefix; - (void)maximum; - (void)hasMore; - (void)after; - (void)lastKey; - (void)keys; - throw IrError("this VM build has no RocksDB fact-store support"); -#endif -} - -VmFactStore::StoredSnapshot -VmFactStore::persistentSnapshotLocked(IrFactRef fact) const { -#ifdef FELIDAE_HAS_ROCKSDB - if (!persistence_ || fact == 0) - throw IrError("persistent fact lookup has no valid store or identity"); - const auto bytes = persistence_->database.get(storedFactKey(fact)); - if (!bytes) - throw IrError("fact targets an identity outside this knowledge runtime"); - auto record = Form::decodeStoredFact( - *bytes, [this](PieceSequence pieces) { - return internSymbolLocked(std::move(pieces)); - }); - if (!record.fact || record.fact->id != fact || - !parents_.contains(record.fact->type) || - record.fact->createdSequence == 0 || - record.fact->createdSequence == std::numeric_limits::max()) - throw IrError("RocksDB contains an invalid fact record"); - validateDeclaredIndexKeysLocked(record.fact); - return {std::move(record.fact), std::move(record.source)}; -#else - (void)fact; - throw IrError("this VM build has no RocksDB fact-store support"); -#endif -} - -IrSymbolRef VmFactStore::internSymbol(PieceSequence pieces) { - if (pieces.empty()) - throw IrError("runtime symbol must contain SentencePiece IDs"); - std::lock_guard lock(mutex_); - return internSymbolLocked(std::move(pieces)); -} - -IrSymbolRef VmFactStore::internSymbolLocked(PieceSequence pieces) const { - const auto found = symbolIds_.find(pieces); - if (found != symbolIds_.end()) - return found->second; - if (symbolTable_.size() == - static_cast(std::numeric_limits::max())) - throw IrError("runtime symbol table exhausted its ID space"); - symbolTable_.push_back(std::move(pieces)); - const auto symbol = static_cast(symbolTable_.size()); - symbolIds_.emplace(symbolTable_.back(), symbol); - return symbol; -} - -std::optional -VmFactStore::findSymbol(std::span pieces) const { - std::lock_guard lock(mutex_); - const PieceSequence key(pieces.begin(), pieces.end()); - const auto found = symbolIds_.find(key); - return found == symbolIds_.end() ? std::nullopt - : std::optional{found->second}; -} - -const std::vector &VmFactStore::symbolTable() const noexcept { - return symbolTable_; -} - -void VmFactStore::registerType(IrSymbolRef type, - std::vector parents, - std::vector> indexes) { - if (type == 0) - throw IrError("fact hierarchy type is invalid"); - std::lock_guard lock(mutex_); - if (const auto existing = parents_.find(type); existing != parents_.end()) { - if (existing->second != parents || declaredIndexes_.at(type) != indexes) - throw IrError("fact hierarchy type has conflicting parents"); - return; - } - std::unordered_set uniqueParents; - for (const auto parent : parents) { - if (parent == 0 || parent == type) - throw IrError("fact hierarchy parent is invalid"); - if (!uniqueParents.insert(parent).second) - throw IrError("fact hierarchy contains a duplicate parent"); - if (isAssignableToLocked(parent, type)) - throw IrError("fact hierarchy contains a cycle"); - } -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_ && !persistence_->loading) { - const auto value = Form::encodeStoredFactType( - type, parents, indexes, symbolTable_); - const std::array mutation{{ - {Form::RocksDb::Mutation::Kind::Put, - storedTypeKey(irSymbolPieces(symbolTable_, type)), value}}}; - persistence_->commit(mutation); - } -#endif - parents_.emplace(type, std::move(parents)); - auto [declaration, _] = - declaredIndexes_.emplace(type, std::move(indexes)); - auto &runtimeIndexes = exactIndexes_[type]; - runtimeIndexes.reserve(declaration->second.size()); - for (const auto &fields : declaration->second) - runtimeIndexes.push_back(ExactIndex{fields, {}}); - ++hierarchyRevision_; - ++knowledgeRevision_; -} - -VmFactPtr VmFactStore::retain(const VmFactPtr &fact) { - if (!fact || !validVmValue(VmValue{fact})) - throw IrError("fact store cannot retain an invalid fact"); - std::lock_guard lock(mutex_); - if (!parents_.contains(fact->type)) - throw IrError("fact store cannot retain an unregistered fact type"); - if (fact->id != 0) { - if (persistence_) - return currentSnapshotLocked(fact); - if (std::ranges::find(facts_, fact) == facts_.end()) - throw IrError("fact already belongs to another knowledge runtime"); - return fact; - } - if (nextId_ == std::numeric_limits::max()) - throw IrError("fact store exhausted its fact ID space"); - auto retained = std::make_shared(*fact); - validateDeclaredIndexKeysLocked(retained); - if (nextSequence_ == std::numeric_limits::max()) - throw IrError("fact store exhausted its creation-order space"); - retained->id = nextId_; - retained->createdSequence = nextSequence_; -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - const auto value = - Form::encodeStoredFact(*retained, std::nullopt, symbolTable_); - std::vector mutation{ - {Form::RocksDb::Mutation::Kind::Put, storedFactKey(retained->id), - value}}; - for (auto &key : persistentIndexKeysLocked(retained)) - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); - std::string allocation; - appendBigEndian64(allocation, nextId_ + 1); - appendBigEndian64(allocation, nextSequence_ + 1); - mutation.push_back({Form::RocksDb::Mutation::Kind::Put, "M/allocation", - std::move(allocation)}); - persistence_->commit(mutation); - } -#endif - ++nextId_; - ++nextSequence_; - if (!persistence_) { - facts_.push_back(retained); - byType_[retained->type].push_back(retained); - for (const auto &[field, _] : retained->fields) - byField_[field].push_back(retained); - } - addToDeclaredIndexesLocked(retained); - provenance_.push_back( - VmFactProvenance{retained->id, 0, - retained->origin == VmFact::Origin::Derived}); - ++membershipRevision_; - ++knowledgeRevision_; - return retained; -} - -void VmFactStore::recordInsert(IrFactRef fact) { - std::lock_guard lock(mutex_); - if (fact == 0) - throw IrError("fact insertion record targets an unknown fact"); - if (persistence_) - (void)persistentSnapshotLocked(fact); - else if (std::none_of(facts_.begin(), facts_.end(), - [&](const auto &item) { - return item->id == fact; - })) - throw IrError("fact insertion record targets an unknown fact"); - mutations_.push_back(VmFactMutation{nextSequence_++, fact, 0, - VmFactMutationKind::Insert}); -} - -namespace { -void requireMatchingSnapshot(const VmFactPtr ¤t, const VmFactPtr &snapshot) { - if (!vmValuesEqualInternal(VmValue{current}, VmValue{snapshot})) - throw IrError("fact mutation uses a stale fact snapshot"); -} -} // namespace - -VmFactPtr VmFactStore::currentSnapshotLocked(const VmFactPtr &fact) const { - if (persistence_) { - auto stored = persistentSnapshotLocked(fact->id).fact; - requireMatchingSnapshot(stored, fact); - return stored; - } - const auto known = - std::find_if(facts_.begin(), facts_.end(), - [&](const auto &item) { return item->id == fact->id; }); - if (known == facts_.end()) - throw IrError( - "fact mutation targets a fact outside this knowledge runtime"); - requireMatchingSnapshot(*known, fact); - return *known; -} - -VmFactPtr VmFactStore::mutate(const VmFactPtr &fact, IrSymbolRef field, - const VmValue &value, IrSymbolRef procedure) { - if (!fact || fact->id == 0 || field == 0 || !validVmValue(value)) - throw IrError("fact mutation is invalid"); - std::lock_guard lock(mutex_); - const auto current = currentSnapshotLocked(fact); - auto updated = std::make_shared(*current); - bool hadField = false; - for (auto &[existing, previous] : updated->fields) { - if (existing == field) { - previous = value; - hadField = true; - break; - } - } - if (!hadField) { - updated->fields.emplace_back(field, value); - } - validateDeclaredIndexKeysLocked(updated); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - const auto source = persistentSnapshotLocked(fact->id).source; - const auto value = Form::encodeStoredFact( - *updated, - source ? std::optional{*source} - : std::optional{}, - symbolTable_); - std::vector mutation{ - {Form::RocksDb::Mutation::Kind::Put, storedFactKey(updated->id), - value}}; - const std::optional sourceView = - source ? std::optional{*source} - : std::optional{}; - for (auto &key : persistentIndexKeysLocked(current, sourceView)) - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); - for (auto &key : persistentIndexKeysLocked(updated, sourceView)) - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); - persistence_->commit(mutation); - } -#endif - if (!persistence_) { - removeFromDeclaredIndexesLocked(current); - const auto replace = [&](auto &items) { - const auto item = - std::find_if(items.begin(), items.end(), [&](const auto &entry) { - return entry->id == current->id; - }); - if (item == items.end()) - throw IrError("fact store index is inconsistent"); - *item = updated; - }; - replace(facts_); - replace(byType_.at(current->type)); - for (const auto &[indexedField, _] : current->fields) - replace(byField_.at(indexedField)); - if (!hadField) - byField_[field].push_back(updated); - addToDeclaredIndexesLocked(updated); - } - mutations_.push_back(VmFactMutation{nextSequence_++, fact->id, field, - VmFactMutationKind::Update}); - provenance_.push_back(VmFactProvenance{ - fact->id, procedure, fact->origin == VmFact::Origin::Derived}); - ++contentRevision_; - return updated; -} - -std::size_t VmFactStore::erase(std::span facts) { - std::lock_guard lock(mutex_); - std::unordered_map requested; - for (const auto &fact : facts) { - if (fact && fact->id != 0) { - const auto [entry, inserted] = requested.emplace(fact->id, fact); - if (!inserted) - requireMatchingSnapshot(entry->second, fact); - } - } - if (requested.empty()) - return 0; - - std::vector removed; - std::unordered_map> removedSources; - if (persistence_) { - removed.reserve(requested.size()); - for (const auto &[id, requestedFact] : requested) { - auto stored = persistentSnapshotLocked(id); - requireMatchingSnapshot(stored.fact, requestedFact); - removed.push_back(std::move(stored.fact)); - removedSources.emplace(id, std::move(stored.source)); - } - } else { - for (const auto &fact : facts_) { - if (const auto found = requested.find(fact->id); found != requested.end()) { - requireMatchingSnapshot(fact, found->second); - removed.push_back(fact); - } - } - } - if (removed.size() != requested.size()) - throw IrError("fact deletion targets a fact outside this knowledge runtime"); - -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - std::vector mutations; - mutations.reserve(removed.size()); - for (const auto &fact : removed) { - mutations.push_back({Form::RocksDb::Mutation::Kind::Erase, - storedFactKey(fact->id), {}}); - const auto &source = removedSources.at(fact->id); - const std::optional sourceView = - source ? std::optional{*source} - : std::optional{}; - for (auto &key : persistentIndexKeysLocked(fact, sourceView)) - mutations.push_back( - {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); - } - persistence_->commit(mutations); - } -#endif - if (!persistence_) { - for (const auto &fact : removed) - removeFromDeclaredIndexesLocked(fact); - const auto removeIds = [&](auto &items) { - std::erase_if(items, [&](const auto &item) { - return item && requested.contains(item->id); - }); - }; - removeIds(facts_); - for (auto &[_, items] : byType_) - removeIds(items); - for (auto &[_, items] : byField_) - removeIds(items); - std::erase_if(byType_, [](const auto &entry) { return entry.second.empty(); }); - std::erase_if(byField_, [](const auto &entry) { return entry.second.empty(); }); - } - for (const auto &fact : removed) { - if (!persistence_) - factSource_.erase(fact->id); - mutations_.push_back(VmFactMutation{nextSequence_++, fact->id, 0, - VmFactMutationKind::Delete}); - } - ++membershipRevision_; - ++knowledgeRevision_; - return removed.size(); -} - -void VmFactStore::restore(const VmFactPtr ¤t, - const VmFactPtr &previous) { - if (!current || !previous || current->id == 0 || - current->id != previous->id || current->type != previous->type) - throw IrError("fact rollback snapshots are incompatible"); - std::lock_guard lock(mutex_); - const auto stored = currentSnapshotLocked(current); - validateDeclaredIndexKeysLocked(previous); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - const auto source = persistentSnapshotLocked(previous->id).source; - const auto value = Form::encodeStoredFact( - *previous, - source ? std::optional{*source} - : std::optional{}, - symbolTable_); - std::vector mutation{ - {Form::RocksDb::Mutation::Kind::Put, storedFactKey(previous->id), - value}}; - const std::optional sourceView = - source ? std::optional{*source} - : std::optional{}; - for (auto &key : persistentIndexKeysLocked(stored, sourceView)) - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); - for (auto &key : persistentIndexKeysLocked(previous, sourceView)) - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); - persistence_->commit(mutation); - } -#endif - if (!persistence_) { - removeFromDeclaredIndexesLocked(stored); - const auto replaceById = [&](auto &items) { - const auto found = - std::find_if(items.begin(), items.end(), [&](const auto &item) { - return item && item->id == current->id; - }); - if (found == items.end()) - throw IrError("fact rollback target is absent"); - *found = previous; - }; - replaceById(facts_); - replaceById(byType_.at(current->type)); - for (auto &[_, items] : byField_) - std::erase_if(items, [&](const auto &item) { - return item && item->id == current->id; - }); - for (const auto &[field, _] : previous->fields) - byField_[field].push_back(previous); - addToDeclaredIndexesLocked(previous); - std::erase_if(byField_, - [](const auto &entry) { return entry.second.empty(); }); - } - ++contentRevision_; - ++knowledgeRevision_; -} - -void VmFactStore::restoreErased(const VmFactPtr &fact, - std::optional source) { - if (!fact || fact->id == 0) - throw IrError("deleted fact rollback snapshot is invalid"); - std::lock_guard lock(mutex_); - validateDeclaredIndexKeysLocked(fact); - if (persistence_) { -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_->database.get(storedFactKey(fact->id))) - throw IrError("deleted fact rollback would duplicate fact identity"); -#endif - } else if (std::any_of(facts_.begin(), facts_.end(), - [&](const auto &existing) { - return existing->id == fact->id; - })) { - throw IrError("deleted fact rollback would duplicate fact identity"); - } -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - const auto value = Form::encodeStoredFact( - *fact, - source ? std::optional{*source} - : std::optional{}, - symbolTable_); - std::vector mutation{ - {Form::RocksDb::Mutation::Kind::Put, storedFactKey(fact->id), value}}; - const std::optional sourceView = - source ? std::optional{*source} - : std::optional{}; - for (auto &key : persistentIndexKeysLocked(fact, sourceView)) - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); - persistence_->commit(mutation); - } -#endif - if (!persistence_) { - facts_.push_back(fact); - byType_[fact->type].push_back(fact); - for (const auto &[field, _] : fact->fields) - byField_[field].push_back(fact); - addToDeclaredIndexesLocked(fact); - if (source) - factSource_[fact->id] = std::move(*source); - const auto order = [](auto &items) { - std::sort(items.begin(), items.end(), - [](const auto &left, const auto &right) { - return left->createdSequence < right->createdSequence; - }); - }; - order(facts_); - order(byType_[fact->type]); - for (const auto &[field, _] : fact->fields) - order(byField_[field]); - } - ++membershipRevision_; - ++knowledgeRevision_; -} - -std::vector VmFactStore::snapshot() const { - std::lock_guard lock(mutex_); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - bool more = false; - auto result = persistentFactsLocked(std::string_view{"F", 1}, 10'001, &more); - if (more || result.size() > 10'000) - throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); - return result; - } -#endif - return facts_; -} - -std::vector VmFactStore::snapshot(IrSymbolRef type) const { - std::lock_guard lock(mutex_); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - bool more = false; - auto result = persistentFactsLocked( - storedConcreteTypeIndexPrefix(irSymbolPieces(symbolTable_, type)), - 10'001, &more); - if (more || result.size() > 10'000) - throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); - return result; - } -#endif - const auto found = byType_.find(type); - return found == byType_.end() ? std::vector{} : found->second; -} - -void VmFactStore::recordSource(IrFactRef fact, std::string source) { - if (fact == 0) - throw IrError("fact source cannot be recorded for an invalid fact"); - std::lock_guard lock(mutex_); - VmFactPtr stored; - std::optional previousSource; - if (persistence_) { - auto record = persistentSnapshotLocked(fact); - stored = std::move(record.fact); - previousSource = std::move(record.source); - } else { - const auto found = std::find_if( - facts_.begin(), facts_.end(), - [&](const auto &item) { return item->id == fact; }); - if (found == facts_.end()) - throw IrError( - "fact source recorded for a fact outside this knowledge runtime"); - stored = *found; - } -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - const auto value = Form::encodeStoredFact( - *stored, std::optional{source}, symbolTable_); - std::vector mutation{ - {Form::RocksDb::Mutation::Kind::Put, storedFactKey(fact), value}}; - if (previousSource) { - auto key = storedSourceIndexPrefix(*previousSource); - appendFactOrder(key, *stored); - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Erase, std::move(key), {}}); - } - auto key = storedSourceIndexPrefix(source); - appendFactOrder(key, *stored); - mutation.push_back( - {Form::RocksDb::Mutation::Kind::Put, std::move(key), {}}); - persistence_->commit(mutation); - } -#endif - if (!persistence_) - factSource_[fact] = std::move(source); -} - -std::optional VmFactStore::sourceOf(IrFactRef fact) const { - std::lock_guard lock(mutex_); - if (persistence_) - return persistentSnapshotLocked(fact).source; - const auto found = factSource_.find(fact); - if (found == factSource_.end()) - return std::nullopt; - return found->second; -} - -std::vector VmFactStore::sourcesForType(IrSymbolRef type) const { - std::lock_guard lock(mutex_); - std::set unique; -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - const auto prefix = - storedConcreteTypeIndexPrefix(irSymbolPieces(symbolTable_, type)); - std::optional after; - bool more = false; - do { - std::string lastKey; - const auto rows = persistentFactsLocked( - prefix, 4096, &more, - after ? std::optional{*after} : std::nullopt, - &lastKey); - for (const auto &fact : rows) - if (const auto source = persistentSnapshotLocked(fact->id).source) - unique.insert(*source); - after = std::move(lastKey); - } while (more && unique.size() < 2); - return {unique.begin(), unique.end()}; - } -#endif - const auto found = byType_.find(type); - if (found != byType_.end()) { - for (const auto &fact : found->second) { - const auto source = factSource_.find(fact->id); - if (source != factSource_.end()) - unique.insert(source->second); - } - } - return {unique.begin(), unique.end()}; -} - -std::vector -VmFactStore::snapshotBySource(std::string_view source) const { - std::lock_guard lock(mutex_); - std::vector result; -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - const auto prefix = storedSourceIndexPrefix(source); - std::optional after; - bool more = false; - do { - std::string lastKey; - auto rows = persistentFactsLocked(prefix, 4096, &more, - after ? std::optional{*after} : std::nullopt, - &lastKey); - result.insert(result.end(), rows.begin(), rows.end()); - after = std::move(lastKey); - } while (more); - // File persistence rewrites the complete owning source, not a query page. - // Only that source's index is scanned; unrelated facts are never loaded. - return result; - } -#endif - for (const auto &fact : facts_) { - const auto found = factSource_.find(fact->id); - if (found != factSource_.end() && found->second == source) - result.push_back(fact); - } - return result; -} - -std::vector -VmFactStore::hierarchyProof(IrSymbolRef child, IrSymbolRef ancestor) const { - std::lock_guard lock(mutex_); - if (child == 0 || ancestor == 0) - return {}; - if (!isAssignableToLocked(child, ancestor)) - return {}; - // A proof is evidence presented to the caller, so choose the shortest - // chain. Parent declaration order is the deterministic tie-breaker. - std::deque>> pending{ - {child, {child}}}; - std::unordered_set visited; - while (!pending.empty()) { - auto [current, proof] = std::move(pending.front()); - pending.pop_front(); - if (!visited.insert(current).second) - continue; - if (current == ancestor) - return proof; - const auto found = parents_.find(current); - if (found == parents_.end()) - continue; - for (const auto parent : found->second) { - auto next = proof; - next.push_back(parent); - pending.emplace_back(parent, std::move(next)); - } - } - return {}; -} - -std::vector> -VmFactStore::hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor) const { - constexpr std::size_t kMaximumProofPaths = 4096; - constexpr std::size_t kMaximumProofDepth = 4096; - std::lock_guard lock(mutex_); - if (child == 0 || ancestor == 0 || - !isAssignableToLocked(child, ancestor)) - return {}; - std::vector> result; - struct Frame { - std::vector parents; - std::size_t next = 0; - }; - const auto frame = [&](IrSymbolRef current) { - Frame result; - if (const auto found = parents_.find(current); found != parents_.end()) - result.parents = found->second; - std::sort(result.parents.begin(), result.parents.end()); - return result; - }; - std::vector path{child}; - std::vector stack{frame(child)}; - while (!path.empty()) { - if (path.size() > kMaximumProofDepth) - throw IrError("fact hierarchy proof depth exceeds its limit"); - if (path.back() == ancestor) { - if (result.size() == kMaximumProofPaths) - throw IrError("fact hierarchy proof-path limit exceeded"); - result.push_back(path); - path.pop_back(); - stack.pop_back(); - continue; - } - auto ¤t = stack.back(); - if (current.next == current.parents.size()) { - path.pop_back(); - stack.pop_back(); - continue; - } - const auto parent = current.parents[current.next++]; - if (std::ranges::find(path, parent) != path.end()) - throw IrError("fact hierarchy cycle reached proof enumeration"); - path.push_back(parent); - stack.push_back(frame(parent)); - } - std::sort(result.begin(), result.end(), [](const auto &left, - const auto &right) { - if (left.size() != right.size()) - return left.size() < right.size(); - return left < right; - }); - return result; -} - -std::vector VmFactStore::commonAncestors(IrSymbolRef left, - IrSymbolRef right) const { - std::lock_guard lock(mutex_); - if (left == 0 || right == 0) - return {}; - // Populate both entries before retaining references: inserting the second - // closure may rehash the cache and invalidate a reference to the first. - (void)ancestorClosureLocked(left); - (void)ancestorClosureLocked(right); - const auto &leftAncestors = ancestorClosureLocked(left); - const auto &rightAncestors = ancestorClosureLocked(right); - std::vector result; - for (const auto candidate : leftAncestors) - if (rightAncestors.contains(candidate)) - result.push_back(candidate); - std::sort(result.begin(), result.end()); - return result; -} - -std::vector -VmFactStore::commonAncestorEvidence(IrSymbolRef left, - IrSymbolRef right) const { - std::vector result; - for (const auto ancestor : commonAncestors(left, right)) { - auto leftProofs = hierarchyProofs(left, ancestor); - auto rightProofs = hierarchyProofs(right, ancestor); - if (leftProofs.empty() || rightProofs.empty()) - continue; - result.push_back( - {ancestor, std::move(leftProofs), std::move(rightProofs), 0, 0}); - auto &evidence = result.back(); - evidence.leftDistance = evidence.leftProofs.front().size() - 1; - evidence.rightDistance = evidence.rightProofs.front().size() - 1; - } - return result; -} - -std::vector -VmFactStore::rankByTimeAndPriority(IrSymbolRef effectiveAtField, - IrSymbolRef priorityField) const { - if (effectiveAtField == 0 || priorityField == 0) - throw IrError("fact ranking fields are invalid"); - std::lock_guard lock(mutex_); - const auto numberField = [](const VmFactPtr &fact, IrSymbolRef field, - const char *label) { - const auto found = - std::find_if(fact->fields.begin(), fact->fields.end(), - [&](const auto &item) { return item.first == field; }); - if (found == fact->fields.end()) - throw IrError(std::string("fact has no ") + label + " field"); - const auto number = std::get_if(&found->second); - if (!number || !std::isfinite(*number)) - throw IrError(std::string("fact ") + label + - " field is not finite numeric data"); - return *number; - }; - std::vector ranked; - const auto candidates = persistence_ ? persistentFactsLocked( - std::string_view{"F", 1}, 10'001) : facts_; - if (candidates.size() > 10'000) - throw IrError("fact ranking exceeds 10000 rows; filter before ranking"); - ranked.reserve(candidates.size()); - for (const auto &fact : candidates) - ranked.push_back({fact, numberField(fact, effectiveAtField, "effective-at"), - numberField(fact, priorityField, "priority")}); - std::sort(ranked.begin(), ranked.end(), - [](const auto &left, const auto &right) { - if (left.effectiveAt != right.effectiveAt) - return left.effectiveAt > right.effectiveAt; - if (left.priority != right.priority) - return left.priority > right.priority; - return left.fact->id < right.fact->id; - }); - return ranked; -} - -std::vector -VmFactStore::snapshotAssignableTo(IrSymbolRef type) const { - std::lock_guard lock(mutex_); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - bool more = false; - auto result = persistentFactsLocked( - storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)), 10'001, - &more); - if (more || result.size() > 10'000) - throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); - return result; - } -#endif - std::vector result; - for (const auto &[candidate, facts] : byType_) { - if (isAssignableToLocked(candidate, type)) - result.insert(result.end(), facts.begin(), facts.end()); - } - std::sort(result.begin(), result.end(), - [](const auto &left, const auto &right) { - if (left->createdSequence != right->createdSequence) - return left->createdSequence < right->createdSequence; - return left->id < right->id; - }); - return result; -} - -VmFactStore::Page VmFactStore::pageAssignableTo( - IrSymbolRef type, std::size_t records, - const std::optional &after) const { - return pageMatching(type, {}, records, after); -} - -VmFactStore::Page VmFactStore::pageMatching( - IrSymbolRef type, - std::span> predicates, - std::size_t records, const std::optional &after) const { - if (records > 10'000) - throw IrError("fact page exceeds the 10000 row limit"); - std::lock_guard lock(mutex_); -#ifdef FELIDAE_HAS_ROCKSDB - if (!persistence_) - throw IrError("indexed fact pagination requires a RocksDB store"); - const auto plan = equalityPlanLocked(type, predicates); - auto prefix = storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)); - if (plan.index) { - prefix = storedExactIndexPrefix(irSymbolPieces(symbolTable_, plan.owner), - declaredIndexes_.at(plan.owner), plan.ordinal, symbolTable_); - appendOrderedKey(prefix, predicateIndexKey(plan.index->fields, plan.covered, - predicates, symbolTable_)); - } - // Bind residual predicates and requested subtype as well as the physical - // index. Canonical map encoding makes argument order irrelevant. - auto predicateMap = std::make_shared(); - predicateMap->entries.assign(predicates.begin(), predicates.end()); - std::string query; - appendPieceKey(query, irSymbolPieces(symbolTable_, type)); - appendOrderedKey(query, Form::encodeStoredValueKey(predicateMap, symbolTable_)); - const auto identity = persistence_->database.identity(); - if (after) { - if (after->database != identity || after->index != prefix || - after->query != query) - throw IrError("fact cursor belongs to another database or query index"); - if (after->revision != persistence_->revision) - throw IrError("fact cursor snapshot expired after a store mutation"); - // A partially covered composite key also contains remaining field values. - if (after->lastKey.size() < prefix.size() + 16 || - !after->lastKey.starts_with(prefix) || - !persistence_->database.get(after->lastKey)) - throw IrError("fact cursor has an invalid continuation key"); - } - Page result; - result.revision = persistence_->revision; - std::optional lastKey = after - ? std::optional{after->lastKey} : std::nullopt; - std::optional continuation = lastKey; - // One lookahead matching row establishes hasMore. Residual filtering is - // bounded independently of output size, so sparse queries cannot run forever. - std::size_t examined = 0; - while (!result.hasMore) { - std::vector keys; - const auto count = std::min(256, records - result.rows.size() + 1); - const auto rows = persistentFactsLocked(prefix, count, nullptr, - lastKey ? std::optional{*lastKey} : std::nullopt, - nullptr, &keys); - if (rows.empty()) - break; - for (std::size_t i = 0; i < rows.size(); ++i) { - if (++examined > 10'001) - throw IrError("fact page candidate limit exceeded; use a more selective index"); - lastKey = keys[i]; - if (!matchesLocked(rows[i], type, predicates)) - continue; - if (result.rows.size() == records) { - result.hasMore = true; - break; - } - result.rows.push_back(rows[i]); - continuation = keys[i]; - } - } - if (result.hasMore && continuation) - result.next = Cursor{identity, prefix, query, std::move(*continuation), - result.revision}; - return result; -#else - (void)type; - (void)predicates; - (void)after; - throw IrError("this VM build has no RocksDB fact-store support"); -#endif -} - -VmFactStore::EqualityPlan VmFactStore::equalityPlanLocked( - IrSymbolRef type, - std::span> predicates) const { - if (!parents_.contains(type)) - throw IrError("fact query references an unregistered type"); - std::unordered_set predicateFields; - for (const auto &[field, value] : predicates) { - if (field == 0 || !predicateFields.insert(field).second || - !validVmValue(value)) - throw IrError("fact query contains an invalid or duplicate predicate"); - } - - EqualityPlan plan; - for (const auto &[owner, indexes] : exactIndexes_) { - if (!isAssignableToLocked(type, owner)) - continue; - for (std::size_t ordinal = 0; ordinal < indexes.size(); ++ordinal) { - const auto &index = indexes[ordinal]; - std::size_t covered = 0; - while (covered < index.fields.size() && - predicateFields.contains(index.fields[covered])) - ++covered; - const auto winsTie = [&] { - if (!plan.index || covered != plan.covered || - index.fields.size() != plan.index->fields.size()) - return false; - // Runtime handles may change when a database is reopened. Durable - // plans must break equal-coverage ties by canonical index identity, - // never unordered-map iteration or process-local symbol numbering. - if (persistence_) - return storedExactIndexPrefix(irSymbolPieces(symbolTable_, owner), - declaredIndexes_.at(owner), ordinal, symbolTable_) < - storedExactIndexPrefix(irSymbolPieces(symbolTable_, plan.owner), - declaredIndexes_.at(plan.owner), plan.ordinal, symbolTable_); - return std::pair{owner, ordinal} < std::pair{plan.owner, plan.ordinal}; - }; - if (covered != 0 && - (covered > plan.covered || - (covered == plan.covered && plan.index && - index.fields.size() < plan.index->fields.size()) || winsTie())) { - plan = {&index, owner, ordinal, covered}; - } - } - } - return plan; -} - -std::vector VmFactStore::snapshotMatching( - IrSymbolRef type, - std::span> predicates) const { - constexpr std::size_t kMaximumUnindexedScan = 10'000; - if (predicates.empty()) - throw IrError("fact query requires at least one predicate"); - std::lock_guard lock(mutex_); - const auto plan = equalityPlanLocked(type, predicates); - const auto *selected = plan.index; - const auto selectedFields = plan.covered; - - std::vector candidates; - if (selected) { - const auto prefix = predicateIndexKey(selected->fields, selectedFields, - predicates, symbolTable_); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - auto storagePrefix = storedExactIndexPrefix( - irSymbolPieces(symbolTable_, plan.owner), - declaredIndexes_.at(plan.owner), plan.ordinal, symbolTable_); - appendOrderedKey(storagePrefix, prefix); - bool more = false; - candidates = persistentFactsLocked(storagePrefix, 10'001, &more); - if (more || candidates.size() > 10'000) - throw IrError( - "fact query exceeds 10000 rows; use page(records:, after:)"); - } else -#endif - if (selectedFields == selected->fields.size()) { - const auto found = selected->rows.find(prefix); - if (found != selected->rows.end()) - candidates = found->second; - } else { - for (auto found = selected->rows.lower_bound(prefix); - found != selected->rows.end() && found->first.size() >= prefix.size() && - std::equal(prefix.begin(), prefix.end(), found->first.begin()); - ++found) { - candidates.insert(candidates.end(), found->second.begin(), - found->second.end()); - } - } - } else { - const auto oversizedScan = [] { - throw IrError("fact query exceeds the bounded unindexed scan; declare " - "an index covering its equality fields"); - }; -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - bool more = false; - candidates = persistentFactsLocked( - storedTypeIndexPrefix(irSymbolPieces(symbolTable_, type)), - kMaximumUnindexedScan + 1, &more); - if (more || candidates.size() > kMaximumUnindexedScan) - oversizedScan(); - } else -#endif - { - for (const auto &[candidateType, rows] : byType_) { - if (!isAssignableToLocked(candidateType, type)) - continue; - // Bound before copying, not after allocating the entire candidate set. - if (rows.size() > kMaximumUnindexedScan - candidates.size()) - oversizedScan(); - candidates.insert(candidates.end(), rows.begin(), rows.end()); - } - } - } - - std::erase_if(candidates, [&](const auto &fact) { - return !matchesLocked(fact, type, predicates); - }); - std::sort(candidates.begin(), candidates.end(), - [](const auto &left, const auto &right) { - if (left->createdSequence != right->createdSequence) - return left->createdSequence < right->createdSequence; - return left->id < right->id; - }); - return candidates; -} - -bool VmFactStore::matchesLocked( - const VmFactPtr &fact, IrSymbolRef type, - std::span> predicates) const { - if (!fact || !isAssignableToLocked(fact->type, type)) - return false; - return std::all_of(predicates.begin(), predicates.end(), - [&](const auto &predicate) { - const auto found = std::find_if(fact->fields.begin(), fact->fields.end(), - [&](const auto &entry) { return entry.first == predicate.first; }); - return found != fact->fields.end() && - vmValuesEqualInternal(found->second, predicate.second); - }); -} - -std::vector VmFactStore::parentsOf(IrSymbolRef type) const { - std::lock_guard lock(mutex_); - const auto found = parents_.find(type); - return found == parents_.end() ? std::vector{} - : found->second; -} - -std::vector VmFactStore::snapshotByField(IrSymbolRef field) const { - std::lock_guard lock(mutex_); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - bool more = false; - auto result = persistentFactsLocked( - storedFieldIndexPrefix(irSymbolPieces(symbolTable_, field)), 10'001, - &more); - if (more || result.size() > 10'000) - throw IrError("fact query exceeds 10000 rows; use page(records:, after:)"); - return result; - } -#endif - const auto found = byField_.find(field); - return found == byField_.end() ? std::vector{} : found->second; -} - -std::vector VmFactStore::mutations() const { - std::lock_guard lock(mutex_); - return mutations_; -} -std::vector VmFactStore::provenance() const { - std::lock_guard lock(mutex_); - return provenance_; -} - -VmFactStoreJournalMark VmFactStore::journalMark() const { - std::lock_guard lock(mutex_); - return {mutations_.size(), provenance_.size()}; -} - -void VmFactStore::rollbackJournal(VmFactStoreJournalMark mark) { - std::lock_guard lock(mutex_); - if (mark.mutations > mutations_.size() || - mark.provenance > provenance_.size()) - throw IrError("fact mutation journal rollback mark is invalid"); - mutations_.resize(mark.mutations); - provenance_.resize(mark.provenance); -} - -VmKnowledgeSnapshot VmFactStore::knowledgeSnapshot() const { - std::uint64_t revision = std::numeric_limits::max(); - VmKnowledgeSnapshot result; - refreshKnowledgeSnapshot(revision, result); - return result; -} - -void VmFactStore::refreshKnowledgeSnapshot(std::uint64_t &knownRevision, - VmKnowledgeSnapshot &result) const { - std::lock_guard lock(mutex_); - if (knownRevision == knowledgeRevision_) - return; - result = {}; - if (persistence_) { -#ifdef FELIDAE_HAS_ROCKSDB - for (const auto &[type, _] : parents_) { - const auto prefix = storedConcreteTypeIndexPrefix( - irSymbolPieces(symbolTable_, type)); - std::optional after; - std::uint64_t count = 0; - bool more = false; - do { - const auto page = persistence_->database.scanPrefix( - prefix, - after ? std::optional{*after} : std::nullopt, - Form::RocksDb::maximumScanRecords); - count += page.rows.size(); - more = page.hasMore; - if (!page.rows.empty()) - after = page.rows.back().first; - } while (more && count <= std::numeric_limits::max()); - if (count == 0) - continue; - result.factTypes.push_back(type); - result.factTypeCounts.emplace_back( - type, static_cast(std::min( - count, std::numeric_limits::max()))); - } -#endif - } else { - result.factTypes.reserve(byType_.size()); - result.factTypeCounts.reserve(byType_.size()); - for (const auto &[type, facts] : byType_) { - result.factTypes.push_back(type); - result.factTypeCounts.emplace_back( - type, static_cast(std::min( - facts.size(), static_cast( - std::numeric_limits::max())))); - } - } - std::sort(result.factTypes.begin(), result.factTypes.end()); - std::sort(result.factTypeCounts.begin(), result.factTypeCounts.end()); - for (const auto &[child, parents] : parents_) { - for (const auto parent : parents) - result.hierarchyEdges.emplace_back(child, parent); - } - std::sort(result.hierarchyEdges.begin(), result.hierarchyEdges.end()); - knownRevision = knowledgeRevision_; -} - -VmFactStoreRevisions VmFactStore::revisions() const { - std::lock_guard lock(mutex_); - return {hierarchyRevision_, membershipRevision_, contentRevision_}; -} - -std::size_t VmFactStore::size() const { - std::lock_guard lock(mutex_); -#ifdef FELIDAE_HAS_ROCKSDB - if (persistence_) { - std::optional after; - std::size_t count = 0; - bool more = false; - do { - const auto page = persistence_->database.scanPrefix( - std::string_view{"F", 1}, - after ? std::optional{*after} : std::nullopt, - Form::RocksDb::maximumScanRecords); - if (page.rows.size() > std::numeric_limits::max() - count) - throw IrError("fact store size exceeds this platform's range"); - count += page.rows.size(); - more = page.hasMore; - if (!page.rows.empty()) - after = page.rows.back().first; - } while (more); - return count; - } -#endif - return facts_.size(); -} - -double VmFactStore::gaussianMembership(double value, - const VmGaussianProfile &profile) { - constexpr double kTailMembership = 0.01; - if (!std::isfinite(value) || !std::isfinite(profile.peak) || - !std::isfinite(profile.fadesIn) || !std::isfinite(profile.fadesOut) || - profile.fadesIn > profile.peak || profile.peak > profile.fadesOut) { - throw IrError("Gaussian profile is invalid"); - } - const auto sigmaFor = [](double distance) { - return distance / std::sqrt(-2.0 * std::log(kTailMembership)); - }; - const auto leftDistance = profile.peak - profile.fadesIn; - const auto rightDistance = profile.fadesOut - profile.peak; - const auto fallback = std::max(leftDistance, rightDistance); - if (fallback == 0.0) - return value == profile.peak ? 1.0 : 0.0; - const auto sigma = - value <= profile.peak - ? sigmaFor(leftDistance == 0.0 ? fallback : leftDistance) - : sigmaFor(rightDistance == 0.0 ? fallback : rightDistance); - const auto z = (value - profile.peak) / sigma; - return std::exp(-0.5 * z * z); -} - -FelidaeKnowledgeRuntime::FelidaeKnowledgeRuntime( - RuntimeStateModel *semanticModel, std::size_t maximumSemanticSteps, - std::size_t maximumCallDepth, std::shared_ptr factStore, - TensorRuntime *tensorRuntime, VmTextDecoder textDecoder, - VmTextEncoder textEncoder) - : factStore_(factStore ? std::move(factStore) - : std::make_shared()), - semanticModel_(semanticModel), tensorRuntime_(tensorRuntime), - textDecoder_(std::move(textDecoder)), - textEncoder_(std::move(textEncoder)), - maximumSemanticSteps_(maximumSemanticSteps), - maximumCallDepth_(maximumCallDepth) { - if (maximumSemanticSteps_ == 0) - throw IrError("direct VM semantic step limit must be positive"); - if (maximumCallDepth_ == 0) - throw IrError("direct VM call depth limit must be positive"); -} - -VmFactPtr FelidaeKnowledgeRuntime::retainFact(const VmFactPtr &fact) { - return factStore_->retain(fact); -} - -VmFactPtr FelidaeKnowledgeRuntime::retainPersistentFact( - const VmFactPtr &fact, std::span source) { - const auto path = decodeText(source); - if (path.empty()) - throw IrError("persistent fact source path must not be empty"); - auto retained = factStore_->retain(fact); - factStore_->recordSource(retained->id, path); - return retained; -} - -VmFactPtr FelidaeKnowledgeRuntime::mutateFact(const VmFactPtr &fact, - IrSymbolRef field, - const VmValue &value) { - return factStore_->mutate( - fact, field, value, - callFrames_.empty() ? 0 : callFrames_.back().procedure); -} - -double FelidaeKnowledgeRuntime::deleteFacts(std::span facts) { - std::map> persistent; - std::vector memory; - for (const auto &fact : facts) { - if (!fact) - throw IrError("fact deletion contains an invalid fact"); - if (const auto source = factStore_->sourceOf(fact->id)) - persistent[*source].push_back(fact); - else - memory.push_back(fact); - } - std::size_t deleted = factStore_->erase(memory); - std::vector committed; - for (const auto &[source, owned] : persistent) { - const auto journal = factStore_->journalMark(); - deleted += factStore_->erase(owned); - try { - (void)persistDatabaseSource(source, owned.front()); - } catch (const std::exception &error) { - for (const auto &fact : owned) - factStore_->restoreErased(fact, source); - factStore_->rollbackJournal(journal); - std::ostringstream message; - message << "fact deletion persistence failed for " << source; - if (!committed.empty()) { - message << " after committing"; - for (const auto &path : committed) - message << ' ' << path; - } - message << ": " << error.what(); - throw IrError(message.str()); - } - committed.push_back(source); - } - return static_cast(deleted); -} - -VmFactPtr FelidaeKnowledgeRuntime::insertFact( - std::span type, const VmMapPtr &values, - std::optional> source) { - if (!values) - throw IrError("fact insertion requires a values map"); - auto fact = std::make_shared(); - fact->type = internRuntimeSymbol(PieceSequence(type.begin(), type.end())); - fact->fields = values->entries; - std::optional owner; - if (source) { - owner = decodeText(*source); - if (owner->empty()) - throw IrError("fact insertion source path must not be empty"); - } else { - const auto known = factStore_->sourcesForType(fact->type); - if (known.size() == 1) - owner = known.front(); - else if (known.size() > 1) - throw IrError( - "fact insertion requires source when its type has multiple sources"); - } - const auto journal = factStore_->journalMark(); - auto retained = factStore_->retain(fact); - if (owner && !owner->empty()) { - factStore_->recordSource(retained->id, *owner); - try { - (void)persistDatabaseSource(*owner); - } catch (...) { - (void)factStore_->erase(std::array{retained}); - factStore_->rollbackJournal(journal); - throw; - } - } - factStore_->recordInsert(retained->id); - return retained; -} - -VmValue FelidaeKnowledgeRuntime::updateFacts( - std::span facts, const VmMapPtr &values) { - if (!values) - throw IrError("fact update requires a values map"); - std::map> persistent; - std::vector memory; - for (const auto &fact : facts) { - if (!fact) - throw IrError("fact update contains an invalid fact"); - if (const auto source = factStore_->sourceOf(fact->id)) - persistent[*source].push_back(fact); - else - memory.push_back(fact); - } - std::unordered_map updatedById; - const auto apply = [&](std::span selected) { - for (auto fact : selected) { - for (const auto &[field, value] : values->entries) - fact = mutateFact(fact, field, value); - updatedById[fact->id] = fact; - } - }; - apply(memory); - std::vector committed; - for (const auto &[source, owned] : persistent) { - const auto journal = factStore_->journalMark(); - apply(owned); - try { - (void)persistDatabaseSource(source); - } catch (const std::exception &error) { - for (const auto &previous : owned) { - const auto current = updatedById.at(previous->id); - factStore_->restore(current, previous); - updatedById[previous->id] = previous; - } - factStore_->rollbackJournal(journal); - std::ostringstream message; - message << "fact update persistence failed for " << source; - if (!committed.empty()) { - message << " after committing"; - for (const auto &path : committed) - message << ' ' << path; - } - message << ": " << error.what(); - throw IrError(message.str()); - } - committed.push_back(source); - } - auto result = std::make_shared(); - result->values.reserve(facts.size()); - for (const auto &fact : facts) - result->values.emplace_back(updatedById.at(fact->id)); - return result; -} - -VmValue FelidaeKnowledgeRuntime::projectFacts( - std::span facts, std::span fields) { - std::vector keys; - keys.reserve(fields.size()); - for (const auto &field : fields) - keys.push_back(internRuntimeSymbol(field.pieces)); - auto result = std::make_shared(); - result->values.reserve(facts.size()); - for (const auto &fact : facts) { - auto projected = std::make_shared(); - for (const auto key : keys) { - const auto found = std::find_if( - fact->fields.begin(), fact->fields.end(), - [&](const auto &entry) { return entry.first == key; }); - if (found == fact->fields.end()) - throw IrError("fact projection references a missing field"); - projected->entries.push_back(*found); - } - result->values.emplace_back(std::move(projected)); - } - return result; -} - -double FelidaeKnowledgeRuntime::aggregateFacts( - std::span facts, std::span field, - std::uint8_t operation) { - if (operation > 3) - throw IrError("fact aggregate operation is invalid"); - const auto key = internRuntimeSymbol(PieceSequence(field.begin(), field.end())); - std::vector values; - values.reserve(facts.size()); - for (const auto &fact : facts) { - const auto found = std::find_if( - fact->fields.begin(), fact->fields.end(), - [&](const auto &entry) { return entry.first == key; }); - if (found == fact->fields.end()) - throw IrError("fact aggregate references a missing field"); - const auto number = std::get_if(&found->second); - if (!number || !std::isfinite(*number)) - throw IrError("fact aggregate field must contain finite numbers"); - values.push_back(*number); - } - // Mirrors the existing array-based Sum/Average/Min/Max convention in - // Builtin.cpp exactly (see its BuiltinId::Sum/Average/Min/Max case): an - // empty Sum is 0.0, not an error -- every other empty aggregate throws. - // Do not duplicate a different empty-input rule here. - if (values.empty()) { - if (operation == 0) - return 0.0; - throw IrError("fact aggregate requires at least one matching fact"); - } - if (operation == 0 || operation == 1) { - const auto total = std::accumulate( - values.begin(), values.end(), 0.0L, - [](long double sum, double value) { return sum + value; }); - const auto result = static_cast( - operation == 0 ? total - : total / static_cast(values.size())); - if (!std::isfinite(result)) - throw IrError("fact aggregate produced a non-finite result"); - return result; - } - if (operation == 2) - return *std::min_element(values.begin(), values.end()); - return *std::max_element(values.begin(), values.end()); -} - -VmValue FelidaeKnowledgeRuntime::searchFacts( - std::span facts, std::span field, - const VmMapPtr &options) { - if (!options) - throw IrError("fact search requires an options map"); - const auto fieldKey = - internRuntimeSymbol(PieceSequence(field.begin(), field.end())); - const auto option = [&](std::string_view name) -> const VmValue * { - const auto key = internRuntimeSymbol(encodeText(name)); - const auto found = std::find_if( - options->entries.begin(), options->entries.end(), - [&](const auto &entry) { return entry.first == key; }); - return found == options->entries.end() ? nullptr : &found->second; - }; - const auto textOption = [&](std::string_view name, - bool required) -> std::optional { - const auto *value = option(name); - if (!value) { - if (required) - throw IrError("fact search requires " + std::string(name)); - return std::nullopt; - } - const auto text = std::get_if(value); - if (!text) - throw IrError("fact search " + std::string(name) + " must be text"); - return decodeText(text->pieces); - }; - const auto numberOption = [&](std::string_view name) - -> std::optional { - const auto *value = option(name); - if (!value) - return std::nullopt; - if (const auto number = std::get_if(value)) { - if (!std::isfinite(*number)) - throw IrError("fact search " + std::string(name) + - " must be finite"); - return *number; - } - if (const auto degree = std::get_if(value)) - return degree->value; - throw IrError("fact search " + std::string(name) + - " must be numeric"); - }; - const auto valueType = [](const VmValue &value) -> std::optional { - if (const auto symbol = std::get_if(&value)) - return symbol->value; - if (const auto fact = std::get_if(&value); fact && *fact) - return (*fact)->type; - return std::nullopt; - }; - const auto asciiLower = [](std::string value) { - std::transform(value.begin(), value.end(), value.begin(), [](char byte) { - const auto current = static_cast(byte); - return static_cast(current >= 'A' && current <= 'Z' - ? current - 'A' + 'a' - : current); - }); - return value; - }; - const auto like = [](std::string_view value, std::string_view pattern) { - std::vector previous(value.size() + 1); - std::vector current(value.size() + 1); - previous[0] = 1; - for (std::size_t patternIndex = 0; patternIndex < pattern.size(); - ++patternIndex) { - std::fill(current.begin(), current.end(), 0); - char token = pattern[patternIndex]; - bool escaped = false; - if (token == '\\') { - if (++patternIndex == pattern.size()) - throw IrError("fact search LIKE pattern has a trailing escape"); - token = pattern[patternIndex]; - escaped = true; - } - if (!escaped && token == '%') { - current[0] = previous[0]; - for (std::size_t index = 1; index <= value.size(); ++index) - current[index] = previous[index] || current[index - 1]; - } else { - for (std::size_t index = 1; index <= value.size(); ++index) - current[index] = - previous[index - 1] && - ((!escaped && token == '_') || value[index - 1] == token); - } - previous.swap(current); - } - return previous[value.size()] != 0; - }; - - const auto searchType = *textOption("type", true); - auto result = std::make_shared(); - result->values.reserve(facts.size()); - const auto appendMatching = [&](const auto &matches) { - for (const auto &fact : facts) { - if (!fact) - throw IrError("fact search contains an invalid fact"); - const auto found = std::find_if( - fact->fields.begin(), fact->fields.end(), - [&](const auto &entry) { return entry.first == fieldKey; }); - if (found != fact->fields.end() && matches(found->second)) - result->values.emplace_back(fact); - } - }; - - if (searchType == "exact" || searchType == "prefix" || - searchType == "suffix" || searchType == "contains" || - searchType == "like" || searchType == "regex") { - auto query = *textOption("query", true); - const auto caseMode = textOption("case", false).value_or("sensitive"); - if (caseMode != "sensitive" && caseMode != "insensitive") - throw IrError("fact search case must be sensitive or insensitive"); - if (query.size() > 1024) - throw IrError("fact search pattern exceeds 1024 bytes"); - const bool insensitive = caseMode == "insensitive"; - const bool foldText = insensitive && searchType != "regex"; - if (foldText) - query = asciiLower(std::move(query)); - std::optional expression; - if (searchType == "regex") { - try { - auto flags = std::regex_constants::ECMAScript | - std::regex_constants::optimize; - if (insensitive) - flags |= std::regex_constants::icase; - expression.emplace(query, flags); - } catch (const std::regex_error &) { - throw IrError("fact search regular expression is invalid"); - } - } - appendMatching([&](const VmValue &value) { - const auto text = std::get_if(&value); - if (!text) - return false; - auto candidate = decodeText(text->pieces); - if (candidate.size() > 64 * 1024) - throw IrError("fact search text exceeds 64 KiB"); - if (foldText) - candidate = asciiLower(std::move(candidate)); - if (searchType == "exact") - return candidate == query; - if (searchType == "prefix") - return candidate.starts_with(query); - if (searchType == "suffix") - return candidate.ends_with(query); - if (searchType == "contains") - return candidate.find(query) != std::string::npos; - if (searchType == "like") - return like(candidate, query); - return std::regex_search(candidate, *expression); - }); - return result; - } - - if (searchType == "hierarchy") { - const auto *query = option("query"); - if (!query) - throw IrError("fact search hierarchy type requires query"); - const auto queryType = valueType(*query); - if (!queryType) - throw IrError("fact search hierarchy query must be a type or fact"); - const auto direction = *textOption("direction", true); - const auto includeSelf = numberOption("includeSelf").value_or(1.0); - if (includeSelf != 0.0 && includeSelf != 1.0) - throw IrError("fact search includeSelf must be 0.0 or 1.0"); - appendMatching([&](const VmValue &value) { - const auto candidate = valueType(value); - if (!candidate || (includeSelf == 0.0 && *candidate == *queryType)) - return false; - if (direction == "descendants") - return !factStore_->hierarchyProof(*candidate, *queryType).empty(); - if (direction == "ancestors") - return !factStore_->hierarchyProof(*queryType, *candidate).empty(); - if (direction == "related") - return !factStore_->commonAncestors(*candidate, *queryType).empty(); - throw IrError("fact search hierarchy direction is invalid"); - }); - return result; - } - - if (searchType == "degree") { - const auto query = numberOption("query"); - const auto tolerance = numberOption("tolerance"); - const auto minimum = numberOption("minimum"); - const auto maximum = numberOption("maximum"); - const bool closeness = query && tolerance; - const bool range = minimum || maximum; - if (closeness == range || (query.has_value() != tolerance.has_value())) - throw IrError( - "fact search degree requires query+tolerance or range bounds"); - // "degree" selects numeric closeness/range discovery; it is not an - // implicit truth conversion. Ordinary number fields therefore retain the - // language's unrestricted finite-double domain. VmDegree values remain - // bounded by their own constructor/type contract. - if (tolerance && *tolerance < 0.0) - throw IrError("fact search tolerance must be non-negative"); - if (minimum && maximum && *minimum > *maximum) - throw IrError("fact search degree minimum exceeds maximum"); - appendMatching([&](const VmValue &value) { - std::optional candidate; - if (const auto number = std::get_if(&value)) - candidate = *number; - else if (const auto degree = std::get_if(&value)) - candidate = degree->value; - if (!candidate || !std::isfinite(*candidate)) - return false; - if (closeness) - return std::fabs(*candidate - *query) <= *tolerance; - return (!minimum || *candidate >= *minimum) && - (!maximum || *candidate <= *maximum); - }); - return result; - } - - throw IrError("fact search type is invalid"); -} - -VmValue FelidaeKnowledgeRuntime::joinFacts( - std::span left, std::span right, - std::span leftField, std::span rightField, - std::uint8_t kind, IrSymbolRef joinedType, IrSymbolRef joinedLeft, - IrSymbolRef joinedRight) { - if (kind > 3) - throw IrError("fact join kind is invalid"); - // joinedType/joinedLeft/joinedRight (the "Joined"/"left"/"right" names - // synthesized for the ephemeral result fact) are resolved by the caller - // from compile-time symbol operands on IrOpcode::FactJoin -- see - // IrCodeGenerator.cpp's dedicated FactJoin lowering. RegisterVm never - // encodes text to pieces at runtime; only leftField/rightField (real - // field names from the source program's own string-literal constants) - // need interning here, exactly like every other query/aggregate path. - const auto leftKey = internRuntimeSymbol( - PieceSequence(leftField.begin(), leftField.end())); - const auto rightKey = internRuntimeSymbol( - PieceSequence(rightField.begin(), rightField.end())); - const auto read = [](const VmFactPtr &fact, - IrSymbolRef field) -> const VmValue * { - if (!fact) - return nullptr; - const auto found = std::find_if( - fact->fields.begin(), fact->fields.end(), - [&](const auto &entry) { return entry.first == field; }); - return found == fact->fields.end() ? nullptr : &found->second; - }; - auto result = std::make_shared(); - std::vector matchedRight(right.size(), false); - std::map> rightIndex; - for (std::size_t index = 0; index < right.size(); ++index) { - if (const auto *value = read(right[index], rightKey)) - rightIndex[Form::encodeStoredValueKey(*value, runtimeSymbolTable())] - .push_back(index); - } - const auto append = [&](VmValue leftValue, VmValue rightValue) { - auto joined = std::make_shared(); - joined->type = joinedType; - joined->fields = {{joinedLeft, std::move(leftValue)}, - {joinedRight, std::move(rightValue)}}; - result->values.emplace_back(VmFactPtr{std::move(joined)}); - }; - for (const auto &leftFact : left) { - const auto *leftValue = read(leftFact, leftKey); - bool matchedLeft = false; - if (leftValue) { - const auto found = rightIndex.find( - Form::encodeStoredValueKey(*leftValue, runtimeSymbolTable())); - if (found != rightIndex.end()) { - for (const auto index : found->second) { - // The canonical key is designed to agree with structural equality; - // retain the authoritative equality check at this trust boundary. - const auto *rightValue = read(right[index], rightKey); - if (!rightValue || !vmValuesEqual(*leftValue, *rightValue)) - continue; - matchedLeft = true; - matchedRight[index] = true; - append(leftFact, right[index]); - } - } - } - if (!matchedLeft && (kind == 1 || kind == 3)) - append(leftFact, VmNil{}); - } - if (kind == 2 || kind == 3) - for (std::size_t index = 0; index < right.size(); ++index) - if (!matchedRight[index]) - append(VmNil{}, right[index]); - return result; -} - -void FelidaeKnowledgeRuntime::registerFactType( - IrSymbolRef type, std::vector parents, - std::vector> indexes) { - factStore_->registerType(type, std::move(parents), std::move(indexes)); - registeredFactTypes_.insert(type); -} - -std::vector -FelidaeKnowledgeRuntime::snapshotFacts(IrSymbolRef type) { - return factStore_->snapshotAssignableTo(type); -} - -std::vector FelidaeKnowledgeRuntime::snapshotMatchingFacts( - IrSymbolRef type, - std::span> predicates) { - return factStore_->snapshotMatching(type, predicates); -} - -std::vector -FelidaeKnowledgeRuntime::hierarchyProof(IrSymbolRef child, - IrSymbolRef ancestor) { - return factStore_->hierarchyProof(child, ancestor); -} - -std::vector> -FelidaeKnowledgeRuntime::hierarchyProofs(IrSymbolRef child, - IrSymbolRef ancestor) { - return factStore_->hierarchyProofs(child, ancestor); -} -std::vector -FelidaeKnowledgeRuntime::commonAncestors(IrSymbolRef left, IrSymbolRef right) { - return factStore_->commonAncestors(left, right); -} - -std::vector -FelidaeKnowledgeRuntime::commonAncestorEvidence(IrSymbolRef left, - IrSymbolRef right) { - return factStore_->commonAncestorEvidence(left, right); -} - -VmValue FelidaeKnowledgeRuntime::ancestorAnalysis(IrSymbolRef left, - IrSymbolRef right) { - const auto candidateType = internRuntimeSymbol(encodeText("AncestorCandidate")); - const auto ancestorField = internRuntimeSymbol(encodeText("ancestor")); - const auto leftProofsField = internRuntimeSymbol(encodeText("leftProofs")); - const auto rightProofsField = internRuntimeSymbol(encodeText("rightProofs")); - const auto leftDistanceField = internRuntimeSymbol(encodeText("leftDistance")); - const auto rightDistanceField = - internRuntimeSymbol(encodeText("rightDistance")); - const auto paths = [](const std::vector> &proofs) { - auto result = std::make_shared(); - result->values.reserve(proofs.size()); - for (const auto &proof : proofs) { - auto path = std::make_shared(); - path->values.reserve(proof.size()); - for (const auto symbol : proof) - path->values.emplace_back(VmSymbol{symbol}); - result->values.emplace_back(std::move(path)); - } - return result; - }; - auto result = std::make_shared(); - const auto evidence = factStore_->commonAncestorEvidence(left, right); - result->values.reserve(evidence.size()); - for (const auto &candidate : evidence) { - auto fact = std::make_shared(); - fact->type = candidateType; - fact->origin = VmFact::Origin::Derived; - fact->fields = { - {ancestorField, VmSymbol{candidate.ancestor}}, - {leftProofsField, paths(candidate.leftProofs)}, - {rightProofsField, paths(candidate.rightProofs)}, - {leftDistanceField, static_cast(candidate.leftDistance)}, - {rightDistanceField, static_cast(candidate.rightDistance)}}; - result->values.emplace_back(std::move(fact)); - } - return result; -} -std::vector -FelidaeKnowledgeRuntime::rankFacts(IrSymbolRef effectiveAtField, - IrSymbolRef priorityField) { - return factStore_->rankByTimeAndPriority(effectiveAtField, priorityField); -} - -void FelidaeKnowledgeRuntime::installIrModule(const IrModule &module) { - module_ = {}; - module_.symbolTable = module.symbolTable; - module_.runtimeSymbols.reserve(module.symbolTable.size()); - for (const auto &pieces : module.symbolTable) - module_.runtimeSymbols.push_back(internRuntimeSymbol(pieces)); -} - -IrSymbolRef -FelidaeKnowledgeRuntime::internRuntimeSymbol(PieceSequence pieces) { - return factStore_->internSymbol(std::move(pieces)); -} - -IrSymbolRef -FelidaeKnowledgeRuntime::resolveSymbol(IrSymbolRef moduleSymbol) const { - if (module_.runtimeSymbols.empty()) - throw IrError("IR runtime has no installed module"); - if (moduleSymbol == 0 || moduleSymbol > module_.runtimeSymbols.size()) - throw IrError("IR module symbol index is outside its runtime mapping"); - return module_.runtimeSymbols[static_cast(moduleSymbol - 1)]; -} - -std::span -FelidaeKnowledgeRuntime::runtimeSymbolTable() const { - return factStore_->symbolTable(); -} - -void FelidaeKnowledgeRuntime::enterProcedure( - IrSymbolRef procedure, std::span parameters, - std::span arguments) { - if (parameters.size() != arguments.size()) - throw IrError("IR procedure received the wrong number of arguments"); - if (procedureDepth_ >= maximumCallDepth_) - throw IrError("IR procedure call depth exceeds its limit"); - ++procedureDepth_; - VmCallFrame frame; - frame.procedure = procedure; - for (std::size_t index = 0; index < parameters.size(); ++index) { - if (!frame.locals.emplace(parameters[index], arguments[index]).second) { - --procedureDepth_; - throw IrError("IR procedure parameter metadata is duplicated"); - } - } - callFrames_.push_back(std::move(frame)); -} - -void FelidaeKnowledgeRuntime::leaveProcedure() noexcept { - if (!callFrames_.empty()) - callFrames_.pop_back(); - if (procedureDepth_ != 0) - --procedureDepth_; -} - -VmValue FelidaeKnowledgeRuntime::loadSymbol(IrSymbolRef symbol) { - // Procedures are lexically isolated: a callee may read its own parameters - // and locals or module globals, never caller-local bindings. - if (!callFrames_.empty()) { - const auto local = callFrames_.back().locals.find(symbol); - if (local != callFrames_.back().locals.end()) - return local->second; - } - if (module_.symbolTable.empty()) - throw IrError("IR runtime has no installed module"); - const auto &globals = module_.globals; - const auto global = globals.find(symbol); - if (global == globals.end()) - throw IrError("direct VM runtime reads an undefined symbol"); - return global->second; -} - -void FelidaeKnowledgeRuntime::storeSymbol(IrSymbolRef symbol, - const VmValue &value) { - if (callFrames_.empty()) { - if (module_.symbolTable.empty()) - throw IrError("IR runtime has no installed module"); - auto &globals = module_.globals; - if (globals.contains(symbol)) { - throw IrError("direct VM runtime cannot rebind an immutable global"); - } - globals.emplace(symbol, value); - return; - } - auto &locals = callFrames_.back().locals; - if (locals.contains(symbol)) { - throw IrError("direct VM runtime cannot rebind an immutable local"); - } - locals.emplace(symbol, value); -} - -RuntimeStateModel *FelidaeKnowledgeRuntime::runtimeStateModel() { - return semanticModel_; -} - -TensorRuntime *FelidaeKnowledgeRuntime::tensorRuntime() { - return tensorRuntime_; -} - -std::string -FelidaeKnowledgeRuntime::decodeText(std::span pieces) const { - if (!textDecoder_) - return VmRuntime::decodeText(pieces); - return textDecoder_(pieces); -} - -PieceSequence FelidaeKnowledgeRuntime::encodeText(std::string_view text) const { - if (!textEncoder_) - return VmRuntime::encodeText(text); - return textEncoder_(text); -} - -VmText FelidaeKnowledgeRuntime::readFile( - std::span pathPieces) const { - constexpr std::uintmax_t kMaximumInputBytes = 64u * 1024u * 1024u; - const std::filesystem::path path(decodeText(pathPieces)); - std::error_code error; - const auto size = std::filesystem::file_size(path, error); - if (error) - throw IrError("file.readFile cannot inspect file: " + path.string()); - if (size > kMaximumInputBytes) - throw IrError("file.readFile input exceeds the 64 MiB limit"); - std::ifstream input(path, std::ios::binary); - if (!input) - throw IrError("file.readFile cannot open file: " + path.string()); - std::string text(static_cast(size), '\0'); - input.read(text.data(), static_cast(text.size())); - if (!input && !text.empty()) - throw IrError("file.readFile cannot complete read: " + path.string()); - return VmText{encodeText(text)}; -} - -VmValue FelidaeKnowledgeRuntime::importCsvFacts( - std::span data, std::span type, - std::span source) { - const auto typePieces = encodeText(decodeText(type)); - const auto knownType = factStore_->findSymbol(typePieces); - if (!knownType || !registeredFactTypes_.contains(*knownType)) { - throw IrError("csv.toFacts type must be declared in the IR module"); - } - - const Form::BuiltinTextCodec codec{ - [this](std::span pieces) { return decodeText(pieces); }, - [this](std::string_view text) { return encodeText(text); }}; - const auto typeName = decodeText(type); - const auto rows = Form::Csv::toFacts(decodeText(data), typeName); - // Empty means "no persistence source" (e.g. an anonymous csv.toFacts call - // never intended for persistence); only a non-empty source is recorded. - const std::optional sourceText = - source.empty() ? std::optional{} : decodeText(source); - auto result = std::make_shared(); - result->values.reserve(rows.size()); - for (const auto &row : rows) { - if (!row.is_object()) - throw IrError("csv.toFacts requires object rows"); - auto fact = std::make_shared(); - fact->type = *knownType; - fact->origin = VmFact::Origin::Asserted; - fact->fields.reserve(row.size()); - for (const auto &[name, value] : row.items()) { - if (name == "__type") - continue; - const auto field = internRuntimeSymbol(encodeText(name)); - fact->fields.emplace_back(field, Form::jsonToVmValue(value, codec)); - } - const auto retained = factStore_->retain(fact); - if (sourceText) - factStore_->recordSource(retained->id, *sourceText); - result->values.emplace_back(retained); - } - return result; -} - -double FelidaeKnowledgeRuntime::persistDatabaseSource( - std::string_view source, const VmFactPtr &emptySchema) { - const VmTextDecoder decoder = [this](std::span pieces) { - return decodeText(pieces); - }; - // Sync only the facts recorded as belonging to this source -- never the - // whole store, and never inferred from fact type alone, since two - // different files can share one fact type (see VmFactStore::recordSource). - Form::Db::sync(std::filesystem::path(source), - factStore_->snapshotBySource(source), factStore_->symbolTable(), - decoder, emptySchema, - [this](IrSymbolRef type) { - return factStore_->parentsOf(type); - }); - return 1.0; -} - -void FelidaeKnowledgeRuntime::beginExecution() { - if (executionDepth_++ == 0) { - executionState_ = - semanticModel_ ? semanticModel_->createExecutionState() : nullptr; - sharedSemanticSteps_ = std::make_shared(0); - } -} - -void FelidaeKnowledgeRuntime::endExecution() noexcept { - if (executionDepth_ == 0) - return; - if (--executionDepth_ == 0) { - executionState_.reset(); - sharedSemanticSteps_.reset(); - } -} - -RuntimeContext -FelidaeKnowledgeRuntime::makeRuntimeContext(const VmValue &) const { - RuntimeContext context; - context.maximumSemanticSteps = maximumSemanticSteps_; - context.executionState = executionState_; - context.sharedSemanticSteps = sharedSemanticSteps_; - context.symbolTable = &factStore_->symbolTable(); - factStore_->refreshKnowledgeSnapshot(context.knowledgeRevision, - context.knowledge); - return context; -} - -void FelidaeKnowledgeRuntime::refreshRuntimeContext( - RuntimeContext &context) const { - factStore_->refreshKnowledgeSnapshot(context.knowledgeRevision, - context.knowledge); -} -void IrVerifier::verify(const FelidaeIr &ir) { - if (ir.words.empty()) - throw IrError("IR is empty"); - if (ir.words.size() > kMaximumIrWords) - throw IrError("IR exceeds its word limit"); - if (ir.registerCount > kMaximumRegisters) - throw IrError("IR exceeds its register limit"); - if (ir.constants.size() > kMaximumIrTableEntries || - ir.symbols.size() > kMaximumIrTableEntries || - ir.texts.size() > kMaximumIrTableEntries || - ir.sourceMap.size() > kMaximumIrTableEntries) { - throw IrError("IR side table exceeds its entry limit"); - } - std::size_t textBytes = 0; - for (const auto &text : ir.texts) { - if (text.size() > kMaximumTextBytes - textBytes) - throw IrError("IR text table exceeds its byte limit"); - textBytes += text.size(); - } - std::unordered_set boundaries; - for (std::size_t scan = 0; scan < ir.words.size();) { - boundaries.insert(scan); - scan += irInstructionWidth(ir, scan); - } - for (const auto &entry : ir.sourceMap) { - if (!boundaries.contains(entry.instructionWord)) { - throw IrError("IR source map does not reference an instruction boundary"); - } - const auto &span = entry.sourceSpan; - if (span.startLine <= 0 || span.startColumn <= 0 || - span.endLine < span.startLine || - (span.endLine == span.startLine && span.endColumn < span.startColumn)) { - throw IrError("IR source map contains an invalid source span"); - } - } - std::vector initialized(ir.registerCount, false); - std::size_t pc = 0; - bool ended = false; - while (pc < ir.words.size()) { - const auto op = opcodeAt(ir, pc); - switch (op) { - case IrOpcode::End: - if (pc + 1 != ir.words.size()) - throw IrError("IR has instructions after END"); - ended = true; - ++pc; - break; - case IrOpcode::LoadConst: - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= ir.constants.size()) - throw IrError("IR references an invalid constant"); - if (ir.constants[ir.words[pc + 2]].kind == IrConstantKind::Text && - ir.constants[ir.words[pc + 2]].value >= ir.texts.size()) { - throw IrError("IR references an invalid text constant"); - } - initialized[ir.words[pc + 1]] = true; - pc += 3; - break; - case IrOpcode::LoadSymbol: - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= ir.symbols.size()) - throw IrError("IR references an invalid symbol"); - initialized[ir.words[pc + 1]] = true; - pc += 3; - break; - case IrOpcode::StoreSymbol: - if (ir.words[pc + 1] >= ir.symbols.size()) - throw IrError("IR stores an invalid symbol"); - requireRegister(ir, ir.words[pc + 2]); - requireInitialized(initialized, ir.words[pc + 2]); - pc += 3; - break; - case IrOpcode::Move: - requireRegister(ir, ir.words[pc + 1]); - requireRegister(ir, ir.words[pc + 2]); - requireInitialized(initialized, ir.words[pc + 2]); - initialized[ir.words[pc + 1]] = true; - pc += 3; - break; - case IrOpcode::ForEachFact: - requireRegister(ir, ir.words[pc + 1]); - requireRegister(ir, ir.words[pc + 4]); - requireInitialized(initialized, ir.words[pc + 4]); - if (ir.words[pc + 2] >= ir.symbols.size() || - ir.words[pc + 3] >= ir.symbols.size()) - throw IrError("IR fact loop references an invalid symbol"); - initialized[ir.words[pc + 1]] = true; - pc += 5; - break; - case IrOpcode::FactJoin: - requireRegister(ir, ir.words[pc + 1]); - for (const auto offset : {2u, 3u, 4u, 5u, 6u}) { - requireRegister(ir, ir.words[pc + offset]); - requireInitialized(initialized, ir.words[pc + offset]); - } - if (ir.words[pc + 7] >= ir.symbols.size() || - ir.words[pc + 8] >= ir.symbols.size() || - ir.words[pc + 9] >= ir.symbols.size()) - throw IrError("IR fact join references an invalid symbol"); - initialized[ir.words[pc + 1]] = true; - pc += 10; - break; - case IrOpcode::FactWhere: - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= ir.symbols.size()) - throw IrError("IR fact where references an invalid type symbol"); - requireRegister(ir, ir.words[pc + 3]); - requireInitialized(initialized, ir.words[pc + 3]); - initialized[ir.words[pc + 1]] = true; - pc += 4; - break; - case IrOpcode::Add: - case IrOpcode::Sub: - case IrOpcode::Mul: - case IrOpcode::Div: - case IrOpcode::Mod: - requireRegister(ir, ir.words[pc + 1]); - requireRegister(ir, ir.words[pc + 2]); - requireRegister(ir, ir.words[pc + 3]); - requireInitialized(initialized, ir.words[pc + 2]); - requireInitialized(initialized, ir.words[pc + 3]); - initialized[ir.words[pc + 1]] = true; - pc += 4; - break; - case IrOpcode::Similarity: - case IrOpcode::HierarchyIsA: - case IrOpcode::HierarchyCommonAncestors: - requireRegister(ir, ir.words[pc + 1]); - requireRegister(ir, ir.words[pc + 2]); - requireRegister(ir, ir.words[pc + 3]); - requireInitialized(initialized, ir.words[pc + 2]); - requireInitialized(initialized, ir.words[pc + 3]); - initialized[ir.words[pc + 1]] = true; - pc += 4; - break; - case IrOpcode::TemporalRank: - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= ir.symbols.size() || - ir.words[pc + 3] >= ir.symbols.size()) { - throw IrError("IR temporal rank references an invalid field symbol"); - } - initialized[ir.words[pc + 1]] = true; - pc += 4; - break; - case IrOpcode::Membership: - for (std::size_t i = 1; i < 6; ++i) { - requireRegister(ir, ir.words[pc + i]); - if (i > 1) - requireInitialized(initialized, ir.words[pc + i]); - } - initialized[ir.words[pc + 1]] = true; - pc += 6; - break; - case IrOpcode::Compare: - requireRegister(ir, ir.words[pc + 1]); - requireRegister(ir, ir.words[pc + 2]); - requireRegister(ir, ir.words[pc + 3]); - requireInitialized(initialized, ir.words[pc + 2]); - requireInitialized(initialized, ir.words[pc + 3]); - if (ir.words[pc + 4] > static_cast(IrComparison::GreaterEqual)) { - throw IrError("IR comparison kind is invalid"); - } - initialized[ir.words[pc + 1]] = true; - pc += 5; - break; - case IrOpcode::Jump: - if (!boundaries.contains(ir.words[pc + 1])) - throw IrError("IR jump target is not an instruction boundary"); - pc += 2; - break; - case IrOpcode::JumpIfFalse: - requireRegister(ir, ir.words[pc + 1]); - requireInitialized(initialized, ir.words[pc + 1]); - if (!boundaries.contains(ir.words[pc + 2])) - throw IrError("IR jump target is not an instruction boundary"); - pc += 3; - break; - case IrOpcode::Builtin: { - requireRegister(ir, ir.words[pc + 1]); - const auto operation = static_cast(ir.words[pc + 2]); - const auto arity = builtinOperationArity(operation); - const auto count = ir.words[pc + 3]; - // csv.toFacts is the one deliberate exception to "one fixed arity per - // BuiltinId" (2 or 3 args -- see the matching exception in - // IrCodeGenerator.cpp's eligibility check and lowering). - const bool validCount = - operation == BuiltinId::CsvToFacts ? (count == 2 || count == 3) - : (arity && count == *arity); - if (!validCount) - throw IrError("IR builtin operation ID or arity is invalid"); - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - requireRegister(ir, ir.words[pc + 4 + index]); - requireInitialized(initialized, ir.words[pc + 4 + index]); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::Call: { - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= ir.symbols.size()) - throw IrError("IR call references an invalid symbol"); - const auto count = ir.words[pc + 3]; - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - requireRegister(ir, ir.words[pc + 4 + index]); - requireInitialized(initialized, ir.words[pc + 4 + index]); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::SemanticEval: { - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] > std::numeric_limits::max() || - !isKnownSemanticOperation( - static_cast(ir.words[pc + 2]))) { - throw IrError("compiler IR semantic operation ID is invalid"); - } - const auto count = ir.words[pc + 3]; - if (!semanticOperationAcceptsArity( - static_cast(ir.words[pc + 2]), count)) { - throw IrError("compiler IR semantic operation arity is invalid"); - } - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - requireRegister(ir, ir.words[pc + 4 + index]); - requireInitialized(initialized, ir.words[pc + 4 + index]); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::Numeric: { - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= static_cast(NumericOperation::Count)) { - throw IrError("IR numeric operation ID is invalid"); - } - const auto operation = static_cast(ir.words[pc + 2]); - const auto count = ir.words[pc + 3]; - if (count != numericOperationArity(operation)) - throw IrError("IR numeric operation arity is invalid"); - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - requireRegister(ir, ir.words[pc + 4 + index]); - requireInitialized(initialized, ir.words[pc + 4 + index]); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::Tensor: { - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= static_cast(TensorOperation::Count)) - throw IrError("IR tensor operation ID is invalid"); - const auto operation = static_cast(ir.words[pc + 2]); - const auto count = ir.words[pc + 3]; - if (count != tensorOperationArity(operation)) - throw IrError("IR tensor operation arity is invalid"); - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - requireRegister(ir, ir.words[pc + 4 + index]); - requireInitialized(initialized, ir.words[pc + 4 + index]); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::CallNamed: { - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= ir.symbols.size()) - throw IrError("IR call references an invalid symbol"); - const auto count = ir.words[pc + 3]; - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - const auto name = ir.words[pc + 4 + 2 * index]; - const auto value = ir.words[pc + 5 + 2 * index]; - if (name != 0 && name - 1 >= ir.symbols.size()) - throw IrError("IR call references an invalid argument name"); - requireRegister(ir, value); - requireInitialized(initialized, value); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::MakeArray: { - requireRegister(ir, ir.words[pc + 1]); - const auto count = ir.words[pc + 3]; - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - requireRegister(ir, ir.words[pc + 4 + index]); - requireInitialized(initialized, ir.words[pc + 4 + index]); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::MakeMap: { - requireRegister(ir, ir.words[pc + 1]); - const auto count = ir.words[pc + 3]; - const auto width = irInstructionWidth(ir, pc); - for (std::size_t index = 0; index < count; ++index) { - const auto symbol = ir.words[pc + 4 + 2 * index]; - const auto value = ir.words[pc + 5 + 2 * index]; - if (symbol >= ir.symbols.size()) - throw IrError("IR map references an invalid field symbol"); - requireRegister(ir, value); - requireInitialized(initialized, value); - } - initialized[ir.words[pc + 1]] = true; - pc += width; - break; - } - case IrOpcode::MakeFact: - requireRegister(ir, ir.words[pc + 1]); - if (ir.words[pc + 2] >= ir.symbols.size()) - throw IrError("IR fact references an invalid symbol"); - if (ir.words[pc + 3] > ir.texts.size()) - throw IrError("IR fact references an invalid source text"); - if (ir.words[pc + 3] != 0 && - ir.texts[ir.words[pc + 3] - 1].empty()) - throw IrError("IR fact source text must not be empty"); - initialized[ir.words[pc + 1]] = true; - pc += 4; - break; - case IrOpcode::GetField: - requireRegister(ir, ir.words[pc + 1]); - requireRegister(ir, ir.words[pc + 2]); - requireInitialized(initialized, ir.words[pc + 2]); - if (ir.words[pc + 3] >= ir.symbols.size()) - throw IrError("IR field references an invalid symbol"); - initialized[ir.words[pc + 1]] = true; - pc += 4; - break; - case IrOpcode::SetField: - requireRegister(ir, ir.words[pc + 1]); - requireRegister(ir, ir.words[pc + 3]); - requireInitialized(initialized, ir.words[pc + 1]); - requireInitialized(initialized, ir.words[pc + 3]); - if (ir.words[pc + 2] >= ir.symbols.size()) - throw IrError("IR field references an invalid symbol"); - pc += 4; - break; - case IrOpcode::Return: - requireRegister(ir, ir.words[pc + 1]); - requireInitialized(initialized, ir.words[pc + 1]); - if (ir.words[pc + 2] != 0) - throw IrError("IR RETURN reserved operand must be zero"); - pc += 3; - break; - default: - throw IrError("IR opcode is not implemented by this VM build"); - } - if (ended) - break; - } - if (!ended) - throw IrError("IR is missing END"); - verifyControlFlowInitialization(ir, boundaries); -} -IrConstant encodeIrNumber(double value) noexcept { - return std::bit_cast(value); -} - -double decodeIrNumber(IrConstant word) noexcept { - return std::bit_cast(word); -} - -bool VmRuntime::shouldBranchFalse(const VmValue &value) const { - if (std::holds_alternative(value)) - return true; - if (const auto *control = std::get_if(&value)) { - if (*control == 0.0) - return true; - if (*control == 1.0) - return false; - throw IrError("VM control value must be exactly 0.0 or 1.0"); - } - throw IrError("VM branch requires a numeric 0.0 or 1.0 control value"); -} - -VmValue VmRuntime::loadSymbol(IrSymbolRef) { - throw IrError("IR symbol loading is unavailable in this runtime"); -} - -void VmRuntime::storeSymbol(IrSymbolRef, const VmValue &) { - throw IrError("IR symbol storage is unavailable in this runtime"); -} - -VmFactPtr VmRuntime::retainFact(const VmFactPtr &) { - throw IrError("IR fact retention is unavailable in this runtime"); -} - -VmFactPtr VmRuntime::retainPersistentFact(const VmFactPtr &, - std::span) { - throw IrError("persistent IR fact retention is unavailable in this runtime"); -} - -VmFactPtr VmRuntime::mutateFact(const VmFactPtr &, IrSymbolRef, - const VmValue &) { - throw IrError("IR fact mutation is unavailable in this runtime"); -} - -double VmRuntime::deleteFacts(std::span) { - throw IrError("IR fact deletion is unavailable in this runtime"); -} - -VmFactPtr VmRuntime::insertFact( - std::span, const VmMapPtr &, - std::optional>) { - throw IrError("IR fact insertion is unavailable in this runtime"); -} - -VmValue VmRuntime::updateFacts(std::span, const VmMapPtr &) { - throw IrError("IR fact update is unavailable in this runtime"); -} - -VmValue VmRuntime::projectFacts(std::span, - std::span) { - throw IrError("IR fact projection is unavailable in this runtime"); -} - -double VmRuntime::aggregateFacts(std::span, - std::span, std::uint8_t) { - throw IrError("IR fact aggregation is unavailable in this runtime"); -} - -VmValue VmRuntime::searchFacts(std::span, - std::span, const VmMapPtr &) { - throw IrError("IR fact search is unavailable in this runtime"); -} - -VmValue VmRuntime::joinFacts(std::span, - std::span, - std::span, - std::span, std::uint8_t, - IrSymbolRef, IrSymbolRef, IrSymbolRef) { - throw IrError("IR fact join is unavailable in this runtime"); -} - -void VmRuntime::registerFactType(IrSymbolRef, std::vector, - std::vector>) { - throw IrError("IR fact hierarchy is unavailable in this runtime"); -} - -std::vector VmRuntime::snapshotFacts(IrSymbolRef) { - throw IrError("IR fact iteration is unavailable in this runtime"); -} -std::vector VmRuntime::snapshotMatchingFacts( - IrSymbolRef, - std::span>) { - throw IrError("IR indexed fact queries are unavailable in this runtime"); -} - -std::vector VmRuntime::hierarchyProof(IrSymbolRef, IrSymbolRef) { - throw IrError("IR hierarchy is unavailable in this runtime"); -} -std::vector> -VmRuntime::hierarchyProofs(IrSymbolRef, IrSymbolRef) { - throw IrError("IR hierarchy is unavailable in this runtime"); -} -std::vector VmRuntime::commonAncestors(IrSymbolRef, IrSymbolRef) { - throw IrError("IR hierarchy is unavailable in this runtime"); -} -std::vector -VmRuntime::commonAncestorEvidence(IrSymbolRef, IrSymbolRef) { - throw IrError("IR hierarchy is unavailable in this runtime"); -} -VmValue VmRuntime::ancestorAnalysis(IrSymbolRef, IrSymbolRef) { - throw IrError("IR hierarchy is unavailable in this runtime"); -} -std::vector VmRuntime::rankFacts(IrSymbolRef, IrSymbolRef) { - throw IrError("IR temporal ranking is unavailable in this runtime"); -} - -void VmRuntime::installIrModule(const IrModule &) { - throw IrError("IR module installation is unavailable in this runtime"); -} -IrSymbolRef VmRuntime::resolveSymbol(IrSymbolRef) const { - throw IrError("IR symbol resolution is unavailable in this runtime"); -} -std::span VmRuntime::runtimeSymbolTable() const { - throw IrError("IR runtime symbol service is unavailable"); -} - -void VmRuntime::enterProcedure(IrSymbolRef, - std::span parameters, - std::span arguments) { - if (parameters.size() != arguments.size()) - throw IrError("IR procedure received the wrong number of arguments"); -} - -void VmRuntime::leaveProcedure() noexcept {} - -RuntimeStateModel *VmRuntime::runtimeStateModel() { return nullptr; } - -TensorRuntime *VmRuntime::tensorRuntime() { return nullptr; } - -std::string VmRuntime::decodeText(std::span) const { - throw IrError("VM required text decoder service is absent"); -} - -PieceSequence VmRuntime::encodeText(std::string_view) const { - throw IrError("VM required text encoder service is absent"); -} - -VmText VmRuntime::readFile(std::span) const { - throw IrError("VM file read service is absent"); -} - -VmValue VmRuntime::importCsvFacts(std::span, - std::span, - std::span) { - throw IrError("VM CSV fact service is absent"); -} - -void VmRuntime::beginExecution() {} - -void VmRuntime::endExecution() noexcept {} - -RuntimeContext VmRuntime::makeRuntimeContext(const VmValue &) const { - return {}; -} - -void VmRuntime::refreshRuntimeContext(RuntimeContext &) const {} - -RegisterVm::RegisterVm(std::size_t maximumInstructionSteps) - : maximumInstructionSteps_(maximumInstructionSteps) { - if (maximumInstructionSteps_ == 0) { - throw IrError("IR instruction-step limit must be positive"); - } -} - -VmValue RegisterVm::executeMain(const VerifiedIrModule &verified, - VmRuntime &runtime, VmValue systemInput) { - const auto &module = verified.get(); - runtime.installIrModule(module); - for (const auto &type : module.factTypes) { - std::vector parents; - parents.reserve(type.parents.size()); - for (const auto parent : type.parents) - parents.push_back(runtime.resolveSymbol(parent)); - std::vector> indexes; - indexes.reserve(type.indexes.size()); - for (const auto &index : type.indexes) { - auto &resolved = indexes.emplace_back(); - resolved.reserve(index.size()); - for (const auto field : index) - resolved.push_back(runtime.resolveSymbol(field)); - } - runtime.registerFactType(runtime.resolveSymbol(type.symbol), - std::move(parents), std::move(indexes)); - } - runtime.beginExecution(); - struct Scope { - VmRuntime &runtime; - ~Scope() { runtime.endExecution(); } - } scope{runtime}; - std::size_t instructionSteps = 0; - auto result = executeIrProgram(module, module.ir, runtime, - std::move(systemInput), 0, instructionSteps); - return result; -} - -VmValue RegisterVm::executeIrProgram(const IrModule &module, - const FelidaeIr &program, - VmRuntime &runtime, VmValue systemInput, - std::size_t callDepth, - std::size_t &instructionSteps) { - if (callDepth > 256) - throw IrError("IR procedure call depth exceeds VM limit"); - std::vector registers(program.registerCount, VmNil{}); - auto semanticContext = runtime.makeRuntimeContext(systemInput); - const auto moduleSymbol = [&](IrWord index) { - return program.symbols.at(index); - }; - const auto symbol = [&](IrWord index) { - return runtime.resolveSymbol(moduleSymbol(index)); - }; - const auto typeSymbol = [&](const VmValue &value) -> IrSymbolRef { - if (const auto item = std::get_if(&value)) { - if (item->value == 0) - throw IrError("IR hierarchy received an invalid symbol"); - return item->value; - } - if (const auto fact = std::get_if(&value); fact && *fact) - return (*fact)->type; - throw IrError("IR hierarchy operands must be symbols or facts"); - }; - const auto symbolArray = [](const std::vector &symbols) { - auto result = std::make_shared(); - result->values.reserve(symbols.size()); - for (const auto value : symbols) - result->values.push_back(VmSymbol{value}); - return result; - }; - const auto invoke = [&](IrSymbolRef procedureSymbol, - const std::vector &arguments) { - const auto found = module.procedures.find(procedureSymbol); - if (found == module.procedures.end()) - throw IrError("IR call target is not a procedure"); - const auto &procedure = found->second; - std::vector parameters; - parameters.reserve(procedure.positionalParameters.size()); - for (const auto parameter : procedure.positionalParameters) - parameters.push_back(runtime.resolveSymbol(parameter)); - runtime.enterProcedure(runtime.resolveSymbol(procedureSymbol), parameters, - arguments); - struct Frame { - VmRuntime &runtime; - ~Frame() { runtime.leaveProcedure(); } - } frame{runtime}; - return executeIrProgram(module, procedure.ir, runtime, VmNil{}, - callDepth + 1, instructionSteps); - }; - for (std::size_t pc = 0; pc < program.words.size();) { - if (instructionSteps++ >= maximumInstructionSteps_) { - throw IrError("IR execution exceeds its instruction-step limit"); - } - const auto op = static_cast(program.words.at(pc)); - const auto width = irInstructionWidth(program, pc); - switch (op) { - case IrOpcode::End: - throw IrError("IR program completed without returning a value"); - case IrOpcode::LoadConst: { - const auto destination = program.words.at(pc + 1); - const auto index = program.words.at(pc + 2); - const auto &constant = program.constants.at(index); - if (constant.kind == IrConstantKind::Number) - registers.at(destination) = decodeIrNumber(constant.value); - else if (constant.kind == IrConstantKind::Boolean) - registers.at(destination) = constant.value == 0 ? 0.0 : 1.0; - else if (constant.kind == IrConstantKind::Nil) - registers.at(destination) = VmNil{}; - else - registers.at(destination) = VmText{program.texts.at(constant.value)}; - break; - } - case IrOpcode::LoadSymbol: - registers.at(program.words.at(pc + 1)) = - runtime.loadSymbol(symbol(program.words.at(pc + 2))); - break; - case IrOpcode::StoreSymbol: - runtime.storeSymbol(symbol(program.words.at(pc + 1)), - registers.at(program.words.at(pc + 2))); - break; - case IrOpcode::Move: - registers.at(program.words.at(pc + 1)) = - registers.at(program.words.at(pc + 2)); - break; - case IrOpcode::Add: - case IrOpcode::Sub: - case IrOpcode::Mul: - case IrOpcode::Div: - case IrOpcode::Mod: { - const auto lhs = - std::get_if(®isters.at(program.words.at(pc + 2))); - const auto rhs = - std::get_if(®isters.at(program.words.at(pc + 3))); - if (!lhs || !rhs) - throw IrError("IR arithmetic operands must be numbers"); - if (!std::isfinite(*lhs) || !std::isfinite(*rhs)) - throw IrError("IR arithmetic operands must be finite"); - double value = 0.0; - if (op == IrOpcode::Add) - value = *lhs + *rhs; - else if (op == IrOpcode::Sub) - value = *lhs - *rhs; - else if (op == IrOpcode::Mul) - value = *lhs * *rhs; - else if (op == IrOpcode::Div) { - if (*rhs == 0.0) - throw IrError("IR division by zero"); - value = *lhs / *rhs; - } else { - if (*rhs == 0.0) - throw IrError("IR modulo by zero"); - value = std::fmod(*lhs, *rhs); - } - if (!std::isfinite(value)) - throw IrError("IR arithmetic produced a non-finite result"); - registers.at(program.words.at(pc + 1)) = value; - break; - } - case IrOpcode::Compare: { - const auto &lhs = registers.at(program.words.at(pc + 2)); - const auto &rhs = registers.at(program.words.at(pc + 3)); - const auto comparison = - static_cast(program.words.at(pc + 4)); - bool value = false; - if (comparison == IrComparison::Equal || - comparison == IrComparison::NotEqual) { - value = vmValuesEqual(lhs, rhs); - if (comparison == IrComparison::NotEqual) - value = !value; - } else { - const auto numeric = [](const VmValue &item) -> std::optional { - if (const auto number = std::get_if(&item)) - return *number; - if (const auto degree = std::get_if(&item)) - return degree->value; - return std::nullopt; - }; - const auto left = numeric(lhs), right = numeric(rhs); - if (!left || !right) - throw IrError("IR ordered comparison requires numeric operands"); - if (comparison == IrComparison::Less) - value = *left < *right; - else if (comparison == IrComparison::LessEqual) - value = *left <= *right; - else if (comparison == IrComparison::Greater) - value = *left > *right; - else - value = *left >= *right; - } - registers.at(program.words.at(pc + 1)) = value ? 1.0 : 0.0; - break; - } - case IrOpcode::Jump: - pc = program.words.at(pc + 1); - continue; - case IrOpcode::JumpIfFalse: - if (runtime.shouldBranchFalse(registers.at(program.words.at(pc + 1)))) { - pc = program.words.at(pc + 2); - continue; - } - break; - case IrOpcode::Call: { - const auto count = program.words.at(pc + 3); - std::vector arguments; - arguments.reserve(count); - for (IrWord index = 0; index < count; ++index) - arguments.push_back(registers.at(program.words.at(pc + 4 + index))); - registers.at(program.words.at(pc + 1)) = - invoke(moduleSymbol(program.words.at(pc + 2)), std::move(arguments)); - break; - } - case IrOpcode::CallNamed: { - const auto procedureSymbol = moduleSymbol(program.words.at(pc + 2)); - const auto found = module.procedures.find(procedureSymbol); - if (found == module.procedures.end()) - throw IrError("IR named-call target is not a procedure"); - const auto &procedure = found->second; - std::vector> mapped( - procedure.positionalParameters.size()); - std::size_t next = 0; - const auto count = program.words.at(pc + 3); - for (IrWord index = 0; index < count; ++index) { - const auto encodedName = program.words.at(pc + 4 + 2 * index); - std::size_t target = 0; - if (encodedName == 0) { - while (next < mapped.size() && mapped[next]) - ++next; - if (next == mapped.size()) - throw IrError("IR named call has too many positional arguments"); - target = next++; - } else { - const auto name = moduleSymbol(encodedName - 1); - const auto parameter = - std::find(procedure.namedParameters.begin(), - procedure.namedParameters.end(), name); - if (parameter == procedure.namedParameters.end()) - throw IrError("IR named call has an unknown argument"); - target = static_cast(parameter - - procedure.namedParameters.begin()); - } - if (mapped[target]) - throw IrError("IR named call duplicates an argument"); - mapped[target] = registers.at(program.words.at(pc + 5 + 2 * index)); - } - std::vector arguments; - arguments.reserve(mapped.size()); - for (auto &value : mapped) { - if (!value) - throw IrError("IR named call omits an argument"); - arguments.push_back(std::move(*value)); - } - registers.at(program.words.at(pc + 1)) = - invoke(procedureSymbol, std::move(arguments)); - break; - } - case IrOpcode::Builtin: { - const auto operation = static_cast(program.words.at(pc + 2)); - const auto count = program.words.at(pc + 3); - std::vector inputs; - inputs.reserve(count); - for (std::size_t index = 0; index < count; ++index) - inputs.push_back(registers.at(program.words.at(pc + 4 + index))); - VmValue result; - if (operation == BuiltinId::FileReadFile) { - const auto path = std::get_if(&inputs.front()); - if (!path) - throw IrError("file.readFile path must be text"); - result = runtime.readFile(path->pieces); - } else if (operation == BuiltinId::CsvToFacts) { - const auto data = std::get_if(&inputs[0]); - const auto type = std::get_if(&inputs[1]); - if (!data || !type) - throw IrError("csv.toFacts data and type must be text"); - // The source-path overload (csv.toFacts(data, type, source)) is - // Source ownership is optional; DML auto-persistence applies only - // when a caller provides one. - std::span source; - if (inputs.size() > 2) { - const auto sourceText = std::get_if(&inputs[2]); - if (!sourceText) - throw IrError("csv.toFacts source must be text"); - source = sourceText->pieces; - } - result = runtime.importCsvFacts(data->pieces, type->pieces, source); - } else if (operation == BuiltinId::AncestorAnalysis) { - result = runtime.ancestorAnalysis(typeSymbol(inputs[0]), - typeSymbol(inputs[1])); - } else if (operation == BuiltinId::PropagateFact) { - // Registered in BuiltinRegistry with no arity entry and no case here - // at all -- the same dead-registration pattern as sort/throw/math - // this session. A hierarchy-guarded variant of ordinary field - // mutation: apply `changes` to `child` only when `child`'s type - // actually descends from `parent`'s type, reusing the same - // mutateFact() an ordinary SetField already uses (see - // IrOpcode::SetField) rather than a second mutation path. - const auto parent = std::get_if(&inputs[0]); - const auto child = std::get_if(&inputs[1]); - const auto changes = std::get_if(&inputs[2]); - if (!parent || !*parent || !child || !*child) - throw IrError("propagateFact requires parent and child facts"); - if (!changes || !*changes) - throw IrError("propagateFact requires a changes map"); - if (runtime.hierarchyProof((*child)->type, (*parent)->type).empty()) { - throw IrError( - "propagateFact requires child to descend from parent's type"); - } - auto propagated = *child; - for (const auto &[field, value] : (*changes)->entries) - propagated = runtime.mutateFact(propagated, field, value); - result = propagated; - } else if (operation == BuiltinId::FactDelete) { - const auto array = std::get_if(&inputs[0]); - if (!array || !*array) - throw IrError("fact deletion requires a fact query result"); - std::vector facts; - facts.reserve((*array)->values.size()); - for (const auto &item : (*array)->values) { - const auto fact = std::get_if(&item); - if (!fact || !*fact) - throw IrError("fact deletion query contains a non-fact value"); - facts.push_back(*fact); - } - result = runtime.deleteFacts(facts); - } else if (operation == BuiltinId::FactInsert) { - const auto type = std::get_if(&inputs[0]); - const auto values = std::get_if(&inputs[1]); - if (!type || !values || !*values) - throw IrError("fact insertion requires a type and values map"); - std::optional> source; - if (!std::holds_alternative(inputs[2])) { - const auto text = std::get_if(&inputs[2]); - if (!text) - throw IrError("fact insertion source must be text or nil"); - source = text->pieces; - } - result = runtime.insertFact(type->pieces, *values, source); - } else if (operation == BuiltinId::FactUpdate) { - const auto array = std::get_if(&inputs[0]); - const auto values = std::get_if(&inputs[1]); - if (!array || !*array || !values || !*values) - throw IrError("fact update requires a query and values map"); - std::vector facts; - facts.reserve((*array)->values.size()); - for (const auto &item : (*array)->values) { - const auto fact = std::get_if(&item); - if (!fact || !*fact) - throw IrError("fact update query contains a non-fact value"); - facts.push_back(*fact); - } - result = runtime.updateFacts(facts, *values); - } else if (operation == BuiltinId::FactProject) { - const auto array = std::get_if(&inputs[0]); - const auto fieldArray = std::get_if(&inputs[1]); - if (!array || !*array || !fieldArray || !*fieldArray) - throw IrError("fact projection requires facts and a field array"); - std::vector facts; - for (const auto &item : (*array)->values) { - const auto fact = std::get_if(&item); - if (!fact || !*fact) - throw IrError("fact projection query contains a non-fact value"); - facts.push_back(*fact); - } - std::vector fields; - for (const auto &item : (*fieldArray)->values) { - const auto field = std::get_if(&item); - if (!field) - throw IrError("fact projection fields must be text"); - fields.push_back(*field); - } - result = runtime.projectFacts(facts, fields); - } else if (operation == BuiltinId::FactSetCombine) { - const auto left = std::get_if(&inputs[0]); - const auto right = std::get_if(&inputs[1]); - const auto mode = std::get_if(&inputs[2]); - if (!left || !*left || !right || !*right || !mode || - (*mode != 0.0 && *mode != 1.0)) - throw IrError("fact condition combination arguments are invalid"); - const auto factId = [](const VmValue &item) { - const auto fact = std::get_if(&item); - if (!fact || !*fact || (*fact)->id == 0) - throw IrError( - "fact condition combination requires retained facts"); - return (*fact)->id; - }; - auto combined = std::make_shared(); - std::unordered_set rightIds; - for (const auto &item : (*right)->values) - rightIds.insert(factId(item)); - std::unordered_set emitted; - for (const auto &item : (*left)->values) { - const auto id = factId(item); - if ((*mode == 0.0 && rightIds.contains(id)) || *mode == 1.0) { - combined->values.push_back(item); - emitted.insert(id); - } - } - if (*mode == 1.0) - for (const auto &item : (*right)->values) - if (emitted.insert(factId(item)).second) - combined->values.push_back(item); - result = std::move(combined); - } else if (operation == BuiltinId::FactAggregate) { - const auto array = std::get_if(&inputs[0]); - const auto field = std::get_if(&inputs[1]); - const auto aggregate = std::get_if(&inputs[2]); - if (!array || !*array || !field || !aggregate || *aggregate < 0.0 || - *aggregate > 3.0 || std::trunc(*aggregate) != *aggregate) - throw IrError("fact aggregate arguments are invalid"); - std::vector facts; - for (const auto &item : (*array)->values) { - const auto fact = std::get_if(&item); - if (!fact || !*fact) - throw IrError("fact aggregate query contains a non-fact value"); - facts.push_back(*fact); - } - result = runtime.aggregateFacts(facts, field->pieces, - static_cast(*aggregate)); - } else if (operation == BuiltinId::FactSearch) { - const auto array = std::get_if(&inputs[0]); - const auto field = std::get_if(&inputs[1]); - const auto options = std::get_if(&inputs[2]); - if (!array || !*array || !field || !options || !*options) - throw IrError("fact search requires facts, field, and options"); - std::vector facts; - facts.reserve((*array)->values.size()); - for (const auto &item : (*array)->values) { - const auto fact = std::get_if(&item); - if (!fact || !*fact) - throw IrError("fact search query contains a non-fact value"); - facts.push_back(*fact); - } - result = runtime.searchFacts(facts, field->pieces, *options); - } else { - const Form::BuiltinTextCodec codec{ - [&](std::span pieces) { - return runtime.decodeText(pieces); - }, - [&](std::string_view text) { return runtime.encodeText(text); }}; - result = Form::evaluateBuiltin(operation, inputs, - runtime.runtimeSymbolTable(), codec); - } - if (!validVmValue(result)) - throw IrError("builtin operation produced an invalid VM value"); - registers.at(program.words.at(pc + 1)) = std::move(result); - break; - } - case IrOpcode::SemanticEval: { - const auto operation = - static_cast(program.words.at(pc + 2)); - const auto count = program.words.at(pc + 3); - std::vector inputs; - inputs.reserve(count); - for (IrWord index = 0; index < count; ++index) - inputs.push_back(registers.at(program.words.at(pc + 4 + index))); - auto *model = runtime.runtimeStateModel(); - if (!model) - throw IrError("IR SemanticEval requires a RuntimeStateModel"); - runtime.refreshRuntimeContext(semanticContext); - const auto steps = semanticContext.sharedSemanticSteps - ? *semanticContext.sharedSemanticSteps - : semanticContext.semanticSteps; - if (steps >= semanticContext.maximumSemanticSteps) - throw IrError("IR semantic operation exceeds execution state limit"); - if (!validSemanticInputs(operation, inputs)) - throw IrError("IR SemanticEval input contract is invalid"); - if (semanticContext.sharedSemanticSteps) - semanticContext.semanticSteps = ++*semanticContext.sharedSemanticSteps; - else - ++semanticContext.semanticSteps; - auto value = - model->evaluate(RuntimeOperation{operation}, inputs, semanticContext); - if (!validSemanticOutput(operation, inputs, value)) { - throw IrError("RuntimeStateModel returned an invalid typed result"); - } - if (const auto fact = std::get_if(&value); fact && *fact) { - auto derived = std::make_shared(**fact); - derived->origin = VmFact::Origin::Derived; - value = runtime.retainFact(derived); - } - registers.at(program.words.at(pc + 1)) = std::move(value); - break; - } - case IrOpcode::Numeric: { - const auto count = program.words.at(pc + 3); - // NumericOperation has a verified maximum arity of four. Keep its hot - // path on the stack rather than allocating a vector for every scalar - // instruction. - std::array operands{}; - for (std::size_t index = 0; index < count; ++index) { - const auto *number = std::get_if( - ®isters.at(program.words.at(pc + 4 + index))); - if (!number) - throw IrError("numeric operation operands must be numbers"); - operands[index] = *number; - } - registers.at(program.words.at(pc + 1)) = evaluateNumericOperation( - static_cast(program.words.at(pc + 2)), - std::span(operands.data(), count)); - break; - } - case IrOpcode::Tensor: { - const auto operation = - static_cast(program.words.at(pc + 2)); - const auto count = program.words.at(pc + 3); - std::vector inputs; - inputs.reserve(count); - for (std::size_t index = 0; index < count; ++index) - inputs.push_back(registers.at(program.words.at(pc + 4 + index))); - auto *backend = runtime.tensorRuntime(); - if (!backend) - throw IrError("IR tensor operation requires LibTorch support"); - auto result = backend->evaluateTensor(operation, inputs, - runtime.runtimeSymbolTable()); - if (!validVmValue(result)) - throw IrError("tensor operation produced an invalid VM value"); - registers.at(program.words.at(pc + 1)) = std::move(result); - break; - } - case IrOpcode::MakeFact: { - auto fact = std::make_shared(); - fact->type = symbol(program.words.at(pc + 2)); - const auto source = program.words.at(pc + 3); - registers.at(program.words.at(pc + 1)) = - source == 0 - ? runtime.retainFact(fact) - : runtime.retainPersistentFact(fact, - program.texts.at(source - 1)); - break; - } - case IrOpcode::MakeArray: { - auto array = std::make_shared(); - const auto count = program.words.at(pc + 3); - array->values.reserve(count); - for (IrWord index = 0; index < count; ++index) - array->values.push_back(registers.at(program.words.at(pc + 4 + index))); - registers.at(program.words.at(pc + 1)) = std::move(array); - break; - } - case IrOpcode::MakeMap: { - auto map = std::make_shared(); - const auto count = program.words.at(pc + 3); - map->entries.reserve(count); - for (IrWord index = 0; index < count; ++index) { - map->entries.emplace_back( - symbol(program.words.at(pc + 4 + 2 * index)), - registers.at(program.words.at(pc + 5 + 2 * index))); - } - registers.at(program.words.at(pc + 1)) = std::move(map); - break; - } - case IrOpcode::GetField: { - const auto field = symbol(program.words.at(pc + 3)); - const auto read = [&](const auto &entries) -> VmValue { - for (const auto &[key, value] : entries) - if (key == field) - return value; - throw IrError("IR field is absent"); - }; - const auto target = program.words.at(pc + 2); - if (const auto fact = std::get_if(®isters.at(target)); - fact && *fact) - registers.at(program.words.at(pc + 1)) = read((*fact)->fields); - else if (const auto map = std::get_if(®isters.at(target)); - map && *map) - registers.at(program.words.at(pc + 1)) = read((*map)->entries); - else - throw IrError("IR field access requires a fact or map"); - break; - } - case IrOpcode::SetField: { - const auto field = symbol(program.words.at(pc + 2)); - const auto value = registers.at(program.words.at(pc + 3)); - const auto object = program.words.at(pc + 1); - if (const auto fact = std::get_if(®isters.at(object)); - fact && *fact) - registers.at(object) = runtime.mutateFact(*fact, field, value); - else if (const auto map = std::get_if(®isters.at(object)); - map && *map) { - const auto found = std::find_if( - (*map)->entries.begin(), (*map)->entries.end(), - [&](const auto &entry) { return entry.first == field; }); - if (found == (*map)->entries.end()) - (*map)->entries.emplace_back(field, value); - else - found->second = value; - } else - throw IrError("IR field assignment requires a fact or map"); - break; - } - case IrOpcode::Similarity: - registers.at(program.words.at(pc + 1)) = - VmDegree(similarityDegree(registers.at(program.words.at(pc + 2)), - registers.at(program.words.at(pc + 3)))); - break; - case IrOpcode::Membership: { - const auto number = [&](std::size_t offset) { - const auto value = - std::get_if(®isters.at(program.words.at(pc + offset))); - if (!value) - throw IrError("IR membership operands must be numbers"); - return *value; - }; - registers.at(program.words.at(pc + 1)) = - VmDegree(VmFactStore::gaussianMembership( - number(2), {number(3), number(4), number(5)})); - break; - } - case IrOpcode::FactWhere: { - const auto predicates = - std::get_if(®isters.at(program.words.at(pc + 3))); - if (!predicates || !*predicates || (*predicates)->entries.empty()) - throw IrError("IR fact where requires a non-empty predicate map"); - const auto facts = runtime.snapshotMatchingFacts( - symbol(program.words.at(pc + 2)), (*predicates)->entries); - auto values = std::make_shared(); - values->values.reserve(facts.size()); - for (const auto &fact : facts) - values->values.emplace_back(fact); - registers.at(program.words.at(pc + 1)) = std::move(values); - break; - } - case IrOpcode::ForEachFact: { - const auto facts = - runtime.snapshotFacts(symbol(program.words.at(pc + 2))); - // The captures register always holds a (possibly empty) map of the - // predicate's outer-scope free variables, evaluated once here in the - // caller's own scope where they are actually defined, then threaded - // through to every invocation -- the synthesized callback procedure - // itself has no access to the caller's registers otherwise. See - // FactDmlLowerer::iteration() in IrCodeGenerator.cpp. A callback - // written directly against the raw for_each_fact(type, callback) form - // (not through that sugar) still takes only the row parameter, so the - // captures argument is included only when the target actually - // declares a second parameter for it -- an older single-parameter - // callback keeps working unchanged. - const auto captures = registers.at(program.words.at(pc + 4)); - const auto callbackSymbol = moduleSymbol(program.words.at(pc + 3)); - const auto callbackProcedure = module.procedures.find(callbackSymbol); - if (callbackProcedure == module.procedures.end()) - throw IrError("IR call target is not a procedure"); - const auto callbackTakesCaptures = - callbackProcedure->second.positionalParameters.size() >= 2; - auto values = std::make_shared(); - values->values.reserve(facts.size()); - for (const auto &fact : facts) { - auto value = - callbackTakesCaptures - ? invoke(callbackSymbol, {VmValue{fact}, captures}) - : invoke(callbackSymbol, {VmValue{fact}}); - if (const auto selected = std::get_if(&value)) { - if (*selected == 0.0) - continue; - if (*selected == 1.0) { - values->values.emplace_back(fact); - continue; - } - } - values->values.push_back(std::move(value)); - } - registers.at(program.words.at(pc + 1)) = std::move(values); - break; - } - case IrOpcode::FactJoin: { - const auto facts = [](const VmValue &value) { - const auto array = std::get_if(&value); - if (!array || !*array) - throw IrError("fact join requires two queries, two fields, and a " - "join kind"); - std::vector result; - result.reserve((*array)->values.size()); - for (const auto &item : (*array)->values) { - const auto fact = std::get_if(&item); - if (!fact || !*fact) - throw IrError("fact join query contains a non-fact value"); - result.push_back(*fact); - } - return result; - }; - const auto leftFacts = facts(registers.at(program.words.at(pc + 2))); - const auto rightFacts = facts(registers.at(program.words.at(pc + 3))); - const auto leftField = - std::get_if(®isters.at(program.words.at(pc + 4))); - const auto rightField = - std::get_if(®isters.at(program.words.at(pc + 5))); - const auto kind = - std::get_if(®isters.at(program.words.at(pc + 6))); - if (!leftField || !rightField || !kind || *kind < 0.0 || *kind > 3.0 || - std::trunc(*kind) != *kind) - throw IrError( - "fact join requires two queries, two fields, and a join kind"); - registers.at(program.words.at(pc + 1)) = runtime.joinFacts( - leftFacts, rightFacts, leftField->pieces, rightField->pieces, - static_cast(*kind), symbol(program.words.at(pc + 7)), - symbol(program.words.at(pc + 8)), symbol(program.words.at(pc + 9))); - break; - } - case IrOpcode::HierarchyIsA: - registers.at(program.words.at(pc + 1)) = - runtime.hierarchyProof( - typeSymbol(registers.at(program.words.at(pc + 2))), - typeSymbol(registers.at(program.words.at(pc + 3)))) - .empty() - ? 0.0 - : 1.0; - break; - case IrOpcode::HierarchyCommonAncestors: - registers.at(program.words.at(pc + 1)) = - symbolArray(runtime.commonAncestors( - typeSymbol(registers.at(program.words.at(pc + 2))), - typeSymbol(registers.at(program.words.at(pc + 3))))); - break; - case IrOpcode::TemporalRank: { - const auto ranked = runtime.rankFacts(symbol(program.words.at(pc + 2)), - symbol(program.words.at(pc + 3))); - auto values = std::make_shared(); - values->values.reserve(ranked.size()); - for (const auto &item : ranked) - values->values.push_back(item.fact); - registers.at(program.words.at(pc + 1)) = std::move(values); - break; - } - case IrOpcode::Return: - return registers.at(program.words.at(pc + 1)); - case IrOpcode::Count: - throw IrError("IR contains an invalid opcode"); - } - pc += width; - } - throw IrError("IR program ended without Return or End"); -} -} // namespace Felidae diff --git a/src/form/RegisterVm.h b/src/form/RegisterVm.h deleted file mode 100644 index c44583a..0000000 --- a/src/form/RegisterVm.h +++ /dev/null @@ -1,678 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace at { -class Tensor; -} - -namespace Felidae { - -enum class TensorOperation : std::uint8_t; - -struct FelidaeIr; -struct IrModule; -class VerifiedIrModule; - -// Executable operands and module-local references use the same fixed-width -// word type stored by FELBIR. A symbol reference is a one-based index into the -// module's full SentencePiece-sequence table, never a source hash. -using IrWord = std::uint32_t; -using IrConstant = std::uint64_t; -using RegisterId = IrWord; -using IrConstantId = IrWord; -using IrSymbolRef = IrWord; -using IrFactRef = std::size_t; -using PieceId = std::uint32_t; -using PieceSequence = std::vector; - -enum class IrConstantKind : std::uint8_t { Number, Boolean, Nil, Text }; - -struct IrSourceMapEntry { - std::size_t instructionWord = 0; - struct Span { - int startLine = 1; - int startColumn = 1; - int endLine = 1; - int endColumn = 1; - } sourceSpan; -}; - -class IrError : public std::runtime_error { -public: - explicit IrError(const std::string &message) : std::runtime_error(message) {} -}; - -// Constant-pool numbers use a canonical bit representation shared by the -// compiler, binary IR loader, and register VM. -IrConstant encodeIrNumber(double value) noexcept; -double decodeIrNumber(IrConstant word) noexcept; -// Canonical instruction-width decoder shared by verification, execution, and -// compiler-side inspection of generated IR. It also rejects invalid or -// truncated instructions, so callers must not maintain parallel width tables. -std::size_t irInstructionWidth(const FelidaeIr &ir, std::size_t pc); - -struct VmNil { - bool operator==(const VmNil &) const = default; -}; -struct VmSymbol { - IrSymbolRef value = 0; - bool operator==(const VmSymbol &) const = default; -}; -struct VmDegree { - double value = 0.0; - explicit VmDegree(double value); - bool operator==(const VmDegree &) const = default; -}; -struct VmText { - PieceSequence pieces; - bool operator==(const VmText &) const = default; -}; -struct VmArray; -using VmArrayPtr = std::shared_ptr; -struct VmMap; -using VmMapPtr = std::shared_ptr; -struct VmTextMap; -using VmTextMapPtr = std::shared_ptr; -struct VmFact; -// Published facts are immutable snapshots. Mutable `VmFact` builders may be -// created locally, but conversion to VmFactPtr removes write access before a -// value enters VmValue or VmFactStore. -using VmFactPtr = std::shared_ptr; -// The portable VM owns a real LibTorch tensor without including Torch headers -// in Form. Only TensorRuntime creates or dereferences `storage`; shape is kept -// here so validation and fallback display remain backend-independent. -struct VmTensor { - std::shared_ptr storage; - std::vector shape; -}; -using VmTensorPtr = std::shared_ptr; -// `double` is Felidae's unrestricted numeric value. Never normalize or clamp -// it merely because the value is used by this non-Boolean language. Only -// operations whose contract is a truth result (comparisons and predicates) -// return exactly 0.0 or 1.0. VmDegree is a distinct, explicitly bounded value. -using VmValue = - std::variant; -static_assert( - [](std::index_sequence) { - return ( - !std::is_same_v> && - ...); - }(std::make_index_sequence>{}), - "VM truth values must be double 0.0 or 1.0, never bool"); -// Public runtime spelling for canonical VM values. -using Value = VmValue; - -// One authoritative structural equality implementation shared by VM opcode -// dispatch and direct runtime-library operations such as array membership. -bool vmValuesEqual(const VmValue &left, const VmValue &right); - -// Stable model/dataset contract. Do not persist VmValue::index(): changing -// the in-memory variant layout must never reinterpret an existing corpus or -// model artifact. -enum class RuntimeValueKind : std::uint8_t { - Nil = 1, - Number = 2, - Degree = 3, - Text = 4, - Array = 5, - Map = 6, - Fact = 7, - Symbol = 8, - Tensor = 9, - TextMap = 10, -}; -RuntimeValueKind runtimeValueKind(const VmValue &value) noexcept; -using VmSymbolDecoder = std::function; -using VmTextDecoder = std::function)>; -using VmTextEncoder = std::function; -using VmTensorDecoder = std::function; -// Rendering is an adapter boundary, not VM state. Form consumes only IDs and -// typed values; callers may inject SentencePiece and symbol decoders for UI. -struct VmDisplayContext { - VmTextDecoder textDecoder; - VmSymbolDecoder symbolDecoder; - VmTensorDecoder tensorDecoder; -}; -std::string vmValueToDisplayString(const VmValue &value, - const VmDisplayContext &context = {}); -struct VmArray { - std::vector values; -}; -struct VmMap { - std::vector> entries; -}; -// Dynamic object keys (for JSON and CSV) are tokenized text, never raw UTF-8 -// or module-local symbol references. Static source maps continue to use -// VmMap; this separate type keeps both identity contracts unambiguous. -struct VmTextMap { - std::vector> entries; -}; -// Facts retain a separate type tag. They are deliberately not aliases for -// maps: map-shaped values must not acquire fact semantics merely by carrying -// a similarly named field. -struct VmFact { - // Identity metadata becomes immutable once VmFactStore::retain succeeds. - // Change retained fields only through VmFactStore::mutate so indexes and - // provenance remain synchronized. - IrFactRef id = 0; - IrSymbolRef type = 0; - enum class Origin : std::uint8_t { - Asserted, - Derived - } origin = Origin::Asserted; - std::uint64_t createdSequence = 0; - std::vector> fields; -}; - -enum class VmFactMutationKind : std::uint8_t { Insert, Update, Delete }; -struct VmFactMutation { - std::uint64_t sequence = 0; - IrFactRef fact = 0; - IrSymbolRef field = 0; - VmFactMutationKind kind = VmFactMutationKind::Update; -}; -struct VmFactProvenance { - IrFactRef fact = 0; - IrSymbolRef procedure = 0; - bool derived = false; -}; -struct VmKnowledgeSnapshot { - std::vector factTypes; - // Sorted, bounded fact population by type. This is a compact runtime - // observation, not a second fact store or a source-text representation. - std::vector> factTypeCounts; - std::vector> hierarchyEdges; -}; -// Numeric, non-boolean evidence returned by Form's deterministic fact -// analysis. `membership` is always in [0, 1] and is never a branch value. -struct VmGaussianProfile { - double peak = 0.0; - double fadesIn = 0.0; - double fadesOut = 0.0; -}; -struct VmRankedFact { - VmFactPtr fact; - double effectiveAt = 0.0; - double priority = 0.0; -}; -struct VmFactStoreRevisions { - std::uint64_t hierarchy = 0; - std::uint64_t membership = 0; - std::uint64_t content = 0; - - bool operator==(const VmFactStoreRevisions &) const = default; -}; -struct VmFactStoreJournalMark { - std::size_t mutations = 0; - std::size_t provenance = 0; -}; - -struct VmCommonAncestorEvidence { - IrSymbolRef ancestor = 0; - std::vector> leftProofs; - std::vector> rightProofs; - std::size_t leftDistance = 0; - std::size_t rightDistance = 0; -}; - -// Process-resident fact storage used by the portable runtime. It belongs to -// Form, not to AST/parser services, and is shared by repeated VM executions in -// a daemon. Mutations go through this owner so fact identity, creation order, -// indexes, provenance, source ownership, and revisions stay synchronized. -// A disk-backed implementation must preserve this contract; this class alone -// is not presented as trillion-scale storage. -class VmFactStore { -public: - VmFactStore(); - explicit VmFactStore(const std::filesystem::path &directory); - ~VmFactStore(); - VmFactStore(const VmFactStore &) = delete; - VmFactStore &operator=(const VmFactStore &) = delete; - // Numeric symbol references are process-local handles. The complete - // SentencePiece sequence stored here is their authoritative identity and - // is what a durable backend encodes. - IrSymbolRef internSymbol(PieceSequence pieces); - std::optional - findSymbol(std::span pieces) const; - const std::vector &symbolTable() const noexcept; - void registerType(IrSymbolRef type, std::vector parents, - std::vector> indexes = {}); - VmFactPtr retain(const VmFactPtr &fact); - void recordInsert(IrFactRef fact); - VmFactPtr mutate(const VmFactPtr &fact, IrSymbolRef field, - const VmValue &value, IrSymbolRef procedure); - std::size_t erase(std::span facts); - void restore(const VmFactPtr ¤t, const VmFactPtr &previous); - void restoreErased(const VmFactPtr &fact, - std::optional source); - std::vector snapshot() const; - std::vector snapshot(IrSymbolRef type) const; - std::vector snapshotAssignableTo(IrSymbolRef type) const; - // Storage continuation metadata, not a VM query-object value. Any committed - // mutation expires the cursor. Keys and database identity survive reopening. - struct Cursor { - std::string database; - std::string index; - std::string query; - std::string lastKey; - std::uint64_t revision = 0; - }; - struct Page { - std::vector rows; - std::optional next; - bool hasMore = false; - std::uint64_t revision = 0; - }; - Page pageAssignableTo(IrSymbolRef type, std::size_t records, - const std::optional &after = std::nullopt) const; - Page pageMatching(IrSymbolRef type, - std::span> predicates, - std::size_t records, - const std::optional &after = std::nullopt) const; - // Plans exact predicates against the widest fully-covered declared index. - // Small unindexed stores may use a bounded scan; large stores fail with an - // actionable index diagnostic instead of silently becoming unbounded. - std::vector snapshotMatching( - IrSymbolRef type, - std::span> predicates) const; - std::vector parentsOf(IrSymbolRef type) const; - std::vector hierarchyProof(IrSymbolRef child, - IrSymbolRef ancestor) const; - std::vector> - hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor) const; - std::vector commonAncestors(IrSymbolRef left, - IrSymbolRef right) const; - std::vector - commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right) const; - // Sorts facts by descending effective time, then descending priority, - // then stable fact identity. Missing/non-numeric fields are rejected. - std::vector - rankByTimeAndPriority(IrSymbolRef effectiveAtField, - IrSymbolRef priorityField) const; - std::vector snapshotByField(IrSymbolRef field) const; - std::vector mutations() const; - std::vector provenance() const; - VmFactStoreJournalMark journalMark() const; - void rollbackJournal(VmFactStoreJournalMark mark); - VmKnowledgeSnapshot knowledgeSnapshot() const; - // Rebuilds `snapshot` only when fact/type state changed. Runtime SSM - // dispatch uses this to avoid sorting the same knowledge graph on every - // SemanticEval instruction. - void refreshKnowledgeSnapshot(std::uint64_t &knownRevision, - VmKnowledgeSnapshot &snapshot) const; - VmFactStoreRevisions revisions() const; - std::size_t size() const; - - // Persistence ownership: which source (e.g. a CSV file path) a fact was - // imported from, if any. Automatic DML persistence serializes only the - // facts that actually belong to the target file, instead of the whole - // store -- it must never infer ownership from fact type alone, since two - // different files can share one fact type. A fact with no recorded - // source is simply excluded from any snapshotBySource() result; only - // CSV import, compiler-linked fact-only .fx rows, and explicit/inferred - // persistent insert are the only paths that establish ownership. Queries - // and updates never invent it. - void recordSource(IrFactRef fact, std::string source); - std::optional sourceOf(IrFactRef fact) const; - std::vector sourcesForType(IrSymbolRef type) const; - std::vector snapshotBySource(std::string_view source) const; - - // A Gaussian tail reaches 1% at each fade boundary. Degenerate edge - // profiles (peak equal to one boundary) reuse the non-degenerate side so - // ratings at 0 and 100 remain continuous on the closed input domain. - static double gaussianMembership(double value, - const VmGaussianProfile &profile); - -private: - class Persistence; - struct StoredSnapshot { - VmFactPtr fact; - std::optional source; - }; - IrSymbolRef internSymbolLocked(PieceSequence pieces) const; - StoredSnapshot persistentSnapshotLocked(IrFactRef fact) const; - VmFactPtr currentSnapshotLocked(const VmFactPtr &snapshot) const; - const std::unordered_set & - ancestorClosureLocked(IrSymbolRef type) const; - bool isAssignableToLocked(IrSymbolRef candidate, IrSymbolRef expected) const; - void validateDeclaredIndexKeysLocked(const VmFactPtr &fact) const; - void addToDeclaredIndexesLocked(const VmFactPtr &fact); - void removeFromDeclaredIndexesLocked(const VmFactPtr &fact); - std::vector persistentIndexKeysLocked( - const VmFactPtr &fact, - std::optional source = std::nullopt) const; - std::vector persistentFactsLocked( - std::string_view prefix, std::size_t maximum, - bool *hasMore = nullptr, - std::optional after = std::nullopt, - std::string *lastKey = nullptr, - std::vector *keys = nullptr) const; - - struct ExactIndex { - std::vector fields; - // Rows belong only to the memory backend. RocksDB stores retain the - // declaration for shared planning but load candidates from durable keys. - std::map, std::vector> rows; - }; - struct EqualityPlan { - const ExactIndex *index = nullptr; - IrSymbolRef owner = 0; - std::size_t ordinal = 0; - std::size_t covered = 0; - }; - EqualityPlan equalityPlanLocked( - IrSymbolRef type, - std::span> predicates) const; - bool matchesLocked( - const VmFactPtr &fact, IrSymbolRef type, - std::span> predicates) const; - - mutable std::mutex mutex_; - std::unique_ptr persistence_; - mutable std::map symbolIds_; - mutable std::vector symbolTable_; - IrFactRef nextId_ = 1; - std::uint64_t nextSequence_ = 1; - std::vector facts_; - std::unordered_map> byType_; - // Memory backend only; persistent field-presence lookups use the IF index. - std::unordered_map> byField_; - std::unordered_map> parents_; - std::unordered_map>> - declaredIndexes_; - std::unordered_map> exactIndexes_; - std::unordered_map factSource_; - std::vector mutations_; - std::vector provenance_; - mutable std::unordered_map< - IrSymbolRef, - std::pair>> - ancestorClosureCache_; - std::uint64_t hierarchyRevision_ = 0; - std::uint64_t membershipRevision_ = 0; - std::uint64_t contentRevision_ = 0; - // The runtime SSM snapshot contains only hierarchy edges and per-type fact - // counts. Its revision therefore excludes ordinary field-value mutation. - std::uint64_t knowledgeRevision_ = 0; -}; -// A semantic operation is a permanent IR ID plus typed VM values. It never -// uses a source symbol, text, or SentencePiece token as executable semantics. -struct RuntimeOperation { - std::uint16_t id = 0; -}; - -// This object is created for a top-level VM execution. Nested procedure VMs -// receive the same execution state, while separate calls to RegisterVm never -// share it. A model state is opaque to the VM but lifetime-bound to this scope. -struct RuntimeContext { - std::size_t maximumSemanticSteps = 1024; - std::size_t semanticSteps = 0; - std::shared_ptr executionState; - std::shared_ptr sharedSemanticSteps; - // Refreshed immediately before each semantic operation. Module-local - // references are resolved through symbolTable to their complete - // SentencePiece sequences at the model boundary. - VmKnowledgeSnapshot knowledge; - const std::vector *symbolTable = nullptr; - std::uint64_t knowledgeRevision = std::numeric_limits::max(); -}; - -class RuntimeStateModel { -public: - virtual ~RuntimeStateModel() = default; - // Called once for each top-level Form runtime execution. Backends use - // this to allocate their recurrent/SSM state without retaining it across - // requests. The default model is stateless. - virtual std::shared_ptr createExecutionState() { return {}; } - virtual Value evaluate(const RuntimeOperation &operation, - std::span inputs, - RuntimeContext &context) = 0; -}; - -class TensorRuntime { -public: - virtual ~TensorRuntime() = default; - // Returned tensors must own finite backend storage. RegisterVm validates the - // portable wrapper; the backend owns element-level validation because Form - // intentionally cannot dereference at::Tensor on unsupported platforms. - virtual Value evaluateTensor(TensorOperation operation, - std::span inputs, - std::span symbolTable) = 0; -}; - -class VmRuntime { -public: - virtual ~VmRuntime() = default; - virtual VmValue loadSymbol(IrSymbolRef symbol); - virtual void storeSymbol(IrSymbolRef symbol, const VmValue &value); - virtual VmFactPtr retainFact(const VmFactPtr &fact); - // Establishes persistent ownership for a compiler-linked fact database - // row. The base runtime rejects it; only a runtime with a fact store and a - // text codec may accept source-owned facts. - virtual VmFactPtr retainPersistentFact(const VmFactPtr &fact, - std::span source); - virtual VmFactPtr mutateFact(const VmFactPtr &fact, IrSymbolRef field, - const VmValue &value); - virtual double deleteFacts(std::span facts); - virtual VmFactPtr insertFact(std::span type, - const VmMapPtr &values, - std::optional> source); - virtual VmValue updateFacts(std::span facts, - const VmMapPtr &values); - virtual VmValue projectFacts(std::span facts, - std::span fields); - virtual double aggregateFacts(std::span facts, - std::span field, - std::uint8_t operation); - virtual VmValue searchFacts(std::span facts, - std::span field, - const VmMapPtr &options); - virtual VmValue joinFacts(std::span left, - std::span right, - std::span leftField, - std::span rightField, - std::uint8_t kind, IrSymbolRef joinedType, - IrSymbolRef joinedLeft, IrSymbolRef joinedRight); - virtual void registerFactType(IrSymbolRef type, - std::vector parents, - std::vector> indexes = {}); - virtual std::vector snapshotFacts(IrSymbolRef type); - virtual std::vector snapshotMatchingFacts( - IrSymbolRef type, - std::span> predicates); - virtual std::vector hierarchyProof(IrSymbolRef child, - IrSymbolRef ancestor); - virtual std::vector> - hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor); - virtual std::vector commonAncestors(IrSymbolRef left, - IrSymbolRef right); - virtual std::vector - commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right); - virtual VmValue ancestorAnalysis(IrSymbolRef left, IrSymbolRef right); - virtual std::vector rankFacts(IrSymbolRef effectiveAtField, - IrSymbolRef priorityField); - // Modules are independently verified before this hook. A long-lived - // runtime may retain their procedure metadata for later calls; the base - // runtime remains intentionally stateless. - virtual void installIrModule(const IrModule &module); - virtual IrSymbolRef resolveSymbol(IrSymbolRef moduleSymbol) const; - virtual std::span runtimeSymbolTable() const; - virtual void enterProcedure(IrSymbolRef procedure, - std::span parameters, - std::span arguments); - virtual void leaveProcedure() noexcept; - // Null means this execution has no learned semantic backend. SemanticEval - // then fails in a controlled manner; exact opcodes never use this hook. - virtual RuntimeStateModel *runtimeStateModel(); - virtual TensorRuntime *tensorRuntime(); - virtual std::string decodeText(std::span pieces) const; - virtual PieceSequence encodeText(std::string_view text) const; - virtual VmText readFile(std::span path) const; - virtual VmValue importCsvFacts(std::span data, - std::span type, - std::span source); - virtual void beginExecution(); - virtual void endExecution() noexcept; - virtual RuntimeContext makeRuntimeContext(const VmValue &systemInput) const; - // A long-lived runtime updates operation context at the semantic boundary; - // the base runtime has no knowledge state to add. - virtual void refreshRuntimeContext(RuntimeContext &context) const; - // Branch protocol, not generic truthiness. The only truth values are the - // doubles 0.0 and 1.0; facts, text, containers, and other numbers are not - // coerced. Nil and 0.0 take the false branch, while 1.0 continues. - virtual bool shouldBranchFalse(const VmValue &value) const; -}; - -// Knowledge services used by verified IR programs. The VM boundary stays -// explicit: IR operations reach only this typed runtime contract and never -// implicitly enter the parser or Interpreter. -class FelidaeKnowledgeRuntime final : public VmRuntime { -public: - explicit FelidaeKnowledgeRuntime(RuntimeStateModel *semanticModel = nullptr, - std::size_t maximumSemanticSteps = 1024, - std::size_t maximumCallDepth = 256, - std::shared_ptr factStore = {}, - TensorRuntime *tensorRuntime = nullptr, - VmTextDecoder textDecoder = {}, - VmTextEncoder textEncoder = {}); - VmValue loadSymbol(IrSymbolRef symbol) override; - void storeSymbol(IrSymbolRef symbol, const VmValue &value) override; - VmFactPtr retainFact(const VmFactPtr &fact) override; - VmFactPtr retainPersistentFact(const VmFactPtr &fact, - std::span source) override; - VmFactPtr mutateFact(const VmFactPtr &fact, IrSymbolRef field, - const VmValue &value) override; - double deleteFacts(std::span facts) override; - VmFactPtr insertFact(std::span type, const VmMapPtr &values, - std::optional> source) override; - VmValue updateFacts(std::span facts, - const VmMapPtr &values) override; - VmValue projectFacts(std::span facts, - std::span fields) override; - double aggregateFacts(std::span facts, - std::span field, - std::uint8_t operation) override; - VmValue searchFacts(std::span facts, - std::span field, - const VmMapPtr &options) override; - VmValue joinFacts(std::span left, - std::span right, - std::span leftField, - std::span rightField, std::uint8_t kind, - IrSymbolRef joinedType, IrSymbolRef joinedLeft, - IrSymbolRef joinedRight) override; - void registerFactType(IrSymbolRef type, - std::vector parents, - std::vector> indexes = {}) override; - std::vector snapshotFacts(IrSymbolRef type) override; - std::vector snapshotMatchingFacts( - IrSymbolRef type, - std::span> predicates) override; - std::vector hierarchyProof(IrSymbolRef child, - IrSymbolRef ancestor) override; - std::vector> - hierarchyProofs(IrSymbolRef child, IrSymbolRef ancestor) override; - std::vector commonAncestors(IrSymbolRef left, - IrSymbolRef right) override; - std::vector - commonAncestorEvidence(IrSymbolRef left, IrSymbolRef right) override; - VmValue ancestorAnalysis(IrSymbolRef left, IrSymbolRef right) override; - std::vector rankFacts(IrSymbolRef effectiveAtField, - IrSymbolRef priorityField) override; - void installIrModule(const IrModule &module) override; - IrSymbolRef resolveSymbol(IrSymbolRef moduleSymbol) const override; - std::span runtimeSymbolTable() const override; - void enterProcedure(IrSymbolRef procedure, - std::span parameters, - std::span arguments) override; - void leaveProcedure() noexcept override; - RuntimeStateModel *runtimeStateModel() override; - TensorRuntime *tensorRuntime() override; - std::string decodeText(std::span pieces) const override; - PieceSequence encodeText(std::string_view text) const override; - VmText readFile(std::span path) const override; - VmValue importCsvFacts(std::span data, - std::span type, - std::span source) override; - void beginExecution() override; - void endExecution() noexcept override; - RuntimeContext makeRuntimeContext(const VmValue &systemInput) const override; - void refreshRuntimeContext(RuntimeContext &context) const override; - const std::shared_ptr &factStore() const noexcept { - return factStore_; - } - std::size_t installedModuleCount() const noexcept { - return module_.symbolTable.empty() ? 0 : 1; - } - -private: - IrSymbolRef internRuntimeSymbol(PieceSequence pieces); - double persistDatabaseSource(std::string_view source, - const VmFactPtr &emptySchema = {}); - // A frame has no AST payload and no shared registers. RegisterVm owns the - // fresh register vector for every invocation; the runtime owns only the - // procedure's lexical parameter/local bindings. - struct VmCallFrame { - IrSymbolRef procedure = 0; - std::unordered_map locals; - }; - std::vector callFrames_; - struct VmModuleState { - std::unordered_map globals; - std::vector symbolTable; - // One entry per module-local symbol. Values are one-based indexes into - // VmFactStore's symbol table, which remains stable across installed modules. - std::vector runtimeSymbols; - }; - // Module globals are process-resident knowledge-runtime state. Registers, - // call frames and recurrent state are deliberately excluded. - VmModuleState module_; - std::unordered_set registeredFactTypes_; - std::shared_ptr factStore_; - RuntimeStateModel *semanticModel_ = nullptr; - TensorRuntime *tensorRuntime_ = nullptr; - VmTextDecoder textDecoder_; - VmTextEncoder textEncoder_; - std::size_t maximumSemanticSteps_ = 1024; - std::size_t maximumCallDepth_ = 256; - std::size_t procedureDepth_ = 0; - std::size_t executionDepth_ = 0; - std::shared_ptr executionState_; - std::shared_ptr sharedSemanticSteps_; -}; - -class RegisterVm { -public: - explicit RegisterVm(std::size_t maximumInstructionSteps = 10'000'000); - VmValue executeMain(const VerifiedIrModule &module, VmRuntime &runtime, - VmValue systemInput = VmNil{}); - -private: - VmValue executeIrProgram(const IrModule &module, - const struct FelidaeIr &program, VmRuntime &runtime, - VmValue systemInput, std::size_t callDepth, - std::size_t &instructionSteps); - std::size_t maximumInstructionSteps_; -}; - -} // namespace Felidae diff --git a/src/form/RuntimeStateModel.cpp b/src/form/RuntimeStateModel.cpp deleted file mode 100644 index 5d3b9a2..0000000 --- a/src/form/RuntimeStateModel.cpp +++ /dev/null @@ -1,716 +0,0 @@ -#include "RuntimeStateModel.h" - -#include "BinaryIr.h" -#include "RuntimeTraining.h" -#include "SemanticOperation.h" -#include "../ModelStore.h" -#ifdef FELIDAE_HAS_FAISS -#include "libs/ExecutionVectorMemory.h" -#endif - -#include -#include -#include -#include - -#ifdef FELIDAE_HAS_TORCH -#include -#include -#include -#endif - -namespace Felidae { -namespace { -std::vector runtimeInputIds( - std::uint16_t operation, std::span inputKinds, - std::span> inputValues, - std::span factTypes, - std::span> factTypeCounts, - std::span> hierarchyEdges, - std::int64_t vocabularySize) { - constexpr std::size_t kMaximumContextItems = 1'024; - if (vocabularySize <= kRuntimeStructuralInputTokens) - throw IrError("runtime GRU input vocabulary is invalid"); - const auto structural = [&](std::int64_t value) { - return vocabularySize - kRuntimeStructuralInputTokens + value; - }; - const auto appendValueTokens = [&](std::vector &ids, - const auto &tokens) { - for (const auto token : tokens) { - if ((token & kRuntimeStructuralEncodingBit) != 0) { - const auto marker = token & ~kRuntimeStructuralEncodingBit; - if (marker >= kRuntimeStructuralInputTokens) - throw IrError("runtime GRU value marker exceeds its vocabulary"); - ids.push_back(structural(marker)); - } else { - if (token >= static_cast( - vocabularySize - kRuntimeStructuralInputTokens)) - throw IrError("runtime GRU value PieceId exceeds its vocabulary"); - ids.push_back(token); - } - } - }; - const auto appendPieces = [&](std::vector &ids, - const PieceSequence &pieces) { - if (pieces.empty()) - throw IrError("runtime GRU symbol has no SentencePiece IDs"); - for (const auto piece : pieces) { - if (piece >= static_cast(vocabularySize - - kRuntimeStructuralInputTokens)) { - throw IrError("runtime GRU SentencePiece ID exceeds its vocabulary"); - } - ids.push_back(piece); - } - }; - const auto marker = [&](RuntimeStructuralToken token) { - return structural(static_cast(token)); - }; - const auto kFactTypesMarker = marker(RuntimeStructuralToken::FactTypes); - const auto kHierarchyMarker = marker(RuntimeStructuralToken::Hierarchy); - const auto kInputsMarker = marker(RuntimeStructuralToken::Inputs); - if (!isKnownSemanticOperation(operation) || - !semanticOperationAcceptsArity(operation, inputKinds.size()) || - (!inputValues.empty() && inputValues.size() != inputKinds.size()) || - inputKinds.size() > kMaximumContextItems || - factTypes.size() > kMaximumContextItems || - factTypeCounts.size() > kMaximumContextItems || - hierarchyEdges.size() > kMaximumContextItems) { - throw IrError("runtime GRU operation context is invalid or too large"); - } - const auto inputKind = inputKinds.front(); - switch (static_cast(operation)) { - case SemanticOperationId::Identity: - break; - case SemanticOperationId::SelectFact: - case SemanticOperationId::DeriveFact: - if (inputKind != RuntimeValueKind::Fact) { - throw IrError("runtime GRU fact operation requires a fact input"); - } - break; - case SemanticOperationId::EvaluateDegree: - if (inputKind != RuntimeValueKind::Number && - inputKind != RuntimeValueKind::Degree) { - throw IrError("runtime GRU degree operation requires a numeric input"); - } - break; - case SemanticOperationId::Suggest: - break; - } - std::vector ids; - ids.reserve(2 + inputKinds.size() + factTypes.size() + - 2 * factTypeCounts.size() + 2 * hierarchyEdges.size()); - ids.push_back(structural(static_cast(operation) - 1)); - ids.push_back(kFactTypesMarker); - for (const auto &type : factTypes) - appendPieces(ids, type); - // Counts distinguish current fact population while keeping a fixed - // integer vocabulary: one, two-to-four, and five-or-more facts. - const auto kFactCountsMarker = marker(RuntimeStructuralToken::FactCounts); - const auto kOneFactMarker = marker(RuntimeStructuralToken::OneFact); - const auto kSeveralFactsMarker = marker(RuntimeStructuralToken::SeveralFacts); - const auto kManyFactsMarker = marker(RuntimeStructuralToken::ManyFacts); - ids.push_back(kFactCountsMarker); - for (const auto &[type, count] : factTypeCounts) { - appendPieces(ids, type); - ids.push_back(count == 1 ? kOneFactMarker - : count < 5 ? kSeveralFactsMarker - : kManyFactsMarker); - } - ids.push_back(kHierarchyMarker); - for (const auto &[child, parent] : hierarchyEdges) { - appendPieces(ids, child); - appendPieces(ids, parent); - } - ids.push_back(kInputsMarker); - for (const auto kind : inputKinds) { - if (kind < RuntimeValueKind::Nil || kind > RuntimeValueKind::TextMap) { - throw IrError("runtime GRU input value kind is invalid"); - } - ids.push_back(structural( - static_cast(RuntimeStructuralToken::InputKindBase) + - static_cast(kind))); - } - for (const auto &value : inputValues) - appendValueTokens(ids, value); - if (ids.size() > 4096) - throw IrError("runtime GRU input sequence exceeds its bound"); - return ids; -} -} // namespace - -std::vector defaultRuntimeOutputVocabulary() { - std::vector vocabulary; - vocabulary.reserve(3 + 2 * kRuntimeModelReferenceLimit + 5); - vocabulary.push_back({RuntimeOutputTokenKind::Nil, 0}); - vocabulary.push_back({RuntimeOutputTokenKind::NumericTruth, 0}); - vocabulary.push_back({RuntimeOutputTokenKind::NumericTruth, 1}); - for (std::size_t index = 0; index < kRuntimeModelReferenceLimit; ++index) { - vocabulary.push_back({RuntimeOutputTokenKind::InputReference, index}); - } - for (std::size_t index = 0; index < kRuntimeModelReferenceLimit; ++index) { - vocabulary.push_back({RuntimeOutputTokenKind::FactFromInput, index}); - } - // A compact degree lattice is intentionally explicit in the model output - // vocabulary. Exact numerical similarity/membership remains deterministic - // VM work; learned operations never masquerade as arbitrary arithmetic. - for (const std::size_t milli : {0u, 250u, 500u, 750u, 1000u}) { - vocabulary.push_back({RuntimeOutputTokenKind::DegreeMilli, milli}); - } - return vocabulary; -} - -class GruRuntimeStateModel::Implementation { -public: -#ifdef FELIDAE_HAS_TORCH - struct Network final : torch::nn::Module { - explicit Network(const Configuration &c) { - embedding = register_module( - "embedding", - torch::nn::Embedding(c.inputVocabularySize, c.embeddingSize)); - recurrent = register_module( - "recurrent", - torch::nn::GRU(torch::nn::GRUOptions(c.embeddingSize, c.hiddenSize) - .num_layers(c.layerCount))); - projection = register_module( - "projection", - torch::nn::Linear(c.hiddenSize, c.outputVocabularySize)); - scoreProjection = register_module("score_projection", - torch::nn::Linear(c.hiddenSize, 1)); - } - torch::nn::Embedding embedding{nullptr}; - torch::nn::GRU recurrent{nullptr}; - torch::nn::Linear projection{nullptr}; - torch::nn::Linear scoreProjection{nullptr}; - }; - struct ExecutionState { - torch::Tensor hidden; -#ifdef FELIDAE_HAS_FAISS - std::unique_ptr vectors; -#endif - }; - explicit Implementation(const Configuration &c, - const std::filesystem::path &artifact) { - if (c.inputVocabularySize <= kRuntimeStructuralInputTokens || - c.outputVocabularySize <= 0 || c.embeddingSize <= 0 || - c.hiddenSize <= 0 || c.layerCount <= 0) { - throw IrError("runtime GRU configuration is invalid"); - } - if (artifact.empty() && c.allowRandomInitialization) { - network = std::make_shared(c); - network->eval(); - return; - } - if (artifact.empty() || !std::filesystem::is_regular_file(artifact)) { - throw IrError("runtime GRU artifact is unavailable: " + - artifact.string()); - } - if (artifact.extension() != ".pt") { - throw IrError( - "runtime production artifact must be a .pt TorchScript module"); - } - try { - production = torch::jit::load(artifact.string()); - production->eval(); - torch::InferenceMode guard; - const auto input = - torch::zeros({1, 1}, torch::TensorOptions().dtype(torch::kInt64)); - const auto hidden = torch::zeros({c.layerCount, 1, c.hiddenSize}); - const auto output = production->forward({input, hidden}).toTuple(); - if (output->elements().size() != 3) { - throw IrError( - "runtime production artifact has an incompatible forward contract"); - } - const auto logits = output->elements()[0].toTensor(); - const auto score = output->elements()[1].toTensor(); - const auto nextHidden = output->elements()[2].toTensor(); - if (logits.dim() != 1 || logits.size(0) != c.outputVocabularySize || - score.numel() != 1 || - nextHidden.dim() != 3 || nextHidden.size(0) != c.layerCount || - nextHidden.size(1) != 1 || nextHidden.size(2) != c.hiddenSize) { - throw IrError( - "runtime production artifact has an incompatible forward contract"); - } - } catch (const c10::Error &error) { - throw IrError("runtime production artifact is not valid TorchScript: " + - std::string(error.what_without_backtrace())); - } - } - std::shared_ptr network; - std::optional production; - std::unique_ptr optimizer; - double optimizerLearningRate = 0.0; - - void prepareOptimizer(double learningRate) { - if (!network) - throw IrError("TorchScript inference artifact cannot be used as a " - "training checkpoint"); - if (!optimizer || optimizerLearningRate != learningRate) { - optimizer = std::make_unique( - network->parameters(), torch::optim::AdamOptions(learningRate)); - optimizerLearningRate = learningRate; - } - } -#else - explicit Implementation(const Configuration &, - const std::filesystem::path &) { - throw IrError("runtime GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); - } -#endif -}; - -GruRuntimeStateModel::GruRuntimeStateModel( - Configuration c, std::vector vocabulary) - : GruRuntimeStateModel(std::move(c), std::move(vocabulary), {}, - VersionedArtifact{}) {} - -GruRuntimeStateModel::GruRuntimeStateModel( - Configuration c, std::vector vocabulary, - const std::filesystem::path &artifact, VersionedArtifact) - : configuration_(c), outputVocabulary_(std::move(vocabulary)), - implementation_( - std::make_unique(configuration_, artifact)) { - if (configuration_.inputVocabularySize <= kRuntimeStructuralInputTokens || - configuration_.outputVocabularySize <= 0 || - configuration_.embeddingSize <= 0 || configuration_.hiddenSize <= 0 || - configuration_.layerCount <= 0 || - outputVocabulary_.size() != - static_cast(configuration_.outputVocabularySize)) - throw IrError( - "runtime GRU configuration or finite output vocabulary is invalid"); - for (const auto &token : outputVocabulary_) - if ((token.kind == RuntimeOutputTokenKind::NumericTruth && - token.value > 1) || - (token.kind == RuntimeOutputTokenKind::DegreeMilli && - token.value > 1000)) - throw IrError("runtime GRU output token is invalid"); -} -GruRuntimeStateModel::~GruRuntimeStateModel() = default; -GruRuntimeStateModel::GruRuntimeStateModel(GruRuntimeStateModel &&) noexcept = - default; -GruRuntimeStateModel & -GruRuntimeStateModel::operator=(GruRuntimeStateModel &&) noexcept = default; - -GruRuntimeStateModel GruRuntimeStateModel::loadVersioned( - Configuration c, std::vector vocabulary, - const std::filesystem::path &directory, - std::string_view expectedSentencePieceIdentity) { - const auto manifest = - readModelManifest(directory / "runtime-manifest.txt"); - constexpr std::string_view modelName = "runtime SSM"; - requireManifestValue(manifest, "artifact_format_version", - kRuntimeArtifactFormatVersion, modelName); - requireManifestValue(manifest, "model_family", kRuntimeModelFamily, - modelName); - requireManifestValue(manifest, "model_version", kRuntimeModelVersion, - modelName); - requireManifestValue(manifest, "backend", "torchscript-gru", modelName); - requireManifestValue(manifest, "tokenizer_contract", - kRuntimeTokenizerContract, modelName); - requireManifestValue(manifest, "sentencepiece_model_identity", - expectedSentencePieceIdentity, modelName); - requireManifestValue(manifest, "decoder_contract", kRuntimeDecoderContract, - modelName); - // Checked against LANGUAGE_VERSION (Version.h), the one source of truth - // for every version this project reports -- there is no separate binary - // IR format version to keep in sync with it. - requireManifestValue(manifest, "ir_binary_version", LANGUAGE_VERSION, - modelName); - requireManifestValue(manifest, "opcode_vocabulary_version", "felidae-ir-v13", - modelName); - requireManifestValue(manifest, "training_schema", - "felidae-runtime-operation-v9", modelName); - if (manifestInteger(manifest, "input_vocabulary", modelName) != - c.inputVocabularySize || - manifestInteger(manifest, "output_vocabulary", modelName) != - c.outputVocabularySize || - manifestInteger(manifest, "embedding_size", modelName) != - c.embeddingSize || - manifestInteger(manifest, "hidden_size", modelName) != c.hiddenSize || - manifestInteger(manifest, "layer_count", modelName) != c.layerCount) - throw IrError("runtime SSM manifest configuration is incompatible"); - const auto artifact = directory / "runtime-gru.pt"; - if (!std::filesystem::is_regular_file(artifact)) - throw IrError("runtime SSM artifact is unavailable"); - return GruRuntimeStateModel(std::move(c), std::move(vocabulary), artifact, - VersionedArtifact{}); -} - -std::shared_ptr GruRuntimeStateModel::createExecutionState() { -#ifdef FELIDAE_HAS_TORCH - return std::make_shared(); -#else - throw IrError("runtime GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -Value GruRuntimeStateModel::evaluate(const RuntimeOperation &operation, - std::span inputs, - RuntimeContext &context) { -#ifdef FELIDAE_HAS_TORCH - if (!context.executionState) - throw IrError( - "runtime GRU evaluation has no execution-local recurrent state"); - auto state = std::static_pointer_cast( - context.executionState); - std::vector inputKinds; - inputKinds.reserve(inputs.size()); - for (const auto &input : inputs) - inputKinds.push_back(runtimeValueKind(input)); - const auto symbols = - context.symbolTable ? std::span(*context.symbolTable) - : std::span{}; - const auto knowledge = runtimeKnowledgePieces(context.knowledge, symbols); - std::vector> inputValues; - inputValues.reserve(inputs.size()); - for (const auto &value : inputs) - inputValues.push_back(runtimeValueEncoding(value, symbols)); - const auto ids = runtimeInputIds( - operation.id, inputKinds, inputValues, knowledge.factTypes, - knowledge.factTypeCounts, knowledge.hierarchyEdges, - configuration_.inputVocabularySize); - torch::InferenceMode guard; - const auto input = - torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - torch::Tensor logits; - torch::Tensor score; - if (implementation_->production) { - if (!state->hidden.defined()) - state->hidden = torch::zeros( - {configuration_.layerCount, 1, configuration_.hiddenSize}); - auto output = - implementation_->production->forward({input, state->hidden}).toTuple(); - logits = output->elements().at(0).toTensor(); - score = output->elements().at(1).toTensor(); - state->hidden = output->elements().at(2).toTensor().detach(); - } else { - const auto result = - state->hidden.defined() - ? implementation_->network->recurrent->forward( - implementation_->network->embedding->forward(input), - state->hidden) - : implementation_->network->recurrent->forward( - implementation_->network->embedding->forward(input)); - state->hidden = std::get<1>(result).detach(); - const auto last = std::get<0>(result) - .select(0, std::get<0>(result).size(0) - 1) - .select(0, 0); - logits = implementation_->network->projection->forward(last); - score = implementation_->network->scoreProjection->forward(last); - } -#ifdef FELIDAE_HAS_FAISS - // Flatten all recurrent layers from this evaluation, not token IDs or - // projected scores. Faiss copies the data; no tensor/autograd graph is held. - const auto vector = state->hidden.to(torch::kCPU, torch::kFloat32).contiguous(); - const auto dimensions = static_cast(vector.numel()); - if (!state->vectors) - state->vectors = std::make_unique( - dimensions, context.maximumSemanticSteps); - state->vectors->append({vector.data_ptr(), dimensions}); -#endif - if (operation.id == static_cast(SemanticOperationId::Suggest)) { - const auto value = score.item(); - if (!std::isfinite(value)) - throw IrError("runtime GRU scoring head produced a non-finite value"); - return value; - } - const auto outputId = logits.argmax().item(); - if (outputId < 0 || - static_cast(outputId) >= outputVocabulary_.size()) - throw IrError( - "runtime GRU emitted a token outside its finite output vocabulary"); - const auto &token = outputVocabulary_[static_cast(outputId)]; - switch (token.kind) { - case RuntimeOutputTokenKind::InputReference: - if (token.value >= inputs.size()) - throw IrError("runtime GRU emitted an unavailable input reference"); - return inputs[token.value]; - case RuntimeOutputTokenKind::FactFromInput: { - if (token.value >= inputs.size()) - throw IrError("runtime GRU emitted an unavailable fact input reference"); - const auto fact = std::get_if(&inputs[token.value]); - if (!fact || !*fact) - throw IrError("runtime GRU fact action requires a fact input"); - auto inferred = std::make_shared(**fact); - inferred->id = 0; - return inferred; - } - case RuntimeOutputTokenKind::DegreeMilli: - return VmDegree(static_cast(token.value) / 1000.0); - case RuntimeOutputTokenKind::Nil: - return VmNil{}; - case RuntimeOutputTokenKind::NumericTruth: - return token.value != 0 ? 1.0 : 0.0; - } - throw IrError("runtime GRU emitted an invalid output token"); -#else - (void)operation; - (void)inputs; - (void)context; - throw IrError("runtime GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -double -GruRuntimeStateModel::trainTeacherForced(const RuntimeTrainingRecord &record, - std::size_t targetToken, - double learningRate) { -#ifdef FELIDAE_HAS_TORCH - verifyRuntimeTrainingRecord(record); - if (targetToken >= outputVocabulary_.size() || learningRate <= 0.0) - throw IrError("runtime GRU training target or learning rate is invalid"); - const auto ids = - runtimeInputIds(record.operationId, record.inputKinds, record.inputValues, - record.factTypes, - record.factTypeCounts, record.hierarchyEdges, - configuration_.inputVocabularySize); - if (ids.size() > 4096) - throw IrError("runtime GRU training record is too large"); - implementation_->prepareOptimizer(learningRate); - implementation_->network->train(); - implementation_->optimizer->zero_grad(); - const auto input = - torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - const auto recurrent = implementation_->network->recurrent->forward( - implementation_->network->embedding->forward(input)); - const auto logits = implementation_->network->projection->forward( - std::get<0>(recurrent) - .select(0, std::get<0>(recurrent).size(0) - 1) - .select(0, 0)); - const auto target = - torch::tensor({static_cast(targetToken)}, - torch::TensorOptions().dtype(torch::kInt64)); - const auto loss = - torch::nn::functional::cross_entropy(logits.unsqueeze(0), target); - loss.backward(); - implementation_->optimizer->step(); - implementation_->network->eval(); - return loss.item(); -#else - (void)record; - (void)targetToken; - (void)learningRate; - throw IrError("runtime GRU training requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -double GruRuntimeStateModel::trainScore(const RuntimeTrainingRecord &record, - double learningRate) { -#ifdef FELIDAE_HAS_TORCH - verifyRuntimeTrainingRecord(record); - if (record.operationId != - static_cast(SemanticOperationId::Suggest) || - record.targetKind != RuntimeTrainingTargetKind::Score || - !std::isfinite(record.targetScore) || learningRate <= 0.0) - throw IrError("runtime GRU score target or learning rate is invalid"); - const auto ids = runtimeInputIds( - record.operationId, record.inputKinds, record.inputValues, record.factTypes, - record.factTypeCounts, record.hierarchyEdges, - configuration_.inputVocabularySize); - implementation_->prepareOptimizer(learningRate); - implementation_->network->train(); - implementation_->optimizer->zero_grad(); - const auto input = - torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - const auto recurrent = implementation_->network->recurrent->forward( - implementation_->network->embedding->forward(input)); - const auto last = std::get<0>(recurrent) - .select(0, std::get<0>(recurrent).size(0) - 1) - .select(0, 0); - const auto predicted = - implementation_->network->scoreProjection->forward(last).reshape({}); - const auto expected = - torch::tensor(record.targetScore, predicted.options()); - const auto loss = torch::mse_loss(predicted, expected); - const auto lossValue = loss.item(); - if (!std::isfinite(lossValue)) - throw IrError("runtime GRU score training produced non-finite loss"); - loss.backward(); - implementation_->optimizer->step(); - implementation_->network->eval(); - return lossValue; -#else - (void)record; - (void)learningRate; - throw IrError("runtime GRU score training requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -std::size_t GruRuntimeStateModel::predictTeacherToken( - const RuntimeTrainingRecord &record) const { -#ifdef FELIDAE_HAS_TORCH - if (!implementation_->network) - throw IrError("runtime teacher prediction requires a training model"); - verifyRuntimeTrainingRecord(record); - const auto ids = - runtimeInputIds(record.operationId, record.inputKinds, record.inputValues, - record.factTypes, - record.factTypeCounts, record.hierarchyEdges, - configuration_.inputVocabularySize); - torch::InferenceMode guard; - const auto input = - torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - const auto recurrent = implementation_->network->recurrent->forward( - implementation_->network->embedding->forward(input)); - const auto output = - implementation_->network->projection - ->forward(std::get<0>(recurrent) - .select(0, std::get<0>(recurrent).size(0) - 1) - .select(0, 0)) - .argmax() - .item(); - if (output < 0 || - static_cast(output) >= outputVocabulary_.size()) { - throw IrError("runtime GRU validation emitted an invalid token"); - } - return static_cast(output); -#else - (void)record; - throw IrError("runtime GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -double GruRuntimeStateModel::predictScore( - const RuntimeTrainingRecord &record) const { -#ifdef FELIDAE_HAS_TORCH - if (!implementation_->network || - record.operationId != - static_cast(SemanticOperationId::Suggest)) - throw IrError("runtime score prediction requires a Suggest training record"); - verifyRuntimeTrainingRecord(record); - const auto ids = runtimeInputIds( - record.operationId, record.inputKinds, record.inputValues, record.factTypes, - record.factTypeCounts, record.hierarchyEdges, - configuration_.inputVocabularySize); - torch::InferenceMode guard; - const auto input = - torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - const auto recurrent = implementation_->network->recurrent->forward( - implementation_->network->embedding->forward(input)); - const auto value = implementation_->network->scoreProjection - ->forward(std::get<0>(recurrent) - .select(0, std::get<0>(recurrent).size(0) - 1) - .select(0, 0)) - .item(); - if (!std::isfinite(value)) - throw IrError("runtime GRU scoring head produced a non-finite value"); - return value; -#else - (void)record; - throw IrError("runtime GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -void GruRuntimeStateModel::saveCheckpoint( - const std::filesystem::path &artifactPath) const { -#ifdef FELIDAE_HAS_TORCH - if (!implementation_->network) - throw IrError("runtime checkpoint export requires a training model"); - if (artifactPath.empty()) - throw IrError("runtime GRU checkpoint path is empty"); - if (artifactPath.extension() != ".ckpt") { - throw IrError("runtime training checkpoint must use the .ckpt extension"); - } - const auto parent = artifactPath.parent_path(); - if (!parent.empty()) - std::filesystem::create_directories(parent); - torch::save(implementation_->network, artifactPath.string()); -#else - (void)artifactPath; - throw IrError( - "runtime GRU checkpoint export requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -void GruRuntimeStateModel::exportTorchScript( - const std::filesystem::path &artifactPath, - std::string_view sentencePieceIdentity) const { -#ifdef FELIDAE_HAS_TORCH - if (!implementation_->network) - throw IrError("runtime TorchScript export requires a training model"); - if (artifactPath.empty()) - throw IrError("runtime TorchScript artifact path is empty"); - if (artifactPath.extension() != ".pt") { - throw IrError("runtime TorchScript artifact must use the .pt extension"); - } - if (!sentencePieceIdentity.starts_with("sha256:") || - sentencePieceIdentity.size() != 71) { - throw IrError("runtime TorchScript export requires an exact SHA-256 " - "SentencePiece identity"); - } - const auto parent = artifactPath.parent_path(); - if (!parent.empty()) - std::filesystem::create_directories(parent); - torch::jit::Module module("FelidaeRuntimeGru"); - module.register_parameter( - "embedding", implementation_->network->embedding->weight.detach().clone(), - false); - module.register_parameter( - "projection_weight", - implementation_->network->projection->weight.detach().clone(), false); - module.register_parameter( - "projection_bias", - implementation_->network->projection->bias.detach().clone(), false); - module.register_parameter( - "score_projection_weight", - implementation_->network->scoreProjection->weight.detach().clone(), - false); - module.register_parameter( - "score_projection_bias", - implementation_->network->scoreProjection->bias.detach().clone(), false); - std::ostringstream parameters; - bool first = true; - for (const auto ¶meter : - implementation_->network->recurrent->named_parameters(false)) { - const auto name = "recurrent_" + parameter.key(); - module.register_parameter(name, parameter.value().detach().clone(), false); - if (!first) - parameters << ", "; - parameters << "self." << name; - first = false; - } - std::ostringstream source; - source << "def forward(self, input_ids: Tensor, hidden: Tensor) -> " - "Tuple[Tensor, Tensor, Tensor]:\n" - << " embedded = torch.embedding(self.embedding, input_ids)\n" - << " recurrent = torch.gru(embedded, hidden, [" << parameters.str() - << "], True, " << configuration_.layerCount - << ", 0.0, False, False, False)\n" - << " logits = torch.linear(recurrent[0][-1][0], " - "self.projection_weight, self.projection_bias)\n" - << " score = torch.linear(recurrent[0][-1][0], " - "self.score_projection_weight, self.score_projection_bias)\n" - << " return logits, score, recurrent[1]\n"; - module.define(source.str()); - module.eval(); - module.save(artifactPath.string()); - std::ofstream manifest(parent / "runtime-manifest.txt", std::ios::trunc); - if (!manifest) - throw IrError("cannot write runtime SSM manifest"); - manifest << "artifact_format_version=" << kRuntimeArtifactFormatVersion - << "\nmodel_family=" << kRuntimeModelFamily - << "\nmodel_version=" << kRuntimeModelVersion - << "\nbackend=torchscript-gru\ntokenizer_contract=" - << kRuntimeTokenizerContract - << "\nsentencepiece_model_identity=" << sentencePieceIdentity - << "\ndecoder_contract=" << kRuntimeDecoderContract - << "\nir_binary_version=" << LANGUAGE_VERSION - << "\nopcode_vocabulary_version=felidae-ir-v13\ntraining_schema=" - "felidae-runtime-operation-v9\ninput_vocabulary=" - << configuration_.inputVocabularySize - << "\noutput_vocabulary=" << configuration_.outputVocabularySize - << "\nembedding_size=" << configuration_.embeddingSize - << "\nhidden_size=" << configuration_.hiddenSize - << "\nlayer_count=" << configuration_.layerCount << "\n"; -#else - (void)artifactPath; - (void)sentencePieceIdentity; - throw IrError( - "runtime GRU TorchScript export requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} -} // namespace Felidae diff --git a/src/form/RuntimeStateModel.h b/src/form/RuntimeStateModel.h deleted file mode 100644 index 25a860f..0000000 --- a/src/form/RuntimeStateModel.h +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -#include "RegisterVm.h" - -#include -#include -#include -#include -#include - -namespace Felidae { - -struct RuntimeTrainingRecord; - -// The Form daemon's recurrent model is intentionally separate from the -// compiler's mixfix IR decoder. It selects only finite, typed VM outcomes. -enum class RuntimeOutputTokenKind : std::uint8_t { - InputReference, - FactFromInput, - DegreeMilli, - Nil, - NumericTruth, -}; - -struct RuntimeOutputToken { - RuntimeOutputTokenKind kind = RuntimeOutputTokenKind::Nil; - std::size_t value = 0; -}; - -// The GRU may select one of these bounded argument positions. This remains -// a finite decoder vocabulary and every selected position is range-checked -// against the current operation inputs before it enters a VM register. -inline constexpr std::size_t kRuntimeModelReferenceLimit = 16; -inline constexpr std::int64_t kRuntimeStructuralInputTokens = 48; -inline constexpr std::string_view kRuntimeArtifactFormatVersion = "2"; -inline constexpr std::string_view kRuntimeModelFamily = - "felidae-vm-runtime-gru"; -inline constexpr std::string_view kRuntimeModelVersion = "runtime-gru-v2"; -inline constexpr std::string_view kRuntimeTokenizerContract = - "sentencepiece-structured-values-v2"; -inline constexpr std::string_view kRuntimeDecoderContract = - "typed-actions-plus-finite-score-v2"; - -// Single production vocabulary contract used by both the VM loader and the -// C++ trainer. A manifest's output_vocabulary is checked against this list. -std::vector defaultRuntimeOutputVocabulary(); - -class GruRuntimeStateModel final : public RuntimeStateModel { -public: - struct Configuration { - std::int64_t inputVocabularySize = 0; - std::int64_t outputVocabularySize = 0; - std::int64_t embeddingSize = 64; - std::int64_t hiddenSize = 128; - std::int64_t layerCount = 1; - bool allowRandomInitialization = false; - }; - - GruRuntimeStateModel(Configuration configuration, - std::vector outputVocabulary); - ~GruRuntimeStateModel() override; - GruRuntimeStateModel(GruRuntimeStateModel&&) noexcept; - GruRuntimeStateModel& operator=(GruRuntimeStateModel&&) noexcept; - GruRuntimeStateModel(const GruRuntimeStateModel&) = delete; - GruRuntimeStateModel& operator=(const GruRuntimeStateModel&) = delete; - - std::shared_ptr createExecutionState() override; - static GruRuntimeStateModel loadVersioned(Configuration configuration, - std::vector outputVocabulary, - const std::filesystem::path& artifactDirectory, - std::string_view expectedSentencePieceIdentity); - Value evaluate(const RuntimeOperation& operation, std::span inputs, - RuntimeContext& context) override; - double trainTeacherForced(const RuntimeTrainingRecord& record, - std::size_t targetToken, double learningRate); - double trainScore(const RuntimeTrainingRecord& record, - double learningRate); - // Deterministic validation path for a persisted JSONL record. It returns - // a finite vocabulary index without constructing a runtime VmValue. - std::size_t predictTeacherToken(const RuntimeTrainingRecord& record) const; - double predictScore(const RuntimeTrainingRecord& record) const; - void saveCheckpoint(const std::filesystem::path& checkpointPath) const; - void exportTorchScript(const std::filesystem::path& artifactPath, - std::string_view sentencePieceIdentity) const; - -private: - struct VersionedArtifact {}; - GruRuntimeStateModel(Configuration configuration, - std::vector outputVocabulary, - const std::filesystem::path& artifactPath, - VersionedArtifact); - class Implementation; - Configuration configuration_; - std::vector outputVocabulary_; - std::unique_ptr implementation_; -}; - -} // namespace Felidae diff --git a/src/form/RuntimeTraining.cpp b/src/form/RuntimeTraining.cpp deleted file mode 100644 index dd7d7a2..0000000 --- a/src/form/RuntimeTraining.cpp +++ /dev/null @@ -1,530 +0,0 @@ -#include "RuntimeTraining.h" -#include "IrModule.h" -#include "SemanticOperation.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae { -namespace { -using Json = nlohmann::json; -constexpr std::size_t kMaximumRecords = 1'000'000; -constexpr std::size_t kMaximumItems = 1'000'000; - -void requireJsonlPath(const std::filesystem::path &path) { - if (path.extension() != ".jsonl") - throw IrError("runtime training datasets must use the .jsonl extension"); -} - -std::uint64_t unsignedValue(const Json &value, const char *name) { - if (!value.is_number_unsigned()) - throw IrError(std::string("runtime JSONL ") + name + - " must be an unsigned integer"); - return value.get(); -} - -std::uint64_t member(const Json &object, const char *name) { - if (!object.contains(name)) - throw IrError(std::string("runtime JSONL record is missing ") + name); - return unsignedValue(object.at(name), name); -} - -template T bounded(std::uint64_t value, const char *name) { - if (value > static_cast(std::numeric_limits::max())) { - throw IrError(std::string("runtime JSONL ") + name + - " exceeds the supported ID range"); - } - return static_cast(value); -} - -RuntimeValueKind valueKind(std::uint64_t value, const char *name) { - if (value < static_cast(RuntimeValueKind::Nil) || - value > static_cast(RuntimeValueKind::TextMap)) { - throw IrError(std::string("runtime JSONL has an invalid ") + name); - } - return static_cast(value); -} - -RuntimeTrainingTargetKind targetKind(std::uint64_t value) { - if (value < static_cast( - RuntimeTrainingTargetKind::InputReference) || - value > - static_cast(RuntimeTrainingTargetKind::Score)) { - throw IrError("runtime JSONL has an invalid target kind"); - } - return static_cast(value); -} - -RuntimeValueKind targetValueKind(const RuntimeTrainingRecord &record) { - switch (record.targetKind) { - case RuntimeTrainingTargetKind::InputReference: - if (record.targetValue >= record.inputKinds.size()) { - throw IrError("runtime JSONL input-reference target is unavailable"); - } - return record.inputKinds[record.targetValue]; - case RuntimeTrainingTargetKind::FactFromInput: - if (record.targetValue >= record.inputKinds.size() || - record.inputKinds[record.targetValue] != RuntimeValueKind::Fact) { - throw IrError( - "runtime JSONL fact target does not reference a fact input"); - } - return RuntimeValueKind::Fact; - case RuntimeTrainingTargetKind::DegreeMilli: - return RuntimeValueKind::Degree; - case RuntimeTrainingTargetKind::Nil: - return RuntimeValueKind::Nil; - case RuntimeTrainingTargetKind::NumericTruth: - return RuntimeValueKind::Number; - case RuntimeTrainingTargetKind::Score: - return RuntimeValueKind::Number; - } - throw IrError("runtime JSONL target kind is invalid"); -} - -void validateTrainingContract(const RuntimeTrainingRecord &record) { - if (!isKnownSemanticOperation(record.operationId) || - !semanticOperationAcceptsArity(record.operationId, - record.inputKinds.size())) { - throw IrError("runtime JSONL semantic operation contract is invalid"); - } - const auto input = record.inputKinds.front(); - const auto output = targetValueKind(record); - switch (static_cast(record.operationId)) { - case SemanticOperationId::Identity: - if (output != input) - throw IrError("runtime Identity teacher changes value kind"); - return; - case SemanticOperationId::SelectFact: - case SemanticOperationId::DeriveFact: - if (input != RuntimeValueKind::Fact || - (output != RuntimeValueKind::Fact && output != RuntimeValueKind::Nil)) { - throw IrError("runtime fact-operation teacher has invalid kinds"); - } - return; - case SemanticOperationId::EvaluateDegree: - if ((input != RuntimeValueKind::Number && - input != RuntimeValueKind::Degree) || - output != RuntimeValueKind::Degree) { - throw IrError("runtime degree-operation teacher has invalid kinds"); - } - return; - case SemanticOperationId::Suggest: - if (record.targetKind != RuntimeTrainingTargetKind::Score || - output != RuntimeValueKind::Number) - throw IrError("runtime Suggest teacher must describe a numeric score"); - return; - } - throw IrError("runtime JSONL semantic operation ID is invalid"); -} - -template std::vector ids(const Json &object, const char *name) { - if (!object.contains(name) || !object.at(name).is_array()) - throw IrError(std::string("runtime JSONL record requires array ") + name); - const auto &source = object.at(name); - if (source.size() > kMaximumItems) - throw IrError(std::string("runtime JSONL ") + name + " is too large"); - std::vector output; - output.reserve(source.size()); - for (const auto &value : source) - output.push_back(bounded(unsignedValue(value, name), name)); - return output; -} - -PieceSequence pieceSequence(const Json &value, const char *name) { - if (!value.is_array() || value.empty()) { - throw IrError(std::string("runtime JSONL ") + name + - " must be a non-empty SentencePiece ID array"); - } - if (value.size() > kMaximumItems) { - throw IrError(std::string("runtime JSONL ") + name + " is too large"); - } - PieceSequence result; - result.reserve(value.size()); - for (const auto &piece : value) { - result.push_back(bounded(unsignedValue(piece, name), name)); - } - return result; -} - -std::vector pieceSequences(const Json &object, - const char *name) { - if (!object.contains(name) || !object.at(name).is_array()) { - throw IrError(std::string("runtime JSONL record requires array ") + name); - } - const auto &source = object.at(name); - if (source.size() > kMaximumItems) { - throw IrError(std::string("runtime JSONL ") + name + " is too large"); - } - std::vector result; - result.reserve(source.size()); - for (const auto &value : source) - result.push_back(pieceSequence(value, name)); - return result; -} - -std::vector> -hierarchyEdges(const Json &object) { - if (!object.contains("hierarchy_edges") || - !object.at("hierarchy_edges").is_array()) { - throw IrError("runtime JSONL record requires array hierarchy_edges"); - } - const auto &source = object.at("hierarchy_edges"); - if (source.size() > kMaximumItems) - throw IrError("runtime JSONL hierarchy_edges is too large"); - std::vector> result; - result.reserve(source.size()); - for (const auto &edge : source) { - if (!edge.is_array() || edge.size() != 2) - throw IrError("runtime JSONL hierarchy edge must contain child and " - "parent SentencePiece sequences"); - result.emplace_back(pieceSequence(edge[0], "hierarchy edge child"), - pieceSequence(edge[1], "hierarchy edge parent")); - } - return result; -} - -std::vector> -factTypeCounts(const Json &object) { - if (!object.contains("fact_type_counts") || - !object.at("fact_type_counts").is_array()) { - throw IrError("runtime JSONL record requires array fact_type_counts"); - } - const auto &source = object.at("fact_type_counts"); - if (source.size() > kMaximumItems) - throw IrError("runtime JSONL fact_type_counts is too large"); - std::vector> result; - result.reserve(source.size()); - for (const auto &item : source) { - if (!item.is_array() || item.size() != 2) - throw IrError("runtime JSONL fact-type count must contain a " - "SentencePiece sequence and count"); - result.emplace_back( - pieceSequence(item[0], "fact-type count type"), - bounded(unsignedValue(item[1], "fact-type count"), - "fact-type count")); - } - if (!std::is_sorted(result.begin(), result.end()) || - std::adjacent_find(result.begin(), result.end(), - [](const auto &left, const auto &right) { - return left.first == right.first; - }) != result.end()) { - throw IrError("runtime JSONL fact_type_counts must be sorted and unique"); - } - return result; -} -} // namespace - -std::vector -runtimeValueEncoding(const VmValue &value, - std::span symbolTable) { - constexpr std::size_t kMaximumEncodedTokens = 4096; - std::vector result; - const auto appendSymbol = [&](IrSymbolRef symbol) { - const auto pieces = irSymbolPieces(symbolTable, symbol); - result.insert(result.end(), pieces.begin(), pieces.end()); - }; - const auto orderedFields = [&](const auto &fields) { - std::vector order(fields.size()); - std::iota(order.begin(), order.end(), 0); - std::sort(order.begin(), order.end(), [&](std::size_t left, - std::size_t right) { - const auto leftPieces = irSymbolPieces(symbolTable, fields[left].first); - const auto rightPieces = irSymbolPieces(symbolTable, fields[right].first); - return std::lexicographical_compare( - leftPieces.begin(), leftPieces.end(), rightPieces.begin(), - rightPieces.end()); - }); - return order; - }; - const auto appendNumber = [&](double number, std::uint32_t marker) { - result.push_back(kRuntimeStructuralEncodingBit | marker); - const auto bits = std::bit_cast(number); - for (int bit = 63; bit >= 0; --bit) - result.push_back(runtimeStructuralToken( - (bits & (std::uint64_t{1} << bit)) - ? RuntimeStructuralToken::NumberBitOne - : RuntimeStructuralToken::NumberBitZero)); - }; - const auto append = [&](const auto &self, const VmValue &item, - std::size_t depth) -> void { - if (depth > 32 || result.size() > kMaximumEncodedTokens) - throw IrError("runtime SSM value encoding exceeds its bound"); - if (std::holds_alternative(item)) { - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Nil)); - } else if (const auto number = std::get_if(&item)) { - appendNumber(*number, - static_cast(RuntimeStructuralToken::Number)); - } else if (const auto degree = std::get_if(&item)) { - appendNumber(degree->value, - static_cast(RuntimeStructuralToken::Degree)); - } else if (const auto text = std::get_if(&item)) { - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Text)); - result.insert(result.end(), text->pieces.begin(), text->pieces.end()); - } else if (const auto symbol = std::get_if(&item)) { - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Symbol)); - appendSymbol(symbol->value); - } else if (const auto array = std::get_if(&item)) { - if (!*array) - throw IrError("runtime SSM cannot encode a null array"); - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Array)); - for (const auto &value : (*array)->values) - self(self, value, depth + 1); - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); - } else if (const auto map = std::get_if(&item)) { - if (!*map) - throw IrError("runtime SSM cannot encode a null map"); - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Map)); - for (const auto index : orderedFields((*map)->entries)) { - const auto &[field, value] = (*map)->entries[index]; - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Field)); - appendSymbol(field); - self(self, value, depth + 1); - } - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); - } else if (const auto fact = std::get_if(&item)) { - if (!*fact) - throw IrError("runtime SSM cannot encode a null fact"); - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Fact)); - appendSymbol((*fact)->type); - for (const auto index : orderedFields((*fact)->fields)) { - const auto &[field, value] = (*fact)->fields[index]; - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Field)); - appendSymbol(field); - self(self, value, depth + 1); - } - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); - } else if (const auto tensor = std::get_if(&item)) { - if (!*tensor || !(*tensor)->storage) - throw IrError("runtime SSM cannot encode a null tensor"); - throw IrError("runtime SSM tensor inputs are unsupported; pass an " - "explicit fact or numeric summary"); - } else if (const auto map = std::get_if(&item)) { - if (!*map) - throw IrError("runtime SSM cannot encode a null text map"); - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::TextMap)); - auto entries = (*map)->entries; - std::sort(entries.begin(), entries.end(), - [](const auto &left, const auto &right) { - return left.first < right.first; - }); - for (const auto &[key, value] : entries) { - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::Field)); - result.insert(result.end(), key.begin(), key.end()); - self(self, value, depth + 1); - } - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); - } - if (result.size() > kMaximumEncodedTokens) - throw IrError("runtime SSM value encoding exceeds its bound"); - }; - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueStart)); - append(append, value, 0); - result.push_back(runtimeStructuralToken(RuntimeStructuralToken::ValueEnd)); - return result; -} - -void verifyRuntimeTrainingRecord(const RuntimeTrainingRecord &record) { - if (record.inputKinds.size() > kMaximumItems || - record.inputValues.size() != record.inputKinds.size() || - record.factTypes.size() > kMaximumItems || - record.factTypeCounts.size() > kMaximumItems || - record.hierarchyEdges.size() > kMaximumItems) { - throw IrError("runtime JSONL record is too large"); - } - for (const auto kind : record.inputKinds) { - (void)valueKind(static_cast(kind), "input value kind"); - } - for (const auto &value : record.inputValues) - if (value.empty() || value.size() > 4096) - throw IrError("runtime JSONL input value encoding is invalid"); - const auto validSequence = [](const PieceSequence &pieces) { - if (pieces.empty()) - throw IrError("runtime JSONL symbol has no SentencePiece IDs"); - }; - for (const auto &type : record.factTypes) - validSequence(type); - for (const auto &[type, count] : record.factTypeCounts) { - (void)count; - validSequence(type); - } - for (const auto &[child, parent] : record.hierarchyEdges) { - validSequence(child); - validSequence(parent); - } - if (!std::is_sorted(record.factTypeCounts.begin(), - record.factTypeCounts.end()) || - std::adjacent_find(record.factTypeCounts.begin(), - record.factTypeCounts.end(), - [](const auto &left, const auto &right) { - return left.first == right.first; - }) != record.factTypeCounts.end()) { - throw IrError("runtime JSONL fact_type_counts must be sorted and unique"); - } - const auto target = targetKind(static_cast(record.targetKind)); - if ((target == RuntimeTrainingTargetKind::NumericTruth && - record.targetValue > 1) || - (target == RuntimeTrainingTargetKind::DegreeMilli && - record.targetValue > 1000)) { - throw IrError("runtime JSONL target value is invalid"); - } - if (target == RuntimeTrainingTargetKind::Score && - !std::isfinite(record.targetScore)) - throw IrError("runtime JSONL score target must be finite"); - validateTrainingContract(record); -} - -RuntimeKnowledgePieces -runtimeKnowledgePieces(const VmKnowledgeSnapshot &knowledge, - std::span symbolTable) { - const auto copySymbol = [&](IrSymbolRef symbol) { - const auto pieces = irSymbolPieces(symbolTable, symbol); - return PieceSequence(pieces.begin(), pieces.end()); - }; - RuntimeKnowledgePieces result; - result.factTypes.reserve(knowledge.factTypes.size()); - for (const auto type : knowledge.factTypes) - result.factTypes.push_back(copySymbol(type)); - result.factTypeCounts.reserve(knowledge.factTypeCounts.size()); - for (const auto &[type, count] : knowledge.factTypeCounts) { - result.factTypeCounts.emplace_back(copySymbol(type), count); - } - result.hierarchyEdges.reserve(knowledge.hierarchyEdges.size()); - for (const auto &[child, parent] : knowledge.hierarchyEdges) { - result.hierarchyEdges.emplace_back(copySymbol(child), copySymbol(parent)); - } - std::sort(result.factTypes.begin(), result.factTypes.end()); - std::sort(result.factTypeCounts.begin(), result.factTypeCounts.end()); - std::sort(result.hierarchyEdges.begin(), result.hierarchyEdges.end()); - return result; -} - -void writeRuntimeTrainingDataset( - const std::filesystem::path &path, - std::span records) { - requireJsonlPath(path); - if (records.size() > kMaximumRecords) - throw IrError("runtime dataset has too many records"); - const auto temporary = path.string() + ".tmp"; - std::ofstream output(temporary, std::ios::trunc); - if (!output) - throw IrError("cannot write runtime JSONL dataset"); - for (const auto &record : records) { - verifyRuntimeTrainingRecord(record); - Json inputKinds = Json::array(); - for (const auto kind : record.inputKinds) - inputKinds.push_back(static_cast(kind)); - Json inputValues = Json::array(); - for (const auto &value : record.inputValues) - inputValues.push_back(value); - Json factTypes = Json::array(); - for (const auto &type : record.factTypes) - factTypes.push_back(type); - Json typeCounts = Json::array(); - for (const auto &[type, count] : record.factTypeCounts) - typeCounts.push_back({type, count}); - Json edges = Json::array(); - for (const auto &[child, parent] : record.hierarchyEdges) - edges.push_back({child, parent}); - Json serialized{{"schema_version", kRuntimeTrainingSchemaVersion}, - {"operation_id", record.operationId}, - {"input_kinds", std::move(inputKinds)}, - {"input_values", std::move(inputValues)}, - {"fact_types", std::move(factTypes)}, - {"fact_type_counts", std::move(typeCounts)}, - {"hierarchy_edges", std::move(edges)}, - {"target_kind", - static_cast(record.targetKind)}, - {"target_value", record.targetValue}}; - if (record.targetKind == RuntimeTrainingTargetKind::Score) - serialized["target_score"] = record.targetScore; - output << serialized.dump() << '\n'; - if (!output) - throw IrError("cannot write runtime JSONL dataset"); - } - output.close(); - std::error_code error; - std::filesystem::rename(temporary, path, error); - if (error) { - std::filesystem::remove(path, error); - error.clear(); - std::filesystem::rename(temporary, path, error); - } - if (error) - throw IrError("cannot finalize runtime JSONL dataset"); -} - -std::vector -loadRuntimeTrainingDataset(const std::filesystem::path &path) { - requireJsonlPath(path); - std::ifstream input(path); - if (!input) - throw IrError("cannot read runtime JSONL dataset"); - std::vector records; - std::string line; - std::size_t lineNumber = 0; - while (std::getline(input, line)) { - ++lineNumber; - if (line.empty()) - continue; - try { - const auto object = Json::parse(line); - if (!object.is_object()) - throw IrError("record must be an object"); - if (member(object, "schema_version") != kRuntimeTrainingSchemaVersion) - throw IrError("schema version is incompatible"); - RuntimeTrainingRecord record; - record.operationId = bounded( - member(object, "operation_id"), "operation_id"); - const auto rawInputKinds = ids(object, "input_kinds"); - for (const auto kind : rawInputKinds) - record.inputKinds.push_back(valueKind(kind, "input value kind")); - if (!object.contains("input_values") || - !object.at("input_values").is_array()) - throw IrError("runtime JSONL record requires array input_values"); - for (const auto &encoded : object.at("input_values")) { - if (!encoded.is_array()) - throw IrError("runtime JSONL input value must be an ID array"); - std::vector value; - value.reserve(encoded.size()); - for (const auto &token : encoded) - value.push_back(bounded( - unsignedValue(token, "input_values"), "input_values")); - record.inputValues.push_back(std::move(value)); - } - record.factTypes = pieceSequences(object, "fact_types"); - record.factTypeCounts = factTypeCounts(object); - record.hierarchyEdges = hierarchyEdges(object); - record.targetKind = targetKind(member(object, "target_kind")); - record.targetValue = bounded( - member(object, "target_value"), "target_value"); - if (record.targetKind == RuntimeTrainingTargetKind::Score) { - if (!object.contains("target_score") || - !object.at("target_score").is_number()) - throw IrError("runtime JSONL score record requires target_score"); - record.targetScore = object.at("target_score").get(); - } - verifyRuntimeTrainingRecord(record); - records.push_back(std::move(record)); - if (records.size() > kMaximumRecords) - throw IrError("runtime dataset has too many records"); - } catch (const nlohmann::json::exception &error) { - throw IrError("runtime JSONL line " + std::to_string(lineNumber) + ": " + - error.what()); - } catch (const IrError &error) { - throw IrError("runtime JSONL line " + std::to_string(lineNumber) + ": " + - error.what()); - } - } - if (!input.eof()) - throw IrError("cannot read runtime JSONL dataset"); - return records; -} -} // namespace Felidae diff --git a/src/form/RuntimeTraining.h b/src/form/RuntimeTraining.h deleted file mode 100644 index bc34a6e..0000000 --- a/src/form/RuntimeTraining.h +++ /dev/null @@ -1,103 +0,0 @@ -#pragma once - -#include "RegisterVm.h" - -#include -#include -#include - -namespace Felidae { - -// Structural tokens share the runtime model's input vocabulary with raw -// SentencePiece IDs. Encoded values set the high bit; RuntimeStateModel -// relocates the low marker into the reserved vocabulary tail. Keep this list -// authoritative for both dataset generation and live inference. -inline constexpr std::uint32_t kRuntimeStructuralEncodingBit = 0x80000000u; -enum class RuntimeStructuralToken : std::uint32_t { - FactTypes = 8, - Hierarchy = 9, - Inputs = 10, - FactCounts = 11, - OneFact = 12, - SeveralFacts = 13, - ManyFacts = 14, - InputKindBase = 15, - ValueStart = 26, - ValueEnd = 27, - Nil = 28, - Number = 29, - Degree = 30, - Text = 31, - Symbol = 32, - Array = 33, - Map = 34, - Fact = 35, - TextMap = 37, - NumberBitZero = 38, - NumberBitOne = 39, - Field = 40, -}; - -constexpr std::uint32_t runtimeStructuralToken(RuntimeStructuralToken token) { - return kRuntimeStructuralEncodingBit | - static_cast(token); -} -static_assert(static_cast(RuntimeStructuralToken::Field) < 48, - "runtime structural token exceeds the reserved vocabulary"); - -// Stable semantic actions produced by the finite runtime GRU vocabulary. -// This is deliberately not VmValue::index() or a model-logit index. -enum class RuntimeTrainingTargetKind : std::uint8_t { - InputReference = 1, - FactFromInput = 2, - DegreeMilli = 3, - Nil = 4, - NumericTruth = 5, - Score = 6, -}; - -// One verified runtime operation, represented exactly as the current GRU -// sees it: operation identity, ordered input kinds, and a bounded snapshot of -// fact types plus hierarchy edges. Hidden train-only features are forbidden. -struct RuntimeTrainingRecord { - std::uint16_t operationId = 0; - std::vector inputKinds; - // Canonical value sequences: SentencePiece IDs are stored directly; - // structural markers use the high bit and are relocated to the model's - // reserved tail vocabulary by RuntimeStateModel. - std::vector> inputValues; - std::vector factTypes; - std::vector> factTypeCounts; - std::vector> hierarchyEdges; - RuntimeTrainingTargetKind targetKind = RuntimeTrainingTargetKind::Nil; - std::uint32_t targetValue = 0; - double targetScore = 0.0; -}; - -std::vector -runtimeValueEncoding(const VmValue &value, - std::span symbolTable); - -struct RuntimeKnowledgePieces { - std::vector factTypes; - std::vector> factTypeCounts; - std::vector> hierarchyEdges; -}; - -// Convert module-local runtime symbol references at the single boundary where -// the SSM consumes them. Both live inference and dataset extraction use this -// path, so their model inputs cannot drift apart. -RuntimeKnowledgePieces runtimeKnowledgePieces( - const VmKnowledgeSnapshot& knowledge, - std::span symbolTable); - -// JSON Lines v9: one self-describing record per line. The -// schema value is repeated deliberately: lines can be validated or streamed -// independently and no legacy binary header needs to be retained. -inline constexpr std::uint32_t kRuntimeTrainingSchemaVersion = 9; -void verifyRuntimeTrainingRecord(const RuntimeTrainingRecord& record); -void writeRuntimeTrainingDataset(const std::filesystem::path& path, - std::span records); -std::vector loadRuntimeTrainingDataset(const std::filesystem::path& path); - -} // namespace Felidae diff --git a/src/form/RuntimeTrainingCommand.h b/src/form/RuntimeTrainingCommand.h deleted file mode 100644 index ffa94a5..0000000 --- a/src/form/RuntimeTrainingCommand.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -namespace Felidae { - -// Runs the existing C++/LibTorch runtime trainer. The VM CLI owns its public -// option parsing so no auxiliary trainer executable is needed. -int runRuntimeGruTraining(int argc, char** argv); - -} // namespace Felidae diff --git a/src/form/SemanticOperation.h b/src/form/SemanticOperation.h deleted file mode 100644 index c6def6f..0000000 --- a/src/form/SemanticOperation.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace Felidae { - -// Permanent semantic ABI namespace shared by compiler output and executable IR. -enum class SemanticOperationId : std::uint16_t { - Identity = 0x0001, - SelectFact = 0x0002, - DeriveFact = 0x0003, - EvaluateDegree = 0x0004, - // Explicit application-facing scoring hook. Unlike EvaluateDegree, its - // result is an ordinary finite double and is never clamped to [0, 1]. - Suggest = 0x0005, -}; - -inline bool isKnownSemanticOperation(std::uint16_t operation) noexcept { - switch (static_cast(operation)) { - case SemanticOperationId::Identity: - case SemanticOperationId::SelectFact: - case SemanticOperationId::DeriveFact: - case SemanticOperationId::EvaluateDegree: - case SemanticOperationId::Suggest: - return true; - } - return false; -} - -inline bool semanticOperationAcceptsArity(std::uint16_t operation, - std::size_t inputCount) noexcept { - return isKnownSemanticOperation(operation) && inputCount == 1; -} - -inline std::optional -semanticOperationForName(std::string_view name) noexcept { - if (name == "semantic_identity") - return SemanticOperationId::Identity; - if (name == "semantic_select_fact") - return SemanticOperationId::SelectFact; - if (name == "semantic_derive_fact") - return SemanticOperationId::DeriveFact; - if (name == "semantic_evaluate_degree") - return SemanticOperationId::EvaluateDegree; - if (name == "ssm.suggest" || name == "ssm:suggest") - return SemanticOperationId::Suggest; - return std::nullopt; -} - -} // namespace Felidae diff --git a/src/form/TensorOperation.h b/src/form/TensorOperation.h deleted file mode 100644 index 6890e66..0000000 --- a/src/form/TensorOperation.h +++ /dev/null @@ -1,126 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace Felidae { - -// Operations executed by the optional platform tensor backend. Supported -// desktop builds provide the backend through LibTorch; RegisterVm retains one -// instruction format. Tensor operations accept numeric scalars, rectangular -// numeric arrays, or an existing tensor; symbolic facts retain fact semantics. -enum class TensorOperation : std::uint8_t { - Size = 0, - Shape, - Dimensions, - Sigmoid, - Relu, - Dot, - MeanSquaredError, - Difference, - CosineSimilarity, - Transpose, - IsSymmetric, - Clone, - Count -}; - -constexpr std::size_t tensorOperationArity(TensorOperation operation) { - switch (operation) { - case TensorOperation::Size: - case TensorOperation::Shape: - case TensorOperation::Dimensions: - case TensorOperation::Sigmoid: - case TensorOperation::Relu: - case TensorOperation::Transpose: - case TensorOperation::IsSymmetric: - case TensorOperation::Clone: - return 1; - case TensorOperation::Dot: - case TensorOperation::MeanSquaredError: - case TensorOperation::Difference: - case TensorOperation::CosineSimilarity: - return 2; - case TensorOperation::Count: - return 0; - } - return 0; -} - -inline std::optional -tensorOperationArgumentIndex(TensorOperation operation, std::string_view name) { - if (operation == TensorOperation::Dot || - operation == TensorOperation::MeanSquaredError || - operation == TensorOperation::Difference || - operation == TensorOperation::CosineSimilarity) { - if (name == "left") - return 0; - if (name == "right") - return 1; - return std::nullopt; - } - return name == "value" ? std::optional{0} : std::nullopt; -} - -inline std::optional -tensorOperationForName(std::string_view name) { - if (name == "tensor:size") - return TensorOperation::Size; - if (name == "tensor:shape") - return TensorOperation::Shape; - if (name == "tensor:dimensions") - return TensorOperation::Dimensions; - if (name == "ml:sigmoid") - return TensorOperation::Sigmoid; - if (name == "ml:relu") - return TensorOperation::Relu; - if (name == "ml:dot") - return TensorOperation::Dot; - if (name == "ml:meanSquaredError") - return TensorOperation::MeanSquaredError; - if (name == "tensor:difference") - return TensorOperation::Difference; - if (name == "tensor:cosineSimilarity") - return TensorOperation::CosineSimilarity; - if (name == "tensor:transpose") - return TensorOperation::Transpose; - if (name == "tensor:isSymmetric") - return TensorOperation::IsSymmetric; - if (name == "tensor:clone") - return TensorOperation::Clone; - return std::nullopt; -} - -// Returns each source argument's canonical operand position. Empty names mean -// a positional call; named and positional arguments cannot be mixed. This is -// the single argument-shape contract shared by eligibility checks and IR -// emission. -inline std::optional> -tensorOperationArgumentOrder(TensorOperation operation, - std::span names) { - const auto arity = tensorOperationArity(operation); - if (names.size() != arity) - return std::nullopt; - const bool named = !names.empty() && !names.front().empty(); - std::vector order; - order.reserve(arity); - std::vector seen(arity); - for (std::size_t index = 0; index < arity; ++index) { - if (named != !names[index].empty()) - return std::nullopt; - const auto target = - named ? tensorOperationArgumentIndex(operation, names[index]) - : std::optional{index}; - if (!target || *target >= arity || seen[*target]) - return std::nullopt; - seen[*target] = true; - order.push_back(*target); - } - return order; -} - -} // namespace Felidae diff --git a/src/form/libs/Builtin.cpp b/src/form/libs/Builtin.cpp deleted file mode 100644 index 6ff12ba..0000000 --- a/src/form/libs/Builtin.cpp +++ /dev/null @@ -1,565 +0,0 @@ -#include "Builtin.h" - -#include "Csv.h" -#include "Group.h" -#include "Json.h" -#include "Set.h" -#include "form/IrModule.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae::Form { -namespace { - -std::string decodeText(std::span pieces, - const BuiltinTextCodec &codec) { - if (!codec.decode) - throw IrError("VM builtin text decoder service is absent"); - return codec.decode(pieces); -} - -PieceSequence encodeText(std::string_view text, const BuiltinTextCodec &codec) { - if (!codec.encode) - throw IrError("VM builtin text encoder service is absent"); - return codec.encode(text); -} - -std::string textValue(const VmValue &value, const BuiltinTextCodec &codec, - std::string_view operation) { - const auto text = std::get_if(&value); - if (!text) - throw IrError(std::string(operation) + " requires text input"); - return decodeText(text->pieces, codec); -} - -double numberValue(const VmValue &value, std::string_view operation) { - const auto number = std::get_if(&value); - if (!number || !std::isfinite(*number)) - throw IrError(std::string(operation) + " requires a finite number"); - return *number; -} - -std::string asciiCase(std::string text, bool upper) { - std::transform(text.begin(), text.end(), text.begin(), [upper](char byte) { - const auto value = static_cast(byte); - return static_cast(upper ? std::toupper(value) : std::tolower(value)); - }); - return text; -} - -double textLength(std::string_view text) { - return static_cast( - std::count_if(text.begin(), text.end(), [](char byte) { - return (static_cast(byte) & 0xc0U) != 0x80U; - })); -} - -} // namespace - -Json::Value vmValueToJson(const VmValue &value, - std::span symbolTable, - const BuiltinTextCodec &codec) { - if (std::holds_alternative(value)) - return nullptr; - if (const auto number = std::get_if(&value)) - return *number; - if (const auto degree = std::get_if(&value)) - return degree->value; - if (const auto text = std::get_if(&value)) - return decodeText(text->pieces, codec); - if (const auto symbol = std::get_if(&value)) - return decodeText(irSymbolPieces(symbolTable, symbol->value), codec); - if (const auto array = std::get_if(&value); array && *array) { - auto result = Json::Value::array(); - for (const auto &item : (*array)->values) - result.push_back(vmValueToJson(item, symbolTable, codec)); - return result; - } - if (const auto map = std::get_if(&value); map && *map) { - auto result = Json::Value::object(); - for (const auto &[key, item] : (*map)->entries) - result[decodeText(key, codec)] = - vmValueToJson(item, symbolTable, codec); - return result; - } - if (const auto map = std::get_if(&value); map && *map) { - auto result = Json::Value::object(); - for (const auto &[key, item] : (*map)->entries) - result[decodeText(irSymbolPieces(symbolTable, key), codec)] = - vmValueToJson(item, symbolTable, codec); - return result; - } - if (const auto fact = std::get_if(&value); fact && *fact) { - auto result = Json::Value::object(); - result["__type"] = - decodeText(irSymbolPieces(symbolTable, (*fact)->type), codec); - for (const auto &[key, item] : (*fact)->fields) - result[decodeText(irSymbolPieces(symbolTable, key), codec)] = - vmValueToJson(item, symbolTable, codec); - return result; - } - throw IrError("VM builtin cannot convert this value to JSON"); -} - -VmValue jsonToVmValue(const Json::Value &value, - const BuiltinTextCodec &codec) { - if (value.is_null()) - return VmNil{}; - if (value.is_boolean()) - return value.get() ? 1.0 : 0.0; - if (value.is_number()) { - const auto number = value.get(); - if (!std::isfinite(number)) - throw IrError("JSON numeric value must be finite"); - return number; - } - if (value.is_string()) { - return VmText{encodeText(value.get_ref(), codec)}; - } - if (value.is_array()) { - auto result = std::make_shared(); - result->values.reserve(value.size()); - for (const auto &item : value) - result->values.push_back(jsonToVmValue(item, codec)); - return result; - } - if (value.is_object()) { - auto result = std::make_shared(); - result->entries.reserve(value.size()); - for (const auto &[key, item] : value.items()) - result->entries.emplace_back(encodeText(key, codec), - jsonToVmValue(item, codec)); - return result; - } - throw IrError("JSON contains an unsupported value kind"); -} - -VmValue evaluateBuiltin(BuiltinId operation, std::span inputs, - std::span symbolTable, - const BuiltinTextCodec &codec) { - const auto arity = builtinOperationArity(operation); - if (!arity || inputs.size() != *arity) - throw IrError("VM builtin operation has an invalid ID or arity"); - try { - switch (operation) { - case BuiltinId::ArrayGet: { - const auto array = std::get_if(&inputs[0]); - const auto position = std::get_if(&inputs[1]); - if (!array || !*array || !position || !std::isfinite(*position) || - *position < 0.0 || std::trunc(*position) != *position || - *position >= static_cast((*array)->values.size())) { - throw IrError("array.get requires a valid array position"); - } - return (*array)->values[static_cast(*position)]; - } - case BuiltinId::ArrayPush: { - const auto array = std::get_if(&inputs[0]); - if (!array || !*array) - throw IrError("array.push requires an array"); - auto result = std::make_shared(); - result->values = (*array)->values; - result->values.push_back(inputs[1]); - return result; - } - case BuiltinId::Count: - case BuiltinId::ArrayLen: { - const auto array = std::get_if(&inputs[0]); - if (!array || !*array) - throw IrError("array length requires an array"); - return static_cast((*array)->values.size()); - } - case BuiltinId::ArrayLimit: { - const auto array = std::get_if(&inputs[0]); - const auto records = std::get_if(&inputs[1]); - if (!array || !*array) - throw IrError("limit requires an array query result"); - if (!records || !std::isfinite(*records) || *records < 0.0 || - std::trunc(*records) != *records) - throw IrError("limit records must be a finite non-negative integer"); - auto result = std::make_shared(); - // Clamp in floating-point space before converting to size_t. This - // avoids an out-of-range conversion for a very large but finite N, - // while preserving SQL LIMIT semantics: asking for more rows than are - // present simply returns the complete, stably ordered result. - const auto count = *records >= static_cast((*array)->values.size()) - ? (*array)->values.size() - : static_cast(*records); - result->values.assign((*array)->values.begin(), - (*array)->values.begin() + count); - return result; - } - case BuiltinId::Sum: - case BuiltinId::Average: - case BuiltinId::Min: - case BuiltinId::Max: { - const auto array = std::get_if(&inputs[0]); - if (!array || !*array) - throw IrError("numeric aggregation requires an array"); - if ((*array)->values.empty()) { - if (operation == BuiltinId::Sum) - return 0.0; - throw IrError("numeric aggregation requires at least one value"); - } - std::vector values; - values.reserve((*array)->values.size()); - for (const auto &item : (*array)->values) { - const auto number = std::get_if(&item); - if (!number || !std::isfinite(*number)) - throw IrError("numeric aggregation requires finite numbers"); - values.push_back(*number); - } - if (operation == BuiltinId::Sum || operation == BuiltinId::Average) { - const auto total = std::accumulate(values.begin(), values.end(), 0.0); - return operation == BuiltinId::Sum - ? total - : total / static_cast(values.size()); - } - const auto bounds = std::minmax_element(values.begin(), values.end()); - return operation == BuiltinId::Min ? *bounds.first : *bounds.second; - } - case BuiltinId::Sort: { - // Registered in BuiltinRegistry and documented in core/prelude.fx - // ("sort(array)") since the start, but had no arity entry and no case - // here -- every call compiled to "not yet lowered to IR". Numeric-only, - // ascending, matching the sibling aggregations (sum/min/max) it sits - // beside in both places. - const auto array = std::get_if(&inputs[0]); - if (!array || !*array) - throw IrError("sort requires an array"); - std::vector values; - values.reserve((*array)->values.size()); - for (const auto &item : (*array)->values) { - const auto number = std::get_if(&item); - if (!number || !std::isfinite(*number)) - throw IrError("sort requires an array of finite numbers"); - values.push_back(*number); - } - std::sort(values.begin(), values.end()); - auto result = std::make_shared(); - result->values.reserve(values.size()); - for (const auto value : values) - result->values.emplace_back(value); - return result; - } - case BuiltinId::Length: - if (const auto text = std::get_if(&inputs[0])) - return textLength(decodeText(text->pieces, codec)); - else if (const auto array = std::get_if(&inputs[0]); - array && *array) - return static_cast((*array)->values.size()); - throw IrError("length requires text or an array"); - case BuiltinId::StrLen: - return textLength(textValue(inputs[0], codec, "str.len")); - case BuiltinId::Lower: - case BuiltinId::StrLower: - return VmText{encodeText( - asciiCase(textValue(inputs[0], codec, "lower"), false), codec)}; - case BuiltinId::Upper: - case BuiltinId::StrUpper: - return VmText{encodeText( - asciiCase(textValue(inputs[0], codec, "upper"), true), codec)}; - case BuiltinId::Contains: - if (const auto text = std::get_if(&inputs[0])) { - const auto data = decodeText(text->pieces, codec); - const auto query = textValue(inputs[1], codec, "contains"); - return data.find(query) == std::string::npos ? 0.0 : 1.0; - } else if (const auto array = std::get_if(&inputs[0]); - array && *array) { - return std::any_of((*array)->values.begin(), (*array)->values.end(), - [&](const VmValue &item) { - return vmValuesEqual(item, inputs[1]); - }) - ? 1.0 - : 0.0; - } - throw IrError("contains requires text or an array"); - case BuiltinId::Search: { - const auto array = std::get_if(&inputs[0]); - if (!array || !*array) - throw IrError("search requires an array of text"); - const auto query = textValue(inputs[1], codec, "search"); - auto result = std::make_shared(); - for (const auto &item : (*array)->values) { - const auto text = std::get_if(&item); - if (!text) - throw IrError("search requires an array of text"); - if (decodeText(text->pieces, codec).find(query) != std::string::npos) - result->values.push_back(item); - } - return result; - } - case BuiltinId::StrContains: { - const auto data = textValue(inputs[0], codec, "str.contains"); - const auto needle = textValue(inputs[1], codec, "str.contains"); - return data.find(needle) == std::string::npos ? 0.0 : 1.0; - } - case BuiltinId::StrConcat: - return VmText{encodeText(textValue(inputs[0], codec, "str.concat") + - textValue(inputs[1], codec, "str.concat"), - codec)}; - case BuiltinId::StrJoin: { - const auto array = std::get_if(&inputs[0]); - if (!array || !*array) - throw IrError("str.join requires an array of text"); - const auto delimiter = textValue(inputs[1], codec, "str.join"); - std::string result; - for (std::size_t index = 0; index < (*array)->values.size(); ++index) { - if (index != 0) - result += delimiter; - result += textValue((*array)->values[index], codec, "str.join"); - } - return VmText{encodeText(result, codec)}; - } - case BuiltinId::StrTrim: { - auto text = textValue(inputs[0], codec, "str.trim"); - const auto whitespace = [](char byte) { - return std::isspace(static_cast(byte)) != 0; - }; - const auto first = std::find_if_not(text.begin(), text.end(), whitespace); - const auto last = - std::find_if_not(text.rbegin(), text.rend(), whitespace).base(); - return VmText{encodeText(first < last ? std::string(first, last) - : std::string{}, - codec)}; - } - case BuiltinId::StrSplit: { - const auto data = textValue(inputs[0], codec, "str.split"); - const auto delimiter = textValue(inputs[1], codec, "str.split"); - if (delimiter.empty()) - throw IrError("str.split delimiter must not be empty"); - auto result = std::make_shared(); - std::size_t begin = 0; - for (;;) { - const auto end = data.find(delimiter, begin); - result->values.emplace_back( - VmText{encodeText(data.substr(begin, end - begin), codec)}); - if (end == std::string::npos) - break; - begin = end + delimiter.size(); - } - return result; - } - case BuiltinId::StrReplace: { - auto data = textValue(inputs[0], codec, "str.replace"); - const auto search = textValue(inputs[1], codec, "str.replace"); - const auto replacement = textValue(inputs[2], codec, "str.replace"); - if (search.empty()) - throw IrError("str.replace search must not be empty"); - std::size_t position = 0; - while ((position = data.find(search, position)) != std::string::npos) { - data.replace(position, search.size(), replacement); - position += replacement.size(); - } - return VmText{encodeText(data, codec)}; - } - case BuiltinId::StrStartsWith: - case BuiltinId::StrEndsWith: { - const auto data = textValue(inputs[0], codec, "string boundary check"); - const auto part = textValue(inputs[1], codec, "string boundary check"); - return (operation == BuiltinId::StrStartsWith ? data.starts_with(part) - : data.ends_with(part)) - ? 1.0 - : 0.0; - } - case BuiltinId::JsonParse: - return jsonToVmValue( - Json::parse(textValue(inputs[0], codec, "json.parse")), codec); - case BuiltinId::JsonGet: { - const auto data = vmValueToJson(inputs[0], symbolTable, codec); - return jsonToVmValue( - Json::get(data, textValue(inputs[1], codec, "json.get")), codec); - } - case BuiltinId::JsonHas: { - const auto data = vmValueToJson(inputs[0], symbolTable, codec); - return Json::has(data, textValue(inputs[1], codec, "json.has")) ? 1.0 - : 0.0; - } - case BuiltinId::JsonKeys: { - auto result = std::make_shared(); - for (const auto &key : - Json::keys(vmValueToJson(inputs[0], symbolTable, codec))) - result->values.emplace_back(VmText{encodeText(key, codec)}); - return result; - } - case BuiltinId::JsonSet: - return jsonToVmValue( - Json::set(vmValueToJson(inputs[0], symbolTable, codec), - textValue(inputs[1], codec, "json.set"), - vmValueToJson(inputs[2], symbolTable, codec)), - codec); - case BuiltinId::JsonRemove: - return jsonToVmValue( - Json::remove(vmValueToJson(inputs[0], symbolTable, codec), - textValue(inputs[1], codec, "json.remove")), - codec); - case BuiltinId::JsonToText: - return VmText{encodeText( - Json::toText(vmValueToJson(inputs[0], symbolTable, codec)), codec)}; - case BuiltinId::CsvParse: - return jsonToVmValue( - Csv::parse(textValue(inputs[0], codec, "csv.parse")), codec); - case BuiltinId::CsvToFacts: - throw IrError("csv.toFacts requires the VM fact service"); - case BuiltinId::CsvToText: - return VmText{encodeText( - Csv::toText(vmValueToJson(inputs[0], symbolTable, codec)), codec)}; - case BuiltinId::CsvToFelidaeFacts: - return VmText{ - encodeText(Csv::toFelidaeFacts( - vmValueToJson(inputs[0], symbolTable, codec), - textValue(inputs[1], codec, "csv.toFelidaeFacts")), - codec)}; - case BuiltinId::GroupClosed: - case BuiltinId::GroupAssociative: - case BuiltinId::GroupCommutative: - return jsonToVmValue( - Group::evaluate(operation, - vmValueToJson(inputs[0], symbolTable, codec), - vmValueToJson(inputs[1], symbolTable, codec), - std::nullopt), - codec); - case BuiltinId::GroupValidate: - case BuiltinId::GroupIdentity: - case BuiltinId::GroupInverse: - case BuiltinId::GroupAbelian: - return jsonToVmValue( - Group::evaluate(operation, - vmValueToJson(inputs[0], symbolTable, codec), - vmValueToJson(inputs[1], symbolTable, codec), - vmValueToJson(inputs[2], symbolTable, codec)), - codec); - case BuiltinId::SetUnion: - case BuiltinId::SetIntersection: - case BuiltinId::SetDifference: - case BuiltinId::SetSymmetricDifference: - case BuiltinId::SetEquals: - case BuiltinId::SetSubset: - case BuiltinId::SetSuperset: - case BuiltinId::SetDisjoint: - return jsonToVmValue( - Set::evaluate(operation, - vmValueToJson(inputs[0], symbolTable, codec)), - codec); - case BuiltinId::SetCardinality: - return jsonToVmValue( - Set::evaluate(operation, - Json::Value::array({vmValueToJson( - inputs[0], symbolTable, codec)})), - codec); - case BuiltinId::SetIntersectionBy: - case BuiltinId::SetDifferenceBy: - case BuiltinId::SetSymmetricDifferenceBy: - case BuiltinId::SetEqualsBy: - case BuiltinId::SetSubsetBy: - case BuiltinId::SetDisjointBy: - return jsonToVmValue( - Set::evaluate(operation, - vmValueToJson(inputs[0], symbolTable, codec), - std::nullopt, - vmValueToJson(inputs[1], symbolTable, codec)), - codec); - case BuiltinId::SetContains: - return jsonToVmValue( - Set::evaluate(operation, - Json::Value::array({vmValueToJson( - inputs[0], symbolTable, codec)}), - vmValueToJson(inputs[1], symbolTable, codec)), - codec); - case BuiltinId::SetContainsBy: - return jsonToVmValue( - Set::evaluate(operation, - Json::Value::array({vmValueToJson( - inputs[0], symbolTable, codec)}), - vmValueToJson(inputs[1], symbolTable, codec), - vmValueToJson(inputs[2], symbolTable, codec)), - codec); - // math.* were registered in BuiltinRegistry (and declared in - // core/math.fx) with no arity entry and no case here at all -- every - // call compiled to "not yet lowered to IR", the same dead-registration - // pattern as the earlier sort/throw fixes this session. - case BuiltinId::MathPi: - return std::numbers::pi; - case BuiltinId::MathE: - return std::numbers::e; - case BuiltinId::MathRandom: { - const auto minimum = numberValue(inputs[0], "math.random"); - const auto maximum = numberValue(inputs[1], "math.random"); - if (minimum > maximum) - throw IrError("math.random requires min <= max"); - thread_local std::mt19937 generator{std::random_device{}()}; - std::uniform_real_distribution distribution(minimum, maximum); - return distribution(generator); - } - case BuiltinId::MathPow: - return std::pow(numberValue(inputs[0], "math.pow"), - numberValue(inputs[1], "math.pow")); - case BuiltinId::MathAtan2: - return std::atan2(numberValue(inputs[0], "math.atan2"), - numberValue(inputs[1], "math.atan2")); - case BuiltinId::MathSqrt: { - const auto value = numberValue(inputs[0], "math.sqrt"); - if (value < 0.0) - throw IrError("math.sqrt requires a non-negative number"); - return std::sqrt(value); - } - case BuiltinId::MathSin: - return std::sin(numberValue(inputs[0], "math.sin")); - case BuiltinId::MathCos: - return std::cos(numberValue(inputs[0], "math.cos")); - case BuiltinId::MathTan: - return std::tan(numberValue(inputs[0], "math.tan")); - case BuiltinId::MathAsin: - return std::asin(numberValue(inputs[0], "math.asin")); - case BuiltinId::MathAcos: - return std::acos(numberValue(inputs[0], "math.acos")); - case BuiltinId::MathAtan: - return std::atan(numberValue(inputs[0], "math.atan")); - case BuiltinId::MathLog: { - const auto value = numberValue(inputs[0], "math.log"); - if (value <= 0.0) - throw IrError("math.log requires a positive number"); - return std::log(value); - } - case BuiltinId::MathLog10: { - const auto value = numberValue(inputs[0], "math.log10"); - if (value <= 0.0) - throw IrError("math.log10 requires a positive number"); - return std::log10(value); - } - case BuiltinId::MathExp: - return std::exp(numberValue(inputs[0], "math.exp")); - case BuiltinId::MathAbs: - return std::fabs(numberValue(inputs[0], "math.abs")); - case BuiltinId::MathFloor: - return std::floor(numberValue(inputs[0], "math.floor")); - case BuiltinId::MathCeil: - return std::ceil(numberValue(inputs[0], "math.ceil")); - case BuiltinId::MathRound: - return std::round(numberValue(inputs[0], "math.round")); - case BuiltinId::WhereGuardFailed: - // Compiler-synthesized only: the implicit else branch of a - // where-guarded clause with no explicit `else` (see - // desugarWhereGuardedClauses in IrCodeGenerator.cpp). Reaching this - // means every guard in the clause failed and there was nothing else - // to fall back to -- a clear runtime failure, not a silent nil. - throw IrError( - "where guard failed: no matching clause and no else branch"); - default: - break; - } - } catch (const IrError &) { - throw; - } catch (const std::exception &error) { - throw IrError(error.what()); - } - throw IrError("VM builtin operation is not implemented"); -} - -} // namespace Felidae::Form diff --git a/src/form/libs/Builtin.h b/src/form/libs/Builtin.h deleted file mode 100644 index 0471802..0000000 --- a/src/form/libs/Builtin.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "form/BuiltinOperation.h" -#include "form/RegisterVm.h" -#include "Json.h" - -namespace Felidae::Form { - -struct BuiltinTextCodec { - VmTextDecoder decode; - std::function encode; -}; - -Json::Value vmValueToJson(const VmValue &value, - std::span symbolTable, - const BuiltinTextCodec &text); -VmValue jsonToVmValue(const Json::Value &value, - const BuiltinTextCodec &text); - -VmValue evaluateBuiltin(BuiltinId operation, std::span inputs, - std::span symbolTable, - const BuiltinTextCodec &text); - -} // namespace Felidae::Form diff --git a/src/form/libs/Csv.cpp b/src/form/libs/Csv.cpp deleted file mode 100644 index 5f9bee0..0000000 --- a/src/form/libs/Csv.cpp +++ /dev/null @@ -1,226 +0,0 @@ -#include "Csv.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae::Form::Csv { -namespace { - -// Scans the whole input in one pass rather than splitting on newlines -// first: RFC4180 allows a quoted field to contain literal CR/LF bytes, so a -// newline can only be trusted as a row separator once it is known not to be -// inside an open quote. Reading line-by-line (the previous implementation) -// cannot make that distinction and misparses any field with an embedded -// newline as "unterminated". A record here is "empty" only when it has no -// fields at all (the position right after a preceding row terminator with -// nothing following); a single empty *field* -- one comma with nothing -// between it and the next comma/newline -- always counts as real content, -// matching the blank-line-vs-single-empty-column distinction the caller -// still needs to make. -std::vector> splitCsvRows(std::string_view text) { - std::vector> rows; - std::vector row; - std::string field; - bool quoted = false; - bool rowHasContent = false; - const auto endField = [&] { - row.push_back(std::move(field)); - field.clear(); - rowHasContent = true; - }; - const auto endRow = [&] { - rows.push_back(std::move(row)); - row.clear(); - rowHasContent = false; - }; - for (std::size_t index = 0; index < text.size(); ++index) { - const char current = text[index]; - if (quoted) { - if (current == '"') { - if (index + 1 < text.size() && text[index + 1] == '"') { - field.push_back('"'); - ++index; - } else { - quoted = false; - } - } else { - field.push_back(current); - } - continue; - } - // A quote only opens quoted mode as the first character of a field - // (RFC4180): a stray quote appearing mid-unquoted-field is literal - // text, not a toggle, and must not swallow a later comma. - if (current == '"' && field.empty()) { - quoted = true; - } else if (current == ',') { - endField(); - } else if (current == '\r') { - if (index + 1 < text.size() && text[index + 1] == '\n') - continue; - endField(); - endRow(); - } else if (current == '\n') { - endField(); - endRow(); - } else { - field.push_back(current); - } - } - if (quoted) - throw std::runtime_error("csv.parse found an unterminated quoted field"); - if (!field.empty() || rowHasContent) { - endField(); - endRow(); - } - return rows; -} - -Json::Value parseRows(std::string_view text, - std::optional typeName) { - Json::Value result = Json::Value::array(); - const auto rows = splitCsvRows(text); - if (rows.empty()) - return result; - const auto &headers = rows.front(); - for (std::size_t rowIndex = 1; rowIndex < rows.size(); ++rowIndex) { - const auto &fields = rows[rowIndex]; - // A blank line is ambiguous for multi-column data (most commonly a - // harmless trailing blank line at end of file, so it's skipped), but for - // single-column data it's the only way to represent an intentional - // empty-string value and must become a real row, not be silently - // dropped. - if (fields.size() == 1 && fields.front().empty() && headers.size() != 1) - continue; - if (fields.size() != headers.size()) - throw std::runtime_error( - "csv.parse row has a different field count than the header"); - Json::Value row = Json::Value::object(); - if (typeName && !typeName->empty()) - row["__type"] = *typeName; - for (std::size_t index = 0; index < headers.size(); ++index) - row[headers[index]] = fields[index]; - result.push_back(std::move(row)); - } - return result; -} - -std::string scalarText(const Json::Value &value) { - return value.is_string() ? value.get() : value.dump(); -} - -std::string quote(std::string_view text) { - if (text.find_first_of(",\"\r\n") == std::string_view::npos) - return std::string(text); - std::string result{"\""}; - for (const char current : text) - result += current == '"' ? "\"\"" : std::string(1, current); - result.push_back('"'); - return result; -} - -std::vector headers(const Json::Value &rows) { - if (!rows.is_array()) - throw std::runtime_error("csv operation expects an array of rows"); - if (rows.empty()) - return {}; - if (!rows.front().is_object()) - throw std::runtime_error("csv operation expects object rows"); - std::vector result; - result.reserve(rows.front().size()); - for (const auto &[key, _] : rows.front().items()) - if (key != "__type") - result.push_back(key); - return result; -} - -} // namespace - -Json::Value parse(std::string_view text) { return parseRows(text, std::nullopt); } - -Json::Value toFacts(std::string_view text, std::string_view typeName) { - if (typeName.empty()) - throw std::runtime_error("csv.toFacts requires a non-empty fact type"); - auto rows = parseRows(text, typeName); - for (auto &row : rows) { - for (auto &[name, value] : row.items()) { - if (name == "__type" || !value.is_string()) - continue; - const auto &cell = value.get_ref(); - if (cell.empty() || - (cell.size() > 1 && cell.front() == '0' && - std::isdigit(static_cast(cell[1])))) - continue; - double number = 0.0; - const auto parsed = - std::from_chars(cell.data(), cell.data() + cell.size(), number); - if (parsed.ec == std::errc{} && parsed.ptr == cell.data() + cell.size() && - std::isfinite(number)) { - value = number; - } - } - } - return rows; -} - -std::string toText(const Json::Value &rows, - std::span columns) { - if (!rows.is_array()) - throw std::runtime_error("csv.toText expects an array of rows"); - std::ostringstream output; - for (std::size_t index = 0; index < columns.size(); ++index) { - if (index) - output << ','; - output << quote(columns[index]); - } - output << '\n'; - for (const auto &row : rows) { - if (!row.is_object()) - throw std::runtime_error("csv.toText expects object rows"); - for (std::size_t index = 0; index < columns.size(); ++index) { - if (index) - output << ','; - const auto found = row.find(columns[index]); - if (found != row.end()) - output << quote(scalarText(*found)); - } - output << '\n'; - } - return output.str(); -} - -std::string toText(const Json::Value &rows) { - if (rows.is_array() && rows.empty()) - return {}; - return toText(rows, headers(rows)); -} - -std::string toFelidaeFacts(const Json::Value &rows, std::string_view typeName) { - if (typeName.empty()) - throw std::runtime_error( - "csv.toFelidaeFacts requires a non-empty fact type"); - const auto columns = headers(rows); - std::ostringstream output; - for (const auto &row : rows) { - if (!row.is_object()) - throw std::runtime_error("csv.toFelidaeFacts expects object rows"); - output << typeName << '('; - for (std::size_t index = 0; index < columns.size(); ++index) { - if (index) - output << ", "; - const auto found = row.find(columns[index]); - output << columns[index] << ": " - << (found == row.end() ? "nil" : found->dump()); - } - output << ")\n"; - } - return output.str(); -} - -} // namespace Felidae::Form::Csv diff --git a/src/form/libs/Csv.h b/src/form/libs/Csv.h deleted file mode 100644 index 7916fbe..0000000 --- a/src/form/libs/Csv.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "Json.h" - -#include -#include -#include - -namespace Felidae::Form::Csv { - -Json::Value parse(std::string_view text); -Json::Value toFacts(std::string_view text, std::string_view typeName); -std::string toText(const Json::Value &rows); -std::string toText(const Json::Value &rows, - std::span columns); -std::string toFelidaeFacts(const Json::Value &rows, std::string_view typeName); - -} // namespace Felidae::Form::Csv diff --git a/src/form/libs/Db.cpp b/src/form/libs/Db.cpp deleted file mode 100644 index b17d137..0000000 --- a/src/form/libs/Db.cpp +++ /dev/null @@ -1,327 +0,0 @@ -#include "Db.h" - -#include "Builtin.h" -#include "Csv.h" -#include "Json.h" -#include "form/IrModule.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#define NOMINMAX -#include -#else -#include -#include -#include -#endif - -namespace Felidae::Form::Db { -namespace { - -std::mutex databaseMutex; - -class DatabaseFileLock { -public: - explicit DatabaseFileLock(const std::filesystem::path &database) { - auto lockPath = database; - lockPath += ".lock"; - if (lockPath.has_parent_path()) - std::filesystem::create_directories(lockPath.parent_path()); -#ifdef _WIN32 - handle_ = CreateFileW(lockPath.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, - 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, - nullptr); - if (handle_ == INVALID_HANDLE_VALUE) - throw IrError("fact database is busy: " + database.string()); -#else - descriptor_ = ::open(lockPath.c_str(), O_CREAT | O_RDWR, 0666); - if (descriptor_ < 0 || flock(descriptor_, LOCK_EX | LOCK_NB) != 0) { - if (descriptor_ >= 0) - ::close(descriptor_); - descriptor_ = -1; - throw IrError("fact database is busy: " + database.string()); - } -#endif - } - - ~DatabaseFileLock() { -#ifdef _WIN32 - if (handle_ != INVALID_HANDLE_VALUE) - CloseHandle(handle_); -#else - if (descriptor_ >= 0) { - flock(descriptor_, LOCK_UN); - ::close(descriptor_); - } -#endif - } - - DatabaseFileLock(const DatabaseFileLock &) = delete; - DatabaseFileLock &operator=(const DatabaseFileLock &) = delete; - -private: -#ifdef _WIN32 - HANDLE handle_ = INVALID_HANDLE_VALUE; -#else - int descriptor_ = -1; -#endif -}; - -std::string numberText(double value) { - if (!std::isfinite(value)) - throw IrError("fact database cannot serialize a non-finite number"); - std::ostringstream output; - output << std::setprecision(std::numeric_limits::max_digits10) - << value; - auto text = output.str(); - if (text.find_first_of(".eE") == std::string::npos) - text += ".0"; - return text; -} - -std::string indentation(std::size_t width) { return std::string(width, ' '); } - -std::string sourceName(std::string value) { - if (value.empty() || - !(std::isalpha(static_cast(value.front())) || - value.front() == '_') || - !std::all_of(value.begin() + 1, value.end(), [](unsigned char byte) { - return std::isalnum(byte) || byte == '_'; - })) { - throw IrError("fact database symbol cannot be written as a source name"); - } - return value; -} - -std::string valueText(const VmValue &value, - std::span symbolTable, - const VmTextDecoder &decodeText, std::size_t indent, - std::size_t depth); - -template -std::string mapText(const Entries &entries, KeyText keyText, - std::span symbolTable, - const VmTextDecoder &decodeText, std::size_t indent, - std::size_t depth) { - if (entries.empty()) - return "{}"; - std::ostringstream output; - output << "{\n"; - for (std::size_t index = 0; index < entries.size(); ++index) { - output << indentation(indent + 4) << keyText(entries[index].first) << ": " - << valueText(entries[index].second, symbolTable, decodeText, - indent + 4, depth + 1); - if (index + 1 < entries.size()) - output << ','; - output << '\n'; - } - output << indentation(indent) << '}'; - return output.str(); -} - -std::string factText(const VmFact &fact, - std::span symbolTable, - const VmTextDecoder &decodeText, std::size_t indent, - std::size_t depth, - std::span parents = {}) { - const auto type = - sourceName(decodeText(irSymbolPieces(symbolTable, fact.type))); - std::ostringstream output; - output << type; - if (!parents.empty()) { - output << " extend "; - for (std::size_t index = 0; index < parents.size(); ++index) { - if (index != 0) - output << ", "; - output << sourceName( - decodeText(irSymbolPieces(symbolTable, parents[index]))); - } - } - output << '('; - if (!fact.fields.empty()) { - output << '\n'; - for (std::size_t index = 0; index < fact.fields.size(); ++index) { - const auto &[field, value] = fact.fields[index]; - output << indentation(indent + 4) - << sourceName(decodeText(irSymbolPieces(symbolTable, field))) - << ": " - << valueText(value, symbolTable, decodeText, indent + 4, - depth + 1); - if (index + 1 < fact.fields.size()) - output << ','; - output << '\n'; - } - output << indentation(indent); - } - output << ')'; - return output.str(); -} - -std::string valueText(const VmValue &value, - std::span symbolTable, - const VmTextDecoder &decodeText, std::size_t indent, - std::size_t depth) { - constexpr std::size_t kMaximumPersistenceDepth = 64; - if (depth > kMaximumPersistenceDepth) - throw IrError("fact database value nesting is too deep"); - if (std::holds_alternative(value)) - return "nil"; - if (const auto number = std::get_if(&value)) - return numberText(*number); - if (const auto degree = std::get_if(&value)) - return numberText(degree->value); - if (const auto text = std::get_if(&value)) - return Json::toText(Json::Value(decodeText(text->pieces))); - if (const auto symbol = std::get_if(&value)) - return decodeText(irSymbolPieces(symbolTable, symbol->value)); - if (const auto array = std::get_if(&value); array && *array) { - if ((*array)->values.empty()) - return "[]"; - std::ostringstream output; - output << "[\n"; - for (std::size_t index = 0; index < (*array)->values.size(); ++index) { - output << indentation(indent + 4) - << valueText((*array)->values[index], symbolTable, decodeText, - indent + 4, depth + 1); - if (index + 1 < (*array)->values.size()) - output << ','; - output << '\n'; - } - output << indentation(indent) << ']'; - return output.str(); - } - if (const auto map = std::get_if(&value); map && *map) { - return mapText( - (*map)->entries, - [&](IrSymbolRef key) { - return sourceName(decodeText(irSymbolPieces(symbolTable, key))); - }, - symbolTable, decodeText, indent, depth); - } - if (const auto map = std::get_if(&value); map && *map) { - return mapText((*map)->entries, - [&](const PieceSequence &key) { - return sourceName(decodeText(key)); - }, - symbolTable, decodeText, indent, depth); - } - if (const auto fact = std::get_if(&value); fact && *fact) - return factText(**fact, symbolTable, decodeText, indent, depth); - if (std::holds_alternative(value)) - throw IrError("fact database cannot serialize a tensor value"); - throw IrError("fact database contains an invalid VM value"); -} - -void atomicWrite(const std::filesystem::path &path, std::string_view content) { - if (path.has_parent_path()) - std::filesystem::create_directories(path.parent_path()); - auto temporary = path; - temporary += ".tmp"; - { - std::ofstream output(temporary, std::ios::binary | std::ios::trunc); - if (!output) - throw IrError("cannot write temporary fact database: " + - temporary.string()); - output.write(content.data(), static_cast(content.size())); - output.flush(); - if (!output) - throw IrError("cannot complete temporary fact database: " + - temporary.string()); - } -#ifdef _WIN32 - if (!MoveFileExW(temporary.wstring().c_str(), path.wstring().c_str(), - MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { - std::filesystem::remove(temporary); - throw IrError("cannot replace fact database: " + path.string()); - } -#else - if (std::rename(temporary.string().c_str(), path.string().c_str()) != 0) { - std::filesystem::remove(temporary); - throw IrError("cannot replace fact database: " + path.string()); - } -#endif -} - -std::string csvText(std::span facts, - std::span symbolTable, - const VmTextDecoder &decodeText, - const VmFactPtr &emptySchema) { - const auto schema = facts.empty() ? emptySchema : facts.front(); - if (!schema) - return {}; - if (!facts.empty() && !facts.front()) - throw IrError("CSV database contains an invalid retained fact"); - const auto type = schema->type; - std::vector fields; - fields.reserve(schema->fields.size()); - for (const auto &[field, _] : schema->fields) - fields.push_back(field); - - const BuiltinTextCodec codec{ - decodeText, - [](std::string_view) -> PieceSequence { - throw IrError("CSV persistence unexpectedly requested text encoding"); - }}; - auto rows = Json::Value::array(); - for (const auto &fact : facts) { - if (!fact || fact->type != type || fact->fields.size() != fields.size()) - throw IrError("CSV persistence cannot mix fact types or schemas"); - for (std::size_t index = 0; index < fields.size(); ++index) { - if (fact->fields[index].first != fields[index]) - throw IrError("CSV persistence requires one stable field order"); - } - rows.push_back(vmValueToJson(VmValue{fact}, symbolTable, codec)); - } - std::vector columns; - columns.reserve(fields.size()); - for (const auto field : fields) - columns.push_back(decodeText(irSymbolPieces(symbolTable, field))); - return Csv::toText(rows, columns); -} - -} // namespace - -void sync(const std::filesystem::path &path, - std::span facts, - std::span symbolTable, - const VmTextDecoder &decodeText, - const VmFactPtr &emptySchema, - const FactParentLookup &parentsOf) { - if (path.empty() || (path.extension() != ".fx" && - path.extension() != ".csv")) - throw IrError("fact persistence requires a non-empty .fx or .csv path"); - if (!decodeText) - throw IrError("fact persistence requires the VM SentencePiece decoder"); - std::string content; - if (path.extension() == ".csv") { - content = csvText(facts, symbolTable, decodeText, emptySchema); - } else { - std::ostringstream source; - source << "# Felidae fact database\n"; - for (const auto &fact : facts) { - if (!fact) - throw IrError("fact database contains an invalid retained fact"); - const auto parents = parentsOf ? parentsOf(fact->type) - : std::vector{}; - source << '\n' - << factText(*fact, symbolTable, decodeText, 0, 0, parents) - << '\n'; - } - content = source.str(); - } - std::lock_guard lock(databaseMutex); - DatabaseFileLock fileLock(path); - atomicWrite(path, content); -} - -} // namespace Felidae::Form::Db diff --git a/src/form/libs/Db.h b/src/form/libs/Db.h deleted file mode 100644 index 9470422..0000000 --- a/src/form/libs/Db.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "form/RegisterVm.h" - -#include -#include - -namespace Felidae::Form::Db { - -using FactParentLookup = - std::function(IrSymbolRef type)>; - -// Internal automatic-persistence helper. Rewrites one database from immutable -// VM fact snapshots; it has no source-language builtin. -void sync(const std::filesystem::path &path, - std::span facts, - std::span symbolTable, - const VmTextDecoder &decodeText, - const VmFactPtr &emptySchema = {}, - const FactParentLookup &parentsOf = {}); - -} // namespace Felidae::Form::Db diff --git a/src/form/libs/ExecutionVectorMemory.cpp b/src/form/libs/ExecutionVectorMemory.cpp deleted file mode 100644 index ef4b4bf..0000000 --- a/src/form/libs/ExecutionVectorMemory.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "ExecutionVectorMemory.h" - -#include "form/IrModule.h" -#include - -#include -#include -#include - -namespace Felidae::Form { - -class ExecutionVectorMemory::Implementation { -public: - Implementation(std::size_t dimensions, std::size_t maximum) - : index(static_cast(dimensions)), capacity(maximum) {} - faiss::IndexFlatL2 index; - std::size_t capacity; -}; - -ExecutionVectorMemory::ExecutionVectorMemory(std::size_t dimensions, - std::size_t capacity) { - if (dimensions == 0 || dimensions > static_cast( - std::numeric_limits::max()) || capacity == 0 || - capacity > std::numeric_limits::max() / sizeof(float) / dimensions) - throw IrError("invalid execution vector memory dimensions or capacity"); - implementation_ = std::make_unique(dimensions, capacity); -} - -ExecutionVectorMemory::~ExecutionVectorMemory() = default; - -void ExecutionVectorMemory::append(std::span state) { - auto &memory = *implementation_; - if (state.size() != static_cast(memory.index.d) || - !std::all_of(state.begin(), state.end(), [](float v) { return std::isfinite(v); })) - throw IrError("execution hidden state has invalid dimensions or non-finite values"); - if (size() == memory.capacity) - throw IrError("execution vector memory reached its semantic-step capacity"); - memory.index.add(1, state.data()); -} - -std::size_t ExecutionVectorMemory::size() const { - return static_cast(implementation_->index.ntotal); -} - -} // namespace Felidae::Form diff --git a/src/form/libs/ExecutionVectorMemory.h b/src/form/libs/ExecutionVectorMemory.h deleted file mode 100644 index e66ddc4..0000000 --- a/src/form/libs/ExecutionVectorMemory.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace Felidae::Form { - -// Owns real numeric hidden-state vectors, never facts or SentencePiece IDs. -// One instance belongs to one execution; there is no serialization or global -// cache. Destroying it releases every retained vector. No training is needed. -class ExecutionVectorMemory { -public: - ExecutionVectorMemory(std::size_t dimensions, std::size_t capacity); - ~ExecutionVectorMemory(); - ExecutionVectorMemory(const ExecutionVectorMemory &) = delete; - ExecutionVectorMemory &operator=(const ExecutionVectorMemory &) = delete; - void append(std::span state); - std::size_t size() const; - -private: - class Implementation; - std::unique_ptr implementation_; -}; - -} // namespace Felidae::Form diff --git a/src/form/libs/FactStorageCodec.cpp b/src/form/libs/FactStorageCodec.cpp deleted file mode 100644 index 92c3822..0000000 --- a/src/form/libs/FactStorageCodec.cpp +++ /dev/null @@ -1,438 +0,0 @@ -#include "form/libs/FactStorageCodec.h" - -#include "form/IrModule.h" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae::Form { -namespace { - -using Json = nlohmann::ordered_json; -constexpr std::size_t kMaximumStorageDepth = 64; -constexpr std::size_t kMaximumStorageItems = 1'000'000; -constexpr std::uint64_t kFactStorageVersion = 1; -constexpr std::uint64_t kFactTypeStorageVersion = 1; - -void appendValueKey(const VmValue &value, - std::span symbols, - StoredValueKey &key, std::size_t depth = 0) { - if (depth > kMaximumStorageDepth) - throw IrError("fact index key exceeds its nesting limit"); - key.push_back(static_cast(runtimeValueKind(value))); - const auto appendSize = [&](std::size_t size) { - key.push_back(static_cast(size)); - }; - const auto appendPieces = [&](std::span value) { - appendSize(value.size()); - for (const auto piece : value) - key.push_back(static_cast(piece)); - }; - const auto appendEntries = [&](const auto &entries) { - std::vector order(entries.size()); - std::iota(order.begin(), order.end(), 0); - std::sort(order.begin(), order.end(), [&](std::size_t left, - std::size_t right) { - // Field order must survive a different symbol-interning order after - // reopening storage. Only SentencePiece sequences define that order. - if constexpr (std::is_same_v< - std::remove_cvref_t, - PieceSequence>) { - return entries[left].first < entries[right].first; - } else { - const auto a = irSymbolPieces(symbols, entries[left].first); - const auto b = irSymbolPieces(symbols, entries[right].first); - return std::lexicographical_compare(a.begin(), a.end(), - b.begin(), b.end()); - } - }); - appendSize(order.size()); - for (const auto index : order) { - const auto &[field, item] = entries[index]; - if constexpr (std::is_same_v, - PieceSequence>) - appendPieces(field); - else - appendPieces(irSymbolPieces(symbols, field)); - appendValueKey(item, symbols, key, depth + 1); - } - }; - if (std::holds_alternative(value)) - return; - if (const auto number = std::get_if(&value)) { - if (!std::isfinite(*number)) - throw IrError("fact index key must be finite"); - key.push_back(std::bit_cast(*number == 0.0 ? 0.0 : *number)); - return; - } - if (const auto degree = std::get_if(&value)) { - key.push_back(std::bit_cast(degree->value)); - return; - } - if (const auto text = std::get_if(&value)) { - appendPieces(text->pieces); - return; - } - if (const auto symbol = std::get_if(&value)) { - appendPieces(irSymbolPieces(symbols, symbol->value)); - return; - } - if (const auto array = std::get_if(&value)) { - if (!*array) - throw IrError("fact index key contains a null array"); - appendSize((*array)->values.size()); - for (const auto &item : (*array)->values) - appendValueKey(item, symbols, key, depth + 1); - return; - } - if (const auto map = std::get_if(&value)) { - if (!*map) - throw IrError("fact index key contains a null map"); - appendEntries((*map)->entries); - return; - } - if (const auto fact = std::get_if(&value)) { - if (!*fact) - throw IrError("fact index key contains a null fact"); - appendPieces(irSymbolPieces(symbols, (*fact)->type)); - appendEntries((*fact)->fields); - return; - } - if (std::holds_alternative(value)) - throw IrError("tensor values cannot be fact index keys"); - const auto &map = std::get(value); - if (!map) - throw IrError("fact index key contains a null text map"); - appendEntries(map->entries); -} - -Json pieces(std::span value) { - Json result = Json::array(); - for (const auto piece : value) - result.push_back(piece); - return result; -} - -// CBOR is an external boundary: JSON numeric conversions otherwise truncate -// fractions and narrow oversized integers before the caller can validate them. -std::uint64_t readUnsigned(const Json &value, - std::uint64_t maximum = UINT64_MAX) { - if (!value.is_number_integer() || - (!value.is_number_unsigned() && value.get() < 0)) - throw IrError("stored fact contains an invalid unsigned integer"); - const auto number = value.get(); - if (number > maximum) - throw IrError("stored fact integer is outside its range"); - return number; -} - -PieceSequence readPieces(const Json &value, bool allowEmpty = false) { - if (!value.is_array() || (!allowEmpty && value.empty()) || - value.size() > kMaximumStorageItems) - throw IrError("stored fact contains an invalid SentencePiece sequence"); - PieceSequence result; - result.reserve(value.size()); - for (const auto &piece : value) { - const auto number = readUnsigned(piece, std::numeric_limits::max()); - result.push_back(static_cast(number)); - } - return result; -} - -Json encodeValue(const VmValue &value, - std::span symbols, std::size_t depth); - -Json encodeEntries( - std::span> entries, - std::span symbols, std::size_t depth) { - if (entries.size() > kMaximumStorageItems) - throw IrError("fact storage entry count exceeds its limit"); - Json result = Json::array(); - for (const auto &[field, value] : entries) - result.push_back( - Json::array({pieces(irSymbolPieces(symbols, field)), - encodeValue(value, symbols, depth + 1)})); - return result; -} - -Json encodeFact(const VmFact &fact, std::span symbols, - std::size_t depth) { - if (fact.type == 0) - throw IrError("fact storage cannot encode an untyped fact"); - return Json::array( - {fact.id, pieces(irSymbolPieces(symbols, fact.type)), - static_cast(fact.origin), fact.createdSequence, - encodeEntries(fact.fields, symbols, depth)}); -} - -Json encodeValue(const VmValue &value, - std::span symbols, std::size_t depth) { - if (depth > kMaximumStorageDepth) - throw IrError("fact storage value nesting exceeds its limit"); - const auto kind = runtimeValueKind(value); - switch (kind) { - case RuntimeValueKind::Nil: - return Json::array({static_cast(kind)}); - case RuntimeValueKind::Number: { - const auto number = std::get(value); - if (!std::isfinite(number)) - throw IrError("fact storage cannot encode a non-finite number"); - return Json::array({static_cast(kind), number}); - } - case RuntimeValueKind::Degree: - return Json::array({static_cast(kind), - std::get(value).value}); - case RuntimeValueKind::Text: - return Json::array({static_cast(kind), - pieces(std::get(value).pieces)}); - case RuntimeValueKind::Symbol: - return Json::array( - {static_cast(kind), - pieces(irSymbolPieces(symbols, std::get(value).value))}); - case RuntimeValueKind::Array: { - const auto &array = std::get(value); - if (!array || array->values.size() > kMaximumStorageItems) - throw IrError("fact storage cannot encode an invalid array"); - Json items = Json::array(); - for (const auto &item : array->values) - items.push_back(encodeValue(item, symbols, depth + 1)); - return Json::array({static_cast(kind), std::move(items)}); - } - case RuntimeValueKind::Map: { - const auto &map = std::get(value); - if (!map) - throw IrError("fact storage cannot encode an invalid map"); - return Json::array({static_cast(kind), - encodeEntries(map->entries, symbols, depth)}); - } - case RuntimeValueKind::Fact: { - const auto &fact = std::get(value); - if (!fact) - throw IrError("fact storage cannot encode an invalid nested fact"); - return Json::array({static_cast(kind), - encodeFact(*fact, symbols, depth + 1)}); - } - case RuntimeValueKind::TextMap: { - const auto &map = std::get(value); - if (!map || map->entries.size() > kMaximumStorageItems) - throw IrError("fact storage cannot encode an invalid text map"); - Json entries = Json::array(); - for (const auto &[field, item] : map->entries) - entries.push_back(Json::array( - {pieces(field), encodeValue(item, symbols, depth + 1)})); - return Json::array({static_cast(kind), std::move(entries)}); - } - case RuntimeValueKind::Tensor: - throw IrError("fact storage cannot persist a LibTorch tensor value"); - } - throw IrError("fact storage encountered an unknown value kind"); -} - -void requireArray(const Json &value, std::size_t size, - std::string_view description) { - if (!value.is_array() || value.size() != size) - throw IrError("stored fact has invalid " + std::string(description)); -} - -VmValue decodeValue(const Json &value, const StoredSymbolInterner &intern, - std::size_t depth); - -std::vector> -decodeEntries(const Json &value, const StoredSymbolInterner &intern, - std::size_t depth) { - if (!value.is_array() || value.size() > kMaximumStorageItems) - throw IrError("stored fact has an invalid field collection"); - std::vector> result; - result.reserve(value.size()); - for (const auto &entry : value) { - requireArray(entry, 2, "field entry"); - result.emplace_back(intern(readPieces(entry[0])), - decodeValue(entry[1], intern, depth + 1)); - } - return result; -} - -VmFactPtr decodeFact(const Json &value, const StoredSymbolInterner &intern, - std::size_t depth) { - requireArray(value, 5, "fact record"); - auto fact = std::make_shared(); - fact->id = readUnsigned(value[0], std::numeric_limits::max()); - fact->type = intern(readPieces(value[1])); - const auto origin = readUnsigned(value[2], - static_cast(VmFact::Origin::Derived)); - fact->origin = static_cast(origin); - fact->createdSequence = readUnsigned(value[3]); - fact->fields = decodeEntries(value[4], intern, depth); - return fact; -} - -VmValue decodeValue(const Json &value, const StoredSymbolInterner &intern, - std::size_t depth) { - if (depth > kMaximumStorageDepth || !value.is_array() || value.empty()) - throw IrError("stored fact contains an invalid nested value"); - const auto kind = static_cast(readUnsigned(value[0], UINT8_MAX)); - switch (kind) { - case RuntimeValueKind::Nil: - requireArray(value, 1, "nil value"); - return VmNil{}; - case RuntimeValueKind::Number: { - requireArray(value, 2, "number value"); - const auto number = value[1].get(); - if (!std::isfinite(number)) - throw IrError("stored fact contains a non-finite number"); - return number; - } - case RuntimeValueKind::Degree: - requireArray(value, 2, "degree value"); - return VmDegree(value[1].get()); - case RuntimeValueKind::Text: - requireArray(value, 2, "text value"); - return VmText{readPieces(value[1], true)}; - case RuntimeValueKind::Symbol: - requireArray(value, 2, "symbol value"); - return VmSymbol{intern(readPieces(value[1]))}; - case RuntimeValueKind::Array: { - requireArray(value, 2, "array value"); - if (!value[1].is_array() || value[1].size() > kMaximumStorageItems) - throw IrError("stored fact contains an invalid array"); - auto result = std::make_shared(); - result->values.reserve(value[1].size()); - for (const auto &item : value[1]) - result->values.push_back(decodeValue(item, intern, depth + 1)); - return result; - } - case RuntimeValueKind::Map: { - requireArray(value, 2, "map value"); - auto result = std::make_shared(); - result->entries = decodeEntries(value[1], intern, depth); - return result; - } - case RuntimeValueKind::Fact: - requireArray(value, 2, "nested fact value"); - return decodeFact(value[1], intern, depth + 1); - case RuntimeValueKind::TextMap: { - requireArray(value, 2, "text-map value"); - if (!value[1].is_array() || value[1].size() > kMaximumStorageItems) - throw IrError("stored fact contains an invalid text map"); - auto result = std::make_shared(); - result->entries.reserve(value[1].size()); - for (const auto &entry : value[1]) { - requireArray(entry, 2, "text-map entry"); - result->entries.emplace_back( - readPieces(entry[0], true), decodeValue(entry[1], intern, depth + 1)); - } - return result; - } - case RuntimeValueKind::Tensor: - throw IrError("stored fact contains an unsupported tensor value"); - } - throw IrError("stored fact contains an unknown value kind"); -} - -} // namespace - -StoredValueKey encodeStoredValueKey( - const VmValue &value, std::span symbols) { - StoredValueKey result; - appendValueKey(value, symbols, result); - return result; -} - -std::string encodeStoredFact(const VmFact &fact, - std::optional source, - std::span symbols) { - const Json record = Json::array( - {kFactStorageVersion, encodeFact(fact, symbols, 0), - source ? Json(*source) : Json(nullptr)}); - const auto bytes = Json::to_cbor(record); - return std::string(reinterpret_cast(bytes.data()), bytes.size()); -} - -StoredFactRecord decodeStoredFact(std::string_view bytes, - const StoredSymbolInterner &intern) { - if (!intern || bytes.empty()) - throw IrError("stored fact record is empty or has no symbol interner"); - try { - const auto *begin = reinterpret_cast(bytes.data()); - const Json record = Json::from_cbor(begin, begin + bytes.size()); - requireArray(record, 3, "storage envelope"); - if (readUnsigned(record[0]) != kFactStorageVersion) - throw IrError("stored fact schema version is unsupported"); - StoredFactRecord result; - result.fact = decodeFact(record[1], intern, 0); - if (!record[2].is_null()) - result.source = record[2].get(); - return result; - } catch (const IrError &) { - throw; - } catch (const std::exception &error) { - throw IrError("cannot decode stored fact record: " + - std::string(error.what())); - } -} - -std::string encodeStoredFactType( - IrSymbolRef type, std::span parents, - std::span> indexes, - std::span symbols) { - Json encodedParents = Json::array(); - for (const auto parent : parents) - encodedParents.push_back(pieces(irSymbolPieces(symbols, parent))); - Json encodedIndexes = Json::array(); - for (const auto &index : indexes) { - Json fields = Json::array(); - for (const auto field : index) - fields.push_back(pieces(irSymbolPieces(symbols, field))); - encodedIndexes.push_back(std::move(fields)); - } - const Json record = Json::array( - {kFactTypeStorageVersion, pieces(irSymbolPieces(symbols, type)), - std::move(encodedParents), std::move(encodedIndexes)}); - const auto bytes = Json::to_cbor(record); - return std::string(reinterpret_cast(bytes.data()), bytes.size()); -} - -StoredFactTypeRecord decodeStoredFactType( - std::string_view bytes, const StoredSymbolInterner &intern) { - if (!intern || bytes.empty()) - throw IrError("stored fact-type record is empty or has no symbol interner"); - try { - const auto *begin = reinterpret_cast(bytes.data()); - const Json record = Json::from_cbor(begin, begin + bytes.size()); - requireArray(record, 4, "fact-type storage envelope"); - if (readUnsigned(record[0]) != kFactTypeStorageVersion) - throw IrError("stored fact-type schema version is unsupported"); - StoredFactTypeRecord result; - result.type = intern(readPieces(record[1])); - if (!record[2].is_array() || record[2].size() > kMaximumStorageItems || - !record[3].is_array() || record[3].size() > kMaximumStorageItems) - throw IrError("stored fact-type metadata is invalid"); - for (const auto &parent : record[2]) - result.parents.push_back(intern(readPieces(parent))); - for (const auto &encodedIndex : record[3]) { - if (!encodedIndex.is_array() || encodedIndex.empty() || - encodedIndex.size() > kMaximumStorageItems) - throw IrError("stored fact-type index is invalid"); - std::vector index; - index.reserve(encodedIndex.size()); - for (const auto &field : encodedIndex) - index.push_back(intern(readPieces(field))); - result.indexes.push_back(std::move(index)); - } - return result; - } catch (const IrError &) { - throw; - } catch (const std::exception &error) { - throw IrError("cannot decode stored fact-type record: " + - std::string(error.what())); - } -} - -} // namespace Felidae::Form diff --git a/src/form/libs/FactStorageCodec.h b/src/form/libs/FactStorageCodec.h deleted file mode 100644 index 883a271..0000000 --- a/src/form/libs/FactStorageCodec.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include "form/RegisterVm.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae::Form { - -struct StoredFactRecord { - VmFactPtr fact; - std::optional source; -}; - -struct StoredFactTypeRecord { - IrSymbolRef type = 0; - std::vector parents; - std::vector> indexes; -}; - -using StoredSymbolInterner = std::function; -using StoredValueKey = std::vector; - -StoredValueKey encodeStoredValueKey( - const VmValue &value, std::span symbols); - -std::string encodeStoredFact(const VmFact &fact, - std::optional source, - std::span symbols); -StoredFactRecord decodeStoredFact(std::string_view bytes, - const StoredSymbolInterner &intern); -std::string encodeStoredFactType( - IrSymbolRef type, std::span parents, - std::span> indexes, - std::span symbols); -StoredFactTypeRecord decodeStoredFactType( - std::string_view bytes, const StoredSymbolInterner &intern); - -} // namespace Felidae::Form diff --git a/src/form/libs/Group.cpp b/src/form/libs/Group.cpp deleted file mode 100644 index 42fdef6..0000000 --- a/src/form/libs/Group.cpp +++ /dev/null @@ -1,166 +0,0 @@ -#include "Group.h" - -#include -#include -#include -#include - -namespace Felidae::Form::Group { -namespace { - -std::string key(const Json::Value &value) { return value.dump(); } - -struct FiniteOperation { - const Json::Value &members; - std::unordered_map table; - - FiniteOperation(const Json::Value &members, const Json::Value &rows) - : members(members) { - if (!members.is_array()) - throw std::runtime_error("Group set must be an array"); - if (members.empty()) - throw std::runtime_error("Group set must not be empty"); - if (!rows.is_array()) - throw std::runtime_error("Group table must be an array"); - std::unordered_set memberKeys; - for (const auto &member : members) { - if (!memberKeys.insert(key(member)).second) - throw std::runtime_error("Group set contains a duplicate member"); - } - for (const auto &row : rows) { - if (!row.is_object() || !row.contains("left") || !row.contains("right") || - !row.contains("result")) { - throw std::runtime_error( - "Group table row requires left, right, and result"); - } - const auto pairKey = key(row.at("left")) + '\x1f' + key(row.at("right")); - if (!table.emplace(pairKey, row.at("result")).second) - throw std::runtime_error("Group table contains a duplicate pair"); - } - } - - const Json::Value *apply(const Json::Value &left, - const Json::Value &right) const { - const auto found = table.find(key(left) + '\x1f' + key(right)); - return found == table.end() ? nullptr : &found->second; - } -}; - -bool closed(const FiniteOperation &operation) { - std::unordered_set members; - for (const auto &item : operation.members) - members.insert(key(item)); - for (const auto &left : operation.members) { - for (const auto &right : operation.members) { - const auto *result = operation.apply(left, right); - if (!result || !members.contains(key(*result))) - return false; - } - } - return true; -} - -bool associative(const FiniteOperation &operation) { - for (const auto &a : operation.members) { - for (const auto &b : operation.members) { - for (const auto &c : operation.members) { - const auto *ab = operation.apply(a, b); - const auto *bc = operation.apply(b, c); - if (!ab || !bc) - return false; - const auto *left = operation.apply(*ab, c); - const auto *right = operation.apply(a, *bc); - if (!left || !right || *left != *right) - return false; - } - } - } - return true; -} - -bool hasIdentity(const FiniteOperation &operation, - const Json::Value &identity) { - for (const auto &item : operation.members) { - const auto *left = operation.apply(identity, item); - const auto *right = operation.apply(item, identity); - if (!left || !right || *left != item || *right != item) - return false; - } - return true; -} - -bool hasInverses(const FiniteOperation &operation, - const Json::Value &identity) { - for (const auto &item : operation.members) { - bool found = false; - for (const auto &candidate : operation.members) { - const auto *left = operation.apply(item, candidate); - const auto *right = operation.apply(candidate, item); - if (left && right && *left == identity && *right == identity) { - found = true; - break; - } - } - if (!found) - return false; - } - return true; -} - -bool commutative(const FiniteOperation &operation) { - for (const auto &left : operation.members) { - for (const auto &right : operation.members) { - const auto *forward = operation.apply(left, right); - const auto *reverse = operation.apply(right, left); - if (!forward || !reverse || *forward != *reverse) - return false; - } - } - return true; -} - -} // namespace - -Json::Value evaluate(BuiltinId operationId, const Json::Value &members, - const Json::Value &table, - const std::optional &identity) { - const FiniteOperation operation{members, table}; - switch (operationId) { - case BuiltinId::GroupClosed: - return closed(operation); - case BuiltinId::GroupAssociative: - return associative(operation); - case BuiltinId::GroupIdentity: - return identity && hasIdentity(operation, identity.value()); - case BuiltinId::GroupInverse: - return identity && hasInverses(operation, identity.value()); - case BuiltinId::GroupCommutative: - return commutative(operation); - case BuiltinId::GroupAbelian: - return identity && closed(operation) && associative(operation) && - hasIdentity(operation, identity.value()) && - hasInverses(operation, identity.value()) && commutative(operation); - case BuiltinId::GroupValidate: { - const bool closure = closed(operation); - const bool associativity = associative(operation); - const bool identityValid = - identity && hasIdentity(operation, identity.value()); - const bool inverseValid = - identity && hasInverses(operation, identity.value()); - const bool commutativity = commutative(operation); - return Json::Value{ - {"valid", closure && associativity && identityValid && inverseValid}, - {"closure", closure}, - {"associative", associativity}, - {"identity", identityValid}, - {"inverse", inverseValid}, - {"commutative", commutativity}, - {"abelian", closure && associativity && identityValid && inverseValid && - commutativity}}; - } - default: - throw std::runtime_error("Unsupported Group operation"); - } -} - -} // namespace Felidae::Form::Group diff --git a/src/form/libs/Group.h b/src/form/libs/Group.h deleted file mode 100644 index cbab26c..0000000 --- a/src/form/libs/Group.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "Json.h" -#include "form/BuiltinOperation.h" - -#include - -namespace Felidae::Form::Group { - -Json::Value evaluate(BuiltinId operation, const Json::Value &members, - const Json::Value &table, - const std::optional &identity); - -} // namespace Felidae::Form::Group diff --git a/src/form/libs/Json.cpp b/src/form/libs/Json.cpp deleted file mode 100644 index 70e448b..0000000 --- a/src/form/libs/Json.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "Json.h" - -#include - -namespace Felidae::Form::Json { - -Value parse(std::string_view text) { - try { - return Value::parse(text.begin(), text.end()); - } catch (const nlohmann::json::exception &error) { - throw std::runtime_error("json.parse received invalid JSON: " + - std::string(error.what())); - } -} - -const Value &get(const Value &value, std::string_view key) { - if (!value.is_object()) - throw std::runtime_error("json.get expects an object"); - const auto found = value.find(std::string(key)); - if (found == value.end()) - throw std::runtime_error("json.get key is absent: " + std::string(key)); - return *found; -} - -bool has(const Value &value, std::string_view key) { - if (!value.is_object()) - throw std::runtime_error("json.has expects an object"); - return value.contains(std::string(key)); -} - -std::vector keys(const Value &value) { - if (!value.is_object()) - throw std::runtime_error("json.keys expects an object"); - std::vector result; - result.reserve(value.size()); - for (const auto &[key, _] : value.items()) - result.push_back(key); - return result; -} - -Value set(Value value, std::string key, Value fieldValue) { - if (!value.is_object()) - throw std::runtime_error("json.set expects an object"); - value[std::move(key)] = std::move(fieldValue); - return value; -} - -Value remove(Value value, std::string_view key) { - if (!value.is_object()) - throw std::runtime_error("json.remove expects an object"); - value.erase(std::string(key)); - return value; -} - -std::string toText(const Value &value) { return value.dump(); } - -} // namespace Felidae::Form::Json diff --git a/src/form/libs/Json.h b/src/form/libs/Json.h deleted file mode 100644 index 5492f4a..0000000 --- a/src/form/libs/Json.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -namespace Felidae::Form::Json { - -using Value = nlohmann::ordered_json; - -Value parse(std::string_view text); -const Value &get(const Value &value, std::string_view key); -bool has(const Value &value, std::string_view key); -std::vector keys(const Value &value); -Value set(Value value, std::string key, Value fieldValue); -Value remove(Value value, std::string_view key); -std::string toText(const Value &value); - -} // namespace Felidae::Form::Json diff --git a/src/form/libs/RocksDb.cpp b/src/form/libs/RocksDb.cpp deleted file mode 100644 index f0fa299..0000000 --- a/src/form/libs/RocksDb.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "form/libs/RocksDb.h" - -#include "form/IrModule.h" - -#include -#include -#include - -#include - -namespace Felidae::Form { -namespace { - -[[noreturn]] void fail(std::string_view operation, - const rocksdb::Status &status) { - throw IrError("RocksDB " + std::string(operation) + " failed: " + - status.ToString()); -} - -bool hasPrefix(std::string_view value, std::string_view prefix) { - return value.size() >= prefix.size() && - value.compare(0, prefix.size(), prefix) == 0; -} - -} // namespace - -class RocksDb::Implementation { -public: - std::unique_ptr database; -}; - -RocksDb::RocksDb(const std::filesystem::path &directory) - : implementation_(std::make_unique()) { - if (directory.empty()) - throw IrError("RocksDB directory must not be empty"); - std::error_code error; - std::filesystem::create_directories(directory, error); - if (error) - throw IrError("cannot create RocksDB directory: " + error.message()); - - rocksdb::Options options; - options.create_if_missing = true; - rocksdb::DB *database = nullptr; - const auto status = rocksdb::DB::Open(options, directory.string(), &database); - if (!status.ok()) - fail("open", status); - implementation_->database.reset(database); -} - -RocksDb::~RocksDb() = default; -RocksDb::RocksDb(RocksDb &&) noexcept = default; -RocksDb &RocksDb::operator=(RocksDb &&) noexcept = default; - -std::string RocksDb::identity() const { - std::string result; - const auto status = implementation_->database->GetDbIdentity(result); - if (!status.ok()) - fail("identity", status); - return result; -} - -std::optional RocksDb::get(std::string_view key) const { - if (key.empty()) - throw IrError("RocksDB key must not be empty"); - std::string value; - const auto status = implementation_->database->Get( - rocksdb::ReadOptions{}, rocksdb::Slice(key.data(), key.size()), &value); - if (status.IsNotFound()) - return std::nullopt; - if (!status.ok()) - fail("read", status); - return value; -} - -std::optional -RocksDb::integerProperty(std::string_view name) const { - if (name.empty()) - throw IrError("RocksDB property name must not be empty"); - std::uint64_t value = 0; - if (!implementation_->database->GetIntProperty( - rocksdb::Slice(name.data(), name.size()), &value)) - return std::nullopt; - return value; -} - -void RocksDb::write(std::span mutations) { - if (mutations.empty()) - return; - rocksdb::WriteBatch batch; - for (const auto &mutation : mutations) { - if (mutation.key.empty()) - throw IrError("RocksDB mutation key must not be empty"); - rocksdb::Status status; - if (mutation.kind == Mutation::Kind::Put) { - status = batch.Put(mutation.key, mutation.value); - } else { - status = batch.Delete(mutation.key); - } - if (!status.ok()) - fail("batch construction", status); - } - rocksdb::WriteOptions options; - options.sync = true; - const auto status = implementation_->database->Write(options, &batch); - if (!status.ok()) - fail("batch commit", status); -} - -RocksDb::Scan RocksDb::scanPrefix( - std::string_view prefix, std::optional after, - std::size_t records) const { - if (prefix.empty()) - throw IrError("RocksDB scan prefix must not be empty"); - if (after && !hasPrefix(*after, prefix)) - throw IrError("RocksDB cursor does not belong to the requested prefix"); - if (records > maximumScanRecords) - throw IrError("RocksDB scan record limit is too large"); - - rocksdb::ReadOptions options; - options.total_order_seek = false; - std::unique_ptr iterator( - implementation_->database->NewIterator(options)); - const auto seek = after.value_or(prefix); - iterator->Seek(rocksdb::Slice(seek.data(), seek.size())); - if (after && iterator->Valid() && iterator->key().ToStringView() == *after) - iterator->Next(); - - Scan result; - result.rows.reserve(records); - while (iterator->Valid() && - hasPrefix(iterator->key().ToStringView(), prefix)) { - if (result.rows.size() == records) { - result.hasMore = true; - break; - } - result.rows.emplace_back(iterator->key().ToString(), - iterator->value().ToString()); - iterator->Next(); - } - if (!iterator->status().ok()) - fail("scan", iterator->status()); - return result; -} - -} // namespace Felidae::Form diff --git a/src/form/libs/RocksDb.h b/src/form/libs/RocksDb.h deleted file mode 100644 index 39ac5b6..0000000 --- a/src/form/libs/RocksDb.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae::Form { - -// Thin ownership boundary around RocksDB. Higher VM layers own Felidae value -// encoding and index layout; this class owns only durable ordered bytes, -// atomic batches, and bounded keyset scans. -class RocksDb { -public: - // A maximum-size VM page plus one lookahead row. Larger reads must page. - static constexpr std::size_t maximumScanRecords = 10'001; - struct Mutation { - enum class Kind { Put, Erase } kind = Kind::Put; - std::string key; - std::string value; - }; - - struct Scan { - std::vector> rows; - bool hasMore = false; - }; - - explicit RocksDb(const std::filesystem::path &directory); - ~RocksDb(); - RocksDb(RocksDb &&) noexcept; - RocksDb &operator=(RocksDb &&) noexcept; - RocksDb(const RocksDb &) = delete; - RocksDb &operator=(const RocksDb &) = delete; - - std::optional get(std::string_view key) const; - std::optional integerProperty(std::string_view name) const; - std::string identity() const; - void write(std::span mutations); - Scan scanPrefix(std::string_view prefix, - std::optional after, - std::size_t records) const; - -private: - class Implementation; - std::unique_ptr implementation_; -}; - -} // namespace Felidae::Form diff --git a/src/form/libs/Set.cpp b/src/form/libs/Set.cpp deleted file mode 100644 index 915e859..0000000 --- a/src/form/libs/Set.cpp +++ /dev/null @@ -1,201 +0,0 @@ -#include "Set.h" - -#include -#include -#include -#include -#include - -namespace Felidae::Form::Set { -namespace { - -using Keys = std::unordered_set; - -std::vector selectedFields(const Json::Value &fields) { - if (!fields.is_array()) - throw std::runtime_error("Set fields must be an array"); - std::vector result; - result.reserve(fields.size()); - for (const auto &field : fields) { - if (!field.is_string()) - throw std::runtime_error("Set fields must contain strings"); - result.push_back(field.get()); - } - return result; -} - -std::vector inputSets(const Json::Value &sets) { - if (!sets.is_array() || sets.empty()) - throw std::runtime_error("Set operation requires at least one input set"); - std::vector result; - result.reserve(sets.size()); - for (const auto &set : sets) { - if (!set.is_array()) - throw std::runtime_error("Set input must be an array"); - result.push_back(&set); - } - return result; -} - -std::string keyFor(const Json::Value &item, - const std::vector &fields) { - if (fields.empty()) - return item.dump(); - if (!item.is_object()) - throw std::runtime_error("Set field comparison requires object values"); - std::string key; - for (const auto &field : fields) { - const auto found = item.find(field); - if (found == item.end()) - return {}; - key += - std::to_string(field.size()) + ':' + field + '=' + found->dump() + ';'; - } - return key; -} - -Keys keysOf(const Json::Value &set, const std::vector &fields, - bool requireComparable = true) { - Keys keys; - for (const auto &item : set) { - auto key = keyFor(item, fields); - if (!key.empty()) - keys.insert(std::move(key)); - } - if (requireComparable && !fields.empty() && !set.empty() && keys.empty()) - throw std::runtime_error( - "Set.by cannot compare an input set because no objects contain all " - "requested fields"); - return keys; -} - -Json::Value orderedUnique(const std::vector &sets, - const std::vector &fields, - const Keys *allowed = nullptr) { - auto result = Json::Value::array(); - Keys seen; - for (const auto *set : sets) { - for (const auto &item : *set) { - const auto comparisonKey = keyFor(item, fields); - if (comparisonKey.empty() || - (allowed && !allowed->contains(comparisonKey))) - continue; - if (seen.insert(item.dump()).second) - result.push_back(item); - } - } - return result; -} - -bool subset(const Json::Value &left, const Json::Value &right, - const std::vector &fields) { - const auto leftKeys = keysOf(left, fields); - const auto rightKeys = keysOf(right, fields); - return std::ranges::all_of( - leftKeys, [&](const auto &key) { return rightKeys.contains(key); }); -} - -} // namespace - -Json::Value evaluate(BuiltinId operation, const Json::Value &setsValue, - const std::optional &value, - const Json::Value &fieldsValue) { - const auto sets = inputSets(setsValue); - const auto fields = selectedFields(fieldsValue); - switch (operation) { - case BuiltinId::SetUnion: - return orderedUnique(sets, {}); - case BuiltinId::SetIntersection: - case BuiltinId::SetIntersectionBy: { - auto common = keysOf(*sets.front(), fields); - for (std::size_t index = 1; index < sets.size(); ++index) { - const auto keys = keysOf(*sets[index], fields); - std::erase_if(common, - [&](const auto &key) { return !keys.contains(key); }); - } - return orderedUnique(sets, fields, &common); - } - case BuiltinId::SetDifference: - case BuiltinId::SetDifferenceBy: { - Keys excluded; - for (std::size_t index = 1; index < sets.size(); ++index) { - const auto keys = keysOf(*sets[index], fields, false); - excluded.insert(keys.begin(), keys.end()); - } - auto result = Json::Value::array(); - Keys seen; - for (const auto &item : *sets.front()) { - const auto key = keyFor(item, fields); - if (!key.empty() && !excluded.contains(key) && - seen.insert(item.dump()).second) - result.push_back(item); - } - return result; - } - case BuiltinId::SetSymmetricDifference: - case BuiltinId::SetSymmetricDifferenceBy: { - std::vector allKeys; - allKeys.reserve(sets.size()); - for (const auto *set : sets) - allKeys.push_back(keysOf(*set, fields)); - Keys allowed; - for (const auto &keys : allKeys) { - for (const auto &key : keys) { - const auto occurrences = std::ranges::count_if( - allKeys, [&](const auto &other) { return other.contains(key); }); - if (occurrences != static_cast(allKeys.size())) - allowed.insert(key); - } - } - return orderedUnique(sets, fields, &allowed); - } - case BuiltinId::SetEquals: - case BuiltinId::SetEqualsBy: - case BuiltinId::SetSubset: - case BuiltinId::SetSubsetBy: - case BuiltinId::SetSuperset: - case BuiltinId::SetDisjoint: - case BuiltinId::SetDisjointBy: { - if (sets.size() != 2) - throw std::runtime_error("Set relation requires exactly two input sets"); - if (operation == BuiltinId::SetEquals || - operation == BuiltinId::SetEqualsBy) - return subset(*sets[0], *sets[1], fields) && - subset(*sets[1], *sets[0], fields); - if (operation == BuiltinId::SetSubset || - operation == BuiltinId::SetSubsetBy) - return subset(*sets[0], *sets[1], fields); - if (operation == BuiltinId::SetSuperset) - return subset(*sets[1], *sets[0], fields); - const auto left = keysOf(*sets[0], fields); - const auto right = keysOf(*sets[1], fields); - return std::ranges::none_of( - left, [&](const auto &key) { return right.contains(key); }); - } - case BuiltinId::SetCardinality: - if (sets.size() != 1) - throw std::runtime_error("Set.cardinality requires one input set"); - return static_cast(keysOf(*sets.front(), {}).size()); - case BuiltinId::SetContains: - case BuiltinId::SetContainsBy: { - if (sets.size() != 1 || !value) - throw std::runtime_error("Set.contains requires one set and a value"); - const auto keys = keysOf(*sets.front(), fields); - std::string wanted; - if (!fields.empty() && !value->is_object()) { - if (fields.size() != 1) - throw std::runtime_error( - "Set.containsBy scalar membership requires exactly one field"); - wanted = std::to_string(fields.front().size()) + ':' + fields.front() + - '=' + value->dump() + ';'; - } else { - wanted = keyFor(*value, fields); - } - return keys.contains(wanted); - } - default: - throw std::runtime_error("Unsupported Set operation"); - } -} - -} // namespace Felidae::Form::Set diff --git a/src/form/libs/Set.h b/src/form/libs/Set.h deleted file mode 100644 index a616e04..0000000 --- a/src/form/libs/Set.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "Json.h" -#include "form/BuiltinOperation.h" - -#include - -namespace Felidae::Form::Set { - -Json::Value evaluate(BuiltinId operation, const Json::Value &sets, - const std::optional &value = std::nullopt, - const Json::Value &fields = Json::Value::array()); - -} // namespace Felidae::Form::Set diff --git a/src/main.cpp b/src/main.cpp index 7b00d41..3c80cb5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,135 +1,311 @@ -#include "CompilerFrontend.h" -#include "IntegerTokenList.h" -#include "MixfixTraining.h" -#include "MixfixStateModel.h" -#include "ModelStore.h" -#include "SentencePieceModel.h" +#include "Interpreter.h" +#include "FelidaeRuntime.h" #include "Version.h" -#include "form/BinaryIr.h" +#include +#include +#include #include #include #include #include #include -#include - namespace fs = std::filesystem; using namespace Felidae; -namespace { -struct Options { fs::path input; std::optional mixfixModelDirectory; }; - -std::optional parseInput(int argc, char** argv) { - if (argc == 1 || (argc == 2 && std::string(argv[1]) == "--help")) return std::nullopt; - Options options; - for (int index = 1; index < argc; ++index) { - const std::string argument(argv[index]); - if (argument == "--mixfix-model") { - if (++index == argc) throw std::runtime_error("--mixfix-model requires a model directory"); - options.mixfixModelDirectory = fs::path(argv[index]); +struct CliOptions { + bool showHelp = false; + bool showVersion = false; + bool repl = false; + bool debug = false; + bool metricsJson = false; + size_t benchmarkRepeat = 1; + std::optional programFile; + std::optional query; + std::vector remainingArgs; +}; + +static CliOptions parseCli(int argc, char** argv) { + CliOptions options; + if (argc <= 1) { + options.showHelp = true; + return options; + } + + for (int i = 1; i < argc; ++i) { + std::string arg = argv[i]; + if (arg == "--help" || arg == "-h") { + options.showHelp = true; + return options; + } + if (arg == "--version" || arg == "-v") { + options.showVersion = true; + return options; + } + if (arg == "--repl") { + options.repl = true; + continue; + } + if (arg == "--debug") { + options.debug = true; + continue; + } + if (arg == "--metrics-json") { + options.metricsJson = true; + continue; + } + if (arg == "--visualize-data-json" || arg == "--visualize-data-html" || + arg == "--inspect-graph" || arg == "--load-imports") { + throw std::runtime_error( + "Visualization options are no longer supported"); + } + if (arg == "--benchmark-repeat") { + if (i + 1 >= argc) { + throw std::runtime_error("--benchmark-repeat expects a positive integer"); + } + const std::string count = argv[++i]; + size_t consumed = 0; + const unsigned long long parsed = std::stoull(count, &consumed); + if (consumed != count.size() || parsed == 0) { + throw std::runtime_error("--benchmark-repeat expects a positive integer"); + } + options.benchmarkRepeat = static_cast(parsed); + continue; + } + if (!options.programFile) { + options.programFile = fs::path(arg); continue; } - if (!options.input.empty()) throw std::runtime_error("felidae_compiler accepts exactly one .fx source file"); - options.input = argument; + if (!options.query && !arg.empty() && arg[0] == '?') { + options.query = arg; + continue; + } + options.remainingArgs.push_back(arg); } - if (options.input.empty()) throw std::runtime_error("felidae_compiler requires a .fx source file"); return options; } -void printHelp() { - std::cout << LANGUAGE_NAME << " compiler v" << LANGUAGE_VERSION << "\n\n" - << "Usage: felidae_compiler [--mixfix-model models/mixfix] program.fx\n" - << " felidae_compiler --tokenize input.fx\n" - << " felidae_compiler --train 'datasets/compiler/*.jsonl' --store-model build|dist [--epochs N] [--learning-rate R]\n" - << "Writes verified Felidae binary IR to the compiler directory.\n"; + +static const char* bannerText() { + return R"( ______ _ _ _ + | ____| | (_) | | + | |__ ___ | |_ __| | __ _ ___ + | __/ _ \| | |/ _` |/ _` |/ _ \ + | | | __/| | | (_| | (_| | __/ + |_| \___||_|_|\__,_|\__, |\___| + + :=Bow(:)|Grr(..)|Roar(<)|Meow(>). + +)"; } +// :=Bow(🐶)|Grr(🐯)|Roar(🦁)|Meow(🐱). -int tokenizeSource(const fs::path& input) { - const auto source = resolveProgramEntryPath(input); - if (source.extension() != FILE_EXTENSION) { - throw std::runtime_error("--tokenize accepts only .fx source files"); - } - const IntegerTokenList tokens(felidaeSentencePieceModel(), - Felidae::readSourceFile(source)); - std::cout << '['; - for (std::size_t index = 0; index < tokens.entries().size(); ++index) { - if (index != 0) std::cout << ','; - std::cout << tokens.entries()[index].id; - } - std::cout << "]\n"; - return 0; +static void printVersion() { + std::cout << LANGUAGE_NAME << " v" << LANGUAGE_VERSION << "\n"; } -int trainMixfixModel(const ModelTrainingOptions& training) { -#ifdef FELIDAE_HAS_TRAINING - const auto datasets = expandJsonlDatasetPaths(training.dataset); - const auto output = modelStoreDirectory(training.store, "mixfix-gru"); - const auto inputVocabulary = std::to_string(felidaeSentencePieceModel().GetPieceSize()); - const auto outputVocabulary = std::to_string(kMixfixStructuralVocabularySize); - std::vector arguments{ - "felidae_compiler", encodeDatasetPaths(datasets), output.string(), inputVocabulary, - outputVocabulary, "0", std::to_string(training.epochs), std::to_string(training.learningRate), - felidaeSentencePieceModelIdentity()}; - std::vector rawArguments; - rawArguments.reserve(arguments.size()); - for (auto& argument : arguments) rawArguments.push_back(argument.data()); - return runMixfixGruTraining(static_cast(rawArguments.size()), rawArguments.data()); -#else - (void)training; - throw std::runtime_error("this compiler build has training disabled; configure FELIDAE_ENABLE_TRAINING=ON"); -#endif +static void printHelp() { + std::cout << bannerText() << "\n" + << LANGUAGE_NAME << " v" << LANGUAGE_VERSION << "\n" + << LANGUAGE_DESCRIPTION << "\n\n" + << "File extension:\n" + << " " << FILE_EXTENSION << "\n\n" + << "Usage:\n" + << " felidae program.fx\n" + << " felidae program.fx '? Query(key: x)'\n" + << " felidae --repl program.fx\n" + << " felidae program.fx --repl\n" + << " felidae program.fx --debug\n" + << " felidae program.fx --metrics-json\n" + << " felidae program.fx --benchmark-repeat 100 --metrics-json\n" + << " felidae program.fx '? Query(key: x)' --benchmark-repeat 100 --metrics-json\n" + << " felidae --help\n" + << " felidae --version\n\n" + << "Commands:\n" + << " program.fx Run program and execute main(...) if found\n" + << " program.fx '? Query(key: x)' Run external query mode\n" + << " --repl program.fx Start interactive REPL\n" + << " program.fx --repl Start interactive REPL\n" + << " program.fx --debug Run with debug adapter diagnostics enabled\n" + << " --metrics-json Emit load and runtime performance counters to stderr\n" + << " --benchmark-repeat N Repeat the entry method or external query in one runtime\n" + << " --help Show this help screen\n" + << " --version Show version information\n\n" + << "Total commands supported: " << TOTAL_COMMANDS_SUPPORTED << "\n\n" + << "Examples:\n" + << " felidae examples/main.fx\n" + << " felidae examples/main.fx '? Person(name: x)'\n" + << " felidae --repl examples/main.fx\n"; +} + +static void runRepl(Interpreter& interpreter) { + std::cout << LANGUAGE_NAME << " v" << LANGUAGE_VERSION << "\n" + << LANGUAGE_DESCRIPTION << "\n" + << "Type 'help' for commands, 'exit' or 'quit' to leave.\n\n"; + std::string line; + while (true) { + std::cout << "felidae> "; + if (!std::getline(std::cin, line)) { + std::cout << "\n"; + break; + } + line = trim(line); + if (line.empty()) continue; + if (line == "exit" || line == "quit") break; + if (line == "version") { + printVersion(); + continue; + } + if (line == "help") { + std::cout << "REPL commands:\n" + << " ? Predicate(field: x) Run old-style query\n" + << " MethodName(args...) Invoke method\n" + << " GlobalName Print global value\n" + << " function(args...) Call built-in function\n" + << " help Show REPL help\n" + << " version Show version\n" + << " exit Exit REPL\n" + << " quit Exit REPL\n"; + continue; + } + + try { + if (!line.empty() && line[0] == '?') { + auto queryGoals = parseQueryText(line); + auto solutions = interpreter.solve(queryGoals, 1000); + printSolutions(interpreter, queryGoals, solutions, std::cout); + continue; + } + if (isBareIdentifier(line) && interpreter.hasGlobal(line)) { + std::cout << interpreter.valueToDisplayString(interpreter.evaluateGlobal(line)) << "\n"; + continue; + } + auto value = interpreter.evaluateExpressionText(line); + std::cout << interpreter.valueToDisplayString(value) << "\n"; + } catch (const std::exception& e) { + std::cout << "error: " << e.what() << "\n"; + } + } } -} // namespace int main(int argc, char** argv) { try { - if (argc == 2 && std::string(argv[1]) == "--version") { - std::cout << LANGUAGE_NAME << " compiler v" << LANGUAGE_VERSION << "\n"; + CliOptions options = parseCli(argc, argv); + if (options.showHelp) { + printHelp(); + return 0; + } + if (options.showVersion) { + printVersion(); return 0; } - if (argc == 3 && std::string(argv[1]) == "--tokenize") { - return tokenizeSource(argv[2]); - } - if (const auto training = parseModelTrainingOptions(argc, argv)) { - return trainMixfixModel(*training); - } - const auto input = parseInput(argc, argv); - if (!input) { printHelp(); return argc == 1 ? 1 : 0; } - const auto source = resolveProgramEntryPath(input->input); - if (source.extension() != FILE_EXTENSION) { - throw std::runtime_error("felidae_compiler accepts only .fx source files"); - } - CompilerOptions compilerOptions; -#ifdef FELIDAE_HAS_TORCH - std::optional mixfixModel; - if (input->mixfixModelDirectory) { - GruMixfixStateModel::Configuration configuration; - configuration.inputVocabularySize = felidaeSentencePieceModel().GetPieceSize(); - configuration.outputVocabularySize = - static_cast(kMixfixStructuralVocabularySize); - configuration.beginToken = 0; - mixfixModel.emplace(GruMixfixStateModel::loadVersioned( - configuration, *input->mixfixModelDirectory, felidaeSentencePieceModelIdentity())); - compilerOptions.mixfixModel = &*mixfixModel; - } -#else - if (input->mixfixModelDirectory) throw std::runtime_error("this compiler build has no LibTorch mixfix support"); -#endif - auto module = verifyIrModule(compileProgramFileToIr(source, compilerOptions)); - // Build artifacts never modify example/source directories or a staged - // distribution. The caller's existing build/ directory is the one - // canonical artifact location for both a developer build and the - // portable compiler. - const auto outputDirectory = fs::absolute(fs::path(argv[0])).lexically_normal().parent_path(); - fs::create_directories(outputDirectory); - auto output = outputDirectory / source.filename(); - output.replace_extension(kBinaryIrExtension); - writeBinaryIr(output, module); - std::cout << output.string() << "\n"; + if (!options.programFile) { + printHelp(); + return 1; + } + + using Clock = std::chrono::steady_clock; + const auto loadStarted = Clock::now(); + Interpreter interpreter; + fs::path entryFile = resolveProgramEntryPath(*options.programFile); + if (entryFile.extension() != FILE_EXTENSION) { + throw std::runtime_error("Felidae source files must use .fx extension"); + } + // A source file becomes executable only after its imports and every + // declaration have registered successfully. Running main while the + // parser was still producing chunks made later declarations invisible + // and could leave effects behind when a later error rejected the file. + // Registration remains streaming; publication is the execution boundary. + loadProgramRoot(entryFile, interpreter); + const auto executionStarted = Clock::now(); + double firstQueryMs = 0.0; + double repeatedQueryAverageMs = 0.0; + size_t measuredQueryRuns = 0; + auto reportMetrics = [&]() { + if (!options.metricsJson) return; + const auto finished = Clock::now(); + const auto loadMicros = std::chrono::duration_cast( + executionStarted - loadStarted).count(); + const auto executionMicros = std::chrono::duration_cast( + finished - executionStarted).count(); + std::cerr << "FELIDAE_METRICS {" + << "\"loadMs\":" << (static_cast(loadMicros) / 1000.0) << "," + << "\"executionMs\":" << (static_cast(executionMicros) / 1000.0) << "," + << "\"queryRuns\":" << measuredQueryRuns << "," + << "\"firstQueryMs\":" << firstQueryMs << "," + << "\"repeatedQueryAverageMs\":" << repeatedQueryAverageMs << "," + << "\"runtime\":" << interpreter.runtimeMetricsJson() + << "}\n"; + }; + if (options.debug) { + std::cerr << "Felidae debug mode enabled for " << entryFile.string() << "\n"; + } + + if (options.repl) { + runRepl(interpreter); + reportMetrics(); + return 0; + } + + if (options.query) { + auto queryGoals = parseQueryText(*options.query); + std::vector solutions; + double repeatedQueryTotalMs = 0.0; + for (size_t run = 0; run < options.benchmarkRepeat; ++run) { + const auto queryStarted = Clock::now(); + solutions = interpreter.solve(queryGoals, 1000); + const auto queryFinished = Clock::now(); + const double queryMs = static_cast( + std::chrono::duration_cast( + queryFinished - queryStarted).count()) / 1000000.0; + if (run == 0) { + firstQueryMs = queryMs; + } else { + repeatedQueryTotalMs += queryMs; + } + } + measuredQueryRuns = options.benchmarkRepeat; + if (options.benchmarkRepeat > 1) { + repeatedQueryAverageMs = + repeatedQueryTotalMs / static_cast(options.benchmarkRepeat - 1); + } + printSolutions(interpreter, queryGoals, solutions, std::cout); + reportMetrics(); + return 0; + } + + if (interpreter.hasMethod("main") || interpreter.hasAutoEntryCall()) { + std::shared_ptr result; + double repeatedEntryTotalMs = 0.0; + for (size_t run = 0; run < options.benchmarkRepeat; ++run) { + const auto entryStarted = Clock::now(); + result = interpreter.hasMethod("main") + ? interpreter.callMain(makeSystemInput(options.remainingArgs)) + : interpreter.callAutoEntry(); + const double entryMs = static_cast( + std::chrono::duration_cast( + Clock::now() - entryStarted).count()) / 1000000.0; + if (run == 0) { + firstQueryMs = entryMs; + } else { + repeatedEntryTotalMs += entryMs; + } + } + measuredQueryRuns = options.benchmarkRepeat; + if (options.benchmarkRepeat > 1) { + repeatedQueryAverageMs = + repeatedEntryTotalMs / static_cast(options.benchmarkRepeat - 1); + } + std::cout << interpreter.valueToDisplayString(result) << "\n"; + } else { + std::cout << "Program loaded successfully. No main() method found.\n" + << "Use a query argument, add a zero-argument entry call, or run with --repl.\n"; + } + + reportMetrics(); return 0; - } catch (const std::exception& error) { - std::cerr << "error: " << error.what() << "\n"; + } catch (const std::exception& e) { + std::cerr << "error: " << e.what() << "\n"; return 1; } } diff --git a/src/tooling/SourceParser.cpp b/src/tooling/SourceParser.cpp deleted file mode 100644 index adf9543..0000000 --- a/src/tooling/SourceParser.cpp +++ /dev/null @@ -1,243 +0,0 @@ -#include "tooling/SourceParser.h" - -#include "CompilerFrontend.h" - -#include -#include -#include - -namespace fs = std::filesystem; - -namespace Felidae::Tooling { - -namespace { - -fs::path findProjectRoot(fs::path start) { - std::error_code ec; - start = fs::absolute(start, ec).lexically_normal(); - if (ec) - return {}; - if (!fs::is_directory(start, ec)) - start = start.parent_path(); - while (!start.empty()) { - if (fs::is_directory(start / "core", ec) && - fs::is_directory(start / "src", ec)) { - return start; - } - const fs::path parent = start.parent_path(); - if (parent == start) - break; - start = parent; - } - return {}; -} - -void addFxFiles(const fs::path &directory, std::vector &files) { - std::error_code ec; - if (!fs::is_directory(directory, ec)) - return; - for (fs::recursive_directory_iterator it(directory, ec), end; - !ec && it != end; it.increment(ec)) { - if (it->is_regular_file(ec) && it->path().extension() == ".fx") { - files.push_back(fs::absolute(it->path()).lexically_normal()); - } - } -} - -std::vector resolveImport(const fs::path &baseDir, - const fs::path &projectRoot, - const std::string &importName) { - std::vector files; - std::vector candidates; - const bool wildcard = importName.find('*') != std::string::npos; - std::string normalizedName = importName; - std::replace(normalizedName.begin(), normalizedName.end(), ':', '/'); - - if (wildcard) { - const auto star = normalizedName.find('*'); - fs::path relativeDirectory = normalizedName.substr(0, star); - candidates.push_back(baseDir / relativeDirectory); - if (!projectRoot.empty()) { - candidates.push_back(projectRoot / relativeDirectory); - candidates.push_back(projectRoot / "core" / relativeDirectory); - candidates.push_back(projectRoot / "stdlib" / relativeDirectory); - } - for (const auto &candidate : candidates) - addFxFiles(candidate, files); - } else { - fs::path relative = normalizedName; - candidates.push_back(baseDir / relative); - if (relative.extension().empty()) - candidates.push_back(baseDir / (relative.string() + ".fx")); - if (!projectRoot.empty()) { - candidates.push_back(projectRoot / relative); - candidates.push_back(projectRoot / "core" / relative); - candidates.push_back(projectRoot / "stdlib" / relative); - if (relative.extension().empty()) { - candidates.push_back(projectRoot / (relative.string() + ".fx")); - candidates.push_back(projectRoot / "core" / - (relative.string() + ".fx")); - candidates.push_back(projectRoot / "stdlib" / - (relative.string() + ".fx")); - } - } - std::error_code ec; - for (const auto &candidate : candidates) { - if (fs::is_regular_file(candidate, ec)) { - files.push_back(fs::absolute(candidate).lexically_normal()); - break; - } - if (fs::is_directory(candidate, ec)) { - addFxFiles(candidate, files); - break; - } - } - } - - std::sort(files.begin(), files.end()); - files.erase(std::unique(files.begin(), files.end()), files.end()); - return files; -} - -std::vector scanImports(const fs::path &file) { - std::vector imports; - const Program program = parseProgramFile(file); - for (const auto &statement : program.imports) { - imports.insert(imports.end(), statement->paths.begin(), - statement->paths.end()); - } - return imports; -} - -struct SourceGraph { - std::vector dependencyOrder; - std::vector unresolvedImports; -}; - -SourceGraph collectSourceGraph(const fs::path &entry, - const fs::path &projectRoot, bool loadImports) { - SourceGraph graph; - std::set visited; - std::set visiting; - const auto visit = [&](const auto &self, fs::path file) -> void { - file = fs::absolute(file).lexically_normal(); - if (visited.count(file) > 0) - return; - if (!visiting.insert(file).second) - return; - if (loadImports) { - for (const auto &importName : scanImports(file)) { - auto resolved = - resolveImport(file.parent_path(), projectRoot, importName); - if (resolved.empty()) { - graph.unresolvedImports.push_back(importName); - continue; - } - for (const auto &dependency : resolved) - self(self, dependency); - } - } - visiting.erase(file); - visited.insert(file); - graph.dependencyOrder.push_back(std::move(file)); - }; - visit(visit, entry); - std::sort(graph.unresolvedImports.begin(), graph.unresolvedImports.end()); - graph.unresolvedImports.erase(std::unique(graph.unresolvedImports.begin(), - graph.unresolvedImports.end()), - graph.unresolvedImports.end()); - return graph; -} - -void parseFileWithRegistry( - const fs::path &file, const std::shared_ptr &operators, - const std::function)> &consume) { - Program program = - parseProgramText(readSourceFile(file), operators, CompilerOptions{}); - for (auto &statement : program.statements) - consume(std::move(statement)); -} - -} // namespace - -Program parseText(std::string text) { - return parseProgramText(std::move(text)); -} - -Program parseFile(const fs::path &path) { - Program program; - parseFileStatements(path, [&](std::shared_ptr statement) { - program.addStatement(std::move(statement)); - }); - return program; -} - -void parseFileStatements( - const fs::path &path, - const std::function)> &consume) { - const fs::path entry = resolveEntryPath(path); - Program program = parseProgramFile(entry); - for (auto &statement : program.statements) - consume(std::move(statement)); -} - -fs::path resolveEntryPath(const fs::path &path) { - const auto resolved = resolveProgramEntryPath(path); - std::error_code ec; - if (!fs::is_regular_file(resolved, ec)) - throw std::runtime_error("Cannot open file: " + resolved.string()); - return resolved; -} - -LoadedProgram loadProgram(const fs::path &entryFile, bool loadImports) { - LoadedProgram loaded; - const fs::path entry = resolveEntryPath(entryFile); - const fs::path projectRoot = findProjectRoot(entry); - auto graph = collectSourceGraph(entry, projectRoot, loadImports); - loaded.files = graph.dependencyOrder; - loaded.unresolvedImports = std::move(graph.unresolvedImports); - loaded.operators = std::make_shared(); - for (const auto &file : graph.dependencyOrder) { - parseFileWithRegistry(file, loaded.operators, - [&](std::shared_ptr statement) { - loaded.program.addStatement(std::move(statement)); - }); - } - return loaded; -} - -LoadedSources loadProgramStatements( - const fs::path &entryFile, bool loadImports, - const std::function &)> &consume) { - LoadedSources loaded; - const fs::path entry = resolveEntryPath(entryFile); - const fs::path projectRoot = findProjectRoot(entry); - auto graph = collectSourceGraph(entry, projectRoot, loadImports); - loaded.files = graph.dependencyOrder; - loaded.unresolvedImports = std::move(graph.unresolvedImports); - loaded.operators = std::make_shared(); - for (const auto &file : graph.dependencyOrder) { - parseFileWithRegistry(file, loaded.operators, consume); - } - return loaded; -} - -std::vector listCoreLibraries(const fs::path &startDir) { - std::vector names; - const fs::path root = findProjectRoot(startDir); - if (root.empty()) - return names; - std::error_code ec; - const fs::path core = root / "core"; - for (fs::directory_iterator it(core, ec), end; !ec && it != end; - it.increment(ec)) { - if (it->is_regular_file(ec) && it->path().extension() == ".fx") { - names.push_back(it->path().stem().string()); - } - } - std::sort(names.begin(), names.end()); - names.erase(std::unique(names.begin(), names.end()), names.end()); - return names; -} - -} // namespace Felidae::Tooling diff --git a/src/tooling/SourceParser.h b/src/tooling/SourceParser.h deleted file mode 100644 index 28cffba..0000000 --- a/src/tooling/SourceParser.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include "AST.h" - -#include -#include -#include -#include - -namespace Felidae::Tooling { - -struct LoadedProgram { - Program program; - std::vector files; - std::vector unresolvedImports; - std::shared_ptr operators; -}; - -struct LoadedSources { - std::vector files; - std::vector unresolvedImports; - std::shared_ptr operators; -}; - -Program parseText(std::string text); -Program parseFile(const std::filesystem::path& path); -void parseFileStatements( - const std::filesystem::path& path, - const std::function)>& consume); -LoadedProgram loadProgram(const std::filesystem::path& entryFile, bool loadImports); -LoadedSources loadProgramStatements( - const std::filesystem::path& entryFile, - bool loadImports, - const std::function&)>& consume); -std::filesystem::path resolveEntryPath(const std::filesystem::path& path); -std::vector listCoreLibraries(const std::filesystem::path& startDir); - -} // namespace Felidae::Tooling From 9d71b4b63bd02f7b791372ec2ec5b285248e193e Mon Sep 17 00:00:00 2001 From: vishalkrishnaag Date: Sat, 12 Sep 2026 02:19:12 +0000 Subject: [PATCH 4/6] rewamp started --- CMakeLists.txt | 96 + README.md | 3301 +--------- build.ps1 | 78 +- build.sh | 222 +- cmake/BetaReleaseCheck.cmake | 100 - cmake/StageDistribution.cmake | 119 - code.md | 55 +- core/csv.fx | 3 +- core/db.fx | 4 + core/group.fx | 3 +- core/json.fx | 3 +- core/set.fx | 2 +- datasets/compiler/README.md | 58 - datasets/compiler/mixfix-invalid-v1.jsonl | 22 - datasets/compiler/mixfix-v1.jsonl | 196 - datasets/vm/README.md | 52 - datasets/vm/runtime-context-v1.jsonl | 15 - docs/README.md | 22 +- docs/builtin-docs.json | 8 +- docs/compiler_form_audit.md | 87 - docs/executable_ir.md | 98 - docs/library_pages.fx | 75 - docs/native_modules.fx | 5 - docs/playground.fx | 2 +- docs/reasoning_benchmark.md | 222 - docs/stdlib.fx | 16 - docs/testing.fx | 13 - docs_language.md | 795 +-- models/README.md | 28 +- models/felidae-bpe/README.md | 11 + models/felidae-bpe/model.txt | 544 ++ src/AST.h | 1847 +++--- src/BuiltinRegistry.cpp | 496 +- src/BuiltinRegistry.h | 9 - src/CompilerFrontend.cpp | 357 -- src/CompilerFrontend.h | 41 - src/FelidaeGrammar.h | 577 +- src/FelidaeIr.h | 98 - src/FelidaeRuntime.cpp | 12 +- src/FelidaeTokenizerIds.h | 162 + src/IntegerParser.cpp | 3293 ++++------ src/IntegerParser.h | 52 +- src/IntegerTokenList.cpp | 126 +- src/IntegerTokenList.h | 14 +- src/Interpreter.cpp | 6634 +++++++++++++++++++- src/Interpreter.h | 8 + src/IrCodeGenerator.cpp | 2995 --------- src/IrCodeGenerator.h | 27 - src/Memory.cpp | 25 + src/Memory.h | 5 + src/MixfixStateModel.cpp | 618 -- src/MixfixStateModel.h | 166 - src/MixfixTraining.h | 9 - src/ModelStore.h | 225 - src/NativeJson.h | 310 + src/NativeRuntime.cpp | 2 +- src/Operator.h | 2 +- src/ReasoningRuntime.cpp | 1196 ++++ src/SentencePieceModel.cpp | 172 - src/SentencePieceModel.h | 19 - src/Symbol.h | 227 +- src/Tokenizer.cpp | 276 + src/Tokenizer.h | 57 + src/VmMain.cpp | 265 - src/debugger/AstAnalyzer.cpp | 585 -- src/debugger/AstAnalyzer.h | 61 - src/debugger/main.cpp | 1210 ---- src/main.cpp | 76 + tests/ExecutionVectorMemoryTest.cpp | 35 - tests/FelidaeIrTest.cpp | 888 --- tests/FormBinaryIrTest.cpp | 76 - tests/FormDbCsvTest.cpp | 582 -- tests/FormIsolationTest.cpp | 36 - tests/LibTorchSmoke.cpp | 171 - tests/MixfixStateModelTest.cpp | 1098 ---- tests/RocksDbTest.cpp | 489 -- tests/SentencePieceModelTest.cpp | 414 -- tests/SentencePiecePipelineTest.cpp | 1505 ----- tests/direct_ast_smoke.fx | 5 + tests/direct_class_end.fx | 18 + tests/direct_class_fact_value.fx | 13 + tests/direct_db_sync.fx | 3 + tests/direct_fact_mutation.fx | 7 + tests/direct_fact_selection.fx | 9 + tests/direct_sync_source.fx | 1 + tools/BuildRuntimeTrainingDataset.cpp | 85 - tools/ExtractMixfixDataset.cpp | 638 -- tools/FactStoreBenchmark.cpp | 145 - tools/GenerateSentencePieceModel.cpp | 185 - tools/IntegerParserBenchmark.cpp | 130 - tools/ReasoningBenchmark.cpp | 127 - tools/TrainMixfixGru.cpp | 392 -- tools/TrainRuntimeGru.cpp | 221 - v2_examples/class_association_reasoning.fx | 10 +- v2_examples/csv_fact_database.fx | 4 +- v2_examples/end_then_pipeline.fx | 5 +- v2_examples/form_core_concepts.fx | 59 - v2_examples/fx_fact_database.fx | 6 +- v2_examples/mixfix_deep_ir_nesting.fx | 25 - v2_examples/mixfix_fuzzy_fact_report.fx | 2 +- v2_examples/mixfix_ir_roundtrip.fx | 9 - v2_examples/optional_end_blocks.fx | 5 +- v2_examples/runtime_ssm_e2e.fx | 3 - v2_examples/sentencepiece_pipeline.fx | 3 - v2_examples/where_guard_chain.fx | 5 +- 105 files changed, 12513 insertions(+), 23405 deletions(-) create mode 100644 CMakeLists.txt mode change 100755 => 100644 build.sh delete mode 100644 cmake/BetaReleaseCheck.cmake delete mode 100644 cmake/StageDistribution.cmake create mode 100644 core/db.fx delete mode 100644 datasets/compiler/README.md delete mode 100644 datasets/compiler/mixfix-invalid-v1.jsonl delete mode 100644 datasets/compiler/mixfix-v1.jsonl delete mode 100644 datasets/vm/README.md delete mode 100644 datasets/vm/runtime-context-v1.jsonl delete mode 100644 docs/compiler_form_audit.md delete mode 100644 docs/executable_ir.md delete mode 100644 docs/library_pages.fx delete mode 100644 docs/native_modules.fx delete mode 100644 docs/reasoning_benchmark.md delete mode 100644 docs/stdlib.fx delete mode 100644 docs/testing.fx create mode 100644 models/felidae-bpe/README.md create mode 100644 models/felidae-bpe/model.txt delete mode 100644 src/CompilerFrontend.cpp delete mode 100644 src/CompilerFrontend.h delete mode 100644 src/FelidaeIr.h create mode 100644 src/FelidaeTokenizerIds.h delete mode 100644 src/IrCodeGenerator.cpp delete mode 100644 src/IrCodeGenerator.h delete mode 100644 src/MixfixStateModel.cpp delete mode 100644 src/MixfixStateModel.h delete mode 100644 src/MixfixTraining.h delete mode 100644 src/ModelStore.h create mode 100644 src/NativeJson.h create mode 100644 src/ReasoningRuntime.cpp delete mode 100644 src/SentencePieceModel.cpp delete mode 100644 src/SentencePieceModel.h create mode 100644 src/Tokenizer.cpp create mode 100644 src/Tokenizer.h delete mode 100644 src/VmMain.cpp delete mode 100644 src/debugger/AstAnalyzer.cpp delete mode 100644 src/debugger/AstAnalyzer.h delete mode 100644 src/debugger/main.cpp delete mode 100644 tests/ExecutionVectorMemoryTest.cpp delete mode 100644 tests/FelidaeIrTest.cpp delete mode 100644 tests/FormBinaryIrTest.cpp delete mode 100644 tests/FormDbCsvTest.cpp delete mode 100644 tests/FormIsolationTest.cpp delete mode 100644 tests/LibTorchSmoke.cpp delete mode 100644 tests/MixfixStateModelTest.cpp delete mode 100644 tests/RocksDbTest.cpp delete mode 100644 tests/SentencePieceModelTest.cpp delete mode 100644 tests/SentencePiecePipelineTest.cpp create mode 100644 tests/direct_ast_smoke.fx create mode 100644 tests/direct_class_end.fx create mode 100644 tests/direct_class_fact_value.fx create mode 100644 tests/direct_db_sync.fx create mode 100644 tests/direct_fact_mutation.fx create mode 100644 tests/direct_fact_selection.fx create mode 100644 tests/direct_sync_source.fx delete mode 100644 tools/BuildRuntimeTrainingDataset.cpp delete mode 100644 tools/ExtractMixfixDataset.cpp delete mode 100644 tools/FactStoreBenchmark.cpp delete mode 100644 tools/GenerateSentencePieceModel.cpp delete mode 100644 tools/IntegerParserBenchmark.cpp delete mode 100644 tools/ReasoningBenchmark.cpp delete mode 100644 tools/TrainMixfixGru.cpp delete mode 100644 tools/TrainRuntimeGru.cpp delete mode 100644 v2_examples/form_core_concepts.fx delete mode 100644 v2_examples/mixfix_deep_ir_nesting.fx delete mode 100644 v2_examples/mixfix_ir_roundtrip.fx delete mode 100644 v2_examples/runtime_ssm_e2e.fx delete mode 100644 v2_examples/sentencepiece_pipeline.fx diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..1a7870b --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,96 @@ +cmake_minimum_required(VERSION 3.21) +project(felidae LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +option(FELIDAE_BUILD_TESTS "Build Felidae regression tests" ON) +option(FELIDAE_ENABLE_SANITIZERS "Enable address and undefined behavior sanitizers" OFF) +option(FELIDAE_ENABLE_STRICT_WARNINGS "Enable strict warnings" OFF) + +function(felidae_common target) + target_include_directories(${target} PRIVATE + ${CMAKE_SOURCE_DIR}/src + ${CMAKE_SOURCE_DIR}/models) + if(UNIX AND NOT APPLE) + target_link_libraries(${target} PRIVATE dl) + endif() + if(FELIDAE_ENABLE_SANITIZERS) + target_compile_options(${target} PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(${target} PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer) + endif() +endfunction() + +add_executable(felidae + src/main.cpp + src/FelidaeRuntime.cpp + src/IntegerParser.cpp + src/IntegerTokenList.cpp + src/Tokenizer.cpp + src/BuiltinRegistry.cpp + src/Interpreter.cpp + src/ReasoningRuntime.cpp + src/Env.cpp + src/Memory.cpp + src/NativeRuntime.cpp) +felidae_common(felidae) +target_compile_definitions(felidae PRIVATE + FELIDAE_TOKENIZER_MODEL_PATH="${CMAKE_SOURCE_DIR}/models/felidae-bpe/model.txt") +target_compile_options(felidae PRIVATE + $<$:-Wall -Wextra -Wnon-virtual-dtor -Wold-style-cast -Woverloaded-virtual>) + +if(FELIDAE_BUILD_TESTS) + enable_testing() + add_test(NAME direct_ast_smoke + COMMAND felidae ${CMAKE_SOURCE_DIR}/tests/direct_ast_smoke.fx) + set_tests_properties(direct_ast_smoke PROPERTIES + PASS_REGULAR_EXPRESSION "answer: 42.*literal: 42.*decimal: 3.14") + + add_test(NAME direct_ast_fact_query + COMMAND felidae ${CMAKE_SOURCE_DIR}/tests/direct_ast_smoke.fx "? fact(name: x)") + set_tests_properties(direct_ast_fact_query PROPERTIES + PASS_REGULAR_EXPRESSION "x = \"tiger\"") + + add_test(NAME direct_ast_rejects_binary + COMMAND felidae ${CMAKE_BINARY_DIR}/legacy.bin) + set_tests_properties(direct_ast_rejects_binary PROPERTIES + WILL_FAIL TRUE) + + add_test(NAME direct_ast_fact_mutation + COMMAND felidae ${CMAKE_SOURCE_DIR}/tests/direct_fact_mutation.fx) + set_tests_properties(direct_ast_fact_mutation PROPERTIES + PASS_REGULAR_EXPRESSION "inserted:.*Temporary.*updated: 1.*deleted: 1.*active: 0") + + add_test(NAME direct_ast_db_sync + COMMAND felidae ${CMAKE_SOURCE_DIR}/tests/direct_db_sync.fx) + set_tests_properties(direct_ast_db_sync PROPERTIES + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests + PASS_REGULAR_EXPRESSION "synchronized: 1.*Synced") + + add_test(NAME direct_ast_fact_selection + COMMAND felidae ${CMAKE_SOURCE_DIR}/tests/direct_fact_selection.fx) + set_tests_properties(direct_ast_fact_selection PROPERTIES + PASS_REGULAR_EXPRESSION "or_count: 3.*and_count: 1.*limited: [[]School") + + add_test(NAME direct_ast_mixfix + COMMAND felidae ${CMAKE_SOURCE_DIR}/v2_examples/mixfix_nested_expression.fx) + set_tests_properties(direct_ast_mixfix PROPERTIES + PASS_REGULAR_EXPRESSION "direct: Validation") + + add_test(NAME direct_ast_class_end + COMMAND felidae ${CMAKE_SOURCE_DIR}/tests/direct_class_end.fx) + set_tests_properties(direct_ast_class_end PROPERTIES + PASS_REGULAR_EXPRESSION "count: 1.*answer: 42") + + add_test(NAME direct_ast_class_mixfix + COMMAND felidae ${CMAKE_SOURCE_DIR}/v2_examples/class_association_reasoning.fx) + set_tests_properties(direct_ast_class_mixfix PROPERTIES + PASS_REGULAR_EXPRESSION "Association.*works at") + + add_test(NAME direct_ast_class_fact_value + COMMAND felidae ${CMAKE_SOURCE_DIR}/tests/direct_class_fact_value.fx) + set_tests_properties(direct_ast_class_fact_value PROPERTIES + PASS_REGULAR_EXPRESSION "person: Person.*from_array: Person.*name: \"Ada\"") +endif() diff --git a/README.md b/README.md index 67d57bb..e608625 100644 --- a/README.md +++ b/README.md @@ -1,3286 +1,45 @@ -
- - - - - Felidae - - # Felidae -### A reasoning language for facts, relationships, degrees, rules, and intelligent software. - -**Felidae combines programming, structured knowledge, fuzzy reasoning, and carefully controlled learned behavior in a fast C++ language and runtime.** - -
- -[![Status](https://img.shields.io/badge/status-beta-F59E0B?style=for-the-badge)](#beta-status) -[![Version](https://img.shields.io/badge/version-0.2.3--beta.1-7C3AED?style=for-the-badge)](#beta-status) -[![C++](https://img.shields.io/badge/C%2B%2B-20-00599C?style=for-the-badge\&logo=cplusplus)](#building-felidae) -[![CMake](https://img.shields.io/badge/CMake-3.21%2B-064F8C?style=for-the-badge\&logo=cmake)](#building-felidae) -[![License](https://img.shields.io/badge/license-MIT-22C55E?style=for-the-badge)](./LICENCE) - -
- -[🌐 Website](https://felidae.xnovity.com) -  •   -[📚 Documentation](./docs) -  •   -[🧪 Examples](./v2_examples) -  •   -[🤝 Contributing](./CONTRIBUTING.md) -  •   -[🔐 Security](./SECURITY.md) - -
- ---- - -> [!IMPORTANT] -> **Felidae is currently beta software.** -> -> It is intended for development, evaluation, experimentation, research, and non-critical workflows. -> -> Production use is **not currently recommended**. Do not make safety-critical, medical, legal, financial, security-critical, or other high-risk decisions solely from Felidae outputs while the project remains in beta. - ---- - -## Welcome to Felidae - -Most programming languages are excellent at answering questions such as: - -```text -What instruction should execute next? -What value should this function return? -Is this condition true or false? -``` - -But many real-world systems need to ask broader questions: - -```text -What do we know? - -How are these facts related? - -Does this item belong to this category? - -How strongly does something match? - -What can be derived from the information available? - -What if an answer is partially true rather than simply true or false? - -Can different kinds of evidence be combined? - -Can a program work with relationships and knowledge directly? -``` - -**Felidae is an experiment in building a programming language around those kinds of problems.** - -It combines familiar programming ideas with: - -* structured facts, -* relationships, -* hierarchy, -* degrees, -* fuzzy reasoning, -* queries, -* custom expressions, -* deterministic computation, -* and optional learned semantic evaluation. - -The intention is not to make ordinary programming unnecessarily complicated. - -The intention is to give developers another way to build software when the problem naturally involves **knowledge and reasoning**, rather than only instructions and data transformations. - ---- - -## ✨ Felidae in one sentence - -> **Felidae is a C++ reasoning language and runtime that lets software work directly with facts, relationships, degrees, and rules while keeping ordinary execution predictable.** - ---- - -## Table of contents - -* [Why Felidae?](#why-felidae) -* [What makes Felidae different?](#what-makes-felidae-different) -* [What Felidae can be useful for](#what-felidae-can-be-useful-for) -* [Felidae at a glance](#felidae-at-a-glance) -* [A quick feel for the language](#a-quick-feel-for-the-language) -* [Facts](#facts) -* [Relationships and hierarchy](#relationships-and-hierarchy) -* [Degrees and fuzzy reasoning](#degrees-and-fuzzy-reasoning) -* [Queries and fact traversal](#queries-and-fact-traversal) -* [Methods and ordinary programming](#methods-and-ordinary-programming) -* [Flexible expressions and mixfix](#flexible-expressions-and-mixfix) -* [Numeric operations](#numeric-operations) -* [Tensor operations](#tensor-operations) -* [Reasoning and proof-style workflows](#reasoning-and-proof-style-workflows) -* [Deterministic and learned behavior](#deterministic-and-learned-behavior) -* [How Felidae works](#how-felidae-works) -* [Compiler and VM separation](#compiler-and-vm-separation) -* [Verified binary programs](#verified-binary-programs) -* [Beta status](#beta-status) -* [Quick start](#quick-start) -* [Requirements](#requirements) -* [Building Felidae](#building-felidae) -* [Linux and WSL](#linux-and-wsl) -* [Windows](#windows) -* [macOS](#macos) -* [Android and cross-compilation](#android-and-cross-compilation) -* [Running a program](#running-a-program) -* [Long-lived VM mode](#long-lived-vm-mode) -* [Working examples](#working-examples) -* [Repository structure](#repository-structure) -* [Dependencies](#dependencies) -* [Testing](#testing) -* [Debugging](#debugging) -* [Code quality](#code-quality) -* [LibTorch](#libtorch) -* [SentencePiece and the tokenizer](#sentencepiece-and-the-tokenizer) -* [Compiler recurrent model](#compiler-recurrent-model) -* [VM recurrent model](#vm-recurrent-model) -* [Training](#training) -* [Release builds](#release-builds) -* [Documentation](#documentation) -* [Editor support](#editor-support) -* [Development principles](#development-principles) -* [Project maturity](#project-maturity) -* [Security](#security) -* [Contributing](#contributing) -* [FAQ](#frequently-asked-questions) -* [License](#license) -* [Project](#project) - ---- - -# Why Felidae? - -Software increasingly works with information that is more complicated than a simple boolean condition. - -Consider statements such as: - -* this customer is **similar** to another customer, -* this observation has **high confidence**, -* this employee belongs to a broader organizational category, -* this product is **partially relevant** to a request, -* this fact is inherited from a more general category, -* several pieces of evidence support a conclusion, -* one explanation is stronger than another, -* a condition is almost satisfied but does not cross a final threshold. - -Traditional programming can represent all of these things. - -But developers often have to manually build layers of: - -```text -objects -+ -rules -+ -database queries -+ -classification logic -+ -scoring systems -+ -relationship graphs -+ -application-specific conventions -``` - -Felidae explores whether some of those ideas can live directly inside the language and runtime. - -Instead of treating reasoning as an external feature bolted onto an application, Felidae makes concepts such as **facts, hierarchy, degrees, and queries part of the programming model itself**. - ---- - -# What makes Felidae different? - -Felidae is not designed around one single feature. - -Its identity comes from combining several ideas. - -| Capability | What it means | -| ---------------------------- | --------------------------------------------------------------------------- | -| 🐾 **Facts** | Structured knowledge can exist directly in the language | -| 🌳 **Hierarchy** | Facts and types can have broader and more specific relationships | -| 🌗 **Degrees** | Values do not always need to collapse immediately into `true` or `false` | -| 🔎 **Queries** | Programs can work with groups of known facts | -| 🧠 **Reasoning** | Facts, rules, hierarchy and evidence can participate in reasoning workflows | -| 🧩 **Flexible expressions** | Domain-oriented expressions can be expressed using mixfix forms | -| ⚙️ **Deterministic runtime** | Ordinary computation remains predictable | -| 🔬 **Controlled learning** | Learned behavior is limited to explicit, validated parts of the system | -| 📦 **Compiled programs** | `.fx` source is compiled before execution | -| 🛡️ **Verification** | Compiled programs are checked before the VM accepts them | -| 🚀 **C++ runtime** | The compiler and VM are implemented primarily in modern C++ | - ---- - -# What Felidae can be useful for - -Felidae is experimental, but its design is particularly relevant to software involving: - -### Expert systems - -Applications where knowledge and rules are evaluated together. - -Examples: - -* diagnosis-like workflows, -* recommendation rules, -* configuration reasoning, -* operational decision support, -* policy evaluation. - -### Knowledge-oriented software - -Systems where relationships between facts are as important as the facts themselves. - -Examples: - -* organizational knowledge, -* product hierarchies, -* scientific classifications, -* domain models, -* knowledge graphs. - -### Fuzzy decision systems - -Applications where there is meaningful information between `false` and `true`. - -Examples: - -* similarity, -* suitability, -* confidence, -* membership, -* relevance, -* preference, -* quality scoring. - -### Rule engines - -Systems with domain rules that need more expressive structure than a large collection of application-level `if` statements. - -### Contextual evaluation - -Programs that evaluate information differently depending on the surrounding facts or state. - -### Reasoning research - -Experiments involving: - -* hierarchical reasoning, -* evidence, -* partial truth, -* alternate proofs, -* semantic evaluation, -* symbolic structures, -* learned assistance. - -### Domain-specific languages - -Felidae's custom/mixfix expression support can make certain domain concepts more readable than ordinary function calls. - -### Analytical systems - -Felidae can combine: - -* facts, -* numeric operations, -* degree calculations, -* tensors, -* hierarchy, -* and rule execution. - ---- - -# Felidae at a glance - -```text -File extension .fx - -Implementation C++20 - -Build system CMake - -Main components Compiler + Form VM - -Program output Verified .bin executable - -Reasoning model Facts + hierarchy + degrees + explicit semantics - -ML backend LibTorch - -Tokenizer SentencePiece - -Primary status Beta - -Current beta 0.2.3-beta.1 - -License MIT -``` - ---- - -# A quick feel for the language - -Felidae can still look familiar to someone who has used ordinary programming languages. - -For example: - -```felidae -Person(name: "unknown", age: 0, active: 0.0) - -Employee extend Person( - name: "unknown", - age: 0, - active: 1.0, - role: "staff" -) - -Engineer extend Employee( - name: "unknown", - age: 0, - active: 1.0, - role: "engineer", - level: 1 -) -``` - -A function can look like: - -```felidae -increment(value: number) => - - return value + 1 -``` - -Functions may call other functions: - -```felidae -double(value: number) => - - return value * 2 - -scoreFor(age: number, level: number) => - - base := double(value: age) - - return base + level -``` - -Recursion is also represented in the current examples: - -```felidae -factorial(value: number) => - - if value <= 1 then - - return 1 - - else - - previous := factorial(value: value - 1) - - return value * previous -``` - -And programs can return structured values: - -```felidae -return { - name: "Felidae", - active: 1.0, - tags: ["facts", "reasoning", "degrees"] -} -``` - -So Felidae is not only a rule notation. - -It remains a programming language while adding reasoning-oriented concepts. - ---- - -# Facts - -Facts are one of the central ideas in Felidae. - -A declaration such as: - -```felidae -Person( - name: "Ada", - age: 32, - active: 1.0 -) -``` - -represents structured information that can participate in runtime operations. - -A fact may contain: - -* names, -* numbers, -* numeric truth values (`0.0` and `1.0`), -* strings, -* arrays, -* maps, -* degree values, -* and other supported values. - -Facts can then become part of: - -* queries, -* hierarchy, -* loops, -* comparisons, -* reasoning, -* reporting, -* semantic evaluation. - -This is different from treating a fact as merely an application-specific JSON document. - -Felidae understands the fact as part of the language/runtime model. - ---- - -# Relationships and hierarchy - -Felidae supports relationships between fact types. - -For example: - -```felidae -Animal(name: "generic") - -Dog extend Animal(name: "fido") - -Cat extend Animal(name: "milo") -``` - -Here: - -```text -Animal -├── Dog -└── Cat -``` - -This allows broader operations to include more specific types. - -Instead of manually writing logic such as: - -```text -if object is Animal -or object is Dog -or object is Cat -... -``` - -a hierarchy-aware operation can start from `Animal`. - -This becomes especially useful when the hierarchy becomes deeper. - -For example: - -```text -Person -└── Employee - └── Engineer -``` - -A system can work with the broader concept while still preserving the more specific type. - ---- - -# Degrees and fuzzy reasoning - -Felidae represents crisp truth with floating-point values: - -```text -0.0 -1.0 -``` - -That is ideal for many problems. - -For example: - -```text -Is 10 greater than 5? → 1.0 -``` - -But other questions are naturally gradual. - -For example: - -```text -How similar are these values? - -How strongly does this score belong to this category? - -How confident is this observation? - -How close is a value to the ideal? -``` - -Felidae allows these kinds of values to remain numeric degrees rather than immediately forcing them into a boolean. - -For example: - -```felidae -membershipDegree := membership(score, profile) - -closenessDegree := similarity(score, 75) -``` - -A degree can later be converted into a crisp decision when the program explicitly chooses a threshold: - -```felidae -if degree >= 75% then - - return "met" - -else - - return "not-met" -``` - -This distinction is important. - -Felidae does not try to make every boolean operation fuzzy. - -Instead: - -```text -graded information remains graded -until -the program explicitly needs a crisp decision -``` - ---- - -## Example degree profile - -A profile might describe a graded category: - -```felidae -RatingProfile( - name: "Strong / Agree", - peak: 75, - fades_in: 50, - fades_out: 90 -) -``` - -The program can then calculate how strongly another value belongs to that profile. - -This is useful for concepts such as: - -* low / medium / high, -* poor / acceptable / strong, -* unlikely / possible / likely, -* weak / moderate / strong evidence, -* low / medium / high similarity. - ---- - -# Queries and fact traversal - -Fact types own their query operations. There is no separate `Fact` library or -selection-object representation: - -```felidae -School(name: "North", district: "central", active: 1.0) -School(name: "West", district: "west", active: 0.0) - -main() => - allSchools := School.all() - activeCentral := School.where(district: "central", active: 1.0) - .limit(records: 100) - discovered := School.search(field: "name", query: "%north%", - type: "like", case: "insensitive") - names := School.select(fields: ["name"], match: {active: 1.0}) - return (all: allSchools, selected: activeCentral, names: names, - count: School.count()) -end -``` - -`Type.where(...)` compiles directly to verified indexed-query IR. Declared -single/composite class indexes are inherited, leading composite prefixes are -usable, and remaining conditions are checked as residual predicates. A small -unindexed table may use a bounded scan; a large one reports that an index is -required. `Type.all()` and `where(using:)` retain the established fact- -iteration path, while `select` projects named fields. Conditions may be -extended with `.AndWhere(...)` and `.OrWhere(...)`. Hierarchy traversal -includes assignable child facts. Exact truth values are numeric `0.0` and -`1.0`. - -`where` and `search` have different contracts. `where` performs structured -equality filtering or invokes a verified predicate. `search` discovers facts -through text (`exact`, `prefix`, `suffix`, `contains`, SQL `like`, or `regex`), -hierarchy (`ancestors`, `descendants`, or `related`), or finite numeric -range/closeness matching. Numeric search accepts negative values and values -greater than `1.0`; only its tolerance is constrained to be non-negative. -Search never changes a graded value into Boolean truth. See -`v2_examples/fact_search_analysis.fx`. - -CSV rows can enter that same native fact store and be synchronized from the VM: - -```felidae -rows := csv.toFacts(data: csvText, type: "School", - source: "build/runtime/schools.csv") -changed := School.where(name: "North") - .update(values: {active: 0.0}) -``` - -Insert, update, and delete persist automatically when affected facts have CSV -source ownership or were linked from a fact-only `.fx` database import. Each -source is staged and replaced independently; an in-memory fact has no implicit -disk side effect. The compiler links `.fx` rows and ownership into IR; the VM -does not parse source files. See -`v2_examples/csv_fact_database.fx` for the complete import, query, aggregate, -and automatic write-back flow. - -Updates and deletes are deliberately conditional: they must be chained after -`where`, `AndWhere`, or `OrWhere`. Direct type-wide mutation is rejected. -Joins must provide both `left` and `right` key fields, so the normal -`Type.join(...)` operation is an explicit inner equijoin rather than a -conditionless Cartesian join. Pass `kind: "left"`, `kind: "right"`, or -`kind: "outer"` to the same operation when unmatched rows are required; -separate `leftJoin`, `rightJoin`, and `OuterJoin` methods do not exist. -The VM builds one ordered right-key lookup and probes it in stable left order, -including every duplicate-key match; it does not execute a nested Cartesian -scan. - -Because child types are assignable to their parents, a parent query can work -with the hierarchy rather than only one exact concrete type. -Classes and ordinary fact declarations use the same hierarchy table: class → -class, class → fact, fact → class, and fact → fact extension are all valid. -Only classes add reusable field/index schema metadata; neither form creates a -runtime class object. - -This gives Felidae a natural path for: - -* typed fact traversal, -* hierarchical searches, -* fact filtering, -* relationship reasoning, -* group operations. - ---- - -# Methods and ordinary programming - -Felidae also supports conventional language constructs. - -The current compiler/runtime examples cover areas such as: - -* procedures, -* arguments, -* named arguments, -* return values, -* recursion, -* conditions, -* arrays, -* maps, -* arithmetic, -* comparisons, -* methods, -* imports, -* custom operators. - -This is intentional. - -Felidae is not meant to require a reasoning operation for ordinary computation. - -Simple work should remain simple. - -For example: - -```felidae -double(value: number) => - - return value * 2 -``` - -does not need machine learning, fuzzy reasoning, or a semantic model. - -It is normal deterministic computation. - ---- - -# Flexible expressions and mixfix - -Felidae supports **mixfix expressions**. - -The term sounds technical, but the underlying idea is simple: - -> A language can allow domain-specific expressions that do not always look like ordinary `function(argument)` calls. - -For example, some domains are naturally expressed as: - -```text -something BETWEEN something AND something -``` - -or: +Felidae is a deterministic functional-logic language with an in-process fact +database. `.fx` source is tokenized, parsed to an AST, and evaluated directly +by the restored interpreter. ```text -IF something THEN something +source.fx -> custom BPE -> IntegerParser -> Program AST -> Interpreter ``` -or another custom pattern. - -Felidae's mixfix system explores allowing such forms while still compiling them into the same executable runtime representation used by ordinary code. - -The repository includes examples covering: +There is no compiler-to-IR conversion, binary program format, VM, SentencePiece +dependency, or SSM-based mixfix path. -* nested mixfix expressions, -* prefix/infix combinations, -* custom operators, -* overloaded operators, -* typed mixfix expressions, -* fact reasoning with mixfix, -* fuzzy facts with mixfix, -* same-anchor patterns, -* deeply nested patterns. +## Build and run -Representative examples include: - -```text -v2_examples/mixfix_ir_roundtrip.fx -v2_examples/mixfix_deep_ir_nesting.fx -v2_examples/mixfix_fuzzy_fact_report.fx -v2_examples/mixfix_operator_overload.fx -v2_examples/mixfix_expr_fact_reasoning.fx -v2_examples/nested_mixfix_overload_resolution.fx +```sh +cmake -S . -B build/debug -DFELIDAE_BUILD_TESTS=ON +cmake --build build/debug --target felidae -j2 +build/debug/felidae tests/direct_ast_smoke.fx +build/debug/felidae v2_examples/mixfix_nested_expression.fx +build/debug/felidae tests/direct_ast_smoke.fx --serve ``` ---- - -# Numeric operations - -Felidae includes deterministic numeric operations directly in the runtime. - -Current operations include functionality such as: - -```text -min -max -abs -avg -clamp -sqrt -pow -lerp -``` - -along with range and finite-value checks. - -These operations execute as ordinary runtime operations. - -Ordinary numbers are unrestricted finite floating-point values, not fuzzy -degrees: negative values and values above `1.0` are preserved. Only predicate -operations such as `in_range`, `is_finite`, and `is_nan` return exact numeric -truth (`0.0` or `1.0`). Arithmetic operations return their full signed -floating-point result. - -They do **not** require the optional semantic model. - -This is an important design rule: - -> If an operation has a clear deterministic answer, Felidae should normally compute that answer directly. - -See: - -```text -v2_examples/numeric_operations.fx -``` - -for examples. - ---- - -# Tensor operations - -Supported desktop builds can also use LibTorch-backed tensor functionality. - -This allows Felidae to work with numeric arrays using operations such as: - -* tensor metadata, -* cloning, -* transpose, -* symmetry checks, -* differences, -* cosine similarity, -* dot product, -* mean squared error, -* sigmoid, -* ReLU. - -These operations remain deterministic. - -The existence of LibTorch inside Felidae does **not** mean every tensor operation is passed through a learned model. - -Tensor mathematics and semantic learning are separate concerns. - -See: - -```text -v2_examples/tensor_operations.fx -``` - -for representative functionality. - ---- - -# Reasoning and proof-style workflows - -Felidae includes reasoning-oriented examples that go beyond simple arithmetic. - -The repository currently includes examples such as: - -```text -coffee_vending_theorem_solver.fx -air_conditioner_theorem_solver.fx -contextual_fact_intelligence.fx -deep_fact_reasoning_analysis.fx -selective_relationship_reasoning.fx -temporal_fact_reasoning.fx -sentiment_fact_expert_system.fx -animal_fact_similarity_evidence.fx -``` - -The reasoning benchmark covers areas including: - -* hierarchy, -* explicit unification, -* theorem-like expressions, -* bounded alternative proofs, -* safe failure cases, -* deterministic execution, -* fault tolerance, -* latency, -* held-out learning evaluation. - -See: - -```text -docs/reasoning_benchmark.md -``` - -for the benchmark methodology. - -Felidae does **not** claim that these benchmarks represent human intelligence or a human IQ score. - -The benchmark is designed to measure specific system behaviors independently. - ---- - -# Deterministic and learned behavior - -Felidae deliberately separates two categories of work. - -## Deterministic work - -Examples: - -```text -2 + 2 - -max(10.0, 20.0) - -array lookup - -procedure call - -fact field access - -comparison - -hierarchical traversal - -tensor dot product -``` - -When the answer is defined by the language, the result should come from ordinary execution. - ---- - -## Learned or semantic work - -Some situations may require choosing between interpretations or evaluating explicitly semantic operations. - -Felidae experiments with recurrent neural models for these limited cases. - -There are currently **two different model roles**. - -### Compiler-side model - -This model is associated with constrained compiler situations such as ambiguous mixfix structures. - -It does not replace the compiler. - -The compiler still owns: - -* syntax, -* validation, -* source errors, -* binary generation, -* verification. - -Model output must pass validation before it can become part of a compiled program. - -### VM-side model - -The VM contains a separate experimental recurrent model for explicit semantic evaluation operations. - -This model is not used automatically for ordinary arithmetic, boolean logic, fact access, or tensor mathematics. - -Semantic evaluation must be explicitly represented. - -Application scoring uses `ssm.suggest(input: value)`. It returns an ordinary -finite floating-point score and may be negative or greater than `1.0`; the VM -does not normalize it or treat it as implicit truth. Deterministic arithmetic, -queries, joins, and hierarchy traversal never invoke the model automatically. - ---- - -## Why separate them? - -Compiler uncertainty and runtime semantic uncertainty are different problems. - -Therefore Felidae does not treat them as one universal AI component. - -```text -Source ambiguity - ↓ -Compiler model - -Runtime semantic operation - ↓ -VM model -``` - -Each model has its own: - -* responsibilities, -* datasets, -* training, -* validation, -* runtime boundary. - ---- - -# How Felidae works - -At the highest level, Felidae is straightforward: - -```text - Felidae source - .fx - │ - ▼ - ┌──────────┐ - │ Compiler │ - └──────────┘ - │ - ▼ - verified binary program - .bin - │ - ▼ - ┌─────────┐ - │ Form VM │ - └─────────┘ - │ - ▼ - result -``` - -The compiler understands source code. - -The VM executes compiled programs. - -This separation is one of the most important architectural principles in Felidae. - ---- - -# Compiler and VM separation - -Felidae deliberately keeps the compiler and runtime separate. - -The compiler is responsible for understanding `.fx` source. - -The runtime should not need to understand source syntax. - -Conceptually: - -```text -SOURCE SIDE - -.fx source - ↓ -token IDs - ↓ -parser - ↓ -compiler - ↓ -verified executable binary - - -RUNTIME SIDE - -.bin - ↓ -loader - ↓ -verification - ↓ -Form VM - ↓ -result -``` - -The syntax-shaped tree is compiler-only high-level IR (HIR). The VM receives -only verified executable IR and never includes or interprets HIR nodes. - -This provides several benefits. - -### Cleaner responsibilities - -The compiler handles language syntax. - -The VM handles execution. - -### Smaller runtime boundary - -Source-language machinery does not need to be carried into normal execution. - -### Better validation - -A compiled binary can be checked before it runs. - -### Easier evolution - -The source language can evolve without forcing every parser detail into the VM. - ---- - -# Verified binary programs - -Felidae source files compile to: - -```text -.bin -``` - -files. - -The binary contains the information needed by the runtime, including concepts such as: - -* instructions, -* operands, -* registers, -* constants, -* procedures, -* symbols, -* source locations, -* fact/type information. - -The binary is verified before normal execution. - -Malformed or invalid programs should fail at the binary boundary rather than being blindly executed. - ---- - -## Why binary programs? - -Compilation provides a clean separation: - -```text -Developer machine - -source.fx - ↓ -compiler - ↓ -program.bin - - -Runtime - -program.bin - ↓ -VM -``` - -That separation also makes it possible to reason clearly about: - -* compiler correctness, -* binary correctness, -* runtime correctness, -* semantic-model correctness. - ---- - -## Beta binary compatibility - -Felidae's binary format is still evolving. - -During beta: - -> A `.bin` file generated by an older beta build may need to be rebuilt with the current compiler. - -Pre-release binary compatibility should not be assumed unless a particular release explicitly documents it. - -Keep the `.fx` source as the authoritative program representation during beta. - ---- - -# Beta status - -Current supported beta: - -```text -0.2.3-beta.1 -``` - -Felidae is under active development. - -Beta means the project is real and usable for testing, but major areas are still evolving. - -During beta, the following may change: - -* syntax, -* compiler behavior, -* binary representation, -* VM instructions, -* APIs, -* model formats, -* training data formats, -* experimental semantic features, -* platform support. - ---- - -## Recommended beta use - -Felidae is suitable for: - -✅ development - -✅ experimentation - -✅ research - -✅ learning - -✅ language exploration - -✅ reasoning experiments - -✅ proof-of-concept systems - -✅ non-critical internal workflows - -✅ benchmark development - ---- - -## Not currently recommended - -Felidae beta should not be the sole decision-maker for: - -❌ medical decisions - -❌ legal decisions - -❌ financial decisions - -❌ safety-critical systems - -❌ infrastructure safety controls - -❌ irreversible high-impact decisions - -❌ security-critical authorization - -Production use is not currently recommended. - -See [SECURITY.md](./SECURITY.md). - ---- - -# Quick start - -## 1. Clone Felidae - -Felidae uses Git submodules, so clone recursively: - -```bash -git clone --recurse-submodules https://github.com/xnvtserver/Felidae.git -cd Felidae -``` - -If you already cloned the repository: - -```bash -git submodule sync --recursive -git submodule update --init --recursive -``` - ---- - -## 2. Build - -On a supported Linux development system: - -```bash -./build.sh --mode test -``` - -The normal Linux test build is created under: - -```text -build/test/ -``` - -The build script: - -1. configures CMake, -2. builds the compiler, -3. builds the VM, -4. builds the tests, -5. runs CTest. - ---- - -## 3. Compile an example - -```bash -./build/test/felidae_compiler \ - v2_examples/form_core_concepts.fx -``` - ---- - -## 4. Run it - -```bash -./build/test/felidae_vm \ - build/test/form_core_concepts.bin -``` - -You have now executed a Felidae program through the normal: - -```text -.fx → compiler → .bin → VM -``` - -pipeline. - ---- - -# Requirements - -The normal project requires: - -| Requirement | Purpose | -| ---------------------- | --------------------------------------------------- | -| C++20-capable compiler | Building Felidae | -| CMake 3.21+ | Build configuration | -| Git | Repository/submodules | -| SentencePiece | Token representation | -| LibTorch | Tensor/model functionality on normal desktop builds | -| CTest | Test execution | -| Ninja | Recommended build backend | - -Useful development tools include: - -```text -GDB -LLDB -clang-tidy -cppcheck -Valgrind -ccache -``` - -depending on your platform. - ---- - -# Building Felidae - -Felidae includes: - -```text -build.sh -build.ps1 -build.cmd -``` - -as well as direct CMake support. - -The portable Unix-style build script supports options such as: - -```bash -./build.sh \ - --mode test \ - --libtorch ON \ - --training OFF \ - --jobs 8 -``` - -Main options include: - -| Option | Values | Meaning | -| ------------ | ----------------- | ------------------------------ | -| `--mode` | `test`, `release` | Build purpose | -| `--training` | `ON`, `OFF` | Compile training functionality | -| `--libtorch` | `ON`, `OFF` | Enable LibTorch | -| `--platform` | platform name | Select target platform | -| `--arch` | architecture | Select target architecture | -| `--jobs` | number / auto | Parallel build jobs | -| `--sanitize` | flag | Enable sanitizer build | - ---- - -# Linux and WSL - -A normal Linux test build is: - -```bash -./build.sh --mode test -``` - -Limit parallelism on machines with less memory: - -```bash -./build.sh --mode test --jobs 2 -``` - -or: - -```bash -FELIDAE_JOBS=2 ./build.sh --mode test -``` - -For a manual Debug build: - -```bash -cmake -S . -B build/debug -G Ninja \ - -DCMAKE_BUILD_TYPE=Debug \ - -DFELIDAE_ENABLE_LIBTORCH=ON \ - -DFELIDAE_BUILD_TESTS=ON -``` - -Then: - -```bash -cmake --build build/debug \ - --target felidae_compiler felidae_vm felidae_debug felidae_tests \ - --parallel 1 -``` - -Run tests: - -```bash -ctest \ - --test-dir build/debug \ - --output-on-failure -``` - ---- - -# Windows - -Felidae supports native Windows development through CMake. - -With LibTorch installed at: - -```text -C:\libtorch -``` - -configure: - -```powershell -cmake -S . -B build/debug -A x64 ` - -DFELIDAE_ENABLE_LIBTORCH=ON ` - -DCMAKE_PREFIX_PATH=C:\libtorch -``` - -Build the compiler and VM: - -```powershell -cmake --build build/debug ` - --config Debug ` - --target felidae_compiler felidae_vm -``` - -Optional development targets: - -```powershell -cmake --build build/debug ` - --config Debug ` - --target felidae_debug -``` - -```powershell -cmake --build build/debug ` - --config Debug ` - --target felidae_tests -``` - -Run tests: - -```powershell -ctest ` - --test-dir build/debug ` - -C Debug ` - --output-on-failure -``` - -If LibTorch DLLs are not available on `PATH`: - -```powershell -$env:PATH = 'C:\libtorch\lib;' + $env:PATH -``` - ---- - -# macOS - -The build system includes native macOS handling for: - -```text -x86_64 -arm64 -``` - -For Apple Silicon, for example: - -```bash -FELIDAE_LIBTORCH_PATH=/path/to/libtorch \ -./build.sh \ - --platform macos \ - --arch arm64 \ - --mode release -``` - -The LibTorch distribution must match the target architecture. - ---- - -# Android and cross-compilation - -Felidae contains an Android cross-compilation path using the official Android NDK. - -Example: - -```bash -ANDROID_NDK_HOME=/opt/android-ndk \ -./build.sh \ - --platform android \ - --arch arm64 \ - --android-api 24 \ - --mode release \ - --libtorch OFF -``` - -Android is not currently treated as the primary production target. - -LibTorch is disabled when it is unavailable for the target. - -Cross-compiled tests can be built even when they cannot be executed on the host machine. - -For another toolchain, Felidae also supports: - -```text -FELIDAE_TOOLCHAIN_FILE -``` - -for custom CMake toolchain configuration. - ---- - -# Running a program - -Compile: - -```bash -./build/debug/felidae_compiler \ - v2_examples/form_core_concepts.fx -``` - -Run: - -```bash -./build/debug/felidae_vm \ - build/debug/form_core_concepts.bin -``` - -The compiler writes the generated binary into the active build/output area instead of modifying the source example directory. - ---- - -# Long-lived VM mode - -Felidae also contains a long-lived Form VM mode. - -Example: - -```bash -felidae_vm --serve program.bin -``` - -To retain the VM fact store across restarts, provide a RocksDB directory. The -directory is data, so keep it under an application-owned location rather than -inside the source tree: - -```bash -felidae_vm --serve --fact-store build/runtime/facts.rocksdb program.bin -``` - -The current server mode supports commands around concepts such as: - -```text -run - -facts - -field - -history - -proof - -load - -modules - -quit -``` - -This allows the VM to remain alive instead of starting a completely new process for every interaction. - -`proof` prints every bounded hierarchy proof path in deterministic order, not -only one arbitrarily selected ancestor route. - -The feature is particularly relevant to future reasoning and fact-oriented workflows. - ---- - -# Working examples - -`v2_examples/` is one of the best places to understand the current language. - -The examples are executable development artifacts rather than only conceptual documentation. - ---- - -## Core language - -| Example | Covers | -| ------------------------------- | -------------------------------------------------------- | -| `form_core_concepts.fx` | Core types, functions, recursion, arrays, maps and facts | -| `ast_typed_methods.fx` | Typed methods | -| `dotless_method_syntax.fx` | Alternative method syntax | -| `list_data_structure.fx` | List structures | -| `standard_search_algorithms.fx` | Search algorithms | -| `parser_fold.fx` | Parser/fold-oriented behavior | - ---- - -## Facts and hierarchy - -| Example | Covers | -| -------------------------------------- | ---------------------------------- | -| `hierarchical_fact_filter.fx` | Concrete parent-type hierarchy query | -| `direct_ancestor_analysis.fx` | Ancestor relationships | -| `fact_degree_loop.fx` | Fact traversal with degree values | -| `fact_similarity_requires_ancestry.fx` | Similarity constrained by ancestry | -| `selective_fact_query.fx` | Fact selection | -| `selective_relationship_reasoning.fx` | Relationship reasoning | -| `temporal_fact_reasoning.fx` | Time-related fact reasoning | - ---- - -## Degree and fuzzy behavior - -| Example | Covers | -| ------------------------------------ | -------------------------------------- | -| `degree_profiles.fx` | Membership, similarity and thresholds | -| `graded_evidence_profiles.fx` | Graded evidence | -| `animal_fact_similarity_evidence.fx` | Similarity with facts | -| `mixfix_fuzzy_fact_report.fx` | Fuzzy degrees combined with mixfix | -| `sentiment_fact_expert_system.fx` | Degree-oriented expert-system behavior | - ---- - -## Reasoning - -| Example | Covers | -| ------------------------------------- | --------------------------------- | -| `coffee_vending_theorem_solver.fx` | Theorem-style reasoning | -| `air_conditioner_theorem_solver.fx` | Rule/reasoning workflow | -| `deep_fact_reasoning_analysis.fx` | Deeper fact analysis | -| `contextual_fact_intelligence.fx` | Context-sensitive fact processing | -| `selective_relationship_reasoning.fx` | Relationship-oriented reasoning | - ---- - -## Mixfix and custom operators - -| Example | Covers | -| -------------------------------------- | ------------------------------ | -| `mixfix_ir_roundtrip.fx` | Mixfix compilation | -| `mixfix_deep_ir_nesting.fx` | Deeply nested mixfix | -| `mixfix_deep_chain_stress.fx` | Long expression chains | -| `mixfix_operator_overload.fx` | Operator overloads | -| `mixfix_expr_fact_reasoning.fx` | Mixfix with facts | -| `mixfix_shape_inference.fx` | Pattern shapes | -| `mixfix_shape_matrix.fx` | Mixfix shape combinations | -| `mixfix_same_anchor.fx` | Same-anchor expressions | -| `mixfix_same_anchor_long.fx` | Longer same-anchor expressions | -| `nested_mixfix_overload_resolution.fx` | Nested overload resolution | -| `symbolic_operator_overload.fx` | Symbolic operators | -| `user_defined_operator_types.fx` | User-defined operator types | -| `typed_builtin_operator_overload.fx` | Typed operator overloads | - ---- - -## Runtime semantic model - -| Example | Covers | -| --------------------------------- | ------------------------------- | -| `runtime_ssm_e2e.fx` | Runtime semantic model pipeline | -| `runtime_ssm_identity_array.fx` | Array identity case | -| `runtime_ssm_identity_boolean.fx` | Boolean identity case | -| `runtime_ssm_identity_degree.fx` | Degree identity case | -| `runtime_ssm_identity_fact.fx` | Fact identity case | -| `runtime_ssm_identity_text.fx` | Text identity case | -| `runtime_training_smoke.fx` | Training workflow smoke case | - ---- - -## Native and imported functionality - -Representative examples include: - -```text -import_smoke.fx -imported_math.fx -imported_public_operator.fx -native_lazy_import.fx -native_packages_smoke.fx -set_group_native.fx -third_party_native_smoke.fx -``` - ---- - -# Repository structure - -The project currently contains areas such as: - -```text -Felidae/ -│ -├── cmake/ -│ └── CMake support -│ -├── core/ -│ └── Core project components -│ -├── datasets/ -│ ├── Compiler data -│ ├── Runtime data -│ └── Tokenizer data -│ -├── docs/ -│ └── Detailed documentation -│ -├── ml/ -│ └── Model-related implementation -│ -├── models/ -│ └── Model/tokenizer assets -│ -├── scripts/ -│ └── Project utilities -│ -├── src/ -│ ├── Compiler -│ ├── Integer parser -│ ├── IR generation -│ └── Form VM/runtime -│ -├── tests/ -│ └── Test suites -│ -├── third_party/ -│ └── Pinned external dependencies -│ -├── tools/ -│ └── Development tools -│ -├── v2_examples/ -│ └── Current production-pipeline examples -│ -├── tree-sitter-felidae/ -│ └── Tree-sitter support -│ -├── emacs-extension/ -├── intellij-idea-extension/ -├── nano-extension/ -├── notepad-plus-plus-extension/ -├── sublime-text-extension/ -├── vim-extension/ -├── vs-code-extension/ -└── zed-extension/ -``` - -The editor-related repositories are maintained as Git submodules. - ---- - -# Dependencies - -Felidae intentionally uses a relatively small set of C++ dependencies. - -Current submodule dependencies include: - -### SentencePiece - -Used for Felidae's integer/token representation. - -### nlohmann/json - -Used for JSON handling in project tooling/data paths. - -### Abseil - -Provides selected C++ utility components. - -### Protocol Buffers - -Available for structured serialization-related needs. - -### Eigen - -Provides mathematical functionality. - -### cpp-httplib - -Lightweight HTTP functionality. - -### rapidcsv - -CSV functionality. - -### LibTorch - -PyTorch's native C++ distribution. - -LibTorch is not kept as an ordinary source submodule in the same way as the lightweight dependencies; developers provide an appropriate platform package. - -### Faiss execution memory - -Optional `FELIDAE_ENABLE_FAISS=ON` retains actual runtime SSM hidden vectors in -an execution-owned CPU Faiss index. It requires LibTorch and the Faiss C++ CMake -package. It does not index facts or SentencePiece IDs, change scores, train a -model, or feed retrieved states back into execution. Retrieval is not exposed -yet. Ordinary numeric expressions do not invoke the SSM to manufacture vectors. - -Each completed SSM evaluation stores one flattened hidden tensor, including all -recurrent layers. Capacity follows the existing execution semantic-step limit; -overflow raises an error rather than evicting states silently. Separate top-level -executions have separate indexes, including requests in a long-lived VM process. -All retained vectors are released with their execution state, with no disk writes. -RocksDB remains independent and continues to own persistent facts. - -After installing Faiss development files, enable and verify with: - -```bash -cmake -S . -B build/debug -DFELIDAE_ENABLE_FAISS=ON -cmake --build build/debug --target felidae_vm felidae_execution_vectors_test felidae_mixfix_state_model_test --parallel 8 -ctest --test-dir build/debug -R '^felidae_(execution_vectors|mixfix_state_model)$' --output-on-failure -``` - -### RocksDB - -RocksDB provides the ordered, durable key/value boundary used by scalable fact -storage and keyset pagination. It is enabled by default on desktop builds and -disabled by default on Android, where the platform package is normally absent. - -On Debian or Ubuntu: - -```bash -sudo apt-get update -sudo apt-get install -y librocksdb-dev -``` - -On macOS with Homebrew: - -```bash -brew install rocksdb -``` - -Disable it explicitly only for a platform without RocksDB: - -```bash -./build.sh --rocksdb OFF -``` - -An opt-in fact-store benchmark generates its synthetic database only under the -selected build tree. It reports ingestion rate, reopen time, cold and warm -indexed lookup latency, requested/returned page size, RocksDB index-reader -memory, estimated live/SST bytes, total storage size, and the cache assumptions. -It does not make a trillion-scale claim. Build and run it explicitly: - -```bash -cmake --build build/debug --target felidae_fact_store_benchmark --parallel 8 -./build/debug/felidae_fact_store_benchmark --records 100000 --page 100 --warm 100 -``` - ---- - -# Testing - -Felidae uses CTest for the primary native test workflow. - -After a Debug build: - -```bash -ctest \ - --test-dir build/debug \ - --output-on-failure -``` - -With the normal build script: - -```bash -./build.sh --mode test -``` - -tests are built and executed automatically on native supported hosts. - ---- - -## Example tests - -The test suite also runs representative `.fx` examples through: - -```text -compiler - ↓ -binary - ↓ -VM -``` - -This is important because a parser-only or compiler-only test cannot demonstrate that the final runtime program actually works. - -Run example-labelled tests: - -```bash -ctest \ - --test-dir build/debug \ - -L examples \ - --output-on-failure -``` - ---- - -# Debugging - -Compiler debugging: - -```bash -gdb --args \ - ./build/debug/felidae_compiler \ - v2_examples/form_core_concepts.fx -``` - -VM debugging: - -```bash -gdb --args \ - ./build/debug/felidae_vm \ - build/debug/form_core_concepts.bin -``` - ---- - -## Runtime trace - -Debug builds support an optional trace: - -```bash -FELIDAE_TRACE=1 \ -./build/debug/felidae_compiler \ -v2_examples/form_core_concepts.fx -``` - -and: - -```bash -FELIDAE_TRACE=1 \ -./build/debug/felidae_vm \ -build/debug/form_core_concepts.bin -``` - -Trace output goes to: - -```text -stderr -``` - -while normal program results remain on: - -```text -stdout -``` - -This keeps diagnostic information separate from application output. - ---- - -## Source-analysis tool - -Felidae also includes: - -```text -felidae_debug -``` - -This is a source-analysis/debugging tool. - -It is **not** the production Form VM. - -Examples: - -```bash -./build/debug/felidae_debug \ - v2_examples/form_core_concepts.fx \ - --check -``` - -Structured diagnostics: - -```bash -./build/debug/felidae_debug \ - v2_examples/form_core_concepts.fx \ - --check-json -``` - ---- - -# Code quality - -The project supports additional C++ analysis tools. - -These are intentionally not run during every normal build because they are substantially slower. - ---- - -## clang-tidy - -```bash -clang-tidy \ - -p build/debug \ - src/form/RegisterVm.cpp \ - src/form/LibTorchTensorRuntime.cpp \ - src/IrCodeGenerator.cpp \ - src/IntegerParser.cpp -``` - ---- - -## cppcheck - -```bash -cppcheck \ - --enable=warning,performance,portability \ - --std=c++20 \ - --project=build/debug/compile_commands.json \ - --suppress=missingIncludeSystem -``` - ---- - -## Valgrind - -```bash -valgrind \ - --error-exitcode=1 \ - --leak-check=full \ - ./build/debug/felidae_libtorch_smoke_test -``` - ---- - -## Sanitizers - -Create a separate sanitizer build: - -```bash -cmake -S . -B build/asan -G Ninja \ - -DCMAKE_BUILD_TYPE=Debug \ - -DFELIDAE_ENABLE_SANITIZERS=ON \ - -DFELIDAE_ENABLE_LIBTORCH=ON \ - -DFELIDAE_BUILD_TESTS=ON -``` - -Build: - -```bash -cmake --build build/asan \ - --target felidae_tests \ - --parallel 1 -``` - -Run: - -```bash -ctest \ - --test-dir build/asan \ - --output-on-failure -``` - ---- - -# LibTorch - -Felidae uses **LibTorch**, the native C++ distribution of PyTorch. - -Python is not required for the current normal compiler/runtime training path. - -LibTorch is used for areas including: - -* tensor operations, -* compiler recurrent-model support, -* VM recurrent-model support. - -For normal desktop development, install an official LibTorch package matching: - -```text -operating system -+ -architecture -+ -compiler ABI -+ -CPU/GPU requirement -``` - -A CPU-only package is appropriate for machines without a supported GPU. - -A common Linux installation location is: - -```text -/opt/libtorch -``` - -The build script will use: - -```text -FELIDAE_LIBTORCH_PATH -``` - -when an explicit location is required. - -Example: - -```bash -FELIDAE_LIBTORCH_PATH=/opt/libtorch \ -./build.sh \ - --mode test \ - --libtorch ON -``` - ---- - -# SentencePiece and the tokenizer - -Felidae intentionally represents source language tokens using integer IDs. - -SentencePiece provides the project's tokenizer representation. - -The compiler feeds SentencePiece complete dot-terminated statement spans, not -individual physical lines. This keeps multiline expressions and `then` chains -in one integer-token stream. Decimal points, adjacent member access, strings, -and comments are distinguished before a terminator boundary is selected; -source offsets remain attached to every emitted token for diagnostics. - -A simplified view is: - -```text -source text - - ↓ - -SentencePiece IDs - - ↓ - -integer parser - - ↓ - -compiler - - ↓ - -verified binary -``` - -The runtime itself is not designed around repeatedly parsing human-readable source text. - -Human-readable text is decoded when a presentation boundary requires it. - ---- - -## Fixed tokenizer model - -The tokenizer is generated from the project's versioned tokenizer corpus: - -```text -datasets/tokenizer/ -``` - -The corpus covers representative syntax families such as: - -* facts, -* hierarchy, -* methods, -* control flow, -* operators, -* queries, -* mixfix, -* semantic operations, -* Unicode, -* strings, -* temporal fields. - -Tokenizer regeneration is a maintainer operation. - -It should not occur during every normal build. - ---- - -
-Advanced: tokenizer regeneration - -
- -After intentionally changing the authoritative tokenizer corpus or grammar inputs: - -```bash -cmake --build build/debug \ - --target felidae_regenerate_sentencepiece_model \ - --parallel 8 -``` - -Generated tokenizer changes should only be committed when: - -* an authoritative input actually changed, -* tokenizer tests pass, -* compiler pipeline tests pass, -* generated IDs are intentionally updated. - -Routine builds should consume the checked-in model rather than rewrite it. - -
- ---- - -# Compiler recurrent model - -Felidae contains an optional compiler-side recurrent model for constrained mixfix ambiguity. - -Its purpose is **not**: - -```text -source → AI → executable -``` - -Instead, the normal compiler remains responsible for the language. - -The model is only allowed to participate at an explicit ambiguity boundary. - -Conceptually: - -```text -normal expression - ↓ -deterministic compiler - ↓ -compiled - - -ambiguous supported mixfix span - ↓ -compiler model - ↓ -validated structural result - ↓ -compiler verification - ↓ -compiled or rejected -``` - -If the model cannot produce an acceptable result, compilation should fail safely rather than secretly executing source through an alternate interpreter. - ---- - -## Compiler model principles - -The model: - -* uses a bounded structural vocabulary, -* works with integer-oriented structures, -* does not own the entire parser, -* does not replace source validation, -* does not directly execute source, -* must produce output accepted by compiler verification. - -The repository currently does not treat an unvalidated model output as executable truth. - ---- - -# VM recurrent model - -Felidae's Form VM contains a **different** optional recurrent model for explicit runtime semantic evaluation. - -This model is separate from the compiler model because runtime meaning and source ambiguity are different problems. - -Conceptually: - -```text -verified runtime state - + -explicit semantic operation - ↓ -runtime model - ↓ -bounded typed result - ↓ -validation - ↓ -VM value -``` - ---- - -## What the VM model does not replace - -It is not intended to replace: - -* addition, -* subtraction, -* multiplication, -* division, -* comparisons, -* ordinary boolean logic, -* procedure calls, -* deterministic fact access, -* deterministic numeric operations, -* tensor mathematics. - -Those operations execute directly. - ---- - -## Runtime semantic results - -The runtime semantic path is intentionally constrained to supported result categories rather than unrestricted arbitrary memory or instruction generation. - -This keeps learned behavior behind a defined runtime boundary. - ---- - -# Training - -Training support is explicit. - -It is not started automatically by an ordinary Felidae build. - -Training requires: - -```text -LibTorch = ON -Training = ON -``` - -For example: - -```bash -./build.sh \ - --mode test \ - --libtorch ON \ - --training ON -``` - ---- - -
-Advanced: compiler-model training - -
- -The compiler can train from reusable JSONL datasets. - -Representative Windows command: - -```powershell -build\debug\felidae_compiler.exe ` - --train 'datasets\compiler\*.jsonl' ` - --store-model build ` - --epochs 8 ` - --learning-rate 0.001 -``` - -Compiler datasets are tied to the tokenizer and structural vocabulary. - -When the tokenizer changes, compiler training data may need to be regenerated. - -Dataset extraction can be run with the relevant CMake target and extraction utility. - -Invalid training records are intended to remain rejection cases rather than being silently accepted as positive examples. - -
- ---- - -
-Advanced: runtime-model training - -
- -The runtime uses its own dataset. - -Representative command: - -```powershell -build\debug\felidae_vm.exe ` - --train datasets\vm\runtime-context-v1.jsonl ` - --store-model build ` - --epochs 8 ` - --learning-rate 0.001 -``` - -The runtime model is trained independently from the compiler model. - -This prevents compiler ambiguity data from being treated as runtime semantic knowledge. - -
- ---- - -# Release builds - -A normal release build can be created with: - -```bash -./build.sh --mode release -``` - -Release mode builds optimized binaries and creates the distribution through the project's distribution target. - -On normal Linux: - -```text -build/release/ -``` - -and the generated distributable package is staged under: - -```text -build/release/dist/ -``` - -The distribution folder is generated. - -It is not intended to be a manually maintained source directory. - ---- - -## Release philosophy - -A release package should come from: - -```text -clean intended source revision - ↓ -Release configuration - ↓ -tests / validation - ↓ -distribution target - ↓ -staged package - ↓ -clean-machine smoke test - ↓ -release -``` - -Do not treat a successful compilation alone as complete release evidence. - ---- - -# Documentation - -The README is intentionally the **front page** of Felidae. - -It should explain: - -* what Felidae is, -* why it exists, -* what it can do, -* how to try it, -* where to learn more. - -Detailed documentation lives under: - -```text -docs/ -``` - -Current documentation includes areas such as: - -```text -docs/README.md - -docs/about.fx -docs/basics.fx -docs/getting_started.fx -docs/language_reference.fx -docs/syntax.fx - -docs/facts.fx -docs/queries.fx -docs/methods.fx - -docs/native_modules.fx -docs/libraries.fx -docs/stdlib.fx - -docs/testing.fx -docs/debugging.fx - -docs/executable_ir.md -docs/expression_inventory.md -docs/compiler_form_audit.md -docs/reasoning_benchmark.md - -docs/server.fx -docs/server_features.fx - -docs/milestones.fx -docs/version.fx -``` - -There are also root-level technical references including: - -```text -docs_language.md -docs_github_linguist.md -``` - ---- - -# Editor support - -Felidae includes or links dedicated editor integrations. - -Current editor-related repositories include: - -| Editor | Component | -| ------------------ | ------------------------------ | -| Visual Studio Code | `vs-code-extension/` | -| IntelliJ IDEA | `intellij-idea-extension/` | -| Vim | `vim-extension/` | -| Emacs | `emacs-extension/` | -| Zed | `zed-extension/` | -| Sublime Text | `sublime-text-extension/` | -| Notepad++ | `notepad-plus-plus-extension/` | -| Nano | `nano-extension/` | - -Felidae also contains: - -```text -tree-sitter-felidae/ -``` - -for Tree-sitter language support. - -Because syntax can evolve during beta, editor integrations may occasionally lag behind the compiler. - -Compiler behavior remains authoritative. - ---- - -# Development principles - -Felidae is guided by several architectural principles. - ---- - -## 1. Keep simple things simple - -Normal arithmetic should be arithmetic. - -```text -2 + 2 -``` - -should not require a neural model. - ---- - -## 2. Keep deterministic work deterministic - -If the runtime can calculate an exact result directly, it should normally do so. - ---- - -## 3. Make reasoning explicit - -Reasoning should be visible in the language/runtime model rather than hidden inside unrelated application code. - ---- - -## 4. Represent knowledge directly - -Facts and relationships should be first-class concepts. - ---- - -## 5. Preserve graded information - -If something is naturally a degree, Felidae should not force it into a boolean too early. - ---- - -## 6. Separate compilation from execution - -The compiler understands source. - -The VM executes verified programs. - ---- - -## 7. Validate learned behavior - -A model output should not automatically become an executable instruction or trusted result. - ---- - -## 8. Keep learned components focused - -Felidae does not aim to make the whole runtime probabilistic. - -Learning is used only at explicit boundaries. - ---- - -## 9. Prefer inspectable systems - -Reasoning behavior should be testable and measurable. - ---- - -## 10. Benchmark claims carefully - -Different qualities should be measured separately. - -For example: - -```text -correctness -determinism -proof success -failure behavior -learning quality -latency -``` - -should not be merged into one impressive-looking but meaningless score. - ---- - -# Project maturity - -Felidae currently contains several different maturity levels. - -### Established project foundations - -Areas with significant existing implementation include: - -* C++ compiler infrastructure, -* `.fx` source compilation, -* verified binary execution, -* register-based Form VM, -* facts, -* hierarchy, -* procedures, -* arrays/maps, -* degree operations, -* numeric operations, -* example programs, -* tests, -* editor integrations. - -### Active beta areas - -Areas that continue to evolve include: - -* binary format, -* advanced fact reasoning, -* mixfix coverage, -* recurrent-model integration, -* runtime semantic evaluation, -* training datasets, -* platform packaging, -* performance stabilization. - -### Experimental areas - -Some examples intentionally explore future-facing behavior. - -An example existing in the repository does not necessarily mean that its API is stable. - -Always check the current documentation before building long-term integrations against a beta feature. - ---- - -# What Felidae is not - -Felidae is **not currently**: - -### A replacement for C++, Rust, Java, Python, or JavaScript - -General-purpose languages remain better choices for many ordinary applications. - -### A general-purpose LLM - -Felidae's learned components are constrained and task-specific. - -### A chatbot framework - -Conversational interaction is not the central language design goal. - -### An excuse to make every operation fuzzy - -Crisp deterministic logic stays crisp. - -### A system where machine learning controls every instruction - -Ordinary runtime execution remains deterministic. - -### Production-certified decision software - -Felidae is still beta. - ---- - -# Security - -Please read: - -[SECURITY.md](./SECURITY.md) - -before using Felidae in an important environment. - -Current beta guidance includes: - -* production use is not recommended, -* important outputs should be independently verified, -* older beta versions may not receive fixes, -* vulnerabilities should be reported privately. - -Do **not** open a public issue containing security-sensitive vulnerability details. - -Security reports can be sent to: - -```text -info@xnovity.com -``` - -or: - -```text -support@xnovity.com -``` - ---- - -# Contributing - -Felidae welcomes contributions involving: - -* compiler development, -* VM development, -* language design, -* fact reasoning, -* degree/fuzzy functionality, -* tests, -* documentation, -* examples, -* performance, -* code quality, -* security, -* portability, -* editor integrations, -* Tree-sitter support, -* datasets, -* development tooling. - -Before contributing, read: - -[CONTRIBUTING.md](./CONTRIBUTING.md) - -and: - -[CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) - ---- - -## A good first contribution - -Useful first contributions include: - -* fixing a reproducible bug, -* improving an existing example, -* adding a regression test, -* correcting documentation, -* improving an error message, -* validating a platform build, -* reducing a compiler warning, -* improving editor syntax coverage. - -Large architectural changes should normally begin with an issue or discussion. - ---- - -# Frequently asked questions - -## Is Felidae a programming language? - -Yes. - -Felidae has source files, syntax, functions, data structures, a compiler, executable binaries, and a VM. - -Its focus on facts and reasoning differentiates it from conventional general-purpose languages. - ---- - -## Is Felidae an AI model? - -No. - -Felidae is a programming language and runtime. - -It contains optional learned components for specific compiler/runtime tasks, but those components are not the entire system. - ---- - -## Does Felidae require machine learning to run programs? - -No. - -Normal deterministic programs should execute without semantic model involvement. - ---- - -## Is fuzzy logic used everywhere? - -No. - -Felidae supports graded values where they are useful. - -Normal boolean conditions remain boolean. - ---- - -## Can Felidae work with facts? - -Yes. - -Facts, fact types, hierarchy, filtering, and traversal are central project areas. - ---- - -## Can one fact type inherit from another? - -The language currently includes hierarchical fact/type relationships using forms such as: - -```felidae -Employee extend Person(...) -``` - ---- - -## Can Felidae perform ordinary calculations? - -Yes. - -Felidae includes normal arithmetic and deterministic numeric operations. - ---- - -## Does Felidae support recursion? - -Current examples include recursive procedures such as factorial. - ---- - -## Does Felidae support arrays and maps? - -Yes. - -Current examples exercise arrays and structured maps. - ---- - -## Does Felidae support custom operators? - -The repository contains multiple examples of custom and overloaded operator behavior. - ---- - -## What is mixfix? - -Mixfix allows an expression to use a custom arrangement of words/operators instead of always looking like: - -```text -function(a, b) -``` - -Felidae uses this to experiment with more domain-oriented expression forms. - ---- - -## Why use SentencePiece in a programming language? - -Felidae's architecture explores representing language input as stable integer IDs before parsing and compilation. - -SentencePiece provides that token-to-integer layer. - -The VM then works with compiled binary structures rather than source strings. - ---- - -## Does the VM contain the parser? - -No. - -The source parser belongs to the compiler side. - -The Form VM executes compiled programs. - ---- - -## Why use a VM? - -The VM provides a dedicated execution environment for Felidae programs. - -It also creates a clear boundary between: - -```text -language compilation -``` - -and: - -```text -program execution -``` - ---- - -## What is Form VM? - -Form VM is Felidae's register-based execution runtime. - -It runs verified compiled Felidae binaries. - ---- - -## Is Felidae interpreted? - -The primary supported path is compiled: - -```text -.fx - ↓ -compiler - ↓ -.bin - ↓ -VM -``` - ---- - -## Does Felidae use Python for training? - -The current project training path is implemented around C++ and LibTorch. - -Python is not required for the normal current training/export/inference path. - ---- - -## Can I disable LibTorch? - -Certain target configurations can disable LibTorch. - -However tensor and model-dependent functionality will then be unavailable and should fail clearly when requested. - ---- - -## Does Felidae support Windows? - -Yes, native CMake/Visual Studio style builds are part of the current development path. - ---- - -## Does Felidae support Linux? - -Yes. - -Linux is a primary development environment. - ---- - -## Does Felidae support macOS? - -The build script includes macOS x86-64 and ARM64 handling. - ---- - -## Does Felidae support Android? - -An Android NDK cross-compilation path exists, but Android should currently be regarded as an experimental/non-primary target. - ---- - -## Is Felidae production ready? - -Not yet. - -Current releases are beta. - ---- - -## Can I use Felidae for critical decisions? - -Not as the sole decision source during beta. - -Important outputs should be independently verified. - ---- - -## Are beta binaries guaranteed to remain compatible? - -No. - -Recompile `.fx` source when the beta executable format changes. - ---- - -## Where should I start? - -For a developer: - -```text -1. Clone recursively -2. Build in test mode -3. Run form_core_concepts.fx -4. Explore degree_profiles.fx -5. Explore hierarchical_fact_filter.fx -6. Read docs/ -``` - ---- - -# Development workflow - -A healthy development cycle looks like: - -```text -change - ↓ -build - ↓ -unit tests - ↓ -example tests - ↓ -static analysis where relevant - ↓ -review - ↓ -release validation -``` - -Before committing: - -```bash -git status --short -``` - -Build outputs should remain inside their build directories. - -Routine builds should not unexpectedly rewrite: - -* tokenizer models, -* generated tokenizer IDs, -* training datasets, -* release artifacts. - -Those are explicit maintainer operations. - ---- - -# Dependency updates - -Several dependencies are Git submodules. - -After intentionally updating them: - -```bash -git submodule sync --recursive -git submodule update --init --recursive -git submodule status --recursive -``` - -A clean recursive clone should also succeed: - -```bash -git clone \ - --recurse-submodules \ - https://github.com/xnvtserver/Felidae.git -``` - -Dependency updates should be reviewed carefully because C++ dependency API or ABI changes can affect the compiler and VM. - ---- - -# Performance - -Felidae is written in C++ partly to keep close control over: - -* memory, -* execution cost, -* runtime boundaries, -* compilation, -* tensor operations. - -However: - -> Performance claims should be measured on real Release builds. - -Debug performance should not be used as evidence of production speed. - -Training throughput and runtime latency should also be measured independently. - ---- - -# Reasoning quality - -Reasoning systems are easy to evaluate poorly. - -Felidae therefore aims to separate measurements such as: - -```text -Does the proof succeed? - -Does an invalid proof fail safely? - -Is the result deterministic? - -How long did execution take? - -Did a learned model generalize? - -Does the model simply memorize a dataset? -``` - -These are different questions. - -A single "accuracy" number can hide serious problems. - -The reasoning benchmark exists to keep those concerns visible. - ---- - -# Project direction - -Felidae is exploring a model where software can combine: - -```text -structured knowledge - + -deterministic computation - + -hierarchy - + -graded values - + -reasoning - + -carefully bounded learning -``` - -without making the entire system opaque. - -The long-term value of Felidae depends less on adding fashionable AI features and more on maintaining a clear answer to: - -> **Why did the system produce this result, and which part of the system was responsible?** - -That principle influences the separation between: - -* compiler and VM, -* deterministic and learned work, -* facts and presentation, -* training and production artifacts, -* beta experiments and supported behavior. - ---- - -# Design philosophy - -Felidae is built around a simple belief: - -> Not every intelligent system needs to be a giant black box. - -Some problems benefit from explicit: - -* facts, -* types, -* rules, -* degrees, -* relationships, -* deterministic calculations. - -Other problems benefit from learned behavior. - -Felidae experiments with putting both in the same system while keeping the boundary visible. - -```text -Know what can be calculated. - -Represent what is known. - -Learn only where learning adds value. - -Validate what learning produces. -``` - ---- - -# Community - -Felidae is developed as an open-source project. - -We welcome: - -* bug reports, -* technical discussions, -* design criticism, -* documentation improvements, -* benchmarks, -* examples, -* code contributions, -* platform testing. - -Please keep discussion respectful and constructive. - -See: - -[CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) - ---- - -# License - -Felidae is distributed under the **MIT License**. - -See: - -[LICENCE](./LICENCE) - -for the complete license text. - ---- - -# Project - -Felidae is developed by **Xnovity Softwares** together with project contributors and supporters. - -### Project website - -https://felidae.xnovity.com - -### Source repository - -https://github.com/xnvtserver/Felidae - -### Issues - -https://github.com/xnvtserver/Felidae/issues - -### Documentation - -[docs/](./docs) - -### Examples - -[v2_examples/](./v2_examples) - ---- - -
- -
- - - - - Felidae - - -### Build software that can work with more than just `true` and `false`. - -**Facts. Relationships. Degrees. Reasoning.** - -
- -If Felidae's direction interests you: - -⭐ **Star the repository** - -🧪 **Try the examples** - -📚 **Explore the documentation** +`--serve` watches the root module and loaded imports. A changed program is +parsed and registered in a replacement interpreter; the prior interpreter +remains alive if the new source is invalid. -🐛 **Report reproducible problems** +## Facts and memory -🤝 **Contribute** +`FactMemory` is the fact database. It owns fact values through immutable, +copy-on-write relation roots, supports indexed query candidates, source +provenance, transactional registration rollback, and explicit snapshots. +No external fact store is required for this interpreter-only runtime. -
+## Token model -**Felidae — reasoning as part of the language.** +`models/felidae-bpe/model.txt` is the checked-in custom-BPE identifier +vocabulary. Its physical line number is the token ID. The lexer owns the first +59 fixed syntax IDs plus reserved `class`, `extends`, `index`, and `end`, as +well as comments, strings, punctuation, and numbers; BPE only looks up +identifier and mixfix-anchor words in the text table. Unknown words are added +deterministically in source order. -
+See [code.md](code.md) for the execution architecture and +[docs_language.md](docs_language.md) for language semantics. diff --git a/build.ps1 b/build.ps1 index 679f26e..958248e 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,86 +1,22 @@ param( [ValidateSet("native", "windows-x64")] [string] $Target = "native", - [ValidateSet("debug", "release", "production", "sanitize")] + [ValidateSet("debug", "release", "sanitize")] [string] $Configuration = "release", - [switch] $WarningsAsErrors, - [switch] $Test, - [switch] $Dist, - [switch] $Beta + [switch] $Test ) $ErrorActionPreference = "Stop" - -$cmakeCommand = Get-Command cmake -ErrorAction SilentlyContinue -$cmakePath = if ($cmakeCommand) { $cmakeCommand.Source } else { $null } -if (-not $cmakePath -and $env:VSINSTALLDIR) { - $candidate = Join-Path $env:VSINSTALLDIR "Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" - if (Test-Path $candidate) { $cmakePath = $candidate } -} -if (-not $cmakePath) { - foreach ($version in "18", "17") { - foreach ($edition in "Community", "Professional", "Enterprise", "BuildTools") { - $candidate = Join-Path ${env:ProgramFiles} "Microsoft Visual Studio\$version\$edition\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" - if (Test-Path $candidate) { $cmakePath = $candidate; break } - } - if ($cmakePath) { break } - } -} -if (-not $cmakePath) { throw "CMake was not found. Install Visual Studio C++ CMake tools or add cmake to PATH." } - -# CMake is the only supported native build graph. It owns SentencePiece and -# the generated TokenId vocabulary, avoiding a stale direct compiler list. -if ($Target -notin @("native", "windows-x64")) { - throw "Unsupported target '$Target': provide a CMake toolchain/preset for SentencePiece cross-compilation." -} -if (-not $env:FELIDAE_LIBTORCH_PATH) { - throw "Windows builds require FELIDAE_LIBTORCH_PATH to name the provisioned CPU LibTorch installation." -} - +$cmake = (Get-Command cmake -ErrorAction Stop).Source $root = Split-Path -Parent $MyInvocation.MyCommand.Path $buildType = if ($Configuration -eq "debug" -or $Configuration -eq "sanitize") { "Debug" } else { "Release" } -$buildDir = if ($env:FELIDAE_BUILD_DIR) { $env:FELIDAE_BUILD_DIR } else { Join-Path $root "build\windows-x64\$($buildType.ToLowerInvariant())" } -$configureArgs = @( - "-S", $root, - "-B", $buildDir, - "-DCMAKE_BUILD_TYPE=$buildType" -) -if ($Test) { - $configureArgs += "-DFELIDAE_BUILD_TESTS=ON" -} -if ($WarningsAsErrors) { - $configureArgs += "-DFELIDAE_ENABLE_STRICT_WARNINGS=ON" -} -if ($env:FELIDAE_LIBTORCH_PATH) { - $configureArgs += "-DCMAKE_PREFIX_PATH=$env:FELIDAE_LIBTORCH_PATH" -} -if ($env:FELIDAE_VERSION) { - $configureArgs += "-DFELIDAE_VERSION=$env:FELIDAE_VERSION" -} -if ($Configuration -eq "sanitize") { - $configureArgs += "-DFELIDAE_ENABLE_SANITIZERS=ON" -} +$buildDir = Join-Path $root "build\windows-x64\$($buildType.ToLowerInvariant())" -& $cmakePath @configureArgs +& $cmake -S $root -B $buildDir "-DCMAKE_BUILD_TYPE=$buildType" "-DFELIDAE_BUILD_TESTS=$($Test.IsPresent)" if ($LASTEXITCODE -ne 0) { throw "CMake configure failed" } - -$jobs = if ($env:FELIDAE_JOBS) { $env:FELIDAE_JOBS } else { "1" } -$targets = if ($Beta) { @("felidae_beta") } elseif ($Dist) { @("felidae_dist") } elseif ($Test) { @("felidae_compiler", "felidae_vm", "felidae_debugger", "felidae_tests") } else { @("felidae_compiler", "felidae_vm", "felidae_debugger") } -& $cmakePath --build $buildDir --config $buildType --target $targets --parallel $jobs -if ($LASTEXITCODE -ne 0) { throw "CMake build failed" } +& $cmake --build $buildDir --config $buildType --target felidae --parallel 1 +if ($LASTEXITCODE -ne 0) { throw "Felidae interpreter build failed" } if ($Test) { & ctest --test-dir $buildDir --build-config $buildType --output-on-failure if ($LASTEXITCODE -ne 0) { throw "CTest failed" } } - -if ($Dist -or $Beta) { - foreach ($executable in @("felidae_compiler.exe", "felidae_vm.exe", "felidae_debugger.exe")) { - $path = Join-Path $buildDir "dist\bin\$executable" - if (-not (Test-Path $path)) { - throw "Distribution staging completed without expected executable: $path" - } - } -} -if (($Dist -or $Beta) -and -not (Test-Path (Join-Path $buildDir "dist\models\felidae.model"))) { - throw "Distribution staging completed without dist\models\felidae.model" -} diff --git a/build.sh b/build.sh old mode 100755 new mode 100644 index 3f744ee..afca0ef --- a/build.sh +++ b/build.sh @@ -1,217 +1,51 @@ #!/usr/bin/env bash set -euo pipefail -# User configuration. Environment variables or command-line options may -# override these values without creating another build script. -MODE="${FELIDAE_MODE:-test}" # test | release -ENABLE_TRAINING="${FELIDAE_ENABLE_TRAINING:-OFF}" # ON | OFF -ENABLE_LIBTORCH="${FELIDAE_ENABLE_LIBTORCH:-auto}" # auto | ON | OFF -ENABLE_ROCKSDB="${FELIDAE_ENABLE_ROCKSDB:-auto}" # auto | ON | OFF -PLATFORM="${FELIDAE_PLATFORM:-auto}" # auto | linux | macos | windows | android | generic -ARCHITECTURE="${FELIDAE_ARCH:-auto}" # auto | x86_64 | arm64 | armv7 -ANDROID_API="${FELIDAE_ANDROID_API:-24}" -JOBS="${FELIDAE_JOBS:-auto}" -SANITIZE=0 - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# Direct-interpreter build entry point. It has no compiler, VM, model +# training, RocksDB, or external runtime options. +MODE="debug" +RUN_TESTS=0 +JOBS="" usage() { - echo "usage: ./build.sh [--mode test|release] [--training ON|OFF] [--libtorch ON|OFF] [--rocksdb ON|OFF]" - echo " [--platform auto|linux|macos|windows|android|generic]" - echo " [--arch auto|x86_64|arm64|armv7] [--android-api N]" - echo " [--jobs N|auto] [--sanitize]" -} - -normalize_boolean() { - case "${1,,}" in - 1|on|true|yes) echo ON ;; - 0|off|false|no) echo OFF ;; - *) echo "Invalid boolean value: $1" >&2; exit 2 ;; - esac + echo "usage: ./build.sh [debug|release|sanitize] [--test] [--jobs N]" } while [[ $# -gt 0 ]]; do case "$1" in - --mode) MODE="${2:-}"; shift 2 ;; - --training) ENABLE_TRAINING="${2:-}"; shift 2 ;; - --libtorch) ENABLE_LIBTORCH="${2:-}"; shift 2 ;; - --rocksdb) ENABLE_ROCKSDB="${2:-}"; shift 2 ;; - --platform) PLATFORM="${2:-}"; shift 2 ;; - --arch) ARCHITECTURE="${2:-}"; shift 2 ;; - --android-api) ANDROID_API="${2:-}"; shift 2 ;; - --jobs) JOBS="${2:-}"; shift 2 ;; - --sanitize) SANITIZE=1; shift ;; - --configuration) - case "${2:-}" in - debug) MODE=test ;; - release|production) MODE=release ;; - sanitize) MODE=test; SANITIZE=1 ;; - *) echo "Unknown configuration: ${2:-}" >&2; exit 2 ;; - esac + debug|release|sanitize) MODE="$1"; shift ;; + --test) RUN_TESTS=1; shift ;; + --jobs) + JOBS="${2:-}" + [[ "$JOBS" =~ ^[1-9][0-9]*$ ]] || { echo "--jobs expects a positive integer" >&2; exit 2; } shift 2 ;; - test|debug) MODE=test; shift ;; - release|production) MODE=release; shift ;; - sanitize) MODE=test; SANITIZE=1; shift ;; --help|-h) usage; exit 0 ;; - --warnings-as-errors|native) shift ;; - --target) - if [[ "${2:-}" != "native" ]]; then - echo "Only the CMake native target is supported" >&2 - exit 2 - fi - shift 2 - ;; - *) echo "Unknown build option: $1" >&2; usage >&2; exit 2 ;; + *) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;; esac done -case "${MODE,,}" in - test) MODE=test; CONFIGURATION=Debug; BUILD_TESTS=ON ;; - release) MODE=release; CONFIGURATION=Release; BUILD_TESTS=OFF ;; - *) echo "Invalid MODE '$MODE'; expected test or release" >&2; exit 2 ;; -esac - -if [[ "${PLATFORM,,}" == auto ]]; then - case "$(uname -s)" in - Linux) PLATFORM=linux ;; - Darwin) PLATFORM=macos ;; - MINGW*|MSYS*|CYGWIN*) PLATFORM=windows ;; - *) PLATFORM=generic ;; - esac -else - PLATFORM="${PLATFORM,,}" -fi -case "$PLATFORM" in linux|macos|windows|android|generic) ;; *) echo "Invalid platform '$PLATFORM'" >&2; exit 2 ;; esac - -if [[ "${ARCHITECTURE,,}" == auto ]]; then - case "$(uname -m)" in - x86_64|amd64) ARCHITECTURE=x86_64 ;; - arm64|aarch64) ARCHITECTURE=arm64 ;; - armv7*|armhf) ARCHITECTURE=armv7 ;; - *) ARCHITECTURE="$(uname -m)" ;; - esac -else - ARCHITECTURE="${ARCHITECTURE,,}" -fi -case "$(uname -m)" in - x86_64|amd64) HOST_ARCHITECTURE=x86_64 ;; - arm64|aarch64) HOST_ARCHITECTURE=arm64 ;; - armv7*|armhf) HOST_ARCHITECTURE=armv7 ;; - *) HOST_ARCHITECTURE="$(uname -m)" ;; +case "$MODE" in + debug) BUILD_TYPE=Debug; BUILD_DIR=build/debug; SANITIZERS=OFF ;; + release) BUILD_TYPE=Release; BUILD_DIR=build/release; SANITIZERS=OFF ;; + sanitize) BUILD_TYPE=Debug; BUILD_DIR=build/asan; SANITIZERS=ON ;; esac -ENABLE_TRAINING="$(normalize_boolean "$ENABLE_TRAINING")" -if [[ "${ENABLE_LIBTORCH,,}" == auto ]]; then - if [[ "$PLATFORM" == android ]]; then - ENABLE_LIBTORCH=OFF - else - ENABLE_LIBTORCH=ON - fi -else - ENABLE_LIBTORCH="$(normalize_boolean "$ENABLE_LIBTORCH")" -fi -if [[ "${ENABLE_ROCKSDB,,}" == auto ]]; then - if [[ "$PLATFORM" == android ]]; then - ENABLE_ROCKSDB=OFF - else - ENABLE_ROCKSDB=ON - fi -else - ENABLE_ROCKSDB="$(normalize_boolean "$ENABLE_ROCKSDB")" -fi -if [[ "${JOBS,,}" == auto ]]; then - if command -v getconf >/dev/null 2>&1; then - JOBS="$(getconf _NPROCESSORS_ONLN)" - elif command -v sysctl >/dev/null 2>&1; then - JOBS="$(sysctl -n hw.ncpu)" - else - JOBS=1 - fi -fi -if [[ ! "$JOBS" =~ ^[1-9][0-9]*$ ]]; then - echo "Invalid job count '$JOBS'; expected auto or a positive integer" >&2 - exit 2 -fi -if [[ "$ENABLE_TRAINING" == ON && "$ENABLE_LIBTORCH" != ON ]]; then - echo "Training requires LibTorch; set ENABLE_LIBTORCH=ON" >&2 - exit 2 -fi - -if [[ "$PLATFORM" == linux && "$ARCHITECTURE" == "$HOST_ARCHITECTURE" ]]; then - DEFAULT_BUILD_DIR="${ROOT_DIR}/build/${MODE}" -else - DEFAULT_BUILD_DIR="${ROOT_DIR}/build/${PLATFORM}-${ARCHITECTURE}/${MODE}" -fi -BUILD_DIR="${FELIDAE_BUILD_DIR:-$DEFAULT_BUILD_DIR}" +BUILD_TESTS=OFF +if [[ "$RUN_TESTS" -eq 1 ]]; then BUILD_TESTS=ON; fi CMAKE_ARGS=( - -S "$ROOT_DIR" + -S . -B "$BUILD_DIR" - "-DCMAKE_BUILD_TYPE=${CONFIGURATION}" - "-DFELIDAE_BUILD_TESTS=${BUILD_TESTS}" - "-DFELIDAE_ENABLE_LIBTORCH=${ENABLE_LIBTORCH}" - "-DFELIDAE_ENABLE_TRAINING=${ENABLE_TRAINING}" - "-DFELIDAE_ENABLE_ROCKSDB=${ENABLE_ROCKSDB}" + "-DCMAKE_BUILD_TYPE=$BUILD_TYPE" + "-DFELIDAE_BUILD_TESTS=$BUILD_TESTS" + "-DFELIDAE_ENABLE_SANITIZERS=$SANITIZERS" ) -CAN_RUN_TESTS=1 -case "$PLATFORM" in - macos) - case "$ARCHITECTURE" in - arm64) CMAKE_ARGS+=("-DCMAKE_OSX_ARCHITECTURES=arm64") ;; - x86_64) CMAKE_ARGS+=("-DCMAKE_OSX_ARCHITECTURES=x86_64") ;; - *) echo "Unsupported macOS architecture '$ARCHITECTURE'" >&2; exit 2 ;; - esac - ;; - android) - NDK_DIR="${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}" - if [[ -z "$NDK_DIR" || ! -f "$NDK_DIR/build/cmake/android.toolchain.cmake" ]]; then - echo "Android builds require ANDROID_NDK_HOME (or ANDROID_NDK_ROOT)" >&2 - exit 2 - fi - case "$ARCHITECTURE" in - arm64) ANDROID_ABI=arm64-v8a ;; - armv7) ANDROID_ABI=armeabi-v7a ;; - x86_64) ANDROID_ABI=x86_64 ;; - *) echo "Unsupported Android architecture '$ARCHITECTURE'" >&2; exit 2 ;; - esac - CMAKE_ARGS+=( - "-DCMAKE_TOOLCHAIN_FILE=${NDK_DIR}/build/cmake/android.toolchain.cmake" - "-DANDROID_ABI=${ANDROID_ABI}" - "-DANDROID_PLATFORM=android-${ANDROID_API}" - ) - CAN_RUN_TESTS=0 - ;; -esac -if [[ -n "${FELIDAE_TOOLCHAIN_FILE:-}" ]]; then - CMAKE_ARGS+=("-DCMAKE_TOOLCHAIN_FILE=${FELIDAE_TOOLCHAIN_FILE}") - CAN_RUN_TESTS=0 -fi -if [[ "$ENABLE_LIBTORCH" == ON ]]; then - if [[ -z "${FELIDAE_LIBTORCH_PATH:-}" ]]; then - echo "LibTorch builds require FELIDAE_LIBTORCH_PATH to name the provisioned CPU LibTorch installation" >&2 - exit 2 - fi - CMAKE_ARGS+=("-DCMAKE_PREFIX_PATH=${FELIDAE_LIBTORCH_PATH}") -fi -if [[ -n "${FELIDAE_VERSION:-}" ]]; then - CMAKE_ARGS+=("-DFELIDAE_VERSION=${FELIDAE_VERSION}") -fi -if [[ "$SANITIZE" -eq 1 ]]; then - CMAKE_ARGS+=("-DFELIDAE_ENABLE_SANITIZERS=ON") -fi - -echo "Felidae platform=${PLATFORM} arch=${ARCHITECTURE} mode=${MODE} configuration=${CONFIGURATION} training=${ENABLE_TRAINING} libtorch=${ENABLE_LIBTORCH} rocksdb=${ENABLE_ROCKSDB} jobs=${JOBS}" cmake "${CMAKE_ARGS[@]}" -if [[ "$MODE" == test ]]; then - cmake --build "$BUILD_DIR" --config "$CONFIGURATION" \ - --target felidae_compiler felidae_vm felidae_debugger felidae_tests --parallel "$JOBS" - if [[ "$CAN_RUN_TESTS" -eq 1 ]]; then - ctest --test-dir "$BUILD_DIR" --build-config "$CONFIGURATION" --output-on-failure - else - echo "Cross-compiled tests were built but not executed on the host" - fi -else - cmake --build "$BUILD_DIR" --config "$CONFIGURATION" \ - --target felidae_dist --parallel "$JOBS" +BUILD_ARGS=(--build "$BUILD_DIR" --target felidae) +if [[ -n "$JOBS" ]]; then BUILD_ARGS+=(--parallel "$JOBS"); fi +cmake "${BUILD_ARGS[@]}" + +if [[ "$RUN_TESTS" -eq 1 ]]; then + ctest --test-dir "$BUILD_DIR" --output-on-failure fi diff --git a/cmake/BetaReleaseCheck.cmake b/cmake/BetaReleaseCheck.cmake deleted file mode 100644 index b1ee3f7..0000000 --- a/cmake/BetaReleaseCheck.cmake +++ /dev/null @@ -1,100 +0,0 @@ -if(NOT DEFINED FELIDAE_BETA_DIST_DIR OR NOT DEFINED FELIDAE_BETA_BUILD_DIR OR NOT DEFINED FELIDAE_BETA_EXAMPLE) - message(FATAL_ERROR "beta release check paths are incomplete") -endif() - -foreach(required bin/felidae_compiler.exe bin/felidae_vm.exe - bin/felidae_debugger.exe models/felidae.model SHA256SUMS.txt README.txt) - if(NOT EXISTS "${FELIDAE_BETA_DIST_DIR}/${required}") - message(FATAL_ERROR "beta distribution is missing ${required}") - endif() -endforeach() - -foreach(forbidden CMakeCache.txt compile_commands.json felidae_compiler.pdb felidae_vm.pdb) - if(EXISTS "${FELIDAE_BETA_DIST_DIR}/${forbidden}") - message(FATAL_ERROR "beta distribution contains build-only artifact ${forbidden}") - endif() -endforeach() - -# A release contains only the two tools, their runtime DLLs, a checksum/readme, -# and model artifacts. This catches accidental staging of build products. -file(GLOB_RECURSE staged_entries RELATIVE "${FELIDAE_BETA_DIST_DIR}" "${FELIDAE_BETA_DIST_DIR}/*") -foreach(entry IN LISTS staged_entries) - if(IS_DIRECTORY "${FELIDAE_BETA_DIST_DIR}/${entry}") - continue() - endif() - if(NOT entry MATCHES "^bin/(felidae_compiler|felidae_vm|felidae_debugger)\\.exe$|^bin/[^/]+\\.dll$|^(README|SHA256SUMS)\\.txt$|^models/.+\\.(model|pt|txt)$|^licenses/[^/]+\\.txt$") - message(FATAL_ERROR "beta distribution contains an unapproved file: ${entry}") - endif() -endforeach() - -# Verify every staged file except the checksum manifest itself, and require the -# manifest to cover every file it claims to ship. -file(STRINGS "${FELIDAE_BETA_DIST_DIR}/SHA256SUMS.txt" checksum_lines) -set(checksummed_files) -foreach(line IN LISTS checksum_lines) - if(line MATCHES "^#" OR line STREQUAL "") - continue() - endif() - if(NOT line MATCHES "^([0-9A-Fa-f]+) (.+)$") - message(FATAL_ERROR "beta checksum entry is malformed: ${line}") - endif() - set(expected_digest "${CMAKE_MATCH_1}") - set(checksummed_file "${CMAKE_MATCH_2}") - if(NOT EXISTS "${FELIDAE_BETA_DIST_DIR}/${checksummed_file}") - message(FATAL_ERROR "beta checksum target is missing: ${checksummed_file}") - endif() - file(SHA256 "${FELIDAE_BETA_DIST_DIR}/${checksummed_file}" actual_digest) - if(NOT actual_digest STREQUAL expected_digest) - message(FATAL_ERROR "beta checksum mismatch: ${checksummed_file}") - endif() - list(APPEND checksummed_files "${checksummed_file}") -endforeach() -foreach(entry IN LISTS staged_entries) - if(NOT IS_DIRECTORY "${FELIDAE_BETA_DIST_DIR}/${entry}" AND NOT entry STREQUAL "SHA256SUMS.txt") - list(FIND checksummed_files "${entry}" checksum_index) - if(checksum_index EQUAL -1) - message(FATAL_ERROR "beta distribution file is missing from SHA256SUMS.txt: ${entry}") - endif() - endif() -endforeach() - -execute_process(COMMAND "${FELIDAE_BETA_DIST_DIR}/felidae_compiler.exe" --version - RESULT_VARIABLE compiler_version_result OUTPUT_VARIABLE compiler_version ERROR_VARIABLE compiler_version_error) -if(NOT compiler_version_result EQUAL 0) - message(FATAL_ERROR "beta compiler does not start: ${compiler_version_error}") -endif() -execute_process(COMMAND "${FELIDAE_BETA_DIST_DIR}/felidae_vm.exe" --version - RESULT_VARIABLE vm_version_result OUTPUT_VARIABLE vm_version ERROR_VARIABLE vm_version_error) -if(NOT vm_version_result EQUAL 0) - message(FATAL_ERROR "beta VM does not start: ${vm_version_error}") -endif() - -get_filename_component(example_name "${FELIDAE_BETA_EXAMPLE}" NAME_WE) -# The compiler's contract is to write generated binaries to build/, never -# into the portable distribution. The staged VM still consumes that freshly -# generated artifact as a separate process. -set(binary "${FELIDAE_BETA_BUILD_DIR}/${example_name}.bin") -execute_process(COMMAND "${FELIDAE_BETA_DIST_DIR}/felidae_compiler.exe" "${FELIDAE_BETA_EXAMPLE}" - RESULT_VARIABLE compile_result OUTPUT_VARIABLE compile_output ERROR_VARIABLE compile_error) -if(NOT compile_result EQUAL 0 OR NOT EXISTS "${binary}") - message(FATAL_ERROR "beta compiler smoke failed: ${compile_error}${compile_output}") -endif() -execute_process(COMMAND "${FELIDAE_BETA_DIST_DIR}/felidae_vm.exe" "${binary}" - RESULT_VARIABLE vm_result OUTPUT_VARIABLE vm_output ERROR_VARIABLE vm_error) -if(NOT vm_result EQUAL 0) - message(FATAL_ERROR "beta VM smoke failed: ${vm_error}${vm_output}") -endif() -if(NOT vm_output MATCHES "756") - message(FATAL_ERROR "beta VM smoke output is unexpected: ${vm_output}") -endif() - -# The VM rejects the retired extension before it even opens a file; the gate -# deliberately does not create or stage an old-format artifact. -set(legacy_binary "${FELIDAE_BETA_DIST_DIR}/${example_name}.fir") -execute_process(COMMAND "${FELIDAE_BETA_DIST_DIR}/felidae_vm.exe" "${legacy_binary}" - RESULT_VARIABLE legacy_result OUTPUT_VARIABLE legacy_output ERROR_VARIABLE legacy_error) -if(legacy_result EQUAL 0 OR NOT legacy_error MATCHES "only \\.bin") - message(FATAL_ERROR "beta VM did not reject legacy .fir input: ${legacy_error}${legacy_output}") -endif() -file(REMOVE "${binary}") -message(STATUS "Felidae beta release check passed: ${compiler_version}${vm_version}") diff --git a/cmake/StageDistribution.cmake b/cmake/StageDistribution.cmake deleted file mode 100644 index 50f5954..0000000 --- a/cmake/StageDistribution.cmake +++ /dev/null @@ -1,119 +0,0 @@ -if(NOT DEFINED FELIDAE_DIST_DIR OR NOT DEFINED FELIDAE_DIST_BUILD_DIR OR - NOT DEFINED FELIDAE_DIST_CONFIG OR - NOT DEFINED FELIDAE_DIST_EXECUTABLE_SUFFIX OR - NOT DEFINED FELIDAE_DIST_MODEL_DIR OR NOT DEFINED FELIDAE_DIST_LICENSE_DIR OR - NOT DEFINED FELIDAE_DIST_VERSION OR - NOT DEFINED FELIDAE_DIST_HAS_LIBTORCH) - message(FATAL_ERROR "distribution staging paths are incomplete") -endif() - -if(NOT FELIDAE_DIST_CONFIG STREQUAL "Release") - message(FATAL_ERROR - "felidae_dist requires a Release configuration; received '${FELIDAE_DIST_CONFIG}'") -endif() - -# This directory is generated only by the explicit felidae_dist target inside -# the active build tree and is safe to replace wholesale after successful builds. -file(REMOVE_RECURSE "${FELIDAE_DIST_DIR}") -file(MAKE_DIRECTORY "${FELIDAE_DIST_DIR}/bin") -file(MAKE_DIRECTORY "${FELIDAE_DIST_DIR}/models") -file(MAKE_DIRECTORY "${FELIDAE_DIST_DIR}/licenses") - -foreach(executable felidae_compiler felidae_vm felidae_debugger) - set(executable_name "${executable}${FELIDAE_DIST_EXECUTABLE_SUFFIX}") - set(source "${FELIDAE_DIST_BUILD_DIR}/${executable_name}") - if(NOT EXISTS "${source}") - message(FATAL_ERROR "distribution executable is unavailable: ${source}") - endif() - file(COPY_FILE "${source}" "${FELIDAE_DIST_DIR}/bin/${executable_name}" ONLY_IF_DIFFERENT) -endforeach() - -if(NOT EXISTS "${FELIDAE_DIST_MODEL_DIR}/felidae.model") - message(FATAL_ERROR "fixed SentencePiece model is unavailable") -endif() -file(COPY "${FELIDAE_DIST_MODEL_DIR}/" DESTINATION "${FELIDAE_DIST_DIR}/models" - FILES_MATCHING PATTERN "*.model" PATTERN "*.pt" PATTERN "*.txt") - -# Post-build runtime discovery records the exact dependency closure for each -# executable. Never glob the build directory: it may also contain unrelated -# plugins or stale DLLs that are not part of the portable runtime contract. -set(runtime_names) -if(FELIDAE_DIST_HAS_LIBTORCH) - foreach(executable felidae_compiler felidae_vm) - set(runtime_manifest - "${FELIDAE_DIST_BUILD_DIR}/felidae-torch-runtime-${executable}.txt") - if(NOT EXISTS "${runtime_manifest}") - message(FATAL_ERROR "LibTorch runtime manifest is unavailable: ${runtime_manifest}") - endif() - file(STRINGS "${runtime_manifest}" executable_runtime_names) - list(APPEND runtime_names ${executable_runtime_names}) - endforeach() - list(REMOVE_DUPLICATES runtime_names) - list(SORT runtime_names) - foreach(runtime_name IN LISTS runtime_names) - if(NOT runtime_name MATCHES "^[A-Za-z0-9_.+-]+\\.(dll|so(\\.[0-9.]+)?|dylib)$") - message(FATAL_ERROR "invalid LibTorch runtime manifest entry: ${runtime_name}") - endif() - set(source_dll "${FELIDAE_DIST_BUILD_DIR}/${runtime_name}") - if(NOT EXISTS "${source_dll}") - message(FATAL_ERROR "resolved LibTorch runtime DLL is unavailable: ${source_dll}") - endif() - file(COPY_FILE "${source_dll}" "${FELIDAE_DIST_DIR}/bin/${runtime_name}" ONLY_IF_DIFFERENT) - endforeach() - if(DEFINED FELIDAE_DIST_TORCH_ROOT AND EXISTS "${FELIDAE_DIST_TORCH_ROOT}/LICENSE") - file(COPY_FILE "${FELIDAE_DIST_TORCH_ROOT}/LICENSE" - "${FELIDAE_DIST_DIR}/licenses/LibTorch-LICENSE.txt" ONLY_IF_DIFFERENT) - else() - message(FATAL_ERROR "LibTorch license is unavailable") - endif() -endif() - -foreach(license_spec - "sentencepiece/LICENSE/SentencePiece-LICENSE.txt" - "protobuf/LICENSE/Protobuf-LICENSE.txt" - "abseil-cpp/LICENSE/Abseil-LICENSE.txt" - "nlohmann_json/LICENSE.MIT/nlohmann-json-LICENSE.txt") - string(REPLACE "/" ";" license_fields "${license_spec}") - list(GET license_fields 0 license_project) - list(GET license_fields 1 license_source_name) - list(GET license_fields 2 license_staged_name) - set(license_source - "${FELIDAE_DIST_LICENSE_DIR}/${license_project}/${license_source_name}") - if(NOT EXISTS "${license_source}") - message(FATAL_ERROR "required dependency license is unavailable: ${license_source}") - endif() - file(COPY_FILE "${license_source}" - "${FELIDAE_DIST_DIR}/licenses/${license_staged_name}" ONLY_IF_DIFFERENT) -endforeach() - -file(WRITE "${FELIDAE_DIST_DIR}/README.txt" -"Felidae ${FELIDAE_DIST_VERSION} portable distribution\n\nRun the programs under bin/:\n felidae_compiler${FELIDAE_DIST_EXECUTABLE_SUFFIX} program.fx\n felidae_vm${FELIDAE_DIST_EXECUTABLE_SUFFIX} program.bin\n felidae_debugger${FELIDAE_DIST_EXECUTABLE_SUFFIX} --help\n\nmodels/felidae.model is required for SentencePiece encoding and symbol decoding.\nRequired LibTorch runtime libraries are staged beside the executables.\nThird-party notices are under licenses/.\n") - -set(release_files - "bin/felidae_compiler${FELIDAE_DIST_EXECUTABLE_SUFFIX}" - "bin/felidae_vm${FELIDAE_DIST_EXECUTABLE_SUFFIX}" - "bin/felidae_debugger${FELIDAE_DIST_EXECUTABLE_SUFFIX}" - README.txt) -foreach(runtime_name IN LISTS runtime_names) - list(APPEND release_files "bin/${runtime_name}") -endforeach() -file(GLOB staged_license_entries RELATIVE "${FELIDAE_DIST_DIR}" - "${FELIDAE_DIST_DIR}/licenses/*") -list(APPEND release_files ${staged_license_entries}) -# All copied model artifacts, including nested GRU checkpoints and manifests, -# are part of the release integrity boundary rather than an unchecked sidecar. -file(GLOB_RECURSE staged_model_entries RELATIVE "${FELIDAE_DIST_DIR}" - "${FELIDAE_DIST_DIR}/models/*") -foreach(entry IN LISTS staged_model_entries) - if(NOT IS_DIRECTORY "${FELIDAE_DIST_DIR}/${entry}") - list(APPEND release_files "${entry}") - endif() -endforeach() -list(REMOVE_DUPLICATES release_files) -list(SORT release_files) -set(checksums "# Felidae ${FELIDAE_DIST_VERSION} beta distribution SHA-256\n") -foreach(release_file IN LISTS release_files) - file(SHA256 "${FELIDAE_DIST_DIR}/${release_file}" digest) - string(APPEND checksums "${digest} ${release_file}\n") -endforeach() -file(WRITE "${FELIDAE_DIST_DIR}/SHA256SUMS.txt" "${checksums}") diff --git a/code.md b/code.md index 4a13751..e3cc47e 100644 --- a/code.md +++ b/code.md @@ -1,49 +1,30 @@ # Felidae architecture -Felidae parses one source representation only: +Felidae executes source directly. There is no compiler, IR, binary artifact, +VM, or statistical mixfix model in the supported path. ```text source.fx - -> SentencePiece Encode (IDs and UTF-8 byte offsets, once) + -> custom BPE tokenizer (stable line IDs and byte offsets) -> IntegerTokenList -> IntegerParser - -> AST compiler / SymbolId interning - -> verified integer IR - -> .bin binary artifact - -> Form RegisterVm + -> Program AST / SymbolId interning + -> Interpreter::addProgram + -> solve / callMain / callAutoEntry ``` -`felidae.model` is the lexical model. `src/FelidaeSentencePieceIds.h` is the -generated runtime vocabulary: it defines every `TokenId` used by the integer -parser. `src/FelidaeGrammar.h` is not a second ID table; it is the declarative -spelling specification consumed only when generating and validating the -model. +`models/felidae-bpe/model.txt` is the checked-in, line-oriented identifier +vocabulary: line N is token ID N. The normal lexer owns fixed syntax, comments, +numbers, and strings; only identifiers and mixfix anchors use BPE. Unknown +identifier words are added in source order, and execution needs no training. -`IntegerTokenList` performs one full-source `SentencePieceProcessor::Encode` -call and preserves its byte offsets. It does not classify pieces, scan source -characters, or synthesize tokens. `IntegerParser` consumes ranges from that -same ID stream. Fixed grammar is matched by `TokenId`; multi-piece identifiers -are assembled as bounded payloads and interned after parsing. +`FactMemory` is Felidae's in-process fact database. It uses immutable, +copy-on-write relation roots and bounded snapshots; the interpreter reuses its +indexes, paging, provenance, rollback, and source reload behavior. -Mixfix literal anchors are encoded once at declaration time and matched as -piece-ID sequences. SentencePiece IDs are lexical only: runtime identity uses -Felidae `SymbolId` and semantic `BuiltinId` values. +Mixfix is deterministic parser and AST-interpreter behavior. Literal anchors +are tokenized from their source spelling and matched by the registered +operator registry; no SSM participates. -There is no Felidae lexer, `TokenType`, legacy parser, fallback tokenizer, or -fragment re-encoding path. Celidae is deprecated and excluded from the active -Felidae build and quality scope. - -## Validation and measurement - -`felidae_sentencepiece_model_test` validates that each declared grammar symbol -has exactly one atomic model piece and its generated ID matches the model. -It also covers ID-only parsing, offsets, Unicode identifiers, native qualified -calls, nested mixfix patterns, parser bounds, and one-encode invariants. - -`felidae_integer_parser_benchmark` reports model initialization, full-source -encoding, parser work, token count, iteration count, recursion depth, and -backtracking attempts. Use `--dump-ids` to inspect model IDs and offsets for a -source file without invoking the parser. - -`./quality_check.sh` uses a single low-priority build job by default. Expensive -sanitizer, Valgrind, and stress modes are opt-in. +Run `felidae program.fx`, or `felidae program.fx --serve` to replace the live +interpreter after a successful source reload. diff --git a/core/csv.fx b/core/csv.fx index a1c2c91..d276480 100644 --- a/core/csv.fx +++ b/core/csv.fx @@ -1,5 +1,4 @@ -# CSV operations are compiler-known declarations. The compiler emits a -# Builtin IR instruction and RegisterVm calls src/form/libs/Csv.cpp directly. +# CSV operations are declared in source and dispatched by the AST interpreter. csv.parse(data: string) => () csv.toFacts(data: string, type: string) => () diff --git a/core/db.fx b/core/db.fx new file mode 100644 index 0000000..75ae7aa --- /dev/null +++ b/core/db.fx @@ -0,0 +1,4 @@ +# Direct fact-database source synchronization. Ordinary Type.insert, +# Type.where(...).update, and Type.where(...).delete are language operations +# and do not require importing this declaration. +db.sync(path: string) => () diff --git a/core/group.fx b/core/group.fx index 13a860c..ff141ad 100644 --- a/core/group.fx +++ b/core/group.fx @@ -1,7 +1,6 @@ # Finite group operations use an explicit Cayley table: # [{left: a, right: b, result: c}, ...] -# The compiler emits Builtin IR and RegisterVm calls -# src/form/libs/Group.cpp directly. +# The AST interpreter dispatches these builtins directly. Group.validate(set: array, table: array, identity: any) => () Group.closed(set: array, table: array) => () diff --git a/core/json.fx b/core/json.fx index 0b45572..28f4e40 100644 --- a/core/json.fx +++ b/core/json.fx @@ -1,5 +1,4 @@ -# JSON operations are compiler-known declarations. The compiler emits a -# Builtin IR instruction and RegisterVm calls src/form/libs/Json.cpp directly. +# JSON operations are declared in source and dispatched by the AST interpreter. json.parse(data: string) => () json.get(data: any, key: string) => () diff --git a/core/set.fx b/core/set.fx index d0e11c7..7dd3acf 100644 --- a/core/set.fx +++ b/core/set.fx @@ -1,4 +1,4 @@ -# Set mathematics is direct Builtin IR executed by RegisterVm. +# Set mathematics is dispatched directly by the AST interpreter. Set.union(sets: array) => () Set.intersection(sets: array) => () diff --git a/datasets/compiler/README.md b/datasets/compiler/README.md deleted file mode 100644 index 1ac5f3c..0000000 --- a/datasets/compiler/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# Compiler mixfix corpus - -Canonical positive file: `mixfix-v1.jsonl`. Rejection-evaluation file: -`mixfix-invalid-v1.jsonl`. - -The dataset is JSON Lines, with one versioned record per line: - -```json -{"schema_version":3,"sentencepiece_model_identity":"sha256:...","compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[1,2],"target_ids":[3,0]} -``` - -The target sequence ends in `IR_END`. The output vocabulary is the parser's -fixed structural vocabulary; constants and symbols remain bounded references -resolved by the compiler context. `mixfix-v1.jsonl` is generated from valid, -deterministically resolved `v2_examples/` spans with -`felidae_extract_mixfix_dataset`, plus deterministic parser-validated -permutations of arithmetic, twelve-level right-nested chains, wide -repeated-anchor forms, heterogeneous typed overloads, and safe-target -abstentions. -Records whose teacher IR cannot fit the -fixed structural bounds are reported and excluded rather than truncated. No -trained mixfix artifact is currently shipped. - -Structurally valid spans that require model target selection receive a single -`ABSTAIN` teacher token instead of fabricated executable IR. Invalid programs -receive `REJECT`; deterministic teachers begin with `ACCEPT`. Complete REJECT -and ABSTAIN families keep most records in training and deterministic held-out -records in validation and test, so safe ambiguity handling is measured. -Executable target families remain isolated across partitions. - -`input_ids` are meaningful only for the exact fixed tokenizer that produced -them. Every record therefore carries `sentencepiece_model_identity`; the C++ -trainer rejects stale corpora after any tokenizer regeneration. -`compiler_ir_vocabulary` similarly prevents training against target IDs from -an older internal compiler-IR opcode layout. It does not change the stable -Felidae executable-IR opcode IDs. - -Current invalid programs named `v2_examples/invalid_*.fx` are kept in the -separate integer-only rejection-evaluation set. Its records contain -`input_ids` and `rejection_stage` (`1` parser, `2` compiler, `3` verified -runtime), an explicit `REJECT` target, and no executable compiler IR. They are -real negative training records: the model learns the bounded rejection -decision without receiving fabricated opcodes. Use them also to measure that a -compiler build rejects malformed input at the intended boundary. - -The trainer splits executable structural target families, not random records: -numeric variations of a generated mixfix template cannot leak into both train -and validation. It reports teacher-forced loss, autoregressive exact sequence -matches, first-decision accuracy, and invalid autoregressive decodes. Small -target families remain training-only and are reported through the family and -validation counts. - -Regenerate both corpora together: - -```text -cmake --build build/debug --target felidae_extract_mixfix_dataset --parallel 8 -./build/debug/felidae_extract_mixfix_dataset datasets/compiler/mixfix-v1.jsonl v2_examples --rejections datasets/compiler/mixfix-invalid-v1.jsonl -``` diff --git a/datasets/compiler/mixfix-invalid-v1.jsonl b/datasets/compiler/mixfix-invalid-v1.jsonl deleted file mode 100644 index 9bd58f7..0000000 --- a/datasets/compiler/mixfix-invalid-v1.jsonl +++ /dev/null @@ -1,22 +0,0 @@ -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[1,45,16,47,45,45,45,45,42,988,898,326,4,996,574,989,325,986,34,985,340,990,728,324,996,978,24,990,1002,42,22,47,45,45,45,45,42,988,898,326,4,996,574,989,325,986,34,985,340,990,728,324,996,993,24,990,1002,42,47,17,47,47,318,16,17,45,30,47,45,45,45,45,9,45,57,45,985,340,990,728,324,1004,317,361,45,52,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[125,437,979,987,328,997,1005,977,532,980,333,975,45,11,45,138,898,326,4,1005,977,532,980,333,975,16,342,23,45,357,17,47,47,27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,315,924,410,125,437,979,987,328,997,22,47,45,45,45,45,657,23,45,42,18,377,19,45,315,924,410,125,437,979,987,328,997,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,353,4,986,23,45,20,571,317,23,45,125,437,979,987,328,997,1005,977,532,980,333,975,22,45,637,23,45,125,437,979,987,328,997,1005,977,532,980,333,975,21,22,47,45,45,45,45,905,585,23,45,357,47,17,47,315,924,410,125,437,979,987,810,708,16,17,45,30,47,45,45,45,45,9,45,377,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[1007,980,983,364,1005,977,532,980,333,975,45,11,45,138,898,326,4,1005,977,532,980,333,975,16,342,23,45,357,17,47,142,702,340,987,1005,977,532,980,333,975,45,11,45,138,898,326,4,1005,977,532,980,333,975,16,342,23,45,357,17,47,47,27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,315,924,410,1007,548,4,986,22,47,45,45,45,45,657,23,45,42,18,377,19,45,315,924,410,1007,548,4,986,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,353,4,23,45,349,983,364,23,45,1007,980,983,364,1005,977,532,980,333,975,22,47,45,45,45,45,353,4,986,23,45,20,352,985,340,987,23,45,142,702,340,987,1005,977,532,980,333,975,21,22,47,45,45,45,45,905,585,23,45,357,47,17,47,315,924,410,1007,548,4,674,518,328,551,340,16,17,45,30,47,45,45,45,45,9,45,377,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,979,988,433,997,673,987,22,47,45,45,45,45,657,23,45,42,18,377,19,45,979,988,433,997,673,987,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,905,585,23,45,357,22,47,45,45,45,45,470,324,986,23,45,991,989,333,47,17,47,979,988,433,997,673,987,137,921,334,16,17,45,30,47,45,45,45,45,986,997,364,706,24,754,315,981,16,342,23,45,377,17,47,45,45,45,45,9,45,377,45,31,45,399,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[137,989,488,1005,977,532,980,333,975,45,11,45,138,898,326,4,1005,977,532,980,333,975,16,342,23,45,357,17,47,47,989,741,978,431,1003,994,702,1010,16,17,45,30,47,45,45,45,45,9,45,13,47,47,27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,989,741,978,431,1003,340,478,22,47,45,45,45,45,657,23,45,42,18,377,19,45,989,741,978,431,1003,340,478,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,353,4,23,45,500,1005,977,532,980,333,975,23,45,137,989,488,1005,977,532,980,333,975,22,47,45,45,45,45,905,585,23,45,357,47,17,47,989,741,978,431,1003,340,478,137,921,334,16,17,45,30,47,45,45,45,45,9,45,500,1005,977,532,980,333,975,24,342,47,47,27,875,347,317,16,47,45,45,45,45,988,898,326,4,23,45,989,741,978,431,1003,340,478,22,47,45,45,45,45,657,23,45,42,18,377,19,45,989,741,978,431,1003,340,478,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,580,698,822,23,45,20,500,1005,977,532,980,333,975,23,45,137,989,488,1005,977,532,980,333,975,21,47,17,47,875,347,146,866,1005,922,384,977,1003,320,984,16,17,45,30,47,45,45,45,45,10,45,989,741,978,431,1003,994,702,1010,16,17,45,36,45,13,47,45,45,45,45,9,45,1005,977,532,980,333,975,1004,326,347,16,47,45,45,45,45,45,45,45,45,500,1005,977,532,980,333,975,23,45,137,989,488,1005,977,532,980,333,975,16,342,23,45,377,17,47,45,45,45,45,17,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[138,898,326,4,1005,977,532,980,333,975,16,17,47,1006,433,980,993,337,345,1005,977,532,980,333,975,45,11,45,138,898,326,4,1005,977,532,980,333,975,16,342,23,45,357,17,47,47,27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,754,350,443,1006,433,980,993,337,345,1003,994,702,1010,22,47,45,45,45,45,657,23,45,42,18,377,19,45,995,433,980,993,337,345,1003,994,702,1010,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,905,585,23,45,357,22,47,45,45,45,45,667,23,45,333,984,551,340,986,452,22,47,45,45,45,45,6,669,23,45,979,340,977,22,47,45,45,45,45,554,987,315,320,345,23,45,340,977,22,47,45,45,45,45,470,324,986,23,45,991,989,333,22,47,45,45,45,45,995,433,980,993,337,345,23,45,754,350,443,47,17,47,754,350,443,1003,994,702,1010,16,17,45,30,47,45,45,45,45,9,45,377,47,47,27,875,347,317,16,47,45,45,45,45,988,898,326,4,23,45,754,350,443,1006,433,980,993,337,345,1003,994,702,1010,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,580,698,822,23,45,20,333,532,980,333,975,23,45,1006,433,980,993,337,345,1005,977,532,980,333,975,21,22,47,45,45,45,45,995,433,980,993,337,345,23,45,991,772,984,331,47,17,47,991,772,984,331,1004,326,347,317,16,17,45,30,47,45,45,45,45,9,45,1005,977,532,980,333,975,1004,326,347,16,47,45,45,45,45,45,45,45,45,333,532,980,333,975,23,45,1006,433,980,993,337,345,1005,977,532,980,333,975,16,342,23,45,377,24,984,332,317,320,419,17,47,45,45,45,45,17,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[146,385,529,360,1005,977,532,980,333,975,45,11,45,138,898,326,4,1005,977,532,980,333,975,16,342,23,45,357,17,47,47,27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,999,385,529,360,1003,340,478,22,47,45,45,45,45,657,23,45,42,18,377,19,45,999,385,529,360,1003,340,478,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,353,4,23,45,999,385,529,360,23,45,146,385,529,360,1005,977,532,980,333,975,22,47,45,45,45,45,905,585,23,45,357,47,17,47,989,352,146,385,529,360,1005,977,532,980,333,975,16,17,45,30,47,45,45,45,45,9,45,999,385,529,360,24,342,47,47,27,875,347,317,16,47,45,45,45,45,988,898,326,4,23,45,999,385,529,360,1003,340,478,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,580,698,822,23,45,20,999,385,529,360,23,45,146,385,529,360,1005,977,532,980,333,975,21,47,17,47,315,924,410,146,385,529,317,16,17,45,30,47,45,45,45,45,9,45,146,385,529,360,1005,977,532,980,333,975,16,342,23,45,377,17,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,644,16,657,23,45,42,18,377,23,45,462,393,19,45,333,532,980,905,45,18,399,23,45,644,19,42,17,47,333,532,980,905,137,977,364,360,16,17,45,30,47,45,45,45,45,9,45,377,47,47,318,16,17,45,30,47,45,45,45,45,9,45,42,498,42,45,333,532,980,905,45,42,978,45,528,804,45,462,393,42,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,644,16,657,23,45,42,18,986,895,346,23,45,462,393,19,45,341,781,708,45,18,335,364,315,551,340,23,45,462,393,19,45,981,749,328,987,45,18,749,979,317,23,45,462,393,19,42,17,47,341,989,765,419,16,17,45,30,47,45,45,45,45,9,45,986,895,346,47,47,318,16,17,45,30,47,45,45,45,45,9,45,42,498,42,45,341,781,708,45,42,333,6,340,317,42,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,644,16,47,45,45,45,45,988,898,326,4,23,45,333,698,979,987,343,981,998,868,22,47,45,45,45,45,657,23,45,42,528,343,45,18,323,23,45,462,393,19,45,537,393,45,18,462,443,992,997,23,45,462,393,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,323,23,45,462,393,22,45,462,443,992,997,23,45,462,393,19,47,17,47,528,343,317,16,17,45,30,47,45,45,45,45,9,45,998,868,16,323,23,45,323,22,45,462,443,992,997,23,45,462,443,992,997,17,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[318,1003,320,984,16,17,45,30,47,45,45,45,45,9,45,51,45,984,443,1003,988,338,365,45,52,47,47,318,1003,320,984,16,17,47,47,27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,984,443,1003,988,338,365,22,47,45,45,45,45,657,23,45,42,18,377,19,45,984,443,1003,988,338,365,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,905,585,23,45,357,47,17,47,359,338,365,1008,443,16,17,45,30,47,45,45,45,45,9,45,377,45,31,45,399,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,333,532,980,333,987,998,988,986,332,374,22,47,45,45,45,45,657,23,45,42,333,532,980,333,987,998,988,986,332,374,45,18,342,19,42,22,47,45,45,45,45,770,752,23,45,579,562,22,47,45,45,45,45,691,530,989,905,23,45,18,342,23,45,357,19,22,47,45,45,45,45,905,585,23,45,357,22,47,45,45,45,45,667,23,45,579,562,22,47,45,45,45,45,6,669,23,45,399,22,47,45,45,45,45,554,987,315,320,345,23,45,340,977,22,47,45,45,45,45,470,324,986,23,45,991,989,333,22,47,45,45,45,45,995,433,980,993,337,345,23,45,754,350,443,47,17,47,991,988,986,332,374,138,979,984,997,16,17,45,30,47,45,45,45,45,10,45,342,45,40,45,49,47,45,45,45,45,9,45,342,47,47,318,16,17,45,30,47,45,45,45,45,9,45,333,532,980,333,987,998,988,986,332,374,45,32,50,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,644,16,47,45,45,45,45,657,23,45,42,359,338,365,45,18,377,23,45,357,19,45,999,866,45,18,399,23,45,357,19,42,47,17,47,333,698,979,987,343,981,16,377,23,45,357,22,45,399,23,45,357,17,45,30,47,45,45,45,45,9,45,377,45,31,45,399,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,375,990,4,982,360,998,333,562,22,47,45,45,45,45,657,23,45,42,381,990,4,977,45,18,342,19,42,22,47,45,45,45,45,770,752,23,45,315,562,22,47,45,45,45,45,691,530,989,905,23,45,18,342,23,45,357,19,22,47,45,45,45,45,905,585,23,45,357,22,47,45,45,45,45,667,23,45,579,562,22,47,45,45,45,45,6,669,23,45,399,22,47,45,45,45,45,554,987,315,320,345,23,45,340,977,22,47,45,45,45,45,470,324,986,23,45,991,989,333,22,47,45,45,45,45,995,433,980,993,337,345,23,45,754,350,443,47,17,47,375,990,4,982,360,16,17,45,30,47,45,45,45,45,9,45,342,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[1,45,42,24,24,34,988,898,326,4,996,574,989,325,986,34,754,350,443,996,476,24,990,1002,42,47,47,318,16,17,45,30,47,45,45,45,45,9,45,16,342,23,45,51,45,352,985,333,981,125,454,987,45,52,17,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,989,741,978,431,407,987,22,47,45,45,45,45,657,23,45,42,18,377,19,45,3,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,408,527,22,45,399,23,45,408,527,19,22,47,45,45,45,45,905,585,23,45,408,527,22,47,45,45,45,45,667,23,45,333,984,551,340,986,452,22,47,45,45,45,45,6,669,23,45,377,22,47,45,45,45,45,554,987,315,320,345,23,45,340,977,22,47,45,45,45,45,470,324,986,23,45,991,989,333,22,47,45,45,45,45,995,433,980,993,337,345,23,45,754,350,443,47,17,47,333,528,799,407,987,16,17,45,30,47,45,45,45,45,9,45,14,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,989,741,978,431,1001,532,320,345,22,47,45,45,45,45,657,23,45,42,18,377,19,45,36,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,343,997,22,45,399,23,45,343,997,19,22,47,45,45,45,45,905,585,23,45,408,527,22,47,45,45,45,45,667,23,45,4,557,393,22,47,45,45,45,45,6,669,23,45,979,340,977,22,47,45,45,45,45,554,987,315,320,345,23,45,340,977,22,47,45,45,45,45,470,324,986,23,45,991,989,333,22,47,45,45,45,45,995,433,980,993,337,345,23,45,754,350,443,47,17,47,333,528,799,1001,532,320,345,16,17,45,30,47,45,45,45,45,9,45,13,47,47,318,16,17,45,30,47,45,45,45,45,9,45,50,45,36,45,51,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[423,16,410,23,45,42,977,49,50,42,17,45,6,47],"rejection_stage":1,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[450,713,993,325,16,17,45,6,45,783,364,423,45,30,47,45,45,45,45,9,45,16,17,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,655,407,2,551,340,16,724,993,370,23,45,42,777,1010,979,749,979,42,17,47,335,985,4,326,360,16,17,45,30,47,45,45,45,45,9,45,42,777,333,800,978,993,325,42,47,47,318,16,17,45,30,47,45,45,45,45,9,45,335,985,4,326,360,16,17,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,985,340,990,728,324,1004,317,361,22,47,45,45,45,45,657,23,45,42,18,377,19,45,985,340,990,728,324,1004,317,361,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,905,585,23,45,357,22,47,45,45,45,45,995,433,980,993,337,345,23,45,991,772,984,331,47,17,47,456,361,1007,341,982,1000,16,17,45,30,47,45,45,45,45,9,45,377,45,31,45,399,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"REJECT","input_ids":[27,988,995,317,344,358,16,47,45,45,45,45,988,898,326,4,23,45,985,340,990,728,324,1004,317,361,22,47,45,45,45,45,657,23,45,42,18,377,19,45,985,340,990,728,324,1004,317,361,45,18,399,19,42,22,47,45,45,45,45,691,530,989,905,23,45,18,377,23,45,357,22,45,399,23,45,357,19,22,47,45,45,45,45,905,585,23,45,357,22,47,45,45,45,45,995,433,980,993,337,345,23,45,991,772,984,331,47,17,47,456,361,1007,341,982,125,16,17,45,30,47,45,45,45,45,9,45,377,45,32,45,399,47],"rejection_stage":2,"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[1]} diff --git a/datasets/compiler/mixfix-v1.jsonl b/datasets/compiler/mixfix-v1.jsonl deleted file mode 100644 index 70d0ae3..0000000 --- a/datasets/compiler/mixfix-v1.jsonl +++ /dev/null @@ -1,196 +0,0 @@ -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[359,527,393,996,580,745,45,999,812,343,768,45,42,359,527,393,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[981,720,317,1007,840,325,45,461,473,1009,988,45,445,1007,840,325,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,16,36,166,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[981,720,317,1004,320,977,45,461,473,1009,988,45,445,1007,840,325,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,16,36,166,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[981,720,317,1004,320,977,45,461,473,1009,988,45,445,1004,320,977,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,16,36,166,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[981,720,317,1004,320,977,45,461,473,1009,988,45,981,720,317,1007,840,325,47,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,16,36,166,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,51,45,38,45,52,17,45,315,986,752,417],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,4,39,101,13,37,38,39,38,16,36,164,37,37,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[359,710,369,996,580,745,45,329,803,986,45,42,359,710,369,45,433,45,987,433,991,319,760,993,325,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[45,999,994,326,45,433,45,498,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[45,999,994,326,45,433,45,532,343,981,776,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[45,999,994,326,45,433,45,993,343,1010,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[45,999,994,326,45,433,45,990,315,807,414,45,993,343,1010,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[990,315,807,414,45,993,343,1010],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,16,36,165,37,37,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[45,999,994,326,45,433,45,978,45,990,315,807,414,45,993,343,1010,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,978,45,990,315,807,414,45,993,343,1010,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,38,164,16,37,165,37,38,16,36,166,37,37,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,994,749,45,874,997,45,325,992,986,45,986,340,997,45,994,978,538],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,16,36,166,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,663,45,445,45,6,45,42,985,363,986,991,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,663,45,445,45,6,45,42,580,993,978,993,337,345,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,663,45,445,45,6,45,42,317,983,4,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,663,45,445,45,6,45,42,557,350,360,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,663,45,445,45,6,45,42,519,410,595,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,52,45,894,317,999,980,352,45,347,748,352,45,54,45,894,317,999,980,352,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,54,45,894,317,999,980,352,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,49,100,16,48,164,37,49,4,50,101,16,47,165,38,48,50,4,51,102,16,46,166,38,47,51,4,52,103,16,45,167,38,46,52,4,53,104,16,44,168,38,45,53,4,54,105,16,43,169,38,44,54,4,55,106,16,42,170,38,43,55,4,56,107,16,41,171,38,42,56,4,57,108,16,40,172,38,41,57,4,58,109,16,39,173,38,40,58,4,59,110,16,38,174,38,39,59,4,60,111,16,37,175,38,38,60,4,61,112,16,36,176,38,37,61,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,48,100,16,47,164,37,48,4,49,101,16,46,165,38,47,49,4,50,102,16,45,166,38,46,50,4,51,103,16,44,167,38,45,51,4,52,104,16,43,168,38,44,52,4,53,105,16,42,169,38,43,53,4,54,106,16,41,170,38,42,54,4,55,107,16,40,171,38,41,55,4,56,108,16,39,172,38,40,56,4,57,109,16,38,173,38,39,57,4,58,110,16,37,174,38,38,58,4,59,111,16,36,175,38,37,59,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,47,100,16,46,164,37,47,4,48,101,16,45,165,38,46,48,4,49,102,16,44,166,38,45,49,4,50,103,16,43,167,38,44,50,4,51,104,16,42,168,38,43,51,4,52,105,16,41,169,38,42,52,4,53,106,16,40,170,38,41,53,4,54,107,16,39,171,38,40,54,4,55,108,16,38,172,38,39,55,4,56,109,16,37,173,38,38,56,4,57,110,16,36,174,38,37,57,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,46,100,16,45,164,37,46,4,47,101,16,44,165,38,45,47,4,48,102,16,43,166,38,44,48,4,49,103,16,42,167,38,43,49,4,50,104,16,41,168,38,42,50,4,51,105,16,40,169,38,41,51,4,52,106,16,39,170,38,40,52,4,53,107,16,38,171,38,39,53,4,54,108,16,37,172,38,38,54,4,55,109,16,36,173,38,37,55,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,45,100,16,44,164,37,45,4,46,101,16,43,165,38,44,46,4,47,102,16,42,166,38,43,47,4,48,103,16,41,167,38,42,48,4,49,104,16,40,168,38,41,49,4,50,105,16,39,169,38,40,50,4,51,106,16,38,170,38,39,51,4,52,107,16,37,171,38,38,52,4,53,108,16,36,172,38,37,53,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,44,100,16,43,164,37,44,4,45,101,16,42,165,38,43,45,4,46,102,16,41,166,38,42,46,4,47,103,16,40,167,38,41,47,4,48,104,16,39,168,38,40,48,4,49,105,16,38,169,38,39,49,4,50,106,16,37,170,38,38,50,4,51,107,16,36,171,38,37,51,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,43,100,16,42,164,37,43,4,44,101,16,41,165,38,42,44,4,45,102,16,40,166,38,41,45,4,46,103,16,39,167,38,40,46,4,47,104,16,38,168,38,39,47,4,48,105,16,37,169,38,38,48,4,49,106,16,36,170,38,37,49,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,42,100,16,41,164,37,42,4,43,101,16,40,165,38,41,43,4,44,102,16,39,166,38,40,44,4,45,103,16,38,167,38,39,45,4,46,104,16,37,168,38,38,46,4,47,105,16,36,169,38,37,47,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,41,100,16,40,164,37,41,4,42,101,16,39,165,38,40,42,4,43,102,16,38,166,38,39,43,4,44,103,16,37,167,38,38,44,4,45,104,16,36,168,38,37,45,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,40,100,16,39,164,37,40,4,41,101,16,38,165,38,39,41,4,42,102,16,37,166,38,38,42,4,43,103,16,36,167,38,37,43,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,39,100,16,38,164,37,39,4,40,101,16,37,165,38,38,40,4,41,102,16,36,166,38,37,41,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,352,360,45,49,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,16,37,164,37,38,4,39,101,16,36,165,38,37,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,352,360,45,49,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,16,36,164,37,37,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,6,352,338,325,45,16,352,360,45,50,17,45,5,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,5,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,5,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,5,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,5,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,16,37,164,37,38,4,41,101,16,40,165,37,41,4,42,102,16,39,166,38,40,42,4,46,103,16,45,167,37,46,4,47,104,16,44,168,38,45,47,4,48,105,16,43,169,38,44,48,4,53,106,16,52,170,37,53,4,54,107,16,51,171,38,52,54,4,55,108,16,50,172,38,51,55,4,56,109,16,49,173,38,50,56,4,62,110,16,61,174,37,62,4,63,111,16,60,175,38,61,63,4,64,112,16,59,176,38,60,64,4,65,113,16,58,177,38,59,65,4,66,114,16,57,178,38,58,66,4,73,115,16,72,179,37,73,4,74,116,16,71,180,38,72,74,4,75,117,16,70,181,38,71,75,4,76,118,16,69,182,38,70,76,4,77,119,16,68,183,38,69,77,4,78,120,16,67,184,38,68,78,16,36,185,42,37,39,43,49,57,67,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,352,360,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,16,36,164,37,37,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,16,37,164,37,38,4,39,101,16,36,165,38,37,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,39,100,16,38,164,37,39,4,40,101,16,37,165,38,38,40,4,41,102,16,36,166,38,37,41,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,40,100,16,39,164,37,40,4,41,101,16,38,165,38,39,41,4,42,102,16,37,166,38,38,42,4,43,103,16,36,167,38,37,43,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,41,100,16,40,164,37,41,4,42,101,16,39,165,38,40,42,4,43,102,16,38,166,38,39,43,4,44,103,16,37,167,38,38,44,4,45,104,16,36,168,38,37,45,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,358,995,938,45,16,352,360,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17,45,993,997,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,42,100,16,41,164,37,42,4,43,101,16,40,165,38,41,43,4,44,102,16,39,166,38,40,44,4,45,103,16,38,167,38,39,45,4,46,104,16,37,168,38,38,46,4,47,105,16,36,169,38,37,47,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[53,45,993,454,987,45,54,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,359,338,365,45,16,50,45,993,454,987,45,51,17,45,999,866,45,16,52,45,993,454,987,45,325,685,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,4,39,101,16,37,164,38,38,39,4,41,102,5,42,165,16,40,166,38,41,42,16,36,167,38,37,40,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,50,45,993,454,987,45,51,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,52,45,993,454,987,45,325,685,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,5,38,164,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,411,320,977,45,16,359,338,365,45,993,983,343,347,45,999,866,45,16,988,710,352,981,45,16,51,45,993,454,987,45,52,17,45,993,997,45,16,50,45,993,454,987,45,50,17,17,17,45,993,997,45,16,51,45,993,454,987,45,50,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,38,164,4,41,100,4,42,101,16,40,165,38,41,42,4,44,102,4,45,103,16,43,166,38,44,45,16,39,167,38,40,43,16,37,168,38,38,39,4,47,104,4,48,105,16,46,169,38,47,48,16,36,170,38,37,46,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,359,338,365,45,993,983,343,347,45,999,866,45,16,988,710,352,981,45,16,51,45,993,454,987,45,52,17,45,993,997,45,16,50,45,993,454,987,45,50,17,17,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,40,100,4,41,101,16,39,165,38,40,41,4,43,102,4,44,103,16,42,166,38,43,44,16,38,167,38,39,42,16,36,168,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,988,710,352,981,45,16,51,45,993,454,987,45,52,17,45,993,997,45,16,50,45,993,454,987,45,50,17,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,4,39,101,16,37,164,38,38,39,4,41,102,4,42,103,16,40,165,38,41,42,16,36,166,38,37,40,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,51,45,993,454,987,45,52,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,50,45,993,454,987,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,51,45,993,454,987,45,50,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[333,6,340,45,583,523,324,45,537,393,45,519,410,595,45,999,866,315,45,985,340,478,45,999,855,45,985,340,987,332,864,47,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,5,39,166,5,40,167,16,36,168,40,37,38,39,40,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,646,45,981,720,317,45,686,804,364,45,519,410,595,45,999,866,315,45,985,340,478,45,999,855,45,16,981,720,317,24,325,992,986,45,36,45,53,45,3,45,13,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,5,39,166,5,42,167,4,43,100,13,41,42,43,36,15,41,70,4,44,103,15,44,70,4,40,101,14,73,4,40,102,16,36,168,40,37,38,39,40,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[55,57,45,6,352,986,352,987,45,993,997,45,462,340,992,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,5,38,164,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,56,45,359,338,365,45,51,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,466,328,977,45,981,720,317,45,387,341,989,372,45,42,761,328,360,32,852,365,32,973,413,42,45,999,866,45,445,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,5,39,165,16,36,166,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,466,328,977,45,445,45,387,341,989,372,45,42,761,328,360,32,643,32,973,413,42,45,999,866,45,987,746,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,5,39,165,16,36,166,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,333,6,340,45,42,981,720,317,42,45,537,393,45,519,410,595,45,999,866,315,45,985,340,478,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,5,38,164,5,39,165,16,36,166,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,924,631,45,518,978,384,45,999,866,45,42,668,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,4,38,100,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,924,631,45,16,333,6,340,45,42,445,42,45,537,393,45,519,410,595,45,999,866,315,45,985,340,478,17,45,999,866,45,42,668,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,5,39,164,5,40,165,16,37,166,39,38,39,40,4,41,101,16,36,167,38,37,41,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,333,6,340,45,42,445,42,45,537,393,45,519,410,595,45,999,866,315,45,985,340,478,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,5,38,164,5,39,165,16,36,166,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,45,767,809,990,4,982,45,52,45,999,866,45,53,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,50,45,31,45,50,17,45,767,809,990,4,982,45,16,51,45,31,45,50,17,45,999,866,45,51,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,4,39,101,8,37,38,39,4,41,102,4,42,103,8,40,41,42,4,43,104,16,36,164,39,37,40,43,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,528,343,45,42,580,555,989,333,42,45,537,393,45,42,320,984,32,467,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,528,343,45,56,45,537,393,45,13,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,528,343,45,42,580,555,989,333,42,45,537,393,45,42,320,984,32,467,42,45,999,866,45,50,49,45,999,855,45,13,45,554,983,997,393,45,20,42,1002,42,21,45,990,4,45,42,749,979,317,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,4,40,103,4,42,104,21,41,36,37,42,4,43,105,16,36,164,42,37,38,39,40,41,43,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,528,343,45,56,45,537,393,45,14,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,45,359,338,365,45,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[42,978,42,45,42,993,42,45,466,325,981,708],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[42,978,42,45,42,993,42,45,42,985,42,45,466,325,981,708],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[42,978,42,45,359,338,365,986,45,42,993,42,45,42,985,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[42,978,42,45,359,338,365,986,45,42,993,42,45,387,341,989,372,45,42,985,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,579,896,977,45,315,986,752,324,45,42,978,42,45,42,993,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[42,978,42,45,525,538,986,45,387,341,989,372,45,5,45,981,749,328,987,45,42,993,42,45,42,985,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[42,437,463,42,45,999,385,991,986,45,342,47,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[42,437,463,42,45,999,385,991,986,45,16,42,349,983,364,42,45,624,45,42,340,977,42,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,42,349,983,364,42,45,624,45,42,340,977,42,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[42,437,463,42,45,999,385,991,986,45,16,42,352,985,340,987,42,45,724,993,370,45,42,388,988,42,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,42,352,985,340,987,42,45,724,993,370,45,42,388,988,42,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[42,437,463,42,45,999,385,991,986,45,42,342,42,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,42,408,777,987,42,45,624,45,42,387,394,42,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[42,437,463,42,45,999,385,991,986,45,16,42,982,410,987,325,42,45,999,385,991,986,45,16,42,335,707,42,45,624,45,42,598,42,17,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[16,42,982,410,987,325,42,45,999,385,991,986,45,16,42,335,707,42,45,624,45,42,598,42,17,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,42,335,707,42,45,624,45,42,598,42,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,359,338,365,45,16,42,377,42,45,624,45,42,349,538,42,17,45,999,866,45,16,42,399,42,45,724,993,370,45,42,986,522,42,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,38,100,4,39,101,16,37,164,38,38,39,4,41,102,4,42,103,16,40,165,38,41,42,16,36,166,38,37,40,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,42,377,42,45,624,45,42,349,538,42,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,42,399,42,45,724,993,370,45,42,986,522,42,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[42,437,463,42,45,588,530,986,45,16,42,990,320,984,993,514,1010,42,45,624,45,42,352,926,42,17,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[16,42,990,320,984,993,514,1010,42,45,624,45,42,352,926,42,17],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,988,453,986,45,387,341,989,372,45,51],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,16,36,164,37,37,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[56,45,316,997,45,381,45,1000,408,538,45,54],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,45,316,997,45,381,45,1000,408,538,45,54,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,45,153,153,153,45,52,45,153,153,153,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[52,45,153,153,153,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,49,45,387,333,358,1003,988,338,365,45,51,51,47,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[377,24,1002,45,31,45,399,24,1002],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ABSTAIN","input_ids":[377,24,997,45,31,45,399,24,997,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[2]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[349,983,364,45,31,45,352,985,340,987,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,5,37,164,5,38,165,16,36,166,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,45,31,45,52,47,45,45,45,45],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,45,767,809,990,4,982,45,52,45,999,866,45,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,45,767,809,990,4,982,45,53,45,999,866,45,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[52,45,767,809,990,4,982,45,54,45,999,866,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[53,45,767,809,990,4,982,45,55,45,999,866,45,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[54,45,767,809,990,4,982,45,56,45,999,866,45,55,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[55,45,767,809,990,4,982,45,57,45,999,866,45,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[56,45,767,809,990,4,982,45,58,45,999,866,45,50,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[57,45,767,809,990,4,982,45,50,49,45,999,866,45,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[58,45,767,809,990,4,982,45,50,50,45,999,866,45,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,49,45,767,809,990,4,982,45,50,51,45,999,866,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,50,45,767,809,990,4,982,45,50,52,45,999,866,45,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,51,45,767,809,990,4,982,45,50,53,45,999,866,45,55,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,52,45,767,809,990,4,982,45,50,54,45,999,866,45,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,53,45,767,809,990,4,982,45,50,55,45,999,866,45,50,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,54,45,767,809,990,4,982,45,50,56,45,999,866,45,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,55,45,767,809,990,4,982,45,50,57,45,999,866,45,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,56,45,767,809,990,4,982,45,50,58,45,999,866,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,57,45,767,809,990,4,982,45,51,49,45,999,866,45,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[50,58,45,767,809,990,4,982,45,51,50,45,999,866,45,55,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,49,45,767,809,990,4,982,45,51,51,45,999,866,45,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,50,45,767,809,990,4,982,45,51,52,45,999,866,45,50,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,51,45,767,809,990,4,982,45,51,53,45,999,866,45,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,52,45,767,809,990,4,982,45,51,54,45,999,866,45,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[51,53,45,767,809,990,4,982,45,51,55,45,999,866,45,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,4,39,102,16,36,164,39,37,38,39,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,45,894,317,999,980,352,45,347,748,352,45,53,45,894,317,999,980,352,45,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,53,45,894,317,999,980,352,45,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,51,45,894,317,999,980,352,45,347,748,352,45,54,45,894,317,999,980,352,45,57,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,54,45,894,317,999,980,352,45,57,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,52,45,894,317,999,980,352,45,347,748,352,45,55,45,894,317,999,980,352,45,58,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,55,45,894,317,999,980,352,45,58,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,53,45,894,317,999,980,352,45,347,748,352,45,56,45,894,317,999,980,352,45,50,49,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,56,45,894,317,999,980,352,45,50,49,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,54,45,894,317,999,980,352,45,347,748,352,45,57,45,894,317,999,980,352,45,50,50,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,57,45,894,317,999,980,352,45,50,50,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,55,45,894,317,999,980,352,45,347,748,352,45,58,45,894,317,999,980,352,45,50,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,58,45,894,317,999,980,352,45,50,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,56,45,894,317,999,980,352,45,347,748,352,45,50,49,45,894,317,999,980,352,45,50,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,49,45,894,317,999,980,352,45,50,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,57,45,894,317,999,980,352,45,347,748,352,45,50,50,45,894,317,999,980,352,45,50,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,50,45,894,317,999,980,352,45,50,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,58,45,894,317,999,980,352,45,347,748,352,45,50,51,45,894,317,999,980,352,45,50,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,51,45,894,317,999,980,352,45,50,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,49,45,894,317,999,980,352,45,347,748,352,45,50,52,45,894,317,999,980,352,45,50,55,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,52,45,894,317,999,980,352,45,50,55,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,50,45,894,317,999,980,352,45,347,748,352,45,50,53,45,894,317,999,980,352,45,50,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,53,45,894,317,999,980,352,45,50,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,51,45,894,317,999,980,352,45,347,748,352,45,50,54,45,894,317,999,980,352,45,50,57,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,54,45,894,317,999,980,352,45,50,57,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,52,45,894,317,999,980,352,45,347,748,352,45,50,55,45,894,317,999,980,352,45,50,58,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,55,45,894,317,999,980,352,45,50,58,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,53,45,894,317,999,980,352,45,347,748,352,45,50,56,45,894,317,999,980,352,45,51,49,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,56,45,894,317,999,980,352,45,51,49,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,54,45,894,317,999,980,352,45,347,748,352,45,50,57,45,894,317,999,980,352,45,51,50,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,57,45,894,317,999,980,352,45,51,50,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,55,45,894,317,999,980,352,45,347,748,352,45,50,58,45,894,317,999,980,352,45,51,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,50,58,45,894,317,999,980,352,45,51,51,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,56,45,894,317,999,980,352,45,347,748,352,45,51,49,45,894,317,999,980,352,45,51,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,49,45,894,317,999,980,352,45,51,52,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,57,45,894,317,999,980,352,45,347,748,352,45,51,50,45,894,317,999,980,352,45,51,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,50,45,894,317,999,980,352,45,51,53,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,50,58,45,894,317,999,980,352,45,347,748,352,45,51,51,45,894,317,999,980,352,45,51,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,51,45,894,317,999,980,352,45,51,54,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,51,49,45,894,317,999,980,352,45,347,748,352,45,51,52,45,894,317,999,980,352,45,51,55,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,52,45,894,317,999,980,352,45,51,55,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,51,50,45,894,317,999,980,352,45,347,748,352,45,51,53,45,894,317,999,980,352,45,51,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,53,45,894,317,999,980,352,45,51,56,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,51,51,45,894,317,999,980,352,45,347,748,352,45,51,54,45,894,317,999,980,352,45,51,57,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,54,45,894,317,999,980,352,45,51,57,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,51,52,45,894,317,999,980,352,45,347,748,352,45,51,55,45,894,317,999,980,352,45,51,58,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,55,45,894,317,999,980,352,45,51,58,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[347,748,352,45,51,53,45,894,317,999,980,352,45,347,748,352,45,51,56,45,894,317,999,980,352,45,52,49,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,39,101,4,40,102,16,38,164,38,39,40,16,36,165,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[45,347,748,352,45,51,56,45,894,317,999,980,352,45,52,49,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,52,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,55,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,58,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,50,51,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,50,54,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,50,57,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,51,50,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,51,53,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,51,56,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,52,49,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,52,52,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,52,55,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,52,58,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,53,51,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,53,54,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,53,57,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,54,50,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,54,53,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,54,56,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,55,49,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,55,52,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,55,55,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,55,58,45,537,393,45,14,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} -{"compiler_ir_vocabulary":"felidae-compiler-ir-v4","decision":"ACCEPT","input_ids":[528,343,45,56,51,45,537,393,45,13,47],"schema_version":3,"sentencepiece_model_identity":"sha256:e84eacbb51d5e63a10c308ea6728a7653f24015099215ad75e2b679a4d01b8b8","target_ids":[0,4,37,100,4,38,101,16,36,164,38,37,38,35,36,36,3]} diff --git a/datasets/vm/README.md b/datasets/vm/README.md deleted file mode 100644 index 608d832..0000000 --- a/datasets/vm/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# VM SSM corpus - -`runtime-context-v1.jsonl` is generated from verified deterministic `.bin` -results built from `v2_examples`. Regenerate it with the current -`felidae_build_runtime_dataset` whenever the tokenizer or this schema changes; -schema-v8 records are intentionally rejected rather than silently training a -model with different inputs. - -The dataset is JSON Lines schema v9, with one operation-level record per line: -`operation_id`, ordered `input_kinds`, canonical `input_values`, sorted -`fact_types`, sorted `fact_type_counts`, sorted `hierarchy_edges`, -`target_kind`, and either `target_value` or `target_score`. Those fields are -exactly the bounded information the current GRU sees at inference; it must not -store whole-program results or train-only features. -Stable `input_kinds` values are nil `1`, number `2`, Degree `3`, text `4`, -array `5`, map `6`, fact `7`, symbol `8`, tensor `9`, and dynamic text-keyed -map `10`. -`input_values` stores SentencePiece IDs directly and uses the documented -reserved structural-token tail for value boundaries, kinds, fields, and exact -floating-point bits. Training and live inference use the same encoder. -Every symbol in the three fact/hierarchy fields is its complete SentencePiece -ID sequence. Module-local indexes, hashes, and source spellings are not model -identity and must never be written to this dataset. -For finite action teachers, `target_value` must name an action in the production vocabulary: input/fact -references `0..15`, numeric truth `0` or `1`, nil `0`, or Degree milli-values -`0`, `250`, `500`, `750`, and `1000`. -An `ssm.suggest` teacher instead uses the score target kind and a finite -`target_score`; validation reports mean absolute error separately from action -accuracy. - -The baseline currently contains 15 deterministic records across the existing -typed runtime fixtures and trains only the permanent `SemanticOperationId::Identity` value -`0x0001`. It preserves one typed input and never hashes a source spelling into -an operation ID. Binaries containing `SemanticEval` still require a separate -explicit teacher and are rejected rather than assigned a whole-program label. -No runtime model is shipped until the broader fact/hierarchy corpus has been -trained and validated. - -`fact_type_counts` is the bounded population observed for each fact type. The -runtime GRU encodes it as one / two-to-four / five-or-more, so it can -distinguish sparse from populated knowledge without serializing fact fields or -converting facts to source text. - -Training uses a fixed-seed structural split by `(operation_id, ordered input -kinds, target action)`. Repeated records from one structural family cannot -appear in both train and validation; the trainer prints per-family held-out -accuracy. This is a baseline measurement, not evidence that the current small -corpus generalizes to arbitrary fact reasoning. - -Invalid `.fx` examples belong to compiler rejection evaluation: invalid source -never reaches a verified `.bin` or the VM SSM. VM datasets therefore contain -only verified operation records with safe, explicit labels. diff --git a/datasets/vm/runtime-context-v1.jsonl b/datasets/vm/runtime-context-v1.jsonl deleted file mode 100644 index 46f19a6..0000000 --- a/datasets/vm/runtime-context-v1.jsonl +++ /dev/null @@ -1,15 +0,0 @@ -{"fact_type_counts":[[[131,436,138,993,986,317,995,551,340],3],[[131,977,326,998,989,351],3],[[131,995,514,998,868,981],1],[[1003,527,987,138,993,986,317,995,551,340],1],[[1003,728,316,765,138,993,986,317,995,551,340],13],[[1003,747,990,4,764,993,325,138,993,986,317,995,551,340],1]],"fact_types":[[131,436,138,993,986,317,995,551,340],[131,977,326,998,989,351],[131,995,514,998,868,981],[1003,527,987,138,993,986,317,995,551,340],[1003,728,316,765,138,993,986,317,995,551,340],[1003,747,990,4,764,993,325,138,993,986,317,995,551,340]],"hierarchy_edges":[[[131,436,138,993,986,317,995,551,340],[1003,728,316,765,138,993,986,317,995,551,340]],[[131,977,326,998,989,351],[131,995,514,998,868,981]],[[1003,527,987,138,993,986,317,995,551,340],[1003,728,316,765,138,993,986,317,995,551,340]],[[1003,747,990,4,764,993,325,138,993,986,317,995,551,340],[1003,728,316,765,138,993,986,317,995,551,340]]],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[[[131,436,1013,983,315,1010,678,347,365],3],[[1003,988,710,369,1005,977,532,977,364],2],[[1006,319,987,393,678,347,365],1],[[1006,319,987,1005,977,532,977,364],5],[[1009,409,1005,977,532,977,364],1]],"fact_types":[[131,436,1013,983,315,1010,678,347,365],[1003,988,710,369,1005,977,532,977,364],[1006,319,987,393,678,347,365],[1006,319,987,1005,977,532,977,364],[1009,409,1005,977,532,977,364]],"hierarchy_edges":[[[131,436,1013,983,315,1010,678,347,365],[1006,319,987,393,678,347,365]],[[1003,988,710,369,1005,977,532,977,364],[1006,319,987,1005,977,532,977,364]],[[1009,409,1005,977,532,977,364],[1006,319,987,1005,977,532,977,364]]],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[[[511],2],[[674,992,394,1005,707,4,981],2]],"fact_types":[[511],[674,992,394,1005,707,4,981]],"hierarchy_edges":[],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[],"fact_types":[],"hierarchy_edges":[],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[[[423],3]],"fact_types":[[423]],"hierarchy_edges":[],"input_kinds":[5],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[[[379],1],[[423],1],[[501],3]],"fact_types":[[379],[423],[501]],"hierarchy_edges":[[[423],[379]],[[501],[423]]],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[[[426,410,595],1],[[511],7],[[1000,986,352,535,975],1]],"fact_types":[[426,410,595],[511],[1000,986,352,535,975]],"hierarchy_edges":[[[511],[1000,986,352,535,975]],[[1000,986,352,535,975],[426,410,595]]],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[[[125,709,978],1],[[1000,984,991,994,978],1],[[1005,980,392],2],[[1005,988,436],1],[[1008,977,371],2]],"fact_types":[[125,709,978],[1000,984,991,994,978],[1005,980,392],[1005,988,436],[1008,977,371]],"hierarchy_edges":[[[125,709,978],[1005,988,436]],[[1000,984,991,994,978],[1005,988,436]],[[1005,980,392],[125,709,978]],[[1005,980,392],[1000,984,991,994,978]],[[1008,977,371],[125,709,978]],[[1008,977,371],[1000,984,991,994,978]]],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[],"fact_types":[],"hierarchy_edges":[],"input_kinds":[6],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[],"fact_types":[],"hierarchy_edges":[],"input_kinds":[1],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[],"fact_types":[],"hierarchy_edges":[],"input_kinds":[2],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[],"fact_types":[],"hierarchy_edges":[],"input_kinds":[3],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[],"fact_types":[],"hierarchy_edges":[],"input_kinds":[4],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[],"fact_types":[],"hierarchy_edges":[],"input_kinds":[5],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} -{"fact_type_counts":[[[142,720,979,320],1]],"fact_types":[[142,720,979,320]],"hierarchy_edges":[],"input_kinds":[7],"operation_id":1,"schema_version":8,"target_kind":1,"target_value":0} diff --git a/docs/README.md b/docs/README.md index fc2279d..0397541 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,22 +1,14 @@ # Felidae documentation -The supported product path is deliberately small: +The supported product path is deliberately small and direct: ```text -source.fx -> felidae_compiler -> verified FELBIR v16 executable IR -> felidae_vm +source.fx -> deterministic lexer + custom BPE -> IntegerParser -> Program AST -> Interpreter ``` -Build artifacts are created only in `build/`; the portable package is generated -only from a Release configuration by the `felidae_dist` CMake target in -`/dist/`. Use the repository -[`README.md`](../README.md) for build, compiler, VM, binary-format, mixfix, -and SSM guidance. +Build artifacts are created only in `build/`. Use the repository +[`README.md`](../README.md) for build, direct interpretation, custom-BPE, +mixfix, fact-memory, and source-reload guidance. -FELBIR contains the verified executable IR, bounded constants, complete -SentencePiece-sequence symbol and text entries, procedures, fact types, and -source maps. It contains no AST, source syntax, symbol hashes, or secondary -instruction representation. - -The former interpreter-hosted documentation site, browser/WASM playground, and -Celidae visualizer were removed because they are not part of the FELBIR/Form VM -release path. +There is no executable IR, binary program format, VM, SentencePiece model, or +SSM path. The AST interpreter and `FactMemory` are authoritative at runtime. diff --git a/docs/builtin-docs.json b/docs/builtin-docs.json index 155f41c..01759c3 100644 --- a/docs/builtin-docs.json +++ b/docs/builtin-docs.json @@ -523,7 +523,7 @@ }, "csv:parse": { "heading": "csv.parse", - "description": "Parses CSV text directly in RegisterVm and returns an array of row maps.", + "description": "Parses CSV text in the direct interpreter and returns an array of row maps.", "example": "rows := csv.parse(data: csvText)", "params": [ { @@ -533,7 +533,7 @@ }, "csv:toFacts": { "heading": "csv.toFacts", - "description": "Parses CSV text into retained native facts of a type declared in the loaded IR module.", + "description": "Parses CSV text into fact maps of the requested source-level type.", "example": "schools := csv.toFacts(data: csvText, type: \"School\")", "params": [ { @@ -546,7 +546,7 @@ }, "csv:toText": { "heading": "csv.toText", - "description": "Writes an array of row maps back to CSV text directly in RegisterVm.", + "description": "Writes an array of row maps back to CSV text in the direct interpreter.", "example": "text := csv.toText(data: rows)", "params": [ { @@ -605,7 +605,7 @@ }, "file:readFile": { "heading": "file.readFile", - "description": "Reads a bounded file as text directly through the RegisterVm file service.", + "description": "Reads a bounded file as text through the direct interpreter file service.", "example": "text := file.readFile(file: \"data.txt\")", "params": [ { diff --git a/docs/compiler_form_audit.md b/docs/compiler_form_audit.md deleted file mode 100644 index c3501bb..0000000 --- a/docs/compiler_form_audit.md +++ /dev/null @@ -1,87 +0,0 @@ -# Compiler and Form VM audit - -Original benchmark date: 2026-08-16. Measurements are Windows Release builds using the -existing `felidae_integer_parser_benchmark` target, five process-start runs. -Stabilization findings were revalidated on Linux on 2026-08-28. - -## Current boundaries - -```text -felidae_compiler.exe - source.fx -> SentencePiece -> IntegerParser -> compiler HIR -> IrCodeGenerator -> .bin - -felidae_vm.exe - program.bin -> binary validation -> IR verifier -> Form RegisterVm - -> optional LibTorch tensor/runtime-SSM backend -``` - -`felidae_vm.exe` has no parser or compiler-HIR dependency. It uses SentencePiece only -at the display/model boundary and, on supported desktop builds, links LibTorch -for deterministic tensor operations and the optional runtime SSM. Core Form -IR verification and execution remain independent of compiler lowering. - -## Measurements - -| Input | Minimum | Median | Maximum | -| --- | ---: | ---: | ---: | -| `ast_typed_methods.fx` | 3,909 us | 4,676 us | 5,690 us | -| `custom_operator_overload.fx` | 2,663 us | 3,927 us | 4,682 us | -| `benchmark_recursive_system_run.fx` | 2,585 us | 4,068 us | 6,260 us | - -For `6 * 7`, the parser benchmark reported 4--14 us SentencePiece encoding, -42--75 us IR compilation, 1--2 us verification, and 4--6 us VM execution. -Process/model initialization dominated total time (886--1,794 us). - -## Proven dead code removed - -- The old executable-AST interpreter, reasoning, native-runtime, environment, and memory runtime - sources were unreachable from active CMake targets. -- The obsolete WASM entry point and stale `FelidaeRuntime` wrapper were - unreachable. -- The old `LegacyIrAdapter` was renamed to `IrCodeGenerator` because it is - active HIR-to-IR code generation, not compatibility runtime code. - -## Stabilized contracts - -- Compiler and debugger source parsing share `CompilerFrontend` file - normalization, entry resolution, SentencePiece parsing, and an explicit - operator registry. The debugger no longer maintains a divergent parser path. -- Debugger JSON-RPC input uses `nlohmann_json`; malformed requests produce - protocol errors instead of being interpreted by raw string searches. -- RegisterVm verification and execution share `irInstructionWidth()` as the - single executable-layout contract. -- Fact hierarchy registration rejects duplicate parents and cycles. Assignable - searches have deterministic creation-order results. -- Map and fact equality are key-based, independent of field insertion order. - Fact similarity reuses the same keyed-field algorithm without non-owning - stack-backed `shared_ptr` adapters. -- Fact retention rejects malformed fields and facts owned by another runtime. - Variable lookup tests cover immutable globals/locals and frame isolation. - -## Remaining complexity worth addressing - -1. `IntegerParser.cpp` is about 2,650 lines. It owns SentencePiece-ID parsing, - operator/mixfix routing, HIR construction, and three HIR-to-IR helper - implementations. Move the HIR-to-IR helpers into a dedicated lowering unit; - parsing should not own code generation. -2. `IrCodeGenerator.cpp` and the parser both participate in lowering. Their - responsibilities should become explicit: parser constructs HIR only; - codegen lowers expressions, globals, methods, and conditions. -3. `IrModule` is the compiler construction form, while `LinkedIrModule` is the - flattened binary form. The names obscure that distinction. A later API - cleanup should name them `UnlinkedIrModule` and `LinkedIrModule`. -4. Operator annotations and `OperatorRegistry` are parser dependencies for - mixfix declarations. They are not dead, but should be isolated from normal - expression parsing behind a small parser routing interface. -5. `Symbol.h` is required for stable IDs and binary symbol-spelling validation. - `BuiltinRegistry` is required for qualified builtin and annotation IDs; - tests cover `math:sin` and `system:print` recognition. - -## Tooling status - -The current Linux machine provides Clang tools, IWYU, `cppcheck`, Valgrind, -Flawfinder, Coccinelle, Doxygen, Graphviz, `pahole`, `bpftrace`, Heaptrack, -Linux perf, and KCachegrind. They are not part of ordinary compilation because -complete analysis is intentionally an explicit release gate. Run them against -the configured `build/debug` compile database and focused executables; a tool -being installed is not evidence that its checks passed. diff --git a/docs/executable_ir.md b/docs/executable_ir.md deleted file mode 100644 index 2313f04..0000000 --- a/docs/executable_ir.md +++ /dev/null @@ -1,98 +0,0 @@ -# Felidae executable IR - -Felidae has one executable instruction representation. The compiler emits it, -the FELBIR writer serializes it, and the Form register VM dispatches it -directly. There is no assembler, fixed-width ISA, or intermediate lowering -format. - -## Encoding contract - -FELBIR v16 stores 32-bit integer words in little-endian order. An instruction -starts with an `IrOpcode`; its opcode determines a fixed or bounded -variable-width operand sequence. Calls, named calls, arrays, maps, `Builtin`, -`Numeric`, and `SemanticEval` carry explicit counts, and the verifier checks -those bounds before execution. - -Registers, constants, procedures, source spans, and symbol references use -bounded integer indexes. A one-based symbol reference addresses exactly one -entry in the module symbol table. Each entry is the complete SentencePiece ID -sequence for that symbol. Hashes, UTF-8 spellings, and process-global symbol -registries are not executable identity. - -The beta format has no compatibility reader. A change to the executable -contract increments `kBinaryIrVersion`, and existing `.bin` files must be -rebuilt. - -## Verification boundary - -The compiler verifies a completed module before writing it. The binary loader -treats bytes as hostile, checks the FELBIR header and exact SentencePiece model -identity, constructs a module, verifies it once, and returns -`VerifiedIrModule`. The writer and VM accept only that typestate, so they do -not repeat whole-module verification. - -Verification covers instruction widths and operands, register and pool -indexes, control flow, initialized-register use, procedure calls and metadata, -symbol references, fact hierarchies, and semantic-operation contracts. - -## Runtime truth - -The VM has no Boolean value alternative. Crisp truth is always a `double`: -`0.0` is false and `1.0` is true. Boolean constants, comparisons, and logical -operations produce only those values. Conditional control accepts `nil`, -`0.0`, or `1.0` and rejects other values instead of inventing truthiness. - -## Runtime library operations - -`Builtin` contains a stable operation ID and an ordered input-register list. -The compiler, verifier, and VM share one arity contract. The VM calls the -corresponding typed C++ implementation directly; there is no native-library -loader, string dispatch, second interpreter, or SSM involvement. JSON and CSV -text boundaries use the module's SentencePiece encoder and decoder. A runtime -without either required service fails explicitly instead of returning a -placeholder value. - -## Numeric operations - -The variable-width `Numeric` instruction contains a destination register, a -`NumericOperation`, and its bounded input-register list. `RegisterVm` executes -`min`, `max`, `abs`, `diff`, `avg`, `weighted_avg`, `clamp`, `floor`, `ceil`, -`round`, `trunc`, `sqrt`, `cbrt`, `pow`, `exp`, `log`, `log10`, `lerp`, -`sign`, `reciprocal`, `square`, `cube`, `in_range`, `is_finite`, and `is_nan` -directly. The callable `mod` form reuses the -existing `Mod` opcode and `std::fmod` implementation. - -## Tensor operations - -The variable-width `Tensor` instruction uses the same destination, operation, -arity, and input-register layout as `Numeric`. On supported builds its one -backend is LibTorch. Numeric scalars and rectangular numeric arrays become -`float64` tensors. Facts, text, symbols, and maps remain symbolic VM values; -they are not flattened into numeric feature vectors. - -`size`, `shape`, `dimensions`, `clone`, `transpose`, `isSymmetric`, absolute -`difference`, cosine similarity, dot product, mean-squared error, sigmoid, and -ReLU execute directly at this boundary. Non-scalar results remain real -LibTorch tensors in `VmValue`; they are materialized as nested arrays only by -the display adapter or another explicit boundary. `clone` performs an actual -tensor clone. `isSymmetric` returns only `0.0` or `1.0`. -Ragged arrays, incompatible shapes, invalid ranks, non-finite numeric inputs, -and cosine similarity with a zero vector fail explicitly. These deterministic -operations never invoke the runtime SSM. - -Ordinary numeric operations require finite numeric operands and a finite -result. Invalid ranges, zero reciprocal or total weight, negative square-root -inputs, non-positive logarithm inputs, and overflow/domain failures raise an -`IrError`. Plain results are signed finite doubles and are never normalized to -the interval from zero to one. `is_finite` and `is_nan` deliberately inspect -non-finite inputs and return numeric `0.0` or `1.0`; they do not introduce -Boolean VM values. No -ordinary numeric operation invokes an SSM. - -## Semantic operations - -`SemanticEval` carries a stable `SemanticOperationId` and an ordered list of -typed input registers. The runtime SSM selects one bounded typed result; it -cannot generate instructions. Its knowledge context resolves module-local -symbol references through the same module symbol table and supplies complete -SentencePiece ID sequences to inference and training. diff --git a/docs/library_pages.fx b/docs/library_pages.fx deleted file mode 100644 index f5073e1..0000000 --- a/docs/library_pages.fx +++ /dev/null @@ -1,75 +0,0 @@ -import ("html_components.fx", "str"). - -DocsLibraryStr() => - cards := RenderModuleGrid(content: str.join(data: [ - RenderMiniCard(input: HtmlCardData(title: "Projection", text: "concat joins two strings; join renders arrays with a delimiter.")), - RenderMiniCard(input: HtmlCardData(title: "Search", text: "contains, startsWith, and endsWith return string-shaped truth values.")), - RenderMiniCard(input: HtmlCardData(title: "Cleanup", text: "lower, upper, trim, split, and replace prepare text before matching or rendering.")) - ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-str", title: "Library: str", p: "The str module handles small text operations used in projections, labels, generated documentation, command output checks, and search preparation.", p2: "Use str.concat(left: ..., right: ...) for two strings and str.join(data: ..., delimiter: ...) for arrays. Keeping those roles separate prevents long concat ladders in documentation and server code.", content: cards, code: "import \"str\".\n\nmain() =>\n first := str.concat(left: \"Felidae\", right: \" docs\"),\n tags := str.join(data: [\"facts\", \"logic\", \"docs\"], delimiter: \", \"),\n normalized := str.lower(data: \"Search Term\"),\n return (title: first, tags: tags, normalized: normalized).", note: "Use str.join when rendering repeated fragments. Use str.concat only when there are exactly two string parts.", code2: "str.contains(data: \"facts as data\", needle: \"facts\")\nstr.trim(data: \" Felidae \")\nstr.replace(data: \"a-b-c\", search: \"-\", replacement: \":\")")). - -DocsLibraryArray() => - cards := RenderModuleGrid(content: str.join(data: [ - RenderMiniCard(input: HtmlCardData(title: "Read", text: "array.get reads a value by position.")), - RenderMiniCard(input: HtmlCardData(title: "Measure", text: "array.len returns the number of values.")), - RenderMiniCard(input: HtmlCardData(title: "Build", text: "array.push returns a new array with one added value.")) - ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-array", title: "Library: array", p: "The array module is intentionally small. Arrays are ordered values, while facts remain the preferred shape for durable named knowledge.", p2: "Use array helpers when order matters or when a runtime-library operation returns a list. For filtering and projection, prefer lambda(data, row => ...) so the transformation stays visible.", content: cards, code: "import \"array\".\n\nmain() =>\n names := [\"Ada\", \"Mina\", \"Ravi\"],\n first := array.get(data: names, position: 0),\n total := array.len(data: names),\n extended := array.push(data: names, value: \"Nia\"),\n return (first: first, total: total, extended: extended).", note: "Use facts when fields need names. Use arrays when order is the important part of the data.", code2: "scores := [91, 72, 65]\npassing := lambda(scores, value => value >= 70)\ncount(passing)")). - -DocsLibraryDb() => - guidance := RenderGuidance(doText: "Keep Type.where queries inside main() or named methods, and return named tuples so the result is testable and documentable.", dontText: "Do not hide fact-store scans behind a second db namespace. Query the fact type directly.", recommendText: "Use Type.where for filtered rows, Type.all for the dataset, and Type.count for totals."), - return (HtmlRichSectionData(id: "lib-db", title: "First-class fact database", p: "A fact type is its own SQL-like query surface. Direct facts, CSV facts, and compiler-linked .fx database rows share one VmFactStore.", p2: "Use Type.all, Type.where, Type.select, Type.count, aggregates, conditional mutations, and keyed joins. There is no public db helper namespace.", content: guidance, code: "Customer(name: \"Ada\", city: \"SEA\", active: 1.0).\nCustomer(name: \"Mina\", city: \"BLR\", active: 1.0).\n\nmain() =>\n rows := Customer.where(active: 1.0)\n return (count: count(data: rows), rows: rows)\nend", note: "Facts define the database contract directly. Keep type and field names stable and clear.", code2: "Customer.all()\nCustomer.where(name: \"Ada\")\nCustomer.count(match: {active: 1.0})\nCustomer.select(fields: [\"name\"], match: {active: 1.0})")). - -DocsLibraryJson() => - cards := RenderModuleGrid(content: str.join(data: [ - RenderMiniCard(input: HtmlCardData(title: "Read", text: "parse turns JSON text into a runtime value; get reads a key.")), - RenderMiniCard(input: HtmlCardData(title: "Inspect", text: "has and keys let code check shape before accessing fields.")), - RenderMiniCard(input: HtmlCardData(title: "Write", text: "set, remove, and toText create JSON-shaped outputs.")) - ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-json", title: "Library: json", p: "The json module is for exchanging runtime values with external systems. It is useful for API responses, saved reports, imported payloads, and browser-facing data.", p2: "Keep durable application knowledge as Felidae facts. Convert to JSON at the boundary when another system needs JSON text or when a documentation page needs embedded structured data.", content: cards, code: "import \"json\".\n\nmain() =>\n payload := json.parse(data: \"{\\\"name\\\":\\\"Ada\\\",\\\"role\\\":\\\"Engineer\\\"}\"),\n name := json.get(data: payload, key: \"name\"),\n hasRole := json.has(data: payload, key: \"role\"),\n keys := json.keys(data: payload),\n return (name: name, hasRole: hasRole, keys: keys).", note: "JSON is a boundary format, not the fact database. Store durable knowledge as facts and serialize only when exchanging data.", code2: "updated := json.set(data: payload, key: \"active\", value: \"true\")\nwithoutRole := json.remove(data: updated, key: \"role\")\ntext := json.toText(data: withoutRole)")). - -DocsLibraryCsv() => - cards := RenderModuleGrid(content: str.join(data: [ - RenderMiniCard(input: HtmlCardData(title: "Parse", text: "csv.parse turns CSV text into rows.")), - RenderMiniCard(input: HtmlCardData(title: "Write", text: "csv.toText serializes row arrays back to CSV.")), - RenderMiniCard(input: HtmlCardData(title: "Facts", text: "toFacts and toFelidaeFacts convert table-shaped rows into fact-shaped data.")) - ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-csv", title: "Library: csv", p: "The csv module is for table-shaped text at system boundaries. Use it when importing spreadsheets, exporting reports, or generating Felidae facts from rows.", p2: "CSV has columns and rows, but it does not carry nested structure as clearly as Felidae facts. Convert CSV into facts when the data becomes part of the program's durable knowledge.", content: cards, code: "import \"csv\".\n\nmain() =>\n rows := csv.parse(data: \"name,role\\nAda,Engineer\\nMina,Designer\"),\n text := csv.toText(data: rows),\n return (rows: rows, text: text).", note: "CSV is best at import and export. Once rows become application knowledge, convert them into named Felidae facts.", code2: "typedRows := csv.toFacts(data: csvText, type: \"Employee\")\nfactsText := csv.toFelidaeFacts(data: rows, type: \"Employee\")")). - -DocsLibraryFile() => - guidance := RenderGuidance(doText: "Keep file paths explicit in main() or edge methods, and convert file content into facts or tuples before deeper processing.", dontText: "Do not hide writes or deletes inside general-purpose helpers. File operations change the host environment and should be visible.", recommendText: "Use readLines for large line-oriented inputs and writeFile/writeLines only when the output path is intentional."), - return (HtmlRichSectionData(id: "lib-file", title: "Library: file", p: "The file module provides native-backed local file I/O: read whole files, read lines, write text, append text, check existence, and delete files.", p2: "Use file at the boundary of a program. After reading a file, shape the data into facts, arrays, or tuples so the rest of the program remains testable.", content: guidance, code: "import \"file\".\n\nmain() =>\n exists := file.exists(path: \"data/input.fx\"),\n text := file.readFile(path: \"data/input.fx\"),\n lines := file.readLines(path: \"data/input.fx\"),\n return (exists: exists, characters: length(text), lines: count(lines)).", note: "File writes and deletes are host-side effects. Keep the path and mode close to the main workflow.", code2: "file.writeFile(path: \"out/report.fx\", data: \"Report(status: \\\"ok\\\").\", mode: \"write\")\nfile.appendFile(path: \"out/report.fx\", data: \"\\nReport(status: \\\"done\\\").\")\nfile.deleteFile(path: \"out/old-report.fx\")")). - -DocsLibraryHttp() => - guidance := RenderGuidance(doText: "Keep hosts, ports, content types, and response bodies explicit.", dontText: "Do not mix server hosting examples with unrelated file or process code on the same page.", recommendText: "Use Http* helper methods for readable response records, then pass those records to HttpServeResponse."), - return (HtmlRichSectionData(id: "lib-http", title: "Library: http", p: "The http module provides native-backed client calls and simple static response serving. It is used by the documentation server to serve the generated SPA from Felidae code.", p2: "The raw http.* functions are native calls. The HttpResponse, HttpHtmlResponse, HttpJsonResponse, HttpUrl, and HttpServeResponse helpers keep application code data-shaped.", content: guidance, code: "import \"http\".\n\nmain() =>\n page := HttpHtmlDocument(title: \"Felidae\", body: \"

ok

\"),\n response := HttpHtmlResponse(body: page),\n return (response: response).", note: "For production documentation hosting, run Felidae behind Nginx and keep the native server bound to 127.0.0.1.", code2: "HttpServeResponse(host: \"127.0.0.1\", port: 8090, response: response)\nHttpJsonResponse(body: \"{\\\"ok\\\":true}\")\nhttp.get(url: \"https://example.com\")")). - -DocsLibraryMath() => - cards := RenderModuleGrid(content: str.join(data: [ - RenderMiniCard(input: HtmlCardData(title: "Constants", text: "pi and e provide numeric constants.")), - RenderMiniCard(input: HtmlCardData(title: "Numeric", text: "abs, floor, ceil, round, sqrt, pow, log, log10, exp.")), - RenderMiniCard(input: HtmlCardData(title: "Trigonometry", text: "sin, cos, tan, asin, acos, atan, atan2.")) - ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-math", title: "Library: math", p: "The math module contains scalar numeric helpers. Use it for deterministic calculations around values already derived from facts or arrays.", p2: "Keep numeric inputs visible near the call. If the values come from facts, derive the numeric array first, then call math functions in a named method or main().", content: cards, code: "import \"math\".\n\nmain() =>\n root := math.sqrt(value: 16),\n distance := math.abs(value: -12),\n power := math.pow(base: 2, exponent: 5),\n rounded := math.round(value: 3.6),\n return (root: root, distance: distance, power: power, rounded: rounded).", note: "Numeric results remain ordinary floating-point values and are not normalized to a truth range. Use ml only for its documented LibTorch operations.", code2: "angle := math.atan2(y: 1, x: 1)\nwave := math.sin(value: angle)\nrandom := math.random(min: 1, max: 10)")). - -DocsLibraryMl() => - cards := RenderModuleGrid(content: str.join(data: [ - RenderMiniCard(input: HtmlCardData(title: "Activation", text: "sigmoid and relu transform one numeric value.")), - RenderMiniCard(input: HtmlCardData(title: "Vectors", text: "dot computes a vector dot product.")), - RenderMiniCard(input: HtmlCardData(title: "Error", text: "meanSquaredError compares equally shaped numeric arrays.")) - ], delimiter: "")), - return (HtmlRichSectionData(id: "lib-ml", title: "Library: ml", p: "The ml module exposes the small set of deterministic LibTorch operations implemented by the runtime: sigmoid, relu, dot, and meanSquaredError.", p2: "These operations evaluate directly in RegisterVm. They do not train a model and do not force ordinary numeric results into the 0.0-to-1.0 range.", content: cards, code: "import \"ml\".\n\nmain() =>\n activation := ml.relu(value: -2.5),\n score := ml.dot(left: [1.5, -2.0, 3.0], right: [4.0, 0.5, -1.0]),\n loss := ml.meanSquaredError(left: [1.0, 2.0], right: [1.5, 1.0]),\n return (activation: activation, score: score, loss: loss).", note: "Only documented operations are available. A missing LibTorch backend raises an explicit runtime error.", code2: "ml.sigmoid(value: -3.0)\nml.relu(value: 4.25)\nml.dot(left: [1, 2], right: [3, 4])\nml.meanSquaredError(left: [1, 2], right: [1, 3])")). - -DocsLibrarySystem() => - return (HtmlRichSectionData(id: "lib-system", title: "Library: system", p: "The system module provides low-level runtime inspection and development output helpers.", p2: "Prefer returning structured data from main() for stable program behavior. Use system.print for startup messages, service logs, or temporary development feedback.", content: "", code: "import \"system\".\n\nmain() =>\n system.print(value: \"checking docs\"),\n return (status: \"printed\").", note: "Printed output is useful for humans, but returned tuples are easier for docs, tests, and automation to verify.", code2: "type(value: [1, 2, 3], name: kind)\ninstanceof(value: 42, type: \"number\")")). - -DocsLibraryConsole() => - return (HtmlRichSectionData(id: "lib-console", title: "Library: console", p: "The console module provides interactive terminal input and output helpers.", p2: "Use console helpers for interactive scripts. Documentation and automated examples should usually return data from main() instead of requiring user input.", content: "", code: "import \"console\".\n\nTenCheck(x: number) =>\n x == 10,\n return (matched: 1.0, message: \"x is ten\")\nelse\n return (matched: 0.0, message: \"x is not ten\").\n\nmain() =>\n x := console.inputNumber(print: \"enter x: \"),\n return (x: x, check: TenCheck(x: x)).", note: "console.input returns text. Use console.inputNumber when the next condition should compare against a number such as x == 10.", code2: "name := console.input(print: \"enter name: \")\nconsole.write(value: \"Hello, \")\nconsole.writeLine(value: name)\nraw := console.readLine()")). - -DocsLibraryProcess() => - guidance := RenderGuidance(doText: "Use process.platform for OS-aware tooling and keep process.exec commands explicit.", dontText: "Do not use process.exec for ordinary logic examples, docs rendering, or hidden application behavior.", recommendText: "When a command must run, return the command and output together so tests can audit it."), - return (HtmlRichSectionData(id: "lib-process", title: "Library: process", p: "The process module exposes host process helpers: platform detection, command execution, and sleep.", p2: "This module is operational and can affect the host environment. Use it for tooling, smoke tests, packaging scripts, or controlled integration points, not for core logic programming examples.", content: guidance, code: "import \"process\".\n\nmain() =>\n platform := process.platform(),\n waited := process.sleep(milliseconds: 10),\n return (platform: platform, waited: waited).", note: "process.exec runs host commands. Treat command strings as operational boundaries and keep them visible.", code2: "output := process.exec(command: \"build\\\\felidae_debug.exe docs\\\\server.fx --check-json\")\nreturn (command: \"docs check\", output: output)")). - -DocsLibraryThread() => - guidance := RenderGuidance(doText: "Use threads for isolated long-running method work where a handle, status, and result make sense.", dontText: "Do not introduce threads into beginner examples or simple fact queries. They add coordination cost.", recommendText: "Create, start, check status, then read result through the thread handle."), - return (HtmlRichSectionData(id: "lib-thread", title: "Library: thread", p: "The thread module runs a method on an independent interpreter snapshot and returns a handle that can be started, paused, stopped, queried, and joined through result access.", p2: "Thread usage is advanced. Keep the threaded function name explicit and return status/result data so the workflow remains observable.", content: guidance, code: "import \"thread\".\n\nWorker() =>\n return (status: \"done\").\n\nmain() =>\n worker := thread.createThread(function: \"Worker\"),\n started := thread.start(thread: worker),\n status := thread.status(thread: worker),\n result := thread.result(thread: worker),\n return (started: started, status: status, result: result).", note: "Threads should not hide fact database mutations. Prefer pure method work or clearly documented operational tasks.", code2: "thread.pause(thread: worker)\nthread.stop(thread: worker)")). diff --git a/docs/native_modules.fx b/docs/native_modules.fx deleted file mode 100644 index 0ff9406..0000000 --- a/docs/native_modules.fx +++ /dev/null @@ -1,5 +0,0 @@ -import "html_components.fx". - -DocsNativeModules() => - guidance := RenderGuidance(doText: "Use compiler-known operations that lower to verified Builtin IR, and provide host services explicitly when an operation needs external state.", dontText: "Do not depend on the retired felidae_native_call JSON ABI or assume that importing a module loads a shared library.", recommendText: "Keep one typed C++ implementation under src/form/libs for each deterministic runtime library operation."), - return (HtmlRichSectionData(id: "native", title: "Runtime Libraries", p: "The production compiler and RegisterVm do not load native-extension DLLs. Deterministic library calls such as json, csv, and finite-group checks are encoded as Builtin instructions in FELBIR and dispatched directly to typed C++ functions.", p2: "A runtime raises an error when a required service is unavailable. Retired native-module bridges are not part of the source tree or build; maintained runtime implementations live under src/form/libs.", content: guidance, code: "import (\"json\", \"csv\").\n\nmain() =>\n value := json.parse(data: \"{\\\"name\\\":\\\"Ada\\\"}\"),\n rows := csv.parse(data: \"name,score\\nAda,42\\n\"),\n return (name: json.get(data: value, key: \"name\"), rows: rows).", note: "Builtin operation IDs and arities are shared by the compiler, verifier, and VM. Ordinary deterministic operations never invoke an SSM.", code2: "source.fx -> IntegerParser -> compiler high-level IR -> verified FELBIR -> RegisterVm -> src/form/libs")). diff --git a/docs/playground.fx b/docs/playground.fx index 1d13fc7..bfb2b6c 100644 --- a/docs/playground.fx +++ b/docs/playground.fx @@ -1,4 +1,4 @@ import "html_components.fx". DocsPlayground() => - return (HtmlPlaygroundData(id: "playground", title: "Playground", p: "Edit a Felidae sample and run it in the browser through the WASM interpreter generated from the C++ runtime. You can still copy or download the same source and run it with the native CLI.", example: "RainDay(month: \"August\", day: \"monday\", chance: 5.2).\nRainDay(month: \"August\", day: \"tuesday\", chance: 0.3).\nRainDay(month: \"August\", day: \"wednesday\", chance: 2.4).\nCat1(name: \"kitten\").\nCat1(name: \"tiger\").\nCat1(name: \"lilly\").\nCat1(name: \"sony\").\nCat2(name: \"joy\").\nCat2(name: \"teddy\").\nCat2(name: \"snowbell\").\n\nCompareCats() =>\n leftCount := Cat1.count(),\n rightCount := Cat2.count(),\n total := leftCount + rightCount,\n return (leftShare: leftCount / total, rightShare: rightCount / total, difference: (leftCount - rightCount) / total).\n\nmain() =>\n august := RainDay.where(month: \"August\"),\n averageChance := RainDay.average(field: \"chance\", match: {month: \"August\"}),\n return (days: august, averageChance: averageChance, cats: CompareCats()).", command: "./build/debug/felidae_vm build/debug/felidae-snippet.bin", note: "Compile the snippet into build/debug first. The browser version loads docs/wasm/felidae_wasm.js; build those assets in a named build subdirectory, then refresh the page." )). + return (HtmlPlaygroundData(id: "playground", title: "Playground", p: "Edit a Felidae sample and run its source directly with the interpreter.", example: "RainDay(month: \"August\", day: \"monday\", chance: 5.2).\nRainDay(month: \"August\", day: \"tuesday\", chance: 0.3).\nRainDay(month: \"August\", day: \"wednesday\", chance: 2.4).\nCat1(name: \"kitten\").\nCat1(name: \"tiger\").\nCat2(name: \"joy\").\nCat2(name: \"snowbell\").\n\nCompareCats() =>\n leftCount := Cat1.count(),\n rightCount := Cat2.count(),\n total := leftCount + rightCount,\n return (leftShare: leftCount / total, rightShare: rightCount / total).\n\nmain() =>\n return (days: RainDay.where(month: \"August\"), cats: CompareCats()).", command: "build/debug/felidae sample.fx", note: "The CLI parses and evaluates source directly; no binary conversion is required." )). diff --git a/docs/reasoning_benchmark.md b/docs/reasoning_benchmark.md deleted file mode 100644 index b8edea7..0000000 --- a/docs/reasoning_benchmark.md +++ /dev/null @@ -1,222 +0,0 @@ -# Felidae reasoning and robustness benchmark - -This benchmark does **not** assign an IQ number. IQ tests are calibrated for -people and would produce a misleading score for a compiler and virtual -machine. The benchmark instead reports concrete capabilities that can be -reproduced from source. - -The initial domains are a -[coffee vending controller](../v2_examples/coffee_vending_theorem_solver.fx) -and an -[air-conditioner controller](../v2_examples/air_conditioner_theorem_solver.fx). -The expected cases are versioned in -[`felidae-reasoning-v1.jsonl`](../datasets/benchmarks/felidae-reasoning-v1.jsonl). - -## What the examples prove - -Both programs use hierarchical facts, explicit structural predicates, -numeric truth, theorem-like mixfix expressions, and ordered alternative -proofs. A failed candidate falls through to another proof, so the examples -exercise bounded backtracking. Invalid HVAC sensor evidence reaches a safe -lockout and missing coffee resources reach a refund instead of an unsafe -action. - -This is deliberately narrower than Prolog. Felidae currently has no native -logic variables, occurs check, automatic unification, choice-point stack, -cut, or exhaustive search engine. The `requestUnifies` and -`observationUnifies` predicates are explicit domain unifiers, and the choice -procedures define a finite search order. Calling this full Prolog -backtracking would overstate the implementation. - -## Reproducible scoring - -Build commands can take time and must be run by the developer. Keep every -artifact below `build/debug`: - -```bash -cmake --build build/debug --target felidae_compiler felidae_vm --parallel 1 - -./build/debug/felidae_compiler v2_examples/coffee_vending_theorem_solver.fx -./build/debug/felidae_vm build/debug/coffee_vending_theorem_solver.bin - -./build/debug/felidae_compiler v2_examples/air_conditioner_theorem_solver.fx -./build/debug/felidae_vm build/debug/air_conditioner_theorem_solver.bin -``` - -The native benchmark target runs the same source-to-verified-IR path in one -process and emits one JSON result. Build it explicitly, then supply expected -action text from the versioned manifest: - -```bash -cmake --build build/debug --target felidae_reasoning_benchmark --parallel 1 - -./build/debug/felidae_reasoning_benchmark --iterations 100 \ - v2_examples/coffee_vending_theorem_solver.fx \ - --expect dispense_coffee --expect refund - -./build/debug/felidae_reasoning_benchmark --iterations 100 \ - v2_examples/air_conditioner_theorem_solver.fx \ - --expect cool --expect ventilate --expect fault_lockout -``` - -The JSON uses numeric `1.0` and `0.0` for determinism and expectation status. -The iteration limit is 10,000; no benchmark or training runs implicitly. - -Record these metrics rather than one opaque score: - -| Metric | Measurement | -|---|---| -| Proof accuracy | Expected actions matched / five manifest cases | -| Safe-failure rate | Safe fallback reached / two injected fault cases | -| Hierarchy accuracy | Correct `isA` results / hierarchy assertions | -| Determinism | Identical output over 100 repeated VM executions | -| Compile rejection | Invalid programs rejected with a diagnostic / invalid programs | -| Compile latency | Median and p95 compiler wall time after five warmups | -| VM latency | Median and p95 VM wall time after five warmups | -| Generalization | Held-out programs compiled and executed correctly without adding them to training | - -Do not count a crash, hang, `nil`, or silent halt as a correct rejection. For -fault tolerance, add cases for invalid sensor truth, missing resources, -unknown fact fields, malformed source, corrupted FELBIR bytes, and recursion -depth exhaustion. The compiler or verifier must reject malformed artifacts; -the domain policy must return a documented safe action for valid but adverse -inputs. - -## Learning and out-of-box evaluation - -Felidae code supplies executable rules; merely reading a new `.fx` file is -not model training. The compiler SSM learns mixfix target selection, while -the runtime SSM learns operation selection. Neither model may invent new -language semantics or bypass executable IR verification. - -Use three disjoint sets when evaluating learning: - -1. **Train** contains examples used by `felidae_compiler --train` or - `felidae_vm --train`. -2. **Validation** selects checkpoints and thresholds. -3. **Held-out transfer** contains new operator wording, hierarchy depth, fact - ordering, and fault combinations never present in the first two sets. - -Report out-of-box accuracy before training, held-out accuracy after training, -the difference, and regression accuracy on the original suite. Never train -on the five benchmark answers and then report those same rows as evidence of -generalization. Save the exact dataset hash, seed, model hash, build type, -CPU, and command line with every result. - -## Current strengths and weaknesses - -Felidae is stronger than a hand-written finite-state table when policies are -shared across many hierarchical fact types, explanations and proof scores -matter, or new combinations of known facts must be evaluated. Verified IR, -bounded indexes, deterministic lowering, and numeric truth also give a useful -safety boundary. - -A conventional finite-state machine remains stronger for tiny controllers -that require certified hard real-time bounds, minimal memory, and an obvious -enumeration of every transition. Felidae's explicit finite alternatives can -grow combinatorially, its learned selectors require held-out validation, and -it does not yet provide a complete logical theorem prover. Physical coffee or -HVAC control additionally needs a trusted I/O layer, actuator interlocks, -timeouts, and independent safety limits outside the reasoning program. - -## Fact-reasoning baseline and improvement gates - -The August 2026 Debug smoke audit used the checked-in compiler and VM without -training. It is a capability baseline, not a trained-model score: - -| Capability | Result | Evidence | -|---|---:|---| -| Numeric similarity and fuzzy membership | pass | `degree_profiles.fx` returned `Degree` values 0.125 and 0.696947396356321 | -| Degree preservation inside facts/maps | pass | similarity, membership, confidence, and truth degree remained separate values | -| Explicit threshold over a Degree | pass | 0.696947396356321 produced `not-met` for the 0.75 threshold | -| Temporal fact ranking | pass | 2025/priority-2 preceded both 2024/priority-1 facts | -| Bounded controller proofs | 5/5 actions | coffee dispense/refund and HVAC cool/ventilate/lockout matched | -| Deep fact analysis example | compile failure | unsupported typed-lambda lowering | -| Multi-ancestor comparison example | retired syntax | use hierarchy primitives and typed fact queries | -| Heterogeneous fact-expression result contract | pass | crisp degree, probability, recoverable error, derived fact, and evidence-list results executed through FELBIR | - -This sample passes the two controller scenarios and the heterogeneous -fact-expression contract. Two selected rich fact-comparison scenarios remain -compiler-rejected. Do not turn that small sample into a general intelligence -percentage: it is not balanced by hierarchy depth, data size, negative -evidence, or held-out domains. - -The deterministic VM primitives are stronger than the source-level feature -surface currently reaching them. Hierarchy proofs, common ancestors, least and -most-general common ancestors, structural similarity, Gaussian membership, -and temporal ranking have verified executable-IR implementations. Several -documented high-level comparison and fact-query forms still fail during IR -generation. - -### Measured engineering bottlenecks - -- Map and fact similarity performs nested field scans, giving quadratic field - comparison cost. Canonical field indexes would make matching near-linear. -- Fact similarity gives 25% weight to exact type identity and does not use - hierarchy distance. Related subtypes can score worse than unrelated facts - with coincidentally similar fields. -- Numeric similarity uses `1 / (1 + absolute_difference)`. It is deterministic - but unit-sensitive across temperature, salary, probability, and other scales. -- Least/most-general ancestor calculation launches repeated hierarchy searches - for pairs of common ancestors. Dense multiple-inheritance graphs can require - quadratic pair checks, each with another graph traversal. -- Temporal ranking scans every retained fact and fails if any fact lacks the - requested fields. It needs a type- or query-bounded indexed candidate set. -- Benchmark `--expect` checks display substrings. It cannot prove exact fact - identity, field differences, calibrated Degrees, or proof paths. -- Felidae has bounded explicit alternatives, but no native logic variables, - occurs check, choice-point stack, or complete unification engine. - -### Intelligence improvement plan - -1. **Complete the source-to-IR surface.** Compile typed fact iteration, - relationship comparison, and maintained fact-analysis examples. Add a - compile-and-run regression for every supported public construct. -2. **Make benchmarks typed.** Assert exact result paths, value kinds, fact - types, ordered IDs, Degree values with tolerances, and expected failures. - Keep substring checks only as presentation smoke tests. -3. **Improve deterministic comparison first.** Canonicalize/index fields, add - schema-declared numeric scales and weights, incorporate hierarchy distance, - and return evidence with contributions, missing fields, paths, and provenance. -4. **Improve graph algorithms.** Cache revision-keyed ancestor closures and - compute minimal/maximal common ancestors without nested full searches. Test - chains, diamonds, multiple inheritance, cycles, and disconnected graphs. -5. **Add bounded unification deliberately.** Introduce typed variables, - substitutions, occurs check, deterministic choice points, step/depth/result - limits, and proof traces as a verified runtime service. -6. **Calibrate non-Boolean reasoning.** Test identity, bounds, promised - symmetry, monotonicity, normalized units, missing/conflicting evidence, and - threshold sensitivity. Report calibration error for learned Degrees. -7. **Evaluate learning last.** Split by domain and hierarchy family, compare - learned proposals with deterministic oracle results, require abstention on - uncertainty, and report accuracy, invalid proposals, calibration, - median/p95 latency, and memory independently. - -The beta gate should require 100% deterministic primitive and safety-case -accuracy, zero invalid values entering VM registers, zero silent halts, stable -results across 100 runs, and separately reported held-out learned accuracy. - -## SSM utilization audit - -The checked-in compiler corpus currently contains 184 `ACCEPT`, 12 `ABSTAIN`, -and 22 `REJECT` decisions. The compiler SSM is used only when verified parser -context leaves a mixfix target ambiguous; exact syntax, numeric intrinsics, -tensor operations, and ordinary IR generation remain deterministic. This is -the intended boundary: adding tensor examples to compiler-SSM training would -teach no ambiguity and would only duplicate the compiler. - -The VM corpus currently contains 15 records, all for -`SemanticOperationId::Identity`. No runtime SSM artifact is shipped. The VM -SSM can return only a bounded input/fact reference, `nil`, numeric truth -`0.0`/`1.0`, or one of five Degree values. This gives a safe extension point -and recurrent request-local state, but the present corpus does not demonstrate -dynamic fact selection, derivation, hierarchy-sensitive decisions, calibrated -soft evidence, or held-out generalization. - -Before claiming those capabilities, add independently labelled records for -`SelectFact`, `DeriveFact`, and `EvaluateDegree`; balance fact kinds, -populations, hierarchy shapes, and negative/abstention cases; split by domain -and hierarchy family; then report exact action accuracy, invalid-output rate, -Degree calibration, abstention quality, and p50/p95 latency. Deterministic -tensor comparison stays outside this model and supplies auditable features or -oracle labels rather than learned arithmetic. diff --git a/docs/stdlib.fx b/docs/stdlib.fx deleted file mode 100644 index d702769..0000000 --- a/docs/stdlib.fx +++ /dev/null @@ -1,16 +0,0 @@ -import ("html_components.fx", "str"). - -DocsStdlib() => - cards := str.join(data: [ - RenderMiniCard(input: HtmlCardData(title: "str", text: "Text projection and matching.")), - RenderMiniCard(input: HtmlCardData(title: "array", text: "Ordered values and small list helpers.")), - RenderMiniCard(input: HtmlCardData(title: "json", text: "JSON boundary values.")), - RenderMiniCard(input: HtmlCardData(title: "csv", text: "CSV rows and fact generation.")), - RenderMiniCard(input: HtmlCardData(title: "file", text: "Local file I/O.")), - RenderMiniCard(input: HtmlCardData(title: "math", text: "Scalar numeric helpers.")), - RenderMiniCard(input: HtmlCardData(title: "system", text: "Runtime print and type inspection.")), - RenderMiniCard(input: HtmlCardData(title: "console", text: "Interactive terminal I/O.")), - RenderMiniCard(input: HtmlCardData(title: "thread", text: "Thread handles for method execution.")) - ], delimiter: ""), - content := RenderModuleGrid(content: cards), - return (HtmlRichSectionData(id: "stdlib", title: "Standard Library", p: "The Felidae standard library is a compact set of explicit modules. Each core/*.fx file is the public contract. Deterministic operations execute as verified Builtin IR calls in RegisterVm; external services must be supplied explicitly by a runtime.", p2: "This page is only the stable overview. Open one module page at a time for focused signatures, examples, and cautions. That keeps json separate from csv, file separate from math, and str separate from array.", content: content, code: "import (\"str\", \"json\").\n\nCustomer(name: \"\").\n\nmain() =>\n rows := Customer.all(),\n names := lambda(rows, row => row.name),\n label := str.join(data: names, delimiter: \", \"),\n return (count: count(rows), names: label, json: json.toText(data: names)).", note: "Read module pages when choosing an API. The overview should stay stable and short; module-specific risks belong near that module.", code2: "Core files:\ncore/str.fx\ncore/array.fx\ncore/json.fx\ncore/csv.fx\ncore/file.fx\ncore/math.fx\ncore/system.fx\ncore/console.fx\ncore/thread.fx")). diff --git a/docs/testing.fx b/docs/testing.fx deleted file mode 100644 index 502390c..0000000 --- a/docs/testing.fx +++ /dev/null @@ -1,13 +0,0 @@ -import "html_components.fx". - -DocsTesting() => - smoke := RenderMiniCard(input: HtmlCardData(title: "Smoke Tests", text: "A smoke test runs a complete .fx file and checks a few stable substrings in the returned tuple. Use this for examples, docs snippets, and regression bugs.")), - unit := RenderMiniCard(input: HtmlCardData(title: "Unit-Style Methods", text: "Keep pure transformations in named methods, then call them from main() with small input facts. Return expected and actual values so failures are obvious.")), - negative := RenderMiniCard(input: HtmlCardData(title: "Negative Cases", text: "Keep invalid syntax, type mismatches, and bad imports under examples/invalid or tests/invalid. Assert parser and AST diagnostics with felidae_debug.")), - ci := RenderMiniCard(input: HtmlCardData(title: "CI Checks", text: "Run felidae_debug --check-json for diagnostics, then run Felidae programs that assert behavior. Use main() results as the stable contract.")), - part1 := str.concat(left: smoke, right: unit), - part2 := str.concat(left: part1, right: negative), - cards := RenderGrid(content: str.concat(left: part2, right: ci)), - guidance := RenderGuidance(doText: "Test through main(), named methods, and stable returned tuples. Keep the expected value near the input data so a failed test reads like a small story.", dontText: "Do not rely only on one-off command-line queries for regression coverage. CLI queries are useful while debugging, but tests should be repeatable from a file.", recommendText: "Register representative v2_examples with CTest so each program is compiled to verified IR, executed by RegisterVm, and checked against a stable result."), - content := str.concat(left: cards, right: guidance), - return (HtmlRichSectionData(id: "testing", title: "Testing Felidae Programs", p: "Felidae tests should look like Felidae programs. Put the behavior under test in named facts and methods, call it from main(), and return a tuple that contains the case name, expected value, actual value, and status. This keeps tests readable by people and easy to run from automation.", p2: "Use two layers: pure unit-style checks inside the language and CTest integration cases that compile v2 examples to binary IR and execute them with RegisterVm. felidae_debug owns syntax and compiler-high-level-IR diagnostics through --check-json.", content: content, code: "AssertEquals(name: string, expected: any, actual: any) =>\n where expected == actual\n return (name: name, status: \"passed\", expected: expected, actual: actual)\nelse\n return (name: name, status: \"failed\", expected: expected, actual: actual)\nend\n\nAddTax(amount: number, rate: number) =>\n return amount + amount * rate\nend\n\nmain() =>\n case1 := AssertEquals(name: \"adds tax\", expected: 110, actual: AddTax(amount: 100, rate: 0.10))\n case2 := AssertEquals(name: \"keeps zero tax\", expected: 80, actual: AddTax(amount: 80, rate: 0.0))\n failures := lambda([case1, case2], row => row.status == \"failed\")\n return (status: \"tested\", passed: count([case1, case2]) - count(failures), failed: count(failures), cases: [case1, case2])\nend", note: "Keep application examples and tests centered on main(). That is the repeatable contract used by documentation, CTest, the compiler, and RegisterVm.", code2: "# Run registered source-to-VM examples from the build tree:\nctest --test-dir build/debug -L examples --output-on-failure" )). diff --git a/docs_language.md b/docs_language.md index 8884fbb..abb0109 100644 --- a/docs_language.md +++ b/docs_language.md @@ -1,773 +1,110 @@ -# Felidae Logic Programming Language Notes +# Felidae language reference -Felidae is a functional logic language for typed facts, explicit dataflow, and -native stdlib calls. This document describes the current ("v2") grammar and -runtime behavior, verified against the interpreter in `src/`. The reference -programs for this grammar live in `v2_examples/`. The `examples/` directory is -legacy material and is being migrated separately; don't copy syntax from it. +Felidae parses `.fx` source into a `Program` AST and evaluates that AST with +the direct interpreter. A program never needs conversion to a binary file. -## Statement Termination +## Statements -Use `.` to give an ordinary statement an explicit boundary: +Facts, rules, methods, globals, imports, and annotations are source-level AST +statements. Use `.` for ordinary declaration boundaries. -```Felidae -import "math". - -Person(name: "Alice", role: "Engineer"). -Person(name: "Bob", role: "Manager"). +```felidae +Person(name: "Ada", active: true). Greeting(name: string) => - return (message: name). -``` - -The tokenizer encodes a complete dot-terminated statement as one span. A -statement can therefore cross physical lines, including a `then` pipeline: - -```Felidae -result := prepare(value: input) - then normalize(value: system.result) - then finish(value: system.result). -``` - -Dots inside a quoted string, a decimal (`3.01`), or adjacent member access -(`a.b.c`) are not terminators. `end` closes a class or method block and is -written without `.`. An annotation is attached to the declaration following -it and is not a separate statement. - -The beta parser still accepts a newline boundary in older unambiguous source, -but new and migrated programs should use explicit dots. SentencePiece itself -does not tokenize line by line; newlines are formatting inside the current -statement span. - -## Goal Separators - -Inside a rule or method body, commas express conjunction. A newline formats a -goal but does not replace an explicit statement boundary in new code: - -```Felidae -HotAdd(value: int) => - doubled := value + value, - return (result: doubled). + return (message: "hello", name: name) -HotAddNoCommas(value: int) => - doubled := value + value. - return (result: doubled). -``` - -## Memory Model - -Facts and rules are stored by predicate name: - -```text -predicate name -> list of ClauseStmt facts/rules +main() => + return Greeting(name: "Ada") ``` -Imported `.fx` statements are parsed and registered incrementally and remain -available for the interpreter lifetime; modules are not evicted and reparsed. -Native package libraries remain demand-loaded at the first native method call. -The runtime also keeps hash maps for predicate-to-clause lookup, compatible -fact indexes, and bounded repeated-query results. These caches are invalidated -whenever new program state is registered. +`:=` is immutable single-assignment inside a goal sequence. `where`, `if`, +`not`, groups, `or` branches, comparisons, and returns are interpreted in +source order. A rule’s fallback branch is evaluated only after the normal +branch cannot solve. -Variables bound with `:=` are immutable and single-assignment: a name already -declared as a rule-head field or a prior `:=` cannot be rebound in the same -scope. Arrays are intended for bounded, in-memory collections; use a -linked-list style structure (see `core/list.fx` and the List/ListItem facts it -declares) for larger logical data sets so the C++ runtime can back storage with -vector chunks without growing one large mutable array. +## Classes and explicit blocks -## Imports +`class` declarations are direct AST schema declarations. Their inheritance is +registered in `FactMemory`, so a child fact participates in queries for its +parent type. `end` explicitly closes a class, method, or nested `if` block; +it has no VM or compiled representation. ```felidae -import "file.fx" -import "directory" -import "directory/*" -import ("one.fx", "two.fx") -import "math" -import ("file", "math", "ml", "db") -import "system" # optional; system is available automatically -``` - -The VS Code extension provides document links for import strings. -Bare library imports resolve to declaration files under `core/`. These files -contain only native method heads such as `math.abs(value: number) => ()`; the -actual body is the matching C++ builtin implementation. Imports are resolved -lazily: the declaration file is only parsed and loaded the first time -something in it is actually needed, so an unused `import` never pays the cost -(or surfaces a parse error in) of the module it names. -`system` is auto-imported by the interpreter, so `system.print(value: data)` can -be called even without an explicit `import "system"`. A handful of pure -expression builtins (`count`, `sum`, `average`, `sort`, `search`, `contains`, -`lower`, `upper`, `length`, `type`, `instanceof`, and basic `math.*` arithmetic) -are always available without any import, because they're dispatched through a -fixed builtin table rather than a declared `core/*.fx` signature. Import the -owning module explicitly anyway for clarity and portability. - -## Compiling And Running Programs - -Source compilation and VM execution are separate: - -```powershell -build\felidae_compiler.exe program.fx -build\felidae_vm.exe build\program.bin -``` - -The compiler writes a verified `.bin` into `build`; the VM loads, verifies, and -executes that artifact. `main` may declare zero -arguments (`main() =>`) or accept `arguments: system.stdin` to read CLI args: - -```Felidae -main(arguments: system.stdin) => - return (args: arguments.args) -``` - -The `system.stdin` object currently contains `args` and deterministic empty -`text`. If no `main` method exists, the program loads successfully and prints -a helpful message. - -## Module And Field Syntax - -Fact rows may be declared directly and should use explicit field names so the -stored data shape is clear: - -```Felidae -Person( - name: "Default", - age: 0, - country: "India" -) -``` - -Rule and method heads may use named fields, typed fields, or positional -parameters depending on the contract: - -```Felidae -ArrayLiteralTest(input: value) => - array:get(data: [1, 2, 3, 4], position: 2, access: value) -``` - -Inline fact values are also valid and evaluate to typed map values: - -```Felidae -Artists() => - return (result: Person(name: "Ramesh", age: 20)) -``` - -Direct fact declarations such as `Employee(name: "Alice")` are supported. -Named fact goals such as `Employee(name: name)` are also supported. A single -positional fact goal inside a method body, such as `Employee(e)`, is not an -iterator and is rejected because Felidae does not implicitly scan a fact type -as though it were a list. Use `lambda(Employee, e => ...)` for explicit fact -iteration, or read from an explicit array/list. - -Facts may repeat a named field to represent multi-valued data. At runtime the -field is materialized as an array for method-body access, and direct fact -queries enumerate each repeated value: - -```Felidae -Cat1(name: "kitten", name: "tiger", name: "lilly") -``` - -Use `.` for top-level package/module calls: - -```Felidae -proofs := provenance.BuildFromRecording(rec: rec, store: store, goal: goal, options: {}) -``` - -Use `.` for map/object field access. Use `:` for named arguments and local namespaces: - -```Felidae -Employee(name: "Alice") -x == a.z.w -array:get(data: [1, 2, 3], position: 0, access: value) -``` - -`::` is not supported. Use `.` for top-level package/module calls. - -## Logic Operators - -`,` is conjunction. It means AND and every goal in the sequence must hold: - -```Felidae -EngineerInSEA(employee: e, name: Name) => - Name == e.name, - e.role == "Engineer", - e.office == "SEA". -``` - -`|` is disjunction. It means OR between goal branches: - -```Felidae -TechnicalOrManager(name: name) => - Employee(name: name, role: "Engineer") | - Employee(name: name, role: "Manager") -``` - -Parentheses isolate complex goal expressions: - -```Felidae -TechnicalArchitectManager(name: name) => - (Employee(name: name, role: "Engineer") | - Employee(name: name, role: "Architect")), - Employee(name: name, role: "Manager") -``` - -## Method-Style Rules - -Typed method-style rule heads use the field name as the local input variable -and the field value as the accepted fact/type: - -```Felidae -isAdult(input: Person) => - p := input - where p.age >= 18 - return ( - name: p.name - ) -``` - -Facts can extend a base fact/type. Child fields override parent fields: - -```Felidae -Person(name: "Default", age: 0, country: "India") -Employee extend Person(name: "Ravi", age: 30, role: "Engineer") -``` - -For an explicit reusable schema, declare a compiler-level fact class. Classes -and methods nested inside them require `end`; instances remain ordinary facts: - -```Felidae class Person name: string - age: number index(name) - index(name, age) - - adult(minimumAge: number) => - where age >= minimumAge - return 1.0 - else - return 0.0 - end end -Person(name: "Ada", age: 32) -``` - -Class fields constrain source fact rows, inherited fields are accepted, and -index declarations are carried in the existing executable fact-type metadata. -The VM maintains exact single/composite indexes for those declarations; -`where` selects the widest fully covered inherited index and applies remaining -predicates as residual checks. Unindexed scans are bounded and large queries -report which corrective action is required. There is no runtime class object -or second interpreter. - -Classes and fact declarations share this one hierarchy. All combinations are -valid when the named parent exists: a fact may extend a fact or class, and a -class may extend a fact or class. A class contributes schema fields and index -metadata; an ordinary fact parent contributes hierarchy membership without -creating a second class runtime. - -## Hierarchical Fact Queries - -Facts are first-class values. Query their declared type directly; no synthetic -`Fact.*` or `Relation.*` namespace exists: - -```Felidae -active := School.where(city: "BLR", active: 1.0) -limited := active.limit(records: 100) -teachers := School.join(type: Teacher, left: "id", right: "school_id") -changed := School.where(city: "BLR").update(values: {active: 0.0}) -removed := School.where(active: 0.0).delete() -titles := School.search(field: "name", query: "%academy%", type: "like", - case: "insensitive") -``` - -`where` uses named-field equality. `AndWhere` intersects with another -condition and `OrWhere` forms a stable union. Hierarchy primitives and ordinary -field comparisons provide explicit evidence-based reasoning without a second -relationship interpreter. - -`update` and `delete` must follow `where`, `AndWhere`, or `OrWhere`; direct -type-wide mutation is rejected. A join must name both key fields. These -requirements prevent accidental blind updates, deletes, and Cartesian joins. - -`where` is deterministic structured filtering. `search` is a separate -discovery operation for text patterns, hierarchy-valued properties, and degree -ranges or closeness. Text search supports exact/prefix/suffix/contains, SQL -LIKE (`%` and `_`), and regular-expression modes. Degree search preserves -intermediate values—including negative values and values greater than `1.0`— -and returns the matching facts in creation order. Its tolerance must be -non-negative; no search result is implicitly normalized into truth. - -Relationships and dependency evidence are ordinary typed facts, not hidden -verbs or a second relationship runtime. For example, declare -`Relationship(from: ..., to: ..., name: ..., degree: ...)`, query it with -`Relationship.where(...)`, and join it to the relevant entity type by explicit -keys. Domain rules decide how graded evidence is combined. Facts, maps, arrays, -strings, and arbitrary numbers are not implicitly Boolean: use an explicit -comparison in `where` or `if` when a branch requires numeric truth. - -When a domain relationship has mixfix syntax, invoke that relationship using -the declared expression itself: - -```Felidae -association := person works at company -``` - -`Association.where(...)` is a later database query over association facts; it -is not a substitute for evaluating the `works at` relationship. - -Joins build an ordered lookup from the declared right key and probe it from -the left input. They preserve fact-creation order and duplicate-key matches; -the runtime does not execute a Cartesian nested scan. - -`commonAncestors(left:, right:)` returns the complete deterministic candidate -set in stable order. Felidae does not expose context-free “lowest” or “highest” -ancestor choices. When an application needs a contextual score, it explicitly -calls `ssm.suggest(input:)`; that result is a finite, unrestricted `double`, -not a degree clamped to `[0, 1]`, and branching must compare it explicitly. -`ancestorAnalysis(left:, right:)` returns each candidate together with every -bounded proof path and the shortest distance from both subjects. The VM -service command `proof ` likewise prints all paths. - -Use `type(value: item, name: TypeName)` to read a value's concrete type, and -`instanceof(value: item, type: Person)` to check whether a value is an instance -of a fact/type or one of its parents through `extend`. Both are goal-style -builtins meant to be used as a guard/condition in a rule body, not assigned -directly with `:=`: - -```Felidae -CheckPerson(input: any) => - instanceof(value: input, type: Person) - return (ok: 1.0) -else - return (ok: 0.0) -``` - -`lambda(Type, item => condition)` filters facts of a type, and -`lambda(sourceArray, item => expression)` maps arrays: - -```Felidae -Adults := lambda(Person, p => isAdult(input: p)) -Names := lambda(Person, p => p.name) -``` - -Method calls do not implicitly iterate over compatible facts. A method processes -one provided input at a time, and `celidae --check-json` reports this before -run/debug execution: - -```Felidae -isAdult(input: Person) => - where input.age >= 18 - return ( - name: input.name - ) -``` - -`isAdult(name: name)` does not scan all `Person` facts. Likewise, -`Person(p)` in a method body does not iterate over `Person` facts. Use lambda -when you want iteration: - -```Felidae -Adults := lambda(Person, p => isAdult(input: p)) -``` - -### Returning A Value - -A method's `return` goal accepts a tuple of named fields, a single bare -expression, `nil`, or nothing at all: - -```Felidae -WithFields(x: number) => - return (x: x, doubled: x * 2) - -WithExpression(x: number) => - return x + 1 - -WithNil() => - return nil - -WithNoValue() => - system.print(value: "done") - return -``` - -### Ordered Fallback Branches - -Method-style rules may use ordered fallback `else` branches. This is not -procedural `if/else`; each branch is tried in order, and the first branch that -returns a result wins. Later branches are skipped. `where` is optional because a -plain comparison goal can also act as the branch guard: - -```Felidae -RoleAccess(input: Employee) => - e := input - e.role == "Engineer" - return ( - name: e.name, - access: "engineering" - ) -else - e.role == "Manager" - return ( - name: e.name, - access: "management" - ) -else - return ( - name: e.name, - access: "default" - ) -``` - -### if/else - -`if` also works as an inline conditional goal, comparing an expression directly -and branching without a separate `where`: - -```Felidae -main() => - x := 10 - if x == 10 - return (ok: 1.0) - else - return (ok: 0.0) -``` - -### Calling Conventions - -A method or compiler-known runtime-library call can be used in direct -assignment, capturing the whole return tuple (or the single returned value, -for a bare `return expr`): - -```Felidae -s := math.sin(value: 0) -result := HotAdd(value: 1) -``` - -User-defined predicates also accept an output-binding convenience: add a named -argument whose name matches a field of the callee's `return` tuple and whose -value is a fresh, not-yet-declared variable. That variable is bound to the -matching field after the call: - -```Felidae -HotAdd(value: int) => - doubled := value + value - return (result: doubled) +class Student extends Person + grade: number +end main() => - HotAdd(value: 1, result: a) - return (result: a) -``` - -Note that this only works when the return-field name is *not* also declared as -a head parameter of the callee — a head parameter and a same-named `:=` target -inside the body would collide, since head parameters are already bound at call -time. Keep output-only fields out of the head parameter list, as `HotAdd` -does above. - -A small set of builtins with a fixed dispatch token (`array:get`, `str:*`, -`json:*`, and similar fast-path natives — see `src/BuiltinRegistry.cpp` for the -full list) require the output variable to already be declared (typically as a -head parameter of the enclosing rule) before it's used this way. The most -portable pattern for these is to wrap the call in a small predicate and invoke -it through a query, or to prefer the plain `:=` assignment form documented -above wherever the native also supports it (most of `math.*`, `str.*`, `csv.*`, -`json.*`, `ml.*`, `http.*`, and `process.*` do). - -## Anonymous Variables - -`_` is anonymous and is not printed: - -```Felidae -Employee(name: "Alice", role: "Engineer", office: "SEA") -Employee(name: "Bob", role: "Manager", office: "LAX") - -# Query: -? Employee(name: Name, role: _, office: "SEA") -``` - -prints only `Name`. - -## Tuple Destructuring - -Tuple-returning methods can be destructured into immutable locals: - -```Felidae -a, b, c := someMethod() -a: string, b: bool, c: float := someMethod() -``` - -The right-hand side is evaluated once and must return a genuine tuple/array -value with the same number of values as the target list — an array literal -(`return [x, y]`), or `fn:tuple(...)` / `fn:pair(...)`. A method's named-field -`return (a: 1, b: 2)` produces a map, not a positional tuple, and is not a -valid right-hand side for this form; use `array1 := someMethod()` and access -fields with `.` instead. Optional target types support builtin types such as -`string`, `bool`, `number`, `int`, `float`, and `array`. A type mismatch raises -a `ProgrammingError` instead of silently binding the wrong value. - -## Arrays - -Both forms are accepted: - -```Felidae -array:get(data: [1, 2, 3, 4], position: 2, access: value) -array1 := fn:array(data: [1, 2, 3, 4]) -``` - -`array:get`'s `access:` output binding follows the fixed-builtin rule above: -`value` must already be declared (for example as a rule-head field) before -this goal runs. `fn:array` is a plain `:=` assignment and always works. - -## Exceptions - -Felidae does not use `try`/`catch`. Recoverable operations return the standard -`Result` value from `core/exception.fx` instead: `{ok, value, error}`. A caller -checks `ok` and passes a failed result to an ordinary source-owned method when -it wants recovery. `core/exception.fx` defines only the `Exception` and -`Result` shapes plus `exception.ok`, `exception.failure`, and -`exception.from`; application error kinds remain in application source. - -```Felidae -import "exception" - -CalculatorActions.handle(result: Result) => - if result.error.kind == "DivisionByZero" then - return exception.ok(value: {quotient: 0, recovered: 1.0}) - else - return result - -SafeDivide(dividend: number, divisor: number) => - if divisor == 0 then - rejected := exception.failure( - kind: "DivisionByZero", - message: "Cannot divide by zero", - source: "calculator" - ) - return CalculatorActions.handle(result: rejected) - else - return exception.ok(value: math.div(lhs: dividend, rhs: divisor)) + return Student(name: "Ada", grade: 10) +end ``` -Use `throw(exception: ..., target: Owner::method)` only for an unrecoverable -path that must immediately stop the current method. The target is one exact -callable reference, never a string. `kind` is the stable programmatic -discriminator while `message` remains user-facing context. - -## Built-In Expression Functions +## Facts and queries -The runtime supports simple expression builtins for direct execution, REPL, and -method bodies: +Facts live in `FactMemory`, which maintains relation indexes, provenance, +temporal metadata, immutable snapshots, and copy-on-write rollback. Queries +unify their fields with candidate facts; there is no second query engine. -```Felidae -count(Adults) -average(lambda(Person, p => p.age)) -sort(lambda(Person, p => p.name)) -search(lambda(Person, p => p.name), "Ra") -contains("Ravi", "Ra") -lower("HELLO") -upper("hello") -length("hello") -ParseDoc("Primary") -``` - -These expression builtins are auto-available from the runtime and documented in -`core/prelude.fx`. Do not model them as empty Felidae methods, because that -would shadow the runtime expression builtin during import. - -Native standard-library calls are dispatched to C++ implementations, keeping -heavy work out of the interpreter loop: +The direct fluent fact API is evaluated by that same store: ```felidae -import ("file", "math", "ml") - -file.readFile(path: "data.txt") -file.readLines(path: "data.txt") -file.writeFile(path: "data.txt", data: "hello", mode: "write") -file.writeFile(path: "data.txt", data: "hello", mode: "append") -file.exists(path: "data.txt") -csv.parse(data: "student,class\nJohn,10c") -csv.toFacts(data: "student,class\nJohn,10c", type: "School") -csv.toText(data: rows) -factText := csv.toFelidaeFacts(data: filteredRows, type: "School") -file.writeFile(path: "converted_csv_school.fx", data: factText, mode: "write") -console.writeLine(value: "hello") -system.print(value: "hello") -name := "Felidae" -system.printf("Hello {name}\n") -math.sqrt(value: 81) -math.pow(base: 2, exponent: 8) -ml.dot(left: [1, 2, 3], right: [4, 5, 6]) -ml.meanSquaredError(left: [1, 2, 3], right: [1, 2, 5]) -http.get(url: "https://example.com") -http.post(url: "http://127.0.0.1:8080/", body: "hello") -http.put(url: "http://127.0.0.1:8080/", body: "hello") -http.delete(url: "http://127.0.0.1:8080/") -http.serveStatic(host: "127.0.0.1", port: 8080, response: "Hello World") -process.platform() -process.exec(command: "echo hello") -process.sleep(milliseconds: 800) +active := School.where(district: "central").AndWhere(active: 1.0) +combined := School.where(district: "central").OrWhere(district: "west") +first := School.where(active: 1.0).limit(records: 1) +inserted := School.insert(values: {name: "Riverside", active: 1.0}) +changed := School.where(name: "Riverside").update(values: {active: 0.0}) +removed := School.where(name: "Riverside").delete() +first := School.get(pos: 0) ``` -HTTP client/server functions use the vendored header-only cpp-httplib module. -HTTPS client calls require an OpenSSL-enabled build of cpp-httplib; otherwise -the runtime raises a clear error. `examples/web_server.fx` starts a blocking -static-response server for GET, POST, PUT, and DELETE `/` routes. -`process.fx` is separate from `console.fx`: console handles stdin/stdout, while -process handles explicit trusted test commands, OS detection, and sleeps. -`csv.parse` returns ordinary row maps. `csv.toFacts(data: ..., type: "School")` -instead creates immutable native facts of a type declared in the loaded IR; -finite numeric cells become numbers and other cells remain text. Those facts -immediately participate in hierarchy queries and concrete type operations: -`School.all()`, `School.select(district: "central")`, and `School.count()`. -There is no synthetic `Fact.*` namespace or lazy `FactSelection` value. - -There is no public `db.sync()` operation. Facts imported from CSV with a source -path retain that ownership. A source file may also import a fact-only `.fx` -database; the compiler links its rows into executable IR and records their -source ownership without adding a runtime parser: +`db.sync(path:)` atomically reloads a fact-only `.fx` source file while +preserving unchanged logical identities. It is exposed by `core/db.fx`. -```Felidae -import "schools.fx" +```felidae +Animal(name: "tiger", habitat: "forest"). +Animal(name: "otter", habitat: "river"). main() => - changed := School.where(id: 7).update(values: {active: 0.0}) - return changed -end + return Animal(name: "tiger") ``` -`Type.insert`, `Type.update`, and `Type.delete` automatically persist each -affected CSV or `.fx` source through atomic replacement. Compiler parsing -never writes a database. Inserts without an inferred or explicit source remain -in memory. - -`ml.sigmoid`, `ml.relu`, `ml.dot`, and `ml.meanSquaredError` execute through the -real LibTorch tensor backend. A build without that backend reports an explicit -runtime error instead of substituting a fake or portable implementation. - -`thread.fx` declares the cooperative concurrency API. `thread.createThread`, -`thread.start`, `thread.status`, and `thread.result` run methods on immutable -interpreter snapshots. `thread.pause` and `thread.stop` intentionally report an -unsupported-operation error until cancellation semantics are implemented safely. - -`list.fx` declares a linked-list-style structure over facts (`List`, -`ListItem`) with `list.get`, `list.first`, and `list.pop` helpers, for -bounded, explicit iteration over ordered data without growing one large -mutable array. - -Deterministic runtime libraries use verified builtin IDs and typed C++ -implementations under `src/form/libs`; the retired native-module bridge is not -part of the build. A runtime reports an explicit error when an optional service -is unavailable. +The CLI supports an external query as its second argument: -`felidae.exe` is the optimized execution runtime and must not link AST analysis -or editor diagnostics. `celidae.exe` is the debugger, analytics, and -visualization product: it owns AST traversal, diagnostics, debugger analytics, -fact-database profiling, and optimization suggestions. Editor extensions call -`celidae.exe --check-json` on file changes and use `felidae.exe` only for normal -Run/Query execution. `celidae.exe --lsp` starts the native JSON-RPC language -server for clients that want a long-lived diagnostics process. -`felidae_debug.exe` is kept as a legacy compatibility name. - -Celidae caches compact diagnostic and statement summaries for repeated -diagnostics, debugger, and visualization requests. It does not retain a complete -project AST for unchanged files. Cached summaries are keyed by normalized path, -file identity, and content identity; unsaved LSP diagnostics are keyed by URI, -length, and content hash. -The normal `felidae.exe` interpreter keeps this cache disabled for now; batch -data-analysis optimization should layer query/fact indexes and visualization -profile caches on top of the runtime once profiling identifies the hot paths. -Source and file reads use a pre-sized read for normal files and a chunked -streaming read for files larger than 10 MB. - -## Exact and graded reasoning - -Felidae keeps exact Datalog truth separate from advisory reasoning. Register -explicit opposites and ask for an auditable proof: - -```felidae -Reasoning.contrary(positive: "Eligible", negative: "Ineligible") -result := Reasoning.prove(query: Eligible(name: "Ravi")) +```sh +felidae animals.fx '? Animal(name: x)' ``` -`Reasoning.prove` returns a `DerivationResult` whose `truth_status` is -`"proved"`, `"disproved"`, `"both"`, or `"unknown"`. Absence of proof is -unknown; it is not explicit disproval. Supporting and opposing fact identities, -rule spans, contradictions, and the explanation path remain available for -auditing. Pure recursive predicates use tabled evaluation; `not Predicate(...)` -is stratified negation-as-failure, requires its variables to be bound, and does -not create contrary evidence. +## Mixfix -Advisory evidence is explicit: +`@mixfix` declarations register deterministic patterns in the interpreter’s +operator registry. Pattern literals are tokenized from source and captures are +resolved as ordinary AST expressions; mixfix never uses a statistical model. ```felidae -evidence := [ - Evidence(source: "policy", degree: 0.9, reliability: 0.8, polarity: "support"), - Evidence(source: "risk", degree: 0.6, reliability: 0.7, polarity: "oppose") -] -decision := Reasoning.decide( - query: Eligible(name: "Ravi"), - evidence: evidence, - profile: ReasoningProfile( - conjunction: "minimum", - disjunction: "maximum", - evidence_aggregation: "maximum", - negation: "one_minus" - ) -) -``` - -Grades and reliability must be finite values from zero through one. Supporting -and opposing evidence are preserved rather than averaged away. Fuzzy degree, -confidence, probability, and similarity are separate fields and never change -the exact truth status automatically. - -Concrete fact queries return ordinary arrays of retained native facts. Query -predicates use numeric `0.0`/`1.0` truth and execute through the verified VM -fact-iteration path; no cursor wrapper or AST runtime is involved. - -Plain numeric values are finite doubles and may be negative, between zero and -one, or greater than one. They are not clamped to a degree range. Classifiers -and logical predicates return exact `0.0`/`1.0`; arithmetic functions such as -`avg`, `diff`, `lerp`, `pow`, and `weighted_avg` preserve ordinary signed -floating-point results. - -## Visual Data Analysis +@mixfix(pattern: "reason {subject: expr} with {evidence: string}") +Reason() => return Explanation(subject: subject, evidence: evidence) -Felidae is useful for log-shaped data because rules can clean, filter, project, -and query records before visualization. Use `lambda(...)`, named fact queries, -CSV/JSON helpers, and method-style guards to shape noisy rows into explicit -facts or globals, then open `Felidae: Visualize`. - -The VS Code visualizer reads the Celidae data snapshot from -`celidae --visualize-data-json --load-imports` and builds multiple views. -Use `celidae --inspect-graph` for lightweight source/file inspection; add -`--load-imports` or use the `--visualize-data-*` commands when the analysis -scenario must include imported fact databases. `celidae --visualize-data-html --load-imports` -emits a standalone HTML visualization for sharing or quick -inspection outside the IDE: - -- Graph: interactive data-flow/fact/method/library diagram with SVG export. -- Profile: charts and counts for node kinds and relationship labels. -- Quality: warnings for isolated data, duplicate labels, sparse metadata, - unlabeled relationships, and high fan-out hubs common in noisy logs. -- Data Table: searchable runtime entities with degree counts and quality - signals. +main() => return reason "tiger" with "observed" +``` -This keeps analysis tied to the same runtime data contract used by queries and -debugging instead of relying on a separate editor-only parser. +## Tokenization -Felidae programs can create the same visualization artifacts programmatically -through interpreter built-ins: +The custom BPE model is `models/felidae-bpe/model.txt`. The normal lexer owns +its fixed first 59 syntax IDs, comments, strings, numbers, punctuation, +operators, and reserved words (including `class`, `extends`, `index`, and +`end`). The remaining line-oriented text dictionary +stores identifiers and mixfix anchors only; missing identifiers are appended +in source order without training. -```felidae -graphJson := visualize.dataJson(loadImports: "true") -html := visualize.dataHtml(loadImports: "true") -file.writeFile(path: "build/report.html", data: html, mode: "write") -``` +## Reloading source -The `felidae.exe` interpreter also accepts `--visualize-data-json` and -`--visualize-data-html` for scripted use. Both interpreter and Celidae routes use -the same runtime graph and HTML renderer, so generated output stays consistent. +Run `felidae program.fx --serve` to watch the root module and its loaded +imports. A changed source tree is parsed into a fresh AST interpreter and +swapped in only after successful registration; the previous program remains +available when a save has syntax or semantic errors. diff --git a/models/README.md b/models/README.md index 3ab6fb9..540f05f 100644 --- a/models/README.md +++ b/models/README.md @@ -1,16 +1,12 @@ -# Generated models - -`felidae.model` and `FelidaeSentencePieceIds.h` are versioned together because -their PieceIds form part of the executable IR contract. Normal builds consume -them without rewriting them. - -After reviewing the relevant Git history and changing an authoritative corpus -or grammar input, regenerate them explicitly with: - -```sh -cmake --build build/debug --target felidae_regenerate_sentencepiece_model --parallel 8 -``` - -Keep the result only when both generated artifacts are intentional and their -tests pass. Versioned LibTorch GRU artifacts and manifests also belong here. -They remain outside `build/`, which is reserved for build products. +# Felidae token model + +`felidae-bpe/model.txt` is the only tokenizer model. It is line-oriented: +line N is token ID N. The first 59 entries are fixed syntax IDs declared in +`src/FelidaeTokenizerIds.h`; do not reorder them. + +The remaining entries form a simple checked-in text dictionary. The normal +lexer owns comments, strings, numbers, punctuation, operators, and reserved +words such as `class`, `extends`, `index`, and `end`; BPE looks up only +identifiers and mixfix anchors, then appends missing +identifiers in source order. No model training, generated binary model, +WordNet synset database, or external tokenizer dependency is needed. diff --git a/models/felidae-bpe/README.md b/models/felidae-bpe/README.md new file mode 100644 index 0000000..b996a58 --- /dev/null +++ b/models/felidae-bpe/README.md @@ -0,0 +1,11 @@ +# Felidae deterministic BPE model + +`model.txt` is a line-oriented vocabulary. The physical line number is the +stable token ID, starting at zero. The first 59 lines are Felidae's fixed +grammar IDs and must not be reordered. `<0xNN>` denotes one byte so that +whitespace and arbitrary UTF-8 remain reversible. New identifier words are +appended deterministically by the runtime. + +The initial word entries are a small checked-in text-dictionary seed. The +runtime extends the same table from source. This tokenizer has no training +step and no WordNet or SentencePiece dependency. diff --git a/models/felidae-bpe/model.txt b/models/felidae-bpe/model.txt new file mode 100644 index 0000000..f5ea77e --- /dev/null +++ b/models/felidae-bpe/model.txt @@ -0,0 +1,544 @@ + +import +not +and +or +then +as +if +else +return +where +extend +lambda +true +false +nil +( +) +{ +} +[ +] +, +: +. +| +? +@ +:= +:: +=> ++ +- +* +/ +% +== +!= +< +<= +> +>= +" +\ +# +<0x20> +<0x09> +<0x0A> +<0x0D> +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +the +of +to +in +is +that +for +on +with +as +by +from +this +be +or +an +are +one +have +not +noun +verb +adjective +adverb +entity +thing +action +object +property +function +value +type +name +class +method +rule +fact +tiger +main +answer +animal +The +first +mixfix +produces +expression +valued +second +captures +complete +expr +invokes +it +Evidence +kind +observed +Context +domain +behaviour +pattern +reason +subject +using +evidence +within +context +reasonFactValue +Explanation +validate +claim +expected +string +validateReasonValue +Validation +result +explanation +direct +cat +bound +literal +A +AST +If +Statements +a +active +adjusted +after +all +any +at +before +behavior +branch +clause +compile +compiler +construct +current +eligible +error +exactly +execution +extra +fails +failure +falls +guard +guarded +guessed +here +inactive +intentionally +involved +level +lowScore +nested +no +nodes +normalizes +number +only +opcode +order +ordinary +passes +path +query +rather +requires +retain +run +runtime +s +score +sequential +single +succeeds +than +their +those +through +while +` +' +; +Acceptable +Agree +Critical +Degree +DegreeReport +Deterministic +Disagree +Exceptional +Neutral +RatingProfile +Strong +Strongly +Subpar +acceptable +below +closenessDegree +condition +confidence +critical +degree +exceptional +explicit +facts +fades_in +fades_out +fuzzy +maps +membership +membershipDegree +met +peak +primitives +profile +quality +rating +remain +report +results +similarity +state +strong +subpar +threshold +truth_degree +values +Applicant +ApprovalDecision +Assessment +CreditProfile +Error +IncomeProfile +InsufficientEvidence +Person +Policy +RuleEvidence +against +applicant +approvedApplicants +array +assess +assessApplicant +assessment +assessmentQualifies +ava +code +composition +contribution +control +credit +creditScore +credit_score +data +decide +declinedApplicants +did +evaluation +expert +explain +explainAssessment +expressions +flow +get +income +incomeScore +income_score +minimum +minimum_credit +minimum_income +minimum_score +mira +normal +participate +pipeline +policies +policy +position +prime +qualifies +reach +required +satisfied +style +system +verification +verificationScore +verification_score +verified +Alice +AnyEmployee +Bob +Choice +Color +Employee +Engineer +ExpectedChoices +ExpectedSamePairs +LAX +Manager +NestedEmployee +Pair +SEA +SamePair +Shape +Wrapped +_ +blue +choiceChecks +choice_count +choices +circle +color +count +employee +employeeNames +employee_count +employees +green +item +left +meta +nestedEmployees +nested_count +office +red +right +role +samePairChecks +same_pair_count +same_pairs +shape +square +wrapped +Factorial +factorial +int +n +print +ABC +Adults +Anu +Artist +Artists +Contemporary +Default +India +Math +Mumbai +Painting +Ramesh +Ravi +School +Sita +Student +Teacher +age +args +arguments +art_form +category +country +location +names +p +school +stdin +Angeles +Charlie +Chicago +David +Eve +Frank +Houston +Imported +Los +New +Parent +Phoenix +York +child +file +parent +place +x +y +decimal +inserted +insert +updated +update +deleted +delete +rows +synchronized +db +sync +ImportedSchool +district +students +importExample +raw +readFile +imported +csv +toFacts +source +Animal +Mammal +Reptile +id +school_id +classifyEnrollment +queryExamples +active_central +central_or_west +OrWhere +large_central +AndWhere +top_one +limit +records +active_central_count +central_or_west_count +large_central_count +top_one_count +projectionExample +select +fields +match +aggregateExamples +total_schools +total_students +sum +field +average_students +average +smallest +min +largest +max +joinExamples +inner +join +inner_count +left_count +mutationExamples +inserted_name +updated_count +deleted_count +ancestryExamples +lizard +common +commonAncestors +ratedAbove +mixfixExample +rated +above +imported_count +classification +queries +projected +aggregates +joins +mutations +ancestry +end +csvData +allSchools +activeCentral +allCount +activeCentralCount +all_schools +all_count +Dog +Cat +or_count +and_count +limited +grade +increment +classify +high +middle +low +double +evaluate +processed +accepted +rejected +Company +Association +left_id +right_id +relation +strength +worksAt +person +company +people +fx +cast_ +companies +works +Receiver +calls +reuse +existing +operations +push +returns +new +so +its +explicitly +obj +len +pos +from_array +key +access diff --git a/src/AST.h b/src/AST.h index 893997f..28b1146 100644 --- a/src/AST.h +++ b/src/AST.h @@ -1,13 +1,7 @@ #pragma once -// Felidae's compiler-only high-level IR (HIR). The representation is a -// syntax-shaped node tree because that preserves source spans, mixfix -// captures, and debugger diagnostics efficiently. It is not executable AST: -// IrCodeGenerator lowers it once to verified FelidaeIr, and neither binary -// modules nor RegisterVm retain or interpret these nodes. - -#include "FelidaeGrammar.h" #include "Operator.h" +#include "FelidaeGrammar.h" #include #include #include @@ -20,604 +14,645 @@ namespace Felidae { enum class ExprKind { - String, - Number, - Bool, - Nil, - Var, - Array, - Map, - Access, - Operator, - Term, - Lambda, - AstValue + String, + Number, + Bool, + Nil, + Var, + Array, + Map, + Access, + Operator, + Term, + Lambda, + FactSelection, + AstValue }; enum class GoalKind { - Call, - Binary, - Assign, - MultiAssign, - Where, - If, - Return, - Not, - Group, - Or + Call, + Binary, + Assign, + MultiAssign, + Where, + If, + Return, + Not, + Group, + Or }; -enum class StatementKind { Import, Clause, GlobalBinding, Class }; +enum class StatementKind { + Import, + Clause, + GlobalBinding, + Class +}; -enum class ClauseKind { Fact, Rule, Method, NativeDeclaration, EntryCall }; +enum class ClauseKind { + Fact, + Rule, + Method, + NativeDeclaration, + EntryCall +}; struct SourceSpan { - int startLine = 1; - int startColumn = 1; - int endLine = 1; - int endColumn = 1; - - bool valid() const { - return startLine > 0 && startColumn > 0 && endLine >= startLine && - (endLine != startLine || endColumn >= startColumn); - } + int startLine = 1; + int startColumn = 1; + int endLine = 1; + int endColumn = 1; + + bool valid() const { + return startLine > 0 && startColumn > 0 && + endLine >= startLine && + (endLine != startLine || endColumn >= startColumn); + } }; class AstNode { public: - virtual ~AstNode() = default; - virtual std::string debug() const = 0; - - // Parser-produced ASTs are finite acyclic trees bounded by the parser's - // recursion and step limits. Lowering relies on that internal invariant; - // cycle detection belongs only at an external AST-construction boundary. - // The parser assigns compact positional metadata as soon as a node is - // completed. Source text remains owned by the input/runtime layer, so - // retaining an AST node never pins a complete input buffer. - SourceSpan sourceSpan; - std::uint64_t nodeId = 0; + virtual ~AstNode() = default; + virtual std::string debug() const = 0; + + // The parser assigns compact positional metadata as soon as a node is + // completed. Source text remains owned by the input/runtime layer, so + // retaining an AST node never pins a complete input buffer. + SourceSpan sourceSpan; + std::uint64_t nodeId = 0; }; class Expr : public AstNode { public: - virtual ExprKind kind() const = 0; - virtual std::shared_ptr clone() const = 0; + virtual ExprKind kind() const = 0; + virtual std::shared_ptr clone() const = 0; }; class StringExpr final : public Expr { public: - explicit StringExpr(std::string value, - std::vector sentencePieceIds = {}, - bool containsEscape = false) - : value(std::move(value)), sentencePieceIds(std::move(sentencePieceIds)), - containsEscape(containsEscape) {} - std::string value; - // Captured from the parser's line-wise SentencePiece stream. The compiler - // writes these IDs directly into IR text constants and does not tokenize - // an already parsed literal again. - std::vector sentencePieceIds; - bool containsEscape = false; - - ExprKind kind() const override { return ExprKind::String; } - std::shared_ptr clone() const override { - return std::make_shared(value, sentencePieceIds, - containsEscape); - } - std::string debug() const override { - std::ostringstream oss; - oss << '"'; - for (char c : value) { - if (c == '"') - oss << "\\\""; - else if (c == '\n') - oss << "\\n"; - else - oss << c; + explicit StringExpr(std::string value) : value(std::move(value)) {} + std::string value; + + ExprKind kind() const override { return ExprKind::String; } + std::shared_ptr clone() const override { return std::make_shared(value); } + std::string debug() const override { + std::ostringstream oss; + oss << '"'; + for (char c : value) { + if (c == '"') oss << "\\\""; + else if (c == '\n') oss << "\\n"; + else oss << c; + } + oss << '"'; + return oss.str(); } - oss << '"'; - return oss.str(); - } }; class NumberExpr final : public Expr { public: - explicit NumberExpr(double value) : value(value) {} - double value; - - ExprKind kind() const override { return ExprKind::Number; } - std::shared_ptr clone() const override { - return std::make_shared(value); - } - std::string debug() const override { - std::ostringstream oss; - oss << std::setprecision(15) << value; - return oss.str(); - } + explicit NumberExpr(double value) : value(value) {} + double value; + + ExprKind kind() const override { return ExprKind::Number; } + std::shared_ptr clone() const override { return std::make_shared(value); } + std::string debug() const override { + std::ostringstream oss; + oss << std::setprecision(15) << value; + return oss.str(); + } }; class BoolExpr final : public Expr { public: - explicit BoolExpr(bool value) : value(value) {} - bool value; - - ExprKind kind() const override { return ExprKind::Bool; } - std::shared_ptr clone() const override { - return std::make_shared(value); - } - std::string debug() const override { return value ? "true" : "false"; } + explicit BoolExpr(bool value) : value(value) {} + bool value; + + ExprKind kind() const override { return ExprKind::Bool; } + std::shared_ptr clone() const override { return std::make_shared(value); } + std::string debug() const override { return value ? "true" : "false"; } }; class NilExpr final : public Expr { public: - ExprKind kind() const override { return ExprKind::Nil; } - std::shared_ptr clone() const override { - return std::make_shared(); - } - std::string debug() const override { return "nil"; } + ExprKind kind() const override { return ExprKind::Nil; } + std::shared_ptr clone() const override { return std::make_shared(); } + std::string debug() const override { return "nil"; } }; class VarExpr final : public Expr { public: - explicit VarExpr(std::string name, - LanguageTypeId languageTypeId = LanguageTypeId::Unknown) - : name(std::move(name)), nameId(symbolIdForName(this->name)), - languageTypeId(languageTypeId) {} - VarExpr(std::string displayName, SymbolId directId, - LanguageTypeId languageTypeId = LanguageTypeId::Unknown, - bool capitalized = false) - : name(std::move(displayName)), nameId(directId), - languageTypeId(languageTypeId), isCapitalized(capitalized) {} - std::string name; - SymbolId nameId = 0; - LanguageTypeId languageTypeId = LanguageTypeId::Unknown; - bool isCapitalized = false; - - ExprKind kind() const override { return ExprKind::Var; } - std::shared_ptr clone() const override { - return std::make_shared(name, nameId, languageTypeId, - isCapitalized); - } - std::string debug() const override { return name; } + explicit VarExpr(std::string name, LanguageTypeId languageTypeId = LanguageTypeId::Unknown) + : name(std::move(name)), nameId(symbolIdForName(this->name)), + languageTypeId(languageTypeId) {} + VarExpr(std::string displayName, SymbolId directId, + LanguageTypeId languageTypeId = LanguageTypeId::Unknown, + bool capitalized = false) + : name(std::move(displayName)), nameId(directId), languageTypeId(languageTypeId), + isCapitalized(capitalized) {} + std::string name; + SymbolId nameId = 0; + LanguageTypeId languageTypeId = LanguageTypeId::Unknown; + bool isCapitalized = false; + + ExprKind kind() const override { return ExprKind::Var; } + std::shared_ptr clone() const override { + return std::make_shared(name, nameId, languageTypeId, isCapitalized); + } + std::string debug() const override { return name; } }; class ArrayExpr final : public Expr { public: - explicit ArrayExpr(std::vector> items) - : items(std::move(items)) {} - - std::vector> items; - - ExprKind kind() const override { return ExprKind::Array; } - std::shared_ptr clone() const override { - std::vector> copied; - copied.reserve(items.size()); - for (const auto &item : items) - copied.push_back(item->clone()); - return std::make_shared(std::move(copied)); - } - - std::string debug() const override { - std::ostringstream oss; - oss << "["; - for (size_t i = 0; i < items.size(); ++i) { - if (i) - oss << ", "; - oss << items[i]->debug(); + explicit ArrayExpr(std::vector> items) + : items(std::move(items)) {} + + std::vector> items; + + ExprKind kind() const override { return ExprKind::Array; } + std::shared_ptr clone() const override { + std::vector> copied; + copied.reserve(items.size()); + for (const auto& item : items) copied.push_back(item->clone()); + return std::make_shared(std::move(copied)); + } + + std::string debug() const override { + std::ostringstream oss; + oss << "["; + for (size_t i = 0; i < items.size(); ++i) { + if (i) oss << ", "; + oss << items[i]->debug(); + } + oss << "]"; + return oss.str(); } - oss << "]"; - return oss.str(); - } }; struct MapEntry { - MapEntry() = default; - MapEntry(std::string key, std::shared_ptr value) - : key(std::move(key)), keyId(symbolIdForName(this->key)), - value(std::move(value)) {} - MapEntry(std::string displayKey, SymbolId directId, - std::shared_ptr value) - : key(std::move(displayKey)), keyId(directId), value(std::move(value)) {} - - std::string key; - SymbolId keyId = 0; - std::shared_ptr value; + MapEntry() = default; + MapEntry(std::string key, std::shared_ptr value) + : key(std::move(key)), keyId(symbolIdForName(this->key)), value(std::move(value)) {} + MapEntry(std::string displayKey, SymbolId directId, std::shared_ptr value) + : key(std::move(displayKey)), keyId(directId), value(std::move(value)) {} + + std::string key; + SymbolId keyId = 0; + std::shared_ptr value; }; class MapExpr final : public Expr { public: - explicit MapExpr(std::vector entries) - : entries(std::move(entries)) {} - - std::vector entries; - // Set only for values created by Felidae fact declarations or - // constructors. It is intentionally separate from the visible __type - // field so an ordinary map cannot masquerade as a fact at the language - // boundary. - std::string factType; - // Runtime-only identity for a value materialized from FactMemory. It is - // deliberately absent from debug(), serialization and structural - // equality: two facts may have equal visible fields while retaining - // distinct identities for dependencies and relationships. - std::uint64_t factIdentity = 0; - - ExprKind kind() const override { return ExprKind::Map; } - std::shared_ptr clone() const override { - std::vector copied; - copied.reserve(entries.size()); - for (const auto &entry : entries) { - copied.push_back(MapEntry{entry.key, entry.value->clone()}); + explicit MapExpr(std::vector entries) + : entries(std::move(entries)) {} + + std::vector entries; + // Set only for values created by Felidae fact declarations or + // constructors. It is intentionally separate from the visible __type + // field so an ordinary map cannot masquerade as a fact at the language + // boundary. + std::string factType; + // Runtime-only identity for a value materialized from FactMemory. It is + // deliberately absent from debug(), serialization and structural + // equality: two facts may have equal visible fields while retaining + // distinct identities for dependencies and relationships. + std::uint64_t factIdentity = 0; + + ExprKind kind() const override { return ExprKind::Map; } + std::shared_ptr clone() const override { + std::vector copied; + copied.reserve(entries.size()); + for (const auto& entry : entries) { + copied.push_back(MapEntry{entry.key, entry.value->clone()}); + } + auto result = std::make_shared(std::move(copied)); + result->factIdentity = factIdentity; + result->factType = factType; + return result; } - auto result = std::make_shared(std::move(copied)); - result->factIdentity = factIdentity; - result->factType = factType; - return result; - } - - std::string debug() const override { - std::ostringstream oss; - oss << "{"; - for (size_t i = 0; i < entries.size(); ++i) { - if (i) - oss << ", "; - oss << entries[i].key << ": " << entries[i].value->debug(); + + std::string debug() const override { + std::ostringstream oss; + oss << "{"; + for (size_t i = 0; i < entries.size(); ++i) { + if (i) oss << ", "; + oss << entries[i].key << ": " << entries[i].value->debug(); + } + oss << "}"; + return oss.str(); } - oss << "}"; - return oss.str(); - } }; enum class AstValueKind : std::uint8_t { Expression, Statement, Statements }; class AstValueExpr final : public Expr { public: - AstValueExpr(AstValueKind valueKind, - std::vector> nodes, - std::string nodeKind) - : valueKind(valueKind), nodes(std::move(nodes)), - nodeKind(std::move(nodeKind)) {} - - AstValueKind valueKind = AstValueKind::Expression; - std::vector> nodes; - std::string nodeKind; - - ExprKind kind() const override { return ExprKind::AstValue; } - std::shared_ptr clone() const override { - return std::make_shared(valueKind, nodes, nodeKind); - } - std::string sourceText() const { - if (nodes.size() != 1 || !nodes.front()) - return {}; - if (const auto variable = - std::dynamic_pointer_cast(nodes.front())) { - return variable->name; + AstValueExpr(AstValueKind valueKind, + std::vector> nodes, + std::string nodeKind) + : valueKind(valueKind), nodes(std::move(nodes)), nodeKind(std::move(nodeKind)) {} + + AstValueKind valueKind = AstValueKind::Expression; + std::vector> nodes; + std::string nodeKind; + + ExprKind kind() const override { return ExprKind::AstValue; } + std::shared_ptr clone() const override { + return std::make_shared(valueKind, nodes, nodeKind); + } + std::string sourceText() const { + if (nodes.size() != 1 || !nodes.front()) return {}; + if (const auto variable = std::dynamic_pointer_cast(nodes.front())) { + return variable->name; + } + if (const auto text = std::dynamic_pointer_cast(nodes.front())) { + return text->value; + } + return nodes.front()->debug(); + } + std::string debug() const override { + const char* type = valueKind == AstValueKind::Expression ? "expr" : + valueKind == AstValueKind::Statement ? "stmt" : "stmts"; + return std::string("<") + type + ":" + nodeKind + ">"; + } +}; + +struct FactSelectionFilter { + std::string field; + SymbolId fieldId = 0; + TokenId::Id op = TokenId::EQUAL; + std::shared_ptr value; +}; + +// Runtime-only lazy fact query. It deliberately is not a MapExpr: user map +// operations cannot mutate or counterfeit its snapshot/cursor metadata. +class FactSelectionExpr final : public Expr { +public: + FactSelectionExpr(std::string factType, + std::uint64_t snapshotGeneration, + std::string field = {}, + std::shared_ptr equals = nullptr, + std::vector designationIds = {}, + std::vector designations = {}, + std::vector filters = {}) + : factType(std::move(factType)), + factTypeId(this->factType.empty() ? 0 : symbolIdForName(this->factType)), + snapshotGeneration(snapshotGeneration), + field(std::move(field)), + fieldId(this->field.empty() ? 0 : symbolIdForName(this->field)), + equals(std::move(equals)), + designationIds(std::move(designationIds)), + designations(std::move(designations)), + filters(std::move(filters)) {} + + std::string factType; + SymbolId factTypeId = 0; + std::uint64_t snapshotGeneration = 0; + std::string field; + SymbolId fieldId = 0; + std::shared_ptr equals; + std::vector designationIds; + std::vector designations; + std::vector filters; + + ExprKind kind() const override { return ExprKind::FactSelection; } + std::shared_ptr clone() const override { + std::vector copiedFilters; + copiedFilters.reserve(filters.size()); + for (const auto& filter : filters) { + copiedFilters.push_back(FactSelectionFilter{ + filter.field, + filter.fieldId, + filter.op, + filter.value ? filter.value->clone() : nullptr}); + } + return std::make_shared( + factType, + snapshotGeneration, + field, + equals ? equals->clone() : nullptr, + designationIds, + designations, + std::move(copiedFilters)); } - if (const auto text = - std::dynamic_pointer_cast(nodes.front())) { - return text->value; + std::string debug() const override { + std::ostringstream out; + out << "{__type: \"FactSelection\", fact_type: \"" + << factType << "\", source: \"memory\", snapshot_generation: " + << snapshotGeneration; + if (!designations.empty()) { + out << ", designations: ["; + for (size_t i = 0; i < designations.size(); ++i) { + if (i) out << ", "; + out << "\"" << designations[i] << "\""; + } + out << "]"; + } + if (!field.empty()) { + out << ", field: \"" << field << "\""; + if (equals) out << ", equals: " << equals->debug(); + } + if (!filters.empty()) out << ", filters: " << filters.size(); + out << "}"; + return out.str(); } - return nodes.front()->debug(); - } - std::string debug() const override { - const char *type = valueKind == AstValueKind::Expression ? "expr" - : valueKind == AstValueKind::Statement ? "stmt" - : "stmts"; - return std::string("<") + type + ":" + nodeKind + ">"; - } }; class AccessExpr final : public Expr { public: - AccessExpr(std::shared_ptr target, std::string key) - : target(std::move(target)), key(std::move(key)), - keyId(symbolIdForName(this->key)) {} + AccessExpr(std::shared_ptr target, std::string key) + : target(std::move(target)), key(std::move(key)), keyId(symbolIdForName(this->key)) {} - std::shared_ptr target; - std::string key; - SymbolId keyId = 0; + std::shared_ptr target; + std::string key; + SymbolId keyId = 0; - ExprKind kind() const override { return ExprKind::Access; } - std::shared_ptr clone() const override { - return std::make_shared(target->clone(), key); - } + ExprKind kind() const override { return ExprKind::Access; } + std::shared_ptr clone() const override { + return std::make_shared(target->clone(), key); + } - std::string debug() const override { return target->debug() + ":" + key; } + std::string debug() const override { + return target->debug() + ":" + key; + } }; struct OperatorCapture { - OperatorCapture() = default; - OperatorCapture(std::string name, std::shared_ptr expression) - : name(std::move(name)), nameId(symbolIdForName(this->name)), - expression(std::move(expression)) {} - - std::string name; - SymbolId nameId = 0; - std::shared_ptr expression; + OperatorCapture() = default; + OperatorCapture(std::string name, std::shared_ptr expression) + : name(std::move(name)), nameId(symbolIdForName(this->name)), expression(std::move(expression)) {} + + std::string name; + SymbolId nameId = 0; + std::shared_ptr expression; }; class OperatorExpression final : public Expr { public: - OperatorExpression(CoreOperator coreOperator, std::shared_ptr left, - std::shared_ptr right) - : operatorId(Felidae::operatorId(coreOperator)), - patternId(corePatternId(coreOperator)), coreOperator(coreOperator), - first_(std::move(left)), second_(std::move(right)), - inlineCaptureCount_(2) {} - - OperatorExpression(CoreOperator coreOperator, std::shared_ptr operand) - : operatorId(Felidae::operatorId(coreOperator)), - patternId(corePatternId(coreOperator)), coreOperator(coreOperator), - first_(std::move(operand)), inlineCaptureCount_(1) {} - - OperatorExpression(OperatorId operatorId, PatternId patternId, - std::vector captures, - bool explicitlyGrouped = false, - SymbolId resolvedMethodId = 0) - : operatorId(operatorId), patternId(patternId), - coreOperator(CoreOperator::Unknown), - explicitlyGrouped(explicitlyGrouped), - resolvedMethodId(resolvedMethodId), - namedCaptures_(std::move(captures)) {} - - OperatorId operatorId = 0; - PatternId patternId = 0; - CoreOperator coreOperator = CoreOperator::Unknown; - bool explicitlyGrouped = false; - // Compiler-only binding for a unique annotation-declared mixfix target. - // The VM receives only the ordinary Call instruction generated from it. - SymbolId resolvedMethodId = 0; - std::string module; - - size_t captureCount() const { - return coreOperator == CoreOperator::Unknown ? namedCaptures_.size() - : inlineCaptureCount_; - } - const std::shared_ptr &capture(size_t index) const { - if (coreOperator == CoreOperator::Unknown) - return namedCaptures_.at(index).expression; - if (index == 0 && inlineCaptureCount_ > 0) - return first_; - if (index == 1 && inlineCaptureCount_ > 1) - return second_; - throw std::out_of_range("Operator capture index"); - } - std::string_view captureName(size_t index) const { - if (coreOperator == CoreOperator::Unknown) - return namedCaptures_.at(index).name; - if (inlineCaptureCount_ == 1 && index == 0) - return "operand"; - if (index == 0) - return "left"; - if (index == 1 && inlineCaptureCount_ > 1) - return "right"; - return {}; - } - - ExprKind kind() const override { return ExprKind::Operator; } - std::shared_ptr clone() const override { - std::shared_ptr result; - if (coreOperator != CoreOperator::Unknown) { - result = captureCount() == 1 - ? std::make_shared(coreOperator, - capture(0)->clone()) - : std::make_shared(coreOperator, - capture(0)->clone(), - capture(1)->clone()); - } else { - std::vector copied; - copied.reserve(namedCaptures_.size()); - for (const auto &capture : namedCaptures_) { - copied.emplace_back(capture.name, capture.expression->clone()); - } - result = std::make_shared( - operatorId, patternId, std::move(copied), explicitlyGrouped, - resolvedMethodId); + OperatorExpression(CoreOperator coreOperator, + std::shared_ptr left, + std::shared_ptr right) + : operatorId(Felidae::operatorId(coreOperator)), + patternId(corePatternId(coreOperator)), + coreOperator(coreOperator), first_(std::move(left)), second_(std::move(right)), + inlineCaptureCount_(2) {} + + OperatorExpression(CoreOperator coreOperator, std::shared_ptr operand) + : operatorId(Felidae::operatorId(coreOperator)), + patternId(corePatternId(coreOperator)), + coreOperator(coreOperator), first_(std::move(operand)), inlineCaptureCount_(1) {} + + OperatorExpression(OperatorId operatorId, + PatternId patternId, + std::vector captures, + bool explicitlyGrouped = false) + : operatorId(operatorId), patternId(patternId), coreOperator(CoreOperator::Unknown), + explicitlyGrouped(explicitlyGrouped), namedCaptures_(std::move(captures)) {} + + OperatorId operatorId = 0; + PatternId patternId = 0; + CoreOperator coreOperator = CoreOperator::Unknown; + bool explicitlyGrouped = false; + std::string module; + + size_t captureCount() const { + return coreOperator == CoreOperator::Unknown ? namedCaptures_.size() : inlineCaptureCount_; + } + const std::shared_ptr& capture(size_t index) const { + if (coreOperator == CoreOperator::Unknown) return namedCaptures_.at(index).expression; + if (index == 0 && inlineCaptureCount_ > 0) return first_; + if (index == 1 && inlineCaptureCount_ > 1) return second_; + throw std::out_of_range("Operator capture index"); } - result->operatorId = operatorId; - result->patternId = patternId; - result->explicitlyGrouped = explicitlyGrouped; - result->resolvedMethodId = resolvedMethodId; - result->module = module; - result->sourceSpan = sourceSpan; - return result; - } - - std::string debug() const override { - const auto definition = coreOperatorDefinition(coreOperator); - if (definition.fixity == OperatorFixity::Prefix && captureCount() == 1) { - return std::string(definition.spelling) + capture(0)->debug(); + std::string_view captureName(size_t index) const { + if (coreOperator == CoreOperator::Unknown) return namedCaptures_.at(index).name; + if (inlineCaptureCount_ == 1 && index == 0) return "operand"; + if (index == 0) return "left"; + if (index == 1 && inlineCaptureCount_ > 1) return "right"; + return {}; } - if (captureCount() == 2) { - return capture(0)->debug() + " " + std::string(definition.spelling) + - " " + capture(1)->debug(); + + ExprKind kind() const override { return ExprKind::Operator; } + std::shared_ptr clone() const override { + std::shared_ptr result; + if (coreOperator != CoreOperator::Unknown) { + result = captureCount() == 1 + ? std::make_shared(coreOperator, capture(0)->clone()) + : std::make_shared(coreOperator, capture(0)->clone(), capture(1)->clone()); + } else { + std::vector copied; + copied.reserve(namedCaptures_.size()); + for (const auto& capture : namedCaptures_) { + copied.emplace_back(capture.name, capture.expression->clone()); + } + result = std::make_shared(operatorId, patternId, std::move(copied), explicitlyGrouped); + } + result->operatorId = operatorId; + result->patternId = patternId; + result->explicitlyGrouped = explicitlyGrouped; + result->module = module; + result->sourceSpan = sourceSpan; + return result; + } + + std::string debug() const override { + const auto definition = coreOperatorDefinition(coreOperator); + if (definition.fixity == OperatorFixity::Prefix && captureCount() == 1) { + return std::string(definition.spelling) + capture(0)->debug(); + } + if (captureCount() == 2) { + return capture(0)->debug() + " " + std::string(definition.spelling) + " " + capture(1)->debug(); + } + return "operator(" + std::to_string(operatorId) + ")"; } - return "operator(" + std::to_string(operatorId) + ")"; - } private: - std::shared_ptr first_; - std::shared_ptr second_; - std::vector namedCaptures_; - std::uint8_t inlineCaptureCount_ = 0; + std::shared_ptr first_; + std::shared_ptr second_; + std::vector namedCaptures_; + std::uint8_t inlineCaptureCount_ = 0; }; struct Arg { - Arg() = default; - Arg(std::string name, std::shared_ptr value) - : name(std::move(name)), - nameId(this->name.empty() ? 0 : symbolIdForName(this->name)), - value(std::move(value)) {} - Arg(std::string displayName, SymbolId directId, std::shared_ptr value) - : name(std::move(displayName)), nameId(directId), - value(std::move(value)) {} - - std::string name; // empty means positional argument - SymbolId nameId = 0; - std::shared_ptr value; - - std::string debug() const { - if (name.empty()) - return value->debug(); - return name + ": " + value->debug(); - } + Arg() = default; + Arg(std::string name, std::shared_ptr value) + : name(std::move(name)), nameId(this->name.empty() ? 0 : symbolIdForName(this->name)), + value(std::move(value)) {} + Arg(std::string displayName, SymbolId directId, std::shared_ptr value) + : name(std::move(displayName)), nameId(directId), value(std::move(value)) {} + + std::string name; // empty means positional argument + SymbolId nameId = 0; + std::shared_ptr value; + + std::string debug() const { + if (name.empty()) return value->debug(); + return name + ": " + value->debug(); + } }; class TermExpr final : public Expr { public: - TermExpr(std::string name, std::vector args, - BuiltinId builtinId = BuiltinId::Unknown, bool capitalized = false) - : name(std::move(name)), nameId(symbolIdForName(this->name)), - builtinId(builtinId), args(std::move(args)), - isCapitalized(capitalized) {} - TermExpr(std::string displayName, SymbolId directId, std::vector args, - BuiltinId builtinId = BuiltinId::Unknown, bool capitalized = false) - : name(std::move(displayName)), nameId(directId), builtinId(builtinId), - args(std::move(args)), isCapitalized(capitalized) {} - - std::string name; - SymbolId nameId = 0; - BuiltinId builtinId = BuiltinId::Unknown; - std::vector args; - bool isCapitalized = false; - - ExprKind kind() const override { return ExprKind::Term; } - std::shared_ptr clone() const override { - std::vector copied; - copied.reserve(args.size()); - for (const auto &arg : args) - copied.emplace_back(arg.name, arg.nameId, arg.value->clone()); - return std::make_shared(name, nameId, std::move(copied), - builtinId, isCapitalized); - } - - std::string debug() const override { - std::ostringstream oss; - oss << name << "("; - for (size_t i = 0; i < args.size(); ++i) { - if (i) - oss << ", "; - oss << args[i].debug(); + TermExpr(std::string name, std::vector args, BuiltinId builtinId = BuiltinId::Unknown, + bool capitalized = false) + : name(std::move(name)), nameId(symbolIdForName(this->name)), + builtinId(builtinId), args(std::move(args)), isCapitalized(capitalized) {} + TermExpr(std::string displayName, SymbolId directId, std::vector args, + BuiltinId builtinId = BuiltinId::Unknown, bool capitalized = false) + : name(std::move(displayName)), nameId(directId), builtinId(builtinId), args(std::move(args)), + isCapitalized(capitalized) {} + + std::string name; + SymbolId nameId = 0; + BuiltinId builtinId = BuiltinId::Unknown; + std::vector args; + bool isCapitalized = false; + + ExprKind kind() const override { return ExprKind::Term; } + std::shared_ptr clone() const override { + std::vector copied; + copied.reserve(args.size()); + for (const auto& arg : args) copied.emplace_back(arg.name, arg.nameId, arg.value->clone()); + return std::make_shared(name, nameId, std::move(copied), builtinId, isCapitalized); + } + + std::string debug() const override { + std::ostringstream oss; + oss << name << "("; + for (size_t i = 0; i < args.size(); ++i) { + if (i) oss << ", "; + oss << args[i].debug(); + } + oss << ")"; + return oss.str(); } - oss << ")"; - return oss.str(); - } }; class LambdaExpr final : public Expr { public: - LambdaExpr(std::shared_ptr source, std::string variable, - std::shared_ptr body, TokenId::Id op = TokenId::UNKNOWN, - std::shared_ptr right = {}) - : source(std::move(source)), variable(std::move(variable)), - variableId(symbolIdForName(this->variable)), body(std::move(body)), - op(op), right(std::move(right)) {} - LambdaExpr(std::shared_ptr source, std::string displayVariable, - SymbolId directVariableId, std::shared_ptr body, - TokenId::Id op = TokenId::UNKNOWN, - std::shared_ptr right = {}) - : source(std::move(source)), variable(std::move(displayVariable)), - variableId(directVariableId), body(std::move(body)), op(op), - right(std::move(right)) {} - - std::shared_ptr source; - std::string variable; - SymbolId variableId = 0; - std::shared_ptr body; - TokenId::Id op; - std::shared_ptr right; - - ExprKind kind() const override { return ExprKind::Lambda; } - std::shared_ptr clone() const override { - return std::make_shared(source->clone(), variable, variableId, - body->clone(), op, - right ? right->clone() : nullptr); - } - - std::string debug() const override { - std::ostringstream oss; - oss << "lambda(" << source->debug() << ", " << variable << " => " - << body->debug(); - if (op != TokenId::UNKNOWN) - oss << " " << builtinTokenSpelling(op) << " " << right->debug(); - oss << ")"; - return oss.str(); - } + LambdaExpr(std::shared_ptr source, + std::string variable, + std::shared_ptr body, + TokenId::Id op = TokenId::UNKNOWN, + std::shared_ptr right = {}) + : source(std::move(source)), variable(std::move(variable)), + variableId(symbolIdForName(this->variable)), body(std::move(body)), + op(std::move(op)), right(std::move(right)) {} + LambdaExpr(std::shared_ptr source, + std::string displayVariable, + SymbolId directVariableId, + std::shared_ptr body, + TokenId::Id op = TokenId::UNKNOWN, + std::shared_ptr right = {}) + : source(std::move(source)), variable(std::move(displayVariable)), + variableId(directVariableId), body(std::move(body)), op(std::move(op)), + right(std::move(right)) {} + + std::shared_ptr source; + std::string variable; + SymbolId variableId = 0; + std::shared_ptr body; + TokenId::Id op; + std::shared_ptr right; + + ExprKind kind() const override { return ExprKind::Lambda; } + std::shared_ptr clone() const override { + return std::make_shared( + source->clone(), variable, variableId, body->clone(), op, + right ? right->clone() : nullptr); + } + + std::string debug() const override { + std::ostringstream oss; + oss << "lambda(" << source->debug() << ", " << variable << " => " << body->debug(); + if (op != TokenId::UNKNOWN) oss << " " << builtinTokenSpelling(op) << " " << right->debug(); + oss << ")"; + return oss.str(); + } }; class Call : public AstNode { public: - std::string name; - SymbolId nameId = 0; - BuiltinId builtinId = BuiltinId::Unknown; - std::vector args; - - Call() = default; - Call(std::string name, std::vector args, - BuiltinId builtinId = BuiltinId::Unknown) - : name(std::move(name)), nameId(symbolIdForName(this->name)), - builtinId(builtinId), args(std::move(args)) {} - Call(std::string displayName, SymbolId directId, std::vector args, - BuiltinId builtinId = BuiltinId::Unknown) - : name(std::move(displayName)), nameId(directId), builtinId(builtinId), - args(std::move(args)) {} - - std::string debug() const override { - std::ostringstream oss; - oss << name << "("; - for (size_t i = 0; i < args.size(); ++i) { - if (i) - oss << ", "; - oss << args[i].debug(); + std::string name; + SymbolId nameId = 0; + BuiltinId builtinId = BuiltinId::Unknown; + std::vector args; + // Query-only semantic designations select existing fact rows. They never + // become serialized fields, types, or inheritance relationships. + std::vector designations; + std::vector designationIds; + + Call() = default; + Call(std::string name, std::vector args, BuiltinId builtinId = BuiltinId::Unknown) + : name(std::move(name)), nameId(symbolIdForName(this->name)), + builtinId(builtinId), args(std::move(args)) {} + Call(std::string displayName, SymbolId directId, std::vector args, + BuiltinId builtinId = BuiltinId::Unknown) + : name(std::move(displayName)), nameId(directId), builtinId(builtinId), args(std::move(args)) {} + + std::string debug() const override { + std::ostringstream oss; + oss << name << "("; + for (size_t i = 0; i < args.size(); ++i) { + if (i) oss << ", "; + oss << args[i].debug(); + } + oss << ")"; + if (!designations.empty()) { + oss << " as "; + for (size_t i = 0; i < designations.size(); ++i) { + if (i) oss << ", "; + oss << designations[i]; + } + } + return oss.str(); } - oss << ")"; - return oss.str(); - } }; class Goal : public AstNode { public: - virtual GoalKind kind() const = 0; - virtual std::shared_ptr clone() const = 0; + virtual GoalKind kind() const = 0; + virtual std::shared_ptr clone() const = 0; }; class CallGoal final : public Goal { public: - explicit CallGoal(Call call) : call(std::move(call)) {} - Call call; - - GoalKind kind() const override { return GoalKind::Call; } - std::shared_ptr clone() const override { - Call copy; - copy.name = call.name; - copy.nameId = call.nameId; - copy.builtinId = call.builtinId; - for (const auto &a : call.args) { - copy.args.emplace_back(a.name, a.nameId, a.value->clone()); + explicit CallGoal(Call call) : call(std::move(call)) {} + Call call; + + GoalKind kind() const override { return GoalKind::Call; } + std::shared_ptr clone() const override { + Call copy; + copy.name = call.name; + copy.nameId = call.nameId; + copy.builtinId = call.builtinId; + copy.designations = call.designations; + copy.designationIds = call.designationIds; + for (const auto& a : call.args) { + copy.args.emplace_back(a.name, a.nameId, a.value->clone()); + } + return std::make_shared(std::move(copy)); } - return std::make_shared(std::move(copy)); - } - std::string debug() const override { return call.debug(); } + std::string debug() const override { return call.debug(); } }; class BinaryGoal final : public Goal { public: - BinaryGoal(std::shared_ptr left, TokenId::Id op, - std::shared_ptr right) - : left(std::move(left)), op(op), right(std::move(right)) {} - - std::shared_ptr left; - TokenId::Id op; - std::shared_ptr right; - - GoalKind kind() const override { return GoalKind::Binary; } - std::shared_ptr clone() const override { - return std::make_shared(left->clone(), op, right->clone()); - } - - std::string debug() const override { - return left->debug() + " " + std::string(builtinTokenSpelling(op)) + " " + - right->debug(); - } + BinaryGoal(std::shared_ptr left, TokenId::Id op, std::shared_ptr right) + : left(std::move(left)), op(std::move(op)), right(std::move(right)) {} + + std::shared_ptr left; + TokenId::Id op; + std::shared_ptr right; + + GoalKind kind() const override { return GoalKind::Binary; } + std::shared_ptr clone() const override { + return std::make_shared(left->clone(), op, right->clone()); + } + + std::string debug() const override { + return left->debug() + " " + std::string(builtinTokenSpelling(op)) + " " + right->debug(); + } }; // Negation-as-failure is intentionally a goal, not an expression operator. @@ -626,532 +661,460 @@ class BinaryGoal final : public Goal { // boolean coercions. class NotGoal final : public Goal { public: - explicit NotGoal(Call call) : call(std::move(call)) {} - Call call; - - GoalKind kind() const override { return GoalKind::Not; } - std::shared_ptr clone() const override { - Call copy; - copy.name = call.name; - copy.nameId = call.nameId; - copy.builtinId = call.builtinId; - for (const auto &arg : call.args) - copy.args.emplace_back(arg.name, arg.nameId, arg.value->clone()); - return std::make_shared(std::move(copy)); - } - std::string debug() const override { return "not " + call.debug(); } + explicit NotGoal(Call call) : call(std::move(call)) {} + Call call; + + GoalKind kind() const override { return GoalKind::Not; } + std::shared_ptr clone() const override { + Call copy; + copy.name = call.name; + copy.nameId = call.nameId; + copy.builtinId = call.builtinId; + for (const auto& arg : call.args) copy.args.emplace_back(arg.name, arg.nameId, arg.value->clone()); + return std::make_shared(std::move(copy)); + } + std::string debug() const override { return "not " + call.debug(); } }; class AssignGoal final : public Goal { public: - AssignGoal(std::string name, std::shared_ptr expr) - : name(std::move(name)), nameId(symbolIdForName(this->name)), - expr(std::move(expr)) {} - AssignGoal(std::string displayName, SymbolId directId, - std::shared_ptr expr) - : name(std::move(displayName)), nameId(directId), expr(std::move(expr)) {} - - std::string name; - SymbolId nameId = 0; - std::shared_ptr expr; - - GoalKind kind() const override { return GoalKind::Assign; } - std::shared_ptr clone() const override { - if (!expr) - return std::make_shared(name, nameId, - std::shared_ptr{}); - return std::make_shared(name, nameId, expr->clone()); - } - - std::string debug() const override { - return name + " := " + (expr ? expr->debug() : ""); - } + AssignGoal(std::string name, std::shared_ptr expr) + : name(std::move(name)), nameId(symbolIdForName(this->name)), expr(std::move(expr)) {} + AssignGoal(std::string displayName, SymbolId directId, std::shared_ptr expr) + : name(std::move(displayName)), nameId(directId), expr(std::move(expr)) {} + + std::string name; + SymbolId nameId = 0; + std::shared_ptr expr; + + GoalKind kind() const override { return GoalKind::Assign; } + std::shared_ptr clone() const override { + if (!expr) return std::make_shared(name, nameId, std::shared_ptr{}); + return std::make_shared(name, nameId, expr->clone()); + } + + std::string debug() const override { + return name + " := " + (expr ? expr->debug() : ""); + } }; struct AssignmentTarget { - std::string name; - SymbolId nameId = 0; - std::string type; - - AssignmentTarget(std::string name, std::string type = {}) - : name(std::move(name)), nameId(symbolIdForName(this->name)), - type(std::move(type)) {} - AssignmentTarget(std::string displayName, SymbolId directId, - std::string type = {}) - : name(std::move(displayName)), nameId(directId), type(std::move(type)) {} - - std::string debug() const { return type.empty() ? name : name + ": " + type; } + std::string name; + SymbolId nameId = 0; + std::string type; + + AssignmentTarget(std::string name, std::string type = {}) + : name(std::move(name)), nameId(symbolIdForName(this->name)), type(std::move(type)) {} + AssignmentTarget(std::string displayName, SymbolId directId, std::string type = {}) + : name(std::move(displayName)), nameId(directId), type(std::move(type)) {} + + std::string debug() const { + return type.empty() ? name : name + ": " + type; + } }; class MultiAssignGoal final : public Goal { public: - MultiAssignGoal(std::vector targets, - std::shared_ptr expr) - : targets(std::move(targets)), expr(std::move(expr)) {} - - std::vector targets; - std::shared_ptr expr; - - GoalKind kind() const override { return GoalKind::MultiAssign; } - std::shared_ptr clone() const override { - return std::make_shared(targets, expr->clone()); - } - - std::string debug() const override { - std::ostringstream oss; - for (size_t i = 0; i < targets.size(); ++i) { - if (i) - oss << ", "; - oss << targets[i].debug(); + MultiAssignGoal(std::vector targets, std::shared_ptr expr) + : targets(std::move(targets)), expr(std::move(expr)) {} + + std::vector targets; + std::shared_ptr expr; + + GoalKind kind() const override { return GoalKind::MultiAssign; } + std::shared_ptr clone() const override { + return std::make_shared(targets, expr->clone()); + } + + std::string debug() const override { + std::ostringstream oss; + for (size_t i = 0; i < targets.size(); ++i) { + if (i) oss << ", "; + oss << targets[i].debug(); + } + oss << " := " << expr->debug(); + return oss.str(); } - oss << " := " << expr->debug(); - return oss.str(); - } }; class WhereGoal final : public Goal { public: - explicit WhereGoal(std::shared_ptr condition) - : condition(std::move(condition)) {} + explicit WhereGoal(std::shared_ptr condition) + : condition(std::move(condition)) {} - std::shared_ptr condition; + std::shared_ptr condition; - GoalKind kind() const override { return GoalKind::Where; } - std::shared_ptr clone() const override { - return std::make_shared(condition->clone()); - } + GoalKind kind() const override { return GoalKind::Where; } + std::shared_ptr clone() const override { + return std::make_shared(condition->clone()); + } - std::string debug() const override { return "where " + condition->debug(); } + std::string debug() const override { return "where " + condition->debug(); } }; class IfGoal final : public Goal { public: - IfGoal(std::shared_ptr condition, - std::vector> thenBranch, - std::vector> elseBranch) - : condition(std::move(condition)), thenBranch(std::move(thenBranch)), - elseBranch(std::move(elseBranch)) {} - - std::shared_ptr condition; - std::vector> thenBranch; - std::vector> elseBranch; - - GoalKind kind() const override { return GoalKind::If; } - std::shared_ptr clone() const override { - std::vector> copiedThen; - copiedThen.reserve(thenBranch.size()); - for (const auto &goal : thenBranch) - copiedThen.push_back(goal->clone()); - std::vector> copiedElse; - copiedElse.reserve(elseBranch.size()); - for (const auto &goal : elseBranch) - copiedElse.push_back(goal->clone()); - return std::make_shared(condition->clone(), std::move(copiedThen), - std::move(copiedElse)); - } - - std::string debug() const override { - std::ostringstream oss; - oss << "if " << condition->debug() << ", "; - for (size_t i = 0; i < thenBranch.size(); ++i) { - if (i) - oss << ", "; - oss << thenBranch[i]->debug(); + IfGoal(std::shared_ptr condition, + std::vector> thenBranch, + std::vector> elseBranch) + : condition(std::move(condition)), thenBranch(std::move(thenBranch)), elseBranch(std::move(elseBranch)) {} + + std::shared_ptr condition; + std::vector> thenBranch; + std::vector> elseBranch; + + GoalKind kind() const override { return GoalKind::If; } + std::shared_ptr clone() const override { + std::vector> copiedThen; + copiedThen.reserve(thenBranch.size()); + for (const auto& goal : thenBranch) copiedThen.push_back(goal->clone()); + std::vector> copiedElse; + copiedElse.reserve(elseBranch.size()); + for (const auto& goal : elseBranch) copiedElse.push_back(goal->clone()); + return std::make_shared(condition->clone(), std::move(copiedThen), std::move(copiedElse)); } - if (!elseBranch.empty()) { - oss << " else "; - for (size_t i = 0; i < elseBranch.size(); ++i) { - if (i) - oss << ", "; - oss << elseBranch[i]->debug(); - } + + std::string debug() const override { + std::ostringstream oss; + oss << "if " << condition->debug() << ", "; + for (size_t i = 0; i < thenBranch.size(); ++i) { + if (i) oss << ", "; + oss << thenBranch[i]->debug(); + } + if (!elseBranch.empty()) { + oss << " else "; + for (size_t i = 0; i < elseBranch.size(); ++i) { + if (i) oss << ", "; + oss << elseBranch[i]->debug(); + } + } + return oss.str(); } - return oss.str(); - } }; class ReturnGoal final : public Goal { public: - explicit ReturnGoal(std::vector fields) : fields(std::move(fields)) {} - - std::vector fields; - - GoalKind kind() const override { return GoalKind::Return; } - std::shared_ptr clone() const override { - std::vector copied; - copied.reserve(fields.size()); - for (const auto &field : fields) - copied.emplace_back(field.name, field.nameId, field.value->clone()); - return std::make_shared(std::move(copied)); - } - - std::string debug() const override { - std::ostringstream oss; - oss << "return ("; - for (size_t i = 0; i < fields.size(); ++i) { - if (i) - oss << ", "; - oss << fields[i].debug(); + explicit ReturnGoal(std::vector fields) : fields(std::move(fields)) {} + + std::vector fields; + + GoalKind kind() const override { return GoalKind::Return; } + std::shared_ptr clone() const override { + std::vector copied; + copied.reserve(fields.size()); + for (const auto& field : fields) copied.emplace_back(field.name, field.nameId, field.value->clone()); + return std::make_shared(std::move(copied)); + } + + std::string debug() const override { + std::ostringstream oss; + oss << "return ("; + for (size_t i = 0; i < fields.size(); ++i) { + if (i) oss << ", "; + oss << fields[i].debug(); + } + oss << ")"; + return oss.str(); } - oss << ")"; - return oss.str(); - } }; class GroupGoal final : public Goal { public: - explicit GroupGoal(std::vector> goals) - : goals(std::move(goals)) {} - - std::vector> goals; - - GoalKind kind() const override { return GoalKind::Group; } - std::shared_ptr clone() const override { - std::vector> copied; - copied.reserve(goals.size()); - for (const auto &goal : goals) - copied.push_back(goal->clone()); - return std::make_shared(std::move(copied)); - } - - std::string debug() const override { - std::ostringstream oss; - oss << "("; - for (size_t i = 0; i < goals.size(); ++i) { - if (i) - oss << ", "; - oss << goals[i]->debug(); + explicit GroupGoal(std::vector> goals) + : goals(std::move(goals)) {} + + std::vector> goals; + + GoalKind kind() const override { return GoalKind::Group; } + std::shared_ptr clone() const override { + std::vector> copied; + copied.reserve(goals.size()); + for (const auto& goal : goals) copied.push_back(goal->clone()); + return std::make_shared(std::move(copied)); + } + + std::string debug() const override { + std::ostringstream oss; + oss << "("; + for (size_t i = 0; i < goals.size(); ++i) { + if (i) oss << ", "; + oss << goals[i]->debug(); + } + oss << ")"; + return oss.str(); } - oss << ")"; - return oss.str(); - } }; class OrGoal final : public Goal { public: - explicit OrGoal(std::vector>> branches) - : branches(std::move(branches)) {} - - std::vector>> branches; - - GoalKind kind() const override { return GoalKind::Or; } - std::shared_ptr clone() const override { - std::vector>> copied; - copied.reserve(branches.size()); - for (const auto &branch : branches) { - std::vector> copiedBranch; - copiedBranch.reserve(branch.size()); - for (const auto &goal : branch) - copiedBranch.push_back(goal->clone()); - copied.push_back(std::move(copiedBranch)); + explicit OrGoal(std::vector>> branches) + : branches(std::move(branches)) {} + + std::vector>> branches; + + GoalKind kind() const override { return GoalKind::Or; } + std::shared_ptr clone() const override { + std::vector>> copied; + copied.reserve(branches.size()); + for (const auto& branch : branches) { + std::vector> copiedBranch; + copiedBranch.reserve(branch.size()); + for (const auto& goal : branch) copiedBranch.push_back(goal->clone()); + copied.push_back(std::move(copiedBranch)); + } + return std::make_shared(std::move(copied)); } - return std::make_shared(std::move(copied)); - } - - std::string debug() const override { - std::ostringstream oss; - for (size_t i = 0; i < branches.size(); ++i) { - if (i) - oss << " | "; - for (size_t j = 0; j < branches[i].size(); ++j) { - if (j) - oss << ", "; - oss << branches[i][j]->debug(); - } + + std::string debug() const override { + std::ostringstream oss; + for (size_t i = 0; i < branches.size(); ++i) { + if (i) oss << " | "; + for (size_t j = 0; j < branches[i].size(); ++j) { + if (j) oss << ", "; + oss << branches[i][j]->debug(); + } + } + return oss.str(); } - return oss.str(); - } }; class Statement : public AstNode { public: - virtual ~Statement() = default; - virtual StatementKind kind() const = 0; + virtual ~Statement() = default; + virtual StatementKind kind() const = 0; }; class ImportStmt final : public Statement { public: - explicit ImportStmt(std::string path) { paths.push_back(std::move(path)); } - explicit ImportStmt(std::vector paths) - : paths(std::move(paths)) {} - std::vector paths; - - StatementKind kind() const override { return StatementKind::Import; } - std::string debug() const override { - std::ostringstream oss; - oss << "import "; - if (paths.size() == 1) { - oss << '"' << paths[0] << '"'; - } else { - oss << "("; - for (size_t i = 0; i < paths.size(); ++i) { - if (i) - oss << " "; - oss << '"' << paths[i] << '"'; - } - oss << ")"; + explicit ImportStmt(std::string path) { paths.push_back(std::move(path)); } + explicit ImportStmt(std::vector paths) : paths(std::move(paths)) {} + std::vector paths; + + StatementKind kind() const override { return StatementKind::Import; } + std::string debug() const override { + std::ostringstream oss; + oss << "import "; + if (paths.size() == 1) { + oss << '"' << paths[0] << '"'; + } else { + oss << "("; + for (size_t i = 0; i < paths.size(); ++i) { + if (i) oss << " "; + oss << '"' << paths[i] << '"'; + } + oss << ")"; + } + oss << "."; + return oss.str(); } - oss << "."; - return oss.str(); - } }; class ClauseStmt final : public Statement { public: - ClauseStmt(Call head, std::vector> body) - : head(std::move(head)), body(std::move(body)), - clauseKind(this->body.empty() ? ClauseKind::Fact : ClauseKind::Rule) {} - ClauseStmt(Call head, std::string parentName, - std::vector> body) - : head(std::move(head)), parentName(std::move(parentName)), - body(std::move(body)), - clauseKind(this->body.empty() ? ClauseKind::Fact : ClauseKind::Rule) { - if (!this->parentName.empty()) - parentNames.push_back(this->parentName); - } - ClauseStmt(Call head, std::string parentName, - std::vector> body, - std::vector>> fallbackBranches, - bool emptyDeclaration = false, - ClauseKind clauseKind = ClauseKind::Rule) - : head(std::move(head)), parentName(std::move(parentName)), - body(std::move(body)), fallbackBranches(std::move(fallbackBranches)), - emptyDeclaration(emptyDeclaration), clauseKind(clauseKind) { - if (!this->parentName.empty()) - parentNames.push_back(this->parentName); - } - ClauseStmt(Call head, std::vector parentNames, - std::vector> body, - std::vector>> fallbackBranches, - bool emptyDeclaration = false, - ClauseKind clauseKind = ClauseKind::Rule) - : head(std::move(head)), parentNames(std::move(parentNames)), - body(std::move(body)), fallbackBranches(std::move(fallbackBranches)), - emptyDeclaration(emptyDeclaration), clauseKind(clauseKind) { - if (!this->parentNames.empty()) - parentName = this->parentNames.front(); - } - - Call head; - // parentName is retained as the primary-parent compatibility view. All - // hierarchy traversal uses parentNames, which preserves every declared - // direct parent in source order. - std::string parentName; - std::vector parentNames; - std::vector> - body; // empty body without => () means fact - std::vector>> fallbackBranches; - bool emptyDeclaration = false; - ClauseKind clauseKind = ClauseKind::Rule; - std::string module; - // Non-empty only for a fact row linked from a fact-only .fx database. - // Compiler lowering carries these already-encoded path pieces into - // MakeFact; the AST itself remains compiler-only and the VM never parses a - // source file to recover ownership. - std::shared_ptr> persistenceSource; - // An annotation is a normal method application evaluated against this - // declaration. Built-in annotations and user annotations share this AST. - std::vector annotations; - - StatementKind kind() const override { return StatementKind::Clause; } - bool isFact() const { return clauseKind == ClauseKind::Fact; } - - std::string debug() const override { - std::ostringstream oss; - for (const auto &annotation : annotations) { - oss << "@" << annotation.debug() << "\n"; + ClauseStmt(Call head, std::vector> body) + : head(std::move(head)), body(std::move(body)), + clauseKind(this->body.empty() ? ClauseKind::Fact : ClauseKind::Rule) {} + ClauseStmt(Call head, std::string parentName, std::vector> body) + : head(std::move(head)), parentName(std::move(parentName)), body(std::move(body)), + clauseKind(this->body.empty() ? ClauseKind::Fact : ClauseKind::Rule) { + if (!this->parentName.empty()) parentNames.push_back(this->parentName); + } + ClauseStmt(Call head, + std::string parentName, + std::vector> body, + std::vector>> fallbackBranches, + bool emptyDeclaration = false, + ClauseKind clauseKind = ClauseKind::Rule) + : head(std::move(head)), parentName(std::move(parentName)), body(std::move(body)), + fallbackBranches(std::move(fallbackBranches)), emptyDeclaration(emptyDeclaration), + clauseKind(clauseKind) { + if (!this->parentName.empty()) parentNames.push_back(this->parentName); } - oss << head.name; - if (!parentNames.empty()) { - oss << " extend "; - for (size_t i = 0; i < parentNames.size(); ++i) { - if (i) - oss << ", "; - oss << parentNames[i]; - } - } else if (!parentName.empty()) - oss << " extend " << parentName; - oss << "("; - for (size_t i = 0; i < head.args.size(); ++i) { - if (i) - oss << ", "; - oss << head.args[i].debug(); + ClauseStmt(Call head, + std::vector parentNames, + std::vector> body, + std::vector>> fallbackBranches, + bool emptyDeclaration = false, + ClauseKind clauseKind = ClauseKind::Rule) + : head(std::move(head)), parentNames(std::move(parentNames)), body(std::move(body)), + fallbackBranches(std::move(fallbackBranches)), emptyDeclaration(emptyDeclaration), + clauseKind(clauseKind) { + if (!this->parentNames.empty()) parentName = this->parentNames.front(); } - oss << ")"; - if (emptyDeclaration) { - oss << " => ()"; - } else if (!body.empty()) { - oss << " => "; - for (size_t i = 0; i < body.size(); ++i) { - if (i) - oss << ", "; - oss << body[i]->debug(); - } - for (const auto &branch : fallbackBranches) { - oss << " else "; - for (size_t i = 0; i < branch.size(); ++i) { - if (i) - oss << ", "; - oss << branch[i]->debug(); + + Call head; + // parentName is retained as the primary-parent compatibility view. All + // hierarchy traversal uses parentNames, which preserves every declared + // direct parent in source order. + std::string parentName; + std::vector parentNames; + // Semantic designations are fact-instance metadata. They are neither + // schema fields nor inheritance edges. + std::vector designations; + std::vector designationIds; + std::vector> body; // empty body without => () means fact + std::vector>> fallbackBranches; + bool emptyDeclaration = false; + ClauseKind clauseKind = ClauseKind::Rule; + std::string module; + // An annotation is a normal method application evaluated against this + // declaration. Built-in annotations and user annotations share this AST. + std::vector annotations; + + StatementKind kind() const override { return StatementKind::Clause; } + bool isFact() const { return clauseKind == ClauseKind::Fact; } + + std::string debug() const override { + std::ostringstream oss; + for (const auto& annotation : annotations) { + oss << "@" << annotation.debug() << "\n"; + } + oss << head.name; + if (!parentNames.empty()) { + oss << " extend "; + for (size_t i = 0; i < parentNames.size(); ++i) { + if (i) oss << ", "; + oss << parentNames[i]; + } + } else if (!parentName.empty()) oss << " extend " << parentName; + oss << "("; + for (size_t i = 0; i < head.args.size(); ++i) { + if (i) oss << ", "; + oss << head.args[i].debug(); + } + oss << ")"; + if (!designations.empty()) { + oss << " as "; + for (size_t i = 0; i < designations.size(); ++i) { + if (i) oss << ", "; + oss << designations[i]; + } } - } + if (emptyDeclaration) { + oss << " => ()"; + } else if (!body.empty()) { + oss << " => "; + for (size_t i = 0; i < body.size(); ++i) { + if (i) oss << ", "; + oss << body[i]->debug(); + } + for (const auto& branch : fallbackBranches) { + oss << " else "; + for (size_t i = 0; i < branch.size(); ++i) { + if (i) oss << ", "; + oss << branch[i]->debug(); + } + } + } + oss << "."; + return oss.str(); } - oss << "."; - return oss.str(); - } }; class GlobalBindingStmt final : public Statement { public: - GlobalBindingStmt(std::string name, std::shared_ptr expr) - : name(std::move(name)), expr(std::move(expr)) {} + GlobalBindingStmt(std::string name, std::shared_ptr expr) + : name(std::move(name)), expr(std::move(expr)) {} - std::string name; - std::shared_ptr expr; + std::string name; + std::shared_ptr expr; - StatementKind kind() const override { return StatementKind::GlobalBinding; } - std::string debug() const override { - return name + " := " + expr->debug() + "."; - } + StatementKind kind() const override { return StatementKind::GlobalBinding; } + std::string debug() const override { + return name + " := " + expr->debug() + "."; + } }; struct ClassFieldDecl { - std::string name; - SymbolId nameId = 0; - std::string typeName; - SourceSpan sourceSpan; + std::string name; + SymbolId nameId = 0; + std::string typeName; + SourceSpan sourceSpan; }; struct ClassIndexDecl { - std::vector fields; - std::vector fieldIds; - SourceSpan sourceSpan; + std::vector fields; + std::vector fieldIds; + SourceSpan sourceSpan; }; -// Compiler-only fact schema. It lowers into the existing IrFactType table; -// RegisterVm never receives or interprets this syntax-shaped declaration. +// A schema remains source-level AST. The direct interpreter registers its +// inheritance and the contained methods without an IR or binary conversion. class ClassStmt final : public Statement { public: - ClassStmt(std::string name, SymbolId nameId, - std::vector parentNames, - std::vector fields, - std::vector indexes = {}, - std::vector> methods = {}) - : name(std::move(name)), nameId(nameId), - parentNames(std::move(parentNames)), fields(std::move(fields)), - indexes(std::move(indexes)), - methods(std::move(methods)) {} - - std::string name; - SymbolId nameId = 0; - std::vector parentNames; - std::vector fields; - std::vector indexes; - std::vector> methods; - - StatementKind kind() const override { return StatementKind::Class; } - std::string debug() const override { - std::ostringstream oss; - oss << "class " << name; - if (!parentNames.empty()) { - oss << " extend "; - for (std::size_t i = 0; i < parentNames.size(); ++i) { - if (i) - oss << ", "; - oss << parentNames[i]; - } - } - oss << '\n'; - for (const auto &field : fields) - oss << " " << field.name << ": " << field.typeName << '\n'; - for (const auto &index : indexes) { - oss << " index("; - for (std::size_t i = 0; i < index.fields.size(); ++i) { - if (i) - oss << ", "; - oss << index.fields[i]; - } - oss << ")\n"; + ClassStmt(std::string name, SymbolId nameId, + std::vector parentNames, + std::vector fields, + std::vector indexes = {}, + std::vector> methods = {}) + : name(std::move(name)), nameId(nameId), + parentNames(std::move(parentNames)), fields(std::move(fields)), + indexes(std::move(indexes)), methods(std::move(methods)) {} + + std::string name; + SymbolId nameId = 0; + std::vector parentNames; + std::vector fields; + std::vector indexes; + std::vector> methods; + + StatementKind kind() const override { return StatementKind::Class; } + std::string debug() const override { + std::ostringstream oss; + oss << "class " << name; + if (!parentNames.empty()) { + oss << " extend "; + for (std::size_t i = 0; i < parentNames.size(); ++i) { + if (i) oss << ", "; + oss << parentNames[i]; + } + } + oss << '\n'; + for (const auto& field : fields) oss << " " << field.name << ": " << field.typeName << '\n'; + for (const auto& index : indexes) { + oss << " index("; + for (std::size_t i = 0; i < index.fields.size(); ++i) { + if (i) oss << ", "; + oss << index.fields[i]; + } + oss << ")\n"; + } + for (const auto& method : methods) oss << " " << method->debug() << '\n'; + return oss.str() + "end"; } - for (const auto &method : methods) - oss << " " << method->debug() << '\n'; - oss << "end"; - return oss.str(); - } }; class Program final : public AstNode { public: - std::vector> statements; - std::vector> imports; - std::vector> clauses; - std::vector> globals; - std::vector> classes; - - void addStatement(std::shared_ptr statement) { - switch (statement->kind()) { - case StatementKind::Import: - imports.push_back(std::static_pointer_cast(statement)); - break; - case StatementKind::Clause: - clauses.push_back(std::static_pointer_cast(statement)); - break; - case StatementKind::GlobalBinding: - globals.push_back(std::static_pointer_cast(statement)); - break; - case StatementKind::Class: - classes.push_back(std::static_pointer_cast(statement)); - for (const auto &method : classes.back()->methods) - clauses.push_back(method); - break; + std::vector> statements; + std::vector> imports; + std::vector> clauses; + std::vector> globals; + std::vector> classes; + + void addStatement(std::shared_ptr statement) { + switch (statement->kind()) { + case StatementKind::Import: + imports.push_back(std::static_pointer_cast(statement)); + break; + case StatementKind::Clause: + clauses.push_back(std::static_pointer_cast(statement)); + break; + case StatementKind::GlobalBinding: + globals.push_back(std::static_pointer_cast(statement)); + break; + case StatementKind::Class: + classes.push_back(std::static_pointer_cast(statement)); + for (const auto& method : classes.back()->methods) clauses.push_back(method); + break; + } + statements.push_back(std::move(statement)); } - statements.push_back(std::move(statement)); - } - - std::string debug() const override { - std::ostringstream oss; - for (const auto &s : statements) - oss << s->debug() << "\n"; - return oss.str(); - } -}; -// Non-fatal or fatal diagnostic about a span of source, in the same -// severity/code/message shape felidae_debug (src/debugger/AstAnalyzer.h) -// has used since its rewrite. Shared here so the compiler can report -// warnings without either linking the debugger's analyzer or hand-rolling a -// second diagnostic struct of its own; felidae_debug still owns the fuller -// analyses (unused symbols, hidden materialization, etc.) that produce -// AstDiagnostic values, this is just the shared value type and the two -// small constructors every diagnostic emitter otherwise repeats. -struct AstDiagnostic { - std::string severity; - std::string message; - int line = 1; - int column = 1; - int endLine = 1; - int endColumn = 1; - std::string code; - std::string file; + std::string debug() const override { + std::ostringstream oss; + for (const auto& s : statements) oss << s->debug() << "\n"; + return oss.str(); + } }; -inline AstDiagnostic diagnosticFor(const AstNode *node, std::string severity, - std::string code, std::string message) { - SourceSpan span; - if (node && node->sourceSpan.valid()) - span = node->sourceSpan; - return AstDiagnostic{std::move(severity), std::move(message), - span.startLine, span.startColumn, - span.endLine, span.endColumn, - std::move(code), ""}; -} - -inline AstDiagnostic diagnosticForSpan(const SourceSpan &span, - std::string severity, std::string code, - std::string message) { - return AstDiagnostic{std::move(severity), std::move(message), - span.startLine, span.startColumn, - span.endLine, span.endColumn, - std::move(code), ""}; -} - } // namespace Felidae diff --git a/src/BuiltinRegistry.cpp b/src/BuiltinRegistry.cpp index af68e1c..ff53e2f 100644 --- a/src/BuiltinRegistry.cpp +++ b/src/BuiltinRegistry.cpp @@ -1,344 +1,244 @@ #include "BuiltinRegistry.h" -#include "SentencePieceModel.h" - -#include -#include #include -#include -#include -#include #include namespace Felidae { namespace { -constexpr std::array kBuiltinModules{ - "json", "csv", "group", "set", "ml", "array", "math", "str", "file", - "system"}; - constexpr BuiltinInfo kBuiltinInfos[] = { - {BuiltinId::Unknown, "", BuiltinEffect::Volatile}, - {BuiltinId::Throw, "throw", BuiltinEffect::WritesExternalState}, - {BuiltinId::Type, "type", BuiltinEffect::Pure}, - {BuiltinId::Instanceof, "instanceof", BuiltinEffect::Pure}, - {BuiltinId::Count, "count", BuiltinEffect::Pure}, - {BuiltinId::Sum, "sum", BuiltinEffect::Pure}, - {BuiltinId::Average, "average", BuiltinEffect::Pure}, - {BuiltinId::Min, "min", BuiltinEffect::Pure}, - {BuiltinId::Max, "max", BuiltinEffect::Pure}, - {BuiltinId::Sort, "sort", BuiltinEffect::Pure}, - {BuiltinId::Search, "search", BuiltinEffect::Pure}, - {BuiltinId::Contains, "contains", BuiltinEffect::Pure}, - {BuiltinId::Lower, "lower", BuiltinEffect::Pure}, - {BuiltinId::Upper, "upper", BuiltinEffect::Pure}, - {BuiltinId::Length, "length", BuiltinEffect::Pure}, - {BuiltinId::ParseDoc, "ParseDoc", BuiltinEffect::Pure}, - {BuiltinId::StrLen, "str:len", BuiltinEffect::Pure}, - {BuiltinId::StrContains, "str:contains", BuiltinEffect::Pure}, - {BuiltinId::StrConcat, "str:concat", BuiltinEffect::Pure}, - {BuiltinId::StrJoin, "str:join", BuiltinEffect::Pure}, - {BuiltinId::StrLower, "str:lower", BuiltinEffect::Pure}, - {BuiltinId::StrUpper, "str:upper", BuiltinEffect::Pure}, - {BuiltinId::StrTrim, "str:trim", BuiltinEffect::Pure}, - {BuiltinId::StrSplit, "str:split", BuiltinEffect::Pure}, - {BuiltinId::StrReplace, "str:replace", BuiltinEffect::Pure}, - {BuiltinId::StrStartsWith, "str:startsWith", BuiltinEffect::Pure}, - {BuiltinId::StrEndsWith, "str:endsWith", BuiltinEffect::Pure}, - {BuiltinId::ArrayGet, "array:get", BuiltinEffect::Pure}, - {BuiltinId::ArrayLen, "array:len", BuiltinEffect::Pure}, - {BuiltinId::ArrayPush, "array:push", BuiltinEffect::Pure}, - {BuiltinId::FnArray, "fn:array", BuiltinEffect::Pure}, - {BuiltinId::FnPair, "fn:pair", BuiltinEffect::Pure}, - {BuiltinId::FnTuple, "fn:tuple", BuiltinEffect::Pure}, - {BuiltinId::PairFirst, "pair:first", BuiltinEffect::Pure}, - {BuiltinId::PairSecond, "pair:second", BuiltinEffect::Pure}, - {BuiltinId::ConsoleReadLine, "console:readLine", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::ConsoleInput, "console:input", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::ConsoleInputNumber, "console:inputNumber", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::ConsoleWriteLine, "console:writeLine", - BuiltinEffect::WritesExternalState}, - {BuiltinId::ConsoleWrite, "console:write", - BuiltinEffect::WritesExternalState}, - {BuiltinId::SystemPrint, "system:print", - BuiltinEffect::WritesExternalState}, - {BuiltinId::SystemPrintf, "system:printf", - BuiltinEffect::WritesExternalState}, - {BuiltinId::SystemRun, "system:run", BuiltinEffect::Volatile}, - {BuiltinId::FileReadFile, "file:readFile", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::FileReadLines, "file:readLines", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::FileReadLine, "file:readLine", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::FileWriteFile, "file:writeFile", - BuiltinEffect::WritesExternalState}, - {BuiltinId::FileWriteLines, "file:writeLines", - BuiltinEffect::WritesExternalState}, - {BuiltinId::FileAppendFile, "file:appendFile", - BuiltinEffect::WritesExternalState}, - {BuiltinId::FileExists, "file:exists", BuiltinEffect::ReadsExternalState}, - {BuiltinId::FileDeleteFile, "file:deleteFile", - BuiltinEffect::WritesExternalState}, - {BuiltinId::CommonAncestors, "commonAncestors", BuiltinEffect::Pure}, - {BuiltinId::AncestorAnalysis, "ancestorAnalysis", BuiltinEffect::Pure}, - // Mutates the fact store (see the RegisterVm.cpp dispatch case) -- - // WritesExternalState because it mutates the retained fact store. - {BuiltinId::PropagateFact, "propagateFact", - BuiltinEffect::WritesExternalState}, - {BuiltinId::JsonObject, "json:object", BuiltinEffect::Pure}, - {BuiltinId::JsonParse, "json:parse", BuiltinEffect::Pure}, - {BuiltinId::JsonGet, "json:get", BuiltinEffect::Pure}, - {BuiltinId::JsonHas, "json:has", BuiltinEffect::Pure}, - {BuiltinId::JsonKeys, "json:keys", BuiltinEffect::Pure}, - {BuiltinId::JsonSet, "json:set", BuiltinEffect::Pure}, - {BuiltinId::JsonRemove, "json:remove", BuiltinEffect::Pure}, - {BuiltinId::JsonToText, "json:toText", BuiltinEffect::Pure}, - {BuiltinId::VisualizeGraphJson, "visualize:graphJson", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::ThreadCreateThread, "thread:createThread", - BuiltinEffect::WritesExternalState}, - {BuiltinId::ThreadStart, "thread:start", - BuiltinEffect::WritesExternalState}, - {BuiltinId::ThreadPause, "thread:pause", - BuiltinEffect::WritesExternalState}, - {BuiltinId::ThreadStop, "thread:stop", BuiltinEffect::WritesExternalState}, - {BuiltinId::ThreadStatus, "thread:status", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::ThreadResult, "thread:result", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::MathPi, "math:pi", BuiltinEffect::Pure}, - {BuiltinId::MathE, "math:e", BuiltinEffect::Pure}, - {BuiltinId::MathRandom, "math:random", BuiltinEffect::Volatile}, - {BuiltinId::MathPow, "math:pow", BuiltinEffect::Pure}, - {BuiltinId::MathAtan2, "math:atan2", BuiltinEffect::Pure}, - {BuiltinId::MathSqrt, "math:sqrt", BuiltinEffect::Pure}, - {BuiltinId::MathSin, "math:sin", BuiltinEffect::Pure}, - {BuiltinId::MathCos, "math:cos", BuiltinEffect::Pure}, - {BuiltinId::MathTan, "math:tan", BuiltinEffect::Pure}, - {BuiltinId::MathAsin, "math:asin", BuiltinEffect::Pure}, - {BuiltinId::MathAcos, "math:acos", BuiltinEffect::Pure}, - {BuiltinId::MathAtan, "math:atan", BuiltinEffect::Pure}, - {BuiltinId::MathLog, "math:log", BuiltinEffect::Pure}, - {BuiltinId::MathLog10, "math:log10", BuiltinEffect::Pure}, - {BuiltinId::MathExp, "math:exp", BuiltinEffect::Pure}, - {BuiltinId::MathAbs, "math:abs", BuiltinEffect::Pure}, - {BuiltinId::MathFloor, "math:floor", BuiltinEffect::Pure}, - {BuiltinId::MathCeil, "math:ceil", BuiltinEffect::Pure}, - {BuiltinId::MathRound, "math:round", BuiltinEffect::Pure}, - {BuiltinId::MathAdd, "math:add", BuiltinEffect::Pure}, - {BuiltinId::MathSub, "math:sub", BuiltinEffect::Pure}, - {BuiltinId::MathMul, "math:mul", BuiltinEffect::Pure}, - {BuiltinId::MathDiv, "math:div", BuiltinEffect::Pure}, - {BuiltinId::MathMod, "math:mod", BuiltinEffect::Pure}, - {BuiltinId::ReasoningContrary, "Reasoning:contrary", - BuiltinEffect::WritesExternalState}, - {BuiltinId::ReasoningProve, "Reasoning:prove", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::ReasoningGrade, "Reasoning:grade", BuiltinEffect::Pure}, - {BuiltinId::ReasoningDecide, "Reasoning:decide", - BuiltinEffect::ReadsExternalState}, - {BuiltinId::MlSigmoid, "ml:sigmoid", BuiltinEffect::Pure}, - {BuiltinId::MlRelu, "ml:relu", BuiltinEffect::Pure}, - {BuiltinId::MlDot, "ml:dot", BuiltinEffect::Pure}, - {BuiltinId::MlMeanSquaredError, "ml:meanSquaredError", BuiltinEffect::Pure}, - {BuiltinId::OverloadAnnotation, "overload", BuiltinEffect::Pure}, - {BuiltinId::MatcherAnnotation, "matcher", BuiltinEffect::Pure}, - {BuiltinId::MixfixAnnotation, "mixfix", BuiltinEffect::Pure}, - {BuiltinId::CsvParse, "csv:parse", BuiltinEffect::Pure}, - {BuiltinId::CsvToFacts, "csv:toFacts", BuiltinEffect::Pure}, - {BuiltinId::CsvToText, "csv:toText", BuiltinEffect::Pure}, - {BuiltinId::CsvToFelidaeFacts, "csv:toFelidaeFacts", BuiltinEffect::Pure}, - {BuiltinId::GroupValidate, "Group:validate", BuiltinEffect::Pure}, - {BuiltinId::GroupClosed, "Group:closed", BuiltinEffect::Pure}, - {BuiltinId::GroupAssociative, "Group:associative", BuiltinEffect::Pure}, - {BuiltinId::GroupIdentity, "Group:identity", BuiltinEffect::Pure}, - {BuiltinId::GroupInverse, "Group:inverse", BuiltinEffect::Pure}, - {BuiltinId::GroupCommutative, "Group:commutative", BuiltinEffect::Pure}, - {BuiltinId::GroupAbelian, "Group:abelian", BuiltinEffect::Pure}, - {BuiltinId::SetUnion, "Set:union", BuiltinEffect::Pure}, - {BuiltinId::SetIntersection, "Set:intersection", BuiltinEffect::Pure}, - {BuiltinId::SetIntersectionBy, "Set:intersectionBy", BuiltinEffect::Pure}, - {BuiltinId::SetDifference, "Set:difference", BuiltinEffect::Pure}, - {BuiltinId::SetDifferenceBy, "Set:differenceBy", BuiltinEffect::Pure}, - {BuiltinId::SetSymmetricDifference, "Set:symmetricDifference", - BuiltinEffect::Pure}, - {BuiltinId::SetSymmetricDifferenceBy, "Set:symmetricDifferenceBy", - BuiltinEffect::Pure}, - {BuiltinId::SetEquals, "Set:equals", BuiltinEffect::Pure}, - {BuiltinId::SetEqualsBy, "Set:equalsBy", BuiltinEffect::Pure}, - {BuiltinId::SetSubset, "Set:subset", BuiltinEffect::Pure}, - {BuiltinId::SetSubsetBy, "Set:subsetBy", BuiltinEffect::Pure}, - {BuiltinId::SetSuperset, "Set:superset", BuiltinEffect::Pure}, - {BuiltinId::SetDisjoint, "Set:disjoint", BuiltinEffect::Pure}, - {BuiltinId::SetDisjointBy, "Set:disjointBy", BuiltinEffect::Pure}, - {BuiltinId::SetCardinality, "Set:cardinality", BuiltinEffect::Pure}, - {BuiltinId::SetContains, "Set:contains", BuiltinEffect::Pure}, - {BuiltinId::SetContainsBy, "Set:containsBy", BuiltinEffect::Pure}, - // Compiler-only fact/query operations (see the enum comment in - // BuiltinOperation.h): Type.* lowering attaches these BuiltinIds - // directly, matching the display names already used in - // IrCodeGenerator.cpp's TermExpr construction and RegisterVm.cpp's error - // messages for each. This table entry was missing entirely for all - // eight, which fails the lockstep static_assert below and does not - // build. - {BuiltinId::ArrayLimit, "array:limit", BuiltinEffect::Pure}, - {BuiltinId::FactInsert, "fact:insert", BuiltinEffect::WritesExternalState}, - {BuiltinId::FactUpdate, "fact:update", BuiltinEffect::WritesExternalState}, - {BuiltinId::FactDelete, "fact:delete", BuiltinEffect::WritesExternalState}, - {BuiltinId::FactJoin, "fact:join", BuiltinEffect::Pure}, - {BuiltinId::FactProject, "fact:project", BuiltinEffect::Pure}, - {BuiltinId::FactAggregate, "fact:aggregate", BuiltinEffect::Pure}, - {BuiltinId::FactSearch, "fact:search", BuiltinEffect::Pure}, - {BuiltinId::FactSetCombine, "fact:setCombine", BuiltinEffect::Pure}, - {BuiltinId::WhereGuardFailed, "where:guardFailed", - BuiltinEffect::WritesExternalState}}; + {BuiltinId::Unknown, "", BuiltinEffect::Volatile}, + {BuiltinId::Throw, "throw", BuiltinEffect::WritesExternalState}, + {BuiltinId::Type, "type", BuiltinEffect::Pure}, + {BuiltinId::Instanceof, "instanceof", BuiltinEffect::Pure}, + {BuiltinId::Count, "count", BuiltinEffect::Pure}, + {BuiltinId::Sum, "sum", BuiltinEffect::Pure}, + {BuiltinId::Average, "average", BuiltinEffect::Pure}, + {BuiltinId::Min, "min", BuiltinEffect::Pure}, + {BuiltinId::Max, "max", BuiltinEffect::Pure}, + {BuiltinId::Sort, "sort", BuiltinEffect::Pure}, + {BuiltinId::Search, "search", BuiltinEffect::Pure}, + {BuiltinId::Contains, "contains", BuiltinEffect::Pure}, + {BuiltinId::Lower, "lower", BuiltinEffect::Pure}, + {BuiltinId::Upper, "upper", BuiltinEffect::Pure}, + {BuiltinId::Length, "length", BuiltinEffect::Pure}, + {BuiltinId::ParseDoc, "ParseDoc", BuiltinEffect::Pure}, + {BuiltinId::StrLen, "str:len", BuiltinEffect::Pure}, + {BuiltinId::StrContains, "str:contains", BuiltinEffect::Pure}, + {BuiltinId::StrConcat, "str:concat", BuiltinEffect::Pure}, + {BuiltinId::StrJoin, "str:join", BuiltinEffect::Pure}, + {BuiltinId::StrLower, "str:lower", BuiltinEffect::Pure}, + {BuiltinId::StrUpper, "str:upper", BuiltinEffect::Pure}, + {BuiltinId::StrTrim, "str:trim", BuiltinEffect::Pure}, + {BuiltinId::StrSplit, "str:split", BuiltinEffect::Pure}, + {BuiltinId::StrReplace, "str:replace", BuiltinEffect::Pure}, + {BuiltinId::StrStartsWith, "str:startsWith", BuiltinEffect::Pure}, + {BuiltinId::StrEndsWith, "str:endsWith", BuiltinEffect::Pure}, + {BuiltinId::ArrayGet, "array:get", BuiltinEffect::Pure}, + {BuiltinId::ArrayLen, "array:len", BuiltinEffect::Pure}, + {BuiltinId::ArrayPush, "array:push", BuiltinEffect::Pure}, + {BuiltinId::FnArray, "fn:array", BuiltinEffect::Pure}, + {BuiltinId::FnPair, "fn:pair", BuiltinEffect::Pure}, + {BuiltinId::FnTuple, "fn:tuple", BuiltinEffect::Pure}, + {BuiltinId::PairFirst, "pair:first", BuiltinEffect::Pure}, + {BuiltinId::PairSecond, "pair:second", BuiltinEffect::Pure}, + {BuiltinId::ConsoleReadLine, "console:readLine", BuiltinEffect::ReadsExternalState}, + {BuiltinId::ConsoleInput, "console:input", BuiltinEffect::ReadsExternalState}, + {BuiltinId::ConsoleInputNumber, "console:inputNumber", BuiltinEffect::ReadsExternalState}, + {BuiltinId::ConsoleWriteLine, "console:writeLine", BuiltinEffect::WritesExternalState}, + {BuiltinId::ConsoleWrite, "console:write", BuiltinEffect::WritesExternalState}, + {BuiltinId::SystemPrint, "system:print", BuiltinEffect::WritesExternalState}, + {BuiltinId::SystemPrintf, "system:printf", BuiltinEffect::WritesExternalState}, + {BuiltinId::SystemRun, "system:run", BuiltinEffect::Volatile}, + {BuiltinId::FileReadFile, "file:readFile", BuiltinEffect::ReadsExternalState}, + {BuiltinId::FileReadLines, "file:readLines", BuiltinEffect::ReadsExternalState}, + {BuiltinId::FileReadLine, "file:readLine", BuiltinEffect::ReadsExternalState}, + {BuiltinId::FileWriteFile, "file:writeFile", BuiltinEffect::WritesExternalState}, + {BuiltinId::FileWriteLines, "file:writeLines", BuiltinEffect::WritesExternalState}, + {BuiltinId::FileAppendFile, "file:appendFile", BuiltinEffect::WritesExternalState}, + {BuiltinId::FileExists, "file:exists", BuiltinEffect::ReadsExternalState}, + {BuiltinId::FileDeleteFile, "file:deleteFile", BuiltinEffect::WritesExternalState}, + {BuiltinId::FactAll, "Fact:all", BuiltinEffect::Pure}, + {BuiltinId::FactFind, "Fact:find", BuiltinEffect::Pure}, + {BuiltinId::FactCount, "Fact:count", BuiltinEffect::Pure}, + {BuiltinId::FactFirst, "Fact:first", BuiltinEffect::Pure}, + {BuiltinId::FactTypes, "Fact:types", BuiltinEffect::Pure}, + {BuiltinId::FactFields, "Fact:fields", BuiltinEffect::Pure}, + {BuiltinId::FactExists, "Fact:exists", BuiltinEffect::Pure}, + {BuiltinId::FactSelect, "Fact:select", BuiltinEffect::Pure}, + {BuiltinId::FactMaterialize, "Fact:materialize", BuiltinEffect::Pure}, + {BuiltinId::FactRelease, "Fact:release", BuiltinEffect::WritesExternalState}, + {BuiltinId::FactTimeline, "Fact:timeline", BuiltinEffect::Pure}, + // Reference evaluation is explicit and can replace the attachment's + // private canonical result, so it must never be query-cached. + {BuiltinId::FactReferences, "Fact:references", BuiltinEffect::WritesExternalState}, + {BuiltinId::DbSync, "db:sync", BuiltinEffect::WritesExternalState}, + {BuiltinId::FactInsert, "Fact:insert", BuiltinEffect::WritesExternalState}, + {BuiltinId::FactUpdate, "Fact:update", BuiltinEffect::WritesExternalState}, + {BuiltinId::FactDelete, "Fact:delete", BuiltinEffect::WritesExternalState}, + {BuiltinId::FactAndWhere, "Fact:andWhere", BuiltinEffect::Pure}, + {BuiltinId::FactOrWhere, "Fact:orWhere", BuiltinEffect::Pure}, + {BuiltinId::FactLimit, "Fact:limit", BuiltinEffect::Pure}, + {BuiltinId::CommonAncestors, "commonAncestors", BuiltinEffect::Pure}, + {BuiltinId::LowestCommonAncestor, "lowestCommonAncestor", BuiltinEffect::Pure}, + {BuiltinId::HighestCommonAncestor, "highestCommonAncestor", BuiltinEffect::Pure}, + {BuiltinId::AncestorAnalysis, "ancestorAnalysis", BuiltinEffect::Pure}, + {BuiltinId::PropagateFact, "propagateFact", BuiltinEffect::Pure}, + {BuiltinId::RelationCompare, "Relation:compare", BuiltinEffect::Pure}, + {BuiltinId::RelationFind, "Relation:find", BuiltinEffect::Pure}, + {BuiltinId::DependencySatisfied, "Dependency:satisfied", BuiltinEffect::Pure}, + {BuiltinId::JsonObject, "json:object", BuiltinEffect::Pure}, + {BuiltinId::JsonParse, "json:parse", BuiltinEffect::Pure}, + {BuiltinId::JsonGet, "json:get", BuiltinEffect::Pure}, + {BuiltinId::JsonHas, "json:has", BuiltinEffect::Pure}, + {BuiltinId::JsonKeys, "json:keys", BuiltinEffect::Pure}, + {BuiltinId::JsonSet, "json:set", BuiltinEffect::Pure}, + {BuiltinId::JsonRemove, "json:remove", BuiltinEffect::Pure}, + {BuiltinId::JsonToText, "json:toText", BuiltinEffect::Pure}, + {BuiltinId::VisualizeGraphJson, "visualize:graphJson", BuiltinEffect::ReadsExternalState}, + {BuiltinId::ThreadCreateThread, "thread:createThread", BuiltinEffect::WritesExternalState}, + {BuiltinId::ThreadStart, "thread:start", BuiltinEffect::WritesExternalState}, + {BuiltinId::ThreadPause, "thread:pause", BuiltinEffect::WritesExternalState}, + {BuiltinId::ThreadStop, "thread:stop", BuiltinEffect::WritesExternalState}, + {BuiltinId::ThreadStatus, "thread:status", BuiltinEffect::ReadsExternalState}, + {BuiltinId::ThreadResult, "thread:result", BuiltinEffect::ReadsExternalState}, + {BuiltinId::MathPi, "math:pi", BuiltinEffect::Pure}, + {BuiltinId::MathE, "math:e", BuiltinEffect::Pure}, + {BuiltinId::MathRandom, "math:random", BuiltinEffect::Volatile}, + {BuiltinId::MathPow, "math:pow", BuiltinEffect::Pure}, + {BuiltinId::MathAtan2, "math:atan2", BuiltinEffect::Pure}, + {BuiltinId::MathSqrt, "math:sqrt", BuiltinEffect::Pure}, + {BuiltinId::MathSin, "math:sin", BuiltinEffect::Pure}, + {BuiltinId::MathCos, "math:cos", BuiltinEffect::Pure}, + {BuiltinId::MathTan, "math:tan", BuiltinEffect::Pure}, + {BuiltinId::MathAsin, "math:asin", BuiltinEffect::Pure}, + {BuiltinId::MathAcos, "math:acos", BuiltinEffect::Pure}, + {BuiltinId::MathAtan, "math:atan", BuiltinEffect::Pure}, + {BuiltinId::MathLog, "math:log", BuiltinEffect::Pure}, + {BuiltinId::MathLog10, "math:log10", BuiltinEffect::Pure}, + {BuiltinId::MathExp, "math:exp", BuiltinEffect::Pure}, + {BuiltinId::MathAbs, "math:abs", BuiltinEffect::Pure}, + {BuiltinId::MathFloor, "math:floor", BuiltinEffect::Pure}, + {BuiltinId::MathCeil, "math:ceil", BuiltinEffect::Pure}, + {BuiltinId::MathRound, "math:round", BuiltinEffect::Pure}, + {BuiltinId::MathAdd, "math:add", BuiltinEffect::Pure}, + {BuiltinId::MathSub, "math:sub", BuiltinEffect::Pure}, + {BuiltinId::MathMul, "math:mul", BuiltinEffect::Pure}, + {BuiltinId::MathDiv, "math:div", BuiltinEffect::Pure}, + {BuiltinId::MathMod, "math:mod", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityMean, "probability:mean", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityVariance, "probability:variance", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityStddev, "probability:stddev", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityNormalize, "probability:normalize", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityEntropy, "probability:entropy", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityCovariance, "probability:covariance", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityCorrelation, "probability:correlation", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityBernoulli, "probability:bernoulli", BuiltinEffect::Volatile}, + {BuiltinId::ProbabilityBinomialPmf, "probability:binomialPmf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityBinomialCdf, "probability:binomialCdf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityPoissonPmf, "probability:poissonPmf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityPoissonCdf, "probability:poissonCdf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityNormalPdf, "probability:normalPdf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityNormalCdf, "probability:normalCdf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityUniformPdf, "probability:uniformPdf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilityUniformCdf, "probability:uniformCdf", BuiltinEffect::Pure}, + {BuiltinId::ProbabilitySample, "probability:sample", BuiltinEffect::Volatile}, + {BuiltinId::ProbabilityWeightedChoice, "probability:weightedChoice", BuiltinEffect::Volatile}, + {BuiltinId::ReasoningContrary, "Reasoning:contrary", BuiltinEffect::WritesExternalState}, + {BuiltinId::ReasoningProve, "Reasoning:prove", BuiltinEffect::ReadsExternalState}, + {BuiltinId::ReasoningGrade, "Reasoning:grade", BuiltinEffect::Pure}, + {BuiltinId::ReasoningDecide, "Reasoning:decide", BuiltinEffect::ReadsExternalState}, + {BuiltinId::MlSigmoid, "ml:sigmoid", BuiltinEffect::Pure}, + {BuiltinId::MlRelu, "ml:relu", BuiltinEffect::Pure}, + {BuiltinId::MlDot, "ml:dot", BuiltinEffect::Pure}, + {BuiltinId::MlMeanSquaredError, "ml:meanSquaredError", BuiltinEffect::Pure}, + {BuiltinId::OverloadAnnotation, "overload", BuiltinEffect::Pure}, + {BuiltinId::MatcherAnnotation, "matcher", BuiltinEffect::Pure}, + {BuiltinId::MixfixAnnotation, "mixfix", BuiltinEffect::Pure} +}; constexpr std::size_t builtinInfoCount() { - return static_cast(BuiltinId::Last) + 1; + return static_cast(BuiltinId::Last) + 1; } -static_assert(sizeof(kBuiltinInfos) / sizeof(kBuiltinInfos[0]) == - builtinInfoCount(), +static_assert(sizeof(kBuiltinInfos) / sizeof(kBuiltinInfos[0]) == builtinInfoCount(), "BuiltinId and builtin registry table must stay in lockstep"); -const BuiltinInfo &builtinInfo(BuiltinId id) { - const auto index = static_cast(id); - if (index >= builtinInfoCount()) - return kBuiltinInfos[0]; - const BuiltinInfo &info = kBuiltinInfos[index]; - return info.id == id ? info : kBuiltinInfos[0]; +const BuiltinInfo& builtinInfo(BuiltinId id) { + const auto index = static_cast(id); + if (index >= builtinInfoCount()) return kBuiltinInfos[0]; + const BuiltinInfo& info = kBuiltinInfos[index]; + return info.id == id ? info : kBuiltinInfos[0]; } -const std::unordered_map &builtinsByName() { - static const std::unordered_map builtins = [] { - std::unordered_map map; - map.reserve(builtinInfoCount() - 1); - map.max_load_factor(0.7f); - for (std::size_t i = 1; i < builtinInfoCount(); ++i) { - const BuiltinInfo *info = kBuiltinInfos + i; - map.emplace(info->name, info->id); - } - return map; - }(); - return builtins; -} - -struct PieceSequenceHash { - std::size_t operator()(const std::vector &ids) const noexcept { - std::size_t hash = ids.size(); - for (const auto id : ids) { - hash ^= std::hash{}(id) + 0x9e3779b9U + (hash << 6U) + - (hash >> 2U); - } - return hash; - } -}; - -std::vector encodeBuiltinPieceIds(const std::string &spelling) { - sentencepiece::SentencePieceText encoded; - const auto status = felidaeSentencePieceModel().Encode(spelling, &encoded); - if (!status.ok()) { - throw std::runtime_error("Unable to encode Felidae builtin vocabulary"); - } - std::vector ids; - ids.reserve(static_cast(encoded.pieces_size())); - for (const auto &piece : encoded.pieces()) { - if (piece.id() == TokenId::UNKNOWN) { - throw std::runtime_error( - "Felidae builtin vocabulary encoded as unknown piece"); - } - ids.push_back(static_cast(piece.id())); - } - return ids; -} - -const std::unordered_map, BuiltinId, - PieceSequenceHash> & -builtinsByPieceIds() { - static const std::unordered_map, BuiltinId, - PieceSequenceHash> - builtins = [] { - std::unordered_map, BuiltinId, - PieceSequenceHash> - map; - map.reserve((builtinInfoCount() - 1) * 2U); - map.max_load_factor(0.7F); - for (std::size_t index = 1; index < builtinInfoCount(); ++index) { - const auto &info = kBuiltinInfos[index]; - const std::string canonical(info.name); - map.emplace(encodeBuiltinPieceIds(canonical), info.id); - std::string dotted = canonical; - for (char &character : dotted) { - if (character == ':') - character = '.'; - } - map.emplace(encodeBuiltinPieceIds(dotted), info.id); +const std::unordered_map& builtinsByName() { + static const std::unordered_map builtins = [] { + std::unordered_map map; + map.reserve(builtinInfoCount() - 1); + map.max_load_factor(0.7f); + for (std::size_t i = 1; i < builtinInfoCount(); ++i) { + const BuiltinInfo* info = kBuiltinInfos + i; + map.emplace(info->name, info->id); } return map; - }(); - return builtins; + }(); + return builtins; } } // namespace -bool isBuiltinModuleName(std::string_view name) { - return std::find(kBuiltinModules.begin(), kBuiltinModules.end(), name) != - kBuiltinModules.end(); -} - -BuiltinId builtinIdForName(const std::string &name) { - return builtinIdForName(std::string_view(name)); +BuiltinId builtinIdForName(const std::string& name) { + return builtinIdForName(std::string_view(name)); } BuiltinId builtinIdForName(std::string_view name) { - auto found = builtinsByName().find(name); - return found == builtinsByName().end() ? BuiltinId::Unknown : found->second; + auto found = builtinsByName().find(name); + if (found != builtinsByName().end()) return found->second; + // Source member syntax uses dots while the historical builtin registry + // stores qualified names with colons. + std::string canonical(name); + std::replace(canonical.begin(), canonical.end(), '.', ':'); + found = builtinsByName().find(canonical); + return found == builtinsByName().end() ? BuiltinId::Unknown : found->second; } -BuiltinId builtinIdForName(const char *name) { - return name ? builtinIdForName(std::string_view(name)) : BuiltinId::Unknown; +BuiltinId builtinIdForName(const char* name) { + return name ? builtinIdForName(std::string_view(name)) : BuiltinId::Unknown; } -BuiltinId builtinIdForPieceIds(const std::vector &pieceIds) { - const auto &builtins = builtinsByPieceIds(); - const auto found = builtins.find(pieceIds); - return found == builtins.end() ? BuiltinId::Unknown : found->second; +bool isBuiltinFunctionName(const std::string& name) { + return builtinIdForName(name) != BuiltinId::Unknown; } -bool isBuiltinFunctionName(const std::string &name) { - return builtinIdForName(name) != BuiltinId::Unknown; +const char* builtinName(BuiltinId id) { + return builtinInfo(id).name; } -const char *builtinName(BuiltinId id) { return builtinInfo(id).name; } - -BuiltinEffect builtinEffect(BuiltinId id) { return builtinInfo(id).effect; } +BuiltinEffect builtinEffect(BuiltinId id) { + return builtinInfo(id).effect; +} -BuiltinEffect builtinEffect(const std::string &name) { - return builtinEffect(builtinIdForName(name)); +BuiltinEffect builtinEffect(const std::string& name) { + return builtinEffect(builtinIdForName(name)); } bool isBuiltinPure(BuiltinId id) { - return builtinEffect(id) == BuiltinEffect::Pure; + return builtinEffect(id) == BuiltinEffect::Pure; } -bool isBuiltinPure(const std::string &name) { - return isBuiltinPure(builtinIdForName(name)); +bool isBuiltinPure(const std::string& name) { + return isBuiltinPure(builtinIdForName(name)); } -const std::vector &allBuiltins() { - static const std::vector builtins = [] { - std::vector list; - list.reserve(builtinInfoCount() - 1); - for (std::size_t i = 1; i < builtinInfoCount(); ++i) - list.push_back(kBuiltinInfos[i]); - return list; - }(); - return builtins; +const std::vector& allBuiltins() { + static const std::vector builtins = [] { + std::vector list; + list.reserve(builtinInfoCount() - 1); + for (std::size_t i = 1; i < builtinInfoCount(); ++i) list.push_back(kBuiltinInfos[i]); + return list; + }(); + return builtins; } } // namespace Felidae diff --git a/src/BuiltinRegistry.h b/src/BuiltinRegistry.h index 66385ca..a8a60cb 100644 --- a/src/BuiltinRegistry.h +++ b/src/BuiltinRegistry.h @@ -23,21 +23,12 @@ struct BuiltinInfo { BuiltinId builtinIdForName(const std::string& name); BuiltinId builtinIdForName(std::string_view name); BuiltinId builtinIdForName(const char* name); -// Parser-facing native resolution. The input is a complete qualified source -// name from the SentencePiece stream (including atomic separator IDs), not a -// decoded spelling. This keeps grammar assembly independent of string -// comparisons while retaining BuiltinId as the interpreter's semantic ID. -BuiltinId builtinIdForPieceIds(const std::vector& pieceIds); bool isBuiltinFunctionName(const std::string& name); const char* builtinName(BuiltinId id); BuiltinEffect builtinEffect(BuiltinId id); BuiltinEffect builtinEffect(const std::string& name); bool isBuiltinPure(BuiltinId id); bool isBuiltinPure(const std::string& name); -// Compiler-known namespaces do not identify source files and need no module -// linking. Keep this decision beside the builtin registry so frontend import -// resolution and IR lowering cannot maintain divergent allowlists. -bool isBuiltinModuleName(std::string_view name); // Every registered builtin except the Unknown sentinel, in table order. const std::vector& allBuiltins(); diff --git a/src/CompilerFrontend.cpp b/src/CompilerFrontend.cpp deleted file mode 100644 index 8f686e6..0000000 --- a/src/CompilerFrontend.cpp +++ /dev/null @@ -1,357 +0,0 @@ -#include "CompilerFrontend.h" - -#include "BuiltinRegistry.h" -#include "IntegerParser.h" -#include "IntegerTokenList.h" -#include "IrCodeGenerator.h" -#include "Operator.h" -#include "SentencePieceModel.h" -#include "Symbol.h" -#include "form/RegisterVm.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; - -namespace Felidae { -namespace { -constexpr std::uintmax_t kStreamingReadThresholdBytes = - 10ull * 1024ull * 1024ull; -constexpr std::size_t kReadChunkBytes = 1024ull * 1024ull; - -std::string normalizeSource(std::string text) { - // A UTF-8 BOM is transport metadata, not Felidae syntax. Retaining it - // creates an unexpected first SentencePiece token before valid syntax. - constexpr char kUtf8Bom[] = {'\xEF', '\xBB', '\xBF'}; - if (text.size() >= std::size(kUtf8Bom) && - std::equal(std::begin(kUtf8Bom), std::end(kUtf8Bom), text.begin())) { - text.erase(0, std::size(kUtf8Bom)); - } - return text; -} -} // namespace - -std::string readSourceFile(const fs::path &path) { - std::ifstream in(path, std::ios::binary); - if (!in) - throw std::runtime_error("Cannot open file: " + path.string()); - std::error_code ec; - const auto size = fs::file_size(path, ec); - if (!ec && size <= kStreamingReadThresholdBytes) { - std::string text(static_cast(size), '\0'); - if (!text.empty()) { - in.read(text.data(), static_cast(text.size())); - if (!in && !in.eof()) - throw std::runtime_error("Cannot read file: " + path.string()); - } - return normalizeSource(std::move(text)); - } - std::string text; - if (!ec) - text.reserve(static_cast( - std::min(size, kStreamingReadThresholdBytes))); - std::vector buffer(kReadChunkBytes); - while (in) { - in.read(buffer.data(), static_cast(buffer.size())); - const auto read = in.gcount(); - if (read > 0) - text.append(buffer.data(), static_cast(read)); - } - if (!in.eof()) - throw std::runtime_error("Cannot read file: " + path.string()); - return normalizeSource(std::move(text)); -} - -std::filesystem::path resolveProgramEntryPath(const fs::path &path) { - fs::path normalized = fs::absolute(path).lexically_normal(); - std::error_code ec; - if (!fs::is_directory(normalized, ec)) - return normalized; - const fs::path mainFile = normalized / "main.fx"; - if (fs::exists(mainFile, ec) && fs::is_regular_file(mainFile, ec)) - return mainFile.lexically_normal(); - throw std::runtime_error("Project directory does not contain main.fx: " + - normalized.string()); -} - -Program parseProgramText(std::string text, const CompilerOptions &options) { - return parseProgramText(std::move(text), std::make_shared(), - options); -} - -Program parseProgramText(std::string text, - std::shared_ptr operators, - const CompilerOptions &options) { - if (!operators) - throw std::invalid_argument("parser operator registry must not be null"); - IntegerTokenList input(felidaeSentencePieceModel(), std::move(text)); - // Mixfix declarations and uses share one parser-owned registry. SentencePiece - // receives complete dot-terminated statements, including multiline chains. - IntegerParser parser(input, std::move(operators), options.mixfixModel); - return parser.parseProgram(); -} - -Program parseProgramFile(const fs::path &path, const CompilerOptions &options) { - return parseProgramText(readSourceFile(resolveProgramEntryPath(path)), - options); -} - -namespace { - -PieceSequence encodePersistenceSource(const fs::path &path) { - std::vector encoded; - const auto spelling = path.string(); - const auto status = felidaeSentencePieceModel().Encode(spelling, &encoded); - if (!status.ok() || encoded.empty()) { - throw IntegerParserError("fact database path cannot be encoded: " + - spelling); - } - PieceSequence pieces; - pieces.reserve(encoded.size()); - for (const int piece : encoded) { - if (piece < 0) - throw IntegerParserError( - "SentencePiece emitted an invalid fact database path piece"); - pieces.push_back(static_cast(piece)); - } - return pieces; -} - -fs::path resolveFactDatabasePath(const fs::path &importer, - std::string_view imported) { - fs::path candidate{std::string(imported)}; - if (candidate.is_relative()) - candidate = importer.parent_path() / candidate; - candidate = fs::absolute(candidate).lexically_normal(); - std::error_code error; - if (!fs::is_regular_file(candidate, error)) { - throw IntegerParserError("fact database import is not a file: " + - candidate.string()); - } - const auto canonical = fs::weakly_canonical(candidate, error); - return error ? candidate : canonical; -} - -class FactDatabaseLinker { -public: - explicit FactDatabaseLinker(const CompilerOptions &options) - : options_(options) {} - - void link(const fs::path &path) { - const auto key = path.string(); - if (linked_.contains(key)) - return; - if (!visiting_.insert(key).second) - throw IntegerParserError("cyclic fact database import: " + key); - - Program database; - try { - database = parseProgramText(readSourceFile(path), options_); - } catch (const std::exception &error) { - visiting_.erase(key); - throw IntegerParserError("cannot parse fact database '" + key + - "': " + error.what()); - } - for (const auto &import : database.imports) { - if (!import) - throw IntegerParserError("invalid import in fact database: " + key); - for (const auto &name : import->paths) { - if (isBuiltinModuleName(name)) - continue; - if (fs::path(name).extension() != ".fx") { - throw IntegerParserError("unsupported fact database import '" + - name + "' in " + key); - } - link(resolveFactDatabasePath(path, name)); - } - } - if (!database.globals.empty()) { - throw IntegerParserError("fact database must not declare globals: " + - key); - } - const auto owner = std::make_shared( - encodePersistenceSource(path)); - for (auto &clause : database.clauses) { - if (!clause || !clause->isFact() || !clause->annotations.empty()) { - throw IntegerParserError( - "fact database may contain only unannotated fact rows: " + key); - } - clause->persistenceSource = owner; - facts_.push_back(std::move(clause)); - } - visiting_.erase(key); - linked_.insert(key); - } - - std::vector> takeFacts() { - return std::move(facts_); - } - -private: - const CompilerOptions &options_; - std::unordered_set visiting_; - std::unordered_set linked_; - std::vector> facts_; -}; - -Program linkFactDatabases(Program program, const fs::path &entry, - const CompilerOptions &options) { - FactDatabaseLinker linker(options); - std::vector> remainingImports; - for (const auto &import : program.imports) { - if (!import) - throw IntegerParserError("invalid source import"); - std::vector remainingPaths; - for (const auto &name : import->paths) { - if (fs::path(name).extension() == ".fx") - linker.link(resolveFactDatabasePath(entry, name)); - else - remainingPaths.push_back(name); - } - if (!remainingPaths.empty()) - remainingImports.push_back( - std::make_shared(std::move(remainingPaths))); - } - - Program linked; - for (auto &import : remainingImports) - linked.addStatement(std::move(import)); - for (auto &fact : linker.takeFacts()) - linked.addStatement(std::move(fact)); - for (auto &global : program.globals) - linked.addStatement(std::move(global)); - std::unordered_set classMethods; - for (const auto &declaration : program.classes) - for (const auto &method : declaration->methods) - classMethods.insert(method.get()); - for (auto &declaration : program.classes) - linked.addStatement(std::move(declaration)); - for (auto &clause : program.clauses) - if (!classMethods.contains(clause.get())) - linked.addStatement(std::move(clause)); - return linked; -} - -} // namespace - -static IrModule compileProgramToIr(Program program) { - auto module = IrCodeGenerator{}.compile(std::move(program)); - std::vector symbols; - const auto collectProgram = [&](const FelidaeIr &program) { - symbols.insert(symbols.end(), program.symbols.begin(), - program.symbols.end()); - }; - collectProgram(module.ir); - symbols.push_back(module.entryProcedure); - for (const auto &[symbol, procedure] : module.procedures) { - symbols.push_back(symbol); - collectProgram(procedure.ir); - symbols.insert(symbols.end(), procedure.positionalParameters.begin(), - procedure.positionalParameters.end()); - symbols.insert(symbols.end(), procedure.namedParameters.begin(), - procedure.namedParameters.end()); - } - for (const auto &type : module.factTypes) { - symbols.push_back(type.symbol); - symbols.insert(symbols.end(), type.parents.begin(), type.parents.end()); - for (const auto &index : type.indexes) - symbols.insert(symbols.end(), index.begin(), index.end()); - } - std::sort(symbols.begin(), symbols.end()); - symbols.erase(std::unique(symbols.begin(), symbols.end()), symbols.end()); - std::unordered_map indexes; - indexes.reserve(symbols.size()); - module.symbolTable.reserve(symbols.size()); - const auto &model = felidaeSentencePieceModel(); - for (const auto symbol : symbols) { - const auto spelling = symbolNameForId(symbol); - if (symbol == 0 || spelling.empty()) - throw IntegerParserError("IR symbol has no canonical lexical spelling"); - PieceSequence pieces = symbolPiecesForId(symbol); - if (pieces.empty()) { - // Compiler-synthesized composite names have no source token span. - // Encode those once at this lexical boundary; parsed names reuse - // the exact PieceIds retained by IntegerParser. - std::vector encoded; - const auto status = model.Encode(spelling, &encoded); - if (!status.ok() || encoded.empty()) - throw IntegerParserError( - "IR symbol cannot be encoded by the fixed SentencePiece model"); - pieces.reserve(encoded.size()); - for (const auto piece : encoded) { - if (piece < 0) - throw IntegerParserError( - "SentencePiece emitted an invalid symbol piece"); - pieces.push_back(static_cast(piece)); - } - } - const auto index = static_cast(module.symbolTable.size() + 1); - indexes.emplace(symbol, index); - module.symbolTable.push_back(std::move(pieces)); - } - const auto remap = [&](IrSymbolRef &symbol) { symbol = indexes.at(symbol); }; - const auto remapProgram = [&](FelidaeIr &program) { - for (auto &symbol : program.symbols) - remap(symbol); - }; - remapProgram(module.ir); - remap(module.entryProcedure); - std::unordered_map procedures; - procedures.reserve(module.procedures.size()); - for (auto &[symbol, procedure] : module.procedures) { - remapProgram(procedure.ir); - for (auto ¶meter : procedure.positionalParameters) - remap(parameter); - for (auto ¶meter : procedure.namedParameters) - remap(parameter); - procedures.emplace(indexes.at(symbol), std::move(procedure)); - } - module.procedures = std::move(procedures); - for (auto &type : module.factTypes) { - remap(type.symbol); - for (auto &parent : type.parents) - remap(parent); - for (auto &index : type.indexes) - for (auto &field : index) - remap(field); - } - module.sentencePieceModelIdentity = felidaeSentencePieceModelIdentity(); - return module; -} - -IrModule compileProgramTextToIr(std::string text, - const CompilerOptions &options) { - return compileProgramToIr(parseProgramText(std::move(text), options)); -} - -IrModule compileProgramFileToIr(const fs::path &path, - const CompilerOptions &options) { - const auto entry = resolveProgramEntryPath(path); - auto program = parseProgramText(readSourceFile(entry), options); - return compileProgramToIr(linkFactDatabases(std::move(program), entry, - options)); -} - -std::optional tryCompileExpressionTextToIr(const std::string &text) { - try { - IntegerTokenList input(felidaeSentencePieceModel(), text); - return IntegerParser(input, std::make_shared()) - .compileExpressionIr(); - } catch (const IntegerParserError &) { - return std::nullopt; - } -} - -} // namespace Felidae diff --git a/src/CompilerFrontend.h b/src/CompilerFrontend.h deleted file mode 100644 index 87b87cb..0000000 --- a/src/CompilerFrontend.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include "AST.h" -#include "FelidaeIr.h" -#include "form/IrModule.h" - -#include -#include -#include -#include - -namespace Felidae { - -class MixfixStateModel; -class OperatorRegistry; - -struct CompilerOptions { - // Optional, verifier-gated compiler SSM. Normal syntax remains fully - // deterministic; only unresolved custom mixfix assembly reaches it. - MixfixStateModel *mixfixModel = nullptr; -}; - -// Source-only frontend boundary. `Program` is Felidae's syntax-shaped, -// compiler-only HIR; the Form VM never includes this header or receives its -// nodes. -std::string readSourceFile(const std::filesystem::path &path); -std::filesystem::path -resolveProgramEntryPath(const std::filesystem::path &path); -Program parseProgramFile(const std::filesystem::path &path, - const CompilerOptions &options = {}); -Program parseProgramText(std::string text, const CompilerOptions &options = {}); -Program parseProgramText(std::string text, - std::shared_ptr operators, - const CompilerOptions &options = {}); -IrModule compileProgramTextToIr(std::string text, - const CompilerOptions &options = {}); -IrModule compileProgramFileToIr(const std::filesystem::path &path, - const CompilerOptions &options = {}); -std::optional tryCompileExpressionTextToIr(const std::string &text); - -} // namespace Felidae diff --git a/src/FelidaeGrammar.h b/src/FelidaeGrammar.h index da5571d..c96be1f 100644 --- a/src/FelidaeGrammar.h +++ b/src/FelidaeGrammar.h @@ -1,10 +1,7 @@ #pragma once #include "Symbol.h" -#include "form/BuiltinOperation.h" -#ifndef FELIDAE_GENERATING_MODEL -#include -#endif +#include "FelidaeTokenizerIds.h" #include #include #include @@ -16,313 +13,377 @@ namespace Felidae { inline constexpr bool isCustomOperatorCharacter(char value) { - switch (value) { - case '~': - case '^': - case '&': - case '$': - return true; - default: - return false; - } + switch (value) { + case '~': + case '^': + case '&': + case '$': + return true; + default: + return false; + } } inline bool isCustomOperatorSpelling(std::string_view spelling) { - return !spelling.empty() && - std::all_of(spelling.begin(), spelling.end(), [](char value) { - return isCustomOperatorCharacter(value); - }); + return !spelling.empty() && std::all_of( + spelling.begin(), spelling.end(), [](char value) { + return isCustomOperatorCharacter(value); + }); } +enum class BuiltinId { + Unknown = 0, + + Throw, + Type, + Instanceof, + + Count, + Sum, + Average, + Min, + Max, + Sort, + Search, + Contains, + Lower, + Upper, + Length, + ParseDoc, + + StrLen, + StrContains, + StrConcat, + StrJoin, + StrLower, + StrUpper, + StrTrim, + StrSplit, + StrReplace, + StrStartsWith, + StrEndsWith, + + ArrayGet, + ArrayLen, + ArrayPush, + + FnArray, + FnPair, + FnTuple, + + PairFirst, + PairSecond, + + ConsoleReadLine, + ConsoleInput, + ConsoleInputNumber, + ConsoleWriteLine, + ConsoleWrite, + SystemPrint, + SystemPrintf, + SystemRun, + + FileReadFile, + FileReadLines, + FileReadLine, + FileWriteFile, + FileWriteLines, + FileAppendFile, + FileExists, + FileDeleteFile, + + FactAll, + FactFind, + FactCount, + FactFirst, + FactTypes, + FactFields, + FactExists, + FactSelect, + FactMaterialize, + FactRelease, + FactTimeline, + FactReferences, + DbSync, + FactInsert, + FactUpdate, + FactDelete, + FactAndWhere, + FactOrWhere, + FactLimit, + + // Fact reasoning is language-native. These operate directly on typed + // fact values; FactMemory remains an implementation detail. + CommonAncestors, + LowestCommonAncestor, + HighestCommonAncestor, + AncestorAnalysis, + PropagateFact, + + RelationCompare, + RelationFind, + DependencySatisfied, + + JsonObject, + JsonParse, + JsonGet, + JsonHas, + JsonKeys, + JsonSet, + JsonRemove, + JsonToText, + + VisualizeGraphJson, + + ThreadCreateThread, + ThreadStart, + ThreadPause, + ThreadStop, + ThreadStatus, + ThreadResult, + + MathPi, + MathE, + MathRandom, + MathPow, + MathAtan2, + MathSqrt, + MathSin, + MathCos, + MathTan, + MathAsin, + MathAcos, + MathAtan, + MathLog, + MathLog10, + MathExp, + MathAbs, + MathFloor, + MathCeil, + MathRound, + MathAdd, + MathSub, + MathMul, + MathDiv, + MathMod, + + ProbabilityMean, + ProbabilityVariance, + ProbabilityStddev, + ProbabilityNormalize, + ProbabilityEntropy, + ProbabilityCovariance, + ProbabilityCorrelation, + ProbabilityBernoulli, + ProbabilityBinomialPmf, + ProbabilityBinomialCdf, + ProbabilityPoissonPmf, + ProbabilityPoissonCdf, + ProbabilityNormalPdf, + ProbabilityNormalCdf, + ProbabilityUniformPdf, + ProbabilityUniformCdf, + ProbabilitySample, + ProbabilityWeightedChoice, + + ReasoningContrary, + ReasoningProve, + ReasoningGrade, + ReasoningDecide, + + MlSigmoid, + MlRelu, + MlDot, + MlMeanSquaredError, + + OverloadAnnotation, + MatcherAnnotation, + MixfixAnnotation, + + Last = MixfixAnnotation +}; + enum class LanguageTypeId { - Unknown = 0, - Any, - Array, - Bool, - Boolean, - Decimal, - Double, - Fact, - Float, - Int, - Number, - String, - Expr, - Mixfix, - Stmt, - Statements + Unknown = 0, + Any, + Array, + Bool, + Boolean, + Decimal, + Double, + Fact, + Float, + Int, + Number, + String, + Expr, + Mixfix, + Stmt, + Statements }; inline constexpr std::string_view languageTypeName(LanguageTypeId type) { - switch (type) { - case LanguageTypeId::Any: - return "any"; - case LanguageTypeId::Array: - return "array"; - case LanguageTypeId::Bool: - return "bool"; - case LanguageTypeId::Boolean: - return "boolean"; - case LanguageTypeId::Decimal: - return "decimal"; - case LanguageTypeId::Double: - return "double"; - case LanguageTypeId::Fact: - return "Fact"; - case LanguageTypeId::Float: - return "float"; - case LanguageTypeId::Int: - return "int"; - case LanguageTypeId::Number: - return "number"; - case LanguageTypeId::String: - return "string"; - case LanguageTypeId::Expr: - return "expr"; - case LanguageTypeId::Mixfix: - return "mixfix"; - case LanguageTypeId::Stmt: - return "stmt"; - case LanguageTypeId::Statements: - return "stmts"; - case LanguageTypeId::Unknown: + switch (type) { + case LanguageTypeId::Any: return "any"; + case LanguageTypeId::Array: return "array"; + case LanguageTypeId::Bool: return "bool"; + case LanguageTypeId::Boolean: return "boolean"; + case LanguageTypeId::Decimal: return "decimal"; + case LanguageTypeId::Double: return "double"; + case LanguageTypeId::Fact: return "Fact"; + case LanguageTypeId::Float: return "float"; + case LanguageTypeId::Int: return "int"; + case LanguageTypeId::Number: return "number"; + case LanguageTypeId::String: return "string"; + case LanguageTypeId::Expr: return "expr"; + case LanguageTypeId::Mixfix: return "mixfix"; + case LanguageTypeId::Stmt: return "stmt"; + case LanguageTypeId::Statements: return "stmts"; + case LanguageTypeId::Unknown: return {}; + } return {}; - } - return {}; } -inline LanguageTypeId languageTypeIdForName(const std::string &name) { - // `obj` is the concise generic-capture spelling used by existing Felidae - // mixfix declarations. It is an alias, not a distinct runtime type: both - // spellings retain Any's intentionally unconstrained matching semantics. - if (name == "any" || name == "obj") - return LanguageTypeId::Any; - if (name == "array") - return LanguageTypeId::Array; - if (name == "bool") - return LanguageTypeId::Bool; - if (name == "boolean") - return LanguageTypeId::Boolean; - if (name == "decimal") - return LanguageTypeId::Decimal; - if (name == "double") - return LanguageTypeId::Double; - if (name == "Fact") - return LanguageTypeId::Fact; - if (name == "float") - return LanguageTypeId::Float; - if (name == "int") - return LanguageTypeId::Int; - if (name == "number") - return LanguageTypeId::Number; - if (name == "string") - return LanguageTypeId::String; - if (name == "expr") - return LanguageTypeId::Expr; - if (name == "mixfix") - return LanguageTypeId::Mixfix; - if (name == "stmt") - return LanguageTypeId::Stmt; - if (name == "stmts") - return LanguageTypeId::Statements; - return LanguageTypeId::Unknown; +inline LanguageTypeId languageTypeIdForName(const std::string& name) { + if (name == "any") return LanguageTypeId::Any; + if (name == "array") return LanguageTypeId::Array; + if (name == "bool") return LanguageTypeId::Bool; + if (name == "boolean") return LanguageTypeId::Boolean; + if (name == "decimal") return LanguageTypeId::Decimal; + if (name == "double") return LanguageTypeId::Double; + if (name == "Fact") return LanguageTypeId::Fact; + if (name == "float") return LanguageTypeId::Float; + if (name == "int") return LanguageTypeId::Int; + if (name == "number") return LanguageTypeId::Number; + if (name == "string") return LanguageTypeId::String; + if (name == "expr") return LanguageTypeId::Expr; + if (name == "mixfix") return LanguageTypeId::Mixfix; + if (name == "stmt") return LanguageTypeId::Stmt; + if (name == "stmts") return LanguageTypeId::Statements; + return LanguageTypeId::Unknown; } -inline bool isFelidaeBuiltinTypeName(const std::string &name) { - return languageTypeIdForName(name) != LanguageTypeId::Unknown; +inline bool isFelidaeBuiltinTypeName(const std::string& name) { + return languageTypeIdForName(name) != LanguageTypeId::Unknown; } -inline bool isFelidaeTypeAnnotationName(const std::string &name) { - return !name.empty() && - (std::isupper(static_cast(name.front())) || - isFelidaeBuiltinTypeName(name)); +inline bool isFelidaeTypeAnnotationName(const std::string& name) { + return !name.empty() && + (std::isupper(static_cast(name.front())) || + isFelidaeBuiltinTypeName(name)); } -inline bool isFelidaeLikelyTypeName(const std::string &name) { - return isFelidaeBuiltinTypeName(name) || - (!name.empty() && - std::isupper(static_cast(name.front()))); +inline bool isFelidaeLikelyTypeName(const std::string& name) { + return isFelidaeBuiltinTypeName(name) || + (!name.empty() && std::isupper(static_cast(name.front()))); } // Model-generation spelling specification for fixed Felidae syntax. Runtime -// grammar IDs are generated into FelidaeSentencePieceIds.h; this file never +// grammar IDs are generated into FelidaeTokenizerIds.h; this file never // owns numeric token identities. struct BuiltinTokenDefinition { - std::string_view spelling; - std::string_view idName; + std::string_view spelling; + std::string_view idName; }; inline constexpr BuiltinTokenDefinition kBuiltinTokens[] = { - {"import", "IMPORT"}, - {"not", "NOT"}, - {"and", "AND"}, - {"or", "OR"}, - {"then", "THEN"}, - {"as", "AS"}, - {"if", "IF"}, - {"else", "ELSE"}, - {"return", "RETURN"}, - {"where", "WHERE"}, - {"extend", "EXTEND"}, - {"lambda", "LAMBDA"}, - {"nil", "NIL"}, - {"(", "LPAREN"}, - {")", "RPAREN"}, - {"{", "LBRACE"}, - {"}", "RBRACE"}, - {"[", "LBRACKET"}, - {"]", "RBRACKET"}, - {",", "COMMA"}, - {":", "COLON"}, - {".", "DOT"}, - {"|", "PIPE"}, - {"?", "QUESTION"}, - {"@", "AT"}, - {":=", "ASSIGN"}, - {"::", "DOUBLE_COLON"}, - {"=>", "ARROW"}, - {"+", "PLUS"}, - {"-", "MINUS"}, - {"*", "STAR"}, - {"/", "SLASH"}, - {"%", "PERCENT"}, - {"==", "EQUAL"}, - {"!=", "NOT_EQUAL"}, - {"<", "LESS"}, - {"<=", "LESS_EQUAL"}, - {">", "GREATER"}, + {"import", "IMPORT"}, {"not", "NOT"}, {"and", "AND"}, {"or", "OR"}, {"then", "THEN"}, {"as", "AS"}, + {"if", "IF"}, {"else", "ELSE"}, {"return", "RETURN"}, {"where", "WHERE"}, {"extend", "EXTEND"}, + {"lambda", "LAMBDA"}, {"true", "TRUE"}, {"false", "FALSE"}, {"nil", "NIL"}, + {"(", "LPAREN"}, {")", "RPAREN"}, {"{", "LBRACE"}, {"}", "RBRACE"}, {"[", "LBRACKET"}, + {"]", "RBRACKET"}, {",", "COMMA"}, {":", "COLON"}, {".", "DOT"}, {"|", "PIPE"}, + {"?", "QUESTION"}, {"@", "AT"}, {":=", "ASSIGN"}, {"::", "DOUBLE_COLON"}, {"=>", "ARROW"}, + {"+", "PLUS"}, {"-", "MINUS"}, {"*", "STAR"}, {"/", "SLASH"}, {"%", "PERCENT"}, + {"==", "EQUAL"}, {"!=", "NOT_EQUAL"}, {"<", "LESS"}, {"<=", "LESS_EQUAL"}, {">", "GREATER"}, {">=", "GREATER_EQUAL"}, // Literal and trivia delimiters are grammar IDs too. The integer parser // must not rediscover them by inspecting source characters after model // encoding. - {"\"", "QUOTE"}, - {"\\", "BACKSLASH"}, - {"#", "COMMENT"}, - {"▁", "SPACE"}, - {"\t", "TAB"}, - {"\n", "NEWLINE"}, - {"\r", "CARRIAGE_RETURN"}, - {"0", "DIGIT_0"}, - {"1", "DIGIT_1"}, - {"2", "DIGIT_2"}, - {"3", "DIGIT_3"}, - {"4", "DIGIT_4"}, - {"5", "DIGIT_5"}, - {"6", "DIGIT_6"}, - {"7", "DIGIT_7"}, - {"8", "DIGIT_8"}, - {"9", "DIGIT_9"}, + {"\"", "QUOTE"}, {"\\", "BACKSLASH"}, {"#", "COMMENT"}, {"▁", "SPACE"}, {"\t", "TAB"}, + {"\n", "NEWLINE"}, {"\r", "CARRIAGE_RETURN"}, + {"0", "DIGIT_0"}, {"1", "DIGIT_1"}, {"2", "DIGIT_2"}, {"3", "DIGIT_3"}, + {"4", "DIGIT_4"}, {"5", "DIGIT_5"}, {"6", "DIGIT_6"}, {"7", "DIGIT_7"}, + {"8", "DIGIT_8"}, {"9", "DIGIT_9"}, }; #ifndef FELIDAE_GENERATING_MODEL -static_assert( - std::size(kBuiltinTokens) == std::size(kFelidaeBuiltinSentencePieceIds), - "Regenerate FelidaeSentencePieceIds.h after changing built-in syntax"); +static_assert(std::size(kBuiltinTokens) == std::size(kFelidaeBuiltinTokenIds), + "Regenerate FelidaeTokenizerIds.h after changing built-in syntax"); #endif -inline constexpr const BuiltinTokenDefinition * -builtinTokenForSpelling(std::string_view spelling) { - for (const auto &token : kBuiltinTokens) { - if (token.spelling == spelling) - return &token; - } - return nullptr; +inline constexpr const BuiltinTokenDefinition* builtinTokenForSpelling(std::string_view spelling) { + for (const auto& token : kBuiltinTokens) { + if (token.spelling == spelling) return &token; + } + return nullptr; } // Integer grammar vocabulary query. The parser uses this directly when it -// assembles non-built-in SentencePiece ranges; no lexer classification is +// assembles non-built-in token ranges; no lexer classification is // involved. -#ifndef FELIDAE_GENERATING_MODEL inline constexpr bool isBuiltinTokenId(TokenId::Id id) { - for (const auto builtin : kFelidaeBuiltinSentencePieceIds) { - if (id == builtin) - return true; - } - return false; + for (const auto builtin : kFelidaeBuiltinTokenIds) { + if (id == builtin) return true; + } + return false; } inline constexpr std::string_view builtinTokenSpelling(TokenId::Id id) { - for (std::size_t index = 0; index < std::size(kBuiltinTokens); ++index) { - if (kFelidaeBuiltinSentencePieceIds[index] == id) - return kBuiltinTokens[index].spelling; - } - return {}; -} - -// The word-spelled keyword IDs (as opposed to punctuation/operator builtin -// IDs such as LPAREN or ARROW). Only these can plausibly be the leading -// fragment of a longer identifier SentencePiece happened to split this way -// (`import` inside `imported`, `if` inside `ifRequired`, ...); punctuation -// IDs never need the same contiguity check. -inline constexpr bool isKeywordWordTokenId(TokenId::Id id) { - switch (id) { - case TokenId::IMPORT: - case TokenId::NOT: - case TokenId::AND: - case TokenId::OR: - case TokenId::THEN: - case TokenId::AS: - case TokenId::IF: - case TokenId::ELSE: - case TokenId::RETURN: - case TokenId::WHERE: - case TokenId::EXTEND: - case TokenId::LAMBDA: - case TokenId::NIL: - return true; - default: - return false; - } + for (std::size_t index = 0; index < std::size(kBuiltinTokens); ++index) { + if (kFelidaeBuiltinTokenIds[index] == id) return kBuiltinTokens[index].spelling; + } + return {}; } // These IDs end an already-started identifier range. Keyword IDs are -// intentionally absent: if SentencePiece emits (for example) the `or` ID in +// intentionally absent: if BPE emits (for example) the `or` ID in // the middle of `Record`, the contiguous IDs still represent one identifier. // At the start of a grammar position, atNameRange() rejects every built-in ID // so reserved words continue to be parsed as grammar vocabulary. inline constexpr bool isIdentifierBoundaryId(TokenId::Id id) { - switch (id) { - case TokenId::LPAREN: - case TokenId::RPAREN: - case TokenId::LBRACE: - case TokenId::RBRACE: - case TokenId::LBRACKET: - case TokenId::RBRACKET: - case TokenId::COMMA: - case TokenId::COLON: - case TokenId::DOT: - case TokenId::PIPE: - case TokenId::QUESTION: - case TokenId::AT: - case TokenId::ASSIGN: - case TokenId::DOUBLE_COLON: - case TokenId::ARROW: - case TokenId::PLUS: - case TokenId::MINUS: - case TokenId::STAR: - case TokenId::SLASH: - case TokenId::PERCENT: - case TokenId::EQUAL: - case TokenId::NOT_EQUAL: - case TokenId::LESS: - case TokenId::LESS_EQUAL: - case TokenId::GREATER: - case TokenId::GREATER_EQUAL: - case TokenId::QUOTE: - case TokenId::BACKSLASH: - case TokenId::COMMENT: - case TokenId::SPACE: - case TokenId::TAB: - case TokenId::NEWLINE: - case TokenId::CARRIAGE_RETURN: - return true; - default: - return false; - } + switch (id) { + case TokenId::LPAREN: + case TokenId::RPAREN: + case TokenId::LBRACE: + case TokenId::RBRACE: + case TokenId::LBRACKET: + case TokenId::RBRACKET: + case TokenId::COMMA: + case TokenId::COLON: + case TokenId::DOT: + case TokenId::PIPE: + case TokenId::QUESTION: + case TokenId::AT: + case TokenId::ASSIGN: + case TokenId::DOUBLE_COLON: + case TokenId::ARROW: + case TokenId::PLUS: + case TokenId::MINUS: + case TokenId::STAR: + case TokenId::SLASH: + case TokenId::PERCENT: + case TokenId::EQUAL: + case TokenId::NOT_EQUAL: + case TokenId::LESS: + case TokenId::LESS_EQUAL: + case TokenId::GREATER: + case TokenId::GREATER_EQUAL: + case TokenId::QUOTE: + case TokenId::BACKSLASH: + case TokenId::COMMENT: + case TokenId::SPACE: + case TokenId::TAB: + case TokenId::NEWLINE: + case TokenId::CARRIAGE_RETURN: + return true; + default: + return false; + } } +#ifndef FELIDAE_GENERATING_MODEL inline constexpr bool isDecimalDigitId(TokenId::Id id) { - return id >= TokenId::DIGIT_0 && id <= TokenId::DIGIT_9; + return id >= TokenId::DIGIT_0 && id <= TokenId::DIGIT_9; } #endif diff --git a/src/FelidaeIr.h b/src/FelidaeIr.h deleted file mode 100644 index f00eaf9..0000000 --- a/src/FelidaeIr.h +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -// Unified variable-width executable IR shared by compiler and RegisterVm. -#include -#include -namespace Felidae { -using SentencePieceId = std::size_t; -} -#include "form/NumericOperation.h" -#include "form/RegisterVm.h" -#include "form/TensorOperation.h" - -namespace Felidae { - -enum class IrOpcode : std::uint8_t { - End = 0, - LoadConst, - LoadSymbol, - StoreSymbol, - Move, - Add, - Sub, - Mul, - Div, - Mod, - Compare, - Jump, - JumpIfFalse, - Call, - CallNamed, - Builtin, - SemanticEval, - // [opcode, destination, type-symbol-table index, source-text index]. The - // source index is one-based; zero creates an in-memory fact. A nonzero - // source is emitted only for compiler-linked fact-only .fx database rows. - MakeFact, - MakeArray, - MakeMap, - GetField, - SetField, - Similarity, - Membership, - ForEachFact, - // [opcode, destination, fact-type-symbol index, predicate-map register]. - // Exact named-field filtering uses VmFactStore's declared index planner; - // no runtime query-object representation is introduced. - FactWhere, - FactJoin, - HierarchyIsA, - HierarchyCommonAncestors, - TemporalRank, - Numeric, - Tensor, - Return, - Count -}; - -inline constexpr IrWord kIrOpcodeCount = static_cast(IrOpcode::Count); - -enum class IrComparison : std::uint8_t { - Equal = 0, - NotEqual, - Less, - LessEqual, - Greater, - GreaterEqual -}; - -struct IrConstantEntry { - IrConstantKind kind = IrConstantKind::Number; - IrConstant value = 0; -}; - -struct FelidaeIr { - std::vector words; - std::vector constants; - // Complete SentencePiece sequences are the canonical text representation. - // IR words carry only a bounded side-table index; UTF-8 exists only at - // source and display boundaries. - std::vector texts; - std::vector symbols; - std::vector sourceMap; - std::size_t registerCount = 0; -}; - -struct IrProcedure { - FelidaeIr ir; - std::vector positionalParameters; - std::vector namedParameters; - IrSourceMapEntry::Span sourceSpan; -}; - -class IrVerifier { -public: - static void verify(const FelidaeIr &ir); -}; - -} // namespace Felidae diff --git a/src/FelidaeRuntime.cpp b/src/FelidaeRuntime.cpp index 15a0e78..e4b1d44 100644 --- a/src/FelidaeRuntime.cpp +++ b/src/FelidaeRuntime.cpp @@ -1,8 +1,8 @@ #include "FelidaeRuntime.h" #include "IntegerParser.h" -#include "SentencePieceModel.h" #include "Symbol.h" +#include "Tokenizer.h" #include #include @@ -82,7 +82,8 @@ Program parseProgramFile(const fs::path& path) { } Program parseProgramText(std::string text) { - IntegerTokenList input(felidaeSentencePieceModel(), std::move(text)); + auto tokenizer = std::make_shared(); + IntegerTokenList input(std::move(tokenizer), std::move(text)); return IntegerParser(input).parseProgram(); } @@ -92,7 +93,8 @@ void parseProgramFileStatements( std::shared_ptr operators, ParserMetrics* metrics) { const fs::path normalized = resolveProgramEntryPath(path); - IntegerTokenList input(felidaeSentencePieceModel(), readSourceFile(normalized)); + auto tokenizer = std::make_shared(); + IntegerTokenList input(std::move(tokenizer), readSourceFile(normalized)); IntegerParser parser(input, std::move(operators)); Program program = parser.parseProgram(); for (auto& statement : program.statements) consume(std::move(statement)); @@ -213,14 +215,14 @@ std::vector listCoreLibraries(const fs::path& startDir) { } std::vector> parseQueryText(const std::string& query) { - IntegerTokenList input(felidaeSentencePieceModel(), query); + auto tokenizer = std::make_shared(); + IntegerTokenList input(std::move(tokenizer), query); return IntegerParser(input).parseQuery(); } static void collectVarsExpr(const std::shared_ptr& expr, std::vector& vars) { if (auto v = std::dynamic_pointer_cast(expr)) { if (v->nameId != InternalSymbol::SystemResultId && - !isInternalGeneratedSymbolId(v->nameId) && std::find(vars.begin(), vars.end(), v->nameId) == vars.end()) { vars.push_back(v->nameId); } diff --git a/src/FelidaeTokenizerIds.h b/src/FelidaeTokenizerIds.h new file mode 100644 index 0000000..01dfb45 --- /dev/null +++ b/src/FelidaeTokenizerIds.h @@ -0,0 +1,162 @@ +// Fixed custom-BPE syntax IDs. Model line N owns ID N. Do not reorder. +#pragma once + +#include + +namespace Felidae { +inline constexpr int kFelidaeBuiltinTokenIds[] = { + 1, // IMPORT + 2, // NOT + 3, // AND + 4, // OR + 5, // THEN + 6, // AS + 7, // IF + 8, // ELSE + 9, // RETURN + 10, // WHERE + 11, // EXTEND + 12, // LAMBDA + 13, // TRUE + 14, // FALSE + 15, // NIL + 16, // LPAREN + 17, // RPAREN + 18, // LBRACE + 19, // RBRACE + 20, // LBRACKET + 21, // RBRACKET + 22, // COMMA + 23, // COLON + 24, // DOT + 25, // PIPE + 26, // QUESTION + 27, // AT + 28, // ASSIGN + 29, // DOUBLE_COLON + 30, // ARROW + 31, // PLUS + 32, // MINUS + 33, // STAR + 34, // SLASH + 35, // PERCENT + 36, // EQUAL + 37, // NOT_EQUAL + 38, // LESS + 39, // LESS_EQUAL + 40, // GREATER + 41, // GREATER_EQUAL + 42, // QUOTE + 43, // BACKSLASH + 44, // COMMENT + 45, // SPACE + 46, // TAB + 47, // NEWLINE + 48, // CARRIAGE_RETURN + 49, // DIGIT_0 + 50, // DIGIT_1 + 51, // DIGIT_2 + 52, // DIGIT_3 + 53, // DIGIT_4 + 54, // DIGIT_5 + 55, // DIGIT_6 + 56, // DIGIT_7 + 57, // DIGIT_8 + 58, // DIGIT_9 +}; + +namespace TokenId { +using Id = std::int32_t; +constexpr Id UNKNOWN = 0; +constexpr Id IMPORT = 1; +constexpr Id NOT = 2; +constexpr Id AND = 3; +constexpr Id OR = 4; +constexpr Id THEN = 5; +constexpr Id AS = 6; +constexpr Id IF = 7; +constexpr Id ELSE = 8; +constexpr Id RETURN = 9; +constexpr Id WHERE = 10; +constexpr Id EXTEND = 11; +constexpr Id LAMBDA = 12; +constexpr Id TRUE = 13; +constexpr Id FALSE = 14; +constexpr Id NIL = 15; +constexpr Id LPAREN = 16; +constexpr Id RPAREN = 17; +constexpr Id LBRACE = 18; +constexpr Id RBRACE = 19; +constexpr Id LBRACKET = 20; +constexpr Id RBRACKET = 21; +constexpr Id COMMA = 22; +constexpr Id COLON = 23; +constexpr Id DOT = 24; +constexpr Id PIPE = 25; +constexpr Id QUESTION = 26; +constexpr Id AT = 27; +constexpr Id ASSIGN = 28; +constexpr Id DOUBLE_COLON = 29; +constexpr Id ARROW = 30; +constexpr Id PLUS = 31; +constexpr Id MINUS = 32; +constexpr Id STAR = 33; +constexpr Id SLASH = 34; +constexpr Id PERCENT = 35; +constexpr Id EQUAL = 36; +constexpr Id NOT_EQUAL = 37; +constexpr Id LESS = 38; +constexpr Id LESS_EQUAL = 39; +constexpr Id GREATER = 40; +constexpr Id GREATER_EQUAL = 41; +constexpr Id QUOTE = 42; +constexpr Id BACKSLASH = 43; +constexpr Id COMMENT = 44; +constexpr Id SPACE = 45; +constexpr Id TAB = 46; +constexpr Id NEWLINE = 47; +constexpr Id CARRIAGE_RETURN = 48; +constexpr Id DIGIT_0 = 49; +constexpr Id DIGIT_1 = 50; +constexpr Id DIGIT_2 = 51; +constexpr Id DIGIT_3 = 52; +constexpr Id DIGIT_4 = 53; +constexpr Id DIGIT_5 = 54; +constexpr Id DIGIT_6 = 55; +constexpr Id DIGIT_7 = 56; +constexpr Id DIGIT_8 = 57; +constexpr Id DIGIT_9 = 58; +// Lexer-owned reserved words deliberately sit outside custom-BPE IDs. They +// are syntax only and must never be learned or persisted in model.txt. +constexpr Id CLASS = -1; +constexpr Id END = -2; +constexpr Id INDEX = -3; +constexpr Id EXTENDS = -4; +} // namespace TokenId + +inline constexpr bool isCapitalizedIdentifierStartId(TokenId::Id id) { + switch (id) { + case 124: return true; + case 125: return true; + case 126: return true; + case 127: return true; + case 128: return true; + case 129: return true; + case 130: return true; + case 131: return true; + case 132: return true; + case 139: return true; + case 140: return true; + case 141: return true; + case 142: return true; + case 143: return true; + case 144: return true; + case 145: return true; + case 146: return true; + case 147: return true; + case 148: return true; + case 149: return true; + default: return false; + } +} +} // namespace Felidae diff --git a/src/IntegerParser.cpp b/src/IntegerParser.cpp index 9d6bc2c..0242452 100644 --- a/src/IntegerParser.cpp +++ b/src/IntegerParser.cpp @@ -1,2259 +1,1384 @@ #include "IntegerParser.h" -#include "IrCodeGenerator.h" -#include "MixfixStateModel.h" - #include "BuiltinRegistry.h" #include "Operator.h" #include "OperatorAnnotation.h" -#include "SentencePieceModel.h" -#include "form/SemanticOperation.h" - -#include -#include +#include "Tokenizer.h" #include #include -#include -#include -#include -#include namespace Felidae { namespace { const SymbolId kMainSymbolId = symbolIdForName("main"); -#ifndef NDEBUG -bool parserTraceEnabled() { - static const bool enabled = [] { - const auto *value = std::getenv("FELIDAE_TRACE"); - return value != nullptr && *value != '\0' && std::string_view(value) != "0"; - }(); - return enabled; -} -#endif - -bool isFragmentableBuiltin(TokenId::Id id) { - switch (id) { - case TokenId::IMPORT: - case TokenId::NOT: - case TokenId::AND: - case TokenId::OR: - case TokenId::THEN: - case TokenId::AS: - case TokenId::IF: - case TokenId::ELSE: - case TokenId::RETURN: - case TokenId::WHERE: - case TokenId::EXTEND: - case TokenId::LAMBDA: - case TokenId::NIL: - return true; - default: +bool hasValueReturn(const std::vector>& goals) { + for (const auto& goal : goals) { + if (const auto returned = std::dynamic_pointer_cast(goal)) { + if (!returned->fields.empty()) return true; + } + } return false; - } -} - -std::string pieceFragment(std::string piece) { - // SentencePiece's whitespace marker has no lexical spelling once - // IntegerParser has already skipped trivia. Byte-fallback pieces are - // converted to their original byte so `re` + `turn` and byte fragments - // participate in the same finite matching table. - constexpr std::string_view marker = "\xE2\x96\x81"; - if (piece.starts_with(marker)) - piece.erase(0, marker.size()); - if (piece.size() == 6 && piece.starts_with("<0x") && piece[5] == '>') { - const auto digit = [](char value) -> int { - if (value >= '0' && value <= '9') - return value - '0'; - if (value >= 'A' && value <= 'F') - return value - 'A' + 10; - return -1; - }; - const int high = digit(piece[3]); - const int low = digit(piece[4]); - if (high >= 0 && low >= 0) - return std::string(1, static_cast((high << 4) | low)); - } - return piece; -} - -const std::vector> &builtinPieceSequences(TokenId::Id id) { - static std::unordered_map>> cache; - if (const auto found = cache.find(id); found != cache.end()) - return found->second; - auto &sequences = cache[id]; - const auto spelling = builtinTokenSpelling(id); - if (!isFragmentableBuiltin(id) || spelling.empty()) - return sequences; - const auto &model = felidaeSentencePieceModel(); - std::vector> pieces; - pieces.reserve(static_cast(model.GetPieceSize())); - for (int pieceId = 0; pieceId < model.GetPieceSize(); ++pieceId) { - auto fragment = pieceFragment(model.IdToPiece(pieceId)); - if (!fragment.empty() && fragment.size() <= spelling.size()) { - pieces.emplace_back(pieceId, std::move(fragment)); - } - } - std::vector current; - const auto collect = [&](const auto &self, std::size_t offset) -> void { - if (sequences.size() >= 64) - return; - if (offset == spelling.size()) { - sequences.push_back(current); - return; - } - for (const auto &[pieceId, fragment] : pieces) { - if (!spelling.substr(offset).starts_with(fragment)) - continue; - current.push_back(pieceId); - self(self, offset + fragment.size()); - current.pop_back(); - } - }; - collect(collect, 0); - return sequences; -} - -bool hasValueReturn(const std::vector> &goals) { - for (const auto &goal : goals) { - if (const auto returned = std::dynamic_pointer_cast(goal)) { - if (!returned->fields.empty()) - return true; - } - } - return false; } -bool isMethodStyleHead(const Call &head) { - if (head.args.empty()) - return false; - for (const auto &argument : head.args) { - const auto type = std::dynamic_pointer_cast(argument.value); - if (argument.name.empty() || !type || - (type->languageTypeId == LanguageTypeId::Unknown && - !isFelidaeTypeAnnotationName(type->name))) { - return false; - } - } - return true; +bool isMethodStyleHead(const Call& head) { + if (head.args.empty()) return false; + for (const auto& argument : head.args) { + const auto type = std::dynamic_pointer_cast(argument.value); + if (argument.name.empty() || !type || + (type->languageTypeId == LanguageTypeId::Unknown && + !isFelidaeTypeAnnotationName(type->name))) { + return false; + } + } + return true; } } // namespace -IntegerParser::IntegerParser(const IntegerTokenList &input, - std::shared_ptr operators, - MixfixStateModel *mixfixModel) - : input_(input), operators_(std::move(operators)), - mixfixModel_(mixfixModel) { - lineStarts_.push_back(0); - for (std::size_t offset = 0; offset < input.source().size(); ++offset) { - if (input.source()[offset] == '\r') { - if (offset + 1 < input.source().size() && - input.source()[offset + 1] == '\n') - ++offset; - lineStarts_.push_back(offset + 1); - } else if (input.source()[offset] == '\n') { - lineStarts_.push_back(offset + 1); - } - } - metrics_.sourceEncodeCount = input.encodeCount(); - metrics_.tokenCount = input.loadedSize(); -#ifndef NDEBUG - if (parserTraceEnabled()) { - std::clog << "[felidae.parser] source_bytes=" << input.source().size() - << " sentencepiece_tokens=" << metrics_.tokenCount - << " encode_passes=" << metrics_.sourceEncodeCount << '\n'; - } -#endif +IntegerParser::IntegerParser(const IntegerTokenList& input, + std::shared_ptr operators) + : input_(input), operators_(std::move(operators)) { + metrics_.sourceEncodeCount = input.encodeCount(); + metrics_.tokenCount = input.entries().size(); } -IntegerParser::RecursionScope::RecursionScope(IntegerParser &parser) - : parser_(parser) { - ++parser_.recursionDepth_; - if (parser_.recursionDepth_ > kMaximumRecursionDepth) { - --parser_.recursionDepth_; - throw IntegerParserError("Maximum integer parser recursion depth exceeded"); - } - parser_.metrics_.peakRecursionDepth = - std::max(parser_.metrics_.peakRecursionDepth, parser_.recursionDepth_); +IntegerParser::RecursionScope::RecursionScope(IntegerParser& parser) : parser_(parser) { + ++parser_.recursionDepth_; + if (parser_.recursionDepth_ > kMaximumRecursionDepth) { + --parser_.recursionDepth_; + throw IntegerParserError("Maximum integer parser recursion depth exceeded"); + } + parser_.metrics_.peakRecursionDepth = std::max( + parser_.metrics_.peakRecursionDepth, parser_.recursionDepth_); } IntegerParser::RecursionScope::~RecursionScope() { - if (parser_.recursionDepth_ != 0) - --parser_.recursionDepth_; + if (parser_.recursionDepth_ != 0) --parser_.recursionDepth_; } void IntegerParser::step() { - if (++metrics_.iterations > kMaximumIterations) { - throw IntegerParserError("Integer parser iteration budget exceeded"); - } + if (++metrics_.iterations > kMaximumIterations) { + throw IntegerParserError("Integer parser iteration budget exceeded"); + } } void IntegerParser::alignPiece() { - while (input_.has(piece_) && input_.entry(piece_).end <= byte_) - ++piece_; + const auto& pieces = input_.entries(); + while (piece_ < pieces.size() && pieces[piece_].end <= byte_) ++piece_; } void IntegerParser::skipTrivia() { - while (input_.has(piece_)) { - step(); - const auto id = input_.entry(piece_).id; - if (id == TokenId::SPACE || id == TokenId::TAB || id == TokenId::NEWLINE || - id == TokenId::CARRIAGE_RETURN) { - byte_ = input_.entry(piece_++).end; - continue; - } - if (id == TokenId::COMMENT) { - byte_ = input_.entry(piece_++).end; - while (input_.has(piece_) && - input_.entry(piece_).id != TokenId::NEWLINE && - input_.entry(piece_).id != TokenId::CARRIAGE_RETURN) { - byte_ = input_.entry(piece_++).end; - } - continue; - } - break; - } - alignPiece(); -} - -std::size_t IntegerParser::builtinSequenceLength(TokenId::Id id) const { - if (!input_.has(piece_)) - return 0; - if (input_.entry(piece_).id == id) { - // A word keyword ID immediately followed (no separator) by another - // non-boundary piece is the leading fragment of one longer identifier - // (`import` inside `imported`, `if` inside `ifRequired`, `true` inside - // `trueValue`, ...), not a standalone reserved word here -- this mirrors - // how isIdentifierBoundaryId already treats a keyword ID appearing mid - // identifier, and how atNameRange() claims this same leading position. - // at()/match() must refuse the match so callers such as the `if`-goal - // and boolean-literal dispatch fall through to ordinary name parsing - // instead of misreading a longer identifier as the reserved word. - if (isKeywordWordTokenId(id) && input_.has(piece_ + 1) && - input_.entry(piece_ + 1).begin == input_.entry(piece_).end && - !isIdentifierBoundaryId(input_.entry(piece_ + 1).id)) { - return 0; - } - return 1; - } - if (!isFragmentableBuiltin(id)) - return 0; - for (const auto &sequence : builtinPieceSequences(id)) { - if (sequence.size() < 2 || !input_.has(piece_ + sequence.size() - 1)) - continue; - std::size_t cursor = byte_; - bool matches = true; - for (std::size_t index = 0; index < sequence.size(); ++index) { - const auto &entry = input_.entry(piece_ + index); - if (entry.id != sequence[index] || entry.begin > cursor || - entry.end <= cursor) { - matches = false; + const auto& pieces = input_.entries(); + while (piece_ < pieces.size()) { + step(); + const auto id = pieces[piece_].id; + if (id == TokenId::SPACE || id == TokenId::TAB || id == TokenId::NEWLINE || + id == TokenId::CARRIAGE_RETURN) { + byte_ = pieces[piece_++].end; + continue; + } + if (id == TokenId::COMMENT) { + byte_ = pieces[piece_++].end; + while (piece_ < pieces.size() && pieces[piece_].id != TokenId::NEWLINE && + pieces[piece_].id != TokenId::CARRIAGE_RETURN) { + byte_ = pieces[piece_++].end; + } + continue; + } break; - } - cursor = entry.end; } - if (matches) - return sequence.size(); - } - return 0; + alignPiece(); } bool IntegerParser::at(TokenId::Id id) { - skipTrivia(); - return builtinSequenceLength(id) != 0; + skipTrivia(); + const auto& pieces = input_.entries(); + return piece_ < pieces.size() && pieces[piece_].id == id; } bool IntegerParser::match(TokenId::Id id) { - if (!at(id)) - return false; - const auto count = builtinSequenceLength(id); - byte_ = input_.entry(piece_ + count - 1).end; - piece_ += count; - return true; -} - -bool IntegerParser::matchBindingOperator() { - if (match(TokenId::ASSIGN)) - return true; - const auto savedByte = byte_; - const auto savedPiece = piece_; - // Both global and local obj declarations use ordinary bindings. The - // initializer determines the existing VM value type; no object wrapper. - if (match(TokenId::COLON) && atNameRange() && consumeNameRange() == "obj") { - require(TokenId::EQUAL, "Expected '=' after object declaration"); + if (!at(id)) return false; + const auto& entry = input_.entries()[piece_++]; + byte_ = entry.end; return true; - } - byte_ = savedByte; - piece_ = savedPiece; - return false; } bool IntegerParser::atBlockEnd() { - const auto savedByte = byte_; - const auto savedPiece = piece_; - const bool matched = matchBlockEnd(); - byte_ = savedByte; - piece_ = savedPiece; - return matched; + skipTrivia(); + return piece_ < input_.entries().size() && input_.entries()[piece_].id == TokenId::END; } bool IntegerParser::matchBlockEnd() { - const auto savedByte = byte_; - const auto savedPiece = piece_; - if (!atNameRange() || consumeNameRange() != "end") { - byte_ = savedByte; - piece_ = savedPiece; - return false; - } - - // `end` is contextual rather than a reserved tokenizer ID. It closes a - // block only when it is the complete remaining word on its source line; - // callable names and mixfix anchors containing `end` remain ordinary HIR. - const bool lineBoundary = lineBreakBeforeNextSignificantPiece(); - const bool dotBoundary = !lineBoundary && at(TokenId::DOT); - const bool inputBoundary = !lineBoundary && !dotBoundary && atEnd(); - if (!lineBoundary && !dotBoundary && !inputBoundary) { - byte_ = savedByte; - piece_ = savedPiece; - return false; - } - if (dotBoundary) - (void)match(TokenId::DOT); - return true; + if (!atBlockEnd()) return false; + const auto end = input_.entries()[piece_++].end; + byte_ = end; + if (at(TokenId::DOT)) (void)match(TokenId::DOT); + return true; } -void IntegerParser::require(TokenId::Id id, const char *message) { - if (!match(id)) { - throw IntegerParserError(std::string(message) + " at source byte " + - std::to_string(byte_)); - } +void IntegerParser::require(TokenId::Id id, const char* message) { + if (!match(id)) { + throw IntegerParserError(std::string(message) + " at source byte " + std::to_string(byte_)); + } } bool IntegerParser::atEnd() { - skipTrivia(); - const auto ended = !input_.has(piece_); - metrics_.sourceEncodeCount = input_.encodeCount(); - metrics_.tokenCount = input_.loadedSize(); - return ended; + skipTrivia(); + return piece_ >= input_.entries().size(); } -bool IntegerParser::atNameRange(bool allowLoneKeyword) { - skipTrivia(); - if (!input_.has(piece_)) - return false; - const auto id = input_.entry(piece_).id; - // A qualified-name segment right after `.`/`:`/`::` (School.where, - // Type.all, Type.select, ...) has no competing grammar interpretation: a - // separator is never followed by the start of a new statement, so a - // keyword spelling standing entirely alone there is unambiguously a name - // segment, not the reserved word. Callers outside that continuation loop - // never pass allowLoneKeyword, so `where`/`if`/... still open their normal - // constructs everywhere else. - if (allowLoneKeyword && isKeywordWordTokenId(id)) - return true; - // A word keyword ID is atomic grammar vocabulary when it stands alone. - // SentencePiece also emits that same ID as the leading piece of a longer - // identifier -- `import` inside `imported`, `if` inside `ifRequired`, - // `and` inside `andy`, `or` inside `orange`, `not` inside `notice`, and so - // on for every word entry in kBuiltinTokens, not just `as`/`Assessment`. - // Restricted to word keywords, never punctuation/digit builtin IDs: `.` - // immediately followed by a digit (`190.0`) or a name (`csv.toFacts`) is - // not an identifier fragment, and isIdentifierBoundaryId's own comment - // already establishes that only keyword IDs get this treatment. A keyword - // ID already stops being a boundary once an identifier range is under way - // (see isIdentifierBoundaryId); the same contiguity test applies here so a - // keyword ID at the very start of a name position gets the same treatment - // instead of unconditionally reading as the reserved word. - if (isKeywordWordTokenId(id) && input_.has(piece_ + 1) && - input_.entry(piece_ + 1).begin == input_.entry(piece_).end && - !isIdentifierBoundaryId(input_.entry(piece_ + 1).id)) { - return true; - } - if (id == TokenId::AS) { - // `foo(as: value)` uses `as` as a named-argument key: not merged with a - // following identifier piece, but still a name position here, set apart - // from the postfix `as` fact-designation keyword by the trailing colon. - std::size_t following = piece_ + 1; - while (input_.has(following) && - (input_.entry(following).id == TokenId::SPACE || - input_.entry(following).id == TokenId::TAB)) { - ++following; - } - if (input_.has(following) && input_.entry(following).id == TokenId::COLON) - return true; - } - return !isBuiltinTokenId(id) && id != TokenId::UNKNOWN; +bool IntegerParser::atNameRange() { + skipTrivia(); + const auto& pieces = input_.entries(); + if (piece_ >= pieces.size()) return false; + const auto id = pieces[piece_].id; + // `as` is an atomic grammar ID when it stands alone after a fact or query. + // The BPE tokenizer also emits that same ID as the prefix of identifiers such + // as `Assessment`; contiguous IDs are one identifier range, never a + // grammar boundary. + if (id == TokenId::AS) { + if (piece_ + 1 < pieces.size() && + pieces[piece_ + 1].begin == pieces[piece_].end && + !isIdentifierBoundaryId(pieces[piece_ + 1].id)) { + return true; + } + std::size_t following = piece_ + 1; + while (following < pieces.size() && + (pieces[following].id == TokenId::SPACE || pieces[following].id == TokenId::TAB)) { + ++following; + } + if (following < pieces.size() && pieces[following].id == TokenId::COLON) return true; + } + return id > TokenId::UNKNOWN && !isBuiltinTokenId(id); } -bool IntegerParser::sourceContainsLineBreak(std::size_t begin, - std::size_t end) const { - return input_.source().find_first_of("\r\n", begin) < end; +bool IntegerParser::sourceContainsLineBreak(std::size_t begin, std::size_t end) const { + for (const auto& entry : input_.entries()) { + if (entry.end <= begin || entry.begin >= end) continue; + if (entry.id == TokenId::NEWLINE || entry.id == TokenId::CARRIAGE_RETURN) return true; + } + return false; } bool IntegerParser::lineBreakBeforeNextSignificantPiece() const { - bool inComment = false; - for (std::size_t index = piece_; input_.has(index); ++index) { - const auto id = input_.entry(index).id; - if (id == TokenId::NEWLINE || id == TokenId::CARRIAGE_RETURN) - return true; - if (inComment) - continue; - if (id == TokenId::COMMENT) { - inComment = true; - continue; - } - if (id != TokenId::SPACE && id != TokenId::TAB) - return false; - } - return false; + const auto& source = input_.source(); + for (std::size_t index = byte_; index < source.size(); ++index) { + const char byte = source[index]; + if (byte == '\n' || byte == '\r') return true; + if (byte == '#') { + const auto newline = source.find_first_of("\r\n", index); + return newline != std::string::npos; + } + if (byte != ' ' && byte != '\t') return false; + } + return false; } std::size_t IntegerParser::sourceLineIndent(std::size_t offset) const { - const auto previous = offset == 0 - ? std::string::npos - : input_.source().find_last_of("\r\n", offset - 1); - const auto begin = previous == std::string::npos ? 0 : previous + 1; - std::size_t indent = 0; - for (auto index = begin; index < offset && index < input_.source().size(); - ++index) { - if (input_.source()[index] == ' ') - ++indent; - else if (input_.source()[index] == '\t') - indent += 4; - else - break; - } - return indent; + std::size_t indent = 0; + bool afterLineBreak = true; + for (const auto& entry : input_.entries()) { + if (entry.begin >= offset) break; + if (entry.id == TokenId::NEWLINE || entry.id == TokenId::CARRIAGE_RETURN) { + indent = 0; + afterLineBreak = true; + } else if (afterLineBreak && entry.id == TokenId::SPACE) { + ++indent; + } else if (afterLineBreak && entry.id == TokenId::TAB) { + indent += 4; + } else { + afterLineBreak = false; + } + } + return indent; } void IntegerParser::consumeStatementTerminator(std::size_t statementBegin) { - if (match(TokenId::DOT) || atEnd()) - return; - if (sourceContainsLineBreak(statementBegin, byte_)) - return; - throw IntegerParserError( - "Expected '.' or newline after statement at source byte " + - std::to_string(byte_)); + if (match(TokenId::DOT) || atEnd()) return; + if (sourceContainsLineBreak(statementBegin, byte_)) return; + throw IntegerParserError("Expected '.' or newline after statement at source byte " + + std::to_string(byte_)); } -std::string IntegerParser::consumeNameRange(bool allowLoneKeyword) { - skipTrivia(); - if (!atNameRange(allowLoneKeyword)) { - const auto id = - input_.has(piece_) ? input_.entry(piece_).id : TokenId::UNKNOWN; - throw IntegerParserError( - "Expected a SentencePiece name range at source byte " + - std::to_string(byte_) + " (ID " + std::to_string(id) + ")"); - } - const std::size_t begin = byte_; - const std::size_t firstPiece = piece_; - // A logical name is a contiguous run of non-grammar SentencePiece IDs. - // SentencePiece may split one source name into many adjacent pieces. - while (input_.has(piece_)) { - const auto id = input_.entry(piece_).id; - if (id == TokenId::UNKNOWN || isIdentifierBoundaryId(id)) - break; - byte_ = input_.entry(piece_++).end; - } - if (byte_ == begin) - throw IntegerParserError("Empty SentencePiece name range"); - auto spelling = input_.source().substr(begin, byte_ - begin); - std::vector pieces; - pieces.reserve(piece_ - firstPiece); - for (std::size_t index = firstPiece; index < piece_; ++index) - pieces.push_back(static_cast(input_.entry(index).id)); - (void)symbolIdForPieces(spelling, pieces); - return spelling; +std::string IntegerParser::consumeNameRange() { + skipTrivia(); + if (!atNameRange()) { + const auto id = piece_ < input_.entries().size() ? input_.entries()[piece_].id : TokenId::UNKNOWN; + throw IntegerParserError("Expected a token name range at source byte " + + std::to_string(byte_) + " (ID " + std::to_string(id) + ")"); + } + const std::size_t begin = byte_; + const auto& pieces = input_.entries(); + // A logical name is a contiguous run of non-grammar token IDs. + // BPE may split one source name into many adjacent pieces. + while (piece_ < pieces.size()) { + const auto id = pieces[piece_].id; + if (id == TokenId::UNKNOWN || isIdentifierBoundaryId(id)) break; + byte_ = pieces[piece_++].end; + } + if (byte_ == begin) throw IntegerParserError("Empty token name range"); + return input_.source().substr(begin, byte_ - begin); } -IntegerParser::StringLiteral IntegerParser::consumeString() { - require(TokenId::QUOTE, "Expected a string literal"); - std::vector ids; - bool containsEscape = false; - while (input_.has(piece_)) { - const auto id = input_.entry(piece_).id; - if (id == TokenId::QUOTE) { - byte_ = input_.entry(piece_++).end; - std::string value; - const auto status = felidaeSentencePieceModel().Decode(ids, &value); - if (!status.ok()) - throw IntegerParserError("Unable to decode string literal IDs"); - // SentencePiece faithfully decodes the lexical escape marker. A - // Felidae string value owns the escaped character instead, so do - // this value-level normalization after decoding; grammar parsing - // never falls back to scanning source characters. - std::string unescaped; - unescaped.reserve(value.size()); - for (std::size_t index = 0; index < value.size(); ++index) { - if (value[index] != '\\' || index + 1 == value.size()) { - unescaped.push_back(value[index]); - continue; - } - const char escaped = value[++index]; - switch (escaped) { - case 'n': - unescaped.push_back('\n'); - break; - case 'r': - unescaped.push_back('\r'); - break; - case 't': - unescaped.push_back('\t'); - break; - case '\\': - unescaped.push_back('\\'); - break; - case '"': - unescaped.push_back('"'); - break; - default: - unescaped.push_back('\\'); - unescaped.push_back(escaped); - break; +std::string IntegerParser::consumeString() { + require(TokenId::QUOTE, "Expected a string literal"); + const std::size_t begin = byte_; + while (piece_ < input_.entries().size()) { + const auto id = input_.entries()[piece_].id; + if (id == TokenId::QUOTE) { + const std::size_t end = input_.entries()[piece_].begin; + byte_ = input_.entries()[piece_++].end; + // Literal content is a lexer-owned source span; BPE supplies IDs + // only for identifiers and mixfix anchors. + const std::string value = input_.source().substr(begin, end - begin); + std::string unescaped; + unescaped.reserve(value.size()); + for (std::size_t index = 0; index < value.size(); ++index) { + if (value[index] != '\\' || index + 1 == value.size()) { + unescaped.push_back(value[index]); + continue; + } + const char escaped = value[++index]; + switch (escaped) { + case 'n': unescaped.push_back('\n'); break; + case 'r': unescaped.push_back('\r'); break; + case 't': unescaped.push_back('\t'); break; + case '\\': unescaped.push_back('\\'); break; + case '"': unescaped.push_back('"'); break; + default: + unescaped.push_back('\\'); + unescaped.push_back(escaped); + break; + } + } + return unescaped; } - } - StringLiteral literal; - literal.value = std::move(unescaped); - literal.containsEscape = containsEscape; - literal.sentencePieceIds.reserve(ids.size()); - for (const auto piece : ids) { - if (piece < 0) - throw IntegerParserError( - "SentencePiece emitted an invalid string piece"); - literal.sentencePieceIds.push_back(static_cast(piece)); - } - return literal; - } - if (id == TokenId::BACKSLASH) { - containsEscape = true; - ids.push_back(id); - byte_ = input_.entry(piece_++).end; - if (!input_.has(piece_)) - throw IntegerParserError("Unterminated string escape"); - } - ids.push_back(input_.entry(piece_).id); - byte_ = input_.entry(piece_++).end; - } - throw IntegerParserError("Unterminated string literal"); + byte_ = input_.entries()[piece_++].end; + } + throw IntegerParserError("Unterminated string literal"); } double IntegerParser::consumeNumber() { - skipTrivia(); - double value = 0.0; - bool consumed = false; - while (input_.has(piece_) && isDecimalDigitId(input_.entry(piece_).id)) { - value = value * 10.0 + - static_cast(input_.entry(piece_).id - TokenId::DIGIT_0); - byte_ = input_.entry(piece_++).end; - consumed = true; - } - const auto integerEnd = byte_; - if (at(TokenId::DOT) && input_.entry(piece_).begin == integerEnd && - input_.has(piece_ + 1) && - input_.entry(piece_).end == input_.entry(piece_ + 1).begin && - isDecimalDigitId(input_.entry(piece_ + 1).id)) { - match(TokenId::DOT); - double scale = 0.1; - while (input_.has(piece_) && isDecimalDigitId(input_.entry(piece_).id)) { - value += static_cast(input_.entry(piece_).id - TokenId::DIGIT_0) * - scale; - scale *= 0.1; - byte_ = input_.entry(piece_++).end; - } - } - if (!consumed) - throw IntegerParserError("Expected a number literal"); - return value; + skipTrivia(); + double value = 0.0; + bool consumed = false; + while (piece_ < input_.entries().size() && isDecimalDigitId(input_.entries()[piece_].id)) { + value = value * 10.0 + static_cast(input_.entries()[piece_].id - TokenId::DIGIT_0); + byte_ = input_.entries()[piece_++].end; + consumed = true; + } + if (at(TokenId::DOT) && piece_ + 1 < input_.entries().size() && + isDecimalDigitId(input_.entries()[piece_ + 1].id)) { + match(TokenId::DOT); + double scale = 0.1; + while (piece_ < input_.entries().size() && isDecimalDigitId(input_.entries()[piece_].id)) { + value += static_cast(input_.entries()[piece_].id - TokenId::DIGIT_0) * scale; + scale *= 0.1; + byte_ = input_.entries()[piece_++].end; + } + } + if (!consumed) throw IntegerParserError("Expected a number literal"); + return value; } std::shared_ptr IntegerParser::parseArray() { - const std::size_t begin = byte_; - require(TokenId::LBRACKET, "Expected '['"); - std::vector> items; - if (!at(TokenId::RBRACKET)) { - do { - items.push_back(parseExpression()); - } while (match(TokenId::COMMA)); - } - require(TokenId::RBRACKET, "Expected ']' after array"); - auto result = std::make_shared(std::move(items)); - stamp(result, begin, byte_); - return result; + const std::size_t begin = byte_; + require(TokenId::LBRACKET, "Expected '['"); + std::vector> items; + if (!at(TokenId::RBRACKET)) { + do { + items.push_back(parseExpression()); + } while (match(TokenId::COMMA)); + } + require(TokenId::RBRACKET, "Expected ']' after array"); + auto result = std::make_shared(std::move(items)); + stamp(result, begin, byte_); + return result; } std::vector IntegerParser::parseArguments(bool allowAnnotationBindings) { - require(TokenId::LPAREN, "Expected '('"); - std::vector arguments; - if (!at(TokenId::RPAREN)) { - do { - skipTrivia(); - const std::size_t before = byte_; - QualifiedName name; - bool named = false; - if (atNameRange()) { - const auto nameStart = byte_; - const auto pieceStart = piece_; - const auto candidate = consumeQualifiedName(false); - if (match(TokenId::COLON)) { - name = candidate; - named = true; - } else { - byte_ = nameStart; - piece_ = pieceStart; - } - } - std::shared_ptr value; - if (allowAnnotationBindings && named && at(TokenId::LBRACKET)) { - require(TokenId::LBRACKET, "Expected '[' for annotation bindings"); - std::vector> bindings; - if (!at(TokenId::RBRACKET)) { - do { - const auto binding = consumeQualifiedName(false); - require(TokenId::COLON, - "Expected ':' after annotation binding name"); - const auto type = consumeQualifiedName(); - auto typeExpr = std::make_shared( - type.spelling, type.nameId, - languageTypeIdForName(type.spelling), type.isCapitalized); - bindings.push_back( - std::make_shared(std::vector{MapEntry{ - binding.spelling, binding.nameId, std::move(typeExpr)}})); - } while (match(TokenId::COMMA)); - } - require(TokenId::RBRACKET, "Expected ']' after annotation bindings"); - value = std::make_shared(std::move(bindings)); - } else if (allowAnnotationBindings && named && atNameRange()) { - const auto valueByte = byte_; - const auto valuePiece = piece_; - const auto binding = consumeQualifiedName(false); - if (match(TokenId::COLON)) { - const auto type = consumeQualifiedName(); - auto typeExpr = std::make_shared( - type.spelling, type.nameId, languageTypeIdForName(type.spelling), - type.isCapitalized); - value = std::make_shared(std::vector{ - MapEntry{binding.spelling, binding.nameId, std::move(typeExpr)}}); - } else { - byte_ = valueByte; - piece_ = valuePiece; - } - } - if (!value) - value = parseExpression(); - if (byte_ == before) - throw IntegerParserError( - "Integer parser made no progress in argument list"); - arguments.emplace_back(named ? std::move(name.spelling) : std::string{}, - named ? name.nameId : 0, std::move(value)); - } while (match(TokenId::COMMA)); - } - require(TokenId::RPAREN, "Expected ')' after arguments"); - return arguments; + require(TokenId::LPAREN, "Expected '('"); + std::vector arguments; + if (!at(TokenId::RPAREN)) { + do { + skipTrivia(); + const std::size_t before = byte_; + QualifiedName name; + bool named = false; + if (atNameRange()) { + const auto nameStart = byte_; + const auto pieceStart = piece_; + const auto candidate = consumeQualifiedName(false); + if (match(TokenId::COLON)) { + name = candidate; + named = true; + } + else { + byte_ = nameStart; + piece_ = pieceStart; + } + } + std::shared_ptr value; + if (allowAnnotationBindings && named && at(TokenId::LBRACKET)) { + require(TokenId::LBRACKET, "Expected '[' for annotation bindings"); + std::vector> bindings; + if (!at(TokenId::RBRACKET)) { + do { + const auto binding = consumeQualifiedName(false); + require(TokenId::COLON, "Expected ':' after annotation binding name"); + const auto type = consumeQualifiedName(); + auto typeExpr = std::make_shared( + type.spelling, type.nameId, languageTypeIdForName(type.spelling), + type.isCapitalized); + bindings.push_back(std::make_shared(std::vector{ + MapEntry{binding.spelling, binding.nameId, std::move(typeExpr)}})); + } while (match(TokenId::COMMA)); + } + require(TokenId::RBRACKET, "Expected ']' after annotation bindings"); + value = std::make_shared(std::move(bindings)); + } else if (allowAnnotationBindings && named && atNameRange()) { + const auto valueByte = byte_; + const auto valuePiece = piece_; + const auto binding = consumeQualifiedName(false); + if (match(TokenId::COLON)) { + const auto type = consumeQualifiedName(); + auto typeExpr = std::make_shared( + type.spelling, type.nameId, languageTypeIdForName(type.spelling), + type.isCapitalized); + value = std::make_shared(std::vector{ + MapEntry{binding.spelling, binding.nameId, std::move(typeExpr)}}); + } else { + byte_ = valueByte; + piece_ = valuePiece; + } + } + if (!value) value = parseExpression(); + if (byte_ == before) throw IntegerParserError("Integer parser made no progress in argument list"); + arguments.emplace_back(named ? std::move(name.spelling) : std::string{}, + named ? name.nameId : 0, std::move(value)); + } while (match(TokenId::COMMA)); + } + require(TokenId::RPAREN, "Expected ')' after arguments"); + return arguments; } -IntegerParser::QualifiedName -IntegerParser::consumeQualifiedName(bool allowNamespaceSeparators) { - const auto firstPiece = piece_; - const bool capitalized = input_.has(piece_) && isCapitalizedIdentifierStartId( - input_.entry(piece_).id); - QualifiedName name{consumeNameRange(), 0, BuiltinId::Unknown, capitalized}; - while (at(TokenId::DOT) || - (allowNamespaceSeparators && - (at(TokenId::COLON) || at(TokenId::DOUBLE_COLON)))) { - const auto beforeByte = byte_; - const auto beforePiece = piece_; - const auto separator = input_.entry(piece_).id; - match(separator); - const auto separatorEnd = byte_; - // A dot followed immediately by a name continues a qualified name. - // Whitespace after it instead leaves a statement terminator for the - // caller. Keyword members such as School.where remain valid names. - if (!atNameRange(/*allowLoneKeyword=*/true) || - (separator == TokenId::DOT ? byte_ != separatorEnd - : sourceContainsLineBreak(separatorEnd, byte_))) { - byte_ = beforeByte; - piece_ = beforePiece; - break; - } - name.spelling += separator == TokenId::DOT ? "." - : separator == TokenId::COLON ? ":" - : "::"; - name.spelling += consumeNameRange(/*allowLoneKeyword=*/true); - } - std::vector ids; - ids.reserve(piece_ - firstPiece); - for (std::size_t index = firstPiece; index < piece_; ++index) { - const auto id = input_.entry(index).id; - if (id != TokenId::SPACE && id != TokenId::TAB && id != TokenId::NEWLINE && - id != TokenId::CARRIAGE_RETURN) { - ids.push_back(id); - } - } - std::vector symbolPieces(ids.begin(), ids.end()); - name.nameId = symbolIdForPieces(name.spelling, symbolPieces); - name.builtinId = builtinIdForPieceIds(ids); - return name; +IntegerParser::QualifiedName IntegerParser::consumeQualifiedName(bool allowNamespaceSeparators, + bool allowDottedName) { + skipTrivia(); + const auto firstPiece = piece_; + const bool capitalized = + piece_ < input_.entries().size() && + std::isupper(static_cast(input_.source().at( + input_.entries()[piece_].begin))) != 0; + QualifiedName name{consumeNameRange(), 0, BuiltinId::Unknown, capitalized}; + while ((allowDottedName && !capitalized && at(TokenId::DOT)) || + (allowNamespaceSeparators && (at(TokenId::COLON) || at(TokenId::DOUBLE_COLON)))) { + const auto beforeByte = byte_; + const auto beforePiece = piece_; + const auto separator = input_.entries()[piece_].id; + match(separator); + const auto separatorEnd = byte_; + if (!atNameRange() || sourceContainsLineBreak(separatorEnd, byte_)) { + byte_ = beforeByte; + piece_ = beforePiece; + break; + } + name.spelling += separator == TokenId::DOT ? "." : + separator == TokenId::COLON ? ":" : "::"; + name.spelling += consumeNameRange(); + } + std::vector ids; + ids.reserve(piece_ - firstPiece); + for (std::size_t index = firstPiece; index < piece_; ++index) { + const auto id = input_.entries()[index].id; + if (id != TokenId::SPACE && id != TokenId::TAB && + id != TokenId::NEWLINE && id != TokenId::CARRIAGE_RETURN) { + ids.push_back(id); + } + } + name.nameId = symbolIdForName(name.spelling); + name.builtinId = builtinIdForName(name.spelling); + return name; } Call IntegerParser::parseCall() { - const std::size_t begin = byte_; - const auto name = consumeQualifiedName(); - if (!at(TokenId::LPAREN)) - throw IntegerParserError("Expected '(' after call name"); - Call result(name.spelling, name.nameId, parseArguments(), name.builtinId); - result.sourceSpan = span(begin, byte_); - return result; + const std::size_t begin = byte_; + const auto name = consumeQualifiedName(); + if (!at(TokenId::LPAREN)) throw IntegerParserError("Expected '(' after call name"); + Call result(name.spelling, name.nameId, parseArguments(), name.builtinId); + result.sourceSpan = span(begin, byte_); + return result; } Call IntegerParser::parseAnnotation() { - require(TokenId::AT, "Expected '@'"); - const auto name = consumeQualifiedName(); - if (!at(TokenId::LPAREN)) { - throw IntegerParserError("Annotation method '" + name.spelling + - "' requires an argument list"); - } - return Call(name.spelling, name.nameId, parseArguments(true), name.builtinId); + require(TokenId::AT, "Expected '@'"); + const auto name = consumeQualifiedName(); + if (!at(TokenId::LPAREN)) { + throw IntegerParserError("Annotation method '" + name.spelling + "' requires an argument list"); + } + return Call(name.spelling, name.nameId, parseArguments(true), name.builtinId); } -const OperatorPatternDefinition & -IntegerParser::registerOperatorPattern(OperatorPatternDefinition pattern) { - if (!operators_) - throw IntegerParserError("Operator registry is unavailable"); - // Pattern structure is registered independently from source IDs. Literal - // anchors use the absolute offsets in the line-wise SentencePiece stream; - // do not encode each anchor again. - OperatorRegistry::compilePattern(pattern); - return operators_->registerPattern(std::move(pattern)); +const OperatorPatternDefinition& IntegerParser::registerOperatorPattern( + OperatorPatternDefinition pattern) { + if (!operators_) throw IntegerParserError("Operator registry is unavailable"); + // Pattern structure is parsed once by the registry. Its literal anchors + // are then encoded once into model-local integer sequences, before the + // pattern becomes visible to the integer matcher. + OperatorRegistry::compilePattern(pattern); + for (auto& anchor : pattern.anchorLexemes) { + for (auto& lexeme : anchor) { + const auto encoded = input_.tokenizer().encode(lexeme.spelling); + if (encoded.empty()) { + throw IntegerParserError("Unable to encode mixfix anchor '" + lexeme.spelling + "'"); + } + lexeme.pieceIds.clear(); + lexeme.pieceIds.reserve(encoded.size()); + for (const auto piece : encoded) + lexeme.pieceIds.push_back(static_cast(piece)); + } + } + return operators_->registerPattern(std::move(pattern)); } -void IntegerParser::prepareOperatorAnnotation(const Call &annotation) { - const bool overload = annotation.builtinId == BuiltinId::OverloadAnnotation || - annotation.name == "overload"; - const bool mixfix = annotation.builtinId == BuiltinId::MixfixAnnotation || - annotation.name == "mixfix"; - const bool matcherAnnotation = - annotation.builtinId == BuiltinId::MatcherAnnotation || - annotation.name == "matcher"; - if (!operators_ || (!overload && !mixfix && !matcherAnnotation)) - return; - // SentencePiece may fragment an annotation spelling differently while the - // canonical decoded name remains exact. Normalize the parser-owned call - // here rather than requiring one tokenization for language syntax. - Call normalized = annotation; - if (overload) - normalized.builtinId = BuiltinId::OverloadAnnotation; - else if (mixfix) - normalized.builtinId = BuiltinId::MixfixAnnotation; - else - normalized.builtinId = BuiltinId::MatcherAnnotation; - ParsedOperatorAnnotation parsed; - try { - parsed = decodeOperatorAnnotation(normalized); - } catch (const std::runtime_error &error) { - throw IntegerParserError(error.what()); - } - const bool matcher = normalized.builtinId == BuiltinId::MatcherAnnotation; - const OperatorPatternDefinition *pattern = nullptr; - try { - if (parsed.pattern.empty()) { - pattern = operators_->findPatternByOperator(parsed.operatorName); - if (!pattern) - throw IntegerParserError( - matcher +void IntegerParser::prepareOperatorAnnotation(const Call& annotation) { + if (!operators_ || (annotation.builtinId != BuiltinId::OverloadAnnotation && + annotation.builtinId != BuiltinId::MixfixAnnotation && + annotation.builtinId != BuiltinId::MatcherAnnotation)) return; + ParsedOperatorAnnotation parsed; + try { + parsed = decodeOperatorAnnotation(annotation); + } catch (const std::runtime_error& error) { + throw IntegerParserError(error.what()); + } + const bool matcher = annotation.builtinId == BuiltinId::MatcherAnnotation; + const OperatorPatternDefinition* pattern = nullptr; + try { + if (parsed.pattern.empty()) { + pattern = operators_->findPatternByOperator(parsed.operatorName); + if (!pattern) throw IntegerParserError(matcher ? "@matcher requires an operator pattern declared by @overload" : "Initial operator overload requires 'pattern'"); - } else { - pattern = operators_->findPattern(parsed.operatorName, parsed.pattern); - if (!pattern) { - OperatorPatternDefinition definition; - definition.operatorName = parsed.operatorName; - definition.pattern = parsed.pattern; - for (const auto &capture : parsed.captures) - definition.captureTypeNames.push_back(capture.type); - definition.precedence = parsed.precedence; - definition.associativity = parsed.associativity; - definition.fixity = parsed.fixity; - definition.hasDeclaredFixity = parsed.hasFixity; - definition.inferFixityFromPattern = - parsed.kind == BuiltinId::MixfixAnnotation; - definition.isMixfixDeclaration = - parsed.kind == BuiltinId::MixfixAnnotation; - definition.visibility = parsed.visibility; - pattern = ®isterOperatorPattern(std::move(definition)); - } - } - // The interpreter registers overload/matcher implementations only - // after the annotated method clause is complete. Parsing registers - // syntax here so subsequent source can be assembled by integer IDs. - (void)matcher; - } catch (const std::runtime_error &error) { - throw IntegerParserError(error.what()); - } + } else { + pattern = operators_->findPattern(parsed.operatorName, parsed.pattern); + if (!pattern) { + OperatorPatternDefinition definition; + definition.operatorName = parsed.operatorName; + definition.pattern = parsed.pattern; + for (const auto& capture : parsed.captures) definition.captureTypeNames.push_back(capture.type); + definition.precedence = parsed.precedence; + definition.associativity = parsed.associativity; + definition.fixity = parsed.fixity; + definition.hasDeclaredFixity = parsed.hasFixity; + definition.inferFixityFromPattern = parsed.kind == BuiltinId::MixfixAnnotation; + definition.isMixfixDeclaration = parsed.kind == BuiltinId::MixfixAnnotation; + definition.visibility = parsed.visibility; + pattern = ®isterOperatorPattern(std::move(definition)); + } + } + // The interpreter registers overload/matcher implementations only + // after the annotated method clause is complete. Parsing registers + // syntax here so subsequent source can be assembled by integer IDs. + (void)matcher; + } catch (const std::runtime_error& error) { + throw IntegerParserError(error.what()); + } } std::shared_ptr IntegerParser::parseGoal() { - skipTrivia(); - const std::size_t begin = byte_; - if (match(TokenId::IF)) { - auto conditionExpression = parseBinaryExpression( - static_cast(OperatorPrecedence::Control), TokenId::THEN); - require(TokenId::THEN, "Expected 'then' after if condition"); - std::shared_ptr condition; - if (const auto comparison = - std::dynamic_pointer_cast(conditionExpression); - comparison && comparison->captureCount() == 2 && - isComparisonOperator(comparison->coreOperator)) { - condition = std::make_shared( - comparison->capture(0), - coreOperatorDefinition(comparison->coreOperator).token, - comparison->capture(1)); - } else { - condition = std::make_shared( - std::move(conditionExpression), TokenId::EQUAL, - std::make_shared(true)); - } - auto thenBranch = parseGoalList(TokenId::DOT); - std::vector> elseBranch; - if (match(TokenId::ELSE)) - elseBranch = parseGoalList(TokenId::DOT); - (void)matchBlockEnd(); - auto result = std::make_shared( - std::move(condition), std::move(thenBranch), std::move(elseBranch)); - stamp(result, begin, byte_); - return result; - } - if (match(TokenId::WHERE)) { - auto expression = parseExpression(); - // Mirrors the `if`-goal condition just above: a plain two-capture - // comparison lowers straight to a BinaryGoal, and anything else -- - // `a and b`, `a or b`, a negation, a nested comparison chain -- lowers by - // comparing the whole expression's truth value against `true`, the same - // fallback `if` already relies on for compound conditions. `where` had - // no such fallback and rejected every compound condition outright; nothing - // else about guard-chain desugaring needed to change since it already - // just consumes `where->condition` as an ordinary Goal. - std::shared_ptr condition; - if (const auto comparison = - std::dynamic_pointer_cast(expression); - comparison && comparison->captureCount() == 2 && - isComparisonOperator(comparison->coreOperator)) { - condition = std::make_shared( - comparison->capture(0), - coreOperatorDefinition(comparison->coreOperator).token, - comparison->capture(1)); - } else { - condition = std::make_shared( - std::move(expression), TokenId::EQUAL, - std::make_shared(true)); - } - auto result = std::make_shared(std::move(condition)); - stamp(result, begin, byte_); - return result; - } - if (match(TokenId::LPAREN)) { - auto grouped = parseGoalList(TokenId::RPAREN); - require(TokenId::RPAREN, "Expected ')' after grouped goals"); - if (grouped.size() == 1) - return grouped.front(); - auto result = std::make_shared(std::move(grouped)); - stamp(result, begin, byte_); - return result; - } - if (match(TokenId::RETURN)) { - std::vector fields; - // `match` intentionally skips trivia, therefore this boundary must - // be observed before probing for the optional parenthesized form. - const bool terminatedByLineBreak = lineBreakBeforeNextSignificantPiece(); - if (!terminatedByLineBreak && match(TokenId::LPAREN)) { - if (!at(TokenId::RPAREN)) { - do { - skipTrivia(); - std::string name; - const auto fieldByte = byte_; - const auto fieldPiece = piece_; - if (atNameRange()) { - const auto candidate = consumeNameRange(); - if (match(TokenId::COLON)) - name = candidate; - else { - byte_ = fieldByte; - piece_ = fieldPiece; + skipTrivia(); + const std::size_t begin = byte_; + if (match(TokenId::IF)) { + auto conditionExpression = parseBinaryExpression( + static_cast(OperatorPrecedence::Control), TokenId::THEN); + require(TokenId::THEN, "Expected 'then' after if condition"); + std::shared_ptr condition; + if (const auto comparison = std::dynamic_pointer_cast(conditionExpression); + comparison && comparison->captureCount() == 2 && + isComparisonOperator(comparison->coreOperator)) { + condition = std::make_shared(comparison->capture(0), + coreOperatorDefinition(comparison->coreOperator).token, comparison->capture(1)); + } else { + condition = std::make_shared(std::move(conditionExpression), TokenId::EQUAL, + std::make_shared(true)); + } + auto thenBranch = parseGoalList(TokenId::DOT); + std::vector> elseBranch; + if (match(TokenId::ELSE)) elseBranch = parseGoalList(TokenId::DOT); + (void)matchBlockEnd(); + auto result = std::make_shared(std::move(condition), std::move(thenBranch), + std::move(elseBranch)); + stamp(result, begin, byte_); + return result; + } + if (match(TokenId::WHERE)) { + auto expression = parseExpression(); + const auto comparison = std::dynamic_pointer_cast(expression); + if (!comparison || comparison->captureCount() != 2 || + !isComparisonOperator(comparison->coreOperator)) { + throw IntegerParserError("Expected comparison after 'where'"); + } + auto binary = std::make_shared(comparison->capture(0), + coreOperatorDefinition(comparison->coreOperator).token, comparison->capture(1)); + auto result = std::make_shared(std::move(binary)); + stamp(result, begin, byte_); + return result; + } + if (match(TokenId::LPAREN)) { + auto grouped = parseGoalList(TokenId::RPAREN); + require(TokenId::RPAREN, "Expected ')' after grouped goals"); + if (grouped.size() == 1) return grouped.front(); + auto result = std::make_shared(std::move(grouped)); + stamp(result, begin, byte_); + return result; + } + if (match(TokenId::RETURN)) { + std::vector fields; + // `match` intentionally skips trivia, therefore this boundary must + // be observed before probing for the optional parenthesized form. + const bool terminatedByLineBreak = lineBreakBeforeNextSignificantPiece(); + if (!terminatedByLineBreak && match(TokenId::LPAREN)) { + if (!at(TokenId::RPAREN)) { + do { + skipTrivia(); + std::string name; + const auto fieldByte = byte_; + const auto fieldPiece = piece_; + if (atNameRange()) { + const auto candidate = consumeNameRange(); + if (match(TokenId::COLON)) name = candidate; + else { byte_ = fieldByte; piece_ = fieldPiece; } + } + fields.emplace_back(std::move(name), parseExpression()); + } while (match(TokenId::COMMA)); } - } - fields.emplace_back(std::move(name), parseExpression()); + require(TokenId::RPAREN, "Expected ')' after return fields"); + } else { + // `return value` is the established method form. The source is + // already one token stream; this merely assembles the + // following integer range as an expression rather than leaving it + // to be misread as the next top-level declaration. + skipTrivia(); + if (!terminatedByLineBreak && !atEnd() && !at(TokenId::ELSE) && !at(TokenId::DOT)) { + fields.emplace_back("", parseExpression()); + } + } + auto result = std::make_shared(std::move(fields)); + stamp(result, begin, byte_); + return result; + } + if (match(TokenId::NOT)) { + auto result = std::make_shared(parseCall()); + stamp(result, begin, byte_); + return result; + } + const auto start = byte_; + const auto startPiece = piece_; + if (atNameRange()) { + const auto name = consumeNameRange(); + if (match(TokenId::ASSIGN)) { + auto result = std::make_shared(name, parseExpression()); + stamp(result, begin, byte_); + return result; + } + } + byte_ = start; + piece_ = startPiece; + auto left = parseExpression(); + std::vector designations; + if (match(TokenId::AS)) { + do { + designations.push_back(consumeQualifiedName()); } while (match(TokenId::COMMA)); - } - require(TokenId::RPAREN, "Expected ')' after return fields"); - } else { - // `return value` is the established method form. The source is - // already one SentencePiece stream; this merely assembles the - // following integer range as an expression rather than leaving it - // to be misread as the next top-level declaration. - skipTrivia(); - if (!terminatedByLineBreak && !atEnd() && !at(TokenId::ELSE) && - !at(TokenId::DOT)) { - fields.emplace_back("", parseExpression()); - } - } - auto result = std::make_shared(std::move(fields)); - stamp(result, begin, byte_); - return result; - } - if (match(TokenId::NOT)) { - auto result = std::make_shared(parseCall()); - stamp(result, begin, byte_); - return result; - } - const auto start = byte_; - const auto startPiece = piece_; - if (atNameRange()) { - const auto name = consumeNameRange(); - if (matchBindingOperator()) { - auto result = std::make_shared(name, parseExpression()); - stamp(result, begin, byte_); - return result; - } - } - byte_ = start; - piece_ = startPiece; - auto left = parseExpression(); - if (match(TokenId::AS)) { - throw IntegerParserError( - "postfix 'as' fact designations are deprecated; use concrete fact " - "type where/select operations"); - } - if (const auto comparison = - std::dynamic_pointer_cast(left); - comparison && comparison->captureCount() == 2 && - isComparisonOperator(comparison->coreOperator)) { - const auto definition = coreOperatorDefinition(comparison->coreOperator); - auto result = std::make_shared( - comparison->capture(0), definition.token, comparison->capture(1)); + } + if (const auto comparison = std::dynamic_pointer_cast(left); + comparison && comparison->captureCount() == 2 && + isComparisonOperator(comparison->coreOperator)) { + const auto definition = coreOperatorDefinition(comparison->coreOperator); + auto result = std::make_shared(comparison->capture(0), definition.token, + comparison->capture(1)); + stamp(result, begin, byte_); + return result; + } + skipTrivia(); + if (piece_ < input_.entries().size() && input_.entries()[piece_].begin == byte_) { + const auto definition = infixOperatorForId(input_.entries()[piece_].id); + if (definition && isComparisonOperator(definition->id)) { + match(input_.entries()[piece_].id); + auto result = std::make_shared(std::move(left), definition->token, parseExpression()); + stamp(result, begin, byte_); + return result; + } + } + const auto term = std::dynamic_pointer_cast(left); + if (!term) throw IntegerParserError("Expected a predicate call or comparison goal"); + Call call(term->name, term->nameId, term->args, term->builtinId); + for (auto& designation : designations) { + call.designations.push_back(std::move(designation.spelling)); + call.designationIds.push_back(designation.nameId); + } + auto result = std::make_shared(std::move(call)); stamp(result, begin, byte_); return result; - } - skipTrivia(); - if (input_.has(piece_) && input_.entry(piece_).begin == byte_) { - const auto definition = infixOperatorForId(input_.entry(piece_).id); - if (definition && isComparisonOperator(definition->id)) { - match(input_.entry(piece_).id); - auto result = std::make_shared( - std::move(left), definition->token, parseExpression()); - stamp(result, begin, byte_); - return result; - } - } - const auto term = std::dynamic_pointer_cast(left); - if (!term) - throw IntegerParserError("Expected a predicate call or comparison goal"); - Call call(term->name, term->nameId, term->args, term->builtinId); - auto result = std::make_shared(std::move(call)); - stamp(result, begin, byte_); - return result; } -std::vector> -IntegerParser::parseGoalList(TokenId::Id terminator) { - std::vector> goals; - if (at(terminator)) +std::vector> IntegerParser::parseGoalList(TokenId::Id terminator) { + std::vector> goals; + if (at(terminator)) return goals; + std::size_t bodyIndent = 0; + bool hasBodyIndent = false; + do { + // Measure indentation at the first significant ID, not at the + // preceding arrow/terminator. This keeps a bare return from pulling + // the next top-level declaration into its method body. + skipTrivia(); + if (atBlockEnd()) break; + const auto before = byte_; + if (!hasBodyIndent) { + bodyIndent = sourceLineIndent(before); + hasBodyIndent = true; + } + goals.push_back(parseGoal()); + if (byte_ == before) throw IntegerParserError("Integer parser made no progress in goal list"); + if (const auto returned = std::dynamic_pointer_cast(goals.back()); + returned && returned->fields.empty() && sourceContainsLineBreak(before, byte_)) { + break; + } + if (match(TokenId::COMMA)) continue; + if (atEnd() || at(terminator) || at(TokenId::ELSE) || atBlockEnd()) break; + if (!sourceContainsLineBreak(before, byte_) || sourceLineIndent(byte_) < bodyIndent) break; + } while (true); return goals; - std::size_t bodyIndent = 0; - bool hasBodyIndent = false; - do { - // Measure indentation at the first significant ID, not at the - // preceding arrow/terminator. This keeps a bare return from pulling - // the next top-level declaration into its method body. - skipTrivia(); - if (atBlockEnd()) - break; - const auto before = byte_; - if (!hasBodyIndent) { - bodyIndent = sourceLineIndent(before); - hasBodyIndent = true; - } - goals.push_back(parseGoal()); - if (byte_ == before) - throw IntegerParserError("Integer parser made no progress in goal list"); - if (const auto returned = - std::dynamic_pointer_cast(goals.back()); - returned && returned->fields.empty() && - sourceContainsLineBreak(before, byte_)) { - break; - } - if (match(TokenId::COMMA)) - continue; - if (atEnd() || at(terminator) || at(TokenId::ELSE) || atBlockEnd()) - break; - if (!sourceContainsLineBreak(before, byte_) || - sourceLineIndent(byte_) < bodyIndent) - break; - if (bodyIndent == 0) { - // Zero-indented multi-line method bodies are supported for - // compatibility. They are ambiguous with the next top-level - // declaration, so detect only unambiguous statement starters - // without re-tokenizing source: annotations/imports, a callable - // clause head. An assignment remains part of this body: without - // indentation, a local assignment and a following global binding - // are otherwise indistinguishable, and method-local semantics - // take precedence until an explicit declaration boundary. - if (at(TokenId::AT) || at(TokenId::IMPORT)) - break; - const auto statementByte = byte_; - const auto statementPiece = piece_; - bool topLevelStatement = false; - if (atNameRange()) { - (void)consumeQualifiedName(); - topLevelStatement = at(TokenId::LPAREN); - } - byte_ = statementByte; - piece_ = statementPiece; - if (topLevelStatement) - break; - } - } while (true); - return goals; } std::shared_ptr IntegerParser::parseStatement() { - lastClauseUsedBlockEnd_ = false; - skipTrivia(); - const std::size_t begin = byte_; - std::vector annotations; - while (at(TokenId::AT)) { - annotations.push_back(parseAnnotation()); + lastClauseUsedBlockEnd_ = false; skipTrivia(); - } - for (const auto &annotation : annotations) - prepareOperatorAnnotation(annotation); - if (annotations.empty() && atNameRange()) { - const auto savedByte = byte_; - const auto savedPiece = piece_; - if (consumeNameRange() == "class") - return parseClassStatement(begin); - byte_ = savedByte; - piece_ = savedPiece; - } - if (match(TokenId::IMPORT)) { - if (!annotations.empty()) - throw IntegerParserError( - "Annotations can only be applied to method declarations"); - std::vector paths; - if (match(TokenId::LPAREN)) { - if (!at(TokenId::RPAREN)) { + const std::size_t begin = byte_; + std::vector annotations; + while (at(TokenId::AT)) { + annotations.push_back(parseAnnotation()); + skipTrivia(); + } + for (const auto& annotation : annotations) prepareOperatorAnnotation(annotation); + if (annotations.empty() && match(TokenId::CLASS)) return parseClassStatement(begin); + if (match(TokenId::IMPORT)) { + if (!annotations.empty()) throw IntegerParserError("Annotations can only be applied to method declarations"); + std::vector paths; + if (match(TokenId::LPAREN)) { + if (!at(TokenId::RPAREN)) { + do { paths.push_back(consumeString()); } while (match(TokenId::COMMA)); + } + require(TokenId::RPAREN, "Expected ')' after import paths"); + } else { + paths.push_back(consumeString()); + } + consumeStatementTerminator(begin); + auto result = std::make_shared(std::move(paths)); + stamp(result, begin, byte_); + return result; + } + const auto checkpoint = byte_; + const auto checkpointPiece = piece_; + if (atNameRange()) { + const auto name = consumeNameRange(); + if (match(TokenId::ASSIGN)) { + if (!annotations.empty()) throw IntegerParserError("Annotations can only be applied to method declarations"); + auto result = std::make_shared(name, parseExpression()); + consumeStatementTerminator(begin); + stamp(result, begin, byte_); + return result; + } + } + byte_ = checkpoint; + piece_ = checkpointPiece; + // Native and user clauses may use qualified heads such as `math.sin`. + // The separators are already atomic grammar IDs, so assemble the entire + // head before requiring its argument list. + const auto clauseName = consumeQualifiedName(); + std::vector parentNames; + if (match(TokenId::EXTEND)) { + do { parentNames.push_back(consumeQualifiedName().spelling); } while (match(TokenId::COMMA)); + } + if (!at(TokenId::LPAREN)) { + throw IntegerParserError("Expected '(' after clause name '" + clauseName.spelling + + "' at source byte " + std::to_string(byte_)); + } + Call head(clauseName.spelling, clauseName.nameId, parseArguments(), clauseName.builtinId); + if (match(TokenId::AS)) { do { - paths.push_back(consumeString().value); + const auto designation = consumeQualifiedName(); + head.designations.push_back(designation.spelling); + head.designationIds.push_back(designation.nameId); } while (match(TokenId::COMMA)); - } - require(TokenId::RPAREN, "Expected ')' after import paths"); - } else { - paths.push_back(consumeString().value); + } + std::vector> body; + std::vector>> fallbackBranches; + bool emptyDeclaration = false; + if (match(TokenId::ARROW)) { + if (match(TokenId::LPAREN)) { + require(TokenId::RPAREN, "Expected ')' after empty declaration"); + emptyDeclaration = true; + } else if (match(TokenId::LBRACE)) { + require(TokenId::RBRACE, "Expected '}' after empty declaration"); + emptyDeclaration = true; + } else { + body = parseGoalList(TokenId::DOT); + while (match(TokenId::ELSE)) { + const auto beforeBranch = byte_; + auto branch = parseGoalList(TokenId::DOT); + if (branch.empty() || byte_ == beforeBranch) { + throw IntegerParserError("Expected fallback branch after 'else'"); + } + fallbackBranches.push_back(std::move(branch)); + } + lastClauseUsedBlockEnd_ = matchBlockEnd(); + } } consumeStatementTerminator(begin); - auto result = std::make_shared(std::move(paths)); + // Annotations describe callable operator implementations. They are + // methods even when their body has a bare `return` (or no value return), + // so classification must not depend solely on ReturnGoal fields. + const ClauseKind kind = emptyDeclaration ? ClauseKind::NativeDeclaration : + (head.nameId == kMainSymbolId || !annotations.empty() || isMethodStyleHead(head) || hasValueReturn(body) || !fallbackBranches.empty() ? ClauseKind::Method : + body.empty() ? ClauseKind::Fact : ClauseKind::Rule); + auto result = std::make_shared(std::move(head), std::move(parentNames), std::move(body), + std::move(fallbackBranches), + emptyDeclaration, kind); + result->designations = result->head.designations; + result->designationIds = result->head.designationIds; + if (!annotations.empty() && result->clauseKind != ClauseKind::Method) { + throw IntegerParserError("Annotations can only be applied to complete method declarations"); + } + result->annotations = std::move(annotations); stamp(result, begin, byte_); return result; - } - const auto checkpoint = byte_; - const auto checkpointPiece = piece_; - if (atNameRange()) { - const auto name = consumeNameRange(); - if (matchBindingOperator()) { - if (!annotations.empty()) - throw IntegerParserError( - "Annotations can only be applied to method declarations"); - auto result = - std::make_shared(name, parseExpression()); - consumeStatementTerminator(begin); - stamp(result, begin, byte_); - return result; - } - } - byte_ = checkpoint; - piece_ = checkpointPiece; - // Native and user clauses may use qualified heads such as `math.sin`. - // The separators are already atomic grammar IDs, so assemble the entire - // head before requiring its argument list. - const auto clauseName = consumeQualifiedName(); - std::vector parentNames; - if (match(TokenId::EXTEND)) { - do { - parentNames.push_back(consumeQualifiedName().spelling); - } while (match(TokenId::COMMA)); - } - if (!at(TokenId::LPAREN)) { - throw IntegerParserError("Expected '(' after clause name '" + - clauseName.spelling + "' at source byte " + - std::to_string(byte_)); - } - Call head(clauseName.spelling, clauseName.nameId, parseArguments(), - clauseName.builtinId); - if (match(TokenId::AS)) { - throw IntegerParserError( - "postfix 'as' fact designations are deprecated; use concrete fact " - "type where/select operations"); - } - std::vector> body; - std::vector>> fallbackBranches; - bool emptyDeclaration = false; - if (match(TokenId::ARROW)) { - if (match(TokenId::LPAREN)) { - require(TokenId::RPAREN, "Expected ')' after empty declaration"); - emptyDeclaration = true; - } else if (match(TokenId::LBRACE)) { - require(TokenId::RBRACE, "Expected '}' after empty declaration"); - emptyDeclaration = true; - } else { - body = parseGoalList(TokenId::DOT); - while (match(TokenId::ELSE)) { - const auto beforeBranch = byte_; - auto branch = parseGoalList(TokenId::DOT); - if (branch.empty() || byte_ == beforeBranch) { - throw IntegerParserError("Expected fallback branch after 'else'"); - } - fallbackBranches.push_back(std::move(branch)); - } - lastClauseUsedBlockEnd_ = matchBlockEnd(); - } - } - consumeStatementTerminator(begin); - // Annotations describe callable operator implementations. They are - // methods even when their body has a bare `return` (or no value return), - // so classification must not depend solely on ReturnGoal fields. - const ClauseKind kind = - emptyDeclaration - ? ClauseKind::NativeDeclaration - : (head.nameId == kMainSymbolId || !annotations.empty() || - isMethodStyleHead(head) || hasValueReturn(body) || - !fallbackBranches.empty() - ? ClauseKind::Method - : body.empty() ? ClauseKind::Fact - : ClauseKind::Rule); - auto result = std::make_shared( - std::move(head), std::move(parentNames), std::move(body), - std::move(fallbackBranches), emptyDeclaration, kind); - if (!annotations.empty() && result->clauseKind != ClauseKind::Method) { - throw IntegerParserError( - "Annotations can only be applied to complete method declarations"); - } - result->annotations = std::move(annotations); - for (const auto &annotation : result->annotations) - registerOperatorImplementation(annotation, *result); - stamp(result, begin, byte_); - return result; } -std::shared_ptr -IntegerParser::parseClassStatement(std::size_t begin) { - const auto className = consumeQualifiedName(false); - if (!className.isCapitalized) - throw IntegerParserError("Class names must begin with an uppercase letter"); - - std::vector parents; - if (match(TokenId::EXTEND)) { - do { - parents.push_back(consumeQualifiedName().spelling); - } while (match(TokenId::COMMA)); - } - if (!lineBreakBeforeNextSignificantPiece()) - throw IntegerParserError("Expected newline after class declaration"); - - std::vector fields; - std::vector indexes; - std::vector> methods; - std::unordered_set fieldIds; - while (!atEnd() && !atBlockEnd()) { - const auto fieldBegin = byte_; - const auto fieldPiece = piece_; - const auto field = consumeQualifiedName(false); - if (field.spelling == "index" && at(TokenId::LPAREN)) { - (void)match(TokenId::LPAREN); - ClassIndexDecl index; - do { - const auto indexedField = consumeQualifiedName(false); - index.fields.push_back(indexedField.spelling); - index.fieldIds.push_back(indexedField.nameId); - } while (match(TokenId::COMMA)); - require(TokenId::RPAREN, "Expected ')' after class index fields"); - if (index.fields.empty()) - throw IntegerParserError("Class index requires at least one field"); - consumeStatementTerminator(fieldBegin); - index.sourceSpan = span(fieldBegin, byte_); - indexes.push_back(std::move(index)); - continue; - } - if (at(TokenId::LPAREN)) { - byte_ = fieldBegin; - piece_ = fieldPiece; - auto statement = parseStatement(); - auto method = std::dynamic_pointer_cast(statement); - if (!method || method->clauseKind != ClauseKind::Method) - throw IntegerParserError("Expected a method declaration in class '" + - className.spelling + "'"); - if (!lastClauseUsedBlockEnd_) - throw IntegerParserError("Class method '" + method->head.name + - "' must end with 'end'"); - method->head.args.insert( - method->head.args.begin(), - Arg("self", symbolIdForName("self"), - std::make_shared(className.spelling, - className.nameId))); - method->head.name = className.spelling + "." + method->head.name; - method->head.nameId = symbolIdForName(method->head.name); - methods.push_back(std::move(method)); - continue; - } - require(TokenId::COLON, "Expected ':' after class field name"); - const auto type = consumeQualifiedName(); - if (!isFelidaeLikelyTypeName(type.spelling)) - throw IntegerParserError("Expected a type name for class field '" + - field.spelling + "'"); - if (!fieldIds.insert(field.nameId).second) - throw IntegerParserError("Duplicate class field '" + field.spelling + - "'"); - consumeStatementTerminator(fieldBegin); - ClassFieldDecl declaration{field.spelling, field.nameId, type.spelling, - span(fieldBegin, byte_)}; - fields.push_back(std::move(declaration)); - } - if (!matchBlockEnd()) - throw IntegerParserError("Expected 'end' after class declaration"); - auto result = std::make_shared( - className.spelling, className.nameId, std::move(parents), - std::move(fields), std::move(indexes), std::move(methods)); - stamp(result, begin, byte_); - return result; +std::shared_ptr IntegerParser::parseClassStatement(std::size_t begin) { + const auto className = consumeQualifiedName(false); + if (!className.isCapitalized) + throw IntegerParserError("Class names must begin with an uppercase letter"); + std::vector parents; + if (match(TokenId::EXTEND) || match(TokenId::EXTENDS)) { + do { parents.push_back(consumeQualifiedName().spelling); } while (match(TokenId::COMMA)); + } + std::vector fields; + std::vector indexes; + std::vector> methods; + std::unordered_set fieldIds; + while (!atEnd() && !atBlockEnd()) { + const auto fieldBegin = byte_; + const auto fieldPiece = piece_; + if (match(TokenId::INDEX)) { + require(TokenId::LPAREN, "Expected '(' after class index"); + ClassIndexDecl index; + do { + const auto indexed = consumeQualifiedName(false); + index.fields.push_back(indexed.spelling); + index.fieldIds.push_back(indexed.nameId); + } while (match(TokenId::COMMA)); + require(TokenId::RPAREN, "Expected ')' after class index fields"); + if (index.fields.empty()) throw IntegerParserError("Class index requires at least one field"); + consumeStatementTerminator(fieldBegin); + index.sourceSpan = span(fieldBegin, byte_); + indexes.push_back(std::move(index)); + continue; + } + const auto field = consumeQualifiedName(false); + if (at(TokenId::LPAREN)) { + byte_ = fieldBegin; + piece_ = fieldPiece; + auto method = std::dynamic_pointer_cast(parseStatement()); + if (!method || method->clauseKind != ClauseKind::Method || !lastClauseUsedBlockEnd_) + throw IntegerParserError("Class methods must be methods terminated by 'end'"); + method->head.args.insert(method->head.args.begin(), Arg("self", symbolIdForName("self"), + std::make_shared(className.spelling, className.nameId))); + method->head.name = className.spelling + "." + method->head.name; + method->head.nameId = symbolIdForName(method->head.name); + methods.push_back(std::move(method)); + continue; + } + require(TokenId::COLON, "Expected ':' after class field name"); + const auto type = consumeQualifiedName(); + if (!isFelidaeLikelyTypeName(type.spelling)) + throw IntegerParserError("Expected a type name for class field '" + field.spelling + "'"); + if (!fieldIds.insert(field.nameId).second) + throw IntegerParserError("Duplicate class field '" + field.spelling + "'"); + consumeStatementTerminator(fieldBegin); + fields.push_back(ClassFieldDecl{field.spelling, field.nameId, type.spelling, span(fieldBegin, byte_)}); + } + if (!matchBlockEnd()) throw IntegerParserError("Expected 'end' after class declaration"); + auto result = std::make_shared(className.spelling, className.nameId, std::move(parents), + std::move(fields), std::move(indexes), std::move(methods)); + stamp(result, begin, byte_); + return result; } Program IntegerParser::parseProgram() { -#ifndef NDEBUG - if (parserTraceEnabled()) - std::clog << "[felidae.parser] action=parse_program begin\n"; -#endif - Program program; - while (!atEnd()) { - const auto before = byte_; - program.addStatement(parseStatement()); - ++metrics_.statementCount; - if (byte_ == before) - throw IntegerParserError("Integer parser made no progress in program"); - } -#ifndef NDEBUG - if (parserTraceEnabled()) { - std::clog << "[felidae.parser] action=parse_program complete statements=" - << metrics_.statementCount << " final_byte=" << byte_ << '\n'; - } -#endif - return program; + Program program; + while (!atEnd()) { + const auto before = byte_; + program.addStatement(parseStatement()); + ++metrics_.statementCount; + if (byte_ == before) throw IntegerParserError("Integer parser made no progress in program"); + } + return program; } std::vector> IntegerParser::parseQuery() { - match(TokenId::QUESTION); - auto goals = parseGoalList(TokenId::DOT); - if (match(TokenId::DOT) && !atEnd()) { - throw IntegerParserError("Unexpected source after query terminator"); - } - if (!atEnd()) - throw IntegerParserError("Expected end of query"); - return goals; + match(TokenId::QUESTION); + auto goals = parseGoalList(TokenId::DOT); + if (match(TokenId::DOT) && !atEnd()) { + throw IntegerParserError("Unexpected source after query terminator"); + } + if (!atEnd()) throw IntegerParserError("Expected end of query"); + return goals; } -bool IntegerParser::startsQuery() { return at(TokenId::QUESTION); } +bool IntegerParser::startsQuery() { + return at(TokenId::QUESTION); +} std::shared_ptr IntegerParser::parseMap() { - const std::size_t begin = byte_; - require(TokenId::LBRACE, "Expected '{'"); - std::vector entries; - if (!at(TokenId::RBRACE)) { - do { - const auto key = consumeNameRange(); - require(TokenId::COLON, "Expected ':' after map key"); - entries.emplace_back(key, parseExpression()); - } while (match(TokenId::COMMA)); - } - require(TokenId::RBRACE, "Expected '}' after map"); - auto result = std::make_shared(std::move(entries)); - stamp(result, begin, byte_); - return result; + const std::size_t begin = byte_; + require(TokenId::LBRACE, "Expected '{'"); + std::vector entries; + if (!at(TokenId::RBRACE)) { + do { + const auto key = consumeNameRange(); + require(TokenId::COLON, "Expected ':' after map key"); + entries.emplace_back(key, parseExpression()); + } while (match(TokenId::COMMA)); + } + require(TokenId::RBRACE, "Expected '}' after map"); + auto result = std::make_shared(std::move(entries)); + stamp(result, begin, byte_); + return result; } std::shared_ptr IntegerParser::parsePrimary() { - RecursionScope recursion(*this); - skipTrivia(); - const std::size_t begin = byte_; - if (at(TokenId::QUOTE)) { - auto literal = consumeString(); - auto result = std::make_shared( - std::move(literal.value), std::move(literal.sentencePieceIds), - literal.containsEscape); - stamp(result, begin, byte_); - return result; - } - if (input_.has(piece_) && isDecimalDigitId(input_.entry(piece_).id)) { - auto number = consumeNumber(); - // A postfix percent is a numeric literal, not modulo: `75%` is the - // threshold 0.75. `%` remains modulo whenever a right operand follows. - const auto beforePercentByte = byte_; - const auto beforePercentPiece = piece_; - // Percent is postfix only when immediately attached to its number. - // Whitespace-delimited `%` remains the binary modulo operator. - if (byte_ > 0 && byte_ < input_.source().size() && - input_.source()[byte_ - 1] != ' ' && - input_.source()[byte_ - 1] != '\t' && input_.source()[byte_] == '%' && - input_.has(piece_) && input_.entry(piece_).id == TokenId::PERCENT) { - byte_ = input_.entry(piece_++).end; - const bool hasRightOperand = - (input_.has(piece_) && isDecimalDigitId(input_.entry(piece_).id)) || - atNameRange() || at(TokenId::LPAREN) || at(TokenId::LBRACKET) || - at(TokenId::LBRACE); - if (hasRightOperand) { - byte_ = beforePercentByte; - piece_ = beforePercentPiece; - } else - number /= 100.0; - } - auto result = std::make_shared(number); - stamp(result, begin, byte_); - return result; - } - if (match(TokenId::NIL)) { - auto result = std::make_shared(); - stamp(result, begin, byte_); - return result; - } - if (match(TokenId::LAMBDA)) { - require(TokenId::LPAREN, "Expected '(' after lambda"); - auto source = parseExpression(); - require(TokenId::COMMA, "Expected ',' after lambda source"); - const auto variable = consumeNameRange(); - require(TokenId::ARROW, "Expected '=>' after lambda variable"); - auto body = parseExpression(); - require(TokenId::RPAREN, "Expected ')' after lambda"); - auto result = std::make_shared(std::move(source), variable, - std::move(body)); - stamp(result, begin, byte_); - return result; - } - if (at(TokenId::LBRACKET)) - return parseArray(); - if (at(TokenId::LBRACE)) - return parseMap(); - if (match(TokenId::LPAREN)) { - auto result = parseExpression(); - require(TokenId::RPAREN, "Expected ')' after grouped expression"); - stamp(result, begin, byte_); - return result; - } - if (atNameRange()) { - const auto name = consumeQualifiedName(); - if (at(TokenId::LPAREN)) { - if (name.spelling == "array") { - require(TokenId::LPAREN, "Expected '(' after array"); - require(TokenId::RPAREN, "array() creates an empty array; use [...] for elements"); - auto result = std::make_shared( - std::vector>{}); + RecursionScope recursion(*this); + skipTrivia(); + const std::size_t begin = byte_; + if (at(TokenId::QUOTE)) { + auto result = std::make_shared(consumeString()); stamp(result, begin, byte_); return result; - } - auto result = std::make_shared(name.spelling, name.nameId, - parseArguments(), name.builtinId, - name.isCapitalized); - stamp(result, begin, byte_); - return result; - } - auto result = std::make_shared( - name.spelling, name.nameId, languageTypeIdForName(name.spelling), - name.isCapitalized); - stamp(result, begin, byte_); - return result; - } - throw IntegerParserError("Expected an expression at source byte " + - std::to_string(byte_)); + } + if (piece_ < input_.entries().size() && isDecimalDigitId(input_.entries()[piece_].id)) { + auto result = std::make_shared(consumeNumber()); + stamp(result, begin, byte_); + return result; + } + if (match(TokenId::TRUE)) { auto result = std::make_shared(true); stamp(result, begin, byte_); return result; } + if (match(TokenId::FALSE)) { auto result = std::make_shared(false); stamp(result, begin, byte_); return result; } + if (match(TokenId::NIL)) { auto result = std::make_shared(); stamp(result, begin, byte_); return result; } + if (match(TokenId::LAMBDA)) { + require(TokenId::LPAREN, "Expected '(' after lambda"); + auto source = parseExpression(); + require(TokenId::COMMA, "Expected ',' after lambda source"); + const auto variable = consumeNameRange(); + require(TokenId::ARROW, "Expected '=>' after lambda variable"); + auto body = parseExpression(); + require(TokenId::RPAREN, "Expected ')' after lambda"); + auto result = std::make_shared(std::move(source), variable, std::move(body)); + stamp(result, begin, byte_); + return result; + } + if (at(TokenId::LBRACKET)) return parseArray(); + if (at(TokenId::LBRACE)) return parseMap(); + if (match(TokenId::LPAREN)) { + auto result = parseExpression(); + require(TokenId::RPAREN, "Expected ')' after grouped expression"); + stamp(result, begin, byte_); + return result; + } + if (atNameRange()) { + // Keep dots for parseUnary so `people.get()` is a receiver call, + // rather than an unrelated qualified callable named `people.get`. + const auto name = consumeQualifiedName(true, false); + if (at(TokenId::LPAREN)) { + auto result = std::make_shared(name.spelling, name.nameId, parseArguments(), + name.builtinId, name.isCapitalized); + stamp(result, begin, byte_); + return result; + } + auto result = std::make_shared(name.spelling, name.nameId, + languageTypeIdForName(name.spelling), + name.isCapitalized); + stamp(result, begin, byte_); + return result; + } + throw IntegerParserError("Expected an expression"); } std::shared_ptr IntegerParser::parseExpression() { - return parseBinaryExpression(static_cast(OperatorPrecedence::Control)); -} - -bool IntegerParser::atPatternLexeme(const PatternLexeme &lexeme) { - const auto savedByte = byte_; - const auto savedPiece = piece_; - const bool matched = matchPatternLexeme(lexeme); - byte_ = savedByte; - piece_ = savedPiece; - return matched; + return parseBinaryExpression(static_cast(OperatorPrecedence::Control)); } -bool IntegerParser::matchPatternLexeme(const PatternLexeme &lexeme) { - const auto savedByte = byte_; - const auto savedPiece = piece_; - skipTrivia(); - std::size_t wanted = 0; - while (!lexeme.pieceIds.empty() && wanted < lexeme.pieceIds.size()) { - if (!input_.has(piece_) || input_.entry(piece_).begin > byte_ || - input_.entry(piece_).end <= byte_) { - break; - } - if (input_.entry(piece_).id != lexeme.pieceIds[wanted]) { - break; - } - ++wanted; - byte_ = input_.entry(piece_++).end; - } - if (!lexeme.pieceIds.empty() && wanted == lexeme.pieceIds.size()) - return true; - - // Anchors are registered once, but SentencePiece IDs are emitted from the - // current source line. The same spelling may therefore be one piece, - // several pieces, or carry a neighbouring whitespace piece. Use the - // original encode offsets to recognize the registered literal spelling; - // this is not a second tokenizer or a string grammar. - byte_ = savedByte; - piece_ = savedPiece; - skipTrivia(); - const auto start = byte_; - const auto end = start + lexeme.spelling.size(); - const auto &source = input_.source(); - if (end > source.size() || - source.compare(start, lexeme.spelling.size(), lexeme.spelling) != 0) { - byte_ = savedByte; - piece_ = savedPiece; - return false; - } - // A word-shaped anchor must end at a source identifier boundary. Without - // this, `plan` could incorrectly assemble inside `planar` when the model - // fragments that identifier differently from a declaration anchor. - const auto isIdentifierByte = [](unsigned char value) { - return std::isalnum(value) != 0 || value == '_'; - }; - if (!lexeme.spelling.empty() && - isIdentifierByte(static_cast(lexeme.spelling.back())) && - end < source.size() && - isIdentifierByte(static_cast(source[end]))) { - byte_ = savedByte; - piece_ = savedPiece; - return false; - } - while (input_.has(piece_) && input_.entry(piece_).end <= end) - ++piece_; - if (input_.has(piece_) && input_.entry(piece_).begin < end) { +bool IntegerParser::atPatternLexeme(const PatternLexeme& lexeme) { + const auto savedByte = byte_; + const auto savedPiece = piece_; + const bool matched = matchPatternLexeme(lexeme); byte_ = savedByte; piece_ = savedPiece; - return false; - } - byte_ = end; - return true; + return matched; } -bool IntegerParser::atPatternAnchor(const std::vector &anchor) { - const auto savedByte = byte_; - const auto savedPiece = piece_; - const bool matched = matchPatternAnchor(anchor); - byte_ = savedByte; - piece_ = savedPiece; - return matched; +bool IntegerParser::matchPatternLexeme(const PatternLexeme& lexeme) { + if (lexeme.pieceIds.empty()) return false; + const auto& entries = input_.entries(); + const auto savedByte = byte_; + const auto savedPiece = piece_; + skipTrivia(); + std::size_t wanted = 0; + while (wanted < lexeme.pieceIds.size()) { + if (piece_ >= entries.size() || entries[piece_].begin > byte_ || + entries[piece_].end <= byte_) { + byte_ = savedByte; + piece_ = savedPiece; + return false; + } + if (entries[piece_].id != lexeme.pieceIds[wanted]) { + byte_ = savedByte; + piece_ = savedPiece; + return false; + } + ++wanted; + byte_ = entries[piece_++].end; + } + return true; } -bool IntegerParser::matchPatternAnchor( - const std::vector &anchor) { - const auto savedByte = byte_; - const auto savedPiece = piece_; - for (const auto &lexeme : anchor) { - if (matchPatternLexeme(lexeme)) - continue; +bool IntegerParser::atPatternAnchor(const std::vector& anchor) { + const auto savedByte = byte_; + const auto savedPiece = piece_; + const bool matched = matchPatternAnchor(anchor); byte_ = savedByte; piece_ = savedPiece; - return false; - } - return true; + return matched; +} + +bool IntegerParser::matchPatternAnchor(const std::vector& anchor) { + const auto savedByte = byte_; + const auto savedPiece = piece_; + for (const auto& lexeme : anchor) { + if (matchPatternLexeme(lexeme)) continue; + byte_ = savedByte; + piece_ = savedPiece; + return false; + } + return true; } std::shared_ptr IntegerParser::tryParseLeadingPattern() { - if (!operators_) - return {}; - const auto startByte = byte_; - const auto startPiece = piece_; - std::shared_ptr selected; - std::size_t selectedByte = startByte; - std::size_t selectedPiece = startPiece; - for (const auto &pattern : operators_->patterns()) { - if (pattern.startsWithCapture || pattern.anchorLexemes.empty() || - pattern.anchorLexemes.front().empty()) - continue; - ++metrics_.backtrackingAttempts; - if (!atPatternLexeme(pattern.anchorLexemes.front().front())) - continue; - byte_ = startByte; - piece_ = startPiece; - bool candidateParsed = false; - try { - if (!matchPatternAnchor(pattern.anchorLexemes.front())) - continue; - std::vector captures; - captures.reserve(pattern.captureNames.size()); - for (std::size_t index = 0; index < pattern.captureNames.size(); - ++index) { - const bool adjacent = - index + 1 < pattern.captureNames.size() && - (index >= pattern.followingAnchorIndices.size() || - !pattern.followingAnchorIndices[index].has_value()); - const auto following = index < pattern.followingAnchorIndices.size() - ? pattern.followingAnchorIndices[index] - : std::optional{}; - const auto *stopAnchor = - following && *following < pattern.anchorLexemes.size() - ? &pattern.anchorLexemes[*following] - : nullptr; - auto captured = - adjacent - ? parseUnary() - : parseBinaryExpression(static_cast(pattern.precedence), - TokenId::UNKNOWN, stopAnchor); - captures.emplace_back(pattern.captureNames[index], std::move(captured)); - if (following && - (*following >= pattern.anchorLexemes.size() || - !matchPatternAnchor(pattern.anchorLexemes[*following]))) { - throw IntegerParserError( - "mixfix candidate did not consume its next anchor"); + if (!operators_) return {}; + const auto startByte = byte_; + const auto startPiece = piece_; + std::shared_ptr selected; + std::size_t selectedByte = startByte; + std::size_t selectedPiece = startPiece; + for (const auto& pattern : operators_->patterns()) { + if (pattern.startsWithCapture || pattern.anchorLexemes.empty() || + pattern.anchorLexemes.front().empty()) continue; + ++metrics_.backtrackingAttempts; + if (!atPatternLexeme(pattern.anchorLexemes.front().front())) continue; + byte_ = startByte; + piece_ = startPiece; + try { + if (!matchPatternAnchor(pattern.anchorLexemes.front())) continue; + std::vector captures; + captures.reserve(pattern.captureNames.size()); + for (std::size_t index = 0; index < pattern.captureNames.size(); ++index) { + const bool adjacent = index + 1 < pattern.captureNames.size() && + (index >= pattern.followingAnchorIndices.size() || + !pattern.followingAnchorIndices[index].has_value()); + const auto following = index < pattern.followingAnchorIndices.size() + ? pattern.followingAnchorIndices[index] : std::optional{}; + const auto* stopAnchor = following && *following < pattern.anchorLexemes.size() + ? &pattern.anchorLexemes[*following] : nullptr; + auto captured = adjacent ? parseUnary() : parseBinaryExpression( + static_cast(pattern.precedence), TokenId::UNKNOWN, stopAnchor); + captures.emplace_back(pattern.captureNames[index], std::move(captured)); + if (following && (*following >= pattern.anchorLexemes.size() || + !matchPatternAnchor(pattern.anchorLexemes[*following]))) { + throw IntegerParserError("mixfix candidate did not consume its next anchor"); + } + } + if (!selected || byte_ > selectedByte) { + selected = std::make_shared( + pattern.operatorId, pattern.patternId, std::move(captures)); + selectedByte = byte_; + selectedPiece = piece_; + } + } catch (const IntegerParserError&) { + // Another candidate sharing this integer anchor may still match. } - } - auto candidate = std::make_shared( - pattern.operatorId, pattern.patternId, std::move(captures)); - stamp(candidate, startByte, byte_); - candidate->resolvedMethodId = resolveMixfixMethod(*candidate); - candidateParsed = true; - if (candidate->resolvedMethodId == 0 && mixfixModel_) { - candidate->resolvedMethodId = resolveModelMixfixMethod(candidate); - } - if (!selected || byte_ > selectedByte || - (byte_ == selectedByte && candidate->resolvedMethodId != 0 && - selected->resolvedMethodId == 0)) { - selected = std::move(candidate); - selectedByte = byte_; - selectedPiece = piece_; - } - } catch (const IntegerParserError &) { - // Once the full syntax shape has parsed, an SSM/IR verification - // error is authoritative. Do not disguise it as an unrelated - // leftover-token parse failure by backtracking to a plain name. - if (candidateParsed) - throw; - // Another candidate sharing this integer anchor may still match. - } - byte_ = startByte; - piece_ = startPiece; - } - if (!selected) - return {}; - byte_ = selectedByte; - piece_ = selectedPiece; - return selected; + byte_ = startByte; + piece_ = startPiece; + } + if (!selected) return {}; + byte_ = selectedByte; + piece_ = selectedPiece; + return selected; } -std::shared_ptr -IntegerParser::tryParseTrailingPattern(std::shared_ptr left, - int minimumPrecedence) { - if (!operators_) - return {}; - const auto leftSpan = left->sourceSpan; - const auto startByte = byte_; - const auto startPiece = piece_; - const auto stampTrailing = - [&](const std::shared_ptr &expression, - std::size_t endByte) { - expression->sourceSpan = leftSpan; - const auto ending = span(startByte, endByte); - expression->sourceSpan.endLine = ending.endLine; - expression->sourceSpan.endColumn = ending.endColumn; - }; - std::shared_ptr immediate; - std::size_t immediateByte = startByte; - std::size_t immediatePiece = startPiece; - for (const auto &pattern : operators_->patterns()) { - if (!pattern.startsWithCapture || pattern.captureNames.empty() || - pattern.anchorLexemes.empty() || - pattern.anchorLexemes.front().empty() || - static_cast(pattern.precedence) < minimumPrecedence) - continue; - ++metrics_.backtrackingAttempts; - if (!atPatternLexeme(pattern.anchorLexemes.front().front())) - continue; - byte_ = startByte; - piece_ = startPiece; - bool candidateParsed = false; - try { - if (!matchPatternAnchor(pattern.anchorLexemes.front())) - continue; - std::vector captures; - captures.reserve(pattern.captureNames.size()); - captures.emplace_back(pattern.captureNames.front(), left->clone()); - for (std::size_t index = 1; index < pattern.captureNames.size(); - ++index) { - const bool adjacent = - index + 1 < pattern.captureNames.size() && - (index >= pattern.followingAnchorIndices.size() || - !pattern.followingAnchorIndices[index].has_value()); - const auto following = index < pattern.followingAnchorIndices.size() - ? pattern.followingAnchorIndices[index] - : std::optional{}; - const auto *stopAnchor = - following && *following < pattern.anchorLexemes.size() - ? &pattern.anchorLexemes[*following] - : nullptr; - auto captured = - adjacent - ? parseUnary() - : parseBinaryExpression(static_cast(pattern.precedence), - TokenId::UNKNOWN, stopAnchor); - captures.emplace_back(pattern.captureNames[index], std::move(captured)); - if (following && - (*following >= pattern.anchorLexemes.size() || - !matchPatternAnchor(pattern.anchorLexemes[*following]))) { - throw IntegerParserError( - "trailing mixfix candidate did not consume its next anchor"); +std::shared_ptr IntegerParser::tryParseTrailingPattern(std::shared_ptr left, + int minimumPrecedence) { + if (!operators_) return {}; + const auto startByte = byte_; + const auto startPiece = piece_; + std::shared_ptr immediate; + std::size_t immediateByte = startByte; + std::size_t immediatePiece = startPiece; + for (const auto& pattern : operators_->patterns()) { + if (!pattern.startsWithCapture || pattern.captureNames.empty() || + pattern.anchorLexemes.empty() || pattern.anchorLexemes.front().empty() || + static_cast(pattern.precedence) < minimumPrecedence) continue; + ++metrics_.backtrackingAttempts; + if (!atPatternLexeme(pattern.anchorLexemes.front().front())) continue; + byte_ = startByte; + piece_ = startPiece; + try { + if (!matchPatternAnchor(pattern.anchorLexemes.front())) continue; + std::vector captures; + captures.reserve(pattern.captureNames.size()); + captures.emplace_back(pattern.captureNames.front(), left->clone()); + for (std::size_t index = 1; index < pattern.captureNames.size(); ++index) { + const bool adjacent = index + 1 < pattern.captureNames.size() && + (index >= pattern.followingAnchorIndices.size() || + !pattern.followingAnchorIndices[index].has_value()); + const auto following = index < pattern.followingAnchorIndices.size() + ? pattern.followingAnchorIndices[index] : std::optional{}; + const auto* stopAnchor = following && *following < pattern.anchorLexemes.size() + ? &pattern.anchorLexemes[*following] : nullptr; + auto captured = adjacent ? parseUnary() : parseBinaryExpression( + static_cast(pattern.precedence), TokenId::UNKNOWN, stopAnchor); + captures.emplace_back(pattern.captureNames[index], std::move(captured)); + if (following && (*following >= pattern.anchorLexemes.size() || + !matchPatternAnchor(pattern.anchorLexemes[*following]))) { + throw IntegerParserError("trailing mixfix candidate did not consume its next anchor"); + } + } + if (!immediate || byte_ > immediateByte) { + immediate = std::make_shared( + pattern.operatorId, pattern.patternId, std::move(captures)); + immediateByte = byte_; + immediatePiece = piece_; + } + } catch (const IntegerParserError&) { + // Another pattern sharing this anchor may still match. } - } - if (!immediate || byte_ > immediateByte) { - immediate = std::make_shared( - pattern.operatorId, pattern.patternId, std::move(captures)); - stampTrailing(immediate, byte_); - immediate->resolvedMethodId = resolveMixfixMethod(*immediate); - candidateParsed = true; - if (immediate->resolvedMethodId == 0 && mixfixModel_) { - immediate->resolvedMethodId = resolveModelMixfixMethod(immediate); + byte_ = startByte; + piece_ = startPiece; + } + if (immediate) { + byte_ = immediateByte; + piece_ = immediatePiece; + return immediate; + } + const OperatorPatternDefinition* selected = nullptr; + std::size_t selectedLength = 0; + for (const auto& pattern : operators_->patterns()) { + if (!pattern.startsWithCapture || pattern.captureNames.empty() || + pattern.anchorLexemes.empty() || pattern.anchorLexemes.front().empty() || + static_cast(pattern.precedence) < minimumPrecedence) continue; + ++metrics_.backtrackingAttempts; + if (!atPatternLexeme(pattern.anchorLexemes.front().front())) continue; + const auto length = pattern.anchorLexemes.front().size(); + if (selected && length == selectedLength) { + throw IntegerParserError("Ambiguous integer mixfix anchor sequence"); } - immediateByte = byte_; - immediatePiece = piece_; - } - } catch (const IntegerParserError &) { - if (candidateParsed) - throw; - // Another pattern sharing this anchor may still match. - } - byte_ = startByte; - piece_ = startPiece; - } - if (immediate) { - byte_ = immediateByte; - piece_ = immediatePiece; - return immediate; - } - const OperatorPatternDefinition *selected = nullptr; - std::size_t selectedLength = 0; - for (const auto &pattern : operators_->patterns()) { - if (!pattern.startsWithCapture || pattern.captureNames.empty() || - pattern.anchorLexemes.empty() || - pattern.anchorLexemes.front().empty() || - static_cast(pattern.precedence) < minimumPrecedence) - continue; - ++metrics_.backtrackingAttempts; - if (!atPatternLexeme(pattern.anchorLexemes.front().front())) - continue; - const auto length = pattern.anchorLexemes.front().size(); - if (selected && length == selectedLength) { - throw IntegerParserError("Ambiguous integer mixfix anchor sequence"); - } - if (!selected || length > selectedLength) { - selected = &pattern; - selectedLength = length; - } - } - if (!selected) { - const auto deferredStartByte = byte_; - const auto deferredStartPiece = piece_; - std::shared_ptr deferred; - std::size_t deferredByte = deferredStartByte; - std::size_t deferredPiece = deferredStartPiece; - for (const auto *pattern : operators_->deferredTrailingCapturePatterns()) { - if (static_cast(pattern->precedence) < minimumPrecedence) - continue; - ++metrics_.backtrackingAttempts; - byte_ = deferredStartByte; - piece_ = deferredStartPiece; - bool candidateParsed = false; - try { - std::vector captures; - captures.reserve(pattern->captureNames.size()); - captures.emplace_back(pattern->captureNames.front(), left->clone()); - for (std::size_t index = 1; index < pattern->captureNames.size(); - ++index) { - const bool adjacent = - index + 1 < pattern->captureNames.size() && - (index >= pattern->followingAnchorIndices.size() || - !pattern->followingAnchorIndices[index].has_value()); - const auto following = index < pattern->followingAnchorIndices.size() - ? pattern->followingAnchorIndices[index] - : std::optional{}; - const auto *stopAnchor = - following && *following < pattern->anchorLexemes.size() - ? &pattern->anchorLexemes[*following] - : nullptr; - auto captured = - adjacent - ? parseUnary() - : parseBinaryExpression(static_cast(pattern->precedence), - TokenId::UNKNOWN, stopAnchor); - captures.emplace_back(pattern->captureNames[index], - std::move(captured)); - if (following && - (*following >= pattern->anchorLexemes.size() || - !matchPatternAnchor(pattern->anchorLexemes[*following]))) { - throw IntegerParserError( - "deferred mixfix candidate did not consume its next anchor"); - } + if (!selected || length > selectedLength) { + selected = &pattern; + selectedLength = length; } - if (!deferred || byte_ > deferredByte) { - deferred = std::make_shared( - pattern->operatorId, pattern->patternId, std::move(captures)); - stampTrailing(deferred, byte_); - deferred->resolvedMethodId = resolveMixfixMethod(*deferred); - candidateParsed = true; - if (deferred->resolvedMethodId == 0 && mixfixModel_) { - deferred->resolvedMethodId = resolveModelMixfixMethod(deferred); - } - deferredByte = byte_; - deferredPiece = piece_; + } + if (!selected) { + const auto startByte = byte_; + const auto startPiece = piece_; + std::shared_ptr deferred; + std::size_t deferredByte = startByte; + std::size_t deferredPiece = startPiece; + for (const auto* pattern : operators_->deferredTrailingCapturePatterns()) { + if (static_cast(pattern->precedence) < minimumPrecedence) continue; + ++metrics_.backtrackingAttempts; + byte_ = startByte; + piece_ = startPiece; + try { + std::vector captures; + captures.reserve(pattern->captureNames.size()); + captures.emplace_back(pattern->captureNames.front(), left->clone()); + for (std::size_t index = 1; index < pattern->captureNames.size(); ++index) { + const bool adjacent = index + 1 < pattern->captureNames.size() && + (index >= pattern->followingAnchorIndices.size() || + !pattern->followingAnchorIndices[index].has_value()); + const auto following = index < pattern->followingAnchorIndices.size() + ? pattern->followingAnchorIndices[index] : std::optional{}; + const auto* stopAnchor = following && *following < pattern->anchorLexemes.size() + ? &pattern->anchorLexemes[*following] : nullptr; + auto captured = adjacent ? parseUnary() : parseBinaryExpression( + static_cast(pattern->precedence), TokenId::UNKNOWN, stopAnchor); + captures.emplace_back(pattern->captureNames[index], std::move(captured)); + if (following && (*following >= pattern->anchorLexemes.size() || + !matchPatternAnchor(pattern->anchorLexemes[*following]))) { + throw IntegerParserError("deferred mixfix candidate did not consume its next anchor"); + } + } + if (!deferred || byte_ > deferredByte) { + deferred = std::make_shared( + pattern->operatorId, pattern->patternId, std::move(captures)); + deferredByte = byte_; + deferredPiece = piece_; + } + } catch (const IntegerParserError&) { + // A different deferred shape may consume this same ID range. + } + } + if (!deferred) { + byte_ = startByte; + piece_ = startPiece; + return {}; } - } catch (const IntegerParserError &) { - if (candidateParsed) - throw; - // A different deferred shape may consume this same ID range. - } - } - if (!deferred) { - byte_ = deferredStartByte; - piece_ = deferredStartPiece; - return {}; - } - byte_ = deferredByte; - piece_ = deferredPiece; - return deferred; - } - if (!matchPatternAnchor(selected->anchorLexemes.front())) { - throw IntegerParserError( - "Integer mixfix anchor disappeared during assembly"); - } - std::vector captures; - captures.reserve(selected->captureNames.size()); - captures.emplace_back(selected->captureNames.front(), std::move(left)); - for (std::size_t index = 1; index < selected->captureNames.size(); ++index) { - const bool adjacent = - index + 1 < selected->captureNames.size() && - (index >= selected->followingAnchorIndices.size() || - !selected->followingAnchorIndices[index].has_value()); - const auto following = index < selected->followingAnchorIndices.size() - ? selected->followingAnchorIndices[index] - : std::optional{}; - const auto *stopAnchor = - following && *following < selected->anchorLexemes.size() - ? &selected->anchorLexemes[*following] - : nullptr; - auto captured = - adjacent ? parseUnary() - : parseBinaryExpression(static_cast(selected->precedence), - TokenId::UNKNOWN, stopAnchor); - captures.emplace_back(selected->captureNames[index], std::move(captured)); - if (index < selected->followingAnchorIndices.size() && - selected->followingAnchorIndices[index]) { - const auto anchorIndex = *selected->followingAnchorIndices[index]; - if (anchorIndex >= selected->anchorLexemes.size() || - !matchPatternAnchor(selected->anchorLexemes[anchorIndex])) { - throw IntegerParserError( - "Expected integer mixfix literal anchor for '" + - selected->operatorName + "' at source byte " + - std::to_string(byte_)); - } - } - } - auto expression = std::make_shared( - selected->operatorId, selected->patternId, std::move(captures)); - stampTrailing(expression, byte_); - expression->resolvedMethodId = resolveMixfixMethod(*expression); - if (expression->resolvedMethodId == 0 && mixfixModel_) { - expression->resolvedMethodId = resolveModelMixfixMethod(expression); - } - return expression; + byte_ = deferredByte; + piece_ = deferredPiece; + return deferred; + } + if (!matchPatternAnchor(selected->anchorLexemes.front())) { + throw IntegerParserError("Integer mixfix anchor disappeared during assembly"); + } + std::vector captures; + captures.reserve(selected->captureNames.size()); + captures.emplace_back(selected->captureNames.front(), std::move(left)); + for (std::size_t index = 1; index < selected->captureNames.size(); ++index) { + const bool adjacent = index + 1 < selected->captureNames.size() && + (index >= selected->followingAnchorIndices.size() || + !selected->followingAnchorIndices[index].has_value()); + const auto following = index < selected->followingAnchorIndices.size() + ? selected->followingAnchorIndices[index] : std::optional{}; + const auto* stopAnchor = following && *following < selected->anchorLexemes.size() + ? &selected->anchorLexemes[*following] : nullptr; + auto captured = adjacent ? parseUnary() : parseBinaryExpression( + static_cast(selected->precedence), TokenId::UNKNOWN, stopAnchor); + captures.emplace_back(selected->captureNames[index], std::move(captured)); + if (index < selected->followingAnchorIndices.size() && + selected->followingAnchorIndices[index]) { + const auto anchorIndex = *selected->followingAnchorIndices[index]; + if (anchorIndex >= selected->anchorLexemes.size() || + !matchPatternAnchor(selected->anchorLexemes[anchorIndex])) { + throw IntegerParserError("Expected integer mixfix literal anchor for '" + + selected->operatorName + "' at source byte " + + std::to_string(byte_)); + } + } + } + return std::make_shared(selected->operatorId, selected->patternId, + std::move(captures)); } std::shared_ptr IntegerParser::parseUnary() { - if (auto pattern = tryParseLeadingPattern()) - return pattern; - if (match(TokenId::NOT)) - return std::make_shared(CoreOperator::LogicalNot, - parseUnary()); - if (match(TokenId::MINUS)) { - auto operand = parseUnary(); - if (const auto number = std::dynamic_pointer_cast(operand)) { - return std::make_shared(-number->value); - } - return std::make_shared(CoreOperator::UnaryMinus, - std::move(operand)); - } - if (match(TokenId::PLUS)) - return parseUnary(); - auto result = parsePrimary(); - while (at(TokenId::DOT) || at(TokenId::COLON)) { - const auto beforeByte = byte_; - const auto beforePiece = piece_; - const auto separator = input_.entry(piece_).id; - match(separator); - const auto separatorEnd = byte_; - if (!atNameRange() || - (separator == TokenId::DOT ? byte_ != separatorEnd - : sourceContainsLineBreak(separatorEnd, byte_))) { - byte_ = beforeByte; - piece_ = beforePiece; - break; - } - const auto member = consumeNameRange(/*allowLoneKeyword=*/true); - if (at(TokenId::LPAREN)) { - auto arguments = parseArguments(); - arguments.insert(arguments.begin(), Arg(std::string{}, std::move(result))); - auto call = std::make_shared( - "__query:" + member, std::move(arguments), BuiltinId::Unknown); - stamp(call, beforeByte, byte_); - result = std::move(call); - } else { - result = std::make_shared(std::move(result), member); - } - } - return result; + if (auto pattern = tryParseLeadingPattern()) return pattern; + if (match(TokenId::NOT)) return std::make_shared(CoreOperator::LogicalNot, parseUnary()); + if (match(TokenId::MINUS)) { + auto operand = parseUnary(); + if (const auto number = std::dynamic_pointer_cast(operand)) { + return std::make_shared(-number->value); + } + return std::make_shared(CoreOperator::UnaryMinus, std::move(operand)); + } + if (match(TokenId::PLUS)) return parseUnary(); + auto result = parsePrimary(); + while (at(TokenId::DOT) || at(TokenId::COLON)) { + const auto beforeByte = byte_; + const auto beforePiece = piece_; + const auto separator = input_.entries()[piece_].id; + match(separator); + const auto separatorEnd = byte_; + const auto memberKeyword = piece_ < input_.entries().size() + ? builtinTokenSpelling(input_.entries()[piece_].id) : std::string_view{}; + if ((!atNameRange() && memberKeyword.empty()) || sourceContainsLineBreak(separatorEnd, byte_)) { + byte_ = beforeByte; + piece_ = beforePiece; + break; + } + std::string member; + if (atNameRange()) { + member = consumeNameRange(); + } else { + member = std::string(memberKeyword); + byte_ = input_.entries()[piece_++].end; + } + if (!at(TokenId::LPAREN)) { + result = std::make_shared(std::move(result), member); + continue; + } + auto arguments = parseArguments(); + const auto type = std::dynamic_pointer_cast(result); + const auto prepend = [&](std::shared_ptr value, const char* name) { + arguments.insert(arguments.begin(), Arg{name, std::move(value)}); + }; + if (type && type->isCapitalized) { + if (member == "all") { + prepend(std::make_shared(type->name), "type"); + result = std::make_shared("Fact:all", std::move(arguments), BuiltinId::FactAll); + continue; + } + if (member == "count") { + prepend(std::make_shared(type->name), "type"); + result = std::make_shared("Fact:count", std::move(arguments), BuiltinId::FactCount); + continue; + } + if (member == "get") { + if (arguments.size() != 1 || + (arguments.front().name != "pos" && + arguments.front().name != "position" && + arguments.front().name != "index")) { + throw IntegerParserError("Type.get requires exactly one named position argument"); + } + prepend(std::make_shared(type->name), "type"); + result = std::make_shared("Fact:first", std::move(arguments), BuiltinId::FactFirst); + continue; + } + if (member == "where") { + std::vector fields; + fields.reserve(arguments.size()); + for (const auto& argument : arguments) { + if (argument.name.empty()) throw IntegerParserError("Type.where requires named fields"); + fields.emplace_back(argument.name, argument.value); + } + std::vector selectArgs; + selectArgs.emplace_back("type", std::make_shared(type->name)); + selectArgs.emplace_back("match", std::make_shared(std::move(fields))); + result = std::make_shared("Fact:select", std::move(selectArgs), BuiltinId::FactSelect); + continue; + } + if (member == "insert") { + prepend(std::make_shared(type->name), "type"); + result = std::make_shared("Fact:insert", std::move(arguments), BuiltinId::FactInsert); + continue; + } + } + if (const auto receiver = std::dynamic_pointer_cast(result)) { + const std::string qualified = receiver->name + "." + member; + const BuiltinId builtin = builtinIdForName(qualified); + if (builtin != BuiltinId::Unknown) { + result = std::make_shared(qualified, std::move(arguments), builtin); + continue; + } + } + if (member == "get" || member == "len" || member == "push") { + prepend(std::move(result), "data"); + const BuiltinId builtin = member == "get" ? BuiltinId::ArrayGet : + member == "len" ? BuiltinId::ArrayLen : BuiltinId::ArrayPush; + result = std::make_shared("array:" + member, std::move(arguments), builtin); + continue; + } + if (member == "update") { + prepend(std::move(result), "selection"); + result = std::make_shared("Fact:update", std::move(arguments), BuiltinId::FactUpdate); + continue; + } + if (member == "AndWhere" || member == "OrWhere") { + std::vector fields; + fields.reserve(arguments.size()); + for (const auto& argument : arguments) { + if (argument.name.empty()) throw IntegerParserError(member + " requires named fields"); + fields.emplace_back(argument.name, argument.value); + } + std::vector filterArgs; + filterArgs.emplace_back("selection", std::move(result)); + filterArgs.emplace_back("match", std::make_shared(std::move(fields))); + result = std::make_shared( + member == "AndWhere" ? "Fact:andWhere" : "Fact:orWhere", + std::move(filterArgs), member == "AndWhere" + ? BuiltinId::FactAndWhere : BuiltinId::FactOrWhere); + continue; + } + if (member == "limit") { + prepend(std::move(result), "selection"); + result = std::make_shared("Fact:limit", std::move(arguments), BuiltinId::FactLimit); + continue; + } + if (member == "delete") { + prepend(std::move(result), "selection"); + result = std::make_shared("Fact:delete", std::move(arguments), BuiltinId::FactDelete); + continue; + } + throw IntegerParserError("Unsupported fact operation '" + member + "'"); + } + return result; } std::shared_ptr IntegerParser::parseBinaryExpression( - int minimumPrecedence, TokenId::Id stop, - const std::vector *stopAnchor) { - RecursionScope recursion(*this); - auto left = parseUnary(); - while (true) { - step(); - skipTrivia(); - if (!input_.has(piece_) || input_.entry(piece_).begin > byte_ || - input_.entry(piece_).end <= byte_) - break; - // Both checks below must ask "is this ID standing alone here", not just - // compare the raw SentencePiece ID -- otherwise a keyword ID that is - // actually the leading fragment of a longer identifier on the next - // statement (`orFilter` after `plain := 1.0`, `thenable` as a `then` - // stop anchor, ...) gets misread as the reserved word/operator, matching - // the same contiguity rule atNameRange()/builtinSequenceLength() already - // apply. at() runs that same check for any ID, keyword or not. - if (stop != TokenId::UNKNOWN && at(stop)) - break; - if (stopAnchor && atPatternAnchor(*stopAnchor)) - break; - const auto operatorBegin = byte_; - if (auto pattern = tryParseTrailingPattern(left, minimumPrecedence)) { - if (byte_ <= operatorBegin) { - throw IntegerParserError("Trailing mixfix parser made no progress"); - } - left = std::move(pattern); - continue; - } - const auto candidateId = input_.entry(piece_).id; - if (!at(candidateId)) - break; - const auto definition = infixOperatorForId(candidateId); - if (!definition || - static_cast(definition->precedence) < minimumPrecedence) - break; - match(candidateId); - const int nextMinimum = - definition->associativity == OperatorAssociativity::Right + int minimumPrecedence, TokenId::Id stop, const std::vector* stopAnchor) { + RecursionScope recursion(*this); + auto left = parseUnary(); + while (true) { + step(); + skipTrivia(); + if (piece_ >= input_.entries().size() || input_.entries()[piece_].begin > byte_ || + input_.entries()[piece_].end <= byte_) break; + if (stop != TokenId::UNKNOWN && input_.entries()[piece_].id == stop) break; + if (stopAnchor && atPatternAnchor(*stopAnchor)) break; + if (auto pattern = tryParseTrailingPattern(left, minimumPrecedence)) { + left = std::move(pattern); + continue; + } + const auto definition = infixOperatorForId(input_.entries()[piece_].id); + if (!definition || static_cast(definition->precedence) < minimumPrecedence) break; + match(input_.entries()[piece_].id); + const int nextMinimum = definition->associativity == OperatorAssociativity::Right ? static_cast(definition->precedence) : static_cast(definition->precedence) + 1; - auto right = parseBinaryExpression(nextMinimum, stop, stopAnchor); - left = std::make_shared(definition->id, std::move(left), - std::move(right)); - } - return left; + auto right = parseBinaryExpression(nextMinimum, stop, stopAnchor); + left = std::make_shared(definition->id, std::move(left), std::move(right)); + } + return left; } std::shared_ptr IntegerParser::parseExpressionText() { - auto result = parseExpression(); - if (!atEnd()) - throw IntegerParserError("Unexpected source after expression"); - return result; + auto result = parseExpression(); + if (!atEnd()) throw IntegerParserError("Unexpected source after expression"); + return result; } -FelidaeIr IntegerParser::compileExpressionIr() { - const auto expression = parseExpressionText(); - const auto hasMixfix = [](const auto &self, - const std::shared_ptr &node) -> bool { - if (const auto operation = - std::dynamic_pointer_cast(node)) { - if (operation->coreOperator == CoreOperator::Unknown) - return true; - for (std::size_t index = 0; index < operation->captureCount(); ++index) { - if (self(self, operation->capture(index))) - return true; - } - } else if (const auto array = std::dynamic_pointer_cast(node)) { - for (const auto &item : array->items) - if (self(self, item)) - return true; - } else if (const auto map = std::dynamic_pointer_cast(node)) { - for (const auto &entry : map->entries) - if (self(self, entry.value)) - return true; - } else if (const auto access = - std::dynamic_pointer_cast(node)) { - return self(self, access->target); - } else if (const auto term = std::dynamic_pointer_cast(node)) { - for (const auto &argument : term->args) - if (self(self, argument.value)) - return true; +SourceSpan IntegerParser::span(std::size_t begin, std::size_t end) const { + SourceSpan result; + const auto advance = [](SourceSpan& target, const IntegerTokenList::Entry& entry, + std::size_t count) { + if (entry.id == TokenId::NEWLINE || entry.id == TokenId::CARRIAGE_RETURN) { + ++target.endLine; + target.endColumn = 1; + } else { + target.endColumn += static_cast(count); + } + }; + SourceSpan cursor; + for (const auto& entry : input_.entries()) { + if (entry.begin >= begin) break; + const auto count = std::min(entry.end, begin) - entry.begin; + advance(cursor, entry, count); } - return false; - }; - if (hasMixfix(hasMixfix, expression)) { - if (!mixfixModel_) { - throw IntegerParserError("mixfix expression requires the verified " - "MixfixStateModel compiler backend"); - } - return compileModelRoutedMixfixExpressionIr(expression); - } - return IrCodeGenerator::lowerExpression(expression); -} - -FelidaeIr IntegerParser::compileModelRoutedMixfixExpressionIr( - const std::shared_ptr &expression) const { - // This vocabulary is deliberately fixed-size and structural. Dynamic - // literals/symbols are collected into bounded parser-owned tables below; - // model output can reference them but never manufacture a machine word. - FelidaeIr shell; - shell.registerCount = kMaximumMixfixRegisters; - const auto addConstant = [&](IrConstantKind kind, IrConstant value, - PieceSequence text = {}) { - if (shell.constants.size() >= kMaximumMixfixReferences) { - throw IntegerParserError( - "mixfix compiler context has too many constants"); - } - if (kind == IrConstantKind::Text) { - shell.texts.push_back(std::move(text)); - value = shell.texts.size() - 1; - } - shell.constants.push_back({kind, value}); - }; - const auto addSymbol = [&](SymbolId symbol) { - if (std::find(shell.symbols.begin(), shell.symbols.end(), symbol) != - shell.symbols.end()) - return; - if (shell.symbols.size() >= kMaximumMixfixReferences) { - throw IntegerParserError("mixfix compiler context has too many symbols"); - } - shell.symbols.push_back(symbol); - }; - const auto collect = [&](const auto &self, - const std::shared_ptr &node) -> void { - if (const auto number = std::dynamic_pointer_cast(node)) { - addConstant(IrConstantKind::Number, encodeIrNumber(number->value)); - } else if (const auto boolean = std::dynamic_pointer_cast(node)) { - addConstant(IrConstantKind::Boolean, boolean->value ? 1 : 0); - } else if (std::dynamic_pointer_cast(node)) { - addConstant(IrConstantKind::Nil, 0); - } else if (const auto text = std::dynamic_pointer_cast(node)) { - if (text->containsEscape) { - throw IntegerParserError("string literal cannot be lowered without its " - "original SentencePiece IDs"); - } - addConstant(IrConstantKind::Text, 0, text->sentencePieceIds); - } else if (const auto variable = std::dynamic_pointer_cast(node)) { - addSymbol(variable->nameId); - } else if (const auto array = std::dynamic_pointer_cast(node)) { - for (const auto &item : array->items) - self(self, item); - } else if (const auto map = std::dynamic_pointer_cast(node)) { - if (!map->factType.empty()) - addSymbol(symbolIdForName(map->factType)); - for (const auto &entry : map->entries) { - addSymbol(entry.keyId); - self(self, entry.value); - } - } else if (const auto access = - std::dynamic_pointer_cast(node)) { - self(self, access->target); - addSymbol(access->keyId); - } else if (const auto term = std::dynamic_pointer_cast(node)) { - addSymbol(term->nameId); - for (const auto &argument : term->args) { - if (!argument.name.empty()) - addSymbol(argument.nameId); - self(self, argument.value); - } - } else if (const auto operation = - std::dynamic_pointer_cast(node)) { - for (std::size_t index = 0; index < operation->captureCount(); ++index) - self(self, operation->capture(index)); - } - }; - collect(collect, expression); - if (const auto operation = - std::dynamic_pointer_cast(expression)) { - for (const auto *overload : - operators_->overloadsForPattern(operation->patternId)) { - addSymbol(overload->methodId); - } - } - - const auto &sourceSpan = expression->sourceSpan; - shell.sourceMap.push_back({0, - {sourceSpan.startLine, sourceSpan.startColumn, - sourceSpan.endLine, sourceSpan.endColumn}}); - - MixfixContext context = makeMixfixContext(shell); - - const auto expressionBegin = sourceOffset(expression->sourceSpan.startLine, - expression->sourceSpan.startColumn); - const auto expressionEnd = sourceOffset(expression->sourceSpan.endLine, - expression->sourceSpan.endColumn); - std::size_t firstPiece = 0; - while (input_.has(firstPiece) && - input_.entry(firstPiece).end <= expressionBegin) - ++firstPiece; - std::size_t pastLastPiece = firstPiece; - while (input_.has(pastLastPiece) && - input_.entry(pastLastPiece).begin < expressionEnd) { - ++pastLastPiece; - } - if (firstPiece == pastLastPiece) { - throw IntegerParserError( - "mixfix compiler expression has no bounded SentencePiece source span"); - } - return compileVerifiedMixfixSpanIr(*mixfixModel_, context, std::move(shell), - firstPiece, pastLastPiece); -} - -FelidaeIr IntegerParser::compileVerifiedMixfixSpanIr( - MixfixStateModel &model, const MixfixContext &context, FelidaeIr irShell, - std::size_t firstPiece, std::size_t pastLastPiece) const { - if (firstPiece >= pastLastPiece || !input_.has(pastLastPiece - 1)) { - throw IntegerParserError( - "mixfix compiler span is outside the SentencePiece input"); - } - std::vector ids; - ids.reserve(pastLastPiece - firstPiece); - for (std::size_t index = firstPiece; index < pastLastPiece; ++index) { - if (input_.entry(index).id < 0) { - throw IntegerParserError("SentencePiece produced a negative token ID"); - } - ids.push_back(static_cast(input_.entry(index).id)); - } - const auto diagnosticSpan = irShell.sourceMap.empty() - ? IrSourceMapEntry::Span{} - : irShell.sourceMap.front().sourceSpan; - try { -#ifndef NDEBUG - if (parserTraceEnabled()) { - std::clog << "[felidae.parser] action=compiler_ssm span_first_piece=" - << firstPiece << " span_past_last_piece=" << pastLastPiece - << " input_ids=" << ids.size() << '\n'; - } -#endif - auto verified = - compileVerifiedMixfixIr(model, ids, context, std::move(irShell)); -#ifndef NDEBUG - if (parserTraceEnabled()) { - std::clog << "[felidae.parser] action=compiler_ssm verified_ir_words=" - << verified.words.size() - << " registers=" << verified.registerCount << '\n'; - } -#endif - return verified; - } catch (const IrError &error) { - throw IntegerParserError( - "mixfix compiler decision at " + - std::to_string(diagnosticSpan.startLine) + ":" + - std::to_string(diagnosticSpan.startColumn) + - " for SentencePiece range [" + std::to_string(firstPiece) + ", " + - std::to_string(pastLastPiece) + "): " + error.what()); - } -} - -void IntegerParser::registerOperatorImplementation(const Call &annotation, - const ClauseStmt &method) { - if (!operators_) - return; - const bool overload = annotation.builtinId == BuiltinId::OverloadAnnotation || - annotation.name == "overload"; - const bool mixfix = annotation.builtinId == BuiltinId::MixfixAnnotation || - annotation.name == "mixfix"; - if (!overload && !mixfix) - return; - Call normalized = annotation; - normalized.builtinId = - mixfix ? BuiltinId::MixfixAnnotation : BuiltinId::OverloadAnnotation; - try { - const auto parsed = decodeOperatorAnnotation(normalized); - const auto *pattern = - parsed.pattern.empty() - ? operators_->findPatternByOperator(parsed.operatorName) - : operators_->findPattern(parsed.operatorName, parsed.pattern); - if (!pattern) - throw IntegerParserError( - "operator implementation has no registered pattern"); - operators_->registerOverload(makeOperatorOverloadDefinition( - parsed, *pattern, method.head.name, method.head.nameId, method.module)); - } catch (const std::runtime_error &error) { - throw IntegerParserError(error.what()); - } -} - -SymbolId -IntegerParser::resolveMixfixMethod(const OperatorExpression &expression) const { - if (!operators_) - return 0; - const auto expressionType = [](const std::shared_ptr &expression) { - if (std::dynamic_pointer_cast(expression)) - return LanguageTypeId::Number; - if (std::dynamic_pointer_cast(expression)) - return LanguageTypeId::String; - if (std::dynamic_pointer_cast(expression)) - return LanguageTypeId::Bool; - if (std::dynamic_pointer_cast(expression)) - return LanguageTypeId::Array; - if (const auto map = std::dynamic_pointer_cast(expression); - map && !map->factType.empty()) - return LanguageTypeId::Fact; - if (const auto operation = - std::dynamic_pointer_cast(expression); - operation && operation->coreOperator == CoreOperator::Unknown) - return LanguageTypeId::Mixfix; - if (const auto hir = std::dynamic_pointer_cast(expression)) { - if (hir->valueKind == AstValueKind::Statement) - return LanguageTypeId::Stmt; - if (hir->valueKind == AstValueKind::Statements) - return LanguageTypeId::Statements; - return LanguageTypeId::Expr; - } - if (const auto variable = std::dynamic_pointer_cast(expression)) - return variable->languageTypeId; - return LanguageTypeId::Unknown; - }; - const auto isNumeric = [](LanguageTypeId type) { - return type == LanguageTypeId::Number || type == LanguageTypeId::Int || - type == LanguageTypeId::Float || type == LanguageTypeId::Double || - type == LanguageTypeId::Decimal; - }; - // A candidate's score is the sum of per-capture specificity. Equal totals - // are a genuine ambiguity and are deliberately left for the compiler SSM. - // In descending order: exact concrete, typed category, mixfix shape, expr, - // and unconstrained any/unknown. - const auto specificity = [&](LanguageTypeId wanted, - LanguageTypeId actual) -> std::optional { - if (wanted == LanguageTypeId::Unknown || wanted == LanguageTypeId::Any) - return 1; - if (wanted == LanguageTypeId::Expr) - return 2; - if (wanted == LanguageTypeId::Mixfix) - return actual == LanguageTypeId::Mixfix ? std::optional{3} - : std::nullopt; - if (actual == wanted) - return 5; - if (actual == LanguageTypeId::Unknown) - return 4; - if (wanted == LanguageTypeId::Number && isNumeric(actual)) - return 4; - return std::nullopt; - }; - std::vector matches; - int highestSpecificity = -1; - for (const auto *candidate : - operators_->overloadsForPattern(expression.patternId)) { - if (candidate->captures.size() != expression.captureCount()) - continue; - int candidateSpecificity = 0; - bool compatible = true; - for (std::size_t index = 0; index < expression.captureCount(); ++index) { - const auto wanted = candidate->captures[index].languageTypeId; - const auto actual = expressionType(expression.capture(index)); - const auto rank = specificity(wanted, actual); - if (!rank) { - compatible = false; - break; - } - candidateSpecificity += *rank; - } - if (!compatible) - continue; - if (candidateSpecificity > highestSpecificity) { - highestSpecificity = candidateSpecificity; - matches.clear(); - } - if (candidateSpecificity == highestSpecificity) - matches.push_back(candidate); - } - if (highestSpecificity < 0) - throw IntegerParserError( - "mixfix expression has no compatible overload at " + - std::to_string(expression.sourceSpan.startLine) + ":" + - std::to_string(expression.sourceSpan.startColumn) + ": " + - expression.debug()); - return matches.size() == 1 ? matches.front()->methodId : 0; -} - -SymbolId IntegerParser::resolveModelMixfixMethod( - const std::shared_ptr &expression) const { - const auto ir = compileModelRoutedMixfixExpressionIr(expression); - std::unordered_set selected; - for (std::size_t pc = 0; pc < ir.words.size();) { - const auto opcode = static_cast(ir.words[pc]); - if (opcode == IrOpcode::Call || opcode == IrOpcode::CallNamed) { - const auto index = static_cast(ir.words[pc + 2]); - if (index >= ir.symbols.size()) - throw IntegerParserError( - "mixfix model call has an invalid symbol reference"); - selected.insert(ir.symbols[index]); + result.startLine = cursor.endLine; + result.startColumn = cursor.endColumn; + result.endLine = result.startLine; + result.endColumn = result.startColumn; + for (const auto& entry : input_.entries()) { + if (entry.end <= begin) continue; + if (entry.begin >= end) break; + const auto overlapBegin = std::max(entry.begin, begin); + const auto overlapEnd = std::min(entry.end, end); + advance(result, entry, overlapEnd - overlapBegin); } - try { - pc += irInstructionWidth(ir, pc); - } catch (const IrError &error) { - throw IntegerParserError("mixfix model emitted invalid IR: " + - std::string(error.what())); - } - } - if (selected.size() != 1) { - throw IntegerParserError( - "mixfix model must emit exactly one target procedure call"); - } - return *selected.begin(); -} - -SourceSpan IntegerParser::span(std::size_t begin, std::size_t end) const { - SourceSpan result; - const auto [startLine, startColumn] = sourcePosition(begin); - const auto [endLine, endColumn] = sourcePosition(end); - result.startLine = startLine; - result.startColumn = startColumn; - result.endLine = endLine; - result.endColumn = endColumn; - return result; -} - -std::pair IntegerParser::sourcePosition(std::size_t offset) const { - offset = std::min(offset, input_.source().size()); - const auto next = - std::upper_bound(lineStarts_.begin(), lineStarts_.end(), offset); - const auto lineIndex = - static_cast(next - lineStarts_.begin() - 1); - return {static_cast(lineIndex + 1), - static_cast(offset - lineStarts_[lineIndex] + 1)}; -} - -std::size_t IntegerParser::sourceOffset(int line, int column) const { - if (line <= 0 || column <= 0 || - static_cast(line) > lineStarts_.size()) { - throw IntegerParserError("Source span is outside the input"); - } - const auto offset = lineStarts_[static_cast(line - 1)] + - static_cast(column - 1); - return std::min(offset, input_.source().size()); + return result; } -void IntegerParser::stamp(const std::shared_ptr &node, - std::size_t begin, std::size_t end) const { - node->sourceSpan = span(begin, end); +void IntegerParser::stamp(const std::shared_ptr& node, + std::size_t begin, + std::size_t end) const { + node->sourceSpan = span(begin, end); } } // namespace Felidae diff --git a/src/IntegerParser.h b/src/IntegerParser.h index c302a3e..d77ad83 100644 --- a/src/IntegerParser.h +++ b/src/IntegerParser.h @@ -1,20 +1,15 @@ #pragma once #include "AST.h" -#include "FelidaeIr.h" #include "IntegerTokenList.h" #include #include #include -#include #include namespace Felidae { -class MixfixStateModel; -struct MixfixContext; - struct IntegerParserMetrics { std::size_t tokenCount = 0; std::size_t statementCount = 0; @@ -29,33 +24,21 @@ class IntegerParserError : public std::runtime_error { explicit IntegerParserError(const std::string& message) : std::runtime_error(message) {} }; -// Direct SentencePiece-ID parser. It has no secondary tokenizer, +// Direct BPE-token-ID grammar assembler. It has no secondary tokenizer, // source-character syntax scanner, or spelling-to-token lookup table. IDs // determine all syntax; original source is retained only to copy an already -// bounded identifier payload into short-lived compiler symbol interning. +// bounded identifier payload into the IR for SymbolId interning. class IntegerParser { public: explicit IntegerParser(const IntegerTokenList& input, - std::shared_ptr operators = {}, - MixfixStateModel* mixfixModel = nullptr); + std::shared_ptr operators = {}); Program parseProgram(); std::vector> parseQuery(); std::shared_ptr parseExpressionText(); - // Transitional direct lowering for the primitive expression subset. It - // consumes the existing SentencePiece stream once and returns executable - // canonical IR without an interpreter invocation. - FelidaeIr compileExpressionIr(); - // Compiler-SSM entry point. The caller selects an existing SentencePiece - // span; this method never retokenizes source text and always verifies the - // finite-vocabulary model output before returning IR. - FelidaeIr compileVerifiedMixfixSpanIr(MixfixStateModel& model, - const MixfixContext& context, - FelidaeIr irShell, - std::size_t firstPiece, - std::size_t pastLastPiece) const; bool startsQuery(); const IntegerParserMetrics& metrics() const noexcept { return metrics_; } + private: struct QualifiedName { std::string spelling; @@ -63,22 +46,14 @@ class IntegerParser { BuiltinId builtinId = BuiltinId::Unknown; bool isCapitalized = false; }; - struct StringLiteral { - std::string value; - std::vector sentencePieceIds; - bool containsEscape = false; - }; const IntegerTokenList& input_; std::shared_ptr operators_; - // Optional compiler backend. Normal grammar is always deterministic; - // only an assembled custom mixfix expression can reach this model. - MixfixStateModel* mixfixModel_ = nullptr; std::size_t piece_ = 0; std::size_t byte_ = 0; std::size_t recursionDepth_ = 0; bool lastClauseUsedBlockEnd_ = false; IntegerParserMetrics metrics_; - std::vector lineStarts_; + static constexpr std::size_t kMaximumRecursionDepth = 512; static constexpr std::size_t kMaximumIterations = 1'000'000; @@ -93,10 +68,8 @@ class IntegerParser { void step(); void skipTrivia(); void alignPiece(); - std::size_t builtinSequenceLength(TokenId::Id id) const; bool at(TokenId::Id id); bool match(TokenId::Id id); - bool matchBindingOperator(); bool atBlockEnd(); bool matchBlockEnd(); void require(TokenId::Id id, const char* message); @@ -117,7 +90,8 @@ class IntegerParser { std::shared_ptr parseArray(); std::shared_ptr parseMap(); std::vector parseArguments(bool allowAnnotationBindings = false); - QualifiedName consumeQualifiedName(bool allowNamespaceSeparators = true); + QualifiedName consumeQualifiedName(bool allowNamespaceSeparators = true, + bool allowDottedName = true); Call parseCall(); std::shared_ptr parseGoal(); std::vector> parseGoalList(TokenId::Id terminator); @@ -125,23 +99,17 @@ class IntegerParser { std::shared_ptr parseClassStatement(std::size_t begin); Call parseAnnotation(); void prepareOperatorAnnotation(const Call& annotation); - void registerOperatorImplementation(const Call& annotation, const ClauseStmt& method); const OperatorPatternDefinition& registerOperatorPattern(OperatorPatternDefinition pattern); - SymbolId resolveMixfixMethod(const OperatorExpression& expression) const; - SymbolId resolveModelMixfixMethod(const std::shared_ptr& expression) const; - std::string consumeNameRange(bool allowLoneKeyword = false); - StringLiteral consumeString(); + std::string consumeNameRange(); + std::string consumeString(); double consumeNumber(); - bool atNameRange(bool allowLoneKeyword = false); + bool atNameRange(); bool sourceContainsLineBreak(std::size_t begin, std::size_t end) const; bool lineBreakBeforeNextSignificantPiece() const; std::size_t sourceLineIndent(std::size_t offset) const; void consumeStatementTerminator(std::size_t statementBegin); SourceSpan span(std::size_t begin, std::size_t end) const; - std::pair sourcePosition(std::size_t offset) const; - std::size_t sourceOffset(int line, int column) const; void stamp(const std::shared_ptr& node, std::size_t begin, std::size_t end) const; - FelidaeIr compileModelRoutedMixfixExpressionIr(const std::shared_ptr& expression) const; }; } // namespace Felidae diff --git a/src/IntegerTokenList.cpp b/src/IntegerTokenList.cpp index 2757f65..d328453 100644 --- a/src/IntegerTokenList.cpp +++ b/src/IntegerTokenList.cpp @@ -1,8 +1,6 @@ #include "IntegerTokenList.h" -#include -#include - +#include #include namespace Felidae { @@ -61,10 +59,12 @@ std::size_t statementEnd(std::string_view source, std::size_t begin) { } // namespace -IntegerTokenList::IntegerTokenList( - const sentencepiece::SentencePieceProcessor &processor, std::string source) - : source_(std::move(source)), processor_(&processor), +IntegerTokenList::IntegerTokenList(std::shared_ptr tokenizer, + std::string source) + : source_(std::move(source)), tokenizer_(std::move(tokenizer)), complete_(source_.empty()) { + if (!tokenizer_) + throw std::invalid_argument("IntegerTokenList requires a tokenizer"); if (!complete_) encodeNextStatement(); } @@ -74,24 +74,102 @@ void IntegerTokenList::encodeNextStatement() const { return; const auto begin = nextStatementBegin_; const auto end = statementEnd(source_, begin); - const absl::string_view statement(source_.data() + begin, end - begin); - sentencepiece::SentencePieceText encoded; - const auto status = processor_->Encode(statement, &encoded); - if (!status.ok()) { - throw std::runtime_error("SentencePiece source encoding failed: " + - status.ToString()); - } + const std::string_view statement(source_.data() + begin, end - begin); ++encodeCount_; - entries_.reserve(entries_.size() + - static_cast(encoded.pieces_size())); - for (const auto &piece : encoded.pieces()) { - const auto relativeBegin = static_cast(piece.begin()); - const auto relativeEnd = static_cast(piece.end()); - if (relativeBegin > relativeEnd || relativeEnd > statement.size()) - throw std::runtime_error("SentencePiece returned an invalid source offset"); - const auto id = static_cast(piece.id()); - entries_.push_back( - Entry{id, begin + relativeBegin, begin + relativeEnd}); + const auto push = [&](TokenId::Id id, std::size_t first, std::size_t last) { + entries_.push_back(Entry{id, begin + first, begin + last}); + }; + const auto fixedId = [](std::string_view spelling) -> TokenId::Id { + for (std::size_t index = 0; index < std::size(kBuiltinTokens); ++index) { + if (kBuiltinTokens[index].spelling == spelling) + return kFelidaeBuiltinTokenIds[index]; + } + if (spelling == "class") return TokenId::CLASS; + if (spelling == "end") return TokenId::END; + if (spelling == "index") return TokenId::INDEX; + if (spelling == "extends") return TokenId::EXTENDS; + return TokenId::UNKNOWN; + }; + for (std::size_t offset = 0; offset < statement.size();) { + const unsigned char byte = static_cast(statement[offset]); + if (statement[offset] == '#') { + const std::size_t first = offset++; + push(TokenId::COMMENT, first, offset); + const std::size_t content = offset; + while (offset < statement.size() && statement[offset] != '\n' && statement[offset] != '\r') ++offset; + if (content != offset) push(TokenId::UNKNOWN, content, offset); + continue; + } + if (statement[offset] == '"') { + push(TokenId::QUOTE, offset, offset + 1); + const std::size_t content = ++offset; + bool escaped = false; + while (offset < statement.size()) { + const char current = statement[offset]; + if (!escaped && current == '"') break; + escaped = !escaped && current == '\\'; + if (current != '\\') escaped = false; + ++offset; + } + if (content != offset) push(TokenId::UNKNOWN, content, offset); + if (offset < statement.size()) { + push(TokenId::QUOTE, offset, offset + 1); + ++offset; + } + continue; + } + if (std::isspace(byte)) { + const TokenId::Id id = statement[offset] == ' ' ? TokenId::SPACE + : statement[offset] == '\t' ? TokenId::TAB + : statement[offset] == '\n' ? TokenId::NEWLINE : TokenId::CARRIAGE_RETURN; + push(id, offset, offset + 1); + ++offset; + continue; + } + if (std::isdigit(byte)) { + push(static_cast(TokenId::DIGIT_0 + statement[offset] - '0'), offset, offset + 1); + ++offset; + continue; + } + bool matched = false; + for (const std::string_view syntax : {std::string_view(":="), std::string_view("::"), + std::string_view("=>"), std::string_view("=="), + std::string_view("!="), std::string_view("<="), + std::string_view(">=")}) { + if (statement.substr(offset).starts_with(syntax)) { + push(fixedId(syntax), offset, offset + syntax.size()); + offset += syntax.size(); + matched = true; + break; + } + } + if (matched) continue; + const TokenId::Id punctuation = fixedId(statement.substr(offset, 1)); + if (punctuation != TokenId::UNKNOWN) { + push(punctuation, offset, offset + 1); + ++offset; + continue; + } + const std::size_t first = offset; + while (offset < statement.size()) { + const unsigned char current = static_cast(statement[offset]); + if (!(std::isalnum(current) || current == '_' || current >= 0x80)) break; + ++offset; + } + if (first == offset) { + push(TokenId::UNKNOWN, offset, offset + 1); + ++offset; + continue; + } + const std::string_view word = statement.substr(first, offset - first); + const TokenId::Id keyword = fixedId(word); + if (keyword != TokenId::UNKNOWN || word == "class" || word == "end" || + word == "index" || word == "extends") { + push(keyword, first, offset); + continue; + } + for (const auto &piece : tokenizer_->encodeWithOffsets(word)) + push(static_cast(piece.id), first + piece.begin, first + piece.end); } nextStatementBegin_ = end; complete_ = end == source_.size(); @@ -106,7 +184,7 @@ bool IntegerTokenList::has(std::size_t index) const { const IntegerTokenList::Entry & IntegerTokenList::entry(std::size_t index) const { if (!has(index)) - throw std::out_of_range("SentencePiece token index is out of range"); + throw std::out_of_range("BPE token index is out of range"); return entries_[index]; } diff --git a/src/IntegerTokenList.h b/src/IntegerTokenList.h index a3a237f..91a4376 100644 --- a/src/IntegerTokenList.h +++ b/src/IntegerTokenList.h @@ -1,18 +1,16 @@ #pragma once #include "FelidaeGrammar.h" +#include "Tokenizer.h" #include +#include #include #include -namespace sentencepiece { -class SentencePieceProcessor; -} - namespace Felidae { -// The sole source-tokenization result. SentencePiece encodes complete +// The sole source-tokenization result. BPE encodes complete // dot-terminated statement spans, so multiline statements and `then` chains // have one stable token stream. Newlines are formatting inside a span. // @@ -29,8 +27,7 @@ class IntegerTokenList { }; IntegerTokenList() = default; - IntegerTokenList(const sentencepiece::SentencePieceProcessor &processor, - std::string source); + IntegerTokenList(std::shared_ptr tokenizer, std::string source); const std::string &source() const noexcept { return source_; } bool has(std::size_t index) const; @@ -39,11 +36,12 @@ class IntegerTokenList { // Tool/test materialization boundary. Production parsing uses has/entry. const std::vector &entries() const; std::size_t encodeCount() const noexcept { return encodeCount_; } + const BpeTokenizer &tokenizer() const noexcept { return *tokenizer_; } private: void encodeNextStatement() const; std::string source_; - const sentencepiece::SentencePieceProcessor *processor_ = nullptr; + std::shared_ptr tokenizer_; mutable std::vector entries_; mutable std::size_t nextStatementBegin_ = 0; mutable std::size_t encodeCount_ = 0; diff --git a/src/Interpreter.cpp b/src/Interpreter.cpp index 2cc7fb0..cf91a04 100644 --- a/src/Interpreter.cpp +++ b/src/Interpreter.cpp @@ -1,12 +1,9 @@ -Warning: truncated output (original token count: 109819) -Total output lines: 9128 - #include "Interpreter.h" #include "BuiltinRegistry.h" #include "IntegerParser.h" -#include "SentencePieceModel.h" #include "FelidaeRuntime.h" #include "OperatorAnnotation.h" +#include "Tokenizer.h" #include #include #include @@ -905,6 +902,10 @@ Interpreter::~Interpreter() { closeNativeLibraries(); } +std::vector Interpreter::loadedSourceFiles() const { + return {loadedFiles_.begin(), loadedFiles_.end()}; +} + void Interpreter::closeNativeLibraries() { for (auto& library : nativeLibraries_) closeSharedLibrary(library.handle); nativeLibraries_.clear(); @@ -926,6 +927,7 @@ void Interpreter::beginModuleTransaction() { transaction->autoEntryResults = autoEntryResults_; transaction->memory = memory_; transaction->globals = globals_; + transaction->classDefinitions = classDefinitions_; transaction->referencesBySource = referencesBySource_; transaction->nextReferenceAttachmentId = nextReferenceAttachmentId_; transaction->nextReferenceCreationOrder = nextReferenceCreationOrder_; @@ -964,6 +966,7 @@ void Interpreter::rollbackModuleTransaction() { autoEntryResults_ = transaction.autoEntryResults; memory_ = transaction.memory; globals_ = transaction.globals; + classDefinitions_ = transaction.classDefinitions; referencesBySource_ = transaction.referencesBySource; nextReferenceAttachmentId_ = transaction.nextReferenceAttachmentId; nextReferenceCreationOrder_ = transaction.nextReferenceCreationOrder; @@ -1212,6 +1215,18 @@ void Interpreter::addProgram(const Program& program) { addClause(std::make_shared(std::move(head), std::vector>{})); break; } + case StatementKind::Class: { + const auto declaration = std::static_pointer_cast(statement); + const auto existing = classDefinitions_.find(declaration->nameId); + if (existing != classDefinitions_.end()) { + throw InterpreterError("Class '" + declaration->name + "' is already declared"); + } + classDefinitions_.emplace(declaration->nameId, declaration); + for (const auto& parent : declaration->parentNames) + memory_.setParent(declaration->name, parent, currentLoadingFile_); + for (const auto& method : declaration->methods) addClause(method); + break; + } } } } catch (...) { @@ -1396,7 +1411,6616 @@ void Interpreter::addClause(std::shared_ptr clause) { } catch (const std::runtime_error& error) { throw InterpreterError(error.what()); } - const auto* pa…79819 tokens truncated…dynamic_pointer_cast(ra)) { + const auto* pattern = parsed.pattern.empty() + ? operators_->findPatternByOperator(parsed.operatorName) + : operators_->findPattern(parsed.operatorName, parsed.pattern); + if (!pattern) throw InterpreterError("Operator annotation pattern was not registered"); + if (!parsed.hasVisibility) { + try { + parsed.visibility = operators_->visibilityForPattern( + pattern->patternId, clause->module); + } catch (const std::runtime_error& error) { + throw InterpreterError(error.what()); + } + } + if (annotation.builtinId == BuiltinId::MixfixAnnotation && + !clause->head.args.empty()) { + throw InterpreterError( + "@mixfix implementations receive captures implicitly; remove method parameters"); + } + if (annotation.builtinId != BuiltinId::MixfixAnnotation && + !clause->head.args.empty()) { + if (clause->head.args.size() != parsed.captures.size()) { + throw InterpreterError( + "Annotated mixfix method parameters must match pattern capture count"); + } + for (std::size_t index = 0; index < parsed.captures.size(); ++index) { + const auto& parameter = clause->head.args[index]; + const auto type = std::dynamic_pointer_cast(parameter.value); + if (parameter.name.empty() || !type || + !isFelidaeTypeAnnotationName(type->name)) { + throw InterpreterError( + "Annotated mixfix parameters must be named and typed"); + } + const auto& capture = parsed.captures[index]; + const bool sameBuiltin = capture.languageTypeId != LanguageTypeId::Unknown && + languageTypeIdForName(type->name) == capture.languageTypeId; + const bool sameFact = capture.languageTypeId == LanguageTypeId::Unknown && + type->name == capture.type; + if (!sameBuiltin && !sameFact) { + throw InterpreterError( + "Annotated mixfix parameter '" + parameter.name + + "' type must match capture '" + capture.name + "'"); + } + } + } + if (parsed.effect != OperatorEffect::Pure) { + throw InterpreterError("Custom operator and matcher methods must be pure"); + } + std::unordered_set purityWalk; + std::string impurity; + if (!isReferenceMethodPure(clause, purityWalk, impurity)) { + throw InterpreterError("Annotated operator method '" + clauseName + + "' is not transitively pure: " + impurity); + } + if (annotation.builtinId == BuiltinId::MatcherAnnotation) { + const auto metadataExpression = [&](const auto& self, + const std::shared_ptr& expression) -> bool { + if (!expression) return false; + if (std::dynamic_pointer_cast(expression) || + std::dynamic_pointer_cast(expression) || + std::dynamic_pointer_cast(expression) || + std::dynamic_pointer_cast(expression) || + std::dynamic_pointer_cast(expression)) return true; + if (auto access = std::dynamic_pointer_cast(expression)) { + return self(self, access->target); + } + if (auto array = std::dynamic_pointer_cast(expression)) { + return std::all_of(array->items.begin(), array->items.end(), + [&](const std::shared_ptr& item) { return self(self, item); }); + } + if (auto map = std::dynamic_pointer_cast(expression)) { + return std::all_of(map->entries.begin(), map->entries.end(), + [&](const MapEntry& field) { return self(self, field.value); }); + } + return false; + }; + const ReturnGoal* returned = nullptr; + for (const auto& goal : clause->body) { + if (auto candidate = std::dynamic_pointer_cast(goal)) { + if (returned) throw InterpreterError("@matcher must return exactly one RequirementMatch"); + returned = candidate.get(); + continue; + } + if (auto guard = std::dynamic_pointer_cast(goal)) { + const auto comparison = std::dynamic_pointer_cast(guard->condition); + if (!comparison || + (comparison->op != TokenId::EQUAL && comparison->op != TokenId::NOT_EQUAL && + comparison->op != TokenId::LESS && comparison->op != TokenId::LESS_EQUAL && + comparison->op != TokenId::GREATER && comparison->op != TokenId::GREATER_EQUAL) || + !metadataExpression(metadataExpression, comparison->left) || + !metadataExpression(metadataExpression, comparison->right)) { + throw InterpreterError( + "@matcher where guards may only compare immutable context or ExpressionRef metadata"); + } + continue; + } else { + throw InterpreterError( + "@matcher bodies may contain only static where guards and RequirementMatch return"); + } + } + if (!returned || returned->fields.size() != 1 || !returned->fields.front().name.empty()) { + throw InterpreterError("@matcher must return RequirementMatch(...)"); + } + const auto wrapper = std::dynamic_pointer_cast(returned->fields.front().value); + if (!wrapper || wrapper->name != "RequirementMatch") { + throw InterpreterError("@matcher must return the RequirementMatch wrapper"); + } + if (wrapper->args.size() != parsed.produces.size()) { + throw InterpreterError("RequirementMatch fields must exactly match @matcher 'produces'"); + } + for (const auto& produced : parsed.produces) { + if (!memory_.isCompatibleType(produced.type, "OperatorRequirement")) { + throw InterpreterError("@matcher produced type '" + produced.type + + "' must extend OperatorRequirement"); + } + const Arg* output = nullptr; + for (const auto& field : wrapper->args) { + if (field.nameId == produced.nameId && field.name == produced.name) { + if (output) throw InterpreterError( + "RequirementMatch repeats factor binding '" + produced.name + "'"); + output = &field; + } + } + const auto prototype = output + ? std::dynamic_pointer_cast(output->value) + : std::shared_ptr{}; + if (!prototype || prototype->nameId != produced.typeId || + prototype->name != produced.type) { + throw InterpreterError("RequirementMatch binding '" + produced.name + + "' must construct " + produced.type); + } + } + operators_->registerMatcher(makeOperatorMatcherDefinition( + parsed, *pattern, clause->head.name, clause->head.nameId, clause->module)); + operatorClauses_[pattern->patternId].push_back(clause); + continue; + } + operators_->registerOverload(makeOperatorOverloadDefinition( + parsed, *pattern, clause->head.name, clause->head.nameId, clause->module)); + operatorClauses_[pattern->patternId].push_back(clause); + } + if (clause->isFact() && globals_.count(clause->head.name) == 0) { + const auto registrationStarted = std::chrono::steady_clock::now(); + auto materialized = factToMap(*clause); + memory_.addFact(clause->head.name, clause->parentName, materialized.value, + currentLoadingFile_, std::nullopt, 1, + std::move(materialized.parentFactIds), clause->designationIds, + std::move(materialized.temporalMetadata)); + const auto& declaredParents = clause->parentNames.empty() + ? std::vector{clause->parentName} + : clause->parentNames; + for (const auto& parent : declaredParents) { + if (!parent.empty()) memory_.setParent(clause->head.name, parent, currentLoadingFile_); + } + factRegistrationMicros_ += static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now() - registrationStarted).count()); + return; + } + // Fact publication advances its relation generation, not the program + // generation. Only executable declarations invalidate dispatch/table + // plans for their symbol. + clauseLookupCache_.erase(clauseName); + ++programGeneration_; + ++symbolGenerations_[clause->head.nameId == 0 + ? symbolIdForName(clauseName) + : clause->head.nameId]; + if (!currentLoadingFile_.empty()) { + clauseOrigins_[clause.get()] = currentLoadingFile_; + } + getOrCreateClauseList(clauseName, clause->head.nameId).push_back(std::move(clause)); +} + +void Interpreter::addImport(const std::filesystem::path& baseDir, const std::string& pattern) { + auto files = expandImportPattern(baseDir, pattern); + for (const auto& file : files) loadProgramFile(file); +} + +std::vector Interpreter::solve(const std::vector>& queryGoals, + size_t maxSolutions) { + ++solveEpoch_; + const bool cacheable = isCacheableQuery(queryGoals); + const std::string cacheKey = cacheable ? solveCacheKey(queryGoals, maxSolutions) : std::string{}; + if (cacheable) { + auto cached = solveCache_.find(cacheKey); + if (cached != solveCache_.end()) { + solveCacheRecency_.splice( + solveCacheRecency_.begin(), solveCacheRecency_, cached->second.recency); + return cached->second.solutions; + } + } + + std::vector out; + Env env; + try { + solveRecursive(queryGoals, std::move(env), out, maxSolutions, 0); + } catch (...) { + collectExecutionGarbage(); + throw; + } + collectExecutionGarbage(); + if (cacheable) storeCachedSolutions(cacheKey, out); + return out; +} + +bool Interpreter::hasMethod(const std::string& name) { + auto clauses = findClauses(name, symbolIdForName(name)); + if (!clauses && ensurePredicateLoaded(name)) { + clauses = findClauses(name, symbolIdForName(name)); + } + if (!clauses) return false; + for (const auto& clause : *clauses) { + if (isMethodClause(*clause)) return true; + } + return false; +} + +bool Interpreter::hasAutoEntryCall() const { + return !autoEntryCalls_.empty(); +} + +bool Interpreter::hasGlobal(const std::string& name) const { + return globals_.count(name) > 0; +} + +std::shared_ptr Interpreter::evaluateGlobal(const std::string& name) const { + auto it = globals_.find(name); + if (it == globals_.end()) throw InterpreterError("Unknown global '" + name + "'"); + return it->second->clone(); +} + +std::shared_ptr Interpreter::evaluateExpressionText(const std::string& text) { + auto tokenizer = std::make_shared(); + IntegerTokenList tokenList(std::move(tokenizer), text); + IntegerParser parser(tokenList); + auto expr = parser.parseExpressionText(); + std::shared_ptr value; + Env env; + if (!evalExprValue(expr, env, value)) { + throw InterpreterError("Expression did not evaluate to a value"); + } + return value; +} + +std::shared_ptr Interpreter::callMain(const std::shared_ptr& systemInput) { + if (!hasMethod("main")) throw InterpreterError("No main() method found"); + std::vector out; + std::shared_ptr mainClause; + auto* mainClauses = findClauses("main", symbolIdForName("main")); + if (!mainClauses) throw InterpreterError("No main() method found"); + for (auto clause = mainClauses->rbegin(); clause != mainClauses->rend(); ++clause) { + if (isMethodClause(**clause)) { + mainClause = *clause; + break; + } + } + if (!mainClause) throw InterpreterError("No main() method found"); + Call call("main", {}); + if (!mainClause->head.args.empty()) { + call.args.push_back(Arg{"arguments", systemInput->clone()}); + } + const bool previousStrictValueFailures = strictValueFailures_; + strictValueFailures_ = true; + try { + solveMethodCall(call, mainClause, Env{}, out, 1, 0); + } catch (...) { + strictValueFailures_ = previousStrictValueFailures; + throw; + } + strictValueFailures_ = previousStrictValueFailures; + if (out.empty()) { + throw InterpreterError("main() produced no result. A goal in main failed; add an explicit return or check method calls used as values."); + } + auto returned = findReturnValue(out.front().env); + if (!returned) { + throw InterpreterError("main() completed without a return value"); + } + return returned->clone(); +} + +std::shared_ptr Interpreter::callAutoEntry() { + if (autoEntryCalls_.empty()) throw InterpreterError("No auto entry call found"); + if (autoEntryResults_.size() != autoEntryCalls_.size() || !autoEntryResults_.front()) { + throw InterpreterError("Auto entry result was not committed at its statement boundary"); + } + return autoEntryResults_.front()->clone(); +} + +std::shared_ptr Interpreter::executeEntryCall(const Call& entryCall) { + auto clauses = findClauses(entryCall.name, entryCall.nameId); + if (!clauses) throw InterpreterError("Auto entry method '" + entryCall.name + "' not found"); + + for (const auto& clause : *clauses) { + if (!isMethodClause(*clause)) continue; + std::vector out; + solveMethodCall(entryCall, clause, Env{}, out, 1, 0); + if (out.empty()) continue; + auto returned = findReturnValue(out.front().env); + if (returned) return returned->clone(); + return std::make_shared("true"); + } + throw InterpreterError("Auto entry method '" + entryCall.name + "' produced no result"); +} + +std::string Interpreter::valueToString(const std::shared_ptr& value) const { + Env env; + auto resolved = resolveExpr(value, env); + std::shared_ptr evaluated; + if (const_cast(this)->evalExprValue(resolved, env, evaluated)) { + return publicValueString(evaluated); + } + return publicValueString(resolved); +} + + +std::string Interpreter::valueToDisplayString(const std::shared_ptr& value) const { + Env env; + auto resolved = resolveExpr(value, env); + std::shared_ptr evaluated; + if (const_cast(this)->evalExprValue(resolved, env, evaluated)) { + return publicDisplayString(evaluated); + } + return publicDisplayString(resolved); +} +void Interpreter::solveRecursive(const std::vector>& goals, + Env env, + std::vector& out, + size_t maxSolutions, + size_t depth) { + try { + { + solveIterative(goals, std::move(env), out, maxSolutions, depth); + } + if (depth == 0) collectExecutionGarbage(); + } catch (...) { + if (depth == 0) collectExecutionGarbage(); + throw; + } +} + +void Interpreter::solveIterative(const std::vector>& goals, + Env env, + std::vector& out, + size_t maxSolutions, + size_t depth) { + struct WorkFrame { + std::shared_ptr>> goals; + size_t goalIndex = 0; + Env env; + size_t depth = 0; + }; + auto root = std::make_shared>>(goals); + std::vector work; + work.push_back(WorkFrame{std::move(root), 0, std::move(env), depth}); + + auto combinedGoals = [](const std::vector>& prefix, + const std::vector>& suffix, + size_t suffixStart) { + auto combined = std::make_shared>>(); + combined->reserve(prefix.size() + suffix.size() - suffixStart); + combined->insert(combined->end(), prefix.begin(), prefix.end()); + combined->insert(combined->end(), suffix.begin() + static_cast(suffixStart), suffix.end()); + return combined; + }; + + while (!work.empty() && out.size() < maxSolutions) { + WorkFrame frame = std::move(work.back()); + work.pop_back(); + if (frame.depth > kMaxNativeGoalFrameDepth) { + throw InterpreterError("Maximum recursion depth reached"); + } + if (frame.goalIndex >= frame.goals->size()) { + ++solutionMaterializations_; + out.push_back(Solution{std::move(frame.env)}); + continue; + } + + const auto& goal = (*frame.goals)[frame.goalIndex]; + const size_t nextGoalIndex = frame.goalIndex + 1; + const auto continueFrame = [&](Env nextEnv) { + work.push_back(WorkFrame{frame.goals, nextGoalIndex, std::move(nextEnv), frame.depth}); + }; + + switch (goal->kind()) { + case GoalKind::Assign: { + const auto assign = std::static_pointer_cast(goal); + if (solveAssignGoal(*assign, frame.env)) continueFrame(std::move(frame.env)); + continue; + } + case GoalKind::MultiAssign: { + const auto assign = std::static_pointer_cast(goal); + if (solveMultiAssignGoal(*assign, frame.env)) continueFrame(std::move(frame.env)); + continue; + } + case GoalKind::Binary: { + const auto binary = std::static_pointer_cast(goal); + if (solveBinaryGoal(*binary, frame.env)) continueFrame(std::move(frame.env)); + continue; + } + case GoalKind::Where: { + const auto where = std::static_pointer_cast(goal); + if (solveWhereGoal(*where, frame.env)) continueFrame(std::move(frame.env)); + continue; + } + case GoalKind::Return: { + const auto returned = std::static_pointer_cast(goal); + if (solveReturnGoal(*returned, frame.env)) continueFrame(std::move(frame.env)); + continue; + } + case GoalKind::Not: { + const auto negated = std::static_pointer_cast(goal); + if (solveNotGoal(*negated, frame.env, frame.depth + 1)) continueFrame(std::move(frame.env)); + continue; + } + case GoalKind::Group: { + const auto group = std::static_pointer_cast(goal); + work.push_back(WorkFrame{combinedGoals(group->goals, *frame.goals, nextGoalIndex), + 0, std::move(frame.env), frame.depth + 1}); + continue; + } + case GoalKind::Or: { + const auto disjunction = std::static_pointer_cast(goal); + for (auto branch = disjunction->branches.rbegin(); branch != disjunction->branches.rend(); ++branch) { + // The first source-order branch is pushed last and is + // therefore processed first. It can consume the current + // environment; only sibling branches need isolation. + Env branchEnv = branch == (disjunction->branches.rend() - 1) + ? std::move(frame.env) + : copyExecutionEnvironment(frame.env); + work.push_back(WorkFrame{combinedGoals(*branch, *frame.goals, nextGoalIndex), + 0, std::move(branchEnv), frame.depth + 1}); + } + continue; + } + case GoalKind::If: { + const auto conditional = std::static_pointer_cast(goal); + if (auto binary = std::dynamic_pointer_cast(conditional->condition)) { + BindingTrail trail; + const auto previousTrail = activeBindingTrail_; + activeBindingTrail_ = &trail; + const auto checkpoint = trail.checkpoint(); + try { + const bool matched = solveBinaryGoal(*binary, frame.env); + if (!matched) trail.rollback(checkpoint); + activeBindingTrail_ = previousTrail; + const auto& branch = matched + ? conditional->thenBranch : conditional->elseBranch; + work.push_back(WorkFrame{ + combinedGoals(branch, *frame.goals, nextGoalIndex), + 0, std::move(frame.env), frame.depth + 1}); + continue; + } catch (...) { + trail.rollback(checkpoint); + activeBindingTrail_ = previousTrail; + throw; + } + } + std::vector conditionSolutions; + solveRecursive({conditional->condition}, copyExecutionEnvironment(frame.env), conditionSolutions, 1, frame.depth + 1); + const auto& branch = conditionSolutions.empty() + ? conditional->elseBranch : conditional->thenBranch; + Env branchEnv = conditionSolutions.empty() + ? std::move(frame.env) : std::move(conditionSolutions.front().env); + work.push_back(WorkFrame{combinedGoals(branch, *frame.goals, nextGoalIndex), + 0, std::move(branchEnv), frame.depth + 1}); + continue; + } + case GoalKind::Call: + break; + } + + const auto callGoal = std::static_pointer_cast(goal); + auto clauses = findClauses(callGoal->call.name, callGoal->call.nameId); + if (!clauses && ensurePredicateLoaded(callGoal->call.name)) { + clauses = findClauses(callGoal->call.name, callGoal->call.nameId); + } + std::vector tableBindings; + if (tableCallAnswers( + callGoal->call, + frame.env, + tableBindings, + nullptr, + true)) { + for (auto binding = tableBindings.rbegin(); + binding != tableBindings.rend(); + ++binding) { + work.push_back(WorkFrame{ + frame.goals, + nextGoalIndex, + std::move(binding->env), + frame.depth + 1}); + } + continue; + } + std::vector continuations; + const bool preferLocalClause = clauses && !nativeDeclarationFor(callGoal->call.name); + if (!preferLocalClause) { + // A tokenized builtin with no user clauses has exactly one possible + // continuation. Move the current environment into that path rather + // than cloning it; fact and user-method calls retain their normal + // backtracking isolation below. + const bool deterministicBuiltin = + callGoal->call.builtinId != BuiltinId::Unknown && !clauses; + Env builtinEnv = deterministicBuiltin + ? std::move(frame.env) + : copyExecutionEnvironment(frame.env); + if (solveBuiltin(callGoal->call, builtinEnv)) { + continuations.push_back(WorkFrame{frame.goals, nextGoalIndex, + std::move(builtinEnv), frame.depth + 1}); + } + } + if (clauses) { + for (const auto& originalClause : *clauses) { + ++clauseAttempts_; + if (isMethodClause(*originalClause)) { + std::vector methodSolutions; + solveMethodCall(callGoal->call, originalClause, copyExecutionEnvironment(frame.env), + methodSolutions, maxSolutions - out.size(), frame.depth + 1); + for (auto& solution : methodSolutions) { + continuations.push_back(WorkFrame{frame.goals, nextGoalIndex, + std::move(solution.env), frame.depth + 1}); + } + continue; + } + const auto clause = standardizeApart(originalClause); + for (auto& nextEnv : unifyCallAlternatives(callGoal->call, clause->head, frame.env)) { + continuations.push_back(WorkFrame{ + combinedGoals(clause->body, *frame.goals, nextGoalIndex), + 0, std::move(nextEnv), frame.depth + 1}); + } + } + } + // Prefer a grounded relation-local equality index before building a + // complete compatible-type candidate vector. The latter is useful for + // scans and inheritance, but allocating it first makes a cold exact + // lookup pay O(relation size) work even when its index has one row. + const std::vector* factCandidates = nullptr; + std::vector*> indexedCandidates; + std::vector designationCandidates; + if (!callGoal->call.designationIds.empty()) { + designationCandidates = memory_.designationIndexes(callGoal->call.designationIds); + } + for (const auto& arg : callGoal->call.args) { + if (arg.name.empty()) continue; + std::shared_ptr resolved; + if (!evalExprValue(arg.value, frame.env, resolved) || !isGroundLiteral(resolved)) continue; + const auto& indexed = memory_.propertyFactIndexes(callGoal->call.name, callGoal->call.nameId, + arg.name, arg.nameId, resolved); + indexedCandidates.push_back(&indexed); + if (!factCandidates || indexed.size() < factCandidates->size()) factCandidates = &indexed; + } + // A grounded multi-property fact call is a conjunction. Selecting + // only the smallest index still leaves candidates that another known + // property already disproves. Intersect the index plans before + // unification so those branches never enter the recursive solver. + std::vector intersectedCandidates; + if (factCandidates && indexedCandidates.size() > 1) { + intersectedCandidates = *factCandidates; + for (const auto* indexed : indexedCandidates) { + if (indexed == factCandidates) continue; + std::unordered_set allowed(indexed->begin(), indexed->end()); + intersectedCandidates.erase( + std::remove_if(intersectedCandidates.begin(), intersectedCandidates.end(), + [&](size_t factIndex) { return !allowed.count(factIndex); }), + intersectedCandidates.end()); + if (intersectedCandidates.empty()) break; + } + factCandidates = &intersectedCandidates; + } + if (!callGoal->call.designationIds.empty()) { + if (!factCandidates) { + factCandidates = &designationCandidates; + } else { + std::unordered_set allowed( + designationCandidates.begin(), designationCandidates.end()); + intersectedCandidates.assign(factCandidates->begin(), factCandidates->end()); + intersectedCandidates.erase( + std::remove_if(intersectedCandidates.begin(), intersectedCandidates.end(), + [&](size_t factIndex) { return !allowed.count(factIndex); }), + intersectedCandidates.end()); + factCandidates = &intersectedCandidates; + } + } + if (!factCandidates) { + factCandidates = &memory_.compatibleFactIndexes(callGoal->call.name, callGoal->call.nameId); + } + const auto solveFactCandidates = [&](const std::vector& candidates, + bool allowHistorical) { + for (size_t factIndex : candidates) { + const auto& fact = memory_.fact(factIndex); + if ((!allowHistorical && !fact.active) || + !memory_.isCompatibleType(fact.type, callGoal->call.name)) continue; + if (!callGoal->call.designationIds.empty() && !std::all_of( + callGoal->call.designationIds.begin(), callGoal->call.designationIds.end(), + [&](SymbolId designation) { + return std::find(fact.designations.begin(), fact.designations.end(), designation) != + fact.designations.end(); + })) { + continue; + } + ++factCandidates_; + Call factHead(callGoal->call.name, {}); + factHead.args = memory_.factArguments(factIndex); + for (auto& nextEnv : unifyCallAlternatives(callGoal->call, factHead, frame.env)) { + continuations.push_back(WorkFrame{frame.goals, nextGoalIndex, + std::move(nextEnv), frame.depth + 1}); + } + } + }; + const auto currentCandidates = memory_.currentFactIndexes(*factCandidates); + const size_t factContinuationStart = continuations.size(); + solveFactCandidates(currentCandidates, false); + // History stays cold: only when the current lineage/context cannot + // satisfy the call do we inspect relevant past rows. Future records + // are deliberately excluded from ordinary reasoning. + if (continuations.size() == factContinuationStart) { + solveFactCandidates(memory_.relevantPastFactIndexes( + callGoal->call.name, callGoal->call.nameId), true); + } + for (auto continuation = continuations.rbegin(); continuation != continuations.rend(); ++continuation) { + work.push_back(std::move(*continuation)); + } + } +} + +bool Interpreter::solveNotGoal(const NotGoal& goal, Env& env, size_t depth) { + // Negation-as-failure is safe only after every argument has been bound by + // preceding positive goals. This avoids an accidental "not exists" scan + // and gives the construct deterministic Datalog-style semantics. + for (const auto& argument : goal.call.args) { + const auto resolved = resolveExpr(argument.value, env); + if (std::dynamic_pointer_cast(resolved)) { + throw InterpreterError("Variables in 'not " + goal.call.name + "(...)' must be bound by preceding positive goals"); + } + } + + auto clauses = findClauses(goal.call.name, goal.call.nameId); + if (clauses) { + for (const auto& clause : *clauses) { + if (isMethodClause(*clause)) { + throw InterpreterError("'not " + goal.call.name + "(...)' only permits pure relational predicates"); + } + } + } else { + if (!memory_.hasActiveRelation(goal.call.name, goal.call.nameId)) { + throw InterpreterError("Unknown relational predicate in negation: " + goal.call.name); + } + } + + // A negative dependency cycle is unstratified. We reject it instead of + // allowing recursive failure to become an arbitrary truth value. + if (!activeNegatedPredicates_.insert(goal.call.name).second) { + throw InterpreterError("Unstratified negative dependency cycle involving '" + goal.call.name + "'"); + } + try { + std::vector matches; + solveRecursive(std::vector>{ + std::make_shared(goal.call)}, + copyExecutionEnvironment(env), matches, 1, depth + 1); + activeNegatedPredicates_.erase(goal.call.name); + return matches.empty(); + } catch (...) { + activeNegatedPredicates_.erase(goal.call.name); + throw; + } +} + +bool Interpreter::solveAssignGoal(const AssignGoal& goal, Env& env) { + auto var = std::make_shared(goal.name, goal.nameId); + if (globals_.count(goal.nameId)) { + throw InterpreterError("Variable '" + goal.name + "' is already assigned and immutable"); + } + auto existing = env.find(goal.nameId); + if (existing != env.end() && !std::dynamic_pointer_cast(resolveExpr(existing->second, env))) { + throw InterpreterError("Variable '" + goal.name + "' is already assigned and immutable"); + } + + std::shared_ptr value; + if (!goal.expr || !evalExprValue(goal.expr, env, value)) { + if (strictValueFailures_) { + throw InterpreterError("Assignment '" + goal.debug() + "' did not produce a value"); + } + return false; + } + return unifyExpr(var, value, env); +} + +bool Interpreter::solveMultiAssignGoal(const MultiAssignGoal& goal, Env& env) { + std::shared_ptr value; + if (!evalExprValue(goal.expr, env, value)) { + if (strictValueFailures_) { + throw InterpreterError("Assignment '" + goal.debug() + "' did not produce a value"); + } + return false; + } + + std::vector> items; + if (auto tuple = std::dynamic_pointer_cast(value)) { + if (tuple->builtinId == BuiltinId::FnTuple) { + for (const auto& arg : tuple->args) items.push_back(cloneExprOrNil(arg.value)); + } + } + if (items.empty()) exprAsArrayItems(value, items); + if (items.size() != goal.targets.size()) { + throw InterpreterError( + "ProgrammingError: tuple assignment expected " + + std::to_string(goal.targets.size()) + " value(s), got " + std::to_string(items.size())); + } + + BindingTrail trail; + const auto previousTrail = activeBindingTrail_; + activeBindingTrail_ = &trail; + const auto checkpoint = trail.checkpoint(); + try { + for (size_t i = 0; i < goal.targets.size(); ++i) { + const auto& target = goal.targets[i]; + if (globals_.count(target.nameId)) { + throw InterpreterError("Variable '" + target.name + "' is already assigned and immutable"); + } + auto existing = env.find(target.nameId); + if (existing != env.end() && + !std::dynamic_pointer_cast(resolveExpr(existing->second, env))) { + throw InterpreterError("Variable '" + target.name + "' is already assigned and immutable"); + } + if (!target.type.empty() && !valueMatchesBuiltinType(items[i], target.type)) { + throw InterpreterError( + "ProgrammingError: tuple assignment target '" + target.name + + "' expects " + target.type + ", got " + exprToString(items[i], env)); + } + if (!unifyExpr(std::make_shared(target.name, target.nameId), items[i], env)) { + trail.rollback(checkpoint); + activeBindingTrail_ = previousTrail; + return false; + } + } + activeBindingTrail_ = previousTrail; + return true; + } catch (...) { + trail.rollback(checkpoint); + activeBindingTrail_ = previousTrail; + throw; + } +} + +bool Interpreter::solveBinaryGoal(const BinaryGoal& goal, Env& env) { + switch (goal.op) { + case TokenId::EQUAL: { + std::shared_ptr leftValue; + std::shared_ptr rightValue; + if (evalExprValue(goal.left, env, leftValue) && evalExprValue(goal.right, env, rightValue)) { + return unifyExpr(leftValue, rightValue, env); + } + return unifyExpr(goal.left, goal.right, env); + } + case TokenId::NOT_EQUAL: { + BindingTrail trail; + const auto previousTrail = activeBindingTrail_; + activeBindingTrail_ = &trail; + const auto checkpoint = trail.checkpoint(); + std::shared_ptr leftValue; + std::shared_ptr rightValue; + try { + bool result = false; + if (evalExprValue(goal.left, env, leftValue) && evalExprValue(goal.right, env, rightValue)) { + result = !unifyExpr(leftValue, rightValue, env); + } else { + result = !unifyExpr(goal.left, goal.right, env); + } + trail.rollback(checkpoint); + activeBindingTrail_ = previousTrail; + return result; + } catch (...) { + trail.rollback(checkpoint); + activeBindingTrail_ = previousTrail; + throw; + } + } + default: + break; + } + + auto left = resolveExpr(goal.left, env); + auto right = resolveExpr(goal.right, env); + if (!isGroundLiteral(left) || !isGroundLiteral(right)) return false; + return compareResolved(left, goal.op, right); +} + +bool Interpreter::solveWhereGoal(const WhereGoal& goal, Env& env) { + if (auto binary = std::dynamic_pointer_cast(goal.condition)) { + return solveBinaryGoal(*binary, env); + } + return false; +} + +bool Interpreter::solveReturnGoal(const ReturnGoal& goal, Env& env) { + if (goal.fields.size() == 1 && goal.fields.front().name.empty()) { + if (valueCallTrampolineDepth_ > 0) { + if (auto tailCall = + std::dynamic_pointer_cast(goal.fields.front().value)) { + // A user-method return can be executed by the iterative value + // call frame. Builtins and native calls retain their normal + // value contract: they may have output adaptation or ABI + // result shaping that cannot be bypassed by a tail jump. + if (tailCall->builtinId == BuiltinId::Unknown && + !nativeDeclarationFor(tailCall->name) && + findClauses(tailCall->name, tailCall->nameId)) { + TermExpr next(tailCall->name, {}, tailCall->builtinId); + next.nameId = tailCall->nameId; + next.args.reserve(tailCall->args.size()); + for (const auto& argument : tailCall->args) { + next.args.push_back( + Arg{argument.name, argument.nameId, argument.value->clone()}); + } + throw TailCallSignal(std::move(next), env); + } + } + } + std::shared_ptr value; + if (!evalExprValue(goal.fields.front().value, env, value)) { + if (strictValueFailures_) { + throw InterpreterError("return value '" + goal.fields.front().value->debug() + "' did not evaluate"); + } + return false; + } + env[internalSymbolString(InternalSymbolKind::Return)] = value; + return true; + } + + std::vector entries; + entries.reserve(goal.fields.size()); + for (const auto& field : goal.fields) { + std::shared_ptr value; + if (!evalExprValue(field.value, env, value)) { + if (strictValueFailures_) { + throw InterpreterError("return field '" + field.name + ": " + field.value->debug() + "' did not evaluate"); + } + return false; + } + entries.push_back(MapEntry{field.name, value}); + } + env[internalSymbolString(InternalSymbolKind::Return)] = std::make_shared(std::move(entries)); + return true; +} + +bool Interpreter::bodyHasReturnGoal(const std::vector>& goals) const { + for (const auto& goal : goals) { + switch (goal->kind()) { + case GoalKind::Return: { + auto returned = std::static_pointer_cast(goal); + if (!returned->fields.empty()) return true; + break; + } + case GoalKind::Group: { + auto group = std::static_pointer_cast(goal); + if (bodyHasReturnGoal(group->goals)) return true; + break; + } + case GoalKind::Or: { + auto orGoal = std::static_pointer_cast(goal); + for (const auto& branch : orGoal->branches) { + if (bodyHasReturnGoal(branch)) return true; + } + break; + } + case GoalKind::If: { + auto ifGoal = std::static_pointer_cast(goal); + if (bodyHasReturnGoal(ifGoal->thenBranch) || bodyHasReturnGoal(ifGoal->elseBranch)) return true; + break; + } + case GoalKind::Call: + case GoalKind::Binary: + case GoalKind::Assign: + case GoalKind::MultiAssign: + case GoalKind::Where: + case GoalKind::Not: + break; + } + } + return false; +} + +bool Interpreter::evaluateGoalTruth(const std::shared_ptr& goal, Env& env) { + std::vector solutions; + const bool previousValueCallMode = valueCallMode_; + valueCallMode_ = false; + try { + solveRecursive({goal}, env, solutions, 1, 0); + } catch (...) { + valueCallMode_ = previousValueCallMode; + throw; + } + valueCallMode_ = previousValueCallMode; + if (solutions.empty()) return false; + env = std::move(solutions.front().env); + return true; +} + +std::shared_ptr Interpreter::evaluateGoalTruthTuple(const std::vector>& goals, Env env) { + std::vector values; + values.reserve(goals.size()); + for (const auto& goal : goals) { + if (std::dynamic_pointer_cast(goal)) continue; + const bool ok = evaluateGoalTruth(goal, env); + values.push_back(Arg{"value", std::make_shared(ok)}); + } + if (values.empty()) { + values.push_back(Arg{"value", std::make_shared(true)}); + } + return std::make_shared("fn:tuple", std::move(values), BuiltinId::FnTuple); +} + +std::shared_ptr Interpreter::executeGoalTruthTuple(const std::vector>& goals, Env env, Env& outEnv) { + std::vector values; + values.reserve(goals.size()); + for (const auto& goal : goals) { + if (std::dynamic_pointer_cast(goal)) continue; + const bool ok = evaluateGoalTruth(goal, env); + values.push_back(Arg{"value", std::make_shared(ok)}); + } + if (values.empty()) { + values.push_back(Arg{"value", std::make_shared(true)}); + } + outEnv = std::move(env); + return std::make_shared("fn:tuple", std::move(values), BuiltinId::FnTuple); +} + +bool Interpreter::solveMethodCall(const Call& call, + const std::shared_ptr& originalClause, + Env env, + std::vector& out, + size_t maxSolutions, + size_t depth) { + if (methodCallDepth_ >= kMaxNativeMethodCallDepth) { + throw InterpreterError( + "Maximum non-tail method recursion depth reached; use an explicit tail return"); + } + CounterScope methodDepth(methodCallDepth_); + if (originalClause->emptyDeclaration) return false; + // Overloads are selected by their complete call shape. Accepting an + // otherwise compatible prefix silently discarded later named arguments, + // which routed rich fact APIs through their short overloads. + for (size_t callIndex = 0; callIndex < call.args.size(); ++callIndex) { + const auto& callArg = call.args[callIndex]; + bool declared = false; + for (size_t paramIndex = 0; paramIndex < originalClause->head.args.size(); ++paramIndex) { + const auto& param = originalClause->head.args[paramIndex]; + if ((!callArg.name.empty() && callArg.name == param.name) || + (callArg.name.empty() && callIndex == paramIndex)) { + declared = true; + break; + } + } + if (!declared) { + // Extra unbound variables are the established predicate-output + // contract. Concrete extras, however, would be silently ignored + // and must not select this overload. + const auto unresolved = std::dynamic_pointer_cast( + resolveExpr(callArg.value, env)); + if (!unresolved) return false; + } + } + Env callerEnv = std::move(env); + std::vector candidates{Env{}}; + const auto* hotParams = hotMethodParamPlan(originalClause); + std::vector coldParams; + if (!hotParams) coldParams = buildMethodParamPlan(*originalClause); + const auto& paramPlans = hotParams ? *hotParams : coldParams; + + for (size_t paramIndex = 0; paramIndex < originalClause->head.args.size(); ++paramIndex) { + const auto& param = originalClause->head.args[paramIndex]; + const auto& paramPlan = paramPlans[paramIndex]; + std::vector nextCandidates; + const Arg* callArg = findArg(call, param, paramIndex); + for (auto& candidate : candidates) { + if (!callArg) { + if (paramPlan.typedParam && bodyHasReturnGoal(originalClause->body)) continue; + nextCandidates.push_back(std::move(candidate)); + continue; + } + Env attempt = std::move(candidate); + if (paramPlan.typeId == LanguageTypeId::Expr || + paramPlan.typeId == LanguageTypeId::Stmt || + paramPlan.typeId == LanguageTypeId::Statements) { + std::shared_ptr astValue; + auto alreadyBound = std::dynamic_pointer_cast( + resolveExpr(callArg->value, callerEnv)); + if (alreadyBound) { + astValue = alreadyBound; + } else if (paramPlan.typeId == LanguageTypeId::Expr) { + astValue = std::make_shared( + AstValueKind::Expression, + std::vector>{callArg->value}, + astNodeKind(callArg->value)); + } else { + continue; + } + if (!valueMatchesBuiltinType(astValue, paramPlan.typeName)) continue; + if (unifyExpr(std::make_shared(paramPlan.localName), astValue, attempt)) { + nextCandidates.push_back(std::move(attempt)); + } + continue; + } + auto unresolvedCallVar = std::dynamic_pointer_cast(resolveExpr(callArg->value, callerEnv)); + if (unresolvedCallVar) { + if (unresolvedCallVar->name == paramPlan.localName || + unifyExpr(std::make_shared(paramPlan.localName), callArg->value, attempt)) { + nextCandidates.push_back(std::move(attempt)); + } + continue; + } + std::shared_ptr value; + if (!evalExprValue(callArg->value, callerEnv, value)) continue; + if (!paramPlan.typedParam) { + if (unifyExpr(std::make_shared(paramPlan.localName), value, attempt)) { + nextCandidates.push_back(std::move(attempt)); + } + continue; + } + if (paramPlan.builtinType) { + if (!valueMatchesBuiltinType(value, paramPlan.typeName)) continue; + if (unifyExpr(std::make_shared(paramPlan.localName), value, attempt)) { + nextCandidates.push_back(std::move(attempt)); + } + continue; + } + auto map = std::dynamic_pointer_cast(value); + std::string actualType; + if (map) { + auto typeValue = findMapValue(value, internalSymbolString(InternalSymbolKind::Type)); + auto typeString = std::dynamic_pointer_cast(typeValue); + if (typeString) actualType = typeString->value; + } + if (actualType.empty() || !memory_.isCompatibleType(actualType, paramPlan.typeName)) continue; + if (unifyExpr(std::make_shared(paramPlan.localName), value, attempt)) { + nextCandidates.push_back(std::move(attempt)); + } + } + candidates = std::move(nextCandidates); + if (candidates.empty()) return false; + } + + auto appendReturnedSolution = [&](const Env& solutionEnv, const std::shared_ptr& returned) -> bool { + Env attempt = callerEnv; + attempt[internalSymbolString(InternalSymbolKind::Return)] = returned; + auto resolvedBinding = [&](const std::string& name) -> std::shared_ptr { + auto bound = solutionEnv.find(name); + if (bound == solutionEnv.end()) return nullptr; + return resolveExpr(bound->second, solutionEnv); + }; + bool ok = true; + size_t positionalOutputIndex = 0; + for (size_t argIndex = 0; argIndex < call.args.size(); ++argIndex) { + const auto& arg = call.args[argIndex]; + bool isInputArg = false; + for (size_t paramIndex = 0; paramIndex < originalClause->head.args.size(); ++paramIndex) { + const auto& param = originalClause->head.args[paramIndex]; + if ((!arg.name.empty() && param.name == arg.name) || + (arg.name.empty() && argIndex == paramIndex)) { + auto unresolved = std::dynamic_pointer_cast(resolveExpr(arg.value, callerEnv)); + isInputArg = !unresolved; + break; + } + } + if (isInputArg) continue; + std::shared_ptr returnedField; + if (!arg.name.empty()) { + returnedField = findMapValue(returned, arg.name); + if (!returnedField) returnedField = findMapValue(returned, "value"); + if (!returnedField) returnedField = findMapValue(returned, "output"); + if (!returnedField) returnedField = findMapValue(returned, ""); + if (!returnedField) { + for (size_t paramIndex = 0; paramIndex < originalClause->head.args.size(); ++paramIndex) { + const auto& param = originalClause->head.args[paramIndex]; + if (param.name != arg.name) continue; + returnedField = resolvedBinding(paramPlans[paramIndex].localName); + break; + } + } + } else if (auto returnedMap = std::dynamic_pointer_cast(returned)) { + if (positionalOutputIndex < returnedMap->entries.size()) { + returnedField = returnedMap->entries[positionalOutputIndex].value; + } + positionalOutputIndex++; + if (!returnedField && argIndex < originalClause->head.args.size()) { + returnedField = resolvedBinding(paramPlans[argIndex].localName); + } + } else { + if (argIndex < originalClause->head.args.size()) { + returnedField = resolvedBinding(paramPlans[argIndex].localName); + } + } + if (!returnedField || !unifyExpr(arg.value, returnedField, attempt)) { + ok = false; + break; + } + } + if (!ok) return false; + out.push_back(Solution{std::move(attempt)}); + return out.size() >= maxSolutions; + }; + + if (!originalClause->fallbackBranches.empty()) { + for (auto& candidate : candidates) { + std::vector preludeSolutions; + if (originalClause->body.empty()) { + preludeSolutions.push_back(Solution{std::move(candidate)}); + } else { + solveRecursive(originalClause->body, std::move(candidate), preludeSolutions, 1, depth + 1); + } + for (auto& prelude : preludeSolutions) { + for (const auto& branch : originalClause->fallbackBranches) { + std::vector branchSolutions; + solveRecursive(branch, prelude.env, branchSolutions, 1, depth + 1); + bool branchReturned = false; + for (auto& solution : branchSolutions) { + auto returnedIt = solution.env.find(internalSymbolString(InternalSymbolKind::Return)); + if (returnedIt == solution.env.end()) continue; + branchReturned = true; + auto returnedValue = returnedIt->second; + if (appendReturnedSolution(solution.env, returnedValue)) return true; + break; + } + if (branchReturned) break; + } + } + } + return true; + } + + for (auto& candidate : candidates) { + if (valueCallMode_ && originalClause->head.name != "main" && !bodyHasReturnGoal(originalClause->body)) { + Env truthEnv; + auto truthTuple = executeGoalTruthTuple(originalClause->body, candidate, truthEnv); + truthEnv[internalSymbolString(InternalSymbolKind::Return)] = truthTuple; + if (appendReturnedSolution(truthEnv, truthTuple)) return true; + continue; + } + + std::vector nested; + Env startingCandidate = candidate; + solveRecursive(originalClause->body, std::move(candidate), nested, 1, depth + 1); + if (nested.empty() && valueCallMode_ && originalClause->head.name != "main") { + Env failedValueEnv = startingCandidate; + failedValueEnv[internalSymbolString(InternalSymbolKind::Return)] = evaluateGoalTruthTuple(originalClause->body, startingCandidate); + nested.push_back(Solution{std::move(failedValueEnv)}); + } + for (auto& solution : nested) { + auto returnedIt = solution.env.find(internalSymbolString(InternalSymbolKind::Return)); + if (returnedIt == solution.env.end()) { + if (originalClause->head.name == "main") { + solution.env[internalSymbolString(InternalSymbolKind::Return)] = std::make_shared(std::vector{}); + } else { + solution.env[internalSymbolString(InternalSymbolKind::Return)] = evaluateGoalTruthTuple(originalClause->body, startingCandidate); + } + returnedIt = solution.env.find(internalSymbolString(InternalSymbolKind::Return)); + } + auto returnedValue = returnedIt->second; + if (appendReturnedSolution(solution.env, returnedValue)) return true; + } + } + return true; +} + +void Interpreter::refreshAncestryCaches() const { + const std::uint64_t generation = memory_.hierarchyGeneration(); + if (ancestryCacheGeneration_ == generation) return; + typeAncestryCache_.clear(); + typeAncestorDistanceCache_.clear(); + typeHierarchyDepthCache_.clear(); + ancestryCacheGeneration_ = generation; +} + +const std::vector& Interpreter::typeAncestry(const std::string& type) const { + refreshAncestryCaches(); + const SymbolId typeId = symbolIdForName(type); + const auto cached = typeAncestryCache_.find(typeId); + if (cached != typeAncestryCache_.end()) return cached->second; + std::vector result; + std::set seen; + std::vector pending{type}; + for (size_t index = 0; index < pending.size(); ++index) { + const std::string current = pending[index]; + if (!seen.insert(current).second) continue; + result.push_back(current); + for (const auto& parent : memory_.parentsOf(current)) pending.push_back(parent); + } + // Fact is the implicit base family. It may own source membership methods, + // but it is deliberately excluded from target comparison dispatch so a + // generic fallback cannot create a second interpretation path. + if (type != "Fact") result.push_back("Fact"); + return typeAncestryCache_.emplace(typeId, std::move(result)).first->second; +} + +const std::unordered_map& +Interpreter::typeAncestorDistances(const std::string& type) const { + refreshAncestryCaches(); + const SymbolId typeId = symbolIdForName(type); + const auto cached = typeAncestorDistanceCache_.find(typeId); + if (cached != typeAncestorDistanceCache_.end()) return cached->second; + std::unordered_map distances; + std::deque> pending; + pending.emplace_back(type, 0); + while (!pending.empty()) { + auto [current, distance] = std::move(pending.front()); + pending.pop_front(); + const auto existing = distances.find(current); + if (existing != distances.end() && existing->second <= distance) continue; + distances[current] = distance; + const auto parents = memory_.parentsOf(current); + if (parents.empty() && current != "Fact") { + pending.emplace_back("Fact", distance + 1); + } else { + for (const auto& parent : parents) { + pending.emplace_back(parent, distance + 1); + } + } + } + return typeAncestorDistanceCache_.emplace(typeId, std::move(distances)) + .first->second; +} + +double Interpreter::typeHierarchyDepth(const std::string& type) const { + refreshAncestryCaches(); + std::unordered_set visiting; + std::function resolve = + [&](const std::string& current) -> double { + if (current == "Fact") return 0.0; + const SymbolId currentId = symbolIdForName(current); + const auto cached = typeHierarchyDepthCache_.find(currentId); + if (cached != typeHierarchyDepthCache_.end()) return cached->second; + if (!visiting.insert(current).second) { + throw InterpreterError( + "Inheritance cycle detected while comparing fact types"); + } + double parentDepth = 0.0; + for (const auto& parent : memory_.parentsOf(current)) { + parentDepth = std::max(parentDepth, resolve(parent)); + } + visiting.erase(current); + const double depth = parentDepth + 1.0; + typeHierarchyDepthCache_.emplace(currentId, depth); + return depth; + }; + return resolve(type); +} + +bool Interpreter::invokeComparisonMethod(const std::shared_ptr& clause, + const Call& call, + const Env& env, + std::shared_ptr& out) { + std::vector solutions; + solveMethodCall(call, clause, env, solutions, 1, 0); + if (solutions.empty()) return false; + const auto returned = solutions.front().env.find(internalSymbolString(InternalSymbolKind::Return)); + if (returned == solutions.front().env.end()) return false; + out = resolveExpr(returned->second, solutions.front().env)->clone(); + return true; +} + +bool Interpreter::evalAncestorAnalysis(const Call& call, + const Env& env, + std::shared_ptr& out) { + auto argument = [&](std::initializer_list names, + size_t positional) -> std::shared_ptr { + for (const char* name : names) { + for (const auto& arg : call.args) { + if (arg.name != name) continue; + std::shared_ptr value; + if (evalExprValue(arg.value, env, value)) return value; + return {}; + } + } + if (positional < call.args.size() && call.args[positional].name.empty()) { + std::shared_ptr value; + if (evalExprValue(call.args[positional].value, env, value)) return value; + } + return {}; + }; + const auto left = argument({"left", "fact1", "source"}, 0); + const auto right = argument({"right", "fact2", "target"}, 1); + const auto factType = [&](const std::shared_ptr& value, + const char* label) -> std::string { + const auto map = std::dynamic_pointer_cast(value); + const auto type = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type))); + if (!map || !type || type->value.empty()) { + throw InterpreterError(std::string(builtinName(call.builtinId)) + + " requires typed fact values for '" + label + "'"); + } + return type->value; + }; + const std::string leftType = factType(left, "left"); + const std::string rightType = factType(right, "right"); + const auto& leftDistances = typeAncestorDistances(leftType); + const auto& rightDistances = typeAncestorDistances(rightType); + + struct Candidate { + std::string type; + std::size_t leftDistance = 0; + std::size_t rightDistance = 0; + double depth = 0.0; + }; + std::vector candidates; + for (const auto& [type, leftDistance] : leftDistances) { + if (type == "Fact") continue; + const auto rightDistance = rightDistances.find(type); + if (rightDistance == rightDistances.end()) continue; + candidates.push_back(Candidate{ + type, leftDistance, rightDistance->second, typeHierarchyDepth(type)}); + } + std::sort(candidates.begin(), candidates.end(), + [](const Candidate& first, const Candidate& second) { + if (first.depth != second.depth) return first.depth > second.depth; + const auto firstDistance = first.leftDistance + first.rightDistance; + const auto secondDistance = second.leftDistance + second.rightDistance; + if (firstDistance != secondDistance) return firstDistance < secondDistance; + return first.type < second.type; + }); + + // In a multiple-inheritance DAG an LCA can be a set. "lowest" means no + // other common candidate is a descendant of it; "highest" is the dual. + // This keeps tied, incomparable ancestors visible to Felidae code. + std::vector lowest; + std::vector highest; + for (const auto& candidate : candidates) { + bool hasMoreSpecific = false; + bool hasMoreGeneral = false; + for (const auto& other : candidates) { + if (candidate.type == other.type) continue; + hasMoreSpecific = hasMoreSpecific || + memory_.isCompatibleType(other.type, candidate.type); + hasMoreGeneral = hasMoreGeneral || + memory_.isCompatibleType(candidate.type, other.type); + } + if (!hasMoreSpecific) lowest.push_back(&candidate); + if (!hasMoreGeneral) highest.push_back(&candidate); + } + auto evidenceFor = [](const Candidate& candidate) { + auto evidence = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("AncestorEvidence")}, + {"ancestor", std::make_shared(candidate.type)}, + {"left_distance", std::make_shared( + static_cast(candidate.leftDistance))}, + {"right_distance", std::make_shared( + static_cast(candidate.rightDistance))}, + {"depth", std::make_shared(candidate.depth)}}); + evidence->factType = "AncestorEvidence"; + return evidence; + }; + auto evidenceArray = [&](const std::vector& selected) { + std::vector> values; + values.reserve(selected.size()); + for (const auto* candidate : selected) values.push_back(evidenceFor(*candidate)); + return std::make_shared(std::move(values)); + }; + std::vector all; + all.reserve(candidates.size()); + for (const auto& candidate : candidates) all.push_back(&candidate); + + const std::vector* requested = &all; + std::string operation = "common"; + if (call.builtinId == BuiltinId::LowestCommonAncestor) { + operation = "lowest"; + requested = &lowest; + } else if (call.builtinId == BuiltinId::HighestCommonAncestor) { + operation = "highest"; + requested = &highest; + } + std::shared_ptr selected = std::make_shared(); + if (requested->size() == 1) { + selected = std::make_shared(requested->front()->type); + } + std::string status = requested->empty() ? "none" : + (requested->size() == 1 ? "unique" : "ambiguous"); + auto result = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("AncestorAnalysis")}, + {"operation", std::make_shared(operation)}, + {"left", left->clone()}, + {"right", right->clone()}, + {"common", evidenceArray(all)}, + {"lowest", evidenceArray(lowest)}, + {"highest", evidenceArray(highest)}, + {"ancestors", evidenceArray(*requested)}, + {"selected", selected}, + {"status", std::make_shared(status)}, + {"hierarchy_generation", std::make_shared( + static_cast(memory_.hierarchyGeneration()))}}); + result->factType = "AncestorAnalysis"; + out = std::move(result); + return true; +} + +bool Interpreter::evalFactPropagation(const Call& call, + const Env& env, + std::shared_ptr& out) { + auto argument = [&](std::initializer_list names, + size_t positional) -> std::shared_ptr { + for (const char* name : names) { + for (const auto& arg : call.args) { + if (arg.name != name) continue; + std::shared_ptr value; + if (evalExprValue(arg.value, env, value)) return value; + return {}; + } + } + if (positional < call.args.size() && call.args[positional].name.empty()) { + std::shared_ptr value; + if (evalExprValue(call.args[positional].value, env, value)) return value; + } + return {}; + }; + const auto parent = argument({"parent", "source"}, 0); + const auto child = argument({"child", "target"}, 1); + const auto changes = argument({"changes", "patch"}, 2); + const auto parentMap = std::dynamic_pointer_cast(parent); + const auto childMap = std::dynamic_pointer_cast(child); + const auto changesMap = std::dynamic_pointer_cast(changes); + const auto parentType = std::dynamic_pointer_cast( + findMapValue(parent, internalSymbolString(InternalSymbolKind::Type))); + const auto childType = std::dynamic_pointer_cast( + findMapValue(child, internalSymbolString(InternalSymbolKind::Type))); + if (!parentMap || !childMap || !changesMap || !parentType || !childType) { + throw InterpreterError( + "propagateFact requires typed 'parent' and 'child' facts plus a changes map"); + } + if (!memory_.isCompatibleType(childType->value, parentType->value)) { + throw InterpreterError("propagateFact parent must be an ancestor of the child fact type"); + } + + std::vector derivedEntries = cloneEntries(childMap->entries); + std::vector> propagated; + std::vector> overridden; + for (const auto& change : changesMap->entries) { + if (change.keyId == InternalSymbol::TypeId || + change.keyId == InternalSymbol::ParentId) { + throw InterpreterError("propagateFact cannot change internal fact identity fields"); + } + const auto parentValue = findMapValue(parent, change.key); + if (!parentValue) { + throw InterpreterError("propagateFact changes must target a property supplied by the parent fact: '" + + change.key + "'"); + } + const auto childValue = findMapValue(child, change.key); + const bool inherited = childValue && exprEqualsLiteral(childValue, parentValue); + auto evidence = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("PropagationEvidence")}, + {"property", std::make_shared(change.key)}, + {"parent_value", parentValue->clone()}, + {"child_value", cloneExprOrNil(childValue)}, + {"change", change.value->clone()}, + {"status", std::make_shared( + inherited ? "propagated" : "overridden")}}); + evidence->factType = "PropagationEvidence"; + if (inherited) { + upsertEntry(derivedEntries, change.key, change.value->clone()); + propagated.push_back(std::move(evidence)); + } else { + overridden.push_back(std::move(evidence)); + } + } + auto derived = std::make_shared(std::move(derivedEntries)); + derived->factType = childMap->factType.empty() ? childType->value : childMap->factType; + const bool complete = overridden.empty(); + auto result = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("FactPropagation")}, + {"state", std::make_shared( + complete ? "propagated" : "partially_overridden")}, + {"parent", parent->clone()}, + {"child", child->clone()}, + {"derived", derived}, + {"propagated", std::make_shared(std::move(propagated))}, + {"overridden", std::make_shared(std::move(overridden))}}); + result->factType = "FactPropagation"; + out = std::move(result); + return true; +} + +bool Interpreter::solveFactAttachment(const Call& call, Env& env) { + const size_t separator = call.name.rfind(':'); + if (separator == std::string::npos) return false; + const std::string receiverName = call.name.substr(0, separator); + const std::string operation = call.name.substr(separator + 1); + if (receiverName.empty() || + (operation != "depends" && operation != "relate" && operation != "references")) { + return false; + } + + const auto receiver = env.find(receiverName); + if (receiver == env.end()) { + throw InterpreterError("'" + receiverName + "." + operation + + "' requires a stored fact with stable logical identity"); + } + const auto source = resolveExpr(receiver->second, env); + const auto sourceId = memory_.logicalFactId(source); + if (!sourceId) { + throw InterpreterError("'" + receiverName + "." + operation + "' requires a stored fact with stable logical identity"); + } + auto named = [&](const std::string& name) -> const Arg* { + for (const auto& arg : call.args) if (arg.name == name) return &arg; + return nullptr; + }; + if (operation == "references") { + return attachFactReference(call, env, *sourceId); + } + if (operation == "depends") { + const Arg* on = named("on"); + if (!on) throw InterpreterError(".depends requires an 'on' fact"); + std::shared_ptr required; + if (!evalExprValue(on->value, env, required)) return false; + const auto requiredMap = std::dynamic_pointer_cast(required); + if (!requiredMap || !findMapValue(required, internalSymbolString(InternalSymbolKind::Type))) { + throw InterpreterError(".depends 'on' must be a fact value"); + } + memory_.addDependency(*sourceId, std::static_pointer_cast(requiredMap->clone())); + } else { + const Arg* to = named("to"); + const Arg* as = named("as"); + if (!to || !as) throw InterpreterError(".relate requires 'to' and 'as' arguments"); + std::shared_ptr target; + std::shared_ptr relationship; + if (!evalExprValue(to->value, env, target) || !evalExprValue(as->value, env, relationship)) return false; + const auto targetId = memory_.logicalFactId(target); + const auto relationMap = std::dynamic_pointer_cast(relationship); + const auto relationshipType = std::dynamic_pointer_cast( + findMapValue(relationship, internalSymbolString(InternalSymbolKind::Type))); + if (!targetId || !relationMap || !relationshipType || relationshipType->value != "Relationship") { + throw InterpreterError(".relate requires a stored target fact and Relationship(...) metadata"); + } + std::shared_ptr degree = std::make_shared(); + std::shared_ptr confidence = std::make_shared(); + if (const Arg* argument = named("degree")) { + if (!evalExprValue(argument->value, env, degree)) return false; + if (!std::dynamic_pointer_cast(degree)) { + throw InterpreterError(".relate degree must be numeric when supplied"); + } + } + if (const Arg* argument = named("confidence")) { + if (!evalExprValue(argument->value, env, confidence)) return false; + if (!std::dynamic_pointer_cast(confidence)) { + throw InterpreterError(".relate confidence must be numeric when supplied"); + } + } + memory_.addRelationship(*sourceId, + *targetId, + std::static_pointer_cast(relationMap->clone()), + degree, + confidence); + } + env[internalSymbolString(InternalSymbolKind::Return)] = std::make_shared("ok"); + return true; +} + +bool Interpreter::referenceValueMatchesType(const std::shared_ptr& value, + const MethodParamPlan& parameter) const { + if (!parameter.typedParam || parameter.typeName == "any") return true; + if (parameter.builtinType) return valueMatchesBuiltinType(value, parameter.typeName); + const auto typeValue = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type))); + return typeValue && memory_.isCompatibleType(typeValue->value, parameter.typeName); +} + +std::shared_ptr Interpreter::resolveReferenceCallable( + const std::shared_ptr& callable, + const std::shared_ptr& source, + const std::shared_ptr& factor, + std::string& normalizedName) { + const auto reference = std::dynamic_pointer_cast(callable); + if (!reference) { + throw InterpreterError(".references 'by' must be a callable reference such as Physics::velocity"); + } + normalizedName = reference->name; + const size_t delimiter = normalizedName.find("::"); + if (delimiter == std::string::npos || delimiter == 0 || + delimiter + 2 >= normalizedName.size() || normalizedName.find("::", delimiter + 2) != std::string::npos) { + throw InterpreterError(".references 'by' must be a two-part callable reference such as Physics::velocity"); + } + normalizedName.replace(delimiter, 2, ":"); + const auto clauses = findClauses(normalizedName, symbolIdForName(normalizedName)); + if (!clauses) { + throw InterpreterError("Unknown referenced callable " + reference->name + "."); + } + + std::shared_ptr selected; + for (const auto& clause : *clauses) { + if (!isMethodClause(*clause) || clause->head.args.size() != 2) continue; + const MethodParamPlan input = makeMethodParamPlan(clause->head.args[0]); + const MethodParamPlan factorParam = makeMethodParamPlan(clause->head.args[1]); + if (input.localName != "input" || factorParam.localName != "factor" || + !input.typedParam || !factorParam.typedParam || + !referenceValueMatchesType(source, input) || + !referenceValueMatchesType(factor, factorParam)) { + continue; + } + if (selected) { + throw InterpreterError("Referenced callable " + reference->name + + " is ambiguous for the source and factor types."); + } + selected = clause; + } + if (!selected) { + throw InterpreterError("Referenced callable " + reference->name + + " must accept compatible typed input and factor parameters."); + } + std::unordered_set visiting; + std::string impurity; + if (!isReferenceMethodPure(selected, visiting, impurity)) { + throw InterpreterError("Referenced callable " + reference->name + " is not pure: " + impurity); + } + return selected; +} + +bool Interpreter::isReferenceMethodPure(const std::shared_ptr& clause, + std::unordered_set& visiting, + std::string& reason) const { + if (!clause || !visiting.insert(clause.get()).second) return true; + auto inspectExpr = [&](const auto& self, const std::shared_ptr& expr) -> bool { + if (!expr) return true; + if (auto term = std::dynamic_pointer_cast(expr)) { + if (term->builtinId != BuiltinId::Unknown && term->builtinId != BuiltinId::Throw && + !isBuiltinPure(term->builtinId)) { + reason = "uses impure builtin '" + term->name + "'"; + return false; + } + if (nativeDeclarationFor(term->name)) { + reason = "uses native callable '" + term->name + "' without a pure capability declaration"; + return false; + } + const auto called = findClauses(term->name, term->nameId); + if (called) for (const auto& next : *called) { + if (isMethodClause(*next) && !isReferenceMethodPure(next, visiting, reason)) return false; + } + for (const auto& arg : term->args) if (!self(self, arg.value)) return false; + } else if (auto array = std::dynamic_pointer_cast(expr)) { + for (const auto& item : array->items) if (!self(self, item)) return false; + } else if (auto map = std::dynamic_pointer_cast(expr)) { + for (const auto& item : map->entries) if (!self(self, item.value)) return false; + } else if (auto access = std::dynamic_pointer_cast(expr)) { + return self(self, access->target); + } else if (auto op = std::dynamic_pointer_cast(expr)) { + for (size_t i = 0; i < op->captureCount(); ++i) { + if (!self(self, op->capture(i))) return false; + } + } else if (auto lambda = std::dynamic_pointer_cast(expr)) { + return self(self, lambda->source) && self(self, lambda->body) && self(self, lambda->right); + } + return true; + }; + auto inspectGoals = [&](const auto& self, const std::vector>& goals) -> bool { + for (const auto& goal : goals) { + if (auto call = std::dynamic_pointer_cast(goal)) { + const auto hasSuffix = [&](const std::string& suffix) { + return call->call.name.size() >= suffix.size() && + call->call.name.compare(call->call.name.size() - suffix.size(), + suffix.size(), suffix) == 0; + }; + if (hasSuffix(":depends") || hasSuffix(":relate") || hasSuffix(":references")) { + reason = "attaches facts"; + return false; + } + if (call->call.builtinId != BuiltinId::Unknown && call->call.builtinId != BuiltinId::Throw && + !isBuiltinPure(call->call.builtinId)) { + reason = "uses impure builtin '" + call->call.name + "'"; + return false; + } + if (nativeDeclarationFor(call->call.name)) { + reason = "uses native callable '" + call->call.name + "' without a pure capability declaration"; + return false; + } + const auto called = findClauses(call->call.name, call->call.nameId); + if (called) for (const auto& next : *called) { + if (isMethodClause(*next) && !isReferenceMethodPure(next, visiting, reason)) return false; + } + for (const auto& arg : call->call.args) if (!inspectExpr(inspectExpr, arg.value)) return false; + } else if (auto assign = std::dynamic_pointer_cast(goal)) { + if (!inspectExpr(inspectExpr, assign->expr)) return false; + } else if (auto ret = std::dynamic_pointer_cast(goal)) { + for (const auto& item : ret->fields) if (!inspectExpr(inspectExpr, item.value)) return false; + } else if (auto conditional = std::dynamic_pointer_cast(goal)) { + if (!self(self, {conditional->condition}) || !self(self, conditional->thenBranch) || + !self(self, conditional->elseBranch)) return false; + } else if (auto group = std::dynamic_pointer_cast(goal)) { + if (!self(self, group->goals)) return false; + } else if (auto alternatives = std::dynamic_pointer_cast(goal)) { + for (const auto& branch : alternatives->branches) if (!self(self, branch)) return false; + } else if (auto where = std::dynamic_pointer_cast(goal)) { + if (!self(self, {where->condition})) return false; + } else if (auto binary = std::dynamic_pointer_cast(goal)) { + if (!inspectExpr(inspectExpr, binary->left) || !inspectExpr(inspectExpr, binary->right)) return false; + } + } + return true; + }; + bool pure = inspectGoals(inspectGoals, clause->body); + for (const auto& branch : clause->fallbackBranches) { + if (pure && !inspectGoals(inspectGoals, branch)) pure = false; + } + visiting.erase(clause.get()); + return pure; +} + +bool Interpreter::attachFactReference(const Call& call, Env& env, std::uint64_t sourceFactId) { + const Arg* by = findArgByNameOrIndex(call, "by", 0); + const Arg* factor = findArgByNameOrIndex(call, "factor", 1); + const Arg* descriptor = findArgByNameOrIndex(call, "as", 2); + if (!by || !factor || !descriptor) { + throw InterpreterError(".references requires 'by', 'factor', and 'as' arguments"); + } + std::shared_ptr factorValue; + std::shared_ptr descriptorValue; + if (!evalExprValue(factor->value, env, factorValue) || + !evalExprValue(descriptor->value, env, descriptorValue)) return false; + const auto descriptorMap = std::dynamic_pointer_cast(descriptorValue); + const auto descriptorType = std::dynamic_pointer_cast( + findMapValue(descriptorValue, internalSymbolString(InternalSymbolKind::Type))); + if (!descriptorMap || !descriptorType || descriptorType->value != "Reference") { + throw InterpreterError(".references 'as' must be a Reference fact"); + } + const auto source = memory_.factValueById(sourceFactId); + if (!source) throw InterpreterError(".references source fact is no longer available"); + std::string callableName; + const auto callable = resolveReferenceCallable(by->value, source, factorValue, callableName); + auto& attachments = referencesBySource_[sourceFactId]; + for (const auto& existing : attachments) { + if (existing.callableName == callableName && existing.descriptor->debug() == descriptorMap->debug() && + existing.defaultFactor->debug() == factorValue->debug()) { + env[internalSymbolString(InternalSymbolKind::Return)] = std::make_shared("ok"); + return true; + } + } + attachments.push_back(ReferenceAttachment{ + nextReferenceAttachmentId_++, sourceFactId, callableName, callable, + factorValue->clone(), std::static_pointer_cast(descriptorMap->clone()), + nextReferenceCreationOrder_++, {}, 0, true}); + env[internalSymbolString(InternalSymbolKind::Return)] = std::make_shared("ok"); + return true; +} + +std::shared_ptr Interpreter::referenceEffectiveFactor(const ReferenceAttachment& attachment) const { + if (auto map = std::dynamic_pointer_cast(attachment.defaultFactor)) { + if (map->factIdentity != 0) { + if (auto current = memory_.factValueById(map->factIdentity)) return current; + } + } + return attachment.defaultFactor->clone(); +} + +bool Interpreter::validateReferenceResult(const std::shared_ptr& value, + std::shared_ptr& result) const { + result = std::dynamic_pointer_cast(value); + const auto resultType = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type))); + const auto derived = findMapValue(value, "result"); + const auto derivedType = std::dynamic_pointer_cast( + findMapValue(derived, internalSymbolString(InternalSymbolKind::Type))); + return result && resultType && resultType->value == "ReferenceResult" && derived && derivedType; +} + +bool Interpreter::evalFactReferences(const Call& call, const Env& env, std::shared_ptr& out) { + const Arg* input = findArgByNameOrIndex(call, "input", 0); + if (!input) throw InterpreterError("Fact.references requires stored fact argument 'input'"); + std::shared_ptr source; + if (!evalExprValue(input->value, env, source)) return false; + const auto sourceId = memory_.logicalFactId(source); + if (!sourceId) throw InterpreterError("Fact.references requires a stored fact with stable logical identity"); + const auto found = referencesBySource_.find(*sourceId); + if (found == referencesBySource_.end()) { + out = std::make_shared(std::vector>{}); + return true; + } + + const Arg* selector = findArgByNameOrIndex(call, "as", std::numeric_limits::max()); + const Arg* overrideArg = findArgByNameOrIndex(call, "factor", std::numeric_limits::max()); + std::shared_ptr selectorValue; + std::shared_ptr overrideValue; + if (selector && !evalExprValue(selector->value, env, selectorValue)) return false; + if (overrideArg && !evalExprValue(overrideArg->value, env, overrideValue)) return false; + const auto selectorMap = std::dynamic_pointer_cast(selectorValue); + if (selector && (!selectorMap || !findMapValue(selectorValue, internalSymbolString(InternalSymbolKind::Type)) || + std::dynamic_pointer_cast(findMapValue(selectorValue, internalSymbolString(InternalSymbolKind::Type)))->value != "Reference")) { + throw InterpreterError("Fact.references 'as' must be a Reference fact"); + } + + std::vector selected; + for (auto& attachment : found->second) { + if (selectorMap && attachment.descriptor->debug() != selectorMap->debug()) continue; + selected.push_back(&attachment); + } + if (selector && selected.empty()) throw InterpreterError("Fact.references selector did not match an attachment"); + if (selector && selected.size() > 1) throw InterpreterError("Fact.references selector is ambiguous"); + + std::vector> staged; + staged.reserve(selected.size()); + const auto currentSource = memory_.factValueById(*sourceId); + if (!currentSource) throw InterpreterError("Fact.references source fact is no longer available"); + for (auto* attachment : selected) { + const std::shared_ptr factor = overrideValue ? overrideValue->clone() : referenceEffectiveFactor(*attachment); + const MethodParamPlan factorParam = makeMethodParamPlan(attachment->callable->head.args[1]); + if (!referenceValueMatchesType(factor, factorParam)) { + throw InterpreterError("Fact.references factor is incompatible with referenced callable " + attachment->callableName); + } + const std::string cycleKey = std::to_string(*sourceId) + ":" + std::to_string(attachment->id) + ":" + factor->debug(); + if (!activeReferenceEvaluations_.insert(cycleKey).second) { + throw InterpreterError("ReferenceEvaluationCycle: " + attachment->callableName); + } + std::shared_ptr evaluated; + try { + TermExpr invocation(attachment->callableName, { + Arg{"input", currentSource->clone()}, Arg{"factor", factor->clone()}}); + if (!evalCallAsValue(invocation, env, evaluated)) { + throw InterpreterError("Referenced callable " + attachment->callableName + " produced no result"); + } + } catch (...) { + activeReferenceEvaluations_.erase(cycleKey); + throw; + } + activeReferenceEvaluations_.erase(cycleKey); + std::shared_ptr validated; + if (!validateReferenceResult(evaluated, validated)) { + throw InterpreterError("Referenced callable " + attachment->callableName + + " must return ReferenceResult(result: TypedFact(...))"); + } + staged.push_back(std::static_pointer_cast(validated->clone())); + } + + if (!overrideValue) { + const std::uint64_t generation = ++referenceEvaluationGeneration_; + for (size_t index = 0; index < selected.size(); ++index) { + selected[index]->canonicalResult = + std::static_pointer_cast(staged[index]->clone()); + selected[index]->canonicalGeneration = generation; + selected[index]->dirty = false; + } + } + std::vector> values; + values.reserve(staged.size()); + for (const auto& value : staged) values.push_back(value->clone()); + out = std::make_shared(std::move(values)); + return true; +} + +bool Interpreter::evalRelationFind(const Call& call, + const Env& env, + std::shared_ptr& out) { + const Arg* inputArg = nullptr; + const Arg* nameArg = nullptr; + for (const auto& arg : call.args) { + if (arg.name == "input" || arg.name == "relationships" || arg.name == "data") inputArg = &arg; + if (arg.name == "name") nameArg = &arg; + } + if (!inputArg && !call.args.empty()) inputArg = &call.args[0]; + if (!nameArg && call.args.size() > 1) nameArg = &call.args[1]; + if (!inputArg || !nameArg) { + throw InterpreterError("Relation.find expects relationship array 'input' and string 'name'"); + } + std::shared_ptr input; + std::shared_ptr nameValue; + if (!evalExprValue(inputArg->value, env, input) || !evalExprValue(nameArg->value, env, nameValue)) return false; + std::string name; + if (!argAsString(nameValue, name)) throw InterpreterError("Relation.find expects string argument 'name'"); + const auto relationships = std::dynamic_pointer_cast(input); + if (!relationships) throw InterpreterError("Relation.find expects an array of relationship facts"); + for (const auto& item : relationships->items) { + auto relationName = findMapValue(item, "name"); + if (!relationName) { + const auto relationKind = findMapValue(item, "as"); + relationName = findMapValue(relationKind, "name"); + } + const auto text = std::dynamic_pointer_cast(relationName); + if (text && text->value == name) { + out = item->clone(); + return true; + } + } + out = std::make_shared(); + return true; +} + +bool Interpreter::evalDependencySatisfied(const Call& call, + const Env& env, + std::shared_ptr& out) { + const Arg* inputArg = nullptr; + for (const auto& arg : call.args) { + if (arg.name == "input" || arg.name == "fact" || arg.name == "value") { + inputArg = &arg; + break; + } + } + if (!inputArg && !call.args.empty()) inputArg = &call.args[0]; + if (!inputArg) throw InterpreterError("Dependency.satisfied expects fact argument 'input'"); + std::shared_ptr input; + if (!evalExprValue(inputArg->value, env, input)) return false; + const auto id = memory_.logicalFactId(input); + const bool satisfied = id && !memory_.hasDependencyCycle(*id) && + memory_.missingDependencies(*id).empty(); + out = std::make_shared(satisfied); + return true; +} + +bool Interpreter::evalRelationCompare(const Call& call, + const Env& env, + std::shared_ptr& out) { + auto argument = [&](const std::string& name, size_t positional) -> std::shared_ptr { + for (const auto& arg : call.args) { + if (arg.name == name) { + std::shared_ptr value; + if (evalExprValue(arg.value, env, value)) return value; + return {}; + } + } + if (positional < call.args.size() && call.args[positional].name.empty()) { + std::shared_ptr value; + if (evalExprValue(call.args[positional].value, env, value)) return value; + } + return {}; + }; + auto source = argument("left", 0); + auto target = argument("right", 1); + std::shared_ptr relationshipSelector; + if (const auto selector = argument("relationship", 5)) { + relationshipSelector = std::dynamic_pointer_cast(selector); + const auto selectorType = std::dynamic_pointer_cast( + findMapValue(selector, internalSymbolString(InternalSymbolKind::Type))); + if (!relationshipSelector || !selectorType || selectorType->value != "Relationship") { + throw InterpreterError( + "Relation.compare relationship must be a Relationship(...) fact pattern"); + } + } + std::string comparisonMode = "directed"; + if (const auto modeValue = argument("mode", 3)) { + const auto mode = std::dynamic_pointer_cast(modeValue); + if (!mode || (mode->value != "directed" && mode->value != "symmetric")) { + throw InterpreterError("Relation.compare mode must be 'directed' or 'symmetric'"); + } + comparisonMode = mode->value; + } + std::size_t maxRelationshipDepth = 4; + if (const auto depthValue = argument("max_depth", 2)) { + const auto number = std::dynamic_pointer_cast(depthValue); + if (!number || number->value < 1.0 || number->value > 64.0 || + std::floor(number->value) != number->value) { + throw InterpreterError("Relation.compare max_depth must be an integer from 1 to 64"); + } + maxRelationshipDepth = static_cast(number->value); + } + std::size_t maxAncestorDepth = 64; + if (const auto depthValue = argument("max_ancestor_depth", 4)) { + const auto number = std::dynamic_pointer_cast(depthValue); + if (!number || number->value < 0.0 || number->value > 64.0 || + std::floor(number->value) != number->value) { + throw InterpreterError("Relation.compare max_ancestor_depth must be an integer from 0 to 64"); + } + maxAncestorDepth = static_cast(number->value); + } + auto sourceMap = std::dynamic_pointer_cast(source); + auto targetMap = std::dynamic_pointer_cast(target); + auto sourceTypeValue = findMapValue(source, internalSymbolString(InternalSymbolKind::Type)); + auto targetTypeValue = findMapValue(target, internalSymbolString(InternalSymbolKind::Type)); + auto sourceType = std::dynamic_pointer_cast(sourceTypeValue); + auto targetType = std::dynamic_pointer_cast(targetTypeValue); + if (!sourceMap || !targetMap || !sourceType || !targetType) { + throw InterpreterError("Relation.compare requires typed fact-compatible 'left' and 'right' values"); + } + + if (comparisonMode == "symmetric") { + // Membership and target interpretation are deliberately directional. + // A symmetric request must therefore retain both proofs rather than + // pretend one direction is canonical or discard a disagreement. + auto direct = [&](const std::shared_ptr& first, + const std::shared_ptr& second, + std::shared_ptr& result) { + Call directional("Relation:compare", {}, BuiltinId::RelationCompare); + directional.args.push_back(Arg{"left", first->clone()}); + directional.args.push_back(Arg{"right", second->clone()}); + directional.args.push_back(Arg{"max_depth", + std::make_shared(static_cast(maxRelationshipDepth))}); + directional.args.push_back(Arg{"max_ancestor_depth", + std::make_shared(static_cast(maxAncestorDepth))}); + if (relationshipSelector) { + directional.args.push_back(Arg{"relationship", relationshipSelector->clone()}); + } + return evalRelationCompare(directional, env, result); + }; + std::shared_ptr forward; + std::shared_ptr reverse; + if (!direct(source, target, forward) || !direct(target, source, reverse)) return false; + const auto forwardState = std::dynamic_pointer_cast(findMapValue(forward, "state")); + const auto reverseState = std::dynamic_pointer_cast(findMapValue(reverse, "state")); + const auto forwardEvidence = findMapValue(forward, "evidence"); + const auto reverseEvidence = findMapValue(reverse, "evidence"); + const auto forwardSimilarity = std::dynamic_pointer_cast( + findMapValue(forwardEvidence, "similarity")); + const auto reverseSimilarity = std::dynamic_pointer_cast( + findMapValue(reverseEvidence, "similarity")); + const bool sameState = forwardState && reverseState && + forwardState->value == reverseState->value; + const bool sameSimilarity = forwardSimilarity && reverseSimilarity && + std::abs(forwardSimilarity->value - reverseSimilarity->value) <= 1e-12; + const bool agrees = sameState && sameSimilarity; + const double similarity = forwardSimilarity && reverseSimilarity + ? (forwardSimilarity->value + reverseSimilarity->value) / 2.0 + : 0.0; + auto result = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("SymmetricComparison")}, + {"mode", std::make_shared("symmetric")}, + {"state", std::make_shared( + agrees ? "agreed" : "directional_difference")}, + {"agrees", std::make_shared(agrees)}, + {"similarity", std::make_shared(similarity)}, + {"forward_similarity", cloneExprOrNil(forwardSimilarity)}, + {"reverse_similarity", cloneExprOrNil(reverseSimilarity)}, + {"forward", forward->clone()}, + {"reverse", reverse->clone()}}); + result->factType = "SymmetricComparison"; + out = std::move(result); + return true; + } + + const auto sourceId = memory_.logicalFactId(source); + const auto targetId = memory_.logicalFactId(target); + // Comparison results are ordinary fact-compatible values and can be + // chained. Other source/target facts must still come from the store. + if (!sourceId && sourceType->value != "Comparison") { + throw InterpreterError("Relation.compare left fact is not present in the fact store or is structurally ambiguous; retrieve it through Fact.all/select"); + } + if (!targetId && targetType->value != "Comparison") { + throw InterpreterError("Relation.compare right fact is not present in the fact store or is structurally ambiguous; retrieve it through Fact.all/select"); + } + + // A constructor-shaped value may mention only its identity fields. Once + // it has been resolved, rules must receive the stored fact's full, + // inherited field set—not the caller's partial reconstruction. + if (sourceId) { + source = memory_.factValueById(*sourceId); + if (!source) throw InterpreterError("Relation.compare source fact is no longer active"); + } + if (targetId) { + target = memory_.factValueById(*targetId); + if (!target) throw InterpreterError("Relation.compare target fact is no longer active"); + } + sourceMap = std::dynamic_pointer_cast(source); + targetMap = std::dynamic_pointer_cast(target); + sourceTypeValue = findMapValue(source, internalSymbolString(InternalSymbolKind::Type)); + targetTypeValue = findMapValue(target, internalSymbolString(InternalSymbolKind::Type)); + sourceType = std::dynamic_pointer_cast(sourceTypeValue); + targetType = std::dynamic_pointer_cast(targetTypeValue); + if (!sourceMap || !targetMap || !sourceType || !targetType) { + throw InterpreterError("Relation.compare resolved fact is invalid"); + } + + // Comparison chaining is still ordinary membership dispatch. The + // standard implementation lives in the built-in core source module, not + // in a separate result-comparison engine or native package. A user + // declaration loaded before execution takes precedence. + if (sourceType->value == "Comparison" && + !findClauses("Comparison:membership", symbolIdForName("Comparison:membership"))) { + ensurePredicateLoaded("Comparison:membership"); + } + const auto& sourceAncestry = typeAncestry(sourceType->value); + const auto& targetAncestry = typeAncestry(targetType->value); + const ComparisonDispatchKey dispatchKey{ + symbolIdForName(sourceType->value), symbolIdForName(targetType->value), + sourceType->value, targetType->value}; + ComparisonDispatchPlan dispatch; + const auto cachedDispatch = comparisonDispatchCache_.find(dispatchKey); + if (cachedDispatch != comparisonDispatchCache_.end()) { + ++dispatchCacheHits_; + dispatch = cachedDispatch->second; + } else { + ++dispatchCacheMisses_; + dispatch.targetFamily = targetType->value; + // Resolution is target-owned. Choosing a method is pure dispatch + // work; its body is still executed only after dependency validation. + for (const auto& family : targetAncestry) { + // Fact is the universal value type, not a target fact family. + // A generic Fact.compareMembership would become an implicit + // second execution path for every comparison and hide the + // structural default. Only concrete target families own + // comparison interpretation. + if (family == "Fact") continue; + const std::string name = family + ":compareMembership"; + auto* clauses = findClauses(name, symbolIdForName(name)); + if (!clauses) continue; + for (const auto& clause : *clauses) { + if (!isMethodClause(*clause)) continue; + bool acceptsContext = false; + for (const auto& parameter : clause->head.args) { + if (parameter.name != "context") continue; + const auto parameterPlan = makeMethodParamPlan(parameter); + acceptsContext = parameterPlan.typedParam && + (parameterPlan.typeName == "Fact" || parameterPlan.typeName == "any"); + break; + } + if (!acceptsContext) continue; + dispatch.comparisonClause = clause; + dispatch.comparisonName = name; + dispatch.targetFamily = family; + break; + } + if (dispatch.comparisonClause) break; + } + + for (const auto& family : sourceAncestry) { + const std::string name = family + ":membership"; + auto* clauses = findClauses(name, symbolIdForName(name)); + if (!clauses) continue; + int bestDistance = std::numeric_limits::max(); + for (const auto& clause : *clauses) { + if (!isMethodClause(*clause)) continue; + int distance = std::numeric_limits::max(); + for (const auto& parameter : clause->head.args) { + if (parameter.name != "against") continue; + const auto parameterPlan = makeMethodParamPlan(parameter); + if (!parameterPlan.typedParam) break; + if (parameterPlan.typeName == "any") { + distance = static_cast(targetAncestry.size()) + 1; + } else if (parameterPlan.typeName == "Fact") { + distance = static_cast(targetAncestry.size()) - 1; + } else { + if (parameterPlan.builtinType) break; + const auto found = std::find(targetAncestry.begin(), targetAncestry.end(), parameterPlan.typeName); + if (found != targetAncestry.end()) { + distance = static_cast(std::distance(targetAncestry.begin(), found)); + } + } + break; + } + if (distance < bestDistance) { + bestDistance = distance; + dispatch.membershipClause = clause; + dispatch.membershipName = name; + } + } + if (dispatch.membershipClause) break; + } + comparisonDispatchCache_.emplace(dispatchKey, dispatch); + } + const auto& comparisonClause = dispatch.comparisonClause; + const auto& comparisonName = dispatch.comparisonName; + const auto& targetFamily = dispatch.targetFamily; + + auto buildResult = [&](const std::string& state, + const std::shared_ptr& membership, + const std::shared_ptr& evidence, + const std::string& reason = {}) { + std::vector entries{ + {internalSymbolString(InternalSymbolKind::Type), std::make_shared("Comparison")}, + {"state", std::make_shared(state)}, + {"source", source->clone()}, + {"target", target->clone()}, + {"targetFamily", std::make_shared(targetFamily)}, + {"membership", cloneExprOrNil(membership)}, + {"evidence", cloneExprOrNil(evidence)}}; + if (!reason.empty()) entries.push_back(MapEntry{"reason", std::make_shared(reason)}); + auto result = std::make_shared(std::move(entries)); + result->factType = "Comparison"; + return result; + }; + + std::vector> missing; + auto appendMissing = [&](const std::optional& id) { + if (!id) return; + for (const auto& dependency : memory_.missingDependencies(*id)) missing.push_back(dependency->clone()); + }; + appendMissing(sourceId); + appendMissing(targetId); + if ((sourceId && memory_.hasDependencyCycle(*sourceId)) || + (targetId && memory_.hasDependencyCycle(*targetId))) { + throw InterpreterError("Relation.compare detected a hard dependency cycle"); + } + if (!missing.empty()) { + auto unresolved = buildResult("unresolved", std::make_shared(), + std::make_shared(std::vector{}), + "required dependency is not satisfied"); + unresolved->entries.push_back(MapEntry{"missingDependencies", std::make_shared(std::move(missing))}); + out = unresolved; + return true; + } + + std::shared_ptr membership; + const auto& membershipClause = dispatch.membershipClause; + const auto& membershipName = dispatch.membershipName; + + const std::string comparisonKey = + (sourceId ? std::to_string(*sourceId) : source->debug()) + "|" + + (targetId ? std::to_string(*targetId) : target->debug()) + "|" + membershipName + "|" + targetFamily; + if (!activeComparisons_.insert(comparisonKey).second) { + throw InterpreterError("Relation.compare detected a comparison cycle for " + sourceType->value + " -> " + targetType->value); + } + struct ComparisonGuard { + std::unordered_set& set; + std::string key; + ~ComparisonGuard() { set.erase(key); } + } guard{activeComparisons_, comparisonKey}; + + if (membershipClause) { + Call membershipCall(membershipName, {{"input", source->clone()}, {"against", target->clone()}}); + if (!invokeComparisonMethod(membershipClause, membershipCall, env, membership)) { + out = buildResult("incomparable", std::make_shared(), + std::make_shared(std::vector{}), + "membership method produced no result"); + return true; + } + } else { + std::vector fields; + for (const auto& entry : sourceMap->entries) { + if (entry.key == internalSymbolString(InternalSymbolKind::Type) || + entry.key == internalSymbolString(InternalSymbolKind::Parent)) continue; + fields.push_back(MapEntry{entry.key, entry.value->clone()}); + } + membership = std::make_shared(std::move(fields)); + } + if (std::dynamic_pointer_cast(membership)) { + out = buildResult("incomparable", membership, + std::make_shared(std::vector{}), + "source cannot produce membership knowledge for this target"); + return true; + } + const auto membershipMap = std::dynamic_pointer_cast(membership); + if (!membershipMap) { + throw InterpreterError("Relation.compare membership method must return a key-value micro-fact or nil"); + } + + std::vector> matched; + std::vector> missingFields; + std::vector> conflicting; + std::vector> unknown; + std::vector> propertyEvidence; + size_t membershipFields = 0; + const double propertyImportance = membershipMap->entries.empty() + ? 0.0 : 1.0 / static_cast(membershipMap->entries.size()); + for (const auto& field : membershipMap->entries) { + ++membershipFields; + const auto targetValue = findMapValue(target, field.key); + std::string status; + if (!targetValue) { + status = "missing"; + missingFields.push_back(std::make_shared(field.key)); + } else if (field.value->debug() == targetValue->debug()) { + status = "matched"; + matched.push_back(std::make_shared(field.key)); + } else { + status = "conflicting"; + conflicting.push_back(std::make_shared(field.key)); + } + auto detail = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("PropertyComparisonEvidence")}, + {"property", std::make_shared(field.key)}, + {"status", std::make_shared(status)}, + {"source_value", field.value->clone()}, + {"target_value", cloneExprOrNil(targetValue)}, + {"importance", std::make_shared(propertyImportance)}, + {"contribution", std::make_shared( + status == "matched" ? propertyImportance : 0.0)}}); + detail->factType = "PropertyComparisonEvidence"; + propertyEvidence.push_back(std::move(detail)); + } + for (const auto& field : targetMap->entries) { + if (field.key == internalSymbolString(InternalSymbolKind::Type) || + field.key == internalSymbolString(InternalSymbolKind::Parent)) continue; + if (!findMapValue(membership, field.key)) unknown.push_back(std::make_shared(field.key)); + } + const bool allMatched = membershipFields > 0 && matched.size() == membershipFields; + const bool exact = allMatched && unknown.empty(); + const bool subset = allMatched && !exact; + const double overlap = membershipFields == 0 ? 0.0 : + static_cast(matched.size()) / static_cast(membershipFields); + bool ancestorContained = memory_.isCompatibleType(sourceType->value, targetType->value); + struct AncestorCandidate { + std::string type; + std::size_t sourceDistance = 0; + std::size_t targetDistance = 0; + double depth = 0.0; + double similarity = 0.0; + }; + std::vector ancestorCandidates; + const auto& sourceDistances = typeAncestorDistances(sourceType->value); + const auto& targetDistances = typeAncestorDistances(targetType->value); + const double sourceDepth = typeHierarchyDepth(sourceType->value); + const double targetDepth = typeHierarchyDepth(targetType->value); + const double depthTotal = sourceDepth + targetDepth; + for (const auto& [ancestor, sourceDistance] : sourceDistances) { + if (ancestor == "Fact") continue; + const auto targetDistance = targetDistances.find(ancestor); + if (targetDistance == targetDistances.end()) continue; + if (sourceDistance > maxAncestorDepth || + targetDistance->second > maxAncestorDepth) continue; + const double commonDepth = typeHierarchyDepth(ancestor); + ancestorCandidates.push_back(AncestorCandidate{ + ancestor, + sourceDistance, + targetDistance->second, + commonDepth, + depthTotal > 0.0 ? (2.0 * commonDepth) / depthTotal : 0.0}); + } + std::sort(ancestorCandidates.begin(), ancestorCandidates.end(), + [](const AncestorCandidate& left, const AncestorCandidate& right) { + if (left.similarity != right.similarity) { + return left.similarity > right.similarity; + } + const auto leftDistance = left.sourceDistance + left.targetDistance; + const auto rightDistance = right.sourceDistance + right.targetDistance; + if (leftDistance != rightDistance) return leftDistance < rightDistance; + return left.type < right.type; + }); + const std::string matchedAncestorName = ancestorCandidates.empty() + ? std::string{} : ancestorCandidates.front().type; + std::shared_ptr matchedAncestor = matchedAncestorName.empty() + ? std::shared_ptr(std::make_shared()) + : std::shared_ptr(std::make_shared(matchedAncestorName)); + const double ancestorDistance = ancestorCandidates.empty() ? 0.0 : + static_cast(ancestorCandidates.front().sourceDistance + + ancestorCandidates.front().targetDistance); + double ancestorSimilarity = 0.0; + if (!ancestorCandidates.empty()) { + ancestorSimilarity = ancestorCandidates.front().similarity; + } + std::vector> ancestorEvidence; + ancestorEvidence.reserve(ancestorCandidates.size()); + for (const auto& candidate : ancestorCandidates) { + auto detail = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("AncestorComparisonEvidence")}, + {"ancestor", std::make_shared(candidate.type)}, + {"source_distance", std::make_shared( + static_cast(candidate.sourceDistance))}, + {"target_distance", std::make_shared( + static_cast(candidate.targetDistance))}, + {"depth", std::make_shared(candidate.depth)}, + {"importance", std::make_shared(candidate.similarity)}}); + detail->factType = "AncestorComparisonEvidence"; + ancestorEvidence.push_back(std::move(detail)); + } + + // Compare bounded relationship neighborhoods as facts, not words. This + // adds explainable multi-hop evidence while keeping cyclic knowledge + // graphs finite and deterministic. + struct RelationPath { + std::size_t depth = 0; + std::uint64_t terminal = 0; + double confidence = 1.0; + }; + const auto relationshipMatches = [&](const FactRelationship& relation) { + if (!relationshipSelector) return true; + if (!relation.relationship) return false; + for (const auto& field : relationshipSelector->entries) { + if (field.keyId == InternalSymbol::TypeId || + field.keyId == InternalSymbol::ParentId) { + continue; + } + const auto actual = findMapValue(relation.relationship, field.key); + if (!actual || !exprEqualsLiteral(actual, field.value)) return false; + } + return true; + }; + auto relationshipNeighborhood = [&](const std::optional& root) { + std::unordered_map paths; + if (!root) return paths; + struct PendingPath { + std::uint64_t factId = 0; + std::size_t depth = 0; + double confidence = 1.0; + }; + std::deque pending{{*root, 0, 1.0}}; + std::unordered_map> visited; + while (!pending.empty()) { + const auto current = pending.front().factId; + const auto depth = pending.front().depth; + const auto pathConfidence = pending.front().confidence; + pending.pop_front(); + const auto seen = visited.find(current); + if (seen != visited.end() && + (seen->second.first < depth || + (seen->second.first == depth && seen->second.second >= pathConfidence))) { + continue; + } + visited[current] = {depth, pathConfidence}; + if (depth >= maxRelationshipDepth) continue; + const auto visitRelationships = [&](const auto& relationships) { + for (const auto& relation : relationships) { + ++relationshipCandidates_; + if (!relationshipMatches(relation)) { + ++relationshipCandidatesPruned_; + continue; + } + const std::uint64_t next = relation.sourceId == current + ? relation.targetId : relation.sourceId; + if (next == 0 || next == current) continue; + const std::string signature = relation.relationship + ? relation.relationship->debug() : std::string("nil"); + double confidence = 1.0; + if (const auto number = std::dynamic_pointer_cast(relation.confidence)) { + confidence = std::clamp(number->value, 0.0, 1.0); + } + const std::size_t nextDepth = depth + 1; + const double combinedConfidence = pathConfidence * confidence; + auto found = paths.find(signature); + if (found == paths.end() || nextDepth < found->second.depth || + (nextDepth == found->second.depth && + combinedConfidence > found->second.confidence)) { + paths[signature] = RelationPath{nextDepth, next, combinedConfidence}; + } + pending.push_back(PendingPath{next, nextDepth, combinedConfidence}); + } + }; + visitRelationships(memory_.outgoingRelationships(current)); + visitRelationships(memory_.incomingRelationships(current)); + } + return paths; + }; + const auto sourceRelationships = relationshipNeighborhood(sourceId); + const auto targetRelationships = relationshipNeighborhood(targetId); + std::vector> relationshipEvidence; + std::vector> relationshipDifferences; + std::size_t sharedRelationships = 0; + double terminalSimilaritySum = 0.0; + std::size_t terminalComparisons = 0; + double sharedConfidenceSum = 0.0; + const auto factTypeForId = [&](std::uint64_t id) -> std::shared_ptr { + const auto value = memory_.factValueById(id); + if (!value) return std::make_shared(); + const auto type = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type))); + return type ? std::static_pointer_cast(type->clone()) + : std::make_shared(); + }; + const auto factTypeNameForId = [&](std::uint64_t id) -> std::string { + const auto value = memory_.factValueById(id); + if (!value) return {}; + const auto type = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type))); + return type ? type->value : std::string{}; + }; + const auto findMapValueById = [](const std::shared_ptr& value, + SymbolId key) -> std::shared_ptr { + const auto map = std::dynamic_pointer_cast(value); + if (!map) return nullptr; + for (const auto& entry : map->entries) { + if (entry.keyId == key) return entry.value; + } + return nullptr; + }; + std::function&, + const std::shared_ptr&, std::size_t)> valueSimilarity; + valueSimilarity = [&](const std::shared_ptr& left, + const std::shared_ptr& right, + std::size_t depth) -> double { + if (!left || !right) return left == right ? 1.0 : 0.0; + if (exprEqualsLiteral(left, right)) return 1.0; + if (depth >= 3) return 0.0; + if (const auto leftMap = std::dynamic_pointer_cast(left)) { + const auto rightMap = std::dynamic_pointer_cast(right); + if (!rightMap) return 0.0; + std::set keys; + for (const auto& entry : leftMap->entries) { + if (entry.keyId != InternalSymbol::TypeId && + entry.keyId != InternalSymbol::ParentId) keys.insert(entry.keyId); + } + for (const auto& entry : rightMap->entries) { + if (entry.keyId != InternalSymbol::TypeId && + entry.keyId != InternalSymbol::ParentId) keys.insert(entry.keyId); + } + if (keys.empty()) return 1.0; + double total = 0.0; + for (const SymbolId key : keys) { + const auto leftValue = findMapValueById(left, key); + const auto rightValue = findMapValueById(right, key); + total += valueSimilarity(leftValue, rightValue, depth + 1); + } + return total / static_cast(keys.size()); + } + if (const auto leftArray = std::dynamic_pointer_cast(left)) { + const auto rightArray = std::dynamic_pointer_cast(right); + if (!rightArray) return 0.0; + if (leftArray->items.empty() || rightArray->items.empty()) { + return leftArray->items.empty() && rightArray->items.empty() ? 1.0 : 0.0; + } + const std::size_t count = std::min(leftArray->items.size(), rightArray->items.size()); + double total = 0.0; + for (std::size_t index = 0; index < count; ++index) { + total += valueSimilarity(leftArray->items[index], rightArray->items[index], depth + 1); + } + return total / static_cast(std::max(leftArray->items.size(), rightArray->items.size())); + } + return 0.0; + }; + const auto typeSimilarity = [&](const std::string& left, + const std::string& right, + std::string& commonAncestor) { + if (left.empty() || right.empty()) return 0.0; + const auto& leftDistances = typeAncestorDistances(left); + const auto& rightDistances = typeAncestorDistances(right); + double best = 0.0; + std::size_t bestDistance = std::numeric_limits::max(); + for (const auto& [ancestor, leftDistance] : leftDistances) { + const auto rightDistance = rightDistances.find(ancestor); + if (rightDistance == rightDistances.end() || ancestor == "Fact") continue; + const double denominator = typeHierarchyDepth(left) + typeHierarchyDepth(right); + const double score = denominator == 0.0 ? 0.0 : + (2.0 * typeHierarchyDepth(ancestor)) / denominator; + const std::size_t distance = leftDistance + rightDistance->second; + if (score > best || (score == best && distance < bestDistance)) { + best = score; + bestDistance = distance; + commonAncestor = ancestor; + } + } + return best; + }; + for (const auto& [signature, sourcePath] : sourceRelationships) { + const auto targetPath = targetRelationships.find(signature); + if (targetPath == targetRelationships.end()) continue; + ++sharedRelationships; + const std::string sourceTerminalType = factTypeNameForId(sourcePath.terminal); + const std::string targetTerminalType = factTypeNameForId(targetPath->second.terminal); + std::string terminalAncestor; + const double terminalTypeSimilarity = typeSimilarity( + sourceTerminalType, targetTerminalType, terminalAncestor); + const auto sourceTerminal = memory_.factValueById(sourcePath.terminal); + const auto targetTerminal = memory_.factValueById(targetPath->second.terminal); + const double terminalPropertySimilarity = valueSimilarity( + sourceTerminal, targetTerminal, 0); + const double terminalSimilarity = sourceTerminal && targetTerminal + ? 0.5 * terminalTypeSimilarity + 0.5 * terminalPropertySimilarity + : terminalTypeSimilarity; + if (!sourceTerminalType.empty() && !targetTerminalType.empty()) { + terminalSimilaritySum += terminalSimilarity; + ++terminalComparisons; + } + const double pathConfidence = sourcePath.confidence * targetPath->second.confidence; + sharedConfidenceSum += pathConfidence; + auto detail = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("RelationshipComparisonEvidence")}, + {"relationship", std::make_shared(signature)}, + {"source_depth", std::make_shared( + static_cast(sourcePath.depth))}, + {"target_depth", std::make_shared( + static_cast(targetPath->second.depth))}, + {"confidence", std::make_shared(pathConfidence)}, + {"terminal_type_similarity", std::make_shared(terminalTypeSimilarity)}, + {"terminal_property_similarity", std::make_shared( + terminalPropertySimilarity)}, + {"source_terminal", factTypeForId(sourcePath.terminal)}, + {"target_terminal", factTypeForId(targetPath->second.terminal)}, + {"terminal_similarity", std::make_shared(terminalSimilarity)}, + {"terminal_common_ancestor", terminalAncestor.empty() + ? std::shared_ptr(std::make_shared()) + : std::shared_ptr(std::make_shared(terminalAncestor))}, + {"matched", std::make_shared(true)}}); + detail->factType = "RelationshipComparisonEvidence"; + relationshipEvidence.push_back(std::move(detail)); + } + auto appendRelationshipDifference = [&](const std::string& signature, + const RelationPath& path, + const std::string& side) { + auto detail = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("RelationshipDifferenceEvidence")}, + {"relationship", std::make_shared(signature)}, + {"side", std::make_shared(side)}, + {"depth", std::make_shared(static_cast(path.depth))}, + {"terminal", factTypeForId(path.terminal)}, + {"matched", std::make_shared(false)}}); + detail->factType = "RelationshipDifferenceEvidence"; + relationshipDifferences.push_back(std::move(detail)); + }; + for (const auto& [signature, path] : sourceRelationships) { + if (targetRelationships.find(signature) == targetRelationships.end()) { + appendRelationshipDifference(signature, path, "source"); + } + } + for (const auto& [signature, path] : targetRelationships) { + if (sourceRelationships.find(signature) == sourceRelationships.end()) { + appendRelationshipDifference(signature, path, "target"); + } + } + const std::size_t relationshipUnion = sourceRelationships.size() + + targetRelationships.size() - sharedRelationships; + const double pathSimilarity = relationshipUnion == 0 ? 0.0 : + static_cast(sharedRelationships) / + static_cast(relationshipUnion); + const double terminalSimilarity = terminalComparisons == 0 ? 0.0 : + terminalSimilaritySum / static_cast(terminalComparisons); + const double relationalConfidence = sharedRelationships == 0 ? 0.0 : + sharedConfidenceSum / static_cast(sharedRelationships); + const double relationshipSimilarity = terminalComparisons == 0 ? pathSimilarity : + 0.5 * pathSimilarity + 0.5 * terminalSimilarity; + const double confidenceWeightedRelationshipSimilarity = + relationshipSimilarity * relationalConfidence; + // Both hierarchy and properties are required. A geometric mean prevents + // coincidentally equal fields in unrelated fact families from producing + // a positive fact-similarity score. + const double structuralSimilarity = std::sqrt(ancestorSimilarity * overlap); + const double similarity = relationshipUnion == 0 ? structuralSimilarity : + (0.70 * structuralSimilarity + + 0.30 * confidenceWeightedRelationshipSimilarity); + std::vector evidenceEntries{ + {"exact", std::make_shared(exact)}, + {"subset", std::make_shared(subset)}, + {"overlap", std::make_shared(overlap)}, + {"propertySimilarity", std::make_shared(overlap)}, + {"ancestorSimilarity", std::make_shared(ancestorSimilarity)}, + {"relationshipSimilarity", std::make_shared(relationshipSimilarity)}, + {"relationalConfidence", std::make_shared(relationalConfidence)}, + {"relationshipMaxDepth", std::make_shared( + static_cast(maxRelationshipDepth))}, + {"relationshipSelector", relationshipSelector + ? std::static_pointer_cast(relationshipSelector->clone()) + : std::shared_ptr(std::make_shared())}, + {"ancestorMaxDepth", std::make_shared( + static_cast(maxAncestorDepth))}, + {"sharedRelationshipCount", std::make_shared( + static_cast(sharedRelationships))}, + {"similarity", std::make_shared(similarity)}, + {"matchedFields", std::make_shared(std::move(matched))}, + {"missingFields", std::make_shared(std::move(missingFields))}, + {"conflictingFields", std::make_shared(std::move(conflicting))}, + {"unknownFields", std::make_shared(std::move(unknown))}, + {"propertyEvidence", std::make_shared( + std::move(propertyEvidence))}, + {"ancestorContained", std::make_shared(ancestorContained)}, + {"matchedAncestor", std::move(matchedAncestor)}, + {"ancestorDistance", std::make_shared(ancestorDistance)}, + {"ancestorEvidence", std::make_shared( + std::move(ancestorEvidence))}, + {"relationshipEvidence", std::make_shared( + std::move(relationshipEvidence))}, + {"relationshipDifferences", std::make_shared( + std::move(relationshipDifferences))}}; + const auto evidence = std::make_shared(std::move(evidenceEntries)); + + std::vector relationshipEntries; + std::unordered_set seenRelationships; + auto appendRelationships = [&](const std::optional& id, const std::string& direction) { + if (!id) return; + const auto append = [&](const auto& relationships) { + for (const auto& relation : relationships) { + const std::string relationshipKey = + std::to_string(relation.sourceId) + "|" + std::to_string(relation.targetId) + "|" + + relation.relationship->debug() + "|" + cloneExprOrNil(relation.degree)->debug() + "|" + + cloneExprOrNil(relation.confidence)->debug(); + if (!seenRelationships.insert(relationshipKey).second) continue; + relationshipEntries.push_back(MapEntry{"relationship", std::make_shared(std::vector{ + {"sourceId", std::make_shared(static_cast(relation.sourceId))}, + {"targetId", std::make_shared(static_cast(relation.targetId))}, + {"as", relation.relationship->clone()}, + {"degree", cloneExprOrNil(relation.degree)}, + {"confidence", cloneExprOrNil(relation.confidence)}, + {"direction", std::make_shared(direction)}})}); + } + }; + append(memory_.outgoingRelationships(*id)); + append(memory_.incomingRelationships(*id)); + }; + appendRelationships(sourceId, "source"); + if (targetId != sourceId) appendRelationships(targetId, "target"); + std::vector> relationshipValues; + for (auto& entry : relationshipEntries) relationshipValues.push_back(entry.value); + std::vector> ancestryValues; + for (const auto& ancestor : targetAncestry) ancestryValues.push_back(std::make_shared(ancestor)); + auto context = std::make_shared(std::vector{ + {internalSymbolString(InternalSymbolKind::Type), + std::make_shared("ComparisonContext")}, + {"source", source->clone()}, {"target", target->clone()}, + {"targetFamily", std::make_shared(targetFamily)}, + {"membership", membership->clone()}, {"targetFields", target->clone()}, + {"ancestry", std::make_shared(std::move(ancestryValues))}, + {"structuralEvidence", evidence->clone()}, + {"relationships", std::make_shared(std::move(relationshipValues))}, + {"dependencyStatus", std::make_shared("satisfied")}}); + context->factType = "ComparisonContext"; + + if (!comparisonClause) { + if (exact) out = buildResult("exact-member", membership, evidence); + else if (subset) out = buildResult("subset-member", membership, evidence); + else if (overlap > 0.0) out = buildResult("partial-member", membership, evidence); + else if (!std::dynamic_pointer_cast(findMapValue(evidence, "conflictingFields"))->items.empty()) { + out = buildResult("conflicting", membership, evidence); + } else out = buildResult("unknown", membership, evidence); + return true; + } + + Call comparisonCall(comparisonName, {{"context", context}}); + std::shared_ptr custom; + if (!invokeComparisonMethod(comparisonClause, comparisonCall, env, custom)) { + throw InterpreterError("Selected target comparison method '" + comparisonName + "' produced no result"); + } + const auto customMap = std::dynamic_pointer_cast(custom); + if (!customMap) throw InterpreterError("compareMembership must return a structured fact"); + std::vector completed = cloneEntries(customMap->entries); + upsertEntry(completed, internalSymbolString(InternalSymbolKind::Type), std::make_shared("Comparison")); + if (!findMapValue(custom, "state")) throw InterpreterError("compareMembership result requires a 'state' field"); + if (!findMapValue(custom, "source")) upsertEntry(completed, "source", source->clone()); + if (!findMapValue(custom, "target")) upsertEntry(completed, "target", target->clone()); + if (!findMapValue(custom, "targetFamily")) upsertEntry(completed, "targetFamily", std::make_shared(targetFamily)); + if (!findMapValue(custom, "membership")) upsertEntry(completed, "membership", membership->clone()); + if (!findMapValue(custom, "evidence")) upsertEntry(completed, "evidence", evidence->clone()); + auto result = std::make_shared(std::move(completed)); + result->factType = "Comparison"; + out = std::move(result); + return true; +} + +bool Interpreter::solveBuiltin(const Call& call, Env& env) { + if (call.builtinId == BuiltinId::CommonAncestors || + call.builtinId == BuiltinId::LowestCommonAncestor || + call.builtinId == BuiltinId::HighestCommonAncestor || + call.builtinId == BuiltinId::AncestorAnalysis || + call.builtinId == BuiltinId::PropagateFact) { + std::shared_ptr result; + const bool evaluated = call.builtinId == BuiltinId::PropagateFact + ? evalFactPropagation(call, env, result) + : evalAncestorAnalysis(call, env, result); + if (!evaluated) return false; + env[InternalSymbol::ReturnId] = result; + for (const auto& argument : call.args) { + if ((argument.name == "result" || argument.name == "out") && + !unifyExpr(argument.value, result, env)) return false; + } + return true; + } + if (call.builtinId == BuiltinId::ReasoningContrary || + call.builtinId == BuiltinId::ReasoningProve || + call.builtinId == BuiltinId::ReasoningGrade || + call.builtinId == BuiltinId::ReasoningDecide) { + TermExpr term(call.name, {}, call.builtinId); + term.nameId = call.nameId; + for (const auto& argument : call.args) { + term.args.emplace_back( + argument.name, + argument.value ? argument.value->clone() + : std::make_shared()); + } + std::shared_ptr result; + if (!evalReasoningBuiltin(term, env, result)) return false; + env[InternalSymbol::ReturnId] = result; + for (const auto& argument : call.args) { + if ((argument.name == "result" || + argument.name == "out") && + !unifyExpr(argument.value, result, env)) return false; + } + return true; + } + if (call.builtinId == BuiltinId::RelationCompare) { + std::shared_ptr result; + if (!evalRelationCompare(call, env, result)) return false; + env[internalSymbolString(InternalSymbolKind::Return)] = result; + for (const auto& arg : call.args) { + if ((arg.name == "result" || arg.name == "out") && !unifyExpr(arg.value, result, env)) return false; + } + return true; + } + if (call.builtinId == BuiltinId::FactReferences) { + std::shared_ptr result; + if (!evalFactReferences(call, env, result)) return false; + env[internalSymbolString(InternalSymbolKind::Return)] = result; + for (const auto& arg : call.args) { + if ((arg.name == "result" || arg.name == "out") && !unifyExpr(arg.value, result, env)) return false; + } + return true; + } + if (solveFactAttachment(call, env)) return true; + const ClauseStmt* nativeDeclaration = nativeDeclarationFor(call.name); + if (!nativeDeclaration) { + ensurePredicateLoaded(call.name); + nativeDeclaration = nativeDeclarationFor(call.name); + } + if (nativeDeclaration) { + Env nativeEnv = env; + if (solveNativeCall(call, nativeEnv)) { + env = std::move(nativeEnv); + return true; + } + } + + auto outArg = [&](const std::string& name, size_t index) -> const Arg* { + return findArgByNameOrIndex(call, name, index); + }; + auto namedArg = [&](const std::string& name) -> const Arg* { + for (const auto& arg : call.args) { + if (arg.name == name) return &arg; + } + return nullptr; + }; + auto valueArg = [&](std::initializer_list names, size_t index, std::shared_ptr& out) -> bool { + const Arg* arg = nullptr; + for (const char* name : names) { + arg = namedArg(name); + if (arg) break; + } + if (!arg && index < call.args.size() && call.args[index].name.empty()) arg = &call.args[index]; + return arg && evalExprValue(arg->value, env, out); + }; + + std::shared_ptr a; + std::shared_ptr b; + std::shared_ptr c; + std::shared_ptr result; + + auto callNativeValueBuiltin = [&]() -> bool { + TermExpr term(call.name, {}, call.builtinId); + for (const auto& arg : call.args) { + if (arg.name == "result" || arg.name == "out" || arg.name == "access") { + continue; + } + term.args.push_back(Arg{arg.name, arg.nameId, arg.value}); + } + std::shared_ptr value; + if (!evalCallAsValue(term, env, value)) return false; + const Arg* out = namedArg("result"); + if (!out) out = namedArg("out"); + if (!out) out = namedArg("access"); + if (!out) out = namedArg("equals"); + if (!out) return true; + return unifyExpr(out->value, value, env); + }; + + const bool mathPredicateBuiltin = + call.builtinId == BuiltinId::MathAdd || + call.builtinId == BuiltinId::MathSub || + call.builtinId == BuiltinId::MathMul || + call.builtinId == BuiltinId::MathDiv || + call.builtinId == BuiltinId::MathMod; + + const bool stringPredicateBuiltin = + call.builtinId == BuiltinId::StrLen || + call.builtinId == BuiltinId::StrContains || + call.builtinId == BuiltinId::StrConcat || + call.builtinId == BuiltinId::StrJoin || + call.builtinId == BuiltinId::StrLower || + call.builtinId == BuiltinId::StrUpper || + call.builtinId == BuiltinId::StrTrim || + call.builtinId == BuiltinId::StrSplit || + call.builtinId == BuiltinId::StrReplace || + call.builtinId == BuiltinId::StrStartsWith || + call.builtinId == BuiltinId::StrEndsWith; + const bool arrayPredicateBuiltin = + call.builtinId == BuiltinId::ArrayGet || + call.builtinId == BuiltinId::ArrayLen || + call.builtinId == BuiltinId::ArrayPush; + const bool pairPredicateBuiltin = + call.builtinId == BuiltinId::PairFirst || + call.builtinId == BuiltinId::PairSecond; + const bool jsonPredicateBuiltin = + call.builtinId == BuiltinId::JsonParse || + call.builtinId == BuiltinId::JsonGet || + call.builtinId == BuiltinId::JsonHas || + call.builtinId == BuiltinId::JsonKeys || + call.builtinId == BuiltinId::JsonSet || + call.builtinId == BuiltinId::JsonRemove || + call.builtinId == BuiltinId::JsonToText; + + if (call.builtinId != BuiltinId::Unknown && + call.builtinId != BuiltinId::Throw && + call.builtinId != BuiltinId::Type && + call.builtinId != BuiltinId::Instanceof && + !mathPredicateBuiltin && + !stringPredicateBuiltin && + !arrayPredicateBuiltin && + !pairPredicateBuiltin && + !jsonPredicateBuiltin) { + return callNativeValueBuiltin(); + } + + if (call.builtinId == BuiltinId::Throw) { + if (!valueArg({"exception"}, 0, a)) { + throw InterpreterError("throw expects a resolvable typed 'exception'"); + } + auto exceptionMap = std::dynamic_pointer_cast(a); + auto exceptionKind = findMapValue(a, "kind"); + auto kindString = std::dynamic_pointer_cast(exceptionKind); + if (!exceptionMap || !kindString) { + throw InterpreterError( + "throw exception must be an object with a string 'kind' field"); + } + env["error_reason"] = exceptionKind->clone(); + + const Arg* target = namedArg("target"); + if (target) { + std::string targetName; + if (auto targetVar = std::dynamic_pointer_cast(target->value)) { + targetName = targetVar->name; + } else { + throw InterpreterError( + "throw target must be a callable reference such as someFunction::Function"); + } + const auto separator = targetName.find("::"); + if (separator == std::string::npos || + targetName.find("::", separator + 2) != std::string::npos) { + throw InterpreterError( + "throw target must be a callable reference such as someFunction::Function"); + } + targetName.replace(separator, 2, ":"); + + Call handler(targetName, {}); + handler.args.push_back(Arg{"exception", a}); + + auto* clauses = findClauses(handler.name, handler.nameId); + if (!clauses && ensurePredicateLoaded(handler.name)) { + clauses = findClauses(handler.name, handler.nameId); + } + if (!clauses) { + throw InterpreterError("Exception handler not found: " + targetName); + } + std::vector handled; + solveRecursive( + {std::make_shared(std::move(handler))}, + env, + handled, + 1, + 0); + if (handled.empty()) return false; + env = std::move(handled.front().env); + } + + const Arg* out = namedArg("out"); + if (!out && call.args.size() > 1 && call.args[1].name.empty()) out = &call.args[1]; + if (out) return unifyExpr(out->value, a, env); + return true; + } + + if (call.builtinId == BuiltinId::Type) { + if (!valueArg({"value", "data", "input"}, 0, a)) return false; + std::string resolvedType; + if (auto ast = std::dynamic_pointer_cast(a)) resolvedType = ast->nodeKind; + else if (auto typeString = std::dynamic_pointer_cast( + findMapValue(a, internalSymbolString(InternalSymbolKind::Type)))) { + resolvedType = typeString->value; + } else if (std::dynamic_pointer_cast(a)) resolvedType = "number"; + else if (std::dynamic_pointer_cast(a)) resolvedType = "string"; + else if (std::dynamic_pointer_cast(a)) resolvedType = "bool"; + else if (std::dynamic_pointer_cast(a)) resolvedType = "array"; + else if (std::dynamic_pointer_cast(a)) resolvedType = "nil"; + else return false; + const Arg* out = namedArg("name"); + if (!out) out = namedArg("type"); + if (!out) out = namedArg("out"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, std::make_shared(resolvedType), env); + } + + if (call.builtinId == BuiltinId::Instanceof) { + if (!valueArg({"value", "data", "input"}, 0, a)) return false; + const Arg* typeArg = namedArg("type"); + if (!typeArg) typeArg = namedArg("parent"); + if (!typeArg) typeArg = namedArg("of"); + if (!typeArg && call.args.size() > 1) typeArg = &call.args[1]; + if (!typeArg) return false; + auto typeValue = findMapValue(a, internalSymbolString(InternalSymbolKind::Type)); + auto typeString = std::dynamic_pointer_cast(typeValue); + if (!typeString) return false; + std::string expected; + if (auto expectedString = std::dynamic_pointer_cast(typeArg->value)) { + expected = expectedString->value; + } else if (auto expectedVar = std::dynamic_pointer_cast(typeArg->value)) { + expected = expectedVar->name; + } else { + return false; + } + return memory_.isCompatibleType(typeString->value, expected); + } + + if (mathPredicateBuiltin) { + if (!valueArg({"lhs", "left"}, 0, a) || !valueArg({"rhs", "right"}, 1, b)) return false; + double left = 0.0; + double right = 0.0; + if (!argAsNumber(a, left) || !argAsNumber(b, right)) return false; + switch (call.builtinId) { + case BuiltinId::MathAdd: + result = std::make_shared(left + right); + break; + case BuiltinId::MathSub: + result = std::make_shared(left - right); + break; + case BuiltinId::MathMul: + result = std::make_shared(left * right); + break; + case BuiltinId::MathDiv: + if (std::fabs(right) < 1e-12) throw InterpreterError("DivisionByZero"); + result = std::make_shared(left / right); + break; + case BuiltinId::MathMod: + if (std::fabs(right) < 1e-12) throw InterpreterError("DivisionByZero"); + result = std::make_shared(std::fmod(left, right)); + break; + default: + return false; + } + const Arg* out = namedArg("result"); + if (!out) out = outArg("out", 2); + return out && unifyExpr(out->value, result, env); + } + + if (stringPredicateBuiltin) { + if (!valueArg({"left", "data", "value"}, 0, a)) return false; + if (call.builtinId == BuiltinId::StrJoin) { + std::vector> items; + if (!exprAsArrayItems(a, items)) return false; + std::string delimiter; + if (!valueArg({"delimiter", "separator"}, 1, b) || !argAsString(b, delimiter)) return false; + std::ostringstream joined; + for (size_t i = 0; i < items.size(); ++i) { + if (i) joined << delimiter; + std::string itemText; + if (argAsString(items[i], itemText)) joined << itemText; + else joined << valueToString(items[i]); + } + result = std::make_shared(joined.str()); + const Arg* out = namedArg("result"); + if (!out) out = outArg("out", 2); + return out && unifyExpr(out->value, result, env); + } + std::string text; + if (!argAsString(a, text)) return false; + if (call.builtinId == BuiltinId::StrLen) { + result = std::make_shared(static_cast(text.size())); + const Arg* out = namedArg("equals"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, result, env); + } + if (call.builtinId == BuiltinId::StrContains) { + if (!valueArg({"needle"}, 1, b)) return false; + std::string needle; + if (!argAsString(b, needle)) return false; + result = std::make_shared( + text.find(needle) != std::string::npos); + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 2); + return out ? unifyExpr(out->value, result, env) : text.find(needle) != std::string::npos; + } + if (call.builtinId == BuiltinId::StrConcat) { + if (!valueArg({"right", "rhs"}, 1, b)) return false; + std::string right; + if (!argAsString(b, right)) return false; + result = std::make_shared(text + right); + const Arg* out = namedArg("result"); + if (!out) out = outArg("out", 2); + return out && unifyExpr(out->value, result, env); + } + if (call.builtinId == BuiltinId::StrTrim) { + result = std::make_shared(Felidae::trim(text)); + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, result, env); + } + if (call.builtinId == BuiltinId::StrSplit) { + if (!valueArg({"delimiter", "separator"}, 1, b)) return false; + std::string delimiter; + if (!argAsString(b, delimiter) || delimiter.empty()) return false; + std::vector> parts; + size_t start = 0; + while (true) { + size_t pos = text.find(delimiter, start); + parts.push_back(std::make_shared(text.substr(start, pos == std::string::npos ? pos : pos - start))); + if (pos == std::string::npos) break; + start = pos + delimiter.size(); + } + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 2); + return out && unifyExpr(out->value, std::make_shared(std::move(parts)), env); + } + if (call.builtinId == BuiltinId::StrReplace) { + if (!valueArg({"search", "needle"}, 1, b)) return false; + std::shared_ptr replacementValue; + const Arg* replacementArg = namedArg("replacement"); + if (!replacementArg) replacementArg = namedArg("with"); + if (!replacementArg || !evalExprValue(replacementArg->value, env, replacementValue)) return false; + std::string search; + std::string replacement; + if (!argAsString(b, search) || !argAsString(replacementValue, replacement) || search.empty()) return false; + size_t pos = 0; + while ((pos = text.find(search, pos)) != std::string::npos) { + text.replace(pos, search.size(), replacement); + pos += replacement.size(); + } + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 3); + return out && unifyExpr(out->value, std::make_shared(text), env); + } + if (call.builtinId == BuiltinId::StrStartsWith || + call.builtinId == BuiltinId::StrEndsWith) { + const bool startsWith = call.builtinId == BuiltinId::StrStartsWith; + if (!valueArg({startsWith ? "prefix" : "suffix"}, 1, b)) return false; + std::string needle; + if (!argAsString(b, needle)) return false; + bool ok = startsWith + ? text.rfind(needle, 0) == 0 + : (needle.size() <= text.size() && text.compare(text.size() - needle.size(), needle.size(), needle) == 0); + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 2); + return out && unifyExpr( + out->value, std::make_shared(ok), env); + } + for (char& ch : text) { + ch = static_cast(call.builtinId == BuiltinId::StrLower + ? std::tolower(static_cast(ch)) + : std::toupper(static_cast(ch))); + } + result = std::make_shared(text); + const Arg* out = namedArg("equals"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, result, env); + } + + if (arrayPredicateBuiltin) { + if (!valueArg({"data", "array"}, 0, a)) return false; + auto args = termArgs(a, BuiltinId::FnArray); + auto arrayTerm = std::dynamic_pointer_cast(a); + if (args.empty() && + !(arrayTerm && arrayTerm->builtinId == BuiltinId::FnArray) && + !std::dynamic_pointer_cast(a)) { + return false; + } + if (call.builtinId == BuiltinId::ArrayLen) { + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, std::make_shared(static_cast(args.size())), env); + } + if (call.builtinId == BuiltinId::ArrayGet) { + if (!valueArg({"position", "index"}, 1, b)) return false; + double index = 0.0; + if (!argAsNumber(b, index) || index < 0 || std::floor(index) != index) return false; + size_t i = static_cast(index); + if (i >= args.size()) return false; + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 2); + return out && unifyExpr(out->value, args[i], env); + } + if (call.builtinId == BuiltinId::ArrayPush) { + if (!valueArg({"value"}, 1, b)) return false; + args.push_back(b); + const Arg* out = namedArg("result"); + if (!out) out = outArg("out", 2); + return out && unifyExpr(out->value, std::make_shared(std::move(args)), env); + } + } + + if (pairPredicateBuiltin) { + if (!valueArg({"data", "pair"}, 0, a)) return false; + auto args = termArgs(a, BuiltinId::FnPair); + if (args.size() != 2) return false; + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, call.builtinId == BuiltinId::PairFirst ? args[0] : args[1], env); + } + + if (call.builtinId == BuiltinId::JsonParse) { + if (!valueArg({"data", "value"}, 0, a)) return false; + std::string jsonText; + if (!argAsString(a, jsonText)) return false; + std::shared_ptr parsed; + if (!parseFlatJsonObject(jsonText, parsed)) return false; + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, parsed, env); + } + + if (call.builtinId == BuiltinId::JsonGet) { + if (!valueArg({"data", "object"}, 0, a) || !valueArg({"key"}, 1, b)) return false; + std::string key; + if (!argAsString(b, key)) return false; + auto value = findMapValue(a, key); + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 2); + if (value && out) return unifyExpr(out->value, value, env); + return false; + } + + if (call.builtinId == BuiltinId::JsonHas || + call.builtinId == BuiltinId::JsonKeys || + call.builtinId == BuiltinId::JsonSet || + call.builtinId == BuiltinId::JsonRemove) { + if (!valueArg({"data", "object"}, 0, a)) return false; + std::vector entries; + if (!exprAsMapEntries(a, entries)) return false; + std::shared_ptr resultValue; + if (call.builtinId == BuiltinId::JsonKeys) { + std::vector> keys; + keys.reserve(entries.size()); + for (const auto& entry : entries) keys.push_back(std::make_shared(entry.key)); + resultValue = std::make_shared(std::move(keys)); + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, resultValue, env); + } + if (!valueArg({"key"}, 1, b)) return false; + std::string key; + if (!argAsString(b, key)) return false; + if (call.builtinId == BuiltinId::JsonHas) { + resultValue = std::make_shared( + static_cast(findMapValue(a, key))); + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 2); + return out && unifyExpr(out->value, resultValue, env); + } + if (call.builtinId == BuiltinId::JsonSet) { + std::shared_ptr value; + const Arg* valueArgPtr = namedArg("value"); + if (!valueArgPtr || !evalExprValue(valueArgPtr->value, env, value)) return false; + upsertEntry(entries, key, cloneExprOrNil(value)); + } else { + removeEntry(entries, key); + } + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", call.builtinId == BuiltinId::JsonSet ? 3 : 2); + return out && unifyExpr(out->value, std::make_shared(std::move(entries)), env); + } + + if (call.builtinId == BuiltinId::JsonToText) { + if (!valueArg({"data", "value"}, 0, a)) return false; + const Arg* out = namedArg("access"); + if (!out) out = outArg("out", 1); + return out && unifyExpr(out->value, std::make_shared(exprToJson(a)), env); + } + + return false; +} + +const ClauseStmt* Interpreter::nativeDeclarationFor(const std::string& name) const { + auto clauses = findClauses(name, symbolIdForName(name)); + if (!clauses) return nullptr; + for (const auto& clause : *clauses) { + if (clause && clause->emptyDeclaration) return clause.get(); + } + return nullptr; +} + +void Interpreter::validateNativeCallTypes(const Call& call, + const ClauseStmt& declaration, + const Env& env, + bool requireDeclaredInputs) { + auto isOutputName = [](const std::string& name) { + return name == "access" || name == "out" || name == "result" || name == "equals"; + }; + if (requireDeclaredInputs) { + for (size_t providedIndex = 0; providedIndex < call.args.size(); ++providedIndex) { + const Arg& provided = call.args[providedIndex]; + if (provided.name.empty()) continue; + bool declaredName = false; + for (const auto& declared : declaration.head.args) { + if (declared.name == provided.name) { + declaredName = true; + break; + } + } + if (!declaredName) { + throw InterpreterError(call.name + " does not declare argument '" + provided.name + "'"); + } + } + } + + for (size_t i = 0; i < declaration.head.args.size(); ++i) { + const Arg& declared = declaration.head.args[i]; + const Arg* provided = findArg(call, declared, i); + auto typeName = std::dynamic_pointer_cast(declared.value); + if (!provided) { + if (requireDeclaredInputs && typeName && isFelidaeBuiltinTypeName(typeName->name) && !isOutputName(declared.name)) { + throw InterpreterError(call.name + " expects argument '" + + (declared.name.empty() ? std::to_string(i) : declared.name) + + "' before calling native library"); + } + continue; + } + if (!typeName || !isFelidaeBuiltinTypeName(typeName->name)) continue; + + std::shared_ptr value; + if (!evalExprValue(provided->value, env, value)) { + if (std::dynamic_pointer_cast(provided->value)) continue; + throw InterpreterError(call.name + " cannot evaluate argument '" + + (declared.name.empty() ? std::to_string(i) : declared.name) + + "' before native type checking"); + } + if (!valueMatchesBuiltinType(value, typeName->name)) { + throw InterpreterError(call.name + " expects argument '" + + (declared.name.empty() ? std::to_string(i) : declared.name) + + "' to be " + typeName->name + " before calling native library"); + } + } +} + +bool Interpreter::solveNativeCall(const Call& call, Env& env) { + const ClauseStmt* declaration = nativeDeclarationFor(call.name); + if (!declaration) return false; + const bool systemLibraryCall = call.name.rfind("system:flibrary:", 0) == 0; + if (!systemLibraryCall && call.builtinId != BuiltinId::Unknown) return false; + const bool genericLibraryLoader = call.name == "system:flibrary:call"; + + std::string moduleName = call.name; + size_t sep = moduleName.find(':'); + if (sep != std::string::npos) moduleName.resize(sep); + if (systemLibraryCall) { + size_t moduleStart = std::string("system:flibrary:").size(); + size_t moduleEnd = call.name.find(':', moduleStart); + moduleName = call.name.substr(moduleStart, moduleEnd == std::string::npos ? std::string::npos : moduleEnd - moduleStart); + } + std::string nativeFunctionName = call.name; + std::shared_ptr loaderArgs; + if (genericLibraryLoader) { + const Arg* moduleArg = findArgByNameOrIndex(call, "module", 0); + const Arg* functionArg = findArgByNameOrIndex(call, "function", 1); + const Arg* argsArg = findArgByNameOrIndex(call, "args", 2); + if (!moduleArg || !functionArg || !argsArg) { + throw InterpreterError("system.flibrary.call expects module, function, and args"); + } + std::shared_ptr moduleValue; + std::shared_ptr functionValue; + std::shared_ptr argsValue; + if (!evalExprValue(moduleArg->value, env, moduleValue) || + !evalExprValue(functionArg->value, env, functionValue) || + !evalExprValue(argsArg->value, env, argsValue)) { + return false; + } + if (!argAsString(moduleValue, moduleName) || moduleName.empty()) { + throw InterpreterError("system.flibrary.call expects string argument 'module'"); + } + std::string functionName; + if (!argAsString(functionValue, functionName) || functionName.empty()) { + throw InterpreterError("system.flibrary.call expects string argument 'function'"); + } + loaderArgs = std::dynamic_pointer_cast(argsValue); + if (!loaderArgs) { + throw InterpreterError("system.flibrary.call expects map argument 'args'"); + } + nativeFunctionName = "system:flibrary:" + moduleName + ":" + functionName; + Call targetCall(nativeFunctionName, {}); + for (const auto& entry : loaderArgs->entries) { + targetCall.args.push_back(Arg{entry.key, entry.keyId, entry.value->clone()}); + } + auto* targetClauses = findClauses(targetCall.name, targetCall.nameId); + if (targetClauses) { + bool matchedDeclaration = false; + std::string firstMismatch; + for (const auto& targetDeclaration : *targetClauses) { + if (!targetDeclaration || !targetDeclaration->emptyDeclaration) continue; + try { + validateNativeCallTypes(targetCall, *targetDeclaration, env, true); + matchedDeclaration = true; + break; + } catch (const InterpreterError& error) { + if (firstMismatch.empty()) firstMismatch = error.what(); + } + } + if (!matchedDeclaration) { + throw InterpreterError(firstMismatch.empty() + ? ("No native declaration overload matches " + nativeFunctionName) + : firstMismatch); + } + } + } + + const NativeLibrary* library = nullptr; + for (const auto& candidate : nativeLibraries_) { + if (candidate.moduleName == moduleName) { + library = &candidate; + break; + } + } + if (!library) { + fs::path baseDir = fs::current_path(); + auto origin = clauseOrigins_.find(declaration); + if (origin != clauseOrigins_.end()) baseDir = origin->second.parent_path(); + fs::path nativeFile = resolveNativeImport(baseDir, moduleName); + if (nativeFile.empty()) { + fs::path root = sourceRootFromBase(baseDir); + const bool nativeModuleExpected = + systemLibraryCall || + fs::exists(root / "native_modules" / moduleName) || + fs::exists(root / "modules" / moduleName); + if (!nativeModuleExpected) return false; + throw InterpreterError("Native module library for '" + moduleName + + "' not found while executing '" + call.name + "'"); + } + loadNativeLibrary(nativeFile); + for (const auto& candidate : nativeLibraries_) { + if (candidate.moduleName == moduleName) { + library = &candidate; + break; + } + } + if (!library) { + throw InterpreterError("Native module library '" + nativeFile.string() + + "' did not register as module '" + moduleName + "'"); + } + } + + validateNativeCallTypes(call, *declaration, env); + const NativeContract& nativeContract = + library->manifest.contractFor(nativeFunctionName); + if (!nativeContract.argumentConstraints.empty()) { + auto valueFor = [&](const std::string& name, size_t index) -> std::shared_ptr { + if (genericLibraryLoader && loaderArgs) { + for (const auto& entry : loaderArgs->entries) { + if (entry.key == name) { + std::shared_ptr value; + return evalExprValue(entry.value, env, value) ? value : nullptr; + } + } + return {}; + } + const Arg* arg = findArgByNameOrIndex(call, name, index); + if (!arg) return {}; + std::shared_ptr value; + if (!evalExprValue(arg->value, env, value)) return {}; + return value; + }; + auto numberValueFor = [&](const std::string& name, size_t index, double& out) -> bool { + auto value = valueFor(name, index); + if (!value) return false; + auto number = std::dynamic_pointer_cast(value); + if (!number) return false; + out = number->value; + return true; + }; + auto validateConstraint = [&](const NativeArgumentConstraint& constraint) { + const auto value = valueFor(constraint.name, constraint.positionalIndex); + if (!value) { + if (constraint.required) { + throw InterpreterError("FactConfigError: missing '" + constraint.name + "' before calling native library"); + } + return; + } + switch (constraint.kind) { + case NativeArgumentConstraintKind::StringOption: { + std::string text; + if (!argAsString(value, text)) { + throw InterpreterError("FactConfigError: '" + constraint.name + "' expects a string before calling native library"); + } + if (std::find(constraint.allowedValues.begin(), constraint.allowedValues.end(), text) == + constraint.allowedValues.end()) { + throw InterpreterError("FactConfigError: unsupported " + constraint.name + " '" + text + "' before calling native library"); + } + return; + } + case NativeArgumentConstraintKind::UnitInterval: + case NativeArgumentConstraintKind::PositiveFinite: { + double number = 0.0; + const bool valid = numberValueFor(constraint.name, constraint.positionalIndex, number) && + std::isfinite(number) && + (constraint.kind != NativeArgumentConstraintKind::UnitInterval || + (number >= 0.0 && number <= 1.0)) && + (constraint.kind != NativeArgumentConstraintKind::PositiveFinite || number >= 1.0); + if (!valid) { + throw InterpreterError(constraint.kind == NativeArgumentConstraintKind::UnitInterval + ? ("FactConfigError: '" + constraint.name + "' must be between 0 and 1 before calling native library") + : ("FactConfigError: '" + constraint.name + "' must be a positive finite number before calling native library")); + } + return; + } + case NativeArgumentConstraintKind::StringArray: { + const auto array = std::dynamic_pointer_cast(value); + if (!array) { + throw InterpreterError("FactConfigError: '" + constraint.name + "' expects an array of strings before calling native library"); + } + for (const auto& item : array->items) { + const auto text = std::dynamic_pointer_cast(item); + if (!text || text->value.empty()) { + throw InterpreterError("FactConfigError: '" + constraint.name + "' expects non-empty string field names before calling native library"); + } + } + return; + } + case NativeArgumentConstraintKind::BooleanText: { + if (std::dynamic_pointer_cast(value)) return; + std::string text; + if (!argAsString(value, text) || (text != "true" && text != "false")) { + throw InterpreterError("FactConfigError: '" + constraint.name + "' expects \"true\" or \"false\" before calling native library"); + } + return; + } + } + }; + for (const auto& constraint : nativeContract.argumentConstraints) { + validateConstraint(constraint); + } + + #if 0 // Replaced by native manifest argument_constraints. + if (false) { + requireOption("lexical_algorithm", 3, {"path", "wup", "wu_palmer", "Wu-Palmer", "Wu Palmer", "resnik", "jiang_conrath", "Jiang-Conrath", "Jiang Conrath", "lin", "edit", "Leacock-Chodorow", "Leacock–Chodorow", "Leacock Chodorow", "leacock_chodorow", "lch"}, false); + } + } + + #endif + } + const auto serializationStart = std::chrono::steady_clock::now(); + std::ostringstream json; + json << "{"; + bool first = true; + std::vector outputArgs; + const bool selectionAwareNative = nativeContract.capabilities.acceptsFactSelections; + std::function(const std::shared_ptr&)> materializeNativeValue; + materializeNativeValue = [&](const std::shared_ptr& value) -> std::shared_ptr { + if (!selectionAwareNative || !value) return value; + const auto kind = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type))); + if (kind && kind->value == "FactSelection") { + return materializeFactSelection(value); + } + if (auto array = std::dynamic_pointer_cast(value)) { + std::vector> items; + items.reserve(array->items.size()); + for (const auto& item : array->items) items.push_back(materializeNativeValue(item)); + return std::make_shared(std::move(items)); + } + return value; + }; + if (genericLibraryLoader) { + for (const auto& entry : loaderArgs->entries) { + std::shared_ptr value; + if (!evalExprValue(entry.value, env, value)) return false; + if (!first) json << ","; + first = false; + json << "\"" << jsonEscape(entry.key) << "\":" + << exprToJson(materializeNativeValue(value)); + } + } else { + for (size_t i = 0; i < call.args.size(); ++i) { + const Arg& arg = call.args[i]; + std::shared_ptr value; + if (!evalExprValue(arg.value, env, value)) { + if (std::dynamic_pointer_cast(arg.value)) { + outputArgs.push_back(&arg); + continue; + } + return false; + } + value = materializeNativeValue(value); + if (!first) json << ","; + first = false; + std::string key = arg.name.empty() ? ("arg" + std::to_string(i)) : arg.name; + json << "\"" << jsonEscape(key) << "\":" << exprToJson(value); + } + } + const NativeCapabilities& capabilities = nativeContract.capabilities; + bool callerProvidedFacts = false; + if (genericLibraryLoader && loaderArgs) { + callerProvidedFacts = std::any_of( + loaderArgs->entries.begin(), loaderArgs->entries.end(), + [](const MapEntry& entry) { return entry.key == "facts"; }); + } else { + callerProvidedFacts = std::any_of( + call.args.begin(), call.args.end(), + [](const Arg& arg) { return arg.name == "facts"; }); + } + if (capabilities.needsFactProjection && !callerProvidedFacts) { + if (!first) json << ","; + first = false; + const std::streampos projectionStart = json.tellp(); + json << "\"__facts\":["; + bool firstFact = true; + std::size_t projectedRows = 0; + std::unordered_set projectedIndexes; + for (const auto& requestedType : capabilities.requestedFactTypes) { + for (const size_t factIndex : + memory_.selectionIndexes(requestedType)) { + if (!projectedIndexes.insert(factIndex).second) continue; + if (projectedRows >= capabilities.maximumProjectedRows) { + throw InterpreterError( + "NativeProjectionLimit: native function '" + + nativeFunctionName + "' requested more than " + + std::to_string(capabilities.maximumProjectedRows) + + " fact rows"); + } + const auto value = memory_.factValue(factIndex); + if (!value) continue; + std::shared_ptr projected = value; + if (!capabilities.requestedFactFields.empty()) { + std::vector fields; + fields.reserve( + capabilities.requestedFactFields.size() + 1); + for (const auto& entry : value->entries) { + if (entry.key == + internalSymbolString( + InternalSymbolKind::Type) || + std::find( + capabilities.requestedFactFields.begin(), + capabilities.requestedFactFields.end(), + entry.key) != + capabilities.requestedFactFields.end()) { + fields.push_back(entry); + } + } + projected = + std::make_shared(std::move(fields)); + } + if (!firstFact) json << ","; + firstFact = false; + json << exprToJson(projected); + ++projectedRows; + } + } + json << "]"; + const std::streampos projectionEnd = json.tellp(); + if (projectionStart >= 0 && projectionEnd >= projectionStart) { + nativeFactProjectionBytes_ += + static_cast(projectionEnd - projectionStart); + } + ++nativeFactProjectionCalls_; + } + if (capabilities.needsFactHierarchy && !callerProvidedFacts) { + if (!first) json << ","; + json << "\"__parents\":{"; + bool firstParent = true; + std::set emittedChildren; + for (const auto& relation : memory_.hierarchyEdges()) { + if (!emittedChildren.insert(relation.first).second) continue; + if (!firstParent) json << ","; + firstParent = false; + const auto parents = memory_.parentsOf(relation.first); + json << "\"" << jsonEscape(relation.first) << "\":["; + for (size_t index = 0; index < parents.size(); ++index) { + if (index) json << ","; + json << "\"" << jsonEscape(parents[index]) << "\""; + } + json << "]"; + } + json << "}"; + } + json << "}"; + + const std::string requestJson = json.str(); + nativeSerializationMicros_ += static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now() - serializationStart).count()); + ++nativeCalls_; + nativeRequestBytes_ += requestJson.size(); + char* response = library->call(nativeFunctionName.c_str(), requestJson.c_str()); + if (!response) throw InterpreterError("Native function '" + nativeFunctionName + "' returned a null response"); + std::string responseText(response); + library->free(response); + + std::shared_ptr parsed; + size_t pos = 0; + if (!parseJsonValue(responseText, pos, parsed)) { + throw InterpreterError("Native function '" + nativeFunctionName + "' returned invalid JSON"); + } + skipJsonWs(responseText, pos); + if (pos != responseText.size()) { + throw InterpreterError("Native function '" + nativeFunctionName + "' returned trailing data after JSON"); + } + + if (auto errorValue = findMapValue(parsed, "error")) { + std::string message; + if (argAsString(errorValue, message) && !message.empty()) { + throw InterpreterError("Native function '" + nativeFunctionName + "' failed: " + message); + } + } + + env[internalSymbolString(InternalSymbolKind::Return)] = parsed->clone(); + if (outputArgs.empty()) return true; + + auto returnedMap = std::dynamic_pointer_cast(parsed); + for (const Arg* outArg : outputArgs) { + std::shared_ptr value; + if (returnedMap) { + if (!outArg->name.empty()) value = findMapValue(parsed, outArg->name); + if (!value) value = findMapValue(parsed, "access"); + if (!value) value = findMapValue(parsed, "out"); + if (!value) value = findMapValue(parsed, "result"); + if (!value) value = findMapValue(parsed, "value"); + if (!value && returnedMap->entries.size() == 1) value = returnedMap->entries.front().value; + if (!value && (outArg->name == "result" || outArg->name == "out" || + outArg->name == "access" || outArg->name == "equals")) { + value = parsed; + } + } else { + value = parsed; + } + if (!value || !unifyExpr(outArg->value, value, env)) return false; + } + return true; +} + +bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::shared_ptr& out) { + if (term.builtinId == BuiltinId::CommonAncestors || + term.builtinId == BuiltinId::LowestCommonAncestor || + term.builtinId == BuiltinId::HighestCommonAncestor || + term.builtinId == BuiltinId::AncestorAnalysis || + term.builtinId == BuiltinId::PropagateFact) { + Call call(term.name, {}, term.builtinId); + for (const auto& arg : term.args) call.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + return term.builtinId == BuiltinId::PropagateFact + ? evalFactPropagation(call, env, out) + : evalAncestorAnalysis(call, env, out); + } + if (term.builtinId == BuiltinId::ReasoningContrary || + term.builtinId == BuiltinId::ReasoningProve || + term.builtinId == BuiltinId::ReasoningGrade || + term.builtinId == BuiltinId::ReasoningDecide) { + // Reasoning.prove/decide must receive the predicate syntax itself; + // evaluating that term first would execute it and discard proof + // identity. The reasoning runtime resolves only its query arguments. + return evalReasoningBuiltin(term, env, out); + } + std::vector> args; + args.reserve(term.args.size()); + for (const auto& arg : term.args) { + std::shared_ptr value; + if (!evalExprValue(arg.value, env, value)) { + if (auto var = std::dynamic_pointer_cast(arg.value)) { + if (var->isCapitalized) { + value = arg.value->clone(); + } else { + return false; + } + } else { + return false; + } + } + args.push_back(value); + } + + if (term.builtinId == BuiltinId::SystemRun) { + if (args.size() != 1) { + throw InterpreterError("system.run expects one Felidae source string"); + } + const auto source = std::dynamic_pointer_cast(args.front()); + if (!source) throw InterpreterError("system.run expects a string source"); + try { + auto tokenizer = std::make_shared(); + IntegerTokenList tokenList(std::move(tokenizer), source->value); + IntegerParser parser(tokenList); + if (parser.startsQuery()) { + const auto solutions = solve(parser.parseQuery()); + std::vector> resultItems; + resultItems.reserve(solutions.size()); + for (const auto& solution : solutions) { + std::vector bindings; + for (const auto& binding : solution.env) { + if (binding.first <= InternalSymbol::SystemResultId) continue; + const std::string name = symbolNameForId(binding.first); + if (name.empty() || isInternalGeneratedSymbolId(binding.first)) continue; + const auto value = resolveExpr(binding.second, solution.env); + if (value) bindings.emplace_back(name, value->clone()); + } + std::sort(bindings.begin(), bindings.end(), [](const MapEntry& left, const MapEntry& right) { + return left.key < right.key; + }); + auto solutionValue = std::make_shared(std::move(bindings)); + solutionValue->factType = "QuerySolution"; + resultItems.push_back(std::move(solutionValue)); + } + auto result = std::make_shared(std::vector{ + {"solutions", std::make_shared(std::move(resultItems))}, + {"count", std::make_shared(static_cast(solutions.size()))} + }); + result->factType = "QueryResult"; + out = std::move(result); + return true; + } + return evalExprValue(parser.parseExpressionText(), env, out); + } catch (const IntegerParserError& error) { + throw InterpreterError(std::string("system.run parse error: ") + error.what()); + } + } + + if (term.builtinId == BuiltinId::FactAndWhere || + term.builtinId == BuiltinId::FactOrWhere || + term.builtinId == BuiltinId::FactLimit) { + const auto argument = [&](const char* name, std::size_t positional) + -> std::shared_ptr { + for (std::size_t index = 0; index < term.args.size(); ++index) { + if (term.args[index].name == name) return args[index]; + } + return positional < args.size() ? args[positional] : nullptr; + }; + const auto selection = std::dynamic_pointer_cast(argument("selection", 0)); + if (!selection) throw InterpreterError("Fact selection operation expects Type.where(...)"); + if (term.builtinId == BuiltinId::FactLimit) { + const auto count = std::dynamic_pointer_cast(argument("records", 1)); + if (!count || count->value < 0 || std::floor(count->value) != count->value) { + throw InterpreterError("Fact.limit expects a non-negative integer records value"); + } + auto rows = materializeFactSelection(selection); + if (rows->items.size() > static_cast(count->value)) { + rows->items.resize(static_cast(count->value)); + } + out = std::move(rows); + return true; + } + const auto match = std::dynamic_pointer_cast(argument("match", 1)); + if (!match) throw InterpreterError("Fact filter expects a map of fields"); + auto filtered = std::static_pointer_cast(selection->clone()); + for (const auto& field : match->entries) { + filtered->filters.push_back(FactSelectionFilter{ + field.key, field.keyId, TokenId::EQUAL, + field.value ? field.value->clone() : std::make_shared()}); + } + if (term.builtinId == BuiltinId::FactAndWhere) { + out = std::move(filtered); + return true; + } + auto alternative = std::static_pointer_cast(selection->clone()); + alternative->filters.clear(); + for (const auto& field : match->entries) { + alternative->filters.push_back(FactSelectionFilter{ + field.key, field.keyId, TokenId::EQUAL, + field.value ? field.value->clone() : std::make_shared()}); + } + auto left = materializeFactSelection(selection); + auto right = materializeFactSelection(alternative); + std::unordered_set seen; + std::vector> rows; + rows.reserve(left->items.size() + right->items.size()); + const auto append = [&](const std::shared_ptr& value) { + const auto map = std::dynamic_pointer_cast(value); + const auto id = map ? map->factIdentity : 0; + if (id == 0 || seen.insert(id).second) rows.push_back(value->clone()); + }; + for (const auto& value : left->items) append(value); + for (const auto& value : right->items) append(value); + out = std::make_shared(std::move(rows)); + return true; + } + + if (term.builtinId == BuiltinId::FactInsert || + term.builtinId == BuiltinId::FactUpdate || + term.builtinId == BuiltinId::FactDelete) { + const auto argument = [&](const char* name, std::size_t positional) + -> std::shared_ptr { + for (std::size_t index = 0; index < term.args.size(); ++index) { + if (term.args[index].name == name) return args[index]; + } + return positional < args.size() ? args[positional] : nullptr; + }; + if (term.builtinId == BuiltinId::FactInsert) { + const auto type = std::dynamic_pointer_cast(argument("type", 0)); + const auto value = std::dynamic_pointer_cast(argument("values", 1)); + if (!type || type->value.empty() || !value) { + throw InterpreterError("Type.insert expects a type and values map"); + } + auto inserted = std::static_pointer_cast(value->clone()); + inserted->factType = type->value; + memory_.addFact(type->value, {}, inserted, currentLoadingFile_); + out = inserted; + return true; + } + const auto selection = std::dynamic_pointer_cast(argument("selection", 0)); + if (!selection) throw InterpreterError("Fact mutation expects a Type.where(...) selection"); + const auto rows = materializeFactSelection(selection); + std::vector indexes; + indexes.reserve(rows->items.size()); + for (const auto& row : rows->items) { + const auto map = std::dynamic_pointer_cast(row); + if (!map || map->factIdentity == 0) continue; + const auto index = memory_.factIndexById(map->factIdentity); + if (index) indexes.push_back(*index); + } + if (term.builtinId == BuiltinId::FactDelete) { + out = std::make_shared(static_cast(memory_.deactivateFacts(indexes))); + return true; + } + const auto patch = std::dynamic_pointer_cast(argument("values", 1)); + if (!patch) throw InterpreterError("Fact.update expects a values map"); + std::size_t updated = 0; + for (const size_t index : indexes) { + const auto current = memory_.factValue(index); + if (!current) continue; + auto next = std::static_pointer_cast(current->clone()); + for (const auto& field : patch->entries) upsertEntry(next->entries, field.key, cloneExprOrNil(field.value)); + if (memory_.replaceFact(index, std::move(next))) ++updated; + } + out = std::make_shared(static_cast(updated)); + return true; + } + + if (term.builtinId == BuiltinId::Type) { + if (args.size() != 1) return false; + if (auto ast = std::dynamic_pointer_cast(args.front())) { + out = std::make_shared(ast->nodeKind); + return true; + } + if (auto type = std::dynamic_pointer_cast( + findMapValue(args.front(), internalSymbolString(InternalSymbolKind::Type)))) { + out = type->clone(); + return true; + } + if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("number"); + else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("string"); + else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("bool"); + else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("array"); + else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("nil"); + else return false; + return true; + } + + if (term.builtinId == BuiltinId::FnPair) { + if (args.size() != 2) return false; + out = std::make_shared("fn:pair", std::vector{{"first", args[0]}, {"last", args[1]}}, BuiltinId::FnPair); + return true; + } + if (term.builtinId == BuiltinId::FnTuple) { + std::vector termArgs; + termArgs.reserve(args.size()); + for (auto& arg : args) termArgs.push_back(Arg{"value", arg}); + out = std::make_shared("fn:tuple", std::move(termArgs), BuiltinId::FnTuple); + return true; + } + if (term.builtinId == BuiltinId::FnArray) { + if (args.size() == 1) { + if (auto array = std::dynamic_pointer_cast(args[0])) { + out = array->clone(); + return true; + } + } + std::vector termArgs; + termArgs.reserve(args.size()); + for (auto& arg : args) termArgs.push_back(Arg{"data", arg}); + out = std::make_shared("fn:array", std::move(termArgs), BuiltinId::FnArray); + return true; + } + if (term.builtinId == BuiltinId::JsonObject) { + std::vector termArgs; + termArgs.reserve(args.size()); + for (auto& arg : args) termArgs.push_back(Arg{"field", arg}); + out = std::make_shared("json:object", std::move(termArgs), BuiltinId::JsonObject); + return true; + } + auto hasCallableBody = [&]() { + auto* clauses = findClauses(term.name, term.nameId); + if (!clauses && ensurePredicateLoaded(term.name)) clauses = findClauses(term.name, term.nameId); + if (!clauses) return false; + for (const auto& clause : *clauses) { + if (!clause->body.empty() || isMethodClause(*clause)) return true; + } + return false; + }; + if (hasMethod(term.name) || hasCallableBody()) return evalCallAsValue(term, env, out); + if (term.builtinId != BuiltinId::Unknown) return evalCallAsValue(term, env, out); + if (term.name.find(':') != std::string::npos && !term.args.empty()) { + if (evalCallAsValue(term, env, out)) return true; + } + + if (term.name.find(':') == std::string::npos && !term.args.empty()) { + std::vector entries; + entries.push_back(MapEntry{std::string(internalSymbolName(InternalSymbolKind::Type)), std::make_shared(term.name)}); + for (size_t i = 0; i < term.args.size(); ++i) { + const auto& arg = term.args[i]; + if (arg.name.empty()) { + entries.push_back(MapEntry{"value", args[i]}); + } else { + entries.push_back(MapEntry{arg.name, args[i]}); + } + } + auto fact = std::make_shared(std::move(entries)); + fact->factType = term.name; + out = std::move(fact); + return true; + } + + std::vector termArgs; + termArgs.reserve(args.size()); + for (auto& arg : args) termArgs.push_back(Arg{"value", arg}); + out = std::make_shared(term.name, std::move(termArgs), term.builtinId); + return true; +} + +bool Interpreter::evalCallAsValue(const TermExpr& term, const Env& env, std::shared_ptr& out) { + TermExpr current(term.name, {}, term.builtinId); + current.nameId = term.nameId; + current.args.reserve(term.args.size()); + for (const auto& argument : term.args) { + current.args.push_back(Arg{argument.name, argument.nameId, argument.value->clone()}); + } + Env currentEnv = env; + ++valueCallTrampolineDepth_; + try { + while (true) { + try { + const bool result = evalCallAsValueOnce(current, currentEnv, out); + --valueCallTrampolineDepth_; + return result; + } catch (TailCallSignal& signal) { + current = std::move(signal.term); + currentEnv = std::move(signal.env); + } + } + } catch (...) { + --valueCallTrampolineDepth_; + throw; + } +} + +bool Interpreter::evalCallAsValueOnce( + const TermExpr& term, + const Env& env, + std::shared_ptr& out) { + const BuiltinId builtin = term.builtinId; + if (builtin == BuiltinId::CommonAncestors || + builtin == BuiltinId::LowestCommonAncestor || + builtin == BuiltinId::HighestCommonAncestor || + builtin == BuiltinId::AncestorAnalysis || + builtin == BuiltinId::PropagateFact) { + Call call(term.name, {}, builtin); + for (const auto& arg : term.args) call.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + return builtin == BuiltinId::PropagateFact + ? evalFactPropagation(call, env, out) + : evalAncestorAnalysis(call, env, out); + } + if (builtin == BuiltinId::RelationCompare) { + Call call(term.name, {}, builtin); + for (const auto& arg : term.args) call.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + return evalRelationCompare(call, env, out); + } + if (builtin == BuiltinId::FactReferences) { + Call call(term.name, {}, builtin); + for (const auto& arg : term.args) call.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + return evalFactReferences(call, env, out); + } + if (builtin == BuiltinId::RelationFind || builtin == BuiltinId::DependencySatisfied) { + Call call(term.name, {}, builtin); + for (const auto& arg : term.args) call.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + return builtin == BuiltinId::RelationFind + ? evalRelationFind(call, env, out) + : evalDependencySatisfied(call, env, out); + } + { + Call attachment(term.name, {}); + for (const auto& arg : term.args) attachment.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + Env attachmentEnv = env; + if (solveFactAttachment(attachment, attachmentEnv)) { + const auto returned = attachmentEnv.find(internalSymbolString(InternalSymbolKind::Return)); + if (returned == attachmentEnv.end()) return false; + out = resolveExpr(returned->second, attachmentEnv)->clone(); + return true; + } + } + if (!nativeDeclarationFor(term.name)) { + ensurePredicateLoaded(term.name); + } + + auto* declaredClauses = findClauses(term.name, term.nameId); + if (declaredClauses) { + for (const auto& clause : *declaredClauses) { + if (bodyHasReturnGoal(clause->body)) continue; + std::string outputName; + size_t missingCount = 0; + for (const auto& parameter : clause->head.args) { + if (parameter.name.empty()) continue; + bool supplied = false; + for (const auto& argument : term.args) { + if (argument.name == parameter.name) { + supplied = true; + break; + } + } + if (!supplied) { + outputName = parameter.name; + ++missingCount; + } + } + if (missingCount != 1) continue; + + const std::string outputVariable = "\x1fvalue_call_output"; + Call outputCall(term.name, {}, term.builtinId); + for (const auto& argument : term.args) { + outputCall.args.push_back(Arg{argument.name, argument.nameId, argument.value->clone()}); + } + outputCall.args.push_back( + Arg{outputName, std::make_shared(outputVariable)}); + + std::vector solutions; + { + PipelineResultClearScope clearPipelineResults(pipelineResults_); + solveRecursive( + {std::make_shared(std::move(outputCall))}, + env, + solutions, + 1, + 0); + } + if (!solutions.empty()) { + auto value = solutions.front().env.find(outputVariable); + if (value != solutions.front().env.end()) { + out = resolveExpr(value->second, solutions.front().env)->clone(); + return true; + } + } + } + + } + + if (nativeDeclarationFor(term.name)) { + Call nativeCall(term.name, {}, term.builtinId); + for (const auto& arg : term.args) nativeCall.args.push_back(Arg{arg.name, arg.nameId, arg.value->clone()}); + Env nativeEnv = env; + if (solveNativeCall(nativeCall, nativeEnv)) { + auto returned = nativeEnv.find(internalSymbolString(InternalSymbolKind::Return)); + if (returned != nativeEnv.end()) { + if (auto returnedMap = std::dynamic_pointer_cast(returned->second)) { + if (returnedMap->entries.size() == 1) { + out = returnedMap->entries.front().value->clone(); + return true; + } + } + out = returned->second->clone(); + return true; + } + } + } + + std::vector> args; + args.reserve(term.args.size()); + for (const auto& arg : term.args) { + std::shared_ptr value; + if (!evalExprValue(arg.value, env, value)) { + if (auto var = std::dynamic_pointer_cast(arg.value)) { + if (var->isCapitalized) { + value = arg.value->clone(); + } else { + return false; + } + } else { + return false; + } + } + args.push_back(value); + } + + auto* callableClauses = findClauses(term.name, term.nameId); + if (!callableClauses && ensurePredicateLoaded(term.name)) { + callableClauses = findClauses(term.name, term.nameId); + } + bool callableBody = false; + if (callableClauses) { + for (const auto& clause : *callableClauses) { + if (!clause->body.empty() || isMethodClause(*clause)) { + callableBody = true; + break; + } + } + } + if (callableBody && !nativeDeclarationFor(term.name)) { + if (!callableClauses) return false; + for (const auto& clause : *callableClauses) { + if (clause->body.empty() && !isMethodClause(*clause)) continue; + Call call(term.name, {}, term.builtinId); + const auto parameterPlans = buildMethodParamPlan(*clause); + for (size_t argumentIndex = 0; argumentIndex < term.args.size(); ++argumentIndex) { + const auto& argument = term.args[argumentIndex]; + bool preserveAst = false; + for (size_t parameterIndex = 0; parameterIndex < clause->head.args.size(); ++parameterIndex) { + const auto& parameter = clause->head.args[parameterIndex]; + if ((!argument.name.empty() && argument.name == parameter.name) || + (argument.name.empty() && argumentIndex == parameterIndex)) { + const auto typeId = parameterPlans[parameterIndex].typeId; + preserveAst = typeId == LanguageTypeId::Expr || + typeId == LanguageTypeId::Stmt || + typeId == LanguageTypeId::Statements; + break; + } + } + call.args.push_back(Arg{ + argument.name, + preserveAst ? argument.value->clone() : args[argumentIndex]}); + } + std::vector solutions; + const bool previousValueCallMode = valueCallMode_; + { + PipelineResultClearScope clearPipelineResults(pipelineResults_); + valueCallMode_ = true; + try { + solveMethodCall(call, clause, env, solutions, 1, 0); + } catch (...) { + valueCallMode_ = previousValueCallMode; + throw; + } + valueCallMode_ = previousValueCallMode; + } + if (!solutions.empty()) { + auto returned = solutions.front().env.find(internalSymbolString(InternalSymbolKind::Return)); + if (returned != solutions.front().env.end()) { + if (auto returnedMap = std::dynamic_pointer_cast(returned->second)) { + if (returnedMap->entries.size() == 1 && returnedMap->entries.front().key.empty()) { + out = returnedMap->entries.front().value->clone(); + return true; + } + } + out = returned->second->clone(); + return true; + } + } + } + Call call(term.name, {}, term.builtinId); + for (size_t i = 0; i < args.size(); ++i) { + call.args.push_back(Arg{term.args[i].name, term.args[i].nameId, args[i]}); + } + std::vector goalSolutions; + { + PipelineResultClearScope clearPipelineResults(pipelineResults_); + solveRecursive({std::make_shared(call)}, env, goalSolutions, 1, 0); + } + if (!goalSolutions.empty()) { + out = std::make_shared("true"); + return true; + } + return false; + } + + auto evalNamed = [&](const std::string& name, size_t index, std::shared_ptr& value) -> bool { + const Arg* arg = findTermArgByNameOrIndex(term, name, index); + if (!arg) return false; + return evalExprValue(arg->value, env, value); + }; + + auto requireNamedString = [&](std::initializer_list names, size_t index, const std::string& label) { + std::shared_ptr value; + const Arg* arg = nullptr; + for (const char* name : names) { + arg = findTermArgByNameOrIndex(term, name, index); + if (arg) break; + } + if (!arg || !evalExprValue(arg->value, env, value)) { + throw InterpreterError(term.name + " expects string argument '" + label + "'"); + } + return requireString(value, term.name, label); + }; + + auto requireNamedNumber = [&](std::initializer_list names, size_t index, const std::string& label) { + std::shared_ptr value; + const Arg* arg = nullptr; + for (const char* name : names) { + arg = findTermArgByNameOrIndex(term, name, index); + if (arg) break; + } + if (!arg || !evalExprValue(arg->value, env, value)) { + throw InterpreterError(term.name + " expects numeric argument '" + label + "'"); + } + return requireNumber(value, term.name, label); + }; + + auto arrayItems = [&](const std::shared_ptr& value) -> std::vector> { + if (auto array = std::dynamic_pointer_cast(value)) return array->items; + if (auto var = std::dynamic_pointer_cast(term.args.empty() ? nullptr : term.args[0].value)) { + if (var->isCapitalized) { + return valuesForLambdaSource(term.args[0].value, env); + } + } + return {}; + }; + + if (builtin == BuiltinId::ArrayGet) { + std::shared_ptr dataValue; + if (!evalNamed("data", 0, dataValue)) { + throw InterpreterError("get expects a receiver value"); + } + std::shared_ptr keyValue; + const auto namedKey = std::find_if(term.args.begin(), term.args.end(), + [](const Arg& argument) { + return argument.name == "key" || argument.name == "value"; + }); + if (namedKey != term.args.end() && + evalExprValue(namedKey->value, env, keyValue)) { + const auto map = std::dynamic_pointer_cast(dataValue); + const auto key = std::dynamic_pointer_cast(keyValue); + if (!map) throw InterpreterError("map.get expects a map receiver, got " + dataValue->debug()); + if (!key) throw InterpreterError("map.get expects a string key"); + const auto value = findMapValue(map, key->value); + if (!value) return false; + out = value->clone(); + return true; + } + std::shared_ptr indexValue; + if (!evalNamed("pos", 1, indexValue) && + !evalNamed("position", 1, indexValue) && + !evalNamed("index", 1, indexValue)) { + throw InterpreterError("array.get expects a named position argument"); + } + auto data = std::dynamic_pointer_cast(dataValue); + double index = 0.0; + if (!data || !argAsNumber(indexValue, index) || index < 0 || std::floor(index) != index) { + throw InterpreterError("array.get expects an array and a non-negative integer position"); + } + const size_t resolvedIndex = static_cast(index); + if (resolvedIndex >= data->items.size()) { + throw InterpreterError("array.get position is outside the array"); + } + out = data->items[resolvedIndex]->clone(); + return true; + } + + if (builtin == BuiltinId::ConsoleReadLine || + builtin == BuiltinId::ConsoleInput || + builtin == BuiltinId::ConsoleInputNumber) { + if (builtin == BuiltinId::ConsoleInput || builtin == BuiltinId::ConsoleInputNumber) { + if (args.size() > 1) throw InterpreterError(term.name + " expects zero arguments or one prompt argument"); + const Arg* promptArg = findTermArgByNameOrIndex(term, "print", 0); + if (!promptArg) promptArg = findTermArgByNameOrIndex(term, "prompt", 0); + if (promptArg) { + std::shared_ptr promptValue; + if (!evalExprValue(promptArg->value, env, promptValue)) { + throw InterpreterError(term.name + " prompt did not evaluate"); + } + std::string promptText = requireString(promptValue, term.name, "print"); + std::cout << promptText; + std::cout.flush(); + } + } else if (!args.empty()) { + throw InterpreterError("console.readLine expects no arguments"); + } + std::string line; + if (!std::getline(std::cin, line)) line.clear(); + if (builtin == BuiltinId::ConsoleInputNumber) { + char* end = nullptr; + const double number = std::strtod(line.c_str(), &end); + while (end && *end && std::isspace(static_cast(*end))) ++end; + if (line.empty() || !end || *end != '\0' || !std::isfinite(number)) { + throw InterpreterError("console.inputNumber expected a numeric input"); + } + out = std::make_shared(number); + } else { + out = std::make_shared(line); + } + return true; + } + + if (builtin == BuiltinId::ConsoleWriteLine || + builtin == BuiltinId::ConsoleWrite || + builtin == BuiltinId::SystemPrint) { + if (args.size() != 1) throw InterpreterError(term.name + " expects one value"); + std::string text = args[0]->debug(); + if (auto str = std::dynamic_pointer_cast(args[0])) text = str->value; + std::cout << text; + if (builtin == BuiltinId::ConsoleWriteLine || builtin == BuiltinId::SystemPrint) std::cout << "\n"; + out = std::make_shared("ok"); + return true; + } + + if (builtin == BuiltinId::SystemPrintf) { + if (args.size() != 1) throw InterpreterError("system.printf expects one format string"); + const auto format = std::dynamic_pointer_cast(args.front()); + if (!format) throw InterpreterError("system.printf expects a string format"); + + auto placeholderValue = [&](std::string name) -> std::shared_ptr { + const auto begin = name.find_first_not_of(" \t"); + const auto end = name.find_last_not_of(" \t"); + if (begin == std::string::npos) { + throw InterpreterError("system.printf does not allow an empty placeholder"); + } + name = name.substr(begin, end - begin + 1); + std::shared_ptr value; + const size_t separator = name.find('.'); + const std::string root = name.substr(0, separator); + if (!evalExprValue(std::make_shared(root), env, value)) { + throw InterpreterError("system.printf cannot resolve '{" + name + "}'"); + } + size_t fieldStart = separator; + while (fieldStart != std::string::npos) { + const size_t next = name.find('.', fieldStart + 1); + const std::string field = name.substr(fieldStart + 1, next - fieldStart - 1); + if (field.empty()) throw InterpreterError("system.printf has an invalid placeholder '{" + name + "}'"); + value = findMapValue(value, field); + if (!value) throw InterpreterError("system.printf cannot resolve '{" + name + "}'"); + value = resolveExpr(value, env); + fieldStart = next; + } + return value; + }; + + std::ostringstream rendered; + for (size_t index = 0; index < format->value.size(); ++index) { + const char current = format->value[index]; + if (current == '{') { + if (index + 1 < format->value.size() && format->value[index + 1] == '{') { + rendered << '{'; + ++index; + continue; + } + const size_t close = format->value.find('}', index + 1); + if (close == std::string::npos) throw InterpreterError("system.printf has an unmatched '{'"); + const auto value = placeholderValue(format->value.substr(index + 1, close - index - 1)); + if (const auto text = std::dynamic_pointer_cast(value)) rendered << text->value; + else rendered << valueToString(value); + index = close; + continue; + } + if (current == '}') { + if (index + 1 < format->value.size() && format->value[index + 1] == '}') { + rendered << '}'; + ++index; + continue; + } + throw InterpreterError("system.printf has an unmatched '}'"); + } + rendered << current; + } + std::cout << rendered.str(); + std::cout.flush(); + out = std::make_shared("ok"); + return true; + } + + if (builtin == BuiltinId::StrConcat) { + std::string left = requireNamedString({"left", "data", "value"}, 0, "left"); + std::string right = requireNamedString({"right", "rhs"}, 1, "right"); + out = std::make_shared(left + right); + return true; + } + + if (builtin == BuiltinId::StrJoin) { + if (args.empty()) throw InterpreterError("str.join expects array argument 'data'"); + std::vector> items; + if (!exprAsArrayItems(args[0], items)) throw InterpreterError("str.join expects array argument 'data'"); + std::string delimiter = requireNamedString({"delimiter", "separator"}, 1, "delimiter"); + std::ostringstream joined; + for (size_t i = 0; i < items.size(); ++i) { + if (i) joined << delimiter; + std::string itemText; + if (argAsString(items[i], itemText)) joined << itemText; + else joined << valueToString(items[i]); + } + out = std::make_shared(joined.str()); + return true; + } + if (builtin == BuiltinId::StrLower || builtin == BuiltinId::StrUpper) { + std::string text = requireNamedString({"data", "value"}, 0, "data"); + for (char& ch : text) { + ch = static_cast(builtin == BuiltinId::StrLower + ? std::tolower(static_cast(ch)) + : std::toupper(static_cast(ch))); + } + out = std::make_shared(text); + return true; + } + + if (builtin == BuiltinId::StrTrim) { + out = std::make_shared(Felidae::trim(requireNamedString({"data", "value"}, 0, "data"))); + return true; + } + + if (builtin == BuiltinId::StrSplit) { + std::string text = requireNamedString({"data", "value"}, 0, "data"); + std::string delimiter = requireNamedString({"delimiter", "separator"}, 1, "delimiter"); + if (delimiter.empty()) throw InterpreterError("str.split expects non-empty delimiter"); + std::vector> parts; + size_t start = 0; + while (true) { + size_t pos = text.find(delimiter, start); + parts.push_back(std::make_shared(text.substr(start, pos == std::string::npos ? pos : pos - start))); + if (pos == std::string::npos) break; + start = pos + delimiter.size(); + } + out = std::make_shared(std::move(parts)); + return true; + } + + if (builtin == BuiltinId::StrReplace) { + std::string text = requireNamedString({"data", "value"}, 0, "data"); + std::string search = requireNamedString({"search", "needle"}, 1, "search"); + std::string replacement = requireNamedString({"replacement", "with"}, 2, "replacement"); + if (search.empty()) throw InterpreterError("str.replace expects non-empty search text"); + size_t pos = 0; + while ((pos = text.find(search, pos)) != std::string::npos) { + text.replace(pos, search.size(), replacement); + pos += replacement.size(); + } + out = std::make_shared(text); + return true; + } + + if (builtin == BuiltinId::StrContains || + builtin == BuiltinId::StrStartsWith || + builtin == BuiltinId::StrEndsWith) { + std::string text = requireNamedString({"data", "value"}, 0, "data"); + std::string needle = builtin == BuiltinId::StrContains + ? requireNamedString({"needle", "search"}, 1, "needle") + : requireNamedString({builtin == BuiltinId::StrStartsWith ? "prefix" : "suffix"}, 1, "needle"); + bool ok = builtin == BuiltinId::StrContains + ? text.find(needle) != std::string::npos + : (builtin == BuiltinId::StrStartsWith + ? text.rfind(needle, 0) == 0 + : (needle.size() <= text.size() && text.compare(text.size() - needle.size(), needle.size(), needle) == 0)); + out = std::make_shared(ok); + return true; + } + + if (builtin == BuiltinId::StrLen) { + std::string text = requireNamedString({"data", "value"}, 0, "data"); + out = std::make_shared(static_cast(text.size())); + return true; + } + + if (builtin == BuiltinId::FileReadFile) { + std::string pathText = requireNamedString({"path", "file"}, 0, "path"); + fs::path target(pathText); + if (fs::is_directory(target)) throw InterpreterError("file.readFile expected a file, got directory: " + pathText); + try { + out = std::make_shared(readSourceFile(target)); + } catch (const std::exception& e) { + throw InterpreterError("file.readFile failed: " + std::string(e.what())); + } + return true; + } + + if (builtin == BuiltinId::FileReadLines) { + std::string pathText = requireNamedString({"path", "file"}, 0, "path"); + fs::path target(pathText); + if (fs::is_directory(target)) throw InterpreterError("file.readLines expected a file, got directory: " + pathText); + std::vector> lines; + try { + readSourceLines(target, [&](const std::string& line) { + lines.push_back(std::make_shared(line)); + }); + } catch (const std::exception& e) { + throw InterpreterError("file.readLines failed: " + std::string(e.what())); + } + out = std::make_shared(std::move(lines)); + return true; + } + + if (builtin == BuiltinId::FileReadLine) { + std::string pathText = requireNamedString({"path", "file"}, 0, "path"); + double lineNumber = requireNamedNumber({"line", "index"}, 1, "line"); + if (lineNumber < 0 || std::floor(lineNumber) != lineNumber) { + throw InterpreterError("file.readLine expects non-negative integer argument 'line'"); + } + fs::path target(pathText); + if (fs::is_directory(target)) throw InterpreterError("file.readLine expected a file, got directory: " + pathText); + std::ifstream in(target, std::ios::binary); + if (!in) throw InterpreterError("file.readLine cannot open: " + pathText); + std::string line; + size_t wanted = static_cast(lineNumber); + for (size_t index = 0; std::getline(in, line); ++index) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (index == wanted) { + out = std::make_shared(line); + return true; + } + } + return false; + } + + if (builtin == BuiltinId::FileWriteFile || + builtin == BuiltinId::FileAppendFile || + builtin == BuiltinId::FileWriteLines) { + std::string pathText = requireNamedString({"path", "file"}, 0, "path"); + std::string data; + if (builtin == BuiltinId::FileWriteLines) { + std::shared_ptr linesValue; + if (!evalNamed("data", 1, linesValue) && !evalNamed("lines", 1, linesValue)) { + throw InterpreterError("file.writeLines expects array argument 'data'"); + } + std::vector> lines; + if (!exprAsArrayItems(linesValue, lines)) throw InterpreterError("file.writeLines expects array argument 'data'"); + std::ostringstream joined; + for (const auto& line : lines) joined << exprTextValue(line) << "\n"; + data = joined.str(); + } else { + data = requireNamedString({"data", "text", "content"}, 1, "data"); + } + std::string modeText = builtin == BuiltinId::FileAppendFile ? "append" : "write"; + if (const Arg* modeArg = findTermArgByNameOrIndex(term, "mode", 2)) { + std::shared_ptr modeValue; + if (!evalExprValue(modeArg->value, env, modeValue) || !argAsString(modeValue, modeText)) { + throw InterpreterError(term.name + " expects string argument 'mode'"); + } + } + if (modeText != "write" && modeText != "append") { + throw InterpreterError(term.name + " mode must be 'write' or 'append'"); + } + std::ios::openmode mode = std::ios::binary; + mode |= modeText == "append" ? std::ios::app : std::ios::trunc; + std::ofstream outFile(fs::path(pathText), mode); + if (!outFile) throw InterpreterError(term.name + " cannot open: " + pathText); + outFile << data; + out = std::make_shared("ok"); + return true; + } + + if (builtin == BuiltinId::FileExists) { + std::string pathText = requireNamedString({"path", "file"}, 0, "path"); + out = std::make_shared(fs::exists(fs::path(pathText))); + return true; + } + + if (builtin == BuiltinId::FileDeleteFile) { + std::string pathText = requireNamedString({"path", "file"}, 0, "path"); + std::error_code ec; + fs::path target(pathText); + if (fs::is_directory(target, ec)) { + if (ec) throw InterpreterError("file.deleteFile failed: " + ec.message()); + throw InterpreterError("file.deleteFile expected a file, got directory: " + pathText); + } + bool removed = fs::remove(target, ec); + if (ec) throw InterpreterError("file.deleteFile failed: " + ec.message()); + out = std::make_shared(removed); + return true; + } + + if (builtin == BuiltinId::JsonParse) { + std::string jsonText = requireNamedString({"data", "value"}, 0, "data"); + std::shared_ptr parsed; + if (!parseFlatJsonObject(jsonText, parsed)) { + throw InterpreterError("json.parse failed: invalid JSON"); + } + out = parsed; + return true; + } + + if (builtin == BuiltinId::JsonGet) { + std::shared_ptr dataValue; + if (!evalNamed("data", 0, dataValue) && !evalNamed("object", 0, dataValue)) { + throw InterpreterError("json.get expects argument 'data'"); + } + std::string key = requireNamedString({"key"}, 1, "key"); + auto value = findMapValue(dataValue, key); + if (!value) return false; + out = value->clone(); + return true; + } + + if (builtin == BuiltinId::JsonHas || builtin == BuiltinId::JsonKeys || + builtin == BuiltinId::JsonSet || builtin == BuiltinId::JsonRemove) { + std::shared_ptr dataValue; + if (!evalNamed("data", 0, dataValue) && !evalNamed("object", 0, dataValue)) { + throw InterpreterError(term.name + " expects argument 'data'"); + } + std::vector entries; + if (!exprAsMapEntries(dataValue, entries)) throw InterpreterError(term.name + " expects map/object argument 'data'"); + if (builtin == BuiltinId::JsonKeys) { + std::vector> keys; + keys.reserve(entries.size()); + for (const auto& entry : entries) keys.push_back(std::make_shared(entry.key)); + out = std::make_shared(std::move(keys)); + return true; + } + std::string key = requireNamedString({"key"}, 1, "key"); + if (builtin == BuiltinId::JsonHas) { + out = std::make_shared( + static_cast(findMapValue(dataValue, key))); + return true; + } + if (builtin == BuiltinId::JsonSet) { + std::shared_ptr value; + if (!evalNamed("value", 2, value)) throw InterpreterError("json.set expects argument 'value'"); + upsertEntry(entries, key, cloneExprOrNil(value)); + } else { + removeEntry(entries, key); + } + out = std::make_shared(std::move(entries)); + return true; + } + + if (builtin == BuiltinId::JsonToText) { + std::shared_ptr dataValue; + if (!evalNamed("data", 0, dataValue) && !evalNamed("value", 0, dataValue)) { + throw InterpreterError("json.toText expects argument 'data'"); + } + out = std::make_shared(exprToJson(dataValue)); + return true; + } + + if (builtin == BuiltinId::ThreadCreateThread) { + std::string functionName = requireNamedString({"function", "name"}, 0, "function"); + out = makeThreadHandle(createThreadTask(functionName)); + return true; + } + + if (builtin == BuiltinId::ThreadStart || + builtin == BuiltinId::ThreadStatus || + builtin == BuiltinId::ThreadResult) { + std::shared_ptr handle; + if (!evalNamed("thread", 0, handle)) throw InterpreterError(term.name + " expects thread argument 'thread'"); + if (builtin == BuiltinId::ThreadStart) { + out = std::make_shared(startThreadTask(handle)); + } else if (builtin == BuiltinId::ThreadStatus) { + out = std::make_shared(threadTaskStatus(handle)); + } else { + out = threadTaskResult(handle); + } + return true; + } + + if (builtin == BuiltinId::ThreadPause || builtin == BuiltinId::ThreadStop) { + throw InterpreterError(term.name + " is not supported; Felidae threads run immutable snapshots to completion"); + } + + const bool factStoreBuiltin = + builtin == BuiltinId::FactAll || builtin == BuiltinId::FactFind || + builtin == BuiltinId::FactCount || builtin == BuiltinId::FactFirst || + builtin == BuiltinId::FactTypes || builtin == BuiltinId::FactFields || + builtin == BuiltinId::FactExists || builtin == BuiltinId::FactSelect || + builtin == BuiltinId::FactMaterialize || builtin == BuiltinId::FactRelease || + builtin == BuiltinId::FactTimeline; + if (factStoreBuiltin || builtin == BuiltinId::DbSync) { + std::string_view op; + switch (builtin) { + case BuiltinId::DbSync: op = "sync"; break; + case BuiltinId::FactAll: op = "all"; break; + case BuiltinId::FactFind: op = "find"; break; + case BuiltinId::FactCount: op = "count"; break; + case BuiltinId::FactFirst: op = "first"; break; + case BuiltinId::FactTypes: op = "types"; break; + case BuiltinId::FactFields: op = "fields"; break; + case BuiltinId::FactExists: op = "exists"; break; + case BuiltinId::FactSelect: op = "select"; break; + case BuiltinId::FactMaterialize: op = "materialize"; break; + case BuiltinId::FactRelease: op = "release"; break; + case BuiltinId::FactTimeline: op = "timeline"; break; + default: break; + } + if (op == "sync") { + const std::string pathText = requireNamedString({"path", "file"}, 0, "path"); + out = std::make_shared(static_cast(syncFactSource(fs::path(pathText)))); + return true; + } + if (op == "materialize") { + std::shared_ptr selection; + if (!evalNamed("selection", 0, selection) && !evalNamed("value", 0, selection)) { + throw InterpreterError("Fact.materialize expects a FactSelection"); + } + out = materializeFactSelection(selection); + return true; + } + if (op == "release") { + std::shared_ptr selection; + if (!evalNamed("selection", 0, selection) && !evalNamed("value", 0, selection)) { + throw InterpreterError("Fact.release expects a FactSelection"); + } + const auto kind = std::dynamic_pointer_cast( + findMapValue(selection, internalSymbolString(InternalSymbolKind::Type))); + const auto generation = std::dynamic_pointer_cast( + findMapValue(selection, "snapshot_generation")); + if (!kind || kind->value != "FactSelection" || !generation || + generation->value <= 0 || std::floor(generation->value) != generation->value) { + throw InterpreterError("Fact.release expects a captured FactSelection"); + } + out = std::make_shared(memory_.releaseSnapshot( + static_cast(generation->value))); + return true; + } + if (op == "timeline") { + std::shared_ptr source; + if (!evalNamed("selection", 0, source) && !evalNamed("fact", 0, source) && + !evalNamed("value", 0, source)) { + throw InterpreterError("Fact.timeline expects a FactSelection or stored fact"); + } + + std::uint64_t snapshotGeneration = 0; + std::vector roots; + if (const auto selection = std::dynamic_pointer_cast(source)) { + snapshotGeneration = selection->snapshotGeneration; + const auto candidates = selection->designationIds.empty() + ? memory_.selectionIndexes(selection->factType, selection->field, + selection->equals && isGroundLiteral(selection->equals) + ? selection->equals : nullptr, snapshotGeneration) + : memory_.designationIndexes(selection->designationIds, snapshotGeneration); + // A timeline is an explicit history request: begin from every + // selected live lineage, including one whose newest version is + // future, then expand only within that lineage. + for (const size_t index : candidates) { + const auto& record = memory_.snapshotFact(snapshotGeneration, index); + if (!record.active || (!selection->factType.empty() && + !memory_.isCompatibleType(record.type, selection->factType))) { + continue; + } + if (!selection->designationIds.empty() && !std::all_of( + selection->designationIds.begin(), selection->designationIds.end(), + [&](SymbolId designation) { + return std::find(record.designations.begin(), record.designations.end(), designation) != + record.designations.end(); + })) { + continue; + } + const auto fact = memory_.factValue(index, snapshotGeneration); + if (!fact) continue; + if (!selection->field.empty()) { + const auto actual = findMapValue(fact, selection->field); + if (!actual || !selection->equals || + !exprContainsLiteral(actual, selection->equals)) continue; + } + bool matches = true; + for (const auto& filter : selection->filters) { + const auto actual = findMapValue(fact, filter.field); + if (!actual || !filter.value) { + matches = false; + break; + } + if (filter.op == TokenId::EQUAL) { + matches = exprContainsLiteral(actual, filter.value); + } else if (filter.op == TokenId::NOT_EQUAL) { + matches = !exprContainsLiteral(actual, filter.value); + } else { + matches = compareResolved(actual, filter.op, filter.value); + } + if (!matches) break; + } + if (matches) roots.push_back(index); + } + } else if (const auto fact = std::dynamic_pointer_cast(source)) { + if (fact->factIdentity == 0) { + throw InterpreterError("Fact.timeline expects a fact stored in the active knowledge base"); + } + const auto index = memory_.factIndexById(fact->factIdentity); + if (!index) throw InterpreterError("Fact.timeline cannot find the stored fact"); + roots.push_back(*index); + } else { + throw InterpreterError("Fact.timeline expects a FactSelection or stored fact"); + } + + const auto stateName = [](TemporalState state) -> std::string { + switch (state) { + case TemporalState::Past: return "past"; + case TemporalState::Current: return "current"; + case TemporalState::Future: return "future"; + } + return "past"; + }; + const auto originName = [](TemporalOrigin origin) -> std::string { + switch (origin) { + case TemporalOrigin::Observed: return "observed"; + case TemporalOrigin::Scheduled: return "scheduled"; + case TemporalOrigin::Derived: return "derived"; + case TemporalOrigin::Predicted: return "predicted"; + case TemporalOrigin::Required: return "required"; + } + return "observed"; + }; + + std::unordered_set seenLineages; + std::vector> events; + for (const size_t root : roots) { + const auto& rootRecord = memory_.snapshotFact(snapshotGeneration, root); + if (!seenLineages.insert(rootRecord.temporal.lineageKey).second) continue; + auto lineage = memory_.temporalLineageIndexesForFact(root, snapshotGeneration); + std::sort(lineage.begin(), lineage.end(), [&](size_t left, size_t right) { + const auto& a = memory_.snapshotFact(snapshotGeneration, left).temporal; + const auto& b = memory_.snapshotFact(snapshotGeneration, right).temporal; + if (a.effectiveTime != b.effectiveTime) return a.effectiveTime < b.effectiveTime; + return a.registrationSequence < b.registrationSequence; + }); + for (const size_t index : lineage) { + const auto& record = memory_.snapshotFact(snapshotGeneration, index); + const auto value = memory_.factValue(index, snapshotGeneration); + if (!value) continue; + std::vector> microFacts; + microFacts.reserve(value->entries.size()); + for (const auto& field : value->entries) { + if (field.keyId == InternalSymbol::TypeId || field.keyId == InternalSymbol::ParentId) continue; + auto micro = std::make_shared(std::vector{ + MapEntry{"field", std::make_shared(field.key)}, + MapEntry{"value", field.value ? field.value->clone() : std::make_shared()}, + MapEntry{"state", std::make_shared(stateName(memory_.temporalState(index, 0, snapshotGeneration)))}, + MapEntry{"fx:effective_at", std::make_shared(static_cast(record.temporal.effectiveTime))} + }); + micro->factType = "TemporalMicroFact"; + microFacts.push_back(std::move(micro)); + } + auto event = std::make_shared(std::vector{ + MapEntry{"fact", value}, + MapEntry{"state", std::make_shared(stateName(memory_.temporalState(index, 0, snapshotGeneration)))}, + MapEntry{"active", std::make_shared(record.active)}, + MapEntry{"fx:effective_at", std::make_shared(static_cast(record.temporal.effectiveTime))}, + MapEntry{"fx:registered_at", std::make_shared(static_cast(record.temporal.registrationTime))}, + MapEntry{"fx:registration_sequence", std::make_shared(static_cast(record.temporal.registrationSequence))}, + MapEntry{"fx:provenance", std::make_shared(originName(record.temporal.origin))}, + MapEntry{"micro_facts", std::make_shared(std::move(microFacts))} + }); + event->factType = "FactTimelineEvent"; + events.push_back(std::move(event)); + } + } + auto timeline = std::make_shared(std::vector{ + MapEntry{"events", std::make_shared(std::move(events))} + }); + timeline->factType = "FactTimeline"; + out = std::move(timeline); + return true; + } + if (op == "types") { + std::set types; + for (const size_t factIndex : memory_.activeFactIndexes()) { + types.insert(memory_.fact(factIndex).type); + } + for (const auto& parent : memory_.parents()) { + types.insert(parent.first); + types.insert(parent.second); + } + std::vector> items; + items.reserve(types.size()); + for (const auto& type : types) items.push_back(std::make_shared(type)); + out = std::make_shared(std::move(items)); + return true; + } + + std::string typeName = requireNamedString({"type", "fact"}, 0, "type"); + if (typeName.empty()) throw InterpreterError(term.name + " expects non-empty type"); + ensurePredicateLoaded(typeName); + + auto matchingFacts = [&]() { + std::vector> rows; + const auto current = memory_.currentFactIndexes(memory_.compatibleFactIndexes(typeName)); + for (size_t factIndex : current) { + if (const auto value = memory_.factValue(factIndex)) { + rows.push_back(value); + } + } + return rows; + }; + + if (op == "select") { + std::shared_ptr match; + if (evalNamed("match", 1, match)) { + const auto map = std::dynamic_pointer_cast(match); + if (!map) throw InterpreterError("Type.where expects a map of fields"); + auto selection = std::make_shared( + typeName, memory_.captureSnapshot()); + for (const auto& field : map->entries) { + selection->filters.push_back(FactSelectionFilter{ + field.key, field.keyId, TokenId::EQUAL, + field.value ? field.value->clone() : std::make_shared()}); + } + out = std::move(selection); + return true; + } + std::string field; + std::shared_ptr expected; + if (term.args.size() > 1) { + field = requireNamedString({"field", "key"}, 1, "field"); + if (!evalNamed("equals", 2, expected) && !evalNamed("value", 2, expected)) { + throw InterpreterError("Fact.select expects argument 'equals'"); + } + } + out = std::make_shared( + typeName, + memory_.captureSnapshot(), + std::move(field), + expected ? expected->clone() : nullptr); + return true; + } + + if (op == "all") { + out = std::make_shared(matchingFacts()); + return true; + } + if (op == "count") { + out = std::make_shared(static_cast(matchingFacts().size())); + return true; + } + if (op == "fields") { + std::set fields; + for (const auto& row : matchingFacts()) { + std::vector entries; + if (!exprAsMapEntries(row, entries)) continue; + for (const auto& entry : entries) { + if (entry.keyId != InternalSymbol::TypeId && entry.keyId != InternalSymbol::ParentId) fields.insert(entry.key); + } + } + std::vector> items; + items.reserve(fields.size()); + for (const auto& field : fields) items.push_back(std::make_shared(field)); + out = std::make_shared(std::move(items)); + return true; + } + if (op == "first" && term.args.size() == 2) { + std::shared_ptr position; + if (!evalNamed("pos", 1, position) && + !evalNamed("position", 1, position) && + !evalNamed("index", 1, position)) { + throw InterpreterError("Type.get expects a named position argument"); + } + const auto number = std::dynamic_pointer_cast(position); + if (!number || number->value < 0 || + std::floor(number->value) != number->value) { + throw InterpreterError("Type.get expects a non-negative integer position"); + } + const auto rows = matchingFacts(); + const auto index = static_cast(number->value); + if (index >= rows.size()) return false; + out = rows[index]->clone(); + return true; + } + if (op == "find" || op == "first") { + std::string field = requireNamedString({"field", "key"}, 1, "field"); + std::shared_ptr expected; + if (!evalNamed("equals", 2, expected) && !evalNamed("value", 2, expected)) { + throw InterpreterError(term.name + " expects argument 'equals'"); + } + std::vector> rows; + for (const auto& row : matchingFacts()) { + auto actual = findMapValue(row, field); + if (actual && exprContainsLiteral(actual, expected)) { + if (op == "first") { + out = row->clone(); + return true; + } + rows.push_back(row->clone()); + } + } + if (op == "first") return false; + out = std::make_shared(std::move(rows)); + return true; + } + throw InterpreterError("Unknown in-memory fact-store builtin: " + term.name); + } + + switch (term.builtinId) { + case BuiltinId::MathPi: + out = std::make_shared(3.14159265358979323846); + return true; + case BuiltinId::MathE: + out = std::make_shared(2.71828182845904523536); + return true; + case BuiltinId::MathRandom: { + double min = term.args.empty() ? 0.0 : requireNamedNumber({"min"}, 0, "min"); + double max = term.args.size() < 2 ? 1.0 : requireNamedNumber({"max"}, 1, "max"); + if (max < min) throw InterpreterError("math.random expects max >= min"); + static thread_local std::mt19937 rng{std::random_device{}()}; + std::uniform_real_distribution dist(min, max); + out = std::make_shared(dist(rng)); + return true; + } + case BuiltinId::MathPow: + case BuiltinId::MathAtan2: + case BuiltinId::MathAdd: + case BuiltinId::MathSub: + case BuiltinId::MathMul: + case BuiltinId::MathDiv: + case BuiltinId::MathMod: { + double left = requireNamedNumber({"lhs", "left", "base", "y"}, 0, "lhs"); + double right = requireNamedNumber({"rhs", "right", "exponent", "x"}, 1, "rhs"); + switch (term.builtinId) { + case BuiltinId::MathPow: + out = std::make_shared(std::pow(left, right)); + break; + case BuiltinId::MathAtan2: + out = std::make_shared(std::atan2(left, right)); + break; + case BuiltinId::MathAdd: + out = std::make_shared(left + right); + break; + case BuiltinId::MathSub: + out = std::make_shared(left - right); + break; + case BuiltinId::MathMul: + out = std::make_shared(left * right); + break; + case BuiltinId::MathDiv: + if (std::fabs(right) < 1e-12) throw InterpreterError("DivisionByZero"); + out = std::make_shared(left / right); + break; + case BuiltinId::MathMod: + if (std::fabs(right) < 1e-12) throw InterpreterError("DivisionByZero"); + out = std::make_shared(std::fmod(left, right)); + break; + default: + return false; + } + return true; + } + case BuiltinId::MathSqrt: + case BuiltinId::MathSin: + case BuiltinId::MathCos: + case BuiltinId::MathTan: + case BuiltinId::MathAsin: + case BuiltinId::MathAcos: + case BuiltinId::MathAtan: + case BuiltinId::MathLog: + case BuiltinId::MathLog10: + case BuiltinId::MathExp: + case BuiltinId::MathAbs: + case BuiltinId::MathFloor: + case BuiltinId::MathCeil: + case BuiltinId::MathRound: { + double value = requireNamedNumber({"value", "data", "x"}, 0, "value"); + switch (term.builtinId) { + case BuiltinId::MathSqrt: out = std::make_shared(std::sqrt(value)); break; + case BuiltinId::MathSin: out = std::make_shared(std::sin(value)); break; + case BuiltinId::MathCos: out = std::make_shared(std::cos(value)); break; + case BuiltinId::MathTan: out = std::make_shared(std::tan(value)); break; + case BuiltinId::MathAsin: out = std::make_shared(std::asin(value)); break; + case BuiltinId::MathAcos: out = std::make_shared(std::acos(value)); break; + case BuiltinId::MathAtan: out = std::make_shared(std::atan(value)); break; + case BuiltinId::MathLog: out = std::make_shared(std::log(value)); break; + case BuiltinId::MathLog10: out = std::make_shared(std::log10(value)); break; + case BuiltinId::MathExp: out = std::make_shared(std::exp(value)); break; + case BuiltinId::MathAbs: out = std::make_shared(std::fabs(value)); break; + case BuiltinId::MathFloor: out = std::make_shared(std::floor(value)); break; + case BuiltinId::MathCeil: out = std::make_shared(std::ceil(value)); break; + case BuiltinId::MathRound: out = std::make_shared(std::round(value)); break; + default: break; + } + return true; + } + default: + break; + } + + if (term.name.rfind("probability:", 0) == 0) { + const std::string op = term.name.substr(12); + static thread_local std::mt19937 rng{std::random_device{}()}; + + auto requireProbability = [&](std::initializer_list names, size_t index, const std::string& label) { + double p = requireNamedNumber(names, index, label); + if (p < 0.0 || p > 1.0) throw InterpreterError(term.name + " expects " + label + " between 0 and 1"); + return p; + }; + + if (op == "bernoulli") { + double p = requireProbability({"p", "probability"}, 0, "p"); + std::bernoulli_distribution dist(p); + out = std::make_shared(dist(rng)); + return true; + } + + if (op == "binomialPmf" || op == "binomialCdf") { + double trialsNumber = factorialTerm(requireNamedNumber({"trials", "n"}, 0, "trials"), term.name, "trials"); + double successesNumber = factorialTerm(requireNamedNumber({"successes", "k"}, 1, "successes"), term.name, "successes"); + double p = requireProbability({"p", "probability"}, 2, "p"); + int n = static_cast(trialsNumber); + int k = static_cast(successesNumber); + if (k > n) { + out = std::make_shared(0.0); + return true; + } + auto pmf = [&](int x) { + double logComb = std::lgamma(n + 1.0) - std::lgamma(x + 1.0) - std::lgamma(n - x + 1.0); + if (p == 0.0) return x == 0 ? 1.0 : 0.0; + if (p == 1.0) return x == n ? 1.0 : 0.0; + return std::exp(logComb + x * std::log(p) + (n - x) * std::log(1.0 - p)); + }; + double value = 0.0; + if (op == "binomialPmf") { + value = pmf(k); + } else { + for (int x = 0; x <= k; ++x) value += pmf(x); + } + out = std::make_shared(value); + return true; + } + + if (op == "poissonPmf" || op == "poissonCdf") { + double lambda = requireNamedNumber({"lambda", "rate"}, 0, "lambda"); + double eventsNumber = factorialTerm(requireNamedNumber({"events", "k"}, 1, "events"), term.name, "events"); + if (lambda < 0.0) throw InterpreterError(term.name + " expects lambda >= 0"); + int k = static_cast(eventsNumber); + auto pmf = [&](int x) { + if (lambda == 0.0) return x == 0 ? 1.0 : 0.0; + return std::exp(x * std::log(lambda) - lambda - std::lgamma(x + 1.0)); + }; + double value = 0.0; + if (op == "poissonPmf") { + value = pmf(k); + } else { + for (int x = 0; x <= k; ++x) value += pmf(x); + } + out = std::make_shared(value); + return true; + } + + if (op == "normalPdf" || op == "normalCdf") { + double x = requireNamedNumber({"x", "value"}, 0, "x"); + double mean = term.args.size() > 1 ? requireNamedNumber({"mean", "mu"}, 1, "mean") : 0.0; + double stddev = term.args.size() > 2 ? requireNamedNumber({"stddev", "sigma"}, 2, "stddev") : 1.0; + if (stddev <= 0.0) throw InterpreterError(term.name + " expects stddev > 0"); + double z = (x - mean) / stddev; + double value = op == "normalPdf" + ? std::exp(-0.5 * z * z) / (stddev * std::sqrt(2.0 * 3.14159265358979323846)) + : 0.5 * (1.0 + std::erf(z / std::sqrt(2.0))); + out = std::make_shared(value); + return true; + } + + if (op == "uniformPdf" || op == "uniformCdf") { + double x = requireNamedNumber({"x", "value"}, 0, "x"); + double min = requireNamedNumber({"min", "a"}, 1, "min"); + double max = requireNamedNumber({"max", "b"}, 2, "max"); + if (max <= min) throw InterpreterError(term.name + " expects max > min"); + double value = 0.0; + if (op == "uniformPdf") { + value = (x >= min && x <= max) ? 1.0 / (max - min) : 0.0; + } else { + value = x <= min ? 0.0 : (x >= max ? 1.0 : (x - min) / (max - min)); + } + out = std::make_shared(value); + return true; + } + + std::shared_ptr dataValue; + if ((op == "mean" || op == "variance" || op == "stddev" || op == "normalize" || op == "entropy") && + (!evalNamed("data", 0, dataValue) && !evalNamed("values", 0, dataValue))) { + throw InterpreterError(term.name + " expects numeric array argument 'data'"); + } + + if (op == "mean" || op == "variance" || op == "stddev" || op == "normalize" || op == "entropy") { + auto values = requireNumberArray(dataValue, term.name, "data"); + if (values.empty()) throw InterpreterError(term.name + " expects a non-empty array"); + double total = 0.0; + for (double value : values) total += value; + if (op == "mean") { + out = std::make_shared(total / static_cast(values.size())); + return true; + } + if (op == "variance" || op == "stddev") { + double mean = total / static_cast(values.size()); + double squared = 0.0; + for (double value : values) squared += (value - mean) * (value - mean); + double variance = squared / static_cast(values.size()); + out = std::make_shared(op == "variance" ? variance : std::sqrt(variance)); + return true; + } + if (op == "normalize") { + if (std::fabs(total) < 1e-12) throw InterpreterError("probability.normalize expects a non-zero sum"); + std::vector normalized; + normalized.reserve(values.size()); + for (double value : values) normalized.push_back(value / total); + out = numbersToArray(normalized); + return true; + } + double entropy = 0.0; + for (double p : values) { + if (p < 0.0) throw InterpreterError("probability.entropy expects non-negative probabilities"); + if (p > 0.0) entropy -= p * std::log2(p); + } + out = std::make_shared(entropy); + return true; + } + + if (op == "covariance" || op == "correlation") { + std::shared_ptr leftValue; + std::shared_ptr rightValue; + if (!evalNamed("left", 0, leftValue) || !evalNamed("right", 1, rightValue)) { + throw InterpreterError(term.name + " expects left and right arrays"); + } + auto left = requireNumberArray(leftValue, term.name, "left"); + auto right = requireNumberArray(rightValue, term.name, "right"); + if (left.empty() || left.size() != right.size()) throw InterpreterError(term.name + " expects arrays of equal non-zero length"); + double leftMean = 0.0; + double rightMean = 0.0; + for (size_t i = 0; i < left.size(); ++i) { + leftMean += left[i]; + rightMean += right[i]; + } + leftMean /= static_cast(left.size()); + rightMean /= static_cast(right.size()); + double covariance = 0.0; + double leftVar = 0.0; + double rightVar = 0.0; + for (size_t i = 0; i < left.size(); ++i) { + double ld = left[i] - leftMean; + double rd = right[i] - rightMean; + covariance += ld * rd; + leftVar += ld * ld; + rightVar += rd * rd; + } + covariance /= static_cast(left.size()); + if (op == "covariance") { + out = std::make_shared(covariance); + return true; + } + if (std::fabs(leftVar) < 1e-12 || std::fabs(rightVar) < 1e-12) { + throw InterpreterError("probability.correlation expects non-constant arrays"); + } + const double count = static_cast(left.size()); + out = std::make_shared(covariance / std::sqrt((leftVar / count) * (rightVar / count))); + return true; + } + + if (op == "sample" || op == "weightedChoice") { + std::shared_ptr valuesValue; + if (!evalNamed("data", 0, valuesValue) && !evalNamed("values", 0, valuesValue)) { + throw InterpreterError(term.name + " expects array argument 'data'"); + } + std::vector> values; + if (!exprAsArrayItems(valuesValue, values) || values.empty()) throw InterpreterError(term.name + " expects a non-empty array"); + if (op == "sample") { + std::uniform_int_distribution dist(0, values.size() - 1); + out = values[dist(rng)]->clone(); + return true; + } + std::shared_ptr weightsValue; + if (!evalNamed("weights", 1, weightsValue)) throw InterpreterError("probability.weightedChoice expects weights"); + auto weights = requireNumberArray(weightsValue, term.name, "weights"); + if (weights.size() != values.size()) throw InterpreterError("probability.weightedChoice expects weights length to match data length"); + for (double weight : weights) { + if (weight < 0.0) throw InterpreterError("probability.weightedChoice expects non-negative weights"); + } + std::discrete_distribution dist(weights.begin(), weights.end()); + out = values[dist(rng)]->clone(); + return true; + } + + throw InterpreterError("Unknown probability builtin: " + term.name); + } + + if (term.name.rfind("ml:", 0) == 0) { + const std::string op = term.name.substr(3); + if (op == "sigmoid" || op == "relu") { + double value = requireNamedNumber({"value", "x"}, 0, "value"); + out = std::make_shared(op == "sigmoid" ? 1.0 / (1.0 + std::exp(-value)) : std::max(0.0, value)); + return true; + } + if (op == "dot" || op == "meanSquaredError") { + std::shared_ptr leftExpr; + std::shared_ptr rightExpr; + if (!evalNamed("left", 0, leftExpr) || !evalNamed("right", 1, rightExpr)) { + throw InterpreterError(term.name + " expects left and right arrays"); + } + std::vector> left; + std::vector> right; + if (!exprAsArray(leftExpr, left) || !exprAsArray(rightExpr, right) || left.size() != right.size()) { + throw InterpreterError(term.name + " expects arrays of equal length"); + } + if (left.empty()) throw InterpreterError(term.name + " expects non-empty arrays"); +#ifdef FELIDAE_HAS_EIGEN + Eigen::VectorXd lhs(static_cast(left.size())); + Eigen::VectorXd rhs(static_cast(right.size())); + for (size_t i = 0; i < left.size(); ++i) { + lhs(static_cast(i)) = requireNumber(left[i], term.name, "left"); + rhs(static_cast(i)) = requireNumber(right[i], term.name, "right"); + } + if (op == "dot") { + out = std::make_shared(lhs.dot(rhs)); + } else { + out = std::make_shared((lhs - rhs).squaredNorm() / static_cast(left.size())); + } +#else + double total = 0.0; + for (size_t i = 0; i < left.size(); ++i) { + double a = requireNumber(left[i], term.name, "left"); + double b = requireNumber(right[i], term.name, "right"); + total += op == "dot" ? a * b : (a - b) * (a - b); + } + out = std::make_shared(op == "dot" ? total : total / static_cast(left.size())); +#endif + return true; + } + throw InterpreterError("Unknown ml builtin: " + term.name); + } + + if (builtin == BuiltinId::ParseDoc) { + if (args.size() != 1) throw InterpreterError("ParseDoc expects one argument"); + std::string text; + if (!argAsString(args[0], text)) throw InterpreterError("ParseDoc expects a string"); + out = std::make_shared("Parsed: " + text); + return true; + } + + if (builtin == BuiltinId::Count || builtin == BuiltinId::Length) { + if (args.size() != 1) throw InterpreterError(term.name + " expects one argument"); + if (const auto selection = std::dynamic_pointer_cast(args[0])) { + out = std::make_shared(static_cast( + materializeFactSelection(selection)->items.size())); + return true; + } + if (auto array = std::dynamic_pointer_cast(args[0])) { + out = std::make_shared(static_cast(array->items.size())); + return true; + } + std::string text; + if (argAsString(args[0], text)) { + out = std::make_shared(static_cast(text.size())); + return true; + } + auto items = arrayItems(args[0]); + if (!items.empty()) { + out = std::make_shared(static_cast(items.size())); + return true; + } + throw InterpreterError(term.name + " expects an array, collection, or string"); + } + + if (builtin == BuiltinId::Sum || builtin == BuiltinId::Average) { + if (args.size() != 1) throw InterpreterError(term.name + " expects one numeric array"); + auto array = std::dynamic_pointer_cast(args[0]); + if (!array) throw InterpreterError(term.name + " expects a numeric array"); + double total = 0.0; + for (const auto& item : array->items) { + double number = 0.0; + if (!argAsNumber(item, number)) throw InterpreterError(term.name + " expects only numbers"); + total += number; + } + if (builtin == BuiltinId::Average && array->items.empty()) throw InterpreterError("average expects a non-empty array"); + out = std::make_shared(builtin == BuiltinId::Average ? total / static_cast(array->items.size()) : total); + return true; + } + + if (builtin == BuiltinId::Min || builtin == BuiltinId::Max || builtin == BuiltinId::Sort) { + if (args.size() != 1) throw InterpreterError(term.name + " expects one array"); + auto array = std::dynamic_pointer_cast(args[0]); + if (!array) throw InterpreterError(term.name + " expects an array"); + std::vector> items; + for (const auto& item : array->items) items.push_back(item->clone()); + auto less = [](const std::shared_ptr& lhs, const std::shared_ptr& rhs) { + double ln = 0.0, rn = 0.0; + if (argAsNumber(lhs, ln) && argAsNumber(rhs, rn)) return ln < rn; + std::string ls, rs; + if (argAsString(lhs, ls) && argAsString(rhs, rs)) return ls < rs; + return lhs->debug() < rhs->debug(); + }; + std::sort(items.begin(), items.end(), less); + if (builtin == BuiltinId::Sort) { + out = std::make_shared(std::move(items)); + } else { + if (items.empty()) throw InterpreterError(term.name + " expects a non-empty array"); + out = builtin == BuiltinId::Min ? items.front() : items.back(); + } + return true; + } + + if (builtin == BuiltinId::Contains || builtin == BuiltinId::Search) { + if (args.size() != 2) throw InterpreterError(term.name + " expects two arguments"); + std::string query; + if (!argAsString(args[1], query)) throw InterpreterError(term.name + " query must be a string"); + std::string text; + if (argAsString(args[0], text)) { + bool found = text.find(query) != std::string::npos; + out = std::make_shared(found); + return true; + } + auto array = std::dynamic_pointer_cast(args[0]); + if (!array) throw InterpreterError(term.name + " expects a string or array"); + std::vector> matches; + for (const auto& item : array->items) { + std::string itemText; + if (argAsString(item, itemText) && itemText.find(query) != std::string::npos) { + if (builtin == BuiltinId::Contains) { + out = std::make_shared("true"); + return true; + } + matches.push_back(item->clone()); + } else if (builtin == BuiltinId::Contains && exprEqualsLiteral(item, args[1])) { + out = std::make_shared("true"); + return true; + } + } + out = builtin == BuiltinId::Contains + ? std::static_pointer_cast(std::make_shared("false")) + : std::static_pointer_cast(std::make_shared(std::move(matches))); + return true; + } + + if (builtin == BuiltinId::Lower || builtin == BuiltinId::Upper) { + if (args.size() != 1) throw InterpreterError(term.name + " expects one string"); + std::string text; + if (!argAsString(args[0], text)) throw InterpreterError(term.name + " expects a string"); + out = std::make_shared(builtin == BuiltinId::Lower ? lowerText(text) : upperText(text)); + return true; + } + + return false; +} + +bool Interpreter::evalExprValue(const std::shared_ptr& expr, const Env& env, std::shared_ptr& out) { + if (auto op = std::dynamic_pointer_cast(expr)) { + return evalOperatorExpr(*op, env, out); + } + auto resolved = resolveExpr(expr, env); + if (auto lambda = std::dynamic_pointer_cast(resolved)) { + auto sourceValues = valuesForLambdaSource(lambda->source, env); + // A type selector is a fact query. Its documented predicate form + // filters facts, including compound predicates that are represented + // as a normal boolean expression rather than LambdaExpr::op/right. + // Array sources retain their mapping behaviour for compatibility. + const auto sourceVariable = std::dynamic_pointer_cast(lambda->source); + const bool sourceIsFactType = + std::dynamic_pointer_cast(lambda->source) != nullptr || + (sourceVariable && sourceVariable->isCapitalized && + globals_.find(sourceVariable->nameId) == globals_.end()); + std::vector> results; + for (const auto& item : sourceValues) { + Env lambdaEnv = env; + lambdaEnv[lambda->variableId] = item; + PipelineResultClearScope clearPipelineResults(pipelineResults_); + if (lambda->op != TokenId::UNKNOWN) { + std::shared_ptr left; + std::shared_ptr right; + if (!evalExprValue(lambda->body, lambdaEnv, left) || + !evalExprValue(lambda->right, lambdaEnv, right)) { + continue; + } + bool ok = lambda->op == TokenId::EQUAL ? unifyExpr(left, right, lambdaEnv) : + lambda->op == TokenId::NOT_EQUAL ? !unifyExpr(left, right, lambdaEnv) : + compareResolved(left, lambda->op, right); + if (ok) results.push_back(item->clone()); + continue; + } + std::shared_ptr mapped; + if (evalExprValue(lambda->body, lambdaEnv, mapped) && !isMethodTruthTupleWithFalse(mapped)) { + if (sourceIsFactType) { + if (const auto predicate = std::dynamic_pointer_cast(mapped)) { + if (predicate->value) results.push_back(item->clone()); + } else { + results.push_back(mapped); + } + } else { + results.push_back(mapped); + } + } + } + out = std::make_shared(std::move(results)); + return true; + } + if (auto term = std::dynamic_pointer_cast(resolved)) { + return evalBuiltinTerm(*term, env, out) || instantiateClass(*term, env, out); + } + if (auto array = std::dynamic_pointer_cast(resolved)) { + std::vector> items; + items.reserve(array->items.size()); + for (const auto& item : array->items) { + std::shared_ptr value; + if (!evalExprValue(item, env, value)) return false; + items.push_back(value); + } + out = std::make_shared(std::move(items)); + return true; + } + if (auto map = std::dynamic_pointer_cast(resolved)) { + std::vector entries; + entries.reserve(map->entries.size()); + for (const auto& entry : map->entries) { + std::shared_ptr value; + if (!evalExprValue(entry.value, env, value)) return false; + entries.push_back(MapEntry{entry.key, value}); + } + auto evaluated = std::make_shared(std::move(entries)); + // Evaluating a stored fact resolves field expressions but must not + // discard its runtime-only identity. This keeps aliases and values + // retrieved through Fact.all/select attached to the same fact record. + evaluated->factIdentity = map->factIdentity; + evaluated->factType = map->factType; + out = std::move(evaluated); + return true; + } + if (auto access = std::dynamic_pointer_cast(resolved)) { + std::shared_ptr target; + if (!evalExprValue(access->target, env, target)) return false; + auto value = findMapValue(target, access->key); + if (!value) return false; + return evalExprValue(value, env, out); + } + if (auto var = std::dynamic_pointer_cast(resolved)) { + auto globalIt = globals_.find(var->name); + if (globalIt != globals_.end()) return evalExprValue(globalIt->second, env, out); + const SymbolId designationId = symbolIdForName(var->name); + if (memory_.hasDesignation(designationId)) { + out = std::make_shared( + "", memory_.captureSnapshot(), "", nullptr, + std::vector{designationId}, + std::vector{var->name}); + return true; + } + return false; + } + out = resolved->clone(); + return true; +} + +bool Interpreter::instantiateClass(const TermExpr& term, const Env& env, + std::shared_ptr& out) { + const auto declared = classDefinitions_.find(term.nameId); + if (declared == classDefinitions_.end()) return false; + const ClassStmt& schema = *declared->second; + if (term.args.size() > schema.fields.size()) { + throw InterpreterError("Class '" + schema.name + "' received too many constructor arguments"); + } + + std::unordered_map fields; + fields.reserve(schema.fields.size()); + for (const auto& field : schema.fields) fields.emplace(field.nameId, &field); + std::unordered_set supplied; + std::vector entries; + entries.reserve(term.args.size()); + for (std::size_t index = 0; index < term.args.size(); ++index) { + const Arg& argument = term.args[index]; + const ClassFieldDecl* field = nullptr; + if (argument.name.empty()) { + field = &schema.fields[index]; + } else { + const auto found = fields.find(argument.nameId); + if (found == fields.end()) { + throw InterpreterError("Class '" + schema.name + "' has no field '" + argument.name + "'"); + } + field = found->second; + } + if (!supplied.insert(field->nameId).second) { + throw InterpreterError("Class constructor repeats field '" + field->name + "'"); + } + std::shared_ptr value; + if (!evalExprValue(argument.value, env, value)) return false; + const LanguageTypeId builtin = languageTypeIdForName(field->typeName); + if (builtin != LanguageTypeId::Unknown) { + if (!valueMatchesBuiltinType(value, builtin)) { + throw InterpreterError("Class field '" + field->name + "' expects " + field->typeName); + } + } else if (field->typeName != "any") { + const auto fact = std::dynamic_pointer_cast(value); + if (!fact || !memory_.isCompatibleType(fact->factType, field->typeName)) { + throw InterpreterError("Class field '" + field->name + "' expects " + field->typeName); + } + } + entries.emplace_back(field->name, field->nameId, std::move(value)); + } + if (supplied.size() != schema.fields.size()) { + throw InterpreterError("Class '" + schema.name + "' requires every declared field"); + } + auto value = std::make_shared(std::move(entries)); + value->factType = schema.name; + out = std::move(value); + return true; +} + +bool Interpreter::evalOperatorExpr(const OperatorExpression& expression, + const Env& env, + std::shared_ptr& out) { + if (expression.coreOperator != CoreOperator::Unknown && + operatorClauses_.count(expression.patternId) > 0) { + bool matched = false; + const bool evaluated = evalCustomOperatorExpr(expression, env, out, &matched); + if (matched) return evaluated; + } + if (expression.coreOperator == CoreOperator::Unknown) { + return evalCustomOperatorExpr(expression, env, out); + } + const auto selectionFieldFilter = [&](const std::shared_ptr& candidate, + const std::shared_ptr& expected, + TokenId::Id op, + std::shared_ptr& selectionOut) { + const auto access = std::dynamic_pointer_cast(candidate); + if (!access) return false; + std::shared_ptr source; + if (!evalExprValue(access->target, env, source)) return false; + const auto selection = std::dynamic_pointer_cast(source); + if (!selection) return false; + std::shared_ptr value; + if (!evalExprValue(expected, env, value)) return false; + auto filtered = std::static_pointer_cast(selection->clone()); + filtered->filters.push_back(FactSelectionFilter{ + access->key, access->keyId, op, std::move(value)}); + selectionOut = std::move(filtered); + return true; + }; + const auto comparisonToken = [&](CoreOperator op) { + switch (op) { + case CoreOperator::StrictEqual: return TokenId::EQUAL; + case CoreOperator::StrictNotEqual: return TokenId::NOT_EQUAL; + case CoreOperator::Less: + case CoreOperator::LessEqual: + case CoreOperator::Greater: + case CoreOperator::GreaterEqual: + return coreOperatorDefinition(op).token; + default: + return TokenId::UNKNOWN; + } + }; + if (expression.captureCount() == 2) { + const TokenId::Id filterOp = comparisonToken(expression.coreOperator); + if (filterOp != TokenId::UNKNOWN) { + std::shared_ptr filtered; + if (selectionFieldFilter(expression.capture(0), expression.capture(1), filterOp, filtered)) { + out = std::move(filtered); + return true; + } + } + } + const auto booleanValue = [](const std::shared_ptr& value, + const char* operatorName) { + if (auto boolean = std::dynamic_pointer_cast(value)) return boolean->value; + if (auto text = std::dynamic_pointer_cast(value)) { + if (text->value == "true") return true; + if (text->value == "false") return false; + } + throw InterpreterError(std::string("Logical operator '") + operatorName + + "' expects boolean operands"); + }; + switch (expression.coreOperator) { + case CoreOperator::Then: { + if (expression.captureCount() != 2) throw InterpreterError("Invalid then operator shape"); + std::shared_ptr previous; + if (!evalExprValue(expression.capture(0), env, previous) || + std::dynamic_pointer_cast(previous)) { + out = std::make_shared(); + return true; + } + PipelineResultValueScope pipelineResult(pipelineResults_, previous); + std::shared_ptr next; + if (!evalExprValue(expression.capture(1), env, next) || + std::dynamic_pointer_cast(next)) { + out = std::make_shared(); + return true; + } + out = std::move(next); + return true; + } + case CoreOperator::UnaryMinus: + case CoreOperator::UnaryPlus: { + if (expression.captureCount() != 1) throw InterpreterError("Invalid unary operator shape"); + std::shared_ptr operand; + if (!evalExprValue(expression.capture(0), env, operand)) return false; + const auto number = std::dynamic_pointer_cast(operand); + if (!number) throw InterpreterError("Unary numeric operator expects a number"); + out = std::make_shared( + expression.coreOperator == CoreOperator::UnaryMinus ? -number->value : number->value); + return true; + } + case CoreOperator::LogicalNot: { + if (expression.captureCount() != 1) throw InterpreterError("Invalid logical not shape"); + std::shared_ptr operand; + if (!evalExprValue(expression.capture(0), env, operand)) return false; + out = std::make_shared(!booleanValue(operand, "not")); + return true; + } + case CoreOperator::LogicalAnd: + case CoreOperator::LogicalOr: { + if (expression.captureCount() != 2) throw InterpreterError("Invalid logical operator shape"); + std::shared_ptr left; + if (!evalExprValue(expression.capture(0), env, left)) return false; + if (expression.coreOperator == CoreOperator::LogicalAnd) { + if (const auto selection = std::dynamic_pointer_cast(left)) { + const auto right = std::dynamic_pointer_cast(expression.capture(1)); + const TokenId::Id filterOp = right ? comparisonToken(right->coreOperator) : TokenId::UNKNOWN; + const auto field = right && right->captureCount() == 2 + ? std::dynamic_pointer_cast(right->capture(0)) : nullptr; + if (filterOp != TokenId::UNKNOWN && field) { + std::shared_ptr value; + if (!evalExprValue(right->capture(1), env, value)) return false; + auto filtered = std::static_pointer_cast(selection->clone()); + filtered->filters.push_back(FactSelectionFilter{ + field->name, field->nameId, filterOp, std::move(value)}); + out = std::move(filtered); + return true; + } + } + } + const bool leftTruth = booleanValue( + left, expression.coreOperator == CoreOperator::LogicalAnd ? "and" : "or"); + if ((expression.coreOperator == CoreOperator::LogicalAnd && !leftTruth) || + (expression.coreOperator == CoreOperator::LogicalOr && leftTruth)) { + out = std::make_shared(leftTruth); + return true; + } + std::shared_ptr right; + if (!evalExprValue(expression.capture(1), env, right)) return false; + out = std::make_shared(booleanValue( + right, expression.coreOperator == CoreOperator::LogicalAnd ? "and" : "or")); + return true; + } + case CoreOperator::Add: + case CoreOperator::Subtract: + case CoreOperator::Multiply: + case CoreOperator::Divide: + case CoreOperator::Modulo: + case CoreOperator::StrictEqual: + case CoreOperator::StrictNotEqual: + case CoreOperator::Less: + case CoreOperator::LessEqual: + case CoreOperator::Greater: + case CoreOperator::GreaterEqual: + break; + default: + throw InterpreterError("Unsupported operator id " + std::to_string(expression.operatorId)); + } + + if (expression.captureCount() != 2) throw InterpreterError("Invalid binary operator shape"); + std::shared_ptr left; + std::shared_ptr right; + if (!evalExprValue(expression.capture(0), env, left) || + !evalExprValue(expression.capture(1), env, right)) { + return false; + } + + switch (expression.coreOperator) { + case CoreOperator::StrictEqual: + case CoreOperator::StrictNotEqual: { + const bool equal = exprEqualsLiteral(left, right); + out = std::make_shared( + expression.coreOperator == CoreOperator::StrictEqual ? equal : !equal); + return true; + } + case CoreOperator::Less: + case CoreOperator::LessEqual: + case CoreOperator::Greater: + case CoreOperator::GreaterEqual: + out = std::make_shared( + compareResolved(left, coreOperatorDefinition(expression.coreOperator).token, right)); + return true; + default: + break; + } + + const auto leftNumber = std::dynamic_pointer_cast(left); + const auto rightNumber = std::dynamic_pointer_cast(right); + if (!leftNumber || !rightNumber) { + throw InterpreterError( + "Operator '" + std::string(coreOperatorDefinition(expression.coreOperator).spelling) + + "' expects numeric operands"); + } + switch (expression.coreOperator) { + case CoreOperator::Add: + out = std::make_shared(leftNumber->value + rightNumber->value); + return true; + case CoreOperator::Subtract: + out = std::make_shared(leftNumber->value - rightNumber->value); + return true; + case CoreOperator::Multiply: + out = std::make_shared(leftNumber->value * rightNumber->value); + return true; + case CoreOperator::Divide: + case CoreOperator::Modulo: + if (std::fabs(rightNumber->value) < 1e-12) throw InterpreterError("DivisionByZero"); + out = std::make_shared( + expression.coreOperator == CoreOperator::Divide + ? leftNumber->value / rightNumber->value + : std::fmod(leftNumber->value, rightNumber->value)); + return true; + default: + break; + } + throw InterpreterError("Invalid numeric operator id " + std::to_string(expression.operatorId)); +} + +bool Interpreter::evalCustomOperatorExpr(const OperatorExpression& expression, + const Env& env, + std::shared_ptr& out, + bool* matched) { + if (matched) *matched = false; + const auto clauses = operatorClauses_.find(expression.patternId); + if (clauses == operatorClauses_.end()) { + if (matched != nullptr) return false; + throw InterpreterError("No overload implementation is registered for operator pattern " + + std::to_string(expression.patternId)); + } + struct ResolvedOperatorType { + LanguageTypeId languageType = LanguageTypeId::Unknown; + SymbolId factTypeId = 0; + std::string factType; + + bool known() const { + return languageType != LanguageTypeId::Unknown || factTypeId != 0; + } + }; + const auto factRuntimeType = [](std::string name) { + if (name.empty()) return ResolvedOperatorType{}; + return ResolvedOperatorType{ + LanguageTypeId::Unknown, symbolIdForName(name), std::move(name)}; + }; + const auto builtinRuntimeType = [](LanguageTypeId type) { + return ResolvedOperatorType{type, 0, {}}; + }; + const auto sameResolvedType = [](const ResolvedOperatorType& left, + const ResolvedOperatorType& right) { + if (left.languageType != LanguageTypeId::Unknown || + right.languageType != LanguageTypeId::Unknown) { + return left.languageType == right.languageType; + } + return left.factTypeId == right.factTypeId && + left.factType == right.factType; + }; + const auto compatibleLanguageType = [](LanguageTypeId actual, + LanguageTypeId expected) { + if (actual == expected) return true; + const auto numeric = [](LanguageTypeId type) { + return type == LanguageTypeId::Number || + type == LanguageTypeId::Decimal || + type == LanguageTypeId::Double || + type == LanguageTypeId::Float || + type == LanguageTypeId::Int; + }; + if (numeric(actual) && numeric(expected)) { + // A general numeric result cannot promise integral output. + return expected != LanguageTypeId::Int || actual == LanguageTypeId::Int; + } + return (actual == LanguageTypeId::Bool || actual == LanguageTypeId::Boolean) && + (expected == LanguageTypeId::Bool || expected == LanguageTypeId::Boolean); + }; + const auto valueType = [&](const std::shared_ptr& value) { + if (auto ast = std::dynamic_pointer_cast(value)) { + return builtinRuntimeType( + ast->valueKind == AstValueKind::Expression + ? LanguageTypeId::Expr + : ast->valueKind == AstValueKind::Statement + ? LanguageTypeId::Stmt + : LanguageTypeId::Statements); + } + if (std::dynamic_pointer_cast(value)) { + return builtinRuntimeType(LanguageTypeId::Number); + } + if (std::dynamic_pointer_cast(value)) { + return builtinRuntimeType(LanguageTypeId::String); + } + if (std::dynamic_pointer_cast(value)) { + return builtinRuntimeType(LanguageTypeId::Bool); + } + if (std::dynamic_pointer_cast(value)) { + return builtinRuntimeType(LanguageTypeId::Array); + } + if (const auto map = std::dynamic_pointer_cast(value)) { + if (!map->factType.empty()) return factRuntimeType(map->factType); + const auto type = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type))); + if (type) return factRuntimeType(type->value); + } + return ResolvedOperatorType{}; + }; + + // Overload selection must not execute captures. Resolve only immutable + // values already present in the frame and direct structural metadata. + const auto metadataValue = [&](const auto& self, + const std::shared_ptr& syntax, + std::unordered_set& resolving) + -> std::shared_ptr { + if (auto ast = std::dynamic_pointer_cast(syntax)) { + if (ast->valueKind == AstValueKind::Expression && ast->nodes.size() == 1) { + if (const auto nested = std::dynamic_pointer_cast(ast->nodes.front())) { + return self(self, nested, resolving); + } + } + return syntax; + } + if (auto variable = std::dynamic_pointer_cast(syntax)) { + if (variable->nameId == InternalSymbol::SystemResultId && + !pipelineResults_.empty()) { + return pipelineResults_.back(); + } + if (!resolving.insert(variable->nameId).second) return syntax; + auto local = env.find(variable->name); + if (local != env.end()) return self(self, local->second, resolving); + auto global = globals_.find(variable->name); + if (global != globals_.end()) return self(self, global->second, resolving); + return syntax; + } + if (auto access = std::dynamic_pointer_cast(syntax)) { + const auto targetVariable = std::dynamic_pointer_cast(access->target); + if (access->keyId == InternalSymbol::ResultId && targetVariable && + targetVariable->nameId == InternalSymbol::SystemId && + !pipelineResults_.empty()) { + return pipelineResults_.back(); + } + auto target = self(self, access->target, resolving); + auto field = findMapValue(target, access->key); + return field ? self(self, field, resolving) : syntax; + } + return syntax; + }; + const auto isRegisteredMixfix = [&](const std::shared_ptr& syntax) { + const auto nested = std::dynamic_pointer_cast(syntax); + if (!nested || nested->coreOperator != CoreOperator::Unknown) return false; + const auto* pattern = operators_->findPatternById(nested->patternId); + return pattern != nullptr && pattern->isMixfixDeclaration; + }; + const auto expressionType = [&](const std::shared_ptr& syntax) { + std::unordered_set resolving; + auto metadata = metadataValue(metadataValue, syntax, resolving); + const ResolvedOperatorType direct = valueType(metadata); + if (direct.known()) return direct; + if (auto term = std::dynamic_pointer_cast(metadata)) { + if (term->isCapitalized) { + return factRuntimeType(term->name); + } + return ResolvedOperatorType{}; + } + if (auto nested = std::dynamic_pointer_cast(metadata)) { + if (nested->coreOperator != CoreOperator::Unknown) { + if (isComparisonOperator(nested->coreOperator)) { + return builtinRuntimeType(LanguageTypeId::Bool); + } + if (nested->coreOperator == CoreOperator::LogicalAnd || + nested->coreOperator == CoreOperator::LogicalOr || + nested->coreOperator == CoreOperator::LogicalNot) { + return builtinRuntimeType(LanguageTypeId::Bool); + } + if (nested->coreOperator == CoreOperator::Add || + nested->coreOperator == CoreOperator::Subtract || + nested->coreOperator == CoreOperator::Multiply || + nested->coreOperator == CoreOperator::Divide || + nested->coreOperator == CoreOperator::Modulo || + nested->coreOperator == CoreOperator::UnaryPlus || + nested->coreOperator == CoreOperator::UnaryMinus) { + return builtinRuntimeType(LanguageTypeId::Number); + } + } + ResolvedOperatorType resultType; + for (const auto* overload : operators_->overloadsForPattern(nested->patternId)) { + if (overload->visibility == OperatorVisibility::Private && + overload->module != nested->module) continue; + const ResolvedOperatorType candidate = + overload->resultLanguageTypeId != LanguageTypeId::Unknown + ? builtinRuntimeType(overload->resultLanguageTypeId) + : factRuntimeType(overload->resultType); + if (!resultType.known()) resultType = candidate; + else if (!sameResolvedType(resultType, candidate)) { + return ResolvedOperatorType{}; + } + } + return resultType; + } + return ResolvedOperatorType{}; + }; + std::vector captureTypes; + captureTypes.reserve(expression.captureCount()); + for (size_t i = 0; i < expression.captureCount(); ++i) { + captureTypes.push_back(expressionType(expression.capture(i))); + } + + struct Candidate { + const OperatorOverloadDefinition* overload = nullptr; + std::shared_ptr clause; + int score = 0; + std::vector> factorPrototypes; + }; + std::vector candidates; + const auto hierarchyRank = [&](const ResolvedOperatorType& actual, + const OperatorTypeBinding& expected) { + if (actual.factTypeId == expected.typeId && actual.factType == expected.type) { + return 100; + } + std::vector> pending{{actual.factType, 0}}; + std::unordered_set visited; + for (size_t index = 0; index < pending.size(); ++index) { + const auto [current, distance] = pending[index]; + if (!visited.insert(current).second) continue; + for (const auto& parent : memory_.parentsOf(current)) { + if (symbolIdForName(parent) == expected.typeId && + parent == expected.type) { + return std::max(20, 80 - distance - 1); + } + pending.emplace_back(parent, distance + 1); + } + } + return -1; + }; + const auto captureScore = [&](const std::vector& captures, + int& score) { + if (captures.size() != captureTypes.size()) return false; + for (size_t i = 0; i < captureTypes.size(); ++i) { + const auto& actual = captureTypes[i]; + const auto& expected = captures[i]; + if (expected.languageTypeId == LanguageTypeId::Mixfix) { + std::unordered_set resolving; + const auto metadata = metadataValue( + metadataValue, expression.capture(i), resolving); + if (!isRegisteredMixfix(metadata)) return false; + // mixfix is a structural refinement of expr, so it always + // outranks the broad code-as-data fallback. + score += 120; + continue; + } + if (expected.languageTypeId == LanguageTypeId::Expr) { + // expr is the generic code-as-data fallback. A concrete fact + // type must win when the nested expression has a known result. + score += 5; + continue; + } + if (expected.languageTypeId == LanguageTypeId::Any) { + score += 10; + continue; + } + // Unknown expression type cannot satisfy a concrete overload. + // Previously this path skipped validation, allowing a typed + // mixfix overload to win before runtime invocation failed. + if (!actual.known()) return false; + if (expected.languageTypeId == LanguageTypeId::Fact) { + if (actual.factTypeId == 0) return false; + score += 10; + continue; + } + if (expected.languageTypeId != LanguageTypeId::Unknown) { + std::unordered_set resolving; + auto metadata = metadataValue( + metadataValue, expression.capture(i), resolving); + if (!valueMatchesBuiltinType(metadata, expected.languageTypeId) && + !compatibleLanguageType(actual.languageType, + expected.languageTypeId)) { + return false; + } + score += actual.languageType == expected.languageTypeId ? 100 : 80; + } else if (actual.factTypeId == expected.typeId && + actual.factType == expected.type) { + score += 100; + } else { + const int rank = hierarchyRank(actual, expected); + if (rank < 0) return false; + score += rank; + } + } + return true; + }; + const auto matchingClause = [&](SymbolId methodId, + const std::string& methodName) -> std::shared_ptr { + for (const auto& clause : clauses->second) { + if (clause->head.nameId == methodId && clause->head.name == methodName) return clause; + } + return {}; + }; + for (const auto* overloadPtr : operators_->overloadsForPattern(expression.patternId)) { + const auto& overload = *overloadPtr; + if (overload.visibility == OperatorVisibility::Private && overload.module != expression.module) continue; + int score = 0; + if (!captureScore(overload.captures, score)) continue; + if (overload.visibility == OperatorVisibility::Private && + overload.module == expression.module) ++score; + const auto overloadClause = matchingClause(overload.methodId, overload.methodName); + if (!overloadClause) continue; + if (overload.factors.empty()) { + candidates.push_back(Candidate{&overload, overloadClause, score, {}}); + continue; + } + for (const auto* matcherPtr : operators_->matchersForPattern( + expression.patternId, overload.factors.size())) { + const auto& matcher = *matcherPtr; + if (matcher.visibility == OperatorVisibility::Private && matcher.module != expression.module) continue; + int matcherScore = score; + if (!captureScore(matcher.captures, matcherScore)) continue; + + std::vector producedForFactor(overload.factors.size(), matcher.produces.size()); + std::vector used(matcher.produces.size(), false); + bool signatureMatches = true; + for (size_t factorIndex = 0; factorIndex < overload.factors.size(); ++factorIndex) { + const auto& required = overload.factors[factorIndex]; + int best = -1; + std::size_t bestIndex = matcher.produces.size(); + for (size_t producedIndex = 0; producedIndex < matcher.produces.size(); ++producedIndex) { + if (used[producedIndex]) continue; + const auto& produced = matcher.produces[producedIndex]; + int rank = -1; + if (produced.typeId == required.typeId && + produced.type == required.type) { + rank = 100; + } else { + rank = hierarchyRank( + factRuntimeType(produced.type), required); + } + if (rank > best) { + best = rank; + bestIndex = producedIndex; + } + } + if (bestIndex == matcher.produces.size()) { + signatureMatches = false; + break; + } + used[bestIndex] = true; + producedForFactor[factorIndex] = bestIndex; + matcherScore += 1000 + best; + } + if (!signatureMatches) continue; + const auto matcherClause = matchingClause(matcher.methodId, matcher.methodName); + if (!matcherClause) continue; + const auto nodeKindFor = [](const std::shared_ptr& syntax) { + if (std::dynamic_pointer_cast(syntax)) return std::string("string"); + if (std::dynamic_pointer_cast(syntax)) return std::string("number"); + if (std::dynamic_pointer_cast(syntax)) return std::string("bool"); + if (std::dynamic_pointer_cast(syntax)) return std::string("nil"); + if (std::dynamic_pointer_cast(syntax)) return std::string("variable"); + if (std::dynamic_pointer_cast(syntax)) return std::string("call"); + if (std::dynamic_pointer_cast(syntax)) return std::string("operator"); + if (std::dynamic_pointer_cast(syntax)) return std::string("array"); + if (std::dynamic_pointer_cast(syntax)) return std::string("map"); + if (std::dynamic_pointer_cast(syntax)) return std::string("access"); + return std::string("expression"); + }; + const auto spanValue = [](const SourceSpan& span) { + std::vector fields; + fields.emplace_back("startLine", std::make_shared(span.startLine)); + fields.emplace_back("startColumn", std::make_shared(span.startColumn)); + fields.emplace_back("endLine", std::make_shared(span.endLine)); + fields.emplace_back("endColumn", std::make_shared(span.endColumn)); + return std::make_shared(std::move(fields)); + }; + const auto syntaxShape = [&](const auto& self, + const std::shared_ptr& syntax) -> std::shared_ptr { + std::vector fields; + fields.emplace_back("nodeKind", std::make_shared(nodeKindFor(syntax))); + fields.emplace_back("sourceSpan", spanValue(syntax->sourceSpan)); + std::vector> children; + if (auto nested = std::dynamic_pointer_cast(syntax)) { + fields.emplace_back("operatorId", std::make_shared(nested->operatorId)); + fields.emplace_back("patternId", std::make_shared(nested->patternId)); + for (size_t child = 0; child < nested->captureCount(); ++child) { + children.push_back(self(self, nested->capture(child))); + } + } else if (auto term = std::dynamic_pointer_cast(syntax)) { + for (const auto& argument : term->args) children.push_back(self(self, argument.value)); + } else if (auto access = std::dynamic_pointer_cast(syntax)) { + children.push_back(self(self, access->target)); + } else if (auto array = std::dynamic_pointer_cast(syntax)) { + for (const auto& item : array->items) children.push_back(self(self, item)); + } else if (auto map = std::dynamic_pointer_cast(syntax)) { + for (const auto& field : map->entries) children.push_back(self(self, field.value)); + } + fields.emplace_back("children", std::make_shared(std::move(children))); + return std::make_shared(std::move(fields)); + }; + const auto expressionReference = [&](size_t index) { + const auto& syntax = expression.capture(index); + std::string nodeKind = nodeKindFor(syntax); + std::string literalKind; + std::shared_ptr literalValue = std::make_shared(); + if (auto stringLiteral = std::dynamic_pointer_cast(syntax)) { + nodeKind = literalKind = "string"; + literalValue = stringLiteral->clone(); + } else if (auto numberLiteral = std::dynamic_pointer_cast(syntax)) { + nodeKind = literalKind = "number"; + literalValue = numberLiteral->clone(); + } else if (auto boolLiteral = std::dynamic_pointer_cast(syntax)) { + nodeKind = literalKind = "bool"; + literalValue = boolLiteral->clone(); + } else if (std::dynamic_pointer_cast(syntax)) { + nodeKind = literalKind = "nil"; + } else if (auto identifier = std::dynamic_pointer_cast(syntax)) { + literalKind = "identifier"; + literalValue = std::make_shared(identifier->name); + } + std::vector fields; + fields.emplace_back(internalSymbolString(InternalSymbolKind::Type), + std::make_shared("ExpressionRef")); + fields.emplace_back("nodeKind", std::make_shared(nodeKind)); + fields.emplace_back("captureName", std::make_shared( + std::string(expression.captureName(index)))); + const auto& inferred = captureTypes[index]; + fields.emplace_back("inferredType", std::make_shared( + inferred.languageType != LanguageTypeId::Unknown + ? std::string(languageTypeName(inferred.languageType)) + : inferred.factType)); + fields.emplace_back("literalKind", std::make_shared(literalKind)); + fields.emplace_back("literalValue", std::move(literalValue)); + fields.emplace_back("explicitlyGrouped", std::make_shared( + std::dynamic_pointer_cast(syntax) + ? std::dynamic_pointer_cast(syntax)->explicitlyGrouped + : false)); + fields.emplace_back("sourceSpan", spanValue(syntax->sourceSpan)); + auto shape = std::dynamic_pointer_cast(syntaxShape(syntaxShape, syntax)); + fields.emplace_back("children", findMapValue(shape, "children")->clone()); + return std::make_shared(std::move(fields)); + }; + const OperatorPatternDefinition* resolvedPattern = + operators_->findPatternById(expression.patternId); + const std::string operatorName = + resolvedPattern ? resolvedPattern->operatorName : std::string{}; + std::vector> referenceValues; + referenceValues.reserve(captureTypes.size()); + std::vector> contextCaptures; + contextCaptures.reserve(captureTypes.size()); + for (size_t i = 0; i < captureTypes.size(); ++i) { + auto reference = expressionReference(i); + referenceValues.push_back(reference); + contextCaptures.push_back(reference->clone()); + } + std::vector contextFields; + contextFields.emplace_back(internalSymbolString(InternalSymbolKind::Type), + std::make_shared("OperatorContext")); + contextFields.emplace_back("operator", std::make_shared(operatorName)); + contextFields.emplace_back("operatorId", std::make_shared(expression.operatorId)); + contextFields.emplace_back("patternId", std::make_shared(expression.patternId)); + contextFields.emplace_back("pattern", std::make_shared( + resolvedPattern ? resolvedPattern->pattern : std::string{})); + contextFields.emplace_back("precedence", std::make_shared( + resolvedPattern ? static_cast(resolvedPattern->precedence) : 0)); + contextFields.emplace_back("associativity", std::make_shared( + !resolvedPattern ? "none" : + resolvedPattern->associativity == OperatorAssociativity::Left ? "left" : + resolvedPattern->associativity == OperatorAssociativity::Right ? "right" : "none")); + contextFields.emplace_back("explicitlyGrouped", + std::make_shared(expression.explicitlyGrouped)); + contextFields.emplace_back("sourceSpan", spanValue(expression.sourceSpan)); + contextFields.emplace_back("captures", std::make_shared(std::move(contextCaptures))); + Env guardEnv; + guardEnv["context"] = std::make_shared(std::move(contextFields)); + for (size_t i = 0; i < matcher.captures.size(); ++i) { + guardEnv[matcher.captures[i].name] = referenceValues[i]; + } + bool guardsMatch = true; + for (const auto& goal : matcherClause->body) { + if (!std::dynamic_pointer_cast(goal)) continue; + std::vector guardSolutions; + solveRecursive({goal}, guardEnv, guardSolutions, 1, 0); + if (guardSolutions.empty()) { + guardsMatch = false; + break; + } + } + if (!guardsMatch) continue; + const ReturnGoal* returned = nullptr; + for (const auto& goal : matcherClause->body) { + if (auto result = std::dynamic_pointer_cast(goal)) returned = result.get(); + } + if (!returned || returned->fields.size() != 1) continue; + const auto wrapper = std::dynamic_pointer_cast(returned->fields.front().value); + if (!wrapper) continue; + + std::vector> factorPrototypes; + factorPrototypes.reserve(overload.factors.size()); + for (size_t factorIndex = 0; factorIndex < overload.factors.size(); ++factorIndex) { + const auto& produced = matcher.produces[producedForFactor[factorIndex]]; + const Arg* prototype = nullptr; + for (const auto& field : wrapper->args) { + if (field.nameId == produced.nameId && field.name == produced.name) { + prototype = &field; + break; + } + } + if (!prototype) { + signatureMatches = false; + break; + } + factorPrototypes.push_back(prototype->value); + } + if (signatureMatches) { + candidates.push_back(Candidate{ + &overload, overloadClause, matcherScore, std::move(factorPrototypes)}); + } + } + } + if (candidates.empty()) { + if (matched != nullptr) return false; + throw InterpreterError("No typed overload matches the operator captures"); + } + std::sort(candidates.begin(), candidates.end(), [](const Candidate& left, const Candidate& right) { + return left.score > right.score; + }); + if (candidates.size() > 1 && candidates[0].score == candidates[1].score) { + throw InterpreterError("Ambiguous operator overload: multiple implementations have equal specificity"); + } + const Candidate& selected = candidates.front(); + if (matched) *matched = true; + std::vector> values; + values.reserve(expression.captureCount()); + for (size_t i = 0; i < expression.captureCount(); ++i) { + std::shared_ptr value; + const auto captureType = selected.overload->captures[i].languageTypeId; + std::unordered_set resolving; + const auto metadata = metadataValue( + metadataValue, expression.capture(i), resolving); + const bool evaluateNestedMixfix = isRegisteredMixfix(metadata); + if (captureType == LanguageTypeId::Expr && !evaluateNestedMixfix) { + value = std::make_shared( + AstValueKind::Expression, + std::vector>{expression.capture(i)}, + astNodeKind(expression.capture(i))); + } else if (!evalExprValue( + evaluateNestedMixfix ? metadata : expression.capture(i), env, value)) { + return false; + } + values.push_back(std::move(value)); + } + Env methodEnv; + for (size_t i = 0; i < values.size(); ++i) { + methodEnv[selected.overload->captures[i].name] = values[i]; + if (!selected.clause->head.args.empty()) { + const auto parameter = makeMethodParamPlan(selected.clause->head.args[i]); + methodEnv[parameter.localName] = values[i]; + } + } + Env prototypeEnv; + for (size_t i = 0; i < values.size(); ++i) { + prototypeEnv[selected.overload->captures[i].name] = values[i]; + } + for (size_t i = 0; i < selected.factorPrototypes.size(); ++i) { + std::shared_ptr materialized; + if (!evalExprValue(selected.factorPrototypes[i], prototypeEnv, materialized)) { + throw InterpreterError("Requirement prototype could not be materialized after overload selection"); + } + methodEnv[selected.overload->factors[i].name] = std::move(materialized); + } + std::vector solutions; + constexpr std::size_t kMaxOperatorManyResults = 1000; + const std::size_t solutionLimit = selected.overload->cardinality == OperatorCardinality::Many + ? kMaxOperatorManyResults + 1 : 2; + solveRecursive(selected.clause->body, methodEnv, solutions, solutionLimit, 0); + if (solutions.empty()) { + for (const auto& branch : selected.clause->fallbackBranches) { + solveRecursive(branch, methodEnv, solutions, solutionLimit, 0); + if (!solutions.empty()) break; + } + } + if (selected.overload->cardinality == OperatorCardinality::One && solutions.size() != 1) { + throw InterpreterError("Operator overload cardinality 'one' requires exactly one result"); + } + if (selected.overload->cardinality == OperatorCardinality::Optional && solutions.size() > 1) { + throw InterpreterError("Operator overload cardinality 'optional' permits at most one result"); + } + if (selected.overload->cardinality == OperatorCardinality::Many && + solutions.size() > kMaxOperatorManyResults) { + throw InterpreterError("Operator overload cardinality 'many' exceeded the 1000-result safety limit"); + } + if (solutions.empty()) { + if (selected.overload->cardinality == OperatorCardinality::Many) { + out = std::make_shared(std::vector>{}); + return true; + } + out = std::make_shared(); + return selected.overload->cardinality == OperatorCardinality::Optional; + } + std::vector> returnedValues; + returnedValues.reserve(solutions.size()); + for (const auto& solution : solutions) { + auto returned = solution.env.find(internalSymbolString(InternalSymbolKind::Return)); + if (returned == solution.env.end()) { + throw InterpreterError("Operator overload method did not return a value"); + } + auto value = resolveExpr(returned->second, solution.env)->clone(); + const ResolvedOperatorType actual = valueType(value); + bool validResult = true; + if (!selected.overload->resultType.empty()) { + if (selected.overload->resultLanguageTypeId != LanguageTypeId::Unknown) { + validResult = valueMatchesBuiltinType( + value, selected.overload->resultLanguageTypeId); + } else if (actual.factTypeId != 0) { + validResult = + (actual.factTypeId == selected.overload->resultTypeId && + actual.factType == selected.overload->resultType) || + memory_.isCompatibleType( + actual.factType, selected.overload->resultType); + } else { + validResult = false; + } + } + if (!validResult) { + const std::string actualName = + actual.languageType != LanguageTypeId::Unknown + ? std::string(languageTypeName(actual.languageType)) + : actual.factType.empty() ? "unknown" : actual.factType; + throw InterpreterError("Operator overload returned '" + actualName + + "', expected '" + selected.overload->resultType + "'"); + } + returnedValues.push_back(std::move(value)); + } + if (selected.overload->cardinality == OperatorCardinality::Many) { + out = std::make_shared(std::move(returnedValues)); + } else { + out = std::move(returnedValues.front()); + } + return true; +} + +bool Interpreter::compareResolved(const std::shared_ptr& left, + TokenId::Id op, + const std::shared_ptr& right) const { + auto ln = std::dynamic_pointer_cast(left); + auto rn = std::dynamic_pointer_cast(right); + if (ln && rn) { + switch (op) { + case TokenId::LESS: return ln->value < rn->value; + case TokenId::LESS_EQUAL: return ln->value <= rn->value; + case TokenId::GREATER: return ln->value > rn->value; + case TokenId::GREATER_EQUAL: return ln->value >= rn->value; + default: return false; + } + } + + auto ls = std::dynamic_pointer_cast(left); + auto rs = std::dynamic_pointer_cast(right); + if (ls && rs) { + switch (op) { + case TokenId::LESS: return ls->value < rs->value; + case TokenId::LESS_EQUAL: return ls->value <= rs->value; + case TokenId::GREATER: return ls->value > rs->value; + case TokenId::GREATER_EQUAL: return ls->value >= rs->value; + default: return false; + } + } + + return false; +} + +bool Interpreter::unifyCall(const Call& goal, const Call& head, Env& env) { + if (goal.nameId != head.nameId) return false; + + bool headHasNamed = false; + for (const auto& a : head.args) if (!a.name.empty()) headHasNamed = true; + + if (goal.args.size() == 1 && goal.args[0].name.empty() && headHasNamed) return false; + + // This supports partial named matching. A goal can specify only the fields it cares about: + // Employee(name: X) can match Employee(name: "Alice", role: "Engineer"). + for (size_t i = 0; i < goal.args.size(); ++i) { + const Arg& goalArg = goal.args[i]; + const Arg* headArg = findArg(head, goalArg, i); + if (!headArg) return false; + if (!unifyExpr(goalArg.value, headArg->value, env)) return false; + } + + // For positional predicates, arity should match. For named predicates, partial matching is allowed. + bool goalHasNamed = false; + for (const auto& a : goal.args) if (!a.name.empty()) goalHasNamed = true; + if (!goalHasNamed && !headHasNamed && goal.args.size() != head.args.size()) return false; + + return true; +} + +std::vector Interpreter::unifyCallAlternatives(const Call& goal, const Call& head, const Env& env) { + if (goal.nameId != head.nameId) return {}; + + bool headHasNamed = false; + bool goalHasNamed = false; + for (const auto& arg : head.args) if (!arg.name.empty()) headHasNamed = true; + for (const auto& arg : goal.args) if (!arg.name.empty()) goalHasNamed = true; + + if (goal.args.size() == 1 && goal.args[0].name.empty() && headHasNamed) return {}; + if (!goalHasNamed && !headHasNamed && goal.args.size() != head.args.size()) return {}; + + std::vector> candidatesByArg; + candidatesByArg.reserve(goal.args.size()); + bool hasAlternatives = false; + for (size_t i = 0; i < goal.args.size(); ++i) { + const Arg& goalArg = goal.args[i]; + std::vector candidates; + if (!goalArg.name.empty()) { + for (const auto& headArg : head.args) { + if (headArg.nameId == goalArg.nameId) { + candidates.push_back(&headArg); + } + } + if (candidates.empty() && i < head.args.size() && head.args[i].name.empty()) { + candidates.push_back(&head.args[i]); + } + } else if (i < head.args.size()) { + candidates.push_back(&head.args[i]); + } + if (candidates.empty()) return {}; + hasAlternatives = hasAlternatives || candidates.size() > 1; + candidatesByArg.push_back(std::move(candidates)); + } + + if (!hasAlternatives) { + Env attempt = env; + for (size_t i = 0; i < goal.args.size(); ++i) { + if (!unifyExpr(goal.args[i].value, candidatesByArg[i].front()->value, attempt)) return {}; + } + std::vector result; + result.reserve(1); + result.push_back(std::move(attempt)); + return result; + } + + std::vector results; + Env working = env; + BindingTrail trail; + BindingTrail* previousTrail = activeBindingTrail_; + activeBindingTrail_ = &trail; + const auto restoreTrail = [&]() { + trail.rollback(0); + activeBindingTrail_ = previousTrail; + }; + const auto enumerate = [&](const auto& self, size_t argumentIndex) -> void { + if (argumentIndex == goal.args.size()) { + results.push_back(working); + return; + } + const auto checkpoint = trail.checkpoint(); + const Arg& goalArg = goal.args[argumentIndex]; + for (const Arg* candidate : candidatesByArg[argumentIndex]) { + trail.rollback(checkpoint); + if (unifyExpr(goalArg.value, candidate->value, working)) { + self(self, argumentIndex + 1); + } + } + trail.rollback(checkpoint); + }; + try { + enumerate(enumerate, 0); + } catch (...) { + restoreTrail(); + throw; + } + restoreTrail(); + return results; +} + +const Arg* Interpreter::findArg(const Call& call, const Arg& wanted, size_t index) const { + if (!wanted.name.empty()) { + for (const auto& a : call.args) { + if (a.nameId == wanted.nameId) return &a; + } + if (index < call.args.size() && call.args[index].name.empty()) return &call.args[index]; + return nullptr; + } + if (index < call.args.size()) return &call.args[index]; + return nullptr; +} + +bool Interpreter::unifyExpr(const std::shared_ptr& a, + const std::shared_ptr& b, + Env& env) { + ++unificationAttempts_; + auto ra = resolveExpr(a, env); + auto rb = resolveExpr(b, env); + + if (isSameVariable(ra, rb)) return true; + + if (auto va = std::dynamic_pointer_cast(ra)) { + if (isInternalGeneratedSymbolId(va->nameId)) return true; + } + if (auto vb = std::dynamic_pointer_cast(rb)) { + if (isInternalGeneratedSymbolId(vb->nameId)) return true; + } + + if (auto va = std::dynamic_pointer_cast(ra)) { + std::shared_ptr value; + value = evalExprValue(rb, env, value) ? value : rb->clone(); + if (activeBindingTrail_) activeBindingTrail_->assign(env, va->nameId, std::move(value)); + else env[va->nameId] = std::move(value); + return true; + } + if (auto vb = std::dynamic_pointer_cast(rb)) { + std::shared_ptr value; + value = evalExprValue(ra, env, value) ? value : ra->clone(); + if (activeBindingTrail_) activeBindingTrail_->assign(env, vb->nameId, std::move(value)); + else env[vb->nameId] = std::move(value); + return true; + } + + if (auto sa = std::dynamic_pointer_cast(ra)) { + auto sb = std::dynamic_pointer_cast(rb); + return sb && sa->value == sb->value; + } + if (auto na = std::dynamic_pointer_cast(ra)) { auto nb = std::dynamic_pointer_cast(rb); return nb && std::fabs(na->value - nb->value) < 1e-12; } diff --git a/src/Interpreter.h b/src/Interpreter.h index be91954..4771a5b 100644 --- a/src/Interpreter.h +++ b/src/Interpreter.h @@ -63,6 +63,9 @@ class Interpreter { void recordParserMetrics(const ParserMetrics& metrics); std::size_t syncFactSource(const std::filesystem::path& file); std::shared_ptr operatorRegistry() const { return operators_; } + // Imported source files registered by the current interpreter. The root + // module is owned by the frontend; callers add it to any watch set. + std::vector loadedSourceFiles() const; private: struct ThreadTask { @@ -182,6 +185,7 @@ class Interpreter { std::vector> autoEntryResults; FactMemory memory; GlobalEnv globals; + std::unordered_map> classDefinitions; std::unordered_map> referencesBySource; std::uint64_t nextReferenceAttachmentId = 1; std::size_t nextReferenceCreationOrder = 0; @@ -205,6 +209,9 @@ class Interpreter { std::vector> autoEntryResults_; FactMemory memory_; GlobalEnv globals_; + // Class declarations are retained as AST schema metadata. A constructor + // call creates a typed map directly; it never passes through IR or a VM. + std::unordered_map> classDefinitions_; std::unordered_map solveCache_; std::list solveCacheRecency_; std::size_t solveCacheBytes_ = 0; @@ -307,6 +314,7 @@ class Interpreter { bool solveBuiltin(const Call& call, Env& env); bool solveNativeCall(const Call& call, Env& env); bool evalBuiltinTerm(const TermExpr& term, const Env& env, std::shared_ptr& out); + bool instantiateClass(const TermExpr& term, const Env& env, std::shared_ptr& out); bool evalAncestorAnalysis(const Call& call, const Env& env, std::shared_ptr& out); bool evalFactPropagation(const Call& call, const Env& env, std::shared_ptr& out); bool evalRelationCompare(const Call& call, const Env& env, std::shared_ptr& out); diff --git a/src/IrCodeGenerator.cpp b/src/IrCodeGenerator.cpp deleted file mode 100644 index 84824ef..0000000 --- a/src/IrCodeGenerator.cpp +++ /dev/null @@ -1,2995 +0,0 @@ -#include "IrCodeGenerator.h" - -#include "BuiltinRegistry.h" -#include "IntegerParser.h" -#include "OperatorAnnotation.h" -#include "Symbol.h" -#include "form/SemanticOperation.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae { -namespace { - -#ifndef NDEBUG -bool codegenTraceEnabled() { - static const bool enabled = [] { - const auto *value = std::getenv("FELIDAE_TRACE"); - return value != nullptr && *value != '\0' && std::string_view(value) != "0"; - }(); - return enabled; -} -#endif - -struct DirectCompileContext { - const std::unordered_set &procedures; - const std::unordered_set &factTypes; -}; - -// Desugars ordered `where` guards into the existing IfGoal representation. -// Goals before a guard execute at their original level; goals after it run -// only when the condition succeeds. Reusing the same fallback branch at each -// level gives every failed guard the clause's established `else` behavior. -// This is a syntax-to-AST normalization only: it adds no opcode or execution -// path, and supports ordinary assignment sequences around guard statements. -std::vector> desugarWhereGuards( - std::span> remaining, - const std::vector> &elseBranch) { - if (remaining.empty()) - throw IntegerParserError("where-guarded clause requires a terminal goal"); - const auto guard = std::find_if( - remaining.begin(), remaining.end(), [](const auto &goal) { - return std::dynamic_pointer_cast(goal) != nullptr; - }); - if (guard == remaining.end()) - return {remaining.begin(), remaining.end()}; - - std::vector> result(remaining.begin(), guard); - const auto where = std::dynamic_pointer_cast(*guard); - const auto offset = static_cast(guard - remaining.begin()); - auto thenBranch = desugarWhereGuards(remaining.subspan(offset + 1), - elseBranch); - auto ifGoal = std::make_shared( - where->condition, std::move(thenBranch), elseBranch); - ifGoal->sourceSpan = where->sourceSpan; - result.push_back(std::move(ifGoal)); - return result; -} - -// Rewrites every where-guarded clause in the program to its desugared -// IfGoal-chain form, in place, before eligibility checks or lowering ever -// see it. `else`-without-`where` stays an explicit compile error (no -// competing implicit-guard grammar); a `where` guard with no `else` compiles -// to an implicit else branch that throws BuiltinId::WhereGuardFailed at -// runtime -- a clear failure instead of a silent nil, and instead of -// rejecting valid guard-only clauses at compile time. -void desugarWhereGuardedClauses(Program &program) { - for (auto &clause : program.clauses) { - if (!clause || clause->isFact()) - continue; - const bool hasWhereGuard = std::any_of( - clause->body.begin(), clause->body.end(), [](const auto &goal) { - return std::dynamic_pointer_cast(goal) != nullptr; - }); - if (!hasWhereGuard && clause->fallbackBranches.empty()) - continue; - if (!hasWhereGuard) { - throw IntegerParserError( - "not yet lowered to IR: else without a where guard at " + - std::to_string(clause->sourceSpan.startLine) + ":" + - std::to_string(clause->sourceSpan.startColumn)); - } - std::vector> elseBranch; - if (clause->fallbackBranches.empty()) { - auto failCall = std::make_shared( - "where:guardFailed", std::vector{}, BuiltinId::WhereGuardFailed); - failCall->sourceSpan = clause->sourceSpan; - auto returned = - std::make_shared(std::vector{Arg({}, failCall)}); - returned->sourceSpan = clause->sourceSpan; - elseBranch.push_back(std::move(returned)); - } else if (clause->fallbackBranches.size() == 1) { - elseBranch = clause->fallbackBranches.front(); - } else { - throw IntegerParserError( - "not yet lowered to IR: a where-guarded clause requires at most " - "one else branch at " + - std::to_string(clause->sourceSpan.startLine) + ":" + - std::to_string(clause->sourceSpan.startColumn)); - } - auto rewritten = std::make_shared(*clause); - rewritten->body = desugarWhereGuards(clause->body, elseBranch); - rewritten->fallbackBranches.clear(); - clause = std::move(rewritten); - } -} - -// Defined later in this file, alongside resolveScopedAccess whose traversal -// shape it mirrors; forward-declared here for FactDmlLowerer::iteration(). -std::shared_ptr substituteCaptures( - const std::shared_ptr &expression, const std::string &rowParameter, - SymbolId rowParameterId, const std::string &capturesVariable, - SymbolId capturesVariableId, - std::vector> &captured, - std::unordered_set &capturedIds); - -// Fact queries are source conveniences over the existing ForEachFact IR -// operation. Each predicate becomes an ordinary compiler-generated procedure; -// RegisterVm therefore retains one iteration/call path for both lambda(...) -// and concrete type methods such as School.all() and School.select(...). -class FactDmlLowerer { -public: - explicit FactDmlLowerer(const Program &program) { - for (const auto &declaration : program.classes) { - if (!declaration) - continue; - occupied_.insert(declaration->nameId); - factTypes_.emplace(declaration->name, declaration->nameId); - } - for (const auto &clause : program.clauses) { - if (!clause) - continue; - occupied_.insert(clause->head.nameId); - if (clause->isFact()) - factTypes_.emplace(clause->head.name, clause->head.nameId); - } - } - - void normalize(Program &program) { - for (auto &binding : program.globals) - if (binding) - binding->expr = expression(binding->expr); - for (auto &clause : program.clauses) { - if (!clause || clause->isFact()) - continue; - goals(clause->body); - for (auto &branch : clause->fallbackBranches) - goals(branch); - } - program.clauses.insert(program.clauses.end(), generated_.begin(), - generated_.end()); - } - -private: - std::optional> - queryRoot(const std::shared_ptr &value) const { - const auto term = std::dynamic_pointer_cast(value); - if (!term) - return std::nullopt; - if (term->name.rfind("__query:", 0) == 0 && !term->args.empty()) - return queryRoot(term->args.front().value); - const auto separator = term->name.rfind('.'); - if (separator == std::string::npos) - return std::nullopt; - const auto typeName = term->name.substr(0, separator); - const auto type = factTypes_.find(typeName); - if (type == factTypes_.end()) - return std::nullopt; - return std::pair{typeName, type->second}; - } - - bool conditionChain(const std::shared_ptr &value) const { - const auto term = std::dynamic_pointer_cast(value); - if (!term) - return false; - if ((term->name == "__query:AndWhere" || - term->name == "__query:OrWhere") && - !term->args.empty()) - return conditionChain(term->args.front().value); - const auto separator = term->name.rfind('.'); - return separator != std::string::npos && - term->name.substr(separator + 1) == "where"; - } - - std::shared_ptr iteration(std::string typeName, SymbolId typeId, - std::string variable, SymbolId variableId, - std::shared_ptr body, - const SourceSpan &sourceSpan) { - std::string procedureName; - SymbolId procedureId = 0; - do { - procedureName = "__fact_query_" + std::to_string(nextProcedure_++); - procedureId = symbolIdForName(procedureName); - } while (occupied_.contains(procedureId)); - occupied_.insert(procedureId); - - // A predicate that reads an outer-scope value (`r.from == tiger_female`, - // not just a literal) closes over it: the synthesized callback below has - // no access to the caller's own registers, so every such reference is - // rewritten to read from a second, explicit __captures parameter - // instead, and the caller builds that map from its own scope where the - // values are actually defined. See substituteCaptures() and - // IrOpcode::ForEachFact's fifth operand in RegisterVm.cpp. - const std::string capturesVariable = "__captures"; - const SymbolId capturesVariableId = symbolIdForName(capturesVariable); - std::vector> captured; - std::unordered_set capturedIds; - body = substituteCaptures(body, variable, variableId, capturesVariable, - capturesVariableId, captured, capturedIds); - - Call head(procedureName, procedureId, - {Arg(variable, variableId, - std::make_shared(typeName, typeId)), - Arg(capturesVariable, capturesVariableId, - std::make_shared("any", symbolIdForName("any")))}); - auto returned = std::make_shared( - std::vector{Arg(std::string{}, std::move(body))}); - returned->sourceSpan = sourceSpan; - auto procedure = std::make_shared( - std::move(head), std::string{}, - std::vector>{std::move(returned)}, - std::vector>>{}, false, - ClauseKind::Method); - procedure->sourceSpan = sourceSpan; - generated_.push_back(std::move(procedure)); - - std::vector captureEntries; - captureEntries.reserve(captured.size()); - for (const auto &[name, id] : captured) { - auto reference = std::make_shared(name, id); - reference->sourceSpan = sourceSpan; - captureEntries.emplace_back(name, id, std::move(reference)); - } - auto capturesMap = std::make_shared(std::move(captureEntries)); - capturesMap->sourceSpan = sourceSpan; - - auto result = std::make_shared( - "for_each_fact", - std::vector{ - Arg(std::string{}, - std::make_shared(typeName, typeId)), - Arg(std::string{}, - std::make_shared(procedureName, procedureId)), - Arg(std::string{}, std::move(capturesMap))}); - result->sourceSpan = sourceSpan; - return result; - } - - std::shared_ptr expression(std::shared_ptr value) { - if (!value) - return value; - if (const auto lambda = std::dynamic_pointer_cast(value)) { - lambda->source = expression(lambda->source); - lambda->body = expression(lambda->body); - if (lambda->right) - lambda->right = expression(lambda->right); - const auto source = std::dynamic_pointer_cast(lambda->source); - const auto type = source ? factTypes_.find(source->name) - : factTypes_.end(); - if (!source || type == factTypes_.end() || type->second != source->nameId) - return value; - return iteration(source->name, source->nameId, lambda->variable, - lambda->variableId, lambda->body, lambda->sourceSpan); - } - if (const auto array = std::dynamic_pointer_cast(value)) { - for (auto &item : array->items) - item = expression(item); - } else if (const auto map = std::dynamic_pointer_cast(value)) { - for (auto &entry : map->entries) - entry.value = expression(entry.value); - } else if (const auto access = - std::dynamic_pointer_cast(value)) { - access->target = expression(access->target); - } else if (const auto term = - std::dynamic_pointer_cast(value)) { - if (term->name == "__query:limit") { - if (term->args.size() != 2 || term->args[1].name != "records") - throw IntegerParserError( - "limit requires exactly one named records argument"); - auto result = std::make_shared( - "array:limit", - std::vector{Arg(std::string{}, expression(term->args[0].value)), - Arg(std::string{}, expression(term->args[1].value))}, - BuiltinId::ArrayLimit); - result->sourceSpan = term->sourceSpan; - return result; - } - if (term->name == "__query:AndWhere" || - term->name == "__query:OrWhere") { - if (term->args.size() < 2) - throw IntegerParserError(term->name.substr(8) + - " requires a condition"); - if (!conditionChain(term->args[0].value)) - throw IntegerParserError(term->name.substr(8) + - " must follow where/AndWhere/OrWhere"); - const auto root = queryRoot(term->args[0].value); - if (!root) - throw IntegerParserError(term->name.substr(8) + - " requires a fact query target"); - std::vector condition(term->args.begin() + 1, term->args.end()); - auto next = std::make_shared( - root->first + ".where", std::move(condition)); - next->sourceSpan = term->sourceSpan; - auto result = std::make_shared( - "fact:setCombine", - std::vector{ - Arg(std::string{}, expression(term->args[0].value)), - Arg(std::string{}, expression(std::move(next))), - Arg(std::string{}, std::make_shared( - term->name == "__query:AndWhere" ? 0.0 - : 1.0))}, - BuiltinId::FactSetCombine); - result->sourceSpan = term->sourceSpan; - return result; - } - if (term->name == "__query:update" || - term->name == "__query:delete") { - // Mutations consume an explicit where/AndWhere/OrWhere selection. - // The compiler lowers the receiver directly to its existing fact - // array, so RegisterVm needs no mutable query-object representation. - if (term->args.empty()) - throw IntegerParserError( - "fact mutation requires a preceding where condition"); - if (!conditionChain(term->args.front().value)) - throw IntegerParserError( - "update/delete must follow where/AndWhere/OrWhere"); - auto rows = expression(term->args.front().value); - if (term->name == "__query:update") { - if (term->args.size() != 2 || term->args[1].name != "values") - throw IntegerParserError( - "update requires exactly one named values map"); - auto result = std::make_shared( - "fact:update", - std::vector{Arg(std::string{}, std::move(rows)), - Arg(std::string{}, - expression(term->args[1].value))}, - BuiltinId::FactUpdate); - result->sourceSpan = term->sourceSpan; - return result; - } - if (term->args.size() != 1) - throw IntegerParserError("delete accepts no arguments"); - auto result = std::make_shared( - "fact:delete", - std::vector{Arg(std::string{}, std::move(rows))}, - BuiltinId::FactDelete); - result->sourceSpan = term->sourceSpan; - return result; - } - for (auto &argument : term->args) - argument.value = expression(argument.value); - const auto separator = term->name.rfind('.'); - if (separator == std::string::npos) - return value; - const auto typeName = term->name.substr(0, separator); - const auto method = term->name.substr(separator + 1); - const auto type = factTypes_.find(typeName); - if (type == factTypes_.end()) - return value; - const auto rowName = "__fact"; - const auto rowId = symbolIdForName(rowName); - const auto mapArguments = [&](const std::shared_ptr &value, - std::string_view label) { - const auto map = std::dynamic_pointer_cast(value); - if (!map) - throw IntegerParserError(typeName + "." + method + " " + - std::string(label) + " must be a map"); - std::vector result; - result.reserve(map->entries.size()); - for (const auto &entry : map->entries) - result.emplace_back(entry.key, entry.keyId, entry.value); - return result; - }; - const auto queryFromMatch = [&](const std::shared_ptr &match) { - auto query = std::make_shared( - typeName + ".where", mapArguments(match, "match")); - query->sourceSpan = term->sourceSpan; - return expression(std::move(query)); - }; - const auto named = [&](std::string_view name) -> std::shared_ptr { - const auto found = std::find_if(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return argument.name == name; - }); - return found == term->args.end() ? nullptr : found->value; - }; - if (method == "search") { - const auto field = std::dynamic_pointer_cast(named("field")); - const auto searchType = - std::dynamic_pointer_cast(named("type")); - if (!field || !searchType) - throw IntegerParserError(typeName + - ".search requires text field and type"); - static const std::unordered_set allowedArguments{ - "field", "query", "type", "case", - "direction", "includeSelf", "minimum", "maximum", - "tolerance"}; - for (const auto &argument : term->args) - if (!allowedArguments.contains(argument.name)) - throw IntegerParserError(typeName + - ".search has an unknown argument " + - argument.name); - - const auto textMode = searchType->value; - const bool textSearch = - textMode == "exact" || textMode == "prefix" || - textMode == "suffix" || textMode == "contains" || - textMode == "like" || textMode == "regex"; - if (textSearch) { - if (!std::dynamic_pointer_cast(named("query"))) - throw IntegerParserError(typeName + ".search " + textMode + - " mode requires a text query"); - if (const auto caseMode = - std::dynamic_pointer_cast(named("case")); - caseMode && caseMode->value != "sensitive" && - caseMode->value != "insensitive") - throw IntegerParserError( - typeName + ".search case must be sensitive or insensitive"); - } else if (textMode == "hierarchy") { - if (!named("query")) - throw IntegerParserError(typeName + - ".search hierarchy type requires query"); - const auto direction = - std::dynamic_pointer_cast(named("direction")); - if (!direction || - (direction->value != "ancestors" && - direction->value != "descendants" && - direction->value != "related")) - throw IntegerParserError( - typeName + ".search hierarchy direction is invalid"); - } else if (textMode == "degree") { - const bool closeness = named("query") && named("tolerance"); - const bool range = named("minimum") || named("maximum"); - if (closeness == range) - throw IntegerParserError( - typeName + - ".search degree type requires either query+tolerance or a range"); - } else { - throw IntegerParserError(typeName + ".search type is invalid"); - } - - std::vector optionEntries; - optionEntries.reserve(term->args.size() - 1); - for (const auto &argument : term->args) { - if (argument.name == "field") - continue; - optionEntries.emplace_back(argument.name, argument.nameId, - argument.value); - } - auto options = std::make_shared(std::move(optionEntries)); - options->sourceSpan = term->sourceSpan; - auto rows = iteration(typeName, type->second, rowName, rowId, - std::make_shared(rowName, rowId), - term->sourceSpan); - auto result = std::make_shared( - "fact:search", - std::vector{Arg(std::string{}, std::move(rows)), - Arg(std::string{}, field), - Arg(std::string{}, std::move(options))}, - BuiltinId::FactSearch); - result->sourceSpan = term->sourceSpan; - return result; - } - if (method == "insert") { - const auto values = named("values"); - const auto source = named("source"); - if (!values || term->args.size() != (source ? 2u : 1u)) - throw IntegerParserError( - typeName + ".insert requires values and optional source"); - auto result = std::make_shared( - "fact:insert", - std::vector{ - Arg(std::string{}, std::make_shared( - typeName, symbolPiecesForId(type->second))), - Arg(std::string{}, values), - Arg(std::string{}, source ? source - : std::make_shared())}, - BuiltinId::FactInsert); - result->sourceSpan = term->sourceSpan; - return result; - } - if (method == "update") { - throw IntegerParserError(typeName + - ".update must follow a where condition"); - } - if (method == "delete") { - throw IntegerParserError(typeName + - ".delete must follow a where condition"); - } - if (method == "join") { - const auto other = std::dynamic_pointer_cast(named("type")); - const auto left = std::dynamic_pointer_cast(named("left")); - const auto right = std::dynamic_pointer_cast(named("right")); - const auto kindArgument = named("kind"); - if (!other || !factTypes_.contains(other->name) || !left || !right || - term->args.size() != (kindArgument ? 4u : 3u)) - throw IntegerParserError(typeName + - ".join requires type, left, right, and an " - "optional kind"); - double kindValue = 0.0; - if (kindArgument) { - const auto kind = - std::dynamic_pointer_cast(kindArgument); - if (!kind) - throw IntegerParserError(typeName + - ".join kind must be text"); - if (kind->value == "inner") - kindValue = 0.0; - else if (kind->value == "left") - kindValue = 1.0; - else if (kind->value == "right") - kindValue = 2.0; - else if (kind->value == "outer") - kindValue = 3.0; - else - throw IntegerParserError( - typeName + - ".join kind must be inner, left, right, or outer"); - } - const auto kind = std::make_shared(kindValue); - auto leftRows = std::make_shared(typeName + ".all", - std::vector{}); - auto rightRows = std::make_shared(other->name + ".all", - std::vector{}); - auto result = std::make_shared( - "fact:join", - std::vector{Arg(std::string{}, expression(leftRows)), - Arg(std::string{}, expression(rightRows)), - Arg(std::string{}, left), Arg(std::string{}, right), - Arg(std::string{}, kind)}, - BuiltinId::FactJoin); - result->sourceSpan = term->sourceSpan; - return result; - } - const auto matchingRows = [&]() { - const auto match = named("match"); - if (match) - return queryFromMatch(match); - return iteration(typeName, type->second, rowName, rowId, - std::make_shared(rowName, rowId), - term->sourceSpan); - }; - if (method == "count") { - if (term->args.size() > 1 || - (term->args.size() == 1 && !named("match"))) - throw IntegerParserError( - typeName + ".count accepts only an optional match map"); - auto rows = matchingRows(); - auto result = std::make_shared( - "array:len", - std::vector{Arg(std::string{}, std::move(rows))}, - BuiltinId::ArrayLen); - result->sourceSpan = term->sourceSpan; - return result; - } - if (method == "sum" || method == "average" || method == "min" || - method == "max") { - const auto field = std::dynamic_pointer_cast(named("field")); - if (!field || term->args.size() > 2 || - (term->args.size() == 2 && !named("match"))) - throw IntegerParserError(typeName + "." + method + - " requires field and optional match"); - const double operation = method == "sum" ? 0.0 - : method == "average" ? 1.0 - : method == "min" ? 2.0 - : 3.0; - auto result = std::make_shared( - "fact:aggregate", - std::vector{Arg(std::string{}, matchingRows()), - Arg(std::string{}, field), - Arg(std::string{}, - std::make_shared(operation))}, - BuiltinId::FactAggregate); - result->sourceSpan = term->sourceSpan; - return result; - } - if (method == "all") { - if (!term->args.empty()) - throw IntegerParserError(typeName + ".all requires no arguments"); - return iteration(typeName, type->second, rowName, rowId, - std::make_shared(rowName, rowId), - term->sourceSpan); - } - if (method == "select") { - const auto fields = std::dynamic_pointer_cast(named("fields")); - if (!fields || term->args.size() > 2 || - (term->args.size() == 2 && !named("match"))) - throw IntegerParserError(typeName + - ".select requires fields and optional match"); - if (std::any_of(fields->items.begin(), fields->items.end(), - [](const auto &field) { - return !std::dynamic_pointer_cast(field); - })) - throw IntegerParserError(typeName + - ".select fields must contain text names"); - auto result = std::make_shared( - "fact:project", - std::vector{Arg(std::string{}, matchingRows()), - Arg(std::string{}, fields)}, - BuiltinId::FactProject); - result->sourceSpan = term->sourceSpan; - return result; - } - if (method == "where") { - if (term->args.size() == 1 && - term->args.front().name == "using") { - const auto callback = - std::dynamic_pointer_cast(term->args.front().value); - if (!callback) - throw IntegerParserError(typeName + - ".where using must name a procedure"); - auto result = std::make_shared( - "for_each_fact", - std::vector{ - Arg(std::string{}, - std::make_shared(typeName, type->second)), - Arg(std::string{}, callback)}, - BuiltinId::Unknown); - result->sourceSpan = term->sourceSpan; - return result; - } - if (term->args.empty() || - std::any_of(term->args.begin(), term->args.end(), - [](const Arg &argument) { - return argument.name.empty(); - })) { - throw IntegerParserError(typeName + "." + method + - " requires named field values"); - } - std::vector predicates; - predicates.reserve(term->args.size()); - for (const auto &argument : term->args) - predicates.emplace_back(argument.name, argument.nameId, - argument.value); - auto predicateMap = std::make_shared(std::move(predicates)); - predicateMap->sourceSpan = term->sourceSpan; - auto result = std::make_shared( - "__fact:where", - std::vector{ - Arg(std::string{}, - std::make_shared(typeName, type->second)), - Arg(std::string{}, std::move(predicateMap))}); - result->sourceSpan = term->sourceSpan; - return result; - } - } else if (const auto operation = - std::dynamic_pointer_cast(value)) { - std::vector captures; - captures.reserve(operation->captureCount()); - for (std::size_t index = 0; index < operation->captureCount(); ++index) { - captures.emplace_back(std::string(operation->captureName(index)), - expression(operation->capture(index))); - } - std::shared_ptr rewritten; - if (operation->coreOperator == CoreOperator::Unknown) { - rewritten = std::make_shared( - operation->operatorId, operation->patternId, std::move(captures), - operation->explicitlyGrouped, operation->resolvedMethodId); - } else if (captures.size() == 1) { - rewritten = std::make_shared( - operation->coreOperator, captures.front().expression); - } else { - rewritten = std::make_shared( - operation->coreOperator, captures.at(0).expression, - captures.at(1).expression); - } - rewritten->module = operation->module; - rewritten->sourceSpan = operation->sourceSpan; - return rewritten; - } - return value; - } - - void goals(std::vector> &items) { - for (auto &goal : items) { - if (const auto assignment = std::dynamic_pointer_cast(goal)) - assignment->expr = expression(assignment->expr); - else if (const auto assignment = - std::dynamic_pointer_cast(goal)) - assignment->expr = expression(assignment->expr); - else if (const auto returned = - std::dynamic_pointer_cast(goal)) - for (auto &field : returned->fields) - field.value = expression(field.value); - else if (const auto binary = - std::dynamic_pointer_cast(goal)) { - binary->left = expression(binary->left); - binary->right = expression(binary->right); - } else if (const auto call = - std::dynamic_pointer_cast(goal)) { - for (auto &argument : call->call.args) - argument.value = expression(argument.value); - } else if (const auto conditional = - std::dynamic_pointer_cast(goal)) { - std::vector> condition{conditional->condition}; - goals(condition); - conditional->condition = condition.front(); - goals(conditional->thenBranch); - goals(conditional->elseBranch); - } - } - } - - std::unordered_map factTypes_; - std::unordered_set occupied_; - std::vector> generated_; - std::size_t nextProcedure_ = 0; -}; - -void lowerFactDml(Program &program) { - FactDmlLowerer(program).normalize(program); -} - -// The integer parser preserves a dotted identifier as one symbol because the -// same SentencePiece sequence is also used for qualified calls and `fx.` -// keys. The compiler is the first phase with lexical scope information, so -// it can safely reinterpret only `local.field` spellings whose first segment -// is a visible binding. Unscoped qualified symbols stay untouched. -std::shared_ptr -resolveScopedAccess(const std::shared_ptr &expression, - const std::unordered_set &visible, - const std::unordered_set *implicitFields = nullptr) { - if (!expression) - return expression; - if (const auto variable = std::dynamic_pointer_cast(expression)) { - const auto dot = variable->name.find('.'); - if (dot == std::string::npos) { - if (implicitFields && implicitFields->contains(variable->nameId)) { - auto access = std::make_shared( - std::make_shared("self", symbolIdForName("self")), - variable->name); - access->keyId = variable->nameId; - access->sourceSpan = variable->sourceSpan; - return access; - } - return expression; - } - const auto baseName = variable->name.substr(0, dot); - if (!visible.contains(symbolIdForName(baseName))) - return expression; - std::shared_ptr result = - std::make_shared(baseName, symbolIdForName(baseName)); - result->sourceSpan = variable->sourceSpan; - std::size_t begin = dot + 1; - while (begin < variable->name.size()) { - const auto next = variable->name.find('.', begin); - const auto key = variable->name.substr( - begin, next == std::string::npos ? std::string::npos : next - begin); - if (key.empty()) - return expression; - auto access = std::make_shared(std::move(result), key); - access->sourceSpan = variable->sourceSpan; - result = std::move(access); - if (next == std::string::npos) - break; - begin = next + 1; - } - return result; - } - if (const auto array = std::dynamic_pointer_cast(expression)) { - for (auto &item : array->items) - item = resolveScopedAccess(item, visible, implicitFields); - } else if (const auto map = std::dynamic_pointer_cast(expression)) { - for (auto &item : map->entries) - item.value = resolveScopedAccess(item.value, visible, implicitFields); - } else if (const auto access = - std::dynamic_pointer_cast(expression)) { - access->target = resolveScopedAccess(access->target, visible, implicitFields); - } else if (const auto term = - std::dynamic_pointer_cast(expression)) { - for (auto &argument : term->args) - argument.value = resolveScopedAccess(argument.value, visible, implicitFields); - const auto dot = term->name.rfind('.'); - const auto firstDot = term->name.find('.'); - if (dot != std::string::npos && - visible.contains(symbolIdForName(term->name.substr(0, firstDot)))) { - const auto operation = builtinIdForName("array:" + term->name.substr(dot + 1)); - if (operation == BuiltinId::ArrayGet || operation == BuiltinId::ArrayLen || - operation == BuiltinId::ArrayPush) { - auto receiver = std::make_shared(term->name.substr(0, dot)); - receiver->sourceSpan = term->sourceSpan; - auto arguments = term->args; - arguments.insert(arguments.begin(), Arg("data", - resolveScopedAccess(receiver, visible, implicitFields))); - auto result = std::make_shared(builtinName(operation), - std::move(arguments), operation); - result->sourceSpan = term->sourceSpan; - return result; - } - } - } else if (const auto operation = - std::dynamic_pointer_cast(expression)) { - std::shared_ptr rewritten; - if (operation->coreOperator == CoreOperator::Unknown) { - std::vector captures; - captures.reserve(operation->captureCount()); - for (std::size_t index = 0; index < operation->captureCount(); ++index) { - captures.emplace_back( - std::string(operation->captureName(index)), - resolveScopedAccess(operation->capture(index), visible, - implicitFields)); - } - rewritten = std::make_shared( - operation->operatorId, operation->patternId, std::move(captures), - operation->explicitlyGrouped, operation->resolvedMethodId); - } else if (operation->captureCount() == 1) { - rewritten = std::make_shared( - operation->coreOperator, - resolveScopedAccess(operation->capture(0), visible, implicitFields)); - } else { - rewritten = std::make_shared( - operation->coreOperator, - resolveScopedAccess(operation->capture(0), visible, implicitFields), - resolveScopedAccess(operation->capture(1), visible, implicitFields)); - } - rewritten->module = operation->module; - rewritten->sourceSpan = operation->sourceSpan; - return rewritten; - } - return expression; -} - -// Rewrites every free-variable reference in a fact-query predicate body (any -// VarExpr other than the row parameter itself) into a read from the -// synthesized callback's captures map, and records each one captured -// (deduplicated, first-seen order) into `captured`. Used by -// FactDmlLowerer::iteration() -- see the comment there for why this -// exists. Mirrors resolveScopedAccess's traversal shape immediately above. -std::shared_ptr substituteCaptures( - const std::shared_ptr &expression, const std::string &rowParameter, - SymbolId rowParameterId, const std::string &capturesVariable, - SymbolId capturesVariableId, - std::vector> &captured, - std::unordered_set &capturedIds) { - if (!expression) - return expression; - if (const auto variable = std::dynamic_pointer_cast(expression)) { - if (variable->nameId == rowParameterId || variable->nameId == 0) - return expression; - // This compiler pass runs before resolveScopedAccess ever splits a - // dotted name into an AccessExpr chain (see that function above), so the - // row parameter's own field access (`s.students`) still arrives here as - // one VarExpr spelled "s.students", not yet AccessExpr(s, "students"). - // Recognize that shape by name prefix and leave it untouched -- only - // resolveScopedAccess is allowed to decide it means field access, this - // pass must not misread it as a free variable named "s.students". - if (variable->name.size() > rowParameter.size() && - variable->name.compare(0, rowParameter.size(), rowParameter) == 0 && - variable->name[rowParameter.size()] == '.') { - return expression; - } - if (capturedIds.insert(variable->nameId).second) - captured.emplace_back(variable->name, variable->nameId); - auto access = std::make_shared( - std::make_shared(capturesVariable, capturesVariableId), - variable->name); - access->keyId = variable->nameId; - access->sourceSpan = variable->sourceSpan; - return access; - } - const auto recurse = [&](const std::shared_ptr &child) { - return substituteCaptures(child, rowParameter, rowParameterId, - capturesVariable, capturesVariableId, captured, - capturedIds); - }; - if (const auto array = std::dynamic_pointer_cast(expression)) { - for (auto &item : array->items) - item = recurse(item); - } else if (const auto map = std::dynamic_pointer_cast(expression)) { - for (auto &item : map->entries) - item.value = recurse(item.value); - } else if (const auto access = - std::dynamic_pointer_cast(expression)) { - // The row parameter's own fields (r.from) stay untouched: substitution - // only ever replaces the target, and the row VarExpr itself is excluded - // above, so `r.from` recurses into `r` (unchanged) then stops. - access->target = recurse(access->target); - } else if (const auto term = - std::dynamic_pointer_cast(expression)) { - for (auto &argument : term->args) - argument.value = recurse(argument.value); - } else if (const auto operation = - std::dynamic_pointer_cast(expression)) { - std::shared_ptr rewritten; - if (operation->coreOperator == CoreOperator::Unknown) { - std::vector captures; - captures.reserve(operation->captureCount()); - for (std::size_t index = 0; index < operation->captureCount(); ++index) { - captures.emplace_back(std::string(operation->captureName(index)), - recurse(operation->capture(index))); - } - rewritten = std::make_shared( - operation->operatorId, operation->patternId, std::move(captures), - operation->explicitlyGrouped, operation->resolvedMethodId); - } else if (operation->captureCount() == 1) { - rewritten = std::make_shared( - operation->coreOperator, recurse(operation->capture(0))); - } else { - rewritten = std::make_shared( - operation->coreOperator, recurse(operation->capture(0)), - recurse(operation->capture(1))); - } - rewritten->module = operation->module; - rewritten->sourceSpan = operation->sourceSpan; - return rewritten; - } - return expression; -} - -void resolveScopedAccessesInGoals(std::vector> &goals, - std::unordered_set visible, - const std::unordered_set *implicitFields = nullptr) { - for (auto &goal : goals) { - const auto expression = [&](std::shared_ptr value) { - return resolveScopedAccess(value, visible, implicitFields); - }; - const auto call = [&](Call &value) { - // Calls used as statements share receiver and argument resolution with - // calls used as values; they must not retain a separate dotted-name path. - auto term = std::make_shared(value.name, value.nameId, - value.args, value.builtinId); - term->sourceSpan = value.sourceSpan; - const auto resolved = std::static_pointer_cast(expression(term)); - value.name = resolved->name; - value.nameId = resolved->nameId; - value.builtinId = resolved->builtinId; - value.args = std::move(resolved->args); - }; - if (const auto called = std::dynamic_pointer_cast(goal)) { - call(called->call); - } else if (const auto negated = std::dynamic_pointer_cast(goal)) { - call(negated->call); - } else if (const auto assignment = - std::dynamic_pointer_cast(goal)) { - assignment->expr = - expression(assignment->expr); - visible.insert(assignment->nameId); - } else if (const auto assignment = - std::dynamic_pointer_cast(goal)) { - assignment->expr = expression(assignment->expr); - for (const auto &target : assignment->targets) - visible.insert(target.nameId); - } else if (const auto returned = - std::dynamic_pointer_cast(goal)) { - for (auto &field : returned->fields) - field.value = resolveScopedAccess(field.value, visible, implicitFields); - } else if (const auto binary = - std::dynamic_pointer_cast(goal)) { - binary->left = expression(binary->left); - binary->right = expression(binary->right); - } else if (const auto where = - std::dynamic_pointer_cast(goal)) { - std::vector> condition{where->condition}; - resolveScopedAccessesInGoals(condition, visible, implicitFields); - where->condition = condition.front(); - } else if (const auto conditional = - std::dynamic_pointer_cast(goal)) { - std::vector> condition{conditional->condition}; - resolveScopedAccessesInGoals(condition, visible, implicitFields); - conditional->condition = condition.front(); - resolveScopedAccessesInGoals(conditional->thenBranch, visible, - implicitFields); - resolveScopedAccessesInGoals(conditional->elseBranch, visible, - implicitFields); - } else if (const auto group = - std::dynamic_pointer_cast(goal)) { - resolveScopedAccessesInGoals(group->goals, visible, implicitFields); - } else if (const auto alternatives = - std::dynamic_pointer_cast(goal)) { - for (auto &branch : alternatives->branches) - resolveScopedAccessesInGoals(branch, visible, implicitFields); - } - } -} - -// Annotated mixfix/overload methods may declare their capture bindings in the -// operator annotation rather than repeat them in the callable head. They are -// still ordinary procedure parameters in IR: this helper gives lowering one -// canonical parameter list for both forms. -std::vector procedureParameters(const ClauseStmt &method) { - std::vector parameters; - parameters.reserve(method.head.args.size()); - for (const auto ¶meter : method.head.args) { - if (parameter.name.empty() || parameter.nameId == 0) { - throw IntegerParserError( - "not yet lowered to IR: invalid procedure parameter"); - } - if (std::find(parameters.begin(), parameters.end(), parameter.nameId) != - parameters.end()) { - throw IntegerParserError( - "not yet lowered to IR: duplicate procedure parameter"); - } - parameters.push_back(parameter.nameId); - } - if (!parameters.empty()) - return parameters; - - for (const auto &annotation : method.annotations) { - if (annotation.builtinId != BuiltinId::MixfixAnnotation && - annotation.builtinId != BuiltinId::OverloadAnnotation) - continue; - const auto parsed = decodeOperatorAnnotation(annotation); - if (parsed.captures.empty()) - continue; - for (const auto &capture : parsed.captures) { - if (capture.nameId == 0 || - std::find(parameters.begin(), parameters.end(), capture.nameId) != - parameters.end()) { - throw IntegerParserError( - "not yet lowered to IR: invalid annotated capture parameter"); - } - parameters.push_back(capture.nameId); - } - return parameters; - } - return parameters; -} - -// The strict module compiler is intentionally closed: every emitted -// LoadSymbol/Call must resolve through typed module globals or procedures. -// No instruction can reconstruct an AST value or invoke Interpreter services. -bool isDirectDeterministicExpression( - const std::shared_ptr &expression, - const std::unordered_set &definedSymbols, - const DirectCompileContext &context) { - if (!expression) - return false; - if (std::dynamic_pointer_cast(expression) || - std::dynamic_pointer_cast(expression) || - std::dynamic_pointer_cast(expression) || - std::dynamic_pointer_cast(expression)) { - return true; - } - if (const auto array = std::dynamic_pointer_cast(expression)) { - return std::all_of( - array->items.begin(), array->items.end(), [&](const auto &item) { - return isDirectDeterministicExpression(item, definedSymbols, context); - }); - } - if (const auto map = std::dynamic_pointer_cast(expression)) { - return std::all_of(map->entries.begin(), map->entries.end(), - [&](const MapEntry &entry) { - return isDirectDeterministicExpression( - entry.value, definedSymbols, context); - }); - } - if (const auto access = std::dynamic_pointer_cast(expression)) { - return isDirectDeterministicExpression(access->target, definedSymbols, - context); - } - if (const auto operation = - std::dynamic_pointer_cast(expression)) { - if (operation->coreOperator == CoreOperator::Then) { - if (operation->captureCount() != 2 || - !isDirectDeterministicExpression(operation->capture(0), - definedSymbols, context)) { - return false; - } - auto pipelineSymbols = definedSymbols; - pipelineSymbols.insert(symbolIdForName("system.result")); - return isDirectDeterministicExpression(operation->capture(1), - pipelineSymbols, context); - } - if (operation->coreOperator == CoreOperator::Unknown && - (operation->resolvedMethodId == 0 || - !context.procedures.contains(operation->resolvedMethodId))) - return false; - for (std::size_t index = 0; index < operation->captureCount(); ++index) { - if (!isDirectDeterministicExpression(operation->capture(index), - definedSymbols, context)) - return false; - } - return true; - } - if (const auto variable = std::dynamic_pointer_cast(expression)) { - return definedSymbols.contains(variable->nameId); - } - if (const auto term = std::dynamic_pointer_cast(expression)) { - if (term->name == "__fact:where" && term->args.size() == 2) { - const auto type = - std::dynamic_pointer_cast(term->args[0].value); - return type && context.factTypes.contains(type->nameId) && - static_cast( - std::dynamic_pointer_cast(term->args[1].value)) && - isDirectDeterministicExpression(term->args[1].value, - definedSymbols, context); - } - if (const auto operation = numericOperationForName(term->name); - operation && term->args.size() == numericOperationArity(*operation) && - std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return argument.name.empty() && - isDirectDeterministicExpression( - argument.value, definedSymbols, context); - })) { - return true; - } - // csv.toFacts has two declared core/csv.fx arities (with/without a - // source path for automatic mutation persistence -- see - // RegisterVm.cpp's csv.toFacts dispatch, which already handles both at - // runtime). builtinOperationArity is one fixed value per BuiltinId, so - // it cannot itself express "2 or 3"; this is the one deliberate - // exception, not a general variable-arity mechanism. - if (term->builtinId == BuiltinId::CsvToFacts && - (term->args.size() == 2 || term->args.size() == 3)) { - return std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return isDirectDeterministicExpression( - argument.value, definedSymbols, context); - }); - } - if (builtinOperationArity(term->builtinId)) { - std::vector names; - names.reserve(term->args.size()); - for (const auto &argument : term->args) - names.push_back(argument.name); - return builtinOperationArgumentOrder(term->builtinId, names) && - std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return isDirectDeterministicExpression( - argument.value, definedSymbols, context); - }); - } - if (const auto operation = tensorOperationForName(term->name)) { - std::vector names; - names.reserve(term->args.size()); - for (const auto &argument : term->args) - names.push_back(argument.name); - if (!tensorOperationArgumentOrder(*operation, names) || - !std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return isDirectDeterministicExpression( - argument.value, definedSymbols, context); - })) - return false; - return true; - } - if (const auto operation = numericOperationForName(term->name)) { - return term->args.size() == numericOperationArity(*operation) && - std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return argument.name.empty() && - isDirectDeterministicExpression( - argument.value, definedSymbols, context); - }); - } - if (term->name == "mod") { - return term->args.size() == 2 && - std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return argument.name.empty() && - isDirectDeterministicExpression( - argument.value, definedSymbols, context); - }); - } - if (semanticOperationForName(term->name)) { - return term->args.size() <= 255 && - std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return isDirectDeterministicExpression( - argument.value, definedSymbols, context); - }); - } - const bool fuzzyIntrinsic = - term->nameId == symbolIdForName("similarity") || - term->nameId == symbolIdForName("membership") || - term->nameId == symbolIdForName("isA") || - term->nameId == symbolIdForName("commonAncestors"); - if (fuzzyIntrinsic) { - const auto expected = - term->nameId == symbolIdForName("similarity") ? 2u : 2u; - return term->args.size() == expected && - std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return isDirectDeterministicExpression( - argument.value, definedSymbols, context); - }); - } - if (term->nameId == symbolIdForName("temporalRank")) { - return term->args.size() == 2 && - std::all_of( - term->args.begin(), term->args.end(), [](const Arg &argument) { - if (std::dynamic_pointer_cast(argument.value)) - return true; - const auto access = - std::dynamic_pointer_cast(argument.value); - return access && - static_cast(std::dynamic_pointer_cast( - access->target)); - }); - } - if (term->nameId == symbolIdForName("for_each_fact")) { - // The third argument (a captures map) is optional: only - // FactDmlLowerer::iteration()'s generated calls provide one, for - // predicates closing over an outer-scope value; a raw, hand-written - // for_each_fact(type, callback) call stays exactly as it was. - if (term->args.size() != 2 && term->args.size() != 3) - return false; - const auto type = std::dynamic_pointer_cast(term->args[0].value); - const auto callback = - std::dynamic_pointer_cast(term->args[1].value); - const bool declaredType = - type && context.factTypes.contains(type->nameId); - if (!declaredType || !callback || - !context.procedures.contains(callback->nameId)) { - return false; - } - return term->args.size() == 2 || - isDirectDeterministicExpression(term->args[2].value, - definedSymbols, context); - } - const bool hasNamedFields = - !term->args.empty() && - std::all_of(term->args.begin(), term->args.end(), - [](const Arg &argument) { return !argument.name.empty(); }); - // A capitalized, named term is an ordinary fact value even when its - // schema was not declared in this module. The parser preserves that - // distinction in TermExpr::isCapitalized; it is not a string heuristic - // or an alternate source parser. - const bool isFactValue = - context.factTypes.contains(term->nameId) || - (term->isCapitalized && term->name.find('.') == std::string::npos && - hasNamedFields); - const bool isProcedure = context.procedures.contains(term->nameId); - return (isProcedure || isFactValue) && - std::all_of(term->args.begin(), term->args.end(), - [&](const Arg &argument) { - return isDirectDeterministicExpression( - argument.value, definedSymbols, context); - }); - } - return false; // calls, lambdas, fact selections, and AST-only values -} - -const SourceSpan & -firstUnsupportedExpression(const std::shared_ptr &expression, - const std::unordered_set &definedSymbols, - const DirectCompileContext &context) { - if (!expression) { - static const SourceSpan unknown{}; - return unknown; - } - if (const auto array = std::dynamic_pointer_cast(expression)) { - for (const auto &item : array->items) { - if (!isDirectDeterministicExpression(item, definedSymbols, context)) - return firstUnsupportedExpression(item, definedSymbols, context); - } - } else if (const auto map = std::dynamic_pointer_cast(expression)) { - for (const auto &item : map->entries) { - if (!isDirectDeterministicExpression(item.value, definedSymbols, context)) - return firstUnsupportedExpression(item.value, definedSymbols, context); - } - } else if (const auto access = - std::dynamic_pointer_cast(expression)) { - if (!isDirectDeterministicExpression(access->target, definedSymbols, - context)) - return firstUnsupportedExpression(access->target, definedSymbols, - context); - } else if (const auto operation = - std::dynamic_pointer_cast(expression)) { - if (operation->coreOperator == CoreOperator::Then && - operation->captureCount() == 2) { - if (!isDirectDeterministicExpression(operation->capture(0), - definedSymbols, context)) { - return firstUnsupportedExpression(operation->capture(0), definedSymbols, - context); - } - auto pipelineSymbols = definedSymbols; - pipelineSymbols.insert(symbolIdForName("system.result")); - if (!isDirectDeterministicExpression(operation->capture(1), - pipelineSymbols, context)) { - return firstUnsupportedExpression(operation->capture(1), - pipelineSymbols, context); - } - return expression->sourceSpan; - } - if (operation->coreOperator == CoreOperator::Unknown && - (operation->resolvedMethodId == 0 || - !context.procedures.contains(operation->resolvedMethodId))) - return expression->sourceSpan; - for (std::size_t index = 0; index < operation->captureCount(); ++index) { - const auto captured = operation->capture(index); - if (!isDirectDeterministicExpression(captured, definedSymbols, context)) - return firstUnsupportedExpression(captured, definedSymbols, context); - } - } else if (const auto term = - std::dynamic_pointer_cast(expression)) { - if (builtinOperationArity(term->builtinId)) { - for (const auto &argument : term->args) { - if (!isDirectDeterministicExpression(argument.value, definedSymbols, - context)) - return firstUnsupportedExpression(argument.value, definedSymbols, - context); - } - return expression->sourceSpan; - } - if (tensorOperationForName(term->name)) { - for (const auto &argument : term->args) { - if (!isDirectDeterministicExpression(argument.value, definedSymbols, - context)) - return firstUnsupportedExpression(argument.value, definedSymbols, - context); - } - return expression->sourceSpan; - } - if (numericOperationForName(term->name) || term->name == "mod") { - for (const auto &argument : term->args) { - if (!argument.name.empty() || - !isDirectDeterministicExpression(argument.value, definedSymbols, - context)) { - return argument.value ? argument.value->sourceSpan - : expression->sourceSpan; - } - } - return expression->sourceSpan; - } - if (semanticOperationForName(term->name)) { - for (const auto &argument : term->args) { - if (!isDirectDeterministicExpression(argument.value, definedSymbols, - context)) - return firstUnsupportedExpression(argument.value, definedSymbols, - context); - } - return expression->sourceSpan; - } - if ((term->nameId == symbolIdForName("similarity") || - term->nameId == symbolIdForName("membership") || - term->nameId == symbolIdForName("isA") || - term->nameId == symbolIdForName("commonAncestors")) && - term->args.size() == 2) { - for (const auto &argument : term->args) { - if (!isDirectDeterministicExpression(argument.value, definedSymbols, - context)) - return firstUnsupportedExpression(argument.value, definedSymbols, - context); - } - return expression->sourceSpan; - } - if (term->nameId == symbolIdForName("temporalRank")) { - for (const auto &argument : term->args) { - if (!isDirectDeterministicExpression(argument.value, definedSymbols, - context)) { - return firstUnsupportedExpression(argument.value, definedSymbols, - context); - } - } - return expression->sourceSpan; - } - if (term->nameId == symbolIdForName("for_each_fact")) - return expression->sourceSpan; - const bool isProcedure = context.procedures.contains(term->nameId); - const bool isFactType = context.factTypes.contains(term->nameId); - if (!isProcedure && !isFactType) { - return expression->sourceSpan; - } - for (const auto &argument : term->args) { - if (!isDirectDeterministicExpression(argument.value, definedSymbols, - context)) - return firstUnsupportedExpression(argument.value, definedSymbols, - context); - } - } - return expression->sourceSpan; -} - -bool isDirectReturn(const std::shared_ptr &goal, - const std::unordered_set &definedSymbols, - const DirectCompileContext &context) { - const auto returned = std::dynamic_pointer_cast(goal); - return returned && std::all_of(returned->fields.begin(), - returned->fields.end(), [&](const Arg &field) { - return isDirectDeterministicExpression( - field.value, definedSymbols, context); - }); -} - -bool isDirectCondition(const std::shared_ptr &goal, - const std::unordered_set &definedSymbols, - const DirectCompileContext &context) { - const auto comparison = std::dynamic_pointer_cast(goal); - if (!comparison || - !isDirectDeterministicExpression(comparison->left, definedSymbols, - context) || - !isDirectDeterministicExpression(comparison->right, definedSymbols, - context)) - return false; - switch (comparison->op) { - case TokenId::EQUAL: - case TokenId::NOT_EQUAL: - case TokenId::LESS: - case TokenId::LESS_EQUAL: - case TokenId::GREATER: - case TokenId::GREATER_EQUAL: - return true; - default: - return false; - } -} - -bool isDirectGoalSequence(const std::vector> &goals, - std::unordered_set visible, - const DirectCompileContext &context) { - if (goals.empty()) - return false; - for (std::size_t index = 0; index + 1 < goals.size(); ++index) { - const auto assignment = std::dynamic_pointer_cast(goals[index]); - if (!assignment || !assignment->expr || - visible.contains(assignment->nameId) || - !isDirectDeterministicExpression(assignment->expr, visible, context)) - return false; - visible.insert(assignment->nameId); - } - if (isDirectReturn(goals.back(), visible, context)) - return true; - const auto conditional = std::dynamic_pointer_cast(goals.back()); - return conditional && - isDirectCondition(conditional->condition, visible, context) && - isDirectGoalSequence(conditional->thenBranch, visible, context) && - isDirectGoalSequence(conditional->elseBranch, visible, context); -} - -const SourceSpan & -firstUnsupportedGoalSequence(const std::vector> &goals, - std::unordered_set visible, - const DirectCompileContext &context) { - static const SourceSpan unknown{}; - if (goals.empty()) - return unknown; - for (std::size_t index = 0; index + 1 < goals.size(); ++index) { - const auto assignment = std::dynamic_pointer_cast(goals[index]); - if (!assignment || !assignment->expr || - visible.contains(assignment->nameId)) { - return goals[index] ? goals[index]->sourceSpan : unknown; - } - if (!isDirectDeterministicExpression(assignment->expr, visible, context)) { - return firstUnsupportedExpression(assignment->expr, visible, context); - } - visible.insert(assignment->nameId); - } - const auto returned = std::dynamic_pointer_cast(goals.back()); - if (!returned) { - const auto conditional = std::dynamic_pointer_cast(goals.back()); - if (!conditional) - return goals.back() ? goals.back()->sourceSpan : unknown; - if (!isDirectCondition(conditional->condition, visible, context)) - return conditional->condition ? conditional->condition->sourceSpan - : conditional->sourceSpan; - if (!isDirectGoalSequence(conditional->thenBranch, visible, context)) - return firstUnsupportedGoalSequence(conditional->thenBranch, visible, - context); - return firstUnsupportedGoalSequence(conditional->elseBranch, visible, - context); - } - for (const auto &field : returned->fields) { - if (!isDirectDeterministicExpression(field.value, visible, context)) { - return firstUnsupportedExpression(field.value, visible, context); - } - } - return returned->sourceSpan; -} - -const SourceSpan & -firstUnsupportedProcedure(const ClauseStmt &method, - const std::unordered_set &globals, - const DirectCompileContext &context) { - auto visible = globals; - for (const auto parameter : procedureParameters(method)) - visible.insert(parameter); - if (method.body.size() == 1) { - if (const auto conditional = - std::dynamic_pointer_cast(method.body.front())) { - if (!isDirectCondition(conditional->condition, visible, context)) { - const auto comparison = - std::dynamic_pointer_cast(conditional->condition); - if (comparison) { - if (!isDirectDeterministicExpression(comparison->left, visible, - context)) - return firstUnsupportedExpression(comparison->left, visible, - context); - if (!isDirectDeterministicExpression(comparison->right, visible, - context)) - return firstUnsupportedExpression(comparison->right, visible, - context); - } - return conditional->condition ? conditional->condition->sourceSpan - : method.sourceSpan; - } - if (!isDirectGoalSequence(conditional->thenBranch, visible, context)) - return firstUnsupportedGoalSequence(conditional->thenBranch, visible, - context); - return firstUnsupportedGoalSequence(conditional->elseBranch, visible, - context); - } - } - return firstUnsupportedGoalSequence(method.body, std::move(visible), context); -} - -bool isDirectBody(const ClauseStmt &method, - const std::unordered_set &visible, - const DirectCompileContext &context) { - if (method.body.empty() || !method.fallbackBranches.empty()) - return false; - if (method.body.size() == 1 && - isDirectReturn(method.body.front(), visible, context)) - return true; - if (method.body.size() == 1) { - const auto conditional = - std::dynamic_pointer_cast(method.body.front()); - return conditional && - isDirectCondition(conditional->condition, visible, context) && - isDirectGoalSequence(conditional->thenBranch, visible, context) && - isDirectGoalSequence(conditional->elseBranch, visible, context); - } - return isDirectGoalSequence(method.body, visible, context); -} - -bool isDirectEntry(const ClauseStmt &method, - const std::unordered_set &definedSymbols, - const DirectCompileContext &context) { - return method.head.nameId == symbolIdForName("main") && - method.head.args.empty() && - isDirectBody(method, definedSymbols, context); -} - -bool isDirectProcedure(const ClauseStmt &method, - const std::unordered_set &globals, - const DirectCompileContext &context) { - auto visible = globals; - for (const auto parameter : procedureParameters(method)) { - if (!visible.insert(parameter).second) - return false; - } - return isDirectBody(method, visible, context); -} - -// Each frontend lowering fragment owns its tables and registers. This linker -// preserves canonical integer IR while rebasing every table/register/jump -// operand; it never reuses AST nodes at runtime. Instruction decoding below -// checks local widths while the one final module verifier owns semantic and -// control-flow validation, avoiding repeated whole-fragment verification. -void appendFragment(FelidaeIr &target, FelidaeIr fragment, - bool dropTerminalReturn, bool dropTerminalEnd = false) { - if (dropTerminalReturn) { - if (fragment.words.size() < 4 || - fragment.words[fragment.words.size() - 4] != - static_cast(IrOpcode::Return) || - fragment.words.back() != static_cast(IrOpcode::End)) { - throw IntegerParserError("IR fragment does not have a terminal return"); - } - fragment.words.resize(fragment.words.size() - 4); - } else if (dropTerminalEnd) { - if (fragment.words.empty() || - fragment.words.back() != static_cast(IrOpcode::End)) { - throw IntegerParserError("IR fragment is missing END"); - } - fragment.words.pop_back(); - } - const IrWord registerBase = target.registerCount; - const IrWord constantBase = target.constants.size(); - const IrWord textBase = target.texts.size(); - const IrWord symbolBase = target.symbols.size(); - const IrWord wordBase = target.words.size(); - for (std::size_t index = 0; index < fragment.constants.size(); ++index) { - auto constant = fragment.constants[index]; - if (constant.kind == IrConstantKind::Text) { - constant.value += textBase; - } - target.constants.push_back(constant); - } - target.texts.insert(target.texts.end(), fragment.texts.begin(), - fragment.texts.end()); - target.symbols.insert(target.symbols.end(), fragment.symbols.begin(), - fragment.symbols.end()); - auto reg = [&](IrWord &value) { value += registerBase; }; - auto symbol = [&](IrWord &value) { value += symbolBase; }; - for (std::size_t pc = 0; pc < fragment.words.size();) { - const auto opcode = static_cast(fragment.words[pc]); - std::size_t width = 0; - switch (opcode) { - case IrOpcode::End: - width = 1; - break; - case IrOpcode::Jump: - fragment.words[pc + 1] += wordBase; - width = 2; - break; - case IrOpcode::LoadConst: - reg(fragment.words[pc + 1]); - fragment.words[pc + 2] += constantBase; - width = 3; - break; - case IrOpcode::LoadSymbol: - reg(fragment.words[pc + 1]); - symbol(fragment.words[pc + 2]); - width = 3; - break; - case IrOpcode::StoreSymbol: - symbol(fragment.words[pc + 1]); - reg(fragment.words[pc + 2]); - width = 3; - break; - case IrOpcode::Move: - reg(fragment.words[pc + 1]); - reg(fragment.words[pc + 2]); - width = 3; - break; - case IrOpcode::JumpIfFalse: - reg(fragment.words[pc + 1]); - fragment.words[pc + 2] += wordBase; - width = 3; - break; - case IrOpcode::MakeFact: - reg(fragment.words[pc + 1]); - symbol(fragment.words[pc + 2]); - // Source ownership is a one-based text index (zero means in-memory). - if (fragment.words[pc + 3] != 0) - fragment.words[pc + 3] += textBase; - width = 4; - break; - case IrOpcode::FactWhere: - reg(fragment.words[pc + 1]); - symbol(fragment.words[pc + 2]); - reg(fragment.words[pc + 3]); - width = 4; - break; - case IrOpcode::Return: - reg(fragment.words[pc + 1]); - width = 3; - break; - case IrOpcode::Add: - case IrOpcode::Sub: - case IrOpcode::Mul: - case IrOpcode::Div: - case IrOpcode::Mod: - case IrOpcode::Similarity: - case IrOpcode::HierarchyIsA: - case IrOpcode::HierarchyCommonAncestors: - reg(fragment.words[pc + 1]); - reg(fragment.words[pc + 2]); - reg(fragment.words[pc + 3]); - width = 4; - break; - case IrOpcode::TemporalRank: - reg(fragment.words[pc + 1]); - symbol(fragment.words[pc + 2]); - symbol(fragment.words[pc + 3]); - width = 4; - break; - case IrOpcode::Membership: - for (std::size_t index = 1; index < 6; ++index) { - reg(fragment.words[pc + index]); - } - width = 6; - break; - case IrOpcode::Compare: - reg(fragment.words[pc + 1]); - reg(fragment.words[pc + 2]); - reg(fragment.words[pc + 3]); - width = 5; - break; - case IrOpcode::GetField: - reg(fragment.words[pc + 1]); - reg(fragment.words[pc + 2]); - symbol(fragment.words[pc + 3]); - width = 4; - break; - case IrOpcode::SetField: - reg(fragment.words[pc + 1]); - symbol(fragment.words[pc + 2]); - reg(fragment.words[pc + 3]); - width = 4; - break; - case IrOpcode::ForEachFact: - reg(fragment.words[pc + 1]); - symbol(fragment.words[pc + 2]); - symbol(fragment.words[pc + 3]); - reg(fragment.words[pc + 4]); - width = 5; - break; - case IrOpcode::FactJoin: - reg(fragment.words[pc + 1]); - reg(fragment.words[pc + 2]); - reg(fragment.words[pc + 3]); - reg(fragment.words[pc + 4]); - reg(fragment.words[pc + 5]); - reg(fragment.words[pc + 6]); - symbol(fragment.words[pc + 7]); - symbol(fragment.words[pc + 8]); - symbol(fragment.words[pc + 9]); - width = 10; - break; - case IrOpcode::Call: - case IrOpcode::Builtin: - case IrOpcode::SemanticEval: - case IrOpcode::Numeric: - case IrOpcode::Tensor: - case IrOpcode::MakeArray: { - reg(fragment.words[pc + 1]); - if (opcode == IrOpcode::Call) - symbol(fragment.words[pc + 2]); - const auto count = fragment.words[pc + 3]; - for (std::size_t index = 0; index < count; ++index) - reg(fragment.words[pc + 4 + index]); - width = 4 + count; - break; - } - case IrOpcode::CallNamed: - case IrOpcode::MakeMap: { - reg(fragment.words[pc + 1]); - if (opcode == IrOpcode::CallNamed) - symbol(fragment.words[pc + 2]); - const auto count = fragment.words[pc + 3]; - for (std::size_t index = 0; index < count; ++index) { - auto &key = fragment.words[pc + 4 + index * 2]; - if (opcode == IrOpcode::CallNamed) { - if (key != 0) - key += symbolBase; - } else - symbol(key); - reg(fragment.words[pc + 5 + index * 2]); - } - width = 4 + count * 2; - break; - } - case IrOpcode::Count: - throw IntegerParserError("IR fragment has an invalid opcode"); - } - pc += width; - } - for (auto entry : fragment.sourceMap) { - entry.instructionWord += wordBase; - target.sourceMap.push_back(std::move(entry)); - } - target.words.insert(target.words.end(), fragment.words.begin(), - fragment.words.end()); - target.registerCount += fragment.registerCount; -} - -void attachFactPersistenceSource(FelidaeIr &program, std::size_t wordBegin, - RegisterId result, IrWord sourceIndex) { - bool attached = false; - for (std::size_t pc = wordBegin; pc < program.words.size();) { - const auto opcode = static_cast(program.words[pc]); - if (opcode == IrOpcode::MakeFact && program.words[pc + 1] == result) { - if (attached) - throw IntegerParserError("fact IR has ambiguous source ownership"); - program.words[pc + 3] = sourceIndex; - attached = true; - } - pc += irInstructionWidth(program, pc); - } - if (!attached) - throw IntegerParserError("fact IR has no source-owning value"); -} - -CoreOperator directConditionOperator(TokenId::Id token) { - switch (token) { - case TokenId::EQUAL: - return CoreOperator::StrictEqual; - case TokenId::NOT_EQUAL: - return CoreOperator::StrictNotEqual; - case TokenId::LESS: - return CoreOperator::Less; - case TokenId::LESS_EQUAL: - return CoreOperator::LessEqual; - case TokenId::GREATER: - return CoreOperator::Greater; - case TokenId::GREATER_EQUAL: - return CoreOperator::GreaterEqual; - default: - throw IntegerParserError("condition has no direct IR comparison"); - } -} - -FelidaeIr compileDirectProcedure( - const ClauseStmt &method, const std::unordered_set &factTypes); - -FelidaeIr compileDirectConditionalEntry( - const ClauseStmt &method, const std::unordered_set &factTypes) { - const auto conditional = - std::dynamic_pointer_cast(method.body.front()); - const auto comparison = - std::dynamic_pointer_cast(conditional->condition); - auto expression = std::make_shared( - directConditionOperator(comparison->op), comparison->left, - comparison->right); - expression->sourceSpan = comparison->sourceSpan; - auto conditionIr = IrCodeGenerator::lowerExpression(expression, factTypes); - const auto conditionRegister = - conditionIr.words.at(conditionIr.words.size() - 3); - FelidaeIr result; - appendFragment(result, std::move(conditionIr), true); - const auto elseJump = result.words.size(); - result.words.insert( - result.words.end(), - {static_cast(IrOpcode::JumpIfFalse), conditionRegister, 0}); - ClauseStmt thenMethod(method.head, conditional->thenBranch); - appendFragment( - result, compileDirectProcedure(thenMethod, factTypes), - false, true); - const auto endJump = result.words.size(); - result.words.insert(result.words.end(), - {static_cast(IrOpcode::Jump), 0}); - const auto elseTarget = result.words.size(); - ClauseStmt elseMethod(method.head, conditional->elseBranch); - appendFragment( - result, compileDirectProcedure(elseMethod, factTypes), - false); - result.words[elseJump + 2] = elseTarget; - result.words[endJump + 1] = result.words.size() - 1; // the final END boundary - return result; -} - -FelidaeIr compileDirectSequentialEntry( - const ClauseStmt &method, const std::unordered_set &factTypes) { - FelidaeIr result; - for (std::size_t index = 0; index + 1 < method.body.size(); ++index) { - const auto assignment = - std::dynamic_pointer_cast(method.body[index]); - GlobalBindingStmt binding(assignment->name, assignment->expr); - binding.sourceSpan = assignment->sourceSpan; - appendFragment(result, - IrCodeGenerator::lowerGlobalBinding(binding, factTypes), - true); - } - // The final statement is not necessarily a return goal -- isDirectProcedure - // also accepts a trailing IfGoal after a run of assignments. Recurse into - // compileDirectProcedure, which already dispatches a single-statement body - // to compileDirectConditionalEntry when it's an IfGoal and to - // lowerEntryMethod (return-goal-only) otherwise, instead of assuming - // the return-goal case here and rejecting a compiler-approved program. - ClauseStmt returned(method.head, {method.body.back()}); - appendFragment( - result, compileDirectProcedure(returned, factTypes), - false); - return result; -} - -FelidaeIr compileDirectProcedure( - const ClauseStmt &method, const std::unordered_set &factTypes) { - if (method.body.size() == 1) { - if (std::dynamic_pointer_cast(method.body.front())) { - return compileDirectConditionalEntry(method, factTypes); - } - return IrCodeGenerator::lowerEntryMethod(method, factTypes); - } - return compileDirectSequentialEntry(method, factTypes); -} - -} // namespace - -FelidaeIr IrCodeGenerator::lowerExpression( - const std::shared_ptr &expression, - const std::unordered_set &factTypes) { - FelidaeIr ir; - const auto addNumber = [&](double number) { - ir.constants.push_back({IrConstantKind::Number, encodeIrNumber(number)}); - return static_cast(ir.constants.size() - 1); - }; - const auto addBoolean = [&](bool boolean) { - ir.constants.push_back({IrConstantKind::Boolean, boolean ? 1ull : 0ull}); - return static_cast(ir.constants.size() - 1); - }; - const auto addText = [&](const StringExpr &text) { - if (text.containsEscape) { - throw IntegerParserError("string literal cannot be lowered without its " - "original SentencePiece IDs"); - } - ir.texts.push_back(text.sentencePieceIds); - ir.constants.push_back( - {IrConstantKind::Text, static_cast(ir.texts.size() - 1)}); - return static_cast(ir.constants.size() - 1); - }; - const auto addNil = [&]() { - ir.constants.push_back({IrConstantKind::Nil, 0}); - return static_cast(ir.constants.size() - 1); - }; - std::optional pipelineResult; - const auto emitFactFields = - [&](RegisterId fact, - const std::vector> &fields) { - std::vector>> grouped; - std::unordered_map groupIndexes; - grouped.reserve(fields.size()); - groupIndexes.reserve(fields.size()); - for (const auto &[name, value] : fields) { - const auto [position, inserted] = - groupIndexes.emplace(name, grouped.size()); - if (inserted) - grouped.push_back({name, {value}}); - else - grouped[position->second].second.push_back(value); - } - for (const auto &[name, values] : grouped) { - RegisterId value = values.front(); - if (values.size() > 1) { - value = static_cast(ir.registerCount++); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::MakeArray), value, 0, - static_cast(values.size())}); - ir.words.insert(ir.words.end(), values.begin(), values.end()); - } - ir.symbols.push_back(name); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::SetField), fact, - static_cast(ir.symbols.size() - 1), value}); - } - }; - auto lower = [&](auto &&self, - const std::shared_ptr &value) -> RegisterId { - const auto emittedAt = ir.words.size(); - const auto result = static_cast(ir.registerCount++); - if (const auto number = std::dynamic_pointer_cast(value)) { - ir.words.insert(ir.words.end(), {static_cast(IrOpcode::LoadConst), - result, addNumber(number->value)}); - } else if (const auto boolean = - std::dynamic_pointer_cast(value)) { - ir.words.insert(ir.words.end(), {static_cast(IrOpcode::LoadConst), - result, addBoolean(boolean->value)}); - } else if (const auto text = std::dynamic_pointer_cast(value)) { - ir.words.insert(ir.words.end(), {static_cast(IrOpcode::LoadConst), - result, addText(*text)}); - } else if (std::dynamic_pointer_cast(value)) { - ir.words.insert(ir.words.end(), {static_cast(IrOpcode::LoadConst), - result, addNil()}); - } else if (const auto variable = - std::dynamic_pointer_cast(value)) { - if (variable->nameId == symbolIdForName("system.result")) { - if (!pipelineResult) { - throw IntegerParserError( - "system.result is available only on the right side of 'then'"); - } - ir.words.insert(ir.words.end(), {static_cast(IrOpcode::Move), - result, *pipelineResult}); - return result; - } - ir.symbols.push_back(variable->nameId); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::LoadSymbol), result, - static_cast(ir.symbols.size() - 1)}); - } else if (const auto term = std::dynamic_pointer_cast(value)) { - if (term->name == "__fact:where") { - if (term->args.size() != 2) - throw IntegerParserError("fact where lowering requires type and predicates"); - const auto type = - std::dynamic_pointer_cast(term->args[0].value); - const auto predicates = - std::dynamic_pointer_cast(term->args[1].value); - if (!type || !predicates) - throw IntegerParserError("fact where lowering received invalid operands"); - const auto predicateRegister = self(self, predicates); - ir.symbols.push_back(type->nameId); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::FactWhere), result, - static_cast(ir.symbols.size() - 1), - predicateRegister}); - } else if (term->builtinId == BuiltinId::CsvToFacts && - (term->args.size() == 2 || term->args.size() == 3)) { - // Mirrors the generic builtin-lowering block below, except the - // arity itself varies (2 or 3, matching the isDirectDeterministicExpression - // exception above) instead of being one fixed constant per - // BuiltinId, so it cannot reuse builtinOperationArity/ - // builtinOperationArgumentOrder as-is. - std::vector> ordered(term->args.size()); - for (const auto &argument : term->args) { - const std::optional index = - argument.name == "data" ? std::optional{0} - : argument.name == "type" ? std::optional{1} - : argument.name == "source" ? std::optional{2} - : std::nullopt; - if (!index || *index >= ordered.size() || ordered[*index]) { - throw IntegerParserError("csv.toFacts has invalid arguments"); - } - ordered[*index] = self(self, argument.value); - } - std::vector operands; - operands.reserve(ordered.size()); - for (const auto operand : ordered) - operands.push_back(*operand); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Builtin), result, - static_cast(term->builtinId), - static_cast(operands.size())}); - ir.words.insert(ir.words.end(), operands.begin(), operands.end()); - } else if (term->builtinId == BuiltinId::FactJoin) { - // Dedicated opcode, not the generic Builtin encoding: a join - // synthesizes a "Joined" fact with "left"/"right" fields whose - // names never appear in the source program, so the VM cannot reuse - // a runtime text encoder for them (RegisterVm stays decoder-only -- - // see FelidaeKnowledgeRuntime::joinFacts). Instead these three - // names are interned as ordinary compiler symbols here, exactly - // like ForEachFact's typeSymbol/callbackSymbol above; the - // CompilerFrontend module-symbol pass (compileProgramTextToIr) - // gives every such symbol a real SentencePiece encoding once, at - // compile time, and RegisterVm resolves them at dispatch time via - // resolveSymbol -- no runtime encodeText call. - if (term->args.size() != 5) - throw IntegerParserError("fact join requires five arguments"); - std::vector operands; - operands.reserve(5); - for (const auto &argument : term->args) - operands.push_back(self(self, argument.value)); - ir.symbols.push_back(symbolIdForName("Joined")); - const auto joinedTypeSymbol = - static_cast(ir.symbols.size() - 1); - ir.symbols.push_back(symbolIdForName("left")); - const auto joinedLeftSymbol = - static_cast(ir.symbols.size() - 1); - ir.symbols.push_back(symbolIdForName("right")); - const auto joinedRightSymbol = - static_cast(ir.symbols.size() - 1); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::FactJoin), result, - operands[0], operands[1], operands[2], operands[3], - operands[4], joinedTypeSymbol, joinedLeftSymbol, - joinedRightSymbol}); - } else if (const auto operation = numericOperationForName(term->name); - operation && - term->args.size() == numericOperationArity(*operation) && - std::all_of(term->args.begin(), term->args.end(), - [](const Arg &argument) { - return argument.name.empty(); - })) { - std::vector operands; - operands.reserve(term->args.size()); - for (const auto &argument : term->args) - operands.push_back(self(self, argument.value)); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Numeric), result, - static_cast(*operation), - static_cast(operands.size())}); - ir.words.insert(ir.words.end(), operands.begin(), operands.end()); - } else if (const auto arity = builtinOperationArity(term->builtinId)) { - std::vector names; - names.reserve(term->args.size()); - for (const auto &argument : term->args) - names.push_back(argument.name); - const auto order = - builtinOperationArgumentOrder(term->builtinId, names); - if (!order) - throw IntegerParserError(term->name + - " has invalid builtin arguments"); - std::vector> ordered(*arity); - for (std::size_t index = 0; index < term->args.size(); ++index) - ordered[(*order)[index]] = self(self, term->args[index].value); - std::vector operands; - operands.reserve(*arity); - for (const auto operand : ordered) { - if (!operand) - throw IntegerParserError(term->name + " omits a builtin argument"); - operands.push_back(*operand); - } - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Builtin), result, - static_cast(term->builtinId), - static_cast(operands.size())}); - ir.words.insert(ir.words.end(), operands.begin(), operands.end()); - } else if (const auto operation = tensorOperationForName(term->name)) { - const auto arity = tensorOperationArity(*operation); - std::vector names; - names.reserve(term->args.size()); - for (const auto &argument : term->args) - names.push_back(argument.name); - const auto order = tensorOperationArgumentOrder(*operation, names); - if (!order) - throw IntegerParserError(term->name + - " has invalid tensor arguments"); - std::vector> ordered(arity); - for (std::size_t index = 0; index < arity; ++index) { - const auto &argument = term->args[index]; - ordered[(*order)[index]] = self(self, argument.value); - } - std::vector operands; - operands.reserve(arity); - for (const auto operand : ordered) { - if (!operand) - throw IntegerParserError(term->name + " omits a tensor argument"); - operands.push_back(*operand); - } - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Tensor), result, - static_cast(*operation), - static_cast(operands.size())}); - ir.words.insert(ir.words.end(), operands.begin(), operands.end()); - } else if (const auto operation = numericOperationForName(term->name)) { - const auto arity = numericOperationArity(*operation); - if (term->args.size() != arity || - std::any_of( - term->args.begin(), term->args.end(), - [](const Arg &argument) { return !argument.name.empty(); })) { - throw IntegerParserError(term->name + " requires exactly " + - std::to_string(arity) + - " positional numeric arguments"); - } - std::vector operands; - operands.reserve(arity); - for (const auto &argument : term->args) - operands.push_back(self(self, argument.value)); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Numeric), result, - static_cast(*operation), - static_cast(operands.size())}); - ir.words.insert(ir.words.end(), operands.begin(), operands.end()); - } else if (term->name == "mod") { - if (term->args.size() != 2 || - std::any_of( - term->args.begin(), term->args.end(), - [](const Arg &argument) { return !argument.name.empty(); })) { - throw IntegerParserError( - "mod requires exactly two positional numeric arguments"); - } - const auto left = self(self, term->args[0].value); - const auto right = self(self, term->args[1].value); - ir.words.insert(ir.words.end(), {static_cast(IrOpcode::Mod), - result, left, right}); - } else if (const auto operation = semanticOperationForName(term->name)) { - if (term->args.size() > 255) - throw IntegerParserError("semantic operation has too many inputs"); - std::vector inputs; - inputs.reserve(term->args.size()); - for (const auto &argument : term->args) - inputs.push_back(self(self, argument.value)); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::SemanticEval), result, - static_cast(*operation), - static_cast(inputs.size())}); - ir.words.insert(ir.words.end(), inputs.begin(), inputs.end()); - } else if (term->nameId == symbolIdForName("for_each_fact")) { - // The third argument (a captures map) is optional -- see the - // isDirectDeterministicExpression case above and - // FactDmlLowerer::iteration() in this file. A raw two-argument - // call gets an empty map so IrOpcode::ForEachFact's fifth operand - // (see RegisterVm.cpp) is always a valid register either way. - if (term->args.size() != 2 && term->args.size() != 3) { - throw IntegerParserError( - "for_each_fact requires a fact type and callback"); - } - const auto type = - std::dynamic_pointer_cast(term->args[0].value); - const auto callback = - std::dynamic_pointer_cast(term->args[1].value); - const auto typeId = - type && factTypes.contains(type->nameId) ? type->nameId : 0; - if (!type || !callback || typeId == 0) { - throw IntegerParserError("for_each_fact requires a declared fact " - "type and deterministic callback"); - } - const std::shared_ptr capturesExpr = - term->args.size() == 3 - ? term->args[2].value - : std::make_shared(std::vector{}); - const auto capturesRegister = self(self, capturesExpr); - ir.symbols.push_back(typeId); - const auto typeSymbol = static_cast(ir.symbols.size() - 1); - ir.symbols.push_back(callback->nameId); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::ForEachFact), result, - typeSymbol, - static_cast(ir.symbols.size() - 1), - capturesRegister}); - } else if (term->nameId == symbolIdForName("similarity")) { - if (term->args.size() != 2) - throw IntegerParserError("similarity requires exactly two arguments"); - const auto left = self(self, term->args[0].value); - const auto right = self(self, term->args[1].value); - ir.words.insert( - ir.words.end(), - {static_cast(IrOpcode::Similarity), result, left, right}); - } else if (term->nameId == symbolIdForName("isA") || - term->nameId == symbolIdForName("commonAncestors")) { - if (term->args.size() != 2) { - throw IntegerParserError(term->name + - " requires exactly two hierarchy arguments"); - } - const auto left = self(self, term->args[0].value); - const auto right = self(self, term->args[1].value); - const auto opcode = - term->nameId == symbolIdForName("isA") ? IrOpcode::HierarchyIsA - : IrOpcode::HierarchyCommonAncestors; - ir.words.insert(ir.words.end(), - {static_cast(opcode), result, left, right}); - } else if (term->nameId == symbolIdForName("temporalRank")) { - if (term->args.size() != 2) { - throw IntegerParserError( - "temporalRank requires effective-at and priority field symbols"); - } - const auto fieldSymbol = [&](const Arg &argument) { - SymbolId fieldId = 0; - if (const auto field = - std::dynamic_pointer_cast(argument.value)) { - fieldId = field->nameId; - } else if (const auto access = std::dynamic_pointer_cast( - argument.value)) { - const auto scope = - std::dynamic_pointer_cast(access->target); - if (scope) - fieldId = symbolIdForName(scope->name + "." + access->key); - } - if (fieldId == 0) { - throw IntegerParserError( - "temporalRank fields must be symbol names"); - } - ir.symbols.push_back(fieldId); - return static_cast(ir.symbols.size() - 1); - }; - const auto effectiveAt = fieldSymbol(term->args[0]); - const auto priority = fieldSymbol(term->args[1]); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::TemporalRank), result, - effectiveAt, priority}); - } else if (term->nameId == symbolIdForName("membership")) { - if (term->args.size() != 2) - throw IntegerParserError( - "membership requires a value and named profile"); - const auto valueRegister = self(self, term->args[0].value); - const auto profile = self(self, term->args[1].value); - const auto field = [&](const char *name) { - const auto fieldRegister = - static_cast(ir.registerCount++); - ir.symbols.push_back(symbolIdForName(name)); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::GetField), - fieldRegister, profile, - static_cast(ir.symbols.size() - 1)}); - return fieldRegister; - }; - const auto peak = field("peak"); - const auto fadesIn = field("fades_in"); - const auto fadesOut = field("fades_out"); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Membership), result, - valueRegister, peak, fadesIn, fadesOut}); - } else { - std::vector arguments; - arguments.reserve(term->args.size()); - const bool hasNamedArguments = std::any_of( - term->args.begin(), term->args.end(), - [](const Arg &argument) { return !argument.name.empty(); }); - std::vector names; - names.reserve(term->args.size()); - for (const auto &argument : term->args) { - arguments.push_back(self(self, argument.value)); - if (hasNamedArguments && argument.name.empty()) { - names.push_back(0); - } else if (hasNamedArguments) { - ir.symbols.push_back(argument.nameId); - names.push_back(static_cast(ir.symbols.size())); - } - } - // Capitalized terms with named fields are first-class fact values - // even without a separately declared fact schema. The AST carries - // this grammar decision; lowering does not infer it from text. - const bool factValue = - factTypes.contains(term->nameId) || - (term->isCapitalized && term->name.find('.') == std::string::npos && - hasNamedArguments); - if (factValue) { - if (!hasNamedArguments) { - throw IntegerParserError("fact construction requires named fields"); - } - ir.symbols.push_back(term->nameId); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::MakeFact), result, - static_cast(ir.symbols.size() - 1), 0}); - std::vector> fields; - fields.reserve(arguments.size()); - for (std::size_t index = 0; index < arguments.size(); ++index) { - if (names[index] == 0) - throw IntegerParserError( - "fact construction requires named fields"); - fields.emplace_back(term->args[index].nameId, arguments[index]); - } - emitFactFields(result, fields); - } else { - ir.symbols.push_back(term->nameId); - if (!hasNamedArguments) { - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Call), result, - static_cast(ir.symbols.size() - 1), - static_cast(arguments.size())}); - ir.words.insert(ir.words.end(), arguments.begin(), arguments.end()); - } else { - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::CallNamed), result, - static_cast(ir.symbols.size() - 1), - static_cast(arguments.size())}); - for (std::size_t index = 0; index < arguments.size(); ++index) { - ir.words.push_back(names[index]); - ir.words.push_back(arguments[index]); - } - } - } - } - } else if (const auto array = std::dynamic_pointer_cast(value)) { - std::vector items; - items.reserve(array->items.size()); - for (const auto &item : array->items) - items.push_back(self(self, item)); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::MakeArray), result, 0, - static_cast(items.size())}); - ir.words.insert(ir.words.end(), items.begin(), items.end()); - } else if (const auto map = std::dynamic_pointer_cast(value)) { - std::vector> entries; - entries.reserve(map->entries.size()); - for (const auto &entry : map->entries) { - const auto item = self(self, entry.value); - entries.emplace_back(entry.keyId, item); - } - if (map->factType.empty()) { - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::MakeMap), result, 0, - static_cast(entries.size())}); - for (const auto &[field, item] : entries) { - ir.symbols.push_back(field); - ir.words.push_back(static_cast(ir.symbols.size() - 1)); - ir.words.push_back(item); - } - } else { - ir.symbols.push_back(symbolIdForName(map->factType)); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::MakeFact), result, - static_cast(ir.symbols.size() - 1), 0}); - emitFactFields(result, entries); - } - } else if (const auto access = - std::dynamic_pointer_cast(value)) { - const auto target = self(self, access->target); - ir.symbols.push_back(access->keyId); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::GetField), result, target, - static_cast(ir.symbols.size() - 1)}); - } else if (const auto operation = - std::dynamic_pointer_cast(value)) { - const auto core = operation->coreOperator; - if (core == CoreOperator::Unknown) { - if (operation->resolvedMethodId == 0) { - throw IntegerParserError( - "mixfix expression requires verified model target selection"); - } - std::vector arguments; - arguments.reserve(operation->captureCount()); - for (std::size_t index = 0; index < operation->captureCount(); - ++index) { - arguments.push_back(self(self, operation->capture(index))); - } - ir.symbols.push_back(operation->resolvedMethodId); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Call), result, - static_cast(ir.symbols.size() - 1), - static_cast(arguments.size())}); - ir.words.insert(ir.words.end(), arguments.begin(), arguments.end()); - } else if (core == CoreOperator::UnaryPlus) { - return self(self, operation->capture(0)); - } else if (core == CoreOperator::Then) { - if (operation->captureCount() != 2) { - throw IntegerParserError( - "then pipeline requires a left and right expression"); - } - const auto left = self(self, operation->capture(0)); - const auto previousPipelineResult = pipelineResult; - pipelineResult = left; - const auto right = self(self, operation->capture(1)); - pipelineResult = previousPipelineResult; - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Move), result, right}); - } else if (core == CoreOperator::UnaryMinus) { - const auto source = self(self, operation->capture(0)); - const auto zero = static_cast(ir.registerCount++); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::LoadConst), zero, - addNumber(0.0), static_cast(IrOpcode::Sub), - result, zero, source}); - } else if (core == CoreOperator::LogicalNot) { - const auto source = self(self, operation->capture(0)); - const auto trueConstant = addBoolean(true); - const auto falseConstant = addBoolean(false); - const auto branch = ir.words.size(); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::JumpIfFalse), source, 0, - static_cast(IrOpcode::LoadConst), result, - falseConstant, static_cast(IrOpcode::Jump), - 0}); - const auto falseTarget = ir.words.size(); - ir.words.insert( - ir.words.end(), - {static_cast(IrOpcode::LoadConst), result, trueConstant}); - const auto endTarget = ir.words.size(); - ir.words[branch + 2] = falseTarget; - ir.words[branch + 7] = endTarget; - } else if (core == CoreOperator::LogicalAnd || - core == CoreOperator::LogicalOr) { - const auto left = self(self, operation->capture(0)); - const auto trueConstant = addBoolean(true); - const auto falseConstant = addBoolean(false); - if (core == CoreOperator::LogicalAnd) { - const auto leftBranch = ir.words.size(); - ir.words.insert( - ir.words.end(), - {static_cast(IrOpcode::JumpIfFalse), left, 0}); - const auto right = self(self, operation->capture(1)); - const auto rightBranch = ir.words.size(); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::JumpIfFalse), right, 0, - static_cast(IrOpcode::LoadConst), result, - trueConstant, static_cast(IrOpcode::Jump), - 0}); - const auto falseTarget = ir.words.size(); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::LoadConst), result, - falseConstant}); - const auto endTarget = ir.words.size(); - ir.words[leftBranch + 2] = falseTarget; - ir.words[rightBranch + 2] = falseTarget; - ir.words[rightBranch + 7] = endTarget; - } else { - const auto leftBranch = ir.words.size(); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::JumpIfFalse), left, 0, - static_cast(IrOpcode::LoadConst), result, - trueConstant, static_cast(IrOpcode::Jump), - 0}); - const auto rightTarget = ir.words.size(); - const auto right = self(self, operation->capture(1)); - const auto rightBranch = ir.words.size(); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::JumpIfFalse), right, 0, - static_cast(IrOpcode::LoadConst), result, - trueConstant, static_cast(IrOpcode::Jump), - 0}); - const auto falseTarget = ir.words.size(); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::LoadConst), result, - falseConstant}); - const auto endTarget = ir.words.size(); - ir.words[leftBranch + 2] = rightTarget; - ir.words[leftBranch + 7] = endTarget; - ir.words[rightBranch + 2] = falseTarget; - ir.words[rightBranch + 7] = endTarget; - } - } else { - const auto left = self(self, operation->capture(0)); - const auto right = self(self, operation->capture(1)); - IrOpcode opcode; - IrComparison comparison = IrComparison::Equal; - switch (core) { - case CoreOperator::Add: - opcode = IrOpcode::Add; - break; - case CoreOperator::Subtract: - opcode = IrOpcode::Sub; - break; - case CoreOperator::Multiply: - opcode = IrOpcode::Mul; - break; - case CoreOperator::Divide: - opcode = IrOpcode::Div; - break; - case CoreOperator::Modulo: - opcode = IrOpcode::Mod; - break; - case CoreOperator::StrictEqual: - opcode = IrOpcode::Compare; - break; - case CoreOperator::StrictNotEqual: - opcode = IrOpcode::Compare; - comparison = IrComparison::NotEqual; - break; - case CoreOperator::Less: - opcode = IrOpcode::Compare; - comparison = IrComparison::Less; - break; - case CoreOperator::LessEqual: - opcode = IrOpcode::Compare; - comparison = IrComparison::LessEqual; - break; - case CoreOperator::Greater: - opcode = IrOpcode::Compare; - comparison = IrComparison::Greater; - break; - case CoreOperator::GreaterEqual: - opcode = IrOpcode::Compare; - comparison = IrComparison::GreaterEqual; - break; - default: - throw IntegerParserError("expression has no direct IR lowering yet"); - } - ir.words.insert(ir.words.end(), - {static_cast(opcode), result, left, right}); - if (opcode == IrOpcode::Compare) - ir.words.push_back(static_cast(comparison)); - } - } else { - throw IntegerParserError("expression has no direct IR lowering yet"); - } - const auto &span = value->sourceSpan; - ir.sourceMap.push_back(IrSourceMapEntry{ - emittedAt, - {span.startLine, span.startColumn, span.endLine, span.endColumn}}); - return result; - }; - const auto result = lower(lower, expression); - ir.words.insert(ir.words.end(), - {static_cast(IrOpcode::Return), result, 0, - static_cast(IrOpcode::End)}); -#ifndef NDEBUG - if (codegenTraceEnabled()) { - std::clog << "[felidae.codegen] action=lower_expression verified_ir_words=" - << ir.words.size() << " registers=" << ir.registerCount - << " constants=" << ir.constants.size() - << " symbols=" << ir.symbols.size() << '\n'; - } -#endif - return ir; -} - -FelidaeIr IrCodeGenerator::lowerGlobalBinding( - const GlobalBindingStmt &binding, - const std::unordered_set &factTypes) { - if (!binding.expr) - throw IntegerParserError("Global binding has no value expression"); - auto ir = lowerExpression(binding.expr, factTypes); - if (ir.words.size() < 4 || - ir.words[ir.words.size() - 4] != static_cast(IrOpcode::Return) || - ir.words.back() != static_cast(IrOpcode::End)) { - throw IntegerParserError("Expression IR is missing its terminal return"); - } - const auto result = ir.words[ir.words.size() - 3]; - ir.symbols.push_back(symbolIdForName(binding.name)); - const auto symbol = static_cast(ir.symbols.size() - 1); - ir.words.resize(ir.words.size() - 4); - ir.words.insert(ir.words.end(), - { - static_cast(IrOpcode::StoreSymbol), - symbol, - result, - static_cast(IrOpcode::LoadSymbol), - result, - symbol, - static_cast(IrOpcode::Return), - result, - 0, - static_cast(IrOpcode::End), - }); - const auto &span = binding.sourceSpan; - ir.sourceMap.push_back(IrSourceMapEntry{ - ir.words.size() - 10, - {span.startLine, span.startColumn, span.endLine, span.endColumn}}); - return ir; -} - -FelidaeIr IrCodeGenerator::lowerEntryMethod( - const ClauseStmt &method, const std::unordered_set &factTypes) { - if (method.body.size() != 1 || !method.fallbackBranches.empty()) { - throw IntegerParserError( - "Method has not reached direct entry IR lowering yet"); - } - const auto returned = - std::dynamic_pointer_cast(method.body.front()); - if (!returned) - throw IntegerParserError("Direct entry IR lowering requires a return goal"); - if (returned->fields.empty()) { - auto nil = std::make_shared(); - nil->sourceSpan = returned->sourceSpan; - return lowerExpression(nil, factTypes); - } - bool named = false; - for (const auto &field : returned->fields) - named = named || !field.name.empty(); - if (!named) { - if (returned->fields.size() != 1) { - throw IntegerParserError( - "Direct entry IR lowering requires one positional return value"); - } - return lowerExpression(returned->fields.front().value, factTypes); - } - std::vector entries; - entries.reserve(returned->fields.size()); - for (const auto &field : returned->fields) { - if (field.name.empty()) { - throw IntegerParserError("Direct entry IR lowering cannot mix named and " - "positional return fields"); - } - entries.emplace_back(field.name, field.nameId, field.value); - } - auto map = std::make_shared(std::move(entries)); - map->sourceSpan = returned->sourceSpan; - return lowerExpression(map, factTypes); -} - - -IrModule IrCodeGenerator::compile(Program program) const { - desugarWhereGuardedClauses(program); - lowerFactDml(program); - IrModule module; - // The strict compiler accepts only constructs that lower to verified IR. - // Unsupported constructs are rejected with a source span; there is no - // interpreter or compatibility execution path. - std::unordered_set directSymbols; - std::unordered_set procedureSymbols; - std::unordered_set factTypes; - std::unordered_map classSchemas; - for (const auto &declaration : program.classes) { - if (!declaration || declaration->name.empty() || - !factTypes.insert(declaration->nameId).second) { - throw IntegerParserError( - "duplicate or invalid class declaration at " + - std::to_string(declaration ? declaration->sourceSpan.startLine : 1) + - ":" + - std::to_string(declaration ? declaration->sourceSpan.startColumn : 1)); - } - classSchemas.emplace(declaration->nameId, declaration.get()); - } - for (const auto &clause : program.clauses) { - if (!clause) - continue; - const bool conflict = - clause->isFact() - ? procedureSymbols.contains(clause->head.nameId) - : factTypes.contains(clause->head.nameId) || - !procedureSymbols.insert(clause->head.nameId).second; - if (conflict) { - throw IntegerParserError( - "not yet lowered to IR: duplicate procedure declaration at " + - std::to_string(clause->sourceSpan.startLine) + ":" + - std::to_string(clause->sourceSpan.startColumn)); - } - // A fact predicate is a table and therefore may have any number of - // source rows. Only callable procedures are single declarations. - if (clause->isFact()) - factTypes.insert(clause->head.nameId); - } - - // A declared schema constrains source fact rows while runtime facts remain - // ordinary first-class maps. Inherited fields are resolved after the class - // hierarchy has been validated below. - std::function &, - std::unordered_set &)> - collectFields; - collectFields = [&](SymbolId type, std::unordered_set &result, - std::unordered_set &visiting) { - const auto schema = classSchemas.find(type); - if (schema == classSchemas.end()) - return; - if (!visiting.insert(type).second) - throw IntegerParserError("cyclic class hierarchy for '" + - schema->second->name + "'"); - for (const auto &parent : schema->second->parentNames) { - const auto parentId = symbolIdForName(parent); - if (!factTypes.contains(parentId)) - throw IntegerParserError("unknown class parent '" + parent + "'"); - collectFields(parentId, result, visiting); - } - for (const auto &field : schema->second->fields) - result.insert(field.nameId); - visiting.erase(type); - }; - for (const auto &clause : program.clauses) { - if (!clause || !clause->isFact() || - !classSchemas.contains(clause->head.nameId)) - continue; - std::unordered_set fields; - std::unordered_set visiting; - collectFields(clause->head.nameId, fields, visiting); - for (const auto &argument : clause->head.args) { - if (argument.name.empty() || !fields.contains(argument.nameId)) { - throw IntegerParserError( - "fact field '" + argument.name + "' is not declared by class '" + - clause->head.name + "' at " + - std::to_string(clause->sourceSpan.startLine) + ":" + - std::to_string(clause->sourceSpan.startColumn)); - } - } - } - std::unordered_map> classMethodFields; - for (const auto &declaration : program.classes) { - std::unordered_set fields; - std::unordered_set visiting; - collectFields(declaration->nameId, fields, visiting); - for (const auto &method : declaration->methods) - classMethodFields.emplace(method->head.nameId, fields); - std::set> uniqueIndexes; - for (const auto &index : declaration->indexes) { - if (std::any_of(index.fieldIds.begin(), index.fieldIds.end(), - [&](SymbolId field) { return !fields.contains(field); })) - throw IntegerParserError("class index references an undeclared field in '" + - declaration->name + "'"); - if (!uniqueIndexes.insert(index.fieldIds).second) - throw IntegerParserError("duplicate class index in '" + - declaration->name + "'"); - } - } - for (const auto &clause : program.clauses) { - if (!clause) - continue; - for (const auto &annotation : clause->annotations) { - const bool operatorAnnotation = - annotation.builtinId == BuiltinId::OverloadAnnotation || - annotation.builtinId == BuiltinId::MixfixAnnotation || - annotation.builtinId == BuiltinId::MatcherAnnotation; - if (!operatorAnnotation && - !procedureSymbols.contains(annotation.nameId)) { - throw IntegerParserError( - "unknown annotation '" + annotation.name + "' at " + - std::to_string(annotation.sourceSpan.startLine) + ":" + - std::to_string(annotation.sourceSpan.startColumn)); - } - } - } - // Module bindings form one immutable namespace. Reject collisions before - // IR generation so a valid-looking FELBIR cannot defer a scope error until VM - // execution. Procedure locals are checked separately against parameters - // and globals by isDirectProcedure/isDirectGoalSequence. - std::unordered_set globalSymbols; - for (const auto &binding : program.globals) { - if (!binding || binding->name.empty()) { - throw IntegerParserError( - "not yet lowered to IR: invalid global binding at " + - std::to_string(binding ? binding->sourceSpan.startLine : 1) + ":" + - std::to_string(binding ? binding->sourceSpan.startColumn : 1)); - } - const auto symbol = symbolIdForName(binding->name); - if (!globalSymbols.insert(symbol).second || - procedureSymbols.contains(symbol) || factTypes.contains(symbol)) { - throw IntegerParserError( - "not yet lowered to IR: duplicate or conflicting global binding at " + - std::to_string(binding->sourceSpan.startLine) + ":" + - std::to_string(binding->sourceSpan.startColumn)); - } - } - // Resolve fields after all module names and method parameters are known. - // This is compiler-local AST normalization; Form receives only the - // resulting GetField IR and retains no syntax dependency. - std::unordered_set lexicalGlobals; - for (auto &binding : program.globals) { - if (!binding) - continue; - binding->expr = resolveScopedAccess(binding->expr, lexicalGlobals); - lexicalGlobals.insert(symbolIdForName(binding->name)); - } - for (auto &clause : program.clauses) { - if (!clause || clause->isFact()) - continue; - auto visible = globalSymbols; - for (const auto parameter : procedureParameters(*clause)) - visible.insert(parameter); - const auto classFields = classMethodFields.find(clause->head.nameId); - resolveScopedAccessesInGoals( - clause->body, std::move(visible), - classFields == classMethodFields.end() ? nullptr : &classFields->second); - } - std::unordered_map factTypeIndexes; - for (const auto &declaration : program.classes) { - std::vector parents; - parents.reserve(declaration->parentNames.size()); - for (const auto &parent : declaration->parentNames) { - const auto parentSymbol = symbolIdForName(parent); - if (!factTypes.contains(parentSymbol)) - throw IntegerParserError("unknown class parent '" + parent + "'"); - parents.push_back(parentSymbol); - } - std::vector> indexes; - indexes.reserve(declaration->indexes.size()); - for (const auto &index : declaration->indexes) - indexes.emplace_back(index.fieldIds.begin(), index.fieldIds.end()); - factTypeIndexes.emplace(declaration->nameId, module.factTypes.size()); - module.factTypes.push_back( - {declaration->nameId, std::move(parents), std::move(indexes), - {declaration->sourceSpan.startLine, - declaration->sourceSpan.startColumn, - declaration->sourceSpan.endLine, declaration->sourceSpan.endColumn}}); - } - for (const auto &clause : program.clauses) { - if (!clause || !clause->isFact()) - continue; - std::vector parents; - for (const auto &parent : clause->parentNames) { - const auto parentSymbol = symbolIdForName(parent); - if (!factTypes.contains(parentSymbol)) { - throw IntegerParserError( - "not yet lowered to IR: unknown fact parent at " + - std::to_string(clause->sourceSpan.startLine) + ":" + - std::to_string(clause->sourceSpan.startColumn)); - } - parents.push_back(parentSymbol); - } - const auto existing = factTypeIndexes.find(clause->head.nameId); - if (existing == factTypeIndexes.end()) { - factTypeIndexes.emplace(clause->head.nameId, module.factTypes.size()); - module.factTypes.push_back( - {clause->head.nameId, - std::move(parents), - {}, - {clause->sourceSpan.startLine, clause->sourceSpan.startColumn, - clause->sourceSpan.endLine, clause->sourceSpan.endColumn}}); - } else if (!parents.empty() && - module.factTypes[existing->second].parents != parents) { - throw IntegerParserError( - "not yet lowered to IR: inconsistent fact hierarchy at " + - std::to_string(clause->sourceSpan.startLine) + ":" + - std::to_string(clause->sourceSpan.startColumn)); - } - } - const DirectCompileContext context{procedureSymbols, factTypes}; - // Builtin modules are compiler-known operation namespaces, not source or - // dynamic-library dependencies. Their imports therefore need no secondary - // parser/execution path. Other imports remain explicitly unsupported until - // they have a verified IR module-linking contract. - // - // This list previously omitted array/math/str/file/system even though - // every one of their declared calls (array.get, math:sqrt, str:upper, - // file.readFile, system.print, ...) already compiles and runs - // fine with no import statement at all -- an explicit `import "array"` - // (etc.) was the only thing that broke the file, rejecting an otherwise - // valid program. Names still absent here (process, http, gtk, qt, - // wordnet, plot, fact, fact_analysis, flibrary) route through the - // system_library_loader bridge, which has no implementation anywhere; - // allowlisting their import would let a file compile while its calls - // silently return nil, which is worse than the current explicit rejection. - const bool builtinImports = std::all_of( - program.imports.begin(), program.imports.end(), [](const auto &import) { - return import && - std::all_of(import->paths.begin(), import->paths.end(), - [](const std::string &path) { - return isBuiltinModuleName(path); - }); - }); - bool directGlobals = builtinImports && !program.clauses.empty(); - for (const auto &binding : program.globals) { - if (!binding || !isDirectDeterministicExpression(binding->expr, - directSymbols, context)) { - directGlobals = false; - break; - } - directSymbols.insert(symbolIdForName(binding->name)); - } - const auto main = std::find_if( - program.clauses.begin(), program.clauses.end(), [](const auto &clause) { - return clause && !clause->isFact() && - clause->head.nameId == symbolIdForName("main"); - }); - const bool eligibleMethods = std::all_of( - program.clauses.begin(), program.clauses.end(), [&](const auto &clause) { - return clause && - (clause->isFact() || - (clause->head.nameId == symbolIdForName("main") - ? isDirectEntry(*clause, directSymbols, context) - : isDirectProcedure(*clause, directSymbols, context))); - }); - if (directGlobals && main != program.clauses.end() && eligibleMethods && - isDirectEntry(**main, directSymbols, context)) { - // Globals must execute before fact rows: a fact field may read a global - // by name (e.g. Person(age: defaultAge)), which lowers to a LoadSymbol - // that requires the matching StoreSymbol to have already run. Global - // bindings never read a fact by name (facts are reached by type/query, - // not symbol lookup), so this order has no matching requirement the - // other way. - for (const auto &binding : program.globals) { - appendFragment(module.ir, - IrCodeGenerator::lowerGlobalBinding(*binding, factTypes), - true); - } - std::map persistenceSources; - for (const auto &clause : program.clauses) { - if (!clause || !clause->isFact() || clause->emptyDeclaration) - continue; - auto fact = std::make_shared( - clause->head.name, clause->head.nameId, clause->head.args, - clause->head.builtinId, true); - fact->sourceSpan = clause->sourceSpan; - if (!isDirectDeterministicExpression(fact, directSymbols, context)) { - throw IntegerParserError( - "not yet lowered to IR: non-deterministic fact row at " + - std::to_string(clause->sourceSpan.startLine) + ":" + - std::to_string(clause->sourceSpan.startColumn)); - } - auto factIr = IrCodeGenerator::lowerExpression(std::move(fact), factTypes); - if (factIr.words.size() < 4 || - factIr.words[factIr.words.size() - 4] != - static_cast(IrOpcode::Return)) { - throw IntegerParserError( - "fact IR fragment does not have a terminal return"); - } - const auto result = static_cast( - module.ir.registerCount + factIr.words[factIr.words.size() - 3]); - const auto wordBegin = module.ir.words.size(); - appendFragment(module.ir, std::move(factIr), true); - if (clause->persistenceSource && - !clause->persistenceSource->empty()) { - auto [source, inserted] = persistenceSources.try_emplace( - *clause->persistenceSource, 0); - if (inserted) { - const auto existing = - std::find(module.ir.texts.begin(), module.ir.texts.end(), - *clause->persistenceSource); - if (existing == module.ir.texts.end()) { - module.ir.texts.push_back(*clause->persistenceSource); - source->second = static_cast(module.ir.texts.size()); - } else { - source->second = static_cast( - std::distance(module.ir.texts.begin(), existing) + 1); - } - } - attachFactPersistenceSource(module.ir, wordBegin, result, - source->second); - } - } - for (const auto &clause : program.clauses) { - if (clause->isFact()) - continue; - const auto parameters = procedureParameters(*clause); - std::vector irParameters; - irParameters.reserve(parameters.size()); - for (const auto parameter : parameters) - irParameters.push_back(parameter); - const auto [_, inserted] = module.procedures.emplace( - clause->head.nameId, - IrProcedure{ - compileDirectProcedure(*clause, factTypes), - irParameters, - irParameters, - {clause->sourceSpan.startLine, clause->sourceSpan.startColumn, - clause->sourceSpan.endLine, clause->sourceSpan.endColumn}}); - if (!inserted) - throw IntegerParserError("duplicate direct IR procedure"); - } - const auto entryRegister = static_cast(module.ir.registerCount++); - module.entryProcedure = (*main)->head.nameId; - module.ir.symbols.push_back((*main)->head.nameId); - const auto entrySymbol = static_cast(module.ir.symbols.size() - 1); - module.ir.words.insert(module.ir.words.end(), - { - static_cast(IrOpcode::Call), - entryRegister, - entrySymbol, - 0, - static_cast(IrOpcode::Return), - entryRegister, - 0, - static_cast(IrOpcode::End), - }); - const auto &span = (*main)->sourceSpan; - module.ir.sourceMap.push_back(IrSourceMapEntry{ - module.ir.words.size() - 8, - {span.startLine, span.startColumn, span.endLine, span.endColumn}}); - return module; - } - SourceSpan span; - bool foundUnsupportedSpan = false; - for (const auto &binding : program.globals) { - if (!binding || !isDirectDeterministicExpression(binding->expr, - directSymbols, context)) { - span = binding && binding->expr - ? firstUnsupportedExpression(binding->expr, directSymbols, - context) - : SourceSpan{}; - foundUnsupportedSpan = true; - break; - } - } - if (!foundUnsupportedSpan) { - for (const auto &clause : program.clauses) { - const auto eligible = - clause && - (clause->isFact() || - (clause->head.nameId == symbolIdForName("main") - ? isDirectEntry(*clause, directSymbols, context) - : isDirectProcedure(*clause, directSymbols, context))); - if (!eligible) { - span = clause - ? firstUnsupportedProcedure(*clause, directSymbols, context) - : SourceSpan{}; - foundUnsupportedSpan = true; - break; - } - } - } - if (!foundUnsupportedSpan && !program.statements.empty() && - program.statements.front()) { - span = program.statements.front()->sourceSpan; - } - throw IntegerParserError( - "not yet lowered to IR: unsupported module construct at " + - std::to_string(span.startLine) + ":" + std::to_string(span.startColumn)); -} - -} // namespace Felidae diff --git a/src/IrCodeGenerator.h b/src/IrCodeGenerator.h deleted file mode 100644 index a859128..0000000 --- a/src/IrCodeGenerator.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -// The syntax-shaped HIR is compiler-front-end input only. FelidaeIr and -// RegisterVm do not include this header and never receive HIR nodes. -#include "AST.h" -#include "form/IrModule.h" - -#include -#include - -namespace Felidae { - -class IrCodeGenerator { -public: - static FelidaeIr lowerExpression( - const std::shared_ptr &expression, - const std::unordered_set &factTypes = {}); - static FelidaeIr lowerGlobalBinding( - const GlobalBindingStmt &binding, - const std::unordered_set &factTypes = {}); - static FelidaeIr lowerEntryMethod( - const ClauseStmt &method, - const std::unordered_set &factTypes = {}); - IrModule compile(Program program) const; -}; - -} // namespace Felidae diff --git a/src/Memory.cpp b/src/Memory.cpp index 3d99d55..a112e84 100644 --- a/src/Memory.cpp +++ b/src/Memory.cpp @@ -1270,6 +1270,31 @@ void FactMemory::removeOrigin(const std::filesystem::path& origin) { compactInactiveIfSafe(); } +std::size_t FactMemory::deactivateFacts(const std::vector& indexes) { + ensureUnique(); + std::size_t changed = 0; + for (const size_t index : indexes) { + if (index >= data_->facts.size() || !data_->facts.at(index).active) continue; + deactivateFact(index); + ++changed; + } + if (changed != 0) { + ++data_->generation; + compactInactiveIfSafe(); + } + return changed; +} + +bool FactMemory::replaceFact(size_t index, std::shared_ptr value) { + if (index >= data_->facts.size() || !data_->facts.at(index).active || !value) return false; + const FactRecord previous = data_->facts.at(index); + deactivateFacts({index}); + addFact(previous.type, previous.parentType, std::move(value), previous.origin, + previous.id, previous.rowVersion + 1, previous.parentFactIds, + previous.designations); + return true; +} + bool FactMemory::isCompatibleType(const std::string& actual, const std::string& expected) const { return isCompatibleTypeInData(*data_, actual, expected); } diff --git a/src/Memory.h b/src/Memory.h index fdafee0..3eb245e 100644 --- a/src/Memory.h +++ b/src/Memory.h @@ -177,6 +177,11 @@ class FactMemory { std::vector factIndexesFromOrigin(const std::filesystem::path& origin) const; bool hasOrigin(const std::filesystem::path& origin) const; void removeOrigin(const std::filesystem::path& origin); + // Language-level mutations preserve stable fact identity. Updates append + // a new row version and retire the prior row; deletes retire rows without + // invalidating snapshots that still refer to their original catalog. + std::size_t deactivateFacts(const std::vector& indexes); + bool replaceFact(size_t index, std::shared_ptr value); bool isCompatibleType(const std::string& actual, const std::string& expected) const; const std::vector& compatibleFactIndexes(const std::string& type, SymbolId typeId = 0); const std::vector& propertyFactIndexes(const std::string& type, diff --git a/src/MixfixStateModel.cpp b/src/MixfixStateModel.cpp deleted file mode 100644 index 2b4b753..0000000 --- a/src/MixfixStateModel.cpp +++ /dev/null @@ -1,618 +0,0 @@ -#include "MixfixStateModel.h" -#include "ModelStore.h" - -#include -#include -#include -#include -#include - -#ifdef FELIDAE_HAS_TORCH -#include -#include -#include -#endif - -namespace Felidae { -namespace { - -IrWord resolveReference(IrWord index, const std::vector &table, - const char *name) { - if (index >= table.size()) { - throw IrError(std::string("mixfix GRU emitted invalid ") + name + - " reference"); - } - return table[index]; -} - -} // namespace - -MixfixContext makeMixfixContext(const FelidaeIr &shell) { - MixfixContext context; - context.maximumOutputWords = 4096; - context.outputVocabulary.push_back({MixfixIrTokenKind::Accept, 0}); - context.outputVocabulary.push_back({MixfixIrTokenKind::Reject, 0}); - context.outputVocabulary.push_back({MixfixIrTokenKind::Abstain, 0}); - context.outputVocabulary.push_back({MixfixIrTokenKind::End, 0}); - for (IrWord opcode = 1; opcode < kIrOpcodeCount; ++opcode) { - context.outputVocabulary.push_back({MixfixIrTokenKind::Opcode, opcode}); - } - for (IrWord index = 0; index < kMaximumMixfixRegisters; ++index) { - context.outputVocabulary.push_back({MixfixIrTokenKind::Register, index}); - } - for (IrWord index = 0; index < kMaximumMixfixReferences; ++index) { - context.outputVocabulary.push_back( - {MixfixIrTokenKind::ConstantReference, index}); - } - for (IrWord index = 0; index < kMaximumMixfixReferences; ++index) { - context.outputVocabulary.push_back( - {MixfixIrTokenKind::SymbolReference, index}); - } - for (IrWord index = 0; index < kMaximumMixfixReferences; ++index) { - context.outputVocabulary.push_back( - {MixfixIrTokenKind::FactReference, index}); - } - for (IrWord index = 0; index < kMaximumMixfixReferences; ++index) { - context.outputVocabulary.push_back( - {MixfixIrTokenKind::ProgramReference, index}); - } - for (IrWord index = 0; index < shell.constants.size(); ++index) - context.constantReferences.push_back(index); - for (IrWord index = 0; index < shell.symbols.size(); ++index) - context.symbolReferences.push_back(index); - return context; -} - -std::vector resolveMixfixIrTokens(std::span tokens, - const MixfixContext &context) { - if (context.maximumOutputWords == 0) - throw IrError("mixfix IR output limit is zero"); - if (tokens.empty()) - throw IrError( - "mixfix model emitted no ACCEPT, REJECT, or ABSTAIN decision"); - const auto contextSummary = [&] { - return "constants=" + std::to_string(context.constantReferences.size()) + - ", symbols=" + std::to_string(context.symbolReferences.size()) + - ", facts=" + std::to_string(context.factReferences.size()) + - ", programs=" + std::to_string(context.programReferences.size()); - }; - if (tokens.front().kind == MixfixIrTokenKind::Reject) { - throw IrError("mixfix model rejected the input (" + contextSummary() + - "); it does not match a learned valid mixfix form"); - } - if (tokens.front().kind == MixfixIrTokenKind::Abstain) { - throw IrError( - "mixfix model found no unique safe target (" + contextSummary() + - "); declare a deterministic overload or retrain with this form"); - } - if (tokens.front().kind != MixfixIrTokenKind::Accept) - throw IrError( - "mixfix model output must begin with ACCEPT, REJECT, or ABSTAIN"); - std::vector words; - words.reserve(std::min(tokens.size(), context.maximumOutputWords)); - for (const auto &token : tokens.subspan(1)) { - if (token.kind == MixfixIrTokenKind::End) { - words.push_back(static_cast(IrOpcode::End)); - return words; - } - if (words.size() >= context.maximumOutputWords) { - throw IrError("mixfix GRU exceeded its bounded decoder output"); - } - switch (token.kind) { - case MixfixIrTokenKind::Accept: - case MixfixIrTokenKind::Reject: - case MixfixIrTokenKind::Abstain: - throw IrError("mixfix model emitted a decision token inside compiler IR"); - case MixfixIrTokenKind::Opcode: - if (token.value >= kIrOpcodeCount) { - throw IrError("mixfix GRU emitted invalid IR opcode"); - } - words.push_back(token.value); - break; - case MixfixIrTokenKind::Register: - words.push_back(token.value); - break; - case MixfixIrTokenKind::ConstantReference: - words.push_back(resolveReference(token.value, context.constantReferences, - "constant")); - break; - case MixfixIrTokenKind::SymbolReference: - words.push_back( - resolveReference(token.value, context.symbolReferences, "symbol")); - break; - case MixfixIrTokenKind::FactReference: - words.push_back( - resolveReference(token.value, context.factReferences, "fact")); - break; - case MixfixIrTokenKind::ProgramReference: - words.push_back( - resolveReference(token.value, context.programReferences, "program")); - break; - case MixfixIrTokenKind::End: - break; - } - } - throw IrError("mixfix GRU decoder did not emit IR_END"); -} - -std::vector -resolveMixfixVocabularyIds(std::span ids, - const MixfixContext &context) { - if (ids.size() > context.maximumOutputWords) { - throw IrError("mixfix GRU exceeded its bounded decoder output"); - } - std::vector tokens; - tokens.reserve(ids.size()); - for (const auto id : ids) { - if (id >= context.outputVocabulary.size()) { - throw IrError( - "mixfix GRU emitted a token outside the finite output vocabulary"); - } - tokens.push_back(context.outputVocabulary[id]); - } - return resolveMixfixIrTokens(tokens, context); -} - -FelidaeIr compileVerifiedMixfixIr(MixfixStateModel &model, - std::span input, - const MixfixContext &context, - FelidaeIr irShell) { - irShell.words = - resolveMixfixVocabularyIds(model.transform(input, context), context); - if (irShell.words.size() > context.maximumOutputWords) { - throw IrError("mixfix model exceeded its bounded IR output"); - } - IrVerifier::verify(irShell); - return irShell; -} - -class GruMixfixStateModel::Implementation { -public: -#ifdef FELIDAE_HAS_TORCH - struct Network final : torch::nn::Module { - explicit Network(const Configuration &c) { - embedding = register_module( - "embedding", - torch::nn::Embedding(c.inputVocabularySize, c.embeddingSize)); - decoderEmbedding = register_module( - "decoder_embedding", - torch::nn::Embedding(c.outputVocabularySize, c.embeddingSize)); - encoder = register_module( - "encoder", - torch::nn::GRU(torch::nn::GRUOptions(c.embeddingSize, c.hiddenSize) - .num_layers(c.layerCount))); - decoder = register_module( - "decoder", - torch::nn::GRU(torch::nn::GRUOptions(c.embeddingSize, c.hiddenSize) - .num_layers(c.layerCount))); - projection = register_module( - "projection", - torch::nn::Linear(c.hiddenSize, c.outputVocabularySize)); - } - torch::nn::Embedding embedding{nullptr}; - torch::nn::Embedding decoderEmbedding{nullptr}; - torch::nn::GRU encoder{nullptr}; - torch::nn::GRU decoder{nullptr}; - torch::nn::Linear projection{nullptr}; - }; - - Implementation(const Configuration &c, - const std::filesystem::path &artifact) { - if (c.inputVocabularySize <= 0 || c.outputVocabularySize <= 0 || - c.embeddingSize <= 0 || c.hiddenSize <= 0 || c.layerCount <= 0 || - c.beginToken < 0 || c.beginToken >= c.outputVocabularySize) { - throw IrError("mixfix GRU configuration is invalid"); - } - if (artifact.empty() && c.allowRandomInitialization) { - network = std::make_shared(c); - network->eval(); - return; - } - if (artifact.empty() || !std::filesystem::is_regular_file(artifact)) { - throw IrError("mixfix GRU artifact is unavailable: " + artifact.string()); - } - if (artifact.extension() != ".pt") { - throw IrError( - "mixfix production artifact must be a .pt TorchScript module"); - } - try { - production = torch::jit::load(artifact.string()); - production->eval(); - torch::InferenceMode guard; - const auto inputIds = - torch::zeros({1, 1}, torch::TensorOptions().dtype(torch::kInt64)); - const auto decoderId = torch::full( - {1, 1}, c.beginToken, torch::TensorOptions().dtype(torch::kInt64)); - const auto encoderHidden = - production->get_method("encode")({inputIds}).toTensor(); - const auto output = - production->get_method("decode_step")({decoderId, encoderHidden}) - .toTuple(); - if (output->elements().size() != 2) { - throw IrError( - "mixfix production artifact has an incompatible forward contract"); - } - const auto logits = output->elements()[0].toTensor(); - const auto decoderHidden = output->elements()[1].toTensor(); - if (encoderHidden.dim() != 3 || encoderHidden.size(0) != c.layerCount || - encoderHidden.size(1) != 1 || encoderHidden.size(2) != c.hiddenSize || - logits.dim() != 1 || logits.size(0) != c.outputVocabularySize || - decoderHidden.sizes() != encoderHidden.sizes()) { - throw IrError( - "mixfix production artifact has an incompatible incremental " - "decoder contract"); - } - } catch (const c10::Error &error) { - throw IrError("mixfix production artifact is not valid TorchScript: " + - std::string(error.what_without_backtrace())); - } - } - std::shared_ptr network; - std::optional production; - std::unique_ptr optimizer; - double optimizerLearningRate = 0.0; - - void prepareOptimizer(double learningRate) { - if (!network) - throw IrError("TorchScript inference artifact cannot be used as a " - "training checkpoint"); - if (!optimizer || optimizerLearningRate != learningRate) { - optimizer = std::make_unique( - network->parameters(), torch::optim::AdamOptions(learningRate)); - optimizerLearningRate = learningRate; - } - } -#else - Implementation(const Configuration &, const std::filesystem::path &) { - throw IrError("mixfix GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); - } -#endif -}; - -GruMixfixStateModel::GruMixfixStateModel(Configuration c) - : GruMixfixStateModel(std::move(c), {}, VersionedArtifact{}) {} - -GruMixfixStateModel::GruMixfixStateModel( - Configuration c, const std::filesystem::path &artifact, VersionedArtifact) - : configuration_(c), implementation_(std::make_unique( - configuration_, artifact)) {} -GruMixfixStateModel::~GruMixfixStateModel() = default; -GruMixfixStateModel::GruMixfixStateModel(GruMixfixStateModel &&) noexcept = - default; -GruMixfixStateModel & -GruMixfixStateModel::operator=(GruMixfixStateModel &&) noexcept = default; - -GruMixfixStateModel GruMixfixStateModel::loadVersioned( - Configuration configuration, const std::filesystem::path &artifactDirectory, - std::string_view expectedSentencePieceIdentity, - std::string_view expectedIrVocabularyVersion) { - const auto manifest = readModelManifest(artifactDirectory / "manifest.txt"); - constexpr std::string_view modelName = "mixfix model"; - requireManifestValue(manifest, "artifact_format_version", - kMixfixArtifactFormatVersion, modelName); - requireManifestValue(manifest, "model_family", kMixfixModelFamily, modelName); - requireManifestValue(manifest, "model_version", kMixfixModelVersion, - modelName); - requireManifestValue(manifest, "backend", "torchscript-gru", modelName); - requireManifestValue(manifest, "tokenizer_contract", kMixfixTokenizerContract, - modelName); - requireManifestValue(manifest, "ir_vocabulary_version", - expectedIrVocabularyVersion, modelName); - requireManifestValue(manifest, "decoder_contract", kMixfixDecoderContract, - modelName); - if (!expectedSentencePieceIdentity.empty() && - manifestValue(manifest, "sentencepiece_model_identity") != - expectedSentencePieceIdentity) { - throw IrError("mixfix model SentencePiece vocabulary is incompatible"); - } - if (manifestInteger(manifest, "input_vocabulary", modelName) != - configuration.inputVocabularySize || - manifestInteger(manifest, "output_vocabulary", modelName) != - configuration.outputVocabularySize || - manifestInteger(manifest, "begin_token", modelName) != - configuration.beginToken || - manifestInteger(manifest, "embedding_size", modelName) != - configuration.embeddingSize || - manifestInteger(manifest, "hidden_size", modelName) != - configuration.hiddenSize || - manifestInteger(manifest, "layer_count", modelName) != - configuration.layerCount) { - throw IrError("mixfix model vocabulary configuration is incompatible"); - } - const auto artifact = artifactDirectory / "mixfix-gru.pt"; - if (!std::filesystem::is_regular_file(artifact)) - throw IrError("mixfix model artifact is unavailable"); - return GruMixfixStateModel(std::move(configuration), artifact, - VersionedArtifact{}); -} - -std::vector -GruMixfixStateModel::transform(std::span input, - const MixfixContext &context) { - if (input.empty()) - throw IrError("mixfix GRU input is empty"); - if (context.outputVocabulary.size() != - static_cast(configuration_.outputVocabularySize)) { - throw IrError("mixfix GRU output vocabulary does not match model artifact"); - } -#ifdef FELIDAE_HAS_TORCH - std::vector ids; - ids.reserve(input.size()); - for (const auto id : input) { - if (id > static_cast( - std::numeric_limits::max()) || - static_cast(id) >= configuration_.inputVocabularySize) { - throw IrError( - "mixfix GRU input SentencePiece ID is outside model vocabulary"); - } - ids.push_back(static_cast(id)); - } - torch::InferenceMode guard; - const auto inputIds = - torch::tensor(ids, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - std::vector tokens; - const auto limit = - std::min(configuration_.maximumDecodeSteps, context.maximumOutputWords); - torch::Tensor decoderHidden; - if (implementation_->production) { - decoderHidden = - implementation_->production->get_method("encode")({inputIds}) - .toTensor(); - } else { - decoderHidden = std::get<1>(implementation_->network->encoder->forward( - implementation_->network->embedding->forward(inputIds))); - } - std::int64_t decoderId = configuration_.beginToken; - for (std::size_t step = 0; step < limit; ++step) { - torch::Tensor logits; - const auto decoderInput = - torch::tensor({decoderId}, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({1, 1}); - if (implementation_->production) { - const auto decoded = - implementation_->production - ->get_method("decode_step")({decoderInput, decoderHidden}) - .toTuple(); - logits = decoded->elements()[0].toTensor(); - decoderHidden = decoded->elements()[1].toTensor(); - } else { - auto decoderResult = implementation_->network->decoder->forward( - implementation_->network->decoderEmbedding->forward(decoderInput), - decoderHidden); - decoderHidden = std::get<1>(decoderResult); - logits = implementation_->network->projection->forward( - std::get<0>(decoderResult).select(0, 0).select(0, 0)); - } - const auto tokenId = logits.argmax().item(); - if (tokenId < 0 || - static_cast(tokenId) >= context.outputVocabulary.size()) { - throw IrError("mixfix GRU emitted token outside finite vocabulary"); - } - const auto vocabularyId = static_cast(tokenId); - tokens.push_back(vocabularyId); - const auto kind = context.outputVocabulary[vocabularyId].kind; - if (kind == MixfixIrTokenKind::End || kind == MixfixIrTokenKind::Reject || - kind == MixfixIrTokenKind::Abstain) - break; - decoderId = tokenId; - } - return tokens; -#else - (void)input; - (void)context; - throw IrError("mixfix GRU backend requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -double GruMixfixStateModel::trainTeacherForced( - std::span input, - std::span targetTokenIds, double learningRate) { - if (input.empty() || targetTokenIds.empty() || learningRate <= 0.0) { - throw IrError("mixfix GRU teacher-forcing batch is invalid"); - } -#ifdef FELIDAE_HAS_TORCH - std::vector encoderIds; - encoderIds.reserve(input.size()); - for (const auto id : input) { - if (id > static_cast( - std::numeric_limits::max()) || - static_cast(id) >= configuration_.inputVocabularySize) { - throw IrError( - "teacher-forcing SentencePiece ID is outside model vocabulary"); - } - encoderIds.push_back(static_cast(id)); - } - std::vector decoderIds; - decoderIds.reserve(targetTokenIds.size()); - decoderIds.push_back(configuration_.beginToken); - for (std::size_t index = 1; index < targetTokenIds.size(); ++index) { - decoderIds.push_back(targetTokenIds[index - 1]); - } - for (const auto id : targetTokenIds) { - if (id < 0 || id >= configuration_.outputVocabularySize) { - throw IrError("teacher-forcing IR token is outside finite vocabulary"); - } - } - auto encoderInput = - torch::tensor(encoderIds, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - auto target = torch::tensor( - std::vector(targetTokenIds.begin(), targetTokenIds.end()), - torch::TensorOptions().dtype(torch::kInt64)); - auto decoderInput = - torch::tensor(decoderIds, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - implementation_->network->train(); - implementation_->prepareOptimizer(learningRate); - implementation_->optimizer->zero_grad(); - const auto encoded = implementation_->network->encoder->forward( - implementation_->network->embedding->forward(encoderInput)); - const auto decoded = implementation_->network->decoder->forward( - implementation_->network->decoderEmbedding->forward(decoderInput), - std::get<1>(encoded)); - const auto logits = implementation_->network->projection->forward( - std::get<0>(decoded).squeeze(1)); - const auto loss = torch::nn::functional::cross_entropy(logits, target); - loss.backward(); - implementation_->optimizer->step(); - implementation_->network->eval(); - return loss.item(); -#else - (void)input; - (void)targetTokenIds; - (void)learningRate; - throw IrError("mixfix GRU training requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -double GruMixfixStateModel::evaluateTeacherForced( - std::span input, - std::span targetTokenIds) { - if (input.empty() || targetTokenIds.empty()) { - throw IrError("mixfix GRU validation batch is invalid"); - } -#ifdef FELIDAE_HAS_TORCH - if (!implementation_->network) { - throw IrError("mixfix teacher-forced validation requires a training model"); - } - std::vector encoderIds; - encoderIds.reserve(input.size()); - for (const auto id : input) { - if (id > static_cast( - std::numeric_limits::max()) || - static_cast(id) >= configuration_.inputVocabularySize) { - throw IrError("validation SentencePiece ID is outside model vocabulary"); - } - encoderIds.push_back(static_cast(id)); - } - std::vector decoderIds{configuration_.beginToken}; - decoderIds.insert(decoderIds.end(), targetTokenIds.begin(), - targetTokenIds.end() - 1); - for (const auto id : targetTokenIds) { - if (id < 0 || id >= configuration_.outputVocabularySize) { - throw IrError("validation IR token is outside finite vocabulary"); - } - } - torch::InferenceMode guard; - implementation_->network->eval(); - const auto encoderInput = - torch::tensor(encoderIds, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - const auto decoderInput = - torch::tensor(decoderIds, torch::TensorOptions().dtype(torch::kInt64)) - .reshape({-1, 1}); - const auto target = torch::tensor( - std::vector(targetTokenIds.begin(), targetTokenIds.end()), - torch::TensorOptions().dtype(torch::kInt64)); - const auto encoded = implementation_->network->encoder->forward( - implementation_->network->embedding->forward(encoderInput)); - const auto decoded = implementation_->network->decoder->forward( - implementation_->network->decoderEmbedding->forward(decoderInput), - std::get<1>(encoded)); - const auto logits = implementation_->network->projection->forward( - std::get<0>(decoded).squeeze(1)); - return torch::nn::functional::cross_entropy(logits, target).item(); -#else - (void)input; - (void)targetTokenIds; - throw IrError("mixfix GRU validation requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -void GruMixfixStateModel::saveCheckpoint( - const std::filesystem::path &artifactPath) const { -#ifdef FELIDAE_HAS_TORCH - if (!implementation_->network) - throw IrError("mixfix checkpoint export requires a training model"); - if (artifactPath.empty()) - throw IrError("mixfix GRU artifact path is empty"); - if (artifactPath.extension() != ".ckpt") - throw IrError("mixfix training checkpoint must use the .ckpt extension"); - const auto parent = artifactPath.parent_path(); - if (!parent.empty()) - std::filesystem::create_directories(parent); - torch::save(implementation_->network, artifactPath.string()); -#else - (void)artifactPath; - throw IrError("mixfix GRU export requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -void GruMixfixStateModel::exportTorchScript( - const std::filesystem::path &artifactPath) const { -#ifdef FELIDAE_HAS_TORCH - if (!implementation_->network) - throw IrError("mixfix TorchScript export requires a training model"); - if (artifactPath.empty()) - throw IrError("mixfix TorchScript artifact path is empty"); - if (artifactPath.extension() != ".pt") - throw IrError("mixfix TorchScript artifact must use the .pt extension"); - const auto parent = artifactPath.parent_path(); - if (!parent.empty()) - std::filesystem::create_directories(parent); - torch::jit::Module module("FelidaeMixfixGru"); - module.register_parameter( - "encoder_embedding", - implementation_->network->embedding->weight.detach().clone(), false); - module.register_parameter( - "decoder_embedding", - implementation_->network->decoderEmbedding->weight.detach().clone(), - false); - module.register_parameter( - "projection_weight", - implementation_->network->projection->weight.detach().clone(), false); - module.register_parameter( - "projection_bias", - implementation_->network->projection->bias.detach().clone(), false); - std::ostringstream encoderParameters, decoderParameters; - const auto registerGru = [&](const auto &gru, const char *prefix, - std::ostringstream &names) { - bool first = true; - for (const auto ¶meter : gru->named_parameters(false)) { - const auto name = std::string(prefix) + "_" + parameter.key(); - module.register_parameter(name, parameter.value().detach().clone(), - false); - if (!first) - names << ", "; - names << "self." << name; - first = false; - } - }; - registerGru(implementation_->network->encoder, "encoder", encoderParameters); - registerGru(implementation_->network->decoder, "decoder", decoderParameters); - std::ostringstream encoderSource; - encoderSource - << "def encode(self, input_ids: Tensor) -> Tensor:\n" - << " encoded_input = torch.embedding(self.encoder_embedding, " - "input_ids)\n" - << " encoder_hidden = torch.zeros([" << configuration_.layerCount - << ", input_ids.size(1), " << configuration_.hiddenSize - << "], dtype=encoded_input.dtype)\n" - << " encoded = torch.gru(encoded_input, encoder_hidden, [" - << encoderParameters.str() << "], True, " << configuration_.layerCount - << ", 0.0, False, False, False)\n" - << " return encoded[1]\n"; - module.define(encoderSource.str()); - std::ostringstream decoderSource; - decoderSource - << "def decode_step(self, decoder_id: Tensor, hidden: Tensor) -> " - "Tuple[Tensor, Tensor]:\n" - << " decoded_input = torch.embedding(self.decoder_embedding, " - "decoder_id)\n" - << " decoded = torch.gru(decoded_input, hidden, [" - << decoderParameters.str() << "], True, " << configuration_.layerCount - << ", 0.0, False, False, False)\n" - << " logits = torch.linear(decoded[0][-1][0], " - "self.projection_weight, self.projection_bias)\n" - << " return logits, decoded[1]\n"; - module.define(decoderSource.str()); - module.eval(); - module.save(artifactPath.string()); -#else - (void)artifactPath; - throw IrError("mixfix GRU export requires FELIDAE_ENABLE_LIBTORCH=ON"); -#endif -} - -} // namespace Felidae diff --git a/src/MixfixStateModel.h b/src/MixfixStateModel.h deleted file mode 100644 index cb6d2b7..0000000 --- a/src/MixfixStateModel.h +++ /dev/null @@ -1,166 +0,0 @@ -#pragma once - -#include "FelidaeIr.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae { - -// The only value emitted by a neural decoder. It is an index into the -// parser-owned finite output vocabulary, never an IR word or table index. -using MixfixVocabularyId = std::uint32_t; - -// A decoder token never carries an unrestricted machine word. References are -// indices into the parser-owned tables below and are resolved only after the -// finite-vocabulary decoder has stopped. -enum class MixfixIrTokenKind : std::uint8_t { - Accept, - Reject, - Abstain, - End, - Opcode, - Register, - ConstantReference, - SymbolReference, - FactReference, - ProgramReference, -}; - -struct MixfixIrToken { - MixfixIrTokenKind kind = MixfixIrTokenKind::End; - IrWord value = 0; -}; - -struct MixfixContext { - // Indexed by the decoder's finite vocabulary IDs. This table is made by - // the parser for one selected mixfix span; the model cannot invent table - // entries, registers, source ranges, or raw size_t values. - std::vector outputVocabulary; - std::vector constantReferences; - std::vector symbolReferences; - std::vector factReferences; - std::vector programReferences; - std::size_t maximumOutputWords = 4096; -}; - -// The parser and corpus extractor share this one fixed structural vocabulary. -// Dynamic constants and symbols remain context-table references. -inline constexpr std::size_t kMaximumMixfixRegisters = 64; -inline constexpr std::size_t kMaximumMixfixReferences = 64; -inline constexpr std::string_view kMixfixIrVocabularyVersion = - "felidae-compiler-ir-v4"; -inline constexpr std::string_view kMixfixArtifactFormatVersion = "1"; -inline constexpr std::string_view kMixfixModelFamily = - "felidae-compiler-mixfix-gru"; -inline constexpr std::string_view kMixfixModelVersion = "mixfix-gru-v2"; -inline constexpr std::string_view kMixfixTokenizerContract = - "sentencepiece-id-sequence-v1"; -inline constexpr std::string_view kMixfixDecoderContract = - "encode-once-decode-step-v1"; -// Three decisions, End, every real opcode, fixed registers, and four bounded -// reference classes. Training artifacts must use this exact parser-owned -// vocabulary. -inline constexpr std::size_t kMixfixStructuralVocabularySize = - 3 + static_cast(kIrOpcodeCount) + kMaximumMixfixRegisters + - 4 * kMaximumMixfixReferences; -MixfixContext makeMixfixContext(const FelidaeIr &shell); - -class MixfixStateModel { -public: - virtual ~MixfixStateModel() = default; - - virtual std::vector - transform(std::span input, - const MixfixContext &context) = 0; -}; - -// A C++ LibTorch encoder/decoder GRU. Its recurrent state is the only state -// that crosses SentencePiece fragments; it is deliberately independent of the -// parser, verifier, and VM so an SSM backend can replace it later. -class GruMixfixStateModel final : public MixfixStateModel { -public: - struct Configuration { - std::int64_t inputVocabularySize = 0; - std::int64_t outputVocabularySize = 0; - std::int64_t embeddingSize = 128; - std::int64_t hiddenSize = 256; - std::int64_t layerCount = 1; - std::int64_t beginToken = 0; - std::size_t maximumDecodeSteps = 4096; - // Only the explicit training tool may opt into an untrained model. - // Inference keeps this false and therefore requires an artifact. - bool allowRandomInitialization = false; - }; - - // Constructs only an explicitly enabled, randomly initialized training - // model. Persisted inference artifacts must pass through loadVersioned(). - explicit GruMixfixStateModel(Configuration configuration); - ~GruMixfixStateModel() override; - - GruMixfixStateModel(GruMixfixStateModel &&) noexcept; - GruMixfixStateModel &operator=(GruMixfixStateModel &&) noexcept; - GruMixfixStateModel(const GruMixfixStateModel &) = delete; - GruMixfixStateModel &operator=(const GruMixfixStateModel &) = delete; - - std::vector - transform(std::span input, - const MixfixContext &context) override; - - // Validates the complete C++-generated artifact contract before loading. - // expectedSentencePieceIdentity is supplied by the parser/model owner. - static GruMixfixStateModel - loadVersioned(Configuration configuration, - const std::filesystem::path &artifactDirectory, - std::string_view expectedSentencePieceIdentity, - std::string_view expectedIrVocabularyVersion = - kMixfixIrVocabularyVersion); - - // One C++ LibTorch teacher-forcing optimization step. targetTokenIds must - // contain the terminating IR_END vocabulary token. This intentionally is - // not called by parsing, normal builds, or inference. - double trainTeacherForced(std::span input, - std::span targetTokenIds, - double learningRate); - - // Held-out teacher-forcing loss. This has no optimizer step and is the - // training tool's validation metric, not an inference-quality claim. - double evaluateTeacherForced(std::span input, - std::span targetTokenIds); - - void saveCheckpoint(const std::filesystem::path &checkpointPath) const; - void exportTorchScript(const std::filesystem::path &artifactPath) const; - -private: - struct VersionedArtifact {}; - GruMixfixStateModel(Configuration configuration, - const std::filesystem::path &artifactPath, - VersionedArtifact); - class Implementation; - Configuration configuration_; - std::unique_ptr implementation_; -}; - -// Shared by every backend: converts a finite decoder token stream to legal IR -// words and refuses unbounded output or missing IR_END. -std::vector resolveMixfixIrTokens(std::span tokens, - const MixfixContext &context); -std::vector -resolveMixfixVocabularyIds(std::span ids, - const MixfixContext &context); - -// The sole model-to-runtime boundary. Callers supply the parser-built IR -// tables and source map; this function installs model words then verifies the -// complete canonical IR before it can reach RegisterVm. -FelidaeIr compileVerifiedMixfixIr(MixfixStateModel &model, - std::span input, - const MixfixContext &context, - FelidaeIr irShell); - -} // namespace Felidae diff --git a/src/MixfixTraining.h b/src/MixfixTraining.h deleted file mode 100644 index 5354f0d..0000000 --- a/src/MixfixTraining.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -namespace Felidae { - -// Runs the existing C++/LibTorch mixfix trainer. The compiler CLI owns its -// public option parsing; this keeps one training implementation. -int runMixfixGruTraining(int argc, char** argv); - -} // namespace Felidae diff --git a/src/ModelStore.h b/src/ModelStore.h deleted file mode 100644 index a04a03e..0000000 --- a/src/ModelStore.h +++ /dev/null @@ -1,225 +0,0 @@ -#pragma once - -#include "form/RegisterVm.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae { - -// Shared by every versioned model loader (compiler-side mixfix GRU, VM-side -// runtime GRU, and any future model). A manifest is a flat `key=value` text -// file written beside its `.pt` artifact; this is the one authoritative -// reader for that format. Do not reintroduce a second copy in a model's own -// .cpp -- the compiler and VM SSM loaders duplicated this by hand until both -// were folded into this function. -using ModelManifest = std::unordered_map; - -inline ModelManifest readModelManifest(const std::filesystem::path& manifestPath) { - std::ifstream manifest(manifestPath); - if (!manifest) - throw IrError("model manifest is unavailable: " + manifestPath.string()); - ModelManifest values; - std::string line; - while (std::getline(manifest, line)) { - const auto separator = line.find('='); - if (separator == std::string::npos || separator == 0) - throw IrError("model manifest contains an invalid field"); - if (!values.emplace(line.substr(0, separator), line.substr(separator + 1)).second) - throw IrError("model manifest repeats " + line.substr(0, separator)); - } - if (!manifest.eof()) - throw IrError("model manifest cannot be read: " + manifestPath.string()); - return values; -} - -inline const std::string& manifestValue(const ModelManifest& manifest, - std::string_view wanted) { - const auto found = manifest.find(std::string(wanted)); - if (found != manifest.end()) - return found->second; - throw IrError("model manifest omits " + std::string(wanted)); -} - -inline void requireManifestValue(const ModelManifest& manifest, - std::string_view key, - std::string_view expected, - std::string_view modelName) { - if (manifestValue(manifest, key) != expected) { - throw IrError(std::string(modelName) + - " manifest is incompatible: " + std::string(key)); - } -} - -inline std::int64_t manifestInteger(const ModelManifest& manifest, - std::string_view key, - std::string_view modelName) { - const auto& text = manifestValue(manifest, key); - try { - std::size_t consumed = 0; - const auto value = std::stoll(text, &consumed); - if (consumed != text.size()) - throw std::invalid_argument("trailing data"); - return value; - } catch (const std::exception&) { - throw IrError(std::string(modelName) + " manifest has invalid " + - std::string(key)); - } -} - -// Training artifacts have two intentional destinations. Keeping the model in -// a named subdirectory prevents the executable and model files from being -// mixed at the root of build/ or dist/. -inline std::filesystem::path modelStoreDirectory(const std::filesystem::path& requested, - std::string_view modelName) { - namespace fs = std::filesystem; - const auto current = fs::current_path().lexically_normal(); - auto root = current; - // Training is commonly launched either from the repository root or from - // build/. Resolve the existing source root without - // creating another nested build directory. - for (auto candidate = current;; candidate = candidate.parent_path()) { - if (fs::is_regular_file(candidate / "CMakeLists.txt") && - fs::is_directory(candidate / "build")) { - root = candidate; - break; - } - if (candidate == candidate.root_path() || candidate.parent_path() == candidate) break; - } - const auto build = (root / "build").lexically_normal(); - const auto dist = (root / "dist").lexically_normal(); - const auto selected = (requested.is_absolute() ? requested : (root / requested)).lexically_normal(); - if (selected == build) return build / modelName; - if (selected == dist) return dist / "models" / modelName; - throw std::runtime_error("--store-model accepts only build or dist"); -} - -// Windows shells do not expand wildcards for native executables. Keep the -// expansion here so `--train datasets/compiler/*.jsonl` is portable across -// the supported CLI hosts and does not require a scratch merge file. -inline bool wildcardMatches(std::string_view pattern, std::string_view text) { - std::size_t patternIndex = 0, textIndex = 0, star = std::string_view::npos, retry = 0; - while (textIndex < text.size()) { - if (patternIndex < pattern.size() && pattern[patternIndex] == text[textIndex]) { - ++patternIndex; - ++textIndex; - } else if (patternIndex < pattern.size() && pattern[patternIndex] == '*') { - star = patternIndex++; - retry = textIndex; - } else if (star != std::string_view::npos) { - patternIndex = star + 1; - textIndex = ++retry; - } else { - return false; - } - } - while (patternIndex < pattern.size() && pattern[patternIndex] == '*') ++patternIndex; - return patternIndex == pattern.size(); -} - -inline std::vector expandJsonlDatasetPaths(const std::filesystem::path& requested) { - namespace fs = std::filesystem; - const auto filename = requested.filename().string(); - if (filename.find('*') == std::string::npos) { - if (requested.extension() != ".jsonl" || !fs::is_regular_file(requested)) { - throw std::runtime_error("--train requires an existing .jsonl dataset or .jsonl wildcard"); - } - return {requested}; - } - if (requested.extension() != ".jsonl") { - throw std::runtime_error("--train wildcard must select .jsonl datasets"); - } - const auto directory = requested.has_parent_path() ? requested.parent_path() : fs::path{"."}; - if (!fs::is_directory(directory)) throw std::runtime_error("training dataset directory does not exist: " + directory.string()); - std::vector result; - for (const auto& entry : fs::directory_iterator(directory)) { - if (entry.is_regular_file() && wildcardMatches(filename, entry.path().filename().string())) { - result.push_back(entry.path()); - } - } - std::sort(result.begin(), result.end()); - if (result.empty()) throw std::runtime_error("--train wildcard matched no .jsonl datasets"); - return result; -} - -inline std::string encodeDatasetPaths(const std::vector& paths) { - // U+001F cannot occur in a Windows filename. The trainer keeps the list - // in memory; no temporary/merged dataset is written. - constexpr char separator = '\x1f'; - std::string result; - for (const auto& path : paths) { - if (path.string().find(separator) != std::string::npos) throw std::runtime_error("training dataset path contains a reserved separator"); - if (!result.empty()) result.push_back(separator); - result += path.string(); - } - return result; -} - -struct ModelTrainingOptions { - std::filesystem::path dataset; - std::filesystem::path store; - std::size_t epochs = 8; - double learningRate = 0.001; -}; - -// Shared only by the two production model commands. Both keep their model -// architecture-specific defaults behind their existing trainers. -inline std::optional parseModelTrainingOptions(int argc, char** argv) { - if (argc < 2 || std::string_view(argv[1]) != "--train") return std::nullopt; - if (argc < 4) throw std::runtime_error("--train requires a dataset and --store-model build|dist"); - ModelTrainingOptions options; - options.dataset = argv[2]; - bool haveStore = false, haveEpochs = false, haveLearningRate = false; - const auto positiveSize = [](std::string_view text, const char* option) { - if (text.empty() || text.front() == '-') throw std::runtime_error(std::string(option) + " requires a positive integer"); - std::size_t consumed = 0; - const auto value = std::stoull(std::string(text), &consumed); - if (consumed != text.size() || value == 0 || value > std::numeric_limits::max()) { - throw std::runtime_error(std::string(option) + " requires a positive integer in range"); - } - return static_cast(value); - }; - const auto positiveReal = [](std::string_view text, const char* option) { - std::size_t consumed = 0; - const auto value = std::stod(std::string(text), &consumed); - if (consumed != text.size() || !std::isfinite(value) || value <= 0.0) { - throw std::runtime_error(std::string(option) + " requires a positive finite number"); - } - return value; - }; - for (int index = 3; index < argc; ++index) { - const std::string_view flag(argv[index]); - if (flag == "--store-model") { - if (haveStore || ++index == argc) throw std::runtime_error("--store-model requires one directory"); - options.store = argv[index]; - haveStore = true; - } else if (flag == "--epochs") { - if (haveEpochs || ++index == argc) throw std::runtime_error("--epochs requires one positive integer"); - options.epochs = positiveSize(argv[index], "--epochs"); - haveEpochs = true; - } else if (flag == "--learning-rate") { - if (haveLearningRate || ++index == argc) throw std::runtime_error("--learning-rate requires one positive number"); - options.learningRate = positiveReal(argv[index], "--learning-rate"); - haveLearningRate = true; - } else { - throw std::runtime_error("unknown training option: " + std::string(flag)); - } - } - if (!haveStore) { - throw std::runtime_error("training options are invalid"); - } - return options; -} - -} // namespace Felidae diff --git a/src/NativeJson.h b/src/NativeJson.h new file mode 100644 index 0000000..89a351c --- /dev/null +++ b/src/NativeJson.h @@ -0,0 +1,310 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae::NativeJson { + +struct Value { + enum class Kind { Null, Bool, Number, String, Array, Object } kind = Kind::Null; + bool boolean = false; + double number = 0.0; + std::string text; + std::vector items; + std::map fields; + std::vector fieldOrder; +}; + +inline void skipWhitespace(const std::string& source, size_t& position) { + while (position < source.size() && + std::isspace(static_cast(source[position]))) { + ++position; + } +} + +inline bool parseValue(const std::string& source, size_t& position, Value& value); + +inline bool parseString(const std::string& source, size_t& position, std::string& value) { + if (position >= source.size() || source[position] != '"') return false; + ++position; + while (position < source.size()) { + const char current = source[position++]; + if (current == '"') return true; + if (current != '\\') { + value.push_back(current); + continue; + } + if (position >= source.size()) return false; + const char escaped = source[position++]; + switch (escaped) { + case '"': value.push_back('"'); break; + case '\\': value.push_back('\\'); break; + case '/': value.push_back('/'); break; + case 'b': value.push_back('\b'); break; + case 'f': value.push_back('\f'); break; + case 'n': value.push_back('\n'); break; + case 'r': value.push_back('\r'); break; + case 't': value.push_back('\t'); break; + default: return false; + } + } + return false; +} + +inline bool parseArray(const std::string& source, size_t& position, Value& value) { + if (position >= source.size() || source[position] != '[') return false; + ++position; + value.kind = Value::Kind::Array; + skipWhitespace(source, position); + if (position < source.size() && source[position] == ']') { + ++position; + return true; + } + while (position < source.size()) { + Value item; + if (!parseValue(source, position, item)) return false; + value.items.push_back(std::move(item)); + skipWhitespace(source, position); + if (position < source.size() && source[position] == ',') { + ++position; + continue; + } + if (position < source.size() && source[position] == ']') { + ++position; + return true; + } + return false; + } + return false; +} + +inline bool parseObject(const std::string& source, size_t& position, Value& value) { + if (position >= source.size() || source[position] != '{') return false; + ++position; + value.kind = Value::Kind::Object; + skipWhitespace(source, position); + if (position < source.size() && source[position] == '}') { + ++position; + return true; + } + while (position < source.size()) { + skipWhitespace(source, position); + std::string key; + if (!parseString(source, position, key)) return false; + skipWhitespace(source, position); + if (position >= source.size() || source[position] != ':') return false; + ++position; + Value fieldValue; + if (!parseValue(source, position, fieldValue)) return false; + value.fieldOrder.push_back(key); + value.fields.emplace(std::move(key), std::move(fieldValue)); + skipWhitespace(source, position); + if (position < source.size() && source[position] == ',') { + ++position; + continue; + } + if (position < source.size() && source[position] == '}') { + ++position; + return true; + } + return false; + } + return false; +} + +inline bool parseNumber(const std::string& source, size_t& position, Value& value) { + const size_t start = position; + if (position < source.size() && source[position] == '-') ++position; + if (position >= source.size()) return false; + if (source[position] == '0') { + ++position; + } else { + if (!std::isdigit(static_cast(source[position]))) return false; + while (position < source.size() && + std::isdigit(static_cast(source[position]))) { + ++position; + } + } + if (position < source.size() && source[position] == '.') { + ++position; + if (position >= source.size() || + !std::isdigit(static_cast(source[position]))) { + return false; + } + while (position < source.size() && + std::isdigit(static_cast(source[position]))) { + ++position; + } + } + if (position < source.size() && + (source[position] == 'e' || source[position] == 'E')) { + ++position; + if (position < source.size() && + (source[position] == '+' || source[position] == '-')) { + ++position; + } + if (position >= source.size() || + !std::isdigit(static_cast(source[position]))) { + return false; + } + while (position < source.size() && + std::isdigit(static_cast(source[position]))) { + ++position; + } + } + value.kind = Value::Kind::Number; + value.number = std::strtod(source.substr(start, position - start).c_str(), nullptr); + return std::isfinite(value.number); +} + +inline bool parseValue(const std::string& source, size_t& position, Value& value) { + skipWhitespace(source, position); + if (position >= source.size()) return false; + if (source[position] == '"') { + value.kind = Value::Kind::String; + return parseString(source, position, value.text); + } + if (source[position] == '[') return parseArray(source, position, value); + if (source[position] == '{') return parseObject(source, position, value); + if (source.compare(position, 4, "null") == 0) { + position += 4; + value.kind = Value::Kind::Null; + return true; + } + if (source.compare(position, 4, "true") == 0) { + position += 4; + value.kind = Value::Kind::Bool; + value.boolean = true; + return true; + } + if (source.compare(position, 5, "false") == 0) { + position += 5; + value.kind = Value::Kind::Bool; + value.boolean = false; + return true; + } + return parseNumber(source, position, value); +} + +inline Value parse(const char* raw, const std::string& context) { + const std::string source = raw ? raw : "{}"; + size_t position = 0; + Value value; + if (!parseValue(source, position, value)) { + throw std::runtime_error(context + " received invalid JSON"); + } + skipWhitespace(source, position); + if (position != source.size()) { + throw std::runtime_error(context + " received trailing JSON data"); + } + return value; +} + +inline const Value* field(const Value& object, const std::string& key) { + if (object.kind != Value::Kind::Object) return nullptr; + const auto found = object.fields.find(key); + return found == object.fields.end() ? nullptr : &found->second; +} + +inline const Value& requireField(const Value& object, + const std::string& key, + Value::Kind kind, + const std::string& context) { + const Value* value = field(object, key); + if (!value || value->kind != kind) { + throw std::runtime_error(context + " expects '" + key + "' with the declared type"); + } + return *value; +} + +inline std::string escape(const std::string& value) { + std::string out; + out.reserve(value.size() + 8); + for (const char current : value) { + switch (current) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: out.push_back(current); break; + } + } + return out; +} + +inline std::string stringify(const Value& value) { + switch (value.kind) { + case Value::Kind::Null: + return "null"; + case Value::Kind::Bool: + return value.boolean ? "true" : "false"; + case Value::Kind::Number: { + std::ostringstream out; + out.precision(15); + out << value.number; + return out.str(); + } + case Value::Kind::String: + return "\"" + escape(value.text) + "\""; + case Value::Kind::Array: { + std::string out = "["; + for (size_t index = 0; index < value.items.size(); ++index) { + if (index != 0) out += ","; + out += stringify(value.items[index]); + } + return out + "]"; + } + case Value::Kind::Object: { + std::string out = "{"; + bool first = true; + auto appendEntry = [&](const std::string& key, const Value& fieldValue) { + if (!first) out += ","; + first = false; + out += "\"" + escape(key) + "\":" + stringify(fieldValue); + }; + if (!value.fieldOrder.empty()) { + for (const auto& key : value.fieldOrder) { + const auto found = value.fields.find(key); + if (found != value.fields.end()) appendEntry(found->first, found->second); + } + } else { + for (const auto& entry : value.fields) appendEntry(entry.first, entry.second); + } + return out + "}"; + } + } + return "null"; +} + +inline Value string(std::string value) { + Value result; + result.kind = Value::Kind::String; + result.text = std::move(value); + return result; +} + +inline Value error(const std::string& message) { + Value result; + result.kind = Value::Kind::Object; + result.fields.emplace("error", string(message)); + return result; +} + +inline char* copyResponse(const std::string& response) { + char* buffer = static_cast(std::malloc(response.size() + 1)); + if (!buffer) return nullptr; + std::memcpy(buffer, response.c_str(), response.size() + 1); + return buffer; +} + +} // namespace Felidae::NativeJson diff --git a/src/NativeRuntime.cpp b/src/NativeRuntime.cpp index af81e26..8bceda6 100644 --- a/src/NativeRuntime.cpp +++ b/src/NativeRuntime.cpp @@ -1,6 +1,6 @@ #include "NativeRuntime.h" -#include "../native_modules/common/NativeJson.h" +#include "NativeJson.h" #include #include diff --git a/src/Operator.h b/src/Operator.h index 90f9684..edd79bd 100644 --- a/src/Operator.h +++ b/src/Operator.h @@ -361,7 +361,7 @@ class OperatorRegistry { public: // Structural compilation is intentionally lexical-model agnostic. Parser - // attaches its native SentencePiece IDs exactly once before registration. + // attaches its native token IDs exactly once before registration. static CoreOperator coreOperatorForPattern(std::string_view pattern) { if (pattern == "{left} + {right}") return CoreOperator::Add; if (pattern == "{left} - {right}") return CoreOperator::Subtract; diff --git a/src/ReasoningRuntime.cpp b/src/ReasoningRuntime.cpp new file mode 100644 index 0000000..7129ef0 --- /dev/null +++ b/src/ReasoningRuntime.cpp @@ -0,0 +1,1196 @@ +#include "Interpreter.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +namespace { + +std::shared_ptr markFact( + std::shared_ptr value, + std::string type) { + value->factType = std::move(type); + return value; +} + +} // namespace + +bool Interpreter::isTableEligibleGoal( + const std::shared_ptr& goal, + SymbolId root, + std::unordered_set& visiting, + std::unordered_set& checked, + bool& recursive) const { + if (!goal) return false; + switch (goal->kind()) { + case GoalKind::Call: { + const auto call = std::static_pointer_cast(goal); + if (call->call.builtinId != BuiltinId::Unknown || + nativeDeclarationFor(call->call.name)) return false; + const SymbolId id = call->call.nameId == 0 + ? symbolIdForName(call->call.name) + : call->call.nameId; + if (id == root || visiting.count(id)) recursive = true; + return isTableEligiblePredicate( + call->call.name, id, visiting, checked, recursive); + } + case GoalKind::Not: { + const auto negated = std::static_pointer_cast(goal); + if (negated->call.builtinId != BuiltinId::Unknown || + nativeDeclarationFor(negated->call.name)) return false; + const SymbolId id = negated->call.nameId == 0 + ? symbolIdForName(negated->call.name) + : negated->call.nameId; + return isTableEligiblePredicate( + negated->call.name, id, visiting, checked, recursive); + } + case GoalKind::Binary: + return true; + case GoalKind::Where: + return isTableEligibleGoal( + std::static_pointer_cast(goal)->condition, + root, + visiting, + checked, + recursive); + case GoalKind::Assign: + return !exprMayHaveSideEffects( + std::static_pointer_cast(goal)->expr); + case GoalKind::Return: + return std::static_pointer_cast(goal)->fields.empty(); + // Branching and value returns retain ordered method semantics. + // Tabled rules are intentionally declarative conjunctions. + case GoalKind::MultiAssign: + case GoalKind::If: + case GoalKind::Group: + case GoalKind::Or: + return false; + } + return false; +} + +bool Interpreter::isTableEligiblePredicate( + const std::string& name, + SymbolId nameId, + std::unordered_set& visiting, + std::unordered_set& checked, + bool& recursive) const { + if (checked.count(nameId)) return true; + if (visiting.count(nameId)) { + recursive = true; + return true; + } + visiting.insert(nameId); + const auto* clauses = findClauses(name, nameId); + if (clauses) { + for (const auto& clause : *clauses) { + if (!clause || clause->clauseKind != ClauseKind::Rule || + isMethodClause(*clause) || + !clause->fallbackBranches.empty()) { + visiting.erase(nameId); + return false; + } + for (const auto& goal : clause->body) { + if (!isTableEligibleGoal( + goal, nameId, visiting, checked, recursive)) { + visiting.erase(nameId); + return false; + } + } + } + } + visiting.erase(nameId); + checked.insert(nameId); + return true; +} + +bool Interpreter::tableEvaluationValid( + const TableEvaluation& evaluation) const { + if (evaluation.hierarchyGeneration != memory_.hierarchyGeneration()) { + return false; + } + for (const auto& dependency : evaluation.callableGenerations) { + const auto current = symbolGenerations_.find(dependency.first); + const std::uint64_t generation = + current == symbolGenerations_.end() ? 0 : current->second; + if (generation != dependency.second) return false; + } + for (const auto& dependency : evaluation.relationGenerations) { + const std::string type = symbolNameForId(dependency.first); + if (memory_.relationGeneration(type, dependency.first) != + dependency.second) return false; + } + return true; +} + +std::shared_ptr +Interpreter::tableEvaluationFor( + const std::string& name, + SymbolId nameId, + bool requireRecursive) { + if (nameId == 0) nameId = symbolIdForName(name); + const auto cached = tableCache_.find(nameId); + if (cached != tableCache_.end() && cached->second && + cached->second->rootName == name && + tableEvaluationValid(*cached->second)) { + ++tableCacheHits_; + return cached->second; + } + if (cached != tableCache_.end()) tableCache_.erase(cached); + + std::unordered_set visiting; + std::unordered_set checked; + bool recursive = false; + if (!isTableEligiblePredicate( + name, nameId, visiting, checked, recursive) || + (requireRecursive && !recursive)) { + return {}; + } + + ++tableCacheMisses_; + auto evaluation = buildTableEvaluation(name, nameId); + if (evaluation) tableCache_[nameId] = evaluation; + return evaluation; +} + +std::vector Interpreter::evaluateTableGoals( + const std::vector>& goals, + std::vector inputs, + const TableEvaluation& evaluation, + std::optional> deltaPivot) { + constexpr std::size_t MaxIntermediateBindings = 1'000'000; + for (std::size_t goalIndex = 0; + goalIndex < goals.size() && !inputs.empty(); + ++goalIndex) { + const auto& goal = goals[goalIndex]; + if (auto call = std::dynamic_pointer_cast(goal)) { + const SymbolId id = call->call.nameId == 0 + ? symbolIdForName(call->call.name) + : call->call.nameId; + const auto table = evaluation.predicates.find(id); + if (table == evaluation.predicates.end()) return {}; + + std::vector allCandidates; + const std::vector* candidates = nullptr; + if (deltaPivot && deltaPivot->first == id && + deltaPivot->second == goalIndex) { + candidates = &table->second.delta; + } else { + allCandidates.resize(table->second.answers.size()); + for (std::size_t i = 0; i < allCandidates.size(); ++i) { + allCandidates[i] = i; + } + candidates = &allCandidates; + } + + std::vector next; + for (const auto& input : inputs) { + for (const std::size_t answerIndex : *candidates) { + if (answerIndex >= table->second.answers.size()) continue; + const auto& answer = table->second.answers[answerIndex]; + for (auto& unified : + unifyCallAlternatives( + call->call, answer.call, input.env)) { + TableBinding binding{ + std::move(unified), input.provenance}; + binding.provenance.insert( + binding.provenance.end(), + answer.provenance.begin(), + answer.provenance.end()); + next.push_back(std::move(binding)); + if (next.size() > MaxIntermediateBindings) { + throw InterpreterError( + "TableLimit: intermediate binding limit reached"); + } + } + } + } + inputs = std::move(next); + continue; + } + + if (auto negated = std::dynamic_pointer_cast(goal)) { + const SymbolId id = negated->call.nameId == 0 + ? symbolIdForName(negated->call.name) + : negated->call.nameId; + const auto table = evaluation.predicates.find(id); + std::vector next; + for (auto& input : inputs) { + bool matched = false; + if (table != evaluation.predicates.end()) { + for (const auto& answer : table->second.answers) { + if (!unifyCallAlternatives( + negated->call, answer.call, input.env).empty()) { + matched = true; + break; + } + } + } + if (!matched) next.push_back(std::move(input)); + } + inputs = std::move(next); + continue; + } + + std::vector next; + for (auto& input : inputs) { + bool accepted = false; + if (auto binary = std::dynamic_pointer_cast(goal)) { + accepted = solveBinaryGoal(*binary, input.env); + } else if (auto where = + std::dynamic_pointer_cast(goal)) { + accepted = solveWhereGoal(*where, input.env); + } else if (auto assign = + std::dynamic_pointer_cast(goal)) { + accepted = solveAssignGoal(*assign, input.env); + } else if (auto returned = + std::dynamic_pointer_cast(goal)) { + accepted = returned->fields.empty(); + } + if (accepted) next.push_back(std::move(input)); + } + inputs = std::move(next); + } + return inputs; +} + +std::shared_ptr +Interpreter::buildTableEvaluation( + const std::string& name, + SymbolId nameId) { + constexpr std::size_t MaxTableAnswers = 1'000'000; + constexpr std::size_t MaxProvenanceNodes = 2'000'000; + constexpr std::size_t MaxSemiNaiveRounds = 100'000; + constexpr std::size_t MaxProofsPerAnswer = 16; + + struct RuleInfo { + std::shared_ptr clause; + SymbolId headId = 0; + std::vector> dependencies; + }; + + auto evaluation = std::make_shared(); + evaluation->rootId = nameId; + evaluation->rootName = name; + evaluation->hierarchyGeneration = memory_.hierarchyGeneration(); + + std::unordered_map names; + std::vector rules; + std::vector pending{nameId}; + names.emplace(nameId, name); + std::unordered_set visited; + while (!pending.empty()) { + const SymbolId currentId = pending.back(); + pending.pop_back(); + if (!visited.insert(currentId).second) continue; + const std::string currentName = names[currentId]; + const auto* clauses = findClauses(currentName, currentId); + if (!clauses) continue; + for (const auto& clause : *clauses) { + if (!clause || clause->clauseKind != ClauseKind::Rule) continue; + RuleInfo rule{clause, currentId, {}}; + for (const auto& goal : clause->body) { + if (auto call = + std::dynamic_pointer_cast(goal)) { + const SymbolId target = call->call.nameId == 0 + ? symbolIdForName(call->call.name) + : call->call.nameId; + rule.dependencies.emplace_back(target, false); + names.emplace(target, call->call.name); + pending.push_back(target); + } else if (auto negated = + std::dynamic_pointer_cast(goal)) { + const SymbolId target = negated->call.nameId == 0 + ? symbolIdForName(negated->call.name) + : negated->call.nameId; + rule.dependencies.emplace_back(target, true); + names.emplace(target, negated->call.name); + pending.push_back(target); + } + } + rules.push_back(std::move(rule)); + } + } + + for (const auto& entry : names) { + const auto generation = symbolGenerations_.find(entry.first); + evaluation->callableGenerations[entry.first] = + generation == symbolGenerations_.end() ? 0 : generation->second; + } + + for (const auto& entry : names) { + PredicateTable table; + table.name = entry.second; + table.nameId = entry.first; + auto inserted = + evaluation->predicates.emplace(entry.first, std::move(table)); + auto& predicate = inserted.first->second; + for (const std::size_t factIndex : + memory_.compatibleFactIndexes(entry.second, entry.first)) { + const auto& fact = memory_.fact(factIndex); + if (!fact.active) continue; + Call answer(entry.second, {}); + answer.nameId = entry.first; + answer.args = memory_.factArguments(factIndex); + const std::string key = answer.debug(); + + ProvenanceNode node; + node.kind = ProvenanceNode::Kind::Fact; + node.factId = fact.id; + const std::size_t provenance = evaluation->provenance.size(); + evaluation->provenance.push_back(std::move(node)); + + const auto existing = predicate.answerByKey.find(key); + if (existing == predicate.answerByKey.end()) { + const std::size_t answerIndex = predicate.answers.size(); + predicate.answerByKey.emplace(key, answerIndex); + predicate.answers.push_back( + TableAnswer{std::move(answer), {provenance}}); + predicate.delta.push_back(answerIndex); + } else if ( + predicate.answers[existing->second].provenance.size() < + MaxProofsPerAnswer) { + predicate.answers[existing->second].provenance.push_back( + provenance); + } + evaluation->relationGenerations[fact.typeId] = + memory_.relationGeneration(fact.type, fact.typeId); + } + evaluation->relationGenerations.try_emplace( + entry.first, + memory_.relationGeneration(entry.second, entry.first)); + } + + std::unordered_map stratum; + for (const auto& entry : names) stratum.emplace(entry.first, 0); + bool changed = false; + for (std::size_t pass = 0; pass <= names.size(); ++pass) { + changed = false; + for (const auto& rule : rules) { + for (const auto& dependency : rule.dependencies) { + const std::size_t required = + stratum[dependency.first] + + (dependency.second ? 1U : 0U); + if (stratum[rule.headId] < required) { + stratum[rule.headId] = required; + changed = true; + } + } + } + if (!changed) break; + if (pass == names.size()) { + throw InterpreterError( + "Unstratified negative dependency cycle in tabled reasoning"); + } + } + + std::size_t maxStratum = 0; + for (const auto& entry : stratum) { + maxStratum = std::max(maxStratum, entry.second); + } + + for (std::size_t currentStratum = 0; + currentStratum <= maxStratum; + ++currentStratum) { + std::vector stratumRules; + std::unordered_set activeHeads; + for (const auto& rule : rules) { + if (stratum[rule.headId] == currentStratum) { + stratumRules.push_back(&rule); + activeHeads.insert(rule.headId); + } + } + if (stratumRules.empty()) continue; + + bool firstRound = true; + for (;;) { + if (++evaluation->rounds > MaxSemiNaiveRounds) { + throw InterpreterError( + "TableLimit: semi-naive iteration limit reached"); + } + struct PendingAnswer { + SymbolId headId = 0; + Call call; + std::size_t provenance = 0; + }; + std::vector pendingAnswers; + + for (const RuleInfo* rule : stratumRules) { + std::vector> pivots; + for (std::size_t goalIndex = 0; + goalIndex < rule->clause->body.size(); + ++goalIndex) { + const auto call = std::dynamic_pointer_cast( + rule->clause->body[goalIndex]); + if (!call) continue; + const SymbolId target = call->call.nameId == 0 + ? symbolIdForName(call->call.name) + : call->call.nameId; + if (stratum[target] == currentStratum) { + const auto table = + evaluation->predicates.find(target); + if (table != evaluation->predicates.end() && + !table->second.delta.empty()) { + pivots.emplace_back(target, goalIndex); + } + } + } + if (pivots.empty() && !firstRound) continue; + if (pivots.empty()) pivots.emplace_back(0, 0); + + for (const auto& pivot : pivots) { + std::vector bindings{ + TableBinding{Env{}, {}}}; + bindings = evaluateTableGoals( + rule->clause->body, + std::move(bindings), + *evaluation, + pivot.first == 0 + ? std::nullopt + : std::optional< + std::pair>(pivot)); + for (auto& binding : bindings) { + Call answer(rule->clause->head.name, {}); + answer.nameId = rule->headId; + bool ground = true; + for (const auto& argument : + rule->clause->head.args) { + const auto resolved = + resolveExpr(argument.value, binding.env); + if (!isGroundLiteral(resolved)) { + ground = false; + break; + } + answer.args.push_back( + Arg{argument.name, argument.nameId, resolved->clone()}); + } + if (!ground) continue; + if (evaluation->provenance.size() >= + MaxProvenanceNodes) { + throw InterpreterError( + "DerivationLimit: provenance node limit reached"); + } + ProvenanceNode node; + node.kind = ProvenanceNode::Kind::Rule; + node.rule = rule->clause->head.name; + node.span = rule->clause->sourceSpan; + node.parents = std::move(binding.provenance); + const std::size_t provenance = + evaluation->provenance.size(); + evaluation->provenance.push_back(std::move(node)); + pendingAnswers.push_back(PendingAnswer{ + rule->headId, + std::move(answer), + provenance}); + } + } + } + + for (const SymbolId head : activeHeads) { + evaluation->predicates[head].delta.clear(); + } + bool progress = false; + for (auto& pendingAnswer : pendingAnswers) { + auto& table = + evaluation->predicates[pendingAnswer.headId]; + const std::string key = pendingAnswer.call.debug(); + const auto existing = table.answerByKey.find(key); + if (existing != table.answerByKey.end()) { + auto& proofs = + table.answers[existing->second].provenance; + if (proofs.size() < MaxProofsPerAnswer) { + proofs.push_back(pendingAnswer.provenance); + } + continue; + } + if (table.answers.size() >= MaxTableAnswers) { + throw InterpreterError( + "TableLimit: answer limit reached for predicate '" + + table.name + "'"); + } + const std::size_t answerIndex = table.answers.size(); + table.answerByKey.emplace(key, answerIndex); + table.answers.push_back(TableAnswer{ + std::move(pendingAnswer.call), + {pendingAnswer.provenance}}); + table.delta.push_back(answerIndex); + ++evaluation->deltaAnswers; + progress = true; + } + firstRound = false; + if (!progress) break; + } + } + + tableRounds_ += evaluation->rounds; + tableDeltaAnswers_ += evaluation->deltaAnswers; + provenanceNodes_ += evaluation->provenance.size(); + return evaluation; +} + +bool Interpreter::tableCallAnswers( + const Call& call, + const Env& env, + std::vector& bindings, + std::shared_ptr* evaluationOut, + bool requireRecursive) { + const SymbolId id = + call.nameId == 0 ? symbolIdForName(call.name) : call.nameId; + auto evaluation = + tableEvaluationFor(call.name, id, requireRecursive); + if (!evaluation) return false; + if (evaluationOut) *evaluationOut = evaluation; + const auto table = evaluation->predicates.find(id); + if (table == evaluation->predicates.end()) return true; + for (const auto& answer : table->second.answers) { + for (auto& unified : + unifyCallAlternatives(call, answer.call, env)) { + bindings.push_back( + TableBinding{std::move(unified), answer.provenance}); + } + } + return true; +} + +namespace { + +std::shared_ptr reasoningMapValue( + const std::shared_ptr& value, + const std::string& key) { + const auto map = std::dynamic_pointer_cast(value); + if (!map) return {}; + const SymbolId keyId = symbolIdForName(key); + for (const auto& entry : map->entries) { + if (entry.keyId == keyId && entry.key == key) return entry.value; + } + return {}; +} + +void reasoningSetValue(std::vector& entries, + const std::string& key, + std::shared_ptr value) { + const SymbolId keyId = symbolIdForName(key); + for (auto& entry : entries) { + if (entry.keyId == keyId && entry.key == key) { + entry.value = std::move(value); + return; + } + } + entries.emplace_back(key, std::move(value)); +} + +std::shared_ptr callAsFact(const Call& call) { + std::vector entries; + entries.emplace_back( + internalSymbolString(InternalSymbolKind::Type), + std::make_shared(call.name)); + for (std::size_t i = 0; i < call.args.size(); ++i) { + const auto& argument = call.args[i]; + entries.emplace_back( + argument.name.empty() + ? "value" + std::to_string(i) + : argument.name, + argument.value ? argument.value->clone() + : std::make_shared()); + } + return markFact( + std::make_shared(std::move(entries)), call.name); +} + +std::shared_ptr stringArray( + const std::set& values) { + std::vector> items; + items.reserve(values.size()); + for (const auto& value : values) { + items.push_back(std::make_shared(value)); + } + return std::make_shared(std::move(items)); +} + +std::shared_ptr factIdArray( + const std::set& values) { + std::vector> items; + items.reserve(values.size()); + for (const std::uint64_t value : values) { + items.push_back(markFact(std::make_shared( + std::vector{ + {"__type", std::make_shared("FactReference")}, + {"fact_id", std::make_shared( + std::to_string(value))}}), "FactReference")); + } + return std::make_shared(std::move(items)); +} + +bool finiteUnitInterval(double value) { + return std::isfinite(value) && value >= 0.0 && value <= 1.0; +} + +} // namespace + +std::shared_ptr Interpreter::materializeDerivationResult( + const Call& query, + const std::vector& supporting, + const std::vector& opposing, + const std::shared_ptr& positiveEvaluation, + const std::shared_ptr& negativeEvaluation) const { + struct Summary { + std::set factIds; + std::set rules; + std::vector> explanation; + }; + const auto summarize = [](const std::vector& bindings, + const std::shared_ptr& evaluation) { + Summary result; + if (!evaluation) return result; + std::unordered_set visited; + std::unordered_set explainedFacts; + std::set> + explainedRules; + std::vector pending; + for (const auto& binding : bindings) { + pending.insert( + pending.end(), + binding.provenance.begin(), + binding.provenance.end()); + } + while (!pending.empty()) { + const std::size_t handle = pending.back(); + pending.pop_back(); + if (!visited.insert(handle).second || + handle >= evaluation->provenance.size()) continue; + const auto& node = evaluation->provenance[handle]; + if (node.kind == ProvenanceNode::Kind::Fact) { + result.factIds.insert(node.factId); + if (explainedFacts.insert(node.factId).second) { + result.explanation.push_back(markFact(std::make_shared( + std::vector{ + {"__type", std::make_shared( + "FactProvenance")}, + {"fact_id", std::make_shared( + std::to_string(node.factId))}}), "FactProvenance")); + } + } else { + result.rules.insert(node.rule); + const auto identity = std::make_tuple( + node.rule, + node.span.startLine, + node.span.startColumn, + node.span.endLine, + node.span.endColumn); + if (explainedRules.insert(identity).second) { + result.explanation.push_back(markFact(std::make_shared( + std::vector{ + {"__type", std::make_shared( + "RuleProvenance")}, + {"rule", std::make_shared(node.rule)}, + {"start_line", std::make_shared( + node.span.startLine)}, + {"start_column", std::make_shared( + node.span.startColumn)}, + {"end_line", std::make_shared( + node.span.endLine)}, + {"end_column", std::make_shared( + node.span.endColumn)}}), "RuleProvenance")); + } + } + pending.insert( + pending.end(), node.parents.begin(), node.parents.end()); + } + return result; + }; + + const Summary positive = summarize(supporting, positiveEvaluation); + const Summary negative = summarize(opposing, negativeEvaluation); + const bool hasPositive = !supporting.empty(); + const bool hasNegative = !opposing.empty(); + const std::string truth = + hasPositive && hasNegative ? "both" : + hasPositive ? "proved" : + hasNegative ? "disproved" : "unknown"; + + std::vector> explanation = + positive.explanation; + explanation.insert( + explanation.end(), + negative.explanation.begin(), + negative.explanation.end()); + + return markFact(std::make_shared(std::vector{ + {"__type", std::make_shared("DerivationResult")}, + {"conclusion", callAsFact(query)}, + {"truth_status", std::make_shared(truth)}, + {"exact", std::make_shared(true)}, + {"fuzzy_degree", std::make_shared()}, + {"confidence", std::make_shared()}, + {"probability", std::make_shared()}, + {"similarity", std::make_shared()}, + {"contradictory", std::make_shared( + hasPositive && hasNegative)}, + {"supporting_facts", factIdArray(positive.factIds)}, + {"opposing_facts", factIdArray(negative.factIds)}, + {"supporting_rules", stringArray(positive.rules)}, + {"opposing_rules", stringArray(negative.rules)}, + {"support_count", std::make_shared( + static_cast(supporting.size()))}, + {"opposition_count", std::make_shared( + static_cast(opposing.size()))}, + {"explanation_path", std::make_shared( + std::move(explanation))}}), "DerivationResult"); +} + +bool Interpreter::evalReasoningContrary( + const TermExpr& term, + const Env& env, + std::shared_ptr& out) { + std::shared_ptr positiveValue; + std::shared_ptr negativeValue; + for (std::size_t i = 0; i < term.args.size(); ++i) { + const auto& argument = term.args[i]; + std::shared_ptr resolved; + if (!evalExprValue(argument.value, env, resolved)) return false; + if (argument.name == "positive" || + (argument.name.empty() && i == 0)) { + positiveValue = std::move(resolved); + } else if (argument.name == "negative" || + (argument.name.empty() && i == 1)) { + negativeValue = std::move(resolved); + } + } + const auto positive = + std::dynamic_pointer_cast(positiveValue); + const auto negative = + std::dynamic_pointer_cast(negativeValue); + if (!positive || positive->value.empty() || + !negative || negative->value.empty()) { + throw InterpreterError( + "Reasoning.contrary expects non-empty string predicates " + "'positive' and 'negative'"); + } + if (positive->value == negative->value) { + throw InterpreterError( + "Reasoning.contrary predicates must be different"); + } + const SymbolId positiveId = symbolIdForName(positive->value); + const auto existing = contraries_.find(positiveId); + if (existing != contraries_.end() && + existing->second != negative->value) { + throw InterpreterError( + "Reasoning.contrary already maps '" + positive->value + + "' to '" + existing->second + "'"); + } + contraries_[positiveId] = negative->value; + out = markFact(std::make_shared(std::vector{ + {"__type", std::make_shared( + "ContraryRegistration")}, + {"positive", positive->clone()}, + {"negative", negative->clone()}}), "ContraryRegistration"); + return true; +} + +bool Interpreter::evalReasoningProve( + const TermExpr& term, + const Env& env, + std::shared_ptr& out) { + const Arg* queryArgument = nullptr; + for (std::size_t i = 0; i < term.args.size(); ++i) { + if (term.args[i].name == "query" || + (term.args[i].name.empty() && i == 0)) { + queryArgument = &term.args[i]; + break; + } + } + if (!queryArgument) { + throw InterpreterError("Reasoning.prove expects 'query'"); + } + + Call query; + if (const auto queryTerm = + std::dynamic_pointer_cast(queryArgument->value)) { + if (queryTerm->builtinId != BuiltinId::Unknown) { + throw InterpreterError( + "Reasoning.prove expects a relational predicate, not a builtin"); + } + query = Call(queryTerm->name, {}); + query.nameId = queryTerm->nameId; + for (const auto& argument : queryTerm->args) { + std::shared_ptr value; + if (!evalExprValue(argument.value, env, value) || + !isGroundLiteral(value)) { + throw InterpreterError( + "Reasoning.prove query arguments must be ground"); + } + query.args.emplace_back(argument.name, argument.nameId, std::move(value)); + } + } else { + std::shared_ptr resolved; + if (!evalExprValue(queryArgument->value, env, resolved)) { + return false; + } + const auto map = std::dynamic_pointer_cast(resolved); + const auto type = std::dynamic_pointer_cast( + reasoningMapValue( + resolved, + internalSymbolString(InternalSymbolKind::Type))); + if (!map || !type || type->value.empty()) { + throw InterpreterError( + "Reasoning.prove expects a typed fact query"); + } + query = Call(type->value, {}); + for (const auto& entry : map->entries) { + if (entry.keyId == InternalSymbol::TypeId || + entry.keyId == InternalSymbol::ParentId) continue; + if (!isGroundLiteral(entry.value)) { + throw InterpreterError( + "Reasoning.prove query arguments must be ground"); + } + query.args.emplace_back(entry.key, entry.keyId, entry.value->clone()); + } + } + + if (!findClauses(query.name, query.nameId) && + !memory_.hasActiveRelation(query.name, query.nameId) && + !contraries_.count(query.nameId)) { + throw InterpreterError( + "Unknown reasoning predicate '" + query.name + "'"); + } + + std::vector supporting; + std::shared_ptr positiveEvaluation; + if (!tableCallAnswers( + query, + env, + supporting, + &positiveEvaluation, + false)) { + throw InterpreterError( + "Reasoning.prove requires a pure relational predicate: '" + + query.name + "'"); + } + + std::vector opposing; + std::shared_ptr negativeEvaluation; + const auto contrary = contraries_.find(query.nameId); + if (contrary != contraries_.end()) { + Call negative(contrary->second, {}); + negative.args.reserve(query.args.size()); + for (const auto& argument : query.args) { + negative.args.emplace_back( + argument.name, argument.value->clone()); + } + if (findClauses(negative.name, negative.nameId) || + memory_.hasActiveRelation(negative.name, negative.nameId)) { + if (!tableCallAnswers( + negative, + env, + opposing, + &negativeEvaluation, + false)) { + throw InterpreterError( + "Contrary predicate '" + negative.name + + "' is not a pure relational predicate"); + } + } + } + + out = materializeDerivationResult( + query, + supporting, + opposing, + positiveEvaluation, + negativeEvaluation); + return true; +} + +bool Interpreter::evalReasoningGrade( + const TermExpr& term, + const Env& env, + std::shared_ptr& out, + const std::shared_ptr& exact) { + std::shared_ptr evidenceValue; + std::shared_ptr profileValue; + std::shared_ptr conclusionValue; + std::shared_ptr probabilityValue; + std::shared_ptr similarityValue; + for (std::size_t i = 0; i < term.args.size(); ++i) { + const auto& argument = term.args[i]; + if (argument.name == "query") continue; + std::shared_ptr value; + if (argument.name == "conclusion") { + // A conclusion is data, not an evaluation request. Preserve a + // predicate-shaped term as a typed fact value instead of invoking + // a rule with the same name. + if (const auto conclusion = + std::dynamic_pointer_cast(argument.value)) { + std::vector fields; + fields.emplace_back( + "__type", + std::make_shared(conclusion->name)); + for (const auto& field : conclusion->args) { + std::shared_ptr resolved; + if (!evalExprValue(field.value, env, resolved)) return false; + fields.emplace_back(field.name, field.nameId, std::move(resolved)); + } + value = markFact( + std::make_shared(std::move(fields)), + conclusion->name); + } + } + if (!value && !evalExprValue(argument.value, env, value)) return false; + if (argument.name == "evidence" || + (argument.name.empty() && i == 0)) { + evidenceValue = std::move(value); + } else if (argument.name == "profile") { + profileValue = std::move(value); + } else if (argument.name == "conclusion") { + conclusionValue = std::move(value); + } else if (argument.name == "probability") { + probabilityValue = std::move(value); + } else if (argument.name == "similarity") { + similarityValue = std::move(value); + } + } + + if (exact && !conclusionValue) { + conclusionValue = reasoningMapValue(exact, "conclusion"); + } + if (!conclusionValue) conclusionValue = std::make_shared(); + + if (profileValue) { + const auto profileType = std::dynamic_pointer_cast( + reasoningMapValue(profileValue, "__type")); + if (!profileType || profileType->value != "ReasoningProfile") { + throw InterpreterError( + "Reasoning.grade profile must be ReasoningProfile(...)"); + } + const auto requirePolicy = + [&](const std::string& field, + std::initializer_list allowed) { + const auto value = std::dynamic_pointer_cast( + reasoningMapValue(profileValue, field)); + if (!value) return; + for (const char* candidate : allowed) { + if (value->value == candidate) return; + } + throw InterpreterError( + "Unsupported ReasoningProfile " + field + + " policy '" + value->value + "'"); + }; + requirePolicy("conjunction", {"minimum"}); + requirePolicy("disjunction", {"maximum"}); + requirePolicy("evidence_aggregation", {"maximum"}); + requirePolicy("negation", {"standard", "one_minus"}); + } else { + profileValue = markFact(std::make_shared( + std::vector{ + {"__type", std::make_shared( + "ReasoningProfile")}, + {"name", std::make_shared("default")}, + {"conjunction", std::make_shared("minimum")}, + {"disjunction", std::make_shared("maximum")}, + {"evidence_aggregation", std::make_shared( + "maximum")}, + {"negation", std::make_shared("one_minus")}}), + "ReasoningProfile"); + } + + std::vector> evidenceItems; + if (evidenceValue) { + const auto array = + std::dynamic_pointer_cast(evidenceValue); + if (!array) { + throw InterpreterError( + "Reasoning.grade evidence must be an array"); + } + evidenceItems = array->items; + } + + bool hasSupport = false; + bool hasOpposition = false; + double support = 0.0; + double opposition = 0.0; + double confidence = 0.0; + for (const auto& evidence : evidenceItems) { + const auto type = std::dynamic_pointer_cast( + reasoningMapValue(evidence, "__type")); + if (!type || + (type->value != "Evidence" && + type->value != "FuzzyMembership" && + type->value != "Comparison")) { + throw InterpreterError( + "Reasoning.grade entries must be Evidence(...), " + "FuzzyMembership(...), or Comparison(...)"); + } + if (type->value == "Comparison") { + const auto similarity = std::dynamic_pointer_cast( + reasoningMapValue(evidence, "similarity")); + const auto confidenceValue = std::dynamic_pointer_cast( + reasoningMapValue(evidence, "relationalConfidence")); + const auto contradictory = std::dynamic_pointer_cast( + reasoningMapValue(evidence, "contradictory")); + const auto conflicting = std::dynamic_pointer_cast( + reasoningMapValue(evidence, "conflictingFields")); + if (!similarity || !finiteUnitInterval(similarity->value)) { + throw InterpreterError( + "Comparison evidence similarity must be finite and between 0 and 1"); + } + const double reliability = confidenceValue + ? confidenceValue->value : 1.0; + if (!finiteUnitInterval(reliability)) { + throw InterpreterError( + "Comparison evidence relationalConfidence must be between 0 and 1"); + } + const bool opposed = (contradictory && contradictory->value) || + (conflicting && !conflicting->items.empty()); + confidence = std::max(confidence, reliability); + if (opposed) { + hasOpposition = true; + opposition = std::max(opposition, + (1.0 - similarity->value) * reliability); + } + if (similarity->value > 0.0) { + hasSupport = true; + support = std::max(support, similarity->value * reliability); + } + continue; + } + const auto degree = std::dynamic_pointer_cast( + reasoningMapValue(evidence, "degree")); + const auto reliabilityValue = + std::dynamic_pointer_cast( + reasoningMapValue(evidence, "reliability")); + const double reliability = + reliabilityValue ? reliabilityValue->value : 1.0; + if (!degree || !finiteUnitInterval(degree->value) || + !finiteUnitInterval(reliability)) { + throw InterpreterError( + "Reasoning grades and reliability must be finite values " + "between 0 and 1"); + } + bool opposing = false; + if (const auto polarity = std::dynamic_pointer_cast( + reasoningMapValue(evidence, "polarity"))) { + opposing = + polarity->value == "oppose" || + polarity->value == "opposing" || + polarity->value == "refute"; + if (!opposing && polarity->value != "support" && + polarity->value != "supporting") { + throw InterpreterError( + "Evidence polarity must be 'support' or 'oppose'"); + } + } else if (const auto supports = + std::dynamic_pointer_cast( + reasoningMapValue(evidence, "supports"))) { + opposing = !supports->value; + } + const double discounted = degree->value * reliability; + confidence = std::max(confidence, reliability); + if (opposing) { + hasOpposition = true; + opposition = std::max(opposition, discounted); + } else { + hasSupport = true; + support = std::max(support, discounted); + } + } + + const auto validatedOptionalGrade = + [&](const std::shared_ptr& value, + const std::string& name) -> std::shared_ptr { + if (!value) return std::make_shared(); + const auto number = + std::dynamic_pointer_cast(value); + if (!number || !finiteUnitInterval(number->value)) { + throw InterpreterError( + "Reasoning " + name + + " must be a finite value between 0 and 1"); + } + return number->clone(); + }; + + std::string truth = "unknown"; + if (exact) { + if (const auto status = std::dynamic_pointer_cast( + reasoningMapValue(exact, "truth_status"))) { + truth = status->value; + } + } + const std::string recommendation = + support > opposition ? "recommend" : + opposition > support ? "reject" : "undetermined"; + + std::vector resultEntries; + if (exact) { + resultEntries.reserve(exact->entries.size() + 8); + for (const auto& entry : exact->entries) { + resultEntries.emplace_back(entry.key, entry.keyId, entry.value->clone()); + } + } + reasoningSetValue(resultEntries, "__type", + std::make_shared("DerivationResult")); + reasoningSetValue(resultEntries, "conclusion", conclusionValue->clone()); + reasoningSetValue(resultEntries, "truth_status", + std::make_shared(truth)); + reasoningSetValue(resultEntries, "exact", + std::make_shared(static_cast(exact))); + reasoningSetValue(resultEntries, "fuzzy_degree", hasSupport + ? std::shared_ptr(std::make_shared(support)) + : std::shared_ptr(std::make_shared())); + reasoningSetValue(resultEntries, "support_degree", hasSupport + ? std::shared_ptr(std::make_shared(support)) + : std::shared_ptr(std::make_shared())); + reasoningSetValue(resultEntries, "opposition_degree", hasOpposition + ? std::shared_ptr(std::make_shared(opposition)) + : std::shared_ptr(std::make_shared())); + reasoningSetValue(resultEntries, "confidence", evidenceItems.empty() + ? std::shared_ptr(std::make_shared()) + : std::shared_ptr(std::make_shared(confidence))); + reasoningSetValue(resultEntries, "probability", + validatedOptionalGrade(probabilityValue, "probability")); + reasoningSetValue(resultEntries, "similarity", + validatedOptionalGrade(similarityValue, "similarity")); + reasoningSetValue(resultEntries, "contradictory", + std::make_shared( + truth == "both" || (hasSupport && hasOpposition))); + reasoningSetValue(resultEntries, "recommendation", + std::make_shared(recommendation)); + reasoningSetValue(resultEntries, "profile", profileValue->clone()); + reasoningSetValue(resultEntries, "evidence", + std::make_shared(evidenceItems)); + out = markFact( + std::make_shared(std::move(resultEntries)), + "DerivationResult"); + return true; +} + +bool Interpreter::evalReasoningBuiltin( + const TermExpr& term, + const Env& env, + std::shared_ptr& out) { + switch (term.builtinId) { + case BuiltinId::ReasoningContrary: + return evalReasoningContrary(term, env, out); + case BuiltinId::ReasoningProve: + return evalReasoningProve(term, env, out); + case BuiltinId::ReasoningGrade: + return evalReasoningGrade(term, env, out); + case BuiltinId::ReasoningDecide: { + std::shared_ptr exactValue; + if (!evalReasoningProve(term, env, exactValue)) return false; + const auto exact = + std::dynamic_pointer_cast(exactValue); + return evalReasoningGrade(term, env, out, exact); + } + default: + return false; + } +} + +} // namespace Felidae diff --git a/src/SentencePieceModel.cpp b/src/SentencePieceModel.cpp deleted file mode 100644 index 160972c..0000000 --- a/src/SentencePieceModel.cpp +++ /dev/null @@ -1,172 +0,0 @@ -#include "SentencePieceModel.h" - -#include "FelidaeGrammar.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#endif - -namespace Felidae { -namespace { - -class Sha256 final { -public: - void update(std::span bytes) { - for (const auto byte : bytes) { - block_[blockSize_++] = byte; - bitCount_ += 8; - if (blockSize_ == block_.size()) { transform(); blockSize_ = 0; } - } - } - std::array finish() { - block_[blockSize_++] = 0x80; - if (blockSize_ > 56) { - while (blockSize_ < block_.size()) block_[blockSize_++] = 0; - transform(); blockSize_ = 0; - } - while (blockSize_ < 56) block_[blockSize_++] = 0; - for (int shift = 56; shift >= 0; shift -= 8) block_[blockSize_++] = static_cast(bitCount_ >> shift); - transform(); - std::array digest{}; - for (std::size_t index = 0; index < state_.size(); ++index) { - digest[4 * index] = static_cast(state_[index] >> 24); - digest[4 * index + 1] = static_cast(state_[index] >> 16); - digest[4 * index + 2] = static_cast(state_[index] >> 8); - digest[4 * index + 3] = static_cast(state_[index]); - } - return digest; - } -private: - static constexpr std::array k{ - 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, - 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, - 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, - 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, - 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, - 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, - 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, - 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}; - static std::uint32_t rotate(std::uint32_t value, unsigned count) { return (value >> count) | (value << (32u - count)); } - void transform() { - std::array words{}; - for (std::size_t index = 0; index < 16; ++index) { - words[index] = (static_cast(block_[4 * index]) << 24) | - (static_cast(block_[4 * index + 1]) << 16) | - (static_cast(block_[4 * index + 2]) << 8) | - block_[4 * index + 3]; - } - for (std::size_t index = 16; index < words.size(); ++index) { - const auto s0 = rotate(words[index - 15], 7) ^ rotate(words[index - 15], 18) ^ (words[index - 15] >> 3); - const auto s1 = rotate(words[index - 2], 17) ^ rotate(words[index - 2], 19) ^ (words[index - 2] >> 10); - words[index] = words[index - 16] + s0 + words[index - 7] + s1; - } - auto a=state_[0],b=state_[1],c=state_[2],d=state_[3],e=state_[4],f=state_[5],g=state_[6],h=state_[7]; - for (std::size_t index = 0; index < words.size(); ++index) { - const auto s1=rotate(e,6)^rotate(e,11)^rotate(e,25), choice=(e&f)^((~e)&g); - const auto temporary1=h+s1+choice+k[index]+words[index]; - const auto s0=rotate(a,2)^rotate(a,13)^rotate(a,22), majority=(a&b)^(a&c)^(b&c); - const auto temporary2=s0+majority; - h=g;g=f;f=e;e=d+temporary1;d=c;c=b;b=a;a=temporary1+temporary2; - } - state_[0]+=a;state_[1]+=b;state_[2]+=c;state_[3]+=d;state_[4]+=e;state_[5]+=f;state_[6]+=g;state_[7]+=h; - } - std::array state_{0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}; - std::array block_{}; - std::size_t blockSize_ = 0; - std::uint64_t bitCount_ = 0; -}; - -std::filesystem::path sentencePieceModelPath() { - const std::filesystem::path configured(FELIDAE_SENTENCEPIECE_MODEL_PATH); - if (std::filesystem::is_regular_file(configured)) return configured; -#ifdef _WIN32 - std::wstring buffer(32'768, L'\0'); - const auto length = GetModuleFileNameW(nullptr, buffer.data(), static_cast(buffer.size())); - if (length != 0 && length < buffer.size()) { - buffer.resize(length); - const auto portable = std::filesystem::path(buffer).parent_path() / "models" / "felidae.model"; - if (std::filesystem::is_regular_file(portable)) return portable; - } -#endif - throw std::runtime_error("Unable to locate fixed Felidae SentencePiece model"); -} - -void validateBuiltins(const sentencepiece::SentencePieceProcessor& model) { - for (std::size_t index = 0; index < std::size(kBuiltinTokens); ++index) { - const auto& builtin = kBuiltinTokens[index]; - const int expected = kFelidaeBuiltinSentencePieceIds[index]; - const int actual = model.PieceToId(std::string(builtin.spelling)); - int matchingPieceCount = 0; - for (int id = 0; id < model.GetPieceSize(); ++id) { - if (model.IdToPiece(id) == builtin.spelling) ++matchingPieceCount; - } - if (actual != expected || actual == TokenId::UNKNOWN || - model.IdToPiece(actual) != builtin.spelling || matchingPieceCount != 1) { - throw std::runtime_error("felidae.model built-in ID mismatch for '" + - std::string(builtin.spelling) + "'"); - } - sentencepiece::SentencePieceText encoded; - const auto status = model.Encode(std::string(builtin.spelling), &encoded); - if (!status.ok() || encoded.pieces_size() != 1 || - static_cast(encoded.pieces(0).id()) != actual || - encoded.pieces(0).begin() != 0 || - encoded.pieces(0).end() != builtin.spelling.size()) { - throw std::runtime_error("felidae.model splits or duplicates built-in '" + - std::string(builtin.spelling) + "'"); - } - } -} - -} // namespace - -const sentencepiece::SentencePieceProcessor& felidaeSentencePieceModel() { - static std::once_flag once; - static std::unique_ptr model; - std::call_once(once, [] { - auto loaded = std::make_unique(); - const auto modelPath = sentencePieceModelPath(); - const auto status = loaded->Load(modelPath.string()); - if (!status.ok()) { - throw std::runtime_error("Unable to load fixed Felidae SentencePiece model: " + - status.ToString()); - } - validateBuiltins(*loaded); - model = std::move(loaded); - }); - return *model; -} - -std::string felidaeSentencePieceModelIdentity() { - (void)felidaeSentencePieceModel(); - std::ifstream input(sentencePieceModelPath(), std::ios::binary); - if (!input) throw std::runtime_error("Unable to hash fixed Felidae SentencePiece model"); - Sha256 sha; - std::array buffer{}; - while (input) { - input.read(reinterpret_cast(buffer.data()), static_cast(buffer.size())); - const auto size = input.gcount(); - if (size > 0) sha.update(std::span(buffer.data(), static_cast(size))); - } - if (!input.eof()) throw std::runtime_error("Unable to read fixed Felidae SentencePiece model"); - std::ostringstream result; - result << "sha256:" << std::hex << std::setfill('0'); - for (const auto byte : sha.finish()) result << std::setw(2) << static_cast(byte); - return result.str(); -} - -} // namespace Felidae diff --git a/src/SentencePieceModel.h b/src/SentencePieceModel.h deleted file mode 100644 index c65f83d..0000000 --- a/src/SentencePieceModel.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include - -#include - -namespace sentencepiece { -class SentencePieceProcessor; -} - -namespace Felidae { - -// Loads the fixed, checked-in model once. This performs no training and -// starts no worker threads; callers only use it to encode complete sources. -const sentencepiece::SentencePieceProcessor& felidaeSentencePieceModel(); -// Exact executable-vocabulary identity used by FELBIR trust boundaries. -std::string felidaeSentencePieceModelIdentity(); - -} // namespace Felidae diff --git a/src/Symbol.h b/src/Symbol.h index 92264c1..4529998 100644 --- a/src/Symbol.h +++ b/src/Symbol.h @@ -1,10 +1,10 @@ #pragma once -#include #include +#include +#include #include #include -#include #include #include #include @@ -13,7 +13,7 @@ namespace Felidae { -using SymbolId = std::uint32_t; +using SymbolId = std::uint64_t; namespace InternalSymbol { inline constexpr SymbolId TypeId = 1; @@ -22,152 +22,141 @@ inline constexpr SymbolId ReturnId = 3; inline constexpr SymbolId SystemId = 4; inline constexpr SymbolId ResultId = 5; inline constexpr SymbolId SystemResultId = 6; -} // namespace InternalSymbol +} enum class InternalSymbolKind : SymbolId { - Type = InternalSymbol::TypeId, - Parent = InternalSymbol::ParentId, - Return = InternalSymbol::ReturnId, - System = InternalSymbol::SystemId, - Result = InternalSymbol::ResultId, - SystemResult = InternalSymbol::SystemResultId + Type = InternalSymbol::TypeId, + Parent = InternalSymbol::ParentId, + Return = InternalSymbol::ReturnId, + System = InternalSymbol::SystemId, + Result = InternalSymbol::ResultId, + SystemResult = InternalSymbol::SystemResultId }; inline std::string_view internalSymbolName(InternalSymbolKind kind) { - switch (kind) { - case InternalSymbolKind::Type: - return "__type"; - case InternalSymbolKind::Parent: - return "__parent"; - case InternalSymbolKind::Return: - return "__return"; - case InternalSymbolKind::System: - return "system"; - case InternalSymbolKind::Result: - return "result"; - case InternalSymbolKind::SystemResult: - return "system:result"; - } - return ""; + switch (kind) { + case InternalSymbolKind::Type: return "__type"; + case InternalSymbolKind::Parent: return "__parent"; + case InternalSymbolKind::Return: return "__return"; + case InternalSymbolKind::System: return "system"; + case InternalSymbolKind::Result: return "result"; + case InternalSymbolKind::SystemResult: return "system:result"; + } + return ""; } inline std::string internalSymbolString(InternalSymbolKind kind) { - return std::string(internalSymbolName(kind)); + return std::string(internalSymbolName(kind)); } -// AST symbols use short-lived compiler handles only. They are never persisted -// or sent to the VM: the compiler replaces them with module-local indexes into -// full SentencePiece ID sequences before verification and binary emission. +// Identifier hashes are not identities: two different names are allowed to +// have the same hash. The old implementation used std::hash directly as a +// SymbolId and therefore had to retain and compare strings throughout every +// hot lookup to defend against collisions. This process-wide interner gives +// every spelling one canonical, collision-free id while keeping source text +// on AST nodes for diagnostics and serialization. class SymbolInterner { public: - SymbolInterner() { - reserve(InternalSymbol::TypeId, - internalSymbolName(InternalSymbolKind::Type)); - reserve(InternalSymbol::ParentId, - internalSymbolName(InternalSymbolKind::Parent)); - reserve(InternalSymbol::ReturnId, - internalSymbolName(InternalSymbolKind::Return)); - reserve(InternalSymbol::SystemId, - internalSymbolName(InternalSymbolKind::System)); - reserve(InternalSymbol::ResultId, - internalSymbolName(InternalSymbolKind::Result)); - reserve(InternalSymbol::SystemResultId, - internalSymbolName(InternalSymbolKind::SystemResult)); - } - - SymbolId intern(std::string_view name) { - if (name.empty()) - return 0; - const std::string key(name); - std::lock_guard lock(mutex_); - const auto found = ids_.find(key); - if (found != ids_.end()) - return found->second; - if (nextSourceId_ == std::numeric_limits::max()) { - throw std::overflow_error("Felidae source symbol handle space exhausted"); + static constexpr SymbolId GeneratedIdBase = SymbolId{1} << 63U; + SymbolInterner() { + reserve(InternalSymbol::TypeId, internalSymbolName(InternalSymbolKind::Type)); + reserve(InternalSymbol::ParentId, internalSymbolName(InternalSymbolKind::Parent)); + reserve(InternalSymbol::ReturnId, internalSymbolName(InternalSymbolKind::Return)); + reserve(InternalSymbol::SystemId, internalSymbolName(InternalSymbolKind::System)); + reserve(InternalSymbol::ResultId, internalSymbolName(InternalSymbolKind::Result)); + reserve(InternalSymbol::SystemResultId, internalSymbolName(InternalSymbolKind::SystemResult)); } - const SymbolId id = nextSourceId_++; - ids_.emplace(key, id); - names_.emplace(id, key); - return id; - } - - SymbolId intern(std::string_view name, - std::span pieces) { - const auto id = intern(name); - if (id == 0 || pieces.empty()) - return id; - std::lock_guard lock(mutex_); - auto &stored = pieces_[id]; - if (stored.empty()) { - stored.assign(pieces.begin(), pieces.end()); - } else if (!std::equal(stored.begin(), stored.end(), pieces.begin(), - pieces.end())) { - throw std::logic_error( - "one source symbol has inconsistent SentencePiece sequences"); + + SymbolId intern(std::string_view name) { + if (name.empty()) return 0; + const std::string key(name); + std::lock_guard lock(mutex_); + const auto found = ids_.find(key); + if (found != ids_.end()) return found->second; + const SymbolId id = nextId_++; + ids_.emplace(key, id); + names_.push_back(key); + return id; + } + + SymbolId makeGenerated() { + std::lock_guard lock(mutex_); + if (nextGeneratedId_ == std::numeric_limits::max()) { + throw std::overflow_error("Felidae generated SymbolId space exhausted"); + } + const SymbolId id = nextGeneratedId_++; + generatedNames_.emplace(id, "$g" + std::to_string(id - GeneratedIdBase)); + return id; + } + + std::string name(SymbolId id) const { + if (id == 0) return {}; + std::lock_guard lock(mutex_); + const auto reserved = reservedNames_.find(id); + if (reserved != reservedNames_.end()) return reserved->second; + const auto generated = generatedNames_.find(id); + if (generated != generatedNames_.end()) return generated->second; + if (id < 1024) return {}; + const std::size_t index = static_cast(id - 1024); + return index < names_.size() ? names_[index] : std::string{}; } - return id; - } - - std::string name(SymbolId id) const { - if (id == 0) - return {}; - std::lock_guard lock(mutex_); - const auto reserved = reservedNames_.find(id); - if (reserved != reservedNames_.end()) - return reserved->second; - const auto found = names_.find(id); - return found == names_.end() ? std::string{} : found->second; - } - - std::vector pieces(SymbolId id) const { - std::lock_guard lock(mutex_); - const auto found = pieces_.find(id); - return found == pieces_.end() ? std::vector{} - : found->second; - } private: - void reserve(SymbolId id, std::string_view name) { - ids_.emplace(std::string(name), id); - reservedNames_.emplace(id, std::string(name)); - } - mutable std::mutex mutex_; - std::unordered_map ids_; - std::unordered_map reservedNames_; - std::unordered_map names_; - std::unordered_map> pieces_; - SymbolId nextSourceId_ = 7; + void reserve(SymbolId id, std::string_view name) { + ids_.emplace(std::string(name), id); + reservedNames_.emplace(id, std::string(name)); + } + + mutable std::mutex mutex_; + std::unordered_map ids_; + std::unordered_map reservedNames_; + std::unordered_map generatedNames_; + std::vector names_; + SymbolId nextId_ = 1024; + SymbolId nextGeneratedId_ = GeneratedIdBase; }; -inline SymbolInterner &symbolInterner() { - static SymbolInterner interner; - return interner; +inline SymbolInterner& symbolInterner() { + static SymbolInterner interner; + return interner; } inline SymbolId symbolIdForName(std::string_view name) { - return symbolInterner().intern(name); -} - -inline SymbolId symbolIdForName(const std::string &name) { - return symbolIdForName(std::string_view(name)); + // Parsing fact-heavy sources repeatedly sees the same small set of type + // and field identifiers. Avoid taking the process-wide interner mutex for + // every occurrence while still confirming the spelling on hash collision. + struct LocalEntry { + std::size_t hash = 0; + std::string spelling; + SymbolId id = 0; + }; + thread_local std::array local{}; + const std::size_t hash = std::hash{}(name); + auto& entry = local[hash % local.size()]; + if (entry.id != 0 && entry.hash == hash && entry.spelling == name) { + return entry.id; + } + const SymbolId id = symbolInterner().intern(name); + entry.hash = hash; + entry.spelling.assign(name.data(), name.size()); + entry.id = id; + return id; } -inline SymbolId symbolIdForName(const char *name) { - return symbolIdForName(std::string_view(name ? name : "")); +inline SymbolId symbolIdForName(const std::string& name) { + return symbolIdForName(std::string_view(name)); } -inline SymbolId symbolIdForPieces(std::string_view name, - std::span pieces) { - return symbolInterner().intern(name, pieces); +inline SymbolId symbolIdForName(const char* name) { + return symbolIdForName(std::string_view(name ? name : "")); } inline std::string symbolNameForId(SymbolId id) { - return symbolInterner().name(id); + return symbolInterner().name(id); } -inline std::vector symbolPiecesForId(SymbolId id) { - return symbolInterner().pieces(id); +inline bool isInternalGeneratedSymbolId(SymbolId id) { + return id != 0 && id >= SymbolInterner::GeneratedIdBase; } } // namespace Felidae diff --git a/src/Tokenizer.cpp b/src/Tokenizer.cpp new file mode 100644 index 0000000..9064c89 --- /dev/null +++ b/src/Tokenizer.cpp @@ -0,0 +1,276 @@ +#include "Tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae { +namespace { + +std::string decodeModelSpelling(std::string_view spelling) { + std::string result; + for (std::size_t index = 0; index < spelling.size();) { + if (index + 6 == spelling.size() && spelling[index] == '<' && + spelling[index + 1] == '0' && spelling[index + 2] == 'x' && + spelling[index + 5] == '>') { + const auto hex = [](char value) -> int { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + if (value >= 'A' && value <= 'F') return value - 'A' + 10; + return -1; + }; + const int high = hex(spelling[index + 3]); + const int low = hex(spelling[index + 4]); + if (high >= 0 && low >= 0) { + result.push_back(static_cast((high << 4) | low)); + index += 6; + continue; + } + } + result.push_back(spelling[index++]); + } + return result; +} + +std::string encodeModelSpelling(std::string_view bytes) { + std::ostringstream output; + for (const unsigned char value : bytes) { + if (value >= 0x20 && value != 0x7f && value != '<' && value != '>') + output << static_cast(value); + else + output << "<0x" << std::uppercase << std::hex << std::setw(2) + << std::setfill('0') << static_cast(value) << ">" + << std::dec; + } + return output.str(); +} + +bool isWordByte(unsigned char value) { + return value >= 0x80 || std::isalnum(value) != 0 || value == '_'; +} + +const std::array &fixedVocabulary() { + static constexpr std::array values{ + "", "import", "not", "and", "or", "then", "as", "if", + "else", "return", "where", "extend", "lambda", "true", "false", + "nil", "(", ")", "{", "}", "[", "]", ",", ":", ".", "|", "?", + "@", ":=", "::", "=>", "+", "-", "*", "/", "%", "==", "!=", "<", + "<=", ">", ">=", "\"", "\\", "#", "<0x20>", "<0x09>", "<0x0A>", + "<0x0D>", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; + return values; +} + +} // namespace + +std::filesystem::path defaultTokenizerModelPath() { +#ifdef FELIDAE_TOKENIZER_MODEL_PATH + return std::filesystem::path(FELIDAE_TOKENIZER_MODEL_PATH); +#else + return std::filesystem::path("models") / "felidae-bpe" / "model.txt"; +#endif +} + +BpeTokenizer::BpeTokenizer(std::filesystem::path modelPath) + : modelPath_(modelPath.empty() ? defaultTokenizerModelPath() + : std::move(modelPath)) { + loadModel(); +} + +void BpeTokenizer::loadModel() { + std::lock_guard lock(mutex_); + entries_.clear(); + matchOrder_.clear(); + std::ifstream input(modelPath_, std::ios::binary); + if (input) { + std::string line; + while (std::getline(input, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + entries_.push_back(Entry{line, decodeModelSpelling(line)}); + } + } + ensureFixedVocabulary(); +} + +void BpeTokenizer::ensureFixedVocabulary() { + const auto &fixed = fixedVocabulary(); + if (entries_.empty()) { + entries_.reserve(fixed.size()); + for (const auto spelling : fixed) + entries_.push_back( + Entry{std::string(spelling), decodeModelSpelling(spelling)}); + std::error_code error; + std::filesystem::create_directories(modelPath_.parent_path(), error); + std::ofstream output(modelPath_, std::ios::binary | std::ios::trunc); + if (!output) + throw std::runtime_error("Unable to create tokenizer model: " + + modelPath_.string()); + for (const auto &entry : entries_) output << entry.spelling << '\n'; + } else if (entries_.size() < fixed.size()) { + throw std::runtime_error("Tokenizer model is missing fixed syntax IDs: " + + modelPath_.string()); + } + for (std::size_t index = 0; index < fixed.size(); ++index) { + if (entries_[index].bytes != decodeModelSpelling(fixed[index])) + throw std::runtime_error("Tokenizer model fixed ID mismatch at line " + + std::to_string(index) + ": " + + modelPath_.string()); + } + for (std::size_t index = 1; index < entries_.size(); ++index) + if (!entries_[index].bytes.empty()) + matchOrder_.emplace_back(entries_[index].bytes, + static_cast(index)); + std::stable_sort(matchOrder_.begin(), matchOrder_.end(), + [](const auto &left, const auto &right) { + if (left.first.size() != right.first.size()) + return left.first.size() > right.first.size(); + return left.second < right.second; + }); +} + +int BpeTokenizer::findToken(std::string_view bytes) const { + for (std::size_t index = 1; index < entries_.size(); ++index) + if (entries_[index].bytes == bytes) return static_cast(index); + return -1; +} + +void BpeTokenizer::appendModelLine(std::string_view bytes) const { + std::error_code error; + std::filesystem::create_directories(modelPath_.parent_path(), error); + std::ofstream output(modelPath_, std::ios::binary | std::ios::app); + if (!output) + throw std::runtime_error("Unable to append tokenizer model: " + + modelPath_.string()); + output << encodeModelSpelling(bytes) << '\n'; +} + +int BpeTokenizer::appendToken(std::string_view bytes) const { + std::lock_guard lock(mutex_); + const int existing = findToken(bytes); + if (existing >= 0) return existing; + const int id = static_cast(entries_.size()); + std::string owned(bytes); + appendModelLine(owned); + entries_.push_back(Entry{encodeModelSpelling(owned), std::move(owned)}); + matchOrder_.emplace_back(entries_.back().bytes, id); + std::stable_sort(matchOrder_.begin(), matchOrder_.end(), + [](const auto &left, const auto &right) { + if (left.first.size() != right.first.size()) + return left.first.size() > right.first.size(); + return left.second < right.second; + }); + return id; +} + +void BpeTokenizer::prime(std::string_view source) const { + std::vector words; + for (std::size_t begin = 0; begin < source.size();) { + if (std::isdigit(static_cast(source[begin]))) { + while (begin < source.size() && + std::isdigit(static_cast(source[begin]))) + ++begin; + continue; + } + if (!isWordByte(static_cast(source[begin]))) { + ++begin; + continue; + } + std::size_t end = begin + 1; + while (end < source.size() && + isWordByte(static_cast(source[end]))) + ++end; + words.emplace_back(source.substr(begin, end - begin)); + begin = end; + } + std::sort(words.begin(), words.end()); + words.erase(std::unique(words.begin(), words.end()), words.end()); + for (const auto &word : words) { + bool known = false; + { + std::lock_guard lock(mutex_); + known = findToken(word) >= 0; + } + if (!known) appendToken(word); + } +} + +std::vector +BpeTokenizer::encodeWithOffsets(std::string_view text) const { + std::vector result; + std::size_t offset = 0; + while (offset < text.size()) { + if (std::isdigit(static_cast(text[offset]))) { + const std::string_view digit = text.substr(offset, 1); + int id = -1; + { + std::lock_guard lock(mutex_); + id = findToken(digit); + } + if (id < 0) id = appendToken(digit); + result.push_back({id, offset, offset + 1}); + ++offset; + continue; + } + if (isWordByte(static_cast(text[offset]))) { + std::size_t end = offset + 1; + while (end < text.size() && + isWordByte(static_cast(text[end]))) + ++end; + const auto word = text.substr(offset, end - offset); + int id = -1; + { + std::lock_guard lock(mutex_); + id = findToken(word); + } + if (id < 0) id = appendToken(word); + result.push_back({id, offset, end}); + offset = end; + continue; + } + int id = -1; + std::size_t length = 0; + { + std::lock_guard lock(mutex_); + for (const auto &[bytes, candidate] : matchOrder_) { + if (bytes.size() <= length || bytes.size() > text.size() - offset) + continue; + if (text.compare(offset, bytes.size(), bytes) == 0) { + id = candidate; + length = bytes.size(); + break; + } + } + } + if (id < 0) { + id = appendToken(text.substr(offset, 1)); + length = 1; + } + result.push_back({id, offset, offset + length}); + offset += length; + } + return result; +} + +std::vector BpeTokenizer::encode(std::string_view text) const { + const auto encoded = encodeWithOffsets(text); + std::vector result; + result.reserve(encoded.size()); + for (const auto token : encoded) result.push_back(token.id); + return result; +} + +std::string BpeTokenizer::decode(std::span tokens) const { + std::lock_guard lock(mutex_); + std::string result; + for (const int id : tokens) { + if (id < 0 || static_cast(id) >= entries_.size()) + throw std::runtime_error("BPE decode received an invalid token ID"); + result += entries_[static_cast(id)].bytes; + } + return result; +} + +} // namespace Felidae diff --git a/src/Tokenizer.h b/src/Tokenizer.h new file mode 100644 index 0000000..566c00f --- /dev/null +++ b/src/Tokenizer.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +struct EncodedToken { + int id = 0; + std::size_t begin = 0; + std::size_t end = 0; +}; + +// Deterministic, training-free BPE vocabulary. Line N in model.txt owns ID N. +// <0xNN> is the escaped spelling for bytes which cannot be represented +// literally in a line-oriented text file. Unknown identifier words are +// appended in encounter order and are immediately reusable by encode/decode. +class BpeTokenizer { +public: + explicit BpeTokenizer(std::filesystem::path modelPath = {}); + + std::vector encode(std::string_view text) const; + std::vector encodeWithOffsets(std::string_view text) const; + std::string decode(std::span tokens) const; + // Reserve unknown identifier words in lexical order before the parser + // traverses the source. This makes newly assigned line IDs independent of + // parser backtracking and statement chunking. + void prime(std::string_view source) const; + + const std::filesystem::path &modelPath() const noexcept { return modelPath_; } + +private: + struct Entry { + std::string spelling; + std::string bytes; + }; + + void loadModel(); + void ensureFixedVocabulary(); + int appendToken(std::string_view bytes) const; + int findToken(std::string_view bytes) const; + void appendModelLine(std::string_view bytes) const; + + std::filesystem::path modelPath_; + mutable std::vector entries_; + mutable std::vector> matchOrder_; + mutable std::mutex mutex_; +}; + +std::filesystem::path defaultTokenizerModelPath(); + +} // namespace Felidae diff --git a/src/VmMain.cpp b/src/VmMain.cpp deleted file mode 100644 index 02d8fc7..0000000 --- a/src/VmMain.cpp +++ /dev/null @@ -1,265 +0,0 @@ -#include "form/BinaryIr.h" -#include "form/RuntimeStateModel.h" -#ifdef FELIDAE_HAS_TORCH -#include "form/LibTorchTensorRuntime.h" -#endif -#include "ModelStore.h" -#include "SentencePieceModel.h" -#include "Version.h" -#include "form/RuntimeTrainingCommand.h" - -#include -#include -#include -#include -#include - -#include - -namespace fs = std::filesystem; -using namespace Felidae; - -namespace { -struct Options { - fs::path input; - bool serve = false; - std::optional modelDirectory; - std::optional factStoreDirectory; -}; - -std::optional parseInput(int argc, char **argv) { - if (argc == 1 || (argc == 2 && std::string(argv[1]) == "--help")) - return std::nullopt; - Options options; - for (int index = 1; index < argc; ++index) { - const std::string argument(argv[index]); - if (argument == "--serve") { - options.serve = true; - continue; - } - if (argument == "--model") { - if (++index == argc) - throw std::runtime_error("--model requires a model directory"); - options.modelDirectory = fs::path(argv[index]); - continue; - } - if (argument == "--fact-store") { - if (++index == argc) - throw std::runtime_error("--fact-store requires a RocksDB directory"); - options.factStoreDirectory = fs::path(argv[index]); - continue; - } - if (!options.input.empty()) - throw std::runtime_error( - "felidae_vm accepts exactly one verified .bin IR file"); - options.input = argument; - } - if (options.input.empty()) - throw std::runtime_error("felidae_vm requires a .bin Felidae IR file"); - return options; -} - -void printHelp() { - std::cout - << LANGUAGE_NAME << " Form VM v" << LANGUAGE_VERSION << "\n\n" - << "Usage: felidae_vm program.bin\n" - << " felidae_vm [--serve] [--model models/runtime] " - "[--fact-store path] program.bin\n" - << " felidae_vm --train datasets/vm/runtime-context-v1.jsonl " - "--store-model build|dist [--epochs N] [--learning-rate R]\n" - << "Loads, verifies once, and executes Felidae IR. --serve keeps one VM " - "and " - "its fact memory resident; use run, facts [type-id], field , " - "history, proof (all paths), load , " - "modules, or quit on stdin.\n"; -} - -int trainRuntimeModel(const ModelTrainingOptions &training) { -#ifdef FELIDAE_HAS_TRAINING - if (training.dataset.extension() != ".jsonl") { - throw std::runtime_error("--train requires one VM .jsonl dataset"); - } - const auto output = modelStoreDirectory(training.store, "runtime-gru"); - std::vector arguments{ - "felidae_vm", training.dataset.string(), output.string(), - std::to_string(training.epochs), std::to_string(training.learningRate)}; - std::vector rawArguments; - rawArguments.reserve(arguments.size()); - for (auto &argument : arguments) - rawArguments.push_back(argument.data()); - return runRuntimeGruTraining(static_cast(rawArguments.size()), - rawArguments.data()); -#else - (void)training; - throw std::runtime_error("this VM build has training disabled; configure " - "FELIDAE_ENABLE_TRAINING=ON"); -#endif -} - -IrSymbolRef readSymbol(std::istringstream &input, const char *command) { - std::uint64_t value = 0; - if (!(input >> value) || value == 0) - throw std::runtime_error(std::string(command) + - " requires a nonzero numeric symbol ID"); - return static_cast(value); -} - -} // namespace - -int main(int argc, char **argv) { - try { - if (argc == 2 && std::string(argv[1]) == "--version") { - std::cout << LANGUAGE_NAME << " Form VM v" << LANGUAGE_VERSION << "\n"; - return 0; - } - if (const auto training = parseModelTrainingOptions(argc, argv)) { - return trainRuntimeModel(*training); - } - const auto options = parseInput(argc, argv); - if (!options) { - printHelp(); - return argc == 1 ? 1 : 0; - } - const auto binary = fs::absolute(options->input).lexically_normal(); - if (binary.extension() != kBinaryIrExtension) { - throw std::runtime_error("felidae_vm accepts only .bin Felidae IR files"); - } - const VmTextDecoder decoder = [](std::span pieces) { - std::vector ids; - ids.reserve(pieces.size()); - for (const auto piece : pieces) - ids.push_back(static_cast(piece)); - std::string text; - const auto status = felidaeSentencePieceModel().Decode(ids, &text); - if (!status.ok()) - throw IrError("SentencePiece cannot decode VM text"); - return text; - }; - const VmTextEncoder encoder = [](std::string_view text) { - std::vector ids; - const auto status = felidaeSentencePieceModel().Encode(text, &ids); - // An empty ids vector is a valid encoding of empty text (e.g. an - // empty CSV cell round-tripped through csv.toFacts), not an encoder - // failure -- only a non-ok status is a genuine error. Rejecting - // empty results here previously made every empty runtime string - // value (imported from CSV, computed, etc.) throw. - if (!status.ok()) - throw IrError("SentencePiece cannot encode VM text"); - PieceSequence pieces; - pieces.reserve(ids.size()); - for (const auto id : ids) { - if (id < 0) - throw IrError("SentencePiece emitted an invalid VM text ID"); - pieces.push_back(static_cast(id)); - } - return pieces; - }; - auto module = loadBinaryIr(binary, felidaeSentencePieceModelIdentity()); - auto display = makeIrDisplayContext(module, decoder); - auto factStore = options->factStoreDirectory - ? std::make_shared( - fs::absolute(*options->factStoreDirectory) - .lexically_normal()) - : std::make_shared(); -#ifdef FELIDAE_HAS_TORCH - std::unique_ptr model; - if (options->modelDirectory) { - auto vocabulary = defaultRuntimeOutputVocabulary(); - GruRuntimeStateModel::Configuration configuration; - configuration.inputVocabularySize = - felidaeSentencePieceModel().GetPieceSize() + - kRuntimeStructuralInputTokens; - configuration.outputVocabularySize = - static_cast(vocabulary.size()); - model = std::make_unique( - GruRuntimeStateModel::loadVersioned( - configuration, std::move(vocabulary), *options->modelDirectory, - felidaeSentencePieceModelIdentity())); - } - LibTorchTensorRuntime tensorRuntime; - display.tensorDecoder = [&](const VmTensor &tensor) { - return tensorRuntime.displayTensor(tensor); - }; - FelidaeKnowledgeRuntime runtime(model.get(), 1024, 256, - std::move(factStore), &tensorRuntime, - decoder, encoder); -#else - if (options->modelDirectory) - throw std::runtime_error( - "this VM build has no LibTorch runtime SSM support"); - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, - std::move(factStore), nullptr, decoder, - encoder); -#endif - RegisterVm vm; - const auto execute = [&] { - std::cout << vmValueToDisplayString(vm.executeMain(module, runtime), - display) - << "\n"; - }; - if (!options->serve) { - execute(); - return 0; - } - std::string command; - while (std::getline(std::cin, command)) { - std::istringstream words(command); - std::string verb; - words >> verb; - if (verb == "run") - execute(); - else if (verb == "load") { - std::string path; - if (!(words >> path)) - throw std::runtime_error("load requires a .bin Felidae IR file"); - const auto next = fs::absolute(fs::path(path)).lexically_normal(); - if (next.extension() != kBinaryIrExtension) - throw std::runtime_error("load accepts only .bin Felidae IR files"); - module = loadBinaryIr(next, felidaeSentencePieceModelIdentity()); - display = makeIrDisplayContext(module, decoder); - std::cout << next.string() << "\n"; - } else if (verb == "modules") { - std::cout << runtime.installedModuleCount() << "\n"; - } else if (verb == "facts") { - std::uint64_t type = 0; - if (words >> type) - std::cout << runtime.factStore()->snapshotAssignableTo(type).size() - << "\n"; - else - std::cout << runtime.factStore()->size() << "\n"; - } else if (verb == "field") { - std::cout << runtime.factStore() - ->snapshotByField(readSymbol(words, "field")) - .size() - << "\n"; - } else if (verb == "history") { - std::cout << runtime.factStore()->mutations().size() << "\n"; - } else if (verb == "proof") { - const auto child = readSymbol(words, "proof"); - const auto ancestor = readSymbol(words, "proof"); - const auto paths = - runtime.factStore()->hierarchyProofs(child, ancestor); - for (std::size_t pathIndex = 0; pathIndex < paths.size(); ++pathIndex) { - if (pathIndex != 0) - std::cout << ' '; - std::cout << '['; - const auto &path = paths[pathIndex]; - for (std::size_t index = 0; index < path.size(); ++index) { - if (index != 0) - std::cout << ' '; - std::cout << path[index]; - } - std::cout << ']'; - } - std::cout << "\n"; - } else if (verb == "quit") - return 0; - else - throw std::runtime_error("VM daemon command is invalid"); - } - return 0; - } catch (const std::exception &error) { - std::cerr << "error: " << error.what() << "\n"; - return 1; - } -} diff --git a/src/debugger/AstAnalyzer.cpp b/src/debugger/AstAnalyzer.cpp deleted file mode 100644 index b49d9a2..0000000 --- a/src/debugger/AstAnalyzer.cpp +++ /dev/null @@ -1,585 +0,0 @@ -#include "debugger/AstAnalyzer.h" -#include "Symbol.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace Felidae { - -namespace { - -bool isIgnoredName(const std::string &name) { - return name.empty() || name == "_" || - name == internalSymbolName(InternalSymbolKind::SystemResult); -} - -bool isLikelyTypeName(const std::string &name) { - return isFelidaeLikelyTypeName(name) || name == "map"; -} - -// Head parameters in the shape editor integrations want for signature help. -// A head writes either an annotation (`name: string`, `input: Person`) or a -// plain binding (`employee: e`); only the former has a type worth showing, -// which is exactly the distinction isLikelyTypeName already draws for the -// unused-variable diagnostics below. A literal default contributes its own -// kind as the type. -std::vector collectHeadParameters(const Call &head) { - std::vector params; - params.reserve(head.args.size()); - for (const auto &arg : head.args) { - SymbolParameter param; - param.name = arg.name; - if (auto var = std::dynamic_pointer_cast(arg.value)) { - if (isLikelyTypeName(var->name)) { - param.type = var->name; - } else if (param.name.empty()) { - // Positional head argument: the bound variable is the only - // name this parameter has. - param.name = var->name; - } - } else if (std::dynamic_pointer_cast(arg.value)) { - param.type = "string"; - } else if (std::dynamic_pointer_cast(arg.value)) { - param.type = "number"; - } else if (std::dynamic_pointer_cast(arg.value)) { - param.type = "bool"; - } - if (param.name.empty()) - continue; - params.push_back(std::move(param)); - } - return params; -} - -void addVarUse(const std::string &name, std::set &uses) { - if (!isIgnoredName(name)) - uses.insert(name); -} - -void collectExprUses(const std::shared_ptr &expr, - std::set &vars, - std::set &calls) { - if (!expr) - return; - if (auto var = std::dynamic_pointer_cast(expr)) { - addVarUse(var->name, vars); - } else if (auto term = std::dynamic_pointer_cast(expr)) { - calls.insert(term->name); - if (term->name == "Reasoning:contrary") { - for (const auto &arg : term->args) { - if (arg.name != "positive" && arg.name != "negative") - continue; - if (auto predicate = std::dynamic_pointer_cast(arg.value)) { - calls.insert(predicate->value); - } - } - } - if (term->name == "thread:createThread") { - for (const auto &arg : term->args) { - if (arg.name != "function" && arg.name != "name") - continue; - if (auto target = std::dynamic_pointer_cast(arg.value)) - calls.insert(target->value); - } - } - for (const auto &arg : term->args) - collectExprUses(arg.value, vars, calls); - } else if (auto lambda = std::dynamic_pointer_cast(expr)) { - if (auto source = std::dynamic_pointer_cast(lambda->source)) { - if (isLikelyTypeName(source->name)) - calls.insert(source->name); - } - collectExprUses(lambda->source, vars, calls); - collectExprUses(lambda->body, vars, calls); - if (lambda->right) - collectExprUses(lambda->right, vars, calls); - } else if (auto array = std::dynamic_pointer_cast(expr)) { - for (const auto &item : array->items) - collectExprUses(item, vars, calls); - } else if (auto map = std::dynamic_pointer_cast(expr)) { - for (const auto &entry : map->entries) - collectExprUses(entry.value, vars, calls); - } else if (auto access = std::dynamic_pointer_cast(expr)) { - auto targetVar = std::dynamic_pointer_cast(access->target); - if (access->key == "result" && targetVar && targetVar->name == "system") - return; - collectExprUses(access->target, vars, calls); - } else if (auto op = std::dynamic_pointer_cast(expr)) { - for (size_t i = 0; i < op->captureCount(); ++i) - collectExprUses(op->capture(i), vars, calls); - } -} - -void collectGoalUses(const std::shared_ptr &goal, - std::set &vars, - std::set &calls) { - if (!goal) - return; - if (auto call = std::dynamic_pointer_cast(goal)) { - calls.insert(call->call.name); - if (call->call.name == "thread:createThread") { - for (const auto &arg : call->call.args) { - if (arg.name != "function" && arg.name != "name") - continue; - if (auto target = std::dynamic_pointer_cast(arg.value)) - calls.insert(target->value); - } - } - for (const auto &arg : call->call.args) - collectExprUses(arg.value, vars, calls); - } else if (auto notGoal = std::dynamic_pointer_cast(goal)) { - calls.insert(notGoal->call.name); - for (const auto &arg : notGoal->call.args) - collectExprUses(arg.value, vars, calls); - } else if (auto assign = std::dynamic_pointer_cast(goal)) { - if (assign->expr) - collectExprUses(assign->expr, vars, calls); - } else if (auto multi = std::dynamic_pointer_cast(goal)) { - collectExprUses(multi->expr, vars, calls); - } else if (auto binary = std::dynamic_pointer_cast(goal)) { - collectExprUses(binary->left, vars, calls); - collectExprUses(binary->right, vars, calls); - } else if (auto where = std::dynamic_pointer_cast(goal)) { - collectGoalUses(where->condition, vars, calls); - } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { - collectGoalUses(ifGoal->condition, vars, calls); - for (const auto &item : ifGoal->thenBranch) - collectGoalUses(item, vars, calls); - for (const auto &item : ifGoal->elseBranch) - collectGoalUses(item, vars, calls); - } else if (auto ret = std::dynamic_pointer_cast(goal)) { - for (const auto &field : ret->fields) - collectExprUses(field.value, vars, calls); - } else if (auto group = std::dynamic_pointer_cast(goal)) { - for (const auto &item : group->goals) - collectGoalUses(item, vars, calls); - } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { - for (const auto &branch : orGoal->branches) { - for (const auto &item : branch) - collectGoalUses(item, vars, calls); - } - } -} - -void collectAssignedNames(const std::vector> &goals, - std::set &assigned) { - for (const auto &goal : goals) { - if (auto assign = std::dynamic_pointer_cast(goal)) { - if (!isIgnoredName(assign->name)) - assigned.insert(assign->name); - } else if (auto multi = std::dynamic_pointer_cast(goal)) { - for (const auto &target : multi->targets) { - if (!isIgnoredName(target.name)) - assigned.insert(target.name); - } - } else if (auto group = std::dynamic_pointer_cast(goal)) { - collectAssignedNames(group->goals, assigned); - } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { - for (const auto &branch : orGoal->branches) - collectAssignedNames(branch, assigned); - } else if (auto where = std::dynamic_pointer_cast(goal)) { - collectAssignedNames({where->condition}, assigned); - } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { - collectAssignedNames({ifGoal->condition}, assigned); - collectAssignedNames(ifGoal->thenBranch, assigned); - collectAssignedNames(ifGoal->elseBranch, assigned); - } - } -} - -void collectGlobalAssignmentCollisions( - const std::vector> &goals, - const std::set &globals, - std::vector &diagnostics) { - for (const auto &goal : goals) { - if (auto assign = std::dynamic_pointer_cast(goal)) { - if (globals.count(assign->name)) { - diagnostics.push_back(diagnosticFor( - assign.get(), "error", "felidae.immutable.global_reassignment", - "Variable '" + assign->name + - "' is already assigned and immutable.")); - } - } else if (auto multi = std::dynamic_pointer_cast(goal)) { - for (const auto &target : multi->targets) { - if (globals.count(target.name)) { - diagnostics.push_back(diagnosticFor( - multi.get(), "error", "felidae.immutable.global_reassignment", - "Variable '" + target.name + - "' is already assigned and immutable.")); - } - } - } else if (auto group = std::dynamic_pointer_cast(goal)) { - collectGlobalAssignmentCollisions(group->goals, globals, diagnostics); - } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { - for (const auto &branch : orGoal->branches) { - collectGlobalAssignmentCollisions(branch, globals, diagnostics); - } - } else if (auto where = std::dynamic_pointer_cast(goal)) { - collectGlobalAssignmentCollisions({where->condition}, globals, - diagnostics); - } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { - collectGlobalAssignmentCollisions({ifGoal->condition}, globals, - diagnostics); - collectGlobalAssignmentCollisions(ifGoal->thenBranch, globals, - diagnostics); - collectGlobalAssignmentCollisions(ifGoal->elseBranch, globals, - diagnostics); - } - } -} - -std::string factSignature(const ClauseStmt &clause) { - std::vector fields; - fields.reserve(clause.head.args.size()); - for (const auto &arg : clause.head.args) - fields.push_back(arg.name + ":" + arg.value->debug()); - std::sort(fields.begin(), fields.end()); - std::ostringstream out; - out << clause.head.name << "|"; - for (const auto &field : fields) - out << field << "|"; - return out.str(); -} - -void warn(std::vector &diagnostics, const AstNode *node, - std::string code, std::string message) { - diagnostics.push_back( - diagnosticFor(node, "warning", std::move(code), std::move(message))); -} - -void collectDiscardedExpressions( - const std::vector> &goals, const std::string &method, - std::vector &diagnostics) { - for (const auto &goal : goals) { - if (auto binary = std::dynamic_pointer_cast(goal)) { - warn(diagnostics, binary.get(), "felidae.expression.discarded", - "Raw expression '" + binary->debug() + "' in method '" + method + - "' has no result consumer. Use it in where/if, assign or return " - "it, " - "or pass it to a call such as system.print."); - } else if (auto group = std::dynamic_pointer_cast(goal)) { - collectDiscardedExpressions(group->goals, method, diagnostics); - } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { - for (const auto &branch : orGoal->branches) { - collectDiscardedExpressions(branch, method, diagnostics); - } - } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { - // The condition is consumed by if. Branch bodies still need checking. - collectDiscardedExpressions(ifGoal->thenBranch, method, diagnostics); - collectDiscardedExpressions(ifGoal->elseBranch, method, diagnostics); - } else if (auto assign = std::dynamic_pointer_cast(goal)) { - // Assignment consumes either its expression or nested goal result. - (void)assign; - } else if (auto where = std::dynamic_pointer_cast(goal)) { - // The condition is consumed by where. - (void)where; - } - } -} - -void validateReasoningExpr(const std::shared_ptr &expr, - const AstNode *owner, - std::vector &diagnostics) { - if (!expr) - return; - if (const auto term = std::dynamic_pointer_cast(expr)) { - if (term->name == "Evidence" || term->name == "FuzzyMembership") { - for (const auto &argument : term->args) { - if (argument.name == "probability" || argument.name == "similarity") { - diagnostics.push_back(diagnosticFor( - owner, "error", "felidae.reasoning.dimension_conflation", - term->name + " uses '" + argument.name + - "' as membership evidence. Keep probability, " - "similarity, and fuzzy degree in separate fields.")); - } - if (argument.name != "degree" && argument.name != "reliability") - continue; - const auto number = - std::dynamic_pointer_cast(argument.value); - if (number && (!std::isfinite(number->value) || number->value < 0.0 || - number->value > 1.0)) { - diagnostics.push_back( - diagnosticFor(owner, "error", "felidae.reasoning.invalid_grade", - term->name + " '" + argument.name + - "' must be between 0 and 1.")); - } - } - } - for (const auto &argument : term->args) { - validateReasoningExpr(argument.value, owner, diagnostics); - } - return; - } - if (const auto array = std::dynamic_pointer_cast(expr)) { - for (const auto &item : array->items) { - validateReasoningExpr(item, owner, diagnostics); - } - } else if (const auto map = std::dynamic_pointer_cast(expr)) { - for (const auto &entry : map->entries) { - validateReasoningExpr(entry.value, owner, diagnostics); - } - } else if (const auto op = - std::dynamic_pointer_cast(expr)) { - for (size_t i = 0; i < op->captureCount(); ++i) { - validateReasoningExpr(op->capture(i), owner, diagnostics); - } - } else if (const auto access = std::dynamic_pointer_cast(expr)) { - validateReasoningExpr(access->target, owner, diagnostics); - } else if (const auto lambda = std::dynamic_pointer_cast(expr)) { - validateReasoningExpr(lambda->source, owner, diagnostics); - validateReasoningExpr(lambda->body, owner, diagnostics); - validateReasoningExpr(lambda->right, owner, diagnostics); - } -} - -void validateReasoningGoals(const std::vector> &goals, - std::vector &diagnostics) { - for (const auto &goal : goals) { - if (!goal) - continue; - if (const auto call = std::dynamic_pointer_cast(goal)) { - for (const auto &argument : call->call.args) { - validateReasoningExpr(argument.value, goal.get(), diagnostics); - } - } else if (const auto assignment = - std::dynamic_pointer_cast(goal)) { - validateReasoningExpr(assignment->expr, goal.get(), diagnostics); - } else if (const auto multiAssignment = - std::dynamic_pointer_cast(goal)) { - validateReasoningExpr(multiAssignment->expr, goal.get(), diagnostics); - } else if (const auto binary = - std::dynamic_pointer_cast(goal)) { - validateReasoningExpr(binary->left, goal.get(), diagnostics); - validateReasoningExpr(binary->right, goal.get(), diagnostics); - } else if (const auto returned = - std::dynamic_pointer_cast(goal)) { - for (const auto &field : returned->fields) { - validateReasoningExpr(field.value, goal.get(), diagnostics); - } - } else if (const auto group = std::dynamic_pointer_cast(goal)) { - validateReasoningGoals(group->goals, diagnostics); - } else if (const auto alternatives = - std::dynamic_pointer_cast(goal)) { - for (const auto &branch : alternatives->branches) { - validateReasoningGoals(branch, diagnostics); - } - } else if (const auto conditional = - std::dynamic_pointer_cast(goal)) { - validateReasoningGoals({conditional->condition}, diagnostics); - validateReasoningGoals(conditional->thenBranch, diagnostics); - validateReasoningGoals(conditional->elseBranch, diagnostics); - } else if (const auto where = std::dynamic_pointer_cast(goal)) { - validateReasoningGoals({where->condition}, diagnostics); - } - } -} - -} // namespace - -struct AstAnalysisSession::Impl { - static constexpr std::size_t MaxExactDuplicateFacts = 10000; - - struct DefinitionSummary { - size_t count = 0; - SourceSpan span; - std::vector spans; - // Head parameters of the last-seen declaration, mirroring how `span` - // also tracks the last one. - std::vector params; - }; - - std::vector diagnostics; - std::map methodDefinitions; - std::map factDefinitions; - std::set globals; - // All spans a global name was (re)bound at; the "unused global" - // diagnostic below points at the last one, mirroring how - // methodDefinitions/factDefinitions point at their last span too. - std::map> globalSpanLists; - std::set calls; - std::unordered_set factSignatures; - std::size_t factsSeen = 0; - bool duplicateCheckTruncated = false; - SourceSpan duplicateCheckSpan; -}; - -AstAnalysisSession::AstAnalysisSession() : impl_(std::make_unique()) {} -AstAnalysisSession::~AstAnalysisSession() = default; -AstAnalysisSession::AstAnalysisSession(AstAnalysisSession &&) noexcept = - default; -AstAnalysisSession & -AstAnalysisSession::operator=(AstAnalysisSession &&) noexcept = default; - -void AstAnalysisSession::consume(const std::shared_ptr &stmt) { - if (!stmt) { - impl_->diagnostics.push_back( - diagnosticFor(nullptr, "error", "felidae.parser.null_statement", - "Parser produced an invalid empty statement.")); - return; - } - if (auto binding = std::dynamic_pointer_cast(stmt)) { - impl_->globals.insert(binding->name); - impl_->globalSpanLists[binding->name].push_back(binding->sourceSpan); - std::set vars; - collectExprUses(binding->expr, vars, impl_->calls); - return; - } - - auto clause = std::dynamic_pointer_cast(stmt); - if (!clause) - return; - - if (clause->isFact()) { - auto &definition = impl_->factDefinitions[clause->head.name]; - ++definition.count; - definition.span = clause->sourceSpan; - definition.spans.push_back(clause->sourceSpan); - definition.params = collectHeadParameters(clause->head); - ++impl_->factsSeen; - if (impl_->factsSeen <= Impl::MaxExactDuplicateFacts) { - const std::string signature = factSignature(*clause); - if (!impl_->factSignatures.insert(signature).second) { - warn(impl_->diagnostics, clause.get(), "felidae.fact.duplicate", - "Duplicate fact declaration for '" + clause->head.name + "'."); - } - } else { - impl_->duplicateCheckTruncated = true; - impl_->duplicateCheckSpan = clause->sourceSpan; - } - return; - } - - auto &definition = impl_->methodDefinitions[clause->head.name]; - ++definition.count; - definition.span = clause->sourceSpan; - definition.spans.push_back(clause->sourceSpan); - definition.params = collectHeadParameters(clause->head); - for (const auto &annotation : clause->annotations) { - if (annotation.builtinId == BuiltinId::OverloadAnnotation || - annotation.builtinId == BuiltinId::MatcherAnnotation) { - // Operator dispatch references the annotated implementation even - // though no source-level TermExpr call names it. - impl_->calls.insert(clause->head.name); - } else { - impl_->calls.insert(annotation.name); - } - } - collectGlobalAssignmentCollisions(clause->body, impl_->globals, - impl_->diagnostics); - collectDiscardedExpressions(clause->body, clause->head.name, - impl_->diagnostics); - validateReasoningGoals(clause->body, impl_->diagnostics); - for (const auto &branch : clause->fallbackBranches) { - collectGlobalAssignmentCollisions(branch, impl_->globals, - impl_->diagnostics); - collectDiscardedExpressions(branch, clause->head.name, impl_->diagnostics); - validateReasoningGoals(branch, impl_->diagnostics); - } - std::set declared; - std::set used; - for (const auto &arg : clause->head.args) { - if (!arg.name.empty()) - declared.insert(arg.name); - if (auto var = std::dynamic_pointer_cast(arg.value)) { - if (!isIgnoredName(var->name) && !isLikelyTypeName(var->name)) { - declared.insert(var->name); - } - } - } - collectAssignedNames(clause->body, declared); - for (const auto &branch : clause->fallbackBranches) { - collectAssignedNames(branch, declared); - } - for (const auto &goal : clause->body) { - collectGoalUses(goal, used, impl_->calls); - } - for (const auto &branch : clause->fallbackBranches) { - for (const auto &goal : branch) { - collectGoalUses(goal, used, impl_->calls); - } - } - for (const auto &name : declared) { - if (!used.count(name)) { - warn(impl_->diagnostics, clause.get(), "felidae.variable.unused", - "Variable '" + name + "' is declared but never used in method '" + - clause->head.name + "'."); - } - } -} - -std::vector AstAnalysisSession::finish() { - if (impl_->duplicateCheckTruncated) { - impl_->diagnostics.push_back(diagnosticForSpan( - impl_->duplicateCheckSpan, "warning", - "felidae.analysis.duplicate_check_bounded", - "Exact duplicate-fact diagnostics were bounded after " + - std::to_string(Impl::MaxExactDuplicateFacts) + - " facts to keep streaming analysis memory bounded.")); - } - for (const auto &item : impl_->methodDefinitions) { - if (item.first != "main" && !impl_->calls.count(item.first)) { - impl_->diagnostics.push_back(diagnosticForSpan( - item.second.span, "warning", "felidae.method.unused", - "Method '" + item.first + - "' is defined but not called in this file.")); - } - } - for (const auto &item : impl_->globals) { - if (!impl_->calls.count(item)) { - impl_->diagnostics.push_back(diagnosticForSpan( - impl_->globalSpanLists[item].back(), "warning", - "felidae.global.unused", - "Global '" + item + "' is defined but not referenced in this file.")); - } - } - for (const auto &item : impl_->factDefinitions) { - if (!impl_->calls.count(item.first)) { - impl_->diagnostics.push_back(diagnosticForSpan( - item.second.span, "warning", "felidae.fact.unused", - "Fact type '" + item.first + - "' is declared but not referenced in this file.")); - } - } - return std::move(impl_->diagnostics); -} - -SymbolSummary AstAnalysisSession::symbols() const { - auto toSymbolDefinitions = [](const auto &definitions) { - std::vector result; - result.reserve(definitions.size()); - for (const auto &[name, definition] : definitions) { - result.push_back(SymbolDefinition{name, definition.count, - definition.spans, definition.params}); - } - return result; - }; - - SymbolSummary summary; - summary.methods = toSymbolDefinitions(impl_->methodDefinitions); - summary.facts = toSymbolDefinitions(impl_->factDefinitions); - summary.globals.reserve(impl_->globals.size()); - for (const auto &name : impl_->globals) { - // impl_->globals and impl_->globalSpanLists are always populated - // together in consume(), so every global name has at least one span. - // A global binding has no parameter list; the empty vector is stated - // rather than left to aggregate initialization so adding a field to - // SymbolDefinition does not silently leave one uninitialized here. - summary.globals.push_back( - SymbolDefinition{name, 1, impl_->globalSpanLists.at(name), {}}); - } - return summary; -} - -std::vector analyzeProgramAst(const Program &program) { - AstAnalysisSession session; - for (const auto &statement : program.statements) - session.consume(statement); - return session.finish(); -} - -} // namespace Felidae diff --git a/src/debugger/AstAnalyzer.h b/src/debugger/AstAnalyzer.h deleted file mode 100644 index 7dd4fa8..0000000 --- a/src/debugger/AstAnalyzer.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include "AST.h" - -#include -#include -#include - -namespace Felidae { - -// AstDiagnostic, diagnosticFor(), and diagnosticForSpan() now live in AST.h -// so the compiler can share them without linking this analyzer. - -// One declared parameter of a method/fact head, e.g. the `name: string` in -// `Greeting(name: string) =>`. `type` is the annotation when the head writes -// one (a type-like identifier such as `string`/`any`/`Person`, or the kind of -// a literal default) and is empty when the head binds a plain variable -// instead, e.g. the `e` in `HasManager(employee: e)`. -struct SymbolParameter { - std::string name; - std::string type; -}; - -struct SymbolDefinition { - std::string name; - std::size_t count = 0; - std::vector spans; - // Parameters of the last-seen declaration of this symbol. Editor - // integrations use these for signature help / parameter info, which is - // why they come from the parsed AST here rather than each extension - // re-deriving them from source text with its own regex. - std::vector params; -}; - -struct SymbolSummary { - std::vector methods; - std::vector facts; - std::vector globals; -}; - -class AstAnalysisSession { -public: - AstAnalysisSession(); - ~AstAnalysisSession(); - AstAnalysisSession(AstAnalysisSession&&) noexcept; - AstAnalysisSession& operator=(AstAnalysisSession&&) noexcept; - AstAnalysisSession(const AstAnalysisSession&) = delete; - AstAnalysisSession& operator=(const AstAnalysisSession&) = delete; - - void consume(const std::shared_ptr& statement); - std::vector finish(); - SymbolSummary symbols() const; - -private: - struct Impl; - std::unique_ptr impl_; -}; - -std::vector analyzeProgramAst(const Program& program); - -} // namespace Felidae diff --git a/src/debugger/main.cpp b/src/debugger/main.cpp deleted file mode 100644 index a63d718..0000000 --- a/src/debugger/main.cpp +++ /dev/null @@ -1,1210 +0,0 @@ -#include "BuiltinRegistry.h" -#include "OperatorAnnotation.h" -#include "Version.h" -#include "debugger/AstAnalyzer.h" -#include "tooling/SourceParser.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include -#endif - -namespace fs = std::filesystem; -using namespace Felidae; - -struct DebugOptions { - bool stopOnEntry = false; - bool loadImports = false; - bool checkJson = false; - bool metricsJson = false; - bool lspMode = false; - bool listLibraries = false; - bool listBuiltins = false; - bool symbolsJson = false; - bool operatorsJson = false; - bool version = false; - bool help = false; - std::optional programFile; -}; - -static DebugOptions parseDebugCli(int argc, char **argv) { - DebugOptions options; - for (int i = 1; i < argc; ++i) { - std::string arg = argv[i]; - if (arg == "--stop-on-entry") { - options.stopOnEntry = true; - continue; - } - if (arg == "--load-imports") { - options.loadImports = true; - continue; - } - if (arg == "--check") { - // Accepted for compatibility with documented usage; the default - // (non --check-json) path below already does exactly this: parse, - // print FELIDAE_DIAGNOSTIC records, and report FELIDAE_CHECK_OK. - continue; - } - if (arg == "--check-json") { - options.checkJson = true; - continue; - } - if (arg == "--metrics-json") { - options.metricsJson = true; - continue; - } - if (arg == "--lsp") { - options.lspMode = true; - continue; - } - if (arg == "--list-libraries") { - options.listLibraries = true; - continue; - } - if (arg == "--list-builtins") { - options.listBuiltins = true; - continue; - } - if (arg == "--symbols-json") { - options.symbolsJson = true; - continue; - } - if (arg == "--operators-json") { - options.operatorsJson = true; - continue; - } - if (arg == "--version" || arg == "-v") { - options.version = true; - continue; - } - if (arg == "--help" || arg == "-h") { - options.help = true; - continue; - } - if (arg == "--inspect-graph" || arg == "--visualize-data-json" || - arg == "--visualize-data-html" || arg == "--json" || arg == "--html") { - throw std::runtime_error("Visualization options are no longer supported"); - } - if (arg == "--query" || (!arg.empty() && arg.front() == '?')) { - throw std::runtime_error("felidae_debug does not execute queries. Run " - "felidae program.fx '? Query(...)'"); - } - if (!options.programFile) { - options.programFile = fs::path(arg); - continue; - } - throw std::runtime_error("Unexpected debugger argument: " + arg); - } - return options; -} - -static void printDebugUsage(std::ostream &out) { - out << "Felidae AST debugger " << LANGUAGE_VERSION << "\n" - << "Pipeline: SentencePiece IDs -> Integer Parser -> AST Analyzer\n" - << "Usage: felidae_debug [--check|--check-json] " - "[--load-imports]\n" - << "\n" - << "Options:\n" - << " --check Parse and emit FELIDAE_DIAGNOSTIC records.\n" - << " --check-json Emit structured JSON diagnostics for editor " - "integrations.\n" - << " --load-imports Parse source imports before AST analysis; native " - "imports are ignored.\n" - << " --stop-on-entry Wait for a debugger command before analysis.\n" - << " --lsp Start the Felidae JSON-RPC diagnostics server " - "over stdio.\n" - << " --list-libraries Print a JSON array of importable core library " - "names.\n" - << " Resolved relative to when given, " - "otherwise the\n" - << " current directory. Editor integrations should " - "call this\n" - << " instead of hand-maintaining a copy of the module " - "list.\n" - << " --list-builtins Print a JSON array of {name, effect} builtin " - "functions.\n" - << " --symbols-json Print a JSON symbol table (methods, facts, " - "globals with\n" - << " source spans and declared params, plus resolved " - "files and\n" - << " unresolved imports) for . Params back " - "editor\n" - << " signature help. Always follows imports, like " - "--lsp.\n" - << " --operators-json Print versioned, non-executing dynamic operator " - "metadata\n" - << " for , including imported public " - "contracts.\n" - << " --version, -v Print {name, version} as JSON.\n"; -} - -static std::string trimText(const std::string &text); - -static void waitForContinue() { - std::cout << "FELIDAE_DEBUG_STOPPED reason=entry\n" << std::flush; - std::string command; - while (std::getline(std::cin, command)) { - command = trimText(command); - if (command == "continue" || command == "c" || command == "next" || - command == "stepIn" || command == "stepOut") { - std::cout << "FELIDAE_DEBUG_CONTINUED\n" << std::flush; - return; - } - if (command == "disconnect" || command == "terminate" || - command == "exit") { - std::cout << "FELIDAE_DEBUG_TERMINATED\n" << std::flush; - std::exit(0); - } - } -} - -static std::string trimText(const std::string &text) { - std::size_t start = 0; - while (start < text.size() && - std::isspace(static_cast(text[start]))) - start++; - std::size_t end = text.size(); - while (end > start && std::isspace(static_cast(text[end - 1]))) - end--; - return text.substr(start, end - start); -} - -static void printAstDiagnostics(const std::vector &diagnostics) { - for (const auto &diagnostic : diagnostics) { - std::cout << "FELIDAE_DIAGNOSTIC " - << "severity=" << diagnostic.severity << " code=" - << (diagnostic.code.empty() ? "felidae.ast" : diagnostic.code) - << " line=" << diagnostic.line << " column=" << diagnostic.column - << " message=" << diagnostic.message << "\n"; - } -} - -static std::string jsonEscape(const std::string &value) { - std::ostringstream out; - for (char ch : value) { - switch (ch) { - case '\\': - out << "\\\\"; - break; - case '"': - out << "\\\""; - break; - case '\b': - out << "\\b"; - break; - case '\f': - out << "\\f"; - break; - case '\n': - out << "\\n"; - break; - case '\r': - out << "\\r"; - break; - case '\t': - out << "\\t"; - break; - default: - if (static_cast(ch) < 0x20) { - out << "\\u"; - const char *hex = "0123456789abcdef"; - out << "00" << hex[(ch >> 4) & 0x0f] << hex[ch & 0x0f]; - } else { - out << ch; - } - } - } - return out.str(); -} - -static const char *builtinEffectName(BuiltinEffect effect) { - switch (effect) { - case BuiltinEffect::Pure: - return "pure"; - case BuiltinEffect::ReadsExternalState: - return "reads"; - case BuiltinEffect::WritesExternalState: - return "writes"; - case BuiltinEffect::Volatile: - return "volatile"; - } - return "volatile"; -} - -static std::string librariesJson(const std::vector &names) { - std::ostringstream out; - out << "["; - for (size_t i = 0; i < names.size(); ++i) { - if (i) - out << ","; - out << "\"" << jsonEscape(names[i]) << "\""; - } - out << "]"; - return out.str(); -} - -static std::string builtinsJson(const std::vector &infos) { - std::ostringstream out; - out << "["; - for (size_t i = 0; i < infos.size(); ++i) { - if (i) - out << ","; - out << "{\"name\":\"" << jsonEscape(infos[i].name) << "\",\"effect\":\"" - << builtinEffectName(infos[i].effect) << "\"}"; - } - out << "]"; - return out.str(); -} - -static std::string spanJson(const SourceSpan &span) { - std::ostringstream out; - out << "{\"startLine\":" << span.startLine - << ",\"startColumn\":" << span.startColumn - << ",\"endLine\":" << span.endLine << ",\"endColumn\":" << span.endColumn - << "}"; - return out.str(); -} - -static std::string -symbolDefinitionsJson(const std::vector &definitions) { - std::ostringstream out; - out << "["; - for (size_t i = 0; i < definitions.size(); ++i) { - if (i) - out << ","; - const auto &definition = definitions[i]; - out << "{\"name\":\"" << jsonEscape(definition.name) - << "\",\"count\":" << definition.count << ",\"spans\":["; - for (size_t s = 0; s < definition.spans.size(); ++s) { - if (s) - out << ","; - out << spanJson(definition.spans[s]); - } - out << "],\"params\":["; - for (size_t p = 0; p < definition.params.size(); ++p) { - if (p) - out << ","; - out << "{\"name\":\"" << jsonEscape(definition.params[p].name) - << "\",\"type\":\"" << jsonEscape(definition.params[p].type) << "\"}"; - } - out << "]}"; - } - out << "]"; - return out.str(); -} - -static std::string -symbolsJson(const SymbolSummary &symbols, const std::vector &files, - const std::vector &unresolvedImports) { - std::ostringstream out; - out << "{\"methods\":" << symbolDefinitionsJson(symbols.methods) - << ",\"facts\":" << symbolDefinitionsJson(symbols.facts) - << ",\"globals\":" << symbolDefinitionsJson(symbols.globals) - << ",\"files\":["; - for (size_t i = 0; i < files.size(); ++i) { - if (i) - out << ","; - out << "\"" << jsonEscape(files[i].string()) << "\""; - } - out << "],\"unresolvedImports\":["; - for (size_t i = 0; i < unresolvedImports.size(); ++i) { - if (i) - out << ","; - out << "\"" << jsonEscape(unresolvedImports[i]) << "\""; - } - out << "]}"; - return out.str(); -} - -static const char *operatorPrecedenceName(OperatorPrecedence value) { - switch (value) { - case OperatorPrecedence::Control: - return "control"; - case OperatorPrecedence::LogicalOr: - return "logical-or"; - case OperatorPrecedence::LogicalAnd: - return "logical-and"; - case OperatorPrecedence::Relationship: - return "relationship"; - case OperatorPrecedence::Ordering: - return "ordering"; - case OperatorPrecedence::Pipeline: - return "pipeline"; - case OperatorPrecedence::Additive: - return "additive"; - case OperatorPrecedence::Multiplicative: - return "multiplicative"; - case OperatorPrecedence::Prefix: - return "prefix"; - } - return "relationship"; -} - -static const char *operatorAssociativityName(OperatorAssociativity value) { - switch (value) { - case OperatorAssociativity::None: - return "none"; - case OperatorAssociativity::Left: - return "left"; - case OperatorAssociativity::Right: - return "right"; - } - return "none"; -} - -static const char *operatorFixityName(OperatorFixity value) { - switch (value) { - case OperatorFixity::Prefix: - return "prefix"; - case OperatorFixity::Infix: - return "infix"; - case OperatorFixity::Postfix: - return "postfix"; - case OperatorFixity::Mixfix: - return "mixfix"; - } - return "infix"; -} - -static const char *operatorVisibilityName(OperatorVisibility value) { - return value == OperatorVisibility::Public ? "public" : "private"; -} - -static const char *operatorCardinalityName(OperatorCardinality value) { - switch (value) { - case OperatorCardinality::One: - return "one"; - case OperatorCardinality::Optional: - return "optional"; - case OperatorCardinality::Many: - return "many"; - } - return "one"; -} - -static std::string -operatorBindingsJson(const std::vector &bindings) { - std::ostringstream out; - out << "["; - for (size_t i = 0; i < bindings.size(); ++i) { - if (i) - out << ","; - out << "{\"name\":\"" << jsonEscape(bindings[i].name) - << "\",\"nameId\":" << bindings[i].nameId << ",\"type\":\"" - << jsonEscape(bindings[i].type) - << "\",\"typeId\":" << bindings[i].typeId << "}"; - } - out << "]"; - return out.str(); -} - -static std::string -operatorMetadataJson(const OperatorRegistry ®istry, - const std::vector &files, - const std::vector &unresolvedImports) { - std::ostringstream out; - out << "{\"protocol\":\"felidae.operator-metadata\",\"version\":1," - "\"patterns\":["; - const auto &patterns = registry.patterns(); - for (size_t i = 0; i < patterns.size(); ++i) { - if (i) - out << ","; - const auto &pattern = patterns[i]; - out << "{\"operatorId\":" << pattern.operatorId - << ",\"patternId\":" << pattern.patternId << ",\"operator\":\"" - << jsonEscape(pattern.operatorName) << "\",\"pattern\":\"" - << jsonEscape(pattern.pattern) << "\",\"precedence\":\"" - << operatorPrecedenceName(pattern.precedence) - << "\",\"associativity\":\"" - << operatorAssociativityName(pattern.associativity) - << "\",\"fixity\":\"" << operatorFixityName(pattern.fixity) - << "\",\"visibility\":\"" << operatorVisibilityName(pattern.visibility) - << "\",\"module\":\"" << jsonEscape(pattern.module) - << "\",\"anchors\":["; - for (size_t a = 0; a < pattern.anchors.size(); ++a) { - if (a) - out << ","; - out << "\"" << jsonEscape(pattern.anchors[a]) << "\""; - } - out << "],\"captures\":["; - for (size_t c = 0; c < pattern.captureNames.size(); ++c) { - if (c) - out << ","; - out << "\"" << jsonEscape(pattern.captureNames[c]) << "\""; - } - out << "]}"; - } - out << "],\"overloads\":["; - const auto &overloads = registry.overloads(); - for (size_t i = 0; i < overloads.size(); ++i) { - if (i) - out << ","; - const auto &overload = overloads[i]; - out << "{\"operatorId\":" << overload.operatorId - << ",\"patternId\":" << overload.patternId << ",\"method\":\"" - << jsonEscape(overload.methodName) - << "\",\"methodId\":" << overload.methodId - << ",\"captures\":" << operatorBindingsJson(overload.captures) - << ",\"factors\":" << operatorBindingsJson(overload.factors) - << ",\"result\":\"" << jsonEscape(overload.resultType) - << "\",\"cardinality\":\"" - << operatorCardinalityName(overload.cardinality) << "\",\"effects\":\"" - << (overload.effect == OperatorEffect::Pure ? "pure" : "impure") - << "\",\"visibility\":\"" << operatorVisibilityName(overload.visibility) - << "\",\"module\":\"" << jsonEscape(overload.module) << "\"}"; - } - out << "],\"matchers\":["; - const auto &matchers = registry.matchers(); - for (size_t i = 0; i < matchers.size(); ++i) { - if (i) - out << ","; - const auto &matcher = matchers[i]; - out << "{\"operatorId\":" << matcher.operatorId - << ",\"patternId\":" << matcher.patternId << ",\"method\":\"" - << jsonEscape(matcher.methodName) - << "\",\"methodId\":" << matcher.methodId - << ",\"captures\":" << operatorBindingsJson(matcher.captures) - << ",\"produces\":" << operatorBindingsJson(matcher.produces) - << ",\"visibility\":\"" << operatorVisibilityName(matcher.visibility) - << "\",\"module\":\"" << jsonEscape(matcher.module) << "\"}"; - } - out << "],\"files\":["; - for (size_t i = 0; i < files.size(); ++i) { - if (i) - out << ","; - out << "\"" << jsonEscape(files[i].string()) << "\""; - } - out << "],\"unresolvedImports\":["; - for (size_t i = 0; i < unresolvedImports.size(); ++i) { - if (i) - out << ","; - out << "\"" << jsonEscape(unresolvedImports[i]) << "\""; - } - out << "]}"; - return out.str(); -} - -static std::string versionJson(const char *toolName) { - std::ostringstream out; - out << "{\"name\":\"" << jsonEscape(toolName) << "\",\"version\":\"" - << jsonEscape(LANGUAGE_VERSION) << "\"}"; - return out.str(); -} - -static int lspSeverity(const std::string &severity) { - if (severity == "error") - return 1; - if (severity == "info") - return 3; - if (severity == "hint") - return 4; - return 2; -} - -static bool hasErrorDiagnostic(const std::vector &diagnostics) { - return std::any_of(diagnostics.begin(), diagnostics.end(), - [](const AstDiagnostic &diagnostic) { - return diagnostic.severity == "error" || - diagnostic.severity == "fatal"; - }); -} - -static std::string -diagnosticsJson(const std::vector &diagnostics) { - std::ostringstream out; - out << "{\"ok\":" << (hasErrorDiagnostic(diagnostics) ? "false" : "true") - << ",\"diagnostics\":["; - for (size_t i = 0; i < diagnostics.size(); ++i) { - const auto &diagnostic = diagnostics[i]; - if (i) - out << ","; - int line = std::max(1, diagnostic.line); - int column = std::max(1, diagnostic.column); - int endLine = std::max(line, diagnostic.endLine); - int endColumn = - std::max(endLine == line ? column : 1, diagnostic.endColumn); - out << "{\"severity\":\"" << jsonEscape(diagnostic.severity) - << "\",\"lspSeverity\":" << lspSeverity(diagnostic.severity) - << ",\"line\":" << line << ",\"column\":" << column - << ",\"endLine\":" << endLine << ",\"endColumn\":" << endColumn - << ",\"code\":\"" - << jsonEscape(diagnostic.code.empty() ? "felidae.ast" : diagnostic.code) - << "\"" - << ",\"file\":\"" << jsonEscape(diagnostic.file) << "\"" - << ",\"message\":\"" << jsonEscape(diagnostic.message) << "\"}"; - } - out << "]}"; - return out.str(); -} - -static std::string errorJson(const std::string &message) { - return "{\"ok\":false,\"diagnostics\":[{\"severity\":\"error\"," - "\"lspSeverity\":1," - "\"line\":1,\"column\":1,\"message\":\"" + - jsonEscape(message) + "\"}]}"; -} - -static int hexValue(char ch) { - if (ch >= '0' && ch <= '9') - return ch - '0'; - if (ch >= 'a' && ch <= 'f') - return 10 + ch - 'a'; - if (ch >= 'A' && ch <= 'F') - return 10 + ch - 'A'; - return -1; -} - -static std::string percentDecode(const std::string &text) { - std::string decoded; - decoded.reserve(text.size()); - for (size_t i = 0; i < text.size(); ++i) { - if (text[i] == '%' && i + 2 < text.size()) { - int hi = hexValue(text[i + 1]); - int lo = hexValue(text[i + 2]); - if (hi >= 0 && lo >= 0) { - decoded.push_back(static_cast((hi << 4) | lo)); - i += 2; - continue; - } - } - decoded.push_back(text[i]); - } - return decoded; -} - -static std::string fileUriToPath(std::string uri) { - const std::string prefix = "file:///"; - if (uri.rfind(prefix, 0) == 0) { - uri = uri.substr(prefix.size()); -#ifdef _WIN32 - for (char &ch : uri) { - if (ch == '/') - ch = '\\'; - } -#else - uri = "/" + uri; -#endif - } - return percentDecode(uri); -} - -static std::string analyzeTextJson(const fs::path &path, - const std::string &text) { - try { - constexpr size_t kMaxTextCacheEntries = 128; - struct CachedTextAnalysis { - size_t size = 0; - size_t hash = 0; - size_t lastUsed = 0; - std::vector diagnostics; - }; - static std::unordered_map textCache; - static size_t textCacheClock = 0; - - const auto key = fs::absolute(path).lexically_normal().string(); - const auto hash = std::hash{}(text); - std::vector diagnostics; - auto cached = textCache.find(key); - if (cached != textCache.end() && cached->second.size == text.size() && - cached->second.hash == hash) { - cached->second.lastUsed = ++textCacheClock; - diagnostics = cached->second.diagnostics; - } else { - Program program = Tooling::parseText(text); - diagnostics = analyzeProgramAst(program); - for (auto &diagnostic : diagnostics) - diagnostic.file = key; - // Only compact diagnostics survive this request. Keeping Program here - // retained every statement and expression for each open editor file. - textCache[key] = - CachedTextAnalysis{text.size(), hash, ++textCacheClock, diagnostics}; - if (textCache.size() > kMaxTextCacheEntries) { - auto oldest = textCache.end(); - for (auto it = textCache.begin(); it != textCache.end(); ++it) { - if (oldest == textCache.end() || - it->second.lastUsed < oldest->second.lastUsed) { - oldest = it; - } - } - if (oldest != textCache.end()) - textCache.erase(oldest); - } - } - return diagnosticsJson(diagnostics); - } catch (const std::exception &e) { - return errorJson(e.what()); - } -} - -static std::string analyzeFileJson(const fs::path &path) { - try { - AstAnalysisSession analysis; - Tooling::loadProgramStatements( - path, true, [&](const std::shared_ptr &statement) { - analysis.consume(statement); - }); - auto diagnostics = analysis.finish(); - const auto file = fs::absolute(path).lexically_normal().string(); - for (auto &diagnostic : diagnostics) - diagnostic.file = file; - return diagnosticsJson(diagnostics); - } catch (const std::exception &e) { - return errorJson(e.what()); - } -} - -static std::string symbolsFileJson(const fs::path &path, bool loadImports) { - try { - AstAnalysisSession analysis; - auto loaded = Tooling::loadProgramStatements( - path, loadImports, [&](const std::shared_ptr &statement) { - analysis.consume(statement); - }); - return symbolsJson(analysis.symbols(), loaded.files, - loaded.unresolvedImports); - } catch (const std::exception &e) { - return errorJson(e.what()); - } -} - -static std::string operatorsFileJson(const fs::path &path, bool loadImports) { - try { - std::vector> clauses; - auto loaded = Tooling::loadProgramStatements( - path, loadImports, [&](const std::shared_ptr &statement) { - if (auto clause = std::dynamic_pointer_cast(statement)) { - clauses.push_back(std::move(clause)); - } - }); - if (!loaded.operators) - return errorJson("Operator metadata registry was not created"); - for (const auto &clause : clauses) { - for (const auto &annotation : clause->annotations) { - if (annotation.builtinId != BuiltinId::OverloadAnnotation && - annotation.builtinId != BuiltinId::MatcherAnnotation) - continue; - auto parsed = decodeOperatorAnnotation(annotation); - const auto *pattern = - parsed.pattern.empty() - ? loaded.operators->findPatternByOperator(parsed.operatorName) - : loaded.operators->findPattern(parsed.operatorName, - parsed.pattern); - if (!pattern) - throw std::runtime_error( - "Operator annotation pattern was not registered for metadata"); - if (!parsed.hasVisibility) { - parsed.visibility = loaded.operators->visibilityForPattern( - pattern->patternId, clause->module); - } - if (annotation.builtinId == BuiltinId::MatcherAnnotation) { - loaded.operators->registerMatcher(makeOperatorMatcherDefinition( - parsed, *pattern, clause->head.name, clause->head.nameId, - clause->module)); - } else { - loaded.operators->registerOverload(makeOperatorOverloadDefinition( - parsed, *pattern, clause->head.name, clause->head.nameId, - clause->module)); - } - } - } - return operatorMetadataJson(*loaded.operators, loaded.files, - loaded.unresolvedImports); - } catch (const std::exception &e) { - return errorJson(e.what()); - } -} - -static void writeLspMessage(const std::string &body) { - std::cout << "Content-Length: " << body.size() << "\r\n\r\n" - << body << std::flush; -} - -// LSP SymbolKind values used for Felidae declarations. -constexpr int kSymbolKindMethod = 6; -constexpr int kSymbolKindConstant = 14; -constexpr int kSymbolKindStruct = 23; - -// Builds a textDocument/documentSymbol result from the analyzer's own symbol -// table, so the outline comes from the real parse rather than each editor -// re-deriving declarations from source text with its own regex. -static std::string documentSymbolsJson(const SymbolSummary &symbols) { - std::ostringstream out; - out << "["; - bool first = true; - auto emit = [&](const std::vector &group, int kind) { - for (const auto &definition : group) { - if (definition.spans.empty()) - continue; - const SourceSpan &span = definition.spans.back(); - const int line = std::max(0, span.startLine - 1); - const int column = std::max(0, span.startColumn - 1); - const int endLine = std::max(line, span.endLine - 1); - const int endColumn = std::max(0, span.endColumn - 1); - - std::string detail; - if (!definition.params.empty()) { - detail = "("; - for (size_t i = 0; i < definition.params.size(); ++i) { - if (i) - detail += ", "; - detail += definition.params[i].name; - if (!definition.params[i].type.empty()) { - detail += ": " + definition.params[i].type; - } - } - detail += ")"; - } - - if (!first) - out << ","; - first = false; - out << "{\"name\":\"" << jsonEscape(definition.name) - << "\",\"kind\":" << kind << ",\"detail\":\"" << jsonEscape(detail) - << "\",\"range\":{\"start\":{\"line\":" << line - << ",\"character\":" << column << "},\"end\":{\"line\":" << endLine - << ",\"character\":" << endColumn - << "}},\"selectionRange\":{\"start\":{\"line\":" << line - << ",\"character\":" << column << "},\"end\":{\"line\":" << line - << ",\"character\":" << column << "}}}"; - } - }; - emit(symbols.methods, kSymbolKindMethod); - emit(symbols.facts, kSymbolKindStruct); - emit(symbols.globals, kSymbolKindConstant); - out << "]"; - return out.str(); -} - -static void publishDiagnostics(const std::string &uri, - const std::string &checkJson) { - const auto analysis = nlohmann::json::parse(checkJson); - auto diagnostics = nlohmann::json::array(); - for (const auto &diagnostic : analysis.at("diagnostics")) { - const int line = std::max(0, diagnostic.value("line", 1) - 1); - const int column = std::max(0, diagnostic.value("column", 1) - 1); - const int endLine = - std::max(line, diagnostic.value("endLine", line + 1) - 1); - const int endColumn = - std::max(endLine == line ? column + 1 : 0, - diagnostic.value("endColumn", column + 2) - 1); - diagnostics.push_back( - {{"range", - {{"start", {{"line", line}, {"character", column}}}, - {"end", {{"line", endLine}, {"character", endColumn}}}}}, - {"severity", diagnostic.value("lspSeverity", 2)}, - {"source", "Felidae Debugger"}, - {"message", diagnostic.value("message", std::string{})}}); - } - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"method", "textDocument/publishDiagnostics"}, - {"params", {{"uri", uri}, {"diagnostics", std::move(diagnostics)}}}} - .dump()); -} - -static bool readLspMessage(std::string &body) { - std::string line; - size_t contentLength = 0; - while (std::getline(std::cin, line)) { - if (!line.empty() && line.back() == '\r') - line.pop_back(); - if (line.empty()) - break; - const std::string header = "Content-Length:"; - if (line.rfind(header, 0) == 0) { - contentLength = - static_cast(std::stoul(trimText(line.substr(header.size())))); - } - } - if (contentLength == 0) - return false; - body.assign(contentLength, '\0'); - std::cin.read(&body[0], static_cast(contentLength)); - return static_cast(std::cin.gcount()) == contentLength; -} - -// Analyses whichever text the server currently holds for `uri`, falling back -// to reading the file when the client has not sent contents. -static SymbolSummary -symbolsForDocument(const std::map &documents, - const std::string &uri) { - AstAnalysisSession analysis; - try { - const auto existing = documents.find(uri); - if (existing != documents.end()) { - // Unsaved editor contents: parse what the client sent, so the - // outline tracks the buffer rather than the file on disk. - Program program = Tooling::parseText(existing->second); - for (const auto &statement : program.statements) - analysis.consume(statement); - } else { - Tooling::loadProgramStatements( - fileUriToPath(uri), false, - [&](const std::shared_ptr &statement) { - analysis.consume(statement); - }); - } - } catch (const std::exception &) { - // A syntax error mid-edit is normal; report whatever parsed. - } - return analysis.symbols(); -} - -// Namespaced declarations are written with either separator (`Dog.membership` -// or `Dog:membership`), so compare on a single normalized form. -static std::string normalizeSymbolLookupName(std::string name) { - for (char &ch : name) { - if (ch == '.') - ch = ':'; - } - return name; -} - -// Word under the given zero-based position, using Felidae's identifier rules -// (letters, digits, underscore, plus `.`/`:` for namespaced names). -static std::string wordAtPosition(const std::string &text, int line, - int character) { - size_t offset = 0; - for (int current = 0; current < line; ++current) { - const size_t newline = text.find('\n', offset); - if (newline == std::string::npos) - return {}; - offset = newline + 1; - } - const size_t lineStart = offset; - size_t lineEnd = text.find('\n', lineStart); - if (lineEnd == std::string::npos) - lineEnd = text.size(); - size_t cursor = std::min(lineStart + static_cast(character), lineEnd); - - auto isNameChar = [](char ch) { - return std::isalnum(static_cast(ch)) || ch == '_' || - ch == '.' || ch == ':'; - }; - size_t start = cursor; - size_t end = cursor; - while (start > lineStart && isNameChar(text[start - 1])) - --start; - while (end < lineEnd && isNameChar(text[end])) - ++end; - if (start >= end) - return {}; - std::string word = text.substr(start, end - start); - while (!word.empty() && (word.front() == '.' || word.front() == ':')) - word.erase(word.begin()); - while (!word.empty() && (word.back() == '.' || word.back() == ':')) - word.pop_back(); - return word; -} - -// textDocument/definition: resolve the name under the cursor against the -// analyzer's symbol table, which already records every declaration's span. -static std::string -definitionJson(const std::map &documents, - const std::string &uri, int line, int character) { - std::string text; - const auto existing = documents.find(uri); - if (existing != documents.end()) { - text = existing->second; - } else { - std::ifstream input(fileUriToPath(uri), std::ios::binary); - if (input) { - text.assign(std::istreambuf_iterator(input), - std::istreambuf_iterator()); - } - } - const std::string name = wordAtPosition(text, line, character); - if (name.empty()) - return "null"; - - const SymbolSummary symbols = symbolsForDocument(documents, uri); - const std::string normalized = normalizeSymbolLookupName(name); - for (const auto *group : - {&symbols.methods, &symbols.facts, &symbols.globals}) { - for (const auto &definition : *group) { - if (normalizeSymbolLookupName(definition.name) != normalized) - continue; - if (definition.spans.empty()) - continue; - const SourceSpan &span = definition.spans.back(); - std::ostringstream out; - out << "{\"uri\":\"" << jsonEscape(uri) - << "\",\"range\":{\"start\":{\"line\":" - << std::max(0, span.startLine - 1) - << ",\"character\":" << std::max(0, span.startColumn - 1) - << "},\"end\":{\"line\":" << std::max(0, span.endLine - 1) - << ",\"character\":" << std::max(0, span.endColumn - 1) << "}}}"; - return out.str(); - } - } - return "null"; -} - -static int runLspServer() { -#ifdef _WIN32 - // The CRT's default text-mode translation rewrites every '\n' written to - // stdout as "\r\n" - since writeLspMessage()/publishDiagnostics() already - // write explicit "\r\n" header terminators, that turned into "\r\r\n" on - // Windows, corrupting the LSP wire format for any real client. Binary - // mode on stdin avoids the equivalent corruption when reading message - // bodies containing embedded newlines. - _setmode(_fileno(stdout), _O_BINARY); - _setmode(_fileno(stdin), _O_BINARY); -#endif - std::map documents; - std::string body; - while (readLspMessage(body)) { - nlohmann::json request; - try { - request = nlohmann::json::parse(body); - } catch (const nlohmann::json::parse_error &error) { - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", nullptr}, - {"error", {{"code", -32700}, {"message", error.what()}}}} - .dump()); - continue; - } - if (!request.is_object()) { - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", nullptr}, - {"error", {{"code", -32600}, {"message", "Invalid Request"}}}} - .dump()); - continue; - } - const auto methodValue = request.find("method"); - if (methodValue == request.end() || !methodValue->is_string()) { - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", request.value("id", nlohmann::json(nullptr))}, - {"error", {{"code", -32600}, {"message", "Invalid Request"}}}} - .dump()); - continue; - } - const std::string method = methodValue->get(); - const bool hasId = request.contains("id"); - const auto id = hasId ? request.at("id") : nlohmann::json(nullptr); - const auto params = request.value("params", nlohmann::json::object()); - if (!params.is_object()) { - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", id}, - {"error", {{"code", -32602}, {"message", "Invalid params"}}}} - .dump()); - continue; - } - const auto textDocument = - params.value("textDocument", nlohmann::json::object()); - if (!textDocument.is_object()) { - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", id}, - {"error", {{"code", -32602}, {"message", "Invalid params"}}}} - .dump()); - continue; - } - const auto uriValue = textDocument.find("uri"); - const std::string uri = - uriValue != textDocument.end() && uriValue->is_string() - ? uriValue->get() - : std::string{}; - if (method == "initialize") { - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", id}, - {"result", - {{"capabilities", - {{"textDocumentSync", 1}, - {"documentSymbolProvider", true}, - {"definitionProvider", true}}}, - {"serverInfo", - {{"name", "felidae_debug"}, {"version", LANGUAGE_VERSION}}}}}} - .dump()); - } else if (method == "textDocument/documentSymbol") { - writeLspMessage( - nlohmann::json{{"jsonrpc", "2.0"}, - {"id", id}, - {"result", nlohmann::json::parse(documentSymbolsJson( - symbolsForDocument(documents, uri)))}} - .dump()); - } else if (method == "textDocument/definition") { - const auto position = params.value("position", nlohmann::json::object()); - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", id}, - {"result", nlohmann::json::parse(definitionJson( - documents, uri, std::max(0, position.value("line", 0)), - std::max(0, position.value("character", 0))))}} - .dump()); - } else if (method == "shutdown") { - writeLspMessage( - nlohmann::json{{"jsonrpc", "2.0"}, {"id", id}, {"result", nullptr}} - .dump()); - } else if (method == "exit") { - return 0; - } else if (method == "textDocument/didOpen" || - method == "textDocument/didChange" || - method == "textDocument/didSave") { - if (textDocument.contains("text")) { - documents[uri] = textDocument.at("text").get(); - } else if (const auto changes = params.find("contentChanges"); - changes != params.end() && changes->is_array() && - !changes->empty() && changes->back().contains("text")) { - documents[uri] = changes->back().at("text").get(); - } else if (params.contains("text")) { - documents[uri] = params.at("text").get(); - } - auto existing = documents.find(uri); - std::string result = - existing != documents.end() - ? analyzeTextJson(fileUriToPath(uri), existing->second) - : analyzeFileJson(fileUriToPath(uri)); - publishDiagnostics(uri, result); - } else if (method == "textDocument/didClose") { - // Without this the server kept every document it had ever seen, - // growing without bound over a long editing session. - documents.erase(uri); - } else if (hasId) { - // A request (has an id, so the client is waiting on a reply) for - // a method this diagnostics-only server doesn't implement, e.g. - // textDocument/completion or textDocument/hover. Previously this - // fell through with no response at all, leaving a spec-compliant - // client blocked forever on that id. Notifications (no id) are - // still silently ignored, per the LSP spec. - writeLspMessage(nlohmann::json{ - {"jsonrpc", "2.0"}, - {"id", id}, - {"error", - {{"code", -32601}, {"message", "Method not found: " + method}}}} - .dump()); - } - } - return 0; -} - -int main(int argc, char **argv) { - DebugOptions options; - try { - options = parseDebugCli(argc, argv); - if (options.help) { - printDebugUsage(std::cout); - return 0; - } - if (options.version) { - std::cout << versionJson("felidae_debug") << "\n" << std::flush; - return 0; - } - if (options.lspMode) { - return runLspServer(); - } - if (options.listLibraries) { - fs::path startDir = - options.programFile - ? Tooling::resolveEntryPath(*options.programFile).parent_path() - : fs::current_path(); - std::cout << librariesJson(Tooling::listCoreLibraries(startDir)) << "\n" - << std::flush; - return 0; - } - if (options.listBuiltins) { - std::cout << builtinsJson(allBuiltins()) << "\n" << std::flush; - return 0; - } - if (!options.programFile) { - std::cerr << "error: felidae_debug requires a .fx program file\n"; - printDebugUsage(std::cerr); - return 1; - } - if (options.programFile->extension() != FILE_EXTENSION) { - throw std::runtime_error("Felidae source files must use .fx extension"); - } - - if (options.symbolsJson) { - std::cout << symbolsFileJson(*options.programFile, options.loadImports) - << "\n" - << std::flush; - return 0; - } - if (options.operatorsJson) { - std::cout << operatorsFileJson(*options.programFile, options.loadImports) - << "\n" - << std::flush; - return 0; - } - - const bool dataOutputOnly = options.checkJson; - if (!dataOutputOnly) { - std::cout << "FELIDAE_DEBUG_READY program=" - << options.programFile->string() << "\n" - << std::flush; - } - if (options.stopOnEntry) { - waitForContinue(); - } - - AstAnalysisSession analysis; - const auto analysisStarted = std::chrono::steady_clock::now(); - Tooling::loadProgramStatements( - *options.programFile, options.loadImports, - [&](const std::shared_ptr &statement) { - analysis.consume(statement); - }); - auto astDiagnostics = analysis.finish(); - const auto analyzedFile = - fs::absolute(*options.programFile).lexically_normal().string(); - for (auto &diagnostic : astDiagnostics) - diagnostic.file = analyzedFile; - const auto analysisMicros = - std::chrono::duration_cast( - std::chrono::steady_clock::now() - analysisStarted) - .count(); - if (!dataOutputOnly) { - std::cerr << "Felidae AST debugger analyzing " - << options.programFile->string() << "\n"; - } - - if (options.checkJson) { - std::cout << diagnosticsJson(astDiagnostics) << "\n" << std::flush; - if (hasErrorDiagnostic(astDiagnostics)) { - return 1; - } - } else { - printAstDiagnostics(astDiagnostics); - std::cout << "FELIDAE_CHECK_OK\n" << std::flush; - } - - if (!dataOutputOnly) { - std::cout << "FELIDAE_DEBUG_EXIT code=0\n" << std::flush; - } - if (options.metricsJson) { - std::cerr << "FELIDAE_DEBUG_METRICS {\"analysisMs\":" - << static_cast(analysisMicros) / 1000.0 << "}\n"; - } - return 0; - } catch (const std::exception &e) { - if (options.checkJson) { - std::cout << errorJson(e.what()) << "\n" << std::flush; - return 1; - } - std::cerr << "error: " << e.what() << "\n"; - std::cout << "FELIDAE_DEBUG_EXIT code=1\n" << std::flush; - return 1; - } -} diff --git a/src/main.cpp b/src/main.cpp index 3c80cb5..dc30aaf 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,8 +7,10 @@ #include #include #include +#include #include #include +#include #include namespace fs = std::filesystem; @@ -20,6 +22,7 @@ struct CliOptions { bool repl = false; bool debug = false; bool metricsJson = false; + bool serve = false; size_t benchmarkRepeat = 1; std::optional programFile; std::optional query; @@ -55,6 +58,10 @@ static CliOptions parseCli(int argc, char** argv) { options.metricsJson = true; continue; } + if (arg == "--serve") { + options.serve = true; + continue; + } if (arg == "--visualize-data-json" || arg == "--visualize-data-html" || arg == "--inspect-graph" || arg == "--load-imports") { throw std::runtime_error( @@ -117,6 +124,7 @@ static void printHelp() { << " felidae program.fx --repl\n" << " felidae program.fx --debug\n" << " felidae program.fx --metrics-json\n" + << " felidae program.fx --serve\n" << " felidae program.fx --benchmark-repeat 100 --metrics-json\n" << " felidae program.fx '? Query(key: x)' --benchmark-repeat 100 --metrics-json\n" << " felidae --help\n" @@ -128,6 +136,7 @@ static void printHelp() { << " program.fx --repl Start interactive REPL\n" << " program.fx --debug Run with debug adapter diagnostics enabled\n" << " --metrics-json Emit load and runtime performance counters to stderr\n" + << " --serve Run source and reload the AST interpreter when source changes\n" << " --benchmark-repeat N Repeat the entry method or external query in one runtime\n" << " --help Show this help screen\n" << " --version Show version information\n\n" @@ -188,6 +197,45 @@ static void runRepl(Interpreter& interpreter) { } } +using SourceTimes = std::map; + +static SourceTimes sourceTimes(const fs::path& root, const Interpreter& interpreter) { + SourceTimes result; + const auto add = [&](const fs::path& source) { + std::error_code error; + const auto normalized = fs::absolute(source, error).lexically_normal(); + result.emplace(normalized, error ? fs::file_time_type::min() + : fs::last_write_time(normalized, error)); + if (error) result[normalized] = fs::file_time_type::min(); + }; + add(root); + for (const auto& source : interpreter.loadedSourceFiles()) add(source); + return result; +} + +static bool sourceChanged(const SourceTimes& watched) { + for (const auto& [source, previous] : watched) { + std::error_code error; + const auto current = fs::last_write_time(source, error); + if (error || current != previous) return true; + } + return false; +} + +static void runServeEntry(Interpreter& interpreter, const CliOptions& options) { + if (options.query) { + const auto goals = parseQueryText(*options.query); + printSolutions(interpreter, goals, interpreter.solve(goals, 1000), std::cout); + return; + } + if (interpreter.hasMethod("main") || interpreter.hasAutoEntryCall()) { + const auto result = interpreter.hasMethod("main") + ? interpreter.callMain(makeSystemInput(options.remainingArgs)) + : interpreter.callAutoEntry(); + std::cout << interpreter.valueToDisplayString(result) << "\n"; + } +} + int main(int argc, char** argv) { try { CliOptions options = parseCli(argc, argv); @@ -211,6 +259,34 @@ int main(int argc, char** argv) { if (entryFile.extension() != FILE_EXTENSION) { throw std::runtime_error("Felidae source files must use .fx extension"); } + if (options.serve) { + if (options.repl) { + throw std::runtime_error("--serve cannot be combined with --repl"); + } + std::unique_ptr interpreter; + SourceTimes watched; + const auto reload = [&]() { + auto next = std::make_unique(); + loadProgramRoot(entryFile, *next); + watched = sourceTimes(entryFile, *next); + interpreter = std::move(next); + runServeEntry(*interpreter, options); + std::cerr << "Felidae source interpreter ready: " << entryFile.string() << "\n"; + }; + reload(); + for (;;) { + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + if (!sourceChanged(watched)) continue; + try { + reload(); + } catch (const std::exception& error) { + // Keep the last successfully constructed interpreter live; + // a bad save must not discard the running source program. + watched = sourceTimes(entryFile, *interpreter); + std::cerr << "source reload failed: " << error.what() << "\n"; + } + } + } // A source file becomes executable only after its imports and every // declaration have registered successfully. Running main while the // parser was still producing chunks made later declarations invisible diff --git a/tests/ExecutionVectorMemoryTest.cpp b/tests/ExecutionVectorMemoryTest.cpp deleted file mode 100644 index 5e512ea..0000000 --- a/tests/ExecutionVectorMemoryTest.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include "form/libs/ExecutionVectorMemory.h" -#include "form/IrModule.h" - -#include -#include -#include - -int main() { - using Felidae::Form::ExecutionVectorMemory; - const auto rejects = [](auto action) { - try { action(); } catch (const Felidae::IrError &) { return true; } - return false; - }; - assert(rejects([] { ExecutionVectorMemory invalid(0, 2); })); - assert(rejects([] { ExecutionVectorMemory invalid(2, 0); })); - { - ExecutionVectorMemory first(2, 2), second(2, 2); - std::array state{-212.421f, 3.5f}; - first.append(state); - assert(first.size() == 1 && second.size() == 0); - assert(rejects([&] { first.append(std::span(state).first(1)); })); - for (const float invalid : {std::numeric_limits::infinity(), - std::numeric_limits::quiet_NaN()}) { - state[0] = invalid; - assert(rejects([&] { first.append(state); })); - assert(first.size() == 1); - } - state = {0.0f, -0.25f}; - first.append(state); - assert(first.size() == 2); - assert(rejects([&] { first.append(state); })); - } - ExecutionVectorMemory nextExecution(2, 2); - assert(nextExecution.size() == 0); -} diff --git a/tests/FelidaeIrTest.cpp b/tests/FelidaeIrTest.cpp deleted file mode 100644 index 7c383b3..0000000 --- a/tests/FelidaeIrTest.cpp +++ /dev/null @@ -1,888 +0,0 @@ -#include "form/IrModule.h" -#include "form/RegisterVm.h" -#include "form/libs/Builtin.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -Felidae::Form::BuiltinTextCodec testTextCodec() { - return {[](std::span pieces) { - std::string text; - text.reserve(pieces.size()); - for (const auto piece : pieces) - text.push_back(static_cast(piece)); - return text; - }, - [](std::string_view text) { - Felidae::PieceSequence pieces; - pieces.reserve(text.size()); - for (const unsigned char character : text) - pieces.push_back(character); - return pieces; - }}; -} - -Felidae::VmText testText(std::string_view text) { - return Felidae::VmText{testTextCodec().encode(text)}; -} - -bool rejects(const std::function &action) { - try { - action(); - } catch (const Felidae::IrError &) { - return true; - } - return false; -} - -Felidae::IrModule returning(Felidae::IrConstant value, - Felidae::IrConstantKind kind) { - using namespace Felidae; - IrModule module; - module.sentencePieceModelIdentity = "sha256:test"; - module.symbolTable = {{1}}; - module.entryProcedure = 1; - module.ir.registerCount = 1; - module.ir.symbols = {1}; - module.ir.words = {static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End)}; - IrProcedure procedure; - procedure.ir.registerCount = 1; - procedure.ir.constants = {{kind, value}}; - procedure.ir.words = {static_cast(IrOpcode::LoadConst), 0, 0, - static_cast(IrOpcode::Return), 0, 0, - static_cast(IrOpcode::End)}; - module.procedures.emplace(1, std::move(procedure)); - return module; -} - -Felidae::IrModule numeric(Felidae::NumericOperation operation, - const std::vector &operands) { - using namespace Felidae; - IrModule module; - module.sentencePieceModelIdentity = "sha256:test"; - module.symbolTable = {{1}}; - module.entryProcedure = 1; - module.ir.registerCount = 1; - module.ir.symbols = {1}; - module.ir.words = {static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End)}; - IrProcedure procedure; - procedure.ir.registerCount = operands.size() + 1; - for (std::size_t index = 0; index < operands.size(); ++index) { - procedure.ir.constants.push_back( - {IrConstantKind::Number, encodeIrNumber(operands[index])}); - procedure.ir.words.insert(procedure.ir.words.end(), - {static_cast(IrOpcode::LoadConst), - static_cast(index), - static_cast(index)}); - } - const auto result = static_cast(operands.size()); - procedure.ir.words.insert(procedure.ir.words.end(), - {static_cast(IrOpcode::Numeric), result, - static_cast(operation), - static_cast(operands.size())}); - for (std::size_t index = 0; index < operands.size(); ++index) - procedure.ir.words.push_back(static_cast(index)); - procedure.ir.words.insert(procedure.ir.words.end(), - {static_cast(IrOpcode::Return), result, 0, - static_cast(IrOpcode::End)}); - module.procedures.emplace(1, std::move(procedure)); - return module; -} - -Felidae::IrModule builtin(Felidae::BuiltinId operation, - std::string_view input) { - using namespace Felidae; - IrModule module; - module.sentencePieceModelIdentity = "sha256:test"; - module.symbolTable = {{1}}; - module.entryProcedure = 1; - module.ir.registerCount = 1; - module.ir.symbols = {1}; - module.ir.words = {static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End)}; - IrProcedure procedure; - procedure.ir.registerCount = 2; - procedure.ir.constants = {{IrConstantKind::Text, 0}}; - procedure.ir.texts = {testText(input).pieces}; - procedure.ir.words = {static_cast(IrOpcode::LoadConst), - 0, - 0, - static_cast(IrOpcode::Builtin), - 1, - static_cast(operation), - 1, - 0, - static_cast(IrOpcode::Return), - 1, - 0, - static_cast(IrOpcode::End)}; - module.procedures.emplace(1, std::move(procedure)); - return module; -} - -double executeNumeric(Felidae::NumericOperation operation, - std::vector operands) { - using namespace Felidae; - auto module = verifyIrModule(numeric(operation, operands)); - FelidaeKnowledgeRuntime runtime; - return std::get(RegisterVm{}.executeMain(module, runtime)); -} - -Felidae::IrModule tensor(Felidae::TensorOperation operation, - const std::vector &operands) { - using namespace Felidae; - auto module = numeric(NumericOperation::Min, operands); - auto &words = module.procedures.at(1).ir.words; - const auto instruction = std::find(words.begin(), words.end(), - static_cast(IrOpcode::Numeric)); - assert(instruction != words.end()); - *instruction = static_cast(IrOpcode::Tensor); - *(instruction + 2) = static_cast(operation); - return module; -} - -double executeModulo(double left, double right) { - using namespace Felidae; - auto module = numeric(NumericOperation::Diff, {left, right}); - auto &program = module.procedures.at(1).ir; - program.words = { - static_cast(IrOpcode::LoadConst), - 0, - 0, - static_cast(IrOpcode::LoadConst), - 1, - 1, - static_cast(IrOpcode::Mod), - 2, - 0, - 1, - static_cast(IrOpcode::Return), - 2, - 0, - static_cast(IrOpcode::End), - }; - auto verified = verifyIrModule(std::move(module)); - FelidaeKnowledgeRuntime runtime; - return std::get(RegisterVm{}.executeMain(verified, runtime)); -} - -double executeKeyedEquality(bool facts) { - using namespace Felidae; - auto module = returning(encodeIrNumber(1.0), IrConstantKind::Number); - module.symbolTable = {{1}, {2}, {3}}; - if (facts) - module.factTypes.push_back(IrFactType{.symbol = 1}); - auto &program = module.procedures.at(1).ir; - program.registerCount = 5; - program.constants = { - {IrConstantKind::Number, encodeIrNumber(10.0)}, - {IrConstantKind::Number, encodeIrNumber(20.0)}, - }; - program.symbols = {1, 2, 3}; - program.words = { - static_cast(IrOpcode::LoadConst), 2, 0, - static_cast(IrOpcode::LoadConst), 3, 1, - }; - if (facts) { - program.words.insert(program.words.end(), - {static_cast(IrOpcode::MakeFact), - 0, - 0, - 0, - static_cast(IrOpcode::SetField), - 0, - 1, - 2, - static_cast(IrOpcode::SetField), - 0, - 2, - 3, - static_cast(IrOpcode::MakeFact), - 1, - 0, - 0, - static_cast(IrOpcode::SetField), - 1, - 2, - 3, - static_cast(IrOpcode::SetField), - 1, - 1, - 2}); - } else { - program.words.insert(program.words.end(), - {static_cast(IrOpcode::MakeMap), 0, 0, 2, 1, 2, - 2, 3, static_cast(IrOpcode::MakeMap), 1, 0, 2, - 2, 3, 1, 2}); - } - program.words.insert(program.words.end(), - {static_cast(IrOpcode::Compare), 4, 0, 1, - static_cast(IrComparison::Equal), - static_cast(IrOpcode::Return), 4, 0, - static_cast(IrOpcode::End)}); - auto verified = verifyIrModule(std::move(module)); - FelidaeKnowledgeRuntime runtime; - return std::get(RegisterVm{}.executeMain(verified, runtime)); -} - -bool close(double actual, double expected, double tolerance = 1e-12) { - return std::abs(actual - expected) <= - tolerance * std::max({1.0, std::abs(actual), std::abs(expected)}); -} -} // namespace - -int main() { - using namespace Felidae; - VmRuntime unsupportedRuntime; - IrModule unsupportedModule; - assert( - rejects([&] { unsupportedRuntime.installIrModule(unsupportedModule); })); - assert(rejects([&] { (void)unsupportedRuntime.resolveSymbol(1); })); - assert(rejects( - [&] { unsupportedRuntime.retainFact(std::make_shared()); })); - assert(rejects([&] { - const std::array source{1}; - unsupportedRuntime.retainPersistentFact(std::make_shared(), - source); - })); - assert(rejects([&] { - unsupportedRuntime.mutateFact(std::make_shared(), 1, 1.0); - })); - assert(rejects([&] { unsupportedRuntime.registerFactType(1, {}); })); - - // Fact averages use an extended accumulator, so two individually finite - // large values do not overflow merely while being averaged. A sum whose - // final double result is genuinely non-finite is rejected. - { - FelidaeKnowledgeRuntime aggregateRuntime; - IrModule module; - module.symbolTable = {{1}, {2}}; - aggregateRuntime.installIrModule(module); - const auto type = aggregateRuntime.resolveSymbol(1); - const auto field = aggregateRuntime.resolveSymbol(2); - aggregateRuntime.registerFactType(type, {}); - const auto makeLarge = [&] { - auto fact = std::make_shared(); - fact->type = type; - fact->fields = {{field, std::numeric_limits::max()}}; - return aggregateRuntime.retainFact(fact); - }; - const std::array facts{makeLarge(), makeLarge()}; - const PieceSequence fieldPieces{2}; - assert(aggregateRuntime.aggregateFacts(facts, fieldPieces, 1) == - std::numeric_limits::max()); - assert(rejects( - [&] { (void)aggregateRuntime.aggregateFacts(facts, fieldPieces, 0); })); - } - - VmFactStore hierarchy; - hierarchy.registerType(1, {}, {{10}}); - hierarchy.registerType(2, {1}); - hierarchy.registerType(3, {2}); - hierarchy.registerType(3, {2}); - assert(rejects([&] { hierarchy.registerType(4, {1, 1}); })); - VmFactStore cyclicHierarchy; - cyclicHierarchy.registerType(1, {2}); - cyclicHierarchy.registerType(2, {3}); - assert(rejects([&] { cyclicHierarchy.registerType(3, {1}); })); - auto indexedFactBuilder = std::make_shared(); - indexedFactBuilder->type = 3; - indexedFactBuilder->fields = {{10, 42.0}}; - const auto indexedFact = hierarchy.retain(indexedFactBuilder); - auto secondIndexedFactBuilder = std::make_shared(); - secondIndexedFactBuilder->type = 2; - secondIndexedFactBuilder->fields = {{10, 43.0}}; - const auto secondIndexedFact = hierarchy.retain(secondIndexedFactBuilder); - assert(hierarchy.retain(secondIndexedFact) == secondIndexedFact); - VmFactStore unrelatedStore; - assert(rejects([&] { (void)unrelatedStore.retain(secondIndexedFact); })); - const auto assignable = hierarchy.snapshotAssignableTo(1); - assert(assignable.size() == 2); - assert(assignable[0]->id < assignable[1]->id); - const std::array, 1> exact42{{{10, 42.0}}}; - assert(hierarchy.snapshotMatching(1, exact42) == - std::vector{indexedFact}); - assert((hierarchy.hierarchyProof(3, 1) == std::vector{3, 2, 1})); - assert((hierarchy.commonAncestors(2, 3) == std::vector{1, 2})); - - VmFactStore diamond; - diamond.registerType(1, {}); - diamond.registerType(2, {1}); - diamond.registerType(3, {1}); - diamond.registerType(4, {3, 2}); - diamond.registerType(5, {2}); - assert((diamond.hierarchyProofs(4, 1) == - std::vector>{{4, 2, 1}, {4, 3, 1}})); - const auto evidence = diamond.commonAncestorEvidence(4, 5); - assert(evidence.size() == 2); - assert(evidence[0].ancestor == 1); - assert(evidence[0].leftProofs.size() == 2); - assert(evidence[0].leftDistance == 2 && evidence[0].rightDistance == 2); - assert(evidence[1].ancestor == 2); - assert((evidence[1].leftProofs == - std::vector>{{4, 2}})); - assert(evidence[1].leftDistance == 1 && evidence[1].rightDistance == 1); - VmFactStore deepHierarchy; - deepHierarchy.registerType(1, {}); - for (IrSymbolRef type = 2; type <= 512; ++type) - deepHierarchy.registerType(type, {static_cast(type - 1)}); - const auto deepProofs = deepHierarchy.hierarchyProofs(512, 1); - assert(deepProofs.size() == 1 && deepProofs.front().size() == 512); - // Prime the per-type closure before adding type 5. Registering hierarchy - // edges must invalidate only that cache domain and expose the new path. - assert(hierarchy.hierarchyProof(5, 1).empty()); - hierarchy.registerType(4, {1}); - hierarchy.registerType(5, {2, 4}); - assert((hierarchy.hierarchyProof(5, 1) == std::vector{5, 2, 1})); - assert(hierarchy.snapshotByField(10).size() == 2); - auto invalidFact = std::make_shared(); - invalidFact->type = 0; - assert(rejects([&] { (void)hierarchy.retain(invalidFact); })); - invalidFact->type = 3; - invalidFact->fields = {{10, 1.0}, {10, 2.0}}; - assert(rejects([&] { (void)hierarchy.retain(invalidFact); })); - assert(rejects([&] { hierarchy.mutate(indexedFact, 11, VmFactPtr{}, 0); })); - const auto revisionsBeforeMutation = hierarchy.revisions(); - std::uint64_t knowledgeRevision = - std::numeric_limits::max(); - VmKnowledgeSnapshot knowledgeBeforeMutation; - hierarchy.refreshKnowledgeSnapshot(knowledgeRevision, - knowledgeBeforeMutation); - const auto knowledgeRevisionBeforeMutation = knowledgeRevision; - const auto updatedIndexedFact = hierarchy.mutate(indexedFact, 10, 44.0, 0); - const auto revisionsAfterMutation = hierarchy.revisions(); - assert(revisionsAfterMutation.hierarchy == - revisionsBeforeMutation.hierarchy); - assert(revisionsAfterMutation.membership == - revisionsBeforeMutation.membership); - assert(revisionsAfterMutation.content == - revisionsBeforeMutation.content + 1); - VmKnowledgeSnapshot knowledgeAfterMutation = knowledgeBeforeMutation; - hierarchy.refreshKnowledgeSnapshot(knowledgeRevision, - knowledgeAfterMutation); - assert(knowledgeRevision == knowledgeRevisionBeforeMutation); - assert(knowledgeAfterMutation.factTypes == - knowledgeBeforeMutation.factTypes); - assert(knowledgeAfterMutation.factTypeCounts == - knowledgeBeforeMutation.factTypeCounts); - assert(knowledgeAfterMutation.hierarchyEdges == - knowledgeBeforeMutation.hierarchyEdges); - assert(std::get(indexedFact->fields.front().second) == 42.0); - assert(std::get(updatedIndexedFact->fields.front().second) == 44.0); - assert(hierarchy.snapshotByField(10).front() == updatedIndexedFact); - assert(hierarchy.snapshotAssignableTo(1).front() == updatedIndexedFact); - assert(hierarchy.snapshotMatching(1, exact42).empty()); - const std::array, 1> exact44{{{10, 44.0}}}; - assert(hierarchy.snapshotMatching(1, exact44) == - std::vector{updatedIndexedFact}); - assert(rejects([&] { (void)hierarchy.mutate(indexedFact, 10, 45.0, 0); })); - - VmFactStore compositeIndex; - compositeIndex.registerType(30, {}, {{31, 32}}); - compositeIndex.registerType(33, {30}); - auto compositeBuilder = std::make_shared(); - compositeBuilder->type = 30; - compositeBuilder->fields = {{31, 7.0}, {32, VmText{{9, 10}}}}; - const auto compositeFact = compositeIndex.retain(compositeBuilder); - const std::array, 2> compositePredicates{{ - {32, VmText{{9, 10}}}, {31, 7.0}}}; - assert(compositeIndex.snapshotMatching(30, compositePredicates) == - std::vector{compositeFact}); - const std::array, 1> prefixPredicate{{ - {31, 7.0}}}; - assert(compositeIndex.snapshotMatching(30, prefixPredicate) == - std::vector{compositeFact}); - auto inheritedBuilder = std::make_shared(); - inheritedBuilder->type = 33; - inheritedBuilder->fields = {{31, 7.0}, {32, VmText{{11}}}}; - const auto inheritedFact = compositeIndex.retain(inheritedBuilder); - assert(compositeIndex.snapshotMatching(33, prefixPredicate) == - std::vector{inheritedFact}); - assert(compositeIndex.snapshotMatching(30, prefixPredicate) == - (std::vector{compositeFact, inheritedFact})); - assert(compositeIndex.erase(std::array{compositeFact}) == 1); - assert(compositeIndex.snapshotMatching(30, compositePredicates).empty()); - compositeIndex.restoreErased(compositeFact, std::nullopt); - assert(compositeIndex.snapshotMatching(30, compositePredicates) == - std::vector{compositeFact}); - - VmFactStore concurrentFacts; - concurrentFacts.registerType(20, {}); - auto concurrentBuilder = std::make_shared(); - concurrentBuilder->type = 20; - concurrentBuilder->fields = {{21, 1.0}}; - const auto immutableSnapshot = concurrentFacts.retain(concurrentBuilder); - std::barrier concurrentStart(2); - std::thread reader([&] { - concurrentStart.arrive_and_wait(); - for (std::size_t iteration = 0; iteration < 256; ++iteration) { - // This handle remains readable while the store publishes a replacement. - assert(std::get(immutableSnapshot->fields.front().second) == 1.0); - const auto indexed = concurrentFacts.snapshotByField(21); - assert(indexed.size() == 1); - const auto value = std::get(indexed.front()->fields.front().second); - assert(value == 1.0 || value == 2.0); - assert((concurrentFacts.hierarchyProof(20, 20) == - std::vector{20})); - } - }); - concurrentStart.arrive_and_wait(); - const auto concurrentUpdate = - concurrentFacts.mutate(immutableSnapshot, 21, 2.0, 22); - reader.join(); - assert(std::get(immutableSnapshot->fields.front().second) == 1.0); - assert(std::get(concurrentUpdate->fields.front().second) == 2.0); - assert(concurrentFacts.snapshotByField(21) == - std::vector{concurrentUpdate}); - assert(concurrentFacts.mutations().size() == 1); - assert(concurrentFacts.provenance().size() == 2); - - FelidaeKnowledgeRuntime bindings; - IrModule bindingModule; - bindingModule.symbolTable = {{1}, {2}, {3}}; - bindings.installIrModule(bindingModule); - bindings.storeSymbol(1, 42.0); - assert(std::get(bindings.loadSymbol(1)) == 42.0); - assert(rejects([&] { bindings.storeSymbol(1, 43.0); })); - bindings.enterProcedure(2, std::array{2}, - std::array{7.0}); - assert(std::get(bindings.loadSymbol(2)) == 7.0); - assert(std::get(bindings.loadSymbol(1)) == 42.0); - bindings.storeSymbol(3, 9.0); - assert(std::get(bindings.loadSymbol(3)) == 9.0); - assert(rejects([&] { bindings.storeSymbol(2, 8.0); })); - bindings.leaveProcedure(); - assert(rejects([&] { (void)bindings.loadSymbol(3); })); - assert(rejects([&] { (void)bindings.resolveSymbol(4); })); - - FelidaeKnowledgeRuntime persistentSymbols; - IrModule firstSymbols; - firstSymbols.symbolTable = {{11}, {12, 13}}; - persistentSymbols.installIrModule(firstSymbols); - const auto firstType = persistentSymbols.resolveSymbol(1); - const auto sharedField = persistentSymbols.resolveSymbol(2); - persistentSymbols.registerFactType(firstType, {}); - auto firstFact = std::make_shared(); - firstFact->type = firstType; - firstFact->fields = {{sharedField, 1.0}}; - const auto retainedFirstFact = persistentSymbols.retainFact(firstFact); - - IrModule secondSymbols; - secondSymbols.symbolTable = {{21}, {12, 13}}; - persistentSymbols.installIrModule(secondSymbols); - const auto secondType = persistentSymbols.resolveSymbol(1); - assert(secondType != firstType); - assert(persistentSymbols.resolveSymbol(2) == sharedField); - persistentSymbols.registerFactType(secondType, {}); - auto secondFact = std::make_shared(); - secondFact->type = secondType; - secondFact->fields = {{sharedField, 2.0}}; - const auto retainedSecondFact = persistentSymbols.retainFact(secondFact); - assert(persistentSymbols.snapshotFacts(firstType) == - std::vector{retainedFirstFact}); - assert(persistentSymbols.snapshotFacts(secondType) == - std::vector{retainedSecondFact}); - - const auto textCodec = testTextCodec(); - const std::vector noSymbols; - const auto parsed = Form::evaluateBuiltin( - BuiltinId::JsonParse, - std::array{testText("{\"name\":\"Ada\",\"active\":true}")}, - noSymbols, textCodec); - assert(std::holds_alternative(parsed)); - const auto name = Form::evaluateBuiltin( - BuiltinId::JsonGet, std::array{parsed, testText("name")}, - noSymbols, textCodec); - assert(std::get(name).pieces == testText("Ada").pieces); - assert(std::get(Form::evaluateBuiltin( - BuiltinId::JsonHas, - std::array{parsed, testText("active")}, noSymbols, - textCodec)) == 1.0); - const auto keys = - Form::evaluateBuiltin(BuiltinId::JsonKeys, std::array{parsed}, - noSymbols, textCodec); - assert(std::get(keys)->values.size() == 2); - const auto updated = Form::evaluateBuiltin( - BuiltinId::JsonSet, - std::array{parsed, testText("score"), VmValue{42.0}}, - noSymbols, textCodec); - const auto removed = - Form::evaluateBuiltin(BuiltinId::JsonRemove, - std::array{updated, testText("active")}, - noSymbols, textCodec); - assert(std::get(Form::evaluateBuiltin( - BuiltinId::JsonHas, - std::array{removed, testText("active")}, noSymbols, - textCodec)) == 0.0); - const auto jsonText = Form::evaluateBuiltin(BuiltinId::JsonToText, - std::array{removed}, - noSymbols, textCodec); - assert(testTextCodec().decode(std::get(jsonText).pieces) == - "{\"name\":\"Ada\",\"score\":42.0}"); - const auto csvRows = Form::evaluateBuiltin( - BuiltinId::CsvParse, - std::array{testText("name,score\nAda,42\n")}, noSymbols, - textCodec); - assert(std::get(csvRows)->values.size() == 1); - assert(std::get(Form::evaluateBuiltin( - BuiltinId::ArrayLen, std::array{csvRows}, noSymbols, - textCodec)) == 1.0); - assert(std::get(Form::evaluateBuiltin( - BuiltinId::ArrayGet, - std::array{csvRows, VmValue{0.0}}, noSymbols, - textCodec)) - ->entries.size() == 2); - auto aggregateValues = std::make_shared(); - aggregateValues->values = {2.0, 4.0, 6.0}; - assert(std::get(Form::evaluateBuiltin( - BuiltinId::Sum, std::array{aggregateValues}, - noSymbols, textCodec)) == 12.0); - assert(std::get(Form::evaluateBuiltin( - BuiltinId::Average, std::array{aggregateValues}, - noSymbols, textCodec)) == 4.0); - const auto csvText = Form::evaluateBuiltin(BuiltinId::CsvToText, - std::array{csvRows}, - noSymbols, textCodec); - assert(testTextCodec().decode(std::get(csvText).pieces) == - "name,score\nAda,42\n"); - assert(rejects([&] { - (void)Form::evaluateBuiltin( - BuiltinId::CsvToFacts, - std::array{testText("name,score\nAda,42\n"), - testText("Person")}, - noSymbols, textCodec); - })); - const auto felidaeFacts = Form::evaluateBuiltin( - BuiltinId::CsvToFelidaeFacts, - std::array{csvRows, testText("Person")}, noSymbols, - textCodec); - assert(testTextCodec().decode(std::get(felidaeFacts).pieces) == - "Person(name: \"Ada\", score: \"42\")\n"); - - const auto groupData = Form::evaluateBuiltin( - BuiltinId::JsonParse, - std::array{testText( - R"({"set":[0,1],"table":[{"left":0,"right":0,"result":0},{"left":0,"right":1,"result":1},{"left":1,"right":0,"result":1},{"left":1,"right":1,"result":0}]})")}, - noSymbols, textCodec); - const auto groupSet = Form::evaluateBuiltin( - BuiltinId::JsonGet, std::array{groupData, testText("set")}, - noSymbols, textCodec); - const auto groupTable = Form::evaluateBuiltin( - BuiltinId::JsonGet, std::array{groupData, testText("table")}, - noSymbols, textCodec); - for (const auto operation : - {BuiltinId::GroupClosed, BuiltinId::GroupAssociative, - BuiltinId::GroupCommutative}) { - assert(std::get(Form::evaluateBuiltin( - operation, std::array{groupSet, groupTable}, - noSymbols, textCodec)) == 1.0); - } - for (const auto operation : - {BuiltinId::GroupIdentity, BuiltinId::GroupInverse, - BuiltinId::GroupAbelian}) { - assert(std::get(Form::evaluateBuiltin( - operation, - std::array{groupSet, groupTable, VmValue{0.0}}, - noSymbols, textCodec)) == 1.0); - } - const auto groupValidation = Form::evaluateBuiltin( - BuiltinId::GroupValidate, - std::array{groupSet, groupTable, VmValue{0.0}}, noSymbols, - textCodec); - assert(std::get(Form::evaluateBuiltin( - BuiltinId::JsonGet, - std::array{groupValidation, testText("valid")}, - noSymbols, textCodec)) == 1.0); - assert(rejects([&] { - auto empty = std::make_shared(); - (void)Form::evaluateBuiltin( - BuiltinId::GroupClosed, - std::array{empty, std::make_shared()}, noSymbols, - textCodec); - })); - assert(rejects([&] { - auto duplicateMembers = std::make_shared(); - duplicateMembers->values = {0.0, 0.0}; - (void)Form::evaluateBuiltin( - BuiltinId::GroupClosed, - std::array{duplicateMembers, groupTable}, noSymbols, - textCodec); - })); - - const auto setInputs = Form::evaluateBuiltin( - BuiltinId::JsonParse, std::array{testText("[[1,2,2],[2,3]]")}, - noSymbols, textCodec); - const auto fields = Form::evaluateBuiltin( - BuiltinId::JsonParse, std::array{testText("[]")}, noSymbols, - textCodec); - const auto setResult = [&](BuiltinId operation, - std::initializer_list inputs) { - return Form::evaluateBuiltin( - operation, std::span{inputs.begin(), inputs.size()}, - noSymbols, textCodec); - }; - assert(std::get(setResult(BuiltinId::SetUnion, {setInputs})) - ->values.size() == 3); - assert( - std::get(setResult(BuiltinId::SetIntersection, {setInputs})) - ->values.size() == 1); - assert(std::get(setResult(BuiltinId::SetDifference, {setInputs})) - ->values.size() == 1); - assert(std::get( - setResult(BuiltinId::SetSymmetricDifference, {setInputs})) - ->values.size() == 2); - assert(std::get(setResult(BuiltinId::SetEquals, {setInputs})) == 0.0); - assert(std::get(setResult(BuiltinId::SetSubset, {setInputs})) == 0.0); - assert(std::get(setResult(BuiltinId::SetSuperset, {setInputs})) == - 0.0); - assert(std::get(setResult(BuiltinId::SetDisjoint, {setInputs})) == - 0.0); - const auto firstSet = Form::evaluateBuiltin( - BuiltinId::JsonParse, std::array{testText("[1,2,2]")}, - noSymbols, textCodec); - assert(std::get(setResult(BuiltinId::SetCardinality, {firstSet})) == - 2.0); - assert(std::get(setResult(BuiltinId::SetContains, - {firstSet, VmValue{2.0}})) == 1.0); - for (const auto operation : - {BuiltinId::SetIntersectionBy, BuiltinId::SetDifferenceBy, - BuiltinId::SetSymmetricDifferenceBy, BuiltinId::SetEqualsBy, - BuiltinId::SetSubsetBy, BuiltinId::SetDisjointBy}) { - assert(!std::holds_alternative( - setResult(operation, {setInputs, fields}))); - } - const auto objectSet = Form::evaluateBuiltin( - BuiltinId::JsonParse, - std::array{testText(R"([{"id":1},{"id":2}])")}, noSymbols, - textCodec); - const auto idField = Form::evaluateBuiltin( - BuiltinId::JsonParse, std::array{testText("[\"id\"]")}, - noSymbols, textCodec); - assert(std::get(setResult(BuiltinId::SetContainsBy, - {objectSet, VmValue{2.0}, idField})) == - 1.0); - assert(rejects([&] { - (void)Form::evaluateBuiltin(BuiltinId::JsonParse, - std::array{testText("{invalid")}, - noSymbols, textCodec); - })); - - auto parsedByVm = verifyIrModule( - builtin(BuiltinId::JsonParse, "{\"active\":true,\"score\":42}")); - FelidaeKnowledgeRuntime builtinRuntime(nullptr, 1024, 256, {}, nullptr, - textCodec.decode, textCodec.encode); - const auto vmObject = RegisterVm{}.executeMain(parsedByVm, builtinRuntime); - assert(std::holds_alternative(vmObject)); - assert(rejects([&] { - FelidaeKnowledgeRuntime missingCodec; - (void)RegisterVm{}.executeMain(parsedByVm, missingCodec); - })); - - static_assert(sizeof(IrWord) == 4); - static_assert(sizeof(IrConstant) == 8); - FelidaeKnowledgeRuntime runtime; - auto number = - verifyIrModule(returning(encodeIrNumber(42.0), IrConstantKind::Number)); - assert(std::get(RegisterVm{}.executeMain(number, runtime)) == 42.0); - assert(executeKeyedEquality(false) == 1.0); - assert(executeKeyedEquality(true) == 1.0); - - FelidaeKnowledgeRuntime truthRuntime; - auto truth = verifyIrModule(returning(1, IrConstantKind::Boolean)); - const auto truthValue = RegisterVm{}.executeMain(truth, truthRuntime); - assert(std::holds_alternative(truthValue)); - assert(std::get(truthValue) == 1.0); - assert(vmValueToDisplayString(truthValue) == "1.0"); - - FelidaeKnowledgeRuntime falseRuntime; - auto falseTruth = verifyIrModule(returning(0, IrConstantKind::Boolean)); - const auto falseValue = RegisterVm{}.executeMain(falseTruth, falseRuntime); - assert(std::holds_alternative(falseValue)); - assert(std::get(falseValue) == 0.0); - assert(vmValueToDisplayString(falseValue) == "0.0"); - - assert(numericOperationForName("min") == NumericOperation::Min); - assert(numericOperationForName("weighted_avg") == - NumericOperation::WeightedAverage); - assert(numericOperationForName("in_range") == NumericOperation::InRange); - assert(!numericOperationForName("MIN")); - assert(close(executeNumeric(NumericOperation::Min, {0.8, 0.3}), 0.3)); - assert(close(executeNumeric(NumericOperation::Max, {0.8, 0.3}), 0.8)); - assert(close(executeNumeric(NumericOperation::Abs, {-4.5}), 4.5)); - assert(close(executeNumeric(NumericOperation::Diff, {8.2, 5.0}), 3.2)); - assert(close(executeNumeric(NumericOperation::Average, {10, 20}), 15)); - assert(close(executeNumeric(NumericOperation::Average, - {std::numeric_limits::max(), - std::numeric_limits::max()}), - std::numeric_limits::max())); - assert(close( - executeNumeric(NumericOperation::WeightedAverage, {10, 20, 1, 3}), 17.5)); - assert(close(executeNumeric(NumericOperation::Clamp, {1.4, 0, 1}), 1)); - assert(close(executeNumeric(NumericOperation::Clamp, {-0.2, 0, 1}), 0)); - assert(close(executeNumeric(NumericOperation::Floor, {-4.2}), -5)); - assert(close(executeNumeric(NumericOperation::Ceil, {-4.8}), -4)); - assert(close(executeNumeric(NumericOperation::Round, {4.6}), 5)); - assert(close(executeNumeric(NumericOperation::Round, {-4.6}), -5)); - assert(close(executeNumeric(NumericOperation::Trunc, {-4.8}), -4)); - assert(close(executeNumeric(NumericOperation::Sqrt, {9}), 3)); - assert(close(executeNumeric(NumericOperation::Cbrt, {-8}), -2)); - assert(close(executeNumeric(NumericOperation::Pow, {2, 3}), 8)); - assert(close(executeModulo(7.5, 2), 1.5)); - assert(close(executeModulo(-7.5, 2), -1.5)); - assert(close(executeNumeric(NumericOperation::Exp, {0}), 1)); - assert(close(executeNumeric(NumericOperation::Log, {std::exp(1.0)}), 1)); - assert(close(executeNumeric(NumericOperation::Log10, {1000}), 3)); - assert(close(executeNumeric(NumericOperation::Lerp, {10, 20, 0.25}), 12.5)); - assert(close(executeNumeric(NumericOperation::Sign, {-7.2}), -1)); - assert(close(executeNumeric(NumericOperation::Sign, {0}), 0)); - assert(close(executeNumeric(NumericOperation::Sign, {7.2}), 1)); - assert(close(executeNumeric(NumericOperation::Reciprocal, {4}), 0.25)); - assert(close(executeNumeric(NumericOperation::Square, {3}), 9)); - assert(close(executeNumeric(NumericOperation::Cube, {-2}), -8)); - assert(close(executeNumeric(NumericOperation::Max, {-345.345, -2.302}), - -2.302)); - assert(close(executeNumeric(NumericOperation::Average, {3.432, -2.302}), - 0.565)); - assert(executeNumeric(NumericOperation::InRange, {0.7, 0, 1}) == 1.0); - assert(executeNumeric(NumericOperation::InRange, {-0.1, 0, 1}) == 0.0); - assert(executeNumeric(NumericOperation::InRange, {0, 0, 1}) == 1.0); - assert(executeNumeric(NumericOperation::InRange, {1, 0, 1}) == 1.0); - assert(executeNumeric(NumericOperation::IsFinite, {1.5}) == 1.0); - assert(executeNumeric(NumericOperation::IsFinite, - {std::numeric_limits::infinity()}) == 0.0); - assert(executeNumeric(NumericOperation::IsFinite, - {std::numeric_limits::quiet_NaN()}) == 0.0); - assert(executeNumeric(NumericOperation::IsNan, - {std::numeric_limits::quiet_NaN()}) == 1.0); - assert(executeNumeric(NumericOperation::IsNan, - {std::numeric_limits::infinity()}) == 0.0); - - assert(rejects([&] { - (void)executeNumeric(NumericOperation::WeightedAverage, {1, 2, 1, -1}); - })); - assert(rejects( - [&] { (void)executeNumeric(NumericOperation::Clamp, {0, 1, -1}); })); - assert(rejects([&] { (void)executeNumeric(NumericOperation::Sqrt, {-1}); })); - assert(rejects([&] { (void)executeNumeric(NumericOperation::Log, {0}); })); - assert(rejects([&] { (void)executeNumeric(NumericOperation::Log10, {-1}); })); - assert( - rejects([&] { (void)executeNumeric(NumericOperation::Pow, {-1, 0.5}); })); - assert(rejects([&] { (void)executeNumeric(NumericOperation::Exp, {1000}); })); - assert(rejects( - [&] { (void)executeNumeric(NumericOperation::Reciprocal, {0}); })); - assert(rejects([&] { (void)executeModulo(7.5, 0); })); - assert(rejects([&] { - (void)executeModulo(std::numeric_limits::infinity(), 2); - })); - assert(rejects( - [&] { (void)executeNumeric(NumericOperation::InRange, {0, 1, -1}); })); - assert(rejects([&] { - (void)executeNumeric(NumericOperation::Square, - {std::numeric_limits::max()}); - })); - assert(rejects([&] { - (void)executeNumeric(NumericOperation::Abs, - {std::numeric_limits::infinity()}); - })); - - auto invalidArity = numeric(NumericOperation::Abs, {1, 2}); - assert(rejects([&] { (void)verifyIrModule(std::move(invalidArity)); })); - - auto verifiedTensor = verifyIrModule(tensor(TensorOperation::Size, {1})); - FelidaeKnowledgeRuntime noTensorBackend; - assert(rejects([&] { - (void)RegisterVm{}.executeMain(verifiedTensor, noTensorBackend); - })); - auto invalidTensorArity = tensor(TensorOperation::Size, {1, 2}); - assert(rejects([&] { (void)verifyIrModule(std::move(invalidTensorArity)); })); - auto invalidTensorOperation = tensor(TensorOperation::Count, {1}); - assert(rejects( - [&] { (void)verifyIrModule(std::move(invalidTensorOperation)); })); - - auto invalidBuiltinOperation = builtin( - static_cast(static_cast(BuiltinId::Last) + 1), - "{}"); - assert(rejects( - [&] { (void)verifyIrModule(std::move(invalidBuiltinOperation)); })); - auto invalidBuiltinArity = builtin(BuiltinId::JsonParse, "{}"); - auto &invalidArityWords = invalidBuiltinArity.procedures.at(1).ir.words; - invalidArityWords[6] = 0; - invalidArityWords.erase(invalidArityWords.begin() + 7); - assert( - rejects([&] { (void)verifyIrModule(std::move(invalidBuiltinArity)); })); - auto uninitializedBuiltinOperand = builtin(BuiltinId::JsonParse, "{}"); - auto &uninitializedWords = - uninitializedBuiltinOperand.procedures.at(1).ir.words; - uninitializedWords.erase(uninitializedWords.begin(), - uninitializedWords.begin() + 3); - assert(rejects( - [&] { (void)verifyIrModule(std::move(uninitializedBuiltinOperand)); })); - - auto invalid = returning(encodeIrNumber(1.0), IrConstantKind::Number); - invalid.procedures.at(1).ir.words[1] = 99; - assert(rejects([&] { (void)verifyIrModule(std::move(invalid)); })); - - // Classes and ordinary facts share IrFactType, so the authoritative IR - // verifier must reject cycles across that mixed hierarchy just as it does - // cycles containing only one source declaration form. - auto cyclicTypes = returning(encodeIrNumber(1.0), IrConstantKind::Number); - cyclicTypes.symbolTable = {{1}, {2}, {3}}; - cyclicTypes.factTypes = { - IrFactType{.symbol = 2, .parents = {3}}, - IrFactType{.symbol = 3, .parents = {2}}, - }; - assert(rejects([&] { (void)verifyIrModule(std::move(cyclicTypes)); })); - - IrModule loop; - loop.sentencePieceModelIdentity = "sha256:test"; - loop.symbolTable = {{1}}; - loop.entryProcedure = 1; - loop.ir.registerCount = 1; - loop.ir.symbols = {1}; - loop.ir.words = {static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End)}; - IrProcedure loopProcedure; - loopProcedure.ir.registerCount = 0; - loopProcedure.ir.words = {static_cast(IrOpcode::Jump), 0, - static_cast(IrOpcode::End)}; - loop.procedures.emplace(1, std::move(loopProcedure)); - auto verifiedLoop = verifyIrModule(std::move(loop)); - FelidaeKnowledgeRuntime loopRuntime; - assert(rejects( - [&] { (void)RegisterVm{16}.executeMain(verifiedLoop, loopRuntime); })); - return 0; -} diff --git a/tests/FormBinaryIrTest.cpp b/tests/FormBinaryIrTest.cpp deleted file mode 100644 index da8457b..0000000 --- a/tests/FormBinaryIrTest.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "form/BinaryIr.h" - -#include -#include -#include -#include -#include - -namespace { -bool rejects(const std::function &action) { - try { - action(); - } catch (const Felidae::IrError &) { - return true; - } - return false; -} -} // namespace - -int main() { - using namespace Felidae; - const std::filesystem::path output(FELIDAE_TEST_OUTPUT_DIR); - std::filesystem::create_directories(output); - IrModule module; - module.sentencePieceModelIdentity = "sha256:test-model"; - // Similar prefixes remain distinct because complete PieceId sequences, - // rather than a hash, define module-local symbol identity. - module.symbolTable = {{11, 12}, {11, 13}}; - module.entryProcedure = 1; - module.ir.registerCount = 1; - module.ir.symbols = {1}; - module.ir.words = {static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End)}; - IrProcedure procedure; - procedure.ir.registerCount = 1; - procedure.ir.constants = {{IrConstantKind::Number, encodeIrNumber(42.0)}}; - procedure.ir.texts = {{21, 22, 23}}; - procedure.ir.words = {static_cast(IrOpcode::LoadConst), 0, 0, - static_cast(IrOpcode::Return), 0, 0, - static_cast(IrOpcode::End)}; - module.procedures.emplace(1, std::move(procedure)); - auto verified = verifyIrModule(std::move(module)); - const auto path = output / "felidae_ir_binary_test.bin"; - writeBinaryIr(path, verified); - std::array magic{}; - { - std::ifstream input(path, std::ios::binary); - input.read(magic.data(), 8); - } - assert( - (magic == std::array{'F', 'E', 'L', 'B', 'I', 'R', '\0', '\0'})); - const auto loaded = loadBinaryIr(path, "sha256:test-model"); - assert(loaded->symbolTable == verified->symbolTable); - assert(loaded->symbolTable[0] != loaded->symbolTable[1]); - assert(loaded->procedures.at(1).ir.texts == - verified->procedures.at(1).ir.texts); - FelidaeKnowledgeRuntime runtime; - assert(std::get(RegisterVm{}.executeMain(loaded, runtime)) == 42.0); - assert(rejects([&] { (void)loadBinaryIr(path, "sha256:wrong-model"); })); - const auto malformed = output / "felidae_ir_malformed.bin"; - { - std::ofstream out(malformed, std::ios::binary); - out << "not FELBIR"; - } - assert(rejects([&] { (void)loadBinaryIr(malformed, "sha256:test-model"); })); - std::error_code ignored; - std::filesystem::remove(path, ignored); - std::filesystem::remove(malformed, ignored); - return 0; -} diff --git a/tests/FormDbCsvTest.cpp b/tests/FormDbCsvTest.cpp deleted file mode 100644 index 0aca7ea..0000000 --- a/tests/FormDbCsvTest.cpp +++ /dev/null @@ -1,582 +0,0 @@ -// Section-13 audit coverage: CSV <-> Fact, round trip, multi-file ownership, -// and atomic persistence, all against real files in a temporary test-output -// directory. No mocked persistence -- Form::Db::sync and Form::Csv perform -// real disk I/O throughout, exercised the same way RegisterVm.cpp's Builtin -// dispatch uses them for CSV import and automatic fact persistence. - -#include "form/IrModule.h" -#include "form/RegisterVm.h" -#include "form/libs/Builtin.h" -#include "form/libs/Csv.h" -#include "form/libs/Db.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace { -using namespace Felidae; - -// Identity byte encoding, matching the pattern used by FelidaeIrTest.cpp's -// testTextCodec(): each source byte becomes one PieceId, so encode/decode -// round-trip exactly without depending on any trained SentencePiece model. -Form::BuiltinTextCodec testTextCodec() { - return {[](std::span pieces) { - std::string text; - text.reserve(pieces.size()); - for (const auto piece : pieces) - text.push_back(static_cast(piece)); - return text; - }, - [](std::string_view text) { - PieceSequence pieces; - pieces.reserve(text.size()); - for (const unsigned char character : text) - pieces.push_back(character); - return pieces; - }}; -} - -bool rejects(const std::function &action) { - try { - action(); - } catch (const IrError &) { - return true; - } catch (const std::exception &) { - return true; - } - return false; -} - -std::string readFile(const std::filesystem::path &path) { - std::ifstream input(path, std::ios::binary); - if (!input) - throw std::runtime_error("test cannot open " + path.string()); - std::ostringstream buffer; - buffer << input.rdbuf(); - return buffer.str(); -} - -std::pair field(IrSymbolRef name, VmText value) { - return std::pair(name, VmValue(std::move(value))); -} - -VmFactPtr makeFact(IrSymbolRef type, - std::vector> fields) { - auto fact = std::make_shared(); - fact->type = type; - fact->fields = std::move(fields); - return fact; -} - -void persistThroughDml(FelidaeKnowledgeRuntime &runtime, - const VmArrayPtr &rows) { - assert(rows && !rows->values.empty()); - const auto fact = std::get(rows->values.front()); - assert(fact && !fact->fields.empty()); - auto unchanged = std::make_shared(); - unchanged->entries.push_back(fact->fields.front()); - (void)runtime.updateFacts(std::array{fact}, unchanged); -} - -} // namespace - -int main() { - const Form::BuiltinTextCodec codec = testTextCodec(); - - // LIMIT is an ordinary deterministic array operation after query lowering: - // it preserves order, clamps oversized requests, and rejects unsafe counts. - { - auto rows = std::make_shared(); - rows->values = {10.0, 20.0, 30.0}; - const std::span noSymbols; - const auto limit = [&](double records) { - return std::get(Form::evaluateBuiltin( - BuiltinId::ArrayLimit, - std::array{VmValue{rows}, VmValue{records}}, noSymbols, - codec)); - }; - const auto firstTwo = limit(2.0); - assert(firstTwo->values.size() == 2); - assert(std::get(firstTwo->values[0]) == 10.0); - assert(std::get(firstTwo->values[1]) == 20.0); - assert(limit(0.0)->values.empty()); - assert(limit(1.0e100)->values.size() == rows->values.size()); - assert(rejects([&] { (void)limit(-1.0); })); - assert(rejects([&] { (void)limit(1.5); })); - assert(rejects( - [&] { (void)limit(std::numeric_limits::infinity()); })); - assert(rejects( - [&] { (void)limit(std::numeric_limits::quiet_NaN()); })); - } - - const std::filesystem::path outDir(FELIDAE_TEST_OUTPUT_DIR); - std::error_code ignored; - std::filesystem::remove_all(outDir, ignored); - std::filesystem::create_directories(outDir); - - // --------------------------------------------------------------------- - // CSV -> Fact - // --------------------------------------------------------------------- - { - // RFC4180 quoting: a quote only opens quoted mode as a field's first - // character, so an embedded comma inside quotes stays inside one field - // and a doubled "" decodes to one literal quote (the parseLine fix). - const std::string csv = "name,note\n" - "Ada,\"hello, world\"\n" - "Grace,\"she said \"\"hi\"\"\"\n"; - const auto rows = Form::Csv::toFacts(csv, "Person"); - assert(rows.is_array() && rows.size() == 2); - assert(rows[0]["__type"] == "Person"); - assert(rows[0]["name"] == "Ada"); - assert(rows[0]["note"] == "hello, world"); - assert(rows[1]["name"] == "Grace"); - assert(rows[1]["note"] == "she said \"hi\""); - - // Numeric coercion, with the leading-zero guard: "42" becomes a real - // number, but "007" stays text (a code, not the number 7). - const auto numeric = Form::Csv::toFacts("id,code\n42,007\n", "Row"); - assert(numeric[0]["id"].is_number()); - assert(numeric[0]["id"] == 42.0); - assert(numeric[0]["code"].is_string()); - assert(numeric[0]["code"] == "007"); - - // Blank-line handling (the parseRows fix): a blank line is skipped for - // multi-column data, but for single-column data it is the only way to - // represent an intentional empty-string row and must be kept. - const auto multiColumn = Form::Csv::parse("a,b\n1,2\n\n3,4\n"); - assert(multiColumn.size() == 2); - const auto singleColumn = Form::Csv::parse("a\nx\n\ny\n"); - assert(singleColumn.size() == 3); - assert(singleColumn[1]["a"] == ""); - - // An unterminated quoted field is a real parse error, not silently - // truncated data. - assert(rejects([&] { (void)Form::Csv::parse("a\n\"unterminated"); })); - } - - // --------------------------------------------------------------------- - // Fact search is deliberately separate from equality/predicate `where`: - // it provides discovery over text patterns, hierarchy-valued properties, - // and graded numeric evidence while preserving stable fact order. - // --------------------------------------------------------------------- - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - const std::vector names{ - "Catalog", "title", "confidence", "category", - "type", "query", "case", "direction", - "includeSelf", "minimum", "maximum", "tolerance", - "Publication", "Book", "Magazine"}; - IrModule module; - for (const auto &name : names) - module.symbolTable.push_back(codec.encode(name)); - runtime.installIrModule(module); - const auto symbol = [&](std::size_t oneBased) { - return runtime.resolveSymbol(static_cast(oneBased)); - }; - runtime.registerFactType(symbol(13), {}); - runtime.registerFactType(symbol(14), {symbol(13)}); - runtime.registerFactType(symbol(15), {symbol(13)}); - runtime.registerFactType(symbol(1), {}); - const auto catalog = [&](std::string_view title, double confidence, - IrSymbolRef category) { - auto fact = std::make_shared(); - fact->type = symbol(1); - fact->fields = { - {symbol(2), VmText{codec.encode(title)}}, - {symbol(3), confidence}, - {symbol(4), VmSymbol{category}}, - }; - return runtime.retainFact(fact); - }; - const std::array facts{ - catalog("Alpha Guide", 0.82, symbol(14)), - catalog("beta guide", 0.74, symbol(15)), - catalog("Reference", 0.40, symbol(13))}; - const auto options = [&](std::initializer_list< - std::pair> entries) { - auto result = std::make_shared(); - result->entries.assign(entries.begin(), entries.end()); - return result; - }; - - const auto likeRows = std::get(runtime.searchFacts( - facts, codec.encode("title"), - options({{symbol(5), VmText{codec.encode("like")}}, - {symbol(6), VmText{codec.encode("%guide")}}, - {symbol(7), VmText{codec.encode("insensitive")}}}))); - assert(likeRows && likeRows->values.size() == 2); - - const auto hierarchyRows = std::get(runtime.searchFacts( - facts, codec.encode("category"), - options({{symbol(5), VmText{codec.encode("hierarchy")}}, - {symbol(6), VmSymbol{symbol(13)}}, - {symbol(8), VmText{codec.encode("descendants")}}, - {symbol(9), 0.0}}))); - assert(hierarchyRows && hierarchyRows->values.size() == 2); - - const auto degreeRows = std::get(runtime.searchFacts( - facts, codec.encode("confidence"), - options({{symbol(5), VmText{codec.encode("degree")}}, - {symbol(10), 0.70}, - {symbol(11), 0.90}}))); - assert(degreeRows && degreeRows->values.size() == 2); - } - - // --------------------------------------------------------------------- - // Fact -> CSV, round trip, and schema (column order) preservation - // --------------------------------------------------------------------- - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - IrModule module; - module.symbolTable = {codec.encode("School")}; - runtime.installIrModule(module); - runtime.registerFactType(/*type=*/1, /*parents=*/{}); - - const std::string csv = "name,district,students\n" - "North,central,420\n" - "West,west,280\n" - "Lake,central,350\n"; - const auto typePieces = codec.encode("School"); - const auto path = outDir / "roundtrip_schools.csv"; - const auto sourcePieces = codec.encode(path.string()); - const auto imported = runtime.importCsvFacts( - codec.encode(csv), typePieces, sourcePieces); - const auto importedArray = std::get(imported); - assert(importedArray && importedArray->values.size() == 3); - - persistThroughDml(runtime, importedArray); - assert(std::filesystem::exists(path)); - - const auto writtenText = readFile(path); - // Bare parse() never coerces field types (only toFacts() does), so it is - // the right tool for a type-agnostic check of column order alone. - const auto writtenParsed = Form::Csv::parse(writtenText); - assert(writtenParsed.size() == 3); - // Schema preservation: the header column order on disk must match the - // source CSV's column order exactly, not an arbitrary field order. - std::vector writtenColumns; - for (const auto &[key, _] : writtenParsed.front().items()) - writtenColumns.push_back(key); - assert((writtenColumns == std::vector{"name", "district", - "students"})); - // Round trip: values, including numeric coercion, survive - // CSV -> Fact -> CSV -> Fact unchanged. - const auto writtenRows = Form::Csv::toFacts(writtenText, "School"); - assert(writtenRows[0]["name"] == "North"); - assert(writtenRows[0]["district"] == "central"); - assert(writtenRows[0]["students"].is_number()); - assert(writtenRows[0]["students"] == 420.0); - assert(writtenRows[1]["name"] == "West"); - assert(writtenRows[2]["district"] == "central"); - } - - // --------------------------------------------------------------------- - // Multi-file ownership: two fact types imported from two different - // source files must sync back to exactly their own file, never the - // other type's rows and never the whole store. - // --------------------------------------------------------------------- - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - IrModule module; - module.symbolTable = {codec.encode("School"), codec.encode("Teacher")}; - runtime.installIrModule(module); - runtime.registerFactType(/*type=*/1, /*parents=*/{}); - runtime.registerFactType(/*type=*/2, /*parents=*/{}); - - const auto schoolsPath = outDir / "ownership_schools.csv"; - const auto teachersPath = outDir / "ownership_teachers.csv"; - const auto schoolsSource = codec.encode(schoolsPath.string()); - const auto teachersSource = codec.encode(teachersPath.string()); - - const auto schoolsImported = runtime.importCsvFacts( - codec.encode("name,district\nNorth,central\nWest,west\n"), codec.encode("School"), - schoolsSource); - const auto teachersImported = runtime.importCsvFacts( - codec.encode("name,subject\nAda,math\nBo,science\nCy,art\n"), - codec.encode("Teacher"), teachersSource); - assert(std::get(schoolsImported)->values.size() == 2); - assert(std::get(teachersImported)->values.size() == 3); - - persistThroughDml(runtime, std::get(schoolsImported)); - persistThroughDml(runtime, std::get(teachersImported)); - - const auto schoolsRows = Form::Csv::parse(readFile(schoolsPath)); - const auto teachersRows = Form::Csv::parse(readFile(teachersPath)); - assert(schoolsRows.size() == 2); - assert(teachersRows.size() == 3); - for (const auto &row : schoolsRows) { - assert(row.contains("district")); - assert(!row.contains("subject")); - } - for (const auto &row : teachersRows) { - assert(row.contains("subject")); - assert(!row.contains("district")); - } - } - - // --------------------------------------------------------------------- - // Automatic DML persistence: update, inferred-source insert, and delete - // each commit the owning CSV without a public db.sync() call. - // --------------------------------------------------------------------- - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - IrModule module; - module.symbolTable = {codec.encode("School")}; - runtime.installIrModule(module); - runtime.registerFactType(/*type=*/1, /*parents=*/{}); - - const auto path = outDir / "automatic_dml.csv"; - const auto source = codec.encode(path.string()); - const auto type = codec.encode("School"); - const auto imported = std::get(runtime.importCsvFacts( - codec.encode("name,students\nNorth,420\nWest,280\n"), type, - source)); - assert(imported && imported->values.size() == 2); - const auto north = std::get(imported->values[0]); - const auto west = std::get(imported->values[1]); - assert(north && west && north->fields.size() == 2); - - auto update = std::make_shared(); - update->entries.emplace_back(north->fields[1].first, 425.0); - const std::array updateTargets{north}; - (void)runtime.updateFacts(updateTargets, update); - auto rows = Form::Csv::toFacts(readFile(path), "School"); - assert(rows.size() == 2 && rows[0]["students"] == 425.0); - - auto insertedValues = std::make_shared(); - insertedValues->entries.emplace_back( - north->fields[0].first, VmText{codec.encode("Lake")}); - insertedValues->entries.emplace_back(north->fields[1].first, 350.0); - const auto inserted = runtime.insertFact(type, insertedValues, std::nullopt); - assert(inserted && runtime.factStore()->sourceOf(inserted->id) == - std::optional{path.string()}); - rows = Form::Csv::toFacts(readFile(path), "School"); - assert(rows.size() == 3 && rows[2]["name"] == "Lake"); - - const std::array deleteTargets{west}; - assert(runtime.deleteFacts(deleteTargets) == 1.0); - rows = Form::Csv::toFacts(readFile(path), "School"); - assert(rows.size() == 2); - assert(rows[0]["name"] == "North"); - assert(rows[1]["name"] == "Lake"); - - const auto remaining = runtime.factStore()->snapshot(/*type=*/1); - assert(runtime.deleteFacts(remaining) == 2.0); - assert(readFile(path) == "name,students\n"); - assert(Form::Csv::toFacts(readFile(path), "School").empty()); - } - - // --------------------------------------------------------------------- - // Native .fx fact databases use the same ownership and transaction path - // as CSV. An explicit source establishes ownership for the first insert; - // later inserts infer the sole source for that fact type. - // --------------------------------------------------------------------- - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - IrModule module; - module.symbolTable = {codec.encode("School"), codec.encode("name"), - codec.encode("students")}; - runtime.installIrModule(module); - runtime.registerFactType(/*type=*/1, /*parents=*/{}); - - const auto path = outDir / "automatic_dml.fx"; - const auto type = codec.encode("School"); - auto northValues = std::make_shared(); - northValues->entries.emplace_back(2, VmText{codec.encode("North")}); - northValues->entries.emplace_back(3, 420.0); - const auto source = codec.encode(path.string()); - const auto north = runtime.insertFact(type, northValues, source); - assert(north && readFile(path).find("students: 420.0") != - std::string::npos); - - auto westValues = std::make_shared(); - westValues->entries.emplace_back(2, VmText{codec.encode("West")}); - westValues->entries.emplace_back(3, 280.0); - const auto west = runtime.insertFact(type, westValues, std::nullopt); - assert(west && runtime.factStore()->sourceOf(west->id) == - std::optional{path.string()}); - - auto update = std::make_shared(); - update->entries.emplace_back(3, 425.0); - (void)runtime.updateFacts(std::array{north}, update); - auto sourceText = readFile(path); - assert(sourceText.find("students: 425.0") != std::string::npos); - assert(sourceText.find("students: 280.0") != std::string::npos); - - assert(runtime.deleteFacts(std::array{west}) == 1.0); - sourceText = readFile(path); - assert(sourceText.find("West") == std::string::npos); - assert(sourceText.find("North") != std::string::npos); - } - - // --------------------------------------------------------------------- - // Runtime transaction rollback. A source with an unsupported extension - // is accepted as import ownership metadata, but persistence must fail at - // the database boundary. Insert/update/delete must then leave the retained - // facts and mutation journal exactly as they were before the operation. - // --------------------------------------------------------------------- - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - IrModule module; - module.symbolTable = {codec.encode("School"), codec.encode("name"), - codec.encode("students")}; - runtime.installIrModule(module); - runtime.registerFactType(/*type=*/1, /*parents=*/{}); - - const auto type = codec.encode("School"); - const auto invalidSource = codec.encode((outDir / "invalid.txt").string()); - const auto imported = std::get(runtime.importCsvFacts( - codec.encode("name,students\nNorth,420\n"), type, invalidSource)); - const auto north = std::get(imported->values.front()); - const auto journalBefore = runtime.factStore()->mutations(); - - auto update = std::make_shared(); - update->entries.emplace_back(3, 425.0); - assert(rejects([&] { - (void)runtime.updateFacts(std::array{north}, update); - })); - auto retained = runtime.factStore()->snapshot(/*type=*/1); - assert(retained.size() == 1); - assert(std::get(retained.front()->fields[1].second) == 420.0); - assert(runtime.factStore()->mutations().size() == journalBefore.size()); - - assert(rejects([&] { - (void)runtime.deleteFacts(std::array{retained.front()}); - })); - retained = runtime.factStore()->snapshot(/*type=*/1); - assert(retained.size() == 1 && retained.front()->id == north->id); - assert(runtime.factStore()->sourceOf(north->id).has_value()); - assert(runtime.factStore()->mutations().size() == journalBefore.size()); - } - - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - IrModule module; - module.symbolTable = {codec.encode("School"), codec.encode("name")}; - runtime.installIrModule(module); - runtime.registerFactType(/*type=*/1, /*parents=*/{}); - auto values = std::make_shared(); - values->entries.emplace_back(2, VmText{codec.encode("North")}); - const auto emptySource = codec.encode(""); - assert(rejects( - [&] { (void)runtime.insertFact(codec.encode("School"), values, - emptySource); })); - const auto invalidSource = codec.encode((outDir / "insert.txt").string()); - assert(rejects( - [&] { (void)runtime.insertFact(codec.encode("School"), values, - invalidSource); })); - assert(runtime.factStore()->snapshot(/*type=*/1).empty()); - assert(runtime.factStore()->mutations().empty()); - } - - // --------------------------------------------------------------------- - // Multi-source transactions are deterministic and source-local. A valid - // earlier source remains committed if a later source fails, while facts - // owned by the failing source are restored to their previous snapshots. - // --------------------------------------------------------------------- - { - FelidaeKnowledgeRuntime runtime(nullptr, 1024, 256, nullptr, nullptr, - codec.decode, codec.encode); - IrModule module; - module.symbolTable = {codec.encode("School"), codec.encode("name"), - codec.encode("students")}; - runtime.installIrModule(module); - runtime.registerFactType(/*type=*/1, /*parents=*/{}); - - const auto committedPath = outDir / "a-committed.csv"; - const auto failedPath = outDir / "z-failed.txt"; - const auto type = codec.encode("School"); - const auto committedRows = std::get(runtime.importCsvFacts( - codec.encode("name,students\nNorth,420\n"), type, - codec.encode(committedPath.string()))); - const auto failedRows = std::get(runtime.importCsvFacts( - codec.encode("name,students\nWest,280\n"), type, - codec.encode(failedPath.string()))); - const std::array targets{ - std::get(committedRows->values.front()), - std::get(failedRows->values.front())}; - auto update = std::make_shared(); - update->entries.emplace_back(3, 500.0); - std::string failure; - try { - (void)runtime.updateFacts(targets, update); - } catch (const IrError &error) { - failure = error.what(); - } - assert(!failure.empty()); - assert(failure.find(failedPath.string()) != std::string::npos); - assert(failure.find(committedPath.string()) != std::string::npos); - const auto committed = Form::Csv::toFacts(readFile(committedPath), - "School"); - assert(committed.size() == 1 && committed[0]["students"] == 500.0); - const auto retained = runtime.factStore()->snapshot(/*type=*/1); - assert(retained.size() == 2); - assert(std::get(retained[0]->fields[1].second) == 500.0); - assert(std::get(retained[1]->fields[1].second) == 280.0); - } - - // --------------------------------------------------------------------- - // Atomic sync: a failed sync (mixed/mismatched fact schema) must never - // touch the file already on disk, and must not leave a stray .tmp file - // behind. Calls Form::Db::sync directly with a deliberately invalid - // facts span to force the failure Form::Db::sync's own schema check - // raises, bypassing the ownership tracking that would normally prevent - // this from ever being assembled through normal owned-fact persistence. - // --------------------------------------------------------------------- - { - const auto path = outDir / "atomic.csv"; - std::vector> adaFields; - adaFields.push_back(field(2, VmText{codec.encode("Ada")})); - std::vector> boFields; - boFields.push_back(field(2, VmText{codec.encode("Bo")})); - std::vector validFacts; - validFacts.push_back(makeFact(1, std::move(adaFields))); - validFacts.push_back(makeFact(1, std::move(boFields))); - std::vector symbolTable; - symbolTable.push_back(codec.encode("Person")); - symbolTable.push_back(codec.encode("name")); - Form::Db::sync(path, validFacts, symbolTable, codec.decode); - assert(std::filesystem::exists(path)); - const auto before = readFile(path); - assert(!before.empty()); - - // A second fact with a different field count than the first violates - // "one stable CSV field order" -- Form::Db::sync must reject this - // before ever writing to the target path. - std::vector> cyFields; - cyFields.push_back(field(2, VmText{codec.encode("Cy")})); - std::vector> deeFields; - deeFields.push_back(field(2, VmText{codec.encode("Dee")})); - deeFields.push_back(field(3, VmText{codec.encode("extra")})); - std::vector mismatchedFacts; - mismatchedFacts.push_back(makeFact(1, std::move(cyFields))); - mismatchedFacts.push_back(makeFact(1, std::move(deeFields))); - std::vector mismatchedSymbolTable; - mismatchedSymbolTable.push_back(codec.encode("Person")); - mismatchedSymbolTable.push_back(codec.encode("name")); - mismatchedSymbolTable.push_back(codec.encode("extra")); - assert(rejects([&] { - Form::Db::sync(path, mismatchedFacts, mismatchedSymbolTable, codec.decode); - })); - - const auto after = readFile(path); - assert(before == after); - assert(!std::filesystem::exists( - std::filesystem::path(path.string() + ".tmp"))); - } - - std::filesystem::remove_all(outDir, ignored); - return 0; -} diff --git a/tests/FormIsolationTest.cpp b/tests/FormIsolationTest.cpp deleted file mode 100644 index b6f93e1..0000000 --- a/tests/FormIsolationTest.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "form/IrModule.h" -#include "form/RegisterVm.h" - -#include -#include - -int main() { - using namespace Felidae; - - constexpr IrSymbolRef kMain = 1; - IrModule module; - module.sentencePieceModelIdentity = "sha256:test"; - module.symbolTable = {{1}}; - module.entryProcedure = kMain; - module.ir.registerCount = 1; - module.ir.symbols = {kMain}; - module.ir.words = {static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End)}; - IrProcedure procedure; - procedure.ir.registerCount = 1; - procedure.ir.constants = {{IrConstantKind::Number, encodeIrNumber(42.0)}}; - procedure.ir.words = {static_cast(IrOpcode::LoadConst), 0, 0, - static_cast(IrOpcode::Return), 0, 0, - static_cast(IrOpcode::End)}; - module.procedures.emplace(kMain, std::move(procedure)); - auto verified = verifyIrModule(std::move(module)); - FelidaeKnowledgeRuntime runtime; - RegisterVm vm; - assert(std::get(vm.executeMain(verified, runtime)) == 42.0); -} diff --git a/tests/LibTorchSmoke.cpp b/tests/LibTorchSmoke.cpp deleted file mode 100644 index 218a397..0000000 --- a/tests/LibTorchSmoke.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include "form/IrModule.h" -#include "form/LibTorchTensorRuntime.h" -#include "form/TensorOperation.h" - -#include - -#include -#include -#include -#include -#include - -struct RegisteredNetwork final : torch::nn::Module { - RegisteredNetwork() { - embedding = register_module("embedding", torch::nn::Embedding(8, 4)); - encoder = register_module( - "encoder", torch::nn::GRU(torch::nn::GRUOptions(4, 4).num_layers(1))); - } - torch::nn::Embedding embedding{nullptr}; - torch::nn::GRU encoder{nullptr}; -}; - -namespace { - -Felidae::VmValue array(std::initializer_list values) { - auto result = std::make_shared(); - result->values.assign(values); - return result; -} - -double number(const Felidae::VmValue &value) { return std::get(value); } - -const Felidae::VmArray &values(const Felidae::VmValue &value) { - return **std::get_if(&value); -} - -Felidae::VmValue materialized(const Felidae::LibTorchTensorRuntime &runtime, - const Felidae::VmValue &value) { - if (const auto tensor = std::get_if(&value)) - return runtime.materializeTensor(**tensor); - return value; -} - -bool rejects(const std::function &action) { - try { - action(); - return false; - } catch (const Felidae::IrError &) { - return true; - } -} - -} // namespace - -int main() { - const auto value = - torch::ones({1}, torch::TensorOptions().dtype(torch::kFloat)); - if (value.item() != 1.0f) - return 1; - auto embedding = torch::nn::Embedding(torch::nn::EmbeddingOptions(8, 4)); - auto gru = torch::nn::GRU(torch::nn::GRUOptions(4, 4).num_layers(1)); - const auto ids = torch::tensor(std::vector{1}, - torch::TensorOptions().dtype(torch::kInt64)) - .reshape({1, 1}); - const auto output = gru->forward(embedding->forward(ids)); - if (std::get<0>(output).numel() != 4) - return 1; - auto network = std::make_shared(); - network->eval(); - const auto registeredOutput = - network->encoder->forward(network->embedding->forward(ids)); - if (std::get<0>(registeredOutput).numel() != 4) - return 1; - - Felidae::LibTorchTensorRuntime tensors; - const std::vector noSymbols; - const auto vectorA = array({1.0, 2.0, 3.0}); - const auto vectorB = array({4.0, 5.0, 6.0}); - assert(number(tensors.evaluateTensor(Felidae::TensorOperation::Dot, - std::array{vectorA, vectorB}, - noSymbols)) == 32.0); - assert(number(tensors.evaluateTensor(Felidae::TensorOperation::Size, - std::array{vectorA}, noSymbols)) == 3.0); - const auto matrix = array({array({1.0, 2.0}), array({2.0, 1.0})}); - const auto shape = tensors.evaluateTensor(Felidae::TensorOperation::Shape, - std::array{matrix}, noSymbols); - assert(values(shape).values.size() == 2); - assert(number(values(shape).values[0]) == 2.0); - assert(number(values(shape).values[1]) == 2.0); - assert(number(tensors.evaluateTensor(Felidae::TensorOperation::Dimensions, - std::array{matrix}, noSymbols)) == 2.0); - assert(number(tensors.evaluateTensor(Felidae::TensorOperation::IsSymmetric, - std::array{matrix}, noSymbols)) == 1.0); - const auto asymmetric = array({array({1.0, 2.0}), array({3.0, 4.0})}); - assert(number(tensors.evaluateTensor(Felidae::TensorOperation::IsSymmetric, - std::array{asymmetric}, noSymbols)) == - 0.0); - const auto transpose = tensors.evaluateTensor( - Felidae::TensorOperation::Transpose, std::array{asymmetric}, noSymbols); - assert(std::holds_alternative(transpose)); - const auto transposeValues = materialized(tensors, transpose); - assert(number(values(values(transposeValues).values[0]).values[1]) == 3.0); - const auto copy = tensors.evaluateTensor(Felidae::TensorOperation::Clone, - std::array{matrix}, noSymbols); - assert(std::holds_alternative(copy)); - const auto copyAgain = tensors.evaluateTensor(Felidae::TensorOperation::Clone, - std::array{copy}, noSymbols); - assert(std::get(copyAgain)->storage != - std::get(copy)->storage); - const auto copyValues = materialized(tensors, copy); - assert(number(values(values(copyValues).values[1]).values[0]) == 2.0); - const auto difference = tensors.evaluateTensor( - Felidae::TensorOperation::Difference, - std::array{array({1.0, 4.0}), array({3.0, 1.0})}, noSymbols); - const auto differenceValues = materialized(tensors, difference); - assert(number(values(differenceValues).values[0]) == 2.0); - assert(number(values(differenceValues).values[1]) == 3.0); - assert(number(tensors.evaluateTensor( - Felidae::TensorOperation::MeanSquaredError, - std::array{array({1.0, 2.0}), array({1.0, 4.0})}, noSymbols)) == - 2.0); - const auto cosine = number(tensors.evaluateTensor( - Felidae::TensorOperation::CosineSimilarity, - std::array{array({1.0, 0.0}), array({1.0, 1.0})}, noSymbols)); - assert(std::abs(cosine - std::sqrt(0.5)) < 1e-12); - const auto sigmoid = tensors.evaluateTensor( - Felidae::TensorOperation::Sigmoid, std::array{array({0.0})}, noSymbols); - assert(number(values(materialized(tensors, sigmoid)).values[0]) == 0.5); - const auto relu = - tensors.evaluateTensor(Felidae::TensorOperation::Relu, - std::array{array({-2.0, 3.0})}, noSymbols); - const auto reluValues = materialized(tensors, relu); - assert(number(values(reluValues).values[0]) == 0.0); - assert(number(values(reluValues).values[1]) == 3.0); - assert(rejects([&] { - const auto zero = array({0.0, 0.0}); - (void)tensors.evaluateTensor(Felidae::TensorOperation::CosineSimilarity, - std::array{zero, zero}, noSymbols); - })); - assert(rejects([&] { - (void)tensors.evaluateTensor(Felidae::TensorOperation::Transpose, - std::array{vectorA}, noSymbols); - })); - assert(rejects([&] { - const auto infinity = array({std::numeric_limits::infinity()}); - (void)tensors.evaluateTensor(Felidae::TensorOperation::Clone, - std::array{infinity}, noSymbols); - })); - assert(rejects([&] { - const auto largest = std::numeric_limits::max(); - (void)tensors.evaluateTensor( - Felidae::TensorOperation::MeanSquaredError, - std::array{array({largest}), array({-largest})}, noSymbols); - })); - assert(rejects([&] { - const auto ragged = array({array({1.0}), array({2.0, 3.0})}); - (void)tensors.evaluateTensor(Felidae::TensorOperation::Shape, - std::array{ragged}, noSymbols); - })); - - auto fact = std::make_shared(); - fact->type = 1; - fact->fields.emplace_back(2, Felidae::VmText{{31, 32}}); - fact->fields.emplace_back(3, 2.5); - const Felidae::VmValue factValue = fact; - assert(rejects([&] { - (void)tensors.evaluateTensor(Felidae::TensorOperation::Size, - std::array{factValue}, noSymbols); - })); - return 0; -} diff --git a/tests/MixfixStateModelTest.cpp b/tests/MixfixStateModelTest.cpp deleted file mode 100644 index 50ca090..0000000 --- a/tests/MixfixStateModelTest.cpp +++ /dev/null @@ -1,1098 +0,0 @@ -#include "MixfixStateModel.h" -#include "CompilerFrontend.h" -#include "SentencePieceModel.h" -#include "form/BinaryIr.h" -#include "form/RuntimeStateModel.h" -#include "form/RuntimeTraining.h" -#include "form/SemanticOperation.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace { - -template bool rejects(Action &&action) { - try { - std::forward(action)(); - } catch (const Felidae::IrError &) { - return true; - } - return false; -} - -template std::string rejectionMessage(Action &&action) { - try { - std::forward(action)(); - } catch (const Felidae::IrError &error) { - return error.what(); - } - return {}; -} - -void writeMixfixManifest( - const std::filesystem::path &directory, - const Felidae::GruMixfixStateModel::Configuration &configuration, - std::string_view sentencePieceIdentity, - std::string_view modelVersion = Felidae::kMixfixModelVersion) { - std::ofstream manifest(directory / "manifest.txt", std::ios::trunc); - assert(manifest); - manifest << "artifact_format_version=" - << Felidae::kMixfixArtifactFormatVersion - << "\nmodel_family=" << Felidae::kMixfixModelFamily - << "\nmodel_version=" << modelVersion - << "\nbackend=torchscript-gru\ntokenizer_contract=" - << Felidae::kMixfixTokenizerContract - << "\nsentencepiece_model_identity=" << sentencePieceIdentity - << "\nir_vocabulary_version=" << Felidae::kMixfixIrVocabularyVersion - << "\ndecoder_contract=" << Felidae::kMixfixDecoderContract - << "\ninput_vocabulary=" << configuration.inputVocabularySize - << "\noutput_vocabulary=" << configuration.outputVocabularySize - << "\nbegin_token=" << configuration.beginToken - << "\nembedding_size=" << configuration.embeddingSize - << "\nhidden_size=" << configuration.hiddenSize - << "\nlayer_count=" << configuration.layerCount << '\n'; -} - -Felidae::VmValue -executeDirect(const Felidae::FelidaeIr &program, Felidae::VmRuntime &runtime, - std::unordered_map - procedures = {}) { - constexpr Felidae::IrSymbolRef kTestEntry = 1; - if (procedures.contains(kTestEntry)) - throw Felidae::IrError("test procedure ID collision"); - Felidae::IrModule module; - module.entryProcedure = kTestEntry; - module.ir.registerCount = 1; - module.ir.symbols = {kTestEntry}; - module.ir.words = { - static_cast(Felidae::IrOpcode::Call), - 0, - 0, - 0, - static_cast(Felidae::IrOpcode::Return), - 0, - 0, - static_cast(Felidae::IrOpcode::End), - }; - module.procedures = std::move(procedures); - module.procedures.emplace(kTestEntry, - Felidae::IrProcedure{program, {}, {}, {}}); - Felidae::IrSymbolRef largestSymbol = kTestEntry; - const auto includeSymbols = [&](const Felidae::IrProcedure &procedure) { - for (const auto symbol : procedure.ir.symbols) - largestSymbol = std::max(largestSymbol, symbol); - for (const auto symbol : procedure.positionalParameters) - largestSymbol = std::max(largestSymbol, symbol); - for (const auto symbol : procedure.namedParameters) - largestSymbol = std::max(largestSymbol, symbol); - }; - for (const auto symbol : module.ir.symbols) - largestSymbol = std::max(largestSymbol, symbol); - for (const auto &[symbol, procedure] : module.procedures) { - largestSymbol = std::max(largestSymbol, symbol); - includeSymbols(procedure); - } - module.sentencePieceModelIdentity = "sha256:test"; - module.symbolTable.reserve(largestSymbol); - for (Felidae::IrSymbolRef symbol = 1; symbol <= largestSymbol; ++symbol) { - module.symbolTable.push_back({symbol}); - } - return Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(std::move(module)), runtime); -} - -bool rejectsBranchValue(Felidae::VmRuntime &runtime, - const Felidae::VmValue &value) { - try { - (void)runtime.shouldBranchFalse(value); - } catch (const Felidae::IrError &) { - return true; - } - return false; -} - -} // namespace - -int main() { - using namespace Felidae; - - class FixedModel final : public MixfixStateModel { - public: - std::vector transform(std::span, - const MixfixContext &) override { - return {0, 1, 2, 3, 4}; - } - }; - class InvalidModel final : public MixfixStateModel { - public: - std::vector transform(std::span, - const MixfixContext &) override { - return {0, 5, 2, 3, 4}; - } - }; - class OversizedModel final : public MixfixStateModel { - public: - std::vector transform(std::span, - const MixfixContext &) override { - return {0, 1, 2, 3, 4}; - } - }; - class UnknownVocabularyModel final : public MixfixStateModel { - public: - std::vector transform(std::span, - const MixfixContext &) override { - return {999}; - } - }; - - MixfixContext context; - context.constantReferences = {0}; - context.outputVocabulary = { - {MixfixIrTokenKind::Accept, 0}, - {MixfixIrTokenKind::Opcode, static_cast(IrOpcode::LoadConst)}, - {MixfixIrTokenKind::Register, 0}, - {MixfixIrTokenKind::ConstantReference, 0}, - {MixfixIrTokenKind::End, 0}, - }; - const std::vector valid = { - {MixfixIrTokenKind::Accept, 0}, - {MixfixIrTokenKind::Opcode, static_cast(IrOpcode::LoadConst)}, - {MixfixIrTokenKind::Register, 0}, - {MixfixIrTokenKind::ConstantReference, 0}, - {MixfixIrTokenKind::End, 0}, - }; - const auto words = resolveMixfixIrTokens(valid, context); - assert( - (words == std::vector{static_cast(IrOpcode::LoadConst), 0, - 0, static_cast(IrOpcode::End)})); - const auto rejectedMessage = rejectionMessage([&] { - const std::array decision{ - {{MixfixIrTokenKind::Reject, 0}}}; - (void)resolveMixfixIrTokens(decision, context); - }); - assert(rejectedMessage.find("constants=1") != std::string::npos); - assert(rejectedMessage.find("learned valid mixfix form") != - std::string::npos); - const auto abstainedMessage = rejectionMessage([&] { - const std::array decision{ - {{MixfixIrTokenKind::Abstain, 0}}}; - (void)resolveMixfixIrTokens(decision, context); - }); - assert(abstainedMessage.find("constants=1") != std::string::npos); - assert(abstainedMessage.find("deterministic overload") != std::string::npos); - - FelidaeIr ir; - ir.words = words; - ir.constants = {{IrConstantKind::Number, encodeIrNumber(1.0)}}; - ir.registerCount = 1; - IrVerifier::verify(ir); - - FixedModel model; - const std::vector input = {1}; - const auto verified = compileVerifiedMixfixIr(model, input, context, ir); - assert(verified.words == words); - - InvalidModel invalidModel; - bool verifierRejected = false; - try { - (void)compileVerifiedMixfixIr(invalidModel, input, context, ir); - } catch (const IrError &) { - verifierRejected = true; - } - assert(verifierRejected); - - MixfixContext tightContext = context; - tightContext.maximumOutputWords = 1; - OversizedModel oversizedModel; - bool oversizedRejected = false; - try { - (void)compileVerifiedMixfixIr(oversizedModel, input, tightContext, ir); - } catch (const IrError &) { - oversizedRejected = true; - } - assert(oversizedRejected); - UnknownVocabularyModel unknownVocabularyModel; - bool vocabularyRejected = false; - try { - (void)compileVerifiedMixfixIr(unknownVocabularyModel, input, context, ir); - } catch (const IrError &) { - vocabularyRejected = true; - } - assert(vocabularyRejected); - -#ifdef FELIDAE_HAS_TORCH - // Capture the parser-bounded input and a verifier-safe structured teacher - // from one genuinely unresolved source expression. The trained GRU must - // later reproduce this sequence itself; the teacher is not used during - // the production compilation below. - class CapturingCompilerTeacher final : public MixfixStateModel { - public: - std::vector boundedInput; - std::vector target; - - std::vector - transform(std::span inputIds, - const MixfixContext &compilerContext) override { - boundedInput.assign(inputIds.begin(), inputIds.end()); - const auto token = [&](MixfixIrTokenKind kind, IrWord value = 0) { - const auto found = std::find_if( - compilerContext.outputVocabulary.begin(), - compilerContext.outputVocabulary.end(), - [&](const MixfixIrToken &candidate) { - return candidate.kind == kind && candidate.value == value; - }); - if (found == compilerContext.outputVocabulary.end()) { - throw IrError( - "compiler E2E teacher token is outside the bounded vocabulary"); - } - return static_cast( - found - compilerContext.outputVocabulary.begin()); - }; - target = { - token(MixfixIrTokenKind::Accept), - token(MixfixIrTokenKind::Opcode, - static_cast(IrOpcode::LoadSymbol)), - token(MixfixIrTokenKind::Register, 1), - token(MixfixIrTokenKind::SymbolReference, 0), - token(MixfixIrTokenKind::Opcode, static_cast(IrOpcode::Call)), - token(MixfixIrTokenKind::Register, 0), - token(MixfixIrTokenKind::SymbolReference, 1), - token(MixfixIrTokenKind::Register, 1), - token(MixfixIrTokenKind::Register, 1), - token(MixfixIrTokenKind::Opcode, - static_cast(IrOpcode::Return)), - token(MixfixIrTokenKind::Register, 0), - token(MixfixIrTokenKind::Register, 0), - token(MixfixIrTokenKind::End), - }; - return target; - } - } compilerTeacher; - const std::string compilerE2eSource = - "@overload(\n" - " operator: pickValue,\n" - " pattern: \"pick {value}\",\n" - " type: prefix,\n" - " captures: {value: number},\n" - " result: number,\n" - " precedence: prefix,\n" - " associativity: right,\n" - " cardinality: one,\n" - " effects: pure,\n" - " visibility: private\n" - ")\n" - "pickNumber() => return value\n" - "@overload(\n" - " operator: pickValue,\n" - " pattern: \"pick {value}\",\n" - " type: prefix,\n" - " captures: {value: string},\n" - " result: number,\n" - " precedence: prefix,\n" - " associativity: right,\n" - " cardinality: one,\n" - " effects: pure,\n" - " visibility: private\n" - ")\n" - "pickString() => return 0\n" - "route(value: any) => return pick value\n" - "main() => return route(value: 42)\n"; - CompilerOptions teacherOptions; - teacherOptions.mixfixModel = &compilerTeacher; - (void)compileProgramTextToIr(compilerE2eSource, teacherOptions); - assert(!compilerTeacher.boundedInput.empty() && - !compilerTeacher.target.empty()); - - GruMixfixStateModel::Configuration trainedCompilerConfiguration; - trainedCompilerConfiguration.inputVocabularySize = - felidaeSentencePieceModel().GetPieceSize(); - trainedCompilerConfiguration.outputVocabularySize = - static_cast(kMixfixStructuralVocabularySize); - trainedCompilerConfiguration.embeddingSize = 16; - trainedCompilerConfiguration.hiddenSize = 24; - trainedCompilerConfiguration.layerCount = 1; - trainedCompilerConfiguration.beginToken = 0; - trainedCompilerConfiguration.maximumDecodeSteps = - compilerTeacher.target.size() + 2; - trainedCompilerConfiguration.allowRandomInitialization = true; - GruMixfixStateModel trainedCompiler(trainedCompilerConfiguration); - std::vector compilerTarget(compilerTeacher.target.begin(), - compilerTeacher.target.end()); - bool compilerSequenceLearned = false; - for (std::size_t step = 0; step < 512 && !compilerSequenceLearned; ++step) { - (void)trainedCompiler.trainTeacherForced(compilerTeacher.boundedInput, - compilerTarget, 0.02); - try { - const auto decoded = trainedCompiler.transform( - compilerTeacher.boundedInput, makeMixfixContext(FelidaeIr{})); - compilerSequenceLearned = decoded == compilerTeacher.target; - } catch (const IrError &) { - // Early autoregressive outputs are expected to be structurally - // invalid until this one bounded teacher sequence is learned. - } - } - assert(compilerSequenceLearned); - const auto trainedCompilerDirectory = - std::filesystem::path(FELIDAE_MODEL_TEST_OUTPUT_DIR) / - "compiler-ssm-e2e"; - std::filesystem::create_directories(trainedCompilerDirectory); - const auto trainedCompilerArtifact = - trainedCompilerDirectory / "mixfix-gru.pt"; - trainedCompiler.exportTorchScript(trainedCompilerArtifact); - writeMixfixManifest(trainedCompilerDirectory, trainedCompilerConfiguration, - felidaeSentencePieceModelIdentity()); - auto reloadedCompiler = GruMixfixStateModel::loadVersioned( - trainedCompilerConfiguration, trainedCompilerDirectory, - felidaeSentencePieceModelIdentity()); - CompilerOptions productionCompilerOptions; - productionCompilerOptions.mixfixModel = &reloadedCompiler; - const auto trainedCompilerIr = - compileProgramTextToIr(compilerE2eSource, productionCompilerOptions); - const auto trainedCompilerBinary = - std::filesystem::path(FELIDAE_MODEL_TEST_OUTPUT_DIR) / - "compiler-ssm-e2e.bin"; - writeBinaryIr(trainedCompilerBinary, - verifyIrModule(IrModule(trainedCompilerIr))); - const auto loadedCompilerBinary = - loadBinaryIr(trainedCompilerBinary, felidaeSentencePieceModelIdentity()); - FelidaeKnowledgeRuntime compilerE2eRuntime; - const auto compilerE2eResult = - RegisterVm{}.executeMain(loadedCompilerBinary, compilerE2eRuntime); - assert(std::holds_alternative(compilerE2eResult)); - assert(std::get(compilerE2eResult) == 42.0); - - // A one-entry finite vocabulary makes autoregressive GRU decoding - // deterministic while still exercising the actual LibTorch encoder, - // recurrent state transfer, decoder, and projection path. - GruMixfixStateModel::Configuration gruConfiguration; - gruConfiguration.inputVocabularySize = 8; - gruConfiguration.outputVocabularySize = 1; - gruConfiguration.embeddingSize = 4; - gruConfiguration.hiddenSize = 4; - gruConfiguration.layerCount = 1; - gruConfiguration.beginToken = 0; - gruConfiguration.maximumDecodeSteps = 2; - gruConfiguration.allowRandomInitialization = true; - GruMixfixStateModel gruModel(gruConfiguration); - MixfixContext gruContext; - gruContext.maximumOutputWords = 2; - gruContext.outputVocabulary = {{MixfixIrTokenKind::Reject, 0}}; - const auto gruTokens = gruModel.transform(input, gruContext); - assert((gruTokens == std::vector{0})); - MixfixContext boundedGruContext; - boundedGruContext.maximumOutputWords = 2; - boundedGruContext.outputVocabulary = {{MixfixIrTokenKind::Opcode, 1}}; - assert(gruModel.transform(input, boundedGruContext).size() == 2); - - // The VM recurrent backend has one shared finite output vocabulary for - // both model loading and C++ training. It retains bounded references to - // every supported input position rather than silently limiting models to - // argument zero. - const auto runtimeVocabulary = defaultRuntimeOutputVocabulary(); - assert(runtimeVocabulary.size() == 3 + 2 * kRuntimeModelReferenceLimit + 5); - assert(runtimeVocabulary[3].kind == RuntimeOutputTokenKind::InputReference && - runtimeVocabulary[3].value == 0); - assert(runtimeVocabulary[3 + kRuntimeModelReferenceLimit - 1].kind == - RuntimeOutputTokenKind::InputReference && - runtimeVocabulary[3 + kRuntimeModelReferenceLimit - 1].value == - kRuntimeModelReferenceLimit - 1); - assert(runtimeVocabulary[3 + kRuntimeModelReferenceLimit].kind == - RuntimeOutputTokenKind::FactFromInput && - runtimeVocabulary[3 + kRuntimeModelReferenceLimit].value == 0); - - // The VM recurrent backend has its own finite output vocabulary. A - // reference token returns the original typed Value, so state-model use - // never invents boolean truthiness or loses fact/text/container payloads. - GruRuntimeStateModel::Configuration runtimeGruConfiguration; - runtimeGruConfiguration.inputVocabularySize = - felidaeSentencePieceModel().GetPieceSize() + - kRuntimeStructuralInputTokens; - runtimeGruConfiguration.outputVocabularySize = 1; - runtimeGruConfiguration.embeddingSize = 4; - runtimeGruConfiguration.hiddenSize = 4; - runtimeGruConfiguration.layerCount = 1; - runtimeGruConfiguration.allowRandomInitialization = true; - GruRuntimeStateModel runtimeGru( - runtimeGruConfiguration, {{RuntimeOutputTokenKind::InputReference, 0}}); - RuntimeContext runtimeGruContext; - runtimeGruContext.executionState = runtimeGru.createExecutionState(); - const std::vector runtimeSymbols{{42}}; - runtimeGruContext.symbolTable = &runtimeSymbols; - const VmValue runtimeText = VmText{{101, 102, 103}}; - assert(std::get( - runtimeGru.evaluate(RuntimeOperation{static_cast( - SemanticOperationId::Identity)}, - {&runtimeText, 1}, runtimeGruContext)) - .pieces == PieceSequence({101, 102, 103})); - auto runtimeFact = std::make_shared(); - runtimeFact->type = 1; - const VmValue runtimeFactValue = runtimeFact; - assert(std::get( - runtimeGru.evaluate(RuntimeOperation{static_cast( - SemanticOperationId::SelectFact)}, - {&runtimeFactValue, 1}, runtimeGruContext)) - ->type == 1); - GruRuntimeStateModel softRuntimeGru( - runtimeGruConfiguration, {{RuntimeOutputTokenKind::DegreeMilli, 725}}); - RuntimeContext softRuntimeContext; - softRuntimeContext.executionState = softRuntimeGru.createExecutionState(); - const VmValue degreeInput = 0.5; - const auto softResult = - softRuntimeGru.evaluate(RuntimeOperation{static_cast( - SemanticOperationId::EvaluateDegree)}, - {°reeInput, 1}, softRuntimeContext); - assert(std::get(softResult).value == 0.725); - RuntimeContext suggestContext; - suggestContext.executionState = runtimeGru.createExecutionState(); - suggestContext.symbolTable = &runtimeSymbols; - const auto suggested = runtimeGru.evaluate( - RuntimeOperation{static_cast( - SemanticOperationId::Suggest)}, - {&runtimeFactValue, 1}, suggestContext); - assert(std::holds_alternative(suggested)); - assert(std::isfinite(std::get(suggested))); - - // Production artifacts are genuine TorchScript modules. Native training - // checkpoints remain separate and must not load through the inference - // constructor. - const auto artifactRoot = - std::filesystem::path(FELIDAE_MODEL_TEST_OUTPUT_DIR) / - "artifact-contract"; - std::filesystem::create_directories(artifactRoot); - const auto mixfixArtifact = artifactRoot / "mixfix-gru.pt"; - const auto mixfixCheckpoint = artifactRoot / "mixfix-gru.ckpt"; - gruModel.saveCheckpoint(mixfixCheckpoint); - gruModel.exportTorchScript(mixfixArtifact); - writeMixfixManifest(artifactRoot, gruConfiguration, - felidaeSentencePieceModelIdentity()); - auto loadedMixfix = GruMixfixStateModel::loadVersioned( - gruConfiguration, artifactRoot, felidaeSentencePieceModelIdentity()); - assert((loadedMixfix.transform(input, gruContext) == - std::vector{0})); - assert(loadedMixfix.transform(input, boundedGruContext).size() == 2); - writeMixfixManifest(artifactRoot, gruConfiguration, - felidaeSentencePieceModelIdentity(), - "incompatible-version"); - assert(rejects([&] { - (void)GruMixfixStateModel::loadVersioned( - gruConfiguration, artifactRoot, felidaeSentencePieceModelIdentity()); - })); - writeMixfixManifest(artifactRoot, gruConfiguration, - felidaeSentencePieceModelIdentity()); - bool productionCheckpointRejected = false; - try { - loadedMixfix.saveCheckpoint(artifactRoot / "production.ckpt"); - } catch (const IrError &) { - productionCheckpointRejected = true; - } - assert(productionCheckpointRejected); - std::filesystem::copy_file(mixfixCheckpoint, mixfixArtifact, - std::filesystem::copy_options::overwrite_existing); - assert(rejects([&] { - (void)GruMixfixStateModel::loadVersioned( - gruConfiguration, artifactRoot, felidaeSentencePieceModelIdentity()); - })); - gruModel.exportTorchScript(mixfixArtifact); - - const auto runtimeArtifact = artifactRoot / "runtime-gru.pt"; - const auto runtimeCheckpoint = artifactRoot / "runtime-gru.ckpt"; - runtimeGru.saveCheckpoint(runtimeCheckpoint); - runtimeGru.exportTorchScript(runtimeArtifact, - felidaeSentencePieceModelIdentity()); - auto loadedRuntime = GruRuntimeStateModel::loadVersioned( - runtimeGruConfiguration, {{RuntimeOutputTokenKind::InputReference, 0}}, - artifactRoot, felidaeSentencePieceModelIdentity()); - RuntimeContext loadedRuntimeContext; - loadedRuntimeContext.executionState = loadedRuntime.createExecutionState(); - assert(std::get( - loadedRuntime.evaluate(RuntimeOperation{static_cast( - SemanticOperationId::Identity)}, - {&runtimeText, 1}, loadedRuntimeContext)) - .pieces == PieceSequence({101, 102, 103})); - std::filesystem::copy_file(runtimeCheckpoint, runtimeArtifact, - std::filesystem::copy_options::overwrite_existing); - assert(rejects([&] { - (void)GruRuntimeStateModel::loadVersioned( - runtimeGruConfiguration, - {{RuntimeOutputTokenKind::InputReference, 0}}, artifactRoot, - felidaeSentencePieceModelIdentity()); - })); - std::filesystem::remove_all(artifactRoot); - - // Real compiler-produced SemanticEval -> verified FELBIR -> trained C++ - // runtime GRU -> TorchScript export/reload -> direct register VM. This - // uses the full production output vocabulary and requires the optimizer - // to learn InputReference(0); it is not a one-class random-model shortcut. - const auto trainedRuntimeVocabulary = defaultRuntimeOutputVocabulary(); - const auto trainedTarget = static_cast( - std::find_if( - trainedRuntimeVocabulary.begin(), trainedRuntimeVocabulary.end(), - [](const RuntimeOutputToken &token) { - return token.kind == RuntimeOutputTokenKind::InputReference && - token.value == 0; - }) - - trainedRuntimeVocabulary.begin()); - assert(trainedTarget < trainedRuntimeVocabulary.size()); - GruRuntimeStateModel::Configuration trainedRuntimeConfiguration; - trainedRuntimeConfiguration.inputVocabularySize = - felidaeSentencePieceModel().GetPieceSize() + - kRuntimeStructuralInputTokens; - trainedRuntimeConfiguration.outputVocabularySize = - static_cast(trainedRuntimeVocabulary.size()); - trainedRuntimeConfiguration.embeddingSize = 8; - trainedRuntimeConfiguration.hiddenSize = 8; - trainedRuntimeConfiguration.layerCount = 1; - trainedRuntimeConfiguration.allowRandomInitialization = true; - GruRuntimeStateModel trainedRuntime(trainedRuntimeConfiguration, - trainedRuntimeVocabulary); - RuntimeTrainingRecord identityTeacher; - identityTeacher.operationId = - static_cast(SemanticOperationId::Identity); - identityTeacher.inputKinds = {RuntimeValueKind::Number}; - identityTeacher.inputValues = {runtimeValueEncoding(VmValue{42.0}, {})}; - identityTeacher.targetKind = RuntimeTrainingTargetKind::InputReference; - identityTeacher.targetValue = 0; - verifyRuntimeTrainingRecord(identityTeacher); - auto serializedTeacher = identityTeacher; - serializedTeacher.factTypes = {{10, 11}}; - serializedTeacher.factTypeCounts = {{{10, 11}, 2}}; - serializedTeacher.hierarchyEdges = {{{10, 11}, {12}}}; - RuntimeTrainingRecord scoreTeacher; - scoreTeacher.operationId = - static_cast(SemanticOperationId::Suggest); - scoreTeacher.inputKinds = {RuntimeValueKind::Number}; - scoreTeacher.inputValues = {runtimeValueEncoding(VmValue{3.432}, {})}; - assert(scoreTeacher.inputValues.front() != - runtimeValueEncoding(VmValue{-2.302}, {})); - scoreTeacher.targetKind = RuntimeTrainingTargetKind::Score; - scoreTeacher.targetScore = -212.421; - verifyRuntimeTrainingRecord(scoreTeacher); - const auto runtimeDataset = - std::filesystem::path(FELIDAE_MODEL_TEST_OUTPUT_DIR) / - "runtime-sequence-roundtrip.jsonl"; - const std::array runtimeTeachers{ - serializedTeacher, scoreTeacher}; - writeRuntimeTrainingDataset(runtimeDataset, runtimeTeachers); - const auto loadedTeachers = loadRuntimeTrainingDataset(runtimeDataset); - assert(loadedTeachers.size() == 2); - assert(loadedTeachers.front().factTypes == serializedTeacher.factTypes); - assert(loadedTeachers.front().factTypeCounts == - serializedTeacher.factTypeCounts); - assert(loadedTeachers.front().hierarchyEdges == - serializedTeacher.hierarchyEdges); - assert(loadedTeachers[1].targetKind == RuntimeTrainingTargetKind::Score); - assert(loadedTeachers[1].targetScore == -212.421); - std::filesystem::remove(runtimeDataset); - auto invalidTeacher = identityTeacher; - invalidTeacher.operationId = 0xffffu; - bool invalidTeacherRejected = false; - try { - verifyRuntimeTrainingRecord(invalidTeacher); - } catch (const IrError &) { - invalidTeacherRejected = true; - } - assert(invalidTeacherRejected); - invalidTeacher = identityTeacher; - invalidTeacher.inputKinds.clear(); - bool invalidTeacherArityRejected = false; - try { - verifyRuntimeTrainingRecord(invalidTeacher); - } catch (const IrError &) { - invalidTeacherArityRejected = true; - } - assert(invalidTeacherArityRejected); - (void)trainedRuntime.trainTeacherForced(identityTeacher, trainedTarget, 0.01); - for (std::size_t step = 1; - step < 128 && - trainedRuntime.predictTeacherToken(identityTeacher) != trainedTarget; - ++step) { - (void)trainedRuntime.trainTeacherForced(identityTeacher, trainedTarget, - 0.01); - } - assert(trainedRuntime.predictTeacherToken(identityTeacher) == trainedTarget); - const auto trainedArtifactDirectory = - std::filesystem::path(FELIDAE_MODEL_TEST_OUTPUT_DIR) / "runtime-ssm-e2e"; - std::filesystem::create_directories(trainedArtifactDirectory); - const auto trainedArtifact = trainedArtifactDirectory / "runtime-gru.pt"; - trainedRuntime.exportTorchScript(trainedArtifact, - felidaeSentencePieceModelIdentity()); - auto reloadedTrainedRuntime = GruRuntimeStateModel::loadVersioned( - trainedRuntimeConfiguration, trainedRuntimeVocabulary, - trainedArtifactDirectory, felidaeSentencePieceModelIdentity()); - const auto trainedRuntimeModule = loadBinaryIr( - FELIDAE_RUNTIME_SSM_E2E_BINARY, felidaeSentencePieceModelIdentity()); - assert(containsRuntimeSemanticOperation(trainedRuntimeModule)); - FelidaeKnowledgeRuntime trainedKnowledgeRuntime(&reloadedTrainedRuntime); - const auto trainedResult = - RegisterVm{}.executeMain(trainedRuntimeModule, trainedKnowledgeRuntime); - assert(std::holds_alternative(trainedResult)); - assert(std::get(trainedResult) == 42.0); -#endif - - FelidaeIr arithmetic; - arithmetic.registerCount = 3; - arithmetic.constants = {{IrConstantKind::Number, encodeIrNumber(6.0)}, - {IrConstantKind::Number, encodeIrNumber(7.0)}}; - arithmetic.words = { - static_cast(IrOpcode::LoadConst), - 0, - 0, - static_cast(IrOpcode::LoadConst), - 1, - 1, - static_cast(IrOpcode::Mul), - 2, - 0, - 1, - static_cast(IrOpcode::Return), - 2, - 0, - static_cast(IrOpcode::End), - }; - class NoRuntime : public VmRuntime { - public: - void installIrModule(const IrModule &) override {} - IrSymbolRef resolveSymbol(IrSymbolRef symbol) const override { - return symbol; - } - VmFactPtr retainFact(const VmFactPtr &fact) override { return fact; } - VmFactPtr mutateFact(const VmFactPtr &fact, IrSymbolRef field, - const VmValue &value) override { - if (!fact) - throw IrError("test mutation requires a fact"); - auto updated = std::make_shared(*fact); - const auto found = - std::find_if(updated->fields.begin(), updated->fields.end(), - [&](const auto &entry) { return entry.first == field; }); - if (found == updated->fields.end()) - updated->fields.emplace_back(field, value); - else - found->second = value; - return updated; - } - } noRuntime; - const auto arithmeticResult = executeDirect(arithmetic, noRuntime); - assert(std::get(arithmeticResult) == 42.0); - // The branch protocol is deliberately narrower than host-language - // truthiness. Every non-boolean VM type remains usable data and must not - // become an implicit control decision. - assert(noRuntime.shouldBranchFalse(VmNil{})); - assert(noRuntime.shouldBranchFalse(0.0)); - assert(!noRuntime.shouldBranchFalse(1.0)); - assert(rejectsBranchValue(noRuntime, 2.0)); - assert(rejectsBranchValue(noRuntime, VmDegree(0.0))); - assert(rejectsBranchValue(noRuntime, VmText{{101}})); - assert(rejectsBranchValue(noRuntime, std::make_shared())); - assert(rejectsBranchValue(noRuntime, std::make_shared())); - assert(rejectsBranchValue(noRuntime, std::make_shared())); - - FelidaeIr factProgram; - factProgram.registerCount = 2; - factProgram.symbols = {50, 51, 12}; - factProgram.constants = {{IrConstantKind::Number, encodeIrNumber(12.0)}}; - factProgram.words = { - static_cast(IrOpcode::MakeFact), - 0, - 0, - 0, - static_cast(IrOpcode::LoadConst), - 1, - 0, - static_cast(IrOpcode::SetField), - 0, - 1, - 1, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End), - }; - auto invalidFactSource = factProgram; - invalidFactSource.words[3] = 1; - assert(rejects([&] { IrVerifier::verify(invalidFactSource); })); - const auto factValue = executeDirect(factProgram, noRuntime); - const auto fact = std::get(factValue); - assert(fact->type == 50 && fact->fields.size() == 1); - assert(fact->fields.front().first == 51); - assert(std::get(fact->fields.front().second) == 12.0); - - class SymbolRuntime final : public NoRuntime { - public: - VmValue loadSymbol(IrSymbolRef symbol) override { - return values.at(symbol); - } - void storeSymbol(IrSymbolRef symbol, const VmValue &value) override { - values[symbol] = value; - } - std::unordered_map values; - } symbolRuntime; - FelidaeIr symbolStore; - symbolStore.registerCount = 1; - symbolStore.symbols = {7}; - symbolStore.constants = {{IrConstantKind::Number, encodeIrNumber(9.0)}}; - symbolStore.words = { - static_cast(IrOpcode::LoadConst), 0, 0, - static_cast(IrOpcode::StoreSymbol), 0, 0, - static_cast(IrOpcode::LoadSymbol), 0, 0, - static_cast(IrOpcode::Return), 0, 0, - static_cast(IrOpcode::End), - }; - assert(std::get(executeDirect(symbolStore, symbolRuntime)) == 9.0); - - FelidaeIr directProcedure; - directProcedure.registerCount = 1; - directProcedure.constants = {{IrConstantKind::Number, encodeIrNumber(7.0)}}; - directProcedure.words = { - static_cast(IrOpcode::LoadConst), 0, 0, - static_cast(IrOpcode::Return), 0, 0, - static_cast(IrOpcode::End), - }; - FelidaeIr directCaller; - directCaller.registerCount = 1; - directCaller.symbols = {99}; - directCaller.words = { - static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End), - }; - FelidaeKnowledgeRuntime procedureRuntime; - assert(std::get(executeDirect( - directCaller, procedureRuntime, - {{99, IrProcedure{directProcedure, {}, {}, {}}}})) == 7.0); - FelidaeIr recursiveProcedure; - recursiveProcedure.registerCount = 1; - recursiveProcedure.symbols = {77}; - recursiveProcedure.words = { - static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End), - }; - FelidaeIr recursiveCaller = directCaller; - recursiveCaller.symbols = {77}; - FelidaeKnowledgeRuntime boundedRecursionRuntime(nullptr, 1024, 2); - bool recursionRejected = false; - try { - (void)executeDirect(recursiveCaller, boundedRecursionRuntime, - {{77, IrProcedure{recursiveProcedure, {}, {}, {}}}}); - } catch (const IrError &) { - recursionRejected = true; - } - assert(recursionRejected); - - class StatefulSemanticModel final : public RuntimeStateModel { - public: - std::shared_ptr createExecutionState() override { - return std::make_shared(0); - } - VmValue evaluate(const RuntimeOperation &operation, - std::span inputs, - RuntimeContext &context) override { - assert(operation.id == - static_cast(SemanticOperationId::Identity) && - inputs.size() == 1); - auto state = - std::static_pointer_cast(context.executionState); - // Generic test runtimes may not opt into the production lifecycle; - // they still receive an execution-local context and never persist - // this fallback state beyond this RegisterVm invocation. - if (!state) { - state = std::make_shared(0); - context.executionState = state; - } - ++*state; - return std::get(inputs.front()) + static_cast(*state); - } - } semanticModel; - class SemanticRuntime final : public NoRuntime { - public: - explicit SemanticRuntime(RuntimeStateModel &model) : model_(model) {} - RuntimeStateModel *runtimeStateModel() override { return &model_; } - RuntimeContext makeRuntimeContext(const VmValue &) const override { - RuntimeContext context; - context.maximumSemanticSteps = 2; - return context; - } - - private: - RuntimeStateModel &model_; - } semanticRuntime(semanticModel); - FelidaeIr semanticProgram; - semanticProgram.registerCount = 2; - semanticProgram.constants = {{IrConstantKind::Number, encodeIrNumber(4.0)}}; - semanticProgram.words = { - static_cast(IrOpcode::LoadConst), - 0, - 0, - static_cast(IrOpcode::SemanticEval), - 1, - static_cast(SemanticOperationId::Identity), - 1, - 0, - static_cast(IrOpcode::Return), - 1, - 0, - static_cast(IrOpcode::End), - }; - assert(std::get(executeDirect(semanticProgram, semanticRuntime)) == - 5.0); - // A new VM execution owns a new RuntimeContext; recurrent state cannot - // leak across requests even when the backend instance is reused. - assert(std::get(executeDirect(semanticProgram, semanticRuntime)) == - 5.0); - FelidaeKnowledgeRuntime directSemanticRuntime(&semanticModel); - assert(std::get( - executeDirect(semanticProgram, directSemanticRuntime)) == 5.0); - // Facts asserted earlier in the same VM program are refreshed into the - // learned-operation context; a model never trains on a snapshot it cannot - // observe during production execution. - class KnowledgeCheckingModel final : public RuntimeStateModel { - public: - VmValue evaluate(const RuntimeOperation &operation, - std::span inputs, - RuntimeContext &context) override { - assert(operation.id == - static_cast(SemanticOperationId::Identity) && - inputs.size() == 1); - assert(context.knowledge.factTypes.size() == 1 && - context.knowledge.factTypes[0] == 77); - assert(context.knowledge.factTypeCounts.size() == 1 && - context.knowledge.factTypeCounts[0].first == 77 && - context.knowledge.factTypeCounts[0].second == 1); - assert(std::holds_alternative(inputs.front())); - return inputs.front(); - } - } knowledgeModel; - FelidaeIr knowledgeProgram; - knowledgeProgram.registerCount = 2; - knowledgeProgram.symbols = {77}; - knowledgeProgram.words = { - static_cast(IrOpcode::MakeFact), - 0, - 0, - 0, - static_cast(IrOpcode::SemanticEval), - 1, - static_cast(SemanticOperationId::Identity), - 1, - 0, - static_cast(IrOpcode::Return), - 1, - 0, - static_cast(IrOpcode::End), - }; - FelidaeKnowledgeRuntime knowledgeRuntime(&knowledgeModel); - assert(std::holds_alternative( - executeDirect(knowledgeProgram, knowledgeRuntime))); - // Nested calls are part of one top-level execution: the SSM state and - // semantic budget are shared across their fresh register frames. - FelidaeIr semanticCaller; - semanticCaller.registerCount = 2; - semanticCaller.symbols = {99}; - semanticCaller.words = { - static_cast(IrOpcode::Call), - 0, - 0, - 0, - static_cast(IrOpcode::Call), - 1, - 0, - 0, - static_cast(IrOpcode::Return), - 1, - 0, - static_cast(IrOpcode::End), - }; - FelidaeKnowledgeRuntime nestedSemanticRuntime(&semanticModel, 2); - assert(std::get(executeDirect( - semanticCaller, nestedSemanticRuntime, - {{99, IrProcedure{semanticProgram, {}, {}, {}}}})) == 6.0); - FelidaeIr overLimitSemanticProgram; - overLimitSemanticProgram.registerCount = 4; - overLimitSemanticProgram.constants = { - {IrConstantKind::Number, encodeIrNumber(1.0)}}; - overLimitSemanticProgram.words = { - static_cast(IrOpcode::LoadConst), - 0, - 0, - static_cast(IrOpcode::SemanticEval), - 1, - static_cast(SemanticOperationId::Identity), - 1, - 0, - static_cast(IrOpcode::SemanticEval), - 2, - static_cast(SemanticOperationId::Identity), - 1, - 1, - static_cast(IrOpcode::SemanticEval), - 3, - static_cast(SemanticOperationId::Identity), - 1, - 2, - static_cast(IrOpcode::Return), - 3, - 0, - static_cast(IrOpcode::End), - }; - bool semanticLimitRejected = false; - try { - (void)executeDirect(overLimitSemanticProgram, semanticRuntime); - } catch (const IrError &) { - semanticLimitRejected = true; - } - assert(semanticLimitRejected); - FelidaeKnowledgeRuntime oneStepSemanticRuntime(&semanticModel, 1); - bool directSemanticLimitRejected = false; - try { - (void)executeDirect(overLimitSemanticProgram, oneStepSemanticRuntime); - } catch (const IrError &) { - directSemanticLimitRejected = true; - } - assert(directSemanticLimitRejected); - bool unavailableSemanticRejected = false; - try { - (void)executeDirect(semanticProgram, noRuntime); - } catch (const IrError &) { - unavailableSemanticRejected = true; - } - assert(unavailableSemanticRejected); - class InvalidSemanticModel final : public RuntimeStateModel { - public: - VmValue evaluate(const RuntimeOperation &, std::span, - RuntimeContext &) override { - return VmMapPtr{}; - } - } invalidSemanticModel; - SemanticRuntime invalidSemanticRuntime(invalidSemanticModel); - bool invalidSemanticRejected = false; - try { - (void)executeDirect(semanticProgram, invalidSemanticRuntime); - } catch (const IrError &) { - invalidSemanticRejected = true; - } - assert(invalidSemanticRejected); - class WrongIdentityTypeModel final : public RuntimeStateModel { - public: - VmValue evaluate(const RuntimeOperation &, std::span, - RuntimeContext &) override { - return VmText{{101, 102}}; - } - } wrongIdentityTypeModel; - SemanticRuntime wrongIdentityRuntime(wrongIdentityTypeModel); - bool wrongIdentityTypeRejected = false; - try { - (void)executeDirect(semanticProgram, wrongIdentityRuntime); - } catch (const IrError &) { - wrongIdentityTypeRejected = true; - } - assert(wrongIdentityTypeRejected); - - FelidaeIr branchSkipsInitialization; - branchSkipsInitialization.registerCount = 2; - branchSkipsInitialization.constants = {{IrConstantKind::Boolean, 1}}; - branchSkipsInitialization.words = { - static_cast(IrOpcode::LoadConst), 0, 0, - static_cast(IrOpcode::JumpIfFalse), 0, 9, - static_cast(IrOpcode::LoadConst), 1, 0, - static_cast(IrOpcode::Return), 1, 0, - static_cast(IrOpcode::End), - }; - bool flowRejected = false; - try { - IrVerifier::verify(branchSkipsInitialization); - } catch (const IrError &) { - flowRejected = true; - } - assert(flowRejected); - - FelidaeIr overflowingCall; - overflowingCall.registerCount = 1; - overflowingCall.symbols = {0}; - overflowingCall.words = {static_cast(IrOpcode::Call), 0, 0, - std::numeric_limits::max()}; - bool overflowRejected = false; - try { - IrVerifier::verify(overflowingCall); - } catch (const IrError &) { - overflowRejected = true; - } - assert(overflowRejected); - - FelidaeIr invalidSemanticOperation; - invalidSemanticOperation.registerCount = 1; - invalidSemanticOperation.words = { - static_cast(IrOpcode::SemanticEval), - 0, - 0xffffu, - 0, - static_cast(IrOpcode::Return), - 0, - 0, - static_cast(IrOpcode::End), - }; - bool invalidSemanticOperationRejected = false; - try { - IrVerifier::verify(invalidSemanticOperation); - } catch (const IrError &) { - invalidSemanticOperationRejected = true; - } - assert(invalidSemanticOperationRejected); - - FelidaeIr overflowingSemanticOperation; - overflowingSemanticOperation.registerCount = 1; - overflowingSemanticOperation.symbols = {1}; - overflowingSemanticOperation.words = { - static_cast(IrOpcode::SemanticEval), - 0, - 0, - std::numeric_limits::max(), - }; - bool overflowingSemanticRejected = false; - try { - IrVerifier::verify(overflowingSemanticOperation); - } catch (const IrError &) { - overflowingSemanticRejected = true; - } - assert(overflowingSemanticRejected); - - FelidaeIr badSourceMap = arithmetic; - badSourceMap.sourceMap = {IrSourceMapEntry{1, {1, 1, 1, 2}}}; - bool sourceMapRejected = false; - try { - IrVerifier::verify(badSourceMap); - } catch (const IrError &) { - sourceMapRejected = true; - } - assert(sourceMapRejected); - - bool rejected = false; - try { - const std::vector noEnd = { - {MixfixIrTokenKind::Opcode, kIrOpcodeCount}}; - (void)resolveMixfixIrTokens(noEnd, context); - } catch (const IrError &) { - rejected = true; - } - assert(rejected); -} diff --git a/tests/RocksDbTest.cpp b/tests/RocksDbTest.cpp deleted file mode 100644 index d6ef865..0000000 --- a/tests/RocksDbTest.cpp +++ /dev/null @@ -1,489 +0,0 @@ -#include "form/libs/RocksDb.h" -#include "form/libs/FactStorageCodec.h" -#include - -#include -#include -#include -#include -#include -#include -#include - -int main() { - namespace fs = std::filesystem; - using Felidae::Form::RocksDb; - - // Corrupt CBOR numbers must not wrap/truncate into valid IDs or tags. - { - using Json = nlohmann::ordered_json; - Felidae::VmFact fact; - fact.type = 1; - fact.fields = {{1, 3.5}}; - const std::vector symbols{{11}}; - const auto bytes = Felidae::Form::encodeStoredFact(fact, std::nullopt, symbols); - const auto original = Json::from_cbor(bytes); - const auto rejectsRecord = [&](const Json &record) { - const auto encoded = Json::to_cbor(record); - try { - (void)Felidae::Form::decodeStoredFact( - std::string_view(reinterpret_cast(encoded.data()), encoded.size()), - [](Felidae::PieceSequence) { return Felidae::IrSymbolRef{1}; }); - } catch (const Felidae::IrError &) { return true; } - return false; - }; - for (const Json invalid : {Json(-1), Json(1.5), Json(true)}) { - for (const auto field : {0, 2, 3}) { - auto record = original; - record[1][field] = invalid; - assert(rejectsRecord(record)); - } - } - auto record = original; - record[1][2] = 256; - assert(rejectsRecord(record)); - record = original; - record[1][4][0][1][0] = original[1][4][0][1][0].get() + 256; - assert(rejectsRecord(record)); - record = original; - record[0] = 1.5; - assert(rejectsRecord(record)); - } - - // Reopening may intern symbols in another order. Equivalent nested fact - // keys must remain byte-for-byte identical across those runtime mappings. - { - const std::vector first{{90}, {10}, {20}}; - const std::vector second{{20}, {90}, {10}}; - auto left = std::make_shared(); - left->type = 1; - left->fields = {{2, 3.5}, {3, Felidae::VmSymbol{1}}}; - auto right = std::make_shared(); - right->type = 2; - right->fields = {{1, Felidae::VmSymbol{2}}, {3, 3.5}}; - assert(Felidae::Form::encodeStoredValueKey(Felidae::VmFactPtr{left}, first) == - Felidae::Form::encodeStoredValueKey(Felidae::VmFactPtr{right}, second)); - auto leftMap = std::make_shared(); - leftMap->entries = left->fields; - auto rightMap = std::make_shared(); - rightMap->entries = right->fields; - assert(Felidae::Form::encodeStoredValueKey(leftMap, first) == - Felidae::Form::encodeStoredValueKey(rightMap, second)); - } - - const fs::path database = - fs::path(FELIDAE_TEST_OUTPUT_DIR) / "ordered-driver.rocksdb"; - std::error_code error; - fs::remove_all(database, error); - assert(!error); - - { - RocksDb store(database); - const std::vector symbols{{11}, {12, 13}, {14}}; - auto nested = std::make_shared(); - nested->type = 1; - nested->fields = {{2, Felidae::VmText{{21, 22}}}}; - Felidae::VmFact fact; - fact.id = 42; - fact.type = 1; - fact.createdSequence = 7; - fact.origin = Felidae::VmFact::Origin::Derived; - auto values = std::make_shared(); - auto emptyKeyMap = std::make_shared(); - emptyKeyMap->entries = {{Felidae::PieceSequence{}, Felidae::VmText{}}}; - values->values = {-212.421, Felidae::VmDegree(0.75), - Felidae::VmFactPtr{nested}, Felidae::VmText{}, emptyKeyMap}; - fact.fields = {{2, values}, {3, Felidae::VmSymbol{1}}}; - const auto encoded = Felidae::Form::encodeStoredFact( - fact, std::string_view("facts/source.fx"), symbols); - const std::vector parents{3}; - const std::vector> indexes{{2}, {2, 3}}; - const auto encodedType = Felidae::Form::encodeStoredFactType( - 1, parents, indexes, symbols); - const std::vector initial{ - {RocksDb::Mutation::Kind::Put, "fact/type/A/0001", "one"}, - {RocksDb::Mutation::Kind::Put, "fact/type/A/0002", "two"}, - {RocksDb::Mutation::Kind::Put, "fact/type/A/0003", "three"}, - {RocksDb::Mutation::Kind::Put, "fact/type/B/0001", "other"}, - {RocksDb::Mutation::Kind::Put, "record/00000042", encoded}, - {RocksDb::Mutation::Kind::Put, "type/primary", encodedType}, - }; - store.write(initial); - assert(store.get("fact/type/A/0002") == "two"); - assert(!store.get("fact/type/A/missing")); - bool oversizedScanRejected = false; - try { - (void)store.scanPrefix("fact/type/A/", std::nullopt, - RocksDb::maximumScanRecords + 1); - } catch (const Felidae::IrError &) { oversizedScanRejected = true; } - assert(oversizedScanRejected); - const auto zero = store.scanPrefix("fact/type/A/", std::nullopt, 0); - assert(zero.rows.empty() && zero.hasMore); - const auto maximum = store.scanPrefix("fact/type/A/", std::nullopt, - RocksDb::maximumScanRecords); - assert(maximum.rows.size() == 3 && !maximum.hasMore); - - const auto first = store.scanPrefix("fact/type/A/", std::nullopt, 2); - assert(first.rows.size() == 2 && first.hasMore); - assert(first.rows[0].second == "one" && first.rows[1].second == "two"); - const auto second = store.scanPrefix( - "fact/type/A/", first.rows.back().first, 2); - assert(second.rows.size() == 1 && !second.hasMore); - assert(second.rows.front().second == "three"); - - const std::vector replacement{ - {RocksDb::Mutation::Kind::Put, "fact/type/A/0002", "updated"}, - {RocksDb::Mutation::Kind::Erase, "fact/type/A/0001", {}}, - }; - store.write(replacement); - } - - // Closing and reopening proves this is durable storage, not an in-memory - // test double hidden behind the driver interface. - { - RocksDb reopened(database); - assert(!reopened.get("fact/type/A/0001")); - assert(reopened.get("fact/type/A/0002") == "updated"); - const auto rows = reopened.scanPrefix("fact/type/A/", std::nullopt, 8); - assert(rows.rows.size() == 2 && !rows.hasMore); - std::map interned; - const auto decoded = Felidae::Form::decodeStoredFact( - *reopened.get("record/00000042"), - [&](Felidae::PieceSequence pieces) { - const auto [found, _] = interned.emplace( - std::move(pieces), - static_cast(interned.size() + 1)); - return found->second; - }); - assert(decoded.source == "facts/source.fx"); - assert(decoded.fact && decoded.fact->id == 42 && - decoded.fact->createdSequence == 7 && - decoded.fact->origin == Felidae::VmFact::Origin::Derived); - const auto decodedValues = - std::get(decoded.fact->fields.front().second); - assert(decodedValues && decodedValues->values.size() == 5); - assert(std::get(decodedValues->values[0]) == -212.421); - assert(std::get(decodedValues->values[1]).value == 0.75); - assert(std::get(decodedValues->values[2])); - assert(std::get(decodedValues->values[3]).pieces.empty()); - const auto emptyMap = - std::get(decodedValues->values[4]); - assert(emptyMap && emptyMap->entries.size() == 1); - assert(emptyMap->entries.front().first.empty()); - assert(std::get(emptyMap->entries.front().second) - .pieces.empty()); - const auto decodedType = Felidae::Form::decodeStoredFactType( - *reopened.get("type/primary"), - [&](Felidae::PieceSequence pieces) { - const auto [found, _] = interned.emplace( - std::move(pieces), - static_cast(interned.size() + 1)); - return found->second; - }); - assert(decodedType.type != 0 && decodedType.parents.size() == 1); - assert(decodedType.indexes.size() == 2 && - decodedType.indexes[1].size() == 2); - } - - const fs::path factDatabase = - fs::path(FELIDAE_TEST_OUTPUT_DIR) / "vm-facts.rocksdb"; - fs::remove_all(factDatabase, error); - assert(!error); - Felidae::IrFactRef storedId = 0; - { - Felidae::VmFactStore facts(factDatabase); - const auto type = facts.internSymbol({101}); - const auto field = facts.internSymbol({102}); - facts.registerType(type, {}, {{field}}); - auto builder = std::make_shared(); - builder->type = type; - builder->fields = {{field, -212.421}}; - auto retained = facts.retain(builder); - storedId = retained->id; - facts.recordSource(storedId, "facts/persistent.fx"); - retained = facts.mutate(retained, field, 89.024, 0); - assert(std::get(retained->fields.front().second) == 89.024); - } - { - RocksDb raw(factDatabase); - // Type registration, insertion, ownership, and update each commit once. - assert(raw.get("M/revision") == std::string("\0\0\0\0\0\0\0\4", 8)); - assert(raw.scanPrefix(std::string_view{"IT", 2}, std::nullopt, 8) - .rows.size() == 1); - assert(raw.scanPrefix(std::string_view{"IF", 2}, std::nullopt, 8) - .rows.size() == 1); - assert(raw.scanPrefix(std::string_view{"IS", 2}, std::nullopt, 8) - .rows.size() == 1); - assert(raw.scanPrefix(std::string_view{"IE", 2}, std::nullopt, 8) - .rows.size() == 1); - } - { - Felidae::VmFactStore reopened(factDatabase); - const auto type = reopened.findSymbol(std::array{101}); - const auto field = reopened.findSymbol(std::array{102}); - assert(type && field); - const std::array, 1> - predicate{{{*field, 89.024}}}; - const auto rows = reopened.snapshotMatching(*type, predicate); - assert(rows.size() == 1 && rows.front()->id == storedId); - assert(reopened.sourceOf(storedId) == "facts/persistent.fx"); - const auto updated = reopened.mutate(rows.front(), *field, -3.0, 0); - assert(std::get(updated->fields.front().second) == -3.0); - bool staleRejected = false; - try { - (void)reopened.mutate(rows.front(), *field, 5.0, 0); - } catch (const Felidae::IrError &) { - staleRejected = true; - } - assert(staleRejected); - assert(reopened.erase(std::array{updated}) == 1); - } - { - Felidae::VmFactStore reopened(factDatabase); - assert(reopened.size() == 0); - auto replacement = std::make_shared(); - replacement->type = reopened.internSymbol({101}); - replacement->fields = {{reopened.internSymbol({102}), 7.0}}; - const auto retained = reopened.retain(replacement); - assert(retained->id > storedId); - assert(retained->createdSequence > 1); - } - { - RocksDb raw(factDatabase); - // Reopening and the rejected stale update must not advance the revision. - // The successful update, deletion, and replacement add three commits. - assert(raw.get("M/revision") == std::string("\0\0\0\0\0\0\0\7", 8)); - const std::array malformed{{ - {RocksDb::Mutation::Kind::Put, "M/revision", "invalid"}}}; - raw.write(malformed); - } - bool malformedRevisionRejected = false; - try { - Felidae::VmFactStore reopened(factDatabase); - } catch (const Felidae::IrError &) { - malformedRevisionRejected = true; - } - assert(malformedRevisionRejected); - - const fs::path pageDatabase = - fs::path(FELIDAE_TEST_OUTPUT_DIR) / "paged-facts.rocksdb"; - fs::remove_all(pageDatabase, error); - assert(!error); - std::optional cursor; - std::vector expected; - { - Felidae::VmFactStore store(pageDatabase); - const auto parent = store.internSymbol({201}); - const auto child = store.internSymbol({202}); - const auto field = store.internSymbol({203}); - const auto residual = store.internSymbol({204}); - store.registerType(parent, {}, {{field}}); - store.registerType(child, {parent}); - for (int i = 0; i < 5; ++i) { - auto fact = std::make_shared(); - fact->type = i % 2 ? child : parent; - fact->fields = {{field, 7.0}, {residual, i % 2 ? 0.0 : 1.0}}; - expected.push_back(store.retain(fact)->id); - } - const auto zero = store.pageAssignableTo(parent, 0); - assert(zero.rows.empty() && zero.hasMore); - const auto first = store.pageAssignableTo(parent, 2); - assert(first.rows.size() == 2 && first.hasMore && first.next); - assert(first.rows[0]->id == expected[0]); - assert(first.rows[1]->id == expected[1]); - cursor = first.next; - const auto rejects = [](const auto &action) { - try { action(); } catch (const Felidae::IrError &) { return true; } - return false; - }; - assert(rejects([&] { (void)store.pageAssignableTo(child, 2, cursor); })); - auto foreign = cursor; - foreign->database += "other"; - assert(rejects([&] { (void)store.pageAssignableTo(parent, 2, foreign); })); - auto invalid = cursor; - invalid->lastKey.pop_back(); - assert(rejects([&] { (void)store.pageAssignableTo(parent, 2, invalid); })); - assert(rejects([&] { (void)store.pageAssignableTo(parent, 10'001); })); - std::vector> predicates{ - {field, 7.0}, {residual, 1.0}}; - const auto matched = store.pageMatching(parent, predicates, 2); - assert(matched.rows.size() == 2 && matched.next && matched.hasMore); - assert(matched.rows[0]->id == expected[0]); - assert(matched.rows[1]->id == expected[2]); - // Equivalent argument order must retain the same cursor query identity. - std::reverse(predicates.begin(), predicates.end()); - const auto remaining = store.pageMatching(parent, predicates, 2, matched.next); - assert(remaining.rows.size() == 1 && !remaining.hasMore); - assert(remaining.rows[0]->id == expected[4]); - predicates[0].second = 0.0; - assert(rejects([&] { - (void)store.pageMatching(parent, predicates, 2, matched.next); - })); - assert(store.pageMatching(child, predicates, 2).rows.size() == 2); - predicates[1].second = 8.0; - assert(store.pageMatching(parent, predicates, 2).rows.empty()); - } - { - Felidae::VmFactStore store(pageDatabase); - const auto parent = store.internSymbol({201}); - const auto second = store.pageAssignableTo(parent, 2, cursor); - assert(second.rows.size() == 2 && second.hasMore && second.next); - assert(second.rows[0]->id == expected[2]); - assert(second.rows[1]->id == expected[3]); - const auto last = store.pageAssignableTo(parent, 2, second.next); - assert(last.rows.size() == 1 && !last.hasMore && !last.next); - assert(last.rows[0]->id == expected[4]); - store.erase(last.rows); - bool stale = false; - try { (void)store.pageAssignableTo(parent, 2, cursor); } - catch (const Felidae::IrError &) { stale = true; } - assert(stale); - } - - const fs::path inheritedDatabase = - fs::path(FELIDAE_TEST_OUTPUT_DIR) / "inherited-index-pages.rocksdb"; - fs::remove_all(inheritedDatabase, error); - assert(!error); - std::optional inheritedCursor; - Felidae::IrSymbolRef previousChild = 0; - { - Felidae::VmFactStore store(inheritedDatabase); - // Deliberately intern out of canonical storage order. - const auto child = store.internSymbol({901}); - previousChild = child; - const auto first = store.internSymbol({801}); - const auto second = store.internSymbol({701}); - const auto field = store.internSymbol({601}); - store.registerType(first, {}, {{field}}); - store.registerType(second, {}, {{field}}); - store.registerType(child, {first, second}); - for (int i = 0; i < 3; ++i) { - auto fact = std::make_shared(); - fact->type = child; - fact->fields = {{field, 5.0}}; - (void)store.retain(fact); - } - const std::array, 1> - predicates{{{field, 5.0}}}; - const auto page = store.pageMatching(child, predicates, 1); - assert(page.rows.size() == 1 && page.next && page.hasMore); - inheritedCursor = page.next; - } - { - Felidae::VmFactStore store(inheritedDatabase); - const auto child = store.internSymbol({901}); - const auto field = store.internSymbol({601}); - assert(child != previousChild); - const std::array, 1> - predicates{{{field, 5.0}}}; - const auto next = store.pageMatching(child, predicates, 2, inheritedCursor); - assert(next.rows.size() == 2 && !next.hasMore); - assert(next.rows[0]->id == 2 && next.rows[1]->id == 3); - } - { - RocksDb raw(inheritedDatabase); - const std::string firstKey("F\0\0\0\0\0\0\0\1", 9); - const auto record = raw.get(firstKey); - assert(record); - const std::array misplaced{{ - {RocksDb::Mutation::Kind::Put, - std::string("F\0\0\0\0\0\0\0\11", 9), *record}}}; - raw.write(misplaced); - } - bool misplacedRecordRejected = false; - try { - Felidae::VmFactStore store(inheritedDatabase); - (void)store.snapshot(); - } - catch (const Felidae::IrError &) { misplacedRecordRejected = true; } - assert(misplacedRecordRejected); - - const auto checkRollback = [](Felidae::VmFactStore &store) { - const auto type = store.internSymbol({1001}); - const auto field = store.internSymbol({1002}); - store.registerType(type, {}, {{field}}); - auto fact = std::make_shared(); - fact->type = type; - fact->fields = {{field, 1.0}}; - const auto original = store.retain(fact); - assert(store.snapshotByField(field).size() == 1); - const auto updated = store.mutate(original, field, 2.0, 0); - const auto other = store.retain(fact); - bool staleDeleteRejected = false; - try { - store.erase(std::array{other, original}); - } catch (const Felidae::IrError &) { staleDeleteRejected = true; } - assert(staleDeleteRejected); - assert(store.size() == 2); // Validate the whole batch before removing any row. - assert(store.erase(std::array{other, other}) == 1); - // Deserialized snapshots are equivalent values, not identical pointers. - const Felidae::VmFactPtr fresh = std::make_shared(*updated); - store.restore(fresh, original); - const std::array, 1> - oldPredicate{{{field, 1.0}}}, newPredicate{{{field, 2.0}}}; - assert(store.snapshotMatching(type, oldPredicate).size() == 1); - assert(store.snapshotMatching(type, newPredicate).empty()); - assert(std::get(store.snapshotByField(field).front()->fields.front().second) == 1.0); - bool staleRejected = false; - try { store.restore(updated, original); } - catch (const Felidae::IrError &) { staleRejected = true; } - assert(staleRejected); - store.erase(std::array{original}); - bool absentRejected = false; - try { store.restore(original, original); } - catch (const Felidae::IrError &) { absentRejected = true; } - assert(absentRejected); - assert(store.snapshot().empty()); - assert(store.snapshotByField(field).empty()); - }; - { - Felidae::VmFactStore memory; - checkRollback(memory); - } - const fs::path rollbackDatabase = - fs::path(FELIDAE_TEST_OUTPUT_DIR) / "rollback-facts.rocksdb"; - fs::remove_all(rollbackDatabase, error); - assert(!error); - { - Felidae::VmFactStore persistent(rollbackDatabase); - checkRollback(persistent); - } - { - Felidae::VmFactStore reopened(rollbackDatabase); - assert(reopened.snapshot().empty()); - } - - const fs::path ownershipDatabase = - fs::path(FELIDAE_TEST_OUTPUT_DIR) / "ownership-facts.rocksdb"; - fs::remove_all(ownershipDatabase, error); - assert(!error); - { - Felidae::VmFactStore store(ownershipDatabase); - const auto type = store.internSymbol({1101}); - store.registerType(type, {}); - auto builder = std::make_shared(); - builder->type = type; - const auto first = store.retain(builder); - const auto second = store.retain(builder); - (void)store.retain(builder); // In-memory ownership: excluded from both files. - store.recordSource(first->id, "a.csv"); - store.recordSource(second->id, "b.csv"); - assert(store.snapshotBySource("a.csv").size() == 1); - assert(store.snapshotBySource("b.csv").size() == 1); - store.recordSource(first->id, "b.csv"); - assert(store.snapshotBySource("a.csv").empty()); - auto rows = store.snapshotBySource("b.csv"); - assert(rows.size() == 2 && rows[0]->id == first->id && - rows[1]->id == second->id); - store.erase(std::array{first}); - assert(store.snapshotBySource("b.csv").size() == 1); - store.restoreErased(first, "b.csv"); - } - { - Felidae::VmFactStore reopened(ownershipDatabase); - assert(reopened.snapshotBySource("a.csv").empty()); - const auto rows = reopened.snapshotBySource("b.csv"); - assert(rows.size() == 2 && rows[0]->id == 1 && rows[1]->id == 2); - assert(reopened.snapshotBySource("missing.csv").empty()); - } -} diff --git a/tests/SentencePieceModelTest.cpp b/tests/SentencePieceModelTest.cpp deleted file mode 100644 index a17b481..0000000 --- a/tests/SentencePieceModelTest.cpp +++ /dev/null @@ -1,414 +0,0 @@ -#include "IntegerTokenList.h" -#include "IntegerParser.h" -#include "FelidaeGrammar.h" -#include "MixfixStateModel.h" -#include "ModelStore.h" -#include "SentencePieceModel.h" - -#include -#include - -#include -#include -#include -#include -#include - -namespace { -template -void assertIntegerParseFails(Fn&& fn) { - bool failed = false; - try { fn(); } - catch (const Felidae::IntegerParserError&) { failed = true; } - assert(failed); -} -} - -int main() { - // CLI-support helpers remain side-effect free and are covered here rather - // than by a scratch executable. Windows-native wildcard expansion is - // required because cmd.exe and PowerShell pass `*.jsonl` literally. - assert(Felidae::wildcardMatches("*.jsonl", "mixfix-v1.jsonl")); - assert(Felidae::wildcardMatches("mixfix-*.jsonl", "mixfix-invalid-v1.jsonl")); - assert(!Felidae::wildcardMatches("*.jsonl", "mixfix-v1.tsv")); - char train[] = "--train"; - char dataset[] = "datasets/compiler/*.jsonl"; - char store[] = "--store-model"; - char build[] = "build"; - char epochs[] = "--epochs"; - char twelve[] = "12"; - char rate[] = "--learning-rate"; - char learningRate[] = "0.01"; - char* trainingArguments[]{nullptr, train, dataset, store, build, epochs, twelve, rate, learningRate}; - const auto training = Felidae::parseModelTrainingOptions( - static_cast(std::size(trainingArguments)), trainingArguments); - assert(training && training->dataset == std::filesystem::path(dataset)); - assert(training->store == std::filesystem::path(build)); - assert(training->epochs == 12 && training->learningRate == 0.01); - const auto rejectsTrainingOptions = [](int count, char** arguments) { - try { (void)Felidae::parseModelTrainingOptions(count, arguments); } - catch (const std::runtime_error&) { return true; } - return false; - }; - char malformedRate[] = "0.01junk"; - char* malformedRateArguments[]{nullptr, train, dataset, store, build, rate, malformedRate}; - assert(rejectsTrainingOptions(static_cast(std::size(malformedRateArguments)), - malformedRateArguments)); - char* duplicateEpochArguments[]{nullptr, train, dataset, store, build, - epochs, twelve, epochs, twelve}; - assert(rejectsTrainingOptions(static_cast(std::size(duplicateEpochArguments)), - duplicateEpochArguments)); - const auto buildModel = Felidae::modelStoreDirectory("build", "mixfix-gru"); - const auto distModel = Felidae::modelStoreDirectory("dist", "runtime-gru"); - assert(buildModel.filename() == "mixfix-gru" && buildModel.parent_path().filename() == "build"); - assert(distModel.filename() == "runtime-gru" && distModel.parent_path().filename() == "models"); - - // Expansion occurs in the executable, not in the user's shell. Keep the - // isolated fixture in the configured build/test-artifacts directory; no - // test may create a random system-temporary build tree. - const std::filesystem::path datasetTestDirectory(FELIDAE_TEST_OUTPUT_DIR); - std::error_code ignored; - std::filesystem::remove_all(datasetTestDirectory, ignored); - std::filesystem::create_directories(datasetTestDirectory); - { - std::ofstream(datasetTestDirectory / "mixfix-v1.jsonl") << "{}\n"; - std::ofstream(datasetTestDirectory / "mixfix-invalid-v1.jsonl") << "{}\n"; - std::ofstream(datasetTestDirectory / "ignored.tsv") << "{}\n"; - } - const auto expanded = Felidae::expandJsonlDatasetPaths(datasetTestDirectory / "mixfix-*.jsonl"); - assert(expanded.size() == 2); - assert(expanded[0].filename() == "mixfix-invalid-v1.jsonl"); - assert(expanded[1].filename() == "mixfix-v1.jsonl"); - std::filesystem::remove_all(datasetTestDirectory); - - assert(Felidae::felidaeSentencePieceModelIdentity() == - "sha256:9f5a24275dacac172f145a776434c5b8a49375e4354c682dc52fbc0675114f4b"); - sentencepiece::SentencePieceProcessor model; - const auto loaded = model.Load(FELIDAE_SENTENCEPIECE_MODEL_PATH); - assert(loaded.ok()); - assert(Felidae::kFelidaeTokenizerDatasetSchemaVersion == 1); - assert(Felidae::kFelidaeTokenizerDatasetRecordCount == 92); - assert(Felidae::kFelidaeSentencePieceVocabularySize == - static_cast(model.GetPieceSize())); - assert(model.GetPieceSize() <= 1024 && model.GetPieceSize() > 512); - - // Corpus-covered identifiers should use learned pieces rather than one - // byte token per source byte. This is a stable detection-efficiency gate, - // while byte fallback below remains the robustness gate for unseen UTF-8. - const std::string corpusVocabulary = - "semantic_identity effective_at commonAncestors for_each_fact RatingProfile"; - sentencepiece::SentencePieceText corpusEncoding; - assert(model.Encode(corpusVocabulary, &corpusEncoding).ok()); - assert(corpusEncoding.pieces_size() < static_cast(corpusVocabulary.size() / 2)); - for (const auto& piece : corpusEncoding.pieces()) { - assert(piece.id() != Felidae::TokenId::UNKNOWN); - } - - for (std::size_t index = 0; index < std::size(Felidae::kBuiltinTokens); ++index) { - const auto spelling = Felidae::kBuiltinTokens[index].spelling; - const int id = model.PieceToId(std::string(spelling)); - assert(id == Felidae::kFelidaeBuiltinSentencePieceIds[index]); - assert(model.IdToPiece(id) == spelling); - - sentencepiece::SentencePieceText encoded; - const auto status = model.Encode(std::string(spelling), &encoded); - assert(status.ok()); - assert(encoded.pieces_size() == 1); - assert(encoded.pieces(0).id() == id); - assert(encoded.pieces(0).begin() == 0); - assert(encoded.pieces(0).end() == static_cast(spelling.size())); - } - - // Capitalization is a source property even when SentencePiece places its - // whitespace marker and several bytes in the first identifier piece. - // This keeps capitalized, named terms on the fact-value path after an - // indented return. - const Felidae::IntegerTokenList indentedFactTokens(model, " Stage(depth: 1)"); - Felidae::IntegerParser indentedFactParser(indentedFactTokens); - const auto indentedFact = std::dynamic_pointer_cast( - indentedFactParser.parseExpressionText()); - assert(indentedFact && indentedFact->isCapitalized); - - - // Arbitrary source spelling must remain distinguishable as integer - // sequences. Byte fallback prevents a pair of user anchors from both - // degenerating to SentencePiece's unknown ID. - std::vector wraps; - std::vector accepts; - std::vector unicode; - for (const std::string& spelling : {std::string("wraps"), std::string("accepts"), std::string("naïve")}) { - sentencepiece::SentencePieceText encoded; - assert(model.Encode(spelling, &encoded).ok()); - std::vector ids; - for (const auto& piece : encoded.pieces()) { - assert(piece.id() != Felidae::TokenId::UNKNOWN); - ids.push_back(piece.id()); - } - if (spelling == "wraps") wraps = std::move(ids); - else if (spelling == "accepts") accepts = std::move(ids); - else unicode = std::move(ids); - } - assert(!wraps.empty() && !accepts.empty() && !unicode.empty()); - assert(wraps != accepts); - - const std::string completeSource = - "# comment\n" - "café(value: \"hello\") => return value\n"; - const Felidae::IntegerTokenList blockTokens(model, "first\nsecond\nthird\n"); - assert(blockTokens.encodeCount() == 1); - assert(!blockTokens.entries().empty()); - const Felidae::IntegerTokenList statementTokens( - model, - "value := pipeline(\n" - " input: \"a.b\", weight: 1.25\n" - ") then worker(value: system.result). # completed\n" - "next := value.member.\n"); - (void)statementTokens.entries(); - assert(statementTokens.encodeCount() == 2); - const Felidae::IntegerTokenList sourceTokens(model, completeSource); - assert(!sourceTokens.entries().empty()); - assert(sourceTokens.encodeCount() == 1); - for (const auto& entry : sourceTokens.entries()) { - assert(entry.begin <= entry.end); - assert(entry.end <= completeSource.size()); - } - - const Felidae::IntegerTokenList expressionTokens( - model, "# ignored\n[\"value\", café, (1.0)]"); - Felidae::IntegerParser integerParser(expressionTokens); - const auto expression = integerParser.parseExpressionText(); - assert(expression->debug() == "[\"value\", café, 1]"); - assert(integerParser.metrics().sourceEncodeCount == 1); - assert(integerParser.metrics().tokenCount == expressionTokens.entries().size()); - assert(integerParser.metrics().iterations > 0); - assert(integerParser.metrics().peakRecursionDepth > 0); - - const Felidae::IntegerTokenList structuredTokens( - model, "# direct integer grammar\nworker(task: {name: \"café\"}).result + 2 * 3"); - Felidae::IntegerParser structuredParser(structuredTokens); - const auto structured = structuredParser.parseExpressionText(); - assert(structured->debug() == "worker(task: {name: \"café\"}):result + 2 * 3"); - assert(structuredParser.metrics().sourceEncodeCount == 1); - - const Felidae::IntegerTokenList programTokens( - model, "import \"core.fx\".\nthreshold := 2 + 3.\nPerson(name: \"Ada\", age: threshold)."); - Felidae::IntegerParser programParser(programTokens); - const auto program = programParser.parseProgram(); - assert(program.imports.size() == 1); - assert(program.globals.size() == 1); - assert(program.clauses.size() == 1); - assert(program.clauses.front()->head.name == "Person"); - - // Qualified declaration heads are assembled from a single ID stream. In - // particular, native declarations such as `math.sin` must not leave the - // DOT ID behind as a second pseudo-statement. - const Felidae::IntegerTokenList qualifiedHeadTokens( - model, "math.sin(value: number) => ().\nsystem.print(value: any) => ().\n"); - Felidae::IntegerParser qualifiedHeadParser(qualifiedHeadTokens); - const auto qualifiedHeadProgram = qualifiedHeadParser.parseProgram(); - assert(qualifiedHeadProgram.clauses.size() == 2); - assert(qualifiedHeadProgram.clauses[0]->head.name == "math.sin"); - assert(qualifiedHeadProgram.clauses[1]->head.name == "system.print"); - assert(qualifiedHeadProgram.clauses[0]->head.builtinId == Felidae::BuiltinId::MathSin); - assert(qualifiedHeadProgram.clauses[1]->head.builtinId == Felidae::BuiltinId::SystemPrint); - assert(qualifiedHeadProgram.clauses[0]->head.nameId != 0); - assert(qualifiedHeadProgram.clauses[1]->head.nameId != 0); - - const Felidae::IntegerTokenList qualifiedCallTokens(model, "math.sin(value: 0)"); - Felidae::IntegerParser qualifiedCallParser(qualifiedCallTokens); - const auto qualifiedCall = std::dynamic_pointer_cast( - qualifiedCallParser.parseExpressionText()); - assert(qualifiedCall && qualifiedCall->builtinId == Felidae::BuiltinId::MathSin); - assert(qualifiedCall->nameId != 0); - - const Felidae::IntegerTokenList repeatedTokens( - model, "Record(index: 0).\nRecord(index: 1).\n"); - Felidae::IntegerParser repeatedParser(repeatedTokens); - const auto repeatedProgram = repeatedParser.parseProgram(); - assert(repeatedProgram.clauses.size() == 2); - - // `as` remains legal as a named field, but postfix fact designations are - // deprecated in favor of concrete type where/select queries. - const Felidae::IntegerTokenList designationTokens( - model, "Assessment(as: \"field\") as audited, reviewed\n"); - Felidae::IntegerParser designationParser(designationTokens); - bool designationRejected = false; - try { - (void)designationParser.parseProgram(); - } catch (const Felidae::IntegerParserError &error) { - designationRejected = - std::string(error.what()).find("deprecated") != std::string::npos; - } - assert(designationRejected); - const Felidae::IntegerTokenList designationQueryTokens( - model, "? Assessment(as: \"field\") as audited"); - Felidae::IntegerParser designationQueryParser(designationQueryTokens); - designationRejected = false; - try { - (void)designationQueryParser.parseQuery(); - } catch (const Felidae::IntegerParserError &error) { - designationRejected = - std::string(error.what()).find("deprecated") != std::string::npos; - } - assert(designationRejected); - - const Felidae::IntegerTokenList dottedLabelTokens( - model, "Event(fx.effective_at: \"2025-01-01\")\n"); - Felidae::IntegerParser dottedLabelParser(dottedLabelTokens); - const auto dottedLabelProgram = dottedLabelParser.parseProgram(); - assert(dottedLabelProgram.clauses.size() == 1); - assert(dottedLabelProgram.clauses.front()->head.args.front().name == "fx.effective_at"); - - // Moderate-size program regression: explicit statements are encoded once - // each rather than being split by their physical line layout. - std::string largeSource; - largeSource.reserve(12'000); - for (int index = 0; index < 512; ++index) { - largeSource += "Record(index: " + std::to_string(index) + ").\n"; - } - const Felidae::IntegerTokenList largeTokens(model, largeSource); - Felidae::IntegerParser largeParser(largeTokens); - const auto largeProgram = largeParser.parseProgram(); - assert(largeProgram.clauses.size() == 512); - assert(largeParser.metrics().sourceEncodeCount == 512); - assert(largeParser.metrics().statementCount == 512); - assert(largeParser.metrics().iterations < 100'000); - - const Felidae::IntegerTokenList methodTokens( - model, "main() =>\n value := 1\n return (answer: value)\n"); - Felidae::IntegerParser methodParser(methodTokens); - const auto methodProgram = methodParser.parseProgram(); - assert(methodProgram.clauses.size() == 1); - assert(methodProgram.clauses.front()->clauseKind == Felidae::ClauseKind::Method); - - const Felidae::IntegerTokenList bareReturnBoundaryTokens( - model, "first() =>\n return\nsecond() => return (value: 1)\n"); - Felidae::IntegerParser bareReturnBoundaryParser(bareReturnBoundaryTokens); - const auto bareReturnBoundaryProgram = bareReturnBoundaryParser.parseProgram(); - assert(bareReturnBoundaryProgram.clauses.size() == 2); - - const Felidae::IntegerTokenList queryTokens( - model, "? AncestorOf(descendant: \"kitten\", ancestor: Ancestor)"); - Felidae::IntegerParser queryParser(queryTokens); - const auto queryGoals = queryParser.parseQuery(); - assert(queryGoals.size() == 1); - - const std::string queryText = "? AncestorOf(descendant: \"kitten\", ancestor: Ancestor)"; - const Felidae::IntegerTokenList decodedQueryTokens( - model, "\"? AncestorOf(descendant: \\\"kitten\\\", ancestor: Ancestor)\""); - Felidae::IntegerParser decodedQueryParser(decodedQueryTokens); - const auto decodedQuery = std::dynamic_pointer_cast( - decodedQueryParser.parseExpressionText()); - assert(decodedQuery && decodedQuery->value == queryText); - - const Felidae::IntegerTokenList conditionalTokens( - model, "choose(value: number) =>\n if value > 0 then\n return (result: 1.0)\n else\n return (result: 0.0)\n"); - Felidae::IntegerParser conditionalParser(conditionalTokens); - const auto conditionalProgram = conditionalParser.parseProgram(); - assert(conditionalProgram.clauses.size() == 1); - assert(!conditionalProgram.clauses.front()->body.empty()); - - const Felidae::IntegerTokenList fallbackTokens( - model, "choose() =>\n return (result: 1.0)\nelse\n return (result: 0.0)\n"); - Felidae::IntegerParser fallbackParser(fallbackTokens); - const auto fallbackProgram = fallbackParser.parseProgram(); - assert(fallbackProgram.clauses.size() == 1); - assert(fallbackProgram.clauses.front()->fallbackBranches.size() == 1); - - // Annotation syntax is assembled from the same integer stream. Literal - // anchors retain their spelling but deliberately do not trigger a second - // SentencePiece encode; matching advances only through full-source - // encode offsets. - auto operators = std::make_shared(); - const Felidae::IntegerTokenList mixfixDeclarationTokens(model, - "@mixfix(pattern: \"choose {value: expr}\")\n" - "choose() => return (value).\n"); - Felidae::IntegerParser mixfixDeclarationParser(mixfixDeclarationTokens, operators); - const auto mixfixDeclarationProgram = mixfixDeclarationParser.parseProgram(); - assert(mixfixDeclarationProgram.clauses.size() == 1); - assert(operators->patterns().size() == 1); - assert(!operators->patterns().front().anchorLexemes.empty()); - assert(operators->patterns().front().anchorLexemes.front().front().spelling == "choose"); - assert(operators->patterns().front().anchorLexemes.front().front().pieceIds.empty()); - const Felidae::IntegerTokenList mixfixUseTokens(model, "choose 7"); - Felidae::IntegerParser mixfixUseParser(mixfixUseTokens, operators); - const auto mixfixUse = std::dynamic_pointer_cast( - mixfixUseParser.parseExpressionText()); - assert(mixfixUse); - assert(mixfixUse->patternId == operators->patterns().front().patternId); - assert(mixfixUse->captureCount() == 1); - // Literal anchors cannot consume an identifier prefix after SentencePiece - // fragmentation: `choose` is not an operator occurrence in `chooseable`. - assertIntegerParseFails([&] { - Felidae::IntegerTokenList prefixedAnchor(model, "chooseable 7"); - Felidae::IntegerParser parser(prefixedAnchor, operators); - (void)parser.parseExpressionText(); - }); - - - const Felidae::IntegerTokenList nestedMixfixDeclarationTokens(model, - "@mixfix(pattern: \"wrap {value: expr} end\")\n" - "wrap() => return (value).\n"); - Felidae::IntegerParser nestedMixfixDeclarationParser(nestedMixfixDeclarationTokens, operators); - (void)nestedMixfixDeclarationParser.parseProgram(); - const Felidae::IntegerTokenList nestedMixfixUseTokens(model, "wrap choose 7 end"); - Felidae::IntegerParser nestedMixfixUseParser(nestedMixfixUseTokens, operators); - const auto nestedMixfixUse = std::dynamic_pointer_cast( - nestedMixfixUseParser.parseExpressionText()); - assert(nestedMixfixUse); - assert(nestedMixfixUse->captureCount() == 1); - assert(std::dynamic_pointer_cast(nestedMixfixUse->capture(0))); - - const Felidae::IntegerTokenList trailingMixfixDeclarationTokens(model, - "@mixfix(pattern: \"{left: expr} combines {right: expr}\")\n" - "combines() => return (left).\n"); - Felidae::IntegerParser trailingMixfixDeclarationParser(trailingMixfixDeclarationTokens, operators); - (void)trailingMixfixDeclarationParser.parseProgram(); - const Felidae::IntegerTokenList trailingMixfixUseTokens(model, "1 combines 2"); - Felidae::IntegerParser trailingMixfixUseParser(trailingMixfixUseTokens, operators); - const auto trailingMixfixUse = std::dynamic_pointer_cast( - trailingMixfixUseParser.parseExpressionText()); - assert(trailingMixfixUse); - assert(trailingMixfixUse->captureCount() == 2); - - // Multiple patterns may share an initial anchor. Candidate assembly is - // bounded and selects the pattern that consumes the longest valid ID - // range instead of treating the shared anchor as a string ambiguity. - auto sameAnchorOperators = std::make_shared(); - const Felidae::IntegerTokenList sameAnchorTokens(model, - "@mixfix(pattern: \"plan {name: string} using {strategy: string} with {budget: number}\")\n" - "longPlan() => return (value: name).\n" - "@mixfix(pattern: \"plan {value: number} using {enabled: number}\")\n" - "shortPlan() => return (value: value).\n" - "main() => return (long: plan \"x\" using \"y\" with 1, short: plan 7 using 1.0).\n"); - Felidae::IntegerParser sameAnchorParser(sameAnchorTokens, sameAnchorOperators); - const auto sameAnchorProgram = sameAnchorParser.parseProgram(); - assert(sameAnchorProgram.clauses.size() == 3); - assert(sameAnchorParser.metrics().backtrackingAttempts > 0); - - - // Malformed and deliberately deep input must fail cleanly under the - // parser's forward-progress and recursion bounds. - assertIntegerParseFails([&] { - Felidae::IntegerTokenList malformed(model, "Person(name: "); - Felidae::IntegerParser parser(malformed); - (void)parser.parseProgram(); - }); - std::string deeplyNested(513, '('); - deeplyNested += "value"; - deeplyNested.append(513, ')'); - assertIntegerParseFails([&] { - Felidae::IntegerTokenList nested(model, deeplyNested); - Felidae::IntegerParser parser(nested); - (void)parser.parseExpressionText(); - }); - - std::string longIdentifier(8192, 'x'); - const Felidae::IntegerTokenList longIdentifierTokens(model, longIdentifier); - Felidae::IntegerParser longIdentifierParser(longIdentifierTokens); - const auto longIdentifierExpr = longIdentifierParser.parseExpressionText(); - assert(longIdentifierExpr->debug() == longIdentifier); - - - std::cout << "felidae SentencePiece model validation passed\n"; -} diff --git a/tests/SentencePiecePipelineTest.cpp b/tests/SentencePiecePipelineTest.cpp deleted file mode 100644 index fe38c89..0000000 --- a/tests/SentencePiecePipelineTest.cpp +++ /dev/null @@ -1,1505 +0,0 @@ -#include "CompilerFrontend.h" -#include "FelidaeIr.h" -#include "IntegerParser.h" -#include "IntegerTokenList.h" -#include "IrCodeGenerator.h" -#include "MixfixStateModel.h" -#include "SentencePieceModel.h" -#include "Symbol.h" -#include "form/BinaryIr.h" -#include "form/SemanticOperation.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace { - -Felidae::VmValue executeIrDirect(const Felidae::FelidaeIr &program, - Felidae::VmRuntime &runtime) { - constexpr Felidae::IrSymbolRef kTestEntry = 1; - Felidae::IrModule module; - module.entryProcedure = kTestEntry; - module.ir.registerCount = 1; - module.ir.symbols = {kTestEntry}; - module.ir.words = { - static_cast(Felidae::IrOpcode::Call), - 0, - 0, - 0, - static_cast(Felidae::IrOpcode::Return), - 0, - 0, - static_cast(Felidae::IrOpcode::End), - }; - module.procedures.emplace(kTestEntry, - Felidae::IrProcedure{program, {}, {}, {}}); - auto largestSymbol = kTestEntry; - for (const auto symbol : program.symbols) - largestSymbol = std::max(largestSymbol, symbol); - module.sentencePieceModelIdentity = "sha256:test"; - module.symbolTable.reserve(largestSymbol); - for (Felidae::IrSymbolRef symbol = 1; symbol <= largestSymbol; ++symbol) { - module.symbolTable.push_back({symbol}); - } - return Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(std::move(module)), runtime); -} - -Felidae::VmValue executeModuleDirect(const Felidae::IrModule &module, - Felidae::VmRuntime &runtime) { - return Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(Felidae::IrModule(module)), runtime); -} - -} // namespace - -int main() { - const std::filesystem::path testOutputDirectory(FELIDAE_TEST_OUTPUT_DIR); - std::filesystem::create_directories(testOutputDirectory); - const auto removeTemporary = [](const std::filesystem::path &path) { - std::error_code ignored; - std::filesystem::remove(path, ignored); - }; - // UTF-8 BOM bytes must never reach SentencePiece as a fake token before - // the first source statement. - const auto bomSource = testOutputDirectory / "utf8-bom-first-line.fx"; - { - std::ofstream out(bomSource, std::ios::binary | std::ios::trunc); - out.write("\xEF\xBB\xBF", 3); - out << "main() => return 42\n"; - } - assert(Felidae::readSourceFile(bomSource) == "main() => return 42\n"); - const auto bomModule = Felidae::compileProgramFileToIr(bomSource); - assert(!bomModule.ir.words.empty()); - removeTemporary(bomSource); - Felidae::VmDisplayContext display; - display.textDecoder = [](std::span pieces) { - std::vector ids(pieces.begin(), pieces.end()); - std::string text; - assert(Felidae::felidaeSentencePieceModel().Decode(ids, &text).ok()); - return text; - }; - display.symbolDecoder = [](Felidae::IrSymbolRef symbol) { - return Felidae::symbolNameForId(symbol); - }; - const Felidae::VmTextEncoder textEncoder = [](std::string_view text) { - std::vector encoded; - assert(Felidae::felidaeSentencePieceModel() - .Encode(std::string(text), &encoded) - .ok()); - return Felidae::PieceSequence(encoded.begin(), encoded.end()); - }; - const auto displayModuleValue = [&](const Felidae::IrModule &module, - const Felidae::VmValue &value) { - const auto verified = Felidae::verifyIrModule(Felidae::IrModule(module)); - return Felidae::vmValueToDisplayString( - value, Felidae::makeIrDisplayContext(verified, display.textDecoder)); - }; - const auto executeModule = [](const Felidae::IrModule &module) { - Felidae::FelidaeKnowledgeRuntime runtime; - Felidae::RegisterVm vm; - return vm.executeMain(Felidae::verifyIrModule(Felidae::IrModule(module)), - runtime); - }; - const auto numericModule = - Felidae::compileProgramFileToIr(FELIDAE_NUMERIC_OPERATIONS_FIXTURE_PATH); - const auto objectArray = Felidae::compileProgramTextToIr( - "main() =>\n" - " people:obj = array()\n" - " return people\n" - "end\n"); - const auto objectArrayResult = - std::get(executeModule(objectArray)); - assert(objectArrayResult && objectArrayResult->values.empty()); - const auto objectReceiver = Felidae::compileProgramTextToIr( - "main() =>\n" - " people:obj = array()\n" - " people := people.push(value: 42)\n" - " people.len()\n" - " return (first: people.get(position: 0), size: people.len())\n" - "end\n"); - const auto receiverResult = - std::get(executeModule(objectReceiver)); - assert(receiverResult && receiverResult->entries.size() == 2); - assert(std::get(receiverResult->entries[0].second) == 42.0); - assert(std::get(receiverResult->entries[1].second) == 1.0); - const auto globalObject = Felidae::compileProgramTextToIr( - "people:obj = [42].\n" - "main() => return people.get(position: 0)\nend\n"); - assert(std::get(executeModule(globalObject)) == 42.0); - const auto sameLineStatements = Felidae::compileProgramTextToIr( - "left := 1.25. right := left. main() => return right."); - assert(std::get(executeModule(sameLineStatements)) == 1.25); - for (const auto *source : { - "main() => people:obj array()\nreturn people\nend\n", - "value := 1 .25. main() => return value.", - "main() => people:obj = array(42)\nreturn people\nend\n", - "main() => people:obj = [42]\nreturn people.get()\nend\n"}) { - bool rejected = false; - try { (void)Felidae::compileProgramTextToIr(source); } - catch (const Felidae::IntegerParserError &) { rejected = true; } - assert(rejected); - } - const auto numericResult = - std::get(executeModule(numericModule)); - const std::array expectedNumeric{ - 0.3, 0.8, 4.5, 3.2, 15.0, 17.5, 1.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, - 8.0, 1.0, 0.0, 3.0, 1.5, 12.5, -1.0, 0.25, 9.0, 8.0, 1.0, 1.0, 0.0}; - assert(numericResult && - numericResult->entries.size() == expectedNumeric.size()); - for (std::size_t index = 0; index < expectedNumeric.size(); ++index) { - const auto actual = std::get(numericResult->entries[index].second); - assert(std::abs(actual - expectedNumeric[index]) <= - 1e-12 * std::max(1.0, std::abs(expectedNumeric[index]))); - } - // Lowercase scalar min/max deliberately overload the established - // one-array aggregators by positional arity. Both paths must remain - // deterministic and preserve unrestricted signed floating-point values. - const auto numericOverloadModule = Felidae::compileProgramTextToIr( - "main() =>\n" - " return (scalar: max(-345.345, -2.302), " - "aggregate: min(data: [3.432, -2.302]))\n" - "end\n"); - const auto numericOverload = - std::get(executeModule(numericOverloadModule)); - assert(numericOverload && numericOverload->entries.size() == 2); - assert(std::get(numericOverload->entries[0].second) == -2.302); - assert(std::get(numericOverload->entries[1].second) == -2.302); - static_assert(std::variant_size_v == 10, - "production VM values must remain typed and AST-free"); - // This covers the production frontend: source -> SentencePiece IDs -> - // integer parser -> AST compiler -> verified IR. No AST runtime exists. - const auto program = Felidae::parseProgramFile(FELIDAE_PIPELINE_FIXTURE_PATH); - assert(program.clauses.size() == 1); - assert(program.clauses.front()->head.name == "main"); - // Source spans come from the original SentencePiece offsets. This covers - // the parser's indexed span path: no secondary source tokenization and no - // per-node linear rescan of the encoded stream. - assert(program.clauses.front()->sourceSpan.startLine == 1); - assert(program.clauses.front()->sourceSpan.startColumn == 1); - assert(program.clauses.front()->sourceSpan.endLine >= 3); - assert(program.clauses.front()->body.size() == 2); - assert(program.clauses.front()->body.front()->sourceSpan.startLine == 2); - assert(program.clauses.front()->body.back()->sourceSpan.startLine == 3); - - // Mixfix declarations and uses share one parser-owned registry over the - // same line-wise SentencePiece stream. This must parse even when the - // strict module compiler can lower a uniquely typed implementation into - // the same Call IR used by ordinary function syntax. - const auto mixfixProgram = Felidae::parseProgramText( - "@mixfix(pattern: \"{left: number} combine {right: number}\")\n" - "combineValue() => return left + right\n" - "main() => return 2 combine 3\n"); - assert(mixfixProgram.clauses.size() == 2); - assert(mixfixProgram.clauses.back()->head.name == "main"); - - const auto directMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"{left: number} combine {right: number}\")\n" - "combineValue(left: number, right: number) => return left + right\n" - "main() => return 17 combine 25\n"); - assert(std::get(executeModule(directMixfixModule)) == 42.0); - - const auto thenPipelineModule = Felidae::compileProgramTextToIr( - "increment(value: number) => return value + 1.\n" - "double(value: number) => return value * 2.\n" - "main() =>\n" - " return increment(value: 9)\n" - " then double(value: system.result)\n" - " then increment(value: system.result).\n"); - assert(std::get(executeModule(thenPipelineModule)) == 21.0); - - const auto nestedThenPipelineModule = Felidae::compileProgramTextToIr( - "increment(value: number) => return value + 1\n" - "double(value: number) => return value * 2\n" - "main() => return 10 then increment(value: system.result then " - "double(value: system.result))\n"); - assert(std::get(executeModule(nestedThenPipelineModule)) == 21.0); - - const auto thenAnchorMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"join {left: number} then {right: number}\")\n" - "joinThen(left: number, right: number) => return left + right\n" - "main() => return join 20 then 22\n"); - assert(std::get(executeModule(thenAnchorMixfixModule)) == 42.0); - - const auto nestedConditionalModule = - Felidae::compileProgramTextToIr("classify(value: number) =>\n" - " if value > 10 then\n" - " return 2\n" - " else\n" - " if value > 0 then\n" - " return 1\n" - " else\n" - " return 0\n" - "main() => return classify(value: 5)\n"); - assert(std::get(executeModule(nestedConditionalModule)) == 1.0); - - const auto optionalEndModule = Felidae::compileProgramTextToIr( - "classify(value: number) =>\n" - " if value > 10 then\n" - " return 2.0\n" - " else\n" - " if value > 0 then\n" - " return 1.0\n" - " else\n" - " return 0.0\n" - " end\n" - " end\n" - "end\n" - "main() => return classify(value: -1)\n" - "end\n"); - assert(std::get(executeModule(optionalEndModule)) == 0.0); - - const auto contextualEndMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"wrap {value: number} end\")\n" - "wrapValue(value: number) => return value\n" - "end\n" - "main() => return wrap 42 end\n" - "end\n"); - assert(std::get(executeModule(contextualEndMixfixModule)) == 42.0); - - const auto whereGuardModule = Felidae::compileProgramTextToIr( - "eligible(score: number, active: number) =>\n" - " adjusted := score + 0\n" - " where adjusted >= 70\n" - " observed := active\n" - " where observed == 1.0\n" - " result := adjusted\n" - " return result\n" - "else\n" - " return 0.0\n" - "main() => return (pass: eligible(score: 82, active: 1.0), " - "low: eligible(score: 40, active: 1.0), " - "inactive: eligible(score: 90, active: 0.0))\n"); - const auto whereGuardResult = displayModuleValue( - whereGuardModule, executeModule(whereGuardModule)); - assert(whereGuardResult == "{pass: 82.0, low: 0.0, inactive: 0.0}"); - - const auto factExpressionModule = - Felidae::compileProgramFileToIr(FELIDAE_FACT_EXPRESSION_FIXTURE_PATH); - const auto factExpression = displayModuleValue( - factExpressionModule, executeModule(factExpressionModule)); - assert(factExpression.find("crisp: 1.0") != std::string::npos); - assert(factExpression.find("chance: 0.2") != std::string::npos); - assert(factExpression.find("UnsupportedMode") != std::string::npos); - assert(factExpression.find("category: companion") != std::string::npos); - assert(factExpression.find("field: legs") != std::string::npos); - - // Hierarchy and temporal source intrinsics must survive the complete - // deterministic frontend -> verified executable IR -> register VM path. - // These are compiler tests, not isolated opcode-construction tests. - const auto hierarchyModule = Felidae::compileProgramTextToIr( - "Root(name: \"root\")\n" - "Child extend Root(name: \"child\")\n" - "main() => return isA(left: Child(name: \"child\"), right: Root(name: " - "\"root\"))\n"); - assert(std::get(executeModule(hierarchyModule)) == 1.0); - - const auto queriedHierarchyModule = Felidae::compileProgramTextToIr( - "Animal(name: \"root\")\n" - "Dog extend Animal(name: \"dog\")\n" - "keep(fact: any) => return fact\n" - "main() => return for_each_fact(Animal, keep)\n"); - const auto queriedFacts = - std::get(executeModule(queriedHierarchyModule)); - assert(queriedFacts && queriedFacts->values.size() == 2); - - const auto hierarchyEvidenceModule = Felidae::compileProgramTextToIr( - "Root(name: \"root\")\n" - "Left extend Root(name: \"left\")\n" - "Right extend Root(name: \"right\")\n" - "Diamond extend Left, Right(name: \"diamond\")\n" - "Other extend Root(name: \"other\")\n" - "main() => return ancestorAnalysis(left: Diamond(name: \"diamond\"), " - "right: Other(name: \"other\"))\n" - "end\n"); - const auto hierarchyEvidence = displayModuleValue( - hierarchyEvidenceModule, executeModule(hierarchyEvidenceModule)); - assert(hierarchyEvidence.find( - "leftProofs: [[Diamond, Left, Root], [Diamond, Right, Root]]") != - std::string::npos); - assert(hierarchyEvidence.find("rightProofs: [[Other, Root]]") != - std::string::npos); - assert(hierarchyEvidence.find("leftDistance: 2") != std::string::npos); - assert(hierarchyEvidence.find("rightDistance: 1.0") != std::string::npos); - - const auto temporalModule = Felidae::compileProgramTextToIr( - "Event(name: \"first\", effective_at: 10, priority: 1)\n" - "Event(name: \"second\", effective_at: 20, priority: 2)\n" - "main() => return temporalRank(effectiveAt: effective_at, priority: " - "priority)\n"); - const auto temporalResult = - std::get(executeModule(temporalModule)); - assert(temporalResult && temporalResult->values.size() == 2); - - // Capability examples are production pipeline regressions, not parser-only - // samples. Their ordered alternative proofs must reach safe actions through - // verified IR, with numeric truth values rendered as 0.0/1.0 rather than - // bool. - const auto coffeeReasoningModule = - Felidae::compileProgramFileToIr(FELIDAE_COFFEE_REASONING_FIXTURE_PATH); - const auto coffeeReasoning = displayModuleValue( - coffeeReasoningModule, executeModule(coffeeReasoningModule)); - assert(coffeeReasoning.find("dispense_coffee") != std::string::npos); - assert(coffeeReasoning.find("refund") != std::string::npos); - assert(coffeeReasoning.find("true") == std::string::npos); - assert(coffeeReasoning.find("false") == std::string::npos); - - const auto hvacReasoningModule = - Felidae::compileProgramFileToIr(FELIDAE_HVAC_REASONING_FIXTURE_PATH); - const auto hvacReasoning = displayModuleValue( - hvacReasoningModule, executeModule(hvacReasoningModule)); - assert(hvacReasoning.find("cool") != std::string::npos); - assert(hvacReasoning.find("ventilate") != std::string::npos); - assert(hvacReasoning.find("fault_lockout") != std::string::npos); - assert(hvacReasoning.find("true") == std::string::npos); - assert(hvacReasoning.find("false") == std::string::npos); - - // An unresolved overload must cross the compiler-model boundary exactly - // once. The backend can select only parser-owned vocabulary entries; the - // resulting executable IR is verified, serialized as FELBIR, loaded - // through the binary verifier, and then executed directly by the VM. - // This bounded backend is deliberately not a trained-model - // quality test; it proves that the production routing cannot silently - // bypass the SSM when overload resolution is genuinely ambiguous. - class SelectingCompilerModel final : public Felidae::MixfixStateModel { - public: - std::size_t calls = 0; - - std::vector - transform(std::span input, - const Felidae::MixfixContext &context) override { - assert(!input.empty()); - ++calls; - const auto token = [&](Felidae::MixfixIrTokenKind kind, - Felidae::IrWord value = 0) { - const auto found = std::find_if( - context.outputVocabulary.begin(), context.outputVocabulary.end(), - [&](const auto &candidate) { - return candidate.kind == kind && candidate.value == value; - }); - assert(found != context.outputVocabulary.end()); - return static_cast( - found - context.outputVocabulary.begin()); - }; - // The shell's first symbol is the captured variable and its next - // symbol is the first matching overload. Load the capture, call - // that bounded symbol reference, and return the selected value. - return { - token(Felidae::MixfixIrTokenKind::Accept), - token(Felidae::MixfixIrTokenKind::Opcode, - static_cast(Felidae::IrOpcode::LoadSymbol)), - token(Felidae::MixfixIrTokenKind::Register, 1), - token(Felidae::MixfixIrTokenKind::SymbolReference, 0), - token(Felidae::MixfixIrTokenKind::Opcode, - static_cast(Felidae::IrOpcode::Call)), - token(Felidae::MixfixIrTokenKind::Register, 0), - token(Felidae::MixfixIrTokenKind::SymbolReference, 1), - token(Felidae::MixfixIrTokenKind::Register, 1), - token(Felidae::MixfixIrTokenKind::Register, 1), - token(Felidae::MixfixIrTokenKind::Opcode, - static_cast(Felidae::IrOpcode::Return)), - token(Felidae::MixfixIrTokenKind::Register, 0), - token(Felidae::MixfixIrTokenKind::Register, 0), - token(Felidae::MixfixIrTokenKind::End), - }; - } - } selectingCompilerModel; - Felidae::CompilerOptions selectingOptions; - selectingOptions.mixfixModel = &selectingCompilerModel; - - const auto specificMixfixModule = Felidae::compileProgramTextToIr( - "@overload(operator: chooseSpecific, pattern: \"choose {value}\", " - "type: prefix, captures: {value: any}, result: number)\n" - "chooseAny() => return 1\n" - "@overload(operator: chooseSpecific, pattern: \"choose {value}\", " - "type: prefix, captures: {value: number}, result: number)\n" - "chooseNumber() => return 2\n" - "main() => return choose 42\n", - selectingOptions); - assert(selectingCompilerModel.calls == 0); - assert(std::get(executeModule(specificMixfixModule)) == 2.0); - - bool incompatibleMixfixRejected = false; - try { - (void)Felidae::compileProgramTextToIr( - "@overload(operator: chooseScalar, pattern: \"scalar {value}\", " - "type: prefix, captures: {value: number}, result: number)\n" - "chooseNumber() => return 1\n" - "@overload(operator: chooseScalar, pattern: \"scalar {value}\", " - "type: prefix, captures: {value: string}, result: number)\n" - "chooseString() => return 2\n" - "main() => return scalar [1, 2]\n", - selectingOptions); - } catch (const Felidae::IntegerParserError &) { - incompatibleMixfixRejected = true; - } - assert(incompatibleMixfixRejected); - assert(selectingCompilerModel.calls == 0); - - const auto selectedMixfixModule = - Felidae::compileProgramTextToIr("@overload(\n" - " operator: chooseValue,\n" - " pattern: \"pick {value}\",\n" - " type: prefix,\n" - " captures: {value: number},\n" - " result: number,\n" - " precedence: prefix,\n" - " associativity: right,\n" - " cardinality: one,\n" - " effects: pure,\n" - " visibility: private\n" - ")\n" - "chooseFirst() => return value\n" - "@overload(\n" - " operator: chooseValue,\n" - " pattern: \"pick {value}\",\n" - " type: prefix,\n" - " captures: {value: string},\n" - " result: number,\n" - " precedence: prefix,\n" - " associativity: right,\n" - " cardinality: one,\n" - " effects: pure,\n" - " visibility: private\n" - ")\n" - "chooseSecond() => return 99\n" - "route(value: any) => return pick value\n" - "main() => return route(value: 42)\n", - selectingOptions); - assert(selectingCompilerModel.calls == 1); - const auto selectedMixfixPath = - testOutputDirectory / "felidae_compiler_ssm_pipeline.bin"; - removeTemporary(selectedMixfixPath); - Felidae::writeBinaryIr( - selectedMixfixPath, - Felidae::verifyIrModule(Felidae::IrModule(selectedMixfixModule))); - const auto selectedMixfixBinary = Felidae::loadBinaryIr( - selectedMixfixPath, Felidae::felidaeSentencePieceModelIdentity()); - Felidae::FelidaeKnowledgeRuntime selectedMixfixRuntime; - assert(std::get(Felidae::RegisterVm{}.executeMain( - selectedMixfixBinary, selectedMixfixRuntime)) == 42.0); - removeTemporary(selectedMixfixPath); - - class RejectingCompilerModel final : public Felidae::MixfixStateModel { - public: - std::size_t calls = 0; - std::vector - transform(std::span input, - const Felidae::MixfixContext &context) override { - assert(!input.empty()); - ++calls; - const auto found = std::find_if( - context.outputVocabulary.begin(), context.outputVocabulary.end(), - [](const auto &token) { - return token.kind == Felidae::MixfixIrTokenKind::Reject; - }); - assert(found != context.outputVocabulary.end()); - return {static_cast( - found - context.outputVocabulary.begin())}; - } - } rejectingCompilerModel; - Felidae::CompilerOptions rejectingOptions; - rejectingOptions.mixfixModel = &rejectingCompilerModel; - bool trailingModelRejectionObserved = false; - try { - (void)Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"{value: number} selects\")\n" - "selectNumber(value: number) => return value\n" - "@mixfix(pattern: \"{value: string} selects\")\n" - "selectText(value: string) => return 0\n" - "route(value: any) => return value selects\n" - "main() => return route(value: 42)\n", - rejectingOptions); - } catch (const Felidae::IntegerParserError &) { - trailingModelRejectionObserved = true; - } - assert(trailingModelRejectionObserved); - assert(rejectingCompilerModel.calls == 1); - - // Annotation-declared captures are compiler-local procedure parameters - // when an implementation omits them from its callable head. The runtime - // still sees only an ordinary verified Call with isolated bindings. - const auto implicitMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"{left: number} combine {right: number}\")\n" - "combineValue() => return left + right\n" - "main() => return 2 combine 3\n"); - assert(std::get(executeModule(implicitMixfixModule)) == 5.0); - - // The parser preserves dotted names so qualified calls and `fx.` keys - // remain one SentencePiece-aware spelling. The compiler resolves only a - // scoped `value.depth` spelling into GetField IR; Form never sees AST or - // source syntax. - const auto implicitFactMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"seed {value: number}\")\n" - "seedValue() => return Stage(depth: value)\n" - "@mixfix(pattern: \"advance {value: mixfix} by {amount: number}\")\n" - "advanceValue() => return Stage(depth: value.depth + amount)\n" - "main() => return advance (seed 1) by 2\n"); - const auto implicitFactMixfix = - std::get(executeModule(implicitFactMixfixModule)); - assert(implicitFactMixfix && - std::get(implicitFactMixfix->fields.front().second) == 3.0); - - // `obj` is the established concise spelling of an unconstrained mixfix - // capture. It must reuse Any matching, not introduce a second type path. - const auto objectMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"echo {value: obj}\")\n" - "echoValue(value: expr) => return value\n" - "main() => return echo 17\n"); - assert(std::get(executeModule(objectMixfixModule)) == 17.0); - - // Nested leading and infix mixfix expressions recursively lower to Call - // IR. The values prove capture boundaries are preserved at every depth. - const auto nestedMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"{left: number} blend {right: number}\")\n" - "blend(left: number, right: number) => return left + right\n" - "@mixfix(pattern: \"combine {left: number} with {right: number}\")\n" - "combine(left: number, right: number) => return left * right\n" - "@mixfix(pattern: \"scale {value: number} by {factor: number}\")\n" - "scale(value: number, factor: number) => return value * factor\n" - "@mixfix(pattern: \"offset {value: number} by {amount: number}\")\n" - "offset(value: number, amount: number) => return value + amount\n" - "main() =>\n" - "leaf := 4 blend 5\n" - "branch := combine (1 blend 2) with (3 blend leaf)\n" - "deep := scale (combine branch with (offset (2 blend 3) by (1 blend 1))) " - "by (2 blend 1)\n" - "return (leaf: leaf, branch: branch, deep: deep)\n"); - const auto nestedMixfixResult = - std::get(executeModule(nestedMixfixModule)); - assert(nestedMixfixResult && nestedMixfixResult->entries.size() == 3); - assert(std::get(nestedMixfixResult->entries[0].second) == 9.0); - assert(std::get(nestedMixfixResult->entries[1].second) == 36.0); - assert(std::get(nestedMixfixResult->entries[2].second) == 756.0); - - // `expr` is a structural mixfix capture: it accepts literals, facts, - // variables, and nested mixfix values without weakening typed captures. - const auto typedNestedMixfixModule = Felidae::compileProgramTextToIr( - "@mixfix(pattern: \"reason {subject: expr} using {evidence: Evidence} " - "within {context: Context}\")\n" - "reasonFactValue() => return Explanation(subject: subject, evidence: " - "evidence, context: context)\n" - "@mixfix(pattern: \"validate {claim: expr} with {expected: string}\")\n" - "validateReasonValue() => return Validation(claim: claim, expected: " - "expected)\n" - "main() =>\n" - "evidence := Evidence(kind: \"observed\")\n" - "context := Context(domain: \"animal-behaviour\")\n" - "claim := reason \"tiger\" using evidence within context\n" - "direct := validate (reason \"cat\" using evidence within context) with " - "\"explanation\"\n" - "return (bound: claim, direct: direct)\n"); - const auto typedNestedMixfixResult = - std::get(executeModule(typedNestedMixfixModule)); - assert(typedNestedMixfixResult && - typedNestedMixfixResult->entries.size() == 2); - assert(std::holds_alternative( - typedNestedMixfixResult->entries[0].second)); - assert(std::holds_alternative( - typedNestedMixfixResult->entries[1].second)); - - // @overload uses the same annotation-capture binding path. Nested core - // expressions remain deterministic and no parser detail reaches Form. - const auto overloadModule = Felidae::compileProgramTextToIr( - "@overload(operator: transformWith, pattern: \"{value} transform {model} " - "with {count}\", " - "type: mixfix, captures: {value: number, model: number, count: number}, " - "result: number)\n" - "transformValue() => return value + model * count\n" - "main() =>\n" - "result := 2 transform 3 with 4\n" - "nested := (1 + 1) transform (2 + 1) with 2\n" - "return (result: result, nested: nested)\n"); - const auto overloadResult = - std::get(executeModule(overloadModule)); - assert(std::get(overloadResult->entries[0].second) == 14.0); - assert(std::get(overloadResult->entries[1].second) == 8.0); - - // Capitalized named terms are primary fact values even without an - // explicit schema declaration. They remain typed facts after a binary - // round-trip rather than being mis-lowered as an unknown call. - const auto adHocFactModule = Felidae::compileProgramTextToIr( - "main() => return Plan(name: \"procedure\", enabled: 1.0)\n"); - const auto adHocFact = - std::get(executeModule(adHocFactModule)); - assert(adHocFact && adHocFact->fields.size() == 2); - - // The public execution path is parser -> verified IR -> register VM. - // This test deliberately does not construct Interpreter or a legacy - // runtime, so a passing pipeline cannot hide an AST execution fallback. - const auto module = - Felidae::compileProgramFileToIr(FELIDAE_PIPELINE_FIXTURE_PATH); - // IrVerifier decodes instruction boundaries. Do not scan raw words for - // opcode values: legal registers, constants, and symbols may share a - // numeric value with an opcode. - Felidae::IrVerifier::verify(module.ir); - const auto verifiedModule = - Felidae::verifyIrModule(Felidae::IrModule(module)); - Felidae::RegisterVm vm; - Felidae::FelidaeKnowledgeRuntime moduleRuntime; - const auto vmResult = vm.executeMain(verifiedModule, moduleRuntime); - assert(Felidae::vmValueToDisplayString( - vmResult, Felidae::makeIrDisplayContext(verifiedModule, - display.textDecoder)) == - "{answer: 42}"); - - // The serialized artifact is executable in a fresh module/runtime path: - // loader verification occurs before RegisterVm sees any instruction. - const auto binaryPath = - testOutputDirectory / "felidae_pipeline_roundtrip.bin"; - Felidae::writeBinaryIr(binaryPath, verifiedModule); - const auto loadedModule = Felidae::loadBinaryIr( - binaryPath, Felidae::felidaeSentencePieceModelIdentity()); - Felidae::FelidaeKnowledgeRuntime loadedRuntime; - const auto textDecoder = [](std::span pieces) { - std::vector ids(pieces.begin(), pieces.end()); - std::string text; - assert(Felidae::felidaeSentencePieceModel().Decode(ids, &text).ok()); - return text; - }; - const auto binaryDisplay = - Felidae::makeIrDisplayContext(loadedModule, textDecoder); - assert(Felidae::vmValueToDisplayString( - vm.executeMain(loadedModule, loadedRuntime), binaryDisplay) == - "{answer: 42}"); - const auto malformedPath = testOutputDirectory / "felidae_pipeline_bad.bin"; - { - std::ofstream bad(malformedPath, std::ios::binary | std::ios::trunc); - bad << "not a felidae IR"; - } - bool malformedRejected = false; - try { - (void)Felidae::loadBinaryIr(malformedPath, - Felidae::felidaeSentencePieceModelIdentity()); - } catch (const Felidae::IrError &) { - malformedRejected = true; - } - assert(malformedRejected); - const auto expectRejectedCopy = [&](const char *suffix, const auto &mutate) { - auto candidate = testOutputDirectory / - (std::string("felidae_pipeline_") + suffix + ".bin"); - std::filesystem::copy_file( - binaryPath, candidate, - std::filesystem::copy_options::overwrite_existing); - mutate(candidate); - bool rejected = false; - try { - (void)Felidae::loadBinaryIr(candidate, - Felidae::felidaeSentencePieceModelIdentity()); - } catch (const Felidae::IrError &) { - rejected = true; - } - removeTemporary(candidate); - assert(rejected); - }; - expectRejectedCopy("bad_version", [](const auto &candidate) { - std::fstream file(candidate, - std::ios::binary | std::ios::in | std::ios::out); - file.seekp(8); - const std::array version{2, 0, 0, 0}; - file.write(version.data(), version.size()); - }); - expectRejectedCopy("bad_endian", [](const auto &candidate) { - std::fstream file(candidate, - std::ios::binary | std::ios::in | std::ios::out); - file.seekp(12); - const std::array endian{}; - file.write(endian.data(), endian.size()); - }); - expectRejectedCopy("truncated", [](const auto &candidate) { - std::filesystem::resize_file(candidate, 20); - }); - removeTemporary(binaryPath); - removeTemporary(malformedPath); - - // Primitive normal syntax is directly lowered from the integer parser to - // canonical IR and evaluated by the register VM, without Interpreter. - Felidae::IntegerTokenList expressionInput( - Felidae::felidaeSentencePieceModel(), "6 * 7"); - Felidae::IntegerParser expressionParser(expressionInput); - const auto expressionIr = expressionParser.compileExpressionIr(); - class NoRuntime final : public Felidae::VmRuntime { - public: - void installIrModule(const Felidae::IrModule &) override {} - Felidae::IrSymbolRef - resolveSymbol(Felidae::IrSymbolRef symbol) const override { - return symbol; - } - Felidae::VmValue loadSymbol(Felidae::IrSymbolRef symbol) override { - return symbols.at(symbol); - } - void storeSymbol(Felidae::IrSymbolRef symbol, - const Felidae::VmValue &value) override { - symbols[symbol] = value; - } - Felidae::VmFactPtr - retainFact(const Felidae::VmFactPtr &fact) override { - return fact; - } - Felidae::VmFactPtr mutateFact(const Felidae::VmFactPtr &fact, - Felidae::IrSymbolRef field, - const Felidae::VmValue &value) override { - if (!fact) - throw Felidae::IrError("test mutation requires a fact"); - auto updated = std::make_shared(*fact); - const auto found = - std::find_if(updated->fields.begin(), updated->fields.end(), - [&](const auto &entry) { return entry.first == field; }); - if (found == updated->fields.end()) - updated->fields.emplace_back(field, value); - else - found->second = value; - return updated; - } - std::unordered_map symbols; - } noRuntime; - Felidae::RegisterVm nativeVm; - assert(std::get(executeIrDirect(expressionIr, noRuntime)) == 42.0); - Felidae::IntegerParser astExpressionParser(expressionInput); - const auto astExpression = astExpressionParser.parseExpressionText(); - const auto astExpressionIr = - Felidae::IrCodeGenerator::lowerExpression(astExpression); - assert(std::get(executeIrDirect(astExpressionIr, noRuntime)) == 42.0); - const auto bindingProgram = Felidae::parseProgramText("answer := 6 * 7."); - assert(bindingProgram.globals.size() == 1); - const auto bindingIr = Felidae::IrCodeGenerator::lowerGlobalBinding( - *bindingProgram.globals.front()); - assert(std::get(executeIrDirect(bindingIr, noRuntime)) == 42.0); - assert(std::get( - noRuntime.symbols.at(Felidae::symbolIdForName("answer"))) == 42.0); - const auto entryProgram = - Felidae::parseProgramText("main() => return (answer: 42)."); - assert(entryProgram.clauses.size() == 1); - const auto entryIr = Felidae::IrCodeGenerator::lowerEntryMethod( - *entryProgram.clauses.front()); - const auto entryResult = - std::get(executeIrDirect(entryIr, noRuntime)); - assert(entryResult && entryResult->entries.size() == 1); - assert(std::get(entryResult->entries.front().second) == 42.0); - auto directFact = - std::make_shared(std::vector{ - Felidae::MapEntry{"age", std::make_shared(4.0)}, - }); - directFact->factType = "Cat"; - const auto directFactIr = - Felidae::IrCodeGenerator::lowerExpression(directFact); - const auto directFactValue = executeIrDirect(directFactIr, noRuntime); - const auto directFactResult = std::get(directFactValue); - assert(directFactResult && - directFactResult->type == Felidae::symbolIdForName("Cat")); - assert(directFactResult->fields.size() == 1 && - directFactResult->fields.front().first == - Felidae::symbolIdForName("age")); - assert(std::get(directFactResult->fields.front().second) == 4.0); - const auto directModule = - Felidae::compileProgramTextToIr("main() => return (answer: 42)."); - Felidae::IrVerifier::verify(directModule.ir); - Felidae::FelidaeKnowledgeRuntime directRuntime; - const auto directResult = executeModuleDirect(directModule, directRuntime); - const auto directMap = std::get(directResult); - assert(directMap && - std::get(directMap->entries.front().second) == 42.0); - assert(displayModuleValue(directModule, directResult) == "{answer: 42}"); - - // Logical operands are control flow, not eager arithmetic. These calls - // would divide by zero if the right operand were emitted before its - // guarding branch. - const auto shortCircuitModule = Felidae::compileProgramTextToIr( - "explode(divisor: number) => return 1 / divisor.\n" - "main() => return (both: 0.0 and explode(divisor: 0), " - "either: 1.0 or explode(divisor: 0)).\n"); - Felidae::FelidaeKnowledgeRuntime shortCircuitRuntime; - const auto shortCircuitResult = - executeModuleDirect(shortCircuitModule, shortCircuitRuntime); - assert(displayModuleValue(shortCircuitModule, shortCircuitResult) == - "{both: 0.0, either: 1.0}"); - - // Repeated fact predicates are rows of one type, not duplicate procedure - // declarations. They enter the runtime through the initializer's typed - // MakeFact operations and QueryFacts invokes a deterministic callback. - const auto repeatedFactsModule = Felidae::compileProgramTextToIr( - "Color(value: \"red\").\n" - "Color(value: \"blue\").\n" - "colorValue(color: Color) => return color.value.\n" - "main() => return for_each_fact(Color, colorValue).\n"); - assert(repeatedFactsModule.factTypes.size() == 1); - Felidae::FelidaeKnowledgeRuntime repeatedFactsRuntime; - const auto repeatedFactsResult = - executeModuleDirect(repeatedFactsModule, repeatedFactsRuntime); - assert(displayModuleValue(repeatedFactsModule, repeatedFactsResult) == - "[red, blue]"); - - const auto concreteFactQueryModule = Felidae::compileProgramTextToIr( - "School(name: \"North\", city: \"BLR\", active: 1.0)\n" - "School(name: \"West\", city: \"MYS\", active: 0.0)\n" - "School(name: \"Lake\", city: \"BLR\", active: 1.0)\n" - "main() =>\n" - " selected := School.where(city: \"BLR\", active: 1.0)\n" - " return (all: School.all(), selected: selected, " - "all_count: School.count(), selected_count: count(data: selected))\n" - "end\n"); - Felidae::FelidaeKnowledgeRuntime concreteFactQueryRuntime; - const auto concreteFactQueryResult = displayModuleValue( - concreteFactQueryModule, - executeModuleDirect(concreteFactQueryModule, concreteFactQueryRuntime)); - assert(concreteFactQueryResult.find("all_count: 3.0") != std::string::npos); - assert(concreteFactQueryResult.find("selected_count: 2.0") != - std::string::npos); - assert(concreteFactQueryResult.find("North") != std::string::npos); - assert(concreteFactQueryResult.find("Lake") != std::string::npos); - assert(concreteFactQueryResult.find("West") != std::string::npos); - - const auto factDmlModule = Felidae::compileProgramTextToIr( - "School(id: 1, name: \"North\", city: \"BLR\", students: 420, active: 1.0)\n" - "School(id: 2, name: \"West\", city: \"MYS\", students: 280, active: 0.0)\n" - "School(id: 3, name: \"Lake\", city: \"BLR\", students: 350, active: 1.0)\n" - "Teacher(name: \"Ada\", school_id: 1)\n" - "Teacher(name: \"Lin\", school_id: 1)\n" - "Teacher(name: \"Grace\", school_id: 9)\n" - "main() =>\n" - " limited := School.where(active: 1.0).AndWhere(city: \"BLR\").limit(records: 1)\n" - " all_limited := School.all().limit(records: 2)\n" - " alternatives := School.where(city: \"MYS\").OrWhere(name: \"Lake\")\n" - " projected := School.select(fields: [\"name\", \"city\"], match: {active: 1.0})\n" - " projected_limited := School.select(fields: [\"name\"], match: {active: 1.0}).limit(records: 1)\n" - " inner_joined := School.join(type: Teacher, left: \"id\", right: \"school_id\")\n" - " joined := School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"left\")\n" - " right_joined := School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"right\")\n" - " outer_joined := School.join(type: Teacher, left: \"id\", right: \"school_id\", kind: \"outer\")\n" - " joined_limited := School.join(type: Teacher, left: \"id\", right: \"school_id\").limit(records: 2)\n" - " none := School.all().limit(records: 0)\n" - " inserted := School.insert(values: {id: 4, name: \"Hill\", city: \"BLR\", students: 100, active: 1.0})\n" - " updated := School.where(id: 2).AndWhere(city: \"MYS\").update(values: {active: 1.0})\n" - " deleted := School.where(id: 3).delete()\n" - " return (limited: count(data: limited), all_limited: count(data: all_limited), alternatives: count(data: alternatives), " - "projected: projected, projected_limited: count(data: projected_limited), inner_joined: count(data: inner_joined), joined: count(data: joined), " - "right_joined: count(data: right_joined), outer_joined: count(data: outer_joined), " - "joined_limited: count(data: joined_limited), none: count(data: none), inserted: inserted, " - "updated: count(data: updated), deleted: deleted, remaining: School.count(), " - "total: School.sum(field: \"students\"), average: School.average(field: \"students\"))\n" - "end\n"); - bool usesIndexedWhere = false; - for (const auto &[_, procedure] : factDmlModule.procedures) { - for (std::size_t pc = 0; pc < procedure.ir.words.size(); - pc += Felidae::irInstructionWidth(procedure.ir, pc)) { - usesIndexedWhere = - usesIndexedWhere || - procedure.ir.words[pc] == - static_cast(Felidae::IrOpcode::FactWhere); - } - } - assert(usesIndexedWhere); - Felidae::FelidaeKnowledgeRuntime factDmlRuntime; - const auto factDmlResult = displayModuleValue( - factDmlModule, executeModuleDirect(factDmlModule, factDmlRuntime)); - assert(factDmlResult.find("limited: 1.0") != std::string::npos); - assert(factDmlResult.find("all_limited: 2") != std::string::npos); - assert(factDmlResult.find("alternatives: 2") != std::string::npos); - assert(factDmlResult.find("projected_limited: 1.0") != std::string::npos); - assert(factDmlResult.find("inner_joined: 2") != std::string::npos); - assert(factDmlResult.find("joined: 4") != std::string::npos); - assert(factDmlResult.find("right_joined: 3") != std::string::npos); - assert(factDmlResult.find("outer_joined: 5") != std::string::npos); - assert(factDmlResult.find("joined_limited: 2") != std::string::npos); - assert(factDmlResult.find("none: 0.0") != std::string::npos); - assert(factDmlResult.find("updated: 1.0") != std::string::npos); - assert(factDmlResult.find("deleted: 1.0") != std::string::npos); - assert(factDmlResult.find("remaining: 3") != std::string::npos); - assert(factDmlResult.find("total: 800") != std::string::npos); - - // A fact-only .fx import is compile-time DDL. Its rows enter ordinary - // MakeFact IR with source ownership, so the existing DML transactions - // persist them without a runtime source parser or public db.sync call. - const auto ownedDatabase = testOutputDirectory / "owned-schools.fx"; - const auto ownedProgram = testOutputDirectory / "owned-schools-main.fx"; - { - std::ofstream out(ownedDatabase, std::ios::trunc); - out << "Entity(id: 0, name: \"root\", students: 0)\n" - "School extend Entity(id: 1, name: \"North\", students: 420)\n" - "School extend Entity(id: 2, name: \"West\", students: 280)\n"; - } - { - std::ofstream out(ownedProgram, std::ios::trunc); - out << "import \"owned-schools.fx\"\n" - "main() =>\n" - " updated := School.where(id: 1).update(values: {students: 425})\n" - " inserted := School.insert(values: {id: 3, name: \"Hill\", students: 100})\n" - " deleted := School.where(id: 2).delete()\n" - " return (updated: count(data: updated), inserted: inserted, deleted: deleted, remaining: School.count())\n" - "end\n"; - } - const auto ownedModule = Felidae::compileProgramFileToIr(ownedProgram); - Felidae::IrWord ownedSource = 0; - std::size_t ownedFactCount = 0; - for (std::size_t pc = 0; pc < ownedModule.ir.words.size(); - pc += Felidae::irInstructionWidth(ownedModule.ir, pc)) { - if (ownedModule.ir.words[pc] == - static_cast(Felidae::IrOpcode::MakeFact) && - ownedModule.ir.words[pc + 3] != 0) { - if (ownedSource == 0) - ownedSource = ownedModule.ir.words[pc + 3]; - assert(ownedModule.ir.words[pc + 3] == ownedSource); - ++ownedFactCount; - } - } - assert(ownedFactCount == 3); - Felidae::FelidaeKnowledgeRuntime ownedRuntime( - nullptr, 1024, 256, {}, nullptr, display.textDecoder, textEncoder); - const auto ownedResult = displayModuleValue( - ownedModule, executeModuleDirect(ownedModule, ownedRuntime)); - assert(ownedResult.find("updated: 1.0") != std::string::npos); - assert(ownedResult.find("deleted: 1.0") != std::string::npos); - assert(ownedResult.find("remaining: 2") != std::string::npos); - const auto persistedDatabase = Felidae::readSourceFile(ownedDatabase); - assert(persistedDatabase.find("students: 425.0") != std::string::npos); - assert(persistedDatabase.find("Hill") != std::string::npos); - assert(persistedDatabase.find("West") == std::string::npos); - assert(persistedDatabase.find("School extend Entity") != std::string::npos); - // The transaction writer's .fx output remains valid compiler input and - // retains hierarchy assignability after a fresh compile/runtime boundary. - { - std::ofstream out(ownedProgram, std::ios::trunc); - out << "import \"owned-schools.fx\"\n" - "main() => return (entities: Entity.count(), schools: School.count())\n" - "end\n"; - } - const auto reloadedModule = Felidae::compileProgramFileToIr(ownedProgram); - Felidae::FelidaeKnowledgeRuntime reloadedRuntime( - nullptr, 1024, 256, {}, nullptr, display.textDecoder, textEncoder); - const auto reloadedResult = displayModuleValue( - reloadedModule, executeModuleDirect(reloadedModule, reloadedRuntime)); - assert(reloadedResult == "{entities: 3, schools: 2}"); - - const auto invalidDatabase = testOutputDirectory / "invalid-database.fx"; - const auto invalidProgram = testOutputDirectory / "invalid-database-main.fx"; - { - std::ofstream out(invalidDatabase, std::ios::trunc); - out << "helper() => return 1\nend\n"; - } - { - std::ofstream out(invalidProgram, std::ios::trunc); - out << "import \"invalid-database.fx\"\nmain() => return 0.0\nend\n"; - } - bool nonFactDatabaseRejected = false; - try { - (void)Felidae::compileProgramFileToIr(invalidProgram); - } catch (const Felidae::IntegerParserError &) { - nonFactDatabaseRejected = true; - } - assert(nonFactDatabaseRejected); - - const auto cyclicA = testOutputDirectory / "cyclic-a.fx"; - const auto cyclicB = testOutputDirectory / "cyclic-b.fx"; - { - std::ofstream out(cyclicA, std::ios::trunc); - out << "import \"cyclic-b.fx\"\nA(id: 1)\n"; - } - { - std::ofstream out(cyclicB, std::ios::trunc); - out << "import \"cyclic-a.fx\"\nB(id: 1)\n"; - } - { - std::ofstream out(invalidProgram, std::ios::trunc); - out << "import \"cyclic-a.fx\"\nmain() => return 0.0\nend\n"; - } - bool cyclicDatabaseRejected = false; - try { - (void)Felidae::compileProgramFileToIr(invalidProgram); - } catch (const Felidae::IntegerParserError &) { - cyclicDatabaseRejected = true; - } - assert(cyclicDatabaseRejected); - - removeTemporary(ownedProgram); - removeTemporary(ownedDatabase); - removeTemporary(ownedDatabase.string() + ".lock"); - removeTemporary(invalidProgram); - removeTemporary(invalidDatabase); - removeTemporary(cyclicA); - removeTemporary(cyclicB); - - // Mutations are intentionally conditional: a direct type-wide update or - // delete is rejected before IR generation. Joins likewise require both - // key fields, preventing an accidental Cartesian operation. - const auto rejectsFactSource = [](std::string_view source) { - try { - (void)Felidae::compileProgramTextToIr(std::string(source)); - return false; - } catch (const Felidae::IntegerParserError &) { - return true; - } - }; - assert(rejectsFactSource( - "School(id: 1)\n" - "main() => return School.update(values: {id: 2})\nend\n")); - assert(rejectsFactSource( - "School(id: 1)\n" - "main() => return School.delete()\nend\n")); - assert(rejectsFactSource( - "School(id: 1)\nTeacher(school_id: 1)\n" - "main() => return School.join(type: Teacher)\nend\n")); - assert(rejectsFactSource( - "School(id: 1)\nTeacher(school_id: 1)\n" - "main() => return School.join(type: Teacher, left: \"id\", " - "right: \"school_id\", kind: \"cross\")\nend\n")); - assert(rejectsFactSource( - "School(id: 1)\nTeacher(school_id: 1)\n" - "main() => return School.leftJoin(type: Teacher, left: \"id\", " - "right: \"school_id\")\nend\n")); - - const auto rejectsLimitAtRuntime = [](std::string records) { - const auto module = Felidae::compileProgramTextToIr( - "School(id: 1)\nmain() => return School.all().limit(records: " + - records + ")\nend\n"); - Felidae::FelidaeKnowledgeRuntime runtime; - try { - (void)executeModuleDirect(module, runtime); - return false; - } catch (const Felidae::IrError &) { - return true; - } - }; - assert(rejectsLimitAtRuntime("-1")); - assert(rejectsLimitAtRuntime("1.5")); - - const auto factSearchModule = Felidae::compileProgramTextToIr( - "Publication(name: \"\")\n" - "Book extend Publication(name: \"\")\n" - "Magazine extend Publication(name: \"\")\n" - "Catalog(title: \"Alpha Guide\", confidence: 0.82, category: Book)\n" - "Catalog(title: \"beta guide\", confidence: 0.74, category: Magazine)\n" - "Catalog(title: \"Reference\", confidence: 0.40, category: Publication)\n" - "Catalog(title: \"Outlier\", confidence: -212.421, category: Publication)\n" - "Catalog(title: \"Strong\", confidence: 89.024, category: Publication)\n" - "main() =>\n" - " exact := Catalog.search(field: \"title\", query: \"alpha guide\", type: \"exact\", case: \"insensitive\")\n" - " liked := Catalog.search(field: \"title\", query: \"%guide\", type: \"like\", case: \"insensitive\")\n" - " regexed := Catalog.search(field: \"title\", query: \"^[ab].*guide$\", type: \"regex\", case: \"insensitive\")\n" - " descendants := Catalog.search(field: \"category\", query: Publication, type: \"hierarchy\", direction: \"descendants\", includeSelf: 0.0)\n" - " ranged := Catalog.search(field: \"confidence\", type: \"degree\", minimum: 0.70, maximum: 0.90)\n" - " close := Catalog.search(field: \"confidence\", query: 0.80, tolerance: 0.08, type: \"degree\")\n" - " unrestricted := Catalog.search(field: \"confidence\", type: \"degree\", minimum: -300, maximum: -200)\n" - " large := Catalog.search(field: \"confidence\", query: 90, tolerance: 1.0, type: \"degree\")\n" - " return (exact: count(data: exact), liked: count(data: liked), regexed: count(data: regexed), descendants: count(data: descendants), ranged: count(data: ranged), close: count(data: close), unrestricted: count(data: unrestricted), large: count(data: large))\n" - "end\n"); - Felidae::FelidaeKnowledgeRuntime factSearchRuntime; - const auto factSearchResult = displayModuleValue( - factSearchModule, - executeModuleDirect(factSearchModule, factSearchRuntime)); - assert(factSearchResult == - "{exact: 1.0, liked: 2, regexed: 2, descendants: 2, ranged: 2, close: 2, unrestricted: 1.0, large: 1.0}"); - - const auto repeatedFieldsModule = Felidae::compileProgramTextToIr( - "Color(value: \"red\", tag: \"warm\", tag: \"primary\").\n" - "Color(value: \"blue\", tag: \"cool\", tag: \"primary\").\n" - "colorTags(color: Color) => return color.tag.\n" - "main() => return for_each_fact(Color, colorTags).\n"); - Felidae::FelidaeKnowledgeRuntime repeatedFieldsRuntime; - assert(displayModuleValue(repeatedFieldsModule, - executeModuleDirect(repeatedFieldsModule, - repeatedFieldsRuntime)) == - "[[warm, primary], [cool, primary]]"); - - // Classes are compiler-only schemas over the existing fact type table. - // Both the class and its nested methods require explicit end boundaries; - // RegisterVm still receives only ordinary fact/procedure IR. - const auto classModule = Felidae::compileProgramTextToIr( - "class Animal\n" - " name: string\n" - " index(name)\n" - "end\n" - "class Human extend Animal\n" - " age: number\n" - " index(name, age)\n" - " eligible(minimumAge: number) =>\n" - " where age >= minimumAge\n" - " return 1.0\n" - " else\n" - " return 0.0\n" - " end\n" - "end\n" - "Human(name: \"Ada\", age: 32)\n" - "main() => return Human.all()\n" - "end\n"); - Felidae::FelidaeKnowledgeRuntime classRuntime; - assert(displayModuleValue(classModule, - executeModuleDirect(classModule, classRuntime)) == - "[{name: Ada, age: 32}]"); - - // Multiple inheritance is retained in the ordinary type table, and a - // class method is an ordinary lowered procedure with an explicit `self` - // argument. This exercises the method body instead of merely accepting its - // declaration. - const auto classMethodModule = Felidae::compileProgramTextToIr( - "class Named\n" - " name: string\n" - "end\n" - "class Active\n" - " active: number\n" - "end\n" - "class Student extend Named, Active\n" - " score: number\n" - " passes(minimum: number) =>\n" - " where active == 1.0 and score >= minimum\n" - " return score\n" - " else\n" - " return 0.0\n" - " end\n" - "end\n" - "Student(name: \"Ada\", active: 1.0, score: 82)\n" - "main() =>\n" - " rows := Student.all()\n" - " student := array.get(data: rows, position: 0)\n" - " return Student.passes(self: student, minimum: 70)\n" - "end\n"); - Felidae::FelidaeKnowledgeRuntime classMethodRuntime; - assert(std::get(Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(Felidae::IrModule(classMethodModule)), - classMethodRuntime)) == 82.0); - - // Classes and legacy fact declarations occupy one fact-type hierarchy. - // Every direction is legal: fact->fact, fact->class, class->fact, and - // class->class. Classes remain compiler schemas rather than a parallel - // runtime hierarchy. - const auto mixedHierarchyModule = Felidae::compileProgramTextToIr( - "FactBase(id: 0)\n" - "FactChild extend FactBase(id: 1)\n" - "class ClassFromFact extend FactBase\n" - " name: string\n" - "end\n" - "class ClassChild extend ClassFromFact\n" - " score: number\n" - "end\n" - "FactFromClass extend ClassFromFact(name: \"row\")\n" - "main() =>\n" - " fact_fact := isA(left: FactChild(id: 2), right: FactBase(id: 0))\n" - " class_fact := isA(left: ClassFromFact(name: \"a\"), right: FactBase(id: 0))\n" - " class_class := isA(left: ClassChild(name: \"b\", score: 4.2), right: ClassFromFact(name: \"a\"))\n" - " fact_class := isA(left: FactFromClass(name: \"row\"), right: ClassFromFact(name: \"a\"))\n" - " return [fact_fact, class_fact, class_class, fact_class]\n" - "end\n"); - Felidae::FelidaeKnowledgeRuntime mixedHierarchyRuntime; - assert(displayModuleValue( - mixedHierarchyModule, - executeModuleDirect(mixedHierarchyModule, - mixedHierarchyRuntime)) == - "[1.0, 1.0, 1.0, 1.0]"); - - // Mixfix relationship methods return ordinary Association facts. No - // relationship-only runtime representation or compare builtin is involved. - const auto associationModule = Felidae::compileProgramTextToIr( - "Person(name: \"Ada\")\n" - "Company(name: \"Felidae\")\n" - "@mixfix(pattern: \"{left: Person} works at {right: Company}\")\n" - "worksAt() =>\n" - " return Association(left: left, right: right, relation: \"works at\", strength: 3.421)\n" - "end\n" - "main() =>\n" - " people := Person.all()\n" - " companies := Company.all()\n" - " person := array.get(data: people, position: 0)\n" - " company := array.get(data: companies, position: 0)\n" - " return person works at company\n" - "end\n"); - Felidae::FelidaeKnowledgeRuntime associationRuntime; - assert(displayModuleValue( - associationModule, - executeModuleDirect(associationModule, associationRuntime)) == - "{left: {name: Ada}, right: {name: Felidae}, relation: works at, " - "strength: 3.421}"); - - // Real source semantic intrinsic -> structured compiler IR - // operation ID -> typed runtime-model result. No tokenizer or symbol ID - // crosses the semantic execution boundary. - const auto semanticModule = Felidae::compileProgramTextToIr( - "main() => return semantic_identity(42).\n"); - const auto semanticIr = - Felidae::verifyIrModule(Felidae::IrModule(semanticModule)); - assert(Felidae::containsRuntimeSemanticOperation(semanticIr)); - class IdentityRuntimeModel final : public Felidae::RuntimeStateModel { - public: - Felidae::VmValue evaluate(const Felidae::RuntimeOperation &operation, - std::span inputs, - Felidae::RuntimeContext &) override { - assert(operation.id == static_cast( - Felidae::SemanticOperationId::Identity)); - assert(inputs.size() == 1); - return inputs.front(); - } - } identityModel; - Felidae::FelidaeKnowledgeRuntime semanticRuntime(&identityModel); - assert(std::get(Felidae::RegisterVm{}.executeMain( - semanticIr, semanticRuntime)) == 42.0); - - const auto suggestModule = Felidae::compileProgramTextToIr( - "Candidate(name: \"Mammal\")\n" - "main() => return ssm.suggest(input: Candidate.all())\n" - "end\n"); - class SuggestRuntimeModel final : public Felidae::RuntimeStateModel { - public: - explicit SuggestRuntimeModel(double score) : score_(score) {} - - Felidae::VmValue evaluate(const Felidae::RuntimeOperation &operation, - std::span inputs, - Felidae::RuntimeContext &) override { - assert(operation.id == static_cast( - Felidae::SemanticOperationId::Suggest)); - assert(inputs.size() == 1); - return score_; - } - private: - double score_; - } suggestModel(-212.421); - Felidae::FelidaeKnowledgeRuntime suggestRuntime(&suggestModel); - assert(std::get(Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(Felidae::IrModule(suggestModule)), - suggestRuntime)) == -212.421); - SuggestRuntimeModel largeSuggestModel(89.024); - Felidae::FelidaeKnowledgeRuntime largeSuggestRuntime(&largeSuggestModel); - assert(std::get(Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(Felidae::IrModule(suggestModule)), - largeSuggestRuntime)) == 89.024); - const auto thresholdModule = Felidae::compileProgramTextToIr( - "Candidate(name: \"Mammal\")\n" - "main() =>\n" - " score := ssm.suggest(input: Candidate.all())\n" - " where score >= 4.5\n" - " return score\n" - "else\n" - " return 0.0\n" - "end\n"); - assert(std::get(Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(Felidae::IrModule(thresholdModule)), - largeSuggestRuntime)) == 89.024); - Felidae::FelidaeKnowledgeRuntime negativeThresholdRuntime(&suggestModel); - assert(std::get(Felidae::RegisterVm{}.executeMain( - Felidae::verifyIrModule(Felidae::IrModule(thresholdModule)), - negativeThresholdRuntime)) == 0.0); - const auto executeBinaryModule = [&](const Felidae::IrModule &candidate) { - const auto path = - testOutputDirectory / "felidae_pipeline_feature_roundtrip.bin"; - try { - Felidae::writeBinaryIr( - path, Felidae::verifyIrModule(Felidae::IrModule(candidate))); - const auto loaded = Felidae::loadBinaryIr( - path, Felidae::felidaeSentencePieceModelIdentity()); - Felidae::FelidaeKnowledgeRuntime runtime; - const auto result = nativeVm.executeMain(loaded, runtime); - std::filesystem::remove(path); - return Felidae::vmValueToDisplayString( - result, Felidae::makeIrDisplayContext(loaded, display.textDecoder)); - } catch (...) { - std::filesystem::remove(path); - throw; - } - }; - assert(executeBinaryModule(directModule) == "{answer: 42}"); - const auto globalsModule = Felidae::compileProgramTextToIr( - "answer := 6 * 7.\nmain() => return (answer: answer)."); - Felidae::IrVerifier::verify(globalsModule.ir); - Felidae::FelidaeKnowledgeRuntime globalsRuntime; - const auto globalsResult = executeModuleDirect(globalsModule, globalsRuntime); - assert(displayModuleValue(globalsModule, globalsResult) == "{answer: 42}"); - assert(executeBinaryModule(globalsModule) == "{answer: 42}"); - const auto textGlobalsModule = Felidae::compileProgramTextToIr( - "label := \"meow\".\nmain() => return (label: label)."); - Felidae::FelidaeKnowledgeRuntime textGlobalsRuntime; - const auto textGlobalsResult = - executeModuleDirect(textGlobalsModule, textGlobalsRuntime); - assert(displayModuleValue(textGlobalsModule, textGlobalsResult) == - "{label: meow}"); - assert(executeBinaryModule(textGlobalsModule) == "{label: meow}"); - const auto conditionalModule = Felidae::compileProgramTextToIr( - "main() =>\nif 3 > 2 then\nreturn (result: \"yes\")\nelse\nreturn " - "(result: \"no\")."); - Felidae::IrVerifier::verify(conditionalModule.ir); - Felidae::FelidaeKnowledgeRuntime conditionalRuntime; - const auto conditionalResult = - executeModuleDirect(conditionalModule, conditionalRuntime); - assert(displayModuleValue(conditionalModule, conditionalResult) == - "{result: yes}"); - assert(executeBinaryModule(conditionalModule) == "{result: yes}"); - const auto falseConditionalModule = Felidae::compileProgramTextToIr( - "main() =>\nif 2 > 3 then\nreturn (result: \"yes\")\nelse\nreturn " - "(result: \"no\")."); - Felidae::FelidaeKnowledgeRuntime falseConditionalRuntime; - const auto falseConditionalResult = - executeModuleDirect(falseConditionalModule, falseConditionalRuntime); - assert(displayModuleValue(falseConditionalModule, falseConditionalResult) == - "{result: no}"); - assert(executeBinaryModule(falseConditionalModule) == "{result: no}"); - const auto localBindingModule = Felidae::compileProgramTextToIr( - "main() =>\nvalue := 40\nanswer := value + 2\nreturn (answer: answer)."); - Felidae::IrVerifier::verify(localBindingModule.ir); - Felidae::FelidaeKnowledgeRuntime localBindingRuntime; - const auto localBindingResult = - executeModuleDirect(localBindingModule, localBindingRuntime); - assert(displayModuleValue(localBindingModule, localBindingResult) == - "{answer: 42}"); - // Signatures are collected before lowering bodies, so main can call a - // later declaration and that declaration can in turn call another later - // declaration. Parameters live in independent VM call frames and named - // arguments are mapped by their declaration-order symbols. - const auto callsModule = Felidae::compileProgramTextToIr( - "main() => return (answer: twice(value: 21)).\n" - "twice(value: expr) =>\n" - "doubled := add(right: value, left: value)\n" - "return doubled.\n" - "add(left: expr, right: expr) => return left + right."); - Felidae::IrVerifier::verify(callsModule.ir); - Felidae::FelidaeKnowledgeRuntime callsRuntime; - const auto callsResult = executeModuleDirect(callsModule, callsRuntime); - assert(displayModuleValue(callsModule, callsResult) == "{answer: 42}"); - assert(executeBinaryModule(callsModule) == "{answer: 42}"); - // A procedure receives an independent lexical frame. Its local `seed` - // cannot overwrite the caller's local of the same name. - const auto isolatedScopeModule = Felidae::compileProgramTextToIr( - "main() =>\n" - "seed := 5\n" - "return (caller: seed, callee: wrap(value: 7)).\n" - "wrap(value: expr) =>\n" - "seed := value + 1\n" - "return seed."); - Felidae::IrVerifier::verify(isolatedScopeModule.ir); - Felidae::FelidaeKnowledgeRuntime isolatedScopeRuntime; - assert(displayModuleValue( - isolatedScopeModule, - executeModuleDirect(isolatedScopeModule, isolatedScopeRuntime)) == - "{caller: 5, callee: 8}"); - assert(executeBinaryModule(isolatedScopeModule) == "{caller: 5, callee: 8}"); - const auto scopeCompileRejected = [](const std::string &source) { - try { - (void)Felidae::compileProgramTextToIr(source); - return false; - } catch (const Felidae::IntegerParserError &) { - return true; - } - }; - assert(scopeCompileRejected( - "value := 1.\nvalue := 2.\nmain() => return value.")); - assert(scopeCompileRejected("value := 1.\nmain() => return " - "value.\nhelper(value: expr) => return value.")); - assert( - scopeCompileRejected("main() => return helper(value: 1).\nhelper(value: " - "expr) =>\nvalue := 2\nreturn value.")); - assert(scopeCompileRejected("main() => return system.result.\n")); - assert( - scopeCompileRejected("main() => return helper(value: 1).\nhelper(value: " - "expr, value: expr) => return value.")); - const auto recursionModule = Felidae::compileProgramTextToIr( - "main() => return (answer: countdown(value: 4)).\n" - "countdown(value: expr) =>\n" - "if value == 0 then\n" - "return 0\n" - "else\n" - "return countdown(value: value - 1)."); - Felidae::FelidaeKnowledgeRuntime recursionRuntime(nullptr, 1024, 16); - const auto recursionResult = - executeModuleDirect(recursionModule, recursionRuntime); - assert(displayModuleValue(recursionModule, recursionResult) == - "{answer: 0.0}"); - assert(executeBinaryModule(recursionModule) == "{answer: 0.0}"); - bool undefinedProcedureRejected = false; - try { - (void)Felidae::compileProgramTextToIr( - "main() => return (answer: helper())."); - } catch (const Felidae::IntegerParserError &) { - undefinedProcedureRejected = true; - } - assert(undefinedProcedureRejected); - const auto runtimeExpressionIr = - Felidae::tryCompileExpressionTextToIr("10 - 3"); - assert(runtimeExpressionIr); - assert(std::get(executeIrDirect(*runtimeExpressionIr, noRuntime)) == - 7.0); - const auto comparisonIr = Felidae::tryCompileExpressionTextToIr("3 < 7"); - assert(comparisonIr); - assert(std::get(executeIrDirect(*comparisonIr, noRuntime)) == 1.0); - const auto logicIr = - Felidae::tryCompileExpressionTextToIr("not 0.0 and 1.0"); - assert(logicIr); - assert(std::get(executeIrDirect(*logicIr, noRuntime)) == 1.0); - const auto moduloIr = Felidae::tryCompileExpressionTextToIr("17 % 5"); - assert(moduloIr); - assert(std::get(executeIrDirect(*moduloIr, noRuntime)) == 2.0); - const auto callIr = Felidae::tryCompileExpressionTextToIr("combine(6, 7)"); - assert(callIr); - Felidae::IrVerifier::verify(*callIr); - const auto namedCallIr = - Felidae::tryCompileExpressionTextToIr("combine(left: 6, right: 7)"); - assert(namedCallIr); - Felidae::IrVerifier::verify(*namedCallIr); - const auto textIr = Felidae::tryCompileExpressionTextToIr("\"mixfix text\""); - assert(textIr); - assert(Felidae::vmValueToDisplayString(executeIrDirect(*textIr, noRuntime), - display) == "mixfix text"); - const auto nilIr = Felidae::tryCompileExpressionTextToIr("nil"); - assert(nilIr); - assert(std::holds_alternative( - executeIrDirect(*nilIr, noRuntime))); - const auto arrayIr = Felidae::tryCompileExpressionTextToIr("[1, 2, 3]"); - assert(arrayIr); - const auto array = - std::get(executeIrDirect(*arrayIr, noRuntime)); - assert(array && array->values.size() == 3 && - std::get(array->values[2]) == 3.0); - const auto mapIr = - Felidae::tryCompileExpressionTextToIr("{answer: 42, enabled: 1.0}"); - assert(mapIr); - const auto map = - std::get(executeIrDirect(*mapIr, noRuntime)); - assert(map && map->entries.size() == 2); - assert(std::get(map->entries[0].second) == 42.0); - assert(std::get(map->entries[1].second) == 1.0); - class SpanModel final : public Felidae::MixfixStateModel { - public: - std::vector - transform(std::span input, - const Felidae::MixfixContext &) override { - assert(!input.empty()); - return {0, 1, 2, 3, 4, 2, 2, 5}; - } - } spanModel; - Felidae::MixfixContext mixfixContext; - mixfixContext.constantReferences = {0}; - mixfixContext.outputVocabulary = { - {Felidae::MixfixIrTokenKind::Accept, 0}, - {Felidae::MixfixIrTokenKind::Opcode, - static_cast(Felidae::IrOpcode::LoadConst)}, - {Felidae::MixfixIrTokenKind::Register, 0}, - {Felidae::MixfixIrTokenKind::ConstantReference, 0}, - {Felidae::MixfixIrTokenKind::Opcode, - static_cast(Felidae::IrOpcode::Return)}, - {Felidae::MixfixIrTokenKind::End, 0}, - }; - Felidae::FelidaeIr mixfixShell; - mixfixShell.registerCount = 1; - mixfixShell.constants = { - {Felidae::IrConstantKind::Number, Felidae::encodeIrNumber(42.0)}}; - Felidae::IntegerTokenList mixfixInput(Felidae::felidaeSentencePieceModel(), - "unresolved mixfix span"); - Felidae::IntegerParser mixfixParser(mixfixInput); - const auto mixfixIr = mixfixParser.compileVerifiedMixfixSpanIr( - spanModel, mixfixContext, mixfixShell, 0, mixfixInput.entries().size()); - assert(std::get(executeIrDirect(mixfixIr, noRuntime)) == 42.0); - const auto fieldIr = - Felidae::tryCompileExpressionTextToIr("{answer: 42}:answer"); - assert(fieldIr); - assert(std::get(executeIrDirect(*fieldIr, noRuntime)) == 42.0); - const auto aggregateEqualityIr = Felidae::tryCompileExpressionTextToIr( - "[1, {answer: 42}] == [1, {answer: 42}]"); - assert(aggregateEqualityIr); - assert(std::get(executeIrDirect(*aggregateEqualityIr, noRuntime)) == - 1.0); -} diff --git a/tests/direct_ast_smoke.fx b/tests/direct_ast_smoke.fx new file mode 100644 index 0000000..cb7d4e3 --- /dev/null +++ b/tests/direct_ast_smoke.fx @@ -0,0 +1,5 @@ +# The lexer owns comments, strings, punctuation, and decimal digits. +fact(name: "tiger"). + +main() => + return (answer: 6 * 7, literal: 42, decimal: 3.14, animal: "tiger") diff --git a/tests/direct_class_end.fx b/tests/direct_class_end.fx new file mode 100644 index 0000000..32c3ba8 --- /dev/null +++ b/tests/direct_class_end.fx @@ -0,0 +1,18 @@ +class Person + name: string + index(name) +end + +class Student extends Person + grade: number +end + +Student(name: "Ada", grade: 10) + +increment(value: number) => + return value + 1 +end + +main() => + return (count: Person.count(), answer: increment(value: 41)) +end diff --git a/tests/direct_class_fact_value.fx b/tests/direct_class_fact_value.fx new file mode 100644 index 0000000..9b8e5ef --- /dev/null +++ b/tests/direct_class_fact_value.fx @@ -0,0 +1,13 @@ +class Person + id: number + name: string +end + +Person(id: 1, name: "Ada") + +main() => + person := Person.get(pos: 0) + people := Person.all() + from_array := people.get(pos: 0) + return (person: person, from_array: from_array, name: person.get(key: "name")) +end diff --git a/tests/direct_db_sync.fx b/tests/direct_db_sync.fx new file mode 100644 index 0000000..a8fe972 --- /dev/null +++ b/tests/direct_db_sync.fx @@ -0,0 +1,3 @@ +main() => + synchronized := db.sync(path: "direct_sync_source.fx") + return (synchronized: synchronized, rows: ImportedSchool.all()) diff --git a/tests/direct_fact_mutation.fx b/tests/direct_fact_mutation.fx new file mode 100644 index 0000000..7a3f07f --- /dev/null +++ b/tests/direct_fact_mutation.fx @@ -0,0 +1,7 @@ +School(name: "North", active: 1.0). + +main() => + inserted := School.insert(values: {name: "Temporary", active: 1.0}) + updated := School.where(name: "North").update(values: {active: 0.0}) + deleted := School.where(name: "Temporary").delete() + return (inserted: inserted, updated: updated, deleted: deleted, rows: School.all()) diff --git a/tests/direct_fact_selection.fx b/tests/direct_fact_selection.fx new file mode 100644 index 0000000..0d9abfd --- /dev/null +++ b/tests/direct_fact_selection.fx @@ -0,0 +1,9 @@ +School(name: "North", district: "central", active: 1.0). +School(name: "South", district: "west", active: 1.0). +School(name: "Closed", district: "central", active: 0.0). + +main() => + central_or_west := School.where(district: "central").OrWhere(district: "west") + active_central := School.where(district: "central").AndWhere(active: 1.0) + top_one := School.where(active: 1.0).limit(records: 1) + return (or_count: count(central_or_west), and_count: count(active_central), limited: top_one) diff --git a/tests/direct_sync_source.fx b/tests/direct_sync_source.fx new file mode 100644 index 0000000..0fd5203 --- /dev/null +++ b/tests/direct_sync_source.fx @@ -0,0 +1 @@ +ImportedSchool(name: "Synced", active: true). diff --git a/tools/BuildRuntimeTrainingDataset.cpp b/tools/BuildRuntimeTrainingDataset.cpp deleted file mode 100644 index 2ab7580..0000000 --- a/tools/BuildRuntimeTrainingDataset.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "SentencePieceModel.h" -#include "form/BinaryIr.h" -#include "form/RegisterVm.h" -#include "form/RuntimeTraining.h" -#include "form/SemanticOperation.h" - -#include -#include -#include - -namespace { -using namespace Felidae; - -RuntimeTrainingRecord -makeIdentityTeacher(const VmValue &value, const VmKnowledgeSnapshot &knowledge, - std::span symbolTable) { - RuntimeTrainingRecord record; - // This is an explicit, stable operation ID. It is not inferred from the - // binary, a program name, or a VmValue variant index. - record.operationId = - static_cast(SemanticOperationId::Identity); - record.inputKinds = {runtimeValueKind(value)}; - record.inputValues = {runtimeValueEncoding(value, symbolTable)}; - auto encoded = runtimeKnowledgePieces(knowledge, symbolTable); - record.factTypes = std::move(encoded.factTypes); - record.factTypeCounts = std::move(encoded.factTypeCounts); - record.hierarchyEdges = std::move(encoded.hierarchyEdges); - // Identity always preserves the exact typed input. Fact derivation has a - // different permanent operation ID and must never be smuggled in here. - record.targetKind = RuntimeTrainingTargetKind::InputReference; - record.targetValue = 0; - return record; -} - -} // namespace - -int main(int argc, char **argv) { - try { - if (argc < 3) { - throw std::runtime_error("usage: felidae_build_runtime_dataset " - "output.jsonl program.bin [more-programs.bin]"); - } - const std::filesystem::path output(argv[1]); - if (output.extension() != ".jsonl") { - throw std::runtime_error("runtime dataset output must be .jsonl"); - } - std::vector records; - records.reserve(static_cast(argc - 2)); - for (int index = 2; index < argc; ++index) { - const std::filesystem::path input(argv[index]); - if (input.extension() != kBinaryIrExtension) { - throw std::runtime_error("runtime dataset input must be .bin"); - } - const auto module = - loadBinaryIr(input, felidaeSentencePieceModelIdentity()); - if (containsRuntimeSemanticOperation(module)) { - throw std::runtime_error( - "runtime SSM binaries require explicit operation-level teachers; " - "no partial dataset was written"); - } - try { - FelidaeKnowledgeRuntime runtime; - RegisterVm vm; - const auto result = vm.executeMain(module, runtime); - const auto knowledge = runtime.factStore()->knowledgeSnapshot(); - records.push_back( - makeIdentityTeacher(result, knowledge, module->symbolTable)); - } catch (const std::exception &error) { - throw std::runtime_error("runtime dataset input failed '" + - input.string() + "': " + error.what()); - } - } - // The writer replaces the corpus only after every input has loaded, - // verified, and executed successfully. - writeRuntimeTrainingDataset(output, records); - std::cout << records.size() - << " deterministic runtime operation records written to " - << std::filesystem::absolute(output).lexically_normal().string() - << "\n"; - return 0; - } catch (const std::exception &error) { - std::cerr << "error: " << error.what() << "\n"; - return 1; - } -} diff --git a/tools/ExtractMixfixDataset.cpp b/tools/ExtractMixfixDataset.cpp deleted file mode 100644 index 7d40619..0000000 --- a/tools/ExtractMixfixDataset.cpp +++ /dev/null @@ -1,638 +0,0 @@ -#include "CompilerFrontend.h" -#include "IntegerParser.h" -#include "IntegerTokenList.h" -#include "IrCodeGenerator.h" -#include "MixfixStateModel.h" -#include "SentencePieceModel.h" -#include "form/RegisterVm.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -using namespace Felidae; - -std::size_t byteOffset(const std::string &source, int line, int column) { - if (line < 1 || column < 1) - throw std::runtime_error("mixfix AST span is invalid"); - std::size_t offset = 0; - for (int current = 1; current < line; ++current) { - const auto newline = source.find('\n', offset); - if (newline == std::string::npos) - throw std::runtime_error("mixfix AST span exceeds source lines"); - offset = newline + 1; - } - offset += static_cast(column - 1); - if (offset > source.size()) - throw std::runtime_error("mixfix AST span exceeds source columns"); - return offset; -} - -std::vector spanIds(const IntegerTokenList &tokens, - const SourceSpan &span) { - const auto first = - byteOffset(tokens.source(), span.startLine, span.startColumn); - const auto last = byteOffset(tokens.source(), span.endLine, span.endColumn); - std::vector result; - for (const auto &entry : tokens.entries()) { - if (entry.id < 0) - throw std::runtime_error("SentencePiece produced a negative token ID"); - if (entry.end > first && entry.begin < last) { - result.push_back(static_cast(entry.id)); - } - } - if (result.empty()) - throw std::runtime_error("mixfix AST span has no SentencePiece IDs"); - return result; -} - -MixfixVocabularyId token(const MixfixContext &context, MixfixIrTokenKind kind, - IrWord value) { - const auto found = std::find_if( - context.outputVocabulary.begin(), context.outputVocabulary.end(), - [&](const MixfixIrToken &item) { - return item.kind == kind && item.value == value; - }); - if (found == context.outputVocabulary.end()) { - throw std::runtime_error( - "mixfix IR cannot be represented by the fixed vocabulary (kind=" + - std::to_string(static_cast(kind)) + - ", value=" + std::to_string(value) + ")"); - } - return static_cast( - std::distance(context.outputVocabulary.begin(), found)); -} - -std::vector encodeTeacher(const FelidaeIr &ir) { - const auto context = makeMixfixContext(ir); - std::vector result; - result.push_back(token(context, MixfixIrTokenKind::Accept, 0)); - const auto raw = [&](IrWord value) { - result.push_back(token(context, MixfixIrTokenKind::Register, value)); - }; - const auto reg = raw; - const auto constant = [&](IrWord value) { - result.push_back( - token(context, MixfixIrTokenKind::ConstantReference, value)); - }; - const auto symbol = [&](IrWord value) { - result.push_back(token(context, MixfixIrTokenKind::SymbolReference, value)); - }; - for (std::size_t pc = 0; pc < ir.words.size();) { - const auto opcode = static_cast(ir.words.at(pc)); - const auto require = [&](std::size_t width) { - if (width > ir.words.size() - pc) - throw std::runtime_error( - "deterministic mixfix teacher IR is truncated"); - }; - if (opcode == IrOpcode::End) { - result.push_back(token(context, MixfixIrTokenKind::End, 0)); - ++pc; - continue; - } - result.push_back( - token(context, MixfixIrTokenKind::Opcode, static_cast(opcode))); - switch (opcode) { - case IrOpcode::End: - break; - case IrOpcode::Jump: - require(2); - raw(ir.words[pc + 1]); - pc += 2; - break; - case IrOpcode::LoadConst: - require(3); - reg(ir.words[pc + 1]); - constant(ir.words[pc + 2]); - pc += 3; - break; - case IrOpcode::LoadSymbol: - case IrOpcode::StoreSymbol: - case IrOpcode::MakeFact: - require(3); - reg(ir.words[pc + 1]); - symbol(ir.words[pc + 2]); - pc += 3; - break; - case IrOpcode::Move: - case IrOpcode::JumpIfFalse: - case IrOpcode::Return: - require(3); - reg(ir.words[pc + 1]); - raw(ir.words[pc + 2]); - pc += 3; - break; - case IrOpcode::Add: - case IrOpcode::Sub: - case IrOpcode::Mul: - case IrOpcode::Div: - case IrOpcode::Mod: - case IrOpcode::GetField: - case IrOpcode::SetField: - case IrOpcode::Similarity: - case IrOpcode::ForEachFact: - case IrOpcode::HierarchyIsA: - case IrOpcode::HierarchyCommonAncestors: - case IrOpcode::HierarchyLeastCommonAncestors: - case IrOpcode::HierarchyMostGeneralAncestors: - require(4); - reg(ir.words[pc + 1]); - raw(ir.words[pc + 2]); - raw(ir.words[pc + 3]); - pc += 4; - break; - case IrOpcode::TemporalRank: - require(4); - reg(ir.words[pc + 1]); - symbol(ir.words[pc + 2]); - symbol(ir.words[pc + 3]); - pc += 4; - break; - case IrOpcode::Compare: - require(5); - reg(ir.words[pc + 1]); - raw(ir.words[pc + 2]); - raw(ir.words[pc + 3]); - raw(ir.words[pc + 4]); - pc += 5; - break; - case IrOpcode::Membership: - require(6); - for (std::size_t index = 1; index < 6; ++index) - raw(ir.words[pc + index]); - pc += 6; - break; - case IrOpcode::Call: - case IrOpcode::Builtin: - case IrOpcode::SemanticEval: - case IrOpcode::Numeric: - case IrOpcode::Tensor: - case IrOpcode::MakeArray: { - require(4); - reg(ir.words[pc + 1]); - if (opcode == IrOpcode::Call) - symbol(ir.words[pc + 2]); - else - raw(ir.words[pc + 2]); - const auto count = ir.words[pc + 3]; - raw(count); - require(4 + count); - for (std::size_t index = 0; index < count; ++index) { - raw(ir.words[pc + 4 + index]); - } - pc += 4 + count; - break; - } - case IrOpcode::CallNamed: - case IrOpcode::MakeMap: { - require(4); - reg(ir.words[pc + 1]); - if (opcode == IrOpcode::CallNamed) - symbol(ir.words[pc + 2]); - else - raw(ir.words[pc + 2]); - const auto count = ir.words[pc + 3]; - raw(count); - require(4 + count * 2); - for (std::size_t index = 0; index < count; ++index) { - symbol(ir.words[pc + 4 + index * 2]); - raw(ir.words[pc + 5 + index * 2]); - } - pc += 4 + count * 2; - break; - } - case IrOpcode::Count: - throw std::runtime_error( - "deterministic mixfix teacher has invalid opcode"); - } - } - if (resolveMixfixVocabularyIds(result, context) != ir.words) { - throw std::runtime_error("mixfix teacher vocabulary round trip failed"); - } - return result; -} - -void visitExpr(const std::shared_ptr &expression, - std::vector> &output) { - if (!expression) - return; - if (const auto operation = - std::dynamic_pointer_cast(expression)) { - if (operation->coreOperator == CoreOperator::Unknown) - output.push_back(operation); - for (std::size_t index = 0; index < operation->captureCount(); ++index) - visitExpr(operation->capture(index), output); - } else if (const auto array = - std::dynamic_pointer_cast(expression)) { - for (const auto &item : array->items) - visitExpr(item, output); - } else if (const auto map = std::dynamic_pointer_cast(expression)) { - for (const auto &entry : map->entries) - visitExpr(entry.value, output); - } else if (const auto access = - std::dynamic_pointer_cast(expression)) { - visitExpr(access->target, output); - } else if (const auto term = - std::dynamic_pointer_cast(expression)) { - for (const auto &argument : term->args) - visitExpr(argument.value, output); - } -} - -void visitCall(const Call &call, - std::vector> &output) { - for (const auto &argument : call.args) - visitExpr(argument.value, output); -} - -void visitGoal(const std::shared_ptr &goal, - std::vector> &output) { - if (const auto call = std::dynamic_pointer_cast(goal)) - visitCall(call->call, output); - else if (const auto binary = std::dynamic_pointer_cast(goal)) { - visitExpr(binary->left, output); - visitExpr(binary->right, output); - } else if (const auto assign = std::dynamic_pointer_cast(goal)) - visitExpr(assign->expr, output); - else if (const auto assign = std::dynamic_pointer_cast(goal)) - visitExpr(assign->expr, output); - else if (const auto where = std::dynamic_pointer_cast(goal)) - visitGoal(where->condition, output); - else if (const auto conditional = std::dynamic_pointer_cast(goal)) { - visitGoal(conditional->condition, output); - for (const auto &item : conditional->thenBranch) - visitGoal(item, output); - for (const auto &item : conditional->elseBranch) - visitGoal(item, output); - } else if (const auto returned = - std::dynamic_pointer_cast(goal)) { - for (const auto &field : returned->fields) - visitExpr(field.value, output); - } else if (const auto group = std::dynamic_pointer_cast(goal)) { - for (const auto &item : group->goals) - visitGoal(item, output); - } else if (const auto alternatives = - std::dynamic_pointer_cast(goal)) { - for (const auto &branch : alternatives->branches) - for (const auto &item : branch) - visitGoal(item, output); - } -} - -bool isInvalidCase(const std::filesystem::path &path) { - return std::any_of(path.begin(), path.end(), [](const auto &component) { - return component == "invalid"; - }); -} - -std::vector -sources(const std::vector &roots, bool invalidCases) { - std::vector result; - for (const auto &root : roots) { - if (std::filesystem::is_regular_file(root) && root.extension() == ".fx" && - isInvalidCase(root) == invalidCases) - result.push_back(root); - else if (std::filesystem::is_directory(root)) { - for (const auto &entry : - std::filesystem::recursive_directory_iterator(root)) { - if (entry.is_regular_file() && entry.path().extension() == ".fx" && - isInvalidCase(entry.path()) == invalidCases) - result.push_back(entry.path()); - } - } else - throw std::runtime_error( - "mixfix dataset input is not a .fx file or directory: " + - root.string()); - } - std::sort(result.begin(), result.end()); - return result; -} - -std::vector sourceIds(const IntegerTokenList &tokens) { - std::vector result; - result.reserve(tokens.entries().size()); - for (const auto &entry : tokens.entries()) { - if (entry.id < 0) - throw std::runtime_error("SentencePiece produced a negative token ID"); - result.push_back(static_cast(entry.id)); - } - if (result.empty()) - throw std::runtime_error("source has no SentencePiece IDs"); - return result; -} - -std::vector> generatedValidSources() { - constexpr std::string_view transform = - R"(@overload(operator: transformWith, pattern: "{value} transform {model} with {count}", type: mixfix, captures: {value: number, model: number, count: number}, result: number, precedence: relationship, associativity: none, cardinality: one, effects: pure, visibility: private) -transformValue() => - return value + model * count - -main() => - return )"; - constexpr std::string_view choose = - R"(@overload(operator: chooseOtherwise, pattern: "choose {left} otherwise {right}", type: mixfix, captures: {left: number, right: number}, result: number, precedence: relationship, associativity: right, cardinality: one, effects: pure, visibility: private) -chooseLarger() => - if left > right then - return left - else - return right - -main() => - return )"; - constexpr std::string_view plan = - R"(@mixfix(pattern: "plan {value: number} using {enabled: bool}") -numberPlan(value:number, enabled:bool) => - return Plan(value: value, enabled: enabled) - -main() => - return )"; - constexpr std::string_view wide = - R"(@mixfix(pattern: "weigh {a: number} then {b: number} then {c: number} then {d: number} then {e: number} then {f: number}") -weighSix(a:number, b:number, c:number, d:number, e:number, f:number) => - return a + b + c + d + e + f - -main() => - return )"; - constexpr std::string_view typed = - R"(@mixfix(pattern: "classify {value: number} using {enabled: bool}") -classifyNumber(value:number, enabled:bool) => - return value - -@mixfix(pattern: "classify {value: string} using {enabled: bool}") -classifyText(value:string, enabled:bool) => - return value - -candidate := 7 - -main() => - return )"; - std::vector> result; - result.reserve(120); - for (std::size_t seed = 1; seed <= 24; ++seed) { - const auto left = std::to_string(seed); - const auto model = std::to_string(seed + 2); - const auto count = std::to_string(seed % 7 + 1); - result.emplace_back("generated-transform-" + std::to_string(seed), - std::string(transform) + left + " transform " + model + - " with " + count + "\n"); - } - for (std::size_t seed = 1; seed <= 24; ++seed) { - const auto left = std::to_string(seed); - const auto middle = std::to_string(seed + 3); - const auto right = std::to_string(seed + 6); - result.emplace_back("generated-choose-" + std::to_string(seed), - std::string(choose) + "choose " + left + - " otherwise choose " + middle + " otherwise " + - right + "\n"); - } - for (std::size_t seed = 1; seed <= 24; ++seed) { - result.emplace_back("generated-plan-" + std::to_string(seed), - std::string(plan) + "plan " + std::to_string(seed * 3) + - " using " + (seed % 2 == 0 ? "1.0\n" : "0.0\n")); - } - for (std::size_t seed = 1; seed <= 16; ++seed) { - std::string expression = std::to_string(seed + 7); - for (std::size_t depth = 0; depth < 12; ++depth) { - expression = - "choose " + std::to_string(seed + depth) + " otherwise " + expression; - } - result.emplace_back("generated-deep-choose-" + std::to_string(seed), - std::string(choose) + expression + "\n"); - } - for (std::size_t seed = 1; seed <= 16; ++seed) { - std::string expression = "weigh"; - for (std::size_t index = 0; index < 6; ++index) { - expression += " " + std::to_string(seed + index); - if (index + 1 < 6) - expression += " then"; - } - result.emplace_back("generated-wide-repeated-anchor-" + - std::to_string(seed), - std::string(wide) + expression + "\n"); - } - for (std::size_t seed = 1; seed <= 16; ++seed) { - // A variable has no concrete capture type during parsing, so both typed - // overloads remain structurally possible. These are safe-target - // abstention teachers, not fabricated calls to either implementation. - result.emplace_back("generated-typed-abstain-" + std::to_string(seed), - std::string(typed) + "classify candidate using " + - (seed % 2 == 0 ? "1.0\n" : "0.0\n")); - } - return result; -} - -void writeJsonl(const std::filesystem::path &output, - const std::vector &records) { - if (output.empty() || output.extension() != ".jsonl") - throw std::runtime_error("dataset output must be .jsonl"); - if (records.empty()) - throw std::runtime_error("dataset has no records"); - if (!output.parent_path().empty()) - std::filesystem::create_directories(output.parent_path()); - const auto temporary = output.string() + ".tmp"; - std::ofstream stream(temporary, std::ios::trunc); - if (!stream) - throw std::runtime_error("cannot write dataset"); - for (const auto &record : records) - stream << record.dump() << '\n'; - stream.close(); - if (!stream) - throw std::runtime_error("cannot finish dataset"); - std::filesystem::rename(temporary, output); -} -} // namespace - -int main(int argc, char **argv) { - try { - if (argc < 3) - throw std::runtime_error( - "usage: felidae_extract_mixfix_dataset output.jsonl examples " - "v2_examples [--rejections invalid.jsonl]"); - const std::filesystem::path output(argv[1]); - if (output.extension() != ".jsonl") - throw std::runtime_error("mixfix dataset output must be .jsonl"); - std::vector roots; - std::optional rejectionOutput; - for (int index = 2; index < argc; ++index) { - if (std::string_view(argv[index]) == "--rejections") { - if (rejectionOutput || ++index >= argc) - throw std::runtime_error( - "--rejections requires one output.jsonl path"); - rejectionOutput.emplace(argv[index]); - } else { - roots.emplace_back(argv[index]); - } - } - if (roots.empty()) - throw std::runtime_error( - "mixfix dataset requires at least one example root"); - std::vector records; - const auto sentencePieceIdentity = felidaeSentencePieceModelIdentity(); - std::set, - std::vector>> - unique; - std::size_t boundedOut = 0; - std::size_t rejectedSources = 0; - std::vector> teachers; - for (const auto &path : sources(roots, false)) - teachers.emplace_back(path.string(), readSourceFile(path)); - auto generated = generatedValidSources(); - teachers.insert(teachers.end(), std::make_move_iterator(generated.begin()), - std::make_move_iterator(generated.end())); - for (const auto &[label, source] : teachers) { - Program program; - try { - program = parseProgramText(source); - } catch (const std::exception &error) { - ++rejectedSources; - std::cerr << "skipping non-teacher source " << label << ": " - << error.what() << '\n'; - continue; - } - const IntegerTokenList tokens(felidaeSentencePieceModel(), source); - std::vector> operations; - for (const auto &global : program.globals) - visitExpr(global->expr, operations); - for (const auto &clause : program.clauses) { - visitCall(clause->head, operations); - for (const auto &annotation : clause->annotations) - visitCall(annotation, operations); - for (const auto &goal : clause->body) - visitGoal(goal, operations); - for (const auto &branch : clause->fallbackBranches) - for (const auto &goal : branch) - visitGoal(goal, operations); - } - if (!operations.empty()) - std::cerr << "found " << operations.size() - << " custom mixfix expressions in " << label << '\n'; - for (const auto &operation : operations) { - const auto input = spanIds(tokens, operation->sourceSpan); - try { - const auto target = - encodeTeacher(IrCodeGenerator::lowerExpression(operation)); - if (unique.emplace(input, target).second) - records.push_back( - {{"schema_version", 3}, - {"sentencepiece_model_identity", sentencePieceIdentity}, - {"compiler_ir_vocabulary", kMixfixIrVocabularyVersion}, - {"input_ids", input}, - {"target_ids", target}, - {"decision", "ACCEPT"}}); - } catch (const std::runtime_error &error) { - const std::string_view message(error.what()); - if (message.find("cannot be represented by the fixed vocabulary") != - std::string_view::npos) { - ++boundedOut; - std::cerr << "skipping bounded-out mixfix teacher in " << label - << ": " << message << '\n'; - } else if (message.find("requires verified model target selection") != - std::string_view::npos || - message.find("has no direct IR lowering") != - std::string_view::npos) { - const auto context = makeMixfixContext(FelidaeIr{}); - const std::vector target{ - token(context, MixfixIrTokenKind::Abstain, 0)}; - if (unique.emplace(input, target).second) { - records.push_back( - {{"schema_version", 3}, - {"sentencepiece_model_identity", sentencePieceIdentity}, - {"compiler_ir_vocabulary", kMixfixIrVocabularyVersion}, - {"input_ids", input}, - {"target_ids", target}, - {"decision", "ABSTAIN"}}); - } - std::cerr << "recording ABSTAIN mixfix teacher in " << label << ": " - << message << '\n'; - } else { - throw; - } - } - } - } - if (records.empty()) - throw std::runtime_error( - "no deterministically resolved mixfix expressions were found"); - std::size_t rejectionRecords = 0; - std::size_t acceptedInvalidSources = 0; - std::vector rejections; - if (rejectionOutput) { - for (const auto &path : sources(roots, true)) { - const auto source = readSourceFile(path); - const IntegerTokenList tokens(felidaeSentencePieceModel(), source); - std::uint32_t stage = 0; - try { - const auto program = parseProgramText(source); - try { - auto module = IrCodeGenerator{}.compile(program); - try { - FelidaeKnowledgeRuntime runtime; - RegisterVm vm; - (void)vm.executeMain(verifyIrModule(std::move(module)), runtime); - } catch (const std::exception &) { - stage = 3; // Verified VM/runtime rejection. - } - } catch (const std::exception &) { - stage = 2; // AST-to-IR/compiler rejection. - } - } catch (const std::exception &) { - stage = 1; // SentencePiece-aware parser rejection. - } - if (stage == 0) { - // Fixture directories occasionally retain a case whose - // historical resource limit no longer applies. It is not - // a valid negative label, so report and exclude it. - ++acceptedInvalidSources; - std::cerr - << "excluding stale invalid fixture that executed successfully: " - << path.string() << '\n'; - continue; - } - const auto context = makeMixfixContext(FelidaeIr{}); - const auto reject = token(context, MixfixIrTokenKind::Reject, 0); - rejections.push_back( - {{"schema_version", 3}, - {"sentencepiece_model_identity", sentencePieceIdentity}, - {"compiler_ir_vocabulary", kMixfixIrVocabularyVersion}, - {"input_ids", sourceIds(tokens)}, - {"target_ids", std::vector{reject}}, - {"decision", "REJECT"}, - {"rejection_stage", stage}}); - } - rejectionRecords = rejections.size(); - } - // All valid and invalid sources are checked before either reusable - // corpus is replaced, so a failed input cannot leave a mixed run. - writeJsonl(output, records); - if (rejectionOutput) - writeJsonl(*rejectionOutput, rejections); - const auto abstentionRecords = static_cast(std::count_if( - records.begin(), records.end(), [](const nlohmann::json &record) { - return record.value("decision", std::string{}) == "ABSTAIN"; - })); - const auto acceptanceRecords = records.size() - abstentionRecords; - std::cout << records.size() << " compiler mixfix records written to " - << output.string() << " (ACCEPT=" << acceptanceRecords - << ", ABSTAIN=" << abstentionRecords << ")" - << "; " << boundedOut - << " expressions exceeded fixed structural bounds; " - << rejectedSources - << " valid-root sources were rejected by the current parser; " - << rejectionRecords - << " invalid rejection-evaluation records written; " - << acceptedInvalidSources << " stale invalid fixtures excluded\n"; - } catch (const std::exception &error) { - std::cerr << "error: " << error.what() << '\n'; - return 1; - } -} diff --git a/tools/FactStoreBenchmark.cpp b/tools/FactStoreBenchmark.cpp deleted file mode 100644 index 80bdb7f..0000000 --- a/tools/FactStoreBenchmark.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "form/RegisterVm.h" -#include "form/libs/RocksDb.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -std::size_t argument(char **begin, char **end, std::string_view name, - std::size_t fallback) { - for (auto current = begin; current != end; ++current) { - if (*current != name || current + 1 == end) - continue; - const std::string_view value(*++current); - std::size_t parsed = 0; - try { - const auto number = std::stoull(std::string(value), &parsed); - if (parsed != value.size() || number == 0 || - number > std::numeric_limits::max()) - throw std::invalid_argument("range"); - return static_cast(number); - } catch (const std::exception &) { - throw Felidae::IrError(std::string(name) + " requires a positive integer"); - } - } - return fallback; -} - -double milliseconds(std::chrono::steady_clock::duration duration) { - return std::chrono::duration(duration).count(); -} - -std::uintmax_t directoryBytes(const std::filesystem::path &directory) { - std::uintmax_t result = 0; - std::error_code error; - for (std::filesystem::recursive_directory_iterator iterator(directory, error), end; - !error && iterator != end; iterator.increment(error)) { - if (iterator->is_regular_file(error)) - result += iterator->file_size(error); - } - if (error) - throw Felidae::IrError("cannot measure benchmark storage: " + error.message()); - return result; -} - -} // namespace - -int main(int argc, char **argv) try { - using Clock = std::chrono::steady_clock; - const auto records = argument(argv + 1, argv + argc, "--records", 10'000); - const auto pageSize = argument(argv + 1, argv + argc, "--page", 100); - const auto warmIterations = argument(argv + 1, argv + argc, "--warm", 100); - if (pageSize > 10'000) - throw Felidae::IrError("--page exceeds the 10000 row runtime limit"); - - const std::filesystem::path database = - std::filesystem::path(FELIDAE_BENCHMARK_OUTPUT_DIR) / - ("fact-store-" + std::to_string(records) + ".rocksdb"); - std::error_code error; - std::filesystem::remove_all(database, error); - if (error) - throw Felidae::IrError("cannot clear benchmark database: " + error.message()); - - const Felidae::PieceSequence typePieces{101}; - const Felidae::PieceSequence fieldPieces{102}; - const auto ingestBegin = Clock::now(); - { - Felidae::VmFactStore store(database); - const auto type = store.internSymbol(typePieces); - const auto field = store.internSymbol(fieldPieces); - store.registerType(type, {}, {{field}}); - for (std::size_t index = 0; index < records; ++index) { - auto fact = std::make_shared(); - fact->type = type; - fact->fields = {{field, static_cast(index % 100)}}; - (void)store.retain(fact); - } - } - const auto ingestEnd = Clock::now(); - - double reopenMilliseconds = 0.0; - double coldMilliseconds = 0.0; - double warmMeanMilliseconds = 0.0; - std::size_t returnedRows = 0; - bool hasMore = false; - std::size_t observedRows = 0; - { - const auto openBegin = Clock::now(); - Felidae::VmFactStore store(database); - const auto type = *store.findSymbol(typePieces); - const auto field = *store.findSymbol(fieldPieces); - const std::pair predicate{field, 42.0}; - const auto openEnd = Clock::now(); - const auto coldBegin = Clock::now(); - const auto cold = store.pageMatching(type, {&predicate, 1}, pageSize); - const auto coldEnd = Clock::now(); - const auto warmBegin = Clock::now(); - for (std::size_t index = 0; index < warmIterations; ++index) - observedRows += store.pageMatching(type, {&predicate, 1}, pageSize).rows.size(); - const auto warmEnd = Clock::now(); - reopenMilliseconds = milliseconds(openEnd - openBegin); - coldMilliseconds = milliseconds(coldEnd - coldBegin); - warmMeanMilliseconds = - milliseconds(warmEnd - warmBegin) / static_cast(warmIterations); - returnedRows = cold.rows.size(); - hasMore = cold.hasMore; - } - Felidae::Form::RocksDb metrics(database); - const auto indexReaderBytes = - metrics.integerProperty("rocksdb.estimate-table-readers-mem"); - const auto liveDataBytes = - metrics.integerProperty("rocksdb.estimate-live-data-size"); - const auto sstBytes = metrics.integerProperty("rocksdb.total-sst-files-size"); - - const auto ingestSeconds = - std::chrono::duration(ingestEnd - ingestBegin).count(); - std::cout << "{\n" - << " \"records\": " << records << ",\n" - << " \"requested_page_size\": " << pageSize << ",\n" - << " \"returned_page_size\": " << returnedRows << ",\n" - << " \"has_more\": " << (hasMore ? "1.0" : "0.0") << ",\n" - << " \"ingestion_records_per_second\": " - << static_cast(records) / ingestSeconds << ",\n" - << " \"reopen_milliseconds\": " << reopenMilliseconds << ",\n" - << " \"cold_lookup_milliseconds\": " << coldMilliseconds << ",\n" - << " \"warm_lookup_mean_milliseconds\": " << warmMeanMilliseconds << ",\n" - << " \"warm_observed_rows\": " << observedRows << ",\n" - << " \"index_reader_memory_bytes\": " << indexReaderBytes.value_or(0) << ",\n" - << " \"estimated_live_data_bytes\": " << liveDataBytes.value_or(0) << ",\n" - << " \"sst_storage_bytes\": " << sstBytes.value_or(0) << ",\n" - << " \"storage_size_bytes\": " << directoryBytes(database) << ",\n" - << " \"cache_state_cold\": \"database reopened; operating-system cache not flushed\",\n" - << " \"cache_state_warm\": \"same process and query repeated\",\n" - << " \"claim\": \"measured local dataset only; no trillion-scale guarantee\"\n" - << "}\n"; - return 0; -} catch (const std::exception &error) { - std::cerr << "error: " << error.what() << '\n'; - return 1; -} diff --git a/tools/GenerateSentencePieceModel.cpp b/tools/GenerateSentencePieceModel.cpp deleted file mode 100644 index 563d3ad..0000000 --- a/tools/GenerateSentencePieceModel.cpp +++ /dev/null @@ -1,185 +0,0 @@ -#include "FelidaeGrammar.h" - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace { -struct TokenizerCorpus { - std::vector sources; -}; - -TokenizerCorpus loadCorpus(const std::string& path) { - std::ifstream input(path, std::ios::binary); - if (!input) throw std::runtime_error("unable to open tokenizer JSONL dataset " + path); - TokenizerCorpus corpus; - std::set ids; - std::set families; - std::string line; - std::size_t lineNumber = 0; - while (std::getline(input, line)) { - ++lineNumber; - if (line.empty()) continue; - const auto record = nlohmann::json::parse(line); - if (!record.is_object() || record.size() != 4 || - !record.contains("schema_version") || !record.at("schema_version").is_number_unsigned() || - record.at("schema_version").get() != 1 || - !record.contains("id") || !record.at("id").is_string() || - !record.contains("family") || !record.at("family").is_string() || - !record.contains("source") || !record.at("source").is_string()) { - throw std::runtime_error("invalid tokenizer JSONL record at line " + std::to_string(lineNumber)); - } - const auto id = record.at("id").get(); - const auto family = record.at("family").get(); - const auto source = record.at("source").get(); - if (id.empty() || id.size() > 128 || family.empty() || family.size() > 64 || - source.empty() || source.size() > 16384 || !ids.insert(id).second) { - throw std::runtime_error("invalid tokenizer JSONL values at line " + std::to_string(lineNumber)); - } - families.insert(family); - corpus.sources.push_back(source); - } - if (!input.eof()) throw std::runtime_error("unable to read tokenizer JSONL dataset"); - if (corpus.sources.size() < 20 || families.size() < 10) { - throw std::runtime_error("tokenizer JSONL dataset needs at least 20 records across 10 syntax families"); - } - return corpus; -} - -class CorpusIterator final : public sentencepiece::SentenceIterator { -public: - explicit CorpusIterator(const std::vector& corpus) : corpus_(corpus) {} - bool done() const override { return index_ >= corpus_.size(); } - void Next() override { if (!done()) ++index_; } - const std::string& value() const override { return corpus_[index_]; } - absl::Status status() const override { return absl::OkStatus(); } -private: - const std::vector& corpus_; - std::size_t index_ = 0; -}; - -void writeFile(const std::string& path, const std::string& data) { - std::ofstream out(path, std::ios::binary | std::ios::trunc); - if (!out || !out.write(data.data(), static_cast(data.size()))) { - throw std::runtime_error("unable to write " + path); - } -} - -bool beginsWithAsciiUppercase(const std::string& piece) { - // A SentencePiece can contain the complete leading identifier fragment - // ("Stage"), only a prefix ("St"), or one byte ("S"). The grammar - // property is carried by its first source character, not by a particular - // fragmentation length. - std::size_t start = 0; - // SentencePiece represents preceding source whitespace with U+2581. The - // marker is not part of the identifier, so it must not hide an uppercase - // first source byte after indentation or a separator. - if (piece.size() >= 3 && piece.compare(0, 3, "\xE2\x96\x81") == 0) start = 3; - if (piece.size() > start && piece[start] >= 'A' && piece[start] <= 'Z') return true; - // Byte-fallback pieces are serialized by SentencePiece as <0xNN>. - return piece.size() == 6 && piece[0] == '<' && piece[1] == '0' && piece[2] == 'x' && - piece[5] == '>' && - ((piece[3] == '4' && piece[4] >= '1' && piece[4] <= '9') || - (piece[3] == '5' && piece[4] >= '0' && piece[4] <= 'A')); -} -} // namespace - -int main(int argc, char** argv) { - if (argc != 4) { - std::cerr << "usage: GenerateSentencePieceModel MODEL_PATH IDS_HEADER_PATH DATASET_JSONL\n"; - return 2; - } - try { - const auto dataset = loadCorpus(argv[3]); - std::vector corpus; - corpus.reserve(std::size(Felidae::kBuiltinTokens) + dataset.sources.size()); - for (const auto& token : Felidae::kBuiltinTokens) corpus.emplace_back(token.spelling); - corpus.insert(corpus.end(), dataset.sources.begin(), dataset.sources.end()); - CorpusIterator iterator(corpus); - sentencepiece::TrainerComponents components; - components.sentence_iterator = &iterator; - auto* spec = components.mutable_trainer_spec(); - spec->set_model_type(sentencepiece::TrainerSpec::BPE); - spec->set_vocab_size(1024); - spec->set_hard_vocab_limit(false); - spec->set_character_coverage(1.0F); - spec->set_shuffle_input_sentence(false); - spec->set_num_threads(1); - spec->set_unk_id(0); - // Every valid UTF-8 source byte must have an integer representation. - // Without byte fallback, unrelated user-defined identifiers can both - // become and no integer parser can distinguish their sequences. - spec->set_byte_fallback(true); - spec->set_bos_id(-1); - spec->set_eos_id(-1); - spec->set_pad_id(-1); - for (const auto& token : Felidae::kBuiltinTokens) { - spec->add_user_defined_symbols(std::string(token.spelling)); - } - auto* normalizer = components.mutable_normalizer_spec(); - normalizer->set_name("identity"); - normalizer->set_add_dummy_prefix(false); - normalizer->set_remove_extra_whitespaces(false); - normalizer->set_escape_whitespaces(true); - - sentencepiece::SetMinLogLevel(2); - std::string serialized; - const auto status = sentencepiece::SentencePieceTrainer::Train(components, &serialized); - if (!status.ok()) throw std::runtime_error(status.ToString()); - sentencepiece::ModelProto model; - if (!model.ParseFromString(serialized)) throw std::runtime_error("model serialization failed"); - - std::string ids = "// Generated by tools/GenerateSentencePieceModel.cpp. Do not edit.\n#pragma once\n\n"; - ids += "#include \n\nnamespace Felidae {\n"; - ids += "inline constexpr std::uint32_t kFelidaeTokenizerDatasetSchemaVersion = 1;\n"; - ids += "inline constexpr std::uint32_t kFelidaeTokenizerDatasetRecordCount = " + - std::to_string(dataset.sources.size()) + ";\n"; - ids += "inline constexpr std::uint32_t kFelidaeSentencePieceVocabularySize = " + - std::to_string(model.pieces_size()) + ";\n"; - ids += "inline constexpr int kFelidaeBuiltinSentencePieceIds[] = {\n"; - for (const auto& token : Felidae::kBuiltinTokens) { - int id = -1; - for (int index = 0; index < model.pieces_size(); ++index) { - if (model.pieces(index).piece() == token.spelling) { id = index; break; } - } - if (id < 0) throw std::runtime_error("missing built-in " + std::string(token.spelling)); - // idName is source-safe even when a grammar symbol itself is a - // line-comment escape such as a backslash. - ids += " " + std::to_string(id) + ", // " + std::string(token.idName) + "\n"; - } - ids += "};\n\nnamespace TokenId {\nusing Id = std::int32_t;\n"; - ids += "constexpr Id UNKNOWN = 0;\n"; - for (const auto& token : Felidae::kBuiltinTokens) { - int id = -1; - for (int index = 0; index < model.pieces_size(); ++index) { - if (model.pieces(index).piece() == token.spelling) { id = index; break; } - } - ids += "constexpr Id " + std::string(token.idName) + " = " + std::to_string(id) + ";\n"; - } - ids += "} // namespace TokenId\n\ninline constexpr bool isCapitalizedIdentifierStartId(TokenId::Id id) {\n"; - ids += " switch (id) {\n"; - for (int index = 0; index < model.pieces_size(); ++index) { - if (beginsWithAsciiUppercase(model.pieces(index).piece())) { - ids += " case " + std::to_string(index) + ": return true;\n"; - } - } - ids += " default: return false;\n }\n}\n"; - ids += "} // namespace Felidae\n"; - writeFile(argv[1], serialized); - writeFile(argv[2], ids); - } catch (const std::exception& error) { - std::cerr << "felidae SentencePiece model generation failed: " << error.what() << '\n'; - return 1; - } - return 0; -} diff --git a/tools/IntegerParserBenchmark.cpp b/tools/IntegerParserBenchmark.cpp deleted file mode 100644 index f0d4cc2..0000000 --- a/tools/IntegerParserBenchmark.cpp +++ /dev/null @@ -1,130 +0,0 @@ -#include "FelidaeIr.h" -#include "IntegerParser.h" -#include "IntegerTokenList.h" -#include "Operator.h" -#include "SentencePieceModel.h" - -#include -#include -#include -#include -#include -#include -#include - -int main(int argc, char **argv) { - const bool nativeExpression = - argc == 3 && std::string_view(argv[1]) == "--native-expression"; - const bool dumpIds = argc == 3 && std::string_view(argv[1]) == "--dump-ids"; - if (nativeExpression) { - const std::string source = argv[2]; - const auto started = std::chrono::steady_clock::now(); - const auto &model = Felidae::felidaeSentencePieceModel(); - const auto modelReady = std::chrono::steady_clock::now(); - Felidae::IntegerTokenList tokens(model, source); - const auto encoded = std::chrono::steady_clock::now(); - Felidae::IntegerParser parser(tokens); - const auto ir = parser.compileExpressionIr(); - const auto compiled = std::chrono::steady_clock::now(); - Felidae::IrVerifier::verify(ir); - const auto verified = std::chrono::steady_clock::now(); - class NoRuntime final : public Felidae::VmRuntime { - public: - void installIrModule(const Felidae::IrModule &) override {} - Felidae::IrSymbolRef - resolveSymbol(Felidae::IrSymbolRef symbol) const override { - return symbol; - } - } runtime; - constexpr Felidae::IrSymbolRef entry = 1; - Felidae::IrModule module; - module.entryProcedure = entry; - module.ir.registerCount = 1; - module.ir.symbols = {entry}; - module.ir.words = { - static_cast(Felidae::IrOpcode::Call), - 0, - 0, - 0, - static_cast(Felidae::IrOpcode::Return), - 0, - 0, - static_cast(Felidae::IrOpcode::End), - }; - module.procedures.emplace(entry, Felidae::IrProcedure{ir, {}, {}, {}}); - auto largestSymbol = entry; - for (const auto symbol : ir.symbols) - largestSymbol = std::max(largestSymbol, symbol); - module.sentencePieceModelIdentity = "sha256:benchmark"; - module.symbolTable.reserve(largestSymbol); - for (Felidae::IrSymbolRef symbol = 1; symbol <= largestSymbol; ++symbol) { - module.symbolTable.push_back({symbol}); - } - Felidae::RegisterVm vm; - (void)vm.executeMain(Felidae::verifyIrModule(std::move(module)), runtime, - Felidae::VmNil{}); - const auto executed = std::chrono::steady_clock::now(); - const auto micros = [](auto begin, auto end) { - return std::chrono::duration_cast(end - begin) - .count(); - }; - std::cout << "{\"mode\":\"native-expression\"" - << ",\"tokenCount\":" << tokens.entries().size() - << ",\"modelInitMicros\":" << micros(started, modelReady) - << ",\"sourceEncodeMicros\":" << micros(modelReady, encoded) - << ",\"irCompileMicros\":" << micros(encoded, compiled) - << ",\"verifyMicros\":" << micros(compiled, verified) - << ",\"vmMicros\":" << micros(verified, executed) - << ",\"totalMicros\":" << micros(started, executed) << "}\n"; - return 0; - } - const int sourceArgument = dumpIds ? 2 : 1; - if (argc != 2 && !dumpIds) { - std::cerr - << "usage: felidae_integer_parser_benchmark [--dump-ids] \n" - << " felidae_integer_parser_benchmark --native-expression " - "\n"; - return 2; - } - std::ifstream input(argv[sourceArgument], std::ios::binary); - if (!input) - throw std::runtime_error("cannot open benchmark source"); - const std::string source((std::istreambuf_iterator(input)), {}); - - const auto started = std::chrono::steady_clock::now(); - const auto modelStarted = started; - const auto &model = Felidae::felidaeSentencePieceModel(); - const auto modelReady = std::chrono::steady_clock::now(); - Felidae::IntegerTokenList tokens(model, source); - const auto encoded = std::chrono::steady_clock::now(); - if (dumpIds) { - for (const auto &entry : tokens.entries()) { - std::cout << entry.id << '\t' << entry.begin << '\t' << entry.end << '\t' - << Felidae::builtinTokenSpelling(entry.id) << '\n'; - } - return 0; - } - // The benchmark must exercise the same single parser path as runtime: - // declarations register their compiled ID anchors before later uses in - // the same source stream are assembled. - auto operators = std::make_shared(); - Felidae::IntegerParser parser(tokens, std::move(operators)); - const auto program = parser.parseProgram(); - const auto finished = std::chrono::steady_clock::now(); - const auto micros = [](auto begin, auto end) { - return std::chrono::duration_cast(end - begin) - .count(); - }; - const auto &metrics = parser.metrics(); - std::cout << "{\"encodeCount\":" << metrics.sourceEncodeCount - << ",\"tokenCount\":" << tokens.entries().size() - << ",\"statementCount\":" << program.statements.size() - << ",\"modelInitMicros\":" << micros(modelStarted, modelReady) - << ",\"sourceEncodeMicros\":" << micros(modelReady, encoded) - << ",\"parseMicros\":" << micros(encoded, finished) - << ",\"totalMicros\":" << micros(started, finished) - << ",\"iterations\":" << metrics.iterations - << ",\"peakRecursionDepth\":" << metrics.peakRecursionDepth - << ",\"backtrackingAttempts\":" << metrics.backtrackingAttempts - << "}\n"; -} diff --git a/tools/ReasoningBenchmark.cpp b/tools/ReasoningBenchmark.cpp deleted file mode 100644 index 35faa5e..0000000 --- a/tools/ReasoningBenchmark.cpp +++ /dev/null @@ -1,127 +0,0 @@ -#include "CompilerFrontend.h" -#include "SentencePieceModel.h" -#include "form/BinaryIr.h" -#include "form/RegisterVm.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -using Clock = std::chrono::steady_clock; - -std::string jsonEscape(std::string_view value) { - std::string escaped; - escaped.reserve(value.size() + 16); - for (const char character : value) { - switch (character) { - case '\\': escaped += "\\\\"; break; - case '"': escaped += "\\\""; break; - case '\n': escaped += "\\n"; break; - case '\r': escaped += "\\r"; break; - case '\t': escaped += "\\t"; break; - default: escaped += character; break; - } - } - return escaped; -} - -std::int64_t micros(Clock::time_point begin, Clock::time_point end) { - return std::chrono::duration_cast(end - begin).count(); -} - -std::int64_t percentile(std::vector values, double fraction) { - if (values.empty()) return 0; - std::sort(values.begin(), values.end()); - const auto index = static_cast(fraction * static_cast(values.size() - 1)); - return values[index]; -} - -} // namespace - -int main(int argc, char** argv) { - try { - std::size_t iterations = 1; - std::filesystem::path source; - std::vector expected; - for (int index = 1; index < argc; ++index) { - const std::string_view argument(argv[index]); - if (argument == "--iterations") { - if (++index == argc) throw std::runtime_error("--iterations requires a value"); - const auto parsed = std::stoull(argv[index]); - if (parsed == 0 || parsed > 10000) { - throw std::runtime_error("iterations must be in [1, 10000]"); - } - iterations = static_cast(parsed); - } else if (argument == "--expect") { - if (++index == argc) throw std::runtime_error("--expect requires display text"); - expected.emplace_back(argv[index]); - } else if (source.empty()) { - source = argv[index]; - } else { - throw std::runtime_error("unexpected argument: " + std::string(argument)); - } - } - if (source.empty()) { - std::cerr << "usage: felidae_reasoning_benchmark [--iterations N]" - " [--expect text]...\n"; - return 2; - } - - const auto compileStarted = Clock::now(); - const auto ir = Felidae::verifyIrModule(Felidae::compileProgramFileToIr(source)); - const auto decoder = [](std::span pieces) { - std::vector ids(pieces.begin(), pieces.end()); - std::string text; - if (!Felidae::felidaeSentencePieceModel().Decode(ids, &text).ok()) throw Felidae::IrError("cannot decode benchmark value"); - return text; - }; - const auto display = Felidae::makeIrDisplayContext(ir, decoder); - const auto compileFinished = Clock::now(); - - std::vector executionMicros; - executionMicros.reserve(iterations); - std::string baseline; - bool deterministic = true; - for (std::size_t iteration = 0; iteration < iterations; ++iteration) { - Felidae::FelidaeKnowledgeRuntime runtime; - const auto started = Clock::now(); - const auto result = Felidae::RegisterVm{}.executeMain(ir, runtime); - const auto finished = Clock::now(); - executionMicros.push_back(micros(started, finished)); - const auto rendered = Felidae::vmValueToDisplayString(result, display); - if (iteration == 0) baseline = rendered; - else deterministic = deterministic && rendered == baseline; - } - - bool expectationsPassed = true; - for (const auto& needle : expected) { - expectationsPassed = expectationsPassed && baseline.find(needle) != std::string::npos; - } - const auto total = std::accumulate( - executionMicros.begin(), executionMicros.end(), std::int64_t{0}); - const auto mean = total / static_cast(executionMicros.size()); - std::cout << "{\"schema_version\":1" - << ",\"source\":\"" << jsonEscape(source.generic_string()) << "\"" - << ",\"iterations\":" << iterations - << ",\"compile_micros\":" << micros(compileStarted, compileFinished) - << ",\"vm_mean_micros\":" << mean - << ",\"vm_median_micros\":" << percentile(executionMicros, 0.50) - << ",\"vm_p95_micros\":" << percentile(executionMicros, 0.95) - << ",\"deterministic\":" << (deterministic ? "1.0" : "0.0") - << ",\"expectations_passed\":" << (expectationsPassed ? "1.0" : "0.0") - << ",\"result\":\"" << jsonEscape(baseline) << "\"}\n"; - return deterministic && expectationsPassed ? 0 : 1; - } catch (const std::exception& error) { - std::cerr << "reasoning benchmark error: " << error.what() << '\n'; - return 1; - } -} diff --git a/tools/TrainMixfixGru.cpp b/tools/TrainMixfixGru.cpp deleted file mode 100644 index 4febef1..0000000 --- a/tools/TrainMixfixGru.cpp +++ /dev/null @@ -1,392 +0,0 @@ -#include "MixfixStateModel.h" -#include "MixfixTraining.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace { - -std::vector ids(const nlohmann::json &record, const char *field) { - if (!record.contains(field) || !record.at(field).is_array() || - record.at(field).empty()) { - throw std::runtime_error( - std::string("mixfix JSONL record requires non-empty ") + field); - } - std::vector result; - for (const auto &value : record.at(field)) { - if (!value.is_number_unsigned() || - value.get() > - static_cast( - std::numeric_limits::max())) { - throw std::runtime_error(std::string("mixfix JSONL ") + field + - " must contain non-negative integer IDs"); - } - result.push_back(static_cast(value.get())); - } - return result; -} - -std::vector datasetPaths(std::string_view encoded) { - constexpr char separator = '\x1f'; - std::vector paths; - std::size_t begin = 0; - while (begin <= encoded.size()) { - const auto end = encoded.find(separator, begin); - const auto segment = encoded.substr(begin, end == std::string_view::npos - ? encoded.size() - begin - : end - begin); - if (segment.empty()) - throw std::runtime_error( - "mixfix training dataset list contains an empty path"); - paths.emplace_back(segment); - if (end == std::string_view::npos) - break; - begin = end + 1; - } - return paths; -} - -} // namespace - -int Felidae::runMixfixGruTraining(int argc, char **argv) { - // JSONL records: {"input_ids":[...],"target_ids":[...]}. The target - // sequence includes the finite IR_END vocabulary token. - if (argc != 9) { - std::cerr << "internal error: compiler training arguments are invalid\n"; - return 2; - } - try { - const auto dataPaths = datasetPaths(argv[1]); - const auto outputDirectory = std::filesystem::path(argv[2]); - for (const auto &dataPath : dataPaths) { - if (dataPath.extension() != ".jsonl") - throw std::runtime_error( - "mixfix training dataset must use the .jsonl extension"); - } - Felidae::GruMixfixStateModel::Configuration config; - config.inputVocabularySize = std::stoll(argv[3]); - config.outputVocabularySize = std::stoll(argv[4]); - config.beginToken = std::stoll(argv[5]); - config.allowRandomInitialization = true; - const auto epochs = std::stoull(argv[6]); - const auto learningRate = std::stod(argv[7]); - if (config.inputVocabularySize <= 0 || config.outputVocabularySize <= 0 || - config.beginToken < 0 || - config.beginToken >= config.outputVocabularySize || epochs == 0 || - learningRate <= 0.0) { - throw std::runtime_error("mixfix training configuration is invalid"); - } - // The public compiler command obtains this value from its pinned - // SentencePiece model before crossing into the isolated LibTorch - // training library. Do not include generated Protobuf types here: - // LibTorch and SentencePiece intentionally own separate dependencies. - if (config.outputVocabularySize != - static_cast(Felidae::kMixfixStructuralVocabularySize)) { - throw std::runtime_error( - "mixfix output vocabulary must match the fixed structural IR " - "vocabulary (expected " + - std::to_string(Felidae::kMixfixStructuralVocabularySize) + ")"); - } - const std::string expectedSentencePieceIdentity(argv[8]); - if (!expectedSentencePieceIdentity.starts_with("sha256:") || - expectedSentencePieceIdentity.size() != 71) { - throw std::runtime_error( - "compiler training requires an exact SHA-256 SentencePiece identity"); - } - struct Sample { - std::vector input; - std::vector target; - Felidae::MixfixIrTokenKind decision = Felidae::MixfixIrTokenKind::Accept; - }; - std::vector samples; - std::size_t rejectedRecords = 0; - std::size_t abstainedRecords = 0; - for (const auto &dataPath : dataPaths) { - std::ifstream dataset(dataPath); - if (!dataset) - throw std::runtime_error("cannot open mixfix dataset: " + - dataPath.string()); - std::string line; - while (std::getline(dataset, line)) { - if (line.empty()) - continue; - const auto record = nlohmann::json::parse(line); - if (!record.is_object()) - throw std::runtime_error("mixfix JSONL record must be an object"); - if (!record.contains("schema_version") || - !record.at("schema_version").is_number_unsigned() || - record.at("schema_version").get() != 3) { - throw std::runtime_error( - "mixfix JSONL schema version is incompatible"); - } - if (!record.contains("sentencepiece_model_identity") || - !record.at("sentencepiece_model_identity").is_string() || - record.at("sentencepiece_model_identity").get() != - expectedSentencePieceIdentity) { - throw std::runtime_error( - "mixfix JSONL was generated by a different SentencePiece model"); - } - if (!record.contains("compiler_ir_vocabulary") || - !record.at("compiler_ir_vocabulary").is_string() || - record.at("compiler_ir_vocabulary").get() != - Felidae::kMixfixIrVocabularyVersion) { - throw std::runtime_error( - "mixfix JSONL compiler IR vocabulary is incompatible"); - } - const auto input = ids(record, "input_ids"); - if (input.empty()) - throw std::runtime_error("mixfix JSONL input_ids cannot be empty"); - for (const auto id : input) { - if (id < 0 || id >= config.inputVocabularySize) { - throw std::runtime_error("mixfix JSONL input ID exceeds the " - "configured SentencePiece vocabulary"); - } - } - if (record.contains("rejection_stage")) { - if (!record.contains("target_ids")) - throw std::runtime_error( - "mixfix rejection record requires a REJECT teacher target"); - ++rejectedRecords; - } - auto target = ids(record, "target_ids"); - if (target.empty()) - throw std::runtime_error("mixfix JSONL target_ids cannot be empty"); - for (const auto id : target) { - if (id < 0 || id >= config.outputVocabularySize) { - throw std::runtime_error("mixfix JSONL target ID exceeds the " - "configured structural vocabulary"); - } - } - const auto vocabulary = - Felidae::makeMixfixContext(Felidae::FelidaeIr{}).outputVocabulary; - const auto firstKind = - vocabulary.at(static_cast(target.front())).kind; - const auto declaredDecision = record.value("decision", std::string{}); - if (record.contains("rejection_stage")) { - if (declaredDecision != "REJECT" || target.size() != 1 || - firstKind != Felidae::MixfixIrTokenKind::Reject) { - throw std::runtime_error( - "mixfix rejection record target must be exactly REJECT"); - } - } else if (declaredDecision == "ABSTAIN") { - if (target.size() != 1 || - firstKind != Felidae::MixfixIrTokenKind::Abstain) { - throw std::runtime_error( - "mixfix abstention record target must be exactly ABSTAIN"); - } - ++abstainedRecords; - } else { - if (!declaredDecision.empty() && declaredDecision != "ACCEPT") { - throw std::runtime_error( - "mixfix JSONL decision must be ACCEPT, REJECT, or ABSTAIN"); - } - if (firstKind != Felidae::MixfixIrTokenKind::Accept) { - throw std::runtime_error( - "mixfix executable teacher target must begin with ACCEPT"); - } - } - Sample sample; - sample.input.assign(input.begin(), input.end()); - sample.target = std::move(target); - sample.decision = firstKind; - samples.push_back(std::move(sample)); - } - } - if (samples.size() < 5) { - throw std::runtime_error("mixfix dataset needs at least five corpus " - "samples for a held-out validation split"); - } - - // Seed before allocation so this explicit training command is - // reproducible. Existing artifacts are never implicit checkpoints: - // a resumed run must be a separate, deliberate trainer feature. - torch::manual_seed(0); - const auto artifact = outputDirectory / "mixfix-gru.pt"; - const auto checkpoint = outputDirectory / "mixfix-gru.ckpt"; - Felidae::GruMixfixStateModel model(config); - std::mt19937 generator(0); - // Keep one complete structural target shape in exactly one partition. - // A random record split makes generated numeric variations of the same - // mixfix form appear in both sets, which makes validation loss look - // better than the model's ability to generalize to another form. - std::map, std::vector> - targetFamilies; - for (std::size_t index = 0; index < samples.size(); ++index) { - targetFamilies[samples[index].target].push_back(index); - } - if (targetFamilies.size() < 3) - throw std::runtime_error( - "mixfix dataset requires at least three structural families for " - "train/validation/test splits"); - std::vector *> familyOrder; - for (auto &[target, family] : targetFamilies) { - (void)target; - familyOrder.push_back(&family); - } - std::shuffle(familyOrder.begin(), familyOrder.end(), generator); - std::vector training, validation, test; - std::size_t heldOutIndex = 0; - const auto splitDecisionFamily = [&](std::vector &family) { - std::shuffle(family.begin(), family.end(), generator); - if (family.size() < 3) { - training.insert(training.end(), family.begin(), family.end()); - return; - } - test.push_back(family[0]); - validation.push_back(family[1]); - training.insert(training.end(), family.begin() + 2, family.end()); - }; - for (auto *family : familyOrder) { - const auto decision = samples[family->front()].decision; - if (decision != Felidae::MixfixIrTokenKind::Accept) { - // REJECT and ABSTAIN share one-token structural targets, so a - // target-family-only split would leave safety unmeasured. - splitDecisionFamily(*family); - continue; - } - auto *destination = &training; - const auto partition = heldOutIndex++ % 10; - if (partition == 0) - destination = &test; - else if (partition == 1) - destination = &validation; - destination->insert(destination->end(), family->begin(), family->end()); - } - if (training.empty() || validation.empty() || test.empty()) - throw std::runtime_error( - "mixfix structural-family split produced an empty partition"); - std::cout << "datasets=" << dataPaths.size() - << " samples=" << samples.size() - << " rejection_records=" << rejectedRecords - << " abstention_records=" << abstainedRecords - << " structural_families=" << targetFamilies.size() - << " training=" << training.size() - << " validation=" << validation.size() << " test=" << test.size() - << "\n"; - const auto evaluationContext = - Felidae::makeMixfixContext(Felidae::FelidaeIr{}); - for (std::size_t epoch = 0; epoch < epochs; ++epoch) { - const auto epochStarted = std::chrono::steady_clock::now(); - std::shuffle(training.begin(), training.end(), generator); - double total = 0.0; - for (const auto index : training) { - const auto &sample = samples[index]; - total += - model.trainTeacherForced(sample.input, sample.target, learningRate); - } - double validationLoss = 0.0; - std::size_t exactSequences = 0; - std::size_t correctDecisions = 0; - std::size_t invalidSequences = 0; - for (const auto index : validation) { - const auto &sample = samples[index]; - validationLoss += - model.evaluateTeacherForced(sample.input, sample.target); - try { - const auto decoded = model.transform(sample.input, evaluationContext); - std::vector expected; - expected.reserve(sample.target.size()); - for (const auto token : sample.target) { - expected.push_back(static_cast(token)); - } - if (!decoded.empty() && decoded.front() == expected.front()) - ++correctDecisions; - if (decoded == expected) - ++exactSequences; - } catch (const Felidae::IrError &) { - ++invalidSequences; - } - } - const auto epochSeconds = - std::chrono::duration(std::chrono::steady_clock::now() - - epochStarted) - .count(); - std::cout << "epoch=" << (epoch + 1) - << " train_loss=" << (total / training.size()) - << " validation_loss=" << (validationLoss / validation.size()) - << " decision_accuracy=" << correctDecisions << '/' - << validation.size() - << " autoregressive_exact=" << exactSequences << '/' - << validation.size() - << " invalid_autoregressive=" << invalidSequences << '/' - << validation.size() << " seconds=" << epochSeconds - << " train_samples_per_second=" - << (epochSeconds > 0.0 - ? static_cast(training.size()) / epochSeconds - : 0.0) - << "\n"; - } - double testLoss = 0.0; - std::size_t testExact = 0, testDecisions = 0, testInvalid = 0; - for (const auto index : test) { - const auto &sample = samples[index]; - testLoss += model.evaluateTeacherForced(sample.input, sample.target); - try { - const auto decoded = model.transform(sample.input, evaluationContext); - std::vector expected; - for (const auto value : sample.target) - expected.push_back(static_cast(value)); - if (!decoded.empty() && decoded.front() == expected.front()) - ++testDecisions; - if (decoded == expected) - ++testExact; - } catch (const Felidae::IrError &) { - ++testInvalid; - } - } - std::cout << "test_loss=" << (testLoss / test.size()) - << " decision_accuracy=" << testDecisions << '/' << test.size() - << " autoregressive_exact=" << testExact << '/' << test.size() - << " invalid_autoregressive=" << testInvalid << '/' << test.size() - << "\n"; - std::filesystem::create_directories(outputDirectory); - model.saveCheckpoint(checkpoint); - model.exportTorchScript(artifact); - std::ofstream manifest(outputDirectory / "manifest.txt", std::ios::trunc); - if (!manifest) - throw std::runtime_error("cannot write compiler model manifest"); - manifest << "artifact_format_version=" - << Felidae::kMixfixArtifactFormatVersion << "\n" - << "model_family=" << Felidae::kMixfixModelFamily << "\n" - << "model_version=" << Felidae::kMixfixModelVersion << "\n" - << "backend=torchscript-gru\n" - << "tokenizer_contract=" << Felidae::kMixfixTokenizerContract - << "\n" - << "sentencepiece_model_identity=" << expectedSentencePieceIdentity - << "\n" - << "ir_vocabulary_version=" << Felidae::kMixfixIrVocabularyVersion - << "\n" - << "decoder_contract=" << Felidae::kMixfixDecoderContract << "\n" - << "input_vocabulary=" << config.inputVocabularySize << "\n" - << "output_vocabulary=" << config.outputVocabularySize << "\n" - << "begin_token=" << config.beginToken << "\n" - << "embedding_size=" << config.embeddingSize << "\n" - << "hidden_size=" << config.hiddenSize << "\n" - << "layer_count=" << config.layerCount << "\n"; - manifest.close(); - if (!manifest) - throw std::runtime_error("cannot finalize compiler model manifest"); - auto verified = Felidae::GruMixfixStateModel::loadVersioned( - config, outputDirectory, expectedSentencePieceIdentity); - (void)verified; - std::cout << std::filesystem::absolute(artifact).lexically_normal().string() - << "\n"; - return 0; - } catch (const std::exception &error) { - std::cerr << "error: " << error.what() << "\n"; - return 1; - } -} diff --git a/tools/TrainRuntimeGru.cpp b/tools/TrainRuntimeGru.cpp deleted file mode 100644 index 8cf9f1f..0000000 --- a/tools/TrainRuntimeGru.cpp +++ /dev/null @@ -1,221 +0,0 @@ -#include "SentencePieceModel.h" -#include "form/RuntimeStateModel.h" -#include "form/RuntimeTraining.h" -#include "form/RuntimeTrainingCommand.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace { -using namespace Felidae; - -std::size_t targetFor(const RuntimeTrainingRecord &record, - const std::vector &vocabulary) { - const auto matches = [&](const RuntimeOutputToken &token) { - switch (record.targetKind) { - case RuntimeTrainingTargetKind::InputReference: - return token.kind == RuntimeOutputTokenKind::InputReference; - case RuntimeTrainingTargetKind::FactFromInput: - return token.kind == RuntimeOutputTokenKind::FactFromInput; - case RuntimeTrainingTargetKind::DegreeMilli: - return token.kind == RuntimeOutputTokenKind::DegreeMilli; - case RuntimeTrainingTargetKind::Nil: - return token.kind == RuntimeOutputTokenKind::Nil; - case RuntimeTrainingTargetKind::NumericTruth: - return token.kind == RuntimeOutputTokenKind::NumericTruth; - case RuntimeTrainingTargetKind::Score: - return false; - } - return false; - }; - for (std::size_t i = 0; i < vocabulary.size(); ++i) { - const auto &token = vocabulary[i]; - if (matches(token) && token.value == record.targetValue) - return i; - } - throw IrError( - "runtime dataset result has no permitted finite GRU action target"); -} -} // namespace - -int Felidae::runRuntimeGruTraining(int argc, char **argv) { - try { - if (argc < 3 || argc > 5) { - throw std::runtime_error( - "internal error: VM training arguments are invalid"); - } - const auto records = Felidae::loadRuntimeTrainingDataset(argv[1]); - if (records.size() < 10) - throw Felidae::IrError( - "runtime training dataset requires at least ten records"); - const std::size_t epochs = argc >= 4 ? std::stoull(argv[3]) : 8; - const double rate = argc == 5 ? std::stod(argv[4]) : 0.001; - if (epochs == 0 || rate <= 0.0) - throw Felidae::IrError("runtime training options are invalid"); - auto vocabulary = Felidae::defaultRuntimeOutputVocabulary(); - Felidae::GruRuntimeStateModel::Configuration configuration; - configuration.inputVocabularySize = - felidaeSentencePieceModel().GetPieceSize() + - kRuntimeStructuralInputTokens; - configuration.outputVocabularySize = - static_cast(vocabulary.size()); - configuration.allowRandomInitialization = true; - // Explicit CPU-first reproducibility: data ordering plus this seed - // makes a repeated C++ training run comparable before benchmarking. - torch::manual_seed(0); - Felidae::GruRuntimeStateModel model(configuration, vocabulary); - std::mt19937_64 random(0); - // Split whole operation/input-shape/action families. A random - // record-level split lets repeated context templates into multiple - // partitions and therefore overstates generalization. - using StructuralFamily = - std::tuple, std::size_t>; - using EvaluationBucket = std::pair; - std::map> families; - for (std::size_t index = 0; index < records.size(); ++index) { - families[{records[index].operationId, records[index].inputKinds, - records[index].targetKind == RuntimeTrainingTargetKind::Score - ? vocabulary.size() - : targetFor(records[index], vocabulary)}] - .push_back(index); - } - if (families.size() < 3) - throw Felidae::IrError( - "runtime dataset requires at least three operation/action families " - "for train/validation/test splits"); - std::vector *> familyOrder; - for (auto &[bucket, family] : families) { - (void)bucket; - familyOrder.push_back(&family); - } - std::shuffle(familyOrder.begin(), familyOrder.end(), random); - std::vector training, validation, test; - for (std::size_t familyIndex = 0; familyIndex < familyOrder.size(); - ++familyIndex) { - auto &destination = familyIndex % 10 == 0 ? test - : familyIndex % 10 == 1 ? validation - : training; - destination.insert(destination.end(), familyOrder[familyIndex]->begin(), - familyOrder[familyIndex]->end()); - } - if (training.empty() || validation.empty() || test.empty()) - throw Felidae::IrError( - "runtime structural-family split produced an empty partition"); - std::cout << "records=" << records.size() - << " structural_families=" << families.size() - << " training=" << training.size() - << " validation=" << validation.size() << " test=" << test.size() - << "\n"; - for (std::size_t epoch = 0; epoch < epochs; ++epoch) { - const auto epochStarted = std::chrono::steady_clock::now(); - std::shuffle(training.begin(), training.end(), random); - double totalLoss = 0.0; - for (const auto index : training) { - const auto &record = records[index]; - totalLoss += record.targetKind == RuntimeTrainingTargetKind::Score - ? model.trainScore(record, rate) - : model.trainTeacherForced( - record, targetFor(record, vocabulary), rate); - } - std::size_t correct = 0; - std::size_t validationClassifications = 0; - std::size_t scoreCount = 0; - double scoreAbsoluteError = 0.0; - std::map> - bucketMetrics; - for (const auto index : validation) { - const auto &record = records[index]; - if (record.targetKind == RuntimeTrainingTargetKind::Score) { - scoreAbsoluteError += - std::abs(model.predictScore(record) - record.targetScore); - ++scoreCount; - continue; - } - const auto target = targetFor(record, vocabulary); - ++validationClassifications; - const auto predicted = model.predictTeacherToken(record); - auto &metric = bucketMetrics[{record.operationId, target}]; - ++metric.second; - correct += predicted == target ? 1 : 0; - if (predicted == target) - ++metric.first; - } - const auto epochSeconds = - std::chrono::duration(std::chrono::steady_clock::now() - - epochStarted) - .count(); - std::cout << "epoch=" << (epoch + 1) - << " train_loss=" << (totalLoss / training.size()) - << " validation_accuracy=" - << (validationClassifications - ? static_cast(correct) / - validationClassifications - : 0.0) - << " validation_score_mae=" - << (scoreCount ? scoreAbsoluteError / scoreCount : 0.0) - << " seconds=" << epochSeconds << " train_samples_per_second=" - << (epochSeconds > 0.0 - ? static_cast(training.size()) / epochSeconds - : 0.0) - << "\n"; - for (const auto &[bucket, metric] : bucketMetrics) { - std::cout << " validation_operation=" << bucket.first - << " target_token=" << bucket.second - << " correct=" << metric.first << '/' << metric.second - << "\n"; - } - } - std::size_t testCorrect = 0; - std::size_t testClassifications = 0; - std::size_t testScores = 0; - double testScoreAbsoluteError = 0.0; - for (const auto index : test) { - const auto &record = records[index]; - if (record.targetKind == RuntimeTrainingTargetKind::Score) { - testScoreAbsoluteError += - std::abs(model.predictScore(record) - record.targetScore); - ++testScores; - } else { - ++testClassifications; - testCorrect += - model.predictTeacherToken(record) == targetFor(record, vocabulary) - ? 1u - : 0u; - } - } - std::cout << "test_accuracy=" - << (testClassifications - ? static_cast(testCorrect) / testClassifications - : 0.0) - << " correct=" << testCorrect << '/' << testClassifications - << " test_score_mae=" - << (testScores ? testScoreAbsoluteError / testScores : 0.0) - << " score_records=" << testScores << "\n"; - const std::filesystem::path output(argv[2]); - std::filesystem::create_directories(output); - model.saveCheckpoint(output / "runtime-gru.ckpt"); - const auto sentencePieceIdentity = felidaeSentencePieceModelIdentity(); - model.exportTorchScript(output / "runtime-gru.pt", sentencePieceIdentity); - // Treat export as successful only when the production manifest gate - // can load these exact weights again. - auto verified = Felidae::GruRuntimeStateModel::loadVersioned( - configuration, vocabulary, output, sentencePieceIdentity); - (void)verified; - std::cout << std::filesystem::absolute(output / "runtime-gru.pt") - .lexically_normal() - .string() - << "\n"; - return 0; - } catch (const std::exception &error) { - std::cerr << "error: " << error.what() << "\n"; - return 1; - } -} diff --git a/v2_examples/class_association_reasoning.fx b/v2_examples/class_association_reasoning.fx index c4bce32..2b3e8a0 100644 --- a/v2_examples/class_association_reasoning.fx +++ b/v2_examples/class_association_reasoning.fx @@ -1,5 +1,5 @@ -# Classes are compiler-only fact schemas. Mixfix methods produce ordinary -# Association facts that remain queryable through the standard fact DML API. +# Classes declare direct-interpreter fact schemas. Mixfix methods produce +# ordinary Association facts queryable through the standard fact API. class Person id: number name: string @@ -35,9 +35,7 @@ worksAt() => end main() => - people := fx.cast_(Person.all()) - companies := fx.cast_(Company.all()) - person := people.get(position: 0) - company := companies.get(position: 0) + person := Person.get(pos: 0) + company := Company.get(pos: 0) return person works at company end diff --git a/v2_examples/csv_fact_database.fx b/v2_examples/csv_fact_database.fx index e67ae1e..7efff84 100644 --- a/v2_examples/csv_fact_database.fx +++ b/v2_examples/csv_fact_database.fx @@ -1,5 +1,5 @@ -# CSV enters the VM as native School facts. Concrete fact-type queries use the -# same retained knowledge store; DML writes owned CSV facts back automatically. +# CSV facts enter the direct interpreter's retained knowledge store. Concrete +# fact-type queries and language-level mutations use the same FactMemory path. import "csv" diff --git a/v2_examples/end_then_pipeline.fx b/v2_examples/end_then_pipeline.fx index 13b6d8a..9443c32 100644 --- a/v2_examples/end_then_pipeline.fx +++ b/v2_examples/end_then_pipeline.fx @@ -1,6 +1,5 @@ -# Optional `end` delimiters make every nested decision and method boundary -# explicit. The existing `then` pipeline remains an expression; `end` adds no -# executable operation and is consumed while constructing compiler HIR. +# Explicit `end` delimiters close methods and nested decisions while the AST +# interpreter preserves the existing `then` pipeline semantics. increment(value: number) => return value + 1 diff --git a/v2_examples/form_core_concepts.fx b/v2_examples/form_core_concepts.fx deleted file mode 100644 index 6fe6f79..0000000 --- a/v2_examples/form_core_concepts.fx +++ /dev/null @@ -1,59 +0,0 @@ -# Core Form/IR workload: no imports, native services, queries, or mixfix. -# It intentionally exercises the language constructs that the source compiler -# must eventually lower into one verified, standalone .bin module. - -Person(name: "unknown", age: 0, active: 0.0) -Employee extend Person(name: "unknown", age: 0, active: 1.0, role: "staff") -Engineer extend Employee(name: "unknown", age: 0, active: 1.0, role: "engineer", level: 1) - -increment(value: number) => - return value + 1 - -double(value: number) => - return value * 2 - -scoreFor(age: number, level: number) => - base := double(value: age) - return base + level - -factorial(value: number) => - if value <= 1 then - return 1 - else - previous := factorial(value: value - 1) - return value * previous - -makeEngineer(name: string, age: number, level: number) => - score := scoreFor(age: age, level: level) - return Engineer( - name: name, - age: age, - active: 1.0, - role: "engineer", - level: level, - score: score - ) - -makeReport(person: Person, sequence: number) => - next := increment(value: sequence) - return { - next: next, - tags: ["core", "form", "ir"], - metrics: { - sequence: sequence, - factorial: factorial(value: 5) - } - } - -main() => - ada := makeEngineer(name: "Ada", age: 32, level: 4) - grace := makeEngineer(name: "Grace", age: 37, level: 5) - adaReport := makeReport(person: ada, sequence: 1) - graceReport := makeReport(person: grace, sequence: 2) - return { - family: "Person/Employee/Engineer", - people: [ada, grace], - reports: [adaReport, graceReport], - totalScore: scoreFor(age: 32, level: 4) + scoreFor(age: 37, level: 5), - recursiveCheck: factorial(value: 6) - } diff --git a/v2_examples/fx_fact_database.fx b/v2_examples/fx_fact_database.fx index 3081006..a7f5ce5 100644 --- a/v2_examples/fx_fact_database.fx +++ b/v2_examples/fx_fact_database.fx @@ -1,7 +1,5 @@ -# A fact-only .fx file is DDL data linked by the compiler. Imported rows keep -# source ownership, so conditional insert/update/delete operations can persist -# them automatically. This example is read-only to keep the checked-in dataset -# deterministic; copy the database under build/ before experimenting with DML. +# A fact-only .fx file is loaded directly into FactMemory. This example is +# read-only to keep the checked-in dataset deterministic. import "../datasets/examples/schools.fx" main() => diff --git a/v2_examples/mixfix_deep_ir_nesting.fx b/v2_examples/mixfix_deep_ir_nesting.fx deleted file mode 100644 index d26a6ca..0000000 --- a/v2_examples/mixfix_deep_ir_nesting.fx +++ /dev/null @@ -1,25 +0,0 @@ -# Deep, executable mixfix nesting. Every annotation has an explicit method -# parameter list, so nested captures lower to ordinary Call IR rather than an -# interpreter-only implicit-capture environment. - -@mixfix(pattern: "{left: number} blend {right: number}") -blend(left: number, right: number) => - return left + right - -@mixfix(pattern: "combine {left: number} with {right: number}") -combine(left: number, right: number) => - return left * right - -@mixfix(pattern: "scale {value: number} by {factor: number}") -scale(value: number, factor: number) => - return value * factor - -@mixfix(pattern: "offset {value: number} by {amount: number}") -offset(value: number, amount: number) => - return value + amount - -main() => - leaf := 4 blend 5 - branch := combine (1 blend 2) with (3 blend leaf) - deep := scale (combine branch with (offset (2 blend 3) by (1 blend 1))) by (2 blend 1) - return (leaf: leaf, branch: branch, deep: deep) diff --git a/v2_examples/mixfix_fuzzy_fact_report.fx b/v2_examples/mixfix_fuzzy_fact_report.fx index 9732462..05d93b1 100644 --- a/v2_examples/mixfix_fuzzy_fact_report.fx +++ b/v2_examples/mixfix_fuzzy_fact_report.fx @@ -1,4 +1,4 @@ -# Strict-IR expert-system baseline. The declarations model hierarchy and +# Direct-interpreter expert-system baseline. The declarations model hierarchy and # time/priority provenance; the returned values remain numeric Degrees/facts, # never implicit booleans. diff --git a/v2_examples/mixfix_ir_roundtrip.fx b/v2_examples/mixfix_ir_roundtrip.fx deleted file mode 100644 index 36be4e3..0000000 --- a/v2_examples/mixfix_ir_roundtrip.fx +++ /dev/null @@ -1,9 +0,0 @@ -# A strict-IR mixfix baseline: captures are explicit procedure parameters. -# It exercises the same Call IR path as a conventional method call. - -@mixfix(pattern: "{left: number} combine {right: number}") -combineValue(left: number, right: number) => - return left + right - -main() => - return 17 combine 25 diff --git a/v2_examples/optional_end_blocks.fx b/v2_examples/optional_end_blocks.fx index 42a2642..68fe6cb 100644 --- a/v2_examples/optional_end_blocks.fx +++ b/v2_examples/optional_end_blocks.fx @@ -1,6 +1,5 @@ -# `end` is an optional contextual block delimiter. It is useful when nested -# control flow would otherwise rely only on indentation. It creates no HIR or -# VM operation: the parser consumes it at method/if boundaries. +# `end` is an explicit contextual block delimiter for nested direct AST +# control flow. It adds no runtime operation. classify(value: number) => if value > 10 then diff --git a/v2_examples/runtime_ssm_e2e.fx b/v2_examples/runtime_ssm_e2e.fx deleted file mode 100644 index cee14ae..0000000 --- a/v2_examples/runtime_ssm_e2e.fx +++ /dev/null @@ -1,3 +0,0 @@ -# End-to-end runtime SSM fixture: the learned Identity operation must preserve -# the exact numeric input through verified FELBIR and the register VM. -main() => return semantic_identity(42). diff --git a/v2_examples/sentencepiece_pipeline.fx b/v2_examples/sentencepiece_pipeline.fx deleted file mode 100644 index fac2af4..0000000 --- a/v2_examples/sentencepiece_pipeline.fx +++ /dev/null @@ -1,3 +0,0 @@ -main() => - answer := 6 * 7 - return (answer: answer) diff --git a/v2_examples/where_guard_chain.fx b/v2_examples/where_guard_chain.fx index 9599fd7..936b262 100644 --- a/v2_examples/where_guard_chain.fx +++ b/v2_examples/where_guard_chain.fx @@ -1,9 +1,8 @@ # `where` is a sequential guard, not a fact-query construct here. Statements # retain their order: those before a guard run at the current level, while # those after it run only if the guard succeeds. If any `where` fails, -# execution falls through to the clause's single `else` branch. The compiler -# normalizes this to ordinary nested if/else AST nodes; no extra opcode or -# runtime path is involved. +# execution falls through to the clause's single `else` branch. The direct +# interpreter evaluates that ordered AST structure without a separate opcode. # # A `where` guard with no `else` at all is intentionally a compile error # ("a where-guarded clause requires exactly one else branch") rather than a From a29aae9854301acfd6c3bb293df69561c7cd47d3 Mon Sep 17 00:00:00 2001 From: vishalkrishnaag Date: Sat, 12 Sep 2026 10:57:50 +0000 Subject: [PATCH 5/6] sentence piece removed --- cmake/RunFelidaeExample.cmake | 42 ------------------------- cmake/StageTorchRuntime.cmake | 59 ----------------------------------- 2 files changed, 101 deletions(-) delete mode 100644 cmake/RunFelidaeExample.cmake delete mode 100644 cmake/StageTorchRuntime.cmake diff --git a/cmake/RunFelidaeExample.cmake b/cmake/RunFelidaeExample.cmake deleted file mode 100644 index 8cf1424..0000000 --- a/cmake/RunFelidaeExample.cmake +++ /dev/null @@ -1,42 +0,0 @@ -if(NOT DEFINED FELIDAE_COMPILER OR NOT DEFINED FELIDAE_VM OR - NOT DEFINED FELIDAE_EXAMPLE OR NOT DEFINED FELIDAE_BINARY_DIR) - message(FATAL_ERROR "Felidae example test is missing a required path") -endif() - -get_filename_component(FELIDAE_EXAMPLE_NAME "${FELIDAE_EXAMPLE}" NAME_WE) -set(FELIDAE_EXAMPLE_BINARY - "${FELIDAE_BINARY_DIR}/${FELIDAE_EXAMPLE_NAME}.bin") -if(NOT DEFINED FELIDAE_RUNTIME_WORKING_DIRECTORY) - set(FELIDAE_RUNTIME_WORKING_DIRECTORY "${FELIDAE_BINARY_DIR}") -endif() - -execute_process( - COMMAND "${FELIDAE_COMPILER}" "${FELIDAE_EXAMPLE}" - WORKING_DIRECTORY "${FELIDAE_BINARY_DIR}" - RESULT_VARIABLE FELIDAE_COMPILE_RESULT - OUTPUT_VARIABLE FELIDAE_COMPILE_OUTPUT - ERROR_VARIABLE FELIDAE_COMPILE_ERROR) -if(NOT FELIDAE_COMPILE_RESULT EQUAL 0) - message(FATAL_ERROR - "Compiler rejected ${FELIDAE_EXAMPLE}:\n${FELIDAE_COMPILE_OUTPUT}${FELIDAE_COMPILE_ERROR}") -endif() -if(NOT EXISTS "${FELIDAE_EXAMPLE_BINARY}") - message(FATAL_ERROR - "Compiler did not create ${FELIDAE_EXAMPLE_BINARY}:\n${FELIDAE_COMPILE_OUTPUT}") -endif() - -execute_process( - COMMAND "${FELIDAE_VM}" "${FELIDAE_EXAMPLE_BINARY}" - WORKING_DIRECTORY "${FELIDAE_RUNTIME_WORKING_DIRECTORY}" - RESULT_VARIABLE FELIDAE_VM_RESULT - OUTPUT_VARIABLE FELIDAE_VM_OUTPUT - ERROR_VARIABLE FELIDAE_VM_ERROR) -if(NOT FELIDAE_VM_RESULT EQUAL 0) - message(FATAL_ERROR - "VM rejected ${FELIDAE_EXAMPLE_BINARY}:\n${FELIDAE_VM_OUTPUT}${FELIDAE_VM_ERROR}") -endif() -if(FELIDAE_VM_OUTPUT STREQUAL "") - message(FATAL_ERROR "VM produced no result for ${FELIDAE_EXAMPLE}") -endif() - -message(STATUS "${FELIDAE_EXAMPLE_NAME}: ${FELIDAE_VM_OUTPUT}") diff --git a/cmake/StageTorchRuntime.cmake b/cmake/StageTorchRuntime.cmake deleted file mode 100644 index e228318..0000000 --- a/cmake/StageTorchRuntime.cmake +++ /dev/null @@ -1,59 +0,0 @@ -if(NOT DEFINED FELIDAE_EXECUTABLE OR NOT DEFINED FELIDAE_TORCH_LIB_DIR OR - NOT DEFINED FELIDAE_OUTPUT_DIR OR NOT DEFINED FELIDAE_RUNTIME_MANIFEST) - message(FATAL_ERROR "LibTorch runtime staging arguments are incomplete") -endif() - -# Silences a CMake policy warning about path normalization during matching; -# NEW is what current CMake recommends and has no effect on which files this -# script stages. -if(POLICY CMP0207) - cmake_policy(SET CMP0207 NEW) -endif() - -file(GET_RUNTIME_DEPENDENCIES - EXECUTABLES "${FELIDAE_EXECUTABLE}" - DIRECTORIES "${FELIDAE_TORCH_LIB_DIR}" - RESOLVED_DEPENDENCIES_VAR resolved - UNRESOLVED_DEPENDENCIES_VAR unresolved - # api-ms-*/ext-ms-* are Windows API Set forwarders: never real files, the - # loader resolves them internally. - PRE_EXCLUDE_REGEXES "api-ms-.*" "ext-ms-.*") - -# AzureAttestManager.dll, AzureAttestNormal.dll, HvsiFileTrust.dll, -# PdmUtilities.dll, and wpaxholder.dll are optional delay-loaded Windows -# security/diagnostics providers referenced by ucrtbased.dll (the Debug -# UCRT); most machines, including normal dev machines, never have them -# installed, and the OS already tolerates their absence at runtime for -# delay-loaded imports. None of them are LibTorch dependencies, so filtering -# them out here cannot hide a genuinely missing Torch DLL -- only a truly -# missing Torch DLL can still fail this script below. GET_RUNTIME_DEPENDENCIES' -# own PRE_EXCLUDE_REGEXES does not reliably suppress these (observed still -# reporting some of them as unresolved even when listed there), so they are -# filtered out of the resolved list explicitly instead. -if(unresolved) - list(FILTER unresolved EXCLUDE REGEX - "^(AzureAttestManager|AzureAttestNormal|HvsiFileTrust|PdmUtilities|wpaxholder)\\.dll$") -endif() - -set(staged_names) -foreach(dependency IN LISTS resolved) - get_filename_component(torch_root "${FELIDAE_TORCH_LIB_DIR}" REALPATH) - get_filename_component(dependency_path "${dependency}" REALPATH) - string(FIND "${dependency_path}" "${torch_root}/" torch_prefix) - if(torch_prefix EQUAL 0) - get_filename_component(dependency_name "${dependency}" NAME) - file(COPY_FILE "${dependency}" "${FELIDAE_OUTPUT_DIR}/${dependency_name}" ONLY_IF_DIFFERENT) - list(APPEND staged_names "${dependency_name}") - endif() -endforeach() - -if(unresolved) - message(FATAL_ERROR "unresolved LibTorch runtime dependencies: ${unresolved}") -endif() -list(REMOVE_DUPLICATES staged_names) -list(SORT staged_names) -set(manifest_text "") -foreach(dependency_name IN LISTS staged_names) - string(APPEND manifest_text "${dependency_name}\n") -endforeach() -file(WRITE "${FELIDAE_RUNTIME_MANIFEST}" "${manifest_text}") From ee8591d5c661a8a0ea9affc7a5852849dba27c49 Mon Sep 17 00:00:00 2001 From: vishalkrishnaag Date: Sat, 12 Sep 2026 10:58:17 +0000 Subject: [PATCH 6/6] related changes of sentence piece removal and standerdization --- CMakeLists.txt | 33 + README.md | 16 +- code.md | 6 +- core/ancestry.fx | 35 + core/fuzzy.fx | 88 ++ core/math.fx | 4 + core/numeric.fx | 67 + docs/README.md | 6 +- docs_language.md | 9 +- models/README.md | 10 +- models/felidae-bpe/README.md | 8 +- models/felidae-bpe/model.txt | 699 ++++++++++ src/AST.h | 38 + src/BuiltinRegistry.cpp | 8 + src/FelidaeGrammar.h | 14 +- src/FelidaeRuntime.cpp | 6 +- src/FelidaeTokenizerIds.h | 5 +- src/IntegerParser.cpp | 129 +- src/IntegerParser.h | 9 +- src/IntegerTokenList.cpp | 7 +- src/IntegerTokenList.h | 8 +- src/Interpreter.cpp | 720 ++++++++--- src/Interpreter.h | 35 +- src/NativeJson.h | 213 +-- src/ReasoningRuntime.cpp | 6 +- src/Tokenizer.cpp | 72 +- src/Tokenizer.h | 56 +- src/debugger/AstAnalyzer.cpp | 585 +++++++++ src/debugger/AstAnalyzer.h | 61 + src/debugger/main.cpp | 1210 ++++++++++++++++++ src/main.cpp | 156 ++- src/tooling/SourceParser.h | 77 ++ v2_examples/ancestor_relatedness_analysis.fx | 75 ++ v2_examples/degree_profiles.fx | 42 +- v2_examples/felidae_language_tour.fx | 2 +- v2_examples/fuzzy_logic_basics.fx | 71 + 36 files changed, 4117 insertions(+), 469 deletions(-) create mode 100644 core/ancestry.fx create mode 100644 core/fuzzy.fx create mode 100644 core/numeric.fx create mode 100644 src/debugger/AstAnalyzer.cpp create mode 100644 src/debugger/AstAnalyzer.h create mode 100644 src/debugger/main.cpp create mode 100644 src/tooling/SourceParser.h create mode 100644 v2_examples/ancestor_relatedness_analysis.fx create mode 100644 v2_examples/fuzzy_logic_basics.fx diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a7870b..b1de256 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,6 +14,15 @@ function(felidae_common target) target_include_directories(${target} PRIVATE ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/models) + # NativeJson.h parses through the real, vendored nlohmann::json library + # (single-header form: no separate build target needed) rather than a + # bespoke recursive-descent parser. csv.parse/csv.toFacts likewise parse + # through the vendored, previously-unused rapidcsv (handles quoted fields + # and escaped separators correctly, which a hand-rolled comma-split would + # not) instead of a bespoke CSV splitter. + target_include_directories(${target} SYSTEM PRIVATE + ${CMAKE_SOURCE_DIR}/third_party/nlohmann_json/single_include + ${CMAKE_SOURCE_DIR}/third_party/rapidcsv/src) if(UNIX AND NOT APPLE) target_link_libraries(${target} PRIVATE dl) endif() @@ -41,6 +50,30 @@ target_compile_definitions(felidae PRIVATE target_compile_options(felidae PRIVATE $<$:-Wall -Wextra -Wnon-virtual-dtor -Wold-style-cast -Woverloaded-virtual>) +# felidae_debug is an explicit developer tool (AST diagnostics, symbol +# table, and a JSON-RPC LSP server for editor integrations - see +# src/debugger/AstAnalyzer.h and code.md). It never runs as part of, or +# alongside, a normal `felidae program.fx` execution: running a program pays +# nothing for it (Interpreter::setGoalHook is a null std::function unless a +# debug session explicitly installs one), and this target is EXCLUDE_FROM_ALL +# so a plain build of `felidae` never even compiles it. +add_executable(felidae_debug EXCLUDE_FROM_ALL + src/debugger/main.cpp + src/debugger/AstAnalyzer.cpp + src/FelidaeRuntime.cpp + src/IntegerParser.cpp + src/IntegerTokenList.cpp + src/Tokenizer.cpp + src/BuiltinRegistry.cpp + src/Interpreter.cpp + src/ReasoningRuntime.cpp + src/Env.cpp + src/Memory.cpp + src/NativeRuntime.cpp) +felidae_common(felidae_debug) +target_compile_definitions(felidae_debug PRIVATE + FELIDAE_TOKENIZER_MODEL_PATH="${CMAKE_SOURCE_DIR}/models/felidae-bpe/model.txt") + if(FELIDAE_BUILD_TESTS) enable_testing() add_test(NAME direct_ast_smoke diff --git a/README.md b/README.md index e608625..d443220 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ database. `.fx` source is tokenized, parsed to an AST, and evaluated directly by the restored interpreter. ```text -source.fx -> custom BPE -> IntegerParser -> Program AST -> Interpreter +source.fx -> word vocabulary tokenizer -> IntegerParser -> Program AST -> Interpreter ``` There is no compiler-to-IR conversion, binary program format, VM, SentencePiece @@ -34,12 +34,14 @@ No external fact store is required for this interpreter-only runtime. ## Token model -`models/felidae-bpe/model.txt` is the checked-in custom-BPE identifier -vocabulary. Its physical line number is the token ID. The lexer owns the first -59 fixed syntax IDs plus reserved `class`, `extends`, `index`, and `end`, as -well as comments, strings, punctuation, and numbers; BPE only looks up -identifier and mixfix-anchor words in the text table. Unknown words are added -deterministically in source order. +`models/felidae-bpe/model.txt` is the checked-in, deterministic word-vocabulary +identifier dictionary (not byte-pair encoding - see `src/Tokenizer.h` for why +the directory kept its old name). Its physical line number is the token ID. +The lexer owns the first 59 fixed syntax IDs plus reserved `class`, `extends`, +`index`, and `end`, as well as comments, strings, punctuation, and numbers; +the vocabulary only looks up whole identifier and mixfix-anchor words in the +text table. Unknown words are added deterministically in source order, with +no training step. See [code.md](code.md) for the execution architecture and [docs_language.md](docs_language.md) for language semantics. diff --git a/code.md b/code.md index e3cc47e..a592a50 100644 --- a/code.md +++ b/code.md @@ -5,7 +5,7 @@ VM, or statistical mixfix model in the supported path. ```text source.fx - -> custom BPE tokenizer (stable line IDs and byte offsets) + -> word vocabulary tokenizer (stable line IDs and byte offsets) -> IntegerTokenList -> IntegerParser -> Program AST / SymbolId interning @@ -15,7 +15,9 @@ source.fx `models/felidae-bpe/model.txt` is the checked-in, line-oriented identifier vocabulary: line N is token ID N. The normal lexer owns fixed syntax, comments, -numbers, and strings; only identifiers and mixfix anchors use BPE. Unknown +numbers, and strings; only identifiers and mixfix anchors go through the word +vocabulary (a deterministic dictionary lookup, not byte-pair encoding - the +directory name is a historical holdover, see `src/Tokenizer.h`). Unknown identifier words are added in source order, and execution needs no training. `FactMemory` is Felidae's in-process fact database. It uses immutable, diff --git a/core/ancestry.fx b/core/ancestry.fx new file mode 100644 index 0000000..fc91ef9 --- /dev/null +++ b/core/ancestry.fx @@ -0,0 +1,35 @@ +# Short, commonly-used names for the native ancestor-hierarchy analysis +# (commonAncestors/lowestCommonAncestor/highestCommonAncestor, +# Interpreter.cpp:evalAncestorAnalysis) plus a deterministic relatedness +# degree built from it. These operate on the `extend` hierarchy between fact +# TYPES, not a genealogy of individual fact instances - "left"/"right" are +# two typed fact values, and the analysis finds their nearest/farthest +# shared ancestor TYPE. + +lca(left: any, right: any) => + return lowestCommonAncestor(left: left, right: right) + +mca(left: any, right: any) => + return highestCommonAncestor(left: left, right: right) + +# Deterministic [0, 1] relatedness degree from the LCA's combined hierarchy +# distance: 1.0 for identical types (distance 0), decaying smoothly and +# never reaching exactly 0 (a positive but arbitrarily small combined +# distance still returns a positive degree). No arbitrary max-depth constant +# is needed since 1 / (1 + distance) is already bounded to (0, 1]. +relatedness(left: any, right: any) => + found := lca(left: left, right: right) + where found.status == "none" + return 0 +else + nearest := found.lowest.get(pos: 0) + totalDistance := nearest.left_distance + nearest.right_distance + return 1 / (1 + totalDistance) + +# A pair counts as close relatives when their relatedness degree is at or +# above `threshold` (default 0.5, i.e. combined hierarchy distance <= 1). +isCloseRelative(left: any, right: any, threshold: number) => + return relatedness(left: left, right: right) >= threshold + +isDistantRelative(left: any, right: any, threshold: number) => + return relatedness(left: left, right: right) < threshold diff --git a/core/fuzzy.fx b/core/fuzzy.fx new file mode 100644 index 0000000..92654bb --- /dev/null +++ b/core/fuzzy.fx @@ -0,0 +1,88 @@ +# Deterministic fuzzy-logic primitives. +# +# A "degree" is a plain number in [0, 1]. Every function below is a fixed, +# repeatable formula over its inputs (clamping, minimum, maximum, linear +# interpolation) — never a learned weight, a trained model, or a sampled +# value — so the same inputs always produce exactly the same degree. This +# formalizes, as callable functions, the conjunction=minimum / +# disjunction=maximum / negation=one_minus policy that ReasoningProfile +# already fixes internally for Reasoning.grade (see ReasoningRuntime.cpp), +# and builds on core/numeric.fx's clamp/lerp/diff (themselves ported from the +# removed VM's NumericOperation set) instead of reimplementing them. +# +# Kept in their own module, separate from logic.fx's Logic.negate and its +# neighbors: those are declared with a dotted, capitalized name +# ("Logic.negate"), which IntegerParser.cpp's clause-head and call parsing +# does not resolve to a plain declared function outside a fixed fact-fluent +# whitelist (where/insert/get/all/count) or a registered native BuiltinId +# (math.*, json.*, ...). Every existing Logic.* helper is unreachable via its +# own name today, and — confirmed while building this module — loading +# logic.fx alongside unrelated identifiers can also corrupt parsing of the +# surrounding program entirely, not just fail the call. That is a +# pre-existing, load-order-sensitive parser bug in the dotted-declaration +# path; fixing it belongs with the interpreter rewamp's duplicate +# call-dispatch cleanup, not here. Every name below is plain (undotted) to +# stay well clear of it. + +import "numeric". + +fuzzyClamp(value: number) => + return clamp(value: value, low: 0, high: 1) + +# Standard fuzzy negation: not(x) = 1 - x. +fuzzyNot(degree: number) => + return 1 - fuzzyClamp(value: degree) + +# Zadeh conjunction/disjunction: and(a, b) = min(a, b), or(a, b) = max(a, b). +fuzzyAnd(a: number, b: number) => + return min([fuzzyClamp(value: a), fuzzyClamp(value: b)]) + +fuzzyOr(a: number, b: number) => + return max([fuzzyClamp(value: a), fuzzyClamp(value: b)]) + +# Linear ramp from degree 0 at `from` to degree 1 at `to`, via the same +# lerp the removed VM used - clamped since a score outside [from, to] must +# still land in [0, 1] rather than overshoot. A degenerate, zero-width ramp +# (from >= to) is already fully risen. +fuzzyRise(score: number, from: number, to: number) => + if from >= to then + return 1 + else + return clamp(value: (score - from) / (to - from), low: 0, high: 1) + end +end + +# Linear ramp from degree 1 at `from` down to degree 0 at `to`. +fuzzyFall(score: number, from: number, to: number) => + if from >= to then + return 1 + else + return clamp(value: (to - score) / (to - from), low: 0, high: 1) + end +end + +# Triangular membership of `score` in a RatingProfile{peak, fades_in, +# fades_out}: degree 0 at or below fades_in, rising linearly to 1 at peak, +# falling linearly back to 0 at fades_out, 0 at or beyond fades_out. A +# profile whose fades_in already equals peak (e.g. an "extreme" rating with +# no rising edge) is fully member (degree 1) for every score up to peak. +membership(score: number, profile: any) => + if score <= profile.fades_in then + return fuzzyRise(score: score, from: profile.fades_in, to: profile.peak) + elif score < profile.peak then + return fuzzyRise(score: score, from: profile.fades_in, to: profile.peak) + elif score == profile.peak then + return 1 + elif score < profile.fades_out then + return fuzzyFall(score: score, from: profile.peak, to: profile.fades_out) + else + return 0 + end +end + +# General-purpose numeric closeness degree: 1 when a == b, falling off with +# their relative difference, clamped to [0, 1]. Deterministic and symmetric. +similarity(a: number, b: number) => + spread := max([math.abs(value: a), math.abs(value: b), 1]) + return fuzzyClamp(value: 1 - (diff(a: a, b: b) / spread)) +end diff --git a/core/math.fx b/core/math.fx index 23f7f9f..c0ccb0f 100644 --- a/core/math.fx +++ b/core/math.fx @@ -19,3 +19,7 @@ math.abs(value: number) => () math.floor(value: number) => () math.ceil(value: number) => () math.round(value: number) => () +# Signed cube root (cbrt(-8) == -2): the one operation below that plain +# arithmetic cannot reproduce, since pow(value, 1/3) is undefined for +# negative bases in the reals. +math.cbrt(value: number) => () diff --git a/core/numeric.fx b/core/numeric.fx new file mode 100644 index 0000000..e3849a9 --- /dev/null +++ b/core/numeric.fx @@ -0,0 +1,67 @@ +# Deterministic numeric utilities, ported from the removed VM's +# NumericOperation set (form/NumericOperation.h, +# form/RegisterVm.cpp:evaluateNumericOperation in git history before +# e32c679) as plain Felidae source rather than native builtins: every one of +# these is exactly reproducible with existing arithmetic, comparisons, and +# the min/max array builtins, so a second native implementation would only +# be a duplicate to keep in sync. math.cbrt (core/math.fx) stays native +# because it is the one operation here plain arithmetic cannot reproduce +# (pow(value, 1/3) is undefined for negative bases in the reals). +# +# Plain (undotted) names throughout - see core/fuzzy.fx's header comment for +# why: a dotted name only resolves as a call through a registered native +# builtin or the small fixed fluent-operation whitelist (where/limit/join/ +# ...), never through an ordinary declared clause, so "numeric.clamp(...)" +# would fail to parse as a call the same way Logic.negate and math.clamp +# already do. + +clamp(value: number, low: number, high: number) => + return max([low, min([high, value])]) + +lerp(a: number, b: number, t: number) => + return a + (b - a) * t + +diff(a: number, b: number) => + return math.abs(value: a - b) + +weightedAverage(a: number, b: number, weightA: number, weightB: number) => + where weightA + weightB == 0 + total := a + b + return total / 2 +else + weighted := a * weightA + b * weightB + totalWeight := weightA + weightB + return weighted / totalWeight + +square(value: number) => + return value * value + +cube(value: number) => + return value * value * value + +reciprocal(value: number) => + where value == 0 + return 0 +else + return 1 / value + +sign(value: number) => + if value > 0 then + return 1 + elif value < 0 then + return -1 + else + return 0 + end +end + +trunc(value: number) => + if value >= 0 then + return math.floor(value: value) + else + return math.ceil(value: value) + end +end + +inRange(value: number, low: number, high: number) => + return value >= low and value <= high diff --git a/docs/README.md b/docs/README.md index 0397541..6a1a347 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3,12 +3,12 @@ The supported product path is deliberately small and direct: ```text -source.fx -> deterministic lexer + custom BPE -> IntegerParser -> Program AST -> Interpreter +source.fx -> deterministic lexer + word vocabulary -> IntegerParser -> Program AST -> Interpreter ``` Build artifacts are created only in `build/`. Use the repository -[`README.md`](../README.md) for build, direct interpretation, custom-BPE, -mixfix, fact-memory, and source-reload guidance. +[`README.md`](../README.md) for build, direct interpretation, the word +vocabulary tokenizer, mixfix, fact-memory, and source-reload guidance. There is no executable IR, binary program format, VM, SentencePiece model, or SSM path. The AST interpreter and `FactMemory` are authoritative at runtime. diff --git a/docs_language.md b/docs_language.md index abb0109..86d9ed3 100644 --- a/docs_language.md +++ b/docs_language.md @@ -95,10 +95,11 @@ main() => return reason "tiger" with "observed" ## Tokenization -The custom BPE model is `models/felidae-bpe/model.txt`. The normal lexer owns -its fixed first 59 syntax IDs, comments, strings, numbers, punctuation, -operators, and reserved words (including `class`, `extends`, `index`, and -`end`). The remaining line-oriented text dictionary +The deterministic word-vocabulary model is `models/felidae-bpe/model.txt` +(not byte-pair encoding despite the directory name - see `src/Tokenizer.h`). +The normal lexer owns its fixed first 59 syntax IDs, comments, strings, +numbers, punctuation, operators, and reserved words (including `class`, +`extends`, `index`, and `end`). The remaining line-oriented text dictionary stores identifiers and mixfix anchors only; missing identifiers are appended in source order without training. diff --git a/models/README.md b/models/README.md index 540f05f..fddc85e 100644 --- a/models/README.md +++ b/models/README.md @@ -6,7 +6,9 @@ line N is token ID N. The first 59 entries are fixed syntax IDs declared in The remaining entries form a simple checked-in text dictionary. The normal lexer owns comments, strings, numbers, punctuation, operators, and reserved -words such as `class`, `extends`, `index`, and `end`; BPE looks up only -identifiers and mixfix anchors, then appends missing -identifiers in source order. No model training, generated binary model, -WordNet synset database, or external tokenizer dependency is needed. +words such as `class`, `extends`, `index`, and `end`; the word vocabulary +looks up only identifiers and mixfix anchors, then appends missing +identifiers in source order. This is a deterministic whole-word dictionary, +not byte-pair encoding (see `src/Tokenizer.h`), so no model training, +generated binary model, WordNet synset database, or external tokenizer +dependency is needed. diff --git a/models/felidae-bpe/README.md b/models/felidae-bpe/README.md index b996a58..1e453a4 100644 --- a/models/felidae-bpe/README.md +++ b/models/felidae-bpe/README.md @@ -1,4 +1,4 @@ -# Felidae deterministic BPE model +# Felidae word vocabulary model `model.txt` is a line-oriented vocabulary. The physical line number is the stable token ID, starting at zero. The first 59 lines are Felidae's fixed @@ -7,5 +7,7 @@ whitespace and arbitrary UTF-8 remain reversible. New identifier words are appended deterministically by the runtime. The initial word entries are a small checked-in text-dictionary seed. The -runtime extends the same table from source. This tokenizer has no training -step and no WordNet or SentencePiece dependency. +runtime extends the same table from source. Despite the directory's name, +this is a deterministic whole-word dictionary lookup, not byte-pair encoding +(see `src/Tokenizer.h` for the full explanation) - it has no training step +and no WordNet or SentencePiece dependency. diff --git a/models/felidae-bpe/model.txt b/models/felidae-bpe/model.txt index f5ea77e..7d2bcf9 100644 --- a/models/felidae-bpe/model.txt +++ b/models/felidae-bpe/model.txt @@ -542,3 +542,702 @@ pos from_array key access +ClimateObservation +zone +temperature +humidity +occupied +HotObservation +ColdObservation +ComfortableObservation +HvacPlant +available +sensor_valid +HeatPump +observationUnifies +observation +isA +proveCooling +plant +proveHeating +proveVentilation +proveIdle +chooseIdle +idle_proof +chooseVentilation +ventilation_proof +chooseHeating +heating_proof +chooseCooling +cooling_proof +warrant +solve +theorem +warrants +faulty +hot +humid_empty +occupied_hot +empty_humid +invalid_sensor +weight_kg +Bird +Canine +Feline +Wolf +Eagle +relationshipReport +lca +selected +mca +type_relatedness +relatedness +close_relative +isCloseRelative +distant_relative +isDistantRelative +weight_similarity +b +rex +fido +wolfie +tom +aquila +same_species +siblings +cousins +unrelated_but_similar_weight +lowestCommonAncestor +highestCommonAncestor +found +status +nearest +lowest +totalDistance +left_distance +right_distance +fuzzyClamp +clamp +fuzzyNot +fuzzyAnd +fuzzyOr +fuzzyRise +fuzzyFall +spread +math +abs +diff +lerp +t +weightedAverage +weightA +weightB +total +weighted +totalWeight +cube +reciprocal +sign +trunc +floor +ceil +inRange +legs +warm_blooded +diet +Tiger +species +habitat +Lion +TigerFemale +sex +produces_milk +nurtures_young +TigerMale +CatFemale +CatMale +AnimalSimilarityEvidence +left_type +right_type +common_ancestor +ancestor_similarity +property_similarity +similar +matched_properties +differing_properties +ancestor_distance +ancestor_evidence +property_evidence +input +overload +operator +animalSimilarity +precedence +relationship +associativity +none +cardinality +effects +pure +visibility +private +compareMammals +ancestors +common_ancestors +tigerFemales +tigerMales +catFemales +catMales +tigerFemale +tigerMale +catFemale +catMale +femalePair +similarTo +mixedPair +malePair +sameSpeciesPair +decisions +female_tiger_to_female_cat +male_tiger_to_female_cat +male_tiger_to_male_cat +male_tiger_to_female_tiger +VendRequest +selection +CoffeeRequest +TeaRequest +VendingMachine +water +beans +tea +ready +HotDrinkMachine +requestUnifies +request +proveCoffee +machine +proveTea +proveRefund +chooseRefund +refund_proof +chooseTea +tea_proof +chooseCoffee +coffee_proof +entail +conclusion +entails +healthy +depleted +degraded +Knowledge +description +learned +FelidaeKnowledge +AnimalKnowledge +CatKnowledge +SonyKnowledge +BankMeaning +FinancialBank +RiverBank +QuestionBank +BankingAlgorithm +KnowledgeContext +term +article +ResolutionEvidence +matched_fact +matched_field +matched_value +relevance +ContextualAnswer +crisp +candidates +QuantityAnswer +interpretBankContext +text +applyArticleContext +explainLearnedTerm +matches +matchCount +matched +explainLearnedContext +answerLearnedQuantity +propertyName +subjectName +amount +json +felidae +what +unlearned +quantum +ambiguousBank +bank +financialBank +financial +articleBank +sonyLegs +how +many +sony +ambiguous_bank +financial_bank +article_bank +sony_legs +Relationship +Living +cellular +WarmBlooded +FourLegged +nourishes_young +family +Carnivore +hunts +Domestic +Wild +Nocturnal +active_time +territory +DogMale +tiger_females +tiger_males +cat_females +dog_males +wild_families +tiger_female +tiger_male +cat_female +dog_male +wild +tiger_cat_relationship +tied_lineage +broad_lineage +tiger_cat_lineage +ancestorAnalysis +tiger_dog_lineage +habitat_propagation +propagateFact +changes +directed_tiger_cat +r +directed_cat_tiger +symmetric_tiger_cat +DeepReasoningReport +Root +Alpha +Beta +Left +Right +degreeFor +degrees +for_each_fact +profiles +Probability +chance +Classification +evaluateFactExpression +mode +probability +derived +Publication +Book +Magazine +Catalog +title +guides +search +case +related +direction +includeSelf +confident +maximum +Machine +cats +machines +propertySimilarity +combinators +warm +humid +muggy +uncomfortable +cool +temperatureReadings +cold_reading +rising_reading +peak_reading +falling_reading +hot_reading +closenessChecks +identical +close +far +comfortLevel +warmProfile +dryProfile +warmDegree +dryDegree +closeness +comfort_dry_day +comfort_muggy_day +observed_at +priority +fadesIn +fadesOut +makeReport +scale +interpretation +members +table +validation +Group +set +identity +closed +associative +inverse +commutative +abelian +has_active +has +keys +removed +remove +json_text +toText +csv_text +purpose +nocturnal +reviewFactValue +when +review +mixfix_degree +assessed +profile_degrees +strongest_profile +SimilarityReport +buildSimilarityReport +EvidenceSummary +ancestor_count +matched_fields +conflicting_fields +compareFactsWithContext +tigers +dogs +dog +feline_pair +compare +mammal_pair +absolute +difference +avg +weighted_avg +clamped +rounded +round +truncated +squareRoot +sqrt +cubeRoot +cbrt +power +pow +exponential +exp +naturalLog +log +decimalLog +log10 +modulo +mod +interpolated +in_range +finite +is_finite +nan +is_nan +bool +point +record +owner +scores +piped +grouped +unary +ordered +unequal +member +printf +format +instanceof +Candidate +region +Entity +Source +Target +Signal +Decoration +sources +targets +signals +decorations +target +signal +decoration +sourceSignalEdge +scope +targetSignalEdge +sourceDecorativeEdge1 +slot +sourceDecorativeEdge2 +sourceDecorativeEdge3 +targetDecorativeEdge1 +targetDecorativeEdge2 +targetDecorativeEdge3 +sourceCausalToSignal +targetCausalToSignal +connectedViaSignal +source_causal_to_signal +target_causal_to_signal +connected_via_signal +SentimentConcept +SentimentCue +token +polarity +PositiveCue +NegativeCue +NegationCue +SentimentPolicy +positive_weight +negative_weight +negation_penalty +positive_threshold +negative_threshold +Review +SentimentAssessment +label +positive_cues +negative_cues +negation_cues +taxonomy +sentimentLabel +sentimentExplanation +positives +negatives +negations +boundedEvidenceDegree +analyseSentiment +cue +str +contains +needle +positive_count +negative_count +negation_count +positive_score +negative_score +negation_score +support_degree +oppose_degree +positive_taxonomy +negative_taxonomy +positive_root +negative_root +Reasoning +reliability +reviews +union +Set +sets +intersection +intersectionBy +differenceBy +symmetric +symmetricDifferenceBy +equals +subset +superset +disjoint +containsBy +searchData +linearSearchFrom +size +linearSearchAt +linearSearch +binarySearchBetween +binarySearchAt +binarySearch +linearSearchLast +binarySearchLast +searchMissing +linear +binary +linear_last +binary_last +missing +salary +effective_at +temporalRank +effectiveAt +console +readLine +inputNumber +write +writeLine +parse +toFelidaeFacts +Exception +message +Result +ok +exception +__type +readLines +line +writeFile +writeLines +appendFile +exists +deleteFile +List +ListItem +list +pop +Logic +negate +Negation +implication +antecedent +consequent +Implication +converse +transformation +contrapositive +contradiction +positive +negative +ContradictionEvidence +pi +e +random +base +exponent +atan2 +sin +cos +tan +asin +acos +atan +StdLib +symmetricDifference +equalsBy +subsetBy +disjointBy +concat +delimiter +lower +upper +trim +split +replace +replacement +startsWith +prefix +endsWith +suffix +thread +createThread +start +pause +stop +c +d +helper +doubled +typeName +Fact +parsed +roundTrip +fromParsed +round_trip +from_parsed +parsed_school_count +ParsedSchool +conflictMerge +BoundaryRequirement +OperatorRequirement +invalidBoundary +factors +invalidBoundaries +FirstRequirement +SecondRequirement +invalidFactors +factor +invalidFactorDeclaration +noisyAdd +noisyAddNumbers +NumericRequirement +unsafeCheck +unsafeContext +numericRequirement +unsafeContextNumbers +matcher +matchWithRuntimeCall +RequirementMatch +VisibilityRequirement +privateVisibilityCheck +privateCheck +requirement +public +publicMatcher +literalValue +visibilityCheck +WrappedRequirement +wrappedContext +useWrappedRequirement +invalidWrapper +requiresNested +routeValue +routes +toward +redundantPlan +strategy +planer +Plan +mainCall +lateCombine +combineLate +requiredPositive +positiveOnly +redundant +combine +malformedPrefix +infix +malformed +secretBlend +unsafeAnd +replaceAnd +unsafeEquality +ordering +replaceEquality +westEmployee +missingAnnotation +decorated +mergeFromA +mergeFromB +additive +secretBlendNumbers +blend +blendNumbers +differenceBetweenNumbers +scoreWith +publicScore +ml +dot +mse +meanSquaredError +sigmoid +relu +bare +dotted diff --git a/src/AST.h b/src/AST.h index 28b1146..1866d8b 100644 --- a/src/AST.h +++ b/src/AST.h @@ -1117,4 +1117,42 @@ class Program final : public AstNode { } }; +// Non-fatal or fatal diagnostic about a span of source, in the same +// severity/code/message shape the felidae_debug tool (src/debugger/ +// AstAnalyzer.h) uses. Shared here so any diagnostic emitter can report +// warnings without hand-rolling a second diagnostic struct of its own; +// felidae_debug still owns the actual analyses (unused symbols, hidden +// materialization, etc.) that produce AstDiagnostic values - this is just +// the shared value type and the two small constructors every emitter +// otherwise repeats. Not used by the interpreter's own execution path, so +// building or running felidae itself never pays for this. +struct AstDiagnostic { + std::string severity; + std::string message; + int line = 1; + int column = 1; + int endLine = 1; + int endColumn = 1; + std::string code; + std::string file; +}; + +inline AstDiagnostic diagnosticFor(const AstNode* node, std::string severity, + std::string code, std::string message) { + SourceSpan span; + if (node && node->sourceSpan.valid()) span = node->sourceSpan; + return AstDiagnostic{std::move(severity), std::move(message), + span.startLine, span.startColumn, + span.endLine, span.endColumn, + std::move(code), ""}; +} + +inline AstDiagnostic diagnosticForSpan(const SourceSpan& span, std::string severity, + std::string code, std::string message) { + return AstDiagnostic{std::move(severity), std::move(message), + span.startLine, span.startColumn, + span.endLine, span.endColumn, + std::move(code), ""}; +} + } // namespace Felidae diff --git a/src/BuiltinRegistry.cpp b/src/BuiltinRegistry.cpp index ff53e2f..6b2a816 100644 --- a/src/BuiltinRegistry.cpp +++ b/src/BuiltinRegistry.cpp @@ -59,6 +59,10 @@ constexpr BuiltinInfo kBuiltinInfos[] = { {BuiltinId::FileAppendFile, "file:appendFile", BuiltinEffect::WritesExternalState}, {BuiltinId::FileExists, "file:exists", BuiltinEffect::ReadsExternalState}, {BuiltinId::FileDeleteFile, "file:deleteFile", BuiltinEffect::WritesExternalState}, + {BuiltinId::CsvParse, "csv:parse", BuiltinEffect::Pure}, + {BuiltinId::CsvToFacts, "csv:toFacts", BuiltinEffect::WritesExternalState}, + {BuiltinId::CsvToText, "csv:toText", BuiltinEffect::Pure}, + {BuiltinId::CsvToFelidaeFacts, "csv:toFelidaeFacts", BuiltinEffect::WritesExternalState}, {BuiltinId::FactAll, "Fact:all", BuiltinEffect::Pure}, {BuiltinId::FactFind, "Fact:find", BuiltinEffect::Pure}, {BuiltinId::FactCount, "Fact:count", BuiltinEffect::Pure}, @@ -80,6 +84,9 @@ constexpr BuiltinInfo kBuiltinInfos[] = { {BuiltinId::FactAndWhere, "Fact:andWhere", BuiltinEffect::Pure}, {BuiltinId::FactOrWhere, "Fact:orWhere", BuiltinEffect::Pure}, {BuiltinId::FactLimit, "Fact:limit", BuiltinEffect::Pure}, + {BuiltinId::FactJoin, "join", BuiltinEffect::Pure}, + {BuiltinId::ArrayWhere, "Array:where", BuiltinEffect::Pure}, + {BuiltinId::ArrayOrderBy, "Array:orderBy", BuiltinEffect::Pure}, {BuiltinId::CommonAncestors, "commonAncestors", BuiltinEffect::Pure}, {BuiltinId::LowestCommonAncestor, "lowestCommonAncestor", BuiltinEffect::Pure}, {BuiltinId::HighestCommonAncestor, "highestCommonAncestor", BuiltinEffect::Pure}, @@ -122,6 +129,7 @@ constexpr BuiltinInfo kBuiltinInfos[] = { {BuiltinId::MathFloor, "math:floor", BuiltinEffect::Pure}, {BuiltinId::MathCeil, "math:ceil", BuiltinEffect::Pure}, {BuiltinId::MathRound, "math:round", BuiltinEffect::Pure}, + {BuiltinId::MathCbrt, "math:cbrt", BuiltinEffect::Pure}, {BuiltinId::MathAdd, "math:add", BuiltinEffect::Pure}, {BuiltinId::MathSub, "math:sub", BuiltinEffect::Pure}, {BuiltinId::MathMul, "math:mul", BuiltinEffect::Pure}, diff --git a/src/FelidaeGrammar.h b/src/FelidaeGrammar.h index c96be1f..a55de25 100644 --- a/src/FelidaeGrammar.h +++ b/src/FelidaeGrammar.h @@ -92,6 +92,11 @@ enum class BuiltinId { FileExists, FileDeleteFile, + CsvParse, + CsvToFacts, + CsvToText, + CsvToFelidaeFacts, + FactAll, FactFind, FactCount, @@ -111,6 +116,9 @@ enum class BuiltinId { FactAndWhere, FactOrWhere, FactLimit, + FactJoin, + ArrayWhere, + ArrayOrderBy, // Fact reasoning is language-native. These operate directly on typed // fact values; FactMemory remains an implementation detail. @@ -161,6 +169,7 @@ enum class BuiltinId { MathFloor, MathCeil, MathRound, + MathCbrt, MathAdd, MathSub, MathMul, @@ -336,8 +345,9 @@ inline constexpr std::string_view builtinTokenSpelling(TokenId::Id id) { } // These IDs end an already-started identifier range. Keyword IDs are -// intentionally absent: if BPE emits (for example) the `or` ID in -// the middle of `Record`, the contiguous IDs still represent one identifier. +// intentionally absent: if the word vocabulary emits (for example) the `or` +// ID in the middle of `Record`, the contiguous IDs still represent one +// identifier. // At the start of a grammar position, atNameRange() rejects every built-in ID // so reserved words continue to be parsed as grammar vocabulary. inline constexpr bool isIdentifierBoundaryId(TokenId::Id id) { diff --git a/src/FelidaeRuntime.cpp b/src/FelidaeRuntime.cpp index e4b1d44..71bcbed 100644 --- a/src/FelidaeRuntime.cpp +++ b/src/FelidaeRuntime.cpp @@ -82,7 +82,7 @@ Program parseProgramFile(const fs::path& path) { } Program parseProgramText(std::string text) { - auto tokenizer = std::make_shared(); + auto tokenizer = std::make_shared(); IntegerTokenList input(std::move(tokenizer), std::move(text)); return IntegerParser(input).parseProgram(); } @@ -93,7 +93,7 @@ void parseProgramFileStatements( std::shared_ptr operators, ParserMetrics* metrics) { const fs::path normalized = resolveProgramEntryPath(path); - auto tokenizer = std::make_shared(); + auto tokenizer = std::make_shared(); IntegerTokenList input(std::move(tokenizer), readSourceFile(normalized)); IntegerParser parser(input, std::move(operators)); Program program = parser.parseProgram(); @@ -215,7 +215,7 @@ std::vector listCoreLibraries(const fs::path& startDir) { } std::vector> parseQueryText(const std::string& query) { - auto tokenizer = std::make_shared(); + auto tokenizer = std::make_shared(); IntegerTokenList input(std::move(tokenizer), query); return IntegerParser(input).parseQuery(); } diff --git a/src/FelidaeTokenizerIds.h b/src/FelidaeTokenizerIds.h index 01dfb45..6776d05 100644 --- a/src/FelidaeTokenizerIds.h +++ b/src/FelidaeTokenizerIds.h @@ -1,4 +1,4 @@ -// Fixed custom-BPE syntax IDs. Model line N owns ID N. Do not reorder. +// Fixed word-vocabulary syntax IDs. Model line N owns ID N. Do not reorder. #pragma once #include @@ -126,12 +126,13 @@ constexpr Id DIGIT_6 = 55; constexpr Id DIGIT_7 = 56; constexpr Id DIGIT_8 = 57; constexpr Id DIGIT_9 = 58; -// Lexer-owned reserved words deliberately sit outside custom-BPE IDs. They +// Lexer-owned reserved words deliberately sit outside the word-vocabulary IDs. They // are syntax only and must never be learned or persisted in model.txt. constexpr Id CLASS = -1; constexpr Id END = -2; constexpr Id INDEX = -3; constexpr Id EXTENDS = -4; +constexpr Id ELIF = -5; } // namespace TokenId inline constexpr bool isCapitalizedIdentifierStartId(TokenId::Id id) { diff --git a/src/IntegerParser.cpp b/src/IntegerParser.cpp index 0242452..24344b9 100644 --- a/src/IntegerParser.cpp +++ b/src/IntegerParser.cpp @@ -134,7 +134,7 @@ bool IntegerParser::atNameRange() { if (piece_ >= pieces.size()) return false; const auto id = pieces[piece_].id; // `as` is an atomic grammar ID when it stands alone after a fact or query. - // The BPE tokenizer also emits that same ID as the prefix of identifiers such + // The word vocabulary also emits that same ID as the prefix of identifiers such // as `Assessment`; contiguous IDs are one identifier range, never a // grammar boundary. if (id == TokenId::AS) { @@ -211,7 +211,7 @@ std::string IntegerParser::consumeNameRange() { const std::size_t begin = byte_; const auto& pieces = input_.entries(); // A logical name is a contiguous run of non-grammar token IDs. - // BPE may split one source name into many adjacent pieces. + // The word vocabulary may split one source name into many adjacent pieces. while (piece_ < pieces.size()) { const auto id = pieces[piece_].id; if (id == TokenId::UNKNOWN || isIdentifierBoundaryId(id)) break; @@ -229,7 +229,7 @@ std::string IntegerParser::consumeString() { if (id == TokenId::QUOTE) { const std::size_t end = input_.entries()[piece_].begin; byte_ = input_.entries()[piece_++].end; - // Literal content is a lexer-owned source span; BPE supplies IDs + // Literal content is a lexer-owned source span; the word vocabulary supplies IDs // only for identifiers and mixfix anchors. const std::string value = input_.source().substr(begin, end - begin); std::string unescaped; @@ -490,26 +490,51 @@ std::shared_ptr IntegerParser::parseGoal() { skipTrivia(); const std::size_t begin = byte_; if (match(TokenId::IF)) { - auto conditionExpression = parseBinaryExpression( - static_cast(OperatorPrecedence::Control), TokenId::THEN); - require(TokenId::THEN, "Expected 'then' after if condition"); - std::shared_ptr condition; - if (const auto comparison = std::dynamic_pointer_cast(conditionExpression); - comparison && comparison->captureCount() == 2 && - isComparisonOperator(comparison->coreOperator)) { - condition = std::make_shared(comparison->capture(0), - coreOperatorDefinition(comparison->coreOperator).token, comparison->capture(1)); - } else { - condition = std::make_shared(std::move(conditionExpression), TokenId::EQUAL, - std::make_shared(true)); + // `elif` is sugar, not a new AST shape: `if A then T1 elif B then T2 + // else T3 end` desugars to exactly the nested + // `if A then T1 else if B then T2 else T3 end end` a user could + // already write by hand (see optional_end_blocks.fx) - one IfGoal + // per condition, each one's elseBranch holding the next. Only one + // `end` appears in the source for the whole chain, so matchBlockEnd + // runs once, after every branch is parsed, never per synthesized + // nesting level. + const auto parseCondition = [&]() -> std::shared_ptr { + auto conditionExpression = parseBinaryExpression( + static_cast(OperatorPrecedence::Control), TokenId::THEN); + require(TokenId::THEN, "Expected 'then' after if condition"); + if (const auto comparison = std::dynamic_pointer_cast(conditionExpression); + comparison && comparison->captureCount() == 2 && + isComparisonOperator(comparison->coreOperator)) { + return std::make_shared(comparison->capture(0), + coreOperatorDefinition(comparison->coreOperator).token, comparison->capture(1)); + } + return std::make_shared(std::move(conditionExpression), TokenId::EQUAL, + std::make_shared(true)); + }; + struct Branch { + std::size_t begin; + std::shared_ptr condition; + std::vector> thenBranch; + }; + std::vector branches; + branches.push_back({begin, parseCondition(), parseGoalList(TokenId::DOT)}); + while (true) { + const auto branchBegin = byte_; + if (!match(TokenId::ELIF)) break; + branches.push_back({branchBegin, parseCondition(), parseGoalList(TokenId::DOT)}); } - auto thenBranch = parseGoalList(TokenId::DOT); std::vector> elseBranch; if (match(TokenId::ELSE)) elseBranch = parseGoalList(TokenId::DOT); (void)matchBlockEnd(); - auto result = std::make_shared(std::move(condition), std::move(thenBranch), - std::move(elseBranch)); - stamp(result, begin, byte_); + std::shared_ptr result; + auto tailElse = std::move(elseBranch); + for (auto branch = branches.rbegin(); branch != branches.rend(); ++branch) { + auto ifGoal = std::make_shared(std::move(branch->condition), + std::move(branch->thenBranch), std::move(tailElse)); + stamp(ifGoal, branch->begin, byte_); + result = ifGoal; + tailElse = std::vector>{std::move(ifGoal)}; + } return result; } if (match(TokenId::WHERE)) { @@ -623,6 +648,47 @@ std::shared_ptr IntegerParser::parseGoal() { return result; } +// True when the parser sits at the start of what can only be a new clause +// head (`qualifiedName(...) =>`, optionally followed by `as designation`), +// never a goal continuing the current body: no goal is itself a bare +// callable head immediately followed by an arrow. Checking this shape - independent +// of indentation - is what stops a same-line body (`f() => return x`, whose +// one line sits at indent 0 like any top-level clause) from swallowing the +// clause that follows it; the indentation dedent check in parseGoalList only +// protects a genuinely indented body. Pure lookahead: parser position is +// always restored before returning. +bool IntegerParser::looksLikeClauseHead() { + skipTrivia(); + if (!atNameRange()) return false; + const auto savedByte = byte_; + const auto savedPiece = piece_; + bool result = false; + try { + consumeQualifiedName(); + if (match(TokenId::LPAREN)) { + std::size_t depth = 1; + const auto& pieces = input_.entries(); + while (depth > 0 && piece_ < pieces.size()) { + const auto id = pieces[piece_].id; + byte_ = pieces[piece_++].end; + if (id == TokenId::LPAREN) ++depth; + else if (id == TokenId::RPAREN) --depth; + } + if (depth == 0) { + if (match(TokenId::AS)) { + do { consumeQualifiedName(); } while (match(TokenId::COMMA)); + } + result = at(TokenId::ARROW); + } + } + } catch (const IntegerParserError&) { + result = false; + } + byte_ = savedByte; + piece_ = savedPiece; + return result; +} + std::vector> IntegerParser::parseGoalList(TokenId::Id terminator) { std::vector> goals; if (at(terminator)) return goals; @@ -634,6 +700,7 @@ std::vector> IntegerParser::parseGoalList(TokenId::Id term // the next top-level declaration into its method body. skipTrivia(); if (atBlockEnd()) break; + if (looksLikeClauseHead()) break; const auto before = byte_; if (!hasBodyIndent) { bodyIndent = sourceLineIndent(before); @@ -1306,6 +1373,30 @@ std::shared_ptr IntegerParser::parseUnary() { result = std::make_shared("Fact:delete", std::move(arguments), BuiltinId::FactDelete); continue; } + // Type.where(field: value, ...) is handled above, gated on a bare + // capitalized receiver. Reaching here with `where` means the + // receiver is some other expression - e.g. join(TypeA, TypeB) - + // whose rows are plain {left, right} pairs rather than one type's + // fields, so the single argument is a boolean predicate expression + // (left.id == right.school_id) evaluated once per row instead of a + // map of field equalities. + if (member == "where") { + if (arguments.size() != 1 || !arguments.front().name.empty()) { + throw IntegerParserError( + "where(...) on a join result expects a single predicate expression, " + "e.g. where(left.id == right.school_id)"); + } + std::vector whereArgs; + whereArgs.emplace_back("selection", std::move(result)); + whereArgs.emplace_back("predicate", std::move(arguments.front().value)); + result = std::make_shared("Array:where", std::move(whereArgs), BuiltinId::ArrayWhere); + continue; + } + if (member == "order_by") { + prepend(std::move(result), "selection"); + result = std::make_shared("Array:orderBy", std::move(arguments), BuiltinId::ArrayOrderBy); + continue; + } throw IntegerParserError("Unsupported fact operation '" + member + "'"); } return result; diff --git a/src/IntegerParser.h b/src/IntegerParser.h index d77ad83..7e7cd62 100644 --- a/src/IntegerParser.h +++ b/src/IntegerParser.h @@ -24,10 +24,10 @@ class IntegerParserError : public std::runtime_error { explicit IntegerParserError(const std::string& message) : std::runtime_error(message) {} }; -// Direct BPE-token-ID grammar assembler. It has no secondary tokenizer, -// source-character syntax scanner, or spelling-to-token lookup table. IDs -// determine all syntax; original source is retained only to copy an already -// bounded identifier payload into the IR for SymbolId interning. +// Direct word-vocabulary-token-ID grammar assembler. It has no secondary +// tokenizer, source-character syntax scanner, or spelling-to-token lookup +// table. IDs determine all syntax; original source is retained only to copy +// an already bounded identifier payload into the IR for SymbolId interning. class IntegerParser { public: explicit IntegerParser(const IntegerTokenList& input, @@ -104,6 +104,7 @@ class IntegerParser { std::string consumeString(); double consumeNumber(); bool atNameRange(); + bool looksLikeClauseHead(); bool sourceContainsLineBreak(std::size_t begin, std::size_t end) const; bool lineBreakBeforeNextSignificantPiece() const; std::size_t sourceLineIndent(std::size_t offset) const; diff --git a/src/IntegerTokenList.cpp b/src/IntegerTokenList.cpp index d328453..9d98122 100644 --- a/src/IntegerTokenList.cpp +++ b/src/IntegerTokenList.cpp @@ -59,7 +59,7 @@ std::size_t statementEnd(std::string_view source, std::size_t begin) { } // namespace -IntegerTokenList::IntegerTokenList(std::shared_ptr tokenizer, +IntegerTokenList::IntegerTokenList(std::shared_ptr tokenizer, std::string source) : source_(std::move(source)), tokenizer_(std::move(tokenizer)), complete_(source_.empty()) { @@ -88,6 +88,7 @@ void IntegerTokenList::encodeNextStatement() const { if (spelling == "end") return TokenId::END; if (spelling == "index") return TokenId::INDEX; if (spelling == "extends") return TokenId::EXTENDS; + if (spelling == "elif") return TokenId::ELIF; return TokenId::UNKNOWN; }; for (std::size_t offset = 0; offset < statement.size();) { @@ -164,7 +165,7 @@ void IntegerTokenList::encodeNextStatement() const { const std::string_view word = statement.substr(first, offset - first); const TokenId::Id keyword = fixedId(word); if (keyword != TokenId::UNKNOWN || word == "class" || word == "end" || - word == "index" || word == "extends") { + word == "index" || word == "extends" || word == "elif") { push(keyword, first, offset); continue; } @@ -184,7 +185,7 @@ bool IntegerTokenList::has(std::size_t index) const { const IntegerTokenList::Entry & IntegerTokenList::entry(std::size_t index) const { if (!has(index)) - throw std::out_of_range("BPE token index is out of range"); + throw std::out_of_range("word vocabulary token index is out of range"); return entries_[index]; } diff --git a/src/IntegerTokenList.h b/src/IntegerTokenList.h index 91a4376..ec96205 100644 --- a/src/IntegerTokenList.h +++ b/src/IntegerTokenList.h @@ -10,7 +10,7 @@ namespace Felidae { -// The sole source-tokenization result. BPE encodes complete +// The sole source-tokenization result. WordVocabulary encodes complete // dot-terminated statement spans, so multiline statements and `then` chains // have one stable token stream. Newlines are formatting inside a span. // @@ -27,7 +27,7 @@ class IntegerTokenList { }; IntegerTokenList() = default; - IntegerTokenList(std::shared_ptr tokenizer, std::string source); + IntegerTokenList(std::shared_ptr tokenizer, std::string source); const std::string &source() const noexcept { return source_; } bool has(std::size_t index) const; @@ -36,12 +36,12 @@ class IntegerTokenList { // Tool/test materialization boundary. Production parsing uses has/entry. const std::vector &entries() const; std::size_t encodeCount() const noexcept { return encodeCount_; } - const BpeTokenizer &tokenizer() const noexcept { return *tokenizer_; } + const WordVocabulary &tokenizer() const noexcept { return *tokenizer_; } private: void encodeNextStatement() const; std::string source_; - std::shared_ptr tokenizer_; + std::shared_ptr tokenizer_; mutable std::vector entries_; mutable std::size_t nextStatementBegin_ = 0; mutable std::size_t encodeCount_ = 0; diff --git a/src/Interpreter.cpp b/src/Interpreter.cpp index cf91a04..fd1aaf6 100644 --- a/src/Interpreter.cpp +++ b/src/Interpreter.cpp @@ -2,8 +2,10 @@ #include "BuiltinRegistry.h" #include "IntegerParser.h" #include "FelidaeRuntime.h" +#include "NativeJson.h" #include "OperatorAnnotation.h" #include "Tokenizer.h" +#include #include #include #include @@ -21,10 +23,6 @@ #include #include -#ifdef FELIDAE_HAS_EIGEN -#include -#endif - namespace Felidae { namespace fs = std::filesystem; @@ -521,6 +519,28 @@ static std::string astNodeKind(const std::shared_ptr& node) { return "expr"; } +// Single authoritative "what does type()/typeof report for this runtime +// value" classification. Both the goal-call form (type(X, Name)) and the +// expression form (Name := type(X)) must agree, so they share this instead +// of maintaining two hand-copied dynamic_pointer_cast chains. +static bool resolveRuntimeTypeName(const std::shared_ptr& value, std::string& out) { + if (auto ast = std::dynamic_pointer_cast(value)) { + out = ast->nodeKind; + return true; + } + if (auto typeString = std::dynamic_pointer_cast( + findMapValue(value, internalSymbolString(InternalSymbolKind::Type)))) { + out = typeString->value; + return true; + } + if (std::dynamic_pointer_cast(value)) { out = "number"; return true; } + if (std::dynamic_pointer_cast(value)) { out = "string"; return true; } + if (std::dynamic_pointer_cast(value)) { out = "bool"; return true; } + if (std::dynamic_pointer_cast(value)) { out = "array"; return true; } + if (std::dynamic_pointer_cast(value)) { out = "nil"; return true; } + return false; +} + static bool valueMatchesBuiltinType(const std::shared_ptr& value, LanguageTypeId type) { switch (type) { @@ -755,146 +775,145 @@ static std::string exprToJson(const std::shared_ptr& expr) { return "\"" + jsonEscape(expr ? expr->debug() : "") + "\""; } -static void skipJsonWs(const std::string& text, size_t& pos) { - while (pos < text.size() && std::isspace(static_cast(text[pos]))) pos++; -} - -static bool parseJsonString(const std::string& text, size_t& pos, std::string& out) { - skipJsonWs(text, pos); - if (pos >= text.size() || text[pos] != '"') return false; - pos++; - out.clear(); - while (pos < text.size() && text[pos] != '"') { - char c = text[pos++]; - if (c == '\\' && pos < text.size()) { - char esc = text[pos++]; - switch (esc) { - case 'n': out.push_back('\n'); break; - case 't': out.push_back('\t'); break; - case 'r': out.push_back('\r'); break; - case '"': out.push_back('"'); break; - case '\\': out.push_back('\\'); break; - default: out.push_back(esc); break; +// The interpreter lowers JSON text into runtime Expr values through the one +// grammar parser in NativeJson.h (also used by NativeRuntime.cpp for native +// module manifests) instead of a second, independently hand-rolled +// recursive-descent JSON parser. Only this conversion step is specific to +// the language's value representation. +static std::shared_ptr jsonValueToExpr(const NativeJson::Value& value) { + switch (value.kind) { + case NativeJson::Value::Kind::Null: + return std::make_shared(); + case NativeJson::Value::Kind::Bool: + return std::make_shared(value.boolean); + case NativeJson::Value::Kind::Number: + return std::make_shared(value.number); + case NativeJson::Value::Kind::String: + return std::make_shared(value.text); + case NativeJson::Value::Kind::Array: { + std::vector> items; + items.reserve(value.items.size()); + for (const auto& item : value.items) items.push_back(jsonValueToExpr(item)); + return std::make_shared(std::move(items)); + } + case NativeJson::Value::Kind::Object: { + std::vector entries; + entries.reserve(value.fieldOrder.size()); + for (const auto& key : value.fieldOrder) { + const auto field = value.fields.find(key); + if (field != value.fields.end()) { + entries.push_back(MapEntry{key, jsonValueToExpr(field->second)}); + } } - } else { - out.push_back(c); + return std::make_shared(std::move(entries)); } } - if (pos >= text.size() || text[pos] != '"') return false; - pos++; - return true; + return std::make_shared(); } -static bool parseJsonValue(const std::string& text, size_t& pos, std::shared_ptr& out); - -static bool parseJsonObjectValue(const std::string& text, size_t& pos, std::shared_ptr& out) { - skipJsonWs(text, pos); - if (pos >= text.size() || text[pos] != '{') return false; - pos++; - std::vector entries; - skipJsonWs(text, pos); - if (pos < text.size() && text[pos] == '}') { - pos++; - out = std::make_shared(std::move(entries)); +static bool parseFlatJsonObject(const std::string& text, std::shared_ptr& out) { + try { + out = jsonValueToExpr(NativeJson::parse(text.c_str(), "json.parse")); return true; - } - while (pos < text.size()) { - std::string key; - std::shared_ptr value; - if (!parseJsonString(text, pos, key)) return false; - skipJsonWs(text, pos); - if (pos >= text.size() || text[pos] != ':') return false; - pos++; - if (!parseJsonValue(text, pos, value)) return false; - entries.push_back(MapEntry{key, value}); - skipJsonWs(text, pos); - if (pos < text.size() && text[pos] == ',') { - pos++; - continue; - } - if (pos < text.size() && text[pos] == '}') { - pos++; - out = std::make_shared(std::move(entries)); - return true; - } + } catch (const std::exception&) { return false; } - return false; } -static bool parseJsonArrayValue(const std::string& text, size_t& pos, std::shared_ptr& out) { - skipJsonWs(text, pos); - if (pos >= text.size() || text[pos] != '[') return false; - pos++; - std::vector> items; - skipJsonWs(text, pos); - if (pos < text.size() && text[pos] == ']') { - pos++; - out = std::make_shared(std::move(items)); - return true; - } - while (pos < text.size()) { - std::shared_ptr value; - if (!parseJsonValue(text, pos, value)) return false; - items.push_back(value); - skipJsonWs(text, pos); - if (pos < text.size() && text[pos] == ',') { - pos++; - continue; +// A cell that fully parses as a finite number becomes one - matching how +// every hand-written fact in this codebase already stores counts/flags as +// numbers (e.g. School(students: 420, active: 1.0)), not strings - so CSV +// facts compare and aggregate the same way hand-written ones do. Anything +// else, including an empty cell, stays exactly the text it was. +static std::shared_ptr csvCellToExpr(const std::string& cell) { + if (!cell.empty()) { + std::size_t consumed = 0; + try { + const double value = std::stod(cell, &consumed); + if (consumed == cell.size() && std::isfinite(value)) { + return std::make_shared(value); + } + } catch (const std::exception&) { + // Not a number - fall through to the plain string below. } - if (pos < text.size() && text[pos] == ']') { - pos++; - out = std::make_shared(std::move(items)); - return true; + } + return std::make_shared(cell); +} + +// Parses through rapidcsv (third_party/rapidcsv, vendored but previously +// unused) rather than a hand-rolled comma-split, so quoted fields containing +// the separator or embedded newlines are handled correctly instead of +// silently misparsed. The header row supplies field names; every other row +// becomes one map, in row order, with fields in header order. +static std::shared_ptr csvTextToRows(const std::string& data) { + std::istringstream input(data); + const rapidcsv::Document document(input, rapidcsv::LabelParams(0, -1)); + const auto columns = document.GetColumnNames(); + std::vector> rows; + rows.reserve(document.GetRowCount()); + for (std::size_t rowIndex = 0; rowIndex < document.GetRowCount(); ++rowIndex) { + std::vector entries; + entries.reserve(columns.size()); + for (std::size_t columnIndex = 0; columnIndex < columns.size(); ++columnIndex) { + entries.push_back(MapEntry{columns[columnIndex], + csvCellToExpr(document.GetCell(columnIndex, rowIndex))}); } - return false; + rows.push_back(std::make_shared(std::move(entries))); } - return false; + return std::make_shared(std::move(rows)); } -static bool parseJsonValue(const std::string& text, size_t& pos, std::shared_ptr& out) { - skipJsonWs(text, pos); - if (pos >= text.size()) return false; - if (text.compare(pos, 4, "null") == 0) { - pos += 4; - out = std::make_shared(); - return true; +// The reverse of csvCellToExpr: a value's display text is already exactly +// what belongs in a cell (numbers print without quotes, strings as their +// own text) - only characters CSV itself treats specially need quoting. +static std::string csvCellText(const std::shared_ptr& value) { + std::string text; + if (const auto string = std::dynamic_pointer_cast(value)) { + text = string->value; + } else if (const auto number = std::dynamic_pointer_cast(value)) { + std::ostringstream out; + out << number->value; + text = out.str(); + } else if (value) { + text = value->debug(); } - if (text.compare(pos, 4, "true") == 0) { - pos += 4; - out = std::make_shared(true); - return true; + if (text.find_first_of(",\"\n\r") == std::string::npos) return text; + std::string quoted = "\""; + for (const char character : text) { + if (character == '"') quoted += "\"\""; + else quoted += character; } - if (text.compare(pos, 5, "false") == 0) { - pos += 5; - out = std::make_shared(false); - return true; + quoted += "\""; + return quoted; +} + +// Column order comes from the first row's own field order (every row here +// already comes from either csv.parse, sharing one header-derived order, or +// hand-built maps a caller is expected to keep consistent) rather than +// recomputing a union of every row's keys, which could silently reorder +// columns row to row. +static std::string rowsToCsvText(const std::vector>& rows) { + std::vector columns; + if (!rows.empty()) { + if (const auto first = std::dynamic_pointer_cast(rows.front())) { + for (const auto& entry : first->entries) columns.push_back(entry.key); + } } - if (text[pos] == '{') return parseJsonObjectValue(text, pos, out); - if (text[pos] == '[') return parseJsonArrayValue(text, pos, out); - if (text[pos] == '"') { - std::string value; - if (!parseJsonString(text, pos, value)) return false; - out = std::make_shared(value); - return true; + std::ostringstream out; + for (std::size_t index = 0; index < columns.size(); ++index) { + if (index) out << ","; + out << csvCellText(std::make_shared(columns[index])); } - size_t start = pos; - if (text[pos] == '-') pos++; - while (pos < text.size() && std::isdigit(static_cast(text[pos]))) pos++; - if (pos < text.size() && text[pos] == '.') { - pos++; - while (pos < text.size() && std::isdigit(static_cast(text[pos]))) pos++; + out << "\r\n"; + for (const auto& row : rows) { + for (std::size_t index = 0; index < columns.size(); ++index) { + if (index) out << ","; + auto value = findMapValue(row, columns[index]); + out << csvCellText(value ? value : std::make_shared("")); + } + out << "\r\n"; } - if (start == pos || (start + 1 == pos && text[start] == '-')) return false; - out = std::make_shared(std::stod(text.substr(start, pos - start))); - return true; -} - -static bool parseFlatJsonObject(const std::string& text, std::shared_ptr& out) { - size_t pos = 0; - if (!parseJsonValue(text, pos, out)) return false; - skipJsonWs(text, pos); - return pos == text.size(); + return out.str(); } Interpreter::~Interpreter() { @@ -1641,7 +1660,7 @@ std::shared_ptr Interpreter::evaluateGlobal(const std::string& name) const } std::shared_ptr Interpreter::evaluateExpressionText(const std::string& text) { - auto tokenizer = std::make_shared(); + auto tokenizer = std::make_shared(); IntegerTokenList tokenList(std::move(tokenizer), text); IntegerParser parser(tokenList); auto expr = parser.parseExpressionText(); @@ -1713,14 +1732,60 @@ std::shared_ptr Interpreter::executeEntryCall(const Call& entryCall) { throw InterpreterError("Auto entry method '" + entryCall.name + "' produced no result"); } +// Type.where(...) stays a lazy, composable selection internally so +// AndWhere/limit/count/iteration can keep narrowing or consuming it without +// re-querying FactMemory each step. But a selection that reaches the actual +// program boundary - what gets printed or returned to a caller - is never +// useful as its own descriptor; every other terminal fact operation +// (OrWhere, limit, get, count, iteration) already materializes it into rows, +// so displaying one directly does the same instead of showing the internal +// {__type: "FactSelection", ...} cursor. +std::shared_ptr Interpreter::materializeIfFactSelection(const std::shared_ptr& value) { + if (!value) return value; + if (std::dynamic_pointer_cast(value)) return materializeFactSelection(value); + // A selection reported alongside other results - e.g. a returned map + // bundling several named queries - is exactly as displayable-as-a-raw- + // descriptor as a bare one, so the replacement recurses into maps and + // arrays rather than only checking the outermost value. + if (auto map = std::dynamic_pointer_cast(value)) { + std::vector entries; + entries.reserve(map->entries.size()); + bool changed = false; + for (const auto& entry : map->entries) { + auto materialized = materializeIfFactSelection(entry.value); + changed = changed || materialized != entry.value; + entries.push_back(MapEntry{entry.key, entry.keyId, materialized}); + } + if (!changed) return value; + auto result = std::make_shared(std::move(entries)); + result->factType = map->factType; + result->factIdentity = map->factIdentity; + return result; + } + if (auto array = std::dynamic_pointer_cast(value)) { + std::vector> items; + items.reserve(array->items.size()); + bool changed = false; + for (const auto& item : array->items) { + auto materialized = materializeIfFactSelection(item); + changed = changed || materialized != item; + items.push_back(materialized); + } + if (!changed) return value; + return std::make_shared(std::move(items)); + } + return value; +} + std::string Interpreter::valueToString(const std::shared_ptr& value) const { Env env; auto resolved = resolveExpr(value, env); std::shared_ptr evaluated; - if (const_cast(this)->evalExprValue(resolved, env, evaluated)) { - return publicValueString(evaluated); + auto* self = const_cast(this); + if (self->evalExprValue(resolved, env, evaluated)) { + return publicValueString(self->materializeIfFactSelection(evaluated)); } - return publicValueString(resolved); + return publicValueString(self->materializeIfFactSelection(resolved)); } @@ -1728,10 +1793,11 @@ std::string Interpreter::valueToDisplayString(const std::shared_ptr& value Env env; auto resolved = resolveExpr(value, env); std::shared_ptr evaluated; - if (const_cast(this)->evalExprValue(resolved, env, evaluated)) { - return publicDisplayString(evaluated); + auto* self = const_cast(this); + if (self->evalExprValue(resolved, env, evaluated)) { + return publicDisplayString(self->materializeIfFactSelection(evaluated)); } - return publicDisplayString(resolved); + return publicDisplayString(self->materializeIfFactSelection(resolved)); } void Interpreter::solveRecursive(const std::vector>& goals, Env env, @@ -1792,6 +1858,16 @@ void Interpreter::solveIterative(const std::vector>& goals work.push_back(WorkFrame{frame.goals, nextGoalIndex, std::move(nextEnv), frame.depth}); }; + // methodCallDepth_ (incremented/decremented only around + // solveMethodCall's own body, via its existing CounterScope) is the + // real method call-stack depth - unlike frame.depth, which also + // increases for group/if/or nesting and, worse, does NOT increase + // for a method called from expression position (e.g. `b := + // helper(x: a)`, the common case): evalBuiltinTerm's user-callable + // path invokes solveMethodCall with a hardcoded depth of 0, + // independent of the caller's frame.depth entirely. + if (goalHook_) goalHook_(*goal, frame.env, methodCallDepth_); + switch (goal->kind()) { case GoalKind::Assign: { const auto assign = std::static_pointer_cast(goal); @@ -2511,17 +2587,54 @@ bool Interpreter::solveMethodCall(const Call& call, }; if (!originalClause->fallbackBranches.empty()) { + // Split the body at its first `where`: goals before it (e.g. `found + // := lca(...)` ahead of `where found.status == "none"`) are an + // unconditional prelude that must still be visible to the `else` + // branches when the guard does not hold, since a branch may depend + // on a value the guard itself was computed from. Only the guard + // onward is allowed to fail outright. (A body with no `where` at all + // puts everything in the prelude, matching plain sequential + // evaluation.) Previously the whole body ran as one unit and the + // fallback ran unconditionally afterward on top of it, so a + // satisfied guard's own return was always overwritten by the first + // `else` branch's result instead of being used, while a failed + // guard produced no solution at all - the fallback never ran either. + std::size_t whereIndex = 0; + while (whereIndex < originalClause->body.size() && + originalClause->body[whereIndex]->kind() != GoalKind::Where) { + ++whereIndex; + } + const std::vector> preludeGoals( + originalClause->body.begin(), originalClause->body.begin() + static_cast(whereIndex)); + const std::vector> guardedGoals( + originalClause->body.begin() + static_cast(whereIndex), originalClause->body.end()); + for (auto& candidate : candidates) { std::vector preludeSolutions; - if (originalClause->body.empty()) { + if (preludeGoals.empty()) { preludeSolutions.push_back(Solution{std::move(candidate)}); } else { - solveRecursive(originalClause->body, std::move(candidate), preludeSolutions, 1, depth + 1); + solveRecursive(preludeGoals, std::move(candidate), preludeSolutions, 1, depth + 1); } for (auto& prelude : preludeSolutions) { + Env preludeEnv = prelude.env; + std::vector guardedSolutions; + if (guardedGoals.empty()) { + guardedSolutions.push_back(Solution{preludeEnv}); + } else { + solveRecursive(guardedGoals, preludeEnv, guardedSolutions, 1, depth + 1); + } + bool guardReturned = false; + for (auto& solution : guardedSolutions) { + auto returnedIt = solution.env.find(internalSymbolString(InternalSymbolKind::Return)); + if (returnedIt == solution.env.end()) continue; + guardReturned = true; + if (appendReturnedSolution(solution.env, returnedIt->second)) return true; + } + if (guardReturned) continue; for (const auto& branch : originalClause->fallbackBranches) { std::vector branchSolutions; - solveRecursive(branch, prelude.env, branchSolutions, 1, depth + 1); + solveRecursive(branch, preludeEnv, branchSolutions, 1, depth + 1); bool branchReturned = false; for (auto& solution : branchSolutions) { auto returnedIt = solution.env.find(internalSymbolString(InternalSymbolKind::Return)); @@ -4339,16 +4452,7 @@ bool Interpreter::solveBuiltin(const Call& call, Env& env) { if (call.builtinId == BuiltinId::Type) { if (!valueArg({"value", "data", "input"}, 0, a)) return false; std::string resolvedType; - if (auto ast = std::dynamic_pointer_cast(a)) resolvedType = ast->nodeKind; - else if (auto typeString = std::dynamic_pointer_cast( - findMapValue(a, internalSymbolString(InternalSymbolKind::Type)))) { - resolvedType = typeString->value; - } else if (std::dynamic_pointer_cast(a)) resolvedType = "number"; - else if (std::dynamic_pointer_cast(a)) resolvedType = "string"; - else if (std::dynamic_pointer_cast(a)) resolvedType = "bool"; - else if (std::dynamic_pointer_cast(a)) resolvedType = "array"; - else if (std::dynamic_pointer_cast(a)) resolvedType = "nil"; - else return false; + if (!resolveRuntimeTypeName(a, resolvedType)) return false; const Arg* out = namedArg("name"); if (!out) out = namedArg("type"); if (!out) out = namedArg("out"); @@ -5046,14 +5150,9 @@ bool Interpreter::solveNativeCall(const Call& call, Env& env) { library->free(response); std::shared_ptr parsed; - size_t pos = 0; - if (!parseJsonValue(responseText, pos, parsed)) { + if (!parseFlatJsonObject(responseText, parsed)) { throw InterpreterError("Native function '" + nativeFunctionName + "' returned invalid JSON"); } - skipJsonWs(responseText, pos); - if (pos != responseText.size()) { - throw InterpreterError("Native function '" + nativeFunctionName + "' returned trailing data after JSON"); - } if (auto errorValue = findMapValue(parsed, "error")) { std::string message; @@ -5087,6 +5186,64 @@ bool Interpreter::solveNativeCall(const Call& call, Env& env) { return true; } +bool Interpreter::evalArrayWherePredicate(const TermExpr& term, const Env& env, std::shared_ptr& out) { + const Arg* selectionArg = nullptr; + const Arg* predicateArg = nullptr; + for (const auto& arg : term.args) { + if (arg.name == "selection") selectionArg = &arg; + else if (arg.name == "predicate") predicateArg = &arg; + } + if (!selectionArg || !predicateArg) return false; + std::shared_ptr selectionValue; + if (!evalExprValue(selectionArg->value, env, selectionValue)) return false; + const auto array = std::dynamic_pointer_cast(selectionValue); + if (!array) { + throw InterpreterError("where(...) on a join result expects an array of {left, right} pairs"); + } + static const SymbolId leftId = symbolIdForName("left"); + static const SymbolId rightId = symbolIdForName("right"); + std::vector> matches; + for (const auto& item : array->items) { + const auto pair = std::dynamic_pointer_cast(item); + Env rowEnv = env; + if (pair) { + if (const auto leftValue = findMapValue(pair, "left")) rowEnv[leftId] = leftValue; + if (const auto rightValue = findMapValue(pair, "right")) rowEnv[rightId] = rightValue; + } + std::shared_ptr matched; + if (evalExprValue(predicateArg->value, rowEnv, matched)) { + if (const auto matchedBool = std::dynamic_pointer_cast(matched); + matchedBool && matchedBool->value) { + matches.push_back(item->clone()); + } + } + } + out = std::make_shared(std::move(matches)); + return true; +} + +// Shared by csv.toFacts (raw CSV text) and csv.toFelidaeFacts (an +// already-parsed array, e.g. from csv.parse): each row's own fields become +// one new fact of `type`, the same way Type.insert(values:) already does +// for a single map (Interpreter.cpp's FactInsert case) - `source`, when +// given, is recorded the same way so a later db.sync/Type.update/delete +// writes back only these rows' file instead of the whole store. +std::shared_ptr Interpreter::insertFactsFromRows(const std::string& type, + const std::vector>& rows, + const std::filesystem::path& source) { + std::vector> inserted; + inserted.reserve(rows.size()); + for (const auto& row : rows) { + const auto rowMap = std::dynamic_pointer_cast(row); + if (!rowMap) throw InterpreterError("csv.toFacts expects every row to be a map of fields"); + auto fact = std::static_pointer_cast(rowMap->clone()); + fact->factType = type; + memory_.addFact(type, {}, fact, source); + inserted.push_back(fact); + } + return std::make_shared(std::move(inserted)); +} + bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::shared_ptr& out) { if (term.builtinId == BuiltinId::CommonAncestors || term.builtinId == BuiltinId::LowestCommonAncestor || @@ -5108,6 +5265,15 @@ bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::sha // identity. The reasoning runtime resolves only its query arguments. return evalReasoningBuiltin(term, env, out); } + if (term.builtinId == BuiltinId::ArrayWhere) { + // Same reasoning as Reasoning.prove above: where(...) after join(...) + // is `left`/`right` comparisons (e.g. left.id == right.school_id). + // Those names are only meaningful once bound per candidate pair, so + // the predicate must stay unevaluated here and be run once per row + // instead - the eager per-argument evaluation loop below would run + // it now with nothing bound. + return evalArrayWherePredicate(term, env, out); + } std::vector> args; args.reserve(term.args.size()); for (const auto& arg : term.args) { @@ -5133,7 +5299,7 @@ bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::sha const auto source = std::dynamic_pointer_cast(args.front()); if (!source) throw InterpreterError("system.run expects a string source"); try { - auto tokenizer = std::make_shared(); + auto tokenizer = std::make_shared(); IntegerTokenList tokenList(std::move(tokenizer), source->value); IntegerParser parser(tokenList); if (parser.startsQuery()) { @@ -5170,9 +5336,38 @@ bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::sha } } + if (term.builtinId == BuiltinId::FactLimit) { + const auto argument = [&](const char* name, std::size_t positional) + -> std::shared_ptr { + for (std::size_t index = 0; index < term.args.size(); ++index) { + if (term.args[index].name == name) return args[index]; + } + return positional < args.size() ? args[positional] : nullptr; + }; + // .limit(...) closes either a lazy Type.where(...) selection or an + // already-materialized array - e.g. join(...).where(...).order_by(...) + // - so it accepts whichever it is handed rather than requiring a + // FactSelectionExpr the way AndWhere/OrWhere below still do (they + // need the lazy filter list to keep composing). + const auto selectionArg = argument("selection", 0); + auto rows = std::dynamic_pointer_cast(selectionArg) + ? materializeFactSelection(selectionArg) + : std::dynamic_pointer_cast(selectionArg); + if (!rows) throw InterpreterError("Fact selection operation expects Type.where(...) or an array"); + const auto count = std::dynamic_pointer_cast(argument("records", 1)); + if (!count || count->value < 0 || std::floor(count->value) != count->value) { + throw InterpreterError("Fact.limit expects a non-negative integer records value"); + } + std::vector> limited = rows->items; + if (limited.size() > static_cast(count->value)) { + limited.resize(static_cast(count->value)); + } + out = std::make_shared(std::move(limited)); + return true; + } + if (term.builtinId == BuiltinId::FactAndWhere || - term.builtinId == BuiltinId::FactOrWhere || - term.builtinId == BuiltinId::FactLimit) { + term.builtinId == BuiltinId::FactOrWhere) { const auto argument = [&](const char* name, std::size_t positional) -> std::shared_ptr { for (std::size_t index = 0; index < term.args.size(); ++index) { @@ -5182,18 +5377,6 @@ bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::sha }; const auto selection = std::dynamic_pointer_cast(argument("selection", 0)); if (!selection) throw InterpreterError("Fact selection operation expects Type.where(...)"); - if (term.builtinId == BuiltinId::FactLimit) { - const auto count = std::dynamic_pointer_cast(argument("records", 1)); - if (!count || count->value < 0 || std::floor(count->value) != count->value) { - throw InterpreterError("Fact.limit expects a non-negative integer records value"); - } - auto rows = materializeFactSelection(selection); - if (rows->items.size() > static_cast(count->value)) { - rows->items.resize(static_cast(count->value)); - } - out = std::move(rows); - return true; - } const auto match = std::dynamic_pointer_cast(argument("match", 1)); if (!match) throw InterpreterError("Fact filter expects a map of fields"); auto filtered = std::static_pointer_cast(selection->clone()); @@ -5229,6 +5412,89 @@ bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::sha return true; } + if (term.builtinId == BuiltinId::FactJoin) { + // join(TypeA, TypeB) is the full cross product, deliberately + // unfiltered: every {left, right} pair of one TypeA fact with one + // TypeB fact. A capitalized type name that never resolves as an + // ordinary value survives the earlier eager-eval loop as its own + // VarExpr (the same fallback Type.all()/Type.count() rely on). + if (args.size() != 2) throw InterpreterError("join expects two fact type names"); + const auto leftType = std::dynamic_pointer_cast(args[0]); + const auto rightType = std::dynamic_pointer_cast(args[1]); + if (!leftType || !leftType->isCapitalized || !rightType || !rightType->isCapitalized) { + throw InterpreterError("join expects two fact type names, e.g. join(School, Teacher)"); + } + ensurePredicateLoaded(leftType->name); + ensurePredicateLoaded(rightType->name); + const auto rowsOf = [&](const std::string& type) { + std::vector> rows; + for (size_t index : memory_.currentFactIndexes(memory_.compatibleFactIndexes(type))) { + if (const auto value = memory_.factValue(index)) rows.push_back(value); + } + return rows; + }; + const auto leftRows = rowsOf(leftType->name); + const auto rightRows = rowsOf(rightType->name); + std::vector> pairs; + pairs.reserve(leftRows.size() * rightRows.size()); + for (const auto& leftRow : leftRows) { + for (const auto& rightRow : rightRows) { + pairs.push_back(std::make_shared(std::vector{ + MapEntry{"left", leftRow->clone()}, + MapEntry{"right", rightRow->clone()}})); + } + } + out = std::make_shared(std::move(pairs)); + return true; + } + + if (term.builtinId == BuiltinId::ArrayOrderBy) { + const auto argument = [&](const char* name, std::size_t positional) + -> std::shared_ptr { + for (std::size_t index = 0; index < term.args.size(); ++index) { + if (term.args[index].name == name) return args[index]; + } + return positional < args.size() ? args[positional] : nullptr; + }; + const auto array = std::dynamic_pointer_cast(argument("selection", 0)); + if (!array) throw InterpreterError("order_by expects an array"); + std::string fieldPath; + if (!argAsString(argument("field", 1), fieldPath) || fieldPath.empty()) { + throw InterpreterError("order_by expects a 'field' path such as \"right.name\""); + } + const auto valueAtPath = [&](const std::shared_ptr& row) -> std::shared_ptr { + std::shared_ptr current = row; + std::size_t start = 0; + while (current && start <= fieldPath.size()) { + const auto dot = fieldPath.find('.', start); + const auto segment = fieldPath.substr(start, dot == std::string::npos ? std::string::npos : dot - start); + current = findMapValue(current, segment); + if (dot == std::string::npos) break; + start = dot + 1; + } + return current; + }; + std::vector> items = array->items; + std::stable_sort(items.begin(), items.end(), + [&](const std::shared_ptr& lhs, const std::shared_ptr& rhs) { + const auto leftValue = valueAtPath(lhs); + const auto rightValue = valueAtPath(rhs); + double leftNumber = 0.0, rightNumber = 0.0; + if (leftValue && rightValue && + argAsNumber(leftValue, leftNumber) && argAsNumber(rightValue, rightNumber)) { + return leftNumber < rightNumber; + } + std::string leftText, rightText; + if (leftValue && rightValue && + argAsString(leftValue, leftText) && argAsString(rightValue, rightText)) { + return leftText < rightText; + } + return false; + }); + out = std::make_shared(std::move(items)); + return true; + } + if (term.builtinId == BuiltinId::FactInsert || term.builtinId == BuiltinId::FactUpdate || term.builtinId == BuiltinId::FactDelete) { @@ -5282,21 +5548,9 @@ bool Interpreter::evalBuiltinTerm(const TermExpr& term, const Env& env, std::sha if (term.builtinId == BuiltinId::Type) { if (args.size() != 1) return false; - if (auto ast = std::dynamic_pointer_cast(args.front())) { - out = std::make_shared(ast->nodeKind); - return true; - } - if (auto type = std::dynamic_pointer_cast( - findMapValue(args.front(), internalSymbolString(InternalSymbolKind::Type)))) { - out = type->clone(); - return true; - } - if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("number"); - else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("string"); - else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("bool"); - else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("array"); - else if (std::dynamic_pointer_cast(args.front())) out = std::make_shared("nil"); - else return false; + std::string resolvedType; + if (!resolveRuntimeTypeName(args.front(), resolvedType)) return false; + out = std::make_shared(resolvedType); return true; } @@ -6003,6 +6257,63 @@ bool Interpreter::evalCallAsValueOnce( return true; } + if (builtin == BuiltinId::CsvParse) { + const std::string data = requireNamedString({"data", "text", "content"}, 0, "data"); + try { + out = csvTextToRows(data); + } catch (const std::exception& e) { + throw InterpreterError("csv.parse failed: " + std::string(e.what())); + } + return true; + } + + if (builtin == BuiltinId::CsvToFacts) { + const std::string data = requireNamedString({"data", "text", "content"}, 0, "data"); + const std::string type = requireNamedString({"type"}, 1, "type"); + std::string source; + if (const Arg* sourceArg = findTermArgByNameOrIndex(term, "source", 2)) { + std::shared_ptr sourceValue; + if (!evalExprValue(sourceArg->value, env, sourceValue) || !argAsString(sourceValue, source)) { + throw InterpreterError("csv.toFacts expects string argument 'source'"); + } + } + std::shared_ptr rows; + try { + rows = csvTextToRows(data); + } catch (const std::exception& e) { + throw InterpreterError("csv.toFacts failed: " + std::string(e.what())); + } + out = insertFactsFromRows(type, rows->items, source); + return true; + } + + if (builtin == BuiltinId::CsvToFelidaeFacts) { + std::shared_ptr dataValue; + if (!evalNamed("data", 0, dataValue)) { + throw InterpreterError("csv.toFelidaeFacts expects array argument 'data'"); + } + std::vector> rows; + if (!exprAsArrayItems(dataValue, rows)) { + throw InterpreterError("csv.toFelidaeFacts expects array argument 'data'"); + } + const std::string type = requireNamedString({"type"}, 1, "type"); + out = insertFactsFromRows(type, rows, {}); + return true; + } + + if (builtin == BuiltinId::CsvToText) { + std::shared_ptr dataValue; + if (!evalNamed("data", 0, dataValue)) { + throw InterpreterError("csv.toText expects array argument 'data'"); + } + std::vector> rows; + if (!exprAsArrayItems(dataValue, rows)) { + throw InterpreterError("csv.toText expects array argument 'data'"); + } + out = std::make_shared(rowsToCsvText(rows)); + return true; + } + if (builtin == BuiltinId::JsonParse) { std::string jsonText = requireNamedString({"data", "value"}, 0, "data"); std::shared_ptr parsed; @@ -6477,7 +6788,8 @@ bool Interpreter::evalCallAsValueOnce( case BuiltinId::MathAbs: case BuiltinId::MathFloor: case BuiltinId::MathCeil: - case BuiltinId::MathRound: { + case BuiltinId::MathRound: + case BuiltinId::MathCbrt: { double value = requireNamedNumber({"value", "data", "x"}, 0, "value"); switch (term.builtinId) { case BuiltinId::MathSqrt: out = std::make_shared(std::sqrt(value)); break; @@ -6494,6 +6806,12 @@ bool Interpreter::evalCallAsValueOnce( case BuiltinId::MathFloor: out = std::make_shared(std::floor(value)); break; case BuiltinId::MathCeil: out = std::make_shared(std::ceil(value)); break; case BuiltinId::MathRound: out = std::make_shared(std::round(value)); break; + // Signed cube root: unlike pow(value, 1/3), this is defined + // for negative inputs too (cbrt(-8) == -2), which is the one + // operation of the old VM's NumericOperation set that plain + // .fx arithmetic genuinely cannot reproduce (every other + // operation below is now a core/math.fx function instead). + case BuiltinId::MathCbrt: out = std::make_shared(std::cbrt(value)); break; default: break; } return true; @@ -6718,19 +7036,12 @@ bool Interpreter::evalCallAsValueOnce( throw InterpreterError(term.name + " expects arrays of equal length"); } if (left.empty()) throw InterpreterError(term.name + " expects non-empty arrays"); -#ifdef FELIDAE_HAS_EIGEN - Eigen::VectorXd lhs(static_cast(left.size())); - Eigen::VectorXd rhs(static_cast(right.size())); - for (size_t i = 0; i < left.size(); ++i) { - lhs(static_cast(i)) = requireNumber(left[i], term.name, "left"); - rhs(static_cast(i)) = requireNumber(right[i], term.name, "right"); - } - if (op == "dot") { - out = std::make_shared(lhs.dot(rhs)); - } else { - out = std::make_shared((lhs - rhs).squaredNorm() / static_cast(left.size())); - } -#else + // Plain scalar accumulation, not a vendored linear-algebra library: + // these vectors are small (fact/array-sized), so there is no real + // need for a heavyweight Eigen dependency here, and none was ever + // wired into the build (no FELIDAE_HAS_EIGEN definition existed + // anywhere in CMakeLists.txt - the branch that used to guard this + // was permanently dead code). double total = 0.0; for (size_t i = 0; i < left.size(); ++i) { double a = requireNumber(left[i], term.name, "left"); @@ -6738,7 +7049,6 @@ bool Interpreter::evalCallAsValueOnce( total += op == "dot" ? a * b : (a - b) * (a - b); } out = std::make_shared(op == "dot" ? total : total / static_cast(left.size())); -#endif return true; } throw InterpreterError("Unknown ml builtin: " + term.name); @@ -8763,7 +9073,18 @@ Interpreter::ClauseList* Interpreter::findClauses(const std::string& name, Symbo } if (nameId == 0) nameId = symbolIdForName(name); auto found = clauses_->find(nameId); - if (found == clauses_->end()) return nullptr; + // "No clauses under this name" is itself a stable answer - invalidated + // the same way a real hit is, by addClause erasing this exact name's + // entry the moment a clause is actually added under it (see addClause). + // Every builtin call whose Call/TermExpr name (e.g. "Fact:select", + // "Fact:andWhere") no user program ever defines a clause for used to + // fall through this miss on every single invocation forever - measured + // as the dominant share of dispatchCacheMisses_ (e.g. ~91% miss rate + // running v2_examples/csv_fact_database.fx --benchmark-repeat 50). + if (found == clauses_->end()) { + if (cacheInvalidationDepth_ == 0) clauseLookupCache_[name] = nullptr; + return nullptr; + } for (auto& bucket : found->second) { if (bucket.name == name) { auto* clauses = &bucket.clauses; @@ -8771,6 +9092,7 @@ Interpreter::ClauseList* Interpreter::findClauses(const std::string& name, Symbo return clauses; } } + if (cacheInvalidationDepth_ == 0) clauseLookupCache_[name] = nullptr; return nullptr; } @@ -8785,7 +9107,10 @@ const Interpreter::ClauseList* Interpreter::findClauses(const std::string& name, } if (nameId == 0) nameId = symbolIdForName(name); auto found = clauses_->find(nameId); - if (found == clauses_->end()) return nullptr; + if (found == clauses_->end()) { + if (cacheInvalidationDepth_ == 0) clauseLookupCache_[name] = nullptr; + return nullptr; + } for (const auto& bucket : found->second) { if (bucket.name == name) { auto* clauses = const_cast(&bucket.clauses); @@ -8793,6 +9118,7 @@ const Interpreter::ClauseList* Interpreter::findClauses(const std::string& name, return clauses; } } + if (cacheInvalidationDepth_ == 0) clauseLookupCache_[name] = nullptr; return nullptr; } diff --git a/src/Interpreter.h b/src/Interpreter.h index 4771a5b..7968573 100644 --- a/src/Interpreter.h +++ b/src/Interpreter.h @@ -6,6 +6,7 @@ #include "NativeRuntime.h" #include "ParserMetrics.h" #include +#include #include #include #include @@ -67,6 +68,25 @@ class Interpreter { // module is owned by the frontend; callers add it to any watch set. std::vector loadedSourceFiles() const; + // Real (not simulated) execution control for a driving debugger: called + // once per goal, immediately before it runs, from solveIterative's + // dispatch loop - the same point every top-level goal and every method + // body's goals pass through (method calls recurse back into that same + // loop via solveRecursive), so one hook covers both without threading a + // callback through every call site. The hook receives the live Env for + // that goal, so `print`/`locals` during a pause see real bound values, + // not placeholders, and the real method call-stack depth (methodCallDepth_, + // shared with the recursion-limit check in solveMethodCall) rather than + // solveIterative's own frame nesting depth, which also counts group/if/or + // bodies and - for a method called from expression position, e.g. `b := + // helper(x: a)` - does not increase at all. Costs one null std::function + // check per goal when unset (the default), so running without a debugger + // attached pays nothing beyond that. Only main.cpp's CLI debug driver + // installs one; the interpreter itself has no notion of breakpoints or + // step modes. + using GoalHook = std::function; + void setGoalHook(GoalHook hook) { goalHook_ = std::move(hook); } + private: struct ThreadTask { explicit ThreadTask(std::string functionName) : functionName(std::move(functionName)) {} @@ -143,8 +163,11 @@ class Interpreter { using ClauseTable = std::unordered_map>; struct ProvenanceNode { - enum class Kind { Fact, Rule }; - Kind kind = Kind::Fact; + // Reuses ClauseKind (AST.h) rather than a private Fact/Rule enum: + // every provenance node originates from a ClauseStmt that already + // carries this same classification, so a second copy would only be + // able to drift from it. + ClauseKind kind = ClauseKind::Fact; std::uint64_t factId = 0; std::string rule; SourceSpan span; @@ -277,6 +300,7 @@ class Interpreter { std::size_t streamedModuleMicros_ = 0; ParserMetrics parserMetrics_; std::size_t factRegistrationMicros_ = 0; + GoalHook goalHook_; mutable std::size_t dispatchCacheHits_ = 0; mutable std::size_t dispatchCacheMisses_ = 0; std::size_t tableCacheHits_ = 0; @@ -324,6 +348,12 @@ class Interpreter { bool evalReasoningBuiltin(const TermExpr& term, const Env& env, std::shared_ptr& out); + bool evalArrayWherePredicate(const TermExpr& term, + const Env& env, + std::shared_ptr& out); + std::shared_ptr insertFactsFromRows(const std::string& type, + const std::vector>& rows, + const std::filesystem::path& source); bool evalReasoningContrary(const TermExpr& term, const Env& env, std::shared_ptr& out); @@ -453,6 +483,7 @@ class Interpreter { }; FactMaterialization factToMap(const ClauseStmt& clause); std::shared_ptr materializeFactSelection(const std::shared_ptr& selection); + std::shared_ptr materializeIfFactSelection(const std::shared_ptr& value); void refreshAncestryCaches() const; const std::vector& typeAncestry(const std::string& type) const; const std::unordered_map& typeAncestorDistances( diff --git a/src/NativeJson.h b/src/NativeJson.h index 89a351c..ad1162f 100644 --- a/src/NativeJson.h +++ b/src/NativeJson.h @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -29,168 +31,63 @@ inline void skipWhitespace(const std::string& source, size_t& position) { } } -inline bool parseValue(const std::string& source, size_t& position, Value& value); - -inline bool parseString(const std::string& source, size_t& position, std::string& value) { - if (position >= source.size() || source[position] != '"') return false; - ++position; - while (position < source.size()) { - const char current = source[position++]; - if (current == '"') return true; - if (current != '\\') { - value.push_back(current); - continue; - } - if (position >= source.size()) return false; - const char escaped = source[position++]; - switch (escaped) { - case '"': value.push_back('"'); break; - case '\\': value.push_back('\\'); break; - case '/': value.push_back('/'); break; - case 'b': value.push_back('\b'); break; - case 'f': value.push_back('\f'); break; - case 'n': value.push_back('\n'); break; - case 'r': value.push_back('\r'); break; - case 't': value.push_back('\t'); break; - default: return false; - } - } - return false; -} - -inline bool parseArray(const std::string& source, size_t& position, Value& value) { - if (position >= source.size() || source[position] != '[') return false; - ++position; - value.kind = Value::Kind::Array; - skipWhitespace(source, position); - if (position < source.size() && source[position] == ']') { - ++position; - return true; - } - while (position < source.size()) { - Value item; - if (!parseValue(source, position, item)) return false; - value.items.push_back(std::move(item)); - skipWhitespace(source, position); - if (position < source.size() && source[position] == ',') { - ++position; - continue; - } - if (position < source.size() && source[position] == ']') { - ++position; - return true; - } - return false; - } - return false; -} - -inline bool parseObject(const std::string& source, size_t& position, Value& value) { - if (position >= source.size() || source[position] != '{') return false; - ++position; - value.kind = Value::Kind::Object; - skipWhitespace(source, position); - if (position < source.size() && source[position] == '}') { - ++position; - return true; - } - while (position < source.size()) { - skipWhitespace(source, position); - std::string key; - if (!parseString(source, position, key)) return false; - skipWhitespace(source, position); - if (position >= source.size() || source[position] != ':') return false; - ++position; - Value fieldValue; - if (!parseValue(source, position, fieldValue)) return false; - value.fieldOrder.push_back(key); - value.fields.emplace(std::move(key), std::move(fieldValue)); - skipWhitespace(source, position); - if (position < source.size() && source[position] == ',') { - ++position; - continue; - } - if (position < source.size() && source[position] == '}') { - ++position; - return true; - } - return false; - } - return false; -} - -inline bool parseNumber(const std::string& source, size_t& position, Value& value) { - const size_t start = position; - if (position < source.size() && source[position] == '-') ++position; - if (position >= source.size()) return false; - if (source[position] == '0') { - ++position; - } else { - if (!std::isdigit(static_cast(source[position]))) return false; - while (position < source.size() && - std::isdigit(static_cast(source[position]))) { - ++position; - } - } - if (position < source.size() && source[position] == '.') { - ++position; - if (position >= source.size() || - !std::isdigit(static_cast(source[position]))) { - return false; - } - while (position < source.size() && - std::isdigit(static_cast(source[position]))) { - ++position; - } - } - if (position < source.size() && - (source[position] == 'e' || source[position] == 'E')) { - ++position; - if (position < source.size() && - (source[position] == '+' || source[position] == '-')) { - ++position; - } - if (position >= source.size() || - !std::isdigit(static_cast(source[position]))) { - return false; - } - while (position < source.size() && - std::isdigit(static_cast(source[position]))) { - ++position; - } +inline Value fromNlohmann(const nlohmann::json& node) { + Value value; + switch (node.type()) { + case nlohmann::json::value_t::null: + case nlohmann::json::value_t::discarded: + value.kind = Value::Kind::Null; + break; + case nlohmann::json::value_t::boolean: + value.kind = Value::Kind::Bool; + value.boolean = node.get(); + break; + case nlohmann::json::value_t::number_integer: + case nlohmann::json::value_t::number_unsigned: + case nlohmann::json::value_t::number_float: + value.kind = Value::Kind::Number; + value.number = node.get(); + break; + case nlohmann::json::value_t::string: + value.kind = Value::Kind::String; + value.text = node.get(); + break; + case nlohmann::json::value_t::array: + value.kind = Value::Kind::Array; + value.items.reserve(node.size()); + for (const auto& item : node) value.items.push_back(fromNlohmann(item)); + break; + case nlohmann::json::value_t::object: + value.kind = Value::Kind::Object; + value.fieldOrder.reserve(node.size()); + for (auto entry = node.begin(); entry != node.end(); ++entry) { + value.fieldOrder.push_back(entry.key()); + value.fields.emplace(entry.key(), fromNlohmann(entry.value())); + } + break; + default: + value.kind = Value::Kind::Null; + break; } - value.kind = Value::Kind::Number; - value.number = std::strtod(source.substr(start, position - start).c_str(), nullptr); - return std::isfinite(value.number); + return value; } +// Parses through the real JSON grammar parser (nlohmann::json, already +// vendored at third_party/nlohmann_json) rather than a second, bespoke +// recursive-descent one: hand-rolling string escapes, number formats +// (exponents, leading-zero rejection), and object/array nesting here would +// only be duplicating what that library already does correctly. Every call +// site in this codebase parses one complete document starting at position +// 0, never several values back-to-back from the same buffer, so "parse the +// rest of source as one document" is exactly what "one value from position" +// needs to mean. inline bool parseValue(const std::string& source, size_t& position, Value& value) { - skipWhitespace(source, position); - if (position >= source.size()) return false; - if (source[position] == '"') { - value.kind = Value::Kind::String; - return parseString(source, position, value.text); - } - if (source[position] == '[') return parseArray(source, position, value); - if (source[position] == '{') return parseObject(source, position, value); - if (source.compare(position, 4, "null") == 0) { - position += 4; - value.kind = Value::Kind::Null; - return true; - } - if (source.compare(position, 4, "true") == 0) { - position += 4; - value.kind = Value::Kind::Bool; - value.boolean = true; - return true; - } - if (source.compare(position, 5, "false") == 0) { - position += 5; - value.kind = Value::Kind::Bool; - value.boolean = false; - return true; - } - return parseNumber(source, position, value); + const std::string remaining = source.substr(position); + const nlohmann::json parsed = nlohmann::json::parse(remaining, nullptr, false); + if (parsed.is_discarded()) return false; + value = fromNlohmann(parsed); + position = source.size(); + return true; } inline Value parse(const char* raw, const std::string& context) { diff --git a/src/ReasoningRuntime.cpp b/src/ReasoningRuntime.cpp index 7129ef0..96dddb5 100644 --- a/src/ReasoningRuntime.cpp +++ b/src/ReasoningRuntime.cpp @@ -342,7 +342,7 @@ Interpreter::buildTableEvaluation( const std::string key = answer.debug(); ProvenanceNode node; - node.kind = ProvenanceNode::Kind::Fact; + node.kind = ClauseKind::Fact; node.factId = fact.id; const std::size_t provenance = evaluation->provenance.size(); evaluation->provenance.push_back(std::move(node)); @@ -478,7 +478,7 @@ Interpreter::buildTableEvaluation( "DerivationLimit: provenance node limit reached"); } ProvenanceNode node; - node.kind = ProvenanceNode::Kind::Rule; + node.kind = ClauseKind::Rule; node.rule = rule->clause->head.name; node.span = rule->clause->sourceSpan; node.parents = std::move(binding.provenance); @@ -666,7 +666,7 @@ std::shared_ptr Interpreter::materializeDerivationResult( if (!visited.insert(handle).second || handle >= evaluation->provenance.size()) continue; const auto& node = evaluation->provenance[handle]; - if (node.kind == ProvenanceNode::Kind::Fact) { + if (node.kind == ClauseKind::Fact) { result.factIds.insert(node.factId); if (explainedFacts.insert(node.factId).second) { result.explanation.push_back(markFact(std::make_shared( diff --git a/src/Tokenizer.cpp b/src/Tokenizer.cpp index 9064c89..cd16c34 100644 --- a/src/Tokenizer.cpp +++ b/src/Tokenizer.cpp @@ -74,16 +74,17 @@ std::filesystem::path defaultTokenizerModelPath() { #endif } -BpeTokenizer::BpeTokenizer(std::filesystem::path modelPath) +WordVocabulary::WordVocabulary(std::filesystem::path modelPath) : modelPath_(modelPath.empty() ? defaultTokenizerModelPath() : std::move(modelPath)) { loadModel(); } -void BpeTokenizer::loadModel() { +void WordVocabulary::loadModel() { std::lock_guard lock(mutex_); entries_.clear(); matchOrder_.clear(); + byBytes_.clear(); std::ifstream input(modelPath_, std::ios::binary); if (input) { std::string line; @@ -95,7 +96,16 @@ void BpeTokenizer::loadModel() { ensureFixedVocabulary(); } -void BpeTokenizer::ensureFixedVocabulary() { +void WordVocabulary::indexEntry(std::size_t index) const { + // Skips index 0 (): its bytes are empty and every other entry's + // absence from byBytes_ is exactly what "unknown" already means, so an + // empty-string key would only ever be a wrong hit for genuinely-empty + // input, never a real spelling. + if (index == 0 || entries_[index].bytes.empty()) return; + byBytes_.emplace(entries_[index].bytes, static_cast(index)); +} + +void WordVocabulary::ensureFixedVocabulary() { const auto &fixed = fixedVocabulary(); if (entries_.empty()) { entries_.reserve(fixed.size()); @@ -119,10 +129,13 @@ void BpeTokenizer::ensureFixedVocabulary() { std::to_string(index) + ": " + modelPath_.string()); } - for (std::size_t index = 1; index < entries_.size(); ++index) + byBytes_.reserve(entries_.size()); + for (std::size_t index = 1; index < entries_.size(); ++index) { + indexEntry(index); if (!entries_[index].bytes.empty()) matchOrder_.emplace_back(entries_[index].bytes, static_cast(index)); + } std::stable_sort(matchOrder_.begin(), matchOrder_.end(), [](const auto &left, const auto &right) { if (left.first.size() != right.first.size()) @@ -131,13 +144,17 @@ void BpeTokenizer::ensureFixedVocabulary() { }); } -int BpeTokenizer::findToken(std::string_view bytes) const { - for (std::size_t index = 1; index < entries_.size(); ++index) - if (entries_[index].bytes == bytes) return static_cast(index); - return -1; +int WordVocabulary::findToken(std::string_view bytes) const { + // O(1) average via byBytes_ instead of a linear scan over every entry: + // this runs once per identifier/digit occurrence encoded, in every + // program, against a vocabulary that only ever grows (700+ entries + // already and counting), so a full scan here was the one lookup every + // encode call paid for unconditionally. + const auto found = byBytes_.find(std::string(bytes)); + return found == byBytes_.end() ? -1 : found->second; } -void BpeTokenizer::appendModelLine(std::string_view bytes) const { +void WordVocabulary::appendModelLine(std::string_view bytes) const { std::error_code error; std::filesystem::create_directories(modelPath_.parent_path(), error); std::ofstream output(modelPath_, std::ios::binary | std::ios::app); @@ -147,7 +164,7 @@ void BpeTokenizer::appendModelLine(std::string_view bytes) const { output << encodeModelSpelling(bytes) << '\n'; } -int BpeTokenizer::appendToken(std::string_view bytes) const { +int WordVocabulary::appendToken(std::string_view bytes, bool addToMatchOrder) const { std::lock_guard lock(mutex_); const int existing = findToken(bytes); if (existing >= 0) return existing; @@ -155,17 +172,20 @@ int BpeTokenizer::appendToken(std::string_view bytes) const { std::string owned(bytes); appendModelLine(owned); entries_.push_back(Entry{encodeModelSpelling(owned), std::move(owned)}); - matchOrder_.emplace_back(entries_.back().bytes, id); - std::stable_sort(matchOrder_.begin(), matchOrder_.end(), - [](const auto &left, const auto &right) { - if (left.first.size() != right.first.size()) - return left.first.size() > right.first.size(); - return left.second < right.second; - }); + indexEntry(static_cast(id)); + if (addToMatchOrder) { + matchOrder_.emplace_back(entries_.back().bytes, id); + std::stable_sort(matchOrder_.begin(), matchOrder_.end(), + [](const auto &left, const auto &right) { + if (left.first.size() != right.first.size()) + return left.first.size() > right.first.size(); + return left.second < right.second; + }); + } return id; } -void BpeTokenizer::prime(std::string_view source) const { +void WordVocabulary::prime(std::string_view source) const { std::vector words; for (std::size_t begin = 0; begin < source.size();) { if (std::isdigit(static_cast(source[begin]))) { @@ -193,12 +213,12 @@ void BpeTokenizer::prime(std::string_view source) const { std::lock_guard lock(mutex_); known = findToken(word) >= 0; } - if (!known) appendToken(word); + if (!known) appendToken(word, false); } } std::vector -BpeTokenizer::encodeWithOffsets(std::string_view text) const { +WordVocabulary::encodeWithOffsets(std::string_view text) const { std::vector result; std::size_t offset = 0; while (offset < text.size()) { @@ -209,7 +229,7 @@ BpeTokenizer::encodeWithOffsets(std::string_view text) const { std::lock_guard lock(mutex_); id = findToken(digit); } - if (id < 0) id = appendToken(digit); + if (id < 0) id = appendToken(digit, false); result.push_back({id, offset, offset + 1}); ++offset; continue; @@ -225,7 +245,7 @@ BpeTokenizer::encodeWithOffsets(std::string_view text) const { std::lock_guard lock(mutex_); id = findToken(word); } - if (id < 0) id = appendToken(word); + if (id < 0) id = appendToken(word, false); result.push_back({id, offset, end}); offset = end; continue; @@ -245,7 +265,7 @@ BpeTokenizer::encodeWithOffsets(std::string_view text) const { } } if (id < 0) { - id = appendToken(text.substr(offset, 1)); + id = appendToken(text.substr(offset, 1), true); length = 1; } result.push_back({id, offset, offset + length}); @@ -254,7 +274,7 @@ BpeTokenizer::encodeWithOffsets(std::string_view text) const { return result; } -std::vector BpeTokenizer::encode(std::string_view text) const { +std::vector WordVocabulary::encode(std::string_view text) const { const auto encoded = encodeWithOffsets(text); std::vector result; result.reserve(encoded.size()); @@ -262,12 +282,12 @@ std::vector BpeTokenizer::encode(std::string_view text) const { return result; } -std::string BpeTokenizer::decode(std::span tokens) const { +std::string WordVocabulary::decode(std::span tokens) const { std::lock_guard lock(mutex_); std::string result; for (const int id : tokens) { if (id < 0 || static_cast(id) >= entries_.size()) - throw std::runtime_error("BPE decode received an invalid token ID"); + throw std::runtime_error("word vocabulary decode received an invalid token ID"); result += entries_[static_cast(id)].bytes; } return result; diff --git a/src/Tokenizer.h b/src/Tokenizer.h index 566c00f..a488931 100644 --- a/src/Tokenizer.h +++ b/src/Tokenizer.h @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace Felidae { @@ -16,13 +17,39 @@ struct EncodedToken { std::size_t end = 0; }; -// Deterministic, training-free BPE vocabulary. Line N in model.txt owns ID N. -// <0xNN> is the escaped spelling for bytes which cannot be represented -// literally in a line-oriented text file. Unknown identifier words are -// appended in encounter order and are immediately reusable by encode/decode. -class BpeTokenizer { +// Deterministic, training-free word vocabulary - not byte-pair encoding. +// Despite the class's former name, no byte-pair merging ever happens here: +// a whole identifier is looked up (and, if unseen, appended) as one atomic +// dictionary entry, and non-word punctuation/operator bytes are matched +// against the same table by longest match. That is exactly what +// README.md/code.md already describe ("unknown words are added +// deterministically in source order", "execution needs no training") - the +// prior name just kept "Bpe" from this project's earlier, removed +// SentencePiece-adjacent tokenizer despite no longer describing what this +// class actually does. +// +// Line N in model.txt owns ID N. <0xNN> is the escaped spelling for bytes +// which cannot be represented literally in a line-oriented text file. +// Unknown identifier words are appended in encounter order and are +// immediately reusable by encode/decode. +// +// Determinism holds within one process run: once a spelling is assigned an +// ID (whether loaded from the checked-in model.txt or appended during this +// run), every later lookup of that same spelling returns that same ID for +// the rest of the run - entries_ is append-only and never reordered or +// rewritten. prime() further makes a single file's own newly-discovered +// words get IDs in a fixed (lexical) order, independent of incidental +// parser backtracking or statement-chunking order. What is NOT guaranteed +// is cross-run stability of IDs assigned to words that are genuinely new to +// this checkout's model.txt: two runs (or two machines) that first meet +// different not-yet-vocabulary words in a different order will grow the +// checked-in file differently. That is a property of any incrementally +// learned, checked-in vocabulary, not a correctness bug in a single run - +// nothing here reads a dynamically assigned ID's numeric value, only its +// identity/equality. +class WordVocabulary { public: - explicit BpeTokenizer(std::filesystem::path modelPath = {}); + explicit WordVocabulary(std::filesystem::path modelPath = {}); std::vector encode(std::string_view text) const; std::vector encodeWithOffsets(std::string_view text) const; @@ -42,13 +69,28 @@ class BpeTokenizer { void loadModel(); void ensureFixedVocabulary(); - int appendToken(std::string_view bytes) const; + // matchOrder is for the longest-match punctuation/operator scan only + // (encodeWithOffsets's non-word, non-digit fallback); word-byte runs and + // digits are always looked up by exact spelling via findToken/byBytes_ + // and never reach that scan, so appending them there too would only cost + // an O(matchOrder_ size) re-sort per new identifier for an entry that can + // never be found again. Only the single "unrecognized punctuation byte" + // call site passes true. + int appendToken(std::string_view bytes, bool addToMatchOrder) const; int findToken(std::string_view bytes) const; void appendModelLine(std::string_view bytes) const; + void indexEntry(std::size_t index) const; std::filesystem::path modelPath_; mutable std::vector entries_; mutable std::vector> matchOrder_; + // findToken used to scan entries_ linearly (O(vocabulary size) per + // identifier occurrence, every occurrence, in every program - the one + // table it never skips). This index makes an exact-spelling lookup O(1) + // average instead, which is the lookup encodeWithOffsets performs for + // every identifier and digit run it sees. Keyed by the same `bytes` (the + // decoded, actual text) findToken compares by. + mutable std::unordered_map byBytes_; mutable std::mutex mutex_; }; diff --git a/src/debugger/AstAnalyzer.cpp b/src/debugger/AstAnalyzer.cpp new file mode 100644 index 0000000..b49d9a2 --- /dev/null +++ b/src/debugger/AstAnalyzer.cpp @@ -0,0 +1,585 @@ +#include "debugger/AstAnalyzer.h" +#include "Symbol.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace Felidae { + +namespace { + +bool isIgnoredName(const std::string &name) { + return name.empty() || name == "_" || + name == internalSymbolName(InternalSymbolKind::SystemResult); +} + +bool isLikelyTypeName(const std::string &name) { + return isFelidaeLikelyTypeName(name) || name == "map"; +} + +// Head parameters in the shape editor integrations want for signature help. +// A head writes either an annotation (`name: string`, `input: Person`) or a +// plain binding (`employee: e`); only the former has a type worth showing, +// which is exactly the distinction isLikelyTypeName already draws for the +// unused-variable diagnostics below. A literal default contributes its own +// kind as the type. +std::vector collectHeadParameters(const Call &head) { + std::vector params; + params.reserve(head.args.size()); + for (const auto &arg : head.args) { + SymbolParameter param; + param.name = arg.name; + if (auto var = std::dynamic_pointer_cast(arg.value)) { + if (isLikelyTypeName(var->name)) { + param.type = var->name; + } else if (param.name.empty()) { + // Positional head argument: the bound variable is the only + // name this parameter has. + param.name = var->name; + } + } else if (std::dynamic_pointer_cast(arg.value)) { + param.type = "string"; + } else if (std::dynamic_pointer_cast(arg.value)) { + param.type = "number"; + } else if (std::dynamic_pointer_cast(arg.value)) { + param.type = "bool"; + } + if (param.name.empty()) + continue; + params.push_back(std::move(param)); + } + return params; +} + +void addVarUse(const std::string &name, std::set &uses) { + if (!isIgnoredName(name)) + uses.insert(name); +} + +void collectExprUses(const std::shared_ptr &expr, + std::set &vars, + std::set &calls) { + if (!expr) + return; + if (auto var = std::dynamic_pointer_cast(expr)) { + addVarUse(var->name, vars); + } else if (auto term = std::dynamic_pointer_cast(expr)) { + calls.insert(term->name); + if (term->name == "Reasoning:contrary") { + for (const auto &arg : term->args) { + if (arg.name != "positive" && arg.name != "negative") + continue; + if (auto predicate = std::dynamic_pointer_cast(arg.value)) { + calls.insert(predicate->value); + } + } + } + if (term->name == "thread:createThread") { + for (const auto &arg : term->args) { + if (arg.name != "function" && arg.name != "name") + continue; + if (auto target = std::dynamic_pointer_cast(arg.value)) + calls.insert(target->value); + } + } + for (const auto &arg : term->args) + collectExprUses(arg.value, vars, calls); + } else if (auto lambda = std::dynamic_pointer_cast(expr)) { + if (auto source = std::dynamic_pointer_cast(lambda->source)) { + if (isLikelyTypeName(source->name)) + calls.insert(source->name); + } + collectExprUses(lambda->source, vars, calls); + collectExprUses(lambda->body, vars, calls); + if (lambda->right) + collectExprUses(lambda->right, vars, calls); + } else if (auto array = std::dynamic_pointer_cast(expr)) { + for (const auto &item : array->items) + collectExprUses(item, vars, calls); + } else if (auto map = std::dynamic_pointer_cast(expr)) { + for (const auto &entry : map->entries) + collectExprUses(entry.value, vars, calls); + } else if (auto access = std::dynamic_pointer_cast(expr)) { + auto targetVar = std::dynamic_pointer_cast(access->target); + if (access->key == "result" && targetVar && targetVar->name == "system") + return; + collectExprUses(access->target, vars, calls); + } else if (auto op = std::dynamic_pointer_cast(expr)) { + for (size_t i = 0; i < op->captureCount(); ++i) + collectExprUses(op->capture(i), vars, calls); + } +} + +void collectGoalUses(const std::shared_ptr &goal, + std::set &vars, + std::set &calls) { + if (!goal) + return; + if (auto call = std::dynamic_pointer_cast(goal)) { + calls.insert(call->call.name); + if (call->call.name == "thread:createThread") { + for (const auto &arg : call->call.args) { + if (arg.name != "function" && arg.name != "name") + continue; + if (auto target = std::dynamic_pointer_cast(arg.value)) + calls.insert(target->value); + } + } + for (const auto &arg : call->call.args) + collectExprUses(arg.value, vars, calls); + } else if (auto notGoal = std::dynamic_pointer_cast(goal)) { + calls.insert(notGoal->call.name); + for (const auto &arg : notGoal->call.args) + collectExprUses(arg.value, vars, calls); + } else if (auto assign = std::dynamic_pointer_cast(goal)) { + if (assign->expr) + collectExprUses(assign->expr, vars, calls); + } else if (auto multi = std::dynamic_pointer_cast(goal)) { + collectExprUses(multi->expr, vars, calls); + } else if (auto binary = std::dynamic_pointer_cast(goal)) { + collectExprUses(binary->left, vars, calls); + collectExprUses(binary->right, vars, calls); + } else if (auto where = std::dynamic_pointer_cast(goal)) { + collectGoalUses(where->condition, vars, calls); + } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { + collectGoalUses(ifGoal->condition, vars, calls); + for (const auto &item : ifGoal->thenBranch) + collectGoalUses(item, vars, calls); + for (const auto &item : ifGoal->elseBranch) + collectGoalUses(item, vars, calls); + } else if (auto ret = std::dynamic_pointer_cast(goal)) { + for (const auto &field : ret->fields) + collectExprUses(field.value, vars, calls); + } else if (auto group = std::dynamic_pointer_cast(goal)) { + for (const auto &item : group->goals) + collectGoalUses(item, vars, calls); + } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { + for (const auto &branch : orGoal->branches) { + for (const auto &item : branch) + collectGoalUses(item, vars, calls); + } + } +} + +void collectAssignedNames(const std::vector> &goals, + std::set &assigned) { + for (const auto &goal : goals) { + if (auto assign = std::dynamic_pointer_cast(goal)) { + if (!isIgnoredName(assign->name)) + assigned.insert(assign->name); + } else if (auto multi = std::dynamic_pointer_cast(goal)) { + for (const auto &target : multi->targets) { + if (!isIgnoredName(target.name)) + assigned.insert(target.name); + } + } else if (auto group = std::dynamic_pointer_cast(goal)) { + collectAssignedNames(group->goals, assigned); + } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { + for (const auto &branch : orGoal->branches) + collectAssignedNames(branch, assigned); + } else if (auto where = std::dynamic_pointer_cast(goal)) { + collectAssignedNames({where->condition}, assigned); + } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { + collectAssignedNames({ifGoal->condition}, assigned); + collectAssignedNames(ifGoal->thenBranch, assigned); + collectAssignedNames(ifGoal->elseBranch, assigned); + } + } +} + +void collectGlobalAssignmentCollisions( + const std::vector> &goals, + const std::set &globals, + std::vector &diagnostics) { + for (const auto &goal : goals) { + if (auto assign = std::dynamic_pointer_cast(goal)) { + if (globals.count(assign->name)) { + diagnostics.push_back(diagnosticFor( + assign.get(), "error", "felidae.immutable.global_reassignment", + "Variable '" + assign->name + + "' is already assigned and immutable.")); + } + } else if (auto multi = std::dynamic_pointer_cast(goal)) { + for (const auto &target : multi->targets) { + if (globals.count(target.name)) { + diagnostics.push_back(diagnosticFor( + multi.get(), "error", "felidae.immutable.global_reassignment", + "Variable '" + target.name + + "' is already assigned and immutable.")); + } + } + } else if (auto group = std::dynamic_pointer_cast(goal)) { + collectGlobalAssignmentCollisions(group->goals, globals, diagnostics); + } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { + for (const auto &branch : orGoal->branches) { + collectGlobalAssignmentCollisions(branch, globals, diagnostics); + } + } else if (auto where = std::dynamic_pointer_cast(goal)) { + collectGlobalAssignmentCollisions({where->condition}, globals, + diagnostics); + } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { + collectGlobalAssignmentCollisions({ifGoal->condition}, globals, + diagnostics); + collectGlobalAssignmentCollisions(ifGoal->thenBranch, globals, + diagnostics); + collectGlobalAssignmentCollisions(ifGoal->elseBranch, globals, + diagnostics); + } + } +} + +std::string factSignature(const ClauseStmt &clause) { + std::vector fields; + fields.reserve(clause.head.args.size()); + for (const auto &arg : clause.head.args) + fields.push_back(arg.name + ":" + arg.value->debug()); + std::sort(fields.begin(), fields.end()); + std::ostringstream out; + out << clause.head.name << "|"; + for (const auto &field : fields) + out << field << "|"; + return out.str(); +} + +void warn(std::vector &diagnostics, const AstNode *node, + std::string code, std::string message) { + diagnostics.push_back( + diagnosticFor(node, "warning", std::move(code), std::move(message))); +} + +void collectDiscardedExpressions( + const std::vector> &goals, const std::string &method, + std::vector &diagnostics) { + for (const auto &goal : goals) { + if (auto binary = std::dynamic_pointer_cast(goal)) { + warn(diagnostics, binary.get(), "felidae.expression.discarded", + "Raw expression '" + binary->debug() + "' in method '" + method + + "' has no result consumer. Use it in where/if, assign or return " + "it, " + "or pass it to a call such as system.print."); + } else if (auto group = std::dynamic_pointer_cast(goal)) { + collectDiscardedExpressions(group->goals, method, diagnostics); + } else if (auto orGoal = std::dynamic_pointer_cast(goal)) { + for (const auto &branch : orGoal->branches) { + collectDiscardedExpressions(branch, method, diagnostics); + } + } else if (auto ifGoal = std::dynamic_pointer_cast(goal)) { + // The condition is consumed by if. Branch bodies still need checking. + collectDiscardedExpressions(ifGoal->thenBranch, method, diagnostics); + collectDiscardedExpressions(ifGoal->elseBranch, method, diagnostics); + } else if (auto assign = std::dynamic_pointer_cast(goal)) { + // Assignment consumes either its expression or nested goal result. + (void)assign; + } else if (auto where = std::dynamic_pointer_cast(goal)) { + // The condition is consumed by where. + (void)where; + } + } +} + +void validateReasoningExpr(const std::shared_ptr &expr, + const AstNode *owner, + std::vector &diagnostics) { + if (!expr) + return; + if (const auto term = std::dynamic_pointer_cast(expr)) { + if (term->name == "Evidence" || term->name == "FuzzyMembership") { + for (const auto &argument : term->args) { + if (argument.name == "probability" || argument.name == "similarity") { + diagnostics.push_back(diagnosticFor( + owner, "error", "felidae.reasoning.dimension_conflation", + term->name + " uses '" + argument.name + + "' as membership evidence. Keep probability, " + "similarity, and fuzzy degree in separate fields.")); + } + if (argument.name != "degree" && argument.name != "reliability") + continue; + const auto number = + std::dynamic_pointer_cast(argument.value); + if (number && (!std::isfinite(number->value) || number->value < 0.0 || + number->value > 1.0)) { + diagnostics.push_back( + diagnosticFor(owner, "error", "felidae.reasoning.invalid_grade", + term->name + " '" + argument.name + + "' must be between 0 and 1.")); + } + } + } + for (const auto &argument : term->args) { + validateReasoningExpr(argument.value, owner, diagnostics); + } + return; + } + if (const auto array = std::dynamic_pointer_cast(expr)) { + for (const auto &item : array->items) { + validateReasoningExpr(item, owner, diagnostics); + } + } else if (const auto map = std::dynamic_pointer_cast(expr)) { + for (const auto &entry : map->entries) { + validateReasoningExpr(entry.value, owner, diagnostics); + } + } else if (const auto op = + std::dynamic_pointer_cast(expr)) { + for (size_t i = 0; i < op->captureCount(); ++i) { + validateReasoningExpr(op->capture(i), owner, diagnostics); + } + } else if (const auto access = std::dynamic_pointer_cast(expr)) { + validateReasoningExpr(access->target, owner, diagnostics); + } else if (const auto lambda = std::dynamic_pointer_cast(expr)) { + validateReasoningExpr(lambda->source, owner, diagnostics); + validateReasoningExpr(lambda->body, owner, diagnostics); + validateReasoningExpr(lambda->right, owner, diagnostics); + } +} + +void validateReasoningGoals(const std::vector> &goals, + std::vector &diagnostics) { + for (const auto &goal : goals) { + if (!goal) + continue; + if (const auto call = std::dynamic_pointer_cast(goal)) { + for (const auto &argument : call->call.args) { + validateReasoningExpr(argument.value, goal.get(), diagnostics); + } + } else if (const auto assignment = + std::dynamic_pointer_cast(goal)) { + validateReasoningExpr(assignment->expr, goal.get(), diagnostics); + } else if (const auto multiAssignment = + std::dynamic_pointer_cast(goal)) { + validateReasoningExpr(multiAssignment->expr, goal.get(), diagnostics); + } else if (const auto binary = + std::dynamic_pointer_cast(goal)) { + validateReasoningExpr(binary->left, goal.get(), diagnostics); + validateReasoningExpr(binary->right, goal.get(), diagnostics); + } else if (const auto returned = + std::dynamic_pointer_cast(goal)) { + for (const auto &field : returned->fields) { + validateReasoningExpr(field.value, goal.get(), diagnostics); + } + } else if (const auto group = std::dynamic_pointer_cast(goal)) { + validateReasoningGoals(group->goals, diagnostics); + } else if (const auto alternatives = + std::dynamic_pointer_cast(goal)) { + for (const auto &branch : alternatives->branches) { + validateReasoningGoals(branch, diagnostics); + } + } else if (const auto conditional = + std::dynamic_pointer_cast(goal)) { + validateReasoningGoals({conditional->condition}, diagnostics); + validateReasoningGoals(conditional->thenBranch, diagnostics); + validateReasoningGoals(conditional->elseBranch, diagnostics); + } else if (const auto where = std::dynamic_pointer_cast(goal)) { + validateReasoningGoals({where->condition}, diagnostics); + } + } +} + +} // namespace + +struct AstAnalysisSession::Impl { + static constexpr std::size_t MaxExactDuplicateFacts = 10000; + + struct DefinitionSummary { + size_t count = 0; + SourceSpan span; + std::vector spans; + // Head parameters of the last-seen declaration, mirroring how `span` + // also tracks the last one. + std::vector params; + }; + + std::vector diagnostics; + std::map methodDefinitions; + std::map factDefinitions; + std::set globals; + // All spans a global name was (re)bound at; the "unused global" + // diagnostic below points at the last one, mirroring how + // methodDefinitions/factDefinitions point at their last span too. + std::map> globalSpanLists; + std::set calls; + std::unordered_set factSignatures; + std::size_t factsSeen = 0; + bool duplicateCheckTruncated = false; + SourceSpan duplicateCheckSpan; +}; + +AstAnalysisSession::AstAnalysisSession() : impl_(std::make_unique()) {} +AstAnalysisSession::~AstAnalysisSession() = default; +AstAnalysisSession::AstAnalysisSession(AstAnalysisSession &&) noexcept = + default; +AstAnalysisSession & +AstAnalysisSession::operator=(AstAnalysisSession &&) noexcept = default; + +void AstAnalysisSession::consume(const std::shared_ptr &stmt) { + if (!stmt) { + impl_->diagnostics.push_back( + diagnosticFor(nullptr, "error", "felidae.parser.null_statement", + "Parser produced an invalid empty statement.")); + return; + } + if (auto binding = std::dynamic_pointer_cast(stmt)) { + impl_->globals.insert(binding->name); + impl_->globalSpanLists[binding->name].push_back(binding->sourceSpan); + std::set vars; + collectExprUses(binding->expr, vars, impl_->calls); + return; + } + + auto clause = std::dynamic_pointer_cast(stmt); + if (!clause) + return; + + if (clause->isFact()) { + auto &definition = impl_->factDefinitions[clause->head.name]; + ++definition.count; + definition.span = clause->sourceSpan; + definition.spans.push_back(clause->sourceSpan); + definition.params = collectHeadParameters(clause->head); + ++impl_->factsSeen; + if (impl_->factsSeen <= Impl::MaxExactDuplicateFacts) { + const std::string signature = factSignature(*clause); + if (!impl_->factSignatures.insert(signature).second) { + warn(impl_->diagnostics, clause.get(), "felidae.fact.duplicate", + "Duplicate fact declaration for '" + clause->head.name + "'."); + } + } else { + impl_->duplicateCheckTruncated = true; + impl_->duplicateCheckSpan = clause->sourceSpan; + } + return; + } + + auto &definition = impl_->methodDefinitions[clause->head.name]; + ++definition.count; + definition.span = clause->sourceSpan; + definition.spans.push_back(clause->sourceSpan); + definition.params = collectHeadParameters(clause->head); + for (const auto &annotation : clause->annotations) { + if (annotation.builtinId == BuiltinId::OverloadAnnotation || + annotation.builtinId == BuiltinId::MatcherAnnotation) { + // Operator dispatch references the annotated implementation even + // though no source-level TermExpr call names it. + impl_->calls.insert(clause->head.name); + } else { + impl_->calls.insert(annotation.name); + } + } + collectGlobalAssignmentCollisions(clause->body, impl_->globals, + impl_->diagnostics); + collectDiscardedExpressions(clause->body, clause->head.name, + impl_->diagnostics); + validateReasoningGoals(clause->body, impl_->diagnostics); + for (const auto &branch : clause->fallbackBranches) { + collectGlobalAssignmentCollisions(branch, impl_->globals, + impl_->diagnostics); + collectDiscardedExpressions(branch, clause->head.name, impl_->diagnostics); + validateReasoningGoals(branch, impl_->diagnostics); + } + std::set declared; + std::set used; + for (const auto &arg : clause->head.args) { + if (!arg.name.empty()) + declared.insert(arg.name); + if (auto var = std::dynamic_pointer_cast(arg.value)) { + if (!isIgnoredName(var->name) && !isLikelyTypeName(var->name)) { + declared.insert(var->name); + } + } + } + collectAssignedNames(clause->body, declared); + for (const auto &branch : clause->fallbackBranches) { + collectAssignedNames(branch, declared); + } + for (const auto &goal : clause->body) { + collectGoalUses(goal, used, impl_->calls); + } + for (const auto &branch : clause->fallbackBranches) { + for (const auto &goal : branch) { + collectGoalUses(goal, used, impl_->calls); + } + } + for (const auto &name : declared) { + if (!used.count(name)) { + warn(impl_->diagnostics, clause.get(), "felidae.variable.unused", + "Variable '" + name + "' is declared but never used in method '" + + clause->head.name + "'."); + } + } +} + +std::vector AstAnalysisSession::finish() { + if (impl_->duplicateCheckTruncated) { + impl_->diagnostics.push_back(diagnosticForSpan( + impl_->duplicateCheckSpan, "warning", + "felidae.analysis.duplicate_check_bounded", + "Exact duplicate-fact diagnostics were bounded after " + + std::to_string(Impl::MaxExactDuplicateFacts) + + " facts to keep streaming analysis memory bounded.")); + } + for (const auto &item : impl_->methodDefinitions) { + if (item.first != "main" && !impl_->calls.count(item.first)) { + impl_->diagnostics.push_back(diagnosticForSpan( + item.second.span, "warning", "felidae.method.unused", + "Method '" + item.first + + "' is defined but not called in this file.")); + } + } + for (const auto &item : impl_->globals) { + if (!impl_->calls.count(item)) { + impl_->diagnostics.push_back(diagnosticForSpan( + impl_->globalSpanLists[item].back(), "warning", + "felidae.global.unused", + "Global '" + item + "' is defined but not referenced in this file.")); + } + } + for (const auto &item : impl_->factDefinitions) { + if (!impl_->calls.count(item.first)) { + impl_->diagnostics.push_back(diagnosticForSpan( + item.second.span, "warning", "felidae.fact.unused", + "Fact type '" + item.first + + "' is declared but not referenced in this file.")); + } + } + return std::move(impl_->diagnostics); +} + +SymbolSummary AstAnalysisSession::symbols() const { + auto toSymbolDefinitions = [](const auto &definitions) { + std::vector result; + result.reserve(definitions.size()); + for (const auto &[name, definition] : definitions) { + result.push_back(SymbolDefinition{name, definition.count, + definition.spans, definition.params}); + } + return result; + }; + + SymbolSummary summary; + summary.methods = toSymbolDefinitions(impl_->methodDefinitions); + summary.facts = toSymbolDefinitions(impl_->factDefinitions); + summary.globals.reserve(impl_->globals.size()); + for (const auto &name : impl_->globals) { + // impl_->globals and impl_->globalSpanLists are always populated + // together in consume(), so every global name has at least one span. + // A global binding has no parameter list; the empty vector is stated + // rather than left to aggregate initialization so adding a field to + // SymbolDefinition does not silently leave one uninitialized here. + summary.globals.push_back( + SymbolDefinition{name, 1, impl_->globalSpanLists.at(name), {}}); + } + return summary; +} + +std::vector analyzeProgramAst(const Program &program) { + AstAnalysisSession session; + for (const auto &statement : program.statements) + session.consume(statement); + return session.finish(); +} + +} // namespace Felidae diff --git a/src/debugger/AstAnalyzer.h b/src/debugger/AstAnalyzer.h new file mode 100644 index 0000000..7dd4fa8 --- /dev/null +++ b/src/debugger/AstAnalyzer.h @@ -0,0 +1,61 @@ +#pragma once + +#include "AST.h" + +#include +#include +#include + +namespace Felidae { + +// AstDiagnostic, diagnosticFor(), and diagnosticForSpan() now live in AST.h +// so the compiler can share them without linking this analyzer. + +// One declared parameter of a method/fact head, e.g. the `name: string` in +// `Greeting(name: string) =>`. `type` is the annotation when the head writes +// one (a type-like identifier such as `string`/`any`/`Person`, or the kind of +// a literal default) and is empty when the head binds a plain variable +// instead, e.g. the `e` in `HasManager(employee: e)`. +struct SymbolParameter { + std::string name; + std::string type; +}; + +struct SymbolDefinition { + std::string name; + std::size_t count = 0; + std::vector spans; + // Parameters of the last-seen declaration of this symbol. Editor + // integrations use these for signature help / parameter info, which is + // why they come from the parsed AST here rather than each extension + // re-deriving them from source text with its own regex. + std::vector params; +}; + +struct SymbolSummary { + std::vector methods; + std::vector facts; + std::vector globals; +}; + +class AstAnalysisSession { +public: + AstAnalysisSession(); + ~AstAnalysisSession(); + AstAnalysisSession(AstAnalysisSession&&) noexcept; + AstAnalysisSession& operator=(AstAnalysisSession&&) noexcept; + AstAnalysisSession(const AstAnalysisSession&) = delete; + AstAnalysisSession& operator=(const AstAnalysisSession&) = delete; + + void consume(const std::shared_ptr& statement); + std::vector finish(); + SymbolSummary symbols() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +std::vector analyzeProgramAst(const Program& program); + +} // namespace Felidae diff --git a/src/debugger/main.cpp b/src/debugger/main.cpp new file mode 100644 index 0000000..0bd8dc8 --- /dev/null +++ b/src/debugger/main.cpp @@ -0,0 +1,1210 @@ +#include "BuiltinRegistry.h" +#include "OperatorAnnotation.h" +#include "Version.h" +#include "debugger/AstAnalyzer.h" +#include "tooling/SourceParser.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#endif + +namespace fs = std::filesystem; +using namespace Felidae; + +struct DebugOptions { + bool stopOnEntry = false; + bool loadImports = false; + bool checkJson = false; + bool metricsJson = false; + bool lspMode = false; + bool listLibraries = false; + bool listBuiltins = false; + bool symbolsJson = false; + bool operatorsJson = false; + bool version = false; + bool help = false; + std::optional programFile; +}; + +static DebugOptions parseDebugCli(int argc, char **argv) { + DebugOptions options; + for (int i = 1; i < argc; ++i) { + std::string arg = argv[i]; + if (arg == "--stop-on-entry") { + options.stopOnEntry = true; + continue; + } + if (arg == "--load-imports") { + options.loadImports = true; + continue; + } + if (arg == "--check") { + // Accepted for compatibility with documented usage; the default + // (non --check-json) path below already does exactly this: parse, + // print FELIDAE_DIAGNOSTIC records, and report FELIDAE_CHECK_OK. + continue; + } + if (arg == "--check-json") { + options.checkJson = true; + continue; + } + if (arg == "--metrics-json") { + options.metricsJson = true; + continue; + } + if (arg == "--lsp") { + options.lspMode = true; + continue; + } + if (arg == "--list-libraries") { + options.listLibraries = true; + continue; + } + if (arg == "--list-builtins") { + options.listBuiltins = true; + continue; + } + if (arg == "--symbols-json") { + options.symbolsJson = true; + continue; + } + if (arg == "--operators-json") { + options.operatorsJson = true; + continue; + } + if (arg == "--version" || arg == "-v") { + options.version = true; + continue; + } + if (arg == "--help" || arg == "-h") { + options.help = true; + continue; + } + if (arg == "--inspect-graph" || arg == "--visualize-data-json" || + arg == "--visualize-data-html" || arg == "--json" || arg == "--html") { + throw std::runtime_error("Visualization options are no longer supported"); + } + if (arg == "--query" || (!arg.empty() && arg.front() == '?')) { + throw std::runtime_error("felidae_debug does not execute queries. Run " + "felidae program.fx '? Query(...)'"); + } + if (!options.programFile) { + options.programFile = fs::path(arg); + continue; + } + throw std::runtime_error("Unexpected debugger argument: " + arg); + } + return options; +} + +static void printDebugUsage(std::ostream &out) { + out << "Felidae AST debugger " << LANGUAGE_VERSION << "\n" + << "Pipeline: word vocabulary -> Integer Parser -> AST Analyzer\n" + << "Usage: felidae_debug [--check|--check-json] " + "[--load-imports]\n" + << "\n" + << "Options:\n" + << " --check Parse and emit FELIDAE_DIAGNOSTIC records.\n" + << " --check-json Emit structured JSON diagnostics for editor " + "integrations.\n" + << " --load-imports Parse source imports before AST analysis; native " + "imports are ignored.\n" + << " --stop-on-entry Wait for a debugger command before analysis.\n" + << " --lsp Start the Felidae JSON-RPC diagnostics server " + "over stdio.\n" + << " --list-libraries Print a JSON array of importable core library " + "names.\n" + << " Resolved relative to when given, " + "otherwise the\n" + << " current directory. Editor integrations should " + "call this\n" + << " instead of hand-maintaining a copy of the module " + "list.\n" + << " --list-builtins Print a JSON array of {name, effect} builtin " + "functions.\n" + << " --symbols-json Print a JSON symbol table (methods, facts, " + "globals with\n" + << " source spans and declared params, plus resolved " + "files and\n" + << " unresolved imports) for . Params back " + "editor\n" + << " signature help. Always follows imports, like " + "--lsp.\n" + << " --operators-json Print versioned, non-executing dynamic operator " + "metadata\n" + << " for , including imported public " + "contracts.\n" + << " --version, -v Print {name, version} as JSON.\n"; +} + +static std::string trimText(const std::string &text); + +static void waitForContinue() { + std::cout << "FELIDAE_DEBUG_STOPPED reason=entry\n" << std::flush; + std::string command; + while (std::getline(std::cin, command)) { + command = trimText(command); + if (command == "continue" || command == "c" || command == "next" || + command == "stepIn" || command == "stepOut") { + std::cout << "FELIDAE_DEBUG_CONTINUED\n" << std::flush; + return; + } + if (command == "disconnect" || command == "terminate" || + command == "exit") { + std::cout << "FELIDAE_DEBUG_TERMINATED\n" << std::flush; + std::exit(0); + } + } +} + +static std::string trimText(const std::string &text) { + std::size_t start = 0; + while (start < text.size() && + std::isspace(static_cast(text[start]))) + start++; + std::size_t end = text.size(); + while (end > start && std::isspace(static_cast(text[end - 1]))) + end--; + return text.substr(start, end - start); +} + +static void printAstDiagnostics(const std::vector &diagnostics) { + for (const auto &diagnostic : diagnostics) { + std::cout << "FELIDAE_DIAGNOSTIC " + << "severity=" << diagnostic.severity << " code=" + << (diagnostic.code.empty() ? "felidae.ast" : diagnostic.code) + << " line=" << diagnostic.line << " column=" << diagnostic.column + << " message=" << diagnostic.message << "\n"; + } +} + +static std::string jsonEscape(const std::string &value) { + std::ostringstream out; + for (char ch : value) { + switch (ch) { + case '\\': + out << "\\\\"; + break; + case '"': + out << "\\\""; + break; + case '\b': + out << "\\b"; + break; + case '\f': + out << "\\f"; + break; + case '\n': + out << "\\n"; + break; + case '\r': + out << "\\r"; + break; + case '\t': + out << "\\t"; + break; + default: + if (static_cast(ch) < 0x20) { + out << "\\u"; + const char *hex = "0123456789abcdef"; + out << "00" << hex[(ch >> 4) & 0x0f] << hex[ch & 0x0f]; + } else { + out << ch; + } + } + } + return out.str(); +} + +static const char *builtinEffectName(BuiltinEffect effect) { + switch (effect) { + case BuiltinEffect::Pure: + return "pure"; + case BuiltinEffect::ReadsExternalState: + return "reads"; + case BuiltinEffect::WritesExternalState: + return "writes"; + case BuiltinEffect::Volatile: + return "volatile"; + } + return "volatile"; +} + +static std::string librariesJson(const std::vector &names) { + std::ostringstream out; + out << "["; + for (size_t i = 0; i < names.size(); ++i) { + if (i) + out << ","; + out << "\"" << jsonEscape(names[i]) << "\""; + } + out << "]"; + return out.str(); +} + +static std::string builtinsJson(const std::vector &infos) { + std::ostringstream out; + out << "["; + for (size_t i = 0; i < infos.size(); ++i) { + if (i) + out << ","; + out << "{\"name\":\"" << jsonEscape(infos[i].name) << "\",\"effect\":\"" + << builtinEffectName(infos[i].effect) << "\"}"; + } + out << "]"; + return out.str(); +} + +static std::string spanJson(const SourceSpan &span) { + std::ostringstream out; + out << "{\"startLine\":" << span.startLine + << ",\"startColumn\":" << span.startColumn + << ",\"endLine\":" << span.endLine << ",\"endColumn\":" << span.endColumn + << "}"; + return out.str(); +} + +static std::string +symbolDefinitionsJson(const std::vector &definitions) { + std::ostringstream out; + out << "["; + for (size_t i = 0; i < definitions.size(); ++i) { + if (i) + out << ","; + const auto &definition = definitions[i]; + out << "{\"name\":\"" << jsonEscape(definition.name) + << "\",\"count\":" << definition.count << ",\"spans\":["; + for (size_t s = 0; s < definition.spans.size(); ++s) { + if (s) + out << ","; + out << spanJson(definition.spans[s]); + } + out << "],\"params\":["; + for (size_t p = 0; p < definition.params.size(); ++p) { + if (p) + out << ","; + out << "{\"name\":\"" << jsonEscape(definition.params[p].name) + << "\",\"type\":\"" << jsonEscape(definition.params[p].type) << "\"}"; + } + out << "]}"; + } + out << "]"; + return out.str(); +} + +static std::string +symbolsJson(const SymbolSummary &symbols, const std::vector &files, + const std::vector &unresolvedImports) { + std::ostringstream out; + out << "{\"methods\":" << symbolDefinitionsJson(symbols.methods) + << ",\"facts\":" << symbolDefinitionsJson(symbols.facts) + << ",\"globals\":" << symbolDefinitionsJson(symbols.globals) + << ",\"files\":["; + for (size_t i = 0; i < files.size(); ++i) { + if (i) + out << ","; + out << "\"" << jsonEscape(files[i].string()) << "\""; + } + out << "],\"unresolvedImports\":["; + for (size_t i = 0; i < unresolvedImports.size(); ++i) { + if (i) + out << ","; + out << "\"" << jsonEscape(unresolvedImports[i]) << "\""; + } + out << "]}"; + return out.str(); +} + +static const char *operatorPrecedenceName(OperatorPrecedence value) { + switch (value) { + case OperatorPrecedence::Control: + return "control"; + case OperatorPrecedence::LogicalOr: + return "logical-or"; + case OperatorPrecedence::LogicalAnd: + return "logical-and"; + case OperatorPrecedence::Relationship: + return "relationship"; + case OperatorPrecedence::Ordering: + return "ordering"; + case OperatorPrecedence::Pipeline: + return "pipeline"; + case OperatorPrecedence::Additive: + return "additive"; + case OperatorPrecedence::Multiplicative: + return "multiplicative"; + case OperatorPrecedence::Prefix: + return "prefix"; + } + return "relationship"; +} + +static const char *operatorAssociativityName(OperatorAssociativity value) { + switch (value) { + case OperatorAssociativity::None: + return "none"; + case OperatorAssociativity::Left: + return "left"; + case OperatorAssociativity::Right: + return "right"; + } + return "none"; +} + +static const char *operatorFixityName(OperatorFixity value) { + switch (value) { + case OperatorFixity::Prefix: + return "prefix"; + case OperatorFixity::Infix: + return "infix"; + case OperatorFixity::Postfix: + return "postfix"; + case OperatorFixity::Mixfix: + return "mixfix"; + } + return "infix"; +} + +static const char *operatorVisibilityName(OperatorVisibility value) { + return value == OperatorVisibility::Public ? "public" : "private"; +} + +static const char *operatorCardinalityName(OperatorCardinality value) { + switch (value) { + case OperatorCardinality::One: + return "one"; + case OperatorCardinality::Optional: + return "optional"; + case OperatorCardinality::Many: + return "many"; + } + return "one"; +} + +static std::string +operatorBindingsJson(const std::vector &bindings) { + std::ostringstream out; + out << "["; + for (size_t i = 0; i < bindings.size(); ++i) { + if (i) + out << ","; + out << "{\"name\":\"" << jsonEscape(bindings[i].name) + << "\",\"nameId\":" << bindings[i].nameId << ",\"type\":\"" + << jsonEscape(bindings[i].type) + << "\",\"typeId\":" << bindings[i].typeId << "}"; + } + out << "]"; + return out.str(); +} + +static std::string +operatorMetadataJson(const OperatorRegistry ®istry, + const std::vector &files, + const std::vector &unresolvedImports) { + std::ostringstream out; + out << "{\"protocol\":\"felidae.operator-metadata\",\"version\":1," + "\"patterns\":["; + const auto &patterns = registry.patterns(); + for (size_t i = 0; i < patterns.size(); ++i) { + if (i) + out << ","; + const auto &pattern = patterns[i]; + out << "{\"operatorId\":" << pattern.operatorId + << ",\"patternId\":" << pattern.patternId << ",\"operator\":\"" + << jsonEscape(pattern.operatorName) << "\",\"pattern\":\"" + << jsonEscape(pattern.pattern) << "\",\"precedence\":\"" + << operatorPrecedenceName(pattern.precedence) + << "\",\"associativity\":\"" + << operatorAssociativityName(pattern.associativity) + << "\",\"fixity\":\"" << operatorFixityName(pattern.fixity) + << "\",\"visibility\":\"" << operatorVisibilityName(pattern.visibility) + << "\",\"module\":\"" << jsonEscape(pattern.module) + << "\",\"anchors\":["; + for (size_t a = 0; a < pattern.anchors.size(); ++a) { + if (a) + out << ","; + out << "\"" << jsonEscape(pattern.anchors[a]) << "\""; + } + out << "],\"captures\":["; + for (size_t c = 0; c < pattern.captureNames.size(); ++c) { + if (c) + out << ","; + out << "\"" << jsonEscape(pattern.captureNames[c]) << "\""; + } + out << "]}"; + } + out << "],\"overloads\":["; + const auto &overloads = registry.overloads(); + for (size_t i = 0; i < overloads.size(); ++i) { + if (i) + out << ","; + const auto &overload = overloads[i]; + out << "{\"operatorId\":" << overload.operatorId + << ",\"patternId\":" << overload.patternId << ",\"method\":\"" + << jsonEscape(overload.methodName) + << "\",\"methodId\":" << overload.methodId + << ",\"captures\":" << operatorBindingsJson(overload.captures) + << ",\"factors\":" << operatorBindingsJson(overload.factors) + << ",\"result\":\"" << jsonEscape(overload.resultType) + << "\",\"cardinality\":\"" + << operatorCardinalityName(overload.cardinality) << "\",\"effects\":\"" + << (overload.effect == OperatorEffect::Pure ? "pure" : "impure") + << "\",\"visibility\":\"" << operatorVisibilityName(overload.visibility) + << "\",\"module\":\"" << jsonEscape(overload.module) << "\"}"; + } + out << "],\"matchers\":["; + const auto &matchers = registry.matchers(); + for (size_t i = 0; i < matchers.size(); ++i) { + if (i) + out << ","; + const auto &matcher = matchers[i]; + out << "{\"operatorId\":" << matcher.operatorId + << ",\"patternId\":" << matcher.patternId << ",\"method\":\"" + << jsonEscape(matcher.methodName) + << "\",\"methodId\":" << matcher.methodId + << ",\"captures\":" << operatorBindingsJson(matcher.captures) + << ",\"produces\":" << operatorBindingsJson(matcher.produces) + << ",\"visibility\":\"" << operatorVisibilityName(matcher.visibility) + << "\",\"module\":\"" << jsonEscape(matcher.module) << "\"}"; + } + out << "],\"files\":["; + for (size_t i = 0; i < files.size(); ++i) { + if (i) + out << ","; + out << "\"" << jsonEscape(files[i].string()) << "\""; + } + out << "],\"unresolvedImports\":["; + for (size_t i = 0; i < unresolvedImports.size(); ++i) { + if (i) + out << ","; + out << "\"" << jsonEscape(unresolvedImports[i]) << "\""; + } + out << "]}"; + return out.str(); +} + +static std::string versionJson(const char *toolName) { + std::ostringstream out; + out << "{\"name\":\"" << jsonEscape(toolName) << "\",\"version\":\"" + << jsonEscape(LANGUAGE_VERSION) << "\"}"; + return out.str(); +} + +static int lspSeverity(const std::string &severity) { + if (severity == "error") + return 1; + if (severity == "info") + return 3; + if (severity == "hint") + return 4; + return 2; +} + +static bool hasErrorDiagnostic(const std::vector &diagnostics) { + return std::any_of(diagnostics.begin(), diagnostics.end(), + [](const AstDiagnostic &diagnostic) { + return diagnostic.severity == "error" || + diagnostic.severity == "fatal"; + }); +} + +static std::string +diagnosticsJson(const std::vector &diagnostics) { + std::ostringstream out; + out << "{\"ok\":" << (hasErrorDiagnostic(diagnostics) ? "false" : "true") + << ",\"diagnostics\":["; + for (size_t i = 0; i < diagnostics.size(); ++i) { + const auto &diagnostic = diagnostics[i]; + if (i) + out << ","; + int line = std::max(1, diagnostic.line); + int column = std::max(1, diagnostic.column); + int endLine = std::max(line, diagnostic.endLine); + int endColumn = + std::max(endLine == line ? column : 1, diagnostic.endColumn); + out << "{\"severity\":\"" << jsonEscape(diagnostic.severity) + << "\",\"lspSeverity\":" << lspSeverity(diagnostic.severity) + << ",\"line\":" << line << ",\"column\":" << column + << ",\"endLine\":" << endLine << ",\"endColumn\":" << endColumn + << ",\"code\":\"" + << jsonEscape(diagnostic.code.empty() ? "felidae.ast" : diagnostic.code) + << "\"" + << ",\"file\":\"" << jsonEscape(diagnostic.file) << "\"" + << ",\"message\":\"" << jsonEscape(diagnostic.message) << "\"}"; + } + out << "]}"; + return out.str(); +} + +static std::string errorJson(const std::string &message) { + return "{\"ok\":false,\"diagnostics\":[{\"severity\":\"error\"," + "\"lspSeverity\":1," + "\"line\":1,\"column\":1,\"message\":\"" + + jsonEscape(message) + "\"}]}"; +} + +static int hexValue(char ch) { + if (ch >= '0' && ch <= '9') + return ch - '0'; + if (ch >= 'a' && ch <= 'f') + return 10 + ch - 'a'; + if (ch >= 'A' && ch <= 'F') + return 10 + ch - 'A'; + return -1; +} + +static std::string percentDecode(const std::string &text) { + std::string decoded; + decoded.reserve(text.size()); + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] == '%' && i + 2 < text.size()) { + int hi = hexValue(text[i + 1]); + int lo = hexValue(text[i + 2]); + if (hi >= 0 && lo >= 0) { + decoded.push_back(static_cast((hi << 4) | lo)); + i += 2; + continue; + } + } + decoded.push_back(text[i]); + } + return decoded; +} + +static std::string fileUriToPath(std::string uri) { + const std::string prefix = "file:///"; + if (uri.rfind(prefix, 0) == 0) { + uri = uri.substr(prefix.size()); +#ifdef _WIN32 + for (char &ch : uri) { + if (ch == '/') + ch = '\\'; + } +#else + uri = "/" + uri; +#endif + } + return percentDecode(uri); +} + +static std::string analyzeTextJson(const fs::path &path, + const std::string &text) { + try { + constexpr size_t kMaxTextCacheEntries = 128; + struct CachedTextAnalysis { + size_t size = 0; + size_t hash = 0; + size_t lastUsed = 0; + std::vector diagnostics; + }; + static std::unordered_map textCache; + static size_t textCacheClock = 0; + + const auto key = fs::absolute(path).lexically_normal().string(); + const auto hash = std::hash{}(text); + std::vector diagnostics; + auto cached = textCache.find(key); + if (cached != textCache.end() && cached->second.size == text.size() && + cached->second.hash == hash) { + cached->second.lastUsed = ++textCacheClock; + diagnostics = cached->second.diagnostics; + } else { + Program program = Tooling::parseText(text); + diagnostics = analyzeProgramAst(program); + for (auto &diagnostic : diagnostics) + diagnostic.file = key; + // Only compact diagnostics survive this request. Keeping Program here + // retained every statement and expression for each open editor file. + textCache[key] = + CachedTextAnalysis{text.size(), hash, ++textCacheClock, diagnostics}; + if (textCache.size() > kMaxTextCacheEntries) { + auto oldest = textCache.end(); + for (auto it = textCache.begin(); it != textCache.end(); ++it) { + if (oldest == textCache.end() || + it->second.lastUsed < oldest->second.lastUsed) { + oldest = it; + } + } + if (oldest != textCache.end()) + textCache.erase(oldest); + } + } + return diagnosticsJson(diagnostics); + } catch (const std::exception &e) { + return errorJson(e.what()); + } +} + +static std::string analyzeFileJson(const fs::path &path) { + try { + AstAnalysisSession analysis; + Tooling::loadProgramStatements( + path, true, [&](const std::shared_ptr &statement) { + analysis.consume(statement); + }); + auto diagnostics = analysis.finish(); + const auto file = fs::absolute(path).lexically_normal().string(); + for (auto &diagnostic : diagnostics) + diagnostic.file = file; + return diagnosticsJson(diagnostics); + } catch (const std::exception &e) { + return errorJson(e.what()); + } +} + +static std::string symbolsFileJson(const fs::path &path, bool loadImports) { + try { + AstAnalysisSession analysis; + auto loaded = Tooling::loadProgramStatements( + path, loadImports, [&](const std::shared_ptr &statement) { + analysis.consume(statement); + }); + return symbolsJson(analysis.symbols(), loaded.files, + loaded.unresolvedImports); + } catch (const std::exception &e) { + return errorJson(e.what()); + } +} + +static std::string operatorsFileJson(const fs::path &path, bool loadImports) { + try { + std::vector> clauses; + auto loaded = Tooling::loadProgramStatements( + path, loadImports, [&](const std::shared_ptr &statement) { + if (auto clause = std::dynamic_pointer_cast(statement)) { + clauses.push_back(std::move(clause)); + } + }); + if (!loaded.operators) + return errorJson("Operator metadata registry was not created"); + for (const auto &clause : clauses) { + for (const auto &annotation : clause->annotations) { + if (annotation.builtinId != BuiltinId::OverloadAnnotation && + annotation.builtinId != BuiltinId::MatcherAnnotation) + continue; + auto parsed = decodeOperatorAnnotation(annotation); + const auto *pattern = + parsed.pattern.empty() + ? loaded.operators->findPatternByOperator(parsed.operatorName) + : loaded.operators->findPattern(parsed.operatorName, + parsed.pattern); + if (!pattern) + throw std::runtime_error( + "Operator annotation pattern was not registered for metadata"); + if (!parsed.hasVisibility) { + parsed.visibility = loaded.operators->visibilityForPattern( + pattern->patternId, clause->module); + } + if (annotation.builtinId == BuiltinId::MatcherAnnotation) { + loaded.operators->registerMatcher(makeOperatorMatcherDefinition( + parsed, *pattern, clause->head.name, clause->head.nameId, + clause->module)); + } else { + loaded.operators->registerOverload(makeOperatorOverloadDefinition( + parsed, *pattern, clause->head.name, clause->head.nameId, + clause->module)); + } + } + } + return operatorMetadataJson(*loaded.operators, loaded.files, + loaded.unresolvedImports); + } catch (const std::exception &e) { + return errorJson(e.what()); + } +} + +static void writeLspMessage(const std::string &body) { + std::cout << "Content-Length: " << body.size() << "\r\n\r\n" + << body << std::flush; +} + +// LSP SymbolKind values used for Felidae declarations. +constexpr int kSymbolKindMethod = 6; +constexpr int kSymbolKindConstant = 14; +constexpr int kSymbolKindStruct = 23; + +// Builds a textDocument/documentSymbol result from the analyzer's own symbol +// table, so the outline comes from the real parse rather than each editor +// re-deriving declarations from source text with its own regex. +static std::string documentSymbolsJson(const SymbolSummary &symbols) { + std::ostringstream out; + out << "["; + bool first = true; + auto emit = [&](const std::vector &group, int kind) { + for (const auto &definition : group) { + if (definition.spans.empty()) + continue; + const SourceSpan &span = definition.spans.back(); + const int line = std::max(0, span.startLine - 1); + const int column = std::max(0, span.startColumn - 1); + const int endLine = std::max(line, span.endLine - 1); + const int endColumn = std::max(0, span.endColumn - 1); + + std::string detail; + if (!definition.params.empty()) { + detail = "("; + for (size_t i = 0; i < definition.params.size(); ++i) { + if (i) + detail += ", "; + detail += definition.params[i].name; + if (!definition.params[i].type.empty()) { + detail += ": " + definition.params[i].type; + } + } + detail += ")"; + } + + if (!first) + out << ","; + first = false; + out << "{\"name\":\"" << jsonEscape(definition.name) + << "\",\"kind\":" << kind << ",\"detail\":\"" << jsonEscape(detail) + << "\",\"range\":{\"start\":{\"line\":" << line + << ",\"character\":" << column << "},\"end\":{\"line\":" << endLine + << ",\"character\":" << endColumn + << "}},\"selectionRange\":{\"start\":{\"line\":" << line + << ",\"character\":" << column << "},\"end\":{\"line\":" << line + << ",\"character\":" << column << "}}}"; + } + }; + emit(symbols.methods, kSymbolKindMethod); + emit(symbols.facts, kSymbolKindStruct); + emit(symbols.globals, kSymbolKindConstant); + out << "]"; + return out.str(); +} + +static void publishDiagnostics(const std::string &uri, + const std::string &checkJson) { + const auto analysis = nlohmann::json::parse(checkJson); + auto diagnostics = nlohmann::json::array(); + for (const auto &diagnostic : analysis.at("diagnostics")) { + const int line = std::max(0, diagnostic.value("line", 1) - 1); + const int column = std::max(0, diagnostic.value("column", 1) - 1); + const int endLine = + std::max(line, diagnostic.value("endLine", line + 1) - 1); + const int endColumn = + std::max(endLine == line ? column + 1 : 0, + diagnostic.value("endColumn", column + 2) - 1); + diagnostics.push_back( + {{"range", + {{"start", {{"line", line}, {"character", column}}}, + {"end", {{"line", endLine}, {"character", endColumn}}}}}, + {"severity", diagnostic.value("lspSeverity", 2)}, + {"source", "Felidae Debugger"}, + {"message", diagnostic.value("message", std::string{})}}); + } + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"method", "textDocument/publishDiagnostics"}, + {"params", {{"uri", uri}, {"diagnostics", std::move(diagnostics)}}}} + .dump()); +} + +static bool readLspMessage(std::string &body) { + std::string line; + size_t contentLength = 0; + while (std::getline(std::cin, line)) { + if (!line.empty() && line.back() == '\r') + line.pop_back(); + if (line.empty()) + break; + const std::string header = "Content-Length:"; + if (line.rfind(header, 0) == 0) { + contentLength = + static_cast(std::stoul(trimText(line.substr(header.size())))); + } + } + if (contentLength == 0) + return false; + body.assign(contentLength, '\0'); + std::cin.read(&body[0], static_cast(contentLength)); + return static_cast(std::cin.gcount()) == contentLength; +} + +// Analyses whichever text the server currently holds for `uri`, falling back +// to reading the file when the client has not sent contents. +static SymbolSummary +symbolsForDocument(const std::map &documents, + const std::string &uri) { + AstAnalysisSession analysis; + try { + const auto existing = documents.find(uri); + if (existing != documents.end()) { + // Unsaved editor contents: parse what the client sent, so the + // outline tracks the buffer rather than the file on disk. + Program program = Tooling::parseText(existing->second); + for (const auto &statement : program.statements) + analysis.consume(statement); + } else { + Tooling::loadProgramStatements( + fileUriToPath(uri), false, + [&](const std::shared_ptr &statement) { + analysis.consume(statement); + }); + } + } catch (const std::exception &) { + // A syntax error mid-edit is normal; report whatever parsed. + } + return analysis.symbols(); +} + +// Namespaced declarations are written with either separator (`Dog.membership` +// or `Dog:membership`), so compare on a single normalized form. +static std::string normalizeSymbolLookupName(std::string name) { + for (char &ch : name) { + if (ch == '.') + ch = ':'; + } + return name; +} + +// Word under the given zero-based position, using Felidae's identifier rules +// (letters, digits, underscore, plus `.`/`:` for namespaced names). +static std::string wordAtPosition(const std::string &text, int line, + int character) { + size_t offset = 0; + for (int current = 0; current < line; ++current) { + const size_t newline = text.find('\n', offset); + if (newline == std::string::npos) + return {}; + offset = newline + 1; + } + const size_t lineStart = offset; + size_t lineEnd = text.find('\n', lineStart); + if (lineEnd == std::string::npos) + lineEnd = text.size(); + size_t cursor = std::min(lineStart + static_cast(character), lineEnd); + + auto isNameChar = [](char ch) { + return std::isalnum(static_cast(ch)) || ch == '_' || + ch == '.' || ch == ':'; + }; + size_t start = cursor; + size_t end = cursor; + while (start > lineStart && isNameChar(text[start - 1])) + --start; + while (end < lineEnd && isNameChar(text[end])) + ++end; + if (start >= end) + return {}; + std::string word = text.substr(start, end - start); + while (!word.empty() && (word.front() == '.' || word.front() == ':')) + word.erase(word.begin()); + while (!word.empty() && (word.back() == '.' || word.back() == ':')) + word.pop_back(); + return word; +} + +// textDocument/definition: resolve the name under the cursor against the +// analyzer's symbol table, which already records every declaration's span. +static std::string +definitionJson(const std::map &documents, + const std::string &uri, int line, int character) { + std::string text; + const auto existing = documents.find(uri); + if (existing != documents.end()) { + text = existing->second; + } else { + std::ifstream input(fileUriToPath(uri), std::ios::binary); + if (input) { + text.assign(std::istreambuf_iterator(input), + std::istreambuf_iterator()); + } + } + const std::string name = wordAtPosition(text, line, character); + if (name.empty()) + return "null"; + + const SymbolSummary symbols = symbolsForDocument(documents, uri); + const std::string normalized = normalizeSymbolLookupName(name); + for (const auto *group : + {&symbols.methods, &symbols.facts, &symbols.globals}) { + for (const auto &definition : *group) { + if (normalizeSymbolLookupName(definition.name) != normalized) + continue; + if (definition.spans.empty()) + continue; + const SourceSpan &span = definition.spans.back(); + std::ostringstream out; + out << "{\"uri\":\"" << jsonEscape(uri) + << "\",\"range\":{\"start\":{\"line\":" + << std::max(0, span.startLine - 1) + << ",\"character\":" << std::max(0, span.startColumn - 1) + << "},\"end\":{\"line\":" << std::max(0, span.endLine - 1) + << ",\"character\":" << std::max(0, span.endColumn - 1) << "}}}"; + return out.str(); + } + } + return "null"; +} + +static int runLspServer() { +#ifdef _WIN32 + // The CRT's default text-mode translation rewrites every '\n' written to + // stdout as "\r\n" - since writeLspMessage()/publishDiagnostics() already + // write explicit "\r\n" header terminators, that turned into "\r\r\n" on + // Windows, corrupting the LSP wire format for any real client. Binary + // mode on stdin avoids the equivalent corruption when reading message + // bodies containing embedded newlines. + _setmode(_fileno(stdout), _O_BINARY); + _setmode(_fileno(stdin), _O_BINARY); +#endif + std::map documents; + std::string body; + while (readLspMessage(body)) { + nlohmann::json request; + try { + request = nlohmann::json::parse(body); + } catch (const nlohmann::json::parse_error &error) { + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", nullptr}, + {"error", {{"code", -32700}, {"message", error.what()}}}} + .dump()); + continue; + } + if (!request.is_object()) { + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", nullptr}, + {"error", {{"code", -32600}, {"message", "Invalid Request"}}}} + .dump()); + continue; + } + const auto methodValue = request.find("method"); + if (methodValue == request.end() || !methodValue->is_string()) { + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", request.value("id", nlohmann::json(nullptr))}, + {"error", {{"code", -32600}, {"message", "Invalid Request"}}}} + .dump()); + continue; + } + const std::string method = methodValue->get(); + const bool hasId = request.contains("id"); + const auto id = hasId ? request.at("id") : nlohmann::json(nullptr); + const auto params = request.value("params", nlohmann::json::object()); + if (!params.is_object()) { + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", id}, + {"error", {{"code", -32602}, {"message", "Invalid params"}}}} + .dump()); + continue; + } + const auto textDocument = + params.value("textDocument", nlohmann::json::object()); + if (!textDocument.is_object()) { + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", id}, + {"error", {{"code", -32602}, {"message", "Invalid params"}}}} + .dump()); + continue; + } + const auto uriValue = textDocument.find("uri"); + const std::string uri = + uriValue != textDocument.end() && uriValue->is_string() + ? uriValue->get() + : std::string{}; + if (method == "initialize") { + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", id}, + {"result", + {{"capabilities", + {{"textDocumentSync", 1}, + {"documentSymbolProvider", true}, + {"definitionProvider", true}}}, + {"serverInfo", + {{"name", "felidae_debug"}, {"version", LANGUAGE_VERSION}}}}}} + .dump()); + } else if (method == "textDocument/documentSymbol") { + writeLspMessage( + nlohmann::json{{"jsonrpc", "2.0"}, + {"id", id}, + {"result", nlohmann::json::parse(documentSymbolsJson( + symbolsForDocument(documents, uri)))}} + .dump()); + } else if (method == "textDocument/definition") { + const auto position = params.value("position", nlohmann::json::object()); + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", id}, + {"result", nlohmann::json::parse(definitionJson( + documents, uri, std::max(0, position.value("line", 0)), + std::max(0, position.value("character", 0))))}} + .dump()); + } else if (method == "shutdown") { + writeLspMessage( + nlohmann::json{{"jsonrpc", "2.0"}, {"id", id}, {"result", nullptr}} + .dump()); + } else if (method == "exit") { + return 0; + } else if (method == "textDocument/didOpen" || + method == "textDocument/didChange" || + method == "textDocument/didSave") { + if (textDocument.contains("text")) { + documents[uri] = textDocument.at("text").get(); + } else if (const auto changes = params.find("contentChanges"); + changes != params.end() && changes->is_array() && + !changes->empty() && changes->back().contains("text")) { + documents[uri] = changes->back().at("text").get(); + } else if (params.contains("text")) { + documents[uri] = params.at("text").get(); + } + auto existing = documents.find(uri); + std::string result = + existing != documents.end() + ? analyzeTextJson(fileUriToPath(uri), existing->second) + : analyzeFileJson(fileUriToPath(uri)); + publishDiagnostics(uri, result); + } else if (method == "textDocument/didClose") { + // Without this the server kept every document it had ever seen, + // growing without bound over a long editing session. + documents.erase(uri); + } else if (hasId) { + // A request (has an id, so the client is waiting on a reply) for + // a method this diagnostics-only server doesn't implement, e.g. + // textDocument/completion or textDocument/hover. Previously this + // fell through with no response at all, leaving a spec-compliant + // client blocked forever on that id. Notifications (no id) are + // still silently ignored, per the LSP spec. + writeLspMessage(nlohmann::json{ + {"jsonrpc", "2.0"}, + {"id", id}, + {"error", + {{"code", -32601}, {"message", "Method not found: " + method}}}} + .dump()); + } + } + return 0; +} + +int main(int argc, char **argv) { + DebugOptions options; + try { + options = parseDebugCli(argc, argv); + if (options.help) { + printDebugUsage(std::cout); + return 0; + } + if (options.version) { + std::cout << versionJson("felidae_debug") << "\n" << std::flush; + return 0; + } + if (options.lspMode) { + return runLspServer(); + } + if (options.listLibraries) { + fs::path startDir = + options.programFile + ? Tooling::resolveEntryPath(*options.programFile).parent_path() + : fs::current_path(); + std::cout << librariesJson(Tooling::listCoreLibraries(startDir)) << "\n" + << std::flush; + return 0; + } + if (options.listBuiltins) { + std::cout << builtinsJson(allBuiltins()) << "\n" << std::flush; + return 0; + } + if (!options.programFile) { + std::cerr << "error: felidae_debug requires a .fx program file\n"; + printDebugUsage(std::cerr); + return 1; + } + if (options.programFile->extension() != FILE_EXTENSION) { + throw std::runtime_error("Felidae source files must use .fx extension"); + } + + if (options.symbolsJson) { + std::cout << symbolsFileJson(*options.programFile, options.loadImports) + << "\n" + << std::flush; + return 0; + } + if (options.operatorsJson) { + std::cout << operatorsFileJson(*options.programFile, options.loadImports) + << "\n" + << std::flush; + return 0; + } + + const bool dataOutputOnly = options.checkJson; + if (!dataOutputOnly) { + std::cout << "FELIDAE_DEBUG_READY program=" + << options.programFile->string() << "\n" + << std::flush; + } + if (options.stopOnEntry) { + waitForContinue(); + } + + AstAnalysisSession analysis; + const auto analysisStarted = std::chrono::steady_clock::now(); + Tooling::loadProgramStatements( + *options.programFile, options.loadImports, + [&](const std::shared_ptr &statement) { + analysis.consume(statement); + }); + auto astDiagnostics = analysis.finish(); + const auto analyzedFile = + fs::absolute(*options.programFile).lexically_normal().string(); + for (auto &diagnostic : astDiagnostics) + diagnostic.file = analyzedFile; + const auto analysisMicros = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - analysisStarted) + .count(); + if (!dataOutputOnly) { + std::cerr << "Felidae AST debugger analyzing " + << options.programFile->string() << "\n"; + } + + if (options.checkJson) { + std::cout << diagnosticsJson(astDiagnostics) << "\n" << std::flush; + if (hasErrorDiagnostic(astDiagnostics)) { + return 1; + } + } else { + printAstDiagnostics(astDiagnostics); + std::cout << "FELIDAE_CHECK_OK\n" << std::flush; + } + + if (!dataOutputOnly) { + std::cout << "FELIDAE_DEBUG_EXIT code=0\n" << std::flush; + } + if (options.metricsJson) { + std::cerr << "FELIDAE_DEBUG_METRICS {\"analysisMs\":" + << static_cast(analysisMicros) / 1000.0 << "}\n"; + } + return 0; + } catch (const std::exception &e) { + if (options.checkJson) { + std::cout << errorJson(e.what()) << "\n" << std::flush; + return 1; + } + std::cerr << "error: " << e.what() << "\n"; + std::cout << "FELIDAE_DEBUG_EXIT code=1\n" << std::flush; + return 1; + } +} diff --git a/src/main.cpp b/src/main.cpp index dc30aaf..1f97071 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,14 +1,18 @@ #include "Interpreter.h" #include "FelidaeRuntime.h" +#include "Symbol.h" #include "Version.h" #include #include #include +#include #include #include #include #include +#include +#include #include #include #include @@ -236,6 +240,144 @@ static void runServeEntry(Interpreter& interpreter, const CliOptions& options) { } } +// Real breakpoint/step debugging over Interpreter::setGoalHook - not a +// simulation. The hook fires once per goal from the live iterative solver +// (solveIterative, Interpreter.cpp), so a pause here sees the goal's actual +// bound Env, and stepping/breakpoints act on real execution rather than +// static analysis or a heuristic over source text. +// +// Line-based text protocol on stdin/stdout, extending the pre-existing +// FELIDAE_DEBUG_STOPPED/CONTINUED marker convention (previously only used to +// gate when static analysis began) so a driving client - the VS Code +// extension, or a person testing this by hand - can attach the same way: +// Output, when paused: +// FELIDAE_DEBUG_STOPPED reason= line= +// Commands read one per line while paused: +// continue | next (step over) | stepIn | stepOut +// break | clear (adjust breakpoints while paused) +// locals (every bound name in the paused Env) +// print (one bound name's real value) +// terminate | quit +// Output when resuming: FELIDAE_DEBUG_CONTINUED +// Output at program end: FELIDAE_DEBUG_TERMINATED +// +// Depth here is Interpreter's existing per-goal nesting depth (grouped/if/or +// bodies and method-call recursion both increase it, since both re-enter the +// same solveIterative loop) - step over/out use it as "stop once back at or +// above the depth this command was issued at," which does not distinguish a +// nested control-flow body from an actual method call. Good enough to step +// through a program goal by goal; a call-frame-accurate depth would need +// solveMethodCall to publish its own frames alongside solveIterative's. +class DebugSession { +public: + void attach(Interpreter& interpreter) { + interpreter_ = &interpreter; + stepMode_ = StepMode::Into; // stopOnEntry: pause before the first goal. + interpreter.setGoalHook([this](const Goal& goal, const Env& env, std::size_t depth) { + onGoal(goal, env, depth); + }); + } + +private: + enum class StepMode { None, Into, Over, Out }; + + void onGoal(const Goal& goal, const Env& env, std::size_t depth) { + if (terminated_) return; + const int line = goal.sourceSpan.valid() ? goal.sourceSpan.startLine : 0; + const char* reason = nullptr; + if (breakpoints_.count(line)) { + reason = "breakpoint"; + } else if (stepMode_ == StepMode::Into) { + reason = "step"; + } else if (stepMode_ == StepMode::Over && depth <= stepDepth_) { + reason = "step"; + } else if (stepMode_ == StepMode::Out && depth < stepDepth_) { + reason = "step"; + } + if (!reason) return; + stepMode_ = StepMode::None; + pauseAndWait(reason, line, depth, env); + } + + void pauseAndWait(const char* reason, int line, std::size_t depth, const Env& env) { + std::cout << "FELIDAE_DEBUG_STOPPED reason=" << reason << " line=" << line << std::endl; + std::string commandLine; + while (std::getline(std::cin, commandLine)) { + commandLine = trim(commandLine); + if (commandLine.empty()) continue; + std::istringstream parsed(commandLine); + std::string command; + parsed >> command; + if (command == "continue") { + std::cout << "FELIDAE_DEBUG_CONTINUED" << std::endl; + return; + } + if (command == "next") { + stepMode_ = StepMode::Over; + stepDepth_ = depth; + std::cout << "FELIDAE_DEBUG_CONTINUED" << std::endl; + return; + } + if (command == "stepIn") { + stepMode_ = StepMode::Into; + std::cout << "FELIDAE_DEBUG_CONTINUED" << std::endl; + return; + } + if (command == "stepOut") { + stepMode_ = StepMode::Out; + stepDepth_ = depth; + std::cout << "FELIDAE_DEBUG_CONTINUED" << std::endl; + return; + } + if (command == "break" || command == "clear") { + int requestedLine = 0; + parsed >> requestedLine; + if (command == "break") breakpoints_.insert(requestedLine); + else breakpoints_.erase(requestedLine); + std::cout << "FELIDAE_DEBUG_BREAKPOINT_" << (command == "break" ? "SET" : "CLEARED") + << " line=" << requestedLine << std::endl; + continue; + } + if (command == "locals") { + std::cout << "FELIDAE_DEBUG_LOCALS_BEGIN" << std::endl; + for (const auto& binding : env) { + if (isInternalGeneratedSymbolId(binding.first)) continue; + const std::string name = symbolNameForId(binding.first); + if (name.empty()) continue; + std::cout << name << " = " << interpreter_->valueToDisplayString(binding.second) << std::endl; + } + std::cout << "FELIDAE_DEBUG_LOCALS_END" << std::endl; + continue; + } + if (command == "print") { + std::string name; + parsed >> name; + const auto found = env.find(name); + std::cout << "FELIDAE_DEBUG_VALUE " << name << " = " + << (found != env.end() ? interpreter_->valueToDisplayString(found->second) : "") + << std::endl; + continue; + } + if (command == "terminate" || command == "quit") { + terminated_ = true; + std::cout << "FELIDAE_DEBUG_TERMINATED" << std::endl; + std::exit(0); + } + std::cout << "FELIDAE_DEBUG_ERROR unknown command '" << command << "'" << std::endl; + } + // stdin closed without an explicit terminate: end the session rather + // than spin forever with no client left to drive it. + terminated_ = true; + std::exit(0); + } + + Interpreter* interpreter_ = nullptr; + std::set breakpoints_; + StepMode stepMode_ = StepMode::None; + std::size_t stepDepth_ = 0; + bool terminated_ = false; +}; + int main(int argc, char** argv) { try { CliOptions options = parseCli(argc, argv); @@ -255,6 +397,16 @@ int main(int argc, char** argv) { using Clock = std::chrono::steady_clock; const auto loadStarted = Clock::now(); Interpreter interpreter; + DebugSession debugSession; + // Attached before loadProgramRoot below, not after: a program with + // no main() executes its bare top-level calls during loading itself + // (Interpreter::addProgram's EntryCall handling), so attaching any + // later would miss stepping through those entirely. + if (options.debug) { + std::cerr << "Felidae debug session for " << options.programFile->string() + << " - stopped on entry, waiting on stdin.\n"; + debugSession.attach(interpreter); + } fs::path entryFile = resolveProgramEntryPath(*options.programFile); if (entryFile.extension() != FILE_EXTENSION) { throw std::runtime_error("Felidae source files must use .fx extension"); @@ -313,10 +465,6 @@ int main(int argc, char** argv) { << "\"runtime\":" << interpreter.runtimeMetricsJson() << "}\n"; }; - if (options.debug) { - std::cerr << "Felidae debug mode enabled for " << entryFile.string() << "\n"; - } - if (options.repl) { runRepl(interpreter); reportMetrics(); diff --git a/src/tooling/SourceParser.h b/src/tooling/SourceParser.h new file mode 100644 index 0000000..adf56b8 --- /dev/null +++ b/src/tooling/SourceParser.h @@ -0,0 +1,77 @@ +#pragma once + +// Compatibility shim over FelidaeRuntime.h for src/debugger/main.cpp, which +// predates the interpreter rewamp that consolidated this project's file +// loading into FelidaeRuntime.h/.cpp (parseProgramFile/parseProgramText/ +// parseProgramFileStatements/loadProgramRoot/resolveProgramEntryPath/ +// listCoreLibraries - the same functions the interpreter's own main.cpp +// uses to load a program). Restoring src/tooling/SourceParser.cpp's original +// bespoke implementation would just be a second, competing copy of exactly +// that loading logic; this header only renames/re-shapes the already-shared +// implementation to the debugger's original call sites instead. +// +// The one thing the old Felidae::Tooling::LoadedSources carried that isn't +// reproduced here is unresolvedImports: FelidaeRuntime.h's addImport-based +// loading does not currently surface which imports failed to resolve as a +// distinct list the way the removed SourceParser did. loadProgramStatements +// below always returns it empty; a caller that needs it back would have to +// add that reporting to Interpreter::addImport itself. + +#include "AST.h" +#include "FelidaeRuntime.h" +#include "Interpreter.h" +#include "Operator.h" + +#include +#include +#include +#include +#include + +namespace Felidae::Tooling { + +struct LoadedSources { + std::vector files; + std::vector unresolvedImports; + std::shared_ptr operators; +}; + +inline Program parseText(std::string text) { + return parseProgramText(std::move(text)); +} + +inline std::filesystem::path resolveEntryPath(const std::filesystem::path& path) { + return resolveProgramEntryPath(path); +} + +inline std::vector listCoreLibraries(const std::filesystem::path& startDir) { + return Felidae::listCoreLibraries(startDir); +} + +inline LoadedSources loadProgramStatements( + const std::filesystem::path& entryFile, + bool loadImports, + const std::function&)>& consume) { + LoadedSources result; + if (!loadImports) { + result.operators = std::make_shared(); + parseProgramFileStatements( + entryFile, + [&](std::shared_ptr statement) { consume(statement); }, + result.operators); + result.files = {resolveProgramEntryPath(entryFile)}; + return result; + } + // Following imports means registering the whole program the same way a + // real run would, so mixfix/annotation resolution (operators-json) sees + // the same operator registry state a live interpreter would build. + Interpreter interpreter; + loadProgramRoot(entryFile, interpreter, [&](const Program& chunk) { + for (const auto& statement : chunk.statements) consume(statement); + }); + result.files = interpreter.loadedSourceFiles(); + result.operators = interpreter.operatorRegistry(); + return result; +} + +} // namespace Felidae::Tooling diff --git a/v2_examples/ancestor_relatedness_analysis.fx b/v2_examples/ancestor_relatedness_analysis.fx new file mode 100644 index 0000000..70c1863 --- /dev/null +++ b/v2_examples/ancestor_relatedness_analysis.fx @@ -0,0 +1,75 @@ +# Ancestor-hierarchy relatedness and value similarity, worked end to end. +# +# Two complementary, both-deterministic notions of "how related are these +# two facts": +# - Type relatedness (core/ancestry.fx): lca/mca walk the `extend` +# hierarchy and relatedness()/isCloseRelative()/isDistantRelative() turn +# the lowest common ancestor's combined distance into a [0, 1] degree. +# - Value similarity (core/fuzzy.fx): similarity(a, b) compares a shared +# numeric field directly, independent of type distance entirely - two +# cousins can still have near-identical weights. +# +# A four-species hierarchy gives every relationship shape: same species +# (distance 0), siblings sharing an immediate parent (Dog/Wolf under Canine, +# distance 2), first cousins sharing a grandparent through different parent +# branches (Dog/Cat: Canine vs Feline under Mammal, distance 4), and +# unrelated branches (Cat/Eagle: Mammal vs Bird, sharing only Animal, +# distance 4 as well - the same combined distance as the cousins, since both +# pairs are two steps from the shared ancestor on each side). + +import "ancestry". +import "fuzzy". + +Animal(name: "", weight_kg: 0). +Mammal extend Animal(name: "", weight_kg: 0). +Bird extend Animal(name: "", weight_kg: 0). +Canine extend Mammal(name: "", weight_kg: 0). +Feline extend Mammal(name: "", weight_kg: 0). +Dog extend Canine(name: "", weight_kg: 0). +Wolf extend Canine(name: "", weight_kg: 0). +Cat extend Feline(name: "", weight_kg: 0). +Eagle extend Bird(name: "", weight_kg: 0). + +# --- Pairwise relationship report ------------------------------------------- +# +# `threshold: 0.3` marks anything at or nearer than sibling distance (2, a +# shared immediate parent) as "close": identical-type pairs (distance 0, +# degree 1) and siblings (distance 2, degree 0.333) both clear it; cousins +# and unrelated pairs (both distance 4, degree 0.2) fall under it. +relationshipReport(left: any, right: any) => + return { + left: left, + right: right, + lca: lca(left: left, right: right).selected, + mca: mca(left: left, right: right).selected, + type_relatedness: relatedness(left: left, right: right), + close_relative: isCloseRelative(left: left, right: right, threshold: 0.3), + distant_relative: isDistantRelative(left: left, right: right, threshold: 0.3), + weight_similarity: similarity(a: left.weight_kg, b: right.weight_kg) + } + +main() => + rex := Dog(name: "Rex", weight_kg: 30) + fido := Dog(name: "Fido", weight_kg: 28) + wolfie := Wolf(name: "Wolfie", weight_kg: 40) + tom := Cat(name: "Tom", weight_kg: 5) + aquila := Eagle(name: "Aquila", weight_kg: 6) + + return { + # Same species: distance 0, degree 1 - always "close" regardless of + # weight, but weight_similarity still varies independently. + same_species: relationshipReport(left: rex, right: fido), + # Siblings sharing an immediate parent (Canine): distance 2, degree + # 0.333 - still "close" at this threshold. + siblings: relationshipReport(left: rex, right: wolfie), + # Cousins: Dog and Cat share grandparent Mammal through different + # parent branches (Canine vs Feline): distance 4, degree 0.2 - a + # 30kg vs 5kg weight is not close either, so both measures agree. + cousins: relationshipReport(left: rex, right: tom), + # Unrelated branches (Mammal vs Bird, sharing only Animal): distance + # 4, the same type-relatedness as the cousins above, but weight + # happens to be nearly identical - the two measures disagree here, + # which is exactly why they are kept as separate, independent + # degrees rather than folded into one score. + unrelated_but_similar_weight: relationshipReport(left: tom, right: aquila) + } diff --git a/v2_examples/degree_profiles.fx b/v2_examples/degree_profiles.fx index 167a1a5..a96e6f7 100644 --- a/v2_examples/degree_profiles.fx +++ b/v2_examples/degree_profiles.fx @@ -1,17 +1,37 @@ # Deterministic fuzzy primitives. `Degree` results remain values in facts and # maps; only the explicit threshold condition below produces a branch. -RatingProfile(name: "", peak: 0, fades_in: 0, fades_out: 0) -DegreeReport(subject: "", similarity: 0, membership: 0, confidence: 0, truth_degree: 0) +import "fuzzy". -critical() => return RatingProfile(name: "Critical / Strongly Disagree", peak: 0, fades_in: 0, fades_out: 30) -subpar() => return RatingProfile(name: "Subpar / Disagree", peak: 30, fades_in: 10, fades_out: 50) -acceptable() => return RatingProfile(name: "Acceptable / Neutral", peak: 50, fades_in: 30, fades_out: 70) -strong() => return RatingProfile(name: "Strong / Agree", peak: 75, fades_in: 50, fades_out: 90) -exceptional() => return RatingProfile(name: "Exceptional / Strongly Agree", peak: 100, fades_in: 75, fades_out: 100) +RatingProfile(name: "", peak: 0, fades_in: 0, fades_out: 0). +DegreeReport(subject: "", similarity: 0, membership: 0, confidence: 0, truth_degree: 0). +# Same-line `Name() => return EXPR` clause bodies do not parse when another +# clause follows them (confirmed: a minimal `a() => return 1` / `b() => +# return 2` pair fails the same way, independent of content or the fact +# vocabulary) — a pre-existing IntegerParser.cpp bug, not something to design +# examples around. Each clause body goes on its own indented line instead. +critical() => + return RatingProfile(name: "Critical / Strongly Disagree", peak: 0, fades_in: 0, fades_out: 30) + +subpar() => + return RatingProfile(name: "Subpar / Disagree", peak: 30, fades_in: 10, fades_out: 50) + +acceptable() => + return RatingProfile(name: "Acceptable / Neutral", peak: 50, fades_in: 30, fades_out: 70) + +strong() => + return RatingProfile(name: "Strong / Agree", peak: 75, fades_in: 50, fades_out: 90) + +exceptional() => + return RatingProfile(name: "Exceptional / Strongly Agree", peak: 100, fades_in: 75, fades_out: 100) + +# `75%` (a bare numeric percent suffix) is not a supported literal — it is +# not used anywhere else in the codebase and fails to parse ("Expected an +# expression") the moment it is actually exercised; 0.75 is the equivalent +# plain decimal degree. threshold(degree: number) => - if degree >= 75% then + if degree >= 0.75 then return "met" else return "not-met" @@ -19,8 +39,8 @@ threshold(degree: number) => main() => score := 68 profile := strong() - membershipDegree := membership(score, profile) - closenessDegree := similarity(score, 75) + membershipDegree := membership(score: score, profile: profile) + closenessDegree := similarity(a: score, b: 75) report := DegreeReport(subject: "quality", similarity: closenessDegree, membership: membershipDegree, confidence: 0.82, truth_degree: membershipDegree) - state := threshold(membershipDegree) + state := threshold(degree: membershipDegree) return {rating: profile, report: report, threshold: state} diff --git a/v2_examples/felidae_language_tour.fx b/v2_examples/felidae_language_tour.fx index 1b911a1..fbd07e0 100644 --- a/v2_examples/felidae_language_tour.fx +++ b/v2_examples/felidae_language_tour.fx @@ -102,7 +102,7 @@ mutationExamples() => # --- 8. Ancestry reasoning --------------------------------------------------- # commonAncestors reads the `extend` graph declared in section 1. Selecting -# one candidate as contextually best belongs to the application or SSM. +# one candidate as contextually best belongs to the calling application. ancestryExamples() => cat := Mammal(name: "cat") lizard := Reptile(name: "lizard") diff --git a/v2_examples/fuzzy_logic_basics.fx b/v2_examples/fuzzy_logic_basics.fx new file mode 100644 index 0000000..5df1b4c --- /dev/null +++ b/v2_examples/fuzzy_logic_basics.fx @@ -0,0 +1,71 @@ +# Deterministic fuzzy logic: syntax reference and worked example. +# +# `core/fuzzy.fx` adds callable fuzzy-logic primitives on top of the +# existing degree/confidence conventions (FactRelationship.degree/confidence +# in Memory.h, ReasoningProfile's conjunction=minimum / disjunction=maximum +# / negation=one_minus policy in ReasoningRuntime.cpp). Every primitive is a +# fixed formula over its inputs — clamp, min, max, linear interpolation — +# so the same inputs always produce exactly the same degree. Nothing here +# samples, learns, or depends on run order. + +import "fuzzy". + +# --- Combinators: fuzzyAnd/fuzzyOr/fuzzyNot ------------------------------ +# +# fuzzyAnd(a, b) = min(a, b) -- Zadeh conjunction +# fuzzyOr(a, b) = max(a, b) -- Zadeh disjunction +# fuzzyNot(d) = 1 - d -- standard fuzzy negation +combinators() => + warm := 0.8 + humid := 0.3 + return { + muggy: fuzzyAnd(a: warm, b: humid), + uncomfortable: fuzzyOr(a: warm, b: humid), + cool: fuzzyNot(degree: warm) + } + +# --- Membership: a triangular fuzzy set ----------------------------------- +# +# membership(score, profile) reads a {peak, fades_in, fades_out} map and +# returns the triangular degree of `score` in that set: 0 at or below +# fades_in, rising to 1 at peak, falling back to 0 at fades_out. +temperatureReadings() => + profile := {peak: 30, fades_in: 20, fades_out: 40} + return { + cold_reading: membership(score: 15, profile: profile), + rising_reading: membership(score: 25, profile: profile), + peak_reading: membership(score: 30, profile: profile), + falling_reading: membership(score: 35, profile: profile), + hot_reading: membership(score: 45, profile: profile) + } + +# --- Similarity: a general-purpose closeness degree ----------------------- +# +# similarity(a, b) is 1 when a == b and falls off with their relative +# difference, clamped to [0, 1]. +closenessChecks() => + return { + identical: similarity(a: 70, b: 70), + close: similarity(a: 70, b: 75), + far: similarity(a: 70, b: 10) + } + +# --- Composing combinators with membership -------------------------------- +# +# A rule can combine two membership degrees deterministically instead of +# branching: "comfortable" only where warm and NOT humid overlap. +comfortLevel(warm: number, humid: number) => + warmProfile := {peak: 30, fades_in: 15, fades_out: 40} + dryProfile := {peak: 0, fades_in: 0, fades_out: 60} + warmDegree := membership(score: warm, profile: warmProfile) + dryDegree := membership(score: humid, profile: dryProfile) + return fuzzyAnd(a: warmDegree, b: dryDegree) + +main() => + return { + combinators: combinators(), + temperature: temperatureReadings(), + closeness: closenessChecks(), + comfort_dry_day: comfortLevel(warm: 28, humid: 10), + comfort_muggy_day: comfortLevel(warm: 28, humid: 55) + }