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