]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_const.rs
auto merge of #6174 : sanxiyn/rust/static-string, r=brson
[rust.git] / src / librustc / middle / check_const.rs
1 // Copyright 2012 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 use driver::session::Session;
12 use middle::resolve;
13 use middle::ty;
14 use middle::typeck;
15 use util::ppaux;
16
17 use syntax::ast::*;
18 use syntax::codemap;
19 use syntax::{visit, ast_util, ast_map};
20
21 pub fn check_crate(sess: Session,
22                    crate: @crate,
23                    ast_map: ast_map::map,
24                    def_map: resolve::DefMap,
25                    method_map: typeck::method_map,
26                    tcx: ty::ctxt) {
27     visit::visit_crate(crate, false, visit::mk_vt(@visit::Visitor {
28         visit_item: |a,b,c| check_item(sess, ast_map, def_map, a, b, c),
29         visit_pat: check_pat,
30         visit_expr: |a,b,c|
31             check_expr(sess, def_map, method_map, tcx, a, b, c),
32         .. *visit::default_visitor()
33     }));
34     sess.abort_if_errors();
35 }
36
37 pub fn check_item(sess: Session,
38                   ast_map: ast_map::map,
39                   def_map: resolve::DefMap,
40                   it: @item,
41                   _is_const: bool,
42                   v: visit::vt<bool>) {
43     match it.node {
44       item_const(_, ex) => {
45         (v.visit_expr)(ex, true, v);
46         check_item_recursion(sess, ast_map, def_map, it);
47       }
48       item_enum(ref enum_definition, _) => {
49         for (*enum_definition).variants.each |var| {
50             for var.node.disr_expr.each |ex| {
51                 (v.visit_expr)(*ex, true, v);
52             }
53         }
54       }
55       _ => visit::visit_item(it, false, v)
56     }
57 }
58
59 pub fn check_pat(p: @pat, _is_const: bool, v: visit::vt<bool>) {
60     fn is_str(e: @expr) -> bool {
61         match e.node {
62             expr_vstore(
63                 @expr { node: expr_lit(@codemap::spanned {
64                     node: lit_str(_),
65                     _}),
66                        _ },
67                 expr_vstore_uniq
68             ) => true,
69             _ => false
70         }
71     }
72     match p.node {
73       // Let through plain ~-string literals here
74       pat_lit(a) => if !is_str(a) { (v.visit_expr)(a, true, v); },
75       pat_range(a, b) => {
76         if !is_str(a) { (v.visit_expr)(a, true, v); }
77         if !is_str(b) { (v.visit_expr)(b, true, v); }
78       }
79       _ => visit::visit_pat(p, false, v)
80     }
81 }
82
83 pub fn check_expr(sess: Session,
84                   def_map: resolve::DefMap,
85                   method_map: typeck::method_map,
86                   tcx: ty::ctxt,
87                   e: @expr,
88                   is_const: bool,
89                   v: visit::vt<bool>) {
90     if is_const {
91         match e.node {
92           expr_unary(deref, _) => { }
93           expr_unary(box(_), _) | expr_unary(uniq(_), _) => {
94             sess.span_err(e.span,
95                           "disallowed operator in constant expression");
96             return;
97           }
98           expr_lit(@codemap::spanned {node: lit_str(_), _}) => { }
99           expr_binary(_, _, _) | expr_unary(_, _) => {
100             if method_map.contains_key(&e.id) {
101                 sess.span_err(e.span, "user-defined operators are not \
102                                        allowed in constant expressions");
103             }
104           }
105           expr_lit(_) => (),
106           expr_cast(_, _) => {
107             let ety = ty::expr_ty(tcx, e);
108             if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
109                 sess.span_err(e.span, ~"can not cast to `" +
110                               ppaux::ty_to_str(tcx, ety) +
111                               ~"` in a constant expression");
112             }
113           }
114           expr_path(pth) => {
115             // NB: In the future you might wish to relax this slightly
116             // to handle on-demand instantiation of functions via
117             // foo::<bar> in a const. Currently that is only done on
118             // a path in trans::callee that only works in block contexts.
119             if pth.types.len() != 0 {
120                 sess.span_err(
121                     e.span, "paths in constants may only refer to \
122                              items without type parameters");
123             }
124             match def_map.find(&e.id) {
125               Some(&def_const(_)) |
126               Some(&def_fn(_, _)) |
127               Some(&def_variant(_, _)) |
128               Some(&def_struct(_)) => { }
129
130               Some(&def) => {
131                 debug!("(checking const) found bad def: %?", def);
132                 sess.span_err(
133                     e.span,
134                     "paths in constants may only refer to \
135                      constants or functions");
136               }
137               None => {
138                 sess.span_bug(e.span, "unbound path in const?!");
139               }
140             }
141           }
142           expr_call(callee, _, NoSugar) => {
143             match def_map.find(&callee.id) {
144                 Some(&def_struct(*)) => {}    // OK.
145                 Some(&def_variant(*)) => {}    // OK.
146                 _ => {
147                     sess.span_err(
148                         e.span,
149                         "function calls in constants are limited to \
150                          struct and enum constructors");
151                 }
152             }
153           }
154           expr_paren(e) => { check_expr(sess, def_map, method_map,
155                                          tcx, e, is_const, v); }
156           expr_vstore(_, expr_vstore_slice) |
157           expr_vec(_, m_imm) |
158           expr_addr_of(m_imm, _) |
159           expr_field(*) |
160           expr_index(*) |
161           expr_tup(*) |
162           expr_struct(_, _, None) => { }
163           expr_addr_of(*) => {
164                 sess.span_err(
165                     e.span,
166                     "borrowed pointers in constants may only refer to \
167                      immutable values");
168           }
169           _ => {
170             sess.span_err(e.span,
171                           "constant contains unimplemented expression type");
172             return;
173           }
174         }
175     }
176     match e.node {
177       expr_lit(@codemap::spanned {node: lit_int(v, t), _}) => {
178         if t != ty_char {
179             if (v as u64) > ast_util::int_ty_max(
180                 if t == ty_i { sess.targ_cfg.int_type } else { t }) {
181                 sess.span_err(e.span, "literal out of range for its type");
182             }
183         }
184       }
185       expr_lit(@codemap::spanned {node: lit_uint(v, t), _}) => {
186         if v > ast_util::uint_ty_max(
187             if t == ty_u { sess.targ_cfg.uint_type } else { t }) {
188             sess.span_err(e.span, "literal out of range for its type");
189         }
190       }
191       _ => ()
192     }
193     visit::visit_expr(e, is_const, v);
194 }
195
196 // Make sure a const item doesn't recursively refer to itself
197 // FIXME: Should use the dependency graph when it's available (#1356)
198 pub fn check_item_recursion(sess: Session,
199                             ast_map: ast_map::map,
200                             def_map: resolve::DefMap,
201                             it: @item) {
202     struct env {
203         root_it: @item,
204         sess: Session,
205         ast_map: ast_map::map,
206         def_map: resolve::DefMap,
207         idstack: @mut ~[node_id]
208     }
209
210     let env = env {
211         root_it: it,
212         sess: sess,
213         ast_map: ast_map,
214         def_map: def_map,
215         idstack: @mut ~[]
216     };
217
218     let visitor = visit::mk_vt(@visit::Visitor {
219         visit_item: visit_item,
220         visit_expr: visit_expr,
221         .. *visit::default_visitor()
222     });
223     (visitor.visit_item)(it, env, visitor);
224
225     fn visit_item(it: @item, env: env, v: visit::vt<env>) {
226         if env.idstack.contains(&(it.id)) {
227             env.sess.span_fatal(env.root_it.span, "recursive constant");
228         }
229         env.idstack.push(it.id);
230         visit::visit_item(it, env, v);
231         env.idstack.pop();
232     }
233
234     fn visit_expr(e: @expr, env: env, v: visit::vt<env>) {
235         match e.node {
236           expr_path(*) => {
237             match env.def_map.find(&e.id) {
238               Some(&def_const(def_id)) => {
239                 if ast_util::is_local(def_id) {
240                   match *env.ast_map.get(&def_id.node) {
241                     ast_map::node_item(it, _) => {
242                       (v.visit_item)(it, env, v);
243                     }
244                     _ => fail!(~"const not bound to an item")
245                   }
246                 }
247               }
248               _ => ()
249             }
250           }
251           _ => ()
252         }
253         visit::visit_expr(e, env, v);
254     }
255 }