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