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::front::map as ast_map;
15 use rustc::session::{Session, CompileResult};
16 use rustc::middle::def::{Def, DefMap};
17 use rustc::util::nodemap::NodeMap;
20 use syntax::codemap::Span;
21 use syntax::feature_gate::{GateIssue, emit_feature_err};
22 use rustc_front::intravisit::{self, Visitor};
25 use std::cell::RefCell;
27 struct CheckCrateVisitor<'a, 'ast: 'a> {
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>>>,
38 impl<'a, 'ast: 'a> Visitor<'ast> for CheckCrateVisitor<'a, 'ast> {
39 fn visit_item(&mut self, it: &'ast hir::Item) {
42 hir::ItemConst(..) => {
43 let mut recursion_visitor =
44 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 =
54 CheckItemRecursionVisitor::new(self, &variant.span);
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 =
70 CheckItemRecursionVisitor::new(self, &ti.span);
71 recursion_visitor.visit_trait_item(ti);
76 intravisit::walk_trait_item(self, ti)
79 fn visit_impl_item(&mut self, ii: &'ast hir::ImplItem) {
81 hir::ImplItemKind::Const(..) => {
82 let mut recursion_visitor =
83 CheckItemRecursionVisitor::new(self, &ii.span);
84 recursion_visitor.visit_impl_item(ii);
88 intravisit::walk_impl_item(self, ii)
92 pub fn check_crate<'ast>(sess: &Session,
93 krate: &'ast hir::Crate,
95 ast_map: &ast_map::Map<'ast>) -> CompileResult {
96 let mut visitor = CheckCrateVisitor {
100 discriminant_map: RefCell::new(NodeMap()),
102 sess.track_errors(|| {
103 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>, span: &'a Span)
118 -> CheckItemRecursionVisitor<'a, 'ast> {
119 CheckItemRecursionVisitor {
124 discriminant_map: &v.discriminant_map,
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 {
143 if !self.sess.features.borrow().static_recursion {
144 emit_feature_err(&self.sess.parse_sess.span_diagnostic,
146 *self.root_span, GateIssue::Language, "recursive static");
149 span_err!(self.sess, *self.root_span, E0265, "recursive constant");
153 self.idstack.push(id);
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.
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
168 let mut discriminant_map = self.discriminant_map.borrow_mut();
169 match enum_definition.variants.first() {
171 Some(variant) if discriminant_map.contains_key(&variant.node.data.id()) => {
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));
187 variant_stack.clear()
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);
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));
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);
209 fn visit_variant(&mut self, variant: &'ast hir::Variant,
210 _: &'ast hir::Generics, _: ast::NodeId) {
211 let variant_id = variant.node.data.id();
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();
218 self.sess.span_bug(variant.span,
219 "`check_static_recursion` attempted to visit \
220 variant with unknown discriminant")
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));
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));
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));
237 fn visit_expr(&mut self, e: &'ast hir::Expr) {
239 hir::ExprPath(..) => {
240 match self.def_map.get(&e.id).map(|d| d.base_def) {
241 Some(Def::Static(def_id, _)) |
242 Some(Def::AssociatedConst(def_id)) |
243 Some(Def::Const(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(_) => {},
256 &format!("expected item, found {}",
257 self.ast_map.node_to_string(node_id)));
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(Def::Variant(enum_id, variant_id)) => {
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
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);
277 self.sess.span_bug(e.span,
278 "`check_static_recursion` found \
279 non-enum in Def::Variant");
288 intravisit::walk_expr(self, e);