zlink-codegen 0.9.0

Utility to generate zlink code from varlink IDL files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! Code generation implementation.

use heck::{ToPascalCase, ToSnakeCase};
use std::fmt::Write;

type Result<T = ()> = std::result::Result<T, std::fmt::Error>;
use zlink::idl::{CustomEnum, CustomObject, CustomType, Field, Interface, Method, Type};

/// Code generator for Varlink interfaces.
pub struct CodeGenerator {
    output: String,
    indent_level: usize,
}

impl CodeGenerator {
    /// Create a new code generator.
    pub fn new() -> Self {
        Self {
            output: String::new(),
            indent_level: 0,
        }
    }

    /// Get the generated output.
    pub fn output(self) -> String {
        self.output
    }

    /// Write module-level header for multiple interfaces.
    pub fn write_module_header(&mut self) -> Result<()> {
        writeln!(
            &mut self.output,
            "// Generated code from Varlink IDL files."
        )?;
        writeln!(&mut self.output)?;
        writeln!(&mut self.output, "use serde::{{Deserialize, Serialize}};")?;
        writeln!(&mut self.output, "use zlink::{{proxy, ReplyError}};")?;
        writeln!(&mut self.output)?;
        Ok(())
    }

    /// Generate code for an interface.
    pub fn generate_interface(
        &mut self,
        interface: &Interface<'_>,
        skip_module_header: bool,
    ) -> Result<()> {
        if skip_module_header {
            self.write_interface_comment(interface)?;
        } else {
            self.write_header(interface)?;
            self.writeln("use serde::{Deserialize, Serialize};")?;
            // Always import ReplyError since we generate a stub error type when there are no errors
            self.writeln("use zlink::{proxy, ReplyError};")?;
            self.writeln("")?;
        }

        // Generate proxy trait using the proxy macro.
        self.generate_proxy_trait(interface)?;
        self.writeln("")?;

        // Generate output structs for methods.
        self.generate_output_structs(interface)?;

        // Generate custom types.
        for custom_type in interface.custom_types() {
            self.generate_custom_type(custom_type)?;
            self.writeln("")?;
        }

        // Generate errors.
        if interface.errors().count() > 0 {
            self.generate_errors(interface)?;
            self.writeln("")?;
        }

        Ok(())
    }

    fn write_interface_comment(&mut self, interface: &Interface<'_>) -> Result<()> {
        writeln!(
            &mut self.output,
            "// Generated code for Varlink interface `{}`.",
            interface.name()
        )?;
        writeln!(&mut self.output)?;
        Ok(())
    }

    fn write_header(&mut self, interface: &Interface<'_>) -> Result<()> {
        writeln!(
            &mut self.output,
            "//! Generated code for Varlink interface `{}`.",
            interface.name()
        )?;
        writeln!(&mut self.output, "//!",)?;
        writeln!(
            &mut self.output,
            "//! This code was generated by `zlink-codegen` from Varlink IDL.",
        )?;
        writeln!(
            &mut self.output,
            "//! You may prefer to adapt it, instead of using it verbatim.",
        )?;
        writeln!(&mut self.output)?;

        // Add interface comments if any.
        for comment in interface.comments() {
            writeln!(&mut self.output, "//! {}", comment.text())?;
        }
        writeln!(&mut self.output)?;

        Ok(())
    }

    fn generate_custom_type(&mut self, custom_type: &CustomType<'_>) -> Result<()> {
        match custom_type {
            CustomType::Object(obj) => self.generate_custom_object(obj),
            CustomType::Enum(enum_type) => self.generate_custom_enum(enum_type),
        }
    }

    fn generate_custom_object(&mut self, obj: &CustomObject<'_>) -> Result<()> {
        // Add comments.
        for comment in obj.comments() {
            self.writeln(&format!("/// {}", comment.text()))?;
        }

        self.writeln("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]")?;
        self.writeln(&format!("pub struct {} {{", custom_type_name(obj.name())))?;
        self.indent();

        for field in obj.fields() {
            self.generate_field(field)?;
        }

        self.dedent();
        self.writeln("}")?;

        Ok(())
    }

    fn generate_custom_enum(&mut self, enum_type: &CustomEnum<'_>) -> Result<()> {
        // Add comments.
        for comment in enum_type.comments() {
            self.writeln(&format!("/// {}", comment.text()))?;
        }

        self.writeln("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]")?;
        self.writeln("#[serde(rename_all = \"snake_case\")]")?;
        self.writeln(&format!(
            "pub enum {} {{",
            custom_type_name(enum_type.name())
        ))?;
        self.indent();

        for variant in enum_type.variants() {
            // Add variant comments.
            for comment in variant.comments() {
                self.writeln(&format!("/// {}", comment.text()))?;
            }

            // Varlink enum variants don't have explicit values, just names.
            let safe_variant_name = rust_ident(&variant.name().to_pascal_case());

            // The enum is renamed to snake_case, which doesn't always make the value of the
            // variant. Say what the value is unless it does.
            if serde_snake_case(unraw(&safe_variant_name)) != variant.name().as_str() {
                self.writeln(&format!("#[serde(rename = \"{}\")]", variant.name()))?;
            }
            self.writeln(&format!("{},", safe_variant_name))?;
        }

        self.dedent();
        self.writeln("}")?;

        Ok(())
    }

    fn generate_field(&mut self, field: &Field<'_>) -> Result<()> {
        // Add field comments.
        for comment in field.comments() {
            self.writeln(&format!("/// {}", comment.text()))?;
        }

        let field_name = field.name().to_snake_case();
        let rust_type = self.type_to_rust(field.ty())?;

        // Check if the field type is optional.
        let rust_type = if matches!(field.ty(), Type::Optional(_)) {
            // The type_to_rust will already wrap in Option
            rust_type
        } else {
            rust_type
        };

        // Rename the field unless its identifier is spelled like its name. A raw identifier isn't,
        // although serde strips the `r#`.
        let safe_field_name = rust_ident(&field_name);
        let field_name_attr = if safe_field_name != field.name().as_str() {
            format!("#[serde(rename = \"{}\")]", field.name())
        } else {
            String::new()
        };

        if !field_name_attr.is_empty() {
            self.writeln(&field_name_attr)?;
        }

        self.writeln(&format!("pub {}: {},", safe_field_name, rust_type))?;

        Ok(())
    }

    fn generate_errors(&mut self, interface: &Interface<'_>) -> Result<()> {
        self.writeln("/// Errors that can occur in this interface.")?;
        self.writeln("#[derive(Debug, Clone, PartialEq, ReplyError)]")?;
        self.writeln(&format!("#[zlink(interface = \"{}\")]", interface.name()))?;
        self.writeln(&format!(
            "pub enum {}Error {{",
            interface_name_to_rust(interface.name())
        ))?;
        self.indent();

        for error in interface.errors() {
            // Add error comments.
            for comment in error.comments() {
                self.writeln(&format!("/// {}", comment.text()))?;
            }

            let safe_variant_name = rust_ident(&error.name().to_pascal_case());

            // The `ReplyError` derive names the error after the variant (without the `r#`), unless
            // told otherwise.
            if unraw(&safe_variant_name) != error.name().as_str() {
                self.writeln(&format!("#[zlink(rename = \"{}\")]", error.name()))?;
            }
            if error.fields().count() == 0 {
                self.writeln(&format!("{},", safe_variant_name))?;
            } else {
                self.writeln(&format!("{} {{", safe_variant_name))?;
                self.indent();
                for field in error.fields() {
                    self.generate_error_field(field)?;
                }
                self.dedent();
                self.writeln("},")?;
            }
        }

        self.dedent();
        self.writeln("}")?;

        Ok(())
    }

    /// Generate output structs for all methods in the `interface`.
    fn generate_output_structs(&mut self, interface: &Interface<'_>) -> Result<()> {
        for method in interface.methods() {
            // Generate output struct for any method with at least one output parameter.
            // Varlink output parameters are always named, so we need a struct even for single
            // outputs.
            if method.outputs().count() > 0 {
                let struct_name = format!("{}Output", method.name().to_pascal_case());

                // Add method comments if available
                self.writeln(&format!(
                    "/// Output parameters for the {} method.",
                    method.name()
                ))?;

                // Add lifetime parameter for output structs that need it
                let (flags, _) = MethodFlags::parse(method);
                let needs_lifetime = output_needs_lifetime(method, flags);

                self.writeln("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]")?;
                if needs_lifetime {
                    self.writeln(&format!("pub struct {}<'a> {{", struct_name))?;
                } else {
                    self.writeln(&format!("pub struct {} {{", struct_name))?;
                }
                self.indent();

                for output in method.outputs() {
                    let field_name = output.name().to_snake_case();
                    // Use reference types for output parameters where appropriate
                    let rust_type = if needs_lifetime {
                        self.type_to_rust_output(output.ty())?
                    } else {
                        self.type_to_rust(output.ty())?
                    };

                    // Add #[serde(borrow)] for fields that need it
                    if needs_lifetime && type_needs_borrow(output.ty()) {
                        self.writeln("#[serde(borrow)]")?;
                    }

                    // Serde takes the name of the field from its identifier, without the `r#` of
                    // a raw one. Rename the field if that isn't its name.
                    let safe_field_name = rust_ident(&field_name);
                    if unraw(&safe_field_name) != output.name().as_str() {
                        self.writeln(&format!("#[serde(rename = \"{}\")]", output.name()))?;
                    }

                    self.writeln(&format!("pub {}: {},", safe_field_name, rust_type))?;
                }

                self.dedent();
                self.writeln("}")?;
                self.writeln("")?;
            }
        }

        Ok(())
    }

    fn generate_proxy_trait(&mut self, interface: &Interface<'_>) -> Result<()> {
        let trait_name = rust_ident(&interface_name_to_rust(interface.name()));

        // Generate a stub error type if there are no errors in the interface
        let error_type = if interface.errors().count() > 0 {
            format!("{}Error", interface_name_to_rust(interface.name()))
        } else {
            // Generate a stub error type for interfaces without errors
            let stub_error_name = format!("{}Error", interface_name_to_rust(interface.name()));

            // Generate the stub error type before the proxy trait
            self.writeln("/// Stub error type for interface without errors.")?;
            self.writeln("///")?;
            self.writeln("/// This is an empty enum that can never be instantiated.")?;
            self.writeln("/// It exists only to satisfy the proxy trait requirements.")?;
            self.writeln("#[derive(Debug, Clone, PartialEq, ReplyError)]")?;
            self.writeln(&format!("#[zlink(interface = \"{}\")]", interface.name()))?;
            self.writeln(&format!("pub enum {} {{}}", stub_error_name))?;
            self.writeln("")?;

            stub_error_name
        };

        self.writeln("/// Proxy trait for calling methods on the interface.")?;
        self.writeln(&format!("#[proxy(\"{}\")]", interface.name()))?;
        self.writeln(&format!("pub trait {} {{", trait_name))?;
        self.indent();

        for method in interface.methods() {
            self.generate_proxy_method_signature(method, &error_type)?;
        }

        self.dedent();
        self.writeln("}")?;

        Ok(())
    }

    /// Generate the proxy methods of the `method`: one for each way of calling it.
    fn generate_proxy_method_signature(
        &mut self,
        method: &Method<'_>,
        error_type: &str,
    ) -> Result<()> {
        // The comments that mark the flags don't document the method: its attributes express them.
        let (flags, docs) = MethodFlags::parse(method);
        let method_name = method.name().to_snake_case();

        // Add input parameters.
        let mut params = String::new();
        for param in method.inputs() {
            let param_name = param.name().to_snake_case();
            let safe_param_name = rust_ident(&param_name);
            // Use references for parameters that can be borrowed
            let rust_type = self.type_to_rust_param(param.ty())?;

            write!(&mut params, ",")?;
            // Add parameter with potential rename attribute.
            if safe_param_name != param.name().as_str() {
                write!(&mut params, " #[zlink(rename = \"{}\")]", param.name(),)?;
            }

            write!(&mut params, " {}: {}", safe_param_name, rust_type)?;
        }

        // Handle output parameters.
        let output_count = method.outputs().count();
        let output = if output_count == 0 {
            "()".to_string()
        } else {
            // Always use the generated output struct for any outputs.
            // Varlink output parameters are always named, so we need a struct even for single
            // outputs.
            let struct_name = format!("{}Output", method.name().to_pascal_case());
            // Add lifetime parameter if the struct needs one
            if output_needs_lifetime(method, flags) {
                format!("{}<'_>", struct_name)
            } else {
                struct_name
            }
        };
        let reply = format!("Result<{}, {}>", output, error_type);

        let calls = flags.calls();
        for &call in &calls {
            // The regular method, or the only one there is, keeps the plain name. The others get
            // the name of their flag as a suffix and are renamed back to the Varlink method.
            let renamed = if calls.len() > 1 { call } else { None };

            // Add method comments.
            for doc in &docs {
                self.writeln(&format!("/// {}", doc))?;
            }
            if let Some(flag) = renamed {
                if !docs.is_empty() {
                    self.writeln("///")?;
                }
                self.writeln(&format!("/// {}", flag.doc()))?;
            }

            let name = match renamed {
                Some(flag) => format!("{}_{}", method_name, flag.name()),
                None => method_name.clone(),
            };
            let safe_name = rust_ident(&name);

            // Tell the proxy macro about the flag, and about the Varlink method unless the macro
            // derives its name from the identifier (without the `r#`) by itself.
            let mut attrs = Vec::new();
            if let Some(flag) = call {
                attrs.push(flag.name().to_string());
            }
            if snake_case_to_pascal_case(unraw(&safe_name)) != method.name().as_str() {
                attrs.push(format!("rename = \"{}\"", method.name()));
            }
            if !attrs.is_empty() {
                self.writeln(&format!("#[zlink({})]", attrs.join(", ")))?;
            }

            // Generate method signature.
            let return_type = if call == Some(CallFlag::More) {
                // The method returns a stream of the replies.
                format!(
                    "zlink::Result<impl zlink::futures_util::Stream<Item = zlink::Result<{}>>>",
                    reply
                )
            } else {
                format!("zlink::Result<{}>", reply)
            };
            self.writeln(&format!(
                "async fn {}(&mut self{}) -> {};",
                safe_name, params, return_type
            ))?;
        }

        Ok(())
    }

    fn generate_error_field(&mut self, field: &Field<'_>) -> Result<()> {
        // Add field comments.
        for comment in field.comments() {
            self.writeln(&format!("/// {}", comment.text()))?;
        }

        let field_name = field.name().to_snake_case();
        let rust_type = self.type_to_rust(field.ty())?;

        // Rename the field unless its identifier is spelled like its name. A raw identifier isn't,
        // although the `ReplyError` derive strips the `r#`.
        let safe_field_name = rust_ident(&field_name);
        let field_name_attr = if safe_field_name != field.name().as_str() {
            format!("#[zlink(rename = \"{}\")]", field.name())
        } else {
            String::new()
        };

        if !field_name_attr.is_empty() {
            self.writeln(&field_name_attr)?;
        }

        self.writeln(&format!("{}: {},", safe_field_name, rust_type))?;

        Ok(())
    }

    fn type_to_rust(&self, ty: &Type) -> Result<String> {
        type_to_rust(ty)
    }

    fn type_to_rust_param(&self, ty: &Type) -> Result<String> {
        type_to_rust_param(ty)
    }

    fn type_to_rust_output(&self, ty: &Type) -> Result<String> {
        type_to_rust_output(ty)
    }

    fn writeln(&mut self, s: &str) -> Result<()> {
        self.write(s)?;
        writeln!(&mut self.output)?;
        Ok(())
    }

    fn write(&mut self, s: &str) -> Result<()> {
        for _ in 0..self.indent_level {
            write!(&mut self.output, "    ")?;
        }
        write!(&mut self.output, "{}", s)?;
        Ok(())
    }

    fn indent(&mut self) {
        self.indent_level += 1;
    }

    fn dedent(&mut self) {
        if self.indent_level > 0 {
            self.indent_level -= 1;
        }
    }
}

impl Default for CodeGenerator {
    fn default() -> Self {
        Self::new()
    }
}

/// Whether the output struct of the `method` has a lifetime, for its fields to borrow from the
/// connection.
fn output_needs_lifetime(method: &Method<'_>, flags: MethodFlags) -> bool {
    // The outputs of the methods taking flags are owned: the replies of a stream must be, and the
    // caller of an upgrade takes the connection apart right after the reply, which a reply
    // borrowing from the connection would prevent.
    !flags.is_flagged() && method.outputs().any(|o| type_needs_lifetime(o.ty()))
}

/// The flags that a method supports or requires.
///
/// The IDL can't express these, so systemd marks its methods with comments right before them.
#[derive(Clone, Copy, Default)]
struct MethodFlags {
    more: FlagSupport,
    upgrade: FlagSupport,
}

impl MethodFlags {
    /// Parse the flags of the `method` from its comments.
    ///
    /// Along with the flags, this gives the texts of the other comments: the ones that document the
    /// method.
    fn parse<'a>(method: &Method<'a>) -> (Self, Vec<&'a str>) {
        let mut flags = Self::default();
        let mut docs = Vec::new();

        for comment in method.comments() {
            match comment.text().trim() {
                MORE_SUPPORTED => flags.more = FlagSupport::Supported,
                MORE_REQUIRED => flags.more = FlagSupport::Required,
                UPGRADE_SUPPORTED => flags.upgrade = FlagSupport::Supported,
                UPGRADE_REQUIRED => flags.upgrade = FlagSupport::Required,
                _ => docs.push(comment.text()),
            }
        }

        (flags, docs)
    }

    /// Whether the method supports or requires any flag.
    fn is_flagged(self) -> bool {
        self.more != FlagSupport::Unsupported || self.upgrade != FlagSupport::Unsupported
    }

    /// The flags that the calls of the method carry, `None` being a call without any.
    ///
    /// Each of these gets a proxy method.
    fn calls(self) -> Vec<Option<CallFlag>> {
        let mut calls = Vec::new();

        // A method that requires a flag can't be called without it.
        if self.more != FlagSupport::Required && self.upgrade != FlagSupport::Required {
            calls.push(None);
        }
        if self.more != FlagSupport::Unsupported {
            calls.push(Some(CallFlag::More));
        }
        if self.upgrade != FlagSupport::Unsupported {
            calls.push(Some(CallFlag::Upgrade));
        }

        calls
    }
}

/// How a method makes use of a flag.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum FlagSupport {
    /// The method doesn't take the flag.
    #[default]
    Unsupported,
    /// The method can be called with or without the flag.
    Supported,
    /// The method can only be called with the flag.
    Required,
}

/// A flag that a call can carry.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CallFlag {
    /// The call gets a stream of replies.
    More,
    /// The reply to the call upgrades the connection.
    Upgrade,
}

impl CallFlag {
    /// The name of the flag, as the `zlink` attribute has it.
    fn name(self) -> &'static str {
        match self {
            Self::More => "more",
            Self::Upgrade => "upgrade",
        }
    }

    /// The doc line of the proxy method that sets the flag, to tell it from the other ones.
    fn doc(self) -> &'static str {
        match self {
            Self::More => "Calls the method with the `more` flag, streaming its replies.",
            Self::Upgrade => {
                "Calls the method with the `upgrade` flag, so a successful reply upgrades the \
                 connection."
            }
        }
    }
}

// The comments that mark the flags of a method, as systemd does.
const MORE_SUPPORTED: &str = "[Supports 'more' flag]";
const MORE_REQUIRED: &str = "[Requires 'more' flag]";
const UPGRADE_SUPPORTED: &str = "[Supports 'upgrade' flag]";
const UPGRADE_REQUIRED: &str = "[Requires 'upgrade' flag]";

fn type_to_rust(ty: &Type) -> Result<String> {
    Ok(match ty {
        Type::Bool => "bool".to_string(),
        Type::Int => "i64".to_string(),
        Type::Float => "f64".to_string(),
        Type::String => "String".to_string(),
        Type::Object(_fields) => {
            // Anonymous struct - generate inline.
            // For now, use serde_json::Value for anonymous objects.
            // In the future, we could generate anonymous structs.
            "serde_json::Value".to_string()
        }
        Type::Enum(_variants) => {
            // Anonymous enum - use String for now.
            "String".to_string()
        }
        Type::Array(elem_type) => {
            let elem_rust = type_to_rust(elem_type.inner())?;
            format!("Vec<{}>", elem_rust)
        }
        Type::Map(value_type) => {
            let value_rust = type_to_rust(value_type.inner())?;
            format!("std::collections::HashMap<String, {}>", value_rust)
        }
        Type::ForeignObject => "serde_json::Value".to_string(),
        Type::Optional(inner_type) => {
            let inner_rust = type_to_rust(inner_type.inner())?;
            format!("Option<{}>", inner_rust)
        }
        Type::Custom(name) => custom_type_name(name),
        Type::Any => "serde_json::Value".to_string(),
    })
}

fn type_to_rust_param(ty: &Type) -> Result<String> {
    Ok(match ty {
        Type::Bool => "bool".to_string(),
        Type::Int => "i64".to_string(),
        Type::Float => "f64".to_string(),
        Type::String => "&str".to_string(),
        Type::Object(_fields) => {
            // For parameters, use reference to avoid clone
            "&serde_json::Value".to_string()
        }
        Type::Enum(_variants) => {
            // Anonymous enum - use &str for parameters
            "&str".to_string()
        }
        Type::Array(elem_type) => {
            // Use slice for array parameters with proper string handling
            let elem_rust = type_to_rust_param_elem(elem_type.inner())?;
            format!("&[{}]", elem_rust)
        }
        Type::Map(value_type) => {
            // Use reference for map parameters with proper string handling
            let value_rust = type_to_rust_param_elem(value_type.inner())?;
            format!("&std::collections::HashMap<&str, {}>", value_rust)
        }
        Type::ForeignObject => "&serde_json::Value".to_string(),
        Type::Optional(inner_type) => {
            let inner_rust = type_to_rust_param(inner_type.inner())?;
            // For optional parameters, always wrap in Option
            format!("Option<{}>", inner_rust)
        }
        Type::Custom(name) => format!("&{}", custom_type_name(name)),
        Type::Any => "&serde_json::Value".to_string(),
    })
}

// Helper function to get the proper type for collection elements in parameters.
// Ensures strings always use &str instead of String.
fn type_to_rust_param_elem(ty: &Type) -> Result<String> {
    Ok(match ty {
        Type::Bool => "bool".to_string(),
        Type::Int => "i64".to_string(),
        Type::Float => "f64".to_string(),
        Type::String => "&str".to_string(),
        Type::Object(_fields) => "serde_json::Value".to_string(),
        Type::Enum(_variants) => "&str".to_string(),
        Type::Array(elem_type) => {
            let elem_rust = type_to_rust_param_elem(elem_type.inner())?;
            format!("Vec<{}>", elem_rust)
        }
        Type::Map(value_type) => {
            let value_rust = type_to_rust_param_elem(value_type.inner())?;
            format!("std::collections::HashMap<&str, {}>", value_rust)
        }
        Type::ForeignObject => "serde_json::Value".to_string(),
        Type::Any => "serde_json::Value".to_string(),
        Type::Optional(inner_type) => {
            let inner_rust = type_to_rust_param_elem(inner_type.inner())?;
            format!("Option<{}>", inner_rust)
        }
        Type::Custom(name) => custom_type_name(name),
    })
}

fn type_to_rust_output(ty: &Type) -> Result<String> {
    Ok(match ty {
        Type::Bool => "bool".to_string(),
        Type::Int => "i64".to_string(),
        Type::Float => "f64".to_string(),
        Type::String => "&'a str".to_string(),
        Type::Object(_fields) => {
            // Use owned type for objects - serde can't deserialize to &Value
            "serde_json::Value".to_string()
        }
        Type::Enum(_variants) => {
            // Anonymous enum - use &str for outputs
            "&'a str".to_string()
        }
        Type::Array(elem_type) => {
            // Use Vec for array outputs with owned inner types (except strings stay as &'a str)
            let elem_rust = match elem_type.inner() {
                Type::String => "&'a str".to_string(),
                Type::Enum(_) => "&'a str".to_string(),
                _ => type_to_rust(elem_type.inner())?,
            };
            format!("Vec<{}>", elem_rust)
        }
        Type::Map(value_type) => {
            // Use HashMap for map outputs with borrowed types for efficiency
            let value_rust = match value_type.inner() {
                Type::String => "&'a str".to_string(),
                Type::Enum(_) => "&'a str".to_string(),
                _ => type_to_rust(value_type.inner())?,
            };
            format!("std::collections::HashMap<&'a str, {}>", value_rust)
        }
        Type::ForeignObject => "serde_json::Value".to_string(),
        Type::Any => "serde_json::Value".to_string(),
        Type::Optional(inner_type) => {
            // For optional outputs, recursively apply type_to_rust_output to maintain
            // correct reference types for strings within collections
            let inner_rust = type_to_rust_output(inner_type.inner())?;
            format!("Option<{}>", inner_rust)
        }
        Type::Custom(name) => custom_type_name(name),
    })
}

/// The Rust name of the custom type `name`.
///
/// The definition of the type and every reference to it get the name from here, so they agree.
fn custom_type_name(name: &str) -> String {
    rust_ident(&name.to_pascal_case())
}

fn interface_name_to_rust(name: &str) -> String {
    // Convert interface name like "org.example.Interface" to "Interface".
    name.split('.').next_back().unwrap_or(name).to_pascal_case()
}

fn type_needs_lifetime(ty: &Type) -> bool {
    match ty {
        Type::String => true,
        Type::Enum(_) => true, // Anonymous enums use &'a str
        Type::Array(inner) => type_needs_lifetime(inner.inner()),
        Type::Map(_) => {
            // Maps always need lifetime because keys are &'a str
            true
        }
        Type::Optional(inner) => type_needs_lifetime(inner.inner()),
        _ => false,
    }
}

fn type_needs_borrow(ty: &Type) -> bool {
    match ty {
        Type::String => true,
        Type::Enum(_) => true, // Anonymous enums use &'a str
        Type::Array(inner) => type_needs_borrow(inner.inner()),
        Type::Map(_) => {
            // Maps always need borrow because keys are &'a str
            true
        }
        Type::Optional(inner) => type_needs_borrow(inner.inner()),
        _ => false,
    }
}

/// Convert snake_case to PascalCase, the way the `proxy` macro does to name the Varlink method of a
/// proxy method that has no `#[zlink(rename)]`.
///
/// This is a copy of `snake_case_to_pascal_case` in `zlink-macros/src/proxy/utils.rs`, with which
/// it has to agree. The integration tests call the methods through the real macro, so they notice
/// if it doesn't.
fn snake_case_to_pascal_case(input: &str) -> String {
    input
        .split('_')
        .map(|word| {
            let mut chars = word.chars();
            let Some(first) = chars.next() else {
                return String::new();
            };
            first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
        })
        .collect()
}

/// The value that serde makes of a variant, for an enum with `#[serde(rename_all = "snake_case")]`.
///
/// This is `RenameRule::SnakeCase` of `serde_derive` (in `src/internals/case.rs`): an underscore
/// goes before each uppercase character but the first one, and all the characters are lowercased.
fn serde_snake_case(variant: &str) -> String {
    let mut snake = String::new();
    for (i, ch) in variant.char_indices() {
        if i > 0 && ch.is_uppercase() {
            snake.push('_');
        }
        snake.push(ch.to_ascii_lowercase());
    }
    snake
}

/// The identifier for the `name`, which is in Rust case already: snake_case for fields, parameters
/// and methods, PascalCase for types and variants.
///
/// A keyword becomes a raw identifier (`r#type`), except for `self`, `Self`, `super` and `crate`,
/// which can't be raw: those get a trailing underscore (`self_`), as rustc suggests. That can't
/// clash with the identifier of another name: Varlink names can't end with an underscore, and
/// converting them to Rust case doesn't add one.
fn rust_ident(name: &str) -> String {
    match name {
        "self" | "Self" | "super" | "crate" => format!("{}_", name),
        _ if is_rust_keyword(name) => format!("r#{}", name),
        _ => name.to_string(),
    }
}

/// The `ident` without the `r#` of a raw identifier, which isn't part of its name.
fn unraw(ident: &str) -> &str {
    ident.strip_prefix("r#").unwrap_or(ident)
}

/// Whether `s` is a keyword of Rust: one that's in use, or one that's reserved for later.
fn is_rust_keyword(s: &str) -> bool {
    [
        "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
        "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move",
        "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait",
        "true", "type", "unsafe", "use", "where", "while",
        // The reserved ones. Some are keywords in the later editions only, but raw identifiers
        // work in all of them.
        "abstract", "become", "box", "do", "final", "gen", "macro", "override", "priv", "try",
        "typeof", "unsized", "virtual", "yield",
    ]
    .contains(&s)
}