]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/util/call_kind.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / compiler / rustc_const_eval / src / util / call_kind.rs
1 //! Common logic for borrowck use-after-move errors when moved into a `fn(self)`,
2 //! as well as errors when attempting to call a non-const function in a const
3 //! context.
4
5 use rustc_hir::def_id::DefId;
6 use rustc_hir::{lang_items, LangItem};
7 use rustc_middle::ty::subst::SubstsRef;
8 use rustc_middle::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt};
9 use rustc_span::symbol::Ident;
10 use rustc_span::{sym, DesugaringKind, Span};
11
12 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
13 pub enum CallDesugaringKind {
14     /// for _ in x {} calls x.into_iter()
15     ForLoopIntoIter,
16     /// x? calls x.branch()
17     QuestionBranch,
18     /// x? calls type_of(x)::from_residual()
19     QuestionFromResidual,
20     /// try { ..; x } calls type_of(x)::from_output(x)
21     TryBlockFromOutput,
22 }
23
24 impl CallDesugaringKind {
25     pub fn trait_def_id(self, tcx: TyCtxt<'_>) -> DefId {
26         match self {
27             Self::ForLoopIntoIter => tcx.get_diagnostic_item(sym::IntoIterator).unwrap(),
28             Self::QuestionBranch | Self::TryBlockFromOutput => {
29                 tcx.require_lang_item(LangItem::Try, None)
30             }
31             Self::QuestionFromResidual => tcx.get_diagnostic_item(sym::FromResidual).unwrap(),
32         }
33     }
34 }
35
36 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
37 pub enum CallKind<'tcx> {
38     /// A normal method call of the form `receiver.foo(a, b, c)`
39     Normal {
40         self_arg: Option<Ident>,
41         desugaring: Option<(CallDesugaringKind, Ty<'tcx>)>,
42         method_did: DefId,
43         method_substs: SubstsRef<'tcx>,
44     },
45     /// A call to `Fn(..)::call(..)`, desugared from `my_closure(a, b, c)`
46     FnCall { fn_trait_id: DefId, self_ty: Ty<'tcx> },
47     /// A call to an operator trait, desugared from operator syntax (e.g. `a << b`)
48     Operator { self_arg: Option<Ident>, trait_id: DefId, self_ty: Ty<'tcx> },
49     DerefCoercion {
50         /// The `Span` of the `Target` associated type
51         /// in the `Deref` impl we are using.
52         deref_target: Span,
53         /// The type `T::Deref` we are dereferencing to
54         deref_target_ty: Ty<'tcx>,
55         self_ty: Ty<'tcx>,
56     },
57 }
58
59 pub fn call_kind<'tcx>(
60     tcx: TyCtxt<'tcx>,
61     param_env: ParamEnv<'tcx>,
62     method_did: DefId,
63     method_substs: SubstsRef<'tcx>,
64     fn_call_span: Span,
65     from_hir_call: bool,
66     self_arg: Option<Ident>,
67 ) -> CallKind<'tcx> {
68     let parent = tcx.opt_associated_item(method_did).and_then(|assoc| {
69         let container_id = assoc.container_id(tcx);
70         match assoc.container {
71             AssocItemContainer::ImplContainer => tcx.trait_id_of_impl(container_id),
72             AssocItemContainer::TraitContainer => Some(container_id),
73         }
74     });
75
76     let fn_call = parent.and_then(|p| {
77         lang_items::FN_TRAITS.iter().filter_map(|&l| tcx.lang_items().get(l)).find(|&id| id == p)
78     });
79
80     let operator = if !from_hir_call && let Some(p) = parent {
81         lang_items::OPERATORS.iter().filter_map(|&l| tcx.lang_items().get(l)).find(|&id| id == p)
82     } else {
83         None
84     };
85
86     let is_deref = !from_hir_call && tcx.is_diagnostic_item(sym::deref_method, method_did);
87
88     // Check for a 'special' use of 'self' -
89     // an FnOnce call, an operator (e.g. `<<`), or a
90     // deref coercion.
91     let kind = if let Some(trait_id) = fn_call {
92         Some(CallKind::FnCall { fn_trait_id: trait_id, self_ty: method_substs.type_at(0) })
93     } else if let Some(trait_id) = operator {
94         Some(CallKind::Operator { self_arg, trait_id, self_ty: method_substs.type_at(0) })
95     } else if is_deref {
96         let deref_target = tcx.get_diagnostic_item(sym::deref_target).and_then(|deref_target| {
97             Instance::resolve(tcx, param_env, deref_target, method_substs).transpose()
98         });
99         if let Some(Ok(instance)) = deref_target {
100             let deref_target_ty = instance.ty(tcx, param_env);
101             Some(CallKind::DerefCoercion {
102                 deref_target: tcx.def_span(instance.def_id()),
103                 deref_target_ty,
104                 self_ty: method_substs.type_at(0),
105             })
106         } else {
107             None
108         }
109     } else {
110         None
111     };
112
113     kind.unwrap_or_else(|| {
114         // This isn't a 'special' use of `self`
115         debug!(?method_did, ?fn_call_span);
116         let desugaring = if Some(method_did) == tcx.lang_items().into_iter_fn()
117             && fn_call_span.desugaring_kind() == Some(DesugaringKind::ForLoop)
118         {
119             Some((CallDesugaringKind::ForLoopIntoIter, method_substs.type_at(0)))
120         } else if fn_call_span.desugaring_kind() == Some(DesugaringKind::QuestionMark) {
121             if Some(method_did) == tcx.lang_items().branch_fn() {
122                 Some((CallDesugaringKind::QuestionBranch, method_substs.type_at(0)))
123             } else if Some(method_did) == tcx.lang_items().from_residual_fn() {
124                 Some((CallDesugaringKind::QuestionFromResidual, method_substs.type_at(0)))
125             } else {
126                 None
127             }
128         } else if Some(method_did) == tcx.lang_items().from_output_fn()
129             && fn_call_span.desugaring_kind() == Some(DesugaringKind::TryBlock)
130         {
131             Some((CallDesugaringKind::TryBlockFromOutput, method_substs.type_at(0)))
132         } else {
133             None
134         };
135         CallKind::Normal { self_arg, desugaring, method_did, method_substs }
136     })
137 }