Skip to main content

yellowstone_vixen_proc_macro/
lib.rs

1extern crate proc_macro;
2
3use proc_macro::TokenStream;
4use syn::{
5    parse::{Parse, ParseStream},
6    parse_macro_input, Ident, LitInt, LitStr, Token,
7};
8
9mod intermediate_representation;
10mod parse;
11mod render;
12mod utils;
13mod vixen;
14
15/// Attribute macro that auto-infers prost annotations from Rust types.
16///
17/// # Modes
18///
19/// - `#[vixen]` — struct with `prost::Message` (default)
20/// - `#[vixen(oneof)]` — enum with `prost::Oneof`
21/// - `#[vixen(enumeration)]` — enum with `prost::Enumeration`
22///
23/// Fields are auto-tagged starting at 1. Use `#[hint(...)]` on individual
24/// fields when the type can't be auto-inferred.
25#[proc_macro_attribute]
26pub fn vixen(attr: TokenStream, item: TokenStream) -> TokenStream {
27    vixen::expand(attr.into(), item.into())
28        .unwrap_or_else(|err| err.to_compile_error())
29        .into()
30}
31
32#[proc_macro]
33pub fn include_vixen_parser(input: TokenStream) -> TokenStream {
34    let input = parse_macro_input!(input as IncludeVixenParserInput);
35
36    match input.parser_config() {
37        Ok(config) => expand_include_vixen_parser(input.idl_path.value(), config),
38        Err(err) => err.to_compile_error().into(),
39    }
40}
41
42/// Input for `include_vixen_parser!`.
43///
44/// The macro accepts a Codama IDL path, plus optional parser config:
45///
46/// ```ignore
47/// include_vixen_parser!(
48///     "../idls/custom_events.json",
49///     cpi_event_discriminator = 0xfe,
50///     cpi_event_payload_offset = 1,
51/// );
52/// ```
53///
54/// Supported config options:
55/// - `cpi_event_discriminator = 0xfe`: hex bytes that identify self-CPI event instructions.
56///   The string form (`"fe"`) is also accepted for multi-byte discriminators.
57/// - `cpi_event_payload_offset = 1`: byte offset where event payload decoding starts.
58///
59/// When omitted, the parser uses Anchor's default self-CPI event envelope:
60/// an 8-byte Anchor event instruction discriminator, followed by the event
61/// discriminator and payload. Override these options for non-Anchor programs
62/// that wrap events differently, such as Pinocchio programs that emit events
63/// through a custom one-byte self-CPI instruction envelope.
64struct IncludeVixenParserInput {
65    idl_path: LitStr,
66    cpi_event_discriminator: Option<HexBytesLiteral>,
67    cpi_event_payload_offset: Option<LitInt>,
68}
69
70enum HexBytesLiteral {
71    Str(LitStr),
72    Int(LitInt),
73}
74
75impl Parse for HexBytesLiteral {
76    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
77        if input.peek(LitStr) {
78            Ok(Self::Str(input.parse()?))
79        } else {
80            Ok(Self::Int(input.parse()?))
81        }
82    }
83}
84
85impl Parse for IncludeVixenParserInput {
86    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
87        let idl_path = input.parse()?;
88        let mut cpi_event_discriminator = None;
89        let mut cpi_event_payload_offset = None;
90
91        while input.peek(Token![,]) {
92            input.parse::<Token![,]>()?;
93
94            if input.is_empty() {
95                break;
96            }
97
98            let key: Ident = input.parse()?;
99            input.parse::<Token![=]>()?;
100
101            match key.to_string().as_str() {
102                "cpi_event_discriminator" => {
103                    cpi_event_discriminator = Some(input.parse()?);
104                },
105                "cpi_event_payload_offset" => {
106                    cpi_event_payload_offset = Some(input.parse()?);
107                },
108                _ => {
109                    return Err(syn::Error::new(
110                        key.span(),
111                        "unsupported include_vixen_parser option",
112                    ));
113                },
114            }
115        }
116
117        Ok(Self {
118            idl_path,
119            cpi_event_discriminator,
120            cpi_event_payload_offset,
121        })
122    }
123}
124
125impl IncludeVixenParserInput {
126    fn parser_config(&self) -> syn::Result<crate::render::vixen_parser::ParserConfig> {
127        let mut config = crate::render::vixen_parser::ParserConfig::default();
128
129        if let Some(discriminator) = &self.cpi_event_discriminator {
130            config.cpi_event.discriminator = decode_hex_bytes_literal(discriminator)?;
131        }
132
133        if let Some(offset) = &self.cpi_event_payload_offset {
134            config.cpi_event.payload_offset = offset.base10_parse()?;
135        } else if self.cpi_event_discriminator.is_some() {
136            config.cpi_event.payload_offset = config.cpi_event.discriminator.len();
137        }
138
139        if config.cpi_event.discriminator.is_empty() {
140            return Err(syn::Error::new(
141                self.idl_path.span(),
142                "cpi_event_discriminator must not be empty",
143            ));
144        }
145
146        if config.cpi_event.payload_offset < config.cpi_event.discriminator.len() {
147            return Err(syn::Error::new(
148                self.cpi_event_payload_offset
149                    .as_ref()
150                    .map_or_else(|| self.idl_path.span(), LitInt::span),
151                "cpi_event_payload_offset must be greater than or equal to \
152                 cpi_event_discriminator length",
153            ));
154        }
155
156        Ok(config)
157    }
158}
159
160fn decode_hex_bytes_literal(lit: &HexBytesLiteral) -> syn::Result<Vec<u8>> {
161    match lit {
162        HexBytesLiteral::Str(lit) => crate::utils::decode_hex_text(&lit.value())
163            .map_err(|err| invalid_cpi_event_discriminator_hex(lit.span(), err)),
164        HexBytesLiteral::Int(lit) => decode_int_literal(lit),
165    }
166}
167
168fn decode_int_literal(lit: &LitInt) -> syn::Result<Vec<u8>> {
169    let value = lit.to_string();
170    let trimmed = value.trim();
171
172    if trimmed.starts_with("0x") || trimmed.starts_with("0X") {
173        return crate::utils::decode_hex_text(trimmed)
174            .map_err(|err| invalid_cpi_event_discriminator_hex(lit.span(), err));
175    }
176
177    let value = lit.base10_parse::<u128>()?;
178    if value == 0 {
179        return Ok(vec![0]);
180    }
181
182    let bytes = value.to_be_bytes();
183    let first_non_zero = bytes
184        .iter()
185        .position(|byte| *byte != 0)
186        .unwrap_or(bytes.len() - 1);
187    Ok(bytes[first_non_zero..].to_vec())
188}
189
190fn invalid_cpi_event_discriminator_hex(
191    span: proc_macro2::Span,
192    err: hex::FromHexError,
193) -> syn::Error {
194    syn::Error::new(
195        span,
196        format!("cpi_event_discriminator must be hex bytes: {err}"),
197    )
198}
199
200fn expand_include_vixen_parser(
201    idl_path: String,
202    config: crate::render::vixen_parser::ParserConfig,
203) -> TokenStream {
204    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
205
206    let full_path = std::path::Path::new(&manifest_dir).join(&idl_path);
207
208    match parse::load_codama_idl(&full_path) {
209        Ok((idl, events)) => crate::render::vixen_parser(&idl, &events, &config).into(),
210        Err(e) => {
211            let error_msg = format!("Failed to load/parse IDL from {:?}: {}", full_path, e);
212
213            quote::quote! {
214                compile_error!(#error_msg);
215            }
216            .into()
217        },
218    }
219}