]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/static_recursion.rs
Auto merge of #41684 - jethrogb:feature/ntstatus, r=alexcrichton
[rust.git] / src / librustc_passes / 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 rustc::hir::map as hir_map;
15 use rustc::session::{CompileResult, Session};
16 use rustc::hir::def::{Def, CtorKind};
17 use rustc::util::nodemap::{NodeMap, NodeSet};
18
19 use syntax::ast;
20 use syntax_pos::Span;
21 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
22 use rustc::hir;
23
24 struct CheckCrateVisitor<'a, 'hir: 'a> {
25     sess: &'a Session,
26     hir_map: &'a hir_map::Map<'hir>,
27     // `discriminant_map` is a cache that associates the `NodeId`s of local
28     // variant definitions with the discriminant expression that applies to
29     // each one. If the variant uses the default values (starting from `0`),
30     // then `None` is stored.
31     discriminant_map: NodeMap<Option<hir::BodyId>>,
32     detected_recursive_ids: NodeSet,
33 }
34
35 impl<'a, 'hir: 'a> Visitor<'hir> for CheckCrateVisitor<'a, 'hir> {
36     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
37         NestedVisitorMap::None
38     }
39
40     fn visit_item(&mut self, it: &'hir hir::Item) {
41         match it.node {
42             hir::ItemStatic(..) |
43             hir::ItemConst(..) => {
44                 let mut recursion_visitor = CheckItemRecursionVisitor::new(self);
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 = CheckItemRecursionVisitor::new(self);
54                         recursion_visitor.populate_enum_discriminants(enum_def);
55                         recursion_visitor.visit_variant(variant, generics, it.id);
56                     }
57                 }
58             }
59             _ => {}
60         }
61         intravisit::walk_item(self, it)
62     }
63
64     fn visit_trait_item(&mut self, ti: &'hir hir::TraitItem) {
65         match ti.node {
66             hir::TraitItemKind::Const(_, ref default) => {
67                 if let Some(_) = *default {
68                     let mut recursion_visitor = CheckItemRecursionVisitor::new(self);
69                     recursion_visitor.visit_trait_item(ti);
70                 }
71             }
72             _ => {}
73         }
74         intravisit::walk_trait_item(self, ti)
75     }
76
77     fn visit_impl_item(&mut self, ii: &'hir hir::ImplItem) {
78         match ii.node {
79             hir::ImplItemKind::Const(..) => {
80                 let mut recursion_visitor = CheckItemRecursionVisitor::new(self);
81                 recursion_visitor.visit_impl_item(ii);
82             }
83             _ => {}
84         }
85         intravisit::walk_impl_item(self, ii)
86     }
87 }
88
89 pub fn check_crate<'hir>(sess: &Session, hir_map: &hir_map::Map<'hir>) -> CompileResult {
90     let mut visitor = CheckCrateVisitor {
91         sess: sess,
92         hir_map: hir_map,
93         discriminant_map: NodeMap(),
94         detected_recursive_ids: NodeSet(),
95     };
96     sess.track_errors(|| {
97         // FIXME(#37712) could use ItemLikeVisitor if trait items were item-like
98         hir_map.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
99     })
100 }
101
102 struct CheckItemRecursionVisitor<'a, 'b: 'a, 'hir: 'b> {
103     sess: &'b Session,
104     hir_map: &'b hir_map::Map<'hir>,
105     discriminant_map: &'a mut NodeMap<Option<hir::BodyId>>,
106     idstack: Vec<ast::NodeId>,
107     detected_recursive_ids: &'a mut NodeSet,
108 }
109
110 impl<'a, 'b: 'a, 'hir: 'b> CheckItemRecursionVisitor<'a, 'b, 'hir> {
111     fn new(v: &'a mut CheckCrateVisitor<'b, 'hir>) -> Self {
112         CheckItemRecursionVisitor {
113             sess: v.sess,
114             hir_map: v.hir_map,
115             discriminant_map: &mut v.discriminant_map,
116             idstack: Vec::new(),
117             detected_recursive_ids: &mut v.detected_recursive_ids,
118         }
119     }
120     fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F, span: Span)
121         where F: Fn(&mut Self)
122     {
123         if self.idstack.iter().any(|&x| x == id) {
124             if self.detected_recursive_ids.contains(&id) {
125                 return;
126             }
127             self.detected_recursive_ids.insert(id);
128             let any_static = self.idstack.iter().any(|&x| {
129                 if let hir_map::NodeItem(item) = self.hir_map.get(x) {
130                     if let hir::ItemStatic(..) = item.node {
131                         true
132                     } else {
133                         false
134                     }
135                 } else {
136                     false
137                 }
138             });
139             if !any_static {
140                 struct_span_err!(self.sess, span, E0265, "recursive constant")
141                     .span_label(span, "recursion not allowed in constant")
142                     .emit();
143             }
144             return;
145         }
146         self.idstack.push(id);
147         f(self);
148         self.idstack.pop();
149     }
150     // If a variant has an expression specifying its discriminant, then it needs
151     // to be checked just like a static or constant. However, if there are more
152     // variants with no explicitly specified discriminant, those variants will
153     // increment the same expression to get their values.
154     //
155     // So for every variant, we need to track whether there is an expression
156     // somewhere in the enum definition that controls its discriminant. We do
157     // this by starting from the end and searching backward.
158     fn populate_enum_discriminants(&mut self, enum_definition: &'hir hir::EnumDef) {
159         // Get the map, and return if we already processed this enum or if it
160         // has no variants.
161         match enum_definition.variants.first() {
162             None => {
163                 return;
164             }
165             Some(variant) if self.discriminant_map.contains_key(&variant.node.data.id()) => {
166                 return;
167             }
168             _ => {}
169         }
170
171         // Go through all the variants.
172         let mut variant_stack: Vec<ast::NodeId> = Vec::new();
173         for variant in enum_definition.variants.iter().rev() {
174             variant_stack.push(variant.node.data.id());
175             // When we find an expression, every variant currently on the stack
176             // is affected by that expression.
177             if let Some(expr) = variant.node.disr_expr {
178                 for id in &variant_stack {
179                     self.discriminant_map.insert(*id, Some(expr));
180                 }
181                 variant_stack.clear()
182             }
183         }
184         // If we are at the top, that always starts at 0, so any variant on the
185         // stack has a default value and does not need to be checked.
186         for id in &variant_stack {
187             self.discriminant_map.insert(*id, None);
188         }
189     }
190 }
191
192 impl<'a, 'b: 'a, 'hir: 'b> Visitor<'hir> for CheckItemRecursionVisitor<'a, 'b, 'hir> {
193     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
194         NestedVisitorMap::OnlyBodies(&self.hir_map)
195     }
196     fn visit_item(&mut self, it: &'hir hir::Item) {
197         self.with_item_id_pushed(it.id, |v| intravisit::walk_item(v, it), it.span);
198     }
199
200     fn visit_enum_def(&mut self,
201                       enum_definition: &'hir hir::EnumDef,
202                       generics: &'hir hir::Generics,
203                       item_id: ast::NodeId,
204                       _: 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,
210                      variant: &'hir hir::Variant,
211                      _: &'hir hir::Generics,
212                      _: ast::NodeId) {
213         let variant_id = variant.node.data.id();
214         let maybe_expr = *self.discriminant_map.get(&variant_id).unwrap_or_else(|| {
215             span_bug!(variant.span,
216                       "`check_static_recursion` attempted to visit \
217                       variant with unknown discriminant")
218         });
219         // If `maybe_expr` is `None`, that's because no discriminant is
220         // specified that affects this variant. Thus, no risk of recursion.
221         if let Some(expr) = maybe_expr {
222             let expr = &self.hir_map.body(expr).value;
223             self.with_item_id_pushed(expr.id, |v| intravisit::walk_expr(v, expr), expr.span);
224         }
225     }
226
227     fn visit_trait_item(&mut self, ti: &'hir hir::TraitItem) {
228         self.with_item_id_pushed(ti.id, |v| intravisit::walk_trait_item(v, ti), ti.span);
229     }
230
231     fn visit_impl_item(&mut self, ii: &'hir hir::ImplItem) {
232         self.with_item_id_pushed(ii.id, |v| intravisit::walk_impl_item(v, ii), ii.span);
233     }
234
235     fn visit_path(&mut self, path: &'hir hir::Path, _: ast::NodeId) {
236         match path.def {
237             Def::Static(def_id, _) |
238             Def::AssociatedConst(def_id) |
239             Def::Const(def_id) => {
240                 if let Some(node_id) = self.hir_map.as_local_node_id(def_id) {
241                     match self.hir_map.get(node_id) {
242                         hir_map::NodeItem(item) => self.visit_item(item),
243                         hir_map::NodeTraitItem(item) => self.visit_trait_item(item),
244                         hir_map::NodeImplItem(item) => self.visit_impl_item(item),
245                         hir_map::NodeForeignItem(_) => {}
246                         _ => {
247                             span_bug!(path.span,
248                                       "expected item, found {}",
249                                       self.hir_map.node_to_string(node_id));
250                         }
251                     }
252                 }
253             }
254             // For variants, we only want to check expressions that
255             // affect the specific variant used, but we need to check
256             // the whole enum definition to see what expression that
257             // might be (if any).
258             Def::VariantCtor(variant_id, CtorKind::Const) => {
259                 if let Some(variant_id) = self.hir_map.as_local_node_id(variant_id) {
260                     let variant = self.hir_map.expect_variant(variant_id);
261                     let enum_id = self.hir_map.get_parent(variant_id);
262                     let enum_item = self.hir_map.expect_item(enum_id);
263                     if let hir::ItemEnum(ref enum_def, ref generics) = enum_item.node {
264                         self.populate_enum_discriminants(enum_def);
265                         self.visit_variant(variant, generics, enum_id);
266                     } else {
267                         span_bug!(path.span,
268                                   "`check_static_recursion` found \
269                                     non-enum in Def::VariantCtor");
270                     }
271                 }
272             }
273             _ => (),
274         }
275         intravisit::walk_path(self, path);
276     }
277 }