rustc_middle/mir/
query.rs

1//! Values computed by queries that use MIR.
2
3use std::fmt::{self, Debug};
4
5use rustc_abi::{FieldIdx, VariantIdx};
6use rustc_errors::ErrorGuaranteed;
7use rustc_index::IndexVec;
8use rustc_index::bit_set::BitMatrix;
9use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
10use rustc_span::{Span, Symbol};
11
12use super::{ConstValue, SourceInfo};
13use crate::ty::{self, CoroutineArgsExt, Ty};
14
15rustc_index::newtype_index! {
16    #[derive(HashStable)]
17    #[encodable]
18    #[debug_format = "_s{}"]
19    pub struct CoroutineSavedLocal {}
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
24pub struct CoroutineSavedTy<'tcx> {
25    pub ty: Ty<'tcx>,
26    /// Source info corresponding to the local in the original MIR body.
27    pub source_info: SourceInfo,
28    /// Whether the local should be ignored for trait bound computations.
29    pub ignore_for_traits: bool,
30}
31
32/// The layout of coroutine state.
33#[derive(Clone, PartialEq, Eq)]
34#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
35pub struct CoroutineLayout<'tcx> {
36    /// The type of every local stored inside the coroutine.
37    pub field_tys: IndexVec<CoroutineSavedLocal, CoroutineSavedTy<'tcx>>,
38
39    /// The name for debuginfo.
40    pub field_names: IndexVec<CoroutineSavedLocal, Option<Symbol>>,
41
42    /// Which of the above fields are in each variant. Note that one field may
43    /// be stored in multiple variants.
44    pub variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>>,
45
46    /// The source that led to each variant being created (usually, a yield or
47    /// await).
48    pub variant_source_info: IndexVec<VariantIdx, SourceInfo>,
49
50    /// Which saved locals are storage-live at the same time. Locals that do not
51    /// have conflicts with each other are allowed to overlap in the computed
52    /// layout.
53    #[type_foldable(identity)]
54    #[type_visitable(ignore)]
55    pub storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
56}
57
58impl Debug for CoroutineLayout<'_> {
59    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
60        fmt.debug_struct("CoroutineLayout")
61            .field_with("field_tys", |fmt| {
62                fmt.debug_map().entries(self.field_tys.iter_enumerated()).finish()
63            })
64            .field_with("variant_fields", |fmt| {
65                let mut map = fmt.debug_map();
66                for (idx, fields) in self.variant_fields.iter_enumerated() {
67                    map.key_with(|fmt| {
68                        let variant_name = ty::CoroutineArgs::variant_name(idx);
69                        if fmt.alternate() {
70                            write!(fmt, "{variant_name:9}({idx:?})")
71                        } else {
72                            write!(fmt, "{variant_name}")
73                        }
74                    });
75                    // Force variant fields to print in regular mode instead of alternate mode.
76                    map.value_with(|fmt| write!(fmt, "{fields:?}"));
77                }
78                map.finish()
79            })
80            .field("storage_conflicts", &self.storage_conflicts)
81            .finish()
82    }
83}
84
85/// The result of the `mir_const_qualif` query.
86///
87/// Each field (except `tainted_by_errors`) corresponds to an implementer of the `Qualif` trait in
88/// `rustc_const_eval/src/transform/check_consts/qualifs.rs`. See that file for more information on each
89/// `Qualif`.
90#[derive(Clone, Copy, Debug, Default, TyEncodable, TyDecodable, HashStable)]
91pub struct ConstQualifs {
92    pub has_mut_interior: bool,
93    pub needs_drop: bool,
94    pub needs_non_const_drop: bool,
95    pub tainted_by_errors: Option<ErrorGuaranteed>,
96}
97/// Outlives-constraints can be categorized to determine whether and why they
98/// are interesting (for error reporting). Order of variants indicates sort
99/// order of the category, thereby influencing diagnostic output.
100///
101/// See also `rustc_const_eval::borrow_check::constraints`.
102#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
103#[derive(TyEncodable, TyDecodable, HashStable, TypeVisitable, TypeFoldable)]
104pub enum ConstraintCategory<'tcx> {
105    Return(ReturnConstraint),
106    Yield,
107    UseAsConst,
108    UseAsStatic,
109    TypeAnnotation(AnnotationSource),
110    Cast {
111        /// Whether this cast is a coercion that was automatically inserted by the compiler.
112        is_implicit_coercion: bool,
113        /// Whether this is an unsizing coercion and if yes, this contains the target type.
114        /// Region variables are erased to ReErased.
115        unsize_to: Option<Ty<'tcx>>,
116    },
117
118    /// Contains the function type if available.
119    CallArgument(Option<Ty<'tcx>>),
120    CopyBound,
121    SizedBound,
122    Assignment,
123    /// A constraint that came from a usage of a variable (e.g. in an ADT expression
124    /// like `Foo { field: my_val }`)
125    Usage,
126    OpaqueType,
127    ClosureUpvar(FieldIdx),
128
129    /// A constraint from a user-written predicate
130    /// with the provided span, written on the item
131    /// with the given `DefId`
132    Predicate(Span),
133
134    /// A "boring" constraint (caused by the given location) is one that
135    /// the user probably doesn't want to see described in diagnostics,
136    /// because it is kind of an artifact of the type system setup.
137    Boring,
138    // Boring and applicable everywhere.
139    BoringNoLocation,
140
141    /// A constraint that doesn't correspond to anything the user sees.
142    Internal,
143
144    /// An internal constraint added when a region outlives a placeholder
145    /// it cannot name and therefore has to outlive `'static`. The argument
146    /// is the unnameable placeholder and the constraint is always between
147    /// an SCC representative and `'static`.
148    OutlivesUnnameablePlaceholder(
149        #[type_foldable(identity)]
150        #[type_visitable(ignore)]
151        ty::RegionVid,
152    ),
153}
154
155#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
156#[derive(TyEncodable, TyDecodable, HashStable, TypeVisitable, TypeFoldable)]
157pub enum ReturnConstraint {
158    Normal,
159    ClosureUpvar(FieldIdx),
160}
161
162#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
163#[derive(TyEncodable, TyDecodable, HashStable, TypeVisitable, TypeFoldable)]
164pub enum AnnotationSource {
165    Ascription,
166    Declaration,
167    OpaqueCast,
168    GenericArg,
169}
170
171/// The constituent parts of a mir constant of kind ADT or array.
172#[derive(Copy, Clone, Debug, HashStable)]
173pub struct DestructuredConstant<'tcx> {
174    pub variant: Option<VariantIdx>,
175    pub fields: &'tcx [(ConstValue, Ty<'tcx>)],
176}