use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use rustorb_xtypes::dynamic::DynamicType;
use rustorb_xtypes::types::{
ArrayType, Element, Extensibility, Primitive as XPrimitive, SequenceType, StructMember,
StructType, Type,
};
use crate::msg::{
ArraySpec, BaseSpec, MessageSpec, Primitive, TypeSpec, parse_message, parse_service,
};
use crate::names::{InterfaceKind, TypeName};
use crate::type_description::{
Field as DescField, FieldType as DescFieldType, IndividualTypeDescription, TypeDescription,
TypeHash, field_type,
};
use crate::value::{Value, check_length, parse_literal};
use crate::{Error, Result};
pub const EMPTY_MESSAGE_MEMBER: &str = "structure_needs_at_least_one_member";
#[derive(Clone, Debug)]
pub enum BaseType {
Primitive(Primitive),
String {
wide: bool,
bound: Option<u32>,
},
Message(MessageType),
}
impl BaseType {
pub(crate) fn describe(&self) -> String {
match self {
BaseType::Primitive(p) => p.name().to_string(),
BaseType::String { wide, bound } => format!(
"{}{}",
if *wide { "wstring" } else { "string" },
bound.map(|b| format!("<={b}")).unwrap_or_default()
),
BaseType::Message(m) => m.name().to_string(),
}
}
}
#[derive(Clone, Debug)]
pub struct FieldType {
pub base: BaseType,
pub array: ArraySpec,
}
#[derive(Clone, Debug)]
pub struct Field {
pub name: String,
pub ty: FieldType,
pub default: Option<Value>,
}
#[derive(Clone, Debug)]
pub struct Constant {
pub name: String,
pub ty: TypeSpec,
pub value: Value,
}
#[derive(Debug)]
struct MessageInner {
name: TypeName,
fields: Vec<Field>,
constants: Vec<Constant>,
dynamic: DynamicType,
individual: IndividualTypeDescription,
referenced: BTreeMap<String, IndividualTypeDescription>,
hash: TypeHash,
}
#[derive(Clone, Debug)]
pub struct MessageType(Arc<MessageInner>);
impl MessageType {
pub fn name(&self) -> &TypeName {
&self.0.name
}
pub fn fields(&self) -> &[Field] {
&self.0.fields
}
pub fn constants(&self) -> &[Constant] {
&self.0.constants
}
pub fn dynamic_type(&self) -> &DynamicType {
&self.0.dynamic
}
pub fn type_description(&self) -> TypeDescription {
TypeDescription {
type_description: self.0.individual.clone(),
referenced_type_descriptions: self.0.referenced.values().cloned().collect(),
}
}
pub fn type_hash(&self) -> TypeHash {
self.0.hash
}
}
impl PartialEq for MessageType {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0) || self.0.name == other.0.name && self.0.hash == other.0.hash
}
}
#[derive(Clone, Debug)]
pub struct ServiceType {
name: TypeName,
request: MessageType,
response: MessageType,
event: MessageType,
description: TypeDescription,
}
impl ServiceType {
pub fn name(&self) -> &TypeName {
&self.name
}
pub fn request(&self) -> &MessageType {
&self.request
}
pub fn response(&self) -> &MessageType {
&self.response
}
pub fn event(&self) -> &MessageType {
&self.event
}
pub fn type_description(&self) -> &TypeDescription {
&self.description
}
pub fn type_hash(&self) -> TypeHash {
self.description.hash()
}
}
const BUILTIN: &[(&str, &str)] = &[
("builtin_interfaces/msg/Time", "int32 sec\nuint32 nanosec\n"),
(
"service_msgs/msg/ServiceEventInfo",
"uint8 REQUEST_SENT = 0\nuint8 REQUEST_RECEIVED = 1\nuint8 RESPONSE_SENT = 2\n\
uint8 RESPONSE_RECEIVED = 3\nuint8 event_type\nbuiltin_interfaces/Time stamp\n\
char[16] client_gid\nint64 sequence_number\n",
),
("rmw_dds_common/msg/Gid", "char[16] data\n"),
(
"rmw_dds_common/msg/NodeEntitiesInfo",
"string<=256 node_namespace\nstring<=256 node_name\nGid[] reader_gid_seq\n\
Gid[] writer_gid_seq\n",
),
(
"rmw_dds_common/msg/ParticipantEntitiesInfo",
"Gid gid\nNodeEntitiesInfo[] node_entities_info_seq\n",
),
];
#[derive(Debug, Default)]
pub struct TypeLibrary {
dirs: Vec<PathBuf>,
texts: HashMap<TypeName, String>,
messages: Mutex<HashMap<TypeName, MessageType>>,
}
impl TypeLibrary {
pub fn new() -> TypeLibrary {
TypeLibrary::default()
}
pub fn with_dirs<P: AsRef<Path>>(dirs: impl IntoIterator<Item = P>) -> TypeLibrary {
let mut l = TypeLibrary::new();
for d in dirs {
l.add_dir(d);
}
l.add_ament_prefix_path();
l
}
pub fn add_dir(&mut self, dir: impl AsRef<Path>) {
self.dirs.push(dir.as_ref().to_path_buf());
}
pub fn add_ament_prefix_path(&mut self) {
if let Some(path) = std::env::var_os("AMENT_PREFIX_PATH") {
for p in std::env::split_paths(&path) {
if !p.as_os_str().is_empty() {
self.add_dir(p.join("share"));
}
}
}
}
pub fn dirs(&self) -> &[PathBuf] {
&self.dirs
}
pub fn add_text(&mut self, name: &str, text: &str) -> Result<()> {
let name = TypeName::parse(name)?;
self.texts.insert(name, text.to_string());
Ok(())
}
pub fn find_file(&self, name: &TypeName) -> Option<PathBuf> {
let file = format!("{}.{}", name.name, name.kind.as_str());
self.dirs.iter().find_map(|d| {
[
d.join(&name.package).join(name.kind.as_str()).join(&file),
d.join("share")
.join(&name.package)
.join(name.kind.as_str())
.join(&file),
]
.into_iter()
.find(|p| p.is_file())
})
}
fn text(&self, name: &TypeName) -> Result<String> {
if let Some(p) = self.find_file(name) {
return std::fs::read_to_string(&p)
.map_err(|e| Error::Io(format!("{}: {e}", p.display())));
}
if let Some(t) = self.texts.get(name) {
return Ok(t.clone());
}
let full = name.to_string();
if let Some((_, t)) = BUILTIN.iter().find(|(n, _)| *n == full) {
return Ok(t.to_string());
}
Err(Error::NotFound(format!(
"{name}: no {}/{}/{}.{} in {:?}",
name.package,
name.kind.as_str(),
name.name,
name.kind.as_str(),
self.dirs
)))
}
pub fn message(&self, name: &str) -> Result<MessageType> {
let name = TypeName::parse(name)?;
if name.kind != InterfaceKind::Message {
return Err(Error::Name(format!(
"{name} is not a message (pkg/msg/Name)"
)));
}
self.resolve(&name, &mut Vec::new())
}
pub fn service(&self, name: &str) -> Result<ServiceType> {
let name = TypeName::parse(name)?;
if name.kind != InterfaceKind::Service {
return Err(Error::Name(format!(
"{name} is not a service (pkg/srv/Name)"
)));
}
let spec = parse_service(&name, &self.text(&name)?)?;
let mut stack = Vec::new();
let request = self.build(&spec.request, &mut stack)?;
let response = self.build(&spec.response, &mut stack)?;
let info = self.resolve(
&TypeName::message("service_msgs", "ServiceEventInfo")?,
&mut stack,
)?;
let nested = |m: &MessageType, array: ArraySpec| FieldType {
base: BaseType::Message(m.clone()),
array,
};
let event = self.assemble(
name.with_suffix("_Event"),
vec![
("info", nested(&info, ArraySpec::None)),
("request", nested(&request, ArraySpec::Bounded(1))),
("response", nested(&response, ArraySpec::Bounded(1))),
],
)?;
let service = self.assemble(
name.clone(),
vec![
("request_message", nested(&request, ArraySpec::None)),
("response_message", nested(&response, ArraySpec::None)),
("event_message", nested(&event, ArraySpec::None)),
],
)?;
Ok(ServiceType {
name,
request,
response,
event,
description: service.type_description(),
})
}
fn resolve(&self, name: &TypeName, stack: &mut Vec<TypeName>) -> Result<MessageType> {
if let Some(m) = self.messages.lock().expect("not poisoned").get(name) {
return Ok(m.clone());
}
if stack.contains(name) {
return Err(Error::Parse(format!(
"{name} uses itself: {}",
stack
.iter()
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join(" -> ")
)));
}
let spec = parse_message(name, &self.text(name)?)?;
stack.push(name.clone());
let m = self.build(&spec, stack);
stack.pop();
let m = m?;
self.messages
.lock()
.expect("not poisoned")
.insert(name.clone(), m.clone());
Ok(m)
}
fn build(&self, spec: &MessageSpec, stack: &mut Vec<TypeName>) -> Result<MessageType> {
let at = |e: Error| Error::Parse(format!("{}: {e}", spec.name));
let mut fields = Vec::new();
for f in &spec.fields {
let base = match &f.ty.base {
BaseSpec::Primitive(p) => BaseType::Primitive(*p),
BaseSpec::String { wide, bound } => BaseType::String {
wide: *wide,
bound: *bound,
},
BaseSpec::Message(n) => BaseType::Message(self.resolve(n, stack)?),
};
let ty = FieldType {
base,
array: f.ty.array,
};
let default = match &f.default {
Some(d) => {
let v = parse_literal(&ty, d)
.map_err(|e| at(Error::Parse(format!("field {}: {e}", f.name))))?;
check_length(&ty, &v)
.map_err(|e| at(Error::Parse(format!("field {}: {e}", f.name))))?;
Some(v)
}
None => None,
};
fields.push(Field {
name: f.name.clone(),
ty,
default,
});
}
let mut constants = Vec::new();
for c in &spec.constants {
let ty = FieldType {
base: match &c.ty.base {
BaseSpec::Primitive(p) => BaseType::Primitive(*p),
BaseSpec::String { wide, bound } => BaseType::String {
wide: *wide,
bound: *bound,
},
BaseSpec::Message(_) => unreachable!("checked by the parser"),
},
array: ArraySpec::None,
};
let value = parse_literal(&ty, &c.value)
.map_err(|e| at(Error::Parse(format!("constant {}: {e}", c.name))))?;
constants.push(Constant {
name: c.name.clone(),
ty: c.ty.clone(),
value,
});
}
let mut m = self.assemble_fields(spec.name.clone(), fields)?;
Arc::get_mut(&mut m.0).expect("not shared yet").constants = constants;
Ok(m)
}
fn assemble(&self, name: TypeName, fields: Vec<(&str, FieldType)>) -> Result<MessageType> {
self.assemble_fields(
name,
fields
.into_iter()
.map(|(n, ty)| Field {
name: n.to_string(),
ty,
default: None,
})
.collect(),
)
}
fn assemble_fields(&self, name: TypeName, mut fields: Vec<Field>) -> Result<MessageType> {
if fields.is_empty() {
fields.push(Field {
name: EMPTY_MESSAGE_MEMBER.to_string(),
ty: FieldType {
base: BaseType::Primitive(Primitive::Uint8),
array: ArraySpec::None,
},
default: None,
});
}
let mut referenced = BTreeMap::new();
for f in &fields {
if let BaseType::Message(m) = &f.ty.base {
referenced.insert(m.0.name.to_string(), m.0.individual.clone());
for (k, v) in &m.0.referenced {
referenced.insert(k.clone(), v.clone());
}
}
}
let individual = IndividualTypeDescription {
type_name: name.to_string(),
fields: fields
.iter()
.map(|f| DescField {
name: f.name.clone(),
field_type: describe(&f.ty),
default_value: String::new(),
})
.collect(),
};
let description = TypeDescription {
type_description: individual.clone(),
referenced_type_descriptions: referenced.values().cloned().collect(),
};
let dynamic = DynamicType::new(Type::Struct(Arc::new(StructType {
name: name.dds_name(),
extensibility: Extensibility::Appendable,
members: fields
.iter()
.enumerate()
.map(|(i, f)| StructMember::new(f.name.clone(), i as u32, dds_type(&f.ty)))
.collect(),
..StructType::default()
})));
let hash = description.hash();
Ok(MessageType(Arc::new(MessageInner {
name,
fields,
constants: Vec::new(),
dynamic,
individual,
referenced,
hash,
})))
}
}
fn describe(ty: &FieldType) -> DescFieldType {
let (mut id, string_capacity, nested) = match &ty.base {
BaseType::Primitive(p) => (
match p {
Primitive::Bool => field_type::BOOLEAN,
Primitive::Byte => field_type::BYTE,
Primitive::Char | Primitive::Uint8 => field_type::UINT8,
Primitive::Float32 => field_type::FLOAT,
Primitive::Float64 => field_type::DOUBLE,
Primitive::Int8 => field_type::INT8,
Primitive::Int16 => field_type::INT16,
Primitive::Uint16 => field_type::UINT16,
Primitive::Int32 => field_type::INT32,
Primitive::Uint32 => field_type::UINT32,
Primitive::Int64 => field_type::INT64,
Primitive::Uint64 => field_type::UINT64,
},
0,
String::new(),
),
BaseType::String { wide, bound: None } => (
if *wide {
field_type::WSTRING
} else {
field_type::STRING
},
0,
String::new(),
),
BaseType::String {
wide,
bound: Some(b),
} => (
if *wide {
field_type::BOUNDED_WSTRING
} else {
field_type::BOUNDED_STRING
},
*b as u64,
String::new(),
),
BaseType::Message(m) => (field_type::NESTED_TYPE, 0, m.name().to_string()),
};
let capacity = match ty.array {
ArraySpec::None => 0,
ArraySpec::Fixed(n) => {
id += field_type::ARRAY_OFFSET;
n as u64
}
ArraySpec::Bounded(n) => {
id += field_type::BOUNDED_SEQUENCE_OFFSET;
n as u64
}
ArraySpec::Unbounded => {
id += field_type::UNBOUNDED_SEQUENCE_OFFSET;
0
}
};
DescFieldType {
type_id: id,
capacity,
string_capacity,
nested_type_name: nested,
}
}
fn dds_type(ty: &FieldType) -> Type {
let element = match &ty.base {
BaseType::Primitive(p) => Type::Primitive(match p {
Primitive::Bool => XPrimitive::Boolean,
Primitive::Byte => XPrimitive::Byte,
Primitive::Char | Primitive::Uint8 => XPrimitive::Uint8,
Primitive::Float32 => XPrimitive::Float32,
Primitive::Float64 => XPrimitive::Float64,
Primitive::Int8 => XPrimitive::Int8,
Primitive::Int16 => XPrimitive::Int16,
Primitive::Uint16 => XPrimitive::Uint16,
Primitive::Int32 => XPrimitive::Int32,
Primitive::Uint32 => XPrimitive::Uint32,
Primitive::Int64 => XPrimitive::Int64,
Primitive::Uint64 => XPrimitive::Uint64,
}),
BaseType::String { wide, bound } => Type::String {
wide: *wide,
bound: bound.unwrap_or(0),
},
BaseType::Message(m) => m.dynamic_type().as_type().clone(),
};
match ty.array {
ArraySpec::None => element,
ArraySpec::Fixed(n) => Type::Array(Arc::new(ArrayType {
element: Element::new(element),
dimensions: vec![n],
})),
ArraySpec::Bounded(n) => Type::Sequence(Arc::new(SequenceType {
element: Element::new(element),
bound: n,
})),
ArraySpec::Unbounded => Type::Sequence(Arc::new(SequenceType {
element: Element::new(element),
bound: 0,
})),
}
}