1
1
use crate :: FnCtxt ;
2
2
use rustc_ast:: util:: parser:: PREC_POSTFIX ;
3
+ use rustc_data_structures:: fx:: FxHashMap ;
3
4
use rustc_errors:: MultiSpan ;
4
5
use rustc_errors:: { Applicability , Diagnostic , DiagnosticBuilder , ErrorGuaranteed } ;
5
6
use rustc_hir as hir;
6
7
use rustc_hir:: def:: CtorKind ;
8
+ use rustc_hir:: intravisit:: Visitor ;
7
9
use rustc_hir:: lang_items:: LangItem ;
8
10
use rustc_hir:: { is_range_literal, Node } ;
9
11
use rustc_infer:: infer:: InferOk ;
10
12
use rustc_middle:: lint:: in_external_macro;
11
13
use rustc_middle:: middle:: stability:: EvalResult ;
12
14
use rustc_middle:: ty:: adjustment:: AllowTwoPhase ;
13
15
use rustc_middle:: ty:: error:: { ExpectedFound , TypeError } ;
14
- use rustc_middle:: ty:: print:: with_no_trimmed_paths;
15
- use rustc_middle:: ty:: { self , Article , AssocItem , Ty , TypeAndMut } ;
16
+ use rustc_middle:: ty:: fold:: { BottomUpFolder , TypeFolder } ;
17
+ use rustc_middle:: ty:: print:: { with_forced_trimmed_paths, with_no_trimmed_paths} ;
18
+ use rustc_middle:: ty:: relate:: TypeRelation ;
19
+ use rustc_middle:: ty:: { self , Article , AssocItem , Ty , TypeAndMut , TypeVisitable } ;
16
20
use rustc_span:: symbol:: { sym, Symbol } ;
17
21
use rustc_span:: { BytePos , Span } ;
18
22
use rustc_trait_selection:: infer:: InferCtxtExt as _;
23
+ use rustc_trait_selection:: traits:: error_reporting:: method_chain:: CollectAllMismatches ;
19
24
use rustc_trait_selection:: traits:: ObligationCause ;
20
25
21
26
use super :: method:: probe;
@@ -40,7 +45,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40
45
self . annotate_alternative_method_deref ( err, expr, error) ;
41
46
42
47
// Use `||` to give these suggestions a precedence
43
- let _ = self . suggest_missing_parentheses ( err, expr)
48
+ let suggested = self . suggest_missing_parentheses ( err, expr)
44
49
|| self . suggest_remove_last_method_call ( err, expr, expected)
45
50
|| self . suggest_associated_const ( err, expr, expected)
46
51
|| self . suggest_deref_ref_or_into ( err, expr, expected, expr_ty, expected_ty_expr)
@@ -54,6 +59,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
54
59
|| self . suggest_copied_or_cloned ( err, expr, expr_ty, expected)
55
60
|| self . suggest_into ( err, expr, expr_ty, expected)
56
61
|| self . suggest_floating_point_literal ( err, expr, expected) ;
62
+ if !suggested {
63
+ self . point_at_expr_source_of_inferred_type ( err, expr, expr_ty, expected) ;
64
+ }
57
65
}
58
66
59
67
pub fn emit_coerce_suggestions (
@@ -205,6 +213,215 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
205
213
( expected, Some ( err) )
206
214
}
207
215
216
+ pub fn point_at_expr_source_of_inferred_type (
217
+ & self ,
218
+ err : & mut Diagnostic ,
219
+ expr : & hir:: Expr < ' _ > ,
220
+ found : Ty < ' tcx > ,
221
+ expected : Ty < ' tcx > ,
222
+ ) -> bool {
223
+ let map = self . tcx . hir ( ) ;
224
+
225
+ let hir:: ExprKind :: Path ( hir:: QPath :: Resolved ( None , p) ) = expr. kind else { return false ; } ;
226
+ let [ hir:: PathSegment { ident, args : None , .. } ] = p. segments else { return false ; } ;
227
+ let hir:: def:: Res :: Local ( hir_id) = p. res else { return false ; } ;
228
+ let Some ( hir:: Node :: Pat ( pat) ) = map. find ( hir_id) else { return false ; } ;
229
+ let Some ( hir:: Node :: Local ( hir:: Local {
230
+ ty : None ,
231
+ init : Some ( init) ,
232
+ ..
233
+ } ) ) = map. find_parent ( pat. hir_id ) else { return false ; } ;
234
+ let Some ( ty) = self . node_ty_opt ( init. hir_id ) else { return false ; } ;
235
+ if ty. is_closure ( ) || init. span . overlaps ( expr. span ) || pat. span . from_expansion ( ) {
236
+ return false ;
237
+ }
238
+
239
+ // Locate all the usages of the relevant binding.
240
+ struct FindExprs < ' hir > {
241
+ hir_id : hir:: HirId ,
242
+ uses : Vec < & ' hir hir:: Expr < ' hir > > ,
243
+ }
244
+ impl < ' v > Visitor < ' v > for FindExprs < ' v > {
245
+ fn visit_expr ( & mut self , ex : & ' v hir:: Expr < ' v > ) {
246
+ if let hir:: ExprKind :: Path ( hir:: QPath :: Resolved ( None , path) ) = ex. kind
247
+ && let hir:: def:: Res :: Local ( hir_id) = path. res
248
+ && hir_id == self . hir_id
249
+ {
250
+ self . uses . push ( ex) ;
251
+ }
252
+ hir:: intravisit:: walk_expr ( self , ex) ;
253
+ }
254
+ }
255
+
256
+ let mut expr_finder = FindExprs { hir_id, uses : vec ! [ ] } ;
257
+ let id = map. get_parent_item ( hir_id) ;
258
+ let hir_id: hir:: HirId = id. into ( ) ;
259
+
260
+ let Some ( node) = map. find ( hir_id) else { return false ; } ;
261
+ let Some ( body_id) = node. body_id ( ) else { return false ; } ;
262
+ let body = map. body ( body_id) ;
263
+ expr_finder. visit_expr ( body. value ) ;
264
+ // Hack to make equality checks on types with inference variables and regions useful.
265
+ let mut eraser = BottomUpFolder {
266
+ tcx : self . tcx ,
267
+ lt_op : |_| self . tcx . lifetimes . re_erased ,
268
+ ct_op : |c| c,
269
+ ty_op : |t| match * t. kind ( ) {
270
+ ty:: Infer ( ty:: TyVar ( vid) ) => self . tcx . mk_ty_infer ( ty:: TyVar ( self . root_var ( vid) ) ) ,
271
+ ty:: Infer ( ty:: IntVar ( _) ) => {
272
+ self . tcx . mk_ty_infer ( ty:: IntVar ( ty:: IntVid { index : 0 } ) )
273
+ }
274
+ ty:: Infer ( ty:: FloatVar ( _) ) => {
275
+ self . tcx . mk_ty_infer ( ty:: FloatVar ( ty:: FloatVid { index : 0 } ) )
276
+ }
277
+ _ => t,
278
+ } ,
279
+ } ;
280
+ let mut prev = eraser. fold_ty ( ty) ;
281
+ let mut prev_span = None ;
282
+
283
+ for binding in expr_finder. uses {
284
+ // In every expression where the binding is referenced, we will look at that
285
+ // expression's type and see if it is where the incorrect found type was fully
286
+ // "materialized" and point at it. We will also try to provide a suggestion there.
287
+ if let Some ( hir:: Node :: Expr ( expr)
288
+ | hir:: Node :: Stmt ( hir:: Stmt {
289
+ kind : hir:: StmtKind :: Expr ( expr) | hir:: StmtKind :: Semi ( expr) ,
290
+ ..
291
+ } ) ) = & map. find_parent ( binding. hir_id )
292
+ && let hir:: ExprKind :: MethodCall ( segment, rcvr, args, _span) = expr. kind
293
+ && rcvr. hir_id == binding. hir_id
294
+ && let Some ( def_id) = self . typeck_results . borrow ( ) . type_dependent_def_id ( expr. hir_id )
295
+ {
296
+ // We special case methods, because they can influence inference through the
297
+ // call's arguments and we can provide a more explicit span.
298
+ let sig = self . tcx . fn_sig ( def_id) ;
299
+ let def_self_ty = sig. input ( 0 ) . skip_binder ( ) ;
300
+ let rcvr_ty = self . node_ty ( rcvr. hir_id ) ;
301
+ // Get the evaluated type *after* calling the method call, so that the influence
302
+ // of the arguments can be reflected in the receiver type. The receiver
303
+ // expression has the type *before* theis analysis is done.
304
+ let ty = match self . lookup_probe (
305
+ segment. ident ,
306
+ rcvr_ty,
307
+ expr,
308
+ probe:: ProbeScope :: TraitsInScope ,
309
+ ) {
310
+ Ok ( pick) => pick. self_ty ,
311
+ Err ( _) => rcvr_ty,
312
+ } ;
313
+ // Remove one layer of references to account for `&mut self` and
314
+ // `&self`, so that we can compare it against the binding.
315
+ let ( ty, def_self_ty) = match ( ty. kind ( ) , def_self_ty. kind ( ) ) {
316
+ ( ty:: Ref ( _, ty, a) , ty:: Ref ( _, self_ty, b) ) if a == b => ( * ty, * self_ty) ,
317
+ _ => ( ty, def_self_ty) ,
318
+ } ;
319
+ let mut param_args = FxHashMap :: default ( ) ;
320
+ let mut param_expected = FxHashMap :: default ( ) ;
321
+ let mut param_found = FxHashMap :: default ( ) ;
322
+ if self . can_eq ( self . param_env , ty, found) . is_ok ( ) {
323
+ // We only point at the first place where the found type was inferred.
324
+ for ( i, param_ty) in sig. inputs ( ) . skip_binder ( ) . iter ( ) . skip ( 1 ) . enumerate ( ) {
325
+ if def_self_ty. contains ( * param_ty) && let ty:: Param ( _) = param_ty. kind ( ) {
326
+ // We found an argument that references a type parameter in `Self`,
327
+ // so we assume that this is the argument that caused the found
328
+ // type, which we know already because of `can_eq` above was first
329
+ // inferred in this method call.
330
+ let arg = & args[ i] ;
331
+ let arg_ty = self . node_ty ( arg. hir_id ) ;
332
+ err. span_label (
333
+ arg. span ,
334
+ & format ! (
335
+ "this is of type `{arg_ty}`, which causes `{ident}` to be \
336
+ inferred as `{ty}`",
337
+ ) ,
338
+ ) ;
339
+ param_args. insert ( param_ty, ( arg, arg_ty) ) ;
340
+ }
341
+ }
342
+ }
343
+
344
+ // Here we find, for a type param `T`, the type that `T` is in the current
345
+ // method call *and* in the original expected type. That way, we can see if we
346
+ // can give any structured suggestion for the function argument.
347
+ let mut c = CollectAllMismatches {
348
+ infcx : & self . infcx ,
349
+ param_env : self . param_env ,
350
+ errors : vec ! [ ] ,
351
+ } ;
352
+ let _ = c. relate ( def_self_ty, ty) ;
353
+ for error in c. errors {
354
+ if let TypeError :: Sorts ( error) = error {
355
+ param_found. insert ( error. expected , error. found ) ;
356
+ }
357
+ }
358
+ c. errors = vec ! [ ] ;
359
+ let _ = c. relate ( def_self_ty, expected) ;
360
+ for error in c. errors {
361
+ if let TypeError :: Sorts ( error) = error {
362
+ param_expected. insert ( error. expected , error. found ) ;
363
+ }
364
+ }
365
+ for ( param, ( arg, arg_ty) ) in param_args. iter ( ) {
366
+ let Some ( expected) = param_expected. get ( param) else { continue ; } ;
367
+ let Some ( found) = param_found. get ( param) else { continue ; } ;
368
+ if self . can_eq ( self . param_env , * arg_ty, * found) . is_err ( ) { continue ; }
369
+ self . emit_coerce_suggestions ( err, arg, * found, * expected, None , None ) ;
370
+ }
371
+
372
+ let ty = eraser. fold_ty ( ty) ;
373
+ if ty. references_error ( ) {
374
+ break ;
375
+ }
376
+ if ty != prev
377
+ && param_args. is_empty ( )
378
+ && self . can_eq ( self . param_env , ty, found) . is_ok ( )
379
+ {
380
+ // We only point at the first place where the found type was inferred.
381
+ err. span_label (
382
+ segment. ident . span ,
383
+ with_forced_trimmed_paths ! ( format!(
384
+ "here the type of `{ident}` is inferred to be `{ty}`" ,
385
+ ) ) ,
386
+ ) ;
387
+ break ;
388
+ } else if !param_args. is_empty ( ) {
389
+ break ;
390
+ }
391
+ prev = ty;
392
+ } else {
393
+ let ty = eraser. fold_ty ( self . node_ty ( binding. hir_id ) ) ;
394
+ if ty. references_error ( ) {
395
+ break ;
396
+ }
397
+ if ty != prev
398
+ && let Some ( span) = prev_span
399
+ && self . can_eq ( self . param_env , ty, found) . is_ok ( )
400
+ {
401
+ // We only point at the first place where the found type was inferred.
402
+ // We use the *previous* span because if the type is known *here* it means
403
+ // it was *evaluated earlier*. We don't do this for method calls because we
404
+ // evaluate the method's self type eagerly, but not in any other case.
405
+ err. span_label (
406
+ span,
407
+ with_forced_trimmed_paths ! ( format!(
408
+ "here the type of `{ident}` is inferred to be `{ty}`" ,
409
+ ) ) ,
410
+ ) ;
411
+ break ;
412
+ }
413
+ prev = ty;
414
+ }
415
+ if binding. hir_id == expr. hir_id {
416
+ // Do not look at expressions that come after the expression we were originally
417
+ // evaluating and had a type error.
418
+ break ;
419
+ }
420
+ prev_span = Some ( binding. span ) ;
421
+ }
422
+ true
423
+ }
424
+
208
425
fn annotate_expected_due_to_let_ty (
209
426
& self ,
210
427
err : & mut Diagnostic ,
0 commit comments