]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/value.rs
Rollup merge of #61191 - phansch:annotate_snippet_refactorings1, r=estebank
[rust.git] / src / librustc / mir / interpret / value.rs
1 use std::fmt;
2 use rustc_macros::HashStable;
3
4 use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size}, subst::SubstsRef};
5 use crate::ty::PlaceholderConst;
6 use crate::hir::def_id::DefId;
7
8 use super::{EvalResult, Pointer, PointerArithmetic, Allocation, AllocId, sign_extend, truncate};
9
10 /// Represents the result of a raw const operation, pre-validation.
11 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
12 pub struct RawConst<'tcx> {
13     // the value lives here, at offset 0, and that allocation definitely is a `AllocKind::Memory`
14     // (so you can use `AllocMap::unwrap_memory`).
15     pub alloc_id: AllocId,
16     pub ty: Ty<'tcx>,
17 }
18
19 /// Represents a constant value in Rust. `Scalar` and `ScalarPair` are optimizations that
20 /// match the `LocalState` optimizations for easy conversions between `Value` and `ConstValue`.
21 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
22          RustcEncodable, RustcDecodable, Hash, HashStable)]
23 pub enum ConstValue<'tcx> {
24     /// A const generic parameter.
25     Param(ParamConst),
26
27     /// Infer the value of the const.
28     Infer(InferConst<'tcx>),
29
30     /// A placeholder const - universally quantified higher-ranked const.
31     Placeholder(PlaceholderConst),
32
33     /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
34     ///
35     /// Not using the enum `Value` to encode that this must not be `Undef`.
36     Scalar(Scalar),
37
38     /// Used only for `&[u8]` and `&str`
39     Slice {
40         data: &'tcx Allocation,
41         start: usize,
42         end: usize,
43     },
44
45     /// An allocation together with a pointer into the allocation.
46     /// Invariant: the pointer's `AllocId` resolves to the allocation.
47     ByRef(Pointer, &'tcx Allocation),
48
49     /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other
50     /// variants when the code is monomorphic enough for that.
51     Unevaluated(DefId, SubstsRef<'tcx>),
52 }
53
54 #[cfg(target_arch = "x86_64")]
55 static_assert_size!(ConstValue<'_>, 32);
56
57 impl<'tcx> ConstValue<'tcx> {
58     #[inline]
59     pub fn try_to_scalar(&self) -> Option<Scalar> {
60         match *self {
61             ConstValue::Param(_) |
62             ConstValue::Infer(_) |
63             ConstValue::Placeholder(_) |
64             ConstValue::ByRef(..) |
65             ConstValue::Unevaluated(..) |
66             ConstValue::Slice { .. } => None,
67             ConstValue::Scalar(val) => Some(val),
68         }
69     }
70
71     #[inline]
72     pub fn try_to_bits(&self, size: Size) -> Option<u128> {
73         self.try_to_scalar()?.to_bits(size).ok()
74     }
75
76     #[inline]
77     pub fn try_to_ptr(&self) -> Option<Pointer> {
78         self.try_to_scalar()?.to_ptr().ok()
79     }
80 }
81
82 /// A `Scalar` represents an immediate, primitive value existing outside of a
83 /// `memory::Allocation`. It is in many ways like a small chunk of a `Allocation`, up to 8 bytes in
84 /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes
85 /// of a simple value or a pointer into another `Allocation`
86 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd,
87          RustcEncodable, RustcDecodable, Hash, HashStable)]
88 pub enum Scalar<Tag=(), Id=AllocId> {
89     /// The raw bytes of a simple value.
90     Raw {
91         /// The first `size` bytes of `data` are the value.
92         /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
93         data: u128,
94         size: u8,
95     },
96
97     /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of
98     /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the
99     /// relocation and its associated offset together as a `Pointer` here.
100     Ptr(Pointer<Tag, Id>),
101 }
102
103 #[cfg(target_arch = "x86_64")]
104 static_assert_size!(Scalar, 24);
105
106 impl<Tag: fmt::Debug, Id: fmt::Debug> fmt::Debug for Scalar<Tag, Id> {
107     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108         match self {
109             Scalar::Ptr(ptr) =>
110                 write!(f, "{:?}", ptr),
111             &Scalar::Raw { data, size } => {
112                 Scalar::check_data(data, size);
113                 if size == 0 {
114                     write!(f, "<ZST>")
115                 } else {
116                     // Format as hex number wide enough to fit any value of the given `size`.
117                     // So data=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
118                     write!(f, "0x{:>0width$x}", data, width=(size*2) as usize)
119                 }
120             }
121         }
122     }
123 }
124
125 impl<Tag> fmt::Display for Scalar<Tag> {
126     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127         match self {
128             Scalar::Ptr(_) => write!(f, "a pointer"),
129             Scalar::Raw { data, .. } => write!(f, "{}", data),
130         }
131     }
132 }
133
134 impl<'tcx> Scalar<()> {
135     #[inline(always)]
136     fn check_data(data: u128, size: u8) {
137         debug_assert_eq!(truncate(data, Size::from_bytes(size as u64)), data,
138                          "Scalar value {:#x} exceeds size of {} bytes", data, size);
139     }
140
141     #[inline]
142     pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
143         match self {
144             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
145             Scalar::Raw { data, size } => Scalar::Raw { data, size },
146         }
147     }
148
149     #[inline(always)]
150     pub fn with_default_tag<Tag>(self) -> Scalar<Tag>
151         where Tag: Default
152     {
153         self.with_tag(Tag::default())
154     }
155 }
156
157 impl<'tcx, Tag> Scalar<Tag> {
158     #[inline]
159     pub fn erase_tag(self) -> Scalar {
160         match self {
161             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
162             Scalar::Raw { data, size } => Scalar::Raw { data, size },
163         }
164     }
165
166     #[inline]
167     pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
168         Scalar::Raw {
169             data: 0,
170             size: cx.data_layout().pointer_size.bytes() as u8,
171         }
172     }
173
174     #[inline]
175     pub fn zst() -> Self {
176         Scalar::Raw { data: 0, size: 0 }
177     }
178
179     #[inline]
180     pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
181         let dl = cx.data_layout();
182         match self {
183             Scalar::Raw { data, size } => {
184                 assert_eq!(size as u64, dl.pointer_size.bytes());
185                 Ok(Scalar::Raw {
186                     data: dl.offset(data as u64, i.bytes())? as u128,
187                     size,
188                 })
189             }
190             Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
191         }
192     }
193
194     #[inline]
195     pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
196         let dl = cx.data_layout();
197         match self {
198             Scalar::Raw { data, size } => {
199                 assert_eq!(size as u64, dl.pointer_size.bytes());
200                 Scalar::Raw {
201                     data: dl.overflowing_offset(data as u64, i.bytes()).0 as u128,
202                     size,
203                 }
204             }
205             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
206         }
207     }
208
209     #[inline]
210     pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
211         let dl = cx.data_layout();
212         match self {
213             Scalar::Raw { data, size } => {
214                 assert_eq!(size as u64, dl.pointer_size().bytes());
215                 Ok(Scalar::Raw {
216                     data: dl.signed_offset(data as u64, i)? as u128,
217                     size,
218                 })
219             }
220             Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
221         }
222     }
223
224     #[inline]
225     pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
226         let dl = cx.data_layout();
227         match self {
228             Scalar::Raw { data, size } => {
229                 assert_eq!(size as u64, dl.pointer_size.bytes());
230                 Scalar::Raw {
231                     data: dl.overflowing_signed_offset(data as u64, i128::from(i)).0 as u128,
232                     size,
233                 }
234             }
235             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
236         }
237     }
238
239     /// Returns this pointer's offset from the allocation base, or from NULL (for
240     /// integer pointers).
241     #[inline]
242     pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
243         match self {
244             Scalar::Raw { data, size } => {
245                 assert_eq!(size as u64, cx.pointer_size().bytes());
246                 Size::from_bytes(data as u64)
247             }
248             Scalar::Ptr(ptr) => ptr.offset,
249         }
250     }
251
252     #[inline]
253     pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
254         match self {
255             Scalar::Raw { data, size } => {
256                 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
257                 data == 0
258             },
259             Scalar::Ptr(_) => false,
260         }
261     }
262
263     #[inline]
264     pub fn from_bool(b: bool) -> Self {
265         Scalar::Raw { data: b as u128, size: 1 }
266     }
267
268     #[inline]
269     pub fn from_char(c: char) -> Self {
270         Scalar::Raw { data: c as u128, size: 4 }
271     }
272
273     #[inline]
274     pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
275         let i = i.into();
276         assert_eq!(
277             truncate(i, size), i,
278             "Unsigned value {:#x} does not fit in {} bits", i, size.bits()
279         );
280         Scalar::Raw { data: i, size: size.bytes() as u8 }
281     }
282
283     #[inline]
284     pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
285         let i = i.into();
286         // `into` performed sign extension, we have to truncate
287         let truncated = truncate(i as u128, size);
288         assert_eq!(
289             sign_extend(truncated, size) as i128, i,
290             "Signed value {:#x} does not fit in {} bits", i, size.bits()
291         );
292         Scalar::Raw { data: truncated, size: size.bytes() as u8 }
293     }
294
295     #[inline]
296     pub fn from_f32(f: f32) -> Self {
297         Scalar::Raw { data: f.to_bits() as u128, size: 4 }
298     }
299
300     #[inline]
301     pub fn from_f64(f: f64) -> Self {
302         Scalar::Raw { data: f.to_bits() as u128, size: 8 }
303     }
304
305     #[inline]
306     pub fn to_bits_or_ptr(
307         self,
308         target_size: Size,
309         cx: &impl HasDataLayout,
310     ) -> Result<u128, Pointer<Tag>> {
311         match self {
312             Scalar::Raw { data, size } => {
313                 assert_eq!(target_size.bytes(), size as u64);
314                 assert_ne!(size, 0, "you should never look at the bits of a ZST");
315                 Scalar::check_data(data, size);
316                 Ok(data)
317             }
318             Scalar::Ptr(ptr) => {
319                 assert_eq!(target_size, cx.data_layout().pointer_size);
320                 Err(ptr)
321             }
322         }
323     }
324
325     #[inline]
326     pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
327         match self {
328             Scalar::Raw { data, size } => {
329                 assert_eq!(target_size.bytes(), size as u64);
330                 assert_ne!(size, 0, "you should never look at the bits of a ZST");
331                 Scalar::check_data(data, size);
332                 Ok(data)
333             }
334             Scalar::Ptr(_) => err!(ReadPointerAsBytes),
335         }
336     }
337
338     #[inline]
339     pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
340         match self {
341             Scalar::Raw { data: 0, .. } => err!(InvalidNullPointerUsage),
342             Scalar::Raw { .. } => err!(ReadBytesAsPointer),
343             Scalar::Ptr(p) => Ok(p),
344         }
345     }
346
347     #[inline]
348     pub fn is_bits(self) -> bool {
349         match self {
350             Scalar::Raw { .. } => true,
351             _ => false,
352         }
353     }
354
355     #[inline]
356     pub fn is_ptr(self) -> bool {
357         match self {
358             Scalar::Ptr(_) => true,
359             _ => false,
360         }
361     }
362
363     pub fn to_bool(self) -> EvalResult<'tcx, bool> {
364         match self {
365             Scalar::Raw { data: 0, size: 1 } => Ok(false),
366             Scalar::Raw { data: 1, size: 1 } => Ok(true),
367             _ => err!(InvalidBool),
368         }
369     }
370
371     pub fn to_char(self) -> EvalResult<'tcx, char> {
372         let val = self.to_u32()?;
373         match ::std::char::from_u32(val) {
374             Some(c) => Ok(c),
375             None => err!(InvalidChar(val as u128)),
376         }
377     }
378
379     pub fn to_u8(self) -> EvalResult<'static, u8> {
380         let sz = Size::from_bits(8);
381         let b = self.to_bits(sz)?;
382         Ok(b as u8)
383     }
384
385     pub fn to_u32(self) -> EvalResult<'static, u32> {
386         let sz = Size::from_bits(32);
387         let b = self.to_bits(sz)?;
388         Ok(b as u32)
389     }
390
391     pub fn to_u64(self) -> EvalResult<'static, u64> {
392         let sz = Size::from_bits(64);
393         let b = self.to_bits(sz)?;
394         Ok(b as u64)
395     }
396
397     pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'static, u64> {
398         let b = self.to_bits(cx.data_layout().pointer_size)?;
399         Ok(b as u64)
400     }
401
402     pub fn to_i8(self) -> EvalResult<'static, i8> {
403         let sz = Size::from_bits(8);
404         let b = self.to_bits(sz)?;
405         let b = sign_extend(b, sz) as i128;
406         Ok(b as i8)
407     }
408
409     pub fn to_i32(self) -> EvalResult<'static, i32> {
410         let sz = Size::from_bits(32);
411         let b = self.to_bits(sz)?;
412         let b = sign_extend(b, sz) as i128;
413         Ok(b as i32)
414     }
415
416     pub fn to_i64(self) -> EvalResult<'static, i64> {
417         let sz = Size::from_bits(64);
418         let b = self.to_bits(sz)?;
419         let b = sign_extend(b, sz) as i128;
420         Ok(b as i64)
421     }
422
423     pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'static, i64> {
424         let sz = cx.data_layout().pointer_size;
425         let b = self.to_bits(sz)?;
426         let b = sign_extend(b, sz) as i128;
427         Ok(b as i64)
428     }
429
430     #[inline]
431     pub fn to_f32(self) -> EvalResult<'static, f32> {
432         Ok(f32::from_bits(self.to_u32()?))
433     }
434
435     #[inline]
436     pub fn to_f64(self) -> EvalResult<'static, f64> {
437         Ok(f64::from_bits(self.to_u64()?))
438     }
439 }
440
441 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
442     #[inline(always)]
443     fn from(ptr: Pointer<Tag>) -> Self {
444         Scalar::Ptr(ptr)
445     }
446 }
447
448 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
449 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
450     Scalar(Scalar<Tag, Id>),
451     Undef,
452 }
453
454 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
455     #[inline(always)]
456     fn from(s: Scalar<Tag>) -> Self {
457         ScalarMaybeUndef::Scalar(s)
458     }
459 }
460
461 impl<Tag: fmt::Debug, Id: fmt::Debug> fmt::Debug for ScalarMaybeUndef<Tag, Id> {
462     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463         match self {
464             ScalarMaybeUndef::Undef => write!(f, "Undef"),
465             ScalarMaybeUndef::Scalar(s) => write!(f, "{:?}", s),
466         }
467     }
468 }
469
470 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
471     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472         match self {
473             ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
474             ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
475         }
476     }
477 }
478
479 impl<'tcx> ScalarMaybeUndef<()> {
480     #[inline]
481     pub fn with_tag<Tag>(self, new_tag: Tag) -> ScalarMaybeUndef<Tag> {
482         match self {
483             ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.with_tag(new_tag)),
484             ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
485         }
486     }
487
488     #[inline(always)]
489     pub fn with_default_tag<Tag>(self) -> ScalarMaybeUndef<Tag>
490         where Tag: Default
491     {
492         self.with_tag(Tag::default())
493     }
494 }
495
496 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
497     #[inline]
498     pub fn erase_tag(self) -> ScalarMaybeUndef
499     {
500         match self {
501             ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
502             ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
503         }
504     }
505
506     #[inline]
507     pub fn not_undef(self) -> EvalResult<'static, Scalar<Tag>> {
508         match self {
509             ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
510             ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
511         }
512     }
513
514     #[inline(always)]
515     pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
516         self.not_undef()?.to_ptr()
517     }
518
519     #[inline(always)]
520     pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
521         self.not_undef()?.to_bits(target_size)
522     }
523
524     #[inline(always)]
525     pub fn to_bool(self) -> EvalResult<'tcx, bool> {
526         self.not_undef()?.to_bool()
527     }
528
529     #[inline(always)]
530     pub fn to_char(self) -> EvalResult<'tcx, char> {
531         self.not_undef()?.to_char()
532     }
533
534     #[inline(always)]
535     pub fn to_f32(self) -> EvalResult<'tcx, f32> {
536         self.not_undef()?.to_f32()
537     }
538
539     #[inline(always)]
540     pub fn to_f64(self) -> EvalResult<'tcx, f64> {
541         self.not_undef()?.to_f64()
542     }
543
544     #[inline(always)]
545     pub fn to_u8(self) -> EvalResult<'tcx, u8> {
546         self.not_undef()?.to_u8()
547     }
548
549     #[inline(always)]
550     pub fn to_u32(self) -> EvalResult<'tcx, u32> {
551         self.not_undef()?.to_u32()
552     }
553
554     #[inline(always)]
555     pub fn to_u64(self) -> EvalResult<'tcx, u64> {
556         self.not_undef()?.to_u64()
557     }
558
559     #[inline(always)]
560     pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
561         self.not_undef()?.to_usize(cx)
562     }
563
564     #[inline(always)]
565     pub fn to_i8(self) -> EvalResult<'tcx, i8> {
566         self.not_undef()?.to_i8()
567     }
568
569     #[inline(always)]
570     pub fn to_i32(self) -> EvalResult<'tcx, i32> {
571         self.not_undef()?.to_i32()
572     }
573
574     #[inline(always)]
575     pub fn to_i64(self) -> EvalResult<'tcx, i64> {
576         self.not_undef()?.to_i64()
577     }
578
579     #[inline(always)]
580     pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, i64> {
581         self.not_undef()?.to_isize(cx)
582     }
583 }
584
585 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {
586     Scalar(v),
587     Undef
588 });