@@ -12,6 +12,7 @@ use rustc_hir::hir_id::HirIdSet;
12
12
use rustc_hir:: intravisit:: { Visitor , walk_body, walk_expr} ;
13
13
use rustc_hir:: { Block , Expr , ExprKind , HirId , Pat , Stmt , StmtKind , UnOp } ;
14
14
use rustc_lint:: { LateContext , LateLintPass } ;
15
+ use rustc_middle:: ty:: IsSuggestable ;
15
16
use rustc_session:: declare_lint_pass;
16
17
use rustc_span:: { DUMMY_SP , Span , SyntaxContext , sym} ;
17
18
use std:: ops:: ControlFlow ;
@@ -24,17 +25,6 @@ declare_clippy_lint! {
24
25
/// ### Why is this bad?
25
26
/// Using `entry` is more efficient.
26
27
///
27
- /// ### Known problems
28
- /// The suggestion may have type inference errors in some cases. e.g.
29
- /// ```no_run
30
- /// let mut map = std::collections::HashMap::new();
31
- /// let _ = if !map.contains_key(&0) {
32
- /// map.insert(0, 0)
33
- /// } else {
34
- /// None
35
- /// };
36
- /// ```
37
- ///
38
28
/// ### Example
39
29
/// ```no_run
40
30
/// # use std::collections::HashMap;
@@ -652,15 +642,24 @@ impl<'tcx> InsertSearchResults<'tcx> {
652
642
(
653
643
self . snippet ( cx, span, app, |res, insertion, ctxt, app| {
654
644
// Insertion into a map would return `None`, but the entry returns a mutable reference.
655
- let value_str = snippet_with_context ( cx, insertion. value . span , ctxt, ".." , app) . 0 ;
645
+ let value = insertion. value ;
646
+ let value_str = snippet_with_context ( cx, value. span , ctxt, ".." , app) . 0 ;
647
+
648
+ let value_ty = cx. typeck_results ( ) . expr_ty ( value) ;
649
+ debug_assert ! (
650
+ value_ty. is_suggestable( cx. tcx, true ) ,
651
+ "an unsuggestable type used as the element type:{value_ty:#?}\n expr={value:#?}"
652
+ ) ;
653
+ let none_str = format_args ! ( "None::<{value_ty}>" ) ;
654
+
656
655
let _ = if is_expr_final_block_expr ( cx. tcx , insertion. call ) {
657
656
write ! (
658
657
res,
659
- "e.insert({value_str});\n {indent}None " ,
658
+ "e.insert({value_str});\n {indent}{none_str} " ,
660
659
indent = snippet_indent( cx, insertion. call. span) . as_deref( ) . unwrap_or( "" ) ,
661
660
)
662
661
} else {
663
- write ! ( res, "{{ e.insert({value_str}); None }}" )
662
+ write ! ( res, "{{ e.insert({value_str}); {none_str} }}" )
664
663
} ;
665
664
} ) ,
666
665
"Vacant(e)" ,
0 commit comments