xsd-parser 1.5.2

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
use std::any::Any;
use std::fmt::{Debug, Display};
use std::mem::take;

use proc_macro2::Ident as Ident2;
use quote::format_ident;

use crate::models::{
    meta::{MetaType, MetaTypes},
    schema::NamespaceId,
    Name, TypeIdent,
};

/// This trait defined how names are generated and formatted in `xsd-parser`.
///
/// Use the [`Interpreter::with_naming`](crate::Interpreter::with_naming) method
/// to use a customized implementation for this trait.
pub trait Naming: Debug {
    /// Clone this object into a new `Box`.
    fn clone_boxed(&self) -> Box<dyn Naming>;

    /// Create a new name builder instance.
    fn builder(&self) -> Box<dyn NameBuilder>;

    /// Unify the given string.
    ///
    /// Before actual name generation or formatting it is sometimes useful
    /// to have a pre-formatting for names, to have a unified schema for the
    /// names in general.
    ///
    /// The default implementation uses pascal case to unify all different kind
    /// of names.
    fn unify(&self, s: &str) -> String;

    /// Generate a name for the passed type `ty` identified by `ident` respecting the
    /// configured type postfixes.
    fn make_type_name(&self, postfixes: &[String], ty: &MetaType, ident: &TypeIdent) -> Name;

    /// Create an unknown enum variant using the provided id.
    ///
    /// The default implementation generated `Unknown{id}` here.
    fn make_unknown_variant(&self, id: usize) -> Ident2;

    /// Format the passed string `s` as module name.
    fn format_module_name(&self, s: &str) -> String;

    /// Format the passed string `s` as type name.
    fn format_type_name(&self, s: &str) -> String;

    /// Format the passed string `s` as field name.
    fn format_field_name(&self, s: &str) -> String;

    /// Format the passed string `s` as variant name.
    fn format_variant_name(&self, s: &str) -> String;

    /// Format the passed string `s` as constant name.
    fn format_constant_name(&self, s: &str) -> String;

    /// Format the passed string `s` as attribute field name.
    ///
    /// The default implementation simply uses [`format_field_name`](Naming::format_field_name).
    fn format_attribute_field_name(&self, s: &str) -> String {
        self.format_field_name(s)
    }

    /// Format the passed string `s` as element field name.
    ///
    /// The default implementation simply uses [`format_field_name`](Naming::format_field_name).
    fn format_element_field_name(&self, s: &str) -> String {
        self.format_field_name(s)
    }

    /// Create a suitable identifier for the passed module name `name`.
    ///
    /// The default implementation uses [`format_module_ident`](Naming::format_module_ident)
    /// with `display_name` set to `None` here.
    fn format_module_ident(&self, name: &Name) -> Ident2 {
        let ident = self.format_module_name(name.as_str());

        format_ident!("{ident}")
    }

    /// Create a suitable identifier for the passed type name `name` respecting
    /// user defined names stored in `display_name`.
    ///
    /// The default implementation uses the `display_name` or `name` as fallback
    /// and formats it using [`format_type_name`](Naming::format_type_name).
    fn format_type_ident(&self, name: &Name, display_name: Option<&str>) -> Ident2 {
        let ident = self.format_type_name(display_name.unwrap_or(name.as_str()));

        format_ident!("{ident}")
    }

    /// Create a suitable identifier for the passed field name `name` respecting
    /// user defined names stored in `display_name`.
    ///
    /// The default implementation uses the `display_name` or `name` as fallback
    /// and formats it using [`format_field_name`](Naming::format_field_name).
    fn format_field_ident(&self, name: &Name, display_name: Option<&str>) -> Ident2 {
        let ident = self.format_field_name(display_name.unwrap_or(name.as_str()));

        format_ident!("{ident}")
    }

    /// Create a suitable identifier for the passed variant name `name` respecting
    /// user defined names stored in `display_name`.
    ///
    /// The default implementation uses [`format_type_ident`](Naming::format_type_ident) here.
    fn format_variant_ident(&self, name: &Name, display_name: Option<&str>) -> Ident2 {
        let ident = self.format_variant_name(display_name.unwrap_or(name.as_str()));

        format_ident!("{ident}")
    }

    /// Create a suitable identifier for the passed constant name `name` respecting
    /// user defined names stored in `display_name`.
    ///
    /// The default implementation uses [`format_constant_name`](Naming::format_constant_name) here.
    fn format_constant_ident(&self, name: &Name, display_name: Option<&str>) -> Ident2 {
        let ident = self.format_constant_name(display_name.unwrap_or(name.as_str()));

        format_ident!("{ident}")
    }

    /// Create a suitable identifier for the passed attribute field name `name`
    /// respecting user defined names stored in `display_name`.
    ///
    /// The default implementation uses [`format_attribute_field_name`](Naming::format_attribute_field_name).
    fn format_attribute_field_ident(&self, name: &Name, display_name: Option<&str>) -> Ident2 {
        let ident = self.format_attribute_field_name(display_name.unwrap_or(name.as_str()));

        format_ident!("{ident}")
    }

    /// Create a suitable identifier for the passed element field name `name`
    /// respecting user defined names stored in `display_name`.
    ///
    /// The default implementation uses [`format_element_field_name`](Naming::format_element_field_name).
    fn format_element_field_ident(&self, name: &Name, display_name: Option<&str>) -> Ident2 {
        let ident = self.format_element_field_name(display_name.unwrap_or(name.as_str()));

        format_ident!("{ident}")
    }

    /// Generate a identifier for the module identified by `ns`.
    fn format_module(&self, types: &MetaTypes, ns: Option<NamespaceId>) -> Option<Ident2> {
        let ns = ns?;
        let module = types.modules.get(&ns)?;
        let name = module.name.as_ref()?;

        Some(self.format_module_ident(name))
    }
}

/// This trait defines a builder for building type names.
///
/// The general idea of the builder is the following:
/// - A type name needs a name to be valid. The name is set by
///   [`set_name`](NameBuilder::set_name).
/// - The name can be extended by multiple prefixes using
///   [`add_extension`](NameBuilder::add_extension).
/// - Sometimes is it not possible to create a unique name. To get one
///   the builder should add a unique id to the name (this is controlled by
///   [`set_with_id`](NameBuilder::set_with_id)).
/// - The output of the name builder is a [`Name`]. `Name`s can be fixed or
///   generated. The name builder should decide automatically which variant of
///   the name has to be generated, if not explicitly specified by the user
///   (using [`set_generated`](NameBuilder::set_generated)).
pub trait NameBuilder: Debug + Any {
    /// Finish the current name building and create a [`Name`] from the known
    /// information.
    fn finish(&self) -> Name;

    /// Merge the data of the `other` name builder into the current name builder.
    /// The passed name builder is of the same type then the current one.
    fn merge(&mut self, other: &dyn NameBuilder);

    /// Create a clone of the current builder and return it as box.
    fn clone_boxed(&self) -> Box<dyn NameBuilder>;

    /// Returns `true` if this builder has a name set, `false` otherwise.
    fn has_name(&self) -> bool;

    /// Returns `true` if this builder has at least on extension set, `false` otherwise.
    fn has_extension(&self) -> bool;

    /// Set the base name of this builder.
    fn set_name(&mut self, name: String);

    /// Instruct the builder to add a unique id to the generated name or not.
    fn set_with_id(&mut self, value: bool);

    /// Instruct the builder to generated a [`Name::Generated`] if `true` is passed,
    /// or a [`Name::Named`] if `false` is passed.
    fn set_generated(&mut self, value: bool);

    /// Add a new `extension` to the builder. If `replace` is set to true, any previous
    /// extension is dropped.
    fn add_extension(&mut self, replace: bool, extension: String);

    /// Remove the specified `suffix` from the name and the extensions.
    fn strip_suffix(&mut self, suffix: &str);

    /// Force the builder to generate a unique id, that is later used to generate
    /// the name.
    ///
    /// Normally the id should be generated as last step (in the
    /// [`finish`](NameBuilder::finish) method), but sometimes it is useful to
    /// force the builder to generate the id to shared it between different copies
    /// of the builder.
    fn generate_unique_id(&mut self);

    /// Prepare the builder to create a type name.
    fn prepare_type_name(&mut self);

    /// Prepare the builder to create a field name.
    fn prepare_field_name(&mut self);

    /// Prepare the builder to create a content type name.
    fn prepare_content_type_name(&mut self);
}

impl NameBuilder for Box<dyn NameBuilder> {
    #[inline]
    fn finish(&self) -> Name {
        (**self).finish()
    }

    #[inline]
    fn merge(&mut self, other: &dyn NameBuilder) {
        (**self).merge(other);
    }

    #[inline]
    fn clone_boxed(&self) -> Box<dyn NameBuilder> {
        (**self).clone_boxed()
    }

    #[inline]
    fn has_name(&self) -> bool {
        (**self).has_name()
    }

    #[inline]
    fn has_extension(&self) -> bool {
        (**self).has_extension()
    }

    #[inline]
    fn set_name(&mut self, name: String) {
        (**self).set_name(name);
    }

    #[inline]
    fn set_with_id(&mut self, value: bool) {
        (**self).set_with_id(value);
    }

    #[inline]
    fn set_generated(&mut self, value: bool) {
        (**self).set_generated(value);
    }

    #[inline]
    fn add_extension(&mut self, replace: bool, extension: String) {
        (**self).add_extension(replace, extension);
    }

    #[inline]
    fn strip_suffix(&mut self, suffix: &str) {
        (**self).strip_suffix(suffix);
    }

    #[inline]
    fn generate_unique_id(&mut self) {
        (**self).generate_unique_id();
    }

    #[inline]
    fn prepare_type_name(&mut self) {
        (**self).prepare_type_name();
    }

    #[inline]
    fn prepare_field_name(&mut self) {
        (**self).prepare_field_name();
    }

    #[inline]
    fn prepare_content_type_name(&mut self) {
        (**self).prepare_content_type_name();
    }
}

/// Helper trait that provides additional builder patterns to the [`NameBuilder`].
pub trait NameBuilderExt: Sized {
    /// Force the builder to generate a unique id.
    #[must_use]
    fn generate_id(self) -> Self;

    /// Tell the builder to add (`true`) or not to add (`false`) the unique id
    /// to the generated name.
    #[must_use]
    fn with_id(self, value: bool) -> Self;

    /// Add extensions to the builder using the passed iterator `iter`. If `replace`
    /// is set to `true` any existing extension is dropped before the new ones are
    /// applied.
    #[must_use]
    fn extend<I>(self, replace: bool, iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: Display;

    /// Remove the specified `suffix` from the builder.
    #[must_use]
    fn remove_suffix(self, suffix: &str) -> Self;

    /// Instruct the builder to create a unique name from the passed `value`.
    ///
    /// This means, that the [`with_id`](NameBuilderExt::with_id) is automatically
    /// set to `false`.
    #[must_use]
    fn unique_name<T>(self, value: T) -> Self
    where
        T: Display;

    /// Instruct the builder to create a name that is shared between different parts
    /// of the code from the passed `value`.
    ///
    /// This means, that the [`with_id`](NameBuilderExt::with_id) is automatically
    /// set to `true` and the generated name has a unique id to be identified.
    #[must_use]
    fn shared_name<T>(self, value: T) -> Self
    where
        T: Display;

    /// If the builder does currently not have a name, the passed `fallback` is applied.
    #[must_use]
    fn or<T>(self, fallback: T) -> Self
    where
        T: NameFallback;

    /// If the builder does currently not have a name, the passed `fallback` is applied.
    #[must_use]
    fn or_else<F, T>(self, fallback: F) -> Self
    where
        F: FnOnce() -> T,
        T: NameFallback;

    /// Prepare the builder to create a type name.
    #[must_use]
    fn type_name(self) -> Self;

    /// Prepare the builder to create a field name.
    #[must_use]
    fn field_name(self) -> Self;

    /// Prepare the builder to create a content type name.
    #[must_use]
    fn content_type_name(self) -> Self;
}

impl<X> NameBuilderExt for X
where
    X: NameBuilder + Sized,
{
    fn generate_id(mut self) -> Self {
        self.generate_unique_id();

        self
    }

    fn with_id(mut self, value: bool) -> Self {
        self.set_with_id(value);

        self
    }

    fn extend<I>(mut self, mut replace: bool, iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: Display,
    {
        for ext in iter {
            let ext = ext.to_string();

            self.add_extension(take(&mut replace), ext);
        }

        self
    }

    fn remove_suffix(mut self, suffix: &str) -> Self {
        self.strip_suffix(suffix);

        self
    }

    fn unique_name<T>(mut self, value: T) -> Self
    where
        T: Display,
    {
        self.set_name(value.to_string());
        self.set_with_id(false);

        self
    }

    fn shared_name<T>(mut self, value: T) -> Self
    where
        T: Display,
    {
        self.set_name(value.to_string());
        self.set_with_id(true);

        self
    }

    fn or<T>(self, fallback: T) -> Self
    where
        T: NameFallback,
    {
        self.or_else(|| fallback)
    }

    fn or_else<F, T>(mut self, fallback: F) -> Self
    where
        F: FnOnce() -> T,
        T: NameFallback,
    {
        if !self.has_name() {
            fallback().apply(&mut self);
        }

        self
    }

    fn type_name(mut self) -> Self {
        self.prepare_type_name();

        self
    }

    fn field_name(mut self) -> Self {
        self.prepare_field_name();

        self
    }

    fn content_type_name(mut self) -> Self {
        self.prepare_content_type_name();

        self
    }
}

/// Helper trait used in [`NameBuilderExt::or`] and [`NameBuilderExt::or_else`] to define
/// what can be used as fallback for a name.
pub trait NameFallback {
    /// Apply the fallback to the passed `builder`.
    fn apply(self, builder: &mut dyn NameBuilder);
}

impl NameFallback for &dyn NameBuilder {
    fn apply(self, builder: &mut dyn NameBuilder) {
        builder.merge(self);
    }
}

impl NameFallback for Box<dyn NameBuilder> {
    fn apply(self, builder: &mut dyn NameBuilder) {
        builder.merge(&*self);
    }
}

impl NameFallback for Name {
    #[inline]
    fn apply(self, builder: &mut dyn NameBuilder) {
        (&self).apply(builder);
    }
}

impl NameFallback for &Name {
    #[inline]
    fn apply(self, builder: &mut dyn NameBuilder) {
        builder.set_name(self.as_str().to_owned());
        builder.set_generated(self.is_generated());
        builder.set_with_id(false);
    }
}

impl NameFallback for Option<&Name> {
    #[inline]
    fn apply(self, builder: &mut dyn NameBuilder) {
        if let Some(x) = self {
            x.apply(builder);
        }
    }
}

impl NameFallback for Option<Name> {
    #[inline]
    fn apply(self, builder: &mut dyn NameBuilder) {
        self.as_ref().apply(builder);
    }
}

impl NameFallback for &Option<Name> {
    fn apply(self, builder: &mut dyn NameBuilder) {
        self.as_ref().apply(builder);
    }
}

impl NameFallback for &String {
    fn apply(self, builder: &mut dyn NameBuilder) {
        builder.set_name(self.to_owned());
        builder.set_with_id(false);
    }
}

impl NameFallback for Option<&String> {
    fn apply(self, builder: &mut dyn NameBuilder) {
        if let Some(x) = self {
            x.apply(builder);
        }
    }
}

impl NameFallback for Option<String> {
    fn apply(self, builder: &mut dyn NameBuilder) {
        self.as_ref().apply(builder);
    }
}

impl NameFallback for &Option<String> {
    fn apply(self, builder: &mut dyn NameBuilder) {
        self.as_ref().apply(builder);
    }
}

impl NameFallback for &str {
    fn apply(self, builder: &mut dyn NameBuilder) {
        builder.set_name(self.to_owned());
        builder.set_with_id(false);
    }
}

impl NameFallback for Option<&str> {
    fn apply(self, builder: &mut dyn NameBuilder) {
        if let Some(x) = self {
            x.apply(builder);
        }
    }
}