@@ -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:: fmt;
@@ -25,17 +26,6 @@ declare_clippy_lint! {
25
26
/// ### Why is this bad?
26
27
/// Using `entry` is more efficient.
27
28
///
28
- /// ### Known problems
29
- /// The suggestion may have type inference errors in some cases. e.g.
30
- /// ```no_run
31
- /// let mut map = std::collections::HashMap::new();
32
- /// let _ = if !map.contains_key(&0) {
33
- /// map.insert(0, 0)
34
- /// } else {
35
- /// None
36
- /// };
37
- /// ```
38
- ///
39
29
/// ### Example
40
30
/// ```no_run
41
31
/// # use std::collections::HashMap;
@@ -653,15 +643,24 @@ impl<'tcx> InsertSearchResults<'tcx> {
653
643
(
654
644
self . snippet ( cx, span, app, |res, insertion, ctxt, app| {
655
645
// Insertion into a map would return `None`, but the entry returns a mutable reference.
656
- let value_str = snippet_with_context ( cx, insertion. value . span , ctxt, ".." , app) . 0 ;
646
+ let value = insertion. value ;
647
+ let value_str = snippet_with_context ( cx, value. span , ctxt, ".." , app) . 0 ;
648
+
649
+ let value_ty = cx. typeck_results ( ) . expr_ty ( value) ;
650
+ debug_assert ! (
651
+ value_ty. is_suggestable( cx. tcx, true ) ,
652
+ "an unsuggestable type used as the element type:{value_ty:#?}\n expr={value:#?}"
653
+ ) ;
654
+ let none_str = format_args ! ( "None::<{value_ty}>" ) ;
655
+
657
656
let _: fmt:: Result = if is_expr_final_block_expr ( cx. tcx , insertion. call ) {
658
657
write ! (
659
658
res,
660
- "e.insert({value_str});\n {indent}None " ,
659
+ "e.insert({value_str});\n {indent}{none_str} " ,
661
660
indent = snippet_indent( cx, insertion. call. span) . as_deref( ) . unwrap_or( "" ) ,
662
661
)
663
662
} else {
664
- write ! ( res, "{{ e.insert({value_str}); None }}" )
663
+ write ! ( res, "{{ e.insert({value_str}); {none_str} }}" )
665
664
} ;
666
665
} ) ,
667
666
"Vacant(e)" ,
0 commit comments