syn-canon 0.5.1

Canonical form of a syn file, equal across formatting drift and local binder names
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
//! Borrowed discovery and independent normalization of lexical contexts.

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use proc_macro2::{Ident, Span, TokenTree};
use quote::ToTokens;
use syn::visit::Visit;
use syn::visit_mut::VisitMut;

use crate::alpha::{
    Renamer, is_unit_path, item_binding, resolve_target_path, single_segment_type_name,
};
use crate::form::CanonicalForm;
use crate::scope::{
    Binding, BindingId, Domain, FirstSeg, Frame, Inherited, Ns, Origin, Target, TargetSeg,
};

/// The kind of lexical scope a context candidate covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContextKind {
    /// A function, method, or trait default body.
    FunctionBody,
    /// An explicit block, a loop body, or an `if` branch.
    Block,
    /// A complete match arm, pattern and guard included.
    Arm,
    /// A complete closure, inputs and body included.
    Closure,
}

/// The metadata of one emitted context candidate.
pub struct Context<'a> {
    /// The kind of lexical scope covered.
    pub kind: ContextKind,
    /// The candidate span from the supplied syntax tree, outer delimiters included.
    pub span: Span,
    /// The item containing the candidate, relative to the caller's module prefix.
    pub item: &'a str,
}

/// The measured work of a `contexts` walk.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ContextWork {
    /// The candidates emitted.
    pub contexts: usize,
    /// The raw leaf tokens the independent normalizations consumed, nested content repeated per containing candidate.
    pub input_tokens: usize,
}

/// Emit each original lexical context once, normalized against its visible declarations.
///
/// ```
/// let forms = |source: &str| {
///     let mut forms = Vec::new();
///     syn_canon::contexts(&syn::parse_str(source).unwrap(), &mut |_, form| forms.push(form));
///     forms
/// };
/// assert_eq!(forms("fn f(x: u32) -> u32 { x + x }"), forms("fn g(y: u32) -> u32 { y + y }"));
/// ```
pub fn contexts(file: &syn::File, emit: &mut dyn FnMut(Context<'_>, CanonicalForm)) -> ContextWork {
    let mut walker = Walker {
        frames: vec![Frame::default()],
        mod_frames: BTreeMap::new(),
        mod_origins: BTreeMap::new(),
        targets: Vec::new(),
        item_path: Vec::new(),
        inline_depth: 0,
        id: 0,
        work: ContextWork::default(),
        emit,
    };
    walker.visit_file(file);
    walker.work
}

/// The original delimiter-inclusive span and raw leaf token count.
fn source_span_and_leaf_tokens(node: &impl ToTokens) -> (Span, usize) {
    let mut first = None;
    let mut last = None;
    let mut count = 0;
    for tree in node.to_token_stream() {
        if first.is_none() {
            first = Some(tree.span());
        }
        last = Some(tree.span());
        count += leaf_count(&tree);
    }
    (
        match (first, last) {
            (Some(first), Some(last)) => first.join(last).unwrap_or_else(Span::call_site),
            _ => Span::call_site(),
        },
        count,
    )
}

/// The leaf tokens of one tree, its inner groups counted.
fn leaf_count(tree: &TokenTree) -> usize {
    match tree {
        TokenTree::Group(group) => group
            .stream()
            .into_iter()
            .map(|inner| leaf_count(&inner))
            .sum(),
        _ => 1,
    }
}

/// Push the names bound by `pat` to `out`, in traversal order, without rewriting it.
fn pat_names(pat: &syn::Pat, out: &mut Vec<String>) {
    match pat {
        syn::Pat::Ident(id) => {
            if !is_unit_path(id) {
                out.push(id.ident.to_string());
            }
            if let Some((_, sub)) = &id.subpat {
                pat_names(sub, out);
            }
        }
        syn::Pat::Tuple(syn::PatTuple { elems, .. })
        | syn::Pat::Slice(syn::PatSlice { elems, .. })
        | syn::Pat::TupleStruct(syn::PatTupleStruct { elems, .. }) => {
            for pat in elems {
                pat_names(pat, out);
            }
        }
        syn::Pat::Struct(r#struct) => {
            for field in &r#struct.fields {
                pat_names(&field.pat, out);
            }
        }
        syn::Pat::Or(r#or) => {
            for pat in &r#or.cases {
                pat_names(pat, out);
            }
        }
        syn::Pat::Reference(syn::PatReference { pat, .. })
        | syn::Pat::Type(syn::PatType { pat, .. })
        | syn::Pat::Paren(syn::PatParen { pat, .. })
        | syn::Pat::Guard(syn::PatGuard { pat, .. }) => pat_names(pat, out),
        _ => {}
    }
}

/// The names bound by the function parameters of `inputs`.
fn fn_input_names<'a>(inputs: impl Iterator<Item = &'a syn::FnArg>) -> Vec<String> {
    let mut out = Vec::new();
    for input in inputs {
        if let syn::FnArg::Typed(pat_type) = input {
            pat_names(&pat_type.pat, &mut out);
        }
    }
    out
}

/// Prebind items and module frames so references may precede declarations.
fn prebind_items<'a>(
    frames: &mut Vec<Frame>,
    mod_frames: &mut BTreeMap<BindingId, Frame>,
    mod_origins: &mut BTreeMap<*const syn::ItemMod, BindingId>,
    id: &mut usize,
    items: impl Iterator<Item = &'a syn::Item>,
) {
    for item in items {
        let (ns, ident, standard, origin) = if let syn::Item::ExternCrate(item) = item {
            (
                Ns::Type,
                item.rename.as_ref().map_or(&item.ident, |(_, alias)| alias),
                crate::macros::MacroResolution::external_crate(item),
                Origin::Use,
            )
        } else if let Some((ns, ident)) = item_binding(item) {
            (ns, ident, None, Origin::Item)
        } else {
            continue;
        };
        let binding_id = BindingId(*id);
        *id += 1;
        let name = ident.to_string();
        frames.last_mut().expect("a scope frame").bind(
            ns,
            &name,
            Binding {
                id: binding_id,
                canon: String::new(),
                origin,
                prim: None,
                port: 0,
                value_port: None,
                target: None,
                raw: false,
                helper: None,
                macro_resolution: standard,
            },
        );
        if let syn::Item::Mod(
            module @ syn::ItemMod {
                content: Some((_, sub_items)),
                ..
            },
        ) = item
        {
            mod_origins.insert(core::ptr::from_ref(module), binding_id);
            frames.push(Frame::default());
            prebind_items(frames, mod_frames, mod_origins, id, sub_items.iter());
            let frame = frames.pop().expect("a scope frame");
            mod_frames.insert(binding_id, frame);
        }
    }
}

/// The written self type of an impl, as the item path's owner.
fn self_type_string(self_ty: &syn::Type) -> String {
    self_ty.to_token_stream().to_string()
}

/// The borrowed walk that records candidates and the lexical environment around them.
struct Walker<'w> {
    /// The scope stack, the file frame first.
    frames: Vec<Frame>,
    /// The item frames of local modules, by module binding id.
    mod_frames: BTreeMap<BindingId, Frame>,
    /// The binding id of each inline module declaration by address, apart for `cfg`-exclusive
    /// declarations sharing one name.
    mod_origins: BTreeMap<*const syn::ItemMod, BindingId>,
    /// The interned alias targets.
    targets: Vec<Target>,
    /// The item path segments, outermost first.
    item_path: Vec<String>,
    /// The inline modules around the walk, whose frames stay on the stack.
    inline_depth: usize,
    /// The next binding id.
    id: usize,
    /// The measured work.
    work: ContextWork,
    /// The candidate emitter.
    emit: &'w mut dyn FnMut(Context<'_>, CanonicalForm),
}

impl Walker<'_> {
    /// Bind `name` in the current frame and return its binding id.
    fn bind(&mut self, ns: Ns, name: &str, origin: Origin) -> BindingId {
        let binding_id = BindingId(self.id);
        self.id += 1;
        self.top_bind(
            ns,
            name,
            Binding {
                id: binding_id,
                canon: String::new(),
                origin,
                prim: None,
                port: 0,
                value_port: None,
                target: None,
                raw: false,
                helper: None,
                macro_resolution: None,
            },
        );
        binding_id
    }

    /// Bind `name` to `binding` in the current frame.
    fn top_bind(&mut self, ns: Ns, name: &str, binding: Binding) {
        self.frames
            .last_mut()
            .expect("a scope frame")
            .bind(ns, name, binding);
    }

    /// Bind `name` in the value and type namespaces to one binding id, a `use` alias form.
    fn bind_value_and_type(
        &mut self,
        name: &str,
        target: Option<usize>,
        origin: Origin,
        macro_resolution: Option<crate::macros::MacroResolution>,
    ) -> BindingId {
        let binding_id = BindingId(self.id);
        self.id += 1;
        let binding = Binding {
            id: binding_id,
            canon: String::new(),
            origin,
            prim: None,
            port: 0,
            value_port: None,
            target,
            raw: false,
            helper: None,
            macro_resolution,
        };
        self.top_bind(Ns::Value, name, binding.clone());
        if origin == Origin::Use {
            self.top_bind(Ns::Macro, name, binding.clone());
        }
        self.top_bind(Ns::Type, name, binding);
        binding_id
    }

    /// Nearest-binding lookup, namespace priority first.
    fn lookup(&self, ns: &[Ns], name: &str) -> Option<&Binding> {
        for ns in ns {
            for frame in self.frames.iter().rev() {
                if let Some(binding) = frame.lookup(*ns, name) {
                    return Some(binding);
                }
            }
        }
        None
    }

    /// Reuse a prebound item's binding id when its declaration is visited.
    fn bind_item_name(&mut self, ns: Ns, ident: &Ident) -> BindingId {
        let name = ident.to_string();
        match self.frames.last().and_then(|frame| frame.lookup(ns, &name)) {
            Some(binding) => binding.id,
            None => self.bind(ns, &name, Origin::Item),
        }
    }

    /// Bind one scope-level `use` item, block-wide.
    fn bind_use_item(&mut self, item: &syn::ItemUse) {
        self.bind_use_tree(
            item.leading_colon.is_some(),
            &[],
            &item.tree,
            crate::context::blocking_attr(&item.attrs),
        );
    }

    /// Bind the block-wide `use` leaves of a scope.
    fn bind_scope_uses<'a>(&mut self, uses: impl Iterator<Item = &'a syn::ItemUse>) {
        for use_item in uses {
            self.bind_use_item(use_item);
        }
    }

    /// Bind the leaf aliases of one `use` tree, resolving each written target.
    fn bind_use_tree(
        &mut self,
        rooted: bool,
        prefix: &[String],
        tree: &syn::UseTree,
        opaque: bool,
    ) {
        match tree {
            syn::UseTree::Path(path) => {
                let mut prefix = prefix.to_vec();
                prefix.push(path.ident.to_string());
                self.bind_use_tree(rooted, &prefix, &path.tree, opaque);
            }
            syn::UseTree::Name(name) if name.ident == "self" => {
                // `a::{self}` imports the module itself under its own name.
                if let Some(alias) = prefix.last() {
                    let segments: Vec<&str> = prefix.iter().map(String::as_str).collect();
                    self.frames.last_mut().expect("a scope frame").std_rebound |=
                        crate::drift::import_rebound(&segments, alias, alias);
                    let (rooted, segments) =
                        resolve_target_path(&|name| self.resolve_first_seg(name), rooted, prefix);
                    self.bind_alias_target(rooted, segments, alias, opaque);
                }
            }
            syn::UseTree::Name(name) => {
                self.bind_alias_leaf(rooted, prefix, &name.ident, &name.ident, opaque);
            }
            syn::UseTree::Rename(rename) => {
                self.bind_alias_leaf(rooted, prefix, &rename.ident, &rename.rename, opaque);
            }
            // A glob outside `std` and the inline modules in view can bring in a macro under
            // any std name.
            syn::UseTree::Glob(_) => {
                self.frames.last_mut().expect("a scope frame").glob = true;
                let segments: Vec<&str> = prefix.iter().map(String::as_str).collect();
                if crate::drift::macro_glob(&segments, self.inline_depth) {
                    self.frames.last_mut().expect("a scope frame").std_rebound =
                        crate::drift::ALL_STD_NAMES;
                }
            }
            syn::UseTree::Group(group) => {
                for tree in &group.items {
                    self.bind_use_tree(rooted, prefix, tree, opaque);
                }
            }
        }
    }

    /// Bind one written target under `alias`.
    fn bind_alias_target(
        &mut self,
        rooted: bool,
        segments: Vec<TargetSeg>,
        alias: &str,
        opaque: bool,
    ) {
        let target = Target { rooted, segments };
        let opaque = opaque
            || self
                .frames
                .last()
                .and_then(|frame| frame.lookup(Ns::Macro, alias))
                .is_some()
            || self.lookup(&[Ns::Macro], alias).is_some_and(|binding| {
                binding.origin == Origin::MacroRule
                    || binding.macro_resolution == Some(crate::macros::MacroResolution::Opaque)
            });
        let resolution = if opaque {
            Some(crate::macros::MacroResolution::Opaque)
        } else {
            crate::macros::MacroResolution::external_target(&target)
        };
        let index = self.targets.len();
        self.targets.push(target);
        self.bind_value_and_type(alias, Some(index), Origin::Use, resolution);
    }

    /// Bind one `use` leaf that imports `ident` under `alias`.
    fn bind_alias_leaf(
        &mut self,
        rooted: bool,
        prefix: &[String],
        ident: &Ident,
        alias: &Ident,
        opaque: bool,
    ) {
        let segments: Vec<&str> = prefix.iter().map(String::as_str).collect();
        self.frames.last_mut().expect("a scope frame").std_rebound |= crate::drift::import_rebound(
            &segments,
            &crate::scope::ident_name(ident),
            &crate::scope::ident_name(alias),
        );
        let mut path = prefix.to_vec();
        path.push(ident.to_string());
        let (rooted, segments) =
            resolve_target_path(&|name| self.resolve_first_seg(name), rooted, &path);
        self.bind_alias_target(rooted, segments, &alias.to_string(), opaque);
    }

    /// Resolve the first-segment question of a written `use` prefix.
    fn resolve_first_seg(&self, name: &str) -> FirstSeg<'_> {
        match self.lookup(&[Ns::Type], name) {
            Some(binding) if binding.target.is_some() => {
                let index = binding.target.expect("a target index");
                FirstSeg::Alias(self.targets.get(index).expect("a target index"))
            }
            Some(binding) => FirstSeg::Module(Domain::Inherited, binding.id),
            None => FirstSeg::Free,
        }
    }

    /// Prebind generic names without repeating the caller's syntax walk.
    fn begin_generics(&mut self, generics: &syn::Generics) {
        self.frames.push(Frame::default());
        for param in &generics.params {
            match param {
                syn::GenericParam::Lifetime(lifetime) => {
                    self.bind(
                        Ns::Lifetime,
                        &lifetime.lifetime.ident.to_string(),
                        Origin::Lifetime,
                    );
                }
                syn::GenericParam::Type(ty_param) => {
                    self.bind(Ns::Type, &ty_param.ident.to_string(), Origin::Generic);
                }
                syn::GenericParam::Const(r#const) => {
                    // A bare reference in `Foo<N>` reads as a type argument.
                    self.bind_value_and_type(
                        &r#const.ident.to_string(),
                        None,
                        Origin::Generic,
                        None,
                    );
                }
            }
        }
    }

    /// Walk a function's signature and body, emitting the body candidate.
    fn visit_fn(&mut self, sig: &syn::Signature, body: &syn::Block) {
        self.begin_generics(&sig.generics);
        self.frames.push(Frame::default());
        for name in fn_input_names(sig.inputs.iter()) {
            self.bind(Ns::Value, &name, Origin::Parameter);
        }
        syn::visit::visit_signature(self, sig);
        let (span, input_tokens) = source_span_and_leaf_tokens(body);
        let inherited = Inherited {
            frames: &self.frames,
            mod_frames: &self.mod_frames,
            targets: &self.targets,
        };
        let form = build_function_body_form(inherited, body, sig.asyncness.is_none());
        self.emit_candidate(ContextKind::FunctionBody, span, input_tokens, form);
        self.visit_block(body);
        self.frames.pop();
        self.frames.pop();
    }

    /// Walk a condition, binding each `let` after its operand, `&&`-only.
    fn walk_let_cond(&mut self, cond: &syn::Expr) {
        match cond {
            syn::Expr::Binary(binary) => {
                self.walk_let_cond(&binary.left);
                self.walk_let_cond(&binary.right);
            }
            syn::Expr::Let(let_expr) => {
                syn::visit::visit_expr(self, &let_expr.expr);
                let mut names = Vec::new();
                pat_names(&let_expr.pat, &mut names);
                for name in &names {
                    self.bind(Ns::Value, name, Origin::Let);
                }
            }
            other => syn::visit::visit_expr(self, other),
        }
    }

    /// Emit one block-slot candidate, a loop body or an `if` branch.
    fn emit_block_slot(&mut self, block: &syn::Block) {
        let (span, input_tokens) = source_span_and_leaf_tokens(block);
        let inherited = Inherited {
            frames: &self.frames,
            mod_frames: &self.mod_frames,
            targets: &self.targets,
        };
        let form = build_block_slot_form(inherited, block);
        self.emit_candidate(ContextKind::Block, span, input_tokens, form);
    }

    /// Emit one block-expression candidate, the label and block included.
    fn emit_block_expr(&mut self, expr: syn::Expr) {
        let (span, input_tokens) = source_span_and_leaf_tokens(&expr);
        let inherited = Inherited {
            frames: &self.frames,
            mod_frames: &self.mod_frames,
            targets: &self.targets,
        };
        let form = build_block_expr_form(inherited, expr);
        self.emit_candidate(ContextKind::Block, span, input_tokens, form);
    }

    /// Emit one candidate with its measured input work.
    fn emit_candidate(
        &mut self,
        kind: ContextKind,
        span: Span,
        input_tokens: usize,
        form: CanonicalForm,
    ) {
        let item = self.item_path.join("::");
        (self.emit)(
            Context {
                kind,
                span,
                item: item.as_str(),
            },
            form,
        );
        self.work.contexts += 1;
        self.work.input_tokens += input_tokens;
    }

    /// Push one item path segment.
    fn push_item_path(&mut self, ident: &Ident) {
        self.item_path.push(ident.to_string());
    }

    /// Push one written item path segment.
    fn push_item_path_str(&mut self, name: String) {
        self.item_path.push(name);
    }

    /// Pop one item path segment.
    fn pop_item_path(&mut self) {
        self.item_path.pop();
    }

    fn observe(&mut self, attrs: &[syn::Attribute]) -> bool {
        let frame = self.frames.last_mut().expect("a scope frame");
        let previous = frame.observed;
        frame.observed |= crate::context::live_attr(attrs);
        previous
    }

    fn restore_observation(&mut self, observed: bool) {
        self.frames.last_mut().expect("a scope frame").observed = observed;
    }
}

impl Visit<'_> for Walker<'_> {
    fn visit_file(&mut self, file: &syn::File) {
        self.observe(&file.attrs);
        prebind_items(
            &mut self.frames,
            &mut self.mod_frames,
            &mut self.mod_origins,
            &mut self.id,
            file.items.iter(),
        );
        // A `macro_rules!` of a std name or a `#[macro_use] extern crate` can reach any call.
        self.frames.last_mut().expect("a scope frame").std_rebound |=
            crate::drift::file_rebound(file);
        self.bind_scope_uses(file.items.iter().filter_map(|item| match item {
            syn::Item::Use(u) => Some(u),
            _ => None,
        }));
        syn::visit::visit_file(self, file);
    }

    fn visit_item(&mut self, item: &syn::Item) {
        let observed = self.observe(crate::helpers::item_attrs(item));
        syn::visit::visit_item(self, item);
        self.restore_observation(observed);
    }

    fn visit_expr(&mut self, expr: &syn::Expr) {
        let observed = self.observe(crate::drift::expr_attrs(expr));
        syn::visit::visit_expr(self, expr);
        self.restore_observation(observed);
    }

    fn visit_block(&mut self, block: &syn::Block) {
        self.frames.push(Frame::default());
        prebind_items(
            &mut self.frames,
            &mut self.mod_frames,
            &mut self.mod_origins,
            &mut self.id,
            block.stmts.iter().filter_map(|stmt| match stmt {
                syn::Stmt::Item(item) => Some(item),
                _ => None,
            }),
        );
        self.bind_scope_uses(block.stmts.iter().filter_map(|stmt| match stmt {
            syn::Stmt::Item(syn::Item::Use(u)) => Some(u),
            _ => None,
        }));
        syn::visit::visit_block(self, block);
        self.frames.pop();
    }

    fn visit_local(&mut self, local: &syn::Local) {
        // The initializer resolves under the outer bindings.
        if let Some(init) = &local.init {
            syn::visit::visit_expr(self, &init.expr);
            if let Some(diverge) = &init.diverge {
                syn::visit::visit_expr(self, &diverge.1);
            }
        }
        let mut names = Vec::new();
        pat_names(&local.pat, &mut names);
        for name in &names {
            self.bind(Ns::Value, name, Origin::Let);
        }
        syn::visit::visit_pat(self, &local.pat);
    }

    // Imports are bound by their enclosing scope.
    fn visit_item_use(&mut self, _: &syn::ItemUse) {}

    fn visit_item_fn(&mut self, item: &syn::ItemFn) {
        self.push_item_path(&item.sig.ident);
        self.visit_fn(&item.sig, &item.block);
        self.pop_item_path();
    }

    fn visit_item_mod(&mut self, item: &syn::ItemMod) {
        self.push_item_path(&item.ident);
        if let Some((_, items)) = &item.content {
            let id = *self
                .mod_origins
                .get(&core::ptr::from_ref(item))
                .expect("a module is prebound");
            let frame = self.mod_frames.remove(&id).unwrap_or_default();
            self.frames.push(frame);
            self.inline_depth += 1;
            self.bind_scope_uses(items.iter().filter_map(|item| match item {
                syn::Item::Use(u) => Some(u),
                _ => None,
            }));
            for item in items {
                self.visit_item(item);
            }
            self.inline_depth -= 1;
            let frame = self.frames.pop().expect("a scope frame");
            self.mod_frames.insert(id, frame);
        }
        self.pop_item_path();
    }

    fn visit_item_impl(&mut self, item: &syn::ItemImpl) {
        self.frames.push(Frame::default());
        if let Some(name) = single_segment_type_name(&item.self_ty)
            && let Some(binding) = self.lookup(&[Ns::Type], &name)
        {
            self.top_bind(Ns::Type, "Self", binding.clone());
        }
        self.push_item_path_str(self_type_string(&item.self_ty));
        let has_generics = item.generics.lt_token.is_some();
        if has_generics {
            self.begin_generics(&item.generics);
        }
        syn::visit::visit_item_impl(self, item);
        if has_generics {
            self.frames.pop();
        }
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_item_trait(&mut self, item: &syn::ItemTrait) {
        self.push_item_path(&item.ident);
        let id = self.bind_item_name(Ns::Type, &item.ident);
        self.begin_generics(&item.generics);
        self.top_bind(
            Ns::Type,
            "Self",
            Binding {
                id,
                canon: String::new(),
                origin: Origin::SelfTy,
                prim: None,
                port: 0,
                value_port: None,
                target: None,
                raw: false,
                helper: None,
                macro_resolution: None,
            },
        );
        syn::visit::visit_item_trait(self, item);
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_item_struct(&mut self, item: &syn::ItemStruct) {
        self.push_item_path(&item.ident);
        self.bind_item_name(Ns::Type, &item.ident);
        self.begin_generics(&item.generics);
        syn::visit::visit_item_struct(self, item);
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_item_enum(&mut self, item: &syn::ItemEnum) {
        self.push_item_path(&item.ident);
        self.bind_item_name(Ns::Type, &item.ident);
        self.begin_generics(&item.generics);
        syn::visit::visit_item_enum(self, item);
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_item_union(&mut self, item: &syn::ItemUnion) {
        self.push_item_path(&item.ident);
        self.bind_item_name(Ns::Type, &item.ident);
        self.begin_generics(&item.generics);
        syn::visit::visit_item_union(self, item);
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_item_type(&mut self, item: &syn::ItemType) {
        self.push_item_path(&item.ident);
        self.bind_item_name(Ns::Type, &item.ident);
        self.begin_generics(&item.generics);
        syn::visit::visit_item_type(self, item);
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_item_trait_alias(&mut self, item: &syn::ItemTraitAlias) {
        self.push_item_path(&item.ident);
        self.bind_item_name(Ns::Type, &item.ident);
        self.begin_generics(&item.generics);
        syn::visit::visit_item_trait_alias(self, item);
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_item_const(&mut self, item: &syn::ItemConst) {
        self.push_item_path(&item.ident);
        self.bind_item_name(Ns::Value, &item.ident);
        syn::visit::visit_item_const(self, item);
        self.pop_item_path();
    }

    fn visit_item_static(&mut self, item: &syn::ItemStatic) {
        self.push_item_path(&item.ident);
        self.bind_item_name(Ns::Value, &item.ident);
        syn::visit::visit_item_static(self, item);
        self.pop_item_path();
    }

    fn visit_item_macro(&mut self, item: &syn::ItemMacro) {
        // `macro_rules!` binds from its declaration onward.
        if let Some(ident) = &item.ident {
            let name = ident.to_string();
            if self
                .frames
                .last()
                .and_then(|frame| frame.lookup(Ns::Macro, &name))
                .is_none_or(|binding| binding.origin != Origin::MacroRule)
            {
                self.bind(Ns::Macro, &name, Origin::MacroRule);
            }
        }
        syn::visit::visit_item_macro(self, item);
    }

    fn visit_foreign_item_fn(&mut self, item: &syn::ForeignItemFn) {
        self.push_item_path(&item.sig.ident);
        self.begin_generics(&item.sig.generics);
        syn::visit::visit_foreign_item_fn(self, item);
        self.frames.pop();
        self.pop_item_path();
    }

    fn visit_impl_item(&mut self, item: &syn::ImplItem) {
        let attrs: &[syn::Attribute] = match item {
            syn::ImplItem::Fn(item) => &item.attrs,
            syn::ImplItem::Const(item) => &item.attrs,
            syn::ImplItem::Type(item) => &item.attrs,
            syn::ImplItem::Macro(item) => &item.attrs,
            _ => &[],
        };
        let observed = self.observe(attrs);
        match item {
            syn::ImplItem::Fn(f) => {
                self.push_item_path(&f.sig.ident);
                self.visit_fn(&f.sig, &f.block);
                self.pop_item_path();
            }
            syn::ImplItem::Const(c) => {
                self.push_item_path(&c.ident);
                syn::visit::visit_impl_item_const(self, c);
                self.pop_item_path();
            }
            syn::ImplItem::Type(t) => {
                self.push_item_path(&t.ident);
                syn::visit::visit_impl_item_type(self, t);
                self.pop_item_path();
            }
            syn::ImplItem::Macro(m) => {
                syn::visit::visit_impl_item_macro(self, m);
            }
            syn::ImplItem::Verbatim(_) | _ => {}
        }
        self.restore_observation(observed);
    }

    fn visit_trait_item(&mut self, item: &syn::TraitItem) {
        let attrs: &[syn::Attribute] = match item {
            syn::TraitItem::Fn(item) => &item.attrs,
            syn::TraitItem::Const(item) => &item.attrs,
            syn::TraitItem::Type(item) => &item.attrs,
            syn::TraitItem::Macro(item) => &item.attrs,
            _ => &[],
        };
        let observed = self.observe(attrs);
        match item {
            syn::TraitItem::Fn(f) => {
                self.push_item_path(&f.sig.ident);
                if let Some(body) = &f.default {
                    self.visit_fn(&f.sig, body);
                } else {
                    self.begin_generics(&f.sig.generics);
                    syn::visit::visit_signature(self, &f.sig);
                    self.frames.pop();
                }
                self.pop_item_path();
            }
            syn::TraitItem::Const(c) => {
                self.push_item_path(&c.ident);
                syn::visit::visit_trait_item_const(self, c);
                self.pop_item_path();
            }
            syn::TraitItem::Type(t) => {
                self.push_item_path(&t.ident);
                syn::visit::visit_trait_item_type(self, t);
                self.pop_item_path();
            }
            syn::TraitItem::Macro(m) => {
                syn::visit::visit_trait_item_macro(self, m);
            }
            syn::TraitItem::Verbatim(_) | _ => {}
        }
        self.restore_observation(observed);
    }

    fn visit_expr_closure(&mut self, closure: &syn::ExprClosure) {
        let (span, input_tokens) = source_span_and_leaf_tokens(closure);
        let inherited = Inherited {
            frames: &self.frames,
            mod_frames: &self.mod_frames,
            targets: &self.targets,
        };
        let form = build_closure_form(inherited, closure);
        self.emit_candidate(ContextKind::Closure, span, input_tokens, form);
        self.frames.push(Frame::default());
        if let Some(bound) = &closure.lifetimes {
            syn::visit::visit_bound_lifetimes(self, bound);
        }
        let mut names = Vec::new();
        for input in &closure.inputs {
            pat_names(input, &mut names);
        }
        for name in &names {
            self.bind(Ns::Value, name, Origin::Closure);
        }
        for input in &closure.inputs {
            syn::visit::visit_pat(self, input);
        }
        syn::visit::visit_return_type(self, &closure.output);
        syn::visit::visit_expr(self, &closure.body);
        self.frames.pop();
    }

    fn visit_expr_block(&mut self, expr: &syn::ExprBlock) {
        self.emit_block_expr(syn::Expr::Block(expr.clone()));
        if let Some(label) = &expr.label {
            self.bind(Ns::Label, &label.name.ident.to_string(), Origin::Label);
        }
        self.visit_block(&expr.block);
    }

    fn visit_expr_unsafe(&mut self, expr: &syn::ExprUnsafe) {
        self.emit_block_expr(syn::Expr::Unsafe(expr.clone()));
        syn::visit::visit_expr_unsafe(self, expr);
    }

    fn visit_expr_async(&mut self, expr: &syn::ExprAsync) {
        self.emit_block_expr(syn::Expr::Async(expr.clone()));
        syn::visit::visit_expr_async(self, expr);
    }

    fn visit_expr_try_block(&mut self, expr: &syn::ExprTryBlock) {
        self.emit_block_expr(syn::Expr::TryBlock(expr.clone()));
        syn::visit::visit_expr_try_block(self, expr);
    }

    fn visit_expr_const(&mut self, expr: &syn::ExprConst) {
        self.emit_block_expr(syn::Expr::Const(expr.clone()));
        syn::visit::visit_expr_const(self, expr);
    }

    fn visit_expr_if(&mut self, expr: &syn::ExprIf) {
        // Condition bindings are visible in the then branch only.
        self.frames.push(Frame::default());
        self.walk_let_cond(&expr.cond);
        self.emit_block_slot(&expr.then_branch);
        self.visit_block(&expr.then_branch);
        self.frames.pop();
        if let Some((_, otherwise)) = &expr.else_branch {
            syn::visit::visit_expr(self, otherwise);
        }
    }

    fn visit_expr_for_loop(&mut self, for_loop: &syn::ExprForLoop) {
        // The iterable resolves under the outer bindings.
        syn::visit::visit_expr(self, &for_loop.expr);
        self.frames.push(Frame::default());
        if let Some(label) = &for_loop.label {
            self.bind(Ns::Label, &label.name.ident.to_string(), Origin::Label);
        }
        let mut names = Vec::new();
        pat_names(&for_loop.pat, &mut names);
        for name in &names {
            self.bind(Ns::Value, name, Origin::Let);
        }
        self.emit_block_slot(&for_loop.body);
        self.visit_block(&for_loop.body);
        self.frames.pop();
    }

    fn visit_expr_while(&mut self, expr: &syn::ExprWhile) {
        self.frames.push(Frame::default());
        if let Some(label) = &expr.label {
            self.bind(Ns::Label, &label.name.ident.to_string(), Origin::Label);
        }
        self.walk_let_cond(&expr.cond);
        self.emit_block_slot(&expr.body);
        self.visit_block(&expr.body);
        self.frames.pop();
    }

    fn visit_expr_loop(&mut self, expr: &syn::ExprLoop) {
        self.frames.push(Frame::default());
        if let Some(label) = &expr.label {
            self.bind(Ns::Label, &label.name.ident.to_string(), Origin::Label);
        }
        self.emit_block_slot(&expr.body);
        self.visit_block(&expr.body);
        self.frames.pop();
    }

    fn visit_arm(&mut self, arm: &syn::Arm) {
        let (span, input_tokens) = source_span_and_leaf_tokens(arm);
        let inherited = Inherited {
            frames: &self.frames,
            mod_frames: &self.mod_frames,
            targets: &self.targets,
        };
        let form = build_arm_form(inherited, arm);
        self.emit_candidate(ContextKind::Arm, span, input_tokens, form);
        self.frames.push(Frame::default());
        let mut names = Vec::new();
        pat_names(&arm.pat, &mut names);
        for name in &names {
            self.bind(Ns::Value, name, Origin::Let);
        }
        syn::visit::visit_arm(self, arm);
        self.frames.pop();
    }

    fn visit_pat_guard(&mut self, node: &syn::PatGuard) {
        syn::visit::visit_pat(self, &node.pat);
        self.walk_let_cond(&node.guard);
    }

    fn visit_bound_lifetimes(&mut self, node: &syn::BoundLifetimes) {
        for param in &node.lifetimes {
            if let syn::GenericParam::Lifetime(lifetime) = param {
                self.bind(
                    Ns::Lifetime,
                    &lifetime.lifetime.ident.to_string(),
                    Origin::Lifetime,
                );
            }
        }
        syn::visit::visit_bound_lifetimes(self, node);
    }

    fn visit_trait_bound(&mut self, node: &syn::TraitBound) {
        // Same owner scoping for `for<'a>` on `dyn` and `impl` bounds.
        self.frames.push(Frame::default());
        syn::visit::visit_trait_bound(self, node);
        self.frames.pop();
    }

    fn visit_type_fn_ptr(&mut self, node: &syn::TypeFnPtr) {
        // Higher-ranked lifetimes cannot capture outer loop labels.
        self.frames.push(Frame::default());
        syn::visit::visit_type_fn_ptr(self, node);
        self.frames.pop();
    }
}

/// Normalize one cloned function body against the inherited environment, reading early
/// returns before the tail as `else` branches when `early`.
fn build_function_body_form(
    inherited: Inherited<'_>,
    body: &syn::Block,
    early: bool,
) -> CanonicalForm {
    let mut block = body.clone();
    let frames = inherited.frames;
    let mut renamer = Renamer::contextual(inherited);
    if !renamer.observes_tokens() {
        crate::drift::normalize_block(&mut block, frames);
    }
    renamer.normalize_return_body(&mut block, early);
    renamer.visit_block_mut(&mut block);
    let facts = renamer.into_reference_facts();
    crate::form::from_node(&block, &facts)
}

/// Normalize one cloned block slot, a loop body or an `if` branch.
fn build_block_slot_form(inherited: Inherited<'_>, block: &syn::Block) -> CanonicalForm {
    let mut block = block.clone();
    let frames = inherited.frames;
    let mut renamer = Renamer::contextual(inherited);
    if !renamer.observes_tokens() {
        crate::drift::normalize_block(&mut block, frames);
    }
    renamer.visit_block_mut(&mut block);
    let facts = renamer.into_reference_facts();
    crate::form::from_node(&block, &facts)
}

/// Normalize one cloned block expression, the label and block included.
fn build_block_expr_form(inherited: Inherited<'_>, expr: syn::Expr) -> CanonicalForm {
    let mut expr = expr;
    let frames = inherited.frames;
    let mut renamer = Renamer::contextual(inherited);
    if !renamer.observes_tokens() {
        crate::drift::normalize_expr(&mut expr, frames);
    }
    renamer.visit_expr_mut(&mut expr);
    let facts = renamer.into_reference_facts();
    crate::form::from_node(&expr, &facts)
}

/// Normalize one cloned match arm.
fn build_arm_form(inherited: Inherited<'_>, arm: &syn::Arm) -> CanonicalForm {
    let mut arm = arm.clone();
    let frames = inherited.frames;
    let mut renamer = Renamer::contextual(inherited);
    if !renamer.observes_tokens() {
        crate::drift::normalize_arm(&mut arm, frames);
    }
    renamer.visit_arm_mut(&mut arm);
    let facts = renamer.into_reference_facts();
    crate::form::from_node(&arm, &facts)
}

/// Normalize one cloned closure, inputs and body included.
fn build_closure_form(inherited: Inherited<'_>, closure: &syn::ExprClosure) -> CanonicalForm {
    let mut expr = syn::Expr::Closure(closure.clone());
    let frames = inherited.frames;
    let mut renamer = Renamer::contextual(inherited);
    if !renamer.observes_tokens() {
        crate::drift::normalize_expr(&mut expr, frames);
    }
    renamer.visit_expr_mut(&mut expr);
    let facts = renamer.into_reference_facts();
    crate::form::from_node(&expr, &facts)
}