Skip to main content

rustorb_dds_ros2/
msg.rs

1//! The ROS 2 interface definition languages `.msg` and `.srv`, parsed.
2//!
3//! A `.msg` file is one field or constant a line, after the ROS 2
4//! documentation "Interfaces":
5//!
6//! ```text
7//! # a comment
8//! int32 x                 # a field
9//! int32 y 5               # a field with a default value
10//! string<=10 name "abc"   # a bounded string
11//! float64[3] v            # an array; [] a sequence, [<=N] a bounded one
12//! geometry_msgs/Point p   # a message of another package
13//! Point q                 # a message of the same package
14//! int32 MAX=100           # a constant (its name in capitals)
15//! ```
16//!
17//! A `.srv` file is a request and a response, separated by a line `---`.
18//! A bare `Header` is `std_msgs/Header`, as in ROS 1.
19
20use crate::names::{InterfaceKind, TypeName, validate_package_name, validate_type_base_name};
21use crate::{Error, Result};
22
23/// A primitive type of the interface languages.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25#[allow(missing_docs)]
26pub enum Primitive {
27    Bool,
28    /// `byte`: an octet.
29    Byte,
30    /// `char`: in ROS 2, an unsigned 8-bit integer.
31    Char,
32    Float32,
33    Float64,
34    Int8,
35    Uint8,
36    Int16,
37    Uint16,
38    Int32,
39    Uint32,
40    Int64,
41    Uint64,
42}
43
44impl Primitive {
45    /// The primitive of a name in a `.msg` file.
46    pub fn from_name(s: &str) -> Option<Primitive> {
47        Some(match s {
48            "bool" => Primitive::Bool,
49            "byte" => Primitive::Byte,
50            "char" => Primitive::Char,
51            "float32" => Primitive::Float32,
52            "float64" => Primitive::Float64,
53            "int8" => Primitive::Int8,
54            "uint8" => Primitive::Uint8,
55            "int16" => Primitive::Int16,
56            "uint16" => Primitive::Uint16,
57            "int32" => Primitive::Int32,
58            "uint32" => Primitive::Uint32,
59            "int64" => Primitive::Int64,
60            "uint64" => Primitive::Uint64,
61            _ => return None,
62        })
63    }
64
65    /// The name in a `.msg` file.
66    pub fn name(self) -> &'static str {
67        match self {
68            Primitive::Bool => "bool",
69            Primitive::Byte => "byte",
70            Primitive::Char => "char",
71            Primitive::Float32 => "float32",
72            Primitive::Float64 => "float64",
73            Primitive::Int8 => "int8",
74            Primitive::Uint8 => "uint8",
75            Primitive::Int16 => "int16",
76            Primitive::Uint16 => "uint16",
77            Primitive::Int32 => "int32",
78            Primitive::Uint32 => "uint32",
79            Primitive::Int64 => "int64",
80            Primitive::Uint64 => "uint64",
81        }
82    }
83
84    /// The range of an integer type, as `i128`; `None` for the others.
85    pub fn integer_range(self) -> Option<(i128, i128)> {
86        Some(match self {
87            Primitive::Byte | Primitive::Char | Primitive::Uint8 => (0, u8::MAX as i128),
88            Primitive::Int8 => (i8::MIN as i128, i8::MAX as i128),
89            Primitive::Int16 => (i16::MIN as i128, i16::MAX as i128),
90            Primitive::Uint16 => (0, u16::MAX as i128),
91            Primitive::Int32 => (i32::MIN as i128, i32::MAX as i128),
92            Primitive::Uint32 => (0, u32::MAX as i128),
93            Primitive::Int64 => (i64::MIN as i128, i64::MAX as i128),
94            Primitive::Uint64 => (0, u64::MAX as i128),
95            Primitive::Bool | Primitive::Float32 | Primitive::Float64 => return None,
96        })
97    }
98}
99
100/// The type of a field, before the messages it names are found.
101#[derive(Clone, Debug, PartialEq, Eq, Hash)]
102pub enum BaseSpec {
103    /// A primitive.
104    Primitive(Primitive),
105    /// `string` or `string<=N`.
106    String {
107        /// `wstring`.
108        wide: bool,
109        /// The bound, in characters; `None` for none.
110        bound: Option<u32>,
111    },
112    /// A message.
113    Message(TypeName),
114}
115
116/// Whether a field is one value, an array or a sequence.
117#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
118pub enum ArraySpec {
119    /// One value.
120    None,
121    /// `T[N]`.
122    Fixed(u32),
123    /// `T[<=N]`.
124    Bounded(u32),
125    /// `T[]`.
126    Unbounded,
127}
128
129/// The type of a field.
130#[derive(Clone, Debug, PartialEq, Eq, Hash)]
131pub struct TypeSpec {
132    /// The element type.
133    pub base: BaseSpec,
134    /// One value, an array or a sequence.
135    pub array: ArraySpec,
136}
137
138/// A field of a message.
139#[derive(Clone, Debug, PartialEq)]
140pub struct FieldSpec {
141    /// The name.
142    pub name: String,
143    /// The type.
144    pub ty: TypeSpec,
145    /// The default value, as written.
146    pub default: Option<String>,
147}
148
149/// A constant of a message.
150#[derive(Clone, Debug, PartialEq)]
151pub struct ConstantSpec {
152    /// The name.
153    pub name: String,
154    /// The type: a primitive or a string.
155    pub ty: TypeSpec,
156    /// The value, as written.
157    pub value: String,
158}
159
160/// A message, as written.
161#[derive(Clone, Debug, PartialEq)]
162pub struct MessageSpec {
163    /// Its name.
164    pub name: TypeName,
165    /// Its fields, in order.
166    pub fields: Vec<FieldSpec>,
167    /// Its constants, in order.
168    pub constants: Vec<ConstantSpec>,
169}
170
171/// A service, as written.
172#[derive(Clone, Debug, PartialEq)]
173pub struct ServiceSpec {
174    /// Its name, `pkg/srv/Name`.
175    pub name: TypeName,
176    /// The request, `pkg/srv/Name_Request`.
177    pub request: MessageSpec,
178    /// The response, `pkg/srv/Name_Response`.
179    pub response: MessageSpec,
180}
181
182/// Removes a comment: from a `#` that is not in a quoted string.
183fn strip_comment(line: &str) -> &str {
184    let mut quote: Option<char> = None;
185    let mut escaped = false;
186    for (i, c) in line.char_indices() {
187        if escaped {
188            escaped = false;
189            continue;
190        }
191        match quote {
192            Some(q) if c == q => quote = None,
193            Some(_) if c == '\\' => escaped = true,
194            Some(_) => {}
195            None if c == '"' || c == '\'' => quote = Some(c),
196            None if c == '#' => return &line[..i],
197            None => {}
198        }
199    }
200    line
201}
202
203fn parse_u32(s: &str, what: &str) -> Result<u32> {
204    s.trim()
205        .parse::<u32>()
206        .map_err(|_| Error::Parse(format!("{what}: {s:?} is not a number")))
207}
208
209/// Parses the type of a field in a message of `package`.
210pub fn parse_type(s: &str, package: &str) -> Result<TypeSpec> {
211    let (base, array) = match s.find('[') {
212        Some(i) => {
213            let inner = s[i..]
214                .strip_prefix('[')
215                .and_then(|r| r.strip_suffix(']'))
216                .ok_or_else(|| Error::Parse(format!("type {s:?}: bad array")))?;
217            let array = if inner.is_empty() {
218                ArraySpec::Unbounded
219            } else if let Some(n) = inner.strip_prefix("<=") {
220                ArraySpec::Bounded(parse_u32(n, s)?)
221            } else {
222                ArraySpec::Fixed(parse_u32(inner, s)?)
223            };
224            (&s[..i], array)
225        }
226        None => (s, ArraySpec::None),
227    };
228    let string = |wide: bool, rest: &str| -> Result<BaseSpec> {
229        let bound = match rest {
230            "" => None,
231            r => match r.strip_prefix("<=") {
232                Some(n) => Some(parse_u32(n, s)?),
233                None => return Err(Error::Parse(format!("type {s:?}: bad string bound"))),
234            },
235        };
236        Ok(BaseSpec::String { wide, bound })
237    };
238    let base = if let Some(p) = Primitive::from_name(base) {
239        BaseSpec::Primitive(p)
240    } else if let Some(rest) = base.strip_prefix("wstring") {
241        string(true, rest)?
242    } else if let Some(rest) = base.strip_prefix("string") {
243        string(false, rest)?
244    } else if base == "Header" {
245        BaseSpec::Message(TypeName::message("std_msgs", "Header")?)
246    } else if base.contains('/') {
247        BaseSpec::Message(TypeName::parse(base)?)
248    } else {
249        validate_type_base_name(base)?;
250        BaseSpec::Message(TypeName::message(package, base)?)
251    };
252    if let BaseSpec::Message(t) = &base
253        && t.kind != InterfaceKind::Message
254    {
255        return Err(Error::Parse(format!(
256            "type {s:?}: a field can only be a message"
257        )));
258    }
259    Ok(TypeSpec { base, array })
260}
261
262fn is_field_name(s: &str) -> bool {
263    s.starts_with(|c: char| c.is_ascii_lowercase())
264        && s.chars()
265            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
266        && !s.contains("__")
267        && !s.ends_with('_')
268}
269
270fn is_constant_name(s: &str) -> bool {
271    s.starts_with(|c: char| c.is_ascii_uppercase())
272        && s.chars()
273            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
274}
275
276fn split_first_word(s: &str) -> (&str, &str) {
277    match s.find(char::is_whitespace) {
278        Some(i) => (&s[..i], s[i..].trim_start()),
279        None => (s, ""),
280    }
281}
282
283/// Parses the text of a `.msg` file of message `name`.
284pub fn parse_message(name: &TypeName, text: &str) -> Result<MessageSpec> {
285    let mut msg = MessageSpec {
286        name: name.clone(),
287        fields: Vec::new(),
288        constants: Vec::new(),
289    };
290    for (no, raw) in text.lines().enumerate() {
291        let at = |e: Error| Error::Parse(format!("{name}, line {}: {e}", no + 1));
292        let line = strip_comment(raw).trim();
293        if line.is_empty() {
294            continue;
295        }
296        let (ty, rest) = split_first_word(line);
297        let ty = parse_type(ty, &name.package).map_err(at)?;
298        if rest.is_empty() {
299            return Err(at(Error::Parse("a field without a name".into())));
300        }
301        let name_end = rest
302            .find(|c: char| c.is_whitespace() || c == '=')
303            .unwrap_or(rest.len());
304        let (field, after) = (&rest[..name_end], rest[name_end..].trim_start());
305        if let Some(value) = after.strip_prefix('=') {
306            if !is_constant_name(field) {
307                return Err(at(Error::Parse(format!(
308                    "constant name {field:?} is not in capitals"
309                ))));
310            }
311            if ty.array != ArraySpec::None || matches!(ty.base, BaseSpec::Message(_)) {
312                return Err(at(Error::Parse(format!(
313                    "constant {field}: only primitives and strings can be constants"
314                ))));
315            }
316            msg.constants.push(ConstantSpec {
317                name: field.to_string(),
318                ty,
319                value: value.trim().to_string(),
320            });
321        } else {
322            if !is_field_name(field) {
323                return Err(at(Error::Parse(format!(
324                    "field name {field:?} is not [a-z][a-z0-9_]* (without '__', not ending in '_')"
325                ))));
326            }
327            if msg.fields.iter().any(|f| f.name == field) {
328                return Err(at(Error::Parse(format!("field {field} twice"))));
329            }
330            msg.fields.push(FieldSpec {
331                name: field.to_string(),
332                ty,
333                default: (!after.is_empty()).then(|| after.to_string()),
334            });
335        }
336    }
337    Ok(msg)
338}
339
340/// Parses the text of a `.srv` file of service `name` (`pkg/srv/Name`).
341pub fn parse_service(name: &TypeName, text: &str) -> Result<ServiceSpec> {
342    validate_package_name(&name.package)?;
343    let mut parts = Vec::new();
344    let mut current = String::new();
345    for line in text.lines() {
346        if strip_comment(line).trim() == "---" {
347            parts.push(std::mem::take(&mut current));
348        } else {
349            current.push_str(line);
350            current.push('\n');
351        }
352    }
353    parts.push(current);
354    if parts.len() != 2 {
355        return Err(Error::Parse(format!(
356            "{name}: a service has one '---' between request and response"
357        )));
358    }
359    Ok(ServiceSpec {
360        name: name.clone(),
361        request: parse_message(&name.with_suffix("_Request"), &parts[0])?,
362        response: parse_message(&name.with_suffix("_Response"), &parts[1])?,
363    })
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[test]
371    fn message() {
372        let name = TypeName::parse("pkg/msg/Test").unwrap();
373        let m = parse_message(
374            &name,
375            "# comment\n\
376             int32 x\n\
377             int32 y 5 # five\n\
378             string<=10 s \"a # b\"\n\
379             float64[3] v [1.0, 2.0, 3.0]\n\
380             uint8[<=4] b\n\
381             Point[] points\n\
382             geometry_msgs/Pose pose\n\
383             Header header\n\
384             int32 MAX=100\n\
385             string NAME = 'x'\n",
386        )
387        .unwrap();
388        assert_eq!(m.fields.len(), 8);
389        assert_eq!(m.fields[1].default.as_deref(), Some("5"));
390        assert_eq!(m.fields[2].default.as_deref(), Some("\"a # b\""));
391        assert_eq!(
392            m.fields[2].ty.base,
393            BaseSpec::String {
394                wide: false,
395                bound: Some(10)
396            }
397        );
398        assert_eq!(m.fields[3].ty.array, ArraySpec::Fixed(3));
399        assert_eq!(m.fields[4].ty.array, ArraySpec::Bounded(4));
400        assert_eq!(
401            m.fields[5].ty.base,
402            BaseSpec::Message(TypeName::parse("pkg/msg/Point").unwrap())
403        );
404        assert_eq!(m.fields[5].ty.array, ArraySpec::Unbounded);
405        assert_eq!(
406            m.fields[7].ty.base,
407            BaseSpec::Message(TypeName::parse("std_msgs/msg/Header").unwrap())
408        );
409        assert_eq!(m.constants.len(), 2);
410        assert_eq!(m.constants[1].value, "'x'");
411        assert!(parse_message(&name, "int32 X").is_err());
412        assert!(parse_message(&name, "int32 x\nint32 x").is_err());
413        assert!(parse_message(&name, "int32 x__y").is_err());
414        assert!(parse_message(&name, "int32[] MAX=1").is_err());
415        assert!(parse_message(&name, "int32").is_err());
416    }
417
418    #[test]
419    fn service() {
420        let name = TypeName::parse("example_interfaces/srv/AddTwoInts").unwrap();
421        let s = parse_service(&name, "int64 a\nint64 b\n---\nint64 sum\n").unwrap();
422        assert_eq!(
423            s.request.name.to_string(),
424            "example_interfaces/srv/AddTwoInts_Request"
425        );
426        assert_eq!(s.request.fields.len(), 2);
427        assert_eq!(s.response.fields[0].name, "sum");
428        assert!(parse_service(&name, "int64 a\n").is_err());
429    }
430}