Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

OWL 2 functional syntax files load, including the ORE corpus published as .owl (#311)

Fabio Rovai4a5c90b0b1a3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6646495d..cb947f61 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,20 @@ All notable changes to Open Ontologies are documented here.
### Added
+- **OWL 2 functional syntax loads, whatever the file is called.** `src/ofn.rs`
+ reads OFN into exactly the triples the W3C "OWL 2 Mapping to RDF Graphs"
+ assigns it, and every path that reads a file reaches it: `load`, `validate`,
+ `convert`, `lint`, `batch`, `onto_load` with its compile cache,
+ `onto_validate` and `onto_convert`. A document is OFN when its first token is
+ `Prefix(` or `Ontology(`, so the ORE 2015 reasoner-competition corpus, 1,920
+ OFN files published as `.owl` that all died in the RDF/XML parser, now loads,
+ and `.ofn` is accepted by name. A construct the reader does not translate
+ fails the whole document by name, count and first line, never a silent drop.
+ SWRL `DLSafeRule`s become the `swrl:` vocabulary `onto_rules_import` already
+ reads. Checked against OWL API 4.5.29 on 93 ORE files across the `dl`, `el`
+ and `pure_dl` tracks: all 93 agree once seven documented OWL API habits are
+ undone, and none of the seven is a defect in either reader.
+
- **A named profile hands a client one job's worth of the tool surface** (#263).
A client aligning two vocabularies has no use for most of what this server
registers, and every tool it has no use for is one more chance to call the
diff --git a/CLAUDE.md b/CLAUDE.md
index 99fec653..abd20e78 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -59,7 +59,7 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_query` | To verify structure, answer competency questions, explore the ontology |
| `onto_diff` | To compare against a reference or previous version |
| `onto_save` | To persist the ontology to a file |
-| `onto_convert` | To convert between formats (Turtle, N-Triples, RDF/XML, N-Quads, TriG) |
+| `onto_convert` | To convert between formats (reads Turtle, N-Triples, RDF/XML, N-Quads, TriG, JSON-LD and OWL 2 functional syntax; writes the first five) |
| `onto_clear` | To reset the store before loading a different ontology |
| `onto_marketplace` | To browse and install ontologies: 33 curated W3C/ISO/industry standards plus community packs from the open registry (`community/registry.json`, fetched at runtime; `community=false` for curated/offline only). Curated IDs always win over community IDs |
| `onto_plugin_list` | To discover installed WASM plugins (community `.wasm` tools in `~/.open-ontologies/plugins` or `./plugins`) and the tools each declares. Requires a build with `--features plugins` |
diff --git a/SKILL.md b/SKILL.md
index 22d28c32..96a28c4e 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -152,7 +152,7 @@ For aligning two ontologies:
| `onto_query` | Verify structure, answer competency questions |
| `onto_diff` | Compare against a reference or previous version |
| `onto_save` | Persist ontology to a file |
-| `onto_convert` | Convert between formats (Turtle, N-Triples, RDF/XML, N-Quads, TriG) |
+| `onto_convert` | Convert between formats (reads Turtle, N-Triples, RDF/XML, N-Quads, TriG, JSON-LD and OWL 2 functional syntax; writes the first five) |
| `onto_clear` | Reset the store before loading a different ontology |
| `onto_pull` | Fetch ontology from a remote URL or SPARQL endpoint |
| `onto_push` | Push ontology to a SPARQL endpoint |
diff --git a/docs/interop-with-graph-platforms.md b/docs/interop-with-graph-platforms.md
index fc82e931..73fa5e17 100644
--- a/docs/interop-with-graph-platforms.md
+++ b/docs/interop-with-graph-platforms.md
@@ -53,7 +53,7 @@ standards, so the handoff is a file or a SPARQL endpoint:
| Concern | Shared ground |
|---|---|
-| Serialisation | Turtle, N-Triples, RDF/XML, JSON-LD, TriG |
+| Serialisation | Turtle, N-Triples, RDF/XML, JSON-LD, TriG; OWL 2 functional syntax read |
| Schema | OWL, RDFS, SKOS |
| Constraints | SHACL |
| Provenance | PROV-O (`prov:wasDerivedFrom`) |
diff --git a/docs/tool-reference.md b/docs/tool-reference.md
index 6bed9542..a32e8a1b 100644
--- a/docs/tool-reference.md
+++ b/docs/tool-reference.md
@@ -104,7 +104,7 @@ it withheld.
| `onto_coevolve_dependency_graph` | Build the shape→OWL-dependency map for a SHACL document. |
| `onto_communities` | Detect communities in the loaded entity graph and return a SKELETON per community: size, top members by degree, internal relations, and the bridges connecting it to other communities. |
| `onto_conservative_check` | Does adding these axioms change anything the ontology ALREADY said? Reasons base and base+extension to a fixpoint under one rule table and reports closure(base ∪ extension) minus closure(base), restricted to triples every name of which the base already used. |
-| `onto_convert` | Convert an RDF file between formats: turtle, ntriples, rdfxml, nquads, trig |
+| `onto_convert` | Convert an ontology file to turtle, ntriples, rdfxml, nquads or trig. |
| `onto_cq_run` | Run a batch of competency questions (CQs) against the loaded ontology (#29). |
| `onto_cq_verdicts_list` | List all stored verdicts for a CQ id, most-recent first. |
| `onto_crosswalk` | Look up clinical crosswalk mappings for a code and system (ICD10, SNOMED, MeSH). |
@@ -141,7 +141,7 @@ it withheld.
| `onto_lineage` | Get the compact lineage log for the current or specified session. |
| `onto_lint` | Check an ontology for quality issues: missing labels, comments, domains, ranges |
| `onto_lint_feedback` | Accept or dismiss a lint issue to improve future lint runs. |
-| `onto_load` | Load an RDF file or inline Turtle content into the in-memory ontology store. |
+| `onto_load` | Load an ontology file or inline Turtle content into the in-memory ontology store. |
| `onto_lock` | Lock IRIs to prevent removal during plan/apply. |
| `onto_map` | Generate a mapping config by inspecting a data file's schema against the currently loaded ontology. |
| `onto_marketplace` | Browse and install ontologies from the curated catalogue of 33 W3C/ISO/industry standards plus the open community-pack registry (community/registry.json, fetched at runtime; override with OPEN_ONTOLOGIES_COMMUNITY_REGISTRY). |
diff --git a/skills/ontology-engineering/SKILL.md b/skills/ontology-engineering/SKILL.md
index 16d0d7a0..1b2030b0 100644
--- a/skills/ontology-engineering/SKILL.md
+++ b/skills/ontology-engineering/SKILL.md
@@ -102,7 +102,7 @@ When embeddings exist, `onto_align` automatically uses them as a 7th alignment s
| `onto_query` | Verify structure, answer competency questions |
| `onto_diff` | Compare against a reference or previous version |
| `onto_save` | Persist the active ontology to a file |
-| `onto_convert` | Convert between Turtle, N-Triples, RDF/XML, N-Quads, TriG |
+| `onto_convert` | Convert between formats (reads Turtle, N-Triples, RDF/XML, N-Quads, TriG, JSON-LD and OWL 2 functional syntax; writes the first five) |
| `onto_clear` | Reset the in-memory store |
| `onto_pull` | Fetch ontology from a remote URL or SPARQL endpoint |
| `onto_push` | Push triples to a SPARQL endpoint |
diff --git a/src/graph.rs b/src/graph.rs
index f7b85184..b4dce6ae 100644
--- a/src/graph.rs
+++ b/src/graph.rs
@@ -7,6 +7,14 @@ use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;
+/// How a document is serialised: one of the RDF formats Oxigraph parses, or
+/// OWL 2 functional syntax, which is not RDF and is read by [`crate::ofn`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SourceFormat {
+ Rdf(RdfFormat),
+ OwlFunctional,
+}
+
/// What a parse produced. `statements` counts parser events; `triples` counts
/// distinct triples, which is the size of the resulting graph. They differ
/// whenever the source repeats a statement.
@@ -299,23 +307,42 @@ impl GraphStore {
fn load_file_mode(&self, path: &str, replace: bool) -> anyhow::Result<usize> {
let content = std::fs::read_to_string(path)?;
- let format = Self::detect_format_sniffed(path, &content);
- let reader = Cursor::new(content.as_bytes());
-
- // A document's own location is its default base, per RFC 3986. Without
- // it, any file using relative IRIs fails to parse at all, which is
- // most published RDF/XML: LUBM's generated data would not load a
- // single triple before this.
- let base = Self::file_base_iri(path);
// All or nothing: see load_turtle (issue #93).
- let mut parser = RdfParser::from_format(format);
- if let Some(base) = base {
- parser = parser.with_base_iri(base)?;
- }
- let quads: Vec<_> = parser.for_reader(reader).collect::<Result<_, _>>()?;
+ let quads = Self::parse_document(path, &content)?;
self.store_parsed_quads(&quads, replace)
}
+ /// Parse a whole document, whatever it is serialised as, into quads.
+ ///
+ /// Every path that reads a FILE goes through here (`load_file`,
+ /// `replace_file`, `validate_file`, `content_as_turtle`), so a format this
+ /// engine learns to read is learned once and reaches the CLI, `batch`, the
+ /// MCP tools and the compile cache together. Before the OWL functional
+ /// syntax reader existed each of those called the RDF parser directly, and
+ /// adding a format meant finding all of them.
+ fn parse_document(path: &str, content: &str) -> anyhow::Result<Vec<Quad>> {
+ match Self::detect_source_format(path, content) {
+ SourceFormat::OwlFunctional => Ok(crate::ofn::parse(content)?
+ .into_iter()
+ .map(|t| t.in_graph(GraphName::DefaultGraph))
+ .collect()),
+ SourceFormat::Rdf(format) => {
+ // A document's own location is its default base, per RFC 3986.
+ // Without it, any file using relative IRIs fails to parse at
+ // all, which is most published RDF/XML: LUBM's generated data
+ // would not load a single triple before this. OFN needs none:
+ // its grammar admits only absolute IRIs.
+ let mut parser = RdfParser::from_format(format);
+ if let Some(base) = Self::file_base_iri(path) {
+ parser = parser.with_base_iri(base)?;
+ }
+ Ok(parser
+ .for_reader(Cursor::new(content.as_bytes()))
+ .collect::<Result<_, _>>()?)
+ }
+ }
+ }
+
fn store_parsed_quads(&self, quads: &[Quad], replace: bool) -> anyhow::Result<usize> {
let before = if replace {
0
@@ -361,8 +388,8 @@ impl GraphStore {
/// As `read_as_turtle`, for content already in hand (stdin, for instance).
pub fn content_as_turtle(path_hint: &str, content: String) -> anyhow::Result<String> {
- let format = Self::detect_format_sniffed(path_hint, &content);
- if format == RdfFormat::Turtle {
+ let format = Self::detect_source_format(path_hint, &content);
+ if format == SourceFormat::Rdf(RdfFormat::Turtle) {
if let Some(base) = Self::file_base_iri(path_hint) {
// Keep the default base on the first source line so downstream
// parsers report the document's original line numbers. A later
@@ -374,14 +401,7 @@ impl GraphStore {
let store = Self::new();
{
let inner = &store.store;
- let base = Self::file_base_iri(path_hint);
- let mut parser = RdfParser::from_format(format);
- if let Some(base) = base {
- parser = parser.with_base_iri(base)?;
- }
- let quads: Vec<_> = parser
- .for_reader(Cursor::new(content.as_bytes()))
- .collect::<Result<_, _>>()?;
+ let quads = Self::parse_document(path_hint, &content)?;
for quad in &quads {
inner.insert(quad)?;
}
@@ -391,13 +411,35 @@ impl GraphStore {
pub fn validate_file(path: &str) -> anyhow::Result<ValidationCounts> {
let content = std::fs::read_to_string(path)?;
- let format = Self::detect_format_sniffed(path, &content);
- let reader = Cursor::new(content.as_bytes());
- let mut parser = RdfParser::from_format(format);
- if let Some(base) = Self::file_base_iri(path) {
- parser = parser.with_base_iri(base)?;
+ if let SourceFormat::Rdf(format) = Self::detect_source_format(path, &content) {
+ let reader = Cursor::new(content.as_bytes());
+ let mut parser = RdfParser::from_format(format);
+ if let Some(base) = Self::file_base_iri(path) {
+ parser = parser.with_base_iri(base)?;
+ }
+ return Self::count_parsed(parser.for_reader(reader));
+ }
+ Self::count_ofn(&content)
+ }
+
+ /// Validate text handed over without a file name: the CLI's `validate -`
+ /// and `onto_validate` with `inline: true`. Both used to go straight to
+ /// the Turtle parser, which is right for everything they were written for
+ /// and wrong for an OWL functional-syntax document, which no Turtle parser
+ /// can read. With no extension to go on, the content decides.
+ pub fn validate_text(content: &str) -> anyhow::Result<ValidationCounts> {
+ if crate::ofn::looks_like_ofn(content) {
+ return Self::count_ofn(content);
}
- Self::count_parsed(parser.for_reader(reader))
+ Self::validate_turtle(content)
+ }
+
+ fn count_ofn(content: &str) -> anyhow::Result<ValidationCounts> {
+ Self::count_parsed(
+ crate::ofn::parse(content)?
+ .into_iter()
+ .map(|t| Ok::<_, oxigraph::io::RdfParseError>(t.in_graph(GraphName::DefaultGraph))),
+ )
}
/// A local document's default base is its encoded file URL. Building this
@@ -1275,6 +1317,24 @@ impl GraphStore {
Ok(out)
}
+ /// The serialisation of a document, deciding between the RDF formats
+ /// Oxigraph parses and the one this crate parses itself.
+ ///
+ /// OWL functional syntax wins on content before anything else is
+ /// consulted, because the extension it most often travels under is `.owl`,
+ /// and `.owl` means RDF/XML to [`Self::detect_format`]. The ORE 2015
+ /// reasoner-competition corpus is 1,920 such files and every one of them
+ /// reached the RDF/XML parser and died on its first line. `.ofn` is the
+ /// one extension that names the syntax, so it is honoured even when the
+ /// content does not sniff, which sends a malformed `.ofn` file to the
+ /// reader that can say what is wrong with it.
+ fn detect_source_format(path: &str, content: &str) -> SourceFormat {
+ if crate::ofn::looks_like_ofn(content) || path.to_ascii_lowercase().ends_with(".ofn") {
+ return SourceFormat::OwlFunctional;
+ }
+ SourceFormat::Rdf(Self::detect_format_sniffed(path, content))
+ }
+
fn detect_format(path: &str) -> RdfFormat {
if path.ends_with(".ttl") || path.ends_with(".turtle") {
RdfFormat::Turtle
diff --git a/src/inputs.rs b/src/inputs.rs
index 966e77a5..dbf26ce1 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -5,7 +5,8 @@ use serde::Deserialize;
#[derive(Deserialize, JsonSchema)]
pub struct OntoValidateInput {
- /// Path to an RDF file OR inline Turtle content
+ /// Path to an ontology file (any format onto_load reads, OWL functional
+ /// syntax included) OR inline Turtle or OWL functional-syntax content
pub input: String,
/// If true, treat input as inline content rather than a file path
pub inline: Option<bool>,
@@ -13,7 +14,8 @@ pub struct OntoValidateInput {
#[derive(Deserialize, JsonSchema)]
pub struct OntoConvertInput {
- /// Path to source RDF file
+ /// Path to the source file: any format onto_load reads, OWL functional
+ /// syntax included
pub path: String,
/// Target format: turtle, ntriples, rdfxml, nquads, trig
pub to: String,
@@ -23,7 +25,8 @@ pub struct OntoConvertInput {
#[derive(Deserialize, JsonSchema)]
pub struct OntoLoadInput {
- /// Path to RDF file, OR inline Turtle/RDF content
+ /// Path to an ontology file: Turtle, N-Triples, RDF/XML, N-Quads, TriG,
+ /// JSON-LD or OWL 2 functional syntax
pub path: Option<String>,
/// Inline Turtle content to load (alternative to path)
pub turtle: Option<String>,
diff --git a/src/lib.rs b/src/lib.rs
index 6e7f9d08..903972fd 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -79,6 +79,9 @@ pub mod marketplace;
/// answered, on rmcp 1.4.0 and on 1.8.0 alike.
pub mod mcp_handshake;
pub mod monitor;
+/// OWL 2 Functional-Style Syntax read into the RDF graph the W3C mapping
+/// assigns it, so `.ofn` files and the OFN-under-`.owl` corpora load.
+pub mod ofn;
pub mod ontology;
pub mod ossie;
pub mod plan;
diff --git a/src/main.rs b/src/main.rs
index 544189e9..608ba72c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2553,7 +2553,7 @@ async fn async_main() -> anyhow::Result<()> {
let result = if input == "-" {
let mut buf = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;
- GraphStore::validate_turtle(&buf)
+ GraphStore::validate_text(&buf)
} else {
GraphStore::validate_file(&input)
};
diff --git a/src/ofn.rs b/src/ofn.rs
new file mode 100644
index 00000000..74268c61
--- /dev/null
+++ b/src/ofn.rs
@@ -0,0 +1,1756 @@
+//! OWL 2 Functional-Style Syntax (OFN) read into the RDF graph it denotes.
+//!
+//! # The gap this closes
+//!
+//! Every loader in this crate hands the bytes to an Oxigraph RDF parser, and
+//! OFN is not RDF. It is the syntax the OWL 2 structural specification is
+//! written in and the one the OWL API writes by default, so it is what the
+//! reasoner-evaluation corpora ship: all 1,920 files of the ORE 2015 pool are
+//! OFN under a `.owl` extension. `.owl` was routed to RDF/XML, so every one of
+//! them failed with `Unexpected text event: 'Prefix(owl:='`, and a benchmark
+//! that wanted to run this engine against the competition corpus could not
+//! load a single file of it.
+//!
+//! # What this file produces, and on whose authority
+//!
+//! Triples, and exactly the triples the W3C "OWL 2 Web Ontology Language
+//! Mapping to RDF Graphs (Second Edition)" says an ontology denotes: Table 1
+//! for entities, expressions and axioms, Table 2 for annotations, and Section
+//! 2.3 for axioms that carry annotations. Nothing here decides what an axiom
+//! MEANS. The mapping is a function from the structural syntax to RDF and the
+//! rest of this engine already reads RDF, so the reasoner, the SHACL validator
+//! and every audit see an OFN file as precisely the graph the OWL API would
+//! have written for it, up to the differences catalogued below.
+//!
+//! The tokeniser and parser are written by hand. The established Rust OWL
+//! library is LGPL and this crate is MIT, and the grammar is small enough that
+//! owning it costs less than the licence question.
+//!
+//! # Where the OWL API writes something else, and why this follows the spec
+//!
+//! Measured on a sample of the ORE pool against OWL API 4.5.29's RDF/XML
+//! writer, and pinned on a fixture by `tests/ofn_reader_test.rs`. Each item is
+//! a choice the mapping makes and the OWL API overrides, so none of them is a
+//! defect in this reader, and each is kept because a reader that copied one
+//! writer's habits would be describing that writer and not the ontology. All
+//! seven leave the two graphs equivalent under the direct semantics.
+//!
+//! 1. A cardinality restriction written with an `owl:Thing` (or `rdfs:Literal`)
+//! filler is QUALIFIED in the source and Table 1 maps it to
+//! `owl:minQualifiedCardinality` with `owl:onClass owl:Thing`. The OWL API
+//! stores the unqualified and the `owl:Thing` forms as one object and writes
+//! both unqualified.
+//! 2. `DifferentIndividuals` over more than two individuals is
+//! `owl:AllDifferent` with `owl:members` in Table 1. The OWL API writes the
+//! OWL 1 property `owl:distinctMembers`, which the reverse mapping still
+//! accepts.
+//! 3. The OWL API adds an `rdf:type` triple for every entity in the signature
+//! that the file never declared, so that its own output parses back as OWL 2
+//! DL. Table 1 maps a `Declaration` to a type triple and maps nothing else
+//! to one, so an undeclared entity stays undeclared here. A file that wants
+//! the declaration can write it.
+//! 4. The OWL API types the cells of some lists `rdf:List` (a `DataOneOf`
+//! literal list, a SWRL built-in's argument list). `T(SEQ ...)` in the
+//! mapping is `rdf:first` and `rdf:rest` and nothing else.
+//! 5. For an annotated `DisjointUnion`, `HasKey` or property-chain axiom the
+//! OWL API writes the list twice, once as the main triple's object and once
+//! as the reification's `owl:annotatedTarget`. Section 2.3.1's own HasKey
+//! example names the same `_:y` in both places, and so does this reader.
+//! 6. The OWL API writes some annotated axioms more than once: the reification
+//! of an annotated `EquivalentClasses` link three times, an annotated
+//! `NegativeObjectPropertyAssertion` node twice. One axiom is one
+//! translation here.
+//! 7. The other way round: two axioms that differ only in their annotations
+//! are one axiom with two annotation sets to the OWL API, which writes its
+//! anonymous class expression once and points both reifications at it.
+//! The mapping translates each axiom by itself, so each gets its own blank
+//! node here.
+//!
+//! The OWL API also sorts the operands of set constructors (`ObjectUnionOf`,
+//! `DisjointClasses` and the rest), reorders the atoms of a SWRL body, and
+//! picks its own orientation for binary symmetric axioms (`InverseObjectProperties`,
+//! `EquivalentDataProperties`). This reader keeps the order the source wrote,
+//! which is the only order nobody had to choose.
+//!
+//! # What it refuses, and how
+//!
+//! A construct this reader does not translate is REFUSED BY NAME, LINE AND
+//! COUNT and the whole document fails, never dropped. That is the house rule
+//! `src/rulesyntax.rs` states for rule syntaxes and the reason is the same: an
+//! ontology that silently lost the axioms the reader did not recognise loads,
+//! reasons to a fixpoint and certifies green, about an ontology nobody wrote.
+//! Parsing does not stop at the first refusal. It skips the refused axiom by
+//! its parentheses and carries on, so one error names every construct that
+//! would have been lost and how often, instead of making the caller fix them
+//! one at a time.
+//!
+//! A malformed document is a different failure and is reported differently: a
+//! syntax error names the line and what was expected there, and stops.
+//!
+//! # SWRL
+//!
+//! `DLSafeRule` is not part of the OWL 2 structural specification. It is the
+//! OWL API's functional-syntax spelling of SWRL, and 22 files of the ORE 2015
+//! pool carry one. It is translated to the `swrl:` RDF vocabulary of the SWRL
+//! member submission, which is what the OWL API writes and what
+//! `src/rulesyntax.rs` already reads, so a rule loaded from OFN reaches the
+//! rule front end exactly as one loaded from RDF/XML does.
+
+use std::collections::{HashMap, HashSet};
+use std::fmt;
+
+use oxigraph::model::vocab::{rdf, rdfs, xsd};
+use oxigraph::model::{BlankNode, Literal, NamedNode, NamedOrBlankNode, Term, Triple};
+
+macro_rules! owl {
+ ($local:literal) => {
+ NamedNode::new_unchecked(concat!("http://www.w3.org/2002/07/owl#", $local))
+ };
+}
+
+macro_rules! swrl {
+ ($local:literal) => {
+ NamedNode::new_unchecked(concat!("http://www.w3.org/2003/11/swrl#", $local))
+ };
+}
+
+const RDF_PLAIN_LITERAL: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral";
+
+/// The prefixes every OFN document may use without declaring them. The
+/// structural specification fixes these five, and the OWL API writes them out
+/// anyway, so predefining them only matters for hand-written files.
+const STANDARD_PREFIXES: &[(&str, &str)] = &[
+ ("owl", "http://www.w3.org/2002/07/owl#"),
+ ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
+ ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
+ ("xsd", "http://www.w3.org/2001/XMLSchema#"),
+ ("xml", "http://www.w3.org/XML/1998/namespace"),
+];
+
+/// Every keyword the grammar knows, in any position.
+///
+/// The list exists to keep two failures apart. A known keyword in the wrong
+/// place (`DataUnionOf` where a class expression belongs) is a malformed
+/// document and a syntax error. A keyword that is not here at all is a
+/// construct this reader was never taught, which is a refusal: counted, named,
+/// and the rest of the document still read so the report is complete.
+const KNOWN_KEYWORDS: &[&str] = &[
+ "Prefix",
+ "Ontology",
+ "Import",
+ "Annotation",
+ "Declaration",
+ "Class",
+ "Datatype",
+ "ObjectProperty",
+ "DataProperty",
+ "AnnotationProperty",
+ "NamedIndividual",
+ "ObjectInverseOf",
+ "ObjectPropertyChain",
+ "DataIntersectionOf",
+ "DataUnionOf",
+ "DataComplementOf",
+ "DataOneOf",
+ "DatatypeRestriction",
+ "ObjectIntersectionOf",
+ "ObjectUnionOf",
+ "ObjectComplementOf",
+ "ObjectOneOf",
+ "ObjectSomeValuesFrom",
+ "ObjectAllValuesFrom",
+ "ObjectHasValue",
+ "ObjectHasSelf",
+ "ObjectMinCardinality",
+ "ObjectMaxCardinality",
+ "ObjectExactCardinality",
+ "DataSomeValuesFrom",
+ "DataAllValuesFrom",
+ "DataHasValue",
+ "DataMinCardinality",
+ "DataMaxCardinality",
+ "DataExactCardinality",
+ "SubClassOf",
+ "EquivalentClasses",
+ "DisjointClasses",
+ "DisjointUnion",
+ "SubObjectPropertyOf",
+ "EquivalentObjectProperties",
+ "DisjointObjectProperties",
+ "InverseObjectProperties",
+ "ObjectPropertyDomain",
+ "ObjectPropertyRange",
+ "FunctionalObjectProperty",
+ "InverseFunctionalObjectProperty",
+ "ReflexiveObjectProperty",
+ "IrreflexiveObjectProperty",
+ "SymmetricObjectProperty",
+ "AsymmetricObjectProperty",
+ "TransitiveObjectProperty",
+ "SubDataPropertyOf",
+ "EquivalentDataProperties",
+ "DisjointDataProperties",
+ "DataPropertyDomain",
+ "DataPropertyRange",
+ "FunctionalDataProperty",
+ "DatatypeDefinition",
+ "HasKey",
+ "SameIndividual",
+ "DifferentIndividuals",
+ "ClassAssertion",
+ "ObjectPropertyAssertion",
+ "NegativeObjectPropertyAssertion",
+ "DataPropertyAssertion",
+ "NegativeDataPropertyAssertion",
+ "AnnotationAssertion",
+ "SubAnnotationPropertyOf",
+ "AnnotationPropertyDomain",
+ "AnnotationPropertyRange",
+ "DLSafeRule",
+ "Body",
+ "Head",
+ "ClassAtom",
+ "DataRangeAtom",
+ "ObjectPropertyAtom",
+ "DataPropertyAtom",
+ "BuiltInAtom",
+ "SameIndividualAtom",
+ "DifferentIndividualsAtom",
+ "Variable",
+];
+
+/// One construct the reader refused, with how often and where it first
+/// appeared.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Refusal {
+ pub construct: String,
+ pub first_line: usize,
+ pub count: usize,
+}
+
+/// Why a document did not load.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum OfnError {
+ /// The document is not well-formed OFN. Parsing stopped at `line`.
+ Syntax { line: usize, message: String },
+ /// The document is well-formed and uses constructs this reader does not
+ /// translate. Nothing was loaded, because loading the rest would be a
+ /// smaller ontology reported as the whole one.
+ Unsupported(Vec<Refusal>),
+}
+
+impl fmt::Display for OfnError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ OfnError::Syntax { line, message } => {
+ write!(f, "OWL functional syntax, line {line}: {message}")
+ }
+ OfnError::Unsupported(refusals) => {
+ let total: usize = refusals.iter().map(|r| r.count).sum();
+ write!(
+ f,
+ "OWL functional syntax: {total} axiom(s) use a construct this reader does \
+ not translate, so nothing was loaded rather than a smaller ontology: "
+ )?;
+ for (i, r) in refusals.iter().enumerate() {
+ if i > 0 {
+ write!(f, "; ")?;
+ }
+ write!(
+ f,
+ "`{}` x{} (first at line {})",
+ r.construct, r.count, r.first_line
+ )?;
+ }
+ Ok(())
+ }
+ }
+ }
+}
+
+impl std::error::Error for OfnError {}
+
+/// True when the first token of `content`, past whitespace and `#` comments,
+/// is `Prefix(` or `Ontology(`.
+///
+/// No other serialisation this crate reads can open that way. Turtle's SPARQL
+/// style `PREFIX ex: <...>` has a name and no parenthesis after the keyword,
+/// and Manchester syntax writes `Prefix:` with a colon, so the parenthesis is
+/// the discriminator and it is checked rather than assumed.
+pub fn looks_like_ofn(content: &str) -> bool {
+ let mut rest = content.trim_start_matches('\u{feff}');
+ loop {
+ rest = rest.trim_start();
+ if let Some(after) = rest.strip_prefix('#') {
+ rest = after.find('\n').map(|i| &after[i..]).unwrap_or("");
+ continue;
+ }
+ break;
+ }
+ ["Prefix", "Ontology"].iter().any(|kw| {
+ rest.strip_prefix(kw)
+ .map(|after| after.trim_start().starts_with('('))
+ .unwrap_or(false)
+ })
+}
+
+/// Parse an OFN document into the triples the W3C mapping assigns it.
+///
+/// All or nothing: on any error no triple is returned, which is the contract
+/// every loader in `src/graph.rs` keeps (issue #93).
+pub fn parse(text: &str) -> Result<Vec<Triple>, OfnError> {
+ let mut p = Parser::new(text);
+ match p.document() {
+ Ok(()) => {}
+ Err(Fail::Syntax { line, message }) => return Err(OfnError::Syntax { line, message }),
+ // `document` absorbs every refusal into the census and never returns
+ // one, so reaching this arm is a defect in the parser, and it is
+ // reported as a syntax error at that line rather than swallowed.
+ Err(Fail::Refuse { construct, line }) => {
+ return Err(OfnError::Syntax {
+ line,
+ message: format!("internal: refusal of `{construct}` escaped the axiom loop"),
+ });
+ }
+ }
+ if !p.refusals.is_empty() {
+ let mut census: Vec<Refusal> = Vec::new();
+ for (construct, line) in p.refusals {
+ match census.iter_mut().find(|r| r.construct == construct) {
+ Some(r) => r.count += 1,
+ None => census.push(Refusal {
+ construct,
+ first_line: line,
+ count: 1,
+ }),
+ }
+ }
+ return Err(OfnError::Unsupported(census));
+ }
+ Ok(p.out)
+}
+
+// --------------------------------------------------------------------------- //
+// Tokens
+// --------------------------------------------------------------------------- //
+
+#[derive(Debug, Clone, PartialEq)]
+enum Tok<'a> {
+ Open,
+ Close,
+ Eq,
+ /// A full IRI, without its angle brackets.
+ Iri(&'a str),
+ /// A keyword, an abbreviated IRI, a prefix name or a non-negative integer.
+ /// Keywords never contain a colon and abbreviated IRIs always do, which is
+ /// how the two are told apart.
+ Word(&'a str),
+ /// `_:label`, kept whole.
+ Blank(&'a str),
+ /// A quoted string with its escapes resolved.
+ Str(String),
+ /// `@tag`, without the `@`.
+ Lang(&'a str),
+ /// `^^`
+ Hats,
+ Eof,
+}
+
+impl fmt::Display for Tok<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Tok::Open => write!(f, "`(`"),
+ Tok::Close => write!(f, "`)`"),
+ Tok::Eq => write!(f, "`=`"),
+ Tok::Iri(s) => write!(f, "`<{s}>`"),
+ Tok::Word(s) => write!(f, "`{s}`"),
+ Tok::Blank(s) => write!(f, "`{s}`"),
+ Tok::Str(s) => {
+ let short: String = s.chars().take(40).collect();
+ write!(f, "string \"{short}\"")
+ }
+ Tok::Lang(s) => write!(f, "`@{s}`"),
+ Tok::Hats => write!(f, "`^^`"),
+ Tok::Eof => write!(f, "end of document"),
+ }
+ }
+}
+
+enum Fail {
+ Syntax { line: usize, message: String },
+ Refuse { construct: String, line: usize },
+}
+
+fn syntax<T>(line: usize, message: impl Into<String>) -> Result<T, Fail> {
+ Err(Fail::Syntax {
+ line,
+ message: message.into(),
+ })
+}
+
+/// A streaming tokeniser. It never holds more than one token of lookahead,
+/// because the corpus this was written for has single files over 500 MB and a
+/// token vector for one of them would cost several times the file.
+struct Lexer<'a> {
+ src: &'a str,
+ pos: usize,
+ line: usize,
+ /// Parenthesis depth after the tokens consumed so far. A refused axiom is
+ /// skipped by reading until the depth returns to where the axiom started,
+ /// which is what lets parsing continue past it.
+ depth: usize,
+ peeked: Option<(Tok<'a>, usize)>,
+}
+
+impl<'a> Lexer<'a> {
+ fn new(src: &'a str) -> Self {
+ let src = src.strip_prefix('\u{feff}').unwrap_or(src);
+ Self {
+ src,
+ pos: 0,
+ line: 1,
+ depth: 0,
+ peeked: None,
+ }
+ }
+
+ fn skip_trivia(&mut self) {
+ let b = self.src.as_bytes();
+ while self.pos < b.len() {
+ match b[self.pos] {
+ b'\n' => {
+ self.line += 1;
+ self.pos += 1;
+ }
+ b' ' | b'\t' | b'\r' | 0x0c => self.pos += 1,
+ // A comment runs to the end of the line. It can only open
+ // between tokens: inside an IRI or a string `#` is content,
+ // and both are consumed whole by `lex` before this sees them.
+ b'#' => {
+ while self.pos < b.len() && b[self.pos] != b'\n' {
+ self.pos += 1;
+ }
+ }
+ _ => break,
+ }
+ }
+ }
+
+ fn lex(&mut self) -> Result<(Tok<'a>, usize), Fail> {
+ self.skip_trivia();
+ let line = self.line;
+ let b = self.src.as_bytes();
+ if self.pos >= b.len() {
+ return Ok((Tok::Eof, line));
+ }
+ let start = self.pos;
+ let tok = match b[start] {
+ b'(' => {
+ self.pos += 1;
+ Tok::Open
+ }
+ b')' => {
+ self.pos += 1;
+ Tok::Close
+ }
+ b'=' => {
+ self.pos += 1;
+ Tok::Eq
+ }
+ b'<' => {
+ let mut i = start + 1;
+ while i < b.len() && b[i] != b'>' {
+ // An IRI cannot hold whitespace, so a newline before the
+ // closing bracket is an unterminated IRI and reporting it
+ // here names the right line instead of one far below.
+ if matches!(b[i], b'\n' | b' ' | b'\t' | b'\r') {
+ return syntax(line, "unterminated IRI: `<` without a closing `>`");
+ }
+ i += 1;
+ }
+ if i >= b.len() {
+ return syntax(line, "unterminated IRI: `<` without a closing `>`");
+ }
+ self.pos = i + 1;
+ Tok::Iri(&self.src[start + 1..i])
+ }
+ b'"' => {
+ let mut out = String::new();
+ let mut i = start + 1;
+ let mut seg = i;
+ loop {
+ if i >= b.len() {
+ return syntax(line, "unterminated string literal");
+ }
+ match b[i] {
+ b'"' => {
+ out.push_str(&self.src[seg..i]);
+ i += 1;
+ break;
+ }
+ b'\\' => {
+ out.push_str(&self.src[seg..i]);
+ match b.get(i + 1) {
+ Some(b'"') => out.push('"'),
+ Some(b'\\') => out.push('\\'),
+ // The grammar admits exactly these two escapes.
+ // Guessing what `\n` meant would change the
+ // literal's value without saying so.
+ _ => {
+ return syntax(
+ self.line,
+ "a string literal may escape only `\\\"` and `\\\\`",
+ );
+ }
+ }
+ i += 2;
+ seg = i;
+ }
+ b'\n' => {
+ self.line += 1;
+ i += 1;
+ }
+ _ => i += 1,
+ }
+ }
+ self.pos = i;
+ Tok::Str(out)
+ }
+ b'@' => {
+ let mut i = start + 1;
+ while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'-') {
+ i += 1;
+ }
+ if i == start + 1 {
+ return syntax(line, "`@` without a language tag");
+ }
+ self.pos = i;
+ Tok::Lang(&self.src[start + 1..i])
+ }
+ b'^' => {
+ if b.get(start + 1) != Some(&b'^') {
+ return syntax(line, "a single `^`: a datatype is introduced by `^^`");
+ }
+ self.pos = start + 2;
+ Tok::Hats
+ }
+ _ => {
+ let mut i = start;
+ while i < b.len()
+ && !matches!(
+ b[i],
+ b' ' | b'\t' | b'\r' | b'\n' | 0x0c | b'(' | b')' | b'<' | b'>' | b'"' | b'='
+ )
+ {
+ i += 1;
+ }
+ if i == start {
+ let ch = self.src[start..].chars().next().unwrap_or('?');
+ return syntax(line, format!("unexpected character `{ch}`"));
+ }
+ self.pos = i;
+ let word = &self.src[start..i];
+ if word.starts_with("_:") {
+ Tok::Blank(word)
+ } else {
+ Tok::Word(word)
+ }
+ }
+ };
+ Ok((tok, line))
+ }
+
+ fn peek(&mut self) -> Result<&Tok<'a>, Fail> {
+ if self.peeked.is_none() {
+ self.peeked = Some(self.lex()?);
+ }
+ Ok(&self.peeked.as_ref().expect("filled above").0)
+ }
+
+ fn next(&mut self) -> Result<(Tok<'a>, usize), Fail> {
+ let (tok, line) = match self.peeked.take() {
+ Some(t) => t,
+ None => self.lex()?,
+ };
+ match tok {
+ Tok::Open => self.depth += 1,
+ Tok::Close => self.depth = self.depth.saturating_sub(1),
+ _ => {}
+ }
+ Ok((tok, line))
+ }
+}
+
+// --------------------------------------------------------------------------- //
+// Parser and translation
+// --------------------------------------------------------------------------- //
+
+/// An annotation, parsed before the thing it annotates is known.
+struct Ann {
+ property: NamedNode,
+ value: Term,
+ annotations: Vec<Ann>,
+}
+
+/// One element of a `DataSomeValuesFrom` / `DataAllValuesFrom` argument list,
+/// which cannot be classified until the list ends: the LAST element is the
+/// data range and every one before it a data property.
+enum DataArg {
+ Iri(NamedNode),
+ Range(NamedOrBlankNode, usize),
+}
+
+struct Parser<'a> {
+ lx: Lexer<'a>,
+ prefixes: HashMap<&'a str, String>,
+ full_iris: HashMap<&'a str, NamedNode>,
+ abbreviated_iris: HashMap<&'a str, NamedNode>,
+ anonymous: HashMap<&'a str, BlankNode>,
+ swrl_variables: HashSet<NamedNode>,
+ out: Vec<Triple>,
+ refusals: Vec<(String, usize)>,
+}
+
+fn is_iri_token(tok: &Tok<'_>) -> bool {
+ match tok {
+ Tok::Iri(_) => true,
+ Tok::Word(w) => w.contains(':'),
+ _ => false,
+ }
+}
+
+impl<'a> Parser<'a> {
+ fn new(src: &'a str) -> Self {
+ let prefixes = STANDARD_PREFIXES
+ .iter()
+ .map(|(p, iri)| (*p, (*iri).to_string()))
+ .collect();
+ Self {
+ lx: Lexer::new(src),
+ prefixes,
+ full_iris: HashMap::new(),
+ abbreviated_iris: HashMap::new(),
+ anonymous: HashMap::new(),
+ swrl_variables: HashSet::new(),
+ out: Vec::new(),
+ refusals: Vec::new(),
+ }
+ }
+
+ // ---- token helpers -------------------------------------------------- //
+
+ fn expect_open(&mut self, context: &str) -> Result<(), Fail> {
+ match self.lx.next()? {
+ (Tok::Open, _) => Ok(()),
+ (tok, line) => syntax(line, format!("expected `(` after `{context}`, found {tok}")),
+ }
+ }
+
+ fn expect_close(&mut self, context: &str) -> Result<(), Fail> {
+ match self.lx.next()? {
+ (Tok::Close, _) => Ok(()),
+ (tok, line) => syntax(
+ line,
+ format!("expected `)` closing `{context}`, found {tok}"),
+ ),
+ }
+ }
+
+ fn at_close(&mut self) -> Result<bool, Fail> {
+ Ok(matches!(self.lx.peek()?, Tok::Close))
+ }
+
+ fn peek_keyword(&mut self, kw: &str) -> Result<bool, Fail> {
+ Ok(matches!(self.lx.peek()?, Tok::Word(w) if *w == kw))
+ }
+
+ /// The failure for a keyword that cannot stand where it was found: a
+ /// syntax error if the grammar knows it elsewhere, a refusal if not.
+ fn misplaced(&self, kw: &str, line: usize, expected: &str) -> Fail {
+ if KNOWN_KEYWORDS.contains(&kw) {
+ Fail::Syntax {
+ line,
+ message: format!("`{kw}` cannot stand where {expected} is expected"),
+ }
+ } else {
+ Fail::Refuse {
+ construct: kw.to_string(),
+ line,
+ }
+ }
+ }
+
+ // ---- terminals ------------------------------------------------------ //
+
+ fn iri_from(&mut self, tok: Tok<'a>, line: usize, what: &str) -> Result<NamedNode, Fail> {
+ match tok {
+ Tok::Iri(s) => {
+ if let Some(n) = self.full_iris.get(s) {
+ return Ok(n.clone());
+ }
+ let node = NamedNode::new(s).or_else(|e| {
+ syntax(line, format!("`<{s}>` is not a valid absolute IRI: {e}"))
+ })?;
+ self.full_iris.insert(s, node.clone());
+ Ok(node)
+ }
+ Tok::Word(w) if w.contains(':') => {
+ if let Some(n) = self.abbreviated_iris.get(w) {
+ return Ok(n.clone());
+ }
+ let (prefix, local) = w.split_once(':').expect("contains ':'");
+ let Some(ns) = self.prefixes.get(prefix) else {
+ return syntax(line, format!("prefix `{prefix}:` in `{w}` was never declared"));
+ };
+ let full = format!("{ns}{local}");
+ let node = NamedNode::new(full.as_str()).or_else(|e| {
+ syntax(
+ line,
+ format!("`{w}` expands to `{full}`, which is not a valid IRI: {e}"),
+ )
+ })?;
+ self.abbreviated_iris.insert(w, node.clone());
+ Ok(node)
+ }
+ Tok::Word(w) if !w.is_empty() && !w.chars().all(|c| c.is_ascii_digit()) => {
+ // A bare keyword followed by `(` where an IRI belongs.
+ if matches!(self.lx.peek()?, Tok::Open) {
+ self.lx.next()?;
+ Err(self.misplaced(w, line, &format!("{what} IRI")))
+ } else {
+ syntax(line, format!("expected {what} IRI, found `{w}`"))
+ }
+ }
+ other => syntax(line, format!("expected {what} IRI, found {other}")),
+ }
+ }
+
+ fn iri(&mut self, what: &str) -> Result<NamedNode, Fail> {
+ let (tok, line) = self.lx.next()?;
+ self.iri_from(tok, line, what)
+ }
+
+ fn anonymous(&mut self, label: &'a str) -> BlankNode {
+ self.anonymous.entry(label).or_default().clone()
+ }
+
+ fn individual(&mut self) -> Result<NamedOrBlankNode, Fail> {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Blank(label) => Ok(self.anonymous(label).into()),
+ other => Ok(self.iri_from(other, line, "individual")?.into()),
+ }
+ }
+
+ fn literal(&mut self) -> Result<Literal, Fail> {
+ let (tok, line) = self.lx.next()?;
+ let Tok::Str(value) = tok else {
+ return syntax(line, format!("expected a literal, found {tok}"));
+ };
+ self.literal_suffix(value, line)
+ }
+
+ fn literal_suffix(&mut self, value: String, line: usize) -> Result<Literal, Fail> {
+ match self.lx.peek()? {
+ Tok::Lang(_) => {
+ let (Tok::Lang(tag), _) = self.lx.next()? else {
+ unreachable!("peeked a language tag")
+ };
+ Literal::new_language_tagged_literal(value, tag)
+ .or_else(|e| syntax(line, format!("`@{tag}` is not a language tag: {e}")))
+ }
+ Tok::Hats => {
+ self.lx.next()?;
+ let datatype = self.iri("datatype")?;
+ if datatype.as_str() == RDF_PLAIN_LITERAL {
+ // Table 1's first two rows: an rdf:PlainLiteral is the
+ // plain RDF literal it spells, with the language tag after
+ // the LAST `@` and an empty tag meaning none.
+ let Some(at) = value.rfind('@') else {
+ return syntax(
+ line,
+ "an rdf:PlainLiteral lexical form must end in `@` or `@tag`",
+ );
+ };
+ let (text, tag) = (&value[..at], &value[at + 1..]);
+ if tag.is_empty() {
+ return Ok(Literal::new_simple_literal(text));
+ }
+ return Literal::new_language_tagged_literal(text, tag)
+ .or_else(|e| syntax(line, format!("`@{tag}` is not a language tag: {e}")));
+ }
+ Ok(Literal::new_typed_literal(value, datatype))
+ }
+ _ => Ok(Literal::new_simple_literal(value)),
+ }
+ }
+
+ fn cardinality(&mut self) -> Result<Literal, Fail> {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Word(w) if !w.is_empty() && w.chars().all(|c| c.is_ascii_digit()) => {
+ let n: u64 = w
+ .parse()
+ .or_else(|_| syntax(line, format!("cardinality `{w}` is out of range")))?;
+ Ok(Literal::new_typed_literal(
+ n.to_string(),
+ xsd::NON_NEGATIVE_INTEGER.into_owned(),
+ ))
+ }
+ other => syntax(
+ line,
+ format!("expected a non-negative integer cardinality, found {other}"),
+ ),
+ }
+ }
+
+ // ---- emission ------------------------------------------------------- //
+
+ fn push(&mut self, s: impl Into<NamedOrBlankNode>, p: NamedNode, o: impl Into<Term>) {
+ self.out.push(Triple::new(s, p, o));
+ }
+
+ /// `T(SEQ ...)`: an `rdf:List`, or `rdf:nil` when empty.
+ fn list(&mut self, items: Vec<Term>) -> NamedOrBlankNode {
+ let mut tail: NamedOrBlankNode = rdf::NIL.into_owned().into();
+ for item in items.into_iter().rev() {
+ let cell = BlankNode::default();
+ self.push(cell.clone(), rdf::FIRST.into_owned(), item);
+ self.push(cell.clone(), rdf::REST.into_owned(), tail);
+ tail = cell.into();
+ }
+ tail
+ }
+
+ /// `TANN(ann, subject)` from Table 2.
+ fn tann(&mut self, subject: NamedOrBlankNode, ann: &Ann) {
+ self.push(subject.clone(), ann.property.clone(), ann.value.clone());
+ if !ann.annotations.is_empty() {
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), owl!("Annotation"));
+ self.push(x.clone(), owl!("annotatedSource"), subject);
+ self.push(x.clone(), owl!("annotatedProperty"), ann.property.clone());
+ self.push(x.clone(), owl!("annotatedTarget"), ann.value.clone());
+ for inner in &ann.annotations {
+ self.tann(x.clone().into(), inner);
+ }
+ }
+ }
+
+ /// An axiom with a main triple (Section 2.3.1): the triple, and when the
+ /// axiom is annotated, an `owl:Axiom` node reifying it that carries the
+ /// annotations.
+ fn main_triple(&mut self, s: NamedOrBlankNode, p: NamedNode, o: Term, anns: &[Ann]) {
+ self.push(s.clone(), p.clone(), o.clone());
+ if !anns.is_empty() {
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), owl!("Axiom"));
+ self.push(x.clone(), owl!("annotatedSource"), s);
+ self.push(x.clone(), owl!("annotatedProperty"), p);
+ self.push(x.clone(), owl!("annotatedTarget"), o);
+ for a in anns {
+ self.tann(x.clone().into(), a);
+ }
+ }
+ }
+
+ /// Section 2.3.2: an n-ary axiom becomes the chain of pairwise triples
+ /// Table 1 gives, and every link of the chain is annotated separately.
+ fn chain(&mut self, items: Vec<NamedOrBlankNode>, p: NamedNode, anns: &[Ann]) {
+ for pair in items.windows(2) {
+ self.main_triple(pair[0].clone(), p.clone(), pair[1].clone().into(), anns);
+ }
+ }
+
+ /// Section 2.3.3: an axiom whose translation is rooted at a blank node
+ /// carries its annotations on that node directly.
+ fn annotate_node(&mut self, x: &BlankNode, anns: &[Ann]) {
+ for a in anns {
+ self.tann(x.clone().into(), a);
+ }
+ }
+
+ /// The `n > 2` row of `DisjointClasses` and its kin: a typed blank node
+ /// with `owl:members`.
+ fn members_node(&mut self, class: NamedNode, items: Vec<NamedOrBlankNode>, anns: &[Ann]) {
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), class);
+ let list = self.list(items.into_iter().map(Into::into).collect());
+ self.push(x.clone(), owl!("members"), list);
+ self.annotate_node(&x, anns);
+ }
+
+ // ---- annotations ---------------------------------------------------- //
+
+ fn annotation_value(&mut self) -> Result<Term, Fail> {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Str(v) => Ok(self.literal_suffix(v, line)?.into()),
+ Tok::Blank(label) => Ok(self.anonymous(label).into()),
+ other => Ok(self.iri_from(other, line, "annotation value")?.into()),
+ }
+ }
+
+ /// The body of `Annotation( ... )`, the keyword already consumed.
+ fn annotation_body(&mut self) -> Result<Ann, Fail> {
+ self.expect_open("Annotation")?;
+ let annotations = self.annotations()?;
+ let property = self.iri("annotation property")?;
+ let value = self.annotation_value()?;
+ self.expect_close("Annotation")?;
+ Ok(Ann {
+ property,
+ value,
+ annotations,
+ })
+ }
+
+ fn annotations(&mut self) -> Result<Vec<Ann>, Fail> {
+ let mut anns = Vec::new();
+ while self.peek_keyword("Annotation")? {
+ self.lx.next()?;
+ anns.push(self.annotation_body()?);
+ }
+ Ok(anns)
+ }
+
+ // ---- expressions ---------------------------------------------------- //
+
+ fn class_expr(&mut self) -> Result<NamedOrBlankNode, Fail> {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Word(w) if !w.contains(':') && matches!(self.lx.peek()?, Tok::Open) => {
+ self.class_constructor(w, line)
+ }
+ other => Ok(self.iri_from(other, line, "class")?.into()),
+ }
+ }
+
+ fn class_exprs_until_close(&mut self) -> Result<Vec<NamedOrBlankNode>, Fail> {
+ let mut items = Vec::new();
+ while !self.at_close()? {
+ items.push(self.class_expr()?);
+ }
+ Ok(items)
+ }
+
+ fn at_least<T>(items: &[T], n: usize, kw: &str, line: usize) -> Result<(), Fail> {
+ if items.len() < n {
+ return syntax(
+ line,
+ format!("`{kw}` needs at least {n} operand(s), found {}", items.len()),
+ );
+ }
+ Ok(())
+ }
+
+ fn restriction(&mut self, property: NamedOrBlankNode) -> BlankNode {
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), owl!("Restriction"));
+ self.push(x.clone(), owl!("onProperty"), property);
+ x
+ }
+
+ fn class_constructor(&mut self, kw: &'a str, line: usize) -> Result<NamedOrBlankNode, Fail> {
+ self.expect_open(kw)?;
+ let x = match kw {
+ "ObjectIntersectionOf" | "ObjectUnionOf" => {
+ let items = self.class_exprs_until_close()?;
+ Self::at_least(&items, 2, kw, line)?;
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), owl!("Class"));
+ let list = self.list(items.into_iter().map(Into::into).collect());
+ let p = if kw == "ObjectIntersectionOf" {
+ owl!("intersectionOf")
+ } else {
+ owl!("unionOf")
+ };
+ self.push(x.clone(), p, list);
+ x
+ }
+ "ObjectComplementOf" => {
+ let ce = self.class_expr()?;
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), owl!("Class"));
+ self.push(x.clone(), owl!("complementOf"), ce);
+ x
+ }
+ "ObjectOneOf" => {
+ let mut items: Vec<Term> = Vec::new();
+ while !self.at_close()? {
+ items.push(self.individual()?.into());
+ }
+ Self::at_least(&items, 1, kw, line)?;
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), owl!("Class"));
+ let list = self.list(items);
+ self.push(x.clone(), owl!("oneOf"), list);
+ x
+ }
+ "ObjectSomeValuesFrom" | "ObjectAllValuesFrom" => {
+ let ope = self.object_property_expr()?;
+ let ce = self.class_expr()?;
+ let x = self.restriction(ope);
+ let p = if kw == "ObjectSomeValuesFrom" {
+ owl!("someValuesFrom")
+ } else {
+ owl!("allValuesFrom")
+ };
+ self.push(x.clone(), p, ce);
+ x
+ }
+ "ObjectHasValue" => {
+ let ope = self.object_property_expr()?;
+ let a = self.individual()?;
+ let x = self.restriction(ope);
+ self.push(x.clone(), owl!("hasValue"), a);
+ x
+ }
+ "ObjectHasSelf" => {
+ let ope = self.object_property_expr()?;
+ let x = self.restriction(ope);
+ self.push(
+ x.clone(),
+ owl!("hasSelf"),
+ Literal::new_typed_literal("true", xsd::BOOLEAN.into_owned()),
+ );
+ x
+ }
+ "ObjectMinCardinality" | "ObjectMaxCardinality" | "ObjectExactCardinality" => {
+ let n = self.cardinality()?;
+ let ope = self.object_property_expr()?;
+ let filler = if self.at_close()? {
+ None
+ } else {
+ Some(self.class_expr()?)
+ };
+ let x = self.restriction(ope);
+ self.cardinality_triples(&x, kw, n, filler, owl!("onClass"));
+ x
+ }
+ "DataSomeValuesFrom" | "DataAllValuesFrom" => {
+ let mut args = Vec::new();
+ while !self.at_close()? {
+ let (tok, l) = self.lx.next()?;
+ match tok {
+ Tok::Word(w) if !w.contains(':') => {
+ args.push(DataArg::Range(self.data_range_constructor(w, l)?, l));
+ }
+ other => args.push(DataArg::Iri(self.iri_from(other, l, "data")?)),
+ }
+ }
+ Self::at_least(&args, 2, kw, line)?;
+ let range = match args.pop().expect("at least two") {
+ DataArg::Iri(n) => NamedOrBlankNode::from(n),
+ DataArg::Range(r, _) => r,
+ };
+ let mut props: Vec<NamedNode> = Vec::new();
+ for a in args {
+ match a {
+ DataArg::Iri(n) => props.push(n),
+ DataArg::Range(_, l) => {
+ return syntax(
+ l,
+ format!("`{kw}` takes data properties before its data range, not a second data range"),
+ );
+ }
+ }
+ }
+ let x = BlankNode::default();
+ self.push(x.clone(), rdf::TYPE.into_owned(), owl!("Restriction"));
+ if props.len() == 1 {
+ let p = props.pop().expect("one");
+ self.push(x.clone(), owl!("onProperty"), p);
+ } else {
+ let list = self.list(props.into_iter().map(Into::into).collect());
+ self.push(x.clone(), owl!("onProperties"), list);
+ }
+ let p = if kw == "DataSomeValuesFrom" {
+ owl!("someValuesFrom")
+ } else {
+ owl!("allValuesFrom")
+ };
+ self.push(x.clone(), p, range);
+ x
+ }
+ "DataHasValue" => {
+ let dp = self.iri("data property")?;
+ let lt = self.literal()?;
+ let x = self.restriction(dp.into());
+ self.push(x.clone(), owl!("hasValue"), lt);
+ x
+ }
+ "DataMinCardinality" | "DataMaxCardinality" | "DataExactCardinality" => {
+ let n = self.cardinality()?;
+ let dp = self.iri("data property")?;
+ let filler = if self.at_close()? {
+ None
+ } else {
+ Some(self.data_range()?)
+ };
+ let x = self.restriction(dp.into());
+ self.cardinality_triples(&x, kw, n, filler, owl!("onDataRange"));
+ x
+ }
+ other => return Err(self.misplaced(other, line, "a class expression")),
+ };
+ self.expect_close(kw)?;
+ Ok(x.into())
+ }
+
+ /// Table 1's six cardinality rows per family: unqualified when the source
+ /// gave no filler, qualified with `owl:onClass` / `owl:onDataRange` when
+ /// it gave one, `owl:Thing` included (see the module notes, item 1).
+ fn cardinality_triples(
+ &mut self,
+ x: &BlankNode,
+ kw: &str,
+ n: Literal,
+ filler: Option<NamedOrBlankNode>,
+ on: NamedNode,
+ ) {
+ let qualified = filler.is_some();
+ let p = match (kw.trim_start_matches("Object").trim_start_matches("Data"), qualified) {
+ ("MinCardinality", false) => owl!("minCardinality"),
+ ("MinCardinality", true) => owl!("minQualifiedCardinality"),
+ ("MaxCardinality", false) => owl!("maxCardinality"),
+ ("MaxCardinality", true) => owl!("maxQualifiedCardinality"),
+ (_, false) => owl!("cardinality"),
+ (_, true) => owl!("qualifiedCardinality"),
+ };
+ self.push(x.clone(), p, n);
+ if let Some(f) = filler {
+ self.push(x.clone(), on, f);
+ }
+ }
+
+ fn object_property_expr(&mut self) -> Result<NamedOrBlankNode, Fail> {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Word("ObjectInverseOf") => {
+ let p = self.inverse_body()?;
+ let x = BlankNode::default();
+ self.push(x.clone(), owl!("inverseOf"), p);
+ Ok(x.into())
+ }
+ Tok::Word(w) if !w.contains(':') && matches!(self.lx.peek()?, Tok::Open) => {
+ self.lx.next()?;
+ Err(self.misplaced(w, line, "an object property expression"))
+ }
+ other => Ok(self.iri_from(other, line, "object property")?.into()),
+ }
+ }
+
+ /// `ObjectInverseOf( P )` with the keyword consumed. The grammar admits a
+ /// named property only, so `ObjectInverseOf(ObjectInverseOf(P))` is a
+ /// syntax error here as it is in the specification.
+ fn inverse_body(&mut self) -> Result<NamedNode, Fail> {
+ self.expect_open("ObjectInverseOf")?;
+ let p = self.iri("object property")?;
+ self.expect_close("ObjectInverseOf")?;
+ Ok(p)
+ }
+
+ fn data_range(&mut self) -> Result<NamedOrBlankNode, Fail> {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Word(w) if !w.contains(':') && matches!(self.lx.peek()?, Tok::Open) => {
+ self.data_range_constructor(w, line)
+ }
+ other => Ok(self.iri_from(other, line, "datatype")?.into()),
+ }
+ }
+
+ fn data_range_constructor(&mut self, kw: &'a str, line: usize) -> Result<NamedOrBlankNode, Fail> {
+ self.expect_open(kw)?;
+ let x = BlankNode::default();
+ match kw {
+ "DataIntersectionOf" | "DataUnionOf" => {
+ let mut items: Vec<Term> = Vec::new();
+ while !self.at_close()? {
+ items.push(self.data_range()?.into());
+ }
+ Self::at_least(&items, 2, kw, line)?;
+ self.push(x.clone(), rdf::TYPE.into_owned(), rdfs::DATATYPE.into_owned());
+ let list = self.list(items);
+ let p = if kw == "DataIntersectionOf" {
+ owl!("intersectionOf")
+ } else {
+ owl!("unionOf")
+ };
+ self.push(x.clone(), p, list);
+ }
+ "DataComplementOf" => {
+ let dr = self.data_range()?;
+ self.push(x.clone(), rdf::TYPE.into_owned(), rdfs::DATATYPE.into_owned());
+ self.push(x.clone(), owl!("datatypeComplementOf"), dr);
+ }
+ "DataOneOf" => {
+ let mut items: Vec<Term> = Vec::new();
+ while !self.at_close()? {
+ items.push(self.literal()?.into());
+ }
+ Self::at_least(&items, 1, kw, line)?;
+ self.push(x.clone(), rdf::TYPE.into_owned(), rdfs::DATATYPE.into_owned());
+ let list = self.list(items);
+ self.push(x.clone(), owl!("oneOf"), list);
+ }
+ "DatatypeRestriction" => {
+ let dt = self.iri("datatype")?;
+ let mut facets: Vec<Term> = Vec::new();
+ while !self.at_close()? {
+ let facet = self.iri("constraining facet")?;
+ let lt = self.literal()?;
+ let y = BlankNode::default();
+ self.push(y.clone(), facet, lt);
+ facets.push(y.into());
+ }
+ Self::at_least(&facets, 1, kw, line)?;
+ self.push(x.clone(), rdf::TYPE.into_owned(), rdfs::DATATYPE.into_owned());
+ self.push(x.clone(), owl!("onDatatype"), dt);
+ let list = self.list(facets);
+ self.push(x.clone(), owl!("withRestrictions"), list);
+ }
+ other => return Err(self.misplaced(other, line, "a data range")),
+ }
+ self.expect_close(kw)?;
+ Ok(x.into())
+ }
+
+ fn iris_until_close(&mut self, what: &str) -> Result<Vec<NamedOrBlankNode>, Fail> {
+ let mut items = Vec::new();
+ while !self.at_close()? {
+ items.push(self.iri(what)?.into());
+ }
+ Ok(items)
+ }
+
+ fn object_property_exprs_until_close(&mut self) -> Result<Vec<NamedOrBlankNode>, Fail> {
+ let mut items = Vec::new();
+ while !self.at_close()? {
+ items.push(self.object_property_expr()?);
+ }
+ Ok(items)
+ }
+
+ // ---- axioms --------------------------------------------------------- //
+
+ fn axiom(&mut self, kw: &'a str, line: usize) -> Result<(), Fail> {
+ self.expect_open(kw)?;
+ let anns = self.annotations()?;
+ let ty = rdf::TYPE.into_owned();
+ match kw {
+ "Declaration" => {
+ let (tok, l) = self.lx.next()?;
+ let class = match tok {
+ Tok::Word("Class") => owl!("Class"),
+ Tok::Word("Datatype") => rdfs::DATATYPE.into_owned(),
+ Tok::Word("ObjectProperty") => owl!("ObjectProperty"),
+ Tok::Word("DataProperty") => owl!("DatatypeProperty"),
+ Tok::Word("AnnotationProperty") => owl!("AnnotationProperty"),
+ Tok::Word("NamedIndividual") => owl!("NamedIndividual"),
+ Tok::Word(w) if !w.contains(':') => {
+ self.expect_open(w)?;
+ return Err(self.misplaced(w, l, "an entity kind"));
+ }
+ other => return syntax(l, format!("expected an entity kind, found {other}")),
+ };
+ self.expect_open("entity")?;
+ let iri = self.iri("entity")?;
+ self.expect_close("entity")?;
+ self.main_triple(iri.into(), ty, class.into(), &anns);
+ }
+ "SubClassOf" => {
+ let sub = self.class_expr()?;
+ let sup = self.class_expr()?;
+ self.main_triple(sub, rdfs::SUB_CLASS_OF.into_owned(), sup.into(), &anns);
+ }
+ "EquivalentClasses" => {
+ let items = self.class_exprs_until_close()?;
+ Self::at_least(&items, 2, kw, line)?;
+ self.chain(items, owl!("equivalentClass"), &anns);
+ }
+ "DisjointClasses" => {
+ let items = self.class_exprs_until_close()?;
+ Self::at_least(&items, 2, kw, line)?;
+ if items.len() == 2 {
+ self.chain(items, owl!("disjointWith"), &anns);
+ } else {
+ self.members_node(owl!("AllDisjointClasses"), items, &anns);
+ }
+ }
+ "DisjointUnion" => {
+ let c = self.iri("class")?;
+ let items = self.class_exprs_until_close()?;
+ Self::at_least(&items, 2, kw, line)?;
+ let list = self.list(items.into_iter().map(Into::into).collect());
+ self.main_triple(c.into(), owl!("disjointUnionOf"), list.into(), &anns);
+ }
+ "SubObjectPropertyOf" => {
+ if self.peek_keyword("ObjectPropertyChain")? {
+ let (_, l) = self.lx.next()?;
+ self.expect_open("ObjectPropertyChain")?;
+ let chain = self.object_property_exprs_until_close()?;
+ Self::at_least(&chain, 2, "ObjectPropertyChain", l)?;
+ self.expect_close("ObjectPropertyChain")?;
+ let sup = self.object_property_expr()?;
+ let list = self.list(chain.into_iter().map(Into::into).collect());
+ self.main_triple(sup, owl!("propertyChainAxiom"), list.into(), &anns);
+ } else {
+ let sub = self.object_property_expr()?;
+ let sup = self.object_property_expr()?;
+ self.main_triple(sub, rdfs::SUB_PROPERTY_OF.into_owned(), sup.into(), &anns);
+ }
+ }
+ "EquivalentObjectProperties" => {
+ let items = self.object_property_exprs_until_close()?;
+ Self::at_least(&items, 2, kw, line)?;
+ self.chain(items, owl!("equivalentProperty"), &anns);
+ }
+ "DisjointObjectProperties" => {
+ let items = self.object_property_exprs_until_close()?;
+ Self::at_least(&items, 2, kw, line)?;
+ if items.len() == 2 {
+ self.chain(items, owl!("propertyDisjointWith"), &anns);
+ } else {
+ self.members_node(owl!("AllDisjointProperties"), items, &anns);
+ }
+ }
+ "ObjectPropertyDomain" | "ObjectPropertyRange" => {
+ let ope = self.object_property_expr()?;
+ let ce = self.class_expr()?;
+ let p = if kw == "ObjectPropertyDomain" {
+ rdfs::DOMAIN.into_owned()
+ } else {
+ rdfs::RANGE.into_owned()
+ };
+ self.main_triple(ope, p, ce.into(), &anns);
+ }
+ "InverseObjectProperties" => {
+ let a = self.object_property_expr()?;
+ let b = self.object_property_expr()?;
+ self.main_triple(a, owl!("inverseOf"), b.into(), &anns);
+ }
+ "FunctionalObjectProperty"
+ | "InverseFunctionalObjectProperty"
+ | "ReflexiveObjectProperty"
+ | "IrreflexiveObjectProperty"
+ | "SymmetricObjectProperty"
+ | "AsymmetricObjectProperty"
+ | "TransitiveObjectProperty" => {
+ let ope = self.object_property_expr()?;
+ let class = match kw {
+ "FunctionalObjectProperty" => owl!("FunctionalProperty"),
+ "InverseFunctionalObjectProperty" => owl!("InverseFunctionalProperty"),
+ "ReflexiveObjectProperty" => owl!("ReflexiveProperty"),
+ "IrreflexiveObjectProperty" => owl!("IrreflexiveProperty"),
+ "SymmetricObjectProperty" => owl!("SymmetricProperty"),
+ "AsymmetricObjectProperty" => owl!("AsymmetricProperty"),
+ _ => owl!("TransitiveProperty"),
+ };
+ self.main_triple(ope, ty, class.into(), &anns);
+ }
+ "SubDataPropertyOf" => {
+ let a = self.iri("data property")?;
+ let b = self.iri("data property")?;
+ self.main_triple(a.into(), rdfs::SUB_PROPERTY_OF.into_owned(), b.into(), &anns);
+ }
+ "EquivalentDataProperties" => {
+ let items = self.iris_until_close("data property")?;
+ Self::at_least(&items, 2, kw, line)?;
+ self.chain(items, owl!("equivalentProperty"), &anns);
+ }
+ "DisjointDataProperties" => {
+ let items = self.iris_until_close("data property")?;
+ Self::at_least(&items, 2, kw, line)?;
+ if items.len() == 2 {
+ self.chain(items, owl!("propertyDisjointWith"), &anns);
+ } else {
+ self.members_node(owl!("AllDisjointProperties"), items, &anns);
+ }
+ }
+ "DataPropertyDomain" => {
+ let dp = self.iri("data property")?;
+ let ce = self.class_expr()?;
+ self.main_triple(dp.into(), rdfs::DOMAIN.into_owned(), ce.into(), &anns);
+ }
+ "DataPropertyRange" => {
+ let dp = self.iri("data property")?;
+ let dr = self.data_range()?;
+ self.main_triple(dp.into(), rdfs::RANGE.into_owned(), dr.into(), &anns);
+ }
+ "FunctionalDataProperty" => {
+ let dp = self.iri("data property")?;
+ self.main_triple(dp.into(), ty, owl!("FunctionalProperty").into(), &anns);
+ }
+ "DatatypeDefinition" => {
+ let dt = self.iri("datatype")?;
+ let dr = self.data_range()?;
+ self.main_triple(dt.into(), owl!("equivalentClass"), dr.into(), &anns);
+ }
+ "HasKey" => {
+ let ce = self.class_expr()?;
+ self.expect_open("HasKey object properties")?;
+ let mut keys = self.object_property_exprs_until_close()?;
+ self.expect_close("HasKey object properties")?;
+ self.expect_open("HasKey data properties")?;
+ keys.extend(self.iris_until_close("data property")?);
+ self.expect_close("HasKey data properties")?;
+ let list = self.list(keys.into_iter().map(Into::into).collect());
+ self.main_triple(ce, owl!("hasKey"), list.into(), &anns);
+ }
+ "SameIndividual" => {
+ let mut items = Vec::new();
+ while !self.at_close()? {
+ items.push(self.individual()?);
+ }
+ Self::at_least(&items, 2, kw, line)?;
+ self.chain(items, owl!("sameAs"), &anns);
+ }
+ "DifferentIndividuals" => {
+ let mut items = Vec::new();
+ while !self.at_close()? {
+ items.push(self.individual()?);
+ }
+ Self::at_least(&items, 2, kw, line)?;
+ if items.len() == 2 {
+ self.chain(items, owl!("differentFrom"), &anns);
+ } else {
+ self.members_node(owl!("AllDifferent"), items, &anns);
+ }
+ }
+ "ClassAssertion" => {
+ let ce = self.class_expr()?;
+ let a = self.individual()?;
+ self.main_triple(a, ty, ce.into(), &anns);
+ }
+ "ObjectPropertyAssertion" => {
+ // Table 1 gives the inverse its own row: the assertion of
+ // `ObjectInverseOf(P)` from a1 to a2 IS the triple a2 P a1,
+ // because RDF has no predicate a blank node could stand in.
+ let inverse = self.peek_keyword("ObjectInverseOf")?;
+ if inverse {
+ self.lx.next()?;
+ }
+ let p = if inverse {
+ self.inverse_body()?
+ } else {
+ self.iri("object property")?
+ };
+ let a1 = self.individual()?;
+ let a2 = self.individual()?;
+ let (s, o) = if inverse { (a2, a1) } else { (a1, a2) };
+ self.main_triple(s, p, o.into(), &anns);
+ }
+ "NegativeObjectPropertyAssertion" => {
+ let ope = self.object_property_expr()?;
+ let a1 = self.individual()?;
+ let a2 = self.individual()?;
+ let x = BlankNode::default();
+ self.push(x.clone(), ty, owl!("NegativePropertyAssertion"));
+ self.push(x.clone(), owl!("sourceIndividual"), a1);
+ self.push(x.clone(), owl!("assertionProperty"), ope);
+ self.push(x.clone(), owl!("targetIndividual"), a2);
+ self.annotate_node(&x, &anns);
+ }
+ "DataPropertyAssertion" => {
+ let dp = self.iri("data property")?;
+ let a = self.individual()?;
+ let lt = self.literal()?;
+ self.main_triple(a, dp, lt.into(), &anns);
+ }
+ "NegativeDataPropertyAssertion" => {
+ let dp = self.iri("data property")?;
+ let a = self.individual()?;
+ let lt = self.literal()?;
+ let x = BlankNode::default();
+ self.push(x.clone(), ty, owl!("NegativePropertyAssertion"));
+ self.push(x.clone(), owl!("sourceIndividual"), a);
+ self.push(x.clone(), owl!("assertionProperty"), dp);
+ self.push(x.clone(), owl!("targetValue"), lt);
+ self.annotate_node(&x, &anns);
+ }
+ "AnnotationAssertion" => {
+ let ap = self.iri("annotation property")?;
+ let subject = self.individual()?;
+ let value = self.annotation_value()?;
+ self.main_triple(subject, ap, value, &anns);
+ }
+ "SubAnnotationPropertyOf" => {
+ let a = self.iri("annotation property")?;
+ let b = self.iri("annotation property")?;
+ self.main_triple(a.into(), rdfs::SUB_PROPERTY_OF.into_owned(), b.into(), &anns);
+ }
+ "AnnotationPropertyDomain" | "AnnotationPropertyRange" => {
+ let ap = self.iri("annotation property")?;
+ let u = self.iri("domain or range")?;
+ let p = if kw == "AnnotationPropertyDomain" {
+ rdfs::DOMAIN.into_owned()
+ } else {
+ rdfs::RANGE.into_owned()
+ };
+ self.main_triple(ap.into(), p, u.into(), &anns);
+ }
+ "DLSafeRule" => self.swrl_rule(&anns)?,
+ other => return Err(self.misplaced(other, line, "an axiom")),
+ }
+ self.expect_close(kw)
+ }
+
+ // ---- SWRL ----------------------------------------------------------- //
+
+ /// `DLSafeRule( annotations Body(atoms) Head(atoms) )` as a `swrl:Imp`.
+ /// The annotations sit on the rule node itself, as the OWL API writes
+ /// them, because a rule has no main triple to reify.
+ fn swrl_rule(&mut self, anns: &[Ann]) -> Result<(), Fail> {
+ let rule = BlankNode::default();
+ self.push(rule.clone(), rdf::TYPE.into_owned(), swrl!("Imp"));
+ self.annotate_node(&rule, anns);
+ for (part, p) in [("Body", swrl!("body")), ("Head", swrl!("head"))] {
+ let (tok, l) = self.lx.next()?;
+ if tok != Tok::Word(part) {
+ return syntax(l, format!("expected `{part}(` in DLSafeRule, found {tok}"));
+ }
+ self.expect_open(part)?;
+ let mut atoms: Vec<Term> = Vec::new();
+ while !self.at_close()? {
+ atoms.push(self.swrl_atom()?.into());
+ }
+ self.expect_close(part)?;
+ let list = self.swrl_atom_list(atoms);
+ self.push(rule.clone(), p, list);
+ }
+ Ok(())
+ }
+
+ /// An `rdf:List` of atoms whose cells are also typed `swrl:AtomList`, the
+ /// class the SWRL submission defines for exactly these lists and the type
+ /// the OWL API writes on every cell.
+ fn swrl_atom_list(&mut self, atoms: Vec<Term>) -> NamedOrBlankNode {
+ let mut tail: NamedOrBlankNode = rdf::NIL.into_owned().into();
+ for item in atoms.into_iter().rev() {
+ let cell = BlankNode::default();
+ self.push(cell.clone(), rdf::TYPE.into_owned(), swrl!("AtomList"));
+ self.push(cell.clone(), rdf::FIRST.into_owned(), item);
+ self.push(cell.clone(), rdf::REST.into_owned(), tail);
+ tail = cell.into();
+ }
+ tail
+ }
+
+ fn swrl_variable(&mut self) -> Result<NamedNode, Fail> {
+ self.expect_open("Variable")?;
+ let v = self.iri("variable")?;
+ self.expect_close("Variable")?;
+ if self.swrl_variables.insert(v.clone()) {
+ self.push(v.clone(), rdf::TYPE.into_owned(), swrl!("Variable"));
+ }
+ Ok(v)
+ }
+
+ fn swrl_i_arg(&mut self) -> Result<NamedOrBlankNode, Fail> {
+ if self.peek_keyword("Variable")? {
+ self.lx.next()?;
+ return Ok(self.swrl_variable()?.into());
+ }
+ self.individual()
+ }
+
+ fn swrl_d_arg(&mut self) -> Result<Term, Fail> {
+ if self.peek_keyword("Variable")? {
+ self.lx.next()?;
+ return Ok(self.swrl_variable()?.into());
+ }
+ Ok(self.literal()?.into())
+ }
+
+ fn swrl_atom(&mut self) -> Result<BlankNode, Fail> {
+ let (tok, line) = self.lx.next()?;
+ let Tok::Word(kw) = tok else {
+ return syntax(line, format!("expected a SWRL atom, found {tok}"));
+ };
+ self.expect_open(kw)?;
+ let x = BlankNode::default();
+ let ty = rdf::TYPE.into_owned();
+ match kw {
+ "ClassAtom" => {
+ let ce = self.class_expr()?;
+ let a = self.swrl_i_arg()?;
+ self.push(x.clone(), ty, swrl!("ClassAtom"));
+ self.push(x.clone(), swrl!("classPredicate"), ce);
+ self.push(x.clone(), swrl!("argument1"), a);
+ }
+ "DataRangeAtom" => {
+ let dr = self.data_range()?;
+ let a = self.swrl_d_arg()?;
+ self.push(x.clone(), ty, swrl!("DataRangeAtom"));
+ self.push(x.clone(), swrl!("dataRange"), dr);
+ self.push(x.clone(), swrl!("argument1"), a);
+ }
+ "ObjectPropertyAtom" => {
+ let ope = self.object_property_expr()?;
+ let a = self.swrl_i_arg()?;
+ let b = self.swrl_i_arg()?;
+ self.push(x.clone(), ty, swrl!("IndividualPropertyAtom"));
+ self.push(x.clone(), swrl!("propertyPredicate"), ope);
+ self.push(x.clone(), swrl!("argument1"), a);
+ self.push(x.clone(), swrl!("argument2"), b);
+ }
+ "DataPropertyAtom" => {
+ let dp = self.iri("data property")?;
+ let a = self.swrl_i_arg()?;
+ let b = self.swrl_d_arg()?;
+ self.push(x.clone(), ty, swrl!("DatavaluedPropertyAtom"));
+ self.push(x.clone(), swrl!("propertyPredicate"), dp);
+ self.push(x.clone(), swrl!("argument1"), a);
+ self.push(x.clone(), swrl!("argument2"), b);
+ }
+ "BuiltInAtom" => {
+ let builtin = self.iri("built-in")?;
+ let mut args: Vec<Term> = Vec::new();
+ while !self.at_close()? {
+ args.push(self.swrl_d_arg()?);
+ }
+ self.push(x.clone(), ty, swrl!("BuiltinAtom"));
+ self.push(x.clone(), swrl!("builtin"), builtin);
+ let list = self.list(args);
+ self.push(x.clone(), swrl!("arguments"), list);
+ }
+ "SameIndividualAtom" | "DifferentIndividualsAtom" => {
+ let a = self.swrl_i_arg()?;
+ let b = self.swrl_i_arg()?;
+ let class = if kw == "SameIndividualAtom" {
+ swrl!("SameIndividualAtom")
+ } else {
+ swrl!("DifferentIndividualsAtom")
+ };
+ self.push(x.clone(), ty, class);
+ self.push(x.clone(), swrl!("argument1"), a);
+ self.push(x.clone(), swrl!("argument2"), b);
+ }
+ other => return Err(self.misplaced(other, line, "a SWRL atom")),
+ }
+ self.expect_close(kw)?;
+ Ok(x)
+ }
+
+ // ---- document ------------------------------------------------------- //
+
+ fn document(&mut self) -> Result<(), Fail> {
+ loop {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Word("Prefix") => self.prefix()?,
+ Tok::Word("Ontology") => {
+ self.ontology()?;
+ break;
+ }
+ Tok::Eof => return syntax(line, "no `Ontology(` found"),
+ other => {
+ return syntax(line, format!("expected `Prefix(` or `Ontology(`, found {other}"));
+ }
+ }
+ }
+ match self.lx.next()? {
+ (Tok::Eof, _) => Ok(()),
+ (tok, line) => syntax(
+ line,
+ format!("text after the closing `)` of `Ontology(`: {tok}"),
+ ),
+ }
+ }
+
+ fn prefix(&mut self) -> Result<(), Fail> {
+ self.expect_open("Prefix")?;
+ let (tok, line) = self.lx.next()?;
+ let name = match tok {
+ Tok::Word(w) if w.ends_with(':') && w.matches(':').count() == 1 => &w[..w.len() - 1],
+ other => return syntax(line, format!("expected a prefix name such as `owl:`, found {other}")),
+ };
+ match self.lx.next()? {
+ (Tok::Eq, _) => {}
+ (tok, line) => return syntax(line, format!("expected `=` in Prefix, found {tok}")),
+ }
+ let (tok, line) = self.lx.next()?;
+ let Tok::Iri(iri) = tok else {
+ return syntax(line, format!("expected `<IRI>` in Prefix, found {tok}"));
+ };
+ self.prefixes.insert(name, iri.to_string());
+ self.expect_close("Prefix")
+ }
+
+ fn ontology(&mut self) -> Result<(), Fail> {
+ self.expect_open("Ontology")?;
+ let subject: NamedOrBlankNode = if is_iri_token(self.lx.peek()?) {
+ let iri = self.iri("ontology")?;
+ if is_iri_token(self.lx.peek()?) {
+ let version = self.iri("version")?;
+ self.push(iri.clone(), owl!("versionIRI"), version);
+ }
+ iri.into()
+ } else {
+ BlankNode::default().into()
+ };
+ self.push(subject.clone(), rdf::TYPE.into_owned(), owl!("Ontology"));
+
+ loop {
+ let (tok, line) = self.lx.next()?;
+ match tok {
+ Tok::Close => return Ok(()),
+ Tok::Word("Import") => {
+ self.expect_open("Import")?;
+ let iri = self.iri("imported ontology")?;
+ self.expect_close("Import")?;
+ self.push(subject.clone(), owl!("imports"), iri);
+ }
+ Tok::Word("Annotation") => {
+ let ann = self.annotation_body()?;
+ self.tann(subject.clone(), &ann);
+ }
+ Tok::Word(kw) if !kw.contains(':') => {
+ // The depth OUTSIDE this axiom. Whatever goes wrong inside
+ // it, a refusal is recovered from by reading until the
+ // parentheses close back to here.
+ let depth = self.lx.depth;
+ match self.axiom(kw, line) {
+ Ok(()) => {}
+ Err(Fail::Refuse { construct, line }) => {
+ self.refusals.push((construct, line));
+ while self.lx.depth > depth {
+ if let (Tok::Eof, l) = self.lx.next()? {
+ return syntax(l, "document ended inside an axiom");
+ }
+ }
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ Tok::Eof => return syntax(line, "document ended before `Ontology(` was closed"),
+ other => return syntax(line, format!("expected an axiom, found {other}")),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sniffing_tells_ofn_from_turtle_and_manchester() {
+ assert!(looks_like_ofn("Prefix(:=<http://e/>)\nOntology()"));
+ assert!(looks_like_ofn("# c\n\n Ontology (<http://e/>)"));
+ assert!(!looks_like_ofn("PREFIX ex: <http://e/>\n"));
+ assert!(!looks_like_ofn("Prefix: ex: <http://e/>\n"));
+ assert!(!looks_like_ofn("@prefix ex: <http://e/> ."));
+ }
+
+ #[test]
+ fn line_numbers_survive_comments_and_multiline_strings() {
+ let doc = "Prefix(:=<http://e/>)\n# comment ( with parens\nOntology(\nAnnotationAssertion(rdfs:label :a \"two\nlines\")\nSubClassOf(:a)\n)";
+ match parse(doc) {
+ Err(OfnError::Syntax { line, .. }) => assert_eq!(line, 6),
+ other => panic!("expected a syntax error, got {other:?}"),
+ }
+ }
+}
diff --git a/src/ontology.rs b/src/ontology.rs
index 6c59e1dd..0db5b6f0 100644
--- a/src/ontology.rs
+++ b/src/ontology.rs
@@ -14,7 +14,7 @@ pub struct OntologyService;
impl OntologyService {
/// Validate RDF syntax. Returns a JSON report (never errors on bad input).
pub fn validate_string(content: &str) -> anyhow::Result<String> {
- match GraphStore::validate_turtle(content) {
+ match GraphStore::validate_text(content) {
Ok(counts) => Ok(serde_json::json!({
"valid": true,
"triple_count": counts.triples,
diff --git a/src/repo.rs b/src/repo.rs
index 2fc344d9..3ef24ee2 100644
--- a/src/repo.rs
+++ b/src/repo.rs
@@ -13,10 +13,12 @@ use std::time::UNIX_EPOCH;
use anyhow::{anyhow, Result};
-/// File extensions the RDF parser (`GraphStore::detect_format`) accepts.
-/// Lowercased, without the leading dot. Keep in sync with `graph.rs`.
+/// File extensions the loaders accept: the RDF parser's
+/// (`GraphStore::detect_format`) and `.ofn`, which `GraphStore` hands to the
+/// OWL functional-syntax reader. Lowercased, without the leading dot. Keep in
+/// sync with `graph.rs`.
pub const RDF_EXTENSIONS: &[&str] = &[
- "ttl", "turtle", "nt", "ntriples", "rdf", "xml", "owl", "nq", "trig", "jsonld",
+ "ttl", "turtle", "nt", "ntriples", "rdf", "xml", "owl", "nq", "trig", "jsonld", "ofn",
];
/// True if `path`'s extension is one of `RDF_EXTENSIONS` (case-insensitive).
diff --git a/src/server.rs b/src/server.rs
index 285c899a..38ce13cb 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -322,7 +322,7 @@ impl OpenOntologiesServer {
// ── Ontology ────────────────────────────────────────────────────────────
- #[tool(name = "onto_validate", description = "Validate RDF/OWL syntax. Accepts a file path or inline Turtle content.")]
+ #[tool(name = "onto_validate", description = "Validate RDF/OWL syntax. Accepts a file path or inline content. A file may be Turtle, N-Triples, RDF/XML, N-Quads, TriG, JSON-LD or OWL 2 functional syntax (OFN), and the content is sniffed before the extension is trusted, so an OFN document published as `.owl` is read as OFN. Inline content is Turtle unless it opens with `Prefix(` or `Ontology(`, in which case it is OFN. An OFN construct the reader does not translate is an error naming the construct, its count and its first line, never a silent drop.")]
async fn onto_validate(&self, Parameters(input): Parameters<OntoValidateInput>) -> String {
use crate::ontology::OntologyService;
if input.inline.unwrap_or(false) {
@@ -332,7 +332,7 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_convert", description = "Convert an RDF file between formats: turtle, ntriples, rdfxml, nquads, trig")]
+ #[tool(name = "onto_convert", description = "Convert an ontology file to turtle, ntriples, rdfxml, nquads or trig. Reads every format onto_load reads, OWL 2 functional syntax (OFN) included, so this is also the way to turn an OFN document into RDF.")]
async fn onto_convert(&self, Parameters(input): Parameters<OntoConvertInput>) -> String {
let store = GraphStore::new();
match store.load_file(&input.path) {
@@ -355,7 +355,7 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_load", description = "Load an RDF file or inline Turtle content into the in-memory ontology store. When given a file path, the parsed graph is also written to a fast N-Triples compile cache (in `[cache] dir`) so subsequent loads from the same source skip parsing. Optional `name`, `auto_refresh`, and `force_recompile` flags control caching/refresh behavior.")]
+ #[tool(name = "onto_load", description = "Load an ontology file or inline Turtle content into the in-memory ontology store. A file may be Turtle, N-Triples, RDF/XML, N-Quads, TriG, JSON-LD or OWL 2 functional syntax (OFN, `.ofn`, or any extension whose content opens with `Prefix(` or `Ontology(`, which covers OFN published as `.owl`); OFN is translated to the RDF graph the W3C OWL 2 mapping assigns it, and a construct the reader does not translate fails the load by name rather than being dropped. When given a file path, the parsed graph is also written to a fast N-Triples compile cache (in `[cache] dir`) so subsequent loads from the same source skip parsing. Optional `name`, `auto_refresh`, and `force_recompile` flags control caching/refresh behavior.")]
async fn onto_load(&self, Parameters(input): Parameters<OntoLoadInput>) -> String {
if let Some(turtle) = input.turtle {
// Inline turtle bypasses the registry/cache (no source file).
diff --git a/tests/fixtures/ofn/all_constructs.ofn b/tests/fixtures/ofn/all_constructs.ofn
new file mode 100644
index 00000000..3544fb00
--- /dev/null
+++ b/tests/fixtures/ofn/all_constructs.ofn
@@ -0,0 +1,126 @@
+# Every construct family the OFN reader translates, in one document.
+# The companion all_constructs.owlapi.nt is what OWL API 4.5.29 writes for
+# this file (RDF/XML, re-serialised to N-Triples by Oxigraph); see
+# tests/ofn_reader_test.rs for the differences that are expected and why.
+Prefix(:=<http://example.org/ofn#>)
+Prefix(owl:=<http://www.w3.org/2002/07/owl#>)
+Prefix(rdf:=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>)
+Prefix(rdfs:=<http://www.w3.org/2000/01/rdf-schema#>)
+Prefix(xsd:=<http://www.w3.org/2001/XMLSchema#>)
+
+Ontology(<http://example.org/ofn> <http://example.org/ofn/1.0>
+Import(<http://example.org/imported>)
+Annotation(rdfs:comment "An ontology that uses everything.")
+
+Declaration(Class(:A))
+Declaration(Class(:B))
+Declaration(Class(:C))
+Declaration(Class(:D))
+Declaration(Class(:Person))
+Declaration(Datatype(:SmallInt))
+Declaration(ObjectProperty(:r))
+Declaration(ObjectProperty(:s))
+Declaration(ObjectProperty(:t))
+Declaration(ObjectProperty(:hasParent))
+Declaration(ObjectProperty(:hasGrandparent))
+Declaration(DataProperty(:age))
+Declaration(DataProperty(:name))
+Declaration(DataProperty(:nick))
+Declaration(AnnotationProperty(:note))
+Declaration(AnnotationProperty(:subnote))
+Declaration(NamedIndividual(:i))
+Declaration(NamedIndividual(:j))
+Declaration(NamedIndividual(:k))
+Declaration(Annotation(:note "declared with a note") Class(:Annotated))
+
+############################ class expressions
+SubClassOf(:A ObjectIntersectionOf(:B :C))
+SubClassOf(:A ObjectUnionOf(:B ObjectComplementOf(:C)))
+SubClassOf(:A ObjectOneOf(:i :j))
+SubClassOf(:A ObjectSomeValuesFrom(:r :B))
+SubClassOf(:A ObjectAllValuesFrom(ObjectInverseOf(:r) :B))
+SubClassOf(:A ObjectHasValue(:r :i))
+SubClassOf(:A ObjectHasSelf(:r))
+SubClassOf(:A ObjectMinCardinality(2 :r))
+SubClassOf(:A ObjectMaxCardinality(3 :r :B))
+SubClassOf(:A ObjectExactCardinality(1 :s :C))
+SubClassOf(:A ObjectExactCardinality(4 :s))
+SubClassOf(:A ObjectMinCardinality(1 :t owl:Thing))
+SubClassOf(:Undeclared :A)
+
+############################ data ranges and data restrictions
+SubClassOf(:B DataSomeValuesFrom(:age DatatypeRestriction(xsd:integer xsd:minInclusive "0"^^xsd:integer xsd:maxExclusive "150"^^xsd:integer)))
+SubClassOf(:B DataAllValuesFrom(:name DataUnionOf(xsd:string DataOneOf("x" "y"@en))))
+SubClassOf(:B DataSomeValuesFrom(:age DataIntersectionOf(xsd:integer DataComplementOf(xsd:negativeInteger))))
+SubClassOf(:B DataHasValue(:name "Bob"))
+SubClassOf(:B DataMinCardinality(1 :name))
+SubClassOf(:B DataMaxCardinality(2 :name xsd:string))
+SubClassOf(:B DataExactCardinality(1 :age))
+DatatypeDefinition(:SmallInt DatatypeRestriction(xsd:integer xsd:maxInclusive "10"^^xsd:integer))
+
+############################ class axioms
+EquivalentClasses(:C :D ObjectSomeValuesFrom(:s :A))
+DisjointClasses(:A :D)
+DisjointClasses(:B :C :Person)
+DisjointUnion(:Person :A :B)
+
+############################ object property axioms
+SubObjectPropertyOf(:s :r)
+SubObjectPropertyOf(ObjectPropertyChain(:hasParent :hasParent) :hasGrandparent)
+EquivalentObjectProperties(:s :t)
+DisjointObjectProperties(:hasParent :t)
+DisjointObjectProperties(:hasGrandparent :hasParent :r)
+InverseObjectProperties(:r ObjectInverseOf(:s))
+ObjectPropertyDomain(:r :A)
+ObjectPropertyRange(:r :B)
+FunctionalObjectProperty(:hasParent)
+InverseFunctionalObjectProperty(:hasParent)
+ReflexiveObjectProperty(:t)
+IrreflexiveObjectProperty(:hasParent)
+SymmetricObjectProperty(:t)
+AsymmetricObjectProperty(:hasParent)
+TransitiveObjectProperty(:hasGrandparent)
+
+############################ data property axioms
+SubDataPropertyOf(:nick :name)
+EquivalentDataProperties(:name :nick)
+DisjointDataProperties(:age :name)
+DataPropertyDomain(:age :Person)
+DataPropertyRange(:age xsd:nonNegativeInteger)
+FunctionalDataProperty(:age)
+HasKey(:Person (:hasParent) (:name))
+
+############################ assertions
+SameIndividual(:i :j)
+DifferentIndividuals(:i :k)
+DifferentIndividuals(:i :j :k)
+ClassAssertion(:A :i)
+ClassAssertion(ObjectSomeValuesFrom(:r :B) _:anon1)
+ObjectPropertyAssertion(:r :i :j)
+ObjectPropertyAssertion(ObjectInverseOf(:s) :i :k)
+ObjectPropertyAssertion(:r _:anon1 :k)
+NegativeObjectPropertyAssertion(:r :j :k)
+DataPropertyAssertion(:age :i "42"^^xsd:integer)
+DataPropertyAssertion(:name :i "Ian \"the \\ quoted\""@en-GB)
+DataPropertyAssertion(:nick :i "plain@"^^rdf:PlainLiteral)
+DataPropertyAssertion(:nick :j "tagged@fr"^^rdf:PlainLiteral)
+NegativeDataPropertyAssertion(:age :j "7"^^xsd:integer)
+
+############################ annotation axioms
+AnnotationAssertion(rdfs:label :A "A label"@en)
+AnnotationAssertion(:note :A <http://example.org/elsewhere>)
+AnnotationAssertion(:note _:anon1 "about an anonymous individual")
+SubAnnotationPropertyOf(:subnote :note)
+AnnotationPropertyDomain(:note :A)
+AnnotationPropertyRange(:note xsd:string)
+
+############################ annotated axioms
+SubClassOf(Annotation(Annotation(:note "nested") rdfs:comment "Children are people.") :C :Person)
+EquivalentClasses(Annotation(:note "three-way") :A :B :C)
+DisjointClasses(Annotation(:note "pairwise") :C :D)
+DisjointClasses(Annotation(:note "n-ary") :A :C :D)
+DisjointUnion(Annotation(:note "union") :D :A :C)
+SubObjectPropertyOf(Annotation(:note "chain") ObjectPropertyChain(:r :s) :t)
+NegativeObjectPropertyAssertion(Annotation(:note "negative") :s :i :k)
+HasKey(Annotation(:note "key") :A () (:age))
+)
diff --git a/tests/fixtures/ofn/all_constructs.owlapi.nt b/tests/fixtures/ofn/all_constructs.owlapi.nt
new file mode 100644
index 00000000..eb10dab9
--- /dev/null
+++ b/tests/fixtures/ofn/all_constructs.owlapi.nt
@@ -0,0 +1,383 @@
+<http://example.org/ofn#A> <http://example.org/ofn#note> <http://example.org/elsewhere> .
+<http://example.org/ofn#A> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#label> "A label"@en .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N09ba1f844bf64d67be384d3d44f571ec .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N14357969e7884d91b154c8ced0956e19 .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N24a51cedaf0d407c9748706ec1c98d1b .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N29300209bf1840c78003da7219ff1f67 .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N42a27c579f674395844e9aa0643dc96b .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N7294666c0fc64fccbf6b93e1d4e0e865 .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N8fa05e5262574e36a9a066b8edd9952d .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nc2ac432d8bf24f2990bebec0d2525670 .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nc41f849034a647cbb99fe862e3b6b828 .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nc8965472e13541f295502bd0c996b5b9 .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nebfa578f8a6e4b548338ef0a12b0a975 .
+<http://example.org/ofn#A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nfc03edb66e694ea6a3a93914123fda96 .
+<http://example.org/ofn#A> <http://www.w3.org/2002/07/owl#disjointWith> <http://example.org/ofn#D> .
+<http://example.org/ofn#A> <http://www.w3.org/2002/07/owl#equivalentClass> <http://example.org/ofn#B> .
+<http://example.org/ofn#A> <http://www.w3.org/2002/07/owl#hasKey> _:N6ec4b8533f1442dbb28014cebcb49f8c .
+<http://example.org/ofn#Annotated> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+<http://example.org/ofn#B> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+<http://example.org/ofn#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N3630c0f30b1c41bdaf7a4391f2cfe2f1 .
+<http://example.org/ofn#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N5d5b7518b92446c49af0922b515f001f .
+<http://example.org/ofn#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:N77a5bf08554c459091c6bcfdf1d36e89 .
+<http://example.org/ofn#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nb06421c63c084df0b032192b010ed3a8 .
+<http://example.org/ofn#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nb1d0c1c88da54074a781866ca3343e91 .
+<http://example.org/ofn#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nb27ca665847c45169ff1c5b643f0749f .
+<http://example.org/ofn#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:Nc82ca09a6a7d44d097368c84d91d7e24 .
+<http://example.org/ofn#B> <http://www.w3.org/2002/07/owl#equivalentClass> <http://example.org/ofn#C> .
+<http://example.org/ofn#C> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+<http://example.org/ofn#C> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://example.org/ofn#Person> .
+<http://example.org/ofn#C> <http://www.w3.org/2002/07/owl#disjointWith> <http://example.org/ofn#D> .
+<http://example.org/ofn#C> <http://www.w3.org/2002/07/owl#equivalentClass> <http://example.org/ofn#D> .
+<http://example.org/ofn#D> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+<http://example.org/ofn#D> <http://www.w3.org/2002/07/owl#disjointUnionOf> _:N7a9770d952ac4244945c839ebe9d589e .
+<http://example.org/ofn#D> <http://www.w3.org/2002/07/owl#equivalentClass> _:N14620c5c72f74cf29d3a2bbb783da0a1 .
+<http://example.org/ofn#Person> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+<http://example.org/ofn#Person> <http://www.w3.org/2002/07/owl#disjointUnionOf> _:N73912197598d461c849ffa0cfe92abc3 .
+<http://example.org/ofn#Person> <http://www.w3.org/2002/07/owl#hasKey> _:N5288deb053174a76a7dafe98deec8aee .
+<http://example.org/ofn#SmallInt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Datatype> .
+<http://example.org/ofn#SmallInt> <http://www.w3.org/2002/07/owl#equivalentClass> _:Nbd5f0423d9634003bfbb847b423b350b .
+<http://example.org/ofn#Undeclared> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+<http://example.org/ofn#Undeclared> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://example.org/ofn#A> .
+<http://example.org/ofn#age> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#DatatypeProperty> .
+<http://example.org/ofn#age> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#FunctionalProperty> .
+<http://example.org/ofn#age> <http://www.w3.org/2000/01/rdf-schema#domain> <http://example.org/ofn#Person> .
+<http://example.org/ofn#age> <http://www.w3.org/2000/01/rdf-schema#range> <http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+<http://example.org/ofn#age> <http://www.w3.org/2002/07/owl#propertyDisjointWith> <http://example.org/ofn#name> .
+<http://example.org/ofn#hasGrandparent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .
+<http://example.org/ofn#hasGrandparent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#TransitiveProperty> .
+<http://example.org/ofn#hasGrandparent> <http://www.w3.org/2002/07/owl#propertyChainAxiom> _:N58db931cbf6b4654b56ddc502f3d4a07 .
+<http://example.org/ofn#hasParent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#AsymmetricProperty> .
+<http://example.org/ofn#hasParent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#FunctionalProperty> .
+<http://example.org/ofn#hasParent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> .
+<http://example.org/ofn#hasParent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#IrreflexiveProperty> .
+<http://example.org/ofn#hasParent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .
+<http://example.org/ofn#hasParent> <http://www.w3.org/2002/07/owl#propertyDisjointWith> <http://example.org/ofn#t> .
+<http://example.org/ofn#i> <http://example.org/ofn#age> "42"^^<http://www.w3.org/2001/XMLSchema#integer> .
+<http://example.org/ofn#i> <http://example.org/ofn#name> "Ian \"the \\ quoted\""@en-gb .
+<http://example.org/ofn#i> <http://example.org/ofn#nick> "plain" .
+<http://example.org/ofn#i> <http://example.org/ofn#r> <http://example.org/ofn#j> .
+<http://example.org/ofn#i> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.org/ofn#A> .
+<http://example.org/ofn#i> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NamedIndividual> .
+<http://example.org/ofn#i> <http://www.w3.org/2002/07/owl#differentFrom> <http://example.org/ofn#k> .
+<http://example.org/ofn#i> <http://www.w3.org/2002/07/owl#sameAs> <http://example.org/ofn#j> .
+<http://example.org/ofn#j> <http://example.org/ofn#nick> "tagged"@fr .
+<http://example.org/ofn#j> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NamedIndividual> .
+<http://example.org/ofn#k> <http://example.org/ofn#s> <http://example.org/ofn#i> .
+<http://example.org/ofn#k> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NamedIndividual> .
+<http://example.org/ofn#name> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#DatatypeProperty> .
+<http://example.org/ofn#name> <http://www.w3.org/2002/07/owl#equivalentProperty> <http://example.org/ofn#nick> .
+<http://example.org/ofn#nick> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#DatatypeProperty> .
+<http://example.org/ofn#nick> <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> <http://example.org/ofn#name> .
+<http://example.org/ofn#note> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#AnnotationProperty> .
+<http://example.org/ofn#note> <http://www.w3.org/2000/01/rdf-schema#domain> <http://example.org/ofn#A> .
+<http://example.org/ofn#note> <http://www.w3.org/2000/01/rdf-schema#range> <http://www.w3.org/2001/XMLSchema#string> .
+<http://example.org/ofn#r> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .
+<http://example.org/ofn#r> <http://www.w3.org/2000/01/rdf-schema#domain> <http://example.org/ofn#A> .
+<http://example.org/ofn#r> <http://www.w3.org/2000/01/rdf-schema#range> <http://example.org/ofn#B> .
+<http://example.org/ofn#r> <http://www.w3.org/2002/07/owl#inverseOf> _:N6d1a83741b294eedb47ee20c5a6a130d .
+<http://example.org/ofn#s> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .
+<http://example.org/ofn#s> <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> <http://example.org/ofn#r> .
+<http://example.org/ofn#s> <http://www.w3.org/2002/07/owl#equivalentProperty> <http://example.org/ofn#t> .
+<http://example.org/ofn#subnote> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#AnnotationProperty> .
+<http://example.org/ofn#subnote> <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> <http://example.org/ofn#note> .
+<http://example.org/ofn#t> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .
+<http://example.org/ofn#t> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ReflexiveProperty> .
+<http://example.org/ofn#t> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#SymmetricProperty> .
+<http://example.org/ofn#t> <http://www.w3.org/2002/07/owl#propertyChainAxiom> _:N21f47c7cdef2421199b3c2ee41603bf4 .
+<http://example.org/ofn> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Ontology> .
+<http://example.org/ofn> <http://www.w3.org/2000/01/rdf-schema#comment> "An ontology that uses everything." .
+<http://example.org/ofn> <http://www.w3.org/2002/07/owl#imports> <http://example.org/imported> .
+<http://example.org/ofn> <http://www.w3.org/2002/07/owl#versionIRI> <http://example.org/ofn/1.0> .
+_:N00a52d244566421aaa07018582205b31 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#i> .
+_:N00a52d244566421aaa07018582205b31 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N486cd9015de14ca9afa4c1122950c172 .
+_:N02fc58b54f0b463993d6ada6a9913753 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#A> .
+_:N02fc58b54f0b463993d6ada6a9913753 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N3eb3b97f29374adfa5b81b8a02742e24 .
+_:N0301af48672a487080834492804295cd <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N0301af48672a487080834492804295cd <http://www.w3.org/2000/01/rdf-schema#comment> "Children are people." .
+_:N0301af48672a487080834492804295cd <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2000/01/rdf-schema#subClassOf> .
+_:N0301af48672a487080834492804295cd <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#C> .
+_:N0301af48672a487080834492804295cd <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#Person> .
+_:N065c0af020ab46a4a6ecdec3fbdd2b3c <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Datatype> .
+_:N065c0af020ab46a4a6ecdec3fbdd2b3c <http://www.w3.org/2002/07/owl#onDatatype> <http://www.w3.org/2001/XMLSchema#integer> .
+_:N065c0af020ab46a4a6ecdec3fbdd2b3c <http://www.w3.org/2002/07/owl#withRestrictions> _:N58d1e79dcbec42bdabd0fc4f141cc8f8 .
+_:N071081c9daf44894bfd77fea1c158ddd <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#C> .
+_:N071081c9daf44894bfd77fea1c158ddd <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N70edcb5b56a544238f20a3b82c5b341a .
+_:N075fac34cd194ebebf8dce630f2f192c <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#s> .
+_:N075fac34cd194ebebf8dce630f2f192c <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N08891c3e507b45baa24dce414ecb151d <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Datatype> .
+_:N08891c3e507b45baa24dce414ecb151d <http://www.w3.org/2002/07/owl#datatypeComplementOf> <http://www.w3.org/2001/XMLSchema#negativeInteger> .
+_:N08e1b6542e9b473d92472caf0799c19d <http://example.org/ofn#note> "key" .
+_:N08e1b6542e9b473d92472caf0799c19d <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N08e1b6542e9b473d92472caf0799c19d <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#hasKey> .
+_:N08e1b6542e9b473d92472caf0799c19d <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#A> .
+_:N08e1b6542e9b473d92472caf0799c19d <http://www.w3.org/2002/07/owl#annotatedTarget> _:Ne34e7c9d4f784193a4ce3d7831cdffb4 .
+_:N09ba1f844bf64d67be384d3d44f571ec <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N09ba1f844bf64d67be384d3d44f571ec <http://www.w3.org/2002/07/owl#minCardinality> "1"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:N09ba1f844bf64d67be384d3d44f571ec <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#t> .
+_:N14357969e7884d91b154c8ced0956e19 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N14357969e7884d91b154c8ced0956e19 <http://www.w3.org/2002/07/owl#hasSelf> "true"^^<http://www.w3.org/2001/XMLSchema#boolean> .
+_:N14357969e7884d91b154c8ced0956e19 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#r> .
+_:N14620c5c72f74cf29d3a2bbb783da0a1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N14620c5c72f74cf29d3a2bbb783da0a1 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#s> .
+_:N14620c5c72f74cf29d3a2bbb783da0a1 <http://www.w3.org/2002/07/owl#someValuesFrom> <http://example.org/ofn#A> .
+_:N1665fe407ba94ecea814a9829c12ca2f <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "y"@en .
+_:N1665fe407ba94ecea814a9829c12ca2f <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N1665fe407ba94ecea814a9829c12ca2f <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#List> .
+_:N20b70ff41ca9455787e1d33bb4f0b163 <http://example.org/ofn#note> "chain" .
+_:N20b70ff41ca9455787e1d33bb4f0b163 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N20b70ff41ca9455787e1d33bb4f0b163 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#propertyChainAxiom> .
+_:N20b70ff41ca9455787e1d33bb4f0b163 <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#t> .
+_:N20b70ff41ca9455787e1d33bb4f0b163 <http://www.w3.org/2002/07/owl#annotatedTarget> _:N3de9141c890d498fac23ad6d1ede53d0 .
+_:N21f47c7cdef2421199b3c2ee41603bf4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#r> .
+_:N21f47c7cdef2421199b3c2ee41603bf4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Nef3b4ac7eb3c46c3a67ebf9818d419f9 .
+_:N24a51cedaf0d407c9748706ec1c98d1b <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N24a51cedaf0d407c9748706ec1c98d1b <http://www.w3.org/2002/07/owl#onClass> <http://example.org/ofn#C> .
+_:N24a51cedaf0d407c9748706ec1c98d1b <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#s> .
+_:N24a51cedaf0d407c9748706ec1c98d1b <http://www.w3.org/2002/07/owl#qualifiedCardinality> "1"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:N29300209bf1840c78003da7219ff1f67 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N29300209bf1840c78003da7219ff1f67 <http://www.w3.org/2002/07/owl#allValuesFrom> <http://example.org/ofn#B> .
+_:N29300209bf1840c78003da7219ff1f67 <http://www.w3.org/2002/07/owl#onProperty> _:Ne41ae497dc0241d7841d8ee410fe6df6 .
+_:N2aadc68440904d60b82fd0d6c0006a06 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#hasParent> .
+_:N2aadc68440904d60b82fd0d6c0006a06 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N2e11307efd4b4a219bb63b26ce992310 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:N33a6950efa954b6493d3ccf5d0dfb4f3 .
+_:N2e11307efd4b4a219bb63b26ce992310 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N2f4267ea7eda4abda0a29d7407cacefe <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#AllDifferent> .
+_:N2f4267ea7eda4abda0a29d7407cacefe <http://www.w3.org/2002/07/owl#distinctMembers> _:Nc9a69822a5c14c94b777083e1042e52b .
+_:N33a6950efa954b6493d3ccf5d0dfb4f3 <http://www.w3.org/2001/XMLSchema#maxExclusive> "150"^^<http://www.w3.org/2001/XMLSchema#integer> .
+_:N34350379ae754c7d9589b6fd65ec649c <http://example.org/ofn#note> "three-way" .
+_:N34350379ae754c7d9589b6fd65ec649c <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N34350379ae754c7d9589b6fd65ec649c <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#equivalentClass> .
+_:N34350379ae754c7d9589b6fd65ec649c <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#A> .
+_:N34350379ae754c7d9589b6fd65ec649c <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#B> .
+_:N360b168e053b4480a11fd620e30df4b3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#AllDisjointProperties> .
+_:N360b168e053b4480a11fd620e30df4b3 <http://www.w3.org/2002/07/owl#members> _:Nf0a77fe65cbc4a5abe95f09e814e0839 .
+_:N3630c0f30b1c41bdaf7a4391f2cfe2f1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N3630c0f30b1c41bdaf7a4391f2cfe2f1 <http://www.w3.org/2002/07/owl#minCardinality> "1"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:N3630c0f30b1c41bdaf7a4391f2cfe2f1 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#name> .
+_:N38fb5b1aa0ca4761b3e2494b45814202 <http://example.org/ofn#note> "three-way" .
+_:N38fb5b1aa0ca4761b3e2494b45814202 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N38fb5b1aa0ca4761b3e2494b45814202 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#equivalentClass> .
+_:N38fb5b1aa0ca4761b3e2494b45814202 <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#B> .
+_:N38fb5b1aa0ca4761b3e2494b45814202 <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#C> .
+_:N3de9141c890d498fac23ad6d1ede53d0 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#r> .
+_:N3de9141c890d498fac23ad6d1ede53d0 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N075fac34cd194ebebf8dce630f2f192c .
+_:N3eb3b97f29374adfa5b81b8a02742e24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#C> .
+_:N3eb3b97f29374adfa5b81b8a02742e24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N3ec5271eb9be43a9a3217f75b9b5eb63 <http://example.org/ofn#note> "nested" .
+_:N3ec5271eb9be43a9a3217f75b9b5eb63 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Annotation> .
+_:N3ec5271eb9be43a9a3217f75b9b5eb63 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2000/01/rdf-schema#comment> .
+_:N3ec5271eb9be43a9a3217f75b9b5eb63 <http://www.w3.org/2002/07/owl#annotatedSource> _:N0301af48672a487080834492804295cd .
+_:N3ec5271eb9be43a9a3217f75b9b5eb63 <http://www.w3.org/2002/07/owl#annotatedTarget> "Children are people." .
+_:N42a27c579f674395844e9aa0643dc96b <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+_:N42a27c579f674395844e9aa0643dc96b <http://www.w3.org/2002/07/owl#intersectionOf> _:N80fddd75f07b4efd81e86a4b99a3f612 .
+_:N432eb9b0944f492da3a3f198a84639c6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#B> .
+_:N432eb9b0944f492da3a3f198a84639c6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N486cd9015de14ca9afa4c1122950c172 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#j> .
+_:N486cd9015de14ca9afa4c1122950c172 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N4d42a395713e4586b71324634ffc805b <http://example.org/ofn#note> "key" .
+_:N4d42a395713e4586b71324634ffc805b <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N4d42a395713e4586b71324634ffc805b <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#hasKey> .
+_:N4d42a395713e4586b71324634ffc805b <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#A> .
+_:N4d42a395713e4586b71324634ffc805b <http://www.w3.org/2002/07/owl#annotatedTarget> _:N731bd666c11440148ba174ec9f927ab2 .
+_:N5288deb053174a76a7dafe98deec8aee <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#hasParent> .
+_:N5288deb053174a76a7dafe98deec8aee <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Nda5282355a1f4ebbad0487f9a8f3b8c7 .
+_:N58d1e79dcbec42bdabd0fc4f141cc8f8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:N675385d487b84b59b0156611383a95e4 .
+_:N58d1e79dcbec42bdabd0fc4f141cc8f8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N2e11307efd4b4a219bb63b26ce992310 .
+_:N58db931cbf6b4654b56ddc502f3d4a07 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#hasParent> .
+_:N58db931cbf6b4654b56ddc502f3d4a07 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N2aadc68440904d60b82fd0d6c0006a06 .
+_:N5aebd1d53b6b429396847d45175b8200 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#B> .
+_:N5aebd1d53b6b429396847d45175b8200 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N071081c9daf44894bfd77fea1c158ddd .
+_:N5d5b7518b92446c49af0922b515f001f <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N5d5b7518b92446c49af0922b515f001f <http://www.w3.org/2002/07/owl#cardinality> "1"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:N5d5b7518b92446c49af0922b515f001f <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#age> .
+_:N6330b79b21b04d078c09d08b66fb062c <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:Na847b775ebd24373a13e760ca325869e .
+_:N6330b79b21b04d078c09d08b66fb062c <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N675385d487b84b59b0156611383a95e4 <http://www.w3.org/2001/XMLSchema#minInclusive> "0"^^<http://www.w3.org/2001/XMLSchema#integer> .
+_:N693fbab92a454bb9b9c12a00705d1506 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#k> .
+_:N693fbab92a454bb9b9c12a00705d1506 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N6d1a83741b294eedb47ee20c5a6a130d <http://www.w3.org/2002/07/owl#inverseOf> <http://example.org/ofn#s> .
+_:N6ec4b8533f1442dbb28014cebcb49f8c <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#age> .
+_:N6ec4b8533f1442dbb28014cebcb49f8c <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N70556bd9934849a88f2ba706005e3d07 <http://example.org/ofn#note> "negative" .
+_:N70556bd9934849a88f2ba706005e3d07 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NegativePropertyAssertion> .
+_:N70556bd9934849a88f2ba706005e3d07 <http://www.w3.org/2002/07/owl#assertionProperty> <http://example.org/ofn#s> .
+_:N70556bd9934849a88f2ba706005e3d07 <http://www.w3.org/2002/07/owl#sourceIndividual> <http://example.org/ofn#i> .
+_:N70556bd9934849a88f2ba706005e3d07 <http://www.w3.org/2002/07/owl#targetIndividual> <http://example.org/ofn#k> .
+_:N70edcb5b56a544238f20a3b82c5b341a <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#Person> .
+_:N70edcb5b56a544238f20a3b82c5b341a <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N7294666c0fc64fccbf6b93e1d4e0e865 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N7294666c0fc64fccbf6b93e1d4e0e865 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#r> .
+_:N7294666c0fc64fccbf6b93e1d4e0e865 <http://www.w3.org/2002/07/owl#someValuesFrom> <http://example.org/ofn#B> .
+_:N731bd666c11440148ba174ec9f927ab2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#age> .
+_:N731bd666c11440148ba174ec9f927ab2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N73912197598d461c849ffa0cfe92abc3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#A> .
+_:N73912197598d461c849ffa0cfe92abc3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N432eb9b0944f492da3a3f198a84639c6 .
+_:N77a5bf08554c459091c6bcfdf1d36e89 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N77a5bf08554c459091c6bcfdf1d36e89 <http://www.w3.org/2002/07/owl#hasValue> "Bob" .
+_:N77a5bf08554c459091c6bcfdf1d36e89 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#name> .
+_:N79e4a8e24830458c910e75d3447ccefc <http://example.org/ofn#note> "about an anonymous individual" .
+_:N79e4a8e24830458c910e75d3447ccefc <http://example.org/ofn#r> <http://example.org/ofn#k> .
+_:N79e4a8e24830458c910e75d3447ccefc <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> _:Ne9b3d9f2b7054c30ab77876b34f67dba .
+_:N7a9770d952ac4244945c839ebe9d589e <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#A> .
+_:N7a9770d952ac4244945c839ebe9d589e <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N88e323bb51cf4b1c9ea4c277e74fd037 .
+_:N80fddd75f07b4efd81e86a4b99a3f612 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#B> .
+_:N80fddd75f07b4efd81e86a4b99a3f612 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N849cf11477b34e72afea5d3cfc14af77 .
+_:N82f45e48526245fcbaf3cbf04f5aa852 <http://example.org/ofn#note> "negative" .
+_:N82f45e48526245fcbaf3cbf04f5aa852 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NegativePropertyAssertion> .
+_:N82f45e48526245fcbaf3cbf04f5aa852 <http://www.w3.org/2002/07/owl#assertionProperty> <http://example.org/ofn#s> .
+_:N82f45e48526245fcbaf3cbf04f5aa852 <http://www.w3.org/2002/07/owl#sourceIndividual> <http://example.org/ofn#i> .
+_:N82f45e48526245fcbaf3cbf04f5aa852 <http://www.w3.org/2002/07/owl#targetIndividual> <http://example.org/ofn#k> .
+_:N849cf11477b34e72afea5d3cfc14af77 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#C> .
+_:N849cf11477b34e72afea5d3cfc14af77 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N88e323bb51cf4b1c9ea4c277e74fd037 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#C> .
+_:N88e323bb51cf4b1c9ea4c277e74fd037 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N8c0a04178e8b40ff833327903e2555dd <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Datatype> .
+_:N8c0a04178e8b40ff833327903e2555dd <http://www.w3.org/2002/07/owl#unionOf> _:N94e0a44f80334459b35153a40de047e2 .
+_:N8fa05e5262574e36a9a066b8edd9952d <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:N8fa05e5262574e36a9a066b8edd9952d <http://www.w3.org/2002/07/owl#minCardinality> "2"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:N8fa05e5262574e36a9a066b8edd9952d <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#r> .
+_:N91c0cdc7aa8846ddb73a6bc289913ce4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#r> .
+_:N91c0cdc7aa8846ddb73a6bc289913ce4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:N9460a4ee3c7d42848e775f1a13f92a60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "x" .
+_:N9460a4ee3c7d42848e775f1a13f92a60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N1665fe407ba94ecea814a9829c12ca2f .
+_:N9460a4ee3c7d42848e775f1a13f92a60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#List> .
+_:N94e0a44f80334459b35153a40de047e2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://www.w3.org/2001/XMLSchema#string> .
+_:N94e0a44f80334459b35153a40de047e2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Nf2051b79e19f4adeb900394aa68ddd4e .
+_:N9a68e634b79f459eb4fe957a27bcad1d <http://example.org/ofn#note> "three-way" .
+_:N9a68e634b79f459eb4fe957a27bcad1d <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N9a68e634b79f459eb4fe957a27bcad1d <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#equivalentClass> .
+_:N9a68e634b79f459eb4fe957a27bcad1d <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#A> .
+_:N9a68e634b79f459eb4fe957a27bcad1d <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#B> .
+_:N9c2f317a6a4d42fc844d7cc31417dbe1 <http://example.org/ofn#note> "declared with a note" .
+_:N9c2f317a6a4d42fc844d7cc31417dbe1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:N9c2f317a6a4d42fc844d7cc31417dbe1 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> .
+_:N9c2f317a6a4d42fc844d7cc31417dbe1 <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#Annotated> .
+_:N9c2f317a6a4d42fc844d7cc31417dbe1 <http://www.w3.org/2002/07/owl#annotatedTarget> <http://www.w3.org/2002/07/owl#Class> .
+_:Na0af295593774ad1a92ba56233166c7c <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#hasParent> .
+_:Na0af295593774ad1a92ba56233166c7c <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N91c0cdc7aa8846ddb73a6bc289913ce4 .
+_:Na4a8fb0d1a6e43658e4261c622cc7939 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:Nbc99d2b654fa4c5787617e615a17b389 .
+_:Na4a8fb0d1a6e43658e4261c622cc7939 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Na847b775ebd24373a13e760ca325869e <http://www.w3.org/2001/XMLSchema#maxInclusive> "10"^^<http://www.w3.org/2001/XMLSchema#integer> .
+_:Naab2f489db2b44d2a740418a0778a6b6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Datatype> .
+_:Naab2f489db2b44d2a740418a0778a6b6 <http://www.w3.org/2002/07/owl#oneOf> _:N9460a4ee3c7d42848e775f1a13f92a60 .
+_:Nadfc08384cbf4c408146f6671a786b36 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#AllDisjointClasses> .
+_:Nadfc08384cbf4c408146f6671a786b36 <http://www.w3.org/2002/07/owl#members> _:N5aebd1d53b6b429396847d45175b8200 .
+_:Naf60971530954dcd94618a504b9e21bd <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:N08891c3e507b45baa24dce414ecb151d .
+_:Naf60971530954dcd94618a504b9e21bd <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Nafdc50e2a461406b9e3fc769ac5e99d9 <http://example.org/ofn#note> "three-way" .
+_:Nafdc50e2a461406b9e3fc769ac5e99d9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:Nafdc50e2a461406b9e3fc769ac5e99d9 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#equivalentClass> .
+_:Nafdc50e2a461406b9e3fc769ac5e99d9 <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#B> .
+_:Nafdc50e2a461406b9e3fc769ac5e99d9 <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#C> .
+_:Nb06421c63c084df0b032192b010ed3a8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Nb06421c63c084df0b032192b010ed3a8 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#age> .
+_:Nb06421c63c084df0b032192b010ed3a8 <http://www.w3.org/2002/07/owl#someValuesFrom> _:Ncc1e14995c304870ba6fa745a0435522 .
+_:Nb1d0c1c88da54074a781866ca3343e91 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Nb1d0c1c88da54074a781866ca3343e91 <http://www.w3.org/2002/07/owl#maxQualifiedCardinality> "2"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:Nb1d0c1c88da54074a781866ca3343e91 <http://www.w3.org/2002/07/owl#onDataRange> <http://www.w3.org/2001/XMLSchema#string> .
+_:Nb1d0c1c88da54074a781866ca3343e91 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#name> .
+_:Nb27ca665847c45169ff1c5b643f0749f <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Nb27ca665847c45169ff1c5b643f0749f <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#age> .
+_:Nb27ca665847c45169ff1c5b643f0749f <http://www.w3.org/2002/07/owl#someValuesFrom> _:N065c0af020ab46a4a6ecdec3fbdd2b3c .
+_:Nbc99d2b654fa4c5787617e615a17b389 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+_:Nbc99d2b654fa4c5787617e615a17b389 <http://www.w3.org/2002/07/owl#complementOf> <http://example.org/ofn#C> .
+_:Nbd5f0423d9634003bfbb847b423b350b <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Datatype> .
+_:Nbd5f0423d9634003bfbb847b423b350b <http://www.w3.org/2002/07/owl#onDatatype> <http://www.w3.org/2001/XMLSchema#integer> .
+_:Nbd5f0423d9634003bfbb847b423b350b <http://www.w3.org/2002/07/owl#withRestrictions> _:N6330b79b21b04d078c09d08b66fb062c .
+_:Nbd854b9eb3eb486c965666ca563bafd0 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#C> .
+_:Nbd854b9eb3eb486c965666ca563bafd0 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Ne48889c6fd1b4cab83cf2883d81814e0 .
+_:Nbf97df0f77bc49ce97ccc3a87e9edd9f <http://example.org/ofn#note> "n-ary" .
+_:Nbf97df0f77bc49ce97ccc3a87e9edd9f <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#AllDisjointClasses> .
+_:Nbf97df0f77bc49ce97ccc3a87e9edd9f <http://www.w3.org/2002/07/owl#members> _:Nf1af79ce3f6548b99228d3906cc831b1 .
+_:Nc245bca7859a4eaa940bc0c353f3c266 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#B> .
+_:Nc245bca7859a4eaa940bc0c353f3c266 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Na4a8fb0d1a6e43658e4261c622cc7939 .
+_:Nc2ac432d8bf24f2990bebec0d2525670 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Nc2ac432d8bf24f2990bebec0d2525670 <http://www.w3.org/2002/07/owl#cardinality> "4"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:Nc2ac432d8bf24f2990bebec0d2525670 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#s> .
+_:Nc361c78a8d1c4184a89abdcabd8d442e <http://example.org/ofn#note> "nested" .
+_:Nc361c78a8d1c4184a89abdcabd8d442e <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Annotation> .
+_:Nc361c78a8d1c4184a89abdcabd8d442e <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2000/01/rdf-schema#comment> .
+_:Nc361c78a8d1c4184a89abdcabd8d442e <http://www.w3.org/2002/07/owl#annotatedSource> _:N0301af48672a487080834492804295cd .
+_:Nc361c78a8d1c4184a89abdcabd8d442e <http://www.w3.org/2002/07/owl#annotatedTarget> "Children are people." .
+_:Nc41f849034a647cbb99fe862e3b6b828 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Nc41f849034a647cbb99fe862e3b6b828 <http://www.w3.org/2002/07/owl#maxQualifiedCardinality> "3"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
+_:Nc41f849034a647cbb99fe862e3b6b828 <http://www.w3.org/2002/07/owl#onClass> <http://example.org/ofn#B> .
+_:Nc41f849034a647cbb99fe862e3b6b828 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#r> .
+_:Nc82ca09a6a7d44d097368c84d91d7e24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Nc82ca09a6a7d44d097368c84d91d7e24 <http://www.w3.org/2002/07/owl#allValuesFrom> _:N8c0a04178e8b40ff833327903e2555dd .
+_:Nc82ca09a6a7d44d097368c84d91d7e24 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#name> .
+_:Nc8965472e13541f295502bd0c996b5b9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+_:Nc8965472e13541f295502bd0c996b5b9 <http://www.w3.org/2002/07/owl#oneOf> _:N00a52d244566421aaa07018582205b31 .
+_:Nc9a69822a5c14c94b777083e1042e52b <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#i> .
+_:Nc9a69822a5c14c94b777083e1042e52b <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Nef2ee04e562d45ec92488d4dff5ba4b1 .
+_:Ncc1e14995c304870ba6fa745a0435522 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Datatype> .
+_:Ncc1e14995c304870ba6fa745a0435522 <http://www.w3.org/2002/07/owl#intersectionOf> _:Nd192140eb57a444aae923c8640beace1 .
+_:Ncedaa14a8fc6463d9ab7e0f8156c188e <http://example.org/ofn#note> "three-way" .
+_:Ncedaa14a8fc6463d9ab7e0f8156c188e <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:Ncedaa14a8fc6463d9ab7e0f8156c188e <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#equivalentClass> .
+_:Ncedaa14a8fc6463d9ab7e0f8156c188e <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#B> .
+_:Ncedaa14a8fc6463d9ab7e0f8156c188e <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#C> .
+_:Nd192140eb57a444aae923c8640beace1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://www.w3.org/2001/XMLSchema#integer> .
+_:Nd192140eb57a444aae923c8640beace1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Naf60971530954dcd94618a504b9e21bd .
+_:Nd3b37f999c674822b7dc105cbb15538f <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NegativePropertyAssertion> .
+_:Nd3b37f999c674822b7dc105cbb15538f <http://www.w3.org/2002/07/owl#assertionProperty> <http://example.org/ofn#r> .
+_:Nd3b37f999c674822b7dc105cbb15538f <http://www.w3.org/2002/07/owl#sourceIndividual> <http://example.org/ofn#j> .
+_:Nd3b37f999c674822b7dc105cbb15538f <http://www.w3.org/2002/07/owl#targetIndividual> <http://example.org/ofn#k> .
+_:Nda5282355a1f4ebbad0487f9a8f3b8c7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#name> .
+_:Nda5282355a1f4ebbad0487f9a8f3b8c7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Ndf787cb4bc1b4f3292db24a259ada66f <http://example.org/ofn#note> "key" .
+_:Ndf787cb4bc1b4f3292db24a259ada66f <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:Ndf787cb4bc1b4f3292db24a259ada66f <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#hasKey> .
+_:Ndf787cb4bc1b4f3292db24a259ada66f <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#A> .
+_:Ndf787cb4bc1b4f3292db24a259ada66f <http://www.w3.org/2002/07/owl#annotatedTarget> _:Ne9bf9694a75b496c9615f86ac5bbd849 .
+_:Ne34e7c9d4f784193a4ce3d7831cdffb4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#age> .
+_:Ne34e7c9d4f784193a4ce3d7831cdffb4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Ne41ae497dc0241d7841d8ee410fe6df6 <http://www.w3.org/2002/07/owl#inverseOf> <http://example.org/ofn#r> .
+_:Ne48889c6fd1b4cab83cf2883d81814e0 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#D> .
+_:Ne48889c6fd1b4cab83cf2883d81814e0 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Ne549e0295fe04960a429e2bbeb34fab5 <http://example.org/ofn#note> "pairwise" .
+_:Ne549e0295fe04960a429e2bbeb34fab5 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:Ne549e0295fe04960a429e2bbeb34fab5 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#disjointWith> .
+_:Ne549e0295fe04960a429e2bbeb34fab5 <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#C> .
+_:Ne549e0295fe04960a429e2bbeb34fab5 <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#D> .
+_:Ne9b3d9f2b7054c30ab77876b34f67dba <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Ne9b3d9f2b7054c30ab77876b34f67dba <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#r> .
+_:Ne9b3d9f2b7054c30ab77876b34f67dba <http://www.w3.org/2002/07/owl#someValuesFrom> <http://example.org/ofn#B> .
+_:Ne9bf9694a75b496c9615f86ac5bbd849 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#age> .
+_:Ne9bf9694a75b496c9615f86ac5bbd849 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Nead0e30583a847ad891528c978644d02 <http://example.org/ofn#note> "pairwise" .
+_:Nead0e30583a847ad891528c978644d02 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:Nead0e30583a847ad891528c978644d02 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#disjointWith> .
+_:Nead0e30583a847ad891528c978644d02 <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#C> .
+_:Nead0e30583a847ad891528c978644d02 <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#D> .
+_:Nebe1b1fe28024dc1a9fe8f7f334a07f4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NegativePropertyAssertion> .
+_:Nebe1b1fe28024dc1a9fe8f7f334a07f4 <http://www.w3.org/2002/07/owl#assertionProperty> <http://example.org/ofn#age> .
+_:Nebe1b1fe28024dc1a9fe8f7f334a07f4 <http://www.w3.org/2002/07/owl#sourceIndividual> <http://example.org/ofn#j> .
+_:Nebe1b1fe28024dc1a9fe8f7f334a07f4 <http://www.w3.org/2002/07/owl#targetValue> "7"^^<http://www.w3.org/2001/XMLSchema#integer> .
+_:Nebfa578f8a6e4b548338ef0a12b0a975 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
+_:Nebfa578f8a6e4b548338ef0a12b0a975 <http://www.w3.org/2002/07/owl#unionOf> _:Nc245bca7859a4eaa940bc0c353f3c266 .
+_:Nef2ee04e562d45ec92488d4dff5ba4b1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#j> .
+_:Nef2ee04e562d45ec92488d4dff5ba4b1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:N693fbab92a454bb9b9c12a00705d1506 .
+_:Nef3b4ac7eb3c46c3a67ebf9818d419f9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#s> .
+_:Nef3b4ac7eb3c46c3a67ebf9818d419f9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Nf0a77fe65cbc4a5abe95f09e814e0839 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#hasGrandparent> .
+_:Nf0a77fe65cbc4a5abe95f09e814e0839 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Na0af295593774ad1a92ba56233166c7c .
+_:Nf1af79ce3f6548b99228d3906cc831b1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/ofn#A> .
+_:Nf1af79ce3f6548b99228d3906cc831b1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:Nbd854b9eb3eb486c965666ca563bafd0 .
+_:Nf2051b79e19f4adeb900394aa68ddd4e <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:Naab2f489db2b44d2a740418a0778a6b6 .
+_:Nf2051b79e19f4adeb900394aa68ddd4e <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
+_:Nf6145f8db03e4ddba411671093c6bf74 <http://example.org/ofn#note> "three-way" .
+_:Nf6145f8db03e4ddba411671093c6bf74 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:Nf6145f8db03e4ddba411671093c6bf74 <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#equivalentClass> .
+_:Nf6145f8db03e4ddba411671093c6bf74 <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#A> .
+_:Nf6145f8db03e4ddba411671093c6bf74 <http://www.w3.org/2002/07/owl#annotatedTarget> <http://example.org/ofn#B> .
+_:Nf9da183cf08d4f61a202bad0b222813d <http://example.org/ofn#note> "union" .
+_:Nf9da183cf08d4f61a202bad0b222813d <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Axiom> .
+_:Nf9da183cf08d4f61a202bad0b222813d <http://www.w3.org/2002/07/owl#annotatedProperty> <http://www.w3.org/2002/07/owl#disjointUnionOf> .
+_:Nf9da183cf08d4f61a202bad0b222813d <http://www.w3.org/2002/07/owl#annotatedSource> <http://example.org/ofn#D> .
+_:Nf9da183cf08d4f61a202bad0b222813d <http://www.w3.org/2002/07/owl#annotatedTarget> _:N02fc58b54f0b463993d6ada6a9913753 .
+_:Nfc03edb66e694ea6a3a93914123fda96 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Restriction> .
+_:Nfc03edb66e694ea6a3a93914123fda96 <http://www.w3.org/2002/07/owl#hasValue> <http://example.org/ofn#i> .
+_:Nfc03edb66e694ea6a3a93914123fda96 <http://www.w3.org/2002/07/owl#onProperty> <http://example.org/ofn#r> .
diff --git a/tests/ofn_reader_test.rs b/tests/ofn_reader_test.rs
new file mode 100644
index 00000000..472a9080
--- /dev/null
+++ b/tests/ofn_reader_test.rs
@@ -0,0 +1,783 @@
+//! The OWL 2 functional-syntax reader (`src/ofn.rs`), held to the W3C mapping.
+//!
+//! Every family test writes an OFN fragment and the Turtle that "OWL 2 Mapping
+//! to RDF Graphs (Second Edition)" Table 1, Table 2 or Section 2.3 says it
+//! denotes, and asserts the two graphs are ISOMORPHIC: both are canonicalised
+//! with RDFC 1.0 and compared triple for triple, so a reader that emitted one
+//! triple too many, one too few, or the right triples around the wrong blank
+//! node fails. The expected Turtle is written from the specification and never
+//! from this reader's output, which is the only way such a test can catch the
+//! reader being wrong.
+//!
+//! `owl_api_equivalence_on_the_fixture_is_exactly_the_documented_differences`
+//! is the second, independent check. It compares the reader against what the
+//! OWL API 4.5.29 writes for the same document, and requires the two to agree
+//! once, and only once, the differences `src/ofn.rs` documents are applied.
+//! An undocumented difference fails it.
+
+use std::collections::BTreeSet;
+use std::sync::Arc;
+
+use open_ontologies::config::CacheConfig;
+use open_ontologies::graph::GraphStore;
+use open_ontologies::ofn::{self, OfnError};
+use open_ontologies::ontology::OntologyService;
+use open_ontologies::registry::{LoadOptions, OntologyRegistry};
+use open_ontologies::state::StateDb;
+
+const ONTOLOGY: &str = "http://e.org/o";
+
+const TTL_PREFIXES: &str = "@prefix : <http://e.org/#> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+@prefix swrl: <http://www.w3.org/2003/11/swrl#> .
+@prefix swrlb: <http://www.w3.org/2003/11/swrlb#> .
+";
+
+fn document(axioms: &str) -> String {
+ format!(
+ "Prefix(:=<http://e.org/#>)\nPrefix(swrlb:=<http://www.w3.org/2003/11/swrlb#>)\nOntology(<{ONTOLOGY}>\n{axioms}\n)\n"
+ )
+}
+
+/// The graph as a sorted list of canonical N-Triples lines, blank nodes
+/// relabelled by RDFC 1.0 so isomorphic graphs compare equal.
+fn canonical(store: &GraphStore) -> Vec<String> {
+ let mut lines: Vec<String> = store
+ .canonicalize_blank_nodes()
+ .unwrap()
+ .all_triples()
+ .unwrap()
+ .into_iter()
+ .map(|(s, p, o)| format!("{s} {p} {o} ."))
+ .collect();
+ lines.sort();
+ lines
+}
+
+/// Load `doc` through the same file path every CLI and MCP load takes, under
+/// a `.owl` name, which is the extension the reader most needs to survive.
+fn load_ofn(doc: &str) -> GraphStore {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("fragment.owl");
+ std::fs::write(&path, doc).unwrap();
+ let store = GraphStore::new();
+ store
+ .load_file(path.to_str().unwrap())
+ .unwrap_or_else(|e| panic!("OFN did not load: {e}\n{doc}"));
+ store
+}
+
+fn turtle(ttl: &str) -> GraphStore {
+ let store = GraphStore::new();
+ store
+ .load_turtle(&format!("{TTL_PREFIXES}{ttl}"), None)
+ .unwrap_or_else(|e| panic!("expected Turtle does not parse: {e}\n{ttl}"));
+ store
+}
+
+/// Assert the axioms map to exactly `expected` (plus the ontology header
+/// triple every document has).
+fn assert_maps_to(axioms: &str, expected: &str) {
+ let got = canonical(&load_ofn(&document(axioms)));
+ let want = canonical(&turtle(&format!(
+ "<{ONTOLOGY}> a owl:Ontology .\n{expected}"
+ )));
+ if got != want {
+ let g: BTreeSet<_> = got.iter().collect();
+ let w: BTreeSet<_> = want.iter().collect();
+ panic!(
+ "OFN did not map to the specified graph.\nonly in reader output:\n {}\nonly in expected:\n {}\n",
+ g.difference(&w).map(|s| s.as_str()).collect::<Vec<_>>().join("\n "),
+ w.difference(&g).map(|s| s.as_str()).collect::<Vec<_>>().join("\n ")
+ );
+ }
+}
+
+// --------------------------------------------------------------------------- //
+// Families, each against the specification
+// --------------------------------------------------------------------------- //
+
+#[test]
+fn ontology_header_imports_annotations_and_every_declaration_kind() {
+ let doc = "Prefix(:=<http://e.org/#>)
+Ontology(<http://e.org/o> <http://e.org/o/1.0>
+ Import(<http://e.org/imported>)
+ Annotation(rdfs:comment \"about\")
+ Declaration(Class(:C))
+ Declaration(Datatype(:D))
+ Declaration(ObjectProperty(:op))
+ Declaration(DataProperty(:dp))
+ Declaration(AnnotationProperty(:ap))
+ Declaration(NamedIndividual(:i))
+)";
+ let got = canonical(&load_ofn(doc));
+ let want = canonical(&turtle(
+ "<http://e.org/o> a owl:Ontology ; owl:versionIRI <http://e.org/o/1.0> ;
+ owl:imports <http://e.org/imported> ; rdfs:comment \"about\" .
+ :C a owl:Class . :D a rdfs:Datatype . :op a owl:ObjectProperty .
+ :dp a owl:DatatypeProperty . :ap a owl:AnnotationProperty . :i a owl:NamedIndividual .",
+ ));
+ assert_eq!(got, want);
+}
+
+#[test]
+fn an_ontology_without_an_iri_is_a_blank_node() {
+ let got = canonical(&load_ofn("Ontology(Declaration(Class(<http://e.org/#C>)))"));
+ let want = canonical(&turtle("[] a owl:Ontology . :C a owl:Class ."));
+ assert_eq!(got, want);
+}
+
+#[test]
+fn object_class_expressions() {
+ assert_maps_to(
+ "SubClassOf(:A ObjectIntersectionOf(:B :C))
+ SubClassOf(:A ObjectUnionOf(:B ObjectComplementOf(:C)))
+ SubClassOf(:A ObjectOneOf(:i :j))
+ SubClassOf(:A ObjectSomeValuesFrom(:r :B))
+ SubClassOf(:A ObjectAllValuesFrom(ObjectInverseOf(:r) :B))
+ SubClassOf(:A ObjectHasValue(:r :i))
+ SubClassOf(:A ObjectHasSelf(:r))",
+ ":A rdfs:subClassOf [ a owl:Class ; owl:intersectionOf ( :B :C ) ] ,
+ [ a owl:Class ; owl:unionOf ( :B [ a owl:Class ; owl:complementOf :C ] ) ] ,
+ [ a owl:Class ; owl:oneOf ( :i :j ) ] ,
+ [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom :B ] ,
+ [ a owl:Restriction ; owl:onProperty [ owl:inverseOf :r ] ; owl:allValuesFrom :B ] ,
+ [ a owl:Restriction ; owl:onProperty :r ; owl:hasValue :i ] ,
+ [ a owl:Restriction ; owl:onProperty :r ; owl:hasSelf true ] .",
+ );
+}
+
+#[test]
+fn object_cardinalities_qualified_unqualified_and_qualified_by_thing() {
+ // The last row is the module notes' item 1: a filler of owl:Thing is a
+ // qualified restriction because the source wrote one, and the reader does
+ // not normalise it away as the OWL API does.
+ assert_maps_to(
+ "SubClassOf(:A ObjectMinCardinality(2 :r))
+ SubClassOf(:A ObjectMaxCardinality(3 :r :B))
+ SubClassOf(:A ObjectExactCardinality(1 :s :C))
+ SubClassOf(:A ObjectExactCardinality(4 :s))
+ SubClassOf(:A ObjectMaxCardinality(0 :s))
+ SubClassOf(:A ObjectMinCardinality(1 :t owl:Thing))",
+ ":A rdfs:subClassOf
+ [ a owl:Restriction ; owl:onProperty :r ; owl:minCardinality \"2\"^^xsd:nonNegativeInteger ] ,
+ [ a owl:Restriction ; owl:onProperty :r ; owl:maxQualifiedCardinality \"3\"^^xsd:nonNegativeInteger ; owl:onClass :B ] ,
+ [ a owl:Restriction ; owl:onProperty :s ; owl:qualifiedCardinality \"1\"^^xsd:nonNegativeInteger ; owl:onClass :C ] ,
+ [ a owl:Restriction ; owl:onProperty :s ; owl:cardinality \"4\"^^xsd:nonNegativeInteger ] ,
+ [ a owl:Restriction ; owl:onProperty :s ; owl:maxCardinality \"0\"^^xsd:nonNegativeInteger ] ,
+ [ a owl:Restriction ; owl:onProperty :t ; owl:minQualifiedCardinality \"1\"^^xsd:nonNegativeInteger ; owl:onClass owl:Thing ] .",
+ );
+}
+
+#[test]
+fn cardinalities_are_typed_non_negative_integer_before_any_store_sees_them() {
+ // The store is not a witness for this: Oxigraph's value encoding writes
+ // every integer-derived literal back as xsd:integer, so a store round
+ // trip cannot tell nonNegativeInteger from integer. The parser's own
+ // output can.
+ let triples = ofn::parse(&document("SubClassOf(:A ObjectMinCardinality(007 :r))")).unwrap();
+ let card = triples
+ .iter()
+ .find(|t| t.predicate.as_str().ends_with("#minCardinality"))
+ .expect("a minCardinality triple");
+ assert_eq!(
+ card.object.to_string(),
+ "\"7\"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger>"
+ );
+}
+
+#[test]
+fn data_ranges_and_data_restrictions() {
+ assert_maps_to(
+ "SubClassOf(:A DataSomeValuesFrom(:age DatatypeRestriction(xsd:integer xsd:minInclusive \"0\"^^xsd:integer xsd:maxExclusive \"150\"^^xsd:integer)))
+ SubClassOf(:A DataAllValuesFrom(:name DataUnionOf(xsd:string DataOneOf(\"x\" \"y\"@en))))
+ SubClassOf(:A DataSomeValuesFrom(:age DataIntersectionOf(xsd:integer DataComplementOf(xsd:negativeInteger))))
+ SubClassOf(:A DataSomeValuesFrom(:p1 :p2 xsd:integer))
+ SubClassOf(:A DataAllValuesFrom(:p1 :p2 DataComplementOf(xsd:integer)))
+ SubClassOf(:A DataHasValue(:name \"Bob\"))
+ SubClassOf(:A DataMinCardinality(1 :name))
+ SubClassOf(:A DataMaxCardinality(2 :name xsd:string))
+ SubClassOf(:A DataExactCardinality(1 :age))
+ SubClassOf(:A DataExactCardinality(3 :age xsd:int))
+ DatatypeDefinition(:Small DatatypeRestriction(xsd:integer xsd:maxInclusive \"10\"^^xsd:integer))",
+ ":A rdfs:subClassOf
+ [ a owl:Restriction ; owl:onProperty :age ; owl:someValuesFrom
+ [ a rdfs:Datatype ; owl:onDatatype xsd:integer ;
+ owl:withRestrictions ( [ xsd:minInclusive 0 ] [ xsd:maxExclusive 150 ] ) ] ] ,
+ [ a owl:Restriction ; owl:onProperty :name ; owl:allValuesFrom
+ [ a rdfs:Datatype ; owl:unionOf ( xsd:string [ a rdfs:Datatype ; owl:oneOf ( \"x\" \"y\"@en ) ] ) ] ] ,
+ [ a owl:Restriction ; owl:onProperty :age ; owl:someValuesFrom
+ [ a rdfs:Datatype ; owl:intersectionOf ( xsd:integer [ a rdfs:Datatype ; owl:datatypeComplementOf xsd:negativeInteger ] ) ] ] ,
+ [ a owl:Restriction ; owl:onProperties ( :p1 :p2 ) ; owl:someValuesFrom xsd:integer ] ,
+ [ a owl:Restriction ; owl:onProperties ( :p1 :p2 ) ; owl:allValuesFrom [ a rdfs:Datatype ; owl:datatypeComplementOf xsd:integer ] ] ,
+ [ a owl:Restriction ; owl:onProperty :name ; owl:hasValue \"Bob\" ] ,
+ [ a owl:Restriction ; owl:onProperty :name ; owl:minCardinality \"1\"^^xsd:nonNegativeInteger ] ,
+ [ a owl:Restriction ; owl:onProperty :name ; owl:maxQualifiedCardinality \"2\"^^xsd:nonNegativeInteger ; owl:onDataRange xsd:string ] ,
+ [ a owl:Restriction ; owl:onProperty :age ; owl:cardinality \"1\"^^xsd:nonNegativeInteger ] ,
+ [ a owl:Restriction ; owl:onProperty :age ; owl:qualifiedCardinality \"3\"^^xsd:nonNegativeInteger ; owl:onDataRange xsd:int ] .
+ :Small owl:equivalentClass [ a rdfs:Datatype ; owl:onDatatype xsd:integer ;
+ owl:withRestrictions ( [ xsd:maxInclusive 10 ] ) ] .",
+ );
+}
+
+#[test]
+fn class_axioms_including_the_n_ary_rows() {
+ assert_maps_to(
+ "EquivalentClasses(:A :B ObjectSomeValuesFrom(:r :C))
+ DisjointClasses(:A :B)
+ DisjointClasses(:A :B :C)
+ DisjointUnion(:P :A :B)",
+ ":A owl:equivalentClass :B .
+ :B owl:equivalentClass [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom :C ] .
+ :A owl:disjointWith :B .
+ [] a owl:AllDisjointClasses ; owl:members ( :A :B :C ) .
+ :P owl:disjointUnionOf ( :A :B ) .",
+ );
+}
+
+#[test]
+fn object_property_axioms_and_all_seven_characteristics() {
+ assert_maps_to(
+ "SubObjectPropertyOf(:s :r)
+ SubObjectPropertyOf(ObjectInverseOf(:s) :t)
+ SubObjectPropertyOf(ObjectPropertyChain(:p :p) :gp)
+ EquivalentObjectProperties(:s :t :u)
+ DisjointObjectProperties(:p :t)
+ DisjointObjectProperties(:p :t ObjectInverseOf(:gp))
+ InverseObjectProperties(:r ObjectInverseOf(:s))
+ ObjectPropertyDomain(:r :A)
+ ObjectPropertyRange(:r ObjectUnionOf(:A :B))
+ FunctionalObjectProperty(:p)
+ InverseFunctionalObjectProperty(ObjectInverseOf(:p))
+ ReflexiveObjectProperty(:t)
+ IrreflexiveObjectProperty(:p)
+ SymmetricObjectProperty(:t)
+ AsymmetricObjectProperty(:p)
+ TransitiveObjectProperty(:gp)",
+ ":s rdfs:subPropertyOf :r .
+ [ owl:inverseOf :s ] rdfs:subPropertyOf :t .
+ :gp owl:propertyChainAxiom ( :p :p ) .
+ :s owl:equivalentProperty :t . :t owl:equivalentProperty :u .
+ :p owl:propertyDisjointWith :t .
+ [] a owl:AllDisjointProperties ; owl:members ( :p :t [ owl:inverseOf :gp ] ) .
+ :r owl:inverseOf [ owl:inverseOf :s ] .
+ :r rdfs:domain :A ; rdfs:range [ a owl:Class ; owl:unionOf ( :A :B ) ] .
+ :p a owl:FunctionalProperty .
+ [ owl:inverseOf :p ] a owl:InverseFunctionalProperty .
+ :t a owl:ReflexiveProperty . :p a owl:IrreflexiveProperty .
+ :t a owl:SymmetricProperty . :p a owl:AsymmetricProperty .
+ :gp a owl:TransitiveProperty .",
+ );
+}
+
+#[test]
+fn data_property_axioms_and_has_key() {
+ assert_maps_to(
+ "SubDataPropertyOf(:nick :name)
+ EquivalentDataProperties(:name :nick)
+ DisjointDataProperties(:age :name)
+ DisjointDataProperties(:age :name :nick)
+ DataPropertyDomain(:age :Person)
+ DataPropertyRange(:age xsd:nonNegativeInteger)
+ FunctionalDataProperty(:age)
+ HasKey(:Person (:parent ObjectInverseOf(:child)) (:name))
+ HasKey(:Thing () ())",
+ ":nick rdfs:subPropertyOf :name .
+ :name owl:equivalentProperty :nick .
+ :age owl:propertyDisjointWith :name .
+ [] a owl:AllDisjointProperties ; owl:members ( :age :name :nick ) .
+ :age rdfs:domain :Person ; rdfs:range xsd:nonNegativeInteger ; a owl:FunctionalProperty .
+ :Person owl:hasKey ( :parent [ owl:inverseOf :child ] :name ) .
+ :Thing owl:hasKey () .",
+ );
+}
+
+#[test]
+fn individual_axioms_anonymous_individuals_and_the_inverse_assertion_row() {
+ assert_maps_to(
+ "SameIndividual(:a :b :c)
+ DifferentIndividuals(:a :b)
+ DifferentIndividuals(:a :b :c)
+ ClassAssertion(:C :a)
+ ClassAssertion(ObjectSomeValuesFrom(:r :C) _:x)
+ ObjectPropertyAssertion(:r _:x :a)
+ ObjectPropertyAssertion(:r :a :b)
+ ObjectPropertyAssertion(ObjectInverseOf(:r) :a :c)
+ NegativeObjectPropertyAssertion(ObjectInverseOf(:r) :a :b)
+ DataPropertyAssertion(:dp :a \"42\"^^xsd:integer)
+ NegativeDataPropertyAssertion(:dp :b \"7\"^^xsd:integer)",
+ ":a owl:sameAs :b . :b owl:sameAs :c .
+ :a owl:differentFrom :b .
+ [] a owl:AllDifferent ; owl:members ( :a :b :c ) .
+ :a a :C .
+ _:x a [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom :C ] ; :r :a .
+ :a :r :b .
+ :c :r :a .
+ [] a owl:NegativePropertyAssertion ; owl:sourceIndividual :a ;
+ owl:assertionProperty [ owl:inverseOf :r ] ; owl:targetIndividual :b .
+ :a :dp 42 .
+ [] a owl:NegativePropertyAssertion ; owl:sourceIndividual :b ;
+ owl:assertionProperty :dp ; owl:targetValue 7 .",
+ );
+}
+
+#[test]
+fn annotation_axioms() {
+ assert_maps_to(
+ "AnnotationAssertion(rdfs:label :a \"A\"@en)
+ AnnotationAssertion(:ap :a <http://elsewhere.org/x>)
+ AnnotationAssertion(:ap _:x _:y)
+ SubAnnotationPropertyOf(:ap2 :ap)
+ AnnotationPropertyDomain(:ap :C)
+ AnnotationPropertyRange(:ap xsd:string)",
+ ":a rdfs:label \"A\"@en ; :ap <http://elsewhere.org/x> .
+ [] :ap [] .
+ :ap2 rdfs:subPropertyOf :ap .
+ :ap rdfs:domain :C ; rdfs:range xsd:string .",
+ );
+}
+
+#[test]
+fn axiom_annotations_follow_section_2_3_for_each_of_its_three_cases() {
+ // 2.3.1 main triple (with a nested annotation, Table 2's second row, and
+ // with the side-triple rows DisjointUnion, HasKey and the property chain),
+ // 2.3.2 the n-ary split with the annotation repeated per link, and 2.3.3
+ // the axioms already rooted at a blank node.
+ assert_maps_to(
+ "SubClassOf(Annotation(Annotation(:ap \"nested\") rdfs:comment \"why\") :A :B)
+ Declaration(Annotation(:ap \"d\") Class(:A))
+ EquivalentClasses(Annotation(:ap \"three\") :A :B :C)
+ DisjointClasses(Annotation(:ap \"n-ary\") :A :B :C)
+ DisjointUnion(Annotation(:ap \"u\") :P :A :B)
+ SubObjectPropertyOf(Annotation(:ap \"chain\") ObjectPropertyChain(:r :s) :t)
+ HasKey(Annotation(:ap \"key\") :A () (:dp))
+ NegativeObjectPropertyAssertion(Annotation(:ap \"neg\") :r :a :b)",
+ ":A rdfs:subClassOf :B .
+ _:ax1 a owl:Axiom ; owl:annotatedSource :A ; owl:annotatedProperty rdfs:subClassOf ;
+ owl:annotatedTarget :B ; rdfs:comment \"why\" .
+ [] a owl:Annotation ; owl:annotatedSource _:ax1 ; owl:annotatedProperty rdfs:comment ;
+ owl:annotatedTarget \"why\" ; :ap \"nested\" .
+
+ :A a owl:Class .
+ [] a owl:Axiom ; owl:annotatedSource :A ; owl:annotatedProperty rdf:type ;
+ owl:annotatedTarget owl:Class ; :ap \"d\" .
+
+ :A owl:equivalentClass :B . :B owl:equivalentClass :C .
+ [] a owl:Axiom ; owl:annotatedSource :A ; owl:annotatedProperty owl:equivalentClass ;
+ owl:annotatedTarget :B ; :ap \"three\" .
+ [] a owl:Axiom ; owl:annotatedSource :B ; owl:annotatedProperty owl:equivalentClass ;
+ owl:annotatedTarget :C ; :ap \"three\" .
+
+ [] a owl:AllDisjointClasses ; owl:members ( :A :B :C ) ; :ap \"n-ary\" .
+
+ :P owl:disjointUnionOf _:u .
+ _:u rdf:first :A ; rdf:rest ( :B ) .
+ [] a owl:Axiom ; owl:annotatedSource :P ; owl:annotatedProperty owl:disjointUnionOf ;
+ owl:annotatedTarget _:u ; :ap \"u\" .
+
+ :t owl:propertyChainAxiom _:c .
+ _:c rdf:first :r ; rdf:rest ( :s ) .
+ [] a owl:Axiom ; owl:annotatedSource :t ; owl:annotatedProperty owl:propertyChainAxiom ;
+ owl:annotatedTarget _:c ; :ap \"chain\" .
+
+ :A owl:hasKey _:k .
+ _:k rdf:first :dp ; rdf:rest rdf:nil .
+ [] a owl:Axiom ; owl:annotatedSource :A ; owl:annotatedProperty owl:hasKey ;
+ owl:annotatedTarget _:k ; :ap \"key\" .
+
+ [] a owl:NegativePropertyAssertion ; owl:sourceIndividual :a ;
+ owl:assertionProperty :r ; owl:targetIndividual :b ; :ap \"neg\" .",
+ );
+}
+
+#[test]
+fn literals_plain_tagged_typed_escaped_and_rdf_plain_literal() {
+ assert_maps_to(
+ "DataPropertyAssertion(:dp :a \"plain\")
+ DataPropertyAssertion(:dp :a \"tagged\"@en-GB)
+ DataPropertyAssertion(:dp :a \"2.5\"^^xsd:decimal)
+ DataPropertyAssertion(:dp :a \"string\"^^xsd:string)
+ DataPropertyAssertion(:dp :a \"say \\\"hi\\\" \\\\ bye\")
+ DataPropertyAssertion(:dp :a \"multi
+line\")
+ DataPropertyAssertion(:dp :a \"x@y@\"^^rdf:PlainLiteral)
+ DataPropertyAssertion(:dp :a \"bonjour@fr\"^^rdf:PlainLiteral)
+ DataPropertyAssertion(:dp :a \"spaced\" ^^ <http://www.w3.org/2001/XMLSchema#token>)",
+ ":a :dp \"plain\" , \"tagged\"@en-gb , 2.5 , \"string\" , \"say \\\"hi\\\" \\\\ bye\" ,
+ \"multi\\nline\" , \"x@y\" , \"bonjour\"@fr , \"spaced\"^^xsd:token .",
+ );
+}
+
+#[test]
+fn lexical_freedom_comments_whitespace_full_iris_and_prefix_redefinition() {
+ let doc = "# leading comment with ( parens ) and \"quotes\"
+Prefix( ex: = <http://e.org/one#> )
+Prefix(ex:=<http://e.org/#>) # the later declaration wins
+Ontology( <http://e.org/o>
+ SubClassOf ( ex:A # a comment between arguments (with parens)
+ <http://e.org/#B> )
+ AnnotationAssertion(rdfs:comment ex:A \"a # inside a string is not a comment\")
+ SubClassOf(<http://e.org/#C>ex:A)
+)
+# trailing comment";
+ let got = canonical(&load_ofn(doc));
+ let want = canonical(&turtle(
+ "<http://e.org/o> a owl:Ontology .
+ :A rdfs:subClassOf :B ; rdfs:comment \"a # inside a string is not a comment\" .
+ :C rdfs:subClassOf :A .",
+ ));
+ assert_eq!(got, want);
+}
+
+#[test]
+fn swrl_rules_map_to_the_vocabulary_the_rule_front_end_reads() {
+ assert_maps_to(
+ "DLSafeRule(Annotation(rdfs:comment \"r\")
+ Body(ClassAtom(:A Variable(:x))
+ ObjectPropertyAtom(:r Variable(:x) Variable(:y))
+ DataPropertyAtom(:dp Variable(:x) Variable(:v))
+ BuiltInAtom(swrlb:greaterThan Variable(:v) \"1\"^^xsd:integer)
+ DataRangeAtom(xsd:integer Variable(:v))
+ SameIndividualAtom(Variable(:x) :a)
+ DifferentIndividualsAtom(Variable(:x) Variable(:y)))
+ Head(ClassAtom(:B Variable(:x))))",
+ ":x a swrl:Variable . :y a swrl:Variable . :v a swrl:Variable .
+ [] a swrl:Imp ; rdfs:comment \"r\" ;
+ swrl:body
+ [ a swrl:AtomList ; rdf:first [ a swrl:ClassAtom ; swrl:classPredicate :A ; swrl:argument1 :x ] ; rdf:rest
+ [ a swrl:AtomList ; rdf:first [ a swrl:IndividualPropertyAtom ; swrl:propertyPredicate :r ; swrl:argument1 :x ; swrl:argument2 :y ] ; rdf:rest
+ [ a swrl:AtomList ; rdf:first [ a swrl:DatavaluedPropertyAtom ; swrl:propertyPredicate :dp ; swrl:argument1 :x ; swrl:argument2 :v ] ; rdf:rest
+ [ a swrl:AtomList ; rdf:first [ a swrl:BuiltinAtom ; swrl:builtin swrlb:greaterThan ; swrl:arguments ( :v 1 ) ] ; rdf:rest
+ [ a swrl:AtomList ; rdf:first [ a swrl:DataRangeAtom ; swrl:dataRange xsd:integer ; swrl:argument1 :v ] ; rdf:rest
+ [ a swrl:AtomList ; rdf:first [ a swrl:SameIndividualAtom ; swrl:argument1 :x ; swrl:argument2 :a ] ; rdf:rest
+ [ a swrl:AtomList ; rdf:first [ a swrl:DifferentIndividualsAtom ; swrl:argument1 :x ; swrl:argument2 :y ] ; rdf:rest rdf:nil ] ] ] ] ] ] ] ;
+ swrl:head
+ [ a swrl:AtomList ; rdf:first [ a swrl:ClassAtom ; swrl:classPredicate :B ; swrl:argument1 :x ] ; rdf:rest rdf:nil ] .",
+ );
+}
+
+#[test]
+fn a_swrl_rule_loaded_from_ofn_reaches_the_rule_front_end() {
+ let store = load_ofn(&document(
+ "DLSafeRule(Body(ClassAtom(:A Variable(:x)) ObjectPropertyAtom(:r Variable(:x) Variable(:y)))
+ Head(ClassAtom(:B Variable(:y))))",
+ ));
+ let imp = open_ontologies::rulesyntax::swrl_from_triples(&store.all_triples().unwrap()).unwrap();
+ assert_eq!(imp.source_rules, 1);
+ assert_eq!(imp.rules.len(), 1, "{:?}", imp.refused);
+ assert!(imp.refused.is_empty());
+}
+
+// --------------------------------------------------------------------------- //
+// Refusals and syntax errors: never a silent drop
+// --------------------------------------------------------------------------- //
+
+#[test]
+fn an_unknown_construct_is_refused_by_name_line_and_count_and_nothing_loads() {
+ let doc = document(
+ "SubClassOf(:A :B)
+FancyAxiom(:a (nested (parens)) :b)
+SubClassOf(:A FancyClassExpression(:x))
+FancyAxiom(:c)
+SubClassOf(:B :C)",
+ );
+ match ofn::parse(&doc) {
+ Err(OfnError::Unsupported(census)) => {
+ assert_eq!(census.len(), 2, "{census:?}");
+ assert_eq!(census[0].construct, "FancyAxiom");
+ assert_eq!(census[0].count, 2);
+ assert_eq!(census[0].first_line, 5);
+ assert_eq!(census[1].construct, "FancyClassExpression");
+ assert_eq!(census[1].count, 1);
+ assert_eq!(census[1].first_line, 6);
+ }
+ other => panic!("expected a refusal, got {other:?}"),
+ }
+
+ // Through the load path: an error naming the construct, and an untouched store.
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("refused.owl");
+ std::fs::write(&path, &doc).unwrap();
+ let store = GraphStore::new();
+ store
+ .load_turtle("<http://e.org/#x> <http://e.org/#y> <http://e.org/#z> .", None)
+ .unwrap();
+ let err = store.load_file(path.to_str().unwrap()).unwrap_err().to_string();
+ assert!(err.contains("FancyAxiom") && err.contains("line 5"), "{err}");
+ assert!(err.contains("FancyClassExpression") && err.contains("line 6"), "{err}");
+ assert_eq!(store.triple_count(), 1, "a refused document must load nothing");
+}
+
+#[test]
+fn syntax_errors_name_the_line_and_what_was_wrong() {
+ let cases: &[(&str, usize, &str)] = &[
+ ("SubClassOf(:A undeclared:B)", 4, "prefix `undeclared:`"),
+ ("AnnotationAssertion(rdfs:label :a \"bad \\n escape\")", 4, "may escape only"),
+ ("EquivalentClasses(:A)", 4, "at least 2"),
+ ("SubClassOf(:A DataOneOf(\"x\"))", 4, "`DataOneOf` cannot stand"),
+ ("SubClassOf(:A <relative>)", 4, "not a valid absolute IRI"),
+ ("SubClassOf(:A :B :C)", 4, "expected `)` closing `SubClassOf`"),
+ ("ObjectPropertyAssertion(ObjectInverseOf(ObjectInverseOf(:r)) :a :b)", 4, "cannot stand where object property IRI"),
+ ("SubClassOf(:A ObjectMinCardinality(-1 :r))", 4, "cardinality"),
+ ("DataPropertyAssertion(:dp :a \"x\"@)", 4, "language tag"),
+ ];
+ for (axioms, line, needle) in cases {
+ match ofn::parse(&document(axioms)) {
+ Err(OfnError::Syntax { line: l, message }) => {
+ assert_eq!(l, *line, "{axioms}: {message}");
+ assert!(message.contains(needle), "{axioms}: {message}");
+ }
+ other => panic!("{axioms}: expected a syntax error, got {other:?}"),
+ }
+ }
+ match ofn::parse("Prefix(:=<http://e.org/#>)\nOntology()\nSubClassOf(:A :B)") {
+ Err(OfnError::Syntax { line: 3, message }) => assert!(message.contains("after the closing")),
+ other => panic!("trailing text: {other:?}"),
+ }
+ match ofn::parse("Prefix(:=<http://e.org/#>)\n") {
+ Err(OfnError::Syntax { message, .. }) => assert!(message.contains("no `Ontology(`")),
+ other => panic!("no ontology: {other:?}"),
+ }
+}
+
+// --------------------------------------------------------------------------- //
+// Wiring: every path that reads a file reaches the reader
+// --------------------------------------------------------------------------- //
+
+const SMALL: &str = "Prefix(:=<http://e.org/#>)
+Ontology(<http://e.org/o>
+Declaration(Class(:A))
+SubClassOf(:A ObjectSomeValuesFrom(:r :B))
+SubClassOf(:A ObjectSomeValuesFrom(:r :B))
+)";
+
+#[test]
+fn every_file_path_and_every_extension_reaches_the_reader() {
+ let tmp = tempfile::tempdir().unwrap();
+ // 1 ontology + 1 declaration + 2 x (subClassOf + 3 restriction triples).
+ // The repeated axiom makes 10 statements; its restriction is a fresh blank
+ // node each time, so the graph keeps all 10 triples.
+ for name in ["a.owl", "a.ofn", "a.fss", "a.OFN", "no_extension"] {
+ let path = tmp.path().join(name);
+ std::fs::write(&path, SMALL).unwrap();
+ let p = path.to_str().unwrap();
+
+ let store = GraphStore::new();
+ assert_eq!(store.load_file(p).unwrap(), 10, "{name}: load_file");
+
+ let counts = GraphStore::validate_file(p).unwrap();
+ assert_eq!((counts.statements, counts.triples), (10, 10), "{name}: validate_file");
+
+ let report: serde_json::Value =
+ serde_json::from_str(&OntologyService::validate_file(p).unwrap()).unwrap();
+ assert_eq!(report["valid"], true, "{name}: onto_validate (path)");
+
+ let ttl = GraphStore::read_as_turtle(p).unwrap();
+ let back = GraphStore::new();
+ back.load_turtle(&ttl, None).unwrap();
+ assert_eq!(back.triple_count(), 10, "{name}: read_as_turtle");
+ }
+ // Inline content with no file name: `validate -` and onto_validate inline.
+ let counts = GraphStore::validate_text(SMALL).unwrap();
+ assert_eq!(counts.statements, 10);
+ let report: serde_json::Value =
+ serde_json::from_str(&OntologyService::validate_string(SMALL).unwrap()).unwrap();
+ assert_eq!(report["valid"], true);
+ // And the inline Turtle path is unchanged.
+ assert_eq!(
+ GraphStore::validate_text("<http://e/a> <http://e/b> <http://e/c> .").unwrap().triples,
+ 1
+ );
+}
+
+#[test]
+fn a_malformed_ofn_file_says_why_instead_of_blaming_rdf_xml() {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("broken.owl");
+ std::fs::write(&path, "Prefix(:=<http://e.org/#>)\nOntology(\nSubClassOf(:A\n").unwrap();
+ let err = GraphStore::validate_file(path.to_str().unwrap()).unwrap_err().to_string();
+ assert!(err.starts_with("OWL functional syntax"), "{err}");
+ assert!(!err.contains("Unexpected text event"), "{err}");
+}
+
+#[test]
+fn the_mcp_load_path_through_the_registry_and_its_cache_reads_ofn() {
+ let tmp = tempfile::tempdir().unwrap();
+ let source = tmp.path().join("ontology.owl");
+ std::fs::write(&source, SMALL).unwrap();
+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = CacheConfig {
+ enabled: true,
+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),
+ idle_ttl_secs: 3600,
+ evictor_interval_secs: 3600,
+ auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
+ };
+ let registry = OntologyRegistry::new(graph.clone(), db, cfg).unwrap();
+ let first = registry
+ .load_file(source.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(first.triple_count, 10);
+ assert_eq!(first.origin, "source");
+ // The second load comes from the N-Quads compile cache, which must give
+ // back the same graph the reader produced.
+ let before = canonical(&graph);
+ let second = registry
+ .load_file(source.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(second.origin, "cache");
+ assert_eq!(canonical(&graph), before);
+}
+
+// --------------------------------------------------------------------------- //
+// Against the OWL API
+// --------------------------------------------------------------------------- //
+
+/// The graph as a SET of triples in which every blank node is replaced by a
+/// Merkle hash of what it reaches along outgoing edges, which is the shape of
+/// every blank node the mapping produces (an expression, a list cell, a
+/// reification). Two structurally identical blank-node subgraphs collapse to
+/// one, so this compares the graphs' lean quotients, and that is what the OWL
+/// API comparison needs: the OWL API writes some annotated axioms more than
+/// once (item 6 below), which RDFC would rightly call a different graph and
+/// which says nothing more than the axiom written once.
+type LeanGraph = BTreeSet<(String, String, String)>;
+
+fn lean_triples(store: &GraphStore) -> LeanGraph {
+ use std::collections::{HashMap, HashSet};
+ use std::hash::{Hash, Hasher};
+ let triples = store.all_triples().unwrap();
+ let mut out: HashMap<&str, Vec<(&str, &str)>> = HashMap::new();
+ for (s, p, o) in &triples {
+ if s.starts_with("_:") {
+ out.entry(s.as_str()).or_default().push((p.as_str(), o.as_str()));
+ }
+ }
+ fn hash_of<'a>(
+ term: &'a str,
+ out: &HashMap<&'a str, Vec<(&'a str, &'a str)>>,
+ memo: &mut HashMap<&'a str, String>,
+ active: &mut HashSet<&'a str>,
+ ) -> String {
+ if !term.starts_with("_:") {
+ return term.to_string();
+ }
+ if let Some(h) = memo.get(term) {
+ return h.clone();
+ }
+ if !active.insert(term) {
+ return "_:cycle".to_string();
+ }
+ let mut parts: Vec<String> = out
+ .get(term)
+ .map(|v| v.iter().map(|(p, o)| format!("{p} {}", hash_of(o, out, memo, active))).collect())
+ .unwrap_or_default();
+ parts.sort();
+ active.remove(term);
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ parts.hash(&mut h);
+ let label = format!("_:h{:016x}", h.finish());
+ memo.insert(term, label.clone());
+ label
+ }
+ let mut memo = HashMap::new();
+ let mut active = HashSet::new();
+ triples
+ .iter()
+ .map(|(s, p, o)| {
+ (
+ hash_of(s, &out, &mut memo, &mut active),
+ p.clone(),
+ hash_of(o, &out, &mut memo, &mut active),
+ )
+ })
+ .collect()
+}
+
+/// `tests/fixtures/ofn/all_constructs.ofn` is every construct family in one
+/// document; `all_constructs.owlapi.nt` is OWL API 4.5.29's RDF/XML for it,
+/// converted to N-Triples by rdflib (not by Oxigraph's store, which would
+/// rewrite every integer-derived literal to xsd:integer on the way through).
+/// The OWL API sorts the operands of set constructors and the fixture is
+/// written in that order, so list order is not one of the differences.
+///
+/// What remains is exactly what the OWL API writes that the mapping does not,
+/// numbered as in `src/ofn.rs`. Items 1 to 4 are each undone by one SPARQL
+/// update; items 5 and 6 (and 7, which this fixture does not exercise) are
+/// absorbed by comparing lean quotients
+/// ([`lean_triples`]). If the reader drifts, or the OWL API differs in a way
+/// nobody wrote down, the sets differ and the failure prints both sides.
+///
+/// `skip` leaves one rewrite out, which is how the test proves each of them
+/// is load-bearing.
+fn owl_api_comparison(skip: Option<usize>) -> (LeanGraph, LeanGraph) {
+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ofn");
+ let mine = GraphStore::new();
+ mine.load_file(dir.join("all_constructs.ofn").to_str().unwrap())
+ .unwrap();
+ let reference = GraphStore::new();
+ reference
+ .load_file(dir.join("all_constructs.owlapi.nt").to_str().unwrap())
+ .unwrap();
+ const P: &str = "PREFIX owl: <http://www.w3.org/2002/07/owl#>
+PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
+PREFIX ex: <http://example.org/ofn#>
+";
+ let rewrites: [(&GraphStore, String); 4] = [
+ // Item 1: the OWL API writes an owl:Thing-qualified cardinality unqualified.
+ (
+ &mine,
+ format!(
+ "{P} DELETE {{ ?x owl:minQualifiedCardinality ?n ; owl:onClass owl:Thing }}
+ INSERT {{ ?x owl:minCardinality ?n }}
+ WHERE {{ ?x owl:minQualifiedCardinality ?n ; owl:onClass owl:Thing }}"
+ ),
+ ),
+ // Item 2: owl:distinctMembers where the mapping says owl:members.
+ (
+ &reference,
+ format!(
+ "{P} DELETE {{ ?x owl:distinctMembers ?l }} INSERT {{ ?x owl:members ?l }}
+ WHERE {{ ?x owl:distinctMembers ?l }}"
+ ),
+ ),
+ // Item 3: a type triple for the one entity the fixture never declares.
+ (&reference, format!("{P} DELETE DATA {{ ex:Undeclared a owl:Class }}")),
+ // Item 4: rdf:type rdf:List on the cells of a DataOneOf literal list.
+ (&reference, format!("{P} DELETE WHERE {{ ?c a rdf:List }}")),
+ ];
+ for (i, (store, update)) in rewrites.iter().enumerate() {
+ if skip != Some(i) {
+ store.sparql_update(update).unwrap();
+ }
+ }
+ // Items 5 and 6 need no rewrite under the lean comparison: the copy of a
+ // list the OWL API writes as a reified axiom's annotatedTarget hashes to
+ // the list it copies, and a reified or blank-node-rooted axiom written
+ // twice hashes to itself.
+ (lean_triples(&mine), lean_triples(&reference))
+}
+
+#[test]
+fn owl_api_equivalence_on_the_fixture_is_exactly_the_documented_differences() {
+ let (got, want) = owl_api_comparison(None);
+ assert!(
+ got == want,
+ "undocumented difference from the OWL API.\nonly in reader:\n {}\nonly in OWL API:\n {}",
+ got.difference(&want).map(|t| format!("{t:?}")).collect::<Vec<_>>().join("\n "),
+ want.difference(&got).map(|t| format!("{t:?}")).collect::<Vec<_>>().join("\n ")
+ );
+ // Each documented difference is real: leaving its rewrite out breaks the
+ // equality. Without this the list in src/ofn.rs could rot into a list of
+ // differences that no longer exist, and the equality above would pass
+ // just the same.
+ for item in 0..4 {
+ let (got, want) = owl_api_comparison(Some(item));
+ assert_ne!(got, want, "documented difference {} no longer occurs", item + 1);
+ }
+}