Skip to main content

nros_node/
ros_args.rs

1//! `--ros-args` parsing: the producer of the remap FALLBACK tier.
2//!
3//! [`crate::names::resolve_name_layered`] resolves a name through two tiers —
4//! the launch projection (authoritative) and a fallback. This module is the
5//! fallback's producer: it reads a process argument vector the way rcl does
6//! and yields the remap rules it carries.
7//!
8//! # Whose grammar
9//!
10//! rcl's, as documented in ROS 2 Humble's installed headers
11//! (`rcl/arguments.h`, `rcl_parse_arguments`; `rcl/remap.h`,
12//! `rcl_remap_topic_name`):
13//!
14//! * ROS arguments are scoped by `--ros-args` and end at `--` or at the end of
15//!   the vector. A vector may open several scopes. Everything outside a scope
16//!   is a non-ROS argument and is left alone.
17//! * `-r` / `--remap` is followed by ONE token, `[node:]from:=to`. A `node:`
18//!   prefix restricts the rule to the node of that NAME.
19//! * Rules are kept in argv order, and the first rule that matches a name wins
20//!   — `foo:=bar bar:=baz` sends `foo` to `bar`, never `baz`.
21//! * A `-r` followed by anything but a valid rule fails the parse.
22//! * `-p` / `--param` is followed by ONE token, `[node:]name:=value`, and
23//!   `--params-file` by a path. Both are parameter OVERRIDES (the
24//!   POSIX case): reported through [`parse_ros_args_events`],
25//!   installed with `Executor::install_argv_params`, and applied when a node
26//!   declares the parameter. The file is the caller's to read — this module
27//!   has no file system — and [`parse_params_yaml`] reads its text.
28//!
29//! # What is REFUSED, and why each one
30//!
31//! Every flag this parser does not honour is a [`RosArgsError`], never a skip.
32//! Silently dropping a ROS argument is the defect `nros::init_with_args` was
33//! written to stop (a `-r chatter:=/other` that compiles and then publishes on
34//! `chatter`). rclcpp is no more lenient: `rclcpp::init` throws
35//! `UnknownROSArgsError` for any ROS argument rcl left unparsed.
36//!
37//! * `__node` / `__name` / `__ns` remaps — node IDENTITY. The launch is
38//!   the authority on a node's name and namespace, with the code's
39//!   default beneath it; an argv identity rung has not been ruled on.
40//! * `rostopic://` / `rosservice://` rules — kind-qualified remaps, which rcl
41//!   itself marks unfinished (`TODO(sloretz) add documentation about
42//!   rostopic:// when it is supported`).
43//! * `-e`/`--enclave`, `--log-level`, `--log-config-file`, the
44//!   `--{enable,disable}-*-logs` switches, and any other token inside a scope.
45//!
46//! # `no_std`, no allocation
47//!
48//! The parse borrows from the arguments it is given and reports each rule
49//! through a callback, so a board that reads its arguments from flash or a
50//! settings store (the other platform cases) can drive it without an
51//! allocator.
52
53/// The `-r`/`--remap` rule one argument carried: `[node:]from:=to`, borrowed
54/// from the argument it was parsed out of.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct RemapArg<'a> {
57    /// `Some(name)` for a `name:from:=to` rule, which applies only to the node
58    /// of that name (rcl matches the node NAME, not its namespace). `None`
59    /// applies to every node in the process.
60    pub node: Option<&'a str>,
61    /// The name being remapped, as written (expanded at resolution time).
62    pub from: &'a str,
63    /// The replacement, as written (expanded at resolution time).
64    pub to: &'a str,
65}
66
67/// The `-p`/`--param` override one argument carried: `[node:]name:=value`,
68/// borrowed from the argument it was parsed out of. Also what
69/// [`parse_params_yaml`] reports for each value in a parameter file.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct ParamArg<'a> {
72    /// `Some(name)` applies only to the node of that NAME; `None` to every
73    /// node (a bare `-p`, or a parameter file's `/**` section).
74    pub node: Option<&'a str>,
75    /// The parameter name, dotted for a nested one (`gains.kp`).
76    pub name: &'a str,
77    /// The value as written. Typed when a node declares the parameter: by the
78    /// type of the default it declares, never guessed from the text alone.
79    pub value: &'a str,
80}
81
82/// One thing a `--ros-args` scope said, in argv order.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum RosArg<'a> {
85    /// `-r` / `--remap [node:]from:=to`.
86    Remap(RemapArg<'a>),
87    /// `-p` / `--param [node:]name:=value`.
88    Param(ParamArg<'a>),
89    /// `--params-file <path>`. The caller reads the file and hands its text to
90    /// [`parse_params_yaml`].
91    ParamsFile(&'a str),
92}
93
94/// Why an argument vector was refused. Each variant names the offending token.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum RosArgsError<'a> {
97    /// A recognised ROS flag nano-ros does not honour (see the module docs for
98    /// the reason each one is refused).
99    Unsupported {
100        /// The flag as written.
101        flag: &'a str,
102    },
103    /// A token inside a `--ros-args` scope that is not a ROS flag at all.
104    Unknown {
105        /// The token as written.
106        token: &'a str,
107    },
108    /// `-r`/`--remap` was the last argument.
109    MissingRule {
110        /// The flag as written.
111        flag: &'a str,
112    },
113    /// `-r`/`--remap` was followed by something that is not `[node:]from:=to`.
114    InvalidRule {
115        /// The rule as written.
116        rule: &'a str,
117    },
118    /// A node-identity remap (`__node`, `__name`, `__ns`, or any `__` rule).
119    IdentityRemap {
120        /// The rule as written.
121        rule: &'a str,
122    },
123    /// `-p`/`--param` or `--params-file` was the last argument.
124    MissingValue {
125        /// The flag as written.
126        flag: &'a str,
127    },
128    /// `-p`/`--param` was followed by something that is not `[node:]name:=value`.
129    InvalidParam {
130        /// The rule as written.
131        rule: &'a str,
132    },
133}
134
135impl core::fmt::Display for RosArgsError<'_> {
136    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
137        match self {
138            Self::Unsupported { flag } => write!(
139                f,
140                "`{flag}` is a ROS argument nano-ros does not honour here (enclaves and log \
141                 configuration have no counterpart; `-p` / `--params-file` are honoured only \
142                 where an executor can hold parameter overrides)"
143            ),
144            Self::Unknown { token } => {
145                write!(
146                    f,
147                    "`{token}` is not a ROS argument (rclcpp refuses it too, as UnknownROSArgsError)"
148                )
149            }
150            Self::MissingRule { flag } => {
151                write!(f, "`{flag}` must be followed by a rule `[node:]from:=to`")
152            }
153            Self::InvalidRule { rule } => {
154                write!(
155                    f,
156                    "`{rule}` is not a remap rule; expected `[node:]from:=to`"
157                )
158            }
159            Self::MissingValue { flag } => {
160                write!(f, "`{flag}` must be followed by a value")
161            }
162            Self::InvalidParam { rule } => write!(
163                f,
164                "`{rule}` is not a parameter override; expected `[node:]name:=value`"
165            ),
166            Self::IdentityRemap { rule } => write!(
167                f,
168                // RFC-0046
169                "`{rule}` remaps a node's identity; the launch file is the authority on a node's \
170                 name and namespace, and an argv rung beneath it is not implemented"
171            ),
172        }
173    }
174}
175
176/// Flags rcl defines that this parser recognises and refuses. Kept as data so
177/// the refusal names the flag rather than calling it unknown.
178const UNSUPPORTED_FLAGS: &[&str] = &["-e", "--enclave", "--log-level", "--log-config-file"];
179
180/// rcl's log-switch flags are `--enable-<suffix>` / `--disable-<suffix>` over
181/// these three suffixes (RCL_LOG_*_FLAG_SUFFIX).
182const LOG_SWITCH_SUFFIXES: &[&str] = &["stdout-logs", "rosout-logs", "external-lib-logs"];
183
184fn is_log_switch(token: &str) -> bool {
185    let rest = token
186        .strip_prefix("--enable-")
187        .or_else(|| token.strip_prefix("--disable-"));
188    matches!(rest, Some(s) if LOG_SWITCH_SUFFIXES.contains(&s))
189}
190
191/// Parse one `[node:]from:=to` rule.
192pub fn parse_remap_rule(rule: &str) -> Result<RemapArg<'_>, RosArgsError<'_>> {
193    let invalid = RosArgsError::InvalidRule { rule };
194    let (lhs, to) = rule.split_once(":=").ok_or(invalid)?;
195    if lhs.contains("://") || to.contains("://") {
196        // `rostopic://` / `rosservice://` — rcl's own unfinished form.
197        return Err(RosArgsError::Unsupported { flag: rule });
198    }
199    let (node, from) = match lhs.split_once(':') {
200        Some((node, from)) => (Some(node), from),
201        None => (None, lhs),
202    };
203    if from.starts_with("__") {
204        return Err(RosArgsError::IdentityRemap { rule });
205    }
206    let bad = |s: &str| s.is_empty() || s.contains(':') || s.chars().any(char::is_whitespace);
207    if bad(from) || bad(to) {
208        return Err(invalid);
209    }
210    if let Some(n) = node
211        && (bad(n) || n.contains('/') || n.contains('~'))
212    {
213        return Err(invalid);
214    }
215    Ok(RemapArg { node, from, to })
216}
217
218/// Parse one `[node:]name:=value` override. An empty value is allowed (it is
219/// an empty string parameter); an empty or blank name is not.
220pub fn parse_param_rule(rule: &str) -> Result<ParamArg<'_>, RosArgsError<'_>> {
221    let invalid = RosArgsError::InvalidParam { rule };
222    let (lhs, value) = rule.split_once(":=").ok_or(invalid)?;
223    let (node, name) = match lhs.split_once(':') {
224        Some((node, name)) => (Some(node), name),
225        None => (None, lhs),
226    };
227    let bad = |s: &str| s.is_empty() || s.contains(':') || s.chars().any(char::is_whitespace);
228    if bad(name) {
229        return Err(invalid);
230    }
231    if let Some(n) = node
232        && (bad(n) || n.contains('/') || n.contains('~'))
233    {
234        return Err(invalid);
235    }
236    Ok(ParamArg { node, name, value })
237}
238
239/// Parse `args` the way `rcl_parse_arguments` does, reporting each remap rule
240/// in argv order through `on_remap`.
241///
242/// Returns the first refusal, naming its token; `on_remap` may have been
243/// called for rules before it, so a caller that must be all-or-nothing should
244/// collect and only commit on `Ok`. Arguments outside every `--ros-args` scope
245/// are ignored, so a vector with no `--ros-args` reports nothing and succeeds.
246///
247/// The remap-only parse: a `-p` / `--params-file` here is REFUSED as
248/// unsupported, because a caller that only installs remaps would otherwise
249/// drop it. A caller that can hold parameter overrides uses
250/// [`parse_ros_args_events`].
251pub fn parse_ros_args<'a, I, F>(args: I, mut on_remap: F) -> Result<(), RosArgsError<'a>>
252where
253    I: IntoIterator<Item = &'a str>,
254    F: FnMut(RemapArg<'a>),
255{
256    parse_impl(args, false, |a| {
257        if let RosArg::Remap(r) = a {
258            on_remap(r);
259        }
260    })
261}
262
263/// Parse `args` like [`parse_ros_args`], reporting remaps AND parameter
264/// overrides (`-p`, `--params-file`) in argv order.
265pub fn parse_ros_args_events<'a, I, F>(args: I, on_arg: F) -> Result<(), RosArgsError<'a>>
266where
267    I: IntoIterator<Item = &'a str>,
268    F: FnMut(RosArg<'a>),
269{
270    parse_impl(args, true, on_arg)
271}
272
273fn parse_impl<'a, I, F>(args: I, params: bool, mut on_arg: F) -> Result<(), RosArgsError<'a>>
274where
275    I: IntoIterator<Item = &'a str>,
276    F: FnMut(RosArg<'a>),
277{
278    let mut in_scope = false;
279    let mut it = args.into_iter();
280    while let Some(arg) = it.next() {
281        if arg == "--ros-args" {
282            in_scope = true;
283            continue;
284        }
285        if !in_scope {
286            continue;
287        }
288        match arg {
289            "--" => in_scope = false,
290            "-r" | "--remap" => {
291                let rule = it.next().ok_or(RosArgsError::MissingRule { flag: arg })?;
292                on_arg(RosArg::Remap(parse_remap_rule(rule)?));
293            }
294            "-p" | "--param" | "--params-file" if !params => {
295                return Err(RosArgsError::Unsupported { flag: arg });
296            }
297            "-p" | "--param" => {
298                let rule = it.next().ok_or(RosArgsError::MissingValue { flag: arg })?;
299                on_arg(RosArg::Param(parse_param_rule(rule)?));
300            }
301            "--params-file" => {
302                let path = it.next().ok_or(RosArgsError::MissingValue { flag: arg })?;
303                on_arg(RosArg::ParamsFile(path));
304            }
305            flag if UNSUPPORTED_FLAGS.contains(&flag) || is_log_switch(flag) => {
306                return Err(RosArgsError::Unsupported { flag });
307            }
308            token => return Err(RosArgsError::Unknown { token }),
309        }
310    }
311    Ok(())
312}
313
314/// Why a parameter file was refused: the 1-based line, the line as written,
315/// and the reason. Every construct the subset does not read is a refusal,
316/// never a skip — a value silently dropped from a file is the same "compiles
317/// and differs" the argv parse exists to stop.
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319pub struct ParamsYamlError<'t> {
320    /// 1-based line number.
321    pub line: usize,
322    /// The offending line, trimmed.
323    pub text: &'t str,
324    /// What is wrong with it.
325    pub reason: &'static str,
326}
327
328impl core::fmt::Display for ParamsYamlError<'_> {
329    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
330        write!(f, "line {}: {}: `{}`", self.line, self.reason, self.text)
331    }
332}
333
334/// The longest dotted name [`parse_params_yaml`] builds (`group.sub.name`).
335pub const MAX_PARAMS_FILE_NAME_LEN: usize = 128;
336const MAX_PARAMS_FILE_DEPTH: usize = 8;
337
338/// Read a ROS 2 parameter file's TEXT — the `--params-file` format — and
339/// report each value through `on_param`, in file order.
340///
341/// The subset rcl's files use and nothing more:
342///
343/// ```yaml
344/// /**:                     # every node; or `talker` / `/ns/talker`
345///   ros__parameters:
346///     rate_hz: 10
347///     gains:
348///       kp: 1.5            # reported as `gains.kp`
349///     frame: "base_link"
350/// ```
351///
352/// A node key matches by its last segment, the node NAME, as `-p node:` and
353/// `-r node:` do; its namespace is not compared. Comments, blank lines and
354/// `---` are skipped. Refused, each with its line: tabs used as indentation,
355/// sequences and flow collections (array parameters are not read from a file
356/// yet), block scalars, anchors, wildcards other than `/**`, and any value not
357/// under `<node>: ros__parameters:`.
358///
359/// `no_std` and allocation-free: the dotted name is built in a fixed buffer
360/// and lent to `on_param` for the call.
361pub fn parse_params_yaml<'t, F>(text: &'t str, mut on_param: F) -> Result<(), ParamsYamlError<'t>>
362where
363    F: for<'n> FnMut(ParamArg<'n>),
364{
365    let mut stack: heapless::Vec<(usize, &'t str), MAX_PARAMS_FILE_DEPTH> = heapless::Vec::new();
366    for (i, raw) in text.lines().enumerate() {
367        let err = |reason| ParamsYamlError {
368            line: i + 1,
369            text: raw.trim(),
370            reason,
371        };
372        let content = yaml_strip_comment(raw);
373        let body = content.trim();
374        if body.is_empty() || body == "---" || body == "..." {
375            continue;
376        }
377        let lead = &content[..content.len() - content.trim_start().len()];
378        if lead.contains('\t') {
379            return Err(err("a tab is not YAML indentation"));
380        }
381        let indent = lead.len();
382        if body == "-" || body.starts_with("- ") {
383            return Err(err("a sequence is not read from a parameter file"));
384        }
385        let (key, rest) =
386            yaml_split_key(body).ok_or_else(|| err("expected `key:` or `key: value`"))?;
387        let key = yaml_unquote(key.trim());
388        while let Some(&(ind, _)) = stack.last() {
389            if ind >= indent {
390                stack.pop();
391            } else {
392                break;
393            }
394        }
395        let rest = rest.trim();
396        if rest.is_empty() {
397            stack
398                .push((indent, key))
399                .map_err(|_| err("nested deeper than a parameter file needs"))?;
400            continue;
401        }
402        if stack.len() < 2 {
403            return Err(err(
404                "a value must sit under `<node>:` then `ros__parameters:`",
405            ));
406        }
407        if stack[1].1 != "ros__parameters" {
408            return Err(err("the level under a node key must be `ros__parameters`"));
409        }
410        if rest.starts_with(['[', '{', '|', '>', '&', '*', '!']) {
411            return Err(err(
412                "an array, inline map, block scalar, anchor or tag is not read from a parameter file",
413            ));
414        }
415        let node = yaml_node_selector(stack[0].1)
416            .ok_or_else(|| err("only the `/**` wildcard is supported"))?;
417        let mut name: heapless::String<MAX_PARAMS_FILE_NAME_LEN> = heapless::String::new();
418        for &(_, group) in &stack[2..] {
419            name.push_str(group)
420                .and_then(|_| name.push('.'))
421                .map_err(|_| err("parameter name longer than MAX_PARAMS_FILE_NAME_LEN"))?;
422        }
423        name.push_str(key)
424            .map_err(|_| err("parameter name longer than MAX_PARAMS_FILE_NAME_LEN"))?;
425        on_param(ParamArg {
426            node,
427            name: &name,
428            value: yaml_unquote(rest),
429        });
430    }
431    Ok(())
432}
433
434/// The line up to a `#` comment that is not inside quotes.
435fn yaml_strip_comment(line: &str) -> &str {
436    let mut quote = None;
437    let mut prev_space = true;
438    for (i, c) in line.char_indices() {
439        match (quote, c) {
440            (None, '"' | '\'') => quote = Some(c),
441            (Some(q), c) if c == q => quote = None,
442            (None, '#') if prev_space => return &line[..i],
443            _ => {}
444        }
445        prev_space = c.is_whitespace();
446    }
447    line
448}
449
450/// `key: rest` / `key:` — the first `:` outside quotes followed by a space or
451/// the end of the line.
452fn yaml_split_key(body: &str) -> Option<(&str, &str)> {
453    let mut quote = None;
454    let bytes = body.as_bytes();
455    for (i, c) in body.char_indices() {
456        match (quote, c) {
457            (None, '"' | '\'') => quote = Some(c),
458            (Some(q), c) if c == q => quote = None,
459            (None, ':') if i + 1 == bytes.len() || bytes[i + 1] == b' ' => {
460                return Some((&body[..i], &body[i + 1..]));
461            }
462            _ => {}
463        }
464    }
465    None
466}
467
468fn yaml_unquote(s: &str) -> &str {
469    let b = s.as_bytes();
470    if b.len() >= 2 && (b[0] == b'"' || b[0] == b'\'') && b[b.len() - 1] == b[0] {
471        &s[1..s.len() - 1]
472    } else {
473        s
474    }
475}
476
477/// `None` for every node (`/**`, `**`), `Some(name)` for a node key, or a
478/// refusal (`Err` as `None` of the outer option) for another wildcard.
479#[allow(clippy::option_option)]
480fn yaml_node_selector(key: &str) -> Option<Option<&str>> {
481    match key {
482        "/**" | "**" => Some(None),
483        k if k.contains('*') => None,
484        k => Some(Some(k.rsplit('/').next().unwrap_or(k))),
485    }
486}
487
488#[cfg(any(has_rmw, test))]
489/// Install parsed `-r` rules in `executor`'s remap table as its FALLBACK tier.
490///
491/// They then reach every entity the executor creates on every road —
492/// `Executor::resolve_entity_name_for` (C, C++), the Rust component sink
493/// (through [`argv_fallback`]) and `Executor::create_node`'s handle — and in
494/// each, a launch rule for the same name still wins.
495///
496/// All or nothing: on failure nothing is installed and the rule that did not
497/// fit is returned (a full table — the executor's runtime table,
498/// `MAX_REMAPS` slots shared with hand-declared rules and none on bare metal —
499/// or a name past its slot's length). Silently installing a prefix of
500/// the rules would be a partial version of the drop this exists to prevent.
501pub fn install_argv_remaps<'r, I>(
502    executor: &mut crate::executor::Executor<'_>,
503    rules: I,
504) -> Result<(), RemapArg<'r>>
505where
506    I: IntoIterator<Item = RemapArg<'r>>,
507    I::IntoIter: Clone,
508{
509    use crate::executor::spin::{RemapRule, RemapTier};
510    let rules = rules.into_iter();
511    let start = executor.remap_len;
512    for (i, r) in rules.clone().enumerate() {
513        let mut rule = RemapRule {
514            node_name: heapless::String::new(),
515            namespace: heapless::String::new(),
516            from: heapless::String::new(),
517            to: heapless::String::new(),
518            tier: RemapTier::Argv,
519        };
520        let fits = rule.node_name.push_str(r.node.unwrap_or("")).is_ok()
521            && rule.from.push_str(r.from).is_ok()
522            && rule.to.push_str(r.to).is_ok();
523        let slot = executor.remap_table.get_mut(start + i);
524        match (fits, slot) {
525            (true, Some(slot)) => *slot = Some(rule),
526            _ => {
527                for s in &mut executor.remap_table[start..start + i] {
528                    *s = None;
529                }
530                return Err(r);
531            }
532        }
533    }
534    executor.remap_len = start + rules.count();
535    Ok(())
536}
537
538#[cfg(any(has_rmw, test))]
539/// Why [`apply_ros_args`] refused an argument vector.
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub enum ApplyError<'a> {
542    /// The parse refused a token ([`parse_ros_args`]).
543    Refused(RosArgsError<'a>),
544    /// The rule did not fit: the runtime remap table is full or absent (its
545    /// slots are shared with hand-declared rules), or a name is longer than
546    /// its slot.
547    DoesNotFit(RemapArg<'a>),
548}
549
550#[cfg(any(has_rmw, test))]
551impl core::fmt::Display for ApplyError<'_> {
552    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
553        match self {
554            Self::Refused(e) => e.fmt(f),
555            Self::DoesNotFit(r) => write!(
556                f,
557                "remap `{}:={}` does not fit: the executor's runtime remap table holds {} \
558                 rules (NROS_EXECUTOR_RUNTIME_REMAPS; 0 on bare metal, which has no argv), \
559                 shared with hand-declared rules; `from`/`to` hold {} bytes, a `node:` \
560                 prefix 64",
561                r.from,
562                r.to,
563                crate::executor::spin::MAX_REMAPS,
564                crate::names::MAX_RESOLVED_NAME_LEN,
565            ),
566        }
567    }
568}
569
570#[cfg(any(has_rmw, test))]
571/// Parse `args` and, given an executor, install its `-r` rules as the
572/// FALLBACK tier — the whole of "honour `--ros-args`" for a caller with no
573/// allocator (the C++ ABI, `nros_cpp_install_argv_remaps`).
574///
575/// With `executor = None` it only VALIDATES, so a caller can refuse a bad
576/// vector before opening a session at all. All or nothing either way: on any
577/// error nothing is installed. Returns the number of rules installed (or that
578/// would be).
579// `MAX_REMAPS` is 0 on bare metal (no runtime remap table, issue 1971): every
580// rule is then the overflow, refused by name.
581#[allow(clippy::absurd_extreme_comparisons)]
582pub fn apply_ros_args<'a, I>(
583    executor: Option<&mut crate::executor::Executor<'_>>,
584    args: I,
585) -> Result<usize, ApplyError<'a>>
586where
587    I: IntoIterator<Item = &'a str>,
588{
589    const N: usize = crate::executor::spin::MAX_REMAPS;
590    let mut rules: [Option<RemapArg<'a>>; N] = [None; N];
591    let mut n = 0usize;
592    let mut overflow = None;
593    parse_ros_args(args, |r| {
594        if n < N {
595            rules[n] = Some(r);
596            n += 1;
597        } else if overflow.is_none() {
598            overflow = Some(r);
599        }
600    })
601    .map_err(ApplyError::Refused)?;
602    if let Some(r) = overflow {
603        return Err(ApplyError::DoesNotFit(r));
604    }
605    if let Some(executor) = executor {
606        install_argv_remaps(executor, rules[..n].iter().flatten().copied())
607            .map_err(ApplyError::DoesNotFit)?;
608    }
609    Ok(n)
610}
611
612#[cfg(all(any(has_rmw, test), feature = "param-store", feature = "alloc"))]
613/// Why [`apply_ros_args_with_params`] refused an argument vector.
614#[derive(Debug, Clone)]
615pub enum ApplyParamsError<'a> {
616    /// The remap half refused it, exactly as [`apply_ros_args`] would.
617    Remaps(ApplyError<'a>),
618    /// `--params-file <path>` could not be read; the reason is the reader's.
619    Unreadable {
620        /// The path as written.
621        path: &'a str,
622        /// What the reader said.
623        why: alloc::string::String,
624    },
625    /// The file was read and its text refused by [`parse_params_yaml`].
626    BadFile {
627        /// The path as written.
628        path: &'a str,
629        /// `line N: reason: `text``.
630        why: alloc::string::String,
631    },
632    /// The parameter store could not be allocated (issue 1706).
633    NoStore,
634}
635
636#[cfg(all(any(has_rmw, test), feature = "param-store", feature = "alloc"))]
637impl core::fmt::Display for ApplyParamsError<'_> {
638    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
639        match self {
640            Self::Remaps(e) => e.fmt(f),
641            Self::Unreadable { path, why } => {
642                write!(f, "`--params-file {path}` cannot be read: {why}")
643            }
644            Self::BadFile { path, why } => write!(f, "`--params-file {path}`, {why}"),
645            Self::NoStore => f.write_str(
646                "the parameter store could not be allocated, so the parameter overrides have \
647                 nowhere to go",
648            ),
649        }
650    }
651}
652
653#[cfg(all(any(has_rmw, test), feature = "param-store", feature = "alloc"))]
654/// [`apply_ros_args`], plus the parameter half.
655///
656/// `-r` rules are installed as [`apply_ros_args`] installs them. `-p` overrides
657/// and every `--params-file` (read through `read_file`, which is the caller's:
658/// this crate has no file system) are installed with
659/// `Executor::install_argv_params`, in argv order, so a later value wins.
660///
661/// With `executor = None` it only VALIDATES — files are still read and parsed,
662/// so a bad file is refused before a session opens. All or nothing: on any
663/// error nothing is installed.
664pub fn apply_ros_args_with_params<'a, I, R>(
665    executor: Option<&mut crate::executor::Executor<'_>>,
666    args: I,
667    mut read_file: R,
668) -> Result<usize, ApplyParamsError<'a>>
669where
670    I: IntoIterator<Item = &'a str> + Clone,
671    R: FnMut(&str) -> Result<alloc::string::String, alloc::string::String>,
672{
673    use alloc::string::String;
674    // Pass 1: the remaps and the refusals, through the remap-only grammar's
675    // twin so a refused token reports exactly as before.
676    let mut params: alloc::vec::Vec<(Option<String>, String, String)> = alloc::vec::Vec::new();
677    let mut files: alloc::vec::Vec<&'a str> = alloc::vec::Vec::new();
678    let mut order: alloc::vec::Vec<Result<usize, usize>> = alloc::vec::Vec::new();
679    parse_ros_args_events(args.clone(), |a| match a {
680        RosArg::Param(p) => {
681            order.push(Ok(params.len()));
682            params.push((
683                p.node.map(String::from),
684                String::from(p.name),
685                String::from(p.value),
686            ));
687        }
688        RosArg::ParamsFile(path) => {
689            order.push(Err(files.len()));
690            files.push(path);
691        }
692        RosArg::Remap(_) => {}
693    })
694    .map_err(|e| ApplyParamsError::Remaps(ApplyError::Refused(e)))?;
695    // Read and parse every file before installing anything.
696    let mut file_params: alloc::vec::Vec<alloc::vec::Vec<(Option<String>, String, String)>> =
697        alloc::vec::Vec::new();
698    for &path in &files {
699        let text = read_file(path).map_err(|why| ApplyParamsError::Unreadable { path, why })?;
700        let mut got = alloc::vec::Vec::new();
701        parse_params_yaml(&text, |p| {
702            got.push((
703                p.node.map(String::from),
704                String::from(p.name),
705                String::from(p.value),
706            ))
707        })
708        .map_err(|e| ApplyParamsError::BadFile {
709            path,
710            why: alloc::format!("{e}"),
711        })?;
712        file_params.push(got);
713    }
714    // The remap half, minus the parameter flags it would refuse.
715    let remap_args = args.into_iter().scan(false, |skip, a| {
716        if core::mem::take(skip) {
717            return Some(None);
718        }
719        if matches!(a, "-p" | "--param" | "--params-file") {
720            *skip = true;
721            return Some(None);
722        }
723        Some(Some(a))
724    });
725    let remap_args: alloc::vec::Vec<&'a str> = remap_args.flatten().collect();
726    let Some(executor) = executor else {
727        let n =
728            apply_ros_args(None, remap_args.iter().copied()).map_err(ApplyParamsError::Remaps)?;
729        return Ok(n + params.len() + file_params.iter().map(alloc::vec::Vec::len).sum::<usize>());
730    };
731    // Commit in the order that keeps it all-or-nothing: make sure the store
732    // exists (the one way the parameter half can fail), then the remaps (which
733    // are all-or-nothing on their own), then the parameters, which can no
734    // longer fail.
735    executor
736        .install_argv_params(core::iter::empty())
737        .map_err(|_| ApplyParamsError::NoStore)?;
738    let n = apply_ros_args(Some(&mut *executor), remap_args.iter().copied())
739        .map_err(ApplyParamsError::Remaps)?;
740    let mut flat: alloc::vec::Vec<&(Option<String>, String, String)> = alloc::vec::Vec::new();
741    for slot in &order {
742        match *slot {
743            Ok(i) => flat.push(&params[i]),
744            Err(f) => flat.extend(file_params[f].iter()),
745        }
746    }
747    let m = executor
748        .install_argv_params(flat.iter().map(|(node, name, value)| ParamArg {
749            node: node.as_deref(),
750            name,
751            value,
752        }))
753        .map_err(|_| ApplyParamsError::NoStore)?;
754    Ok(n + m)
755}
756
757#[cfg(any(has_rmw, test))]
758/// The installed argv rules that apply to the node named `node_name` (in
759/// `namespace`), as a fallback tier for [`crate::names::resolve_name_layered`].
760///
761/// For a resolver that keeps its AUTHORITATIVE rules somewhere other than the
762/// executor's table — the Rust component sink holds its launch rules as a
763/// slice on `RuntimeCtx` — and so cannot use
764/// `Executor::resolve_entity_name_for` directly.
765pub fn argv_fallback<'e>(
766    executor: &'e crate::executor::Executor<'_>,
767    node_name: &'e str,
768    namespace: &'e str,
769) -> impl Iterator<Item = (&'e str, &'e str)> + 'e {
770    use crate::executor::spin::{RemapTier, tier_rules};
771    tier_rules(
772        &executor.remap_table[..executor.remap_len],
773        RemapTier::Argv,
774        node_name,
775        namespace,
776    )
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782
783    fn rules<'a>(args: &[&'a str]) -> Result<heapless::Vec<RemapArg<'a>, 8>, RosArgsError<'a>> {
784        let mut out = heapless::Vec::new();
785        parse_ros_args(args.iter().copied(), |r| out.push(r).unwrap())?;
786        Ok(out)
787    }
788
789    fn rule<'a>(node: Option<&'a str>, from: &'a str, to: &'a str) -> RemapArg<'a> {
790        RemapArg { node, from, to }
791    }
792
793    #[test]
794    fn no_scope_reports_nothing_and_leaves_user_arguments_alone() {
795        assert!(
796            rules(&["prog", "-r", "a:=b", "--verbose"])
797                .unwrap()
798                .is_empty()
799        );
800        assert!(rules(&[]).unwrap().is_empty());
801    }
802
803    #[test]
804    fn short_and_long_remap_flags_keep_argv_order() {
805        let got = rules(&[
806            "prog",
807            "--ros-args",
808            "-r",
809            "foo:=bar",
810            "--remap",
811            "bar:=baz",
812        ])
813        .unwrap();
814        assert_eq!(
815            got.as_slice(),
816            &[rule(None, "foo", "bar"), rule(None, "bar", "baz")]
817        );
818    }
819
820    #[test]
821    fn a_node_prefix_scopes_the_rule() {
822        let got = rules(&["--ros-args", "-r", "alice:foo:=~/bar"]).unwrap();
823        assert_eq!(got.as_slice(), &[rule(Some("alice"), "foo", "~/bar")]);
824    }
825
826    #[test]
827    fn double_dash_closes_the_scope_and_a_second_scope_reopens_it() {
828        let got = rules(&[
829            "--ros-args",
830            "-r",
831            "a:=b",
832            "--",
833            "-r",
834            "user:=arg",
835            "--ros-args",
836            "-r",
837            "c:=d",
838        ])
839        .unwrap();
840        assert_eq!(
841            got.as_slice(),
842            &[rule(None, "a", "b"), rule(None, "c", "d")]
843        );
844    }
845
846    #[test]
847    fn parameter_overrides_are_refused_by_name() {
848        for flag in ["-p", "--param", "--params-file"] {
849            assert_eq!(
850                rules(&["--ros-args", flag, "x:=1"]),
851                Err(RosArgsError::Unsupported { flag })
852            );
853        }
854    }
855
856    #[test]
857    fn enclave_and_log_flags_are_refused_by_name() {
858        for flag in [
859            "-e",
860            "--enclave",
861            "--log-level",
862            "--log-config-file",
863            "--disable-rosout-logs",
864        ] {
865            assert_eq!(
866                rules(&["--ros-args", flag]),
867                Err(RosArgsError::Unsupported { flag })
868            );
869        }
870    }
871
872    #[test]
873    fn an_unknown_token_inside_a_scope_is_refused_not_skipped() {
874        assert_eq!(
875            rules(&["--ros-args", "-r", "a:=b", "--frobnicate"]),
876            Err(RosArgsError::Unknown {
877                token: "--frobnicate"
878            })
879        );
880        // A look-alike of a real log switch is still unknown, not a switch.
881        assert_eq!(
882            rules(&["--ros-args", "--enable-everything"]),
883            Err(RosArgsError::Unknown {
884                token: "--enable-everything"
885            })
886        );
887    }
888
889    #[test]
890    fn a_remap_flag_needs_a_valid_rule_after_it() {
891        assert_eq!(
892            rules(&["--ros-args", "-r"]),
893            Err(RosArgsError::MissingRule { flag: "-r" })
894        );
895        for bad in [
896            "nocolon", ":=b", "a:=", "a b:=c", ":a:=b", "n/s:a:=b", "a:=b:c",
897        ] {
898            assert_eq!(
899                rules(&["--ros-args", "--remap", bad]),
900                Err(RosArgsError::InvalidRule { rule: bad }),
901                "{bad}"
902            );
903        }
904    }
905
906    #[test]
907    fn identity_remaps_are_refused() {
908        for r in ["__node:=x", "__name:=x", "__ns:=/x", "talker:__ns:=/x"] {
909            assert_eq!(
910                rules(&["--ros-args", "-r", r]),
911                Err(RosArgsError::IdentityRemap { rule: r })
912            );
913        }
914    }
915
916    // ---------------------------------------------------------------------
917    // The producer feeding the seam: real argv -> parse -> install -> resolve.
918    //
919    // `names.rs`'s precedence tests hand `resolve_name_layered` two arrays;
920    // these run the whole chain a hosted `init_with_args` caller gets, against
921    // the executor's own table and resolver.
922    // ---------------------------------------------------------------------
923
924    /// Same gate as `executor::node`'s tests: `Executor::from_session` over a
925    /// `MockSession` needs `std` and no linked backend.
926    #[cfg(all(feature = "alloc", not(feature = "rmw-cffi")))]
927    mod chain {
928        use super::super::*;
929        extern crate std;
930        use crate::{executor::Executor, mock::MockSession};
931
932        fn executor() -> Executor<'static> {
933            Executor::from_session(MockSession::new())
934        }
935
936        /// Parse `argv` and install what it carries, the way
937        /// `nros::Context::create_executor` does.
938        fn install_argv(exec: &mut Executor<'_>, argv: &[&'static str]) {
939            let mut parsed: std::vec::Vec<RemapArg<'static>> = std::vec::Vec::new();
940            parse_ros_args(argv.iter().copied(), |r| parsed.push(r)).expect("argv parses");
941            install_argv_remaps(exec, parsed.iter().copied()).expect("rules fit");
942        }
943
944        fn resolve(exec: &Executor<'_>, node: &str, source: &str) -> std::string::String {
945            std::string::String::from(
946                exec.resolve_entity_name_for(node, "/", source)
947                    .unwrap()
948                    .as_str(),
949            )
950        }
951
952        #[test]
953        fn a_launch_rule_wins_over_argv_even_when_argv_was_installed_first() {
954            // Declaration order argues for the WRONG winner here: the argv rule
955            // sits in the table first. A flat first-match over the table (the
956            // shape before tiers) hands it the name.
957            let mut exec = executor();
958            install_argv(
959                &mut exec,
960                &["prog", "--ros-args", "-r", "chatter:=/from_argv"],
961            );
962            exec.declare_remap("talker", "/", "chatter", "/from_launch")
963                .unwrap();
964            assert_eq!(resolve(&exec, "talker", "chatter"), "/from_launch");
965        }
966
967        #[test]
968        fn an_argv_rule_applies_where_the_launch_projected_none() {
969            let mut exec = executor();
970            install_argv(
971                &mut exec,
972                &["prog", "--ros-args", "-r", "chatter:=/from_argv"],
973            );
974            exec.declare_remap("talker", "/", "chatter", "/from_launch")
975                .unwrap();
976            // `listener` has no launch rule for `chatter`, so the fallback answers.
977            assert_eq!(resolve(&exec, "listener", "chatter"), "/from_argv");
978            // ...and a name no rule mentions is only expanded.
979            assert_eq!(resolve(&exec, "talker", "other"), "/other");
980        }
981
982        // Issue 1971 -- the launch rules are the flash table now; the same
983        // layering holds against it.
984        static LAUNCH: [crate::executor::LaunchRemap; 1] = [crate::executor::LaunchRemap::new(
985            c"talker",
986            c"/",
987            c"chatter",
988            c"/from_flash",
989        )];
990
991        #[test]
992        fn a_flash_launch_rule_wins_over_argv() {
993            let mut exec = executor();
994            install_argv(
995                &mut exec,
996                &["prog", "--ros-args", "-r", "chatter:=/from_argv"],
997            );
998            exec.set_launch_remaps(&LAUNCH);
999            assert_eq!(resolve(&exec, "talker", "chatter"), "/from_flash");
1000            // A node the flash table names no rule for still falls back.
1001            assert_eq!(resolve(&exec, "listener", "chatter"), "/from_argv");
1002        }
1003
1004        #[test]
1005        fn a_flash_launch_rule_takes_no_runtime_slot() {
1006            let mut exec = executor();
1007            exec.set_launch_remaps(&LAUNCH);
1008            assert_eq!(exec.remap_len, 0);
1009            assert_eq!(resolve(&exec, "talker", "chatter"), "/from_flash");
1010        }
1011
1012        #[test]
1013        fn a_node_prefixed_argv_rule_reaches_only_that_node() {
1014            let mut exec = executor();
1015            install_argv(
1016                &mut exec,
1017                &["--ros-args", "-r", "talker:chatter:=/only_talker"],
1018            );
1019            assert_eq!(resolve(&exec, "talker", "chatter"), "/only_talker");
1020            assert_eq!(resolve(&exec, "listener", "chatter"), "/chatter");
1021        }
1022
1023        #[test]
1024        fn within_argv_the_first_rule_wins() {
1025            // rcl: `foo:=bar bar:=baz` sends `foo` to `bar`, never `baz`.
1026            let mut exec = executor();
1027            install_argv(
1028                &mut exec,
1029                &["--ros-args", "-r", "foo:=bar", "-r", "bar:=baz"],
1030            );
1031            assert_eq!(resolve(&exec, "n", "foo"), "/bar");
1032        }
1033
1034        #[test]
1035        fn argv_fallback_yields_only_argv_rules_for_the_named_node() {
1036            // What the Rust component sink reads as its fallback tier.
1037            let mut exec = executor();
1038            install_argv(
1039                &mut exec,
1040                &["--ros-args", "-r", "a:=/x", "-r", "other:b:=/y"],
1041            );
1042            exec.declare_remap("talker", "/", "a", "/launch").unwrap();
1043            let got: std::vec::Vec<_> = argv_fallback(&exec, "talker", "/").collect();
1044            assert_eq!(got, [("a", "/x")]);
1045        }
1046
1047        #[test]
1048        fn install_is_all_or_nothing() {
1049            let mut exec = executor();
1050            let free = exec.remap_table.len();
1051            for i in 0..free - 1 {
1052                let from = std::format!("/f{i}");
1053                exec.declare_remap("n", "/", &from, "/t").unwrap();
1054            }
1055            let before = exec.remap_len;
1056            let rules = [
1057                RemapArg {
1058                    node: None,
1059                    from: "fits",
1060                    to: "/a",
1061                },
1062                RemapArg {
1063                    node: None,
1064                    from: "does_not",
1065                    to: "/b",
1066                },
1067            ];
1068            assert_eq!(install_argv_remaps(&mut exec, rules), Err(rules[1]));
1069            assert_eq!(
1070                exec.remap_len, before,
1071                "a refused install leaves no rule behind"
1072            );
1073            assert_eq!(resolve(&exec, "n", "fits"), "/fits");
1074        }
1075    }
1076
1077    #[test]
1078    fn kind_qualified_remaps_are_refused() {
1079        let r = "rostopic://foo:=bar";
1080        assert_eq!(
1081            rules(&["--ros-args", "-r", r]),
1082            Err(RosArgsError::Unsupported { flag: r })
1083        );
1084    }
1085
1086    #[test]
1087    fn apply_validates_without_an_executor_and_installs_nothing() {
1088        let ok = [
1089            "prog",
1090            "--ros-args",
1091            "-r",
1092            "a:=b",
1093            "-r",
1094            "n:c:=d",
1095            "--",
1096            "x",
1097        ];
1098        assert_eq!(apply_ros_args(None, ok.iter().copied()), Ok(2));
1099        assert_eq!(
1100            apply_ros_args(None, ["prog", "plain"].iter().copied()),
1101            Ok(0)
1102        );
1103    }
1104
1105    #[test]
1106    fn apply_refuses_by_name_what_the_parse_refuses() {
1107        let bad = ["prog", "--ros-args", "-r", "a:=b", "-p", "x:=1"];
1108        assert_eq!(
1109            apply_ros_args(None, bad.iter().copied()),
1110            Err(ApplyError::Refused(RosArgsError::Unsupported {
1111                flag: "-p"
1112            }))
1113        );
1114    }
1115
1116    #[test]
1117    fn apply_refuses_more_rules_than_the_table_can_ever_hold() {
1118        const N: usize = crate::executor::spin::MAX_REMAPS;
1119        let mut args: heapless::Vec<&str, { 2 + 2 * (N + 1) }> = heapless::Vec::new();
1120        args.extend_from_slice(&["prog", "--ros-args"]).unwrap();
1121        for _ in 0..=N {
1122            args.extend_from_slice(&["-r", "a:=b"]).unwrap();
1123        }
1124        assert!(matches!(
1125            apply_ros_args(None, args.iter().copied()),
1126            Err(ApplyError::DoesNotFit(_))
1127        ));
1128    }
1129}
1130
1131// `alloc` for the YAML helper's owned rows; the lanes that build nros-node
1132// without it (the declared-QoS registration check) still compile its tests.
1133#[cfg(all(test, feature = "alloc"))]
1134mod param_tests {
1135    use super::*;
1136
1137    fn events<'a>(args: &[&'a str]) -> Result<heapless::Vec<RosArg<'a>, 8>, RosArgsError<'a>> {
1138        let mut out = heapless::Vec::new();
1139        parse_ros_args_events(args.iter().copied(), |a| out.push(a).unwrap())?;
1140        Ok(out)
1141    }
1142
1143    #[test]
1144    fn p_and_params_file_are_events_in_argv_order() {
1145        let got = events(&[
1146            "prog",
1147            "--ros-args",
1148            "-p",
1149            "a:=1",
1150            "--params-file",
1151            "x.yaml",
1152            "-r",
1153            "f:=t",
1154            "--param",
1155            "n:b:=two",
1156        ])
1157        .unwrap();
1158        assert_eq!(got.len(), 4);
1159        assert_eq!(
1160            got[0],
1161            RosArg::Param(ParamArg {
1162                node: None,
1163                name: "a",
1164                value: "1"
1165            })
1166        );
1167        assert_eq!(got[1], RosArg::ParamsFile("x.yaml"));
1168        assert!(matches!(got[2], RosArg::Remap(_)));
1169        assert_eq!(
1170            got[3],
1171            RosArg::Param(ParamArg {
1172                node: Some("n"),
1173                name: "b",
1174                value: "two"
1175            })
1176        );
1177    }
1178
1179    #[test]
1180    fn the_remap_only_parse_still_refuses_parameter_flags() {
1181        let r = parse_ros_args(["prog", "--ros-args", "-p", "a:=1"], |_| {});
1182        assert_eq!(r, Err(RosArgsError::Unsupported { flag: "-p" }));
1183        let r = parse_ros_args(["prog", "--ros-args", "--params-file", "x"], |_| {});
1184        assert_eq!(
1185            r,
1186            Err(RosArgsError::Unsupported {
1187                flag: "--params-file"
1188            })
1189        );
1190    }
1191
1192    #[test]
1193    fn malformed_overrides_are_refused_by_name() {
1194        assert_eq!(
1195            events(&["p", "--ros-args", "-p"]).unwrap_err(),
1196            RosArgsError::MissingValue { flag: "-p" }
1197        );
1198        assert_eq!(
1199            events(&["p", "--ros-args", "-p", "novalue"]).unwrap_err(),
1200            RosArgsError::InvalidParam { rule: "novalue" }
1201        );
1202        assert_eq!(
1203            events(&["p", "--ros-args", "--params-file"]).unwrap_err(),
1204            RosArgsError::MissingValue {
1205                flag: "--params-file"
1206            }
1207        );
1208        // An empty VALUE is an empty string, not a malformed rule.
1209        assert_eq!(
1210            events(&["p", "--ros-args", "-p", "label:="]).unwrap()[0],
1211            RosArg::Param(ParamArg {
1212                node: None,
1213                name: "label",
1214                value: ""
1215            })
1216        );
1217    }
1218
1219    fn yaml(
1220        text: &str,
1221    ) -> Result<
1222        alloc::vec::Vec<(
1223            Option<alloc::string::String>,
1224            alloc::string::String,
1225            alloc::string::String,
1226        )>,
1227        alloc::string::String,
1228    > {
1229        let mut out = alloc::vec::Vec::new();
1230        parse_params_yaml(text, |p| {
1231            out.push((
1232                p.node.map(alloc::string::String::from),
1233                alloc::string::String::from(p.name),
1234                alloc::string::String::from(p.value),
1235            ))
1236        })
1237        .map_err(|e| alloc::format!("{e}"))?;
1238        Ok(out)
1239    }
1240
1241    #[test]
1242    fn a_params_file_reports_dotted_names_per_node() {
1243        let got = yaml("/**:\n  ros__parameters:\n    a: 1  # c\n    g:\n      b: 'x # not a comment'\n/ns/talker:\n  ros__parameters:\n    c: true\n").unwrap();
1244        assert_eq!(got.len(), 3);
1245        assert_eq!(got[0], (None, "a".into(), "1".into()));
1246        assert_eq!(got[1], (None, "g.b".into(), "x # not a comment".into()));
1247        assert_eq!(got[2], (Some("talker".into()), "c".into(), "true".into()));
1248    }
1249
1250    #[test]
1251    fn what_the_subset_does_not_read_is_refused_with_its_line() {
1252        let e = yaml("/**:\n  ros__parameters:\n    xs: [1, 2]\n").unwrap_err();
1253        assert!(e.starts_with("line 3:"), "{e}");
1254        let e = yaml("/**:\n  params:\n    a: 1\n").unwrap_err();
1255        assert!(e.contains("ros__parameters"), "{e}");
1256        let e = yaml("/*/x:\n  ros__parameters:\n    a: 1\n").unwrap_err();
1257        assert!(e.contains("wildcard"), "{e}");
1258        let e = yaml("/**:\n\tros__parameters:\n").unwrap_err();
1259        assert!(e.contains("tab"), "{e}");
1260        let e = yaml("/**:\n  ros__parameters:\n    - a\n").unwrap_err();
1261        assert!(e.contains("sequence"), "{e}");
1262    }
1263}