Skip to main content

anchor_syn/parser/program/
mod.rs

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