codama_attributes/codama_directives/
codama_directive.rs

1use crate::{
2    AccountDirective, AttributeContext, DefaultValueDirective, EncodingDirective, ErrorDirective,
3    FixedSizeDirective, SizePrefixDirective, TypeDirective,
4};
5use codama_syn_helpers::{extensions::*, Meta};
6use derive_more::derive::From;
7
8#[derive(Debug, PartialEq, From)]
9pub enum CodamaDirective {
10    // Type directives.
11    Type(TypeDirective),
12    DefaultValue(DefaultValueDirective),
13    Encoding(EncodingDirective),
14    FixedSize(FixedSizeDirective),
15    SizePrefix(SizePrefixDirective),
16
17    // Instruction directives.
18    Account(AccountDirective),
19
20    // Error directives.
21    Error(ErrorDirective),
22}
23
24impl CodamaDirective {
25    pub fn parse(meta: &Meta, ctx: &AttributeContext) -> syn::Result<Self> {
26        let path = meta.path()?;
27        match path.to_string().as_str() {
28            // Type directives.
29            "type" => Ok(TypeDirective::parse(meta)?.into()),
30            "default_value" => Ok(DefaultValueDirective::parse(meta)?.into()),
31            "encoding" => Ok(EncodingDirective::parse(meta)?.into()),
32            "fixed_size" => Ok(FixedSizeDirective::parse(meta)?.into()),
33            "size_prefix" => Ok(SizePrefixDirective::parse(meta)?.into()),
34
35            // Instruction directives.
36            "account" => Ok(AccountDirective::parse(meta, ctx)?.into()),
37
38            // Error directives.
39            "error" => Ok(ErrorDirective::parse(meta)?.into()),
40
41            _ => Err(path.error("unrecognized codama directive")),
42        }
43    }
44
45    pub fn name(&self) -> &'static str {
46        match self {
47            // Type directives.
48            Self::Type(_) => "type",
49            Self::DefaultValue(_) => "default_value",
50            Self::Encoding(_) => "encoding",
51            Self::FixedSize(_) => "fixed_size",
52            Self::SizePrefix(_) => "size_prefix",
53
54            // Instruction directives.
55            Self::Account(_) => "account",
56
57            // Error directives.
58            Self::Error(_) => "error",
59        }
60    }
61}