diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index f85b8de35dd5b..ffac53735caf2 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -477,6 +477,22 @@ fn const_expr_unadjusted(cx: @mut CrateContext, (expr::cast_integral, expr::cast_pointer) => { llvm::LLVMConstIntToPtr(v, llty.to_ref()) } + (expr::cast_pointer, expr::cast_integral) => { + // it's impossible to relocate a link-time constant if the + // destination is not exactly of the same size than the pointer + // if this is the case, emit an error rather than letting + // LLVM report the error + let bty = type_of::type_of(cx, basety); + let csize = machine::llsize_of_alloc(cx, bty); + let tsize = machine::llsize_of_alloc(cx, llty); + if csize != tsize { + cx.sess.span_fatal(e.span, + "Cannot cast relocated expression to \ + a different size because its value is not known at \ + compile time"); + } + llvm::LLVMConstPtrToInt(v, llty.to_ref()) + } _ => { cx.sess.impossible_case(e.span, "bad combination of types for cast") diff --git a/src/test/compile-fail/const-ptr-cast-relocation.rs b/src/test/compile-fail/const-ptr-cast-relocation.rs new file mode 100644 index 0000000000000..5c892a05962df --- /dev/null +++ b/src/test/compile-fail/const-ptr-cast-relocation.rs @@ -0,0 +1,19 @@ +// Copyright 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn foo() { +} + +// should fail on both 32 and 64 bits archs +static a: u16 = foo as u16; +//~^ ERROR cannot cast relocated expression to a different size + +fn main() { +} diff --git a/src/test/run-pass/const-ptr-cast.rs b/src/test/run-pass/const-ptr-cast.rs new file mode 100644 index 0000000000000..559aec30f1414 --- /dev/null +++ b/src/test/run-pass/const-ptr-cast.rs @@ -0,0 +1,18 @@ +// Copyright 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn foo() { +} + +static a: uint = foo as uint; + +fn main() { + println!("{:u}", a); +}