X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=crates%2Fide%2Fsrc%2Fexpand_macro.rs;h=949744c01b2ae73a79c342bea85f5cb9834776b5;hb=749eeef3e75a3acc993fdd454ebadaa7e319509a;hp=5f34ba8391979831b227cbf2021182ddd10e26b8;hpb=7d1015b8d177a02dff03d2c70bc74e5d4ed34335;p=rust.git diff --git a/crates/ide/src/expand_macro.rs b/crates/ide/src/expand_macro.rs index 5f34ba83919..949744c01b2 100644 --- a/crates/ide/src/expand_macro.rs +++ b/crates/ide/src/expand_macro.rs @@ -1,9 +1,10 @@ -use std::iter; - use hir::Semantics; -use ide_db::{helpers::pick_best_token, RootDatabase}; +use ide_db::{ + helpers::{insert_whitespace_into_node::insert_ws_into, pick_best_token}, + RootDatabase, +}; use itertools::Itertools; -use syntax::{ast, ted, AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, T}; +use syntax::{ast, ted, AstNode, SyntaxKind, SyntaxNode}; use crate::FilePosition; @@ -32,19 +33,32 @@ pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option< _ => 0, })?; - let descended = sema.descend_into_macros_single(tok.clone()); - if let Some(attr) = descended.ancestors().find_map(ast::Attr::cast) { - if let Some((path, tt)) = attr.as_simple_call() { - if path == "derive" { - let mut tt = tt.syntax().children_with_tokens().skip(1).join(""); - tt.pop(); - let expansions = sema.expand_derive_macro(&attr)?; - return Some(ExpandedMacro { - name: tt, - expansion: expansions.into_iter().map(insert_whitespaces).join(""), - }); - } + // due to how Rust Analyzer works internally, we need to special case derive attributes, + // otherwise they might not get found, e.g. here with the cursor at $0 `#[attr]` would expand: + // ``` + // #[attr] + // #[derive($0Foo)] + // struct Bar; + // ``` + + let derive = sema.descend_into_macros(tok.clone()).iter().find_map(|descended| { + let attr = descended.ancestors().find_map(ast::Attr::cast)?; + let (path, tt) = attr.as_simple_call()?; + if path == "derive" { + let mut tt = tt.syntax().children_with_tokens().skip(1).join(""); + tt.pop(); + let expansions = sema.expand_derive_macro(&attr)?; + Some(ExpandedMacro { + name: tt, + expansion: expansions.into_iter().map(insert_ws_into).join(""), + }) + } else { + None } + }); + + if derive.is_some() { + return derive; } // FIXME: Intermix attribute and bang! expansions @@ -69,7 +83,7 @@ pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option< // FIXME: // macro expansion may lose all white space information // But we hope someday we can use ra_fmt for that - let expansion = insert_whitespaces(expanded?); + let expansion = insert_ws_into(expanded?).to_string(); Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion }) } @@ -109,80 +123,6 @@ fn expand( Some(expanded) } -// FIXME: It would also be cool to share logic here and in the mbe tests, -// which are pretty unreadable at the moment. -fn insert_whitespaces(syn: SyntaxNode) -> String { - use SyntaxKind::*; - let mut res = String::new(); - - let mut indent = 0; - let mut last: Option = None; - - for event in syn.preorder_with_tokens() { - let token = match event { - WalkEvent::Enter(NodeOrToken::Token(token)) => token, - WalkEvent::Leave(NodeOrToken::Node(node)) - if matches!(node.kind(), ATTR | MATCH_ARM | STRUCT | ENUM | UNION | FN | IMPL) => - { - res.push('\n'); - res.extend(iter::repeat(" ").take(2 * indent)); - continue; - } - _ => continue, - }; - let is_next = |f: fn(SyntaxKind) -> bool, default| -> bool { - token.next_token().map(|it| f(it.kind())).unwrap_or(default) - }; - let is_last = - |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) }; - - match token.kind() { - k if is_text(k) && is_next(|it| !it.is_punct(), true) => { - res.push_str(token.text()); - res.push(' '); - } - L_CURLY if is_next(|it| it != R_CURLY, true) => { - indent += 1; - if is_last(is_text, false) { - res.push(' '); - } - res.push_str("{\n"); - res.extend(iter::repeat(" ").take(2 * indent)); - } - R_CURLY if is_last(|it| it != L_CURLY, true) => { - indent = indent.saturating_sub(1); - res.push('\n'); - res.extend(iter::repeat(" ").take(2 * indent)); - res.push_str("}"); - } - R_CURLY => { - res.push_str("}\n"); - res.extend(iter::repeat(" ").take(2 * indent)); - } - LIFETIME_IDENT if is_next(|it| it == IDENT || it == MUT_KW, true) => { - res.push_str(token.text()); - res.push(' '); - } - T![;] => { - res.push_str(";\n"); - res.extend(iter::repeat(" ").take(2 * indent)); - } - T![->] => res.push_str(" -> "), - T![=] => res.push_str(" = "), - T![=>] => res.push_str(" => "), - _ => res.push_str(token.text()), - } - - last = Some(token.kind()); - } - - return res; - - fn is_text(k: SyntaxKind) -> bool { - k.is_keyword() || k.is_literal() || k == IDENT - } -} - #[cfg(test)] mod tests { use expect_test::{expect, Expect}; @@ -197,6 +137,23 @@ fn check(ra_fixture: &str, expect: Expect) { expect.assert_eq(&actual); } + #[test] + fn macro_expand_as_keyword() { + check( + r#" +macro_rules! bar { + ($i:tt) => { $i as _ } +} +fn main() { + let x: u64 = ba$0r!(5i64); +} +"#, + expect![[r#" + bar + 5i64 as _"#]], + ); + } + #[test] fn macro_expand_recursive_expansion() { check( @@ -353,15 +310,16 @@ fn main() { fn macro_expand_derive() { check( r#" -#[rustc_builtin_macro] -pub macro Clone {} +//- proc_macros: identity +//- minicore: clone, derive +#[proc_macros::identity] #[derive(C$0lone)] struct Foo {} "#, expect![[r#" Clone - impl< >crate::clone::Clone for Foo< >{} + impl< >core::clone::Clone for Foo< >{} "#]], ); @@ -371,10 +329,7 @@ impl< >crate::clone::Clone for Foo< >{} fn macro_expand_derive2() { check( r#" -#[rustc_builtin_macro] -pub macro Clone {} -#[rustc_builtin_macro] -pub macro Copy {} +//- minicore: copy, clone, derive #[derive(Cop$0y)] #[derive(Clone)] @@ -382,7 +337,7 @@ struct Foo {} "#, expect![[r#" Copy - impl< >crate::marker::Copy for Foo< >{} + impl< >core::marker::Copy for Foo< >{} "#]], ); @@ -392,19 +347,16 @@ impl< >crate::marker::Copy for Foo< >{} fn macro_expand_derive_multi() { check( r#" -#[rustc_builtin_macro] -pub macro Clone {} -#[rustc_builtin_macro] -pub macro Copy {} +//- minicore: copy, clone, derive #[derive(Cop$0y, Clone)] struct Foo {} "#, expect![[r#" Copy, Clone - impl< >crate::marker::Copy for Foo< >{} + impl< >core::marker::Copy for Foo< >{} - impl< >crate::clone::Clone for Foo< >{} + impl< >core::clone::Clone for Foo< >{} "#]], );