Skip to main content

sbol_convert/upgrade/
mod.rs

1//! Convert SBOL 2 RDF documents to SBOL 3.
2//!
3//! Most published synbio content (SynBioHub, iGEM Registry, JBEI ICE)
4//! predates SBOL 3 and remains in SBOL 2 form. This module reads SBOL 2 RDF
5//! and emits SBOL 3 RDF that can be loaded by the rest of the crate and
6//! validated like any natively-authored SBOL 3 document.
7//!
8//! Conversion happens at the RDF triple level and matches the conversion
9//! decisions of the SynBioDex/SBOL-Converter reference. No external runtime is
10//! required: input goes in as bytes (any RDF serialization the [`RdfFormat`]
11//! enum supports), output comes back as bytes plus an [`UpgradeReport`] of
12//! warnings.
13//!
14//! ```no_run
15//! use sbol_convert::upgrade_from_sbol2_path;
16//!
17//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
18//! let (document, report) = upgrade_from_sbol2_path("design.xml")?;
19//!
20//! for warning in report.warnings() {
21//!     eprintln!("{warning:?}");
22//! }
23//!
24//! document.check()?;
25//! # Ok(())
26//! # }
27//! ```
28//!
29//! The [`Document`] is always returned when the input parses as valid SBOL 2
30//! RDF. Callers gate on validation with the existing [`Document::check`]
31//! method if they want a strict pipeline.
32//!
33//! For the full conversion model (workflows organized by what you have, the
34//! `https://sbols.org/backport/2_3#` namespace, structural collapses
35//! (SequenceAnnotation, MapsTo, Interface), known divergences, and known
36//! limitations) see the [conversion guide][conversion-md].
37//!
38//! [`Document`]: sbol3::Document
39//! [`Document::check`]: sbol3::Document::check
40//! [`RdfFormat`]: sbol3::RdfFormat
41//! [conversion-md]: https://github.com/SynBioDex/sbol-rs/blob/master/docs/conversion.md
42
43use std::collections::{HashMap, HashSet};
44use std::path::Path;
45
46use crate::sbol2_vocab as v2;
47use sbol_rdf::{Graph, ParseError, RdfFormat};
48use sbol_rdf::{Iri, Resource, Term, Triple};
49use sbol3::Document;
50use sbol3::vocab as v3;
51
52mod emit;
53mod engine;
54mod identity;
55mod values;
56
57use identity::IdentityMap;
58
59/// Configuration for [`sbol2_to_sbol3`].
60#[derive(Clone, Debug)]
61#[non_exhaustive]
62pub struct UpgradeOptions {
63    /// Default namespace to attach to top-level objects whose namespace
64    /// cannot be derived from the input (no `persistentIdentity`, no
65    /// `displayId`, IRI parses as opaque). If `None`, an
66    /// [`UpgradeWarning::NamespaceFallback`] is emitted and the object is
67    /// left without `hasNamespace`.
68    pub default_namespace: Option<Iri>,
69
70    /// Whether to stamp the conversion-provenance annotations (the original
71    /// SBOL 2 identities, collapsed-SequenceAnnotation and temp-sequence
72    /// markers) under the `https://sbols.org/backport/2_3#` namespace so a
73    /// later SBOL 3 → SBOL 2 downgrade can reconstruct the SBOL 2 shape.
74    /// Defaults to `true`.
75    pub preserve_backport: bool,
76}
77
78impl Default for UpgradeOptions {
79    fn default() -> Self {
80        Self {
81            default_namespace: None,
82            preserve_backport: true,
83        }
84    }
85}
86
87impl UpgradeOptions {
88    pub fn new() -> Self {
89        Self::default()
90    }
91}
92
93/// Warnings emitted by [`sbol2_to_sbol3`]. The presence of warnings does not
94/// stop conversion. Every warning records something the upgrade could not
95/// translate cleanly but chose not to fail on.
96#[derive(Clone, Debug, PartialEq, Eq)]
97#[non_exhaustive]
98pub enum UpgradeWarning {
99    /// A top-level subject's `hasNamespace` could not be derived from
100    /// `persistentIdentity` + `displayId` or from the IRI's URL origin.
101    /// The upgrade either used [`UpgradeOptions::default_namespace`]
102    /// or left the subject without `hasNamespace`. URL-origin
103    /// derivation is the canonical fallback for HTTP-style IRIs and
104    /// does not warn.
105    NamespaceFallback {
106        subject: String,
107        source: NamespaceSource,
108    },
109    /// A `sbol2:MapsTo` was decomposed into a Constraint, but the local or
110    /// remote side could not be resolved to a SubComponent. The constraint
111    /// was skipped.
112    UnresolvedMapsTo { mapsto: String, side: MapsToSide },
113    /// A `sbol2:MapsTo` carried a `refinement` value with no SBOL 3
114    /// Constraint equivalent (notably `merge`). The Constraint is still
115    /// emitted, with its restriction coerced to `sbol3:verifyIdentical`.
116    UnsupportedRefinement { mapsto: String, refinement: String },
117    /// A `sbol2:SequenceAnnotation` referenced a `sbol2:component`. The
118    /// upgrade collapsed the SA shell onto the referenced SubComponent.
119    SequenceAnnotationWithComponent { annotation: String },
120    /// A subject carried an SBOL 2 type the upgrade does not understand.
121    /// The subject is dropped; the unknown class has no SBOL 3 equivalent.
122    UnknownSbol2Type { subject: String, sbol2_type: String },
123    /// A Location belongs to a SequenceFeature on a Component that has no
124    /// (or more than one) `sbol2:sequence`, so `sbol3:hasSequence` could not
125    /// be unambiguously inferred. The resulting SBOL 3 document will fail
126    /// `sbol3-10110` cardinality validation until the source data is
127    /// corrected to declare exactly one Sequence per Component.
128    LocationWithoutSequence {
129        location: String,
130        component: String,
131        sequence_count: usize,
132    },
133    /// Two or more distinct SBOL 2 subjects in the input share a
134    /// canonical SBOL 3 IRI after version-stripping. For example,
135    /// `<lab/foo/1>` (whose canonical is `<lab/foo>`) and
136    /// `<lab/foo>` itself. The conversion preserves every input triple
137    /// but lands all of them at the same SBOL 3 subject, silently
138    /// merging the entities into a single chimeric Component / Sequence
139    /// / etc. The input was technically non-conformant SBOL 2
140    /// (persistentIdentity should be unique), but the merge is
141    /// otherwise indistinguishable from intended behavior; this warning
142    /// surfaces the situation so callers can audit the source data.
143    IdentityCollision {
144        canonical: String,
145        sources: Vec<String>,
146    },
147}
148
149/// Indicates which path was taken when a namespace had to be derived without
150/// a usable `persistentIdentity` + `displayId` pair.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum NamespaceSource {
154    /// Parsed scheme+host of the subject IRI.
155    UrlOrigin,
156    /// Used [`UpgradeOptions::default_namespace`].
157    DefaultOption,
158    /// No fallback applied; the object has no `hasNamespace` in the output.
159    None,
160}
161
162/// Which side of a MapsTo failed to resolve.
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164#[non_exhaustive]
165pub enum MapsToSide {
166    Local,
167    Remote,
168    /// The MapsTo had no enclosing
169    /// `sbol2:Module` / `sbol2:FunctionalComponent`
170    /// carrier: nothing in the source pointed at it via the
171    /// `sbol2:mapsTo` containment predicate, so the upgrade has no
172    /// place to attach the resulting ComponentReference + Constraint
173    /// pair.
174    Carrier,
175}
176
177/// Tally of how many SBOL 2 constructs the upgrade rewrote into SBOL 3
178/// constructs. Useful for end-of-run summaries and CI signals (e.g. an
179/// expected document type accidentally dropping to zero across a refactor).
180#[derive(Clone, Copy, Debug, Default)]
181#[non_exhaustive]
182pub struct UpgradeCounts {
183    /// `sbol2:ComponentDefinition` subjects rewritten to `sbol3:Component`.
184    pub component_definitions: usize,
185    /// `sbol2:ModuleDefinition` subjects rewritten to `sbol3:Component`
186    /// (with synthesized `SBO:functionalEntity` type).
187    pub module_definitions: usize,
188    /// `sbol2:Component` / `sbol2:Module` / `sbol2:FunctionalComponent`
189    /// subjects rewritten to `sbol3:SubComponent`.
190    pub sub_components: usize,
191    /// Standalone `sbol2:SequenceAnnotation` subjects rewritten to
192    /// `sbol3:SequenceFeature` (i.e. SAs that did NOT carry a
193    /// `sbol2:component` reference).
194    pub sequence_features: usize,
195    /// SequenceAnnotations that referenced a `sbol2:component` and were
196    /// collapsed onto the referenced SubComponent.
197    pub sequence_annotations_collapsed: usize,
198    /// `sbol2:MapsTo` subjects decomposed into ComponentReference +
199    /// Constraint pairs.
200    pub mapstos_decomposed: usize,
201    /// `sbol3:Interface` objects synthesized from FunctionalComponent
202    /// direction information.
203    pub interfaces_synthesized: usize,
204    /// Locations that received a `sbol3:hasSequence` triple inferred from
205    /// their enclosing Component's single sequence.
206    pub locations_with_inferred_sequence: usize,
207}
208
209/// Report of every non-fatal issue encountered during an upgrade run, plus
210/// counts of what the converter rewrote.
211#[derive(Clone, Debug, Default)]
212#[non_exhaustive]
213pub struct UpgradeReport {
214    warnings: Vec<UpgradeWarning>,
215    counts: UpgradeCounts,
216}
217
218impl UpgradeReport {
219    /// Iterates over every warning recorded during the run.
220    pub fn warnings(&self) -> &[UpgradeWarning] {
221        &self.warnings
222    }
223
224    /// Returns the per-construct counts.
225    pub fn counts(&self) -> &UpgradeCounts {
226        &self.counts
227    }
228
229    /// Returns `true` if no warnings were recorded.
230    pub fn is_clean(&self) -> bool {
231        self.warnings.is_empty()
232    }
233
234    pub(crate) fn push(&mut self, warning: UpgradeWarning) {
235        self.warnings.push(warning);
236    }
237}
238
239/// Errors returned by [`sbol2_to_sbol3`].
240#[derive(Debug)]
241#[non_exhaustive]
242pub enum UpgradeError {
243    /// The input bytes did not parse as RDF.
244    Parse(ParseError),
245    /// The input parsed, but no SBOL 2 typed subjects were detected. Pass an
246    /// SBOL 2 document; SBOL 3 input does not need an upgrade.
247    NotSbol2,
248}
249
250impl std::fmt::Display for UpgradeError {
251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252        match self {
253            Self::Parse(err) => write!(f, "failed to parse input as RDF: {err}"),
254            Self::NotSbol2 => write!(
255                f,
256                "input contains no SBOL 2 typed subjects \
257                 (http://sbols.org/v2# rdf:type) — nothing to upgrade",
258            ),
259        }
260    }
261}
262
263impl std::error::Error for UpgradeError {
264    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
265        match self {
266            Self::Parse(err) => Some(err),
267            Self::NotSbol2 => None,
268        }
269    }
270}
271
272impl From<ParseError> for UpgradeError {
273    fn from(err: ParseError) -> Self {
274        Self::Parse(err)
275    }
276}
277
278/// Converts an SBOL 2 RDF graph to SBOL 3 RDF.
279///
280/// The input graph must contain at least one subject typed in the SBOL 2
281/// namespace (`http://sbols.org/v2#…`); otherwise [`UpgradeError::NotSbol2`]
282/// is returned. Returns the new graph plus an [`UpgradeReport`] of any
283/// non-fatal issues.
284///
285/// Literals are converted as they appear in `graph`. The document-level
286/// [`upgrade`] and the text-level [`upgrade_from_sbol2`] pass the graph of an
287/// [`sbol2::Document`], whose literals carry the datatypes the SBOL 2 schema
288/// assigns.
289pub fn sbol2_to_sbol3(
290    graph: &Graph,
291    options: UpgradeOptions,
292) -> Result<(Graph, UpgradeReport), UpgradeError> {
293    let mut engine = Engine::new(graph, options);
294    engine.preflight()?;
295    engine.convert();
296    Ok((Graph::new(engine.output_triples), engine.report))
297}
298
299/// Convenience wrapper: parses input bytes as an [`sbol2::Document`], calls
300/// [`sbol2_to_sbol3`] on its graph, then returns both the SBOL 3 [`Graph`] and
301/// the [`UpgradeReport`]. Produces the same graph as [`upgrade_from_sbol2`].
302pub fn parse_and_upgrade(
303    input: &str,
304    format: RdfFormat,
305    options: UpgradeOptions,
306) -> Result<(Graph, UpgradeReport), UpgradeError> {
307    let graph = Graph::parse(input, format)?;
308    sbol2_to_sbol3(sbol2::Document::from_rdf_graph(graph).rdf_graph(), options)
309}
310
311/// Upgrades an SBOL 2 RDF document to SBOL 3 and returns the resulting
312/// [`Document`] alongside an [`UpgradeReport`] of any non-fatal issues
313/// encountered during conversion.
314///
315/// The returned [`Document`] is always produced when the input parses as
316/// valid SBOL 2 RDF. Call [`Document::check`] if you want a strict
317/// pipeline that rejects content the upgrade could not coerce into
318/// fully-conformant SBOL 3.
319pub fn upgrade_from_sbol2(
320    input: &str,
321    format: RdfFormat,
322) -> Result<(Document, UpgradeReport), UpgradeError> {
323    upgrade_from_sbol2_with(input, format, UpgradeOptions::default())
324}
325
326/// Like [`upgrade_from_sbol2`], with explicit [`UpgradeOptions`].
327pub fn upgrade_from_sbol2_with(
328    input: &str,
329    format: RdfFormat,
330    options: UpgradeOptions,
331) -> Result<(Document, UpgradeReport), UpgradeError> {
332    let parsed = Graph::parse(input, format).map_err(UpgradeError::Parse)?;
333    upgrade_with(&sbol2::Document::from_rdf_graph(parsed), options)
334}
335
336/// Upgrades a parsed SBOL 2 [`sbol2::Document`] to SBOL 3 in memory and
337/// returns the resulting [`Document`] alongside an [`UpgradeReport`] of any
338/// non-fatal issues encountered during conversion.
339///
340/// The conversion reads the document's RDF graph directly, without
341/// serializing it. As with [`upgrade_from_sbol2`], call [`Document::check`]
342/// to reject content the upgrade could not coerce into fully conformant
343/// SBOL 3.
344///
345/// ```no_run
346/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
347/// let design = sbol2::Document::read_path("design.rdf")?;
348/// design.check()?;
349///
350/// let (upgraded, report) = sbol_convert::upgrade(&design)?;
351/// for warning in report.warnings() {
352///     eprintln!("{warning:?}");
353/// }
354/// upgraded.check()?;
355/// # Ok(())
356/// # }
357/// ```
358pub fn upgrade(document: &sbol2::Document) -> Result<(Document, UpgradeReport), UpgradeError> {
359    upgrade_with(document, UpgradeOptions::default())
360}
361
362/// Like [`upgrade`], with explicit [`UpgradeOptions`].
363pub fn upgrade_with(
364    document: &sbol2::Document,
365    options: UpgradeOptions,
366) -> Result<(Document, UpgradeReport), UpgradeError> {
367    let (upgraded, report) = sbol2_to_sbol3(document.rdf_graph(), options)?;
368    Ok((Document::from_rdf_graph(upgraded), report))
369}
370
371/// Reads an SBOL 2 RDF file from disk and upgrades it to SBOL 3. The
372/// format is inferred from the path's extension (`.ttl`, `.rdf`, `.xml`,
373/// `.jsonld`, `.nt`).
374pub fn upgrade_from_sbol2_path(
375    path: impl AsRef<Path>,
376) -> Result<(Document, UpgradeReport), UpgradeFromPathError> {
377    let path = path.as_ref();
378    let format =
379        infer_sbol2_rdf_format(path).ok_or_else(|| UpgradeFromPathError::UnknownFormat {
380            path: path.to_path_buf(),
381            extension: path
382                .extension()
383                .and_then(|ext| ext.to_str())
384                .map(str::to_owned),
385        })?;
386    let input = std::fs::read_to_string(path).map_err(|source| UpgradeFromPathError::Io {
387        path: path.to_path_buf(),
388        source,
389    })?;
390    upgrade_from_sbol2(&input, format).map_err(UpgradeFromPathError::Upgrade)
391}
392
393fn infer_sbol2_rdf_format(path: &Path) -> Option<RdfFormat> {
394    if let Some(format) = RdfFormat::from_path(path) {
395        return Some(format);
396    }
397    let extension = path.extension()?.to_str()?.to_ascii_lowercase();
398    (extension == "xml").then_some(RdfFormat::RdfXml)
399}
400
401/// Errors returned by [`upgrade_from_sbol2_path`].
402#[derive(Debug)]
403#[non_exhaustive]
404pub enum UpgradeFromPathError {
405    /// Failed to read the file at the given path.
406    Io {
407        path: std::path::PathBuf,
408        source: std::io::Error,
409    },
410    /// The path's extension did not match any supported RDF serialization.
411    UnknownFormat {
412        path: std::path::PathBuf,
413        extension: Option<String>,
414    },
415    /// The file was loaded but the upgrade itself failed.
416    Upgrade(UpgradeError),
417}
418
419impl std::fmt::Display for UpgradeFromPathError {
420    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421        match self {
422            Self::Io { path, source } => write!(f, "failed to read {}: {source}", path.display()),
423            Self::UnknownFormat { path, extension } => {
424                let ext = extension.as_deref().unwrap_or("<none>");
425                write!(
426                    f,
427                    "unsupported extension `{ext}` for {} — supported: .ttl, .rdf, .jsonld, .nt",
428                    path.display()
429                )
430            }
431            Self::Upgrade(err) => write!(f, "{err}"),
432        }
433    }
434}
435
436impl std::error::Error for UpgradeFromPathError {
437    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
438        match self {
439            Self::Io { source, .. } => Some(source),
440            Self::UnknownFormat { .. } => None,
441            Self::Upgrade(err) => Some(err),
442        }
443    }
444}
445
446#[derive(Clone, Copy)]
447enum FcDirection {
448    Input,
449    Output,
450    Inout,
451}
452
453/// Per-MapsTo selector for the constraint shape emitted by
454/// [`Engine::synthesize_mapsto_decomposition`]. Derived from the source
455/// MapsTo's `sbol2:refinement` value (or its absence).
456#[derive(Clone, Copy)]
457enum RefinementShape {
458    UseLocal,
459    UseRemote,
460    VerifyIdentical,
461}
462
463#[derive(Default, Clone)]
464struct MapsToInfo {
465    local: Option<String>,
466    remote: Option<String>,
467    refinement: Option<String>,
468    display_id: Option<String>,
469}
470
471struct Engine<'a> {
472    input: &'a Graph,
473    options: UpgradeOptions,
474    identity: IdentityMap,
475    /// Subject IRI → its rdf:type IRI string, for every subject the
476    /// upgrade may need to namespace (SBOL 2 typed subjects, plus the
477    /// PROV top-level classes that SBOL 2 documents commonly carry).
478    /// Both populate `hasNamespace` on emission.
479    typed_subjects: HashMap<String, String>,
480    /// Original CD IRI → list of Sequence IRIs it references via
481    /// `sbol2:sequence`. Used to infer `hasSequence` on Locations after
482    /// conversion.
483    cd_sequences: HashMap<String, Vec<String>>,
484    /// Original Location IRI (Range/Cut/GenericLocation) → original SA IRI
485    /// that owns it. Used together with [`sa_to_cd`] to walk back to the
486    /// owning Component and infer the Location's `hasSequence`.
487    location_to_sa: HashMap<String, String>,
488    /// Original SA IRI → original CD IRI that owns it.
489    sa_to_cd: HashMap<String, String>,
490    /// Original SA IRI → original SubComponent (Component) IRI it references
491    /// via `sbol2:component`. When this mapping is non-empty for an SA, the
492    /// SA shell is discarded and its Locations move onto the referenced
493    /// SubComponent (SEP-010 / sbolgraph SequenceAnnotation collapse rule).
494    sa_to_subcomponent: HashMap<String, String>,
495    /// Subject IRI → its SBOL 2 displayId. Used when structural rewrites move
496    /// child subjects under a different parent and must preserve SBOL 3 child
497    /// identity rules.
498    display_ids: HashMap<String, String>,
499    /// Owning-relation index: child subject IRI → parent subject IRI. Built
500    /// from every SBOL 2 containment predicate (module, functionalComponent,
501    /// component, mapsTo, interaction, participation, location, etc.). Used
502    /// by [`Engine::owning_top_level`] to walk back to the enclosing
503    /// top-level subject when synthesizing new triples (e.g. attaching
504    /// MapsTo-derived ComponentReferences to the enclosing Component).
505    owned_by: HashMap<String, String>,
506    /// Original MapsTo IRI → its parsed local/remote/refinement values plus
507    /// the MapsTo's displayId.
508    mapsto_info: HashMap<String, MapsToInfo>,
509    /// Original FunctionalComponent IRI → the SBOL 3 Interface slot it
510    /// should occupy. SBOL 2 `inout` and public+`none` components both map
511    /// to SBOL 3 `nondirectional`.
512    fc_directions: HashMap<String, FcDirection>,
513    /// FunctionalComponents that explicitly declared `sbol2:direction none`.
514    /// The SBOL 2→3 mapping still lists these under Interface.nondirectional
515    /// when their access is public.
516    fc_direction_none: HashSet<String>,
517    /// FunctionalComponents that explicitly declared `sbol2:access public`.
518    fc_public_access: HashSet<String>,
519    output_triples: Vec<Triple>,
520    /// Subjects already given a `sbol3:hasNamespace` triple. Used to avoid
521    /// duplicate emissions when a subject has multiple `sbol2:displayId`
522    /// triples or appears more than once in pre-scan.
523    namespaced_subjects: HashSet<String>,
524    /// Every IRI the upgrade has observed in the input graph (rewritten
525    /// to its canonical SBOL 3 form) or allocated as a synthesized
526    /// SBOL 3 subject so far. Every IRI-synthesis site (SA-collapse
527    /// Location rewrite, MapsTo decomposition CRef/Constraint,
528    /// synthesized Interface) routes its candidate IRI through
529    /// `next_available_*` against this pool. The invariant the pool
530    /// enforces (mirrored from the downgrade) is: **no two distinct
531    /// SBOL 3 entities ever land at the same IRI**, regardless of how
532    /// creatively the input names things.
533    used_iris: HashSet<String>,
534    /// Original Location IRI → displayId literal value to emit on the
535    /// rewritten subject. Populated only when the SA-collapse Location
536    /// rewrite had to disambiguate the Location's new IRI with a `_N`
537    /// suffix, so the emitted `sbol3:displayId` still matches the
538    /// IRI's last segment (sbol3-10204 compliance).
539    location_display_id_overrides: HashMap<String, String>,
540    /// Canonical IRIs of custom-typed (GenericTopLevel) subjects that carry
541    /// SBOL 2 identity properties but no recognized SBOL 2 / PROV / OM type.
542    /// SBOL 3 has no GenericTopLevel class, so each is treated as an SBOL 3
543    /// top-level: its custom `rdf:type` is retained and it receives a
544    /// synthesized `sbol3:hasNamespace`.
545    generic_top_levels: HashSet<String>,
546    report: UpgradeReport,
547}
548
549fn is_top_level_sbol2(sbol2_type: &str) -> bool {
550    matches!(
551        sbol2_type,
552        v2::SBOL2_COMPONENT_DEFINITION
553            | v2::SBOL2_MODULE_DEFINITION
554            | v2::SBOL2_SEQUENCE
555            | v2::SBOL2_MODEL
556            | v2::SBOL2_COLLECTION
557            | v2::SBOL2_IMPLEMENTATION
558            | v2::SBOL2_ATTACHMENT
559            | v2::SBOL2_EXPERIMENT
560            | v2::SBOL2_EXPERIMENTAL_DATA
561            | v2::SBOL2_COMBINATORIAL_DERIVATION
562    ) || is_prov_top_level(sbol2_type)
563}
564
565/// PROV classes that act as SBOL 3 top-level objects (they appear at the
566/// document root and need `sbol3:hasNamespace`). PROV `Association` and
567/// `Usage` are intentionally absent; those are children of `Activity`.
568fn is_prov_top_level(type_iri: &str) -> bool {
569    matches!(
570        type_iri,
571        v3::PROV_ACTIVITY | v3::PROV_AGENT_CLASS | v3::PROV_PLAN
572    )
573}
574
575fn type_precedence(type_iri: &str) -> u8 {
576    if is_known_sbol2_type(type_iri) || is_prov_top_level(type_iri) {
577        2
578    } else if type_iri.starts_with(v2::SBOL2_NS) {
579        1
580    } else {
581        0
582    }
583}
584
585fn is_known_sbol2_type(type_iri: &str) -> bool {
586    matches!(
587        type_iri,
588        v2::SBOL2_COMPONENT_DEFINITION
589            | v2::SBOL2_MODULE_DEFINITION
590            | v2::SBOL2_COMPONENT
591            | v2::SBOL2_MODULE
592            | v2::SBOL2_FUNCTIONAL_COMPONENT
593            | v2::SBOL2_SEQUENCE_ANNOTATION
594            | v2::SBOL2_SEQUENCE_CONSTRAINT
595            | v2::SBOL2_SEQUENCE
596            | v2::SBOL2_MODEL
597            | v2::SBOL2_INTERACTION
598            | v2::SBOL2_PARTICIPATION
599            | v2::SBOL2_COLLECTION
600            | v2::SBOL2_IMPLEMENTATION
601            | v2::SBOL2_ATTACHMENT
602            | v2::SBOL2_EXPERIMENT
603            | v2::SBOL2_EXPERIMENTAL_DATA
604            | v2::SBOL2_COMBINATORIAL_DERIVATION
605            | v2::SBOL2_VARIABLE_COMPONENT
606            | v2::SBOL2_RANGE
607            | v2::SBOL2_CUT
608            | v2::SBOL2_GENERIC_LOCATION
609            | v2::SBOL2_MAPS_TO
610    )
611}
612
613use sbol_core::iri::last_iri_segment as last_path_segment;
614
615/// Returns a child `(display_id, iri)` under `parent` whose IRI is not
616/// already in `used`, inserting the chosen IRI. Disambiguates by appending
617/// `_2`, `_3`, … and keeps displayId aligned with the child IRI.
618fn next_available_child_iri(
619    parent: &str,
620    base_display_id: &str,
621    used: &mut HashSet<String>,
622) -> (String, String) {
623    let mut counter: usize = 1;
624    loop {
625        let display_id = if counter == 1 {
626            base_display_id.to_owned()
627        } else {
628            format!("{base_display_id}_{counter}")
629        };
630        let iri = format!("{parent}/{display_id}");
631        if used.insert(iri.clone()) {
632            return (display_id, iri);
633        }
634        counter += 1;
635    }
636}
637
638/// Returns a `(display_id, iri)` for a Constraint synthesized under
639/// `top_level`, using the next available `Constraint<N>` name (1-based). The
640/// counter skips names already taken — including any real SequenceConstraint
641/// on the same Component — matching the reference converter's per-Component
642/// `createConstraint` numbering.
643fn next_available_constraint_iri(top_level: &str, used: &mut HashSet<String>) -> (String, String) {
644    let mut counter: usize = 1;
645    loop {
646        let display_id = format!("Constraint{counter}");
647        let iri = format!("{top_level}/{display_id}");
648        if used.insert(iri.clone()) {
649            return (display_id, iri);
650        }
651        counter += 1;
652    }
653}
654
655/// Canonical N-Triples line for a single triple, used by the snapshot
656/// regenerator and the conformance test so both sides agree on formatting.
657/// `xsd:string`-typed literals are emitted in bare form (matching
658/// sbol-utilities and the N-Triples 1.1 convention) so plain-string
659/// divergences don't masquerade as data drift. Embedded control
660/// characters in literals are escaped per the N-Triples grammar
661/// (`\n`, `\r`, `\t`, `\\`, `\"`) so each triple stays on a single line
662/// for diff-friendly snapshot files.
663pub fn canonical_nt_line(triple: &Triple) -> String {
664    const XSD_STRING: &str = "http://www.w3.org/2001/XMLSchema#string";
665    // `Resource` and `Term` are `#[non_exhaustive]`, so the match
666    // requires a fall-through arm. A future variant should fail the
667    // snapshot loudly rather than silently produce invalid N-Triples;
668    // bumping the underlying RDF crate must come with explicit
669    // handling here.
670    let subject = match &triple.subject {
671        Resource::Iri(iri) => format!("<{}>", iri.as_str()),
672        Resource::BlankNode(b) => format!("_:{}", b.as_str()),
673        other => unreachable!("unhandled Resource variant: {other:?}"),
674    };
675    let predicate = format!("<{}>", triple.predicate.as_str());
676    let object = match &triple.object {
677        Term::Resource(Resource::Iri(iri)) => format!("<{}>", iri.as_str()),
678        Term::Resource(Resource::BlankNode(b)) => format!("_:{}", b.as_str()),
679        Term::Literal(literal) => {
680            let escaped = escape_nt_string(literal.value());
681            if let Some(lang) = literal.language() {
682                format!("\"{escaped}\"@{lang}")
683            } else if literal.datatype().as_str() == XSD_STRING {
684                format!("\"{escaped}\"")
685            } else {
686                format!("\"{escaped}\"^^<{}>", literal.datatype().as_str())
687            }
688        }
689        other => unreachable!("unhandled Term variant: {other:?}"),
690    };
691    format!("{subject} {predicate} {object} .")
692}
693
694fn escape_nt_string(value: &str) -> String {
695    let mut out = String::with_capacity(value.len());
696    for c in value.chars() {
697        match c {
698            '\\' => out.push_str("\\\\"),
699            '"' => out.push_str("\\\""),
700            '\n' => out.push_str("\\n"),
701            '\r' => out.push_str("\\r"),
702            '\t' => out.push_str("\\t"),
703            // N-Triples 1.1 forbids unescaped control characters and
704            // DEL in literals. Emit `\uXXXX` / `\UXXXXXXXX` for anything
705            // in the C0/C1 control ranges and U+007F.
706            c if (c as u32) < 0x20 || c as u32 == 0x7F => {
707                out.push_str(&format!("\\u{:04X}", c as u32));
708            }
709            _ => out.push(c),
710        }
711    }
712    out
713}
714
715fn url_origin(iri: &str) -> Option<String> {
716    // URL form: `scheme://host/path` → `scheme://host`.
717    if let Some((scheme, rest)) = iri.split_once("://") {
718        let authority_end = rest.find('/').unwrap_or(rest.len());
719        let host = &rest[..authority_end];
720        if !scheme.is_empty() && !host.is_empty() {
721            return Some(format!("{scheme}://{host}"));
722        }
723    }
724
725    // URN form (RFC 8141): `urn:nid:nss` → `urn:nid`. Treat the namespace
726    // identifier as the origin so URN-style IRIs get a stable
727    // `hasNamespace` even when persistentIdentity+displayId derivation
728    // fails. Tolerate either `:` or `/` between nid and nss.
729    if let Some(after_urn) = iri.strip_prefix("urn:")
730        && !after_urn.is_empty()
731    {
732        let nid_end = after_urn.find([':', '/']).unwrap_or(after_urn.len());
733        let nid = &after_urn[..nid_end];
734        if !nid.is_empty() {
735            return Some(format!("urn:{nid}"));
736        }
737    }
738    None
739}