Repository: rust-analyzer/rust-analyzer
Pull request #8292 (2021-04-02 11:00:23)

internal: document Cargo.lock maintenance process
bors r+
🤖


Patch:
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs
index 3bf722d2a7..d3caeef4ee 100644
--- a/crates/hir/src/semantics.rs
+++ b/crates/hir/src/semantics.rs
@@ -76,11 +76,9 @@ impl PathResolution {
     pub fn assoc_type_shorthand_candidates<R>(
         &self,
         db: &dyn HirDatabase,
-        mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
+        mut cb: impl FnMut(TypeAlias) -> Option<R>,
     ) -> Option<R> {
-        associated_type_shorthand_candidates(db, self.in_type_ns()?, |name, _, id| {
-            cb(name, id.into())
-        })
+        associated_type_shorthand_candidates(db, self.in_type_ns()?, |_, _, id| cb(id.into()))
     }
 }
 
diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs
index 8e9ea0a038..37d162b328 100644
--- a/crates/hir/src/source_analyzer.rs
+++ b/crates/hir/src/source_analyzer.rs
@@ -20,7 +20,7 @@ use hir_def::{
 use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
 use hir_ty::{
     diagnostics::{record_literal_missing_fields, record_pattern_missing_fields},
-    InferenceResult, Substitution, TyLoweringContext,
+    InferenceResult, Substitution,
 };
 use syntax::{
     ast::{self, AstNode},
@@ -466,21 +466,7 @@ fn resolve_hir_path_(
     prefer_value_ns: bool,
 ) -> Option<PathResolution> {
     let types = || {
-        let (ty, unresolved) = match path.type_anchor() {
-            Some(type_ref) => {
-                let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
-                res.map(|ty_ns| (ty_ns, path.segments().first()))
-            }
-            None => {
-                let (ty, remaining) =
-                    resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
-                match remaining {
-                    Some(remaining) if remaining > 1 => None,
-                    _ => Some((ty, path.segments().get(1))),
-                }
-            }
-        }?;
-        let res = match ty {
+        resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
             TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
             TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
             TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
@@ -490,17 +476,7 @@ fn resolve_hir_path_(
             TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
             TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
             TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
-        };
-        match unresolved {
-            Some(unresolved) => res
-                .assoc_type_shorthand_candidates(db, |name, alias| {
-                    (name == unresolved.name).then(|| alias)
-                })
-                .map(TypeAlias::from)
-                .map(Into::into)
-                .map(PathResolution::Def),
-            None => Some(res),
-        }
+        })
     };
 
     let body_owner = resolver.body_owner();
diff --git a/crates/hir_def/src/item_tree/lower.rs b/crates/hir_def/src/item_tree/lower.rs
index 124dcc8666..8d38628111 100644
--- a/crates/hir_def/src/item_tree/lower.rs
+++ b/crates/hir_def/src/item_tree/lower.rs
@@ -174,12 +174,6 @@ impl Ctx {
         let forced_vis = self.forced_visibility.take();
 
         let mut block_stack = Vec::new();
-
-        // if container itself is block, add it to the stack
-        if let Some(block) = ast::BlockExpr::cast(container.clone()) {
-            block_stack.push(self.source_ast_id_map.ast_id(&block));
-        }
-
         for event in container.preorder().skip(1) {
             match event {
                 WalkEvent::Enter(node) => {
diff --git a/crates/hir_ty/src/lower.rs b/crates/hir_ty/src/lower.rs
index 14f34d73c6..afbfa12d51 100644
--- a/crates/hir_ty/src/lower.rs
+++ b/crates/hir_ty/src/lower.rs
@@ -146,7 +146,7 @@ impl<'a> TyLoweringContext<'a> {
         self.lower_ty_ext(type_ref).0
     }
 
-    pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
+    fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
         let mut res = None;
         let ty = match type_ref {
             TypeRef::Never => TyKind::Never.intern(&Interner),
diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs
index 28e2e17dc2..5f9edb4761 100644
--- a/crates/ide/src/hover.rs
+++ b/crates/ide/src/hover.rs
@@ -3834,67 +3834,4 @@ fn foo() {}
             "#]],
         );
     }
-
-    #[test]
-    fn hover_generic_assoc() {
-        check(
-            r#"
-fn foo<T: A>() where T::Assoc$0: {}
-
-trait A {
-    type Assoc;
-}"#,
-            expect![[r#"
-                *Assoc*
-
-                ```rust
-                test
-                ```
-
-                ```rust
-                type Assoc
-                ```
-            "#]],
-        );
-        check(
-            r#"
-fn foo<T: A>() {
-    let _: <T>::Assoc$0;
-}
-
-trait A {
-    type Assoc;
-}"#,
-            expect![[r#"
-                *Assoc*
-
-                ```rust
-                test
-                ```
-
-                ```rust
-                type Assoc
-                ```
-            "#]],
-        );
-        check(
-            r#"
-trait A where
-    Self::Assoc$0: ,
-{
-    type Assoc;
-}"#,
-            expect![[r#"
-                *Assoc*
-
-                ```rust
-                test
-                ```
-
-                ```rust
-                type Assoc
-                ```
-            "#]],
-        );
-    }
 }
diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs
index 9df8d21afc..67a10766b2 100644
--- a/crates/ide/src/syntax_highlighting.rs
+++ b/crates/ide/src/syntax_highlighting.rs
@@ -48,9 +48,6 @@ pub struct HlRange {
 //
 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
 // We also give special modifier for `mut` and `&mut` local variables.
-//
-// image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
-// image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
 pub(crate) fn highlight(
     db: &RootDatabase,
     file_id: FileId,
diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs
index 11408d445a..e10b7d98e3 100644
--- a/crates/ide/src/typing.rs
+++ b/crates/ide/src/typing.rs
@@ -49,9 +49,6 @@ pub(crate) const TRIGGER_CHARS: &str = ".=>";
 // ----
 // "editor.formatOnType": true,
 // ----
-//
-// image::https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif[]
-// image::https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif[]
 pub(crate) fn on_char_typed(
     db: &RootDatabase,
     position: FilePosition,
diff --git a/crates/ide_assists/src/assist_context.rs b/crates/ide_assists/src/assist_context.rs
index 8714e4978c..1482d37f84 100644
--- a/crates/ide_assists/src/assist_context.rs
+++ b/crates/ide_assists/src/assist_context.rs
@@ -13,7 +13,7 @@ use ide_db::{
     RootDatabase,
 };
 use syntax::{
-    algo::{self, find_node_at_offset, find_node_at_range, SyntaxRewriter},
+    algo::{self, find_node_at_offset, SyntaxRewriter},
     AstNode, AstToken, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxNodePtr,
     SyntaxToken, TextRange, TextSize, TokenAtOffset,
 };
@@ -89,9 +89,6 @@ impl<'a> AssistContext<'a> {
     pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
         find_node_at_offset(self.source_file.syntax(), self.offset())
     }
-    pub(crate) fn find_node_at_range<N: AstNode>(&self) -> Option<N> {
-        find_node_at_range(self.source_file.syntax(), self.frange.range)
-    }
     pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
         self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset())
     }
diff --git a/crates/ide_assists/src/handlers/extract_type_alias.rs b/crates/ide_assists/src/handlers/extract_type_alias.rs
deleted file mode 100644
index 442a209b97..0000000000
--- a/crates/ide_assists/src/handlers/extract_type_alias.rs
+++ /dev/null
@@ -1,149 +0,0 @@
-use syntax::ast::{self, AstNode};
-
-use crate::{AssistContext, AssistId, AssistKind, Assists};
-
-// Assist: extract_type_alias
-//
-// Extracts the selected type as a type alias.
-//
-// ```
-// struct S {
-//     field: $0(u8, u8, u8)$0,
-// }
-// ```
-// ->
-// ```
-// type $0Type = (u8, u8, u8);
-//
-// struct S {
-//     field: Type,
-// }
-// ```
-pub(crate) fn extract_type_alias(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
-    if ctx.frange.range.is_empty() {
-        return None;
-    }
-
-    let node = ctx.find_node_at_range::<ast::Type>()?;
-    let insert = ctx.find_node_at_offset::<ast::Item>()?.syntax().text_range().start();
-    let target = node.syntax().text_range();
-
-    acc.add(
-        AssistId("extract_type_alias", AssistKind::RefactorExtract),
-        "Extract type as type alias",
-        target,
-        |builder| {
-            builder.edit_file(ctx.frange.file_id);
-            builder.replace(target, "Type");
-            match ctx.config.snippet_cap {
-                Some(cap) => {
-                    builder.insert_snippet(cap, insert, format!("type $0Type = {};\n\n", node));
-                }
-                None => {
-                    builder.insert(insert, format!("type Type = {};\n\n", node));
-                }
-            }
-        },
-    )
-}
-
-#[cfg(test)]
-mod tests {
-    use crate::tests::{check_assist, check_assist_not_applicable};
-
-    use super::*;
-
-    #[test]
-    fn test_not_applicable_without_selection() {
-        check_assist_not_applicable(
-            extract_type_alias,
-            r"
-struct S {
-    field: $0(u8, u8, u8),
-}
-            ",
-        );
-    }
-
-    #[test]
-    fn test_simple_types() {
-        check_assist(
-            extract_type_alias,
-            r"
-struct S {
-    field: $0u8$0,
-}
-            ",
-            r#"
-type $0Type = u8;
-
-struct S {
-    field: Type,
-}
-            "#,
-        );
-    }
-
-    #[test]
-    fn test_generic_type_arg() {
-        check_assist(
-            extract_type_alias,
-            r"
-fn generic<T>() {}
-
-fn f() {
-    generic::<$0()$0>();
-}
-            ",
-            r#"
-fn generic<T>() {}
-
-type $0Type = ();
-
-fn f() {
-    generic::<Type>();
-}
-            "#,
-        );
-    }
-
-    #[test]
-    fn test_inner_type_arg() {
-        check_assist(
-            extract_type_alias,
-            r"
-struct Vec<T> {}
-struct S {
-    v: Vec<Vec<$0Vec<u8>$0>>,
-}
-            ",
-            r#"
-struct Vec<T> {}
-type $0Type = Vec<u8>;
-
-struct S {
-    v: Vec<Vec<Type>>,
-}
-            "#,
-        );
-    }
-
-    #[test]
-    fn test_extract_inner_type() {
-        check_assist(
-            extract_type_alias,
-            r"
-struct S {
-    field: ($0u8$0,),
-}
-            ",
-            r#"
-type $0Type = u8;
-
-struct S {
-    field: (Type,),
-}
-            "#,
-        );
-    }
-}
diff --git a/crates/ide_assists/src/lib.rs b/crates/ide_assists/src/lib.rs
index 3d1dcef4ce..8c068a6c0e 100644
--- a/crates/ide_assists/src/lib.rs
+++ b/crates/ide_assists/src/lib.rs
@@ -121,7 +121,6 @@ mod handlers {
     mod expand_glob_import;
     mod extract_function;
     mod extract_struct_from_enum_variant;
-    mod extract_type_alias;
     mod extract_variable;
     mod fill_match_arms;
     mod fix_visibility;
@@ -188,7 +187,6 @@ mod handlers {
             early_return::convert_to_guarded_return,
             expand_glob_import::expand_glob_import,
             extract_struct_from_enum_variant::extract_struct_from_enum_variant,
-            extract_type_alias::extract_type_alias,
             fill_match_arms::fill_match_arms,
             fix_visibility::fix_visibility,
             flip_binexpr::flip_binexpr,
diff --git a/crates/ide_completion/src/completions/qualified_path.rs b/crates/ide_completion/src/completions/qualified_path.rs
index 969249df60..1891eb5b36 100644
--- a/crates/ide_completion/src/completions/qualified_path.rs
+++ b/crates/ide_completion/src/completions/qualified_path.rs
@@ -24,7 +24,7 @@ pub(crate) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionCon
     };
 
     // Add associated types on type parameters and `Self`.
-    resolution.assoc_type_shorthand_candidates(ctx.db, |_, alias| {
+    resolution.assoc_type_shorthand_candidates(ctx.db, |alias| {
         acc.add_type_alias(ctx, alias);
         None::<()>
     });
diff --git a/crates/rust-analyzer/src/diagnostics/to_proto.rs b/crates/rust-analyzer/src/diagnostics/to_proto.rs
index e2f319f6b0..76994de71d 100644
--- a/crates/rust-analyzer/src/diagnostics/to_proto.rs
+++ b/crates/rust-analyzer/src/diagnostics/to_proto.rs
@@ -34,14 +34,22 @@ fn diagnostic_severity(
     Some(res)
 }
 
-/// Checks whether a file name is from macro invocation and does not refer to an actual file.
-fn is_dummy_macro_file(file_name: &str) -> bool {
-    // FIXME: current rustc does not seem to emit `<macro file>` files anymore?
+/// Check whether a file name is from macro invocation
+fn is_from_macro(file_name: &str) -> bool {
     file_name.starts_with('<') && file_name.ends_with('>')
 }
 
-/// Converts a Rust span to a LSP location
+/// Converts a Rust span to a LSP location, resolving macro expansion site if neccesary
 fn location(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location {
+    let mut span = span.clone();
+    while let Some(expansion) = span.expansion {
+        span = expansion.span;
+    }
+    return location_naive(workspace_root, &span);
+}
+
+/// Converts a Rust span to a LSP location
+fn location_naive(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location {
     let file_name = workspace_root.join(&span.file_name);
     let uri = url_from_abs_path(&file_name);
 
@@ -54,25 +62,7 @@ fn location(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location
     lsp_types::Location { uri, range }
 }
 
-/// Extracts a suitable "primary" location from a rustc diagnostic.
-///
-/// This takes locations pointing into the standard library, or generally outside the current
-/// workspace into account and tries to avoid those, in case macros are involved.
-fn primary_location(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location {
-    let span_stack = std::iter::successors(Some(span), |span| Some(&span.expansion.as_ref()?.span));
-    for span in span_stack.clone() {
-        let abs_path = workspace_root.join(&span.file_name);
-        if !is_dummy_macro_file(&span.file_name) && abs_path.starts_with(workspace_root) {
-            return location(workspace_root, span);
-        }
-    }
-
-    // Fall back to the outermost macro invocation if no suitable span comes up.
-    let last_span = span_stack.last().unwrap();
-    location(workspace_root, last_span)
-}
-
-/// Converts a secondary Rust span to a LSP related information
+/// Converts a secondary Rust span to a LSP related inflocation(ormation
 ///
 /// If the span is unlabelled this will return `None`.
 fn diagnostic_related_information(
@@ -241,7 +231,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
     primary_spans
         .iter()
         .flat_map(|primary_span| {
-            let primary_location = primary_location(workspace_root, &primary_span);
+            let location = location(workspace_root, &primary_span);
 
             let mut message = message.clone();
             if needs_primary_span_label {
@@ -253,47 +243,31 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
             // Each primary diagnostic span may result in multiple LSP diagnostics.
             let mut diagnostics = Vec::new();
 
-            let mut related_info_macro_calls = vec![];
+            let mut related_macro_info = None;
 
             // If error occurs from macro expansion, add related info pointing to
             // where the error originated
             // Also, we would generate an additional diagnostic, so that exact place of macro
             // will be highlighted in the error origin place.
-            let span_stack = std::iter::successors(Some(*primary_span), |span| {
-                Some(&span.expansion.as_ref()?.span)
-            });
-            for (i, span) in span_stack.enumerate() {
-                if is_dummy_macro_file(&span.file_name) {
-                    continue;
-                }
-
-                // First span is the original diagnostic, others are macro call locations that
-                // generated that code.
-                let is_in_macro_call = i != 0;
+            if !is_from_macro(&primary_span.file_name) && primary_span.expansion.is_some() {
+                let in_macro_location = location_naive(workspace_root, &primary_span);
 
-                let secondary_location = location(workspace_root, &span);
-                if secondary_location == primary_location {
-                    continue;
-                }
-                related_info_macro_calls.push(lsp_types::DiagnosticRelatedInformation {
-                    location: secondary_location.clone(),
-                    message: if is_in_macro_call {
-                        "Error originated from macro call here".to_string()
-                    } else {
-                        "Actual error occurred here".to_string()
-                    },
+                // Add related information for the main disagnostic.
+                related_macro_info = Some(lsp_types::DiagnosticRelatedInformation {
+                    location: in_macro_location.clone(),
+                    message: "Error originated from macro here".to_string(),
                 });
+
                 // For the additional in-macro diagnostic we add the inverse message pointing to the error location in code.
                 let information_for_additional_diagnostic =
                     vec![lsp_types::DiagnosticRelatedInformation {
-                        location: primary_location.clone(),
+                        location: location.clone(),
                         message: "Exact error occurred here".to_string(),
                     }];
 
                 let diagnostic = lsp_types::Diagnostic {
-                    range: secondary_location.range,
-                    // downgrade to hint if we're pointing at the macro
-                    severity: Some(lsp_types::DiagnosticSeverity::Hint),
+                    range: in_macro_location.range,
+                    severity,
                     code: code.clone().map(lsp_types::NumberOrString::String),
                     code_description: code_description.clone(),
                     source: Some(source.clone()),
@@ -302,8 +276,9 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
                     tags: if tags.is_empty() { None } else { Some(tags.clone()) },
                     data: None,
                 };
+
                 diagnostics.push(MappedRustDiagnostic {
-                    url: secondary_location.uri,
+                    url: in_macro_location.uri,
                     diagnostic,
                     fixes: Vec::new(),
                 });
@@ -311,25 +286,23 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
 
             // Emit the primary diagnostic.
             diagnostics.push(MappedRustDiagnostic {
-                url: primary_location.uri.clone(),
+                url: location.uri.clone(),
                 diagnostic: lsp_types::Diagnostic {
-                    range: primary_location.range,
+                    range: location.range,
                     severity,
                     code: code.clone().map(lsp_types::NumberOrString::String),
                     code_description: code_description.clone(),
                     source: Some(source.clone()),
                     message,
-                    related_information: {
-                        let info = related_info_macro_calls
+                    related_information: if subdiagnostics.is_empty() {
+                        None
+                    } else {
+                        let mut related = subdiagnostics
                             .iter()
-                            .cloned()
-                            .chain(subdiagnostics.iter().map(|sub| sub.related.clone()))
+                            .map(|sub| sub.related.clone())
                             .collect::<Vec<_>>();
-                        if info.is_empty() {
-                            None
-                        } else {
-                            Some(info)
-                        }
+                        related.extend(related_macro_info);
+                        Some(related)
                     },
                     tags: if tags.is_empty() { None } else { Some(tags.clone()) },
                     data: None,
@@ -341,7 +314,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
             // This is useful because they will show up in the user's editor, unlike
             // `related_information`, which just produces hard-to-read links, at least in VS Code.
             let back_ref = lsp_types::DiagnosticRelatedInformation {
-                location: primary_location,
+                location,
                 message: "original diagnostic".to_string(),
             };
             for sub in &subdiagnostics {
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs
index 53d29ddfc6..85e67554c2 100644
--- a/crates/rust-analyzer/src/handlers.rs
+++ b/crates/rust-analyzer/src/handlers.rs
@@ -84,8 +84,7 @@ pub(crate) fn handle_analyzer_status(
 
 pub(crate) fn handle_memory_usage(state: &mut GlobalState, _: ()) -> Result<String> {
     let _p = profile::span("handle_memory_usage");
-    let mut mem = state.analysis_host.per_query_memory_usage();
-    mem.push(("Remaining".into(), profile::memory_usage().allocated));
+    let mem = state.analysis_host.per_query_memory_usage();
 
     let mut out = String::new();
     for (name, bytes) in mem {
diff --git a/docs/dev/style.md b/docs/dev/style.md
index e4a1672cab..1b1c24b1e8 100644
--- a/docs/dev/style.md
+++ b/docs/dev/style.md
@@ -55,9 +55,9 @@ https://www.tedinski.com/2018/02/06/system-boundaries.html
 We try to be very conservative with usage of crates.io dependencies.
 Don't use small "helper" crates (exception: `itertools` is allowed).
 If there's some general reusable bit of code you need, consider adding it to the `stdx` crate.
+A useful exercise is to read Cargo.lock and see if some of the *transitive* dependencies do not make sense for rust-analyzer.
 
-**Rationale:** keep compile times low, create ecosystem pressure for faster
-compiles, reduce the number of things which might break.
+**Rationale:** keep compile times low, create ecosystem pressure for faster compiles, reduce the number of things which might break.
 
 ## Commit Style
 
diff --git a/editors/code/src/snippets.ts b/editors/code/src/snippets.ts
index 9561aa345b..dc53ebe2ee 100644
--- a/editors/code/src/snippets.ts
+++ b/editors/code/src/snippets.ts
@@ -29,7 +29,7 @@ async function editorFromUri(uri: vscode.Uri): Promise<vscode.TextEditor | undef
 }
 
 export async function applySnippetTextEdits(editor: vscode.TextEditor, edits: vscode.TextEdit[]) {
-    const selections: vscode.Selection[] = [];
+    let selection: vscode.Selection | undefined = undefined;
     let lineDelta = 0;
     await editor.edit((builder) => {
         for (const indel of edits) {
@@ -44,18 +44,18 @@ export async function applySnippetTextEdits(editor: vscode.TextEditor, edits: vs
                     indel.range.start.character + placeholderStart
                     : prefix.length - lastNewline - 1;
                 const endColumn = startColumn + placeholderLength;
-                selections.push(new vscode.Selection(
+                selection = new vscode.Selection(
                     new vscode.Position(startLine, startColumn),
                     new vscode.Position(startLine, endColumn),
-                ));
+                );
                 builder.replace(indel.range, newText);
             } else {
+                lineDelta = countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
                 builder.replace(indel.range, indel.newText);
             }
-            lineDelta = countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
         }
     });
-    if (selections.length > 0) editor.selections = selections;
+    if (selection) editor.selection = selection;
 }
 
 function parseSnippet(snip: string): [string, [number, number]] | undefined {


Test patch:
diff --git a/crates/hir_ty/src/tests/macros.rs b/crates/hir_ty/src/tests/macros.rs
index 86e3d8b86e..3eb01dbd0f 100644
--- a/crates/hir_ty/src/tests/macros.rs
+++ b/crates/hir_ty/src/tests/macros.rs
@@ -372,32 +372,6 @@ fn recursive_inner_item_macro_rules() {
     );
 }
 
-#[test]
-fn infer_macro_defining_block_with_items() {
-    check_infer(
-        r#"
-        macro_rules! foo {
-            () => {{
-                fn bar() -> usize { 0 }
-                bar()
-            }};
-        }
-        fn main() {
-            let _a = foo!();
-        }
-    "#,
-        expect![[r#"
-            !15..18 '{0}': usize
-            !16..17 '0': usize
-            !0..24 '{fnbar...bar()}': usize
-            !18..21 'bar': fn bar() -> usize
-            !18..23 'bar()': usize
-            98..122 '{     ...!(); }': ()
-            108..110 '_a': usize
-        "#]],
-    );
-}
-
 #[test]
 fn infer_type_value_macro_having_same_name() {
     check_infer(
diff --git a/crates/ide_assists/src/tests/generated.rs b/crates/ide_assists/src/tests/generated.rs
index 03b7fb3662..736027ff00 100644
--- a/crates/ide_assists/src/tests/generated.rs
+++ b/crates/ide_assists/src/tests/generated.rs
@@ -328,25 +328,6 @@ enum A { One(One) }
     )
 }
 
-#[test]
-fn doctest_extract_type_alias() {
-    check_doc_test(
-        "extract_type_alias",
-        r#####"
-struct S {
-    field: $0(u8, u8, u8)$0,
-}
-"#####,
-        r#####"
-type $0Type = (u8, u8, u8);
-
-struct S {
-    field: Type,
-}
-"#####,
-    )
-}
-
 #[test]
 fn doctest_extract_variable() {
     check_doc_test(
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt b/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt
index c847bbb356..f999848a7f 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt
@@ -13,16 +13,16 @@
         diagnostic: Diagnostic {
             range: Range {
                 start: Position {
-                    line: 271,
+                    line: 264,
                     character: 8,
                 },
                 end: Position {
-                    line: 271,
-                    character: 50,
+                    line: 264,
+                    character: 76,
                 },
             },
             severity: Some(
-                Hint,
+                Error,
             ),
             code: None,
             code_description: None,
@@ -40,18 +40,18 @@
                                 password: None,
                                 host: None,
                                 port: None,
-                                path: "/test/crates/hir_def/src/path.rs",
+                                path: "/test/crates/hir_def/src/data.rs",
                                 query: None,
                                 fragment: None,
                             },
                             range: Range {
                                 start: Position {
-                                    line: 264,
-                                    character: 8,
+                                    line: 79,
+                                    character: 15,
                                 },
                                 end: Position {
-                                    line: 264,
-                                    character: 76,
+                                    line: 79,
+                                    character: 41,
                                 },
                             },
                         },
@@ -86,71 +86,6 @@
                     character: 41,
                 },
             },
-            severity: Some(
-                Hint,
-            ),
-            code: None,
-            code_description: None,
-            source: Some(
-                "rustc",
-            ),
-            message: "Please register your known path in the path module",
-            related_information: Some(
-                [
-                    DiagnosticRelatedInformation {
-                        location: Location {
-                            uri: Url {
-                                scheme: "file",
-                                username: "",
-                                password: None,
-                                host: None,
-                                port: None,
-                                path: "/test/crates/hir_def/src/path.rs",
-                                query: None,
-                                fragment: None,
-                            },
-                            range: Range {
-                                start: Position {
-                                    line: 264,
-                                    character: 8,
-                                },
-                                end: Position {
-                                    line: 264,
-                                    character: 76,
-                                },
-                            },
-                        },
-                        message: "Exact error occurred here",
-                    },
-                ],
-            ),
-            tags: None,
-            data: None,
-        },
-        fixes: [],
-    },
-    MappedRustDiagnostic {
-        url: Url {
-            scheme: "file",
-            username: "",
-            password: None,
-            host: None,
-            port: None,
-            path: "/test/crates/hir_def/src/path.rs",
-            query: None,
-            fragment: None,
-        },
-        diagnostic: Diagnostic {
-            range: Range {
-                start: Position {
-                    line: 264,
-                    character: 8,
-                },
-                end: Position {
-                    line: 264,
-                    character: 76,
-                },
-            },
             severity: Some(
                 Error,
             ),
@@ -160,60 +95,7 @@
                 "rustc",
             ),
             message: "Please register your known path in the path module",
-            related_information: Some(
-                [
-                    DiagnosticRelatedInformation {
-                        location: Location {
-                            uri: Url {
-                                scheme: "file",
-                                username: "",
-                                password: None,
-                                host: None,
-                                port: None,
-                                path: "/test/crates/hir_def/src/path.rs",
-                                query: None,
-                                fragment: None,
-                            },
-                            range: Range {
-                                start: Position {
-                                    line: 271,
-                                    character: 8,
-                                },
-                                end: Position {
-                                    line: 271,
-                                    character: 50,
-                                },
-                            },
-                        },
-                        message: "Error originated from macro call here",
-                    },
-                    DiagnosticRelatedInformation {
-                        location: Location {
-                            uri: Url {
-                                scheme: "file",
-                                username: "",
-                                password: None,
-                                host: None,
-                                port: None,
-                                path: "/test/crates/hir_def/src/data.rs",
-                                query: None,
-                                fragment: None,
-                            },
-                            range: Range {
-                                start: Position {
-                                    line: 79,
-                                    character: 15,
-                                },
-                                end: Position {
-                                    line: 79,
-                                    character: 41,
-                                },
-                            },
-                        },
-                        message: "Error originated from macro call here",
-                    },
-                ],
-            ),
+            related_information: None,
             tags: None,
             data: None,
         },