rust/crates/ra_ide_api_light/src/assists/add_derive.rs

85 lines
2.2 KiB
Rust
Raw Normal View History

2019-01-03 06:08:32 -06:00
use ra_syntax::{
ast::{self, AstNode, AttrsOwner},
SyntaxKind::{WHITESPACE, COMMENT},
TextUnit,
};
2019-01-03 09:59:17 -06:00
use crate::assists::{AssistCtx, Assist};
2019-01-03 06:08:32 -06:00
2019-01-03 09:59:17 -06:00
pub fn add_derive(ctx: AssistCtx) -> Option<Assist> {
let nominal = ctx.node_at_offset::<ast::NominalDef>()?;
2019-01-03 06:08:32 -06:00
let node_start = derive_insertion_offset(nominal)?;
2019-01-03 09:59:17 -06:00
ctx.build("add `#[derive]`", |edit| {
2019-01-03 06:08:32 -06:00
let derive_attr = nominal
.attrs()
.filter_map(|x| x.as_call())
.filter(|(name, _arg)| name == "derive")
.map(|(_name, arg)| arg)
.next();
let offset = match derive_attr {
None => {
2019-01-03 09:59:17 -06:00
edit.insert(node_start, "#[derive()]\n");
2019-01-03 06:08:32 -06:00
node_start + TextUnit::of_str("#[derive(")
}
Some(tt) => tt.syntax().range().end() - TextUnit::of_char(')'),
};
2019-01-03 09:59:17 -06:00
edit.set_cursor(offset)
})
}
2019-01-03 06:08:32 -06:00
2019-01-03 09:59:17 -06:00
// Insert `derive` after doc comments.
2019-01-07 07:53:24 -06:00
fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextUnit> {
2019-01-03 09:59:17 -06:00
let non_ws_child = nominal
.syntax()
.children()
.find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
Some(non_ws_child.range().start())
2019-01-03 06:08:32 -06:00
}
#[cfg(test)]
mod tests {
use super::*;
2019-01-03 09:59:17 -06:00
use crate::assists::check_assist;
2019-01-03 06:08:32 -06:00
#[test]
fn add_derive_new() {
2019-01-03 09:59:17 -06:00
check_assist(
add_derive,
2019-01-03 06:08:32 -06:00
"struct Foo { a: i32, <|>}",
"#[derive(<|>)]\nstruct Foo { a: i32, }",
);
2019-01-03 09:59:17 -06:00
check_assist(
add_derive,
2019-01-03 06:08:32 -06:00
"struct Foo { <|> a: i32, }",
"#[derive(<|>)]\nstruct Foo { a: i32, }",
);
}
#[test]
fn add_derive_existing() {
2019-01-03 09:59:17 -06:00
check_assist(
add_derive,
2019-01-03 06:08:32 -06:00
"#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
"#[derive(Clone<|>)]\nstruct Foo { a: i32, }",
);
}
#[test]
fn add_derive_new_with_doc_comment() {
2019-01-03 09:59:17 -06:00
check_assist(
add_derive,
2019-01-03 06:08:32 -06:00
"
/// `Foo` is a pretty important struct.
/// It does stuff.
struct Foo { a: i32<|>, }
",
"
/// `Foo` is a pretty important struct.
/// It does stuff.
#[derive(<|>)]
struct Foo { a: i32, }
",
);
}
}