codama_attributes/codama_directives/
default_value_directive.rs1use crate::{utils::FromMeta, Attribute, CodamaAttribute, CodamaDirective};
2use codama_errors::CodamaError;
3use codama_nodes::InstructionInputValueNode;
4use codama_syn_helpers::Meta;
5
6#[derive(Debug, PartialEq)]
7pub struct DefaultValueDirective {
8 pub node: InstructionInputValueNode,
9}
10
11impl DefaultValueDirective {
12 pub fn parse(meta: &Meta) -> syn::Result<Self> {
13 let pv = meta.assert_directive("default_value")?.as_path_value()?;
14 let node = InstructionInputValueNode::from_meta(&pv.value)?;
15 Ok(Self { node })
16 }
17}
18
19impl<'a> TryFrom<&'a CodamaAttribute<'a>> for &'a DefaultValueDirective {
20 type Error = CodamaError;
21
22 fn try_from(attribute: &'a CodamaAttribute) -> Result<Self, Self::Error> {
23 match attribute.directive {
24 CodamaDirective::DefaultValue(ref a) => Ok(a),
25 _ => Err(CodamaError::InvalidCodamaDirective {
26 expected: "default_value".to_string(),
27 actual: attribute.directive.name().to_string(),
28 }),
29 }
30 }
31}
32
33impl<'a> TryFrom<&'a Attribute<'a>> for &'a DefaultValueDirective {
34 type Error = CodamaError;
35
36 fn try_from(attribute: &'a Attribute) -> Result<Self, Self::Error> {
37 <&CodamaAttribute>::try_from(attribute)?.try_into()
38 }
39}
40
41#[cfg(test)]
42mod tests {
43 use super::*;
44 use codama_nodes::BooleanValueNode;
45 use syn::parse_quote;
46
47 #[test]
48 fn ok() {
49 let meta: Meta = parse_quote! { default_value = true };
50 let node = DefaultValueDirective::parse(&meta).unwrap().node;
51
52 assert_eq!(node, BooleanValueNode::new(true).into());
53 }
54
55 #[test]
56 fn no_input() {
57 let meta: Meta = parse_quote! { default_value = };
58 let error = DefaultValueDirective::parse(&meta).unwrap_err();
59 assert_eq!(error.to_string(), "unrecognized value");
60 }
61
62 #[test]
63 fn multiple_inputs() {
64 let meta: Meta = parse_quote! { default_value = (true, false) };
65 let error = DefaultValueDirective::parse(&meta).unwrap_err();
66 assert_eq!(error.to_string(), "expected a single value, found a list");
67 }
68
69 #[test]
70 fn unrecognized_value() {
71 let meta: Meta = parse_quote! { default_value = banana };
72 let error = DefaultValueDirective::parse(&meta).unwrap_err();
73 assert_eq!(error.to_string(), "unrecognized value");
74 }
75}