use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crossfoot_core::xml::{resolve_uri, Node};
use crossfoot_core::{
ns, Atom, Decimal, Decimals, Diagnostic, Document, Fact, FactId, FactKind, Footnote,
FootnoteRel, FootnoteTarget, Frag, InlineInfo, Instance, InstanceSource, QName,
};
use crossfoot_instance::{parse_context, parse_unit};
use indexmap::IndexMap;
use crate::codes::*;
use crate::schema::{self, is_ix, is_ix_named};
use crate::text::{collapse, escaped_content, inner_text, xtrim, EscapeCtx, Exclude};
use crate::transform::{self, TransformError};
use crate::InlineSet;
type Key = (usize, u32);
fn key(di: usize, n: Node<'_>) -> Key {
(di, n.id.0)
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum Kind {
NonFraction,
NonNumeric,
Fraction,
Tuple,
}
struct FactRec<'a> {
di: usize,
node: Node<'a>,
kind: Kind,
name: Option<QName>,
target: Option<Atom>,
nil: bool,
value: Option<String>,
fraction: Option<(String, String)>,
display: String,
format: Option<QName>,
scale: Option<i32>,
sign_negative: bool,
continued: bool,
invalid: bool,
parent: Option<usize>,
order: Option<Decimal>,
dropped: bool,
children: Vec<usize>,
}
fn ws_attr<'a>(n: Node<'a>, local: &str) -> Option<&'a str> {
n.att(local).map(xtrim)
}
fn is_nil(n: Node<'_>) -> bool {
matches!(n.attr(ns::XSI, "nil").map(xtrim), Some("true") | Some("1"))
}
fn nearest_ix_ancestor(n: Node<'_>) -> Option<Node<'_>> {
let mut cur = n.parent_element();
while let Some(p) = cur {
if is_ix(p) {
return Some(p);
}
cur = p.parent_element();
}
None
}
fn html_base(doc: &Document) -> Option<String> {
let root = doc.document_element()?;
let head = root.elements().find(|e| e.is(ns::XHTML, "head"))?;
let base = head.elements().find(|e| e.is(ns::XHTML, "base"))?;
base.att("href").map(|s| s.to_string())
}
fn d(code: &str, msg: impl Into<String>, n: Node<'_>) -> Diagnostic {
Diagnostic::error(code, msg).at(n)
}
pub(crate) fn load(docs: Vec<Arc<Document>>) -> InlineSet {
let mut diags: Vec<Diagnostic> = Vec::new();
let uris: Vec<Atom> = docs.iter().map(|d| d.uri.clone()).collect();
let docs_ref: Vec<&Document> = docs.iter().map(|d| &**d).collect();
let mut usable: Vec<bool> = Vec::with_capacity(docs.len());
for doc in &docs_ref {
let ok = match doc.document_element() {
Some(r) => r.is(ns::XHTML, "html"),
None => false,
};
if !ok {
let msg = format!(
"{} is not an Inline XBRL document (root must be xhtml:html)",
doc.uri
);
match doc.document_element() {
Some(r) => diags.push(d(UNSUPPORTED_DOCUMENT_TYPE, msg, r)),
None => diags.push(Diagnostic::error(UNSUPPORTED_DOCUMENT_TYPE, msg)),
}
} else {
schema::check_document(doc, &mut diags);
}
usable.push(ok);
}
let html_bases: Vec<EscapeCtx> = docs_ref
.iter()
.map(|d| EscapeCtx {
html_base: html_base(d),
})
.collect();
let mut ix_elems: Vec<(usize, Node<'_>)> = Vec::new();
for (di, doc) in docs_ref.iter().enumerate() {
if !usable[di] {
continue;
}
for n in doc.elements() {
if is_ix(n) {
ix_elems.push((di, n));
}
}
}
let of = |local: &'static str| {
ix_elems
.iter()
.filter(move |(_, n)| n.local() == local)
.copied()
};
let mut ids: HashMap<String, (usize, Node<'_>)> = HashMap::new();
for (di, doc) in docs_ref.iter().enumerate() {
if !usable[di] {
continue;
}
let mut local_ids: HashSet<&str> = HashSet::new();
for n in doc.elements() {
let Some(id) = n.att("id") else { continue };
let id = xtrim(id);
if !local_ids.insert(id) {
diags.push(d(
DUPLICATE_ID,
format!("id '{}' is not unique in the document", id),
n,
));
continue;
}
let relevant = is_ix(n)
|| n.ancestors()
.any(|a| is_ix(a) && matches!(a.local(), "resources" | "references"));
if !relevant {
continue;
}
if let Some((odi, _)) = ids.get(id) {
if *odi != di {
diags.push(d(
DUPLICATE_ID,
format!("id '{}' is not unique in the document set", id),
n,
));
}
continue;
}
ids.insert(id.to_string(), (di, n));
}
}
if of("header").next().is_none() {
diags.push(Diagnostic::error(
HEADER_ABSENT,
"the document set has no ix:header",
));
}
if of("resources").next().is_none() {
diags.push(Diagnostic::error(
RESOURCES_ABSENT,
"the document set has no ix:resources",
));
}
struct TargetRefs<'a> {
refs: Vec<Node<'a>>,
schema_refs: Vec<Atom>,
linkbase_refs: Vec<Atom>,
lang: Option<Atom>,
}
let mut targets: IndexMap<Option<Atom>, TargetRefs<'_>> = IndexMap::new();
for (_, r) in of("references") {
let target = ws_attr(r, "target").map(Atom::from);
let t = targets.entry(target).or_insert_with(|| TargetRefs {
refs: Vec::new(),
schema_refs: Vec::new(),
linkbase_refs: Vec::new(),
lang: None,
});
for c in r.elements() {
if let Some(h) = c.attr(ns::XLINK, "href") {
let u = Atom::from(resolve_uri(&c.base_uri(), xtrim(h)).as_str());
if c.is(ns::LINK, "schemaRef") {
t.schema_refs.push(u);
} else if c.is(ns::LINK, "linkbaseRef") {
t.linkbase_refs.push(u);
}
}
}
if let Some(l) = r.attr(ns::XML, "lang") {
t.lang = Some(Atom::from(l));
}
t.refs.push(r);
}
for (target, t) in &targets {
let tname = target.as_deref().unwrap_or("(default)");
let mut seen: HashSet<QName> = HashSet::new();
let mut with_id = 0;
for r in &t.refs {
for a in r.attributes() {
let ans: &str = &a.name.ns;
if ans.is_empty() {
if &*a.name.local == "id" {
with_id += 1;
}
continue;
}
if ans == ns::XBRLI {
diags.push(d(
INVALID_ATTRIBUTE_CONTENT,
format!(
"ix:references must not have the xbrli attribute {}",
a.name.local
),
*r,
));
continue;
}
if schema::is_ix_ns(ans) || (ans == ns::XML && &*a.name.local == "base") {
continue;
}
if !seen.insert(a.name.clone()) {
diags.push(d(
REPEATED_OTHER_ATTRIBUTES,
format!(
"attribute {} appears on more than one ix:references for target {}",
a.name, tname
),
*r,
));
}
}
}
if with_id > 1 {
diags.push(d(
REPEATED_ID_ATTRIBUTE,
format!("more than one ix:references for target {} has an id", tname),
t.refs[1],
));
}
if t.refs.len() > 1 {
let scopes: Vec<Vec<(Atom, Atom)>> =
t.refs.iter().map(|r| r.in_scope_namespaces()).collect();
let get = |s: &Vec<(Atom, Atom)>, p: &str| {
s.iter().find(|(q, _)| &**q == p).map(|(_, u)| u.clone())
};
'outer: for i in 0..scopes.len() {
for j in i + 1..scopes.len() {
let (a, b) = (&scopes[i], &scopes[j]);
if get(a, "") != get(b, "") {
diags.push(d(
REFERENCES_NAMESPACE_CLASH,
format!(
"ix:references for target {} have different default namespaces",
tname
),
t.refs[j],
));
break 'outer;
}
for (p, u) in a {
if let Some(u2) = get(b, p) {
if &u2 != u {
diags.push(d(REFERENCES_NAMESPACE_CLASH, format!("prefix {} is bound to different namespaces on ix:references for target {}", p, tname), t.refs[j]));
break 'outer;
}
}
}
}
}
}
}
let mut contexts: IndexMap<Atom, crossfoot_core::Context> = IndexMap::new();
let mut units: IndexMap<Atom, crossfoot_core::Unit> = IndexMap::new();
let mut role_refs: Vec<(Atom, Atom)> = Vec::new();
let mut arcrole_refs: Vec<(Atom, Atom)> = Vec::new();
for (di, res) in of("resources") {
for r in res.elements() {
if !is_ix(r) {
for x in r.descendant_elements() {
if is_ix(x) {
diags.push(d(
MISPLACED_IX_ELEMENT,
format!("ix:{} must not appear inside {}", x.local(), r.name()),
x,
));
}
}
}
match (r.ns(), r.local()) {
(ns::XBRLI, "context") => match parse_context(r, di as u32) {
Ok(c) => {
if !c.id.is_empty() {
contexts.entry(c.id.clone()).or_insert(c);
}
}
Err(e) => diags.push(e),
},
(ns::XBRLI, "unit") => match parse_unit(r, di as u32) {
Ok(u) => {
if !u.id.is_empty() {
units.entry(u.id.clone()).or_insert(u);
}
}
Err(e) => diags.push(e),
},
(ns::LINK, "roleRef") => role_refs.push((
Atom::from(r.att("roleURI").unwrap_or("")),
Atom::from(
resolve_uri(&r.base_uri(), r.attr(ns::XLINK, "href").unwrap_or(""))
.as_str(),
),
)),
(ns::LINK, "arcroleRef") => arcrole_refs.push((
Atom::from(r.att("arcroleURI").unwrap_or("")),
Atom::from(
resolve_uri(&r.base_uri(), r.attr(ns::XLINK, "href").unwrap_or(""))
.as_str(),
),
)),
_ => {}
}
}
}
for (_, x) in of("exclude") {
if !x
.ancestors()
.any(|a| is_ix(a) && matches!(a.local(), "continuation" | "footnote" | "nonNumeric"))
{
diags.push(d(
MISPLACED_EXCLUDE,
"ix:exclude must be a descendant of ix:nonNumeric, ix:footnote or ix:continuation",
x,
));
}
}
let mut continuations: HashMap<&str, (usize, Node<'_>)> = HashMap::new();
for (di, c) in of("continuation") {
if let Some(id) = ws_attr(c, "id") {
continuations.entry(id).or_insert((di, c));
}
}
let mut chains: HashMap<Key, Vec<(usize, Node<'_>)>> = HashMap::new();
let mut reached: HashMap<Key, usize> = HashMap::new();
for (di, head) in ix_elems
.iter()
.copied()
.filter(|(_, n)| matches!(n.local(), "nonNumeric" | "footnote"))
{
let Some(mut next) = ws_attr(head, "continuedAt") else {
continue;
};
let mut chain: Vec<(usize, Node<'_>)> = Vec::new();
let mut members: Vec<Node<'_>> = vec![head];
loop {
match continuations.get(next) {
None => {
diags.push(d(
DANGLING_CONTINUATION,
format!(
"continuedAt '{}' does not identify an ix:continuation",
next
),
head,
));
break;
}
Some(&(cdi, c)) => {
if members.contains(&c) {
diags.push(d(
CONTINUATION_REUSE,
format!("continuation chain of {} is cyclic", next),
c,
));
break;
}
let n = reached.entry(key(cdi, c)).or_insert(0);
*n += 1;
if *n > 1 {
diags.push(d(
CONTINUATION_REUSE,
format!(
"ix:continuation '{}' is the continuation of more than one element",
next
),
c,
));
}
members.push(c);
chain.push((cdi, c));
match ws_attr(c, "continuedAt") {
Some(nx) => next = nx,
None => break,
}
}
}
}
'nest: for (i, a) in members.iter().enumerate() {
for (j, b) in members.iter().enumerate() {
if i != j && a.is_ancestor_of(b) {
diags.push(d(CONTINUATION_INVALID_NESTING, "an element of a continuation chain contains another element of the same chain", *b));
break 'nest;
}
}
}
chains.insert(key(di, head), chain);
}
for (di, c) in of("continuation") {
if !reached.contains_key(&key(di, c)) {
diags.push(d(
UNREFERENCED_CONTINUATION,
format!(
"ix:continuation '{}' is not the continuation of any fact or footnote",
ws_attr(c, "id").unwrap_or("")
),
c,
));
}
}
let mut facts: Vec<FactRec<'_>> = Vec::new();
let mut fact_index: HashMap<Key, usize> = HashMap::new();
for &(di, n) in &ix_elems {
let kind = match n.local() {
"nonFraction" => Kind::NonFraction,
"nonNumeric" => Kind::NonNumeric,
"fraction" => Kind::Fraction,
"tuple" => Kind::Tuple,
_ => continue,
};
if kind != Kind::Fraction {
if let Some(a) = nearest_ix_ancestor(n) {
if a.local() == "fraction" {
diags.push(d(
UNKNOWN_FRACTION_CHILD,
format!("ix:{} is not allowed inside ix:fraction", n.local()),
n,
));
continue;
}
}
}
let name = n.att("name").and_then(|v| n.resolve_qname(v, true));
if n.att("name").is_some() && name.is_none() {
diags.push(d(
schema::CVC_DATATYPE,
format!(
"name '{}' is not a resolvable QName",
n.att("name").unwrap_or("")
),
n,
));
}
for a in n.attributes() {
if a.name.ns.as_ref() == ns::XBRLI {
diags.push(d(
INVALID_ATTRIBUTE_CONTENT,
format!(
"ix:{} must not have the xbrli attribute {}",
n.local(),
a.name.local
),
n,
));
}
}
let rec = build_fact(di, n, kind, name, &chains, &html_bases[di], &mut diags);
fact_index.insert(key(di, n), facts.len());
facts.push(rec);
}
for f in &facts {
if f.kind != Kind::Tuple {
if let Some(c) = ws_attr(f.node, "contextRef") {
if !contexts.contains_key(c) {
diags.push(d(
UNKNOWN_CONTEXT,
format!(
"contextRef '{}' does not identify a context in ix:resources",
c
),
f.node,
));
}
}
}
if matches!(f.kind, Kind::NonFraction | Kind::Fraction) {
if let Some(u) = ws_attr(f.node, "unitRef") {
if !units.contains_key(u) {
diags.push(d(
UNKNOWN_UNIT,
format!("unitRef '{}' does not identify a unit in ix:resources", u),
f.node,
));
}
}
}
}
let mut used_targets: Vec<Option<Atom>> = Vec::new();
for f in &facts {
if !used_targets.contains(&f.target) {
used_targets.push(f.target.clone());
}
}
if used_targets.is_empty() {
used_targets.push(None);
}
for t in &used_targets {
if !targets.contains_key(t) {
diags.push(Diagnostic::error(
REFERENCES_ABSENT,
format!(
"no ix:references for target {}",
t.as_deref().unwrap_or("(default)")
),
));
}
}
let mut tuple_ids: HashMap<&str, usize> = HashMap::new();
for (i, f) in facts.iter().enumerate() {
if f.kind == Kind::Tuple {
if let Some(t) = ws_attr(f.node, "tupleID") {
if tuple_ids.contains_key(t) {
diags.push(d(
DUPLICATE_TUPLE_ID,
format!("tupleID '{}' is not unique in the document set", t),
f.node,
));
} else {
tuple_ids.insert(t, i);
}
}
}
}
for i in 0..facts.len() {
let n = facts[i].node;
let parent = match ws_attr(n, "tupleRef") {
Some(r) => match tuple_ids.get(r) {
Some(&p) => Some(p),
None => {
diags.push(d(
UNKNOWN_TUPLE,
format!("tupleRef '{}' does not identify an ix:tuple", r),
n,
));
None
}
},
None => nearest_ix_ancestor(n)
.filter(|a| a.local() == "tuple")
.and_then(|a| fact_index.get(&key(facts[i].di, a)).copied()),
};
let order_attr = ws_attr(n, "order");
let order = order_attr.and_then(|o| {
if schema::is_decimal_lexical(o) {
Decimal::parse(o)
} else {
None
}
});
match parent {
Some(p) => {
if order_attr.is_none() {
diags.push(d(
ORDER_ABSENT,
"a tuple member must have an order attribute",
n,
));
}
if facts[p].target != facts[i].target {
diags.push(d(
INCONSISTENT_TARGETS,
"a tuple member must have the same target as its tuple",
n,
));
}
facts[i].parent = Some(p);
facts[i].order = order;
facts[p].children.push(i);
}
None => {
if order_attr.is_some() && ws_attr(n, "tupleRef").is_none() {
diags.push(d(
ORDER_ON_NON_TUPLE_CHILD,
"order is only allowed on tuple members",
n,
));
}
}
}
}
for i in 0..facts.len() {
let mut seen = vec![i];
let mut cur = facts[i].parent;
while let Some(p) = cur {
if p == i {
diags.push(d(TUPLE_CYCLE, "tuple nesting is cyclic", facts[i].node));
break;
}
if seen.contains(&p) {
break;
}
seen.push(p);
cur = facts[p].parent;
}
}
let in_cycle: Vec<bool> = (0..facts.len())
.map(|i| {
let mut seen = vec![i];
let mut cur = facts[i].parent;
while let Some(p) = cur {
if seen.contains(&p) {
return true;
}
seen.push(p);
cur = facts[p].parent;
}
false
})
.collect();
for t in 0..facts.len() {
if facts[t].kind != Kind::Tuple {
continue;
}
let kids = facts[t].children.clone();
if facts[t].nil && !kids.is_empty() {
diags.push(d(
NIL_TUPLE_WITH_CHILD,
"a nil tuple must not have members",
facts[t].node,
));
}
if !facts[t].nil && kids.is_empty() {
diags.push(d(
TUPLE_NON_EMPTY_VALIDATION,
"a tuple must have at least one member",
facts[t].node,
));
}
check_tuple_descendants(facts[t].node, &mut diags);
let mut sorted = kids.clone();
sorted.sort_by(|a, b| facts[*a].order.cmp(&facts[*b].order));
for w in 0..sorted.len() {
for v in 0..w {
let (a, b) = (sorted[v], sorted[w]);
if facts[a].order.is_none() || facts[a].order != facts[b].order || facts[a].dropped
{
continue;
}
if same_member(&facts[a], &facts[b]) {
facts[b].dropped = true;
} else {
diags.push(d(
ORDER_DUPLICATE,
"two members of a tuple have the same order but differ",
facts[b].node,
));
facts[b].dropped = true;
}
}
}
sorted.retain(|k| !facts[*k].dropped);
facts[t].children = sorted;
}
let mut footnotes: Vec<(usize, Node<'_>, Footnote)> = Vec::new();
let mut footnote_by_id: HashMap<String, usize> = HashMap::new();
for (di, f) in of("footnote") {
let ix10 = f.ns() == ns::IX10;
let fid = if ix10 {
ws_attr(f, "footnoteID").or_else(|| ws_attr(f, "id"))
} else {
ws_attr(f, "id")
};
if f.lang().is_none() {
diags.push(d(
FOOTNOTE_WITHOUT_XML_LANG,
"no xml:lang is in scope for ix:footnote",
f,
));
}
let mut content = String::new();
escaped_content(f, &mut content, &html_bases[di]);
if let Some(chain) = chains.get(&key(di, f)) {
for &(cdi, c) in chain {
escaped_content(c, &mut content, &html_bases[cdi]);
}
}
let fn_ = Footnote {
id: fid.map(Atom::from),
role: Some(Atom::from(
ws_attr(f, "footnoteRole").unwrap_or(crossfoot_core::role::FOOTNOTE),
)),
lang: f.lang().map(Atom::from),
content,
node: Some(Frag {
doc: di as u32,
node: f.id,
}),
};
if let Some(id) = fid {
footnote_by_id
.entry(id.to_string())
.or_insert(footnotes.len());
}
footnotes.push((di, f, fn_));
}
let fact_by_id: HashMap<&str, usize> = facts
.iter()
.enumerate()
.filter_map(|(i, f)| ws_attr(f.node, "id").map(|id| (id, i)))
.collect();
struct Rel {
from: usize,
to: RelTo,
arcrole: Atom,
link_role: Atom,
}
#[derive(Clone, Copy, PartialEq)]
enum RelTo {
Footnote(usize),
Fact(usize),
}
let mut rels: Vec<Rel> = Vec::new();
for (_, r) in of("relationship") {
let from_refs: Vec<&str> = r.att("fromRefs").unwrap_or("").split_whitespace().collect();
let to_refs: Vec<&str> = r.att("toRefs").unwrap_or("").split_whitespace().collect();
let arcrole =
Atom::from(ws_attr(r, "arcrole").unwrap_or(crossfoot_core::arcrole::FACT_FOOTNOTE));
let link_role = Atom::from(ws_attr(r, "linkRole").unwrap_or(crossfoot_core::role::LINK));
for t in &from_refs {
if to_refs.contains(t) {
diags.push(d(
RELATIONSHIP_CROSS_DUPLICATION,
format!("'{}' appears in both fromRefs and toRefs", t),
r,
));
}
}
let mut froms = Vec::new();
for t in &from_refs {
match fact_by_id.get(t) {
Some(&i) => froms.push(i),
None => diags.push(d(
DANGLING_RELATIONSHIP_FROM_REF,
format!("fromRefs '{}' does not identify a fact", t),
r,
)),
}
}
let mut tos = Vec::new();
for t in &to_refs {
if let Some(&i) = footnote_by_id.get(*t) {
tos.push(RelTo::Footnote(i));
} else if let Some(&i) = fact_by_id.get(t) {
tos.push(RelTo::Fact(i));
} else {
diags.push(d(
DANGLING_RELATIONSHIP_TO_REF,
format!("toRefs '{}' does not identify a footnote or fact", t),
r,
));
}
}
let has_fn = tos.iter().any(|t| matches!(t, RelTo::Footnote(_)));
let has_fact = tos.iter().any(|t| matches!(t, RelTo::Fact(_)));
if has_fn && has_fact {
diags.push(d(
RELATIONSHIP_MIXED_TO_REFS,
"toRefs mixes footnotes and facts",
r,
));
}
for &f in &froms {
for &t in &tos {
rels.push(Rel {
from: f,
to: t,
arcrole: arcrole.clone(),
link_role: link_role.clone(),
});
}
}
}
for (i, f) in facts.iter().enumerate() {
if f.node.ns() != ns::IX10 {
continue;
}
if let Some(refs) = f.node.att("footnoteRefs") {
for t in refs.split_whitespace() {
match footnote_by_id.get(t) {
Some(&fi) => {
let fnode = footnotes[fi].1;
let arcrole = Atom::from(
ws_attr(fnode, "arcrole")
.unwrap_or(crossfoot_core::arcrole::FACT_FOOTNOTE),
);
let link_role = Atom::from(
ws_attr(fnode, "footnoteLinkRole")
.unwrap_or(crossfoot_core::role::LINK),
);
rels.push(Rel {
from: i,
to: RelTo::Footnote(fi),
arcrole,
link_role,
});
}
None => diags.push(d(
DANGLING_RELATIONSHIP_TO_REF,
format!("footnoteRefs '{}' does not identify a footnote", t),
f.node,
)),
}
}
}
}
let mut target_list: Vec<Option<Atom>> = vec![None];
for t in targets.keys().chain(used_targets.iter()) {
if !target_list.contains(t) {
target_list.push(t.clone());
}
}
let mut instances = Vec::new();
for target in &target_list {
let mut inst = Instance::new(
&uris[0],
InstanceSource::Inline {
documents: uris.clone(),
target: target.clone(),
},
);
inst.docs = docs.clone();
if let Some(t) = targets.get(target) {
inst.schema_refs = t.schema_refs.clone();
inst.linkbase_refs = t.linkbase_refs.clone();
}
inst.role_refs = role_refs.clone();
inst.arcrole_refs = arcrole_refs.clone();
inst.contexts = contexts.clone();
inst.units = units.clone();
let root_lang = targets.get(target).and_then(|t| t.lang.clone());
let copied: HashSet<usize> = rels
.iter()
.filter_map(|r| match r.to {
RelTo::Fact(x) if &facts[r.from].target == target && &facts[x].target != target => {
Some(x)
}
_ => None,
})
.collect();
let mut map: HashMap<usize, FactId> = HashMap::new();
for (i, f) in facts.iter().enumerate() {
if (&f.target != target && !copied.contains(&i)) || f.dropped || in_cycle[i] {
continue;
}
let Some(name) = &f.name else { continue };
let id = FactId(inst.facts.len() as u32);
map.insert(i, id);
inst.facts
.push(to_fact(f, name.clone(), &facts, root_lang.clone()));
}
for (i, f) in facts.iter().enumerate() {
let Some(&id) = map.get(&i) else { continue };
let parent = f.parent.and_then(|p| map.get(&p).copied());
inst.facts[id.0 as usize].parent = parent;
inst.facts[id.0 as usize].children = f
.children
.iter()
.filter_map(|c| map.get(c).copied())
.collect();
if parent.is_none() {
inst.top_level.push(id);
}
}
let mut fn_map: HashMap<usize, usize> = HashMap::new();
for r in &rels {
let Some(&from) = map.get(&r.from) else {
continue;
};
let to = match r.to {
RelTo::Footnote(fi) => {
let idx = *fn_map.entry(fi).or_insert_with(|| {
inst.footnotes.push(footnotes[fi].2.clone());
inst.footnotes.len() - 1
});
FootnoteTarget::Footnote(idx)
}
RelTo::Fact(t) => match map.get(&t) {
Some(&tid) => FootnoteTarget::Fact(tid),
None => continue,
},
};
inst.footnote_rels.push(FootnoteRel {
arcrole: r.arcrole.clone(),
link_role: r.link_role.clone(),
from,
to,
});
}
instances.push(inst);
}
InlineSet { instances, diags }
}
fn check_tuple_descendants(n: Node<'_>, diags: &mut Vec<Diagnostic>) {
for c in n.elements() {
if is_ix(c) {
if matches!(c.local(), "numerator" | "denominator") {
diags.push(d(
INVALID_TUPLE_CHILD,
format!("ix:{} is not allowed as tuple content", c.local()),
c,
));
}
} else {
check_tuple_descendants(c, diags);
}
}
}
fn same_member(a: &FactRec<'_>, b: &FactRec<'_>) -> bool {
if a.node.name() != b.node.name() {
return false;
}
let mut va = String::new();
let mut vb = String::new();
inner_text(a.node, &mut va, Exclude::Html);
inner_text(b.node, &mut vb, Exclude::Html);
if collapse(&va) != collapse(&vb) {
return false;
}
let attrs = |n: Node<'_>| {
let mut v: Vec<(QName, String)> = n
.attributes()
.iter()
.filter(|a| !(a.name.ns.is_empty() && matches!(&*a.name.local, "order" | "tupleRef")))
.map(|a| (a.name.clone(), collapse(&a.value)))
.collect();
v.sort_by(|x, y| x.0.cmp(&y.0));
v
};
attrs(a.node) == attrs(b.node)
}
fn to_fact(f: &FactRec<'_>, concept: QName, all: &[FactRec<'_>], root_lang: Option<Atom>) -> Fact {
let n = f.node;
let dec = |v: Option<&str>| match v {
Some("INF") => Some(Decimals::Inf),
Some(s) => s.parse().ok().map(Decimals::N),
None => None,
};
let mut lang = n.attr(ns::XML, "lang").map(Atom::from);
let mut p = f.parent;
while lang.is_none() {
let Some(pi) = p else { break };
lang = all[pi].node.attr(ns::XML, "lang").map(Atom::from);
p = all[pi].parent;
}
let lang = lang.or(root_lang);
let item = f.kind != Kind::Tuple;
Fact {
id: n.att("id").map(|s| Atom::from(xtrim(s))),
concept,
kind: if item {
FactKind::Item
} else {
FactKind::Tuple
},
context: if item {
ws_attr(n, "contextRef").map(Atom::from)
} else {
None
},
unit: if matches!(f.kind, Kind::NonFraction | Kind::Fraction) {
ws_attr(n, "unitRef").map(Atom::from)
} else {
None
},
value: if f.nil { None } else { f.value.clone() },
is_nil: f.nil,
decimals: if f.kind == Kind::NonFraction {
dec(ws_attr(n, "decimals"))
} else {
None
},
precision: if f.kind == Kind::NonFraction {
dec(ws_attr(n, "precision"))
} else {
None
},
lang: if f.kind == Kind::NonNumeric {
lang
} else {
None
},
parent: None,
children: Vec::new(),
node: Some(Frag {
doc: f.di as u32,
node: n.id,
}),
inline: Some(InlineInfo {
format: f.format.clone(),
scale: f.scale,
sign_negative: f.sign_negative,
display: f.display.clone(),
target: f.target.clone(),
element: Some(Frag {
doc: f.di as u32,
node: n.id,
}),
continued: f.continued,
}),
fraction: if f.nil { None } else { f.fraction.clone() },
}
}
fn numeric_term(
n: Node<'_>,
raw: &str,
format: &Option<QName>,
scale: Option<i32>,
negative: bool,
diags: &mut Vec<Diagnostic>,
) -> (Option<String>, bool) {
let v = match format {
Some(f) => match transform::apply(f, &collapse(raw)) {
Ok(v) => v,
Err(TransformError::UnknownFormat) => {
diags.push(d(
FORMAT_UNDEFINED,
format!("transformation format {} is not defined", f),
n,
));
return (None, true);
}
Err(TransformError::Invalid) => {
diags.push(d(
INVALID_DATA_TYPE,
format!(
"'{}' is not valid for the transformation format {}",
collapse(raw),
f
),
n,
));
return (None, true);
}
},
None => {
let t = xtrim(raw);
let ok = !t.starts_with('-')
&& (schema::is_decimal_lexical(t)
|| (t.parse::<f64>().is_ok() && t.chars().any(|c| c.is_ascii_digit())));
if !ok {
diags.push(d(
FORMAT_ABSENT_NEGATIVE_NUMBER,
format!(
"'{}' is not a non-negative number and no format is given",
t
),
n,
));
return (None, true);
}
t.to_string()
}
};
let num = Decimal::parse(&v).or_else(|| Decimal::parse_sci(&v));
match num {
Some(mut x) => {
if let Some(s) = scale {
x = x.scale_pow10(s as i64);
}
if negative {
x = x.neg();
}
if scale.is_none() && !negative {
(Some(v), false)
} else {
(Some(x.canonical()), false)
}
}
None => {
diags.push(d(INVALID_DATA_TYPE, format!("'{}' is not a number", v), n));
(Some(v), true)
}
}
}
fn parse_scale(n: Node<'_>) -> Option<i32> {
ws_attr(n, "scale").and_then(|s| s.strip_prefix('+').unwrap_or(s).parse::<i32>().ok())
}
fn build_fact<'a>(
di: usize,
n: Node<'a>,
kind: Kind,
name: Option<QName>,
chains: &HashMap<Key, Vec<(usize, Node<'a>)>>,
ectx: &EscapeCtx,
diags: &mut Vec<Diagnostic>,
) -> FactRec<'a> {
let nil = is_nil(n);
let format = n.att("format").and_then(|f| schema::resolve_format(n, f));
let scale = parse_scale(n);
let sign_negative = n.att("sign") == Some("-");
let mut rec = FactRec {
di,
node: n,
kind,
name,
target: ws_attr(n, "target").map(Atom::from),
nil,
value: None,
fraction: None,
display: String::new(),
format: format.clone(),
scale,
sign_negative,
continued: false,
invalid: false,
parent: None,
order: None,
dropped: false,
children: Vec::new(),
};
match kind {
Kind::NonFraction => {
let has_decimals = n.att("decimals").is_some();
let has_precision = n.att("precision").is_some();
if nil {
if has_decimals || has_precision {
diags.push(d(
PRECISION_AND_DECIMALS_PRESENT,
"a nil ix:nonFraction must not have decimals or precision",
n,
));
}
} else if has_decimals && has_precision {
diags.push(d(
PRECISION_AND_DECIMALS_PRESENT,
"ix:nonFraction has both decimals and precision",
n,
));
} else if !has_decimals && !has_precision {
diags.push(d(
PRECISION_AND_DECIMALS_ABSENT,
"ix:nonFraction has neither decimals nor precision",
n,
));
}
let child = n.elements().find(|c| is_ix_named(*c, "nonFraction"));
if let Some(c) = child {
if n.children().any(|x| x.is_text()) {
diags.push(d(
NON_FRACTION_CHILD_ELEMENT_MIXED,
"ix:nonFraction must not have both text and a nested ix:nonFraction",
n,
));
}
if is_nil(c) != nil {
diags.push(d(
NON_FRACTION_NESTED_NIL_MISMATCH,
"nested ix:nonFraction elements must agree on xsi:nil",
c,
));
} else {
let fmt = |e: Node<'_>| {
e.att("format").map(|f| {
schema::resolve_format(e, f)
.map(|q| q.clark())
.unwrap_or_else(|| xtrim(f).to_string())
})
};
let scl = |e: Node<'_>| {
e.att("scale").map(|s| {
parse_scale(e)
.map(|v| v.to_string())
.unwrap_or_else(|| xtrim(s).to_string())
})
};
for a in ["format", "scale", "unitRef"] {
let same = match a {
"format" => fmt(n) == fmt(c),
"scale" => scl(n) == scl(c),
_ => n.att(a).map(xtrim) == c.att(a).map(xtrim),
};
if !same {
diags.push(d(
NON_FRACTION_NESTED_ATTRIBUTE_MISMATCH,
format!("nested ix:nonFraction elements must have the same {}", a),
c,
));
break;
}
}
}
}
if nil {
if let Some(f) = &format {
let _ = numeric_term(n, "", &Some(f.clone()), None, false, diags);
}
return rec;
}
let mut raw = String::new();
inner_text(n, &mut raw, Exclude::Html);
rec.display = raw.clone();
if n.first_child().is_none()
|| (format.is_none() && xtrim(&raw).is_empty() && child.is_none())
{
diags.push(d(
NON_FRACTION_INCOMPLETE_CONTENT,
"ix:nonFraction must have content or be nil",
n,
));
rec.invalid = true;
rec.value = Some(String::new());
return rec;
}
let (v, bad) = numeric_term(n, &raw, &format, scale, sign_negative, diags);
rec.invalid = bad;
rec.value = Some(v.unwrap_or_else(|| xtrim(&raw).to_string()));
}
Kind::NonNumeric => {
let escape = matches!(n.att("escape").map(xtrim), Some("true") | Some("1"));
let mut text = String::new();
let mut display = String::new();
if escape {
escaped_content(n, &mut text, ectx);
} else {
inner_text(n, &mut text, Exclude::Html);
}
inner_text(n, &mut display, Exclude::Html);
if let Some(chain) = chains.get(&key(di, n)) {
rec.continued = !chain.is_empty();
for &(_, c) in chain {
if escape {
escaped_content(c, &mut text, ectx);
} else {
inner_text(c, &mut text, Exclude::Html);
}
inner_text(c, &mut display, Exclude::Html);
}
}
rec.display = display;
let v = match &format {
Some(f) => {
let input = if nil { String::new() } else { collapse(&text) };
match transform::apply(f, &input) {
Ok(v) => v,
Err(TransformError::UnknownFormat) => {
diags.push(d(
FORMAT_UNDEFINED,
format!("transformation format {} is not defined", f),
n,
));
rec.invalid = true;
text
}
Err(TransformError::Invalid) => {
diags.push(d(
INVALID_DATA_TYPE,
format!(
"'{}' is not valid for the transformation format {}",
input, f
),
n,
));
rec.invalid = true;
text
}
}
}
None => text,
};
if !nil {
rec.value = Some(v);
}
}
Kind::Fraction => {
let mut nums: Vec<Node<'_>> = Vec::new();
let mut dens: Vec<Node<'_>> = Vec::new();
let mut nested: Vec<Node<'_>> = Vec::new();
collect_fraction_terms(n, &mut nums, &mut dens, &mut nested);
for c in &nested {
if is_nil(*c) != nil {
diags.push(d(
FRACTION_NESTED_NIL_MISMATCH,
"nested ix:fraction elements must agree on xsi:nil",
*c,
));
}
let attrs = |e: Node<'_>| {
let mut v: Vec<(QName, String)> = e
.attributes()
.iter()
.filter(|a| {
!a.name.ns.is_empty() && a.name.ns.as_ref() != ns::XSI
|| (a.name.ns.is_empty() && &*a.name.local == "unitRef")
})
.map(|a| (a.name.clone(), xtrim(&a.value).to_string()))
.collect();
v.sort_by(|x, y| x.0.cmp(&y.0));
v
};
if attrs(*c) != attrs(n) {
diags.push(d(FRACTION_NESTED_ATTRIBUTE_MISMATCH, "nested ix:fraction elements must have the same unitRef and foreign attributes", *c));
}
}
if nil {
if !nums.is_empty() || !dens.is_empty() {
diags.push(d(
INCOMPLETE_FRACTION,
"a nil ix:fraction must not have a numerator or denominator",
n,
));
}
return rec;
}
for (terms, what) in [(&nums, "numerator"), (&dens, "denominator")] {
if terms.is_empty() {
diags.push(d(
INCOMPLETE_FRACTION,
format!("ix:fraction has no ix:{}", what),
n,
));
} else if terms.len() > 1 {
diags.push(d(
MULTIPLE_NUMERATOR_DENOMINATOR,
format!("ix:fraction has more than one ix:{}", what),
n,
));
}
}
if nums.len() == 1 && dens.len() == 1 {
let term = |t: Node<'_>, diags: &mut Vec<Diagnostic>| -> Option<String> {
let f = t.att("format").and_then(|f| schema::resolve_format(t, f));
let raw = t.string_value();
numeric_term(
t,
&raw,
&f,
parse_scale(t),
t.att("sign") == Some("-"),
diags,
)
.0
};
let a = term(nums[0], diags);
let b = term(dens[0], diags);
rec.display = format!(
"{}/{}",
nums[0].string_value().trim(),
dens[0].string_value().trim()
);
match (a, b) {
(Some(a), Some(b)) => {
rec.value = Some(format!("{}/{}", a, b));
rec.fraction = Some((a, b));
}
_ => {
rec.invalid = true;
rec.value = Some("NaN".into());
}
}
} else {
rec.invalid = true;
}
}
Kind::Tuple => {}
}
rec
}
fn collect_fraction_terms<'a>(
n: Node<'a>,
nums: &mut Vec<Node<'a>>,
dens: &mut Vec<Node<'a>>,
nested: &mut Vec<Node<'a>>,
) {
for c in n.elements() {
if is_ix(c) {
match c.local() {
"numerator" => nums.push(c),
"denominator" => dens.push(c),
"fraction" => {
nested.push(c);
collect_fraction_terms(c, nums, dens, nested);
}
_ => {}
}
} else {
collect_fraction_terms(c, nums, dens, nested);
}
}
}
#[cfg(test)]
#[path = "extract_tests.rs"]
mod tests;