rustorb-dds-ros2 0.4.0

The ROS 2 conventions on DDS for rustorb-dds: names, interface types from .msg/.srv, RIHS01 type hashes, node discovery
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
//! The ROS 2 interface definition languages `.msg` and `.srv`, parsed.
//!
//! A `.msg` file is one field or constant a line, after the ROS 2
//! documentation "Interfaces":
//!
//! ```text
//! # a comment
//! int32 x                 # a field
//! int32 y 5               # a field with a default value
//! string<=10 name "abc"   # a bounded string
//! float64[3] v            # an array; [] a sequence, [<=N] a bounded one
//! geometry_msgs/Point p   # a message of another package
//! Point q                 # a message of the same package
//! int32 MAX=100           # a constant (its name in capitals)
//! ```
//!
//! A `.srv` file is a request and a response, separated by a line `---`.
//! A bare `Header` is `std_msgs/Header`, as in ROS 1.

use crate::names::{InterfaceKind, TypeName, validate_package_name, validate_type_base_name};
use crate::{Error, Result};

/// A primitive type of the interface languages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Primitive {
    Bool,
    /// `byte`: an octet.
    Byte,
    /// `char`: in ROS 2, an unsigned 8-bit integer.
    Char,
    Float32,
    Float64,
    Int8,
    Uint8,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
}

impl Primitive {
    /// The primitive of a name in a `.msg` file.
    pub fn from_name(s: &str) -> Option<Primitive> {
        Some(match s {
            "bool" => Primitive::Bool,
            "byte" => Primitive::Byte,
            "char" => Primitive::Char,
            "float32" => Primitive::Float32,
            "float64" => Primitive::Float64,
            "int8" => Primitive::Int8,
            "uint8" => Primitive::Uint8,
            "int16" => Primitive::Int16,
            "uint16" => Primitive::Uint16,
            "int32" => Primitive::Int32,
            "uint32" => Primitive::Uint32,
            "int64" => Primitive::Int64,
            "uint64" => Primitive::Uint64,
            _ => return None,
        })
    }

    /// The name in a `.msg` file.
    pub fn name(self) -> &'static str {
        match self {
            Primitive::Bool => "bool",
            Primitive::Byte => "byte",
            Primitive::Char => "char",
            Primitive::Float32 => "float32",
            Primitive::Float64 => "float64",
            Primitive::Int8 => "int8",
            Primitive::Uint8 => "uint8",
            Primitive::Int16 => "int16",
            Primitive::Uint16 => "uint16",
            Primitive::Int32 => "int32",
            Primitive::Uint32 => "uint32",
            Primitive::Int64 => "int64",
            Primitive::Uint64 => "uint64",
        }
    }

    /// The range of an integer type, as `i128`; `None` for the others.
    pub fn integer_range(self) -> Option<(i128, i128)> {
        Some(match self {
            Primitive::Byte | Primitive::Char | Primitive::Uint8 => (0, u8::MAX as i128),
            Primitive::Int8 => (i8::MIN as i128, i8::MAX as i128),
            Primitive::Int16 => (i16::MIN as i128, i16::MAX as i128),
            Primitive::Uint16 => (0, u16::MAX as i128),
            Primitive::Int32 => (i32::MIN as i128, i32::MAX as i128),
            Primitive::Uint32 => (0, u32::MAX as i128),
            Primitive::Int64 => (i64::MIN as i128, i64::MAX as i128),
            Primitive::Uint64 => (0, u64::MAX as i128),
            Primitive::Bool | Primitive::Float32 | Primitive::Float64 => return None,
        })
    }
}

/// The type of a field, before the messages it names are found.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum BaseSpec {
    /// A primitive.
    Primitive(Primitive),
    /// `string` or `string<=N`.
    String {
        /// `wstring`.
        wide: bool,
        /// The bound, in characters; `None` for none.
        bound: Option<u32>,
    },
    /// A message.
    Message(TypeName),
}

/// Whether a field is one value, an array or a sequence.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ArraySpec {
    /// One value.
    None,
    /// `T[N]`.
    Fixed(u32),
    /// `T[<=N]`.
    Bounded(u32),
    /// `T[]`.
    Unbounded,
}

/// The type of a field.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TypeSpec {
    /// The element type.
    pub base: BaseSpec,
    /// One value, an array or a sequence.
    pub array: ArraySpec,
}

/// A field of a message.
#[derive(Clone, Debug, PartialEq)]
pub struct FieldSpec {
    /// The name.
    pub name: String,
    /// The type.
    pub ty: TypeSpec,
    /// The default value, as written.
    pub default: Option<String>,
}

/// A constant of a message.
#[derive(Clone, Debug, PartialEq)]
pub struct ConstantSpec {
    /// The name.
    pub name: String,
    /// The type: a primitive or a string.
    pub ty: TypeSpec,
    /// The value, as written.
    pub value: String,
}

/// A message, as written.
#[derive(Clone, Debug, PartialEq)]
pub struct MessageSpec {
    /// Its name.
    pub name: TypeName,
    /// Its fields, in order.
    pub fields: Vec<FieldSpec>,
    /// Its constants, in order.
    pub constants: Vec<ConstantSpec>,
}

/// A service, as written.
#[derive(Clone, Debug, PartialEq)]
pub struct ServiceSpec {
    /// Its name, `pkg/srv/Name`.
    pub name: TypeName,
    /// The request, `pkg/srv/Name_Request`.
    pub request: MessageSpec,
    /// The response, `pkg/srv/Name_Response`.
    pub response: MessageSpec,
}

/// Removes a comment: from a `#` that is not in a quoted string.
fn strip_comment(line: &str) -> &str {
    let mut quote: Option<char> = None;
    let mut escaped = false;
    for (i, c) in line.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        match quote {
            Some(q) if c == q => quote = None,
            Some(_) if c == '\\' => escaped = true,
            Some(_) => {}
            None if c == '"' || c == '\'' => quote = Some(c),
            None if c == '#' => return &line[..i],
            None => {}
        }
    }
    line
}

fn parse_u32(s: &str, what: &str) -> Result<u32> {
    s.trim()
        .parse::<u32>()
        .map_err(|_| Error::Parse(format!("{what}: {s:?} is not a number")))
}

/// Parses the type of a field in a message of `package`.
pub fn parse_type(s: &str, package: &str) -> Result<TypeSpec> {
    let (base, array) = match s.find('[') {
        Some(i) => {
            let inner = s[i..]
                .strip_prefix('[')
                .and_then(|r| r.strip_suffix(']'))
                .ok_or_else(|| Error::Parse(format!("type {s:?}: bad array")))?;
            let array = if inner.is_empty() {
                ArraySpec::Unbounded
            } else if let Some(n) = inner.strip_prefix("<=") {
                ArraySpec::Bounded(parse_u32(n, s)?)
            } else {
                ArraySpec::Fixed(parse_u32(inner, s)?)
            };
            (&s[..i], array)
        }
        None => (s, ArraySpec::None),
    };
    let string = |wide: bool, rest: &str| -> Result<BaseSpec> {
        let bound = match rest {
            "" => None,
            r => match r.strip_prefix("<=") {
                Some(n) => Some(parse_u32(n, s)?),
                None => return Err(Error::Parse(format!("type {s:?}: bad string bound"))),
            },
        };
        Ok(BaseSpec::String { wide, bound })
    };
    let base = if let Some(p) = Primitive::from_name(base) {
        BaseSpec::Primitive(p)
    } else if let Some(rest) = base.strip_prefix("wstring") {
        string(true, rest)?
    } else if let Some(rest) = base.strip_prefix("string") {
        string(false, rest)?
    } else if base == "Header" {
        BaseSpec::Message(TypeName::message("std_msgs", "Header")?)
    } else if base.contains('/') {
        BaseSpec::Message(TypeName::parse(base)?)
    } else {
        validate_type_base_name(base)?;
        BaseSpec::Message(TypeName::message(package, base)?)
    };
    if let BaseSpec::Message(t) = &base
        && t.kind != InterfaceKind::Message
    {
        return Err(Error::Parse(format!(
            "type {s:?}: a field can only be a message"
        )));
    }
    Ok(TypeSpec { base, array })
}

fn is_field_name(s: &str) -> bool {
    s.starts_with(|c: char| c.is_ascii_lowercase())
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
        && !s.contains("__")
        && !s.ends_with('_')
}

fn is_constant_name(s: &str) -> bool {
    s.starts_with(|c: char| c.is_ascii_uppercase())
        && s.chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}

fn split_first_word(s: &str) -> (&str, &str) {
    match s.find(char::is_whitespace) {
        Some(i) => (&s[..i], s[i..].trim_start()),
        None => (s, ""),
    }
}

/// Parses the text of a `.msg` file of message `name`.
pub fn parse_message(name: &TypeName, text: &str) -> Result<MessageSpec> {
    let mut msg = MessageSpec {
        name: name.clone(),
        fields: Vec::new(),
        constants: Vec::new(),
    };
    for (no, raw) in text.lines().enumerate() {
        let at = |e: Error| Error::Parse(format!("{name}, line {}: {e}", no + 1));
        let line = strip_comment(raw).trim();
        if line.is_empty() {
            continue;
        }
        let (ty, rest) = split_first_word(line);
        let ty = parse_type(ty, &name.package).map_err(at)?;
        if rest.is_empty() {
            return Err(at(Error::Parse("a field without a name".into())));
        }
        let name_end = rest
            .find(|c: char| c.is_whitespace() || c == '=')
            .unwrap_or(rest.len());
        let (field, after) = (&rest[..name_end], rest[name_end..].trim_start());
        if let Some(value) = after.strip_prefix('=') {
            if !is_constant_name(field) {
                return Err(at(Error::Parse(format!(
                    "constant name {field:?} is not in capitals"
                ))));
            }
            if ty.array != ArraySpec::None || matches!(ty.base, BaseSpec::Message(_)) {
                return Err(at(Error::Parse(format!(
                    "constant {field}: only primitives and strings can be constants"
                ))));
            }
            msg.constants.push(ConstantSpec {
                name: field.to_string(),
                ty,
                value: value.trim().to_string(),
            });
        } else {
            if !is_field_name(field) {
                return Err(at(Error::Parse(format!(
                    "field name {field:?} is not [a-z][a-z0-9_]* (without '__', not ending in '_')"
                ))));
            }
            if msg.fields.iter().any(|f| f.name == field) {
                return Err(at(Error::Parse(format!("field {field} twice"))));
            }
            msg.fields.push(FieldSpec {
                name: field.to_string(),
                ty,
                default: (!after.is_empty()).then(|| after.to_string()),
            });
        }
    }
    Ok(msg)
}

/// Parses the text of a `.srv` file of service `name` (`pkg/srv/Name`).
pub fn parse_service(name: &TypeName, text: &str) -> Result<ServiceSpec> {
    validate_package_name(&name.package)?;
    let mut parts = Vec::new();
    let mut current = String::new();
    for line in text.lines() {
        if strip_comment(line).trim() == "---" {
            parts.push(std::mem::take(&mut current));
        } else {
            current.push_str(line);
            current.push('\n');
        }
    }
    parts.push(current);
    if parts.len() != 2 {
        return Err(Error::Parse(format!(
            "{name}: a service has one '---' between request and response"
        )));
    }
    Ok(ServiceSpec {
        name: name.clone(),
        request: parse_message(&name.with_suffix("_Request"), &parts[0])?,
        response: parse_message(&name.with_suffix("_Response"), &parts[1])?,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn message() {
        let name = TypeName::parse("pkg/msg/Test").unwrap();
        let m = parse_message(
            &name,
            "# comment\n\
             int32 x\n\
             int32 y 5 # five\n\
             string<=10 s \"a # b\"\n\
             float64[3] v [1.0, 2.0, 3.0]\n\
             uint8[<=4] b\n\
             Point[] points\n\
             geometry_msgs/Pose pose\n\
             Header header\n\
             int32 MAX=100\n\
             string NAME = 'x'\n",
        )
        .unwrap();
        assert_eq!(m.fields.len(), 8);
        assert_eq!(m.fields[1].default.as_deref(), Some("5"));
        assert_eq!(m.fields[2].default.as_deref(), Some("\"a # b\""));
        assert_eq!(
            m.fields[2].ty.base,
            BaseSpec::String {
                wide: false,
                bound: Some(10)
            }
        );
        assert_eq!(m.fields[3].ty.array, ArraySpec::Fixed(3));
        assert_eq!(m.fields[4].ty.array, ArraySpec::Bounded(4));
        assert_eq!(
            m.fields[5].ty.base,
            BaseSpec::Message(TypeName::parse("pkg/msg/Point").unwrap())
        );
        assert_eq!(m.fields[5].ty.array, ArraySpec::Unbounded);
        assert_eq!(
            m.fields[7].ty.base,
            BaseSpec::Message(TypeName::parse("std_msgs/msg/Header").unwrap())
        );
        assert_eq!(m.constants.len(), 2);
        assert_eq!(m.constants[1].value, "'x'");
        assert!(parse_message(&name, "int32 X").is_err());
        assert!(parse_message(&name, "int32 x\nint32 x").is_err());
        assert!(parse_message(&name, "int32 x__y").is_err());
        assert!(parse_message(&name, "int32[] MAX=1").is_err());
        assert!(parse_message(&name, "int32").is_err());
    }

    #[test]
    fn service() {
        let name = TypeName::parse("example_interfaces/srv/AddTwoInts").unwrap();
        let s = parse_service(&name, "int64 a\nint64 b\n---\nint64 sum\n").unwrap();
        assert_eq!(
            s.request.name.to_string(),
            "example_interfaces/srv/AddTwoInts_Request"
        );
        assert_eq!(s.request.fields.len(), 2);
        assert_eq!(s.response.fields[0].name, "sum");
        assert!(parse_service(&name, "int64 a\n").is_err());
    }
}