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 middle
::const_eval
::ConstVal
;
12 use middle
::def_id
::DefId
;
13 use middle
::subst
::Substs
;
14 use middle
::ty
::{self, AdtDef, ClosureSubsts, FnOutput, Region, Ty}
;
15 use rustc_back
::slice
;
16 use rustc_data_structures
::tuple_slice
::TupleSlice
;
17 use rustc_front
::hir
::InlineAsm
;
18 use syntax
::ast
::{self, Name}
;
19 use syntax
::codemap
::Span
;
20 use graphviz
::IntoCow
;
23 use std
::fmt
::{self, Debug, Formatter, Write}
;
25 use std
::ops
::{Index, IndexMut}
;
27 /// Lowered representation of a single function.
28 #[derive(RustcEncodable, RustcDecodable)]
29 pub struct Mir
<'tcx
> {
30 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
31 /// that indexes into this vector.
32 pub basic_blocks
: Vec
<BasicBlockData
<'tcx
>>,
34 /// Return type of the function.
35 pub return_ty
: FnOutput
<'tcx
>,
37 /// Variables: these are stack slots corresponding to user variables. They may be
38 /// assigned many times.
39 pub var_decls
: Vec
<VarDecl
<'tcx
>>,
41 /// Args: these are stack slots corresponding to the input arguments.
42 pub arg_decls
: Vec
<ArgDecl
<'tcx
>>,
44 /// Temp declarations: stack slots that for temporaries created by
45 /// the compiler. These are assigned once, but they are not SSA
46 /// values in that it is possible to borrow them and mutate them
47 /// through the resulting reference.
48 pub temp_decls
: Vec
<TempDecl
<'tcx
>>,
51 /// where execution begins
52 pub const START_BLOCK
: BasicBlock
= BasicBlock(0);
54 /// where execution ends, on normal return
55 pub const END_BLOCK
: BasicBlock
= BasicBlock(1);
57 impl<'tcx
> Mir
<'tcx
> {
58 pub fn all_basic_blocks(&self) -> Vec
<BasicBlock
> {
59 (0..self.basic_blocks
.len())
60 .map(|i
| BasicBlock
::new(i
))
64 pub fn basic_block_data(&self, bb
: BasicBlock
) -> &BasicBlockData
<'tcx
> {
65 &self.basic_blocks
[bb
.index()]
68 pub fn basic_block_data_mut(&mut self, bb
: BasicBlock
) -> &mut BasicBlockData
<'tcx
> {
69 &mut self.basic_blocks
[bb
.index()]
73 impl<'tcx
> Index
<BasicBlock
> for Mir
<'tcx
> {
74 type Output
= BasicBlockData
<'tcx
>;
77 fn index(&self, index
: BasicBlock
) -> &BasicBlockData
<'tcx
> {
78 self.basic_block_data(index
)
82 impl<'tcx
> IndexMut
<BasicBlock
> for Mir
<'tcx
> {
84 fn index_mut(&mut self, index
: BasicBlock
) -> &mut BasicBlockData
<'tcx
> {
85 self.basic_block_data_mut(index
)
89 ///////////////////////////////////////////////////////////////////////////
90 // Mutability and borrow kinds
92 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
98 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
100 /// Data must be immutable and is aliasable.
103 /// Data must be immutable but not aliasable. This kind of borrow
104 /// cannot currently be expressed by the user and is used only in
105 /// implicit closure bindings. It is needed when you the closure
106 /// is borrowing or mutating a mutable referent, e.g.:
108 /// let x: &mut isize = ...;
109 /// let y = || *x += 5;
111 /// If we were to try to translate this closure into a more explicit
112 /// form, we'd encounter an error with the code as written:
114 /// struct Env { x: & &mut isize }
115 /// let x: &mut isize = ...;
116 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
117 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
119 /// This is then illegal because you cannot mutate a `&mut` found
120 /// in an aliasable location. To solve, you'd have to translate with
121 /// an `&mut` borrow:
123 /// struct Env { x: & &mut isize }
124 /// let x: &mut isize = ...;
125 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
126 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
128 /// Now the assignment to `**env.x` is legal, but creating a
129 /// mutable pointer to `x` is not because `x` is not mutable. We
130 /// could fix this by declaring `x` as `let mut x`. This is ok in
131 /// user code, if awkward, but extra weird for closures, since the
132 /// borrow is hidden.
134 /// So we introduce a "unique imm" borrow -- the referent is
135 /// immutable, but not aliasable. This solves the problem. For
136 /// simplicity, we don't give users the way to express this
137 /// borrow, it's just used when translating closures.
140 /// Data is mutable and not aliasable.
144 ///////////////////////////////////////////////////////////////////////////
145 // Variables and temps
147 // A "variable" is a binding declared by the user as part of the fn
149 #[derive(RustcEncodable, RustcDecodable)]
150 pub struct VarDecl
<'tcx
> {
151 pub mutability
: Mutability
,
156 // A "temp" is a temporary that we place on the stack. They are
157 // anonymous, always mutable, and have only a type.
158 #[derive(RustcEncodable, RustcDecodable)]
159 pub struct TempDecl
<'tcx
> {
163 // A "arg" is one of the function's formal arguments. These are
164 // anonymous and distinct from the bindings that the user declares.
166 // For example, in this function:
169 // fn foo((x, y): (i32, u32)) { ... }
172 // there is only one argument, of type `(i32, u32)`, but two bindings
174 #[derive(RustcEncodable, RustcDecodable)]
175 pub struct ArgDecl
<'tcx
> {
179 ///////////////////////////////////////////////////////////////////////////
182 /// The index of a particular basic block. The index is into the `basic_blocks`
183 /// list of the `Mir`.
185 /// (We use a `u32` internally just to save memory.)
186 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
187 pub struct BasicBlock(u32);
190 pub fn new(index
: usize) -> BasicBlock
{
191 assert
!(index
< (u32::MAX
as usize));
192 BasicBlock(index
as u32)
195 /// Extract the index.
196 pub fn index(self) -> usize {
201 impl Debug
for BasicBlock
{
202 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
203 write
!(fmt
, "bb{}", self.0)
207 ///////////////////////////////////////////////////////////////////////////
208 // BasicBlock and Terminator
210 #[derive(Debug, RustcEncodable, RustcDecodable)]
211 pub struct BasicBlockData
<'tcx
> {
212 pub statements
: Vec
<Statement
<'tcx
>>,
213 pub terminator
: Option
<Terminator
<'tcx
>>,
214 pub is_cleanup
: bool
,
217 #[derive(RustcEncodable, RustcDecodable)]
218 pub enum Terminator
<'tcx
> {
219 /// block should have one successor in the graph; we jump there
224 /// jump to branch 0 if this lvalue evaluates to true
227 targets
: (BasicBlock
, BasicBlock
),
230 /// lvalue evaluates to some enum; jump depending on the branch
233 adt_def
: AdtDef
<'tcx
>,
234 targets
: Vec
<BasicBlock
>,
237 /// operand evaluates to an integer; jump depending on its value
238 /// to one of the targets, and otherwise fallback to `otherwise`
240 /// discriminant value being tested
243 /// type of value being tested
246 /// Possible values. The locations to branch to in each case
247 /// are found in the corresponding indices from the `targets` vector.
248 values
: Vec
<ConstVal
>,
250 /// Possible branch sites. The length of this vector should be
251 /// equal to the length of the `values` vector plus 1 -- the
252 /// extra item is the block to branch to if none of the values
254 targets
: Vec
<BasicBlock
>,
257 /// Indicates that the landing pad is finished and unwinding should
258 /// continue. Emitted by build::scope::diverge_cleanup.
261 /// Indicates a normal return. The ReturnPointer lvalue should
262 /// have been filled in by now. This should only occur in the
266 /// Block ends with a call of a converging function
268 /// The function that’s being called
270 /// Arguments the function is called with
271 args
: Vec
<Operand
<'tcx
>>,
272 /// The kind of call with associated information
273 kind
: CallKind
<'tcx
>,
277 #[derive(Clone, RustcEncodable, RustcDecodable)]
278 pub enum CallKind
<'tcx
> {
279 /// Diverging function without associated cleanup
281 /// Diverging function with associated cleanup
282 DivergingCleanup(BasicBlock
),
283 /// Converging function without associated cleanup
285 /// Destination where the call result is written
286 destination
: Lvalue
<'tcx
>,
287 /// Block to branch into on successful return
291 /// Destination where the call result is written
292 destination
: Lvalue
<'tcx
>,
293 /// First target is branched to on successful return.
294 /// Second block contains the cleanups to do on unwind.
295 targets
: (BasicBlock
, BasicBlock
)
299 impl<'tcx
> CallKind
<'tcx
> {
300 pub fn successors(&self) -> &[BasicBlock
] {
302 CallKind
::Diverging
=> &[],
303 CallKind
::DivergingCleanup(ref b
) |
304 CallKind
::Converging { target: ref b, .. }
=> slice
::ref_slice(b
),
305 CallKind
::ConvergingCleanup { ref targets, .. }
=> targets
.as_slice(),
309 pub fn successors_mut(&mut self) -> &mut [BasicBlock
] {
311 CallKind
::Diverging
=> &mut [],
312 CallKind
::DivergingCleanup(ref mut b
) |
313 CallKind
::Converging { target: ref mut b, .. }
=> slice
::mut_ref_slice(b
),
314 CallKind
::ConvergingCleanup { ref mut targets, .. }
=> targets
.as_mut_slice(),
318 pub fn destination(&self) -> Option
<&Lvalue
<'tcx
>> {
320 CallKind
::Converging { ref destination, .. }
|
321 CallKind
::ConvergingCleanup { ref destination, .. }
=> Some(destination
),
322 CallKind
::Diverging
|
323 CallKind
::DivergingCleanup(_
) => None
327 pub fn destination_mut(&mut self) -> Option
<&mut Lvalue
<'tcx
>> {
329 CallKind
::Converging { ref mut destination, .. }
|
330 CallKind
::ConvergingCleanup { ref mut destination, .. }
=> Some(destination
),
331 CallKind
::Diverging
|
332 CallKind
::DivergingCleanup(_
) => None
337 impl<'tcx
> Terminator
<'tcx
> {
338 pub fn successors(&self) -> &[BasicBlock
] {
339 use self::Terminator
::*;
341 Goto { target: ref b }
=> slice
::ref_slice(b
),
342 If { targets: ref b, .. }
=> b
.as_slice(),
343 Switch { targets: ref b, .. }
=> b
,
344 SwitchInt { targets: ref b, .. }
=> b
,
347 Call { ref kind, .. }
=> kind
.successors(),
351 pub fn successors_mut(&mut self) -> &mut [BasicBlock
] {
352 use self::Terminator
::*;
354 Goto { target: ref mut b }
=> slice
::mut_ref_slice(b
),
355 If { targets: ref mut b, .. }
=> b
.as_mut_slice(),
356 Switch { targets: ref mut b, .. }
=> b
,
357 SwitchInt { targets: ref mut b, .. }
=> b
,
360 Call { ref mut kind, .. }
=> kind
.successors_mut(),
365 impl<'tcx
> BasicBlockData
<'tcx
> {
366 pub fn new(terminator
: Option
<Terminator
<'tcx
>>) -> BasicBlockData
<'tcx
> {
369 terminator
: terminator
,
374 /// Accessor for terminator.
376 /// Terminator may not be None after construction of the basic block is complete. This accessor
377 /// provides a convenience way to reach the terminator.
378 pub fn terminator(&self) -> &Terminator
<'tcx
> {
379 self.terminator
.as_ref().expect("invalid terminator state")
382 pub fn terminator_mut(&mut self) -> &mut Terminator
<'tcx
> {
383 self.terminator
.as_mut().expect("invalid terminator state")
387 impl<'tcx
> Debug
for Terminator
<'tcx
> {
388 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
389 try
!(self.fmt_head(fmt
));
390 let successors
= self.successors();
391 let labels
= self.fmt_successor_labels();
392 assert_eq
!(successors
.len(), labels
.len());
394 match successors
.len() {
397 1 => write
!(fmt
, " -> {:?}", successors
[0]),
400 try
!(write
!(fmt
, " -> ["));
401 for (i
, target
) in successors
.iter().enumerate() {
403 try
!(write
!(fmt
, ", "));
405 try
!(write
!(fmt
, "{}: {:?}", labels
[i
], target
));
414 impl<'tcx
> Terminator
<'tcx
> {
415 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
416 /// successor basic block, if any. The only information not inlcuded is the list of possible
417 /// successors, which may be rendered differently between the text and the graphviz format.
418 pub fn fmt_head
<W
: Write
>(&self, fmt
: &mut W
) -> fmt
::Result
{
419 use self::Terminator
::*;
421 Goto { .. }
=> write
!(fmt
, "goto"),
422 If { cond: ref lv, .. }
=> write
!(fmt
, "if({:?})", lv
),
423 Switch { discr: ref lv, .. }
=> write
!(fmt
, "switch({:?})", lv
),
424 SwitchInt { discr: ref lv, .. }
=> write
!(fmt
, "switchInt({:?})", lv
),
425 Return
=> write
!(fmt
, "return"),
426 Resume
=> write
!(fmt
, "resume"),
427 Call { ref kind, ref func, ref args }
=> {
428 if let Some(destination
) = kind
.destination() {
429 try
!(write
!(fmt
, "{:?} = ", destination
));
431 try
!(write
!(fmt
, "{:?}(", func
));
432 for (index
, arg
) in args
.iter().enumerate() {
434 try
!(write
!(fmt
, ", "));
436 try
!(write
!(fmt
, "{:?}", arg
));
443 /// Return the list of labels for the edges to the successor basic blocks.
444 pub fn fmt_successor_labels(&self) -> Vec
<Cow
<'
static, str>> {
445 use self::Terminator
::*;
447 Return
| Resume
=> vec
![],
448 Goto { .. }
=> vec
!["".into_cow()],
449 If { .. }
=> vec
!["true".into_cow(), "false".into_cow()],
450 Switch { ref adt_def, .. }
=> {
453 .map(|variant
| variant
.name
.to_string().into_cow())
456 SwitchInt { ref values, .. }
=> {
459 let mut buf
= String
::new();
460 fmt_const_val(&mut buf
, const_val
).unwrap();
463 .chain(iter
::once(String
::from("otherwise").into_cow()))
466 Call { ref kind, .. }
=> match *kind
{
467 CallKind
::Diverging
=>
469 CallKind
::DivergingCleanup(..) =>
470 vec
!["unwind".into_cow()],
471 CallKind
::Converging { .. }
=>
472 vec
!["return".into_cow()],
473 CallKind
::ConvergingCleanup { .. }
=>
474 vec
!["return".into_cow(), "unwind".into_cow()],
481 ///////////////////////////////////////////////////////////////////////////
484 #[derive(RustcEncodable, RustcDecodable)]
485 pub struct Statement
<'tcx
> {
487 pub kind
: StatementKind
<'tcx
>,
490 #[derive(Debug, RustcEncodable, RustcDecodable)]
491 pub enum StatementKind
<'tcx
> {
492 Assign(Lvalue
<'tcx
>, Rvalue
<'tcx
>),
493 Drop(DropKind
, Lvalue
<'tcx
>),
496 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
498 Free
, // free a partially constructed box, should go away eventually
502 impl<'tcx
> Debug
for Statement
<'tcx
> {
503 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
504 use self::StatementKind
::*;
506 Assign(ref lv
, ref rv
) => write
!(fmt
, "{:?} = {:?}", lv
, rv
),
507 Drop(DropKind
::Free
, ref lv
) => write
!(fmt
, "free {:?}", lv
),
508 Drop(DropKind
::Deep
, ref lv
) => write
!(fmt
, "drop {:?}", lv
),
512 ///////////////////////////////////////////////////////////////////////////
515 /// A path to a value; something that can be evaluated without
516 /// changing or disturbing program state.
517 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
518 pub enum Lvalue
<'tcx
> {
519 /// local variable declared by the user
522 /// temporary introduced during lowering into MIR
525 /// formal parameter of the function; note that these are NOT the
526 /// bindings that the user declares, which are vars
529 /// static or static mut variable
532 /// the return pointer of the fn
535 /// projection out of an lvalue (access a field, deref a pointer, etc)
536 Projection(Box
<LvalueProjection
<'tcx
>>),
539 /// The `Projection` data structure defines things of the form `B.x`
540 /// or `*B` or `B[index]`. Note that it is parameterized because it is
541 /// shared between `Constant` and `Lvalue`. See the aliases
542 /// `LvalueProjection` etc below.
543 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
544 pub struct Projection
<'tcx
, B
, V
> {
546 pub elem
: ProjectionElem
<'tcx
, V
>,
549 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
550 pub enum ProjectionElem
<'tcx
, V
> {
555 // These indices are generated by slice patterns. Easiest to explain
559 // [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
560 // [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
561 // [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
562 // [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
565 offset
: u32, // index or -index (in Python terms), depending on from_end
566 min_length
: u32, // thing being indexed must be at least this long
567 from_end
: bool
, // counting backwards from end?
570 // "Downcast" to a variant of an ADT. Currently, we only introduce
571 // this for ADTs with more than one variant. It may be better to
572 // just introduce it always, or always for enums.
573 Downcast(AdtDef
<'tcx
>, usize),
576 /// Alias for projections as they appear in lvalues, where the base is an lvalue
577 /// and the index is an operand.
578 pub type LvalueProjection
<'tcx
> = Projection
<'tcx
, Lvalue
<'tcx
>, Operand
<'tcx
>>;
580 /// Alias for projections as they appear in lvalues, where the base is an lvalue
581 /// and the index is an operand.
582 pub type LvalueElem
<'tcx
> = ProjectionElem
<'tcx
, Operand
<'tcx
>>;
584 /// Index into the list of fields found in a `VariantDef`
585 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
586 pub struct Field(u32);
589 pub fn new(value
: usize) -> Field
{
590 assert
!(value
< (u32::MAX
) as usize);
594 pub fn index(self) -> usize {
599 impl<'tcx
> Lvalue
<'tcx
> {
600 pub fn field(self, f
: Field
) -> Lvalue
<'tcx
> {
601 self.elem(ProjectionElem
::Field(f
))
604 pub fn deref(self) -> Lvalue
<'tcx
> {
605 self.elem(ProjectionElem
::Deref
)
608 pub fn index(self, index
: Operand
<'tcx
>) -> Lvalue
<'tcx
> {
609 self.elem(ProjectionElem
::Index(index
))
612 pub fn elem(self, elem
: LvalueElem
<'tcx
>) -> Lvalue
<'tcx
> {
613 Lvalue
::Projection(Box
::new(LvalueProjection
{
620 impl<'tcx
> Debug
for Lvalue
<'tcx
> {
621 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
626 write
!(fmt
, "var{:?}", id
),
628 write
!(fmt
, "arg{:?}", id
),
630 write
!(fmt
, "tmp{:?}", id
),
632 write
!(fmt
, "{}", ty
::tls
::with(|tcx
| tcx
.item_path_str(def_id
))),
634 write
!(fmt
, "return"),
635 Projection(ref data
) =>
637 ProjectionElem
::Downcast(ref adt_def
, index
) =>
638 write
!(fmt
, "({:?} as {})", data
.base
, adt_def
.variants
[index
].name
),
639 ProjectionElem
::Deref
=>
640 write
!(fmt
, "(*{:?})", data
.base
),
641 ProjectionElem
::Field(field
) =>
642 write
!(fmt
, "{:?}.{:?}", data
.base
, field
.index()),
643 ProjectionElem
::Index(ref index
) =>
644 write
!(fmt
, "{:?}[{:?}]", data
.base
, index
),
645 ProjectionElem
::ConstantIndex { offset, min_length, from_end: false }
=>
646 write
!(fmt
, "{:?}[{:?} of {:?}]", data
.base
, offset
, min_length
),
647 ProjectionElem
::ConstantIndex { offset, min_length, from_end: true }
=>
648 write
!(fmt
, "{:?}[-{:?} of {:?}]", data
.base
, offset
, min_length
),
654 ///////////////////////////////////////////////////////////////////////////
657 // These are values that can appear inside an rvalue (or an index
658 // lvalue). They are intentionally limited to prevent rvalues from
659 // being nested in one another.
661 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
662 pub enum Operand
<'tcx
> {
663 Consume(Lvalue
<'tcx
>),
664 Constant(Constant
<'tcx
>),
667 impl<'tcx
> Debug
for Operand
<'tcx
> {
668 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
669 use self::Operand
::*;
671 Constant(ref a
) => write
!(fmt
, "{:?}", a
),
672 Consume(ref lv
) => write
!(fmt
, "{:?}", lv
),
677 ///////////////////////////////////////////////////////////////////////////
680 #[derive(Clone, RustcEncodable, RustcDecodable)]
681 pub enum Rvalue
<'tcx
> {
682 // x (either a move or copy, depending on type of x)
686 Repeat(Operand
<'tcx
>, Constant
<'tcx
>),
689 Ref(Region
, BorrowKind
, Lvalue
<'tcx
>),
691 // length of a [X] or [X;n] value
694 Cast(CastKind
, Operand
<'tcx
>, Ty
<'tcx
>),
696 BinaryOp(BinOp
, Operand
<'tcx
>, Operand
<'tcx
>),
698 UnaryOp(UnOp
, Operand
<'tcx
>),
700 // Creates an *uninitialized* Box
703 // Create an aggregate value, like a tuple or struct. This is
704 // only needed because we want to distinguish `dest = Foo { x:
705 // ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
706 // that `Foo` has a destructor. These rvalues can be optimized
707 // away after type-checking and before lowering.
708 Aggregate(AggregateKind
<'tcx
>, Vec
<Operand
<'tcx
>>),
710 // Generates a slice of the form `&input[from_start..L-from_end]`
711 // where `L` is the length of the slice. This is only created by
712 // slice pattern matching, so e.g. a pattern of the form `[x, y,
713 // .., z]` might create a slice with `from_start=2` and
721 InlineAsm(InlineAsm
),
724 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
728 /// Convert unique, zero-sized type for a fn to fn()
731 /// Convert safe fn() to unsafe fn()
734 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
735 /// trans must figure out the details once full monomorphization
736 /// is known. For example, this could be used to cast from a
737 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
738 /// (presuming `T: Trait`).
742 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
743 pub enum AggregateKind
<'tcx
> {
746 Adt(AdtDef
<'tcx
>, usize, &'tcx Substs
<'tcx
>),
747 Closure(DefId
, &'tcx ClosureSubsts
<'tcx
>),
750 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
752 /// The `+` operator (addition)
754 /// The `-` operator (subtraction)
756 /// The `*` operator (multiplication)
758 /// The `/` operator (division)
760 /// The `%` operator (modulus)
762 /// The `^` operator (bitwise xor)
764 /// The `&` operator (bitwise and)
766 /// The `|` operator (bitwise or)
768 /// The `<<` operator (shift left)
770 /// The `>>` operator (shift right)
772 /// The `==` operator (equality)
774 /// The `<` operator (less than)
776 /// The `<=` operator (less than or equal to)
778 /// The `!=` operator (not equal to)
780 /// The `>=` operator (greater than or equal to)
782 /// The `>` operator (greater than)
786 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
788 /// The `!` operator for logical inversion
790 /// The `-` operator for negation
794 impl<'tcx
> Debug
for Rvalue
<'tcx
> {
795 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
799 Use(ref lvalue
) => write
!(fmt
, "{:?}", lvalue
),
800 Repeat(ref a
, ref b
) => write
!(fmt
, "[{:?}; {:?}]", a
, b
),
801 Len(ref a
) => write
!(fmt
, "Len({:?})", a
),
802 Cast(ref kind
, ref lv
, ref ty
) => write
!(fmt
, "{:?} as {:?} ({:?})", lv
, ty
, kind
),
803 BinaryOp(ref op
, ref a
, ref b
) => write
!(fmt
, "{:?}({:?}, {:?})", op
, a
, b
),
804 UnaryOp(ref op
, ref a
) => write
!(fmt
, "{:?}({:?})", op
, a
),
805 Box(ref t
) => write
!(fmt
, "Box({:?})", t
),
806 InlineAsm(ref asm
) => write
!(fmt
, "InlineAsm({:?})", asm
),
807 Slice { ref input, from_start, from_end }
=>
808 write
!(fmt
, "{:?}[{:?}..-{:?}]", input
, from_start
, from_end
),
810 Ref(_
, borrow_kind
, ref lv
) => {
811 let kind_str
= match borrow_kind
{
812 BorrowKind
::Shared
=> "",
813 BorrowKind
::Mut
| BorrowKind
::Unique
=> "mut ",
815 write
!(fmt
, "&{}{:?}", kind_str
, lv
)
818 Aggregate(ref kind
, ref lvs
) => {
819 use self::AggregateKind
::*;
821 fn fmt_tuple(fmt
: &mut Formatter
, name
: &str, lvs
: &[Operand
]) -> fmt
::Result
{
822 let mut tuple_fmt
= fmt
.debug_tuple(name
);
830 Vec
=> write
!(fmt
, "{:?}", lvs
),
834 0 => write
!(fmt
, "()"),
835 1 => write
!(fmt
, "({:?},)", lvs
[0]),
836 _
=> fmt_tuple(fmt
, "", lvs
),
840 Adt(adt_def
, variant
, _
) => {
841 let variant_def
= &adt_def
.variants
[variant
];
842 let name
= ty
::tls
::with(|tcx
| tcx
.item_path_str(variant_def
.did
));
844 match variant_def
.kind() {
845 ty
::VariantKind
::Unit
=> write
!(fmt
, "{}", name
),
846 ty
::VariantKind
::Tuple
=> fmt_tuple(fmt
, &name
, lvs
),
847 ty
::VariantKind
::Struct
=> {
848 let mut struct_fmt
= fmt
.debug_struct(&name
);
849 for (field
, lv
) in variant_def
.fields
.iter().zip(lvs
) {
850 struct_fmt
.field(&field
.name
.as_str(), lv
);
857 Closure(def_id
, _
) => ty
::tls
::with(|tcx
| {
858 if let Some(node_id
) = tcx
.map
.as_local_node_id(def_id
) {
859 let name
= format
!("[closure@{:?}]", tcx
.map
.span(node_id
));
860 let mut struct_fmt
= fmt
.debug_struct(&name
);
862 tcx
.with_freevars(node_id
, |freevars
| {
863 for (freevar
, lv
) in freevars
.iter().zip(lvs
) {
864 let var_name
= tcx
.local_var_name_str(freevar
.def
.var_id());
865 struct_fmt
.field(&var_name
, lv
);
871 write
!(fmt
, "[closure]")
880 ///////////////////////////////////////////////////////////////////////////
883 // Two constants are equal if they are the same constant. Note that
884 // this does not necessarily mean that they are "==" in Rust -- in
885 // particular one must be wary of `NaN`!
887 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
888 pub struct Constant
<'tcx
> {
891 pub literal
: Literal
<'tcx
>,
894 #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)]
897 /// This is any sort of callable (usually those that have a type of `fn(…) -> …`). This
898 /// includes functions, constructors, but not methods which have their own ItemKind.
903 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
904 pub enum Literal
<'tcx
> {
908 substs
: &'tcx Substs
<'tcx
>,
915 impl<'tcx
> Debug
for Constant
<'tcx
> {
916 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
917 write
!(fmt
, "{:?}", self.literal
)
921 impl<'tcx
> Debug
for Literal
<'tcx
> {
922 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
923 use self::Literal
::*;
925 Item { def_id, .. }
=>
926 write
!(fmt
, "{}", item_path_str(def_id
)),
927 Value { ref value }
=> {
928 try
!(write
!(fmt
, "const "));
929 fmt_const_val(fmt
, value
)
935 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
936 fn fmt_const_val
<W
: Write
>(fmt
: &mut W
, const_val
: &ConstVal
) -> fmt
::Result
{
937 use middle
::const_eval
::ConstVal
::*;
939 Float(f
) => write
!(fmt
, "{:?}", f
),
940 Int(n
) => write
!(fmt
, "{:?}", n
),
941 Uint(n
) => write
!(fmt
, "{:?}", n
),
942 Str(ref s
) => write
!(fmt
, "{:?}", s
),
943 ByteStr(ref bytes
) => {
944 let escaped
: String
= bytes
946 .flat_map(|&ch
| ascii
::escape_default(ch
).map(|c
| c
as char))
948 write
!(fmt
, "b\"{}\"", escaped
)
950 Bool(b
) => write
!(fmt
, "{:?}", b
),
951 Function(def_id
) => write
!(fmt
, "{}", item_path_str(def_id
)),
952 Struct(node_id
) | Tuple(node_id
) | Array(node_id
, _
) | Repeat(node_id
, _
) =>
953 write
!(fmt
, "{}", node_to_string(node_id
)),
957 fn node_to_string(node_id
: ast
::NodeId
) -> String
{
958 ty
::tls
::with(|tcx
| tcx
.map
.node_to_user_string(node_id
))
961 fn item_path_str(def_id
: DefId
) -> String
{
962 ty
::tls
::with(|tcx
| tcx
.item_path_str(def_id
))