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