use std::fmt;
use crate::constants::{
EDAM_IUPAC_DNA, EDAM_IUPAC_PROTEIN, EDAM_IUPAC_RNA, RESTRICTION_MEETS,
ROLE_INTEGRATION_MERGE_ROLES, SBO_DNA, SBO_PROTEIN, SBO_RNA,
};
use crate::{
BuildError, Component, Constraint, Document, Iri, Namespace, Resource, SbolObject,
SbolTopLevel, Sequence, SubComponent,
};
macro_rules! handle {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct $name(usize);
};
}
handle!(
ComponentId
);
handle!(
SequenceId
);
handle!(
FeatureId
);
handle!(
ConstraintId
);
#[derive(Debug)]
#[non_exhaustive]
pub enum DesignProblem {
Build {
display_id: String,
source: BuildError,
},
DanglingReference {
display_id: String,
},
Assembly(BuildError),
Custom(String),
}
impl fmt::Display for DesignProblem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Build { display_id, source } => {
write!(f, "failed to build `{display_id}`: {source}")
}
Self::DanglingReference { display_id } => {
write!(
f,
"`{display_id}` references an object that failed to build"
)
}
Self::Assembly(source) => write!(f, "failed to assemble document: {source}"),
Self::Custom(message) => write!(f, "{message}"),
}
}
}
#[derive(Debug)]
pub struct DesignError {
pub problems: Vec<DesignProblem>,
}
impl fmt::Display for DesignError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "design has {} problem(s):", self.problems.len())?;
for problem in &self.problems {
write!(f, "\n - {problem}")?;
}
Ok(())
}
}
impl std::error::Error for DesignError {}
pub struct Design {
namespace: Namespace,
slots: Vec<Slot>,
problems: Vec<DesignProblem>,
}
#[allow(clippy::large_enum_variant)]
enum Slot {
Object(SbolObject),
Pending(SubComponentSpec),
Failed,
}
impl Design {
pub fn new(namespace: impl AsRef<str>) -> Result<Self, DesignError> {
let namespace = Namespace::new(namespace.as_ref()).map_err(|source| DesignError {
problems: vec![DesignProblem::Build {
display_id: namespace.as_ref().to_string(),
source: source.into(),
}],
})?;
Ok(Self {
namespace,
slots: Vec::new(),
problems: Vec::new(),
})
}
pub fn from_document(document: &Document) -> Result<Self, DesignError> {
let namespace = imported_namespace(document).ok_or_else(|| DesignError {
problems: vec![DesignProblem::Custom(
"cannot import a document with no namespaced top-level object; \
the arena needs a namespace to root any objects added later"
.to_string(),
)],
})?;
let slots = document
.typed_objects()
.iter()
.cloned()
.map(Slot::Object)
.collect();
Ok(Self {
namespace,
slots,
problems: Vec::new(),
})
}
pub fn component_id(&self, identity: &Resource) -> Option<ComponentId> {
self.slots
.iter()
.enumerate()
.find_map(|(index, slot)| match slot {
Slot::Object(SbolObject::Component(component))
if &component.identity == identity =>
{
Some(ComponentId(index))
}
_ => None,
})
}
pub fn component(&mut self, display_id: &str) -> ComponentDraft<'_> {
ComponentDraft {
design: self,
display_id: display_id.to_string(),
types: Vec::new(),
roles: Vec::new(),
sequences: Vec::new(),
name: None,
description: None,
}
}
pub fn sequence(&mut self, display_id: &str) -> SequenceDraft<'_> {
SequenceDraft {
design: self,
display_id: display_id.to_string(),
elements: None,
encoding: None,
name: None,
description: None,
}
}
pub fn sub_component(
&mut self,
parent: ComponentId,
display_id: &str,
) -> SubComponentDraft<'_> {
SubComponentDraft {
design: self,
parent: Some(parent),
display_id: display_id.to_string(),
instance_of: None,
roles: Vec::new(),
role_integration: None,
name: None,
description: None,
}
}
pub fn detached_sub_component(&mut self, display_id: &str) -> SubComponentDraft<'_> {
SubComponentDraft {
design: self,
parent: None,
display_id: display_id.to_string(),
instance_of: None,
roles: Vec::new(),
role_integration: None,
name: None,
description: None,
}
}
pub fn meets(
&mut self,
parent: ComponentId,
left: FeatureId,
right: FeatureId,
) -> ConstraintId {
self.constrain(parent, left, RESTRICTION_MEETS, right)
}
pub fn constrain(
&mut self,
parent: ComponentId,
subject: FeatureId,
restriction: Iri,
object: FeatureId,
) -> ConstraintId {
let display_id = format!("constraint_{}", self.parent_constraint_count(parent));
let (parent_iri, subject_iri, object_iri) = match (
self.identity_of(parent.0),
self.identity_of(subject.0),
self.identity_of(object.0),
) {
(Some(p), Some(s), Some(o)) => (p, s, o),
_ => return ConstraintId(self.push_dangling(display_id)),
};
let built = Constraint::builder(&parent_iri, display_id.as_str()).and_then(|b| {
b.subject(subject_iri)
.restriction(restriction)
.constrained_object(object_iri)
.build()
});
match built {
Ok(constraint) => {
let child = constraint.identity.clone();
let index = self.push(SbolObject::Constraint(constraint));
self.attach_constraint(parent, child);
ConstraintId(index)
}
Err(source) => ConstraintId(self.push_failed(display_id, source)),
}
}
pub fn resolve_component(&self, component: ComponentId) -> Option<&Component> {
match &self.slots[component.0] {
Slot::Object(SbolObject::Component(component)) => Some(component),
_ => None,
}
}
pub fn report(&mut self, message: impl Into<String>) {
self.problems.push(DesignProblem::Custom(message.into()));
}
pub fn place_feature(&mut self, parent: ComponentId, feature: FeatureId) -> FeatureId {
let spec = match std::mem::replace(&mut self.slots[feature.0], Slot::Failed) {
Slot::Pending(spec) => spec,
other => {
self.slots[feature.0] = other;
self.report(
"place_feature expects a detached feature from \
`detached_sub_component`; the handle is already placed or invalid",
);
return feature;
}
};
self.finish_sub_component(parent, spec)
}
pub fn finish(self) -> Result<Document, DesignError> {
if !self.problems.is_empty() {
return Err(DesignError {
problems: self.problems,
});
}
let objects = self
.slots
.into_iter()
.filter_map(|slot| match slot {
Slot::Object(object) => Some(object),
Slot::Pending(_) | Slot::Failed => None,
})
.collect();
Document::from_objects(objects).map_err(|source| DesignError {
problems: vec![DesignProblem::Assembly(source)],
})
}
fn push(&mut self, object: SbolObject) -> usize {
self.slots.push(Slot::Object(object));
self.slots.len() - 1
}
fn push_pending(&mut self, spec: SubComponentSpec) -> usize {
self.slots.push(Slot::Pending(spec));
self.slots.len() - 1
}
fn push_failed(&mut self, display_id: String, source: BuildError) -> usize {
self.problems
.push(DesignProblem::Build { display_id, source });
self.slots.push(Slot::Failed);
self.slots.len() - 1
}
fn push_dangling(&mut self, display_id: String) -> usize {
self.problems
.push(DesignProblem::DanglingReference { display_id });
self.slots.push(Slot::Failed);
self.slots.len() - 1
}
fn identity_of(&self, index: usize) -> Option<Resource> {
match &self.slots[index] {
Slot::Object(object) => Some(object.identity().clone()),
Slot::Pending(_) | Slot::Failed => None,
}
}
fn parent_constraint_count(&self, parent: ComponentId) -> usize {
match &self.slots[parent.0] {
Slot::Object(SbolObject::Component(component)) => component.constraints.len(),
_ => 0,
}
}
fn attach_feature(&mut self, parent: ComponentId, child: Resource) {
if let Slot::Object(SbolObject::Component(component)) = &mut self.slots[parent.0] {
component.features.push(child);
}
}
fn attach_constraint(&mut self, parent: ComponentId, child: Resource) {
if let Slot::Object(SbolObject::Component(component)) = &mut self.slots[parent.0] {
component.constraints.push(child);
}
}
fn finish_component(
&mut self,
display_id: String,
types: Vec<Iri>,
roles: Vec<Iri>,
sequences: Vec<SequenceId>,
name: Option<String>,
description: Option<String>,
) -> ComponentId {
let sequence_iris: Vec<Resource> = sequences
.into_iter()
.filter_map(|id| self.identity_of(id.0))
.collect();
let built =
Component::builder(self.namespace.as_str(), display_id.as_str()).and_then(|b| {
let mut b = b
.types(types)
.component_roles(roles)
.sequences(sequence_iris);
if let Some(name) = name {
b = b.name(name);
}
if let Some(description) = description {
b = b.description(description);
}
b.build()
});
match built {
Ok(component) => ComponentId(self.push(SbolObject::Component(component))),
Err(source) => ComponentId(self.push_failed(display_id, source)),
}
}
fn finish_sequence(
&mut self,
display_id: String,
elements: Option<String>,
encoding: Option<Iri>,
name: Option<String>,
description: Option<String>,
) -> SequenceId {
let built = Sequence::builder(self.namespace.as_str(), display_id.as_str()).and_then(|b| {
let mut b = b;
if let Some(elements) = elements {
b = b.elements(elements);
}
if let Some(encoding) = encoding {
b = b.encoding(encoding);
}
if let Some(name) = name {
b = b.name(name);
}
if let Some(description) = description {
b = b.description(description);
}
b.build()
});
match built {
Ok(sequence) => SequenceId(self.push(SbolObject::Sequence(sequence))),
Err(source) => SequenceId(self.push_failed(display_id, source)),
}
}
fn finish_sub_component(&mut self, parent: ComponentId, spec: SubComponentSpec) -> FeatureId {
let SubComponentSpec {
display_id,
instance_of,
roles,
role_integration,
name,
description,
} = spec;
let parent_iri = match self.identity_of(parent.0) {
Some(iri) => iri,
None => return FeatureId(self.push_dangling(display_id)),
};
let instance_iri = instance_of.and_then(|id| self.identity_of(id.0));
let role_integration = match role_integration {
Some(value) => Some(value),
None if !roles.is_empty() => Some(ROLE_INTEGRATION_MERGE_ROLES),
None => None,
};
let built = SubComponent::builder(&parent_iri, display_id.as_str()).and_then(|b| {
let mut b = b.roles(roles);
if let Some(instance_iri) = instance_iri {
b = b.instance_of(instance_iri);
}
if let Some(role_integration) = role_integration {
b = b.role_integration(role_integration);
}
if let Some(name) = name {
b = b.name(name);
}
if let Some(description) = description {
b = b.description(description);
}
b.build()
});
match built {
Ok(sub) => {
let child = sub.identity.clone();
let index = self.push(SbolObject::SubComponent(sub));
self.attach_feature(parent, child);
FeatureId(index)
}
Err(source) => FeatureId(self.push_failed(display_id, source)),
}
}
}
#[must_use = "call `.add()` to register the component in the design"]
pub struct ComponentDraft<'d> {
design: &'d mut Design,
display_id: String,
types: Vec<Iri>,
roles: Vec<Iri>,
sequences: Vec<SequenceId>,
name: Option<String>,
description: Option<String>,
}
impl ComponentDraft<'_> {
pub fn dna(mut self) -> Self {
self.types.push(SBO_DNA);
self
}
pub fn rna(mut self) -> Self {
self.types.push(SBO_RNA);
self
}
pub fn protein(mut self) -> Self {
self.types.push(SBO_PROTEIN);
self
}
pub fn type_(mut self, type_: Iri) -> Self {
self.types.push(type_);
self
}
pub fn role(mut self, role: Iri) -> Self {
self.roles.push(role);
self
}
pub fn sequence(mut self, sequence: SequenceId) -> Self {
self.sequences.push(sequence);
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn add(self) -> ComponentId {
let Self {
design,
display_id,
types,
roles,
sequences,
name,
description,
} = self;
design.finish_component(display_id, types, roles, sequences, name, description)
}
}
#[must_use = "call `.add()` to register the sequence in the design"]
pub struct SequenceDraft<'d> {
design: &'d mut Design,
display_id: String,
elements: Option<String>,
encoding: Option<Iri>,
name: Option<String>,
description: Option<String>,
}
impl SequenceDraft<'_> {
pub fn elements(mut self, elements: impl Into<String>) -> Self {
self.elements = Some(elements.into());
self
}
pub fn dna(mut self) -> Self {
self.encoding = Some(EDAM_IUPAC_DNA);
self
}
pub fn rna(mut self) -> Self {
self.encoding = Some(EDAM_IUPAC_RNA);
self
}
pub fn protein(mut self) -> Self {
self.encoding = Some(EDAM_IUPAC_PROTEIN);
self
}
pub fn encoding(mut self, encoding: Iri) -> Self {
self.encoding = Some(encoding);
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn add(self) -> SequenceId {
let Self {
design,
display_id,
elements,
encoding,
name,
description,
} = self;
design.finish_sequence(display_id, elements, encoding, name, description)
}
}
#[must_use = "call `.add()` to register the sub-component in the design"]
pub struct SubComponentDraft<'d> {
design: &'d mut Design,
parent: Option<ComponentId>,
display_id: String,
instance_of: Option<ComponentId>,
roles: Vec<Iri>,
role_integration: Option<Iri>,
name: Option<String>,
description: Option<String>,
}
impl SubComponentDraft<'_> {
pub fn instance_of(mut self, component: ComponentId) -> Self {
self.instance_of = Some(component);
self
}
pub fn role_integration(mut self, role_integration: Iri) -> Self {
self.role_integration = Some(role_integration);
self
}
pub fn role(mut self, role: Iri) -> Self {
self.roles.push(role);
self
}
pub fn roles(mut self, roles: impl IntoIterator<Item = Iri>) -> Self {
self.roles = roles.into_iter().collect();
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn add(self) -> FeatureId {
let Self {
design,
parent,
display_id,
instance_of,
roles,
role_integration,
name,
description,
} = self;
let spec = SubComponentSpec {
display_id,
instance_of,
roles,
role_integration,
name,
description,
};
match parent {
Some(parent) => design.finish_sub_component(parent, spec),
None => FeatureId(design.push_pending(spec)),
}
}
}
struct SubComponentSpec {
display_id: String,
instance_of: Option<ComponentId>,
roles: Vec<Iri>,
role_integration: Option<Iri>,
name: Option<String>,
description: Option<String>,
}
fn imported_namespace(document: &Document) -> Option<Namespace> {
let iri = document
.components()
.find_map(|component| component.namespace())
.or_else(|| {
document
.sequences()
.find_map(|sequence| sequence.namespace())
})
.or_else(|| {
document
.collections()
.find_map(|collection| collection.namespace())
})?;
Namespace::new(iri.as_str()).ok()
}
pub fn sanitize_display_id(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for ch in input.chars() {
if ch.is_ascii_alphanumeric() || ch == '_' {
out.push(ch);
} else {
out.push('_');
}
}
match out.chars().next() {
None => "_".to_string(),
Some(first) if first.is_ascii_digit() => format!("_{out}"),
Some(_) => out,
}
}
#[cfg(test)]
mod tests;