xsd-parser 1.1.0

Rust code generator for XML schema files
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
//! Contains the [`Config`] structures for the [`generate`](super::generate) method.

use std::path::PathBuf;

use bitflags::bitflags;
use url::Url;

pub use crate::generator::{BoxFlags, GeneratorFlags, SerdeSupport, TypedefMode};
pub use crate::schema::{Namespace, NamespacePrefix};
pub use crate::types::{IdentType, Type};

use crate::schema::Schemas;
use crate::types::{Ident, Name};
use crate::InterpreterError;

/// Configuration structure for the [`generate`](super::generate) method.
#[must_use]
#[derive(Default, Debug, Clone)]
pub struct Config {
    /// Configuration for the schema parser.
    pub parser: ParserConfig,

    /// Configuration for the schema interpreter.
    pub interpreter: InterpreterConfig,

    /// Configuration for the type information optimizer.
    pub optimizer: OptimizerConfig,

    /// Configuration for the code generator.
    pub generator: GeneratorConfig,
}

/// Configuration for the schema parser.
#[derive(Debug, Clone)]
pub struct ParserConfig {
    /// List of resolvers to use for resolving referenced schemas.
    pub resolver: Vec<Resolver>,

    /// List of namespaces to add to the parser before the schemas are loaded.
    ///
    /// See [`with_namespace`](crate::Parser::with_namespace) for more details.
    pub namespaces: Vec<(NamespacePrefix, Namespace)>,

    /// List of schemas to load.
    pub schemas: Vec<Schema>,

    /// Additional flags to control the parser.
    pub flags: ParserFlags,

    /// Wether to enable the debug output and where to write it to.
    pub debug_output: Option<PathBuf>,
}

/// Configuration for the schema interpreter.
#[derive(Debug, Clone)]
pub struct InterpreterConfig {
    /// List of user defined types to add to the interpreter before the schemas
    /// are actually interpreted.
    ///
    /// See [`with_type`](crate::Interpreter::with_type) for more details.
    pub types: Vec<(IdentTriple, Type)>,

    /// Additional flags to control the interpreter.
    pub flags: InterpreterFlags,

    /// Wether to enable the debug output and where to write it to.
    pub debug_output: Option<PathBuf>,
}

/// Configuration for the type information optimizer.
#[derive(Debug, Clone)]
pub struct OptimizerConfig {
    /// Additional flags to control the optimizer.
    pub flags: OptimizerFlags,

    /// Wether to enable the debug output and where to write it to.
    pub debug_output: Option<PathBuf>,
}

/// Configuration for the code generator.
#[derive(Debug, Clone)]
pub struct GeneratorConfig {
    /// Types to add to the generator before the actual code is generated.
    ///
    /// See [`with_type`](crate::Generator::with_type) for more details.
    pub types: Vec<IdentTriple>,

    /// Sets the traits the generated types should derive from.
    ///
    /// See [`derive`](crate::Generator::derive) for more details.
    pub derive: Option<Vec<String>>,

    /// Set the traits that should be implemented by dynamic types.
    ///
    /// See [`dyn_type_traits`](crate::Generator::dyn_type_traits) for more details.
    pub dyn_type_traits: Option<Vec<String>>,

    /// Postfixes that should be applied to the name of the different generated
    /// types.
    ///
    /// See [`with_type_postfix`](crate::Generator::with_type_postfix) for more details.
    pub type_postfix: TypePostfix,

    /// Tell the generator how to deal with boxing.
    pub box_flags: BoxFlags,

    /// Tells the generator how to deal with type definitions.
    pub typedef_mode: TypedefMode,

    /// Tells the generator how to generate code for the [`serde`] crate.
    pub serde_support: SerdeSupport,

    /// Specify which types the generator should generate code for.
    pub generate: Generate,

    /// Additional flags to control the generator.
    pub flags: GeneratorFlags,

    /// Name of the `xsd-parser` crate that is used for the generated code.
    pub xsd_parser: String,

    /// Renderers to use for rendering the code.
    pub renderers: Vec<Renderer>,
}

/// Postfixed that will be added to the different types generated by the code generator.
#[derive(Debug, Clone)]
pub struct TypePostfix {
    /// Postfix added to normal types (like `xs:simpleType` or `xs:complexType`).
    pub type_: String,

    /// Postfixes added to elements (like `xs:element`).
    pub element: String,

    /// Postfixes added to inline types if elements (like `xs:element`).
    pub element_type: String,
}

/// Configuration for the [`Resolver`](crate::parser::resolver::Resolver)s used in [`ParserConfig`].
#[derive(Debug, Clone)]
pub enum Resolver {
    /// Resolver that is used to resolve ewb resources (like `http://...` or `https://...`).
    #[cfg(feature = "web-resolver")]
    Web,

    /// Resolver that is used to resolve local resources from disk (like `./local-schema.xsd` or `file://...`).
    File,
}

/// Configuration for the schemas to load used in [`ParserConfig`].
#[derive(Debug, Clone)]
pub enum Schema {
    /// Load a schema from the provided URL.
    Url(Url),

    /// Load a schema from the provided file path.
    File(PathBuf),

    /// Load the schema from the provided string.
    Schema(String),
}

/// Configuration which types the [`Generator`](crate::Generator) should generate
/// code for used in [`GeneratorConfig`].
#[derive(Debug, Clone)]
pub enum Generate {
    /// The generator will generate code for all types of the schemas.
    All,

    /// The generator will generate code for all types that have a name.
    Named,

    /// List of identifiers the generator will generate code for.
    Types(Vec<IdentTriple>),
}

/// Identifier that is used inside the config.
///
/// Each element in a XML schema is uniquely identified by the following three
/// values:
///     - The namespace of the element (or no namespace at all).
///     - The name of the element.
///     - The type of element.
///
/// This struct is used to bundle these three information to a unique identifier
/// for an element.
#[derive(Debug, Clone)]
pub struct IdentTriple {
    /// Namespace where the type is defined in.
    pub ns: Option<NamespaceIdent>,

    /// Name of the type.
    pub name: String,

    /// Type of the identifier (because pure names are not unique in XSD).
    pub type_: IdentType,
}

/// Identifies a namespace by either it's known prefix or by the namespace directly.
#[derive(Debug, Clone)]
pub enum NamespaceIdent {
    /// Uses a namespace prefix to refer to a specific namespace in the schema.
    Prefix(NamespacePrefix),

    /// Uses the full namespace to refer to a specific namespace in the schema.
    Namespace(Namespace),
}

/// Configuration for the [`Renderer`](crate::generator::renderer::Renderer)s
/// the [`Generator`](crate::Generator) should use for rendering the code.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Renderer {
    /// Render to render the pure types.
    Types,

    /// Renderer to render associated methods that return the default values
    /// of the different fields of a struct.
    Defaults,

    /// Renderer to add constants for the namespaces to the generated code.
    NamespaceConstants,

    /// Renderer that adds the [`WithNamespace`](crate::WithNamespace) trait to
    /// the generated types.
    WithNamespaceTrait,

    /// Renderer that renders code for the `quick_xml` serializer of the
    /// different types.
    QuickXmlSerialize,

    /// Renderer that renders code for the `quick_xml` deserializer of the
    /// different types.
    QuickXmlDeserialize {
        /// Whether to box the deserializer or not.
        ///
        /// For more details have a look at [`QuickXmlDeserializeRenderer::boxed_deserializer`](crate::QuickXmlDeserializeRenderer::boxed_deserializer).
        boxed_deserializer: bool,
    },
}

bitflags! {
    /// Flags to control the [`Parser`](crate::Parser).
    #[derive(Debug, Clone)]
    pub struct ParserFlags: u32 {
        /// Whether the parser should resolve `xs:include` and `xs:import` elements
        /// or not.
        ///
        /// See [`resolve_includes`](crate::Parser::resolve_includes) for details.
        const RESOLVE_INCLUDES = 1 << 0;

        /// Whether to add the default namespaces to the parser or not.
        ///
        /// See [`with_default_namespaces`](crate::Parser::with_default_namespaces) for details.
        const DEFAULT_NAMESPACES = 1 << 1;
    }
}

bitflags! {
    /// Flags to control the [`Interpreter`](crate::Interpreter).
    #[derive(Debug, Clone)]
    pub struct InterpreterFlags: u32 {
        /// Whether to add the build-in types to the interpreter or not.
        ///
        /// See [`with_buildin_types`](crate::Interpreter::with_buildin_types) for details.
        const BUILDIN_TYPES = 1 << 0;

        /// Whether to add the default types definitions to the interpreter or not.
        ///
        /// See [`with_default_typedefs`](crate::Interpreter::with_default_typedefs) for details.
        const DEFAULT_TYPEDEFS = 1 << 1;

        /// Whether to add a default type definitions for `xs:anyType` or not.
        ///
        /// See [`with_xs_any_type`](crate::Interpreter::with_xs_any_type) for details.
        const WITH_XS_ANY_TYPE = 1 << 2;
    }
}

bitflags! {
    /// Flags to control the [`Optimizer`](crate::Optimizer).
    #[derive(Debug, Clone)]
    pub struct OptimizerFlags: u32 {
        /// Whether to remove empty enum variants or not.
        ///
        /// See [`remove_empty_enum_variants`](crate::Optimizer::remove_empty_enum_variants) for details.
        const REMOVE_EMPTY_ENUM_VARIANTS = 1 << 0;

        /// Whether to remove empty enums or not.
        ///
        /// See [`remove_empty_enums`](crate::Optimizer::remove_empty_enums) for details.
        const REMOVE_EMPTY_ENUMS = 1 << 1;

        /// Whether to remove duplicate union variants or not.
        ///
        /// See [`remove_duplicate_union_variants`](crate::Optimizer::remove_duplicate_union_variants) for details.
        const REMOVE_DUPLICATE_UNION_VARIANTS = 1 << 2;

        /// Whether to remove empty unions or not.
        ///
        /// See [`remove_empty_unions`](crate::Optimizer::remove_empty_unions) for details.
        const REMOVE_EMPTY_UNIONS = 1 << 3;

        /// Whether to use the unrestricted base type of a type or not.
        ///
        /// See [`use_unrestricted_base_type`](crate::Optimizer::use_unrestricted_base_type) for details.
        const USE_UNRESTRICTED_BASE_TYPE = 1 << 4;

        /// Whether to convert dynamic types to choices or not.
        ///
        /// See [`convert_dynamic_to_choice`](crate::Optimizer::convert_dynamic_to_choice) for details.
        const CONVERT_DYNAMIC_TO_CHOICE = 1 << 5;

        /// Whether to flatten the content of complex types or not.
        ///
        /// See [`flatten_complex_types`](crate::Optimizer::flatten_complex_types) for details.
        const FLATTEN_COMPLEX_TYPES = 1 << 6;

        /// Whether to flatten unions or not.
        ///
        /// See [`flatten_unions`](crate::Optimizer::flatten_unions) for details.
        const FLATTEN_UNIONS = 1 << 7;

        /// Whether to merge enumerations and unions or not.
        ///
        /// See [`merge_enum_unions`](crate::Optimizer::merge_enum_unions) for details.
        const MERGE_ENUM_UNIONS = 1 << 8;

        /// Whether to resolve type definitions or not.
        ///
        /// See [`resolve_typedefs`](crate::Optimizer::resolve_typedefs) for details.
        const RESOLVE_TYPEDEFS = 1 << 9;

        /// Whether to remove duplicate types or not.
        ///
        /// See [`remove_duplicates`](crate::Optimizer::remove_duplicates) for details.
        const REMOVE_DUPLICATES = 1 << 10;

        /// Group that contains all necessary optimization that should be applied
        /// if code with [`serde`] support should be rendered.
        const SERDE =  Self::FLATTEN_COMPLEX_TYPES.bits()
            | Self::FLATTEN_UNIONS.bits()
            | Self::MERGE_ENUM_UNIONS.bits();

        /// Wether to merge the cardinality of a complex choice type or not.
        ///
        /// See [`merge_choice_cardinalities`](crate::Optimizer::merge_choice_cardinalities) for details.
        const MERGE_CHOICE_CARDINALITIES = 1 << 11;
    }
}

impl Config {
    /// Set parser flags to the config.
    pub fn set_parser_flags(mut self, flags: ParserFlags) -> Self {
        self.parser.flags = flags;

        self
    }

    /// Add parser flags to the config.
    pub fn with_parser_flags(mut self, flags: ParserFlags) -> Self {
        self.parser.flags.insert(flags);

        self
    }

    /// Remove parser flags to the config.
    pub fn without_parser_flags(mut self, flags: ParserFlags) -> Self {
        self.parser.flags.remove(flags);

        self
    }

    /// Set interpreter flags to the config.
    pub fn set_interpreter_flags(mut self, flags: InterpreterFlags) -> Self {
        self.interpreter.flags = flags;

        self
    }

    /// Add code interpreter flags to the config.
    pub fn with_interpreter_flags(mut self, flags: InterpreterFlags) -> Self {
        self.interpreter.flags.insert(flags);

        self
    }

    /// Remove code interpreter flags to the config.
    pub fn without_interpreter_flags(mut self, flags: InterpreterFlags) -> Self {
        self.interpreter.flags.remove(flags);

        self
    }

    /// Set optimizer flags to the config.
    pub fn set_optimizer_flags(mut self, flags: OptimizerFlags) -> Self {
        self.optimizer.flags = flags;

        self
    }

    /// Add optimizer flags to the config.
    pub fn with_optimizer_flags(mut self, flags: OptimizerFlags) -> Self {
        self.optimizer.flags.insert(flags);

        self
    }

    /// Remove optimizer flags to the config.
    pub fn without_optimizer_flags(mut self, flags: OptimizerFlags) -> Self {
        self.optimizer.flags.remove(flags);

        self
    }

    /// Set generator flags to the config.
    pub fn set_generator_flags(mut self, flags: GeneratorFlags) -> Self {
        self.generator.flags = flags;

        self
    }

    /// Add code generator flags to the config.
    pub fn with_generator_flags(mut self, flags: GeneratorFlags) -> Self {
        self.generator.flags.insert(flags);

        self
    }

    /// Remove code generator flags to the config.
    pub fn without_generator_flags(mut self, flags: GeneratorFlags) -> Self {
        self.generator.flags.remove(flags);

        self
    }

    /// Set boxing flags to the code generator config.
    pub fn set_box_flags(mut self, flags: BoxFlags) -> Self {
        self.generator.box_flags = flags;

        self
    }

    /// Add boxing flags to the code generator config.
    pub fn with_box_flags(mut self, flags: BoxFlags) -> Self {
        self.generator.box_flags.insert(flags);

        self
    }

    /// Remove boxing flags to the code generator config.
    pub fn without_box_flags(mut self, flags: BoxFlags) -> Self {
        self.generator.box_flags.remove(flags);

        self
    }

    /// Adds the passed `renderer` to the config.
    ///
    /// If the same type of renderer was already added,
    /// it is replaced by the new one.
    pub fn with_renderer(mut self, renderer: Renderer) -> Self {
        if let Some(index) = self.generator.renderers.iter().position(|x| x == &renderer) {
            self.generator.renderers[index] = renderer;
        } else {
            self.generator.renderers.push(renderer);
        }

        self
    }

    /// Add multiple renderers to the generator config.
    ///
    /// See [`with_renderer`](Self::with_renderer) for details.
    pub fn with_renderers<I>(mut self, renderers: I) -> Self
    where
        I: IntoIterator<Item = Renderer>,
    {
        for renderer in renderers {
            self = self.with_renderer(renderer);
        }

        self
    }

    /// Enable code generation for [`quick_xml`] serialization.
    pub fn with_quick_xml_serialize(self) -> Self {
        self.with_renderers([
            Renderer::Types,
            Renderer::Defaults,
            Renderer::NamespaceConstants,
            Renderer::QuickXmlSerialize,
        ])
    }

    /// Enable code generation for [`quick_xml`] deserialization with the default settings.
    pub fn with_quick_xml_deserialize(self) -> Self {
        self.with_quick_xml_deserialize_config(false)
    }

    /// Enable code generation for [`quick_xml`] deserialization
    /// with the passed configuration.
    pub fn with_quick_xml_deserialize_config(self, boxed_deserializer: bool) -> Self {
        self.with_renderers([
            Renderer::Types,
            Renderer::Defaults,
            Renderer::NamespaceConstants,
            Renderer::QuickXmlDeserialize { boxed_deserializer },
        ])
    }

    /// Enable code generation for [`quick_xml`] serialization and deserialization
    /// with the default settings.
    pub fn with_quick_xml(self) -> Self {
        self.with_quick_xml_serialize().with_quick_xml_deserialize()
    }

    /// Enable code generation for [`quick_xml`] serialization and deserialization
    /// with the passed configuration.
    pub fn with_quick_xml_config(self, boxed_deserializer: bool) -> Self {
        self.with_quick_xml_serialize()
            .with_quick_xml_deserialize_config(boxed_deserializer)
    }

    /// Set the [`serde`] support.
    pub fn with_serde_support(mut self, serde_support: SerdeSupport) -> Self {
        self.generator.serde_support = serde_support;

        if self.generator.serde_support != SerdeSupport::None {
            self.optimizer.flags |= OptimizerFlags::SERDE;
        }

        self
    }

    /// Set the types the code should be generated for.
    pub fn with_generate<I>(mut self, types: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<IdentTriple>,
    {
        self.generator.generate = Generate::Types(types.into_iter().map(Into::into).collect());

        self
    }

    /// Set the typedef mode for the generator.
    pub fn with_typedef_mode(mut self, mode: TypedefMode) -> Self {
        self.generator.typedef_mode = mode;

        self
    }

    /// Set the traits the generated types should derive from.
    pub fn with_derive<I>(mut self, derive: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        self.generator.derive = Some(
            derive
                .into_iter()
                .map(Into::into)
                .filter(|s| !s.is_empty())
                .collect(),
        );

        self
    }
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            resolver: vec![Resolver::File],
            schemas: vec![],
            namespaces: vec![],
            flags: ParserFlags::RESOLVE_INCLUDES | ParserFlags::DEFAULT_NAMESPACES,
            debug_output: None,
        }
    }
}

impl Default for InterpreterConfig {
    fn default() -> Self {
        Self {
            types: vec![],
            debug_output: None,
            flags: InterpreterFlags::BUILDIN_TYPES
                | InterpreterFlags::DEFAULT_TYPEDEFS
                | InterpreterFlags::WITH_XS_ANY_TYPE,
        }
    }
}

impl Default for OptimizerConfig {
    fn default() -> Self {
        Self {
            debug_output: None,
            flags: OptimizerFlags::REMOVE_EMPTY_ENUM_VARIANTS
                | OptimizerFlags::REMOVE_EMPTY_ENUMS
                | OptimizerFlags::REMOVE_DUPLICATE_UNION_VARIANTS
                | OptimizerFlags::REMOVE_EMPTY_UNIONS,
        }
    }
}

impl Default for GeneratorConfig {
    fn default() -> Self {
        Self {
            types: vec![],
            derive: None,
            type_postfix: TypePostfix::default(),
            dyn_type_traits: None,
            box_flags: BoxFlags::AUTO,
            typedef_mode: TypedefMode::Auto,
            serde_support: SerdeSupport::None,
            generate: Generate::Named,
            flags: GeneratorFlags::empty(),
            xsd_parser: "xsd_parser".into(),
            renderers: vec![Renderer::Types],
        }
    }
}

impl Default for TypePostfix {
    fn default() -> Self {
        Self {
            type_: String::from("Type"),
            element: String::new(),
            element_type: String::from("ElementType"),
        }
    }
}

/* IdentTriple */

impl IdentTriple {
    /// Resolve the triple to an actual type that is available in the schema.
    ///
    /// # Errors
    ///
    /// Returns an error if the namespace or the namespace prefix could not be
    /// resolved.
    pub fn resolve(self, schemas: &Schemas) -> Result<Ident, InterpreterError> {
        let ns = match self.ns {
            None => None,
            Some(NamespaceIdent::Prefix(prefix)) => Some(
                schemas
                    .resolve_prefix(&prefix)
                    .ok_or(InterpreterError::UnknownNamespacePrefix(prefix))?,
            ),
            #[allow(clippy::unnecessary_literal_unwrap)]
            Some(NamespaceIdent::Namespace(ns)) => {
                let ns = Some(ns);
                Some(
                    schemas
                        .resolve_namespace(&ns)
                        .ok_or_else(|| InterpreterError::UnknownNamespace(ns.unwrap()))?,
                )
            }
        };

        Ok(Ident {
            ns,
            name: Name::new_named(self.name),
            type_: self.type_,
        })
    }
}

impl<X> From<(IdentType, X)> for IdentTriple
where
    X: AsRef<str>,
{
    fn from((type_, ident): (IdentType, X)) -> Self {
        let ident = ident.as_ref();
        let (prefix, name) = ident
            .split_once(':')
            .map_or((None, ident), |(a, b)| (Some(a), b));
        let ns = prefix.map(|x| NamespaceIdent::prefix(x.as_bytes().to_owned()));
        let name = name.to_owned();

        Self { ns, name, type_ }
    }
}

impl<N, X> From<(IdentType, N, X)> for IdentTriple
where
    N: Into<Option<NamespaceIdent>>,
    X: Into<String>,
{
    fn from((type_, ns, name): (IdentType, N, X)) -> Self {
        let ns = ns.into();
        let name = name.into();

        Self { ns, name, type_ }
    }
}

/* NamespaceIdent */

impl NamespaceIdent {
    /// Creates a new [`NamespaceIdent::Prefix`] instance from the passed `value`.
    pub fn prefix<X>(value: X) -> Self
    where
        NamespacePrefix: From<X>,
    {
        Self::Prefix(NamespacePrefix::from(value))
    }

    /// Creates a new [`NamespaceIdent::Namespace`] instance from the passed `value`.
    pub fn namespace<X>(value: X) -> Self
    where
        Namespace: From<X>,
    {
        Self::Namespace(Namespace::from(value))
    }
}

impl From<Namespace> for NamespaceIdent {
    fn from(value: Namespace) -> Self {
        Self::Namespace(value)
    }
}

impl From<NamespacePrefix> for NamespaceIdent {
    fn from(value: NamespacePrefix) -> Self {
        Self::Prefix(value)
    }
}