From 98e2f674e9e736720d1cd0a5b8c24e1fb10f64a1 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 3 Sep 2020 14:38:34 +0200 Subject: Fix inserting imports in front of inner attributes --- .../handlers/replace_qualified_name_with_use.rs | 5 ++- crates/assists/src/utils/insert_use.rs | 52 +++++++++++++++++++++- 2 files changed, 54 insertions(+), 3 deletions(-) (limited to 'crates') diff --git a/crates/assists/src/handlers/replace_qualified_name_with_use.rs b/crates/assists/src/handlers/replace_qualified_name_with_use.rs index 56e85125d..597bc268c 100644 --- a/crates/assists/src/handlers/replace_qualified_name_with_use.rs +++ b/crates/assists/src/handlers/replace_qualified_name_with_use.rs @@ -348,9 +348,9 @@ use std::fmt::{Debug, nested::{self, Display}}; impl std::fmt::nested<|> for Foo { } ", - // FIXME(veykril): self is being pulled out for some reason now + // FIXME(veykril): nested is duplicated now r" -use std::fmt::{Debug, nested::{Display}, nested}; +use std::fmt::{Debug, nested::{self, Display}, nested}; impl nested for Foo { } @@ -518,6 +518,7 @@ fn main() { ", r" #![allow(dead_code)] + use std::fmt::Debug; fn main() { diff --git a/crates/assists/src/utils/insert_use.rs b/crates/assists/src/utils/insert_use.rs index f2acda6f3..1ddd72197 100644 --- a/crates/assists/src/utils/insert_use.rs +++ b/crates/assists/src/utils/insert_use.rs @@ -275,7 +275,27 @@ fn find_insert_position( (InsertPosition::After(node.into()), AddBlankLine::BeforeTwice) } // there are no imports in this file at all - None => (InsertPosition::First, AddBlankLine::AfterTwice), + None => { + // check if the scope has a inner attributes, we dont want to insert in front of it + match scope + .children() + // no flat_map here cause we want to short circuit the iterator + .map(ast::Attr::cast) + .take_while(|attr| { + attr.as_ref() + .map(|attr| attr.kind() == ast::AttrKind::Inner) + .unwrap_or(false) + }) + .last() + .flatten() + { + Some(attr) => ( + InsertPosition::After(attr.syntax().clone().into()), + AddBlankLine::BeforeTwice, + ), + None => (InsertPosition::First, AddBlankLine::AfterTwice), + } + } }, } } @@ -459,6 +479,36 @@ fn main() {}", ) } + #[test] + fn insert_after_inner_attr() { + // empty files will get two trailing newlines + // this is due to the test case insert_no_imports above + check_full( + "foo::bar", + r"#![allow(unused_imports)]", + r"#![allow(unused_imports)] + +use foo::bar;", + ) + } + + #[test] + fn insert_after_inner_attr2() { + // empty files will get two trailing newlines + // this is due to the test case insert_no_imports above + check_full( + "foo::bar", + r"#![allow(unused_imports)] + +fn main() {}", + r"#![allow(unused_imports)] + +use foo::bar; + +fn main() {}", + ) + } + #[test] fn merge_groups() { check_last("std::io", r"use std::fmt;", r"use std::{fmt, io};") -- cgit v1.2.3