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