file.rs 20 KB

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