rust/src/librustc/middle/check_const.rs

250 lines
8.6 KiB
Rust
Raw Normal View History

// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use driver::session::Session;
use middle::def::*;
use middle::resolve;
use middle::ty;
use middle::typeck;
use util::ppaux;
use syntax::ast::*;
use syntax::{ast_util, ast_map};
use syntax::visit::Visitor;
use syntax::visit;
2014-03-05 21:07:47 -06:00
pub struct CheckCrateVisitor<'a> {
tcx: &'a ty::ctxt,
}
2014-03-05 21:07:47 -06:00
impl<'a> Visitor<bool> for CheckCrateVisitor<'a> {
fn visit_item(&mut self, i: &Item, env: bool) {
2014-03-05 08:36:01 -06:00
check_item(self, i, env);
}
2014-01-06 06:00:46 -06:00
fn visit_pat(&mut self, p: &Pat, env: bool) {
check_pat(self, p, env);
}
2014-01-06 06:00:46 -06:00
fn visit_expr(&mut self, ex: &Expr, env: bool) {
2014-03-05 08:36:01 -06:00
check_expr(self, ex, env);
}
}
pub fn check_crate(krate: &Crate, tcx: &ty::ctxt) {
visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx }, krate, false);
2014-03-05 08:36:01 -06:00
tcx.sess.abort_if_errors();
}
2014-03-05 08:36:01 -06:00
fn check_item(v: &mut CheckCrateVisitor, it: &Item, _is_const: bool) {
2012-08-06 14:34:08 -05:00
match it.node {
ItemStatic(_, _, ex) => {
2014-05-16 12:15:33 -05:00
v.visit_expr(&*ex, true);
2014-04-22 11:06:43 -05:00
check_item_recursion(&v.tcx.sess, &v.tcx.map, &v.tcx.def_map, it);
}
ItemEnum(ref enum_definition, _) => {
for var in (*enum_definition).variants.iter() {
for ex in var.node.disr_expr.iter() {
2014-05-16 12:15:33 -05:00
v.visit_expr(&**ex, true);
}
}
}
_ => visit::walk_item(v, it, false)
}
}
2014-03-05 08:36:01 -06:00
fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) {
fn is_str(e: &Expr) -> bool {
2012-08-06 14:34:08 -05:00
match e.node {
DST coercions and DST structs [breaking-change] 1. The internal layout for traits has changed from (vtable, data) to (data, vtable). If you were relying on this in unsafe transmutes, you might get some very weird and apparently unrelated errors. You should not be doing this! Prefer not to do this at all, but if you must, you should use raw::TraitObject rather than hardcoding rustc's internal representation into your code. 2. The minimal type of reference-to-vec-literals (e.g., `&[1, 2, 3]`) is now a fixed size vec (e.g., `&[int, ..3]`) where it used to be an unsized vec (e.g., `&[int]`). If you want the unszied type, you must explicitly give the type (e.g., `let x: &[_] = &[1, 2, 3]`). Note in particular where multiple blocks must have the same type (e.g., if and else clauses, vec elements), the compiler will not coerce to the unsized type without a hint. E.g., `[&[1], &[1, 2]]` used to be a valid expression of type '[&[int]]'. It no longer type checks since the first element now has type `&[int, ..1]` and the second has type &[int, ..2]` which are incompatible. 3. The type of blocks (including functions) must be coercible to the expected type (used to be a subtype). Mostly this makes things more flexible and not less (in particular, in the case of coercing function bodies to the return type). However, in some rare cases, this is less flexible. TBH, I'm not exactly sure of the exact effects. I think the change causes us to resolve inferred type variables slightly earlier which might make us slightly more restrictive. Possibly it only affects blocks with unreachable code. E.g., `if ... { fail!(); "Hello" }` used to type check, it no longer does. The fix is to add a semicolon after the string.
2014-08-04 07:20:11 -05:00
ExprBox(_, expr) => {
match expr.node {
ExprLit(lit) => ast_util::lit_is_str(lit),
_ => false,
}
}
_ => false,
2012-07-12 14:14:08 -05:00
}
}
2012-08-06 14:34:08 -05:00
match p.node {
// Let through plain ~-string literals here
2014-05-16 12:15:33 -05:00
PatLit(ref a) => if !is_str(&**a) { v.visit_expr(&**a, true); },
PatRange(ref a, ref b) => {
if !is_str(&**a) { v.visit_expr(&**a, true); }
if !is_str(&**b) { v.visit_expr(&**b, true); }
}
_ => visit::walk_pat(v, p, false)
}
}
2014-03-05 08:36:01 -06:00
fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) {
if is_const {
2012-08-06 14:34:08 -05:00
match e.node {
ExprUnary(UnDeref, _) => { }
ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => {
span_err!(v.tcx.sess, e.span, E0010, "cannot do allocations in constant expressions");
2012-08-01 19:30:05 -05:00
return;
}
ExprLit(lit) if ast_util::lit_is_str(lit) => {}
2013-11-28 14:22:53 -06:00
ExprBinary(..) | ExprUnary(..) => {
2014-03-05 08:36:01 -06:00
let method_call = typeck::MethodCall::expr(e.id);
if v.tcx.method_map.borrow().contains_key(&method_call) {
span_err!(v.tcx.sess, e.span, E0011,
"user-defined operators are not allowed in constant expressions");
}
}
ExprLit(_) => (),
ExprCast(_, _) => {
2014-03-05 08:36:01 -06:00
let ety = ty::expr_ty(v.tcx, e);
if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
span_err!(v.tcx.sess, e.span, E0012,
"can not cast to `{}` in a constant expression",
ppaux::ty_to_string(v.tcx, ety)
);
}
}
ExprPath(ref pth) => {
// NB: In the future you might wish to relax this slightly
// to handle on-demand instantiation of functions via
// foo::<bar> in a const. Currently that is only done on
// a path in trans::callee that only works in block contexts.
if !pth.segments.iter().all(|segment| segment.types.is_empty()) {
span_err!(v.tcx.sess, e.span, E0013,
"paths in constants may only refer to items without type parameters");
}
match v.tcx.def_map.borrow().find(&e.id) {
2013-11-28 14:22:53 -06:00
Some(&DefStatic(..)) |
Some(&DefFn(_, _)) |
Some(&DefVariant(_, _, _)) |
Some(&DefStruct(_)) => { }
2013-03-22 21:26:41 -05:00
Some(&def) => {
debug!("(checking const) found bad def: {:?}", def);
span_err!(v.tcx.sess, e.span, E0014,
"paths in constants may only refer to constants or functions");
}
None => {
2014-03-05 08:36:01 -06:00
v.tcx.sess.span_bug(e.span, "unbound path in const?!");
}
}
}
ExprCall(callee, _) => {
match v.tcx.def_map.borrow().find(&callee.id) {
2013-11-28 14:22:53 -06:00
Some(&DefStruct(..)) => {} // OK.
Some(&DefVariant(..)) => {} // OK.
_ => {
span_err!(v.tcx.sess, e.span, E0015,
"function calls in constants are limited to struct and enum constructors");
}
}
}
ExprBlock(ref block) => {
// Check all statements in the block
for stmt in block.stmts.iter() {
let block_span_err = |span|
span_err!(v.tcx.sess, span, E0016,
"blocks in constants are limited to items and tail expressions");
match stmt.node {
StmtDecl(ref span, _) => {
match span.node {
DeclLocal(_) => block_span_err(span.span),
// Item statements are allowed
DeclItem(_) => {}
}
}
StmtExpr(ref expr, _) => block_span_err(expr.span),
StmtSemi(ref semi, _) => block_span_err(semi.span),
StmtMac(..) => v.tcx.sess.span_bug(e.span,
"unexpanded statement macro in const?!")
}
}
match block.expr {
Some(ref expr) => check_expr(v, &**expr, true),
None => {}
}
}
ExprVec(_) |
ExprAddrOf(MutImmutable, _) |
ExprParen(..) |
2013-11-28 14:22:53 -06:00
ExprField(..) |
ExprIndex(..) |
ExprTup(..) |
ExprRepeat(..) |
ExprStruct(..) => { }
DST coercions and DST structs [breaking-change] 1. The internal layout for traits has changed from (vtable, data) to (data, vtable). If you were relying on this in unsafe transmutes, you might get some very weird and apparently unrelated errors. You should not be doing this! Prefer not to do this at all, but if you must, you should use raw::TraitObject rather than hardcoding rustc's internal representation into your code. 2. The minimal type of reference-to-vec-literals (e.g., `&[1, 2, 3]`) is now a fixed size vec (e.g., `&[int, ..3]`) where it used to be an unsized vec (e.g., `&[int]`). If you want the unszied type, you must explicitly give the type (e.g., `let x: &[_] = &[1, 2, 3]`). Note in particular where multiple blocks must have the same type (e.g., if and else clauses, vec elements), the compiler will not coerce to the unsized type without a hint. E.g., `[&[1], &[1, 2]]` used to be a valid expression of type '[&[int]]'. It no longer type checks since the first element now has type `&[int, ..1]` and the second has type &[int, ..2]` which are incompatible. 3. The type of blocks (including functions) must be coercible to the expected type (used to be a subtype). Mostly this makes things more flexible and not less (in particular, in the case of coercing function bodies to the return type). However, in some rare cases, this is less flexible. TBH, I'm not exactly sure of the exact effects. I think the change causes us to resolve inferred type variables slightly earlier which might make us slightly more restrictive. Possibly it only affects blocks with unreachable code. E.g., `if ... { fail!(); "Hello" }` used to type check, it no longer does. The fix is to add a semicolon after the string.
2014-08-04 07:20:11 -05:00
ExprAddrOf(_, inner) => {
match inner.node {
// Mutable slices are allowed.
ExprVec(_) => {}
_ => span_err!(v.tcx.sess, e.span, E0017,
"references in constants may only refer to immutable values");
}
},
2012-08-03 21:59:04 -05:00
_ => {
span_err!(v.tcx.sess, e.span, E0019,
"constant contains unimplemented expression type");
return;
}
}
}
visit::walk_expr(v, e, is_const);
}
2014-01-06 06:00:46 -06:00
struct CheckItemRecursionVisitor<'a> {
root_it: &'a Item,
2014-03-05 08:36:01 -06:00
sess: &'a Session,
ast_map: &'a ast_map::Map,
2014-04-22 11:06:43 -05:00
def_map: &'a resolve::DefMap,
idstack: Vec<NodeId> }
2012-04-04 18:12:57 -05:00
// Make sure a const item doesn't recursively refer to itself
2012-06-07 15:49:01 -05:00
// FIXME: Should use the dependency graph when it's available (#1356)
2014-03-05 08:36:01 -06:00
pub fn check_item_recursion<'a>(sess: &'a Session,
ast_map: &'a ast_map::Map,
2014-04-22 11:06:43 -05:00
def_map: &'a resolve::DefMap,
it: &'a Item) {
2014-01-06 06:00:46 -06:00
let mut visitor = CheckItemRecursionVisitor {
2012-04-04 18:12:57 -05:00
root_it: it,
sess: sess,
ast_map: ast_map,
def_map: def_map,
idstack: Vec::new()
2012-04-04 18:12:57 -05:00
};
visitor.visit_item(it, ());
}
2012-04-04 18:12:57 -05:00
2014-01-06 06:00:46 -06:00
impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> {
fn visit_item(&mut self, it: &Item, _: ()) {
2014-01-06 06:00:46 -06:00
if self.idstack.iter().any(|x| x == &(it.id)) {
self.sess.span_fatal(self.root_it.span, "recursive constant");
2012-04-04 18:12:57 -05:00
}
2014-01-06 06:00:46 -06:00
self.idstack.push(it.id);
visit::walk_item(self, it, ());
2014-01-06 06:00:46 -06:00
self.idstack.pop();
2012-04-04 18:12:57 -05:00
}
2014-01-06 06:00:46 -06:00
fn visit_expr(&mut self, e: &Expr, _: ()) {
2012-08-06 14:34:08 -05:00
match e.node {
ExprPath(..) => {
2014-03-20 21:49:20 -05:00
match self.def_map.borrow().find(&e.id) {
Some(&DefStatic(def_id, _)) if
2013-12-27 18:09:29 -06:00
ast_util::is_local(def_id) => {
2014-05-16 12:15:33 -05:00
self.visit_item(&*self.ast_map.expect_item(def_id.node), ());
2013-12-27 18:09:29 -06:00
}
_ => ()
}
},
_ => ()
2012-04-04 18:12:57 -05:00
}
visit::walk_expr(self, e, ());
2012-04-04 18:12:57 -05:00
}
}