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