5 use ra_parser::FragmentKind;
7 ast::{self, AstNode, GenericParamsOwner, ModuleItemOwner, NameOwner},
11 use crate::{db::AstDatabase, name, quote, LazyMacroId, 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 ) -> Result<tt::Subtree, mbe::ExpandError> {
27 let expander = match *self {
28 $( BuiltinDeriveExpander::$trait => $expand, )*
34 pub fn find_builtin_derive(ident: &name::Name) -> Option<MacroDefId> {
35 let kind = match ident {
36 $( id if id == &name::name![$trait] => BuiltinDeriveExpander::$trait, )*
40 Some(MacroDefId { krate: None, ast_id: None, kind: MacroDefKind::BuiltInDerive(kind), local_inner: false })
47 Clone => clone_expand,
48 Default => default_expand,
49 Debug => debug_expand,
52 PartialOrd => partial_ord_expand,
54 PartialEq => partial_eq_expand
62 fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, mbe::ExpandError> {
63 let (parsed, token_map) = mbe::token_tree_to_syntax_node(tt, FragmentKind::Items)?; // FragmentKind::Items doesn't parse attrs?
64 let macro_items = ast::MacroItems::cast(parsed.syntax_node()).ok_or_else(|| {
65 debug!("derive node didn't parse");
66 mbe::ExpandError::UnexpectedToken
68 let item = macro_items.items().next().ok_or_else(|| {
69 debug!("no module item parsed");
70 mbe::ExpandError::NoMatchingRule
72 let node = item.syntax();
73 let (name, params) = match_ast! {
75 ast::Struct(it) => (it.name(), it.generic_param_list()),
76 ast::Enum(it) => (it.name(), it.generic_param_list()),
77 ast::Union(it) => (it.name(), it.generic_param_list()),
79 debug!("unexpected node is {:?}", node);
80 return Err(mbe::ExpandError::ConversionError)
84 let name = name.ok_or_else(|| {
85 debug!("parsed item has no name");
86 mbe::ExpandError::NoMatchingRule
88 let name_token_id = token_map.token_by_range(name.syntax().text_range()).ok_or_else(|| {
89 debug!("name token not found");
90 mbe::ExpandError::ConversionError
92 let name_token = tt::Ident { id: name_token_id, text: name.text().clone() };
93 let type_params = params.map_or(0, |type_param_list| type_param_list.type_params().count());
94 Ok(BasicAdtInfo { name: name_token, type_params })
97 fn make_type_args(n: usize, bound: Vec<tt::TokenTree>) -> Vec<tt::TokenTree> {
98 let mut result = Vec::<tt::TokenTree>::new();
100 tt::Leaf::Punct(tt::Punct {
102 spacing: tt::Spacing::Alone,
103 id: tt::TokenId::unspecified(),
110 tt::Leaf::Punct(tt::Punct {
112 spacing: tt::Spacing::Alone,
113 id: tt::TokenId::unspecified(),
119 tt::Leaf::Ident(tt::Ident {
120 id: tt::TokenId::unspecified(),
121 text: format!("T{}", i).into(),
125 result.extend(bound.iter().cloned());
128 tt::Leaf::Punct(tt::Punct {
130 spacing: tt::Spacing::Alone,
131 id: tt::TokenId::unspecified(),
138 fn expand_simple_derive(
140 trait_path: tt::Subtree,
141 ) -> Result<tt::Subtree, mbe::ExpandError> {
142 let info = parse_adt(tt)?;
143 let name = info.name;
144 let trait_path_clone = trait_path.token_trees.clone();
145 let bound = (quote! { : ##trait_path_clone }).token_trees;
146 let type_params = make_type_args(info.type_params, bound);
147 let type_args = make_type_args(info.type_params, Vec::new());
148 let trait_path = trait_path.token_trees;
149 let expanded = quote! {
150 impl ##type_params ##trait_path for #name ##type_args {}
155 fn find_builtin_crate(db: &dyn AstDatabase, id: LazyMacroId) -> tt::TokenTree {
156 // FIXME: make hygiene works for builtin derive macro
157 // such that $crate can be used here.
158 let cg = db.crate_graph();
159 let krate = db.lookup_intern_macro(id).krate;
162 // All crates except core itself should have a dependency on core,
163 // We detect `core` by seeing whether it doesn't have such a dependency.
164 let tt = if cg[krate].dependencies.iter().any(|dep| &*dep.name == "core") {
170 tt.token_trees[0].clone()
174 db: &dyn AstDatabase,
177 ) -> Result<tt::Subtree, mbe::ExpandError> {
178 let krate = find_builtin_crate(db, id);
179 expand_simple_derive(tt, quote! { #krate::marker::Copy })
183 db: &dyn AstDatabase,
186 ) -> Result<tt::Subtree, mbe::ExpandError> {
187 let krate = find_builtin_crate(db, id);
188 expand_simple_derive(tt, quote! { #krate::clone::Clone })
192 db: &dyn AstDatabase,
195 ) -> Result<tt::Subtree, mbe::ExpandError> {
196 let krate = find_builtin_crate(db, id);
197 expand_simple_derive(tt, quote! { #krate::default::Default })
201 db: &dyn AstDatabase,
204 ) -> Result<tt::Subtree, mbe::ExpandError> {
205 let krate = find_builtin_crate(db, id);
206 expand_simple_derive(tt, quote! { #krate::fmt::Debug })
210 db: &dyn AstDatabase,
213 ) -> Result<tt::Subtree, mbe::ExpandError> {
214 let krate = find_builtin_crate(db, id);
215 expand_simple_derive(tt, quote! { #krate::hash::Hash })
219 db: &dyn AstDatabase,
222 ) -> Result<tt::Subtree, mbe::ExpandError> {
223 let krate = find_builtin_crate(db, id);
224 expand_simple_derive(tt, quote! { #krate::cmp::Eq })
227 fn partial_eq_expand(
228 db: &dyn AstDatabase,
231 ) -> Result<tt::Subtree, mbe::ExpandError> {
232 let krate = find_builtin_crate(db, id);
233 expand_simple_derive(tt, quote! { #krate::cmp::PartialEq })
237 db: &dyn AstDatabase,
240 ) -> Result<tt::Subtree, mbe::ExpandError> {
241 let krate = find_builtin_crate(db, id);
242 expand_simple_derive(tt, quote! { #krate::cmp::Ord })
245 fn partial_ord_expand(
246 db: &dyn AstDatabase,
249 ) -> Result<tt::Subtree, mbe::ExpandError> {
250 let krate = find_builtin_crate(db, id);
251 expand_simple_derive(tt, quote! { #krate::cmp::PartialOrd })
256 use name::{known, Name};
257 use ra_db::{fixture::WithFixture, CrateId, SourceDatabase};
259 use crate::{test_db::TestDB, AstId, MacroCallId, MacroCallKind, MacroCallLoc};
263 fn expand_builtin_derive(s: &str, name: Name) -> String {
264 let def = find_builtin_derive(&name).unwrap();
265 let fixture = format!(
266 r#"//- /main.rs crate:main deps:core
269 //- /lib.rs crate:core
275 let (db, file_pos) = TestDB::with_position(&fixture);
276 let file_id = file_pos.file_id;
277 let parsed = db.parse(file_id);
279 parsed.syntax_node().descendants().filter_map(ast::Item::cast).collect();
281 let ast_id_map = db.ast_id_map(file_id.into());
283 let attr_id = AstId::new(file_id.into(), ast_id_map.ast_id(&items[0]));
285 let loc = MacroCallLoc {
288 kind: MacroCallKind::Attr(attr_id, name.to_string()),
291 let id: MacroCallId = db.intern_macro(loc).into();
292 let parsed = db.parse_or_expand(id.as_file()).unwrap();
294 // FIXME text() for syntax nodes parsed from token tree looks weird
295 // because there's no whitespace, see below
296 parsed.text().to_string()
300 fn test_copy_expand_simple() {
301 let expanded = expand_builtin_derive(
309 assert_eq!(expanded, "impl< >core::marker::CopyforFoo< >{}");
313 fn test_copy_expand_with_type_params() {
314 let expanded = expand_builtin_derive(
324 "impl<T0:core::marker::Copy,T1:core::marker::Copy>core::marker::CopyforFoo<T0,T1>{}"
329 fn test_copy_expand_with_lifetimes() {
330 let expanded = expand_builtin_derive(
333 struct Foo<A, B, 'a, 'b>;
338 // We currently just ignore lifetimes
342 "impl<T0:core::marker::Copy,T1:core::marker::Copy>core::marker::CopyforFoo<T0,T1>{}"
347 fn test_clone_expand() {
348 let expanded = expand_builtin_derive(
358 "impl<T0:core::clone::Clone,T1:core::clone::Clone>core::clone::CloneforFoo<T0,T1>{}"