xsd_parser/generator/
mod.rs

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
//! The `generator` module contains the code [`Generator`] and all related types.

mod data;
mod error;
mod helper;
mod misc;
mod renderer;

use std::collections::{BTreeMap, HashSet, VecDeque};
use std::fmt::Display;

use proc_macro2::{Ident as Ident2, TokenStream};
use quote::{format_ident, quote};
use tracing::instrument;

use crate::types::{Ident, IdentType, Type, Types};

pub use self::error::Error;
pub use self::misc::{BoxFlags, ContentMode, GenerateFlags, SerdeSupport, TypedefMode};

use self::data::TypeData;
use self::helper::Walk;
use self::misc::{
    format_module, format_type_ident, make_type_name, Module, Modules, PendingType, StateFlags,
    TypeRef,
};

/// Type that is used to generate rust code from a [`Types`] object.
#[must_use]
#[derive(Debug)]
pub struct Generator<'types> {
    types: &'types Types,

    /* state */
    cache: BTreeMap<Ident, TypeRef>,
    pending: VecDeque<PendingType<'types>>,

    /* code */
    modules: Modules,

    /* config */
    derive: Vec<Ident2>,
    postfixes: [String; 5],
    box_flags: BoxFlags,
    content_mode: ContentMode,
    typedef_mode: TypedefMode,
    serde_support: SerdeSupport,
    generate_flags: GenerateFlags,
    xsd_parser_crate: Ident2,
}

/* Generator */

impl<'types> Generator<'types> {
    /// Create a new code generator from the passed `types`.
    pub fn new(types: &'types Types) -> Self {
        Self {
            types,

            cache: BTreeMap::new(),
            pending: VecDeque::new(),
            modules: Modules::default(),

            derive: vec![format_ident!("Debug"), format_ident!("Clone")],
            postfixes: [
                String::from("Type"), // Type
                String::new(),        // Group
                String::new(),        // Element
                String::new(),        // Attribute
                String::new(),        // AttributeGroup
            ],
            box_flags: BoxFlags::AUTO,
            content_mode: ContentMode::Auto,
            typedef_mode: TypedefMode::Auto,
            serde_support: SerdeSupport::None,
            generate_flags: GenerateFlags::empty(),
            xsd_parser_crate: format_ident!("xsd_parser"),
        }
    }

    /// Set the name of the `xsd-parser` create that the generator should use for
    /// generating the code.
    pub fn xsd_parser_crate<S: Display>(mut self, value: S) -> Self {
        self.xsd_parser_crate = format_ident!("{value}");

        self
    }

    /// Set the traits the generated types should derive from.
    ///
    /// Default is `Debug` and `Clone`.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let generator = Generator::new(types)
    ///     .derive(vec!["Debug", "Clone", "Eq", "PartialEq", "Ord", "PartialOrd"]);
    /// ```
    pub fn derive<I>(mut self, value: I) -> Self
    where
        I: IntoIterator,
        I::Item: Display,
    {
        self.derive = value.into_iter().map(|x| format_ident!("{x}")).collect();

        self
    }

    /// Set the [`BoxFlags`] flags the generator should use for generating the code.
    pub fn box_flags(mut self, value: BoxFlags) -> Self {
        self.box_flags = value;

        self
    }

    /// Set the [`ContentMode`] value the generator should use for generating the code.
    pub fn content_mode(mut self, value: ContentMode) -> Self {
        self.content_mode = value;

        self
    }

    /// Set the [`TypedefMode`] value the generator should use for generating the code.
    pub fn typedef_mode(mut self, value: TypedefMode) -> Self {
        self.typedef_mode = value;

        self
    }

    /// Set the [`SerdeSupport`] value the generator should use for generating the code.
    pub fn serde_support(mut self, value: SerdeSupport) -> Self {
        self.serde_support = value;

        self
    }

    /// Set the [`GenerateFlags`] flags the generator should use for generating the code.
    pub fn generate_flags(mut self, value: GenerateFlags) -> Self {
        self.generate_flags = value;

        self
    }

    /// Add the passed [`GenerateFlags`] flags the generator should use for generating the code.
    pub fn with_generate_flags(mut self, value: GenerateFlags) -> Self {
        self.generate_flags |= value;

        self
    }

    /// Set the postfixes the generator should use for the different types.
    ///
    /// Default is `"Type"` for the [`IdentType::Type`] type and `""` for the other types.
    pub fn with_type_postfix<S: Into<String>>(mut self, type_: IdentType, postfix: S) -> Self {
        self.postfixes[type_ as usize] = postfix.into();

        self
    }

    /// Add a custom implemented type to the generator.
    ///
    /// This will add a custom implemented type to the generator. These types are
    /// usually implemented and provided by the user of the generated code. The
    /// generator will just reference to the type definition and will not generate
    /// any code related to this type.
    ///
    /// # Errors
    ///
    /// Returns an error if the namespace of the passed identifier is unknown.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let generator = Generator::new(types)
    ///     .with_type(Ident::type_("UserDefinedType"));
    /// ```
    pub fn with_type(mut self, ident: Ident) -> Result<Self, Error> {
        let module_ident = format_module(self.types, ident.ns)?;
        let type_ident = format_ident!("{}", ident.name.to_string());

        let type_ref = TypeRef {
            ns: ident.ns,
            module_ident,
            type_ident,
            flags: StateFlags::empty(),
            boxed_elements: HashSet::new(),
        };
        self.cache.insert(ident, type_ref);

        Ok(self)
    }

    /// Generate the code for the given type.
    ///
    /// This will generate the code for the passed type identifier and all
    /// dependencies of this type.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let generator = Generator::new(types)
    ///     .generate_type(Ident::type_("Root"));
    /// ```
    #[instrument(err, level = "trace", skip(self))]
    pub fn generate_type(mut self, ident: Ident) -> Result<Self, Error> {
        self.get_or_create_type_ref(ident)?;
        self.generate_pending()?;

        Ok(self)
    }

    /// Generate the code for all types.
    ///
    /// This will generate the code for all types and all dependencies of this
    /// type that are specified in the [`Types`] object passed to the generator.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let generator = Generator::new(types)
    ///     .generate_all_types();
    /// ```
    #[instrument(err, level = "trace", skip(self))]
    pub fn generate_all_types(mut self) -> Result<Self, Error> {
        for ident in self.types.keys() {
            self.get_or_create_type_ref(ident.clone())?;
        }
        self.generate_pending()?;

        Ok(self)
    }

    /// Finish the code generation.
    ///
    /// THis will return the generated code as [`TokenStream`].
    #[instrument(level = "trace", skip(self))]
    pub fn finish(self) -> TokenStream {
        let Self {
            modules,
            types,
            serde_support,
            ..
        } = self;

        let serde = serde_includes(serde_support);

        let modules = modules.0.into_iter().map(|(ns, module)| {
            let Module {
                code,
                quick_xml_serialize,
                quick_xml_deserialize,
            } = module;

            let quick_xml_serialize = quick_xml_serialize.map(|code| {
                quote! {
                    pub mod quick_xml_serialize {
                        use super::*;

                        #code
                    }
                }
            });

            let quick_xml_deserialize = quick_xml_deserialize.map(|code| {
                quote! {
                    pub mod quick_xml_deserialize {
                        use super::*;

                        #code
                    }
                }
            });

            let code = quote! {
                #code
                #quick_xml_serialize
                #quick_xml_deserialize
            };

            if let Some(ns) = ns {
                let name = format_module(types, Some(ns)).unwrap();

                quote! {
                    pub mod #name {
                        use super::*;

                        #code
                    }
                }
            } else {
                code
            }
        });

        quote! {
            #serde

            #( #modules )*
        }
    }

    #[instrument(level = "trace", skip(self))]
    fn get_or_create_type_ref(&mut self, ident: Ident) -> Result<&TypeRef, Error> {
        let Self {
            types,
            cache,
            pending,
            postfixes,
            generate_flags,
            ..
        } = self;

        if !cache.contains_key(&ident) {
            let ty = types
                .get(&ident)
                .ok_or_else(|| Error::UnknownType(ident.clone()))?;
            let name = make_type_name(postfixes, ty, &ident);
            let (module_ident, type_ident) = if let Type::BuildIn(x) = ty {
                (None, format_ident!("{x}"))
            } else {
                let use_modules = generate_flags.intersects(GenerateFlags::USE_MODULES);
                let module_ident = format_module(types, use_modules.then_some(ident.ns).flatten())?;
                let type_ident = format_type_ident(&name);

                (module_ident, type_ident)
            };

            let boxed_elements = get_boxed_elements(&ident, ty, types, cache);
            pending.push_back(PendingType {
                ty,
                ident: ident.clone(),
            });

            let type_ref = TypeRef {
                module_ident,
                ns: ident.ns,
                type_ident,
                flags: StateFlags::empty(),
                boxed_elements,
            };

            assert!(cache.insert(ident.clone(), type_ref).is_none());
        }

        Ok(cache.get_mut(&ident).unwrap())
    }

    #[instrument(err, level = "trace", skip(self))]
    fn generate_pending(&mut self) -> Result<(), Error> {
        while let Some(args) = self.pending.pop_front() {
            self.generate_type_intern(args)?;
        }

        Ok(())
    }

    #[instrument(err, level = "trace", skip(self))]
    fn generate_type_intern(&mut self, data: PendingType<'types>) -> Result<(), Error> {
        let PendingType { ty, ident } = data;

        let data = TypeData {
            ty,
            ident,
            generator: self,
        };

        match data.ty {
            Type::BuildIn(_) => Ok(()),
            Type::Union(x) => data.generate_union(x),
            Type::Abstract(x) => data.generate_abstract(x),
            Type::Reference(x) => data.generate_reference(x),
            Type::Enumeration(x) => data.generate_enumeration(x),
            Type::ComplexType(x) => data.generate_complex_type(x),
            Type::All(x) => data.generate_all(x),
            Type::Choice(x) => data.generate_choice(x),
            Type::Sequence(x) => data.generate_sequence(x),
        }
    }
}

/* TypeRef */

impl TypeRef {
    fn add_flag_checked(&mut self, flag: StateFlags) -> bool {
        let ret = self.flags.intersects(flag);

        self.flags |= flag;

        ret
    }
}

/* Helper */

fn serde_includes(serde_support: SerdeSupport) -> Option<TokenStream> {
    let serde = matches!(
        serde_support,
        SerdeSupport::QuickXml | SerdeSupport::SerdeXmlRs
    );

    serde.then(|| {
        quote!(
            use serde::{Serialize, Deserialize};
        )
    })
}

fn get_boxed_elements<'a>(
    ident: &Ident,
    mut ty: &'a Type,
    types: &'a Types,
    cache: &BTreeMap<Ident, TypeRef>,
) -> HashSet<Ident> {
    if let Type::ComplexType(ci) = ty {
        if let Some(type_) = ci.content.as_ref().and_then(|ident| types.get(ident)) {
            ty = type_;
        }
    }

    match ty {
        Type::All(si) | Type::Choice(si) | Type::Sequence(si) => si
            .elements
            .iter()
            .filter_map(|f| {
                if Walk::new(types, cache).is_loop(ident, &f.type_) {
                    Some(f.ident.clone())
                } else {
                    None
                }
            })
            .collect(),
        _ => HashSet::new(),
    }
}