7 ast::{self, AstNode, HasGenericParams, HasModuleItem, HasName},
11 use crate::{db::AstDatabase, name, quote, AstId, CrateId, MacroCallId, MacroDefId, MacroDefKind};
13 macro_rules! register_builtin {
14 ( $($trait:ident => $expand:ident),* ) => {
15 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16 pub enum BuiltinDeriveExpander {
20 impl BuiltinDeriveExpander {
26 ) -> ExpandResult<tt::Subtree> {
27 let expander = match *self {
28 $( BuiltinDeriveExpander::$trait => $expand, )*
33 fn find_by_name(name: &name::Name) -> Option<Self> {
35 $( id if id == &name::name![$trait] => Some(BuiltinDeriveExpander::$trait), )*
46 Clone => clone_expand,
47 Default => default_expand,
48 Debug => debug_expand,
51 PartialOrd => partial_ord_expand,
53 PartialEq => partial_eq_expand
56 pub fn find_builtin_derive(
59 ast_id: AstId<ast::Macro>,
60 ) -> Option<MacroDefId> {
61 let expander = BuiltinDeriveExpander::find_by_name(ident)?;
64 kind: MacroDefKind::BuiltInDerive(expander, ast_id),
74 fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, mbe::ExpandError> {
75 let (parsed, token_map) = mbe::token_tree_to_syntax_node(tt, mbe::ParserEntryPoint::Items)?; // FragmentKind::Items doesn't parse attrs?
76 let macro_items = ast::MacroItems::cast(parsed.syntax_node()).ok_or_else(|| {
77 debug!("derive node didn't parse");
78 mbe::ExpandError::UnexpectedToken
80 let item = macro_items.items().next().ok_or_else(|| {
81 debug!("no module item parsed");
82 mbe::ExpandError::NoMatchingRule
84 let node = item.syntax();
85 let (name, params) = match_ast! {
87 ast::Struct(it) => (it.name(), it.generic_param_list()),
88 ast::Enum(it) => (it.name(), it.generic_param_list()),
89 ast::Union(it) => (it.name(), it.generic_param_list()),
91 debug!("unexpected node is {:?}", node);
92 return Err(mbe::ExpandError::ConversionError)
96 let name = name.ok_or_else(|| {
97 debug!("parsed item has no name");
98 mbe::ExpandError::NoMatchingRule
100 let name_token_id = token_map.token_by_range(name.syntax().text_range()).ok_or_else(|| {
101 debug!("name token not found");
102 mbe::ExpandError::ConversionError
104 let name_token = tt::Ident { id: name_token_id, text: name.text().into() };
105 let type_params = params.map_or(0, |type_param_list| type_param_list.type_params().count());
106 Ok(BasicAdtInfo { name: name_token, type_params })
109 fn make_type_args(n: usize, bound: Vec<tt::TokenTree>) -> Vec<tt::TokenTree> {
110 let mut result = Vec::<tt::TokenTree>::with_capacity(n * 2);
112 tt::Leaf::Punct(tt::Punct {
114 spacing: tt::Spacing::Alone,
115 id: tt::TokenId::unspecified(),
122 tt::Leaf::Punct(tt::Punct {
124 spacing: tt::Spacing::Alone,
125 id: tt::TokenId::unspecified(),
131 tt::Leaf::Ident(tt::Ident {
132 id: tt::TokenId::unspecified(),
133 text: format!("T{}", i).into(),
137 result.extend(bound.iter().cloned());
140 tt::Leaf::Punct(tt::Punct {
142 spacing: tt::Spacing::Alone,
143 id: tt::TokenId::unspecified(),
150 fn expand_simple_derive(tt: &tt::Subtree, trait_path: tt::Subtree) -> ExpandResult<tt::Subtree> {
151 let info = match parse_adt(tt) {
153 Err(e) => return ExpandResult::only_err(e),
155 let name = info.name;
156 let trait_path_clone = trait_path.token_trees.clone();
157 let bound = (quote! { : ##trait_path_clone }).token_trees;
158 let type_params = make_type_args(info.type_params, bound);
159 let type_args = make_type_args(info.type_params, Vec::new());
160 let trait_path = trait_path.token_trees;
161 let expanded = quote! {
162 impl ##type_params ##trait_path for #name ##type_args {}
164 ExpandResult::ok(expanded)
167 fn find_builtin_crate(db: &dyn AstDatabase, id: MacroCallId) -> tt::TokenTree {
168 // FIXME: make hygiene works for builtin derive macro
169 // such that $crate can be used here.
170 let cg = db.crate_graph();
171 let krate = db.lookup_intern_macro(id).krate;
174 // All crates except core itself should have a dependency on core,
175 // We detect `core` by seeing whether it doesn't have such a dependency.
176 let tt = if cg[krate].dependencies.iter().any(|dep| &*dep.name == "core") {
182 tt.token_trees[0].clone()
186 db: &dyn AstDatabase,
189 ) -> ExpandResult<tt::Subtree> {
190 let krate = find_builtin_crate(db, id);
191 expand_simple_derive(tt, quote! { #krate::marker::Copy })
195 db: &dyn AstDatabase,
198 ) -> ExpandResult<tt::Subtree> {
199 let krate = find_builtin_crate(db, id);
200 expand_simple_derive(tt, quote! { #krate::clone::Clone })
204 db: &dyn AstDatabase,
207 ) -> ExpandResult<tt::Subtree> {
208 let krate = find_builtin_crate(db, id);
209 expand_simple_derive(tt, quote! { #krate::default::Default })
213 db: &dyn AstDatabase,
216 ) -> ExpandResult<tt::Subtree> {
217 let krate = find_builtin_crate(db, id);
218 expand_simple_derive(tt, quote! { #krate::fmt::Debug })
222 db: &dyn AstDatabase,
225 ) -> ExpandResult<tt::Subtree> {
226 let krate = find_builtin_crate(db, id);
227 expand_simple_derive(tt, quote! { #krate::hash::Hash })
230 fn eq_expand(db: &dyn AstDatabase, id: MacroCallId, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
231 let krate = find_builtin_crate(db, id);
232 expand_simple_derive(tt, quote! { #krate::cmp::Eq })
235 fn partial_eq_expand(
236 db: &dyn AstDatabase,
239 ) -> ExpandResult<tt::Subtree> {
240 let krate = find_builtin_crate(db, id);
241 expand_simple_derive(tt, quote! { #krate::cmp::PartialEq })
245 db: &dyn AstDatabase,
248 ) -> ExpandResult<tt::Subtree> {
249 let krate = find_builtin_crate(db, id);
250 expand_simple_derive(tt, quote! { #krate::cmp::Ord })
253 fn partial_ord_expand(
254 db: &dyn AstDatabase,
257 ) -> ExpandResult<tt::Subtree> {
258 let krate = find_builtin_crate(db, id);
259 expand_simple_derive(tt, quote! { #krate::cmp::PartialOrd })
264 use base_db::{fixture::WithFixture, CrateId, SourceDatabase};
265 use expect_test::{expect, Expect};
268 use crate::{test_db::TestDB, AstId, MacroCallId, MacroCallKind, MacroCallLoc};
272 fn expand_builtin_derive(ra_fixture: &str) -> String {
273 let fixture = format!(
274 r#"//- /main.rs crate:main deps:core
277 //- /lib.rs crate:core
283 let (db, file_pos) = TestDB::with_position(&fixture);
284 let file_id = file_pos.file_id;
285 let ast_id_map = db.ast_id_map(file_id.into());
286 let parsed = db.parse(file_id);
288 parsed.syntax_node().descendants().filter_map(ast::Macro::cast).collect();
289 let items: Vec<_> = parsed
292 .filter(|node| !ast::Macro::can_cast(node.kind()))
293 .filter_map(ast::Item::cast)
296 assert_eq!(macros.len(), 1, "test must contain exactly 1 macro definition");
297 assert_eq!(items.len(), 1, "test must contain exactly 1 item");
299 let macro_ast_id = AstId::new(file_id.into(), ast_id_map.ast_id(¯os[0]));
300 let name = match ¯os[0] {
301 ast::Macro::MacroRules(rules) => rules.name().unwrap().as_name(),
302 ast::Macro::MacroDef(def) => def.name().unwrap().as_name(),
305 let expander = BuiltinDeriveExpander::find_by_name(&name).unwrap();
307 let ast_id = AstId::new(file_id.into(), ast_id_map.ast_id(&items[0]));
309 let loc = MacroCallLoc {
312 kind: MacroDefKind::BuiltInDerive(expander, macro_ast_id),
317 kind: MacroCallKind::Derive {
319 derive_name: name.to_string(),
320 derive_attr_index: 0,
324 let id: MacroCallId = db.intern_macro(loc);
325 let parsed = db.parse_or_expand(id.as_file()).unwrap();
327 // FIXME text() for syntax nodes parsed from token tree looks weird
328 // because there's no whitespace, see below
329 parsed.text().to_string()
332 fn check_derive(ra_fixture: &str, expected: Expect) {
333 let expanded = expand_builtin_derive(ra_fixture);
334 expected.assert_eq(&expanded);
338 fn test_copy_expand_simple() {
345 expect![["impl< >core::marker::CopyforFoo< >{}"]],
350 fn test_copy_expand_with_type_params() {
357 expect![["impl<T0:core::marker::Copy,T1:core::marker::Copy>core::marker::CopyforFoo<T0,T1>{}"]],
362 fn test_copy_expand_with_lifetimes() {
367 struct Foo<A, B, 'a, 'b>;
369 // We currently just ignore lifetimes
370 expect![["impl<T0:core::marker::Copy,T1:core::marker::Copy>core::marker::CopyforFoo<T0,T1>{}"]],
375 fn test_clone_expand() {
382 expect![["impl<T0:core::clone::Clone,T1:core::clone::Clone>core::clone::CloneforFoo<T0,T1>{}"]],