Skip to content

Commit a8b76b6

Browse files
committed
Expand into pseudo-derive attribute expansions in completions
1 parent 533f178 commit a8b76b6

File tree

13 files changed

+197
-56
lines changed

13 files changed

+197
-56
lines changed

crates/hir/src/semantics.rs

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,10 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
151151
self.imp.expand_attr_macro(item)
152152
}
153153

154+
pub fn expand_derive_as_pseudo_attr_macro(&self, attr: &ast::Attr) -> Option<SyntaxNode> {
155+
self.imp.expand_derive_as_pseudo_attr_macro(attr)
156+
}
157+
154158
pub fn resolve_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<Option<Macro>>> {
155159
self.imp.resolve_derive_macro(derive)
156160
}
@@ -185,6 +189,19 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
185189
self.imp.speculative_expand_attr(actual_macro_call, speculative_args, token_to_map)
186190
}
187191

192+
pub fn speculative_expand_derive_as_pseudo_attr_macro(
193+
&self,
194+
actual_macro_call: &ast::Attr,
195+
speculative_args: &ast::Attr,
196+
token_to_map: SyntaxToken,
197+
) -> Option<(SyntaxNode, SyntaxToken)> {
198+
self.imp.speculative_expand_derive_as_pseudo_attr_macro(
199+
actual_macro_call,
200+
speculative_args,
201+
token_to_map,
202+
)
203+
}
204+
188205
/// Descend the token into macrocalls to its first mapped counterpart.
189206
pub fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
190207
self.imp.descend_into_macros_single(token)
@@ -438,9 +455,16 @@ impl<'db> SemanticsImpl<'db> {
438455
fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
439456
let src = self.wrap_node_infile(item.clone());
440457
let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
441-
let file_id = macro_call_id.as_file();
442-
let node = self.parse_or_expand(file_id)?;
443-
Some(node)
458+
self.parse_or_expand(macro_call_id.as_file())
459+
}
460+
461+
fn expand_derive_as_pseudo_attr_macro(&self, attr: &ast::Attr) -> Option<SyntaxNode> {
462+
let src = self.wrap_node_infile(attr.clone());
463+
let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
464+
let call_id = self.with_ctx(|ctx| {
465+
ctx.attr_to_derive_macro_call(src.with_value(&adt), src).map(|(_, it, _)| it)
466+
})?;
467+
self.parse_or_expand(call_id.as_file())
444468
}
445469

446470
fn resolve_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<Option<Macro>>> {
@@ -533,6 +557,25 @@ impl<'db> SemanticsImpl<'db> {
533557
)
534558
}
535559

560+
fn speculative_expand_derive_as_pseudo_attr_macro(
561+
&self,
562+
actual_macro_call: &ast::Attr,
563+
speculative_args: &ast::Attr,
564+
token_to_map: SyntaxToken,
565+
) -> Option<(SyntaxNode, SyntaxToken)> {
566+
let attr = self.wrap_node_infile(actual_macro_call.clone());
567+
let adt = actual_macro_call.syntax().parent().and_then(ast::Adt::cast)?;
568+
let macro_call_id = self.with_ctx(|ctx| {
569+
ctx.attr_to_derive_macro_call(attr.with_value(&adt), attr).map(|(_, it, _)| it)
570+
})?;
571+
hir_expand::db::expand_speculative(
572+
self.db.upcast(),
573+
macro_call_id,
574+
speculative_args.syntax(),
575+
token_to_map,
576+
)
577+
}
578+
536579
// This might not be the correct way to do this, but it works for now
537580
fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
538581
let mut res = smallvec![];

crates/hir_expand/src/builtin_attr_macro.rs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
//! Builtin attributes.
22
3-
use itertools::Itertools;
4-
53
use crate::{db::AstDatabase, name, ExpandResult, MacroCallId, MacroCallKind};
64

75
macro_rules! register_builtin {
@@ -98,10 +96,16 @@ fn derive_attr_expand(
9896
) -> ExpandResult<tt::Subtree> {
9997
let loc = db.lookup_intern_macro_call(id);
10098
let derives = match &loc.kind {
101-
MacroCallKind::Attr { attr_args, .. } => &attr_args.0,
102-
_ => return ExpandResult::ok(tt.clone()),
99+
MacroCallKind::Attr { attr_args, is_derive: true, .. } => &attr_args.0,
100+
_ => return ExpandResult::ok(Default::default()),
103101
};
102+
pseudo_derive_attr_expansion(tt, derives)
103+
}
104104

105+
pub fn pseudo_derive_attr_expansion(
106+
tt: &tt::Subtree,
107+
args: &tt::Subtree,
108+
) -> ExpandResult<tt::Subtree> {
105109
let mk_leaf = |char| {
106110
tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct {
107111
char,
@@ -111,21 +115,12 @@ fn derive_attr_expand(
111115
};
112116

113117
let mut token_trees = Vec::new();
114-
for (comma, group) in &derives
115-
.token_trees
116-
.iter()
117-
.filter_map(|tt| match tt {
118-
tt::TokenTree::Leaf(l) => Some(l),
119-
tt::TokenTree::Subtree(_) => None,
120-
})
121-
.group_by(|l| matches!(l, tt::Leaf::Punct(tt::Punct { char: ',', .. })))
118+
for tt in (&args.token_trees)
119+
.split(|tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: ',', .. }))))
122120
{
123-
if comma {
124-
continue;
125-
}
126121
token_trees.push(mk_leaf('#'));
127122
token_trees.push(mk_leaf('['));
128-
token_trees.extend(group.cloned().map(tt::TokenTree::Leaf));
123+
token_trees.extend(tt.iter().cloned());
129124
token_trees.push(mk_leaf(']'));
130125
}
131126
token_trees.push(mk_leaf('('));

crates/hir_expand/src/db.rs

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ use syntax::{
1414
};
1515

1616
use crate::{
17-
ast_id_map::AstIdMap, fixup, hygiene::HygieneFrame, BuiltinAttrExpander, BuiltinDeriveExpander,
18-
BuiltinFnLikeExpander, ExpandError, ExpandResult, ExpandTo, HirFileId, HirFileIdRepr,
19-
MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind, MacroFile,
20-
ProcMacroExpander,
17+
ast_id_map::AstIdMap, builtin_attr_macro::pseudo_derive_attr_expansion, fixup,
18+
hygiene::HygieneFrame, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander,
19+
ExpandError, ExpandResult, ExpandTo, HirFileId, HirFileIdRepr, MacroCallId, MacroCallKind,
20+
MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
2121
};
2222

2323
/// Total limit on the number of tokens produced by any macro invocation.
@@ -161,14 +161,16 @@ pub fn expand_speculative(
161161
);
162162

163163
let (attr_arg, token_id) = match loc.kind {
164-
MacroCallKind::Attr { invoc_attr_index, .. } => {
165-
// Attributes may have an input token tree, build the subtree and map for this as well
166-
// then try finding a token id for our token if it is inside this input subtree.
167-
let item = ast::Item::cast(speculative_args.clone())?;
168-
let attr = item
169-
.doc_comments_and_attrs()
170-
.nth(invoc_attr_index as usize)
171-
.and_then(Either::left)?;
164+
MacroCallKind::Attr { invoc_attr_index, is_derive, .. } => {
165+
let attr = if is_derive {
166+
// for pseudo-derive expansion we actually pass the attribute itself only
167+
ast::Attr::cast(speculative_args.clone())
168+
} else {
169+
// Attributes may have an input token tree, build the subtree and map for this as well
170+
// then try finding a token id for our token if it is inside this input subtree.
171+
let item = ast::Item::cast(speculative_args.clone())?;
172+
item.doc_comments_and_attrs().nth(invoc_attr_index as usize).and_then(Either::left)
173+
}?;
172174
match attr.token_tree() {
173175
Some(token_tree) => {
174176
let (mut tree, map) = syntax_node_to_token_tree(attr.token_tree()?.syntax());
@@ -205,11 +207,15 @@ pub fn expand_speculative(
205207

206208
// Do the actual expansion, we need to directly expand the proc macro due to the attribute args
207209
// Otherwise the expand query will fetch the non speculative attribute args and pass those instead.
208-
let mut speculative_expansion = if let MacroDefKind::ProcMacro(expander, ..) = loc.def.kind {
209-
tt.delimiter = None;
210-
expander.expand(db, loc.krate, &tt, attr_arg.as_ref())
211-
} else {
212-
macro_def.expand(db, actual_macro_call, &tt)
210+
let mut speculative_expansion = match loc.def.kind {
211+
MacroDefKind::ProcMacro(expander, ..) => {
212+
tt.delimiter = None;
213+
expander.expand(db, loc.krate, &tt, attr_arg.as_ref())
214+
}
215+
MacroDefKind::BuiltInAttr(BuiltinAttrExpander::Derive, _) => {
216+
pseudo_derive_attr_expansion(&tt, attr_arg.as_ref()?)
217+
}
218+
_ => macro_def.expand(db, actual_macro_call, &tt),
213219
};
214220

215221
let expand_to = macro_expand_to(db, actual_macro_call);

crates/ide_assists/src/handlers/remove_dbg.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub(crate) fn remove_dbg(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
3232
}
3333

3434
let mac_input = tt.syntax().children_with_tokens().skip(1).take_while(|it| *it != r_delim);
35-
let input_expressions = mac_input.into_iter().group_by(|tok| tok.kind() == T![,]);
35+
let input_expressions = mac_input.group_by(|tok| tok.kind() == T![,]);
3636
let input_expressions = input_expressions
3737
.into_iter()
3838
.filter_map(|(is_sep, group)| (!is_sep).then(|| group))

crates/ide_completion/src/completions/attribute.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ mod derive;
2929
mod lint;
3030
mod repr;
3131

32+
pub(crate) use self::derive::complete_derive;
33+
3234
/// Complete inputs to known builtin attributes as well as derive attributes
3335
pub(crate) fn complete_known_attribute_input(
3436
acc: &mut Completions,
@@ -46,7 +48,6 @@ pub(crate) fn complete_known_attribute_input(
4648

4749
match path.text().as_str() {
4850
"repr" => repr::complete_repr(acc, ctx, tt),
49-
"derive" => derive::complete_derive(acc, ctx, ctx.attr.as_ref()?),
5051
"feature" => lint::complete_lint(acc, ctx, &parse_tt_as_comma_sep_paths(tt)?, FEATURES),
5152
"allow" | "warn" | "deny" | "forbid" => {
5253
let existing_lints = parse_tt_as_comma_sep_paths(tt)?;
@@ -62,9 +63,7 @@ pub(crate) fn complete_known_attribute_input(
6263

6364
lint::complete_lint(acc, ctx, &existing_lints, &lints);
6465
}
65-
"cfg" => {
66-
cfg::complete_cfg(acc, ctx);
67-
}
66+
"cfg" => cfg::complete_cfg(acc, ctx),
6867
_ => (),
6968
}
7069
Some(())
@@ -347,7 +346,7 @@ fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
347346
.children_with_tokens()
348347
.skip(1)
349348
.take_while(|it| it.as_token() != Some(&r_paren));
350-
let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
349+
let input_expressions = tokens.group_by(|tok| tok.kind() == T![,]);
351350
Some(
352351
input_expressions
353352
.into_iter()

crates/ide_completion/src/completions/attribute/derive.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,21 @@ use ide_db::{
66
};
77
use itertools::Itertools;
88
use rustc_hash::FxHashSet;
9-
use syntax::{ast, SmolStr, SyntaxKind};
9+
use syntax::{SmolStr, SyntaxKind};
1010

1111
use crate::{
12-
completions::flyimport::compute_fuzzy_completion_order_key, context::CompletionContext,
13-
item::CompletionItem, Completions, ImportEdit,
12+
completions::flyimport::compute_fuzzy_completion_order_key,
13+
context::{CompletionContext, PathCompletionCtx, PathKind},
14+
item::CompletionItem,
15+
Completions, ImportEdit,
1416
};
1517

16-
pub(super) fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, attr: &ast::Attr) {
18+
pub(crate) fn complete_derive(acc: &mut Completions, ctx: &CompletionContext) {
19+
let attr = match (&ctx.path_context, ctx.attr.as_ref()) {
20+
(Some(PathCompletionCtx { kind: Some(PathKind::Derive), .. }), Some(attr)) => attr,
21+
_ => return,
22+
};
23+
1724
let core = ctx.famous_defs().core();
1825
let existing_derives: FxHashSet<_> =
1926
ctx.sema.resolve_derive_macro(attr).into_iter().flatten().flatten().collect();

crates/ide_completion/src/completions/flyimport.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ pub(crate) fn import_on_the_fly(acc: &mut Completions, ctx: &CompletionContext)
153153
};
154154
match (kind, import.original_item) {
155155
// Aren't handled in flyimport
156-
(PathKind::Vis { .. } | PathKind::Use, _) => false,
156+
(PathKind::Vis { .. } | PathKind::Use | PathKind::Derive, _) => false,
157157
// modules are always fair game
158158
(_, ItemInNs::Types(hir::ModuleDef::Module(_))) => true,
159159
// and so are macros(except for attributes)

crates/ide_completion/src/completions/qualified_path.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,13 @@ pub(crate) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionCon
6363
}
6464

6565
match kind {
66-
Some(PathKind::Pat | PathKind::Attr { .. } | PathKind::Vis { .. } | PathKind::Use) => {
66+
Some(
67+
PathKind::Pat
68+
| PathKind::Attr { .. }
69+
| PathKind::Vis { .. }
70+
| PathKind::Use
71+
| PathKind::Derive,
72+
) => {
6773
return;
6874
}
6975
_ => {

crates/ide_completion/src/completions/unqualified_path.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,11 @@ pub(crate) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionC
1919
Some(PathCompletionCtx {
2020
kind:
2121
Some(
22-
PathKind::Vis { .. }
23-
| PathKind::Attr { .. }
22+
PathKind::Attr { .. }
23+
| PathKind::Derive
24+
| PathKind::Pat
2425
| PathKind::Use { .. }
25-
| PathKind::Pat,
26+
| PathKind::Vis { .. },
2627
),
2728
..
2829
}) => return,

0 commit comments

Comments
 (0)