1 //! Renderer for macro invocations.
3 use hir::{Documentation, HasSource};
4 use ide_db::SymbolKind;
5 use syntax::display::macro_label;
8 item::{CompletionItem, CompletionKind, ImportEdit},
12 pub(crate) fn render_macro<'a>(
13 ctx: RenderContext<'a>,
14 import_to_add: Option<ImportEdit>,
16 macro_: hir::MacroDef,
17 ) -> Option<CompletionItem> {
18 let _p = profile::span("render_macro");
19 MacroRender::new(ctx, name, macro_).render(import_to_add)
23 struct MacroRender<'a> {
24 ctx: RenderContext<'a>,
26 macro_: hir::MacroDef,
27 docs: Option<Documentation>,
32 impl<'a> MacroRender<'a> {
33 fn new(ctx: RenderContext<'a>, name: String, macro_: hir::MacroDef) -> MacroRender<'a> {
34 let docs = ctx.docs(macro_);
35 let docs_str = docs.as_ref().map_or("", |s| s.as_str());
36 let (bra, ket) = guess_macro_braces(&name, docs_str);
38 MacroRender { ctx, name, macro_, docs, bra, ket }
41 fn render(&self, import_to_add: Option<ImportEdit>) -> Option<CompletionItem> {
43 CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), &self.label());
45 .kind(SymbolKind::Macro)
46 .set_documentation(self.docs.clone())
47 .set_deprecated(self.ctx.is_deprecated(self.macro_))
48 .add_import(import_to_add)
49 .set_detail(self.detail());
51 let needs_bang = self.needs_bang();
52 match self.ctx.snippet_cap() {
53 Some(cap) if needs_bang => {
54 let snippet = self.snippet();
55 let lookup = self.lookup();
56 builder.insert_snippet(cap, snippet).lookup_by(lookup);
58 None if needs_bang => {
59 builder.insert_text(self.banged_name());
62 cov_mark::hit!(dont_insert_macro_call_parens_unncessary);
63 builder.insert_text(&self.name);
70 fn needs_bang(&self) -> bool {
71 self.ctx.completion.use_item_syntax.is_none() && !self.ctx.completion.is_macro_call
74 fn label(&self) -> String {
75 if self.needs_bang() && self.ctx.snippet_cap().is_some() {
76 format!("{}!{}…{}", self.name, self.bra, self.ket)
82 fn snippet(&self) -> String {
83 format!("{}!{}$0{}", self.name, self.bra, self.ket)
86 fn lookup(&self) -> String {
90 fn banged_name(&self) -> String {
91 format!("{}!", self.name)
94 fn detail(&self) -> Option<String> {
95 let ast_node = self.macro_.source(self.ctx.db())?.value;
96 Some(macro_label(&ast_node))
100 fn guess_macro_braces(macro_name: &str, docs: &str) -> (&'static str, &'static str) {
101 let mut votes = [0, 0, 0];
102 for (idx, s) in docs.match_indices(¯o_name) {
103 let (before, after) = (&docs[..idx], &docs[idx + s.len()..]);
104 // Ensure to match the full word
105 if after.starts_with('!')
106 && !before.ends_with(|c: char| c == '_' || c.is_ascii_alphanumeric())
108 // It may have spaces before the braces like `foo! {}`
109 match after[1..].chars().find(|&c| !c.is_whitespace()) {
110 Some('{') => votes[0] += 1,
111 Some('[') => votes[1] += 1,
112 Some('(') => votes[2] += 1,
118 // Insert a space before `{}`.
119 // We prefer the last one when some votes equal.
120 let (_vote, (bra, ket)) = votes
122 .zip(&[(" {", "}"), ("[", "]"), ("(", ")")])
123 .max_by_key(|&(&vote, _)| vote)
130 use crate::test_utils::check_edit;
133 fn dont_insert_macro_call_parens_unncessary() {
134 cov_mark::check!(dont_insert_macro_call_parens_unncessary);
138 //- /main.rs crate:main deps:foo
140 //- /foo/lib.rs crate:foo
142 macro_rules! frobnicate { () => () }
152 macro_rules! frobnicate { () => () }
153 fn main() { frob$0!(); }
156 macro_rules! frobnicate { () => () }
157 fn main() { frobnicate!(); }
163 fn guesses_macro_braces() {
167 /// Creates a [`Vec`] containing the arguments.
170 /// let v = vec![1, 2, 3];
171 /// assert_eq!(v[0], 1);
172 /// assert_eq!(v[1], 2);
173 /// assert_eq!(v[2], 3);
175 macro_rules! vec { () => {} }
180 /// Creates a [`Vec`] containing the arguments.
183 /// let v = vec![1, 2, 3];
184 /// assert_eq!(v[0], 1);
185 /// assert_eq!(v[1], 2);
186 /// assert_eq!(v[2], 3);
188 macro_rules! vec { () => {} }
190 fn fn main() { vec![$0] }
199 /// Don't call `fooo!()` `fooo!()`, or `_foo![]` `_foo![]`,
200 /// call as `let _=foo! { hello world };`
201 macro_rules! foo { () => {} }
207 /// Don't call `fooo!()` `fooo!()`, or `_foo![]` `_foo![]`,
208 /// call as `let _=foo! { hello world };`
209 macro_rules! foo { () => {} }
210 fn main() { foo! {$0} }