error.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. use crate::{Error, ErrorArgs, ErrorCode};
  2. // Removes any internal #[msg] attributes, as they are inert.
  3. pub fn parse(error_enum: &mut syn::ItemEnum, args: Option<ErrorArgs>) -> Error {
  4. let ident = error_enum.ident.clone();
  5. let mut last_discriminant = 0;
  6. let codes: Vec<ErrorCode> = error_enum
  7. .variants
  8. .iter_mut()
  9. .map(|variant: &mut syn::Variant| {
  10. let msg = parse_error_attribute(variant);
  11. let ident = variant.ident.clone();
  12. let id = match &variant.discriminant {
  13. None => last_discriminant,
  14. Some((_, disc)) => match disc {
  15. syn::Expr::Lit(expr_lit) => match &expr_lit.lit {
  16. syn::Lit::Int(int) => {
  17. int.base10_parse::<u32>().expect("Must be a base 10 number")
  18. }
  19. _ => panic!("Invalid error discriminant"),
  20. },
  21. _ => panic!("Invalid error discriminant"),
  22. },
  23. };
  24. last_discriminant = id + 1;
  25. // Remove any attributes on the error variant.
  26. variant.attrs = vec![];
  27. ErrorCode { id, ident, msg }
  28. })
  29. .collect();
  30. Error {
  31. name: error_enum.ident.to_string(),
  32. raw_enum: error_enum.clone(),
  33. ident,
  34. codes,
  35. args,
  36. }
  37. }
  38. fn parse_error_attribute(variant: &syn::Variant) -> Option<String> {
  39. let attrs = &variant.attrs;
  40. match attrs.len() {
  41. 0 => None,
  42. 1 => {
  43. let attr = &attrs[0];
  44. let attr_str = attr.path.segments[0].ident.to_string();
  45. assert!(&attr_str == "msg", "Use msg to specify error strings");
  46. let mut tts = attr.tokens.clone().into_iter();
  47. let g_stream = match tts.next().expect("Must have a token group") {
  48. proc_macro2::TokenTree::Group(g) => g.stream(),
  49. _ => panic!("Invalid syntax"),
  50. };
  51. let msg = match g_stream.into_iter().next() {
  52. None => panic!("Must specify a message string"),
  53. Some(msg) => msg.to_string().replace('\"', ""),
  54. };
  55. Some(msg)
  56. }
  57. _ => {
  58. panic!("Too many attributes found. Use `msg` to specify error strings");
  59. }
  60. }
  61. }