file.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. use crate::idl::*;
  2. use crate::parser::{self, accounts, error, program};
  3. use crate::{AccountsStruct, StateIx};
  4. use anyhow::Result;
  5. use heck::MixedCase;
  6. use quote::ToTokens;
  7. use std::collections::{HashMap, HashSet};
  8. use std::fs::File;
  9. use std::io::Read;
  10. use std::path::Path;
  11. static DERIVE_NAME: &'static str = "Accounts";
  12. // Parse an entire interface file.
  13. pub fn parse(filename: impl AsRef<Path>) -> Result<Idl> {
  14. let mut file = File::open(&filename)?;
  15. let mut src = String::new();
  16. file.read_to_string(&mut src).expect("Unable to read file");
  17. let f = syn::parse_file(&src).expect("Unable to parse file");
  18. let p = program::parse(parse_program_mod(&f));
  19. let accs = parse_accounts(&f);
  20. let acc_names = {
  21. let mut acc_names = HashSet::new();
  22. for accs_strct in accs.values() {
  23. for a in accs_strct.account_tys(&accs)? {
  24. acc_names.insert(a);
  25. }
  26. }
  27. acc_names
  28. };
  29. let state = match p.state {
  30. None => None,
  31. Some(state) => match state.ctor_and_anchor {
  32. None => None, // State struct defined but no implementation
  33. Some((ctor, anchor_ident)) => {
  34. let mut methods = state
  35. .impl_block_and_methods
  36. .map(|(_impl_block, methods)| {
  37. methods
  38. .iter()
  39. .map(|method: &StateIx| {
  40. let name = method.ident.to_string().to_mixed_case();
  41. let args = method
  42. .args
  43. .iter()
  44. .map(|arg| {
  45. let mut tts = proc_macro2::TokenStream::new();
  46. arg.raw_arg.ty.to_tokens(&mut tts);
  47. let ty = tts.to_string().parse().unwrap();
  48. IdlField {
  49. name: arg.name.to_string().to_mixed_case(),
  50. ty,
  51. }
  52. })
  53. .collect::<Vec<_>>();
  54. let accounts_strct =
  55. accs.get(&method.anchor_ident.to_string()).unwrap();
  56. let accounts = accounts_strct.idl_accounts(&accs);
  57. IdlStateMethod {
  58. name,
  59. args,
  60. accounts,
  61. }
  62. })
  63. .collect::<Vec<_>>()
  64. })
  65. .unwrap_or(Vec::new());
  66. let ctor = {
  67. let name = "new".to_string();
  68. let args = ctor
  69. .sig
  70. .inputs
  71. .iter()
  72. .filter_map(|arg: &syn::FnArg| match arg {
  73. syn::FnArg::Typed(pat_ty) => {
  74. // TODO: this filtering should be donein the parser.
  75. let mut arg_str = parser::tts_to_string(&pat_ty.ty);
  76. arg_str.retain(|c| !c.is_whitespace());
  77. if arg_str.starts_with("Context<") {
  78. return None;
  79. }
  80. Some(arg)
  81. }
  82. _ => None,
  83. })
  84. .map(|arg: &syn::FnArg| match arg {
  85. syn::FnArg::Typed(arg_typed) => {
  86. let mut tts = proc_macro2::TokenStream::new();
  87. arg_typed.ty.to_tokens(&mut tts);
  88. let ty = tts.to_string().parse().unwrap();
  89. IdlField {
  90. name: parser::tts_to_string(&arg_typed.pat).to_mixed_case(),
  91. ty,
  92. }
  93. }
  94. _ => panic!("Invalid syntax"),
  95. })
  96. .collect();
  97. let accounts_strct = accs.get(&anchor_ident.to_string()).unwrap();
  98. let accounts = accounts_strct.idl_accounts(&accs);
  99. IdlStateMethod {
  100. name,
  101. args,
  102. accounts,
  103. }
  104. };
  105. methods.insert(0, ctor);
  106. let strct = {
  107. let fields = match state.strct.fields {
  108. syn::Fields::Named(f_named) => f_named
  109. .named
  110. .iter()
  111. .map(|f: &syn::Field| {
  112. let mut tts = proc_macro2::TokenStream::new();
  113. f.ty.to_tokens(&mut tts);
  114. let ty = tts.to_string().parse().unwrap();
  115. IdlField {
  116. name: f.ident.as_ref().unwrap().to_string().to_mixed_case(),
  117. ty,
  118. }
  119. })
  120. .collect::<Vec<IdlField>>(),
  121. _ => panic!("State must be a struct"),
  122. };
  123. IdlTypeDef {
  124. name: state.name,
  125. ty: IdlTypeDefTy::Struct { fields },
  126. }
  127. };
  128. Some(IdlState { strct, methods })
  129. }
  130. },
  131. };
  132. let error = parse_error_enum(&f).map(|mut e| error::parse(&mut e));
  133. let error_codes = error.as_ref().map(|e| {
  134. e.codes
  135. .iter()
  136. .map(|code| IdlErrorCode {
  137. code: 100 + code.id,
  138. name: code.ident.to_string(),
  139. msg: code.msg.clone(),
  140. })
  141. .collect::<Vec<IdlErrorCode>>()
  142. });
  143. let instructions = p
  144. .ixs
  145. .iter()
  146. .map(|ix| {
  147. let args = ix
  148. .args
  149. .iter()
  150. .map(|arg| {
  151. let mut tts = proc_macro2::TokenStream::new();
  152. arg.raw_arg.ty.to_tokens(&mut tts);
  153. let ty = tts.to_string().parse().unwrap();
  154. IdlField {
  155. name: arg.name.to_string().to_mixed_case(),
  156. ty,
  157. }
  158. })
  159. .collect::<Vec<_>>();
  160. // todo: don't unwrap
  161. let accounts_strct = accs.get(&ix.anchor_ident.to_string()).unwrap();
  162. let accounts = accounts_strct.idl_accounts(&accs);
  163. IdlIx {
  164. name: ix.ident.to_string().to_mixed_case(),
  165. accounts,
  166. args,
  167. }
  168. })
  169. .collect::<Vec<_>>();
  170. // All user defined types.
  171. let mut accounts = vec![];
  172. let mut types = vec![];
  173. let ty_defs = parse_ty_defs(&f)?;
  174. let error_name = error.map(|e| e.name).unwrap_or("".to_string());
  175. for ty_def in ty_defs {
  176. // Don't add the error type to the types or accounts sections.
  177. if ty_def.name != error_name {
  178. if acc_names.contains(&ty_def.name) {
  179. accounts.push(ty_def);
  180. } else {
  181. types.push(ty_def);
  182. }
  183. }
  184. }
  185. Ok(Idl {
  186. version: "0.0.0".to_string(),
  187. name: p.name.to_string(),
  188. state,
  189. instructions,
  190. types,
  191. accounts,
  192. errors: error_codes,
  193. metadata: None,
  194. })
  195. }
  196. // Parse the main program mod.
  197. fn parse_program_mod(f: &syn::File) -> syn::ItemMod {
  198. let mods = f
  199. .items
  200. .iter()
  201. .filter_map(|i| match i {
  202. syn::Item::Mod(item_mod) => {
  203. let mods = item_mod
  204. .attrs
  205. .iter()
  206. .filter_map(|attr| {
  207. let segment = attr.path.segments.last().unwrap();
  208. if segment.ident.to_string() == "program" {
  209. return Some(attr);
  210. }
  211. None
  212. })
  213. .collect::<Vec<_>>();
  214. if mods.len() != 1 {
  215. return None;
  216. }
  217. Some(item_mod)
  218. }
  219. _ => None,
  220. })
  221. .collect::<Vec<_>>();
  222. if mods.len() != 1 {
  223. panic!("Did not find program attribute");
  224. }
  225. mods[0].clone()
  226. }
  227. fn parse_error_enum(f: &syn::File) -> Option<syn::ItemEnum> {
  228. f.items
  229. .iter()
  230. .filter_map(|i| match i {
  231. syn::Item::Enum(item_enum) => {
  232. let attrs = item_enum
  233. .attrs
  234. .iter()
  235. .filter_map(|attr| {
  236. let segment = attr.path.segments.last().unwrap();
  237. if segment.ident.to_string() == "error" {
  238. return Some(attr);
  239. }
  240. None
  241. })
  242. .collect::<Vec<_>>();
  243. match attrs.len() {
  244. 0 => None,
  245. 1 => Some(item_enum),
  246. _ => panic!("Invalid syntax: one error attribute allowed"),
  247. }
  248. }
  249. _ => None,
  250. })
  251. .next()
  252. .cloned()
  253. }
  254. // Parse all structs implementing the `Accounts` trait.
  255. fn parse_accounts(f: &syn::File) -> HashMap<String, AccountsStruct> {
  256. f.items
  257. .iter()
  258. .filter_map(|i| match i {
  259. syn::Item::Struct(i_strct) => {
  260. for attr in &i_strct.attrs {
  261. if attr.tokens.to_string().contains(DERIVE_NAME) {
  262. let strct = accounts::parse(i_strct);
  263. return Some((strct.ident.to_string(), strct));
  264. }
  265. }
  266. None
  267. }
  268. // TODO: parse manual implementations. Currently we only look
  269. // for derives.
  270. _ => None,
  271. })
  272. .collect()
  273. }
  274. // Parse all user defined types in the file.
  275. fn parse_ty_defs(f: &syn::File) -> Result<Vec<IdlTypeDef>> {
  276. f.items
  277. .iter()
  278. .filter_map(|i| match i {
  279. syn::Item::Struct(item_strct) => {
  280. for attr in &item_strct.attrs {
  281. if attr.tokens.to_string().contains(DERIVE_NAME) {
  282. return None;
  283. }
  284. }
  285. if let syn::Visibility::Public(_) = &item_strct.vis {
  286. let name = item_strct.ident.to_string();
  287. let fields = match &item_strct.fields {
  288. syn::Fields::Named(fields) => fields
  289. .named
  290. .iter()
  291. .map(|f: &syn::Field| {
  292. let mut tts = proc_macro2::TokenStream::new();
  293. f.ty.to_tokens(&mut tts);
  294. Ok(IdlField {
  295. name: f.ident.as_ref().unwrap().to_string().to_mixed_case(),
  296. ty: tts.to_string().parse()?,
  297. })
  298. })
  299. .collect::<Result<Vec<IdlField>>>(),
  300. _ => panic!("Only named structs are allowed."),
  301. };
  302. return Some(fields.map(|fields| IdlTypeDef {
  303. name,
  304. ty: IdlTypeDefTy::Struct { fields },
  305. }));
  306. }
  307. None
  308. }
  309. syn::Item::Enum(enm) => {
  310. let name = enm.ident.to_string();
  311. let variants = enm
  312. .variants
  313. .iter()
  314. .map(|variant: &syn::Variant| {
  315. let name = variant.ident.to_string();
  316. let fields = match &variant.fields {
  317. syn::Fields::Unit => None,
  318. syn::Fields::Unnamed(fields) => {
  319. let fields: Vec<IdlType> =
  320. fields.unnamed.iter().map(to_idl_type).collect();
  321. Some(EnumFields::Tuple(fields))
  322. }
  323. syn::Fields::Named(fields) => {
  324. let fields: Vec<IdlField> = fields
  325. .named
  326. .iter()
  327. .map(|f: &syn::Field| {
  328. let name = f.ident.as_ref().unwrap().to_string();
  329. let ty = to_idl_type(f);
  330. IdlField { name, ty }
  331. })
  332. .collect();
  333. Some(EnumFields::Named(fields))
  334. }
  335. };
  336. EnumVariant { name, fields }
  337. })
  338. .collect::<Vec<EnumVariant>>();
  339. Some(Ok(IdlTypeDef {
  340. name,
  341. ty: IdlTypeDefTy::Enum { variants },
  342. }))
  343. }
  344. _ => None,
  345. })
  346. .collect()
  347. }
  348. fn to_idl_type(f: &syn::Field) -> IdlType {
  349. let mut tts = proc_macro2::TokenStream::new();
  350. f.ty.to_tokens(&mut tts);
  351. tts.to_string().parse().unwrap()
  352. }