anchor_syn/parser/program/
mod.rs

1use crate::parser::docs;
2use crate::Program;
3use syn::parse::{Error as ParseError, Result as ParseResult};
4use syn::spanned::Spanned;
5
6mod instructions;
7
8pub fn parse(program_mod: syn::ItemMod) -> ParseResult<Program> {
9    let docs = docs::parse(&program_mod.attrs);
10    let (ixs, fallback_fn) = instructions::parse(&program_mod)?;
11    Ok(Program {
12        ixs,
13        name: program_mod.ident.clone(),
14        docs,
15        program_mod,
16        fallback_fn,
17    })
18}
19
20fn ctx_accounts_ident(path_ty: &syn::PatType) -> ParseResult<proc_macro2::Ident> {
21    let p = match &*path_ty.ty {
22        syn::Type::Path(p) => &p.path,
23        _ => return Err(ParseError::new(path_ty.ty.span(), "invalid type")),
24    };
25    let segment = p
26        .segments
27        .first()
28        .ok_or_else(|| ParseError::new(p.segments.span(), "expected generic arguments here"))?;
29
30    let generic_args = match &segment.arguments {
31        syn::PathArguments::AngleBracketed(args) => args,
32        _ => return Err(ParseError::new(path_ty.span(), "missing accounts context")),
33    };
34    let generic_ty = generic_args
35        .args
36        .iter()
37        .filter_map(|arg| match arg {
38            syn::GenericArgument::Type(ty) => Some(ty),
39            _ => None,
40        })
41        .next()
42        .ok_or_else(|| ParseError::new(generic_args.span(), "expected Accounts type"))?;
43
44    let path = match generic_ty {
45        syn::Type::Path(ty_path) => &ty_path.path,
46        _ => {
47            return Err(ParseError::new(
48                generic_ty.span(),
49                "expected Accounts struct type",
50            ))
51        }
52    };
53    Ok(path.segments[0].ident.clone())
54}