Repository: rust-lang/rust-analyzer
Pull request #12765 (2022-07-14 20:57:10)

fix: Fix imports being inserted before doc comments in inline modules
Fixes https://github.com/rust-lang/rust-analyzer/issues/12758


Patch:
diff --git a/crates/hir-expand/src/lib.rs b/crates/hir-expand/src/lib.rs
index 8fcfad2009..0844e1f625 100644
--- a/crates/hir-expand/src/lib.rs
+++ b/crates/hir-expand/src/lib.rs
@@ -778,19 +778,36 @@ impl<'a> InFile<&'a SyntaxNode> {
     /// For attributes and derives, this will point back to the attribute only.
     /// For the entire item `InFile::use original_file_range_full`.
     pub fn original_file_range(self, db: &dyn db::AstDatabase) -> FileRange {
+        if let Some(res) = self.original_file_range_opt(db) {
+            return res;
+        }
+
+        // Fall back to whole macro call.
         match self.file_id.0 {
             HirFileIdRepr::FileId(file_id) => FileRange { file_id, range: self.value.text_range() },
             HirFileIdRepr::MacroFile(mac_file) => {
-                if let Some(res) = self.original_file_range_opt(db) {
-                    return res;
-                }
-                // Fall back to whole macro call.
                 let loc = db.lookup_intern_macro_call(mac_file.macro_call_id);
                 loc.kind.original_call_range(db)
             }
         }
     }
 
+    /// Falls back to the macro call range if the node cannot be mapped up fully.
+    pub fn original_file_range_full(self, db: &dyn db::AstDatabase) -> FileRange {
+        if let Some(res) = self.original_file_range_opt(db) {
+            return res;
+        }
+
+        // Fall back to whole macro call.
+        match self.file_id.0 {
+            HirFileIdRepr::FileId(file_id) => FileRange { file_id, range: self.value.text_range() },
+            HirFileIdRepr::MacroFile(mac_file) => {
+                let loc = db.lookup_intern_macro_call(mac_file.macro_call_id);
+                loc.kind.original_call_range_with_body(db)
+            }
+        }
+    }
+
     /// Attempts to map the syntax node back up its macro calls.
     pub fn original_file_range_opt(self, db: &dyn db::AstDatabase) -> Option<FileRange> {
         match ascend_node_border_tokens(db, self) {
@@ -817,49 +834,6 @@ impl InFile<SyntaxToken> {
         let expansion = self.file_id.expansion_info(db)?;
         expansion.map_token_up(db, self.as_ref()).map(|(it, _)| it)
     }
-
-    /// Falls back to the macro call range if the node cannot be mapped up fully.
-    pub fn original_file_range(self, db: &dyn db::AstDatabase) -> FileRange {
-        match self.file_id.0 {
-            HirFileIdRepr::FileId(file_id) => FileRange { file_id, range: self.value.text_range() },
-            HirFileIdRepr::MacroFile(mac_file) => {
-                if let Some(res) = self.original_file_range_opt(db) {
-                    return res;
-                }
-                // Fall back to whole macro call.
-                let loc = db.lookup_intern_macro_call(mac_file.macro_call_id);
-                loc.kind.original_call_range(db)
-            }
-        }
-    }
-
-    /// Attempts to map the syntax node back up its macro calls.
-    pub fn original_file_range_opt(self, db: &dyn db::AstDatabase) -> Option<FileRange> {
-        match self.file_id.0 {
-            HirFileIdRepr::FileId(file_id) => {
-                Some(FileRange { file_id, range: self.value.text_range() })
-            }
-            HirFileIdRepr::MacroFile(_) => {
-                let expansion = self.file_id.expansion_info(db)?;
-                let InFile { file_id, value } = ascend_call_token(db, &expansion, self)?;
-                let original_file = file_id.original_file(db);
-                if file_id != original_file.into() {
-                    return None;
-                }
-                Some(FileRange { file_id: original_file, range: value.text_range() })
-            }
-        }
-    }
-
-    pub fn ancestors_with_macros(
-        self,
-        db: &dyn db::AstDatabase,
-    ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
-        self.value.parent().into_iter().flat_map({
-            let file_id = self.file_id;
-            move |parent| InFile::new(file_id, &parent).ancestors_with_macros(db)
-        })
-    }
 }
 
 fn ascend_node_border_tokens(
@@ -893,6 +867,18 @@ fn ascend_call_token(
     None
 }
 
+impl InFile<SyntaxToken> {
+    pub fn ancestors_with_macros(
+        self,
+        db: &dyn db::AstDatabase,
+    ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
+        self.value.parent().into_iter().flat_map({
+            let file_id = self.file_id;
+            move |parent| InFile::new(file_id, &parent).ancestors_with_macros(db)
+        })
+    }
+}
+
 impl<N: AstNode> InFile<N> {
     pub fn descendants<T: AstNode>(self) -> impl Iterator<Item = InFile<T>> {
         self.value.syntax().descendants().filter_map(T::cast).map(move |n| self.with_value(n))
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 86124b68b5..96424d087e 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -3307,15 +3307,6 @@ impl Type {
         let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), to.ty.clone()));
         hir_ty::could_coerce(db, self.env.clone(), &tys)
     }
-
-    pub fn as_type_param(&self, db: &dyn HirDatabase) -> Option<TypeParam> {
-        match self.ty.kind(Interner) {
-            TyKind::Placeholder(p) => Some(TypeParam {
-                id: TypeParamId::from_unchecked(hir_ty::from_placeholder_idx(db, *p)),
-            }),
-            _ => None,
-        }
-    }
 }
 
 #[derive(Debug)]
diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs
index 94b638d4c6..9233c198df 100644
--- a/crates/ide-assists/src/handlers/extract_function.rs
+++ b/crates/ide-assists/src/handlers/extract_function.rs
@@ -2,9 +2,7 @@ use std::iter;
 
 use ast::make;
 use either::Either;
-use hir::{
-    HasSource, HirDisplay, InFile, Local, ModuleDef, PathResolution, Semantics, TypeInfo, TypeParam,
-};
+use hir::{HasSource, HirDisplay, InFile, Local, ModuleDef, Semantics, TypeInfo};
 use ide_db::{
     defs::{Definition, NameRefClass},
     famous_defs::FamousDefs,
@@ -20,7 +18,7 @@ use syntax::{
     ast::{
         self,
         edit::{AstNodeEdit, IndentLevel},
-        AstNode, HasGenericParams,
+        AstNode,
     },
     match_ast, ted, SyntaxElement,
     SyntaxKind::{self, COMMENT},
@@ -296,8 +294,6 @@ struct ContainerInfo {
     parent_loop: Option<SyntaxNode>,
     /// The function's return type, const's type etc.
     ret_type: Option<hir::Type>,
-    generic_param_lists: Vec<ast::GenericParamList>,
-    where_clauses: Vec<ast::WhereClause>,
 }
 
 /// Control flow that is exported from extracted function
@@ -521,24 +517,6 @@ impl FunctionBody {
         }
     }
 
-    fn descendants(&self) -> impl Iterator<Item = SyntaxNode> {
-        match self {
-            FunctionBody::Expr(expr) => expr.syntax().descendants(),
-            FunctionBody::Span { parent, .. } => parent.syntax().descendants(),
-        }
-    }
-
-    fn descendant_paths(&self) -> impl Iterator<Item = ast::Path> {
-        self.descendants().filter_map(|node| {
-            match_ast! {
-                match node {
-                    ast::Path(it) => Some(it),
-                    _ => None
-                }
-            }
-        })
-    }
-
     fn from_expr(expr: ast::Expr) -> Option<Self> {
         match expr {
             ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
@@ -753,7 +731,6 @@ impl FunctionBody {
                 parent_loop.get_or_insert(loop_.syntax().clone());
             }
         };
-
         let (is_const, expr, ty) = loop {
             let anc = ancestors.next()?;
             break match_ast! {
@@ -821,20 +798,7 @@ impl FunctionBody {
             container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
                 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
             });
-
-        let parent = self.parent()?;
-        let parents = generic_parents(&parent);
-        let generic_param_lists = parents.iter().filter_map(|it| it.generic_param_list()).collect();
-        let where_clauses = parents.iter().filter_map(|it| it.where_clause()).collect();
-
-        Some(ContainerInfo {
-            is_in_tail,
-            is_const,
-            parent_loop,
-            ret_type: ty,
-            generic_param_lists,
-            where_clauses,
-        })
+        Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
     }
 
     fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
@@ -991,56 +955,6 @@ impl FunctionBody {
     }
 }
 
-enum GenericParent {
-    Fn(ast::Fn),
-    Impl(ast::Impl),
-    Trait(ast::Trait),
-}
-
-impl GenericParent {
-    fn generic_param_list(&self) -> Option<ast::GenericParamList> {
-        match self {
-            GenericParent::Fn(fn_) => fn_.generic_param_list(),
-            GenericParent::Impl(impl_) => impl_.generic_param_list(),
-            GenericParent::Trait(trait_) => trait_.generic_param_list(),
-        }
-    }
-
-    fn where_clause(&self) -> Option<ast::WhereClause> {
-        match self {
-            GenericParent::Fn(fn_) => fn_.where_clause(),
-            GenericParent::Impl(impl_) => impl_.where_clause(),
-            GenericParent::Trait(trait_) => trait_.where_clause(),
-        }
-    }
-}
-
-/// Search `parent`'s ancestors for items with potentially applicable generic parameters
-fn generic_parents(parent: &SyntaxNode) -> Vec<GenericParent> {
-    let mut list = Vec::new();
-    if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) {
-        match parent_item {
-            ast::Item::Fn(ref fn_) => {
-                if let Some(parent_parent) = parent_item
-                    .syntax()
-                    .parent()
-                    .and_then(|it| it.parent())
-                    .and_then(ast::Item::cast)
-                {
-                    match parent_parent {
-                        ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)),
-                        ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)),
-                        _ => (),
-                    }
-                }
-                list.push(GenericParent::Fn(fn_.clone()));
-            }
-            _ => (),
-        }
-    }
-    list
-}
-
 /// checks if relevant var is used with `&mut` access inside body
 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
     usages
@@ -1448,154 +1362,37 @@ fn format_function(
     let const_kw = if fun.mods.is_const { "const " } else { "" };
     let async_kw = if fun.control_flow.is_async { "async " } else { "" };
     let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
-    let (generic_params, where_clause) = make_generic_params_and_where_clause(ctx, fun);
     match ctx.config.snippet_cap {
         Some(_) => format_to!(
             fn_def,
-            "\n\n{}{}{}{}fn $0{}",
+            "\n\n{}{}{}{}fn $0{}{}",
             new_indent,
             const_kw,
             async_kw,
             unsafe_kw,
             fun.name,
+            params
         ),
         None => format_to!(
             fn_def,
-            "\n\n{}{}{}{}fn {}",
+            "\n\n{}{}{}{}fn {}{}",
             new_indent,
             const_kw,
             async_kw,
             unsafe_kw,
             fun.name,
+            params
         ),
     }
-
-    if let Some(generic_params) = generic_params {
-        format_to!(fn_def, "{}", generic_params);
-    }
-
-    format_to!(fn_def, "{}", params);
-
     if let Some(ret_ty) = ret_ty {
         format_to!(fn_def, " {}", ret_ty);
     }
-
-    if let Some(where_clause) = where_clause {
-        format_to!(fn_def, " {}", where_clause);
-    }
-
     format_to!(fn_def, " {}", body);
 
     fn_def
 }
 
-fn make_generic_params_and_where_clause(
-    ctx: &AssistContext,
-    fun: &Function,
-) -> (Option<ast::GenericParamList>, Option<ast::WhereClause>) {
-    let used_type_params = fun.type_params(ctx);
-
-    let generic_param_list = make_generic_param_list(ctx, fun, &used_type_params);
-    let where_clause = make_where_clause(ctx, fun, &used_type_params);
-
-    (generic_param_list, where_clause)
-}
-
-fn make_generic_param_list(
-    ctx: &AssistContext,
-    fun: &Function,
-    used_type_params: &[TypeParam],
-) -> Option<ast::GenericParamList> {
-    let mut generic_params = fun
-        .mods
-        .generic_param_lists
-        .iter()
-        .flat_map(|parent_params| {
-            parent_params
-                .generic_params()
-                .filter(|param| param_is_required(ctx, param, used_type_params))
-        })
-        .peekable();
-
-    if generic_params.peek().is_some() {
-        Some(make::generic_param_list(generic_params))
-    } else {
-        None
-    }
-}
-
-fn param_is_required(
-    ctx: &AssistContext,
-    param: &ast::GenericParam,
-    used_type_params: &[TypeParam],
-) -> bool {
-    match param {
-        ast::GenericParam::ConstParam(_) | ast::GenericParam::LifetimeParam(_) => false,
-        ast::GenericParam::TypeParam(type_param) => match &ctx.sema.to_def(type_param) {
-            Some(def) => used_type_params.contains(def),
-            _ => false,
-        },
-    }
-}
-
-fn make_where_clause(
-    ctx: &AssistContext,
-    fun: &Function,
-    used_type_params: &[TypeParam],
-) -> Option<ast::WhereClause> {
-    let mut predicates = fun
-        .mods
-        .where_clauses
-        .iter()
-        .flat_map(|parent_where_clause| {
-            parent_where_clause
-                .predicates()
-                .filter(|pred| pred_is_required(ctx, pred, used_type_params))
-        })
-        .peekable();
-
-    if predicates.peek().is_some() {
-        Some(make::where_clause(predicates))
-    } else {
-        None
-    }
-}
-
-fn pred_is_required(
-    ctx: &AssistContext,
-    pred: &ast::WherePred,
-    used_type_params: &[TypeParam],
-) -> bool {
-    match resolved_type_param(ctx, pred) {
-        Some(it) => used_type_params.contains(&it),
-        None => false,
-    }
-}
-
-fn resolved_type_param(ctx: &AssistContext, pred: &ast::WherePred) -> Option<TypeParam> {
-    let path = match pred.ty()? {
-        ast::Type::PathType(path_type) => path_type.path(),
-        _ => None,
-    }?;
-
-    match ctx.sema.resolve_path(&path)? {
-        PathResolution::TypeParam(type_param) => Some(type_param),
-        _ => None,
-    }
-}
-
 impl Function {
-    /// Collect all the `TypeParam`s used in the `body` and `params`.
-    fn type_params(&self, ctx: &AssistContext) -> Vec<TypeParam> {
-        let type_params_in_descendant_paths =
-            self.body.descendant_paths().filter_map(|it| match ctx.sema.resolve_path(&it) {
-                Some(PathResolution::TypeParam(type_param)) => Some(type_param),
-                _ => None,
-            });
-        let type_params_in_params = self.params.iter().filter_map(|p| p.ty.as_type_param(ctx.db()));
-        type_params_in_descendant_paths.chain(type_params_in_params).collect()
-    }
-
     fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
         let self_param = self.self_param.clone();
         let params = self.params.iter().map(|param| param.to_param(ctx, module));
@@ -5075,254 +4872,6 @@ fn parent(factor: i32) {
 fn $0fun_name(v: &[i32; 3], factor: i32) {
     v.iter().map(|it| it * factor);
 }
-"#,
-        );
-    }
-
-    #[test]
-    fn preserve_generics() {
-        check_assist(
-            extract_function,
-            r#"
-fn func<T: Debug>(i: T) {
-    $0foo(i);$0
-}
-"#,
-            r#"
-fn func<T: Debug>(i: T) {
-    fun_name(i);
-}
-
-fn $0fun_name<T: Debug>(i: T) {
-    foo(i);
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn preserve_generics_from_body() {
-        check_assist(
-            extract_function,
-            r#"
-fn func<T: Default>() -> T {
-    $0T::default()$0
-}
-"#,
-            r#"
-fn func<T: Default>() -> T {
-    fun_name()
-}
-
-fn $0fun_name<T: Default>() -> T {
-    T::default()
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn filter_unused_generics() {
-        check_assist(
-            extract_function,
-            r#"
-fn func<T: Debug, U: Copy>(i: T, u: U) {
-    bar(u);
-    $0foo(i);$0
-}
-"#,
-            r#"
-fn func<T: Debug, U: Copy>(i: T, u: U) {
-    bar(u);
-    fun_name(i);
-}
-
-fn $0fun_name<T: Debug>(i: T) {
-    foo(i);
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn empty_generic_param_list() {
-        check_assist(
-            extract_function,
-            r#"
-fn func<T: Debug>(t: T, i: u32) {
-    bar(t);
-    $0foo(i);$0
-}
-"#,
-            r#"
-fn func<T: Debug>(t: T, i: u32) {
-    bar(t);
-    fun_name(i);
-}
-
-fn $0fun_name(i: u32) {
-    foo(i);
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn preserve_where_clause() {
-        check_assist(
-            extract_function,
-            r#"
-fn func<T>(i: T) where T: Debug {
-    $0foo(i);$0
-}
-"#,
-            r#"
-fn func<T>(i: T) where T: Debug {
-    fun_name(i);
-}
-
-fn $0fun_name<T>(i: T) where T: Debug {
-    foo(i);
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn filter_unused_where_clause() {
-        check_assist(
-            extract_function,
-            r#"
-fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
-    bar(u);
-    $0foo(i);$0
-}
-"#,
-            r#"
-fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
-    bar(u);
-    fun_name(i);
-}
-
-fn $0fun_name<T>(i: T) where T: Debug {
-    foo(i);
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn nested_generics() {
-        check_assist(
-            extract_function,
-            r#"
-struct Struct<T: Into<i32>>(T);
-impl <T: Into<i32> + Copy> Struct<T> {
-    fn func<V: Into<i32>>(&self, v: V) -> i32 {
-        let t = self.0;
-        $0t.into() + v.into()$0
-    }
-}
-"#,
-            r#"
-struct Struct<T: Into<i32>>(T);
-impl <T: Into<i32> + Copy> Struct<T> {
-    fn func<V: Into<i32>>(&self, v: V) -> i32 {
-        let t = self.0;
-        fun_name(t, v)
-    }
-}
-
-fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
-    t.into() + v.into()
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn filters_unused_nested_generics() {
-        check_assist(
-            extract_function,
-            r#"
-struct Struct<T: Into<i32>, U: Debug>(T, U);
-impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
-    fn func<V: Into<i32>>(&self, v: V) -> i32 {
-        let t = self.0;
-        $0t.into() + v.into()$0
-    }
-}
-"#,
-            r#"
-struct Struct<T: Into<i32>, U: Debug>(T, U);
-impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
-    fn func<V: Into<i32>>(&self, v: V) -> i32 {
-        let t = self.0;
-        fun_name(t, v)
-    }
-}
-
-fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
-    t.into() + v.into()
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn nested_where_clauses() {
-        check_assist(
-            extract_function,
-            r#"
-struct Struct<T>(T) where T: Into<i32>;
-impl <T> Struct<T> where T: Into<i32> + Copy {
-    fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
-        let t = self.0;
-        $0t.into() + v.into()$0
-    }
-}
-"#,
-            r#"
-struct Struct<T>(T) where T: Into<i32>;
-impl <T> Struct<T> where T: Into<i32> + Copy {
-    fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
-        let t = self.0;
-        fun_name(t, v)
-    }
-}
-
-fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {
-    t.into() + v.into()
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn filters_unused_nested_where_clauses() {
-        check_assist(
-            extract_function,
-            r#"
-struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
-impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
-    fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
-        let t = self.0;
-        $0t.into() + v.into()$0
-    }
-}
-"#,
-            r#"
-struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
-impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
-    fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
-        let t = self.0;
-        fun_name(t, v)
-    }
-}
-
-fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {
-    t.into() + v.into()
-}
 "#,
         );
     }
diff --git a/crates/ide-assists/src/handlers/generate_function.rs b/crates/ide-assists/src/handlers/generate_function.rs
index 061a481344..c8650979e9 100644
--- a/crates/ide-assists/src/handlers/generate_function.rs
+++ b/crates/ide-assists/src/handlers/generate_function.rs
@@ -176,7 +176,7 @@ fn get_adt_source(
     adt: &hir::Adt,
     fn_name: &str,
 ) -> Option<(Option<ast::Impl>, FileId)> {
-    let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
+    let range = adt.source(ctx.sema.db)?.syntax().original_file_range_full(ctx.sema.db);
     let file = ctx.sema.parse(range.file_id);
     let adt_source =
         ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
diff --git a/crates/ide-assists/src/handlers/inline_call.rs b/crates/ide-assists/src/handlers/inline_call.rs
index c857adf876..ab614b0ace 100644
--- a/crates/ide-assists/src/handlers/inline_call.rs
+++ b/crates/ide-assists/src/handlers/inline_call.rs
@@ -198,7 +198,7 @@ pub(crate) fn inline_call(acc: &mut Assists, ctx: &AssistContext) -> Option<()>
     let fn_body = fn_source.value.body()?;
     let param_list = fn_source.value.param_list()?;
 
-    let FileRange { file_id, range } = fn_source.syntax().original_file_range(ctx.sema.db);
+    let FileRange { file_id, range } = fn_source.syntax().original_file_range_full(ctx.sema.db);
     if file_id == ctx.file_id() && range.contains(ctx.offset()) {
         cov_mark::hit!(inline_call_recursive);
         return None;
diff --git a/crates/ide-db/src/imports/insert_use.rs b/crates/ide-db/src/imports/insert_use.rs
index d1cd347819..c14182279d 100644
--- a/crates/ide-db/src/imports/insert_use.rs
+++ b/crates/ide-db/src/imports/insert_use.rs
@@ -396,10 +396,19 @@ fn insert_use_(
         }
     }
 
+    let l_curly = match scope {
+        ImportScope::File(_) => None,
+        // don't insert the imports before the item list/block expr's opening curly brace
+        ImportScope::Module(item_list) => item_list.l_curly_token(),
+        // don't insert the imports before the item list's opening curly brace
+        ImportScope::Block(block) => block.l_curly_token(),
+    };
     // there are no imports in this file at all
     // so put the import after all inner module attributes and possible license header comments
     if let Some(last_inner_element) = scope_syntax
         .children_with_tokens()
+        // skip the curly brace
+        .skip(l_curly.is_some() as usize)
         .take_while(|child| match child {
             NodeOrToken::Node(node) => is_inner_attribute(node.clone()),
             NodeOrToken::Token(token) => {
@@ -413,30 +422,21 @@ fn insert_use_(
         cov_mark::hit!(insert_empty_inner_attr);
         ted::insert(ted::Position::after(&last_inner_element), use_item.syntax());
         ted::insert(ted::Position::after(last_inner_element), make::tokens::single_newline());
-        return;
-    }
-    let l_curly = match scope {
-        ImportScope::File(_) => {
-            cov_mark::hit!(insert_empty_file);
-            ted::insert(ted::Position::first_child_of(scope_syntax), make::tokens::blank_line());
-            ted::insert(ted::Position::first_child_of(scope_syntax), use_item.syntax());
-            return;
-        }
-        // don't insert the imports before the item list/block expr's opening curly brace
-        ImportScope::Module(item_list) => item_list.l_curly_token(),
-        // don't insert the imports before the item list's opening curly brace
-        ImportScope::Block(block) => block.l_curly_token(),
-    };
-    match l_curly {
-        Some(b) => {
-            cov_mark::hit!(insert_empty_module);
-            ted::insert(ted::Position::after(&b), make::tokens::single_newline());
-            ted::insert(ted::Position::after(&b), use_item.syntax());
-        }
-        None => {
-            // This should never happens, broken module syntax node
-            ted::insert(ted::Position::first_child_of(scope_syntax), make::tokens::blank_line());
-            ted::insert(ted::Position::first_child_of(scope_syntax), use_item.syntax());
+    } else {
+        match l_curly {
+            Some(b) => {
+                cov_mark::hit!(insert_empty_module);
+                ted::insert(ted::Position::after(&b), make::tokens::single_newline());
+                ted::insert(ted::Position::after(&b), use_item.syntax());
+            }
+            None => {
+                cov_mark::hit!(insert_empty_file);
+                ted::insert(
+                    ted::Position::first_child_of(scope_syntax),
+                    make::tokens::blank_line(),
+                );
+                ted::insert(ted::Position::first_child_of(scope_syntax), use_item.syntax());
+            }
         }
     }
 }
diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs
index 4a11fb73cd..e6bd46347d 100644
--- a/crates/ide-db/src/search.rs
+++ b/crates/ide-db/src/search.rs
@@ -239,14 +239,14 @@ impl Definition {
                 DefWithBody::Static(s) => s.source(db).map(|src| src.syntax().cloned()),
             };
             return match def {
-                Some(def) => SearchScope::file_range(def.as_ref().original_file_range(db)),
+                Some(def) => SearchScope::file_range(def.as_ref().original_file_range_full(db)),
                 None => SearchScope::single_file(file_id),
             };
         }
 
         if let Definition::SelfType(impl_) = self {
             return match impl_.source(db).map(|src| src.syntax().cloned()) {
-                Some(def) => SearchScope::file_range(def.as_ref().original_file_range(db)),
+                Some(def) => SearchScope::file_range(def.as_ref().original_file_range_full(db)),
                 None => SearchScope::single_file(file_id),
             };
         }
@@ -262,7 +262,7 @@ impl Definition {
                 hir::GenericDef::Const(it) => it.source(db).map(|src| src.syntax().cloned()),
             };
             return match def {
-                Some(def) => SearchScope::file_range(def.as_ref().original_file_range(db)),
+                Some(def) => SearchScope::file_range(def.as_ref().original_file_range_full(db)),
                 None => SearchScope::single_file(file_id),
             };
         }
diff --git a/crates/ide-diagnostics/src/handlers/unresolved_proc_macro.rs b/crates/ide-diagnostics/src/handlers/unresolved_proc_macro.rs
index 760f51f904..fde3901a73 100644
--- a/crates/ide-diagnostics/src/handlers/unresolved_proc_macro.rs
+++ b/crates/ide-diagnostics/src/handlers/unresolved_proc_macro.rs
@@ -1,5 +1,4 @@
 use hir::db::DefDatabase;
-use syntax::NodeOrToken;
 
 use crate::{Diagnostic, DiagnosticsContext, Severity};
 
@@ -19,16 +18,9 @@ pub(crate) fn unresolved_proc_macro(
     proc_attr_macros_enabled: bool,
 ) -> Diagnostic {
     // Use more accurate position if available.
-    let display_range = (|| {
-        let precise_location = d.precise_location?;
-        let root = ctx.sema.parse_or_expand(d.node.file_id)?;
-        match root.covering_element(precise_location) {
-            NodeOrToken::Node(it) => Some(ctx.sema.original_range(&it)),
-            NodeOrToken::Token(it) => d.node.with_value(it).original_file_range_opt(ctx.sema.db),
-        }
-    })()
-    .unwrap_or_else(|| ctx.sema.diagnostics_display_range(d.node.clone()))
-    .range;
+    let display_range = d
+        .precise_location
+        .unwrap_or_else(|| ctx.sema.diagnostics_display_range(d.node.clone()).range);
 
     let config_enabled = match d.kind {
         hir::MacroKind::Attr => proc_macros_enabled && proc_attr_macros_enabled,


Test patch:
diff --git a/crates/ide-db/src/imports/insert_use/tests.rs b/crates/ide-db/src/imports/insert_use/tests.rs
index 70a7a15232..59673af320 100644
--- a/crates/ide-db/src/imports/insert_use/tests.rs
+++ b/crates/ide-db/src/imports/insert_use/tests.rs
@@ -441,6 +441,19 @@ fn inserts_after_single_line_inner_comments() {
 
 use foo::bar::Baz;"#,
     );
+    check_none(
+        "foo::bar::Baz",
+        r"mod foo {
+    //! Single line inner comments do not allow any code before them.
+$0
+}",
+        r"mod foo {
+    //! Single line inner comments do not allow any code before them.
+
+    use foo::bar::Baz;
+
+}",
+    );
 }
 
 #[test]