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
//! [COLLADA] parser.
//!
//! [COLLADA]: https://en.wikipedia.org/wiki/COLLADA

mod geometry;
mod instance;
mod iter;

use std::{cmp, collections::HashMap, fmt, io, marker::PhantomData, ops, str, str::FromStr};

use indexmap::IndexMap;

use self::geometry::*;
use crate::{
    float, int,
    xml::{self, XmlNodeExt},
    Scene,
};

/// Parses meshes from bytes of COLLADA text.
pub fn from_slice(bytes: &[u8]) -> io::Result<Scene> {
    from_str(str::from_utf8(bytes).map_err(crate::error::invalid_data)?)
}

/// Parses meshes from a string of COLLADA text.
pub fn from_str(s: &str) -> io::Result<Scene> {
    let xml = xml::Document::parse(s).map_err(crate::error::invalid_data)?;
    let collada = Document::parse(&xml)?;
    Ok(Scene {
        meshes: instance::build_meshes(&collada),
    })
}

// Inspired by gltf-json's `Get` trait.
/// Helper trait for retrieving top-level objects by a universal identifier.
pub(crate) trait Get<T> {
    type Target;

    fn get(&self, uri: &T) -> Option<&Self::Target>;
}

macro_rules! impl_get_by_uri {
    ($ty:ty, $($field:ident).*) => {
        impl Get<Uri<$ty>> for Document {
            type Target = $ty;

            fn get(&self, index: &Uri<$ty>) -> Option<&Self::Target> {
                self.$($field).*.get(&index.0)
            }
        }
    };
}

impl_get_by_uri!(Accessor, library_geometries.accessors);
impl_get_by_uri!(ArrayData, library_geometries.array_data);
impl_get_by_uri!(Geometry, library_geometries.geometries);

#[derive(Debug)]
pub(crate) struct Uri<T>(String, PhantomData<fn() -> T>);

impl<T> Uri<T> {
    pub(crate) fn parse(url: &str) -> io::Result<Self> {
        // skipping the leading #, hopefully the remaining text is the accessor ID only
        if let Some(url) = url.strip_prefix('#') {
            Ok(Self(url.to_owned(), PhantomData))
        } else {
            Err(format_err!("unknown reference format {:?}", url))
        }
    }

    pub(crate) fn cast<U>(self) -> Uri<U> {
        Uri(self.0, PhantomData)
    }

    #[allow(dead_code)] // TODO(material)
    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }
}

impl<T> PartialEq for Uri<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> Eq for Uri<T> {}

impl<T, S> PartialEq<S> for Uri<T>
where
    S: ?Sized + AsRef<str>,
{
    fn eq(&self, other: &S) -> bool {
        self.0 == other.as_ref()
    }
}

impl<T> PartialEq<Uri<T>> for str {
    fn eq(&self, other: &Uri<T>) -> bool {
        self == other.0
    }
}

impl<T> PartialEq<Uri<T>> for String {
    fn eq(&self, other: &Uri<T>) -> bool {
        *self == other.0
    }
}

pub(crate) trait ColladaXmlNodeExt<'a, 'input> {
    fn parse_url<T>(&self, name: &str) -> io::Result<Uri<T>>;
    fn parse_url_opt<T>(&self, name: &str) -> io::Result<Option<Uri<T>>>;
}

impl<'a, 'input> ColladaXmlNodeExt<'a, 'input> for xml::Node<'a, 'input> {
    fn parse_url<T>(&self, name: &str) -> io::Result<Uri<T>> {
        let url = self.required_attribute(name)?;
        Uri::parse(url).map_err(|e| {
            format_err!(
                "{} in {} attribute of <{}> element at {}",
                e,
                name,
                self.tag_name().name(),
                self.attr_value_location(name),
            )
        })
    }

    fn parse_url_opt<T>(&self, name: &str) -> io::Result<Option<Uri<T>>> {
        if let Some(url) = self.attribute(name) {
            Uri::parse(url).map(Some).map_err(|e| {
                format_err!(
                    "{} in {} attribute of <{}> element at {}",
                    e,
                    name,
                    self.tag_name().name(),
                    self.attr_value_location(name),
                )
            })
        } else {
            Ok(None)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Version {
    pub(crate) minor: u32,
    pub(crate) patch: u32,
}

impl Version {
    pub(crate) const MIN: Self = Self { minor: 4, patch: 0 };
}

impl FromStr for Version {
    type Err = io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        (|| {
            let mut digits = s.splitn(3, '.');
            let major = digits.next()?;
            if major != "1" {
                return None;
            }
            let minor = digits.next()?.parse().ok()?;
            let patch = digits.next()?.parse().ok()?;
            Some(Self { minor, patch })
        })()
        .ok_or_else(|| format_err!("unrecognized version format {:?}", s))
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "1.{}.{}", self.minor, self.patch)
    }
}

pub(crate) struct Context {
    pub(crate) library_geometries: LibraryGeometries,
}

#[derive(Debug)]
pub(crate) struct Document {
    pub(crate) library_geometries: LibraryGeometries,
}

impl Document {
    /*
    The `<COLLADA>` element

    Attributes:
    - `version` (Required)
    - `xmlns` (xs:anyURI)
    - `base` (xs:anyURI)

    Child elements must appear in the following order if present:
    - `<asset>` (1)
    - library_element (0 or more)
        Any quantity and combination of any library elements can appear in any order:
        - `<library_animation_clips>`
        - `<library_animations>`
        - `<library_articulated_systems>` (in Kinematics)
        - `<library_cameras>`
        - `<library_controllers>`
        - `<library_effects>` (in FX)
        - `<library_force_fields>` (in Physics)
        - `<library_formulas>`
        - `<library_geometries>`
        - `<library_images>` (in FX)
        - `<library_joints>` (in Kinematics)
        - `<library_kinematics_models>` (in Kinematics)
        - `<library_kinematics_scenes>` (in Kinematics)
        - `<library_lights>`
        - `<library_materials>` (in FX)
        - `<library_nodes>`
        - `<library_physics_materials>` (in Physics)
        - `<library_physics_models>` (in Physics)
        - `<library_physics_scenes>` (in Physics)
        - `<library_visual_scenes>`
    - `<scene>` (0 or 1)
    - `<extra>` (0 or more)
    */
    pub(crate) fn parse(doc: &xml::Document<'_>) -> io::Result<Self> {
        let node = doc.root_element();
        if node.tag_name().name() != "COLLADA" {
            bail!("root element is not <COLLADA>");
        }

        let version: Version = node.required_attribute("version")?.parse()?;
        if version < Version::MIN {
            bail!("collada schema version {} is not supported", version);
        };
        // debug!("collada schema version is {}", version);

        let mut cx = Context {
            library_geometries: LibraryGeometries::default(),
        };

        for node in node.element_children() {
            match node.tag_name().name() {
                "library_geometries" => {
                    parse_library_geometries(&mut cx, node)?;
                }
                _name => {
                    // debug!("ignored <{}> element", name);
                }
            }
        }

        Ok(Self {
            library_geometries: cx.library_geometries,
        })
    }

    pub(crate) fn get<T>(&self, url: &T) -> Option<&<Self as Get<T>>::Target>
    where
        Self: Get<T>,
    {
        <Self as Get<T>>::get(self, url)
    }
}

impl<T> ops::Index<&T> for Document
where
    Self: Get<T>,
{
    type Output = <Self as Get<T>>::Target;

    #[track_caller]
    fn index(&self, url: &T) -> &Self::Output {
        self.get(url).expect("no entry found for key")
    }
}

#[derive(Debug)]
pub(crate) struct Source {
    // Required
    pub(crate) id: String,
    // Optional
    #[allow(dead_code)]
    pub(crate) name: Option<String>,

    // 0 or 1
    pub(crate) array_element: Option<ArrayElement>,
    // 0 or 1
    pub(crate) accessor: Option<Accessor>,
}

impl Source {
    /*
    The `<source>` element (core)

    Attributes:
    - `id` (xs:ID, Required)
    - `name` (xs:token, Optional)

    Child elements must appear in the following order if present:
    - `<asset>` (0 or 1)
    - array_element (0 or 1)
        Can be one of:
        - `<bool_array>`
        - `<float_array>`
        - `<IDREF_array>`
        - `<int_array>`
        - `<Name_array>`
        - `<SIDREF_array>`
        - `<token_array>`
    - `<technique_common>` (0 or 1)
    - `<technique>` (core) (0 or more)
    */
    fn parse(node: xml::Node<'_, '_>) -> io::Result<Self> {
        debug_assert_eq!(node.tag_name().name(), "source");
        let id = node.required_attribute("id")?;
        let mut array_element = None;
        let mut accessor = None;

        for child in node.element_children() {
            match child.tag_name().name() {
                "float_array" | "IDREF_array" | "Name_array" => {
                    array_element = Some(parse_array_element(child)?);
                }
                "technique_common" => {
                    for technique in child.element_children() {
                        match technique.tag_name().name() {
                            "accessor" => {
                                accessor = Some(Accessor::parse(technique)?);
                            }
                            _ => return Err(error::unexpected_child_elem(technique)),
                        }
                    }
                }
                "bool_array" | "int_array" | "SIDREF_array" | "token_array" => {
                    // warn!(
                    //     "ignored array element {} ({})",
                    //     child.tag_name().name(),
                    //     child.node_location()
                    // );
                }
                "asset" | "technique" => { /* skip */ }
                _ => return Err(error::unexpected_child_elem(child)),
            }
        }

        Ok(Self {
            id: id.into(),
            name: node.attribute("name").map(Into::into),
            array_element,
            accessor,
        })
    }
}

#[derive(Debug)]
pub(crate) struct ArrayElement {
    // Required
    pub(crate) id: String,
    // Required
    #[allow(dead_code)]
    pub(crate) count: u32,

    pub(crate) data: ArrayData,
}

fn parse_array_element(node: xml::Node<'_, '_>) -> io::Result<ArrayElement> {
    let name = node.tag_name().name();
    let is_string_array = name == "IDREF_array" || name == "Name_array";

    let id = node.required_attribute("id")?;
    let count = node.parse_required_attribute("count")?;
    let mut content = node.text().unwrap_or_default().trim();

    // some exporters write empty data arrays, but we need to conserve them anyways because others might reference them
    if content.is_empty() {
        let data = if is_string_array {
            ArrayData::String(vec![])
        } else {
            ArrayData::Float(vec![])
        };
        return Ok(ArrayElement {
            id: id.into(),
            count,
            data,
        });
    }

    if is_string_array {
        // TODO: check large count
        let mut values = Vec::with_capacity(count as _);
        for _ in 0..count {
            if content.is_empty() {
                bail!(
                    "expected more values while reading <{}> contents at {}",
                    node.tag_name().name(),
                    node.node_location()
                );
            }

            let mut n = 0;
            while content
                .as_bytes()
                .get(0)
                .map_or(false, |b| !b.is_ascii_whitespace())
            {
                n += 1;
            }
            values.push(content[..n].into());

            content = content.get(n..).unwrap_or_default().trim_start();
        }

        Ok(ArrayElement {
            id: id.into(),
            count,
            data: ArrayData::String(values),
        })
    } else {
        // TODO: check large count
        let mut values = Vec::with_capacity(count as _);
        // TODO: https://stackoverflow.com/questions/4325363/converting-a-number-with-comma-as-decimal-point-to-float
        let content = content.replace(',', ".");
        for res in float::parse_array_exact(&content, count as _) {
            let value = res.map_err(|e| {
                format_err!(
                    "{} in <{}> element ({})",
                    e,
                    node.tag_name().name(),
                    node.node_location(),
                )
            })?;
            values.push(value);
        }

        Ok(ArrayElement {
            id: id.into(),
            count,
            data: ArrayData::Float(values),
        })
    }
}

/// Data source array.
#[derive(Debug)]
pub(crate) enum ArrayData {
    /// <float_array>
    Float(Vec<f32>),
    /// <IDREF_array> or <Name_array>
    String(Vec<String>),
    // TODO(material)
    // /// <int_array>
    // Int(Vec<i32>),
    // /// <bool_array>
    // Bool(Vec<bool>),
}

#[allow(dead_code)] // TODO(material)
impl ArrayData {
    pub(crate) fn is_float(&self) -> bool {
        matches!(self, Self::Float(..))
    }

    pub(crate) fn is_string(&self) -> bool {
        matches!(self, Self::String(..))
    }

    pub(crate) fn as_float(&self) -> Option<&[f32]> {
        match self {
            Self::Float(v) => Some(v),
            Self::String(..) => None,
        }
    }

    pub(crate) fn as_string(&self) -> Option<&[String]> {
        match self {
            Self::Float(..) => None,
            Self::String(v) => Some(v),
        }
    }

    pub(crate) fn len(&self) -> usize {
        match self {
            Self::Float(v) => v.len(),
            Self::String(v) => v.len(),
        }
    }

    pub(crate) fn is_empty(&self) -> bool {
        match self {
            Self::Float(v) => v.is_empty(),
            Self::String(v) => v.is_empty(),
        }
    }
}

#[derive(Debug)]
pub(crate) struct Accessor {
    // Required
    pub(crate) count: u32,
    // Optional
    #[allow(dead_code)] // TODO(material)
    pub(crate) offset: u32,
    // Required
    pub(crate) source: Uri<ArrayData>,
    // Optional
    pub(crate) stride: u32,

    // 0 or more
    #[allow(dead_code)] // TODO(material)
    pub(crate) params: Vec<Param>,
}

impl Accessor {
    /*
    The `<accessor>` element

    Attributes:
    - `count` (uint_type, Required)
    - `offset` (uint_type, Optional, default: 0)
    - `source` (xs:anyURI, Required)
    - `stride` (uint_type, Optional, default: 1)

    Child elements:
    - `<param>` (0 or more)
    */
    fn parse(node: xml::Node<'_, '_>) -> io::Result<Self> {
        debug_assert_eq!(node.tag_name().name(), "accessor");
        let count = node.parse_required_attribute("count")?;
        let source = node.parse_url("source")?;
        let offset = node.parse_attribute("offset")?.unwrap_or(0);
        let stride = node.parse_attribute("stride")?.unwrap_or(1);
        let mut params = vec![];

        for child in node.element_children() {
            match child.tag_name().name() {
                "param" => {
                    params.push(Param::parse(child)?);
                }
                _ => return Err(error::unexpected_child_elem(child)),
            }
        }

        Ok(Self {
            count,
            offset,
            source,
            stride,
            params,
        })
    }
}

#[allow(dead_code)] // TODO(material)
#[derive(Debug)]
pub(crate) struct Param {
    /// The name of this element.
    pub(crate) name: Option<String>,
    /// The scoped identifier of this element.
    pub(crate) sid: Option<String>,
    // Required
    pub(crate) ty: String,
    // Optional
    pub(crate) semantic: Option<String>,
}

impl Param {
    /*
    The `<param>` element (data flow)

    Attributes:
    - `name` (xs:token, Optional)
    - `sid` (sid_type, Optional)
    - `type` (xs:NMTOKEN, Required)
    - `semantic` (xs:NMTOKEN, Optional)
    */
    fn parse(node: xml::Node<'_, '_>) -> io::Result<Self> {
        let ty = node.required_attribute("type")?;
        let name = node.attribute("name");
        let sid = node.attribute("sid");
        let semantic = node.attribute("semantic");
        Ok(Self {
            name: name.map(Into::into),
            sid: sid.map(Into::into),
            ty: ty.into(),
            semantic: semantic.map(Into::into),
        })
    }
}

#[derive(Debug)]
pub(crate) struct SharedInput<T = Accessor> {
    // Required
    pub(crate) offset: u32,
    // Required
    pub(crate) semantic: InputSemantic,
    // Required
    pub(crate) source: Uri<T>,
    // Optional
    pub(crate) set: u32,
}

impl<T> SharedInput<T> {
    /*
    The `<input>` element (shared)

    Attributes:
    - `offset` (uint_type, Required)
    - `semantic` (xs:NMTOKEN, Required)
    - `source` (uri_fragment_type, Required)
    - `set` (uint_type, Optional)
    */
    fn parse(node: xml::Node<'_, '_>) -> io::Result<Self> {
        debug_assert_eq!(node.tag_name().name(), "input");
        let semantic = node.parse_required_attribute("semantic")?;
        let source = node.parse_url("source")?;
        let offset = node.parse_required_attribute("offset")?;
        let set = node.parse_attribute("set")?.unwrap_or(0);
        Ok(Self {
            offset,
            semantic,
            source,
            set,
        })
    }

    pub(crate) fn cast<U>(self) -> SharedInput<U> {
        SharedInput {
            offset: self.offset,
            semantic: self.semantic,
            source: self.source.cast(),
            set: self.set,
        }
    }
}

#[derive(Debug)]
pub(crate) struct UnsharedInput {
    // Required
    pub(crate) semantic: InputSemantic,
    // Required
    pub(crate) source: Uri<Accessor>,
}

impl UnsharedInput {
    /*
    The `<input>` element (unshared)

    Attributes:
    - `semantic` (xs:NMTOKEN, Required)
    - `source` (uri_fragment_type, Required)
    */
    fn parse(node: xml::Node<'_, '_>) -> io::Result<Self> {
        debug_assert_eq!(node.tag_name().name(), "input");
        let semantic = node.parse_required_attribute("semantic")?;
        let source = node.parse_url("source")?;
        Ok(Self { semantic, source })
    }
}

// refs: https://www.khronos.org/files/collada_spec_1_4.pdf#page=74
// refs: https://www.khronos.org/files/collada_spec_1_5.pdf#page=88
#[allow(non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum InputSemantic {
    /// Geometric binormal (bitangent) vector.
    BINORMAL,
    /// Color coordinate vector. Color inputs are RGB (float3_type).
    COLOR,
    /// Continuity constraint at the control vertex (CV).
    CONTINUITY,
    /// Raster or MIP-level input.
    IMAGE,
    /// Sampler input.
    INPUT,
    /// Tangent vector for preceding control point.
    IN_TANGENT,
    /// Sampler interpolation type.
    INTERPOLATION,
    /// Inverse of local-to-world matrix.
    INV_BIND_MATRIX,
    /// Skin influence identifier.
    JOINT,
    /// Number of piece-wise linear approximation steps to use for the spline segment that follows this CV.
    LINEAR_STEPS,
    /// Morph targets for mesh morphing.
    MORPH_TARGET,
    /// Weights for mesh morphing
    MORPH_WEIGHT,
    /// Normal vector
    NORMAL,
    /// Sampler output.
    OUTPUT,
    /// Tangent vector for succeeding control point.
    OUT_TANGENT,
    /// Geometric coordinate vector.
    POSITION,
    /// Geometric tangent vector.
    TANGENT,
    /// Texture binormal (bitangent) vector.
    TEXBINORMAL,
    /// Texture coordinate vector.
    TEXCOORD,
    /// Texture tangent vector.
    TEXTANGENT,
    /// Generic parameter vector.
    UV,
    /// Mesh vertex.
    VERTEX,
    /// Skin influence weighting value.
    WEIGHT,
}

impl FromStr for InputSemantic {
    type Err = io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "BINORMAL" => Self::BINORMAL,
            "COLOR" => Self::COLOR,
            "CONTINUITY" => Self::CONTINUITY,
            "IMAGE" => Self::IMAGE,
            "INPUT" => Self::INPUT,
            "IN_TANGENT" => Self::IN_TANGENT,
            "INTERPOLATION" => Self::INTERPOLATION,
            "INV_BIND_MATRIX" => Self::INV_BIND_MATRIX,
            "JOINT" => Self::JOINT,
            "LINEAR_STEPS" => Self::LINEAR_STEPS,
            "MORPH_TARGET" => Self::MORPH_TARGET,
            "MORPH_WEIGHT" => Self::MORPH_WEIGHT,
            "NORMAL" => Self::NORMAL,
            "OUTPUT" => Self::OUTPUT,
            "OUT_TANGENT" => Self::OUT_TANGENT,
            "POSITION" => Self::POSITION,
            "TANGENT" => Self::TANGENT,
            "TEXBINORMAL" => Self::TEXBINORMAL,
            "TEXCOORD" => Self::TEXCOORD,
            "TEXTANGENT" => Self::TEXTANGENT,
            "UV" => Self::UV,
            "VERTEX" => Self::VERTEX,
            "WEIGHT" => Self::WEIGHT,
            _ => bail!("unknown input semantic {:?}", s),
        })
    }
}

mod error {
    use super::*;

    #[cold]
    pub(crate) fn one_or_more_elems(node: xml::Node<'_, '_>, name: &str) -> io::Error {
        format_err!(
            "<{}> element must be contain one or more <{}> elements ({})",
            node.tag_name().name(),
            name,
            node.node_location()
        )
    }

    #[cold]
    pub(crate) fn exactly_one_elem(node: xml::Node<'_, '_>, name: &str) -> io::Error {
        format_err!(
            "<{}> element must be contain exactly one <{}> element ({})",
            node.tag_name().name(),
            name,
            node.node_location()
        )
    }

    #[cold]
    pub(crate) fn multiple_elems(node: xml::Node<'_, '_>) -> io::Error {
        format_err!(
            "multiple <{}> elements ({})",
            node.tag_name().name(),
            node.node_location()
        )
    }

    #[cold]
    pub(crate) fn unexpected_child_elem(child: xml::Node<'_, '_>) -> io::Error {
        format_err!(
            "unexpected child element <{}> in <{}> element ({})",
            child.tag_name().name(),
            child.parent_element().unwrap().tag_name().name(),
            child.node_location()
        )
    }
}

mod warn {
    use super::*;

    #[cold]
    pub(crate) fn unsupported_child_elem(_child: xml::Node<'_, '_>) {
        // warn!(
        //     "<{}> child element in <{}> element is unsupported ({})",
        //     child.tag_name().name(),
        //     child.parent_element().unwrap().tag_name().name(),
        //     child.node_location()
        // );
    }
}