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