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