]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/intravisit.rs
Auto merge of #47956 - retep998:is-nibbles, r=BurntSushi
[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 syntax::abi::Abi;
45 use syntax::ast::{NodeId, CRATE_NODE_ID, 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_mod(&mut self, m: &'v Mod, _s: Span, n: NodeId) {
252         walk_mod(self, m, n)
253     }
254     fn visit_foreign_item(&mut self, i: &'v ForeignItem) {
255         walk_foreign_item(self, i)
256     }
257     fn visit_local(&mut self, l: &'v Local) {
258         walk_local(self, l)
259     }
260     fn visit_block(&mut self, b: &'v Block) {
261         walk_block(self, b)
262     }
263     fn visit_stmt(&mut self, s: &'v Stmt) {
264         walk_stmt(self, s)
265     }
266     fn visit_arm(&mut self, a: &'v Arm) {
267         walk_arm(self, a)
268     }
269     fn visit_pat(&mut self, p: &'v Pat) {
270         walk_pat(self, p)
271     }
272     fn visit_decl(&mut self, d: &'v Decl) {
273         walk_decl(self, d)
274     }
275     fn visit_expr(&mut self, ex: &'v Expr) {
276         walk_expr(self, ex)
277     }
278     fn visit_ty(&mut self, t: &'v Ty) {
279         walk_ty(self, t)
280     }
281     fn visit_generic_param(&mut self, p: &'v GenericParam) {
282         walk_generic_param(self, p)
283     }
284     fn visit_generics(&mut self, g: &'v Generics) {
285         walk_generics(self, g)
286     }
287     fn visit_where_predicate(&mut self, predicate: &'v WherePredicate) {
288         walk_where_predicate(self, predicate)
289     }
290     fn visit_fn_decl(&mut self, fd: &'v FnDecl) {
291         walk_fn_decl(self, fd)
292     }
293     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: BodyId, s: Span, id: NodeId) {
294         walk_fn(self, fk, fd, b, s, id)
295     }
296     fn visit_trait_item(&mut self, ti: &'v TraitItem) {
297         walk_trait_item(self, ti)
298     }
299     fn visit_trait_item_ref(&mut self, ii: &'v TraitItemRef) {
300         walk_trait_item_ref(self, ii)
301     }
302     fn visit_impl_item(&mut self, ii: &'v ImplItem) {
303         walk_impl_item(self, ii)
304     }
305     fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) {
306         walk_impl_item_ref(self, ii)
307     }
308     fn visit_trait_ref(&mut self, t: &'v TraitRef) {
309         walk_trait_ref(self, t)
310     }
311     fn visit_ty_param_bound(&mut self, bounds: &'v TyParamBound) {
312         walk_ty_param_bound(self, bounds)
313     }
314     fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: TraitBoundModifier) {
315         walk_poly_trait_ref(self, t, m)
316     }
317     fn visit_variant_data(&mut self,
318                           s: &'v VariantData,
319                           _: Name,
320                           _: &'v Generics,
321                           _parent_id: NodeId,
322                           _: Span) {
323         walk_struct_def(self, s)
324     }
325     fn visit_struct_field(&mut self, s: &'v StructField) {
326         walk_struct_field(self, s)
327     }
328     fn visit_enum_def(&mut self,
329                       enum_definition: &'v EnumDef,
330                       generics: &'v Generics,
331                       item_id: NodeId,
332                       _: Span) {
333         walk_enum_def(self, enum_definition, generics, item_id)
334     }
335     fn visit_variant(&mut self, v: &'v Variant, g: &'v Generics, item_id: NodeId) {
336         walk_variant(self, v, g, item_id)
337     }
338     fn visit_label(&mut self, label: &'v Label) {
339         walk_label(self, label)
340     }
341     fn visit_lifetime(&mut self, lifetime: &'v Lifetime) {
342         walk_lifetime(self, lifetime)
343     }
344     fn visit_qpath(&mut self, qpath: &'v QPath, id: NodeId, span: Span) {
345         walk_qpath(self, qpath, id, span)
346     }
347     fn visit_path(&mut self, path: &'v Path, _id: NodeId) {
348         walk_path(self, path)
349     }
350     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment) {
351         walk_path_segment(self, path_span, path_segment)
352     }
353     fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &'v PathParameters) {
354         walk_path_parameters(self, path_span, path_parameters)
355     }
356     fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding) {
357         walk_assoc_type_binding(self, type_binding)
358     }
359     fn visit_attribute(&mut self, _attr: &'v Attribute) {
360     }
361     fn visit_macro_def(&mut self, macro_def: &'v MacroDef) {
362         walk_macro_def(self, macro_def)
363     }
364     fn visit_vis(&mut self, vis: &'v Visibility) {
365         walk_vis(self, vis)
366     }
367     fn visit_associated_item_kind(&mut self, kind: &'v AssociatedItemKind) {
368         walk_associated_item_kind(self, kind);
369     }
370     fn visit_defaultness(&mut self, defaultness: &'v Defaultness) {
371         walk_defaultness(self, defaultness);
372     }
373 }
374
375 /// Walks the contents of a crate. See also `Crate::visit_all_items`.
376 pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate) {
377     visitor.visit_mod(&krate.module, krate.span, CRATE_NODE_ID);
378     walk_list!(visitor, visit_attribute, &krate.attrs);
379     walk_list!(visitor, visit_macro_def, &krate.exported_macros);
380 }
381
382 pub fn walk_macro_def<'v, V: Visitor<'v>>(visitor: &mut V, macro_def: &'v MacroDef) {
383     visitor.visit_id(macro_def.id);
384     visitor.visit_name(macro_def.span, macro_def.name);
385     walk_list!(visitor, visit_attribute, &macro_def.attrs);
386 }
387
388 pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod, mod_node_id: NodeId) {
389     visitor.visit_id(mod_node_id);
390     for &item_id in &module.item_ids {
391         visitor.visit_nested_item(item_id);
392     }
393 }
394
395 pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body) {
396     for argument in &body.arguments {
397         visitor.visit_id(argument.id);
398         visitor.visit_pat(&argument.pat);
399     }
400     visitor.visit_expr(&body.value);
401 }
402
403 pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local) {
404     // Intentionally visiting the expr first - the initialization expr
405     // dominates the local's definition.
406     walk_list!(visitor, visit_expr, &local.init);
407
408     visitor.visit_id(local.id);
409     visitor.visit_pat(&local.pat);
410     walk_list!(visitor, visit_ty, &local.ty);
411 }
412
413 pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) {
414     visitor.visit_name(label.span, label.name);
415 }
416
417 pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) {
418     visitor.visit_id(lifetime.id);
419     match lifetime.name {
420         LifetimeName::Name(name) => {
421             visitor.visit_name(lifetime.span, name);
422         }
423         LifetimeName::Static | LifetimeName::Implicit | LifetimeName::Underscore => {}
424     }
425 }
426
427 pub fn walk_poly_trait_ref<'v, V>(visitor: &mut V,
428                                   trait_ref: &'v PolyTraitRef,
429                                   _modifier: TraitBoundModifier)
430     where V: Visitor<'v>
431 {
432     walk_list!(visitor, visit_generic_param, &trait_ref.bound_generic_params);
433     visitor.visit_trait_ref(&trait_ref.trait_ref);
434 }
435
436 pub fn walk_trait_ref<'v, V>(visitor: &mut V, trait_ref: &'v TraitRef)
437     where V: Visitor<'v>
438 {
439     visitor.visit_id(trait_ref.ref_id);
440     visitor.visit_path(&trait_ref.path, trait_ref.ref_id)
441 }
442
443 pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) {
444     visitor.visit_vis(&item.vis);
445     visitor.visit_name(item.span, item.name);
446     match item.node {
447         ItemExternCrate(opt_name) => {
448             visitor.visit_id(item.id);
449             if let Some(name) = opt_name {
450                 visitor.visit_name(item.span, name);
451             }
452         }
453         ItemUse(ref path, _) => {
454             visitor.visit_id(item.id);
455             visitor.visit_path(path, item.id);
456         }
457         ItemStatic(ref typ, _, body) |
458         ItemConst(ref typ, body) => {
459             visitor.visit_id(item.id);
460             visitor.visit_ty(typ);
461             visitor.visit_nested_body(body);
462         }
463         ItemFn(ref declaration, unsafety, constness, abi, ref generics, body_id) => {
464             visitor.visit_fn(FnKind::ItemFn(item.name,
465                                             generics,
466                                             unsafety,
467                                             constness,
468                                             abi,
469                                             &item.vis,
470                                             &item.attrs),
471                              declaration,
472                              body_id,
473                              item.span,
474                              item.id)
475         }
476         ItemMod(ref module) => {
477             // visit_mod() takes care of visiting the Item's NodeId
478             visitor.visit_mod(module, item.span, item.id)
479         }
480         ItemForeignMod(ref foreign_module) => {
481             visitor.visit_id(item.id);
482             walk_list!(visitor, visit_foreign_item, &foreign_module.items);
483         }
484         ItemGlobalAsm(_) => {
485             visitor.visit_id(item.id);
486         }
487         ItemTy(ref typ, ref type_parameters) => {
488             visitor.visit_id(item.id);
489             visitor.visit_ty(typ);
490             visitor.visit_generics(type_parameters)
491         }
492         ItemEnum(ref enum_definition, ref type_parameters) => {
493             visitor.visit_generics(type_parameters);
494             // visit_enum_def() takes care of visiting the Item's NodeId
495             visitor.visit_enum_def(enum_definition, type_parameters, item.id, item.span)
496         }
497         ItemImpl(.., ref type_parameters, ref opt_trait_reference, ref typ, ref impl_item_refs) => {
498             visitor.visit_id(item.id);
499             visitor.visit_generics(type_parameters);
500             walk_list!(visitor, visit_trait_ref, opt_trait_reference);
501             visitor.visit_ty(typ);
502             walk_list!(visitor, visit_impl_item_ref, impl_item_refs);
503         }
504         ItemStruct(ref struct_definition, ref generics) |
505         ItemUnion(ref struct_definition, ref generics) => {
506             visitor.visit_generics(generics);
507             visitor.visit_id(item.id);
508             visitor.visit_variant_data(struct_definition, item.name, generics, item.id, item.span);
509         }
510         ItemTrait(.., ref generics, ref bounds, ref trait_item_refs) => {
511             visitor.visit_id(item.id);
512             visitor.visit_generics(generics);
513             walk_list!(visitor, visit_ty_param_bound, bounds);
514             walk_list!(visitor, visit_trait_item_ref, trait_item_refs);
515         }
516         ItemTraitAlias(ref generics, ref bounds) => {
517             visitor.visit_id(item.id);
518             visitor.visit_generics(generics);
519             walk_list!(visitor, visit_ty_param_bound, bounds);
520         }
521     }
522     walk_list!(visitor, visit_attribute, &item.attrs);
523 }
524
525 pub fn walk_enum_def<'v, V: Visitor<'v>>(visitor: &mut V,
526                                          enum_definition: &'v EnumDef,
527                                          generics: &'v Generics,
528                                          item_id: NodeId) {
529     visitor.visit_id(item_id);
530     walk_list!(visitor,
531                visit_variant,
532                &enum_definition.variants,
533                generics,
534                item_id);
535 }
536
537 pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V,
538                                         variant: &'v Variant,
539                                         generics: &'v Generics,
540                                         parent_item_id: NodeId) {
541     visitor.visit_name(variant.span, variant.node.name);
542     visitor.visit_variant_data(&variant.node.data,
543                                variant.node.name,
544                                generics,
545                                parent_item_id,
546                                variant.span);
547     walk_list!(visitor, visit_nested_body, variant.node.disr_expr);
548     walk_list!(visitor, visit_attribute, &variant.node.attrs);
549 }
550
551 pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) {
552     visitor.visit_id(typ.id);
553
554     match typ.node {
555         TySlice(ref ty) => {
556             visitor.visit_ty(ty)
557         }
558         TyPtr(ref mutable_type) => {
559             visitor.visit_ty(&mutable_type.ty)
560         }
561         TyRptr(ref lifetime, ref mutable_type) => {
562             visitor.visit_lifetime(lifetime);
563             visitor.visit_ty(&mutable_type.ty)
564         }
565         TyNever => {},
566         TyTup(ref tuple_element_types) => {
567             walk_list!(visitor, visit_ty, tuple_element_types);
568         }
569         TyBareFn(ref function_declaration) => {
570             visitor.visit_fn_decl(&function_declaration.decl);
571             walk_list!(visitor, visit_generic_param, &function_declaration.generic_params);
572         }
573         TyPath(ref qpath) => {
574             visitor.visit_qpath(qpath, typ.id, typ.span);
575         }
576         TyArray(ref ty, length) => {
577             visitor.visit_ty(ty);
578             visitor.visit_nested_body(length)
579         }
580         TyTraitObject(ref bounds, ref lifetime) => {
581             for bound in bounds {
582                 visitor.visit_poly_trait_ref(bound, TraitBoundModifier::None);
583             }
584             visitor.visit_lifetime(lifetime);
585         }
586         TyImplTraitExistential(ref existty, ref lifetimes) => {
587             let ExistTy { ref generics, ref bounds } = *existty;
588             walk_generics(visitor, generics);
589             walk_list!(visitor, visit_ty_param_bound, bounds);
590             walk_list!(visitor, visit_lifetime, lifetimes);
591         }
592         TyTypeof(expression) => {
593             visitor.visit_nested_body(expression)
594         }
595         TyInfer | TyErr => {}
596     }
597 }
598
599 pub fn walk_qpath<'v, V: Visitor<'v>>(visitor: &mut V, qpath: &'v QPath, id: NodeId, span: Span) {
600     match *qpath {
601         QPath::Resolved(ref maybe_qself, ref path) => {
602             if let Some(ref qself) = *maybe_qself {
603                 visitor.visit_ty(qself);
604             }
605             visitor.visit_path(path, id)
606         }
607         QPath::TypeRelative(ref qself, ref segment) => {
608             visitor.visit_ty(qself);
609             visitor.visit_path_segment(span, segment);
610         }
611     }
612 }
613
614 pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path) {
615     visitor.visit_def_mention(path.def);
616     for segment in &path.segments {
617         visitor.visit_path_segment(path.span, segment);
618     }
619 }
620
621 pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V,
622                                              path_span: Span,
623                                              segment: &'v PathSegment) {
624     visitor.visit_name(path_span, segment.name);
625     if let Some(ref parameters) = segment.parameters {
626         visitor.visit_path_parameters(path_span, parameters);
627     }
628 }
629
630 pub fn walk_path_parameters<'v, V: Visitor<'v>>(visitor: &mut V,
631                                                 _path_span: Span,
632                                                 path_parameters: &'v PathParameters) {
633     walk_list!(visitor, visit_lifetime, &path_parameters.lifetimes);
634     walk_list!(visitor, visit_ty, &path_parameters.types);
635     walk_list!(visitor, visit_assoc_type_binding, &path_parameters.bindings);
636 }
637
638 pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(visitor: &mut V,
639                                                    type_binding: &'v TypeBinding) {
640     visitor.visit_id(type_binding.id);
641     visitor.visit_name(type_binding.span, type_binding.name);
642     visitor.visit_ty(&type_binding.ty);
643 }
644
645 pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) {
646     visitor.visit_id(pattern.id);
647     match pattern.node {
648         PatKind::TupleStruct(ref qpath, ref children, _) => {
649             visitor.visit_qpath(qpath, pattern.id, pattern.span);
650             walk_list!(visitor, visit_pat, children);
651         }
652         PatKind::Path(ref qpath) => {
653             visitor.visit_qpath(qpath, pattern.id, pattern.span);
654         }
655         PatKind::Struct(ref qpath, ref fields, _) => {
656             visitor.visit_qpath(qpath, pattern.id, pattern.span);
657             for field in fields {
658                 visitor.visit_name(field.span, field.node.name);
659                 visitor.visit_pat(&field.node.pat)
660             }
661         }
662         PatKind::Tuple(ref tuple_elements, _) => {
663             walk_list!(visitor, visit_pat, tuple_elements);
664         }
665         PatKind::Box(ref subpattern) |
666         PatKind::Ref(ref subpattern, _) => {
667             visitor.visit_pat(subpattern)
668         }
669         PatKind::Binding(_, canonical_id, ref pth1, ref optional_subpattern) => {
670             visitor.visit_def_mention(Def::Local(canonical_id));
671             visitor.visit_name(pth1.span, pth1.node);
672             walk_list!(visitor, visit_pat, optional_subpattern);
673         }
674         PatKind::Lit(ref expression) => visitor.visit_expr(expression),
675         PatKind::Range(ref lower_bound, ref upper_bound, _) => {
676             visitor.visit_expr(lower_bound);
677             visitor.visit_expr(upper_bound)
678         }
679         PatKind::Wild => (),
680         PatKind::Slice(ref prepatterns, ref slice_pattern, ref postpatterns) => {
681             walk_list!(visitor, visit_pat, prepatterns);
682             walk_list!(visitor, visit_pat, slice_pattern);
683             walk_list!(visitor, visit_pat, postpatterns);
684         }
685     }
686 }
687
688 pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem) {
689     visitor.visit_id(foreign_item.id);
690     visitor.visit_vis(&foreign_item.vis);
691     visitor.visit_name(foreign_item.span, foreign_item.name);
692
693     match foreign_item.node {
694         ForeignItemFn(ref function_declaration, ref names, ref generics) => {
695             visitor.visit_generics(generics);
696             visitor.visit_fn_decl(function_declaration);
697             for name in names {
698                 visitor.visit_name(name.span, name.node);
699             }
700         }
701         ForeignItemStatic(ref typ, _) => visitor.visit_ty(typ),
702         ForeignItemType => (),
703     }
704
705     walk_list!(visitor, visit_attribute, &foreign_item.attrs);
706 }
707
708 pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v TyParamBound) {
709     match *bound {
710         TraitTyParamBound(ref typ, modifier) => {
711             visitor.visit_poly_trait_ref(typ, modifier);
712         }
713         RegionTyParamBound(ref lifetime) => {
714             visitor.visit_lifetime(lifetime);
715         }
716     }
717 }
718
719 pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) {
720     match *param {
721         GenericParam::Lifetime(ref ld) => {
722             visitor.visit_lifetime(&ld.lifetime);
723             walk_list!(visitor, visit_lifetime, &ld.bounds);
724         }
725         GenericParam::Type(ref ty_param) => {
726             visitor.visit_id(ty_param.id);
727             visitor.visit_name(ty_param.span, ty_param.name);
728             walk_list!(visitor, visit_ty_param_bound, &ty_param.bounds);
729             walk_list!(visitor, visit_ty, &ty_param.default);
730         }
731     }
732 }
733
734 pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) {
735     walk_list!(visitor, visit_generic_param, &generics.params);
736     visitor.visit_id(generics.where_clause.id);
737     walk_list!(visitor, visit_where_predicate, &generics.where_clause.predicates);
738 }
739
740 pub fn walk_where_predicate<'v, V: Visitor<'v>>(
741     visitor: &mut V,
742     predicate: &'v WherePredicate)
743 {
744     match predicate {
745         &WherePredicate::BoundPredicate(WhereBoundPredicate{ref bounded_ty,
746                                                             ref bounds,
747                                                             ref bound_generic_params,
748                                                             ..}) => {
749             visitor.visit_ty(bounded_ty);
750             walk_list!(visitor, visit_ty_param_bound, bounds);
751             walk_list!(visitor, visit_generic_param, bound_generic_params);
752         }
753         &WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime,
754                                                               ref bounds,
755                                                               ..}) => {
756             visitor.visit_lifetime(lifetime);
757             walk_list!(visitor, visit_lifetime, bounds);
758         }
759         &WherePredicate::EqPredicate(WhereEqPredicate{id,
760                                                       ref lhs_ty,
761                                                       ref rhs_ty,
762                                                       ..}) => {
763             visitor.visit_id(id);
764             visitor.visit_ty(lhs_ty);
765             visitor.visit_ty(rhs_ty);
766         }
767     }
768 }
769
770 pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FunctionRetTy) {
771     if let Return(ref output_ty) = *ret_ty {
772         visitor.visit_ty(output_ty)
773     }
774 }
775
776 pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl) {
777     for ty in &function_declaration.inputs {
778         visitor.visit_ty(ty)
779     }
780     walk_fn_ret_ty(visitor, &function_declaration.output)
781 }
782
783 pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, function_kind: FnKind<'v>) {
784     match function_kind {
785         FnKind::ItemFn(_, generics, ..) => {
786             visitor.visit_generics(generics);
787         }
788         FnKind::Method(..) |
789         FnKind::Closure(_) => {}
790     }
791 }
792
793 pub fn walk_fn<'v, V: Visitor<'v>>(visitor: &mut V,
794                                    function_kind: FnKind<'v>,
795                                    function_declaration: &'v FnDecl,
796                                    body_id: BodyId,
797                                    _span: Span,
798                                    id: NodeId) {
799     visitor.visit_id(id);
800     visitor.visit_fn_decl(function_declaration);
801     walk_fn_kind(visitor, function_kind);
802     visitor.visit_nested_body(body_id)
803 }
804
805 pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v TraitItem) {
806     visitor.visit_name(trait_item.span, trait_item.name);
807     walk_list!(visitor, visit_attribute, &trait_item.attrs);
808     visitor.visit_generics(&trait_item.generics);
809     match trait_item.node {
810         TraitItemKind::Const(ref ty, default) => {
811             visitor.visit_id(trait_item.id);
812             visitor.visit_ty(ty);
813             walk_list!(visitor, visit_nested_body, default);
814         }
815         TraitItemKind::Method(ref sig, TraitMethod::Required(ref names)) => {
816             visitor.visit_id(trait_item.id);
817             visitor.visit_fn_decl(&sig.decl);
818             for name in names {
819                 visitor.visit_name(name.span, name.node);
820             }
821         }
822         TraitItemKind::Method(ref sig, TraitMethod::Provided(body_id)) => {
823             visitor.visit_fn(FnKind::Method(trait_item.name,
824                                             sig,
825                                             None,
826                                             &trait_item.attrs),
827                              &sig.decl,
828                              body_id,
829                              trait_item.span,
830                              trait_item.id);
831         }
832         TraitItemKind::Type(ref bounds, ref default) => {
833             visitor.visit_id(trait_item.id);
834             walk_list!(visitor, visit_ty_param_bound, bounds);
835             walk_list!(visitor, visit_ty, default);
836         }
837     }
838 }
839
840 pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: &'v TraitItemRef) {
841     // NB: Deliberately force a compilation error if/when new fields are added.
842     let TraitItemRef { id, name, ref kind, span, ref defaultness } = *trait_item_ref;
843     visitor.visit_nested_trait_item(id);
844     visitor.visit_name(span, name);
845     visitor.visit_associated_item_kind(kind);
846     visitor.visit_defaultness(defaultness);
847 }
848
849 pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem) {
850     // NB: Deliberately force a compilation error if/when new fields are added.
851     let ImplItem {
852         id: _,
853         hir_id: _,
854         name,
855         ref vis,
856         ref defaultness,
857         ref attrs,
858         ref generics,
859         ref node,
860         span
861     } = *impl_item;
862
863     visitor.visit_name(span, name);
864     visitor.visit_vis(vis);
865     visitor.visit_defaultness(defaultness);
866     walk_list!(visitor, visit_attribute, attrs);
867     visitor.visit_generics(generics);
868     match *node {
869         ImplItemKind::Const(ref ty, body) => {
870             visitor.visit_id(impl_item.id);
871             visitor.visit_ty(ty);
872             visitor.visit_nested_body(body);
873         }
874         ImplItemKind::Method(ref sig, body_id) => {
875             visitor.visit_fn(FnKind::Method(impl_item.name,
876                                             sig,
877                                             Some(&impl_item.vis),
878                                             &impl_item.attrs),
879                              &sig.decl,
880                              body_id,
881                              impl_item.span,
882                              impl_item.id);
883         }
884         ImplItemKind::Type(ref ty) => {
885             visitor.visit_id(impl_item.id);
886             visitor.visit_ty(ty);
887         }
888     }
889 }
890
891 pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) {
892     // NB: Deliberately force a compilation error if/when new fields are added.
893     let ImplItemRef { id, name, ref kind, span, ref vis, ref defaultness } = *impl_item_ref;
894     visitor.visit_nested_impl_item(id);
895     visitor.visit_name(span, name);
896     visitor.visit_associated_item_kind(kind);
897     visitor.visit_vis(vis);
898     visitor.visit_defaultness(defaultness);
899 }
900
901
902 pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V, struct_definition: &'v VariantData) {
903     visitor.visit_id(struct_definition.id());
904     walk_list!(visitor, visit_struct_field, struct_definition.fields());
905 }
906
907 pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, struct_field: &'v StructField) {
908     visitor.visit_id(struct_field.id);
909     visitor.visit_vis(&struct_field.vis);
910     visitor.visit_name(struct_field.span, struct_field.name);
911     visitor.visit_ty(&struct_field.ty);
912     walk_list!(visitor, visit_attribute, &struct_field.attrs);
913 }
914
915 pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block) {
916     visitor.visit_id(block.id);
917     walk_list!(visitor, visit_stmt, &block.stmts);
918     walk_list!(visitor, visit_expr, &block.expr);
919 }
920
921 pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt) {
922     match statement.node {
923         StmtDecl(ref declaration, id) => {
924             visitor.visit_id(id);
925             visitor.visit_decl(declaration)
926         }
927         StmtExpr(ref expression, id) |
928         StmtSemi(ref expression, id) => {
929             visitor.visit_id(id);
930             visitor.visit_expr(expression)
931         }
932     }
933 }
934
935 pub fn walk_decl<'v, V: Visitor<'v>>(visitor: &mut V, declaration: &'v Decl) {
936     match declaration.node {
937         DeclLocal(ref local) => visitor.visit_local(local),
938         DeclItem(item) => visitor.visit_nested_item(item),
939     }
940 }
941
942 pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
943     visitor.visit_id(expression.id);
944     walk_list!(visitor, visit_attribute, expression.attrs.iter());
945     match expression.node {
946         ExprBox(ref subexpression) => {
947             visitor.visit_expr(subexpression)
948         }
949         ExprArray(ref subexpressions) => {
950             walk_list!(visitor, visit_expr, subexpressions);
951         }
952         ExprRepeat(ref element, count) => {
953             visitor.visit_expr(element);
954             visitor.visit_nested_body(count)
955         }
956         ExprStruct(ref qpath, ref fields, ref optional_base) => {
957             visitor.visit_qpath(qpath, expression.id, expression.span);
958             for field in fields {
959                 visitor.visit_name(field.name.span, field.name.node);
960                 visitor.visit_expr(&field.expr)
961             }
962             walk_list!(visitor, visit_expr, optional_base);
963         }
964         ExprTup(ref subexpressions) => {
965             walk_list!(visitor, visit_expr, subexpressions);
966         }
967         ExprCall(ref callee_expression, ref arguments) => {
968             visitor.visit_expr(callee_expression);
969             walk_list!(visitor, visit_expr, arguments);
970         }
971         ExprMethodCall(ref segment, _, ref arguments) => {
972             visitor.visit_path_segment(expression.span, segment);
973             walk_list!(visitor, visit_expr, arguments);
974         }
975         ExprBinary(_, ref left_expression, ref right_expression) => {
976             visitor.visit_expr(left_expression);
977             visitor.visit_expr(right_expression)
978         }
979         ExprAddrOf(_, ref subexpression) | ExprUnary(_, ref subexpression) => {
980             visitor.visit_expr(subexpression)
981         }
982         ExprLit(_) => {}
983         ExprCast(ref subexpression, ref typ) | ExprType(ref subexpression, ref typ) => {
984             visitor.visit_expr(subexpression);
985             visitor.visit_ty(typ)
986         }
987         ExprIf(ref head_expression, ref if_block, ref optional_else) => {
988             visitor.visit_expr(head_expression);
989             visitor.visit_expr(if_block);
990             walk_list!(visitor, visit_expr, optional_else);
991         }
992         ExprWhile(ref subexpression, ref block, ref opt_label) => {
993             walk_list!(visitor, visit_label, opt_label);
994             visitor.visit_expr(subexpression);
995             visitor.visit_block(block);
996         }
997         ExprLoop(ref block, ref opt_label, _) => {
998             walk_list!(visitor, visit_label, opt_label);
999             visitor.visit_block(block);
1000         }
1001         ExprMatch(ref subexpression, ref arms, _) => {
1002             visitor.visit_expr(subexpression);
1003             walk_list!(visitor, visit_arm, arms);
1004         }
1005         ExprClosure(_, ref function_declaration, body, _fn_decl_span, _gen) => {
1006             visitor.visit_fn(FnKind::Closure(&expression.attrs),
1007                              function_declaration,
1008                              body,
1009                              expression.span,
1010                              expression.id)
1011         }
1012         ExprBlock(ref block) => visitor.visit_block(block),
1013         ExprAssign(ref left_hand_expression, ref right_hand_expression) => {
1014             visitor.visit_expr(right_hand_expression);
1015             visitor.visit_expr(left_hand_expression)
1016         }
1017         ExprAssignOp(_, ref left_expression, ref right_expression) => {
1018             visitor.visit_expr(right_expression);
1019             visitor.visit_expr(left_expression)
1020         }
1021         ExprField(ref subexpression, ref name) => {
1022             visitor.visit_expr(subexpression);
1023             visitor.visit_name(name.span, name.node);
1024         }
1025         ExprTupField(ref subexpression, _) => {
1026             visitor.visit_expr(subexpression);
1027         }
1028         ExprIndex(ref main_expression, ref index_expression) => {
1029             visitor.visit_expr(main_expression);
1030             visitor.visit_expr(index_expression)
1031         }
1032         ExprPath(ref qpath) => {
1033             visitor.visit_qpath(qpath, expression.id, expression.span);
1034         }
1035         ExprBreak(ref destination, ref opt_expr) => {
1036             if let Some(ref label) = destination.label {
1037                 visitor.visit_label(label);
1038                 match destination.target_id {
1039                     ScopeTarget::Block(node_id) |
1040                     ScopeTarget::Loop(LoopIdResult::Ok(node_id)) =>
1041                         visitor.visit_def_mention(Def::Label(node_id)),
1042                     ScopeTarget::Loop(LoopIdResult::Err(_)) => {},
1043                 };
1044             }
1045             walk_list!(visitor, visit_expr, opt_expr);
1046         }
1047         ExprAgain(ref destination) => {
1048             if let Some(ref label) = destination.label {
1049                 visitor.visit_label(label);
1050                 match destination.target_id {
1051                     ScopeTarget::Block(_) => bug!("can't `continue` to a non-loop block"),
1052                     ScopeTarget::Loop(LoopIdResult::Ok(node_id)) =>
1053                         visitor.visit_def_mention(Def::Label(node_id)),
1054                     ScopeTarget::Loop(LoopIdResult::Err(_)) => {},
1055                 };
1056             }
1057         }
1058         ExprRet(ref optional_expression) => {
1059             walk_list!(visitor, visit_expr, optional_expression);
1060         }
1061         ExprInlineAsm(_, ref outputs, ref inputs) => {
1062             for output in outputs {
1063                 visitor.visit_expr(output)
1064             }
1065             for input in inputs {
1066                 visitor.visit_expr(input)
1067             }
1068         }
1069         ExprYield(ref subexpression) => {
1070             visitor.visit_expr(subexpression);
1071         }
1072     }
1073 }
1074
1075 pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm) {
1076     walk_list!(visitor, visit_pat, &arm.pats);
1077     walk_list!(visitor, visit_expr, &arm.guard);
1078     visitor.visit_expr(&arm.body);
1079     walk_list!(visitor, visit_attribute, &arm.attrs);
1080 }
1081
1082 pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility) {
1083     if let Visibility::Restricted { ref path, id } = *vis {
1084         visitor.visit_id(id);
1085         visitor.visit_path(path, id)
1086     }
1087 }
1088
1089 pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssociatedItemKind) {
1090     // No visitable content here: this fn exists so you can call it if
1091     // the right thing to do, should content be added in the future,
1092     // would be to walk it.
1093 }
1094
1095 pub fn walk_defaultness<'v, V: Visitor<'v>>(_: &mut V, _: &'v Defaultness) {
1096     // No visitable content here: this fn exists so you can call it if
1097     // the right thing to do, should content be added in the future,
1098     // would be to walk it.
1099 }
1100
1101 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq)]
1102 pub struct IdRange {
1103     pub min: NodeId,
1104     pub max: NodeId,
1105 }
1106
1107 impl IdRange {
1108     pub fn max() -> IdRange {
1109         IdRange {
1110             min: NodeId::from_u32(u32::MAX),
1111             max: NodeId::from_u32(u32::MIN),
1112         }
1113     }
1114
1115     pub fn empty(&self) -> bool {
1116         self.min >= self.max
1117     }
1118
1119     pub fn contains(&self, id: NodeId) -> bool {
1120         id >= self.min && id < self.max
1121     }
1122
1123     pub fn add(&mut self, id: NodeId) {
1124         self.min = cmp::min(self.min, id);
1125         self.max = cmp::max(self.max, NodeId::from_u32(id.as_u32() + 1));
1126     }
1127
1128 }
1129
1130
1131 pub struct IdRangeComputingVisitor<'a, 'hir: 'a> {
1132     result: IdRange,
1133     map: &'a map::Map<'hir>,
1134 }
1135
1136 impl<'a, 'hir> IdRangeComputingVisitor<'a, 'hir> {
1137     pub fn new(map: &'a map::Map<'hir>) -> IdRangeComputingVisitor<'a, 'hir> {
1138         IdRangeComputingVisitor { result: IdRange::max(), map: map }
1139     }
1140
1141     pub fn result(&self) -> IdRange {
1142         self.result
1143     }
1144 }
1145
1146 impl<'a, 'hir> Visitor<'hir> for IdRangeComputingVisitor<'a, 'hir> {
1147     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
1148         NestedVisitorMap::OnlyBodies(&self.map)
1149     }
1150
1151     fn visit_id(&mut self, id: NodeId) {
1152         self.result.add(id);
1153     }
1154 }