]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/intravisit.rs
e49a5e4ee6ae95fc4e1f1730f2784b18eb0e4707
[rust.git] / src / librustc / hir / intravisit.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! HIR walker for walking the contents of nodes.
12 //!
13 //! **For an overview of the visitor strategy, see the docs on the
14 //! `super::itemlikevisit::ItemLikeVisitor` trait.**
15 //!
16 //! If you have decided to use this visitor, here are some general
17 //! notes on how to do it:
18 //!
19 //! Each overridden visit method has full control over what
20 //! happens with its node, it can do its own traversal of the node's children,
21 //! call `intravisit::walk_*` to apply the default traversal algorithm, or prevent
22 //! deeper traversal by doing nothing.
23 //!
24 //! When visiting the HIR, the contents of nested items are NOT visited
25 //! by default. This is different from the AST visitor, which does a deep walk.
26 //! Hence this module is called `intravisit`; see the method `visit_nested_item`
27 //! for more details.
28 //!
29 //! Note: it is an important invariant that the default visitor walks
30 //! the body of a function in "execution order" - more concretely, if
31 //! we consider the reverse post-order (RPO) of the CFG implied by the HIR,
32 //! then a pre-order traversal of the HIR is consistent with the CFG RPO
33 //! on the *initial CFG point* of each HIR node, while a post-order traversal
34 //! of the HIR is consistent with the CFG RPO on each *final CFG point* of
35 //! each CFG node.
36 //!
37 //! One thing that follows is that if HIR node A always starts/ends executing
38 //! before HIR node B, then A appears in traversal pre/postorder before B,
39 //! respectively. (This follows from RPO respecting CFG domination).
40 //!
41 //! This order consistency is required in a few places in rustc, for
42 //! example generator inference, and possibly also HIR borrowck.
43
44 use rustc_target::spec::abi::Abi;
45 use syntax::ast::{NodeId, CRATE_NODE_ID, Ident, Name, Attribute};
46 use syntax_pos::Span;
47 use hir::*;
48 use hir::def::Def;
49 use hir::map::{self, Map};
50 use super::itemlikevisit::DeepVisitor;
51
52 use std::cmp;
53 use std::u32;
54
55 #[derive(Copy, Clone, PartialEq, Eq)]
56 pub enum FnKind<'a> {
57     /// fn foo() or extern "Abi" fn foo()
58     ItemFn(Name, &'a Generics, Unsafety, Constness, Abi, &'a Visibility, &'a [Attribute]),
59
60     /// fn foo(&self)
61     Method(Name, &'a MethodSig, Option<&'a Visibility>, &'a [Attribute]),
62
63     /// |x, y| {}
64     Closure(&'a [Attribute]),
65 }
66
67 impl<'a> FnKind<'a> {
68     pub fn attrs(&self) -> &'a [Attribute] {
69         match *self {
70             FnKind::ItemFn(.., attrs) => attrs,
71             FnKind::Method(.., attrs) => attrs,
72             FnKind::Closure(attrs) => attrs,
73         }
74     }
75 }
76
77 /// Specifies what nested things a visitor wants to visit. The most
78 /// common choice is `OnlyBodies`, which will cause the visitor to
79 /// visit fn bodies for fns that it encounters, but skip over nested
80 /// item-like things.
81 ///
82 /// See the comments on `ItemLikeVisitor` for more details on the overall
83 /// visit strategy.
84 pub enum NestedVisitorMap<'this, 'tcx: 'this> {
85     /// Do not visit any nested things. When you add a new
86     /// "non-nested" thing, you will want to audit such uses to see if
87     /// they remain valid.
88     ///
89     /// Use this if you are only walking some particular kind of tree
90     /// (i.e., a type, or fn signature) and you don't want to thread a
91     /// HIR map around.
92     None,
93
94     /// Do not visit nested item-like things, but visit nested things
95     /// that are inside of an item-like.
96     ///
97     /// **This is the most common choice.** A very common pattern is
98     /// to use `visit_all_item_likes()` as an outer loop,
99     /// and to have the visitor that visits the contents of each item
100     /// using this setting.
101     OnlyBodies(&'this Map<'tcx>),
102
103     /// Visit all nested things, including item-likes.
104     ///
105     /// **This is an unusual choice.** It is used when you want to
106     /// process everything within their lexical context. Typically you
107     /// kick off the visit by doing `walk_krate()`.
108     All(&'this Map<'tcx>),
109 }
110
111 impl<'this, 'tcx> NestedVisitorMap<'this, 'tcx> {
112     /// Returns the map to use for an "intra item-like" thing (if any).
113     /// e.g., function body.
114     pub fn intra(self) -> Option<&'this Map<'tcx>> {
115         match self {
116             NestedVisitorMap::None => None,
117             NestedVisitorMap::OnlyBodies(map) => Some(map),
118             NestedVisitorMap::All(map) => Some(map),
119         }
120     }
121
122     /// Returns the map to use for an "item-like" thing (if any).
123     /// e.g., item, impl-item.
124     pub fn inter(self) -> Option<&'this Map<'tcx>> {
125         match self {
126             NestedVisitorMap::None => None,
127             NestedVisitorMap::OnlyBodies(_) => None,
128             NestedVisitorMap::All(map) => Some(map),
129         }
130     }
131 }
132
133 /// Each method of the Visitor trait is a hook to be potentially
134 /// overridden.  Each method's default implementation recursively visits
135 /// the substructure of the input via the corresponding `walk` method;
136 /// e.g. the `visit_mod` method by default calls `intravisit::walk_mod`.
137 ///
138 /// Note that this visitor does NOT visit nested items by default
139 /// (this is why the module is called `intravisit`, to distinguish it
140 /// from the AST's `visit` module, which acts differently). If you
141 /// simply want to visit all items in the crate in some order, you
142 /// should call `Crate::visit_all_items`. Otherwise, see the comment
143 /// on `visit_nested_item` for details on how to visit nested items.
144 ///
145 /// If you want to ensure that your code handles every variant
146 /// explicitly, you need to override each method.  (And you also need
147 /// to monitor future changes to `Visitor` in case a new method with a
148 /// new default implementation gets introduced.)
149 pub trait Visitor<'v> : Sized {
150     ///////////////////////////////////////////////////////////////////////////
151     // Nested items.
152
153     /// The default versions of the `visit_nested_XXX` routines invoke
154     /// this method to get a map to use. By selecting an enum variant,
155     /// you control which kinds of nested HIR are visited; see
156     /// `NestedVisitorMap` for details. By "nested HIR", we are
157     /// referring to bits of HIR that are not directly embedded within
158     /// one another but rather indirectly, through a table in the
159     /// crate. This is done to control dependencies during incremental
160     /// compilation: the non-inline bits of HIR can be tracked and
161     /// hashed separately.
162     ///
163     /// **If for some reason you want the nested behavior, but don't
164     /// have a `Map` at your disposal:** then you should override the
165     /// `visit_nested_XXX` methods, and override this method to
166     /// `panic!()`. This way, if a new `visit_nested_XXX` variant is
167     /// added in the future, we will see the panic in your code and
168     /// fix it appropriately.
169     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v>;
170
171     /// Invoked when a nested item is encountered. By default does
172     /// nothing unless you override `nested_visit_map` to return
173     /// `Some(_)`, in which case it will walk the item. **You probably
174     /// don't want to override this method** -- instead, override
175     /// `nested_visit_map` or use the "shallow" or "deep" visit
176     /// patterns described on `itemlikevisit::ItemLikeVisitor`. The only
177     /// reason to override this method is if you want a nested pattern
178     /// but cannot supply a `Map`; see `nested_visit_map` for advice.
179     #[allow(unused_variables)]
180     fn visit_nested_item(&mut self, id: ItemId) {
181         let opt_item = self.nested_visit_map().inter().map(|map| map.expect_item(id.id));
182         if let Some(item) = opt_item {
183             self.visit_item(item);
184         }
185     }
186
187     /// Like `visit_nested_item()`, but for trait items. See
188     /// `visit_nested_item()` for advice on when to override this
189     /// method.
190     #[allow(unused_variables)]
191     fn visit_nested_trait_item(&mut self, id: TraitItemId) {
192         let opt_item = self.nested_visit_map().inter().map(|map| map.trait_item(id));
193         if let Some(item) = opt_item {
194             self.visit_trait_item(item);
195         }
196     }
197
198     /// Like `visit_nested_item()`, but for impl items. See
199     /// `visit_nested_item()` for advice on when to override this
200     /// method.
201     #[allow(unused_variables)]
202     fn visit_nested_impl_item(&mut self, id: ImplItemId) {
203         let opt_item = self.nested_visit_map().inter().map(|map| map.impl_item(id));
204         if let Some(item) = opt_item {
205             self.visit_impl_item(item);
206         }
207     }
208
209     /// Invoked to visit the body of a function, method or closure. Like
210     /// visit_nested_item, does nothing by default unless you override
211     /// `nested_visit_map` to return `Some(_)`, in which case it will walk the
212     /// body.
213     fn visit_nested_body(&mut self, id: BodyId) {
214         let opt_body = self.nested_visit_map().intra().map(|map| map.body(id));
215         if let Some(body) = opt_body {
216             self.visit_body(body);
217         }
218     }
219
220     /// Visit the top-level item and (optionally) nested items / impl items. See
221     /// `visit_nested_item` for details.
222     fn visit_item(&mut self, i: &'v Item) {
223         walk_item(self, i)
224     }
225
226     fn visit_body(&mut self, b: &'v Body) {
227         walk_body(self, b);
228     }
229
230     /// When invoking `visit_all_item_likes()`, you need to supply an
231     /// item-like visitor.  This method converts a "intra-visit"
232     /// visitor into an item-like visitor that walks the entire tree.
233     /// If you use this, you probably don't want to process the
234     /// contents of nested item-like things, since the outer loop will
235     /// visit them as well.
236     fn as_deep_visitor<'s>(&'s mut self) -> DeepVisitor<'s, Self> {
237         DeepVisitor::new(self)
238     }
239
240     ///////////////////////////////////////////////////////////////////////////
241
242     fn visit_id(&mut self, _node_id: NodeId) {
243         // Nothing to do.
244     }
245     fn visit_def_mention(&mut self, _def: Def) {
246         // Nothing to do.
247     }
248     fn visit_name(&mut self, _span: Span, _name: Name) {
249         // Nothing to do.
250     }
251     fn visit_ident(&mut self, ident: Ident) {
252         walk_ident(self, ident)
253     }
254     fn visit_mod(&mut self, m: &'v Mod, _s: Span, n: NodeId) {
255         walk_mod(self, m, n)
256     }
257     fn visit_foreign_item(&mut self, i: &'v ForeignItem) {
258         walk_foreign_item(self, i)
259     }
260     fn visit_local(&mut self, l: &'v Local) {
261         walk_local(self, l)
262     }
263     fn visit_block(&mut self, b: &'v Block) {
264         walk_block(self, b)
265     }
266     fn visit_stmt(&mut self, s: &'v Stmt) {
267         walk_stmt(self, s)
268     }
269     fn visit_arm(&mut self, a: &'v Arm) {
270         walk_arm(self, a)
271     }
272     fn visit_pat(&mut self, p: &'v Pat) {
273         walk_pat(self, p)
274     }
275     fn visit_decl(&mut self, d: &'v Decl) {
276         walk_decl(self, d)
277     }
278     fn visit_anon_const(&mut self, c: &'v AnonConst) {
279         walk_anon_const(self, c)
280     }
281     fn visit_expr(&mut self, ex: &'v Expr) {
282         walk_expr(self, ex)
283     }
284     fn visit_ty(&mut self, t: &'v Ty) {
285         walk_ty(self, t)
286     }
287     fn visit_generic_param(&mut self, p: &'v GenericParam) {
288         walk_generic_param(self, p)
289     }
290     fn visit_generics(&mut self, g: &'v Generics) {
291         walk_generics(self, g)
292     }
293     fn visit_where_predicate(&mut self, predicate: &'v WherePredicate) {
294         walk_where_predicate(self, predicate)
295     }
296     fn visit_fn_decl(&mut self, fd: &'v FnDecl) {
297         walk_fn_decl(self, fd)
298     }
299     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: BodyId, s: Span, id: NodeId) {
300         walk_fn(self, fk, fd, b, s, id)
301     }
302     fn visit_trait_item(&mut self, ti: &'v TraitItem) {
303         walk_trait_item(self, ti)
304     }
305     fn visit_trait_item_ref(&mut self, ii: &'v TraitItemRef) {
306         walk_trait_item_ref(self, ii)
307     }
308     fn visit_impl_item(&mut self, ii: &'v ImplItem) {
309         walk_impl_item(self, ii)
310     }
311     fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) {
312         walk_impl_item_ref(self, ii)
313     }
314     fn visit_trait_ref(&mut self, t: &'v TraitRef) {
315         walk_trait_ref(self, t)
316     }
317     fn visit_param_bound(&mut self, bounds: &'v GenericBound) {
318         walk_param_bound(self, bounds)
319     }
320     fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: TraitBoundModifier) {
321         walk_poly_trait_ref(self, t, m)
322     }
323     fn visit_variant_data(&mut self,
324                           s: &'v VariantData,
325                           _: Name,
326                           _: &'v Generics,
327                           _parent_id: NodeId,
328                           _: Span) {
329         walk_struct_def(self, s)
330     }
331     fn visit_struct_field(&mut self, s: &'v StructField) {
332         walk_struct_field(self, s)
333     }
334     fn visit_enum_def(&mut self,
335                       enum_definition: &'v EnumDef,
336                       generics: &'v Generics,
337                       item_id: NodeId,
338                       _: Span) {
339         walk_enum_def(self, enum_definition, generics, item_id)
340     }
341     fn visit_variant(&mut self, v: &'v Variant, g: &'v Generics, item_id: NodeId) {
342         walk_variant(self, v, g, item_id)
343     }
344     fn visit_label(&mut self, label: &'v Label) {
345         walk_label(self, label)
346     }
347     fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg) {
348         match generic_arg {
349             GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
350             GenericArg::Type(ty) => self.visit_ty(ty),
351         }
352     }
353     fn visit_lifetime(&mut self, lifetime: &'v Lifetime) {
354         walk_lifetime(self, lifetime)
355     }
356     fn visit_qpath(&mut self, qpath: &'v QPath, id: NodeId, span: Span) {
357         walk_qpath(self, qpath, id, span)
358     }
359     fn visit_path(&mut self, path: &'v Path, _id: NodeId) {
360         walk_path(self, path)
361     }
362     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment) {
363         walk_path_segment(self, path_span, path_segment)
364     }
365     fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs) {
366         walk_generic_args(self, path_span, generic_args)
367     }
368     fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding) {
369         walk_assoc_type_binding(self, type_binding)
370     }
371     fn visit_attribute(&mut self, _attr: &'v Attribute) {
372     }
373     fn visit_macro_def(&mut self, macro_def: &'v MacroDef) {
374         walk_macro_def(self, macro_def)
375     }
376     fn visit_vis(&mut self, vis: &'v Visibility) {
377         walk_vis(self, vis)
378     }
379     fn visit_associated_item_kind(&mut self, kind: &'v AssociatedItemKind) {
380         walk_associated_item_kind(self, kind);
381     }
382     fn visit_defaultness(&mut self, defaultness: &'v Defaultness) {
383         walk_defaultness(self, defaultness);
384     }
385 }
386
387 /// Walks the contents of a crate. See also `Crate::visit_all_items`.
388 pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate) {
389     visitor.visit_mod(&krate.module, krate.span, CRATE_NODE_ID);
390     walk_list!(visitor, visit_attribute, &krate.attrs);
391     walk_list!(visitor, visit_macro_def, &krate.exported_macros);
392 }
393
394 pub fn walk_macro_def<'v, V: Visitor<'v>>(visitor: &mut V, macro_def: &'v MacroDef) {
395     visitor.visit_id(macro_def.id);
396     visitor.visit_name(macro_def.span, macro_def.name);
397     walk_list!(visitor, visit_attribute, &macro_def.attrs);
398 }
399
400 pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod, mod_node_id: NodeId) {
401     visitor.visit_id(mod_node_id);
402     for &item_id in &module.item_ids {
403         visitor.visit_nested_item(item_id);
404     }
405 }
406
407 pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body) {
408     for argument in &body.arguments {
409         visitor.visit_id(argument.id);
410         visitor.visit_pat(&argument.pat);
411     }
412     visitor.visit_expr(&body.value);
413 }
414
415 pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local) {
416     // Intentionally visiting the expr first - the initialization expr
417     // dominates the local's definition.
418     walk_list!(visitor, visit_expr, &local.init);
419     walk_list!(visitor, visit_attribute, local.attrs.iter());
420     visitor.visit_id(local.id);
421     visitor.visit_pat(&local.pat);
422     walk_list!(visitor, visit_ty, &local.ty);
423 }
424
425 pub fn walk_ident<'v, V: Visitor<'v>>(visitor: &mut V, ident: Ident) {
426     visitor.visit_name(ident.span, ident.name);
427 }
428
429 pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) {
430     visitor.visit_name(label.span, label.name);
431 }
432
433 pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) {
434     visitor.visit_id(lifetime.id);
435     match lifetime.name {
436         LifetimeName::Param(ParamName::Plain(name)) => {
437             visitor.visit_name(lifetime.span, name);
438         }
439         LifetimeName::Param(ParamName::Fresh(_)) |
440         LifetimeName::Static |
441         LifetimeName::Implicit |
442         LifetimeName::Underscore => {}
443     }
444 }
445
446 pub fn walk_poly_trait_ref<'v, V>(visitor: &mut V,
447                                   trait_ref: &'v PolyTraitRef,
448                                   _modifier: TraitBoundModifier)
449     where V: Visitor<'v>
450 {
451     walk_list!(visitor, visit_generic_param, &trait_ref.bound_generic_params);
452     visitor.visit_trait_ref(&trait_ref.trait_ref);
453 }
454
455 pub fn walk_trait_ref<'v, V>(visitor: &mut V, trait_ref: &'v TraitRef)
456     where V: Visitor<'v>
457 {
458     visitor.visit_id(trait_ref.ref_id);
459     visitor.visit_path(&trait_ref.path, trait_ref.ref_id)
460 }
461
462 pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) {
463     visitor.visit_vis(&item.vis);
464     visitor.visit_name(item.span, item.name);
465     match item.node {
466         ItemExternCrate(orig_name) => {
467             visitor.visit_id(item.id);
468             if let Some(orig_name) = orig_name {
469                 visitor.visit_name(item.span, orig_name);
470             }
471         }
472         ItemUse(ref path, _) => {
473             visitor.visit_id(item.id);
474             visitor.visit_path(path, item.id);
475         }
476         ItemStatic(ref typ, _, body) |
477         ItemConst(ref typ, body) => {
478             visitor.visit_id(item.id);
479             visitor.visit_ty(typ);
480             visitor.visit_nested_body(body);
481         }
482         ItemFn(ref declaration, unsafety, constness, abi, ref generics, body_id) => {
483             visitor.visit_fn(FnKind::ItemFn(item.name,
484                                             generics,
485                                             unsafety,
486                                             constness,
487                                             abi,
488                                             &item.vis,
489                                             &item.attrs),
490                              declaration,
491                              body_id,
492                              item.span,
493                              item.id)
494         }
495         ItemMod(ref module) => {
496             // visit_mod() takes care of visiting the Item's NodeId
497             visitor.visit_mod(module, item.span, item.id)
498         }
499         ItemForeignMod(ref foreign_module) => {
500             visitor.visit_id(item.id);
501             walk_list!(visitor, visit_foreign_item, &foreign_module.items);
502         }
503         ItemGlobalAsm(_) => {
504             visitor.visit_id(item.id);
505         }
506         ItemTy(ref typ, ref type_parameters) => {
507             visitor.visit_id(item.id);
508             visitor.visit_ty(typ);
509             visitor.visit_generics(type_parameters)
510         }
511         ItemExistential(ExistTy {ref generics, ref bounds, impl_trait_fn}) => {
512             visitor.visit_id(item.id);
513             walk_generics(visitor, generics);
514             walk_list!(visitor, visit_ty_param_bound, bounds);
515             if let Some(impl_trait_fn) = impl_trait_fn {
516                 visitor.visit_def_mention(Def::Fn(impl_trait_fn))
517             }
518         }
519         ItemEnum(ref enum_definition, ref type_parameters) => {
520             visitor.visit_generics(type_parameters);
521             // visit_enum_def() takes care of visiting the Item's NodeId
522             visitor.visit_enum_def(enum_definition, type_parameters, item.id, item.span)
523         }
524         ItemImpl(.., ref type_parameters, ref opt_trait_reference, ref typ, ref impl_item_refs) => {
525             visitor.visit_id(item.id);
526             visitor.visit_generics(type_parameters);
527             walk_list!(visitor, visit_trait_ref, opt_trait_reference);
528             visitor.visit_ty(typ);
529             walk_list!(visitor, visit_impl_item_ref, impl_item_refs);
530         }
531         ItemStruct(ref struct_definition, ref generics) |
532         ItemUnion(ref struct_definition, ref generics) => {
533             visitor.visit_generics(generics);
534             visitor.visit_id(item.id);
535             visitor.visit_variant_data(struct_definition, item.name, generics, item.id, item.span);
536         }
537         ItemTrait(.., ref generics, ref bounds, ref trait_item_refs) => {
538             visitor.visit_id(item.id);
539             visitor.visit_generics(generics);
540             walk_list!(visitor, visit_param_bound, bounds);
541             walk_list!(visitor, visit_trait_item_ref, trait_item_refs);
542         }
543         ItemTraitAlias(ref generics, ref bounds) => {
544             visitor.visit_id(item.id);
545             visitor.visit_generics(generics);
546             walk_list!(visitor, visit_param_bound, bounds);
547         }
548     }
549     walk_list!(visitor, visit_attribute, &item.attrs);
550 }
551
552 pub fn walk_enum_def<'v, V: Visitor<'v>>(visitor: &mut V,
553                                          enum_definition: &'v EnumDef,
554                                          generics: &'v Generics,
555                                          item_id: NodeId) {
556     visitor.visit_id(item_id);
557     walk_list!(visitor,
558                visit_variant,
559                &enum_definition.variants,
560                generics,
561                item_id);
562 }
563
564 pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V,
565                                         variant: &'v Variant,
566                                         generics: &'v Generics,
567                                         parent_item_id: NodeId) {
568     visitor.visit_name(variant.span, variant.node.name);
569     visitor.visit_variant_data(&variant.node.data,
570                                variant.node.name,
571                                generics,
572                                parent_item_id,
573                                variant.span);
574     walk_list!(visitor, visit_anon_const, &variant.node.disr_expr);
575     walk_list!(visitor, visit_attribute, &variant.node.attrs);
576 }
577
578 pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) {
579     visitor.visit_id(typ.id);
580
581     match typ.node {
582         TySlice(ref ty) => {
583             visitor.visit_ty(ty)
584         }
585         TyPtr(ref mutable_type) => {
586             visitor.visit_ty(&mutable_type.ty)
587         }
588         TyRptr(ref lifetime, ref mutable_type) => {
589             visitor.visit_lifetime(lifetime);
590             visitor.visit_ty(&mutable_type.ty)
591         }
592         TyNever => {},
593         TyTup(ref tuple_element_types) => {
594             walk_list!(visitor, visit_ty, tuple_element_types);
595         }
596         TyBareFn(ref function_declaration) => {
597             walk_list!(visitor, visit_generic_param, &function_declaration.generic_params);
598             visitor.visit_fn_decl(&function_declaration.decl);
599         }
600         TyPath(ref qpath) => {
601             visitor.visit_qpath(qpath, typ.id, typ.span);
602         }
603         TyArray(ref ty, ref length) => {
604             visitor.visit_ty(ty);
605             visitor.visit_anon_const(length)
606         }
607         TyTraitObject(ref bounds, ref lifetime) => {
608             for bound in bounds {
609                 visitor.visit_poly_trait_ref(bound, TraitBoundModifier::None);
610             }
611             visitor.visit_lifetime(lifetime);
612         }
613         TyImplTraitExistential(item_id, def_id, ref lifetimes) => {
614             visitor.visit_def_mention(Def::Existential(def_id));
615             visitor.visit_nested_item(item_id);
616             walk_list!(visitor, visit_lifetime, lifetimes);
617         }
618         TyTypeof(ref expression) => {
619             visitor.visit_anon_const(expression)
620         }
621         TyInfer | TyErr => {}
622     }
623 }
624
625 pub fn walk_qpath<'v, V: Visitor<'v>>(visitor: &mut V, qpath: &'v QPath, id: NodeId, span: Span) {
626     match *qpath {
627         QPath::Resolved(ref maybe_qself, ref path) => {
628             if let Some(ref qself) = *maybe_qself {
629                 visitor.visit_ty(qself);
630             }
631             visitor.visit_path(path, id)
632         }
633         QPath::TypeRelative(ref qself, ref segment) => {
634             visitor.visit_ty(qself);
635             visitor.visit_path_segment(span, segment);
636         }
637     }
638 }
639
640 pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path) {
641     visitor.visit_def_mention(path.def);
642     for segment in &path.segments {
643         visitor.visit_path_segment(path.span, segment);
644     }
645 }
646
647 pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V,
648                                              path_span: Span,
649                                              segment: &'v PathSegment) {
650     visitor.visit_name(path_span, segment.name);
651     if let Some(ref args) = segment.args {
652         visitor.visit_generic_args(path_span, args);
653     }
654 }
655
656 pub fn walk_generic_args<'v, V: Visitor<'v>>(visitor: &mut V,
657                                              _path_span: Span,
658                                              generic_args: &'v GenericArgs) {
659     walk_list!(visitor, visit_generic_arg, &generic_args.args);
660     walk_list!(visitor, visit_assoc_type_binding, &generic_args.bindings);
661 }
662
663 pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(visitor: &mut V,
664                                                    type_binding: &'v TypeBinding) {
665     visitor.visit_id(type_binding.id);
666     visitor.visit_name(type_binding.span, type_binding.name);
667     visitor.visit_ty(&type_binding.ty);
668 }
669
670 pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) {
671     visitor.visit_id(pattern.id);
672     match pattern.node {
673         PatKind::TupleStruct(ref qpath, ref children, _) => {
674             visitor.visit_qpath(qpath, pattern.id, pattern.span);
675             walk_list!(visitor, visit_pat, children);
676         }
677         PatKind::Path(ref qpath) => {
678             visitor.visit_qpath(qpath, pattern.id, pattern.span);
679         }
680         PatKind::Struct(ref qpath, ref fields, _) => {
681             visitor.visit_qpath(qpath, pattern.id, pattern.span);
682             for field in fields {
683                 visitor.visit_id(field.node.id);
684                 visitor.visit_ident(field.node.ident);
685                 visitor.visit_pat(&field.node.pat)
686             }
687         }
688         PatKind::Tuple(ref tuple_elements, _) => {
689             walk_list!(visitor, visit_pat, tuple_elements);
690         }
691         PatKind::Box(ref subpattern) |
692         PatKind::Ref(ref subpattern, _) => {
693             visitor.visit_pat(subpattern)
694         }
695         PatKind::Binding(_, canonical_id, ref pth1, ref optional_subpattern) => {
696             visitor.visit_def_mention(Def::Local(canonical_id));
697             visitor.visit_name(pth1.span, pth1.node);
698             walk_list!(visitor, visit_pat, optional_subpattern);
699         }
700         PatKind::Lit(ref expression) => visitor.visit_expr(expression),
701         PatKind::Range(ref lower_bound, ref upper_bound, _) => {
702             visitor.visit_expr(lower_bound);
703             visitor.visit_expr(upper_bound)
704         }
705         PatKind::Wild => (),
706         PatKind::Slice(ref prepatterns, ref slice_pattern, ref postpatterns) => {
707             walk_list!(visitor, visit_pat, prepatterns);
708             walk_list!(visitor, visit_pat, slice_pattern);
709             walk_list!(visitor, visit_pat, postpatterns);
710         }
711     }
712 }
713
714 pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem) {
715     visitor.visit_id(foreign_item.id);
716     visitor.visit_vis(&foreign_item.vis);
717     visitor.visit_name(foreign_item.span, foreign_item.name);
718
719     match foreign_item.node {
720         ForeignItemFn(ref function_declaration, ref names, ref generics) => {
721             visitor.visit_generics(generics);
722             visitor.visit_fn_decl(function_declaration);
723             for name in names {
724                 visitor.visit_name(name.span, name.node);
725             }
726         }
727         ForeignItemStatic(ref typ, _) => visitor.visit_ty(typ),
728         ForeignItemType => (),
729     }
730
731     walk_list!(visitor, visit_attribute, &foreign_item.attrs);
732 }
733
734 pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound) {
735     match *bound {
736         GenericBound::Trait(ref typ, modifier) => {
737             visitor.visit_poly_trait_ref(typ, modifier);
738         }
739         GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime),
740     }
741 }
742
743 pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) {
744     visitor.visit_id(param.id);
745     match param.name {
746         ParamName::Plain(name) => visitor.visit_name(param.span, name),
747         ParamName::Fresh(_) => {}
748     }
749     match param.kind {
750         GenericParamKind::Lifetime { .. } => {}
751         GenericParamKind::Type { ref default, .. } => walk_list!(visitor, visit_ty, default),
752     }
753     walk_list!(visitor, visit_attribute, &param.attrs);
754     walk_list!(visitor, visit_param_bound, &param.bounds);
755 }
756
757 pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) {
758     walk_list!(visitor, visit_generic_param, &generics.params);
759     visitor.visit_id(generics.where_clause.id);
760     walk_list!(visitor, visit_where_predicate, &generics.where_clause.predicates);
761 }
762
763 pub fn walk_where_predicate<'v, V: Visitor<'v>>(
764     visitor: &mut V,
765     predicate: &'v WherePredicate)
766 {
767     match predicate {
768         &WherePredicate::BoundPredicate(WhereBoundPredicate{ref bounded_ty,
769                                                             ref bounds,
770                                                             ref bound_generic_params,
771                                                             ..}) => {
772             visitor.visit_ty(bounded_ty);
773             walk_list!(visitor, visit_param_bound, bounds);
774             walk_list!(visitor, visit_generic_param, bound_generic_params);
775         }
776         &WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime,
777                                                               ref bounds,
778                                                               ..}) => {
779             visitor.visit_lifetime(lifetime);
780             walk_list!(visitor, visit_param_bound, bounds);
781         }
782         &WherePredicate::EqPredicate(WhereEqPredicate{id,
783                                                       ref lhs_ty,
784                                                       ref rhs_ty,
785                                                       ..}) => {
786             visitor.visit_id(id);
787             visitor.visit_ty(lhs_ty);
788             visitor.visit_ty(rhs_ty);
789         }
790     }
791 }
792
793 pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FunctionRetTy) {
794     if let Return(ref output_ty) = *ret_ty {
795         visitor.visit_ty(output_ty)
796     }
797 }
798
799 pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl) {
800     for ty in &function_declaration.inputs {
801         visitor.visit_ty(ty)
802     }
803     walk_fn_ret_ty(visitor, &function_declaration.output)
804 }
805
806 pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, function_kind: FnKind<'v>) {
807     match function_kind {
808         FnKind::ItemFn(_, generics, ..) => {
809             visitor.visit_generics(generics);
810         }
811         FnKind::Method(..) |
812         FnKind::Closure(_) => {}
813     }
814 }
815
816 pub fn walk_fn<'v, V: Visitor<'v>>(visitor: &mut V,
817                                    function_kind: FnKind<'v>,
818                                    function_declaration: &'v FnDecl,
819                                    body_id: BodyId,
820                                    _span: Span,
821                                    id: NodeId) {
822     visitor.visit_id(id);
823     visitor.visit_fn_decl(function_declaration);
824     walk_fn_kind(visitor, function_kind);
825     visitor.visit_nested_body(body_id)
826 }
827
828 pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v TraitItem) {
829     visitor.visit_name(trait_item.span, trait_item.name);
830     walk_list!(visitor, visit_attribute, &trait_item.attrs);
831     visitor.visit_generics(&trait_item.generics);
832     match trait_item.node {
833         TraitItemKind::Const(ref ty, default) => {
834             visitor.visit_id(trait_item.id);
835             visitor.visit_ty(ty);
836             walk_list!(visitor, visit_nested_body, default);
837         }
838         TraitItemKind::Method(ref sig, TraitMethod::Required(ref names)) => {
839             visitor.visit_id(trait_item.id);
840             visitor.visit_fn_decl(&sig.decl);
841             for name in names {
842                 visitor.visit_name(name.span, name.node);
843             }
844         }
845         TraitItemKind::Method(ref sig, TraitMethod::Provided(body_id)) => {
846             visitor.visit_fn(FnKind::Method(trait_item.name,
847                                             sig,
848                                             None,
849                                             &trait_item.attrs),
850                              &sig.decl,
851                              body_id,
852                              trait_item.span,
853                              trait_item.id);
854         }
855         TraitItemKind::Type(ref bounds, ref default) => {
856             visitor.visit_id(trait_item.id);
857             walk_list!(visitor, visit_param_bound, bounds);
858             walk_list!(visitor, visit_ty, default);
859         }
860     }
861 }
862
863 pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: &'v TraitItemRef) {
864     // NB: Deliberately force a compilation error if/when new fields are added.
865     let TraitItemRef { id, name, ref kind, span, ref defaultness } = *trait_item_ref;
866     visitor.visit_nested_trait_item(id);
867     visitor.visit_name(span, name);
868     visitor.visit_associated_item_kind(kind);
869     visitor.visit_defaultness(defaultness);
870 }
871
872 pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem) {
873     // NB: Deliberately force a compilation error if/when new fields are added.
874     let ImplItem {
875         id: _,
876         hir_id: _,
877         name,
878         ref vis,
879         ref defaultness,
880         ref attrs,
881         ref generics,
882         ref node,
883         span
884     } = *impl_item;
885
886     visitor.visit_name(span, name);
887     visitor.visit_vis(vis);
888     visitor.visit_defaultness(defaultness);
889     walk_list!(visitor, visit_attribute, attrs);
890     visitor.visit_generics(generics);
891     match *node {
892         ImplItemKind::Const(ref ty, body) => {
893             visitor.visit_id(impl_item.id);
894             visitor.visit_ty(ty);
895             visitor.visit_nested_body(body);
896         }
897         ImplItemKind::Method(ref sig, body_id) => {
898             visitor.visit_fn(FnKind::Method(impl_item.name,
899                                             sig,
900                                             Some(&impl_item.vis),
901                                             &impl_item.attrs),
902                              &sig.decl,
903                              body_id,
904                              impl_item.span,
905                              impl_item.id);
906         }
907         ImplItemKind::Type(ref ty) => {
908             visitor.visit_id(impl_item.id);
909             visitor.visit_ty(ty);
910         }
911     }
912 }
913
914 pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) {
915     // NB: Deliberately force a compilation error if/when new fields are added.
916     let ImplItemRef { id, name, ref kind, span, ref vis, ref defaultness } = *impl_item_ref;
917     visitor.visit_nested_impl_item(id);
918     visitor.visit_name(span, name);
919     visitor.visit_associated_item_kind(kind);
920     visitor.visit_vis(vis);
921     visitor.visit_defaultness(defaultness);
922 }
923
924
925 pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V, struct_definition: &'v VariantData) {
926     visitor.visit_id(struct_definition.id());
927     walk_list!(visitor, visit_struct_field, struct_definition.fields());
928 }
929
930 pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, struct_field: &'v StructField) {
931     visitor.visit_id(struct_field.id);
932     visitor.visit_vis(&struct_field.vis);
933     visitor.visit_ident(struct_field.ident);
934     visitor.visit_ty(&struct_field.ty);
935     walk_list!(visitor, visit_attribute, &struct_field.attrs);
936 }
937
938 pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block) {
939     visitor.visit_id(block.id);
940     walk_list!(visitor, visit_stmt, &block.stmts);
941     walk_list!(visitor, visit_expr, &block.expr);
942 }
943
944 pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt) {
945     match statement.node {
946         StmtDecl(ref declaration, id) => {
947             visitor.visit_id(id);
948             visitor.visit_decl(declaration)
949         }
950         StmtExpr(ref expression, id) |
951         StmtSemi(ref expression, id) => {
952             visitor.visit_id(id);
953             visitor.visit_expr(expression)
954         }
955     }
956 }
957
958 pub fn walk_decl<'v, V: Visitor<'v>>(visitor: &mut V, declaration: &'v Decl) {
959     match declaration.node {
960         DeclLocal(ref local) => visitor.visit_local(local),
961         DeclItem(item) => visitor.visit_nested_item(item),
962     }
963 }
964
965 pub fn walk_anon_const<'v, V: Visitor<'v>>(visitor: &mut V, constant: &'v AnonConst) {
966     visitor.visit_id(constant.id);
967     visitor.visit_nested_body(constant.body);
968 }
969
970 pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
971     visitor.visit_id(expression.id);
972     walk_list!(visitor, visit_attribute, expression.attrs.iter());
973     match expression.node {
974         ExprBox(ref subexpression) => {
975             visitor.visit_expr(subexpression)
976         }
977         ExprArray(ref subexpressions) => {
978             walk_list!(visitor, visit_expr, subexpressions);
979         }
980         ExprRepeat(ref element, ref count) => {
981             visitor.visit_expr(element);
982             visitor.visit_anon_const(count)
983         }
984         ExprStruct(ref qpath, ref fields, ref optional_base) => {
985             visitor.visit_qpath(qpath, expression.id, expression.span);
986             for field in fields {
987                 visitor.visit_id(field.id);
988                 visitor.visit_ident(field.ident);
989                 visitor.visit_expr(&field.expr)
990             }
991             walk_list!(visitor, visit_expr, optional_base);
992         }
993         ExprTup(ref subexpressions) => {
994             walk_list!(visitor, visit_expr, subexpressions);
995         }
996         ExprCall(ref callee_expression, ref arguments) => {
997             visitor.visit_expr(callee_expression);
998             walk_list!(visitor, visit_expr, arguments);
999         }
1000         ExprMethodCall(ref segment, _, ref arguments) => {
1001             visitor.visit_path_segment(expression.span, segment);
1002             walk_list!(visitor, visit_expr, arguments);
1003         }
1004         ExprBinary(_, ref left_expression, ref right_expression) => {
1005             visitor.visit_expr(left_expression);
1006             visitor.visit_expr(right_expression)
1007         }
1008         ExprAddrOf(_, ref subexpression) | ExprUnary(_, ref subexpression) => {
1009             visitor.visit_expr(subexpression)
1010         }
1011         ExprLit(_) => {}
1012         ExprCast(ref subexpression, ref typ) | ExprType(ref subexpression, ref typ) => {
1013             visitor.visit_expr(subexpression);
1014             visitor.visit_ty(typ)
1015         }
1016         ExprIf(ref head_expression, ref if_block, ref optional_else) => {
1017             visitor.visit_expr(head_expression);
1018             visitor.visit_expr(if_block);
1019             walk_list!(visitor, visit_expr, optional_else);
1020         }
1021         ExprWhile(ref subexpression, ref block, ref opt_label) => {
1022             walk_list!(visitor, visit_label, opt_label);
1023             visitor.visit_expr(subexpression);
1024             visitor.visit_block(block);
1025         }
1026         ExprLoop(ref block, ref opt_label, _) => {
1027             walk_list!(visitor, visit_label, opt_label);
1028             visitor.visit_block(block);
1029         }
1030         ExprMatch(ref subexpression, ref arms, _) => {
1031             visitor.visit_expr(subexpression);
1032             walk_list!(visitor, visit_arm, arms);
1033         }
1034         ExprClosure(_, ref function_declaration, body, _fn_decl_span, _gen) => {
1035             visitor.visit_fn(FnKind::Closure(&expression.attrs),
1036                              function_declaration,
1037                              body,
1038                              expression.span,
1039                              expression.id)
1040         }
1041         ExprBlock(ref block, ref opt_label) => {
1042             walk_list!(visitor, visit_label, opt_label);
1043             visitor.visit_block(block);
1044         }
1045         ExprAssign(ref left_hand_expression, ref right_hand_expression) => {
1046             visitor.visit_expr(right_hand_expression);
1047             visitor.visit_expr(left_hand_expression)
1048         }
1049         ExprAssignOp(_, ref left_expression, ref right_expression) => {
1050             visitor.visit_expr(right_expression);
1051             visitor.visit_expr(left_expression)
1052         }
1053         ExprField(ref subexpression, ident) => {
1054             visitor.visit_expr(subexpression);
1055             visitor.visit_ident(ident);
1056         }
1057         ExprIndex(ref main_expression, ref index_expression) => {
1058             visitor.visit_expr(main_expression);
1059             visitor.visit_expr(index_expression)
1060         }
1061         ExprPath(ref qpath) => {
1062             visitor.visit_qpath(qpath, expression.id, expression.span);
1063         }
1064         ExprBreak(ref destination, ref opt_expr) => {
1065             if let Some(ref label) = destination.label {
1066                 visitor.visit_label(label);
1067                 match destination.target_id {
1068                     Ok(node_id) => visitor.visit_def_mention(Def::Label(node_id)),
1069                     Err(_) => {},
1070                 };
1071             }
1072             walk_list!(visitor, visit_expr, opt_expr);
1073         }
1074         ExprAgain(ref destination) => {
1075             if let Some(ref label) = destination.label {
1076                 visitor.visit_label(label);
1077                 match destination.target_id {
1078                     Ok(node_id) => visitor.visit_def_mention(Def::Label(node_id)),
1079                     Err(_) => {},
1080                 };
1081             }
1082         }
1083         ExprRet(ref optional_expression) => {
1084             walk_list!(visitor, visit_expr, optional_expression);
1085         }
1086         ExprInlineAsm(_, ref outputs, ref inputs) => {
1087             for output in outputs {
1088                 visitor.visit_expr(output)
1089             }
1090             for input in inputs {
1091                 visitor.visit_expr(input)
1092             }
1093         }
1094         ExprYield(ref subexpression) => {
1095             visitor.visit_expr(subexpression);
1096         }
1097     }
1098 }
1099
1100 pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm) {
1101     walk_list!(visitor, visit_pat, &arm.pats);
1102     walk_list!(visitor, visit_expr, &arm.guard);
1103     visitor.visit_expr(&arm.body);
1104     walk_list!(visitor, visit_attribute, &arm.attrs);
1105 }
1106
1107 pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility) {
1108     if let Visibility::Restricted { ref path, id } = *vis {
1109         visitor.visit_id(id);
1110         visitor.visit_path(path, id)
1111     }
1112 }
1113
1114 pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssociatedItemKind) {
1115     // No visitable content here: this fn exists so you can call it if
1116     // the right thing to do, should content be added in the future,
1117     // would be to walk it.
1118 }
1119
1120 pub fn walk_defaultness<'v, V: Visitor<'v>>(_: &mut V, _: &'v Defaultness) {
1121     // No visitable content here: this fn exists so you can call it if
1122     // the right thing to do, should content be added in the future,
1123     // would be to walk it.
1124 }
1125
1126 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq)]
1127 pub struct IdRange {
1128     pub min: NodeId,
1129     pub max: NodeId,
1130 }
1131
1132 impl IdRange {
1133     pub fn max() -> IdRange {
1134         IdRange {
1135             min: NodeId::from_u32(u32::MAX),
1136             max: NodeId::from_u32(u32::MIN),
1137         }
1138     }
1139
1140     pub fn empty(&self) -> bool {
1141         self.min >= self.max
1142     }
1143
1144     pub fn contains(&self, id: NodeId) -> bool {
1145         id >= self.min && id < self.max
1146     }
1147
1148     pub fn add(&mut self, id: NodeId) {
1149         self.min = cmp::min(self.min, id);
1150         self.max = cmp::max(self.max, NodeId::from_u32(id.as_u32() + 1));
1151     }
1152
1153 }
1154
1155
1156 pub struct IdRangeComputingVisitor<'a, 'hir: 'a> {
1157     result: IdRange,
1158     map: &'a map::Map<'hir>,
1159 }
1160
1161 impl<'a, 'hir> IdRangeComputingVisitor<'a, 'hir> {
1162     pub fn new(map: &'a map::Map<'hir>) -> IdRangeComputingVisitor<'a, 'hir> {
1163         IdRangeComputingVisitor { result: IdRange::max(), map: map }
1164     }
1165
1166     pub fn result(&self) -> IdRange {
1167         self.result
1168     }
1169 }
1170
1171 impl<'a, 'hir> Visitor<'hir> for IdRangeComputingVisitor<'a, 'hir> {
1172     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
1173         NestedVisitorMap::OnlyBodies(&self.map)
1174     }
1175
1176     fn visit_id(&mut self, id: NodeId) {
1177         self.result.add(id);
1178     }
1179 }