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 //! MIR datatypes and passes. See the [rustc guide] for more info.
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/mir/index.html
15 use hir::def::CtorKind;
16 use hir::def_id::DefId;
17 use hir::{self, HirId, InlineAsm};
19 use mir::interpret::{ConstValue, EvalErrorKind, Scalar};
20 use mir::visit::MirVisitable;
21 use rustc_apfloat::ieee::{Double, Single};
22 use rustc_apfloat::Float;
23 use rustc_data_structures::graph::dominators::{dominators, Dominators};
24 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
25 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
26 use rustc_data_structures::sync::Lrc;
27 use rustc_data_structures::sync::MappedReadGuard;
28 use rustc_serialize as serialize;
29 use smallvec::SmallVec;
31 use std::fmt::{self, Debug, Formatter, Write};
32 use std::ops::{Index, IndexMut};
34 use std::vec::IntoIter;
35 use std::{iter, mem, option, u32};
36 use syntax::ast::{self, Name};
37 use syntax::symbol::InternedString;
38 use syntax_pos::{Span, DUMMY_SP};
39 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
40 use ty::subst::{CanonicalUserSubsts, Subst, Substs};
41 use ty::{self, AdtDef, CanonicalTy, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt};
44 pub use mir::interpret::AssertMessage;
54 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
56 pub trait HasLocalDecls<'tcx> {
57 fn local_decls(&self) -> &LocalDecls<'tcx>;
60 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
61 fn local_decls(&self) -> &LocalDecls<'tcx> {
66 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
67 fn local_decls(&self) -> &LocalDecls<'tcx> {
72 /// Lowered representation of a single function.
73 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
74 pub struct Mir<'tcx> {
75 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
76 /// that indexes into this vector.
77 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
79 /// List of source scopes; these are referenced by statements
80 /// and used for debuginfo. Indexed by a `SourceScope`.
81 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
83 /// Crate-local information for each source scope, that can't (and
84 /// needn't) be tracked across crates.
85 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
87 /// Rvalues promoted from this function, such as borrows of constants.
88 /// Each of them is the Mir of a constant with the fn's type parameters
89 /// in scope, but a separate set of locals.
90 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
92 /// Yield type of the function, if it is a generator.
93 pub yield_ty: Option<Ty<'tcx>>,
95 /// Generator drop glue
96 pub generator_drop: Option<Box<Mir<'tcx>>>,
98 /// The layout of a generator. Produced by the state transformation.
99 pub generator_layout: Option<GeneratorLayout<'tcx>>,
101 /// Declarations of locals.
103 /// The first local is the return value pointer, followed by `arg_count`
104 /// locals for the function arguments, followed by any user-declared
105 /// variables and temporaries.
106 pub local_decls: LocalDecls<'tcx>,
108 /// Number of arguments this function takes.
110 /// Starting at local 1, `arg_count` locals will be provided by the caller
111 /// and can be assumed to be initialized.
113 /// If this MIR was built for a constant, this will be 0.
114 pub arg_count: usize,
116 /// Names and capture modes of all the closure upvars, assuming
117 /// the first argument is either the closure or a reference to it.
118 pub upvar_decls: Vec<UpvarDecl>,
120 /// Mark an argument local (which must be a tuple) as getting passed as
121 /// its individual components at the LLVM level.
123 /// This is used for the "rust-call" ABI.
124 pub spread_arg: Option<Local>,
126 /// A span representing this MIR, for error reporting
129 /// A cache for various calculations
133 impl<'tcx> Mir<'tcx> {
135 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
136 source_scopes: IndexVec<SourceScope, SourceScopeData>,
137 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
138 promoted: IndexVec<Promoted, Mir<'tcx>>,
139 yield_ty: Option<Ty<'tcx>>,
140 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
142 upvar_decls: Vec<UpvarDecl>,
145 // We need `arg_count` locals, and one for the return place
147 local_decls.len() >= arg_count + 1,
148 "expected at least {} locals, got {}",
156 source_scope_local_data,
159 generator_drop: None,
160 generator_layout: None,
166 cache: cache::Cache::new(),
171 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
176 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
177 self.cache.invalidate();
178 &mut self.basic_blocks
182 pub fn basic_blocks_and_local_decls_mut(
185 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
186 &mut LocalDecls<'tcx>,
188 self.cache.invalidate();
189 (&mut self.basic_blocks, &mut self.local_decls)
193 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
194 self.cache.predecessors(self)
198 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
199 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
203 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
204 let if_zero_locations = if loc.statement_index == 0 {
205 let predecessor_blocks = self.predecessors_for(loc.block);
206 let num_predecessor_blocks = predecessor_blocks.len();
208 (0..num_predecessor_blocks)
209 .map(move |i| predecessor_blocks[i])
210 .map(move |bb| self.terminator_loc(bb)),
216 let if_not_zero_locations = if loc.statement_index == 0 {
221 statement_index: loc.statement_index - 1,
228 .chain(if_not_zero_locations)
232 pub fn dominators(&self) -> Dominators<BasicBlock> {
237 pub fn local_kind(&self, local: Local) -> LocalKind {
238 let index = local.as_usize();
241 self.local_decls[local].mutability == Mutability::Mut,
242 "return place should be mutable"
245 LocalKind::ReturnPointer
246 } else if index < self.arg_count + 1 {
248 } else if self.local_decls[local].name.is_some() {
255 /// Returns an iterator over all temporaries.
257 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
258 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
259 let local = Local::new(index);
260 if self.local_decls[local].is_user_variable.is_some() {
268 /// Returns an iterator over all user-declared locals.
270 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
271 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
272 let local = Local::new(index);
273 if self.local_decls[local].is_user_variable.is_some() {
281 /// Returns an iterator over all user-declared mutable arguments and locals.
283 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
284 (1..self.local_decls.len()).filter_map(move |index| {
285 let local = Local::new(index);
286 let decl = &self.local_decls[local];
287 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
288 && decl.mutability == Mutability::Mut
297 /// Returns an iterator over all function arguments.
299 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
300 let arg_count = self.arg_count;
301 (1..arg_count + 1).map(Local::new)
304 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
305 /// locals that are neither arguments nor the return place).
307 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
308 let arg_count = self.arg_count;
309 let local_count = self.local_decls.len();
310 (arg_count + 1..local_count).map(Local::new)
313 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
314 /// invalidating statement indices in `Location`s.
315 pub fn make_statement_nop(&mut self, location: Location) {
316 let block = &mut self[location.block];
317 debug_assert!(location.statement_index < block.statements.len());
318 block.statements[location.statement_index].make_nop()
321 /// Returns the source info associated with `location`.
322 pub fn source_info(&self, location: Location) -> &SourceInfo {
323 let block = &self[location.block];
324 let stmts = &block.statements;
325 let idx = location.statement_index;
326 if idx < stmts.len() {
327 &stmts[idx].source_info
329 assert_eq!(idx, stmts.len());
330 &block.terminator().source_info
334 /// Check if `sub` is a sub scope of `sup`
335 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
337 match self.source_scopes[sub].parent_scope {
338 None => return false,
345 /// Return the return type, it always return first element from `local_decls` array
346 pub fn return_ty(&self) -> Ty<'tcx> {
347 self.local_decls[RETURN_PLACE].ty
350 /// Get the location of the terminator for the given block
351 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
354 statement_index: self[bb].statements.len(),
359 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
362 /// Unsafe because of a PushUnsafeBlock
364 /// Unsafe because of an unsafe fn
366 /// Unsafe because of an `unsafe` block
367 ExplicitUnsafe(ast::NodeId),
370 impl_stable_hash_for!(struct Mir<'tcx> {
373 source_scope_local_data,
386 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
387 type Output = BasicBlockData<'tcx>;
390 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
391 &self.basic_blocks()[index]
395 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
397 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
398 &mut self.basic_blocks_mut()[index]
402 #[derive(Copy, Clone, Debug)]
403 pub enum ClearCrossCrate<T> {
408 impl<T> ClearCrossCrate<T> {
409 pub fn assert_crate_local(self) -> T {
411 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
412 ClearCrossCrate::Set(v) => v,
417 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
418 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
420 /// Grouped information about the source code origin of a MIR entity.
421 /// Intended to be inspected by diagnostics and debuginfo.
422 /// Most passes can work with it as a whole, within a single function.
423 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
424 pub struct SourceInfo {
425 /// Source span for the AST pertaining to this MIR entity.
428 /// The source scope, keeping track of which bindings can be
429 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
430 pub scope: SourceScope,
433 ///////////////////////////////////////////////////////////////////////////
434 // Mutability and borrow kinds
436 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
437 pub enum Mutability {
442 impl From<Mutability> for hir::Mutability {
443 fn from(m: Mutability) -> Self {
445 Mutability::Mut => hir::MutMutable,
446 Mutability::Not => hir::MutImmutable,
451 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
452 pub enum BorrowKind {
453 /// Data must be immutable and is aliasable.
456 /// The immediately borrowed place must be immutable, but projections from
457 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
458 /// conflict with a mutable borrow of `a.b.c`.
460 /// This is used when lowering matches: when matching on a place we want to
461 /// ensure that place have the same value from the start of the match until
462 /// an arm is selected. This prevents this code from compiling:
464 /// let mut x = &Some(0);
467 /// Some(_) if { x = &None; false } => (),
471 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
472 /// should not prevent `if let None = x { ... }`, for example, because the
473 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
474 /// We can also report errors with this kind of borrow differently.
477 /// Data must be immutable but not aliasable. This kind of borrow
478 /// cannot currently be expressed by the user and is used only in
479 /// implicit closure bindings. It is needed when the closure is
480 /// borrowing or mutating a mutable referent, e.g.:
482 /// let x: &mut isize = ...;
483 /// let y = || *x += 5;
485 /// If we were to try to translate this closure into a more explicit
486 /// form, we'd encounter an error with the code as written:
488 /// struct Env { x: & &mut isize }
489 /// let x: &mut isize = ...;
490 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
491 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
493 /// This is then illegal because you cannot mutate an `&mut` found
494 /// in an aliasable location. To solve, you'd have to translate with
495 /// an `&mut` borrow:
497 /// struct Env { x: & &mut isize }
498 /// let x: &mut isize = ...;
499 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
500 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
502 /// Now the assignment to `**env.x` is legal, but creating a
503 /// mutable pointer to `x` is not because `x` is not mutable. We
504 /// could fix this by declaring `x` as `let mut x`. This is ok in
505 /// user code, if awkward, but extra weird for closures, since the
506 /// borrow is hidden.
508 /// So we introduce a "unique imm" borrow -- the referent is
509 /// immutable, but not aliasable. This solves the problem. For
510 /// simplicity, we don't give users the way to express this
511 /// borrow, it's just used when translating closures.
514 /// Data is mutable and not aliasable.
516 /// True if this borrow arose from method-call auto-ref
517 /// (i.e. `adjustment::Adjust::Borrow`)
518 allow_two_phase_borrow: bool,
523 pub fn allows_two_phase_borrow(&self) -> bool {
525 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
526 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
531 ///////////////////////////////////////////////////////////////////////////
532 // Variables and temps
536 DEBUG_FORMAT = "_{}",
537 const RETURN_PLACE = 0,
541 /// Classifies locals into categories. See `Mir::local_kind`.
542 #[derive(PartialEq, Eq, Debug)]
544 /// User-declared variable binding
546 /// Compiler-introduced temporary
548 /// Function argument
550 /// Location of function's return value
554 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
555 pub struct VarBindingForm<'tcx> {
556 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
557 pub binding_mode: ty::BindingMode,
558 /// If an explicit type was provided for this variable binding,
559 /// this holds the source Span of that type.
561 /// NOTE: If you want to change this to a `HirId`, be wary that
562 /// doing so breaks incremental compilation (as of this writing),
563 /// while a `Span` does not cause our tests to fail.
564 pub opt_ty_info: Option<Span>,
565 /// Place of the RHS of the =, or the subject of the `match` where this
566 /// variable is initialized. None in the case of `let PATTERN;`.
567 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
568 /// (a) the right-hand side isn't evaluated as a place expression.
569 /// (b) it gives a way to separate this case from the remaining cases
571 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
572 /// Span of the pattern in which this variable was bound.
576 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
577 pub enum BindingForm<'tcx> {
578 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
579 Var(VarBindingForm<'tcx>),
580 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
581 ImplicitSelf(ImplicitSelfKind),
582 /// Reference used in a guard expression to ensure immutability.
586 /// Represents what type of implicit self a function has, if any.
587 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
588 pub enum ImplicitSelfKind {
589 /// Represents a `fn x(self);`.
591 /// Represents a `fn x(mut self);`.
593 /// Represents a `fn x(&self);`.
595 /// Represents a `fn x(&mut self);`.
597 /// Represents when a function does not have a self argument or
598 /// when a function has a `self: X` argument.
602 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
604 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
611 impl_stable_hash_for!(enum self::ImplicitSelfKind {
619 mod binding_form_impl {
620 use ich::StableHashingContext;
621 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
623 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
624 fn hash_stable<W: StableHasherResult>(
626 hcx: &mut StableHashingContext<'a>,
627 hasher: &mut StableHasher<W>,
629 use super::BindingForm::*;
630 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
633 Var(binding) => binding.hash_stable(hcx, hasher),
634 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
641 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
642 /// created during evaluation of expressions in a block tail
643 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
645 /// It is used to improve diagnostics when such temporaries are
646 /// involved in borrow_check errors, e.g. explanations of where the
647 /// temporaries come from, when their destructors are run, and/or how
648 /// one might revise the code to satisfy the borrow checker's rules.
649 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
650 pub struct BlockTailInfo {
651 /// If `true`, then the value resulting from evaluating this tail
652 /// expression is ignored by the block's expression context.
654 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
655 /// but not e.g. `let _x = { ...; tail };`
656 pub tail_result_is_ignored: bool,
659 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
663 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
664 /// argument, or the return place.
665 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
666 pub struct LocalDecl<'tcx> {
667 /// `let mut x` vs `let x`.
669 /// Temporaries and the return place are always mutable.
670 pub mutability: Mutability,
672 /// Some(binding_mode) if this corresponds to a user-declared local variable.
674 /// This is solely used for local diagnostics when generating
675 /// warnings/errors when compiling the current crate, and
676 /// therefore it need not be visible across crates. pnkfelix
677 /// currently hypothesized we *need* to wrap this in a
678 /// `ClearCrossCrate` as long as it carries as `HirId`.
679 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
681 /// True if this is an internal local
683 /// These locals are not based on types in the source code and are only used
684 /// for a few desugarings at the moment.
686 /// The generator transformation will sanity check the locals which are live
687 /// across a suspension point against the type components of the generator
688 /// which type checking knows are live across a suspension point. We need to
689 /// flag drop flags to avoid triggering this check as they are introduced
692 /// Unsafety checking will also ignore dereferences of these locals,
693 /// so they can be used for raw pointers only used in a desugaring.
695 /// This should be sound because the drop flags are fully algebraic, and
696 /// therefore don't affect the OIBIT or outlives properties of the
700 /// If this local is a temporary and `is_block_tail` is `Some`,
701 /// then it is a temporary created for evaluation of some
702 /// subexpression of some block's tail expression (with no
703 /// intervening statement context).
704 pub is_block_tail: Option<BlockTailInfo>,
706 /// Type of this local.
709 /// If the user manually ascribed a type to this variable,
710 /// e.g. via `let x: T`, then we carry that type here. The MIR
711 /// borrow checker needs this information since it can affect
712 /// region inference.
713 pub user_ty: UserTypeProjections<'tcx>,
715 /// Name of the local, used in debuginfo and pretty-printing.
717 /// Note that function arguments can also have this set to `Some(_)`
718 /// to generate better debuginfo.
719 pub name: Option<Name>,
721 /// The *syntactic* (i.e. not visibility) source scope the local is defined
722 /// in. If the local was defined in a let-statement, this
723 /// is *within* the let-statement, rather than outside
726 /// This is needed because the visibility source scope of locals within
727 /// a let-statement is weird.
729 /// The reason is that we want the local to be *within* the let-statement
730 /// for lint purposes, but we want the local to be *after* the let-statement
731 /// for names-in-scope purposes.
733 /// That's it, if we have a let-statement like the one in this
737 /// fn foo(x: &str) {
738 /// #[allow(unused_mut)]
739 /// let mut x: u32 = { // <- one unused mut
740 /// let mut y: u32 = x.parse().unwrap();
747 /// Then, from a lint point of view, the declaration of `x: u32`
748 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
749 /// lint scopes are the same as the AST/HIR nesting.
751 /// However, from a name lookup point of view, the scopes look more like
752 /// as if the let-statements were `match` expressions:
755 /// fn foo(x: &str) {
757 /// match x.parse().unwrap() {
766 /// We care about the name-lookup scopes for debuginfo - if the
767 /// debuginfo instruction pointer is at the call to `x.parse()`, we
768 /// want `x` to refer to `x: &str`, but if it is at the call to
769 /// `drop(x)`, we want it to refer to `x: u32`.
771 /// To allow both uses to work, we need to have more than a single scope
772 /// for a local. We have the `source_info.scope` represent the
773 /// "syntactic" lint scope (with a variable being under its let
774 /// block) while the `visibility_scope` represents the "local variable"
775 /// scope (where the "rest" of a block is under all prior let-statements).
777 /// The end result looks like this:
781 /// │{ argument x: &str }
783 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
784 /// │ │ // in practice because I'm lazy.
786 /// │ │← x.source_info.scope
787 /// │ │← `x.parse().unwrap()`
789 /// │ │ │← y.source_info.scope
791 /// │ │ │{ let y: u32 }
793 /// │ │ │← y.visibility_scope
796 /// │ │{ let x: u32 }
797 /// │ │← x.visibility_scope
798 /// │ │← `drop(x)` // this accesses `x: u32`
800 pub source_info: SourceInfo,
802 /// Source scope within which the local is visible (for debuginfo)
803 /// (see `source_info` for more details).
804 pub visibility_scope: SourceScope,
807 impl<'tcx> LocalDecl<'tcx> {
808 /// Returns true only if local is a binding that can itself be
809 /// made mutable via the addition of the `mut` keyword, namely
810 /// something like the occurrences of `x` in:
811 /// - `fn foo(x: Type) { ... }`,
813 /// - or `match ... { C(x) => ... }`
814 pub fn can_be_made_mutable(&self) -> bool {
815 match self.is_user_variable {
816 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
817 binding_mode: ty::BindingMode::BindByValue(_),
823 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
830 /// Returns true if local is definitely not a `ref ident` or
831 /// `ref mut ident` binding. (Such bindings cannot be made into
832 /// mutable bindings, but the inverse does not necessarily hold).
833 pub fn is_nonref_binding(&self) -> bool {
834 match self.is_user_variable {
835 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
836 binding_mode: ty::BindingMode::BindByValue(_),
842 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
848 /// Create a new `LocalDecl` for a temporary.
850 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
851 Self::new_local(ty, Mutability::Mut, false, span)
854 /// Converts `self` into same `LocalDecl` except tagged as immutable.
856 pub fn immutable(mut self) -> Self {
857 self.mutability = Mutability::Not;
861 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
863 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
864 assert!(self.is_block_tail.is_none());
865 self.is_block_tail = Some(info);
869 /// Create a new `LocalDecl` for a internal temporary.
871 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
872 Self::new_local(ty, Mutability::Mut, true, span)
878 mutability: Mutability,
885 user_ty: UserTypeProjections::none(),
887 source_info: SourceInfo {
889 scope: OUTERMOST_SOURCE_SCOPE,
891 visibility_scope: OUTERMOST_SOURCE_SCOPE,
893 is_user_variable: None,
898 /// Builds a `LocalDecl` for the return place.
900 /// This must be inserted into the `local_decls` list as the first local.
902 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
904 mutability: Mutability::Mut,
906 user_ty: UserTypeProjections::none(),
907 source_info: SourceInfo {
909 scope: OUTERMOST_SOURCE_SCOPE,
911 visibility_scope: OUTERMOST_SOURCE_SCOPE,
914 name: None, // FIXME maybe we do want some name here?
915 is_user_variable: None,
920 /// A closure capture, with its name and mode.
921 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
922 pub struct UpvarDecl {
923 pub debug_name: Name,
925 /// `HirId` of the captured variable
926 pub var_hir_id: ClearCrossCrate<HirId>,
928 /// If true, the capture is behind a reference.
931 pub mutability: Mutability,
934 ///////////////////////////////////////////////////////////////////////////
938 pub struct BasicBlock {
939 DEBUG_FORMAT = "bb{}",
940 const START_BLOCK = 0,
945 pub fn start_location(self) -> Location {
953 ///////////////////////////////////////////////////////////////////////////
954 // BasicBlockData and Terminator
956 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
957 pub struct BasicBlockData<'tcx> {
958 /// List of statements in this block.
959 pub statements: Vec<Statement<'tcx>>,
961 /// Terminator for this block.
963 /// NB. This should generally ONLY be `None` during construction.
964 /// Therefore, you should generally access it via the
965 /// `terminator()` or `terminator_mut()` methods. The only
966 /// exception is that certain passes, such as `simplify_cfg`, swap
967 /// out the terminator temporarily with `None` while they continue
968 /// to recurse over the set of basic blocks.
969 pub terminator: Option<Terminator<'tcx>>,
971 /// If true, this block lies on an unwind path. This is used
972 /// during codegen where distinct kinds of basic blocks may be
973 /// generated (particularly for MSVC cleanup). Unwind blocks must
974 /// only branch to other unwind blocks.
975 pub is_cleanup: bool,
978 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
979 pub struct Terminator<'tcx> {
980 pub source_info: SourceInfo,
981 pub kind: TerminatorKind<'tcx>,
984 #[derive(Clone, RustcEncodable, RustcDecodable)]
985 pub enum TerminatorKind<'tcx> {
986 /// block should have one successor in the graph; we jump there
987 Goto { target: BasicBlock },
989 /// operand evaluates to an integer; jump depending on its value
990 /// to one of the targets, and otherwise fallback to `otherwise`
992 /// discriminant value being tested
993 discr: Operand<'tcx>,
995 /// type of value being tested
998 /// Possible values. The locations to branch to in each case
999 /// are found in the corresponding indices from the `targets` vector.
1000 values: Cow<'tcx, [u128]>,
1002 /// Possible branch sites. The last element of this vector is used
1003 /// for the otherwise branch, so targets.len() == values.len() + 1
1005 // This invariant is quite non-obvious and also could be improved.
1006 // One way to make this invariant is to have something like this instead:
1008 // branches: Vec<(ConstInt, BasicBlock)>,
1009 // otherwise: Option<BasicBlock> // exhaustive if None
1011 // However we’ve decided to keep this as-is until we figure a case
1012 // where some other approach seems to be strictly better than other.
1013 targets: Vec<BasicBlock>,
1016 /// Indicates that the landing pad is finished and unwinding should
1017 /// continue. Emitted by build::scope::diverge_cleanup.
1020 /// Indicates that the landing pad is finished and that the process
1021 /// should abort. Used to prevent unwinding for foreign items.
1024 /// Indicates a normal return. The return place should have
1025 /// been filled in by now. This should occur at most once.
1028 /// Indicates a terminator that can never be reached.
1033 location: Place<'tcx>,
1035 unwind: Option<BasicBlock>,
1038 /// Drop the Place and assign the new value over it. This ensures
1039 /// that the assignment to `P` occurs *even if* the destructor for
1040 /// place unwinds. Its semantics are best explained by the
1045 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1053 /// Drop(P, goto BB1, unwind BB2)
1056 /// // P is now uninitialized
1060 /// // P is now uninitialized -- its dtor panicked
1065 location: Place<'tcx>,
1066 value: Operand<'tcx>,
1068 unwind: Option<BasicBlock>,
1071 /// Block ends with a call of a converging function
1073 /// The function that’s being called
1074 func: Operand<'tcx>,
1075 /// Arguments the function is called with.
1076 /// These are owned by the callee, which is free to modify them.
1077 /// This allows the memory occupied by "by-value" arguments to be
1078 /// reused across function calls without duplicating the contents.
1079 args: Vec<Operand<'tcx>>,
1080 /// Destination for the return value. If some, the call is converging.
1081 destination: Option<(Place<'tcx>, BasicBlock)>,
1082 /// Cleanups to be done if the call unwinds.
1083 cleanup: Option<BasicBlock>,
1084 /// Whether this is from a call in HIR, rather than from an overloaded
1085 /// operator. True for overloaded function call.
1086 from_hir_call: bool,
1089 /// Jump to the target if the condition has the expected value,
1090 /// otherwise panic with a message and a cleanup target.
1092 cond: Operand<'tcx>,
1094 msg: AssertMessage<'tcx>,
1096 cleanup: Option<BasicBlock>,
1101 /// The value to return
1102 value: Operand<'tcx>,
1103 /// Where to resume to
1105 /// Cleanup to be done if the generator is dropped at this suspend point
1106 drop: Option<BasicBlock>,
1109 /// Indicates the end of the dropping of a generator
1112 /// A block where control flow only ever takes one real path, but borrowck
1113 /// needs to be more conservative.
1115 /// The target normal control flow will take
1116 real_target: BasicBlock,
1117 /// The list of blocks control flow could conceptually take, but won't
1119 imaginary_targets: Vec<BasicBlock>,
1121 /// A terminator for blocks that only take one path in reality, but where we
1122 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1123 /// This can arise in infinite loops with no function calls for example.
1125 /// The target normal control flow will take
1126 real_target: BasicBlock,
1127 /// The imaginary cleanup block link. This particular path will never be taken
1128 /// in practice, but in order to avoid fragility we want to always
1129 /// consider it in borrowck. We don't want to accept programs which
1130 /// pass borrowck only when panic=abort or some assertions are disabled
1131 /// due to release vs. debug mode builds. This needs to be an Option because
1132 /// of the remove_noop_landing_pads and no_landing_pads passes
1133 unwind: Option<BasicBlock>,
1137 pub type Successors<'a> =
1138 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1139 pub type SuccessorsMut<'a> =
1140 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1142 impl<'tcx> Terminator<'tcx> {
1143 pub fn successors(&self) -> Successors<'_> {
1144 self.kind.successors()
1147 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1148 self.kind.successors_mut()
1151 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1155 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1156 self.kind.unwind_mut()
1160 impl<'tcx> TerminatorKind<'tcx> {
1161 pub fn if_<'a, 'gcx>(
1162 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1163 cond: Operand<'tcx>,
1166 ) -> TerminatorKind<'tcx> {
1167 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1168 TerminatorKind::SwitchInt {
1170 switch_ty: tcx.types.bool,
1171 values: From::from(BOOL_SWITCH_FALSE),
1172 targets: vec![f, t],
1176 pub fn successors(&self) -> Successors<'_> {
1177 use self::TerminatorKind::*;
1188 } => None.into_iter().chain(&[]),
1189 Goto { target: ref t }
1192 cleanup: Some(ref t),
1196 destination: Some((_, ref t)),
1223 } => Some(t).into_iter().chain(&[]),
1225 destination: Some((_, ref t)),
1226 cleanup: Some(ref u),
1236 unwind: Some(ref u),
1241 unwind: Some(ref u),
1246 cleanup: Some(ref u),
1251 unwind: Some(ref u),
1252 } => Some(t).into_iter().chain(slice::from_ref(u)),
1253 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1256 ref imaginary_targets,
1257 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1261 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1262 use self::TerminatorKind::*;
1273 } => None.into_iter().chain(&mut []),
1274 Goto { target: ref mut t }
1277 cleanup: Some(ref mut t),
1281 destination: Some((_, ref mut t)),
1306 real_target: ref mut t,
1308 } => Some(t).into_iter().chain(&mut []),
1310 destination: Some((_, ref mut t)),
1311 cleanup: Some(ref mut u),
1316 drop: Some(ref mut u),
1321 unwind: Some(ref mut u),
1326 unwind: Some(ref mut u),
1331 cleanup: Some(ref mut u),
1335 real_target: ref mut t,
1336 unwind: Some(ref mut u),
1337 } => Some(t).into_iter().chain(slice::from_mut(u)),
1340 } => None.into_iter().chain(&mut targets[..]),
1342 ref mut real_target,
1343 ref mut imaginary_targets,
1344 } => Some(real_target)
1346 .chain(&mut imaginary_targets[..]),
1350 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1352 TerminatorKind::Goto { .. }
1353 | TerminatorKind::Resume
1354 | TerminatorKind::Abort
1355 | TerminatorKind::Return
1356 | TerminatorKind::Unreachable
1357 | TerminatorKind::GeneratorDrop
1358 | TerminatorKind::Yield { .. }
1359 | TerminatorKind::SwitchInt { .. }
1360 | TerminatorKind::FalseEdges { .. } => None,
1361 TerminatorKind::Call {
1362 cleanup: ref unwind,
1365 | TerminatorKind::Assert {
1366 cleanup: ref unwind,
1369 | TerminatorKind::DropAndReplace { ref unwind, .. }
1370 | TerminatorKind::Drop { ref unwind, .. }
1371 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1375 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1377 TerminatorKind::Goto { .. }
1378 | TerminatorKind::Resume
1379 | TerminatorKind::Abort
1380 | TerminatorKind::Return
1381 | TerminatorKind::Unreachable
1382 | TerminatorKind::GeneratorDrop
1383 | TerminatorKind::Yield { .. }
1384 | TerminatorKind::SwitchInt { .. }
1385 | TerminatorKind::FalseEdges { .. } => None,
1386 TerminatorKind::Call {
1387 cleanup: ref mut unwind,
1390 | TerminatorKind::Assert {
1391 cleanup: ref mut unwind,
1394 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1395 | TerminatorKind::Drop { ref mut unwind, .. }
1396 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1401 impl<'tcx> BasicBlockData<'tcx> {
1402 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1410 /// Accessor for terminator.
1412 /// Terminator may not be None after construction of the basic block is complete. This accessor
1413 /// provides a convenience way to reach the terminator.
1414 pub fn terminator(&self) -> &Terminator<'tcx> {
1415 self.terminator.as_ref().expect("invalid terminator state")
1418 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1419 self.terminator.as_mut().expect("invalid terminator state")
1422 pub fn retain_statements<F>(&mut self, mut f: F)
1424 F: FnMut(&mut Statement<'_>) -> bool,
1426 for s in &mut self.statements {
1433 pub fn expand_statements<F, I>(&mut self, mut f: F)
1435 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1436 I: iter::TrustedLen<Item = Statement<'tcx>>,
1438 // Gather all the iterators we'll need to splice in, and their positions.
1439 let mut splices: Vec<(usize, I)> = vec![];
1440 let mut extra_stmts = 0;
1441 for (i, s) in self.statements.iter_mut().enumerate() {
1442 if let Some(mut new_stmts) = f(s) {
1443 if let Some(first) = new_stmts.next() {
1444 // We can already store the first new statement.
1447 // Save the other statements for optimized splicing.
1448 let remaining = new_stmts.size_hint().0;
1450 splices.push((i + 1 + extra_stmts, new_stmts));
1451 extra_stmts += remaining;
1459 // Splice in the new statements, from the end of the block.
1460 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1461 // where a range of elements ("gap") is left uninitialized, with
1462 // splicing adding new elements to the end of that gap and moving
1463 // existing elements from before the gap to the end of the gap.
1464 // For now, this is safe code, emulating a gap but initializing it.
1465 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1466 self.statements.resize(
1469 source_info: SourceInfo {
1471 scope: OUTERMOST_SOURCE_SCOPE,
1473 kind: StatementKind::Nop,
1476 for (splice_start, new_stmts) in splices.into_iter().rev() {
1477 let splice_end = splice_start + new_stmts.size_hint().0;
1478 while gap.end > splice_end {
1481 self.statements.swap(gap.start, gap.end);
1483 self.statements.splice(splice_start..splice_end, new_stmts);
1484 gap.end = splice_start;
1488 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1489 if index < self.statements.len() {
1490 &self.statements[index]
1497 impl<'tcx> Debug for TerminatorKind<'tcx> {
1498 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1499 self.fmt_head(fmt)?;
1500 let successor_count = self.successors().count();
1501 let labels = self.fmt_successor_labels();
1502 assert_eq!(successor_count, labels.len());
1504 match successor_count {
1507 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1510 write!(fmt, " -> [")?;
1511 for (i, target) in self.successors().enumerate() {
1515 write!(fmt, "{}: {:?}", labels[i], target)?;
1523 impl<'tcx> TerminatorKind<'tcx> {
1524 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1525 /// successor basic block, if any. The only information not included is the list of possible
1526 /// successors, which may be rendered differently between the text and the graphviz format.
1527 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1528 use self::TerminatorKind::*;
1530 Goto { .. } => write!(fmt, "goto"),
1532 discr: ref place, ..
1533 } => write!(fmt, "switchInt({:?})", place),
1534 Return => write!(fmt, "return"),
1535 GeneratorDrop => write!(fmt, "generator_drop"),
1536 Resume => write!(fmt, "resume"),
1537 Abort => write!(fmt, "abort"),
1538 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1539 Unreachable => write!(fmt, "unreachable"),
1540 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1545 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1552 if let Some((ref destination, _)) = *destination {
1553 write!(fmt, "{:?} = ", destination)?;
1555 write!(fmt, "{:?}(", func)?;
1556 for (index, arg) in args.iter().enumerate() {
1560 write!(fmt, "{:?}", arg)?;
1570 write!(fmt, "assert(")?;
1574 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1576 FalseEdges { .. } => write!(fmt, "falseEdges"),
1577 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1581 /// Return the list of labels for the edges to the successor basic blocks.
1582 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1583 use self::TerminatorKind::*;
1585 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1586 Goto { .. } => vec!["".into()],
1592 let size = ty::tls::with(|tcx| {
1593 let param_env = ty::ParamEnv::empty();
1594 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1595 tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1600 let mut s = String::new();
1602 val: ConstValue::Scalar(
1605 size: size.bytes() as u8,
1610 fmt_const_val(&mut s, &c).unwrap();
1612 }).chain(iter::once("otherwise".into()))
1616 destination: Some(_),
1619 } => vec!["return".into(), "unwind".into()],
1621 destination: Some(_),
1624 } => vec!["return".into()],
1629 } => vec!["unwind".into()],
1635 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1636 Yield { drop: None, .. } => vec!["resume".into()],
1637 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1638 vec!["return".into()]
1645 } => vec!["return".into(), "unwind".into()],
1646 Assert { cleanup: None, .. } => vec!["".into()],
1647 Assert { .. } => vec!["success".into(), "unwind".into()],
1649 ref imaginary_targets,
1652 let mut l = vec!["real".into()];
1653 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1658 } => vec!["real".into(), "cleanup".into()],
1659 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1664 ///////////////////////////////////////////////////////////////////////////
1667 #[derive(Clone, RustcEncodable, RustcDecodable)]
1668 pub struct Statement<'tcx> {
1669 pub source_info: SourceInfo,
1670 pub kind: StatementKind<'tcx>,
1673 impl<'tcx> Statement<'tcx> {
1674 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1675 /// invalidating statement indices in `Location`s.
1676 pub fn make_nop(&mut self) {
1677 // `Statement` contributes significantly to peak memory usage. Make
1678 // sure it doesn't get bigger.
1679 static_assert!(STATEMENT_IS_AT_MOST_56_BYTES: mem::size_of::<Statement<'_>>() <= 56);
1681 self.kind = StatementKind::Nop
1684 /// Changes a statement to a nop and returns the original statement.
1685 pub fn replace_nop(&mut self) -> Self {
1687 source_info: self.source_info,
1688 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1693 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1694 pub enum StatementKind<'tcx> {
1695 /// Write the RHS Rvalue to the LHS Place.
1696 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1698 /// This represents all the reading that a pattern match may do
1699 /// (e.g. inspecting constants and discriminant values), and the
1700 /// kind of pattern it comes from. This is in order to adapt potential
1701 /// error messages to these specific patterns.
1702 FakeRead(FakeReadCause, Place<'tcx>),
1704 /// Write the discriminant for a variant to the enum Place.
1707 variant_index: usize,
1710 /// Start a live range for the storage of the local.
1713 /// End the current live range for the storage of the local.
1716 /// Execute a piece of inline Assembly.
1718 asm: Box<InlineAsm>,
1719 outputs: Box<[Place<'tcx>]>,
1720 inputs: Box<[Operand<'tcx>]>,
1723 /// Assert the given places to be valid inhabitants of their type. These statements are
1724 /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1725 /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1726 Validate(ValidationOp, Vec<ValidationOperand<'tcx, Place<'tcx>>>),
1728 /// Mark one terminating point of a region scope (i.e. static region).
1729 /// (The starting point(s) arise implicitly from borrows.)
1730 EndRegion(region::Scope),
1732 /// Encodes a user's type ascription. These need to be preserved
1733 /// intact so that NLL can respect them. For example:
1737 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1738 /// to the user-given type `T`. The effect depends on the specified variance:
1740 /// - `Covariant` -- requires that `T_y <: T`
1741 /// - `Contravariant` -- requires that `T_y :> T`
1742 /// - `Invariant` -- requires that `T_y == T`
1743 /// - `Bivariant` -- no effect
1744 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection<'tcx>>),
1746 /// No-op. Useful for deleting instructions without affecting statement indices.
1750 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1751 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1752 pub enum FakeReadCause {
1753 /// Inject a fake read of the borrowed input at the start of each arm's
1754 /// pattern testing code.
1756 /// This should ensure that you cannot change the variant for an enum
1757 /// while you are in the midst of matching on it.
1760 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1761 /// generate a read of x to check that it is initialized and safe.
1764 /// Officially, the semantics of
1766 /// `let pattern = <expr>;`
1768 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1769 /// into the pattern.
1771 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1772 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1773 /// but in some cases it can affect the borrow checker, as in #53695.
1774 /// Therefore, we insert a "fake read" here to ensure that we get
1775 /// appropriate errors.
1779 /// The `ValidationOp` describes what happens with each of the operands of a
1780 /// `Validate` statement.
1781 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1782 pub enum ValidationOp {
1783 /// Recursively traverse the place following the type and validate that all type
1784 /// invariants are maintained. Furthermore, acquire exclusive/read-only access to the
1785 /// memory reachable from the place.
1787 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1790 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1791 /// access *until* the given region ends. Then, access will be recovered.
1792 Suspend(region::Scope),
1795 impl Debug for ValidationOp {
1796 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1797 use self::ValidationOp::*;
1799 Acquire => write!(fmt, "Acquire"),
1800 Release => write!(fmt, "Release"),
1801 // (reuse lifetime rendering policy from ppaux.)
1802 Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1807 // This is generic so that it can be reused by miri
1808 #[derive(Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1809 pub struct ValidationOperand<'tcx, T> {
1812 pub re: Option<region::Scope>,
1813 pub mutbl: hir::Mutability,
1816 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1817 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1818 write!(fmt, "{:?}: {:?}", self.place, self.ty)?;
1819 if let Some(ce) = self.re {
1820 // (reuse lifetime rendering policy from ppaux.)
1821 write!(fmt, "/{}", ty::ReScope(ce))?;
1823 if let hir::MutImmutable = self.mutbl {
1824 write!(fmt, " (imm)")?;
1830 impl<'tcx> Debug for Statement<'tcx> {
1831 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1832 use self::StatementKind::*;
1834 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1835 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1836 // (reuse lifetime rendering policy from ppaux.)
1837 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1838 Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
1839 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1840 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1844 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1849 } => write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs),
1850 AscribeUserType(ref place, ref variance, ref c_ty) => {
1851 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1853 Nop => write!(fmt, "nop"),
1858 ///////////////////////////////////////////////////////////////////////////
1861 /// A path to a value; something that can be evaluated without
1862 /// changing or disturbing program state.
1863 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1864 pub enum Place<'tcx> {
1868 /// static or static mut variable
1869 Static(Box<Static<'tcx>>),
1871 /// Constant code promoted to an injected static
1872 Promoted(Box<(Promoted, Ty<'tcx>)>),
1874 /// projection out of a place (access a field, deref a pointer, etc)
1875 Projection(Box<PlaceProjection<'tcx>>),
1878 /// The def-id of a static, along with its normalized type (which is
1879 /// stored to avoid requiring normalization when reading MIR).
1880 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1881 pub struct Static<'tcx> {
1886 impl_stable_hash_for!(struct Static<'tcx> {
1891 /// The `Projection` data structure defines things of the form `B.x`
1892 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1893 /// shared between `Constant` and `Place`. See the aliases
1894 /// `PlaceProjection` etc below.
1895 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1896 pub struct Projection<'tcx, B, V, T> {
1898 pub elem: ProjectionElem<'tcx, V, T>,
1901 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1902 pub enum ProjectionElem<'tcx, V, T> {
1907 /// These indices are generated by slice patterns. Easiest to explain
1911 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1912 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1913 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1914 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1917 /// index or -index (in Python terms), depending on from_end
1919 /// thing being indexed must be at least this long
1921 /// counting backwards from end?
1925 /// These indices are generated by slice patterns.
1927 /// slice[from:-to] in Python terms.
1933 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1934 /// this for ADTs with more than one variant. It may be better to
1935 /// just introduce it always, or always for enums.
1936 Downcast(&'tcx AdtDef, usize),
1939 /// Alias for projections as they appear in places, where the base is a place
1940 /// and the index is a local.
1941 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1943 /// Alias for projections as they appear in places, where the base is a place
1944 /// and the index is a local.
1945 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1947 /// Alias for projections as they appear in `UserTypeProjection`, where we
1948 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1949 pub type ProjectionKind<'tcx> = ProjectionElem<'tcx, (), ()>;
1953 DEBUG_FORMAT = "field[{}]"
1957 impl<'tcx> Place<'tcx> {
1958 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1959 self.elem(ProjectionElem::Field(f, ty))
1962 pub fn deref(self) -> Place<'tcx> {
1963 self.elem(ProjectionElem::Deref)
1966 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1967 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1970 pub fn index(self, index: Local) -> Place<'tcx> {
1971 self.elem(ProjectionElem::Index(index))
1974 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1975 Place::Projection(Box::new(PlaceProjection { base: self, elem }))
1978 /// Find the innermost `Local` from this `Place`, *if* it is either a local itself or
1979 /// a single deref of a local.
1981 /// FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1982 pub fn local(&self) -> Option<Local> {
1984 Place::Local(local) |
1985 Place::Projection(box Projection {
1986 base: Place::Local(local),
1987 elem: ProjectionElem::Deref,
1993 /// Find the innermost `Local` from this `Place`.
1994 pub fn base_local(&self) -> Option<Local> {
1996 Place::Local(local) => Some(*local),
1997 Place::Projection(box Projection { base, elem: _ }) => base.base_local(),
1998 Place::Promoted(..) | Place::Static(..) => None,
2003 impl<'tcx> Debug for Place<'tcx> {
2004 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2008 Local(id) => write!(fmt, "{:?}", id),
2009 Static(box self::Static { def_id, ty }) => write!(
2012 ty::tls::with(|tcx| tcx.item_path_str(def_id)),
2015 Promoted(ref promoted) => write!(fmt, "({:?}: {:?})", promoted.0, promoted.1),
2016 Projection(ref data) => match data.elem {
2017 ProjectionElem::Downcast(ref adt_def, index) => {
2018 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name)
2020 ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
2021 ProjectionElem::Field(field, ty) => {
2022 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
2024 ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
2025 ProjectionElem::ConstantIndex {
2029 } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
2030 ProjectionElem::ConstantIndex {
2034 } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
2035 ProjectionElem::Subslice { from, to } if to == 0 => {
2036 write!(fmt, "{:?}[{:?}:]", data.base, from)
2038 ProjectionElem::Subslice { from, to } if from == 0 => {
2039 write!(fmt, "{:?}[:-{:?}]", data.base, to)
2041 ProjectionElem::Subslice { from, to } => {
2042 write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
2049 ///////////////////////////////////////////////////////////////////////////
2053 pub struct SourceScope {
2054 DEBUG_FORMAT = "scope[{}]",
2055 const OUTERMOST_SOURCE_SCOPE = 0,
2059 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2060 pub struct SourceScopeData {
2062 pub parent_scope: Option<SourceScope>,
2065 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2066 pub struct SourceScopeLocalData {
2067 /// A NodeId with lint levels equivalent to this scope's lint levels.
2068 pub lint_root: ast::NodeId,
2069 /// The unsafe block that contains this node.
2073 ///////////////////////////////////////////////////////////////////////////
2076 /// These are values that can appear inside an rvalue. They are intentionally
2077 /// limited to prevent rvalues from being nested in one another.
2078 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
2079 pub enum Operand<'tcx> {
2080 /// Copy: The value must be available for use afterwards.
2082 /// This implies that the type of the place must be `Copy`; this is true
2083 /// by construction during build, but also checked by the MIR type checker.
2086 /// Move: The value (including old borrows of it) will not be used again.
2088 /// Safe for values of all types (modulo future developments towards `?Move`).
2089 /// Correct usage patterns are enforced by the borrow checker for safe code.
2090 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2093 /// Synthesizes a constant value.
2094 Constant(Box<Constant<'tcx>>),
2097 impl<'tcx> Debug for Operand<'tcx> {
2098 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2099 use self::Operand::*;
2101 Constant(ref a) => write!(fmt, "{:?}", a),
2102 Copy(ref place) => write!(fmt, "{:?}", place),
2103 Move(ref place) => write!(fmt, "move {:?}", place),
2108 impl<'tcx> Operand<'tcx> {
2109 /// Convenience helper to make a constant that refers to the fn
2110 /// with given def-id and substs. Since this is used to synthesize
2111 /// MIR, assumes `user_ty` is None.
2112 pub fn function_handle<'a>(
2113 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2115 substs: &'tcx Substs<'tcx>,
2118 let ty = tcx.type_of(def_id).subst(tcx, substs);
2119 Operand::Constant(box Constant {
2123 literal: ty::Const::zero_sized(tcx, ty),
2127 pub fn to_copy(&self) -> Self {
2129 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2130 Operand::Move(ref place) => Operand::Copy(place.clone()),
2135 ///////////////////////////////////////////////////////////////////////////
2138 #[derive(Clone, RustcEncodable, RustcDecodable)]
2139 pub enum Rvalue<'tcx> {
2140 /// x (either a move or copy, depending on type of x)
2144 Repeat(Operand<'tcx>, u64),
2147 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2149 /// length of a [X] or [X;n] value
2152 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2154 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2155 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2157 NullaryOp(NullOp, Ty<'tcx>),
2158 UnaryOp(UnOp, Operand<'tcx>),
2160 /// Read the discriminant of an ADT.
2162 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
2163 /// be defined to return, say, a 0) if ADT is not an enum.
2164 Discriminant(Place<'tcx>),
2166 /// Create an aggregate value, like a tuple or struct. This is
2167 /// only needed because we want to distinguish `dest = Foo { x:
2168 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2169 /// that `Foo` has a destructor. These rvalues can be optimized
2170 /// away after type-checking and before lowering.
2171 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2174 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2178 /// Convert unique, zero-sized type for a fn to fn()
2181 /// Convert non capturing closure to fn()
2184 /// Convert safe fn() to unsafe fn()
2187 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
2188 /// codegen must figure out the details once full monomorphization
2189 /// is known. For example, this could be used to cast from a
2190 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
2191 /// (presuming `T: Trait`).
2195 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2196 pub enum AggregateKind<'tcx> {
2197 /// The type is of the element
2201 /// The second field is the variant index. It's equal to 0 for struct
2202 /// and union expressions. The fourth field is
2203 /// active field number and is present only for union expressions
2204 /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
2205 /// active field index would identity the field `c`
2210 Option<UserTypeAnnotation<'tcx>>,
2214 Closure(DefId, ClosureSubsts<'tcx>),
2215 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2218 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2220 /// The `+` operator (addition)
2222 /// The `-` operator (subtraction)
2224 /// The `*` operator (multiplication)
2226 /// The `/` operator (division)
2228 /// The `%` operator (modulus)
2230 /// The `^` operator (bitwise xor)
2232 /// The `&` operator (bitwise and)
2234 /// The `|` operator (bitwise or)
2236 /// The `<<` operator (shift left)
2238 /// The `>>` operator (shift right)
2240 /// The `==` operator (equality)
2242 /// The `<` operator (less than)
2244 /// The `<=` operator (less than or equal to)
2246 /// The `!=` operator (not equal to)
2248 /// The `>=` operator (greater than or equal to)
2250 /// The `>` operator (greater than)
2252 /// The `ptr.offset` operator
2257 pub fn is_checkable(self) -> bool {
2260 Add | Sub | Mul | Shl | Shr => true,
2266 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2268 /// Return the size of a value of that type
2270 /// Create a new uninitialized box for a value of that type
2274 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2276 /// The `!` operator for logical inversion
2278 /// The `-` operator for negation
2282 impl<'tcx> Debug for Rvalue<'tcx> {
2283 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2284 use self::Rvalue::*;
2287 Use(ref place) => write!(fmt, "{:?}", place),
2288 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2289 Len(ref a) => write!(fmt, "Len({:?})", a),
2290 Cast(ref kind, ref place, ref ty) => {
2291 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2293 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2294 CheckedBinaryOp(ref op, ref a, ref b) => {
2295 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2297 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2298 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2299 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2300 Ref(region, borrow_kind, ref place) => {
2301 let kind_str = match borrow_kind {
2302 BorrowKind::Shared => "",
2303 BorrowKind::Shallow => "shallow ",
2304 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2307 // When printing regions, add trailing space if necessary.
2308 let region = if ppaux::verbose() || ppaux::identify_regions() {
2309 let mut region = region.to_string();
2310 if region.len() > 0 {
2315 // Do not even print 'static
2318 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2321 Aggregate(ref kind, ref places) => {
2322 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2323 let mut tuple_fmt = fmt.debug_tuple("");
2324 for place in places {
2325 tuple_fmt.field(place);
2331 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2333 AggregateKind::Tuple => match places.len() {
2334 0 => write!(fmt, "()"),
2335 1 => write!(fmt, "({:?},)", places[0]),
2336 _ => fmt_tuple(fmt, places),
2339 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2340 let variant_def = &adt_def.variants[variant];
2342 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
2344 match variant_def.ctor_kind {
2345 CtorKind::Const => Ok(()),
2346 CtorKind::Fn => fmt_tuple(fmt, places),
2347 CtorKind::Fictive => {
2348 let mut struct_fmt = fmt.debug_struct("");
2349 for (field, place) in variant_def.fields.iter().zip(places) {
2350 struct_fmt.field(&field.ident.as_str(), place);
2357 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2358 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2359 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2360 format!("[closure@{:?}]", node_id)
2362 format!("[closure@{:?}]", tcx.hir.span(node_id))
2364 let mut struct_fmt = fmt.debug_struct(&name);
2366 tcx.with_freevars(node_id, |freevars| {
2367 for (freevar, place) in freevars.iter().zip(places) {
2368 let var_name = tcx.hir.name(freevar.var_id());
2369 struct_fmt.field(&var_name.as_str(), place);
2375 write!(fmt, "[closure]")
2379 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2380 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2381 let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
2382 let mut struct_fmt = fmt.debug_struct(&name);
2384 tcx.with_freevars(node_id, |freevars| {
2385 for (freevar, place) in freevars.iter().zip(places) {
2386 let var_name = tcx.hir.name(freevar.var_id());
2387 struct_fmt.field(&var_name.as_str(), place);
2389 struct_fmt.field("$state", &places[freevars.len()]);
2390 for i in (freevars.len() + 1)..places.len() {
2392 .field(&format!("${}", i - freevars.len() - 1), &places[i]);
2398 write!(fmt, "[generator]")
2407 ///////////////////////////////////////////////////////////////////////////
2410 /// Two constants are equal if they are the same constant. Note that
2411 /// this does not necessarily mean that they are "==" in Rust -- in
2412 /// particular one must be wary of `NaN`!
2414 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2415 pub struct Constant<'tcx> {
2419 /// Optional user-given type: for something like
2420 /// `collect::<Vec<_>>`, this would be present and would
2421 /// indicate that `Vec<_>` was explicitly specified.
2423 /// Needed for NLL to impose user-given type constraints.
2424 pub user_ty: Option<UserTypeAnnotation<'tcx>>,
2426 pub literal: &'tcx ty::Const<'tcx>,
2429 /// A user-given type annotation attached to a constant. These arise
2430 /// from constants that are named via paths, like `Foo::<A>::new` and
2432 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2433 pub enum UserTypeAnnotation<'tcx> {
2434 Ty(CanonicalTy<'tcx>),
2436 /// The canonical type is the result of `type_of(def_id)` with the
2437 /// given substitutions applied.
2438 TypeOf(DefId, CanonicalUserSubsts<'tcx>),
2441 EnumTypeFoldableImpl! {
2442 impl<'tcx> TypeFoldable<'tcx> for UserTypeAnnotation<'tcx> {
2443 (UserTypeAnnotation::Ty)(ty),
2444 (UserTypeAnnotation::TypeOf)(def, substs),
2449 impl<'a, 'tcx> Lift<'tcx> for UserTypeAnnotation<'a> {
2450 type Lifted = UserTypeAnnotation<'tcx>;
2451 (UserTypeAnnotation::Ty)(ty),
2452 (UserTypeAnnotation::TypeOf)(def, substs),
2456 /// A collection of projections into user types.
2458 /// They are projections because a binding can occur a part of a
2459 /// parent pattern that has been ascribed a type.
2461 /// Its a collection because there can be multiple type ascriptions on
2462 /// the path from the root of the pattern down to the binding itself.
2467 /// struct S<'a>((i32, &'a str), String);
2468 /// let S((_, w): (i32, &'static str), _): S = ...;
2469 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2470 /// // --------------------------------- ^ (2)
2473 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2474 /// ascribed the type `(i32, &'static str)`.
2476 /// The highlights labelled `(2)` show the whole pattern being
2477 /// ascribed the type `S`.
2479 /// In this example, when we descend to `w`, we will have built up the
2480 /// following two projected types:
2482 /// * base: `S`, projection: `(base.0).1`
2483 /// * base: `(i32, &'static str)`, projection: `base.1`
2485 /// The first will lead to the constraint `w: &'1 str` (for some
2486 /// inferred region `'1`). The second will lead to the constraint `w:
2488 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2489 pub struct UserTypeProjections<'tcx> {
2490 pub(crate) contents: Vec<(UserTypeProjection<'tcx>, Span)>,
2493 BraceStructTypeFoldableImpl! {
2494 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections<'tcx> {
2499 impl<'tcx> UserTypeProjections<'tcx> {
2500 pub fn none() -> Self {
2501 UserTypeProjections { contents: vec![] }
2504 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection<'tcx>, Span)>) -> Self {
2505 UserTypeProjections { contents: projs.collect() }
2508 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection<'tcx>, Span)> {
2509 self.contents.iter()
2512 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection<'tcx>> {
2513 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2517 /// Encodes the effect of a user-supplied type annotation on the
2518 /// subcomponents of a pattern. The effect is determined by applying the
2519 /// given list of proejctions to some underlying base type. Often,
2520 /// the projection element list `projs` is empty, in which case this
2521 /// directly encodes a type in `base`. But in the case of complex patterns with
2522 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2523 /// in which case the `projs` vector is used.
2527 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2529 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2530 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2531 /// determined by finding the type of the `.0` field from `T`.
2532 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2533 pub struct UserTypeProjection<'tcx> {
2534 pub base: UserTypeAnnotation<'tcx>,
2535 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
2538 impl<'tcx> Copy for ProjectionKind<'tcx> { }
2540 CloneTypeFoldableAndLiftImpls! { ProjectionKind<'tcx>, }
2542 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection<'tcx> {
2543 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2544 use mir::ProjectionElem::*;
2546 let base = self.base.fold_with(folder);
2547 let projs: Vec<_> = self.projs
2552 Field(f, ()) => Field(f.clone(), ()),
2553 Index(()) => Index(()),
2554 elem => elem.clone(),
2558 UserTypeProjection { base, projs }
2561 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2562 self.base.visit_with(visitor)
2563 // Note: there's nothing in `self.proj` to visit.
2568 pub struct Promoted {
2569 DEBUG_FORMAT = "promoted[{}]"
2573 impl<'tcx> Debug for Constant<'tcx> {
2574 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2575 write!(fmt, "const ")?;
2576 fmt_const_val(fmt, self.literal)
2580 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2581 pub fn fmt_const_val(f: &mut impl Write, const_val: &ty::Const<'_>) -> fmt::Result {
2583 let value = const_val.val;
2584 let ty = const_val.ty;
2585 // print some primitives
2586 if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2588 Bool if bits == 0 => return write!(f, "false"),
2589 Bool if bits == 1 => return write!(f, "true"),
2590 Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2591 Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2592 Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2594 let bit_width = ty::tls::with(|tcx| {
2595 let ty = tcx.lift_to_global(&ty).unwrap();
2596 tcx.layout_of(ty::ParamEnv::empty().and(ty))
2601 let shift = 128 - bit_width;
2602 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2604 Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2608 // print function definitons
2609 if let FnDef(did, _) = ty.sty {
2610 return write!(f, "{}", item_path_str(did));
2612 // print string literals
2613 if let ConstValue::ScalarPair(ptr, len) = value {
2614 if let Scalar::Ptr(ptr) = ptr {
2615 if let Scalar::Bits { bits: len, .. } = len {
2616 if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2617 return ty::tls::with(|tcx| {
2618 let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2619 if let Some(interpret::AllocType::Memory(alloc)) = alloc {
2620 assert_eq!(len as usize as u128, len);
2622 &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2623 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2624 write!(f, "{:?}", s)
2626 write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2633 // just raw dump everything else
2634 write!(f, "{:?}:{}", value, ty)
2637 fn item_path_str(def_id: DefId) -> String {
2638 ty::tls::with(|tcx| tcx.item_path_str(def_id))
2641 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2642 type Node = BasicBlock;
2645 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2646 fn num_nodes(&self) -> usize {
2647 self.basic_blocks.len()
2651 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2652 fn start_node(&self) -> Self::Node {
2657 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2658 fn predecessors<'graph>(
2661 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2662 self.predecessors_for(node).clone().into_iter()
2666 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2667 fn successors<'graph>(
2670 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2671 self.basic_blocks[node].terminator().successors().cloned()
2675 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2676 type Item = BasicBlock;
2677 type Iter = IntoIter<BasicBlock>;
2680 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2681 type Item = BasicBlock;
2682 type Iter = iter::Cloned<Successors<'b>>;
2685 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
2686 pub struct Location {
2687 /// the location is within this block
2688 pub block: BasicBlock,
2690 /// the location is the start of the statement; or, if `statement_index`
2691 /// == num-statements, then the start of the terminator.
2692 pub statement_index: usize,
2695 impl fmt::Debug for Location {
2696 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2697 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2702 pub const START: Location = Location {
2707 /// Returns the location immediately after this one within the enclosing block.
2709 /// Note that if this location represents a terminator, then the
2710 /// resulting location would be out of bounds and invalid.
2711 pub fn successor_within_block(&self) -> Location {
2714 statement_index: self.statement_index + 1,
2718 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2719 if self.block == other.block {
2720 self.statement_index <= other.statement_index
2722 dominators.is_dominated_by(other.block, self.block)
2727 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2728 pub enum UnsafetyViolationKind {
2730 /// unsafety is not allowed at all in min const fn
2732 ExternStatic(ast::NodeId),
2733 BorrowPacked(ast::NodeId),
2736 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2737 pub struct UnsafetyViolation {
2738 pub source_info: SourceInfo,
2739 pub description: InternedString,
2740 pub details: InternedString,
2741 pub kind: UnsafetyViolationKind,
2744 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2745 pub struct UnsafetyCheckResult {
2746 /// Violations that are propagated *upwards* from this function
2747 pub violations: Lrc<[UnsafetyViolation]>,
2748 /// unsafe blocks in this function, along with whether they are used. This is
2749 /// used for the "unused_unsafe" lint.
2750 pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>,
2753 /// The layout of generator state
2754 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2755 pub struct GeneratorLayout<'tcx> {
2756 pub fields: Vec<LocalDecl<'tcx>>,
2759 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2760 pub struct BorrowCheckResult<'gcx> {
2761 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
2762 pub used_mut_upvars: SmallVec<[Field; 8]>,
2765 /// After we borrow check a closure, we are left with various
2766 /// requirements that we have inferred between the free regions that
2767 /// appear in the closure's signature or on its field types. These
2768 /// requirements are then verified and proved by the closure's
2769 /// creating function. This struct encodes those requirements.
2771 /// The requirements are listed as being between various
2772 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2773 /// vids refer to the free regions that appear in the closure (or
2774 /// generator's) type, in order of appearance. (This numbering is
2775 /// actually defined by the `UniversalRegions` struct in the NLL
2776 /// region checker. See for example
2777 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2778 /// regions in the closure's type "as if" they were erased, so their
2779 /// precise identity is not important, only their position.
2781 /// Example: If type check produces a closure with the closure substs:
2784 /// ClosureSubsts = [
2785 /// i8, // the "closure kind"
2786 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2787 /// &'a String, // some upvar
2791 /// here, there is one unique free region (`'a`) but it appears
2792 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2795 /// ClosureSubsts = [
2796 /// i8, // the "closure kind"
2797 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2798 /// &'2 String, // some upvar
2802 /// Now the code might impose a requirement like `'1: '2`. When an
2803 /// instance of the closure is created, the corresponding free regions
2804 /// can be extracted from its type and constrained to have the given
2805 /// outlives relationship.
2807 /// In some cases, we have to record outlives requirements between
2808 /// types and regions as well. In that case, if those types include
2809 /// any regions, those regions are recorded as `ReClosureBound`
2810 /// instances assigned one of these same indices. Those regions will
2811 /// be substituted away by the creator. We use `ReClosureBound` in
2812 /// that case because the regions must be allocated in the global
2813 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2814 /// internally within the rest of the NLL code).
2815 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2816 pub struct ClosureRegionRequirements<'gcx> {
2817 /// The number of external regions defined on the closure. In our
2818 /// example above, it would be 3 -- one for `'static`, then `'1`
2819 /// and `'2`. This is just used for a sanity check later on, to
2820 /// make sure that the number of regions we see at the callsite
2822 pub num_external_vids: usize,
2824 /// Requirements between the various free regions defined in
2826 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
2829 /// Indicates an outlives constraint between a type or between two
2830 /// free-regions declared on the closure.
2831 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2832 pub struct ClosureOutlivesRequirement<'tcx> {
2833 // This region or type ...
2834 pub subject: ClosureOutlivesSubject<'tcx>,
2836 // ... must outlive this one.
2837 pub outlived_free_region: ty::RegionVid,
2839 // If not, report an error here ...
2840 pub blame_span: Span,
2842 // ... due to this reason.
2843 pub category: ConstraintCategory,
2846 /// Outlives constraints can be categorized to determine whether and why they
2847 /// are interesting (for error reporting). Order of variants indicates sort
2848 /// order of the category, thereby influencing diagnostic output.
2850 /// See also [rustc_mir::borrow_check::nll::constraints]
2851 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
2852 pub enum ConstraintCategory {
2859 /// A constraint that came from checking the body of a closure.
2861 /// We try to get the category that the closure used when reporting this.
2869 /// A "boring" constraint (caused by the given location) is one that
2870 /// the user probably doesn't want to see described in diagnostics,
2871 /// because it is kind of an artifact of the type system setup.
2872 /// Example: `x = Foo { field: y }` technically creates
2873 /// intermediate regions representing the "type of `Foo { field: y
2874 /// }`", and data flows from `y` into those variables, but they
2875 /// are not very interesting. The assignment into `x` on the other
2878 // Boring and applicable everywhere.
2881 /// A constraint that doesn't correspond to anything the user sees.
2885 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2886 /// that must outlive some region.
2887 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2888 pub enum ClosureOutlivesSubject<'tcx> {
2889 /// Subject is a type, typically a type parameter, but could also
2890 /// be a projection. Indicates a requirement like `T: 'a` being
2891 /// passed to the caller, where the type here is `T`.
2893 /// The type here is guaranteed not to contain any free regions at
2897 /// Subject is a free region from the closure. Indicates a requirement
2898 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2899 Region(ty::RegionVid),
2903 * TypeFoldable implementations for MIR types
2906 CloneTypeFoldableAndLiftImpls! {
2915 SourceScopeLocalData,
2918 BraceStructTypeFoldableImpl! {
2919 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2922 source_scope_local_data,
2936 BraceStructTypeFoldableImpl! {
2937 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2942 BraceStructTypeFoldableImpl! {
2943 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
2956 BraceStructTypeFoldableImpl! {
2957 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
2964 BraceStructTypeFoldableImpl! {
2965 impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Place<'tcx>> {
2966 place, ty, re, mutbl
2970 BraceStructTypeFoldableImpl! {
2971 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
2976 EnumTypeFoldableImpl! {
2977 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
2978 (StatementKind::Assign)(a, b),
2979 (StatementKind::FakeRead)(cause, place),
2980 (StatementKind::SetDiscriminant) { place, variant_index },
2981 (StatementKind::StorageLive)(a),
2982 (StatementKind::StorageDead)(a),
2983 (StatementKind::InlineAsm) { asm, outputs, inputs },
2984 (StatementKind::Validate)(a, b),
2985 (StatementKind::EndRegion)(a),
2986 (StatementKind::AscribeUserType)(a, v, b),
2987 (StatementKind::Nop),
2991 EnumTypeFoldableImpl! {
2992 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
2993 (ClearCrossCrate::Clear),
2994 (ClearCrossCrate::Set)(a),
2995 } where T: TypeFoldable<'tcx>
2998 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2999 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3000 use mir::TerminatorKind::*;
3002 let kind = match self.kind {
3003 Goto { target } => Goto { target: target },
3010 discr: discr.fold_with(folder),
3011 switch_ty: switch_ty.fold_with(folder),
3012 values: values.clone(),
3013 targets: targets.clone(),
3020 location: location.fold_with(folder),
3029 } => DropAndReplace {
3030 location: location.fold_with(folder),
3031 value: value.fold_with(folder),
3040 value: value.fold_with(folder),
3051 let dest = destination
3053 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3056 func: func.fold_with(folder),
3057 args: args.fold_with(folder),
3070 let msg = if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3071 EvalErrorKind::BoundsCheck {
3072 len: len.fold_with(folder),
3073 index: index.fold_with(folder),
3079 cond: cond.fold_with(folder),
3086 GeneratorDrop => GeneratorDrop,
3090 Unreachable => Unreachable,
3093 ref imaginary_targets,
3096 imaginary_targets: imaginary_targets.clone(),
3107 source_info: self.source_info,
3112 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3113 use mir::TerminatorKind::*;
3120 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3121 Drop { ref location, .. } => location.visit_with(visitor),
3126 } => location.visit_with(visitor) || value.visit_with(visitor),
3127 Yield { ref value, .. } => value.visit_with(visitor),
3134 let dest = if let Some((ref loc, _)) = *destination {
3135 loc.visit_with(visitor)
3139 dest || func.visit_with(visitor) || args.visit_with(visitor)
3142 ref cond, ref msg, ..
3144 if cond.visit_with(visitor) {
3145 if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3146 len.visit_with(visitor) || index.visit_with(visitor)
3161 | FalseUnwind { .. } => false,
3166 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3167 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3169 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3174 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3175 if let &Place::Projection(ref p) = self {
3176 p.visit_with(visitor)
3183 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3184 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3187 Use(ref op) => Use(op.fold_with(folder)),
3188 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3189 Ref(region, bk, ref place) => {
3190 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3192 Len(ref place) => Len(place.fold_with(folder)),
3193 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3194 BinaryOp(op, ref rhs, ref lhs) => {
3195 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3197 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3198 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3200 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3201 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3202 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3203 Aggregate(ref kind, ref fields) => {
3204 let kind = box match **kind {
3205 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3206 AggregateKind::Tuple => AggregateKind::Tuple,
3207 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3210 substs.fold_with(folder),
3211 user_ty.fold_with(folder),
3214 AggregateKind::Closure(id, substs) => {
3215 AggregateKind::Closure(id, substs.fold_with(folder))
3217 AggregateKind::Generator(id, substs, movablity) => {
3218 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3221 Aggregate(kind, fields.fold_with(folder))
3226 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3229 Use(ref op) => op.visit_with(visitor),
3230 Repeat(ref op, _) => op.visit_with(visitor),
3231 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3232 Len(ref place) => place.visit_with(visitor),
3233 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3234 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3235 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3237 UnaryOp(_, ref val) => val.visit_with(visitor),
3238 Discriminant(ref place) => place.visit_with(visitor),
3239 NullaryOp(_, ty) => ty.visit_with(visitor),
3240 Aggregate(ref kind, ref fields) => {
3242 AggregateKind::Array(ty) => ty.visit_with(visitor),
3243 AggregateKind::Tuple => false,
3244 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3245 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3247 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3248 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3249 }) || fields.visit_with(visitor)
3255 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3256 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3258 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3259 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3260 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3264 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3266 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3267 Operand::Constant(ref c) => c.visit_with(visitor),
3272 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
3274 B: TypeFoldable<'tcx>,
3275 V: TypeFoldable<'tcx>,
3276 T: TypeFoldable<'tcx>,
3278 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3279 use mir::ProjectionElem::*;
3281 let base = self.base.fold_with(folder);
3282 let elem = match self.elem {
3284 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3285 Index(ref v) => Index(v.fold_with(folder)),
3286 ref elem => elem.clone(),
3289 Projection { base, elem }
3292 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3293 use mir::ProjectionElem::*;
3295 self.base.visit_with(visitor) || match self.elem {
3296 Field(_, ref ty) => ty.visit_with(visitor),
3297 Index(ref v) => v.visit_with(visitor),
3303 impl<'tcx> TypeFoldable<'tcx> for Field {
3304 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3307 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3312 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3313 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3315 span: self.span.clone(),
3316 ty: self.ty.fold_with(folder),
3317 user_ty: self.user_ty.fold_with(folder),
3318 literal: self.literal.fold_with(folder),
3321 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3322 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)