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