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!: ic-cdk-bindgen rewrite #486

Merged
merged 6 commits into from
May 1, 2024
Merged
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
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion examples/counter/src/counter_rs/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::cell::{Cell, RefCell};

thread_local! {
static COUNTER: RefCell<candid::Nat> = RefCell::new(candid::Nat::from(0u8));
static OWNER: Cell<Principal> = Cell::new(Principal::from_slice(&[]));
static OWNER: Cell<Principal> = const {Cell::new(Principal::from_slice(&[]))};
}

#[init]
Expand Down
13 changes: 4 additions & 9 deletions examples/counter/src/inter2_rs/build.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
use ic_cdk_bindgen::{Builder, Config};
use std::path::PathBuf;

fn main() {
let manifest_dir =
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("Cannot find manifest dir"));
let inter_mo = Config::new("inter_mo");
let mut builder = Builder::new();
builder.add(inter_mo);
builder.build(Some(manifest_dir.join("declarations")));
println!("cargo:rerun-if-changed=build.rs");
ic_cdk_bindgen::Builder::new("inter_mo")
.generate_consumer()
.unwrap();
}
6 changes: 4 additions & 2 deletions examples/counter/src/inter2_rs/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use ic_cdk::update;

mod declarations;
use declarations::inter_mo::inter_mo;
mod inter_mo {
include!(concat!(env!("OUT_DIR"), "/consumer/inter_mo.rs"));
}
use inter_mo::inter_mo;

#[update]
async fn read() -> candid::Nat {
Expand Down
13 changes: 4 additions & 9 deletions examples/counter/src/inter_rs/build.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
use ic_cdk_bindgen::{Builder, Config};
use std::path::PathBuf;

fn main() {
let manifest_dir =
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("Cannot find manifest dir"));
let counter = Config::new("counter_mo");
let mut builder = Builder::new();
builder.add(counter);
builder.build(Some(manifest_dir.join("declarations")));
println!("cargo:rerun-if-changed=build.rs");
ic_cdk_bindgen::Builder::new("counter_mo")
.generate_consumer()
.unwrap();
}
6 changes: 4 additions & 2 deletions examples/counter/src/inter_rs/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use ic_cdk::update;

mod declarations;
use declarations::counter_mo::counter_mo;
mod counter_mo {
include!(concat!(env!("OUT_DIR"), "/consumer/counter_mo.rs"));
}
use counter_mo::counter_mo;

#[update]
async fn read() -> candid::Nat {
Expand Down
16 changes: 5 additions & 11 deletions examples/profile/src/profile_inter_rs/build.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
use ic_cdk_bindgen::{Builder, Config};
use std::path::PathBuf;

fn main() {
// A workaround to force always rerun build.rs
println!("cargo:rerun-if-changed=NULL");
let manifest_dir =
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("Cannot find manifest dir"));
let profile_rs = Config::new("profile_rs");
let mut builder = Builder::new();
builder.add(profile_rs);
builder.build(Some(manifest_dir.join("declarations")));
println!("cargo:rerun-if-changed=build.rs");
ic_cdk_bindgen::Builder::new("profile_rs")
.candid_path("../profile_rs/profile.did")
.generate_consumer()
.unwrap();
}
6 changes: 4 additions & 2 deletions examples/profile/src/profile_inter_rs/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use ic_cdk::update;

mod declarations;
use declarations::profile_rs::{profile_rs, Profile};
mod profile_rs {
include!(concat!(env!("OUT_DIR"), "/consumer/profile_rs.rs"));
}
use profile_rs::{profile_rs, Profile};

#[update(name = "getSelf")]
async fn get_self() -> Profile {
Expand Down
1 change: 1 addition & 0 deletions src/ic-cdk-bindgen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ candid.workspace = true
candid_parser.workspace = true
convert_case = "0.6"
pretty = "0.12"
thiserror = "1.0"
116 changes: 37 additions & 79 deletions src/ic-cdk-bindgen/src/code_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ use pretty::RcDoc;
use std::collections::BTreeSet;

#[derive(Clone)]
#[allow(dead_code)]
pub enum Target {
CanisterCall,
Agent,
CanisterStub,
Consumer,
Provider,
Type,
}

#[derive(Clone)]
pub struct Config {
candid_crate: String,
type_attributes: String,
canister_id: Option<candid::Principal>,
service_name: String,
target: Target,
Expand All @@ -24,21 +24,15 @@ impl Config {
pub fn new() -> Self {
Config {
candid_crate: "candid".to_string(),
type_attributes: "".to_string(),
canister_id: None,
service_name: "service".to_string(),
target: Target::CanisterCall,
target: Target::Consumer,
}
}
pub fn set_candid_crate(&mut self, name: String) -> &mut Self {
self.candid_crate = name;
self
}
/// Applies to all types for now
pub fn set_type_attributes(&mut self, attr: String) -> &mut Self {
self.type_attributes = attr;
self
}
/// Only generates SERVICE struct if canister_id is not provided
pub fn set_canister_id(&mut self, id: candid::Principal) -> &mut Self {
self.canister_id = Some(id);
Expand Down Expand Up @@ -208,17 +202,8 @@ fn pp_variant_fields<'a>(fs: &'a [Field], recs: &RecPoints) -> RcDoc<'a> {
enclose_space("{", fields, "}")
}

fn pp_defs<'a>(
config: &'a Config,
env: &'a TypeEnv,
def_list: &'a [&'a str],
recs: &'a RecPoints,
) -> RcDoc<'a> {
let derive = if config.type_attributes.is_empty() {
"#[derive(CandidType, Deserialize)]"
} else {
&config.type_attributes
};
fn pp_defs<'a>(env: &'a TypeEnv, def_list: &'a [&'a str], recs: &'a RecPoints) -> RcDoc<'a> {
let derive = "#[derive(CandidType, Deserialize)]";
lines(def_list.iter().map(|id| {
let ty = env.find_type(id).unwrap();
let name = ident(id, Some(Case::Pascal)).append(" ");
Expand Down Expand Up @@ -317,9 +302,9 @@ fn pp_function<'a>(config: &Config, id: &'a str, func: &'a Function) -> RcDoc<'a
let name = ident(id, Some(Case::Snake));
let empty = BTreeSet::new();
let arg_prefix = str(match config.target {
Target::CanisterCall => "&self",
Target::Agent => "&self",
Target::CanisterStub => unimplemented!(),
Target::Consumer => "&self",
Target::Provider => unimplemented!(),
Target::Type => unimplemented!(),
});
let args = concat(
std::iter::once(arg_prefix).chain(
Expand All @@ -331,24 +316,13 @@ fn pp_function<'a>(config: &Config, id: &'a str, func: &'a Function) -> RcDoc<'a
",",
);
let rets = match config.target {
Target::CanisterCall => enclose(
Target::Consumer => enclose(
"(",
RcDoc::concat(func.rets.iter().map(|ty| pp_ty(ty, &empty).append(","))),
")",
),
Target::Agent => match func.rets.len() {
0 => str("()"),
1 => pp_ty(&func.rets[0], &empty),
_ => enclose(
"(",
RcDoc::intersperse(
func.rets.iter().map(|ty| pp_ty(ty, &empty)),
RcDoc::text(", "),
),
")",
),
},
Target::CanisterStub => unimplemented!(),
Target::Provider => unimplemented!(),
Target::Type => unimplemented!(),
};
let sig = kwd("pub async fn")
.append(name)
Expand All @@ -357,40 +331,25 @@ fn pp_function<'a>(config: &Config, id: &'a str, func: &'a Function) -> RcDoc<'a
.append(enclose("Result<", rets, "> "));
let method = id.escape_debug().to_string();
let body = match config.target {
Target::CanisterCall => {
Target::Consumer => {
let args = RcDoc::concat((0..func.args.len()).map(|i| RcDoc::text(format!("arg{i},"))));
str("ic_cdk::call(self.0, \"")
.append(method)
.append("\", ")
.append(enclose("(", args, ")"))
.append(").await")
}
Target::Agent => {
let is_query = func.is_query();
let builder_method = if is_query { "query" } else { "update" };
let call = if is_query { "call" } else { "call_and_wait" };
let args = RcDoc::intersperse(
(0..func.args.len()).map(|i| RcDoc::text(format!("&arg{i}"))),
RcDoc::text(", "),
);
let blob = str("Encode!").append(enclose("(", args, ")?;"));
let rets = RcDoc::concat(
func.rets
.iter()
.map(|ty| str(", ").append(pp_ty(ty, &empty))),
);
str("let args = ").append(blob).append(RcDoc::hardline())
.append(format!("let bytes = self.1.{builder_method}(&self.0, \"{method}\").with_arg(args).{call}().await?;"))
.append(RcDoc::hardline())
.append("Ok(Decode!(&bytes").append(rets).append(")?)")
}
Target::CanisterStub => unimplemented!(),
Target::Provider => unimplemented!(),
Target::Type => unimplemented!(),
};
sig.append(enclose_space("{", body, "}"))
}

fn pp_actor<'a>(config: &'a Config, env: &'a TypeEnv, actor: &'a Type) -> RcDoc<'a> {
// TODO trace to service before we figure out what canister means in Rust
// TODO: currently we only generate actor for consumer
if matches!(config.target, Target::Type | Target::Provider) {
return RcDoc::nil();
}
let serv = env.as_service(actor).unwrap();
let body = RcDoc::intersperse(
serv.iter().map(|(id, func)| {
Expand All @@ -401,17 +360,14 @@ fn pp_actor<'a>(config: &'a Config, env: &'a TypeEnv, actor: &'a Type) -> RcDoc<
);
let struct_name = config.service_name.to_case(Case::Pascal);
let service_def = match config.target {
Target::CanisterCall => format!("pub struct {}(pub Principal);", struct_name),
Target::Agent => format!(
"pub struct {}<'a>(pub Principal, pub &'a ic_agent::Agent);",
struct_name
),
Target::CanisterStub => unimplemented!(),
Target::Consumer => format!("pub struct {}(pub Principal);", struct_name),
Target::Provider => unimplemented!(),
Target::Type => unimplemented!(),
};
let service_impl = match config.target {
Target::CanisterCall => format!("impl {} ", struct_name),
Target::Agent => format!("impl<'a> {}<'a> ", struct_name),
Target::CanisterStub => unimplemented!(),
Target::Consumer => format!("impl {} ", struct_name),
Target::Provider => unimplemented!(),
Target::Type => unimplemented!(),
};
let res = RcDoc::text(service_def)
.append(RcDoc::hardline())
Expand All @@ -430,12 +386,12 @@ fn pp_actor<'a>(config: &'a Config, env: &'a TypeEnv, actor: &'a Type) -> RcDoc<
slice, cid
));
let instance = match config.target {
Target::CanisterCall => format!(
"pub const {} : {} = {}(CANISTER_ID);",
Target::Consumer => format!(
"#[allow(non_upper_case_globals)]\npub const {} : {} = {}(CANISTER_ID);",
config.service_name, struct_name, struct_name
),
Target::Agent => "".to_string(),
Target::CanisterStub => unimplemented!(),
Target::Provider => unimplemented!(),
Target::Type => unimplemented!(),
};
res.append(id).append(RcDoc::hardline()).append(instance)
} else {
Expand All @@ -447,16 +403,16 @@ pub fn compile(config: &Config, env: &TypeEnv, actor: &Option<Type>) -> String {
let header = format!(
r#"// This is an experimental feature to generate Rust binding from Candid.
// You may want to manually adjust some of the types.
#![allow(dead_code, unused_imports)]
#[allow(unused_imports)]
use {}::{{self, CandidType, Deserialize, Principal, Encode, Decode}};
"#,
config.candid_crate
);
let header = header
+ match &config.target {
Target::CanisterCall => "use ic_cdk::api::call::CallResult as Result;\n",
Target::Agent => "type Result<T> = std::result::Result<T, ic_agent::AgentError>;\n",
Target::CanisterStub => "",
Target::Consumer => "use ic_cdk::api::call::CallResult as Result;\n",
Target::Provider => "",
Target::Type => "",
};
let (env, actor) = nominalize_all(env, actor);
let def_list: Vec<_> = if let Some(actor) = &actor {
Expand All @@ -465,7 +421,9 @@ use {}::{{self, CandidType, Deserialize, Principal, Encode, Decode}};
env.0.iter().map(|pair| pair.0.as_ref()).collect()
};
let recs = infer_rec(&env, &def_list).unwrap();
let defs = pp_defs(config, &env, &def_list, &recs);

let defs = pp_defs(&env, &def_list, &recs);

let doc = match &actor {
None => defs,
Some(actor) => {
Expand Down
10 changes: 10 additions & 0 deletions src/ic-cdk-bindgen/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use thiserror::Error;

#[derive(Error, Debug)]
pub enum IcCdkBindgenError {
#[error("Custom error: {0}")]
Custom(String),

#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
}
Loading
Loading