Skip to content

Commit

Permalink
fix merge conflict - incorporate both
Browse files Browse the repository at this point in the history
  • Loading branch information
paul-schaaf committed Dec 4, 2021
2 parents c0d8914 + 8467491 commit 06e3d6c
Show file tree
Hide file tree
Showing 12 changed files with 131 additions and 6 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use anchor_client::Cluster;
use anchor_syn::idl::Idl;
use anyhow::{anyhow, Error, Result};
use clap::{ArgEnum, Clap};
use heck::SnakeCase;
use serde::{Deserialize, Serialize};
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, Signer};
Expand Down Expand Up @@ -68,14 +69,16 @@ impl Manifest {
.name
.as_ref()
.unwrap()
.to_string())
.to_string()
.to_snake_case())
} else {
Ok(self
.package
.as_ref()
.ok_or_else(|| anyhow!("package section not provided"))?
.name
.to_string())
.to_string()
.to_snake_case())
}
}

Expand Down
2 changes: 2 additions & 0 deletions lang/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ default = []
anchor-debug = [
"anchor-attribute-access-control/anchor-debug",
"anchor-attribute-account/anchor-debug",
"anchor-attribute-constant/anchor-debug",
"anchor-attribute-error/anchor-debug",
"anchor-attribute-event/anchor-debug",
"anchor-attribute-interface/anchor-debug",
Expand All @@ -25,6 +26,7 @@ anchor-debug = [
[dependencies]
anchor-attribute-access-control = { path = "./attribute/access-control", version = "0.18.2" }
anchor-attribute-account = { path = "./attribute/account", version = "0.18.2" }
anchor-attribute-constant = { path = "./attribute/constant", version = "0.18.2" }
anchor-attribute-error = { path = "./attribute/error", version = "0.18.2" }
anchor-attribute-program = { path = "./attribute/program", version = "0.18.2" }
anchor-attribute-state = { path = "./attribute/state", version = "0.18.2" }
Expand Down
19 changes: 19 additions & 0 deletions lang/attribute/constant/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "anchor-attribute-constant"
version = "0.18.2"
authors = ["Serum Foundation <foundation@projectserum.com>"]
repository = "https://github.com/project-serum/anchor"
license = "Apache-2.0"
description = "Anchor attribute macro for creating constant types"
edition = "2018"

[lib]
proc-macro = true

[features]
anchor-debug = ["anchor-syn/anchor-debug"]

[dependencies]
proc-macro2 = "1.0"
syn = { version = "1.0.60", features = ["full"] }
anchor-syn = { path = "../../syn", version = "0.18.2" }
11 changes: 11 additions & 0 deletions lang/attribute/constant/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
extern crate proc_macro;

/// A marker attribute used to mark const values that should be included in the
/// generated IDL but functionally does nothing.
#[proc_macro_attribute]
pub fn constant(
_attr: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
input
}
9 changes: 5 additions & 4 deletions lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ pub use crate::sysvar::Sysvar;
pub use crate::unchecked_account::UncheckedAccount;
pub use anchor_attribute_access_control::access_control;
pub use anchor_attribute_account::{account, declare_id, zero_copy};
pub use anchor_attribute_constant::constant;
pub use anchor_attribute_error::error;
pub use anchor_attribute_event::{emit, event};
pub use anchor_attribute_interface::interface;
Expand Down Expand Up @@ -250,10 +251,10 @@ impl Key for Pubkey {
/// All programs should include it via `anchor_lang::prelude::*;`.
pub mod prelude {
pub use super::{
access_control, account, declare_id, emit, error, event, interface, program, require,
state, zero_copy, Account, AccountDeserialize, AccountLoader, AccountSerialize, Accounts,
AccountsExit, AnchorDeserialize, AnchorSerialize, Context, CpiContext, Id, Key, Owner,
Program, Signer, System, SystemAccount, Sysvar, ToAccountInfo, ToAccountInfos,
access_control, account, constant, declare_id, emit, error, event, interface, program,
require, state, zero_copy, Account, AccountDeserialize, AccountLoader, AccountSerialize,
Accounts, AccountsExit, AnchorDeserialize, AnchorSerialize, Context, CpiContext, Id, Key,
Owner, Program, Signer, System, SystemAccount, Sysvar, ToAccountInfo, ToAccountInfos,
ToAccountMetas, UncheckedAccount,
};

Expand Down
23 changes: 23 additions & 0 deletions lang/syn/src/idl/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,15 @@ pub fn parse(filename: impl AsRef<Path>, version: String) -> Result<Option<Idl>>
}
}

let constants = parse_consts(&ctx)
.iter()
.map(|c: &&syn::ItemConst| IdlConst {
name: c.ident.to_string(),
ty: c.ty.to_token_stream().to_string().parse().unwrap(),
value: c.expr.to_token_stream().to_string().parse().unwrap(),
})
.collect::<Vec<IdlConst>>();

Ok(Some(Idl {
version,
name: p.name.to_string(),
Expand All @@ -237,6 +246,7 @@ pub fn parse(filename: impl AsRef<Path>, version: String) -> Result<Option<Idl>>
},
errors: error_codes,
metadata: None,
constants,
}))
}

Expand Down Expand Up @@ -344,6 +354,19 @@ fn parse_account_derives(ctx: &CrateContext) -> HashMap<String, AccountsStruct>
.collect()
}

fn parse_consts(ctx: &CrateContext) -> Vec<&syn::ItemConst> {
ctx.consts()
.filter(|item_strct| {
for attr in &item_strct.attrs {
if attr.path.segments.last().unwrap().ident == "constant" {
return true;
}
}
false
})
.collect()
}

// Parse all user defined types in the file.
fn parse_ty_defs(ctx: &CrateContext) -> Result<Vec<IdlTypeDefinition>> {
ctx.structs()
Expand Down
9 changes: 9 additions & 0 deletions lang/syn/src/idl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ pub mod file;
pub struct Idl {
pub version: String,
pub name: String,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub constants: Vec<IdlConst>,
pub instructions: Vec<IdlInstruction>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub state: Option<IdlState>,
Expand All @@ -22,6 +24,13 @@ pub struct Idl {
pub metadata: Option<JsonValue>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct IdlConst {
pub name: String,
pub ty: IdlType,
pub value: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct IdlState {
#[serde(rename = "struct")]
Expand Down
11 changes: 11 additions & 0 deletions lang/syn/src/parser/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ pub struct CrateContext {
}

impl CrateContext {
pub fn consts(&self) -> impl Iterator<Item = &syn::ItemConst> {
self.modules.iter().flat_map(|(_, ctx)| ctx.consts())
}

pub fn structs(&self) -> impl Iterator<Item = &syn::ItemStruct> {
self.modules.iter().flat_map(|(_, ctx)| ctx.structs())
}
Expand Down Expand Up @@ -183,4 +187,11 @@ impl ParsedModule {
_ => None,
})
}

fn consts(&self) -> impl Iterator<Item = &syn::ItemConst> {
self.items.iter().filter_map(|i| match i {
syn::Item::Const(item) => Some(item),
_ => None,
})
}
}
6 changes: 6 additions & 0 deletions tests/misc/programs/misc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ mod event;

declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

#[constant]
pub const BASE: u128 = 1_000_000;
#[constant]
pub const DECIMALS: u8 = 6;
pub const NO_IDL: u16 = 55;

#[program]
pub mod misc {
use super::*;
Expand Down
23 changes: 23 additions & 0 deletions tests/misc/tests/misc.js
Original file line number Diff line number Diff line change
Expand Up @@ -1234,6 +1234,29 @@ describe("misc", () => {
}
})

it("Should include BASE const in IDL", async () => {
assert(
miscIdl.constants.find(
(c) => c.name === "BASE" && c.ty === "u128" && c.value === "1_000_000"
) !== undefined
);
});

it("Should include DECIMALS const in IDL", async () => {
assert(
miscIdl.constants.find(
(c) => c.name === "DECIMALS" && c.ty === "u8" && c.value === "6"
) !== undefined
);
});

it("Should not include NO_IDL const in IDL", async () => {
assert.equal(
miscIdl.constants.find((c) => c.name === "NO_IDL"),
undefined
);
});

it("Can use multidimensional array", async () => {
const array2d = new Array(10).fill(new Array(10).fill(99));
const data = anchor.web3.Keypair.generate();
Expand Down
7 changes: 7 additions & 0 deletions ts/src/idl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ export type Idl = {
types?: IdlTypeDef[];
events?: IdlEvent[];
errors?: IdlErrorCode[];
constants?: IdlConstant[];
};

export type IdlConstant = {
name: string;
type: IdlType;
value: string;
};

export type IdlEvent = {
Expand Down

0 comments on commit 06e3d6c

Please sign in to comment.