Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
Export first-order logic over a translation a theorem is about, and treat a prover as an oracle
FABIOTESS01e5b55f3798
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 993c50af..d3f01c7d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,56 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Added+- **First-order export, over the translation a machine-checked adequacy theorem+ is about.** `fol --out DIR --format tptp|clif` (also `onto_fol_export` and+ batch `fol`) writes the loaded ontology as TPTP FOF or as ISO/IEC 24707+ Common Logic, and with `--goals FILE` one problem per conjecture, so an+ ontology can be handed to E, Vampire or any other first-order prover. The+ translation in `src/tptp.rs` transcribes `OwlLean/Translation.lean` from the+ sibling `owl-lean` project, whose `OwlLean.adequacy` is machine-checked with+ no `sorry`, no Mathlib and axioms `propext`, `Classical.choice`,+ `Quot.sound`. Everyone else's OWL-to-FOL exporter is validated empirically+ (FOWL, over 168 ChEBI modules) or proved on paper (Hets); LATIN's+ `OWL2toFOL.elf` has its cardinality constructors and `objectPropertyChain`+ commented out, and those are used by 37.2% and 45.9% of constrained real+ ontologies. The background axioms and the individual typing axioms the+ theorem requires are emitted, the freshness side condition is enforced at+ every call site rather than assumed, and both have machine-checked+ countermodels in `OwlLean/Refutations.lean` showing what goes wrong without+ them. **The correspondence between the Rust and the Lean is pinned by+ `tests/fol_translation_correspondence_test.rs` and is NOT itself proved**,+ which is stated in the module docs, in the JSON report and in the header of+ every emitted file. Constructs outside the fragment are named in the output+ with counts and reasons through `exports_a_weaker_axiom_set` and+ `constructs_not_exported`, the shape the description-logic layer already uses+ for `certifies_a_weaker_axiom_set`. CLIF is a second serialiser over the one+ translation, never a second translation, and is restricted to the+ first-order-equivalent fragment of Common Logic: no sequence markers, fixed+ arity, no quantification into a predicate position. See+ docs/first-order-export.md and decision 0005.+- **The CLIF export is gated against leaving the exactly semantically+ conformant subdialect.** ISO/IEC 24707 first edition A.4.2 says the+ subdialect using neither numerals nor quoted strings is exactly semantically+ conformant, so staying inside it makes CLIF entailment and Common Logic+ entailment coincide and the adequacy theorem needs no qualification at the+ CLIF end. `clif_stays_in_the_exactly_conformant_subdialect` walks every+ emitted sentence and fails on a bare decimal or a single-quoted string. The+ scope is stated exactly: no numerals and no quoted strings IN SENTENCE+ POSITIONS, with comment annotations the named exception.+- **`tools/fol_differential.py`, an ATP as a differential oracle and never as+ an authority.** It reasons with a certificate, exports one problem per+ claimed entailment from a separate unreasoned store, and asks E or Vampire.+ A conclusion the engine derives and the prover refutes is+ `CLAIMED_NOT_ENTAILED` and exits 1; a prover that gives up is+ `UNDETERMINED` and is never read as agreement. **An ATP verdict is an oracle+ opinion, exactly like pyshacl's in `tools/shacl_differential.py`**: a+ superposition refutation cannot be checked without a verified first-order+ calculus with unification, which does not exist in core Lean, so a+ disagreement is a bug in one of the two and the tool says so rather than+ adjudicating. With no prover installed it skips loudly with the install line,+ and `FOL_DIFF_REQUIRE_ATP=1` turns that skip into a failure. Run against E+ 3.2.5 over FOAF it reported 58 disagreements on first use, all of them+ defects in the new export layer, listed under Fixed below.- **Derivation certificates, checked by a proved-sound Lean checker.**`reason --certificate DIR` (also `onto_reason`'s `certificate_dir` and batch`reason --certificate`) writes `asserted.tsv` and `derivations.tsv`: every@@ -20,6 +70,63 @@ All notable changes to Open Ontologies are documented here.trace. See docs/lean-certificates.md and decision 0002.### Fixed+- **The CLIF export produced files that parse cleanly and yield NOTHING.**+ Every sentence was emitted as `(cl:comment '...' SENTENCE)`, the shape+ ISO/IEC 21838-2's BFO files use. Measured against both CLIF parsers that+ exist, that form is discarded: py-typedlogic returns an empty theory and+ Macleod has no production for it, and both do the same to BFO's own files. A+ file that is formally valid and practically empty is the assurance-laundering+ shape this project exists to attack, and it was in this project's own output.+ The default is now a standalone `(cl:comment '...')` phrase followed by a+ bare sentence, which py-typedlogic reads back at exactly the count the+ exporter reports (7, 161, 251, 107 and 705 sentences over five ontologies);+ `--clif-comments wrapped` keeps the old shape and the docs say what it costs.+- **CLIF comment strings were double-quoted, and quote style was bound to+ operator spelling so no flag combination could emit conforming CLIF.**+ ISO/IEC 24707 A.2.2.2 makes the single quote the string delimiter. The choice+ had been justified by matching the CLIF files ISO hosts for ISO/IEC 21838-2,+ and that corpus has been withdrawn by its own maintainers: BFO's release+ notes of 7 December 2025 say "Comment texts are surrounded by single, not+ double quotes". The ISO-hosted files carry 369 double-quoted `cl:comment`+ forms; BFO master carries 356 single-quoted and none double-quoted. Comment+ strings are now single-quoted in both dialects and the two settings are+ independent.+- **The CLIF text was unnamed.** All 227 COLORE texts are named, Macleod+ refuses an unnamed one with "Error in ontology: bad URI", and py-typedlogic+ otherwise reports the first comment as the theory's name. The text now+ carries the ontology's own `owl:Ontology` IRI where it declares one, written+ bare because Macleod's lexer has no double-quote token.+- **Two false claims in the first-order export docs.** They said a CLIF file in+ one dialect's spelling does not parse in the other's tools; py-typedlogic+ maps both spellings to identical results with identical sentence counts. They+ also implied Macleod reads the `colore` output; it reads neither, because it+ cannot lex an IRI in a symbol position at all. Both are corrected and the+ measurements are in docs/first-order-export.md.+- **A property characteristic overrode an explicit `owl:DatatypeProperty`+ declaration in the first-order export.** FOAF declares `foaf:msnChatID` as+ both `owl:DatatypeProperty` and `owl:InverseFunctionalProperty`, which OWL 2+ DL forbids and RDF-serialised vocabularies assert anyway. The characteristic+ won, so the property was exported as an object property throughout and every+ axiom about it used the wrong symbol. `OwlP2` is a disjoint sum, so `op:p`+ and `dp:p` are unrelated predicates and the difference is not cosmetic. The+ declaration now wins and a characteristic on a data property is dropped and+ named. Found by `tools/fol_differential.py` on its first real run.+- **The goal builder did not map `owl:Thing` and `owl:Nothing`, and did not+ consult the entity-kind classification.** A derived triple+ `X rdfs:subClassOf owl:Thing` became a subsumption under an atomic class+ symbol occurring in no axiom rather than under the translation's `top`, and a+ goal about a data property asked about `op:p` while the axioms spoke about+ `dp:p`. Fifty-two of FOAF's 181 claimed entailments came back as+ disagreements that were entirely this; the remaining six were the+ declaration-versus-characteristic defect above. Also found by the+ differential.+- **The differential exported from the store the reasoner had just materialised+ into**, so every conjecture was entailed by the theory already stating it and+ the run could not fail. A deliberately broken exporter still scored clean+ under it. The reasoner and the exporter now run against separate stores, the+ export loads the certificate's own `asserted.tsv` so the two see the same+ graph down to the blank node labels, and a triple-count mismatch aborts the+ run rather than reporting a differential that cannot fail.- **`sh:sparql` ignored `sh:prefixes` and merged every `sh:declare` in theshapes graph into one prologue.** A prefix bound to two namespaces emittedtwo `PREFIX` lines, SPARQL took the last, and which one won was decided bydiff --git a/CLAUDE.md b/CLAUDE.mdindex b44b6243..1bb6b96b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -105,6 +105,7 @@ Claude dynamically decides the next tool call based on what the previous tool re| `onto_enforce_feedback` | To accept/dismiss an enforce violation — teaches enforce to suppress repeatedly dismissed violations || `onto_dl_explain` | To explain why a class is unsatisfiable using DL tableaux reasoning — returns clash trace || `onto_dl_check` | To check if one class is subsumed by another using DL tableaux reasoning |+| `onto_fol_export` | To hand the ontology to the automated-theorem-proving ecosystem. Writes TPTP FOF (what E and Vampire read) or ISO/IEC 24707 CLIF (the standards-track interchange syntax, and what ISO/IEC 21838-2 publishes BFO in), restricted both to the first-order-equivalent fragment of Common Logic and to the subdialect ISO/IEC 24707 A.4.2 calls exactly semantically conformant, each checked by a test rather than asserted. Both are serialisers over ONE translation: the one `OwlLean.adequacy` in the sibling owl-lean project is machine-checked about, including the background axioms and the individual typing axioms that theorem requires. The correspondence between this emitter and that Lean is PINNED BY TESTS AND NOT PROVED, and the emitted file says so. Constructs outside the fragment are named with counts and reasons in `constructs_not_exported`, never dropped silently. CLIF sentences are emitted BARE with standalone `(cl:comment '...')` labels, because the two CLIF parsers that exist both return an EMPTY theory from the wrapped `(cl:comment '...' SENTENCE)` form that ISO/IEC 21838-2's own BFO files use; `clif_comments: "wrapped"` restores that form and loses the content. Pass `goals_file` to also write one problem per conjecture. A PROVER'S VERDICT ON THE OUTPUT IS AN ORACLE OPINION AND NEVER A CERTIFICATE: use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it. See docs/first-order-export.md and decision 0005 || `onto_embed` | After loading an ontology — generates text + Poincaré structural embeddings for all classes. The default local model is **multilingual** (`paraphrase-multilingual-MiniLM-L12-v2`), so labels in different natural languages embed into a shared space. Honours `[embeddings] provider = "local" \| "openai"` in `config.toml`; OpenAI-compatible gateways (Azure, Ollama, vLLM, LocalAI, …) are supported via `OPEN_ONTOLOGIES_EMBEDDINGS_*` env vars || `onto_search` | To find classes by natural language description — requires onto_embed first || `onto_similarity` | To compute embedding similarity between two specific IRIs |diff --git a/docs/decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md b/docs/decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.mdnew file mode 100644index 00000000..92a35d2d--- /dev/null+++ b/docs/decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md@@ -0,0 +1,219 @@+# 0005 · A prover is an oracle, and a translation is a theorem++- **Status**: implemented · `src/tptp.rs`, `fol --out DIR --format tptp|clif`, `onto_fol_export` ·+ correspondence pinned by `tests/fol_translation_correspondence_test.rs` (31 tests) ·+ differential in `tools/fol_differential.py`, run against E 3.2.5 · the translation mirrors+ `OwlLean/Translation.lean` in the sibling `owl-lean` project, whose `OwlLean.adequacy` is+ machine-checked with axioms `propext`, `Classical.choice`, `Quot.sound` · **the Rust-to-Lean+ correspondence is pinned by tests and is NOT proved**+- **Written**: 2026-09-14+- **Related**: decision 0002 (an inference carries a certificate), which this decision is the+ boundary of; `tools/shacl_differential.py`, whose treatment of pyshacl this copies exactly++## The problem++There is a problem on each side of this work, and they pull in opposite directions.++An OWL-to-first-order exporter is easy to write and hard to justify. FOWL+validated its mapping empirically over 168 consistent ChEBI modules. Hets proves its OWL-to-CASL+comorphism on paper, through the institution satisfaction condition. LATIN's `OWL2toFOL.elf` is+type-checked by Twelf, which is no longer maintained, and has its cardinality constructors and+`objectPropertyChain` commented out. So an exporter can emit a plausible file and nobody, including+its author, can say what the file means.++The opposite temptation arrives with the output. Once an ontology is in TPTP, a prover will answer questions+about it, and the answers look like proofs. They are not. Decision 0002 lets this engine say an+inference is *checked*, because `lean/` holds a checker whose soundness is a machine-checked+theorem and the certificate is small enough to re-derive. A superposition refutation is not like+that. Checking one needs a verified first-order calculus with unification, which does not exist in+core Lean. Treating a prover's `SZS status Theorem` as a certificate would undo the distinction+decision 0002 exists to draw, inside the same codebase, one layer up.++## Decisions++1. **The exporter emits the translation a machine-checked theorem is about.** The sibling project+ `owl-lean` proves `OwlLean.adequacy`: for an ontology `O` and an axiom `a`,+ `Entails O a ↔ FOL.Entails (background ++ indAxioms inds ++ O.map trAx) (trAx a)`, no `sorry`,+ no Mathlib, axioms `[propext, Classical.choice, Quot.sound]`. `src/tptp.rs` transcribes `tr`,+ `trAx`, `background` and `indAxioms` function for function. Nothing is normalised, simplified or+ optimised on the way out: `⊤` fillers still emit `$true` conjuncts, because the file has to+ carry the formula the theorem is about rather than one equivalent to it.+2. **The correspondence is pinned by tests and is not proved, and the output says so.**+ Nothing mechanically checks that `Translation::axiom` is `OwlLean.trAx`. What exists is+ `tests/fol_translation_correspondence_test.rs`, whose expected strings are computed BY HAND from+ `OwlLean/Translation.lean` rather than recorded from a run: a golden file captured from the+ emitter would agree with the emitter by construction and would catch nothing. The claim appears+ in the module docs, in the JSON report, and in the header of every emitted file, because a limit+ stated only in a README gets read without one.+3. **What the theorem needs is handled, not assumed.** `tr_bridge` holds only under+ `Fresh n x`, and `OwlLean.Refutations.tr_bridge_needs_freshness` is a machine-checked+ countermodel where the existential `tr` allocates captures its own subject variable. The+ exporter never chooses a counter: every entry goes through `Translation::concept_fresh`, which+ refuses unless `x < c`, and the call sites reproduce `trAx`'s own `tr c 0 2`, `tr c 1 2`,+ `tr c 0 1`. Separately, `background` alone does not force a constant to denote an object, and+ `OwlLean.Refutations.adequacy_needs_ind_axioms` refutes adequacy outright with the empty+ ontology and `⊤(a)`; `indAxioms`, i.e. `thing(a)` for every individual name, is the fix and is+ emitted. Both were real defects found while proving the theorem.+4. **What is not exported is named in the output.** `exports_a_weaker_axiom_set` and+ `constructs_not_exported` carry every construct outside the fragment with its count and the+ reason, the same shape as `certifies_a_weaker_axiom_set` on the description-logic layer. A+ construct rewritten into the fragment before translation, such as `owl:AllDisjointClasses` or+ `owl:equivalentProperty`, is listed under `reduced_to_fragment` rather than passed off as+ native. Annotations are counted separately, because an annotation carries no Direct Semantics+ content and folding 206 `rdfs:label` triples into the drop list would bury the sixteen+ constructs that do weaken the axiom set.+5. **An ATP verdict is an oracle opinion and is labelled as one everywhere it appears.**+ `tools/fol_differential.py` runs the engine's claimed entailments past E or Vampire and reports+ `AGREE`, `CLAIMED_NOT_ENTAILED`, `WEAKER_EXPORT`, `UNDETERMINED`, `ATP_ERROR` or `NOT_ASKED`. A+ disagreement is a bug in one of the two and the tool's job is to say so, not to adjudicate.+ `UNDETERMINED` is never collapsed into agreement: the translated theory is not decidable in+ general and a non-entailment often has only infinite countermodels. The word "proved" appears+ nowhere next to a prover's answer.+6. **A disagreement caused by the fragment is separated from a disagreement caused by a bug, and+ the separation is computed rather than guessed.** OWL TIME derives a class assertion from a+ data-property assertion, and GoodRelations derives a range from a data-property hierarchy;+ neither has a constructor in `OwlLean/Syntax.lean`, so the exported theory genuinely does not+ entail those conclusions and the prover is right to say so. Calling that a bug would send a+ reader hunting a defect that was a stated limitation. Every triple in the certificate is put to+ the exporter as a goal of its own, so the exporter's own judgement decides what is expressible;+ a conclusion is reachable when it is an expressible asserted triple or some derivation of it has+ every premise reachable; and a conclusion with no surviving derivation is reported as+ `WEAKER_EXPORT` with the blocking triple named. The verdict is only as good as that+ expressibility judgement, so the triple is printed rather than summarised.+7. **The differential exports from an unreasoned store, and checks that it did.** `reason`+ materialises into the default graph, so exporting from the same store puts the conclusion into+ the axioms and every conjecture becomes trivially entailed. That was this tool's first shape,+ and a deliberately broken exporter still scored a clean run under it. It now runs the reasoner+ and the exporter against separate stores, loads the certificate's own `asserted.tsv` for the+ export so the two see the same graph down to the blank node labels, and aborts if the triple+ counts differ rather than reporting a differential that cannot fail.+8. **Two serialisers, one translation.** `Form` is computed once; TPTP FOF and CLIF are folds over+ it and contain no OWL-specific logic. The correspondence test reads the CLIF back with an+ S-expression reader and requires the identical `Form`, so a drift in either writer is caught+ rather than argued about.+9. **The CLIF is restricted to the first-order-equivalent fragment, and says so in the file.**+ Common Logic is not plain first-order logic: it has sequence markers, arity-free predicates, and+ a universe in which relations are themselves individuals. ISO/IEC 24707 clause 6.5 is explicit+ that sequence markers make the logic non-compact and therefore not first-order. The adequacy+ theorem is about plain first-order logic, so the emitted text uses no sequence markers, fixed+ arity everywhere, and no quantification into a predicate position. `Form` cannot express any of+ the three; `clif_uses_only_fol_fragment` checks that the writer still does not.++## Why CLIF at all, given TPTP exists++Because they are not competing. TPTP is the execution format and CLIF is the interchange format,+and the toolchain confirms the split: Macleod translates CLIF to TPTP and to LADR and then calls+Vampire, Prover9, Paradox or Mace4 (`src/macleod/Commands.py` has exactly those four; E is not+among them). The consumer that matters here is standards-side, and it is a requirement rather than+a preference. **ISO/IEC 21838-1:2021 clause 4.3 requires that a top-level ontology be available+through an axiomatisation in a language conforming to ISO/IEC 24707**, its note naming CLIF, CGIF+and XCL as the qualifying dialects. Two qualifications travel with that and must not be dropped:+the English clause text was NOT read here, being paywalled, so the "shall be available" modality+comes from the Russian identical adoption of the same standard; and CLIF specifically is not+mandatory, since CGIF or XCL would satisfy clause 4.3 equally. CLIF is named for Basic Formal+Ontology in particular by ISO/IEC 21838-2 clause 4.4.1(a), which WAS read verbatim, and the ISO+maintenance portal ships `21838-2/common-logic/*.cl` alongside a Prover9 rendering and an OWL+approximation. BFO's own documentation states that the OWL version is an approximation to the CLIF+one and that an OWL axiom counts as valid just in case it is provable from the stronger+implementation. An ontology engine that can emit only TPTP cannot speak to that audience in its own+notation.++## CLIF was got wrong three times, and each time by assertion rather than measurement++Every correction below came from reading the standard or running a parser, and each replaced+something this project had simply assumed.++**Vertical bars.** Names were first written as `|...|`. That is Common Lisp's and KIF's convention.+A.2.2.2 sets `namequote = '"'`, and in CLIF the vertical bar is an ordinary name character, so+`|x|` lexes as a bare name containing two pipes and protects nothing. Names are now enclosed names+in double quotes, which A.2.2.4 recommends for IRIs.++**Double-quoted comment strings.** Comments were then written with double quotes, justified by+matching the CLIF files ISO hosts for ISO/IEC 21838-2. That corpus has been withdrawn by its own+maintainers: BFO's release notes of 7 December 2025 say "Comment texts are surrounded by single,+not double quotes". Counted, the ISO-hosted files carry 369 double-quoted `cl:comment` forms and+BFO master carries 356 single-quoted and none double-quoted. Worse, quote style had been bound to+operator spelling, so **no combination of flags could emit conforming CLIF**. The two are now+independent and comment strings are single-quoted in both dialects.++**Sentences wrapped in comments.** Every sentence was emitted as `(cl:comment '...' SENTENCE)`, the+shape BFO uses. Measured, both CLIF parsers that exist return an EMPTY theory from such a file:+py-typedlogic treats the form as discardable and Macleod has no production for it, and both do the+same to BFO's own files. A file that is formally valid and practically empty is the+assurance-laundering shape this project exists to attack, found inside this project's own output.+The default is now a standalone `(cl:comment '...')` phrase followed by a bare sentence, which+py-typedlogic reads back at exactly the sentence count the exporter reports; `--clif-comments+wrapped` keeps the old shape and the docs say what it costs. The text is also named now, because+all 227 COLORE texts are named and an unnamed one is refused by Macleod and misnamed by+py-typedlogic.++## Two dialects, because the ecosystem has two++`cl:text` and `cl:comment` are ISO/IEC 24707's reserved tokens and are what ISO publishes BFO in.+The COLORE repository is written with `cl-text` and `cl-comment`, and the Macleod parser+(`src/macleod/parsing/parser.py`) maps only the hyphen forms, with the colon forms present and+commented out. `--clif-dialect` therefore takes `iso` (the default) or `colore`. It is a spelling+and not a second translation: the correspondence test reads both dialects back to the identical+`Form`. It is **not** true that a file in one spelling fails in the other's tools, which this+record claimed until it was measured: py-typedlogic maps both spellings to identical results with+identical sentence counts. Macleod reads neither, because it cannot lex an IRI in a symbol+position at all.++## The subdialect claim is gated, not asserted++ISO/IEC 24707 first edition A.4.2: "The subdialect of CLIF which does not use numerals or quoted+strings is exactly semantically conformant". Staying inside it makes CLIF entailment and Common+Logic entailment coincide, so the adequacy theorem needs no qualification at the CLIF end. The+scope is stated exactly, in the header and in the docs: no decimal numerals and no quoted strings+IN SENTENCE POSITIONS, with comment annotations as the named exception, since a comment's text is a+quoted string by definition. `clif_stays_in_the_exactly_conformant_subdialect` walks every emitted+sentence and fails on either violation, and both failures have been demonstrated.++Nothing is claimed about the second edition's Annex A.3, which this project has not read, and+nothing anywhere says Common Logic requires infinite universes: abstract Common Logic requires only+non-emptiness, and the infinite-universe requirement is CLIF-specific, sits in the withdrawn first+edition, and sits awkwardly beside A.4.2 in that same edition.++## The quoting trap points opposite ways++TPTP takes single-quoted atoms for IRIs and CLIF takes double-quoted enclosed names, for the same+IRIs, for opposite reasons. In TPTP a double-quoted string is a *distinct object*, pairwise unequal+to every other; using it for IRIs would silently assert that all individuals are pairwise distinct,+which contradicts OWL's lack of a unique name assumption and would make every `owl:sameAs` export+unsound while still parsing and still proving things. In CLIF a single-quoted string is an+*interpreted name* that denotes itself, which is why A.2.2.4 recommends enclosed names for IRIs and+why using single quotes there would leave the exactly-conformant subdialect. Both traps are real+and they point opposite ways, so both are written down rather than left to a reader's intuition.++## What this does not claim++- **No ATP result is certified, in either direction.** `AGREE` means a second implementation+ reached the same conclusion. It is evidence, like pyshacl's agreement, and it is not a proof.+- **The Rust is not verified against the Lean.** Decision 0002's checker earns its verdict from a+ theorem. This layer earns its verdict from a test suite, and the difference is stated rather than+ blurred.+- **The front end is unclaimed on both sides.** `owl-lean`'s README lists OWL-file-to-abstract-syntax+ as not started: IRI resolution, the imports closure, the OWL 2 datatype map and facets, punning,+ blank node scoping. The reader in `src/tptp.rs` is that front end, and it is the part of this work+ that no theorem touches. Everything it cannot read, it names.+- **`hinds` is satisfied by construction, not weakened.** The theorem's hypothesis is+ `∀ a : S.Ind, a ∈ inds`, and the export's signature is the individual vocabulary occurring in the+ axioms and the goal, so the hypothesis holds for the signature the export defines. `owl-lean`+ lists weakening it to the occurring vocabulary as open; the exporter sits on the side of the gap+ where it is satisfied.++## Still not done++- The reader covers the common constructs and names the rest; it is not an OWL 2 conformance front+ end and does not claim to be.+- Cardinalities above 25 are dropped and named rather than expanded, because `minCard n` emits+ `n(n-1)/2` distinctness literals.+- Nothing runs the differential in CI. It needs a prover on `PATH`, skips loudly without one, and+ turns that skip into a failure under `FOL_DIFF_REQUIRE_ATP=1`; wiring a CI leg that installs E is+ not done. Nor is a CI leg that runs a CLIF parser over the export, which is what caught the+ empty-file defect.+- Nobody here has read ISO/IEC 24707:2018 or either part of ISO/IEC 21838. All three are priced at+ CHF 0, 70 pages for 24707, but downloading them needs a free ISO account, which is an owner+ action and not one to take on someone's behalf. The old ITTF free-standards site closed in 2025;+ the catalogue pages are reachable at `committee.iso.org` when `www.iso.org` returns 403. Until+ that is done, every clause cited here is scoped to the edition and the text actually read.diff --git a/docs/first-order-export.md b/docs/first-order-export.mdnew file mode 100644index 00000000..5bc54d61--- /dev/null+++ b/docs/first-order-export.md@@ -0,0 +1,405 @@+# First-order export, and what an ATP verdict is worth++The engine can hand an ontology to the automated-theorem-proving ecosystem, in TPTP FOF and in+ISO/IEC 24707 CLIF. The translation it emits is the one a machine-checked adequacy theorem is+about, so a reader of the file can cite a kernel-checked result about what it means.++This page is the how-to. The design and its limits are in+[decision 0005](decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md).++**Read this first.** A prover's answer about an exported file is an ORACLE OPINION, not a+certificate. Decision 0002 lets this engine say an OWL-RL inference is *checked*, because `lean/`+holds a checker whose soundness is a theorem. A superposition refutation cannot be checked that+way: it needs a verified first-order calculus with unification, which does not exist in core Lean.+When E says `SZS status Theorem`, that carries exactly the weight of pyshacl agreeing with the+SHACL validator, and nothing here calls it a proof.++## Export++```bash+# TPTP FOF, which is what E, Vampire and every other first-order prover read.+printf 'load ontology.ttl\nfol --out /tmp/fol --format tptp\n' \+ | open-ontologies --no-connect --data-dir /tmp/store batch -++# ISO/IEC 24707 CLIF. `iso` (default) writes cl:text; `colore` writes cl-text.+printf 'load ontology.ttl\nfol --out /tmp/fol --format clif --clif-dialect iso\n' \+ | open-ontologies --no-connect --data-dir /tmp/store batch -+```++Over MCP, `onto_fol_export` takes `out_dir`, `format`, `clif_dialect`, `goals_file` and+`goals_skip_columns`.++`ontology.p` (or `ontology.clif`) lands in the directory. With `--goals FILE`, where FILE is a TSV+whose first three columns are a triple, one problem per goal lands under `goals/` with a+`goals.json` manifest. `derivations.tsv` from `reason --certificate` is the intended input; it puts+the rule in column one, so pass `--goals-skip-columns 1`.++## What comes out++```+fof(background_1, axiom, ! [X0] : (~ (thing(X0) & lit(X0)))).+fof(background_2, axiom, ? [X0] : thing(X0)).+fof(ind_typing_1, axiom, thing('i:http://example.org/a')).+fof(owl_1_subClassOf, axiom, ! [X0] : (thing(X0) => ('c:http://example.org/A'(X0) =>+ ? [X2] : (thing(X2) & ('op:http://example.org/r'(X0,X2) & 'c:http://example.org/B'(X2)))))).+```++`thing` and `lit` are the soft-typing predicates. The Direct Semantics requires the object domain+and the data domain to be disjoint, and an unsorted first-order target has one domain, so object+positions are relativised by `thing` and data positions by `lit`. Omit this and the translation is+unsound for every data-property axiom.++Symbols carry a kind prefix: `c:` for a class, `d:` for a datatype, `op:` for an object property,+`dp:` for a data property, `i:` for an individual. That is not decoration. `OwlP1` and `OwlP2` are+disjoint sums in the Lean, so an IRI used as both a class and an object property is two unrelated+symbols, and a rendering that collapsed them would emit a different theory. Every prefix contains a+colon, which no unquoted TPTP lower-word may, so a prefixed symbol can never collide with the bare+`thing` and `lit`.++The two `background` axioms and the `ind_typing_*` axioms are not optional. See below.++## Ask a prover something++```bash+# Reason with a certificate, then export one problem per derived triple.+printf 'load ontology.ttl\nreason --profile owl-rl-ext --certificate /tmp/cert\n' \+ | open-ontologies --no-connect --data-dir /tmp/a batch -+printf 'load ontology.ttl\nfol --out /tmp/fol --format tptp --goals /tmp/cert/derivations.tsv --goals-skip-columns 1\n' \+ | open-ontologies --no-connect --data-dir /tmp/b batch -++eprover --auto --cpu-limit=10 /tmp/fol/goals/goal_00000.p+```++Note the two separate data directories. `reason` materialises its inferences into the default+graph, so exporting from the same store would put the conclusion into the axioms and make every+conjecture trivially entailed. `tools/fol_differential.py` does this correctly and checks that it+did; see below.++## The differential oracle++```bash+cargo build --release+python3 tools/fol_differential.py ontology.ttl --profile owl-rl-ext --timeout 10 --json out.json+```++It reasons with a certificate, exports one problem per claimed entailment from a separate+unreasoned store, and runs an ATP on each.++| verdict | means |+|---|---|+| `CLAIMED_NOT_ENTAILED` | the engine derived it, every premise of every derivation it found is expressible in the fragment, and the ATP still found a model of the axioms with the conclusion false. One of the two is wrong. Exits 1 |+| `ATP_ERROR` | the prover could not read the file. A defect in the exporter until shown otherwise. Exits 1 |+| `WEAKER_EXPORT` | the ATP is right and neither side is wrong: the engine's derivation rests on a triple the fragment cannot express, so the exported theory really does not entail the conclusion. The blocking triple is named. Does not fail the run |+| `UNDETERMINED` | the prover ran out of time or gave up. Common and honest, and NOT agreement |+| `NOT_ASKED` | no axiom form in `OwlLean/Syntax.lean` corresponds to the derived triple, with the reason |+| `AGREE` | the ATP also finds the conclusion entailed |++The `CLAIMED_NOT_ENTAILED` / `WEAKER_EXPORT` split is computed exactly, not guessed. Every triple+in the certificate is put to the exporter as a goal of its own, so the exporter's own+`triple_as_axiom` decides which are expressible. A conclusion is reachable in the exported theory+when it is an asserted triple the fragment can express, or when some derivation of it has every+premise reachable; the tool walks that relation with memoisation and reports the blocking triple+when no derivation survives. **Read the named triple.** The verdict is only as good as the+expressibility judgement behind it, so if that judgement ever refused a triple the export does in+fact carry, a real bug would be filed as `WEAKER_EXPORT` instead of as `CLAIMED_NOT_ENTAILED`. The+triple is printed rather than summarised for that reason.++E or Vampire, whichever is on `PATH`. Prover9 is deliberately not probed: it reads LADR, not TPTP.+With no prover installed the run skips loudly with the install line and exits 0; set+`FOL_DIFF_REQUIRE_ATP=1` to make that a failure, as `OO_REQUIRE_FIXTURES=1` does in the Rust suite.++`UNDETERMINED` is the normal outcome for a non-entailment. The translated theory is not decidable+in general, and a conclusion that does not follow often has only infinite countermodels, so a+prover that cannot refute it has told you nothing either way. The tool never reads that as+agreement.++## What is proved, and where the proof stops++`OwlLean.adequacy`, in the sibling `owl-lean` project:++> for an ontology `O`, an axiom `a`, and `inds` enumerating the individual vocabulary,+> `Entails O a ↔ FOL.Entails (background ++ indAxioms inds ++ O.map trAx) (trAx a)`++No `sorry`, no Mathlib, axioms `propext`, `Classical.choice` and `Quot.sound`, reprinted by+`lake env lean Audit.lean`. It covers every constructor of the fragment, cardinality restrictions+and `propertyChainAxiom` included, which is where LATIN's `OWL2toFOL.elf` stops: its cardinality+cases and `objectPropertyChain` are commented out, and 45.9% of constrained real ontologies use+property chains while 37.2% use qualified cardinality.++**The proof stops at the Lean.** `src/tptp.rs` is a transcription of `OwlLean/Translation.lean`+into Rust, and nothing mechanically checks that the transcription is faithful.+`tests/fol_translation_correspondence_test.rs` pins it: worked cases whose expected strings were+computed by hand from the Lean, unrolling `tr`, `trAx`, `mkEx`, `mkAll`, `distinctPairs`,+`somePairEq`, `Form.conj` and the counter arithmetic. A golden file captured from the emitter would+agree with the emitter by construction and would catch nothing, which is why the strings are+hand-derived. **The correspondence is pinned by tests and is not itself proved**, and that sentence+is in the module docs, in the JSON report and in the header of every emitted file.++## The two conditions the theorem carries++Both were real defects found while proving it, and both have machine-checked countermodels in+`OwlLean/Refutations.lean`.++**Freshness.** `tr` allocates bound variables from a counter and `tr_bridge` holds only under+`Fresh n x`, that is `x < n`. `tr_bridge_needs_freshness` exhibits an interpretation where the+translation of `∃r.⊤` at subject 0 with the counter also at 0 captures its own subject, so the+formula stops saying "`a` has an `r`-successor" and starts saying "something is `r`-related to+itself". The exporter never picks a counter: every entry goes through+`Translation::concept_fresh`, which refuses unless the subject is strictly below the counter, and+the call sites reproduce `trAx`'s own `tr c 0 2`, `tr c 1 2`, `tr c 0 1`. Break one and the export+fails with a message naming the countermodel, rather than writing a captured file.++**Individual typing axioms.** Nothing in `background` forces a constant to denote an object, so an+arbitrary first-order model may interpret an individual name outside `thing`.+`adequacy_needs_ind_axioms` refutes the left-to-right direction of adequacy outright, with the+empty ontology and the axiom `⊤(a)`: the countermodel `Mbad` sends the name to a literal. The fix+is `indAxioms`, `thing(a)` for every individual name, and the exporter emits one per individual in+the signature. The theorem's hypothesis is `∀ a : S.Ind, a ∈ inds`; the export's signature is the+individual vocabulary occurring in the axioms and the goal, so the hypothesis holds for the+signature the export defines.++## What is dropped, and where it is said++In the output, not in a comment. The report carries `exports_a_weaker_axiom_set` and+`constructs_not_exported`, the same shape the description-logic layer uses for+`certifies_a_weaker_axiom_set`:++```json+{+ "exports_a_weaker_axiom_set": true,+ "constructs_not_exported": [+ {"construct": "restriction on an inverse property expression", "occurrences": 6,+ "why": "Concept.some_ / all_ / minCard / maxCard take a named property (S.OProp), not an OPE"}+ ],+ "reduced_to_fragment": [+ {"construct": "owl:AllDisjointClasses", "occurrences": 2,+ "how": "expanded pairwise into Axiom.disjointWith"}+ ],+ "annotations_ignored": {"count": 206, "why": "an annotation carries no Direct Semantics content"}+}+```++Outside the fragment: `owl:hasKey`, datatype facets (`owl:withRestrictions`, `owl:onDatatype`),+`owl:datatypeComplementOf`, `owl:NegativePropertyAssertion`, data cardinality restrictions,+data-property assertions (`Axiom` has `oPropAssert` and no `dPropAssert`), property characteristics+on a data property, restrictions and `owl:inverseOf` over an anonymous property expression,+`rdfs:subPropertyOf` outside the object-property case, datatype expressions, and any cardinality+above 25, which is capped because `minCard n` emits `n(n-1)/2` distinctness literals.++Rewritten into the fragment before translation, exactly and at the OWL level:+`owl:AllDisjointClasses`, `owl:AllDifferent`, `owl:disjointUnionOf`, `owl:equivalentProperty` (two+`subOProp` axioms, which is what `EquivalentObjectProperties` means under the Direct Semantics),+and exact cardinality (as `min` and `max`).++Annotations are counted separately from the drops, because ignoring one does not weaken the axiom+set and folding 206 `rdfs:label` triples into the list would bury the constructs that do.++## CLIF, and its two dialects++Common Logic is **not** plain first-order logic. It has sequence markers, arity-free predicates,+and a universe in which relations are themselves individuals; ISO/IEC 24707 clause 6.5 states that+sequence markers make the logic non-compact and therefore not first-order. The adequacy theorem is+about plain first-order logic, so the emitted text is restricted to the fragment where the two+coincide: no sequence markers, fixed arity everywhere, no quantification into a predicate position.+The restriction is in the file header and is checked by `clif_uses_only_fol_fragment`.++`(and)` with no arguments is truth and `(or)` with no arguments is falsity (A.2.3.7). CLIF defines+no truth constants.++### The quoting trap points opposite ways in the two syntaxes++The TPTP writer uses **single**-quoted atoms for IRIs and the CLIF writer uses **double**-quoted+enclosed names for the same IRIs. That is deliberate, and it is the reverse of what most people+assume.++In TPTP a single-quoted atom is an ordinary constant, and a **double**-quoted string is a *distinct+object*, pairwise unequal to every other distinct object by fiat. Had the TPTP writer used double+quotes for IRIs it would have silently asserted that all individuals are pairwise distinct. OWL has+no unique name assumption, so every `owl:sameAs` export would become unsound, and the file would+still parse and still prove things.++In CLIF the polarity flips. A **single**-quoted string is an *interpreted name* that denotes+itself; a **double**-quoted enclosed name is an ordinary interpretable name, which is why A.2.2.4+recommends the enclosed-name syntax for writing IRIs. The vertical bar is an ordinary name+character in CLIF and is Common Lisp's convention, not CLIF's.++### The exactly semantically conformant subdialect++ISO/IEC 24707 first edition Annex A.4.2, verbatim: "The subdialect of CLIF which does not use+numerals or quoted strings is exactly semantically conformant". A numeral and a quoted string are+interpreted names, and a text containing them constrains its own interpretations in a way abstract+Common Logic does not. Stay out of them and CLIF entailment and Common Logic entailment coincide,+so the adequacy theorem's biconditional needs no qualification at the CLIF end.++**The scope of that claim, exactly: no decimal numerals and no quoted strings IN SENTENCE+POSITIONS.** Comment annotations are the named exception, because a comment's text is a quoted+string by definition, so a strict reading of "does not use quoted strings" would exclude any file+carrying a comment at all. The CLIF files ISO hosts for ISO/IEC 21838-2 are in the same position,+using single quotes only inside comment headers.++The property is checked rather than asserted:+`clif_stays_in_the_exactly_conformant_subdialect` walks every emitted sentence, skips the comment+annotations, and fails on a bare decimal or a single-quoted string.++Nothing here is claimed about the second edition's Annex A.3, which this project has not read. In+particular this page does not say that Common Logic requires infinite universes; abstract Common+Logic requires only non-emptiness, and the infinite-universe requirement is CLIF-specific, appears+in the withdrawn first edition, and sits awkwardly beside A.4.2 in that same edition.++### The two dialects, and what actually reads them++| dialect | spelling |+|---|---|+| `iso` (default) | `cl:text`, `cl:comment` |+| `colore` | `cl-text`, `cl-comment` |++Comment strings are **single**-quoted in both. Quote style is not a dialect matter: A.2.2.2 makes+the single quote the string delimiter, and BFO's release notes of 7 December 2025 retract the+double-quoted form, saying "Comment texts are surrounded by single, not double quotes". This+exporter emitted double quotes until that was measured. The ISO-hosted 21838-2 files carry 369+double-quoted `cl:comment` forms across 15 files; BFO master carries 356 single-quoted and none+double-quoted across 13. Matching the corpus was the wrong test, because the corpus had been+withdrawn by its own maintainers. Binding quote style to operator spelling, as this exporter did at+first, meant **no combination of flags could emit conforming CLIF**.++It is **not** true that a file in one spelling fails in the other's tools. Measured:+py-typedlogic maps both spellings to identical results with identical sentence counts. What is true+is narrower and is set out below.++### Why CLIF at all, given TPTP exists++They are not competing. Macleod translates CLIF to TPTP and to LADR and then calls Vampire,+Prover9, Paradox or Mace4, so TPTP is the execution format and CLIF is the interchange format.++More than a preference: **ISO/IEC 21838-1:2021 clause 4.3 requires that a top-level ontology be+available through an axiomatisation in a language conforming to ISO/IEC 24707**, and its note names+CLIF, CGIF and XCL as the qualifying dialects. Two qualifications travel with that sentence and+must not be dropped. First, the English clause text was **not** read here: it is paywalled, and the+"shall be available" modality comes from the Russian identical adoption of the same standard.+Second, CLIF specifically is not mandatory, because CGIF or XCL would satisfy clause 4.3 equally;+CLIF is named for Basic Formal Ontology in particular by ISO/IEC 21838-2 clause 4.4.1(a), which+**was** read verbatim. BFO's own documentation adds that the OWL version is an approximation to the+CLIF one.++### What the two existing CLIF parsers actually do with our output++Measured on this machine with py-typedlogic's `ClifParser` and the Macleod toolchain, over five+exports.++| | py-typedlogic | Macleod |+|---|---|---|+| default shape (named text, standalone comments, bare sentences) | accepts, recovers every sentence | accepts the shape; rejects our symbols |+| `--clif-comments wrapped` | accepts and recovers **zero** sentences | no production for a commented sentence |++Sentence counts recovered from the default shape, against the exporter's own report of+`background + individual typing + axioms`:++| ontology | exporter | py-typedlogic |+|---|---:|---:|+| the smoke ontology | 2+1+4 = 7 | 7 |+| `pizza.ttl` | 2+5+698 = 705 | 705 |+| `foaf.ttl` | 2+1+158 = 161 | 161 |+| `gufo.ttl` | 2+2+247 = 251 | 251 |+| `mushroom-ontology.ttl` | 2+0+105 = 107 | 107 |++**Why the default is not the BFO shape.** py-typedlogic treats a `(cl:comment ...)` form as+discardable, so a file whose sentences all sit inside one parses cleanly and yields zero sentences.+It does the same to BFO's own files. Macleod has no commented-sentence production at all. A file+that is formally valid and practically empty is the assurance-laundering shape this project exists+to attack, so it is not the default; `--clif-comments wrapped` remains available and the row above+says what it costs.++**Why the text is named.** All 227 COLORE texts are named. Macleod refuses an unnamed text with+"Error in ontology: bad URI", and py-typedlogic otherwise reports the first comment as the theory's+name. The name is the ontology's own `owl:Ontology` IRI when it declares one. It is written bare+rather than double-quoted because Macleod's lexer has no double-quote token.++**Macleod cannot consume an IRI-named ontology, and that is not fixable from this side.** Its lexer+rejects a double-quoted enclosed name outright, and it also rejects most bare IRI-shaped symbols:+measured, `cA:x` and `cA/x` are accepted while `c:http://e/A` and `http://e/A` are not, which is a+PLY token-precedence accident rather than a documented rule. It further rejects the zero-ary+`(and)` that A.2.3.7 explicitly licenses, and rejects a backtick, a slash, a double quote or a+percent sign inside a comment string. COLORE ontologies use short bare identifiers, which is the+world Macleod is built for. The kind prefixes `c:` / `op:` are load-bearing here, because `OwlP1`+and `OwlP2` are disjoint sums, so this exporter will not mangle IRIs into opaque identifiers to+satisfy a lexer.++### An external parser rejects ISO's own normative corpus++Both parsers independently reject the **same 8 of the 227** Common Logic files ISO hosts for+ISO/IEC 21838-4, while accepting every one of our exports. An independent bracket-balance check,+counting only brackets outside quoted strings and enclosed names, finds that **4 of the 8 are+literally unbalanced**:++| file | bracket imbalance |+|---|---|+| `simple_curve_segment_theorems.clif` | +3 unclosed |+| `region_mt.clif` | +1 unclosed |+| `psl_actors.clif` | -2, closes past the top level |+| `requires.clif` | -1, closes past the top level |+| `atomic_act_mereology.clif`, `multig_complex.clif`, `possibly_consumable.clif`, `reusable.clif` | balanced; rejected for other reasons |++py-typedlogic rejects 8 of 227; Macleod rejects 18 of 227, a superset of those 8. This is the+strongest available argument that a fragment gate and an external parser check are worth having: a+normative corpus published by a standards body does not survive contact with either of the two+parsers that read its language.++## Known limitations++Stated rather than discovered later.++- **The reader is a front end and no theorem touches it.** `owl-lean` lists OWL-file-to-abstract-syntax+ as not started: IRI resolution, the imports closure, the OWL 2 datatype map and facets, punning,+ blank node scoping. `src/tptp.rs`'s reader is that front end. Everything it cannot read it names,+ and that is the whole of its guarantee.+- **Entity kinds are inferred when undeclared.** A property with no `owl:ObjectProperty` or+ `owl:DatatypeProperty` declaration is classified by whether it ever takes a literal object, and+ every such inference is listed under `entity_kinds_inferred`. An explicit `owl:DatatypeProperty`+ declaration beats a property characteristic: FOAF declares `foaf:msnChatID` as both a datatype+ property and an inverse-functional property, which OWL 2 DL forbids.+- **Blank node labels are not stable across loads.** A goal naming an anonymous class expression+ must come from the same graph the export was built from, which is why the differential loads the+ certificate's own `asserted.tsv` rather than the source file twice. Otherwise the goal is refused+ with that reason.+- **Nothing runs the differential in CI.** It needs a prover on `PATH` and skips loudly without+ one. A CI leg that installs E is not wired.+- **Nobody here has read ISO/IEC 24707:2018 or either part of ISO/IEC 21838.** All three are priced+ at CHF 0, 70 pages for 24707, but downloading them needs a free ISO account, which is an owner+ action. The old ITTF free-standards site closed in 2025; catalogue pages are reachable at+ `committee.iso.org` when `www.iso.org` returns 403. Every clause cited on this page is scoped to+ the edition and the text actually read, and the second edition's Annex A.3 has not been read at+ all.+- **Only E has actually been run.** Every number on this page comes from E 3.2.5. The Vampire+ branch of the prover detection has never executed, because Vampire is not installed here; its+ argument vector and its SZS parsing are written from the documented interface and are untested.+ Treat `--atp vampire` as unverified until someone runs it.+- **`AGREE` is evidence, not proof.** It means a second implementation reached the same conclusion.++## What it caught++Run against FOAF on the day it was written, the differential reported 58 `CLAIMED_NOT_ENTAILED`+out of 181 claimed entailments. All 58 were defects in this layer, found in three classes: the+first two accounted for 52 and the third for the remaining 6.++1. The goal builder did not map `owl:Thing` and `owl:Nothing` to the translation's `top` and `bot`,+ so `X rdfs:subClassOf owl:Thing` asked about an atomic class symbol occurring in no axiom.+2. The goal builder did not consult the entity-kind classification, so a goal about a data property+ asked about `op:p` while the axioms spoke about `dp:p`. `OwlP2` is a disjoint sum, so those are+ unrelated predicates.+3. **In the exporter itself, not only in the goals**: a property characteristic was allowed to+ override an explicit `owl:DatatypeProperty` declaration, so `foaf:msnChatID` was exported as an+ object property throughout.++After the fixes, 181 of 181 agree.++It also forced the `WEAKER_EXPORT` verdict into existence. OWL TIME and GoodRelations both produced+disagreements that were neither side's fault: `rdfs2` derives `time:unitDay a+time:GeneralDurationDescription` from the data-property assertion `time:unitDay time:days "1"`, and+`scm-rng2` derives `gr:hasMinValueFloat rdfs:range rdfs:Literal` from+`gr:hasMinValueFloat rdfs:subPropertyOf gr:hasMinValue` between two data properties. The fragment+has no `dPropAssert` and no data-property hierarchy, so the exported theory genuinely does not+entail either conclusion. Reporting those as `CLAIMED_NOT_ENTAILED` would have sent someone hunting+a bug that was a stated limitation all along. The tool's own first shape had a worse defect: it exported from+the store the reasoner had just materialised into, so the conclusion was already among the axioms+and a deliberately broken exporter still scored a clean run. That was found by running the+stop-the-line gate on deliberately broken input, which is the only reason it was found at all.diff --git a/src/batch.rs b/src/batch.rsindex a5cede8f..afee4117 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -98,6 +98,7 @@ impl BatchRunner {"validate" => self.exec_validate(&cmd.args),"lint" => self.exec_lint(&cmd.args),"reason" => self.exec_reason(&cmd.args),+ "fol" => self.exec_fol(&cmd.args),"shacl" => self.exec_shacl(&cmd.args),// The CLI subcommand is spelled with a hyphen and this arm accepted// only the underscore, so every documented invocation was rejected@@ -274,6 +275,36 @@ impl BatchRunner {serde_json::from_str(&result).unwrap_or(json!({"raw": result}))}+ /// First-order export. The store is in-memory per process, so this is the+ /// only way to load and export in one run, exactly as for `reason+ /// --certificate`.+ fn exec_fol(&self, args: &[String]) -> Value {+ let Some(out) = Self::flag_value(args, "--out") else {+ return json!({"error": "fol requires --out DIR"});+ };+ let format = Self::flag_value(args, "--format").unwrap_or("tptp".to_string());+ let dialect = Self::flag_value(args, "--clif-dialect");+ let comments = Self::flag_value(args, "--clif-comments");+ let syntax =+ match crate::tptp::Syntax::parse(&format, dialect.as_deref(), comments.as_deref()) {+ Ok(s) => s,+ Err(e) => return json!({"error": e.to_string()}),+ };+ let goals = Self::flag_value(args, "--goals");+ let skip: usize = Self::flag_value(args, "--goals-skip-columns")+ .and_then(|v| v.parse().ok())+ .unwrap_or(0);+ let result = crate::tptp::export(+ &self.graph,+ std::path::Path::new(&out),+ syntax,+ goals.as_deref().map(std::path::Path::new),+ skip,+ )+ .unwrap_or_else(|e| json!({"error": e.to_string()}).to_string());+ serde_json::from_str(&result).unwrap_or(json!({"raw": result}))+ }+fn exec_shacl(&self, args: &[String]) -> Value {use crate::shacl::ShaclValidator;let shapes_path = match args.first() {diff --git a/src/inputs.rs b/src/inputs.rsindex d0f12725..390a5540 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -284,6 +284,41 @@ pub struct OntoReasonInput {pub rules_file: Option<String>,}+#[derive(Deserialize, JsonSchema)]+pub struct OntoFolExportInput {+ /// Directory to write the export to. `ontology.p` (TPTP) or+ /// `ontology.clif` lands here, plus one problem per goal under `goals/`.+ pub out_dir: String,+ /// `tptp` (FOF, what E and Vampire read) or `clif` (ISO/IEC 24707 Common+ /// Logic Interchange Format, restricted to the first-order-equivalent+ /// fragment). Default `tptp`. Both are renderings of ONE translation.+ pub format: Option<String>,+ /// A TSV of triples to ask as conjectures, one problem file per line. The+ /// `derivations.tsv` written by `onto_reason` with `certificate_dir` is+ /// the intended input; set `goals_skip_columns` to 1 for it, because its+ /// first column is the rule name.+ pub goals_file: Option<String>,+ /// Number of leading tab-separated columns to skip on each goals line+ /// before the subject. Default 0.+ pub goals_skip_columns: Option<usize>,+ /// Which CLIF spelling to emit, when `format` is `clif`. `iso` (default)+ /// writes `cl:text` / `cl:comment`, ISO/IEC 24707's own reserved tokens+ /// and what ISO publishes the BFO axiomatisation in with ISO/IEC 21838-2.+ /// `colore` writes `cl-text` / `cl-comment`, which is what the COLORE+ /// repository uses and what the Macleod toolchain's shipped lexer accepts;+ /// Macleod cannot read the ISO spelling. Ignored for `tptp`.+ pub clif_dialect: Option<String>,+ /// Where a formula's label goes, when `format` is `clif`. `standalone`+ /// (default) writes `(cl:comment '...')` as its own phrase and the+ /// sentence bare; `wrapped` writes `(cl:comment '...' SENTENCE)`, the+ /// shape ISO/IEC 21838-2's BFO files use. Wrapped is correct CLIF and,+ /// measured, unreadable: py-typedlogic discards the form and returns an+ /// EMPTY theory, and Macleod has no production for it, so both parsers+ /// lose the entire content of such a file, BFO's own included. Ignored+ /// for `tptp`.+ pub clif_comments: Option<String>,+}+#[derive(Deserialize, JsonSchema)]pub struct OntoDlExplainInput {/// IRI of the class to explain unsatisfiability fordiff --git a/src/lib.rs b/src/lib.rsindex a65dec7a..249d40f3 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -84,6 +84,9 @@ pub mod state;pub mod structembed;pub mod tableaux;pub mod toolfilter;+/// First-order export (TPTP FOF and ISO/IEC 24707 CLIF) over the translation+/// owl-lean's machine-checked adequacy theorem is about.+pub mod tptp;#[cfg(feature = "turbovec")]pub mod turbo_index;#[cfg(feature = "embeddings")]diff --git a/src/main.rs b/src/main.rsindex 25f5932c..d53049f2 100644--- a/src/main.rs+++ b/src/main.rs@@ -443,6 +443,41 @@ enum Commands {#[arg(long)]rules: Option<String>,},+ /// Export the loaded ontology as first-order logic, for an ATP+ ///+ /// The translation is the one owl-lean's machine-checked adequacy theorem+ /// (`OwlLean.adequacy`) is about. The correspondence between this emitter+ /// and that Lean is PINNED BY TESTS AND NOT ITSELF PROVED, and a prover's+ /// verdict on the output is an oracle opinion, never a certificate.+ Fol {+ /// Output directory. `ontology.p` (or `.clif`) lands here, plus one+ /// problem per goal under `goals/` when --goals is given.+ #[arg(long)]+ out: String,+ /// `tptp` (FOF, what provers read) or `clif` (ISO/IEC 24707 Common+ /// Logic, restricted to the first-order-equivalent fragment).+ #[arg(long, default_value = "tptp")]+ format: String,+ /// With --format clif: `iso` (default, `cl:text`, what ISO/IEC 21838-2+ /// publishes BFO in) or `colore` (`cl-text`, what COLORE and the+ /// Macleod toolchain read; Macleod cannot read the ISO spelling).+ #[arg(long, default_value = "iso")]+ clif_dialect: String,+ /// With --format clif: `standalone` (default) puts each label in its+ /// own `(cl:comment '...')` phrase and the sentence bare, or `wrapped`+ /// for `(cl:comment '...' SENTENCE)`, the shape BFO uses. Wrapped is+ /// correct CLIF that both existing CLIF parsers read as EMPTY.+ #[arg(long, default_value = "standalone")]+ clif_comments: String,+ /// A TSV of triples to ask as conjectures, one problem per line.+ /// `derivations.tsv` from `reason --certificate` is the intended+ /// input; pass --goals-skip-columns 1 for it, because its first+ /// column is the rule name.+ #[arg(long)]+ goals: Option<String>,+ #[arg(long, default_value_t = 0)]+ goals_skip_columns: usize,+ },/// Full pipeline: ingest → SHACL → reasonExtend {data_path: String,@@ -645,6 +680,25 @@ impl Commands {}cmd("reason", a)}+ Commands::Fol { out, format, clif_dialect, clif_comments, goals, goals_skip_columns } => {+ let mut a = vec![+ "--out".into(),+ absolutize(out),+ "--format".into(),+ format.clone(),+ "--clif-dialect".into(),+ clif_dialect.clone(),+ "--clif-comments".into(),+ clif_comments.clone(),+ ];+ if let Some(g) = goals {+ a.push("--goals".into());+ a.push(absolutize(g));+ a.push("--goals-skip-columns".into());+ a.push(goals_skip_columns.to_string());+ }+ cmd("fol", a)+ }Commands::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),Commands::Status => cmd("status", vec![]),Commands::Pull { url, sparql, query } => {@@ -2357,6 +2411,25 @@ async fn async_main() -> anyhow::Result<()> {};output_result_checked(&result, cli.pretty);}+ Commands::Fol { out, format, clif_dialect, clif_comments, goals, goals_skip_columns } => {+ let (_db, graph) = setup(&cli.data_dir)?;+ let result = match open_ontologies::tptp::Syntax::parse(+ &format,+ Some(&clif_dialect),+ Some(&clif_comments),+ ) {+ Ok(syntax) => open_ontologies::tptp::export(+ &graph,+ std::path::Path::new(&out),+ syntax,+ goals.as_deref().map(std::path::Path::new),+ goals_skip_columns,+ )+ .unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string()),+ Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),+ };+ output_result_checked(&result, cli.pretty);+ }Commands::Extend {data_path,format: _format,@@ -2871,6 +2944,7 @@ mod proxy_serialization_tests {Commands::Query { query: "SELECT ?s WHERE { ?s ?p ?o }".into() },Commands::Lint { input: "x.ttl".into() },Commands::Reason { profile: "rdfs".into(), certificate: None, rules: None },+ Commands::Fol { out: "/tmp/fol".into(), format: "tptp".into(), clif_dialect: "iso".into(), clif_comments: "standalone".into(), goals: None, goals_skip_columns: 0 },Commands::Shacl { shapes: "s.ttl".into() },Commands::Status,Commands::Pull { url: "http://example.org".into(), sparql: false, query: None },diff --git a/src/server.rs b/src/server.rsindex 9dff0247..8a7d22f7 100644--- a/src/server.rs+++ b/src/server.rs@@ -1922,6 +1922,26 @@ impl OpenOntologiesServer {.unwrap_or_else(Self::err_json)}+ #[tool(name = "onto_fol_export", description = "Export the loaded ontology as first-order logic, so it can be handed to the automated-theorem-proving ecosystem. Two syntaxes over ONE translation: `tptp` (FOF, what E, Vampire and every other first-order prover read) and `clif` (ISO/IEC 24707 Common Logic Interchange Format, restricted to the first-order-equivalent fragment: no sequence markers, fixed arity, no quantification into a predicate position). The translation is the one a MACHINE-CHECKED ADEQUACY THEOREM is about: `OwlLean.adequacy` in the sibling owl-lean project, axioms propext + Classical.choice + Quot.sound, no sorry, no Mathlib. That theorem is why the emitted file means what it says. THE CORRESPONDENCE BETWEEN THIS EMITTER AND THAT LEAN IS PINNED BY TESTS AND IS NOT ITSELF PROVED. The output includes the background axioms (the two domains are disjoint, the object domain is non-empty) and the individual typing axioms `thing(a)`, whose ABSENCE REFUTES ADEQUACY OUTRIGHT (OwlLean.Refutations.adequacy_needs_ind_axioms). Constructs outside the fragment are NOT dropped silently: `exports_a_weaker_axiom_set` and `constructs_not_exported` name every one with its count and the reason, and `reduced_to_fragment` names every construct rewritten before translation. Pass `goals_file` (a TSV of triples, e.g. the `derivations.tsv` from onto_reason with certificate_dir, with goals_skip_columns=1) to also write one problem per conjecture. A PROVER'S VERDICT ON THESE FILES IS AN ORACLE OPINION AND NEVER A CERTIFICATE: checking a superposition refutation needs a verified first-order calculus with unification, which does not exist in core Lean. Use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it.")]+ async fn onto_fol_export(&self, Parameters(input): Parameters<OntoFolExportInput>) -> String {+ let syntax = match crate::tptp::Syntax::parse(+ input.format.as_deref().unwrap_or("tptp"),+ input.clif_dialect.as_deref(),+ input.clif_comments.as_deref(),+ ) {+ Ok(s) => s,+ Err(e) => return Self::err_json(e),+ };+ crate::tptp::export(+ &self.graph,+ std::path::Path::new(&input.out_dir),+ syntax,+ input.goals_file.as_deref().map(std::path::Path::new),+ input.goals_skip_columns.unwrap_or(0),+ )+ .unwrap_or_else(Self::err_json)+ }+#[tool(name = "onto_dl_explain", description = "Explain why a class is unsatisfiable using DL tableaux reasoning. Returns an explanation trace showing the logical contradictions that make the class impossible to instantiate.")]async fn onto_dl_explain(&self, Parameters(input): Parameters<OntoDlExplainInput>) -> String {use crate::tableaux::DlReasoner;diff --git a/src/tptp.rs b/src/tptp.rsnew file mode 100644index 00000000..8a16c1a7--- /dev/null+++ b/src/tptp.rs@@ -0,0 +1,2947 @@+//! First-order export: hand an ontology to the automated-theorem-proving+//! ecosystem, in TPTP FOF and in ISO/IEC 24707 CLIF.+//!+//! # What makes this different from every other OWL-to-FOL exporter+//!+//! A sibling project, `owl-lean`, carries a machine-checked adequacy theorem+//! for an OWL-to-first-order translation: `OwlLean.adequacy`, with axiom+//! footprint `[propext, Classical.choice, Quot.sound]`, no `sorry` and no+//! Mathlib. Everyone else's exporter is validated empirically (FOWL, over 168+//! ChEBI modules) or proved on paper (Hets, via the institution satisfaction+//! condition). The translation in this file is written to be the SAME+//! translation that theorem is about, function for function, so a reader can+//! cite a kernel-checked result about what the emitted file means.+//!+//! `adequacy` says, for an ontology `O` and an axiom `a`:+//!+//! ```text+//! Entails O a ↔ FOL.Entails (background ++ indAxioms inds ++ O.map trAx) (trAx a)+//! ```+//!+//! given `hinds : ∀ x : S.Ind, x ∈ inds`, i.e. `inds` enumerates the whole+//! individual vocabulary of the signature.+//!+//! # The correspondence is PINNED BY TESTS AND IS NOT ITSELF PROVED+//!+//! This is Rust and that is Lean. Nothing mechanically checks that+//! `Translation::concept` below is `OwlLean.tr`, or that `Translation::axiom`+//! is `OwlLean.trAx`. What exists is+//! `tests/fol_translation_correspondence_test.rs`, which takes worked cases,+//! computes the expected formula by hand from `OwlLean/Translation.lean`, and+//! pins the emitted string against it. If the Rust and the Lean drift apart,+//! that test is the only thing that will notice. Read the claim as: the+//! translation is the one the theorem is about, up to a test suite, not up to+//! a proof.+//!+//! # The two things the theorem needs, and how they are handled here+//!+//! ## Freshness+//!+//! `tr` allocates bound variables from a counter, and `tr_bridge` needs+//! `Fresh n x`, that is `x < n`: the subject variable must lie strictly below+//! the counter. It is not bookkeeping.+//! `OwlLean.Refutations.tr_bridge_needs_freshness` is a machine-checked+//! countermodel in which the translation of `∃r.⊤` at subject `0` with counter+//! `0` captures its own subject, so the formula stops saying "`a` has an+//! `r`-successor" and starts saying "something is `r`-related to itself".+//!+//! How this file handles it: the exporter never picks a counter. Every entry+//! into the concept translation goes through [`Translation::concept_fresh`],+//! which returns `Err` unless `x < counter`, and the four call sites reproduce+//! `trAx`'s own choices (`tr c 0 2`, `tr c 1 2`, `tr c 0 1`) rather than+//! inventing them. An edit that changes a counter fails a test instead of+//! silently emitting a captured formula.+//!+//! ## Individual typing axioms+//!+//! Nothing in `background` forces a constant to denote an OBJECT, so an+//! arbitrary first-order model may interpret an individual name outside+//! `thing`. `OwlLean.Refutations.adequacy_needs_ind_axioms` refutes the+//! left-to-right direction of adequacy outright with the empty ontology and+//! the axiom `⊤(a)`: the countermodel `Mbad` sends the name to a literal. The+//! fix is `indAxioms`, i.e. `Thing(a)` for every individual name. This was a+//! real defect found while proving the theorem, not a hypothetical.+//!+//! How this file handles it: [`FolProblem::ind_axioms`] emits `thing(i)` for+//! every individual in the signature, and the signature is built from exactly+//! the individual names occurring in the exported axioms and in the goal. The+//! theorem's hypothesis is `∀ x : S.Ind, x ∈ inds`, which holds here because+//! `S.Ind` IS the occurring set by construction. (`owl-lean`'s README lists+//! weakening that hypothesis to "the occurring vocabulary" as open work; the+//! exporter sits on the side of the gap where the hypothesis is satisfied.)+//! `tests/fol_translation_correspondence_test.rs` reconstructs the `Mbad`+//! scenario and fails if the typing axiom is ever absent.+//!+//! # What an ATP's answer is worth+//!+//! Nothing here certifies anything. A derivation certificate from the+//! forward-chaining reasoner can be checked because `lean/` holds a checker+//! whose soundness is a theorem (decision 0002). A superposition refutation+//! cannot: checking one needs a verified first-order calculus with+//! unification, which does not exist in core Lean. So when E or Vampire says+//! "Theorem", that is an ORACLE OPINION, exactly like pyshacl's verdict in+//! `tools/shacl_differential.py`, and `tools/fol_differential.py` reports+//! disagreement rather than adjudicating it. The word "proved" does not appear+//! next to an ATP verdict anywhere in this codebase.+//!+//! # The quoting trap, which points opposite ways in the two syntaxes+//!+//! [`fof::quoted`] uses SINGLE-quoted TPTP atoms and [`clif::enclosed`] uses+//! DOUBLE-quoted CLIF enclosed names. That is not an inconsistency and it is+//! the reverse of what most people assume, so both halves are written down.+//!+//! In TPTP a single-quoted atom is an ordinary constant, and a DOUBLE-quoted+//! string is a "distinct object", which is pairwise unequal to every other+//! distinct object by fiat. Had the TPTP printer used double quotes for IRIs it+//! would have silently asserted that all individuals are pairwise distinct.+//! OWL has no unique name assumption, so that would make every `owl:sameAs`+//! export unsound, and the file would still parse and still prove things.+//!+//! In CLIF the polarity flips. A single-quoted string is an INTERPRETED name+//! that denotes itself, and a double-quoted enclosed name is an ordinary+//! interpretable name, which is why A.2.2.4 recommends the enclosed-name+//! syntax for writing IRIs. Using single quotes for IRIs there would take the+//! text out of the subdialect A.4.2 calls exactly semantically conformant.+//!+//! So: single quotes in TPTP, double quotes in CLIF, for the same IRI, for+//! opposite reasons.+//!+//! # Two serialisers, one translation+//!+//! [`Form`] is computed once. [`tptp`] and [`clif`] are renderings of it and+//! contain no OWL-specific logic at all; each is a fold over `Form`. CLIF is+//! restricted to the first-order-equivalent fragment of Common Logic on+//! purpose: no sequence markers, fixed arity at every position, no+//! quantification into a predicate position. Common Logic is NOT plain+//! first-order logic, and the adequacy theorem is about a translation into+//! plain first-order logic, so anything outside that fragment would sit+//! outside the theorem. [`Form`] cannot express the excluded constructs, which+//! is the structural reason the restriction holds; `clif_uses_only_fol_fragment`+//! in the correspondence test is the check that it still holds.++use std::collections::{BTreeMap, BTreeSet};+use std::fmt::Write as _;++// ── The target logic: OwlLean/FOL/Basic.lean ────────────────────────────────++/// A first-order term. Mirrors `OwlLean.FOL.Term`: a `Nat`-indexed variable or+/// a constant, and constants are individual names (`FSig.Const := S.Ind`).+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub enum Term {+ Var(u32),+ Const(String),+}++/// Unary predicate symbols. Mirrors `OwlLean.OwlP1`.+///+/// The four arms are a disjoint sum in Lean and are disjoint symbols here, so+/// an IRI used as both a class and a datatype yields two unrelated predicates.+/// That is what the Structural Specification's separation of entity kinds+/// means, and it is what `Sig` encodes by giving each kind its own type.+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub enum P1 {+ Cls(String),+ Dt(String),+ Thing,+ Lit,+}++/// Binary predicate symbols. Mirrors `OwlLean.OwlP2`.+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub enum P2 {+ Op(String),+ Dp(String),+}++/// A first-order formula. Mirrors `OwlLean.FOL.Form` constructor for+/// constructor, including the explicit `Nat` on each binder: `owl-lean` uses+/// named variables rather than de Bruijn indices precisely so that freshness+/// is a proof obligation and not a silent convention, and an exporter that+/// renumbered would be emitting a different formula.+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub enum Form {+ App1(P1, Term),+ App2(P2, Term, Term),+ Eq(Term, Term),+ Tru,+ Fls,+ Neg(Box<Form>),+ And(Box<Form>, Box<Form>),+ Or(Box<Form>, Box<Form>),+ Imp(Box<Form>, Box<Form>),+ All(u32, Box<Form>),+ Ex(u32, Box<Form>),+}++impl Form {+ fn neg(f: Form) -> Form {+ Form::Neg(Box::new(f))+ }+ fn and(f: Form, g: Form) -> Form {+ Form::And(Box::new(f), Box::new(g))+ }+ fn or(f: Form, g: Form) -> Form {+ Form::Or(Box::new(f), Box::new(g))+ }+ fn imp(f: Form, g: Form) -> Form {+ Form::Imp(Box::new(f), Box::new(g))+ }+ fn all(n: u32, f: Form) -> Form {+ Form::All(n, Box::new(f))+ }+ fn ex(n: u32, f: Form) -> Form {+ Form::Ex(n, Box::new(f))+ }++ /// `OwlLean.FOL.Form.conj`. Right-associated, `[]` is `tru`, `[f]` is `f`.+ /// The shape matters: `conj [a, b, c]` is `and a (and b c)` and not+ /// `and (and a b) c`, and the correspondence test pins the difference.+ fn conj(mut fs: Vec<Form>) -> Form {+ match fs.len() {+ 0 => Form::Tru,+ 1 => fs.pop().expect("length checked"),+ _ => {+ let head = fs.remove(0);+ Form::and(head, Form::conj(fs))+ }+ }+ }++ /// `OwlLean.FOL.Form.disj`.+ fn disj(mut fs: Vec<Form>) -> Form {+ match fs.len() {+ 0 => Form::Fls,+ 1 => fs.pop().expect("length checked"),+ _ => {+ let head = fs.remove(0);+ Form::or(head, Form::disj(fs))+ }+ }+ }++ /// Every individual name occurring in the formula. Used to build the+ /// signature's individual vocabulary, which is what `indAxioms` ranges+ /// over and what the adequacy theorem's `hinds` hypothesis is about.+ fn individuals(&self, out: &mut BTreeSet<String>) {+ fn t(term: &Term, out: &mut BTreeSet<String>) {+ if let Term::Const(a) = term {+ out.insert(a.clone());+ }+ }+ match self {+ Form::App1(_, x) => t(x, out),+ Form::App2(_, x, y) | Form::Eq(x, y) => {+ t(x, out);+ t(y, out);+ }+ Form::Tru | Form::Fls => {}+ Form::Neg(f) | Form::All(_, f) | Form::Ex(_, f) => f.individuals(out),+ Form::And(f, g) | Form::Or(f, g) | Form::Imp(f, g) => {+ f.individuals(out);+ g.individuals(out);+ }+ }+ }+}++// Smart constructors for the atoms `Translation.lean` defines by name, kept+// with the same names so the two files read alike.+fn v(n: u32) -> Term {+ Term::Var(n)+}+fn k(a: &str) -> Term {+ Term::Const(a.to_string())+}+fn cls(a: &str, t: Term) -> Form {+ Form::App1(P1::Cls(a.to_string()), t)+}+fn dt(d: &str, t: Term) -> Form {+ Form::App1(P1::Dt(d.to_string()), t)+}+fn thing(t: Term) -> Form {+ Form::App1(P1::Thing, t)+}+fn lit(t: Term) -> Form {+ Form::App1(P1::Lit, t)+}+fn op(r: &str, t: Term, u: Term) -> Form {+ Form::App2(P2::Op(r.to_string()), t, u)+}+fn dp(p: &str, t: Term, u: Term) -> Form {+ Form::App2(P2::Dp(p.to_string()), t, u)+}++/// `OwlLean.exObj`: guarded existential over the object domain.+fn ex_obj(n: u32, f: Form) -> Form {+ Form::ex(n, Form::and(thing(v(n)), f))+}+/// `OwlLean.allObj`: guarded universal over the object domain.+fn all_obj(n: u32, f: Form) -> Form {+ Form::all(n, Form::imp(thing(v(n)), f))+}+/// `OwlLean.exDat`.+fn ex_dat(n: u32, f: Form) -> Form {+ Form::ex(n, Form::and(lit(v(n)), f))+}+/// `OwlLean.allDat`.+fn all_dat(n: u32, f: Form) -> Form {+ Form::all(n, Form::imp(lit(v(n)), f))+}++/// `OwlLean.substT`.+fn subst_t(x: u32, u: &Term, t: &Term) -> Term {+ match t {+ Term::Var(m) if *m == x => u.clone(),+ other => other.clone(),+ }+}++/// `OwlLean.substVar`. Capture-avoiding for the constant terms it is used+/// with: a binder that rebinds the index stops the descent.+fn subst_var(x: u32, u: &Term, f: &Form) -> Form {+ match f {+ Form::App1(p, t) => Form::App1(p.clone(), subst_t(x, u, t)),+ Form::App2(p, t, w) => Form::App2(p.clone(), subst_t(x, u, t), subst_t(x, u, w)),+ Form::Eq(t, w) => Form::Eq(subst_t(x, u, t), subst_t(x, u, w)),+ Form::Tru => Form::Tru,+ Form::Fls => Form::Fls,+ Form::Neg(g) => Form::neg(subst_var(x, u, g)),+ Form::And(g, h) => Form::and(subst_var(x, u, g), subst_var(x, u, h)),+ Form::Or(g, h) => Form::or(subst_var(x, u, g), subst_var(x, u, h)),+ Form::Imp(g, h) => Form::imp(subst_var(x, u, g), subst_var(x, u, h)),+ Form::All(n, g) => {+ if *n == x {+ Form::All(*n, g.clone())+ } else {+ Form::all(*n, subst_var(x, u, g))+ }+ }+ Form::Ex(n, g) => {+ if *n == x {+ Form::Ex(*n, g.clone())+ } else {+ Form::ex(*n, subst_var(x, u, g))+ }+ }+ }+}++/// `OwlLean.mkEx`.+fn mk_ex(ns: &[u32], f: Form) -> Form {+ match ns.split_first() {+ None => f,+ Some((n, rest)) => ex_obj(*n, mk_ex(rest, f)),+ }+}++/// `OwlLean.mkAll`.+fn mk_all(ns: &[u32], f: Form) -> Form {+ match ns.split_first() {+ None => f,+ Some((n, rest)) => all_obj(*n, mk_all(rest, f)),+ }+}++/// `OwlLean.distinctPairs`. The order is the Lean order: for `n :: ns`, every+/// pair `(n, m)` with `m` in `ns` first, then recursively over `ns`.+fn distinct_pairs(ys: &[u32]) -> Vec<Form> {+ match ys.split_first() {+ None => Vec::new(),+ Some((n, rest)) => {+ let mut out: Vec<Form> = rest+ .iter()+ .map(|m| Form::neg(Form::Eq(v(*n), v(*m))))+ .collect();+ out.extend(distinct_pairs(rest));+ out+ }+ }+}++/// `OwlLean.somePairEq`.+fn some_pair_eq(ys: &[u32]) -> Vec<Form> {+ match ys.split_first() {+ None => Vec::new(),+ Some((n, rest)) => {+ let mut out: Vec<Form> = rest.iter().map(|m| Form::Eq(v(*n), v(*m))).collect();+ out.extend(some_pair_eq(rest));+ out+ }+ }+}++// ── The source logic: OwlLean/Syntax.lean ───────────────────────────────────++/// Class expressions. Mirrors `OwlLean.Concept`. `MinCard`/`MaxCard` are the+/// QUALIFIED forms; the unqualified ones are recovered with `Top` as filler,+/// exactly as in the Lean.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Concept {+ Top,+ Bot,+ Atom(String),+ Inter(Box<Concept>, Box<Concept>),+ Union(Box<Concept>, Box<Concept>),+ Compl(Box<Concept>),+ OneOf(Vec<String>),+ Some_(String, Box<Concept>),+ All_(String, Box<Concept>),+ HasVal(String, String),+ HasSelf(String),+ MinCard(u32, String, Box<Concept>),+ MaxCard(u32, String, Box<Concept>),+ DataSome(String, String),+ DataAll(String, String),+}++/// Object property expressions. Mirrors `OwlLean.OPE`.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Ope {+ Named(String),+ Inv(String),+}++/// Axioms. Mirrors `OwlLean.Axiom`, all twenty-two forms.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum OwlAxiom {+ SubClass(Concept, Concept),+ EquivClass(Concept, Concept),+ DisjointWith(Concept, Concept),+ SubOProp(Ope, Ope),+ OPropDomain(Ope, Concept),+ OPropRange(Ope, Concept),+ DPropDomain(String, Concept),+ DPropRange(String, String),+ Transitive(String),+ Symmetric(String),+ Asymmetric(String),+ Reflexive(String),+ Irreflexive(String),+ Functional(String),+ InvFunctional(String),+ InverseOf(String, String),+ PropDisjoint(String, String),+ Chain(Vec<String>, String),+ ClassAssert(Concept, String),+ OPropAssert(String, String, String),+ SameAs(String, String),+ DifferentFrom(String, String),+}++// ── The translation: OwlLean/Translation.lean ───────────────────────────────++/// A violation of the freshness side condition the adequacy theorem carries.+///+/// `tr_bridge` holds only under `Fresh n x`, i.e. `x < n`. This error exists+/// so that a future edit to a counter fails loudly rather than emitting a+/// formula in which the subject variable has been captured. See+/// `OwlLean.Refutations.tr_bridge_needs_freshness`, the machine-checked+/// countermodel for exactly this.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NotFresh {+ pub subject: u32,+ pub counter: u32,+}++impl std::fmt::Display for NotFresh {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "freshness violated: subject variable X{} is not below the counter {}. \+ OwlLean.tr_bridge holds only under `Fresh n x` (x < n); without it the \+ existential `tr` allocates CAPTURES the subject variable, and \+ OwlLean.Refutations.tr_bridge_needs_freshness is the countermodel",+ self.subject, self.counter+ )+ }+}++impl std::error::Error for NotFresh {}++/// The translation. Every method is a transcription of the Lean function named+/// in its doc comment; nothing here is an optimisation or a normalisation of+/// it, because the emitted formula has to be the formula the theorem is about+/// and not one equivalent to it.+pub struct Translation;++impl Translation {+ /// `OwlLean.tr` under the theorem's freshness side condition.+ ///+ /// Callers must satisfy `subject < counter`. The unchecked body is+ /// [`Translation::concept`], which exists only because the recursive calls+ /// inside it maintain the invariant themselves (`tr_mono`: the counter+ /// never decreases) and re-checking on every node would be noise.+ pub fn concept_fresh(c: &Concept, subject: u32, counter: u32) -> Result<(Form, u32), NotFresh> {+ if subject >= counter {+ return Err(NotFresh { subject, counter });+ }+ Ok(Self::concept(c, subject, counter))+ }++ /// `OwlLean.tr`: translate a class expression at subject variable `x` with+ /// next free index `c`, returning the formula and the next free index.+ fn concept(c: &Concept, x: u32, counter: u32) -> (Form, u32) {+ match c {+ Concept::Top => (Form::Tru, counter),+ Concept::Bot => (Form::Fls, counter),+ Concept::Atom(a) => (cls(a, v(x)), counter),+ Concept::Inter(p, q) => {+ let (f, c1) = Self::concept(p, x, counter);+ let (g, c2) = Self::concept(q, x, c1);+ (Form::and(f, g), c2)+ }+ Concept::Union(p, q) => {+ let (f, c1) = Self::concept(p, x, counter);+ let (g, c2) = Self::concept(q, x, c1);+ (Form::or(f, g), c2)+ }+ Concept::Compl(p) => {+ let (f, c1) = Self::concept(p, x, counter);+ (Form::neg(f), c1)+ }+ Concept::OneOf(as_) => (+ Form::disj(as_.iter().map(|a| Form::Eq(v(x), k(a))).collect()),+ counter,+ ),+ Concept::Some_(r, p) => {+ let y = counter;+ let (f, c1) = Self::concept(p, y, counter + 1);+ (ex_obj(y, Form::and(op(r, v(x), v(y)), f)), c1)+ }+ Concept::All_(r, p) => {+ let y = counter;+ let (f, c1) = Self::concept(p, y, counter + 1);+ (all_obj(y, Form::imp(op(r, v(x), v(y)), f)), c1)+ }+ Concept::HasVal(r, a) => (op(r, v(x), k(a)), counter),+ Concept::HasSelf(r) => (op(r, v(x), v(x)), counter),+ Concept::DataSome(p, t) => (+ ex_dat(+ counter,+ Form::and(dp(p, v(x), v(counter)), dt(t, v(counter))),+ ),+ counter + 1,+ ),+ Concept::DataAll(p, t) => (+ all_dat(+ counter,+ Form::imp(dp(p, v(x), v(counter)), dt(t, v(counter))),+ ),+ counter + 1,+ ),+ // The two cases LATIN's OWL2toFOL.elf has commented out, and the+ // ones 37.2% of constrained real ontologies and gchq/HQDM's 357+ // cardinality-bearing restrictions depend on.+ Concept::MinCard(n, r, p) => {+ let ys: Vec<u32> = (0..*n).map(|i| counter + i).collect();+ let (bodies, c1) = Self::concept_list(p, &ys, counter + n);+ let mut parts = distinct_pairs(&ys);+ parts.extend(+ ys.iter()+ .zip(bodies)+ .map(|(y, f)| Form::and(op(r, v(x), v(*y)), f)),+ );+ (mk_ex(&ys, Form::conj(parts)), c1)+ }+ Concept::MaxCard(n, r, p) => {+ let ys: Vec<u32> = (0..=*n).map(|i| counter + i).collect();+ let (bodies, c1) = Self::concept_list(p, &ys, counter + n + 1);+ let body: Vec<Form> = ys+ .iter()+ .zip(bodies)+ .map(|(y, f)| Form::and(op(r, v(x), v(*y)), f))+ .collect();+ (+ mk_all(+ &ys,+ Form::imp(Form::conj(body), Form::disj(some_pair_eq(&ys))),+ ),+ c1,+ )+ }+ }+ }++ /// `OwlLean.tr.trList`: translate one concept once per subject variable,+ /// threading the freshness counter left to right.+ fn concept_list(p: &Concept, ys: &[u32], counter: u32) -> (Vec<Form>, u32) {+ match ys.split_first() {+ None => (Vec::new(), counter),+ Some((y, rest)) => {+ let (f, c1) = Self::concept(p, *y, counter);+ let (mut fs, c2) = Self::concept_list(p, rest, c1);+ fs.insert(0, f);+ (fs, c2)+ }+ }+ }++ /// `OwlLean.trAx.ope`.+ fn ope(r: &Ope, i: u32, j: u32) -> Form {+ match r {+ Ope::Named(r) => op(r, v(i), v(j)),+ Ope::Inv(r) => op(r, v(j), v(i)),+ }+ }++ /// `OwlLean.trAx`: translate an axiom to a closed formula.+ ///+ /// The counters are `trAx`'s own and are not a choice this file makes.+ /// Each is routed through [`Translation::concept_fresh`], so `0 < 2`,+ /// `1 < 2` and `0 < 1` are checked at run time rather than asserted in a+ /// comment.+ pub fn axiom(a: &OwlAxiom) -> Result<Form, NotFresh> {+ Ok(match a {+ OwlAxiom::SubClass(c, d) => {+ let (f, n) = Self::concept_fresh(c, 0, 2)?;+ let (g, _) = Self::concept_fresh(d, 0, n)?;+ all_obj(0, Form::imp(f, g))+ }+ OwlAxiom::EquivClass(c, d) => {+ let (f, n) = Self::concept_fresh(c, 0, 2)?;+ let (g, _) = Self::concept_fresh(d, 0, n)?;+ all_obj(+ 0,+ Form::and(Form::imp(f.clone(), g.clone()), Form::imp(g, f)),+ )+ }+ OwlAxiom::DisjointWith(c, d) => {+ let (f, n) = Self::concept_fresh(c, 0, 2)?;+ let (g, _) = Self::concept_fresh(d, 0, n)?;+ all_obj(0, Form::neg(Form::and(f, g)))+ }+ OwlAxiom::SubOProp(r, s) => all_obj(+ 0,+ all_obj(1, Form::imp(Self::ope(r, 0, 1), Self::ope(s, 0, 1))),+ ),+ OwlAxiom::OPropDomain(r, c) => {+ let (f, _) = Self::concept_fresh(c, 0, 2)?;+ all_obj(0, all_obj(1, Form::imp(Self::ope(r, 0, 1), f)))+ }+ OwlAxiom::OPropRange(r, c) => {+ let (f, _) = Self::concept_fresh(c, 1, 2)?;+ all_obj(0, all_obj(1, Form::imp(Self::ope(r, 0, 1), f)))+ }+ OwlAxiom::DPropDomain(p, c) => {+ let (f, _) = Self::concept_fresh(c, 0, 2)?;+ all_obj(0, all_dat(1, Form::imp(dp(p, v(0), v(1)), f)))+ }+ OwlAxiom::DPropRange(p, t) => all_obj(+ 0,+ all_dat(1, Form::imp(dp(p, v(0), v(1)), dt(t, v(1)))),+ ),+ OwlAxiom::Transitive(r) => all_obj(+ 0,+ all_obj(+ 1,+ all_obj(+ 2,+ Form::imp(+ Form::and(op(r, v(0), v(1)), op(r, v(1), v(2))),+ op(r, v(0), v(2)),+ ),+ ),+ ),+ ),+ OwlAxiom::Symmetric(r) => all_obj(+ 0,+ all_obj(1, Form::imp(op(r, v(0), v(1)), op(r, v(1), v(0)))),+ ),+ OwlAxiom::Asymmetric(r) => all_obj(+ 0,+ all_obj(+ 1,+ Form::imp(op(r, v(0), v(1)), Form::neg(op(r, v(1), v(0)))),+ ),+ ),+ OwlAxiom::Reflexive(r) => all_obj(0, op(r, v(0), v(0))),+ OwlAxiom::Irreflexive(r) => all_obj(0, Form::neg(op(r, v(0), v(0)))),+ OwlAxiom::Functional(r) => all_obj(+ 0,+ all_obj(+ 1,+ all_obj(+ 2,+ Form::imp(+ Form::and(op(r, v(0), v(1)), op(r, v(0), v(2))),+ Form::Eq(v(1), v(2)),+ ),+ ),+ ),+ ),+ OwlAxiom::InvFunctional(r) => all_obj(+ 0,+ all_obj(+ 1,+ all_obj(+ 2,+ Form::imp(+ Form::and(op(r, v(0), v(2)), op(r, v(1), v(2))),+ Form::Eq(v(0), v(1)),+ ),+ ),+ ),+ ),+ OwlAxiom::InverseOf(r, s) => all_obj(+ 0,+ all_obj(+ 1,+ Form::and(+ Form::imp(op(r, v(0), v(1)), op(s, v(1), v(0))),+ Form::imp(op(s, v(1), v(0)), op(r, v(0), v(1))),+ ),+ ),+ ),+ OwlAxiom::PropDisjoint(r, s) => all_obj(+ 0,+ all_obj(+ 1,+ Form::neg(Form::and(op(r, v(0), v(1)), op(s, v(0), v(1)))),+ ),+ ),+ // `OwlLean.trAx.chainForm`: a chain of length n needs n+1 variables.+ OwlAxiom::Chain(rs, s) => {+ let n = rs.len() as u32;+ let vars: Vec<u32> = (0..=n).collect();+ let body: Vec<Form> = rs+ .iter()+ .enumerate()+ .map(|(i, r)| op(r, v(i as u32), v(i as u32 + 1)))+ .collect();+ mk_all(+ &vars,+ Form::imp(Form::conj(body), op(s, v(0), v(n))),+ )+ }+ // The `thing(a)` conjunct here is NOT the individual typing axiom.+ // It is part of `trAx` itself, and it is what `Mbad` refutes when+ // the typing axioms are absent from the background theory.+ OwlAxiom::ClassAssert(c, a) => {+ let (f, _) = Self::concept_fresh(c, 0, 1)?;+ Form::and(thing(k(a)), subst_var(0, &k(a), &f))+ }+ OwlAxiom::OPropAssert(r, a, b) => op(r, k(a), k(b)),+ OwlAxiom::SameAs(a, b) => Form::Eq(k(a), k(b)),+ OwlAxiom::DifferentFrom(a, b) => Form::neg(Form::Eq(k(a), k(b))),+ })+ }++ /// `OwlLean.background`: the two domains are disjoint, and the object+ /// domain is non-empty.+ ///+ /// These are the Direct Semantics' side conditions on an interpretation+ /// and MUST accompany any translated ontology. Note that both quantifiers+ /// are UNGUARDED in the Lean (`.all 0`, `.ex 0`, not `allObj`/`exObj`),+ /// which is exactly what makes the second one say "some element of the+ /// domain is an object" rather than a tautology.+ ///+ /// `owl-lean` also records that the disjointness axiom is never USED by+ /// the proof: `ofStruc` cuts the single first-order domain into two Lean+ /// types whether or not they overlap as sets, and every quantifier `tr`+ /// emits is guarded. It is discharged, not consumed. It is emitted anyway,+ /// because it is part of the theory the theorem is stated about and+ /// because a consumer reading the file has no other way to learn that the+ /// two sorts are meant to be disjoint.+ pub fn background() -> Vec<Form> {+ vec![+ Form::all(0, Form::neg(Form::and(thing(v(0)), lit(v(0))))),+ Form::ex(0, thing(v(0))),+ ]+ }++ /// `OwlLean.indAxioms`: `Thing(a)` for each individual name.+ ///+ /// The absence of these was a real defect found while proving adequacy,+ /// refuted by `OwlLean.Refutations.adequacy_needs_ind_axioms`. Real+ /// OWL-to-FOL tools emit them; the theorem says what it costs to leave+ /// them out.+ pub fn ind_axioms(inds: &BTreeSet<String>) -> Vec<Form> {+ inds.iter().map(|a| thing(k(a))).collect()+ }+}++// ── One problem, two serialisations ─────────────────────────────────────────++/// The first-order content of an export: a background theory, the individual+/// typing axioms, the translated ontology, and optionally one conjecture.+///+/// Computed once. [`FolProblem::to_tptp`] and [`FolProblem::to_clif`] are+/// renderings of it and share every formula; neither contains OWL-specific+/// logic.+#[derive(Clone, Debug)]+pub struct FolProblem {+ pub background: Vec<Form>,+ pub ind_axioms: Vec<Form>,+ /// Translated ontology axioms, each paired with a short label naming the+ /// OWL axiom form it came from, so a reader of the file can find the+ /// source construct without re-deriving it.+ pub axioms: Vec<(String, Form)>,+ pub conjecture: Option<(String, Form)>,+ /// Individual names the typing axioms range over, in a fixed order.+ pub individuals: BTreeSet<String>,+}++impl FolProblem {+ /// Build the problem for an ontology and an optional goal.+ ///+ /// The individual vocabulary is collected from the translated formulas+ /// themselves, including the goal's, so `indAxioms` covers exactly the+ /// constants that can appear. That is what makes the adequacy theorem's+ /// `hinds : ∀ x : S.Ind, x ∈ inds` hold for the signature this export+ /// defines.+ pub fn build(+ axioms: &[OwlAxiom],+ goal: Option<&OwlAxiom>,+ ) -> Result<FolProblem, NotFresh> {+ let mut translated = Vec::with_capacity(axioms.len());+ let mut individuals = BTreeSet::new();+ for a in axioms {+ let f = Translation::axiom(a)?;+ f.individuals(&mut individuals);+ translated.push((axiom_label(a).to_string(), f));+ }+ let conjecture = match goal {+ None => None,+ Some(g) => {+ let f = Translation::axiom(g)?;+ f.individuals(&mut individuals);+ Some((axiom_label(g).to_string(), f))+ }+ };+ Ok(FolProblem {+ background: Translation::background(),+ ind_axioms: Translation::ind_axioms(&individuals),+ axioms: translated,+ conjecture,+ individuals,+ })+ }++ /// Every formula in the problem, in emission order, paired with the role+ /// it plays. Both serialisers walk exactly this, which is the mechanical+ /// reason they cannot disagree about which formulas are in the file.+ pub fn formulas(&self) -> Vec<(String, &'static str, &Form)> {+ let mut out: Vec<(String, &'static str, &Form)> = Vec::new();+ for (i, f) in self.background.iter().enumerate() {+ out.push((format!("background_{}", i + 1), "axiom", f));+ }+ for (i, f) in self.ind_axioms.iter().enumerate() {+ out.push((format!("ind_typing_{}", i + 1), "axiom", f));+ }+ for (i, (label, f)) in self.axioms.iter().enumerate() {+ out.push((format!("owl_{}_{}", i + 1, label), "axiom", f));+ }+ if let Some((label, f)) = &self.conjecture {+ out.push((format!("goal_{label}"), "conjecture", f));+ }+ out+ }++ /// TPTP FOF.+ pub fn to_tptp(&self) -> String {+ let mut s = String::new();+ s.push_str(&header("%", self.conjecture.is_some()));+ for (name, role, f) in self.formulas() {+ let _ = writeln!(s, "fof({name}, {role}, {}).", fof::form(f));+ }+ s+ }++ /// ISO/IEC 24707 CLIF, restricted to the first-order-equivalent fragment.+ ///+ /// Everything in the file is CLIF: there are no lexical comments, because+ /// the standard defines `cl:comment` as a reserved element and this+ /// project could not establish a `//` or `/* */` line-comment convention+ /// from the standard's own text. The header therefore rides on+ /// `cl:comment` attached to `(and)`, the empty conjunction, which ISO/IEC+ /// 24707 A.2.3.7 makes the truth value TRUE. It is true in every model, so+ /// it adds nothing to the theory and the file still denotes exactly the+ /// formula set [`FolProblem::formulas`] lists.+ pub fn to_clif(+ &self,+ dialect: ClifDialect,+ comments: ClifComments,+ name: &str,+ ) -> String {+ let mut s = String::new();+ // A NAMED text. All 227 COLORE texts are named, Macleod rejects an+ // unnamed one with "Error in ontology: bad URI", and py-typedlogic+ // otherwise reports the first comment as the theory's name.+ let _ = writeln!(s, "({} {}", dialect.text_op(), clif::text_name(name));+ let _ = writeln!(+ s,+ " {}",+ clif::standalone_comment(dialect, &header_text(self.conjecture.is_some(), true))+ );+ for (label, role, f) in self.formulas() {+ match comments {+ ClifComments::Standalone => {+ let _ = writeln!(+ s,+ " {}",+ clif::standalone_comment(dialect, &format!("{label} ({role})"))+ );+ let _ = writeln!(s, " {}", clif::form(f));+ }+ ClifComments::Wrapped => {+ let _ = writeln!(+ s,+ " {}",+ clif::commented(dialect, &format!("{label} ({role})"), f)+ );+ }+ }+ }+ s.push_str(")\n");+ s+ }+}++/// The header both serialisers carry, with each line prefixed by the syntax's+/// comment marker. It is not decoration: a file that leaves its own limits to+/// a README gets read without one.+fn header(comment: &str, has_goal: bool) -> String {+ header_text(has_goal, comment == "//")+ .lines()+ .map(|l| {+ if l.is_empty() {+ format!("{comment}\n")+ } else {+ format!("{comment} {l}\n")+ }+ })+ .collect()+}++/// The header, unprefixed, so CLIF can carry it inside a `cl:comment` string.+fn header_text(has_goal: bool, clif: bool) -> String {+ let mut lines: Vec<&str> = vec![+ "Generated by open-ontologies `fol` export.",+ "",+ "The translation is the one owl-lean's machine-checked adequacy theorem",+ "`OwlLean.adequacy` is about (axioms: propext, Classical.choice, Quot.sound;",+ "no sorry, no Mathlib). The CORRESPONDENCE between this emitter and that Lean",+ "translation is PINNED BY TESTS AND IS NOT ITSELF PROVED.",+ "",+ "`thing` and `lit` are the soft-typing predicates: object positions are",+ "relativised by `thing`, data positions by `lit`. The first two axioms are",+ "owl-lean's `background`; the `ind_typing_*` axioms are its `indAxioms`, and",+ "omitting them refutes adequacy outright (OwlLean.Refutations).",+ ];+ if clif {+ lines.extend([+ "",+ "CLIF RESTRICTION. Common Logic is not plain first-order logic. This text",+ "uses only the first-order-equivalent fragment: no sequence markers, fixed",+ "arity at every position, and no quantification into a predicate position.",+ "Sequence markers are what actually take Common Logic past first order",+ "(ISO/IEC 24707 clause 6.5: the logic with them is not compact), and the",+ "adequacy theorem is about plain first-order logic, so anything outside this",+ "fragment would sit outside the theorem.",+ "",+ "`(and)` with no arguments is truth and `(or)` with no arguments is falsity",+ "(A.2.3.7). CLIF defines no truth constants, and these are its readings.",+ "Names are enclosed names in DOUBLE QUOTES (A.2.2.2 namequote), which A.2.2.4",+ "recommends for writing IRIs as names. The vertical bar is an ordinary name",+ "character in CLIF and is not a quoting construct.",+ "",+ "EXACTLY CONFORMANT SUBDIALECT. ISO/IEC 24707 first edition Annex A.4.2: \"The",+ "subdialect of CLIF which does not use numerals or quoted strings is exactly",+ "semantically conformant\". This text stays in it, so CLIF entailment and",+ "Common Logic entailment coincide here and the adequacy theorem needs no",+ "qualification at the CLIF end. The scope of that claim, exactly: no decimal",+ "numerals and no quoted strings IN SENTENCE POSITIONS. Comment annotations are",+ "the named exception, since a comment text is a quoted string by definition;",+ "the CLIF files ISO hosts for ISO/IEC 21838-2 are in the same position. The",+ "property is checked, not asserted: clif_stays_in_the_exactly_conformant_subdialect",+ "in tests/fol_translation_correspondence_test.rs. Nothing here is claimed about",+ "the second edition's Annex A.3, which this project has not read.",+ "",+ "DIALECT. This file uses one of the two spellings in circulation. `cl:text`",+ "and `cl:comment` are ISO/IEC 24707's reserved tokens and are what ISO",+ "publishes with ISO/IEC 21838-2 (BFO-2020 CLIF). The COLORE repository and",+ "the Macleod toolchain's shipped lexer use `cl-text` and `cl-comment`",+ "instead, and will not read the colon spelling. Re-export with the other",+ "dialect rather than hand-editing.",+ ]);+ }+ if has_goal {+ lines.extend([+ "",+ "A prover's verdict on this file is an ORACLE OPINION, not a certificate.",+ "Checking a superposition refutation needs a verified first-order calculus",+ "with unification, which does not exist in core Lean. Disagreement between",+ "a prover and this engine is a bug in one of the two and nothing here says",+ "which.",+ ]);+ }+ lines.join("\n")+}++fn axiom_label(a: &OwlAxiom) -> &'static str {+ match a {+ OwlAxiom::SubClass(..) => "subClassOf",+ OwlAxiom::EquivClass(..) => "equivalentClass",+ OwlAxiom::DisjointWith(..) => "disjointWith",+ OwlAxiom::SubOProp(..) => "subObjectPropertyOf",+ OwlAxiom::OPropDomain(..) => "objectPropertyDomain",+ OwlAxiom::OPropRange(..) => "objectPropertyRange",+ OwlAxiom::DPropDomain(..) => "dataPropertyDomain",+ OwlAxiom::DPropRange(..) => "dataPropertyRange",+ OwlAxiom::Transitive(..) => "transitiveProperty",+ OwlAxiom::Symmetric(..) => "symmetricProperty",+ OwlAxiom::Asymmetric(..) => "asymmetricProperty",+ OwlAxiom::Reflexive(..) => "reflexiveProperty",+ OwlAxiom::Irreflexive(..) => "irreflexiveProperty",+ OwlAxiom::Functional(..) => "functionalProperty",+ OwlAxiom::InvFunctional(..) => "inverseFunctionalProperty",+ OwlAxiom::InverseOf(..) => "inverseOf",+ OwlAxiom::PropDisjoint(..) => "propertyDisjointWith",+ OwlAxiom::Chain(..) => "propertyChainAxiom",+ OwlAxiom::ClassAssert(..) => "classAssertion",+ OwlAxiom::OPropAssert(..) => "objectPropertyAssertion",+ OwlAxiom::SameAs(..) => "sameAs",+ OwlAxiom::DifferentFrom(..) => "differentFrom",+ }+}++// ── Serialiser 1: TPTP FOF ──────────────────────────────────────────────────++/// TPTP FOF rendering of [`Form`]. A fold over the formula and nothing else.+///+/// Named `fof` rather than `tptp` so it sits beside [`clif`] as one of two+/// syntaxes, which is what it is.+pub mod fof {+ use super::{Form, P1, P2, Term};++ /// Symbols are single-quoted TPTP atoms carrying a kind prefix.+ ///+ /// The prefix is not cosmetic. `OwlP1` and `OwlP2` are disjoint sums in+ /// the Lean, so a class and an object property that happen to share an IRI+ /// are two unrelated symbols, and a rendering that collapsed them would+ /// emit a different theory. Every prefix contains a colon, which is not+ /// legal in an unquoted TPTP lower-word, so no prefixed symbol can ever+ /// collide with the bare atoms `thing` and `lit`.+ fn quoted(prefix: &str, iri: &str) -> String {+ let mut s = String::with_capacity(iri.len() + prefix.len() + 4);+ s.push('\'');+ s.push_str(prefix);+ for ch in iri.chars() {+ if ch == '\\' || ch == '\'' {+ s.push('\\');+ }+ s.push(ch);+ }+ s.push('\'');+ s+ }++ fn p1(p: &P1) -> String {+ match p {+ P1::Cls(a) => quoted("c:", a),+ P1::Dt(d) => quoted("d:", d),+ P1::Thing => "thing".to_string(),+ P1::Lit => "lit".to_string(),+ }+ }++ fn p2(p: &P2) -> String {+ match p {+ P2::Op(r) => quoted("op:", r),+ P2::Dp(d) => quoted("dp:", d),+ }+ }++ fn term(t: &Term) -> String {+ match t {+ Term::Var(n) => format!("X{n}"),+ Term::Const(a) => quoted("i:", a),+ }+ }++ /// True when the rendering is already a TPTP unitary formula and so needs+ /// no extra bracket under `~` or after a quantifier's colon.+ ///+ /// The binary connectives qualify because [`form`] brackets them itself.+ /// `Eq`, `Neg` and the quantifiers do not: `~ ~ p` is not legal TPTP,+ /// unary connectives being non-associative, and an unbracketed `X0 = X1`+ /// under a `~` is likewise not a unit formula.+ fn already_unit(f: &Form) -> bool {+ matches!(+ f,+ Form::App1(..)+ | Form::App2(..)+ | Form::Tru+ | Form::Fls+ | Form::And(..)+ | Form::Or(..)+ | Form::Imp(..)+ )+ }++ fn unit(f: &Form) -> String {+ if already_unit(f) {+ form(f)+ } else {+ format!("({})", form(f))+ }+ }++ /// Render a formula. Compound connectives are fully bracketed, which keeps+ /// the output independent of any reader's precedence table.+ pub fn form(f: &Form) -> String {+ match f {+ Form::App1(p, t) => format!("{}({})", p1(p), term(t)),+ Form::App2(p, t, u) => format!("{}({},{})", p2(p), term(t), term(u)),+ Form::Eq(t, u) => format!("{} = {}", term(t), term(u)),+ Form::Tru => "$true".to_string(),+ Form::Fls => "$false".to_string(),+ Form::Neg(g) => format!("~ {}", unit(g)),+ Form::And(g, h) => format!("({} & {})", form(g), form(h)),+ Form::Or(g, h) => format!("({} | {})", form(g), form(h)),+ Form::Imp(g, h) => format!("({} => {})", form(g), form(h)),+ Form::All(n, g) => format!("! [X{n}] : {}", unit(g)),+ Form::Ex(n, g) => format!("? [X{n}] : {}", unit(g)),+ }+ }+}++// ── Serialiser 2: ISO/IEC 24707 CLIF ────────────────────────────────────────++/// Which spelling of the Common Logic operators to emit.+///+/// This is not a style choice. Two spellings are in circulation and the two+/// main consumers disagree, so a file in one dialect is unreadable to half the+/// ecosystem.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ClifDialect {+ /// `cl:text`, `cl:comment`.+ ///+ /// The spelling in ISO/IEC 24707's own reserved-token list, and what ISO+ /// publishes the BFO axiomatisation in.+ Iso,+ /// `cl-text`, `cl-comment`.+ ///+ /// What the COLORE repository is written in and what the Macleod+ /// toolchain's shipped lexer maps; `src/macleod/parsing/parser.py` has the+ /// colon spellings present and commented out.+ Colore,+}++/// Where a formula's label goes.+///+/// This is not cosmetic. It decides whether the file has any content a reader+/// can recover, and the measurement is in `docs/first-order-export.md`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ClifComments {+ /// A standalone `(cl:comment '...')` phrase, then the sentence on its own.+ ///+ /// The default, because it is the only shape either available CLIF parser+ /// gives back any content from. py-typedlogic treats a `(cl:comment ...)`+ /// form as discardable, so a file whose sentences are all inside one+ /// parses cleanly and yields ZERO sentences; Macleod has no+ /// commented-sentence production at all. A file that is formally valid and+ /// practically empty is the assurance-laundering shape this project exists+ /// to attack, so it is not the default here.+ Standalone,+ /// `(cl:comment '...' SENTENCE)`, the shape ISO/IEC 21838-2's BFO files+ /// use.+ ///+ /// Off by default. Correct CLIF, and unreadable by both parsers that exist+ /// today, including on BFO's own files.+ Wrapped,+}++impl ClifComments {+ pub fn parse(s: &str) -> anyhow::Result<ClifComments> {+ match s.to_ascii_lowercase().as_str() {+ "standalone" | "separate" => Ok(ClifComments::Standalone),+ "wrapped" | "bfo" => Ok(ClifComments::Wrapped),+ other => anyhow::bail!(+ "unknown CLIF comment placement {other:?}; expected `standalone` (the \+ default, the only shape either available parser recovers sentences from) \+ or `wrapped` (what BFO uses, and what both parsers read as empty)"+ ),+ }+ }+ pub fn name(self) -> &'static str {+ match self {+ ClifComments::Standalone => "standalone",+ ClifComments::Wrapped => "wrapped",+ }+ }+}++impl ClifDialect {+ pub fn parse(s: &str) -> anyhow::Result<ClifDialect> {+ match s.to_ascii_lowercase().as_str() {+ "iso" | "iso24707" | "colon" => Ok(ClifDialect::Iso),+ "colore" | "macleod" | "hyphen" => Ok(ClifDialect::Colore),+ other => anyhow::bail!(+ "unknown CLIF dialect {other:?}; expected `iso` (cl:text, what ISO/IEC \+ 21838-2 publishes) or `colore` (cl-text, what COLORE and Macleod read)"+ ),+ }+ }+ fn text_op(self) -> &'static str {+ match self {+ ClifDialect::Iso => "cl:text",+ ClifDialect::Colore => "cl-text",+ }+ }+ fn comment_op(self) -> &'static str {+ match self {+ ClifDialect::Iso => "cl:comment",+ ClifDialect::Colore => "cl-comment",+ }+ }+ pub fn name(self) -> &'static str {+ match self {+ ClifDialect::Iso => "iso",+ ClifDialect::Colore => "colore",+ }+ }+}++/// CLIF rendering of [`Form`], restricted to the first-order-equivalent+/// fragment of Common Logic.+///+/// Common Logic is not first-order logic: it has sequence markers, arity-free+/// predicates, and a single universe in which relations are themselves+/// individuals. The adequacy theorem is about a translation into PLAIN+/// first-order logic, so the emitted text stays inside the fragment where the+/// two coincide:+///+/// * no sequence markers (`...x`), which are what actually take Common Logic+/// past first order: clause 6.5 of ISO/IEC 24707 states that a logic with+/// them is not compact and therefore not first-order,+/// * fixed arity everywhere: `thing` and `lit` and every class and datatype at+/// arity one, every property at arity two, always. Arity-freedom alone does+/// not escape first-order logic (clause 6.6.1 gives the de-punning+/// reduction), but fixing arity is what makes the text expressible in TPTP+/// FOF at all,+/// * no quantification into a predicate position: every bound variable occurs+/// only as an argument.+///+/// [`Form`] cannot express any of the three, which is the structural reason+/// the restriction holds. `clif_uses_only_fol_fragment` in+/// `tests/fol_translation_correspondence_test.rs` is the check that it still+/// does.+pub mod clif {+ use super::{ClifDialect, Form, P1, P2, Term};++ /// Names are written as CLIF **enclosed names**, delimited by DOUBLE+ /// QUOTES, with `"` and `\` escaped.+ ///+ /// Not vertical bars. ISO/IEC 24707 A.2.2.2 sets `namequote = '"'`, and+ /// A.2.2.4 recommends the enclosed-name syntax specifically for writing+ /// IRIs as names. The vertical bar is an ordinary name character in CLIF+ /// (it is in the `char` production), so `|x|` would lex as a bare name+ /// containing two pipes and would not protect a slash or a colon. The+ /// bar convention belongs to Common Lisp and to KIF, not to CLIF.+ ///+ /// The kind prefixes are the TPTP serialiser's, for the same reason:+ /// `OwlP1` and `OwlP2` are disjoint sums in the Lean.+ fn enclosed(prefix: &str, iri: &str) -> String {+ let mut s = String::with_capacity(iri.len() + prefix.len() + 4);+ s.push('"');+ s.push_str(prefix);+ for ch in iri.chars() {+ if ch == '\\' || ch == '"' {+ s.push('\\');+ }+ s.push(ch);+ }+ s.push('"');+ s+ }++ /// A comment string, in SINGLE quotes, with `\\` and `'` escaped.+ ///+ /// ISO/IEC 24707 A.2.2.2 makes the single quote the string delimiter+ /// (`stringquote`) and the double quote the enclosed-name delimiter+ /// (`namequote`), so a comment's text is a quoted string and takes single+ /// quotes. This exporter emitted double quotes until it was measured: the+ /// CLIF files ISO hosts for ISO/IEC 21838-2 carry 369 double-quoted+ /// `cl:comment` forms, and BFO's own release notes of 7 December 2025+ /// retract exactly that, saying "Comment texts are surrounded by single,+ /// not double quotes". BFO master has 356 single-quoted and none+ /// double-quoted. Matching the corpus was the wrong test; the corpus had+ /// been withdrawn by its maintainers.+ ///+ /// The quote style does NOT vary with the dialect. Binding the two+ /// together meant no combination of flags could emit conforming CLIF.+ pub fn comment_string(text: &str) -> String {+ let mut s = String::with_capacity(text.len() + 2);+ s.push('\'');+ for ch in text.chars() {+ if ch == '\\' || ch == '\'' {+ s.push('\\');+ }+ s.push(ch);+ }+ s.push('\'');+ s+ }++ /// A text name. Bare when the IRI has no character that would break a+ /// name token, and a double-quoted enclosed name otherwise.+ ///+ /// Bare is preferred because both available parsers accept it and name the+ /// theory correctly, while Macleod's lexer has no double-quote token at+ /// all. CLIF's `char` production admits `:` and `/`, and COLORE names all+ /// 227 of its texts with a bare IRI.+ pub fn text_name(iri: &str) -> String {+ let safe = !iri.is_empty()+ && !iri+ .chars()+ .any(|c| c.is_whitespace() || matches!(c, '(' | ')' | '\'' | '"' | '|'));+ if safe {+ iri.to_string()+ } else {+ let mut s = String::from("\"");+ for ch in iri.chars() {+ if ch == '\\' || ch == '"' {+ s.push('\\');+ }+ s.push(ch);+ }+ s.push('"');+ s+ }+ }++ /// A standalone `(cl:comment '...')` phrase.+ ///+ /// Lexical comments are not used anywhere in the emitted text: ISO/IEC+ /// 24707 defines `cl:comment` as a reserved element, whereas a `//` or+ /// `/* */` line comment is a convention this project could not establish+ /// from the standard's own text.+ pub fn standalone_comment(dialect: ClifDialect, label: &str) -> String {+ format!("({} {})", dialect.comment_op(), comment_string(label))+ }++ /// `(cl:comment '...' SENTENCE)`, the shape BFO uses.+ ///+ /// Correct CLIF and, measured, unreadable: py-typedlogic discards the form+ /// and returns an empty theory, and Macleod has no production for it. It+ /// does the same to BFO's own files. Reachable only through+ /// `ClifComments::Wrapped`, which is not the default.+ pub fn commented(dialect: ClifDialect, label: &str, f: &Form) -> String {+ format!(+ "({} {} {})",+ dialect.comment_op(),+ comment_string(label),+ form(f)+ )+ }++ fn p1(p: &P1) -> String {+ match p {+ P1::Cls(a) => enclosed("c:", a),+ P1::Dt(d) => enclosed("d:", d),+ P1::Thing => "thing".to_string(),+ P1::Lit => "lit".to_string(),+ }+ }++ fn p2(p: &P2) -> String {+ match p {+ P2::Op(r) => enclosed("op:", r),+ P2::Dp(d) => enclosed("dp:", d),+ }+ }++ fn term(t: &Term) -> String {+ match t {+ Term::Var(n) => format!("X{n}"),+ Term::Const(a) => enclosed("i:", a),+ }+ }++ /// Render a formula.+ ///+ /// `(and)` and `(or)` with no arguments are truth and falsity: CLIF's+ /// boolean sentence takes zero or more arguments and defines no truth+ /// constants of its own.+ pub fn form(f: &Form) -> String {+ match f {+ Form::App1(p, t) => format!("({} {})", p1(p), term(t)),+ Form::App2(p, t, u) => format!("({} {} {})", p2(p), term(t), term(u)),+ Form::Eq(t, u) => format!("(= {} {})", term(t), term(u)),+ Form::Tru => "(and)".to_string(),+ Form::Fls => "(or)".to_string(),+ Form::Neg(g) => format!("(not {})", form(g)),+ Form::And(g, h) => format!("(and {} {})", form(g), form(h)),+ Form::Or(g, h) => format!("(or {} {})", form(g), form(h)),+ Form::Imp(g, h) => format!("(if {} {})", form(g), form(h)),+ Form::All(n, g) => format!("(forall (X{n}) {})", form(g)),+ Form::Ex(n, g) => format!("(exists (X{n}) {})", form(g)),+ }+ }+}++// ── Reading an ontology out of the graph ────────────────────────────────────++const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";+const RDF_FIRST: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#first";+const RDF_REST: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest";+const RDF_NIL: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil";+const RDFS_SUBCLASS: &str = "http://www.w3.org/2000/01/rdf-schema#subClassOf";+const RDFS_SUBPROP: &str = "http://www.w3.org/2000/01/rdf-schema#subPropertyOf";+const RDFS_DOMAIN: &str = "http://www.w3.org/2000/01/rdf-schema#domain";+const RDFS_RANGE: &str = "http://www.w3.org/2000/01/rdf-schema#range";+const RDFS_DATATYPE: &str = "http://www.w3.org/2000/01/rdf-schema#Datatype";+const OWL: &str = "http://www.w3.org/2002/07/owl#";++fn owl(local: &str) -> String {+ format!("{OWL}{local}")+}++/// A construct present in the graph and absent from the export, with the count+/// and the reason.+///+/// The description says why, not merely that. An ontology whose unexported+/// constructs are invisible is a trap; the description-logic layer already+/// carries `certifies_a_weaker_axiom_set` for the same reason.+#[derive(Debug, Clone, serde::Serialize)]+pub struct Dropped {+ pub construct: String,+ pub occurrences: u64,+ pub why: String,+}++/// A construct rewritten into the fragment before translation, exactly and at+/// the OWL level.+///+/// These are not translation choices. `EquivalentObjectProperties(p q)` is+/// `SubObjectPropertyOf(p q)` and `SubObjectPropertyOf(q p)` under the Direct+/// Semantics, and `AllDisjointClasses` is its pairwise expansion. Listing them+/// keeps the difference between "the fragment covers this" and "the fragment+/// covers a rewriting of this" visible to a reader of the report.+#[derive(Debug, Clone, serde::Serialize)]+pub struct Reduced {+ pub construct: String,+ pub occurrences: u64,+ pub how: String,+}++/// What the reader made of the graph.+pub struct ReadOntology {+ pub axioms: Vec<OwlAxiom>,+ pub dropped: Vec<Dropped>,+ pub reduced: Vec<Reduced>,+ /// Properties whose entity kind was not declared and had to be inferred.+ pub inferred_object_properties: Vec<String>,+ pub inferred_data_properties: Vec<String>,+ /// Terms the reader treated as datatypes rather than as classes.+ ///+ /// `OwlP1` separates `cls` from `dt`, so `c:xsd:anyURI` and `d:xsd:anyURI`+ /// are unrelated predicates. More to the point, `OwlLean/Syntax.lean` has+ /// no axiom form asserting that an individual belongs to a DATATYPE:+ /// `classAssert` takes a `Concept`, and no `Concept` constructor denotes+ /// datatype membership. A goal of that shape has to be refused rather than+ /// translated as a class assertion under a symbol occurring in no axiom.+ pub datatypes: BTreeSet<String>,+ /// Properties the reader treated as object properties, and as data+ /// properties, declarations and inferences together.+ ///+ /// A goal must be built with the SAME symbols the axioms use. `OwlP2` is a+ /// disjoint sum, so `op:p` and `dp:p` are unrelated predicates, and a+ /// conjecture that picked the wrong arm would ask about a symbol occurring+ /// in no axiom. The prover would answer CounterSatisfiable, correctly, and+ /// the report would read as a disagreement with the engine when it was a+ /// defect in the question.+ pub object_properties: BTreeSet<String>,+ pub data_properties: BTreeSet<String>,+ /// Literal-valued triples whose predicate is an annotation property.+ /// Ignoring these does not weaken the axiom set, because an annotation has+ /// no Direct Semantics content. Reported so that is a stated fact rather+ /// than a silent omission.+ pub annotations_ignored: u64,+ /// Class expressions that are not named classes, keyed by the node that+ /// carries them.+ ///+ /// A derived triple can name one: `rdfs9` concludes `x rdf:type _:b` where+ /// `_:b` is a restriction. Without this map the conjecture would be built+ /// over an atomic class symbol that occurs nowhere in the axioms, and the+ /// prover would report no verdict on a question nobody meant to ask. That+ /// is worse than refusing the goal, because it reads as a limitation of+ /// the prover rather than as a defect here.+ pub anonymous_classes: BTreeMap<String, Concept>,+}++/// Maximum cardinality the export will expand.+///+/// `minCard n` emits `n(n-1)/2` distinctness literals and `n` guarded+/// existentials, so a four-figure cardinality is a file no prover will read.+/// Anything above the cap is DROPPED AND NAMED rather than truncated.+const MAX_CARDINALITY: u32 = 25;++/// The CLIF text name used when the source declares no `owl:Ontology` IRI.+///+/// Named rather than left anonymous: all 227 COLORE texts carry a name,+/// Macleod refuses an unnamed text with "Error in ontology: bad URI", and+/// py-typedlogic otherwise takes the first comment for the theory's name.+const UNNAMED_TEXT: &str = "http://open-ontologies.org/fol/unnamed-export";++struct Reader {+ /// subject -> [(predicate, object)]+ by_subject: BTreeMap<String, Vec<(String, String)>>,+ object_properties: BTreeSet<String>,+ data_properties: BTreeSet<String>,+ annotation_properties: BTreeSet<String>,+ classes: BTreeSet<String>,+ annotations_ignored: u64,+ dropped: BTreeMap<String, (u64, String)>,+ reduced: BTreeMap<String, (u64, String)>,+ inferred_object: BTreeSet<String>,+ inferred_data: BTreeSet<String>,+}++/// Strip the N-Triples spelling oxigraph hands back: `<iri>` becomes `iri`,+/// `_:b0` and literals are left as they are.+fn bare(term: &str) -> &str {+ if term.len() >= 2 && term.starts_with('<') && term.ends_with('>') {+ &term[1..term.len() - 1]+ } else {+ term+ }+}++fn is_iri(term: &str) -> bool {+ term.starts_with('<') && term.ends_with('>')+}++fn is_literal(term: &str) -> bool {+ term.starts_with('"')+}++impl Reader {+ fn new(triples: Vec<(String, String, String)>) -> Reader {+ let mut by_subject: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();+ for (s, p, o) in triples {+ by_subject.entry(s).or_default().push((p, o));+ }+ let mut r = Reader {+ by_subject,+ object_properties: BTreeSet::new(),+ data_properties: BTreeSet::new(),+ annotation_properties: BTreeSet::new(),+ classes: BTreeSet::new(),+ annotations_ignored: 0,+ dropped: BTreeMap::new(),+ reduced: BTreeMap::new(),+ inferred_object: BTreeSet::new(),+ inferred_data: BTreeSet::new(),+ };+ r.collect_declarations();+ r+ }++ fn objects(&self, s: &str, p: &str) -> Vec<&str> {+ self.by_subject+ .get(s)+ .map(|ps| {+ ps.iter()+ .filter(|(q, _)| bare(q) == p)+ .map(|(_, o)| o.as_str())+ .collect()+ })+ .unwrap_or_default()+ }++ fn object(&self, s: &str, p: &str) -> Option<&str> {+ self.objects(s, p).into_iter().next()+ }++ fn has_type(&self, s: &str, ty: &str) -> bool {+ self.objects(s, RDF_TYPE).iter().any(|o| bare(o) == ty)+ }++ fn drop(&mut self, construct: &str, why: &str) {+ let e = self+ .dropped+ .entry(construct.to_string())+ .or_insert((0, why.to_string()));+ e.0 += 1;+ }++ fn reduce(&mut self, construct: &str, how: &str) {+ let e = self+ .reduced+ .entry(construct.to_string())+ .or_insert((0, how.to_string()));+ e.0 += 1;+ }++ fn collect_declarations(&mut self) {+ let subjects: Vec<String> = self.by_subject.keys().cloned().collect();+ for s in subjects {+ let bare_s = bare(&s).to_string();+ if self.has_type(&s, &owl("ObjectProperty")) {+ self.object_properties.insert(bare_s.clone());+ }+ if self.has_type(&s, &owl("DatatypeProperty")) {+ self.data_properties.insert(bare_s.clone());+ }+ if self.has_type(&s, &owl("AnnotationProperty")) {+ self.annotation_properties.insert(bare_s.clone());+ }+ // A property characteristic implies an OBJECT property only when+ // nothing has declared the property a data property. FOAF declares+ // `foaf:msnChatID` as `owl:DatatypeProperty` AND+ // `owl:InverseFunctionalProperty`, which OWL 2 DL forbids and+ // RDF-serialised vocabularies do anyway. Letting the characteristic+ // win made the axioms speak about `op:msnChatID` while every goal+ // about it spoke about `dp:msnChatID`, and the differential+ // reported six disagreements that were entirely this.+ if !self.data_properties.contains(&bare_s) {+ for extra in [+ "TransitiveProperty",+ "SymmetricProperty",+ "AsymmetricProperty",+ "ReflexiveProperty",+ "IrreflexiveProperty",+ "InverseFunctionalProperty",+ ] {+ if self.has_type(&s, &owl(extra)) {+ self.object_properties.insert(bare_s.clone());+ }+ }+ }+ if self.has_type(&s, &owl("Class")) || self.has_type(&s, &owl("Restriction")) {+ self.classes.insert(bare_s.clone());+ }+ }+ // An IRI declared BOTH `owl:ObjectProperty` and `owl:DatatypeProperty`+ // is outside OWL 2 DL, which forbids that overlap. `Sig` keeps the+ // kinds apart as distinct types, so there is no reading of such a+ // property that the fragment supports: it would have to be `op:p` and+ // `dp:p` at once, and those are unrelated predicates. The data+ // declaration is taken and the conflict is recorded, because a silent+ // choice between two declarations is the kind of thing that later+ // looks like a reasoning bug.+ let punned = self+ .object_properties+ .intersection(&self.data_properties)+ .count() as u64;+ if punned > 0 {+ let e = self+ .dropped+ .entry("property declared both object and data".to_string())+ .or_insert((+ 0,+ "OWL 2 DL forbids the overlap and OwlLean.Sig keeps OProp and DProp \+ apart as distinct types, so no single symbol can carry both readings. \+ The data declaration is used and the object reading is not exported"+ .to_string(),+ ));+ e.0 += punned;+ let both: Vec<String> = self+ .object_properties+ .intersection(&self.data_properties)+ .cloned()+ .collect();+ for p in both {+ self.object_properties.remove(&p);+ }+ }+ }++ /// Is this node a datatype? Declared `rdfs:Datatype`, or a member of the+ /// two families every ontology uses without declaring.+ ///+ /// The goal builder in `triple_as_axiom` asks the same question of the+ /// `datatypes` set this reader publishes, so the axioms and the conjectures+ /// cannot disagree about which symbol a term gets.+ fn is_datatype_node(&self, node: &str) -> bool {+ let b = bare(node);+ b.starts_with("http://www.w3.org/2001/XMLSchema#")+ || b == "http://www.w3.org/2000/01/rdf-schema#Literal"+ || b == "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"+ || self.has_type(node, RDFS_DATATYPE)+ }++ /// Is this property an object property? Declarations win; an undeclared+ /// property is classified by whether it ever takes a literal object, and+ /// every such inference is reported.+ fn is_object_property(&mut self, p: &str) -> bool {+ if self.object_properties.contains(p) {+ return true;+ }+ if self.data_properties.contains(p) {+ return false;+ }+ let has_literal_object = self+ .by_subject+ .values()+ .flatten()+ .any(|(q, o)| bare(q) == p && is_literal(o));+ if has_literal_object {+ self.inferred_data.insert(p.to_string());+ false+ } else {+ self.inferred_object.insert(p.to_string());+ true+ }+ }++ /// Walk an `rdf:first`/`rdf:rest` chain.+ ///+ /// Strict, as decision 0002 requires of the reasoner's list walk: every+ /// node must carry both, and the chain must reach `rdf:nil`. A list that+ /// does not is `None`, and the caller drops the axiom and names it.+ /// Deriving less from malformed input is the sound direction.+ fn list(&self, head: &str) -> Option<Vec<String>> {+ let mut out = Vec::new();+ let mut node = head.to_string();+ let mut seen = BTreeSet::new();+ loop {+ if bare(&node) == RDF_NIL {+ return Some(out);+ }+ if !seen.insert(node.clone()) {+ return None; // cyclic rest chain+ }+ let first = self.object(&node, RDF_FIRST)?.to_string();+ let rest = self.object(&node, RDF_REST)?.to_string();+ out.push(first);+ node = rest;+ }+ }++ /// Read a class expression. `None` means outside the fragment; the reason+ /// has already been recorded.+ fn concept(&mut self, node: &str) -> Option<Concept> {+ if is_literal(node) {+ self.drop(+ "literal in class position",+ "a literal is not a class expression",+ );+ return None;+ }+ let b = bare(node).to_string();+ if b == owl("Thing") {+ return Some(Concept::Top);+ }+ if b == owl("Nothing") {+ return Some(Concept::Bot);+ }+ if self.is_datatype_node(node) {+ // `OwlP1` separates `cls` from `dt`, and no `Concept` constructor+ // denotes membership of a datatype. Reading `X rdf:type xsd:anyURI`+ // as a CLASS assertion would put an axiom in the file that the+ // ontology does not state, which is the unsound direction: a+ // weakening is safe and an addition is not.+ self.drop(+ "datatype in a class position",+ "OwlLean/Syntax.lean has no Concept constructor for membership of a \+ datatype, and OwlP1 keeps cls and dt apart, so this cannot be read as \+ a class without inventing an axiom",+ );+ return None;+ }+ if b == owl("topObjectProperty") || b == owl("bottomObjectProperty") {+ self.drop(+ "owl:topObjectProperty / owl:bottomObjectProperty",+ "fixed-interpretation properties; OwlLean/Syntax.lean has no constructor \+ for them and treating them as ordinary names would lose their semantics",+ );+ return None;+ }++ // Restriction+ if self.has_type(node, &owl("Restriction")) {+ return self.restriction(node);+ }++ // Boolean and enumeration constructors+ if let Some(l) = self.object(node, &owl("intersectionOf")).map(str::to_string) {+ if self.has_type(node, RDFS_DATATYPE) {+ self.drop(+ "owl:intersectionOf on a datatype",+ "OwlLean/Syntax.lean has no datatype-expression layer; only named \+ datatypes appear, via dataSome / dataAll / dPropRange",+ );+ return None;+ }+ let items = match self.list(&l) {+ Some(i) => i,+ None => {+ self.drop(+ "owl:intersectionOf with a malformed list",+ "a node missing rdf:first or rdf:rest, or a chain not reaching \+ rdf:nil; deriving less from malformed input is the sound direction",+ );+ return None;+ }+ };+ return self.fold_boolean(&items, true);+ }+ if let Some(l) = self.object(node, &owl("unionOf")).map(str::to_string) {+ if self.has_type(node, RDFS_DATATYPE) {+ self.drop(+ "owl:unionOf on a datatype",+ "OwlLean/Syntax.lean has no datatype-expression layer",+ );+ return None;+ }+ let items = match self.list(&l) {+ Some(i) => i,+ None => {+ self.drop("owl:unionOf with a malformed list", "see above");+ return None;+ }+ };+ return self.fold_boolean(&items, false);+ }+ if let Some(c) = self.object(node, &owl("complementOf")).map(str::to_string) {+ if self.has_type(node, RDFS_DATATYPE) {+ self.drop(+ "owl:datatypeComplementOf / complementOf on a datatype",+ "no datatype-expression layer in the fragment",+ );+ return None;+ }+ return Some(Concept::Compl(Box::new(self.concept(&c)?)));+ }+ if let Some(l) = self.object(node, &owl("oneOf")).map(str::to_string) {+ if self.has_type(node, RDFS_DATATYPE) {+ self.drop(+ "owl:oneOf on a datatype (a data enumeration)",+ "Concept.oneOf ranges over individuals, not literals",+ );+ return None;+ }+ let items = match self.list(&l) {+ Some(i) => i,+ None => {+ self.drop("owl:oneOf with a malformed list", "see above");+ return None;+ }+ };+ if items.iter().any(|i| is_literal(i)) {+ self.drop(+ "owl:oneOf containing a literal",+ "Concept.oneOf ranges over individuals, not literals",+ );+ return None;+ }+ return Some(Concept::OneOf(+ items.iter().map(|i| bare(i).to_string()).collect(),+ ));+ }++ if is_iri(node) || node.starts_with("_:") {+ return Some(Concept::Atom(b));+ }+ self.drop("unreadable class position", "neither an IRI nor a blank node");+ None+ }++ fn fold_boolean(&mut self, items: &[String], intersection: bool) -> Option<Concept> {+ let mut parts = Vec::with_capacity(items.len());+ for i in items {+ parts.push(self.concept(i)?);+ }+ // An n-ary constructor folds RIGHT, so `and [a,b,c]` is+ // `Inter a (Inter b c)`, matching the shape of `Form::conj`.+ let mut it = parts.into_iter().rev();+ let mut acc = it.next()?;+ for p in it {+ acc = if intersection {+ Concept::Inter(Box::new(p), Box::new(acc))+ } else {+ Concept::Union(Box::new(p), Box::new(acc))+ };+ }+ Some(acc)+ }++ fn cardinality(&mut self, node: &str, pred: &str) -> Option<u32> {+ let raw = self.object(node, &owl(pred))?.to_string();+ // A typed literal arrives as `"2"^^<...integer>`.+ let digits: String = raw+ .trim_start_matches('"')+ .chars()+ .take_while(|c| c.is_ascii_digit())+ .collect();+ let n: u32 = match digits.parse() {+ Ok(n) => n,+ Err(_) => {+ self.drop(+ "cardinality that is not a non-negative integer",+ "the restriction is unreadable, so it is not exported",+ );+ return None;+ }+ };+ if n > MAX_CARDINALITY {+ self.drop(+ "cardinality above the expansion cap",+ &format!(+ "minCard n emits n(n-1)/2 distinctness literals; the cap is {MAX_CARDINALITY} \+ and this restriction is dropped rather than truncated"+ ),+ );+ return None;+ }+ Some(n)+ }++ fn restriction(&mut self, node: &str) -> Option<Concept> {+ let prop = match self.object(node, &owl("onProperty")).map(str::to_string) {+ Some(p) => p,+ None => {+ self.drop(+ "owl:Restriction with no owl:onProperty",+ "not a well-formed restriction",+ );+ return None;+ }+ };+ if !is_iri(&prop) {+ // `owl:onProperty [ owl:inverseOf p ]`: Concept.some_ takes an+ // S.OProp and not an OPE, so an inverse property expression inside+ // a restriction is outside the fragment.+ self.drop(+ "restriction on an inverse property expression",+ "Concept.some_ / all_ / minCard / maxCard take a named property \+ (S.OProp), not an OPE, in OwlLean/Syntax.lean",+ );+ return None;+ }+ let p = bare(&prop).to_string();+ let is_obj = self.is_object_property(&p);++ if let Some(f) = self.object(node, &owl("someValuesFrom")).map(str::to_string) {+ return if is_obj {+ Some(Concept::Some_(p, Box::new(self.concept(&f)?)))+ } else {+ Some(Concept::DataSome(p, bare(&f).to_string()))+ };+ }+ if let Some(f) = self.object(node, &owl("allValuesFrom")).map(str::to_string) {+ return if is_obj {+ Some(Concept::All_(p, Box::new(self.concept(&f)?)))+ } else {+ Some(Concept::DataAll(p, bare(&f).to_string()))+ };+ }+ if let Some(val) = self.object(node, &owl("hasValue")).map(str::to_string) {+ if !is_obj || is_literal(&val) {+ self.drop(+ "owl:hasValue on a data property",+ "Concept.hasVal takes an S.OProp and an S.Ind; a literal value is \+ outside the fragment",+ );+ return None;+ }+ return Some(Concept::HasVal(p, bare(&val).to_string()));+ }+ if let Some(val) = self.object(node, &owl("hasSelf")).map(str::to_string) {+ if val.starts_with("\"true\"") {+ return Some(Concept::HasSelf(p));+ }+ self.drop(+ "owl:hasSelf with a value other than true",+ "only the self-restriction is in the fragment",+ );+ return None;+ }+ if self.object(node, &owl("onDataRange")).is_some() {+ self.drop(+ "data cardinality restriction (owl:onDataRange)",+ "OwlLean/Syntax.lean has minCard / maxCard on object properties only",+ );+ return None;+ }+ if !is_obj+ && ["minCardinality", "maxCardinality", "cardinality"]+ .iter()+ .any(|c| self.object(node, &owl(c)).is_some())+ {+ self.drop(+ "cardinality restriction on a data property",+ "OwlLean/Syntax.lean has minCard / maxCard on object properties only",+ );+ return None;+ }++ // Qualified forms first: `owl:onClass` is what distinguishes them.+ let on_class = self.object(node, &owl("onClass")).map(str::to_string);+ let filler = match &on_class {+ Some(c) => self.concept(&c.clone())?,+ None => Concept::Top,+ };++ for (pred, qualified) in [+ ("minQualifiedCardinality", true),+ ("minCardinality", false),+ ] {+ if self.object(node, &owl(pred)).is_some() {+ if qualified && on_class.is_none() {+ self.drop(+ "owl:minQualifiedCardinality with no owl:onClass",+ "not a well-formed qualified restriction",+ );+ return None;+ }+ let n = self.cardinality(node, pred)?;+ return Some(Concept::MinCard(n, p, Box::new(filler)));+ }+ }+ for (pred, qualified) in [+ ("maxQualifiedCardinality", true),+ ("maxCardinality", false),+ ] {+ if self.object(node, &owl(pred)).is_some() {+ if qualified && on_class.is_none() {+ self.drop(+ "owl:maxQualifiedCardinality with no owl:onClass",+ "not a well-formed qualified restriction",+ );+ return None;+ }+ let n = self.cardinality(node, pred)?;+ return Some(Concept::MaxCard(n, p, Box::new(filler)));+ }+ }+ for pred in ["qualifiedCardinality", "cardinality"] {+ if self.object(node, &owl(pred)).is_some() {+ let n = self.cardinality(node, pred)?;+ self.reduce(+ "exact cardinality",+ "expanded as Inter (minCard n) (maxCard n), which is what the \+ owl-lean fragment note means by \"yes, as min+max\"",+ );+ return Some(Concept::Inter(+ Box::new(Concept::MinCard(n, p.clone(), Box::new(filler.clone()))),+ Box::new(Concept::MaxCard(n, p, Box::new(filler))),+ ));+ }+ }++ self.drop(+ "owl:Restriction with no recognised constraint",+ "carries owl:onProperty but none of someValuesFrom, allValuesFrom, \+ hasValue, hasSelf or a cardinality",+ );+ None+ }++ /// Split the literal-valued triples into genuine data property assertions+ /// and annotations.+ ///+ /// An annotation property is one declared `owl:AnnotationProperty`, or one+ /// of the vocabulary terms the OWL 2 Structural Specification fixes as+ /// built-in annotation properties, or a term from the usual annotation+ /// vocabularies. The distinction matters because only the first kind is a+ /// weakening of the axiom set.+ fn count_literal_triples(&self) -> (u64, u64) {+ const BUILT_IN: [&str; 9] = [+ "http://www.w3.org/2000/01/rdf-schema#label",+ "http://www.w3.org/2000/01/rdf-schema#comment",+ "http://www.w3.org/2000/01/rdf-schema#seeAlso",+ "http://www.w3.org/2000/01/rdf-schema#isDefinedBy",+ "http://www.w3.org/2002/07/owl#versionInfo",+ "http://www.w3.org/2002/07/owl#deprecated",+ "http://www.w3.org/2002/07/owl#backwardCompatibleWith",+ "http://www.w3.org/2002/07/owl#incompatibleWith",+ "http://www.w3.org/2002/07/owl#priorVersion",+ ];+ const PREFIXES: [&str; 4] = [+ "http://www.w3.org/2004/02/skos/core#",+ "http://purl.org/dc/elements/1.1/",+ "http://purl.org/dc/terms/",+ "http://www.w3.org/ns/prov#",+ ];+ let (mut data, mut anno) = (0u64, 0u64);+ for (p, o) in self.by_subject.values().flatten() {+ if !is_literal(o) {+ continue;+ }+ let bp = bare(p);+ let is_anno = self.annotation_properties.contains(bp)+ || BUILT_IN.contains(&bp)+ || PREFIXES.iter().any(|pre| bp.starts_with(pre));+ if is_anno {+ anno += 1;+ } else {+ data += 1;+ }+ }+ (data, anno)+ }++ /// Constructs that have no place in the fragment at all. Counted by+ /// scanning for the predicate or the class, the same shape as+ /// `DlReasoner::unmodelled_constructs`.+ fn count_out_of_fragment(&mut self) {+ const OUT: [(&str, &str, &str); 6] = [+ (+ "owl:hasKey",+ "hasKey",+ "no constructor in OwlLean/Syntax.lean; measured at 4.3% of constrained \+ ontologies and excluded from the fragment on that measurement",+ ),+ (+ "owl:withRestrictions",+ "withRestrictions",+ "datatype facets need the OWL 2 datatype map, which is a front end concern \+ owl-lean has not started",+ ),+ (+ "owl:onDatatype",+ "onDatatype",+ "datatype facets; see owl:withRestrictions",+ ),+ (+ "owl:datatypeComplementOf",+ "datatypeComplementOf",+ "no datatype-expression layer in the fragment",+ ),+ (+ "owl:NegativePropertyAssertion",+ "NegativePropertyAssertion",+ "no constructor in OwlLean/Syntax.lean",+ ),+ (+ "owl:AllDisjointProperties",+ "AllDisjointProperties",+ "reduced to pairwise owl:propertyDisjointWith where every member is a \+ declared object property, dropped otherwise",+ ),+ ];+ let mut counts: BTreeMap<&str, u64> = BTreeMap::new();+ for (s, ps) in &self.by_subject {+ for (p, o) in ps {+ for (label, local, _) in OUT {+ let iri = owl(local);+ if bare(p) == iri || bare(o) == iri || bare(s) == iri {+ *counts.entry(label).or_default() += 1;+ }+ }+ }+ }+ for (label, _, why) in OUT {+ if let Some(n) = counts.get(label) {+ let e = self+ .dropped+ .entry(label.to_string())+ .or_insert((0, why.to_string()));+ e.0 += n;+ }+ }+ }++ fn read(mut self) -> ReadOntology {+ let mut axioms = Vec::new();+ let subjects: Vec<String> = self.by_subject.keys().cloned().collect();++ for s in &subjects {+ let pairs = self.by_subject.get(s).cloned().unwrap_or_default();+ let bare_s = bare(s).to_string();++ for (p, o) in &pairs {+ let bp = bare(p).to_string();+ let bo = bare(o).to_string();++ match bp.as_str() {+ RDFS_SUBCLASS => {+ if let (Some(c), Some(d)) =+ (self.concept(s), self.concept(o))+ {+ axioms.push(OwlAxiom::SubClass(c, d));+ }+ }+ RDFS_SUBPROP => {+ let so = self.is_object_property(&bare_s);+ let oo = is_iri(o) && self.is_object_property(&bo);+ if so && oo {+ axioms.push(OwlAxiom::SubOProp(+ Ope::Named(bare_s.clone()),+ Ope::Named(bo.clone()),+ ));+ } else {+ self.drop(+ "rdfs:subPropertyOf outside the object-property case",+ "OwlLean/Syntax.lean's subOProp relates two OPEs; there is \+ no data-property hierarchy constructor",+ );+ }+ }+ RDFS_DOMAIN => {+ if self.is_object_property(&bare_s) {+ if let Some(c) = self.concept(o) {+ axioms.push(OwlAxiom::OPropDomain(+ Ope::Named(bare_s.clone()),+ c,+ ));+ }+ } else if let Some(c) = self.concept(o) {+ axioms.push(OwlAxiom::DPropDomain(bare_s.clone(), c));+ }+ }+ RDFS_RANGE => {+ if self.is_object_property(&bare_s) {+ if let Some(c) = self.concept(o) {+ axioms.push(OwlAxiom::OPropRange(+ Ope::Named(bare_s.clone()),+ c,+ ));+ }+ } else {+ axioms.push(OwlAxiom::DPropRange(bare_s.clone(), bo.clone()));+ }+ }+ _ => {}+ }++ if bp == owl("equivalentClass") {+ if self.has_type(s, RDFS_DATATYPE) || self.has_type(o, RDFS_DATATYPE) {+ self.drop(+ "owl:equivalentClass between datatypes",+ "a datatype definition; no datatype-expression layer in the fragment",+ );+ } else if let (Some(c), Some(d)) = (self.concept(s), self.concept(o)) {+ axioms.push(OwlAxiom::EquivClass(c, d));+ }+ } else if bp == owl("disjointWith") {+ if let (Some(c), Some(d)) = (self.concept(s), self.concept(o)) {+ axioms.push(OwlAxiom::DisjointWith(c, d));+ }+ } else if bp == owl("inverseOf") {+ if is_iri(s) && is_iri(o) {+ axioms.push(OwlAxiom::InverseOf(bare_s.clone(), bo.clone()));+ } else {+ self.drop(+ "owl:inverseOf on an anonymous property expression",+ "Axiom.inverseOf relates two named object properties",+ );+ }+ } else if bp == owl("propertyDisjointWith") {+ axioms.push(OwlAxiom::PropDisjoint(bare_s.clone(), bo.clone()));+ } else if bp == owl("equivalentProperty") {+ let so = self.is_object_property(&bare_s);+ let oo = is_iri(o) && self.is_object_property(&bo);+ if so && oo {+ self.reduce(+ "owl:equivalentProperty",+ "expanded as two subOProp axioms, which is what \+ EquivalentObjectProperties means under the Direct Semantics",+ );+ axioms.push(OwlAxiom::SubOProp(+ Ope::Named(bare_s.clone()),+ Ope::Named(bo.clone()),+ ));+ axioms.push(OwlAxiom::SubOProp(+ Ope::Named(bo.clone()),+ Ope::Named(bare_s.clone()),+ ));+ } else {+ self.drop(+ "owl:equivalentProperty outside the object-property case",+ "there is no data-property hierarchy constructor in the fragment",+ );+ }+ } else if bp == owl("propertyChainAxiom") {+ match self.list(o) {+ Some(items) if items.iter().all(|i| is_iri(i)) => {+ axioms.push(OwlAxiom::Chain(+ items.iter().map(|i| bare(i).to_string()).collect(),+ bare_s.clone(),+ ));+ }+ _ => {+ self.drop(+ "owl:propertyChainAxiom with a malformed or anonymous chain",+ "Axiom.chain takes a list of named object properties",+ );+ }+ }+ } else if bp == owl("sameAs") {+ axioms.push(OwlAxiom::SameAs(bare_s.clone(), bo.clone()));+ } else if bp == owl("differentFrom") {+ axioms.push(OwlAxiom::DifferentFrom(bare_s.clone(), bo.clone()));+ } else if bp == owl("disjointUnionOf") {+ match self.list(o) {+ Some(items) => {+ self.reduce(+ "owl:disjointUnionOf",+ "expanded as one equivalentClass against the union plus the \+ pairwise disjointness axioms, which is its definition",+ );+ let parts: Vec<Concept> = items+ .iter()+ .filter_map(|i| self.concept(i))+ .collect();+ if parts.len() == items.len()+ && let Some(whole) = self.concept(s)+ && let Some(u) = fold_union(&parts) {+ axioms.push(OwlAxiom::EquivClass(whole, u));+ for (i, a) in parts.iter().enumerate() {+ for b in &parts[i + 1..] {+ axioms.push(OwlAxiom::DisjointWith(+ a.clone(),+ b.clone(),+ ));+ }+ }+ }+ }+ None => {+ self.drop("owl:disjointUnionOf with a malformed list", "see above");+ }+ }+ }+ }++ // Property characteristics, from rdf:type. Every one of them takes+ // an S.OProp in OwlLean/Syntax.lean, so a characteristic on a data+ // property is outside the fragment and is named rather than+ // exported under the wrong symbol.+ for (ty, mk) in [+ ("TransitiveProperty", 0u8),+ ("SymmetricProperty", 1),+ ("AsymmetricProperty", 2),+ ("ReflexiveProperty", 3),+ ("IrreflexiveProperty", 4),+ ("InverseFunctionalProperty", 5),+ ("FunctionalProperty", 6),+ ] {+ if !self.has_type(s, &owl(ty)) {+ continue;+ }+ if !self.is_object_property(&bare_s) {+ self.drop(+ &format!("owl:{ty} on a data property"),+ "every property characteristic in OwlLean/Syntax.lean takes an \+ S.OProp; OWL 2 DL forbids these on a data property and RDF \+ vocabularies assert them anyway",+ );+ continue;+ }+ axioms.push(match mk {+ 0 => OwlAxiom::Transitive(bare_s.clone()),+ 1 => OwlAxiom::Symmetric(bare_s.clone()),+ 2 => OwlAxiom::Asymmetric(bare_s.clone()),+ 3 => OwlAxiom::Reflexive(bare_s.clone()),+ 4 => OwlAxiom::Irreflexive(bare_s.clone()),+ 5 => OwlAxiom::InvFunctional(bare_s.clone()),+ _ => OwlAxiom::Functional(bare_s.clone()),+ });+ }++ // n-ary disjointness and difference, via their pairwise readings.+ if self.has_type(s, &owl("AllDisjointClasses"))+ && let Some(l) = self.object(s, &owl("members")).map(str::to_string) {+ match self.list(&l) {+ Some(items) => {+ self.reduce(+ "owl:AllDisjointClasses",+ "expanded pairwise into Axiom.disjointWith",+ );+ let parts: Vec<Concept> =+ items.iter().filter_map(|i| self.concept(i)).collect();+ for (i, a) in parts.iter().enumerate() {+ for b in &parts[i + 1..] {+ axioms.push(OwlAxiom::DisjointWith(a.clone(), b.clone()));+ }+ }+ }+ None => {+ self.drop("owl:AllDisjointClasses with a malformed list", "see above");+ }+ }+ }+ if self.has_type(s, &owl("AllDifferent")) {+ let head = self+ .object(s, &owl("members"))+ .or_else(|| self.object(s, &owl("distinctMembers")))+ .map(str::to_string);+ if let Some(l) = head {+ match self.list(&l) {+ Some(items) => {+ self.reduce(+ "owl:AllDifferent",+ "expanded pairwise into Axiom.differentFrom",+ );+ for (i, a) in items.iter().enumerate() {+ for b in &items[i + 1..] {+ axioms.push(OwlAxiom::DifferentFrom(+ bare(a).to_string(),+ bare(b).to_string(),+ ));+ }+ }+ }+ None => {+ self.drop("owl:AllDifferent with a malformed list", "see above");+ }+ }+ }+ }+ }++ // Assertions. An individual is a subject that is neither a class, a+ // property, nor a piece of OWL syntax.+ for s in &subjects {+ let bare_s = bare(s).to_string();+ if self.classes.contains(&bare_s)+ || self.object_properties.contains(&bare_s)+ || self.data_properties.contains(&bare_s)+ || bare_s.starts_with(OWL)+ {+ continue;+ }+ let pairs = self.by_subject.get(s).cloned().unwrap_or_default();+ for (p, o) in &pairs {+ let bp = bare(p).to_string();+ if bp == RDF_TYPE {+ let bo = bare(o).to_string();+ if bo.starts_with(OWL) || bo.starts_with("http://www.w3.org/2000/01/rdf-schema#")+ {+ continue; // a declaration, not a class assertion+ }+ if let Some(c) = self.concept(o) {+ axioms.push(OwlAxiom::ClassAssert(c, bare_s.clone()));+ }+ continue;+ }+ if bp.starts_with(OWL)+ || bp.starts_with("http://www.w3.org/2000/01/rdf-schema#")+ || bp.starts_with("http://www.w3.org/1999/02/22-rdf-syntax-ns#")+ {+ continue;+ }+ if is_literal(o) {+ continue; // a data property assertion; see below+ }+ if self.is_object_property(&bp) {+ axioms.push(OwlAxiom::OPropAssert(+ bp.clone(),+ bare_s.clone(),+ bare(o).to_string(),+ ));+ }+ }+ }++ self.count_out_of_fragment();+ // Data property assertions have no constructor in the fragment: the+ // Axiom type has oPropAssert and no dPropAssert.+ //+ // ANNOTATIONS ARE NOT COUNTED HERE. `rdfs:label` and its kin carry no+ // Direct Semantics content, so ignoring them does not weaken the axiom+ // set, and counting them would bury the constructs that DO weaken it+ // under hundreds of labels. gUFO alone has 222 literal-valued triples+ // of which almost all are annotations. They are reported separately,+ // under their own heading, so nothing is silent either way.+ let (dpa, annotations) = self.count_literal_triples();+ self.annotations_ignored = annotations;+ if dpa > 0 {+ self.dropped.insert(+ "data property assertion".to_string(),+ (+ dpa,+ "OwlLean/Syntax.lean's Axiom type has oPropAssert and no dPropAssert; \+ a triple with a literal object is not exported"+ .to_string(),+ ),+ );+ }++ // Resolve every anonymous class expression once more, so a conjecture+ // naming one can be built. The drop and reduce ledgers are snapshotted+ // across this pass: it re-reads nodes the axiom walk already read, and+ // counting them twice would misreport how much the export omits.+ let dropped_before = self.dropped.clone();+ let reduced_before = self.reduced.clone();+ let mut anonymous_classes = BTreeMap::new();+ for s in &subjects {+ let anon = s.starts_with("_:")+ || self.has_type(s, &owl("Restriction"))+ || self.object(s, &owl("intersectionOf")).is_some()+ || self.object(s, &owl("unionOf")).is_some()+ || self.object(s, &owl("complementOf")).is_some()+ || self.object(s, &owl("oneOf")).is_some();+ if !anon {+ continue;+ }+ if let Some(k) = self.concept(s) {+ anonymous_classes.insert(bare(s).to_string(), k);+ }+ }+ self.dropped = dropped_before;+ self.reduced = reduced_before;++ // The datatype vocabulary: anything declared rdfs:Datatype, anything+ // standing in a datatype position in an exported axiom, plus the two+ // families every ontology uses without declaring.+ let mut datatypes: BTreeSet<String> = self+ .by_subject+ .keys()+ .filter(|s| self.is_datatype_node(s))+ .map(|s| bare(s).to_string())+ .collect();+ fn concept_datatypes(c: &Concept, out: &mut BTreeSet<String>) {+ match c {+ Concept::DataSome(_, t) | Concept::DataAll(_, t) => {+ out.insert(t.clone());+ }+ Concept::Inter(a, b) | Concept::Union(a, b) => {+ concept_datatypes(a, out);+ concept_datatypes(b, out);+ }+ Concept::Compl(a) => concept_datatypes(a, out),+ Concept::Some_(_, a) | Concept::All_(_, a) => concept_datatypes(a, out),+ Concept::MinCard(_, _, a) | Concept::MaxCard(_, _, a) => {+ concept_datatypes(a, out)+ }+ _ => {}+ }+ }+ for a in &axioms {+ match a {+ OwlAxiom::DPropRange(_, t) => {+ datatypes.insert(t.clone());+ }+ OwlAxiom::SubClass(c, d)+ | OwlAxiom::EquivClass(c, d)+ | OwlAxiom::DisjointWith(c, d) => {+ concept_datatypes(c, &mut datatypes);+ concept_datatypes(d, &mut datatypes);+ }+ OwlAxiom::OPropDomain(_, c)+ | OwlAxiom::OPropRange(_, c)+ | OwlAxiom::DPropDomain(_, c)+ | OwlAxiom::ClassAssert(c, _) => concept_datatypes(c, &mut datatypes),+ _ => {}+ }+ }++ let mut object_properties = self.object_properties.clone();+ object_properties.extend(self.inferred_object.iter().cloned());+ let mut data_properties = self.data_properties.clone();+ data_properties.extend(self.inferred_data.iter().cloned());++ ReadOntology {+ axioms,+ datatypes,+ object_properties,+ data_properties,+ annotations_ignored: self.annotations_ignored,+ anonymous_classes,+ dropped: self+ .dropped+ .into_iter()+ .map(|(construct, (occurrences, why))| Dropped {+ construct,+ occurrences,+ why,+ })+ .collect(),+ reduced: self+ .reduced+ .into_iter()+ .map(|(construct, (occurrences, how))| Reduced {+ construct,+ occurrences,+ how,+ })+ .collect(),+ inferred_object_properties: self.inferred_object.into_iter().collect(),+ inferred_data_properties: self.inferred_data.into_iter().collect(),+ }+ }+}++fn fold_union(parts: &[Concept]) -> Option<Concept> {+ let mut it = parts.iter().rev();+ let mut acc = it.next()?.clone();+ for p in it {+ acc = Concept::Union(Box::new(p.clone()), Box::new(acc));+ }+ Some(acc)+}++/// Read the loaded graph into the `OwlLean/Syntax.lean` fragment.+pub fn read_graph(triples: Vec<(String, String, String)>) -> ReadOntology {+ Reader::new(triples).read()+}++/// Translate one RDF triple into a fragment axiom, for use as a conjecture.+///+/// A derived triple from `reason --certificate` is one of a handful of shapes.+/// Anything else returns `None` and the caller must report it rather than+/// quietly not asking the question.+pub fn triple_as_axiom(+ read: &ReadOntology,+ s: &str,+ p: &str,+ o: &str,+) -> Result<OwlAxiom, String> {+ let (bs, bp, bo) = (bare(s), bare(p), bare(o));+ // A class position that is not a named class must resolve to the class+ // EXPRESSION the graph gives it, or the goal is not asked at all. Building+ // an atom out of a blank node would ask about a symbol that occurs in no+ // axiom, and the prover's inevitable non-answer would look like a limit of+ // the prover instead of a defect here.+ // Declarations win; an undeclared property that was never seen with a+ // literal object is an object property, which is what the reader assumed+ // when it built the axioms.+ let is_object = |prop: &str| -> bool { !read.data_properties.contains(prop) };+ // A datatype is one the reader saw in a datatype position, one declared+ // rdfs:Datatype, or a member of the two families every ontology uses+ // without declaring.+ let is_datatype = |node: &str| -> bool {+ read.datatypes.contains(node)+ || node.starts_with("http://www.w3.org/2001/XMLSchema#")+ || node == "http://www.w3.org/2000/01/rdf-schema#Literal"+ || node == "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"+ };+ let class_at = |node: &str| -> Result<Concept, String> {+ // The same readings `Reader::concept` gives these two. Without them a+ // goal `X rdfs:subClassOf owl:Thing` becomes a subsumption under an+ // ATOM that occurs in no axiom, rather than under the translation's+ // `top`, and the prover reports a countermodel to a question nobody+ // asked. Fifty-two of FOAF's inferences came back that way, this cause+ // and the entity-kind one below between them.+ if node == owl("Thing") {+ return Ok(Concept::Top);+ }+ if node == owl("Nothing") {+ return Ok(Concept::Bot);+ }+ if is_datatype(node) {+ return Err(format!(+ "{node} is a DATATYPE, and OwlLean/Syntax.lean has no axiom form asserting \+ that something belongs to one: Axiom.classAssert takes a Concept and no \+ Concept constructor denotes datatype membership. Translating it as a class \+ assertion would name `c:{node}`, a symbol the axioms never mention, and the \+ prover would report a countermodel to a question nobody asked"+ ));+ }+ if node.starts_with("_:") {+ return read.anonymous_classes.get(node).cloned().ok_or_else(|| {+ format!(+ "the class position is the blank node {node}, which carries no class \+ expression in THIS graph. Blank node labels are not stable across \+ loads, so a goal naming one must come from the same graph the \+ export was built from"+ )+ });+ }+ Ok(read+ .anonymous_classes+ .get(node)+ .cloned()+ .unwrap_or_else(|| Concept::Atom(node.to_string())))+ };+ let no_form = || {+ Err(format!(+ "no axiom form in OwlLean/Syntax.lean corresponds to the triple \+ ({bs} {bp} {bo}), so the question cannot be put to a prover in this \+ translation"+ ))+ };+ if is_literal(s) || is_literal(o) {+ return Err(format!(+ "a literal stands in a position OwlLean/Syntax.lean has no constructor for \+ ({bs} {bp} {bo}); the Axiom type has oPropAssert and no dPropAssert"+ ));+ }+ match bp {+ RDF_TYPE => {+ if bo.starts_with(OWL) || bo.starts_with("http://www.w3.org/2000/01/rdf-schema#") {+ return Err(format!(+ "{bo} is a vocabulary declaration, not a class assertion, so there is \+ nothing to ask"+ ));+ }+ Ok(OwlAxiom::ClassAssert(class_at(bo)?, bs.to_string()))+ }+ RDFS_SUBCLASS => Ok(OwlAxiom::SubClass(class_at(bs)?, class_at(bo)?)),+ RDFS_SUBPROP => {+ if is_object(bs) && is_object(bo) {+ Ok(OwlAxiom::SubOProp(+ Ope::Named(bs.to_string()),+ Ope::Named(bo.to_string()),+ ))+ } else {+ Err(format!(+ "{bs} or {bo} is a data property, and OwlLean/Syntax.lean's subOProp \+ relates two OPEs; there is no data-property hierarchy constructor"+ ))+ }+ }+ RDFS_DOMAIN => {+ if is_object(bs) {+ Ok(OwlAxiom::OPropDomain(Ope::Named(bs.to_string()), class_at(bo)?))+ } else {+ Ok(OwlAxiom::DPropDomain(bs.to_string(), class_at(bo)?))+ }+ }+ RDFS_RANGE => {+ if is_object(bs) {+ Ok(OwlAxiom::OPropRange(Ope::Named(bs.to_string()), class_at(bo)?))+ } else {+ Ok(OwlAxiom::DPropRange(bs.to_string(), bo.to_string()))+ }+ }+ _ if bp == owl("sameAs") => Ok(OwlAxiom::SameAs(bs.to_string(), bo.to_string())),+ _ if bp == owl("differentFrom") => {+ Ok(OwlAxiom::DifferentFrom(bs.to_string(), bo.to_string()))+ }+ _ if bp == owl("inverseOf") => Ok(OwlAxiom::InverseOf(bs.to_string(), bo.to_string())),+ _ if bp == owl("equivalentClass") => {+ Ok(OwlAxiom::EquivClass(class_at(bs)?, class_at(bo)?))+ }+ _ if bp == owl("disjointWith") => {+ Ok(OwlAxiom::DisjointWith(class_at(bs)?, class_at(bo)?))+ }+ _ if bp.starts_with(OWL)+ || bp.starts_with("http://www.w3.org/2000/01/rdf-schema#")+ || bp.starts_with("http://www.w3.org/1999/02/22-rdf-syntax-ns#") =>+ {+ no_form()+ }+ _ if is_object(bp) => Ok(OwlAxiom::OPropAssert(+ bp.to_string(),+ bs.to_string(),+ bo.to_string(),+ )),+ _ => Err(format!(+ "{bp} is a data property, and OwlLean/Syntax.lean's Axiom type has \+ oPropAssert and no dPropAssert"+ )),+ }+}++// ── The export itself ───────────────────────────────────────────────────────++/// Output syntax. Two serialisers over one translation, never two+/// translations.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Syntax {+ /// TPTP FOF, the format every first-order prover reads and the one the+ /// differential oracle runs.+ Tptp,+ /// ISO/IEC 24707 Common Logic Interchange Format, restricted to the+ /// first-order-equivalent fragment. The standards-track interchange+ /// syntax for the same first-order content, and the one ISO/IEC 21838-2+ /// publishes BFO in.+ Clif(ClifDialect, ClifComments),+}++impl Syntax {+ /// `dialect` and `comments` are consulted only for CLIF and default to+ /// `iso` and `standalone`.+ pub fn parse(+ s: &str,+ dialect: Option<&str>,+ comments: Option<&str>,+ ) -> anyhow::Result<Syntax> {+ match s.to_ascii_lowercase().as_str() {+ "tptp" | "fof" | "tptp-fof" => Ok(Syntax::Tptp),+ "clif" | "cl" | "common-logic" => Ok(Syntax::Clif(+ ClifDialect::parse(dialect.unwrap_or("iso"))?,+ ClifComments::parse(comments.unwrap_or("standalone"))?,+ )),+ other => anyhow::bail!(+ "unknown first-order syntax {other:?}; expected `tptp` or `clif`"+ ),+ }+ }+ pub fn extension(self) -> &'static str {+ match self {+ Syntax::Tptp => "p",+ Syntax::Clif(..) => "clif",+ }+ }+ pub fn name(self) -> &'static str {+ match self {+ Syntax::Tptp => "tptp",+ Syntax::Clif(..) => "clif",+ }+ }+ pub fn dialect(self) -> Option<ClifDialect> {+ match self {+ Syntax::Tptp => None,+ Syntax::Clif(d, _) => Some(d),+ }+ }+ pub fn comments(self) -> Option<ClifComments> {+ match self {+ Syntax::Tptp => None,+ Syntax::Clif(_, c) => Some(c),+ }+ }+ fn render(self, problem: &FolProblem, name: &str) -> String {+ match self {+ Syntax::Tptp => problem.to_tptp(),+ Syntax::Clif(d, c) => problem.to_clif(d, c, name),+ }+ }+}++/// One goal that could not be asked.+#[derive(Debug, serde::Serialize)]+pub struct GoalNotAsked {+ pub triple: [String; 3],+ pub why: String,+}++/// Export the loaded ontology to `dir`, and optionally one problem per goal.+///+/// `goals` is a TSV whose first three tab-separated columns are a triple in+/// N-Triples spelling. `derivations.tsv` from `reason --certificate` has the+/// rule in column one, so `goals_skip_columns` is 1 for that file and 0 for a+/// plain triple list.+pub fn export(+ graph: &std::sync::Arc<crate::graph::GraphStore>,+ dir: &std::path::Path,+ syntax: Syntax,+ goals: Option<&std::path::Path>,+ goals_skip_columns: usize,+) -> anyhow::Result<String> {+ let triples = graph.all_triples()?;+ let initial_triples = triples.len();+ // The text name, for CLIF. The ontology's own IRI when it declares one,+ // because a name that identifies the source is worth more than a unique+ // one, and a stated fallback otherwise.+ let ontology_iri = triples+ .iter()+ .find(|(_, p, o)| bare(p) == RDF_TYPE && bare(o) == owl("Ontology"))+ .map(|(s, _, _)| bare(s).to_string())+ .filter(|s| !s.starts_with("_:"))+ .unwrap_or_else(|| UNNAMED_TEXT.to_string());+ let read = read_graph(triples);++ let problem = FolProblem::build(&read.axioms, None)?;+ std::fs::create_dir_all(dir)?;+ let main = dir.join(format!("ontology.{}", syntax.extension()));+ std::fs::write(&main, syntax.render(&problem, &ontology_iri))?;++ let mut goal_files = Vec::new();+ let mut not_asked: Vec<GoalNotAsked> = Vec::new();+ if let Some(path) = goals {+ let text = std::fs::read_to_string(path)?;+ let goals_dir = dir.join("goals");+ std::fs::create_dir_all(&goals_dir)?;+ let mut manifest = Vec::new();+ for (i, line) in text.lines().enumerate() {+ if line.trim().is_empty() {+ continue;+ }+ let cols: Vec<&str> = line.split('\t').collect();+ if cols.len() < goals_skip_columns + 3 {+ not_asked.push(GoalNotAsked {+ triple: [line.to_string(), String::new(), String::new()],+ why: format!(+ "fewer than {} tab-separated columns",+ goals_skip_columns + 3+ ),+ });+ continue;+ }+ let (s, p, o) = (+ cols[goals_skip_columns],+ cols[goals_skip_columns + 1],+ cols[goals_skip_columns + 2],+ );+ let ax = match triple_as_axiom(&read, s, p, o) {+ Ok(ax) => ax,+ Err(why) => {+ not_asked.push(GoalNotAsked {+ triple: [s.to_string(), p.to_string(), o.to_string()],+ why,+ });+ continue;+ }+ };+ let gp = FolProblem::build(&read.axioms, Some(&ax))?;+ let name = format!("goal_{i:05}.{}", syntax.extension());+ std::fs::write(+ goals_dir.join(&name),+ syntax.render(&gp, &format!("{ontology_iri}#goal-{i:05}")),+ )?;+ manifest.push(serde_json::json!({+ "file": name,+ "triple": [s, p, o],+ "axiom_form": axiom_label(&ax),+ }));+ goal_files.push(1);+ }+ std::fs::write(+ dir.join("goals.json"),+ serde_json::to_string_pretty(&serde_json::json!({+ "goals": manifest,+ "not_asked": not_asked,+ }))?,+ )?;+ }++ let report = serde_json::json!({+ "syntax": syntax.name(),+ "clif_dialect": syntax.dialect().map(|d| d.name()),+ "clif_comments": syntax.comments().map(|c| c.name()),+ "clif_text_name": syntax.dialect().map(|_| ontology_iri.clone()),+ "dir": dir.display().to_string(),+ "ontology_file": main.display().to_string(),+ "initial_triples": initial_triples,+ "axioms_exported": problem.axioms.len(),+ "background_axioms": problem.background.len(),+ "individual_typing_axioms": problem.ind_axioms.len(),+ "individuals": problem.individuals.len(),+ "goal_problems": goal_files.len(),+ "goals_not_asked": not_asked.len(),+ // The description-logic layer already carries this flag for its model+ // certificates. An ontology whose unexported constructs are invisible+ // is a trap, so the flag and the list are in the OUTPUT and not only+ // in a comment.+ "exports_a_weaker_axiom_set": !read.dropped.is_empty(),+ "constructs_not_exported": read.dropped,+ "reduced_to_fragment": read.reduced,+ "annotations_ignored": {+ "count": read.annotations_ignored,+ "why": "an annotation carries no OWL 2 Direct Semantics content, so ignoring \+ one does not weaken the axiom set. Counted separately from \+ constructs_not_exported for that reason, and counted rather than \+ passed over in silence",+ },+ "entity_kinds_inferred": {+ "why": "a property with no owl:ObjectProperty or owl:DatatypeProperty \+ declaration is classified by whether it ever takes a literal object. \+ That is an inference, not a reading, so it is listed",+ "as_object_property": read.inferred_object_properties,+ "as_data_property": read.inferred_data_properties,+ },+ "translation": {+ "mirrors": "owl-lean OwlLean/Translation.lean (tr, trAx, background, indAxioms)",+ "theorem": "OwlLean.adequacy",+ "theorem_axioms": ["propext", "Classical.choice", "Quot.sound"],+ "correspondence": "PINNED BY tests/fol_translation_correspondence_test.rs AND \+ NOT ITSELF PROVED. Nothing mechanically checks that this Rust \+ is that Lean",+ "freshness": "every entry into the concept translation goes through \+ Translation::concept_fresh, which refuses unless the subject \+ variable is strictly below the counter. OwlLean.tr_bridge holds \+ only under that condition and \+ OwlLean.Refutations.tr_bridge_needs_freshness is the countermodel",+ "individual_typing": "thing(a) is emitted for every individual name in the \+ signature. Without these axioms adequacy is FALSE: \+ OwlLean.Refutations.adequacy_needs_ind_axioms refutes the \+ left-to-right direction with the empty ontology and the \+ axiom Top(a)",+ },+ "not_certified": "a prover's verdict on these files is an ORACLE OPINION and never a \+ certificate. Checking a superposition refutation needs a verified \+ first-order calculus with unification, which does not exist in core \+ Lean. Use tools/fol_differential.py, which reports disagreement and \+ does not adjudicate it",+ });+ Ok(report.to_string())+}diff --git a/tests/fol_translation_correspondence_test.rs b/tests/fol_translation_correspondence_test.rsnew file mode 100644index 00000000..be1c9232--- /dev/null+++ b/tests/fol_translation_correspondence_test.rs@@ -0,0 +1,1283 @@+//! The emitted first-order logic IS the translation `OwlLean/Translation.lean`+//! defines, for a set of worked cases.+//!+//! This is the point of the first-order export. It is not enough that the file+//! parses, and it is not enough that a prover likes it: `owl-lean` carries a+//! machine-checked adequacy theorem, `OwlLean.adequacy`, and that theorem is+//! worth citing only if the Rust emitter emits the translation the theorem is+//! about. Every expected string below was computed BY HAND from+//! `OwlLean/Translation.lean`, unrolling `tr`, `trAx`, `mkEx`, `mkAll`,+//! `distinctPairs`, `somePairEq`, `Form.conj` and `Form.disj`, and the counter+//! arithmetic with them.+//!+//! **The correspondence is pinned by these tests and is NOT itself proved.**+//! Nothing mechanically checks that `Translation::axiom` is `OwlLean.trAx`.+//! This file is the only thing that will notice if the Rust and the Lean drift+//! apart, which is exactly why the cases are hand-computed rather than+//! recorded from a run: a golden file captured from the emitter would agree+//! with the emitter by construction and would have caught nothing.+//!+//! The tests are grouped:+//!+//! 1. `tr` and `trAx`, case by case, pinned against hand-computed TPTP.+//! 2. The two things the adequacy theorem needs: the freshness side+//! condition and the individual typing axioms, each with the countermodel+//! from `OwlLean/Refutations.lean` reconstructed as a test.+//! 3. One translation, two serialisers: the CLIF output is read back with a+//! small S-expression reader defined here and must recover the identical+//! `Form`, so a drift in either writer is caught.+//! 4. The CLIF output stays inside the first-order-equivalent fragment of+//! Common Logic.+//! 5. Constructs outside the fragment are named in the output.++use open_ontologies::tptp::{+ clif, fof, ClifComments, ClifDialect, Concept, FolProblem, Form, Ope, OwlAxiom, Syntax,+ Translation, P1, P2, Term,+};++const TEXT_NAME: &str = "http://e/ontology";++fn c(s: &str) -> Concept {+ Concept::Atom(format!("http://e/{s}"))+}+fn iri(s: &str) -> String {+ format!("http://e/{s}")+}+/// The TPTP spelling of an IRI under a kind prefix, so the expected strings+/// below stay readable.+fn q(prefix: &str, s: &str) -> String {+ format!("'{prefix}http://e/{s}'")+}++fn tptp_of(a: &OwlAxiom) -> String {+ fof::form(&Translation::axiom(a).expect("freshness holds at trAx's own call sites"))+}++// ── 1. tr and trAx, hand-computed from OwlLean/Translation.lean ─────────────++/// `trAx (subClass (atom A) (atom B))`+///+/// `tr (atom A) 0 2 = (cls A (v 0), 2)`, `tr (atom B) 0 2 = (cls B (v 0), 2)`,+/// then `allObj 0 (imp f g)` where `allObj n f = .all n (.imp (thing (v n)) f)`.+#[test]+fn sub_class_of_two_atoms() {+ let got = tptp_of(&OwlAxiom::SubClass(c("A"), c("B")));+ let expected = format!(+ "! [X0] : (thing(X0) => ({a}(X0) => {b}(X0)))",+ a = q("c:", "A"),+ b = q("c:", "B")+ );+ assert_eq!(got, expected);+}++/// `trAx (subClass (atom A) (some_ r (atom B)))`+///+/// The bound variable is X2, not X1. `trAx` starts the counter at 2 because+/// the subject is variable 0 and `subOProp`-shaped axioms use 1; `tr (some_ r p)+/// x c` takes `y := c` and recurses at `c + 1`. An exporter that allocated+/// from 1, or that reused the subject index, would emit a formula the adequacy+/// theorem says nothing about, and the freshness countermodel+/// `OwlLean.Refutations.tr_bridge_needs_freshness` is what goes wrong at the+/// extreme of that mistake.+#[test]+fn some_values_from_allocates_x2() {+ let got = tptp_of(&OwlAxiom::SubClass(+ c("A"),+ Concept::Some_(iri("r"), Box::new(c("B"))),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => ({a}(X0) => ? [X2] : (thing(X2) & ({r}(X0,X2) & {b}(X2)))))",+ a = q("c:", "A"),+ b = q("c:", "B"),+ r = q("op:", "r")+ );+ assert_eq!(got, expected);+}++/// `trAx (subClass (all_ r top) ...)`: the guarded universal.+#[test]+fn all_values_from_is_a_guarded_universal() {+ let got = tptp_of(&OwlAxiom::SubClass(+ Concept::All_(iri("r"), Box::new(c("B"))),+ c("A"),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => (! [X2] : (thing(X2) => ({r}(X0,X2) => {b}(X2))) => {a}(X0)))",+ a = q("c:", "A"),+ b = q("c:", "B"),+ r = q("op:", "r")+ );+ assert_eq!(got, expected);+}++/// The counter is THREADED between the two sides of a subsumption.+///+/// `tr c 0 2` returns a next-free index, and `tr d 0 n` starts from it, so the+/// right-hand existential binds X3 and not X2. This is the single most+/// effective drift detector in the file: an exporter that restarted the+/// counter per class expression would produce two formulas that capture each+/// other's variables and would pass every "does it parse" check.+#[test]+fn the_counter_is_threaded_across_a_subsumption() {+ let got = tptp_of(&OwlAxiom::SubClass(+ Concept::Some_(iri("r"), Box::new(Concept::Top)),+ Concept::Some_(iri("s"), Box::new(Concept::Top)),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => (? [X2] : (thing(X2) & ({r}(X0,X2) & $true)) \+ => ? [X3] : (thing(X3) & ({s}(X0,X3) & $true))))",+ r = q("op:", "r"),+ s = q("op:", "s")+ );+ assert_eq!(got, expected);+}++/// `trAx (subClass (atom A) (minCard 2 r (atom B)))`+///+/// `ys = [2, 3]`, `trList (atom B) ys (c + n) = ([cls B (v 2), cls B (v 3)], 4)`,+/// `distinctPairs [2,3] = [neg (eq (v 2) (v 3))]`, and the conjunction is+/// `distinctPairs ++ zip`, in that order, right-associated by `Form.conj`.+/// These are the cases LATIN's `OWL2toFOL.elf` has commented out.+#[test]+fn min_cardinality_expands_with_distinctness() {+ let got = tptp_of(&OwlAxiom::SubClass(+ c("A"),+ Concept::MinCard(2, iri("r"), Box::new(c("B"))),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => ({a}(X0) => \+ ? [X2] : (thing(X2) & ? [X3] : (thing(X3) & \+ (~ (X2 = X3) & (({r}(X0,X2) & {b}(X2)) & ({r}(X0,X3) & {b}(X3))))))))",+ a = q("c:", "A"),+ b = q("c:", "B"),+ r = q("op:", "r")+ );+ assert_eq!(got, expected);+}++/// `trAx (subClass (atom A) (maxCard 1 r top))`+///+/// `maxCard n` allocates `n + 1` variables, so `ys = [2, 3]` for `n = 1`, and+/// the consequent is `disj (somePairEq ys)`. The `$true` conjuncts are the+/// translation of the `top` filler and are NOT optimised away: the emitted+/// formula has to be the formula the theorem is about, not one equivalent to+/// it.+#[test]+fn max_cardinality_expands_with_pairwise_equality() {+ let got = tptp_of(&OwlAxiom::SubClass(+ c("A"),+ Concept::MaxCard(1, iri("r"), Box::new(Concept::Top)),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => ({a}(X0) => \+ ! [X2] : (thing(X2) => ! [X3] : (thing(X3) => \+ ((({r}(X0,X2) & $true) & ({r}(X0,X3) & $true)) => X2 = X3)))))",+ a = q("c:", "A"),+ r = q("op:", "r")+ );+ assert_eq!(got, expected);+}++/// `trAx (chain [r, s] t)`: a chain of length n needs n+1 variables, all+/// guarded, and the conclusion relates `v 0` to `v n`.+#[test]+fn property_chain_uses_n_plus_one_variables() {+ let got = tptp_of(&OwlAxiom::Chain(vec![iri("r"), iri("s")], iri("t")));+ let expected = format!(+ "! [X0] : (thing(X0) => ! [X1] : (thing(X1) => ! [X2] : (thing(X2) => \+ (({r}(X0,X1) & {s}(X1,X2)) => {t}(X0,X2)))))",+ r = q("op:", "r"),+ s = q("op:", "s"),+ t = q("op:", "t")+ );+ assert_eq!(got, expected);+}++/// `trAx (classAssert c a) = .and (thing (k a)) (substSubj f a)`.+///+/// The `thing(a)` conjunct is part of `trAx` itself. It is NOT the individual+/// typing axiom, and having it here does not make `indAxioms` redundant:+/// `OwlLean.Refutations.Mbad_refutes` shows this very formula failing in a+/// model where the constant denotes a literal.+#[test]+fn class_assertion_substitutes_the_subject_and_types_it() {+ let got = tptp_of(&OwlAxiom::ClassAssert(c("A"), iri("a")));+ let expected = format!(+ "(thing({i}) & {a}({i}))",+ a = q("c:", "A"),+ i = q("i:", "a")+ );+ assert_eq!(got, expected);+}++/// `tr (oneOf as) x c = (disj (as.map (fun a => eq (v x) (k a))), c)`.+#[test]+fn one_of_is_a_disjunction_of_equalities() {+ let got = tptp_of(&OwlAxiom::SubClass(+ c("A"),+ Concept::OneOf(vec![iri("a"), iri("b")]),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => ({a}(X0) => (X0 = {ia} | X0 = {ib})))",+ a = q("c:", "A"),+ ia = q("i:", "a"),+ ib = q("i:", "b")+ );+ assert_eq!(got, expected);+}++/// `trAx (oPropRange r c)` translates the filler at subject variable **1**,+/// not 0: `let (f, _) := tr c 1 2`. Domain uses 0. Getting these the same way+/// round is a silent correctness bug in every exporter that has it.+#[test]+fn range_translates_the_filler_at_variable_one() {+ let range = tptp_of(&OwlAxiom::OPropRange(Ope::Named(iri("r")), c("B")));+ let domain = tptp_of(&OwlAxiom::OPropDomain(Ope::Named(iri("r")), c("B")));+ assert_eq!(+ range,+ format!(+ "! [X0] : (thing(X0) => ! [X1] : (thing(X1) => ({r}(X0,X1) => {b}(X1))))",+ r = q("op:", "r"),+ b = q("c:", "B")+ )+ );+ assert_eq!(+ domain,+ format!(+ "! [X0] : (thing(X0) => ! [X1] : (thing(X1) => ({r}(X0,X1) => {b}(X0))))",+ r = q("op:", "r"),+ b = q("c:", "B")+ )+ );+}++/// `trAx.ope (.inv r) i j = op r (v j) (v i)`: an inverse property expression+/// swaps the argument order and introduces no new symbol.+#[test]+fn an_inverse_property_expression_swaps_the_arguments() {+ let got = tptp_of(&OwlAxiom::SubOProp(+ Ope::Named(iri("r")),+ Ope::Inv(iri("s")),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => ! [X1] : (thing(X1) => ({r}(X0,X1) => {s}(X1,X0))))",+ r = q("op:", "r"),+ s = q("op:", "s")+ );+ assert_eq!(got, expected);+}++/// `functional` and `invFunctional` differ only in which positions repeat,+/// and both are pinned so a transposition cannot slip through.+#[test]+fn functional_and_inverse_functional_differ_in_argument_position() {+ let f = tptp_of(&OwlAxiom::Functional(iri("r")));+ let i = tptp_of(&OwlAxiom::InvFunctional(iri("r")));+ let r = q("op:", "r");+ assert_eq!(+ f,+ format!(+ "! [X0] : (thing(X0) => ! [X1] : (thing(X1) => ! [X2] : (thing(X2) => \+ (({r}(X0,X1) & {r}(X0,X2)) => X1 = X2))))"+ )+ );+ assert_eq!(+ i,+ format!(+ "! [X0] : (thing(X0) => ! [X1] : (thing(X1) => ! [X2] : (thing(X2) => \+ (({r}(X0,X2) & {r}(X1,X2)) => X0 = X1))))"+ )+ );+}++/// The data side: `dataSome` guards with `lit`, not `thing`, and allocates one+/// variable. Omitting the soft typing makes the translation unsound for every+/// data-property axiom, which is why `background` carries the disjointness.+#[test]+fn data_some_values_from_is_guarded_by_lit() {+ let got = tptp_of(&OwlAxiom::SubClass(+ c("A"),+ Concept::DataSome(iri("p"), iri("D")),+ ));+ let expected = format!(+ "! [X0] : (thing(X0) => ({a}(X0) => ? [X2] : (lit(X2) & ({p}(X0,X2) & {d}(X2)))))",+ a = q("c:", "A"),+ p = q("dp:", "p"),+ d = q("d:", "D")+ );+ assert_eq!(got, expected);+}++/// `dPropRange`: object subject, data object.+#[test]+fn data_property_range_mixes_the_two_guards() {+ let got = tptp_of(&OwlAxiom::DPropRange(iri("p"), iri("D")));+ let expected = format!(+ "! [X0] : (thing(X0) => ! [X1] : (lit(X1) => ({p}(X0,X1) => {d}(X1))))",+ p = q("dp:", "p"),+ d = q("d:", "D")+ );+ assert_eq!(got, expected);+}++/// Equality axioms translate to equality, not to a predicate.+#[test]+fn same_as_and_different_from_use_equality() {+ assert_eq!(+ tptp_of(&OwlAxiom::SameAs(iri("a"), iri("b"))),+ format!("{} = {}", q("i:", "a"), q("i:", "b"))+ );+ assert_eq!(+ tptp_of(&OwlAxiom::DifferentFrom(iri("a"), iri("b"))),+ format!("~ ({} = {})", q("i:", "a"), q("i:", "b"))+ );+}++/// `background` is `OwlLean.background`, verbatim, and both quantifiers are+/// UNGUARDED. Guarding the second one would turn "some element of the domain+/// is an object" into a tautology.+#[test]+fn background_is_two_unguarded_axioms() {+ let b = Translation::background();+ assert_eq!(b.len(), 2);+ assert_eq!(fof::form(&b[0]), "! [X0] : (~ (thing(X0) & lit(X0)))");+ assert_eq!(fof::form(&b[1]), "? [X0] : thing(X0)");+}++/// Every one of the twenty-two axiom forms in `OwlLean/Syntax.lean` translates+/// without tripping the freshness check. A form that is added to `OwlAxiom`+/// and left out of this list is not covered by the count assertion, which is+/// the honest limit of what a test like this can do.+#[test]+fn every_axiom_form_translates() {+ let all = vec![+ OwlAxiom::SubClass(c("A"), c("B")),+ OwlAxiom::EquivClass(c("A"), c("B")),+ OwlAxiom::DisjointWith(c("A"), c("B")),+ OwlAxiom::SubOProp(Ope::Named(iri("r")), Ope::Named(iri("s"))),+ OwlAxiom::OPropDomain(Ope::Named(iri("r")), c("A")),+ OwlAxiom::OPropRange(Ope::Named(iri("r")), c("A")),+ OwlAxiom::DPropDomain(iri("p"), c("A")),+ OwlAxiom::DPropRange(iri("p"), iri("D")),+ OwlAxiom::Transitive(iri("r")),+ OwlAxiom::Symmetric(iri("r")),+ OwlAxiom::Asymmetric(iri("r")),+ OwlAxiom::Reflexive(iri("r")),+ OwlAxiom::Irreflexive(iri("r")),+ OwlAxiom::Functional(iri("r")),+ OwlAxiom::InvFunctional(iri("r")),+ OwlAxiom::InverseOf(iri("r"), iri("s")),+ OwlAxiom::PropDisjoint(iri("r"), iri("s")),+ OwlAxiom::Chain(vec![iri("r"), iri("s")], iri("t")),+ OwlAxiom::ClassAssert(c("A"), iri("a")),+ OwlAxiom::OPropAssert(iri("r"), iri("a"), iri("b")),+ OwlAxiom::SameAs(iri("a"), iri("b")),+ OwlAxiom::DifferentFrom(iri("a"), iri("b")),+ ];+ assert_eq!(all.len(), 22, "OwlLean/Syntax.lean has 22 axiom forms");+ for a in &all {+ Translation::axiom(a).unwrap_or_else(|e| panic!("{a:?} failed: {e}"));+ }+}++/// Every one of the fifteen concept forms translates, at `trAx`'s own counter.+#[test]+fn every_concept_form_translates() {+ let all = vec![+ Concept::Top,+ Concept::Bot,+ c("A"),+ Concept::Inter(Box::new(c("A")), Box::new(c("B"))),+ Concept::Union(Box::new(c("A")), Box::new(c("B"))),+ Concept::Compl(Box::new(c("A"))),+ Concept::OneOf(vec![iri("a")]),+ Concept::Some_(iri("r"), Box::new(c("A"))),+ Concept::All_(iri("r"), Box::new(c("A"))),+ Concept::HasVal(iri("r"), iri("a")),+ Concept::HasSelf(iri("r")),+ Concept::MinCard(2, iri("r"), Box::new(c("A"))),+ Concept::MaxCard(2, iri("r"), Box::new(c("A"))),+ Concept::DataSome(iri("p"), iri("D")),+ Concept::DataAll(iri("p"), iri("D")),+ ];+ assert_eq!(all.len(), 15, "OwlLean/Syntax.lean has 15 concept forms");+ for k in &all {+ Translation::concept_fresh(k, 0, 2).unwrap_or_else(|e| panic!("{k:?} failed: {e}"));+ }+}++// ── 2. The two things the adequacy theorem needs ────────────────────────────++/// **Gate.** `tr_bridge` holds only under `Fresh n x`, i.e. `x < n`.+///+/// `OwlLean.Refutations.tr_bridge_needs_freshness` is the machine-checked+/// countermodel: it translates `∃r.⊤` at subject 0 with the counter also at 0,+/// and exhibits an interpretation where the two readings disagree because the+/// existential `tr` allocates has captured the subject variable. This test+/// puts exactly that call to the exporter and requires a refusal.+#[test]+fn freshness_gate_refuses_the_refutations_countermodel_call() {+ let captured = Concept::Some_(iri("r"), Box::new(Concept::Top));+ let err = Translation::concept_fresh(&captured, 0, 0)+ .expect_err("subject 0 with counter 0 is the Refutations countermodel and must be refused");+ assert_eq!(err.subject, 0);+ assert_eq!(err.counter, 0);+ assert!(err.to_string().contains("tr_bridge_needs_freshness"));++ // The boundary: x = c is refused, x = c - 1 is accepted.+ assert!(Translation::concept_fresh(&captured, 2, 2).is_err());+ assert!(Translation::concept_fresh(&captured, 1, 2).is_ok());+}++/// **Gate.** The individual typing axioms are emitted.+///+/// This reconstructs `OwlLean.Refutations`: the empty ontology, the axiom+/// `⊤(a)`. `adequacy_needs_ind_axioms` refutes the left-to-right direction of+/// adequacy for exactly this pair when `indAxioms` is missing, because `Mbad`+/// interprets the constant outside `thing`. The typing axiom is the fix, so it+/// must be in the file.+#[test]+fn the_individual_typing_axiom_is_emitted() {+ let goal = OwlAxiom::ClassAssert(Concept::Top, iri("a"));+ let problem = FolProblem::build(&[], Some(&goal)).expect("translates");++ assert_eq!(+ problem.ind_axioms.len(),+ 1,+ "the empty ontology with the goal Top(a) has one individual, so one typing axiom"+ );+ assert_eq!(fof::form(&problem.ind_axioms[0]), "thing('i:http://e/a')");++ let text = problem.to_tptp();+ assert!(+ text.contains("fof(ind_typing_1, axiom, thing('i:http://e/a'))."),+ "without this axiom OwlLean.Refutations.adequacy_needs_ind_axioms refutes \+ adequacy outright. Emitted:\n{text}"+ );+}++/// The typing axioms range over EVERY individual the problem mentions,+/// including one that occurs only in the conjecture. The adequacy theorem's+/// hypothesis is `∀ a : S.Ind, a ∈ inds`, and the signature here is the+/// occurring vocabulary, so an individual left out would break it.+#[test]+fn the_typing_axioms_cover_the_goals_individuals_too() {+ let ontology = vec![OwlAxiom::OPropAssert(iri("r"), iri("a"), iri("b"))];+ let goal = OwlAxiom::ClassAssert(c("A"), iri("zz"));+ let problem = FolProblem::build(&ontology, Some(&goal)).expect("translates");+ let names: Vec<&str> = problem.individuals.iter().map(String::as_str).collect();+ assert_eq!(names, vec![iri("a"), iri("b"), iri("zz")]);+ assert_eq!(problem.ind_axioms.len(), 3);+}++// ── 3. One translation, two serialisers ─────────────────────────────────────+//+// A tiny CLIF reader, defined here and nowhere in `src/`, because it exists+// only to check the writer. Reading the emitted text back and requiring the+// identical `Form` is what makes "two serialisations of one translation" a+// checked claim rather than a design intention.++#[derive(Debug, PartialEq, Eq, Clone)]+enum Sexp {+ Atom(String),+ List(Vec<Sexp>),+}++fn lex(src: &str) -> Vec<String> {+ let mut out = Vec::new();+ let mut chars = src.chars().peekable();+ while let Some(ch) = chars.next() {+ match ch {+ '(' | ')' => out.push(ch.to_string()),+ c if c.is_whitespace() => {}+ '"' | '\'' => {+ // An enclosed name (double quotes, ISO/IEC 24707 A.2.2.2+ // `namequote`) or a quoted string (single quotes,+ // `stringquote`), each running to its matching delimiter with+ // backslash escapes.+ let mut name = String::new();+ name.push(ch);+ loop {+ match chars.next() {+ None => panic!("unterminated enclosed name or string"),+ Some('\\') => {+ name.push('\\');+ name.push(chars.next().expect("escape at end of input"));+ }+ Some(c) if c == ch => {+ name.push(c);+ break;+ }+ Some(c) => name.push(c),+ }+ }+ out.push(name);+ }+ c => {+ let mut name = String::from(c);+ while let Some(&n) = chars.peek() {+ if n == '(' || n == ')' || n.is_whitespace() || n == '"' || n == '\'' {+ break;+ }+ name.push(n);+ chars.next();+ }+ out.push(name);+ }+ }+ }+ out+}++fn parse(tokens: &[String], i: &mut usize) -> Sexp {+ let t = &tokens[*i];+ *i += 1;+ if t == "(" {+ let mut items = Vec::new();+ while tokens[*i] != ")" {+ items.push(parse(tokens, i));+ }+ *i += 1;+ Sexp::List(items)+ } else {+ assert_ne!(t, ")", "unbalanced CLIF");+ Sexp::Atom(t.clone())+ }+}++fn read_sexp(src: &str) -> Sexp {+ let tokens = lex(src);+ let mut i = 0;+ let s = parse(&tokens, &mut i);+ assert_eq!(i, tokens.len(), "trailing tokens in {src}");+ s+}++/// Undo `clif::enclosed`: strip the DOUBLE QUOTES and the escapes.+fn unenclose(name: &str) -> Option<String> {+ let inner = name.strip_prefix('"')?.strip_suffix('"')?;+ let mut out = String::new();+ let mut chars = inner.chars();+ while let Some(ch) = chars.next() {+ if ch == '\\' {+ out.push(chars.next().expect("escape at end"));+ } else {+ out.push(ch);+ }+ }+ Some(out)+}++fn read_term(s: &Sexp) -> Term {+ let Sexp::Atom(a) = s else {+ panic!("a CLIF term in the first-order fragment is an atom, found {s:?}")+ };+ match unenclose(a) {+ Some(name) => {+ let rest = name+ .strip_prefix("i:")+ .unwrap_or_else(|| panic!("a constant must carry the i: prefix, found {name}"));+ Term::Const(rest.to_string())+ }+ None => {+ let n = a+ .strip_prefix('X')+ .and_then(|d| d.parse().ok())+ .unwrap_or_else(|| panic!("a variable must be Xn, found {a}"));+ Term::Var(n)+ }+ }+}++fn read_p1(s: &Sexp) -> P1 {+ let Sexp::Atom(a) = s else { panic!("predicate position must be a name") };+ match a.as_str() {+ "thing" => return P1::Thing,+ "lit" => return P1::Lit,+ _ => {}+ }+ let name = unenclose(a).unwrap_or_else(|| panic!("unknown bare predicate {a}"));+ if let Some(r) = name.strip_prefix("c:") {+ P1::Cls(r.to_string())+ } else if let Some(r) = name.strip_prefix("d:") {+ P1::Dt(r.to_string())+ } else {+ panic!("unary predicate {name} carries no kind prefix")+ }+}++fn read_p2(s: &Sexp) -> P2 {+ let Sexp::Atom(a) = s else { panic!("predicate position must be a name") };+ let name = unenclose(a).unwrap_or_else(|| panic!("unknown bare predicate {a}"));+ if let Some(r) = name.strip_prefix("op:") {+ P2::Op(r.to_string())+ } else if let Some(r) = name.strip_prefix("dp:") {+ P2::Dp(r.to_string())+ } else {+ panic!("binary predicate {name} carries no kind prefix")+ }+}++fn read_form(s: &Sexp) -> Form {+ let Sexp::List(items) = s else {+ panic!("a CLIF sentence is a list, found {s:?}")+ };+ if items.is_empty() {+ panic!("the empty list is not a CLIF sentence");+ }+ if let Sexp::Atom(head) = &items[0] {+ // A commented sentence has the same semantics as the sentence.+ if (head == "cl:comment" || head == "cl-comment") && items.len() == 3 {+ return read_form(&items[2]);+ }+ match (head.as_str(), items.len()) {+ ("and", 1) => return Form::Tru,+ ("or", 1) => return Form::Fls,+ ("and", 3) => {+ return Form::And(+ Box::new(read_form(&items[1])),+ Box::new(read_form(&items[2])),+ )+ }+ ("or", 3) => {+ return Form::Or(+ Box::new(read_form(&items[1])),+ Box::new(read_form(&items[2])),+ )+ }+ ("if", 3) => {+ return Form::Imp(+ Box::new(read_form(&items[1])),+ Box::new(read_form(&items[2])),+ )+ }+ ("not", 2) => return Form::Neg(Box::new(read_form(&items[1]))),+ ("=", 3) => return Form::Eq(read_term(&items[1]), read_term(&items[2])),+ ("forall", 3) | ("exists", 3) => {+ let Sexp::List(binders) = &items[1] else {+ panic!("a quantifier's binding list must be a list")+ };+ assert_eq!(binders.len(), 1, "the writer emits one binder per quantifier");+ let Term::Var(n) = read_term(&binders[0]) else {+ panic!("a binder must be a variable")+ };+ let body = Box::new(read_form(&items[2]));+ return if head == "forall" {+ Form::All(n, body)+ } else {+ Form::Ex(n, body)+ };+ }+ _ => {}+ }+ }+ // An atomic sentence: a predicate applied to terms.+ match items.len() {+ 2 => Form::App1(read_p1(&items[0]), read_term(&items[1])),+ 3 => Form::App2(read_p2(&items[0]), read_term(&items[1]), read_term(&items[2])),+ n => panic!("no first-order atom of arity {}: {s:?}", n - 1),+ }+}++/// A corpus that exercises every constructor of `Form` at least once.+fn corpus() -> Vec<OwlAxiom> {+ vec![+ OwlAxiom::SubClass(c("A"), c("B")),+ OwlAxiom::SubClass(c("A"), Concept::Some_(iri("r"), Box::new(c("B")))),+ OwlAxiom::SubClass(c("A"), Concept::All_(iri("r"), Box::new(c("B")))),+ OwlAxiom::SubClass(c("A"), Concept::MinCard(2, iri("r"), Box::new(c("B")))),+ OwlAxiom::SubClass(c("A"), Concept::MaxCard(1, iri("r"), Box::new(Concept::Top))),+ OwlAxiom::SubClass(Concept::Bot, Concept::Compl(Box::new(c("B")))),+ OwlAxiom::SubClass(+ Concept::Inter(Box::new(c("A")), Box::new(c("B"))),+ Concept::Union(Box::new(c("A")), Box::new(c("B"))),+ ),+ OwlAxiom::SubClass(c("A"), Concept::OneOf(vec![iri("a"), iri("b")])),+ OwlAxiom::SubClass(c("A"), Concept::HasVal(iri("r"), iri("a"))),+ OwlAxiom::SubClass(c("A"), Concept::HasSelf(iri("r"))),+ OwlAxiom::SubClass(c("A"), Concept::DataSome(iri("p"), iri("D"))),+ OwlAxiom::SubClass(c("A"), Concept::DataAll(iri("p"), iri("D"))),+ OwlAxiom::EquivClass(c("A"), c("B")),+ OwlAxiom::DisjointWith(c("A"), c("B")),+ OwlAxiom::SubOProp(Ope::Named(iri("r")), Ope::Inv(iri("s"))),+ OwlAxiom::OPropDomain(Ope::Inv(iri("r")), c("A")),+ OwlAxiom::OPropRange(Ope::Named(iri("r")), c("A")),+ OwlAxiom::DPropDomain(iri("p"), c("A")),+ OwlAxiom::DPropRange(iri("p"), iri("D")),+ OwlAxiom::Transitive(iri("r")),+ OwlAxiom::Symmetric(iri("r")),+ OwlAxiom::Asymmetric(iri("r")),+ OwlAxiom::Reflexive(iri("r")),+ OwlAxiom::Irreflexive(iri("r")),+ OwlAxiom::Functional(iri("r")),+ OwlAxiom::InvFunctional(iri("r")),+ OwlAxiom::InverseOf(iri("r"), iri("s")),+ OwlAxiom::PropDisjoint(iri("r"), iri("s")),+ OwlAxiom::Chain(vec![iri("r"), iri("s")], iri("t")),+ OwlAxiom::ClassAssert(c("A"), iri("a")),+ OwlAxiom::OPropAssert(iri("r"), iri("a"), iri("b")),+ OwlAxiom::SameAs(iri("a"), iri("b")),+ OwlAxiom::DifferentFrom(iri("a"), iri("b")),+ ]+}++/// **The two serialisers denote the same formula set.**+///+/// Every formula in the problem, background and typing axioms included, is+/// rendered to CLIF, read back with the reader above, and required to be the+/// identical `Form` the TPTP writer was handed. A drift in either writer+/// breaks this.+#[test]+fn clif_round_trips_to_the_same_forms() {+ let problem = FolProblem::build(&corpus(), None).expect("translates");+ let formulas = problem.formulas();+ assert!(formulas.len() >= 36, "corpus should be substantial");+ for (name, _role, f) in &formulas {+ let text = clif::form(f);+ let back = read_form(&read_sexp(&text));+ assert_eq!(&&back, f, "CLIF round trip differs for {name}: {text}");+ }+}++/// The two files carry the same formulas in the same order, so neither+/// serialiser can quietly include or omit one.+#[test]+fn both_files_carry_the_same_formulas_in_the_same_order() {+ let problem = FolProblem::build(&corpus(), Some(&OwlAxiom::SubClass(c("A"), c("B"))))+ .expect("translates");+ let names: Vec<String> = problem.formulas().into_iter().map(|(n, _, _)| n).collect();++ let tptp_text = problem.to_tptp();+ let clif_text = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME);+ for n in &names {+ assert!(tptp_text.contains(&format!("fof({n}, ")), "TPTP missing {n}");+ assert!(+ clif_text.contains(&format!("(cl:comment '{n} (")),+ "CLIF missing {n}"+ );+ }+ // Same count of emitted sentences in each. The CLIF has one more+ // `cl:comment`, the header, and it rides on `(and)`, which is true in+ // every model and so adds nothing to the theory.+ assert_eq!(+ tptp_text.matches("\nfof(").count(),+ names.len(),+ "TPTP sentence count"+ );+ assert_eq!(+ clif_text.matches("(cl:comment ").count(),+ names.len() + 1,+ "one standalone comment per formula, plus the header comment"+ );+}++/// Hand-pinned CLIF, for the same worked cases as the TPTP above. The round+/// trip proves the two agree with each other; these pin what they agree ON.+#[test]+fn clif_worked_cases_are_pinned_by_hand() {+ let f = Translation::axiom(&OwlAxiom::SubClass(+ c("A"),+ Concept::Some_(iri("r"), Box::new(c("B"))),+ ))+ .unwrap();+ assert_eq!(+ clif::form(&f),+ "(forall (X0) (if (thing X0) (if (\"c:http://e/A\" X0) \+ (exists (X2) (and (thing X2) (and (\"op:http://e/r\" X0 X2) (\"c:http://e/B\" X2)))))))"+ );++ let b = Translation::background();+ assert_eq!(+ clif::form(&b[0]),+ "(forall (X0) (not (and (thing X0) (lit X0))))"+ );+ assert_eq!(clif::form(&b[1]), "(exists (X0) (thing X0))");++ // `(and)` is truth and `(or)` is falsity; CLIF has no truth constants.+ assert_eq!(clif::form(&Form::Tru), "(and)");+ assert_eq!(clif::form(&Form::Fls), "(or)");++ let max = Translation::axiom(&OwlAxiom::SubClass(+ c("A"),+ Concept::MaxCard(1, iri("r"), Box::new(Concept::Top)),+ ))+ .unwrap();+ assert_eq!(+ clif::form(&max),+ "(forall (X0) (if (thing X0) (if (\"c:http://e/A\" X0) \+ (forall (X2) (if (thing X2) (forall (X3) (if (thing X3) \+ (if (and (and (\"op:http://e/r\" X0 X2) (and)) (and (\"op:http://e/r\" X0 X3) (and))) \+ (= X2 X3)))))))))"+ );+}++// ── 4. The CLIF stays inside the first-order-equivalent fragment ────────────++/// **Gate.** Common Logic is not plain first-order logic.+///+/// It has sequence markers, arity-free predicates, and a universe in which+/// relations are themselves individuals. The adequacy theorem is about a+/// translation into PLAIN first-order logic, so an emitted text using any of+/// those would sit outside the theorem. Three properties are checked over the+/// whole corpus:+///+/// * no sequence marker anywhere in the text,+/// * every predicate name is used at ONE arity throughout,+/// * no bound variable ever appears in a predicate position.+#[test]+fn clif_uses_only_fol_fragment() {+ use std::collections::HashMap;++ let problem = FolProblem::build(&corpus(), None).expect("translates");+ let text = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME);+ assert!(+ !text.contains("..."),+ "a sequence marker would take the text outside plain first-order logic"+ );++ let mut arity: HashMap<String, usize> = HashMap::new();+ let mut bound: Vec<u32> = Vec::new();++ fn walk(+ s: &Sexp,+ arity: &mut HashMap<String, usize>,+ bound: &mut Vec<u32>,+ ) {+ let Sexp::List(items) = s else { return };+ if items.is_empty() {+ return;+ }+ if let Sexp::Atom(head) = &items[0] {+ match head.as_str() {+ "and" | "or" | "if" | "iff" | "not" => {+ for it in &items[1..] {+ walk(it, arity, bound);+ }+ return;+ }+ "forall" | "exists" => {+ let Sexp::List(binders) = &items[1] else {+ panic!("binding list must be a list")+ };+ for b in binders {+ let Sexp::Atom(a) = b else { panic!("binder must be a name") };+ let n: u32 = a+ .strip_prefix('X')+ .and_then(|d| d.parse().ok())+ .expect("binder must be Xn");+ bound.push(n);+ }+ walk(&items[2], arity, bound);+ for _ in binders {+ bound.pop();+ }+ return;+ }+ "=" => {+ assert_eq!(items.len(), 3, "equality is binary in the fragment");+ return;+ }+ _ => {}+ }+ // An atomic sentence. The operator must be a NAME, never a bound+ // variable: quantifying into a predicate position is the+ // second-order half of Common Logic.+ if let Some(n) = head.strip_prefix('X').and_then(|d| d.parse::<u32>().ok()) {+ assert!(+ !bound.contains(&n),+ "bound variable X{n} used in a predicate position"+ );+ }+ let seen = arity.entry(head.clone()).or_insert(items.len() - 1);+ assert_eq!(+ *seen,+ items.len() - 1,+ "predicate {head} used at two arities, which is arity-free Common Logic \+ and not plain first-order logic"+ );+ // Arguments must all be terms.+ for it in &items[1..] {+ assert!(+ matches!(it, Sexp::Atom(_)),+ "an argument in the first-order fragment is a term, found {it:?}"+ );+ }+ } else {+ panic!("an operator position must be a name, found {:?}", items[0]);+ }+ }++ for (_, _, f) in problem.formulas() {+ walk(&read_sexp(&clif::form(f)), &mut arity, &mut bound);+ }+ assert!(arity.contains_key("thing") && arity.contains_key("lit"));+ assert_eq!(arity["thing"], 1);+ assert_eq!(arity["lit"], 1);+}++/// The emitted CLIF says, in the file, that it is restricted. A limit stated+/// only in a README gets read without one.+#[test]+fn the_clif_header_states_the_restriction() {+ let problem = FolProblem::build(&corpus(), None).expect("translates");+ let text = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME);+ assert!(text.contains("CLIF RESTRICTION"));+ assert!(text.contains("no sequence markers"));+ assert!(text.contains("(cl:text"));+ assert!(text.contains("DIALECT"));+ // No LEXICAL comments: the standard defines `cl:comment` as a reserved+ // element, and this project could not establish a `//` or `/* */`+ // line-comment convention from the standard's own text, so it emits+ // none. (`//` itself occurs inside every IRI, so the check is on line+ // starts, not on the substring.)+ assert!(+ !text.lines().any(|l| l.trim_start().starts_with("//")+ || l.trim_start().starts_with("/*")),+ "the CLIF body carries no lexical comments"+ );+ assert!(text.contains("(cl:comment '"), "labels ride on cl:comment");+}++/// Both headers say that the correspondence is pinned by tests and not proved,+/// and a file with a conjecture also says an ATP verdict is an oracle opinion.+#[test]+fn the_headers_state_the_limits() {+ let with_goal = FolProblem::build(&[], Some(&OwlAxiom::SubClass(c("A"), c("B")))).unwrap();+ for text in [+ with_goal.to_tptp(),+ with_goal.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME),+ ] {+ assert!(text.contains("PINNED BY TESTS AND IS NOT ITSELF PROVED"));+ assert!(text.contains("ORACLE OPINION, not a certificate"));+ }+ let no_goal = FolProblem::build(&[], None).unwrap();+ assert!(!no_goal.to_tptp().contains("ORACLE OPINION"));+}++// ── 5. What is dropped is named ─────────────────────────────────────────────++/// **Gate.** An ontology whose unexported constructs are invisible is a trap.+///+/// `owl:hasKey` is outside `OwlLean/Syntax.lean`. The report must say so, with+/// a count and a reason, and must set `exports_a_weaker_axiom_set`, the same+/// flag the description-logic layer sets for its model certificates.+#[test]+fn constructs_outside_the_fragment_are_named_in_the_output() {+ let ttl = r#"+@prefix : <http://e/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+:A a owl:Class ; rdfs:subClassOf :B .+:B a owl:Class .+:k a owl:ObjectProperty .+:A owl:hasKey ( :k ) .+"#;+ let graph = std::sync::Arc::new(open_ontologies::graph::GraphStore::new());+ graph.load_turtle(ttl, None).expect("turtle parses");+ let dir = tempfile::tempdir().expect("tempdir");+ let report = open_ontologies::tptp::export(&graph, dir.path(), Syntax::Tptp, None, 0)+ .expect("export");+ let v: serde_json::Value = serde_json::from_str(&report).expect("json");++ assert_eq!(+ v["exports_a_weaker_axiom_set"], true,+ "hasKey is outside the fragment, so the export is weaker than the ontology"+ );+ let named: Vec<String> = v["constructs_not_exported"]+ .as_array()+ .expect("a list")+ .iter()+ .map(|d| d["construct"].as_str().unwrap_or("").to_string())+ .collect();+ assert!(+ named.iter().any(|n| n.contains("hasKey")),+ "owl:hasKey must be named, got {named:?}"+ );+ // And the reason travels with it, not only the name.+ let why = v["constructs_not_exported"][0]["why"].as_str().unwrap_or("");+ assert!(!why.is_empty(), "a dropped construct carries its reason");+}++/// A clean ontology inside the fragment does NOT set the flag, so the flag+/// means something.+#[test]+fn an_ontology_inside_the_fragment_does_not_set_the_flag() {+ let ttl = r#"+@prefix : <http://e/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+:A a owl:Class ; rdfs:subClassOf :B .+:B a owl:Class .+:r a owl:ObjectProperty, owl:TransitiveProperty .+:a a :A .+"#;+ let graph = std::sync::Arc::new(open_ontologies::graph::GraphStore::new());+ graph.load_turtle(ttl, None).expect("turtle parses");+ let dir = tempfile::tempdir().expect("tempdir");+ let report = open_ontologies::tptp::export(&graph, dir.path(), Syntax::Tptp, None, 0)+ .expect("export");+ let v: serde_json::Value = serde_json::from_str(&report).expect("json");+ assert_eq!(+ v["exports_a_weaker_axiom_set"], false,+ "nothing here is outside the fragment; got {}",+ v["constructs_not_exported"]+ );+ assert_eq!(v["individual_typing_axioms"], 1);+}++/// The COLORE dialect is a different SPELLING of the same text, not a+/// different translation.+///+/// COLORE is written with `cl-text` / `cl-comment` and single-quoted comment+/// strings, and the Macleod toolchain's shipped lexer maps only those; a file+/// in the ISO spelling does not parse there. The two outputs must therefore+/// differ in the operators and in nothing else, which the round trip through+/// the reader checks formula by formula.+#[test]+fn the_colore_dialect_changes_the_spelling_and_nothing_else() {+ let problem = FolProblem::build(&corpus(), None).expect("translates");+ let iso = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME);+ let colore = problem.to_clif(ClifDialect::Colore, ClifComments::Standalone, TEXT_NAME);++ assert!(iso.contains("(cl:text") && !iso.contains("(cl-text"));+ assert!(colore.contains("(cl-text") && !colore.contains("(cl:text"));+ // Comment strings are SINGLE quoted in BOTH. Quote style is not a dialect+ // matter: ISO/IEC 24707 A.2.2.2 makes the single quote the string+ // delimiter, and BFO's release notes of 7 December 2025 retract the+ // double-quoted form its ISO-hosted files use. Binding the two together+ // meant no flag combination emitted conforming CLIF.+ assert!(colore.contains("(cl-comment '"));+ assert!(iso.contains("(cl:comment '"));+ assert!(!iso.contains("(cl:comment \""), "comment strings are never double quoted");++ // Enclosed names are double-quoted in BOTH: ISO/IEC 24707 A.2.2.2 makes+ // the double quote the namequote, and A.2.2.4 recommends the enclosed-name+ // syntax for IRIs. That is not a dialect matter.+ assert!(colore.contains("\"c:http://e/A\""));+ assert!(iso.contains("\"c:http://e/A\""));++ // Same formulas, read back.+ for (name, _role, f) in problem.formulas() {+ for dialect in [ClifDialect::Iso, ClifDialect::Colore] {+ let text = clif::form(f);+ assert_eq!(+ &read_form(&read_sexp(&text)),+ f,+ "{} round trip differs in the {} dialect",+ name,+ dialect.name()+ );+ }+ }+}++/// An unknown dialect, comment placement or syntax is refused with a message+/// that names the alternatives, rather than silently defaulting.+#[test]+fn an_unknown_syntax_or_dialect_is_refused() {+ assert!(Syntax::parse("smtlib", None, None).is_err());+ let e =+ Syntax::parse("clif", Some("kif"), None).expect_err("kif is not a CLIF dialect");+ assert!(+ e.to_string().contains("iso") && e.to_string().contains("colore"),+ "got {e}"+ );+ let e = Syntax::parse("clif", None, Some("inline"))+ .expect_err("inline is not a comment placement");+ assert!(+ e.to_string().contains("standalone") && e.to_string().contains("wrapped"),+ "got {e}"+ );+ // The defaults, and the alternatives.+ let d = Syntax::parse("clif", None, None).unwrap();+ assert_eq!(d.dialect(), Some(ClifDialect::Iso));+ assert_eq!(+ d.comments(),+ Some(ClifComments::Standalone),+ "standalone is the default, because it is the only shape either \+ available parser recovers sentences from"+ );+ assert_eq!(+ Syntax::parse("clif", Some("colore"), Some("wrapped"))+ .unwrap()+ .comments(),+ Some(ClifComments::Wrapped)+ );+ assert_eq!(Syntax::parse("tptp", None, None).unwrap().dialect(), None);+}++/// **Gate.** The default CLIF shape is the one a parser can recover sentences+/// from, and the wrapped shape stays reachable but off.+///+/// py-typedlogic treats a `(cl:comment ...)` form as discardable, so a file+/// whose sentences are all inside one parses cleanly and yields ZERO+/// sentences; Macleod has no commented-sentence production at all. Both do+/// that to ISO/IEC 21838-2's own BFO files. A file that is formally valid and+/// practically empty is the assurance-laundering shape this project exists to+/// attack, so the default must not be it.+#[test]+fn the_default_clif_shape_leaves_sentences_outside_the_comments() {+ let problem = FolProblem::build(&corpus(), None).expect("translates");+ let n = problem.formulas().len();++ let standalone = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME);+ assert_eq!(+ standalone.matches("(cl:comment ").count(),+ n + 1,+ "one comment per formula plus the header"+ );++ // Structural, not line-based: the header comment spans many lines. For+ // every `(cl:comment '`, walk to the closing unescaped quote and require+ // the next non-space character to be the closing bracket. That is exactly+ // the check that distinguishes a standalone comment from one wrapping a+ // sentence, and it is the one that would have caught the original shape.+ let chars: Vec<char> = standalone.chars().collect();+ let marker: Vec<char> = "(cl:comment '".chars().collect();+ let mut found = 0usize;+ let mut i = 0usize;+ while i + marker.len() <= chars.len() {+ if chars[i..i + marker.len()] != marker[..] {+ i += 1;+ continue;+ }+ found += 1;+ let mut j = i + marker.len();+ while j < chars.len() && chars[j] != '\'' {+ j += if chars[j] == '\\' { 2 } else { 1 };+ }+ j += 1;+ while j < chars.len() && chars[j].is_whitespace() {+ j += 1;+ }+ assert_eq!(+ chars.get(j),+ Some(&')'),+ "comment {found} does not close immediately after its string, so a \+ sentence is inside it and both available parsers would drop it"+ );+ i = j;+ }+ assert_eq!(found, n + 1, "every comment was walked");++ // And the sentences are there, one per formula, as phrases of the text in+ // their own right. Read with the S-expression reader below rather than by+ // scanning lines: the header comment spans many lines and several of them+ // begin with an open bracket.+ let Sexp::List(items) = read_sexp(&standalone) else {+ panic!("the whole file is one form")+ };+ assert_eq!(items[0], Sexp::Atom("cl:text".to_string()));+ assert_eq!(items[1], Sexp::Atom(TEXT_NAME.to_string()));+ let (comments, sentences): (Vec<_>, Vec<_>) = items[2..].iter().partition(|p| {+ matches!(p, Sexp::List(xs) if xs.first() == Some(&Sexp::Atom("cl:comment".to_string())))+ });+ assert_eq!(comments.len(), n + 1, "one comment per formula plus the header");+ assert_eq!(sentences.len(), n, "one bare sentence per formula");+ // Every one of them is a formula this project can read back.+ for phrase in &sentences {+ read_form(phrase);+ }++ // The wrapped shape is still available and is not the default.+ let wrapped = problem.to_clif(ClifDialect::Iso, ClifComments::Wrapped, TEXT_NAME);+ assert!(wrapped.contains("(cl:comment 'owl_1_subClassOf (axiom)' (forall"));+ assert!(!standalone.contains("(cl:comment 'owl_1_subClassOf (axiom)' (forall"));+}++/// **Gate.** The text is NAMED.+///+/// All 227 COLORE texts are named, Macleod refuses an unnamed text with+/// "Error in ontology: bad URI", and py-typedlogic otherwise reports the+/// first comment as the theory's name. The name is bare rather than+/// double-quoted because Macleod's lexer has no double-quote token.+#[test]+fn the_clif_text_is_named() {+ let problem = FolProblem::build(&corpus(), None).expect("translates");+ let text = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME);+ assert!(+ text.starts_with(&format!("(cl:text {TEXT_NAME}\n")),+ "the text must carry its name, got: {}",+ text.lines().next().unwrap_or("")+ );+ let colore = problem.to_clif(ClifDialect::Colore, ClifComments::Standalone, TEXT_NAME);+ assert!(colore.starts_with(&format!("(cl-text {TEXT_NAME}\n")));++ // A name that would break a bare token falls back to an enclosed name.+ let awkward = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, "a name (x)");+ assert!(awkward.starts_with("(cl:text \"a name (x)\"\n"), "got {}", &awkward[..40]);+}++/// **Gate.** The emitted CLIF stays inside the subdialect ISO/IEC 24707 calls+/// EXACTLY semantically conformant.+///+/// Annex A.4.2 of the first edition says, verbatim: "The subdialect of CLIF+/// which does not use numerals or quoted strings is exactly semantically+/// conformant". That matters because a CLIF numeral and a single-quoted string+/// are INTERPRETED names, which denote themselves, and a text containing them+/// constrains its own interpretations in a way abstract Common Logic does not.+/// Stay out of that subdialect and CLIF entailment and Common Logic entailment+/// coincide, so the adequacy theorem's biconditional needs no qualification at+/// the CLIF end.+///+/// **The scope of the claim, stated exactly.** No decimal numerals and no+/// quoted strings IN SENTENCE POSITIONS. Comment annotations are the named+/// exception: a comment's text is a quoted string, and this exporter emits+/// comments in single quotes because A.2.2.2 makes the single quote the string+/// delimiter. A strict reading of "does not use quoted strings" would exclude+/// any file carrying a comment at all. The CLIF files ISO hosts for ISO/IEC+/// 21838-2 are in the same position, using single quotes only inside comment+/// headers, so the precedent is the same; the limit is written down here+/// rather than left for a reader to assume away.+///+/// Nothing here is claimed about the second edition's Annex A.3, which nobody+/// on this project has read.+#[test]+fn clif_stays_in_the_exactly_conformant_subdialect() {+ let problem = FolProblem::build(&corpus(), Some(&OwlAxiom::SubClass(c("A"), c("B"))))+ .expect("translates");++ for dialect in [ClifDialect::Iso, ClifDialect::Colore] {+ let text = problem.to_clif(dialect, ClifComments::Standalone, TEXT_NAME);+ let Sexp::List(items) = read_sexp(&text) else {+ panic!("the whole file is one form")+ };+ let comment_op = Sexp::Atom(+ if dialect == ClifDialect::Iso { "cl:comment" } else { "cl-comment" }.to_string(),+ );+ let mut checked = 0usize;+ for phrase in &items[2..] {+ if matches!(phrase, Sexp::List(xs) if xs.first() == Some(&comment_op)) {+ continue; // the named exception, and only here+ }+ checked += 1;+ check_no_interpreted_names(phrase);+ }+ assert!(checked > 0, "some sentence was checked in the {dialect:?} dialect");+ }+}++/// No decimal numeral and no single-quoted string anywhere in a sentence.+fn check_no_interpreted_names(s: &Sexp) {+ match s {+ Sexp::Atom(a) => {+ assert!(+ !a.starts_with('\''),+ "a single-quoted string is an INTERPRETED name and takes the text out of \+ the exactly-conformant subdialect (A.4.2): {a}"+ );+ // A CLIF numeral is a bare decimal. `X0` is a name, not a numeral,+ // because it does not begin with a digit; a quoted name is not a+ // numeral either.+ assert!(+ !a.starts_with('"')+ && !(a.starts_with(|c: char| c.is_ascii_digit())+ && a.chars().all(|c| c.is_ascii_digit() || c == '.'))+ || a.starts_with('"'),+ "a numeral is an INTERPRETED name and takes the text out of the \+ exactly-conformant subdialect (A.4.2): {a}"+ );+ }+ Sexp::List(xs) => xs.iter().for_each(check_no_interpreted_names),+ }+}diff --git a/tools/fol_differential.py b/tools/fol_differential.pynew file mode 100644index 00000000..07fe47e3--- /dev/null+++ b/tools/fol_differential.py@@ -0,0 +1,554 @@+#!/usr/bin/env python3+"""Differential oracle: open-ontologies' entailments against an ATP, over the+translation owl-lean's adequacy theorem is about.++THE ATP IS AN ORACLE, NOT AN AUTHORITY. This is the whole design and it is not+a hedge. A derivation certificate from the forward-chaining reasoner can be+CHECKED, because `lean/` holds a checker whose soundness is a machine-checked+theorem (decision 0002). A superposition refutation cannot: checking one needs+a verified first-order calculus with unification, and no such thing exists in+core Lean. So when E or Vampire answers "Theorem", that is an opinion of+exactly the same standing as pyshacl's verdict in `tools/shacl_differential.py`.+A disagreement is a bug in ONE OF THE TWO and this tool's job is to say so, not+to decide which. Nothing here prints the word "proved", and nothing here treats+either side as ground truth in either direction.++What it does:++ 1. Runs the engine's reasoner with `--certificate`, so every entailment it+ claims is written out as a derived triple.+ 2. Asks the engine to export the ontology and one first-order problem per+ derived triple, in TPTP FOF. The translation happens in Rust, ONCE, under+ the correspondence tests: this script never builds a formula, because a+ formula it built would not be the one the theorem is about.+ 3. Runs an ATP on each problem and compares.++The verdicts, in order of severity:++ CLAIMED_NOT_ENTAILED - the engine derived it, EVERY premise of every derivation+ it found is expressible in the fragment, and the ATP+ still says the negation is satisfiable. The+ stop-the-line case, the analogue of a false clean. One+ of the two is wrong and it must be found.+ WEAKER_EXPORT - the ATP says the negation is satisfiable, and it is+ right to: the engine's derivation rests on a triple the+ fragment cannot express, so the exported theory really+ does not entail the conclusion. Not a bug in either+ side. The missing triple is named. This is the common+ case for data-property assertions and for the+ data-property hierarchy, neither of which+ OwlLean/Syntax.lean has a constructor for.+ READ THE NAMED TRIPLE. This verdict is only as good as+ the expressibility judgement behind it, which is the+ exporter's own `triple_as_axiom`. If that ever refused+ a triple the export does in fact carry, a real bug+ would be filed here instead of under+ CLAIMED_NOT_ENTAILED, so the blocking triple is printed+ rather than summarised away.+ ATP_ERROR - the prover could not read the file. A defect in the+ exporter until shown otherwise.+ UNDETERMINED - the prover ran out of time or gave up. Honest and+ common: the translated theory is usually not decidable+ and a non-entailment often has only infinite+ countermodels. NOT evidence of agreement.+ NOT_ASKED - no axiom form in OwlLean/Syntax.lean corresponds to the+ derived triple, so the question could not be put. The+ exporter lists these; they are reproduced here.+ AGREE - the ATP also finds the conclusion entailed.++Usage:+ python3 tools/fol_differential.py ONTOLOGY.ttl [--json out.json]+ [--profile owl-rl-ext] [--limit N]+ [--timeout S] [--atp eprover|vampire]++Requires an ATP. If none is installed the run SKIPS LOUDLY with the install+line and exits 0, the way the Lean-dependent tests skip on a missing `lake`;+set FOL_DIFF_REQUIRE_ATP=1 to turn that skip into a failure, as+OO_REQUIRE_FIXTURES=1 does in the Rust suite.+"""+import argparse+import json+import os+import pathlib+import re+import shutil+import subprocess+import sys+import tempfile++BIN = os.environ.get(+ "OPEN_ONTOLOGIES_BIN",+ str(pathlib.Path(__file__).resolve().parent.parent / "target" / "release" / "open-ontologies"),+)++# E and Vampire first because both read TPTP FOF natively and both report SZS+# status lines. Prover9 is deliberately NOT probed: it reads LADR, not TPTP,+# and silently treating its input as TPTP would be exactly the kind of+# unnoticed mismatch this tool exists to catch.+ATPS = [+ {+ "name": "eprover",+ "argv": lambda f, t: ["eprover", "--auto", "--tptp3-format", f"--cpu-limit={t}", f],+ "install": "brew install eprover (or apt-get install eprover, or "+ "https://github.com/eprover/eprover)",+ },+ {+ # UNTESTED. Vampire was not installed on the machine this was written+ # on, so this argument vector and the SZS parsing for it come from the+ # documented interface and have never run. Said here rather than+ # discovered by whoever first passes --atp vampire.+ "name": "vampire",+ "argv": lambda f, t: ["vampire", "--mode", "casc", "-t", str(t), f],+ "install": "brew install vampire (or https://github.com/vprover/vampire)",+ },+]++SZS = re.compile(r"SZS status\s+(\w+)")++# OWL-RL derivation chains over a real ontology are deeper than Python's+# default 1000 frames. Raising the limit is cheap; a RecursionError is caught+# and REPORTED rather than swallowed, because a crash that turns into a clean+# verdict is the failure mode this whole tool exists to avoid.+sys.setrecursionlimit(50000)++# The SZS ontology, read for what it means about ENTAILMENT of the conjecture.+# `Theorem` and `ContradictoryAxioms` both mean the conjecture follows: from an+# inconsistent theory everything follows, which is a true entailment and a+# separate problem with the ontology, flagged rather than hidden.+ENTAILED = {"Theorem", "ContradictoryAxioms"}+NOT_ENTAILED = {"CounterSatisfiable", "Satisfiable", "CounterTheorem"}+GAVE_UP = {"ResourceOut", "Timeout", "GaveUp", "Unknown", "InputError", "Incomplete"}+++def detect_atp(preferred=None):+ """Return the first installed ATP, or None. Never guesses at a binary that+ reads a different input language."""+ candidates = ATPS+ if preferred:+ candidates = [a for a in ATPS if a["name"] == preferred]+ if not candidates:+ names = ", ".join(a["name"] for a in ATPS)+ raise SystemExit(f"unknown --atp {preferred!r}; known: {names}")+ for atp in candidates:+ if shutil.which(atp["name"]):+ return atp+ return None+++def skip_loudly(preferred):+ """No ATP. Say so in a way nothing can mistake for a pass."""+ lines = [+ "",+ "=" * 72,+ "SKIPPED_FIXTURE: no automated theorem prover found on PATH.",+ "",+ "This differential is UNTESTED on this machine. That is not agreement",+ "between the engine and an ATP; it is the absence of a second opinion.",+ "",+ "Install one of:",+ ]+ for atp in ATPS:+ if preferred and atp["name"] != preferred:+ continue+ lines.append(f" {atp['name']:<10} {atp['install']}")+ lines += [+ "",+ "Set FOL_DIFF_REQUIRE_ATP=1 to make a missing prover a failure instead",+ "of a skip, as OO_REQUIRE_FIXTURES=1 does in the Rust suite.",+ "=" * 72,+ "",+ ]+ print("\n".join(lines), flush=True)+ if os.environ.get("FOL_DIFF_REQUIRE_ATP") == "1":+ print("FOL_DIFF_REQUIRE_ATP=1, so this is a failure, not a skip.", flush=True)+ return 2+ return 0+++def batch(store, script, timeout):+ """One batch run. The store is in-memory per process, so load and use must+ share an invocation."""+ proc = subprocess.run(+ [BIN, "--no-connect", "--data-dir", str(store), "batch", "-"],+ input=script, capture_output=True, text=True, timeout=timeout,+ env=dict(os.environ, OPEN_ONTOLOGIES_STORAGE_MODE="persistent"),+ )+ results = {}+ for line in proc.stdout.splitlines():+ try:+ row = json.loads(line)+ except json.JSONDecodeError:+ continue+ if "command" in row:+ results[row["command"]] = row.get("result", {})+ return results, proc+++def run_engine(ontology, workdir, profile, timeout):+ """Reason with a certificate, then export from a SEPARATE, UNREASONED store.++ TWO runs, and the separation is the whole point. `reason` materialises its+ inferences into the default graph, so an export from the same store would+ contain the derived triples as ASSERTED axioms and every conjecture would+ be entailed by the trivial argument that the theory already states it. That+ is a differential that cannot fail, which is worse than no differential:+ it was this tool's first shape and a deliberately broken exporter still+ scored a clean run. The certificate is taken from run A, the axioms from+ run B, over the graph as loaded.++ Every formula is built by the Rust exporter; this script constructs no+ logic of its own, because a formula it built would not be the one the+ adequacy theorem is about.+ """+ cert = workdir / "cert"+ fol = workdir / "fol"++ reasoned, proc_a = batch(+ workdir / "store_reason",+ f"load {ontology}\nreason --profile {profile} --certificate {cert}\n",+ timeout,+ )+ if "error" in reasoned.get("reason", {}):+ raise SystemExit("reasoning failed:\n" + json.dumps(reasoned, indent=1)[:2000])++ # Run B loads the certificate's OWN asserted graph rather than the source+ # file again. Two reasons, and the second is not obvious.+ #+ # * It is exactly the graph the reasoner started from, so the axioms the+ # prover sees and the premises the engine used are the same triples.+ # * Blank node labels are not stable across loads. A derived triple like+ # `x rdf:type _:b12` names an anonymous class expression, and reloading+ # the Turtle would relabel it, so the goal would name a node the export+ # had never heard of. Every restriction-valued inference would come back+ # NOT_ASKED, which reads as a limitation of the fragment when it is+ # really an artefact of loading twice.+ #+ # asserted.tsv is `s TAB p TAB o` in N-Triples term spelling, so joining+ # the columns with spaces and appending a full stop IS N-Triples.+ asserted_nt = workdir / "asserted.nt"+ with open(cert / "asserted.tsv") as src, open(asserted_nt, "w") as dst:+ for line in src:+ cols = line.rstrip("\n").split("\t")+ if len(cols) == 3:+ dst.write(" ".join(cols) + " .\n")++ # Everything that appears anywhere in the certificate, asked as a goal in+ # its own right. The exporter's `not_asked` list is then the exact set of+ # triples the fragment cannot express, decided by the exporter rather than+ # guessed at here.+ every = workdir / "every.tsv"+ seen = set()+ with open(cert / "derivations.tsv") as src, open(every, "w") as dst:+ for line in src:+ cols = line.rstrip("\n").split("\t")[1:]+ for i in range(0, len(cols) - 2, 3):+ t = tuple(cols[i:i + 3])+ if len(t) == 3 and t not in seen:+ seen.add(t)+ dst.write("\t".join(t) + "\n")+ with open(cert / "asserted.tsv") as src, open(every, "a") as dst:+ for line in src:+ t = tuple(line.rstrip("\n").split("\t"))+ if len(t) == 3 and t not in seen:+ seen.add(t)+ dst.write("\t".join(t) + "\n")++ exported, proc_b = batch(+ workdir / "store_export",+ f"load {asserted_nt}\n"+ f"fol --out {fol} --format tptp --goals {cert}/derivations.tsv "+ f"--goals-skip-columns 1\n"+ f"fol --out {fol}_all --format tptp --goals {every} --goals-skip-columns 0\n",+ timeout,+ )+ if "fol" not in exported or "error" in exported.get("fol", {}):+ raise SystemExit(+ "the engine did not produce an export:\n"+ + json.dumps(exported, indent=1)[:2000]+ + "\n"+ + (proc_a.stderr + proc_b.stderr)[:2000]+ )++ # The export must be over the ASSERTED graph. `asserted` in the certificate+ # is the triple count the reasoner started from; `initial_triples` is what+ # the exporter saw. If they differ, the export is over a materialised store+ # and every AGREE below would be vacuous. Abort rather than report.+ asserted = reasoned["reason"].get("certificate", {}).get("asserted")+ seen = exported["fol"].get("initial_triples")+ if asserted is not None and seen is not None and asserted != seen:+ raise SystemExit(+ f"the export saw {seen} triples and the reasoner started from {asserted}. "+ "The exporter is looking at a materialised store, so every conjecture would "+ "be entailed by the theory already stating it. Refusing to report a "+ "differential that cannot fail."+ )++ results = dict(reasoned)+ results.update(exported)+ return results, fol, cert, pathlib.Path(str(fol) + "_all")+++def load_derivations(path):+ """conclusion triple -> list of premise lists, from derivations.tsv.++ Each line is `rule TAB s TAB p TAB o` for the conclusion, then the premises+ as further triples.+ """+ out = {}+ with open(path) as fh:+ for line in fh:+ cols = line.rstrip("\n").split("\t")+ if len(cols) < 4 or (len(cols) - 1) % 3 != 0:+ continue+ terms = cols[1:]+ triples = [tuple(terms[i:i + 3]) for i in range(0, len(terms), 3)]+ out.setdefault(triples[0], []).append(triples[1:])+ return out+++def unreachable_premise(goal, derivations, expressible, asserted):+ """Return a triple that blocks every derivation of `goal`, or None.++ A conclusion is reachable in the exported theory when it is an asserted+ triple the fragment can express, or when some derivation of it has every+ premise reachable. This is the exact question, not a heuristic: if no+ derivation the engine found has all its leaves expressible, the exported+ theory genuinely does not entail the conclusion and the prover is right to+ say so.++ The memoisation is sound because the certificate is acyclic by+ construction: decision 0002 requires every premise of a step to be asserted+ or concluded by an EARLIER step, and `lake exe oo-cert` rejects a+ certificate where that fails. The in-progress guard below is belt and+ braces, and it cuts conservatively (a cycle counts as unreachable on that+ path) rather than looping.+ """+ state = {}+ blocker = {}++ def reach(t, stack):+ if t in state:+ return state[t]+ if t in stack:+ return False # a cycle proves nothing on its own+ if t in asserted and t in expressible:+ state[t] = True+ return True+ stack = stack | {t}+ for premises in derivations.get(t, []):+ bad = next((q for q in premises if not reach(q, stack)), None)+ if bad is None:+ state[t] = True+ return True+ blocker.setdefault(t, bad)+ state[t] = False+ if t not in blocker and t in asserted:+ blocker[t] = t # asserted but not expressible+ return False++ if reach(goal, frozenset()):+ return None+ # Walk down to the deepest named blocker, which is the one worth reporting.+ seen, cur = set(), goal+ while cur in blocker and cur not in seen:+ seen.add(cur)+ nxt = blocker[cur]+ if nxt == cur:+ break+ cur = nxt+ return cur+++def ask(atp, problem, timeout):+ """Run the prover and return (szs_status, detail). Never raises."""+ try:+ proc = subprocess.run(+ atp["argv"](str(problem), timeout),+ capture_output=True, text=True, timeout=timeout + 15,+ )+ except subprocess.TimeoutExpired:+ return "Timeout", f"{atp['name']} exceeded {timeout + 15}s wall clock"+ except OSError as exc:+ return "InputError", f"{type(exc).__name__}: {exc}"+ text = proc.stdout + proc.stderr+ found = SZS.findall(text)+ if not found:+ tail = text.strip().splitlines()[-3:]+ return "InputError", "no SZS status line: " + " / ".join(tail)[:300]+ # The LAST status is the verdict; E prints an input status first.+ return found[-1], ""+++def classify(status):+ """Map an SZS status to a verdict. Order matters: the claimed-but-refuted+ case is checked first, and nothing collapses a give-up into agreement."""+ if status in ENTAILED:+ if status == "ContradictoryAxioms":+ return "AGREE", (+ "entailed, but the ATP found the AXIOMS contradictory, so "+ "everything is entailed. That is a defect in the ontology or in "+ "the translation of it, not a confirmation of this inference"+ )+ return "AGREE", "the ATP also finds the conclusion entailed"+ if status in NOT_ENTAILED:+ return "CLAIMED_NOT_ENTAILED", (+ f"the engine derived this triple; the ATP reports SZS {status}, i.e. a "+ "model of the axioms and the negated conclusion. One of the two is "+ "wrong. This tool does not say which: an ATP verdict is an oracle "+ "opinion, and the engine's own derivation certificate is the thing "+ "that CAN be checked (lake exe oo-cert)"+ )+ if status in GAVE_UP:+ return "UNDETERMINED", (+ f"SZS {status}: no verdict. The translated theory is not decidable in "+ "general and a non-entailment often has only infinite countermodels, "+ "so this is expected and is NOT agreement"+ )+ return "ATP_ERROR", f"unhandled SZS status {status}"+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("ontology")+ ap.add_argument("--profile", default="owl-rl-ext")+ ap.add_argument("--atp", help="force a prover instead of taking the first installed")+ ap.add_argument("--timeout", type=int, default=int(os.environ.get("FOL_DIFF_TIMEOUT", 10)),+ help="per-problem CPU limit in seconds (default 10)")+ ap.add_argument("--limit", type=int, help="only ask the first N goals")+ ap.add_argument("--json")+ args = ap.parse_args()++ atp = detect_atp(args.atp)+ if atp is None:+ return skip_loudly(args.atp)+ print(f"ATP: {atp['name']} (an ORACLE, not an authority)", flush=True)++ if not os.path.exists(BIN):+ raise SystemExit(+ f"engine binary not found at {BIN}. Build it with `cargo build --release`, "+ "or set OPEN_ONTOLOGIES_BIN."+ )++ with tempfile.TemporaryDirectory() as tmp:+ workdir = pathlib.Path(tmp)+ engine, fol_dir, cert_dir, all_dir = run_engine(+ args.ontology, workdir, args.profile, 600+ )+ export = engine["fol"]+ reasoned = engine.get("reason", {})++ print(+ f"engine: {reasoned.get('inferred_count', '?')} inference(s) under "+ f"{args.profile}; exported {export['axioms_exported']} axiom(s), "+ f"{export['individual_typing_axioms']} individual typing axiom(s), "+ f"{export['goal_problems']} goal problem(s)",+ flush=True,+ )+ if export.get("exports_a_weaker_axiom_set"):+ print(+ " NOTE: the export is a WEAKER axiom set than the ontology. The "+ "prover is being asked about less than the ontology says:",+ flush=True,+ )+ for d in export.get("constructs_not_exported", []):+ print(f" {d['construct']} x{d['occurrences']}: {d['why']}", flush=True)++ manifest = json.loads((fol_dir / "goals.json").read_text())+ goals = manifest["goals"]+ not_asked = manifest["not_asked"]+ if args.limit:+ goals = goals[: args.limit]++ all_manifest = json.loads((all_dir / "goals.json").read_text())+ inexpressible = {tuple(n["triple"]) for n in all_manifest["not_asked"]}+ expressible = {tuple(g["triple"]) for g in all_manifest["goals"]}+ derivations = load_derivations(cert_dir / "derivations.tsv")+ asserted = set()+ with open(cert_dir / "asserted.tsv") as fh:+ for line in fh:+ t = tuple(line.rstrip("\n").split("\t"))+ if len(t) == 3:+ asserted.add(t)+ print(+ f"fragment: {len(expressible)} of {len(expressible) + len(inexpressible)} "+ f"certificate triples are expressible in OwlLean/Syntax.lean",+ flush=True,+ )++ rows = []+ for g in goals:+ status, detail = ask(atp, fol_dir / "goals" / g["file"], args.timeout)+ verdict, why = classify(status)+ if verdict == "CLAIMED_NOT_ENTAILED":+ try:+ blocker = unreachable_premise(+ tuple(g["triple"]), derivations, expressible, asserted+ )+ except RecursionError:+ blocker = None+ why += (+ ". NOTE: the derivation chain was too deep to walk, so this row "+ "was NOT checked for the weaker-export case and may be one"+ )+ if blocker is not None:+ verdict = "WEAKER_EXPORT"+ why = (+ "the prover is right and neither side is wrong: every derivation "+ "the engine found for this triple rests on "+ f"`{' '.join(blocker)}`, which OwlLean/Syntax.lean has no "+ "constructor for, so the EXPORTED theory does not entail the "+ "conclusion even though the ontology does. This is what "+ "exports_a_weaker_axiom_set means, made concrete"+ )+ if detail:+ why = f"{why} ({detail})" if why else detail+ triple = " ".join(g["triple"])+ rows.append({+ "file": g["file"], "triple": g["triple"], "axiom_form": g["axiom_form"],+ "szs": status, "verdict": verdict, "detail": why,+ })+ print(f"{verdict:<22} {triple}\n{'':<22} {why}", flush=True)++ for n in not_asked:+ print(f"{'NOT_ASKED':<22} {' '.join(n['triple'])}\n{'':<22} {n['why']}", flush=True)++ counts = {}+ for r in rows:+ counts[r["verdict"]] = counts.get(r["verdict"], 0) + 1+ counts["NOT_ASKED"] = len(not_asked)++ print("\n" + "=" * 72)+ print(f"{len(rows)} entailment(s) put to {atp['name']}, {len(not_asked)} not askable")+ for kind in ("CLAIMED_NOT_ENTAILED", "ATP_ERROR", "WEAKER_EXPORT", "UNDETERMINED",+ "NOT_ASKED", "AGREE"):+ if counts.get(kind):+ print(f" {kind:<22} {counts[kind]}")+ print(+ "\nAn ATP verdict is an ORACLE OPINION and never a certificate. AGREE means a "+ "second implementation\nreached the same conclusion, not that anything was proved: "+ "checking a superposition refutation\nneeds a verified first-order calculus with "+ "unification, which does not exist in core Lean.\nThe engine's own derivation "+ "certificate is the artefact that CAN be checked, with\n`cd lean && lake exe oo-cert`."+ )+ if counts.get("WEAKER_EXPORT"):+ print(+ "\nWEAKER_EXPORT is not a defect in the engine or in the prover. It is the "+ "fragment:\nthe engine's derivation uses a triple OwlLean/Syntax.lean cannot "+ "express, so the exported\ntheory really is weaker than the ontology. Each row "+ "names the triple. Check that the\nnamed triple is one the fragment genuinely "+ "lacks, because this verdict rests on the\nexporter's own judgement of what it "+ "can express."+ )++ if args.json:+ with open(args.json, "w") as fh:+ json.dump({"atp": atp["name"], "rows": rows, "not_asked": not_asked,+ "counts": counts}, fh, indent=1)++ # A conclusion the engine claims and the ATP refutes is the one result that+ # must fail a pipeline. An undetermined run is not a pass and not a failure.+ return 1 if counts.get("CLAIMED_NOT_ENTAILED") or counts.get("ATP_ERROR") else 0+++if __name__ == "__main__":+ sys.exit(main())