omg-idl-code-gen 0.2.3

OMG IDL to Rust code generator library
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
// Copyright (C) 2019  Frank Rehberger
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0>
use linked_hash_map::LinkedHashMap;
use serde_derive::Serialize;
use std::{collections::HashSet, fmt};

const INDENTION: usize = 4;
const IMPORT_VEC: &str = "use std::vec::Vec;";
const IMPORT_SERDE: &str = "use serde_derive::{Serialize, Deserialize};";

/// Enum representing a basic operator that applies to a single value.
/// i.e. + (Positive), - (Negative), ~ (Inverse)
#[derive(Clone, Debug)]
pub enum UnaryOp {
    Neg,
    Pos,
    Inverse,
}

impl UnaryOp {
    /// Convert the UnaryOp enumeration into a &str
    pub fn to_str(&self) -> &str {
        match self {
            UnaryOp::Neg => "-",
            UnaryOp::Pos => "+",
            UnaryOp::Inverse => "~",
        }
    }
}

/// Enum representing an operator on two values. I.e. + (Add), - (Sub),
/// * (Mul), / (Div), % (Mod), < (LShift), > (RShift), | (Or), ^ (Xor),
///   & (And)
#[derive(Clone, Debug)]
pub enum BinaryOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    LShift,
    RShift,
    Or,
    Xor,
    And,
}

impl BinaryOp {
    /// Convert the BinaryOp enumeration into a &str
    pub fn to_str(&self) -> &str {
        match self {
            BinaryOp::Add => "+",
            BinaryOp::Sub => "-",
            BinaryOp::Mul => "*",
            BinaryOp::Div => "/",
            BinaryOp::Mod => "%",
            BinaryOp::LShift => "<<",
            BinaryOp::RShift => ">>",
            BinaryOp::Or => "|",
            BinaryOp::Xor => "^",
            BinaryOp::And => "&",
        }
    }
}

/// A name under scope, I.e. crate::cmn
#[derive(Clone, Debug)]
pub struct IdlScopedName(pub Vec<String>, pub bool);

impl fmt::Display for IdlScopedName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let is_absolute_path = self.1;
        let components = &self.0;
        for (idx, comp) in components.iter().enumerate() {
            // TODO, use paths according to "crate::" or "super::"
            if idx == 0 && !is_absolute_path {
                write!(f, "{comp}")?
            } else if idx == 0 && is_absolute_path {
                write!(f, "crate::{comp}")?
            } else {
                write!(f, "::{comp}")?
            }
        }
        Ok(())
    }
}

/// Representation of all the different right hand options in an equation.
#[derive(Clone, Debug, Default)]
pub enum IdlValueExpr {
    #[default]
    None,
    DecLiteral(String),
    HexLiteral(String),
    OctLiteral(String),
    CharLiteral(String),
    WideCharLiteral(String),
    StringLiteral(String),
    WideStringLiteral(String),
    BooleanLiteral(bool),
    FloatLiteral(
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
    ),
    UnaryOp(UnaryOp, Box<IdlValueExpr>),
    BinaryOp(BinaryOp, Box<IdlValueExpr>),
    Expr(Box<IdlValueExpr>, Box<IdlValueExpr>),
    Brace(Box<IdlValueExpr>),
    ScopedName(IdlScopedName),
}

impl fmt::Display for IdlValueExpr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let value_expr = match self {
            IdlValueExpr::None => "",
            IdlValueExpr::DecLiteral(val) => val,
            IdlValueExpr::HexLiteral(val) => val,
            IdlValueExpr::OctLiteral(val) => val,
            IdlValueExpr::CharLiteral(val) => val,
            IdlValueExpr::WideCharLiteral(val) => val,
            IdlValueExpr::StringLiteral(val) => val,
            IdlValueExpr::WideStringLiteral(val) => val,
            IdlValueExpr::BooleanLiteral(val) => &val.to_string(),
            IdlValueExpr::UnaryOp(op, expr) => &format!("{}{}", op.to_str(), expr),
            IdlValueExpr::BinaryOp(op, expr) => &format!("{}{}", op.to_str(), expr),
            IdlValueExpr::Expr(expr1, expr2) => &format!("{}{}", expr1, expr2),
            IdlValueExpr::Brace(expr) => &format!("({})", expr),
            IdlValueExpr::FloatLiteral(integral, fraction, exponent, suffix) => &format!(
                "{}.{}e{}{}",
                integral.as_ref().unwrap().clone(),
                fraction.as_ref().unwrap().clone(),
                exponent.as_ref().unwrap().clone(),
                suffix.as_ref().unwrap().clone()
            ),
            IdlValueExpr::ScopedName(name) => &name.to_string(),
        };
        write!(f, "{value_expr}")
    }
}

/// Representation of an IDL Struct
#[derive(Clone, Debug)]
pub struct IdlStructMember {
    pub id: String,
    pub type_spec: IdlTypeSpec,
}

/// Representation of an IDL Switch
#[derive(Clone, Debug)]
pub struct IdlSwitchElement {
    pub id: String,
    pub type_spec: IdlTypeSpec,
}

/// Representation of an IDL Switch Label
#[derive(Clone, Debug)]
pub enum IdlSwitchLabel {
    Label(IdlValueExpr),
    Default,
}

/// Representation of an IDL Switch Case
#[derive(Clone, Debug)]
pub struct IdlSwitchCase {
    pub labels: Vec<IdlSwitchLabel>,
    pub elem_spec: IdlSwitchElement,
}

/// Representation of an IDL Type
#[derive(Clone, Debug, Default)]
pub enum IdlTypeSpec {
    #[default]
    None,
    ArrayType(Box<IdlTypeSpec>, Vec<IdlValueExpr>),
    SequenceType(Box<IdlTypeSpec>),
    StringType(Option<Box<IdlValueExpr>>),
    WideStringType(Option<Box<IdlValueExpr>>),
    // FixedPtType,
    // EnumDcl,
    // BitsetDcl,
    // BitmaskDcl,
    F32Type,
    F64Type,
    F128Type,
    I16Type,
    I32Type,
    I64Type,
    U16Type,
    U32Type,
    U64Type,
    CharType,
    WideCharType,
    BooleanType,
    OctetType,
    // AnyType,
    // ObjectType,
    // ValueBaseType,
    ScopedName(IdlScopedName),
}

impl fmt::Display for IdlTypeSpec {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let value_expr = match self {
            IdlTypeSpec::F32Type => Ok("f32".to_string()),
            IdlTypeSpec::F64Type => Ok("f64".to_string()),
            IdlTypeSpec::F128Type => Ok("f128".to_string()),
            IdlTypeSpec::I16Type => Ok("i16".to_string()),
            IdlTypeSpec::I32Type => Ok("i32".to_string()),
            IdlTypeSpec::I64Type => Ok("i64".to_string()),
            IdlTypeSpec::U16Type => Ok("u16".to_string()),
            IdlTypeSpec::U32Type => Ok("u32".to_string()),
            IdlTypeSpec::U64Type => Ok("u64".to_string()),
            IdlTypeSpec::CharType => Ok("char".to_string()),
            IdlTypeSpec::WideCharType => Ok("char".to_string()),
            IdlTypeSpec::BooleanType => Ok("bool".to_string()),
            IdlTypeSpec::OctetType => Ok("u8".to_string()),
            IdlTypeSpec::StringType(None) => Ok("String".to_string()),
            IdlTypeSpec::WideStringType(None) => Ok("String".to_string()),
            // TODO implement String/Sequence bounds
            IdlTypeSpec::StringType(_) => Ok("String".to_string()),
            // TODO implement String/Sequence bounds for serializer and deserialzer
            IdlTypeSpec::WideStringType(_) => Ok("String".to_string()),
            IdlTypeSpec::SequenceType(typ_expr) => Ok(format!("Vec<{}>", typ_expr.as_ref())),
            IdlTypeSpec::ArrayType(typ_expr, dim_expr_list) => {
                let dim_list_str = dim_expr_list
                    .iter()
                    .map(|expr| match expr {
                        IdlValueExpr::DecLiteral(_)
                        | IdlValueExpr::HexLiteral(_)
                        | IdlValueExpr::OctLiteral(_)
                        | IdlValueExpr::Expr(_, _)
                        | IdlValueExpr::BinaryOp(_, _) => Ok(format!(";{}_usize]", expr)),
                        IdlValueExpr::ScopedName(_) => Ok(format!(";{} as usize]", expr)),
                        _ => Err(fmt::Error),
                    })
                    .collect::<Result<String, fmt::Error>>()?;
                Ok(format!(
                    "{}{}{dim_list_str}",
                    "[".repeat(dim_expr_list.len()),
                    typ_expr
                ))
            }
            IdlTypeSpec::ScopedName(name) => Ok(name.to_string()),
            _ => unimplemented!(),
        }?;
        write!(f, "{value_expr}")
    }
}

/// Selector for the different supported IDL kinds
#[derive(Clone, Debug, Default)]
pub enum IdlTypeDclKind {
    #[default]
    None,
    TypeDcl(String, IdlTypeSpec),
    StructDcl(String, Vec<IdlStructMember>),
    UnionDcl(String, IdlTypeSpec, Vec<IdlSwitchCase>),
    EnumDcl(String, Vec<String>),
}

/// Representation of an IDL Type
#[derive(Clone, Debug, Default)]
pub struct IdlTypeDcl(pub IdlTypeDclKind);

/// Data storage to align with Jinja (IdlStruct)
#[derive(Serialize)]
struct IdlStructField {
    name: String,
    type_str: String,
    directive: String,
}

/// Data storage to align with Jinja (IdlSwitch)
#[derive(Serialize)]
struct IdlSwitchField {
    name: String,
    element_id: String,
    element_type: String,
}

impl IdlTypeDcl {
    /// Convert the object to a Result<String> for output. The env must have the templates
    /// already loaded.
    pub fn render(
        &self,
        env: &minijinja::Environment,
        level: usize,
    ) -> Result<String, minijinja::Error> {
        match self.0 {
            IdlTypeDclKind::TypeDcl(ref id, ref type_spec) => {
                let tmpl = env.get_template("typedef.j2")?;
                tmpl.render(minijinja::context! {
                    typedef_name => id,
                    typedef_type => type_spec.to_string(),
                    indent_level => level
                })
            }
            IdlTypeDclKind::StructDcl(ref id, ref type_spec) => {
                let tmpl = env.get_template("struct.j2")?;
                let fields = type_spec
                    .iter()
                    .map(|field| {
                        // @todo this doesn't work because the type needs to be determined. But if
                        //       the type is a ScopedName it can also be an array
                        if let IdlTypeSpec::ArrayType(_, _) = field.type_spec {
                            IdlStructField {
                                name: field.id.clone(),
                                type_str: field.type_spec.to_string(),
                                directive: "#[serde(with = \"serde_arrays\")]".to_string(),
                            }
                        } else {
                            IdlStructField {
                                name: field.id.clone(),
                                type_str: field.type_spec.to_string(),
                                directive: String::new(),
                            }
                        }
                    })
                    .collect::<Vec<IdlStructField>>();

                tmpl.render(minijinja::context! {
                    struct_name => id,
                    fields,
                    indent_level => level
                })
            }
            IdlTypeDclKind::EnumDcl(ref id, ref enums) => {
                let tmpl = env.get_template("enum.j2")?;
                tmpl.render(minijinja::context! {
                    enum_name => id,
                    variants => enums,
                    indent_level => level
                })
            }
            IdlTypeDclKind::UnionDcl(ref id, ref _type_spec, ref switch_cases) => {
                let tmpl = env.get_template("union_switch.j2")?;
                let union_members = switch_cases
                    .iter()
                    .flat_map(|case| {
                        case.labels
                            .clone()
                            .iter()
                            .map(|label| {
                                let label = match label {
                                    IdlSwitchLabel::Label(label) => label.to_string(),
                                    IdlSwitchLabel::Default => "default".to_owned(),
                                };

                                IdlSwitchField {
                                    name: label.to_string(),
                                    element_id: case.elem_spec.id.clone(),
                                    element_type: case.elem_spec.type_spec.to_string(),
                                }
                            })
                            .collect::<Vec<IdlSwitchField>>()
                    })
                    .collect::<Vec<IdlSwitchField>>();

                tmpl.render(minijinja::context! {
                    union_name => id,
                    union_members,
                    indent_level => level
                })
            }
            IdlTypeDclKind::None => Ok(String::new()),
        }
    }
}

/// Data representation of a const declaration
#[derive(Clone, Default, Debug)]
pub struct IdlConstDcl {
    pub id: String,
    pub typedcl: IdlTypeSpec,
    pub value: IdlValueExpr,
}

impl IdlConstDcl {
    /// Convert the object to a Result<String> for output. The env must have the templates
    /// already loaded.
    pub fn render(
        &self,
        env: &minijinja::Environment,
        level: usize,
    ) -> Result<String, minijinja::Error> {
        let tmpl = env.get_template("const.j2")?;

        // Rust does not support const String's. Convert them to &str
        let type_str = match &self.typedcl {
            IdlTypeSpec::StringType(_) | IdlTypeSpec::WideStringType(_) => "&str".to_owned(),
            _ => self.typedcl.to_string(),
        };

        tmpl.render(minijinja::context! {
            const_name => self.id,
            const_type => type_str,
            const_value => self.value.to_string(),
            indent_level => level
        })
    }
}

/// Data representation of an IDL Module or the root module.
#[derive(Clone, Default, Debug)]
pub struct IdlModule {
    pub id: Option<String>,
    pub modules: LinkedHashMap<String, IdlModule>,
    pub types: LinkedHashMap<String, IdlTypeDcl>,
    pub constants: LinkedHashMap<String, IdlConstDcl>,
}

impl IdlModule {
    pub fn new(id: Option<String>) -> IdlModule {
        IdlModule {
            id,
            modules: LinkedHashMap::default(),
            types: LinkedHashMap::default(),
            constants: LinkedHashMap::default(),
        }
    }

    /// Convert the object to a Result<String> for output. The env must have the templates
    /// already loaded.
    pub fn render(
        &self,
        env: &minijinja::Environment,
        level: usize,
    ) -> Result<String, minijinja::Error> {
        let mut module_info = String::new();
        let add = if self.id.is_some() { 1 } else { 0 };

        let mut uses = HashSet::new();
        for typ in self.types.values() {
            if let IdlTypeDcl(IdlTypeDclKind::TypeDcl(_, IdlTypeSpec::SequenceType(_))) = typ {
                uses.insert(IMPORT_VEC);
            } else if let IdlTypeDcl(IdlTypeDclKind::StructDcl(_, _)) = typ {
                uses.insert(IMPORT_SERDE);
            } else if let IdlTypeDcl(IdlTypeDclKind::EnumDcl(_, _)) = typ {
                uses.insert(IMPORT_SERDE);
            } else if let IdlTypeDcl(IdlTypeDclKind::UnionDcl(_, _, _)) = typ {
                uses.insert(IMPORT_SERDE);
            }
        }
        for cnsts in self.constants.values() {
            if let IdlTypeSpec::SequenceType(_) = cnsts.typedcl {
                uses.insert(IMPORT_VEC);
                break;
            }
        }

        for required_use in uses {
            let uses = format!(
                "{:indent$}{required_use}\n",
                "",
                indent = (level + add) * INDENTION
            );
            module_info.push_str(&uses);
        }

        for typ in self.types.values() {
            let rendered = typ.render(env, level + add)?;
            module_info.push_str(&rendered);
            module_info.push('\n');
        }

        for module in self.modules.values() {
            let rendered = module.render(env, level + add)?;
            module_info.push_str(&rendered);
            module_info.push('\n');
        }

        for cnst in self.constants.values() {
            let rendered = cnst.render(env, level + add)?;
            module_info.push_str(&rendered);
            module_info.push('\n');
        }

        match self.id {
            Some(ref id_str) => {
                let tmpl = env.get_template("module.j2")?;
                tmpl.render(minijinja::context! {
                    module_name => id_str,
                    module_information => module_info,
                    indent_level => level
                })
            }
            None => Ok(module_info),
        }
    }
}