rustc_hir/
intravisit.rs

1//! HIR walker for walking the contents of nodes.
2//!
3//! Here are the three available patterns for the visitor strategy,
4//! in roughly the order of desirability:
5//!
6//! 1. **Shallow visit**: Get a simple callback for every item (or item-like thing) in the HIR.
7//!    - Example: find all items with a `#[foo]` attribute on them.
8//!    - How: Use the `hir_crate_items` or `hir_module_items` query to traverse over item-like ids
9//!       (ItemId, TraitItemId, etc.) and use tcx.def_kind and `tcx.hir_item*(id)` to filter and
10//!       access actual item-like thing, respectively.
11//!    - Pro: Efficient; just walks the lists of item ids and gives users control whether to access
12//!       the hir_owners themselves or not.
13//!    - Con: Don't get information about nesting
14//!    - Con: Don't have methods for specific bits of HIR, like "on
15//!      every expr, do this".
16//! 2. **Deep visit**: Want to scan for specific kinds of HIR nodes within
17//!    an item, but don't care about how item-like things are nested
18//!    within one another.
19//!    - Example: Examine each expression to look for its type and do some check or other.
20//!    - How: Implement `intravisit::Visitor` and override the `NestedFilter` type to
21//!      `nested_filter::OnlyBodies` (and implement `maybe_tcx`), and use
22//!      `tcx.hir_visit_all_item_likes_in_crate(&mut visitor)`. Within your
23//!      `intravisit::Visitor` impl, implement methods like `visit_expr()` (don't forget to invoke
24//!      `intravisit::walk_expr()` to keep walking the subparts).
25//!    - Pro: Visitor methods for any kind of HIR node, not just item-like things.
26//!    - Pro: Integrates well into dependency tracking.
27//!    - Con: Don't get information about nesting between items
28//! 3. **Nested visit**: Want to visit the whole HIR and you care about the nesting between
29//!    item-like things.
30//!    - Example: Lifetime resolution, which wants to bring lifetimes declared on the
31//!      impl into scope while visiting the impl-items, and then back out again.
32//!    - How: Implement `intravisit::Visitor` and override the `NestedFilter` type to
33//!      `nested_filter::All` (and implement `maybe_tcx`). Walk your crate with
34//!      `tcx.hir_walk_toplevel_module(visitor)`.
35//!    - Pro: Visitor methods for any kind of HIR node, not just item-like things.
36//!    - Pro: Preserves nesting information
37//!    - Con: Does not integrate well into dependency tracking.
38//!
39//! If you have decided to use this visitor, here are some general
40//! notes on how to do so:
41//!
42//! Each overridden visit method has full control over what
43//! happens with its node, it can do its own traversal of the node's children,
44//! call `intravisit::walk_*` to apply the default traversal algorithm, or prevent
45//! deeper traversal by doing nothing.
46//!
47//! When visiting the HIR, the contents of nested items are NOT visited
48//! by default. This is different from the AST visitor, which does a deep walk.
49//! Hence this module is called `intravisit`; see the method `visit_nested_item`
50//! for more details.
51//!
52//! Note: it is an important invariant that the default visitor walks
53//! the body of a function in "execution order" - more concretely, if
54//! we consider the reverse post-order (RPO) of the CFG implied by the HIR,
55//! then a pre-order traversal of the HIR is consistent with the CFG RPO
56//! on the *initial CFG point* of each HIR node, while a post-order traversal
57//! of the HIR is consistent with the CFG RPO on each *final CFG point* of
58//! each CFG node.
59//!
60//! One thing that follows is that if HIR node A always starts/ends executing
61//! before HIR node B, then A appears in traversal pre/postorder before B,
62//! respectively. (This follows from RPO respecting CFG domination).
63//!
64//! This order consistency is required in a few places in rustc, for
65//! example coroutine inference, and possibly also HIR borrowck.
66
67use rustc_ast::Label;
68use rustc_ast::visit::{VisitorResult, try_visit, visit_opt, walk_list};
69use rustc_span::def_id::LocalDefId;
70use rustc_span::{Ident, Span, Symbol};
71
72use crate::hir::*;
73
74pub trait IntoVisitor<'hir> {
75    type Visitor: Visitor<'hir>;
76    fn into_visitor(&self) -> Self::Visitor;
77}
78
79#[derive(Copy, Clone, Debug)]
80pub enum FnKind<'a> {
81    /// `#[xxx] pub async/const/extern "Abi" fn foo()`
82    ItemFn(Ident, &'a Generics<'a>, FnHeader),
83
84    /// `fn foo(&self)`
85    Method(Ident, &'a FnSig<'a>),
86
87    /// `|x, y| {}`
88    Closure,
89}
90
91impl<'a> FnKind<'a> {
92    pub fn header(&self) -> Option<&FnHeader> {
93        match *self {
94            FnKind::ItemFn(_, _, ref header) => Some(header),
95            FnKind::Method(_, ref sig) => Some(&sig.header),
96            FnKind::Closure => None,
97        }
98    }
99
100    pub fn constness(self) -> Constness {
101        self.header().map_or(Constness::NotConst, |header| header.constness)
102    }
103
104    pub fn asyncness(self) -> IsAsync {
105        self.header().map_or(IsAsync::NotAsync, |header| header.asyncness)
106    }
107}
108
109/// HIR things retrievable from `TyCtxt`, avoiding an explicit dependence on
110/// `TyCtxt`. The only impls are for `!` (where these functions are never
111/// called) and `TyCtxt` (in `rustc_middle`).
112pub trait HirTyCtxt<'hir> {
113    /// Retrieves the `Node` corresponding to `id`.
114    fn hir_node(&self, hir_id: HirId) -> Node<'hir>;
115    fn hir_body(&self, id: BodyId) -> &'hir Body<'hir>;
116    fn hir_item(&self, id: ItemId) -> &'hir Item<'hir>;
117    fn hir_trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir>;
118    fn hir_impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir>;
119    fn hir_foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir>;
120}
121
122// Used when no tcx is actually available, forcing manual implementation of nested visitors.
123impl<'hir> HirTyCtxt<'hir> for ! {
124    fn hir_node(&self, _: HirId) -> Node<'hir> {
125        unreachable!();
126    }
127    fn hir_body(&self, _: BodyId) -> &'hir Body<'hir> {
128        unreachable!();
129    }
130    fn hir_item(&self, _: ItemId) -> &'hir Item<'hir> {
131        unreachable!();
132    }
133    fn hir_trait_item(&self, _: TraitItemId) -> &'hir TraitItem<'hir> {
134        unreachable!();
135    }
136    fn hir_impl_item(&self, _: ImplItemId) -> &'hir ImplItem<'hir> {
137        unreachable!();
138    }
139    fn hir_foreign_item(&self, _: ForeignItemId) -> &'hir ForeignItem<'hir> {
140        unreachable!();
141    }
142}
143
144pub mod nested_filter {
145    use super::HirTyCtxt;
146
147    /// Specifies what nested things a visitor wants to visit. By "nested
148    /// things", we are referring to bits of HIR that are not directly embedded
149    /// within one another but rather indirectly, through a table in the crate.
150    /// This is done to control dependencies during incremental compilation: the
151    /// non-inline bits of HIR can be tracked and hashed separately.
152    ///
153    /// The most common choice is `OnlyBodies`, which will cause the visitor to
154    /// visit fn bodies for fns that it encounters, and closure bodies, but
155    /// skip over nested item-like things.
156    ///
157    /// See the comments at [`rustc_hir::intravisit`] for more details on the overall
158    /// visit strategy.
159    pub trait NestedFilter<'hir> {
160        type MaybeTyCtxt: HirTyCtxt<'hir>;
161
162        /// Whether the visitor visits nested "item-like" things.
163        /// E.g., item, impl-item.
164        const INTER: bool;
165        /// Whether the visitor visits "intra item-like" things.
166        /// E.g., function body, closure, `AnonConst`
167        const INTRA: bool;
168    }
169
170    /// Do not visit any nested things. When you add a new
171    /// "non-nested" thing, you will want to audit such uses to see if
172    /// they remain valid.
173    ///
174    /// Use this if you are only walking some particular kind of tree
175    /// (i.e., a type, or fn signature) and you don't want to thread a
176    /// `tcx` around.
177    pub struct None(());
178    impl NestedFilter<'_> for None {
179        type MaybeTyCtxt = !;
180        const INTER: bool = false;
181        const INTRA: bool = false;
182    }
183}
184
185use nested_filter::NestedFilter;
186
187/// Each method of the Visitor trait is a hook to be potentially
188/// overridden. Each method's default implementation recursively visits
189/// the substructure of the input via the corresponding `walk` method;
190/// e.g., the `visit_mod` method by default calls `intravisit::walk_mod`.
191///
192/// Note that this visitor does NOT visit nested items by default
193/// (this is why the module is called `intravisit`, to distinguish it
194/// from the AST's `visit` module, which acts differently). If you
195/// simply want to visit all items in the crate in some order, you
196/// should call `tcx.hir_visit_all_item_likes_in_crate`. Otherwise, see the comment
197/// on `visit_nested_item` for details on how to visit nested items.
198///
199/// If you want to ensure that your code handles every variant
200/// explicitly, you need to override each method. (And you also need
201/// to monitor future changes to `Visitor` in case a new method with a
202/// new default implementation gets introduced.)
203///
204/// Every `walk_*` method uses deconstruction to access fields of structs and
205/// enums. This will result in a compile error if a field is added, which makes
206/// it more likely the appropriate visit call will be added for it.
207pub trait Visitor<'v>: Sized {
208    // This type should not be overridden, it exists for convenient usage as `Self::MaybeTyCtxt`.
209    type MaybeTyCtxt: HirTyCtxt<'v> = <Self::NestedFilter as NestedFilter<'v>>::MaybeTyCtxt;
210
211    ///////////////////////////////////////////////////////////////////////////
212    // Nested items.
213
214    /// Override this type to control which nested HIR are visited; see
215    /// [`NestedFilter`] for details. If you override this type, you
216    /// must also override [`maybe_tcx`](Self::maybe_tcx).
217    ///
218    /// **If for some reason you want the nested behavior, but don't
219    /// have a `tcx` at your disposal:** then override the
220    /// `visit_nested_XXX` methods. If a new `visit_nested_XXX` variant is
221    /// added in the future, it will cause a panic which can be detected
222    /// and fixed appropriately.
223    type NestedFilter: NestedFilter<'v> = nested_filter::None;
224
225    /// The result type of the `visit_*` methods. Can be either `()`,
226    /// or `ControlFlow<T>`.
227    type Result: VisitorResult = ();
228
229    /// If `type NestedFilter` is set to visit nested items, this method
230    /// must also be overridden to provide a map to retrieve nested items.
231    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
232        panic!(
233            "maybe_tcx must be implemented or consider using \
234            `type NestedFilter = nested_filter::None` (the default)"
235        );
236    }
237
238    /// Invoked when a nested item is encountered. By default, when
239    /// `Self::NestedFilter` is `nested_filter::None`, this method does
240    /// nothing. **You probably don't want to override this method** --
241    /// instead, override [`Self::NestedFilter`] or use the "shallow" or
242    /// "deep" visit patterns described at
243    /// [`rustc_hir::intravisit`]. The only reason to override
244    /// this method is if you want a nested pattern but cannot supply a
245    /// `TyCtxt`; see `maybe_tcx` for advice.
246    fn visit_nested_item(&mut self, id: ItemId) -> Self::Result {
247        if Self::NestedFilter::INTER {
248            let item = self.maybe_tcx().hir_item(id);
249            try_visit!(self.visit_item(item));
250        }
251        Self::Result::output()
252    }
253
254    /// Like `visit_nested_item()`, but for trait items. See
255    /// `visit_nested_item()` for advice on when to override this
256    /// method.
257    fn visit_nested_trait_item(&mut self, id: TraitItemId) -> Self::Result {
258        if Self::NestedFilter::INTER {
259            let item = self.maybe_tcx().hir_trait_item(id);
260            try_visit!(self.visit_trait_item(item));
261        }
262        Self::Result::output()
263    }
264
265    /// Like `visit_nested_item()`, but for impl items. See
266    /// `visit_nested_item()` for advice on when to override this
267    /// method.
268    fn visit_nested_impl_item(&mut self, id: ImplItemId) -> Self::Result {
269        if Self::NestedFilter::INTER {
270            let item = self.maybe_tcx().hir_impl_item(id);
271            try_visit!(self.visit_impl_item(item));
272        }
273        Self::Result::output()
274    }
275
276    /// Like `visit_nested_item()`, but for foreign items. See
277    /// `visit_nested_item()` for advice on when to override this
278    /// method.
279    fn visit_nested_foreign_item(&mut self, id: ForeignItemId) -> Self::Result {
280        if Self::NestedFilter::INTER {
281            let item = self.maybe_tcx().hir_foreign_item(id);
282            try_visit!(self.visit_foreign_item(item));
283        }
284        Self::Result::output()
285    }
286
287    /// Invoked to visit the body of a function, method or closure. Like
288    /// `visit_nested_item`, does nothing by default unless you override
289    /// `Self::NestedFilter`.
290    fn visit_nested_body(&mut self, id: BodyId) -> Self::Result {
291        if Self::NestedFilter::INTRA {
292            let body = self.maybe_tcx().hir_body(id);
293            try_visit!(self.visit_body(body));
294        }
295        Self::Result::output()
296    }
297
298    fn visit_param(&mut self, param: &'v Param<'v>) -> Self::Result {
299        walk_param(self, param)
300    }
301
302    /// Visits the top-level item and (optionally) nested items / impl items. See
303    /// `visit_nested_item` for details.
304    fn visit_item(&mut self, i: &'v Item<'v>) -> Self::Result {
305        walk_item(self, i)
306    }
307
308    fn visit_body(&mut self, b: &Body<'v>) -> Self::Result {
309        walk_body(self, b)
310    }
311
312    ///////////////////////////////////////////////////////////////////////////
313
314    fn visit_id(&mut self, _hir_id: HirId) -> Self::Result {
315        Self::Result::output()
316    }
317    fn visit_name(&mut self, _name: Symbol) -> Self::Result {
318        Self::Result::output()
319    }
320    fn visit_ident(&mut self, ident: Ident) -> Self::Result {
321        walk_ident(self, ident)
322    }
323    fn visit_mod(&mut self, m: &'v Mod<'v>, _s: Span, _n: HirId) -> Self::Result {
324        walk_mod(self, m)
325    }
326    fn visit_foreign_item(&mut self, i: &'v ForeignItem<'v>) -> Self::Result {
327        walk_foreign_item(self, i)
328    }
329    fn visit_local(&mut self, l: &'v LetStmt<'v>) -> Self::Result {
330        walk_local(self, l)
331    }
332    fn visit_block(&mut self, b: &'v Block<'v>) -> Self::Result {
333        walk_block(self, b)
334    }
335    fn visit_stmt(&mut self, s: &'v Stmt<'v>) -> Self::Result {
336        walk_stmt(self, s)
337    }
338    fn visit_arm(&mut self, a: &'v Arm<'v>) -> Self::Result {
339        walk_arm(self, a)
340    }
341    fn visit_pat(&mut self, p: &'v Pat<'v>) -> Self::Result {
342        walk_pat(self, p)
343    }
344    fn visit_pat_field(&mut self, f: &'v PatField<'v>) -> Self::Result {
345        walk_pat_field(self, f)
346    }
347    fn visit_pat_expr(&mut self, expr: &'v PatExpr<'v>) -> Self::Result {
348        walk_pat_expr(self, expr)
349    }
350    fn visit_lit(&mut self, _hir_id: HirId, _lit: Lit, _negated: bool) -> Self::Result {
351        Self::Result::output()
352    }
353    fn visit_anon_const(&mut self, c: &'v AnonConst) -> Self::Result {
354        walk_anon_const(self, c)
355    }
356    fn visit_inline_const(&mut self, c: &'v ConstBlock) -> Self::Result {
357        walk_inline_const(self, c)
358    }
359
360    fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg<'v>) -> Self::Result {
361        walk_generic_arg(self, generic_arg)
362    }
363
364    /// All types are treated as ambiguous types for the purposes of hir visiting in
365    /// order to ensure that visitors can handle infer vars without it being too error-prone.
366    ///
367    /// The [`Visitor::visit_infer`] method should be overridden in order to handle infer vars.
368    fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) -> Self::Result {
369        walk_ty(self, t)
370    }
371
372    fn visit_const_item_rhs(&mut self, c: ConstItemRhs<'v>) -> Self::Result {
373        walk_const_item_rhs(self, c)
374    }
375
376    /// All consts are treated as ambiguous consts for the purposes of hir visiting in
377    /// order to ensure that visitors can handle infer vars without it being too error-prone.
378    ///
379    /// The [`Visitor::visit_infer`] method should be overridden in order to handle infer vars.
380    fn visit_const_arg(&mut self, c: &'v ConstArg<'v, AmbigArg>) -> Self::Result {
381        walk_const_arg(self, c)
382    }
383
384    #[allow(unused_variables)]
385    fn visit_infer(&mut self, inf_id: HirId, inf_span: Span, kind: InferKind<'v>) -> Self::Result {
386        self.visit_id(inf_id)
387    }
388
389    fn visit_lifetime(&mut self, lifetime: &'v Lifetime) -> Self::Result {
390        walk_lifetime(self, lifetime)
391    }
392
393    fn visit_expr(&mut self, ex: &'v Expr<'v>) -> Self::Result {
394        walk_expr(self, ex)
395    }
396    fn visit_expr_field(&mut self, field: &'v ExprField<'v>) -> Self::Result {
397        walk_expr_field(self, field)
398    }
399    fn visit_pattern_type_pattern(&mut self, p: &'v TyPat<'v>) -> Self::Result {
400        walk_ty_pat(self, p)
401    }
402    fn visit_generic_param(&mut self, p: &'v GenericParam<'v>) -> Self::Result {
403        walk_generic_param(self, p)
404    }
405    fn visit_const_param_default(&mut self, _param: HirId, ct: &'v ConstArg<'v>) -> Self::Result {
406        walk_const_param_default(self, ct)
407    }
408    fn visit_generics(&mut self, g: &'v Generics<'v>) -> Self::Result {
409        walk_generics(self, g)
410    }
411    fn visit_where_predicate(&mut self, predicate: &'v WherePredicate<'v>) -> Self::Result {
412        walk_where_predicate(self, predicate)
413    }
414    fn visit_fn_ret_ty(&mut self, ret_ty: &'v FnRetTy<'v>) -> Self::Result {
415        walk_fn_ret_ty(self, ret_ty)
416    }
417    fn visit_fn_decl(&mut self, fd: &'v FnDecl<'v>) -> Self::Result {
418        walk_fn_decl(self, fd)
419    }
420    fn visit_fn(
421        &mut self,
422        fk: FnKind<'v>,
423        fd: &'v FnDecl<'v>,
424        b: BodyId,
425        _: Span,
426        id: LocalDefId,
427    ) -> Self::Result {
428        walk_fn(self, fk, fd, b, id)
429    }
430    fn visit_use(&mut self, path: &'v UsePath<'v>, hir_id: HirId) -> Self::Result {
431        walk_use(self, path, hir_id)
432    }
433    fn visit_trait_item(&mut self, ti: &'v TraitItem<'v>) -> Self::Result {
434        walk_trait_item(self, ti)
435    }
436    fn visit_trait_item_ref(&mut self, ii: &'v TraitItemId) -> Self::Result {
437        walk_trait_item_ref(self, *ii)
438    }
439    fn visit_impl_item(&mut self, ii: &'v ImplItem<'v>) -> Self::Result {
440        walk_impl_item(self, ii)
441    }
442    fn visit_foreign_item_ref(&mut self, ii: &'v ForeignItemId) -> Self::Result {
443        walk_foreign_item_ref(self, *ii)
444    }
445    fn visit_impl_item_ref(&mut self, ii: &'v ImplItemId) -> Self::Result {
446        walk_impl_item_ref(self, *ii)
447    }
448    fn visit_trait_ref(&mut self, t: &'v TraitRef<'v>) -> Self::Result {
449        walk_trait_ref(self, t)
450    }
451    fn visit_param_bound(&mut self, bounds: &'v GenericBound<'v>) -> Self::Result {
452        walk_param_bound(self, bounds)
453    }
454    fn visit_precise_capturing_arg(&mut self, arg: &'v PreciseCapturingArg<'v>) -> Self::Result {
455        walk_precise_capturing_arg(self, arg)
456    }
457    fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef<'v>) -> Self::Result {
458        walk_poly_trait_ref(self, t)
459    }
460    fn visit_opaque_ty(&mut self, opaque: &'v OpaqueTy<'v>) -> Self::Result {
461        walk_opaque_ty(self, opaque)
462    }
463    fn visit_variant_data(&mut self, s: &'v VariantData<'v>) -> Self::Result {
464        walk_struct_def(self, s)
465    }
466    fn visit_field_def(&mut self, s: &'v FieldDef<'v>) -> Self::Result {
467        walk_field_def(self, s)
468    }
469    fn visit_enum_def(&mut self, enum_definition: &'v EnumDef<'v>) -> Self::Result {
470        walk_enum_def(self, enum_definition)
471    }
472    fn visit_variant(&mut self, v: &'v Variant<'v>) -> Self::Result {
473        walk_variant(self, v)
474    }
475    fn visit_label(&mut self, label: &'v Label) -> Self::Result {
476        walk_label(self, label)
477    }
478    // The span is that of the surrounding type/pattern/expr/whatever.
479    fn visit_qpath(&mut self, qpath: &'v QPath<'v>, id: HirId, _span: Span) -> Self::Result {
480        walk_qpath(self, qpath, id)
481    }
482    fn visit_path(&mut self, path: &Path<'v>, _id: HirId) -> Self::Result {
483        walk_path(self, path)
484    }
485    fn visit_path_segment(&mut self, path_segment: &'v PathSegment<'v>) -> Self::Result {
486        walk_path_segment(self, path_segment)
487    }
488    fn visit_generic_args(&mut self, generic_args: &'v GenericArgs<'v>) -> Self::Result {
489        walk_generic_args(self, generic_args)
490    }
491    fn visit_assoc_item_constraint(
492        &mut self,
493        constraint: &'v AssocItemConstraint<'v>,
494    ) -> Self::Result {
495        walk_assoc_item_constraint(self, constraint)
496    }
497    fn visit_attribute(&mut self, _attr: &'v Attribute) -> Self::Result {
498        Self::Result::output()
499    }
500    fn visit_defaultness(&mut self, defaultness: &'v Defaultness) -> Self::Result {
501        walk_defaultness(self, defaultness)
502    }
503    fn visit_inline_asm(&mut self, asm: &'v InlineAsm<'v>, id: HirId) -> Self::Result {
504        walk_inline_asm(self, asm, id)
505    }
506}
507
508pub trait VisitorExt<'v>: Visitor<'v> {
509    /// Extension trait method to visit types in unambiguous positions, this is not
510    /// directly on the [`Visitor`] trait as this method should never be overridden.
511    ///
512    /// Named `visit_ty_unambig` instead of `visit_unambig_ty` to aid in discovery
513    /// by IDes when `v.visit_ty` is written.
514    fn visit_ty_unambig(&mut self, t: &'v Ty<'v>) -> Self::Result {
515        walk_unambig_ty(self, t)
516    }
517    /// Extension trait method to visit consts in unambiguous positions, this is not
518    /// directly on the [`Visitor`] trait as this method should never be overridden.
519    ///
520    /// Named `visit_const_arg_unambig` instead of `visit_unambig_const_arg` to aid in
521    /// discovery by IDes when `v.visit_const_arg` is written.
522    fn visit_const_arg_unambig(&mut self, c: &'v ConstArg<'v>) -> Self::Result {
523        walk_unambig_const_arg(self, c)
524    }
525}
526impl<'v, V: Visitor<'v>> VisitorExt<'v> for V {}
527
528pub fn walk_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Param<'v>) -> V::Result {
529    let Param { hir_id, pat, ty_span: _, span: _ } = param;
530    try_visit!(visitor.visit_id(*hir_id));
531    visitor.visit_pat(pat)
532}
533
534pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) -> V::Result {
535    let Item { owner_id: _, kind, span: _, vis_span: _, has_delayed_lints: _ } = item;
536    try_visit!(visitor.visit_id(item.hir_id()));
537    match *kind {
538        ItemKind::ExternCrate(orig_name, ident) => {
539            visit_opt!(visitor, visit_name, orig_name);
540            try_visit!(visitor.visit_ident(ident));
541        }
542        ItemKind::Use(ref path, kind) => {
543            try_visit!(visitor.visit_use(path, item.hir_id()));
544            match kind {
545                UseKind::Single(ident) => try_visit!(visitor.visit_ident(ident)),
546                UseKind::Glob | UseKind::ListStem => {}
547            }
548        }
549        ItemKind::Static(_, ident, ref typ, body) => {
550            try_visit!(visitor.visit_ident(ident));
551            try_visit!(visitor.visit_ty_unambig(typ));
552            try_visit!(visitor.visit_nested_body(body));
553        }
554        ItemKind::Const(ident, ref generics, ref typ, rhs) => {
555            try_visit!(visitor.visit_ident(ident));
556            try_visit!(visitor.visit_generics(generics));
557            try_visit!(visitor.visit_ty_unambig(typ));
558            try_visit!(visitor.visit_const_item_rhs(rhs));
559        }
560        ItemKind::Fn { ident, sig, generics, body: body_id, .. } => {
561            try_visit!(visitor.visit_ident(ident));
562            try_visit!(visitor.visit_fn(
563                FnKind::ItemFn(ident, generics, sig.header),
564                sig.decl,
565                body_id,
566                item.span,
567                item.owner_id.def_id,
568            ));
569        }
570        ItemKind::Macro(ident, _def, _kind) => {
571            try_visit!(visitor.visit_ident(ident));
572        }
573        ItemKind::Mod(ident, ref module) => {
574            try_visit!(visitor.visit_ident(ident));
575            try_visit!(visitor.visit_mod(module, item.span, item.hir_id()));
576        }
577        ItemKind::ForeignMod { abi: _, items } => {
578            walk_list!(visitor, visit_foreign_item_ref, items);
579        }
580        ItemKind::GlobalAsm { asm: _, fake_body } => {
581            // Visit the fake body, which contains the asm statement.
582            // Therefore we should not visit the asm statement again
583            // outside of the body, or some visitors won't have their
584            // typeck results set correctly.
585            try_visit!(visitor.visit_nested_body(fake_body));
586        }
587        ItemKind::TyAlias(ident, ref generics, ref ty) => {
588            try_visit!(visitor.visit_ident(ident));
589            try_visit!(visitor.visit_generics(generics));
590            try_visit!(visitor.visit_ty_unambig(ty));
591        }
592        ItemKind::Enum(ident, ref generics, ref enum_definition) => {
593            try_visit!(visitor.visit_ident(ident));
594            try_visit!(visitor.visit_generics(generics));
595            try_visit!(visitor.visit_enum_def(enum_definition));
596        }
597        ItemKind::Impl(Impl { generics, of_trait, self_ty, items, constness: _ }) => {
598            try_visit!(visitor.visit_generics(generics));
599            if let Some(TraitImplHeader {
600                safety: _,
601                polarity: _,
602                defaultness: _,
603                defaultness_span: _,
604                trait_ref,
605            }) = of_trait
606            {
607                try_visit!(visitor.visit_trait_ref(trait_ref));
608            }
609            try_visit!(visitor.visit_ty_unambig(self_ty));
610            walk_list!(visitor, visit_impl_item_ref, items);
611        }
612        ItemKind::Struct(ident, ref generics, ref struct_definition)
613        | ItemKind::Union(ident, ref generics, ref struct_definition) => {
614            try_visit!(visitor.visit_ident(ident));
615            try_visit!(visitor.visit_generics(generics));
616            try_visit!(visitor.visit_variant_data(struct_definition));
617        }
618        ItemKind::Trait(
619            _constness,
620            _is_auto,
621            _safety,
622            ident,
623            ref generics,
624            bounds,
625            trait_item_refs,
626        ) => {
627            try_visit!(visitor.visit_ident(ident));
628            try_visit!(visitor.visit_generics(generics));
629            walk_list!(visitor, visit_param_bound, bounds);
630            walk_list!(visitor, visit_trait_item_ref, trait_item_refs);
631        }
632        ItemKind::TraitAlias(_constness, ident, ref generics, bounds) => {
633            try_visit!(visitor.visit_ident(ident));
634            try_visit!(visitor.visit_generics(generics));
635            walk_list!(visitor, visit_param_bound, bounds);
636        }
637    }
638    V::Result::output()
639}
640
641pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &Body<'v>) -> V::Result {
642    let Body { params, value } = body;
643    walk_list!(visitor, visit_param, *params);
644    visitor.visit_expr(*value)
645}
646
647pub fn walk_ident<'v, V: Visitor<'v>>(visitor: &mut V, ident: Ident) -> V::Result {
648    visitor.visit_name(ident.name)
649}
650
651pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>) -> V::Result {
652    let Mod { spans: _, item_ids } = module;
653    walk_list!(visitor, visit_nested_item, item_ids.iter().copied());
654    V::Result::output()
655}
656
657pub fn walk_foreign_item<'v, V: Visitor<'v>>(
658    visitor: &mut V,
659    foreign_item: &'v ForeignItem<'v>,
660) -> V::Result {
661    let ForeignItem { ident, kind, owner_id: _, span: _, vis_span: _, has_delayed_lints: _ } =
662        foreign_item;
663    try_visit!(visitor.visit_id(foreign_item.hir_id()));
664    try_visit!(visitor.visit_ident(*ident));
665
666    match *kind {
667        ForeignItemKind::Fn(ref sig, param_idents, ref generics) => {
668            try_visit!(visitor.visit_generics(generics));
669            try_visit!(visitor.visit_fn_decl(sig.decl));
670            for ident in param_idents.iter().copied() {
671                visit_opt!(visitor, visit_ident, ident);
672            }
673        }
674        ForeignItemKind::Static(ref typ, _, _) => {
675            try_visit!(visitor.visit_ty_unambig(typ));
676        }
677        ForeignItemKind::Type => (),
678    }
679    V::Result::output()
680}
681
682pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v LetStmt<'v>) -> V::Result {
683    // Intentionally visiting the expr first - the initialization expr
684    // dominates the local's definition.
685    let LetStmt { super_: _, pat, ty, init, els, hir_id, span: _, source: _ } = local;
686    visit_opt!(visitor, visit_expr, *init);
687    try_visit!(visitor.visit_id(*hir_id));
688    try_visit!(visitor.visit_pat(*pat));
689    visit_opt!(visitor, visit_block, *els);
690    visit_opt!(visitor, visit_ty_unambig, *ty);
691    V::Result::output()
692}
693
694pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block<'v>) -> V::Result {
695    let Block { stmts, expr, hir_id, rules: _, span: _, targeted_by_break: _ } = block;
696    try_visit!(visitor.visit_id(*hir_id));
697    walk_list!(visitor, visit_stmt, *stmts);
698    visit_opt!(visitor, visit_expr, *expr);
699    V::Result::output()
700}
701
702pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt<'v>) -> V::Result {
703    let Stmt { kind, hir_id, span: _ } = statement;
704    try_visit!(visitor.visit_id(*hir_id));
705    match *kind {
706        StmtKind::Let(ref local) => visitor.visit_local(local),
707        StmtKind::Item(item) => visitor.visit_nested_item(item),
708        StmtKind::Expr(ref expression) | StmtKind::Semi(ref expression) => {
709            visitor.visit_expr(expression)
710        }
711    }
712}
713
714pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm<'v>) -> V::Result {
715    let Arm { hir_id, span: _, pat, guard, body } = arm;
716    try_visit!(visitor.visit_id(*hir_id));
717    try_visit!(visitor.visit_pat(*pat));
718    visit_opt!(visitor, visit_expr, *guard);
719    visitor.visit_expr(*body)
720}
721
722pub fn walk_ty_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v TyPat<'v>) -> V::Result {
723    let TyPat { kind, hir_id, span: _ } = pattern;
724    try_visit!(visitor.visit_id(*hir_id));
725    match *kind {
726        TyPatKind::Range(lower_bound, upper_bound) => {
727            try_visit!(visitor.visit_const_arg_unambig(lower_bound));
728            try_visit!(visitor.visit_const_arg_unambig(upper_bound));
729        }
730        TyPatKind::Or(patterns) => walk_list!(visitor, visit_pattern_type_pattern, patterns),
731        TyPatKind::NotNull | TyPatKind::Err(_) => (),
732    }
733    V::Result::output()
734}
735
736pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat<'v>) -> V::Result {
737    let Pat { hir_id, kind, span, default_binding_modes: _ } = pattern;
738    try_visit!(visitor.visit_id(*hir_id));
739    match *kind {
740        PatKind::TupleStruct(ref qpath, children, _) => {
741            try_visit!(visitor.visit_qpath(qpath, *hir_id, *span));
742            walk_list!(visitor, visit_pat, children);
743        }
744        PatKind::Struct(ref qpath, fields, _) => {
745            try_visit!(visitor.visit_qpath(qpath, *hir_id, *span));
746            walk_list!(visitor, visit_pat_field, fields);
747        }
748        PatKind::Or(pats) => walk_list!(visitor, visit_pat, pats),
749        PatKind::Tuple(tuple_elements, _) => {
750            walk_list!(visitor, visit_pat, tuple_elements);
751        }
752        PatKind::Box(ref subpattern)
753        | PatKind::Deref(ref subpattern)
754        | PatKind::Ref(ref subpattern, _, _) => {
755            try_visit!(visitor.visit_pat(subpattern));
756        }
757        PatKind::Binding(_, _hir_id, ident, ref optional_subpattern) => {
758            try_visit!(visitor.visit_ident(ident));
759            visit_opt!(visitor, visit_pat, optional_subpattern);
760        }
761        PatKind::Expr(ref expression) => try_visit!(visitor.visit_pat_expr(expression)),
762        PatKind::Range(ref lower_bound, ref upper_bound, _) => {
763            visit_opt!(visitor, visit_pat_expr, lower_bound);
764            visit_opt!(visitor, visit_pat_expr, upper_bound);
765        }
766        PatKind::Missing | PatKind::Never | PatKind::Wild | PatKind::Err(_) => (),
767        PatKind::Slice(prepatterns, ref slice_pattern, postpatterns) => {
768            walk_list!(visitor, visit_pat, prepatterns);
769            visit_opt!(visitor, visit_pat, slice_pattern);
770            walk_list!(visitor, visit_pat, postpatterns);
771        }
772        PatKind::Guard(subpat, condition) => {
773            try_visit!(visitor.visit_pat(subpat));
774            try_visit!(visitor.visit_expr(condition));
775        }
776    }
777    V::Result::output()
778}
779
780pub fn walk_pat_field<'v, V: Visitor<'v>>(visitor: &mut V, field: &'v PatField<'v>) -> V::Result {
781    let PatField { hir_id, ident, pat, is_shorthand: _, span: _ } = field;
782    try_visit!(visitor.visit_id(*hir_id));
783    try_visit!(visitor.visit_ident(*ident));
784    visitor.visit_pat(*pat)
785}
786
787pub fn walk_pat_expr<'v, V: Visitor<'v>>(visitor: &mut V, expr: &'v PatExpr<'v>) -> V::Result {
788    let PatExpr { hir_id, span, kind } = expr;
789    try_visit!(visitor.visit_id(*hir_id));
790    match kind {
791        PatExprKind::Lit { lit, negated } => visitor.visit_lit(*hir_id, *lit, *negated),
792        PatExprKind::ConstBlock(c) => visitor.visit_inline_const(c),
793        PatExprKind::Path(qpath) => visitor.visit_qpath(qpath, *hir_id, *span),
794    }
795}
796
797pub fn walk_anon_const<'v, V: Visitor<'v>>(visitor: &mut V, constant: &'v AnonConst) -> V::Result {
798    let AnonConst { hir_id, def_id: _, body, span: _ } = constant;
799    try_visit!(visitor.visit_id(*hir_id));
800    visitor.visit_nested_body(*body)
801}
802
803pub fn walk_inline_const<'v, V: Visitor<'v>>(
804    visitor: &mut V,
805    constant: &'v ConstBlock,
806) -> V::Result {
807    let ConstBlock { hir_id, def_id: _, body } = constant;
808    try_visit!(visitor.visit_id(*hir_id));
809    visitor.visit_nested_body(*body)
810}
811
812pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) -> V::Result {
813    let Expr { hir_id, kind, span } = expression;
814    try_visit!(visitor.visit_id(*hir_id));
815    match *kind {
816        ExprKind::Array(subexpressions) => {
817            walk_list!(visitor, visit_expr, subexpressions);
818        }
819        ExprKind::ConstBlock(ref const_block) => {
820            try_visit!(visitor.visit_inline_const(const_block))
821        }
822        ExprKind::Repeat(ref element, ref count) => {
823            try_visit!(visitor.visit_expr(element));
824            try_visit!(visitor.visit_const_arg_unambig(count));
825        }
826        ExprKind::Struct(ref qpath, fields, ref optional_base) => {
827            try_visit!(visitor.visit_qpath(qpath, *hir_id, *span));
828            walk_list!(visitor, visit_expr_field, fields);
829            match optional_base {
830                StructTailExpr::Base(base) => try_visit!(visitor.visit_expr(base)),
831                StructTailExpr::None | StructTailExpr::DefaultFields(_) => {}
832            }
833        }
834        ExprKind::Tup(subexpressions) => {
835            walk_list!(visitor, visit_expr, subexpressions);
836        }
837        ExprKind::Call(ref callee_expression, arguments) => {
838            try_visit!(visitor.visit_expr(callee_expression));
839            walk_list!(visitor, visit_expr, arguments);
840        }
841        ExprKind::MethodCall(ref segment, receiver, arguments, _) => {
842            try_visit!(visitor.visit_path_segment(segment));
843            try_visit!(visitor.visit_expr(receiver));
844            walk_list!(visitor, visit_expr, arguments);
845        }
846        ExprKind::Use(expr, _) => {
847            try_visit!(visitor.visit_expr(expr));
848        }
849        ExprKind::Binary(_, ref left_expression, ref right_expression) => {
850            try_visit!(visitor.visit_expr(left_expression));
851            try_visit!(visitor.visit_expr(right_expression));
852        }
853        ExprKind::AddrOf(_, _, ref subexpression) | ExprKind::Unary(_, ref subexpression) => {
854            try_visit!(visitor.visit_expr(subexpression));
855        }
856        ExprKind::Cast(ref subexpression, ref typ) | ExprKind::Type(ref subexpression, ref typ) => {
857            try_visit!(visitor.visit_expr(subexpression));
858            try_visit!(visitor.visit_ty_unambig(typ));
859        }
860        ExprKind::DropTemps(ref subexpression) => {
861            try_visit!(visitor.visit_expr(subexpression));
862        }
863        ExprKind::Let(LetExpr { span: _, pat, ty, init, recovered: _ }) => {
864            // match the visit order in walk_local
865            try_visit!(visitor.visit_expr(init));
866            try_visit!(visitor.visit_pat(pat));
867            visit_opt!(visitor, visit_ty_unambig, ty);
868        }
869        ExprKind::If(ref cond, ref then, ref else_opt) => {
870            try_visit!(visitor.visit_expr(cond));
871            try_visit!(visitor.visit_expr(then));
872            visit_opt!(visitor, visit_expr, else_opt);
873        }
874        ExprKind::Loop(ref block, ref opt_label, _, _) => {
875            visit_opt!(visitor, visit_label, opt_label);
876            try_visit!(visitor.visit_block(block));
877        }
878        ExprKind::Match(ref subexpression, arms, _) => {
879            try_visit!(visitor.visit_expr(subexpression));
880            walk_list!(visitor, visit_arm, arms);
881        }
882        ExprKind::Closure(&Closure {
883            def_id,
884            binder: _,
885            bound_generic_params,
886            fn_decl,
887            body,
888            capture_clause: _,
889            fn_decl_span: _,
890            fn_arg_span: _,
891            kind: _,
892            constness: _,
893        }) => {
894            walk_list!(visitor, visit_generic_param, bound_generic_params);
895            try_visit!(visitor.visit_fn(FnKind::Closure, fn_decl, body, *span, def_id));
896        }
897        ExprKind::Block(ref block, ref opt_label) => {
898            visit_opt!(visitor, visit_label, opt_label);
899            try_visit!(visitor.visit_block(block));
900        }
901        ExprKind::Assign(ref lhs, ref rhs, _) => {
902            try_visit!(visitor.visit_expr(rhs));
903            try_visit!(visitor.visit_expr(lhs));
904        }
905        ExprKind::AssignOp(_, ref left_expression, ref right_expression) => {
906            try_visit!(visitor.visit_expr(right_expression));
907            try_visit!(visitor.visit_expr(left_expression));
908        }
909        ExprKind::Field(ref subexpression, ident) => {
910            try_visit!(visitor.visit_expr(subexpression));
911            try_visit!(visitor.visit_ident(ident));
912        }
913        ExprKind::Index(ref main_expression, ref index_expression, _) => {
914            try_visit!(visitor.visit_expr(main_expression));
915            try_visit!(visitor.visit_expr(index_expression));
916        }
917        ExprKind::Path(ref qpath) => {
918            try_visit!(visitor.visit_qpath(qpath, *hir_id, *span));
919        }
920        ExprKind::Break(ref destination, ref opt_expr) => {
921            visit_opt!(visitor, visit_label, &destination.label);
922            visit_opt!(visitor, visit_expr, opt_expr);
923        }
924        ExprKind::Continue(ref destination) => {
925            visit_opt!(visitor, visit_label, &destination.label);
926        }
927        ExprKind::Ret(ref optional_expression) => {
928            visit_opt!(visitor, visit_expr, optional_expression);
929        }
930        ExprKind::Become(ref expr) => try_visit!(visitor.visit_expr(expr)),
931        ExprKind::InlineAsm(ref asm) => {
932            try_visit!(visitor.visit_inline_asm(asm, *hir_id));
933        }
934        ExprKind::OffsetOf(ref container, ref fields) => {
935            try_visit!(visitor.visit_ty_unambig(container));
936            walk_list!(visitor, visit_ident, fields.iter().copied());
937        }
938        ExprKind::Yield(ref subexpression, _) => {
939            try_visit!(visitor.visit_expr(subexpression));
940        }
941        ExprKind::UnsafeBinderCast(_kind, expr, ty) => {
942            try_visit!(visitor.visit_expr(expr));
943            visit_opt!(visitor, visit_ty_unambig, ty);
944        }
945        ExprKind::Lit(lit) => try_visit!(visitor.visit_lit(*hir_id, lit, false)),
946        ExprKind::Err(_) => {}
947    }
948    V::Result::output()
949}
950
951pub fn walk_expr_field<'v, V: Visitor<'v>>(visitor: &mut V, field: &'v ExprField<'v>) -> V::Result {
952    let ExprField { hir_id, ident, expr, span: _, is_shorthand: _ } = field;
953    try_visit!(visitor.visit_id(*hir_id));
954    try_visit!(visitor.visit_ident(*ident));
955    visitor.visit_expr(*expr)
956}
957/// We track whether an infer var is from a [`Ty`], [`ConstArg`], or [`GenericArg`] so that
958/// HIR visitors overriding [`Visitor::visit_infer`] can determine what kind of infer is being visited
959pub enum InferKind<'hir> {
960    Ty(&'hir Ty<'hir>),
961    Const(&'hir ConstArg<'hir>),
962    Ambig(&'hir InferArg),
963}
964
965pub fn walk_generic_arg<'v, V: Visitor<'v>>(
966    visitor: &mut V,
967    generic_arg: &'v GenericArg<'v>,
968) -> V::Result {
969    match generic_arg {
970        GenericArg::Lifetime(lt) => visitor.visit_lifetime(lt),
971        GenericArg::Type(ty) => visitor.visit_ty(ty),
972        GenericArg::Const(ct) => visitor.visit_const_arg(ct),
973        GenericArg::Infer(inf) => {
974            let InferArg { hir_id, span } = inf;
975            visitor.visit_infer(*hir_id, *span, InferKind::Ambig(inf))
976        }
977    }
978}
979
980pub fn walk_unambig_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> V::Result {
981    match typ.try_as_ambig_ty() {
982        Some(ambig_ty) => visitor.visit_ty(ambig_ty),
983        None => {
984            let Ty { hir_id, span, kind: _ } = typ;
985            visitor.visit_infer(*hir_id, *span, InferKind::Ty(typ))
986        }
987    }
988}
989
990pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v, AmbigArg>) -> V::Result {
991    let Ty { hir_id, span: _, kind } = typ;
992    try_visit!(visitor.visit_id(*hir_id));
993
994    match *kind {
995        TyKind::Slice(ref ty) => try_visit!(visitor.visit_ty_unambig(ty)),
996        TyKind::Ptr(ref mutable_type) => try_visit!(visitor.visit_ty_unambig(mutable_type.ty)),
997        TyKind::Ref(ref lifetime, ref mutable_type) => {
998            try_visit!(visitor.visit_lifetime(lifetime));
999            try_visit!(visitor.visit_ty_unambig(mutable_type.ty));
1000        }
1001        TyKind::Never => {}
1002        TyKind::Tup(tuple_element_types) => {
1003            walk_list!(visitor, visit_ty_unambig, tuple_element_types);
1004        }
1005        TyKind::FnPtr(ref function_declaration) => {
1006            walk_list!(visitor, visit_generic_param, function_declaration.generic_params);
1007            try_visit!(visitor.visit_fn_decl(function_declaration.decl));
1008        }
1009        TyKind::UnsafeBinder(ref unsafe_binder) => {
1010            walk_list!(visitor, visit_generic_param, unsafe_binder.generic_params);
1011            try_visit!(visitor.visit_ty_unambig(unsafe_binder.inner_ty));
1012        }
1013        TyKind::Path(ref qpath) => {
1014            try_visit!(visitor.visit_qpath(qpath, typ.hir_id, typ.span));
1015        }
1016        TyKind::OpaqueDef(opaque) => {
1017            try_visit!(visitor.visit_opaque_ty(opaque));
1018        }
1019        TyKind::TraitAscription(bounds) => {
1020            walk_list!(visitor, visit_param_bound, bounds);
1021        }
1022        TyKind::Array(ref ty, ref length) => {
1023            try_visit!(visitor.visit_ty_unambig(ty));
1024            try_visit!(visitor.visit_const_arg_unambig(length));
1025        }
1026        TyKind::TraitObject(bounds, ref lifetime) => {
1027            for bound in bounds {
1028                try_visit!(visitor.visit_poly_trait_ref(bound));
1029            }
1030            try_visit!(visitor.visit_lifetime(lifetime));
1031        }
1032        TyKind::Typeof(ref expression) => try_visit!(visitor.visit_anon_const(expression)),
1033        TyKind::InferDelegation(..) | TyKind::Err(_) => {}
1034        TyKind::Pat(ty, pat) => {
1035            try_visit!(visitor.visit_ty_unambig(ty));
1036            try_visit!(visitor.visit_pattern_type_pattern(pat));
1037        }
1038    }
1039    V::Result::output()
1040}
1041
1042pub fn walk_const_item_rhs<'v, V: Visitor<'v>>(
1043    visitor: &mut V,
1044    ct_rhs: ConstItemRhs<'v>,
1045) -> V::Result {
1046    match ct_rhs {
1047        ConstItemRhs::Body(body_id) => visitor.visit_nested_body(body_id),
1048        ConstItemRhs::TypeConst(const_arg) => visitor.visit_const_arg_unambig(const_arg),
1049    }
1050}
1051
1052pub fn walk_unambig_const_arg<'v, V: Visitor<'v>>(
1053    visitor: &mut V,
1054    const_arg: &'v ConstArg<'v>,
1055) -> V::Result {
1056    match const_arg.try_as_ambig_ct() {
1057        Some(ambig_ct) => visitor.visit_const_arg(ambig_ct),
1058        None => {
1059            let ConstArg { hir_id, kind: _ } = const_arg;
1060            visitor.visit_infer(*hir_id, const_arg.span(), InferKind::Const(const_arg))
1061        }
1062    }
1063}
1064
1065pub fn walk_const_arg<'v, V: Visitor<'v>>(
1066    visitor: &mut V,
1067    const_arg: &'v ConstArg<'v, AmbigArg>,
1068) -> V::Result {
1069    let ConstArg { hir_id, kind } = const_arg;
1070    try_visit!(visitor.visit_id(*hir_id));
1071    match kind {
1072        ConstArgKind::Path(qpath) => visitor.visit_qpath(qpath, *hir_id, qpath.span()),
1073        ConstArgKind::Anon(anon) => visitor.visit_anon_const(*anon),
1074        ConstArgKind::Error(_, _) => V::Result::output(), // errors and spans are not important
1075    }
1076}
1077
1078pub fn walk_generic_param<'v, V: Visitor<'v>>(
1079    visitor: &mut V,
1080    param: &'v GenericParam<'v>,
1081) -> V::Result {
1082    let GenericParam {
1083        hir_id,
1084        def_id: _,
1085        name,
1086        span: _,
1087        pure_wrt_drop: _,
1088        kind,
1089        colon_span: _,
1090        source: _,
1091    } = param;
1092    try_visit!(visitor.visit_id(*hir_id));
1093    match *name {
1094        ParamName::Plain(ident) | ParamName::Error(ident) => try_visit!(visitor.visit_ident(ident)),
1095        ParamName::Fresh => {}
1096    }
1097    match *kind {
1098        GenericParamKind::Lifetime { .. } => {}
1099        GenericParamKind::Type { ref default, .. } => {
1100            visit_opt!(visitor, visit_ty_unambig, default)
1101        }
1102        GenericParamKind::Const { ref ty, ref default } => {
1103            try_visit!(visitor.visit_ty_unambig(ty));
1104            if let Some(default) = default {
1105                try_visit!(visitor.visit_const_param_default(*hir_id, default));
1106            }
1107        }
1108    }
1109    V::Result::output()
1110}
1111
1112pub fn walk_const_param_default<'v, V: Visitor<'v>>(
1113    visitor: &mut V,
1114    ct: &'v ConstArg<'v>,
1115) -> V::Result {
1116    visitor.visit_const_arg_unambig(ct)
1117}
1118
1119pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics<'v>) -> V::Result {
1120    let &Generics {
1121        params,
1122        predicates,
1123        has_where_clause_predicates: _,
1124        where_clause_span: _,
1125        span: _,
1126    } = generics;
1127    walk_list!(visitor, visit_generic_param, params);
1128    walk_list!(visitor, visit_where_predicate, predicates);
1129    V::Result::output()
1130}
1131
1132pub fn walk_where_predicate<'v, V: Visitor<'v>>(
1133    visitor: &mut V,
1134    predicate: &'v WherePredicate<'v>,
1135) -> V::Result {
1136    let &WherePredicate { hir_id, kind, span: _ } = predicate;
1137    try_visit!(visitor.visit_id(hir_id));
1138    match *kind {
1139        WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1140            ref bounded_ty,
1141            bounds,
1142            bound_generic_params,
1143            origin: _,
1144        }) => {
1145            try_visit!(visitor.visit_ty_unambig(bounded_ty));
1146            walk_list!(visitor, visit_param_bound, bounds);
1147            walk_list!(visitor, visit_generic_param, bound_generic_params);
1148        }
1149        WherePredicateKind::RegionPredicate(WhereRegionPredicate {
1150            ref lifetime,
1151            bounds,
1152            in_where_clause: _,
1153        }) => {
1154            try_visit!(visitor.visit_lifetime(lifetime));
1155            walk_list!(visitor, visit_param_bound, bounds);
1156        }
1157        WherePredicateKind::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty }) => {
1158            try_visit!(visitor.visit_ty_unambig(lhs_ty));
1159            try_visit!(visitor.visit_ty_unambig(rhs_ty));
1160        }
1161    }
1162    V::Result::output()
1163}
1164
1165pub fn walk_fn_decl<'v, V: Visitor<'v>>(
1166    visitor: &mut V,
1167    function_declaration: &'v FnDecl<'v>,
1168) -> V::Result {
1169    let FnDecl { inputs, output, c_variadic: _, implicit_self: _, lifetime_elision_allowed: _ } =
1170        function_declaration;
1171    walk_list!(visitor, visit_ty_unambig, *inputs);
1172    visitor.visit_fn_ret_ty(output)
1173}
1174
1175pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FnRetTy<'v>) -> V::Result {
1176    if let FnRetTy::Return(output_ty) = *ret_ty {
1177        try_visit!(visitor.visit_ty_unambig(output_ty));
1178    }
1179    V::Result::output()
1180}
1181
1182pub fn walk_fn<'v, V: Visitor<'v>>(
1183    visitor: &mut V,
1184    function_kind: FnKind<'v>,
1185    function_declaration: &'v FnDecl<'v>,
1186    body_id: BodyId,
1187    _: LocalDefId,
1188) -> V::Result {
1189    try_visit!(visitor.visit_fn_decl(function_declaration));
1190    try_visit!(walk_fn_kind(visitor, function_kind));
1191    visitor.visit_nested_body(body_id)
1192}
1193
1194pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, function_kind: FnKind<'v>) -> V::Result {
1195    match function_kind {
1196        FnKind::ItemFn(_, generics, ..) => {
1197            try_visit!(visitor.visit_generics(generics));
1198        }
1199        FnKind::Closure | FnKind::Method(..) => {}
1200    }
1201    V::Result::output()
1202}
1203
1204pub fn walk_use<'v, V: Visitor<'v>>(
1205    visitor: &mut V,
1206    path: &'v UsePath<'v>,
1207    hir_id: HirId,
1208) -> V::Result {
1209    let UsePath { segments, ref res, span } = *path;
1210    for res in res.present_items() {
1211        try_visit!(visitor.visit_path(&Path { segments, res, span }, hir_id));
1212    }
1213    V::Result::output()
1214}
1215
1216pub fn walk_trait_item<'v, V: Visitor<'v>>(
1217    visitor: &mut V,
1218    trait_item: &'v TraitItem<'v>,
1219) -> V::Result {
1220    let TraitItem {
1221        ident,
1222        generics,
1223        ref defaultness,
1224        ref kind,
1225        span,
1226        owner_id: _,
1227        has_delayed_lints: _,
1228    } = *trait_item;
1229    let hir_id = trait_item.hir_id();
1230    try_visit!(visitor.visit_ident(ident));
1231    try_visit!(visitor.visit_generics(&generics));
1232    try_visit!(visitor.visit_defaultness(&defaultness));
1233    try_visit!(visitor.visit_id(hir_id));
1234    match *kind {
1235        TraitItemKind::Const(ref ty, default) => {
1236            try_visit!(visitor.visit_ty_unambig(ty));
1237            visit_opt!(visitor, visit_const_item_rhs, default);
1238        }
1239        TraitItemKind::Fn(ref sig, TraitFn::Required(param_idents)) => {
1240            try_visit!(visitor.visit_fn_decl(sig.decl));
1241            for ident in param_idents.iter().copied() {
1242                visit_opt!(visitor, visit_ident, ident);
1243            }
1244        }
1245        TraitItemKind::Fn(ref sig, TraitFn::Provided(body_id)) => {
1246            try_visit!(visitor.visit_fn(
1247                FnKind::Method(ident, sig),
1248                sig.decl,
1249                body_id,
1250                span,
1251                trait_item.owner_id.def_id,
1252            ));
1253        }
1254        TraitItemKind::Type(bounds, ref default) => {
1255            walk_list!(visitor, visit_param_bound, bounds);
1256            visit_opt!(visitor, visit_ty_unambig, default);
1257        }
1258    }
1259    V::Result::output()
1260}
1261
1262pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, id: TraitItemId) -> V::Result {
1263    visitor.visit_nested_trait_item(id)
1264}
1265
1266pub fn walk_impl_item<'v, V: Visitor<'v>>(
1267    visitor: &mut V,
1268    impl_item: &'v ImplItem<'v>,
1269) -> V::Result {
1270    let ImplItem {
1271        owner_id: _,
1272        ident,
1273        ref generics,
1274        ref impl_kind,
1275        ref kind,
1276        span: _,
1277        has_delayed_lints: _,
1278    } = *impl_item;
1279
1280    try_visit!(visitor.visit_ident(ident));
1281    try_visit!(visitor.visit_generics(generics));
1282    try_visit!(visitor.visit_id(impl_item.hir_id()));
1283    match impl_kind {
1284        ImplItemImplKind::Inherent { vis_span: _ } => {}
1285        ImplItemImplKind::Trait { defaultness, trait_item_def_id: _ } => {
1286            try_visit!(visitor.visit_defaultness(defaultness));
1287        }
1288    }
1289    match *kind {
1290        ImplItemKind::Const(ref ty, rhs) => {
1291            try_visit!(visitor.visit_ty_unambig(ty));
1292            visitor.visit_const_item_rhs(rhs)
1293        }
1294        ImplItemKind::Fn(ref sig, body_id) => visitor.visit_fn(
1295            FnKind::Method(impl_item.ident, sig),
1296            sig.decl,
1297            body_id,
1298            impl_item.span,
1299            impl_item.owner_id.def_id,
1300        ),
1301        ImplItemKind::Type(ref ty) => visitor.visit_ty_unambig(ty),
1302    }
1303}
1304
1305pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, id: ForeignItemId) -> V::Result {
1306    visitor.visit_nested_foreign_item(id)
1307}
1308
1309pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, id: ImplItemId) -> V::Result {
1310    visitor.visit_nested_impl_item(id)
1311}
1312
1313pub fn walk_trait_ref<'v, V: Visitor<'v>>(
1314    visitor: &mut V,
1315    trait_ref: &'v TraitRef<'v>,
1316) -> V::Result {
1317    let TraitRef { hir_ref_id, path } = trait_ref;
1318    try_visit!(visitor.visit_id(*hir_ref_id));
1319    visitor.visit_path(*path, *hir_ref_id)
1320}
1321
1322pub fn walk_param_bound<'v, V: Visitor<'v>>(
1323    visitor: &mut V,
1324    bound: &'v GenericBound<'v>,
1325) -> V::Result {
1326    match *bound {
1327        GenericBound::Trait(ref typ) => visitor.visit_poly_trait_ref(typ),
1328        GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime),
1329        GenericBound::Use(args, _) => {
1330            walk_list!(visitor, visit_precise_capturing_arg, args);
1331            V::Result::output()
1332        }
1333    }
1334}
1335
1336pub fn walk_precise_capturing_arg<'v, V: Visitor<'v>>(
1337    visitor: &mut V,
1338    arg: &'v PreciseCapturingArg<'v>,
1339) -> V::Result {
1340    match *arg {
1341        PreciseCapturingArg::Lifetime(lt) => visitor.visit_lifetime(lt),
1342        PreciseCapturingArg::Param(param) => {
1343            let PreciseCapturingNonLifetimeArg { hir_id, ident, res: _ } = param;
1344            try_visit!(visitor.visit_id(hir_id));
1345            visitor.visit_ident(ident)
1346        }
1347    }
1348}
1349
1350pub fn walk_poly_trait_ref<'v, V: Visitor<'v>>(
1351    visitor: &mut V,
1352    trait_ref: &'v PolyTraitRef<'v>,
1353) -> V::Result {
1354    let PolyTraitRef { bound_generic_params, modifiers: _, trait_ref, span: _ } = trait_ref;
1355    walk_list!(visitor, visit_generic_param, *bound_generic_params);
1356    visitor.visit_trait_ref(trait_ref)
1357}
1358
1359pub fn walk_opaque_ty<'v, V: Visitor<'v>>(visitor: &mut V, opaque: &'v OpaqueTy<'v>) -> V::Result {
1360    let &OpaqueTy { hir_id, def_id: _, bounds, origin: _, span: _ } = opaque;
1361    try_visit!(visitor.visit_id(hir_id));
1362    walk_list!(visitor, visit_param_bound, bounds);
1363    V::Result::output()
1364}
1365
1366pub fn walk_struct_def<'v, V: Visitor<'v>>(
1367    visitor: &mut V,
1368    struct_definition: &'v VariantData<'v>,
1369) -> V::Result {
1370    visit_opt!(visitor, visit_id, struct_definition.ctor_hir_id());
1371    walk_list!(visitor, visit_field_def, struct_definition.fields());
1372    V::Result::output()
1373}
1374
1375pub fn walk_field_def<'v, V: Visitor<'v>>(
1376    visitor: &mut V,
1377    FieldDef { hir_id, ident, ty, default, span: _, vis_span: _, def_id: _, safety: _ }: &'v FieldDef<'v>,
1378) -> V::Result {
1379    try_visit!(visitor.visit_id(*hir_id));
1380    try_visit!(visitor.visit_ident(*ident));
1381    visit_opt!(visitor, visit_anon_const, default);
1382    visitor.visit_ty_unambig(*ty)
1383}
1384
1385pub fn walk_enum_def<'v, V: Visitor<'v>>(
1386    visitor: &mut V,
1387    enum_definition: &'v EnumDef<'v>,
1388) -> V::Result {
1389    let EnumDef { variants } = enum_definition;
1390    walk_list!(visitor, visit_variant, *variants);
1391    V::Result::output()
1392}
1393
1394pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V, variant: &'v Variant<'v>) -> V::Result {
1395    let Variant { ident, hir_id, def_id: _, data, disr_expr, span: _ } = variant;
1396    try_visit!(visitor.visit_ident(*ident));
1397    try_visit!(visitor.visit_id(*hir_id));
1398    try_visit!(visitor.visit_variant_data(data));
1399    visit_opt!(visitor, visit_anon_const, disr_expr);
1400    V::Result::output()
1401}
1402
1403pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) -> V::Result {
1404    let Label { ident } = label;
1405    visitor.visit_ident(*ident)
1406}
1407
1408pub fn walk_inf<'v, V: Visitor<'v>>(visitor: &mut V, inf: &'v InferArg) -> V::Result {
1409    let InferArg { hir_id, span: _ } = inf;
1410    visitor.visit_id(*hir_id)
1411}
1412
1413pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) -> V::Result {
1414    let Lifetime { hir_id, ident, kind: _, source: _, syntax: _ } = lifetime;
1415    try_visit!(visitor.visit_id(*hir_id));
1416    visitor.visit_ident(*ident)
1417}
1418
1419pub fn walk_qpath<'v, V: Visitor<'v>>(
1420    visitor: &mut V,
1421    qpath: &'v QPath<'v>,
1422    id: HirId,
1423) -> V::Result {
1424    match *qpath {
1425        QPath::Resolved(ref maybe_qself, ref path) => {
1426            visit_opt!(visitor, visit_ty_unambig, maybe_qself);
1427            visitor.visit_path(path, id)
1428        }
1429        QPath::TypeRelative(ref qself, ref segment) => {
1430            try_visit!(visitor.visit_ty_unambig(qself));
1431            visitor.visit_path_segment(segment)
1432        }
1433    }
1434}
1435
1436pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &Path<'v>) -> V::Result {
1437    let Path { segments, span: _, res: _ } = path;
1438    walk_list!(visitor, visit_path_segment, *segments);
1439    V::Result::output()
1440}
1441
1442pub fn walk_path_segment<'v, V: Visitor<'v>>(
1443    visitor: &mut V,
1444    segment: &'v PathSegment<'v>,
1445) -> V::Result {
1446    let PathSegment { ident, hir_id, res: _, args, infer_args: _ } = segment;
1447    try_visit!(visitor.visit_ident(*ident));
1448    try_visit!(visitor.visit_id(*hir_id));
1449    visit_opt!(visitor, visit_generic_args, *args);
1450    V::Result::output()
1451}
1452
1453pub fn walk_generic_args<'v, V: Visitor<'v>>(
1454    visitor: &mut V,
1455    generic_args: &'v GenericArgs<'v>,
1456) -> V::Result {
1457    let GenericArgs { args, constraints, parenthesized: _, span_ext: _ } = generic_args;
1458    walk_list!(visitor, visit_generic_arg, *args);
1459    walk_list!(visitor, visit_assoc_item_constraint, *constraints);
1460    V::Result::output()
1461}
1462
1463pub fn walk_assoc_item_constraint<'v, V: Visitor<'v>>(
1464    visitor: &mut V,
1465    constraint: &'v AssocItemConstraint<'v>,
1466) -> V::Result {
1467    let AssocItemConstraint { hir_id, ident, gen_args, kind: _, span: _ } = constraint;
1468    try_visit!(visitor.visit_id(*hir_id));
1469    try_visit!(visitor.visit_ident(*ident));
1470    try_visit!(visitor.visit_generic_args(*gen_args));
1471    match constraint.kind {
1472        AssocItemConstraintKind::Equality { ref term } => match term {
1473            Term::Ty(ty) => try_visit!(visitor.visit_ty_unambig(ty)),
1474            Term::Const(c) => try_visit!(visitor.visit_const_arg_unambig(c)),
1475        },
1476        AssocItemConstraintKind::Bound { bounds } => {
1477            walk_list!(visitor, visit_param_bound, bounds)
1478        }
1479    }
1480    V::Result::output()
1481}
1482
1483pub fn walk_defaultness<'v, V: Visitor<'v>>(_: &mut V, _: &'v Defaultness) -> V::Result {
1484    // No visitable content here: this fn exists so you can call it if
1485    // the right thing to do, should content be added in the future,
1486    // would be to walk it.
1487    V::Result::output()
1488}
1489
1490pub fn walk_inline_asm<'v, V: Visitor<'v>>(
1491    visitor: &mut V,
1492    asm: &'v InlineAsm<'v>,
1493    id: HirId,
1494) -> V::Result {
1495    for (op, op_sp) in asm.operands {
1496        match op {
1497            InlineAsmOperand::In { expr, .. } | InlineAsmOperand::InOut { expr, .. } => {
1498                try_visit!(visitor.visit_expr(expr));
1499            }
1500            InlineAsmOperand::Out { expr, .. } => {
1501                visit_opt!(visitor, visit_expr, expr);
1502            }
1503            InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1504                try_visit!(visitor.visit_expr(in_expr));
1505                visit_opt!(visitor, visit_expr, out_expr);
1506            }
1507            InlineAsmOperand::Const { anon_const, .. } => {
1508                try_visit!(visitor.visit_inline_const(anon_const));
1509            }
1510            InlineAsmOperand::SymFn { expr, .. } => {
1511                try_visit!(visitor.visit_expr(expr));
1512            }
1513            InlineAsmOperand::SymStatic { path, .. } => {
1514                try_visit!(visitor.visit_qpath(path, id, *op_sp));
1515            }
1516            InlineAsmOperand::Label { block } => try_visit!(visitor.visit_block(block)),
1517        }
1518    }
1519    V::Result::output()
1520}