rust/crates/ra_ide/src/expand_macro.rs

293 lines
8.1 KiB
Rust
Raw Normal View History

2019-11-19 11:12:56 -06:00
//! This modules implements "expand macro" functionality in the IDE
2019-11-17 12:47:50 -06:00
2019-11-17 13:35:46 -06:00
use hir::db::AstDatabase;
2019-11-17 12:47:50 -06:00
use ra_db::SourceDatabase;
2020-02-06 05:52:32 -06:00
use ra_ide_db::RootDatabase;
2019-11-17 12:47:50 -06:00
use ra_syntax::{
algo::{find_node_at_offset, replace_descendants},
ast, AstNode, NodeOrToken, SyntaxElement, SyntaxKind, SyntaxNode, WalkEvent, T,
2019-11-17 12:47:50 -06:00
};
2020-02-06 05:52:32 -06:00
use rustc_hash::FxHashMap;
use crate::FilePosition;
2019-11-17 12:47:50 -06:00
2019-11-19 08:56:48 -06:00
pub struct ExpandedMacro {
pub name: String,
pub expansion: String,
}
pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
let parse = db.parse(position.file_id);
let file = parse.tree();
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 12:47:50 -06:00
2019-11-28 03:50:26 -06:00
let source = hir::InFile::new(position.file_id.into(), mac.syntax());
2019-11-19 22:21:31 -06:00
let expanded = expand_macro_recur(db, source, source.with_value(&mac))?;
2019-11-17 12:47:50 -06:00
// FIXME:
// macro expansion may lose all white space information
// But we hope someday we can use ra_fmt for that
2019-11-19 08:56:48 -06:00
let expansion = insert_whitespaces(expanded);
Some(ExpandedMacro { name: name_ref.text().to_string(), expansion })
2019-11-17 12:47:50 -06:00
}
fn expand_macro_recur(
db: &RootDatabase,
2019-11-28 03:50:26 -06:00
source: hir::InFile<&SyntaxNode>,
macro_call: hir::InFile<&ast::MacroCall>,
2019-11-17 12:47:50 -06:00
) -> Option<SyntaxNode> {
let analyzer = hir::SourceAnalyzer::new(db, source, None);
2019-11-19 22:21:31 -06:00
let expansion = analyzer.expand(db, macro_call)?;
let macro_file_id = expansion.file_id();
2019-11-21 22:04:20 -06:00
let mut expanded: SyntaxNode = db.parse_or_expand(macro_file_id)?;
2019-11-17 12:47:50 -06:00
let children = expanded.descendants().filter_map(ast::MacroCall::cast);
let mut replaces: FxHashMap<SyntaxElement, SyntaxElement> = FxHashMap::default();
2019-11-17 12:47:50 -06:00
for child in children.into_iter() {
2019-11-28 03:50:26 -06:00
let node = hir::InFile::new(macro_file_id, &child);
2019-11-22 20:33:14 -06:00
if let Some(new_node) = expand_macro_recur(db, source, node) {
// 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 {
replaces.insert(child.syntax().clone().into(), new_node.into());
}
2019-11-21 22:04:20 -06:00
}
2019-11-17 12:47:50 -06:00
}
Some(replace_descendants(&expanded, &|n| replaces.get(n).cloned()))
2019-11-17 12:47:50 -06:00
}
2019-11-19 10:12:48 -06: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 10:12:48 -06:00
use SyntaxKind::*;
2019-11-17 12:47:50 -06:00
2019-11-19 10:12:48 -06: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 12:47:50 -06:00
2019-11-19 10:12:48 -06:00
let mut indent = 0;
let mut last: Option<SyntaxKind> = None;
while let Some(token) = token_iter.next() {
2019-11-19 10:12:48 -06: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 14:14:30 -06:00
let is_last =
|f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
2019-11-19 10:12:48 -06:00
res += &match token.kind() {
2019-12-20 14:14:30 -06:00
k if is_text(k) && is_next(|it| !it.is_punct(), true) => token.text().to_string() + " ",
2019-11-19 10:12:48 -06:00
L_CURLY if is_next(|it| it != R_CURLY, true) => {
indent += 1;
2019-12-20 14:14:30 -06:00
let leading_space = if is_last(is_text, false) { " " } else { "" };
2019-11-21 12:35:49 -06:00
format!("{}{{\n{}", leading_space, " ".repeat(indent))
2019-11-19 10:12:48 -06:00
}
R_CURLY if is_last(|it| it != L_CURLY, true) => {
2019-12-20 14:14:30 -06:00
indent = indent.saturating_sub(1);
2019-11-21 12:35:49 -06:00
format!("\n{}}}", " ".repeat(indent))
2019-11-19 10:12:48 -06:00
}
2019-11-21 12:35:49 -06:00
R_CURLY => format!("}}\n{}", " ".repeat(indent)),
2019-11-19 10:12:48 -06: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 12:47:50 -06:00
2019-11-21 12:35:49 -06:00
return res;
fn is_text(k: SyntaxKind) -> bool {
k.is_keyword() || k.is_literal() || k == IDENT
}
2019-11-17 12:47:50 -06:00
}
#[cfg(test)]
mod tests {
2019-11-19 10:12:48 -06:00
use super::*;
2019-11-17 12:47:50 -06:00
use crate::mock_analysis::analysis_and_position;
2019-11-19 10:12:48 -06:00
use insta::assert_snapshot;
2019-11-17 12:47:50 -06:00
2019-11-19 10:12:48 -06:00
fn check_expand_macro(fixture: &str) -> ExpandedMacro {
2019-11-17 12:47:50 -06:00
let (analysis, pos) = analysis_and_position(fixture);
2019-11-19 10:12:48 -06:00
analysis.expand_macro(pos).unwrap().unwrap()
2019-11-17 12:47:50 -06:00
}
#[test]
fn macro_expand_recursive_expansion() {
2019-11-19 10:12:48 -06:00
let res = check_expand_macro(
2019-11-17 12:47:50 -06:00
r#"
//- /lib.rs
macro_rules! bar {
() => { fn b() {} }
}
macro_rules! foo {
() => { bar!(); }
}
macro_rules! baz {
() => { foo!(); }
2019-11-20 00:40:36 -06:00
}
2019-11-17 12:47:50 -06:00
f<|>oo!();
"#,
);
2019-11-19 10:12:48 -06:00
assert_eq!(res.name, "foo");
assert_snapshot!(res.expansion, @r###"
fn b(){}
"###);
}
#[test]
fn macro_expand_multiple_lines() {
let res = check_expand_macro(
r#"
//- /lib.rs
macro_rules! foo {
2019-11-20 00:40:36 -06:00
() => {
2019-11-19 10:12:48 -06:00
fn some_thing() -> u32 {
let a = 0;
a + 10
}
}
}
f<|>oo!();
"#,
);
assert_eq!(res.name, "foo");
assert_snapshot!(res.expansion, @r###"
fn some_thing() -> u32 {
let a = 0;
a+10
2019-11-20 00:40:36 -06:00
}
2019-11-21 12:35:30 -06:00
"###);
}
#[test]
fn macro_expand_match_ast() {
let res = check_expand_macro(
r#"
//- /lib.rs
macro_rules! match_ast {
(match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
2020-02-06 05:52:32 -06:00
2019-11-21 12:35:30 -06:00
(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 05:52:32 -06:00
}
2019-11-21 12:35:30 -06:00
fn main() {
mat<|>ch_ast! {
match container {
ast::TraitDef(it) => {},
ast::ImplBlock(it) => {},
_ => { continue },
}
}
}
"#,
);
assert_eq!(res.name, "match_ast");
assert_snapshot!(res.expansion, @r###"
{
if let Some(it) = ast::TraitDef::cast(container.clone()){}
else if let Some(it) = ast::ImplBlock::cast(container.clone()){}
else {
{
continue
}
}
}
2019-11-19 10:12:48 -06:00
"###);
2019-11-17 12:47:50 -06:00
}
2019-11-21 22:04:20 -06:00
#[test]
fn macro_expand_match_ast_inside_let_statement() {
let res = check_expand_macro(
r#"
//- /lib.rs
macro_rules! match_ast {
2020-02-06 05:52:32 -06:00
(match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
2019-11-21 22:04:20 -06:00
(match ($node:expr) {}) => {{}};
2020-02-06 05:52:32 -06:00
}
2019-11-21 22:04:20 -06:00
2020-02-06 05:52:32 -06:00
fn main() {
2019-11-21 22:04:20 -06:00
let p = f(|it| {
let res = mat<|>ch_ast! { match c {}};
Some(res)
})?;
}
"#,
);
assert_eq!(res.name, "match_ast");
assert_snapshot!(res.expansion, @r###"{}"###);
}
2019-11-22 20:33:14 -06:00
#[test]
fn macro_expand_inner_macro_fail_to_expand() {
let res = check_expand_macro(
r#"
//- /lib.rs
macro_rules! bar {
(BAD) => {};
}
macro_rules! foo {
() => {bar!()};
2020-02-06 05:52:32 -06:00
}
2019-11-22 20:33:14 -06:00
2020-02-06 05:52:32 -06:00
fn main() {
2019-11-22 20:33:14 -06:00
let res = fo<|>o!();
}
"#,
);
assert_eq!(res.name, "foo");
assert_snapshot!(res.expansion, @r###"bar!()"###);
}
#[test]
fn macro_expand_with_dollar_crate() {
let res = check_expand_macro(
r#"
//- /lib.rs
#[macro_export]
macro_rules! bar {
() => {0};
}
macro_rules! foo {
() => {$crate::bar!()};
2020-02-06 05:52:32 -06:00
}
2020-02-06 05:52:32 -06:00
fn main() {
let res = fo<|>o!();
}
"#,
);
assert_eq!(res.name, "foo");
assert_snapshot!(res.expansion, @r###"0"###);
}
2019-11-17 12:47:50 -06:00
}