ty_ext.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. use crate::ASTResult;
  2. use syn::{self, AngleBracketedGenericArguments, PathSegment};
  3. #[derive(Eq, PartialEq, Debug)]
  4. pub enum PrimitiveTy {
  5. Map(MapInfo),
  6. Vec,
  7. Opt,
  8. Other,
  9. }
  10. #[derive(Debug)]
  11. pub struct TyInfo<'a> {
  12. pub ident: &'a syn::Ident,
  13. pub ty: &'a syn::Type,
  14. pub primitive_ty: PrimitiveTy,
  15. pub bracket_ty_info: Box<Option<TyInfo<'a>>>,
  16. }
  17. #[derive(Debug, Eq, PartialEq)]
  18. pub struct MapInfo {
  19. pub key: String,
  20. pub value: String,
  21. }
  22. impl MapInfo {
  23. fn new(key: String, value: String) -> Self {
  24. MapInfo { key, value }
  25. }
  26. }
  27. impl<'a> TyInfo<'a> {
  28. #[allow(dead_code)]
  29. pub fn bracketed_ident(&'a self) -> &'a syn::Ident {
  30. match self.bracket_ty_info.as_ref() {
  31. Some(b_ty) => b_ty.ident,
  32. None => {
  33. panic!()
  34. }
  35. }
  36. }
  37. }
  38. pub fn parse_ty<'a>(ast_result: &ASTResult, ty: &'a syn::Type) -> Result<Option<TyInfo<'a>>, String> {
  39. // Type -> TypePath -> Path -> PathSegment -> PathArguments ->
  40. // AngleBracketedGenericArguments -> GenericArgument -> Type.
  41. if let syn::Type::Path(ref p) = ty {
  42. if p.path.segments.len() != 1 {
  43. return Ok(None);
  44. }
  45. let seg = match p.path.segments.last() {
  46. Some(seg) => seg,
  47. None => return Ok(None),
  48. };
  49. let _is_option = seg.ident == "Option";
  50. return if let syn::PathArguments::AngleBracketed(ref bracketed) = seg.arguments {
  51. match seg.ident.to_string().as_ref() {
  52. "HashMap" => generate_hashmap_ty_info(ast_result, ty, seg, bracketed),
  53. "Vec" => generate_vec_ty_info(ast_result, seg, bracketed),
  54. "Option" => generate_option_ty_info(ast_result, ty, seg, bracketed),
  55. _ => {
  56. let msg = format!("Unsupported type: {}", seg.ident);
  57. ast_result.error_spanned_by(&seg.ident, &msg);
  58. return Err(msg);
  59. }
  60. }
  61. } else {
  62. return Ok(Some(TyInfo {
  63. ident: &seg.ident,
  64. ty,
  65. primitive_ty: PrimitiveTy::Other,
  66. bracket_ty_info: Box::new(None),
  67. }));
  68. };
  69. }
  70. Err("Unsupported inner type, get inner type fail".to_string())
  71. }
  72. fn parse_bracketed(bracketed: &AngleBracketedGenericArguments) -> Vec<&syn::Type> {
  73. bracketed
  74. .args
  75. .iter()
  76. .flat_map(|arg| {
  77. if let syn::GenericArgument::Type(ref ty_in_bracket) = arg {
  78. Some(ty_in_bracket)
  79. } else {
  80. None
  81. }
  82. })
  83. .collect::<Vec<&syn::Type>>()
  84. }
  85. pub fn generate_hashmap_ty_info<'a>(
  86. ast_result: &ASTResult,
  87. ty: &'a syn::Type,
  88. path_segment: &'a PathSegment,
  89. bracketed: &'a AngleBracketedGenericArguments,
  90. ) -> Result<Option<TyInfo<'a>>, String> {
  91. // The args of map must greater than 2
  92. if bracketed.args.len() != 2 {
  93. return Ok(None);
  94. }
  95. let types = parse_bracketed(bracketed);
  96. let key = parse_ty(ast_result, types[0])?.unwrap().ident.to_string();
  97. let value = parse_ty(ast_result, types[1])?.unwrap().ident.to_string();
  98. let bracket_ty_info = Box::new(parse_ty(ast_result, types[1])?);
  99. Ok(Some(TyInfo {
  100. ident: &path_segment.ident,
  101. ty,
  102. primitive_ty: PrimitiveTy::Map(MapInfo::new(key, value)),
  103. bracket_ty_info,
  104. }))
  105. }
  106. fn generate_option_ty_info<'a>(
  107. ast_result: &ASTResult,
  108. ty: &'a syn::Type,
  109. path_segment: &'a PathSegment,
  110. bracketed: &'a AngleBracketedGenericArguments,
  111. ) -> Result<Option<TyInfo<'a>>, String> {
  112. assert_eq!(path_segment.ident.to_string(), "Option".to_string());
  113. let types = parse_bracketed(bracketed);
  114. let bracket_ty_info = Box::new(parse_ty(ast_result, types[0])?);
  115. Ok(Some(TyInfo {
  116. ident: &path_segment.ident,
  117. ty,
  118. primitive_ty: PrimitiveTy::Opt,
  119. bracket_ty_info,
  120. }))
  121. }
  122. fn generate_vec_ty_info<'a>(
  123. ast_result: &ASTResult,
  124. path_segment: &'a PathSegment,
  125. bracketed: &'a AngleBracketedGenericArguments,
  126. ) -> Result<Option<TyInfo<'a>>, String> {
  127. if bracketed.args.len() != 1 {
  128. return Ok(None);
  129. }
  130. if let syn::GenericArgument::Type(ref bracketed_type) = bracketed.args.first().unwrap() {
  131. let bracketed_ty_info = Box::new(parse_ty(ast_result, bracketed_type)?);
  132. return Ok(Some(TyInfo {
  133. ident: &path_segment.ident,
  134. ty: bracketed_type,
  135. primitive_ty: PrimitiveTy::Vec,
  136. bracket_ty_info: bracketed_ty_info,
  137. }));
  138. }
  139. Ok(None)
  140. }