]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_const.rs
Removed the obsolete ast::CallSugar (previously used by `do`).
[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     def_map: resolve::DefMap,
26     method_map: typeck::method_map,
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::method_map,
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::method_map,
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(_, ExprVstoreSlice) |
177           ExprVec(_, MutImmutable) |
178           ExprAddrOf(MutImmutable, _) |
179           ExprParen(..) |
180           ExprField(..) |
181           ExprIndex(..) |
182           ExprTup(..) |
183           ExprRepeat(..) |
184           ExprStruct(..) => { }
185           ExprAddrOf(..) => {
186                 sess.span_err(
187                     e.span,
188                     "references in constants may only refer to \
189                      immutable values");
190           },
191           ExprVstore(_, ExprVstoreUniq) => {
192               sess.span_err(e.span, "cannot allocate vectors in constant expressions")
193           },
194
195           _ => {
196             sess.span_err(e.span,
197                           "constant contains unimplemented expression type");
198             return;
199           }
200         }
201     }
202     visit::walk_expr(v, e, is_const);
203 }
204
205 struct CheckItemRecursionVisitor<'a> {
206     root_it: &'a Item,
207     sess: Session,
208     ast_map: &'a ast_map::Map,
209     def_map: resolve::DefMap,
210     idstack: ~[NodeId]
211 }
212
213 // Make sure a const item doesn't recursively refer to itself
214 // FIXME: Should use the dependency graph when it's available (#1356)
215 pub fn check_item_recursion<'a>(sess: Session,
216                                 ast_map: &'a ast_map::Map,
217                                 def_map: resolve::DefMap,
218                                 it: &'a Item) {
219
220     let mut visitor = CheckItemRecursionVisitor {
221         root_it: it,
222         sess: sess,
223         ast_map: ast_map,
224         def_map: def_map,
225         idstack: ~[]
226     };
227     visitor.visit_item(it, ());
228 }
229
230 impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> {
231     fn visit_item(&mut self, it: &Item, _: ()) {
232         if self.idstack.iter().any(|x| x == &(it.id)) {
233             self.sess.span_fatal(self.root_it.span, "recursive constant");
234         }
235         self.idstack.push(it.id);
236         visit::walk_item(self, it, ());
237         self.idstack.pop();
238     }
239
240     fn visit_expr(&mut self, e: &Expr, _: ()) {
241         match e.node {
242             ExprPath(..) => {
243                 let def_map = self.def_map.borrow();
244                 match def_map.get().find(&e.id) {
245                     Some(&DefStatic(def_id, _)) if
246                             ast_util::is_local(def_id) => {
247                         self.visit_item(self.ast_map.expect_item(def_id.node), ());
248                     }
249                     _ => ()
250                 }
251             },
252             _ => ()
253         }
254         visit::walk_expr(self, e, ());
255     }
256 }