Skip to content

Commit 8ea9d93

Browse files
Rewrite #[derive] removal to be based on AST
1 parent da08198 commit 8ea9d93

File tree

4 files changed

+112
-107
lines changed

4 files changed

+112
-107
lines changed

crates/hir_expand/src/db.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ use syntax::{
1212
};
1313

1414
use crate::{
15-
ast_id_map::AstIdMap, hygiene::HygieneFrame, BuiltinDeriveExpander, BuiltinFnLikeExpander,
16-
EagerCallLoc, EagerMacroId, HirFileId, HirFileIdRepr, LazyMacroId, MacroCallId, MacroCallLoc,
17-
MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
15+
ast_id_map::AstIdMap, hygiene::HygieneFrame, input::process_macro_input, BuiltinDeriveExpander,
16+
BuiltinFnLikeExpander, EagerCallLoc, EagerMacroId, HirFileId, HirFileIdRepr, LazyMacroId,
17+
MacroCallId, MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
1818
};
1919

2020
/// Total limit on the number of tokens produced by any macro invocation.
@@ -281,6 +281,7 @@ fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
281281
};
282282
let loc = db.lookup_intern_macro(id);
283283
let arg = loc.kind.arg(db)?;
284+
let arg = process_macro_input(db, arg, id);
284285
Some(arg.green().into())
285286
}
286287

crates/hir_expand/src/input.rs

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
//! Macro input conditioning.
2+
3+
use syntax::{
4+
ast::{self, AttrsOwner},
5+
AstNode, SyntaxNode,
6+
};
7+
8+
use crate::{
9+
db::AstDatabase,
10+
name::{name, AsName},
11+
LazyMacroId, MacroCallKind, MacroCallLoc,
12+
};
13+
14+
pub(crate) fn process_macro_input(
15+
db: &dyn AstDatabase,
16+
node: SyntaxNode,
17+
id: LazyMacroId,
18+
) -> SyntaxNode {
19+
let loc: MacroCallLoc = db.lookup_intern_macro(id);
20+
21+
match loc.kind {
22+
MacroCallKind::FnLike { .. } => node,
23+
MacroCallKind::Derive { derive_attr_index, .. } => {
24+
let item = match ast::Item::cast(node.clone()) {
25+
Some(item) => item,
26+
None => return node,
27+
};
28+
29+
remove_derives_up_to(item, derive_attr_index as usize).syntax().clone()
30+
}
31+
}
32+
}
33+
34+
/// Removes `#[derive]` attributes from `item`, up to `attr_index`.
35+
fn remove_derives_up_to(item: ast::Item, attr_index: usize) -> ast::Item {
36+
let item = item.clone_for_update();
37+
for attr in item.attrs().take(attr_index + 1) {
38+
if let Some(name) =
39+
attr.path().and_then(|path| path.as_single_segment()).and_then(|seg| seg.name_ref())
40+
{
41+
if name.as_name() == name![derive] {
42+
attr.syntax().detach();
43+
}
44+
}
45+
}
46+
item
47+
}
48+
49+
#[cfg(test)]
50+
mod tests {
51+
use base_db::fixture::WithFixture;
52+
use base_db::SourceDatabase;
53+
use expect_test::{expect, Expect};
54+
55+
use crate::test_db::TestDB;
56+
57+
use super::*;
58+
59+
fn test_remove_derives_up_to(attr: usize, ra_fixture: &str, expect: Expect) {
60+
let (db, file_id) = TestDB::with_single_file(&ra_fixture);
61+
let parsed = db.parse(file_id);
62+
63+
let mut items: Vec<_> =
64+
parsed.syntax_node().descendants().filter_map(ast::Item::cast).collect();
65+
assert_eq!(items.len(), 1);
66+
67+
let item = remove_derives_up_to(items.pop().unwrap(), attr);
68+
expect.assert_eq(&item.to_string());
69+
}
70+
71+
#[test]
72+
fn remove_derive() {
73+
test_remove_derives_up_to(
74+
2,
75+
r#"
76+
#[allow(unused)]
77+
#[derive(Copy)]
78+
#[derive(Hello)]
79+
#[derive(Clone)]
80+
struct A {
81+
bar: u32
82+
}
83+
"#,
84+
expect![[r#"
85+
#[allow(unused)]
86+
87+
88+
#[derive(Clone)]
89+
struct A {
90+
bar: u32
91+
}"#]],
92+
);
93+
}
94+
}

crates/hir_expand/src/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub mod builtin_macro;
1414
pub mod proc_macro;
1515
pub mod quote;
1616
pub mod eager;
17+
mod input;
1718

1819
use either::Either;
1920

@@ -292,8 +293,19 @@ pub struct MacroCallLoc {
292293

293294
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
294295
pub enum MacroCallKind {
295-
FnLike { ast_id: AstId<ast::MacroCall>, fragment: FragmentKind },
296-
Derive { ast_id: AstId<ast::Item>, derive_name: String, derive_attr_index: u32 },
296+
FnLike {
297+
ast_id: AstId<ast::MacroCall>,
298+
fragment: FragmentKind,
299+
},
300+
Derive {
301+
ast_id: AstId<ast::Item>,
302+
derive_name: String,
303+
/// Syntactical index of the invoking `#[derive]` attribute.
304+
///
305+
/// Outer attributes are counted first, then inner attributes. This does not support
306+
/// out-of-line modules, which may have attributes spread across 2 files!
307+
derive_attr_index: u32,
308+
},
297309
}
298310

299311
impl MacroCallKind {

crates/hir_expand/src/proc_macro.rs

Lines changed: 0 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
33
use crate::db::AstDatabase;
44
use base_db::{CrateId, ProcMacroId};
5-
use tt::buffer::{Cursor, TokenBuffer};
65

76
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
87
pub struct ProcMacroExpander {
@@ -44,9 +43,6 @@ impl ProcMacroExpander {
4443
.clone()
4544
.ok_or_else(|| err!("No derive macro found."))?;
4645

47-
let tt = remove_derive_attrs(tt)
48-
.ok_or_else(|| err!("Fail to remove derive for custom derive"))?;
49-
5046
// Proc macros have access to the environment variables of the invoking crate.
5147
let env = &krate_graph[calling_crate].env;
5248

@@ -56,101 +52,3 @@ impl ProcMacroExpander {
5652
}
5753
}
5854
}
59-
60-
fn eat_punct(cursor: &mut Cursor, c: char) -> bool {
61-
if let Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Punct(punct), _)) = cursor.token_tree() {
62-
if punct.char == c {
63-
*cursor = cursor.bump();
64-
return true;
65-
}
66-
}
67-
false
68-
}
69-
70-
fn eat_subtree(cursor: &mut Cursor, kind: tt::DelimiterKind) -> bool {
71-
if let Some(tt::buffer::TokenTreeRef::Subtree(subtree, _)) = cursor.token_tree() {
72-
if Some(kind) == subtree.delimiter_kind() {
73-
*cursor = cursor.bump_subtree();
74-
return true;
75-
}
76-
}
77-
false
78-
}
79-
80-
fn eat_ident(cursor: &mut Cursor, t: &str) -> bool {
81-
if let Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Ident(ident), _)) = cursor.token_tree() {
82-
if t == ident.text.as_str() {
83-
*cursor = cursor.bump();
84-
return true;
85-
}
86-
}
87-
false
88-
}
89-
90-
fn remove_derive_attrs(tt: &tt::Subtree) -> Option<tt::Subtree> {
91-
let buffer = TokenBuffer::from_tokens(&tt.token_trees);
92-
let mut p = buffer.begin();
93-
let mut result = tt::Subtree::default();
94-
95-
while !p.eof() {
96-
let curr = p;
97-
98-
if eat_punct(&mut p, '#') {
99-
eat_punct(&mut p, '!');
100-
let parent = p;
101-
if eat_subtree(&mut p, tt::DelimiterKind::Bracket) {
102-
if eat_ident(&mut p, "derive") {
103-
p = parent.bump();
104-
continue;
105-
}
106-
}
107-
}
108-
109-
result.token_trees.push(curr.token_tree()?.cloned());
110-
p = curr.bump();
111-
}
112-
113-
Some(result)
114-
}
115-
116-
#[cfg(test)]
117-
mod tests {
118-
use super::*;
119-
use test_utils::assert_eq_text;
120-
121-
#[test]
122-
fn test_remove_derive_attrs() {
123-
let tt = mbe::parse_to_token_tree(
124-
r#"
125-
#[allow(unused)]
126-
#[derive(Copy)]
127-
#[derive(Hello)]
128-
struct A {
129-
bar: u32
130-
}
131-
"#,
132-
)
133-
.unwrap()
134-
.0;
135-
let result = format!("{:#?}", remove_derive_attrs(&tt).unwrap());
136-
137-
assert_eq_text!(
138-
r#"
139-
SUBTREE $
140-
PUNCH # [alone] 0
141-
SUBTREE [] 1
142-
IDENT allow 2
143-
SUBTREE () 3
144-
IDENT unused 4
145-
IDENT struct 15
146-
IDENT A 16
147-
SUBTREE {} 17
148-
IDENT bar 18
149-
PUNCH : [alone] 19
150-
IDENT u32 20
151-
"#
152-
.trim(),
153-
&result
154-
);
155-
}
156-
}

0 commit comments

Comments
 (0)