Skip to main content

rustorb_dds_ros2/
library.rs

1//! ROS 2 interface types found in `.msg` and `.srv` files, with their
2//! DDS types (DynamicType), descriptions and RIHS01 hashes.
3
4use std::collections::{BTreeMap, HashMap};
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7
8use rustorb_xtypes::dynamic::DynamicType;
9use rustorb_xtypes::types::{
10    ArrayType, Element, Extensibility, Primitive as XPrimitive, SequenceType, StructMember,
11    StructType, Type,
12};
13
14use crate::msg::{
15    ArraySpec, BaseSpec, MessageSpec, Primitive, TypeSpec, parse_message, parse_service,
16};
17use crate::names::{InterfaceKind, TypeName};
18use crate::type_description::{
19    Field as DescField, FieldType as DescFieldType, IndividualTypeDescription, TypeDescription,
20    TypeHash, field_type,
21};
22use crate::value::{Value, check_length, parse_literal};
23use crate::{Error, Result};
24
25/// The member ROS 2 gives a message without fields, since a DDS struct
26/// has at least one.
27pub const EMPTY_MESSAGE_MEMBER: &str = "structure_needs_at_least_one_member";
28
29/// The element type of a field, its messages found.
30#[derive(Clone, Debug)]
31pub enum BaseType {
32    /// A primitive.
33    Primitive(Primitive),
34    /// `string` or `wstring`.
35    String {
36        /// `wstring`.
37        wide: bool,
38        /// The bound, in characters; `None` for none.
39        bound: Option<u32>,
40    },
41    /// A message.
42    Message(MessageType),
43}
44
45impl BaseType {
46    pub(crate) fn describe(&self) -> String {
47        match self {
48            BaseType::Primitive(p) => p.name().to_string(),
49            BaseType::String { wide, bound } => format!(
50                "{}{}",
51                if *wide { "wstring" } else { "string" },
52                bound.map(|b| format!("<={b}")).unwrap_or_default()
53            ),
54            BaseType::Message(m) => m.name().to_string(),
55        }
56    }
57}
58
59/// The type of a field.
60#[derive(Clone, Debug)]
61pub struct FieldType {
62    /// The element type.
63    pub base: BaseType,
64    /// One value, an array or a sequence.
65    pub array: ArraySpec,
66}
67
68/// A field of a message.
69#[derive(Clone, Debug)]
70pub struct Field {
71    /// The name.
72    pub name: String,
73    /// The type.
74    pub ty: FieldType,
75    /// The default value of the `.msg` file.
76    pub default: Option<Value>,
77}
78
79/// A constant of a message.
80#[derive(Clone, Debug)]
81pub struct Constant {
82    /// The name.
83    pub name: String,
84    /// The type.
85    pub ty: TypeSpec,
86    /// The value.
87    pub value: Value,
88}
89
90#[derive(Debug)]
91struct MessageInner {
92    name: TypeName,
93    fields: Vec<Field>,
94    constants: Vec<Constant>,
95    dynamic: DynamicType,
96    individual: IndividualTypeDescription,
97    /// The descriptions of the types it uses, by name.
98    referenced: BTreeMap<String, IndividualTypeDescription>,
99    hash: TypeHash,
100}
101
102/// A ROS 2 message type: `pkg/msg/Name`, or the request, response or
103/// event of a service.
104///
105/// A message without fields has the one field
106/// [`EMPTY_MESSAGE_MEMBER`] of type `uint8`, in its DDS type and in its
107/// description, as ROS 2 gives it.
108#[derive(Clone, Debug)]
109pub struct MessageType(Arc<MessageInner>);
110
111impl MessageType {
112    /// Its name.
113    pub fn name(&self) -> &TypeName {
114        &self.0.name
115    }
116
117    /// Its fields, in order.
118    pub fn fields(&self) -> &[Field] {
119        &self.0.fields
120    }
121
122    /// Its constants.
123    pub fn constants(&self) -> &[Constant] {
124        &self.0.constants
125    }
126
127    /// Its DDS type, `pkg::msg::dds_::Name_`, for
128    /// [`DomainParticipant::create_dynamic_topic`](rustorb_dds::DomainParticipant::create_dynamic_topic).
129    pub fn dynamic_type(&self) -> &DynamicType {
130        &self.0.dynamic
131    }
132
133    /// Its description (REP-2011).
134    pub fn type_description(&self) -> TypeDescription {
135        TypeDescription {
136            type_description: self.0.individual.clone(),
137            referenced_type_descriptions: self.0.referenced.values().cloned().collect(),
138        }
139    }
140
141    /// Its RIHS01 hash.
142    pub fn type_hash(&self) -> TypeHash {
143        self.0.hash
144    }
145}
146
147impl PartialEq for MessageType {
148    fn eq(&self, other: &Self) -> bool {
149        Arc::ptr_eq(&self.0, &other.0) || self.0.name == other.0.name && self.0.hash == other.0.hash
150    }
151}
152
153/// A ROS 2 service type `pkg/srv/Name`.
154#[derive(Clone, Debug)]
155pub struct ServiceType {
156    name: TypeName,
157    request: MessageType,
158    response: MessageType,
159    event: MessageType,
160    description: TypeDescription,
161}
162
163impl ServiceType {
164    /// Its name.
165    pub fn name(&self) -> &TypeName {
166        &self.name
167    }
168
169    /// The request, `pkg/srv/Name_Request`: the type of the topic `rq/`.
170    pub fn request(&self) -> &MessageType {
171        &self.request
172    }
173
174    /// The response, `pkg/srv/Name_Response`: the type of the topic `rr/`.
175    pub fn response(&self) -> &MessageType {
176        &self.response
177    }
178
179    /// The event of service introspection, `pkg/srv/Name_Event`.
180    pub fn event(&self) -> &MessageType {
181        &self.event
182    }
183
184    /// The description of the service: `pkg/srv/Name`, whose fields are
185    /// its request, response and event.
186    pub fn type_description(&self) -> &TypeDescription {
187        &self.description
188    }
189
190    /// The RIHS01 hash of the service.
191    pub fn type_hash(&self) -> TypeHash {
192        self.description.hash()
193    }
194}
195
196/// Definitions this crate needs even when no `.msg` file is found: those
197/// of service events and of `ros_discovery_info`. Written from their
198/// documented fields; files found on the search path come first.
199const BUILTIN: &[(&str, &str)] = &[
200    ("builtin_interfaces/msg/Time", "int32 sec\nuint32 nanosec\n"),
201    (
202        "service_msgs/msg/ServiceEventInfo",
203        "uint8 REQUEST_SENT = 0\nuint8 REQUEST_RECEIVED = 1\nuint8 RESPONSE_SENT = 2\n\
204         uint8 RESPONSE_RECEIVED = 3\nuint8 event_type\nbuiltin_interfaces/Time stamp\n\
205         char[16] client_gid\nint64 sequence_number\n",
206    ),
207    ("rmw_dds_common/msg/Gid", "char[16] data\n"),
208    (
209        "rmw_dds_common/msg/NodeEntitiesInfo",
210        "string<=256 node_namespace\nstring<=256 node_name\nGid[] reader_gid_seq\n\
211         Gid[] writer_gid_seq\n",
212    ),
213    (
214        "rmw_dds_common/msg/ParticipantEntitiesInfo",
215        "Gid gid\nNodeEntitiesInfo[] node_entities_info_seq\n",
216    ),
217];
218
219/// Where the definitions of interface types are found, and the types
220/// made from them.
221///
222/// A type `pkg/msg/Name` is the file `<dir>/<pkg>/msg/Name.msg` (or
223/// `<dir>/share/<pkg>/msg/Name.msg`) of the first directory that has
224/// it, else a text given with [`Self::add_text`], else one of the few
225/// built in. [`Self::add_ament_prefix_path`] adds the `share` directories
226/// of the ROS 2 installations of `AMENT_PREFIX_PATH`.
227///
228/// The types are made once and kept.
229#[derive(Debug, Default)]
230pub struct TypeLibrary {
231    dirs: Vec<PathBuf>,
232    texts: HashMap<TypeName, String>,
233    messages: Mutex<HashMap<TypeName, MessageType>>,
234}
235
236impl TypeLibrary {
237    /// A library with no directories: the built-in definitions only.
238    pub fn new() -> TypeLibrary {
239        TypeLibrary::default()
240    }
241
242    /// A library of the directories `dirs`, then those of
243    /// `AMENT_PREFIX_PATH`.
244    pub fn with_dirs<P: AsRef<Path>>(dirs: impl IntoIterator<Item = P>) -> TypeLibrary {
245        let mut l = TypeLibrary::new();
246        for d in dirs {
247            l.add_dir(d);
248        }
249        l.add_ament_prefix_path();
250        l
251    }
252
253    /// Adds a directory to look in, after those added before.
254    pub fn add_dir(&mut self, dir: impl AsRef<Path>) {
255        self.dirs.push(dir.as_ref().to_path_buf());
256    }
257
258    /// Adds `<prefix>/share` for each prefix of `AMENT_PREFIX_PATH`.
259    pub fn add_ament_prefix_path(&mut self) {
260        if let Some(path) = std::env::var_os("AMENT_PREFIX_PATH") {
261            for p in std::env::split_paths(&path) {
262                if !p.as_os_str().is_empty() {
263                    self.add_dir(p.join("share"));
264                }
265            }
266        }
267    }
268
269    /// The directories looked in, in order.
270    pub fn dirs(&self) -> &[PathBuf] {
271        &self.dirs
272    }
273
274    /// Gives the text of the `.msg` or `.srv` file of `name`
275    /// (`pkg/msg/Name` or `pkg/srv/Name`), for when there is no file; a
276    /// file found in the directories comes first.
277    pub fn add_text(&mut self, name: &str, text: &str) -> Result<()> {
278        let name = TypeName::parse(name)?;
279        self.texts.insert(name, text.to_string());
280        Ok(())
281    }
282
283    /// The file of `name` in the directories, if one has it.
284    pub fn find_file(&self, name: &TypeName) -> Option<PathBuf> {
285        let file = format!("{}.{}", name.name, name.kind.as_str());
286        self.dirs.iter().find_map(|d| {
287            [
288                d.join(&name.package).join(name.kind.as_str()).join(&file),
289                d.join("share")
290                    .join(&name.package)
291                    .join(name.kind.as_str())
292                    .join(&file),
293            ]
294            .into_iter()
295            .find(|p| p.is_file())
296        })
297    }
298
299    fn text(&self, name: &TypeName) -> Result<String> {
300        if let Some(p) = self.find_file(name) {
301            return std::fs::read_to_string(&p)
302                .map_err(|e| Error::Io(format!("{}: {e}", p.display())));
303        }
304        if let Some(t) = self.texts.get(name) {
305            return Ok(t.clone());
306        }
307        let full = name.to_string();
308        if let Some((_, t)) = BUILTIN.iter().find(|(n, _)| *n == full) {
309            return Ok(t.to_string());
310        }
311        Err(Error::NotFound(format!(
312            "{name}: no {}/{}/{}.{} in {:?}",
313            name.package,
314            name.kind.as_str(),
315            name.name,
316            name.kind.as_str(),
317            self.dirs
318        )))
319    }
320
321    /// The message type `name` (`pkg/msg/Name` or `pkg/Name`), and the
322    /// types it uses.
323    pub fn message(&self, name: &str) -> Result<MessageType> {
324        let name = TypeName::parse(name)?;
325        if name.kind != InterfaceKind::Message {
326            return Err(Error::Name(format!(
327                "{name} is not a message (pkg/msg/Name)"
328            )));
329        }
330        self.resolve(&name, &mut Vec::new())
331    }
332
333    /// The service type `name` (`pkg/srv/Name`).
334    pub fn service(&self, name: &str) -> Result<ServiceType> {
335        let name = TypeName::parse(name)?;
336        if name.kind != InterfaceKind::Service {
337            return Err(Error::Name(format!(
338                "{name} is not a service (pkg/srv/Name)"
339            )));
340        }
341        let spec = parse_service(&name, &self.text(&name)?)?;
342        let mut stack = Vec::new();
343        let request = self.build(&spec.request, &mut stack)?;
344        let response = self.build(&spec.response, &mut stack)?;
345        // The event of service introspection (REP-2012): what ROS 2
346        // hashes the service with.
347        let info = self.resolve(
348            &TypeName::message("service_msgs", "ServiceEventInfo")?,
349            &mut stack,
350        )?;
351        let nested = |m: &MessageType, array: ArraySpec| FieldType {
352            base: BaseType::Message(m.clone()),
353            array,
354        };
355        let event = self.assemble(
356            name.with_suffix("_Event"),
357            vec![
358                ("info", nested(&info, ArraySpec::None)),
359                ("request", nested(&request, ArraySpec::Bounded(1))),
360                ("response", nested(&response, ArraySpec::Bounded(1))),
361            ],
362        )?;
363        let service = self.assemble(
364            name.clone(),
365            vec![
366                ("request_message", nested(&request, ArraySpec::None)),
367                ("response_message", nested(&response, ArraySpec::None)),
368                ("event_message", nested(&event, ArraySpec::None)),
369            ],
370        )?;
371        Ok(ServiceType {
372            name,
373            request,
374            response,
375            event,
376            description: service.type_description(),
377        })
378    }
379
380    fn resolve(&self, name: &TypeName, stack: &mut Vec<TypeName>) -> Result<MessageType> {
381        if let Some(m) = self.messages.lock().expect("not poisoned").get(name) {
382            return Ok(m.clone());
383        }
384        if stack.contains(name) {
385            return Err(Error::Parse(format!(
386                "{name} uses itself: {}",
387                stack
388                    .iter()
389                    .map(|n| n.to_string())
390                    .collect::<Vec<_>>()
391                    .join(" -> ")
392            )));
393        }
394        let spec = parse_message(name, &self.text(name)?)?;
395        stack.push(name.clone());
396        let m = self.build(&spec, stack);
397        stack.pop();
398        let m = m?;
399        self.messages
400            .lock()
401            .expect("not poisoned")
402            .insert(name.clone(), m.clone());
403        Ok(m)
404    }
405
406    /// The message of `spec`, the messages it names found.
407    fn build(&self, spec: &MessageSpec, stack: &mut Vec<TypeName>) -> Result<MessageType> {
408        let at = |e: Error| Error::Parse(format!("{}: {e}", spec.name));
409        let mut fields = Vec::new();
410        for f in &spec.fields {
411            let base = match &f.ty.base {
412                BaseSpec::Primitive(p) => BaseType::Primitive(*p),
413                BaseSpec::String { wide, bound } => BaseType::String {
414                    wide: *wide,
415                    bound: *bound,
416                },
417                BaseSpec::Message(n) => BaseType::Message(self.resolve(n, stack)?),
418            };
419            let ty = FieldType {
420                base,
421                array: f.ty.array,
422            };
423            let default = match &f.default {
424                Some(d) => {
425                    let v = parse_literal(&ty, d)
426                        .map_err(|e| at(Error::Parse(format!("field {}: {e}", f.name))))?;
427                    check_length(&ty, &v)
428                        .map_err(|e| at(Error::Parse(format!("field {}: {e}", f.name))))?;
429                    Some(v)
430                }
431                None => None,
432            };
433            fields.push(Field {
434                name: f.name.clone(),
435                ty,
436                default,
437            });
438        }
439        let mut constants = Vec::new();
440        for c in &spec.constants {
441            let ty = FieldType {
442                base: match &c.ty.base {
443                    BaseSpec::Primitive(p) => BaseType::Primitive(*p),
444                    BaseSpec::String { wide, bound } => BaseType::String {
445                        wide: *wide,
446                        bound: *bound,
447                    },
448                    BaseSpec::Message(_) => unreachable!("checked by the parser"),
449                },
450                array: ArraySpec::None,
451            };
452            let value = parse_literal(&ty, &c.value)
453                .map_err(|e| at(Error::Parse(format!("constant {}: {e}", c.name))))?;
454            constants.push(Constant {
455                name: c.name.clone(),
456                ty: c.ty.clone(),
457                value,
458            });
459        }
460        let mut m = self.assemble_fields(spec.name.clone(), fields)?;
461        Arc::get_mut(&mut m.0).expect("not shared yet").constants = constants;
462        Ok(m)
463    }
464
465    fn assemble(&self, name: TypeName, fields: Vec<(&str, FieldType)>) -> Result<MessageType> {
466        self.assemble_fields(
467            name,
468            fields
469                .into_iter()
470                .map(|(n, ty)| Field {
471                    name: n.to_string(),
472                    ty,
473                    default: None,
474                })
475                .collect(),
476        )
477    }
478
479    fn assemble_fields(&self, name: TypeName, mut fields: Vec<Field>) -> Result<MessageType> {
480        if fields.is_empty() {
481            fields.push(Field {
482                name: EMPTY_MESSAGE_MEMBER.to_string(),
483                ty: FieldType {
484                    base: BaseType::Primitive(Primitive::Uint8),
485                    array: ArraySpec::None,
486                },
487                default: None,
488            });
489        }
490        let mut referenced = BTreeMap::new();
491        for f in &fields {
492            if let BaseType::Message(m) = &f.ty.base {
493                referenced.insert(m.0.name.to_string(), m.0.individual.clone());
494                for (k, v) in &m.0.referenced {
495                    referenced.insert(k.clone(), v.clone());
496                }
497            }
498        }
499        let individual = IndividualTypeDescription {
500            type_name: name.to_string(),
501            fields: fields
502                .iter()
503                .map(|f| DescField {
504                    name: f.name.clone(),
505                    field_type: describe(&f.ty),
506                    default_value: String::new(),
507                })
508                .collect(),
509        };
510        let description = TypeDescription {
511            type_description: individual.clone(),
512            referenced_type_descriptions: referenced.values().cloned().collect(),
513        };
514        let dynamic = DynamicType::new(Type::Struct(Arc::new(StructType {
515            name: name.dds_name(),
516            // ROS 2's types are appendable in its IDL; with XCDR1, which
517            // ROS 2 uses, appendable and final serialize the same.
518            extensibility: Extensibility::Appendable,
519            members: fields
520                .iter()
521                .enumerate()
522                .map(|(i, f)| StructMember::new(f.name.clone(), i as u32, dds_type(&f.ty)))
523                .collect(),
524            ..StructType::default()
525        })));
526        let hash = description.hash();
527        Ok(MessageType(Arc::new(MessageInner {
528            name,
529            fields,
530            constants: Vec::new(),
531            dynamic,
532            individual,
533            referenced,
534            hash,
535        })))
536    }
537}
538
539fn describe(ty: &FieldType) -> DescFieldType {
540    let (mut id, string_capacity, nested) = match &ty.base {
541        BaseType::Primitive(p) => (
542            match p {
543                Primitive::Bool => field_type::BOOLEAN,
544                Primitive::Byte => field_type::BYTE,
545                // `char` is `uint8` in ROS 2 (its .msg to .idl mapping).
546                Primitive::Char | Primitive::Uint8 => field_type::UINT8,
547                Primitive::Float32 => field_type::FLOAT,
548                Primitive::Float64 => field_type::DOUBLE,
549                Primitive::Int8 => field_type::INT8,
550                Primitive::Int16 => field_type::INT16,
551                Primitive::Uint16 => field_type::UINT16,
552                Primitive::Int32 => field_type::INT32,
553                Primitive::Uint32 => field_type::UINT32,
554                Primitive::Int64 => field_type::INT64,
555                Primitive::Uint64 => field_type::UINT64,
556            },
557            0,
558            String::new(),
559        ),
560        BaseType::String { wide, bound: None } => (
561            if *wide {
562                field_type::WSTRING
563            } else {
564                field_type::STRING
565            },
566            0,
567            String::new(),
568        ),
569        BaseType::String {
570            wide,
571            bound: Some(b),
572        } => (
573            if *wide {
574                field_type::BOUNDED_WSTRING
575            } else {
576                field_type::BOUNDED_STRING
577            },
578            *b as u64,
579            String::new(),
580        ),
581        BaseType::Message(m) => (field_type::NESTED_TYPE, 0, m.name().to_string()),
582    };
583    let capacity = match ty.array {
584        ArraySpec::None => 0,
585        ArraySpec::Fixed(n) => {
586            id += field_type::ARRAY_OFFSET;
587            n as u64
588        }
589        ArraySpec::Bounded(n) => {
590            id += field_type::BOUNDED_SEQUENCE_OFFSET;
591            n as u64
592        }
593        ArraySpec::Unbounded => {
594            id += field_type::UNBOUNDED_SEQUENCE_OFFSET;
595            0
596        }
597    };
598    DescFieldType {
599        type_id: id,
600        capacity,
601        string_capacity,
602        nested_type_name: nested,
603    }
604}
605
606fn dds_type(ty: &FieldType) -> Type {
607    let element = match &ty.base {
608        BaseType::Primitive(p) => Type::Primitive(match p {
609            Primitive::Bool => XPrimitive::Boolean,
610            Primitive::Byte => XPrimitive::Byte,
611            Primitive::Char | Primitive::Uint8 => XPrimitive::Uint8,
612            Primitive::Float32 => XPrimitive::Float32,
613            Primitive::Float64 => XPrimitive::Float64,
614            Primitive::Int8 => XPrimitive::Int8,
615            Primitive::Int16 => XPrimitive::Int16,
616            Primitive::Uint16 => XPrimitive::Uint16,
617            Primitive::Int32 => XPrimitive::Int32,
618            Primitive::Uint32 => XPrimitive::Uint32,
619            Primitive::Int64 => XPrimitive::Int64,
620            Primitive::Uint64 => XPrimitive::Uint64,
621        }),
622        BaseType::String { wide, bound } => Type::String {
623            wide: *wide,
624            bound: bound.unwrap_or(0),
625        },
626        BaseType::Message(m) => m.dynamic_type().as_type().clone(),
627    };
628    match ty.array {
629        ArraySpec::None => element,
630        ArraySpec::Fixed(n) => Type::Array(Arc::new(ArrayType {
631            element: Element::new(element),
632            dimensions: vec![n],
633        })),
634        ArraySpec::Bounded(n) => Type::Sequence(Arc::new(SequenceType {
635            element: Element::new(element),
636            bound: n,
637        })),
638        ArraySpec::Unbounded => Type::Sequence(Arc::new(SequenceType {
639            element: Element::new(element),
640            bound: 0,
641        })),
642    }
643}