Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: export candid #28

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 5 additions & 1 deletion examples/print/src/print_rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,9 @@ crate-type = ["cdylib"]
[dependencies]
ic-cdk = { path = "../../../../src/ic-cdk", version = "0.1.0" }
ic-cdk-macros = { path = "../../../../src/ic-cdk-macros", version = "0.1.0" }
candid = "0.6.2"
candid = { git = "https://github.com/dfinity/candid.git", branch = "derive-func" }
serde = "1.0.111"

[features]
default = []
export_candid = ["ic-cdk/wasi"]
22 changes: 22 additions & 0 deletions examples/print/src/print_rs/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,26 @@
use candid::{CandidType, Deserialize};

#[ic_cdk_macros::query]
fn print() {
ic_cdk::print("Hello World");
}

#[ic_cdk_macros::update(name = "🐂")]
fn test(name: String) -> (usize, String) {
(name.len(), name)
}

#[derive(CandidType, Deserialize)]
struct List { head: i8, tail: Option<Box<List>> }

#[derive(CandidType, Deserialize)]
enum A { A1(u16), A2(List), A3(String, candid::Principal) }

#[ic_cdk_macros::query]
fn id_struct(a:List) -> List { a }

#[ic_cdk_macros::update]
fn id_variant(a:A) -> A { a }

ic_cdk_macros::export_candid!();

2 changes: 1 addition & 1 deletion src/ic-cdk-macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ include = ["src", "Cargo.toml", "LICENSE", "README.md"]
proc-macro = true

[dependencies]
candid = "0.6.2"
candid = { git = "https://github.com/dfinity/candid.git", branch = "derive-func" }
ic-cdk = { path = "../ic-cdk", version = "0.1" }
syn = { version = "1.0", features = ["fold", "full"] }
quote = "1.0"
Expand Down
27 changes: 15 additions & 12 deletions src/ic-cdk-macros/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ enum MethodType {

impl MethodType {
pub fn is_lifecycle(&self) -> bool {
match self {
MethodType::Init | MethodType::PreUpgrade | MethodType::PostUpgrade => true,
_ => false,
}
matches!(
self,
MethodType::Init | MethodType::PreUpgrade | MethodType::PostUpgrade
)
}
}

Expand Down Expand Up @@ -131,15 +131,16 @@ fn dfn_macro(
&format!("{}_{}_", name.to_string(), crate::id()),
Span::call_site(),
);

let rename = attrs.name.unwrap_or_else(|| name.to_string());
let export_name = if method.is_lifecycle() {
format!("{}", method)
} else {
format!(
"{0} {1}",
method,
attrs.name.unwrap_or_else(|| name.to_string())
)
format!("{0} {1}", method, rename,)
};
let candid_method_attr = match method {
MethodType::Query => quote! { #[candid::candid_method(query, rename = #rename)] },
MethodType::Update => quote! { #[candid::candid_method(update, rename = #rename)] },
_ => quote! {},
};

let function_call = if is_async {
Expand Down Expand Up @@ -183,7 +184,7 @@ fn dfn_macro(
quote! {}
};

Ok(quote! {
let res = quote! {
#[export_name = #export_name]
fn #outer_function_ident() {
ic_cdk::setup();
Expand All @@ -197,8 +198,10 @@ fn dfn_macro(
});
}

#candid_method_attr
#item
})
};
Ok(res)
}

pub(crate) fn ic_query(
Expand Down
20 changes: 20 additions & 0 deletions src/ic-cdk-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,23 @@ pub fn post_upgrade(attr: TokenStream, item: TokenStream) -> TokenStream {
pub fn import(attr: TokenStream, item: TokenStream) -> TokenStream {
handle_debug_and_errors(import::ic_import, "ic_import", attr, item)
}

#[proc_macro]
pub fn export_candid(_input: TokenStream) -> TokenStream {
let res = quote::quote! {
candid::export_service!();

#[ic_cdk_macros::query(name = "__get_candid_interface_tmp_hack")]
fn export_candid() -> String {
__export_service()
}
#[cfg(feature = "export_candid")]
#[no_mangle]
pub unsafe extern "C" fn _start() {
let result = export_candid();
let ret = unsafe { ::ic_cdk::api::wasi::print(&result) };
ic_cdk::api::wasi::proc_exit(ret as u32);
}
};
res.into()
}
3 changes: 2 additions & 1 deletion src/ic-cdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ keywords = ["internet-computer", "types", "dfinity", "canister", "cdk"]
include = ["src", "Cargo.toml", "LICENSE", "README.md"]

[dependencies]
candid = "0.6.2"
candid = { git = "https://github.com/dfinity/candid.git", branch = "derive-func" }
cfg-if = "0.1.10"
ic-types = "0.1.1"
serde = "1.0.110"
wee_alloc = { version = "0.4.5" }

[features]
experimental = []
wasi = []
3 changes: 3 additions & 0 deletions src/ic-cdk/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
use ic_types::Principal;
use std::convert::TryFrom;

#[cfg(all(target_arch = "wasm32", feature = "wasi"))]
pub mod wasi;

pub mod call;
pub mod stable;

Expand Down
4 changes: 2 additions & 2 deletions src/ic-cdk/src/api/ic0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ macro_rules! _ic0_module_ret {
macro_rules! ic0_module {
( $( ic0. $name: ident : ( $( $argname: ident : $argtype: ty ),* ) -> $rettype: tt ; )+ ) => {

#[cfg(target_arch = "wasm32")]
#[cfg(all(target_arch = "wasm32", not(feature = "wasi")))]
#[link(wasm_import_module = "ic0")]
extern "C" {
$(pub(super) fn $name($( $argname: $argtype, )*) -> _ic0_module_ret!($rettype) ;)*
}

$(
#[cfg(not(target_arch = "wasm32"))]
#[cfg(not(all(target_arch = "wasm32", not(feature = "wasi"))))]
pub(super) unsafe fn $name($( $argname: $argtype, )*) -> _ic0_module_ret!($rettype) {
let _ = ( $( $argname, )* ); // make sure the arguments are used.
panic!("{} should only be called inside canisters.", stringify!( $name ));
Expand Down
25 changes: 25 additions & 0 deletions src/ic-cdk/src/api/wasi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
type Fd = u32;
type Size = usize;
pub type Errno = i32;
pub type Rval = u32;

#[repr(C)]
pub struct Ciovec {
buf: *const u8,
buf_len: Size,
}

#[link(wasm_import_module = "wasi_snapshot_preview1")]
extern "C" {
pub fn fd_write(fd: Fd, iovs_ptr: *const Ciovec, iovs_len: Size, nwritten: *mut Size) -> Errno;
pub fn proc_exit(rval: Rval);
}
pub unsafe fn print(text: &str) -> Errno {
let ciovec = Ciovec {
buf: text.as_ptr(),
buf_len: text.len(),
};
let ciovecs = [ciovec];
let mut nwritten = 0;
fd_write(1, ciovecs.as_ptr(), ciovecs.len(), &mut nwritten)
}
2 changes: 1 addition & 1 deletion src/ic-cdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn block_on<F: 'static + std::future::Future<Output = ()>>(future: F) {
}

/// Format and then print the formatted message
#[cfg(target_arch = "wasm32")]
#[cfg(all(target_arch = "wasm32", not(feature = "wasi")))]
#[macro_export]
macro_rules! println {
($fmt:expr) => (ic_cdk::print(format!($fmt)));
Expand Down