Repository: rust-lang/rust-analyzer (rust)

Issue:
assist: replace generic with impl trait
```rust
fn new<P: AsRef<Path>>(location: P) -> Self { }
```
Placing the cursor on `P: AsRef<Path>` or on the `P` of `location: P` should trigger an assist to change this to
```rust
fn new(location: impl AsRef<Path>) -> Self { }
```

We already have an assist `replace impl trait with generic` that does the opposite.

<!-- TRIAGEBOT_START -->

<!-- TRIAGEBOT_ASSIGN_START -->

<!-- TRIAGEBOT_ASSIGN_DATA_START$${"user":"justahero"}$$TRIAGEBOT_ASSIGN_DATA_END -->

<!-- TRIAGEBOT_ASSIGN_END -->
<!-- TRIAGEBOT_END -->

Pull request description:
feat: Assist to replace generic with impl trait
This adds a new assist named "Replace named generic with impl". It is the inverse operation to the existing "Replace impl trait with generic" assist.

It allows to refactor the following statement:

```rust
//      👇 cursor
fn new<T$0: ToString>(input: T) -> Self {}
```

to be transformed into:

```rust
fn new(input: impl ToString) -> Self {}
```

* adds new helper function `impl_trait_type` to create AST node
* add method to remove an existing generic param type from param list

Closes #14626

Patch:
diff --git a/crates/hir-def/src/body.rs b/crates/hir-def/src/body.rs
index 36626ed1a9..a387bdbc19 100644
--- a/crates/hir-def/src/body.rs
+++ b/crates/hir-def/src/body.rs
@@ -227,8 +227,9 @@ impl Body {
         });
     }
 
-    pub fn walk_pats_shallow(&self, pat_id: PatId, mut f: impl FnMut(PatId)) {
+    pub fn walk_pats(&self, pat_id: PatId, f: &mut impl FnMut(PatId)) {
         let pat = &self[pat_id];
+        f(pat_id);
         match pat {
             Pat::Range { .. }
             | Pat::Lit(..)
@@ -238,28 +239,23 @@ impl Body {
             | Pat::Missing => {}
             &Pat::Bind { subpat, .. } => {
                 if let Some(subpat) = subpat {
-                    f(subpat);
+                    self.walk_pats(subpat, f);
                 }
             }
             Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => {
-                args.iter().copied().for_each(|p| f(p));
+                args.iter().copied().for_each(|p| self.walk_pats(p, f));
             }
-            Pat::Ref { pat, .. } => f(*pat),
+            Pat::Ref { pat, .. } => self.walk_pats(*pat, f),
             Pat::Slice { prefix, slice, suffix } => {
                 let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter());
-                total_iter.copied().for_each(|p| f(p));
+                total_iter.copied().for_each(|p| self.walk_pats(p, f));
             }
             Pat::Record { args, .. } => {
-                args.iter().for_each(|RecordFieldPat { pat, .. }| f(*pat));
+                args.iter().for_each(|RecordFieldPat { pat, .. }| self.walk_pats(*pat, f));
             }
-            Pat::Box { inner } => f(*inner),
+            Pat::Box { inner } => self.walk_pats(*inner, f),
         }
     }
-
-    pub fn walk_pats(&self, pat_id: PatId, f: &mut impl FnMut(PatId)) {
-        f(pat_id);
-        self.walk_pats_shallow(pat_id, |p| self.walk_pats(p, f));
-    }
 }
 
 impl Default for Body {
diff --git a/crates/hir-expand/src/builtin_fn_macro.rs b/crates/hir-expand/src/builtin_fn_macro.rs
index 7ce5b02314..0640ba774b 100644
--- a/crates/hir-expand/src/builtin_fn_macro.rs
+++ b/crates/hir-expand/src/builtin_fn_macro.rs
@@ -820,10 +820,10 @@ fn option_env_expand(
             )
         }
     };
-    // FIXME: Use `DOLLAR_CRATE` when that works in eager macros.
+
     let expanded = match get_env_inner(db, arg_id, &key) {
-        None => quote! { ::core::option::Option::None::<&str> },
-        Some(s) => quote! { ::core::option::Option::Some(#s) },
+        None => quote! { #DOLLAR_CRATE::option::Option::None::<&str> },
+        Some(s) => quote! { #DOLLAR_CRATE::option::Option::Some(#s) },
     };
 
     ExpandResult::ok(ExpandedEager::new(expanded))
diff --git a/crates/hir-ty/src/infer/closure.rs b/crates/hir-ty/src/infer/closure.rs
index 787c5c54a2..7878ebcc58 100644
--- a/crates/hir-ty/src/infer/closure.rs
+++ b/crates/hir-ty/src/infer/closure.rs
@@ -643,21 +643,7 @@ impl InferenceContext<'_> {
             }
             None => *result = Some(ck),
         };
-
-        self.walk_pat_inner(
-            pat,
-            &mut update_result,
-            BorrowKind::Mut { allow_two_phase_borrow: false },
-        );
-    }
-
-    fn walk_pat_inner(
-        &mut self,
-        p: PatId,
-        update_result: &mut impl FnMut(CaptureKind),
-        mut for_mut: BorrowKind,
-    ) {
-        match &self.body[p] {
+        self.body.walk_pats(pat, &mut |p| match &self.body[p] {
             Pat::Ref { .. }
             | Pat::Box { .. }
             | Pat::Missing
@@ -692,15 +678,13 @@ impl InferenceContext<'_> {
                     }
                 }
                 crate::BindingMode::Ref(r) => match r {
-                    Mutability::Mut => update_result(CaptureKind::ByRef(for_mut)),
+                    Mutability::Mut => update_result(CaptureKind::ByRef(BorrowKind::Mut {
+                        allow_two_phase_borrow: false,
+                    })),
                     Mutability::Not => update_result(CaptureKind::ByRef(BorrowKind::Shared)),
                 },
             },
-        }
-        if self.result.pat_adjustments.get(&p).map_or(false, |x| !x.is_empty()) {
-            for_mut = BorrowKind::Unique;
-        }
-        self.body.walk_pats_shallow(p, |p| self.walk_pat_inner(p, update_result, for_mut));
+        });
     }
 
     fn expr_ty(&self, expr: ExprId) -> Ty {
diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs
index f307584843..b800c2e32a 100644
--- a/crates/hir-ty/src/infer/expr.rs
+++ b/crates/hir-ty/src/infer/expr.rs
@@ -575,9 +575,6 @@ impl<'a> InferenceContext<'a> {
                     let field_ty = field_def.map_or(self.err_ty(), |it| {
                         field_types[it.local_id].clone().substitute(Interner, &substs)
                     });
-                    // Field type might have some unknown types
-                    // FIXME: we may want to emit a single type variable for all instance of type fields?
-                    let field_ty = self.insert_type_vars(field_ty);
                     self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
                 }
                 if let Some(expr) = spread {
@@ -1025,8 +1022,7 @@ impl<'a> InferenceContext<'a> {
                 )
             }
         };
-        // Try to evaluate unevaluated constant, and insert variable if is not possible.
-        let len = self.table.insert_const_vars_shallow(len);
+
         TyKind::Array(elem_ty, len).intern(Interner)
     }
 
@@ -1682,10 +1678,9 @@ impl<'a> InferenceContext<'a> {
                 } else {
                     param_ty
                 };
-                // The function signature may contain some unknown types, so we need to insert
-                // type vars here to avoid type mismatch false positive.
-                let coercion_target = self.insert_type_vars(coercion_target);
-                if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
+                if !coercion_target.is_unknown()
+                    && self.coerce(Some(arg), &ty, &coercion_target).is_err()
+                {
                     self.result.type_mismatches.insert(
                         arg.into(),
                         TypeMismatch { expected: coercion_target, actual: ty.clone() },
diff --git a/crates/hir-ty/src/infer/unify.rs b/crates/hir-ty/src/infer/unify.rs
index 38eae475b5..21b962a48f 100644
--- a/crates/hir-ty/src/infer/unify.rs
+++ b/crates/hir-ty/src/infer/unify.rs
@@ -781,16 +781,8 @@ impl<'a> InferenceTable<'a> {
     pub(super) fn insert_const_vars_shallow(&mut self, c: Const) -> Const {
         let data = c.data(Interner);
         match &data.value {
-            ConstValue::Concrete(cc) => match &cc.interned {
+            ConstValue::Concrete(cc) => match cc.interned {
                 crate::ConstScalar::Unknown => self.new_const_var(data.ty.clone()),
-                // try to evaluate unevaluated const. Replace with new var if const eval failed.
-                crate::ConstScalar::UnevaluatedConst(id, subst) => {
-                    if let Ok(eval) = self.db.const_eval(*id, subst.clone()) {
-                        eval
-                    } else {
-                        self.new_const_var(data.ty.clone())
-                    }
-                }
                 _ => c,
             },
             _ => c,
diff --git a/crates/ide-assists/src/handlers/replace_named_generic_with_impl.rs b/crates/ide-assists/src/handlers/replace_named_generic_with_impl.rs
new file mode 100644
index 0000000000..f32ceb4265
--- /dev/null
+++ b/crates/ide-assists/src/handlers/replace_named_generic_with_impl.rs
@@ -0,0 +1,213 @@
+use hir::Semantics;
+use ide_db::{
+    base_db::{FileId, FileRange},
+    defs::Definition,
+    search::SearchScope,
+    RootDatabase,
+};
+use syntax::{
+    ast::{self, make::impl_trait_type, HasGenericParams, HasName, HasTypeBounds},
+    ted, AstNode,
+};
+
+use crate::{AssistContext, AssistId, AssistKind, Assists};
+
+// Assist: replace_named_generic_with_impl
+//
+// Replaces named generic with an `impl Trait` in function argument.
+//
+// ```
+// fn new<P$0: AsRef<Path>>(location: P) -> Self {}
+// ```
+// ->
+// ```
+// fn new(location: impl AsRef<Path>) -> Self {}
+// ```
+pub(crate) fn replace_named_generic_with_impl(
+    acc: &mut Assists,
+    ctx: &AssistContext<'_>,
+) -> Option<()> {
+    // finds `<P: AsRef<Path>>`
+    let type_param = ctx.find_node_at_offset::<ast::TypeParam>()?;
+    // returns `P`
+    let type_param_name = type_param.name()?;
+
+    // The list of type bounds / traits: `AsRef<Path>`
+    let type_bound_list = type_param.type_bound_list()?;
+
+    let fn_ = type_param.syntax().ancestors().find_map(ast::Fn::cast)?;
+    let params = fn_
+        .param_list()?
+        .params()
+        .filter_map(|param| {
+            // function parameter type needs to match generic type name
+            if let ast::Type::PathType(path_type) = param.ty()? {
+                let left = path_type.path()?.segment()?.name_ref()?.ident_token()?.to_string();
+                let right = type_param_name.to_string();
+                if left == right {
+                    Some(param)
+                } else {
+                    None
+                }
+            } else {
+                None
+            }
+        })
+        .collect::<Vec<_>>();
+
+    if params.is_empty() {
+        return None;
+    }
+
+    let type_param_hir_def = ctx.sema.to_def(&type_param)?;
+    let type_param_def = Definition::GenericParam(hir::GenericParam::TypeParam(type_param_hir_def));
+
+    if is_referenced_outside(&ctx.sema, type_param_def, &fn_, ctx.file_id()) {
+        return None;
+    }
+
+    let target = type_param.syntax().text_range();
+
+    acc.add(
+        AssistId("replace_named_generic_with_impl", AssistKind::RefactorRewrite),
+        "Replace named generic with impl",
+        target,
+        |edit| {
+            let type_param = edit.make_mut(type_param);
+            let fn_ = edit.make_mut(fn_);
+
+            // get all params
+            let param_types = params
+                .iter()
+                .filter_map(|param| match param.ty() {
+                    Some(ast::Type::PathType(param_type)) => Some(edit.make_mut(param_type)),
+                    _ => None,
+                })
+                .collect::<Vec<_>>();
+
+            if let Some(generic_params) = fn_.generic_param_list() {
+                generic_params.remove_generic_param(ast::GenericParam::TypeParam(type_param));
+                if generic_params.generic_params().count() == 0 {
+                    ted::remove(generic_params.syntax());
+                }
+            }
+
+            // get type bounds in signature type: `P` -> `impl AsRef<Path>`
+            let new_bounds = impl_trait_type(type_bound_list);
+            for param_type in param_types.iter().rev() {
+                ted::replace(param_type.syntax(), new_bounds.clone_for_update().syntax());
+            }
+        },
+    )
+}
+
+fn is_referenced_outside(
+    sema: &Semantics<'_, RootDatabase>,
+    type_param_def: Definition,
+    fn_: &ast::Fn,
+    file_id: FileId,
+) -> bool {
+    // limit search scope to function body & return type
+    let search_ranges = vec![
+        fn_.body().map(|body| body.syntax().text_range()),
+        fn_.ret_type().map(|ret_type| ret_type.syntax().text_range()),
+    ];
+
+    search_ranges.into_iter().flatten().any(|search_range| {
+        let file_range = FileRange { file_id, range: search_range };
+        !type_param_def.usages(sema).in_scope(SearchScope::file_range(file_range)).all().is_empty()
+    })
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    use crate::tests::{check_assist, check_assist_not_applicable};
+
+    #[test]
+    fn replace_generic_moves_into_function() {
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"fn new<T$0: ToString>(input: T) -> Self {}"#,
+            r#"fn new(input: impl ToString) -> Self {}"#,
+        );
+    }
+
+    #[test]
+    fn replace_generic_with_inner_associated_type() {
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"fn new<P$0: AsRef<Path>>(input: P) -> Self {}"#,
+            r#"fn new(input: impl AsRef<Path>) -> Self {}"#,
+        );
+    }
+
+    #[test]
+    fn replace_generic_trait_applies_to_all_matching_params() {
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"fn new<T$0: ToString>(a: T, b: T) -> Self {}"#,
+            r#"fn new(a: impl ToString, b: impl ToString) -> Self {}"#,
+        );
+    }
+
+    #[test]
+    fn replace_generic_with_multiple_generic_params() {
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"fn new<P: AsRef<Path>, T$0: ToString>(t: T, p: P) -> Self {}"#,
+            r#"fn new<P: AsRef<Path>>(t: impl ToString, p: P) -> Self {}"#,
+        );
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"fn new<T$0: ToString, P: AsRef<Path>>(t: T, p: P) -> Self {}"#,
+            r#"fn new<P: AsRef<Path>>(t: impl ToString, p: P) -> Self {}"#,
+        );
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"fn new<A: Send, B$0: ToString, C: Debug>(a: A, b: B, c: C) -> Self {}"#,
+            r#"fn new<A: Send, C: Debug>(a: A, b: impl ToString, c: C) -> Self {}"#,
+        );
+    }
+
+    #[test]
+    fn replace_generic_with_multiple_trait_bounds() {
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"fn new<P$0: Send + Sync>(p: P) -> Self {}"#,
+            r#"fn new(p: impl Send + Sync) -> Self {}"#,
+        );
+    }
+
+    #[test]
+    fn replace_generic_not_applicable_if_param_used_as_return_type() {
+        check_assist_not_applicable(
+            replace_named_generic_with_impl,
+            r#"fn new<P$0: Send + Sync>(p: P) -> P {}"#,
+        );
+    }
+
+    #[test]
+    fn replace_generic_not_applicable_if_param_used_in_fn_body() {
+        check_assist_not_applicable(
+            replace_named_generic_with_impl,
+            r#"fn new<P$0: ToString>(p: P) { let x: &dyn P = &O; }"#,
+        );
+    }
+
+    #[test]
+    fn replace_generic_ignores_another_function_with_same_param_type() {
+        check_assist(
+            replace_named_generic_with_impl,
+            r#"
+            fn new<P$0: Send + Sync>(p: P) {}
+            fn hello<P: Debug>(p: P) { println!("{:?}", p); }
+            "#,
+            r#"
+            fn new(p: impl Send + Sync) {}
+            fn hello<P: Debug>(p: P) { println!("{:?}", p); }
+            "#,
+        );
+    }
+}
diff --git a/crates/ide-assists/src/lib.rs b/crates/ide-assists/src/lib.rs
index fc03903e59..bd282e5343 100644
--- a/crates/ide-assists/src/lib.rs
+++ b/crates/ide-assists/src/lib.rs
@@ -193,6 +193,7 @@ mod handlers {
     mod replace_arith_op;
     mod introduce_named_generic;
     mod replace_let_with_if_let;
+    mod replace_named_generic_with_impl;
     mod replace_qualified_name_with_use;
     mod replace_string_with_char;
     mod replace_turbofish_with_explicit_type;
@@ -299,6 +300,7 @@ mod handlers {
             replace_let_with_if_let::replace_let_with_if_let,
             replace_method_eager_lazy::replace_with_eager_method,
             replace_method_eager_lazy::replace_with_lazy_method,
+            replace_named_generic_with_impl::replace_named_generic_with_impl,
             replace_turbofish_with_explicit_type::replace_turbofish_with_explicit_type,
             replace_qualified_name_with_use::replace_qualified_name_with_use,
             replace_arith_op::replace_arith_with_wrapping,
diff --git a/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/crates/ide-diagnostics/src/handlers/mutability_errors.rs
index 45b44c2c5c..0af4100180 100644
--- a/crates/ide-diagnostics/src/handlers/mutability_errors.rs
+++ b/crates/ide-diagnostics/src/handlers/mutability_errors.rs
@@ -352,32 +352,6 @@ fn main() {
         );
     }
 
-    #[test]
-    fn match_closure_capture() {
-        check_diagnostics(
-            r#"
-//- minicore: option
-fn main() {
-    let mut v = &mut Some(2);
-      //^^^^^ 💡 weak: variable does not need to be mutable
-    let _ = || match v {
-        Some(k) => {
-            *k = 5;
-        }
-        None => {}
-    };
-    let v = &mut Some(2);
-    let _ = || match v {
-                   //^ 💡 error: cannot mutate immutable variable `v`
-        ref mut k => {
-            *k = &mut Some(5);
-        }
-    };
-}
-"#,
-        );
-    }
-
     #[test]
     fn match_bindings() {
         check_diagnostics(
diff --git a/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/crates/ide-diagnostics/src/handlers/type_mismatch.rs
index c28f98d833..a5359741ac 100644
--- a/crates/ide-diagnostics/src/handlers/type_mismatch.rs
+++ b/crates/ide-diagnostics/src/handlers/type_mismatch.rs
@@ -644,47 +644,6 @@ fn h() {
         );
     }
 
-    #[test]
-    fn unknown_type_in_function_signature() {
-        check_diagnostics(
-            r#"
-struct X<T>(T);
-
-fn foo(x: X<Unknown>) {}
-fn test1() {
-    // Unknown might be `i32`, so we should not emit type mismatch here.
-    foo(X(42));
-}
-fn test2() {
-    foo(42);
-      //^^ error: expected X<{unknown}>, found i32
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn evaluate_const_generics_in_types() {
-        check_diagnostics(
-            r#"
-pub const ONE: usize = 1;
-
-pub struct Inner<const P: usize>();
-
-pub struct Outer {
-    pub inner: Inner<ONE>,
-}
-
-fn main() {
-    _ = Outer {
-        inner: Inner::<2>(),
-             //^^^^^^^^^^^^ error: expected Inner<1>, found Inner<2>
-    };
-}
-"#,
-        );
-    }
-
     #[test]
     fn type_mismatch_pat_smoke_test() {
         check_diagnostics(
diff --git a/crates/ide/src/goto_type_definition.rs b/crates/ide/src/goto_type_definition.rs
index 6048990f74..fb55a60ec4 100644
--- a/crates/ide/src/goto_type_definition.rs
+++ b/crates/ide/src/goto_type_definition.rs
@@ -38,41 +38,32 @@ pub(crate) fn goto_type_definition(
     };
     let range = token.text_range();
     sema.descend_into_macros(token)
-        .into_iter()
+        .iter()
         .filter_map(|token| {
-            let ty = sema
-                .token_ancestors_with_macros(token)
-                // When `token` is within a macro call, we can't determine its type. Don't continue
-                // this traversal because otherwise we'll end up returning the type of *that* macro
-                // call, which is not what we want in general.
-                //
-                // Macro calls always wrap `TokenTree`s, so it's sufficient and efficient to test
-                // if the current node is a `TokenTree`.
-                .take_while(|node| !ast::TokenTree::can_cast(node.kind()))
-                .find_map(|node| {
-                    let ty = match_ast! {
-                        match node {
-                            ast::Expr(it) => sema.type_of_expr(&it)?.original,
-                            ast::Pat(it) => sema.type_of_pat(&it)?.original,
-                            ast::SelfParam(it) => sema.type_of_self(&it)?,
-                            ast::Type(it) => sema.resolve_type(&it)?,
-                            ast::RecordField(it) => sema.to_def(&it)?.ty(db.upcast()),
-                            // can't match on RecordExprField directly as `ast::Expr` will match an iteration too early otherwise
-                            ast::NameRef(it) => {
-                                if let Some(record_field) = ast::RecordExprField::for_name_ref(&it) {
-                                    let (_, _, ty) = sema.resolve_record_field(&record_field)?;
-                                    ty
-                                } else {
-                                    let record_field = ast::RecordPatField::for_field_name_ref(&it)?;
-                                    sema.resolve_record_pat_field(&record_field)?.1
-                                }
-                            },
-                            _ => return None,
-                        }
-                    };
+            let ty = sema.token_ancestors_with_macros(token.clone()).find_map(|node| {
+                let ty = match_ast! {
+                    match node {
+                        ast::Expr(it) => sema.type_of_expr(&it)?.original,
+                        ast::Pat(it) => sema.type_of_pat(&it)?.original,
+                        ast::SelfParam(it) => sema.type_of_self(&it)?,
+                        ast::Type(it) => sema.resolve_type(&it)?,
+                        ast::RecordField(it) => sema.to_def(&it).map(|d| d.ty(db.upcast()))?,
+                        // can't match on RecordExprField directly as `ast::Expr` will match an iteration too early otherwise
+                        ast::NameRef(it) => {
+                            if let Some(record_field) = ast::RecordExprField::for_name_ref(&it) {
+                                let (_, _, ty) = sema.resolve_record_field(&record_field)?;
+                                ty
+                            } else {
+                                let record_field = ast::RecordPatField::for_field_name_ref(&it)?;
+                                sema.resolve_record_pat_field(&record_field)?.1
+                            }
+                        },
+                        _ => return None,
+                    }
+                };
 
-                    Some(ty)
-                });
+                Some(ty)
+            });
             ty
         })
         .for_each(|ty| {
@@ -103,7 +94,7 @@ mod tests {
     fn check(ra_fixture: &str) {
         let (analysis, position, expected) = fixture::annotations(ra_fixture);
         let navs = analysis.goto_type_definition(position).unwrap().unwrap().info;
-        assert!(!navs.is_empty(), "navigation is empty");
+        assert_ne!(navs.len(), 0);
 
         let cmp = |&FileRange { file_id, range }: &_| (file_id, range.start());
         let navs = navs
@@ -113,7 +104,7 @@ mod tests {
             .collect::<Vec<_>>();
         let expected = expected
             .into_iter()
-            .map(|(file_range, _)| file_range)
+            .map(|(FileRange { file_id, range }, _)| FileRange { file_id, range })
             .sorted_by_key(cmp)
             .collect::<Vec<_>>();
         assert_eq!(expected, navs);
@@ -207,32 +198,6 @@ id! {
         );
     }
 
-    #[test]
-    fn dont_collect_type_from_token_in_macro_call() {
-        check(
-            r#"
-struct DontCollectMe;
-struct S;
-     //^
-
-macro_rules! inner {
-    ($t:tt) => { DontCollectMe }
-}
-macro_rules! m {
-    ($t:ident) => {
-        match $t {
-            _ => inner!($t);
-        }
-    }
-}
-
-fn test() {
-    m!($0S);
-}
-"#,
-        );
-    }
-
     #[test]
     fn goto_type_definition_for_param() {
         check(
diff --git a/crates/rust-analyzer/src/cli/flags.rs b/crates/rust-analyzer/src/cli/flags.rs
index 31012c01b9..6b5a79b431 100644
--- a/crates/rust-analyzer/src/cli/flags.rs
+++ b/crates/rust-analyzer/src/cli/flags.rs
@@ -112,9 +112,6 @@ xflags::xflags! {
 
         cmd scip {
             required path: PathBuf
-
-            /// The output path where the SCIP file will be written to. Defaults to `index.scip`.
-            optional --output path: PathBuf
         }
     }
 }
@@ -211,7 +208,6 @@ pub struct Lsif {
 #[derive(Debug)]
 pub struct Scip {
     pub path: PathBuf,
-    pub output: Option<PathBuf>,
 }
 
 impl RustAnalyzer {
diff --git a/crates/rust-analyzer/src/cli/scip.rs b/crates/rust-analyzer/src/cli/scip.rs
index b0b724bdfe..61924d5843 100644
--- a/crates/rust-analyzer/src/cli/scip.rs
+++ b/crates/rust-analyzer/src/cli/scip.rs
@@ -2,7 +2,6 @@
 
 use std::{
     collections::{HashMap, HashSet},
-    path::PathBuf,
     time::Instant,
 };
 
@@ -166,8 +165,7 @@ impl flags::Scip {
             special_fields: Default::default(),
         };
 
-        let out_path = self.output.unwrap_or_else(|| PathBuf::from(r"index.scip"));
-        scip::write_message_to_file(out_path, index)
+        scip::write_message_to_file("index.scip", index)
             .map_err(|err| anyhow::anyhow!("Failed to write scip to file: {}", err))?;
 
         eprintln!("Generating SCIP finished {:?}", now.elapsed());
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index 99aa48fd07..f06abe0763 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -184,7 +184,6 @@ impl GlobalState {
         // NOTE: don't count blocking select! call as a loop-turn time
         let _p = profile::span("GlobalState::handle_event");
 
-        let event_dbg = format!("{event:?}");
         tracing::debug!("{:?} handle_event({:?})", loop_start, event);
         let task_queue_len = self.task_pool.handle.len();
         if task_queue_len > 0 {
@@ -395,10 +394,8 @@ impl GlobalState {
 
         let loop_duration = loop_start.elapsed();
         if loop_duration > Duration::from_millis(100) && was_quiescent {
-            tracing::warn!("overly long loop turn took {loop_duration:?}: {event_dbg}");
-            self.poke_rust_analyzer_developer(format!(
-                "overly long loop turn took {loop_duration:?}: {event_dbg}"
-            ));
+            tracing::warn!("overly long loop turn: {:?}", loop_duration);
+            self.poke_rust_analyzer_developer(format!("overly long loop turn: {loop_duration:?}"));
         }
         Ok(())
     }
diff --git a/crates/syntax/src/ast/edit_in_place.rs b/crates/syntax/src/ast/edit_in_place.rs
index 995e8d8d15..b3ea6ca8d4 100644
--- a/crates/syntax/src/ast/edit_in_place.rs
+++ b/crates/syntax/src/ast/edit_in_place.rs
@@ -236,6 +236,21 @@ impl ast::GenericParamList {
         }
     }
 
+    /// Removes the existing generic param
+    pub fn remove_generic_param(&self, generic_param: ast::GenericParam) {
+        if let Some(previous) = generic_param.syntax().prev_sibling() {
+            if let Some(next_token) = previous.next_sibling_or_token() {
+                ted::remove_all(next_token..=generic_param.syntax().clone().into());
+            }
+        } else if let Some(next) = generic_param.syntax().next_sibling() {
+            if let Some(next_token) = next.prev_sibling_or_token() {
+                ted::remove_all(generic_param.syntax().clone().into()..=next_token);
+            }
+        } else {
+            ted::remove(generic_param.syntax());
+        }
+    }
+
     /// Constructs a matching [`ast::GenericArgList`]
     pub fn to_generic_args(&self) -> ast::GenericArgList {
         let args = self.generic_params().filter_map(|param| match param {
diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs
index 8d2dc8709b..3a61fb0a52 100644
--- a/crates/syntax/src/ast/make.rs
+++ b/crates/syntax/src/ast/make.rs
@@ -232,6 +232,10 @@ pub fn impl_trait(
     ast_from_text(&format!("impl{ty_params_str} {trait_} for {ty}{ty_genargs_str} {{}}"))
 }
 
+pub fn impl_trait_type(bounds: ast::TypeBoundList) -> ast::ImplTraitType {
+    ast_from_text(&format!("fn f(x: impl {bounds}) {{}}"))
+}
+
 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
     ast_from_text(&format!("type __ = {name_ref};"))
 }


Test patch:
diff --git a/crates/hir-def/src/macro_expansion_tests/builtin_fn_macro.rs b/crates/hir-def/src/macro_expansion_tests/builtin_fn_macro.rs
index 006d292992..13aa6130be 100644
--- a/crates/hir-def/src/macro_expansion_tests/builtin_fn_macro.rs
+++ b/crates/hir-def/src/macro_expansion_tests/builtin_fn_macro.rs
@@ -97,7 +97,7 @@ fn main() { option_env!("TEST_ENV_VAR"); }
 #[rustc_builtin_macro]
 macro_rules! option_env {() => {}}
 
-fn main() { ::core::option::Option::None:: < &str>; }
+fn main() { $crate::option::Option::None:: < &str>; }
 "#]],
     );
 }
diff --git a/crates/hir-ty/src/layout/tests/closure.rs b/crates/hir-ty/src/layout/tests/closure.rs
index 576e7f3fc6..811d608880 100644
--- a/crates/hir-ty/src/layout/tests/closure.rs
+++ b/crates/hir-ty/src/layout/tests/closure.rs
@@ -201,7 +201,7 @@ fn match_pattern() {
         ]
         |x: i64| {
             match y {
-                X(_a, _, _c) => x,
+                X(_a, _b, _c) => x,
             }
         }
     }
@@ -217,18 +217,6 @@ fn match_pattern() {
             }
         }
     }
-    size_and_align_expr! {
-        minicore: copy;
-        stmts: [
-            struct X(i64, i32, (u8, i128));
-            let y: X = X(2, 5, (7, 3));
-        ]
-        |x: i64| {
-            match y {
-                ref _y => x,
-            }
-        }
-    }
 }
 
 #[test]
diff --git a/crates/hir-ty/src/tests/macros.rs b/crates/hir-ty/src/tests/macros.rs
index 772bd3e536..9377a3a5f2 100644
--- a/crates/hir-ty/src/tests/macros.rs
+++ b/crates/hir-ty/src/tests/macros.rs
@@ -947,7 +947,7 @@ fn infer_builtin_macros_concat_with_lazy() {
 
 #[test]
 fn infer_builtin_macros_env() {
-    check_types(
+    check_infer(
         r#"
         //- /main.rs env:foo=bar
         #[rustc_builtin_macro]
@@ -955,26 +955,13 @@ fn infer_builtin_macros_env() {
 
         fn main() {
             let x = env!("foo");
-              //^ &str
-        }
-        "#,
-    );
-}
-
-#[test]
-fn infer_builtin_macros_option_env() {
-    check_types(
-        r#"
-        //- minicore: option
-        //- /main.rs env:foo=bar
-        #[rustc_builtin_macro]
-        macro_rules! option_env {() => {}}
-
-        fn main() {
-            let x = option_env!("foo");
-              //^ Option<&str>
         }
         "#,
+        expect![[r#"
+            !0..22 '"__RA_...TED__"': &str
+            62..90 '{     ...o"); }': ()
+            72..73 'x': &str
+        "#]],
     );
 }
 
diff --git a/crates/hir-ty/src/tests/regression.rs b/crates/hir-ty/src/tests/regression.rs
index 1fdeddede0..9f5f1ea325 100644
--- a/crates/hir-ty/src/tests/regression.rs
+++ b/crates/hir-ty/src/tests/regression.rs
@@ -1837,78 +1837,3 @@ fn foo() {
 }",
     );
 }
-
-#[test]
-fn regression_14844() {
-    check_no_mismatches(
-        r#"
-pub type Ty = Unknown;
-
-pub struct Inner<T>();
-
-pub struct Outer {
-    pub inner: Inner<Ty>,
-}
-
-fn main() {
-    _ = Outer {
-        inner: Inner::<i32>(),
-    };
-}
-        "#,
-    );
-    check_no_mismatches(
-        r#"
-pub const ONE: usize = 1;
-
-pub struct Inner<const P: usize>();
-
-pub struct Outer {
-    pub inner: Inner<ONE>,
-}
-
-fn main() {
-    _ = Outer {
-        inner: Inner::<1>(),
-    };
-}
-        "#,
-    );
-    check_no_mismatches(
-        r#"
-pub const ONE: usize = unknown();
-
-pub struct Inner<const P: usize>();
-
-pub struct Outer {
-    pub inner: Inner<ONE>,
-}
-
-fn main() {
-    _ = Outer {
-        inner: Inner::<1>(),
-    };
-}
-        "#,
-    );
-    check_no_mismatches(
-        r#"
-pub const N: usize = 2 + 2;
-
-fn f(t: [u8; N]) {}
-
-fn main() {
-    let a = [1, 2, 3, 4];
-    f(a);
-    let b = [1; 4];
-    let c: [u8; N] = b;
-    let d = [1; N];
-    let e: [u8; N] = d;
-    let f = [1; N];
-    let g = match f {
-        [a, b, c, d] => a + b + c + d,
-    };
-}
-        "#,
-    );
-}
diff --git a/crates/ide-assists/src/tests/generated.rs b/crates/ide-assists/src/tests/generated.rs
index 0096254ecb..8a35fd290e 100644
--- a/crates/ide-assists/src/tests/generated.rs
+++ b/crates/ide-assists/src/tests/generated.rs
@@ -2338,6 +2338,19 @@ fn handle(action: Action) {
     )
 }
 
+#[test]
+fn doctest_replace_named_generic_with_impl() {
+    check_doc_test(
+        "replace_named_generic_with_impl",
+        r#####"
+fn new<P$0: AsRef<Path>>(location: P) -> Self {}
+"#####,
+        r#####"
+fn new(location: impl AsRef<Path>) -> Self {}
+"#####,
+    )
+}
+
 #[test]
 fn doctest_replace_qualified_name_with_use() {
     check_doc_test(