5 use ra_parser::FragmentKind;
7 ast::{self, AstNode, ModuleItemOwner, NameOwner, TypeParamsOwner},
11 use crate::db::AstDatabase;
12 use crate::{name, quote, LazyMacroId, MacroDefId, MacroDefKind};
14 macro_rules! register_builtin {
15 ( $($trait:ident => $expand:ident),* ) => {
16 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17 pub enum BuiltinDeriveExpander {
21 impl BuiltinDeriveExpander {
27 ) -> Result<tt::Subtree, mbe::ExpandError> {
28 let expander = match *self {
29 $( BuiltinDeriveExpander::$trait => $expand, )*
35 pub fn find_builtin_derive(ident: &name::Name) -> Option<MacroDefId> {
36 let kind = match ident {
37 $( id if id == &name::name![$trait] => BuiltinDeriveExpander::$trait, )*
41 Some(MacroDefId { krate: None, ast_id: None, kind: MacroDefKind::BuiltInDerive(kind) })
48 Clone => clone_expand,
49 Default => default_expand,
50 Debug => debug_expand,
53 PartialOrd => partial_ord_expand,
55 PartialEq => partial_eq_expand
63 fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, mbe::ExpandError> {
64 let (parsed, token_map) = mbe::token_tree_to_syntax_node(tt, FragmentKind::Items)?; // FragmentKind::Items doesn't parse attrs?
65 let macro_items = ast::MacroItems::cast(parsed.syntax_node()).ok_or_else(|| {
66 debug!("derive node didn't parse");
67 mbe::ExpandError::UnexpectedToken
69 let item = macro_items.items().next().ok_or_else(|| {
70 debug!("no module item parsed");
71 mbe::ExpandError::NoMatchingRule
73 let node = item.syntax();
74 let (name, params) = match_ast! {
76 ast::StructDef(it) => (it.name(), it.type_param_list()),
77 ast::EnumDef(it) => (it.name(), it.type_param_list()),
78 ast::UnionDef(it) => (it.name(), it.type_param_list()),
80 debug!("unexpected node is {:?}", node);
81 return Err(mbe::ExpandError::ConversionError)
85 let name = name.ok_or_else(|| {
86 debug!("parsed item has no name");
87 mbe::ExpandError::NoMatchingRule
89 let name_token_id = token_map.token_by_range(name.syntax().text_range()).ok_or_else(|| {
90 debug!("name token not found");
91 mbe::ExpandError::ConversionError
93 let name_token = tt::Ident { id: name_token_id, text: name.text().clone() };
94 let type_params = params.map_or(0, |type_param_list| type_param_list.type_params().count());
95 Ok(BasicAdtInfo { name: name_token, type_params })
98 fn make_type_args(n: usize, bound: Vec<tt::TokenTree>) -> Vec<tt::TokenTree> {
99 let mut result = Vec::<tt::TokenTree>::new();
101 tt::Leaf::Punct(tt::Punct {
103 spacing: tt::Spacing::Alone,
104 id: tt::TokenId::unspecified(),
111 tt::Leaf::Punct(tt::Punct {
113 spacing: tt::Spacing::Alone,
114 id: tt::TokenId::unspecified(),
120 tt::Leaf::Ident(tt::Ident {
121 id: tt::TokenId::unspecified(),
122 text: format!("T{}", i).into(),
126 result.extend(bound.iter().cloned());
129 tt::Leaf::Punct(tt::Punct {
131 spacing: tt::Spacing::Alone,
132 id: tt::TokenId::unspecified(),
139 fn expand_simple_derive(
141 trait_path: tt::Subtree,
142 ) -> Result<tt::Subtree, mbe::ExpandError> {
143 let info = parse_adt(tt)?;
144 let name = info.name;
145 let trait_path_clone = trait_path.token_trees.clone();
146 let bound = (quote! { : ##trait_path_clone }).token_trees;
147 let type_params = make_type_args(info.type_params, bound);
148 let type_args = make_type_args(info.type_params, Vec::new());
149 let trait_path = trait_path.token_trees;
150 let expanded = quote! {
151 impl ##type_params ##trait_path for #name ##type_args {}
157 _db: &dyn AstDatabase,
160 ) -> Result<tt::Subtree, mbe::ExpandError> {
161 expand_simple_derive(tt, quote! { std::marker::Copy })
165 _db: &dyn AstDatabase,
168 ) -> Result<tt::Subtree, mbe::ExpandError> {
169 expand_simple_derive(tt, quote! { std::clone::Clone })
173 _db: &dyn AstDatabase,
176 ) -> Result<tt::Subtree, mbe::ExpandError> {
177 expand_simple_derive(tt, quote! { std::default::Default })
181 _db: &dyn AstDatabase,
184 ) -> Result<tt::Subtree, mbe::ExpandError> {
185 expand_simple_derive(tt, quote! { std::fmt::Debug })
189 _db: &dyn AstDatabase,
192 ) -> Result<tt::Subtree, mbe::ExpandError> {
193 expand_simple_derive(tt, quote! { std::hash::Hash })
197 _db: &dyn AstDatabase,
200 ) -> Result<tt::Subtree, mbe::ExpandError> {
201 expand_simple_derive(tt, quote! { std::cmp::Eq })
204 fn partial_eq_expand(
205 _db: &dyn AstDatabase,
208 ) -> Result<tt::Subtree, mbe::ExpandError> {
209 expand_simple_derive(tt, quote! { std::cmp::PartialEq })
213 _db: &dyn AstDatabase,
216 ) -> Result<tt::Subtree, mbe::ExpandError> {
217 expand_simple_derive(tt, quote! { std::cmp::Ord })
220 fn partial_ord_expand(
221 _db: &dyn AstDatabase,
224 ) -> Result<tt::Subtree, mbe::ExpandError> {
225 expand_simple_derive(tt, quote! { std::cmp::PartialOrd })
231 use crate::{test_db::TestDB, AstId, MacroCallId, MacroCallKind, MacroCallLoc};
232 use name::{known, Name};
233 use ra_db::{fixture::WithFixture, SourceDatabase};
235 fn expand_builtin_derive(s: &str, name: Name) -> String {
236 let def = find_builtin_derive(&name).unwrap();
238 let (db, file_id) = TestDB::with_single_file(&s);
239 let parsed = db.parse(file_id);
241 parsed.syntax_node().descendants().filter_map(ast::ModuleItem::cast).collect();
243 let ast_id_map = db.ast_id_map(file_id.into());
245 let attr_id = AstId::new(file_id.into(), ast_id_map.ast_id(&items[0]));
247 let loc = MacroCallLoc { def, kind: MacroCallKind::Attr(attr_id, name.to_string()) };
249 let id: MacroCallId = db.intern_macro(loc).into();
250 let parsed = db.parse_or_expand(id.as_file()).unwrap();
252 // FIXME text() for syntax nodes parsed from token tree looks weird
253 // because there's no whitespace, see below
254 parsed.text().to_string()
258 fn test_copy_expand_simple() {
259 let expanded = expand_builtin_derive(
267 assert_eq!(expanded, "impl< >std::marker::CopyforFoo< >{}");
271 fn test_copy_expand_with_type_params() {
272 let expanded = expand_builtin_derive(
282 "impl<T0:std::marker::Copy,T1:std::marker::Copy>std::marker::CopyforFoo<T0,T1>{}"
287 fn test_copy_expand_with_lifetimes() {
288 let expanded = expand_builtin_derive(
291 struct Foo<A, B, 'a, 'b>;
296 // We currently just ignore lifetimes
300 "impl<T0:std::marker::Copy,T1:std::marker::Copy>std::marker::CopyforFoo<T0,T1>{}"
305 fn test_clone_expand() {
306 let expanded = expand_builtin_derive(
316 "impl<T0:std::clone::Clone,T1:std::clone::Clone>std::clone::CloneforFoo<T0,T1>{}"