move-syn 0.0.8

Move syntax parsing
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
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
#![cfg_attr(nightly, feature(doc_cfg))]
#![expect(clippy::result_large_err, reason = "Error from the unsynn crate")]

//! Move syntax parsing using [`unsynn`](::unsynn).

use std::borrow::Cow;
use std::collections::HashMap;

pub use unsynn;
use unsynn::*;

mod functions;
#[cfg(test)]
mod tests;
mod vis;

#[cfg(feature = "fun-sig")]
pub use self::functions::FunctionArg;
pub use self::functions::{Function, NativeFun};
pub use self::vis::Visibility;

/// Process raw Move code so that it can be used as input to Rust's tokenizer.
///
/// Move's and Rust's tokens are very similar, with the exception of raw identifiers for which Move
/// uses the syntax "`ident`".
///
/// This function the backticks around identifiers, if found. Thus, we can re-use Rust's tokenizer
/// afterwards, implemented by the [`proc_macro2`] crate. This is relevant because
/// [`unsynn!`]-generated types requires Rust's [`TokenStream`] as input for parsing.
pub fn sanitize_for_tokenizer(content: &str) -> String {
    let regex = raw_ident_regex();
    let mut lines = content.lines().map(|line| {
        // Ignore commented or doc lines
        if !line.trim_start().starts_with("//") {
            regex.replace(line, "$1")
        } else {
            Cow::Borrowed(line)
        }
    });
    lines.next().map_or_else(String::new, |line| {
        let mut sanitized = String::with_capacity(content.len());
        sanitized.push_str(&line);
        for line in lines {
            sanitized.push('\n');
            sanitized.push_str(&line);
        }
        sanitized
    })
}

fn raw_ident_regex() -> regex::Regex {
    regex::Regex::new("`([[:alnum:]_]+)`").expect("Valid regex")
}

pub mod kw {
    //! Move keywords.
    use unsynn::*;

    unsynn! {
        pub keyword Struct = "struct";
        pub keyword Phantom = "phantom";
        pub keyword Public = "public";
        pub keyword Has = "has";
        pub keyword Copy = "copy";
        pub keyword Drop = "drop";
        pub keyword Key = "key";
        pub keyword Store = "store";
        pub keyword Module = "module";
        pub keyword Package = "package";
        pub keyword Friend = "friend";
        pub keyword Use = "use";
        pub keyword Fun = "fun";
        pub keyword As = "as";
        pub keyword Const = "const";
        pub keyword Mut = "mut";
        pub keyword Entry = "entry";
        pub keyword Native = "native";
        pub keyword Macro = "macro";
        pub keyword Vector = "vector";
        pub keyword Enum = "enum";
    }
}

unsynn! {
    pub enum File {
        /// A Move file in the 2024 recommended format.
        ModuleLabel(LabeledModule),
        /// A Move file in the legacy style.
        Legacy(Vec<Module>),
    }

    /// A single module defined with a top-level [label].
    ///
    /// [label]: https://move-book.com/guides/code-quality-checklist#using-module-label
    pub struct LabeledModule {
        attrs: Vec<Attributes>,
        keyword: kw::Module,
        named_address: Ident,
        path_sep: PathSep,
        ident: Ident,
        semicolon: Semicolon,
        contents: Vec<Item>,
    }

    /// A Move module declaration.
    pub struct Module {
        pub attrs: Vec<Attributes>,
        keyword: kw::Module,
        pub named_address: Ident,
        path_sep: PathSep,
        pub ident: Ident,
        contents: BraceGroupContaining<Vec<Item>>,
    }

    /// A Move language item.
    pub struct Item {
        pub attrs: Vec<Attributes>,
        vis: Option<Vis>,
        pub kind: ItemKind,
    }

    // === Attributes ===

    /// A Move [attributes] anottation.
    ///
    /// Examples: `#[test_only]`, `#[allow(...)]`, doc comment (`/// ...`).
    ///
    /// [attributes]: https://github.com/MystenLabs/sui/blob/129788902da4afc54a10af4ae45971a57ef080be/external-crates/move/crates/move-compiler/src/parser/syntax.rs#L1202-L1204
    #[derive(Clone)]
    pub struct Attributes {
        pound: Pound,
        contents: BracketGroupContaining<DelimitedVec<Attribute, Comma, TrailingDelimiter::Optional>>,
    }

    /// A single [attribute].
    ///
    /// Attribute =
    ///     "for"
    ///     | <Identifier>
    ///     | <Identifier> "=" <AttributeValue>
    ///     | <Identifier> "(" Comma<Attribute> ")"
    ///
    /// [attribute]: https://github.com/MystenLabs/sui/blob/129788902da4afc54a10af4ae45971a57ef080be/external-crates/move/crates/move-compiler/src/parser/syntax.rs#L1154-L1158
    #[derive(Clone)]
    enum Attribute {
        // NOTE: special case for doc strings
        Doc(Cons<DocKw, Assign, LiteralString>),
        For(ForKw),
        Other {
            ident: Ident,
            sub: Option<SubAttribute>,
        }
    }

    keyword DocKw = "doc";
    keyword ForKw = "for";

    #[derive(Clone)]
    enum SubAttribute {
        Eq(Cons<Assign, AttributeValue>),
        List(ParenthesisGroupContaining<DelimitedVec<Box<Attribute>, Comma, TrailingDelimiter::Optional>>),
    }

    /// AttributeValue =
    ///     <Value>
    ///     | <NameAccessChain>
    ///
    /// Based on
    /// <https://github.com/MystenLabs/sui/blob/129788902da4afc54a10af4ae45971a57ef080be/external-crates/move/crates/move-compiler/src/parser/syntax.rs#L1135-L1138>
    #[derive(Clone)]
    enum AttributeValue {
        Lit(Literal),
        //      NameAccessChain =
        //          <LeadingNameAccess> <OptionalTypeArgs>
        //              ( "::" <Identifier> <OptionalTypeArgs> )^n
        NameAccessChain {
            // TODO: support NumericalAddress
            // LeadingNameAccess = <NumericalAddress> | <Identifier> | <SyntaxIdentifier>
            leading_name_access: Either<SyntaxIdent, Ident>,
            // NOTE: ignoring <OptionalTypeArgs> for now
            // https://github.com/MystenLabs/sui/blob/129788902da4afc54a10af4ae45971a57ef080be/external-crates/move/crates/move-compiler/src/parser/syntax.rs#L3168
            path: DelimitedVec<PathSep, Ident, TrailingDelimiter::Forbidden>,
        },
    }

    // === Visibility modifiers ===

    /// Move item visibility.
    ///
    /// `public`, `public(package)`, `public(friend)`
    #[derive(Clone)]
    struct Vis {
        public: kw::Public,
        modifier: Option<ParenthesisGroupContaining<VisibilityModifier>>,
    }

    /// Move item visibility modifier.
    ///
    /// Examples:
    /// - `public(package)`
    /// - `public(friend)`
    #[derive(Clone)]
    enum VisibilityModifier {
        Package(kw::Package),
        Friend(kw::Friend)
    }

    // === ===

    /// All Move item types.
    #[non_exhaustive]
    pub enum ItemKind {
        Struct(Struct),
        Enum(Enum),
        Import(Import),
        UseFun(UseFun),
        Const(Const),
        Function(Function),
        MacroFun(MacroFun),
        NativeFun(NativeFun)
    }

    /// Alias for a receiver method, like `use fun foo as Bar.bar;`
    pub struct UseFun {
        keyword: kw::Use,
        fun_kw: kw::Fun,
        fun_path: ItemPath,
        as_kw: kw::As,
        ty: Ident,
        dot: Dot,
        method: Ident,
        semicolon: Semicolon,
    }

    // === Constants ===

    pub struct Const {
        /// `const`
        const_kw: kw::Const,
        /// `NAME`
        ident: Ident,
        /// `:`
        colon: Colon,
        /// Type
        ty: Type,
        /// `=`
        assign: Assign,
        /// Hack to parse anything until (but excluding) a `;`
        expr: Vec<Cons<Except<Semicolon>, TokenTree>>,
        /// `;`
        semicolon: Semicolon,
    }

    // === Imports ===

    pub struct Import {
        keyword: kw::Use,
        named_address: Ident,
        path_sep: PathSep,
        module: ImportModule,
        semicolon: Semicolon,
    }

    /// `module`, `module as alias`, `module::...`, `{module, ...}`
    enum ImportModule {
        One(ModuleOrItems),
        Many(BraceGroupContaining<CommaDelimitedVec<ModuleOrItems>>),
    }

    #[derive(Clone)]
    struct ModuleOrItems {
        ident: Ident,
        next: Option<AliasOrItems>,
    }

    #[derive(Clone)]
    enum AliasOrItems {
        Alias {
            as_kw: kw::As,
            alias: Ident,
        },
        Items {
            sep: PathSep,
            item: ImportItem,
        }
    }

    #[derive(Clone)]
    enum ImportItem {
        One(MaybeAliased),
        Many(BraceGroupContaining<CommaDelimitedVec<MaybeAliased>>)
    }

    #[derive(Clone)]
    struct MaybeAliased {
        ident: Ident,
        alias: Option<Cons<kw::As, Ident>>,
    }

    // === Structs ===

    /// A Move struct.
    #[derive(Clone)]
    pub struct Struct {
        keyword: kw::Struct,
        pub ident: Ident,
        pub generics: Option<Generics>,
        pub kind: StructKind,
    }

    /// The kinds of structs; either a braced or tuple one.
    #[derive(Clone)]
    pub enum StructKind {
        Braced(BracedStruct),
        Tuple(TupleStruct),
    }

    /// Braced structs have their abilities declared before their fields.
    #[derive(Clone)]
    pub struct BracedStruct {
        abilities: Option<Abilities>,
        pub fields: NamedFields,
    }

    /// Tuple structs have their abilities declared after their fields, with a trailing semicolon
    /// if so.
    #[derive(Clone)]
    pub struct TupleStruct {
        pub fields: PositionalFields,
        abilities: Option<Cons<Abilities, Semicolon>>
    }

    // === Enums ===

    #[derive(Clone)]
    pub struct Enum {
        keyword: kw::Enum,
        pub ident: Ident,
        pub generics: Option<Generics>,
        abilities: Option<Abilities>,
        content: BraceGroupContaining<CommaDelimitedVec<EnumVariant>>,
    }

    #[derive(Clone)]
    pub struct EnumVariant {
        pub attrs: Vec<Attributes>,
        pub ident: Ident,
        /// The fields of the enum variants. If none, it's a "unit" or "empty" variant.
        pub fields: Option<FieldsKind>
    }

    /// Kinds of fields for a Move enum.
    #[derive(Clone)]
    pub enum FieldsKind {
        Positional(PositionalFields),
        Named(NamedFields),
    }

    // === Datatype fields ===

    /// Parenthesis group containing comma-delimited unnamed fields.
    #[derive(Clone)]
    pub struct PositionalFields(ParenthesisGroupContaining<DelimitedVec<UnnamedField, Comma>>);

    /// Brace group containing comma-delimited named fields.
    #[derive(Clone)]
    pub struct NamedFields(BraceGroupContaining<DelimitedVec<NamedField, Comma>>);

    /// Named datatype field.
    #[derive(Clone)]
    pub struct NamedField {
        pub attrs: Vec<Attributes>,
        pub ident: Ident,
        colon: Colon,
        pub ty: Type,
    }

    /// Unnamed datatype field.
    #[derive(Clone)]
    pub struct UnnamedField {
        pub attrs: Vec<Attributes>,
        pub ty: Type,
    }

    // === Generics ===

    /// The generics of a datatype or function.
    ///
    /// # Example
    /// `<T, U: drop, V: key + store>`
    #[derive(Clone)]
    pub struct Generics {
        lt_token: Lt,
        type_args: DelimitedVec<Generic, Comma>,
        gt_token: Gt,
    }

    /// A generic type declaration.
    ///
    /// # Examples
    /// * `T`
    /// * `T: drop`
    /// * `T: key + store`
    /// * `phantom T`
    #[derive(Clone)]
    pub struct Generic {
        pub phantom: Option<kw::Phantom>,
        pub ident: Ident,
        bounds: Option<GenericBounds>
    }

    /// Captures the fact that:
    /// * `:` must be followed by an ability
    /// * additional abilities are preceeded by `+`
    #[derive(Clone)]
    struct GenericBounds {
        colon: Colon,
        abilities: Many<Ability, Plus, TrailingDelimiter::Forbidden>,
    }

    // === Abilities ===

    /// Abilities declaration for a datatype.
    ///
    /// Example: `has key, store`
    #[derive(Clone)]
    struct Abilities {
        has: kw::Has,
        keywords: Many<Ability, Comma, TrailingDelimiter::Forbidden>,
    }

    /// Ability keywords.
    #[derive(Clone)]
    pub enum Ability {
        Copy(kw::Copy),
        Drop(kw::Drop),
        Key(kw::Key),
        Store(kw::Store),
    }

    // === Macros ===

    pub struct MacroFun {
        macro_kw: kw::Macro,
        fun_kw: kw::Fun,
        ident: Ident,
        generics: Option<MacroGenerics>,
        args: ParenthesisGroup,
        ret: Option<Cons<Colon, Either<MacroReturn, ParenthesisGroup>>>,
        body: BraceGroup,
    }

    struct MacroGenerics {
        lt_token: Lt,
        type_args: DelimitedVec<MacroTypeArg, Comma>,
        gt_token: Gt,
    }

    /// `$T: drop + store`
    struct MacroTypeArg{
        name: SyntaxIdent,
        bounds: Option<GenericBounds>,
    }

    /// Either `_` or a 'concrete' type
    enum MacroReturn {
        Underscore(Underscore),
        Concrete(Cons<Option<Ref>, MacroReturnType>),
    }

    /// Return type for macro funs.
    ///
    /// - `$T`
    /// - `&mut $T`
    /// - `&String`
    /// - `Option<$T>`
    enum MacroReturnType {
        MacroTypeName(SyntaxIdent),
        Hybrid(HybridMacroType)
    }

    struct HybridMacroType {
        ident: Ident,
        type_args: Option<Cons<Lt, Many<Either<Type, SyntaxIdent, Box<HybridMacroType>>, Comma>, Gt>>
    }

    /// `$T`
    ///
    /// Name based on
    /// https://github.com/MystenLabs/sui/blob/129788902da4afc54a10af4ae45971a57ef080be/external-crates/move/crates/move-compiler/src/parser/syntax.rs#L675-L678
    #[derive(Clone)]
    struct SyntaxIdent {
        dollar: Dollar,
        ident: Ident,
    }

    // === Types ===

    /// Type of function arguments or returns.
    pub struct MaybeRefType {
        r#ref: Option<Ref>,
        r#type: Type,
    }

    /// The reference prefix
    struct Ref {
        and: And,
        r#mut: Option<kw::Mut>,
    }

    /// Non-reference type, used in datatype fields.
    #[derive(Clone)]
    pub struct Type {
        pub path: ItemPath,
        pub type_args: Option<TypeArgs>
    }

    /// Path to an item.
    #[derive(Clone)]
    pub enum ItemPath {
        /// Fully qualified,
        Full {
            named_address: Ident,
            sep0: PathSep,
            module: Ident,
            sep1: PathSep,
            item: Ident,
        },
        /// Module prefix only, if it was imported already.
        Module {
            module: Ident,
            sep: PathSep,
            item: Ident,
        },
        /// Only the item identifier.
        Ident(Ident),
    }

    /// Angle bracket group (`<...>`) containing comma-delimited types.
    #[derive(Clone)]
    pub struct TypeArgs {
        lt: Lt,
        args: Many<Box<Type>, Comma>,
        gt: Gt,
    }
}

impl File {
    pub fn into_modules(self) -> impl Iterator<Item = Module> {
        match self {
            Self::ModuleLabel(labeled) => std::iter::once(labeled.into_module()).boxed(),
            Self::Legacy(modules) => modules.into_iter().boxed(),
        }
    }
}

impl LabeledModule {
    pub fn into_module(self) -> Module {
        Module {
            attrs: self.attrs,
            keyword: self.keyword,
            named_address: self.named_address,
            path_sep: self.path_sep,
            ident: self.ident,
            contents: BraceGroupContaining {
                content: self.contents,
            },
        }
    }
}

impl Module {
    /// Add `sui` implicit imports as explicit `use` statements to the module.
    ///
    /// [Reference](https://move-book.com/programmability/sui-framework#implicit-imports)
    pub fn with_implicit_sui_imports(&mut self) -> &mut Self {
        // Build the map of implicit imports keyed by the identifiers they export.
        let implicit_imports: HashMap<_, _> = [
            "use sui::object;",
            "use sui::object::ID;",
            "use sui::object::UID;",
            "use sui::tx_context;",
            "use sui::tx_context::TxContext;",
            "use sui::transfer;",
        ]
        .into_iter()
        .map(|text| {
            text.to_token_iter()
                .parse_all::<Import>()
                .expect("Valid imports")
        })
        .map(|import| {
            let ident = import
                .imported_idents()
                .next()
                .expect("Each import exposes exactly one ident");
            (ident.clone(), import)
        })
        .collect();

        self.add_implicit_imports(implicit_imports)
    }

    /// Add `iota` implicit imports as explicit `use` statements to the module.
    ///
    /// Adapted from the `sui` equivalents.
    pub fn with_implicit_iota_imports(&mut self) -> &mut Self {
        // Build the map of implicit imports keyed by the identifiers they export.
        let implicit_imports: HashMap<_, _> = [
            "use iota::object;",
            "use iota::object::ID;",
            "use iota::object::UID;",
            "use iota::tx_context;",
            "use iota::tx_context::TxContext;",
            "use iota::transfer;",
        ]
        .into_iter()
        .map(|text| {
            text.to_token_iter()
                .parse_all::<Import>()
                .expect("Valid imports")
        })
        .map(|import| {
            let ident = import
                .imported_idents()
                .next()
                .expect("Each import exposes exactly one ident");
            (ident.clone(), import)
        })
        .collect();

        self.add_implicit_imports(implicit_imports)
    }

    /// Resolve all datatype field types to their fully-qualified paths.
    pub fn fully_qualify_datatype_field_types(&mut self) -> &mut Self {
        // Collect all imported types and their paths
        let imports: HashMap<_, _> = self
            .items()
            .filter_map(|item| match &item.kind {
                ItemKind::Import(import) => Some(import),
                _ => None,
            })
            .flat_map(|import| import.flatten())
            .collect();

        // Resolve datatype fields' types
        for item in &mut self.contents.content {
            match &mut item.kind {
                ItemKind::Enum(e) => {
                    let generics = &e.type_param_idents();
                    e.map_types(|ty| ty.resolve(&imports, generics));
                }
                ItemKind::Struct(s) => {
                    let generics = &s.type_param_idents();
                    s.map_types(|ty| ty.resolve(&imports, generics));
                }
                _ => (),
            }
        }

        self
    }

    pub fn items(&self) -> impl Iterator<Item = &Item> {
        self.contents.content.iter()
    }

    #[cfg(test)]
    pub fn into_items(self) -> impl Iterator<Item = Item> {
        self.contents.content.into_iter()
    }

    fn add_implicit_imports(&mut self, mut implicit_imports: HashMap<Ident, Import>) -> &mut Self {
        // Filter out any that were shadowed by existing imports
        for item in self.items() {
            let ItemKind::Import(import) = &item.kind else {
                continue;
            };
            for ident in import.imported_idents() {
                implicit_imports.remove(ident);
            }
        }

        // Add the remaining implicit imports to the list of module items
        for (_, import) in implicit_imports {
            self.contents.content.push(Item {
                attrs: vec![],
                vis: None,
                kind: ItemKind::Import(import),
            })
        }
        self
    }
}

impl Import {
    /// List of idents (or aliases) brought into scope by this import and their paths
    /// (`named_address::module(::item)?`).
    pub fn flatten(&self) -> impl Iterator<Item = (Ident, FlatImport)> + '_ {
        let named_address = self.named_address.clone();
        match &self.module {
            // use named_address::module...
            ImportModule::One(module_or_items) => module_or_items.flatten(named_address),
            // use named_address::{...}
            ImportModule::Many(BraceGroupContaining { content: ms }) => ms
                .iter()
                .flat_map(move |Delimited { value, .. }| value.flatten(named_address.clone()))
                .boxed(),
        }
    }

    /// The list of item idents brought into scope by this import.
    fn imported_idents(&self) -> impl Iterator<Item = &Ident> {
        match &self.module {
            ImportModule::One(module_or_items) => module_or_items.available_idents(),
            ImportModule::Many(BraceGroupContaining { content: ms }) => ms
                .iter()
                .flat_map(|delimited| delimited.value.available_idents())
                .boxed(),
        }
    }
}

impl ModuleOrItems {
    /// Flat canonical imports (`named_address::module(::item)?`).
    fn flatten(&self, named_address: Ident) -> Box<dyn Iterator<Item = (Ident, FlatImport)> + '_> {
        let module = self.ident.clone();

        let Some(next) = &self.next else {
            // module;
            return std::iter::once((
                module.clone(),
                FlatImport::Module {
                    named_address,
                    module,
                },
            ))
            .boxed();
        };

        match next {
            // module as alias;
            AliasOrItems::Alias { alias, .. } => std::iter::once((
                alias.clone(),
                FlatImport::Module {
                    named_address,
                    module,
                },
            ))
            .boxed(),

            // module::item( as alias)?;
            AliasOrItems::Items {
                item: ImportItem::One(maybe_aliased),
                ..
            } => std::iter::once(maybe_aliased.flat_import(named_address, module)).boxed(),

            // module::{(item( as alias)?),+};
            AliasOrItems::Items {
                item: ImportItem::Many(BraceGroupContaining { content: items }),
                ..
            } => items
                .iter()
                .map(move |Delimited { value, .. }| {
                    value.flat_import(named_address.clone(), module.clone())
                })
                .boxed(),
        }
    }

    /// Identifiers this import makes available in scope.
    fn available_idents(&self) -> Box<dyn Iterator<Item = &Ident> + '_> {
        let Some(next) = &self.next else {
            return std::iter::once(&self.ident).boxed();
        };

        match next {
            AliasOrItems::Alias { alias, .. } => std::iter::once(alias).boxed(),

            AliasOrItems::Items {
                item: ImportItem::One(item),
                ..
            } => std::iter::once(item.available_ident(&self.ident)).boxed(),

            AliasOrItems::Items {
                item: ImportItem::Many(BraceGroupContaining { content: items }),
                ..
            } => items
                .iter()
                .map(|delimited| delimited.value.available_ident(&self.ident))
                .boxed(),
        }
    }
}

impl MaybeAliased {
    /// Special handling for `Self` imports.
    fn flat_import(&self, named_address: Ident, module: Ident) -> (Ident, FlatImport) {
        if self.ident == "Self" {
            (
                self.alias().unwrap_or(&module).clone(),
                FlatImport::Module {
                    named_address,
                    module,
                },
            )
        } else {
            (
                self.alias().unwrap_or(&self.ident).clone(),
                FlatImport::Item {
                    named_address,
                    module,
                    r#type: self.ident.clone(),
                },
            )
        }
    }

    fn available_ident<'a>(&'a self, module: &'a Ident) -> &'a Ident {
        if self.ident == "Self" {
            self.alias().unwrap_or(module)
        } else {
            self.alias().unwrap_or(&self.ident)
        }
    }

    /// The identifier alias that's available in scope, if any.
    fn alias(&self) -> Option<&Ident> {
        self.alias.as_ref().map(|cons| &cons.second)
    }
}

impl Attributes {
    /// Whether this is a `#[doc = "..."]`.
    pub fn is_doc(&self) -> bool {
        matches!(
            &self.contents.content[..],
            [Delimited {
                value: Attribute::Doc(_),
                ..
            }]
        )
    }

    /// Everything inside the bracket group, `#[...]`.
    pub const fn contents(&self) -> &impl ToTokens {
        &self.contents.content
    }

    /// Contents of each [attribute].
    ///
    /// [attribute]: https://github.com/MystenLabs/sui/blob/129788902da4afc54a10af4ae45971a57ef080be/external-crates/move/crates/move-compiler/src/parser/syntax.rs#L1154-L1158
    pub fn erased_attributes(&self) -> impl Iterator<Item = &dyn ToTokens> + '_ {
        self.contents
            .content
            .iter()
            .map(|delimited| &delimited.value as _)
    }

    /// Contents of parameterized attributes as `#[ext(<external_attribute>)]`
    pub fn external_attributes(&self) -> impl Iterator<Item = &dyn ToTokens> + '_ {
        self.contents.content.iter().filter_map(|d| match &d.value {
            Attribute::Other {
                ident,
                sub: Some(SubAttribute::List(inner)),
            } if ident == "ext" => Some(&inner.content as _),
            _ => None,
        })
    }
}

impl ItemKind {
    /// Whether this item is a datatype (enum/struct) declaration.
    pub const fn is_datatype(&self) -> bool {
        matches!(self, Self::Enum(_) | Self::Struct(_))
    }
}

impl Struct {
    pub fn abilities(&self) -> impl Iterator<Item = &Ability> {
        use StructKind as K;
        match &self.kind {
            K::Braced(braced) => braced
                .abilities
                .iter()
                .flat_map(|a| a.keywords.iter())
                .map(|d| &d.value)
                .boxed(),
            K::Tuple(tuple) => tuple
                .abilities
                .iter()
                .flat_map(|a| a.first.keywords.iter())
                .map(|d| &d.value)
                .boxed(),
        }
    }
}

impl BracedStruct {
    pub fn fields(&self) -> impl Iterator<Item = &NamedField> + Clone + '_ {
        self.fields.fields()
    }

    /// Whether this struct has no fields.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

impl TupleStruct {
    pub fn fields(&self) -> impl Iterator<Item = &UnnamedField> + Clone + '_ {
        self.fields.fields()
    }

    /// Whether this struct has no fields.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

impl Enum {
    pub fn abilities(&self) -> impl Iterator<Item = &Ability> {
        self.abilities
            .iter()
            .flat_map(|a| a.keywords.iter())
            .map(|d| &d.value)
    }

    pub fn variants(&self) -> impl Iterator<Item = &EnumVariant> {
        self.content
            .content
            .iter()
            .map(|Delimited { value, .. }| value)
    }
}

impl NamedFields {
    pub fn fields(&self) -> impl Iterator<Item = &NamedField> + Clone + '_ {
        self.0.content.iter().map(|d| &d.value)
    }

    pub fn is_empty(&self) -> bool {
        self.0.content.is_empty()
    }
}

impl PositionalFields {
    pub fn new() -> Self {
        Self(ParenthesisGroupContaining {
            content: std::iter::empty::<UnnamedField>()
                .collect::<DelimitedVec<_, _, TrailingDelimiter::Mandatory>>()
                .into(),
        })
    }

    pub fn fields(&self) -> impl Iterator<Item = &UnnamedField> + Clone + '_ {
        self.0.content.iter().map(|d| &d.value)
    }

    pub fn is_empty(&self) -> bool {
        self.0.content.is_empty()
    }
}

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

impl Type {
    /// Resolve the types' path to a fully-qualified declaration, recursively.
    fn resolve(&mut self, imports: &HashMap<Ident, FlatImport>, generics: &[Ident]) {
        use ItemPath as P;
        // First, resolve the type arguments
        self.map_types(|ty| ty.resolve(imports, generics));

        // Then resolve its own path
        // HACK: We trust the Move code is valid, so the expected import should always be found,
        // hence we don't error/panic if it isn't
        let resolved = match &self.path {
            P::Module {
                module,
                item: r#type,
                ..
            } => {
                let Some(FlatImport::Module {
                    named_address,
                    module,
                }) = imports.get(module)
                else {
                    return;
                };
                P::Full {
                    named_address: named_address.clone(),
                    sep0: PathSep::default(),
                    module: module.clone(),
                    sep1: PathSep::default(),
                    item: r#type.clone(),
                }
            }
            P::Ident(ident) if !generics.contains(ident) => {
                let Some(FlatImport::Item {
                    named_address,
                    module,
                    r#type,
                }) = imports.get(ident)
                else {
                    return;
                };
                P::Full {
                    named_address: named_address.clone(),
                    sep0: PathSep::default(),
                    module: module.clone(),
                    sep1: PathSep::default(),
                    item: r#type.clone(),
                }
            }
            // Already fully-qualified types or idents shadowed by generics should be left alone
            _ => return,
        };
        self.path = resolved;
    }
}

impl TypeArgs {
    /// Guaranteed to be non-empty.
    pub fn types(&self) -> impl Iterator<Item = &Type> {
        self.args.iter().map(|args| &*args.value)
    }
}

impl Generics {
    pub fn generics(&self) -> impl Iterator<Item = &Generic> + '_ {
        self.type_args.iter().map(|d| &d.value)
    }
}

impl MaybeRefType {
    /// Whether this is an immutable reference to a type.
    pub fn is_ref(&self) -> bool {
        self.r#ref.as_ref().is_some_and(|r| r.r#mut.is_none())
    }

    /// Reference to the Move type
    pub const fn type_(&self) -> &Type {
        &self.r#type
    }
}

// === Non-lang items ===

#[cfg_attr(test, derive(derive_more::Display))]
pub enum FlatImport {
    #[cfg_attr(test, display("{named_address}::{module}"))]
    Module { named_address: Ident, module: Ident },
    #[cfg_attr(test, display("{named_address}::{module}::{type}"))]
    Item {
        named_address: Ident,
        module: Ident,
        r#type: Ident,
    },
}

// === Misc helpers ===

/// Box an iterator, necessary when returning different types that implement [`Iterator`].
trait IteratorBoxed<'a>: Iterator + 'a {
    fn boxed(self) -> Box<dyn Iterator<Item = Self::Item> + 'a>
    where
        Self: Sized,
    {
        Box::new(self)
    }
}

impl<'a, T> IteratorBoxed<'a> for T where T: Iterator + 'a {}

/// Something that can be generic over type parameters.
trait HasGenerics {
    fn generics(&self) -> Option<&Generics>;

    /// Identifiers of the generic type parameters.
    fn type_param_idents(&self) -> Vec<Ident> {
        self.generics()
            .iter()
            .flat_map(|generics| generics.generics())
            .map(|generic| generic.ident.clone())
            .collect()
    }
}

impl HasGenerics for Enum {
    fn generics(&self) -> Option<&Generics> {
        self.generics.as_ref()
    }
}

impl HasGenerics for Struct {
    fn generics(&self) -> Option<&Generics> {
        self.generics.as_ref()
    }
}

/// Something that has inner types, e.g., datatype fields, function arguments and returns.
trait Typed {
    /// Field types. Used to resolve into fully-qualified paths.
    fn map_types(&mut self, f: impl FnMut(&mut Type));
}

impl Typed for Enum {
    fn map_types(&mut self, mut f: impl FnMut(&mut Type)) {
        mutate_delimited_vec(&mut self.content.content, |variant| {
            variant.map_types(&mut f)
        });
    }
}

impl Typed for EnumVariant {
    fn map_types(&mut self, f: impl FnMut(&mut Type)) {
        let Some(fields) = &mut self.fields else {
            return;
        };
        fields.map_types(f);
    }
}

impl Typed for Struct {
    fn map_types(&mut self, f: impl FnMut(&mut Type)) {
        match &mut self.kind {
            StructKind::Braced(braced_struct) => braced_struct.fields.map_types(f),
            StructKind::Tuple(tuple_struct) => tuple_struct.fields.map_types(f),
        }
    }
}

impl Typed for FieldsKind {
    fn map_types(&mut self, f: impl FnMut(&mut Type)) {
        match self {
            Self::Named(named) => named.map_types(f),
            Self::Positional(positional) => positional.map_types(f),
        }
    }
}

impl Typed for NamedFields {
    fn map_types(&mut self, mut f: impl FnMut(&mut Type)) {
        mutate_delimited_vec(&mut self.0.content, |field| f(&mut field.ty));
    }
}

impl Typed for PositionalFields {
    fn map_types(&mut self, mut f: impl FnMut(&mut Type)) {
        mutate_delimited_vec(&mut self.0.content, |field| f(&mut field.ty));
    }
}

impl Typed for Type {
    fn map_types(&mut self, mut f: impl FnMut(&mut Self)) {
        if let Some(args) = &mut self.type_args {
            mutate_delimited_vec(&mut args.args, |t| f(&mut *t))
        }
    }
}

// HACK: circumvent the fact that `DelimitedVec` doesn't have a `DerefMut` implementation.
// WARN: this changes `P` to be `Forbidden`
fn mutate_delimited_vec<T, D: Default, const MIN: usize, const MAX: usize>(
    dvec: &mut DelimitedVec<T, D, TrailingDelimiter::Optional, MIN, MAX>,
    mut f: impl FnMut(&mut T),
) {
    type ForbiddenDelimited<T, D, const MIN: usize, const MAX: usize> =
        DelimitedVec<T, D, TrailingDelimiter::Forbidden, MIN, MAX>;

    let temp: ForbiddenDelimited<T, D, MIN, MAX> = std::iter::empty::<T>().collect();
    let mut swapped = std::mem::replace(dvec, temp.into());
    swapped = swapped
        .into_iter()
        .map(|mut d| {
            f(&mut d.value);
            d.value
        })
        .collect::<ForbiddenDelimited<T, D, MIN, MAX>>()
        .into();
    *dvec = swapped;
}