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