file.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. returns: None,
  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. returns: None,
  105. }
  106. };
  107. methods.insert(0, ctor);
  108. let strct = {
  109. let fields = match state.strct.fields {
  110. syn::Fields::Named(f_named) => f_named
  111. .named
  112. .iter()
  113. .map(|f: &syn::Field| {
  114. let mut tts = proc_macro2::TokenStream::new();
  115. f.ty.to_tokens(&mut tts);
  116. let ty = tts.to_string().parse().unwrap();
  117. IdlField {
  118. name: f.ident.as_ref().unwrap().to_string().to_mixed_case(),
  119. ty,
  120. }
  121. })
  122. .collect::<Vec<IdlField>>(),
  123. _ => panic!("State must be a struct"),
  124. };
  125. IdlTypeDefinition {
  126. name: state.name,
  127. ty: IdlTypeDefinitionTy::Struct { fields },
  128. }
  129. };
  130. Some(IdlState { strct, methods })
  131. }
  132. },
  133. };
  134. let error = parse_error_enum(&ctx).map(|mut e| error::parse(&mut e, None));
  135. let error_codes = error.as_ref().map(|e| {
  136. e.codes
  137. .iter()
  138. .map(|code| IdlErrorCode {
  139. code: ERROR_CODE_OFFSET + code.id,
  140. name: code.ident.to_string(),
  141. msg: code.msg.clone(),
  142. })
  143. .collect::<Vec<IdlErrorCode>>()
  144. });
  145. let instructions = p
  146. .ixs
  147. .iter()
  148. .map(|ix| {
  149. let args = ix
  150. .args
  151. .iter()
  152. .map(|arg| IdlField {
  153. name: arg.name.to_string().to_mixed_case(),
  154. ty: to_idl_type(&ctx, &arg.raw_arg.ty),
  155. })
  156. .collect::<Vec<_>>();
  157. // todo: don't unwrap
  158. let accounts_strct = accs.get(&ix.anchor_ident.to_string()).unwrap();
  159. let accounts = idl_accounts(&ctx, accounts_strct, &accs, seeds_feature);
  160. let ret_type_str = ix.returns.ty.to_token_stream().to_string();
  161. let returns = match ret_type_str.as_str() {
  162. "()" => None,
  163. _ => Some(ret_type_str.parse().unwrap()),
  164. };
  165. IdlInstruction {
  166. name: ix.ident.to_string().to_mixed_case(),
  167. accounts,
  168. args,
  169. returns,
  170. }
  171. })
  172. .collect::<Vec<_>>();
  173. let events = parse_events(&ctx)
  174. .iter()
  175. .map(|e: &&syn::ItemStruct| {
  176. let fields = match &e.fields {
  177. syn::Fields::Named(n) => n,
  178. _ => panic!("Event fields must be named"),
  179. };
  180. let fields = fields
  181. .named
  182. .iter()
  183. .map(|f: &syn::Field| {
  184. let index = match f.attrs.get(0) {
  185. None => false,
  186. Some(i) => parser::tts_to_string(&i.path) == "index",
  187. };
  188. IdlEventField {
  189. name: f.ident.clone().unwrap().to_string().to_mixed_case(),
  190. ty: to_idl_type(&ctx, &f.ty),
  191. index,
  192. }
  193. })
  194. .collect::<Vec<IdlEventField>>();
  195. IdlEvent {
  196. name: e.ident.to_string(),
  197. fields,
  198. }
  199. })
  200. .collect::<Vec<IdlEvent>>();
  201. // All user defined types.
  202. let mut accounts = vec![];
  203. let mut types = vec![];
  204. let ty_defs = parse_ty_defs(&ctx)?;
  205. let account_structs = parse_accounts(&ctx);
  206. let account_names: HashSet<String> = account_structs
  207. .iter()
  208. .map(|a| a.ident.to_string())
  209. .collect::<HashSet<_>>();
  210. let error_name = error.map(|e| e.name).unwrap_or_else(|| "".to_string());
  211. // All types that aren't in the accounts section, are in the types section.
  212. for ty_def in ty_defs {
  213. // Don't add the error type to the types or accounts sections.
  214. if ty_def.name != error_name {
  215. if account_names.contains(&ty_def.name) {
  216. accounts.push(ty_def);
  217. } else if !events.iter().any(|e| e.name == ty_def.name) {
  218. types.push(ty_def);
  219. }
  220. }
  221. }
  222. let constants = parse_consts(&ctx)
  223. .iter()
  224. .map(|c: &&syn::ItemConst| IdlConst {
  225. name: c.ident.to_string(),
  226. ty: c.ty.to_token_stream().to_string().parse().unwrap(),
  227. value: c.expr.to_token_stream().to_string().parse().unwrap(),
  228. })
  229. .collect::<Vec<IdlConst>>();
  230. Ok(Some(Idl {
  231. version,
  232. name: p.name.to_string(),
  233. state,
  234. instructions,
  235. types,
  236. accounts,
  237. events: if events.is_empty() {
  238. None
  239. } else {
  240. Some(events)
  241. },
  242. errors: error_codes,
  243. metadata: None,
  244. constants,
  245. }))
  246. }
  247. // Parse the main program mod.
  248. fn parse_program_mod(ctx: &CrateContext) -> Option<syn::ItemMod> {
  249. let root = ctx.root_module();
  250. let mods = root
  251. .items()
  252. .filter_map(|i| match i {
  253. syn::Item::Mod(item_mod) => {
  254. let mod_count = item_mod
  255. .attrs
  256. .iter()
  257. .filter(|attr| attr.path.segments.last().unwrap().ident == "program")
  258. .count();
  259. if mod_count != 1 {
  260. return None;
  261. }
  262. Some(item_mod)
  263. }
  264. _ => None,
  265. })
  266. .collect::<Vec<_>>();
  267. if mods.len() != 1 {
  268. return None;
  269. }
  270. Some(mods[0].clone())
  271. }
  272. fn parse_error_enum(ctx: &CrateContext) -> Option<syn::ItemEnum> {
  273. ctx.enums()
  274. .filter_map(|item_enum| {
  275. let attrs_count = item_enum
  276. .attrs
  277. .iter()
  278. .filter(|attr| {
  279. let segment = attr.path.segments.last().unwrap();
  280. segment.ident == "error_code"
  281. })
  282. .count();
  283. match attrs_count {
  284. 0 => None,
  285. 1 => Some(item_enum),
  286. _ => panic!("Invalid syntax: one error attribute allowed"),
  287. }
  288. })
  289. .next()
  290. .cloned()
  291. }
  292. fn parse_events(ctx: &CrateContext) -> Vec<&syn::ItemStruct> {
  293. ctx.structs()
  294. .filter_map(|item_strct| {
  295. let attrs_count = item_strct
  296. .attrs
  297. .iter()
  298. .filter(|attr| {
  299. let segment = attr.path.segments.last().unwrap();
  300. segment.ident == "event"
  301. })
  302. .count();
  303. match attrs_count {
  304. 0 => None,
  305. 1 => Some(item_strct),
  306. _ => panic!("Invalid syntax: one event attribute allowed"),
  307. }
  308. })
  309. .collect()
  310. }
  311. fn parse_accounts(ctx: &CrateContext) -> Vec<&syn::ItemStruct> {
  312. ctx.structs()
  313. .filter_map(|item_strct| {
  314. let attrs_count = item_strct
  315. .attrs
  316. .iter()
  317. .filter(|attr| {
  318. let segment = attr.path.segments.last().unwrap();
  319. segment.ident == "account" || segment.ident == "associated"
  320. })
  321. .count();
  322. match attrs_count {
  323. 0 => None,
  324. 1 => Some(item_strct),
  325. _ => panic!("Invalid syntax: one event attribute allowed"),
  326. }
  327. })
  328. .collect()
  329. }
  330. // Parse all structs implementing the `Accounts` trait.
  331. fn parse_account_derives(ctx: &CrateContext) -> HashMap<String, AccountsStruct> {
  332. // TODO: parse manual implementations. Currently we only look
  333. // for derives.
  334. ctx.structs()
  335. .filter_map(|i_strct| {
  336. for attr in &i_strct.attrs {
  337. if attr.path.is_ident("derive") && attr.tokens.to_string().contains(DERIVE_NAME) {
  338. let strct = accounts::parse(i_strct).expect("Code not parseable");
  339. return Some((strct.ident.to_string(), strct));
  340. }
  341. }
  342. None
  343. })
  344. .collect()
  345. }
  346. fn parse_consts(ctx: &CrateContext) -> Vec<&syn::ItemConst> {
  347. ctx.consts()
  348. .filter(|item_strct| {
  349. for attr in &item_strct.attrs {
  350. if attr.path.segments.last().unwrap().ident == "constant" {
  351. return true;
  352. }
  353. }
  354. false
  355. })
  356. .collect()
  357. }
  358. // Parse all user defined types in the file.
  359. fn parse_ty_defs(ctx: &CrateContext) -> Result<Vec<IdlTypeDefinition>> {
  360. ctx.structs()
  361. .filter_map(|item_strct| {
  362. // Only take serializable types
  363. let serializable = item_strct.attrs.iter().any(|attr| {
  364. let attr_string = attr.tokens.to_string();
  365. let attr_name = attr.path.segments.last().unwrap().ident.to_string();
  366. let attr_serializable = ["account", "associated", "event", "zero_copy"];
  367. let derived_serializable = attr_name == "derive"
  368. && attr_string.contains("AnchorSerialize")
  369. && attr_string.contains("AnchorDeserialize");
  370. attr_serializable.iter().any(|a| *a == attr_name) || derived_serializable
  371. });
  372. if !serializable {
  373. return None;
  374. }
  375. // Only take public types
  376. match &item_strct.vis {
  377. syn::Visibility::Public(_) => (),
  378. _ => return None,
  379. }
  380. let name = item_strct.ident.to_string();
  381. let fields = match &item_strct.fields {
  382. syn::Fields::Named(fields) => fields
  383. .named
  384. .iter()
  385. .map(|f: &syn::Field| {
  386. Ok(IdlField {
  387. name: f.ident.as_ref().unwrap().to_string().to_mixed_case(),
  388. ty: to_idl_type(ctx, &f.ty),
  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> = fields
  411. .unnamed
  412. .iter()
  413. .map(|f| to_idl_type(ctx, &f.ty))
  414. .collect();
  415. Some(EnumFields::Tuple(fields))
  416. }
  417. syn::Fields::Named(fields) => {
  418. let fields: Vec<IdlField> = fields
  419. .named
  420. .iter()
  421. .map(|f: &syn::Field| {
  422. let name = f.ident.as_ref().unwrap().to_string();
  423. let ty = to_idl_type(ctx, &f.ty);
  424. IdlField { name, ty }
  425. })
  426. .collect();
  427. Some(EnumFields::Named(fields))
  428. }
  429. };
  430. IdlEnumVariant { name, fields }
  431. })
  432. .collect::<Vec<IdlEnumVariant>>();
  433. Ok(IdlTypeDefinition {
  434. name,
  435. ty: IdlTypeDefinitionTy::Enum { variants },
  436. })
  437. }))
  438. .collect()
  439. }
  440. // Replace variable array lengths with values
  441. fn resolve_variable_array_lengths(ctx: &CrateContext, mut tts_string: String) -> String {
  442. for constant in ctx.consts().filter(|c| match *c.ty {
  443. // Filter to only those consts that are of type usize or could be cast to usize
  444. syn::Type::Path(ref p) => {
  445. let segment = p.path.segments.last().unwrap();
  446. matches!(
  447. segment.ident.to_string().as_str(),
  448. "usize"
  449. | "u8"
  450. | "u16"
  451. | "u32"
  452. | "u64"
  453. | "u128"
  454. | "isize"
  455. | "i8"
  456. | "i16"
  457. | "i32"
  458. | "i64"
  459. | "i128"
  460. )
  461. }
  462. _ => false,
  463. }) {
  464. let mut check_string = tts_string.clone();
  465. // Strip whitespace to handle accidental double whitespaces
  466. check_string.retain(|c| !c.is_whitespace());
  467. let size_string = format!("{}]", &constant.ident.to_string());
  468. let cast_size_string = format!("{}asusize]", &constant.ident.to_string());
  469. // Check for something to replace
  470. let mut replacement_string = None;
  471. if check_string.contains(cast_size_string.as_str()) {
  472. replacement_string = Some(cast_size_string);
  473. } else if check_string.contains(size_string.as_str()) {
  474. replacement_string = Some(size_string);
  475. }
  476. if let Some(replacement_string) = replacement_string {
  477. // Check for the existence of consts existing elsewhere in the
  478. // crate which have the same name, are usize, and have a
  479. // different value. We can't know which was intended for the
  480. // array size from ctx.
  481. if ctx.consts().any(|c| {
  482. c != constant
  483. && c.ident == constant.ident
  484. && c.ty == constant.ty
  485. && c.expr != constant.expr
  486. }) {
  487. panic!("Crate wide unique name required for array size const.");
  488. }
  489. // Replace the match, don't break because there might be multiple replacements to be
  490. // made in the case of multidimensional arrays
  491. tts_string = check_string.replace(
  492. &replacement_string,
  493. format!("{}]", &constant.expr.to_token_stream()).as_str(),
  494. );
  495. }
  496. }
  497. tts_string
  498. }
  499. fn to_idl_type(ctx: &CrateContext, ty: &syn::Type) -> IdlType {
  500. let mut tts_string = parser::tts_to_string(&ty);
  501. if tts_string.starts_with('[') {
  502. tts_string = resolve_variable_array_lengths(ctx, tts_string);
  503. }
  504. tts_string.parse().unwrap()
  505. }
  506. fn idl_accounts(
  507. ctx: &CrateContext,
  508. accounts: &AccountsStruct,
  509. global_accs: &HashMap<String, AccountsStruct>,
  510. seeds_feature: bool,
  511. ) -> Vec<IdlAccountItem> {
  512. accounts
  513. .fields
  514. .iter()
  515. .map(|acc: &AccountField| match acc {
  516. AccountField::CompositeField(comp_f) => {
  517. let accs_strct = global_accs.get(&comp_f.symbol).unwrap_or_else(|| {
  518. panic!("Could not resolve Accounts symbol {}", comp_f.symbol)
  519. });
  520. let accounts = idl_accounts(ctx, accs_strct, global_accs, seeds_feature);
  521. IdlAccountItem::IdlAccounts(IdlAccounts {
  522. name: comp_f.ident.to_string().to_mixed_case(),
  523. accounts,
  524. })
  525. }
  526. AccountField::Field(acc) => IdlAccountItem::IdlAccount(IdlAccount {
  527. name: acc.ident.to_string().to_mixed_case(),
  528. is_mut: acc.constraints.is_mutable(),
  529. is_signer: match acc.ty {
  530. Ty::Signer => true,
  531. _ => acc.constraints.is_signer(),
  532. },
  533. pda: pda::parse(ctx, accounts, acc, seeds_feature),
  534. }),
  535. })
  536. .collect::<Vec<_>>()
  537. }