]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/repr.rs
2931af2936f5187989704e07da3b275bf5ba08c3
[rust.git] / src / librustc / mir / repr.rs
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.
4 //
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.
10
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};
17 use util::ppaux;
18 use rustc_back::slice;
19 use rustc_front::hir::InlineAsm;
20 use std::ascii;
21 use std::borrow::{Cow};
22 use std::fmt::{self, Debug, Formatter, Write};
23 use std::{iter, u32};
24 use std::ops::{Index, IndexMut};
25 use syntax::ast::{self, Name};
26 use syntax::codemap::Span;
27
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>>,
34
35     /// List of lexical scopes; these are referenced by statements and
36     /// used (eventually) for debuginfo. Indexed by a `ScopeId`.
37     pub scopes: ScopeDataVec,
38
39     /// Return type of the function.
40     pub return_ty: FnOutput<'tcx>,
41
42     /// Variables: these are stack slots corresponding to user variables. They may be
43     /// assigned many times.
44     pub var_decls: Vec<VarDecl<'tcx>>,
45
46     /// Args: these are stack slots corresponding to the input arguments.
47     pub arg_decls: Vec<ArgDecl<'tcx>>,
48
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>>,
54
55     /// A span representing this MIR, for error reporting
56     pub span: Span,
57 }
58
59 /// where execution begins
60 pub const START_BLOCK: BasicBlock = BasicBlock(0);
61
62 /// where execution ends, on normal return
63 pub const END_BLOCK: BasicBlock = BasicBlock(1);
64
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))
69             .collect()
70     }
71
72     pub fn basic_block_data(&self, bb: BasicBlock) -> &BasicBlockData<'tcx> {
73         &self.basic_blocks[bb.index()]
74     }
75
76     pub fn basic_block_data_mut(&mut self, bb: BasicBlock) -> &mut BasicBlockData<'tcx> {
77         &mut self.basic_blocks[bb.index()]
78     }
79 }
80
81 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
82     type Output = BasicBlockData<'tcx>;
83
84     #[inline]
85     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
86         self.basic_block_data(index)
87     }
88 }
89
90 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
91     #[inline]
92     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
93         self.basic_block_data_mut(index)
94     }
95 }
96
97 ///////////////////////////////////////////////////////////////////////////
98 // Mutability and borrow kinds
99
100 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
101 pub enum Mutability {
102     Mut,
103     Not,
104 }
105
106 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
107 pub enum BorrowKind {
108     /// Data must be immutable and is aliasable.
109     Shared,
110
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.:
115     ///
116     ///    let x: &mut isize = ...;
117     ///    let y = || *x += 5;
118     ///
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:
121     ///
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; }
126     ///
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:
130     ///
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; }
135     ///
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.
141     ///
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.
146     Unique,
147
148     /// Data is mutable and not aliasable.
149     Mut,
150 }
151
152 ///////////////////////////////////////////////////////////////////////////
153 // Variables and temps
154
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,
161
162     /// name that user gave the variable; not that, internally,
163     /// mir references variables by index
164     pub name: Name,
165
166     /// type inferred for this variable (`let x: ty = ...`)
167     pub ty: Ty<'tcx>,
168
169     /// scope in which variable was declared
170     pub scope: ScopeId,
171
172     /// span where variable was declared
173     pub span: Span,
174 }
175
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> {
180     pub ty: Ty<'tcx>,
181 }
182
183 /// A "arg" is one of the function's formal arguments. These are
184 /// anonymous and distinct from the bindings that the user declares.
185 ///
186 /// For example, in this function:
187 ///
188 /// ```
189 /// fn foo((x, y): (i32, u32)) { ... }
190 /// ```
191 ///
192 /// there is only one argument, of type `(i32, u32)`, but two bindings
193 /// (`x` and `y`).
194 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
195 pub struct ArgDecl<'tcx> {
196     pub ty: Ty<'tcx>,
197
198     /// If true, this argument is a tuple after monomorphization,
199     /// and has to be collected from multiple actual arguments.
200     pub spread: bool
201 }
202
203 ///////////////////////////////////////////////////////////////////////////
204 // BasicBlock
205
206 /// The index of a particular basic block. The index is into the `basic_blocks`
207 /// list of the `Mir`.
208 ///
209 /// (We use a `u32` internally just to save memory.)
210 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
211 pub struct BasicBlock(u32);
212
213 impl BasicBlock {
214     pub fn new(index: usize) -> BasicBlock {
215         assert!(index < (u32::MAX as usize));
216         BasicBlock(index as u32)
217     }
218
219     /// Extract the index.
220     pub fn index(self) -> usize {
221         self.0 as usize
222     }
223 }
224
225 impl Debug for BasicBlock {
226     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
227         write!(fmt, "bb{}", self.0)
228     }
229 }
230
231 ///////////////////////////////////////////////////////////////////////////
232 // BasicBlockData and Terminator
233
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,
239 }
240
241 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
242 pub struct Terminator<'tcx> {
243     pub span: Span,
244     pub scope: ScopeId,
245     pub kind: TerminatorKind<'tcx>
246 }
247
248 #[derive(Clone, RustcEncodable, RustcDecodable)]
249 pub enum TerminatorKind<'tcx> {
250     /// block should have one successor in the graph; we jump there
251     Goto {
252         target: BasicBlock,
253     },
254
255     /// jump to branch 0 if this lvalue evaluates to true
256     If {
257         cond: Operand<'tcx>,
258         targets: (BasicBlock, BasicBlock),
259     },
260
261     /// lvalue evaluates to some enum; jump depending on the branch
262     Switch {
263         discr: Lvalue<'tcx>,
264         adt_def: AdtDef<'tcx>,
265         targets: Vec<BasicBlock>,
266     },
267
268     /// operand evaluates to an integer; jump depending on its value
269     /// to one of the targets, and otherwise fallback to `otherwise`
270     SwitchInt {
271         /// discriminant value being tested
272         discr: Lvalue<'tcx>,
273
274         /// type of value being tested
275         switch_ty: Ty<'tcx>,
276
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>,
280
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
284         /// fit.
285         targets: Vec<BasicBlock>,
286     },
287
288     /// Indicates that the landing pad is finished and unwinding should
289     /// continue. Emitted by build::scope::diverge_cleanup.
290     Resume,
291
292     /// Indicates a normal return. The ReturnPointer lvalue should
293     /// have been filled in by now. This should only occur in the
294     /// `END_BLOCK`.
295     Return,
296
297     /// Drop the Lvalue
298     Drop {
299         value: Lvalue<'tcx>,
300         target: BasicBlock,
301         unwind: Option<BasicBlock>
302     },
303
304     /// Block ends with a call of a converging function
305     Call {
306         /// The function that’s being called
307         func: Operand<'tcx>,
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>
314     },
315 }
316
317 impl<'tcx> Terminator<'tcx> {
318     pub fn successors(&self) -> Cow<[BasicBlock]> {
319         self.kind.successors()
320     }
321
322     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
323         self.kind.successors_mut()
324     }
325 }
326
327 impl<'tcx> TerminatorKind<'tcx> {
328     pub fn successors(&self) -> Cow<[BasicBlock]> {
329         use self::TerminatorKind::*;
330         match *self {
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(),
344         }
345     }
346
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::*;
351         match *self {
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]
364         }
365     }
366 }
367
368 impl<'tcx> BasicBlockData<'tcx> {
369     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
370         BasicBlockData {
371             statements: vec![],
372             terminator: terminator,
373             is_cleanup: false,
374         }
375     }
376
377     /// Accessor for terminator.
378     ///
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")
383     }
384
385     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
386         self.terminator.as_mut().expect("invalid terminator state")
387     }
388 }
389
390 impl<'tcx> Debug for TerminatorKind<'tcx> {
391     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
392         self.fmt_head(fmt)?;
393         let successors = self.successors();
394         let labels = self.fmt_successor_labels();
395         assert_eq!(successors.len(), labels.len());
396
397         match successors.len() {
398             0 => Ok(()),
399
400             1 => write!(fmt, " -> {:?}", successors[0]),
401
402             _ => {
403                 write!(fmt, " -> [")?;
404                 for (i, target) in successors.iter().enumerate() {
405                     if i > 0 {
406                         write!(fmt, ", ")?;
407                     }
408                     write!(fmt, "{}: {:?}", labels[i], target)?;
409                 }
410                 write!(fmt, "]")
411             }
412
413         }
414     }
415 }
416
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::*;
423         match *self {
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)?;
434                 }
435                 write!(fmt, "{:?}(", func)?;
436                 for (index, arg) in args.iter().enumerate() {
437                     if index > 0 {
438                         write!(fmt, ", ")?;
439                     }
440                     write!(fmt, "{:?}", arg)?;
441                 }
442                 write!(fmt, ")")
443             }
444         }
445     }
446
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::*;
450         match *self {
451             Return | Resume => vec![],
452             Goto { .. } => vec!["".into()],
453             If { .. } => vec!["true".into(), "false".into()],
454             Switch { ref adt_def, .. } => {
455                 adt_def.variants
456                        .iter()
457                        .map(|variant| variant.name.to_string().into())
458                        .collect()
459             }
460             SwitchInt { ref values, .. } => {
461                 values.iter()
462                       .map(|const_val| {
463                           let mut buf = String::new();
464                           fmt_const_val(&mut buf, const_val).unwrap();
465                           buf.into()
466                       })
467                       .chain(iter::once(String::from("otherwise").into()))
468                       .collect()
469             }
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()],
477         }
478     }
479 }
480
481
482 ///////////////////////////////////////////////////////////////////////////
483 // Statements
484
485 #[derive(Clone, RustcEncodable, RustcDecodable)]
486 pub struct Statement<'tcx> {
487     pub span: Span,
488     pub scope: ScopeId,
489     pub kind: StatementKind<'tcx>,
490 }
491
492 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
493 pub enum StatementKind<'tcx> {
494     Assign(Lvalue<'tcx>, Rvalue<'tcx>),
495 }
496
497 impl<'tcx> Debug for Statement<'tcx> {
498     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
499         use self::StatementKind::*;
500         match self.kind {
501             Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv)
502         }
503     }
504 }
505
506 ///////////////////////////////////////////////////////////////////////////
507 // Lvalues
508
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
514     Var(u32),
515
516     /// temporary introduced during lowering into MIR
517     Temp(u32),
518
519     /// formal parameter of the function; note that these are NOT the
520     /// bindings that the user declares, which are vars
521     Arg(u32),
522
523     /// static or static mut variable
524     Static(DefId),
525
526     /// the return pointer of the fn
527     ReturnPointer,
528
529     /// projection out of an lvalue (access a field, deref a pointer, etc)
530     Projection(Box<LvalueProjection<'tcx>>),
531 }
532
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> {
539     pub base: B,
540     pub elem: ProjectionElem<'tcx, V>,
541 }
542
543 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
544 pub enum ProjectionElem<'tcx, V> {
545     Deref,
546     Field(Field, Ty<'tcx>),
547     Index(V),
548
549     /// These indices are generated by slice patterns. Easiest to explain
550     /// by example:
551     ///
552     /// ```
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 },
557     /// ```
558     ConstantIndex {
559         /// index or -index (in Python terms), depending on from_end
560         offset: u32,
561         /// thing being indexed must be at least this long
562         min_length: u32,
563         /// counting backwards from end?
564         from_end: bool,
565     },
566
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),
571 }
572
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>>;
576
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>>;
580
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);
584
585 impl Field {
586     pub fn new(value: usize) -> Field {
587         assert!(value < (u32::MAX) as usize);
588         Field(value as u32)
589     }
590
591     pub fn index(self) -> usize {
592         self.0 as usize
593     }
594 }
595
596 impl<'tcx> Lvalue<'tcx> {
597     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
598         self.elem(ProjectionElem::Field(f, ty))
599     }
600
601     pub fn deref(self) -> Lvalue<'tcx> {
602         self.elem(ProjectionElem::Deref)
603     }
604
605     pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
606         self.elem(ProjectionElem::Index(index))
607     }
608
609     pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
610         Lvalue::Projection(Box::new(LvalueProjection {
611             base: self,
612             elem: elem,
613         }))
614     }
615 }
616
617 impl<'tcx> Debug for Lvalue<'tcx> {
618     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
619         use self::Lvalue::*;
620
621         match *self {
622             Var(id) =>
623                 write!(fmt, "var{:?}", id),
624             Arg(id) =>
625                 write!(fmt, "arg{:?}", id),
626             Temp(id) =>
627                 write!(fmt, "tmp{:?}", id),
628             Static(def_id) =>
629                 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
630             ReturnPointer =>
631                 write!(fmt, "return"),
632             Projection(ref data) =>
633                 match data.elem {
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),
646                 },
647         }
648     }
649 }
650
651 ///////////////////////////////////////////////////////////////////////////
652 // Scopes
653
654 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
655 pub struct ScopeDataVec {
656     pub vec: Vec<ScopeData>
657 }
658
659 impl ScopeDataVec {
660     pub fn new() -> Self {
661         ScopeDataVec { vec: Vec::new() }
662     }
663 }
664
665 impl Index<ScopeId> for ScopeDataVec {
666     type Output = ScopeData;
667
668     #[inline]
669     fn index(&self, index: ScopeId) -> &ScopeData {
670         &self.vec[index.index()]
671     }
672 }
673
674 impl IndexMut<ScopeId> for ScopeDataVec {
675     #[inline]
676     fn index_mut(&mut self, index: ScopeId) -> &mut ScopeData {
677         &mut self.vec[index.index()]
678     }
679 }
680
681 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
682 pub struct ScopeId(u32);
683
684 impl ScopeId {
685     pub fn new(index: usize) -> ScopeId {
686         assert!(index < (u32::MAX as usize));
687         ScopeId(index as u32)
688     }
689
690     pub fn index(self) -> usize {
691         self.0 as usize
692     }
693 }
694
695 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
696 pub struct ScopeData {
697     pub parent_scope: Option<ScopeId>,
698 }
699
700 ///////////////////////////////////////////////////////////////////////////
701 // Operands
702
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>),
710 }
711
712 impl<'tcx> Debug for Operand<'tcx> {
713     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
714         use self::Operand::*;
715         match *self {
716             Constant(ref a) => write!(fmt, "{:?}", a),
717             Consume(ref lv) => write!(fmt, "{:?}", lv),
718         }
719     }
720 }
721
722 ///////////////////////////////////////////////////////////////////////////
723 /// Rvalues
724
725 #[derive(Clone, RustcEncodable, RustcDecodable)]
726 pub enum Rvalue<'tcx> {
727     /// x (either a move or copy, depending on type of x)
728     Use(Operand<'tcx>),
729
730     /// [x; 32]
731     Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
732
733     /// &x or &mut x
734     Ref(Region, BorrowKind, Lvalue<'tcx>),
735
736     /// length of a [X] or [X;n] value
737     Len(Lvalue<'tcx>),
738
739     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
740
741     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
742
743     UnaryOp(UnOp, Operand<'tcx>),
744
745     /// Creates an *uninitialized* Box
746     Box(Ty<'tcx>),
747
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>>),
754
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
759     /// `from_end=1`.
760     Slice {
761         input: Lvalue<'tcx>,
762         from_start: usize,
763         from_end: usize,
764     },
765
766     InlineAsm {
767         asm: InlineAsm,
768         outputs: Vec<Lvalue<'tcx>>,
769         inputs: Vec<Operand<'tcx>>
770     }
771 }
772
773 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
774 pub enum CastKind {
775     Misc,
776
777     /// Convert unique, zero-sized type for a fn to fn()
778     ReifyFnPointer,
779
780     /// Convert safe fn() to unsafe fn()
781     UnsafeFnPointer,
782
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`).
788     Unsize,
789 }
790
791 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
792 pub enum AggregateKind<'tcx> {
793     Vec,
794     Tuple,
795     Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>),
796     Closure(DefId, &'tcx ClosureSubsts<'tcx>),
797 }
798
799 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
800 pub enum BinOp {
801     /// The `+` operator (addition)
802     Add,
803     /// The `-` operator (subtraction)
804     Sub,
805     /// The `*` operator (multiplication)
806     Mul,
807     /// The `/` operator (division)
808     Div,
809     /// The `%` operator (modulus)
810     Rem,
811     /// The `^` operator (bitwise xor)
812     BitXor,
813     /// The `&` operator (bitwise and)
814     BitAnd,
815     /// The `|` operator (bitwise or)
816     BitOr,
817     /// The `<<` operator (shift left)
818     Shl,
819     /// The `>>` operator (shift right)
820     Shr,
821     /// The `==` operator (equality)
822     Eq,
823     /// The `<` operator (less than)
824     Lt,
825     /// The `<=` operator (less than or equal to)
826     Le,
827     /// The `!=` operator (not equal to)
828     Ne,
829     /// The `>=` operator (greater than or equal to)
830     Ge,
831     /// The `>` operator (greater than)
832     Gt,
833 }
834
835 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
836 pub enum UnOp {
837     /// The `!` operator for logical inversion
838     Not,
839     /// The `-` operator for negation
840     Neg,
841 }
842
843 impl<'tcx> Debug for Rvalue<'tcx> {
844     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
845         use self::Rvalue::*;
846
847         match *self {
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)
857             }
858             Slice { ref input, from_start, from_end } =>
859                 write!(fmt, "{:?}[{:?}..-{:?}]", input, from_start, from_end),
860
861             Ref(_, borrow_kind, ref lv) => {
862                 let kind_str = match borrow_kind {
863                     BorrowKind::Shared => "",
864                     BorrowKind::Mut | BorrowKind::Unique => "mut ",
865                 };
866                 write!(fmt, "&{}{:?}", kind_str, lv)
867             }
868
869             Aggregate(ref kind, ref lvs) => {
870                 use self::AggregateKind::*;
871
872                 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
873                     let mut tuple_fmt = fmt.debug_tuple("");
874                     for lv in lvs {
875                         tuple_fmt.field(lv);
876                     }
877                     tuple_fmt.finish()
878                 }
879
880                 match *kind {
881                     Vec => write!(fmt, "{:?}", lvs),
882
883                     Tuple => {
884                         match lvs.len() {
885                             0 => write!(fmt, "()"),
886                             1 => write!(fmt, "({:?},)", lvs[0]),
887                             _ => fmt_tuple(fmt, lvs),
888                         }
889                     }
890
891                     Adt(adt_def, variant, substs) => {
892                         let variant_def = &adt_def.variants[variant];
893
894                         ppaux::parameterized(fmt, substs, variant_def.did,
895                                              ppaux::Ns::Value, &[],
896                                              |tcx| {
897                             tcx.lookup_item_type(variant_def.did).generics
898                         })?;
899
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);
907                                 }
908                                 struct_fmt.finish()
909                             }
910                         }
911                     }
912
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);
917
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);
922                                 }
923                             });
924
925                             struct_fmt.finish()
926                         } else {
927                             write!(fmt, "[closure]")
928                         }
929                     }),
930                 }
931             }
932         }
933     }
934 }
935
936 ///////////////////////////////////////////////////////////////////////////
937 /// Constants
938 ///
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`!
942
943 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
944 pub struct Constant<'tcx> {
945     pub span: Span,
946     pub ty: Ty<'tcx>,
947     pub literal: Literal<'tcx>,
948 }
949
950 #[derive(Clone, RustcEncodable, RustcDecodable)]
951 pub struct TypedConstVal<'tcx> {
952     pub ty: Ty<'tcx>,
953     pub span: Span,
954     pub value: ConstUsize,
955 }
956
957 impl<'tcx> Debug for TypedConstVal<'tcx> {
958     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
959         write!(fmt, "const {}", ConstInt::Usize(self.value))
960     }
961 }
962
963 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
964 pub enum Literal<'tcx> {
965     Item {
966         def_id: DefId,
967         substs: &'tcx Substs<'tcx>,
968     },
969     Value {
970         value: ConstVal,
971     },
972 }
973
974 impl<'tcx> Debug for Constant<'tcx> {
975     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
976         write!(fmt, "{:?}", self.literal)
977     }
978 }
979
980 impl<'tcx> Debug for Literal<'tcx> {
981     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
982         use self::Literal::*;
983         match *self {
984             Item { def_id, substs } => {
985                 ppaux::parameterized(fmt, substs, def_id, ppaux::Ns::Value, &[],
986                                      |tcx| tcx.lookup_item_type(def_id).generics)
987             }
988             Value { ref value } => {
989                 write!(fmt, "const ")?;
990                 fmt_const_val(fmt, value)
991             }
992         }
993     }
994 }
995
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::*;
999     match *const_val {
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
1005                 .iter()
1006                 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1007                 .collect();
1008             write!(fmt, "b\"{}\"", escaped)
1009         }
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!(),
1016     }
1017 }
1018
1019 fn node_to_string(node_id: ast::NodeId) -> String {
1020     ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1021 }
1022
1023 fn item_path_str(def_id: DefId) -> String {
1024     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1025 }