]> git.lizzy.rs Git - rust.git/blob - src/error.rs
improve out of bounds error message
[rust.git] / src / error.rs
1 use std::error::Error;
2 use std::fmt;
3 use rustc::mir::repr as mir;
4 use memory::Pointer;
5
6 #[derive(Clone, Debug)]
7 pub enum EvalError {
8     DanglingPointerDeref,
9     InvalidBool,
10     InvalidDiscriminant,
11     PointerOutOfBounds {
12         ptr: Pointer,
13         size: usize,
14         allocation_size: usize,
15     },
16     ReadPointerAsBytes,
17     ReadBytesAsPointer,
18     InvalidPointerMath,
19     ReadUndefBytes,
20     InvalidBoolOp(mir::BinOp),
21     Unimplemented(String),
22 }
23
24 pub type EvalResult<T> = Result<T, EvalError>;
25
26 impl Error for EvalError {
27     fn description(&self) -> &str {
28         match *self {
29             EvalError::DanglingPointerDeref =>
30                 "dangling pointer was dereferenced",
31             EvalError::InvalidBool =>
32                 "invalid boolean value read",
33             EvalError::InvalidDiscriminant =>
34                 "invalid enum discriminant value read",
35             EvalError::PointerOutOfBounds { .. } =>
36                 "pointer offset outside bounds of allocation",
37             EvalError::ReadPointerAsBytes =>
38                 "a raw memory access tried to access part of a pointer value as raw bytes",
39             EvalError::ReadBytesAsPointer =>
40                 "attempted to interpret some raw bytes as a pointer address",
41             EvalError::InvalidPointerMath =>
42                 "attempted to do math or a comparison on pointers into different allocations",
43             EvalError::ReadUndefBytes =>
44                 "attempted to read undefined bytes",
45             EvalError::InvalidBoolOp(_) =>
46                 "invalid boolean operation",
47             EvalError::Unimplemented(ref msg) => msg,
48         }
49     }
50
51     fn cause(&self) -> Option<&Error> { None }
52 }
53
54 impl fmt::Display for EvalError {
55     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56         match *self {
57             EvalError::PointerOutOfBounds { ptr, size, allocation_size } => {
58                 write!(f, "memory access of {}..{} outside bounds of allocation {} which has size {}",
59                        ptr.offset, ptr.offset + size, ptr.alloc_id, allocation_size)
60             },
61             _ => write!(f, "{}", self.description()),
62         }
63     }
64 }