use crossfoot_core::xml::{is_ncname, Node};
use crossfoot_core::{ns, Diagnostic, Document, QName};
pub(crate) const CVC_2_1: &str = "xbrl.core.xml.SchemaValidationError.cvc-complex-type_2_1";
pub(crate) const CVC_2_2: &str = "xbrl.core.xml.SchemaValidationError.cvc-complex-type_2_2";
pub(crate) const CVC_2_4_A: &str = "xbrl.core.xml.SchemaValidationError.cvc-complex-type_2_4_a";
pub(crate) const CVC_2_4_B: &str = "xbrl.core.xml.SchemaValidationError.cvc-complex-type_2_4_b";
pub(crate) const CVC_2_4_D: &str = "xbrl.core.xml.SchemaValidationError.cvc-complex-type_2_4_d";
pub(crate) const CVC_3_2_2: &str = "xbrl.core.xml.SchemaValidationError.cvc-complex-type_3_2_2";
pub(crate) const CVC_4: &str = "xbrl.core.xml.SchemaValidationError.cvc-complex-type_4";
pub(crate) const CVC_ATTRIBUTE_3: &str = "xbrl.core.xml.SchemaValidationError.cvc-attribute_3";
pub(crate) const CVC_PATTERN: &str = "xbrl.core.xml.SchemaValidationError.cvc-pattern-valid";
pub(crate) const CVC_DATATYPE: &str =
"xbrl.core.xml.SchemaValidationError.cvc-datatype-valid_1_2_1";
pub(crate) const CVC_MINLENGTH: &str = "xbrl.core.xml.SchemaValidationError.cvc-minLength-valid";
pub(crate) const CVC_ELT_1: &str = "xbrl.core.xml.SchemaValidationError.cvc-elt_1";
pub(crate) const CVC_ELT_3_2_1: &str = "xbrl.core.xml.SchemaValidationError.cvc-elt_3_2_1";
pub(crate) fn is_ix_ns(s: &str) -> bool {
s == ns::IX11 || s == ns::IX10
}
pub(crate) fn is_ix(n: Node<'_>) -> bool {
n.is_element() && is_ix_ns(n.ns())
}
pub(crate) fn is_ix_named(n: Node<'_>, local: &str) -> bool {
is_ix(n) && n.local() == local
}
#[derive(Copy, Clone, PartialEq)]
enum AttrType {
String,
NcName,
IdRefs,
QName,
Decimal,
Integer,
Boolean,
Sign,
AnyUri,
DecimalsType,
PrecisionType,
}
#[derive(Copy, Clone, PartialEq)]
enum Foreign {
None,
Xml,
Other,
}
struct ElementDecl {
attrs: &'static [(&'static str, AttrType, bool)],
foreign: Foreign,
}
const TUPLESHARED: &[(&str, AttrType, bool)] = &[
("id", AttrType::NcName, false),
("name", AttrType::QName, true),
("order", AttrType::Decimal, false),
("target", AttrType::NcName, false),
("tupleRef", AttrType::NcName, false),
];
fn decl(local: &str, ix10: bool) -> Option<ElementDecl> {
use AttrType::*;
let d = match local {
"header" | "hidden" | "resources" | "exclude" => ElementDecl {
attrs: &[],
foreign: Foreign::None,
},
"references" => ElementDecl {
attrs: &[("id", NcName, false), ("target", NcName, false)],
foreign: Foreign::Other,
},
"relationship" => ElementDecl {
attrs: &[
("arcrole", AnyUri, false),
("fromRefs", IdRefs, true),
("linkRole", AnyUri, false),
("order", Decimal, false),
("toRefs", IdRefs, true),
],
foreign: Foreign::Xml,
},
"footnote" if ix10 => ElementDecl {
attrs: &[
("arcrole", AnyUri, false),
("footnoteID", NcName, true),
("footnoteLinkRole", AnyUri, false),
("footnoteRole", AnyUri, false),
("title", String, false),
("id", NcName, false),
],
foreign: Foreign::Xml,
},
"footnote" => ElementDecl {
attrs: &[
("continuedAt", NcName, false),
("footnoteRole", AnyUri, false),
("id", NcName, true),
("title", String, false),
],
foreign: Foreign::Xml,
},
"continuation" => ElementDecl {
attrs: &[("continuedAt", NcName, false), ("id", NcName, true)],
foreign: Foreign::None,
},
"numerator" | "denominator" => ElementDecl {
attrs: &[
("format", QName, false),
("scale", Integer, false),
("sign", Sign, false),
],
foreign: Foreign::None,
},
"fraction" => ElementDecl {
attrs: &[
("contextRef", NcName, true),
("unitRef", NcName, true),
("footnoteRefs", IdRefs, false),
],
foreign: Foreign::Other,
},
"nonFraction" => ElementDecl {
attrs: &[
("contextRef", NcName, true),
("unitRef", NcName, true),
("format", QName, false),
("scale", Integer, false),
("sign", Sign, false),
("decimals", DecimalsType, false),
("precision", PrecisionType, false),
("footnoteRefs", IdRefs, false),
],
foreign: Foreign::Other,
},
"nonNumeric" => ElementDecl {
attrs: &[
("contextRef", NcName, true),
("continuedAt", NcName, false),
("escape", Boolean, false),
("format", QName, false),
("footnoteRefs", IdRefs, false),
],
foreign: Foreign::Other,
},
"tuple" => ElementDecl {
attrs: &[("tupleID", NcName, false), ("footnoteRefs", IdRefs, false)],
foreign: Foreign::Other,
},
_ => return None,
};
Some(d)
}
fn uses_tupleshared(local: &str) -> bool {
matches!(local, "fraction" | "nonFraction" | "nonNumeric" | "tuple")
}
fn type_ok(t: AttrType, v: &str, n: Node<'_>) -> Result<(), &'static str> {
let c = v.trim_matches(|c: char| c == ' ' || c == '\t' || c == '\n' || c == '\r');
let ok = match t {
AttrType::String | AttrType::AnyUri => true,
AttrType::NcName => is_ncname(c),
AttrType::IdRefs => {
let toks: Vec<&str> = c.split_whitespace().collect();
if toks.is_empty() {
return Err(CVC_MINLENGTH);
}
toks.iter().all(|t| is_ncname(t))
}
AttrType::QName => {
n.resolve_qname(c, true).is_some()
|| c.split_once(':')
.map(|(p, l)| is_ncname(p) && is_ncname(l))
.unwrap_or(false)
}
AttrType::Decimal => is_decimal_lexical(c),
AttrType::Integer => is_integer_lexical(c),
AttrType::Boolean => matches!(c, "true" | "false" | "1" | "0"),
AttrType::Sign => {
if v == "-" {
true
} else {
return Err(CVC_PATTERN);
}
}
AttrType::DecimalsType => c == "INF" || is_integer_lexical(c),
AttrType::PrecisionType => c == "INF" || (is_integer_lexical(c) && !c.starts_with('-')),
};
if ok {
Ok(())
} else {
Err(CVC_DATATYPE)
}
}
pub(crate) fn is_decimal_lexical(s: &str) -> bool {
let s = s.strip_prefix(['+', '-']).unwrap_or(s);
if s.is_empty() {
return false;
}
let (a, b) = match s.split_once('.') {
Some((a, b)) => (a, Some(b)),
None => (s, None),
};
if !a.chars().all(|c| c.is_ascii_digit()) {
return false;
}
match b {
Some(b) => b.chars().all(|c| c.is_ascii_digit()) && !(a.is_empty() && b.is_empty()),
None => !a.is_empty(),
}
}
pub(crate) fn is_integer_lexical(s: &str) -> bool {
let s = s.strip_prefix(['+', '-']).unwrap_or(s);
!s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
}
fn is_base_class(local: &str) -> bool {
matches!(
local,
"footnote" | "fraction" | "nonFraction" | "nonNumeric" | "tuple"
)
}
fn is_inline_class(local: &str) -> bool {
is_base_class(local)
|| matches!(
local,
"continuation" | "denominator" | "exclude" | "header" | "numerator"
)
}
fn err(code: &str, msg: String, n: Node<'_>) -> Diagnostic {
Diagnostic::error(code, msg).at(n)
}
fn name_of(n: Node<'_>) -> String {
let q = n.name();
if q.prefix.is_empty() {
q.local.to_string()
} else {
format!("{}:{}", q.prefix, q.local)
}
}
pub(crate) fn check_document(doc: &Document, diags: &mut Vec<Diagnostic>) {
let Some(root) = doc.document_element() else {
return;
};
for n in root.descendants_or_self() {
if !n.is_element() {
continue;
}
for a in n.attributes() {
if is_ix_ns(&a.name.ns) {
diags.push(err(
CVC_3_2_2,
format!("attribute {} is not allowed on {}", a.name, name_of(n)),
n,
));
}
}
if is_ix(n) {
check_ix_element(n, diags);
} else if n.ns() == ns::XHTML {
check_xhtml_element(n, diags);
} else if (n.is(ns::XBRLI, "context") || n.is(ns::XBRLI, "unit"))
&& n.parent_element()
.map(|p| is_ix_named(p, "resources"))
.unwrap_or(false)
{
if n.att("id").is_none() {
diags.push(err(CVC_4, format!("{} has no id attribute", name_of(n)), n));
}
if n.is(ns::XBRLI, "context") {
check_context_content(n, diags);
}
}
}
}
fn check_context_content(n: Node<'_>, diags: &mut Vec<Diagnostic>) {
let expect = |parent: Node<'_>, seq: &[(&str, bool)], diags: &mut Vec<Diagnostic>| {
let mut i = 0;
for c in parent.elements() {
if i < seq.len() && !c.is(ns::XBRLI, seq[i].0) && !seq[i].1 {
diags.push(err(
CVC_2_4_A,
format!(
"{} is not expected in {}; {} is expected",
name_of(c),
name_of(parent),
seq[i].0
),
c,
));
return;
}
while i < seq.len() && !c.is(ns::XBRLI, seq[i].0) {
i += 1;
}
if i == seq.len() {
diags.push(err(
CVC_2_4_A,
format!("{} is not expected in {}", name_of(c), name_of(parent)),
c,
));
return;
}
i += 1;
}
};
expect(
n,
&[("entity", false), ("period", false), ("scenario", true)],
diags,
);
if let Some(entity) = n.elements().find(|c| c.is(ns::XBRLI, "entity")) {
expect(entity, &[("identifier", false), ("segment", true)], diags);
}
}
fn check_ix_element(n: Node<'_>, diags: &mut Vec<Diagnostic>) {
let local = n.local();
let ix10 = n.ns() == ns::IX10;
let Some(d) = decl(local, ix10) else {
diags.push(err(
CVC_ELT_1,
format!("ix:{} is not an Inline XBRL element", local),
n,
));
return;
};
for a in n.attributes() {
let ans: &str = &a.name.ns;
if is_ix_ns(ans) {
continue; }
if ans.is_empty() {
let decl_ty = d
.attrs
.iter()
.find(|(l, _, _)| *l == &*a.name.local && (ix10 || *l != "footnoteRefs"))
.map(|(_, t, _)| *t)
.or_else(|| {
if uses_tupleshared(local) {
TUPLESHARED
.iter()
.find(|(l, _, _)| *l == &*a.name.local)
.map(|(_, t, _)| *t)
} else {
None
}
});
match decl_ty {
None => diags.push(err(
CVC_3_2_2,
format!("attribute {} is not allowed on ix:{}", a.name.local, local),
n,
)),
Some(t) => {
if let Err(code) = type_ok(t, &a.value, n) {
diags.push(err(
code,
format!(
"ix:{} @{} value '{}' is not valid",
local, a.name.local, a.value
),
n,
));
diags.push(err(
CVC_ATTRIBUTE_3,
format!(
"ix:{} @{} value '{}' is not valid",
local, a.name.local, a.value
),
n,
));
}
}
}
continue;
}
if ans == ns::XSI {
continue;
}
let allowed = match d.foreign {
Foreign::None => false,
Foreign::Xml => ans == ns::XML,
Foreign::Other => true,
};
if !allowed {
diags.push(err(
CVC_3_2_2,
format!("attribute {} is not allowed on ix:{}", a.name, local),
n,
));
}
}
let mut required: Vec<&str> = d
.attrs
.iter()
.filter(|(_, _, r)| *r)
.map(|(l, _, _)| *l)
.collect();
if uses_tupleshared(local) {
required.push("name");
}
for r in required {
if n.att(r).is_none() {
diags.push(err(
CVC_4,
format!("ix:{} is missing the required attribute {}", local, r),
n,
));
}
}
if is_base_class(local)
&& matches!(
n.attr(ns::XSI, "nil").map(str::trim),
Some("true") | Some("1")
)
&& n.children()
.any(|c| c.is_element() || (c.is_text() && !c.text().unwrap_or("").trim().is_empty()))
{
diags.push(err(
CVC_ELT_3_2_1,
format!("nil ix:{} must be empty", local),
n,
));
}
let parent = n.parent_element();
let placement_ok = match local {
"hidden" | "references" | "resources" => {
parent.map(|p| is_ix_named(p, "header")).unwrap_or(false)
}
"relationship" => parent.map(|p| is_ix_named(p, "resources")).unwrap_or(false),
_ => match parent {
None => false,
Some(p) if is_ix(p) => true, Some(p) if p.ns() == ns::XHTML => flow_context(p),
Some(_) => true, },
};
if !placement_ok && !parent.map(is_ix).unwrap_or(false) {
diags.push(err(
CVC_2_4_A,
format!(
"ix:{} is not allowed inside {}",
local,
parent.map(name_of).unwrap_or_default()
),
n,
));
}
match local {
"header" => check_header_content(n, diags),
"hidden" => {
let mut any = false;
for c in n.elements() {
any = true;
if !(is_ix(c) && is_base_class(c.local())) {
diags.push(err(
CVC_2_4_A,
format!("{} is not allowed in ix:hidden", name_of(c)),
c,
));
}
}
if !any {
diags.push(err(
CVC_2_4_B,
"ix:hidden must contain at least one fact or footnote".into(),
n,
));
}
no_text(n, diags);
}
"references" => {
let mut any = false;
for c in n.elements() {
any = true;
if !(c.is(ns::LINK, "schemaRef") || c.is(ns::LINK, "linkbaseRef")) {
diags.push(err(
CVC_2_4_A,
format!("{} is not allowed in ix:references", name_of(c)),
c,
));
}
}
if !any {
diags.push(err(
CVC_2_4_B,
"ix:references must contain a link:schemaRef or link:linkbaseRef".into(),
n,
));
}
no_text(n, diags);
}
"resources" => {
for c in n.elements() {
let ok = is_ix_named(c, "relationship")
|| c.is(ns::LINK, "roleRef")
|| c.is(ns::LINK, "arcroleRef")
|| c.is(ns::XBRLI, "context")
|| c.is(ns::XBRLI, "unit");
if !ok {
diags.push(err(
CVC_2_4_A,
format!("{} is not allowed in ix:resources", name_of(c)),
c,
));
}
}
no_text(n, diags);
}
"relationship" => {
if let Some(c) = n.elements().next() {
diags.push(err(CVC_2_4_D, "ix:relationship must be empty".into(), c));
}
}
"numerator" | "denominator" => {
let mut has_el = false;
for c in n.elements() {
has_el = true;
diags.push(err(
CVC_2_2,
format!("ix:{} must contain only text, found {}", local, name_of(c)),
c,
));
}
let text = n.string_value();
if text.is_empty() || has_el {
diags.push(err(
CVC_MINLENGTH,
format!("ix:{} must not be empty", local),
n,
));
if !has_el {
diags.push(err(CVC_2_2, format!("ix:{} must not be empty", local), n));
}
}
}
"nonFraction" => {
let kids: Vec<Node<'_>> = n.elements().collect();
let mut seen_nf = false;
for c in &kids {
if is_ix_named(*c, "nonFraction") {
if seen_nf {
diags.push(err(
CVC_2_4_D,
"ix:nonFraction may contain at most one nested ix:nonFraction".into(),
*c,
));
}
seen_nf = true;
} else {
diags.push(err(
CVC_2_4_A,
format!("{} is not allowed in ix:nonFraction", name_of(*c)),
*c,
));
}
}
}
"footnote" | "nonNumeric" | "continuation" | "exclude" | "tuple" | "fraction" => {
for c in n.elements() {
if !flow_child_ok(c) {
diags.push(err(
CVC_2_4_A,
format!("{} is not allowed in ix:{}", name_of(c), local),
c,
));
}
}
}
_ => {}
}
}
fn no_text(n: Node<'_>, diags: &mut Vec<Diagnostic>) {
for c in n.children() {
if c.is_text() && !c.text().unwrap_or("").trim().is_empty() {
diags.push(err(
CVC_2_2,
format!("text is not allowed in {}", name_of(n)),
n,
));
return;
}
}
}
fn flow_child_ok(c: Node<'_>) -> bool {
if is_ix(c) {
return is_inline_class(c.local());
}
c.ns() == ns::XHTML
&& !matches!(
c.local(),
"html"
| "head"
| "body"
| "title"
| "meta"
| "link"
| "base"
| "style"
| "li"
| "tr"
| "td"
| "th"
| "dt"
| "dd"
| "thead"
| "tbody"
| "tfoot"
| "col"
| "colgroup"
| "caption"
| "option"
| "optgroup"
| "legend"
| "param"
| "area"
)
}
fn flow_context(p: Node<'_>) -> bool {
!matches!(
p.local(),
"html"
| "head"
| "title"
| "meta"
| "link"
| "base"
| "style"
| "script"
| "table"
| "thead"
| "tbody"
| "tfoot"
| "tr"
| "colgroup"
| "col"
| "ul"
| "ol"
| "dl"
| "select"
| "optgroup"
| "option"
| "param"
| "area"
| "map"
| "br"
| "hr"
| "img"
| "input"
)
}
fn check_header_content(n: Node<'_>, diags: &mut Vec<Diagnostic>) {
let mut state = 0u8; for c in n.elements() {
let local = if is_ix(c) { c.local() } else { "" };
let next = match (state, local) {
(0, "hidden") => Some(1),
(0..=2, "references") => Some(2),
(0..=2, "resources") => Some(3),
_ => None,
};
match next {
Some(s) => state = s,
None => {
let code = if state == 3 { CVC_2_4_D } else { CVC_2_4_A };
diags.push(err(
code,
format!("{} is not expected here in ix:header", name_of(c)),
c,
));
}
}
}
no_text(n, diags);
}
fn check_xhtml_element(n: Node<'_>, diags: &mut Vec<Diagnostic>) {
let allowed = crate::xhtml_attrs::allowed(n.local());
for a in n.attributes() {
let ans: &str = &a.name.ns;
if let Some(list) = allowed {
if ans.is_empty() && !list.contains(&&*a.name.local) {
diags.push(err(
CVC_3_2_2,
format!(
"attribute {} is not allowed on {} in XHTML 1.1",
a.name.local,
name_of(n)
),
n,
));
}
}
if ans == ns::XML && !matches!(&*a.name.local, "lang" | "space") {
diags.push(err(
CVC_3_2_2,
format!(
"attribute xml:{} is not allowed on {}",
a.name.local,
name_of(n)
),
n,
));
}
if ans.is_empty() && &*a.name.local == "class" && a.value.trim().is_empty() {
diags.push(err(
CVC_MINLENGTH,
format!("empty class attribute on {}", name_of(n)),
n,
));
diags.push(err(
CVC_ATTRIBUTE_3,
format!("empty class attribute on {}", name_of(n)),
n,
));
}
}
if matches!(
n.local(),
"br" | "hr" | "img" | "meta" | "link" | "input" | "col" | "area" | "base" | "param"
) && n.first_child().is_some()
{
diags.push(err(
CVC_2_1,
format!("{} must be empty (its content type is empty)", name_of(n)),
n,
));
}
let only: &[&str] = match n.local() {
"ol" | "ul" => &["li"],
"dl" => &["dt", "dd"],
"tr" => &["th", "td"],
_ => &[],
};
if !only.is_empty() {
let mut any = false;
for c in n.elements() {
any = true;
if !(c.ns() == ns::XHTML && only.contains(&c.local())) {
diags.push(err(
CVC_2_4_A,
format!(
"{} is not expected in {}; expected {}",
name_of(c),
name_of(n),
only.join(" or ")
),
c,
));
break;
}
}
if !any {
diags.push(err(
CVC_2_4_B,
format!(
"{} is incomplete: it needs at least one {}",
name_of(n),
only.join(" or ")
),
n,
));
}
}
if n.local() == "meta" && n.att("content").is_none() {
diags.push(err(
CVC_4,
"meta is missing the required attribute content".into(),
n,
));
}
}
pub(crate) fn resolve_format(n: Node<'_>, v: &str) -> Option<QName> {
let v = v.trim();
if v.is_empty() {
return None;
}
n.resolve_qname(v, true).or_else(|| {
let (p, l) = v.split_once(':').unwrap_or(("", v));
Some(QName::with_prefix(
&format!("urn:crossfoot:unbound-prefix:{}", p),
l,
p,
))
})
}