1use rustc_errors::Applicability;
2use rustc_hir_analysis::autoderef::Autoderef;
3use rustc_infer::infer::InferOk;
4use rustc_infer::traits::{Obligation, ObligationCauseCode};
5use rustc_middle::span_bug;
6use rustc_middle::ty::adjustment::{
7 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, OverloadedDeref,
8 PointerCoercion,
9};
10use rustc_middle::ty::{self, Ty};
11use rustc_span::{Span, sym};
12use tracing::debug;
13use {rustc_ast as ast, rustc_hir as hir};
14
15use crate::method::{MethodCallee, TreatNotYetDefinedOpaques};
16use crate::{FnCtxt, PlaceOp};
17
18impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
19 pub(super) fn lookup_derefing(
21 &self,
22 expr: &hir::Expr<'_>,
23 oprnd_expr: &'tcx hir::Expr<'tcx>,
24 oprnd_ty: Ty<'tcx>,
25 ) -> Option<Ty<'tcx>> {
26 if let Some(ty) = oprnd_ty.builtin_deref(true) {
27 return Some(ty);
28 }
29
30 let ok = self.try_overloaded_deref(expr.span, oprnd_ty)?;
31 let method = self.register_infer_ok_obligations(ok);
32 if let ty::Ref(_, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() {
33 self.apply_adjustments(
34 oprnd_expr,
35 vec![Adjustment {
36 kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Not)),
37 target: method.sig.inputs()[0],
38 }],
39 );
40 } else {
41 span_bug!(expr.span, "input to deref is not a ref?");
42 }
43 let ty = self.make_overloaded_place_return_type(method);
44 self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
45 Some(ty)
46 }
47
48 pub(super) fn lookup_indexing(
50 &self,
51 expr: &hir::Expr<'_>,
52 base_expr: &'tcx hir::Expr<'tcx>,
53 base_ty: Ty<'tcx>,
54 index_expr: &'tcx hir::Expr<'tcx>,
55 idx_ty: Ty<'tcx>,
56 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
57 let mut autoderef = self.autoderef(base_expr.span, base_ty);
62 let mut result = None;
63 while result.is_none() && autoderef.next().is_some() {
64 result = self.try_index_step(expr, base_expr, &autoderef, idx_ty, index_expr);
65 }
66 self.register_predicates(autoderef.into_obligations());
67 result
68 }
69
70 fn negative_index(
71 &self,
72 ty: Ty<'tcx>,
73 span: Span,
74 base_expr: &hir::Expr<'_>,
75 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
76 let ty = self.resolve_vars_if_possible(ty);
77 let mut err = self.dcx().struct_span_err(
78 span,
79 format!("negative integers cannot be used to index on a `{ty}`"),
80 );
81 err.span_label(span, format!("cannot use a negative integer for indexing on `{ty}`"));
82 if let (hir::ExprKind::Path(..), Ok(snippet)) =
83 (&base_expr.kind, self.tcx.sess.source_map().span_to_snippet(base_expr.span))
84 {
85 err.span_suggestion_verbose(
87 span.shrink_to_lo(),
88 format!(
89 "to access an element starting from the end of the `{ty}`, compute the index",
90 ),
91 format!("{snippet}.len() "),
92 Applicability::MachineApplicable,
93 );
94 }
95 let reported = err.emit();
96 Some((Ty::new_error(self.tcx, reported), Ty::new_error(self.tcx, reported)))
97 }
98
99 fn try_index_step(
105 &self,
106 expr: &hir::Expr<'_>,
107 base_expr: &hir::Expr<'_>,
108 autoderef: &Autoderef<'a, 'tcx>,
109 index_ty: Ty<'tcx>,
110 index_expr: &hir::Expr<'_>,
111 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
112 let adjusted_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
113 debug!(
114 "try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
115 index_ty={:?})",
116 expr, base_expr, adjusted_ty, index_ty
117 );
118
119 if let hir::ExprKind::Unary(
120 hir::UnOp::Neg,
121 hir::Expr {
122 kind: hir::ExprKind::Lit(hir::Lit { node: ast::LitKind::Int(..), .. }),
123 ..
124 },
125 ) = index_expr.kind
126 {
127 match adjusted_ty.kind() {
128 ty::Adt(def, _) if self.tcx.is_diagnostic_item(sym::Vec, def.did()) => {
129 return self.negative_index(adjusted_ty, index_expr.span, base_expr);
130 }
131 ty::Slice(_) | ty::Array(_, _) => {
132 return self.negative_index(adjusted_ty, index_expr.span, base_expr);
133 }
134 _ => {}
135 }
136 }
137
138 for unsize in [false, true] {
139 let mut self_ty = adjusted_ty;
140 if unsize {
141 if let ty::Array(element_ty, ct) = *adjusted_ty.kind() {
143 self.register_predicate(Obligation::new(
144 self.tcx,
145 self.cause(base_expr.span, ObligationCauseCode::ArrayLen(adjusted_ty)),
146 self.param_env,
147 ty::ClauseKind::ConstArgHasType(ct, self.tcx.types.usize),
148 ));
149 self_ty = Ty::new_slice(self.tcx, element_ty);
150 } else {
151 continue;
152 }
153 }
154
155 let input_ty = self.next_ty_var(base_expr.span);
159 let method =
160 self.try_overloaded_place_op(expr.span, self_ty, Some(input_ty), PlaceOp::Index);
161
162 if let Some(result) = method {
163 debug!("try_index_step: success, using overloaded indexing");
164 let method = self.register_infer_ok_obligations(result);
165
166 let mut adjustments = self.adjust_steps(autoderef);
167 if let ty::Ref(region, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() {
168 adjustments.push(Adjustment {
169 kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Not)),
170 target: Ty::new_imm_ref(self.tcx, *region, adjusted_ty),
171 });
172 } else {
173 span_bug!(expr.span, "input to index is not a ref?");
174 }
175 if unsize {
176 adjustments.push(Adjustment {
177 kind: Adjust::Pointer(PointerCoercion::Unsize),
178 target: method.sig.inputs()[0],
179 });
180 }
181 self.apply_adjustments(base_expr, adjustments);
182
183 self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
184
185 return Some((input_ty, self.make_overloaded_place_return_type(method)));
186 }
187 }
188
189 None
190 }
191
192 pub(super) fn try_overloaded_place_op(
197 &self,
198 span: Span,
199 base_ty: Ty<'tcx>,
200 opt_rhs_ty: Option<Ty<'tcx>>,
201 op: PlaceOp,
202 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
203 debug!("try_overloaded_place_op({:?},{:?},{:?})", span, base_ty, op);
204
205 let (Some(imm_tr), imm_op) = (match op {
206 PlaceOp::Deref => (self.tcx.lang_items().deref_trait(), sym::deref),
207 PlaceOp::Index => (self.tcx.lang_items().index_trait(), sym::index),
208 }) else {
209 return None;
211 };
212
213 let treat_opaques = TreatNotYetDefinedOpaques::AsInfer;
216 self.lookup_method_for_operator(
217 self.misc(span),
218 imm_op,
219 imm_tr,
220 base_ty,
221 opt_rhs_ty,
222 treat_opaques,
223 )
224 }
225
226 fn try_mutable_overloaded_place_op(
227 &self,
228 span: Span,
229 base_ty: Ty<'tcx>,
230 opt_rhs_ty: Option<Ty<'tcx>>,
231 op: PlaceOp,
232 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
233 debug!("try_mutable_overloaded_place_op({:?},{:?},{:?})", span, base_ty, op);
234
235 let (Some(mut_tr), mut_op) = (match op {
236 PlaceOp::Deref => (self.tcx.lang_items().deref_mut_trait(), sym::deref_mut),
237 PlaceOp::Index => (self.tcx.lang_items().index_mut_trait(), sym::index_mut),
238 }) else {
239 return None;
241 };
242
243 let treat_opaques = TreatNotYetDefinedOpaques::AsInfer;
248 self.lookup_method_for_operator(
249 self.misc(span),
250 mut_op,
251 mut_tr,
252 base_ty,
253 opt_rhs_ty,
254 treat_opaques,
255 )
256 }
257
258 pub(crate) fn convert_place_derefs_to_mutable(&self, expr: &hir::Expr<'_>) {
266 let mut exprs = vec![expr];
268
269 while let hir::ExprKind::Field(expr, _)
270 | hir::ExprKind::Index(expr, _, _)
271 | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = exprs.last().unwrap().kind
272 {
273 exprs.push(expr);
274 }
275
276 debug!("convert_place_derefs_to_mutable: exprs={:?}", exprs);
277
278 let mut inside_union = false;
280 for (i, &expr) in exprs.iter().rev().enumerate() {
281 debug!("convert_place_derefs_to_mutable: i={} expr={:?}", i, expr);
282
283 let mut source = self.node_ty(expr.hir_id);
284 if matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Deref, _)) {
285 inside_union = false;
287 }
288 if source.is_union() {
289 inside_union = true;
290 }
291 let previous_adjustments =
298 self.typeck_results.borrow_mut().adjustments_mut().remove(expr.hir_id);
299 if let Some(mut adjustments) = previous_adjustments {
300 for adjustment in &mut adjustments {
301 if let Adjust::Deref(Some(ref mut deref)) = adjustment.kind
302 && let Some(ok) = self.try_mutable_overloaded_place_op(
303 expr.span,
304 source,
305 None,
306 PlaceOp::Deref,
307 )
308 {
309 let method = self.register_infer_ok_obligations(ok);
310 let ty::Ref(_, _, mutbl) = *method.sig.output().kind() else {
311 span_bug!(
312 self.tcx.def_span(method.def_id),
313 "expected DerefMut to return a &mut"
314 );
315 };
316 *deref = OverloadedDeref { mutbl, span: deref.span };
317 self.enforce_context_effects(None, expr.span, method.def_id, method.args);
318 if inside_union
321 && source.ty_adt_def().is_some_and(|adt| adt.is_manually_drop())
322 {
323 self.dcx().struct_span_err(
324 expr.span,
325 "not automatically applying `DerefMut` on `ManuallyDrop` union field",
326 )
327 .with_help(
328 "writing to this reference calls the destructor for the old value",
329 )
330 .with_help("add an explicit `*` if that is desired, or call `ptr::write` to not run the destructor")
331 .emit();
332 }
333 }
334 source = adjustment.target;
335 }
336 self.typeck_results.borrow_mut().adjustments_mut().insert(expr.hir_id, adjustments);
337 }
338
339 match expr.kind {
340 hir::ExprKind::Index(base_expr, ..) => {
341 self.convert_place_op_to_mutable(PlaceOp::Index, expr, base_expr);
342 }
343 hir::ExprKind::Unary(hir::UnOp::Deref, base_expr) => {
344 self.convert_place_op_to_mutable(PlaceOp::Deref, expr, base_expr);
345 }
346 _ => {}
347 }
348 }
349 }
350
351 fn convert_place_op_to_mutable(
352 &self,
353 op: PlaceOp,
354 expr: &hir::Expr<'_>,
355 base_expr: &hir::Expr<'_>,
356 ) {
357 debug!("convert_place_op_to_mutable({:?}, {:?}, {:?})", op, expr, base_expr);
358 if !self.typeck_results.borrow().is_method_call(expr) {
359 debug!("convert_place_op_to_mutable - builtin, nothing to do");
360 return;
361 }
362
363 let base_ty = self
365 .typeck_results
366 .borrow()
367 .expr_ty_adjusted(base_expr)
368 .builtin_deref(false)
369 .expect("place op takes something that is not a ref");
370
371 let arg_ty = match op {
372 PlaceOp::Deref => None,
373 PlaceOp::Index => {
374 Some(self.typeck_results.borrow().node_args(expr.hir_id).type_at(1))
383 }
384 };
385 let method = self.try_mutable_overloaded_place_op(expr.span, base_ty, arg_ty, op);
386 let method = match method {
387 Some(ok) => self.register_infer_ok_obligations(ok),
388 None => return,
391 };
392 debug!("convert_place_op_to_mutable: method={:?}", method);
393 self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
394
395 let ty::Ref(region, _, hir::Mutability::Mut) = method.sig.inputs()[0].kind() else {
396 span_bug!(expr.span, "input to mutable place op is not a mut ref?");
397 };
398
399 let base_expr_ty = self.node_ty(base_expr.hir_id);
402 if let Some(adjustments) =
403 self.typeck_results.borrow_mut().adjustments_mut().get_mut(base_expr.hir_id)
404 {
405 let mut source = base_expr_ty;
406 for adjustment in &mut adjustments[..] {
407 if let Adjust::Borrow(AutoBorrow::Ref(..)) = adjustment.kind {
408 debug!("convert_place_op_to_mutable: converting autoref {:?}", adjustment);
409 let mutbl = AutoBorrowMutability::Mut {
410 allow_two_phase_borrow: AllowTwoPhase::No,
415 };
416 adjustment.kind = Adjust::Borrow(AutoBorrow::Ref(mutbl));
417 adjustment.target = Ty::new_ref(self.tcx, *region, source, mutbl.into());
418 }
419 source = adjustment.target;
420 }
421
422 if let [
424 ..,
425 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
426 Adjustment { kind: Adjust::Pointer(PointerCoercion::Unsize), ref mut target },
427 ] = adjustments[..]
428 {
429 *target = method.sig.inputs()[0];
430 }
431 }
432 }
433}