Skip to main content

ontocore_parser/
rdf.rs

1use crate::vocab::{Rdf, Rdfs, OWL};
2use ontocore_core::{
3    limits::{MAX_FILE_BYTES, MAX_TRIPLES_PER_FILE},
4    read_file_capped, Annotation, Axiom, Entity, EntityKind, Import, Namespace, OntologyFormat,
5    ParseStatus, SourceLocation, AXIOM_KIND_SUB_CLASS_OF,
6};
7use oxigraph::io::{RdfFormat, RdfParseError, RdfParser, RdfSerializer};
8use oxigraph::model::{GraphName, Literal, NamedNode, Quad, Subject, Term};
9use std::collections::{BTreeMap, BTreeSet, HashMap};
10use std::path::Path;
11use thiserror::Error;
12
13#[derive(Debug, Error)]
14pub enum ParseError {
15    #[error("IO error: {0}")]
16    Io(#[from] std::io::Error),
17
18    #[error("RDF parse error: {0}")]
19    Rdf(String),
20
21    #[error("unsupported format: {0}")]
22    UnsupportedFormat(String),
23
24    #[error("limit exceeded: {0}")]
25    LimitExceeded(String),
26
27    #[error("invalid UTF-8: {0}")]
28    InvalidUtf8(String),
29}
30
31pub type Result<T> = std::result::Result<T, ParseError>;
32
33#[derive(Debug, Clone)]
34pub struct ParsedOntology {
35    pub ontology_id: String,
36    pub base_iri: Option<String>,
37    pub imports: Vec<String>,
38    pub namespaces: BTreeMap<String, String>,
39    pub entities: Vec<Entity>,
40    pub annotations: Vec<Annotation>,
41    pub axioms: Vec<Axiom>,
42    pub namespace_rows: Vec<Namespace>,
43    pub import_rows: Vec<Import>,
44    pub parse_status: ParseStatus,
45    pub parse_message: Option<String>,
46    pub parse_error_location: Option<SourceLocation>,
47    pub triple_count: usize,
48    quads: Vec<Quad>,
49}
50
51impl ParsedOntology {
52    /// RDF quads for catalog indexing only — not a stable public API.
53    #[doc(hidden)]
54    pub fn quads(&self) -> &[Quad] {
55        &self.quads
56    }
57}
58
59pub fn parse_ontology_file(
60    path: &Path,
61    format: OntologyFormat,
62    ontology_id: &str,
63    content_hash: &str,
64    modified_time: u64,
65) -> Result<ParsedOntology> {
66    if format == OntologyFormat::Obo {
67        return crate::obo::parse_obo_file(path, ontology_id, content_hash, modified_time);
68    }
69    if format == OntologyFormat::OwlXml {
70        let content = read_file_capped(path, MAX_FILE_BYTES)
71            .map_err(|e| ParseError::LimitExceeded(e.to_string()))?;
72        let _source_text = String::from_utf8(content).map_err(|e| {
73            ParseError::InvalidUtf8(format!("invalid UTF-8 in {}: {e}", path.display()))
74        })?;
75        return Ok(empty_parsed_ontology(ontology_id));
76    }
77    let _ = (content_hash, modified_time);
78    let content = read_file_capped(path, MAX_FILE_BYTES)
79        .map_err(|e| ParseError::LimitExceeded(e.to_string()))?;
80    let source_text = String::from_utf8(content).map_err(|e| {
81        ParseError::InvalidUtf8(format!("invalid UTF-8 in {}: {e}", path.display()))
82    })?;
83    parse_ontology_text(path, format, ontology_id, &source_text, source_text.as_bytes())
84}
85
86/// Parse ontology source text (used for LSP open buffers and file parsing).
87pub fn parse_ontology_text(
88    path: &Path,
89    format: OntologyFormat,
90    ontology_id: &str,
91    source_text: &str,
92    raw_bytes: &[u8],
93) -> Result<ParsedOntology> {
94    if source_text.len() as u64 > MAX_FILE_BYTES || raw_bytes.len() as u64 > MAX_FILE_BYTES {
95        return Err(ParseError::LimitExceeded(format!(
96            "source exceeds {MAX_FILE_BYTES} bytes: {}",
97            path.display()
98        )));
99    }
100    if format == OntologyFormat::Obo {
101        return crate::obo::parse_obo_text(path, ontology_id, source_text);
102    }
103    if format == OntologyFormat::OwlXml {
104        return Ok(empty_parsed_ontology(ontology_id));
105    }
106    let rdf_format = to_rdf_format(format, path)?;
107
108    let mut quads = Vec::new();
109    let mut parse_message = None;
110    let mut parse_error_location = None;
111    let mut parse_status = ParseStatus::Ok;
112
113    let parser = RdfParser::from_format(rdf_format);
114    for quad in parser.for_reader(raw_bytes) {
115        match quad {
116            Ok(q) => {
117                if quads.len() >= MAX_TRIPLES_PER_FILE {
118                    return Err(ParseError::LimitExceeded(format!(
119                        "file exceeds {MAX_TRIPLES_PER_FILE} triples: {}",
120                        path.display()
121                    )));
122                }
123                quads.push(q);
124            }
125            Err(e) => {
126                parse_status = ParseStatus::Error;
127                parse_message = Some(format_parse_error(&e));
128                parse_error_location = extract_parse_error_location(&e, source_text);
129                break;
130            }
131        }
132    }
133
134    // Keep partial quads on error so a trailing syntax fault does not wipe the catalog.
135    if parse_status == ParseStatus::Error && quads.is_empty() {
136        return Ok(empty_result(
137            ontology_id,
138            parse_status,
139            parse_message,
140            parse_error_location,
141            BTreeMap::new(),
142        ));
143    }
144
145    let mut namespaces =
146        if format == OntologyFormat::TriG { extract_prefixes(&quads) } else { BTreeMap::new() };
147    namespaces.extend(extract_declared_prefixes(source_text, format));
148    if namespaces.is_empty() {
149        namespaces.insert("".to_string(), default_base_iri(path));
150    }
151
152    let mut builder = OntologyBuilder::new(ontology_id.to_string(), namespaces.clone());
153    for quad in &quads {
154        builder.ingest_quad(quad);
155    }
156    builder.finish(parse_status, parse_message, parse_error_location, source_text, quads)
157}
158
159fn empty_parsed_ontology(ontology_id: &str) -> ParsedOntology {
160    ParsedOntology {
161        ontology_id: ontology_id.to_string(),
162        base_iri: None,
163        imports: Vec::new(),
164        namespaces: BTreeMap::new(),
165        entities: Vec::new(),
166        annotations: Vec::new(),
167        axioms: Vec::new(),
168        namespace_rows: Vec::new(),
169        import_rows: Vec::new(),
170        parse_status: ParseStatus::Ok,
171        parse_message: None,
172        parse_error_location: None,
173        triple_count: 0,
174        quads: Vec::new(),
175    }
176}
177
178fn to_rdf_format(format: OntologyFormat, path: &Path) -> Result<RdfFormat> {
179    match format {
180        OntologyFormat::Turtle => Ok(RdfFormat::Turtle),
181        OntologyFormat::RdfXml | OntologyFormat::Owl => Ok(RdfFormat::RdfXml),
182        OntologyFormat::JsonLd => Ok(RdfFormat::JsonLd { profile: Default::default() }),
183        OntologyFormat::NTriples => Ok(RdfFormat::NTriples),
184        OntologyFormat::NQuads => Ok(RdfFormat::NQuads),
185        OntologyFormat::TriG => Ok(RdfFormat::TriG),
186        OntologyFormat::Obo => {
187            Err(ParseError::UnsupportedFormat("OBO format must use parse_obo_text".to_string()))
188        }
189        OntologyFormat::OwlXml => {
190            Err(ParseError::UnsupportedFormat("OWL/XML must use parse_ontology_text".to_string()))
191        }
192        OntologyFormat::Unknown => Err(ParseError::UnsupportedFormat(path.display().to_string())),
193    }
194}
195
196fn format_parse_error(error: &RdfParseError) -> String {
197    error.to_string()
198}
199
200fn extract_parse_error_location(
201    error: &RdfParseError,
202    _source_text: &str,
203) -> Option<SourceLocation> {
204    let msg = error.to_string();
205    let line = msg.split_whitespace().collect::<Vec<_>>().windows(2).find_map(|w| {
206        if w[0].eq_ignore_ascii_case("line") {
207            w[1].trim_end_matches(':').parse().ok()
208        } else {
209            None
210        }
211    });
212    let column = msg.split_whitespace().collect::<Vec<_>>().windows(2).find_map(|w| {
213        if w[0].eq_ignore_ascii_case("column") || w[0].eq_ignore_ascii_case("col") {
214            w[1].trim_end_matches(':').parse().ok()
215        } else {
216            None
217        }
218    });
219    if line.is_some() || column.is_some() {
220        Some(SourceLocation { line, column, ..Default::default() })
221    } else {
222        None
223    }
224}
225
226fn default_base_iri(path: &Path) -> String {
227    ontocore_core::file_uri_for_path(path)
228}
229
230fn extract_declared_prefixes(
231    source_text: &str,
232    format: OntologyFormat,
233) -> BTreeMap<String, String> {
234    let mut prefixes = BTreeMap::new();
235
236    if matches!(format, OntologyFormat::Turtle | OntologyFormat::TriG) {
237        for line in source_text.lines() {
238            let trimmed = line.trim();
239            let rest = trimmed
240                .strip_prefix("@prefix ")
241                .or_else(|| trimmed.strip_prefix("@PREFIX "))
242                .or_else(|| trimmed.strip_prefix("PREFIX "));
243            let Some(rest) = rest else {
244                continue;
245            };
246            let Some((prefix_part, iri_part)) = rest.split_once('<') else {
247                continue;
248            };
249            let prefix = prefix_part.trim().trim_end_matches(':');
250            let Some(iri) = iri_part.split('>').next() else {
251                continue;
252            };
253            prefixes.insert(prefix.to_string(), iri.to_string());
254        }
255        return prefixes;
256    }
257
258    if matches!(format, OntologyFormat::RdfXml | OntologyFormat::Owl) {
259        static XMLNS_ATTR: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
260            regex::Regex::new(r#"xmlns(?::([A-Za-z][\w-]*))?="([^"]+)""#).expect("xmlns regex")
261        });
262        for cap in XMLNS_ATTR.captures_iter(source_text) {
263            let prefix = cap.get(1).map(|m| m.as_str()).unwrap_or("");
264            let iri = cap.get(2).map(|m| m.as_str()).unwrap_or("");
265            if !iri.is_empty() {
266                prefixes.insert(prefix.to_string(), iri.to_string());
267            }
268        }
269    }
270
271    prefixes
272}
273
274fn extract_prefixes(quads: &[Quad]) -> BTreeMap<String, String> {
275    let mut prefixes = BTreeMap::new();
276    for quad in quads {
277        if let oxigraph::model::GraphNameRef::NamedNode(graph) = quad.graph_name.as_ref() {
278            let iri = graph.as_str();
279            if let Some((prefix, _)) = iri.rsplit_once('#') {
280                if let Some((p, _)) = prefix.rsplit_once('/') {
281                    prefixes
282                        .entry(short_name_from_iri(p))
283                        .or_insert_with(|| format!("{}/", prefix.trim_end_matches('#')));
284                }
285            }
286        }
287    }
288    prefixes
289}
290
291pub(crate) fn assemble_parsed_ontology(
292    ontology_id: &str,
293    base_iri: Option<String>,
294    namespaces: BTreeMap<String, String>,
295    entities: Vec<Entity>,
296    annotations: Vec<Annotation>,
297    axioms: Vec<Axiom>,
298) -> ParsedOntology {
299    let namespace_rows: Vec<Namespace> = namespaces
300        .iter()
301        .map(|(prefix, iri)| Namespace {
302            prefix: prefix.clone(),
303            iri: iri.clone(),
304            ontology_id: ontology_id.to_string(),
305        })
306        .collect();
307    let quads = materialize_catalog_quads(&entities, &annotations, &axioms);
308    let triple_count = quads.len().max(entities.len() + annotations.len() + axioms.len());
309    ParsedOntology {
310        ontology_id: ontology_id.to_string(),
311        base_iri,
312        imports: Vec::new(),
313        namespaces: namespaces.clone(),
314        entities,
315        annotations,
316        axioms,
317        namespace_rows,
318        import_rows: Vec::new(),
319        parse_status: ParseStatus::Ok,
320        parse_message: None,
321        parse_error_location: None,
322        triple_count,
323        quads,
324    }
325}
326
327/// Build RDF quads from catalog entities/axioms so SPARQL sees OBO (and similar) content.
328fn materialize_catalog_quads(
329    entities: &[Entity],
330    annotations: &[Annotation],
331    axioms: &[Axiom],
332) -> Vec<Quad> {
333    let mut quads = Vec::new();
334    for entity in entities {
335        let Some(subject) = named_node(&entity.iri) else {
336            continue;
337        };
338        let type_iri = match entity.kind {
339            EntityKind::Class => OWL::class(),
340            EntityKind::ObjectProperty => OWL::object_property(),
341            EntityKind::DataProperty => OWL::datatype_property(),
342            EntityKind::AnnotationProperty => OWL::annotation_property(),
343            EntityKind::Individual => OWL::named_individual(),
344            EntityKind::Ontology => OWL::ontology(),
345            EntityKind::Other => continue,
346        };
347        quads.push(Quad::new(
348            subject.clone(),
349            Rdf::type_().into_owned(),
350            type_iri.into_owned(),
351            GraphName::DefaultGraph,
352        ));
353        for label in &entity.labels {
354            quads.push(Quad::new(
355                subject.clone(),
356                Rdfs::label().into_owned(),
357                Literal::new_simple_literal(label),
358                GraphName::DefaultGraph,
359            ));
360        }
361        for comment in &entity.comments {
362            quads.push(Quad::new(
363                subject.clone(),
364                Rdfs::comment().into_owned(),
365                Literal::new_simple_literal(comment),
366                GraphName::DefaultGraph,
367            ));
368        }
369        if entity.deprecated {
370            quads.push(Quad::new(
371                subject,
372                OWL::deprecated().into_owned(),
373                Literal::from(true),
374                GraphName::DefaultGraph,
375            ));
376        }
377    }
378    for axiom in axioms {
379        if axiom.axiom_kind != AXIOM_KIND_SUB_CLASS_OF {
380            continue;
381        }
382        let (Some(s), Some(o)) = (named_node(&axiom.subject), named_node(&axiom.object)) else {
383            continue;
384        };
385        quads.push(Quad::new(s, Rdfs::sub_class_of().into_owned(), o, GraphName::DefaultGraph));
386    }
387    for ann in annotations {
388        let Some(s) = named_node(&ann.subject) else {
389            continue;
390        };
391        let pred_iri = expand_annotation_predicate(&ann.predicate);
392        let Some(p) = pred_iri.as_deref().and_then(named_node) else {
393            continue;
394        };
395        if let Some(o) = named_node(&ann.object) {
396            quads.push(Quad::new(s, p, o, GraphName::DefaultGraph));
397        } else {
398            quads.push(Quad::new(
399                s,
400                p,
401                Literal::new_simple_literal(&ann.object),
402                GraphName::DefaultGraph,
403            ));
404        }
405    }
406    quads
407}
408
409fn named_node(iri: &str) -> Option<NamedNode> {
410    NamedNode::new(iri).ok()
411}
412
413const OBO_INOWL_NS: &str = "http://www.geneontology.org/formats/oboInOwl#";
414const OBO_PURL_NS: &str = "http://purl.obolibrary.org/obo/";
415
416/// Expand OBO-style annotation CURIEs used by the OBO parser.
417fn expand_annotation_predicate(pred: &str) -> Option<String> {
418    if pred.contains("://") {
419        return Some(pred.to_string());
420    }
421    let (prefix, local) = pred.split_once(':')?;
422    match prefix {
423        "obo" => Some(expand_obo_curie(local)),
424        _ => None,
425    }
426}
427
428fn expand_obo_curie(local: &str) -> String {
429    match local {
430        "hasExactSynonym" | "hasBroadSynonym" | "hasNarrowSynonym" | "hasRelatedSynonym"
431        | "hasDbXref" => format!("{OBO_INOWL_NS}{local}"),
432        // OBO term IDs (e.g. IAO_0000115) use the PURL namespace.
433        _ if local.contains('_') => format!("{OBO_PURL_NS}{local}"),
434        _ => format!("{OBO_INOWL_NS}{local}"),
435    }
436}
437
438/// Serialize RDF quads as Turtle (used to bridge OBO catalog quads into OntoLogos).
439pub fn serialize_quads_turtle(quads: &[Quad]) -> Result<String> {
440    let mut serializer = RdfSerializer::from_format(RdfFormat::Turtle).for_writer(Vec::new());
441    for quad in quads {
442        serializer.serialize_quad(quad).map_err(|e| ParseError::Rdf(e.to_string()))?;
443    }
444    let bytes = serializer.finish().map_err(|e| ParseError::Rdf(e.to_string()))?;
445    String::from_utf8(bytes).map_err(|e| ParseError::Rdf(e.to_string()))
446}
447
448fn empty_result(
449    ontology_id: &str,
450    parse_status: ParseStatus,
451    parse_message: Option<String>,
452    parse_error_location: Option<SourceLocation>,
453    namespaces: BTreeMap<String, String>,
454) -> ParsedOntology {
455    ParsedOntology {
456        ontology_id: ontology_id.to_string(),
457        base_iri: namespaces.values().next().cloned(),
458        imports: Vec::new(),
459        namespaces: namespaces.clone(),
460        entities: Vec::new(),
461        annotations: Vec::new(),
462        axioms: Vec::new(),
463        namespace_rows: namespaces
464            .into_iter()
465            .map(|(prefix, iri)| Namespace { prefix, iri, ontology_id: ontology_id.to_string() })
466            .collect(),
467        import_rows: Vec::new(),
468        parse_status,
469        parse_message,
470        parse_error_location,
471        triple_count: 0,
472        quads: Vec::new(),
473    }
474}
475
476struct EntityState {
477    kind: EntityKind,
478    labels: Vec<String>,
479    comments: Vec<String>,
480    deprecated: bool,
481    types: BTreeSet<String>,
482}
483
484struct OntologyBuilder {
485    ontology_id: String,
486    namespaces: BTreeMap<String, String>,
487    entities: HashMap<String, EntityState>,
488    annotations: Vec<Annotation>,
489    axioms: Vec<Axiom>,
490    imports: BTreeSet<String>,
491    ontology_iris: BTreeSet<String>,
492    triple_count: usize,
493    axiom_counter: usize,
494}
495
496impl OntologyBuilder {
497    fn new(ontology_id: String, namespaces: BTreeMap<String, String>) -> Self {
498        Self {
499            ontology_id,
500            namespaces,
501            entities: HashMap::new(),
502            annotations: Vec::new(),
503            axioms: Vec::new(),
504            imports: BTreeSet::new(),
505            ontology_iris: BTreeSet::new(),
506            triple_count: 0,
507            axiom_counter: 0,
508        }
509    }
510
511    fn ingest_quad(&mut self, quad: &Quad) {
512        self.triple_count += 1;
513        let subject = subject_to_string(&quad.subject);
514        let predicate = quad.predicate.as_str().to_string();
515        let object = term_to_string(&quad.object);
516
517        if quad.predicate == Rdf::type_() {
518            if let Term::NamedNode(node) = &quad.object {
519                let type_iri = node.as_str();
520                if type_iri == OWL::ontology().as_str() {
521                    self.ontology_iris.insert(subject.clone());
522                }
523                let kind = entity_kind_for_type(type_iri);
524                if kind != EntityKind::Other {
525                    let entry =
526                        self.entities.entry(subject.clone()).or_insert_with(|| EntityState {
527                            kind,
528                            labels: Vec::new(),
529                            comments: Vec::new(),
530                            deprecated: false,
531                            types: BTreeSet::new(),
532                        });
533                    entry.types.insert(type_iri.to_string());
534                    if entry.kind == EntityKind::Other
535                        || kind_priority(kind) > kind_priority(entry.kind)
536                    {
537                        entry.kind = kind;
538                    }
539                }
540            }
541            return;
542        }
543
544        if quad.predicate == OWL::imports() {
545            self.imports.insert(object.clone());
546            return;
547        }
548
549        if quad.predicate == Rdfs::label() {
550            if let Some(entity) = self.entities.get_mut(&subject) {
551                entity.labels.push(object.clone());
552            } else {
553                self.entities.entry(subject.clone()).or_insert_with(|| EntityState {
554                    kind: EntityKind::Other,
555                    labels: vec![object.clone()],
556                    comments: Vec::new(),
557                    deprecated: false,
558                    types: BTreeSet::new(),
559                });
560            }
561            self.annotations.push(Annotation {
562                subject: subject.clone(),
563                predicate: predicate.clone(),
564                object: object.clone(),
565                ontology_id: self.ontology_id.clone(),
566                source_location: SourceLocation::default(),
567            });
568            return;
569        }
570
571        if quad.predicate == Rdfs::comment() {
572            if let Some(entity) = self.entities.get_mut(&subject) {
573                entity.comments.push(object.clone());
574            } else {
575                self.entities.entry(subject.clone()).or_insert_with(|| EntityState {
576                    kind: EntityKind::Other,
577                    labels: Vec::new(),
578                    comments: vec![object.clone()],
579                    deprecated: false,
580                    types: BTreeSet::new(),
581                });
582            }
583            self.annotations.push(Annotation {
584                subject: subject.clone(),
585                predicate: predicate.clone(),
586                object: object.clone(),
587                ontology_id: self.ontology_id.clone(),
588                source_location: SourceLocation::default(),
589            });
590            return;
591        }
592
593        if quad.predicate == OWL::deprecated() {
594            let entry = self.entities.entry(subject.clone()).or_insert_with(|| EntityState {
595                kind: EntityKind::Other,
596                labels: Vec::new(),
597                comments: Vec::new(),
598                deprecated: false,
599                types: BTreeSet::new(),
600            });
601            entry.deprecated = ontocore_core::parse_boolean_literal(&object).unwrap_or(false);
602            return;
603        }
604
605        if quad.predicate == OWL::same_as() {
606            self.annotations.push(Annotation {
607                subject: subject.clone(),
608                predicate: predicate.clone(),
609                object: object.clone(),
610                ontology_id: self.ontology_id.clone(),
611                source_location: SourceLocation::default(),
612            });
613            return;
614        }
615
616        if quad.predicate == Rdfs::sub_class_of() {
617            self.axiom_counter += 1;
618            self.axioms.push(Axiom {
619                id: format!("{}#axiom-{}", self.ontology_id, self.axiom_counter),
620                ontology_id: self.ontology_id.clone(),
621                subject: subject.clone(),
622                predicate: predicate.clone(),
623                object: object.clone(),
624                axiom_kind: AXIOM_KIND_SUB_CLASS_OF.to_string(),
625                source_location: SourceLocation::default(),
626            });
627        }
628    }
629
630    fn finish(
631        self,
632        parse_status: ParseStatus,
633        parse_message: Option<String>,
634        parse_error_location: Option<SourceLocation>,
635        source_text: &str,
636        quads: Vec<Quad>,
637    ) -> Result<ParsedOntology> {
638        let base_iri = self
639            .ontology_iris
640            .iter()
641            .next()
642            .cloned()
643            .or_else(|| self.namespaces.get("").cloned())
644            .or_else(|| self.namespaces.values().next().cloned());
645
646        let ontology_id = if let Some(iri) = self.ontology_iris.iter().next() {
647            iri.clone()
648        } else {
649            self.ontology_id.clone()
650        };
651
652        let mut entities = Vec::new();
653        for (iri, state) in &self.entities {
654            if state.kind == EntityKind::Other {
655                continue;
656            }
657            let short_name = short_name_from_iri(iri);
658            entities.push(Entity {
659                iri: iri.clone(),
660                short_name: short_name.clone(),
661                kind: state.kind,
662                ontology_id: ontology_id.clone(),
663                source_location: find_entity_source_location(
664                    source_text,
665                    iri,
666                    &short_name,
667                    &self.namespaces,
668                ),
669                labels: state.labels.clone(),
670                comments: state.comments.clone(),
671                deprecated: state.deprecated,
672                obo_id: None,
673                characteristics: Default::default(),
674            });
675        }
676        entities.sort_by(|a, b| a.iri.cmp(&b.iri));
677
678        let namespace_rows = self
679            .namespaces
680            .iter()
681            .map(|(prefix, iri)| Namespace {
682                prefix: prefix.clone(),
683                iri: iri.clone(),
684                ontology_id: ontology_id.clone(),
685            })
686            .collect();
687
688        let import_rows = self
689            .imports
690            .iter()
691            .map(|import_iri| Import {
692                ontology_id: ontology_id.clone(),
693                import_iri: import_iri.clone(),
694            })
695            .collect();
696
697        let mut annotations = self.annotations;
698        for ann in &mut annotations {
699            ann.ontology_id = ontology_id.clone();
700        }
701        let mut axioms = self.axioms;
702        for axiom in &mut axioms {
703            axiom.ontology_id = ontology_id.clone();
704        }
705
706        Ok(ParsedOntology {
707            ontology_id,
708            base_iri,
709            imports: self.imports.into_iter().collect(),
710            namespaces: self.namespaces.clone(),
711            entities,
712            annotations,
713            axioms,
714            namespace_rows,
715            import_rows,
716            parse_status,
717            parse_message,
718            parse_error_location,
719            triple_count: self.triple_count,
720            quads,
721        })
722    }
723}
724
725fn entity_kind_for_type(type_iri: &str) -> EntityKind {
726    match type_iri {
727        t if t == OWL::class().as_str() || t == Rdfs::class().as_str() => EntityKind::Class,
728        t if t == OWL::object_property().as_str() => EntityKind::ObjectProperty,
729        t if t == OWL::datatype_property().as_str() => EntityKind::DataProperty,
730        t if t == OWL::annotation_property().as_str() => EntityKind::AnnotationProperty,
731        t if t == OWL::named_individual().as_str() => EntityKind::Individual,
732        t if t == OWL::ontology().as_str() => EntityKind::Ontology,
733        _ => EntityKind::Other,
734    }
735}
736
737fn kind_priority(kind: EntityKind) -> u8 {
738    match kind {
739        EntityKind::Class => 5,
740        EntityKind::ObjectProperty => 5,
741        EntityKind::DataProperty => 5,
742        EntityKind::AnnotationProperty => 5,
743        EntityKind::Individual => 4,
744        EntityKind::Ontology => 3,
745        EntityKind::Other => 0,
746    }
747}
748
749fn subject_to_string(subject: &Subject) -> String {
750    match subject {
751        Subject::NamedNode(node) => node.as_str().to_string(),
752        Subject::BlankNode(node) => format!("_:{}", node.as_str()),
753        #[allow(unreachable_patterns)]
754        _ => subject.to_string(),
755    }
756}
757
758fn term_to_string(term: &Term) -> String {
759    match term {
760        Term::NamedNode(node) => node.as_str().to_string(),
761        Term::BlankNode(node) => format!("_:{}", node.as_str()),
762        Term::Literal(lit) => lit.value().to_string(),
763        #[allow(unreachable_patterns)]
764        _ => term.to_string(),
765    }
766}
767
768fn find_entity_source_location(
769    source_text: &str,
770    iri: &str,
771    short_name: &str,
772    namespaces: &BTreeMap<String, String>,
773) -> SourceLocation {
774    let mut needles = vec![iri.to_string(), format!("<{iri}>"), format!(":{short_name}")];
775    for (prefix, ns) in namespaces {
776        if iri.starts_with(ns) && !prefix.is_empty() {
777            needles.push(format!("{prefix}:{short_name}"));
778        }
779    }
780    for line in source_text.lines() {
781        let trimmed = line.trim();
782        if !(trimmed.starts_with("@prefix")
783            || trimmed.starts_with("@PREFIX")
784            || trimmed.starts_with("PREFIX "))
785        {
786            continue;
787        }
788        let prefix_kw_len = if trimmed.to_ascii_lowercase().starts_with("@prefix ") {
789            "@prefix ".len()
790        } else if trimmed.to_ascii_lowercase().starts_with("prefix ") {
791            "PREFIX ".len()
792        } else {
793            continue;
794        };
795        if let Some(colon) = trimmed.find(':') {
796            if colon < prefix_kw_len {
797                continue;
798            }
799            let prefix = trimmed[prefix_kw_len..colon].trim();
800            let prefix = prefix.trim_start_matches('@');
801            if let (Some(start), Some(end)) = (line.find('<'), line.find('>')) {
802                if start < end {
803                    let ns = &line[start + 1..end];
804                    if iri.starts_with(ns) && !prefix.is_empty() {
805                        needles.push(format!("{prefix}:{short_name}"));
806                    }
807                }
808            }
809        }
810    }
811
812    for (line_idx, line) in source_text.lines().enumerate() {
813        for needle in &needles {
814            if let Some(col) = line.find(needle) {
815                return SourceLocation {
816                    line: Some((line_idx + 1) as u64),
817                    column: Some(col as u64),
818                    start_byte: None,
819                    end_byte: None,
820                };
821            }
822        }
823    }
824
825    SourceLocation::default()
826}
827
828fn short_name_from_iri(iri: &str) -> String {
829    if let Some((_, name)) = iri.rsplit_once('#') {
830        return name.to_string();
831    }
832    if let Some((_, name)) = iri.rsplit_once('/') {
833        return name.to_string();
834    }
835    iri.to_string()
836}
837
838#[cfg(test)]
839mod tests {
840    use super::*;
841    use std::fs;
842    use std::io::Write;
843
844    #[test]
845    fn rejects_oversized_source_text() {
846        let dir = tempfile::tempdir().unwrap();
847        let path = dir.path().join("huge.ttl");
848        let oversized = "x".repeat((MAX_FILE_BYTES + 1) as usize);
849        let err = parse_ontology_text(
850            &path,
851            OntologyFormat::Turtle,
852            "doc-1",
853            &oversized,
854            oversized.as_bytes(),
855        )
856        .unwrap_err();
857        assert!(matches!(err, ParseError::LimitExceeded(_)));
858    }
859
860    #[test]
861    fn rejects_invalid_utf8_ontology_file() {
862        let dir = tempfile::tempdir().unwrap();
863        let path = dir.path().join("bad.ttl");
864        std::fs::write(&path, b"@prefix ex: <http://ex/> .\n\xff\xfe\n").unwrap();
865        let err = parse_ontology_file(&path, OntologyFormat::Turtle, "doc-1", "h", 0).unwrap_err();
866        assert!(matches!(err, ParseError::InvalidUtf8(_)));
867    }
868
869    #[test]
870    fn parses_simple_turtle_ontology() {
871        let dir = tempfile::tempdir().unwrap();
872        let path = dir.path().join("test.ttl");
873        let mut f = fs::File::create(&path).unwrap();
874        writeln!(
875            f,
876            r#"@prefix ex: <http://example.org/test#> .
877@prefix owl: <http://www.w3.org/2002/07/owl#> .
878@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
879
880<http://example.org/test> a owl:Ontology .
881
882ex:Person a owl:Class ;
883    rdfs:label "Person" ;
884    rdfs:comment "A human being" .
885
886ex:knows a owl:ObjectProperty ;
887    rdfs:label "knows" .
888"#
889        )
890        .unwrap();
891
892        let parsed =
893            parse_ontology_file(&path, OntologyFormat::Turtle, "doc-1", "hash", 0).unwrap();
894
895        assert_eq!(parsed.parse_status, ParseStatus::Ok);
896
897        let person = parsed
898            .entities
899            .iter()
900            .find(|e| e.iri == "http://example.org/test#Person")
901            .expect("Person entity");
902        assert_eq!(person.kind, EntityKind::Class);
903        assert_eq!(person.labels, vec!["Person".to_string()]);
904        assert!(person.source_location.line.is_some());
905
906        let knows = parsed
907            .entities
908            .iter()
909            .find(|e| e.iri == "http://example.org/test#knows")
910            .expect("knows property");
911        assert_eq!(knows.kind, EntityKind::ObjectProperty);
912        assert_eq!(knows.labels, vec!["knows".to_string()]);
913    }
914
915    #[test]
916    fn extracts_turtle_prefix_declarations() {
917        let dir = tempfile::tempdir().unwrap();
918        let path = dir.path().join("test.ttl");
919        let mut f = fs::File::create(&path).unwrap();
920        writeln!(
921            f,
922            r#"@prefix ex: <http://example.org/test#> .
923@prefix owl: <http://www.w3.org/2002/07/owl#> .
924
925<http://example.org/test> a owl:Ontology .
926ex:Person a owl:Class .
927"#
928        )
929        .unwrap();
930
931        let parsed =
932            parse_ontology_file(&path, OntologyFormat::Turtle, "doc-1", "hash", 0).unwrap();
933
934        assert_eq!(parsed.base_iri.as_deref(), Some("http://example.org/test"));
935        assert_eq!(
936            parsed.namespaces.get("ex").map(String::as_str),
937            Some("http://example.org/test#")
938        );
939    }
940
941    #[test]
942    fn trailing_parse_error_keeps_prior_entities() {
943        let ttl = r#"@prefix ex: <http://example.org/test#> .
944@prefix owl: <http://www.w3.org/2002/07/owl#> .
945
946ex:Person a owl:Class ;
947    rdfs:label "Person" .
948
949ex:Broken a owl:Class ; this is not valid turtle
950"#;
951        let parsed = parse_ontology_text(
952            Path::new("partial.ttl"),
953            OntologyFormat::Turtle,
954            "doc-1",
955            ttl,
956            ttl.as_bytes(),
957        )
958        .expect("partial parse");
959        assert_eq!(parsed.parse_status, ParseStatus::Error);
960        assert!(
961            parsed.entities.iter().any(|e| e.iri == "http://example.org/test#Person"),
962            "entities parsed before the fault must be retained"
963        );
964        assert!(!parsed.quads().is_empty());
965    }
966
967    #[test]
968    fn default_base_iri_uses_file_uri_helper() {
969        let dir = tempfile::tempdir().unwrap();
970        let path = dir.path().join("bare.ttl");
971        fs::write(&path, "<> a <http://www.w3.org/2002/07/owl#Ontology> .\n").unwrap();
972        let uri = default_base_iri(&path);
973        assert!(uri.starts_with("file://"), "got {uri}");
974        assert!(!uri.contains('\\'), "raw backslash must not appear: {uri}");
975        assert_eq!(uri, ontocore_core::file_uri_for_path(&path));
976    }
977}