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