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.
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.
11 // This compiler pass detects constants that refer to themselves
14 use rustc::dep_graph::DepNode;
15 use rustc::hir::map as ast_map;
16 use rustc::session::{CompileResult, Session};
17 use rustc::hir::def::{Def, DefMap};
18 use rustc::util::nodemap::NodeMap;
21 use syntax::feature_gate::{GateIssue, emit_feature_err};
23 use rustc::hir::intravisit::{self, Visitor};
26 use std::cell::RefCell;
28 struct CheckCrateVisitor<'a, 'ast: 'a> {
31 ast_map: &'a ast_map::Map<'ast>,
32 // `discriminant_map` is a cache that associates the `NodeId`s of local
33 // variant definitions with the discriminant expression that applies to
34 // each one. If the variant uses the default values (starting from `0`),
35 // then `None` is stored.
36 discriminant_map: RefCell<NodeMap<Option<&'ast hir::Expr>>>,
39 impl<'a, 'ast: 'a> Visitor<'ast> for CheckCrateVisitor<'a, 'ast> {
40 fn visit_item(&mut self, it: &'ast hir::Item) {
43 hir::ItemConst(..) => {
44 let mut recursion_visitor = CheckItemRecursionVisitor::new(self, &it.span);
45 recursion_visitor.visit_item(it);
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 = CheckItemRecursionVisitor::new(self,
55 recursion_visitor.populate_enum_discriminants(enum_def);
56 recursion_visitor.visit_variant(variant, generics, it.id);
62 intravisit::walk_item(self, it)
65 fn visit_trait_item(&mut self, ti: &'ast hir::TraitItem) {
67 hir::ConstTraitItem(_, ref default) => {
68 if let Some(_) = *default {
69 let mut recursion_visitor = CheckItemRecursionVisitor::new(self, &ti.span);
70 recursion_visitor.visit_trait_item(ti);
75 intravisit::walk_trait_item(self, ti)
78 fn visit_impl_item(&mut self, ii: &'ast hir::ImplItem) {
80 hir::ImplItemKind::Const(..) => {
81 let mut recursion_visitor = CheckItemRecursionVisitor::new(self, &ii.span);
82 recursion_visitor.visit_impl_item(ii);
86 intravisit::walk_impl_item(self, ii)
90 pub fn check_crate<'ast>(sess: &Session,
92 ast_map: &ast_map::Map<'ast>)
94 let _task = ast_map.dep_graph.in_task(DepNode::CheckStaticRecursion);
96 let mut visitor = CheckCrateVisitor {
100 discriminant_map: RefCell::new(NodeMap()),
102 sess.track_errors(|| {
103 ast_map.krate().visit_all_items(&mut visitor);
107 struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
110 ast_map: &'a ast_map::Map<'ast>,
112 discriminant_map: &'a RefCell<NodeMap<Option<&'ast hir::Expr>>>,
113 idstack: Vec<ast::NodeId>,
116 impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
117 fn new(v: &'a CheckCrateVisitor<'a, 'ast>,
119 -> CheckItemRecursionVisitor<'a, 'ast> {
120 CheckItemRecursionVisitor {
125 discriminant_map: &v.discriminant_map,
129 fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F, span: Span)
130 where F: Fn(&mut Self)
132 if self.idstack.iter().any(|&x| x == id) {
133 let any_static = self.idstack.iter().any(|&x| {
134 if let ast_map::NodeItem(item) = self.ast_map.get(x) {
135 if let hir::ItemStatic(..) = item.node {
145 if !self.sess.features.borrow().static_recursion {
146 emit_feature_err(&self.sess.parse_sess.span_diagnostic,
153 struct_span_err!(self.sess, span, E0265, "recursive constant")
154 .span_label(span, &format!("recursion not allowed in constant"))
159 self.idstack.push(id);
163 // If a variant has an expression specifying its discriminant, then it needs
164 // to be checked just like a static or constant. However, if there are more
165 // variants with no explicitly specified discriminant, those variants will
166 // increment the same expression to get their values.
168 // So for every variant, we need to track whether there is an expression
169 // somewhere in the enum definition that controls its discriminant. We do
170 // this by starting from the end and searching backward.
171 fn populate_enum_discriminants(&self, enum_definition: &'ast hir::EnumDef) {
172 // Get the map, and return if we already processed this enum or if it
174 let mut discriminant_map = self.discriminant_map.borrow_mut();
175 match enum_definition.variants.first() {
179 Some(variant) if discriminant_map.contains_key(&variant.node.data.id()) => {
185 // Go through all the variants.
186 let mut variant_stack: Vec<ast::NodeId> = Vec::new();
187 for variant in enum_definition.variants.iter().rev() {
188 variant_stack.push(variant.node.data.id());
189 // When we find an expression, every variant currently on the stack
190 // is affected by that expression.
191 if let Some(ref expr) = variant.node.disr_expr {
192 for id in &variant_stack {
193 discriminant_map.insert(*id, Some(expr));
195 variant_stack.clear()
198 // If we are at the top, that always starts at 0, so any variant on the
199 // stack has a default value and does not need to be checked.
200 for id in &variant_stack {
201 discriminant_map.insert(*id, None);
206 impl<'a, 'ast: 'a> Visitor<'ast> for CheckItemRecursionVisitor<'a, 'ast> {
207 fn visit_item(&mut self, it: &'ast hir::Item) {
208 self.with_item_id_pushed(it.id, |v| intravisit::walk_item(v, it), it.span);
211 fn visit_enum_def(&mut self,
212 enum_definition: &'ast hir::EnumDef,
213 generics: &'ast hir::Generics,
214 item_id: ast::NodeId,
216 self.populate_enum_discriminants(enum_definition);
217 intravisit::walk_enum_def(self, enum_definition, generics, item_id);
220 fn visit_variant(&mut self,
221 variant: &'ast hir::Variant,
222 _: &'ast hir::Generics,
224 let variant_id = variant.node.data.id();
226 if let Some(get_expr) = self.discriminant_map.borrow().get(&variant_id) {
227 // This is necessary because we need to let the `discriminant_map`
228 // borrow fall out of scope, so that we can reborrow farther down.
229 maybe_expr = (*get_expr).clone();
231 span_bug!(variant.span,
232 "`check_static_recursion` attempted to visit \
233 variant with unknown discriminant")
235 // If `maybe_expr` is `None`, that's because no discriminant is
236 // specified that affects this variant. Thus, no risk of recursion.
237 if let Some(expr) = maybe_expr {
238 self.with_item_id_pushed(expr.id, |v| intravisit::walk_expr(v, expr), expr.span);
242 fn visit_trait_item(&mut self, ti: &'ast hir::TraitItem) {
243 self.with_item_id_pushed(ti.id, |v| intravisit::walk_trait_item(v, ti), ti.span);
246 fn visit_impl_item(&mut self, ii: &'ast hir::ImplItem) {
247 self.with_item_id_pushed(ii.id, |v| intravisit::walk_impl_item(v, ii), ii.span);
250 fn visit_expr(&mut self, e: &'ast hir::Expr) {
252 hir::ExprPath(..) => {
253 match self.def_map.get(&e.id).map(|d| d.base_def) {
254 Some(Def::Static(def_id, _)) |
255 Some(Def::AssociatedConst(def_id)) |
256 Some(Def::Const(def_id)) => {
257 if let Some(node_id) = self.ast_map.as_local_node_id(def_id) {
258 match self.ast_map.get(node_id) {
259 ast_map::NodeItem(item) => self.visit_item(item),
260 ast_map::NodeTraitItem(item) => self.visit_trait_item(item),
261 ast_map::NodeImplItem(item) => self.visit_impl_item(item),
262 ast_map::NodeForeignItem(_) => {}
265 "expected item, found {}",
266 self.ast_map.node_to_string(node_id));
271 // For variants, we only want to check expressions that
272 // affect the specific variant used, but we need to check
273 // the whole enum definition to see what expression that
274 // might be (if any).
275 Some(Def::Variant(enum_id, variant_id)) => {
276 if let Some(enum_node_id) = self.ast_map.as_local_node_id(enum_id) {
277 if let hir::ItemEnum(ref enum_def, ref generics) = self.ast_map
278 .expect_item(enum_node_id)
280 self.populate_enum_discriminants(enum_def);
281 let enum_id = self.ast_map.as_local_node_id(enum_id).unwrap();
282 let variant_id = self.ast_map.as_local_node_id(variant_id).unwrap();
283 let variant = self.ast_map.expect_variant(variant_id);
284 self.visit_variant(variant, generics, enum_id);
287 "`check_static_recursion` found \
288 non-enum in Def::Variant");
297 intravisit::walk_expr(self, e);