Skip to main content

nros/
init.rs

1//! Top-level init API, on every target.
2//!
3//! [`Context`] is WHERE this image is connected — locator, domain, RMW,
4//! session mode, and the source those came from. One per process or
5//! image; a resolved value, not an
6//! entity on the graph. A `Node` is a named participant with its own
7//! entities, and one image holds several of those on one `Context`.
8//!
9//! ## Where the values come from
10//!
11//! * **Hosted** (feature `env`): the process environment (`ROS_DOMAIN_ID`,
12//!   `NROS_LOCATOR`, `NROS_SESSION_MODE`, `NROS_RMW` / `RMW_IMPLEMENTATION`)
13//!   through the one hosted resolver, `crate::env::try_resolve_hosted`. A
14//!   launcher projects per-node values into that environment before exec.
15//! * **Freestanding** (no `env`): there is no process and no environment; the
16//!   same values are BAKED at compile time — `option_env!("NROS_ENTRY_LOCATOR")` and
17//!   `option_env!("NROS_ENTRY_DOMAIN_ID")`, exported into this crate's build by
18//!   `nros_zephyr_build::bake_nros_config()` from Kconfig (`build.rs`), or
19//!   present in the process environment of the build for the other RTOS lanes
20//!   (the board crates read the same two names the same way). The semantics
21//!   survive with the source moved from run time to build time: "the
22//!   environment this image was built for or launched in".
23//!
24//! The `env` feature gates ONLY the process-environment reader and the
25//! argv/launch entry points; `Context`, [`ContextSource`], [`InitError`],
26//! [`InitOptions`] and [`Context::config`] compile on every target. The floor
27//! for `Context` itself is `alloc`: `locator` and `rmw` are owned `String`s
28//! so the value outlives whatever transient produced it (an env cache, a
29//! parsed launch file, a harness-supplied override).
30//!
31//! ## The rclrs family
32//!
33//! [`Context::default_from_env`], [`Context::from_env`] and (hosted only)
34//! [`Context::new`] are the `rclrs::Context` constructors under the same
35//! names; [`InitOptions`] is rclrs's, with the one option it has. [`init()`] is
36//! the C++-symmetric anchor (`rclcpp::init`) and equals `default_from_env()`.
37//!
38//! Two patterns are supported:
39//!
40//! 1. **Node pkg** — register via the [`nros::node!`](crate::node!)
41//!    macro; the generated runtime owns the spin loop and
42//!    builds its `Context` through [`Context::default_from_env`].
43//! 2. **Application pkg** — call [`init()`] / [`Context::default_from_env`]
44//!    (or [`init_with_args`] / [`Context::new`] for argv-style entry) and
45//!    drive your own spin. The returned [`Context`] carries the domain id,
46//!    locator and RMW choice from the environment — see "Where launch content
47//!    comes from" below.
48//!
49//! To actually open a session, call [`Context::create_executor`] (`alloc`) or
50//! [`Context::create_executor_in`] (caller-supplied backing, nothing leaked),
51//! then name each node with `Executor::create_node`. The older spelling —
52//! materialise an [`crate::ExecutorConfig`] via [`Context::config`] and pass it
53//! to `Executor::open` — still works and is what a single-node entry wants;
54//! the pair was added because it cannot express the second node.
55//!
56//! ## Where launch content comes from
57//!
58//! Nothing here reads a launch file at run time. A launch tree reaches an
59//! image at BUILD time: `nros sync` resolves it into the image's SystemModel,
60//! and the generated entry (`nros::main!(launch = …)`,
61//! `nano_ros_entry(… LAUNCH …)`) installs its node identities, remaps and
62//! parameters. What is left for init to read is the environment
63//! (`ROS_DOMAIN_ID`, `NROS_LOCATOR`, `NROS_SESSION_MODE`,
64//! `RMW_IMPLEMENTATION`) and, through [`init_with_args`] / [`Context::new`],
65//! per-process `--ros-args`. (The runtime-overlay
66//! placeholder was retired, and with it the ~~`init_with_launch*`~~ entry points
67//! named after it.)
68
69#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
70use core::mem::MaybeUninit;
71
72#[cfg(feature = "alloc")]
73use nros_node::DOMAIN_ID_MAX;
74#[cfg(feature = "alloc")]
75use nros_node::ExecutorConfig;
76// phase-427 W10 — the open failure a `create_executor*` call can carry back.
77// Ungated: `NodeError` lives in `nros_node::executor::types`, which is compiled
78// on every target, and [`InitError`] is on every target too (W9).
79use nros_node::NodeError;
80#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
81use nros_node::{Executor, ExecutorSizing};
82#[cfg(feature = "alloc")]
83use nros_rmw::SessionMode;
84
85/// Errors returned by the init API.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum InitError {
88    /// A launch-derived env var (`ROS_DOMAIN_ID`, etc.) failed to parse —
89    /// or, freestanding, the baked `NROS_ENTRY_DOMAIN_ID` is not a decimal integer.
90    EnvParseFailed,
91    /// A domain id — from the environment, the bake, or an
92    /// [`InitOptions::with_domain_id`] override — exceeds
93    /// [`crate::DOMAIN_ID_MAX`]. Rejected here rather than
94    /// handed to a backend that can only fail later (the #206 rule).
95    DomainIdOutOfRange,
96    /// phase-484 W8c — a RETIRED environment variable is set (`ZENOH_LOCATOR`,
97    /// `ZENOH_MODE`). Refused rather than ignored: an ignored locator dials
98    /// the default router, which reads as "no delivery".
99    RetiredEnvVar {
100        /// The retired name the environment still sets.
101        name: &'static str,
102        /// The canonical name to set instead.
103        replacement: &'static str,
104    },
105    /// phase-427 W10 — [`Context::create_executor`] /
106    /// [`Context::create_executor_in`] resolved the identity and the RMW
107    /// session open then failed.
108    ///
109    /// The backend's own [`NodeError`] is CARRIED, not flattened into a flag:
110    /// `Transport(InvalidConfig)` (no backend registered, or more than one and
111    /// no selector) and `Transport(ConnectionFailed)` (the router is not there)
112    /// are different problems with different fixes, and issue 0465 is what
113    /// collapsing them cost the last time.
114    ExecutorOpenFailed(NodeError),
115    /// phase-427 W10 — [`Context::create_executor_in`] was handed a backing
116    /// smaller than the executor's tables need.
117    ///
118    /// Refused rather than accepted: `Executor::open_in` is `unsafe` precisely
119    /// because a short backing is undefined behaviour, so the safe wrapper
120    /// checks the length and names both numbers. `needed` is
121    /// `ExecutorSizing::DEFAULT.u64_len()` for this build — it moves with
122    /// `NROS_EXECUTOR_MAX_CBS` / `_MAX_SC` / `_ARENA_SIZE` / `_MAX_NODES`, so a
123    /// caller sizing a `static` from a literal will hear about it here rather
124    /// than corrupting memory later.
125    BackingTooSmall {
126        /// `u64` words the executor's tables need.
127        needed: usize,
128        /// `u64` words the caller supplied.
129        given: usize,
130    },
131}
132
133impl core::fmt::Display for InitError {
134    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
135        match self {
136            InitError::EnvParseFailed => f.write_str("env var parse failed"),
137            InitError::DomainIdOutOfRange => f.write_str("domain id out of range"),
138            InitError::RetiredEnvVar { name, replacement } => write!(
139                f,
140                "{name} is retired and no longer read; set {replacement} instead (unset {name})"
141            ),
142            InitError::ExecutorOpenFailed(e) => {
143                write!(f, "RMW session open failed: {e:?}")
144            }
145            InitError::BackingTooSmall { needed, given } => write!(
146                f,
147                "executor backing too small: {given} u64 words supplied, {needed} needed"
148            ),
149        }
150    }
151}
152
153// `core::error::Error` — `std::error::Error` is a re-export of it since Rust
154// 1.81, so this is the same trait, and it needs no feature: phase-427 W9 took
155// this module out from behind `env`.
156impl core::error::Error for InitError {}
157
158/// Resolved init context.
159///
160/// Returned by every `init*` entry point and every `Context::*` constructor.
161/// Carries the fields the user needs to construct an [`ExecutorConfig`] and
162/// open a session.
163///
164/// Fields are owned (`String`) so the `Context` can outlive transient parents
165/// (env caches, parsed launch files, a harness-supplied locator). That is why
166/// the type's feature floor is `alloc`.
167///
168/// ADOPT-BOUNDED against `rclrs::Context`, which OWNS the rcl context. This is
169/// the resolved identity as a plain value, so:
170/// - There is no `ok()`: the value has no shutdown state; liveness is the
171///   executor's.
172/// - `domain_id` is a public field, not a `domain_id()` method.
173/// - Executors are opened FROM it: [`create_executor`](Self::create_executor)
174///   leaks an executor-lifetime backing (needs `alloc`), and
175///   [`create_executor_in`](Self::create_executor_in) takes caller storage.
176#[cfg(feature = "alloc")]
177#[derive(Debug, Clone)]
178pub struct Context {
179    /// ROS 2 domain ID (`ROS_DOMAIN_ID`, default 0; baked `NROS_ENTRY_DOMAIN_ID`
180    /// freestanding).
181    pub domain_id: u32,
182    /// Middleware locator (`NROS_LOCATOR`; baked
183    /// `NROS_ENTRY_LOCATOR` freestanding). Empty means ABSENT: `nros` is
184    /// RMW-agnostic, so the linked backend substitutes its own default.
185    pub locator: alloc::string::String,
186    /// Session mode (`NROS_SESSION_MODE`, default `Client`).
187    pub mode: SessionMode,
188    /// RMW implementation hint (`RMW_IMPLEMENTATION` /  `NROS_RMW`).
189    ///
190    /// Empty when neither var is set, and always empty freestanding (an image
191    /// links exactly one backend). The runtime uses this to pick a primary
192    /// backend when multiple are linked; see `crate::internals::open_session`.
193    pub rmw: alloc::string::String,
194    /// Source of this context — useful for diagnostics + tests.
195    pub source: ContextSource,
196    /// The `-r`/`--remap` rules `init_with_args` / `Context::new` parsed
197    /// out of `--ros-args`, in argv order. Installed as the FALLBACK remap
198    /// sched task of every executor this context creates
199    /// (`Context::create_executor`, `Context::create_executor_in`).
200    ///
201    /// rcl keeps its global arguments on the context for the same reason: the
202    /// context is what the process was started with, and every node created
203    /// from it inherits them. Private, because nothing outside the parse
204    /// should write a rule here — and a rule that bypassed the parse would
205    /// bypass its refusals too.
206    #[cfg_attr(not(feature = "env"), allow(dead_code))]
207    ros_args: alloc::vec::Vec<ArgvRemap>,
208    /// phase-482 W5 — the `-p` / `--params-file` overrides, in argv order,
209    /// installed in every executor this context creates and applied when a
210    /// node declares the parameter (`Executor::install_argv_params`). Empty
211    /// unless `nros` has `param-services`; without it the parse refuses them.
212    #[cfg_attr(not(feature = "env"), allow(dead_code))]
213    ros_params: alloc::vec::Vec<ArgvParam>,
214}
215
216/// One parameter override, owned — from `-p [node:]name:=value` or a
217/// `--params-file` entry.
218#[cfg(feature = "alloc")]
219#[derive(Debug, Clone, PartialEq, Eq)]
220#[cfg_attr(not(feature = "env"), allow(dead_code))]
221struct ArgvParam {
222    node: Option<alloc::string::String>,
223    name: alloc::string::String,
224    value: alloc::string::String,
225}
226
227/// One `-r [node:]from:=to` rule, owned so a [`Context`] can outlive the
228/// argument vector it came from.
229#[cfg(feature = "alloc")]
230#[derive(Debug, Clone, PartialEq, Eq)]
231#[cfg_attr(not(feature = "env"), allow(dead_code))]
232struct ArgvRemap {
233    node: Option<alloc::string::String>,
234    from: alloc::string::String,
235    to: alloc::string::String,
236}
237
238/// Where the [`Context`] came from. Diagnostics only.
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub enum ContextSource {
241    /// Built from env vars by [`init()`] / [`init_with_args`] /
242    /// [`Context::new`], or by [`Context::default_from_env`] /
243    /// [`Context::from_env`] on a hosted build.
244    Env,
245    /// phase-427 W9 — built from the constants baked into this crate at
246    /// compile time (`NROS_ENTRY_LOCATOR`, `NROS_ENTRY_DOMAIN_ID`) by [`Context::baked`],
247    /// which is what [`Context::default_from_env`] / [`Context::from_env`]
248    /// resolve to on a freestanding build. The entry macros
249    /// (`nros::main!`'s Zephyr arm, `nros::zephyr_component_main!`) produce
250    /// this one.
251    Baked,
252}
253
254/// `rclrs::InitOptions`, with the one option it has.
255///
256/// Consumed by [`Context::from_env`] and [`Context::new`]; `None` for the
257/// domain keeps whatever the environment (hosted) or the bake (freestanding)
258/// resolved.
259#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
260pub struct InitOptions {
261    domain_id: Option<u32>,
262}
263
264impl InitOptions {
265    /// Default options: nothing overridden.
266    pub const fn new() -> Self {
267        Self { domain_id: None }
268    }
269
270    /// Override the domain id (`Some`) or keep the resolved one (`None`).
271    ///
272    /// `usize` because that is rclrs's signature. A value above `u32::MAX`
273    /// cannot be a domain id at all; it saturates here and the constructor
274    /// that consumes the options then rejects it as
275    /// [`InitError::DomainIdOutOfRange`], which is the loud place — a builder
276    /// method has no `Result` to carry the refusal in.
277    pub const fn with_domain_id(mut self, domain_id: Option<usize>) -> Self {
278        self.domain_id = match domain_id {
279            Some(d) if d > u32::MAX as usize => Some(u32::MAX),
280            Some(d) => Some(d as u32),
281            None => None,
282        };
283        self
284    }
285
286    /// The in-place twin of [`with_domain_id`](Self::with_domain_id) — rclrs
287    /// has both, and a ported `opts.set_domain_id(Some(7))` compiles as
288    /// written. Same saturation.
289    pub fn set_domain_id(&mut self, domain_id: Option<usize>) {
290        *self = self.with_domain_id(domain_id);
291    }
292
293    /// The domain override, if any.
294    ///
295    /// `Option<usize>`, which is rclrs's signature and the same reason
296    /// [`with_domain_id`](Self::with_domain_id) takes one. This
297    /// returned `Option<u32>` — the STORED width — so the two setters spoke
298    /// rclrs and the getter spoke the field, and a ported
299    /// `let d: Option<usize> = opts.domain_id();` failed on a type nobody
300    /// chose. The value is still stored as a `u32` and `with_domain_id`'s
301    /// saturation still applies, so a round trip through `u32::MAX + 1`
302    /// reports `u32::MAX`; the refusal stays on the consuming constructor
303    /// ([`InitError::DomainIdOutOfRange`]), which is where a `Result` exists
304    /// to carry it.
305    pub const fn domain_id(&self) -> Option<usize> {
306        match self.domain_id {
307            Some(d) => Some(d as usize),
308            None => None,
309        }
310    }
311}
312
313#[cfg(feature = "alloc")]
314/// The range check every constructor applies to a domain id, whatever its
315/// source (env, bake, override): the same bound `try_resolve_hosted` enforces
316/// ("INCLUDING a baked one"), so a freestanding image cannot boot on a domain
317/// a hosted process would have refused.
318fn check_domain_id(domain_id: u32) -> Result<u32, InitError> {
319    if domain_id > DOMAIN_ID_MAX {
320        Err(InitError::DomainIdOutOfRange)
321    } else {
322        Ok(domain_id)
323    }
324}
325
326#[cfg(feature = "alloc")]
327impl Context {
328    /// `rclrs::Context::domain_id()` — the resolved ROS domain.
329    ///
330    /// `usize`, because that is rclrs's return type (0.7.0,
331    /// `rclrs/src/context.rs`) and this name exists so a ported
332    /// `ctx.domain_id()` compiles. The field stays `pub` and stays `u32`:
333    /// `Context` is a plain value with nothing to hide, `u32` is the width
334    /// every producer and consumer of a domain in this tree speaks
335    /// (`BoardConfig::domain_id`, `ExecutorConfig::domain_id`,
336    /// `NodeHandle::domain_id`, the `NROS_ENTRY_DOMAIN_ID` bake), and fields and
337    /// methods are in different namespaces in Rust, so the two coexist. The
338    /// widening is lossless on every target here — `usize` is at least 32
339    /// bits on all of them, down to `thumbv7m-none-eabi`.
340    ///
341    /// The API-parity ledger row `rust:Context::domain_id` proposed `-> u32`
342    /// once and that would have been a second, quieter port break; it then
343    /// argued `usize` from consistency with [`InitOptions`], which was only
344    /// two thirds true — the setters took `usize`, the getter returned
345    /// `Option<u32>`. Both getters speak `usize` now, so the argument is the
346    /// one this crate can actually make: it is upstream's type.
347    #[must_use]
348    pub const fn domain_id(&self) -> usize {
349        self.domain_id as usize
350    }
351
352    /// Materialise an [`ExecutorConfig`] for a node with the given name.
353    ///
354    /// The returned config borrows from `self`, so callers usually do:
355    ///
356    /// ```ignore
357    /// let ctx = nros::Context::default_from_env()?;
358    /// let cfg = ctx.config("talker");
359    /// let mut executor = nros::Executor::open(&cfg)?;
360    /// ```
361    ///
362    /// This is the shape where the executor IS the node it was
363    /// configured with, and it stays: an entry that opens exactly one node
364    /// wants exactly this. What it cannot express is the second node, which is
365    /// why `Context::create_executor()` + `Executor::create_node(name)` now sit
366    /// beside it — the session takes no name, and each node takes its own.
367    // phase-427 W10 — the one legitimate remaining use of the deprecated
368    // builder spelling: this method IS the executor-is-the-node shape, so it
369    // asks for it deliberately rather than by not having heard.
370    ///
371    /// # Refused when the context carries `--ros-args` remaps
372    ///
373    /// An [`ExecutorConfig`] has nowhere to put them, so the executor
374    /// `Executor::open` builds from it would never see them — the silent drop
375    /// `init_with_args` exists to prevent. Such a context PANICS here,
376    /// naming `Context::create_executor`, which installs them.
377    #[allow(deprecated)] // the deliberate use named above (phase-427 W10)
378    pub fn config<'a>(&'a self, node_name: &'a str) -> ExecutorConfig<'a> {
379        #[cfg(feature = "env")]
380        if !self.ros_args.is_empty() || !self.ros_params.is_empty() {
381            refuse_ros_args(&RosArgsRefusal::UnreachableExecutor);
382        }
383        ExecutorConfig::new(self.locator.as_str())
384            .node_name(node_name)
385            .domain_id(self.domain_id)
386            .mode(self.mode)
387    }
388
389    /// `rclrs::Context::default_from_env()` — the environment, default
390    /// options.
391    ///
392    /// Hosted (feature `env`) this reads the process environment and is
393    /// exactly [`init()`]; freestanding it is [`Context::baked`], the build
394    /// environment this image was compiled for: the semantics survive with
395    /// the source moved from run time to
396    /// build time, which is the bounded half of this adoption.
397    pub fn default_from_env() -> Result<Context, InitError> {
398        #[cfg(feature = "env")]
399        {
400            init()
401        }
402        #[cfg(not(feature = "env"))]
403        {
404            Self::baked()
405        }
406    }
407
408    /// `rclrs::Context::from_env(options)` — [`default_from_env`](Self::default_from_env)
409    /// with the [`InitOptions`] applied on top: a
410    /// `Some` domain replaces the resolved one, `None` keeps it.
411    ///
412    /// Bounded: [`InitOptions`] carries rclrs's one option, `domain_id`, and no
413    /// other, so an option rclrs adds later is a compile error here. A domain above
414    /// `DOMAIN_ID_MAX` is [`InitError::DomainIdOutOfRange`]. Freestanding, the base
415    /// the options override is the BAKED context ([`Context::baked`]), not a
416    /// process environment.
417    pub fn from_env(options: InitOptions) -> Result<Context, InitError> {
418        let mut ctx = Self::default_from_env()?;
419        if let Some(domain_id) = options.domain_id {
420            ctx.domain_id = check_domain_id(domain_id)?;
421        }
422        Ok(ctx)
423    }
424
425    /// `rclrs::Context::new(args, options)` — the argv constructor. HOSTED
426    /// ONLY: a freestanding image has no argv, so the name is absent there and
427    /// the compiler says so.
428    ///
429    /// **What it does with the arguments:** the same as [`init_with_args`] —
430    /// `-r`/`--remap` rules inside `--ros-args` are parsed onto the returned
431    /// context and every other ROS argument is REFUSED LOUDLY at the call
432    /// ([`REFUSE_INIT_ARGS`]). Arguments outside a `--ros-args` scope are the
433    /// program's own and are left alone.
434    ///
435    /// `S: AsRef<str>` is a superset of rclrs's `Item = String`, so
436    /// `Context::new(std::env::args(), InitOptions::new())` compiles as
437    /// written.
438    #[cfg(feature = "env")]
439    pub fn new<I, S>(args: I, options: InitOptions) -> Result<Context, InitError>
440    where
441        I: IntoIterator<Item = S>,
442        S: AsRef<str>,
443    {
444        let (ros_args, ros_params) = parse_ros_args_or_refuse(args);
445        let mut context = Self::from_env(options)?;
446        context.ros_args = ros_args;
447        context.ros_params = ros_params;
448        Ok(context)
449    }
450
451    /// The freestanding constructor: the constants baked into
452    /// this crate at compile time.
453    ///
454    /// * `NROS_ENTRY_LOCATOR` — the middleware locator. Unset or empty ⇒ empty ⇒
455    ///   the linked backend's own default (for zenoh-pico that is
456    ///   multicast scouting, which native_sim NSOS cannot satisfy — hence the
457    ///   bake).
458    /// * `NROS_ENTRY_DOMAIN_ID` — the domain. Unset ⇒ 0; non-numeric ⇒
459    ///   [`InitError::EnvParseFailed`]; above `DOMAIN_ID_MAX` ⇒
460    ///   [`InitError::DomainIdOutOfRange`].
461    ///
462    /// Both names reach this crate's build the same way they reach the board
463    /// crates: on Zephyr, `build.rs` re-exports `CONFIG_NROS_LOCATOR` /
464    /// `CONFIG_NROS_DOMAIN_ID` from `$DOTCONFIG` (`nros_zephyr_build::
465    /// bake_nros_config`, the `$DOTCONFIG` channel); on the other RTOS lanes the
466    /// fixture build exports them into the process environment. This is the
467    /// ONE `option_env!` site for the pair — the entry macros used to carry
468    /// their own copies (and `nros::main!`'s Zephyr arm had lost the domain
469    /// half, the drift a second copy invites), which is what "one source of the baked
470    /// shape" replaces.
471    ///
472    /// Mode is `Client` and `rmw` is empty: an image links exactly one
473    /// backend and nothing bakes a session mode today.
474    ///
475    /// Hosted builds have this too — it answers "what was baked", which a
476    /// hosted process rarely wants; [`Context::default_from_env`] is the
477    /// constructor that picks the right source for the build.
478    pub fn baked() -> Result<Context, InitError> {
479        Self::from_baked(
480            option_env!("NROS_ENTRY_LOCATOR"),
481            option_env!("NROS_ENTRY_DOMAIN_ID"),
482        )
483    }
484
485    /// The parse behind [`Context::baked`], with the two constants injected
486    /// so a unit test can exercise every arm without a build environment.
487    /// Public because the macros in `nros-macros` expand in another crate;
488    /// not API.
489    #[doc(hidden)]
490    pub fn from_baked(
491        baked_locator: Option<&str>,
492        baked_domain_id: Option<&str>,
493    ) -> Result<Context, InitError> {
494        let domain_id = match baked_domain_id {
495            Some(d) => check_domain_id(d.trim().parse().map_err(|_| InitError::EnvParseFailed)?)?,
496            None => 0,
497        };
498        Ok(Context {
499            domain_id,
500            locator: alloc::string::String::from(baked_locator.unwrap_or("")),
501            mode: SessionMode::Client,
502            rmw: alloc::string::String::new(),
503            source: ContextSource::Baked,
504            ros_args: alloc::vec::Vec::new(),
505            ros_params: alloc::vec::Vec::new(),
506        })
507    }
508
509    /// Replace the locator with one handed in at run time, when there is one.
510    ///
511    /// `native_sim` test parallelism: the harness launches
512    /// an image with `-testargs --nros-locator=<loc>` and a per-test router on
513    /// that ephemeral port, and `nros_runtime_locator_override()`
514    /// (`nros-platform-zephyr`, argv-backed) hands it back here. `None` or an
515    /// empty string keeps the baked value, so on real hardware — where the hook
516    /// returns NULL — the bake stands. The entry macros call this after
517    /// [`Context::default_from_env`]; a hand-written entry may too.
518    pub fn with_locator_override(mut self, locator: Option<&str>) -> Self {
519        if let Some(loc) = locator {
520            if !loc.is_empty() {
521                self.locator = alloc::string::String::from(loc);
522            }
523        }
524        self
525    }
526
527    /// Drop the baked locator when the image has
528    /// session properties.
529    ///
530    /// With an RMW file the file is the wiring, and every other road bakes no
531    /// locator beside it (`nros::main!`, the C/C++ boot blob). A Zephyr image
532    /// still bakes its Kconfig locator (`CONFIG_NROS_LOCATOR`, default
533    /// `tcp/127.0.0.1:7447`), and the zenoh shim dials a supplied locator
534    /// BEFORE the file's `connect` list: a router on that port would win, and
535    /// the file's would be a fallback. Called before
536    /// [`with_locator_override`](Self::with_locator_override), so a run-time
537    /// locator still wins. Public for the entry macro; not API.
538    #[doc(hidden)]
539    pub fn yield_locator_to_session_properties(
540        mut self,
541        properties: &[nros_node::SessionProperty],
542    ) -> Self {
543        if !properties.is_empty() {
544            self.locator.clear();
545        }
546        self
547    }
548
549    /// phase-427 W10 — the config the executor's SESSION opens with: this
550    /// context's locator, domain and mode, and no node name.
551    ///
552    /// The counterpart of [`config`](Self::config), which is for the older
553    /// shape where the executor IS the node it was configured with. Here the
554    /// session carries no ROS identity of its own — `Executor::create_node`
555    /// supplies that, once per node, and one executor holds several
556    /// (RFC-0047). What lands in `ExecutorConfig::node_name` is therefore
557    /// whatever [`ExecutorConfig::new`] defaults to; it names the transport
558    /// session for diagnostics, not a participant on the graph.
559    #[cfg(feature = "rmw-cffi")]
560    fn session_config(&self) -> ExecutorConfig<'_> {
561        ExecutorConfig::new(self.locator.as_str())
562            .domain_id(self.domain_id)
563            .mode(self.mode)
564    }
565}
566
567/// phase-427 W10 — `rclrs::Context::create_executor`, and the ours-only
568/// no-leak twin beside it.
569///
570/// Both are gated on `rmw-cffi`, because an executor without the vtable
571/// runtime has no session to open; `create_executor` is additionally gated on
572/// `alloc`, because it is the one that leaks a default-sized backing.
573#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
574impl Context {
575    /// `rclrs::Context::create_executor()` — open the session this context
576    /// resolved and hand back the [`Executor`] that owns it.
577    ///
578    /// This is the entry a ported rclrs `main` lands on: upstream writes
579    /// `context.create_basic_executor()` (or `create_executor(runtime)`) and
580    /// gets an `Executor` back; ours returns a `Result`, so the port is a `?`.
581    /// The runtime argument has no counterpart here and is not accepted — one
582    /// executor per RTOS task is the model, and there is no runtime
583    /// to choose between.
584    ///
585    /// The node name is NOT taken here. Name nodes with
586    /// [`Executor::create_node`], which is where several named nodes on one
587    /// session already live.
588    ///
589    /// # Available on `alloc` only
590    ///
591    /// It leaks an executor-lifetime backing at
592    /// [`ExecutorSizing::DEFAULT`] — the reason it is `Executor<'static>` and
593    /// the reason it needs an allocator. A target without one calls
594    /// [`create_executor_in`](Self::create_executor_in) with its own
595    /// `static`, which is the same open with the storage supplied rather than
596    /// leaked. (Today [`Context`] itself has an `alloc` floor — its `locator`
597    /// and `rmw` are owned `String`s — so the pair moves together; if that
598    /// floor ever drops, this is the half that stays behind.)
599    ///
600    /// ```ignore
601    /// let context = nros::Context::default_from_env()?;
602    /// let mut executor = context.create_executor()?;
603    /// let mut node = executor.create_node("talker")?;
604    /// ```
605    ///
606    /// The `-r` rules `init_with_args` / `Context::new` parsed are
607    /// installed in the new executor as its fallback remap tier.
608    pub fn create_executor(&self) -> Result<Executor<'static>, InitError> {
609        let mut executor =
610            Executor::open(&self.session_config()).map_err(InitError::ExecutorOpenFailed)?;
611        self.install_ros_args(&mut executor);
612        Ok(executor)
613    }
614
615    /// Put this context's `--ros-args` remaps into `executor`'s fallback tier.
616    /// A rule that does not fit is REFUSED rather than dropped.
617    fn install_ros_args(&self, executor: &mut Executor<'_>) {
618        #[cfg(feature = "env")]
619        {
620            let rules = self.ros_args.iter().map(|r| nros_node::ros_args::RemapArg {
621                node: r.node.as_deref(),
622                from: r.from.as_str(),
623                to: r.to.as_str(),
624            });
625            if let Err(rule) = nros_node::ros_args::install_argv_remaps(executor, rules) {
626                refuse_ros_args(&RosArgsRefusal::DoesNotFit {
627                    node: rule.node,
628                    from: rule.from,
629                    to: rule.to,
630                });
631            }
632            #[cfg(feature = "param-store")]
633            if !self.ros_params.is_empty() {
634                let params = self
635                    .ros_params
636                    .iter()
637                    .map(|p| nros_node::ros_args::ParamArg {
638                        node: p.node.as_deref(),
639                        name: p.name.as_str(),
640                        value: p.value.as_str(),
641                    });
642                if executor.install_argv_params(params).is_err() {
643                    refuse_ros_args(&RosArgsRefusal::NoParamStore);
644                }
645            }
646        }
647        #[cfg(not(feature = "env"))]
648        let _ = executor;
649    }
650
651    /// OURS — [`create_executor`](Self::create_executor) with the storage
652    /// supplied by the caller instead of leaked.
653    ///
654    /// The freestanding form. An RTOS or bare-metal entry owns a
655    /// `static mut [MaybeUninit<u64>; N]` (or the array the `nros::main!`
656    /// macro sizes for it) and hands it in; nothing is allocated, and the
657    /// returned executor borrows the backing for `'b` rather than living
658    /// forever. rclrs has no counterpart — it allocates.
659    ///
660    /// `backing` must hold at least `ExecutorSizing::DEFAULT.u64_len()` words.
661    /// A shorter slice is [`InitError::BackingTooSmall`] naming both numbers,
662    /// never undefined behaviour: this is the safe wrapper around the `unsafe`
663    /// `Executor::open_in`, and the length check is what makes it safe. Size
664    /// the array with `ExecutorSizing::DEFAULT.u64_len()` rather than a
665    /// literal, since the default moves with `NROS_EXECUTOR_MAX_CBS` and its
666    /// siblings.
667    ///
668    /// ```ignore
669    /// static mut BACKING: [MaybeUninit<u64>; N] = [MaybeUninit::uninit(); N];
670    /// let context = nros::Context::default_from_env()?;
671    /// // SAFETY: single-threaded entry, taken once.
672    /// let mut executor = context.create_executor_in(unsafe { &mut *&raw mut BACKING })?;
673    /// let mut node = executor.create_node("talker")?;
674    /// ```
675    pub fn create_executor_in<'b>(
676        &self,
677        backing: &'b mut [MaybeUninit<u64>],
678    ) -> Result<Executor<'b>, InitError> {
679        let sizing = ExecutorSizing::DEFAULT;
680        let needed = sizing.u64_len();
681        let given = backing.len();
682        if given < needed {
683            return Err(InitError::BackingTooSmall { needed, given });
684        }
685        // SAFETY: `backing` is at least `sizing.u64_len()` words (checked
686        // directly above), is `u64`-aligned by its element type, is uniquely
687        // borrowed for `'b`, and the returned `Executor<'b>` is the only thing
688        // that can reach it for that lifetime.
689        let mut executor = unsafe { Executor::open_in(&self.session_config(), backing, sizing) }
690            .map_err(InitError::ExecutorOpenFailed)?;
691        self.install_ros_args(&mut executor);
692        Ok(executor)
693    }
694}
695
696#[cfg(feature = "env")]
697fn read_env_context(source: ContextSource) -> Result<Context, InitError> {
698    // issue 0687 — through the ONE resolver, not a third parse of the same four
699    // variables. This function had its own copy, and the copies had drifted:
700    // it did not see the legacy `ZENOH_LOCATOR`/`ZENOH_MODE` spellings (now
701    // retired and refused by the shared reader), and it range-checked nothing, so
702    // `ROS_DOMAIN_ID=300` reached a backend that could only fail later.
703    //
704    // Issue 0330 — no backend default for the locator: `nros` is RMW-agnostic,
705    // so unset env leaves it EMPTY (= absent) and the linked backend
706    // substitutes its own (zenoh: `nros_rmw_zenoh::DEFAULT_LOCATOR`; xrce: its
707    // agent default; cyclonedds ignores the locator entirely). That is what
708    // `resolve_hosted` does with an empty `BootConfig` too.
709    let resolved =
710        crate::env::try_resolve_hosted(nros_node::BootConfig::default()).map_err(|e| match e {
711            nros_node::BootConfigError::DomainIdRange => InitError::DomainIdOutOfRange,
712            nros_node::BootConfigError::DomainIdParse => InitError::EnvParseFailed,
713            nros_node::BootConfigError::RetiredEnvVar { name, replacement } => {
714                InitError::RetiredEnvVar { name, replacement }
715            }
716        })?;
717    let locator = alloc::string::String::from(resolved.locator);
718    let domain_id = resolved.domain_id;
719    let mode = resolved.mode;
720    // issue 0687 — the `$NROS_RMW` half comes from the shared selector; the
721    // `RMW_IMPLEMENTATION` fallback stays HERE and only here. `Context.rmw` is
722    // a ROS-vocabulary HINT (`rmw_cyclonedds_cpp`), not the cffi registry
723    // selector (`cyclonedds`) — folding the two together would hand a ROS name
724    // to `resolve_backend`, which answers `Unknown` and fails the open.
725    let rmw = crate::rmw_selector()
726        .map(|s| alloc::string::String::from(s.as_str()))
727        .or_else(|| crate::env::var("RMW_IMPLEMENTATION").map(alloc::string::String::from))
728        .unwrap_or_default();
729    Ok(Context {
730        domain_id,
731        locator,
732        mode,
733        rmw,
734        source,
735        ros_args: alloc::vec::Vec::new(),
736        ros_params: alloc::vec::Vec::new(),
737    })
738}
739
740/// Pattern 3 — raw init, launch file ignored. The C++-symmetric anchor:
741/// `rclcpp::init()` in the Rust spelling, and EQUAL to
742/// [`Context::default_from_env`] on a hosted build (under the ROS 2
743/// adoption rule each language follows its own upstream; rclrs spells
744/// this one on the type, rclcpp as a free function, and both are here).
745///
746/// Reads env vars (`ROS_DOMAIN_ID`, `NROS_LOCATOR`, `NROS_SESSION_MODE`,
747/// `NROS_RMW` / `RMW_IMPLEMENTATION`) and returns a [`Context`]. The
748/// caller owns the spin loop — typically `Executor::open(&ctx.config(name))`
749/// followed by `spin` or a hand-rolled `spin_once` loop.
750#[cfg(feature = "env")]
751pub fn init() -> Result<Context, InitError> {
752    read_env_context(ContextSource::Env)
753}
754
755/// The refusal [`init_with_args`] and [`Context::new`] emit for a ROS
756/// argument nano-ros does not honour. Panics carry this text followed by the
757/// refused argument. `NROS_RCLCPP_REFUSE_INIT_ARGV` is the C++ twin
758/// (`packages/api/nros-cpp/include/rclcpp/logging.hpp`), and it
759/// states the same honoured and refused sets, from the same parser.
760///
761/// The rule is the ROS 2 adoption rule; the remap fallback follows rcl's
762/// local-before-global order, and the parameter application is the launch tree's.
763#[cfg(feature = "env")]
764// user-surface: table
765pub const REFUSE_INIT_ARGS: &str = "nros::init_with_args / nros::Context::new was given a --ros-args \
766argument nano-ros cannot honour. Proceeding would DISCARD it -- the \
767'compiles and differs' the rule forbids. HONOURED inside --ros-args ... --: -r / --remap \
768[node:]from:=to, applied as the FALLBACK beneath any remap the launch file projected for the same \
769name (rcl's local-before-global), through Context::create_executor / \
770create_executor_in; and, in an image with a parameter store, -p / --param [node:]name:=value and \
771--params-file <path>, applied when a node declares the parameter. REFUSED: \
772node-identity remaps (__node, __name, __ns), -e / --enclave, the log flags, any token that is not a \
773ROS flag, and -p / --params-file in an image without a parameter store. A nros configure \
774image does not read argv at all: its launch remaps and parameters are projected into the \
775GENERATED ENTRY at BUILD time.";
776
777/// Does `args` open a `--ros-args` scope at all?
778///
779/// No longer the refusal's predicate — since the `-r` parse landed, a vector
780/// with `--ros-args` is parsed, and only what it cannot honour is refused
781/// (`nros_node::ros_args::parse_ros_args`). Kept because "will this argv be
782/// read?" is still a question a caller can ask before handing it over.
783///
784/// Exact match only. `--ros-args-extra` is not the flag, and a prefix match
785/// would claim an argument nano-ros never reads — pinned by a unit test.
786#[cfg(feature = "env")]
787pub fn args_have_ros_args<I, S>(args: I) -> bool
788where
789    I: IntoIterator<Item = S>,
790    S: AsRef<str>,
791{
792    args.into_iter().any(|a| a.as_ref() == "--ros-args")
793}
794
795/// Why a `--ros-args` vector, or a context carrying one, was refused.
796#[cfg(feature = "env")]
797enum RosArgsRefusal<'a> {
798    /// The parse itself refused an argument.
799    Parse(nros_node::ros_args::RosArgsError<'a>),
800    /// A parsed rule did not fit the executor's remap table.
801    #[cfg(feature = "rmw-cffi")]
802    DoesNotFit {
803        node: Option<&'a str>,
804        from: &'a str,
805        to: &'a str,
806    },
807    /// [`Context::config`] was asked for a config that cannot carry the rules.
808    UnreachableExecutor,
809    /// phase-482 W5 — `--params-file <path>` could not be read or parsed.
810    #[cfg(feature = "param-store")]
811    ParamsFile {
812        path: alloc::string::String,
813        why: alloc::string::String,
814    },
815    /// phase-482 W5 — the parameter store could not be allocated (issue 1706).
816    #[cfg(all(feature = "param-store", feature = "rmw-cffi"))]
817    NoParamStore,
818}
819
820#[cfg(feature = "env")]
821impl core::fmt::Display for RosArgsRefusal<'_> {
822    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
823        match self {
824            Self::Parse(e) => e.fmt(f),
825            #[cfg(feature = "rmw-cffi")]
826            Self::DoesNotFit { node, from, to } => {
827                let node = node.map(|n| alloc::format!("{n}:")).unwrap_or_default();
828                write!(
829                    f,
830                    "`-r {node}{from}:={to}` does not fit the executor's remap table (MAX_REMAPS rules, \
831                     shared with launch remaps; names up to {} bytes)",
832                    nros_node::names::MAX_RESOLVED_NAME_LEN
833                )
834            }
835            Self::UnreachableExecutor => f.write_str(
836                "Context::config() cannot carry this context's --ros-args remaps or parameter \
837                 overrides into the executor Executor::open builds from it; use \
838                 Context::create_executor() or create_executor_in(), which install them",
839            ),
840            #[cfg(feature = "param-store")]
841            Self::ParamsFile { path, why } => write!(f, "`--params-file {path}`: {why}"),
842            #[cfg(all(feature = "param-store", feature = "rmw-cffi"))]
843            Self::NoParamStore => f.write_str(
844                "the parameter store could not be allocated, so the parameter overrides have \
845                 nowhere to go",
846            ),
847        }
848    }
849}
850
851/// The one refusal site: logged through `nros_log` (never `std::println!`,
852/// issue 0589), then a panic carrying [`REFUSE_INIT_ARGS`] and the reason —
853/// the shape `rclcpp::init(argc, argv)` has in `nros.hpp`, and the shape
854/// rclcpp's own `UnknownROSArgsError` has.
855#[cfg(feature = "env")]
856fn refuse_ros_args(why: &RosArgsRefusal<'_>) -> ! {
857    nros_log::log_error!(
858        nros_log::get_logger("nros"),
859        "{}\n  refused: {}",
860        REFUSE_INIT_ARGS,
861        why
862    );
863    panic!("{REFUSE_INIT_ARGS}\n  refused: {why}");
864}
865
866/// Parse `args` (rcl's grammar — `nros_node::ros_args`) into owned rules, or
867/// refuse. Shared by [`init_with_args`] and [`Context::new`], so the two stay
868/// one behaviour.
869#[cfg(feature = "env")]
870fn parse_ros_args_or_refuse<I, S>(
871    args: I,
872) -> (alloc::vec::Vec<ArgvRemap>, alloc::vec::Vec<ArgvParam>)
873where
874    I: IntoIterator<Item = S>,
875    S: AsRef<str>,
876{
877    use alloc::string::String;
878    let owned: alloc::vec::Vec<String> =
879        args.into_iter().map(|a| String::from(a.as_ref())).collect();
880    let mut rules = alloc::vec::Vec::new();
881    #[cfg_attr(not(feature = "param-store"), allow(unused_mut))]
882    let mut params: alloc::vec::Vec<ArgvParam> = alloc::vec::Vec::new();
883    let remap = |r: nros_node::ros_args::RemapArg<'_>| ArgvRemap {
884        node: r.node.map(String::from),
885        from: String::from(r.from),
886        to: String::from(r.to),
887    };
888    // phase-482 W5 — with a parameter store, `-p` and `--params-file` are
889    // honoured, each file's entries landing where its flag stood (so a later
890    // `-p` overrides it and a later file overrides an earlier `-p`). Without
891    // one, the remap-only parse refuses them by name.
892    #[cfg(feature = "param-store")]
893    let parsed = {
894        let mut events = alloc::vec::Vec::new();
895        let r = nros_node::ros_args::parse_ros_args_events(owned.iter().map(|a| a.as_str()), |a| {
896            events.push(a)
897        });
898        if r.is_ok() {
899            for a in events {
900                match a {
901                    nros_node::ros_args::RosArg::Remap(r) => rules.push(remap(r)),
902                    nros_node::ros_args::RosArg::Param(p) => params.push(ArgvParam {
903                        node: p.node.map(String::from),
904                        name: String::from(p.name),
905                        value: String::from(p.value),
906                    }),
907                    nros_node::ros_args::RosArg::ParamsFile(path) => {
908                        // phase-359 W10 stage B — the C library's read, beside
909                        // `getenv`, so the hosted entry needs no `std`.
910                        let text = match crate::env::read_file(path) {
911                            Ok(t) => t,
912                            Err(why) => refuse_ros_args(&RosArgsRefusal::ParamsFile {
913                                path: String::from(path),
914                                why: String::from(why),
915                            }),
916                        };
917                        if let Err(e) = nros_node::ros_args::parse_params_yaml(&text, |p| {
918                            params.push(ArgvParam {
919                                node: p.node.map(String::from),
920                                name: String::from(p.name),
921                                value: String::from(p.value),
922                            })
923                        }) {
924                            refuse_ros_args(&RosArgsRefusal::ParamsFile {
925                                path: String::from(path),
926                                why: alloc::format!("{e}"),
927                            });
928                        }
929                    }
930                }
931            }
932        }
933        r
934    };
935    #[cfg(not(feature = "param-store"))]
936    let parsed = nros_node::ros_args::parse_ros_args(owned.iter().map(|a| a.as_str()), |r| {
937        rules.push(remap(r))
938    });
939    if let Err(e) = parsed {
940        refuse_ros_args(&RosArgsRefusal::Parse(e));
941    }
942    (rules, params)
943}
944
945/// Pattern 3 — like [`init()`] but takes the process arguments, the way
946/// `rclcpp::init(argc, argv)` / rclrs's `Context::new(args, ..)` do. The
947/// free-function twin of [`Context::new`] with default options.
948///
949/// # What it does with the arguments
950///
951/// It parses `--ros-args` with rcl's grammar (Humble `rcl/arguments.h`): ROS
952/// arguments live between `--ros-args` and `--` (or the end), several scopes
953/// may appear, and everything outside them is the program's own and is left
954/// alone.
955///
956/// * **`-r` / `--remap [node:]from:=to` — honoured.** The rules ride on the
957///   returned [`Context`] and are installed in every executor it creates
958///   (`Context::create_executor` / `Context::create_executor_in`) as the
959///   FALLBACK remap tier: a launch-projected rule for the same name wins
960///   (launch is authoritative), exactly as rcl checks a node's local arguments before the
961///   process's global ones. They reach entities on every road — the handle
962///   `Executor::create_node` returns, `nros::node!` components, and the C and
963///   C++ APIs.
964/// * **`-p` / `--param [node:]name:=value` and `--params-file <path>` —
965///   honoured when `nros` has `param-services`** (the
966///   POSIX case). They ride on the [`Context`] in argv order and are applied
967///   when a node DECLARES the parameter: the last matching override wins, its
968///   text typed by the declared default, and a `node:` override reaches only
969///   the node of that name. The envelope, stated here because it is the API:
970///   a parameter file is read with `std::fs` and holds scalars only (arrays,
971///   anchors and block scalars are refused, with their line), a node key
972///   matches by NAME not namespace, and an override that does not parse as
973///   the declared type is logged and the default kept.
974/// * **Everything else inside a scope — refused, loudly**: node-identity
975///   remaps, enclaves, log flags, unknown tokens, and `-p` / `--params-file`
976///   in an image with no parameter store. Logged through `nros_log`, then a panic
977///   carrying [`REFUSE_INIT_ARGS`] and the argument. rclcpp refuses unknown
978///   ROS arguments too (`UnknownROSArgsError`).
979///
980/// # Where the rules do NOT reach
981///
982/// [`Context::config`] refuses a context that carries rules, because an
983/// `ExecutorConfig` cannot carry them. Entities created through the
984/// executor's own `add_*` registration methods or a `node_mut` context are
985/// not remapped either: those are also where the C ABI and the component
986/// sink hand their ALREADY-RESOLVED names, so remapping there would apply a
987/// rule twice.
988#[cfg(feature = "env")]
989pub fn init_with_args<I, S>(args: I) -> Result<Context, InitError>
990where
991    I: IntoIterator<Item = S>,
992    S: AsRef<str>,
993{
994    let (ros_args, ros_params) = parse_ros_args_or_refuse(args);
995    let mut context = init()?;
996    context.ros_args = ros_args;
997    context.ros_params = ros_params;
998    Ok(context)
999}
1000
1001#[cfg(all(test, feature = "env"))]
1002mod ros_args_refusal_tests {
1003    use super::*;
1004
1005    #[test]
1006    fn predicate_matches_the_flag_exactly() {
1007        let _env = crate::env::test_env_lock();
1008        assert!(args_have_ros_args(["node", "--ros-args", "-p", "x:=1"]));
1009        assert!(args_have_ros_args(["--ros-args"]));
1010        // A prefix match would refuse an argument nano-ros never drops.
1011        assert!(!args_have_ros_args(["--ros-args-extra"]));
1012        assert!(!args_have_ros_args(["--ros-arg"]));
1013        assert!(!args_have_ros_args(["node", "--verbose"]));
1014        assert!(!args_have_ros_args(core::iter::empty::<&str>()));
1015    }
1016
1017    fn remap(node: Option<&str>, from: &str, to: &str) -> ArgvRemap {
1018        ArgvRemap {
1019            node: node.map(alloc::string::String::from),
1020            from: alloc::string::String::from(from),
1021            to: alloc::string::String::from(to),
1022        }
1023    }
1024
1025    #[test]
1026    fn remap_rules_ride_on_the_context_in_argv_order() {
1027        let _env = crate::env::test_env_lock();
1028        let ctx = init_with_args([
1029            "/usr/bin/talker",
1030            "--ros-args",
1031            "-r",
1032            "chatter:=/other",
1033            "--remap",
1034            "talker:~/out:=/wire",
1035            "--",
1036            "positional",
1037        ])
1038        .expect("init");
1039        assert_eq!(
1040            ctx.ros_args,
1041            [
1042                remap(None, "chatter", "/other"),
1043                remap(Some("talker"), "~/out", "/wire")
1044            ]
1045        );
1046    }
1047
1048    #[test]
1049    fn an_empty_scope_is_not_a_refusal() {
1050        let _env = crate::env::test_env_lock();
1051        assert!(
1052            init_with_args(["--ros-args"])
1053                .expect("init")
1054                .ros_args
1055                .is_empty()
1056        );
1057    }
1058
1059    /// Without a parameter store there is nowhere to put an override, so the
1060    /// parse refuses it by name rather than dropping it.
1061    #[cfg(not(feature = "param-store"))]
1062    #[test]
1063    #[should_panic(expected = "refused: `-p`")]
1064    fn parameter_overrides_are_still_refused_by_name() {
1065        let _env = crate::env::test_env_lock();
1066        let _ = init_with_args(["/usr/bin/talker", "--ros-args", "-r", "a:=b", "-p", "x:=1"]);
1067    }
1068
1069    #[cfg(feature = "param-store")]
1070    fn param(node: Option<&str>, name: &str, value: &str) -> ArgvParam {
1071        ArgvParam {
1072            node: node.map(alloc::string::String::from),
1073            name: alloc::string::String::from(name),
1074            value: alloc::string::String::from(value),
1075        }
1076    }
1077
1078    /// phase-482 W5 — `-p` and a `--params-file` ride on the context in argv
1079    /// order, the file's entries where its flag stood, beside the remaps.
1080    #[cfg(feature = "param-store")]
1081    #[test]
1082    fn parameter_overrides_ride_on_the_context_in_argv_order() {
1083        let _env = crate::env::test_env_lock();
1084        let path =
1085            std::env::temp_dir().join(alloc::format!("nros-w5-params-{}.yaml", std::process::id()));
1086        std::fs::write(
1087            &path,
1088            "/**:\n  ros__parameters:\n    rate: 30\n/talker:\n  ros__parameters:\n    gains:\n      kp: 1.5\n",
1089        )
1090        .unwrap();
1091        let path_s = path.to_str().unwrap();
1092        let ctx = init_with_args([
1093            "/usr/bin/talker",
1094            "--ros-args",
1095            "-p",
1096            "rate:=10",
1097            "--params-file",
1098            path_s,
1099            "-r",
1100            "chatter:=/other",
1101            "-p",
1102            "talker:label:=hi",
1103        ])
1104        .expect("init");
1105        let _ = std::fs::remove_file(&path);
1106        assert_eq!(
1107            ctx.ros_params,
1108            [
1109                param(None, "rate", "10"),
1110                param(None, "rate", "30"),
1111                param(Some("talker"), "gains.kp", "1.5"),
1112                param(Some("talker"), "label", "hi"),
1113            ]
1114        );
1115        assert_eq!(ctx.ros_args, [remap(None, "chatter", "/other")]);
1116    }
1117
1118    /// An unreadable parameter file is refused, naming the path — never a
1119    /// silently empty set of overrides.
1120    #[cfg(feature = "param-store")]
1121    #[test]
1122    #[should_panic(expected = "--params-file /nonexistent/nros-w5.yaml")]
1123    fn an_unreadable_params_file_is_refused_by_path() {
1124        let _env = crate::env::test_env_lock();
1125        let _ = init_with_args(["--ros-args", "--params-file", "/nonexistent/nros-w5.yaml"]);
1126    }
1127
1128    #[test]
1129    #[should_panic(expected = "remaps a node's identity")]
1130    fn identity_remaps_are_refused() {
1131        let _env = crate::env::test_env_lock();
1132        let _ = init_with_args(["--ros-args", "-r", "__ns:=/robot"]);
1133    }
1134
1135    #[test]
1136    #[should_panic(expected = "Context::config() cannot carry")]
1137    fn config_refuses_a_context_that_carries_remaps() {
1138        let _env = crate::env::test_env_lock();
1139        let ctx = init_with_args(["--ros-args", "-r", "chatter:=/other"]).expect("init");
1140        let _ = ctx.config("talker");
1141    }
1142
1143    #[test]
1144    fn config_is_unaffected_without_remaps() {
1145        let _env = crate::env::test_env_lock();
1146        let ctx = init_with_args(["/usr/bin/talker", "--verbose"]).expect("init");
1147        assert_eq!(ctx.config("talker").node_name, "talker");
1148    }
1149
1150    #[test]
1151    fn plain_args_pass_through_to_init() {
1152        let _env = crate::env::test_env_lock();
1153        // Same answer as `init()` — the arguments are not consulted, and no
1154        // refusal fires. Both read the same environment, so compare the
1155        // resolved knobs rather than asserting a particular value.
1156        let via_args = init_with_args(["/usr/bin/talker", "--verbose", "positional"]);
1157        let plain = init();
1158        match (via_args, plain) {
1159            (Ok(a), Ok(b)) => {
1160                assert_eq!(a.domain_id, b.domain_id);
1161                assert_eq!(a.locator, b.locator);
1162                assert_eq!(a.rmw, b.rmw);
1163            }
1164            (Err(a), Err(b)) => assert_eq!(a, b),
1165            (a, b) => panic!("init_with_args and init disagree: {a:?} vs {b:?}"),
1166        }
1167    }
1168
1169    // phase-427 W9 — the rclrs family on a hosted build.
1170
1171    fn same_identity(a: &Context, b: &Context) {
1172        assert_eq!(a.domain_id, b.domain_id);
1173        assert_eq!(a.locator, b.locator);
1174        assert_eq!(a.mode, b.mode);
1175        assert_eq!(a.rmw, b.rmw);
1176        assert_eq!(a.source, b.source);
1177    }
1178
1179    #[test]
1180    fn default_from_env_is_init() {
1181        let _env = crate::env::test_env_lock();
1182        match (Context::default_from_env(), init()) {
1183            (Ok(a), Ok(b)) => {
1184                same_identity(&a, &b);
1185                assert_eq!(a.source, ContextSource::Env);
1186            }
1187            (Err(a), Err(b)) => assert_eq!(a, b),
1188            (a, b) => panic!("default_from_env and init disagree: {a:?} vs {b:?}"),
1189        }
1190    }
1191
1192    #[test]
1193    fn from_env_honours_the_domain_override() {
1194        let _env = crate::env::test_env_lock();
1195        let env = match init() {
1196            Ok(c) => c,
1197            Err(e) => panic!("init() failed on the test host: {e:?}"),
1198        };
1199        // A value the environment is not carrying, so the override is visible
1200        // whatever `ROS_DOMAIN_ID` says.
1201        let wanted = if env.domain_id == 7 { 9 } else { 7 };
1202        let ctx = Context::from_env(InitOptions::new().with_domain_id(Some(wanted as usize)))
1203            .expect("from_env with a valid override");
1204        assert_eq!(ctx.domain_id, wanted);
1205        // Everything else is untouched.
1206        assert_eq!(ctx.locator, env.locator);
1207        assert_eq!(ctx.rmw, env.rmw);
1208        assert_eq!(ctx.source, ContextSource::Env);
1209    }
1210
1211    #[test]
1212    fn from_env_with_no_override_keeps_the_env_value() {
1213        let _env = crate::env::test_env_lock();
1214        match (
1215            Context::from_env(InitOptions::new().with_domain_id(None)),
1216            init(),
1217        ) {
1218            (Ok(a), Ok(b)) => same_identity(&a, &b),
1219            (Err(a), Err(b)) => assert_eq!(a, b),
1220            (a, b) => panic!("from_env(None) and init disagree: {a:?} vs {b:?}"),
1221        }
1222    }
1223
1224    #[test]
1225    fn from_env_rejects_an_out_of_range_override() {
1226        let _env = crate::env::test_env_lock();
1227        if init().is_err() {
1228            // The environment itself is invalid; the override is never reached.
1229            return;
1230        }
1231        assert_eq!(
1232            Context::from_env(InitOptions::new().with_domain_id(Some(DOMAIN_ID_MAX as usize + 1)))
1233                .map(|c| c.domain_id),
1234            Err(InitError::DomainIdOutOfRange)
1235        );
1236        // A value no `u32` can hold saturates in the builder and is refused
1237        // here, not truncated into a plausible small number.
1238        assert_eq!(
1239            Context::from_env(InitOptions::new().with_domain_id(Some(usize::MAX)))
1240                .map(|c| c.domain_id),
1241            Err(InitError::DomainIdOutOfRange)
1242        );
1243    }
1244
1245    #[test]
1246    #[should_panic(expected = "refused: `--enclave`")]
1247    fn context_new_refuses_what_it_cannot_honour() {
1248        let _env = crate::env::test_env_lock();
1249        let _ = Context::new(
1250            [
1251                "/usr/bin/talker",
1252                "--ros-args",
1253                "-r",
1254                "chatter:=/other",
1255                "--enclave",
1256                "/e",
1257            ],
1258            InitOptions::new(),
1259        );
1260    }
1261
1262    #[test]
1263    fn context_new_parses_exactly_like_init_with_args() {
1264        let _env = crate::env::test_env_lock();
1265        let argv = ["/usr/bin/talker", "--ros-args", "-r", "chatter:=/other"];
1266        let a = Context::new(argv, InitOptions::new()).expect("Context::new");
1267        let b = init_with_args(argv).expect("init_with_args");
1268        assert_eq!(a.ros_args, b.ros_args);
1269        assert_eq!(a.ros_args, [remap(None, "chatter", "/other")]);
1270    }
1271
1272    #[test]
1273    fn context_new_passes_plain_args_through() {
1274        let _env = crate::env::test_env_lock();
1275        let opts = InitOptions::new().with_domain_id(Some(3));
1276        match (
1277            Context::new(["/usr/bin/talker", "--verbose", "positional"], opts),
1278            Context::from_env(opts),
1279        ) {
1280            (Ok(a), Ok(b)) => {
1281                same_identity(&a, &b);
1282                assert_eq!(a.domain_id, 3);
1283            }
1284            (Err(a), Err(b)) => assert_eq!(a, b),
1285            (a, b) => panic!("Context::new and from_env disagree: {a:?} vs {b:?}"),
1286        }
1287    }
1288
1289    #[test]
1290    fn context_new_accepts_rclrs_argv_shape() {
1291        let _env = crate::env::test_env_lock();
1292        // `impl IntoIterator<Item = String>` is what rclrs takes; ours must
1293        // accept the same call unchanged.
1294        let args: alloc::vec::Vec<alloc::string::String> =
1295            alloc::vec![alloc::string::String::from("talker")];
1296        let _ = Context::new(args, InitOptions::default());
1297    }
1298}
1299
1300/// phase-427 W9 — the freestanding constructor's parse, with the constants
1301/// injected. Runs on the `alloc` floor (`cargo test -p nros --features alloc
1302/// --lib`); nothing here reads the environment.
1303#[cfg(all(test, feature = "alloc"))]
1304mod baked_tests {
1305    use super::*;
1306
1307    #[test]
1308    fn nothing_baked_is_domain_zero_and_an_absent_locator() {
1309        let ctx = Context::from_baked(None, None).expect("nothing baked is valid");
1310        assert_eq!(ctx.domain_id, 0);
1311        assert_eq!(ctx.locator, "");
1312        assert_eq!(ctx.mode, SessionMode::Client);
1313        assert_eq!(ctx.rmw, "");
1314        assert_eq!(ctx.source, ContextSource::Baked);
1315    }
1316
1317    #[test]
1318    fn baked_values_are_carried() {
1319        let ctx = Context::from_baked(Some("tcp/127.0.0.1:7456"), Some("42")).expect("valid bake");
1320        assert_eq!(ctx.locator, "tcp/127.0.0.1:7456");
1321        assert_eq!(ctx.domain_id, 42);
1322        assert_eq!(ctx.source, ContextSource::Baked);
1323        // The config it materialises is the one the macros used to assemble
1324        // by hand: locator, domain, node name, client mode.
1325        let cfg = ctx.config("talker");
1326        assert_eq!(cfg.locator, "tcp/127.0.0.1:7456");
1327        assert_eq!(cfg.domain_id, 42);
1328        assert_eq!(cfg.node_name, "talker");
1329        assert_eq!(cfg.mode, SessionMode::Client);
1330    }
1331
1332    #[test]
1333    fn an_empty_baked_locator_is_absent() {
1334        let ctx = Context::from_baked(Some(""), None).expect("empty is absent, not an error");
1335        assert_eq!(ctx.locator, "");
1336    }
1337
1338    #[test]
1339    fn a_non_numeric_baked_domain_is_refused() {
1340        assert_eq!(
1341            Context::from_baked(None, Some("seven")).map(|c| c.domain_id),
1342            Err(InitError::EnvParseFailed)
1343        );
1344        assert_eq!(
1345            Context::from_baked(None, Some("-1")).map(|c| c.domain_id),
1346            Err(InitError::EnvParseFailed)
1347        );
1348    }
1349
1350    #[test]
1351    fn an_out_of_range_baked_domain_is_refused() {
1352        // The bound `try_resolve_hosted` applies, so an image cannot be built
1353        // onto a domain a hosted process would refuse to boot on.
1354        assert_eq!(
1355            Context::from_baked(None, Some("300")).map(|c| c.domain_id),
1356            Err(InitError::DomainIdOutOfRange)
1357        );
1358        assert_eq!(
1359            Context::from_baked(None, Some("232")).map(|c| c.domain_id),
1360            Ok(DOMAIN_ID_MAX)
1361        );
1362    }
1363
1364    #[test]
1365    fn locator_override_applies_only_when_present_and_non_empty() {
1366        let baked = || Context::from_baked(Some("tcp/10.0.2.2:7447"), Some("1")).unwrap();
1367        assert_eq!(
1368            baked()
1369                .with_locator_override(Some("tcp/127.0.0.1:7456"))
1370                .locator,
1371            "tcp/127.0.0.1:7456"
1372        );
1373        assert_eq!(
1374            baked().with_locator_override(None).locator,
1375            "tcp/10.0.2.2:7447"
1376        );
1377        assert_eq!(
1378            baked().with_locator_override(Some("")).locator,
1379            "tcp/10.0.2.2:7447"
1380        );
1381        // The override touches nothing else.
1382        let ctx = baked().with_locator_override(Some("tcp/127.0.0.1:7456"));
1383        assert_eq!(ctx.domain_id, 1);
1384        assert_eq!(ctx.source, ContextSource::Baked);
1385    }
1386
1387    #[test]
1388    fn baked_session_properties_take_the_locators_place() {
1389        let baked = || Context::from_baked(Some("tcp/10.0.2.2:7447"), Some("1")).unwrap();
1390        // Issue 2051 — a run-time locator, applied after, still wins.
1391        let connect = [nros_node::SessionProperty::new(
1392            c"connect",
1393            c"tcp/10.0.0.9:7499",
1394        )];
1395        assert_eq!(
1396            baked()
1397                .yield_locator_to_session_properties(&connect)
1398                .locator,
1399            ""
1400        );
1401        assert_eq!(
1402            baked().yield_locator_to_session_properties(&[]).locator,
1403            baked().locator
1404        );
1405        assert_eq!(
1406            baked()
1407                .yield_locator_to_session_properties(&connect)
1408                .with_locator_override(Some("tcp/127.0.0.1:7456"))
1409                .locator,
1410            "tcp/127.0.0.1:7456"
1411        );
1412    }
1413
1414    /// phase-467 row `rust:Context::domain_id`. Two claims, and the second is
1415    /// the one worth a test: the accessor answers the field, and it answers it
1416    /// as a `usize` — rclrs's type — so a ported `let d: usize =
1417    /// ctx.domain_id();` compiles. The annotation is the assertion; without it
1418    /// an integer literal would infer whatever the accessor returns and the
1419    /// test would pass against a `u32` too.
1420    #[test]
1421    fn context_domain_id_reads_the_field_as_rclrs_types_it() {
1422        let ctx = Context::from_baked(Some("tcp/10.0.2.2:7447"), Some("7")).unwrap();
1423        let d: usize = ctx.domain_id();
1424        assert_eq!(d, 7);
1425        assert_eq!(ctx.domain_id(), ctx.domain_id as usize);
1426        // The field did not move: `Context` is a plain struct and both
1427        // spellings reach the same byte.
1428        assert_eq!(ctx.domain_id, 7u32);
1429    }
1430
1431    #[test]
1432    fn baked_reads_this_crates_build_environment() {
1433        // The values depend on the build; the SHAPE does not. Whatever was
1434        // baked, the source is `Baked`, and a parse failure would have come
1435        // from a bake this test cannot control — report it rather than hide it.
1436        match Context::baked() {
1437            Ok(ctx) => assert_eq!(ctx.source, ContextSource::Baked),
1438            Err(e) => panic!(
1439                "NROS_ENTRY_DOMAIN_ID was baked into this test build with a value the constructor refuses: {e:?}"
1440            ),
1441        }
1442    }
1443
1444    #[test]
1445    fn init_options_default_overrides_nothing() {
1446        assert_eq!(InitOptions::new(), InitOptions::default());
1447        assert_eq!(InitOptions::new().domain_id(), None);
1448        assert_eq!(
1449            InitOptions::new().with_domain_id(Some(5)).domain_id(),
1450            Some(5)
1451        );
1452        assert_eq!(
1453            InitOptions::new()
1454                .with_domain_id(Some(5))
1455                .with_domain_id(None)
1456                .domain_id(),
1457            None
1458        );
1459        // Saturates rather than truncates: `u32::MAX + 1` must not read as 0.
1460        // Reported back as a `usize`, which is the getter's type since
1461        // phase-467 — the saturation is in the STORED `u32` and the getter
1462        // only widens it, so this is the one place the two widths are both
1463        // visible in one line.
1464        assert_eq!(
1465            InitOptions::new()
1466                .with_domain_id(Some(u32::MAX as usize + 1))
1467                .domain_id(),
1468            Some(u32::MAX as usize)
1469        );
1470        // The in-place spelling is the same operation.
1471        let mut opts = InitOptions::new();
1472        opts.set_domain_id(Some(9));
1473        assert_eq!(opts, InitOptions::new().with_domain_id(Some(9)));
1474        opts.set_domain_id(None);
1475        assert_eq!(opts, InitOptions::new());
1476    }
1477
1478    /// phase-427 W10 — the two variants `create_executor*` can produce say
1479    /// WHICH thing went wrong, in words. `alloc` only: the errors are values
1480    /// and need no RMW to construct, which is the point of testing them here
1481    /// rather than beside a session.
1482    #[test]
1483    fn the_executor_errors_say_what_happened() {
1484        use alloc::string::ToString as _;
1485
1486        let too_small = InitError::BackingTooSmall {
1487            needed: 4096,
1488            given: 8,
1489        }
1490        .to_string();
1491        // Both numbers, because "too small" without them tells a caller
1492        // nothing they can act on.
1493        assert!(too_small.contains("4096"), "{too_small}");
1494        assert!(too_small.contains('8'), "{too_small}");
1495
1496        // The backend's own error survives the wrapping — issue 0465's rule:
1497        // an exhausted table and a missing router must not read alike.
1498        let open_failed = InitError::ExecutorOpenFailed(NodeError::NodeTableFull).to_string();
1499        assert!(open_failed.contains("NodeTableFull"), "{open_failed}");
1500        assert_ne!(
1501            open_failed,
1502            InitError::ExecutorOpenFailed(NodeError::NameTooLong).to_string()
1503        );
1504    }
1505
1506    #[cfg(not(feature = "env"))]
1507    #[test]
1508    fn freestanding_default_from_env_is_the_bake() {
1509        // Without `env` there is no process environment to read; the family
1510        // resolves to the bake, and the override still lands on top of it.
1511        let ctx = Context::default_from_env().expect("bake");
1512        assert_eq!(ctx.source, ContextSource::Baked);
1513        let ctx = Context::from_env(InitOptions::new().with_domain_id(Some(11))).expect("bake");
1514        assert_eq!(ctx.domain_id, 11);
1515        assert_eq!(ctx.source, ContextSource::Baked);
1516    }
1517}