file.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. use crate::idl::*;
  2. use crate::parser::context::CrateContext;
  3. use crate::parser::{self, accounts, error, program};
  4. use crate::Ty;
  5. use crate::{AccountField, AccountsStruct, StateIx};
  6. use anyhow::Result;
  7. use heck::MixedCase;
  8. use quote::ToTokens;
  9. use std::collections::{HashMap, HashSet};
  10. use std::path::Path;
  11. const DERIVE_NAME: &str = "Accounts";
  12. // TODO: sharee this with `anchor_lang` crate.
  13. const ERROR_CODE_OFFSET: u32 = 6000;
  14. // Parse an entire interface file.
  15. pub fn parse(
  16. filename: impl AsRef<Path>,
  17. version: String,
  18. seeds_feature: bool,
  19. ) -> Result<Option<Idl>> {
  20. let ctx = CrateContext::parse(filename)?;
  21. let program_mod = match parse_program_mod(&ctx) {
  22. None => return Ok(None),
  23. Some(m) => m,
  24. };
  25. let p = program::parse(program_mod)?;
  26. let accs = parse_account_derives(&ctx);
  27. let state = match p.state {
  28. None => None,
  29. Some(state) => match state.ctor_and_anchor {
  30. None => None, // State struct defined but no implementation
  31. Some((ctor, anchor_ident)) => {
  32. let mut methods = state
  33. .impl_block_and_methods
  34. .map(|(_impl_block, methods)| {
  35. methods
  36. .iter()
  37. .map(|method: &StateIx| {
  38. let name = method.ident.to_string().to_mixed_case();
  39. let args = method
  40. .args
  41. .iter()
  42. .map(|arg| {
  43. let mut tts = proc_macro2::TokenStream::new();
  44. arg.raw_arg.ty.to_tokens(&mut tts);
  45. let ty = tts.to_string().parse().unwrap();
  46. IdlField {
  47. name: arg.name.to_string().to_mixed_case(),
  48. ty,
  49. }
  50. })
  51. .collect::<Vec<_>>();
  52. let accounts_strct =
  53. accs.get(&method.anchor_ident.to_string()).unwrap();
  54. let accounts =
  55. idl_accounts(&ctx, accounts_strct, &accs, seeds_feature);
  56. IdlInstruction {
  57. name,
  58. accounts,
  59. args,
  60. }
  61. })
  62. .collect::<Vec<_>>()
  63. })
  64. .unwrap_or_default();
  65. let ctor = {
  66. let name = "new".to_string();
  67. let args = ctor
  68. .sig
  69. .inputs
  70. .iter()
  71. .filter(|arg| match arg {
  72. syn::FnArg::Typed(pat_ty) => {
  73. // TODO: this filtering should be done in the parser.
  74. let mut arg_str = parser::tts_to_string(&pat_ty.ty);
  75. arg_str.retain(|c| !c.is_whitespace());
  76. !arg_str.starts_with("Context<")
  77. }
  78. _ => false,
  79. })
  80. .map(|arg: &syn::FnArg| match arg {
  81. syn::FnArg::Typed(arg_typed) => {
  82. let mut tts = proc_macro2::TokenStream::new();
  83. arg_typed.ty.to_tokens(&mut tts);
  84. let ty = tts.to_string().parse().unwrap();
  85. IdlField {
  86. name: parser::tts_to_string(&arg_typed.pat).to_mixed_case(),
  87. ty,
  88. }
  89. }
  90. _ => panic!("Invalid syntax"),
  91. })
  92. .collect();
  93. let accounts_strct = accs.get(&anchor_ident.to_string()).unwrap();
  94. let accounts = idl_accounts(&ctx, accounts_strct, &accs, seeds_feature);
  95. IdlInstruction {
  96. name,
  97. accounts,
  98. args,
  99. }
  100. };
  101. methods.insert(0, ctor);
  102. let strct = {
  103. let fields = match state.strct.fields {
  104. syn::Fields::Named(f_named) => f_named
  105. .named
  106. .iter()
  107. .map(|f: &syn::Field| {
  108. let mut tts = proc_macro2::TokenStream::new();
  109. f.ty.to_tokens(&mut tts);
  110. let ty = tts.to_string().parse().unwrap();
  111. IdlField {
  112. name: f.ident.as_ref().unwrap().to_string().to_mixed_case(),
  113. ty,
  114. }
  115. })
  116. .collect::<Vec<IdlField>>(),
  117. _ => panic!("State must be a struct"),
  118. };
  119. IdlTypeDefinition {
  120. name: state.name,
  121. ty: IdlTypeDefinitionTy::Struct { fields },
  122. }
  123. };
  124. Some(IdlState { strct, methods })
  125. }
  126. },
  127. };
  128. let error = parse_error_enum(&ctx).map(|mut e| error::parse(&mut e, None));
  129. let error_codes = error.as_ref().map(|e| {
  130. e.codes
  131. .iter()
  132. .map(|code| IdlErrorCode {
  133. code: ERROR_CODE_OFFSET + code.id,
  134. name: code.ident.to_string(),
  135. msg: code.msg.clone(),
  136. })
  137. .collect::<Vec<IdlErrorCode>>()
  138. });
  139. let instructions = p
  140. .ixs
  141. .iter()
  142. .map(|ix| {
  143. let args = ix
  144. .args
  145. .iter()
  146. .map(|arg| {
  147. let mut tts = proc_macro2::TokenStream::new();
  148. arg.raw_arg.ty.to_tokens(&mut tts);
  149. let ty = tts.to_string().parse().unwrap();
  150. IdlField {
  151. name: arg.name.to_string().to_mixed_case(),
  152. ty,
  153. }
  154. })
  155. .collect::<Vec<_>>();
  156. // todo: don't unwrap
  157. let accounts_strct = accs.get(&ix.anchor_ident.to_string()).unwrap();
  158. let accounts = idl_accounts(&ctx, accounts_strct, &accs, seeds_feature);
  159. IdlInstruction {
  160. name: ix.ident.to_string().to_mixed_case(),
  161. accounts,
  162. args,
  163. }
  164. })
  165. .collect::<Vec<_>>();
  166. let events = parse_events(&ctx)
  167. .iter()
  168. .map(|e: &&syn::ItemStruct| {
  169. let fields = match &e.fields {
  170. syn::Fields::Named(n) => n,
  171. _ => panic!("Event fields must be named"),
  172. };
  173. let fields = fields
  174. .named
  175. .iter()
  176. .map(|f: &syn::Field| {
  177. let index = match f.attrs.get(0) {
  178. None => false,
  179. Some(i) => parser::tts_to_string(&i.path) == "index",
  180. };
  181. IdlEventField {
  182. name: f.ident.clone().unwrap().to_string().to_mixed_case(),
  183. ty: parser::tts_to_string(&f.ty).parse().unwrap(),
  184. index,
  185. }
  186. })
  187. .collect::<Vec<IdlEventField>>();
  188. IdlEvent {
  189. name: e.ident.to_string(),
  190. fields,
  191. }
  192. })
  193. .collect::<Vec<IdlEvent>>();
  194. // All user defined types.
  195. let mut accounts = vec![];
  196. let mut types = vec![];
  197. let ty_defs = parse_ty_defs(&ctx)?;
  198. let account_structs = parse_accounts(&ctx);
  199. let account_names: HashSet<String> = account_structs
  200. .iter()
  201. .map(|a| a.ident.to_string())
  202. .collect::<HashSet<_>>();
  203. let error_name = error.map(|e| e.name).unwrap_or_else(|| "".to_string());
  204. // All types that aren't in the accounts section, are in the types section.
  205. for ty_def in ty_defs {
  206. // Don't add the error type to the types or accounts sections.
  207. if ty_def.name != error_name {
  208. if account_names.contains(&ty_def.name) {
  209. accounts.push(ty_def);
  210. } else if !events.iter().any(|e| e.name == ty_def.name) {
  211. types.push(ty_def);
  212. }
  213. }
  214. }
  215. let constants = parse_consts(&ctx)
  216. .iter()
  217. .map(|c: &&syn::ItemConst| IdlConst {
  218. name: c.ident.to_string(),
  219. ty: c.ty.to_token_stream().to_string().parse().unwrap(),
  220. value: c.expr.to_token_stream().to_string().parse().unwrap(),
  221. })
  222. .collect::<Vec<IdlConst>>();
  223. Ok(Some(Idl {
  224. version,
  225. name: p.name.to_string(),
  226. state,
  227. instructions,
  228. types,
  229. accounts,
  230. events: if events.is_empty() {
  231. None
  232. } else {
  233. Some(events)
  234. },
  235. errors: error_codes,
  236. metadata: None,
  237. constants,
  238. }))
  239. }
  240. // Parse the main program mod.
  241. fn parse_program_mod(ctx: &CrateContext) -> Option<syn::ItemMod> {
  242. let root = ctx.root_module();
  243. let mods = root
  244. .items()
  245. .filter_map(|i| match i {
  246. syn::Item::Mod(item_mod) => {
  247. let mod_count = item_mod
  248. .attrs
  249. .iter()
  250. .filter(|attr| attr.path.segments.last().unwrap().ident == "program")
  251. .count();
  252. if mod_count != 1 {
  253. return None;
  254. }
  255. Some(item_mod)
  256. }
  257. _ => None,
  258. })
  259. .collect::<Vec<_>>();
  260. if mods.len() != 1 {
  261. return None;
  262. }
  263. Some(mods[0].clone())
  264. }
  265. fn parse_error_enum(ctx: &CrateContext) -> Option<syn::ItemEnum> {
  266. ctx.enums()
  267. .filter_map(|item_enum| {
  268. let attrs_count = item_enum
  269. .attrs
  270. .iter()
  271. .filter(|attr| {
  272. let segment = attr.path.segments.last().unwrap();
  273. segment.ident == "error"
  274. })
  275. .count();
  276. match attrs_count {
  277. 0 => None,
  278. 1 => Some(item_enum),
  279. _ => panic!("Invalid syntax: one error attribute allowed"),
  280. }
  281. })
  282. .next()
  283. .cloned()
  284. }
  285. fn parse_events(ctx: &CrateContext) -> Vec<&syn::ItemStruct> {
  286. ctx.structs()
  287. .filter_map(|item_strct| {
  288. let attrs_count = item_strct
  289. .attrs
  290. .iter()
  291. .filter(|attr| {
  292. let segment = attr.path.segments.last().unwrap();
  293. segment.ident == "event"
  294. })
  295. .count();
  296. match attrs_count {
  297. 0 => None,
  298. 1 => Some(item_strct),
  299. _ => panic!("Invalid syntax: one event attribute allowed"),
  300. }
  301. })
  302. .collect()
  303. }
  304. fn parse_accounts(ctx: &CrateContext) -> Vec<&syn::ItemStruct> {
  305. ctx.structs()
  306. .filter_map(|item_strct| {
  307. let attrs_count = item_strct
  308. .attrs
  309. .iter()
  310. .filter(|attr| {
  311. let segment = attr.path.segments.last().unwrap();
  312. segment.ident == "account" || segment.ident == "associated"
  313. })
  314. .count();
  315. match attrs_count {
  316. 0 => None,
  317. 1 => Some(item_strct),
  318. _ => panic!("Invalid syntax: one event attribute allowed"),
  319. }
  320. })
  321. .collect()
  322. }
  323. // Parse all structs implementing the `Accounts` trait.
  324. fn parse_account_derives(ctx: &CrateContext) -> HashMap<String, AccountsStruct> {
  325. // TODO: parse manual implementations. Currently we only look
  326. // for derives.
  327. ctx.structs()
  328. .filter_map(|i_strct| {
  329. for attr in &i_strct.attrs {
  330. if attr.tokens.to_string().contains(DERIVE_NAME) {
  331. let strct = accounts::parse(i_strct).expect("Code not parseable");
  332. return Some((strct.ident.to_string(), strct));
  333. }
  334. }
  335. None
  336. })
  337. .collect()
  338. }
  339. fn parse_consts(ctx: &CrateContext) -> Vec<&syn::ItemConst> {
  340. ctx.consts()
  341. .filter(|item_strct| {
  342. for attr in &item_strct.attrs {
  343. if attr.path.segments.last().unwrap().ident == "constant" {
  344. return true;
  345. }
  346. }
  347. false
  348. })
  349. .collect()
  350. }
  351. // Parse all user defined types in the file.
  352. fn parse_ty_defs(ctx: &CrateContext) -> Result<Vec<IdlTypeDefinition>> {
  353. ctx.structs()
  354. .filter_map(|item_strct| {
  355. // Only take serializable types
  356. let serializable = item_strct.attrs.iter().any(|attr| {
  357. let attr_string = attr.tokens.to_string();
  358. let attr_name = attr.path.segments.last().unwrap().ident.to_string();
  359. let attr_serializable = ["account", "associated", "event", "zero_copy"];
  360. let derived_serializable = attr_name == "derive"
  361. && attr_string.contains("AnchorSerialize")
  362. && attr_string.contains("AnchorDeserialize");
  363. attr_serializable.iter().any(|a| *a == attr_name) || derived_serializable
  364. });
  365. if !serializable {
  366. return None;
  367. }
  368. // Only take public types
  369. match &item_strct.vis {
  370. syn::Visibility::Public(_) => (),
  371. _ => return None,
  372. }
  373. let name = item_strct.ident.to_string();
  374. let fields = match &item_strct.fields {
  375. syn::Fields::Named(fields) => fields
  376. .named
  377. .iter()
  378. .map(|f: &syn::Field| {
  379. let mut tts = proc_macro2::TokenStream::new();
  380. f.ty.to_tokens(&mut tts);
  381. // Handle array sizes that are constants
  382. let mut tts_string = tts.to_string();
  383. if tts_string.starts_with('[') {
  384. tts_string = resolve_variable_array_length(ctx, tts_string);
  385. }
  386. Ok(IdlField {
  387. name: f.ident.as_ref().unwrap().to_string().to_mixed_case(),
  388. ty: tts_string.parse()?,
  389. })
  390. })
  391. .collect::<Result<Vec<IdlField>>>(),
  392. syn::Fields::Unnamed(_) => return None,
  393. _ => panic!("Empty structs are allowed."),
  394. };
  395. Some(fields.map(|fields| IdlTypeDefinition {
  396. name,
  397. ty: IdlTypeDefinitionTy::Struct { fields },
  398. }))
  399. })
  400. .chain(ctx.enums().map(|enm| {
  401. let name = enm.ident.to_string();
  402. let variants = enm
  403. .variants
  404. .iter()
  405. .map(|variant: &syn::Variant| {
  406. let name = variant.ident.to_string();
  407. let fields = match &variant.fields {
  408. syn::Fields::Unit => None,
  409. syn::Fields::Unnamed(fields) => {
  410. let fields: Vec<IdlType> =
  411. fields.unnamed.iter().map(to_idl_type).collect();
  412. Some(EnumFields::Tuple(fields))
  413. }
  414. syn::Fields::Named(fields) => {
  415. let fields: Vec<IdlField> = fields
  416. .named
  417. .iter()
  418. .map(|f: &syn::Field| {
  419. let name = f.ident.as_ref().unwrap().to_string();
  420. let ty = to_idl_type(f);
  421. IdlField { name, ty }
  422. })
  423. .collect();
  424. Some(EnumFields::Named(fields))
  425. }
  426. };
  427. IdlEnumVariant { name, fields }
  428. })
  429. .collect::<Vec<IdlEnumVariant>>();
  430. Ok(IdlTypeDefinition {
  431. name,
  432. ty: IdlTypeDefinitionTy::Enum { variants },
  433. })
  434. }))
  435. .collect()
  436. }
  437. // Replace variable array lengths with values
  438. fn resolve_variable_array_length(ctx: &CrateContext, tts_string: String) -> String {
  439. for constant in ctx.consts() {
  440. if constant.ty.to_token_stream().to_string() == "usize"
  441. && tts_string.contains(&constant.ident.to_string())
  442. {
  443. // Check for the existence of consts existing elsewhere in the
  444. // crate which have the same name, are usize, and have a
  445. // different value. We can't know which was intended for the
  446. // array size from ctx.
  447. if ctx.consts().any(|c| {
  448. c != constant
  449. && c.ident == constant.ident
  450. && c.ty == constant.ty
  451. && c.expr != constant.expr
  452. }) {
  453. panic!("Crate wide unique name required for array size const.");
  454. }
  455. return tts_string.replace(
  456. &constant.ident.to_string(),
  457. &constant.expr.to_token_stream().to_string(),
  458. );
  459. }
  460. }
  461. tts_string
  462. }
  463. fn to_idl_type(f: &syn::Field) -> IdlType {
  464. let mut tts = proc_macro2::TokenStream::new();
  465. f.ty.to_tokens(&mut tts);
  466. tts.to_string().parse().unwrap()
  467. }
  468. fn idl_accounts(
  469. ctx: &CrateContext,
  470. accounts: &AccountsStruct,
  471. global_accs: &HashMap<String, AccountsStruct>,
  472. seeds_feature: bool,
  473. ) -> Vec<IdlAccountItem> {
  474. accounts
  475. .fields
  476. .iter()
  477. .map(|acc: &AccountField| match acc {
  478. AccountField::CompositeField(comp_f) => {
  479. let accs_strct = global_accs
  480. .get(&comp_f.symbol)
  481. .expect("Could not resolve Accounts symbol");
  482. let accounts = idl_accounts(ctx, accs_strct, global_accs, seeds_feature);
  483. IdlAccountItem::IdlAccounts(IdlAccounts {
  484. name: comp_f.ident.to_string().to_mixed_case(),
  485. accounts,
  486. })
  487. }
  488. AccountField::Field(acc) => IdlAccountItem::IdlAccount(IdlAccount {
  489. name: acc.ident.to_string().to_mixed_case(),
  490. is_mut: acc.constraints.is_mutable(),
  491. is_signer: match acc.ty {
  492. Ty::Signer => true,
  493. _ => acc.constraints.is_signer(),
  494. },
  495. pda: pda::parse(ctx, accounts, acc, seeds_feature),
  496. }),
  497. })
  498. .collect::<Vec<_>>()
  499. }