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