Skip to main content

robonix_codegen/codegen/
contract_gen.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Generate `robonix_contracts.proto` from `<root>/capabilities/**/*.toml`.
3//
4// `[mode].type` → `robonix_contracts.proto` (see `<root>/capabilities/README.md`).
5// Streaming: `rpc_server_stream` uses the .srv response (exactly one field) as stream element; `rpc_client_stream` uses the request (exactly one field).
6
7use anyhow::{Context, Result, bail};
8use serde::Deserialize;
9use std::collections::BTreeSet;
10use std::fmt::Write as _;
11use std::fs;
12use std::path::{Path, PathBuf};
13
14#[path = "contract_channel_gen.rs"]
15mod channel_gen;
16
17use super::msg_parser::{MsgField, MsgResolver, MsgTypeRef, SrvSpec};
18use super::proto_gen::proto_package_name;
19
20#[derive(Debug, Deserialize)]
21struct ContractToml {
22    contract: ContractMeta,
23    mode: ModeSpec,
24}
25
26#[derive(Debug, Deserialize)]
27struct ContractMeta {
28    id: String,
29    version: String,
30    kind: String,
31    /// IDL reference: full path under one of the merged lib roots
32    /// (`<robonix>/capabilities/lib/` or `<pkg>/capabilities/lib/`),
33    /// with the `.srv` / `.msg` extension. Examples:
34    ///   `system/pilot/srv/SubmitTask.srv`        → lib/.../srv/SubmitTask.srv
35    ///   `common_interfaces/sensor_msgs/msg/Image.msg` → lib/.../msg/Image.msg
36    idl: String,
37    /// Documentation-only meaning of this abstract contract. This is not the
38    /// provider/runtime capability description declared to Atlas.
39    #[serde(default)]
40    description: String,
41    /// Whether Pilot may include implementations in its model-facing catalog.
42    /// This metadata does not change generated transport stubs.
43    #[serde(default = "default_true")]
44    llm_callable: bool,
45}
46
47fn default_true() -> bool {
48    true
49}
50
51#[derive(Debug, Deserialize)]
52struct ModeSpec {
53    #[serde(rename = "type")]
54    mode_type: String,
55}
56
57/// Internal IDL-reference triple after parsing `<lib-relative path>`.
58/// Constructed in resolve_contract_io from the `[contract].idl` schema;
59/// passed to the per-mode resolvers.
60struct IdlRef<'a> {
61    /// Original path string from the toml field, kept for error messages.
62    path: &'a str,
63}
64
65/// `(ROS package, srv name)` pairs from every contract's
66/// `[contract].idl` when it points at a `.srv`. Used by proto generation:
67/// only these `.srv` files get `*_Request` / `*_Response` messages.
68pub fn collect_referenced_srvs(contracts_dir: &Path) -> Result<BTreeSet<(String, String)>> {
69    let paths = collect_tomls(contracts_dir)?;
70    let mut set = BTreeSet::new();
71    for p in paths {
72        let raw =
73            fs::read_to_string(&p).with_context(|| format!("read contract {}", p.display()))?;
74        let c: ContractToml =
75            toml::from_str(&raw).with_context(|| format!("parse TOML {}", p.display()))?;
76        let idl = c.contract.idl.trim();
77        match parse_idl_path(idl) {
78            Some((pkg, "srv", name)) => {
79                set.insert((pkg.to_string(), name.to_string()));
80            }
81            Some((_, "msg", _)) => {
82                // `idl` points at a `.msg` (topic mode); not a srv reference.
83            }
84            _ => bail!(
85                "contract {}: [contract].idl must be a lib-relative file path ending in .srv or .msg, got {idl:?}",
86                c.contract.id
87            ),
88        }
89    }
90    Ok(set)
91}
92
93/// Lightweight per-contract view for documentation generation. Built from
94/// the same TOML parse + directory walk as proto generation, so the docs
95/// reference can't drift from what codegen / atlas actually read.
96pub struct ContractSummary {
97    pub id: String,
98    pub version: String,
99    pub kind: String,
100    pub mode: String,
101    pub idl: String,
102    /// Documentation-only meaning of this abstract contract.
103    pub description: String,
104    /// Whether Pilot may expose implementations to its planning model.
105    pub llm_callable: bool,
106    /// Absolute path to the source `.v1.toml`.
107    pub toml_path: PathBuf,
108}
109
110/// Load every contract under `dirs` (recursively, skipping `lib/`), de-duped
111/// by id (later dir wins, matching atlas merge semantics), sorted by id.
112/// Backs `robonix-codegen --lang docs`.
113pub fn load_contract_summaries(dirs: &[PathBuf]) -> Result<Vec<ContractSummary>> {
114    let mut by_id: std::collections::BTreeMap<String, ContractSummary> =
115        std::collections::BTreeMap::new();
116    for d in dirs {
117        for p in collect_tomls(d)? {
118            let raw =
119                fs::read_to_string(&p).with_context(|| format!("read contract {}", p.display()))?;
120            let c: ContractToml =
121                toml::from_str(&raw).with_context(|| format!("parse TOML {}", p.display()))?;
122            by_id.insert(
123                c.contract.id.clone(),
124                ContractSummary {
125                    id: c.contract.id,
126                    version: c.contract.version,
127                    kind: c.contract.kind,
128                    mode: c.mode.mode_type,
129                    idl: c.contract.idl,
130                    description: c.contract.description.trim().to_string(),
131                    llm_callable: c.contract.llm_callable,
132                    toml_path: p,
133                },
134            );
135        }
136    }
137    Ok(by_id.into_values().collect())
138}
139
140pub fn generate(
141    resolver: &mut MsgResolver,
142    contracts_dirs: &[PathBuf],
143    out_dir: &Path,
144    verbose: bool,
145) -> Result<()> {
146    let mut paths: Vec<PathBuf> = Vec::new();
147    for d in contracts_dirs {
148        for p in collect_tomls(d)? {
149            paths.push(p);
150        }
151    }
152    if paths.is_empty() {
153        if verbose {
154            for d in contracts_dirs {
155                eprintln!(
156                    "[robonix-codegen] contracts: no .toml under {}",
157                    d.display()
158                );
159            }
160        }
161        return Ok(());
162    }
163
164    // De-dup on contract id: later root wins, matching atlas's
165    // contract-registry merge semantics. This lets a per-package
166    // contract override a global one of the same id during codegen.
167    let mut by_id: std::collections::BTreeMap<String, (PathBuf, ContractToml)> =
168        std::collections::BTreeMap::new();
169    for p in paths {
170        let raw =
171            fs::read_to_string(&p).with_context(|| format!("read contract {}", p.display()))?;
172        let c: ContractToml =
173            toml::from_str(&raw).with_context(|| format!("parse TOML {}", p.display()))?;
174        by_id.insert(c.contract.id.clone(), (p, c));
175    }
176    let mut contracts: Vec<(PathBuf, ContractToml)> = by_id.into_values().collect();
177    contracts.sort_by(|a, b| a.1.contract.id.cmp(&b.1.contract.id));
178
179    let mut out = String::new();
180    writeln!(&mut out, "// @generated by robonix-codegen (--contracts).")?;
181    writeln!(&mut out, "// Do not edit by hand.")?;
182    writeln!(&mut out, "syntax = \"proto3\";")?;
183    writeln!(&mut out)?;
184    writeln!(&mut out, "package robonix.contracts;")?;
185    writeln!(&mut out)?;
186    writeln!(&mut out, "import \"google/protobuf/empty.proto\";")?;
187    writeln!(&mut out)?;
188
189    let mut imports: BTreeSet<String> = BTreeSet::new();
190    let mut needs_string_wire = false;
191
192    let mut proto_types: Vec<(String, ResolvedType, ResolvedType)> = Vec::new();
193    for (_, c) in &contracts {
194        let (in_t, out_t) = resolve_contract_io(c, resolver, &mut imports, &mut needs_string_wire)?;
195        proto_types.push((c.contract.id.clone(), in_t, out_t));
196    }
197
198    for imp in &imports {
199        writeln!(&mut out, "import \"{imp}\";",)?;
200    }
201    if !imports.is_empty() {
202        writeln!(&mut out)?;
203    }
204
205    if needs_string_wire {
206        writeln!(
207            &mut out,
208            "// Wrapper for contracts that use primitive/string until shared IDL exists."
209        )?;
210        writeln!(&mut out, "message StringWire {{")?;
211        writeln!(&mut out, "  string value = 1;")?;
212        writeln!(&mut out, "}}")?;
213        writeln!(&mut out)?;
214    }
215
216    for ((_, c), (_, in_t, out_t)) in contracts.iter().zip(proto_types.iter()) {
217        let mode = c.mode.mode_type.trim();
218        let svc = contract_id_to_service_name(&c.contract.id);
219        let method = contract_method_name(c);
220        writeln!(
221            &mut out,
222            "// contract: {} (v{})",
223            c.contract.id, c.contract.version
224        )?;
225        writeln!(&mut out, "service {svc} {{")?;
226
227        let rpc = match mode {
228            "rpc" => format_unary(&method, in_t, out_t),
229            "rpc_server_stream" | "topic_out" => format_stream_out(&method, in_t, out_t),
230            "rpc_client_stream" | "topic_in" => format_stream_in(&method, in_t, out_t),
231            "rpc_bidirectional_stream" => format_bidi_stream(&method, in_t, out_t),
232            other => bail!(
233                "unknown [mode].type '{other}' in contract {} (expected rpc | rpc_server_stream | rpc_client_stream | topic_out | topic_in)",
234                c.contract.id
235            ),
236        };
237        writeln!(&mut out, "  {rpc}")?;
238
239        writeln!(&mut out, "}}")?;
240        writeln!(&mut out)?;
241    }
242
243    let outfile = out_dir.join("robonix_contracts.proto");
244    fs::write(&outfile, &out).with_context(|| format!("write {}", outfile.display()))?;
245    if verbose {
246        eprintln!(
247            "[robonix-codegen] contracts: wrote {} ({} services)",
248            outfile.display(),
249            contracts.len()
250        );
251    }
252
253    channel_gen::generate(&contracts, &proto_types, resolver, out_dir, verbose)?;
254    Ok(())
255}
256
257#[derive(Clone)]
258enum ResolvedType {
259    ProtoFqn(String),
260    GoogleEmpty,
261    /// Reserved escape hatch for raw string-typed contracts. Currently
262    /// unused (no contract opts in); kept so the plumbing is in place
263    /// for the rare case it's needed.
264    #[allow(dead_code)]
265    StringWire,
266}
267
268fn format_stream_out(method: &str, input: &ResolvedType, output: &ResolvedType) -> String {
269    format!(
270        "rpc {method}({}) returns (stream {});",
271        empty_or_type(input),
272        stream_element(output)
273    )
274}
275
276fn format_stream_in(method: &str, input: &ResolvedType, output: &ResolvedType) -> String {
277    format!(
278        "rpc {method}(stream {}) returns ({});",
279        stream_element(input),
280        unary_return(output)
281    )
282}
283
284fn format_bidi_stream(method: &str, input: &ResolvedType, output: &ResolvedType) -> String {
285    format!(
286        "rpc {method}(stream {}) returns (stream {});",
287        stream_element(input),
288        stream_element(output)
289    )
290}
291
292fn format_unary(method: &str, input: &ResolvedType, output: &ResolvedType) -> String {
293    format!(
294        "rpc {method}({}) returns ({});",
295        unary_arg(input),
296        unary_return(output)
297    )
298}
299
300fn empty_or_type(t: &ResolvedType) -> String {
301    match t {
302        ResolvedType::GoogleEmpty => "google.protobuf.Empty".to_string(),
303        ResolvedType::ProtoFqn(s) => s.clone(),
304        ResolvedType::StringWire => "robonix.contracts.StringWire".to_string(),
305    }
306}
307
308fn unary_arg(t: &ResolvedType) -> String {
309    empty_or_type(t)
310}
311
312fn unary_return(t: &ResolvedType) -> String {
313    match t {
314        ResolvedType::GoogleEmpty => "google.protobuf.Empty".to_string(),
315        ResolvedType::ProtoFqn(s) => s.clone(),
316        ResolvedType::StringWire => "robonix.contracts.StringWire".to_string(),
317    }
318}
319
320fn stream_element(t: &ResolvedType) -> String {
321    unary_arg(t)
322}
323
324fn srv_stream_field_to_resolved(
325    contract_id: &str,
326    srv_path: &str,
327    section: &str,
328    field: &MsgField,
329    resolver: &mut MsgResolver,
330    imports: &mut BTreeSet<String>,
331    needs_string_wire: &mut bool,
332) -> Result<ResolvedType> {
333    if field.is_array {
334        bail!(
335            "contract {contract_id}: [{section}] stream element must be a single message, not an array (in {srv_path})"
336        );
337    }
338    field_to_resolved_type(field, resolver, imports, needs_string_wire)
339}
340
341fn resolve_contract_io(
342    c: &ContractToml,
343    resolver: &mut MsgResolver,
344    imports: &mut BTreeSet<String>,
345    needs_string_wire: &mut bool,
346) -> Result<(ResolvedType, ResolvedType)> {
347    let mode = c.mode.mode_type.trim();
348    let idl_path = c.contract.idl.trim();
349    let (_, kind, _) = parse_idl_path(idl_path).ok_or_else(|| {
350        anyhow::anyhow!(
351            "contract {}: [contract].idl must be a lib-relative file path ending in .srv or .msg, got {idl_path:?}",
352            c.contract.id
353        )
354    })?;
355
356    // Verify the file actually exists at this path under at least one
357    // configured lib root. The `idl` field is interpreted as the literal
358    // lib-relative file path (with extension); codegen joins each
359    // lib_root with this path and checks file existence.
360    if !idl_path_exists(idl_path, resolver) {
361        bail!(
362            "contract {}: idl path {idl_path:?} doesn't resolve to a file under any lib root ({})",
363            c.contract.id,
364            resolver.include_paths.len()
365        );
366    }
367
368    let idl = IdlRef { path: idl_path };
369
370    match (mode, kind) {
371        ("rpc", "srv") => resolve_srv_contract_pair(idl.path, resolver, imports, needs_string_wire),
372        ("rpc_server_stream", "srv") => {
373            resolve_srv_server_stream(&idl, &c.contract.id, resolver, imports, needs_string_wire)
374        }
375        ("rpc_client_stream", "srv") => {
376            resolve_srv_client_stream(&idl, &c.contract.id, resolver, imports, needs_string_wire)
377        }
378        ("rpc_bidirectional_stream", "srv") => {
379            resolve_srv_bidi_stream(&idl, &c.contract.id, resolver, imports, needs_string_wire)
380        }
381        ("topic_out", "msg") => {
382            let elem = resolve_io(idl.path, resolver, imports, needs_string_wire)?;
383            Ok((ResolvedType::GoogleEmpty, elem))
384        }
385        ("topic_in", "msg") => {
386            let elem = resolve_io(idl.path, resolver, imports, needs_string_wire)?;
387            Ok((elem, ResolvedType::GoogleEmpty))
388        }
389        ("rpc" | "rpc_server_stream" | "rpc_client_stream" | "rpc_bidirectional_stream", "msg") => {
390            bail!(
391                "contract {}: mode={mode:?} requires a `.srv` IDL but [contract].idl points at a `.msg` ({idl_path:?})",
392                c.contract.id
393            )
394        }
395        ("topic_out" | "topic_in", "srv") => {
396            bail!(
397                "contract {}: mode={mode:?} requires a `.msg` IDL but [contract].idl points at a `.srv` ({idl_path:?})",
398                c.contract.id
399            )
400        }
401        (other, _) => bail!(
402            "unknown [mode].type {other:?} in contract {}",
403            c.contract.id
404        ),
405    }
406}
407
408/// Parse the user-written `idl` path. The path includes the file extension
409/// (`.srv` / `.msg`) and is interpreted as the literal lib-relative file
410/// path — codegen will look it up at `<lib_root>/<idl>` for each lib root.
411///
412/// Returns `(pkg, kind, name)` where:
413///   - `kind` is derived from the file extension (`"srv"` / `"msg"`)
414///   - `name` is the file basename without extension (e.g. `SubmitTask`)
415///   - `pkg` is the directory immediately above `srv/` / `msg/` when
416///     the path follows the conventional `<...>/<pkg>/{srv,msg}/<Name>`
417///     layout — needed by the downstream MsgResolver lookup. For flat
418///     layouts (no `/srv/` or `/msg/` subdir), `pkg` is empty: the
419///     existing resolver doesn't index those, and the caller will get
420///     a clear "not indexed" error from the resolver itself.
421fn parse_idl_path(
422    s: &str,
423) -> Option<(
424    &str,         /* pkg */
425    &'static str, /* kind */
426    &str,         /* name */
427)> {
428    let (stem, kind): (&str, &'static str) = if let Some(rest) = s.strip_suffix(".srv") {
429        (rest, "srv")
430    } else {
431        let rest = s.strip_suffix(".msg")?;
432        (rest, "msg")
433    };
434    let parts: Vec<&str> = stem.split('/').filter(|p| !p.is_empty()).collect();
435    if parts.is_empty() {
436        return None;
437    }
438    let n = parts.len();
439    let name = parts[n - 1];
440    let pkg = if n >= 3 && (parts[n - 2] == "srv" || parts[n - 2] == "msg") {
441        parts[n - 3]
442    } else {
443        ""
444    };
445    Some((pkg, kind, name))
446}
447
448/// Verify the user-written idl path resolves to an actual file under
449/// at least one of the resolver's include_paths. The path is the literal
450/// file path — codegen joins it directly with each lib root.
451fn idl_path_exists(idl: &str, resolver: &MsgResolver) -> bool {
452    for root in &resolver.include_paths {
453        if root.join(idl).is_file() {
454            return true;
455        }
456    }
457    false
458}
459
460fn resolve_srv_server_stream(
461    idl: &IdlRef,
462    contract_id: &str,
463    resolver: &mut MsgResolver,
464    imports: &mut BTreeSet<String>,
465    needs_string_wire: &mut bool,
466) -> Result<(ResolvedType, ResolvedType)> {
467    let p = idl.path;
468    let Some((pkg, "srv", name)) = parse_idl_path(p) else {
469        bail!("[contract].idl must end with /srv/Name for rpc modes, got {p:?}");
470    };
471    resolver
472        .resolve_srv(pkg, name)
473        .with_context(|| format!("resolve srv {p}"))?;
474    let spec = resolver
475        .srv_spec(pkg, name)
476        .ok_or_else(|| anyhow::anyhow!("internal: srv {p} not cached"))?
477        .clone();
478
479    let res = &spec.response;
480    if res.fields.len() != 1 {
481        bail!(
482            "contract {contract_id}: [mode] rpc_server_stream requires the .srv response section to have exactly one field (stream element type), got {} in {p}",
483            res.fields.len()
484        );
485    }
486    let in_t = srv_request_to_contract_input(&spec, resolver, imports, needs_string_wire)?;
487    let out_t = srv_stream_field_to_resolved(
488        contract_id,
489        p,
490        "response",
491        &res.fields[0],
492        resolver,
493        imports,
494        needs_string_wire,
495    )?;
496    Ok((in_t, out_t))
497}
498
499fn resolve_srv_client_stream(
500    idl: &IdlRef,
501    contract_id: &str,
502    resolver: &mut MsgResolver,
503    imports: &mut BTreeSet<String>,
504    needs_string_wire: &mut bool,
505) -> Result<(ResolvedType, ResolvedType)> {
506    let p = idl.path;
507    let Some((pkg, "srv", name)) = parse_idl_path(p) else {
508        bail!("[contract].idl must end with /srv/Name for rpc modes, got {p:?}");
509    };
510    resolver
511        .resolve_srv(pkg, name)
512        .with_context(|| format!("resolve srv {p}"))?;
513    let spec = resolver
514        .srv_spec(pkg, name)
515        .ok_or_else(|| anyhow::anyhow!("internal: srv {p} not cached"))?
516        .clone();
517
518    let req = &spec.request;
519    if req.fields.len() != 1 {
520        bail!(
521            "contract {contract_id}: [mode] rpc_client_stream requires the .srv request section to have exactly one field (stream element type), got {} in {p}",
522            req.fields.len()
523        );
524    }
525    let in_t = srv_stream_field_to_resolved(
526        contract_id,
527        p,
528        "request",
529        &req.fields[0],
530        resolver,
531        imports,
532        needs_string_wire,
533    )?;
534    let out_t = srv_response_to_contract_output(&spec, resolver, imports, needs_string_wire)?;
535    Ok((in_t, out_t))
536}
537
538/// Bidirectional stream: the `.srv` Request and Response sections are the
539/// per-message stream element types (each must have exactly one field, same
540/// rule as server-stream / client-stream). Mirrors gRPC bidi shape:
541/// `rpc M(stream RequestType) returns (stream ResponseType)`.
542fn resolve_srv_bidi_stream(
543    idl: &IdlRef,
544    contract_id: &str,
545    resolver: &mut MsgResolver,
546    imports: &mut BTreeSet<String>,
547    needs_string_wire: &mut bool,
548) -> Result<(ResolvedType, ResolvedType)> {
549    let p = idl.path;
550    let Some((pkg, "srv", name)) = parse_idl_path(p) else {
551        bail!("[contract].idl must end with /srv/Name for rpc modes, got {p:?}");
552    };
553    resolver
554        .resolve_srv(pkg, name)
555        .with_context(|| format!("resolve srv {p}"))?;
556    let spec = resolver
557        .srv_spec(pkg, name)
558        .ok_or_else(|| anyhow::anyhow!("internal: srv {p} not cached"))?
559        .clone();
560
561    let req = &spec.request;
562    let res = &spec.response;
563    if req.fields.len() != 1 {
564        bail!(
565            "contract {contract_id}: [mode] rpc_bidirectional_stream requires the .srv request section to have exactly one field (client→server stream element type), got {} in {p}",
566            req.fields.len()
567        );
568    }
569    if res.fields.len() != 1 {
570        bail!(
571            "contract {contract_id}: [mode] rpc_bidirectional_stream requires the .srv response section to have exactly one field (server→client stream element type), got {} in {p}",
572            res.fields.len()
573        );
574    }
575    let in_t = srv_stream_field_to_resolved(
576        contract_id,
577        p,
578        "request",
579        &req.fields[0],
580        resolver,
581        imports,
582        needs_string_wire,
583    )?;
584    let out_t = srv_stream_field_to_resolved(
585        contract_id,
586        p,
587        "response",
588        &res.fields[0],
589        resolver,
590        imports,
591        needs_string_wire,
592    )?;
593    Ok((in_t, out_t))
594}
595
596fn srv_request_to_contract_input(
597    srv: &SrvSpec,
598    resolver: &mut MsgResolver,
599    imports: &mut BTreeSet<String>,
600    needs_string_wire: &mut bool,
601) -> Result<ResolvedType> {
602    let req = &srv.request;
603    if req.fields.len() == 1 {
604        return field_to_resolved_type(&req.fields[0], resolver, imports, needs_string_wire);
605    }
606    imports.insert(format!("{}.proto", srv.package));
607    Ok(ResolvedType::ProtoFqn(format!(
608        "{}.{}",
609        proto_package_name(&srv.package),
610        req.name
611    )))
612}
613
614/// Empty `.srv` response section → `google.protobuf.Empty`; else the generated `*_Response` message.
615fn srv_response_to_contract_output(
616    srv: &SrvSpec,
617    resolver: &mut MsgResolver,
618    imports: &mut BTreeSet<String>,
619    _needs_string_wire: &mut bool,
620) -> Result<ResolvedType> {
621    let res = &srv.response;
622    if res.fields.is_empty() {
623        return Ok(ResolvedType::GoogleEmpty);
624    }
625    for f in &res.fields {
626        if let MsgTypeRef::Named { package, name } = &f.type_ref {
627            resolver.resolve_named_type(package, name, None)?;
628        }
629    }
630    imports.insert(format!("{}.proto", srv.package));
631    Ok(ResolvedType::ProtoFqn(format!(
632        "{}.{}",
633        proto_package_name(&srv.package),
634        res.name
635    )))
636}
637
638fn resolve_srv_contract_pair(
639    path: &str,
640    resolver: &mut MsgResolver,
641    imports: &mut BTreeSet<String>,
642    _needs_string_wire: &mut bool,
643) -> Result<(ResolvedType, ResolvedType)> {
644    let p = path.trim();
645    if let Some((pkg, "srv", name)) = parse_idl_path(p) {
646        resolver
647            .resolve_srv(pkg, name)
648            .with_context(|| format!("resolve srv {p}"))?;
649        imports.insert(format!("{pkg}.proto"));
650        let req = format!("{name}_Request");
651        let res = format!("{name}_Response");
652        return Ok((
653            ResolvedType::ProtoFqn(format!("{}.{}", proto_package_name(pkg), req)),
654            ResolvedType::ProtoFqn(format!("{}.{}", proto_package_name(pkg), res)),
655        ));
656    }
657    bail!("[contract].idl must end with /srv/Name for rpc modes, got {p:?}");
658}
659
660fn field_to_resolved_type(
661    field: &MsgField,
662    resolver: &mut MsgResolver,
663    imports: &mut BTreeSet<String>,
664    needs_string_wire: &mut bool,
665) -> Result<ResolvedType> {
666    match &field.type_ref {
667        MsgTypeRef::Primitive(_) => bail!(
668            "contract I/O field `{}` must use a named ROS message type, not a primitive",
669            field.name
670        ),
671        MsgTypeRef::Named { package, name } => resolve_io(
672            &format!("{package}/msg/{name}"),
673            resolver,
674            imports,
675            needs_string_wire,
676        ),
677    }
678}
679
680/// Resolve a nested ROS-style type reference from inside a .srv/.msg
681/// file (3-segment `pkg/msg/Name` or `pkg/srv/Name`). Different from
682/// the user-facing top-level `idl` field, which uses the new
683/// extension-bearing path format and is resolved via `parse_idl_path`.
684fn resolve_io(
685    spec: &str,
686    resolver: &mut MsgResolver,
687    imports: &mut BTreeSet<String>,
688    _needs_string_wire: &mut bool,
689) -> Result<ResolvedType> {
690    let s = spec.trim();
691    // First try the new extension-bearing path format (used when this
692    // function is called from topic_out / topic_in / bidi resolvers
693    // with the user's `idl` field value).
694    if (s.ends_with(".srv") || s.ends_with(".msg"))
695        && let Some((pkg, kind, name)) = parse_idl_path(s)
696    {
697        return match kind {
698            "msg" => {
699                resolver
700                    .resolve_named_type(pkg, name, None)
701                    .with_context(|| {
702                        format!("resolve msg {pkg}/{name} referenced from contract")
703                    })?;
704                imports.insert(format!("{pkg}.proto"));
705                Ok(ResolvedType::ProtoFqn(format!(
706                    "{}.{}",
707                    proto_package_name(pkg),
708                    name
709                )))
710            }
711            "srv" => {
712                resolver.resolve_srv(pkg, name).with_context(|| {
713                    format!("resolve srv {pkg}/{name} referenced from contract")
714                })?;
715                imports.insert(format!("{pkg}.proto"));
716                let req = format!("{}_Request", name);
717                Ok(ResolvedType::ProtoFqn(format!(
718                    "{}.{}",
719                    proto_package_name(pkg),
720                    req
721                )))
722            }
723            _ => unreachable!(),
724        };
725    }
726    // Otherwise: nested ROS-style reference inside an IDL file
727    // (`pkg/msg/Name` / `pkg/Name` for same-pkg refs handled by parser).
728    let parts: Vec<&str> = s.split('/').collect();
729    match parts.as_slice() {
730        [pkg, "msg", name] => {
731            resolver
732                .resolve_named_type(pkg, name, None)
733                .with_context(|| format!("resolve msg {pkg}/{name} referenced from contract"))?;
734            imports.insert(format!("{pkg}.proto"));
735            Ok(ResolvedType::ProtoFqn(format!(
736                "{}.{}",
737                proto_package_name(pkg),
738                name
739            )))
740        }
741        [pkg, "srv", name] => {
742            resolver
743                .resolve_srv(pkg, name)
744                .with_context(|| format!("resolve srv {pkg}/{name} referenced from contract"))?;
745            imports.insert(format!("{pkg}.proto"));
746            let req = format!("{}_Request", name);
747            Ok(ResolvedType::ProtoFqn(format!(
748                "{}.{}",
749                proto_package_name(pkg),
750                req
751            )))
752        }
753        _ => bail!(
754            "unsupported IDL reference {s:?} (expected `<pkg>/msg/<Name>` or `<pkg>/srv/<Name>` for nested refs, or a lib-relative path ending in .srv/.msg for top-level idl)"
755        ),
756    }
757}
758
759#[allow(dead_code)]
760fn parse_ros_path(s: &str) -> Option<(&str, &str, &str)> {
761    let parts: Vec<&str> = s.split('/').collect();
762    if parts.len() != 3 {
763        return None;
764    }
765    Some((parts[0], parts[1], parts[2]))
766}
767
768fn contract_method_name(contract: &ContractToml) -> String {
769    let (_, kind, name) = parse_idl_path(contract.contract.idl.trim()).unwrap();
770    // Topic methods use the contract leaf, not the shared message name.
771    upper_camel(if kind == "srv" {
772        name
773    } else {
774        contract.contract.id.rsplit('/').next().unwrap()
775    })
776}
777
778/// Convert an arbitrary identifier to UpperCamelCase. Splits on `_`/`-`/
779/// digit-letter boundaries and capitalises each segment.
780/// `submit_task` → `SubmitTask`; `scan_2d` → `Scan2d`; `SubmitTask` → `SubmitTask`.
781fn upper_camel(s: &str) -> String {
782    let mut out = String::with_capacity(s.len());
783    let mut capitalize_next = true;
784    for ch in s.chars() {
785        if ch == '_' || ch == '-' {
786            capitalize_next = true;
787            continue;
788        }
789        if capitalize_next {
790            out.extend(ch.to_uppercase());
791            capitalize_next = false;
792        } else {
793            out.push(ch);
794        }
795    }
796    out
797}
798
799/// Uniform PascalCase per `/`-segment. No prefix stripping.
800/// `robonix/primitive/chassis/move` → `RobonixPrimitiveChassisMove`.
801/// `mycomp/a/b/c`                   → `MycompABC`.
802fn contract_id_to_service_name(id: &str) -> String {
803    id.split('/')
804        .filter(|x| !x.is_empty())
805        .map(|seg| {
806            seg.split('_')
807                .filter(|p| !p.is_empty())
808                .map(|p| {
809                    let mut c = p.chars();
810                    match c.next() {
811                        None => String::new(),
812                        Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
813                    }
814                })
815                .collect::<String>()
816        })
817        .collect::<String>()
818}
819
820fn collect_tomls(dir: &Path) -> Result<Vec<PathBuf>> {
821    let mut v = Vec::new();
822    collect_tomls_inner(dir, &mut v)?;
823    v.sort();
824    Ok(v)
825}
826
827fn collect_tomls_inner(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
828    if !dir.is_dir() {
829        bail!("contracts directory does not exist: {}", dir.display());
830    }
831    for entry in fs::read_dir(dir).with_context(|| format!("read_dir {}", dir.display()))? {
832        let entry = entry?;
833        let p = entry.path();
834        if p.is_dir() {
835            // Hard convention: `<capabilities>/lib/` holds only ROS
836            // msg/srv source for the IDL resolver. Skip it here so
837            // any stray .toml dropped under lib/ never gets picked up
838            // as a contract.
839            if p.file_name().and_then(|s| s.to_str()) == Some("lib") {
840                continue;
841            }
842            collect_tomls_inner(&p, out)?;
843        } else if p.extension().and_then(|x| x.to_str()) == Some("toml") {
844            out.push(p);
845        }
846    }
847    Ok(())
848}
浙ICP备2023005800号-2 浙公网安备33010902005384号