rust-analyzer/crates/ra_ide/src/expand_macro.rs

284 lines
6.9 KiB
Rust
Raw Normal View History

use hir::Semantics;
2020-02-06 11:52:32 +00:00
use ra_ide_db::RootDatabase;
2019-11-17 18:47:50 +00:00
use ra_syntax::{
algo::{find_node_at_offset, SyntaxRewriter},
2020-07-01 15:52:22 +00:00
ast, AstNode, NodeOrToken, SyntaxKind,
SyntaxKind::*,
SyntaxNode, WalkEvent, T,
2019-11-17 18:47:50 +00:00
};
2020-02-06 11:52:32 +00:00
use crate::FilePosition;
2019-11-17 18:47:50 +00:00
2019-11-19 14:56:48 +00:00
pub struct ExpandedMacro {
pub name: String,
pub expansion: String,
}
2020-05-31 08:14:36 +00:00
// Feature: Expand Macro Recursively
//
// Shows the full macro expansion of the macro at current cursor.
//
// |===
// | Editor | Action Name
//
// | VS Code | **Rust Analyzer: Expand macro recursively**
// |===
2019-11-19 14:56:48 +00:00
pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
let sema = Semantics::new(db);
let file = sema.parse(position.file_id);
let name_ref = find_node_at_offset::<ast::NameRef>(file.syntax(), position.offset)?;
let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?;
2019-11-17 18:47:50 +00:00
let expanded = expand_macro_recur(&sema, &mac)?;
2019-11-17 18:47:50 +00:00
// FIXME:
// macro expansion may lose all white space information
// But we hope someday we can use ra_fmt for that
2019-11-19 14:56:48 +00:00
let expansion = insert_whitespaces(expanded);
Some(ExpandedMacro { name: name_ref.text().to_string(), expansion })
2019-11-17 18:47:50 +00:00
}
fn expand_macro_recur(
sema: &Semantics<RootDatabase>,
macro_call: &ast::MacroCall,
2019-11-17 18:47:50 +00:00
) -> Option<SyntaxNode> {
let mut expanded = sema.expand(macro_call)?;
2019-11-17 18:47:50 +00:00
let children = expanded.descendants().filter_map(ast::MacroCall::cast);
let mut rewriter = SyntaxRewriter::default();
2019-11-17 18:47:50 +00:00
for child in children.into_iter() {
if let Some(new_node) = expand_macro_recur(sema, &child) {
2019-11-23 02:33:14 +00:00
// Replace the whole node if it is root
// `replace_descendants` will not replace the parent node
// but `SyntaxNode::descendants include itself
if expanded == *child.syntax() {
expanded = new_node;
} else {
rewriter.replace(child.syntax(), &new_node)
2019-11-23 02:33:14 +00:00
}
2019-11-22 04:04:20 +00:00
}
2019-11-17 18:47:50 +00:00
}
let res = rewriter.rewrite(&expanded);
Some(res)
2019-11-17 18:47:50 +00:00
}
2019-11-19 16:12:48 +00:00
// 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 {
2019-11-19 16:12:48 +00:00
let mut res = String::new();
let mut token_iter = syn
.preorder_with_tokens()
.filter_map(|event| {
if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
Some(token)
} else {
None
}
})
.peekable();
2019-11-17 18:47:50 +00:00
2019-11-19 16:12:48 +00:00
let mut indent = 0;
let mut last: Option<SyntaxKind> = None;
while let Some(token) = token_iter.next() {
2019-11-19 16:12:48 +00:00
let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
};
2019-12-20 20:14:30 +00:00
let is_last =
|f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
2019-11-19 16:12:48 +00:00
res += &match token.kind() {
2019-12-20 20:14:30 +00:00
k if is_text(k) && is_next(|it| !it.is_punct(), true) => token.text().to_string() + " ",
2019-11-19 16:12:48 +00:00
L_CURLY if is_next(|it| it != R_CURLY, true) => {
indent += 1;
2019-12-20 20:14:30 +00:00
let leading_space = if is_last(is_text, false) { " " } else { "" };
2019-11-21 18:35:49 +00:00
format!("{}{{\n{}", leading_space, " ".repeat(indent))
2019-11-19 16:12:48 +00:00
}
R_CURLY if is_last(|it| it != L_CURLY, true) => {
2019-12-20 20:14:30 +00:00
indent = indent.saturating_sub(1);
2019-11-21 18:35:49 +00:00
format!("\n{}}}", " ".repeat(indent))
2019-11-19 16:12:48 +00:00
}
2019-11-21 18:35:49 +00:00
R_CURLY => format!("}}\n{}", " ".repeat(indent)),
2019-11-19 16:12:48 +00:00
T![;] => format!(";\n{}", " ".repeat(indent)),
T![->] => " -> ".to_string(),
T![=] => " = ".to_string(),
T![=>] => " => ".to_string(),
_ => token.text().to_string(),
};
last = Some(token.kind());
}
2019-11-17 18:47:50 +00:00
2019-11-21 18:35:49 +00:00
return res;
fn is_text(k: SyntaxKind) -> bool {
k.is_keyword() || k.is_literal() || k == IDENT
}
2019-11-17 18:47:50 +00:00
}
#[cfg(test)]
mod tests {
2020-07-01 15:52:22 +00:00
use expect::{expect, Expect};
2019-11-17 18:47:50 +00:00
use crate::mock_analysis::analysis_and_position;
2020-07-01 15:52:22 +00:00
fn check(ra_fixture: &str, expect: Expect) {
let (analysis, pos) = analysis_and_position(ra_fixture);
let expansion = analysis.expand_macro(pos).unwrap().unwrap();
let actual = format!("{}\n{}", expansion.name, expansion.expansion);
expect.assert_eq(&actual);
2019-11-17 18:47:50 +00:00
}
#[test]
fn macro_expand_recursive_expansion() {
2020-07-01 15:52:22 +00:00
check(
2019-11-17 18:47:50 +00:00
r#"
2020-07-01 15:52:22 +00:00
macro_rules! bar {
() => { fn b() {} }
}
macro_rules! foo {
() => { bar!(); }
}
macro_rules! baz {
() => { foo!(); }
}
f<|>oo!();
"#,
expect![[r#"
foo
fn b(){}
"#]],
2019-11-17 18:47:50 +00:00
);
2019-11-19 16:12:48 +00:00
}
#[test]
fn macro_expand_multiple_lines() {
2020-07-01 15:52:22 +00:00
check(
2019-11-19 16:12:48 +00:00
r#"
2020-07-01 15:52:22 +00:00
macro_rules! foo {
() => {
fn some_thing() -> u32 {
let a = 0;
a + 10
2019-11-19 16:12:48 +00:00
}
2020-07-01 15:52:22 +00:00
}
}
f<|>oo!();
2019-11-19 16:12:48 +00:00
"#,
2020-07-01 15:52:22 +00:00
expect![[r#"
foo
fn some_thing() -> u32 {
let a = 0;
a+10
}"#]],
2019-11-19 16:12:48 +00:00
);
2019-11-21 18:35:30 +00:00
}
#[test]
fn macro_expand_match_ast() {
2020-07-01 15:52:22 +00:00
check(
2019-11-21 18:35:30 +00:00
r#"
2020-07-01 15:52:22 +00:00
macro_rules! match_ast {
(match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
(match ($node:expr) {
$( ast::$ast:ident($it:ident) => $res:block, )*
_ => $catch_all:expr $(,)?
}) => {{
$( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
{ $catch_all }
}};
}
2020-02-06 11:52:32 +00:00
2020-07-01 15:52:22 +00:00
fn main() {
mat<|>ch_ast! {
match container {
ast::TraitDef(it) => {},
ast::ImplDef(it) => {},
_ => { continue },
2020-02-06 11:52:32 +00:00
}
2019-11-21 18:35:30 +00:00
}
}
2020-07-01 15:52:22 +00:00
"#,
expect![[r#"
match_ast
{
if let Some(it) = ast::TraitDef::cast(container.clone()){}
else if let Some(it) = ast::ImplDef::cast(container.clone()){}
else {
{
continue
}
}
}"#]],
);
2019-11-17 18:47:50 +00:00
}
2019-11-22 04:04:20 +00:00
#[test]
fn macro_expand_match_ast_inside_let_statement() {
2020-07-01 15:52:22 +00:00
check(
2019-11-22 04:04:20 +00:00
r#"
2020-07-01 15:52:22 +00:00
macro_rules! match_ast {
(match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
(match ($node:expr) {}) => {{}};
}
2019-11-22 04:04:20 +00:00
2020-07-01 15:52:22 +00:00
fn main() {
let p = f(|it| {
let res = mat<|>ch_ast! { match c {}};
Some(res)
})?;
}
"#,
expect![[r#"
match_ast
{}
"#]],
2019-11-22 04:04:20 +00:00
);
}
2019-11-23 02:33:14 +00:00
#[test]
fn macro_expand_inner_macro_fail_to_expand() {
2020-07-01 15:52:22 +00:00
check(
2019-11-23 02:33:14 +00:00
r#"
2020-07-01 15:52:22 +00:00
macro_rules! bar {
(BAD) => {};
}
macro_rules! foo {
() => {bar!()};
}
2019-11-23 02:33:14 +00:00
2020-07-01 15:52:22 +00:00
fn main() {
let res = fo<|>o!();
}
"#,
expect![[r#"
foo
"#]],
2019-11-23 02:33:14 +00:00
);
}
#[test]
fn macro_expand_with_dollar_crate() {
2020-07-01 15:52:22 +00:00
check(
r#"
2020-07-01 15:52:22 +00:00
#[macro_export]
macro_rules! bar {
() => {0};
}
macro_rules! foo {
() => {$crate::bar!()};
}
2020-07-01 15:52:22 +00:00
fn main() {
let res = fo<|>o!();
}
"#,
expect![[r#"
foo
0 "#]],
);
}
2019-11-17 18:47:50 +00:00
}