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