Skip to main content

nros_params/
launch_text.rs

1// Issue 2638.
2//! The ONE reading of a launch parameter's baked text.
3//!
4//! An embedded image has no launch runtime to hand `--params-file` to, so the
5//! build bakes every launch parameter as TEXT and the image types it when it
6//! seeds the store. That text is written by
7//! `nros_orchestration_ir::launch_param_text` and read here; the two are one
8//! convention and are tested as a round trip.
9//!
10//! The reading follows what ROS gives the same value:
11//!
12//! - a scalar is `true` / `false` (any of the three cases rcl accepts), then
13//!   an `i64`, then an `f64`, then a string -- the order rcl's YAML reading
14//!   gives an unquoted scalar;
15//! - a whole text in single quotes is a STRING, with `''` read as `'`. The
16//!   writer quotes a string that would otherwise read as something else;
17//! - a YAML flow sequence `[a, b, c]` is an ARRAY. The first element decides
18//!   the element type and every other element must have it, which is rcl's
19//!   rule (`parse.c`: "Sequence should be of same type"): `[1, 2.5]` is
20//!   refused, not widened. A quoted element is a string.
21//!
22//! The list used to be baked as `a,b,c` and read as one string, so a
23//! `[40.0, 50.0, 60.0]` from a `config/*.param.yaml` reached the node as the
24//! string `"40.0,50.0,60.0"` -- and a one-element list as a scalar.
25//!
26//! No allocation: the element type is decided in one pass over the text and
27//! the value is filled in place in a second, so no temporary array exists.
28
29use crate::types::ParameterValue;
30use heapless::{String, Vec};
31
32/// Why a baked text has no value to seed.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum LaunchTextError {
35    /// `[]`. ROS gives an empty sequence no value: rcl's file parser
36    /// allocates a sequence on its first element and never for `[]`, and
37    /// launch_ros refuses an inline `value="[]"` ("Expected a non-empty
38    /// sequence"). There is no element type to give it, so a seeder leaves
39    /// the declaration's default standing.
40    EmptyList,
41    /// A list whose elements are not all one type (`[1, 2.5]`, `[1, a]`).
42    /// rcl refuses the file and launch_ros refuses the inline value.
43    MixedList,
44    /// A string past `MAX_STRING_VALUE_LEN`, or a list past `MAX_ARRAY_LEN`
45    /// (`MAX_STRING_ARRAY_LEN` for a list of strings).
46    DoesNotFit,
47    /// An unterminated quote or a stray character after a quoted element.
48    Malformed,
49}
50
51#[derive(Clone, Copy, PartialEq, Eq)]
52enum Kind {
53    Bool,
54    Integer,
55    Double,
56    String,
57}
58
59fn boolean(t: &str) -> Option<bool> {
60    match t {
61        "true" | "True" | "TRUE" => Some(true),
62        "false" | "False" | "FALSE" => Some(false),
63        _ => None,
64    }
65}
66
67fn kind_of_unquoted(t: &str) -> Kind {
68    if boolean(t).is_some() {
69        Kind::Bool
70    } else if t.parse::<i64>().is_ok() {
71        Kind::Integer
72    } else if t.parse::<f64>().is_ok() {
73        Kind::Double
74    } else {
75        Kind::String
76    }
77}
78
79/// One element of a flow sequence, as written.
80#[derive(Clone, Copy)]
81enum Element<'a> {
82    /// Unquoted, trimmed.
83    Plain(&'a str),
84    /// Single-quoted; the slice is BETWEEN the quotes, `''` still doubled.
85    Single(&'a str),
86    /// Double-quoted; the slice is between the quotes, escapes not read.
87    Double(&'a str),
88}
89
90impl Element<'_> {
91    fn kind(self) -> Kind {
92        match self {
93            Element::Plain(t) => kind_of_unquoted(t),
94            Element::Single(_) | Element::Double(_) => Kind::String,
95        }
96    }
97}
98
99/// Walk the elements of the flow sequence body `inner` (the text between
100/// `[` and `]`), calling `f` on each. `Err(Malformed)` on a broken quote.
101fn for_each_element<'a>(
102    inner: &'a str,
103    mut f: impl FnMut(Element<'a>) -> Result<(), LaunchTextError>,
104) -> Result<usize, LaunchTextError> {
105    let bytes = inner.as_bytes();
106    let mut i = 0;
107    let mut n = 0;
108    let skip_ws = |i: &mut usize| {
109        while *i < bytes.len() && bytes[*i].is_ascii_whitespace() {
110            *i += 1;
111        }
112    };
113    skip_ws(&mut i);
114    if i == bytes.len() {
115        return Ok(0);
116    }
117    loop {
118        skip_ws(&mut i);
119        let element = match bytes.get(i) {
120            Some(b'\'') => {
121                let start = i + 1;
122                let mut j = start;
123                loop {
124                    match bytes.get(j) {
125                        None => return Err(LaunchTextError::Malformed),
126                        Some(b'\'') if bytes.get(j + 1) == Some(&b'\'') => j += 2,
127                        Some(b'\'') => break,
128                        Some(_) => j += 1,
129                    }
130                }
131                i = j + 1;
132                Element::Single(&inner[start..j])
133            }
134            Some(b'"') => {
135                let start = i + 1;
136                let mut j = start;
137                loop {
138                    match bytes.get(j) {
139                        None => return Err(LaunchTextError::Malformed),
140                        Some(b'\\') => j += 2,
141                        Some(b'"') => break,
142                        Some(_) => j += 1,
143                    }
144                }
145                i = j + 1;
146                Element::Double(&inner[start..j])
147            }
148            _ => {
149                let start = i;
150                while i < bytes.len() && bytes[i] != b',' {
151                    i += 1;
152                }
153                Element::Plain(inner[start..i].trim())
154            }
155        };
156        f(element)?;
157        n += 1;
158        skip_ws(&mut i);
159        match bytes.get(i) {
160            None => return Ok(n),
161            Some(b',') => {
162                i += 1;
163                // YAML allows one trailing comma: `[a, b,]` is two elements.
164                skip_ws(&mut i);
165                if i == bytes.len() {
166                    return Ok(n);
167                }
168            }
169            Some(_) => return Err(LaunchTextError::Malformed),
170        }
171    }
172}
173
174/// Push `'...'`'s content into `out`, reading `''` as `'`.
175fn push_single_quoted<const N: usize>(out: &mut String<N>, body: &str) -> bool {
176    let mut rest = body;
177    while let Some(at) = rest.find("''") {
178        if out.push_str(&rest[..=at]).is_err() {
179            return false;
180        }
181        rest = &rest[at + 2..];
182    }
183    out.push_str(rest).is_ok()
184}
185
186fn list_body(text: &str) -> Option<&str> {
187    text.strip_prefix('[')?.strip_suffix(']')
188}
189
190fn single_quoted_body(text: &str) -> Option<&str> {
191    let body = text.strip_prefix('\'')?.strip_suffix('\'')?;
192    // `'a' 'b'` is not one quoted scalar: every inner quote must be doubled.
193    let mut rest = body;
194    while let Some(at) = rest.find('\'') {
195        if rest.as_bytes().get(at + 1) != Some(&b'\'') {
196            return None;
197        }
198        rest = &rest[at + 2..];
199    }
200    Some(body)
201}
202
203/// A flow sequence body's element type and element count: the first element
204/// decides the type and every other must have it (rcl's rule). The ONE pass both
205/// readers below take.
206fn list_kind(inner: &str) -> Result<(Kind, usize), LaunchTextError> {
207    let mut kind: Option<Kind> = None;
208    let n = for_each_element(inner, |e| {
209        let k = e.kind();
210        match kind {
211            None => kind = Some(k),
212            Some(seen) if seen != k => return Err(LaunchTextError::MixedList),
213            Some(_) => {}
214        }
215        Ok(())
216    })?;
217    match kind {
218        Some(kind) => Ok((kind, n)),
219        None => Err(LaunchTextError::EmptyList),
220    }
221}
222
223/// The TYPE a launch parameter's baked text seeds the store with.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum LaunchTextType {
226    Bool,
227    Integer,
228    Double,
229    String,
230    BoolArray,
231    IntegerArray,
232    DoubleArray,
233    StringArray,
234}
235
236// Issue 2768 (a build sizing the store counts launch seeds).
237/// The type [`ParameterValue::assign_launch_text`] would give
238/// `text`, without filling a value and without a capacity check.
239///
240/// For a BUILD that sizes the store before any value exists: a launch seed
241/// takes a slot of this type, so the host counts it by the device's own
242/// reading rather than a second one that could disagree. No capacity, because
243/// the build is what decides the capacities: a seed too long for today's store
244/// is exactly what the count must grow it for, not a reason to skip it.
245/// `Err` only where the device refuses the text whatever the capacity: an
246/// empty list, a mixed list, a broken quote.
247// Issue 2702.
248/// How big the launch text `text` is, as a parameter value: its element count
249/// (1 for a scalar) and the longest string in it, in bytes as written
250/// (0 when it holds no string). `nros build` suggests a parameter store bound
251/// from the seeds an image declares; a seed is an initial value, not a
252/// maximum, so this is a FLOOR, never a size.
253pub fn launch_text_extent(text: &str) -> Result<(usize, usize), LaunchTextError> {
254    let text = text.trim();
255    let Some(inner) = list_body(text) else {
256        let longest = match launch_text_type(text)? {
257            LaunchTextType::String => single_quoted_body(text).unwrap_or(text).len(),
258            _ => 0,
259        };
260        return Ok((1, longest));
261    };
262    let mut longest = 0;
263    let n = for_each_element(inner, |e| {
264        if let Element::Plain(t) | Element::Single(t) | Element::Double(t) = e
265            && e.kind() == Kind::String
266        {
267            longest = longest.max(t.len());
268        }
269        Ok(())
270    })?;
271    Ok((n, longest))
272}
273
274pub fn launch_text_type(text: &str) -> Result<LaunchTextType, LaunchTextError> {
275    if let Some(inner) = list_body(text.trim()) {
276        let (kind, _) = list_kind(inner)?;
277        return Ok(match kind {
278            Kind::Bool => LaunchTextType::BoolArray,
279            Kind::Integer => LaunchTextType::IntegerArray,
280            Kind::Double => LaunchTextType::DoubleArray,
281            Kind::String => LaunchTextType::StringArray,
282        });
283    }
284    if single_quoted_body(text).is_some() {
285        return Ok(LaunchTextType::String);
286    }
287    Ok(match kind_of_unquoted(text) {
288        Kind::Bool => LaunchTextType::Bool,
289        Kind::Integer => LaunchTextType::Integer,
290        Kind::Double => LaunchTextType::Double,
291        Kind::String => LaunchTextType::String,
292    })
293}
294
295impl ParameterValue {
296    /// Type a launch parameter's baked text and write it into `self`, IN
297    /// PLACE (a value is ~8 KiB; see `assign_string`). The reading is the
298    /// module's: scalar inference, a single-quoted string, or a flow
299    /// sequence typed by its elements.
300    ///
301    /// On `Err`, `self` is unspecified and must not be stored.
302    pub fn assign_launch_text(&mut self, text: &str) -> Result<(), LaunchTextError> {
303        if let Some(inner) = list_body(text.trim()) {
304            return self.assign_flow_list(inner);
305        }
306        if let Some(body) = single_quoted_body(text) {
307            if !matches!(self, Self::String(_)) {
308                *self = Self::String(String::new());
309            }
310            return match self {
311                Self::String(s) => {
312                    s.clear();
313                    if push_single_quoted(s, body) {
314                        Ok(())
315                    } else {
316                        Err(LaunchTextError::DoesNotFit)
317                    }
318                }
319                _ => Err(LaunchTextError::DoesNotFit),
320            };
321        }
322        if let Some(b) = boolean(text) {
323            *self = Self::Bool(b);
324        } else if let Ok(i) = text.parse::<i64>() {
325            *self = Self::Integer(i);
326        } else if let Ok(d) = text.parse::<f64>() {
327            *self = Self::Double(d);
328        } else if !self.assign_string(text) {
329            return Err(LaunchTextError::DoesNotFit);
330        }
331        Ok(())
332    }
333
334    fn assign_flow_list(&mut self, inner: &str) -> Result<(), LaunchTextError> {
335        // Pass 1: the element type, which the first element decides.
336        let (kind, n) = list_kind(inner)?;
337        // A string list has its own element bound (issue 2647).
338        let cap = if kind == Kind::String {
339            crate::types::MAX_STRING_ARRAY_LEN
340        } else {
341            crate::types::MAX_ARRAY_LEN
342        };
343        if n > cap {
344            return Err(LaunchTextError::DoesNotFit);
345        }
346        // Pass 2: fill the value of that type in place.
347        *self = match kind {
348            Kind::Bool => Self::BoolArray(Vec::new()),
349            Kind::Integer => Self::IntegerArray(Vec::new()),
350            Kind::Double => Self::DoubleArray(Vec::new()),
351            Kind::String => Self::StringArray(Vec::new()),
352        };
353        let full = LaunchTextError::DoesNotFit;
354        for_each_element(inner, |e| {
355            let pushed = match (&mut *self, e) {
356                (Self::BoolArray(v), Element::Plain(t)) => {
357                    v.push(boolean(t).unwrap_or(false)).is_ok()
358                }
359                (Self::IntegerArray(v), Element::Plain(t)) => {
360                    v.push(t.parse::<i64>().unwrap_or(0)).is_ok()
361                }
362                (Self::DoubleArray(v), Element::Plain(t)) => {
363                    v.push(t.parse::<f64>().unwrap_or(0.0)).is_ok()
364                }
365                (Self::StringArray(v), e) => {
366                    let mut s = String::new();
367                    let ok = match e {
368                        Element::Plain(t) | Element::Double(t) => s.push_str(t).is_ok(),
369                        Element::Single(t) => push_single_quoted(&mut s, t),
370                    };
371                    ok && v.push(s).is_ok()
372                }
373                _ => false,
374            };
375            if pushed { Ok(()) } else { Err(full) }
376        })?;
377        Ok(())
378    }
379}
380
381#[cfg(test)]
382mod tests {
383
384    /// Issue 2702 -- the floors `nros build` suggests: element count and the
385    /// longest string, as written.
386    #[test]
387    fn a_seeds_extent_is_its_element_count_and_longest_string() {
388        assert_eq!(launch_text_extent("[left, '5', 'a, b']"), Ok((3, 4)));
389        assert_eq!(launch_text_extent("[40.0, 50.0, 60.0]"), Ok((3, 0)));
390        assert_eq!(launch_text_extent("[true, false]"), Ok((2, 0)));
391        assert_eq!(launch_text_extent("hello"), Ok((1, 5)));
392        assert_eq!(launch_text_extent("'quoted'"), Ok((1, 6)));
393        assert_eq!(launch_text_extent("250"), Ok((1, 0)));
394    }
395
396    use super::*;
397
398    fn read(text: &str) -> Result<ParameterValue, LaunchTextError> {
399        let mut v = ParameterValue::NotSet;
400        v.assign_launch_text(text).map(|()| v)
401    }
402
403    /// Issue 2768 -- the build's type reading and the device's value reading
404    /// agree on every text the device can store, and refuse the same texts.
405    #[test]
406    fn the_type_reader_agrees_with_the_value_reader() {
407        let corpus = [
408            "true",
409            "FALSE",
410            "42",
411            "-7",
412            "1.0",
413            "1e3",
414            "hello",
415            "",
416            "40.0,50.0",
417            "'1.0'",
418            "'[a]'",
419            "'it''s'",
420            "''",
421            "'a' 'b'",
422            "[true, false]",
423            "[1, 2, 3]",
424            "[1.5, 2.5]",
425            "[a, b]",
426            "['x', y]",
427            "[1, 2.5]",
428            "[]",
429            "[1, a]",
430            "['broken]",
431            " [1, 2] ",
432        ];
433        for text in corpus {
434            let ty = launch_text_type(text);
435            match read(text) {
436                Ok(v) => {
437                    let want = match v {
438                        ParameterValue::Bool(_) => LaunchTextType::Bool,
439                        ParameterValue::Integer(_) => LaunchTextType::Integer,
440                        ParameterValue::Double(_) => LaunchTextType::Double,
441                        ParameterValue::String(_) => LaunchTextType::String,
442                        ParameterValue::BoolArray(_) => LaunchTextType::BoolArray,
443                        ParameterValue::IntegerArray(_) => LaunchTextType::IntegerArray,
444                        ParameterValue::DoubleArray(_) => LaunchTextType::DoubleArray,
445                        ParameterValue::StringArray(_) => LaunchTextType::StringArray,
446                        other => panic!("{text:?}: unexpected {other:?}"),
447                    };
448                    assert_eq!(ty, Ok(want), "{text:?}");
449                }
450                Err(LaunchTextError::DoesNotFit) => {
451                    assert!(ty.is_ok(), "{text:?}: a capacity is not a type error")
452                }
453                Err(e) => assert_eq!(ty, Err(e), "{text:?}"),
454            }
455        }
456        // A list longer than any store is still typed: the build grows for it.
457        extern crate std;
458        let long = std::format!("[{}]", std::vec!["1"; 4096].join(", "));
459        assert_eq!(launch_text_type(&long), Ok(LaunchTextType::IntegerArray));
460    }
461
462    #[test]
463    fn scalars_keep_the_inference_they_had() {
464        assert!(matches!(read("true"), Ok(ParameterValue::Bool(true))));
465        assert!(matches!(read("FALSE"), Ok(ParameterValue::Bool(false))));
466        assert!(matches!(read("42"), Ok(ParameterValue::Integer(42))));
467        assert!(matches!(read("1.0"), Ok(ParameterValue::Double(d)) if d == 1.0));
468        assert!(matches!(read("hello"), Ok(ParameterValue::String(s)) if s == "hello"));
469        assert!(matches!(read(""), Ok(ParameterValue::String(s)) if s.is_empty()));
470        // A comma is not a list: only a bracketed flow sequence is.
471        assert!(matches!(read("40.0,50.0"), Ok(ParameterValue::String(s)) if s == "40.0,50.0"));
472    }
473
474    #[test]
475    fn a_quoted_text_is_a_string() {
476        assert!(matches!(read("'1.0'"), Ok(ParameterValue::String(s)) if s == "1.0"));
477        assert!(matches!(read("'[a]'"), Ok(ParameterValue::String(s)) if s == "[a]"));
478        assert!(matches!(read("'it''s'"), Ok(ParameterValue::String(s)) if s == "it's"));
479        assert!(matches!(read("''"), Ok(ParameterValue::String(s)) if s.is_empty()));
480        // Not ONE quoted scalar: read as the plain text it is.
481        assert!(matches!(read("'a' 'b'"), Ok(ParameterValue::String(s)) if s == "'a' 'b'"));
482    }
483
484    #[test]
485    fn a_double_list_is_a_double_array() {
486        match read("[40.0, 50.0, 60.0]") {
487            Ok(ParameterValue::DoubleArray(v)) => assert_eq!(v.as_slice(), &[40.0, 50.0, 60.0]),
488            other => panic!("{other:?}"),
489        }
490        match read("[1.5]") {
491            Ok(ParameterValue::DoubleArray(v)) => assert_eq!(v.as_slice(), &[1.5]),
492            other => panic!("one element is still a list: {other:?}"),
493        }
494    }
495
496    #[test]
497    fn integer_bool_and_string_lists() {
498        match read("[1, -2, 3]") {
499            Ok(ParameterValue::IntegerArray(v)) => assert_eq!(v.as_slice(), &[1, -2, 3]),
500            other => panic!("{other:?}"),
501        }
502        match read("[true, False]") {
503            Ok(ParameterValue::BoolArray(v)) => assert_eq!(v.as_slice(), &[true, false]),
504            other => panic!("{other:?}"),
505        }
506        match read("[a, '5', 'x, y', 'it''s', \"q\"]") {
507            Ok(ParameterValue::StringArray(v)) => {
508                let got: std::vec::Vec<&str> = v.iter().map(|s| s.as_str()).collect();
509                assert_eq!(got, ["a", "5", "x, y", "it's", "q"]);
510            }
511            other => panic!("{other:?}"),
512        }
513    }
514
515    #[test]
516    fn empty_and_mixed_lists_have_no_value() {
517        assert_eq!(read("[]").unwrap_err(), LaunchTextError::EmptyList);
518        assert_eq!(read("[ ]").unwrap_err(), LaunchTextError::EmptyList);
519        assert_eq!(read("[1, 2.5]").unwrap_err(), LaunchTextError::MixedList);
520        assert_eq!(read("[1, a]").unwrap_err(), LaunchTextError::MixedList);
521        assert_eq!(read("['1', 1]").unwrap_err(), LaunchTextError::MixedList);
522        match read("[a, b,]") {
523            Ok(ParameterValue::StringArray(v)) => assert_eq!(v.len(), 2),
524            other => panic!("a trailing comma adds no element: {other:?}"),
525        }
526        assert_eq!(read("['a]").unwrap_err(), LaunchTextError::Malformed);
527        assert_eq!(read("['a' b]").unwrap_err(), LaunchTextError::Malformed);
528    }
529
530    #[test]
531    fn a_list_past_the_capacity_is_refused_not_cut() {
532        let mut t = std::string::String::from("[");
533        for i in 0..=crate::types::MAX_ARRAY_LEN {
534            if i > 0 {
535                t.push_str(", ");
536            }
537            t.push('1');
538        }
539        t.push(']');
540        assert_eq!(read(&t).unwrap_err(), LaunchTextError::DoesNotFit);
541    }
542}