file.rs 19 KB

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