entity.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. use convert_case::{Case, Casing};
  2. use quote::{format_ident, quote};
  3. fn extract_doc_comment(attrs: &[syn::Attribute]) -> proc_macro2::TokenStream {
  4. attrs
  5. .iter()
  6. .flat_map(|a| match a.parse_meta() {
  7. Ok(syn::Meta::NameValue(mnv)) => {
  8. if mnv.path.is_ident("doc") {
  9. if let syn::Lit::Str(ls) = mnv.lit {
  10. let lsv = ls.value();
  11. return Some(quote! { Some(#lsv) });
  12. }
  13. }
  14. None
  15. }
  16. _ => None,
  17. })
  18. .next()
  19. .unwrap_or(quote! { None })
  20. }
  21. fn is_elided(attrs: &[syn::Attribute]) -> bool {
  22. attrs.iter().filter(|a| a.path.is_ident("elide")).count() > 0
  23. }
  24. fn is_unique(attrs: &[syn::Attribute]) -> bool {
  25. attrs.iter().filter(|a| a.path.is_ident("unique")).count() > 0
  26. }
  27. fn is_key(attrs: &[syn::Attribute]) -> bool {
  28. attrs.iter().filter(|a| a.path.is_ident("key")).count() > 0
  29. }
  30. pub fn derive(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
  31. let input: syn::DeriveInput = syn::parse_macro_input!(tokens);
  32. let parts = match input.data {
  33. syn::Data::Struct(syn::DataStruct {
  34. struct_token: _,
  35. fields: syn::Fields::Named(fields),
  36. semi_token: _,
  37. }) => fields
  38. .named
  39. .into_iter()
  40. .map(|f| (f.ident.unwrap(), f.ty, f.attrs))
  41. .collect::<Vec<_>>(),
  42. _ => panic!("Can only derive Entity on data structs with named fields!"),
  43. };
  44. let entity_ident = input.ident;
  45. let make_combined_name = |part: &(syn::Ident, syn::Type, _)| {
  46. format_ident!(
  47. "{}{}PartType",
  48. entity_ident,
  49. part.0.to_string().to_case(Case::UpperCamel)
  50. )
  51. };
  52. let make_part_list = |plist: &Vec<_>| match plist.len() {
  53. 0 => quote! { microrm::schema::entity::EmptyList<Self> },
  54. 1 => {
  55. let ty = make_combined_name(plist.first().as_ref().unwrap());
  56. quote! { #ty }
  57. }
  58. _ => {
  59. let tys = plist.iter().map(make_combined_name);
  60. quote! { ( #(#tys),* ) }
  61. }
  62. };
  63. let vis = input.vis;
  64. // collect list of unique parts
  65. let key_parts = parts
  66. .iter()
  67. .filter(|part| is_key(&part.2))
  68. .cloned()
  69. .collect::<Vec<_>>();
  70. let part_defs = parts.iter().map(|part| {
  71. let part_combined_name = make_combined_name(part);
  72. let part_base_ident = &part.0;
  73. let part_base_name = &part.0.to_string();
  74. let part_type = &part.1;
  75. let placeholder = format!("${}_{}", entity_ident, part_base_name);
  76. let unique = is_unique(&part.2);
  77. let doc = extract_doc_comment(&part.2);
  78. quote! {
  79. #[derive(Clone, Copy, Default)]
  80. #vis struct #part_combined_name;
  81. impl ::microrm::schema::entity::EntityPart for #part_combined_name {
  82. type Datum = #part_type;
  83. type Entity = #entity_ident;
  84. fn part_name() -> &'static str {
  85. #part_base_name
  86. }
  87. fn placeholder() -> &'static str {
  88. #placeholder
  89. }
  90. fn unique() -> bool {
  91. #unique
  92. }
  93. fn desc() -> Option<&'static str> {
  94. #doc
  95. }
  96. fn get_datum(from: &Self::Entity) -> &Self::Datum {
  97. &from.#part_base_ident
  98. }
  99. }
  100. }
  101. });
  102. let part_visit = parts.iter().map(|part| {
  103. let part_combined_name = make_combined_name(part);
  104. quote! {
  105. v.visit::<#part_combined_name>();
  106. }
  107. });
  108. let part_ref_visit = parts.iter().map(|part| {
  109. let part_combined_name = make_combined_name(part);
  110. let field = &part.0;
  111. quote! {
  112. v.visit_datum::<#part_combined_name>(&self.#field);
  113. }
  114. });
  115. let part_mut_visit = parts.iter().map(|part| {
  116. let part_combined_name = make_combined_name(part);
  117. let field = &part.0;
  118. quote! {
  119. v.visit_datum_mut::<#part_combined_name>(&mut self.#field);
  120. }
  121. });
  122. let part_names = parts.iter().map(|part| {
  123. let part_combined_name = make_combined_name(part);
  124. let part_camel_name = format_ident!("{}", part.0.to_string().to_case(Case::UpperCamel));
  125. quote! {
  126. pub const #part_camel_name : #part_combined_name = #part_combined_name;
  127. }
  128. });
  129. let build_struct = parts
  130. .iter()
  131. .enumerate()
  132. .map(|(i, part)| {
  133. let ident = &part.0;
  134. match parts.len() {
  135. 1 => {
  136. quote! {
  137. #ident: values
  138. }
  139. }
  140. _ => {
  141. let idx = syn::Index::from(i);
  142. quote! {
  143. #ident: values. #idx
  144. }
  145. }
  146. }
  147. })
  148. .collect::<Vec<_>>();
  149. let debug_fields = parts
  150. .iter()
  151. .filter(|part| !is_elided(&part.2))
  152. .map(|part| {
  153. let ident = &part.0;
  154. let field = ident.to_string();
  155. quote! {
  156. self . #ident . debug_field(#field, &mut ds);
  157. }
  158. })
  159. .collect::<Vec<_>>();
  160. let parts_list = make_part_list(&parts);
  161. let key_list = make_part_list(&key_parts);
  162. let entity_ident_str = entity_ident.to_string();
  163. let entity_name = entity_ident.to_string().to_case(Case::Snake);
  164. let id_ident = format_ident!("{}ID", entity_ident);
  165. quote! {
  166. #(#part_defs)*
  167. impl #entity_ident {
  168. #(#part_names)*
  169. }
  170. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
  171. #vis struct #id_ident (i64);
  172. impl ::microrm::schema::entity::EntityID for #id_ident {
  173. type Entity = #entity_ident;
  174. fn from_raw(raw: i64) -> Self { Self(raw) }
  175. fn into_raw(self) -> i64 { self.0 }
  176. }
  177. impl ::microrm::schema::entity::EntityPart for #id_ident {
  178. type Datum = Self;
  179. type Entity = #entity_ident;
  180. fn unique() -> bool { false }
  181. fn part_name() -> &'static str { "id" }
  182. fn placeholder() -> &'static str { "TODO" }
  183. fn desc() -> Option<&'static str> { None }
  184. fn get_datum(from: &Self::Entity) -> &Self::Datum {
  185. unreachable!()
  186. }
  187. }
  188. impl ::microrm::schema::datum::Datum for #id_ident {
  189. fn sql_type() -> &'static str {
  190. <i64 as ::microrm::schema::datum::Datum>::sql_type()
  191. }
  192. fn bind_to<'a>(&self, stmt: &mut ::microrm::db::StatementContext, index: i32) {
  193. <i64 as ::microrm::schema::datum::Datum>::bind_to(&self.0, stmt, index)
  194. }
  195. fn build_from<'a>(
  196. adata: ::microrm::schema::AssocData,
  197. stmt: &mut ::microrm::db::StatementRow,
  198. index: &mut i32,
  199. ) -> ::microrm::DBResult<Self>
  200. where
  201. Self: Sized,
  202. {
  203. Ok(Self(<i64 as ::microrm::schema::datum::Datum>::build_from(adata, stmt, index)?))
  204. }
  205. fn accept_discriminator(d: &mut impl ::microrm::schema::datum::DatumDiscriminator) where Self: Sized {
  206. d.visit_entity_id::<#entity_ident>();
  207. }
  208. fn accept_discriminator_ref(&self, d: &mut impl ::microrm::schema::datum::DatumDiscriminatorRef) where Self: Sized {
  209. d.visit_entity_id::<#entity_ident>(self);
  210. }
  211. }
  212. impl ::microrm::schema::datum::ConcreteDatum for #id_ident {}
  213. impl ::std::fmt::Debug for #entity_ident {
  214. fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> {
  215. use ::microrm::schema::datum::Datum;
  216. let mut ds = f.debug_struct(#entity_ident_str);
  217. #(#debug_fields)*
  218. ds.finish()
  219. }
  220. }
  221. impl ::microrm::schema::entity::Entity for #entity_ident {
  222. type Parts = #parts_list;
  223. type Keys = #key_list;
  224. type ID = #id_ident;
  225. fn build(values: <Self::Parts as ::microrm::schema::entity::EntityPartList>::DatumList) -> Self {
  226. Self {
  227. #(#build_struct),*
  228. }
  229. }
  230. fn entity_name() -> &'static str { #entity_name }
  231. fn accept_part_visitor(v: &mut impl ::microrm::schema::entity::EntityPartVisitor) {
  232. #(
  233. #part_visit
  234. );*
  235. }
  236. fn accept_part_visitor_ref(&self, v: &mut impl ::microrm::schema::entity::EntityPartVisitor) {
  237. #(
  238. #part_ref_visit
  239. );*
  240. }
  241. fn accept_part_visitor_mut(&mut self, v: &mut impl ::microrm::schema::entity::EntityPartVisitor) {
  242. #(
  243. #part_mut_visit
  244. );*
  245. }
  246. }
  247. }
  248. .into()
  249. }