shank_idl/
idl_type_definition.rs1use std::convert::{TryFrom, TryInto};
2
3use anyhow::{Error, Result};
4use serde::{Deserialize, Serialize};
5use shank_macro_impl::{
6 custom_type::{CustomEnum, CustomStruct},
7 parsed_enum::ParsedEnum,
8 parsed_struct::ParsedStruct,
9};
10
11use crate::{idl_field::IdlField, idl_variant::IdlEnumVariant};
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
17#[serde(rename_all = "lowercase", tag = "kind")]
18pub enum IdlTypeDefinitionTy {
19 Struct { fields: Vec<IdlField> },
20 Enum { variants: Vec<IdlEnumVariant> },
21}
22
23impl TryFrom<ParsedStruct> for IdlTypeDefinitionTy {
24 type Error = Error;
25
26 fn try_from(strct: ParsedStruct) -> Result<Self> {
27 let fields = strct
28 .fields
29 .into_iter()
30 .map(IdlField::try_from)
31 .collect::<Result<Vec<IdlField>>>()?;
32
33 Ok(Self::Struct { fields })
34 }
35}
36
37impl TryFrom<ParsedEnum> for IdlTypeDefinitionTy {
38 type Error = Error;
39
40 fn try_from(enm: ParsedEnum) -> Result<Self> {
41 let variants = enm
42 .variants
43 .into_iter()
44 .map(IdlEnumVariant::try_from)
45 .collect::<Result<Vec<IdlEnumVariant>>>()?;
46
47 Ok(Self::Enum { variants })
48 }
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
55pub struct IdlTypeDefinition {
56 pub name: String,
57 #[serde(rename = "type")]
58 pub ty: IdlTypeDefinitionTy,
59}
60
61impl TryFrom<ParsedStruct> for IdlTypeDefinition {
62 type Error = Error;
63
64 fn try_from(strct: ParsedStruct) -> Result<Self> {
65 let name = strct.ident.to_string();
66 let ty: IdlTypeDefinitionTy = strct.try_into()?;
67 Ok(Self { ty, name })
68 }
69}
70
71impl TryFrom<CustomStruct> for IdlTypeDefinition {
72 type Error = Error;
73
74 fn try_from(strct: CustomStruct) -> Result<Self> {
75 let name = strct.ident.to_string();
76 let ty: IdlTypeDefinitionTy = strct.0.try_into()?;
77 Ok(Self { ty, name })
78 }
79}
80
81impl TryFrom<CustomEnum> for IdlTypeDefinition {
82 type Error = Error;
83
84 fn try_from(enm: CustomEnum) -> Result<Self> {
85 let name = enm.ident.to_string();
86 let ty: IdlTypeDefinitionTy = enm.0.try_into()?;
87 Ok(Self { ty, name })
88 }
89}