@@ -454,12 +454,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
454
454
false
455
455
}
456
456
457
- pub fn check_for_cast ( & self ,
458
- err : & mut DiagnosticBuilder < ' tcx > ,
459
- expr : & hir:: Expr ,
460
- checked_ty : Ty < ' tcx > ,
461
- expected_ty : Ty < ' tcx > )
462
- -> bool {
457
+ pub fn check_for_cast (
458
+ & self ,
459
+ err : & mut DiagnosticBuilder < ' tcx > ,
460
+ expr : & hir:: Expr ,
461
+ checked_ty : Ty < ' tcx > ,
462
+ expected_ty : Ty < ' tcx > ,
463
+ ) -> bool {
463
464
let parent_id = self . tcx . hir ( ) . get_parent_node ( expr. id ) ;
464
465
if let Some ( parent) = self . tcx . hir ( ) . find ( parent_id) {
465
466
// Shouldn't suggest `.into()` on `const`s.
@@ -487,17 +488,40 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
487
488
// For now, don't suggest casting with `as`.
488
489
let can_cast = false ;
489
490
491
+ let mut prefix = String :: new ( ) ;
492
+ if let Some ( hir:: Node :: Expr ( hir:: Expr {
493
+ node : hir:: ExprKind :: Struct ( _, fields, _) ,
494
+ ..
495
+ } ) ) = self . tcx . hir ( ) . find ( self . tcx . hir ( ) . get_parent_node ( expr. id ) ) {
496
+ // `expr` is a literal field for a struct, only suggest if appropriate
497
+ for field in fields {
498
+ if field. expr . id == expr. id {
499
+ // This is a field literal
500
+ prefix = format ! ( "{}: " , field. ident) ;
501
+ break ;
502
+ }
503
+ }
504
+ if & prefix == "" {
505
+ // Likely a field was meant, but this field wasn't found. Do not suggest anything.
506
+ return false ;
507
+ }
508
+ }
509
+
490
510
let needs_paren = expr. precedence ( ) . order ( ) < ( PREC_POSTFIX as i8 ) ;
491
511
492
512
if let Ok ( src) = self . tcx . sess . source_map ( ) . span_to_snippet ( expr. span ) {
493
513
let msg = format ! ( "you can cast an `{}` to `{}`" , checked_ty, expected_ty) ;
494
- let cast_suggestion = format ! ( "{}{}{} as {}" ,
495
- if needs_paren { "(" } else { "" } ,
496
- src,
497
- if needs_paren { ")" } else { "" } ,
498
- expected_ty) ;
514
+ let cast_suggestion = format ! (
515
+ "{}{}{}{} as {}" ,
516
+ prefix,
517
+ if needs_paren { "(" } else { "" } ,
518
+ src,
519
+ if needs_paren { ")" } else { "" } ,
520
+ expected_ty,
521
+ ) ;
499
522
let into_suggestion = format ! (
500
- "{}{}{}.into()" ,
523
+ "{}{}{}{}.into()" ,
524
+ prefix,
501
525
if needs_paren { "(" } else { "" } ,
502
526
src,
503
527
if needs_paren { ")" } else { "" } ,
0 commit comments