1 // Copyright 2014 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.
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.
11 use graphviz::IntoCow;
12 use middle::const_eval::ConstVal;
13 use rustc_const_eval::{ConstUsize, ConstInt};
14 use middle::def_id::DefId;
15 use middle::subst::Substs;
16 use middle::ty::{self, AdtDef, ClosureSubsts, FnOutput, Region, Ty};
18 use rustc_back::slice;
19 use rustc_front::hir::InlineAsm;
21 use std::borrow::{Cow};
22 use std::fmt::{self, Debug, Formatter, Write};
24 use std::ops::{Index, IndexMut};
25 use syntax::ast::{self, Name};
26 use syntax::codemap::Span;
28 /// Lowered representation of a single function.
29 #[derive(Clone, RustcEncodable, RustcDecodable)]
30 pub struct Mir<'tcx> {
31 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
32 /// that indexes into this vector.
33 pub basic_blocks: Vec<BasicBlockData<'tcx>>,
35 /// List of lexical scopes; these are referenced by statements and
36 /// used (eventually) for debuginfo. Indexed by a `ScopeId`.
37 pub scopes: ScopeDataVec,
39 /// Return type of the function.
40 pub return_ty: FnOutput<'tcx>,
42 /// Variables: these are stack slots corresponding to user variables. They may be
43 /// assigned many times.
44 pub var_decls: Vec<VarDecl<'tcx>>,
46 /// Args: these are stack slots corresponding to the input arguments.
47 pub arg_decls: Vec<ArgDecl<'tcx>>,
49 /// Temp declarations: stack slots that for temporaries created by
50 /// the compiler. These are assigned once, but they are not SSA
51 /// values in that it is possible to borrow them and mutate them
52 /// through the resulting reference.
53 pub temp_decls: Vec<TempDecl<'tcx>>,
55 /// A span representing this MIR, for error reporting
59 /// where execution begins
60 pub const START_BLOCK: BasicBlock = BasicBlock(0);
62 /// where execution ends, on normal return
63 pub const END_BLOCK: BasicBlock = BasicBlock(1);
65 impl<'tcx> Mir<'tcx> {
66 pub fn all_basic_blocks(&self) -> Vec<BasicBlock> {
67 (0..self.basic_blocks.len())
68 .map(|i| BasicBlock::new(i))
72 pub fn basic_block_data(&self, bb: BasicBlock) -> &BasicBlockData<'tcx> {
73 &self.basic_blocks[bb.index()]
76 pub fn basic_block_data_mut(&mut self, bb: BasicBlock) -> &mut BasicBlockData<'tcx> {
77 &mut self.basic_blocks[bb.index()]
81 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
82 type Output = BasicBlockData<'tcx>;
85 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
86 self.basic_block_data(index)
90 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
92 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
93 self.basic_block_data_mut(index)
97 ///////////////////////////////////////////////////////////////////////////
98 // Mutability and borrow kinds
100 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
101 pub enum Mutability {
106 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
107 pub enum BorrowKind {
108 /// Data must be immutable and is aliasable.
111 /// Data must be immutable but not aliasable. This kind of borrow
112 /// cannot currently be expressed by the user and is used only in
113 /// implicit closure bindings. It is needed when you the closure
114 /// is borrowing or mutating a mutable referent, e.g.:
116 /// let x: &mut isize = ...;
117 /// let y = || *x += 5;
119 /// If we were to try to translate this closure into a more explicit
120 /// form, we'd encounter an error with the code as written:
122 /// struct Env { x: & &mut isize }
123 /// let x: &mut isize = ...;
124 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
125 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
127 /// This is then illegal because you cannot mutate a `&mut` found
128 /// in an aliasable location. To solve, you'd have to translate with
129 /// an `&mut` borrow:
131 /// struct Env { x: & &mut isize }
132 /// let x: &mut isize = ...;
133 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
134 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
136 /// Now the assignment to `**env.x` is legal, but creating a
137 /// mutable pointer to `x` is not because `x` is not mutable. We
138 /// could fix this by declaring `x` as `let mut x`. This is ok in
139 /// user code, if awkward, but extra weird for closures, since the
140 /// borrow is hidden.
142 /// So we introduce a "unique imm" borrow -- the referent is
143 /// immutable, but not aliasable. This solves the problem. For
144 /// simplicity, we don't give users the way to express this
145 /// borrow, it's just used when translating closures.
148 /// Data is mutable and not aliasable.
152 ///////////////////////////////////////////////////////////////////////////
153 // Variables and temps
155 /// A "variable" is a binding declared by the user as part of the fn
156 /// decl, a let, etc.
157 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
158 pub struct VarDecl<'tcx> {
159 /// `let mut x` vs `let x`
160 pub mutability: Mutability,
162 /// name that user gave the variable; not that, internally,
163 /// mir references variables by index
166 /// type inferred for this variable (`let x: ty = ...`)
169 /// scope in which variable was declared
172 /// span where variable was declared
176 /// A "temp" is a temporary that we place on the stack. They are
177 /// anonymous, always mutable, and have only a type.
178 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
179 pub struct TempDecl<'tcx> {
183 /// A "arg" is one of the function's formal arguments. These are
184 /// anonymous and distinct from the bindings that the user declares.
186 /// For example, in this function:
189 /// fn foo((x, y): (i32, u32)) { ... }
192 /// there is only one argument, of type `(i32, u32)`, but two bindings
194 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
195 pub struct ArgDecl<'tcx> {
198 /// If true, this argument is a tuple after monomorphization,
199 /// and has to be collected from multiple actual arguments.
203 ///////////////////////////////////////////////////////////////////////////
206 /// The index of a particular basic block. The index is into the `basic_blocks`
207 /// list of the `Mir`.
209 /// (We use a `u32` internally just to save memory.)
210 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
211 pub struct BasicBlock(u32);
214 pub fn new(index: usize) -> BasicBlock {
215 assert!(index < (u32::MAX as usize));
216 BasicBlock(index as u32)
219 /// Extract the index.
220 pub fn index(self) -> usize {
225 impl Debug for BasicBlock {
226 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
227 write!(fmt, "bb{}", self.0)
231 ///////////////////////////////////////////////////////////////////////////
232 // BasicBlockData and Terminator
234 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
235 pub struct BasicBlockData<'tcx> {
236 pub statements: Vec<Statement<'tcx>>,
237 pub terminator: Option<Terminator<'tcx>>,
238 pub is_cleanup: bool,
241 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
242 pub struct Terminator<'tcx> {
245 pub kind: TerminatorKind<'tcx>
248 #[derive(Clone, RustcEncodable, RustcDecodable)]
249 pub enum TerminatorKind<'tcx> {
250 /// block should have one successor in the graph; we jump there
255 /// jump to branch 0 if this lvalue evaluates to true
258 targets: (BasicBlock, BasicBlock),
261 /// lvalue evaluates to some enum; jump depending on the branch
264 adt_def: AdtDef<'tcx>,
265 targets: Vec<BasicBlock>,
268 /// operand evaluates to an integer; jump depending on its value
269 /// to one of the targets, and otherwise fallback to `otherwise`
271 /// discriminant value being tested
274 /// type of value being tested
277 /// Possible values. The locations to branch to in each case
278 /// are found in the corresponding indices from the `targets` vector.
279 values: Vec<ConstVal>,
281 /// Possible branch sites. The length of this vector should be
282 /// equal to the length of the `values` vector plus 1 -- the
283 /// extra item is the block to branch to if none of the values
285 targets: Vec<BasicBlock>,
288 /// Indicates that the landing pad is finished and unwinding should
289 /// continue. Emitted by build::scope::diverge_cleanup.
292 /// Indicates a normal return. The ReturnPointer lvalue should
293 /// have been filled in by now. This should only occur in the
301 unwind: Option<BasicBlock>
304 /// Block ends with a call of a converging function
306 /// The function that’s being called
308 /// Arguments the function is called with
309 args: Vec<Operand<'tcx>>,
310 /// Destination for the return value. If some, the call is converging.
311 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
312 /// Cleanups to be done if the call unwinds.
313 cleanup: Option<BasicBlock>
317 impl<'tcx> Terminator<'tcx> {
318 pub fn successors(&self) -> Cow<[BasicBlock]> {
319 self.kind.successors()
322 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
323 self.kind.successors_mut()
327 impl<'tcx> TerminatorKind<'tcx> {
328 pub fn successors(&self) -> Cow<[BasicBlock]> {
329 use self::TerminatorKind::*;
331 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
332 If { targets: (b1, b2), .. } => vec![b1, b2].into_cow(),
333 Switch { targets: ref b, .. } => b[..].into_cow(),
334 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
335 Resume => (&[]).into_cow(),
336 Return => (&[]).into_cow(),
337 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
338 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
339 slice::ref_slice(t).into_cow(),
340 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
341 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
342 Drop { target, unwind: Some(unwind), .. } => vec![target, unwind].into_cow(),
343 Drop { ref target, .. } => slice::ref_slice(target).into_cow(),
347 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
348 // `Vec<&mut BasicBlock>` would look like in the first place.
349 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
350 use self::TerminatorKind::*;
352 Goto { target: ref mut b } => vec![b],
353 If { targets: (ref mut b1, ref mut b2), .. } => vec![b1, b2],
354 Switch { targets: ref mut b, .. } => b.iter_mut().collect(),
355 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
356 Resume => Vec::new(),
357 Return => Vec::new(),
358 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
359 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
360 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
361 Call { destination: None, cleanup: None, .. } => vec![],
362 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
363 Drop { ref mut target, .. } => vec![target]
368 impl<'tcx> BasicBlockData<'tcx> {
369 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
372 terminator: terminator,
377 /// Accessor for terminator.
379 /// Terminator may not be None after construction of the basic block is complete. This accessor
380 /// provides a convenience way to reach the terminator.
381 pub fn terminator(&self) -> &Terminator<'tcx> {
382 self.terminator.as_ref().expect("invalid terminator state")
385 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
386 self.terminator.as_mut().expect("invalid terminator state")
390 impl<'tcx> Debug for TerminatorKind<'tcx> {
391 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
393 let successors = self.successors();
394 let labels = self.fmt_successor_labels();
395 assert_eq!(successors.len(), labels.len());
397 match successors.len() {
400 1 => write!(fmt, " -> {:?}", successors[0]),
403 write!(fmt, " -> [")?;
404 for (i, target) in successors.iter().enumerate() {
408 write!(fmt, "{}: {:?}", labels[i], target)?;
417 impl<'tcx> TerminatorKind<'tcx> {
418 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
419 /// successor basic block, if any. The only information not inlcuded is the list of possible
420 /// successors, which may be rendered differently between the text and the graphviz format.
421 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
422 use self::TerminatorKind::*;
424 Goto { .. } => write!(fmt, "goto"),
425 If { cond: ref lv, .. } => write!(fmt, "if({:?})", lv),
426 Switch { discr: ref lv, .. } => write!(fmt, "switch({:?})", lv),
427 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
428 Return => write!(fmt, "return"),
429 Resume => write!(fmt, "resume"),
430 Drop { ref value, .. } => write!(fmt, "drop({:?})", value),
431 Call { ref func, ref args, ref destination, .. } => {
432 if let Some((ref destination, _)) = *destination {
433 write!(fmt, "{:?} = ", destination)?;
435 write!(fmt, "{:?}(", func)?;
436 for (index, arg) in args.iter().enumerate() {
440 write!(fmt, "{:?}", arg)?;
447 /// Return the list of labels for the edges to the successor basic blocks.
448 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
449 use self::TerminatorKind::*;
451 Return | Resume => vec![],
452 Goto { .. } => vec!["".into()],
453 If { .. } => vec!["true".into(), "false".into()],
454 Switch { ref adt_def, .. } => {
457 .map(|variant| variant.name.to_string().into())
460 SwitchInt { ref values, .. } => {
463 let mut buf = String::new();
464 fmt_const_val(&mut buf, const_val).unwrap();
467 .chain(iter::once(String::from("otherwise").into()))
470 Call { destination: Some(_), cleanup: Some(_), .. } =>
471 vec!["return".into_cow(), "unwind".into_cow()],
472 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
473 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
474 Call { destination: None, cleanup: None, .. } => vec![],
475 Drop { unwind: None, .. } => vec!["return".into_cow()],
476 Drop { .. } => vec!["return".into_cow(), "unwind".into_cow()],
482 ///////////////////////////////////////////////////////////////////////////
485 #[derive(Clone, RustcEncodable, RustcDecodable)]
486 pub struct Statement<'tcx> {
489 pub kind: StatementKind<'tcx>,
492 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
493 pub enum StatementKind<'tcx> {
494 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
497 impl<'tcx> Debug for Statement<'tcx> {
498 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
499 use self::StatementKind::*;
501 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv)
506 ///////////////////////////////////////////////////////////////////////////
509 /// A path to a value; something that can be evaluated without
510 /// changing or disturbing program state.
511 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
512 pub enum Lvalue<'tcx> {
513 /// local variable declared by the user
516 /// temporary introduced during lowering into MIR
519 /// formal parameter of the function; note that these are NOT the
520 /// bindings that the user declares, which are vars
523 /// static or static mut variable
526 /// the return pointer of the fn
529 /// projection out of an lvalue (access a field, deref a pointer, etc)
530 Projection(Box<LvalueProjection<'tcx>>),
533 /// The `Projection` data structure defines things of the form `B.x`
534 /// or `*B` or `B[index]`. Note that it is parameterized because it is
535 /// shared between `Constant` and `Lvalue`. See the aliases
536 /// `LvalueProjection` etc below.
537 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
538 pub struct Projection<'tcx, B, V> {
540 pub elem: ProjectionElem<'tcx, V>,
543 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
544 pub enum ProjectionElem<'tcx, V> {
546 Field(Field, Ty<'tcx>),
549 /// These indices are generated by slice patterns. Easiest to explain
553 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
554 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
555 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
556 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
559 /// index or -index (in Python terms), depending on from_end
561 /// thing being indexed must be at least this long
563 /// counting backwards from end?
567 /// "Downcast" to a variant of an ADT. Currently, we only introduce
568 /// this for ADTs with more than one variant. It may be better to
569 /// just introduce it always, or always for enums.
570 Downcast(AdtDef<'tcx>, usize),
573 /// Alias for projections as they appear in lvalues, where the base is an lvalue
574 /// and the index is an operand.
575 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
577 /// Alias for projections as they appear in lvalues, where the base is an lvalue
578 /// and the index is an operand.
579 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
581 /// Index into the list of fields found in a `VariantDef`
582 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
583 pub struct Field(u32);
586 pub fn new(value: usize) -> Field {
587 assert!(value < (u32::MAX) as usize);
591 pub fn index(self) -> usize {
596 impl<'tcx> Lvalue<'tcx> {
597 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
598 self.elem(ProjectionElem::Field(f, ty))
601 pub fn deref(self) -> Lvalue<'tcx> {
602 self.elem(ProjectionElem::Deref)
605 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
606 self.elem(ProjectionElem::Index(index))
609 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
610 Lvalue::Projection(Box::new(LvalueProjection {
617 impl<'tcx> Debug for Lvalue<'tcx> {
618 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
623 write!(fmt, "var{:?}", id),
625 write!(fmt, "arg{:?}", id),
627 write!(fmt, "tmp{:?}", id),
629 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
631 write!(fmt, "return"),
632 Projection(ref data) =>
634 ProjectionElem::Downcast(ref adt_def, index) =>
635 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
636 ProjectionElem::Deref =>
637 write!(fmt, "(*{:?})", data.base),
638 ProjectionElem::Field(field, ty) =>
639 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
640 ProjectionElem::Index(ref index) =>
641 write!(fmt, "{:?}[{:?}]", data.base, index),
642 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
643 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
644 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
645 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
651 ///////////////////////////////////////////////////////////////////////////
654 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
655 pub struct ScopeDataVec {
656 pub vec: Vec<ScopeData>
660 pub fn new() -> Self {
661 ScopeDataVec { vec: Vec::new() }
665 impl Index<ScopeId> for ScopeDataVec {
666 type Output = ScopeData;
669 fn index(&self, index: ScopeId) -> &ScopeData {
670 &self.vec[index.index()]
674 impl IndexMut<ScopeId> for ScopeDataVec {
676 fn index_mut(&mut self, index: ScopeId) -> &mut ScopeData {
677 &mut self.vec[index.index()]
681 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
682 pub struct ScopeId(u32);
685 pub fn new(index: usize) -> ScopeId {
686 assert!(index < (u32::MAX as usize));
687 ScopeId(index as u32)
690 pub fn index(self) -> usize {
695 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
696 pub struct ScopeData {
697 pub parent_scope: Option<ScopeId>,
700 ///////////////////////////////////////////////////////////////////////////
703 /// These are values that can appear inside an rvalue (or an index
704 /// lvalue). They are intentionally limited to prevent rvalues from
705 /// being nested in one another.
706 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
707 pub enum Operand<'tcx> {
708 Consume(Lvalue<'tcx>),
709 Constant(Constant<'tcx>),
712 impl<'tcx> Debug for Operand<'tcx> {
713 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
714 use self::Operand::*;
716 Constant(ref a) => write!(fmt, "{:?}", a),
717 Consume(ref lv) => write!(fmt, "{:?}", lv),
722 ///////////////////////////////////////////////////////////////////////////
725 #[derive(Clone, RustcEncodable, RustcDecodable)]
726 pub enum Rvalue<'tcx> {
727 /// x (either a move or copy, depending on type of x)
731 Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
734 Ref(Region, BorrowKind, Lvalue<'tcx>),
736 /// length of a [X] or [X;n] value
739 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
741 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
743 UnaryOp(UnOp, Operand<'tcx>),
745 /// Creates an *uninitialized* Box
748 /// Create an aggregate value, like a tuple or struct. This is
749 /// only needed because we want to distinguish `dest = Foo { x:
750 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
751 /// that `Foo` has a destructor. These rvalues can be optimized
752 /// away after type-checking and before lowering.
753 Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
755 /// Generates a slice of the form `&input[from_start..L-from_end]`
756 /// where `L` is the length of the slice. This is only created by
757 /// slice pattern matching, so e.g. a pattern of the form `[x, y,
758 /// .., z]` might create a slice with `from_start=2` and
768 outputs: Vec<Lvalue<'tcx>>,
769 inputs: Vec<Operand<'tcx>>
773 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
777 /// Convert unique, zero-sized type for a fn to fn()
780 /// Convert safe fn() to unsafe fn()
783 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
784 /// trans must figure out the details once full monomorphization
785 /// is known. For example, this could be used to cast from a
786 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
787 /// (presuming `T: Trait`).
791 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
792 pub enum AggregateKind<'tcx> {
795 Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>),
796 Closure(DefId, &'tcx ClosureSubsts<'tcx>),
799 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
801 /// The `+` operator (addition)
803 /// The `-` operator (subtraction)
805 /// The `*` operator (multiplication)
807 /// The `/` operator (division)
809 /// The `%` operator (modulus)
811 /// The `^` operator (bitwise xor)
813 /// The `&` operator (bitwise and)
815 /// The `|` operator (bitwise or)
817 /// The `<<` operator (shift left)
819 /// The `>>` operator (shift right)
821 /// The `==` operator (equality)
823 /// The `<` operator (less than)
825 /// The `<=` operator (less than or equal to)
827 /// The `!=` operator (not equal to)
829 /// The `>=` operator (greater than or equal to)
831 /// The `>` operator (greater than)
835 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
837 /// The `!` operator for logical inversion
839 /// The `-` operator for negation
843 impl<'tcx> Debug for Rvalue<'tcx> {
844 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
848 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
849 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
850 Len(ref a) => write!(fmt, "Len({:?})", a),
851 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
852 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
853 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
854 Box(ref t) => write!(fmt, "Box({:?})", t),
855 InlineAsm { ref asm, ref outputs, ref inputs } => {
856 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
858 Slice { ref input, from_start, from_end } =>
859 write!(fmt, "{:?}[{:?}..-{:?}]", input, from_start, from_end),
861 Ref(_, borrow_kind, ref lv) => {
862 let kind_str = match borrow_kind {
863 BorrowKind::Shared => "",
864 BorrowKind::Mut | BorrowKind::Unique => "mut ",
866 write!(fmt, "&{}{:?}", kind_str, lv)
869 Aggregate(ref kind, ref lvs) => {
870 use self::AggregateKind::*;
872 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
873 let mut tuple_fmt = fmt.debug_tuple("");
881 Vec => write!(fmt, "{:?}", lvs),
885 0 => write!(fmt, "()"),
886 1 => write!(fmt, "({:?},)", lvs[0]),
887 _ => fmt_tuple(fmt, lvs),
891 Adt(adt_def, variant, substs) => {
892 let variant_def = &adt_def.variants[variant];
894 ppaux::parameterized(fmt, substs, variant_def.did,
895 ppaux::Ns::Value, &[],
897 tcx.lookup_item_type(variant_def.did).generics
900 match variant_def.kind() {
901 ty::VariantKind::Unit => Ok(()),
902 ty::VariantKind::Tuple => fmt_tuple(fmt, lvs),
903 ty::VariantKind::Struct => {
904 let mut struct_fmt = fmt.debug_struct("");
905 for (field, lv) in variant_def.fields.iter().zip(lvs) {
906 struct_fmt.field(&field.name.as_str(), lv);
913 Closure(def_id, _) => ty::tls::with(|tcx| {
914 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
915 let name = format!("[closure@{:?}]", tcx.map.span(node_id));
916 let mut struct_fmt = fmt.debug_struct(&name);
918 tcx.with_freevars(node_id, |freevars| {
919 for (freevar, lv) in freevars.iter().zip(lvs) {
920 let var_name = tcx.local_var_name_str(freevar.def.var_id());
921 struct_fmt.field(&var_name, lv);
927 write!(fmt, "[closure]")
936 ///////////////////////////////////////////////////////////////////////////
939 /// Two constants are equal if they are the same constant. Note that
940 /// this does not necessarily mean that they are "==" in Rust -- in
941 /// particular one must be wary of `NaN`!
943 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
944 pub struct Constant<'tcx> {
947 pub literal: Literal<'tcx>,
950 #[derive(Clone, RustcEncodable, RustcDecodable)]
951 pub struct TypedConstVal<'tcx> {
954 pub value: ConstUsize,
957 impl<'tcx> Debug for TypedConstVal<'tcx> {
958 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
959 write!(fmt, "const {}", ConstInt::Usize(self.value))
963 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
964 pub enum Literal<'tcx> {
967 substs: &'tcx Substs<'tcx>,
974 impl<'tcx> Debug for Constant<'tcx> {
975 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
976 write!(fmt, "{:?}", self.literal)
980 impl<'tcx> Debug for Literal<'tcx> {
981 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
982 use self::Literal::*;
984 Item { def_id, substs } => {
985 ppaux::parameterized(fmt, substs, def_id, ppaux::Ns::Value, &[],
986 |tcx| tcx.lookup_item_type(def_id).generics)
988 Value { ref value } => {
989 write!(fmt, "const ")?;
990 fmt_const_val(fmt, value)
996 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
997 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
998 use middle::const_eval::ConstVal::*;
1000 Float(f) => write!(fmt, "{:?}", f),
1001 Integral(n) => write!(fmt, "{}", n),
1002 Str(ref s) => write!(fmt, "{:?}", s),
1003 ByteStr(ref bytes) => {
1004 let escaped: String = bytes
1006 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1008 write!(fmt, "b\"{}\"", escaped)
1010 Bool(b) => write!(fmt, "{:?}", b),
1011 Function(def_id) => write!(fmt, "{}", item_path_str(def_id)),
1012 Struct(node_id) | Tuple(node_id) | Array(node_id, _) | Repeat(node_id, _) =>
1013 write!(fmt, "{}", node_to_string(node_id)),
1014 Char(c) => write!(fmt, "{:?}", c),
1015 Dummy => unreachable!(),
1019 fn node_to_string(node_id: ast::NodeId) -> String {
1020 ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1023 fn item_path_str(def_id: DefId) -> String {
1024 ty::tls::with(|tcx| tcx.item_path_str(def_id))