From f24bba74d02a14552693a8d4b11b74bb8ffa93db Mon Sep 17 00:00:00 2001 From: Edwin Cheng Date: Fri, 15 Nov 2019 22:13:41 +0800 Subject: Fixed a bug for string lit in quote --- crates/ra_hir_expand/src/quote.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'crates') diff --git a/crates/ra_hir_expand/src/quote.rs b/crates/ra_hir_expand/src/quote.rs index 35133d216..65a35e52f 100644 --- a/crates/ra_hir_expand/src/quote.rs +++ b/crates/ra_hir_expand/src/quote.rs @@ -172,12 +172,12 @@ impl_to_to_tokentrees! { u32 => self { tt::Literal{text: self.to_string().into()} }; usize => self { tt::Literal{text: self.to_string().into()}}; i32 => self { tt::Literal{text: self.to_string().into()}}; - &str => self { tt::Literal{text: self.to_string().into()}}; - String => self { tt::Literal{text: self.into()}}; tt::Leaf => self { self }; tt::Literal => self { self }; tt::Ident => self { self }; - tt::Punct => self { self } + tt::Punct => self { self }; + &str => self { tt::Literal{text: format!("{:?}", self.escape_default().to_string()).into()}}; + String => self { tt::Literal{text: format!("{:?}", self.escape_default().to_string()).into()}} } #[cfg(test)] @@ -200,7 +200,7 @@ mod tests { let a = 20; assert_eq!(quote!(#a).to_string(), "20"); let s: String = "hello".into(); - assert_eq!(quote!(#s).to_string(), "hello"); + assert_eq!(quote!(#s).to_string(), "\"hello\""); } fn mk_ident(name: &str) -> tt::Ident { -- cgit v1.2.3 From 3ccd05fedc46796f793295901a8619492256468e Mon Sep 17 00:00:00 2001 From: Edwin Cheng Date: Mon, 18 Nov 2019 02:47:50 +0800 Subject: Add recursive expand in vscode --- crates/ra_ide_api/src/expand_macro.rs | 112 +++++++++++++++++++++++++ crates/ra_ide_api/src/lib.rs | 5 ++ crates/ra_lsp_server/src/main_loop.rs | 1 + crates/ra_lsp_server/src/main_loop/handlers.rs | 15 ++++ crates/ra_lsp_server/src/req.rs | 15 ++++ 5 files changed, 148 insertions(+) create mode 100644 crates/ra_ide_api/src/expand_macro.rs (limited to 'crates') diff --git a/crates/ra_ide_api/src/expand_macro.rs b/crates/ra_ide_api/src/expand_macro.rs new file mode 100644 index 000000000..48dc90932 --- /dev/null +++ b/crates/ra_ide_api/src/expand_macro.rs @@ -0,0 +1,112 @@ +//! FIXME: write short doc here + +use crate::{db::RootDatabase, FilePosition}; +use ra_db::SourceDatabase; +use rustc_hash::FxHashMap; + +use hir::db::AstDatabase; +use ra_syntax::{ + algo::{find_node_at_offset, replace_descendants}, + ast::{self}, + AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, +}; + +fn insert_whitespaces(syn: SyntaxNode) -> String { + 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(); + + while let Some(token) = token_iter.next() { + res += &token.text().to_string(); + if token.kind().is_keyword() + || token.kind().is_literal() + || token.kind() == SyntaxKind::IDENT + { + if !token_iter.peek().map(|it| it.kind().is_punct()).unwrap_or(false) { + res += " "; + } + } + } + + res +} + +fn expand_macro_recur( + db: &RootDatabase, + source: hir::Source<&SyntaxNode>, + macro_call: &ast::MacroCall, +) -> Option { + let analyzer = hir::SourceAnalyzer::new(db, source, None); + let expansion = analyzer.expand(db, ¯o_call)?; + let expanded: SyntaxNode = db.parse_or_expand(expansion.file_id())?; + + let children = expanded.descendants().filter_map(ast::MacroCall::cast); + let mut replaces = FxHashMap::default(); + + for child in children.into_iter() { + let source = hir::Source::new(expansion.file_id(), source.ast); + let new_node = expand_macro_recur(db, source, &child)?; + + replaces.insert(child.syntax().clone().into(), new_node.into()); + } + + Some(replace_descendants(&expanded, &replaces)) +} + +pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<(String, String)> { + let parse = db.parse(position.file_id); + let file = parse.tree(); + let name_ref = find_node_at_offset::(file.syntax(), position.offset)?; + let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?; + + let source = hir::Source::new(position.file_id.into(), mac.syntax()); + + let expanded = expand_macro_recur(db, source, &mac)?; + + // FIXME: + // macro expansion may lose all white space information + // But we hope someday we can use ra_fmt for that + let res = insert_whitespaces(expanded); + Some((name_ref.text().to_string(), res)) +} + +#[cfg(test)] +mod tests { + use crate::mock_analysis::analysis_and_position; + + fn check_expand_macro(fixture: &str, expected: (&str, &str)) { + let (analysis, pos) = analysis_and_position(fixture); + + let result = analysis.expand_macro(pos).unwrap().unwrap(); + assert_eq!(result, (expected.0.to_string(), expected.1.to_string())); + } + + #[test] + fn macro_expand_recursive_expansion() { + check_expand_macro( + r#" + //- /lib.rs + macro_rules! bar { + () => { fn b() {} } + } + macro_rules! foo { + () => { bar!(); } + } + macro_rules! baz { + () => { foo!(); } + } + f<|>oo!(); + "#, + ("foo", "fn b(){}"), + ); + } +} diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs index 110ddcd62..d1b73ef6f 100644 --- a/crates/ra_ide_api/src/lib.rs +++ b/crates/ra_ide_api/src/lib.rs @@ -42,6 +42,7 @@ mod display; mod inlay_hints; mod wasm_shims; mod expand; +mod expand_macro; #[cfg(test)] mod marks; @@ -296,6 +297,10 @@ impl Analysis { self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range)) } + pub fn expand_macro(&self, position: FilePosition) -> Cancelable> { + self.with_db(|db| expand_macro::expand_macro(db, position)) + } + /// Returns an edit to remove all newlines in the range, cleaning up minor /// stuff like trailing commas. pub fn join_lines(&self, frange: FileRange) -> Cancelable { diff --git a/crates/ra_lsp_server/src/main_loop.rs b/crates/ra_lsp_server/src/main_loop.rs index 379dab438..f828efdee 100644 --- a/crates/ra_lsp_server/src/main_loop.rs +++ b/crates/ra_lsp_server/src/main_loop.rs @@ -436,6 +436,7 @@ fn on_request( })? .on::(handlers::handle_analyzer_status)? .on::(handlers::handle_syntax_tree)? + .on::(handlers::handle_expand_macro)? .on::(handlers::handle_on_type_formatting)? .on::(handlers::handle_document_symbol)? .on::(handlers::handle_workspace_symbol)? diff --git a/crates/ra_lsp_server/src/main_loop/handlers.rs b/crates/ra_lsp_server/src/main_loop/handlers.rs index 20f9aee13..783b0a827 100644 --- a/crates/ra_lsp_server/src/main_loop/handlers.rs +++ b/crates/ra_lsp_server/src/main_loop/handlers.rs @@ -47,6 +47,21 @@ pub fn handle_syntax_tree(world: WorldSnapshot, params: req::SyntaxTreeParams) - Ok(res) } +pub fn handle_expand_macro( + world: WorldSnapshot, + params: req::ExpandMacroParams, +) -> Result> { + let _p = profile("handle_expand_macro"); + let file_id = params.text_document.try_conv_with(&world)?; + let line_index = world.analysis().file_line_index(file_id)?; + let offset = params.position.map(|p| p.conv_with(&line_index)); + + match offset { + None => Ok(None), + Some(offset) => Ok(world.analysis().expand_macro(FilePosition { file_id, offset })?), + } +} + pub fn handle_selection_range( world: WorldSnapshot, params: req::SelectionRangeParams, diff --git a/crates/ra_lsp_server/src/req.rs b/crates/ra_lsp_server/src/req.rs index d25fc5726..dbc0e9624 100644 --- a/crates/ra_lsp_server/src/req.rs +++ b/crates/ra_lsp_server/src/req.rs @@ -45,6 +45,21 @@ pub struct SyntaxTreeParams { pub range: Option, } +pub enum ExpandMacro {} + +impl Request for ExpandMacro { + type Params = ExpandMacroParams; + type Result = Option<(String, String)>; + const METHOD: &'static str = "rust-analyzer/expandMacro"; +} + +#[derive(Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ExpandMacroParams { + pub text_document: TextDocumentIdentifier, + pub position: Option, +} + pub enum SelectionRangeRequest {} impl Request for SelectionRangeRequest { -- cgit v1.2.3 From ae49a22b5cdd47add478fef6bb8ad3d75338e313 Mon Sep 17 00:00:00 2001 From: Edwin Cheng Date: Mon, 18 Nov 2019 03:35:46 +0800 Subject: Rebase --- crates/ra_hir/src/source_binder.rs | 5 +++++ crates/ra_ide_api/src/expand_macro.rs | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) (limited to 'crates') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index f0ed8e2b2..6d75296a5 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -140,6 +140,11 @@ impl Expansion { exp_info.map_token_down(token) } + pub fn source(&self, db: &impl HirDatabase) -> Source> { + let loc = db.lookup_intern_macro(self.macro_call_id); + Source::new(self.file_id(), loc.ast_id) + } + fn file_id(&self) -> HirFileId { self.macro_call_id.as_file(MacroFileKind::Items) } diff --git a/crates/ra_ide_api/src/expand_macro.rs b/crates/ra_ide_api/src/expand_macro.rs index 48dc90932..49c096ed5 100644 --- a/crates/ra_ide_api/src/expand_macro.rs +++ b/crates/ra_ide_api/src/expand_macro.rs @@ -1,10 +1,10 @@ //! FIXME: write short doc here use crate::{db::RootDatabase, FilePosition}; +use hir::db::AstDatabase; use ra_db::SourceDatabase; use rustc_hash::FxHashMap; -use hir::db::AstDatabase; use ra_syntax::{ algo::{find_node_at_offset, replace_descendants}, ast::{self}, @@ -47,13 +47,14 @@ fn expand_macro_recur( ) -> Option { let analyzer = hir::SourceAnalyzer::new(db, source, None); let expansion = analyzer.expand(db, ¯o_call)?; - let expanded: SyntaxNode = db.parse_or_expand(expansion.file_id())?; + let new_source = expansion.source(db); + let expanded: SyntaxNode = db.parse_or_expand(new_source.file_id)?; let children = expanded.descendants().filter_map(ast::MacroCall::cast); let mut replaces = FxHashMap::default(); for child in children.into_iter() { - let source = hir::Source::new(expansion.file_id(), source.ast); + let source = new_source.with_ast(source.ast); let new_node = expand_macro_recur(db, source, &child)?; replaces.insert(child.syntax().clone().into(), new_node.into()); -- cgit v1.2.3 From 94c63d280246971983cad4fa6ce2d333e3ba9f02 Mon Sep 17 00:00:00 2001 From: Edwin Cheng Date: Tue, 19 Nov 2019 22:56:28 +0800 Subject: Change to use Expansion::file_id and reordering --- crates/ra_hir/src/source_binder.rs | 7 +--- crates/ra_ide_api/src/expand_macro.rs | 79 +++++++++++++++++------------------ 2 files changed, 40 insertions(+), 46 deletions(-) (limited to 'crates') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 6d75296a5..5d3196c2a 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -140,12 +140,7 @@ impl Expansion { exp_info.map_token_down(token) } - pub fn source(&self, db: &impl HirDatabase) -> Source> { - let loc = db.lookup_intern_macro(self.macro_call_id); - Source::new(self.file_id(), loc.ast_id) - } - - fn file_id(&self) -> HirFileId { + pub fn file_id(&self) -> HirFileId { self.macro_call_id.as_file(MacroFileKind::Items) } } diff --git a/crates/ra_ide_api/src/expand_macro.rs b/crates/ra_ide_api/src/expand_macro.rs index 49c096ed5..bd557d455 100644 --- a/crates/ra_ide_api/src/expand_macro.rs +++ b/crates/ra_ide_api/src/expand_macro.rs @@ -11,33 +11,20 @@ use ra_syntax::{ AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, }; -fn insert_whitespaces(syn: SyntaxNode) -> String { - 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(); +pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<(String, String)> { + let parse = db.parse(position.file_id); + let file = parse.tree(); + let name_ref = find_node_at_offset::(file.syntax(), position.offset)?; + let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?; - while let Some(token) = token_iter.next() { - res += &token.text().to_string(); - if token.kind().is_keyword() - || token.kind().is_literal() - || token.kind() == SyntaxKind::IDENT - { - if !token_iter.peek().map(|it| it.kind().is_punct()).unwrap_or(false) { - res += " "; - } - } - } + let source = hir::Source::new(position.file_id.into(), mac.syntax()); + let expanded = expand_macro_recur(db, source, &mac)?; - res + // FIXME: + // macro expansion may lose all white space information + // But we hope someday we can use ra_fmt for that + let res = insert_whitespaces(expanded); + Some((name_ref.text().to_string(), res)) } fn expand_macro_recur( @@ -47,14 +34,14 @@ fn expand_macro_recur( ) -> Option { let analyzer = hir::SourceAnalyzer::new(db, source, None); let expansion = analyzer.expand(db, ¯o_call)?; - let new_source = expansion.source(db); - let expanded: SyntaxNode = db.parse_or_expand(new_source.file_id)?; + let macro_file_id = expansion.file_id(); + let expanded: SyntaxNode = db.parse_or_expand(macro_file_id)?; let children = expanded.descendants().filter_map(ast::MacroCall::cast); let mut replaces = FxHashMap::default(); for child in children.into_iter() { - let source = new_source.with_ast(source.ast); + let source = hir::Source::new(macro_file_id, source.ast); let new_node = expand_macro_recur(db, source, &child)?; replaces.insert(child.syntax().clone().into(), new_node.into()); @@ -63,21 +50,33 @@ fn expand_macro_recur( Some(replace_descendants(&expanded, &replaces)) } -pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<(String, String)> { - let parse = db.parse(position.file_id); - let file = parse.tree(); - let name_ref = find_node_at_offset::(file.syntax(), position.offset)?; - let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?; +fn insert_whitespaces(syn: SyntaxNode) -> String { + let mut res = String::new(); - let source = hir::Source::new(position.file_id.into(), mac.syntax()); + let mut token_iter = syn + .preorder_with_tokens() + .filter_map(|event| { + if let WalkEvent::Enter(NodeOrToken::Token(token)) = event { + Some(token) + } else { + None + } + }) + .peekable(); - let expanded = expand_macro_recur(db, source, &mac)?; + while let Some(token) = token_iter.next() { + res += &token.text().to_string(); + if token.kind().is_keyword() + || token.kind().is_literal() + || token.kind() == SyntaxKind::IDENT + { + if !token_iter.peek().map(|it| it.kind().is_punct()).unwrap_or(false) { + res += " "; + } + } + } - // FIXME: - // macro expansion may lose all white space information - // But we hope someday we can use ra_fmt for that - let res = insert_whitespaces(expanded); - Some((name_ref.text().to_string(), res)) + res } #[cfg(test)] -- cgit v1.2.3 From 4012da07fd22223660a21c65d54d10a9a632eda0 Mon Sep 17 00:00:00 2001 From: Edwin Cheng Date: Tue, 19 Nov 2019 22:56:48 +0800 Subject: Change return type of expand_macro --- crates/ra_ide_api/src/expand_macro.rs | 14 ++++++++++---- crates/ra_ide_api/src/lib.rs | 3 ++- crates/ra_lsp_server/src/main_loop/handlers.rs | 7 +++++-- crates/ra_lsp_server/src/req.rs | 9 ++++++++- 4 files changed, 25 insertions(+), 8 deletions(-) (limited to 'crates') diff --git a/crates/ra_ide_api/src/expand_macro.rs b/crates/ra_ide_api/src/expand_macro.rs index bd557d455..44e77ba50 100644 --- a/crates/ra_ide_api/src/expand_macro.rs +++ b/crates/ra_ide_api/src/expand_macro.rs @@ -11,7 +11,12 @@ use ra_syntax::{ AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, }; -pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<(String, String)> { +pub struct ExpandedMacro { + pub name: String, + pub expansion: String, +} + +pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option { let parse = db.parse(position.file_id); let file = parse.tree(); let name_ref = find_node_at_offset::(file.syntax(), position.offset)?; @@ -23,8 +28,8 @@ 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 res = insert_whitespaces(expanded); - Some((name_ref.text().to_string(), res)) + let expansion = insert_whitespaces(expanded); + Some(ExpandedMacro { name: name_ref.text().to_string(), expansion }) } fn expand_macro_recur( @@ -87,7 +92,8 @@ mod tests { let (analysis, pos) = analysis_and_position(fixture); let result = analysis.expand_macro(pos).unwrap().unwrap(); - assert_eq!(result, (expected.0.to_string(), expected.1.to_string())); + assert_eq!(result.name, expected.0.to_string()); + assert_eq!(result.expansion, expected.1.to_string()); } #[test] diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs index d1b73ef6f..57ed97147 100644 --- a/crates/ra_ide_api/src/lib.rs +++ b/crates/ra_ide_api/src/lib.rs @@ -66,6 +66,7 @@ pub use crate::{ completion::{CompletionItem, CompletionItemKind, InsertTextFormat}, diagnostics::Severity, display::{file_structure, FunctionSignature, NavigationTarget, StructureNode}, + expand_macro::ExpandedMacro, feature_flags::FeatureFlags, folding_ranges::{Fold, FoldKind}, hover::HoverResult, @@ -297,7 +298,7 @@ impl Analysis { self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range)) } - pub fn expand_macro(&self, position: FilePosition) -> Cancelable> { + pub fn expand_macro(&self, position: FilePosition) -> Cancelable> { self.with_db(|db| expand_macro::expand_macro(db, position)) } diff --git a/crates/ra_lsp_server/src/main_loop/handlers.rs b/crates/ra_lsp_server/src/main_loop/handlers.rs index 783b0a827..0461bf385 100644 --- a/crates/ra_lsp_server/src/main_loop/handlers.rs +++ b/crates/ra_lsp_server/src/main_loop/handlers.rs @@ -50,7 +50,7 @@ pub fn handle_syntax_tree(world: WorldSnapshot, params: req::SyntaxTreeParams) - pub fn handle_expand_macro( world: WorldSnapshot, params: req::ExpandMacroParams, -) -> Result> { +) -> Result> { let _p = profile("handle_expand_macro"); let file_id = params.text_document.try_conv_with(&world)?; let line_index = world.analysis().file_line_index(file_id)?; @@ -58,7 +58,10 @@ pub fn handle_expand_macro( match offset { None => Ok(None), - Some(offset) => Ok(world.analysis().expand_macro(FilePosition { file_id, offset })?), + Some(offset) => { + let res = world.analysis().expand_macro(FilePosition { file_id, offset })?; + Ok(res.map(|it| req::ExpandedMacro { name: it.name, expansion: it.expansion })) + } } } diff --git a/crates/ra_lsp_server/src/req.rs b/crates/ra_lsp_server/src/req.rs index dbc0e9624..39361b7e8 100644 --- a/crates/ra_lsp_server/src/req.rs +++ b/crates/ra_lsp_server/src/req.rs @@ -45,11 +45,18 @@ pub struct SyntaxTreeParams { pub range: Option, } +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ExpandedMacro { + pub name: String, + pub expansion: String, +} + pub enum ExpandMacro {} impl Request for ExpandMacro { type Params = ExpandMacroParams; - type Result = Option<(String, String)>; + type Result = Option; const METHOD: &'static str = "rust-analyzer/expandMacro"; } -- cgit v1.2.3 From 80fe467ce864de077d2f5a4e29e1a4d5fe535dc3 Mon Sep 17 00:00:00 2001 From: Edwin Cheng Date: Wed, 20 Nov 2019 00:12:48 +0800 Subject: Improve insert_whitespaces --- crates/ra_ide_api/src/expand_macro.rs | 94 ++++++++++++++++++++++++++++------- 1 file changed, 77 insertions(+), 17 deletions(-) (limited to 'crates') diff --git a/crates/ra_ide_api/src/expand_macro.rs b/crates/ra_ide_api/src/expand_macro.rs index 44e77ba50..07a7c738a 100644 --- a/crates/ra_ide_api/src/expand_macro.rs +++ b/crates/ra_ide_api/src/expand_macro.rs @@ -8,7 +8,7 @@ use rustc_hash::FxHashMap; use ra_syntax::{ algo::{find_node_at_offset, replace_descendants}, ast::{self}, - AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, + AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, T, }; pub struct ExpandedMacro { @@ -55,9 +55,12 @@ fn expand_macro_recur( Some(replace_descendants(&expanded, &replaces)) } +// 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 { - let mut res = String::new(); + use SyntaxKind::*; + let mut res = String::new(); let mut token_iter = syn .preorder_with_tokens() .filter_map(|event| { @@ -69,16 +72,44 @@ fn insert_whitespaces(syn: SyntaxNode) -> String { }) .peekable(); + let mut indent = 0; + let mut last: Option = None; + while let Some(token) = token_iter.next() { - res += &token.text().to_string(); - if token.kind().is_keyword() - || token.kind().is_literal() - || token.kind() == SyntaxKind::IDENT - { - if !token_iter.peek().map(|it| it.kind().is_punct()).unwrap_or(false) { - res += " "; + let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool { + token_iter.peek().map(|it| f(it.kind())).unwrap_or(default) + }; + let is_last = |f: fn(SyntaxKind) -> bool, default| -> bool { + last.map(|it| f(it)).unwrap_or(default) + }; + + res += &match token.kind() { + k @ _ + if (k.is_keyword() || k.is_literal() || k == IDENT) + && is_next(|it| !it.is_punct(), true) => + { + token.text().to_string() + " " } - } + L_CURLY if is_next(|it| it != R_CURLY, true) => { + indent += 1; + format!(" {{\n{}", " ".repeat(indent)) + } + R_CURLY if is_last(|it| it != L_CURLY, true) => { + indent = indent.checked_sub(1).unwrap_or(0); + format!("\n}}{}", " ".repeat(indent)) + } + R_CURLY => { + indent = indent.checked_sub(1).unwrap_or(0); + format!("}}\n{}", " ".repeat(indent)) + } + T![;] => format!(";\n{}", " ".repeat(indent)), + T![->] => " -> ".to_string(), + T![=] => " = ".to_string(), + T![=>] => " => ".to_string(), + _ => token.text().to_string(), + }; + + last = Some(token.kind()); } res @@ -86,19 +117,18 @@ fn insert_whitespaces(syn: SyntaxNode) -> String { #[cfg(test)] mod tests { + use super::*; use crate::mock_analysis::analysis_and_position; + use insta::assert_snapshot; - fn check_expand_macro(fixture: &str, expected: (&str, &str)) { + fn check_expand_macro(fixture: &str) -> ExpandedMacro { let (analysis, pos) = analysis_and_position(fixture); - - let result = analysis.expand_macro(pos).unwrap().unwrap(); - assert_eq!(result.name, expected.0.to_string()); - assert_eq!(result.expansion, expected.1.to_string()); + analysis.expand_macro(pos).unwrap().unwrap() } #[test] fn macro_expand_recursive_expansion() { - check_expand_macro( + let res = check_expand_macro( r#" //- /lib.rs macro_rules! bar { @@ -112,7 +142,37 @@ mod tests { } f<|>oo!(); "#, - ("foo", "fn b(){}"), ); + + 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 { + () => { + 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 +} +"###); } } -- cgit v1.2.3 From e29017139708174e922af7af614b1eb390952ecf Mon Sep 17 00:00:00 2001 From: Edwin Cheng Date: Wed, 20 Nov 2019 01:12:56 +0800 Subject: Add shot doc for expand_macro module --- crates/ra_ide_api/src/expand_macro.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'crates') diff --git a/crates/ra_ide_api/src/expand_macro.rs b/crates/ra_ide_api/src/expand_macro.rs index 07a7c738a..e9eb2a7fb 100644 --- a/crates/ra_ide_api/src/expand_macro.rs +++ b/crates/ra_ide_api/src/expand_macro.rs @@ -1,4 +1,4 @@ -//! FIXME: write short doc here +//! This modules implements "expand macro" functionality in the IDE use crate::{db::RootDatabase, FilePosition}; use hir::db::AstDatabase; -- cgit v1.2.3 From 83a8430e0a4f4c88e45a017a2212c981b42a4a7a Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 19 Nov 2019 21:13:36 +0300 Subject: :arrow_up: rowan --- crates/ra_syntax/Cargo.toml | 2 +- crates/ra_syntax/src/algo.rs | 33 ++++++++++++++++----------------- crates/ra_syntax/src/ast/extensions.rs | 2 +- 3 files changed, 18 insertions(+), 19 deletions(-) (limited to 'crates') diff --git a/crates/ra_syntax/Cargo.toml b/crates/ra_syntax/Cargo.toml index 45a18a73f..5db2b58c0 100644 --- a/crates/ra_syntax/Cargo.toml +++ b/crates/ra_syntax/Cargo.toml @@ -12,7 +12,7 @@ doctest = false [dependencies] itertools = "0.8.0" -rowan = "0.6.1" +rowan = "0.7.0" rustc_lexer = "0.1.0" rustc-hash = "1.0.1" arrayvec = "0.5.1" diff --git a/crates/ra_syntax/src/algo.rs b/crates/ra_syntax/src/algo.rs index 7cfea70f9..1c075082a 100644 --- a/crates/ra_syntax/src/algo.rs +++ b/crates/ra_syntax/src/algo.rs @@ -134,23 +134,19 @@ pub fn insert_children( to_green_element(element) }); - let old_children = parent.green().children(); + let mut old_children = parent.green().children().map(|it| match it { + NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()), + NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()), + }); let new_children = match &position { - InsertPosition::First => { - to_insert.chain(old_children.iter().cloned()).collect::>() - } - InsertPosition::Last => old_children.iter().cloned().chain(to_insert).collect::>(), + InsertPosition::First => to_insert.chain(old_children).collect::>(), + InsertPosition::Last => old_children.chain(to_insert).collect::>(), InsertPosition::Before(anchor) | InsertPosition::After(anchor) => { let take_anchor = if let InsertPosition::After(_) = position { 1 } else { 0 }; let split_at = position_of_child(parent, anchor.clone()) + take_anchor; - let (before, after) = old_children.split_at(split_at); - before - .iter() - .cloned() - .chain(to_insert) - .chain(after.iter().cloned()) - .collect::>() + let before = old_children.by_ref().take(split_at).collect::>(); + before.into_iter().chain(to_insert).chain(old_children).collect::>() } }; @@ -168,13 +164,16 @@ pub fn replace_children( ) -> SyntaxNode { let start = position_of_child(parent, to_delete.start().clone()); let end = position_of_child(parent, to_delete.end().clone()); - let old_children = parent.green().children(); + let mut old_children = parent.green().children().map(|it| match it { + NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()), + NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()), + }); - let new_children = old_children[..start] - .iter() - .cloned() + let before = old_children.by_ref().take(start).collect::>(); + let new_children = before + .into_iter() .chain(to_insert.map(to_green_element)) - .chain(old_children[end + 1..].iter().cloned()) + .chain(old_children.skip(end + 1 - start)) .collect::>(); with_children(parent, new_children) } diff --git a/crates/ra_syntax/src/ast/extensions.rs b/crates/ra_syntax/src/ast/extensions.rs index 761b2435c..4851dacb2 100644 --- a/crates/ra_syntax/src/ast/extensions.rs +++ b/crates/ra_syntax/src/ast/extensions.rs @@ -32,7 +32,7 @@ impl ast::NameRef { } fn text_of_first_token(node: &SyntaxNode) -> &SmolStr { - node.green().children().first().and_then(|it| it.as_token()).unwrap().text() + node.green().children().next().and_then(|it| it.into_token()).unwrap().text() } impl ast::Attr { -- cgit v1.2.3