]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_static_recursion.rs
Make name resolution errors non-fatal
[rust.git] / src / librustc / middle / check_static_recursion.rs
1 // Copyright 2014 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 // This compiler pass detects constants that refer to themselves
12 // recursively.
13
14 use front::map as ast_map;
15 use session::Session;
16 use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefVariant, DefMap};
17 use util::nodemap::NodeMap;
18
19 use syntax::{ast};
20 use syntax::codemap::Span;
21 use syntax::feature_gate::{GateIssue, emit_feature_err};
22 use rustc_front::intravisit::{self, Visitor};
23 use rustc_front::hir;
24
25 use std::cell::RefCell;
26
27 struct CheckCrateVisitor<'a, 'ast: 'a> {
28     sess: &'a Session,
29     def_map: &'a DefMap,
30     ast_map: &'a ast_map::Map<'ast>,
31     // `discriminant_map` is a cache that associates the `NodeId`s of local
32     // variant definitions with the discriminant expression that applies to
33     // each one. If the variant uses the default values (starting from `0`),
34     // then `None` is stored.
35     discriminant_map: RefCell<NodeMap<Option<&'ast hir::Expr>>>,
36 }
37
38 impl<'a, 'ast: 'a> Visitor<'ast> for CheckCrateVisitor<'a, 'ast> {
39     fn visit_item(&mut self, it: &'ast hir::Item) {
40         match it.node {
41             hir::ItemStatic(..) |
42             hir::ItemConst(..) => {
43                 let mut recursion_visitor =
44                     CheckItemRecursionVisitor::new(self, &it.span);
45                 recursion_visitor.visit_item(it);
46             },
47             hir::ItemEnum(ref enum_def, ref generics) => {
48                 // We could process the whole enum, but handling the variants
49                 // with discriminant expressions one by one gives more specific,
50                 // less redundant output.
51                 for variant in &enum_def.variants {
52                     if let Some(_) = variant.node.disr_expr {
53                         let mut recursion_visitor =
54                             CheckItemRecursionVisitor::new(self, &variant.span);
55                         recursion_visitor.populate_enum_discriminants(enum_def);
56                         recursion_visitor.visit_variant(variant, generics, it.id);
57                     }
58                 }
59             }
60             _ => {}
61         }
62         intravisit::walk_item(self, it)
63     }
64
65     fn visit_trait_item(&mut self, ti: &'ast hir::TraitItem) {
66         match ti.node {
67             hir::ConstTraitItem(_, ref default) => {
68                 if let Some(_) = *default {
69                     let mut recursion_visitor =
70                         CheckItemRecursionVisitor::new(self, &ti.span);
71                     recursion_visitor.visit_trait_item(ti);
72                 }
73             }
74             _ => {}
75         }
76         intravisit::walk_trait_item(self, ti)
77     }
78
79     fn visit_impl_item(&mut self, ii: &'ast hir::ImplItem) {
80         match ii.node {
81             hir::ImplItemKind::Const(..) => {
82                 let mut recursion_visitor =
83                     CheckItemRecursionVisitor::new(self, &ii.span);
84                 recursion_visitor.visit_impl_item(ii);
85             }
86             _ => {}
87         }
88         intravisit::walk_impl_item(self, ii)
89     }
90 }
91
92 pub fn check_crate<'ast>(sess: &Session,
93                          krate: &'ast hir::Crate,
94                          def_map: &DefMap,
95                          ast_map: &ast_map::Map<'ast>) {
96     let mut visitor = CheckCrateVisitor {
97         sess: sess,
98         def_map: def_map,
99         ast_map: ast_map,
100         discriminant_map: RefCell::new(NodeMap()),
101     };
102     sess.abort_if_new_errors(|| {
103         krate.visit_all_items(&mut visitor);
104     });
105 }
106
107 struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
108     root_span: &'a Span,
109     sess: &'a Session,
110     ast_map: &'a ast_map::Map<'ast>,
111     def_map: &'a DefMap,
112     discriminant_map: &'a RefCell<NodeMap<Option<&'ast hir::Expr>>>,
113     idstack: Vec<ast::NodeId>,
114 }
115
116 impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
117     fn new(v: &'a CheckCrateVisitor<'a, 'ast>, span: &'a Span)
118            -> CheckItemRecursionVisitor<'a, 'ast> {
119         CheckItemRecursionVisitor {
120             root_span: span,
121             sess: v.sess,
122             ast_map: v.ast_map,
123             def_map: v.def_map,
124             discriminant_map: &v.discriminant_map,
125             idstack: Vec::new(),
126         }
127     }
128     fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
129           where F: Fn(&mut Self) {
130         if self.idstack.iter().any(|&x| x == id) {
131             let any_static = self.idstack.iter().any(|&x| {
132                 if let ast_map::NodeItem(item) = self.ast_map.get(x) {
133                     if let hir::ItemStatic(..) = item.node {
134                         true
135                     } else {
136                         false
137                     }
138                 } else {
139                     false
140                 }
141             });
142             if any_static {
143                 if !self.sess.features.borrow().static_recursion {
144                     emit_feature_err(&self.sess.parse_sess.span_diagnostic,
145                                      "static_recursion",
146                                      *self.root_span, GateIssue::Language, "recursive static");
147                 }
148             } else {
149                 span_err!(self.sess, *self.root_span, E0265, "recursive constant");
150             }
151             return;
152         }
153         self.idstack.push(id);
154         f(self);
155         self.idstack.pop();
156     }
157     // If a variant has an expression specifying its discriminant, then it needs
158     // to be checked just like a static or constant. However, if there are more
159     // variants with no explicitly specified discriminant, those variants will
160     // increment the same expression to get their values.
161     //
162     // So for every variant, we need to track whether there is an expression
163     // somewhere in the enum definition that controls its discriminant. We do
164     // this by starting from the end and searching backward.
165     fn populate_enum_discriminants(&self, enum_definition: &'ast hir::EnumDef) {
166         // Get the map, and return if we already processed this enum or if it
167         // has no variants.
168         let mut discriminant_map = self.discriminant_map.borrow_mut();
169         match enum_definition.variants.first() {
170             None => { return; }
171             Some(variant) if discriminant_map.contains_key(&variant.node.data.id()) => {
172                 return;
173             }
174             _ => {}
175         }
176
177         // Go through all the variants.
178         let mut variant_stack: Vec<ast::NodeId> = Vec::new();
179         for variant in enum_definition.variants.iter().rev() {
180             variant_stack.push(variant.node.data.id());
181             // When we find an expression, every variant currently on the stack
182             // is affected by that expression.
183             if let Some(ref expr) = variant.node.disr_expr {
184                 for id in &variant_stack {
185                     discriminant_map.insert(*id, Some(expr));
186                 }
187                 variant_stack.clear()
188             }
189         }
190         // If we are at the top, that always starts at 0, so any variant on the
191         // stack has a default value and does not need to be checked.
192         for id in &variant_stack {
193             discriminant_map.insert(*id, None);
194         }
195     }
196 }
197
198 impl<'a, 'ast: 'a> Visitor<'ast> for CheckItemRecursionVisitor<'a, 'ast> {
199     fn visit_item(&mut self, it: &'ast hir::Item) {
200         self.with_item_id_pushed(it.id, |v| intravisit::walk_item(v, it));
201     }
202
203     fn visit_enum_def(&mut self, enum_definition: &'ast hir::EnumDef,
204                       generics: &'ast hir::Generics, item_id: ast::NodeId, _: Span) {
205         self.populate_enum_discriminants(enum_definition);
206         intravisit::walk_enum_def(self, enum_definition, generics, item_id);
207     }
208
209     fn visit_variant(&mut self, variant: &'ast hir::Variant,
210                      _: &'ast hir::Generics, _: ast::NodeId) {
211         let variant_id = variant.node.data.id();
212         let maybe_expr;
213         if let Some(get_expr) = self.discriminant_map.borrow().get(&variant_id) {
214             // This is necessary because we need to let the `discriminant_map`
215             // borrow fall out of scope, so that we can reborrow farther down.
216             maybe_expr = (*get_expr).clone();
217         } else {
218             self.sess.span_bug(variant.span,
219                                "`check_static_recursion` attempted to visit \
220                                 variant with unknown discriminant")
221         }
222         // If `maybe_expr` is `None`, that's because no discriminant is
223         // specified that affects this variant. Thus, no risk of recursion.
224         if let Some(expr) = maybe_expr {
225             self.with_item_id_pushed(expr.id, |v| intravisit::walk_expr(v, expr));
226         }
227     }
228
229     fn visit_trait_item(&mut self, ti: &'ast hir::TraitItem) {
230         self.with_item_id_pushed(ti.id, |v| intravisit::walk_trait_item(v, ti));
231     }
232
233     fn visit_impl_item(&mut self, ii: &'ast hir::ImplItem) {
234         self.with_item_id_pushed(ii.id, |v| intravisit::walk_impl_item(v, ii));
235     }
236
237     fn visit_expr(&mut self, e: &'ast hir::Expr) {
238         match e.node {
239             hir::ExprPath(..) => {
240                 match self.def_map.get(&e.id).map(|d| d.base_def) {
241                     Some(DefStatic(def_id, _)) |
242                     Some(DefAssociatedConst(def_id)) |
243                     Some(DefConst(def_id)) => {
244                         if let Some(node_id) = self.ast_map.as_local_node_id(def_id) {
245                             match self.ast_map.get(node_id) {
246                                 ast_map::NodeItem(item) =>
247                                     self.visit_item(item),
248                                 ast_map::NodeTraitItem(item) =>
249                                     self.visit_trait_item(item),
250                                 ast_map::NodeImplItem(item) =>
251                                     self.visit_impl_item(item),
252                                 ast_map::NodeForeignItem(_) => {},
253                                 _ => {
254                                     self.sess.span_bug(
255                                         e.span,
256                                         &format!("expected item, found {}",
257                                                  self.ast_map.node_to_string(node_id)));
258                                 }
259                             }
260                         }
261                     }
262                     // For variants, we only want to check expressions that
263                     // affect the specific variant used, but we need to check
264                     // the whole enum definition to see what expression that
265                     // might be (if any).
266                     Some(DefVariant(enum_id, variant_id, false)) => {
267                         if let Some(enum_node_id) = self.ast_map.as_local_node_id(enum_id) {
268                             if let hir::ItemEnum(ref enum_def, ref generics) =
269                                 self.ast_map.expect_item(enum_node_id).node
270                             {
271                                 self.populate_enum_discriminants(enum_def);
272                                 let enum_id = self.ast_map.as_local_node_id(enum_id).unwrap();
273                                 let variant_id = self.ast_map.as_local_node_id(variant_id).unwrap();
274                                 let variant = self.ast_map.expect_variant(variant_id);
275                                 self.visit_variant(variant, generics, enum_id);
276                             } else {
277                                 self.sess.span_bug(e.span,
278                                                    "`check_static_recursion` found \
279                                                     non-enum in DefVariant");
280                             }
281                         }
282                     }
283                     _ => ()
284                 }
285             },
286             _ => ()
287         }
288         intravisit::walk_expr(self, e);
289     }
290 }