use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use ifc::ifczip::{self, Budget, IfcZipError, InnerFormat};
use ifc::schema::for_version;
use ifc::xml_layout::DeclaredXmlLayout;
use ifc::{Codec, EntityId, Model, ModelError, Schema, SchemaVersion, StepCodec, XmlCodec};
use ifc::{SchemaReading, XmlLayout, XmlProfile};
use crate::cli::InputLayout;
use crate::error::{CliError, CliResult};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Source {
Step,
IfcXml(XmlLayout),
}
#[derive(Debug)]
pub(crate) struct Loaded {
pub(crate) model: Model,
pub(crate) path: String,
pub(crate) source: Source,
pub(crate) lines: Option<LineIndex>,
pub(crate) archive_entry: Option<String>,
}
impl Loaded {
pub(crate) fn format(&self) -> String {
let format = match self.source {
Source::Step => "STEP",
Source::IfcXml(XmlLayout::Xsd) => "ifcXML (XSD layout)",
Source::IfcXml(_) => "ifcXML (native layout)",
};
match &self.archive_entry {
Some(entry) => format!("{format} in ifcZIP ({entry})"),
None => format.to_owned(),
}
}
}
pub(crate) fn read(path: &Path, layout: InputLayout) -> CliResult<Loaded> {
let shown = path.display().to_string();
let bytes = std::fs::read(path).map_err(|error| CliError::Io {
path: shown.clone(),
detail: error.to_string(),
})?;
let mut extension = path
.extension()
.and_then(|extension| extension.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
let (bytes, archive_entry) = if ifczip::is_zip(&bytes) {
let entry = ifczip::extract(&bytes, &Budget::DEFAULT).map_err(|error| match error {
IfcZipError::BudgetExceeded { .. } => {
CliError::BudgetExceeded(format!("{shown}: ifcZIP {error}"))
}
IfcZipError::Encrypted { .. } | IfcZipError::UnsupportedCompression { .. } => {
CliError::Unsupported(format!("{shown}: ifcZIP {error}"))
}
other => CliError::Parse {
path: shown.clone(),
detail: format!("ifcZIP {other}"),
},
})?;
extension = match entry.format {
InnerFormat::Step => "ifc",
_ => "ifcxml",
}
.to_owned();
(entry.bytes, Some(entry.name))
} else {
(bytes, None)
};
let xml = XmlCodec::default();
let is_xml = xml.detect(&bytes);
let is_step = !is_xml
&& (StepCodec.detect(&bytes) || StepCodec.extensions().contains(&extension.as_str()));
let parse = |error: ModelError| match error {
ModelError::Io(detail) => CliError::Io {
path: shown.clone(),
detail,
},
other => CliError::Parse {
path: shown.clone(),
detail: other.to_string(),
},
};
if is_step {
let lines = LineIndex::of(&bytes);
let model = StepCodec.read_owned(bytes).map_err(parse)?;
return Ok(Loaded {
model,
path: shown,
source: Source::Step,
lines: Some(lines),
archive_entry,
});
}
if !is_xml && !xml.extensions().contains(&extension.as_str()) {
return Err(CliError::Parse {
path: shown,
detail: "neither a STEP (ISO-10303-21) nor an ifcXML document".to_owned(),
});
}
let codec = xml_reader(&bytes, layout).map_err(|error| match error {
CliError::Unsupported(detail) => CliError::Parse {
path: shown.clone(),
detail,
},
other => other,
})?;
let source = Source::IfcXml(codec.layout());
let model = codec.read_owned(bytes).map_err(parse)?;
Ok(Loaded {
model,
path: shown,
source,
lines: None,
archive_entry,
})
}
fn xml_reader(bytes: &[u8], layout: InputLayout) -> CliResult<XmlCodec> {
let declared = ifc::xml_layout::declared_xml_layout(bytes);
let layout = match (layout, &declared) {
(InputLayout::Native, _) => XmlLayout::Native,
(InputLayout::Xsd, _) => XmlLayout::Xsd,
(InputLayout::Auto, DeclaredXmlLayout::Native { .. }) => XmlLayout::Native,
(InputLayout::Auto, DeclaredXmlLayout::Xsd(_)) => XmlLayout::Xsd,
(InputLayout::Auto, _) => {
return Err(CliError::Unsupported(
"cannot tell the ifcXML layout: the root element has no `schema` attribute \
(native layout) and no IFC4 or IFC4X3_ADD2 namespace (XSD layout); \
name it with --input-layout"
.to_owned(),
))
}
};
if layout == XmlLayout::Xsd {
let DeclaredXmlLayout::Xsd(profile) = declared else {
return Err(CliError::Unsupported(
"an XSD-layout document must declare the IFC4 ADD2 TC1 or IFC4X3 ADD2 namespace"
.to_owned(),
));
};
return Ok(XmlCodec::xsd(release_tables(profile.version())?, profile));
}
let DeclaredXmlLayout::Native { schema, positional } = declared else {
return Ok(XmlCodec::default());
};
let bundled =
SchemaVersion::from_header_token(&schema).and_then(|version| release_tables(version).ok());
Ok(match bundled {
Some(tables) if positional => {
XmlCodec::with_schema(tables).with_reading(SchemaReading::Lenient)
}
Some(tables) => XmlCodec::with_schema(tables),
None => XmlCodec::default(),
})
}
fn release_tables(version: SchemaVersion) -> CliResult<Arc<Schema>> {
for_version(version)
.map(|schema| Arc::new(schema.clone()))
.map_err(|refused| {
CliError::UnsupportedSchema(format!("{}: {refused}", version.release_id()))
})
}
pub(crate) fn xsd_profile_for(version: SchemaVersion) -> Option<XmlProfile> {
[XmlProfile::Ifc4Add2Tc1, XmlProfile::Ifc4x3Add2]
.into_iter()
.find(|profile| profile.version() == version)
}
pub(crate) fn declared_schema(model: &Model) -> CliResult<&'static Schema> {
let token = model.header().schema_token().ok_or_else(|| {
CliError::UnsupportedSchema("the header declares no FILE_SCHEMA".to_owned())
})?;
let version = SchemaVersion::from_header_token(token).ok_or_else(|| {
CliError::UnsupportedSchema(format!("unrecognised schema token {token:?}"))
})?;
for_version(version)
.map_err(|refused| CliError::UnsupportedSchema(format!("{token}: {refused}")))
}
pub(crate) fn find_entity(model: &Model, schema: &Schema, reference: &str) -> CliResult<EntityId> {
let trimmed = reference.trim();
let digits = trimmed.strip_prefix('#').unwrap_or(trimmed);
if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) {
let id = digits
.parse::<u64>()
.map(EntityId)
.map_err(|_| CliError::MissingEntity(format!("#{digits} is out of range")))?;
return if model.contains(id) {
Ok(id)
} else {
Err(CliError::MissingEntity(format!(
"#{} is not in the model",
id.0
)))
};
}
let Some(guid) = ifc::Guid::parse(trimmed) else {
return Err(CliError::Usage(format!(
"{trimmed:?} is neither an entity id (#12) nor a valid 22-character GlobalId"
)));
};
match ifc::by_guid(model, schema, &guid) {
Ok(Some(id)) => Ok(id),
Ok(None) => Err(CliError::MissingEntity(format!(
"no entity has GlobalId {trimmed}"
))),
Err(duplicate) => Err(CliError::InvalidModel(duplicate.to_string())),
}
}
#[derive(Debug, Default)]
pub(crate) struct LineIndex {
lines: HashMap<u64, usize>,
}
impl LineIndex {
pub(crate) fn of(bytes: &[u8]) -> Self {
let mut lines = HashMap::new();
for (index, line) in bytes.split(|byte| *byte == b'\n').enumerate() {
let line = line.trim_ascii_start();
let Some(rest) = line.strip_prefix(b"#") else {
continue;
};
let digits = rest.iter().take_while(|byte| byte.is_ascii_digit()).count();
if digits == 0 || !rest[digits..].trim_ascii_start().starts_with(b"=") {
continue;
}
let id = std::str::from_utf8(&rest[..digits])
.ok()
.and_then(|text| text.parse::<u64>().ok());
if let Some(id) = id {
lines.entry(id).or_insert(index + 1);
}
}
Self { lines }
}
pub(crate) fn line(&self, id: u64) -> Option<usize> {
self.lines.get(&id).copied()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn records_are_indexed_by_their_line() {
let index = LineIndex::of(b"DATA;\n#1=IFCWALL();\n #20 = IFCSLAB();\n#3IFCX;\n");
assert_eq!(index.line(1), Some(2));
assert_eq!(index.line(20), Some(3));
assert_eq!(index.line(3), None, "no `=`: not a record start");
}
}