Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion lang/syn/src/idl/constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ pub fn gen_idl_print_fn_constant(item: &syn::ItemConst) -> TokenStream {
_ => quote! { vec![] },
};

let value = if is_string_type(&item.ty) {
quote! { #expr.to_string() }
} else {
quote! { format!("{:?}", #expr) }
};

let fn_body = match gen_idl_type(&item.ty, &[]) {
Ok((ty, _)) => gen_print_section(
"const",
Expand All @@ -30,7 +36,7 @@ pub fn gen_idl_print_fn_constant(item: &syn::ItemConst) -> TokenStream {
name: #name.into(),
docs: #docs,
ty: #ty,
value: format!("{:?}", #expr),
value: #value,
}
},
),
Expand All @@ -44,3 +50,17 @@ pub fn gen_idl_print_fn_constant(item: &syn::ItemConst) -> TokenStream {
}
}
}

fn is_string_type(ty: &syn::Type) -> bool {
match ty {
syn::Type::Path(path) => {
path.path.segments.len() == 1
&& matches!(
path.path.segments.first().map(|segment| &segment.ident),
Some(ident) if ident == "String" || ident == "str"
)
}
syn::Type::Reference(reference) => is_string_type(&reference.elem),
_ => false,
}
}
5 changes: 5 additions & 0 deletions tests/idl/idls/idl.json
Original file line number Diff line number Diff line change
Expand Up @@ -1660,6 +1660,11 @@
"type": "i128",
"value": "1000000"
},
{
"name": "SEED_PREFIX",
"type": "string",
"value": "favor"
},
{
"name": "TEST_CONVERT_MODULE_PATHS",
"docs": [
Expand Down
3 changes: 3 additions & 0 deletions tests/idl/programs/idl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ pub const BYTE_STR: u8 = b't';
#[constant]
pub const BYTES_STR: &[u8] = b"test";

#[constant]
pub const SEED_PREFIX: &str = "favor";

pub const NO_IDL: u16 = 55;

#[program]
Expand Down
6 changes: 6 additions & 0 deletions tests/idl/tests/idl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,12 @@ describe("IDL", () => {
c.type === "bytes" &&
c.value === "[116, 101, 115, 116]"
);
checkDefined(
(c) =>
c.name === "seedPrefix" &&
c.type === "string" &&
c.value === "favor"
);
});

it("Does not include constants that are not marked with `#[constant]`", () => {
Expand Down
Loading