]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_const.rs
auto merge of #12871 : aochagavia/rust/Optimize-while_some, r=alexcrichton
[rust.git] / src / librustc / middle / check_const.rs
1 // Copyright 2012-2013 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
12 use driver::session::Session;
13 use middle::resolve;
14 use middle::ty;
15 use middle::typeck;
16 use util::ppaux;
17
18 use std::vec_ng::Vec;
19 use syntax::ast::*;
20 use syntax::{ast_util, ast_map};
21 use syntax::visit::Visitor;
22 use syntax::visit;
23
24 pub struct CheckCrateVisitor {
25     sess: Session,
26     def_map: resolve::DefMap,
27     method_map: typeck::MethodMap,
28     tcx: ty::ctxt,
29 }
30
31 impl Visitor<bool> for CheckCrateVisitor {
32     fn visit_item(&mut self, i: &Item, env: bool) {
33         check_item(self, self.sess, self.def_map, i, env);
34     }
35     fn visit_pat(&mut self, p: &Pat, env: bool) {
36         check_pat(self, p, env);
37     }
38     fn visit_expr(&mut self, ex: &Expr, env: bool) {
39         check_expr(self, self.sess, self.def_map, self.method_map,
40                    self.tcx, ex, env);
41     }
42 }
43
44 pub fn check_crate(sess: Session,
45                    krate: &Crate,
46                    def_map: resolve::DefMap,
47                    method_map: typeck::MethodMap,
48                    tcx: ty::ctxt) {
49     let mut v = CheckCrateVisitor {
50         sess: sess,
51         def_map: def_map,
52         method_map: method_map,
53         tcx: tcx,
54     };
55     visit::walk_crate(&mut v, krate, false);
56     sess.abort_if_errors();
57 }
58
59 pub fn check_item(v: &mut CheckCrateVisitor,
60                   sess: Session,
61                   def_map: resolve::DefMap,
62                   it: &Item,
63                   _is_const: bool) {
64     match it.node {
65         ItemStatic(_, _, ex) => {
66             v.visit_expr(ex, true);
67             check_item_recursion(sess, &v.tcx.map, def_map, it);
68         }
69         ItemEnum(ref enum_definition, _) => {
70             for var in (*enum_definition).variants.iter() {
71                 for ex in var.node.disr_expr.iter() {
72                     v.visit_expr(*ex, true);
73                 }
74             }
75         }
76         _ => visit::walk_item(v, it, false)
77     }
78 }
79
80 pub fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) {
81     fn is_str(e: @Expr) -> bool {
82         match e.node {
83             ExprVstore(expr, ExprVstoreUniq) => {
84                 match expr.node {
85                     ExprLit(lit) => ast_util::lit_is_str(lit),
86                     _ => false,
87                 }
88             }
89             _ => false,
90         }
91     }
92     match p.node {
93       // Let through plain ~-string literals here
94       PatLit(a) => if !is_str(a) { v.visit_expr(a, true); },
95       PatRange(a, b) => {
96         if !is_str(a) { v.visit_expr(a, true); }
97         if !is_str(b) { v.visit_expr(b, true); }
98       }
99       _ => visit::walk_pat(v, p, false)
100     }
101 }
102
103 pub fn check_expr(v: &mut CheckCrateVisitor,
104                   sess: Session,
105                   def_map: resolve::DefMap,
106                   method_map: typeck::MethodMap,
107                   tcx: ty::ctxt,
108                   e: &Expr,
109                   is_const: bool) {
110     if is_const {
111         match e.node {
112           ExprUnary(UnDeref, _) => { }
113           ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => {
114             sess.span_err(e.span,
115                           "cannot do allocations in constant expressions");
116             return;
117           }
118           ExprLit(lit) if ast_util::lit_is_str(lit) => {}
119           ExprBinary(..) | ExprUnary(..) => {
120               let method_call = typeck::MethodCall::expr(e.id);
121             if method_map.borrow().get().contains_key(&method_call) {
122                 sess.span_err(e.span, "user-defined operators are not \
123                                        allowed in constant expressions");
124             }
125           }
126           ExprLit(_) => (),
127           ExprCast(_, _) => {
128             let ety = ty::expr_ty(tcx, e);
129             if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
130                 sess.span_err(e.span, ~"can not cast to `" +
131                               ppaux::ty_to_str(tcx, ety) +
132                               "` in a constant expression");
133             }
134           }
135           ExprPath(ref pth) => {
136             // NB: In the future you might wish to relax this slightly
137             // to handle on-demand instantiation of functions via
138             // foo::<bar> in a const. Currently that is only done on
139             // a path in trans::callee that only works in block contexts.
140             if !pth.segments.iter().all(|segment| segment.types.is_empty()) {
141                 sess.span_err(
142                     e.span, "paths in constants may only refer to \
143                              items without type parameters");
144             }
145             let def_map = def_map.borrow();
146             match def_map.get().find(&e.id) {
147               Some(&DefStatic(..)) |
148               Some(&DefFn(_, _)) |
149               Some(&DefVariant(_, _, _)) |
150               Some(&DefStruct(_)) => { }
151
152               Some(&def) => {
153                 debug!("(checking const) found bad def: {:?}", def);
154                 sess.span_err(
155                     e.span,
156                     "paths in constants may only refer to \
157                      constants or functions");
158               }
159               None => {
160                 sess.span_bug(e.span, "unbound path in const?!");
161               }
162             }
163           }
164           ExprCall(callee, _) => {
165             let def_map = def_map.borrow();
166             match def_map.get().find(&callee.id) {
167                 Some(&DefStruct(..)) => {}    // OK.
168                 Some(&DefVariant(..)) => {}    // OK.
169                 _ => {
170                     sess.span_err(
171                         e.span,
172                         "function calls in constants are limited to \
173                          struct and enum constructors");
174                 }
175             }
176           }
177           ExprVstore(_, ExprVstoreSlice) |
178           ExprVec(_, MutImmutable) |
179           ExprAddrOf(MutImmutable, _) |
180           ExprParen(..) |
181           ExprField(..) |
182           ExprIndex(..) |
183           ExprTup(..) |
184           ExprRepeat(..) |
185           ExprStruct(..) => { }
186           ExprAddrOf(..) => {
187                 sess.span_err(
188                     e.span,
189                     "references in constants may only refer to \
190                      immutable values");
191           },
192           ExprVstore(_, ExprVstoreUniq) => {
193               sess.span_err(e.span, "cannot allocate vectors in constant expressions")
194           },
195
196           _ => {
197             sess.span_err(e.span,
198                           "constant contains unimplemented expression type");
199             return;
200           }
201         }
202     }
203     visit::walk_expr(v, e, is_const);
204 }
205
206 struct CheckItemRecursionVisitor<'a> {
207     root_it: &'a Item,
208     sess: Session,
209     ast_map: &'a ast_map::Map,
210     def_map: resolve::DefMap,
211     idstack: Vec<NodeId> }
212
213 // Make sure a const item doesn't recursively refer to itself
214 // FIXME: Should use the dependency graph when it's available (#1356)
215 pub fn check_item_recursion<'a>(sess: Session,
216                                 ast_map: &'a ast_map::Map,
217                                 def_map: resolve::DefMap,
218                                 it: &'a Item) {
219
220     let mut visitor = CheckItemRecursionVisitor {
221         root_it: it,
222         sess: sess,
223         ast_map: ast_map,
224         def_map: def_map,
225         idstack: Vec::new()
226     };
227     visitor.visit_item(it, ());
228 }
229
230 impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> {
231     fn visit_item(&mut self, it: &Item, _: ()) {
232         if self.idstack.iter().any(|x| x == &(it.id)) {
233             self.sess.span_fatal(self.root_it.span, "recursive constant");
234         }
235         self.idstack.push(it.id);
236         visit::walk_item(self, it, ());
237         self.idstack.pop();
238     }
239
240     fn visit_expr(&mut self, e: &Expr, _: ()) {
241         match e.node {
242             ExprPath(..) => {
243                 let def_map = self.def_map.borrow();
244                 match def_map.get().find(&e.id) {
245                     Some(&DefStatic(def_id, _)) if
246                             ast_util::is_local(def_id) => {
247                         self.visit_item(self.ast_map.expect_item(def_id.node), ());
248                     }
249                     _ => ()
250                 }
251             },
252             _ => ()
253         }
254         visit::walk_expr(self, e, ());
255     }
256 }