rtps-idl 0.2.0

RTPS 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
// 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 std::io::Write;
use std::io::Error;

///
#[derive(Clone, Debug)]
pub enum UnaryOp {
    Neg,
    Pos,
    Inverse,
}

const INDENTION: usize = 4;
const ATTR_ALLOW_DEADCODE: &str = "#[allow(dead_code)]";
const ATTR_DERIVE_SERDE: &str = "#[derive(Serialize, Deserialize)]";
const ATTR_DERIVE_CLONE_DEBUG: &str = "#[derive(Clone, Debug)]";
const ATTR_ALLOW_NON_CAMEL_CASE_TYPES: &str = "#[allow(non_camel_case_types)]";
const ATTR_ALLOW_NON_SNAKE_CASE: &str = "#[allow(non_snake_case)]";
const IMPORT_SERDE: &str = "use serde_derive::{Serialize, Deserialize};";
const ATTR_ALLOW_UNUSED_IMPORTS: &str = "#[allow(unused_imports)]";

impl UnaryOp {
    pub fn write<W: Write>(&self, out: &mut W) -> Result<(), Error> {
        let _ = match self {
            UnaryOp::Neg => write!(out, "-"),
            UnaryOp::Pos => write!(out, "+"),
            UnaryOp::Inverse => write!(out, "~"),
        };
        Ok(())
    }
}

///
#[derive(Clone, Debug)]
pub enum BinaryOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    LShift,
    RShift,
    Or,
    Xor,
    And,
}


impl BinaryOp {
    pub fn write<W: Write>(&self, out: &mut W) -> Result<(), Error> {
        let _ = match self {
            BinaryOp::Add => write!(out, "+"),
            BinaryOp::Sub => write!(out, "-"),
            BinaryOp::Mul => write!(out, "*"),
            BinaryOp::Div => write!(out, "/"),
            BinaryOp::Mod => write!(out, "%"),
            BinaryOp::LShift => write!(out, "<<"),
            BinaryOp::RShift => write!(out, ">>"),
            BinaryOp::Or => write!(out, "|"),
            BinaryOp::Xor => write!(out, "^"),
            BinaryOp::And => write!(out, "&"),
        };
        Ok(())
    }
}

///
#[derive(Clone, Debug)]
pub struct IdlScopedName(pub Vec<String>, pub bool);

impl IdlScopedName {
    pub fn write<W: Write>(&self, out: &mut W) -> Result<(), Error> {
        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 {
                let _ = write!(out, "{}", comp);
            } else if idx == 0 && is_absolute_path {
                let _ = write!(out, "crate::{}", comp);
            } else {
                let _ = write!(out, "::{}", comp);
            }
        }
        Ok(())
    }
}

///
#[derive(Clone, Debug)]
pub enum IdlValueExpr {
    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 IdlValueExpr {
    pub fn write<W: Write>(&self, out: &mut W) -> Result<(), Error> {
        let _ = match self {
            IdlValueExpr::None => write!(out, ""),
            IdlValueExpr::DecLiteral(ref val) => write!(out, "{}", val),
            IdlValueExpr::HexLiteral(ref val) => write!(out, "{}", val),
            IdlValueExpr::OctLiteral(ref val) => write!(out, "{}", val),
            IdlValueExpr::CharLiteral(ref val) => write!(out, "{}", val),
            IdlValueExpr::WideCharLiteral(ref val) => write!(out, "{}", val),
            IdlValueExpr::StringLiteral(ref val) => write!(out, "{}", val),
            IdlValueExpr::WideStringLiteral(ref val) => write!(out, "{}", val),
            IdlValueExpr::BooleanLiteral(val) => write!(out, "{}", val),
            //            FloatLiteral(ref integ => write!(out, "{}", val), ref fract, ref expo, ref suffix) => write!(out, "{}", val),
            IdlValueExpr::UnaryOp(op, ref expr) => op.write(out).and_then(|_| expr.write(out)),
            IdlValueExpr::BinaryOp(op, ref expr) => op.write(out).and_then(|_| expr.write(out)),
            IdlValueExpr::Expr(ref expr1, ref expr2) => expr1.write(out).and_then(|_| expr2.write(out)),
            IdlValueExpr::Brace(ref expr) => write!(out, "{}", "(")
                .and_then(|_| expr.write(out))
                .and_then(|_| write!(out, "{}", ")")),
            IdlValueExpr::FloatLiteral(ref integral, ref fraction, ref exponent, ref suffix) => {
                integral.as_ref().and_then(|i| write!(out, "{}", i).err());
                fraction.as_ref().and_then(|f| write!(out, ".{}", f).err());
                exponent.as_ref().and_then(|e| write!(out, "e{}", e).err());
                suffix.as_ref().and_then(|s| write!(out, "{}", s).err());
                Ok(())
            }
            IdlValueExpr::ScopedName(ref name) => name.write(out),
            //_ => unimplemented!(),
        };
        Ok(())
    }
}

///
impl Default for IdlValueExpr {
    fn default() -> IdlValueExpr { IdlValueExpr::None }
}

///
#[derive(Clone, Debug)]
pub struct IdlStructMember {
    pub id: String,
    pub type_spec: Box<IdlTypeSpec>,
}

///
impl IdlStructMember {
    ///
    pub fn write<W: Write>(&self, out: &mut W, _level: usize) -> Result<(), Error> {
        write!(out, "{}: ", self.id)
            .and_then(|_| self.type_spec.write(out))
            .and_then(|_| write!(out, ","))
    }
}

///
#[derive(Clone, Debug)]
pub struct IdlSwitchElement {
    pub id: String,
    pub type_spec: Box<IdlTypeSpec>,
}

///
impl IdlSwitchElement {
    ///
    pub fn write<W: Write>(&self, out: &mut W, _level: usize) -> Result<(), Error> {
        write!(out, "{}: ", self.id)
            .and_then(|_| self.type_spec.write(out))
            .and_then(|_| write!(out, ","))
    }
}

///
#[derive(Clone, Debug)]
pub enum IdlSwitchLabel {
    Label(Box<IdlValueExpr>),
    Default,
}

///
#[derive(Clone, Debug)]
pub struct IdlSwitchCase {
    pub labels: Vec<IdlSwitchLabel>,
    pub elem_spec: Box<IdlSwitchElement>,
}

///
impl IdlSwitchCase {
    ///
    pub fn write<W: Write>(&self, out: &mut W, level: usize) -> Result<(), Error> {
        for label in &self.labels {
            match label {
                IdlSwitchLabel::Label(ref val_expr) =>
                    write!(out, "{:indent$}", "", indent = level * INDENTION)
                        .and_then(|_| val_expr.write(out))
                        .and_then(|_| write!(out, "{}", "{"))
                        .and_then(|_| self.elem_spec.write(out, level + 1))
                        .and_then(|_| writeln!(out, "{}", "},"))?,
                IdlSwitchLabel::Default =>
                    write!(out, "{:indent$}default{}", "", "{", indent = level * INDENTION)
                        .and_then(|_| self.elem_spec.write(out, level + 1))
                        .and_then(|_| writeln!(out, "{}", "},"))?,
            }
        }
        Ok(())
    }
}

///
#[derive(Clone, Debug)]
pub enum IdlTypeSpec {
    None,
    ArrayType(Box<IdlTypeSpec>, Vec<Box<IdlValueExpr>>),
    SequenceType(Box<IdlTypeSpec>, Option<Box<IdlValueExpr>>),
    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 IdlTypeSpec {
    ///
    pub fn write<W: Write>(&self, out: &mut W) -> Result<(), Error> {
        let _ = match self {
            IdlTypeSpec::F32Type => write!(out, "f32"),
            IdlTypeSpec::F64Type => write!(out, "f64"),
            IdlTypeSpec::F128Type => write!(out, "f128"),
            IdlTypeSpec::I16Type => write!(out, "i16"),
            IdlTypeSpec::I32Type => write!(out, "i32"),
            IdlTypeSpec::I64Type => write!(out, "i64"),
            IdlTypeSpec::U16Type => write!(out, "u16"),
            IdlTypeSpec::U32Type => write!(out, "u32"),
            IdlTypeSpec::U64Type => write!(out, "u64"),
            IdlTypeSpec::CharType => write!(out, "char"),
            IdlTypeSpec::WideCharType => write!(out, "char"),
            IdlTypeSpec::BooleanType => write!(out, "bool"),
            IdlTypeSpec::OctetType => write!(out, "u8"),
            IdlTypeSpec::StringType(None) => write!(out, "String"),
            IdlTypeSpec::WideStringType(None) => write!(out, "String"),
            // TODO implement String/Sequence bounds
            IdlTypeSpec::StringType(_) => write!(out, "String"),
            // TODO implement String/Sequence bounds for serializer and deserialzer
            IdlTypeSpec::WideStringType(_) => write!(out, "String"),
            IdlTypeSpec::SequenceType(typ_expr, _) => {
                write!(out, "Vec<")
                    .and_then(|_| typ_expr.as_ref().write(out))
                    .and_then(|_| write!(out, ">"))
            }
            IdlTypeSpec::ArrayType(typ_expr, dim_expr_list) => {
                for _ in dim_expr_list { let _ = write!(out, "["); }
                let _ = typ_expr.as_ref().write(out);
                for dim_expr in dim_expr_list {
                    // TODO return result
                    let _ = write!(out, ";")
                        .and_then(|_| dim_expr.as_ref().write(out))
                        .and_then(|_| write!(out, "]"));
                }
                Ok(())
            }
            IdlTypeSpec::ScopedName(ref name) => name.write(out),
            _ => unimplemented!(),
        };

        Ok(())
    }
}

///
impl Default for IdlTypeSpec {
    fn default() -> IdlTypeSpec { IdlTypeSpec::None }
}

///
#[derive(Clone, Debug)]
pub enum IdlTypeDclKind {
    None,
    TypeDcl(String, Box<IdlTypeSpec>),
    StructDcl(String, Vec<Box<IdlStructMember>>),
    UnionDcl(String, Box<IdlTypeSpec>, Vec<IdlSwitchCase>),
    EnumDcl(String,  Vec<String>),
}

///
impl Default for IdlTypeDclKind {
    fn default() -> IdlTypeDclKind { IdlTypeDclKind::None }
}

///
#[derive(Clone,
Debug,
Default)]
pub struct IdlTypeDcl(pub IdlTypeDclKind);

///
impl IdlTypeDcl {
    ///
    ///
    pub fn write<W: Write>(&mut self, out: &mut W, level: usize) -> Result<(), Error> {
        match self.0 {
            IdlTypeDclKind::TypeDcl(ref id, ref type_spec) => {
                // TODO collect/return result
                let _ = writeln!(out, "");
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_DEADCODE, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_NON_CAMEL_CASE_TYPES, indent = level * INDENTION);
                let _ = write!(out, "{:indent$}pub type {} = ", "", id, indent = level * INDENTION);
                let _ = type_spec.as_ref().write(out);
                let _ = writeln!(out, ";");
                Ok(())
            }
            IdlTypeDclKind::StructDcl(ref id, ref type_spec) => {
                // TODO collect/return result
                let _ = writeln!(out, "");
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_DEADCODE, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_NON_CAMEL_CASE_TYPES, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_DERIVE_SERDE, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_DERIVE_CLONE_DEBUG, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}pub struct {} {}", "", id, "{", indent = level * INDENTION);
                for member in type_spec {
                    let _ = write!(out, "{:indent$}", "", indent = (level +1) * INDENTION)
                        .and_then(|_| member.as_ref().write(out, level + 1))
                        .and_then(|_| writeln!(out));
                }
                let _ = writeln!(out, "{:indent$}{}", "", "}", indent = level * INDENTION);
                Ok(())
            }

            IdlTypeDclKind::EnumDcl(ref id, ref enums) => {
                // TODO collect/return result
                let _ = writeln!(out, "");
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_DEADCODE, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_NON_CAMEL_CASE_TYPES, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_DERIVE_SERDE, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_DERIVE_CLONE_DEBUG, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}pub enum {} {}", "", id, "{", indent = level * INDENTION);
                for variant in enums {
                    let _ = writeln!(out, "{:indent$}{},", "", variant, indent = (level +1) * INDENTION);
                }
                let _ = writeln!(out, "{:indent$}{}", "", "}", indent = level * INDENTION);
                Ok(())
            }

            IdlTypeDclKind::UnionDcl(ref id, ref _type_spec, ref switch_cases) => {
                // TODO collect/return result
                let _ = writeln!(out, "");
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_DEADCODE, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_NON_CAMEL_CASE_TYPES, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_DERIVE_SERDE, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}{}", "", ATTR_DERIVE_CLONE_DEBUG, indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}pub enum {} {}", "", id, "{", indent = level * INDENTION);
                for case in switch_cases {
                    let _ = case.write(out, level + 1);
                }
                let _ = writeln!(out, "{:indent$}{}", "", "}", indent = level * INDENTION);

                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}// TODO custom de-/serializer", "", indent = level * INDENTION);
                let _ = writeln!(out, "{:indent$}//", "", indent = level * INDENTION);

                Ok(())
            }
            _ => Ok(())
        }
    }
}

///
#[derive(Clone,
Default,
Debug)]
pub struct IdlConstDcl {
    pub id: String,
    pub typedcl: Box<IdlTypeSpec>,
    pub value: Box<IdlValueExpr>,
}

///
impl IdlConstDcl {
    ///
    ///
    pub fn write<W: Write>(&mut self, out: &mut W, level: usize) -> Result<(), Error> {
        writeln!(out, "{:indent$}{}", "", ATTR_ALLOW_DEADCODE, indent = level * INDENTION)
            .and_then(|_| write!(out, "{:indent$}const {}", "", self.id, indent = level * INDENTION))
            .and_then(|_| write!(out, ": "))
            .and_then(|_| self.typedcl.write(out))
            .and_then(|_| write!(out, " = "))
            .and_then(|_| self.value.write(out))
            .and_then(|_| writeln!(out, ";"))
    }
}

///
#[derive(Clone,
Default, Debug)]
pub struct IdlModule {
    pub id: Option<String>,
    pub level: usize,
    pub modules: LinkedHashMap<String, Box<IdlModule>>,
    pub types: LinkedHashMap<String, Box<IdlTypeDcl>>,
    pub constants: LinkedHashMap<String, Box<IdlConstDcl>>,
}


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

    pub fn write<W: Write>(&mut self, out: &mut W, level: usize) -> Result<(), Error> {
        let _prolog = match self.id {
            Some(ref id_str) =>
                writeln!(out, "{:indent$}{}", "",
                         ATTR_ALLOW_NON_SNAKE_CASE, indent = level * INDENTION)
                    .and_then(|_| writeln!(out, "{:indent$}pub mod {} {}", "", id_str, "{", indent = level * INDENTION)),

            _ => write!(out, ""),
        };

        let add: usize = if self.id.is_some() { 1 } else { 0 };

        let _ = writeln!(out, "{:indent$}{}", "",
                         ATTR_ALLOW_UNUSED_IMPORTS, indent = (level + add) * INDENTION)
            .and_then(|_| writeln!(out, "{:indent$}{}", "",
                                   IMPORT_SERDE, indent = (level + add) * INDENTION));

        for typ in self.types.entries() {
            typ.into_mut().write(out, level + add)?;
        }

        for module in self.modules.entries() {
            module.into_mut().write(out, level + add)?;
        }

        for cnst in self.constants.entries() {
            cnst.into_mut().write(out, level + add)?;
        }

        let _epilog = match self.id {
            Some(_) => writeln!(out, "{:indent$}{}", "", "}", indent = level * INDENTION),
            _ => write!(out, ""),
        };

        Ok(())
    }
}