]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_const.rs
Removed some unnecessary RefCells from resolve
[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 middle::def::*;
13 use middle::ty;
14 use middle::typeck;
15 use util::ppaux;
16
17 use syntax::ast::*;
18 use syntax::ast_util;
19 use syntax::visit::Visitor;
20 use syntax::visit;
21
22 struct CheckCrateVisitor<'a, 'tcx: 'a> {
23     tcx: &'a ty::ctxt<'tcx>,
24     in_const: bool
25 }
26
27 impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
28     fn with_const(&mut self, in_const: bool, f: |&mut CheckCrateVisitor<'a, 'tcx>|) {
29         let was_const = self.in_const;
30         self.in_const = in_const;
31         f(self);
32         self.in_const = was_const;
33     }
34     fn inside_const(&mut self, f: |&mut CheckCrateVisitor<'a, 'tcx>|) {
35         self.with_const(true, f);
36     }
37     fn outside_const(&mut self, f: |&mut CheckCrateVisitor<'a, 'tcx>|) {
38         self.with_const(false, f);
39     }
40 }
41
42 impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> {
43     fn visit_item(&mut self, i: &Item) {
44         check_item(self, i);
45     }
46     fn visit_pat(&mut self, p: &Pat) {
47         check_pat(self, p);
48     }
49     fn visit_expr(&mut self, ex: &Expr) {
50         check_expr(self, ex);
51     }
52 }
53
54 pub fn check_crate(tcx: &ty::ctxt) {
55     visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx, in_const: false },
56                       tcx.map.krate());
57     tcx.sess.abort_if_errors();
58 }
59
60 fn check_item(v: &mut CheckCrateVisitor, it: &Item) {
61     match it.node {
62         ItemStatic(_, _, ref ex) => {
63             v.inside_const(|v| v.visit_expr(&**ex));
64         }
65         ItemEnum(ref enum_definition, _) => {
66             for var in (*enum_definition).variants.iter() {
67                 for ex in var.node.disr_expr.iter() {
68                     v.inside_const(|v| v.visit_expr(&**ex));
69                 }
70             }
71         }
72         _ => v.outside_const(|v| visit::walk_item(v, it))
73     }
74 }
75
76 fn check_pat(v: &mut CheckCrateVisitor, p: &Pat) {
77     fn is_str(e: &Expr) -> bool {
78         match e.node {
79             ExprBox(_, ref expr) => {
80                 match expr.node {
81                     ExprLit(ref lit) => ast_util::lit_is_str(&**lit),
82                     _ => false,
83                 }
84             }
85             _ => false,
86         }
87     }
88     match p.node {
89         // Let through plain ~-string literals here
90         PatLit(ref a) => if !is_str(&**a) { v.inside_const(|v| v.visit_expr(&**a)); },
91         PatRange(ref a, ref b) => {
92             if !is_str(&**a) { v.inside_const(|v| v.visit_expr(&**a)); }
93             if !is_str(&**b) { v.inside_const(|v| v.visit_expr(&**b)); }
94         }
95         _ => v.outside_const(|v| visit::walk_pat(v, p))
96     }
97 }
98
99 fn check_expr(v: &mut CheckCrateVisitor, e: &Expr) {
100     if v.in_const {
101         match e.node {
102           ExprUnary(UnDeref, _) => { }
103           ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => {
104             span_err!(v.tcx.sess, e.span, E0010, "cannot do allocations in constant expressions");
105             return;
106           }
107           ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {}
108           ExprBinary(..) | ExprUnary(..) => {
109             let method_call = typeck::MethodCall::expr(e.id);
110             if v.tcx.method_map.borrow().contains_key(&method_call) {
111                 span_err!(v.tcx.sess, e.span, E0011,
112                     "user-defined operators are not allowed in constant expressions");
113             }
114           }
115           ExprLit(_) => (),
116           ExprCast(_, _) => {
117             let ety = ty::expr_ty(v.tcx, e);
118             if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
119                 span_err!(v.tcx.sess, e.span, E0012,
120                     "can not cast to `{}` in a constant expression",
121                     ppaux::ty_to_string(v.tcx, ety)
122                 );
123             }
124           }
125           ExprPath(ref pth) => {
126             // NB: In the future you might wish to relax this slightly
127             // to handle on-demand instantiation of functions via
128             // foo::<bar> in a const. Currently that is only done on
129             // a path in trans::callee that only works in block contexts.
130             if !pth.segments.iter().all(|segment| segment.types.is_empty()) {
131                 span_err!(v.tcx.sess, e.span, E0013,
132                     "paths in constants may only refer to items without type parameters");
133             }
134             match v.tcx.def_map.borrow().find(&e.id) {
135               Some(&DefStatic(..)) |
136               Some(&DefFn(_, _)) |
137               Some(&DefVariant(_, _, _)) |
138               Some(&DefStruct(_)) => { }
139
140               Some(&def) => {
141                 debug!("(checking const) found bad def: {:?}", def);
142                 span_err!(v.tcx.sess, e.span, E0014,
143                     "paths in constants may only refer to constants or functions");
144               }
145               None => {
146                 v.tcx.sess.span_bug(e.span, "unbound path in const?!");
147               }
148             }
149           }
150           ExprCall(ref callee, _) => {
151             match v.tcx.def_map.borrow().find(&callee.id) {
152                 Some(&DefStruct(..)) => {}    // OK.
153                 Some(&DefVariant(..)) => {}    // OK.
154                 _ => {
155                     span_err!(v.tcx.sess, e.span, E0015,
156                       "function calls in constants are limited to struct and enum constructors");
157                 }
158             }
159           }
160           ExprBlock(ref block) => {
161             // Check all statements in the block
162             for stmt in block.stmts.iter() {
163                 let block_span_err = |span|
164                     span_err!(v.tcx.sess, span, E0016,
165                         "blocks in constants are limited to items and tail expressions");
166                 match stmt.node {
167                     StmtDecl(ref span, _) => {
168                         match span.node {
169                             DeclLocal(_) => block_span_err(span.span),
170
171                             // Item statements are allowed
172                             DeclItem(_) => {}
173                         }
174                     }
175                     StmtExpr(ref expr, _) => block_span_err(expr.span),
176                     StmtSemi(ref semi, _) => block_span_err(semi.span),
177                     StmtMac(..) => v.tcx.sess.span_bug(e.span,
178                         "unexpanded statement macro in const?!")
179                 }
180             }
181             match block.expr {
182                 Some(ref expr) => check_expr(v, &**expr),
183                 None => {}
184             }
185           }
186           ExprVec(_) |
187           ExprAddrOf(MutImmutable, _) |
188           ExprParen(..) |
189           ExprField(..) |
190           ExprTupField(..) |
191           ExprIndex(..) |
192           ExprTup(..) |
193           ExprRepeat(..) |
194           ExprStruct(..) => { }
195           ExprAddrOf(_, ref inner) => {
196                 match inner.node {
197                     // Mutable slices are allowed.
198                     ExprVec(_) => {}
199                     _ => span_err!(v.tcx.sess, e.span, E0017,
200                                    "references in constants may only refer to immutable values")
201
202                 }
203           },
204
205           _ => {
206               span_err!(v.tcx.sess, e.span, E0019,
207                   "constant contains unimplemented expression type");
208               return;
209           }
210         }
211     }
212     visit::walk_expr(v, e);
213 }