zlink-codegen 0.8.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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
use zlink::idl::Interface;
use zlink_codegen::generate_interface;

#[test]
fn test_simple_interface() {
    let idl = r#"
# Simple Ping interface
interface org.example.ping

method Ping(message: string) -> (reply: string)
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check that the generated code contains expected elements.
    assert!(code.contains("#[proxy(\"org.example.ping\")]"));
    assert!(code.contains("pub trait Ping"));
    assert!(code.contains("async fn ping"));
    // Check that string parameters use references
    assert!(code.contains("message: &str"));
}

#[test]
fn test_interface_with_types() {
    let idl = r#"
interface org.example.types

type Person (
    name: string,
    age: int,
    email: ?string
)

type Status (idle, busy, away)

method GetPerson(id: int) -> (person: Person)
method SetStatus(status: Status) -> ()
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check that custom types are generated.
    assert!(code.contains("pub struct Person"));
    assert!(code.contains("pub name: String"));
    assert!(code.contains("pub age: i64"));
    assert!(code.contains("pub email: Option<String>"));

    assert!(code.contains("pub enum Status"));
    assert!(code.contains("Idle,"));
    assert!(code.contains("Busy,"));
    assert!(code.contains("Away,"));
}

#[test]
fn test_interface_with_errors() {
    let idl = r#"
interface org.example.errors

error NotFound(id: int)
error InvalidInput(message: string)

method Get(id: int) -> (value: string)
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check that errors are generated.
    assert!(code.contains("#[derive(Debug, Clone, PartialEq, ReplyError)]"));
    assert!(code.contains("#[zlink(interface = \"org.example.errors\")]"));
    assert!(code.contains("pub enum ErrorsError"));
    assert!(code.contains("NotFound"));
    assert!(code.contains("InvalidInput"));
}

#[test]
fn test_interface_with_arrays_and_dicts() {
    let idl = r#"
interface org.example.collections

method ListItems() -> (items: []string)
method GetConfig() -> (config: [string]string)
method ProcessData(numbers: []int) -> (results: [string]int)
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check that arrays and dicts are handled in output structs.
    // Output structs use references for strings for efficiency.
    assert!(code.contains("Vec<&'a str>"));
    assert!(code.contains("std::collections::HashMap<&'a str, &'a str>"));
    assert!(code.contains("std::collections::HashMap<&'a str, i64>"));

    // Check that parameters use references
    assert!(code.contains("numbers: &[i64]"));
}

#[test]
fn test_interface_with_optional_fields() {
    let idl = r#"
interface org.example.optional

type Config (
    name: string,
    value: ?string,
    enabled: ?bool
)

method GetConfig() -> (config: ?Config)
method SetConfig(config: ?Config) -> ()
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check that optional fields are handled.
    assert!(code.contains("pub value: Option<String>"));
    assert!(code.contains("pub enabled: Option<bool>"));
    assert!(code.contains("Option<Config>"));

    // Check that optional parameters are handled with references
    assert!(code.contains("config: Option<&Config>"));
}

#[test]
fn test_interface_with_multiple_outputs() {
    let idl = r#"
interface org.example.multi

method GetStats() -> (
    total: int,
    average: float,
    min: int,
    max: int
)
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check that multiple outputs create a struct (no lifetime needed for primitives)
    assert!(code.contains("pub struct GetStatsOutput"));
    assert!(code.contains("pub total: i64"));
    assert!(code.contains("pub average: f64"));
    assert!(code.contains("pub min: i64"));
    assert!(code.contains("pub max: i64"));
}

#[test]
fn test_org_varlink_service() {
    let idl = r#"
# The Varlink Service Interface is provided by every varlink service. It
# describes the service and the interfaces it implements.
interface org.varlink.service

# Get a list of all the interfaces a service provides and information
# about the service implementation.
method GetInfo() -> (
    vendor: string,
    product: string,
    version: string,
    url: string,
    interfaces: []string
)

# Get the description of an interface that is implemented by this service.
method GetInterfaceDescription(interface: string) -> (description: string)

# The requested interface was not found.
error InterfaceNotFound (interface: string)

# The requested method was not found
error MethodNotFound (method: string)

# The interface defines the requested method, but the service does not
# implement it.
error MethodNotImplemented (method: string)

# One of the passed parameters is invalid.
error InvalidParameter (parameter: string)
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check the generated code contains the expected elements.
    assert!(code.contains("#[proxy(\"org.varlink.service\")]"));
    assert!(code.contains("pub trait Service"));
    assert!(code.contains("async fn get_info"));
    assert!(code.contains("async fn get_interface_description"));
    assert!(code.contains("#[derive(Debug, Clone, PartialEq, ReplyError)]"));
    assert!(code.contains("#[zlink(interface = \"org.varlink.service\")]"));
    assert!(code.contains("pub enum ServiceError"));
    assert!(code.contains("InterfaceNotFound"));
    assert!(code.contains("MethodNotFound"));
    assert!(code.contains("MethodNotImplemented"));
    assert!(code.contains("InvalidParameter"));

    // Check that string parameters use references
    assert!(code.contains("interface: &str"));

    // Check that GetInfo creates an output struct for multiple outputs with lifetime
    assert!(code.contains("pub struct GetInfoOutput<'a>"));
    assert!(code.contains("pub vendor: &'a str"));
    assert!(code.contains("pub product: &'a str"));
    assert!(code.contains("pub version: &'a str"));
    assert!(code.contains("pub url: &'a str"));
    assert!(code.contains("pub interfaces: Vec<&'a str>"));
}

#[test]
fn test_reference_types_in_proxy() {
    let idl = r#"
interface org.example.refs

type CustomData (
    field1: string,
    field2: int
)

method SendString(text: string) -> ()
method SendArray(items: []string) -> ()
method SendMap(data: [string]int) -> ()
method SendCustom(data: CustomData) -> ()
method SendOptional(text: ?string, data: ?CustomData) -> ()
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check that all parameters use appropriate reference types
    assert!(code.contains("text: &str"));
    assert!(code.contains("items: &[&str]"));
    assert!(code.contains("data: &std::collections::HashMap<&str, i64>"));
    assert!(code.contains("data: &CustomData"));
    assert!(code.contains("text: Option<&str>"));
    assert!(code.contains("data: Option<&CustomData>"));
}

#[test]
fn test_camelcase_rename_attributes() {
    // Read the IDL file from the integration test to avoid duplication.
    let idl_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("test-integration")
        .join("camelcase.idl");
    let idl = std::fs::read_to_string(idl_path).expect("Failed to read camelcase.idl");

    let interface = Interface::try_from(idl.as_str()).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Verify method parameters have #[zlink(rename)] attributes.
    assert!(code.contains(r#"#[zlink(rename = "userId")] user_id: i64"#));
    assert!(code.contains(r#"#[zlink(rename = "includeEmail")] include_email: Option<bool>"#));

    // Verify struct fields have #[serde(rename)] attributes.
    assert!(code.contains(r#"#[serde(rename = "userName")]"#));
    assert!(code.contains("pub user_name: String"));
    assert!(code.contains(r#"#[serde(rename = "emailAddress")]"#));
    assert!(code.contains("pub email_address: Option<String>"));

    // Verify output struct fields have #[serde(rename)] attributes.
    assert!(code.contains(r#"#[serde(rename = "userData")]"#));
    assert!(code.contains("pub user_data: UserData"));
    assert!(code.contains(r#"#[serde(rename = "lastLogin")]"#));
    assert!(code.contains("pub last_login: &'a str"));

    // Verify error fields have #[zlink(rename)] attributes (not #[serde(rename)]).
    assert!(code.contains("UserNotFound {"));
    assert!(code.contains(r#"#[zlink(rename = "userId")]"#));
    assert!(code.contains("user_id: i64"));
}

#[test]
fn test_interface_with_any_type() {
    let idl = r#"
interface org.example.anytype

type Config (
    name: string,
    metadata: any,
    extra: ?any,
    items: []any,
    tags: [string]any
)

method SetConfig(data: any) -> (result: any)
method GetData() -> (items: []any, map: [string]any)
"#;

    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Check struct fields use serde_json::Value for any type.
    assert!(code.contains("pub metadata: serde_json::Value"));
    assert!(code.contains("pub extra: Option<serde_json::Value>"));
    assert!(code.contains("pub items: Vec<serde_json::Value>"));
    assert!(code.contains("pub tags: std::collections::HashMap<String, serde_json::Value>"));

    // Check method input parameters use references.
    assert!(code.contains("data: &serde_json::Value"));

    // Check single output returns serde_json::Value.
    assert!(code.contains("serde_json::Value"));

    // Check GetData output struct contains array and map of any.
    assert!(code.contains("Vec<serde_json::Value>"));
    assert!(code.contains("std::collections::HashMap<"));
}

#[test]
fn flags_proxy_methods() {
    let code = flags_code();

    // The method supports the `more` flag: besides the regular method, there's a streaming one.
    assert_contains(
        &code,
        concat!(
            "    /// Lists the items.\n",
            "    async fn list(&mut self) -> zlink::Result<Result<ListOutput, FlagsError>>;\n",
            "    /// Lists the items.\n",
            "    ///\n",
            "    /// Calls the method with the `more` flag, streaming its replies.\n",
            "    #[zlink(more, rename = \"List\")]\n",
            "    async fn list_more(&mut self) -> zlink::Result<impl zlink::futures_util::Stream<",
            "Item = zlink::Result<Result<ListOutput, FlagsError>>>>;\n",
        ),
    );

    // The method requires the `more` flag: there's only a streaming method, with the plain name.
    assert_contains(
        &code,
        concat!(
            "    /// Watches the items for changes.\n",
            "    #[zlink(more)]\n",
            "    async fn watch(&mut self) -> zlink::Result<impl zlink::futures_util::Stream<",
            "Item = zlink::Result<Result<WatchOutput, FlagsError>>>>;\n",
        ),
    );

    // The method requires the `upgrade` flag: there's only a method for that, with the plain name.
    assert_contains(
        &code,
        concat!(
            "    /// Downloads an item over the upgraded connection.\n",
            "    #[zlink(upgrade)]\n",
            "    async fn download(&mut self, name: &str) -> ",
            "zlink::Result<Result<DownloadOutput, FlagsError>>;\n",
        ),
    );

    // The method supports the `upgrade` flag: besides the regular method, there's one for that.
    assert_contains(
        &code,
        concat!(
            "    /// Gets an item, or downloads it over the upgraded connection.\n",
            "    async fn fetch(&mut self, name: &str) -> ",
            "zlink::Result<Result<FetchOutput, FlagsError>>;\n",
            "    /// Gets an item, or downloads it over the upgraded connection.\n",
            "    ///\n",
            "    /// Calls the method with the `upgrade` flag, so a successful reply upgrades the ",
            "connection.\n",
            "    #[zlink(upgrade, rename = \"Fetch\")]\n",
            "    async fn fetch_upgrade(&mut self, name: &str) -> ",
            "zlink::Result<Result<FetchOutput, FlagsError>>;\n",
        ),
    );

    // The method without flags is as it always was.
    assert_contains(
        &code,
        concat!(
            "    /// Pings the service.\n",
            "    async fn ping(&mut self) -> zlink::Result<Result<(), FlagsError>>;\n",
        ),
    );

    // There are no other methods.
    assert_eq!(code.matches("async fn ").count(), 7);
}

#[test]
fn flags_owned_outputs() {
    // The replies to the calls with flags can't borrow from the connection.
    let code = flags_code();
    assert_contains(&code, "pub struct ListOutput {\n    pub item: Item,\n}");
    assert_contains(
        &code,
        "pub struct WatchOutput {\n    pub name: String,\n    pub removed: bool,\n}",
    );
    assert_contains(
        &code,
        "pub struct DownloadOutput {\n    pub size: i64,\n    pub checksum: String,\n}",
    );
    assert!(!code.contains("'a"));
    assert!(!code.contains("'_"));
    assert!(!code.contains("serde(borrow)"));

    // The replies to the calls without flags still borrow, in the same interface.
    let idl = r#"
interface org.example.mixed

# [Requires 'more' flag]
method Watch() -> (name: string)

# [Supports 'upgrade' flag]
method Fetch() -> (names: []string, kinds: [string]string)

method Name() -> (name: string)
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    assert_contains(&code, "pub struct WatchOutput {\n    pub name: String,\n}");
    assert_contains(
        &code,
        concat!(
            "pub struct FetchOutput {\n",
            "    pub names: Vec<String>,\n",
            "    pub kinds: std::collections::HashMap<String, String>,\n",
            "}",
        ),
    );
    assert_contains(
        &code,
        "pub struct NameOutput<'a> {\n    #[serde(borrow)]\n    pub name: &'a str,\n}",
    );
    // The signatures agree with the structs.
    assert_contains(
        &code,
        "Item = zlink::Result<Result<WatchOutput, MixedError>>>>;",
    );
    assert_contains(
        &code,
        "async fn fetch(&mut self) -> zlink::Result<Result<FetchOutput, MixedError>>;",
    );
    assert_contains(
        &code,
        "async fn fetch_upgrade(&mut self) -> zlink::Result<Result<FetchOutput, MixedError>>;",
    );
    assert_contains(
        &code,
        "async fn name(&mut self) -> zlink::Result<Result<NameOutput<'_>, MixedError>>;",
    );
}

#[test]
fn flags_comments_are_not_docs() {
    // None of the comments that mark the flags is left in the generated code.
    let code = flags_code();
    for comment in [
        "[Supports 'more' flag]",
        "[Requires 'more' flag]",
        "[Supports 'upgrade' flag]",
        "[Requires 'upgrade' flag]",
    ] {
        assert!(!code.contains(comment), "`{comment}` found in:\n{code}");
    }

    // The other comments stay, in order, including the ones that merely look like the marking
    // ones. The marking ones are matched trimmed, so the trailing tab doesn't matter.
    let idl = concat!(
        "interface org.example.docs\n",
        "\n",
        "# Opens the file.\n",
        "# [Supports 'more' flag]\t\n",
        "# It stays open until it's closed.\n",
        "method Open() -> ()\n",
        "\n",
        "# [supports 'more' flag]\n",
        "# [Supports 'more' flags]\n",
        "# Supports 'more' flag\n",
        "method Close() -> ()\n",
    );
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    assert_contains(
        &code,
        concat!(
            "    /// Opens the file.\n",
            "    /// It stays open until it's closed.\n",
            "    async fn open(&mut self) -> zlink::Result<Result<(), DocsError>>;\n",
            "    /// Opens the file.\n",
            "    /// It stays open until it's closed.\n",
            "    ///\n",
            "    /// Calls the method with the `more` flag, streaming its replies.\n",
            "    #[zlink(more, rename = \"Open\")]\n",
            "    async fn open_more(&mut self) -> zlink::Result<impl zlink::futures_util::Stream<",
            "Item = zlink::Result<Result<(), DocsError>>>>;\n",
        ),
    );
    assert_contains(
        &code,
        concat!(
            "    /// [supports 'more' flag]\n",
            "    /// [Supports 'more' flags]\n",
            "    /// Supports 'more' flag\n",
            "    async fn close(&mut self) -> zlink::Result<Result<(), DocsError>>;\n",
        ),
    );
    assert_eq!(code.matches("async fn ").count(), 3);
}

#[test]
fn flags_proxy_method_names() {
    let idl = r#"
interface org.example.names

# [Supports 'more' flag]
# [Supports 'upgrade' flag]
method Open(path: string) -> (fd: int)

# [Requires 'more' flag]
# [Requires 'upgrade' flag]
method Tunnel() -> ()

# [Supports 'more' flag]
method Type() -> ()
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // Both flags are supported: the regular method is followed by the one for each flag.
    assert_contains(
        &code,
        concat!(
            "    async fn open(&mut self, path: &str) -> ",
            "zlink::Result<Result<OpenOutput, NamesError>>;\n",
            "    /// Calls the method with the `more` flag, streaming its replies.\n",
            "    #[zlink(more, rename = \"Open\")]\n",
            "    async fn open_more(&mut self, path: &str) -> ",
            "zlink::Result<impl zlink::futures_util::Stream<",
            "Item = zlink::Result<Result<OpenOutput, NamesError>>>>;\n",
            "    /// Calls the method with the `upgrade` flag, so a successful reply upgrades the ",
            "connection.\n",
            "    #[zlink(upgrade, rename = \"Open\")]\n",
            "    async fn open_upgrade(&mut self, path: &str) -> ",
            "zlink::Result<Result<OpenOutput, NamesError>>;\n",
        ),
    );

    // Both flags are required: there's no regular method, and none has the plain name.
    assert_contains(
        &code,
        concat!(
            "    /// Calls the method with the `more` flag, streaming its replies.\n",
            "    #[zlink(more, rename = \"Tunnel\")]\n",
            "    async fn tunnel_more(&mut self) -> ",
            "zlink::Result<impl zlink::futures_util::Stream<",
            "Item = zlink::Result<Result<(), NamesError>>>>;\n",
            "    /// Calls the method with the `upgrade` flag, so a successful reply upgrades the ",
            "connection.\n",
            "    #[zlink(upgrade, rename = \"Tunnel\")]\n",
            "    async fn tunnel_upgrade(&mut self) -> zlink::Result<Result<(), NamesError>>;\n",
        ),
    );
    assert!(!code.contains("fn tunnel("));

    // The names that are Rust keywords are only escaped if they're not suffixed.
    assert_contains(
        &code,
        "    async fn r#type(&mut self) -> zlink::Result<Result<(), NamesError>>;\n",
    );
    assert_contains(
        &code,
        "    #[zlink(more, rename = \"Type\")]\n    async fn type_more(&mut self)",
    );
}

#[test]
fn keyword_struct_fields() {
    let code = names_code();

    // The keywords that can be raw identifiers are, and the ones that can't be get an underscore.
    // The fields keep their names on the wire either way.
    assert_contains(
        &code,
        concat!(
            "pub struct Node {\n",
            "    #[serde(rename = \"self\")]\n",
            "    pub self_: String,\n",
            "    #[serde(rename = \"crate\")]\n",
            "    pub crate_: i64,\n",
            "    #[serde(rename = \"super\")]\n",
            "    pub super_: Option<String>,\n",
            "    #[serde(rename = \"type\")]\n",
            "    pub r#type: String,\n",
            "    #[serde(rename = \"try\")]\n",
            "    pub r#try: bool,\n",
            "    #[serde(rename = \"gen\")]\n",
            "    pub r#gen: Option<String>,\n",
            "}\n",
        ),
    );
}

#[test]
fn keyword_params_and_outputs() {
    let code = names_code();

    // The parameters are renamed back, the raw identifiers as well as the ones with an underscore.
    assert_contains(
        &code,
        concat!(
            "async fn get_uuid(&mut self, #[zlink(rename = \"self\")] self_: &str, ",
            "#[zlink(rename = \"crate\")] crate_: i64) -> ",
            "zlink::Result<Result<GetUuidOutput<'_>, NamesError>>;\n",
        ),
    );

    // The same goes for the outputs, except for the raw identifiers: serde strips their `r#`, so
    // they need no rename.
    assert_contains(
        &code,
        concat!(
            "pub struct GetUuidOutput<'a> {\n",
            "    #[serde(borrow)]\n",
            "    #[serde(rename = \"super\")]\n",
            "    pub super_: &'a str,\n",
            "}\n",
        ),
    );
    let idl = r#"
interface org.example.outputs

method Get() -> (type: string, super: int, try: bool)
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();
    assert_contains(
        &code,
        concat!(
            "pub struct GetOutput<'a> {\n",
            "    #[serde(borrow)]\n",
            "    pub r#type: &'a str,\n",
            "    #[serde(rename = \"super\")]\n",
            "    pub super_: i64,\n",
            "    pub r#try: bool,\n",
            "}\n",
        ),
    );
}

#[test]
fn keyword_error_fields() {
    let code = names_code();

    assert_contains(
        &code,
        concat!(
            "    HttpError {\n",
            "        #[zlink(rename = \"self\")]\n",
            "        self_: String,\n",
            "    },\n",
        ),
    );

    let idl = r#"
interface org.example.errors

error Failed(type: string, crate: int)
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();
    assert_contains(
        &code,
        concat!(
            "    Failed {\n",
            "        #[zlink(rename = \"type\")]\n",
            "        r#type: String,\n",
            "        #[zlink(rename = \"crate\")]\n",
            "        crate_: i64,\n",
            "    },\n",
        ),
    );
}

#[test]
fn keyword_method_names() {
    let code = names_code();
    assert_contains(
        &code,
        "    async fn self_(&mut self) -> zlink::Result<Result<(), NamesError>>;\n",
    );

    let idl = r#"
interface org.example.keywords

method Super() -> ()
method Crate() -> ()
method Type() -> ()
method Try() -> ()

# [Supports 'more' flag]
method Self() -> ()
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // The names are only made identifiers after the suffix of a flag is added to them.
    assert_contains(
        &code,
        concat!(
            "    async fn super_(&mut self) -> zlink::Result<Result<(), KeywordsError>>;\n",
            "    async fn crate_(&mut self) -> zlink::Result<Result<(), KeywordsError>>;\n",
            "    async fn r#type(&mut self) -> zlink::Result<Result<(), KeywordsError>>;\n",
            "    async fn r#try(&mut self) -> zlink::Result<Result<(), KeywordsError>>;\n",
            "    async fn self_(&mut self) -> zlink::Result<Result<(), KeywordsError>>;\n",
            "    /// Calls the method with the `more` flag, streaming its replies.\n",
            "    #[zlink(more, rename = \"Self\")]\n",
            "    async fn self_more(&mut self) -> ",
        ),
    );
}

#[test]
fn keyword_type_names() {
    let idl = r#"
interface org.example.keywords

type Self (value: int)

type Kind (Self, other)

error Self(self: string)

method Make(value: Self, values: []Self) -> (value: ?Self)
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // The definitions and the references to the type agree on its name.
    assert_contains(&code, "pub struct Self_ {\n    pub value: i64,\n}\n");
    assert_contains(
        &code,
        concat!(
            "async fn make(&mut self, value: &Self_, values: &[Self_]) -> ",
            "zlink::Result<Result<MakeOutput, KeywordsError>>;\n",
        ),
    );
    assert_contains(
        &code,
        "pub struct MakeOutput {\n    pub value: Option<Self_>,\n}\n",
    );

    // The variants are renamed back to the names that they have in the IDL.
    assert_contains(
        &code,
        concat!(
            "pub enum Kind {\n",
            "    #[serde(rename = \"Self\")]\n",
            "    Self_,\n",
            "    Other,\n",
            "}\n",
        ),
    );
    assert_contains(
        &code,
        concat!(
            "    #[zlink(rename = \"Self\")]\n",
            "    Self_ {\n",
            "        #[zlink(rename = \"self\")]\n",
            "        self_: String,\n",
            "    },\n",
        ),
    );
}

#[test]
fn keyword_trait_name() {
    let idl = r#"
interface org.example.Self

method Ping() -> ()
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    assert_contains(&code, "#[proxy(\"org.example.Self\")]\npub trait Self_ {\n");
    // The name of the error type is made of the name of the interface, not of the trait.
    assert_contains(&code, "pub enum SelfError {}\n");
    assert_contains(&code, "zlink::Result<Result<(), SelfError>>;\n");
}

#[test]
fn reserved_keywords() {
    let reserved = [
        "abstract", "become", "box", "do", "final", "gen", "macro", "override", "priv", "try",
        "typeof", "unsized", "virtual", "yield",
    ];
    // The contextual keywords are valid identifiers as they are.
    let contextual = ["union", "macro_rules", "safe", "raw"];
    let fields: Vec<_> = reserved
        .iter()
        .chain(&contextual)
        .map(|name| format!("{name}: int"))
        .collect();
    let idl = format!(
        "interface org.example.reserved\n\ntype Names ({})\n",
        fields.join(", ")
    );
    let interface = Interface::try_from(idl.as_str()).unwrap();
    let code = generate_interface(&interface).unwrap();

    for name in reserved {
        assert_contains(
            &code,
            &format!("    #[serde(rename = \"{name}\")]\n    pub r#{name}: i64,\n"),
        );
    }
    for name in contextual {
        assert_contains(&code, &format!("    pub {name}: i64,\n"));
    }
}

#[test]
fn method_names_that_map_back() {
    let code = names_code();

    // The proxy macro would make `GetUuid` of `get_uuid`, so it's told which method it is.
    assert_contains(
        &code,
        concat!(
            "    #[zlink(rename = \"GetUUID\")]\n",
            "    async fn get_uuid(&mut self, #[zlink(rename = \"self\")] self_: &str, ",
            "#[zlink(rename = \"crate\")] crate_: i64) -> ",
            "zlink::Result<Result<GetUuidOutput<'_>, NamesError>>;\n",
        ),
    );

    // It makes `Self` of `self_`, so there's nothing to tell.
    assert_contains(
        &code,
        concat!(
            "    /// A method that is named after a keyword.\n",
            "    async fn self_(&mut self) -> zlink::Result<Result<(), NamesError>>;\n",
        ),
    );

    // What matters is what the macro makes of the identifier, not what the name looks like.
    let idl = r#"
interface org.example.methods

method GetUuid() -> ()
method HTTPGet() -> ()
method IPv4Address() -> ()
method ListUUIDs() -> ()
method Get2Things() -> ()
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();
    assert_contains(
        &code,
        concat!(
            "    async fn get_uuid(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
            "    #[zlink(rename = \"HTTPGet\")]\n",
            "    async fn http_get(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
            "    async fn i_pv4_address(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
            "    #[zlink(rename = \"ListUUIDs\")]\n",
            "    async fn list_uui_ds(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
            "    async fn get2_things(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
        ),
    );
}

#[test]
fn method_names_of_keywords_in_other_case() {
    let idl = r#"
interface org.example.methods

method TYPE() -> ()
method SELF() -> ()
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // The macro makes `Type` and `Self` of `r#type` and `self_`, not `TYPE` and `SELF`.
    assert_contains(
        &code,
        concat!(
            "    #[zlink(rename = \"TYPE\")]\n",
            "    async fn r#type(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
            "    #[zlink(rename = \"SELF\")]\n",
            "    async fn self_(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
        ),
    );
}

#[test]
fn method_names_with_flags_that_map_back() {
    let idl = r#"
interface org.example.methods

# [Supports 'more' flag]
method GetUUID() -> ()

# [Requires 'upgrade' flag]
method OpenFD() -> ()
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();

    // The attribute of the method that is renamed back anyway has the flag too.
    assert_contains(
        &code,
        concat!(
            "    #[zlink(rename = \"GetUUID\")]\n",
            "    async fn get_uuid(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
            "    /// Calls the method with the `more` flag, streaming its replies.\n",
            "    #[zlink(more, rename = \"GetUUID\")]\n",
            "    async fn get_uuid_more(&mut self) -> ",
            "zlink::Result<impl zlink::futures_util::Stream<",
            "Item = zlink::Result<Result<(), MethodsError>>>>;\n",
            "    #[zlink(upgrade, rename = \"OpenFD\")]\n",
            "    async fn open_fd(&mut self) -> zlink::Result<Result<(), MethodsError>>;\n",
        ),
    );
}

#[test]
fn error_names_that_map_back() {
    let code = names_code();

    // The `ReplyError` derive would name the error `HttpError` after its variant, so it's told the
    // name.
    assert_contains(
        &code,
        concat!(
            "    #[zlink(rename = \"HTTPError\")]\n",
            "    HttpError {\n",
            "        #[zlink(rename = \"self\")]\n",
            "        self_: String,\n",
            "    },\n",
        ),
    );

    // Only the errors whose variants are named differently are told the names.
    let idl = r#"
interface org.example.errors

# Not found.
error NotFound()

# Bad UTF-8.
error InvalidUTF8(offset: int)
error IOError()
error HTTP2Error(code: int)
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();
    assert_contains(
        &code,
        concat!(
            "    /// Not found.\n",
            "    NotFound,\n",
            "    /// Bad UTF-8.\n",
            "    #[zlink(rename = \"InvalidUTF8\")]\n",
            "    InvalidUtf8 {\n",
            "        offset: i64,\n",
            "    },\n",
            "    #[zlink(rename = \"IOError\")]\n",
            "    IoError,\n",
            "    #[zlink(rename = \"HTTP2Error\")]\n",
            "    Http2Error {\n",
            "        code: i64,\n",
            "    },\n",
        ),
    );
}

#[test]
fn enum_values_that_map_back() {
    let code = names_code();

    // Serde would make `fast` and `http` of the variants `Fast` and `Http`, so it's told the
    // values. It makes `slow_down` of `SlowDown` already.
    assert_contains(
        &code,
        concat!(
            "#[serde(rename_all = \"snake_case\")]\n",
            "pub enum Mode {\n",
            "    #[serde(rename = \"Fast\")]\n",
            "    Fast,\n",
            "    SlowDown,\n",
            "    #[serde(rename = \"HTTP\")]\n",
            "    Http,\n",
            "}\n",
        ),
    );

    // What serde makes of the variants is what decides, not how the values look.
    let idl = r#"
interface org.example.enums

type Kind (
    foo,
    foo_bar,
    # The fast one.
    Fast,
    camelCase,
    x_1,
    a1,
    UPPER
)
"#;
    let interface = Interface::try_from(idl).unwrap();
    let code = generate_interface(&interface).unwrap();
    assert_contains(
        &code,
        concat!(
            "#[serde(rename_all = \"snake_case\")]\n",
            "pub enum Kind {\n",
            "    Foo,\n",
            "    FooBar,\n",
            "    /// The fast one.\n",
            "    #[serde(rename = \"Fast\")]\n",
            "    Fast,\n",
            "    #[serde(rename = \"camelCase\")]\n",
            "    CamelCase,\n",
            "    #[serde(rename = \"x_1\")]\n",
            "    X1,\n",
            "    A1,\n",
            "    #[serde(rename = \"UPPER\")]\n",
            "    Upper,\n",
            "}\n",
        ),
    );
}

/// Generate the code for the IDL of the integration test, whose methods have all kinds of flags.
fn flags_code() -> String {
    // Read the IDL file from the integration test to avoid duplication.
    let idl_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("test-integration")
        .join("flags.idl");
    let idl = std::fs::read_to_string(idl_path).expect("Failed to read flags.idl");

    let interface = Interface::try_from(idl.as_str()).unwrap();
    generate_interface(&interface).unwrap()
}

/// Generate the code for the IDL of the integration test, whose names need care.
fn names_code() -> String {
    // Read the IDL file from the integration test to avoid duplication.
    let idl_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("test-integration")
        .join("names.idl");
    let idl = std::fs::read_to_string(idl_path).expect("Failed to read names.idl");

    let interface = Interface::try_from(idl.as_str()).unwrap();
    generate_interface(&interface).unwrap()
}

/// Assert that the `code` contains the `expected` code.
#[track_caller]
fn assert_contains(code: &str, expected: &str) {
    assert!(
        code.contains(expected),
        "`{expected}` not found in:\n{code}"
    );
}