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
Emit CNF for the clausal fragment, and close decision 0005's chain on it (#226)
Fabio Rovai1e07f850e996
diff --git a/src/main.rs b/src/main.rsindex f02e51ea..7939eaab 100644--- a/src/main.rs+++ b/src/main.rs@@ -501,7 +501,9 @@ enum Commands {/// checker `oo-folmodel` reads, with its digest in the report.#[arg(long)]out: String,- /// `tptp` (FOF, what provers read), `clif` or `cgif` (two of ISO/IEC+ /// `tptp` (FOF, what provers read), `cnf` (the same theory already in clauses, so a+ /// prover's refutation can be checked by `oo-fores`; refused outside OWL 2 RL's clausal+ /// fragment), `clif` or `cgif` (two of ISO/IEC/// 24707 Common Logic's three dialects, both restricted to the/// first-order-equivalent fragment), `smtlib` (SMT-LIB 2, what Z3/// reads) or `ladr` (what Mace4 reads, with every symbol MANGLED anddiff --git a/src/tptp.rs b/src/tptp.rsindex 3d2ce002..68d8784e 100644--- a/src/tptp.rs+++ b/src/tptp.rs@@ -992,6 +992,73 @@ impl FolProblem {s}+ /// The one Skolem constant this renderer introduces.+ ///+ /// `background_2` is `∃X. thing(X)`, the non-empty-domain axiom, and it is+ /// a CLOSED existential, so a single constant witnesses it. Every other+ /// formula is relativised to `thing`, so the axiom cannot simply be+ /// dropped: an empty `thing` would satisfy the rest vacuously. It is the+ /// same constant in every export, it is named so that it reads as what it+ /// is, and it is the ONLY Skolemisation in this file.+ pub const DOMAIN_WITNESS: &'static str = "$domain_witness";++ /// TPTP CNF, for the clausal fragment only.+ ///+ /// Refuses, naming the axioms, when any formula needs a Skolem function.+ /// That is `someValuesFrom` in superclass position, which OWL 2 RL forbids+ /// and OWL DL permits; measured over three real exports it was 0 of 1,423+ /// formulas in an RL ontology and 126 of 426 in a DL one. Clausifying+ /// those would need a Skolemisation theorem nobody has proved here, so+ /// the FOF path stays the right one for them and this one says so.+ ///+ /// The conjecture is negated ONCE and emitted as `negated_conjecture`,+ /// the way `checker_entries` negates it for the model direction.+ pub fn to_cnf(&self) -> anyhow::Result<String> {+ let witness = Term::Const(Self::DOMAIN_WITNESS.to_string());+ let mut named: Vec<(String, String, Form)> = Vec::new();+ for (name, role, f) in self.formulas() {+ // `background_2` gets a readable witness name; every other closed+ // existential, which in practice means the negated goal, gets a+ // constant named after its formula by `skolem_constants`.+ let f = match (name.as_str(), f) {+ ("background_2", Form::Ex(n, body)) => subst_var(*n, &witness, body),+ _ => f.clone(),+ };+ let (role, f) = if role == "conjecture" {+ ("negated_conjecture".to_string(), Form::neg(f))+ } else {+ (role.to_string(), f)+ };+ named.push((name, role, f));+ }+ let plain: Vec<(String, Form)> = named.iter().map(|(n, _, f)| (n.clone(), f.clone())).collect();+ if let Fragment::NeedsSkolem(axioms) = fragment(&plain) {+ anyhow::bail!(+ "this ontology is outside the clausal fragment: {} of its {} formulas need a \+ Skolem FUNCTION ({}{}), an existential under a universal. That is what \+ `someValuesFrom` in superclass position exports as, and OWL 2 RL forbids it. \+ A closed existential (the domain axiom, a negated universal goal) needs only a \+ constant and is handled; this needs a function of the bound variable, and \+ nothing here proves that Skolemisation. Export as `tptp` instead; a prover's \+ refutation of it is an oracle opinion, and `cnf` will not pretend otherwise.",+ axioms.len(),+ named.len(),+ axioms.iter().take(3).cloned().collect::<Vec<_>>().join(", "),+ if axioms.len() > 3 { ", …" } else { "" }+ );+ }+ let mut s = String::new();+ s.push_str(&header("%", self.conjecture.is_some(), TPTP_STYLE));+ s.push_str("% CNF. Every formula is a clause, so a prover's refutation of this file is\n");+ s.push_str("% resolution end to end and can be checked by oo-fores (Fo.unsat_of_check).\n");+ s.push_str(&format!(+ "% One Skolem constant, '{}', witnesses the non-empty domain (background_2).\n",+ sym::constant(Self::DOMAIN_WITNESS)+ ));+ s.push_str(&cnf_records(&named).expect("fragment() said every formula is clausal"));+ Ok(s)+ }+/// ISO/IEC 24707 CLIF, restricted to the first-order-equivalent fragment.////// Everything in the file is CLIF: there are no lexical comments, because@@ -1516,6 +1583,225 @@ pub mod fof {}}+// ── The clausal fragment, and CNF for it ────────────────────────────────────+//+// Decision 0005 says a superposition refutation cannot be certified because it+// needs a verified first-order calculus with unification. `lean/Fo` now has the+// resolution half of one, and `tstp::to_fo_certificate` feeds it a prover's+// derivation. The gap that remained was CLAUSIFICATION: a prover handed `fof`+// clausifies before it resolves, and clausification is not resolution, so the+// translation reached nothing. Measured on real exports, a FOF problem+// translated 0 of 8 steps and the same problem as CNF translated 2 of 2.+//+// The fix is not to clausify better. It is to NOT MAKE THE PROVER DO IT, and+// the measurement says when that is free.+//+// ## What needs a Skolem function, and what does not+//+// Measured over three exported ontologies, 1,905 formulas:+//+// * `? [X0] : thing(X0)` — the non-empty-domain axiom. Exactly one per+// export, always the same formula, never derived from an ontology axiom.+// * `someValuesFrom` in SUPERCLASS position, `A ⊑ ∃r.B`. 126 in an OWL DL+// ontology, ZERO in both OWL 2 RL ones.+// * Everything else — 1,422 of 1,423 in one of them — has no existential at+// all, so there is nothing to Skolemise.+//+// That zero is not luck. **OWL 2 RL forbids an existential restriction in+// superclass position**, because it is not clausal. So for the profile this+// engine's certificate layer already covers, clausification is NNF plus+// distribution: a truth-preserving EQUIVALENCE, needing no Skolemisation+// theorem and no argument about choice over models.+//+// So the exporter asks which fragment it is in and says so, rather than+// promising CNF it cannot always give.++/// Which fragment an axiom set falls in, and therefore whether a refutation+/// over it can be certified end to end.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Fragment {+ /// No existential survives negation-normalisation, so the axioms are+ /// clauses after distribution and no Skolem function is needed.+ Clausal,+ /// At least one axiom needs a Skolem function. Named, because a reader is+ /// entitled to know WHICH axiom cost them the certificate.+ NeedsSkolem(Vec<String>),+}++/// Push negations inward. The result uses `Neg` only on atoms, and `Imp` not+/// at all.+fn nnf(f: &Form) -> Form {+ match f {+ Form::App1(..) | Form::App2(..) | Form::Eq(..) | Form::Tru | Form::Fls => f.clone(),+ Form::And(a, b) => Form::and(nnf(a), nnf(b)),+ Form::Or(a, b) => Form::or(nnf(a), nnf(b)),+ Form::Imp(a, b) => Form::or(nnf_neg(a), nnf(b)),+ Form::All(n, g) => Form::All(*n, Box::new(nnf(g))),+ Form::Ex(n, g) => Form::Ex(*n, Box::new(nnf(g))),+ Form::Neg(g) => nnf_neg(g),+ }+}++/// The negation of `f`, in negation normal form.+fn nnf_neg(f: &Form) -> Form {+ match f {+ Form::App1(..) | Form::App2(..) | Form::Eq(..) => Form::neg(f.clone()),+ Form::Tru => Form::Fls,+ Form::Fls => Form::Tru,+ Form::Neg(g) => nnf(g),+ Form::And(a, b) => Form::or(nnf_neg(a), nnf_neg(b)),+ Form::Or(a, b) => Form::and(nnf_neg(a), nnf_neg(b)),+ // ¬(a ⇒ b) is a ∧ ¬b.+ Form::Imp(a, b) => Form::and(nnf(a), nnf_neg(b)),+ Form::All(n, g) => Form::Ex(*n, Box::new(nnf_neg(g))),+ Form::Ex(n, g) => Form::All(*n, Box::new(nnf_neg(g))),+ }+}++fn has_ex(f: &Form) -> bool {+ match f {+ Form::Ex(..) => true,+ Form::App1(..) | Form::App2(..) | Form::Eq(..) | Form::Tru | Form::Fls => false,+ Form::Neg(g) | Form::All(_, g) => has_ex(g),+ Form::And(a, b) | Form::Or(a, b) | Form::Imp(a, b) => has_ex(a) || has_ex(b),+ }+}++/// A literal of a clause, kept as a `Form` that is an atom or a negated atom.+type CnfLit = Form;++/// Distribute `∨` over `∧` on a quantifier-free NNF matrix.+///+/// Returns one `Vec<CnfLit>` per clause. `$true` makes a clause a tautology and+/// the clause is dropped; `$false` is dropped from a clause, and a clause with+/// nothing left is the EMPTY clause, which is kept because it means something.+fn distribute(f: &Form) -> Vec<Vec<CnfLit>> {+ match f {+ Form::And(a, b) => {+ let mut out = distribute(a);+ out.extend(distribute(b));+ out+ }+ Form::Or(a, b) => {+ let (l, r) = (distribute(a), distribute(b));+ let mut out = Vec::with_capacity(l.len() * r.len());+ for x in &l {+ for y in &r {+ let mut c = x.clone();+ c.extend(y.iter().cloned());+ out.push(c);+ }+ }+ out+ }+ Form::All(_, g) => distribute(g),+ Form::Fls => vec![vec![]],+ Form::Tru => vec![vec![Form::Tru]],+ atom => vec![vec![atom.clone()]],+ }+}++/// Is this clause a tautology, by carrying `$true` or a complementary pair?+fn tautological(c: &[CnfLit]) -> bool {+ if c.iter().any(|l| matches!(l, Form::Tru)) {+ return true;+ }+ for l in c {+ if let Form::Neg(inner) = l+ && c.iter().any(|m| m == inner.as_ref())+ {+ return true;+ }+ }+ false+}++/// Strip a CLOSED existential prefix, one fresh constant per variable.+///+/// This is the whole of the Skolemisation this file performs, and the line it+/// draws is the line between a Skolem CONSTANT and a Skolem FUNCTION. An+/// existential at the top of a closed formula depends on nothing, so a fresh+/// constant witnesses it, and the argument is one sentence: any model of+/// `∃X. φ` interprets the constant as the witness. An existential UNDER a+/// universal depends on that universal's variable and needs a function of it,+/// and that argument is the one nobody has proved here, so it is refused.+///+/// Two things in an export are closed existentials: `background_2`, which is+/// `∃X. thing(X)`, and every NEGATED universal conjecture, because+/// `¬∀X.(A ⇒ B)` is `∃X.(A ∧ ¬B)`. Measured on a real refutation, Vampire's own+/// proof of the FOF form carried exactly one `skolemize` step, and it was this.+fn skolem_constants(name: &str, f: Form) -> Form {+ let mut f = f;+ loop {+ match f {+ Form::Ex(n, body) => {+ let c = Term::Const(format!("$sk_{name}_X{n}"));+ f = subst_var(n, &c, &body);+ }+ other => return other,+ }+ }+}++/// Turn one formula into clauses, or say it needs a Skolem function.+///+/// No Skolemisation at all here: this is the pure question "is it already+/// clausal". `clauses_of_closed` is the one that introduces constants.+pub fn clauses_of(f: &Form) -> Option<Vec<Vec<Form>>> {+ let n = nnf(f);+ if has_ex(&n) {+ return None;+ }+ let mut out: Vec<Vec<Form>> = Vec::new();+ for mut c in distribute(&n) {+ if tautological(&c) {+ continue;+ }+ c.retain(|l| !matches!(l, Form::Fls));+ c.dedup();+ out.push(c);+ }+ Some(out)+}++/// Clauses of a closed formula, introducing constants for a leading+/// existential prefix and refusing only an existential that survives under a+/// universal.+pub fn clauses_of_closed(name: &str, f: &Form) -> Option<Vec<Vec<Form>>> {+ clauses_of(&skolem_constants(name, nnf(f)))+}++/// Which fragment a whole problem is in.+pub fn fragment(named: &[(String, Form)]) -> Fragment {+ let bad: Vec<String> = named+ .iter()+ .filter(|(n, f)| clauses_of_closed(n, f).is_none())+ .map(|(n, _)| n.clone())+ .collect();+ if bad.is_empty() { Fragment::Clausal } else { Fragment::NeedsSkolem(bad) }+}++/// Render clauses as TPTP `cnf(...)` records.+///+/// Every clause is separately universally quantified, which is what `cnf` means,+/// so the quantifier prefix is dropped rather than rewritten.+pub fn cnf_records(named: &[(String, String, Form)]) -> Option<String> {+ let mut s = String::new();+ for (name, role, f) in named {+ let cs = clauses_of_closed(name, f)?;+ for (i, c) in cs.iter().enumerate() {+ let body = if c.is_empty() {+ "$false".to_string()+ } else {+ c.iter().map(fof::form).collect::<Vec<_>>().join(" | ")+ };+ let nm = if cs.len() == 1 { name.clone() } else { format!("{name}_{i}") };+ s.push_str(&format!("cnf({nm}, {role}, ({body})).\n"));+ }+ }+ Some(s)+}+// ── Serialiser 2: ISO/IEC 24707 CLIF ────────────────────────────────────────/// Which spelling of the Common Logic operators to emit.@@ -3991,6 +4277,13 @@ pub enum Syntax {Smtlib(smtlib::SmtEncoding),/// LADR, for Mace4. Mangled symbols, the table beside the file.Ladr,+ /// TPTP CNF: the same theory as `Tptp`, already in clauses, so a prover+ /// never clausifies and its refutation is resolution end to end, which is+ /// what `tstp::to_fo_certificate` and `oo-fores` can check. Available ONLY+ /// in the clausal fragment; an ontology with a superclass existential is+ /// refused by name rather than clausified by a Skolemisation nobody+ /// proved.+ Cnf,}impl Syntax {@@ -4005,6 +4298,7 @@ impl Syntax {) -> anyhow::Result<Syntax> {match s.to_ascii_lowercase().as_str() {"tptp" | "fof" | "tptp-fof" => Ok(Syntax::Tptp),+ "cnf" | "tptp-cnf" => Ok(Syntax::Cnf),"clif" | "cl" | "common-logic" => Ok(Syntax::Clif(ClifDialect::parse(dialect.unwrap_or("iso"))?,ClifComments::parse(comments.unwrap_or("standalone"))?,@@ -4020,14 +4314,15 @@ impl Syntax {})),"ladr" | "mace4" | "prover9" => Ok(Syntax::Ladr),other => anyhow::bail!(- "unknown first-order syntax {other:?}; expected `tptp`, `clif`, `cgif`, \- `smtlib` or `ladr`"+ "unknown first-order syntax {other:?}; expected `tptp`, `cnf`, `clif`, \+ `cgif`, `smtlib` or `ladr`"),}}pub fn extension(self) -> &'static str {match self {Syntax::Tptp => "p",+ Syntax::Cnf => "p",Syntax::Clif(..) => "clif",Syntax::Cgif => "cgif",Syntax::Smtlib(_) => "smt2",@@ -4037,6 +4332,7 @@ impl Syntax {pub fn name(self) -> &'static str {match self {Syntax::Tptp => "tptp",+ Syntax::Cnf => "cnf",Syntax::Clif(..) => "clif",Syntax::Cgif => "cgif",Syntax::Smtlib(_) => "smtlib",@@ -4066,6 +4362,7 @@ impl Syntax {fn render(self, problem: &FolProblem, name: &str) -> anyhow::Result<String> {Ok(match self {Syntax::Tptp => problem.to_tptp(),+ Syntax::Cnf => problem.to_cnf()?,Syntax::Clif(d, c) => problem.to_clif(d, c, name),Syntax::Cgif => problem.to_cgif(name)?,Syntax::Smtlib(e) => problem.to_smtlib(e)?,diff --git a/tests/cnf_end_to_end_test.rs b/tests/cnf_end_to_end_test.rsnew file mode 100644index 00000000..bbe7ee36--- /dev/null+++ b/tests/cnf_end_to_end_test.rs@@ -0,0 +1,139 @@+//! Decision 0005's chain, closed for the clausal fragment, on a real ontology.+//!+//! `ies-building-extension.ttl` is exported as CNF with a goal that is two+//! subclass steps deep, Vampire refutes it, the refutation is translated into+//! `lean/Fo`'s format, and `oo-fores` accepts it, discharging+//! `Fo.unsat_of_check`. Every link is a real tool on real output; the test+//! skips cleanly when a tool is absent and asserts hard when it is present.++use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::atomic::{AtomicU64, Ordering};++use open_ontologies::graph::GraphStore;+use open_ontologies::tptp::{export, Syntax};+use open_ontologies::tstp::to_fo_certificate;++static NEXT: AtomicU64 = AtomicU64::new(0);++fn scratch() -> PathBuf {+ let d = std::env::temp_dir().join(format!(+ "oo-cnf-e2e-{}-{}",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::Relaxed)+ ));+ std::fs::create_dir_all(&d).unwrap();+ d+}++fn on_path(name: &str) -> Option<PathBuf> {+ std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(name)).find(|p| p.is_file())+}++fn fores() -> Option<PathBuf> {+ if let Ok(p) = std::env::var("OO_FORES") {+ let p = PathBuf::from(p);+ return p.exists().then_some(p);+ }+ let built = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lean/.lake/build/bin/oo-fores");+ built.exists().then_some(built)+}++const ONTOLOGY: &str = "benchmark/generated/ies-building-extension.ttl";++/// `Building ⊑ BuiltEntity ⊑ ies:Entity`, so the goal is derived, not asserted.+const GOAL: &str = "<http://example.org/ontology/ies-building#Building>\t\+ <http://www.w3.org/2000/01/rdf-schema#subClassOf>\t\+ <http://ies.data.gov.uk/ontology/ies4#Entity>\n";++fn export_with_goal(syntax: Syntax) -> (PathBuf, PathBuf) {+ let ttl = std::fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(ONTOLOGY))+ .expect("the benchmark ontology is in the tree");+ let graph = std::sync::Arc::new(GraphStore::new());+ graph.load_turtle(&ttl, None).expect("turtle parses");+ let dir = scratch();+ let goals = dir.join("goal.tsv");+ std::fs::write(&goals, GOAL).unwrap();+ export(&graph, &dir, syntax, Some(goals.as_path()), 0).expect("export runs");+ let goal_file = dir.join("goals").join("goal_00000.p");+ assert!(goal_file.exists(), "the goal problem must be written for {}", syntax.name());+ (dir, goal_file)+}++fn szs(vampire: &Path, problem: &Path) -> (String, String) {+ let o = Command::new(vampire).arg("--proof").arg("tptp").arg(problem).output().unwrap();+ let text = String::from_utf8_lossy(&o.stdout).into_owned();+ let status = text+ .lines()+ .find_map(|l| l.strip_prefix("% SZS status ").map(|r| r.split_whitespace().next().unwrap_or("").to_string()))+ .unwrap_or_default();+ (status, text)+}++#[test]+fn the_cnf_export_of_a_real_ontology_is_clauses_only() {+ let (_dir, goal) = export_with_goal(Syntax::Cnf);+ let text = std::fs::read_to_string(&goal).unwrap();+ assert!(text.lines().any(|l| l.starts_with("cnf(")), "{}", &text[..text.len().min(400)]);+ assert!(!text.lines().any(|l| l.starts_with("fof(")), "no fof records in a cnf export");+ assert!(!text.contains('?'), "no existential survives; the two closed ones become constants");+ assert!(text.contains("i:$domain_witness"), "background_2's witness constant is named");+ assert!(text.contains("i:$sk_goal_"), "the negated goal's witness constant is named");+ assert!(text.contains("negated_conjecture"), "the goal is negated once and says so");+}++#[test]+fn fof_and_cnf_of_the_same_goal_get_the_same_verdict() {+ // `Theorem` is what Vampire says of a FOF problem with a conjecture and+ // `Unsatisfiable` of a CNF problem whose negated conjecture is asserted.+ // They are one verdict in two dialects, and the two encodings must agree.+ let Some(v) = on_path("vampire") else { return };+ let (_d1, fof) = export_with_goal(Syntax::Tptp);+ let (_d2, cnf) = export_with_goal(Syntax::Cnf);+ let (sf, _) = szs(&v, &fof);+ let (sc, _) = szs(&v, &cnf);+ assert_eq!(sf, "Theorem", "FOF encoding");+ assert_eq!(sc, "Unsatisfiable", "CNF encoding");+}++#[test]+fn vampires_refutation_of_the_cnf_export_is_checked_by_the_lean_theorem() {+ let (Some(v), Some(f)) = (on_path("vampire"), fores()) else { return };+ let (dir, cnf) = export_with_goal(Syntax::Cnf);+ let (status, proof) = szs(&v, &cnf);+ assert_eq!(status, "Unsatisfiable");++ let cert = to_fo_certificate(&proof).expect("the derivation parses");+ assert!(+ cert.untranslated.is_empty(),+ "a CNF problem's refutation is resolution end to end; left out: {:?}",+ cert.untranslated+ );+ assert!(cert.reaches_false, "the certificate must reach the empty clause");++ let cert_path = dir.join("r.cert");+ std::fs::write(&cert_path, &cert.text).unwrap();+ let o = Command::new(f).arg(&cert_path).output().unwrap();+ let out = String::from_utf8_lossy(&o.stdout);+ assert_eq!(o.status.code(), Some(0), "oo-fores refused a real refutation:\n{out}\n{}", cert.text);+ assert!(out.contains(r#""theorem":"Fo.unsat_of_check""#), "{out}");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn the_fof_refutation_of_the_same_goal_does_not_translate_whole() {+ // The control. Same ontology, same goal, FOF encoding: the prover+ // clausifies and Skolemises first, and none of that is resolution, so the+ // certificate must NOT reach the empty clause. This is the measurement+ // that justified building the CNF path at all.+ let Some(v) = on_path("vampire") else { return };+ let (_dir, fof) = export_with_goal(Syntax::Tptp);+ let (_, proof) = szs(&v, &fof);+ let cert = to_fo_certificate(&proof).expect("parses");+ assert!(!cert.reaches_false, "FOF input must leave clausification untranslated");+ assert!(+ cert.untranslated.iter().any(|(_, r)| r.contains("cnf_transformation") || r.contains("skolemi")),+ "the untranslated steps must be named: {:?}",+ cert.untranslated+ );+}diff --git a/tests/cnf_fragment_test.rs b/tests/cnf_fragment_test.rsnew file mode 100644index 00000000..ab12079d--- /dev/null+++ b/tests/cnf_fragment_test.rs@@ -0,0 +1,199 @@+//! The clausal fragment, and the CNF the exporter can emit for it.+//!+//! The measurement behind this is in `src/tptp.rs`: OWL 2 RL forbids an+//! existential restriction in superclass position, so for the profile this+//! engine certifies, clausification is NNF plus distribution and needs no+//! Skolem function. These tests pin that, and pin the refusal for the profile+//! where it is false.++use open_ontologies::tptp::{clauses_of, cnf_records, fragment, Form, Fragment, P1, Term};++fn c(n: &str) -> P1 {+ P1::Cls(n.to_string())+}++fn atom(n: &str, v: u32) -> Form {+ Form::App1(c(n), Term::Var(v))+}++/// `∀X. A(X) ⇒ B(X)`, the shape almost every RL axiom exports as.+fn subclass() -> Form {+ Form::All(0, Box::new(Form::Imp(Box::new(atom("A", 0)), Box::new(atom("B", 0)))))+}++#[test]+fn an_implication_becomes_one_clause() {+ let cs = clauses_of(&subclass()).expect("no skolem needed");+ assert_eq!(cs.len(), 1, "{cs:?}");+ assert_eq!(cs[0].len(), 2, "¬A ∨ B: {:?}", cs[0]);+}++#[test]+fn a_conjunction_in_the_head_becomes_two_clauses() {+ // ∀X. A(X) ⇒ (B(X) ∧ C(X)) is (¬A ∨ B) ∧ (¬A ∨ C).+ let f = Form::All(+ 0,+ Box::new(Form::Imp(+ Box::new(atom("A", 0)),+ Box::new(Form::And(Box::new(atom("B", 0)), Box::new(atom("C", 0))))),+ ),+ );+ let cs = clauses_of(&f).expect("no skolem needed");+ assert_eq!(cs.len(), 2, "{cs:?}");+}++#[test]+fn a_tautology_is_dropped_rather_than_emitted() {+ // ∀X. A(X) ⇒ A(X) is ¬A ∨ A, which says nothing.+ let f = Form::All(0, Box::new(Form::Imp(Box::new(atom("A", 0)), Box::new(atom("A", 0)))));+ assert_eq!(clauses_of(&f).unwrap().len(), 0);+}++#[test]+fn a_superclass_existential_is_refused_and_named() {+ // ∀X. A(X) ⇒ ∃Y. B(Y). This is `someValuesFrom` in superclass position,+ // it is outside OWL 2 RL, and it needs a Skolem FUNCTION of X.+ let f = Form::All(+ 0,+ Box::new(Form::Imp(+ Box::new(atom("A", 0)),+ Box::new(Form::Ex(1, Box::new(atom("B", 1)))),+ )),+ );+ assert!(clauses_of(&f).is_none(), "an existential head needs Skolemisation");+ match fragment(&[("owl_2_subClassOf".into(), f)]) {+ Fragment::NeedsSkolem(names) => assert_eq!(names, vec!["owl_2_subClassOf".to_string()]),+ other => panic!("expected a refusal naming the axiom, got {other:?}"),+ }+}++#[test]+fn an_existential_in_the_antecedent_is_fine() {+ // ∀X. (∃Y. B(Y)) ⇒ A(X). Moving the negation inward turns that existential+ // into a UNIVERSAL, so nothing needs Skolemising. Refusing it would refuse+ // a formula that is genuinely clausal.+ let f = Form::All(+ 0,+ Box::new(Form::Imp(+ Box::new(Form::Ex(1, Box::new(atom("B", 1)))),+ Box::new(atom("A", 0)),+ )),+ );+ assert!(clauses_of(&f).is_some(), "a negative existential is a universal");+}++#[test]+fn a_doubly_negated_existential_in_the_antecedent_still_needs_skolem() {+ // ∀X. (¬∃Y. B(Y)) ⇒ A(X) is (∃Y. B(Y)) ∨ A(X): the existential comes out+ // POSITIVE and does need a Skolem function. Easy to get backwards, so it+ // is pinned rather than reasoned about each time.+ let f = Form::All(+ 0,+ Box::new(Form::Imp(+ Box::new(Form::Neg(Box::new(Form::Ex(1, Box::new(atom("B", 1)))))),+ Box::new(atom("A", 0)),+ )),+ );+ assert!(clauses_of(&f).is_none());+}++#[test]+fn a_clausal_problem_renders_as_cnf_records() {+ let out = cnf_records(&[("ax1".into(), "axiom".into(), subclass())]).expect("clausal");+ assert!(out.starts_with("cnf(ax1, axiom, ("), "{out}");+ assert!(out.contains(" | "), "a two-literal clause: {out}");+ assert!(!out.contains('!'), "cnf records carry no quantifier prefix: {out}");+}++#[test]+fn the_domain_axiom_is_the_one_existential_that_is_not_a_restriction() {+ // `∃X. thing(X)`, the non-empty-domain axiom, is a CLOSED existential. It+ // needs one fixed Skolem CONSTANT, not a function of anything, and it is+ // the same formula in every export. It is still refused here, because+ // this function does no Skolemisation at all: what to do about it is the+ // exporter's decision and is recorded there, not hidden in a rewrite.+ let f = Form::Ex(0, Box::new(Form::App1(P1::Thing, Term::Var(0))));+ assert!(clauses_of(&f).is_none());+}++// ── to_cnf on a whole problem ───────────────────────────────────────────────++use open_ontologies::tptp::FolProblem;++fn problem(axioms: Vec<Form>, conjecture: Option<Form>) -> FolProblem {+ FolProblem {+ background: open_ontologies::tptp::Translation::background(),+ ind_axioms: vec![],+ axioms: axioms.into_iter().enumerate().map(|(i, f)| (format!("a{i}"), f)).collect(),+ conjecture: conjecture.map(|f| ("goal".to_string(), f)),+ individuals: Default::default(),+ }+}++#[test]+fn to_cnf_witnesses_the_domain_once_and_negates_the_goal_once() {+ let p = problem(vec![subclass()], Some(atom("A", 0)));+ let out = p.to_cnf().expect("clausal");+ // background_2 was `∃X. thing(X)`; it must come out as one ground fact.+ assert!(+ out.contains(&format!("thing('i:{}')", FolProblem::DOMAIN_WITNESS)),+ "the domain axiom must become a single witness fact:\n{out}"+ );+ assert!(!out.contains('?'), "no existential may survive into CNF:\n{out}");+ assert!(!out.contains('!'), "no universal prefix in cnf records:\n{out}");+ // The conjecture is negated ONCE and its role says so.+ assert_eq!(out.matches("negated_conjecture").count(), 1, "{out}");+ assert!(out.contains("cnf(goal_goal, negated_conjecture, (~ "), "{out}");+ // The exact role token, comma-delimited: `negated_conjecture, (` contains+ // the substring `conjecture, (`, so a bare substring test would pass for+ // the wrong reason.+ assert!(!out.contains(", conjecture, ("), "a bare `conjecture` role must not appear:\n{out}");+}++#[test]+fn to_cnf_refuses_outside_the_fragment_and_names_the_axiom() {+ // A ⊑ ∃r.B in superclass position: outside OWL 2 RL, needs a Skolem function.+ let sv = Form::All(+ 0,+ Box::new(Form::Imp(+ Box::new(atom("A", 0)),+ Box::new(Form::Ex(1, Box::new(atom("B", 1)))),+ )),+ );+ let p = problem(vec![subclass(), sv], None);+ let err = p.to_cnf().expect_err("a superclass existential must be refused");+ let msg = err.to_string();+ assert!(msg.contains("owl_2_a1"), "the refusal must name the axiom: {msg}");+ assert!(msg.contains("1 of "), "and count it: {msg}");+ assert!(msg.contains("tptp"), "and point at the format that still works: {msg}");+}++// ── Skolem constants, and only constants ────────────────────────────────────++#[test]+fn a_negated_universal_goal_is_a_closed_existential_and_gets_a_constant() {+ // Goal `∀X. A(X) ⇒ B(X)`. Negated it is `∃X. A(X) ∧ ¬B(X)`, which depends+ // on nothing, so ONE fresh constant witnesses it. Vampire's own FOF proof+ // of such a goal carries exactly one `skolemize` step, and this is it.+ let p = problem(vec![subclass()], Some(subclass()));+ let out = p.to_cnf().expect("a closed existential needs only a constant");+ assert!(out.contains("$sk_goal_goal_X0"), "the witness is named after its formula:\n{out}");+ assert!(!out.contains('?'), "{out}");+ // `A(c) ∧ ¬B(c)` is TWO unit clauses, both negated_conjecture.+ assert_eq!(out.matches("negated_conjecture").count(), 2, "{out}");+}++#[test]+fn an_existential_under_a_universal_still_needs_a_function_and_is_refused() {+ // Unchanged by the constants rule: `∀X. A(X) ⇒ ∃Y. r(X,Y)` needs f(X).+ let sv = Form::All(+ 0,+ Box::new(Form::Imp(+ Box::new(atom("A", 0)),+ Box::new(Form::Ex(1, Box::new(atom("B", 1)))),+ )),+ );+ let err = problem(vec![sv], None).to_cnf().expect_err("needs a Skolem function");+ assert!(err.to_string().contains("Skolem FUNCTION"), "{err}");+ assert!(err.to_string().contains("under a universal"), "{err}");+}