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