codama_attributes/codama_directives/
account_directive.rs1use crate::{
2 utils::{FromMeta, SetOnce},
3 Attribute, AttributeContext, CodamaAttribute, CodamaDirective, Resolvable,
4};
5use codama_errors::{CodamaError, CodamaResult};
6use codama_nodes::{
7 CamelCaseString, Docs, InstructionAccountNode, InstructionInputValueNode, IsSigner,
8};
9use codama_syn_helpers::{extensions::*, Meta};
10
11#[derive(Debug, PartialEq)]
12pub struct AccountDirective {
13 pub name: CamelCaseString,
14 pub is_writable: bool,
15 pub is_signer: IsSigner,
16 pub is_optional: bool,
17 pub docs: Docs,
18 pub default_value: Option<Resolvable<InstructionInputValueNode>>,
19}
20
21impl AccountDirective {
22 pub fn parse(meta: &Meta, ctx: &AttributeContext) -> syn::Result<Self> {
23 meta.assert_directive("account")?;
24 let mut name = SetOnce::<CamelCaseString>::new("name");
25 if let AttributeContext::Field(syn::Field {
26 ident: Some(ident), ..
27 }) = ctx
28 {
29 name = name.initial_value(ident.to_string().into())
30 }
31 let mut is_writable = SetOnce::<bool>::new("writable").initial_value(false);
32 let mut is_signer = SetOnce::<IsSigner>::new("signer").initial_value(false.into());
33 let mut is_optional = SetOnce::<bool>::new("optional").initial_value(false);
34 let mut default_value =
35 SetOnce::<Resolvable<InstructionInputValueNode>>::new("default_value");
36 let mut docs = SetOnce::<Docs>::new("docs");
37 match meta.is_path_or_empty_list() {
38 true => (),
39 false => meta
40 .as_path_list()?
41 .each(|ref meta| match meta.path_str().as_str() {
42 "name" => name.set(meta.as_value()?.as_expr()?.as_string()?.into(), meta),
43 "writable" => is_writable.set(bool::from_meta(meta)?, meta),
44 "signer" => is_signer.set(IsSigner::from_meta(meta)?, meta),
45 "optional" => is_optional.set(bool::from_meta(meta)?, meta),
46 "default_value" => default_value.set(
47 Resolvable::<InstructionInputValueNode>::from_meta(meta.as_value()?)?,
48 meta,
49 ),
50 "docs" => docs.set(Docs::from_meta(meta)?, meta),
51 _ => Err(meta.error("unrecognized attribute")),
52 })?,
53 }
54 Ok(AccountDirective {
55 name: name.take(meta)?,
56 is_writable: is_writable.take(meta)?,
57 is_signer: is_signer.take(meta)?,
58 is_optional: is_optional.take(meta)?,
59 docs: docs.option().unwrap_or_default(),
60 default_value: default_value.option(),
61 })
62 }
63
64 pub fn to_instruction_account_node(&self) -> CodamaResult<InstructionAccountNode> {
67 Ok(InstructionAccountNode {
68 name: self.name.clone(),
69 is_writable: self.is_writable,
70 is_signer: self.is_signer,
71 is_optional: if self.is_optional { Some(true) } else { None },
72 docs: self.docs.clone(),
73 default_value: Box::new(
74 self.default_value
75 .as_ref()
76 .map(|r| r.try_resolved().cloned())
77 .transpose()?,
78 ),
79 })
80 }
81}
82
83impl<'a> TryFrom<&'a CodamaAttribute<'a>> for &'a AccountDirective {
84 type Error = CodamaError;
85
86 fn try_from(attribute: &'a CodamaAttribute) -> Result<Self, Self::Error> {
87 match attribute.directive.as_ref() {
88 CodamaDirective::Account(ref a) => Ok(a),
89 _ => Err(CodamaError::InvalidCodamaDirective {
90 expected: "account".to_string(),
91 actual: attribute.directive.name().to_string(),
92 }),
93 }
94 }
95}
96
97impl<'a> TryFrom<&'a Attribute<'a>> for &'a AccountDirective {
98 type Error = CodamaError;
99
100 fn try_from(attribute: &'a Attribute) -> Result<Self, Self::Error> {
101 <&CodamaAttribute>::try_from(attribute)?.try_into()
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108 use codama_nodes::PayerValueNode;
109
110 #[test]
111 fn fully_set() {
112 let meta: Meta = syn::parse_quote! { account(name = "payer", writable, signer, optional, default_value = payer) };
113 let item = syn::parse_quote! { struct Foo; };
114 let ctx = AttributeContext::Item(&item);
115 let directive = AccountDirective::parse(&meta, &ctx).unwrap();
116 assert_eq!(
117 directive,
118 AccountDirective {
119 name: "payer".into(),
120 is_writable: true,
121 is_signer: IsSigner::True,
122 is_optional: true,
123 default_value: Some(Resolvable::Resolved(PayerValueNode::new().into())),
124 docs: Docs::default(),
125 }
126 );
127 }
128
129 #[test]
130 fn fully_set_with_explicit_values() {
131 let meta: Meta = syn::parse_quote! { account(
132 name = "payer",
133 writable = true,
134 signer = "either",
135 optional = false,
136 default_value = payer
137 ) };
138 let item = syn::parse_quote! { struct Foo; };
139 let ctx = AttributeContext::Item(&item);
140 let directive = AccountDirective::parse(&meta, &ctx).unwrap();
141 assert_eq!(
142 directive,
143 AccountDirective {
144 name: "payer".into(),
145 is_writable: true,
146 is_signer: IsSigner::Either,
147 is_optional: false,
148 default_value: Some(Resolvable::Resolved(PayerValueNode::new().into())),
149 docs: Docs::default(),
150 }
151 );
152 }
153
154 #[test]
155 fn empty_on_named_field() {
156 let meta: Meta = syn::parse_quote! { account };
157 let field = syn::parse_quote! { authority: AccountMeta };
158 let ctx = AttributeContext::Field(&field);
159 let directive = AccountDirective::parse(&meta, &ctx).unwrap();
160 assert_eq!(
161 directive,
162 AccountDirective {
163 name: "authority".into(),
164 is_writable: false,
165 is_signer: IsSigner::False,
166 is_optional: false,
167 default_value: None,
168 docs: Docs::default(),
169 }
170 );
171 }
172
173 #[test]
174 fn empty_on_struct() {
175 let meta: Meta = syn::parse_quote! { account };
176 let item = syn::parse_quote! { struct Foo; };
177 let ctx = AttributeContext::Item(&item);
178 let error = AccountDirective::parse(&meta, &ctx).unwrap_err();
179 assert_eq!(error.to_string(), "name is missing");
180 }
181
182 #[test]
183 fn with_docs() {
184 let meta: Meta = syn::parse_quote! { account(name = "stake", writable, docs = "what this account is for") };
185 let item = syn::parse_quote! { struct Foo; };
186 let ctx = AttributeContext::Item(&item);
187 let directive = AccountDirective::parse(&meta, &ctx).unwrap();
188 assert_eq!(
189 directive,
190 AccountDirective {
191 name: "stake".into(),
192 is_writable: true,
193 is_signer: IsSigner::False,
194 is_optional: false,
195 default_value: None,
196 docs: vec!["what this account is for".to_string()].into(),
197 }
198 );
199 }
200
201 #[test]
202 fn with_docs_array() {
203 let meta: Meta = syn::parse_quote! { account(name = "authority", signer, docs = ["Line 1", "Line 2", "Line 3"]) };
204 let item = syn::parse_quote! { struct Foo; };
205 let ctx = AttributeContext::Item(&item);
206 let directive = AccountDirective::parse(&meta, &ctx).unwrap();
207 assert_eq!(
208 directive,
209 AccountDirective {
210 name: "authority".into(),
211 is_writable: false,
212 is_signer: IsSigner::True,
213 is_optional: false,
214 default_value: None,
215 docs: vec![
216 "Line 1".to_string(),
217 "Line 2".to_string(),
218 "Line 3".to_string()
219 ]
220 .into(),
221 }
222 );
223 }
224}