crossfoot-inline 0.3.0

Inline XBRL 1.1 document sets and the transformation registry (Crossfoot)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! Schema-level validity of Inline XBRL documents: the content models and attribute
//! declarations of the ix 1.0/1.1 schemas (`xhtml-inlinexbrl-1_1-definitions.xsd`) and the
//! few XHTML 1.1 rules that inline documents commonly break. Codes follow the Xerces
//! constraint names the conformance suite uses (`cvc-complex-type.2.4.a` → `..._2_4_a`).
//!
//! This is a hand-written validator for the ix vocabulary, not a general XSD engine: the
//! XHTML content models are checked only where the ix schemas constrain them.

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
}

/// Attribute value types used by the ix schemas.
#[derive(Copy, Clone, PartialEq)]
enum AttrType {
    String,
    NcName,
    IdRefs,
    QName,
    Decimal,
    Integer,
    Boolean,
    Sign,
    AnyUri,
    DecimalsType,
    PrecisionType,
}

/// Which foreign (namespaced) attributes an element accepts.
#[derive(Copy, Clone, PartialEq)]
enum Foreign {
    /// None at all (only xsi:*).
    None,
    /// Only `xml:*`.
    Xml,
    /// Any namespace other than the ix namespace (`##other`).
    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())
}

/// Elements that belong to the `xbrl.ix.base.class` group (allowed in ix:hidden).
fn is_base_class(local: &str) -> bool {
    matches!(
        local,
        "footnote" | "fraction" | "nonFraction" | "nonNumeric" | "tuple"
    )
}

/// Elements of `xbrl.ix.inline.class`, which the ix modules add to the XHTML Flow/Inline mix.
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)
    }
}

/// Check one document of the set.
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;
        }
        // attributes in the ix namespace are never allowed (no anyAttribute admits them)
        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);
            }
        }
    }
}

/// `xbrli:context` content model (XBRL 2.1 schema): `entity` (`identifier`, `segment?`),
/// `period`, `scenario?`, in that order and nothing else. Contexts in an XML instance are
/// schema-validated by the XSD layer; contexts inside `ix:resources` are checked here.
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;
    };
    // attributes
    for a in n.attributes() {
        let ans: &str = &a.name.ns;
        if is_ix_ns(ans) {
            continue; // reported above
        }
        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,
            ));
        }
    }
    // a nil element must be empty (cvc-elt.3.2.1)
    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,
        ));
    }
    // placement: what may contain this element
    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, // checked by the parent's content model
            Some(p) if p.ns() == ns::XHTML => flow_context(p),
            Some(_) => true, // inside foreign XML: reported as MisplacedIXElement by the spec rules
        },
    };
    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,
        ));
    }
    // content models
    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,
                    ));
                }
            }
        }
        _ => {}
    }
}

/// Text content where the content model is element-only.
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;
        }
    }
}

/// Can an element appear in XHTML Flow content (inside ix elements with Flow content)?
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"
        )
}

/// Is this XHTML element one whose content admits the ix inline class?
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>) {
    // sequence: hidden?, references*, resources?
    let mut state = 0u8; // 0 = start, 1 = after hidden, 2 = in references, 3 = after resources
    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;
        // no-namespace attributes the XHTML 1.1 schema does not declare for this element
        // (`<span x-id>`, `<td width>`, `<html lang>`); Arelle reports these through lxml
        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,
            ));
        }
    }
    // XHTML 1.1 elements declared EMPTY: any content, even whitespace, is invalid
    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,
        ));
    }
    // element-only XHTML 1.1 content models that filings break: lists hold only list items
    // and table rows only cells (`<ol><ol>` seen in an ESEF filing; Arelle reports
    // lxml SCHEMAV_ELEMENT_CONTENT)
    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,
            ));
        }
    }
    // (`a name` and `meta charset` are covered by the attribute table above)
    if n.local() == "meta" && n.att("content").is_none() {
        diags.push(err(
            CVC_4,
            "meta is missing the required attribute content".into(),
            n,
        ));
    }
}

/// A QName attribute value (`format`) resolved with the in-scope namespaces.
/// A prefix that is not in scope yields a QName in no registry namespace, so the format is
/// reported as undefined rather than silently ignored.
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,
        ))
    })
}