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 pub mutability: Mutability,
162 pub scope: ScopeId, // scope in which variable was declared
163 pub span: Span, // span where variable was declared
166 /// A "temp" is a temporary that we place on the stack. They are
167 /// anonymous, always mutable, and have only a type.
168 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
169 pub struct TempDecl<'tcx> {
173 /// A "arg" is one of the function's formal arguments. These are
174 /// anonymous and distinct from the bindings that the user declares.
176 /// For example, in this function:
179 /// fn foo((x, y): (i32, u32)) { ... }
182 /// there is only one argument, of type `(i32, u32)`, but two bindings
184 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
185 pub struct ArgDecl<'tcx> {
188 /// If true, this argument is a tuple after monomorphization,
189 /// and has to be collected from multiple actual arguments.
193 ///////////////////////////////////////////////////////////////////////////
196 /// The index of a particular basic block. The index is into the `basic_blocks`
197 /// list of the `Mir`.
199 /// (We use a `u32` internally just to save memory.)
200 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
201 pub struct BasicBlock(u32);
204 pub fn new(index: usize) -> BasicBlock {
205 assert!(index < (u32::MAX as usize));
206 BasicBlock(index as u32)
209 /// Extract the index.
210 pub fn index(self) -> usize {
215 impl Debug for BasicBlock {
216 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
217 write!(fmt, "bb{}", self.0)
221 ///////////////////////////////////////////////////////////////////////////
222 // BasicBlockData and Terminator
224 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
225 pub struct BasicBlockData<'tcx> {
226 pub statements: Vec<Statement<'tcx>>,
227 pub terminator: Option<Terminator<'tcx>>,
228 pub is_cleanup: bool,
231 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
232 pub struct Terminator<'tcx> {
235 pub kind: TerminatorKind<'tcx>
238 #[derive(Clone, RustcEncodable, RustcDecodable)]
239 pub enum TerminatorKind<'tcx> {
240 /// block should have one successor in the graph; we jump there
245 /// jump to branch 0 if this lvalue evaluates to true
248 targets: (BasicBlock, BasicBlock),
251 /// lvalue evaluates to some enum; jump depending on the branch
254 adt_def: AdtDef<'tcx>,
255 targets: Vec<BasicBlock>,
258 /// operand evaluates to an integer; jump depending on its value
259 /// to one of the targets, and otherwise fallback to `otherwise`
261 /// discriminant value being tested
264 /// type of value being tested
267 /// Possible values. The locations to branch to in each case
268 /// are found in the corresponding indices from the `targets` vector.
269 values: Vec<ConstVal>,
271 /// Possible branch sites. The length of this vector should be
272 /// equal to the length of the `values` vector plus 1 -- the
273 /// extra item is the block to branch to if none of the values
275 targets: Vec<BasicBlock>,
278 /// Indicates that the landing pad is finished and unwinding should
279 /// continue. Emitted by build::scope::diverge_cleanup.
282 /// Indicates a normal return. The ReturnPointer lvalue should
283 /// have been filled in by now. This should only occur in the
291 unwind: Option<BasicBlock>
294 /// Block ends with a call of a converging function
296 /// The function that’s being called
298 /// Arguments the function is called with
299 args: Vec<Operand<'tcx>>,
300 /// Destination for the return value. If some, the call is converging.
301 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
302 /// Cleanups to be done if the call unwinds.
303 cleanup: Option<BasicBlock>
307 impl<'tcx> Terminator<'tcx> {
308 pub fn successors(&self) -> Cow<[BasicBlock]> {
309 self.kind.successors()
312 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
313 self.kind.successors_mut()
317 impl<'tcx> TerminatorKind<'tcx> {
318 pub fn successors(&self) -> Cow<[BasicBlock]> {
319 use self::TerminatorKind::*;
321 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
322 If { targets: (b1, b2), .. } => vec![b1, b2].into_cow(),
323 Switch { targets: ref b, .. } => b[..].into_cow(),
324 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
325 Resume => (&[]).into_cow(),
326 Return => (&[]).into_cow(),
327 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
328 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
329 slice::ref_slice(t).into_cow(),
330 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
331 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
332 Drop { target, unwind: Some(unwind), .. } => vec![target, unwind].into_cow(),
333 Drop { ref target, .. } => slice::ref_slice(target).into_cow(),
337 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
338 // `Vec<&mut BasicBlock>` would look like in the first place.
339 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
340 use self::TerminatorKind::*;
342 Goto { target: ref mut b } => vec![b],
343 If { targets: (ref mut b1, ref mut b2), .. } => vec![b1, b2],
344 Switch { targets: ref mut b, .. } => b.iter_mut().collect(),
345 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
346 Resume => Vec::new(),
347 Return => Vec::new(),
348 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
349 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
350 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
351 Call { destination: None, cleanup: None, .. } => vec![],
352 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
353 Drop { ref mut target, .. } => vec![target]
358 impl<'tcx> BasicBlockData<'tcx> {
359 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
362 terminator: terminator,
367 /// Accessor for terminator.
369 /// Terminator may not be None after construction of the basic block is complete. This accessor
370 /// provides a convenience way to reach the terminator.
371 pub fn terminator(&self) -> &Terminator<'tcx> {
372 self.terminator.as_ref().expect("invalid terminator state")
375 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
376 self.terminator.as_mut().expect("invalid terminator state")
380 impl<'tcx> Debug for TerminatorKind<'tcx> {
381 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
383 let successors = self.successors();
384 let labels = self.fmt_successor_labels();
385 assert_eq!(successors.len(), labels.len());
387 match successors.len() {
390 1 => write!(fmt, " -> {:?}", successors[0]),
393 write!(fmt, " -> [")?;
394 for (i, target) in successors.iter().enumerate() {
398 write!(fmt, "{}: {:?}", labels[i], target)?;
407 impl<'tcx> TerminatorKind<'tcx> {
408 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
409 /// successor basic block, if any. The only information not inlcuded is the list of possible
410 /// successors, which may be rendered differently between the text and the graphviz format.
411 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
412 use self::TerminatorKind::*;
414 Goto { .. } => write!(fmt, "goto"),
415 If { cond: ref lv, .. } => write!(fmt, "if({:?})", lv),
416 Switch { discr: ref lv, .. } => write!(fmt, "switch({:?})", lv),
417 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
418 Return => write!(fmt, "return"),
419 Resume => write!(fmt, "resume"),
420 Drop { ref value, .. } => write!(fmt, "drop({:?})", value),
421 Call { ref func, ref args, ref destination, .. } => {
422 if let Some((ref destination, _)) = *destination {
423 write!(fmt, "{:?} = ", destination)?;
425 write!(fmt, "{:?}(", func)?;
426 for (index, arg) in args.iter().enumerate() {
430 write!(fmt, "{:?}", arg)?;
437 /// Return the list of labels for the edges to the successor basic blocks.
438 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
439 use self::TerminatorKind::*;
441 Return | Resume => vec![],
442 Goto { .. } => vec!["".into()],
443 If { .. } => vec!["true".into(), "false".into()],
444 Switch { ref adt_def, .. } => {
447 .map(|variant| variant.name.to_string().into())
450 SwitchInt { ref values, .. } => {
453 let mut buf = String::new();
454 fmt_const_val(&mut buf, const_val).unwrap();
457 .chain(iter::once(String::from("otherwise").into()))
460 Call { destination: Some(_), cleanup: Some(_), .. } =>
461 vec!["return".into_cow(), "unwind".into_cow()],
462 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
463 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
464 Call { destination: None, cleanup: None, .. } => vec![],
465 Drop { unwind: None, .. } => vec!["return".into_cow()],
466 Drop { .. } => vec!["return".into_cow(), "unwind".into_cow()],
472 ///////////////////////////////////////////////////////////////////////////
475 #[derive(Clone, RustcEncodable, RustcDecodable)]
476 pub struct Statement<'tcx> {
479 pub kind: StatementKind<'tcx>,
482 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
483 pub enum StatementKind<'tcx> {
484 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
487 impl<'tcx> Debug for Statement<'tcx> {
488 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
489 use self::StatementKind::*;
491 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv)
496 ///////////////////////////////////////////////////////////////////////////
499 /// A path to a value; something that can be evaluated without
500 /// changing or disturbing program state.
501 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
502 pub enum Lvalue<'tcx> {
503 /// local variable declared by the user
506 /// temporary introduced during lowering into MIR
509 /// formal parameter of the function; note that these are NOT the
510 /// bindings that the user declares, which are vars
513 /// static or static mut variable
516 /// the return pointer of the fn
519 /// projection out of an lvalue (access a field, deref a pointer, etc)
520 Projection(Box<LvalueProjection<'tcx>>),
523 /// The `Projection` data structure defines things of the form `B.x`
524 /// or `*B` or `B[index]`. Note that it is parameterized because it is
525 /// shared between `Constant` and `Lvalue`. See the aliases
526 /// `LvalueProjection` etc below.
527 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
528 pub struct Projection<'tcx, B, V> {
530 pub elem: ProjectionElem<'tcx, V>,
533 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
534 pub enum ProjectionElem<'tcx, V> {
536 Field(Field, Ty<'tcx>),
539 /// These indices are generated by slice patterns. Easiest to explain
543 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
544 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
545 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
546 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
549 /// index or -index (in Python terms), depending on from_end
551 /// thing being indexed must be at least this long
553 /// counting backwards from end?
557 /// "Downcast" to a variant of an ADT. Currently, we only introduce
558 /// this for ADTs with more than one variant. It may be better to
559 /// just introduce it always, or always for enums.
560 Downcast(AdtDef<'tcx>, usize),
563 /// Alias for projections as they appear in lvalues, where the base is an lvalue
564 /// and the index is an operand.
565 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
567 /// Alias for projections as they appear in lvalues, where the base is an lvalue
568 /// and the index is an operand.
569 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
571 /// Index into the list of fields found in a `VariantDef`
572 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
573 pub struct Field(u32);
576 pub fn new(value: usize) -> Field {
577 assert!(value < (u32::MAX) as usize);
581 pub fn index(self) -> usize {
586 impl<'tcx> Lvalue<'tcx> {
587 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
588 self.elem(ProjectionElem::Field(f, ty))
591 pub fn deref(self) -> Lvalue<'tcx> {
592 self.elem(ProjectionElem::Deref)
595 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
596 self.elem(ProjectionElem::Index(index))
599 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
600 Lvalue::Projection(Box::new(LvalueProjection {
607 impl<'tcx> Debug for Lvalue<'tcx> {
608 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
613 write!(fmt, "var{:?}", id),
615 write!(fmt, "arg{:?}", id),
617 write!(fmt, "tmp{:?}", id),
619 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
621 write!(fmt, "return"),
622 Projection(ref data) =>
624 ProjectionElem::Downcast(ref adt_def, index) =>
625 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
626 ProjectionElem::Deref =>
627 write!(fmt, "(*{:?})", data.base),
628 ProjectionElem::Field(field, ty) =>
629 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
630 ProjectionElem::Index(ref index) =>
631 write!(fmt, "{:?}[{:?}]", data.base, index),
632 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
633 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
634 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
635 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
641 ///////////////////////////////////////////////////////////////////////////
644 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
645 pub struct ScopeDataVec {
646 pub vec: Vec<ScopeData>
650 pub fn new() -> Self {
651 ScopeDataVec { vec: Vec::new() }
655 impl Index<ScopeId> for ScopeDataVec {
656 type Output = ScopeData;
659 fn index(&self, index: ScopeId) -> &ScopeData {
660 &self.vec[index.index()]
664 impl IndexMut<ScopeId> for ScopeDataVec {
666 fn index_mut(&mut self, index: ScopeId) -> &mut ScopeData {
667 &mut self.vec[index.index()]
671 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
672 pub struct ScopeId(u32);
675 pub fn new(index: usize) -> ScopeId {
676 assert!(index < (u32::MAX as usize));
677 ScopeId(index as u32)
680 pub fn index(self) -> usize {
685 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
686 pub struct ScopeData {
687 pub parent_scope: Option<ScopeId>,
690 ///////////////////////////////////////////////////////////////////////////
693 /// These are values that can appear inside an rvalue (or an index
694 /// lvalue). They are intentionally limited to prevent rvalues from
695 /// being nested in one another.
696 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
697 pub enum Operand<'tcx> {
698 Consume(Lvalue<'tcx>),
699 Constant(Constant<'tcx>),
702 impl<'tcx> Debug for Operand<'tcx> {
703 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
704 use self::Operand::*;
706 Constant(ref a) => write!(fmt, "{:?}", a),
707 Consume(ref lv) => write!(fmt, "{:?}", lv),
712 ///////////////////////////////////////////////////////////////////////////
715 #[derive(Clone, RustcEncodable, RustcDecodable)]
716 pub enum Rvalue<'tcx> {
717 /// x (either a move or copy, depending on type of x)
721 Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
724 Ref(Region, BorrowKind, Lvalue<'tcx>),
726 /// length of a [X] or [X;n] value
729 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
731 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
733 UnaryOp(UnOp, Operand<'tcx>),
735 /// Creates an *uninitialized* Box
738 /// Create an aggregate value, like a tuple or struct. This is
739 /// only needed because we want to distinguish `dest = Foo { x:
740 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
741 /// that `Foo` has a destructor. These rvalues can be optimized
742 /// away after type-checking and before lowering.
743 Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
745 /// Generates a slice of the form `&input[from_start..L-from_end]`
746 /// where `L` is the length of the slice. This is only created by
747 /// slice pattern matching, so e.g. a pattern of the form `[x, y,
748 /// .., z]` might create a slice with `from_start=2` and
758 outputs: Vec<Lvalue<'tcx>>,
759 inputs: Vec<Operand<'tcx>>
763 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
767 /// Convert unique, zero-sized type for a fn to fn()
770 /// Convert safe fn() to unsafe fn()
773 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
774 /// trans must figure out the details once full monomorphization
775 /// is known. For example, this could be used to cast from a
776 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
777 /// (presuming `T: Trait`).
781 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
782 pub enum AggregateKind<'tcx> {
785 Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>),
786 Closure(DefId, &'tcx ClosureSubsts<'tcx>),
789 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
791 /// The `+` operator (addition)
793 /// The `-` operator (subtraction)
795 /// The `*` operator (multiplication)
797 /// The `/` operator (division)
799 /// The `%` operator (modulus)
801 /// The `^` operator (bitwise xor)
803 /// The `&` operator (bitwise and)
805 /// The `|` operator (bitwise or)
807 /// The `<<` operator (shift left)
809 /// The `>>` operator (shift right)
811 /// The `==` operator (equality)
813 /// The `<` operator (less than)
815 /// The `<=` operator (less than or equal to)
817 /// The `!=` operator (not equal to)
819 /// The `>=` operator (greater than or equal to)
821 /// The `>` operator (greater than)
825 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
827 /// The `!` operator for logical inversion
829 /// The `-` operator for negation
833 impl<'tcx> Debug for Rvalue<'tcx> {
834 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
838 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
839 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
840 Len(ref a) => write!(fmt, "Len({:?})", a),
841 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
842 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
843 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
844 Box(ref t) => write!(fmt, "Box({:?})", t),
845 InlineAsm { ref asm, ref outputs, ref inputs } => {
846 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
848 Slice { ref input, from_start, from_end } =>
849 write!(fmt, "{:?}[{:?}..-{:?}]", input, from_start, from_end),
851 Ref(_, borrow_kind, ref lv) => {
852 let kind_str = match borrow_kind {
853 BorrowKind::Shared => "",
854 BorrowKind::Mut | BorrowKind::Unique => "mut ",
856 write!(fmt, "&{}{:?}", kind_str, lv)
859 Aggregate(ref kind, ref lvs) => {
860 use self::AggregateKind::*;
862 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
863 let mut tuple_fmt = fmt.debug_tuple("");
871 Vec => write!(fmt, "{:?}", lvs),
875 0 => write!(fmt, "()"),
876 1 => write!(fmt, "({:?},)", lvs[0]),
877 _ => fmt_tuple(fmt, lvs),
881 Adt(adt_def, variant, substs) => {
882 let variant_def = &adt_def.variants[variant];
884 ppaux::parameterized(fmt, substs, variant_def.did,
885 ppaux::Ns::Value, &[],
887 tcx.lookup_item_type(variant_def.did).generics
890 match variant_def.kind() {
891 ty::VariantKind::Unit => Ok(()),
892 ty::VariantKind::Tuple => fmt_tuple(fmt, lvs),
893 ty::VariantKind::Struct => {
894 let mut struct_fmt = fmt.debug_struct("");
895 for (field, lv) in variant_def.fields.iter().zip(lvs) {
896 struct_fmt.field(&field.name.as_str(), lv);
903 Closure(def_id, _) => ty::tls::with(|tcx| {
904 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
905 let name = format!("[closure@{:?}]", tcx.map.span(node_id));
906 let mut struct_fmt = fmt.debug_struct(&name);
908 tcx.with_freevars(node_id, |freevars| {
909 for (freevar, lv) in freevars.iter().zip(lvs) {
910 let var_name = tcx.local_var_name_str(freevar.def.var_id());
911 struct_fmt.field(&var_name, lv);
917 write!(fmt, "[closure]")
926 ///////////////////////////////////////////////////////////////////////////
929 /// Two constants are equal if they are the same constant. Note that
930 /// this does not necessarily mean that they are "==" in Rust -- in
931 /// particular one must be wary of `NaN`!
933 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
934 pub struct Constant<'tcx> {
937 pub literal: Literal<'tcx>,
940 #[derive(Clone, RustcEncodable, RustcDecodable)]
941 pub struct TypedConstVal<'tcx> {
944 pub value: ConstUsize,
947 impl<'tcx> Debug for TypedConstVal<'tcx> {
948 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
949 write!(fmt, "const {}", ConstInt::Usize(self.value))
953 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
954 pub enum Literal<'tcx> {
957 substs: &'tcx Substs<'tcx>,
964 impl<'tcx> Debug for Constant<'tcx> {
965 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
966 write!(fmt, "{:?}", self.literal)
970 impl<'tcx> Debug for Literal<'tcx> {
971 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
972 use self::Literal::*;
974 Item { def_id, substs } => {
975 ppaux::parameterized(fmt, substs, def_id, ppaux::Ns::Value, &[],
976 |tcx| tcx.lookup_item_type(def_id).generics)
978 Value { ref value } => {
979 write!(fmt, "const ")?;
980 fmt_const_val(fmt, value)
986 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
987 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
988 use middle::const_eval::ConstVal::*;
990 Float(f) => write!(fmt, "{:?}", f),
991 Integral(n) => write!(fmt, "{}", n),
992 Str(ref s) => write!(fmt, "{:?}", s),
993 ByteStr(ref bytes) => {
994 let escaped: String = bytes
996 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
998 write!(fmt, "b\"{}\"", escaped)
1000 Bool(b) => write!(fmt, "{:?}", b),
1001 Function(def_id) => write!(fmt, "{}", item_path_str(def_id)),
1002 Struct(node_id) | Tuple(node_id) | Array(node_id, _) | Repeat(node_id, _) =>
1003 write!(fmt, "{}", node_to_string(node_id)),
1004 Char(c) => write!(fmt, "{:?}", c),
1005 Dummy => unreachable!(),
1009 fn node_to_string(node_id: ast::NodeId) -> String {
1010 ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1013 fn item_path_str(def_id: DefId) -> String {
1014 ty::tls::with(|tcx| tcx.item_path_str(def_id))