]> git.lizzy.rs Git - rust.git/commitdiff
Do not add default and closure types in 'add explicit type' assist
authorKirill Bulatov <mail4score@gmail.com>
Tue, 21 Apr 2020 19:56:11 +0000 (22:56 +0300)
committerKirill Bulatov <mail4score@gmail.com>
Tue, 21 Apr 2020 19:56:40 +0000 (22:56 +0300)
crates/ra_assists/src/handlers/add_explicit_type.rs
crates/ra_hir/src/code_model.rs

index d86d804b2ee572abf45e3ddc1c6de9cb00133a0b..6c56d93d878d4cbff8fa21f3a567150efce20224 100644 (file)
@@ -52,21 +52,22 @@ pub(crate) fn add_explicit_type(ctx: AssistCtx) -> Option<Assist> {
     }
     // Infer type
     let ty = ctx.sema.type_of_expr(&expr)?;
-    // Assist not applicable if the type is unknown
-    if ty.contains_unknown() {
+
+    if ty.contains_unknown() || ty.is_closure() {
         return None;
     }
 
     let db = ctx.db;
+    let new_type_string = ty.display_truncated(db, None).to_string();
     ctx.add_assist(
         AssistId("add_explicit_type"),
-        format!("Insert explicit type '{}'", ty.display(db)),
+        format!("Insert explicit type '{}'", new_type_string),
         |edit| {
             edit.target(pat_range);
             if let Some(ascribed_ty) = ascribed_ty {
-                edit.replace(ascribed_ty.syntax().text_range(), format!("{}", ty.display(db)));
+                edit.replace(ascribed_ty.syntax().text_range(), new_type_string);
             } else {
-                edit.insert(name_range.end(), format!(": {}", ty.display(db)));
+                edit.insert(name_range.end(), format!(": {}", new_type_string));
             }
         },
     )
@@ -174,4 +175,41 @@ fn add_explicit_type_not_applicable_if_cursor_before_let() {
             "fn f() <|>{let a = match 1 {2 => 3, 3 => 5};}",
         )
     }
+
+    #[test]
+    fn closure_parameters_are_not_added() {
+        check_assist_not_applicable(
+            add_explicit_type,
+            r#"
+fn main() {
+    let multiply_by_two<|> = |i| i * 3;
+    let six = multiply_by_two(2);
+}"#,
+        )
+    }
+
+    #[test]
+    fn default_generics_should_not_be_added() {
+        check_assist(
+            add_explicit_type,
+            r#"
+struct Test<K, T = u8> {
+    k: K,
+    t: T,
+}
+
+fn main() {
+    let test<|> = Test { t: 23, k: 33 };
+}"#,
+            r#"
+struct Test<K, T = u8> {
+    k: K,
+    t: T,
+}
+
+fn main() {
+    let test<|>: Test<i32> = Test { t: 23, k: 33 };
+}"#,
+        );
+    }
 }
index 6e0d89466bdbf14424fbbb8680301e9521b4f51c..43f932e20cc8e189ed0c22eacb3ed79aaf898eb9 100644 (file)
@@ -1132,6 +1132,10 @@ pub fn as_callable(&self) -> Option<CallableDef> {
         Some(self.ty.value.as_callable()?.0)
     }
 
+    pub fn is_closure(&self) -> bool {
+        matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { .. }, .. }))
+    }
+
     pub fn contains_unknown(&self) -> bool {
         return go(&self.ty.value);