Skip to main content

zlink_codegen/
codegen.rs

1//! Code generation implementation.
2
3use heck::{ToPascalCase, ToSnakeCase};
4use std::fmt::Write;
5
6type Result<T = ()> = std::result::Result<T, std::fmt::Error>;
7use zlink::idl::{CustomEnum, CustomObject, CustomType, Field, Interface, Method, Type};
8
9/// Code generator for Varlink interfaces.
10pub struct CodeGenerator {
11    output: String,
12    indent_level: usize,
13}
14
15impl CodeGenerator {
16    /// Create a new code generator.
17    pub fn new() -> Self {
18        Self {
19            output: String::new(),
20            indent_level: 0,
21        }
22    }
23
24    /// Get the generated output.
25    pub fn output(self) -> String {
26        self.output
27    }
28
29    /// Write module-level header for multiple interfaces.
30    pub fn write_module_header(&mut self) -> Result<()> {
31        writeln!(
32            &mut self.output,
33            "// Generated code from Varlink IDL files."
34        )?;
35        writeln!(&mut self.output)?;
36        writeln!(&mut self.output, "use serde::{{Deserialize, Serialize}};")?;
37        writeln!(&mut self.output, "use zlink::{{proxy, ReplyError}};")?;
38        writeln!(&mut self.output)?;
39        Ok(())
40    }
41
42    /// Generate code for an interface.
43    pub fn generate_interface(
44        &mut self,
45        interface: &Interface<'_>,
46        skip_module_header: bool,
47    ) -> Result<()> {
48        if skip_module_header {
49            self.write_interface_comment(interface)?;
50        } else {
51            self.write_header(interface)?;
52            self.writeln("use serde::{Deserialize, Serialize};")?;
53            // Always import ReplyError since we generate a stub error type when there are no errors
54            self.writeln("use zlink::{proxy, ReplyError};")?;
55            self.writeln("")?;
56        }
57
58        // Generate proxy trait using the proxy macro.
59        self.generate_proxy_trait(interface)?;
60        self.writeln("")?;
61
62        // Generate output structs for methods.
63        self.generate_output_structs(interface)?;
64
65        // Generate custom types.
66        for custom_type in interface.custom_types() {
67            self.generate_custom_type(custom_type)?;
68            self.writeln("")?;
69        }
70
71        // Generate errors.
72        if interface.errors().count() > 0 {
73            self.generate_errors(interface)?;
74            self.writeln("")?;
75        }
76
77        Ok(())
78    }
79
80    fn write_interface_comment(&mut self, interface: &Interface<'_>) -> Result<()> {
81        writeln!(
82            &mut self.output,
83            "// Generated code for Varlink interface `{}`.",
84            interface.name()
85        )?;
86        writeln!(&mut self.output)?;
87        Ok(())
88    }
89
90    fn write_header(&mut self, interface: &Interface<'_>) -> Result<()> {
91        writeln!(
92            &mut self.output,
93            "//! Generated code for Varlink interface `{}`.",
94            interface.name()
95        )?;
96        writeln!(&mut self.output, "//!",)?;
97        writeln!(
98            &mut self.output,
99            "//! This code was generated by `zlink-codegen` from Varlink IDL.",
100        )?;
101        writeln!(
102            &mut self.output,
103            "//! You may prefer to adapt it, instead of using it verbatim.",
104        )?;
105        writeln!(&mut self.output)?;
106
107        // Add interface comments if any.
108        for comment in interface.comments() {
109            writeln!(&mut self.output, "//! {}", comment.text())?;
110        }
111        writeln!(&mut self.output)?;
112
113        Ok(())
114    }
115
116    fn generate_custom_type(&mut self, custom_type: &CustomType<'_>) -> Result<()> {
117        match custom_type {
118            CustomType::Object(obj) => self.generate_custom_object(obj),
119            CustomType::Enum(enum_type) => self.generate_custom_enum(enum_type),
120        }
121    }
122
123    fn generate_custom_object(&mut self, obj: &CustomObject<'_>) -> Result<()> {
124        // Add comments.
125        for comment in obj.comments() {
126            self.writeln(&format!("/// {}", comment.text()))?;
127        }
128
129        self.writeln("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]")?;
130        self.writeln(&format!("pub struct {} {{", custom_type_name(obj.name())))?;
131        self.indent();
132
133        for field in obj.fields() {
134            self.generate_field(field)?;
135        }
136
137        self.dedent();
138        self.writeln("}")?;
139
140        Ok(())
141    }
142
143    fn generate_custom_enum(&mut self, enum_type: &CustomEnum<'_>) -> Result<()> {
144        // Add comments.
145        for comment in enum_type.comments() {
146            self.writeln(&format!("/// {}", comment.text()))?;
147        }
148
149        self.writeln("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]")?;
150        self.writeln("#[serde(rename_all = \"snake_case\")]")?;
151        self.writeln(&format!(
152            "pub enum {} {{",
153            custom_type_name(enum_type.name())
154        ))?;
155        self.indent();
156
157        for variant in enum_type.variants() {
158            // Add variant comments.
159            for comment in variant.comments() {
160                self.writeln(&format!("/// {}", comment.text()))?;
161            }
162
163            // Varlink enum variants don't have explicit values, just names.
164            let safe_variant_name = rust_ident(&variant.name().to_pascal_case());
165
166            // The enum is renamed to snake_case, which doesn't always make the value of the
167            // variant. Say what the value is unless it does.
168            if serde_snake_case(unraw(&safe_variant_name)) != variant.name().as_str() {
169                self.writeln(&format!("#[serde(rename = \"{}\")]", variant.name()))?;
170            }
171            self.writeln(&format!("{},", safe_variant_name))?;
172        }
173
174        self.dedent();
175        self.writeln("}")?;
176
177        Ok(())
178    }
179
180    fn generate_field(&mut self, field: &Field<'_>) -> Result<()> {
181        // Add field comments.
182        for comment in field.comments() {
183            self.writeln(&format!("/// {}", comment.text()))?;
184        }
185
186        let field_name = field.name().to_snake_case();
187        let rust_type = self.type_to_rust(field.ty())?;
188
189        // Check if the field type is optional.
190        let rust_type = if matches!(field.ty(), Type::Optional(_)) {
191            // The type_to_rust will already wrap in Option
192            rust_type
193        } else {
194            rust_type
195        };
196
197        // Rename the field unless its identifier is spelled like its name. A raw identifier isn't,
198        // although serde strips the `r#`.
199        let safe_field_name = rust_ident(&field_name);
200        let field_name_attr = if safe_field_name != field.name().as_str() {
201            format!("#[serde(rename = \"{}\")]", field.name())
202        } else {
203            String::new()
204        };
205
206        if !field_name_attr.is_empty() {
207            self.writeln(&field_name_attr)?;
208        }
209
210        self.writeln(&format!("pub {}: {},", safe_field_name, rust_type))?;
211
212        Ok(())
213    }
214
215    fn generate_errors(&mut self, interface: &Interface<'_>) -> Result<()> {
216        self.writeln("/// Errors that can occur in this interface.")?;
217        self.writeln("#[derive(Debug, Clone, PartialEq, ReplyError)]")?;
218        self.writeln(&format!("#[zlink(interface = \"{}\")]", interface.name()))?;
219        self.writeln(&format!(
220            "pub enum {}Error {{",
221            interface_name_to_rust(interface.name())
222        ))?;
223        self.indent();
224
225        for error in interface.errors() {
226            // Add error comments.
227            for comment in error.comments() {
228                self.writeln(&format!("/// {}", comment.text()))?;
229            }
230
231            let safe_variant_name = rust_ident(&error.name().to_pascal_case());
232
233            // The `ReplyError` derive names the error after the variant (without the `r#`), unless
234            // told otherwise.
235            if unraw(&safe_variant_name) != error.name().as_str() {
236                self.writeln(&format!("#[zlink(rename = \"{}\")]", error.name()))?;
237            }
238            if error.fields().count() == 0 {
239                self.writeln(&format!("{},", safe_variant_name))?;
240            } else {
241                self.writeln(&format!("{} {{", safe_variant_name))?;
242                self.indent();
243                for field in error.fields() {
244                    self.generate_error_field(field)?;
245                }
246                self.dedent();
247                self.writeln("},")?;
248            }
249        }
250
251        self.dedent();
252        self.writeln("}")?;
253
254        Ok(())
255    }
256
257    /// Generate output structs for all methods in the `interface`.
258    fn generate_output_structs(&mut self, interface: &Interface<'_>) -> Result<()> {
259        for method in interface.methods() {
260            // Generate output struct for any method with at least one output parameter.
261            // Varlink output parameters are always named, so we need a struct even for single
262            // outputs.
263            if method.outputs().count() > 0 {
264                let struct_name = format!("{}Output", method.name().to_pascal_case());
265
266                // Add method comments if available
267                self.writeln(&format!(
268                    "/// Output parameters for the {} method.",
269                    method.name()
270                ))?;
271
272                // Add lifetime parameter for output structs that need it
273                let (flags, _) = MethodFlags::parse(method);
274                let needs_lifetime = output_needs_lifetime(method, flags);
275
276                self.writeln("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]")?;
277                if needs_lifetime {
278                    self.writeln(&format!("pub struct {}<'a> {{", struct_name))?;
279                } else {
280                    self.writeln(&format!("pub struct {} {{", struct_name))?;
281                }
282                self.indent();
283
284                for output in method.outputs() {
285                    let field_name = output.name().to_snake_case();
286                    // Use reference types for output parameters where appropriate
287                    let rust_type = if needs_lifetime {
288                        self.type_to_rust_output(output.ty())?
289                    } else {
290                        self.type_to_rust(output.ty())?
291                    };
292
293                    // Add #[serde(borrow)] for fields that need it
294                    if needs_lifetime && type_needs_borrow(output.ty()) {
295                        self.writeln("#[serde(borrow)]")?;
296                    }
297
298                    // Serde takes the name of the field from its identifier, without the `r#` of
299                    // a raw one. Rename the field if that isn't its name.
300                    let safe_field_name = rust_ident(&field_name);
301                    if unraw(&safe_field_name) != output.name().as_str() {
302                        self.writeln(&format!("#[serde(rename = \"{}\")]", output.name()))?;
303                    }
304
305                    self.writeln(&format!("pub {}: {},", safe_field_name, rust_type))?;
306                }
307
308                self.dedent();
309                self.writeln("}")?;
310                self.writeln("")?;
311            }
312        }
313
314        Ok(())
315    }
316
317    fn generate_proxy_trait(&mut self, interface: &Interface<'_>) -> Result<()> {
318        let trait_name = rust_ident(&interface_name_to_rust(interface.name()));
319
320        // Generate a stub error type if there are no errors in the interface
321        let error_type = if interface.errors().count() > 0 {
322            format!("{}Error", interface_name_to_rust(interface.name()))
323        } else {
324            // Generate a stub error type for interfaces without errors
325            let stub_error_name = format!("{}Error", interface_name_to_rust(interface.name()));
326
327            // Generate the stub error type before the proxy trait
328            self.writeln("/// Stub error type for interface without errors.")?;
329            self.writeln("///")?;
330            self.writeln("/// This is an empty enum that can never be instantiated.")?;
331            self.writeln("/// It exists only to satisfy the proxy trait requirements.")?;
332            self.writeln("#[derive(Debug, Clone, PartialEq, ReplyError)]")?;
333            self.writeln(&format!("#[zlink(interface = \"{}\")]", interface.name()))?;
334            self.writeln(&format!("pub enum {} {{}}", stub_error_name))?;
335            self.writeln("")?;
336
337            stub_error_name
338        };
339
340        self.writeln("/// Proxy trait for calling methods on the interface.")?;
341        self.writeln(&format!("#[proxy(\"{}\")]", interface.name()))?;
342        self.writeln(&format!("pub trait {} {{", trait_name))?;
343        self.indent();
344
345        for method in interface.methods() {
346            self.generate_proxy_method_signature(method, &error_type)?;
347        }
348
349        self.dedent();
350        self.writeln("}")?;
351
352        Ok(())
353    }
354
355    /// Generate the proxy methods of the `method`: one for each way of calling it.
356    fn generate_proxy_method_signature(
357        &mut self,
358        method: &Method<'_>,
359        error_type: &str,
360    ) -> Result<()> {
361        // The comments that mark the flags don't document the method: its attributes express them.
362        let (flags, docs) = MethodFlags::parse(method);
363        let method_name = method.name().to_snake_case();
364
365        // Add input parameters.
366        let mut params = String::new();
367        for param in method.inputs() {
368            let param_name = param.name().to_snake_case();
369            let safe_param_name = rust_ident(&param_name);
370            // Use references for parameters that can be borrowed
371            let rust_type = self.type_to_rust_param(param.ty())?;
372
373            write!(&mut params, ",")?;
374            // Add parameter with potential rename attribute.
375            if safe_param_name != param.name().as_str() {
376                write!(&mut params, " #[zlink(rename = \"{}\")]", param.name(),)?;
377            }
378
379            write!(&mut params, " {}: {}", safe_param_name, rust_type)?;
380        }
381
382        // Handle output parameters.
383        let output_count = method.outputs().count();
384        let output = if output_count == 0 {
385            "()".to_string()
386        } else {
387            // Always use the generated output struct for any outputs.
388            // Varlink output parameters are always named, so we need a struct even for single
389            // outputs.
390            let struct_name = format!("{}Output", method.name().to_pascal_case());
391            // Add lifetime parameter if the struct needs one
392            if output_needs_lifetime(method, flags) {
393                format!("{}<'_>", struct_name)
394            } else {
395                struct_name
396            }
397        };
398        let reply = format!("Result<{}, {}>", output, error_type);
399
400        let calls = flags.calls();
401        for &call in &calls {
402            // The regular method, or the only one there is, keeps the plain name. The others get
403            // the name of their flag as a suffix and are renamed back to the Varlink method.
404            let renamed = if calls.len() > 1 { call } else { None };
405
406            // Add method comments.
407            for doc in &docs {
408                self.writeln(&format!("/// {}", doc))?;
409            }
410            if let Some(flag) = renamed {
411                if !docs.is_empty() {
412                    self.writeln("///")?;
413                }
414                self.writeln(&format!("/// {}", flag.doc()))?;
415            }
416
417            let name = match renamed {
418                Some(flag) => format!("{}_{}", method_name, flag.name()),
419                None => method_name.clone(),
420            };
421            let safe_name = rust_ident(&name);
422
423            // Tell the proxy macro about the flag, and about the Varlink method unless the macro
424            // derives its name from the identifier (without the `r#`) by itself.
425            let mut attrs = Vec::new();
426            if let Some(flag) = call {
427                attrs.push(flag.name().to_string());
428            }
429            if snake_case_to_pascal_case(unraw(&safe_name)) != method.name().as_str() {
430                attrs.push(format!("rename = \"{}\"", method.name()));
431            }
432            if !attrs.is_empty() {
433                self.writeln(&format!("#[zlink({})]", attrs.join(", ")))?;
434            }
435
436            // Generate method signature.
437            let return_type = if call == Some(CallFlag::More) {
438                // The method returns a stream of the replies.
439                format!(
440                    "zlink::Result<impl zlink::futures_util::Stream<Item = zlink::Result<{}>>>",
441                    reply
442                )
443            } else {
444                format!("zlink::Result<{}>", reply)
445            };
446            self.writeln(&format!(
447                "async fn {}(&mut self{}) -> {};",
448                safe_name, params, return_type
449            ))?;
450        }
451
452        Ok(())
453    }
454
455    fn generate_error_field(&mut self, field: &Field<'_>) -> Result<()> {
456        // Add field comments.
457        for comment in field.comments() {
458            self.writeln(&format!("/// {}", comment.text()))?;
459        }
460
461        let field_name = field.name().to_snake_case();
462        let rust_type = self.type_to_rust(field.ty())?;
463
464        // Rename the field unless its identifier is spelled like its name. A raw identifier isn't,
465        // although the `ReplyError` derive strips the `r#`.
466        let safe_field_name = rust_ident(&field_name);
467        let field_name_attr = if safe_field_name != field.name().as_str() {
468            format!("#[zlink(rename = \"{}\")]", field.name())
469        } else {
470            String::new()
471        };
472
473        if !field_name_attr.is_empty() {
474            self.writeln(&field_name_attr)?;
475        }
476
477        self.writeln(&format!("{}: {},", safe_field_name, rust_type))?;
478
479        Ok(())
480    }
481
482    fn type_to_rust(&self, ty: &Type) -> Result<String> {
483        type_to_rust(ty)
484    }
485
486    fn type_to_rust_param(&self, ty: &Type) -> Result<String> {
487        type_to_rust_param(ty)
488    }
489
490    fn type_to_rust_output(&self, ty: &Type) -> Result<String> {
491        type_to_rust_output(ty)
492    }
493
494    fn writeln(&mut self, s: &str) -> Result<()> {
495        self.write(s)?;
496        writeln!(&mut self.output)?;
497        Ok(())
498    }
499
500    fn write(&mut self, s: &str) -> Result<()> {
501        for _ in 0..self.indent_level {
502            write!(&mut self.output, "    ")?;
503        }
504        write!(&mut self.output, "{}", s)?;
505        Ok(())
506    }
507
508    fn indent(&mut self) {
509        self.indent_level += 1;
510    }
511
512    fn dedent(&mut self) {
513        if self.indent_level > 0 {
514            self.indent_level -= 1;
515        }
516    }
517}
518
519impl Default for CodeGenerator {
520    fn default() -> Self {
521        Self::new()
522    }
523}
524
525/// Whether the output struct of the `method` has a lifetime, for its fields to borrow from the
526/// connection.
527fn output_needs_lifetime(method: &Method<'_>, flags: MethodFlags) -> bool {
528    // The outputs of the methods taking flags are owned: the replies of a stream must be, and the
529    // caller of an upgrade takes the connection apart right after the reply, which a reply
530    // borrowing from the connection would prevent.
531    !flags.is_flagged() && method.outputs().any(|o| type_needs_lifetime(o.ty()))
532}
533
534/// The flags that a method supports or requires.
535///
536/// The IDL can't express these, so systemd marks its methods with comments right before them.
537#[derive(Clone, Copy, Default)]
538struct MethodFlags {
539    more: FlagSupport,
540    upgrade: FlagSupport,
541}
542
543impl MethodFlags {
544    /// Parse the flags of the `method` from its comments.
545    ///
546    /// Along with the flags, this gives the texts of the other comments: the ones that document the
547    /// method.
548    fn parse<'a>(method: &Method<'a>) -> (Self, Vec<&'a str>) {
549        let mut flags = Self::default();
550        let mut docs = Vec::new();
551
552        for comment in method.comments() {
553            match comment.text().trim() {
554                MORE_SUPPORTED => flags.more = FlagSupport::Supported,
555                MORE_REQUIRED => flags.more = FlagSupport::Required,
556                UPGRADE_SUPPORTED => flags.upgrade = FlagSupport::Supported,
557                UPGRADE_REQUIRED => flags.upgrade = FlagSupport::Required,
558                _ => docs.push(comment.text()),
559            }
560        }
561
562        (flags, docs)
563    }
564
565    /// Whether the method supports or requires any flag.
566    fn is_flagged(self) -> bool {
567        self.more != FlagSupport::Unsupported || self.upgrade != FlagSupport::Unsupported
568    }
569
570    /// The flags that the calls of the method carry, `None` being a call without any.
571    ///
572    /// Each of these gets a proxy method.
573    fn calls(self) -> Vec<Option<CallFlag>> {
574        let mut calls = Vec::new();
575
576        // A method that requires a flag can't be called without it.
577        if self.more != FlagSupport::Required && self.upgrade != FlagSupport::Required {
578            calls.push(None);
579        }
580        if self.more != FlagSupport::Unsupported {
581            calls.push(Some(CallFlag::More));
582        }
583        if self.upgrade != FlagSupport::Unsupported {
584            calls.push(Some(CallFlag::Upgrade));
585        }
586
587        calls
588    }
589}
590
591/// How a method makes use of a flag.
592#[derive(Clone, Copy, Default, PartialEq, Eq)]
593enum FlagSupport {
594    /// The method doesn't take the flag.
595    #[default]
596    Unsupported,
597    /// The method can be called with or without the flag.
598    Supported,
599    /// The method can only be called with the flag.
600    Required,
601}
602
603/// A flag that a call can carry.
604#[derive(Clone, Copy, PartialEq, Eq)]
605enum CallFlag {
606    /// The call gets a stream of replies.
607    More,
608    /// The reply to the call upgrades the connection.
609    Upgrade,
610}
611
612impl CallFlag {
613    /// The name of the flag, as the `zlink` attribute has it.
614    fn name(self) -> &'static str {
615        match self {
616            Self::More => "more",
617            Self::Upgrade => "upgrade",
618        }
619    }
620
621    /// The doc line of the proxy method that sets the flag, to tell it from the other ones.
622    fn doc(self) -> &'static str {
623        match self {
624            Self::More => "Calls the method with the `more` flag, streaming its replies.",
625            Self::Upgrade => {
626                "Calls the method with the `upgrade` flag, so a successful reply upgrades the \
627                 connection."
628            }
629        }
630    }
631}
632
633// The comments that mark the flags of a method, as systemd does.
634const MORE_SUPPORTED: &str = "[Supports 'more' flag]";
635const MORE_REQUIRED: &str = "[Requires 'more' flag]";
636const UPGRADE_SUPPORTED: &str = "[Supports 'upgrade' flag]";
637const UPGRADE_REQUIRED: &str = "[Requires 'upgrade' flag]";
638
639fn type_to_rust(ty: &Type) -> Result<String> {
640    Ok(match ty {
641        Type::Bool => "bool".to_string(),
642        Type::Int => "i64".to_string(),
643        Type::Float => "f64".to_string(),
644        Type::String => "String".to_string(),
645        Type::Object(_fields) => {
646            // Anonymous struct - generate inline.
647            // For now, use serde_json::Value for anonymous objects.
648            // In the future, we could generate anonymous structs.
649            "serde_json::Value".to_string()
650        }
651        Type::Enum(_variants) => {
652            // Anonymous enum - use String for now.
653            "String".to_string()
654        }
655        Type::Array(elem_type) => {
656            let elem_rust = type_to_rust(elem_type.inner())?;
657            format!("Vec<{}>", elem_rust)
658        }
659        Type::Map(value_type) => {
660            let value_rust = type_to_rust(value_type.inner())?;
661            format!("std::collections::HashMap<String, {}>", value_rust)
662        }
663        Type::ForeignObject => "serde_json::Value".to_string(),
664        Type::Optional(inner_type) => {
665            let inner_rust = type_to_rust(inner_type.inner())?;
666            format!("Option<{}>", inner_rust)
667        }
668        Type::Custom(name) => custom_type_name(name),
669        Type::Any => "serde_json::Value".to_string(),
670    })
671}
672
673fn type_to_rust_param(ty: &Type) -> Result<String> {
674    Ok(match ty {
675        Type::Bool => "bool".to_string(),
676        Type::Int => "i64".to_string(),
677        Type::Float => "f64".to_string(),
678        Type::String => "&str".to_string(),
679        Type::Object(_fields) => {
680            // For parameters, use reference to avoid clone
681            "&serde_json::Value".to_string()
682        }
683        Type::Enum(_variants) => {
684            // Anonymous enum - use &str for parameters
685            "&str".to_string()
686        }
687        Type::Array(elem_type) => {
688            // Use slice for array parameters with proper string handling
689            let elem_rust = type_to_rust_param_elem(elem_type.inner())?;
690            format!("&[{}]", elem_rust)
691        }
692        Type::Map(value_type) => {
693            // Use reference for map parameters with proper string handling
694            let value_rust = type_to_rust_param_elem(value_type.inner())?;
695            format!("&std::collections::HashMap<&str, {}>", value_rust)
696        }
697        Type::ForeignObject => "&serde_json::Value".to_string(),
698        Type::Optional(inner_type) => {
699            let inner_rust = type_to_rust_param(inner_type.inner())?;
700            // For optional parameters, always wrap in Option
701            format!("Option<{}>", inner_rust)
702        }
703        Type::Custom(name) => format!("&{}", custom_type_name(name)),
704        Type::Any => "&serde_json::Value".to_string(),
705    })
706}
707
708// Helper function to get the proper type for collection elements in parameters.
709// Ensures strings always use &str instead of String.
710fn type_to_rust_param_elem(ty: &Type) -> Result<String> {
711    Ok(match ty {
712        Type::Bool => "bool".to_string(),
713        Type::Int => "i64".to_string(),
714        Type::Float => "f64".to_string(),
715        Type::String => "&str".to_string(),
716        Type::Object(_fields) => "serde_json::Value".to_string(),
717        Type::Enum(_variants) => "&str".to_string(),
718        Type::Array(elem_type) => {
719            let elem_rust = type_to_rust_param_elem(elem_type.inner())?;
720            format!("Vec<{}>", elem_rust)
721        }
722        Type::Map(value_type) => {
723            let value_rust = type_to_rust_param_elem(value_type.inner())?;
724            format!("std::collections::HashMap<&str, {}>", value_rust)
725        }
726        Type::ForeignObject => "serde_json::Value".to_string(),
727        Type::Any => "serde_json::Value".to_string(),
728        Type::Optional(inner_type) => {
729            let inner_rust = type_to_rust_param_elem(inner_type.inner())?;
730            format!("Option<{}>", inner_rust)
731        }
732        Type::Custom(name) => custom_type_name(name),
733    })
734}
735
736fn type_to_rust_output(ty: &Type) -> Result<String> {
737    Ok(match ty {
738        Type::Bool => "bool".to_string(),
739        Type::Int => "i64".to_string(),
740        Type::Float => "f64".to_string(),
741        Type::String => "&'a str".to_string(),
742        Type::Object(_fields) => {
743            // Use owned type for objects - serde can't deserialize to &Value
744            "serde_json::Value".to_string()
745        }
746        Type::Enum(_variants) => {
747            // Anonymous enum - use &str for outputs
748            "&'a str".to_string()
749        }
750        Type::Array(elem_type) => {
751            // Use Vec for array outputs with owned inner types (except strings stay as &'a str)
752            let elem_rust = match elem_type.inner() {
753                Type::String => "&'a str".to_string(),
754                Type::Enum(_) => "&'a str".to_string(),
755                _ => type_to_rust(elem_type.inner())?,
756            };
757            format!("Vec<{}>", elem_rust)
758        }
759        Type::Map(value_type) => {
760            // Use HashMap for map outputs with borrowed types for efficiency
761            let value_rust = match value_type.inner() {
762                Type::String => "&'a str".to_string(),
763                Type::Enum(_) => "&'a str".to_string(),
764                _ => type_to_rust(value_type.inner())?,
765            };
766            format!("std::collections::HashMap<&'a str, {}>", value_rust)
767        }
768        Type::ForeignObject => "serde_json::Value".to_string(),
769        Type::Any => "serde_json::Value".to_string(),
770        Type::Optional(inner_type) => {
771            // For optional outputs, recursively apply type_to_rust_output to maintain
772            // correct reference types for strings within collections
773            let inner_rust = type_to_rust_output(inner_type.inner())?;
774            format!("Option<{}>", inner_rust)
775        }
776        Type::Custom(name) => custom_type_name(name),
777    })
778}
779
780/// The Rust name of the custom type `name`.
781///
782/// The definition of the type and every reference to it get the name from here, so they agree.
783fn custom_type_name(name: &str) -> String {
784    rust_ident(&name.to_pascal_case())
785}
786
787fn interface_name_to_rust(name: &str) -> String {
788    // Convert interface name like "org.example.Interface" to "Interface".
789    name.split('.').next_back().unwrap_or(name).to_pascal_case()
790}
791
792fn type_needs_lifetime(ty: &Type) -> bool {
793    match ty {
794        Type::String => true,
795        Type::Enum(_) => true, // Anonymous enums use &'a str
796        Type::Array(inner) => type_needs_lifetime(inner.inner()),
797        Type::Map(_) => {
798            // Maps always need lifetime because keys are &'a str
799            true
800        }
801        Type::Optional(inner) => type_needs_lifetime(inner.inner()),
802        _ => false,
803    }
804}
805
806fn type_needs_borrow(ty: &Type) -> bool {
807    match ty {
808        Type::String => true,
809        Type::Enum(_) => true, // Anonymous enums use &'a str
810        Type::Array(inner) => type_needs_borrow(inner.inner()),
811        Type::Map(_) => {
812            // Maps always need borrow because keys are &'a str
813            true
814        }
815        Type::Optional(inner) => type_needs_borrow(inner.inner()),
816        _ => false,
817    }
818}
819
820/// Convert snake_case to PascalCase, the way the `proxy` macro does to name the Varlink method of a
821/// proxy method that has no `#[zlink(rename)]`.
822///
823/// This is a copy of `snake_case_to_pascal_case` in `zlink-macros/src/proxy/utils.rs`, with which
824/// it has to agree. The integration tests call the methods through the real macro, so they notice
825/// if it doesn't.
826fn snake_case_to_pascal_case(input: &str) -> String {
827    input
828        .split('_')
829        .map(|word| {
830            let mut chars = word.chars();
831            let Some(first) = chars.next() else {
832                return String::new();
833            };
834            first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
835        })
836        .collect()
837}
838
839/// The value that serde makes of a variant, for an enum with `#[serde(rename_all = "snake_case")]`.
840///
841/// This is `RenameRule::SnakeCase` of `serde_derive` (in `src/internals/case.rs`): an underscore
842/// goes before each uppercase character but the first one, and all the characters are lowercased.
843fn serde_snake_case(variant: &str) -> String {
844    let mut snake = String::new();
845    for (i, ch) in variant.char_indices() {
846        if i > 0 && ch.is_uppercase() {
847            snake.push('_');
848        }
849        snake.push(ch.to_ascii_lowercase());
850    }
851    snake
852}
853
854/// The identifier for the `name`, which is in Rust case already: snake_case for fields, parameters
855/// and methods, PascalCase for types and variants.
856///
857/// A keyword becomes a raw identifier (`r#type`), except for `self`, `Self`, `super` and `crate`,
858/// which can't be raw: those get a trailing underscore (`self_`), as rustc suggests. That can't
859/// clash with the identifier of another name: Varlink names can't end with an underscore, and
860/// converting them to Rust case doesn't add one.
861fn rust_ident(name: &str) -> String {
862    match name {
863        "self" | "Self" | "super" | "crate" => format!("{}_", name),
864        _ if is_rust_keyword(name) => format!("r#{}", name),
865        _ => name.to_string(),
866    }
867}
868
869/// The `ident` without the `r#` of a raw identifier, which isn't part of its name.
870fn unraw(ident: &str) -> &str {
871    ident.strip_prefix("r#").unwrap_or(ident)
872}
873
874/// Whether `s` is a keyword of Rust: one that's in use, or one that's reserved for later.
875fn is_rust_keyword(s: &str) -> bool {
876    [
877        "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
878        "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move",
879        "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait",
880        "true", "type", "unsafe", "use", "where", "while",
881        // The reserved ones. Some are keywords in the later editions only, but raw identifiers
882        // work in all of them.
883        "abstract", "become", "box", "do", "final", "gen", "macro", "override", "priv", "try",
884        "typeof", "unsized", "virtual", "yield",
885    ]
886    .contains(&s)
887}