attr.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. #![allow(clippy::all)]
  2. use crate::{symbol::*, Ctxt};
  3. use quote::ToTokens;
  4. use syn::{
  5. self,
  6. parse::{self, Parse},
  7. Meta::{List, NameValue, Path},
  8. NestedMeta::{Lit, Meta},
  9. };
  10. use proc_macro2::{Group, Span, TokenStream, TokenTree};
  11. #[allow(dead_code)]
  12. pub struct AttrsContainer {
  13. name: String,
  14. pb_struct_type: Option<syn::Type>,
  15. pb_enum_type: Option<syn::Type>,
  16. }
  17. impl AttrsContainer {
  18. /// Extract out the `#[pb(...)]` attributes from an item.
  19. pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self {
  20. let mut pb_struct_type = ASTAttr::none(cx, PB_STRUCT);
  21. let mut pb_enum_type = ASTAttr::none(cx, PB_ENUM);
  22. for meta_item in item.attrs.iter().flat_map(|attr| get_meta_items(cx, attr)).flatten() {
  23. match &meta_item {
  24. // Parse `#[pb(struct = "Type")]
  25. Meta(NameValue(m)) if m.path == PB_STRUCT => {
  26. if let Ok(into_ty) = parse_lit_into_ty(cx, PB_STRUCT, &m.lit) {
  27. pb_struct_type.set_opt(&m.path, Some(into_ty));
  28. }
  29. },
  30. // Parse `#[pb(enum = "Type")]
  31. Meta(NameValue(m)) if m.path == PB_ENUM => {
  32. if let Ok(into_ty) = parse_lit_into_ty(cx, PB_ENUM, &m.lit) {
  33. pb_enum_type.set_opt(&m.path, Some(into_ty));
  34. }
  35. },
  36. Meta(meta_item) => {
  37. let path = meta_item.path().into_token_stream().to_string().replace(' ', "");
  38. cx.error_spanned_by(meta_item.path(), format!("unknown pb container attribute `{}`", path));
  39. },
  40. Lit(lit) => {
  41. cx.error_spanned_by(lit, "unexpected literal in pb container attribute");
  42. },
  43. }
  44. }
  45. match &item.data {
  46. syn::Data::Struct(_) => {
  47. pb_struct_type.set_if_none(default_pb_type(&cx, &item.ident));
  48. },
  49. syn::Data::Enum(_) => {
  50. pb_enum_type.set_if_none(default_pb_type(&cx, &item.ident));
  51. },
  52. _ => {},
  53. }
  54. AttrsContainer {
  55. name: item.ident.to_string(),
  56. pb_struct_type: pb_struct_type.get(),
  57. pb_enum_type: pb_enum_type.get(),
  58. }
  59. }
  60. pub fn pb_struct_type(&self) -> Option<&syn::Type> { self.pb_struct_type.as_ref() }
  61. pub fn pb_enum_type(&self) -> Option<&syn::Type> { self.pb_enum_type.as_ref() }
  62. }
  63. struct ASTAttr<'c, T> {
  64. cx: &'c Ctxt,
  65. name: Symbol,
  66. tokens: TokenStream,
  67. value: Option<T>,
  68. }
  69. impl<'c, T> ASTAttr<'c, T> {
  70. fn none(cx: &'c Ctxt, name: Symbol) -> Self {
  71. ASTAttr {
  72. cx,
  73. name,
  74. tokens: TokenStream::new(),
  75. value: None,
  76. }
  77. }
  78. fn set<A: ToTokens>(&mut self, obj: A, value: T) {
  79. let tokens = obj.into_token_stream();
  80. if self.value.is_some() {
  81. self.cx
  82. .error_spanned_by(tokens, format!("duplicate attribute `{}`", self.name));
  83. } else {
  84. self.tokens = tokens;
  85. self.value = Some(value);
  86. }
  87. }
  88. fn set_opt<A: ToTokens>(&mut self, obj: A, value: Option<T>) {
  89. if let Some(value) = value {
  90. self.set(obj, value);
  91. }
  92. }
  93. fn set_if_none(&mut self, value: T) {
  94. if self.value.is_none() {
  95. self.value = Some(value);
  96. }
  97. }
  98. fn get(self) -> Option<T> { self.value }
  99. #[allow(dead_code)]
  100. fn get_with_tokens(self) -> Option<(TokenStream, T)> {
  101. match self.value {
  102. Some(v) => Some((self.tokens, v)),
  103. None => None,
  104. }
  105. }
  106. }
  107. pub struct ASTAttrField {
  108. #[allow(dead_code)]
  109. name: String,
  110. pb_index: Option<syn::LitInt>,
  111. pb_one_of: bool,
  112. skip_serializing: bool,
  113. skip_deserializing: bool,
  114. serialize_with: Option<syn::ExprPath>,
  115. deserialize_with: Option<syn::ExprPath>,
  116. }
  117. impl ASTAttrField {
  118. /// Extract out the `#[pb(...)]` attributes from a struct field.
  119. pub fn from_ast(cx: &Ctxt, index: usize, field: &syn::Field) -> Self {
  120. let mut pb_index = ASTAttr::none(cx, PB_INDEX);
  121. let mut pb_one_of = BoolAttr::none(cx, PB_ONE_OF);
  122. let mut serialize_with = ASTAttr::none(cx, SERIALIZE_WITH);
  123. let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING);
  124. let mut deserialize_with = ASTAttr::none(cx, DESERIALIZE_WITH);
  125. let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING);
  126. let ident = match &field.ident {
  127. Some(ident) => ident.to_string(),
  128. None => index.to_string(),
  129. };
  130. for meta_item in field.attrs.iter().flat_map(|attr| get_meta_items(cx, attr)).flatten() {
  131. match &meta_item {
  132. // Parse `#[pb(skip)]`
  133. Meta(Path(word)) if word == SKIP => {
  134. skip_serializing.set_true(word);
  135. skip_deserializing.set_true(word);
  136. },
  137. // Parse '#[pb(index = x)]'
  138. Meta(NameValue(m)) if m.path == PB_INDEX => {
  139. if let syn::Lit::Int(lit) = &m.lit {
  140. pb_index.set(&m.path, lit.clone());
  141. }
  142. },
  143. // Parse `#[pb(one_of)]`
  144. Meta(Path(path)) if path == PB_ONE_OF => {
  145. pb_one_of.set_true(path);
  146. },
  147. // Parse `#[pb(serialize_with = "...")]`
  148. Meta(NameValue(m)) if m.path == SERIALIZE_WITH => {
  149. if let Ok(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &m.lit) {
  150. serialize_with.set(&m.path, path);
  151. }
  152. },
  153. // Parse `#[pb(deserialize_with = "...")]`
  154. Meta(NameValue(m)) if m.path == DESERIALIZE_WITH => {
  155. if let Ok(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &m.lit) {
  156. deserialize_with.set(&m.path, path);
  157. }
  158. },
  159. Meta(meta_item) => {
  160. let path = meta_item.path().into_token_stream().to_string().replace(' ', "");
  161. cx.error_spanned_by(meta_item.path(), format!("unknown field attribute `{}`", path));
  162. },
  163. Lit(lit) => {
  164. cx.error_spanned_by(lit, "unexpected literal in pb field attribute");
  165. },
  166. }
  167. }
  168. ASTAttrField {
  169. name: ident,
  170. pb_index: pb_index.get(),
  171. pb_one_of: pb_one_of.get(),
  172. skip_serializing: skip_serializing.get(),
  173. skip_deserializing: skip_deserializing.get(),
  174. serialize_with: serialize_with.get(),
  175. deserialize_with: deserialize_with.get(),
  176. }
  177. }
  178. #[allow(dead_code)]
  179. pub fn pb_index(&self) -> Option<String> { self.pb_index.as_ref().map(|lit| lit.base10_digits().to_string()) }
  180. pub fn is_one_of(&self) -> bool { self.pb_one_of }
  181. pub fn serialize_with(&self) -> Option<&syn::ExprPath> { self.serialize_with.as_ref() }
  182. pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { self.deserialize_with.as_ref() }
  183. pub fn skip_serializing(&self) -> bool { self.skip_serializing }
  184. pub fn skip_deserializing(&self) -> bool { self.skip_deserializing }
  185. }
  186. pub enum Default {
  187. /// Field must always be specified because it does not have a default.
  188. None,
  189. /// The default is given by `std::default::Default::default()`.
  190. Default,
  191. /// The default is given by this function.
  192. Path(syn::ExprPath),
  193. }
  194. #[derive(Debug, Clone)]
  195. pub struct EventAttrs {
  196. input: Option<syn::Path>,
  197. output: Option<syn::Path>,
  198. error_ty: Option<String>,
  199. pub ignore: bool,
  200. }
  201. #[derive(Debug, Clone)]
  202. pub struct ASTEnumAttrVariant {
  203. pub enum_name: String,
  204. pub enum_item_name: String,
  205. pub value: String,
  206. pub event_attrs: EventAttrs,
  207. }
  208. impl ASTEnumAttrVariant {
  209. pub fn from_ast(ctxt: &Ctxt, ident: &syn::Ident, variant: &syn::Variant, enum_attrs: &[syn::Attribute]) -> Self {
  210. let enum_item_name = variant.ident.to_string();
  211. let enum_name = ident.to_string();
  212. let mut value = String::new();
  213. if variant.discriminant.is_some() {
  214. if let syn::Expr::Lit(ref expr_list) = variant.discriminant.as_ref().unwrap().1 {
  215. let lit_int = if let syn::Lit::Int(ref int_value) = expr_list.lit {
  216. int_value
  217. } else {
  218. unimplemented!()
  219. };
  220. value = lit_int.base10_digits().to_string();
  221. }
  222. }
  223. let event_attrs = get_event_attrs_from(ctxt, &variant.attrs, enum_attrs);
  224. ASTEnumAttrVariant {
  225. enum_name,
  226. enum_item_name,
  227. value,
  228. event_attrs,
  229. }
  230. }
  231. pub fn event_input(&self) -> Option<syn::Path> { self.event_attrs.input.clone() }
  232. pub fn event_output(&self) -> Option<syn::Path> { self.event_attrs.output.clone() }
  233. pub fn event_error(&self) -> String { self.event_attrs.error_ty.as_ref().unwrap().clone() }
  234. }
  235. fn get_event_attrs_from(ctxt: &Ctxt, variant_attrs: &[syn::Attribute], enum_attrs: &[syn::Attribute]) -> EventAttrs {
  236. let mut event_attrs = EventAttrs {
  237. input: None,
  238. output: None,
  239. error_ty: None,
  240. ignore: false,
  241. };
  242. enum_attrs
  243. .iter()
  244. .filter(|attr| attr.path.segments.iter().any(|s| s.ident == EVENT_ERR))
  245. .for_each(|attr| {
  246. if let Ok(NameValue(named_value)) = attr.parse_meta() {
  247. if let syn::Lit::Str(s) = named_value.lit {
  248. event_attrs.error_ty = Some(s.value());
  249. } else {
  250. eprintln!("❌ {} should not be empty", EVENT_ERR);
  251. }
  252. } else {
  253. eprintln!("❌ Can not find any {} on attr: {:#?}", EVENT_ERR, attr);
  254. }
  255. });
  256. let mut extract_event_attr = |attr: &syn::Attribute, meta_item: &syn::NestedMeta| match &meta_item {
  257. Meta(NameValue(name_value)) => {
  258. if name_value.path == EVENT_INPUT {
  259. if let syn::Lit::Str(s) = &name_value.lit {
  260. let input_type = parse_lit_str(s)
  261. .map_err(|_| {
  262. ctxt.error_spanned_by(s, format!("failed to parse request deserializer {:?}", s.value()))
  263. })
  264. .unwrap();
  265. event_attrs.input = Some(input_type);
  266. }
  267. }
  268. if name_value.path == EVENT_OUTPUT {
  269. if let syn::Lit::Str(s) = &name_value.lit {
  270. let output_type = parse_lit_str(s)
  271. .map_err(|_| {
  272. ctxt.error_spanned_by(s, format!("failed to parse response deserializer {:?}", s.value()))
  273. })
  274. .unwrap();
  275. event_attrs.output = Some(output_type);
  276. }
  277. }
  278. },
  279. Meta(Path(word)) => {
  280. if word == EVENT_IGNORE && attr.path == EVENT {
  281. event_attrs.ignore = true;
  282. }
  283. },
  284. Lit(s) => ctxt.error_spanned_by(s, "unexpected attribute"),
  285. _ => ctxt.error_spanned_by(meta_item, "unexpected attribute"),
  286. };
  287. let attr_meta_items_info = variant_attrs
  288. .iter()
  289. .flat_map(|attr| match get_meta_items(ctxt, attr) {
  290. Ok(items) => Some((attr, items)),
  291. Err(_) => None,
  292. })
  293. .collect::<Vec<(&syn::Attribute, Vec<syn::NestedMeta>)>>();
  294. for (attr, nested_metas) in attr_meta_items_info {
  295. nested_metas
  296. .iter()
  297. .for_each(|meta_item| extract_event_attr(attr, meta_item))
  298. }
  299. // eprintln!("😁{:#?}", event_attrs);
  300. event_attrs
  301. }
  302. pub fn get_meta_items(cx: &Ctxt, attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()> {
  303. if attr.path != PB_ATTRS && attr.path != EVENT {
  304. return Ok(vec![]);
  305. }
  306. // http://strymon.systems.ethz.ch/typename/syn/enum.Meta.html
  307. match attr.parse_meta() {
  308. Ok(List(meta)) => Ok(meta.nested.into_iter().collect()),
  309. Ok(other) => {
  310. cx.error_spanned_by(other, "expected #[pb(...)] or or #[event(...)]");
  311. Err(())
  312. },
  313. Err(err) => {
  314. cx.error_spanned_by(attr, "attribute must be str, e.g. #[pb(xx = \"xxx\")]");
  315. cx.syn_error(err);
  316. Err(())
  317. },
  318. }
  319. }
  320. fn parse_lit_into_expr_path(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::ExprPath, ()> {
  321. let string = get_lit_str(cx, attr_name, lit)?;
  322. parse_lit_str(string).map_err(|_| cx.error_spanned_by(lit, format!("failed to parse path: {:?}", string.value())))
  323. }
  324. fn get_lit_str<'a>(cx: &Ctxt, attr_name: Symbol, lit: &'a syn::Lit) -> Result<&'a syn::LitStr, ()> {
  325. if let syn::Lit::Str(lit) = lit {
  326. Ok(lit)
  327. } else {
  328. cx.error_spanned_by(
  329. lit,
  330. format!(
  331. "expected pb {} attribute to be a string: `{} = \"...\"`",
  332. attr_name, attr_name
  333. ),
  334. );
  335. Err(())
  336. }
  337. }
  338. fn parse_lit_into_ty(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::Type, ()> {
  339. let string = get_lit_str(cx, attr_name, lit)?;
  340. parse_lit_str(string).map_err(|_| {
  341. cx.error_spanned_by(
  342. lit,
  343. format!("failed to parse type: {} = {:?}", attr_name, string.value()),
  344. )
  345. })
  346. }
  347. pub fn parse_lit_str<T>(s: &syn::LitStr) -> parse::Result<T>
  348. where
  349. T: Parse,
  350. {
  351. let tokens = spanned_tokens(s)?;
  352. syn::parse2(tokens)
  353. }
  354. fn spanned_tokens(s: &syn::LitStr) -> parse::Result<TokenStream> {
  355. let stream = syn::parse_str(&s.value())?;
  356. Ok(respan_token_stream(stream, s.span()))
  357. }
  358. fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream {
  359. stream.into_iter().map(|token| respan_token_tree(token, span)).collect()
  360. }
  361. fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree {
  362. if let TokenTree::Group(g) = &mut token {
  363. *g = Group::new(g.delimiter(), respan_token_stream(g.stream(), span));
  364. }
  365. token.set_span(span);
  366. token
  367. }
  368. fn default_pb_type(ctxt: &Ctxt, ident: &syn::Ident) -> syn::Type {
  369. let take_ident = ident.to_string();
  370. let lit_str = syn::LitStr::new(&take_ident, ident.span());
  371. if let Ok(tokens) = spanned_tokens(&lit_str) {
  372. if let Ok(pb_struct_ty) = syn::parse2(tokens) {
  373. return pb_struct_ty;
  374. }
  375. }
  376. ctxt.error_spanned_by(ident, format!("❌ Can't find {} protobuf struct", take_ident));
  377. panic!()
  378. }
  379. #[allow(dead_code)]
  380. pub fn is_option(ty: &syn::Type) -> bool {
  381. let path = match ungroup(ty) {
  382. syn::Type::Path(ty) => &ty.path,
  383. _ => {
  384. return false;
  385. },
  386. };
  387. let seg = match path.segments.last() {
  388. Some(seg) => seg,
  389. None => {
  390. return false;
  391. },
  392. };
  393. let args = match &seg.arguments {
  394. syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args,
  395. _ => {
  396. return false;
  397. },
  398. };
  399. seg.ident == "Option" && args.len() == 1
  400. }
  401. #[allow(dead_code)]
  402. pub fn ungroup(mut ty: &syn::Type) -> &syn::Type {
  403. while let syn::Type::Group(group) = ty {
  404. ty = &group.elem;
  405. }
  406. ty
  407. }
  408. struct BoolAttr<'c>(ASTAttr<'c, ()>);
  409. impl<'c> BoolAttr<'c> {
  410. fn none(cx: &'c Ctxt, name: Symbol) -> Self { BoolAttr(ASTAttr::none(cx, name)) }
  411. fn set_true<A: ToTokens>(&mut self, obj: A) { self.0.set(obj, ()); }
  412. fn get(&self) -> bool { self.0.value.is_some() }
  413. }