diff --git a/Cargo.toml b/Cargo.toml index 45506db323..e35f8aef58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,5 @@ [workspace] members = [ - # "src/compiler/typescript_to_rust/azle_generate", "src/compiler/typescript_to_rust/azle_generate_rearchitecture", - "src/compiler/typescript_to_rust/canister_methods" - # "src/compiler/typescript_to_rust/azle_vm_value_derive" + "src/compiler/typescript_to_rust/canister_methods", ] diff --git a/src/compiler/compile_rust_code.ts b/src/compiler/compile_rust_code.ts index 7c3b36b8a2..ef9fa33ee7 100644 --- a/src/compiler/compile_rust_code.ts +++ b/src/compiler/compile_rust_code.ts @@ -14,7 +14,7 @@ export async function compileRustCode( ) { await time(`[2/2] 🚧 Building Wasm binary...`, 'inline', async () => { execSync( - `cd ${canisterPath} && ${GLOBAL_AZLE_RUST_BIN_DIR}/cargo build --target wasm32-wasi --package azle_generate_rearchitecture --release`, + `cd ${canisterPath} && ${GLOBAL_AZLE_RUST_BIN_DIR}/cargo build --target wasm32-wasi --manifest-path azle_generate_rearchitecture/Cargo.toml --release`, { stdio, env: { diff --git a/src/compiler/index.ts b/src/compiler/index.ts index b46dd405c5..5166b5b9bf 100644 --- a/src/compiler/index.ts +++ b/src/compiler/index.ts @@ -60,7 +60,6 @@ async function azle() { candidPath ); await compileRustCode(canisterName, canisterPath, stdioType); - gzipWasmBinary(wasmFilePath, stdioType); } ); diff --git a/src/compiler/typescript_to_rust/azle_generate/Cargo.toml b/src/compiler/typescript_to_rust/azle_generate/Cargo.toml deleted file mode 100644 index 2dc0f46791..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "azle_generate" -version = "0.0.0" -edition = "2018" - -[dependencies] -quote = "1.0.26" -syn = "2.0.15" -proc-macro2 = "1.0.56" -swc_common = "0.27.10" -swc_ecma_parser = "0.117.4" -swc_ecma_ast = "0.90.10" -annotate-snippets = "0.9.1" -cdk_framework = { git = "https://github.com/demergent-labs/cdk_framework", rev = "fcdbad3e85d8566a7e0f7a8afdbdfc4463fb03c8" } -# cdk_framework = { path = "/home/cdk_framework" } -serde = "1.0.160" -serde_json = "1.0.96" -prettyplease = "0.2.4" diff --git a/src/compiler/typescript_to_rust/azle_generate/src/alias_table/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/alias_table/mod.rs deleted file mode 100644 index 2749761234..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/alias_table/mod.rs +++ /dev/null @@ -1,174 +0,0 @@ -use std::collections::HashMap; - -use serde::{Deserialize, Serialize}; - -pub type Filename = String; -pub type AliasTables = HashMap; - -pub type AliasLists = HashMap>; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct AliasTable { - pub alias: Vec, - pub blob: Vec, - pub bool: Vec, - pub call_result: Vec, - pub empty: Vec, - pub float32: Vec, - pub float64: Vec, - pub func: Vec, - pub guard_result: Vec, - pub heartbeat_decorator: Vec, - pub init_decorator: Vec, - pub inspect_message_decorator: Vec, - pub int: Vec, - pub int8: Vec, - pub int16: Vec, - pub int32: Vec, - pub int64: Vec, - pub manual: Vec, - pub nat: Vec, - pub nat8: Vec, - pub nat16: Vec, - pub nat32: Vec, - pub nat64: Vec, - pub null: Vec, - pub opt: Vec, - pub oneway_mode: Vec, - pub post_upgrade_decorator: Vec, - pub pre_upgrade_decorator: Vec, - pub principal: Vec, - pub query_decorator: Vec, - pub query_mode: Vec, - pub record: Vec, - pub reserved: Vec, - pub service: Vec, - pub service_query_decorator: Vec, - pub service_update_decorator: Vec, - pub stable_b_tree_map: Vec, - pub text: Vec, - pub tuple: Vec, - pub update_decorator: Vec, - pub update_mode: Vec, - pub variant: Vec, - pub vec: Vec, - pub void: Vec, -} - -impl AliasTable { - // We want thing that would show up as type aliases. That means we need to - // look at the alias name and if it maps to something that can't become an - // alias then it's not aliasable. - // For example: - // export type MyRecord = azle.Record<{}>; - // should parsed as a record and not a type alias. azle.Record should be in - // self.record so self.record is included in this list so that if - // azle.Record is searched for we will find it and return false (azle.Record is not aliasable) - // On the otherhand: - // export type MyBoolVec = azle.Vec; - // should be parsed as a type alias. - // You will notice that self.vec is not included in this list. - // In fact you will notice that the only things not on this list are Vec and Opt - pub fn is_aliasable(&self, alias: &String) -> bool { - ![ - &self.alias, - &self.blob, - &self.bool, - &self.call_result, - &self.empty, - &self.float32, - &self.float64, - &self.func, - &self.guard_result, - &self.heartbeat_decorator, - &self.init_decorator, - &self.inspect_message_decorator, - &self.init_decorator, - &self.inspect_message_decorator, - &self.int, - &self.int8, - &self.int16, - &self.int32, - &self.int64, - &self.manual, - &self.nat, - &self.nat8, - &self.nat16, - &self.nat32, - &self.nat64, - &self.null, - &self.oneway_mode, - &self.post_upgrade_decorator, - &self.pre_upgrade_decorator, - &self.principal, - &self.query_decorator, - &self.query_mode, - &self.record, - &self.reserved, - &self.service, - &self.service_query_decorator, - &self.service_update_decorator, - &self.stable_b_tree_map, - &self.text, - &self.tuple, - &self.update_decorator, - &self.update_mode, - &self.variant, - &self.void, - ] - .iter() - .any(|list| list.contains(alias)) - } - pub fn search(&self, alias: &String) -> bool { - [ - &self.alias, - &self.blob, - &self.bool, - &self.call_result, - &self.empty, - &self.float32, - &self.float64, - &self.func, - &self.guard_result, - &self.heartbeat_decorator, - &self.init_decorator, - &self.inspect_message_decorator, - &self.init_decorator, - &self.inspect_message_decorator, - &self.int, - &self.int8, - &self.int16, - &self.int32, - &self.int64, - &self.manual, - &self.nat, - &self.nat8, - &self.nat16, - &self.nat32, - &self.nat64, - &self.null, - &self.opt, - &self.oneway_mode, - &self.post_upgrade_decorator, - &self.pre_upgrade_decorator, - &self.principal, - &self.query_decorator, - &self.query_mode, - &self.record, - &self.reserved, - &self.service, - &self.service_query_decorator, - &self.service_update_decorator, - &self.stable_b_tree_map, - &self.text, - &self.tuple, - &self.update_decorator, - &self.update_mode, - &self.variant, - &self.vec, - &self.void, - ] - .iter() - .any(|list| list.contains(alias)) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/async_await_result_handler.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/async_await_result_handler.rs deleted file mode 100644 index 2f30134365..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/async_await_result_handler.rs +++ /dev/null @@ -1,118 +0,0 @@ -use cdk_framework::{ - act::node::{canister_method::QueryOrUpdateMethod, Context}, - traits::ToTypeAnnotation, -}; -use proc_macro2::TokenStream; -use quote::quote; - -use crate::ts_keywords; - -pub fn generate(methods: &Vec) -> TokenStream { - let match_arms = generate_match_arms(methods); - quote! { - fn async_await_result_handler( - boa_context: &mut boa_engine::Context, - boa_return_value: &boa_engine::JsValue, - uuid: &str, - method_name: &str, - manual: bool, - ) -> Result { - let boa_return_value_object = match boa_return_value.as_object() { - Some(object) => object, - None => return Ok(boa_return_value.clone()), - }; - - if !boa_return_value_object.is_promise() { - return Ok(boa_return_value.clone()); - } - - boa_context.run_jobs(); - - let js_promise = boa_engine::object::builtins::JsPromise::from_object( - boa_return_value_object.clone(), - ) - .map_err(|js_error| js_error.to_std_string(&mut *boa_context))?; - - let state = js_promise - .state() - .map_err(|js_error| js_error.to_std_string(&mut *boa_context))?; - - return match &state { - boa_engine::builtins::promise::PromiseState::Fulfilled(js_value) => { - PROMISE_MAP_REF_CELL.with(|promise_map_ref_cell| { - let mut promise_map = promise_map_ref_cell.borrow_mut(); - - promise_map.remove(uuid); - }); - - if manual == true { - return Ok(boa_return_value.clone()); - } - - match method_name { - #(#match_arms)* - "_AZLE_TIMER" => {} - _ => { - return Err(format!( - "\nUncaught ReferenceError: {} is not defined", - method_name - )) - } - }; - - return Ok(boa_return_value.clone()); - } - boa_engine::builtins::promise::PromiseState::Rejected(js_value) => { - PROMISE_MAP_REF_CELL.with(|promise_map_ref_cell| { - let mut promise_map = promise_map_ref_cell.borrow_mut(); - - promise_map.remove(uuid); - }); - - return Err(js_value.clone().to_std_string(&mut *boa_context)); - } - boa_engine::builtins::promise::PromiseState::Pending => { - PROMISE_MAP_REF_CELL.with(|promise_map_ref_cell| { - let mut promise_map = promise_map_ref_cell.borrow_mut(); - - promise_map.insert(uuid.to_string(), boa_return_value.clone()); - }); - - return Ok(boa_return_value.clone()); - } - }; - } - } -} - -fn generate_match_arms(methods: &Vec) -> Vec { - methods - .iter() - .filter(|method| method.is_async) - .map(|method| generate_match_arm(method)) - .collect() -} - -fn generate_match_arm(method: &QueryOrUpdateMethod) -> TokenStream { - let name = &method.name; - let return_type = method.return_type.to_type_annotation( - &Context { - keyword_list: ts_keywords::ts_keywords(), - cdk_name: "azle".to_string(), - }, - name.clone(), - ); - - quote!( - #name => { - let reply_value: (#return_type) = js_value - .clone() - .try_from_vm_value(&mut *boa_context) - .map_err(|js_error: boa_engine::JsError| { - js_error.to_std_string(&mut *boa_context) - })?; - - ic_cdk::api::call::reply((reply_value,)); - } - ) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/accept_message.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/accept_message.rs deleted file mode 100644 index 064d781649..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/accept_message.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn accept_message( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::call::accept_message() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/arg_data_raw.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/arg_data_raw.rs deleted file mode 100644 index 1db0b47d0a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/arg_data_raw.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn arg_data_raw( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::call::arg_data_raw() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/arg_data_raw_size.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/arg_data_raw_size.rs deleted file mode 100644 index e9a2795f5b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/arg_data_raw_size.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn arg_data_raw_size( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - ic_cdk::api::call::arg_data_raw_size() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/mod.rs deleted file mode 100644 index b38d388da9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod post_await_state_management; -pub mod pre_await_state_management; -pub mod promise_fulfillment; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/post_await_state_management.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/post_await_state_management.rs deleted file mode 100644 index 6cf7126946..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/post_await_state_management.rs +++ /dev/null @@ -1,21 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - UUID_REF_CELL.with(|uuid_ref_cell| { - let mut uuid_mut = uuid_ref_cell.borrow_mut(); - - *uuid_mut = uuid.clone(); - }); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = method_name.clone() - }); - - MANUAL_REF_CELL.with(|manual_ref_cell| { - let mut manual_mut = manual_ref_cell.borrow_mut(); - - *manual_mut = manual; - }); - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/pre_await_state_management.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/pre_await_state_management.rs deleted file mode 100644 index 7c9fa3bc19..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/pre_await_state_management.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - let uuid = UUID_REF_CELL.with(|uuid_ref_cell| uuid_ref_cell.borrow().clone()); - let method_name = METHOD_NAME_REF_CELL.with(|method_name_ref_cell| method_name_ref_cell.borrow().clone()); - let manual = MANUAL_REF_CELL.with(|manual_ref_cell| manual_ref_cell.borrow().clone()); - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/promise_fulfillment.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/promise_fulfillment.rs deleted file mode 100644 index 98cccc7ff1..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/async_call/promise_fulfillment.rs +++ /dev/null @@ -1,92 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - let call_result_js_value = match call_result { - Ok(value) => { - let js_value = match value.try_into_vm_value(&mut *boa_context) { - Ok(js_value) => js_value, - Err(vmc_err) => { - js_promise_resolvers - .reject - .call( - &boa_engine::JsValue::undefined(), - &[vmc_err.to_js_error(None).to_opaque(&mut *boa_context)], - &mut *boa_context, - ) - .unwrap_or_trap(&mut *boa_context) - } - }; - - let canister_result_js_object = - boa_engine::object::ObjectInitializer::new(&mut *boa_context) - .property("Ok", js_value, boa_engine::property::Attribute::all()) - .build(); - - let canister_result_js_value = canister_result_js_object.into(); - - canister_result_js_value - } - Err(err) => { - let js_value = match format!( - "Rejection code {rejection_code}, {error_message}", - rejection_code = (err.0 as i32).to_string(), - error_message = err.1 - ) - .try_into_vm_value(&mut *boa_context) - { - Ok(js_value) => js_value, - Err(vmc_err) => { - js_promise_resolvers - .reject - .call( - &boa_engine::JsValue::undefined(), - &[vmc_err.to_js_error(None).to_opaque(&mut *boa_context)], - &mut *boa_context, - ) - .unwrap_or_trap(&mut *boa_context) - } - }; - - let canister_result_js_object = - boa_engine::object::ObjectInitializer::new(&mut *boa_context) - .property("Err", js_value, boa_engine::property::Attribute::all()) - .build(); - - let canister_result_js_value = canister_result_js_object.into(); - - canister_result_js_value - } - }; - - js_promise_resolvers - .resolve - .call( - &boa_engine::JsValue::undefined(), - &[call_result_js_value], - &mut *boa_context, - ) - .unwrap_or_trap(&mut *boa_context); - - let main_promise = PROMISE_MAP_REF_CELL.with(|promise_map_ref_cell| { - let promise_map = promise_map_ref_cell.borrow().clone(); - - let main_promise = promise_map - .get(&uuid) - .unwrap_or_trap("ReferenceError: top-level promise is not defined"); - - main_promise.clone() - }); - - async_await_result_handler( - &mut *boa_context, - &main_promise, - &uuid, - &method_name, - manual, - ) - .unwrap_or_trap(&mut *boa_context); - }); - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/call_raw.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/call_raw.rs deleted file mode 100644 index 37c9649444..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/call_raw.rs +++ /dev/null @@ -1,56 +0,0 @@ -use super::async_call::{ - post_await_state_management, pre_await_state_management, promise_fulfillment, -}; - -pub fn generate() -> proc_macro2::TokenStream { - let pre_await_state_management = pre_await_state_management::generate(); - let post_await_state_management = post_await_state_management::generate(); - let promise_fulfillment = promise_fulfillment::generate(); - - quote::quote! { - fn call_raw( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let (js_promise, js_promise_resolvers) = - boa_engine::object::builtins::JsPromise::new_pending(context); - - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - let method_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'method' was not provided".to_js_error(None))? - .clone(); - let args_raw_js_value = aargs - .get(2) - .ok_or_else(|| "An argument for 'argsRaw' was not provided".to_js_error(None))? - .clone(); - let payment_js_value = aargs - .get(3) - .ok_or_else(|| "An argument for 'payment' was not provided".to_js_error(None))? - .clone(); - - let canister_id: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - let method: String = method_js_value.try_from_vm_value(&mut *context)?; - let args_raw: Vec = args_raw_js_value.try_from_vm_value(&mut *context)?; - let payment: u64 = payment_js_value.try_from_vm_value(&mut *context)?; - - ic_cdk::spawn(async move { - #pre_await_state_management - - let call_result = - ic_cdk::api::call::call_raw(canister_id, &method, &args_raw, payment).await; - - #post_await_state_management - - #promise_fulfillment - }); - - Ok(js_promise.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/call_raw128.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/call_raw128.rs deleted file mode 100644 index 0a6a87402b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/call_raw128.rs +++ /dev/null @@ -1,56 +0,0 @@ -use super::async_call::{ - post_await_state_management, pre_await_state_management, promise_fulfillment, -}; - -pub fn generate() -> proc_macro2::TokenStream { - let pre_await_state_management = pre_await_state_management::generate(); - let post_await_state_management = post_await_state_management::generate(); - let promise_fulfillment = promise_fulfillment::generate(); - - quote::quote! { - fn call_raw128( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let (js_promise, js_promise_resolvers) = - boa_engine::object::builtins::JsPromise::new_pending(context); - - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - let method_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'method' was not provided".to_js_error(None))? - .clone(); - let args_raw_js_value = aargs - .get(2) - .ok_or_else(|| "An argument for 'argsRaw' was not provided".to_js_error(None))? - .clone(); - let payment_js_value = aargs - .get(3) - .ok_or_else(|| "An argument for 'payment' was not provided".to_js_error(None))? - .clone(); - - let canister_id: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - let method: String = method_js_value.try_from_vm_value(&mut *context)?; - let args_raw: Vec = args_raw_js_value.try_from_vm_value(&mut *context)?; - let payment: u128 = payment_js_value.try_from_vm_value(&mut *context)?; - - ic_cdk::spawn(async move { - #pre_await_state_management - - let call_result = - ic_cdk::api::call::call_raw128(canister_id, &method, &args_raw, payment).await; - - #post_await_state_management - - #promise_fulfillment - }); - - Ok(js_promise.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/caller.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/caller.rs deleted file mode 100644 index 63498c48b9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/caller.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn caller( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - ic_cdk::api::caller() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/candid_decode.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/candid_decode.rs deleted file mode 100644 index e9c844b074..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/candid_decode.rs +++ /dev/null @@ -1,26 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn candid_decode( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let candid_encoded: Vec = aargs - .get(0) - .ok_or_else(|| "An argument for 'candidEncoded' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let candid_args: candid::IDLArgs = candid::IDLArgs::from_bytes(&candid_encoded) - .map_err(|err| { - boa_engine::error::JsNativeError::error().with_message(err.to_string().as_str()) - })?; - - let candid_string = candid_args.to_string(); - - candid_string - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/candid_encode.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/candid_encode.rs deleted file mode 100644 index 4bd821bb81..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/candid_encode.rs +++ /dev/null @@ -1,31 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn candid_encode( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let candid_string: String = aargs - .get(0) - .ok_or_else(|| "An argument for 'candidString' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let candid_args: candid::IDLArgs = - candid_string.parse().map_err(|err: candid::error::Error| { - boa_engine::error::JsNativeError::error().with_message(err.to_string().as_str()) - })?; - let candid_encoded: Vec = - candid_args - .to_bytes() - .map_err(|err: candid::error::Error| { - boa_engine::error::JsNativeError::error() - .with_message(err.to_string().as_str()) - })?; - - candid_encoded - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_balance.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_balance.rs deleted file mode 100644 index fead530891..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_balance.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn canister_balance( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::canister_balance() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_balance128.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_balance128.rs deleted file mode 100644 index 062daaa708..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_balance128.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn canister_balance128( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - ic_cdk::api::canister_balance128() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_version.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_version.rs deleted file mode 100644 index 305ab1a178..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/canister_version.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn canister_version( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - ic_cdk::api::canister_version() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/clear_timer.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/clear_timer.rs deleted file mode 100644 index 3bf83f4518..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/clear_timer.rs +++ /dev/null @@ -1,19 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn clear_timer( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let timer_id: ic_cdk_timers::TimerId = aargs - .get(0) - .ok_or_else(|| "An argument for 'id' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk_timers::clear_timer(timer_id); - - Ok(boa_engine::JsValue::Undefined) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/data_certificate.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/data_certificate.rs deleted file mode 100644 index 7e8b2a5292..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/data_certificate.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn data_certificate( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::data_certificate() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/id.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/id.rs deleted file mode 100644 index 12496d15dd..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/id.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn id( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::id() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/instruction_counter.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/instruction_counter.rs deleted file mode 100644 index da81f51dcf..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/instruction_counter.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn instruction_counter( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - ic_cdk::api::instruction_counter() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/is_controller.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/is_controller.rs deleted file mode 100644 index 846d32705e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/is_controller.rs +++ /dev/null @@ -1,19 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn is_controller( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - let principal: candid::Principal = aargs - .get(0) - .ok_or_else(|| "An argument for 'principal' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk::api::is_controller(&principal) - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/method_name.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/method_name.rs deleted file mode 100644 index 67ecbd4dfc..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/method_name.rs +++ /dev/null @@ -1,11 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn method_name( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - _context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - Ok(ic_cdk::api::call::method_name().into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/mod.rs deleted file mode 100644 index 34df742972..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/mod.rs +++ /dev/null @@ -1,156 +0,0 @@ -use cdk_framework::act::node::{candid::Service, canister_method::QueryOrUpdateMethod}; - -use crate::StableBTreeMapNode; - -mod accept_message; -mod arg_data_raw; -mod arg_data_raw_size; -mod async_call; -mod call_raw; -mod call_raw128; -mod caller; -mod candid_decode; -mod candid_encode; -mod canister_balance; -mod canister_balance128; -mod canister_version; -mod clear_timer; -mod data_certificate; -mod id; -mod instruction_counter; -mod is_controller; -mod method_name; -mod msg_cycles_accept; -mod msg_cycles_accept128; -mod msg_cycles_available; -mod msg_cycles_available128; -mod msg_cycles_refunded; -mod msg_cycles_refunded128; -mod notify_raw; -mod performance_counter; -mod print; -mod reject; -mod reject_code; -mod reject_message; -mod reply; -mod reply_raw; -mod service; -mod set_certified_data; -mod set_timer; -mod set_timer_interval; -mod stable64_grow; -mod stable64_read; -mod stable64_size; -mod stable64_write; -mod stable_b_tree_map; -mod stable_bytes; -mod stable_grow; -mod stable_read; -mod stable_size; -mod stable_write; -mod time; -mod trap; - -pub fn generate( - query_and_update_methods: &Vec, - services: &Vec, - stable_b_tree_map_nodes: &Vec, -) -> proc_macro2::TokenStream { - let accept_message = accept_message::generate(); - let arg_data_raw = arg_data_raw::generate(); - let arg_data_raw_size = arg_data_raw_size::generate(); - let call_raw = call_raw::generate(); - let call_raw128 = call_raw128::generate(); - let caller = caller::generate(); - let candid_decode = candid_decode::generate(); - let candid_encode = candid_encode::generate(); - let canister_balance = canister_balance::generate(); - let canister_balance128 = canister_balance128::generate(); - let canister_version = canister_version::generate(); - let clear_timer = clear_timer::generate(); - let data_certificate = data_certificate::generate(); - let id = id::generate(); - let instruction_counter = instruction_counter::generate(); - let is_controller = is_controller::generate(); - let method_name = method_name::generate(); - let msg_cycles_accept = msg_cycles_accept::generate(); - let msg_cycles_accept128 = msg_cycles_accept128::generate(); - let msg_cycles_available = msg_cycles_available::generate(); - let msg_cycles_available128 = msg_cycles_available128::generate(); - let msg_cycles_refunded = msg_cycles_refunded::generate(); - let msg_cycles_refunded128 = msg_cycles_refunded128::generate(); - let notify_raw = notify_raw::generate(); - let performance_counter = performance_counter::generate(); - let print = print::generate(); - let reject = reject::generate(); - let reject_code = reject_code::generate(); - let reject_message = reject_message::generate(); - let reply = reply::generate(query_and_update_methods); - let reply_raw = reply_raw::generate(); - let service_functions = service::generate(services); - let set_certified_data = set_certified_data::generate(); - let set_timer = set_timer::generate(); - let set_timer_interval = set_timer_interval::generate(); - let stable64_grow = stable64_grow::generate(); - let stable64_read = stable64_read::generate(); - let stable64_size = stable64_size::generate(); - let stable64_write = stable64_write::generate(); - let stable_b_tree_map = stable_b_tree_map::generate(stable_b_tree_map_nodes); - let stable_bytes = stable_bytes::generate(); - let stable_grow = stable_grow::generate(); - let stable_read = stable_read::generate(); - let stable_size = stable_size::generate(); - let stable_write = stable_write::generate(); - let time = time::generate(); - let trap = trap::generate(); - - quote::quote! { - #accept_message - #arg_data_raw - #arg_data_raw_size - #call_raw - #call_raw128 - #caller - #candid_decode - #candid_encode - #canister_balance - #canister_balance128 - #canister_version - #clear_timer - #data_certificate - #id - #instruction_counter - #is_controller - #method_name - #msg_cycles_accept - #msg_cycles_accept128 - #msg_cycles_available - #msg_cycles_available128 - #msg_cycles_refunded - #msg_cycles_refunded128 - #notify_raw - #performance_counter - #print - #reject - #reject_code - #reject_message - #reply - #reply_raw - #(#service_functions)* - #set_certified_data - #set_timer - #set_timer_interval - #stable64_grow - #stable64_read - #stable64_size - #stable64_write - #stable_b_tree_map - #stable_bytes - #stable_grow - #stable_read - #stable_size - #stable_write - #time - #trap - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_accept.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_accept.rs deleted file mode 100644 index 71d321e0b0..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_accept.rs +++ /dev/null @@ -1,20 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn msg_cycles_accept( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let max_amount: u64 = aargs - .get(0) - .ok_or_else(|| "An argument for 'maxAmount' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let return_value: boa_engine::bigint::JsBigInt = - ic_cdk::api::call::msg_cycles_accept(max_amount).into(); - - Ok(return_value.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_accept128.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_accept128.rs deleted file mode 100644 index 5c287d1f2f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_accept128.rs +++ /dev/null @@ -1,22 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn msg_cycles_accept128( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let max_amount: u128 = aargs - .get(0) - .ok_or_else(|| "An argument for 'maxAmount' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let return_value = - boa_engine::bigint::JsBigInt::new(boa_engine::bigint::RawBigInt::from( - ic_cdk::api::call::msg_cycles_accept128(max_amount), - )); - - Ok(return_value.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_available.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_available.rs deleted file mode 100644 index 1f2e6b0005..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_available.rs +++ /dev/null @@ -1,14 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn msg_cycles_available( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - _context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let return_value: boa_engine::bigint::JsBigInt = - ic_cdk::api::call::msg_cycles_available().into(); - - Ok(return_value.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_available128.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_available128.rs deleted file mode 100644 index d191163ea7..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_available128.rs +++ /dev/null @@ -1,16 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn msg_cycles_available128( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - _context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - // TODO: This extra conversion may not be necessary once - // https://github.com/boa-dev/boa/issues/1970 is implemented. - let return_value: boa_engine::bigint::JsBigInt = - ic_cdk::api::call::msg_cycles_available().into(); - - Ok(return_value.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_refunded.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_refunded.rs deleted file mode 100644 index e00c598895..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_refunded.rs +++ /dev/null @@ -1,14 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn msg_cycles_refunded( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - _context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let return_value: boa_engine::bigint::JsBigInt = - ic_cdk::api::call::msg_cycles_refunded().into(); - - Ok(return_value.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_refunded128.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_refunded128.rs deleted file mode 100644 index 6fb6940fd6..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/msg_cycles_refunded128.rs +++ /dev/null @@ -1,15 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn msg_cycles_refunded128( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - _context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let return_value = boa_engine::bigint::JsBigInt::new( - boa_engine::bigint::RawBigInt::from(ic_cdk::api::call::msg_cycles_refunded128()), - ); - - Ok(return_value.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/notify_raw.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/notify_raw.rs deleted file mode 100644 index a51318c161..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/notify_raw.rs +++ /dev/null @@ -1,43 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn notify_raw( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - let method_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'method' was not provided".to_js_error(None))? - .clone(); - let args_raw_js_value = aargs - .get(2) - .ok_or_else(|| "An argument for 'argsRaw' was not provided".to_js_error(None))? - .clone(); - let payment_js_value = aargs - .get(3) - .ok_or_else(|| "An argument for 'payment' was not provided".to_js_error(None))? - .clone(); - - let canister_id_principal: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - let method_string: String = method_js_value.try_from_vm_value(&mut *context)?; - let args_raw_vec: Vec = args_raw_js_value.try_from_vm_value(&mut *context)?; - let payment: u128 = payment_js_value.try_from_vm_value(&mut *context)?; - - let notify_result = ic_cdk::api::call::notify_raw( - canister_id_principal, - &method_string, - &args_raw_vec, - payment, - ); - - notify_result - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/performance_counter.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/performance_counter.rs deleted file mode 100644 index 54cd55934d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/performance_counter.rs +++ /dev/null @@ -1,20 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn performance_counter( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let counter_type: u32 = aargs - .get(0) - .ok_or_else(|| "An argument for 'counterType' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(context)?; - - let return_value: boa_engine::bigint::JsBigInt = - ic_cdk::api::call::performance_counter(counter_type).into(); - - Ok(return_value.into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/print.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/print.rs deleted file mode 100644 index 956644600b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/print.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn print( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - _context: &mut boa_engine::Context - ) -> boa_engine::JsResult { - ic_cdk::println!("{:#?}", aargs); - - return Ok(boa_engine::JsValue::Undefined); - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject.rs deleted file mode 100644 index b59f800f58..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject.rs +++ /dev/null @@ -1,19 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn reject( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let message: String = aargs - .get(0) - .ok_or_else(|| "An argument for 'message' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk::api::call::reject(&message) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject_code.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject_code.rs deleted file mode 100644 index 87b6fb7097..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject_code.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn reject_code( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::call::reject_code() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject_message.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject_message.rs deleted file mode 100644 index 5751440761..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reject_message.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn reject_message( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::call::reject_message() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reply.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reply.rs deleted file mode 100644 index fbcda05b8d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reply.rs +++ /dev/null @@ -1,64 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; - -use cdk_framework::{ - act::node::{canister_method::QueryOrUpdateMethod, Context}, - traits::ToTypeAnnotation, -}; - -use crate::ts_keywords; - -pub fn generate(methods: &Vec) -> TokenStream { - let match_arms = generate_match_arms(methods); - quote! { - fn reply( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let method_name = METHOD_NAME_REF_CELL - .with(|method_name_ref_cell| method_name_ref_cell.borrow().clone()); - - match &method_name[..] { - #(#match_arms)* - _ => { - Err(format!("Missing reply handler for method '{method_name}'") - .to_js_error(None)) - } - } - } - } -} - -fn generate_match_arms(methods: &Vec) -> Vec { - methods - .iter() - .filter(|method| method.is_manual) - .map(|method| generate_match_arm(method)) - .collect() -} - -fn generate_match_arm(method: &QueryOrUpdateMethod) -> TokenStream { - let name = &method.name; - let return_type = method.return_type.to_type_annotation( - &Context { - keyword_list: ts_keywords::ts_keywords(), - cdk_name: "azle".to_string(), - }, - name.clone(), - ); - - quote!( - #name => { - let reply_value: (#return_type) = aargs - .get(0) - .ok_or_else(|| "An argument for 'reply' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk::api::call::reply((reply_value,)) - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - ) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reply_raw.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reply_raw.rs deleted file mode 100644 index 129137c612..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/reply_raw.rs +++ /dev/null @@ -1,22 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; - -pub fn generate() -> TokenStream { - quote! { - fn reply_raw( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let buf_vec: Vec = aargs - .get(0) - .ok_or_else(|| "An argument for 'buf' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk::api::call::reply_raw(&buf_vec) - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call.rs deleted file mode 100644 index 211df4fae7..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call.rs +++ /dev/null @@ -1,63 +0,0 @@ -use cdk_framework::act::node::candid::{service::Method, Service}; -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; - -pub fn generate( - service: &Service, - method: &Method, - pre_await_state_management: &TokenStream, - post_await_state_management: &TokenStream, - promise_fulfillment: &TokenStream, -) -> TokenStream { - let call_function_name_string = format!("call_{}_{}", service.name, method.name); - let call_function_name_ident = format_ident!("{}", call_function_name_string); - let call_wrapper_fn_name = format_ident!("{}_wrapper", call_function_name_string); - let param_variables = super::generate_param_variables(method, &service.name); - let args = super::generate_args_list(method); - - quote! { - fn #call_wrapper_fn_name( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - - let args_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'args' was not provided".to_js_error(None))? - .clone(); - - let canister_id_principal: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - - let args_js_object = args_js_value - .as_object() - .ok_or_else(|| "'args' is not an object".to_js_error(None))?; - - #(#param_variables)* - - let (js_promise, js_promise_resolvers) = - boa_engine::object::builtins::JsPromise::new_pending(context); - - ic_cdk::spawn(async move { - #pre_await_state_management - - let call_result = #call_function_name_ident( - canister_id_principal, - #args, - ) - .await; - - #post_await_state_management - - #promise_fulfillment - }); - - Ok(js_promise.clone().into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call_with_payment.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call_with_payment.rs deleted file mode 100644 index 39d5169608..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call_with_payment.rs +++ /dev/null @@ -1,72 +0,0 @@ -use cdk_framework::act::node::candid::{service::Method, Service}; -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; - -pub fn generate( - service: &Service, - method: &Method, - pre_await_state_management: &TokenStream, - post_await_state_management: &TokenStream, - promise_fulfillment: &TokenStream, -) -> TokenStream { - let call_with_payment_function_name_string = - format!("call_with_payment_{}_{}", service.name, method.name); - let call_with_payment_function_name_ident = - format_ident!("{}", call_with_payment_function_name_string); - let call_with_payment_wrapper_fn_name = - format_ident!("{}_wrapper", call_with_payment_function_name_string); - let param_variables = super::generate_param_variables(method, &service.name); - let args = super::generate_args_list(method); - - let index_string = param_variables.len().to_string(); - - quote! { - fn #call_with_payment_wrapper_fn_name( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - - let args_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'args' was not provided".to_js_error(None))? - .clone(); - - let canister_id_principal: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - - let args_js_object = args_js_value - .as_object() - .ok_or_else(|| "'args' is not an object".to_js_error(None))?; - - #(#param_variables)* - - let cycles_js_value = args_js_object.get(#index_string, context)?; - let cycles: u64 = cycles_js_value.try_from_vm_value(&mut *context)?; - - let (js_promise, js_promise_resolvers) = - boa_engine::object::builtins::JsPromise::new_pending(context); - - ic_cdk::spawn(async move { - #pre_await_state_management - - let call_result = #call_with_payment_function_name_ident( - canister_id_principal, - #args, - cycles, - ) - .await; - - #post_await_state_management - - #promise_fulfillment - }); - - Ok(js_promise.clone().into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call_with_payment128.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call_with_payment128.rs deleted file mode 100644 index c40f013821..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/call_with_payment128.rs +++ /dev/null @@ -1,72 +0,0 @@ -use cdk_framework::act::node::candid::{service::Method, Service}; -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; - -pub fn generate( - service: &Service, - method: &Method, - pre_await_state_management: &TokenStream, - post_await_state_management: &TokenStream, - promise_fulfillment: &TokenStream, -) -> TokenStream { - let call_with_payment128_function_name_string = - format!("call_with_payment128_{}_{}", service.name, method.name); - let call_with_payment128_function_name_ident = - format_ident!("{}", call_with_payment128_function_name_string); - let call_with_payment128_wrapper_fn_name = - format_ident!("{}_wrapper", call_with_payment128_function_name_string); - let param_variables = super::generate_param_variables(method, &service.name); - let args = super::generate_args_list(method); - - let index_string = param_variables.len().to_string(); - - quote! { - fn #call_with_payment128_wrapper_fn_name( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - - let args_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'args' was not provided".to_js_error(None))? - .clone(); - - let canister_id_principal: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - - let args_js_object = args_js_value - .as_object() - .ok_or_else(|| "'args' is not an object".to_js_error(None))?; - - #(#param_variables)* - - let cycles_js_value = args_js_object.get(#index_string, context)?; - let cycles: u128 = cycles_js_value.try_from_vm_value(&mut *context)?; - - let (js_promise, js_promise_resolvers) = - boa_engine::object::builtins::JsPromise::new_pending(context); - - ic_cdk::spawn(async move { - #pre_await_state_management - - let call_result = #call_with_payment128_function_name_ident( - canister_id_principal, - #args, - cycles, - ) - .await; - - #post_await_state_management - - #promise_fulfillment - }); - - Ok(js_promise.clone().into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/mod.rs deleted file mode 100644 index ac4fd93f1d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/mod.rs +++ /dev/null @@ -1,109 +0,0 @@ -use cdk_framework::act::node::candid::Service; -use cdk_framework::act::{ - node::{candid::service::Method, Context}, - ToTypeAnnotation, -}; -use proc_macro2::{Ident, TokenStream}; -use quote::{format_ident, quote}; - -use super::async_call::{ - post_await_state_management, pre_await_state_management, promise_fulfillment, -}; -use crate::ts_keywords; - -mod call; -mod call_with_payment; -mod call_with_payment128; -mod notify; -mod notify_with_payment128; - -pub fn generate(services: &Vec) -> Vec { - services - .iter() - .map(|service| { - service - .methods - .iter() - .map(|method| { - let pre_await_state_management = pre_await_state_management::generate(); - let post_await_state_management = post_await_state_management::generate(); - let promise_fulfillment = promise_fulfillment::generate(); - - let call_function = call::generate( - service, - method, - &pre_await_state_management, - &post_await_state_management, - &promise_fulfillment, - ); - let call_with_payment_function = call_with_payment::generate( - service, - method, - &pre_await_state_management, - &post_await_state_management, - &promise_fulfillment, - ); - let call_with_payment128_function = call_with_payment128::generate( - service, - method, - &pre_await_state_management, - &post_await_state_management, - &promise_fulfillment, - ); - let notify_function = notify::generate(service, method); - let notify_with_payment128_function = - notify_with_payment128::generate(service, method); - - quote! { - #call_function - #call_with_payment_function - #call_with_payment128_function - #notify_function - #notify_with_payment128_function - } - }) - .collect() - }) - .collect::>>() - .concat() -} - -pub fn generate_param_variables(method: &Method, canister_name: &String) -> Vec { - method - .params - .iter() - .enumerate() - .map(|(index, param)| { - let param_name_js_value = format_ident!("{}_js_value", ¶m.get_prefixed_name()); - let param_name = format_ident!("{}", ¶m.get_prefixed_name()); - let param_type = param.to_type_annotation( - &Context { - keyword_list: ts_keywords::ts_keywords(), - cdk_name: "azle".to_string(), - }, - method.create_qualified_name(canister_name), - ); - - quote! { - let #param_name_js_value = args_js_object.get(#index, context)?; - let #param_name: #param_type = #param_name_js_value - .try_from_vm_value(&mut *context)?; - } - }) - .collect() -} - -pub fn generate_args_list(method: &Method) -> TokenStream { - let param_names: Vec = method - .params - .iter() - .map(|param| format_ident!("{}", ¶m.get_prefixed_name())) - .collect(); - - let comma = if param_names.len() == 1 { - quote! { , } - } else { - quote! {} - }; - return quote! { (#(#param_names),*#comma) }; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/notify.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/notify.rs deleted file mode 100644 index 7c06f8da9c..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/notify.rs +++ /dev/null @@ -1,47 +0,0 @@ -use cdk_framework::act::node::candid::service::{Method, Service}; -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; - -pub fn generate(service: &Service, method: &Method) -> TokenStream { - let function_name_string = format!("notify_{}_{}", service.name, method.name); - let real_function_name = format_ident!("{}", function_name_string); - let wrapper_fn_name = format_ident!("{}_wrapper", function_name_string); - let param_variables = super::generate_param_variables(method, &service.name); - let args = super::generate_args_list(method); - - quote! { - fn #wrapper_fn_name( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - - let args_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'args' was not provided".to_js_error(None))? - .clone(); - - let canister_id_principal: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - - let args_js_object = args_js_value - .as_object() - .ok_or_else(|| "'args' is not an object".to_js_error(None))?; - - #(#param_variables)* - - let notify_result = #real_function_name( - canister_id_principal, - #args, - ); - - notify_result - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/notify_with_payment128.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/notify_with_payment128.rs deleted file mode 100644 index 0beef4443f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/service/notify_with_payment128.rs +++ /dev/null @@ -1,55 +0,0 @@ -use cdk_framework::act::node::candid::service::{Method, Service}; -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; - -pub fn generate(service: &Service, method: &Method) -> TokenStream { - let function_name_string = format!("notify_with_payment128_{}_{}", service.name, method.name); - let real_function_name = format_ident!("{}", function_name_string); - let wrapper_fn_name = format_ident!("{}_wrapper", function_name_string); - let param_variables = super::generate_param_variables(method, &service.name); - let args = super::generate_args_list(method); - - quote! { - fn #wrapper_fn_name( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let canister_id_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'canisterId' was not provided".to_js_error(None))? - .clone(); - - let args_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'args' was not provided".to_js_error(None))? - .clone(); - - let cycles_js_value = aargs - .get(2) - .ok_or_else(|| "An argument for 'cycles' was not provided".to_js_error(None))? - .clone(); - - let canister_id_principal: candid::Principal = canister_id_js_value - .try_from_vm_value(&mut *context)?; - - let args_js_object = args_js_value - .as_object() - .ok_or_else(|| "'args' is not an object".to_js_error(None))?; - - #(#param_variables)* - - let cycles: u128 = cycles_js_value.try_from_vm_value(&mut *context)?; - - let notify_result = #real_function_name( - canister_id_principal, - #args, - cycles, - ); - - notify_result - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_certified_data.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_certified_data.rs deleted file mode 100644 index ed31a7ee52..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_certified_data.rs +++ /dev/null @@ -1,19 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn set_certified_data( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let data: Vec = aargs - .get(0) - .ok_or_else(|| "An argument for 'data' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk::api::set_certified_data(&data) - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_timer.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_timer.rs deleted file mode 100644 index 1fe8245433..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_timer.rs +++ /dev/null @@ -1,75 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn set_timer( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let delay_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'delay' was not provided".to_js_error(None))? - .clone(); - let func_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'callback' was not provided".to_js_error(None))?; - - let delay_as_u64: u64 = delay_js_value.try_from_vm_value(&mut *context)?; - let delay = core::time::Duration::new(delay_as_u64, 0); - - - if !func_js_value.is_callable() { - return Err("TypeError: 'callback' is not a function".to_js_error(None)); - } - - let func_js_object = func_js_value - .as_object() - .ok_or_else(|| "TypeError: 'callback' is not a function".to_js_error(None))? - .clone(); - - let closure = move || { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - let uuid = uuid::Uuid::new_v4().to_string(); - - UUID_REF_CELL.with(|uuid_ref_cell| { - let mut uuid_mut = uuid_ref_cell.borrow_mut(); - - *uuid_mut = uuid.clone(); - }); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = "_AZLE_TIMER".to_string(); - }); - - MANUAL_REF_CELL.with(|manual_ref_cell| { - let mut manual_mut = manual_ref_cell.borrow_mut(); - - *manual_mut = false; - }); - - let boa_return_value = func_js_object - .call(&boa_engine::JsValue::Null, &[], &mut *boa_context) - .unwrap_or_trap(&mut *boa_context); - - async_await_result_handler( - &mut boa_context, - &boa_return_value, - &uuid, - "_AZLE_TIMER", - false, - ) - .unwrap_or_trap(&mut *boa_context); - }); - }; - - let timer_id = ic_cdk_timers::set_timer(delay, closure); - - timer_id - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_timer_interval.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_timer_interval.rs deleted file mode 100644 index e01c1f286e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/set_timer_interval.rs +++ /dev/null @@ -1,74 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn set_timer_interval( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let interval_js_value = aargs - .get(0) - .ok_or_else(|| "An argument for 'interval' was not provided".to_js_error(None))? - .clone(); - let func_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'callback' was not provided".to_js_error(None))?; - - let interval_as_u64: u64 = interval_js_value.try_from_vm_value(&mut *context)?; - let interval = core::time::Duration::new(interval_as_u64, 0); - - if !func_js_value.is_callable() { - return Err("TypeError: 'callback' is not a function".to_js_error(None)); - } - - let func_js_object = func_js_value - .as_object() - .ok_or_else(|| "TypeError: 'callback' is not a function".to_js_error(None))? - .clone(); - - let closure = move || { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - let uuid = uuid::Uuid::new_v4().to_string(); - - UUID_REF_CELL.with(|uuid_ref_cell| { - let mut uuid_mut = uuid_ref_cell.borrow_mut(); - - *uuid_mut = uuid.clone(); - }); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = "_AZLE_TIMER".to_string(); - }); - - MANUAL_REF_CELL.with(|manual_ref_cell| { - let mut manual_mut = manual_ref_cell.borrow_mut(); - - *manual_mut = false; - }); - - let boa_return_value = func_js_object - .call(&boa_engine::JsValue::Null, &[], &mut *boa_context) - .unwrap_or_trap(&mut *boa_context); - - async_await_result_handler( - &mut boa_context, - &boa_return_value, - &uuid, - "_AZLE_TIMER", - false, - ) - .unwrap_or_trap(&mut *boa_context); - }); - }; - - let timer_id = ic_cdk_timers::set_timer_interval(interval, closure); - - timer_id - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_grow.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_grow.rs deleted file mode 100644 index 760731dd99..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_grow.rs +++ /dev/null @@ -1,19 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable64_grow( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let new_pages: u64 = aargs - .get(0) - .ok_or_else(|| "An argument for 'newPages' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk::api::stable::stable64_grow(new_pages) - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_read.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_read.rs deleted file mode 100644 index eb4b69d645..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_read.rs +++ /dev/null @@ -1,28 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable64_read( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let offset: u64 = aargs - .get(0) - .ok_or_else(|| "An argument for 'offset' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let length: u64 = aargs - .get(1) - .ok_or_else(|| "An argument for 'length' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let mut buf: Vec = vec![0; length as usize]; - ic_cdk::api::stable::stable64_read(offset, &mut buf); - - buf.to_vec() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_size.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_size.rs deleted file mode 100644 index b4ebbe1c9e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_size.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable64_size( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::stable::stable64_size() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_write.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_write.rs deleted file mode 100644 index 973af40264..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable64_write.rs +++ /dev/null @@ -1,26 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable64_write( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let offset: u64 = aargs - .get(0) - .ok_or_else(|| "An argument for 'offset' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let buf_vector: Vec = aargs - .get(1) - .ok_or_else(|| "An argument for 'buffer' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let buf: &[u8] = &buf_vector[..]; - ic_cdk::api::stable::stable64_write(offset, buf); - - Ok(boa_engine::JsValue::Undefined) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/contains_key.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/contains_key.rs deleted file mode 100644 index cc327f6302..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/contains_key.rs +++ /dev/null @@ -1,70 +0,0 @@ -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote! { - fn stable_b_tree_map_contains_key( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let key_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'key' was not provided".to_js_error(None))? - .clone(); - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - let (key_wrapper_type_name, _) = stable_b_tree_map::rust::wrapper_type::generate( - &stable_b_tree_map_node.key_type, - memory_id, - "Key", - ); - - quote! { - #memory_id => { - let wrapped_key = - &#key_wrapper_type_name(key_js_value.try_from_vm_value(&mut *context)?); - - #map_name_ident - .with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell - .borrow() - .contains_key(wrapped_key) - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/get.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/get.rs deleted file mode 100644 index e28f829352..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/get.rs +++ /dev/null @@ -1,68 +0,0 @@ -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote::quote! { - fn stable_b_tree_map_get( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let key_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'key' was not provided".to_js_error(None))? - .clone(); - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - let (key_wrapper_type_name, _) = stable_b_tree_map::rust::wrapper_type::generate( - &stable_b_tree_map_node.key_type, - memory_id, - "Key", - ); - - quote! { - #memory_id => { - let wrapped_key = - &#key_wrapper_type_name(key_js_value.try_from_vm_value(&mut *context)?); - - #map_name_ident - .with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell.borrow().get(wrapped_key) - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/insert.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/insert.rs deleted file mode 100644 index f1f2feb508..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/insert.rs +++ /dev/null @@ -1,81 +0,0 @@ -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote::quote! { - fn stable_b_tree_map_insert( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let key_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'key' was not provided".to_js_error(None))? - .clone(); - - let value_js_value = aargs - .get(2) - .ok_or_else(|| "An argument for 'value' was not provided".to_js_error(None))? - .clone(); - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - let (key_wrapper_type_name, _) = stable_b_tree_map::rust::wrapper_type::generate( - &stable_b_tree_map_node.key_type, - memory_id, - "Key", - ); - let (value_wrapper_type_name, _) = stable_b_tree_map::rust::wrapper_type::generate( - &stable_b_tree_map_node.value_type, - memory_id, - "Value", - ); - - // TODO the return value here might need a little work like in get - quote! { - #memory_id => { - let key = - #key_wrapper_type_name(key_js_value.try_from_vm_value(&mut *context)?); - let value = - #value_wrapper_type_name(value_js_value.try_from_vm_value(&mut *context)?); - - #map_name_ident - .with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell.borrow_mut().insert(key, value) - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/is_empty.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/is_empty.rs deleted file mode 100644 index d64a27651c..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/is_empty.rs +++ /dev/null @@ -1,54 +0,0 @@ -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote! { - fn stable_b_tree_map_is_empty( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - quote! { - #memory_id => { - #map_name_ident - .with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell.borrow().is_empty() - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/items.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/items.rs deleted file mode 100644 index 6a1b6456d0..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/items.rs +++ /dev/null @@ -1,76 +0,0 @@ -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote! { - fn stable_b_tree_map_items( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - quote! { - #memory_id => { - let items = #map_name_ident.with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell - .borrow() - .iter() - .map(|(key_wrapper_type, value_wrapper_type)| { - let key = key_wrapper_type - .0 - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None))?; - let value = value_wrapper_type - .0 - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None))?; - let tuple = vec![key, value]; - - Ok(boa_engine::object::builtins::JsArray::from_iter( - tuple, - &mut *context, - ) - .into()) - }) - .collect::, boa_engine::JsError>>() - })?; - - Ok( - boa_engine::object::builtins::JsArray::from_iter(items, &mut *context) - .into(), - ) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/keys.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/keys.rs deleted file mode 100644 index 517b0b38b6..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/keys.rs +++ /dev/null @@ -1,58 +0,0 @@ -// use cdk_framework::act::node::candid::type_annotation::ToTypeAnnotation; -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote! { - fn stable_b_tree_map_keys( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - quote! { - #memory_id => { - #map_name_ident.with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell - .borrow() - .iter() - .map(|(key_wrapper_type, _)| key_wrapper_type.0) - .collect::>() - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/len.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/len.rs deleted file mode 100644 index 86ca7da457..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/len.rs +++ /dev/null @@ -1,53 +0,0 @@ -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote! { - fn stable_b_tree_map_len( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - quote! { - #memory_id => { - #map_name_ident.with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell.borrow().len() - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/mod.rs deleted file mode 100644 index 953d4fbab8..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/mod.rs +++ /dev/null @@ -1,35 +0,0 @@ -use crate::StableBTreeMapNode; - -mod contains_key; -mod get; -mod insert; -mod is_empty; -mod items; -mod keys; -mod len; -mod remove; -mod values; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let contains_key = contains_key::generate(stable_b_tree_map_nodes); - let get = get::generate(stable_b_tree_map_nodes); - let insert = insert::generate(stable_b_tree_map_nodes); - let is_empty = is_empty::generate(stable_b_tree_map_nodes); - let items = items::generate(stable_b_tree_map_nodes); - let keys = keys::generate(stable_b_tree_map_nodes); - let len = len::generate(stable_b_tree_map_nodes); - let remove = remove::generate(stable_b_tree_map_nodes); - let values = values::generate(stable_b_tree_map_nodes); - - quote::quote! { - #contains_key - #get - #insert - #is_empty - #items - #keys - #len - #remove - #values - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/remove.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/remove.rs deleted file mode 100644 index 2b0f1d517e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/remove.rs +++ /dev/null @@ -1,68 +0,0 @@ -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote! { - fn stable_b_tree_map_remove( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let key_js_value = aargs - .get(1) - .ok_or_else(|| "An argument for 'key' was not provided".to_js_error(None))? - .clone(); - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - let (key_wrapper_type_name, _) = stable_b_tree_map::rust::wrapper_type::generate( - &stable_b_tree_map_node.key_type, - memory_id, - "Key", - ); - - quote! { - #memory_id => { - let key = - #key_wrapper_type_name(key_js_value.try_from_vm_value(&mut *context)?); - - #map_name_ident - .with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell.borrow_mut().remove(&key) - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/values.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/values.rs deleted file mode 100644 index 96f5de7485..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_b_tree_map/values.rs +++ /dev/null @@ -1,58 +0,0 @@ -// use cdk_framework::act::node::candid::type_annotation::ToTypeAnnotation; -use quote::quote; - -use crate::{body::stable_b_tree_map, StableBTreeMapNode}; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> proc_macro2::TokenStream { - let match_arms = generate_match_arms(stable_b_tree_map_nodes); - - quote! { - fn stable_b_tree_map_values( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let memory_id: u8 = aargs - .get(0) - .ok_or_else(|| "An argument for 'memoryId' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - match memory_id { - #(#match_arms)* - _ => Err(format!( - "Memory id {} does not have an associated StableBTreeMap", - memory_id - ) - .to_js_error(None)), - } - } - } -} - -fn generate_match_arms( - stable_b_tree_map_nodes: &Vec, -) -> Vec { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let memory_id = stable_b_tree_map_node.memory_id; - let map_name_ident = - stable_b_tree_map::rust::ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - - quote! { - #memory_id => { - #map_name_ident.with(|stable_b_tree_map_ref_cell| { - stable_b_tree_map_ref_cell - .borrow() - .iter() - .map(|(_, value_wrapper_type)| value_wrapper_type.0) - .collect::>() - }) - .try_into_vm_value(&mut *context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_bytes.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_bytes.rs deleted file mode 100644 index 9d748652b6..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_bytes.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable_bytes( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::stable::stable_bytes() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_grow.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_grow.rs deleted file mode 100644 index 6f66d0dbc9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_grow.rs +++ /dev/null @@ -1,19 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable_grow( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let new_pages: u32 = aargs - .get(0) - .ok_or_else(|| "An argument for 'newPages' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - ic_cdk::api::stable::stable_grow(new_pages) - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_read.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_read.rs deleted file mode 100644 index fcf1e57c0c..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_read.rs +++ /dev/null @@ -1,28 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable_read( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let offset: u32 = aargs - .get(0) - .ok_or_else(|| "An argument for 'offset' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let length: u32 = aargs - .get(1) - .ok_or_else(|| "An argument for 'length' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let mut buf: Vec = vec![0; length as usize]; - ic_cdk::api::stable::stable_read(offset, &mut buf); - - buf.to_vec() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_size.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_size.rs deleted file mode 100644 index 66a9db32e5..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_size.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable_size( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::stable::stable_size() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_write.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_write.rs deleted file mode 100644 index 7344a6fb67..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/stable_write.rs +++ /dev/null @@ -1,26 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn stable_write( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let offset: u32 = aargs - .get(0) - .ok_or_else(|| "An argument for 'offset' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let buf_vector: Vec = aargs - .get(1) - .ok_or_else(|| "An argument for 'buffer' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(&mut *context)?; - - let buf: &[u8] = &buf_vector[..]; - ic_cdk::api::stable::stable_write(offset, buf); - - Ok(boa_engine::JsValue::Undefined) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/time.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/time.rs deleted file mode 100644 index 1e5bb79b9a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/time.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn time( - _this: &boa_engine::JsValue, - _aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - ic_cdk::api::time() - .try_into_vm_value(context) - .map_err(|vmc_err| vmc_err.to_js_error(None)) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/trap.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/trap.rs deleted file mode 100644 index 7fd7b47f76..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/functions/trap.rs +++ /dev/null @@ -1,17 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - fn trap( - _this: &boa_engine::JsValue, - aargs: &[boa_engine::JsValue], - context: &mut boa_engine::Context, - ) -> boa_engine::JsResult { - let message: String = aargs - .get(0) - .ok_or_else(|| "An argument for 'message' was not provided".to_js_error(None))? - .clone() - .try_from_vm_value(context)?; - - ic_cdk::api::trap(&message); - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/mod.rs deleted file mode 100644 index 26753dfb6c..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod functions; -pub mod register_function; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/register_function.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/register_function.rs deleted file mode 100644 index 9aac5b0220..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/ic_object/register_function.rs +++ /dev/null @@ -1,133 +0,0 @@ -use cdk_framework::act::node::candid::Service; -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; - -use crate::{ts_ast::TsAst, Error}; - -pub fn generate(ts_ast: &TsAst) -> Result> { - let services = ts_ast.build_services()?; - - let notify_functions = generate_notify_functions(&services); - let cross_canister_functions = generate_cross_canister_functions(&services); - - Ok(quote::quote! { - fn register_ic_object(boa_context: &mut boa_engine::Context) { - let ic = boa_engine::object::ObjectInitializer::new(boa_context) - .function(boa_engine::NativeFunction::from_fn_ptr(accept_message), "acceptMessage", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(arg_data_raw), "argDataRaw", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(arg_data_raw_size), "argDataRawSize", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(call_raw), "callRaw", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(call_raw128), "callRaw128", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(caller), "caller", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(candid_decode), "candidDecode", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(candid_encode), "candidEncode", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(canister_balance), "canisterBalance", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(canister_balance128), "canisterBalance128", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(canister_version), "canisterVersion", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(clear_timer), "clearTimer", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(data_certificate), "dataCertificate", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(id), "id", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(instruction_counter), "instructionCounter", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(is_controller), "isController", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(method_name), "methodName", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(msg_cycles_accept), "msgCyclesAccept", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(msg_cycles_accept128), "msgCyclesAccept128", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(msg_cycles_available), "msgCyclesAvailable", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(msg_cycles_available128), "msgCyclesAvailable128", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(msg_cycles_refunded), "msgCyclesRefunded", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(msg_cycles_refunded128), "msgCyclesRefunded128", 0) - #(#notify_functions)* - #(#cross_canister_functions)* - .function(boa_engine::NativeFunction::from_fn_ptr(notify_raw), "notifyRaw", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(performance_counter), "performanceCounter", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(print), "print", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(reject), "reject", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(reject_code), "rejectCode", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(reject_message), "rejectMessage", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(reply), "reply", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(reply_raw), "replyRaw", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(set_certified_data), "setCertifiedData", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(set_timer), "setTimer", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(set_timer_interval), "setTimerInterval", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_bytes), "stableBytes", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_contains_key), "stableBTreeMapContainsKey", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_get), "stableBTreeMapGet", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_insert), "stableBTreeMapInsert", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_is_empty), "stableBTreeMapIsEmpty", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_items), "stableBTreeMapItems", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_keys), "stableBTreeMapKeys", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_values), "stableBTreeMapValues", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_len), "stableBTreeMapLen", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_b_tree_map_remove), "stableBTreeMapRemove", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_grow), "stableGrow", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_read), "stableRead", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_size), "stableSize", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable_write), "stableWrite", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable64_grow), "stable64Grow", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable64_read), "stable64Read", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable64_size), "stable64Size", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(stable64_write), "stable64Write", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(time), "time", 0) - .function(boa_engine::NativeFunction::from_fn_ptr(trap), "trap", 0) - .build(); - - boa_context.register_global_property( - "ic", - ic, - boa_engine::property::Attribute::all(), - ); - } - }) -} - -fn generate_notify_functions(services: &Vec) -> Vec { - services.iter().map(|canister| { - canister.methods.iter().map(|method| { - let notify_function_name_string = format!("notify_{}_{}", canister.name, method.name); - let notify_wrapper_function_name = format_ident!("{}_wrapper", notify_function_name_string); - - let notify_with_payment128_function_name_string = format!("notify_with_payment128_{}_{}", canister.name, method.name); - let notify_with_payment128_wrapper_function_name = format_ident!("{}_wrapper", notify_with_payment128_function_name_string); - - quote! { - .function(boa_engine::NativeFunction::from_fn_ptr(#notify_wrapper_function_name), #notify_function_name_string, 0) - .function(boa_engine::NativeFunction::from_fn_ptr(#notify_with_payment128_wrapper_function_name), #notify_with_payment128_function_name_string, 0) - } - }).collect() - }).collect::>>().concat() -} - -fn generate_cross_canister_functions(services: &Vec) -> Vec { - services - .iter() - .map(|canister| { - canister - .methods - .iter() - .map(|method| { - let call_function_name_string = - format!("call_{}_{}", canister.name, method.name); - let call_wrapper_function_name = - format_ident!("{}_wrapper", call_function_name_string); - - let call_with_payment_function_name_string = - format!("call_with_payment_{}_{}", canister.name, method.name); - let call_with_payment_wrapper_function_name = - format_ident!("{}_wrapper", call_with_payment_function_name_string); - - let call_with_payment128_function_name_string = - format!("call_with_payment128_{}_{}", canister.name, method.name); - let call_with_payment128_wrapper_function_name = - format_ident!("{}_wrapper", call_with_payment128_function_name_string); - - quote! { - .function(boa_engine::NativeFunction::from_fn_ptr(#call_wrapper_function_name), #call_function_name_string, 0) - .function(boa_engine::NativeFunction::from_fn_ptr(#call_with_payment_wrapper_function_name), #call_with_payment_function_name_string, 0) - .function(boa_engine::NativeFunction::from_fn_ptr(#call_with_payment128_wrapper_function_name), #call_with_payment128_function_name_string, 0) - } - }) - .collect() - }) - .collect::>>() - .concat() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/mod.rs deleted file mode 100644 index 0b8b599325..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/mod.rs +++ /dev/null @@ -1,79 +0,0 @@ -use cdk_framework::{ - act::node::{ - candid::Service, - canister_method::{QueryMethod, QueryOrUpdateMethod, UpdateMethod}, - }, - traits::CollectIterResults, -}; -use proc_macro2::TokenStream; -use quote::quote; - -use crate::{plugin::Plugin, ts_ast::TsAst, Error}; - -use self::stable_b_tree_map::StableBTreeMapNode; - -mod ic_object; -mod to_js_error; - -pub mod async_await_result_handler; -pub mod runtime_error; -pub mod stable_b_tree_map; -pub mod unwrap_or_trap; - -pub fn generate( - ts_ast: &TsAst, - query_methods: &Vec, - update_methods: &Vec, - services: &Vec, - stable_b_tree_map_nodes: &Vec, - plugins: &Vec, -) -> Result> { - let register_ic_object_function = ic_object::register_function::generate(ts_ast)?; - - let query_and_update_methods = vec![ - query_methods - .iter() - .map(|query_method| QueryOrUpdateMethod::Query(query_method.clone())) - .collect::>(), - update_methods - .iter() - .map(|update_methods| QueryOrUpdateMethod::Update(update_methods.clone())) - .collect::>(), - ] - .concat(); - - let async_await_result_handler = - async_await_result_handler::generate(&query_and_update_methods); - let ic_object_functions = ic_object::functions::generate( - &query_and_update_methods, - services, - &stable_b_tree_map_nodes, - ); - - let stable_b_tree_maps = stable_b_tree_map::rust::generate(&stable_b_tree_map_nodes); - let unwrap_or_trap = unwrap_or_trap::generate(); - let runtime_error = runtime_error::generate(); - let to_js_errors = to_js_error::generate(); - - let plugins_code = plugins - .iter() - .map(|plugin| plugin.to_code()) - .collect_results()?; - - Ok(quote! { - #runtime_error - #to_js_errors - #async_await_result_handler - #ic_object_functions - #register_ic_object_function - #stable_b_tree_maps - #unwrap_or_trap - #(#plugins_code)* - - // TODO this is temporary until this issue is resolved: https://github.com/demergent-labs/azle/issues/1029 - #[ic_cdk_macros::query] - fn __get_candid_interface_tmp_hack() -> String { - __export_service() - } - }) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/runtime_error.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/runtime_error.rs deleted file mode 100644 index 670833f1af..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/runtime_error.rs +++ /dev/null @@ -1,48 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; - -pub fn generate() -> TokenStream { - quote! { - enum RuntimeError { - IntoVmValueError(String), // TODO: Consider this might be the same as TypeError - JsError(boa_engine::JsError), - ReferenceError(String), - TypeError(String), - String(String), - } - - impl RuntimeError { - pub fn to_string(&self) -> String { - match self { - Self::IntoVmValueError(msg) => msg.to_string(), - Self::JsError(js_error) => BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - js_error.clone().to_std_string(&mut boa_context) - }), - Self::ReferenceError(msg) => format!("ReferenceError: {msg}"), - Self::TypeError(msg) => format!("TypeError: {msg}"), - Self::String(msg) => msg.clone(), - } - } - } - - impl From for RuntimeError { - fn from(value: boa_engine::JsError) -> Self { - Self::JsError(value) - } - } - - impl From for RuntimeError { - fn from(value: CdkActTryIntoVmValueError) -> Self { - Self::IntoVmValueError(value.0) - } - } - - impl From for RuntimeError { - fn from(value: String) -> Self { - Self::String(value) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/expr.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/expr.rs deleted file mode 100644 index 1ddba6d220..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/expr.rs +++ /dev/null @@ -1,53 +0,0 @@ -use swc_ecma_ast::{Expr, Lit}; - -pub trait ToU8 { - fn to_u8(&self) -> Result; -} - -pub trait ToU32 { - fn to_u32(&self) -> Result; -} - -impl ToU8 for Expr { - fn to_u8(&self) -> Result { - let error_message = format!("Unable to convert Expr to u8"); - match self { - Expr::Lit(lit) => match lit { - Lit::Num(num) => { - if num.value.fract() != 0.0 - || num.value > u8::MAX as f64 - || num.value < u8::MIN as f64 - { - return Err(error_message); - } - - Ok(num.value as u8) - } - _ => return Err(error_message), - }, - _ => return Err(error_message), - } - } -} - -impl ToU32 for Expr { - fn to_u32(&self) -> Result { - let error_message = format!("Unable to convert Expr to u32"); - match self { - Expr::Lit(lit) => match lit { - Lit::Num(num) => { - if num.value.fract() != 0.0 - || num.value > u32::MAX as f64 - || num.value < u32::MIN as f64 - { - return Err(error_message); - } - - Ok(num.value as u32) - } - _ => return Err(error_message), - }, - _ => return Err(error_message), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/mod.rs deleted file mode 100644 index 137d1f693a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/mod.rs +++ /dev/null @@ -1,105 +0,0 @@ -use cdk_framework::{act::node::CandidType, traits::CollectIterResults}; -use std::ops::Deref; -use swc_ecma_ast::{Decl, Expr, VarDecl}; - -use crate::{ - traits::{GetName, GetOptionalName}, - ts_ast::{Program, SourceMapped, TsAst}, - Error, -}; - -use self::module_item::AsDecl; - -mod expr; -mod module_item; -pub mod new_expr; - -pub mod rust; - -#[derive(Clone, Debug)] -pub struct StableBTreeMapNode { - pub memory_id: u8, - pub key_type: CandidType, - pub value_type: CandidType, - pub max_key_size: u32, - pub max_value_size: u32, -} - -impl TsAst { - pub fn build_stable_b_tree_map_nodes(&self) -> Result, Vec> { - self.programs - .iter() - .map(|program| program.build_stable_b_tree_map_nodes()) - .collect_results() - .map(|vec_of_vec| vec_of_vec.into_iter().flatten().collect::>()) - } -} - -impl Program { - pub fn spawn(&self, child: &C) -> SourceMapped - where - C: Clone, - { - SourceMapped::new(child, &self.source_map, &self.alias_table, &self.alias_list) - } - - pub fn build_stable_b_tree_map_nodes(&self) -> Result, Vec> { - match self.deref() { - swc_ecma_ast::Program::Module(module) => module - .body - .iter() - .filter_map(|module_item| module_item.as_decl()) - .map(|decl| self.process_decl(decl)) - .collect_results() - .map(|vec_of_vec| vec_of_vec.into_iter().flatten().collect::>()), - swc_ecma_ast::Program::Script(_) => Ok(vec![]), - } - } - - fn process_decl(&self, decl: &Decl) -> Result, Vec> { - match decl { - Decl::Var(var_decl) => self.process_var_decl(var_decl), - _ => Ok(vec![]), - } - } - - fn process_var_decl(&self, var_decl: &VarDecl) -> Result, Vec> { - var_decl - .decls - .iter() - .filter_map(|var_declarator| match &var_declarator.init { - Some(init) => match &**init { - Expr::New(new_expr) - if matches!( - &*new_expr.callee, - Expr::Ident(ident) if self.alias_table.stable_b_tree_map.contains(&ident.get_name()) - ) => - { - Some( - self.spawn(new_expr) - .to_stable_b_tree_map_node(), - ) - } - Expr::New(new_expr)=> { - match &*new_expr.callee { - Expr::Member(member) => { - member.get_name().and_then(|name| { - if self.alias_table.stable_b_tree_map.contains(&name) { - Some( - self.spawn(new_expr) - .to_stable_b_tree_map_node(), - ) - } else { - None - }}) - }, - _ => None - } - }, - _ => None, - }, - _ => None, - }) - .collect() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/module_item.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/module_item.rs deleted file mode 100644 index 5af787bad3..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/module_item.rs +++ /dev/null @@ -1,15 +0,0 @@ -use swc_ecma_ast::{Decl, ModuleDecl, ModuleItem, Stmt}; - -pub trait AsDecl { - fn as_decl(&self) -> Option<&Decl>; -} - -impl AsDecl for ModuleItem { - fn as_decl(&self) -> Option<&Decl> { - match self { - ModuleItem::Stmt(Stmt::Decl(decl)) => Some(decl), - ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) => Some(&export_decl.decl), - _ => None, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/arg_spread.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/arg_spread.rs deleted file mode 100644 index bd071269af..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/arg_spread.rs +++ /dev/null @@ -1,60 +0,0 @@ -use swc_ecma_ast::NewExpr; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct ArgSpread { - source: String, - location: Location, -} - -impl ArgSpread { - pub fn from_new_expr(sm_new_expr: &SourceMapped) -> Self { - Self { - source: sm_new_expr.get_source(), - location: sm_new_expr.get_location(), - } - } - - fn build_arg_spread_error_message(&self) -> CompilerOutput { - let title = "StableBTreeMap does not currently support argument spreading".to_string(); - // UNWRAP HERE // UNWRAP HERE - let range = ( - self.source.find("(").unwrap() + 1, - self.source.find(")").unwrap(), - ); - let annotation = "attempted to spread arguments here".to_string(); - let help = "specify each argument individually. E.g.:".to_string(); - let suggestion = "memory_id, max_key_size, max_value_size".to_string(); - - super::build_error_message( - &title, - &self.source, - &self.location, - range, - annotation, - help, - suggestion, - ) - } -} - -impl std::error::Error for ArgSpread {} - -impl From for crate::Error { - fn from(error: ArgSpread) -> Self { - Self::ArgSpread(error) - } -} - -impl std::fmt::Display for ArgSpread { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_arg_spread_error_message()) - } -} - -impl SourceMapped<'_, NewExpr> {} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/incorrect_number_of_args.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/incorrect_number_of_args.rs deleted file mode 100644 index b9a3e47289..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/incorrect_number_of_args.rs +++ /dev/null @@ -1,40 +0,0 @@ -use swc_ecma_ast::NewExpr; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct IncorrectNumberOfArgs { - source: String, - location: Location, -} - -impl IncorrectNumberOfArgs { - pub fn from_new_expr(sm_new_expr: &SourceMapped) -> Self { - Self { - source: sm_new_expr.get_source(), - location: sm_new_expr.get_location(), - } - } - - fn build_incorrect_number_of_args_error_message(&self) -> CompilerOutput { - super::build_arg_error_message("incorrect arguments", &self.source, &self.location) - } -} - -impl std::error::Error for IncorrectNumberOfArgs {} - -impl From for crate::Error { - fn from(error: IncorrectNumberOfArgs) -> Self { - Self::IncorrectNumberOfArgs(error) - } -} - -impl std::fmt::Display for IncorrectNumberOfArgs { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_incorrect_number_of_args_error_message()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/incorrect_type_args.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/incorrect_type_args.rs deleted file mode 100644 index 243a870c6b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/incorrect_type_args.rs +++ /dev/null @@ -1,44 +0,0 @@ -use swc_ecma_ast::NewExpr; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct IncorrectTypeArgs { - source: String, - location: Location, -} - -impl IncorrectTypeArgs { - pub fn from_new_expr(sm_new_expr: &SourceMapped) -> Self { - Self { - source: sm_new_expr.get_source(), - location: sm_new_expr.get_location(), - } - } - - fn build_incorrect_type_args_error_message(&self) -> CompilerOutput { - super::build_type_arg_error_message( - "wrong number of type arguments", - &self.source, - &self.location, - ) - } -} - -impl std::error::Error for IncorrectTypeArgs {} - -impl From for crate::Error { - fn from(error: IncorrectTypeArgs) -> Self { - Self::IncorrectTypeArgs(error) - } -} - -impl std::fmt::Display for IncorrectTypeArgs { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_incorrect_type_args_error_message()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/invalid_arg.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/invalid_arg.rs deleted file mode 100644 index 6d244ff064..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/invalid_arg.rs +++ /dev/null @@ -1,125 +0,0 @@ -use swc_ecma_ast::NewExpr; - -use super::ArgName; -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct InvalidArg { - arg_name: ArgName, - source: String, - location: Location, -} - -impl InvalidArg { - pub fn from_new_expr(sm_new_expr: &SourceMapped, arg_name: ArgName) -> Self { - Self { - source: sm_new_expr.get_source(), - location: sm_new_expr.get_location(), - arg_name, - } - } - - pub fn build_invalid_arg_error_message(&self) -> CompilerOutput { - let max_size = match self.arg_name { - ArgName::MessageId => "255".to_string(), - ArgName::MaxKeySize => "4,294,967,295".to_string(), - ArgName::MaxValueSize => "4,294,967,295".to_string(), - }; - let title = format!( - "invalid argument: must be an integer literal between 0 and {} inclusive", - max_size - ); - - // UNWRAP HERE - let open_paren_index = self.source.find("(").unwrap(); - - let message_id_start_index = self - .source - .char_indices() - .find(|(i, c)| *i > open_paren_index && !c.is_whitespace()) - .map(|(i, _)| i) - // UNWRAP HERE - .unwrap(); - let message_id_end_index = self - .source - .char_indices() - .find(|(i, c)| *i > message_id_start_index && c == &',') - .map(|(i, _)| i) - // UNWRAP HERE - .unwrap(); - let message_id_range = (message_id_start_index, message_id_end_index); - - let max_key_size_start_index = self - .source - .char_indices() - .find(|(i, c)| *i > message_id_end_index && !c.is_whitespace()) - .map(|(i, _)| i) - // UNWRAP HERE - .unwrap(); - let max_key_size_end_index = self - .source - .char_indices() - .find(|(i, c)| *i > max_key_size_start_index && c == &',') - .map(|(i, _)| i) - // UNWRAP HERE - .unwrap(); - let max_key_size_range = (max_key_size_start_index, max_key_size_end_index); - - let max_value_size_start_index = self - .source - .char_indices() - .find(|(i, c)| *i > max_key_size_end_index && !c.is_whitespace()) - .map(|(i, _)| i) - // UNWRAP HERE - .unwrap(); - let max_value_size_end_index = self - .source - .char_indices() - .find(|(i, c)| *i > max_value_size_start_index && (c.is_whitespace() || c == &')')) - .map(|(i, _)| i) - // UNWRAP HERE - .unwrap(); - let max_value_size_range = (max_value_size_start_index, max_value_size_end_index); - - let range = match self.arg_name { - ArgName::MessageId => message_id_range, - ArgName::MaxKeySize => max_key_size_range, - ArgName::MaxValueSize => max_value_size_range, - }; - let annotation = "expected here".to_string(); - let help = "use a valid integer literal. E.g.:".to_string(); - let suggestion = match self.arg_name { - ArgName::MessageId => "0".to_string(), - ArgName::MaxKeySize => "100".to_string(), - ArgName::MaxValueSize => "1_000".to_string(), - }; - - super::build_error_message( - &title, - &self.source, - &self.location, - range, - annotation, - help, - suggestion, - ) - } -} - -impl std::error::Error for InvalidArg {} - -impl From for crate::Error { - fn from(error: InvalidArg) -> Self { - Self::InvalidArg(error) - } -} - -impl std::fmt::Display for InvalidArg { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_invalid_arg_error_message()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/missing_args.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/missing_args.rs deleted file mode 100644 index 1c4b46655a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/missing_args.rs +++ /dev/null @@ -1,40 +0,0 @@ -use swc_ecma_ast::NewExpr; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct MissingArgs { - source: String, - location: Location, -} - -impl MissingArgs { - pub fn from_new_expr(sm_new_expr: &SourceMapped) -> Self { - Self { - source: sm_new_expr.get_source(), - location: sm_new_expr.get_location(), - } - } - - fn build_missing_args_error_message(&self) -> CompilerOutput { - super::build_arg_error_message("missing arguments", &self.source, &self.location) - } -} - -impl std::error::Error for MissingArgs {} - -impl From for crate::Error { - fn from(error: MissingArgs) -> Self { - Self::MissingArgs(error) - } -} - -impl std::fmt::Display for MissingArgs { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_missing_args_error_message()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/missing_sbtm_type_argument.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/missing_sbtm_type_argument.rs deleted file mode 100644 index 54bac084b9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/missing_sbtm_type_argument.rs +++ /dev/null @@ -1,40 +0,0 @@ -use swc_ecma_ast::NewExpr; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct MissingSbtmTypeArguments { - source: String, - location: Location, -} - -impl MissingSbtmTypeArguments { - pub fn from_new_expr(sm_new_expr: &SourceMapped) -> Self { - Self { - source: sm_new_expr.get_source(), - location: sm_new_expr.get_location(), - } - } - - pub fn build_missing_type_args_error_message(&self) -> CompilerOutput { - super::build_type_arg_error_message("missing type arguments", &self.source, &self.location) - } -} - -impl std::error::Error for MissingSbtmTypeArguments {} - -impl From for crate::Error { - fn from(error: MissingSbtmTypeArguments) -> Self { - Self::MissingSbtmTypeArgument(error) - } -} - -impl std::fmt::Display for MissingSbtmTypeArguments { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_missing_type_args_error_message()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/mod.rs deleted file mode 100644 index 51b59122af..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/errors/mod.rs +++ /dev/null @@ -1,88 +0,0 @@ -mod arg_spread; -mod incorrect_number_of_args; -mod incorrect_type_args; -mod invalid_arg; -mod missing_args; -mod missing_sbtm_type_argument; - -use super::ArgName; -use crate::errors::{CompilerOutput, Location, Suggestion}; - -pub use arg_spread::ArgSpread; -pub use incorrect_number_of_args::IncorrectNumberOfArgs; -pub use incorrect_type_args::IncorrectTypeArgs; -pub use invalid_arg::InvalidArg; -pub use missing_args::MissingArgs; -pub use missing_sbtm_type_argument::MissingSbtmTypeArguments; - -pub fn build_type_arg_error_message( - title: &str, - source: &str, - location: &Location, -) -> CompilerOutput { - // let range = ( - // // UNWRAP HERE // TODO this will be made more complicated by robust imports - // source.find("StableBTreeMap").unwrap() + "StableBTreeMap".len(), - // // UNWRAP HERE - // source.find("(").unwrap(), - // ); - let range = (0, 0); // TODO figure out a dynamic way to get the range with the symbol table instead of the string literal "StableBTreeMap" - let annotation = "expected exactly 2 type arguments here".to_string(); - let help = "specify a key and value type. E.g.:".to_string(); - let suggestion = "".to_string(); - - build_error_message(title, source, location, range, annotation, help, suggestion) -} - -pub fn build_arg_error_message(title: &str, source: &str, location: &Location) -> CompilerOutput { - // UNWRAP HERE // UNWRAP HERE - let range = (source.find("(").unwrap() + 1, source.find(")").unwrap()); - let annotation = "expected exactly 3 arguments here".to_string(); - let help = "specify a memory id, the max key size, and the max value size. E.g.:".to_string(); - let suggestion = "memory_id, max_key_size, max_value_size".to_string(); - - build_error_message(title, source, location, range, annotation, help, suggestion) -} - -fn build_error_message( - title: &str, - source: &str, - location: &Location, - range: (usize, usize), - annotation: String, - help: String, - suggestion: String, -) -> CompilerOutput { - let adjusted_range = if range.0 == range.1 { - (range.0, range.1 + 1) - } else { - range - }; - - let modified_source = [ - // UNWRAP HERE - source.get(..range.0).unwrap(), - &suggestion, - // UNWRAP HERE - source.get(range.1..).unwrap(), - ] - .join(""); - - let suggestion_range = (range.0, range.0 + &suggestion.len()); - - CompilerOutput { - title: title.to_string(), - location: Location { - range: adjusted_range, - ..location.clone() - }, - annotation, - suggestion: Some(Suggestion { - title: help, - source: modified_source, - range: suggestion_range, - annotation: None, - import_suggestion: None, - }), - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/get_span.rs deleted file mode 100644 index 647c846ca4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/get_span.rs +++ /dev/null @@ -1,9 +0,0 @@ -use swc_ecma_ast::NewExpr; - -use crate::traits::GetSpan; - -impl GetSpan for NewExpr { - fn get_span(&self) -> swc_common::Span { - self.span - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/mod.rs deleted file mode 100644 index a8455f6d29..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/new_expr/mod.rs +++ /dev/null @@ -1,84 +0,0 @@ -use std::ops::Deref; - -use cdk_framework::traits::CollectResults; -use swc_ecma_ast::NewExpr; - -use self::errors::{ - ArgSpread, IncorrectNumberOfArgs, IncorrectTypeArgs, InvalidArg, MissingArgs, - MissingSbtmTypeArguments, -}; - -use super::expr::{ToU32, ToU8}; -use crate::{ - canister_method::check_length_and_map::CheckLengthAndMapTwo, ts_ast::SourceMapped, Error, - StableBTreeMapNode, -}; - -pub mod errors; -mod get_span; - -#[derive(PartialEq, Clone, Debug)] -pub enum ArgName { - MessageId, - MaxKeySize, - MaxValueSize, -} - -impl SourceMapped<'_, NewExpr> { - pub fn to_stable_b_tree_map_node(&self) -> Result> { - match &self.type_args { - Some(type_args) => { - match &self.args { - Some(args) => { - if args.len() == 0 { - return Err(vec![MissingArgs::from_new_expr(self).into()]); - } - if args.len() != 3 { - return Err(vec![IncorrectNumberOfArgs::from_new_expr(self).into()]); - } - let (type_arg_candid_types, _, memory_id, max_key_size, max_value_size) = ( - // Get key and value type from type_args - type_args - .params - .check_length_and_map( - type_args.params.len() == 2, - |_| IncorrectTypeArgs::from_new_expr(self).into(), - |param| self.spawn(param.deref()).to_candid_type(), - ) - .collect_results(), - // Get memory id and max key and value size from the call arguments - if args.iter().any(|arg| arg.spread.is_some()) { - return Err(vec![ArgSpread::from_new_expr(self).into()]); - } else { - Ok(()) - }, - args[0].expr.to_u8().map_err(|_| { - vec![InvalidArg::from_new_expr(self, ArgName::MessageId).into()] - }), - args[1].expr.to_u32().map_err(|_| { - vec![InvalidArg::from_new_expr(self, ArgName::MaxKeySize).into()] - }), - args[2].expr.to_u32().map_err(|_| { - vec![InvalidArg::from_new_expr(self, ArgName::MaxValueSize).into()] - }), - ) - .collect_results()?; - - let key_type = type_arg_candid_types[0].clone(); - let value_type = type_arg_candid_types[1].clone(); - - Ok(StableBTreeMapNode { - memory_id, - key_type, - max_key_size, - value_type, - max_value_size, - }) - } - None => Err(vec![MissingArgs::from_new_expr(self).into()]), - } - } - None => Err(vec![MissingSbtmTypeArguments::from_new_expr(self).into()]), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/bounded_storable_impl.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/bounded_storable_impl.rs deleted file mode 100644 index ede77bb0e4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/bounded_storable_impl.rs +++ /dev/null @@ -1,10 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; - -pub fn generate(wrapper_type_name: &Ident, max_size: u32) -> TokenStream { - quote::quote! { - impl ic_stable_structures::BoundedStorable for #wrapper_type_name { - const MAX_SIZE: u32 = #max_size; - const IS_FIXED_SIZE: bool = false; - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/mod.rs deleted file mode 100644 index 633802fc95..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/mod.rs +++ /dev/null @@ -1,97 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; - -use crate::StableBTreeMapNode; - -mod bounded_storable_impl; -mod storable_impl; - -pub mod ref_cell_ident; -pub mod try_into_vm_value_impl; -pub mod wrapper_type; - -pub fn generate(stable_b_tree_map_nodes: &Vec) -> TokenStream { - let stable_b_tree_maps_and_impls = - generate_global_stable_b_tree_maps_and_impls(stable_b_tree_map_nodes); - let stable_b_tree_maps: Vec = stable_b_tree_maps_and_impls - .iter() - .map(|stable_b_tree_map_and_impl| stable_b_tree_map_and_impl.0.clone()) - .collect(); - let stable_b_tree_impls: Vec = stable_b_tree_maps_and_impls - .iter() - .map(|stable_b_tree_map_and_impl| stable_b_tree_map_and_impl.1.clone()) - .collect(); - - quote! { - thread_local! { - static MEMORY_MANAGER_REF_CELL: std::cell::RefCell> - = std::cell::RefCell::new(ic_stable_structures::memory_manager::MemoryManager::init(ic_stable_structures::DefaultMemoryImpl::default())); - - #(#stable_b_tree_maps)* - } - - #(#stable_b_tree_impls)* - } -} - -fn generate_global_stable_b_tree_maps_and_impls( - stable_b_tree_map_nodes: &Vec, -) -> Vec<(proc_macro2::TokenStream, proc_macro2::TokenStream)> { - stable_b_tree_map_nodes - .iter() - .map(|stable_b_tree_map_node| { - let map_name_ident = ref_cell_ident::generate(stable_b_tree_map_node.memory_id); - let memory_id = stable_b_tree_map_node.memory_id; - - let (key_wrapper_type_name, key_wrapper_type) = - wrapper_type::generate(&stable_b_tree_map_node.key_type, memory_id, "Key"); - let (value_wrapper_type_name, value_wrapper_type) = - wrapper_type::generate(&stable_b_tree_map_node.value_type, memory_id, "Value"); - - let key_try_into_vm_value_impl = - try_into_vm_value_impl::generate(&key_wrapper_type_name); - let key_storable_impl = storable_impl::generate(&key_wrapper_type_name); - let key_bounded_storable_impl = bounded_storable_impl::generate( - &key_wrapper_type_name, - stable_b_tree_map_node.max_key_size, - ); - - let value_try_into_vm_value_impl = - try_into_vm_value_impl::generate(&value_wrapper_type_name); - let value_storable_impl = storable_impl::generate(&value_wrapper_type_name); - let value_bounded_storable_impl = bounded_storable_impl::generate( - &value_wrapper_type_name, - stable_b_tree_map_node.max_value_size, - ); - - ( - quote! { - static #map_name_ident: std::cell::RefCell< - ic_stable_structures::StableBTreeMap< - #key_wrapper_type_name, - #value_wrapper_type_name, - ic_stable_structures::memory_manager::VirtualMemory< - ic_stable_structures::DefaultMemoryImpl - > - > - > = std::cell::RefCell::new(ic_stable_structures::StableBTreeMap::init( - MEMORY_MANAGER_REF_CELL.with(|m| { - m.borrow().get(ic_stable_structures::memory_manager::MemoryId::new(#memory_id)) - }), - )); - }, - quote! { - #key_wrapper_type - #key_try_into_vm_value_impl - #key_storable_impl - #key_bounded_storable_impl - - #value_wrapper_type - #value_try_into_vm_value_impl - #value_storable_impl - #value_bounded_storable_impl - }, - ) - }) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/ref_cell_ident.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/ref_cell_ident.rs deleted file mode 100644 index d3f3ba4165..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/ref_cell_ident.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub fn generate(memory_id: u8) -> proc_macro2::Ident { - quote::format_ident!("STABLE_B_TREE_MAP_{}_REF_CELL", memory_id) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/storable_impl.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/storable_impl.rs deleted file mode 100644 index 309adbfff8..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/storable_impl.rs +++ /dev/null @@ -1,28 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; - -pub fn generate(wrapper_type_name: &Ident) -> TokenStream { - quote::quote! { - impl ic_stable_structures::Storable for #wrapper_type_name { - fn to_bytes(&self) -> std::borrow::Cow<[u8]> { - unwrap_or_trap(|| { - Ok(std::borrow::Cow::Owned(candid::Encode!(self).map_err( - |candid_error| { - RuntimeError::String(format!( - "CandidError: {}", - candid_error.to_string() - )) - }, - )?)) - }) - } - - fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self { - unwrap_or_trap(|| { - candid::Decode!(&bytes, Self).map_err(|candid_error| { - RuntimeError::String(format!("CandidError: {}", candid_error.to_string())) - }) - }) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/try_into_vm_value_impl.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/try_into_vm_value_impl.rs deleted file mode 100644 index c6ee6e2030..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/try_into_vm_value_impl.rs +++ /dev/null @@ -1,11 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; - -pub fn generate(wrapper_type_name: &Ident) -> TokenStream { - quote::quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for #wrapper_type_name { - fn try_into_vm_value(self, context: &mut boa_engine::Context) -> Result { - Ok(self.0.try_into_vm_value(context)?) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/wrapper_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/wrapper_type.rs deleted file mode 100644 index 4977c46c76..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/stable_b_tree_map/rust/wrapper_type.rs +++ /dev/null @@ -1,44 +0,0 @@ -use cdk_framework::{ - act::{ - node::{CandidType, Context}, - ToTypeAnnotation, - }, - traits::{Declare, ToIdent}, -}; -use proc_macro2::{Ident, TokenStream}; -use quote::quote; - -use crate::ts_keywords; - -pub fn generate( - act_data_type: &CandidType, - memory_id: u8, - key_or_value: &str, -) -> (Ident, TokenStream) { - let wrapper_struct_name = format!("StableBTreeMap{}{}Type", memory_id, key_or_value); - let inner_type = &act_data_type.to_type_annotation( - &Context { - keyword_list: ts_keywords::ts_keywords(), - cdk_name: "azle".to_string(), - }, - wrapper_struct_name.clone(), - ); - let wrapper_struct_name_ident = wrapper_struct_name.to_ident(); - - let dependent_types = act_data_type.flatten( - &Context { - keyword_list: ts_keywords::ts_keywords(), - cdk_name: "azle".to_string(), - }, - wrapper_struct_name.clone(), - ); - - ( - wrapper_struct_name_ident.clone(), - quote! { - #[derive(candid::CandidType, candid::Deserialize, CdkActTryFromVmValue, Ord, PartialOrd, Eq, PartialEq, Clone)] - struct #wrapper_struct_name_ident(#inner_type); - #(#dependent_types)* - }, - ) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/to_js_error.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/to_js_error.rs deleted file mode 100644 index 594fe65ede..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/to_js_error.rs +++ /dev/null @@ -1,67 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; - -pub fn generate() -> TokenStream { - quote! { - trait ToJsError { - fn to_js_error(self, opt_cause: Option) -> boa_engine::JsError; - } - - impl ToJsError for CdkActTryIntoVmValueError { - fn to_js_error(self, opt_cause: Option) -> boa_engine::JsError { - self.0.to_js_error(opt_cause) - } - } - - impl ToJsError for String { - fn to_js_error(self, opt_cause: Option) -> boa_engine::JsError { - self.as_str().to_js_error(opt_cause) - } - } - - impl<'a> ToJsError for &'a str { - fn to_js_error(self, opt_cause: Option) -> boa_engine::JsError { - let raw_error_message = self; - let error_types = [ - "Error: ", - "EvalError: ", - "RangeError: ", - "ReferenceError: ", - "SyntaxError: ", - "TypeError: ", - "UriError: ", - ]; - - for error_type in error_types.iter() { - if raw_error_message.starts_with(error_type) { - let message = raw_error_message - .splitn(2, error_type) - .collect::>()[1]; - - let js_native_error = match *error_type { - "Error: " => boa_engine::error::JsNativeError::error(), - "EvalError: " => boa_engine::error::JsNativeError::eval(), - "RangeError: " => boa_engine::error::JsNativeError::range(), - "ReferenceError: " => boa_engine::error::JsNativeError::reference(), - "SyntaxError: " => boa_engine::error::JsNativeError::syntax(), - "TypeError: " => boa_engine::error::JsNativeError::typ(), - "UriError: " => boa_engine::error::JsNativeError::uri(), - _ => unreachable!(), - } - .with_message(message); - - return match opt_cause { - Some(cause) => js_native_error.with_cause(cause), - None => js_native_error, - } - .into(); - } - } - - return boa_engine::error::JsNativeError::error() - .with_message(raw_error_message) - .into(); - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/body/unwrap_or_trap.rs b/src/compiler/typescript_to_rust/azle_generate/src/body/unwrap_or_trap.rs deleted file mode 100644 index c161ba819f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/body/unwrap_or_trap.rs +++ /dev/null @@ -1,187 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; - -pub fn generate() -> TokenStream { - quote! { - fn unwrap_or_trap(callback: Callback) -> SuccessValue - where - Callback: FnOnce() -> Result, - { - callback() - .unwrap_or_else(|err| ic_cdk::api::trap(&format!("\nUncaught {}", err.to_string()))) - } - - pub trait UnwrapJsResultOrTrap { - fn unwrap_or_trap(self, context: &mut boa_engine::Context) -> boa_engine::JsValue; - } - - impl UnwrapJsResultOrTrap for boa_engine::JsResult { - fn unwrap_or_trap(self, context: &mut boa_engine::Context) -> boa_engine::JsValue { - match self { - Ok(js_value) => js_value, - Err(js_error) => { - let error_message = js_error.to_std_string(context); - - ic_cdk::api::trap(&format!("\nUncaught {error_message}")); - } - } - } - } - - impl UnwrapJsResultOrTrap for Result { - fn unwrap_or_trap(self, context: &mut boa_engine::Context) -> boa_engine::JsValue { - match self { - Ok(js_value) => js_value, - Err(error_string) => { - ic_cdk::api::trap(&format!("\nUncaught {error_string}")); - } - } - } - } - - pub trait UnwrapOrTrapWithMessage { - fn unwrap_or_trap(self, err_message: &str) -> T; - } - - impl UnwrapOrTrapWithMessage for Option { - fn unwrap_or_trap(self, err_message: &str) -> T { - match self { - Some(some) => some, - None => ic_cdk::trap(&format!("\nUncaught {err_message}")), - } - } - } - - trait ToStdString { - fn to_std_string(self, context: &mut boa_engine::Context) -> String; - } - - impl ToStdString for boa_engine::JsError { - fn to_std_string(self, context: &mut boa_engine::Context) -> String { - self.to_opaque(context).to_std_string(context) - } - } - - impl ToStdString for boa_engine::JsValue { - fn to_std_string(self, context: &mut boa_engine::Context) -> String { - match &self { - boa_engine::JsValue::BigInt(bigint) => bigint.to_string(), - boa_engine::JsValue::Boolean(boolean) => boolean.to_string(), - boa_engine::JsValue::Integer(integer) => integer.to_string(), - boa_engine::JsValue::Null => "null".to_string(), - boa_engine::JsValue::Object(object) => { - js_object_to_string(&self, &object, context) - } - boa_engine::JsValue::Rational(rational) => rational.to_string(), - boa_engine::JsValue::String(string) => string - .to_std_string() - .unwrap_or_else(|err| format!("InternalError: {err}")), - boa_engine::JsValue::Symbol(symbol) => symbol.to_string(), - boa_engine::JsValue::Undefined => "undefined".to_string(), - } - } - } - - fn js_object_to_string( - error_value: &boa_engine::JsValue, - js_object: &boa_engine::JsObject, - context: &mut boa_engine::Context, - ) -> String { - if js_object.is_error() { - return js_error_object_to_string(js_object, context); - } - - let to_string_js_value = match js_object.get("toString", context) { - Ok(to_string_js_value) => to_string_js_value, - Err(err) => { - return "TypeError: Property 'toString' of object is not a function".to_string() - } - }; - - let to_string_js_object = match to_string_js_value.as_object() { - Some(to_string_js_object) => to_string_js_object, - None => { - return "TypeError: Property 'toString' of object is not a function".to_string() - } - }; - - let string_js_value = match to_string_js_object.call(error_value, &[], context) { - Ok(string_js_value) => string_js_value, - Err(js_error) => return format!("InternalError: {js_error}"), - }; - - string_js_value - .try_from_vm_value(context) - .unwrap_or_else(|js_error| format!("InternalError: {js_error}")) - } - - fn js_error_object_to_string( - js_object: &boa_engine::JsObject, - context: &mut boa_engine::Context, - ) -> String { - try_js_error_object_to_string(js_object, context).unwrap_or_else(|js_error| { - let cause = js_error.to_std_string(&mut *context); - - format!( - "InternalError: Encountered an error while serializing an error\n \ - [cause]: {cause}" - ) - }) - } - - fn try_js_error_object_to_string( - js_object: &boa_engine::JsObject, - context: &mut boa_engine::Context, - ) -> Result { - let error_name = get_js_error_name(js_object, context)?; - let error_message = get_js_error_message(js_object, context)?; - let cause_opt = get_js_error_cause(js_object, context)?; - - let error_string = match cause_opt { - Some(cause) => format!( - "{error_name}: {error_message}\n [cause]: {cause}" - ), - None => format!("{error_name}: {error_message}"), - }; - - Ok(error_string) - } - - fn get_js_error_name( - js_object: &boa_engine::JsObject, - context: &mut boa_engine::Context, - ) -> Result { - match js_object.prototype() { - Some(prototype_js_object) => prototype_js_object - .get("name", &mut *context)? - .try_from_vm_value(&mut *context), - None => Ok("Error".to_string()), - } - } - - fn get_js_error_message( - js_object: &boa_engine::JsObject, - context: &mut boa_engine::Context, - ) -> Result { - js_object - .get("message", &mut *context)? - .try_from_vm_value(&mut *context) - } - - fn get_js_error_cause( - js_object: &boa_engine::JsObject, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> { - match js_object.get("cause", &mut *context) { - Ok(cause_js_value) => { - if cause_js_value.is_undefined() { - Ok(None) - } else { - Ok(Some(cause_js_value.to_std_string(&mut *context))) - } - }, - Err(js_error) => Err(js_error), - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/mod.rs deleted file mode 100644 index 8a4814c8e4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod utils; -mod wrong_enclosed_type; - -pub use wrong_enclosed_type::WrongEnclosedType; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/utils.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/utils.rs deleted file mode 100644 index 4b7465a4e1..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/utils.rs +++ /dev/null @@ -1,94 +0,0 @@ -use swc_common::Span; -use swc_ecma_ast::{TsType, TsTypeRef}; - -use crate::{ - traits::{GetName, GetSourceFileInfo, GetSpan}, - ts_ast::SourceMapped, - Error, -}; - -impl SourceMapped<'_, TsTypeRef> { - /// Returns the span of the enclosed type if it exists, otherwise returns - /// the span of the enclosing type - pub fn get_enclosed_span(&self) -> Span { - match &self.type_params { - Some(type_params) => type_params.span, - None => self.span, - } - } - - pub fn generate_example_func(&self) -> String { - if self.get_enclosed_ts_types().len() == 0 { - "Func void>>".to_string() - } else { - let enclosed_types = self.get_enclosed_ts_types().iter().enumerate().fold( - String::new(), - |acc, (index, enclosed_type)| { - let source_text = self.source_map.get_text(enclosed_type.get_span()); - format!("{}param_name{}: {}, ", acc, index, source_text) - }, - ); - let enclosed_types = enclosed_types[..enclosed_types.len() - 2].to_string(); - format!(" void>", enclosed_types) - } - } - - pub fn generate_example_variant(&self) -> Result { - if self.get_enclosed_ts_types().len() == 0 { - Ok(format!("{}<{{variant_name: null}}>", self.get_name())) - } else { - let enclosed_type = self.get_enclosed_ts_types().iter().enumerate().fold( - String::new(), - |acc, (index, enclosed_type)| { - let source_text = self.source_map.get_text(enclosed_type.get_span()); - format!("{} variant_name{}: {},\n", acc, index, source_text) - }, - ); - let enclosed_type = enclosed_type[..enclosed_type.len() - 2].to_string(); - Ok(format!("<{{\n{}\n}}>", enclosed_type)) - } - } - - pub fn generate_example_option(&self) -> Result { - if self.get_enclosed_ts_types().len() == 0 { - return Ok(format!("{}", self.get_name())); - } - let enclosed_types: String = self.get_enclosed_ts_types().iter().enumerate().fold( - String::new(), - |acc, (index, enclosed_type)| { - let source_text = self.source_map.get_text(enclosed_type.get_span()); - format!("{} member_name{}: {},\n", acc, index, source_text) - }, - ); - Ok(format!("<{{\n{}\n}}>", enclosed_types)) - } - - pub fn generate_example_record(&self) -> String { - "Record<{prop1: Type2, prop2: Type2, propN: TypeN}>".to_string() - } - - pub fn generate_example_tuple(&self) -> String { - "Tuple<[Type1, Type2, TypeN]>".to_string() - } - - pub fn generate_example_vec(&self) -> String { - "Vec".to_string() - } - - pub fn get_param_count(&self) -> usize { - self.get_enclosed_ts_types().len() - } -} - -trait GetEnclosedTsTypes { - fn get_enclosed_ts_types(&self) -> Vec; -} - -impl GetEnclosedTsTypes for TsTypeRef { - fn get_enclosed_ts_types(&self) -> Vec { - match &self.type_params { - Some(params) => params.params.iter().map(|param| *param.clone()).collect(), - None => vec![], - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/wrong_enclosed_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/wrong_enclosed_type.rs deleted file mode 100644 index 6bce636dd0..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/errors/wrong_enclosed_type.rs +++ /dev/null @@ -1,196 +0,0 @@ -use swc_common::source_map::Pos; -use swc_ecma_ast::TsTypeRef; - -use crate::{ - errors::{CompilerOutput, InternalError, Location, Suggestion, SuggestionModifications}, - traits::{GetName, GetSourceFileInfo, GetSourceInfo}, - ts_ast::SourceMapped, - Error, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct WrongEnclosedType { - name: EnclosingType, - modified_source: String, - modified_range: (usize, usize), - location: Location, -} - -// NOTE: Vec, and Opt are not included in this enum because they have much more -// flexibility with their enclosing type. Their enclosed type can be any sort of -// TsType. On the other hand Variants and Records must be TsTypeLiterals. Funcs -// have to be a very specific form of TsFnOrConstructorType, and Tuples need to -// be TsTupleTypes -#[derive(Debug, Clone, PartialEq)] -enum EnclosingType { - Variant, - Func, - Record, - Tuple, -} - -impl WrongEnclosedType { - pub fn error_from_ts_type_ref(sm_ts_type_ref: &SourceMapped) -> Error { - let original_location = sm_ts_type_ref.get_location(); - let name = sm_ts_type_ref.get_name(); - let name = match name.as_str() { - _ if sm_ts_type_ref.alias_table.variant.contains(&name) => EnclosingType::Variant, - _ if sm_ts_type_ref.alias_table.func.contains(&name) => EnclosingType::Func, - _ if sm_ts_type_ref.alias_table.record.contains(&name) => EnclosingType::Record, - _ if sm_ts_type_ref.alias_table.tuple.contains(&name) => EnclosingType::Tuple, - _ => return InternalError::new().into(), - }; - let (source, range) = match name { - EnclosingType::Func => sm_ts_type_ref.get_func_source_and_range(), - _ => (original_location.source, original_location.range), - }; - let (modified_source, modified_range) = match name { - EnclosingType::Variant => match sm_ts_type_ref.variant_wrong_enclosed_type_error() { - Ok(value) => value, - Err(err) => return err, - }, - EnclosingType::Func => sm_ts_type_ref.get_func_suggestion_modifications(), - _ => ("".to_string(), (0, 0)), // TODO make arms for tuple and record - }; - - Self { - modified_source, - modified_range, - location: Location { - source, - range, - ..original_location - }, - name, - } - .into() - } - - fn variant_wrong_enclosed_type_error(&self) -> CompilerOutput { - let suggestion = Some(Suggestion { - title: "Variants must have a type literal as the enclosed type.".to_string(), - source: self.modified_source.clone(), - range: self.modified_range, - annotation: Some("Try wrapping your value in a type literal.".to_string()), - import_suggestion: None, - }); - CompilerOutput { - title: "Invalid Variant".to_string(), - location: self.location.clone(), - annotation: "Must have type literal enclosed here.".to_string(), - suggestion, - } - } - - fn record_wrong_enclosed_type_error(&self) -> CompilerOutput { - let suggestion = Some(Suggestion { - title: "Records must have a type literal as the enclosed type.".to_string(), - source: self.modified_source.clone(), - range: self.modified_range, - annotation: Some("Try wrapping your value in a type literal.".to_string()), - import_suggestion: None, - }); - CompilerOutput { - title: "Invalid Record".to_string(), - location: self.location.clone(), - annotation: "Must have type literal enclosed here.".to_string(), - suggestion, - } - } - - fn tuple_wrong_enclosed_type_error(&self) -> CompilerOutput { - CompilerOutput { - title: "Invalid Record".to_string(), - location: self.location.clone(), - annotation: "Must have type literal enclosed here.".to_string(), - suggestion: None, - } - } - - // TODO: 2 ways to improve this: - // - // 1. If the enclosed type is a TsFunc type, suggest that they wrap it in - // `Oneway`, `Query`, or `Update` and show them what that would look like in - // the example. - // - // 2. If the enclosed type is a TypeRef that contains a TsFunc, just with - // the wrong name, we should only modify the name in the example, (rather - // than nuking their function signature). - fn func_wrong_enclosed_type_error(&self) -> CompilerOutput { - CompilerOutput { - title: "Invalid Func declaration".to_string(), - location: self.location.clone(), - annotation: "the type params here are invalid".to_string(), - suggestion: Some(Suggestion { - title: - "Funcs must have either Query, Update, or Oneway as the enclosed type. E.g.:" - .to_string(), - range: self.modified_range, - source: self.modified_source.clone(), - annotation: None, - import_suggestion: None, - }), - } - } -} - -impl std::error::Error for WrongEnclosedType {} - -impl std::fmt::Display for WrongEnclosedType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - let compiler_output = match self.name { - EnclosingType::Variant => self.variant_wrong_enclosed_type_error(), - EnclosingType::Func => self.func_wrong_enclosed_type_error(), - EnclosingType::Record => self.record_wrong_enclosed_type_error(), - EnclosingType::Tuple => self.tuple_wrong_enclosed_type_error(), - }; - write!(f, "{}", compiler_output) - } -} - -impl From for crate::Error { - fn from(value: WrongEnclosedType) -> Self { - Self::WrongEnclosedType(value) - } -} - -impl SourceMapped<'_, TsTypeRef> { - fn variant_wrong_enclosed_type_error(&self) -> Result { - let example_variant = self.generate_example_variant()?; - let modified_source = self - .source_map - .generate_modified_source(self.get_enclosed_span(), &example_variant); - let modified_range = self - .source_map - .generate_modified_range(self.get_enclosed_span(), &example_variant); - Ok((modified_source, modified_range)) - } - - fn get_func_suggestion_modifications(&self) -> SuggestionModifications { - let example_func = "Update<() => void>".to_string(); - - let (source, (start_pos, end_pos)) = self.get_func_source_and_range(); - - let modified_source = format!( - "{}{}{}", - source[..start_pos + 1].to_string(), - example_func, - source[end_pos - 1..].to_string() - ); - let modified_range = (start_pos + 1, start_pos + 1 + example_func.len()); - (modified_source, modified_range) - } - - fn get_func_source_and_range(&self) -> (String, (usize, usize)) { - let type_params_absolute_range = (self.get_enclosed_span().lo, self.get_enclosed_span().hi); - let source = self - .source_map - .get_source_from_range(type_params_absolute_range); - - let start_pos = self.source_map.get_range(self.get_enclosed_span()).0; - let offset = type_params_absolute_range.0.to_usize() - start_pos; - let end_pos = self.get_enclosed_span().hi.to_usize() - offset; - let range = (start_pos, end_pos); - (source, range) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/func/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/func/mod.rs deleted file mode 100644 index 3f9a5499ca..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/func/mod.rs +++ /dev/null @@ -1,101 +0,0 @@ -use cdk_framework::{ - act::node::{candid::Func, node_parts::mode::Mode}, - traits::{CollectIterResults, CollectResults}, -}; -use std::ops::Deref; -use swc_ecma_ast::{TsFnOrConstructorType, TsType, TsTypeAliasDecl, TsTypeAnn, TsTypeRef}; - -use crate::{ - traits::{GetName, GetTsType}, - ts_ast::SourceMapped, - Error, -}; - -use super::errors::WrongEnclosedType; - -mod rust; - -impl SourceMapped<'_, TsTypeAliasDecl> { - pub fn to_func(&self) -> Result, Vec> { - if self.is_something_that_could_be_in_the_alias_table() { - return Ok(None); - } - self.process_ts_type_ref(&self.alias_table.func, |ts_type_ref| { - ts_type_ref.to_func(Some(self.id.get_name())) - }) - .map(|result| result.flatten()) - } -} - -impl SourceMapped<'_, TsTypeRef> { - pub fn is_func(&self) -> bool { - self.alias_table.func.contains(&self.get_name()) - } - - pub fn to_func(&self, name: Option) -> Result, Vec> { - if !self.is_func() { - return Ok(None); - } - let request_type_ts_type = self.get_ts_type()?; - let request_type_type_ref = match request_type_ts_type.deref() { - TsType::TsTypeRef(ts_type_ref) => self.spawn(ts_type_ref), - _ => return Err(vec![WrongEnclosedType::error_from_ts_type_ref(self).into()]), - }; - - let (mode, ts_type) = ( - { - let name = request_type_type_ref.get_name(); - match name.as_str() { - _ if self.alias_table.query_mode.contains(&name) => Ok(Mode::Query), - _ if self.alias_table.update_mode.contains(&name) => Ok(Mode::Update), - _ if self.alias_table.oneway_mode.contains(&name) => Ok(Mode::Oneway), - _ => Err(vec![WrongEnclosedType::error_from_ts_type_ref(self).into()]), - } - }, - request_type_type_ref.get_ts_type().map_err(Error::into), - ) - .collect_results()?; - - let ts_fn_type = match ts_type.deref() { - TsType::TsFnOrConstructorType(TsFnOrConstructorType::TsFnType(ts_fn_type)) => { - self.spawn(ts_fn_type) - } - _ => return Err(vec![WrongEnclosedType::error_from_ts_type_ref(self).into()]), - }; - - let param_to_candid = |param: &TsType| self.spawn(param).to_candid_type(); - - let (params, return_type) = ( - ts_fn_type - .get_param_types()? - .iter() - .map(param_to_candid) - .collect_results(), - self.spawn(&ts_fn_type.get_ts_type_ann().get_ts_type()) - .to_candid_type(), - ) - .collect_results()?; - - let to_vm_value = |name: String| rust::generate_into_vm_value_impl(name); - let list_to_vm_value = |name: String| rust::generate_list_into_vm_value_impl(name); - let from_vm_value = |name: String| rust::generate_from_vm_value_impl(name); - let list_from_vm_value = |name: String| rust::generate_list_from_vm_value_impl(name); - - Ok(Some(Func::new( - name, - params, - return_type, - mode, - to_vm_value, - list_to_vm_value, - from_vm_value, - list_from_vm_value, - ))) - } -} - -impl GetTsType for TsTypeAnn { - fn get_ts_type(&self) -> swc_ecma_ast::TsType { - *self.type_ann.clone() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/func/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/func/rust.rs deleted file mode 100644 index 3dc62abd04..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/func/rust.rs +++ /dev/null @@ -1,48 +0,0 @@ -use cdk_framework::traits::ToIdent; -use proc_macro2::TokenStream; -use quote::{quote, ToTokens}; - -pub fn generate_into_vm_value_impl(function_name: String) -> TokenStream { - let function_name = function_name.to_ident().to_token_stream(); - quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for #function_name { - fn try_into_vm_value(self, context: &mut boa_engine::Context) -> Result { - self.0.try_into_vm_value(context) - } - } - } -} - -pub fn generate_list_into_vm_value_impl(function_name: String) -> TokenStream { - let function_name = function_name.to_ident().to_token_stream(); - quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for Vec<#function_name> { - fn try_into_vm_value(self, context: &mut boa_engine::Context) -> Result { - try_into_vm_value_generic_array(self, context) - } - } - } -} - -pub fn generate_from_vm_value_impl(function_name: String) -> TokenStream { - let function_name = function_name.to_ident().to_token_stream(); - quote! { - impl CdkActTryFromVmValue<#function_name, boa_engine::JsError, &mut boa_engine::Context<'_>> for boa_engine::JsValue { - fn try_from_vm_value(self, context: &mut boa_engine::Context) -> Result<#function_name, boa_engine::JsError> { - let candid_func: candid::Func = self.try_from_vm_value(context)?; - Ok(#function_name::new(candid_func.principal, candid_func.method)) - } - } - } -} - -pub fn generate_list_from_vm_value_impl(function_name: String) -> TokenStream { - let function_name = function_name.to_ident().to_token_stream(); - quote! { - impl CdkActTryFromVmValue, boa_engine::JsError, &mut boa_engine::Context<'_>> for boa_engine::JsValue { - fn try_from_vm_value(self, context: &mut boa_engine::Context) -> Result, boa_engine::JsError> { - try_from_vm_value_generic_array(self, context) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/mod.rs deleted file mode 100644 index 54b6a17a2a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/mod.rs +++ /dev/null @@ -1,57 +0,0 @@ -use cdk_framework::{ - act::CandidTypes, - traits::{CollectIterResults, CollectResults}, -}; -use swc_ecma_ast::TsTypeAliasDecl; - -use crate::{ - ts_ast::{SourceMapped, TsAst}, - Error, -}; - -pub mod errors; -pub mod func; -pub mod opt; -pub mod primitive; -pub mod record; -pub mod service; -pub mod tuple; -pub mod type_alias; -pub mod type_param; -pub mod type_ref; -pub mod variant; -pub mod vec; - -impl TsAst { - pub fn build_candid_types(&self) -> Result> { - let (type_aliases, funcs, records, services, tuples, variants) = ( - self.extract_candid_types(|x| x.to_type_alias()), - self.extract_candid_types(|x| x.to_func()), - self.extract_candid_types(|x| x.to_record()), - self.build_services(), - self.extract_candid_types(|x| x.to_tuple()), - self.extract_candid_types(|x| x.to_variant()), - ) - .collect_results()?; - - Ok(CandidTypes { - funcs, - records, - services, - tuples, - type_aliases, - variants, - }) - } - - pub fn extract_candid_types(&self, extractor: F) -> Result, Vec> - where - F: Fn(&SourceMapped) -> Result, Vec>, - { - self.ts_type_alias_decls() - .iter() - .map(|ts_type_alias_decl| extractor(&ts_type_alias_decl).transpose()) - .flatten() - .collect_results() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/opt/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/opt/mod.rs deleted file mode 100644 index 0767033dd5..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/opt/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -use cdk_framework::act::node::candid::Opt; -use swc_ecma_ast::TsTypeRef; - -use crate::{traits::GetName, ts_ast::SourceMapped, Error}; - -impl SourceMapped<'_, TsTypeRef> { - pub fn to_option(&self) -> Result, Vec> { - if self.alias_table.opt.contains(&self.get_name()) { - let enclosed_act_data_type = self.get_ts_type()?.to_candid_type()?; - Ok(Some(Opt { - enclosed_type: Box::from(enclosed_act_data_type), - })) - } else { - Ok(None) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/errors/mod.rs deleted file mode 100644 index 3fbf1acde3..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/errors/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod unsupported_type; - -pub use unsupported_type::UnsupportedType; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/errors/unsupported_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/errors/unsupported_type.rs deleted file mode 100644 index 2efa3bb9f6..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/errors/unsupported_type.rs +++ /dev/null @@ -1,92 +0,0 @@ -use swc_ecma_ast::{TsKeywordType, TsKeywordTypeKind}; - -use crate::{ - errors::{CompilerOutput, InternalError, Location, Suggestion, SuggestionModifications}, - traits::{GetSourceFileInfo, GetSourceInfo, GetSourceText}, - ts_ast::SourceMapped, - Error, -}; - -#[derive(Clone, Debug, PartialEq)] -pub struct UnsupportedType { - annotation: String, - location: Location, - suggestion_modifications: Option, -} - -impl std::error::Error for UnsupportedType {} - -impl UnsupportedType { - pub fn error_from_ts_keyword_type(sm_keyword_type: &SourceMapped) -> Error { - let (suggestion_modifications, annotation) = match &sm_keyword_type.kind { - TsKeywordTypeKind::TsBigIntKeyword => sm_keyword_type.create_bigint_error(), - TsKeywordTypeKind::TsObjectKeyword => sm_keyword_type.create_not_supported_tuple(), - TsKeywordTypeKind::TsNeverKeyword => sm_keyword_type.create_not_supported_tuple(), - TsKeywordTypeKind::TsSymbolKeyword => sm_keyword_type.create_not_supported_tuple(), - TsKeywordTypeKind::TsIntrinsicKeyword => sm_keyword_type.create_not_supported_tuple(), - TsKeywordTypeKind::TsUndefinedKeyword => sm_keyword_type.create_not_supported_tuple(), - TsKeywordTypeKind::TsUnknownKeyword => sm_keyword_type.create_not_supported_tuple(), - TsKeywordTypeKind::TsAnyKeyword => sm_keyword_type.create_not_supported_tuple(), - _ => return Error::InternalError(InternalError::new()), - }; - Self { - annotation, - location: sm_keyword_type.get_location(), - suggestion_modifications, - } - .into() - } -} - -impl From for crate::Error { - fn from(error: UnsupportedType) -> Self { - Self::UnsupportedType(error) - } -} - -impl std::fmt::Display for UnsupportedType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let title = "`int` will cover most everything that `bigint` does. For more number type options see: https://internetcomputer.org/docs/current/references/candid-ref/#type-nat".to_string(); - let suggestion = match &self.suggestion_modifications { - Some(suggestion_modifications) => Some(Suggestion { - annotation: Some("Try using `int` here.".to_string()), - import_suggestion: Some("import { int } from 'azle';".to_string()), - source: suggestion_modifications.0.clone(), - range: suggestion_modifications.1, - title, - }), - None => None, - }; - let compiler_output = CompilerOutput { - title: "Unsupported Type".to_string(), - annotation: self.annotation.clone(), - suggestion, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} - -impl SourceMapped<'_, TsKeywordType> { - fn create_bigint_error(&self) -> (Option, String) { - let replacement = "int".to_string(); - let range = self - .source_map - .generate_modified_range(self.span, &replacement); - let source = self - .source_map - .generate_modified_source(self.span, &replacement); - - ( - Some((source, range)), - "bigint is not a supported type".to_string(), - ) - } - - fn create_not_supported_tuple(&self) -> (Option, String) { - ( - None, - format!("{} is not a supported type", self.get_source_text()), - ) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/mod.rs deleted file mode 100644 index def6e537a8..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/primitive/mod.rs +++ /dev/null @@ -1,62 +0,0 @@ -pub mod errors; - -use cdk_framework::act::node::candid::Primitive; -use swc_common::Span; -use swc_ecma_ast::{TsKeywordType, TsKeywordTypeKind, TsTypeRef}; - -use crate::{ - traits::{GetName, GetSpan}, - ts_ast::SourceMapped, - Error, -}; - -use self::errors::UnsupportedType; - -impl SourceMapped<'_, TsKeywordType> { - pub fn to_primitive(&self) -> Result { - Ok(match self.kind { - TsKeywordTypeKind::TsBooleanKeyword => Primitive::Bool, - TsKeywordTypeKind::TsStringKeyword => Primitive::String, - TsKeywordTypeKind::TsVoidKeyword => Primitive::Void, - TsKeywordTypeKind::TsNullKeyword => Primitive::Null, - TsKeywordTypeKind::TsNumberKeyword => Primitive::Float64, - TsKeywordTypeKind::TsBigIntKeyword => Primitive::Int, - _ => return Err(UnsupportedType::error_from_ts_keyword_type(self).into()), - }) - } -} - -impl SourceMapped<'_, TsTypeRef> { - pub fn to_primitive(&self) -> Result, Error> { - let name = self.get_name(); - Ok(Some(match name.as_str() { - _ if self.alias_table.blob.contains(&name) => Primitive::Blob, - _ if self.alias_table.float32.contains(&name) => Primitive::Float32, - _ if self.alias_table.float64.contains(&name) => Primitive::Float64, - _ if self.alias_table.int.contains(&name) => Primitive::Int, - _ if self.alias_table.int8.contains(&name) => Primitive::Int8, - _ if self.alias_table.int16.contains(&name) => Primitive::Int16, - _ if self.alias_table.int32.contains(&name) => Primitive::Int32, - _ if self.alias_table.int64.contains(&name) => Primitive::Int64, - _ if self.alias_table.nat.contains(&name) => Primitive::Nat, - _ if self.alias_table.nat8.contains(&name) => Primitive::Nat8, - _ if self.alias_table.nat16.contains(&name) => Primitive::Nat16, - _ if self.alias_table.nat32.contains(&name) => Primitive::Nat32, - _ if self.alias_table.nat64.contains(&name) => Primitive::Nat64, - _ if self.alias_table.principal.contains(&name) => Primitive::Principal, - _ if self.alias_table.empty.contains(&name) => Primitive::Empty, - _ if self.alias_table.reserved.contains(&name) => Primitive::Reserved, - _ if self.alias_table.text.contains(&name) => Primitive::String, - _ if self.alias_table.null.contains(&name) => Primitive::Null, - _ if self.alias_table.void.contains(&name) => Primitive::Void, - _ if self.alias_table.bool.contains(&name) => Primitive::Bool, - _ => return Ok(None), - })) - } -} - -impl GetSpan for TsKeywordType { - fn get_span(&self) -> Span { - self.span - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/errors/mod.rs deleted file mode 100644 index 68a9900c72..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/errors/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod record_property_signature; - -pub use record_property_signature::RecordPropertySignature; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/errors/record_property_signature.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/errors/record_property_signature.rs deleted file mode 100644 index 39d67a8f20..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/errors/record_property_signature.rs +++ /dev/null @@ -1,63 +0,0 @@ -use swc_ecma_ast::TsTypeElement; - -use crate::{ - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::{GetSourceFileInfo, GetSourceInfo, GetSpan, TypeToString}, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct RecordPropertySignature { - location: Location, - type_name: String, - suggestion_modifications: SuggestionModifications, -} - -impl RecordPropertySignature { - pub fn from_ts_type_element(sm_ts_type_elements: &SourceMapped) -> Self { - let replacement = "property_name: boolean".to_string(); - let suggestion_modifications = ( - sm_ts_type_elements - .source_map - .generate_modified_source(sm_ts_type_elements.get_span(), &replacement), - sm_ts_type_elements - .source_map - .generate_modified_range(sm_ts_type_elements.get_span(), &replacement), - ); - - Self { - location: sm_ts_type_elements.get_location(), - suggestion_modifications, - type_name: sm_ts_type_elements.type_to_string(), - } - } - - fn record_property_signature_error(&self) -> CompilerOutput { - CompilerOutput { - title: "Invalid Record".to_string(), - location: self.location.clone(), - annotation: format!("{} is not allowed here.", self.type_name), - suggestion: Some(Suggestion { - title: "Record members must be properties.".to_string(), - source: self.suggestion_modifications.0.clone(), - range: self.suggestion_modifications.1, - annotation: Some("For example".to_string()), - import_suggestion: None, - }), - } - } -} - -impl std::error::Error for RecordPropertySignature {} - -impl From for crate::Error { - fn from(error: RecordPropertySignature) -> Self { - Self::RecordPropertySignature(error) - } -} - -impl std::fmt::Display for RecordPropertySignature { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.record_property_signature_error()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/mod.rs deleted file mode 100644 index 1bd66a15c0..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/record/mod.rs +++ /dev/null @@ -1,91 +0,0 @@ -pub mod errors; - -use cdk_framework::{ - act::node::candid::{record::Member, Record}, - traits::{CollectIterResults, CollectResults}, -}; -use swc_ecma_ast::{TsPropertySignature, TsTypeAliasDecl, TsTypeElement, TsTypeLit, TsTypeRef}; - -use crate::{traits::GetName, ts_ast::SourceMapped, Error}; - -use self::errors::RecordPropertySignature; - -use super::errors::WrongEnclosedType; - -impl SourceMapped<'_, TsTypeAliasDecl> { - pub fn to_record(&self) -> Result, Vec> { - self.process_ts_type_ref(&self.alias_table.record, |type_ref| { - if self.is_something_that_could_be_in_the_alias_table() { - return Ok(None); - } - let (type_params, record_type_ref) = - (self.get_type_params(), type_ref.to_record()).collect_results()?; - match record_type_ref { - Some(members) => Ok(Some(Record { - name: Some(self.id.get_name()), - type_params: type_params.into(), - ..members - })), - None => Ok(None), - } - }) - .map(|result| result.flatten()) - } -} - -impl SourceMapped<'_, TsTypeRef> { - pub fn is_record(&self) -> bool { - return self.alias_table.record.contains(&self.get_name()); - } - - pub fn to_record(&self) -> Result, Vec> { - if !self.is_record() { - return Ok(None); - } - Ok(Some( - match self.get_ts_type()?.as_ts_type_lit() { - Some(ts_type_lit) => ts_type_lit, - None => return Err(vec![WrongEnclosedType::error_from_ts_type_ref(self).into()]), - } - .to_record()?, - )) - } -} - -impl SourceMapped<'_, TsTypeLit> { - pub fn to_record(&self) -> Result> { - let members: Vec = self - .members - .iter() - .map(|member| self.spawn(member).to_record_member()) - .collect_results()?; - - Ok(Record { - name: None, - members, - type_params: vec![].into(), - }) - } -} - -impl SourceMapped<'_, TsTypeElement> { - pub fn to_record_member(&self) -> Result> { - match self.as_property_signature() { - Some(ts_property_signature) => ts_property_signature.to_record_member(), - None => Err(vec![ - RecordPropertySignature::from_ts_type_element(self).into() - ]), - } - } -} - -impl SourceMapped<'_, TsPropertySignature> { - pub fn to_record_member(&self) -> Result> { - let (name, candid_type) = ( - self.get_member_name().map_err(Error::into), - self.get_act_data_type(), - ) - .collect_results()?; - Ok(Member { name, candid_type }) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/get_service_class_decls.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/get_service_class_decls.rs deleted file mode 100644 index 56abb512d9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/get_service_class_decls.rs +++ /dev/null @@ -1,88 +0,0 @@ -use std::ops::Deref; -use swc_common::SourceMap; -use swc_ecma_ast::{ClassDecl, Decl, Module, ModuleDecl, ModuleItem, Stmt}; - -use crate::{ - traits::GetOptionalName, - ts_ast::{Program, SourceMapped}, - AliasTable, -}; - -pub trait GetFlattenedServiceClassDecls { - fn get_service_class_declarations(&self) -> Vec>; -} - -impl GetFlattenedServiceClassDecls for Vec { - fn get_service_class_declarations(&self) -> Vec> { - self.into_iter() - .flat_map(|program| program.get_service_class_declarations()) - .collect() - } -} - -impl Program { - fn get_service_class_declarations(&self) -> Vec> { - match self.deref() { - swc_ecma_ast::Program::Module(module) => module.get_service_class_declarations( - &self.source_map, - &self.alias_table, - &self.alias_list, - ), - swc_ecma_ast::Program::Script(_) => vec![], - } - } -} - -trait GetServiceClassDecls { - fn get_service_class_declarations<'a>( - &'a self, - source_map: &'a SourceMap, - alias_table: &'a AliasTable, - alias_list: &'a Vec, - ) -> Vec>; -} - -impl GetServiceClassDecls for Module { - fn get_service_class_declarations<'a>( - &'a self, - source_map: &'a SourceMap, - alias_table: &'a AliasTable, - alias_list: &'a Vec, - ) -> Vec> { - self.body.iter().fold(vec![], |mut acc, module_item| { - // acc is mut because SourceMapped can't be cloned, which is - // necessary to do something like: - // return vec![acc, vec![SourceMapped::new(class_decl, source_map)]].concat(); - - let decl_opt = match module_item { - ModuleItem::ModuleDecl(decl) => match decl { - ModuleDecl::ExportDecl(export_decl) => Some(&export_decl.decl), - _ => None, - }, - ModuleItem::Stmt(stmt) => match stmt { - Stmt::Decl(decl) => Some(decl), - _ => None, - }, - }; - - if let Some(decl) = decl_opt { - if let Decl::Class(class_decl) = decl { - if let Some(super_class) = &class_decl.class.super_class { - if let Some(name) = super_class.get_name() { - if alias_table.service.contains(&name) { - acc.push(SourceMapped::new( - class_decl, - source_map, - alias_table, - alias_list, - )) - } - } - } - } - } - - acc - }) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/get_span.rs deleted file mode 100644 index ac27c68170..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/get_span.rs +++ /dev/null @@ -1,25 +0,0 @@ -use swc_common::Span; -use swc_ecma_ast::{ClassMember, ClassProp}; - -use crate::traits::GetSpan; - -impl GetSpan for ClassProp { - fn get_span(&self) -> Span { - self.span - } -} - -impl GetSpan for ClassMember { - fn get_span(&self) -> Span { - match self { - ClassMember::Constructor(constructor) => constructor.span, - ClassMember::Method(method) => method.span, - ClassMember::PrivateMethod(private_method) => private_method.span, - ClassMember::ClassProp(class_prop) => class_prop.span, - ClassMember::PrivateProp(private_prop) => private_prop.span, - ClassMember::TsIndexSignature(ts_index_signature) => ts_index_signature.span, - ClassMember::Empty(empty) => empty.span, - ClassMember::StaticBlock(static_block) => static_block.span, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/computed_property_not_allowed.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/computed_property_not_allowed.rs deleted file mode 100644 index a36d107ddf..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/computed_property_not_allowed.rs +++ /dev/null @@ -1,40 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ComputedPropertyNotAllowed { - location: Location, -} - -impl ComputedPropertyNotAllowed { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for ComputedPropertyNotAllowed {} - -impl From for crate::Error { - fn from(error: ComputedPropertyNotAllowed) -> Self { - Self::ComputedPropertyNotAllowed(error) - } -} - -impl std::fmt::Display for ComputedPropertyNotAllowed { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Computed property not allowed. Computed properties in service definitions aren't currently supported.".to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_class_member.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_class_member.rs deleted file mode 100644 index 76d74f08af..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_class_member.rs +++ /dev/null @@ -1,76 +0,0 @@ -use swc_ecma_ast::{ClassDecl, ClassMember}; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::{GetName, GetSourceFileInfo, GetSpan}, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct InvalidClassMember { - location: Location, - member_type: String, - class_name: String, -} - -impl InvalidClassMember { - pub fn from_class_decl( - class_decl: &SourceMapped, - class_member: &ClassMember, - ) -> Self { - let class_name = class_decl.ident.get_name(); - - let member_type = match class_member { - ClassMember::Constructor(_) => "constructor", - ClassMember::Method(_) => "method", - ClassMember::PrivateMethod(_) => "private method", - ClassMember::ClassProp(_) => "class prop", - ClassMember::PrivateProp(_) => "private prop", - ClassMember::TsIndexSignature(_) => "TS index signature", - ClassMember::Empty(_) => "empty block", - ClassMember::StaticBlock(_) => "static block", - } - .to_string(); - - Self { - location: class_decl.build_location_from_class_member(class_member), - member_type, - class_name, - } - } -} - -impl std::error::Error for InvalidClassMember {} - -impl From for crate::Error { - fn from(error: InvalidClassMember) -> Self { - Self::InvalidClassMember(error) - } -} - -impl std::fmt::Display for InvalidClassMember { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: format!( - "Invalid {} in class {}\nHelp: Remove this member or make it a property", - self.member_type, self.class_name, - ), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} - -impl SourceMapped<'_, ClassDecl> { - fn build_location_from_class_member(&self, class_member: &ClassMember) -> Location { - let span = class_member.get_span(); - Location { - origin: self.source_map.get_origin(span), - line_number: self.source_map.get_line_number(span), - range: self.source_map.get_range(span), - source: self.source_map.get_source(span), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_decorator.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_decorator.rs deleted file mode 100644 index a37d0cc55d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_decorator.rs +++ /dev/null @@ -1,41 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct InvalidDecorator { - location: Location, -} - -impl InvalidDecorator { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for InvalidDecorator {} - -impl From for crate::Error { - fn from(error: InvalidDecorator) -> Self { - Self::InvalidDecorator(error) - } -} - -impl std::fmt::Display for InvalidDecorator { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Invalid decorator. Only @serviceQuery and @serviceUpdate are permitted." - .to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_return_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_return_type.rs deleted file mode 100644 index 48548c45a4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/invalid_return_type.rs +++ /dev/null @@ -1,41 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct InvalidReturnType { - location: Location, -} - -impl InvalidReturnType { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for InvalidReturnType {} - -impl From for crate::Error { - fn from(error: InvalidReturnType) -> Self { - Self::InvalidReturnType(error) - } -} - -impl std::fmt::Display for InvalidReturnType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Method has an invalid return type. Only function return types are permitted." - .to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_call_result_annotation.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_call_result_annotation.rs deleted file mode 100644 index 50b5f1ec66..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_call_result_annotation.rs +++ /dev/null @@ -1,40 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MissingCallResultAnnotation { - location: Location, -} - -impl MissingCallResultAnnotation { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for MissingCallResultAnnotation {} - -impl From for crate::Error { - fn from(error: MissingCallResultAnnotation) -> Self { - Self::MissingCallResultAnnotation(error) - } -} - -impl std::fmt::Display for MissingCallResultAnnotation { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Invalid return type. External canister methods must wrap their return types in the CallResult generic type.".to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_decorator.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_decorator.rs deleted file mode 100644 index 52493e3a94..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_decorator.rs +++ /dev/null @@ -1,40 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MissingDecorator { - location: Location, -} - -impl MissingDecorator { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for MissingDecorator {} - -impl From for crate::Error { - fn from(error: MissingDecorator) -> Self { - Self::MissingDecorator(error) - } -} - -impl std::fmt::Display for MissingDecorator { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Missing decorator. External canister methods must be decorated with either @query or @update.".to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_type_annotation.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_type_annotation.rs deleted file mode 100644 index 65c23f3389..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_type_annotation.rs +++ /dev/null @@ -1,41 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MissingTypeAnnotation { - location: Location, -} - -impl MissingTypeAnnotation { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for MissingTypeAnnotation {} - -impl From for crate::Error { - fn from(error: MissingTypeAnnotation) -> Self { - Self::MissingTypeAnnotation(error) - } -} - -impl std::fmt::Display for MissingTypeAnnotation { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Missing type annotation. External canister methods must specify a return type." - .to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_type_argument.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_type_argument.rs deleted file mode 100644 index 3319465849..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/missing_type_argument.rs +++ /dev/null @@ -1,33 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{errors::Location, traits::GetSourceInfo, ts_ast::SourceMapped}; - -#[derive(Debug, Clone, PartialEq)] -pub struct MissingTypeArguments { - message: String, - location: Location, -} - -impl MissingTypeArguments { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - message: "Missing type argument. Generic type CallResult requires 1 type argument." - .to_string(), - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for MissingTypeArguments {} - -impl From for crate::Error { - fn from(error: MissingTypeArguments) -> Self { - Self::MissingTypeArgument(error) - } -} - -impl std::fmt::Display for MissingTypeArguments { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.message) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/mod.rs deleted file mode 100644 index 21550461f3..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -mod computed_property_not_allowed; -mod invalid_class_member; -mod invalid_decorator; -mod invalid_return_type; -mod missing_call_result_annotation; -mod missing_decorator; -mod missing_type_annotation; -mod missing_type_argument; -mod not_exactly_one_decorator; -mod too_many_return_types; - -pub use computed_property_not_allowed::ComputedPropertyNotAllowed; -pub use invalid_class_member::InvalidClassMember; -pub use invalid_decorator::InvalidDecorator; -pub use invalid_return_type::InvalidReturnType; -pub use missing_call_result_annotation::MissingCallResultAnnotation; -pub use missing_decorator::MissingDecorator; -pub use missing_type_annotation::MissingTypeAnnotation; -pub use missing_type_argument::MissingTypeArguments; -pub use not_exactly_one_decorator::NotExactlyOneDecorator; -pub use too_many_return_types::TooManyReturnTypes; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/not_exactly_one_decorator.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/not_exactly_one_decorator.rs deleted file mode 100644 index 546bd6c71f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/not_exactly_one_decorator.rs +++ /dev/null @@ -1,45 +0,0 @@ -use swc_ecma_ast::{ClassProp, Decorator}; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct NotExactlyOneDecorator { - decorators: Vec, - location: Location, -} - -impl NotExactlyOneDecorator { - pub fn from_decorator_list( - decorators: &Vec, - sm_class_prop: &SourceMapped, - ) -> Self { - Self { - decorators: decorators.clone(), - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for NotExactlyOneDecorator {} - -impl From for crate::Error { - fn from(error: NotExactlyOneDecorator) -> Self { - Self::NotExactlyOneDecorator(error) - } -} - -impl std::fmt::Display for NotExactlyOneDecorator { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Too many decorators. Service methods can only specify one decorator: @serviceQuery or @serviceUpdate.".to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/too_many_return_types.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/too_many_return_types.rs deleted file mode 100644 index 1313d77e72..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/errors/too_many_return_types.rs +++ /dev/null @@ -1,41 +0,0 @@ -use swc_ecma_ast::ClassProp; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct TooManyReturnTypes { - location: Location, -} - -impl TooManyReturnTypes { - pub fn from_class_prop(sm_class_prop: &SourceMapped) -> Self { - Self { - location: sm_class_prop.get_location(), - } - } -} - -impl std::error::Error for TooManyReturnTypes {} - -impl From for crate::Error { - fn from(error: TooManyReturnTypes) -> Self { - Self::TooManyReturnTypes(error) - } -} - -impl std::fmt::Display for TooManyReturnTypes { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Too many return types. Generic type CallResult requires 1 type argument" - .to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/mod.rs deleted file mode 100644 index 8f6df1d872..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -use cdk_framework::{act::node::candid::service::Method, traits::CollectIterResults}; -use swc_ecma_ast::{ClassDecl, ClassMember}; - -use crate::{ts_ast::SourceMapped, Error}; - -use self::errors::InvalidClassMember; - -pub mod errors; -mod to_service_method; - -impl SourceMapped<'_, ClassDecl> { - pub fn build_service_methods(&self) -> Result, Vec> { - self.class - .body - .iter() - .map(|member| self.class_member_to_service_method(member)) - .collect_results() - } - - fn class_member_to_service_method( - &self, - class_member: &ClassMember, - ) -> Result> { - match class_member { - ClassMember::ClassProp(class_prop) => { - let class_prop_with_source_map = self.spawn(class_prop); - - class_prop_with_source_map.to_service_method() - } - _ => Err(vec![InvalidClassMember::from_class_decl( - self, - class_member, - ) - .into()]), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/to_service_method.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/to_service_method.rs deleted file mode 100644 index 6dd001ea1b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/method/to_service_method.rs +++ /dev/null @@ -1,205 +0,0 @@ -use cdk_framework::{ - act::node::{candid::service::Method, node_parts::mode::Mode, CandidType, Param}, - traits::{CollectIterResults, CollectResults}, -}; -use swc_ecma_ast::{ClassProp, TsFnOrConstructorType, TsFnParam, TsFnType, TsType}; - -pub use crate::canister_method::check_length_and_map::CheckLengthAndMapTwo; -use crate::{ - errors::errors::{ - ArrayDestructuringInParamsNotSupported, FunctionParamsMustHaveType, - ObjectDestructuringNotSupported, RestParametersNotSupported, - }, - traits::{GetName, GetOptionalName, GetTsType}, - ts_ast::SourceMapped, - Error, -}; - -use super::errors::{ - ComputedPropertyNotAllowed, InvalidDecorator, InvalidReturnType, MissingCallResultAnnotation, - MissingDecorator, MissingTypeAnnotation, MissingTypeArguments, NotExactlyOneDecorator, - TooManyReturnTypes, -}; - -impl SourceMapped<'_, ClassProp> { - pub fn to_service_method(&self) -> Result> { - let (_, _, name, mode, params, return_type) = ( - if self.decorators.len() == 0 { - Err(vec![MissingDecorator::from_class_prop(self).into()]) - } else { - Ok(()) - }, - if !self.has_azle_decorator() { - Err(vec![InvalidDecorator::from_class_prop(self).into()]) - } else { - Ok(()) - }, - self.name().map_err(Error::into), - { - let decorator_name = self.get_decorator_name()?[..].to_string(); - match decorator_name.as_str() { - _ if self - .alias_table - .service_query_decorator - .contains(&decorator_name) => - { - Ok(Mode::Query) - } - _ if self - .alias_table - .service_update_decorator - .contains(&decorator_name) => - { - Ok(Mode::Update) - } - _ => Err(vec![InvalidDecorator::from_class_prop(self).into()]), - } - }, - self.build_act_fn_params(), - self.build_return_type(), - ) - .collect_results()?; - - Ok(Method::new(name, mode, params, return_type)) - } - - fn build_act_fn_params(&self) -> Result, Vec> { - self.ts_fn_type() - .map_err(Into::>::into)? - .build_act_fn_params() - } - - fn build_return_type(&self) -> Result> { - let return_ts_type = self.return_ts_type()?; - let candid_type = self.spawn(&return_ts_type).to_candid_type()?; - Ok(candid_type) - } - - fn contains_decorator(&self, names: &Vec) -> bool { - self.decorators.iter().any(|decorator| { - if let Some(name) = decorator.expr.get_name() { - return names.contains(&name); - } - false - }) - } - - fn has_azle_decorator(&self) -> bool { - self.contains_decorator(&self.alias_table.service_query_decorator) - || self.contains_decorator(&self.alias_table.service_update_decorator) - } - - fn get_decorator_name(&self) -> Result> { - self.decorators.check_length_is_one_and_map( - |decorators| NotExactlyOneDecorator::from_decorator_list(decorators, self).into(), - |decorator| { - decorator - .expr - .get_name() - .ok_or_else(|| vec![InvalidDecorator::from_class_prop(self).into()]) - }, - ) - } - - fn name(&self) -> Result { - let name = match &self.key { - swc_ecma_ast::PropName::Ident(ident) => ident.get_name(), - swc_ecma_ast::PropName::Str(str) => str.value.to_string(), - swc_ecma_ast::PropName::Num(num) => num.value.to_string(), - swc_ecma_ast::PropName::Computed(_) => { - return Err(ComputedPropertyNotAllowed::from_class_prop(self).into()) - } - swc_ecma_ast::PropName::BigInt(big_int) => big_int.value.to_string(), - }; - - return Ok(name); - } - - fn return_ts_type(&self) -> Result { - let ts_fn_type = self.ts_fn_type()?; - match &*ts_fn_type.type_ann.type_ann { - TsType::TsTypeRef(ts_type_ref) => { - if !self - .alias_table - .call_result - .contains(&ts_type_ref.type_name.get_name()) - { - return Err(MissingCallResultAnnotation::from_class_prop(self).into()); - } - - match &ts_type_ref.type_params { - Some(ts_type_param_inst) => { - if ts_type_param_inst.params.len() != 1 { - return Err(TooManyReturnTypes::from_class_prop(self).into()); - } - - let inner_type = &*ts_type_param_inst.params[0]; - Ok(inner_type.clone()) - } - None => return Err(MissingTypeArguments::from_class_prop(self).into()), - } - } - _ => return Err(MissingCallResultAnnotation::from_class_prop(self).into()), - } - } - - fn ts_fn_type(&self) -> Result, Error> { - match &self.type_ann { - Some(type_ann) => match &*type_ann.type_ann { - TsType::TsFnOrConstructorType(fn_or_constructor_type) => { - match fn_or_constructor_type { - TsFnOrConstructorType::TsFnType(ts_fn_type) => Ok(self.spawn(ts_fn_type)), - TsFnOrConstructorType::TsConstructorType(_) => { - return Err(InvalidReturnType::from_class_prop(self).into()) - } - } - } - _ => return Err(InvalidReturnType::from_class_prop(self).into()), - }, - None => return Err(MissingTypeAnnotation::from_class_prop(self).into()), - } - } -} - -impl SourceMapped<'_, TsFnType> { - pub fn build_act_fn_params(&self) -> Result, Vec> { - self.params - .iter() - .map(|param| self.ts_fn_param_to_param(param)) - .collect_results() - } - - fn ts_fn_param_to_param(&self, param: &TsFnParam) -> Result> { - match param { - TsFnParam::Ident(identifier) => { - let name = identifier.get_name(); - let candid_type = match &identifier.type_ann { - Some(ts_type_ann) => self.spawn(&ts_type_ann.get_ts_type()).to_candid_type()?, - None => { - return Err(vec![Into::::into( - FunctionParamsMustHaveType::from_ts_fn_type(self), - )]) - } - }; - Ok(Param { name, candid_type }) - } - TsFnParam::Array(array_pat) => { - return Err(vec![Into::::into( - ArrayDestructuringInParamsNotSupported::from_ts_fn_type(self, array_pat), - )]) - } - TsFnParam::Rest(rest_pat) => { - return Err(vec![RestParametersNotSupported::from_ts_fn_type( - self, rest_pat, - ) - .into()]) - } - TsFnParam::Object(object_pat) => { - return Err(vec![ObjectDestructuringNotSupported::from_ts_fn_type( - self, object_pat, - ) - .into()]) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/mod.rs deleted file mode 100644 index a4161c33de..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/mod.rs +++ /dev/null @@ -1,42 +0,0 @@ -use cdk_framework::{act::node::candid::Service, traits::CollectIterResults}; -use swc_ecma_ast::ClassDecl; - -use crate::{ - traits::GetName, - ts_ast::{SourceMapped, TsAst}, - Error, -}; -use get_service_class_decls::GetFlattenedServiceClassDecls; -use vm_value_conversions::{from_vm_value, list_from_vm_value, list_to_vm_value, to_vm_value}; - -mod get_service_class_decls; -mod get_span; -pub mod method; -mod vm_value_conversions; - -impl TsAst { - pub fn build_services(&self) -> Result, Vec> { - let service_class_declarations = self.programs.get_service_class_declarations(); - - service_class_declarations - .iter() - .map(|service_class_decl| service_class_decl.to_service()) - .collect_results() - } -} - -impl SourceMapped<'_, ClassDecl> { - pub fn to_service(&self) -> Result> { - let methods = self.build_service_methods()?; - let name = self.ident.get_name(); - - Ok(Service { - name, - methods, - to_vm_value, - list_to_vm_value, - from_vm_value, - list_from_vm_value, - }) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/vm_value_conversions.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/vm_value_conversions.rs deleted file mode 100644 index 911f140d8e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/service/vm_value_conversions.rs +++ /dev/null @@ -1,102 +0,0 @@ -use cdk_framework::traits::ToIdent; -use proc_macro2::TokenStream; -use quote::quote; - -pub fn to_vm_value(name: String) -> TokenStream { - let service_name = name.to_ident(); - - quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for #service_name - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(context - .eval(boa_engine::Source::from_bytes(&format!( - "new {}(Principal.fromText(\"{}\"))", - stringify!(#service_name), - self.0.principal.to_string() - )))?) - } - } - } -} - -pub fn list_to_vm_value(name: String) -> TokenStream { - let service_name = name.to_ident(); - - quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for Vec<#service_name> - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - try_into_vm_value_generic_array(self, context) - } - } - - } -} - -pub fn from_vm_value(name: String) -> TokenStream { - let service_name = name.to_ident(); - let service_name_string = service_name.to_string(); - - let value_is_not_of_service_type_error_message = - format!("TypeError: Value is not of type '{}'", &service_name_string); - - quote! { - impl CdkActTryFromVmValue<#service_name, boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result<#service_name, boa_engine::JsError> { - let js_object = self.as_object().ok_or_else(|| { - let cause = "TypeError: Value is not an object".to_js_error(None); - #value_is_not_of_service_type_error_message.to_js_error(Some(cause)) - })?; - - let canister_id_js_value = js_object.get("canisterId", context)?; - - let principal = - canister_id_js_value - .try_from_vm_value(context) - .map_err(|principal_err| { - let cause = - "TypeError: Property 'canisterId' is not of type 'Principal'" - .to_js_error(Some(principal_err)); - #value_is_not_of_service_type_error_message.to_js_error(Some(cause)) - })?; - - Ok(#service_name::new(principal)) - } - } - } -} - -pub fn list_from_vm_value(name: String) -> TokenStream { - let service_name = name.to_ident(); - - quote! { - impl - CdkActTryFromVmValue< - Vec<#service_name>, - boa_engine::JsError, - &mut boa_engine::Context<'_>, - > for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> { - try_from_vm_value_generic_array(self, context) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/tuple/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/tuple/mod.rs deleted file mode 100644 index b8b210cbeb..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/tuple/mod.rs +++ /dev/null @@ -1,78 +0,0 @@ -use cdk_framework::{ - act::node::candid::{tuple::Elem, Tuple}, - traits::{CollectIterResults, CollectResults}, -}; -use swc_common::Span; -use swc_ecma_ast::{TsTupleElement, TsTupleType, TsTypeAliasDecl, TsTypeRef}; - -use crate::{ - traits::{GetName, GetSpan}, - ts_ast::SourceMapped, - Error, -}; - -use super::errors::WrongEnclosedType; - -impl SourceMapped<'_, TsTypeAliasDecl> { - pub fn to_tuple(&self) -> Result, Vec> { - self.process_ts_type_ref(&self.alias_table.tuple, |type_ref| { - if self.is_something_that_could_be_in_the_alias_table() { - return Ok(None); - } - let (type_params, tuple_type_ref) = - (self.get_type_params(), type_ref.to_tuple()).collect_results()?; - match tuple_type_ref { - Some(members) => Ok(Some(Tuple { - name: Some(self.id.get_name()), - type_params: type_params.into(), - ..members - })), - None => Ok(None), - } - }) - .map(|result| result.flatten()) - } -} - -impl SourceMapped<'_, TsTypeRef> { - pub fn is_tuple(&self) -> bool { - self.alias_table.tuple.contains(&self.get_name()) - } - - pub fn to_tuple(&self) -> Result, Vec> { - if !self.is_tuple() { - return Ok(None); - } - match self.get_ts_type()?.as_ts_tuple_type() { - Some(ts_tuple_type) => Ok(Some(ts_tuple_type.to_tuple()?)), - None => return Err(vec![WrongEnclosedType::error_from_ts_type_ref(self).into()]), - } - } -} - -impl SourceMapped<'_, TsTupleType> { - pub fn to_tuple(&self) -> Result> { - Ok(Tuple { - name: None, - elems: self.get_elem_types()?, - type_params: vec![].into(), - }) - } - - fn get_elem_types(&self) -> Result, Vec> { - let ts_tuple_element_to_elem = |elem: &TsTupleElement| { - let candid_type = self.spawn(&elem.ty).to_candid_type()?; - Ok(Elem { candid_type }) - }; - self.elem_types - .iter() - .map(ts_tuple_element_to_elem) - .collect_results() - } -} - -impl GetSpan for TsTupleType { - fn get_span(&self) -> Span { - self.span - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_alias/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_alias/mod.rs deleted file mode 100644 index d7cf037aa2..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_alias/mod.rs +++ /dev/null @@ -1,125 +0,0 @@ -use cdk_framework::act::node::candid::TypeAlias; -use swc_ecma_ast::{TsEntityName, TsType, TsTypeAliasDecl, TsTypeRef}; - -use crate::{traits::GetName, ts_ast::SourceMapped, Error}; - -impl SourceMapped<'_, TsTypeAliasDecl> { - pub fn to_type_alias(&self) -> Result, Vec> { - let type_alias_name = self.id.get_name(); - // If the thing on the right hand side is not a type ref then we don't - // need to consider it. The type aliases that we are going to be passing - // to rust are going to be aliases to developer defined types. Like - // custom Records and Variants. All of those will be TsTypeRefs. Any - // type_aliases to ts primitives should be taken care of in the alias - // table. - let type_ref = match &*self.type_ann { - TsType::TsTypeRef(ts_type_ref) => self.spawn(ts_type_ref), - _ => return Ok(None), - }; - // We do want to allow things like - // export type MyBoolVec = azle.Vec - // So we want to allow type refs like azle.Vec but not anything like - // azle.Manual. That wouldn't make any sense for a type alias. So we - // filter all of those out - if !self.alias_table.is_aliasable(&type_ref.get_name()) { - return Ok(None); - } - // We also want to make sure that the type_alias name (the left hand - // side of the type alias decl) is not in the alias table. If it is in - // the alias table then the right hand side doesn't really matter - // because it means that the right hand side mapped to an azle type. - // This comes into play if the right hand side is something like a - // qualified name. In this case the right hand side itself might not - // have made it into table because it was only ever an intermediate step - // on the path to determining if the type_alias_name should have been in - // the alias table - if self.alias_table.search(&type_alias_name) { - return Ok(None); - } - - // Try and convert the right hand side to a candid type. If you can - // great it might be something we need to make an alias for. If not then - // lets not bother with it. - let aliased_type = match type_ref.to_candid_type() { - Ok(candid_type) => Box::from(candid_type), - Err(_) => return Ok(None), - }; - - // Finally make sure that the type_alias_name is in the list of possible - // Type aliases - if !self.alias_list.contains(&type_alias_name) { - return Ok(None); - } - - // After all checks are complete, create and return the type alias - return Ok(Some(TypeAlias { - name: type_alias_name, - aliased_type, - type_params: self.get_type_params()?.into(), - })); - } - - /** - * The point of this function is to help filter out things that look like - * they might be records, variant, tuples, or funcs but are actually members - * of the alias table. - * For example: - * export type MyRecordDecorator = azle.Record; - * is not a record and should not be put into the CandidTypes.records list. - * For right now lets only use it as such. - * - * So the only thing this should be doing is checking to see that all of the - * type args are generics and all of them are defined in the - */ - pub fn is_something_that_could_be_in_the_alias_table(&self) -> bool { - let type_params: Vec<_> = self - .type_params - .iter() - .flat_map(|ts_type_param_decl| ts_type_param_decl.params.clone()) - .map(|ts_type_param| ts_type_param.name.get_name()) - .collect(); - let type_args: Vec<_> = match &*self.type_ann { - TsType::TsTypeRef(ts_type_ref) => ts_type_ref - .type_params - .iter() - .flat_map(|thing| thing.params.clone()) - .map(|boxed_type| *boxed_type) - .collect(), - _ => vec![], - }; - if type_params.len() != type_args.len() { - return false; - } - let type_args_are_generics = type_args.iter().all(|ts_type| { - if let TsType::TsTypeRef(type_ref) = ts_type { - if let TsEntityName::Ident(name) = &type_ref.type_name { - return type_params.contains(&name.get_name()); - } - } - false - }); - type_args_are_generics - } - - pub fn process_ts_type_ref( - &self, - type_names: &Vec, - handler: F, - ) -> Result, Vec> - where - F: Fn(SourceMapped) -> Result>, - { - match &*self.type_ann { - TsType::TsTypeRef(ts_type_ref) => { - let name = ts_type_ref.type_name.get_name(); - if type_names.contains(&name) { - let type_ref = self.spawn(ts_type_ref); - handler(type_ref).map(Some) - } else { - Ok(None) - } - } - _ => Ok(None), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_param/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_param/mod.rs deleted file mode 100644 index 05ab15cc96..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_param/mod.rs +++ /dev/null @@ -1,45 +0,0 @@ -use cdk_framework::{ - act::node::candid::TypeParam, - traits::{CollectIterResults, ToIdent}, -}; -use swc_ecma_ast::TsTypeAliasDecl; - -use crate::{traits::GetName, ts_ast::SourceMapped, Error}; -use quote::quote; - -impl SourceMapped<'_, TsTypeAliasDecl> { - pub fn get_type_params(&self) -> Result, Vec> { - self.type_params - .iter() - .map(|type_params| { - type_params.params.iter().map(|type_param| { - Ok(TypeParam { - name: type_param.name.get_name(), - try_into_vm_value_trait_bound: quote!( - for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - > - ), - try_from_vm_value_trait_bound: |name_string| { - let name = name_string.to_ident(); - - quote!( - boa_engine::JsValue: for<'a, 'b> CdkActTryFromVmValue< - #name, - boa_engine::JsError, - &'a mut boa_engine::Context<'b> - > + for<'a, 'b> CdkActTryFromVmValue< - Box<#name>, - boa_engine::JsError, - &'a mut boa_engine::Context<'b> - > - ) - }, - }) - }) - }) - .flatten() - .collect_results() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/errors/mod.rs deleted file mode 100644 index 6675d22393..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/errors/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod wrong_number_of_params; - -pub use wrong_number_of_params::WrongNumberOfParams; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/errors/wrong_number_of_params.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/errors/wrong_number_of_params.rs deleted file mode 100644 index d2c1279499..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/errors/wrong_number_of_params.rs +++ /dev/null @@ -1,215 +0,0 @@ -use std::fmt::Display; - -use swc_ecma_ast::TsTypeRef; - -use crate::{ - errors::{CompilerOutput, InternalError, Location, Suggestion, SuggestionModifications}, - internal_error, - traits::{GetName, GetSourceFileInfo, GetSourceInfo}, - ts_ast::SourceMapped, - Error, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct WrongNumberOfParams { - name: TypeRefCandidTypes, - param_count: usize, - location: Location, - modified_source: String, - modified_range: (usize, usize), -} - -#[derive(Debug, Clone, PartialEq)] -enum TypeRefCandidTypes { - Record, - Variant, - Tuple, - Vec, - Opt, - Func, -} - -impl WrongNumberOfParams { - pub fn error_from_ts_type_ref(sm_ts_type_ref: &SourceMapped) -> Error { - let name = match sm_ts_type_ref.get_candid_type() { - Ok(name) => name, - Err(err) => return err, - }; - let param_count = sm_ts_type_ref.get_param_count(); - let (modified_source, modified_range) = - match sm_ts_type_ref.get_suggestion_modifications(&name) { - Ok(ok) => ok, - Err(err) => return err, - }; - Self { - location: sm_ts_type_ref.get_location(), - param_count, - modified_source, - modified_range, - name, - } - .into() - } - - fn create_compiler_output(&self) -> Result { - Ok(CompilerOutput { - title: self.create_title(), - location: self.location.clone(), - annotation: self.create_annotation()?, - suggestion: Some(self.create_suggestion()?), - }) - } - - fn create_title(&self) -> String { - match self.name { - TypeRefCandidTypes::Record => "Invalid Record", - TypeRefCandidTypes::Variant => "Invalid Variant", - TypeRefCandidTypes::Tuple => "Invalid Tuple", - TypeRefCandidTypes::Vec => "Invalid Vec", - TypeRefCandidTypes::Opt => "Invalid Opt", - TypeRefCandidTypes::Func => "Invalid Func", - } - .to_string() - } - - fn create_annotation(&self) -> Result { - if self.param_count == 1 { - return Err(InternalError::new().into()); - } - Ok(if self.param_count == 0 { - "Needs to have an enclosed type here." - } else { - "Only one enclosed type allowed here." - } - .to_string()) - } - - fn create_suggestion(&self) -> Result { - Ok(Suggestion { - title: self.create_suggestion_title(), - range: self.modified_range, - source: self.modified_source.clone(), - annotation: Some(self.create_suggestion_annotation()?), - import_suggestion: None, - }) - } - fn create_suggestion_title(&self) -> String { - match self.name { - TypeRefCandidTypes::Record => "Record must have example one enclose type.", - TypeRefCandidTypes::Variant => "Variant must have exactly one enclosed type. If you need multiple variants, put them all in a type literal.", - TypeRefCandidTypes::Tuple => "Tuples must have exactly one enclosed type.", - TypeRefCandidTypes::Vec => "Vecs must have example one enclosed type.", - TypeRefCandidTypes::Opt => "Opts must have exactly one enclosed type.", - TypeRefCandidTypes::Func => "Funcs must have exactly one enclosed type.", - } - .to_string() - } - - fn create_suggestion_annotation(&self) -> Result { - if self.param_count == 1 { - return Err(InternalError::new().into()); - } - Ok(match self.name { - TypeRefCandidTypes::Record => { - if self.param_count == 0 { - "The simplest Record is an empty type literal" - } else { - "Try wrapping everything in a type literal" - } - } - TypeRefCandidTypes::Variant => { - if self.param_count == 0 { - "The simplest Variant is a type literal with a single member with type null" - } else { - "Try wrapping everything in a type literal" - } - } - TypeRefCandidTypes::Tuple => { - if self.param_count == 0 { - "Add types to the tuple here" - } else { - "Try wrapping everything in square braces" - } - } - TypeRefCandidTypes::Vec => { - if self.param_count == 0 { - "For example if you want a vec of boolean value, enclose boolean with Vec" - } else { - "" - } - } - TypeRefCandidTypes::Opt => { - if self.param_count == 0 { - "For example if you want an optional boolean value, enclose boolean with Opt" - } else { - "" - } - } - TypeRefCandidTypes::Func => { - if self.param_count == 0 { - "If the func has no parameters or return type then you could do this." - } else { - "Did you mean to have multiple parameters?" - } - } - } - .to_string()) - } -} - -impl std::error::Error for WrongNumberOfParams {} - -impl From for crate::Error { - fn from(error: WrongNumberOfParams) -> Self { - Self::WrongNumberOfParams(error) - } -} - -impl Display for WrongNumberOfParams { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.create_compiler_output() { - Ok(compiler_output) => write!(f, "{}", compiler_output), - Err(err) => write!(f, "{}", err), - } - } -} - -impl SourceMapped<'_, TsTypeRef> { - fn get_candid_type(&self) -> Result { - let name = self.get_name(); - Ok(match name.as_str() { - _ if self.alias_table.variant.contains(&name) => TypeRefCandidTypes::Variant, - _ if self.alias_table.func.contains(&name) => TypeRefCandidTypes::Func, - _ if self.alias_table.opt.contains(&name) => TypeRefCandidTypes::Opt, - _ if self.alias_table.record.contains(&name) => TypeRefCandidTypes::Record, - _ if self.alias_table.tuple.contains(&name) => TypeRefCandidTypes::Tuple, - _ if self.alias_table.vec.contains(&name) => TypeRefCandidTypes::Vec, - _ => internal_error!(), - }) - } - - fn get_suggestion_modifications( - &self, - candid_type: &TypeRefCandidTypes, - ) -> Result { - let example = match candid_type { - TypeRefCandidTypes::Variant => self.generate_example_variant()?, - TypeRefCandidTypes::Func => self.generate_example_func(), - TypeRefCandidTypes::Opt => self.generate_example_option()?, - TypeRefCandidTypes::Record => self.generate_example_record(), - TypeRefCandidTypes::Tuple => self.generate_example_tuple(), - TypeRefCandidTypes::Vec => self.generate_example_vec(), - }; - Ok(self.get_suggestion_modifications_from_example(example.as_str())) - } - - fn get_suggestion_modifications_from_example(&self, example: &str) -> SuggestionModifications { - let modified_source = self - .source_map - .generate_modified_source(self.get_enclosed_span(), example); - let modified_range = self - .source_map - .generate_modified_range(self.get_enclosed_span(), example); - (modified_source, modified_range) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/mod.rs deleted file mode 100644 index a37662f7c9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/type_ref/mod.rs +++ /dev/null @@ -1,103 +0,0 @@ -use cdk_framework::{ - act::node::{ - candid::{TypeArg, TypeRef}, - CandidType, - }, - traits::CollectIterResults, -}; -use std::ops::Deref; -use swc_common::Span; -use swc_ecma_ast::{TsType, TsTypeRef}; - -use crate::{ - traits::{GetName, GetSpan}, - ts_ast::SourceMapped, - Error, -}; - -use self::errors::WrongNumberOfParams; - -pub mod errors; - -impl SourceMapped<'_, TsTypeRef> { - pub fn get_ts_type(&self) -> Result, Error> { - match &self.type_params { - Some(params) => { - if params.params.len() != 1 { - return Err(WrongNumberOfParams::error_from_ts_type_ref(self).into()); - } - let inner_type = params.params[0].deref(); - Ok(self.spawn(inner_type)) - } - None => return Err(WrongNumberOfParams::error_from_ts_type_ref(self).into()), - } - } - - pub fn to_type_ref(&self) -> Result> { - let type_arguments = self - .type_params - .iter() - .map(|type_params| { - type_params - .params - .iter() - .map(|param| self.spawn(param.deref()).to_candid_type()) - }) - .flatten() - .collect_results() - .map(|param| { - param - .into_iter() - .map(|param| TypeArg(param)) - .collect::>() - })?; - - let name_string = self.get_name(); - - Ok(TypeRef { - name: if name_string == "Result" { - "_AzleResult".to_string() - } else { - name_string.to_string() - }, - type_arguments, - }) - } - - pub fn to_candid_type(&self) -> Result> { - if let Some(primitive) = self.to_primitive()? { - return Ok(CandidType::Primitive(primitive)); - } - if let Some(opt) = self.to_option()? { - return Ok(CandidType::Opt(opt)); - } - if let Some(func) = self.to_func(None)? { - return Ok(CandidType::Func(func)); - } - if let Some(record) = self.to_record()? { - return Ok(CandidType::Record(record)); - } - if let Some(tuple) = self.to_tuple()? { - return Ok(CandidType::Tuple(tuple)); - } - if let Some(variant) = self.to_variant()? { - return Ok(CandidType::Variant(variant)); - } - if let Some(vec) = self.to_vec()? { - return Ok(CandidType::Array(vec)); - } - Ok(CandidType::TypeRef(self.to_type_ref()?)) - } -} - -impl GetName for SourceMapped<'_, TsTypeRef> { - fn get_name(&self) -> String { - return self.type_name.get_name(); - } -} - -impl GetSpan for TsTypeRef { - fn get_span(&self) -> Span { - self.span - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/errors/mod.rs deleted file mode 100644 index 8273ed9ca7..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/errors/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod variant_property_signature; - -pub use variant_property_signature::VariantPropertySignature; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/errors/variant_property_signature.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/errors/variant_property_signature.rs deleted file mode 100644 index 1f8de51ce7..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/errors/variant_property_signature.rs +++ /dev/null @@ -1,65 +0,0 @@ -use swc_ecma_ast::TsTypeElement; - -use crate::{ - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::{GetSourceFileInfo, GetSourceInfo, GetSpan, TypeToString}, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct VariantPropertySignature { - location: Location, - type_name: String, - suggestion_modifications: SuggestionModifications, -} - -impl VariantPropertySignature { - pub fn from_ts_type_element(sm_ts_type_elements: &SourceMapped) -> Self { - let replacement = "property_name: null".to_string(); - let suggestion_modifications = ( - sm_ts_type_elements - .source_map - .generate_modified_source(sm_ts_type_elements.get_span(), &replacement), - sm_ts_type_elements - .source_map - .generate_modified_range(sm_ts_type_elements.get_span(), &replacement), - ); - - Self { - location: sm_ts_type_elements.get_location(), - suggestion_modifications, - type_name: sm_ts_type_elements.type_to_string(), - } - } - - fn variant_property_signature_error(&self) -> CompilerOutput { - CompilerOutput { - title: "Invalid Variant".to_string(), - location: self.location.clone(), - annotation: format!("{} is not allowed here.", self.type_name), - suggestion: Some(Suggestion { - title: "Variant members must be properties".to_string(), - annotation: Some("For example".to_string()), - import_suggestion: None, - source: self.suggestion_modifications.0.clone(), - range: self.suggestion_modifications.1, - }), - } - } -} - -impl std::error::Error for VariantPropertySignature {} - -impl From for crate::Error { - fn from(error: VariantPropertySignature) -> Self { - Self::VariantPropertySignature(error) - } -} - -impl std::fmt::Display for VariantPropertySignature { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.variant_property_signature_error()) - } -} - -impl SourceMapped<'_, TsTypeElement> {} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/mod.rs deleted file mode 100644 index 51231877dc..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/variant/mod.rs +++ /dev/null @@ -1,105 +0,0 @@ -pub mod errors; - -use cdk_framework::{ - act::node::candid::{variant::Member, Variant}, - traits::{CollectIterResults, CollectResults}, -}; -use swc_ecma_ast::{TsPropertySignature, TsTypeAliasDecl, TsTypeElement, TsTypeLit, TsTypeRef}; - -use crate::{traits::GetName, ts_ast::SourceMapped, Error}; - -use self::errors::VariantPropertySignature; - -use super::errors::WrongEnclosedType; - -impl SourceMapped<'_, TsTypeAliasDecl> { - pub fn to_variant(&self) -> Result, Vec> { - self.process_ts_type_ref(&self.alias_table.variant, |type_ref| { - if self.is_something_that_could_be_in_the_alias_table() { - return Ok(None); - } - // TODO this should be undone once we put all user-defined types in their own module - let name_string = self.id.get_name(); - let name = Some(if name_string == "Result" { - "_AzleResult".to_string() - } else { - name_string - }); - - let (type_params, variant_type_ref) = - (self.get_type_params(), type_ref.to_variant()).collect_results()?; - - match variant_type_ref { - Some(members) => Ok(Some(Variant { - name, - type_params: type_params.into(), - ..members - })), - None => Ok(None), - } - }) - .map(|result| result.flatten()) - } -} - -impl SourceMapped<'_, TsTypeRef> { - pub fn is_variant(&self) -> bool { - self.alias_table.variant.contains(&self.get_name()) - } - - pub fn to_variant(&self) -> Result, Vec> { - if !self.is_variant() { - return Ok(None); - } - Ok(Some( - match self.get_ts_type()?.as_ts_type_lit() { - Some(ts_type_lit) => ts_type_lit, - None => return Err(vec![WrongEnclosedType::error_from_ts_type_ref(self).into()]), - } - .to_variant()?, - )) - } -} - -impl SourceMapped<'_, TsTypeLit> { - pub fn to_variant(&self) -> Result> { - let ts_type_element_to_variant_member = - |member: &TsTypeElement| self.spawn(member).to_variant_member(); - let members: Vec = self - .members - .iter() - .map(ts_type_element_to_variant_member) - .collect_results()?; - - Ok(Variant { - name: None, - members, - type_params: vec![].into(), - }) - } -} - -impl SourceMapped<'_, TsTypeElement> { - pub fn to_variant_member(&self) -> Result> { - let ts_property_signature = match self.as_property_signature() { - Some(ts_property_signature) => ts_property_signature, - None => { - return Err(vec![ - VariantPropertySignature::from_ts_type_element(self).into() - ]) - } - }; - ts_property_signature.to_variant_member() - } -} - -impl SourceMapped<'_, TsPropertySignature> { - pub(super) fn to_variant_member(&self) -> Result> { - let (name, candid_type) = ( - self.get_member_name().map_err(Error::into), - self.get_act_data_type(), - ) - .collect_results()?; - Ok(Member { name, candid_type }) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/vec/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/candid_type/vec/mod.rs deleted file mode 100644 index 28a27c897d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/candid_type/vec/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -use cdk_framework::act::node::candid::Array; -use swc_ecma_ast::TsTypeRef; - -use crate::{traits::GetName, ts_ast::SourceMapped, Error}; - -impl SourceMapped<'_, TsTypeRef> { - pub fn to_vec(&self) -> Result, Vec> { - if self.alias_table.vec.contains(&self.get_name()) { - let enclosed_act_data_type = self.get_ts_type()?.to_candid_type()?; - Ok(Some(Array { - enclosed_type: Box::from(enclosed_act_data_type), - })) - } else { - Ok(None) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/invalid_params.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/invalid_params.rs deleted file mode 100644 index 60fd20fd65..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/invalid_params.rs +++ /dev/null @@ -1,41 +0,0 @@ -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct InvalidParams { - location: Location, -} - -impl InvalidParams { - pub fn from_annotated_fn_decl(annotated_fn_decl: &SourceMapped) -> Self { - Self { - location: annotated_fn_decl - .source_map - .get_location(annotated_fn_decl.fn_decl.function.span), - } - } -} - -impl std::error::Error for InvalidParams {} - -impl From for crate::Error { - fn from(error: InvalidParams) -> Self { - Self::InvalidParams(error) - } -} - -impl std::fmt::Display for InvalidParams { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let compiler_output = CompilerOutput { - title: "Something is impossibly wrong with your parameters. Please open an issue showing your canister methods and this error.".to_string(), - annotation: "".to_string(), - suggestion: None, - location: self.location.clone(), - }; - write!(f, "{}", compiler_output) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/missing_return_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/missing_return_type.rs deleted file mode 100644 index 5480f6316a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/missing_return_type.rs +++ /dev/null @@ -1,77 +0,0 @@ -use swc_ecma_ast::TsTypeRef; - -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct MissingReturnType { - location: Location, - sug_mod: SuggestionModifications, - canister_method_type: String, -} - -impl MissingReturnType { - pub fn from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - ts_type_ref: &TsTypeRef, - canister_method_type: &str, - ) -> Self { - let example_type_param = "".to_string(); - let example_return_type = format!("{}{}", canister_method_type, example_type_param); - - let span = ts_type_ref.span; - let range = annotated_fn_decl.source_map.get_range(span); - let location = Location { - origin: annotated_fn_decl.source_map.get_origin(span), - line_number: annotated_fn_decl.source_map.get_line_number(span), - source: format!("{} ", annotated_fn_decl.source_map.get_source(span)), - range: (range.1, range.1 + 1), - }; - Self { - location, - sug_mod: ( - annotated_fn_decl - .source_map - .generate_modified_source(span, &example_return_type), - (range.1, range.1 + example_type_param.len()), - ), - canister_method_type: canister_method_type.to_string(), - } - } - - fn build_missing_return_type_error_msg(&self) -> CompilerOutput { - CompilerOutput { - title: "Missing return type".to_string(), - location: self.location.clone(), - annotation: "Expected return type here".to_string(), - suggestion: Some(Suggestion { - title: format!( - "Specify a return type as a type argument to `{}`. E.g.:", - self.canister_method_type - ), - annotation: None, - import_suggestion: None, - source: self.sug_mod.0.clone(), - range: self.sug_mod.1, - }), - } - } -} - -impl std::error::Error for MissingReturnType {} - -impl From for crate::Error { - fn from(error: MissingReturnType) -> Self { - Self::MissingReturnType(error) - } -} - -impl std::fmt::Display for MissingReturnType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_missing_return_type_error_msg()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/mod.rs deleted file mode 100644 index 78c7f5d66d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -mod invalid_params; -mod missing_return_type; -mod param_default_value; -mod untyped_param; - -pub use invalid_params::InvalidParams; -pub use missing_return_type::MissingReturnType; -pub use param_default_value::ParamDefaultValue; -pub use untyped_param::UntypedParam; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/param_default_value.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/param_default_value.rs deleted file mode 100644 index 9e99c07e4b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/param_default_value.rs +++ /dev/null @@ -1,91 +0,0 @@ -use swc_ecma_ast::AssignPat; - -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location, Suggestion}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct ParamDefaultValue { - compiler_output: CompilerOutput, -} - -impl ParamDefaultValue { - pub fn from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - assign_pat: &AssignPat, - ) -> Self { - Self { - compiler_output: annotated_fn_decl.build_param_default_value_error_msg(assign_pat), - } - } -} - -impl std::error::Error for ParamDefaultValue {} - -impl From for crate::Error { - fn from(error: ParamDefaultValue) -> Self { - Self::ParamDefaultValue(error) - } -} - -impl std::fmt::Display for ParamDefaultValue { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.compiler_output) - } -} - -impl SourceMapped<'_, AnnotatedFnDecl> { - fn build_param_default_value_error_msg(&self, assign_pat: &AssignPat) -> CompilerOutput { - let title = "Setting default values for parameters is unsupported at this time".to_string(); - let origin = self.source_map.get_origin(assign_pat.span); - let line_number = self.source_map.get_line_number(assign_pat.span); - let source = self.source_map.get_source(assign_pat.span); - let range = self.source_map.get_range(assign_pat.span); - let equals_index_option = source.find('='); - - match equals_index_option { - Some(equals_index) => { - let equals_sign_and_right_hand_range = (equals_index, range.1); - - let corrected_source: String = source - .chars() - .take(equals_index) - .chain(source.chars().skip(range.1)) - .collect(); - - CompilerOutput { - title, - location: Location { - origin, - line_number, - source, - range: equals_sign_and_right_hand_range, - }, - annotation: "Attempted to set a default value here".to_string(), - suggestion: Some(Suggestion { - title: "Remove the default value or set it inside the function body" - .to_string(), - source: corrected_source, - range: (range.0, equals_index), - annotation: None, - import_suggestion: None, - }), - } - } - None => CompilerOutput { - title, - location: Location { - origin, - line_number, - source: source.clone(), - range: (range.0, source.len()), - }, - annotation: "Attempted to assign a default value to this parameter".to_string(), - suggestion: None, - }, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/untyped_param.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/untyped_param.rs deleted file mode 100644 index 40dc07b28e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/errors/untyped_param.rs +++ /dev/null @@ -1,82 +0,0 @@ -use swc_ecma_ast::BindingIdent; - -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct UntypedParam { - location: Location, - suggestion_modifications: SuggestionModifications, -} - -impl UntypedParam { - pub fn from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - binding_ident: &BindingIdent, - ) -> Self { - let range = annotated_fn_decl.source_map.get_range(binding_ident.span); - let raw_source = annotated_fn_decl.source_map.get_source(binding_ident.span); - let source = if raw_source.len() <= range.1 + 1 { - format!("{} ", raw_source) - } else { - raw_source - }; - let example_type_ann = ": ParamType".to_string(); // TODO: Come up with a better name from the source - let corrected_source = annotated_fn_decl - .source_map - .generate_source_with_range_replaced( - binding_ident.span, - (range.1, range.1), - &example_type_ann, - ); - let suggestion_modifications = ( - corrected_source, - (range.1, range.1 + example_type_ann.len()), - ); - - Self { - location: Location { - origin: annotated_fn_decl.source_map.get_origin(binding_ident.span), - line_number: annotated_fn_decl - .source_map - .get_line_number(binding_ident.span), - source, - range: (range.1, range.1 + 1), - }, - suggestion_modifications, - } - } - - fn build_untyped_param_error_msg(&self) -> CompilerOutput { - CompilerOutput { - title: "Untyped parameter".to_string(), - location: self.location.clone(), - annotation: "Expected type annotation here".to_string(), - suggestion: Some(Suggestion { - title: "Specify a type for the parameter".to_string(), - source: self.suggestion_modifications.0.clone(), - range: self.suggestion_modifications.1, - annotation: None, - import_suggestion: None, - }), - } - } -} - -impl std::error::Error for UntypedParam {} - -impl From for crate::Error { - fn from(error: UntypedParam) -> Self { - Self::UntypedParam(error) - } -} - -impl std::fmt::Display for UntypedParam { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_untyped_param_error_msg()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/get_annotated_fn_decls.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/get_annotated_fn_decls.rs deleted file mode 100644 index 65a6557182..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/get_annotated_fn_decls.rs +++ /dev/null @@ -1,33 +0,0 @@ -use std::ops::Deref; - -use crate::{ - canister_method::{module::ModuleHelperMethods, AnnotatedFnDecl}, - ts_ast::Program, - ts_ast::SourceMapped, - Error, -}; - -pub trait GetAnnotatedFnDecls { - fn get_annotated_fn_decls(&self) -> (Vec>, Vec); -} - -impl GetAnnotatedFnDecls for Vec { - fn get_annotated_fn_decls(&self) -> (Vec>, Vec) { - self.iter().fold((vec![], vec![]), |acc, program| { - let (fn_decls, errors) = program.get_annotated_fn_decls(); - - (vec![acc.0, fn_decls].concat(), vec![acc.1, errors].concat()) - }) - } -} - -impl Program { - fn get_annotated_fn_decls(&self) -> (Vec>, Vec) { - match self.deref() { - swc_ecma_ast::Program::Module(module) => { - module.get_annotated_fn_decls(&self.source_map, &self.alias_table, &self.alias_list) - } - swc_ecma_ast::Program::Script(_) => (vec![], vec![]), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/mod.rs deleted file mode 100644 index 2ce0d4de50..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotated_fn_decl/mod.rs +++ /dev/null @@ -1,187 +0,0 @@ -use cdk_framework::{act::node::canister_method::CanisterMethodType, traits::CollectIterResults}; -use proc_macro2::Ident; -use quote::format_ident; -use swc_ecma_ast::{BindingIdent, FnDecl, Pat, TsType}; - -use crate::{ - canister_method::Annotation, - errors::errors::{ - ArrayDestructuringInParamsNotSupported, ObjectDestructuringNotSupported, - RestParametersNotSupported, - }, - internal_error, - traits::GetName, - ts_ast::SourceMapped, - Error, -}; - -pub use get_annotated_fn_decls::GetAnnotatedFnDecls; - -use self::errors::{InvalidParams, MissingReturnType, ParamDefaultValue, UntypedParam}; - -use super::errors::MissingReturnTypeAnnotation; - -mod get_annotated_fn_decls; - -pub mod errors; - -#[derive(Clone)] -pub struct AnnotatedFnDecl { - pub annotation: Annotation, - pub fn_decl: FnDecl, -} - -impl SourceMapped<'_, AnnotatedFnDecl> { - pub fn get_return_ts_type(&self) -> Result<&TsType, Error> { - match &self.fn_decl.function.return_type { - Some(ts_type_ann) => { - let return_type = &*ts_type_ann.type_ann; - - let promise_return_type = if self.is_promise() { - let type_ref = match return_type.as_ts_type_ref() { - Some(type_ref) => type_ref, - None => internal_error!(), // Since it is a promise we know it's a type_ref - }; - match &type_ref.type_params { - Some(type_param_instantiation) => &*type_param_instantiation.params[0], - None => { - return Err(MissingReturnType::from_annotated_fn_decl( - self, type_ref, "Promise", - ) - .into()) - } - } - } else { - return_type - }; - - let manual_return_type = if self.is_manual() { - let inner_type_ref = match promise_return_type.as_ts_type_ref() { - Some(inner_type_ref) => inner_type_ref, - None => internal_error!(), // Since it is manual we know it's a type_ref - }; - match &inner_type_ref.type_params { - Some(type_param_instantiation) => &type_param_instantiation.params[0], - None => { - return Err(MissingReturnType::from_annotated_fn_decl( - self, - inner_type_ref, - "Manual", - ) - .into()) - } - } - } else { - promise_return_type - }; - Ok(manual_return_type) - } - None => return Err(MissingReturnTypeAnnotation::from_annotated_fn_decl(self).into()), - } - } - - pub fn get_function_name(&self) -> String { - self.fn_decl.ident.get_name() - } - - pub fn get_param_name_idents(&self) -> Result, Vec> { - let param_idents = self.get_param_binding_idents()?; - - Ok(param_idents - .iter() - .map(|ident| format_ident!("{}", ident.get_name())) - .collect()) - } - - pub fn get_param_binding_idents(&self) -> Result, Vec> { - self.fn_decl - .function - .params - .iter() - .map(|param| match ¶m.pat { - Pat::Ident(ident) => Ok(ident), - Pat::Array(array_pat) => Err(vec![Into::::into( - ArrayDestructuringInParamsNotSupported::from_annotated_fn_decl(self, array_pat), - )]), - Pat::Rest(rest_pat) => { - Err(vec![RestParametersNotSupported::from_annotated_fn_decl( - self, rest_pat, - ) - .into()]) - } - Pat::Object(object_pat) => Err(vec![ - ObjectDestructuringNotSupported::from_annotated_fn_decl(self, object_pat) - .into(), - ]), - Pat::Assign(assign_pat) => Err(vec![ParamDefaultValue::from_annotated_fn_decl( - self, assign_pat, - ) - .into()]), - Pat::Invalid(_) => Err(vec![InvalidParams::from_annotated_fn_decl(self).into()]), - Pat::Expr(_) => Err(vec![InvalidParams::from_annotated_fn_decl(self).into()]), - }) - .collect_results() - } - - pub fn get_param_ts_types(&self) -> Result, Vec> { - let param_idents = self.get_param_binding_idents()?; - - param_idents - .iter() - .map(|ident| match &ident.type_ann { - Some(ts_type_ann) => Ok(ts_type_ann.type_ann.as_ref()), - None => { - return Err(vec![ - UntypedParam::from_annotated_fn_decl(self, *ident).into() - ]) - } - }) - .collect_results() - } - - /// Returns whether the fn_decl is of the provided type. - /// - /// **Note:** This method shouldn't panic even if it is missing a return - /// type because it is called to filter all fn_decls, including those that - /// aren't canister methods. - pub fn is_canister_method_type(&self, canister_method_type: CanisterMethodType) -> bool { - self.annotation.method_type == canister_method_type - } - - pub fn is_manual(&self) -> bool { - let return_type = self - .fn_decl - .function - .return_type - .as_ref() - .and_then(|ts_type_ann| match self.is_promise() { - true => ts_type_ann - .type_ann - .as_ts_type_ref() - .and_then(|ts_type_ref| ts_type_ref.type_params.clone()) - .and_then(|type_param_instantiation| { - Some(*type_param_instantiation.params[0].clone()) - }), - false => Some(*ts_type_ann.type_ann.clone()), - }); - - match return_type { - Some(TsType::TsTypeRef(ts_type_ref)) => self - .alias_table - .manual - .contains(&self.spawn(&ts_type_ref).get_name()), - - _ => false, - } - } - - pub fn is_promise(&self) -> bool { - match &self.fn_decl.function.return_type { - Some(ts_type_ann) => match &*ts_type_ann.type_ann { - TsType::TsTypeRef(ts_type_ref) => ts_type_ref.type_name.get_name() == "Promise", - _ => false, - }, - None => false, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotation.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotation.rs deleted file mode 100644 index 7358950f23..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/annotation.rs +++ /dev/null @@ -1,252 +0,0 @@ -use cdk_framework::act::node::canister_method::CanisterMethodType; -use std::ops::Deref; -use swc_common::Span; -use swc_ecma_ast::{Callee, Expr, ModuleItem, Prop, PropName, PropOrSpread, Stmt}; - -use crate::{ - errors::{ArgumentError, SyntaxError, TypeError}, - internal_error, - traits::{GetName, GetOptionalName, GetSourceFileInfo, GetSpan}, - ts_ast::SourceMapped, - AliasTable, Error, -}; - -#[derive(Clone)] -pub struct Annotation { - pub method_type: CanisterMethodType, - pub guard: Option, - pub span: Span, -} - -impl Annotation { - pub fn new( - name: &str, - guard: Option, - span: Span, - alias_table: &AliasTable, - ) -> Result { - let name = name.to_string(); - let method_type = match name.as_str() { - _ if alias_table.heartbeat_decorator.contains(&name) => CanisterMethodType::Heartbeat, - _ if alias_table.init_decorator.contains(&name) => CanisterMethodType::Init, - _ if alias_table.inspect_message_decorator.contains(&name) => { - CanisterMethodType::InspectMessage - } - _ if alias_table.post_upgrade_decorator.contains(&name) => { - CanisterMethodType::PostUpgrade - } - _ if alias_table.pre_upgrade_decorator.contains(&name) => { - CanisterMethodType::PreUpgrade - } - _ if alias_table.query_decorator.contains(&name) => CanisterMethodType::Query, - _ if alias_table.update_decorator.contains(&name) => CanisterMethodType::Update, - _ => internal_error!(), - }; - - let guard = match guard { - Some(str_ref) => Some(str_ref.to_string()), - None => None, - }; - - Ok(Self { - method_type, - guard, - span, - }) - } - - pub fn from_module_item(module_item: &SourceMapped) -> Result { - let expr = match module_item.deref() { - ModuleItem::Stmt(Stmt::Expr(expr)) => &*expr.expr, - _ => internal_error!(), - }; - - match expr { - Expr::Ident(ident) => { - Self::new(&ident.get_name(), None, ident.span, module_item.alias_table) - } - Expr::Member(member) => { - let name = match member.get_name() { - Some(name) => name, - None => internal_error!(), // If the member name can't be made into a name then it won't be recognized as annotation so it won't possibly get here - }; - Self::new(&name, None, member.span, module_item.alias_table) - } - Expr::Call(call_expr) => { - let method_type = match &call_expr.callee { - Callee::Expr(expr) => match &**expr { - Expr::Ident(ident) => ident.get_name(), - Expr::Member(member) => match member.get_name() { - Some(name) => name, - None => internal_error!(), // If the member name can't be made into a name then it won't be recognized as annotation so it won't possibly get here - }, - _ => internal_error!(), - }, - _ => internal_error!(), - }; - - if call_expr.args.len() > 1 { - let location = module_item.source_map.get_location(call_expr.span); - return Err(ArgumentError::error( - format!("expected 0-1 arguments, but got {}", call_expr.args.len()), - location, - )); - } - - if call_expr.args.len() == 0 { - return Self::new(&method_type, None, call_expr.span, module_item.alias_table); - } - - let options_object = { - let expr_or_spread = &call_expr.args[0]; - if expr_or_spread.spread.is_some() { - return Err( - SyntaxError::error( - "spread operation is unsupported in canister method annotations at this time.".to_string(), - module_item.source_map.get_location(expr_or_spread.expr.get_span()) - ), - ); - } - match &*expr_or_spread.expr { - Expr::Object(object_literal) => object_literal, - _ => { - return Err(TypeError::error( - format!("expected options to be an object literal"), - module_item - .source_map - .get_location(expr_or_spread.expr.get_span()), - )) - } - } - }; - - // TODO: instead of counting the properties, consider going through all properties - // and saying "Property x does not exist on type CanisterMethodOptions" - if options_object.props.len() > 1 { - return Err(TypeError::error( - "too many properties: expected only one property, \"guard\"".to_string(), - module_item.source_map.get_location(options_object.span), - )); - } - - if options_object.props.len() == 0 { - // TODO: Consider making this an error. If options object has no - // properties it should be removed and the annotation not invoked - - return Self::new(&method_type, None, call_expr.span, module_item.alias_table); - } - - let option_property = match &options_object.props[0] { - PropOrSpread::Spread(spread_element) => return Err( - SyntaxError::error( - "spread operation is unsupported in canister method annotations at this time.".to_string(), - module_item.source_map.get_location(spread_element.expr.get_span()) - ) - ), - PropOrSpread::Prop(prop) => match &**prop { - Prop::KeyValue(key_value_prop) => key_value_prop, - Prop::Shorthand(ident) => return Err( - SyntaxError::error( - "shorthand notation unsupported here".to_string(), - module_item.source_map.get_location(ident.span) - ) - ), - Prop::Assign(assign_prop) => return Err( - SyntaxError::error( - "default assignment unsupported here".to_string(), - module_item.source_map.get_location(assign_prop.key.span) - ) - ), - Prop::Getter(getter_prop) => return Err( - SyntaxError::error( - "getter not allowed here".to_string(), - module_item.source_map.get_location(getter_prop.span) - ) - ), - Prop::Setter(setter_prop) => return Err( - SyntaxError::error( - "setter not allowed here".to_string(), - module_item.source_map.get_location(setter_prop.span) - ) - ), - Prop::Method(method_prop) => return Err( - SyntaxError::error( - "method not allowed here".to_string(), - module_item.source_map.get_location(method_prop.function.span) - ) - ), - }, - }; - - let (key, key_span) = - match &option_property.key { - PropName::Ident(ident) => (ident.get_name(), ident.span), - PropName::Str(str) => (str.value.to_string(), str.span), - PropName::Num(num) => { - return Err(TypeError::error( - format!( - "invalid property: given \"{}\", but expected \"guard\"", - num.value - ), - module_item.source_map.get_location(num.span), - )) - } - PropName::BigInt(big_int) => { - return Err(TypeError::error( - format!( - "invalid property: given \"{}\", but expected \"guard\"", - big_int.value - ), - module_item.source_map.get_location(big_int.span), - )) - } - PropName::Computed(computed_prop_name) => return Err(SyntaxError::error( - "computed properties are not supported in options object at this time." - .to_string(), - module_item.source_map.get_location(computed_prop_name.span), - )), - }; - - if key != "guard".to_string() { - return Err(TypeError::error( - format!( - "invalid property: given \"{}\", but expected \"guard\"", - key - ), - module_item.source_map.get_location(key_span), - )); - } - - let guard_fn_name = match &*option_property.value { - Expr::Ident(ident) => Some(ident.get_name()), - _ => return Err(TypeError::error( - "invalid value: guard must be an identifier referring to a guard function" - .to_string(), - module_item - .source_map - .get_location(option_property.value.get_span()), - )), - }; - - Self::new( - &method_type, - guard_fn_name, - call_expr.span, - module_item.alias_table, - ) - } - _ => internal_error!(), - } - } -} - -pub fn is_canister_method_annotation(name: &str, alias_table: &AliasTable) -> bool { - let name = name.to_string(); - alias_table.heartbeat_decorator.contains(&name) - || alias_table.init_decorator.contains(&name) - || alias_table.inspect_message_decorator.contains(&name) - || alias_table.post_upgrade_decorator.contains(&name) - || alias_table.pre_upgrade_decorator.contains(&name) - || alias_table.query_decorator.contains(&name) - || alias_table.update_decorator.contains(&name) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/check_length_and_map.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/check_length_and_map.rs deleted file mode 100644 index e52aa83000..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/check_length_and_map.rs +++ /dev/null @@ -1,67 +0,0 @@ -use crate::Error; - -pub trait CheckLengthAndMapTwo { - fn check_length_and_map( - &self, - length_check: bool, - length_error_generator: E, - callback: F, - ) -> Vec>> - where - F: Fn(&Node) -> Result>, - E: Fn(&Vec) -> Error; - - fn check_length_is_one_and_map( - &self, - length_error_generator: E, - callback: F, - ) -> Result> - where - F: Fn(&Node) -> Result>, - E: Fn(&Vec) -> Error + Clone; -} - -impl CheckLengthAndMapTwo for Vec { - fn check_length_and_map( - &self, - meets_length_requirement: bool, - length_error_generator: E, - callback: F, - ) -> Vec>> - where - F: Fn(&Node) -> Result>, - E: Fn(&Vec) -> Error, - { - let results_list: Vec<_> = self.clone().into_iter().map(callback).collect(); - - if !meets_length_requirement { - let length_error: Vec = length_error_generator(self).into(); - let length_result: Result = Err(length_error); - - vec![length_result] - .into_iter() - .chain(results_list) - .collect() - } else { - results_list - } - } - - fn check_length_is_one_and_map( - &self, - length_error_generator: E, - callback: F, - ) -> Result> - where - F: Fn(&Node) -> Result>, - E: Fn(&Vec) -> Error + Clone, - { - match self - .check_length_and_map(self.len() == 1, length_error_generator.clone(), callback) - .pop() - { - Some(ok_value) => ok_value, - None => Err(length_error_generator(self).into()), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/async_not_allowed.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/async_not_allowed.rs deleted file mode 100644 index 537b66a5a3..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/async_not_allowed.rs +++ /dev/null @@ -1,111 +0,0 @@ -use cdk_framework::act::node::canister_method::CanisterMethodType; - -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, InternalError, Location, Suggestion}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, - Error, -}; - -/// Returned when a system canister method (other than heartbeat) is marked as async. -/// -/// # Example -/// -/// ```ts -/// import { $init } from 'azle'; -/// -/// $init; -/// export async function init(): Promise {} -/// ``` -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AsyncNotAllowed { - pub annotation: String, - pub location: Location, -} - -impl AsyncNotAllowed { - pub fn error_from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - ) -> Error { - let annotation = match annotated_fn_decl.annotation.method_type { - CanisterMethodType::Heartbeat => "$heartbeat", - CanisterMethodType::Init => "$init", - CanisterMethodType::InspectMessage => "$inspectMessage", - CanisterMethodType::PostUpgrade => "$postUpgrade", - CanisterMethodType::PreUpgrade => "$preUpgrade", - CanisterMethodType::Query => "$query", - CanisterMethodType::Update => "$update", - } - .to_string(); - - let span = match &annotated_fn_decl.fn_decl.function.return_type { - Some(return_type) => return_type.span, - // Return Types are guaranteed by a check in get_annotated_fn_decls: - // src/compiler/typescript_to_rust/azle_generate/src/canister_method/module.rs - None => return Error::InternalError(InternalError::new()), - }; - let origin = annotated_fn_decl.source_map.get_origin(span); - let line_number = annotated_fn_decl.source_map.get_line_number(span); - let source = annotated_fn_decl.source_map.get_source(span); - let range = annotated_fn_decl.source_map.get_range(span); - - Self { - annotation, - location: Location { - line_number, - origin, - range, - source, - }, - } - .into() - } - - pub fn to_string(&self) -> String { - let title = format!("{} canister method cannot be async", self.annotation); - - let annotation = "here".to_string(); - - let removed_async_keyword = "".to_string(); - let suggestion = Some(Suggestion { - title: "Remove the async keyword. E.g.:".to_string(), - source: generate_source_with_range_replaced(&self.location, &removed_async_keyword), - range: (0, 0), - annotation: None, - import_suggestion: None, - }); - - CompilerOutput { - title, - location: self.location.clone(), - annotation, - suggestion, - } - .to_string() - } -} - -impl std::error::Error for AsyncNotAllowed {} - -impl std::fmt::Display for AsyncNotAllowed { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for crate::Error { - fn from(error: AsyncNotAllowed) -> Self { - Self::AsyncNotAllowed(error) - } -} - -fn generate_source_with_range_replaced(location: &Location, replacement: &String) -> String { - location - .source - .chars() - .take(location.range.0) - .chain(replacement.chars()) - .chain(location.source.chars().skip(location.range.1)) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/duplicate_system_method.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/duplicate_system_method.rs deleted file mode 100644 index fd34c774b2..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/duplicate_system_method.rs +++ /dev/null @@ -1,150 +0,0 @@ -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; -use cdk_framework::act::node::canister_method::CanisterMethodType; -use swc_common::{source_map::Pos, Span}; - -use crate::{canister_method::AnnotatedFnDecl, traits::GetSourceFileInfo, ts_ast::SourceMapped}; - -/// Returned when Azle detects multiple system canister method annotations -/// of the same type. -/// -/// # Example -/// -/// ```ts -/// import { $init } from 'azle'; -/// -/// $init; -/// export function firstOccurrence(): void { -/// console.log("First init method") -/// } -/// -/// $init; -/// export function secondOccurrence(): void { -/// console.log("Invalid second init method") -/// } -/// ``` -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DuplicateSystemMethod { - pub canister_method_type: CanisterMethodType, - pub origin: String, - pub line_number: usize, - pub source: String, - pub ranges: Vec<(usize, usize)>, -} - -impl DuplicateSystemMethod { - pub fn from_annotated_fn_decls( - annotated_fn_decls: &Vec<&SourceMapped>, - canister_method_type: CanisterMethodType, - ) -> Self { - // TODO: Might this be a problem if the fn_decls come from different - // typescript files? - let source_map = annotated_fn_decls[0].source_map; - - // TODO: Grab the span of the annotation - let canister_method_spans: Vec = annotated_fn_decls - .iter() - .map(|annotated_fn_decl| annotated_fn_decl.fn_decl.function.span) - .collect(); - - let total_range = ( - canister_method_spans[0].lo, - canister_method_spans[canister_method_spans.len() - 1].hi, - ); - let source = source_map.get_source_from_range(total_range); - - let first_occurrence = canister_method_spans[0]; - let line_number = source_map.get_line_number(first_occurrence); - let origin = source_map.get_origin(first_occurrence); - let offset = total_range.0.to_usize() - source_map.get_range(first_occurrence).0; - - let ranges: Vec<_> = canister_method_spans - .iter() - .map(|span| source_map.get_multi_line_range(span, offset)) - .collect(); - - Self { - canister_method_type, - origin, - line_number, - source, - ranges, - } - } - - pub fn to_string(&self) -> String { - let canister_method_type = match self.canister_method_type { - CanisterMethodType::Heartbeat => "$heartbeat", - CanisterMethodType::Init => "$init", - CanisterMethodType::InspectMessage => "$inspectMessage", - CanisterMethodType::PostUpgrade => "$postUpgrade", - CanisterMethodType::PreUpgrade => "$preUpgrade", - CanisterMethodType::Query => "$query", - CanisterMethodType::Update => "$update", - }; - - let error_message = format!( - "duplicate {} canister method implementation", - canister_method_type - ); - - let annotations: Vec = self - .ranges - .iter() - .enumerate() - .map(|(i, range)| SourceAnnotation { - label: if i == 0 { - "first specified here" - } else { - "and later specified here" - }, - annotation_type: AnnotationType::Error, - range: *range, - }) - .collect(); - - let suggestion = format!("remove all but one {} method", canister_method_type); - - let error_snippet = Snippet { - title: Some(Annotation { - label: Some(&error_message), - id: None, - annotation_type: AnnotationType::Error, - }), - slices: vec![Slice { - source: &self.source, - line_start: self.line_number, - origin: Some(&self.origin), - fold: true, - annotations: annotations, - }], - footer: vec![Annotation { - label: Some(&suggestion), - id: None, - annotation_type: AnnotationType::Help, - }], - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - format!("{}", DisplayList::from(error_snippet)) - } -} - -impl std::error::Error for DuplicateSystemMethod {} - -impl std::fmt::Display for DuplicateSystemMethod { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for crate::Error { - fn from(error: DuplicateSystemMethod) -> Self { - Self::DuplicateSystemMethodImplementation(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/extraneous_canister_method_annotation.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/extraneous_canister_method_annotation.rs deleted file mode 100644 index b4141794f4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/extraneous_canister_method_annotation.rs +++ /dev/null @@ -1,110 +0,0 @@ -use cdk_framework::act::node::canister_method::CanisterMethodType; - -use crate::{ - canister_method::Annotation, - errors::{CompilerOutput, Location, Suggestion}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -/// Returned when Azle detects a canister method annotation without an -/// accompanying exported function signature immediately after. -/// -/// # Examples -/// -/// 1. Decorator separated from function by other statements -/// -/// ```ts -/// import { $init } from 'azle'; -/// -/// $init; // Not immediately followed by exported function -/// let thisShouldNotBeHere; -/// export function init(): void {} -/// ``` -/// -/// 2. Trailing decorator at end of file -/// -/// ```ts -/// import { $query } from 'azle'; -/// -/// //... -/// -/// $query; // Not followed by exported function -/// ``` -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ExtraneousCanisterMethodAnnotation { - pub annotation: String, - pub location: Location, -} - -impl ExtraneousCanisterMethodAnnotation { - pub fn from_annotation(sm_annotation: &SourceMapped) -> Self { - let annotation = match sm_annotation.method_type { - CanisterMethodType::Heartbeat => "$heartbeat", - CanisterMethodType::Init => "$init", - CanisterMethodType::InspectMessage => "$inspectMessage", - CanisterMethodType::PostUpgrade => "$postUpgrade", - CanisterMethodType::PreUpgrade => "$preUpgrade", - CanisterMethodType::Query => "$query", - CanisterMethodType::Update => "$update", - } - .to_string(); - - let span = sm_annotation.span; - let line_number = sm_annotation.source_map.get_line_number(span); - let origin = sm_annotation.source_map.get_origin(span); - let range = sm_annotation.source_map.get_range(span); - let source = sm_annotation.source_map.get_source(span); - - Self { - annotation, - location: Location { - line_number, - origin, - range, - source, - }, - } - } - - pub fn to_string(&self) -> String { - let example_function_declaration = - "export function some_canister_method() {\n // method body\n}"; - - let suggested_source = - format!("{}\n{}", self.location.source, example_function_declaration); - - CompilerOutput { - title: format!("extraneous {} annotation", self.annotation), - location: self.location.clone(), - annotation: "expected this to be followed by an exported function declaration" - .to_string(), - suggestion: Some(Suggestion { - title: "Follow it with an exported function declaration or remove it. E.g.:" - .to_string(), - source: suggested_source, - range: ( - self.location.range.1 + 1, - self.location.range.1 + example_function_declaration.len(), - ), - annotation: None, - import_suggestion: None, - }), - } - .to_string() - } -} - -impl std::error::Error for ExtraneousCanisterMethodAnnotation {} - -impl std::fmt::Display for ExtraneousCanisterMethodAnnotation { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for crate::Error { - fn from(error: ExtraneousCanisterMethodAnnotation) -> Self { - Self::ExtraneousCanisterMethodAnnotation(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/missing_return_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/missing_return_type.rs deleted file mode 100644 index 7d956cef06..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/missing_return_type.rs +++ /dev/null @@ -1,121 +0,0 @@ -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location, Suggestion}, - traits::{GetName, GetSourceFileInfo}, - ts_ast::SourceMapped, -}; - -/// Returned when Azle detects a canister method that doesn't specify a return type. -/// -/// # Example -/// -/// ```ts -/// import { $query } from 'azle'; -/// -/// $query; -/// export function canisterMethod() {} -/// ``` -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MissingReturnTypeAnnotation { - pub function_name: String, - pub location: Location, -} - -impl MissingReturnTypeAnnotation { - pub fn from_annotated_fn_decl(annotated_fn_decl: &SourceMapped) -> Self { - let span = annotated_fn_decl.fn_decl.function.span; - - let function_name = annotated_fn_decl.fn_decl.ident.get_name(); - - let line_number = annotated_fn_decl.source_map.get_line_number(span); - let origin = annotated_fn_decl.source_map.get_origin(span); - - // TODO: Not very robust. - let range = match annotated_fn_decl.fn_decl.function.params.last() { - Some(param) => { - let last_param_span_end_pos = - annotated_fn_decl.source_map.get_range(param.span).1 + 1; - (last_param_span_end_pos, last_param_span_end_pos + 1) - } - None => { - let ident_span_end_pos = annotated_fn_decl - .source_map - .get_range(annotated_fn_decl.fn_decl.ident.span) - .1; - let parens_length = "()".to_string().len(); - - ( - ident_span_end_pos + parens_length, - ident_span_end_pos + parens_length + 1, - ) - } - }; - let source = annotated_fn_decl.source_map.get_source(span); - - Self { - function_name, - location: Location { - origin, - line_number, - source, - range, - }, - } - } - - pub fn to_string(&self) -> String { - let example_return_type = ": void".to_string(); - let suggested_source = insert_return_type_into_source( - &self.location.source, - self.location.range.0, - &example_return_type, - ); - - CompilerOutput { - title: format!( - "missing return type annotation for canister method \"{}\"", - self.function_name - ), - location: self.location.clone(), - annotation: "expected here".to_string(), - suggestion: Some(Suggestion { - title: "Add a valid candid type as a return type. E.g.:".to_string(), - source: suggested_source, - range: ( - self.location.range.0, - self.location.range.0 + example_return_type.len(), - ), - annotation: None, - import_suggestion: None, - }), - } - .to_string() - } -} - -impl std::error::Error for MissingReturnTypeAnnotation {} - -impl std::fmt::Display for MissingReturnTypeAnnotation { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for crate::Error { - fn from(error: MissingReturnTypeAnnotation) -> Self { - Self::MissingReturnTypeAnnotation(error) - } -} - -fn insert_return_type_into_source( - source: &String, - index: usize, - return_type_annotation: &String, -) -> String { - format!( - "{}{}{}", - &source[..index], - return_type_annotation, - &source[index..] - ) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/mod.rs deleted file mode 100644 index be07cbf594..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -use swc_ecma_ast::{TsKeywordTypeKind, TsType}; - -use crate::{canister_method::AnnotatedFnDecl, ts_ast::SourceMapped}; - -pub use async_not_allowed::AsyncNotAllowed; -pub use duplicate_system_method::DuplicateSystemMethod; -pub use extraneous_canister_method_annotation::ExtraneousCanisterMethodAnnotation; -pub use missing_return_type::MissingReturnTypeAnnotation; -pub use void_return_type_required::VoidReturnTypeRequired; - -mod async_not_allowed; -mod duplicate_system_method; -mod extraneous_canister_method_annotation; -mod missing_return_type; -mod void_return_type_required; - -impl<'a> SourceMapped<'a, AnnotatedFnDecl> { - pub fn is_void(&self) -> bool { - if let Ok(TsType::TsKeywordType(keyword)) = self.get_return_ts_type() { - if let TsKeywordTypeKind::TsVoidKeyword = keyword.kind { - return true; - } - } - - return false; - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/void_return_type_required.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/void_return_type_required.rs deleted file mode 100644 index 3091a28474..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/errors/void_return_type_required.rs +++ /dev/null @@ -1,101 +0,0 @@ -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, InternalError, Location, Suggestion}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, - Error, -}; - -/// Returned when a system canister method has a return type other than void -/// (or Promise for heartbeat methods). -/// -/// # Example -/// -/// ```ts -/// import { $init } from 'azle'; -/// -/// $init; -/// export function init(): boolean { -/// return false -/// } -/// ``` -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct VoidReturnTypeRequired { - pub location: Location, -} - -impl VoidReturnTypeRequired { - pub fn error_from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - ) -> Error { - let span = match &annotated_fn_decl.fn_decl.function.return_type { - Some(return_type) => return_type.span, - // Return Types are guaranteed by a check in get_annotated_fn_decls: - // src/compiler/typescript_to_rust/azle_generate/src/canister_method/module.rs - None => return Error::InternalError(InternalError::new()), - }; - let line_number = annotated_fn_decl.source_map.get_line_number(span); - let origin = annotated_fn_decl.source_map.get_origin(span); - let range = annotated_fn_decl.source_map.get_range(span); - let source = annotated_fn_decl.source_map.get_source(span); - - Self { - location: Location { - line_number, - origin, - range, - source, - }, - } - .into() - } - - pub fn to_string(&self) -> String { - let title = "return type required to be void on system canister methods".to_string(); - let annotation = "required here".to_string(); - - let void_return_type = ": void".to_string(); - let suggestion = Some(Suggestion { - title: "Change the return type to void. E.g.:".to_string(), - source: generate_source_with_range_replaced(&self.location, &void_return_type), - range: ( - self.location.range.0, - self.location.range.0 + void_return_type.len(), - ), - annotation: None, - import_suggestion: None, - }); - - CompilerOutput { - title, - location: self.location.clone(), - annotation, - suggestion, - } - .to_string() - } -} - -impl std::error::Error for VoidReturnTypeRequired {} - -impl std::fmt::Display for VoidReturnTypeRequired { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for crate::Error { - fn from(error: VoidReturnTypeRequired) -> Self { - Self::VoidReturnTypeRequired(error) - } -} - -fn generate_source_with_range_replaced(location: &Location, replacement: &String) -> String { - location - .source - .chars() - .take(location.range.0) - .chain(replacement.chars()) - .chain(location.source.chars().skip(location.range.1)) - .collect() -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/heartbeat/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/heartbeat/mod.rs deleted file mode 100644 index 454e28c4ff..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/heartbeat/mod.rs +++ /dev/null @@ -1,55 +0,0 @@ -use cdk_framework::{ - act::node::canister_method::{CanisterMethodType, HeartbeatMethod}, - traits::CollectResults, -}; - -use super::{ - check_length_and_map::CheckLengthAndMapTwo, - errors::{DuplicateSystemMethod, VoidReturnTypeRequired}, - AnnotatedFnDecl, -}; -use crate::{ts_ast::SourceMapped, Error, TsAst}; - -mod rust; - -impl TsAst { - pub fn build_heartbeat_method( - &self, - annotated_fn_decls: &Vec>, - ) -> Result, Vec> { - let heartbeat_fn_decls: Vec<_> = annotated_fn_decls - .iter() - .filter(|annotated_fn_decl| { - annotated_fn_decl.is_canister_method_type(CanisterMethodType::Heartbeat) - }) - .collect(); - Ok(heartbeat_fn_decls - .check_length_and_map( - heartbeat_fn_decls.len() <= 1, - |fn_decls| { - DuplicateSystemMethod::from_annotated_fn_decls( - &fn_decls, - CanisterMethodType::Heartbeat, - ) - .into() - }, - |heartbeat_fn_decl| { - if !heartbeat_fn_decl.is_void() { - Err( - VoidReturnTypeRequired::error_from_annotated_fn_decl(heartbeat_fn_decl) - .into(), - ) - } else { - let body = rust::generate(heartbeat_fn_decl)?; - let guard_function_name = heartbeat_fn_decl.annotation.guard.clone(); - Ok(HeartbeatMethod { - body, - guard_function_name, - }) - } - }, - ) - .collect_results()? - .pop()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/heartbeat/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/heartbeat/rust.rs deleted file mode 100644 index 618a96d4f6..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/heartbeat/rust.rs +++ /dev/null @@ -1,53 +0,0 @@ -use crate::{ - canister_method::{rust, AnnotatedFnDecl}, - ts_ast::SourceMapped, - Error, -}; - -pub fn generate( - heartbeat_fn_decl: &SourceMapped, -) -> Result> { - let call_to_heartbeat_js_function = rust::generate_call_to_js_function(heartbeat_fn_decl)?; - - let function_name = heartbeat_fn_decl.get_function_name(); - - Ok(quote::quote! { - unwrap_or_trap(|| { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - let uuid = uuid::Uuid::new_v4().to_string(); - - UUID_REF_CELL.with(|uuid_ref_cell| { - let mut uuid_mut = uuid_ref_cell.borrow_mut(); - - *uuid_mut = uuid.clone(); - }); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = #function_name.to_string() - }); - - MANUAL_REF_CELL.with(|manual_ref_cell| { - let mut manual_mut = manual_ref_cell.borrow_mut(); - - *manual_mut = true; - }); - - #call_to_heartbeat_js_function - - async_await_result_handler( - &mut boa_context, - &boa_return_value, - &uuid, - #function_name, - true - )?; - - Ok(()) - }) - }) - }) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/init/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/init/mod.rs deleted file mode 100644 index 860520c10d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/init/mod.rs +++ /dev/null @@ -1,84 +0,0 @@ -use cdk_framework::{ - act::node::canister_method::{CanisterMethodType, InitMethod}, - traits::CollectResults, -}; - -use super::{ - check_length_and_map::CheckLengthAndMapTwo, - errors::{DuplicateSystemMethod, VoidReturnTypeRequired}, - AnnotatedFnDecl, -}; -use crate::{ - canister_method::errors::AsyncNotAllowed, plugin::Plugin, ts_ast::SourceMapped, Error, TsAst, -}; - -mod rust; - -impl TsAst { - pub fn build_init_method( - &self, - annotated_fn_decls: &Vec>, - plugins: &Vec, - environment_variables: &Vec<(String, String)>, - ) -> Result> { - let init_fn_decls: Vec<_> = annotated_fn_decls - .iter() - .filter(|annotated_fn_decl| { - annotated_fn_decl.is_canister_method_type(CanisterMethodType::Init) - }) - .collect(); - let init_method_option = init_fn_decls - .check_length_and_map( - init_fn_decls.len() <= 1, - |fn_decls| { - DuplicateSystemMethod::from_annotated_fn_decls( - &fn_decls, - CanisterMethodType::Init, - ) - .into() - }, - |init_fn_decl| { - let (_, _, params, body) = ( - match init_fn_decl.is_void() { - true => Ok(()), - false => { - Err(vec![VoidReturnTypeRequired::error_from_annotated_fn_decl( - init_fn_decl, - )]) - } - }, - match init_fn_decl.fn_decl.function.is_async { - true => Err(vec![AsyncNotAllowed::error_from_annotated_fn_decl( - init_fn_decl, - )]), - false => Ok(()), - }, - init_fn_decl.build_params(), - rust::generate(Some(init_fn_decl), plugins, environment_variables), - ) - .collect_results()?; - - let guard_function_name = None; // Unsupported. See https://github.com/demergent-labs/azle/issues/954 - - Ok(InitMethod { - params, - body, - guard_function_name, - }) - }, - ) - .collect_results()? - .pop(); - - match init_method_option { - Some(init_fn_decl) => Ok(init_fn_decl), - None => { - Ok(InitMethod { - params: vec![], - body: rust::generate(None, plugins, environment_variables)?, - guard_function_name: None, // Unsupported. See https://github.com/demergent-labs/azle/issues/954 - }) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/init/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/init/rust.rs deleted file mode 100644 index e4bac7df32..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/init/rust.rs +++ /dev/null @@ -1,66 +0,0 @@ -use crate::{ - canister_method::{rust, AnnotatedFnDecl}, - plugin::Plugin, - ts_ast::SourceMapped, - Error, -}; -use cdk_framework::traits::ToIdent; -use quote::quote; - -pub fn generate( - init_fn_decl_option: Option<&SourceMapped>, - plugins: &Vec, - environment_variables: &Vec<(String, String)>, -) -> Result> { - let call_to_init_js_function = rust::maybe_generate_call_to_js_function(&init_fn_decl_option)?; - - let function_name = match &init_fn_decl_option { - Some(init_fn_decl) => init_fn_decl.get_function_name(), - None => "DOES_NOT_EXIST".to_string(), - }; - - let register_plugins = plugins.iter().map(|plugin| { - let register_function_ident = plugin.register_function.to_ident(); - - quote!(#register_function_ident(&mut boa_context);) - }); - - let register_process_object = rust::generate_register_process_object(environment_variables); - - Ok(quote! { - unsafe { ic_wasi_polyfill::init(&[], &[]); } - - unwrap_or_trap(|| { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = #function_name.to_string() - }); - - register_ic_object(&mut boa_context); - - #register_process_object - - #(#register_plugins)* - - boa_context.eval( - boa_engine::Source::from_bytes( - &format!( - "let exports = {{}}; {compiled_js}", - compiled_js = MAIN_JS - ) - ) - )?; - - #call_to_init_js_function - - ic_cdk_timers::set_timer(core::time::Duration::new(0, 0), rng_seed); - - Ok(()) - }) - }) - }) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/inspect_message/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/inspect_message/mod.rs deleted file mode 100644 index ddff3bad5f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/inspect_message/mod.rs +++ /dev/null @@ -1,68 +0,0 @@ -use cdk_framework::{ - act::node::{canister_method::CanisterMethodType, canister_method::InspectMessageMethod}, - traits::CollectResults, -}; - -use super::{ - check_length_and_map::CheckLengthAndMapTwo, - errors::{AsyncNotAllowed, DuplicateSystemMethod, VoidReturnTypeRequired}, - AnnotatedFnDecl, -}; -use crate::{ts_ast::SourceMapped, Error, TsAst}; - -mod rust; - -impl TsAst { - pub fn build_inspect_message_method( - &self, - annotated_fn_decls: &Vec>, - ) -> Result, Vec> { - let inspect_message_fn_decls: Vec<_> = annotated_fn_decls - .iter() - .filter(|annotated_fn_decl| { - annotated_fn_decl.is_canister_method_type(CanisterMethodType::InspectMessage) - }) - .collect(); - Ok(inspect_message_fn_decls - .check_length_and_map( - inspect_message_fn_decls.len() <= 1, - |fn_decls| { - DuplicateSystemMethod::from_annotated_fn_decls( - &fn_decls, - CanisterMethodType::InspectMessage, - ) - .into() - }, - |inspect_message_fn_decl| { - let (_, _, body) = ( - match inspect_message_fn_decl.is_void() { - true => Ok(()), - false => { - Err(vec![VoidReturnTypeRequired::error_from_annotated_fn_decl( - inspect_message_fn_decl, - )]) - } - }, - match inspect_message_fn_decl.fn_decl.function.is_async { - true => Err(vec![AsyncNotAllowed::error_from_annotated_fn_decl( - inspect_message_fn_decl, - ) - .into()]), - false => Ok(()), - }, - rust::generate(inspect_message_fn_decl), - ) - .collect_results()?; - - let guard_function_name = inspect_message_fn_decl.annotation.guard.clone(); - - Ok(InspectMessageMethod { - body, - guard_function_name, - }) - }, - ) - .collect_results()? - .pop()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/inspect_message/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/inspect_message/rust.rs deleted file mode 100644 index f7927b59bf..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/inspect_message/rust.rs +++ /dev/null @@ -1,32 +0,0 @@ -use crate::{ - canister_method::{rust, AnnotatedFnDecl}, - ts_ast::SourceMapped, - Error, -}; - -pub fn generate( - inspect_message_fn_decl: &SourceMapped, -) -> Result> { - let call_to_inspect_message_js_function = - rust::generate_call_to_js_function(inspect_message_fn_decl)?; - - let function_name = inspect_message_fn_decl.get_function_name(); - - Ok(quote::quote! { - unwrap_or_trap(|| { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = #function_name.to_string() - }); - - #call_to_inspect_message_js_function - - Ok(()) - }) - }) - }) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/mod.rs deleted file mode 100644 index 892d9315e7..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/mod.rs +++ /dev/null @@ -1,72 +0,0 @@ -use cdk_framework::{act::CanisterMethods, traits::CollectResults}; - -use crate::{plugin::Plugin, ts_ast::TsAst, Error}; - -pub use annotated_fn_decl::{AnnotatedFnDecl, GetAnnotatedFnDecls}; -pub use annotation::Annotation; - -pub mod annotated_fn_decl; -mod annotation; -pub mod check_length_and_map; -mod heartbeat; -mod init; -mod inspect_message; -mod module_item; -mod post_upgrade; -mod pre_upgrade; -mod query_and_update; -mod rust; - -pub mod errors; -pub mod module; - -impl TsAst { - pub fn build_canister_methods( - &self, - plugins: &Vec, - environment_variables: &Vec<(String, String)>, - ) -> Result> { - let (annotated_fn_decls, get_annotated_fn_decls_errors) = - self.programs.get_annotated_fn_decls(); - - let build_canister_methods_result = ( - self.build_heartbeat_method(&annotated_fn_decls), - self.build_init_method(&annotated_fn_decls, plugins, environment_variables), - self.build_inspect_message_method(&annotated_fn_decls), - self.build_post_upgrade_method(&annotated_fn_decls, plugins, environment_variables), - self.build_pre_upgrade_method(&annotated_fn_decls), - self.build_query_methods(&annotated_fn_decls), - self.build_update_methods(&annotated_fn_decls), - ) - .collect_results(); - - match build_canister_methods_result { - Ok(canister_methods) => { - if !get_annotated_fn_decls_errors.is_empty() { - return Err(get_annotated_fn_decls_errors); - } - - let ( - heartbeat_method, - init_method, - inspect_message_method, - post_upgrade_method, - pre_upgrade_method, - query_methods, - update_methods, - ) = canister_methods; - - Ok(CanisterMethods { - heartbeat_method, - init_method: Some(init_method), - inspect_message_method, - post_upgrade_method: Some(post_upgrade_method), - pre_upgrade_method, - query_methods, - update_methods, - }) - } - Err(errors) => Err(vec![get_annotated_fn_decls_errors, errors].concat()), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/module.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/module.rs deleted file mode 100644 index 2c3a8025a8..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/module.rs +++ /dev/null @@ -1,154 +0,0 @@ -use swc_common::SourceMap; -use swc_ecma_ast::{Decl, FnDecl, Module, ModuleDecl, ModuleItem, Stmt}; - -use crate::{ - canister_method::{ - errors::{ExtraneousCanisterMethodAnnotation, MissingReturnTypeAnnotation}, - AnnotatedFnDecl, - }, - ts_ast::SourceMapped, - AliasTable, Error, -}; - -pub trait ModuleHelperMethods { - fn get_annotated_fn_decls<'a>( - &'a self, - source_map: &'a SourceMap, - alias_table: &'a AliasTable, - alias_list: &'a Vec, - ) -> (Vec>, Vec); - fn get_fn_decls<'a>( - &'a self, - source_map: &'a SourceMap, - alias_table: &'a AliasTable, - alias_list: &'a Vec, - ) -> Vec>; -} - -struct Accumulator<'a> { - pub annotated_fn_decls: Vec>, - pub errors: Vec, -} - -impl Accumulator<'_> { - pub fn new() -> Self { - Self { - annotated_fn_decls: Default::default(), - errors: Default::default(), - } - } -} - -impl<'a> From> for (Vec>, Vec) { - fn from(acc: Accumulator<'a>) -> Self { - (acc.annotated_fn_decls, acc.errors) - } -} - -impl ModuleHelperMethods for Module { - // TODO: This should be implemented on SourceMapped. - // Then you wouldn't need to pass the source_map in as a param. - // ideally body then would be a Vec> - fn get_annotated_fn_decls<'a>( - &'a self, - source_map: &'a SourceMap, - alias_table: &'a AliasTable, - alias_list: &'a Vec, - ) -> (Vec>, Vec) { - let source_mapped_body: Vec<_> = self - .body - .iter() - .map(|module_item| SourceMapped::new(module_item, source_map, alias_table, alias_list)) - .collect(); - - source_mapped_body.clone() - .into_iter() - .enumerate() - .fold(Accumulator::new(), |mut acc, (i, module_item)| { - if let Some(result) = module_item.as_canister_method_annotation() { - match result { - Ok(annotation) => { - match source_mapped_body.get(i + 1) { - Some(next_item) => { - let next_item = module_item.spawn(next_item); - match next_item.as_exported_fn_decl() { - Some(fn_decl) => { - let annotated_fn_decl = AnnotatedFnDecl { - annotation, - fn_decl: fn_decl.clone(), - }; - let sm_annotated_fn_decl = SourceMapped::new(&annotated_fn_decl, source_map, alias_table, alias_list); - - match &fn_decl.function.return_type { - Some(_) => { - acc.annotated_fn_decls.push(sm_annotated_fn_decl) - } - None => { - let missing_return_type_annotation = - MissingReturnTypeAnnotation::from_annotated_fn_decl(&sm_annotated_fn_decl); - acc.errors.push(missing_return_type_annotation.into()) - } - } - } - // There is an annotation not followed by an exported function (but not at end of file) - None => acc.errors.push( - ExtraneousCanisterMethodAnnotation::from_annotation( - &module_item.spawn(&annotation) - ).into() - ) - } - } - // There is a dangling canister method annotation at the end of the file. - None => acc.errors.push( - ExtraneousCanisterMethodAnnotation::from_annotation(&module_item.spawn(&annotation)) - .into(), - ), - }; - }, - Err(err) => acc.errors.push(err) - } - } - - acc - }) - .into() - } - - fn get_fn_decls<'a>( - &'a self, - source_map: &'a SourceMap, - alias_table: &'a AliasTable, - alias_list: &'a Vec, - ) -> Vec> { - self.body - .iter() - .filter_map(|module_item| { - Some(SourceMapped::new( - module_item.as_decl()?.as_fn_decl()?, - source_map, - alias_table, - alias_list, - )) - }) - .collect() - } -} - -trait AsDecl { - fn as_decl(&self) -> Option<&Decl>; -} - -impl AsDecl for ModuleItem { - fn as_decl(&self) -> Option<&Decl> { - match self { - ModuleItem::ModuleDecl(decl) => match decl { - ModuleDecl::ExportDecl(export_decl) => Some(&export_decl.decl), - _ => None, - }, - ModuleItem::Stmt(stmt) => match stmt { - Stmt::Decl(decl) => Some(decl), - _ => None, - }, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/module_item.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/module_item.rs deleted file mode 100644 index 84c651c489..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/module_item.rs +++ /dev/null @@ -1,41 +0,0 @@ -use swc_ecma_ast::{ExprStmt, FnDecl, ModuleItem}; - -use crate::{traits::GetOptionalName, ts_ast::SourceMapped, Error}; - -use super::{annotation::is_canister_method_annotation, Annotation}; - -impl SourceMapped<'_, ModuleItem> { - pub fn as_canister_method_annotation(&self) -> Option> { - self.as_stmt() - .and_then(|stmt| stmt.as_expr()) - .and_then(|expr_stmt| { - expr_stmt - .expr - .as_call() - .and_then(|call_expr| call_expr.callee.as_expr()) - .and_then(|box_expr| box_expr.get_name()) - .or(expr_stmt.expr.get_name()) - .and_then(|name| { - if is_canister_method_annotation(&name, self.alias_table) { - Some(Annotation::from_module_item(self)) - } else { - None - } - }) - }) - } - - pub fn as_exported_fn_decl(&self) -> Option { - Some( - self.as_module_decl()? - .as_export_decl()? - .decl - .as_fn_decl()? - .clone(), - ) - } - - pub fn as_expr_stmt(&self) -> Option { - Some(self.as_stmt()?.as_expr()?.clone()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/post_upgrade/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/post_upgrade/mod.rs deleted file mode 100644 index a764cca23a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/post_upgrade/mod.rs +++ /dev/null @@ -1,83 +0,0 @@ -use cdk_framework::{ - act::node::canister_method::{CanisterMethodType, PostUpgradeMethod}, - traits::CollectResults, -}; - -use super::{ - check_length_and_map::CheckLengthAndMapTwo, - errors::{AsyncNotAllowed, DuplicateSystemMethod, VoidReturnTypeRequired}, - AnnotatedFnDecl, -}; -use crate::{plugin::Plugin, ts_ast::SourceMapped, Error, TsAst}; - -mod rust; - -impl TsAst { - pub fn build_post_upgrade_method( - &self, - annotated_fn_decls: &Vec>, - plugins: &Vec, - environment_variables: &Vec<(String, String)>, - ) -> Result> { - let post_upgrade_fn_decls: Vec<_> = annotated_fn_decls - .iter() - .filter(|annotated_fn_decl| { - annotated_fn_decl.is_canister_method_type(CanisterMethodType::PostUpgrade) - }) - .collect(); - let post_upgrade_method_option = post_upgrade_fn_decls - .check_length_and_map( - post_upgrade_fn_decls.len() <= 1, - |fn_decls| { - DuplicateSystemMethod::from_annotated_fn_decls( - fn_decls, - CanisterMethodType::PostUpgrade, - ) - .into() - }, - |post_upgrade_fn_decl| { - let (_, _, params, body) = ( - match post_upgrade_fn_decl.is_void() { - true => Ok(()), - false => { - Err(vec![VoidReturnTypeRequired::error_from_annotated_fn_decl( - post_upgrade_fn_decl, - )]) - } - }, - match post_upgrade_fn_decl.fn_decl.function.is_async { - true => Err(vec![AsyncNotAllowed::error_from_annotated_fn_decl( - post_upgrade_fn_decl, - ) - .into()]), - false => Ok(()), - }, - post_upgrade_fn_decl.build_params(), - rust::generate(Some(post_upgrade_fn_decl), plugins, environment_variables), - ) - .collect_results()?; - - let guard_function_name = None; // Unsupported. See https://github.com/demergent-labs/azle/issues/954 - - Ok(PostUpgradeMethod { - body, - params, - guard_function_name, - }) - }, - ) - .collect_results()? - .pop(); - - match post_upgrade_method_option { - Some(post_upgrade_method) => Ok(post_upgrade_method), - None => { - Ok(PostUpgradeMethod { - params: vec![], - body: rust::generate(None, plugins, environment_variables)?, - guard_function_name: None, // Unsupported. See https://github.com/demergent-labs/azle/issues/954, - }) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/post_upgrade/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/post_upgrade/rust.rs deleted file mode 100644 index 4d759718a8..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/post_upgrade/rust.rs +++ /dev/null @@ -1,69 +0,0 @@ -use cdk_framework::traits::ToIdent; -use proc_macro2::TokenStream; -use quote::quote; - -use crate::{ - canister_method::{rust, AnnotatedFnDecl}, - plugin::Plugin, - ts_ast::SourceMapped, - Error, -}; - -pub fn generate( - post_upgrade_fn_decl_option: Option<&SourceMapped>, - plugins: &Vec, - environment_variables: &Vec<(String, String)>, -) -> Result> { - let call_to_post_upgrade_js_function = - rust::maybe_generate_call_to_js_function(&post_upgrade_fn_decl_option)?; - - let function_name = match &post_upgrade_fn_decl_option { - Some(post_upgrade_fn_decl) => post_upgrade_fn_decl.get_function_name(), - None => "DOES_NOT_EXIST".to_string(), - }; - - let register_plugins = plugins.iter().map(|plugin| { - let register_function_ident = plugin.register_function.to_ident(); - - quote!(#register_function_ident(&mut boa_context);) - }); - - let register_process_object = rust::generate_register_process_object(environment_variables); - - Ok(quote! { - unsafe { ic_wasi_polyfill::init(&[], &[]); } - - unwrap_or_trap(|| { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = #function_name.to_string() - }); - - register_ic_object(&mut boa_context); - - #register_process_object - - #(#register_plugins)* - - boa_context.eval( - boa_engine::Source::from_bytes( - &format!( - "let exports = {{}}; {compiled_js}", - compiled_js = MAIN_JS - ) - ) - )?; - - #call_to_post_upgrade_js_function - - ic_cdk_timers::set_timer(core::time::Duration::new(0, 0), rng_seed); - - Ok(()) - }) - }) - }) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/pre_upgrade/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/pre_upgrade/mod.rs deleted file mode 100644 index 3adf3befe4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/pre_upgrade/mod.rs +++ /dev/null @@ -1,67 +0,0 @@ -use cdk_framework::{ - act::node::canister_method::{CanisterMethodType, PreUpgradeMethod}, - traits::CollectResults, -}; - -use super::{ - check_length_and_map::CheckLengthAndMapTwo, - errors::{AsyncNotAllowed, DuplicateSystemMethod, VoidReturnTypeRequired}, - AnnotatedFnDecl, -}; -use crate::{ts_ast::SourceMapped, Error, TsAst}; - -mod rust; - -impl TsAst { - pub fn build_pre_upgrade_method( - &self, - annotated_fn_decls: &Vec>, - ) -> Result, Vec> { - let pre_upgrade_fn_decls: Vec<_> = annotated_fn_decls - .iter() - .filter(|annotated_fn_decl| { - annotated_fn_decl.is_canister_method_type(CanisterMethodType::PreUpgrade) - }) - .collect(); - Ok(pre_upgrade_fn_decls - .check_length_and_map( - pre_upgrade_fn_decls.len() <= 1, - |fn_decls| { - DuplicateSystemMethod::from_annotated_fn_decls( - fn_decls, - CanisterMethodType::PreUpgrade, - ) - .into() - }, - |pre_upgrade_fn_decl| { - let (_, _, body) = ( - match pre_upgrade_fn_decl.is_void() { - true => Ok(()), - false => { - Err(vec![VoidReturnTypeRequired::error_from_annotated_fn_decl( - pre_upgrade_fn_decl, - )]) - } - }, - match pre_upgrade_fn_decl.fn_decl.function.is_async { - true => Err(vec![AsyncNotAllowed::error_from_annotated_fn_decl( - pre_upgrade_fn_decl, - )]), - false => Ok(()), - }, - rust::generate(pre_upgrade_fn_decl), - ) - .collect_results()?; - - let guard_function_name = pre_upgrade_fn_decl.annotation.guard.clone(); - - Ok(PreUpgradeMethod { - body, - guard_function_name, - }) - }, - ) - .collect_results()? - .pop()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/pre_upgrade/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/pre_upgrade/rust.rs deleted file mode 100644 index a28b912aad..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/pre_upgrade/rust.rs +++ /dev/null @@ -1,31 +0,0 @@ -use crate::{ - canister_method::{rust, AnnotatedFnDecl}, - ts_ast::SourceMapped, - Error, -}; - -pub fn generate( - pre_upgrade_fn_decl: &SourceMapped, -) -> Result> { - let call_to_pre_upgrade_js_function = rust::generate_call_to_js_function(&pre_upgrade_fn_decl)?; - - let function_name = pre_upgrade_fn_decl.get_function_name(); - - Ok(quote::quote! { - unwrap_or_trap(|| { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = #function_name.to_string(); - }); - - #call_to_pre_upgrade_js_function - - Ok(()) - }) - }) - }) -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/mod.rs deleted file mode 100644 index 0445357efe..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod query; -mod shared; -mod update; - -pub use shared::body::generate as generate_body; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/query.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/query.rs deleted file mode 100644 index dd2ea78f2d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/query.rs +++ /dev/null @@ -1,22 +0,0 @@ -use cdk_framework::{ - act::node::canister_method::{CanisterMethodType, QueryMethod}, - traits::CollectIterResults, -}; - -use crate::{canister_method::AnnotatedFnDecl, ts_ast::SourceMapped, Error, TsAst}; - -impl TsAst { - pub fn build_query_methods( - &self, - annotated_fn_decls: &Vec>, - ) -> Result, Vec> { - Ok(annotated_fn_decls - .iter() - .filter(|fn_decl| fn_decl.is_canister_method_type(CanisterMethodType::Query)) - .map(|query_fn_decl| query_fn_decl.to_definition()) - .collect_results()? - .into_iter() - .map(|definition| QueryMethod { definition }) - .collect()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/body.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/body.rs deleted file mode 100644 index 2d8bc46ece..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/body.rs +++ /dev/null @@ -1,136 +0,0 @@ -use cdk_framework::traits::CollectResults; -use proc_macro2::TokenStream; -use quote::quote; -use swc_ecma_ast::{ - TsKeywordTypeKind::{TsNullKeyword, TsVoidKeyword}, - TsType, -}; - -use crate::{ - canister_method::{rust, AnnotatedFnDecl}, - traits::GetName, - ts_ast::SourceMapped, - Error, -}; - -pub fn generate( - fn_decl: &SourceMapped, -) -> Result> { - let (call_to_js_function, return_expression) = ( - rust::generate_call_to_js_function(fn_decl), - generate_return_expression(fn_decl).map_err(Error::into), - ) - .collect_results()?; - - let manual = fn_decl.is_manual(); - let function_name = fn_decl.get_function_name(); - - Ok(quote! { - unwrap_or_trap(|| { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - let uuid = uuid::Uuid::new_v4().to_string(); - - UUID_REF_CELL.with(|uuid_ref_cell| { - let mut uuid_mut = uuid_ref_cell.borrow_mut(); - - *uuid_mut = uuid.clone(); - }); - - METHOD_NAME_REF_CELL.with(|method_name_ref_cell| { - let mut method_name_mut = method_name_ref_cell.borrow_mut(); - - *method_name_mut = #function_name.to_string() - }); - - MANUAL_REF_CELL.with(|manual_ref_cell| { - let mut manual_mut = manual_ref_cell.borrow_mut(); - - *manual_mut = #manual; - }); - - #call_to_js_function - - let final_return_value = async_await_result_handler( - &mut boa_context, - &boa_return_value, - &uuid, - #function_name, - #manual - )?; - - #return_expression - }) - }) - }) -} - -/// Generates the return expression for a canister method body -/// -/// # Context -/// -/// * `final_return_value: boa_engine::JsValue` - The value to be returned -/// unless this is a ManualReply method. -/// * `boa_context: &mut boa_engine::Context` - The current boa context -fn generate_return_expression( - annotated_fn_decl: &SourceMapped, -) -> Result { - if annotated_fn_decl.is_manual() || annotated_fn_decl.is_promise() { - return Ok(quote! { - Ok(ic_cdk::api::call::ManualReply::empty()) - }); - } - - let return_type = annotated_fn_decl.get_return_ts_type()?; - - let null_and_void_handler = match return_type { - TsType::TsKeywordType(keyword) => match keyword.kind { - TsNullKeyword => check_for_not_null_return_value(), - TsVoidKeyword => check_for_not_void_return_value(), - _ => quote! {}, - }, - TsType::TsTypeRef(type_ref) => { - let sm_type_ref = annotated_fn_decl.spawn(type_ref); - if sm_type_ref - .alias_table - .void - .contains(&sm_type_ref.get_name()) - { - check_for_not_void_return_value() - } else if sm_type_ref - .alias_table - .null - .contains(&sm_type_ref.get_name()) - { - check_for_not_null_return_value() - } else { - quote! {} - } - } - _ => quote! {}, - }; - - Ok(quote! { - #null_and_void_handler - - Ok(final_return_value - .try_from_vm_value(&mut *boa_context)?) - }) -} - -fn check_for_not_null_return_value() -> TokenStream { - quote! { - if !final_return_value.is_null() { - return Err(RuntimeError::TypeError("Value is not of type 'null'".to_string())); - } - } -} - -fn check_for_not_void_return_value() -> TokenStream { - quote! { - if !final_return_value.is_undefined() { - return Err(RuntimeError::TypeError("Value is not of type 'void'".to_string())); - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/mod.rs deleted file mode 100644 index e2c8a0ebd7..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub(super) mod body; -mod to_definition; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/to_definition.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/to_definition.rs deleted file mode 100644 index 9e5fac4f01..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/shared/to_definition.rs +++ /dev/null @@ -1,62 +0,0 @@ -use cdk_framework::{ - act::node::{canister_method::QueryOrUpdateDefinition, CandidType, Param}, - traits::{CollectIterResults, CollectResults}, -}; -use swc_ecma_ast::TsType; - -use crate::{ - canister_method::{query_and_update, AnnotatedFnDecl}, - ts_ast::SourceMapped, - Error, -}; - -impl<'a> SourceMapped<'a, AnnotatedFnDecl> { - pub fn to_definition(&self) -> Result> { - let (body, params, return_type) = ( - query_and_update::generate_body(&self), - self.build_params(), - self.build_return_type(), - ) - .collect_results()?; - - let guard_function_name = self.annotation.guard.clone(); - let name = self.get_function_name(); - - Ok(QueryOrUpdateDefinition::new( - self.is_promise(), - self.is_manual(), - guard_function_name, - name, - params, - return_type, - body, - )) - } - - pub fn build_params(&self) -> Result, Vec> { - let (names, types) = - (self.get_param_name_idents(), self.build_param_types()).collect_results()?; - Ok(names - .iter() - .enumerate() - .map(|(i, name)| Param { - name: name.clone().to_string(), - candid_type: types[i].clone(), - }) - .collect()) - } - - // TODO why is this separated from get_name. It would be much simpler - // imho to get the names and the params all in the same pass - fn build_param_types(&self) -> Result, Vec> { - let ts_type_to_candid_type = |ts_type: &TsType| self.spawn(ts_type).to_candid_type(); - self.get_param_ts_types()? - .into_iter() - .map(ts_type_to_candid_type) - .collect_results() - } - - fn build_return_type(&self) -> Result> { - self.spawn(self.get_return_ts_type()?).to_candid_type() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/update.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/update.rs deleted file mode 100644 index 8d85e822a9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/query_and_update/update.rs +++ /dev/null @@ -1,24 +0,0 @@ -use cdk_framework::{ - act::node::canister_method::{CanisterMethodType, UpdateMethod}, - traits::CollectIterResults, -}; - -use crate::{canister_method::AnnotatedFnDecl, ts_ast::SourceMapped, Error, TsAst}; - -impl TsAst { - pub fn build_update_methods( - &self, - annotated_fn_decls: &Vec>, - ) -> Result, Vec> { - let update_methods = annotated_fn_decls - .iter() - .filter(|fn_decl| fn_decl.is_canister_method_type(CanisterMethodType::Update)) - .map(|update_fn_decl| update_fn_decl.to_definition()) - .collect_results()? - .into_iter() - .map(|definition| UpdateMethod { definition }) - .collect(); - - Ok(update_methods) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/canister_method/rust.rs deleted file mode 100644 index c786312ceb..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/canister_method/rust.rs +++ /dev/null @@ -1,82 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; -use quote::{format_ident, quote}; - -use crate::{canister_method::AnnotatedFnDecl, ts_ast::SourceMapped, Error}; - -pub fn maybe_generate_call_to_js_function( - annotated_fn_decl_option: &Option<&SourceMapped>, -) -> Result> { - if let Some(annotated_fn_decl) = &annotated_fn_decl_option { - generate_call_to_js_function(annotated_fn_decl) - } else { - Ok(quote!()) - } -} - -pub fn generate_call_to_js_function( - annotated_fn_decl: &SourceMapped, -) -> Result> { - let function_name = annotated_fn_decl.get_function_name(); - let param_name_idents: Vec = annotated_fn_decl - .build_params()? - .iter() - .map(|param| format_ident!("{}", param.get_prefixed_name())) - .collect(); - - Ok(quote! { - let exports_js_value = boa_context - .eval(boa_engine::Source::from_bytes("exports"))?; - let exports_js_object = exports_js_value - .as_object() - .ok_or_else(|| RuntimeError::TypeError("'exports' is not an object".to_string()))?; - - let function_js_value = exports_js_object.get(#function_name, &mut boa_context)?; - let function_js_object = function_js_value.as_object() - .ok_or_else(|| RuntimeError::ReferenceError(format!("{} is not defined", #function_name)))?; - - let boa_return_value = function_js_object - .call( - &boa_engine::JsValue::Null, - &[#(#param_name_idents.try_into_vm_value(&mut boa_context)?),*], - &mut boa_context - )?; - }) -} - -pub fn generate_register_process_object( - environment_variables: &Vec<(String, String)>, -) -> TokenStream { - let env_properties = environment_variables.iter().map(|environment_variable| { - let name = &environment_variable.0; - let value = &environment_variable.1; - - quote! { - .property( - #name, - #value, - boa_engine::property::Attribute::all() - ) - } - }); - - quote! { - let env = boa_engine::object::ObjectInitializer::new(&mut boa_context) - #(#env_properties)* - .build(); - - - let process = boa_engine::object::ObjectInitializer::new(&mut boa_context) - .property( - "env", - env, - boa_engine::property::Attribute::all() - ) - .build(); - - boa_context.register_global_property( - "process", - process, - boa_engine::property::Attribute::all(), - ); - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/compiler_output.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/compiler_output.rs deleted file mode 100644 index 7d3b681323..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/compiler_output.rs +++ /dev/null @@ -1,102 +0,0 @@ -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; -use std::fmt; - -use super::{Location, Suggestion}; - -#[derive(Clone, Debug, PartialEq)] -pub struct CompilerOutput { - pub title: String, - pub annotation: String, - pub suggestion: Option, - pub location: Location, -} - -impl CompilerOutput { - fn to_string(&self) -> String { - let error_snippet = Snippet { - title: Some(Annotation { - label: Some(&self.title), - id: None, - annotation_type: AnnotationType::Error, - }), - footer: vec![], - slices: vec![Slice { - source: &self.location.source, - line_start: self.location.line_number, - origin: Some(&self.location.origin), - fold: true, - annotations: vec![SourceAnnotation { - label: &self.annotation, - annotation_type: AnnotationType::Error, - range: self.location.range, - }], - }], - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - match &self.suggestion { - None => format!("{}", DisplayList::from(error_snippet)), - Some(suggestion) => { - let suggestion_slice = Slice { - source: &suggestion.source, - line_start: self.location.line_number, - origin: None, - fold: false, - annotations: vec![SourceAnnotation { - label: match &suggestion.annotation { - Some(annotation) => &annotation, - None => "", - }, - annotation_type: AnnotationType::Help, - range: suggestion.range, - }], - }; - let slices = match &suggestion.import_suggestion { - Some(import) => vec![ - Slice { - source: &import, - line_start: 1, - origin: None, - annotations: vec![], - fold: false, - }, - suggestion_slice, - ], - None => vec![suggestion_slice], - }; - - let suggestion_snippet = Snippet { - title: Some(Annotation { - label: Some(&suggestion.title), - id: None, - annotation_type: AnnotationType::Help, - }), - footer: vec![], - slices, - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - format!( - "{}\n{}", - DisplayList::from(error_snippet), - DisplayList::from(suggestion_snippet) - ) - } - } - } -} - -impl fmt::Display for CompilerOutput { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_string()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/argument_error.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/argument_error.rs deleted file mode 100644 index f60431eb1e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/argument_error.rs +++ /dev/null @@ -1,44 +0,0 @@ -use crate::{ - errors::{CompilerOutput, Location}, - Error, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ArgumentError { - message: String, - location: Location, -} - -impl ArgumentError { - pub fn new(message: String, location: Location) -> Self { - Self { message, location } - } - - pub fn error(message: String, location: Location) -> Error { - Error::ArgumentError(Self { message, location }) - } - - pub fn to_string(&self) -> String { - CompilerOutput { - title: format!("ArgumentError: {}", self.message), - location: self.location.clone(), - annotation: "".to_string(), - suggestion: None, - } - .to_string() - } -} - -impl std::error::Error for ArgumentError {} - -impl std::fmt::Display for ArgumentError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for Error { - fn from(error: ArgumentError) -> Self { - Self::ArgumentError(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/array_destructuring_in_params_not_supported.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/array_destructuring_in_params_not_supported.rs deleted file mode 100644 index 1ff7f75b90..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/array_destructuring_in_params_not_supported.rs +++ /dev/null @@ -1,103 +0,0 @@ -use swc_common::SourceMap; -use swc_ecma_ast::{ArrayPat, TsFnParam, TsFnType}; - -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -use super::GetDestructureRange; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ArrayDestructuringInParamsNotSupported { - location: Location, - suggestion_modifications: SuggestionModifications, -} - -impl ArrayDestructuringInParamsNotSupported { - pub fn from_ts_fn_param( - sm_ts_fn_param: &SourceMapped, - array_pat: &ArrayPat, - ) -> Self { - Self::build(sm_ts_fn_param.source_map, array_pat) - } - - pub fn from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - array_pat: &ArrayPat, - ) -> Self { - Self::build(annotated_fn_decl.source_map, array_pat) - } - - pub fn from_ts_fn_type(sm_ts_fn_type: &SourceMapped, array_pat: &ArrayPat) -> Self { - Self::build(sm_ts_fn_type.source_map, array_pat) - } - - fn build(source_map: &SourceMap, array_pat: &ArrayPat) -> Self { - let destructure_range = array_pat.get_destructure_range(source_map); - Self { - location: create_location(destructure_range, source_map, array_pat), - suggestion_modifications: create_suggestion_modification( - destructure_range, - source_map, - array_pat, - ), - } - } - - fn build_array_destructure_error_message(&self) -> CompilerOutput { - CompilerOutput { - title: "Array destructuring in parameters is unsupported at this time".to_string(), - location: self.location.clone(), - annotation: "Attempted to destructure here".to_string(), - suggestion: Some(Suggestion { - title: "Remove destructuring in favor of a concrete name".to_string(), - source: self.suggestion_modifications.0.clone(), - range: self.suggestion_modifications.1, - annotation: None, - import_suggestion: None, - }), - } - } -} - -impl std::error::Error for ArrayDestructuringInParamsNotSupported {} - -impl From for crate::Error { - fn from(error: ArrayDestructuringInParamsNotSupported) -> Self { - Self::ArrayDestructuringInParamsNotSupported(error) - } -} - -impl std::fmt::Display for ArrayDestructuringInParamsNotSupported { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_array_destructure_error_message()) - } -} - -fn create_suggestion_modification( - range: (usize, usize), - source_map: &SourceMap, - array_pat: &ArrayPat, -) -> SuggestionModifications { - let replacement_name = "myParam"; // TODO: Come up with a better name from the ts_type_ann - let source = - source_map.generate_source_with_range_replaced(array_pat.span, range, replacement_name); - let range = (range.0, range.0 + replacement_name.len()); - (source, range) -} - -fn create_location( - range: (usize, usize), - source_map: &SourceMap, - array_pat: &ArrayPat, -) -> Location { - Location { - origin: source_map.get_origin(array_pat.span), - line_number: source_map.get_line_number(array_pat.span), - source: source_map.get_source(array_pat.span), - range, - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/file_syntax_error.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/file_syntax_error.rs deleted file mode 100644 index 9e2bd1352e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/file_syntax_error.rs +++ /dev/null @@ -1,30 +0,0 @@ -use swc_ecma_parser::error::Error; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct FileSyntaxError { - ts_file_name: String, - error: String, -} - -impl FileSyntaxError { - pub fn from_file_name(file_name: &str, error: Error) -> Self { - Self { - ts_file_name: file_name.to_string(), - error: error.kind().msg().to_string(), - } - } -} - -impl std::error::Error for FileSyntaxError {} - -impl From for crate::Error { - fn from(error: FileSyntaxError) -> Self { - Self::FileSyntaxError(error) - } -} - -impl std::fmt::Display for FileSyntaxError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}: Syntax Error: {}", self.ts_file_name, self.error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/function_params_must_have_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/function_params_must_have_type.rs deleted file mode 100644 index 1b38349841..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/function_params_must_have_type.rs +++ /dev/null @@ -1,36 +0,0 @@ -use swc_ecma_ast::{TsFnParam, TsFnType}; - -use crate::{errors::Location, traits::GetSourceInfo, ts_ast::SourceMapped}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct FunctionParamsMustHaveType { - location: Location, -} - -impl FunctionParamsMustHaveType { - pub fn from_ts_fn_type(sm_ts_fn_type: &SourceMapped) -> Self { - Self { - location: sm_ts_fn_type.get_location(), - } - } - - pub fn from_ts_fn_param(sm_ts_fn_param: &SourceMapped) -> Self { - Self { - location: sm_ts_fn_param.get_location(), - } - } -} - -impl std::error::Error for FunctionParamsMustHaveType {} - -impl From for crate::Error { - fn from(error: FunctionParamsMustHaveType) -> Self { - Self::FunctionParamsMustHaveType(error) - } -} - -impl std::fmt::Display for FunctionParamsMustHaveType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Function parameters must have a type") - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/guard_function_not_found.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/guard_function_not_found.rs deleted file mode 100644 index 1b1f1aef4c..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/guard_function_not_found.rs +++ /dev/null @@ -1,22 +0,0 @@ -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct GuardFunctionNotFound { - pub name: String, -} - -impl std::error::Error for GuardFunctionNotFound {} - -impl std::fmt::Display for GuardFunctionNotFound { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "The guard function {} is used, but never defined.", - self.name - ) - } -} - -impl From for crate::Error { - fn from(error: GuardFunctionNotFound) -> Self { - Self::GuardFunctionNotFound(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/internal_error.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/internal_error.rs deleted file mode 100644 index 68e262bf75..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/internal_error.rs +++ /dev/null @@ -1,28 +0,0 @@ -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct InternalError { - backtrace: String, -} - -impl std::fmt::Display for InternalError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "InternalError: Oops! Looks like we introduced a bug while refactoring 🤦\nPlease open a ticket at https://github.com/demergent-labs/azle/issues/new\n{}", self.backtrace - ) - } -} - -impl InternalError { - pub fn new() -> Self { - let backtrace = std::backtrace::Backtrace::force_capture().to_string(); - Self { backtrace } - } -} - -impl std::error::Error for InternalError {} - -impl From for crate::Error { - fn from(error: InternalError) -> Self { - Self::InternalError(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/mod.rs deleted file mode 100644 index 8b7f70c77e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/mod.rs +++ /dev/null @@ -1,82 +0,0 @@ -mod argument_error; -mod array_destructuring_in_params_not_supported; -mod file_syntax_error; -mod function_params_must_have_type; -mod guard_function_not_found; -mod internal_error; -mod multiple_canister_method_definitions; -mod multiple_guard_function_definitions; -mod multiple_type_definitions; -mod object_destructuring_not_supported; -mod rest_parameters_not_supported; -mod syntax_error; -mod type_error; -mod type_not_found; -mod unable_to_load_file; -mod unable_to_load_plugin; -mod unable_to_parse_plugin; - -use swc_common::SourceMap; -use swc_ecma_ast::{ArrayPat, ObjectPat, RestPat}; - -use crate::{ - traits::{GetDestructureRange, GetSourceFileInfo}, - ts_ast::source_map::Range, -}; - -pub use argument_error::ArgumentError; -pub use array_destructuring_in_params_not_supported::ArrayDestructuringInParamsNotSupported; -pub use file_syntax_error::FileSyntaxError; -pub use function_params_must_have_type::FunctionParamsMustHaveType; -pub use guard_function_not_found::GuardFunctionNotFound; -pub use internal_error::InternalError; -pub use multiple_canister_method_definitions::MultipleCanisterMethodDefinitions; -pub use multiple_guard_function_definitions::MultipleGuardFunctionDefinitions; -pub use multiple_type_definitions::MultipleTypeDefinitions; -pub use object_destructuring_not_supported::ObjectDestructuringNotSupported; -pub use rest_parameters_not_supported::RestParametersNotSupported; -pub use syntax_error::SyntaxError; -pub use type_error::TypeError; -pub use type_not_found::TypeNotFound; -pub use unable_to_load_file::UnableToLoadFile; -pub use unable_to_load_plugin::UnableToLoadPlugin; -pub use unable_to_parse_plugin::UnableToParsePlugin; - -impl GetDestructureRange for ArrayPat { - fn get_destructure_range(&self, source_map: &SourceMap) -> Range { - let full_param_span_range = source_map.get_range(self.span); - let ts_type_ann = match &self.type_ann { - Some(type_ann) => type_ann, - None => return full_param_span_range, - }; - let type_ann_range = source_map.get_range(ts_type_ann.span); - let range_without_type_annotation = (full_param_span_range.0, type_ann_range.0); - range_without_type_annotation - } -} - -impl GetDestructureRange for RestPat { - fn get_destructure_range(&self, source_map: &SourceMap) -> Range { - let full_param_span_range = source_map.get_range(self.span); - let ts_type_ann = match &self.type_ann { - Some(type_ann) => type_ann, - None => return full_param_span_range, - }; - let type_ann_range = source_map.get_range(ts_type_ann.span); - let range_without_type_annotation = (full_param_span_range.0, type_ann_range.0); - range_without_type_annotation - } -} - -impl GetDestructureRange for ObjectPat { - fn get_destructure_range(&self, source_map: &SourceMap) -> Range { - let full_param_span_range = source_map.get_range(self.span); - let ts_type_ann = match &self.type_ann { - Some(ts_type_ann) => ts_type_ann, - None => return full_param_span_range, - }; - let type_ann_range = source_map.get_range(ts_type_ann.span); - let range_without_type_annotation = (full_param_span_range.0, type_ann_range.0); - range_without_type_annotation - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_canister_method_definitions.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_canister_method_definitions.rs deleted file mode 100644 index 73e5c795f6..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_canister_method_definitions.rs +++ /dev/null @@ -1,22 +0,0 @@ -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MultipleCanisterMethodDefinitions { - pub name: String, -} - -impl std::error::Error for MultipleCanisterMethodDefinitions {} - -impl std::fmt::Display for MultipleCanisterMethodDefinitions { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Conflicting canister method definitions found for {}.", - self.name - ) - } -} - -impl From for crate::Error { - fn from(error: MultipleCanisterMethodDefinitions) -> Self { - Self::MultipleCanisterMethodDefinitions(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_guard_function_definitions.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_guard_function_definitions.rs deleted file mode 100644 index 91f199a1ed..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_guard_function_definitions.rs +++ /dev/null @@ -1,22 +0,0 @@ -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MultipleGuardFunctionDefinitions { - pub name: String, -} - -impl std::error::Error for MultipleGuardFunctionDefinitions {} - -impl std::fmt::Display for MultipleGuardFunctionDefinitions { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Conflicting guard function definitions found for {}.", - self.name - ) - } -} - -impl From for crate::Error { - fn from(error: MultipleGuardFunctionDefinitions) -> Self { - Self::MultipleGuardFunctionDefinitions(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_type_definitions.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_type_definitions.rs deleted file mode 100644 index 7255e353d9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/multiple_type_definitions.rs +++ /dev/null @@ -1,18 +0,0 @@ -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MultipleTypeDefinitions { - pub name: String, -} - -impl std::error::Error for MultipleTypeDefinitions {} - -impl std::fmt::Display for MultipleTypeDefinitions { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Conflicting type definitions found for {}.", self.name) - } -} - -impl From for crate::Error { - fn from(error: MultipleTypeDefinitions) -> Self { - Self::MultipleTypeDefinitions(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/object_destructuring_not_supported.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/object_destructuring_not_supported.rs deleted file mode 100644 index 52eb7c102f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/object_destructuring_not_supported.rs +++ /dev/null @@ -1,103 +0,0 @@ -use swc_common::SourceMap; -use swc_ecma_ast::{ObjectPat, TsFnParam, TsFnType}; - -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -use super::GetDestructureRange; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ObjectDestructuringNotSupported { - location: Location, - suggestion_modifications: SuggestionModifications, -} - -impl ObjectDestructuringNotSupported { - pub fn from_ts_fn_param( - sm_ts_fn_param: &SourceMapped, - object_pat: &ObjectPat, - ) -> Self { - Self::build(sm_ts_fn_param.source_map, object_pat) - } - - pub fn from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - object_pat: &ObjectPat, - ) -> Self { - Self::build(annotated_fn_decl.source_map, object_pat) - } - - pub fn from_ts_fn_type(sm_ts_fn_type: &SourceMapped, object_pat: &ObjectPat) -> Self { - Self::build(sm_ts_fn_type.source_map, object_pat) - } - - fn build(source_map: &SourceMap, object_pat: &ObjectPat) -> Self { - let destructure_range = object_pat.get_destructure_range(source_map); - Self { - location: create_location(destructure_range, source_map, object_pat), - suggestion_modifications: create_suggestion_modification( - destructure_range, - source_map, - object_pat, - ), - } - } - - fn build_object_destructure_error_msg(&self) -> CompilerOutput { - CompilerOutput { - title: "Object destructuring in parameters is unsupported at this time".to_string(), - location: self.location.clone(), - annotation: "Attempted to destructure here".to_string(), - suggestion: Some(Suggestion { - title: "Remove destructuring in favor of a concrete name".to_string(), - annotation: None, - import_suggestion: None, - source: self.suggestion_modifications.0.clone(), - range: self.suggestion_modifications.1.clone(), - }), - } - } -} - -impl std::error::Error for ObjectDestructuringNotSupported {} - -impl From for crate::Error { - fn from(error: ObjectDestructuringNotSupported) -> Self { - Self::ObjectDestructuringNotSupported(error) - } -} - -impl std::fmt::Display for ObjectDestructuringNotSupported { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_object_destructure_error_msg()) - } -} - -fn create_suggestion_modification( - range: (usize, usize), - source_map: &SourceMap, - object_pat: &ObjectPat, -) -> SuggestionModifications { - let replacement_name = "myParam"; // TODO: Come up with a better name from the ts_type_ann - let source = - source_map.generate_source_with_range_replaced(object_pat.span, range, replacement_name); - let range = (range.0, range.0 + replacement_name.len()); - (source, range) -} - -fn create_location( - range: (usize, usize), - source_map: &SourceMap, - object_pat: &ObjectPat, -) -> Location { - Location { - origin: source_map.get_origin(object_pat.span), - line_number: source_map.get_line_number(object_pat.span), - source: source_map.get_source(object_pat.span), - range, - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/rest_parameters_not_supported.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/rest_parameters_not_supported.rs deleted file mode 100644 index 680618ff57..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/rest_parameters_not_supported.rs +++ /dev/null @@ -1,110 +0,0 @@ -use swc_common::SourceMap; -use swc_ecma_ast::{RestPat, TsFnParam, TsFnType}; - -use crate::{ - canister_method::AnnotatedFnDecl, - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::GetSourceFileInfo, - ts_ast::SourceMapped, -}; - -use super::GetDestructureRange; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RestParametersNotSupported { - message: String, - location: Location, - suggestion_modifications: SuggestionModifications, -} - -impl RestParametersNotSupported { - pub fn from_ts_fn_param(sm_ts_fn_param: &SourceMapped, rest_pat: &RestPat) -> Self { - Self::build( - "Rest parameters are not supported at this time", - sm_ts_fn_param.source_map, - rest_pat, - ) - } - - pub fn from_annotated_fn_decl( - annotated_fn_decl: &SourceMapped, - rest_pat: &RestPat, - ) -> Self { - Self::build( - "Rest parameters are not supported in canister method signatures", - annotated_fn_decl.source_map, - rest_pat, - ) - } - - pub fn from_ts_fn_type(sm_ts_fn_type: &SourceMapped, rest_pat: &RestPat) -> Self { - Self::build( - "Rest parameters are not supported at this time", - sm_ts_fn_type.source_map, - rest_pat, - ) - } - - fn build(message: &str, source_map: &SourceMap, rest_pat: &RestPat) -> Self { - let destructure_range = rest_pat.get_destructure_range(source_map); - Self { - message: message.to_string(), - location: create_location(destructure_range, source_map, rest_pat), - suggestion_modifications: create_suggestion_modification( - destructure_range, - source_map, - rest_pat, - ), - } - } - - fn build_rest_param_error_msg(&self) -> CompilerOutput { - CompilerOutput { - title: self.message.clone(), - location: self.location.clone(), - annotation: "Attempted parameter spread here".to_string(), - suggestion: Some(Suggestion { - title: "Specify each parameter individually with a concrete type".to_string(), - annotation: None, - import_suggestion: None, - source: self.suggestion_modifications.0.clone(), - range: self.suggestion_modifications.1, - }), - } - } -} - -impl std::error::Error for RestParametersNotSupported {} - -impl From for crate::Error { - fn from(error: RestParametersNotSupported) -> Self { - Self::RestParametersNotSupported(error) - } -} - -impl std::fmt::Display for RestParametersNotSupported { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.build_rest_param_error_msg()) - } -} - -fn create_suggestion_modification( - range: (usize, usize), - source_map: &SourceMap, - rest_pat: &RestPat, -) -> SuggestionModifications { - let replacement_name = "myParam"; // TODO: Come up with a better name from the ts_type_ann - let source = - source_map.generate_source_with_range_replaced(rest_pat.span, range, replacement_name); - let range = (range.0, range.0 + replacement_name.len()); - (source, range) -} - -fn create_location(range: (usize, usize), source_map: &SourceMap, rest_pat: &RestPat) -> Location { - Location { - origin: source_map.get_origin(rest_pat.span), - line_number: source_map.get_line_number(rest_pat.span), - source: source_map.get_source(rest_pat.span), - range, - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/syntax_error.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/syntax_error.rs deleted file mode 100644 index 08864263e9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/syntax_error.rs +++ /dev/null @@ -1,44 +0,0 @@ -use crate::{ - errors::{CompilerOutput, Location}, - Error, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SyntaxError { - message: String, - location: Location, -} - -impl SyntaxError { - pub fn new(message: String, location: Location) -> Self { - Self { message, location } - } - - pub fn error(message: String, location: Location) -> Error { - Error::SyntaxError(Self { message, location }) - } - - pub fn to_string(&self) -> String { - CompilerOutput { - title: format!("SyntaxError: {}", self.message), - location: self.location.clone(), - annotation: "".to_string(), - suggestion: None, - } - .to_string() - } -} - -impl std::error::Error for SyntaxError {} - -impl std::fmt::Display for SyntaxError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for Error { - fn from(error: SyntaxError) -> Self { - Self::SyntaxError(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/type_error.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/type_error.rs deleted file mode 100644 index 0f7260e143..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/type_error.rs +++ /dev/null @@ -1,44 +0,0 @@ -use crate::{ - errors::{CompilerOutput, Location}, - Error, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct TypeError { - message: String, - location: Location, -} - -impl TypeError { - pub fn new(message: String, location: Location) -> Self { - TypeError { message, location } - } - - pub fn error(message: String, location: Location) -> Error { - Error::TypeError(Self { message, location }) - } - - pub fn to_string(&self) -> String { - CompilerOutput { - title: format!("TypeError: {}", self.message), - location: self.location.clone(), - annotation: "".to_string(), - suggestion: None, - } - .to_string() - } -} - -impl std::error::Error for TypeError {} - -impl std::fmt::Display for TypeError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.to_string()) - } -} - -impl From for Error { - fn from(error: TypeError) -> Self { - Self::TypeError(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/type_not_found.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/type_not_found.rs deleted file mode 100644 index 8f7774125f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/type_not_found.rs +++ /dev/null @@ -1,18 +0,0 @@ -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct TypeNotFound { - pub name: String, -} - -impl std::error::Error for TypeNotFound {} - -impl std::fmt::Display for TypeNotFound { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "The type {} is used, but never defined.", self.name) - } -} - -impl From for crate::Error { - fn from(error: TypeNotFound) -> Self { - Self::TypeNotFound(error) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_load_file.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_load_file.rs deleted file mode 100644 index 7772778a50..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_load_file.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::io::Error; - -// TODO explore getting rid of the need for clone here so we can have the actual error -#[derive(Debug, Clone, PartialEq)] -pub struct UnableToLoadFile { - ts_file_name: String, - error: String, -} - -impl UnableToLoadFile { - pub fn from_error(error: Error, ts_file_name: &str) -> Self { - Self { - ts_file_name: ts_file_name.to_string(), - error: error.to_string(), - } - } -} - -impl std::error::Error for UnableToLoadFile {} - -impl From for crate::Error { - fn from(error: UnableToLoadFile) -> Self { - Self::UnableToLoadFile(error) - } -} - -impl std::fmt::Display for UnableToLoadFile { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Error: Unable to load file {}\n{}", - self.ts_file_name, self.error - ) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_load_plugin.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_load_plugin.rs deleted file mode 100644 index 0dd36ed9a9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_load_plugin.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::{io::Error, path::PathBuf}; - -#[derive(Debug, Clone, PartialEq)] -pub struct UnableToLoadPlugin { - plugin_file_name: String, - error: String, -} - -impl UnableToLoadPlugin { - pub fn from_error(error: Error, plugin_file_buf: &PathBuf) -> Self { - Self { - plugin_file_name: plugin_file_buf.to_string_lossy().to_string(), - error: error.to_string(), - } - } -} - -impl std::error::Error for UnableToLoadPlugin {} - -impl From for crate::Error { - fn from(error: UnableToLoadPlugin) -> Self { - Self::UnableToLoadPlugin(error) - } -} - -impl std::fmt::Display for UnableToLoadPlugin { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Error: Unable to load plugin file {}\n{}", - self.plugin_file_name, self.error - ) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_parse_plugin.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_parse_plugin.rs deleted file mode 100644 index 42c4e2fedb..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/errors/unable_to_parse_plugin.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::path::PathBuf; -use syn::Error; - -#[derive(Debug, Clone, PartialEq)] -pub struct UnableToParsePlugin { - plugin_file_name: String, - error: String, -} - -impl UnableToParsePlugin { - pub fn from_error(error: Error, plugin_file_buf: &PathBuf) -> Self { - Self { - plugin_file_name: plugin_file_buf.to_string_lossy().to_string(), - error: error.to_string(), - } - } -} - -impl std::error::Error for UnableToParsePlugin {} - -impl From for crate::Error { - fn from(error: UnableToParsePlugin) -> Self { - Self::UnableToParsePlugin(error) - } -} - -impl std::fmt::Display for UnableToParsePlugin { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Error: Unable to parse plugin file {}\n{}", - self.plugin_file_name, self.error - ) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/location.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/location.rs deleted file mode 100644 index 9558460bbc..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/location.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct Location { - pub origin: String, - pub line_number: usize, - pub source: String, - pub range: (usize, usize), -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/mod.rs deleted file mode 100644 index cc3d1b9c52..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/mod.rs +++ /dev/null @@ -1,209 +0,0 @@ -use std::fmt::Debug; - -use cdk_framework::act::abstract_canister_tree::Error as CdkfError; - -mod compiler_output; -mod location; -mod suggestion; - -pub mod errors; - -use self::errors::{ - ArrayDestructuringInParamsNotSupported, FileSyntaxError, FunctionParamsMustHaveType, - MultipleCanisterMethodDefinitions, MultipleGuardFunctionDefinitions, MultipleTypeDefinitions, - ObjectDestructuringNotSupported, RestParametersNotSupported, UnableToLoadFile, - UnableToLoadPlugin, UnableToParsePlugin, -}; -pub use self::{ - compiler_output::CompilerOutput, - errors::{ - ArgumentError, GuardFunctionNotFound, InternalError, SyntaxError, TypeError, TypeNotFound, - }, - location::Location, - suggestion::Suggestion, -}; -use crate::{ - body::stable_b_tree_map::new_expr::errors::{ - ArgSpread, IncorrectNumberOfArgs, IncorrectTypeArgs, InvalidArg, MissingArgs, - MissingSbtmTypeArguments, - }, - candid_type::{ - errors::WrongEnclosedType, - primitive::errors::UnsupportedType, - record::errors::RecordPropertySignature, - service::method::errors::{ - ComputedPropertyNotAllowed, InvalidClassMember, InvalidDecorator, InvalidReturnType, - MissingCallResultAnnotation, MissingDecorator, MissingTypeAnnotation, - MissingTypeArguments, NotExactlyOneDecorator, TooManyReturnTypes, - }, - type_ref::errors::WrongNumberOfParams, - variant::errors::VariantPropertySignature, - }, - canister_method::{ - annotated_fn_decl::errors::{MissingReturnType, ParamDefaultValue, UntypedParam}, - errors::{ - AsyncNotAllowed, DuplicateSystemMethod, ExtraneousCanisterMethodAnnotation, - MissingReturnTypeAnnotation, VoidReturnTypeRequired, - }, - }, - ts_ast::{ - ts_type::{ - errors::{UnexpectedTsTupleTypes, UnexpectedTsType, UnexpectedTsTypeLiteral}, - ts_fn_or_constructor_type::ts_fn_type::errors::NotEnclosedInFunc, - }, - ts_type_element::ts_property_signature::errors::{NoTypeAnnotation, UnsupportedMemberName}, - }, -}; - -use crate::canister_method::annotated_fn_decl::errors::InvalidParams; - -pub type SuggestionModifications = (String, (usize, usize)); - -#[derive(Debug, Clone, PartialEq)] -pub enum Error { - TypeNotFound(TypeNotFound), - GuardFunctionNotFound(GuardFunctionNotFound), - DuplicateSystemMethodImplementation(DuplicateSystemMethod), - ExtraneousCanisterMethodAnnotation(ExtraneousCanisterMethodAnnotation), - MissingReturnTypeAnnotation(MissingReturnTypeAnnotation), - InternalError(InternalError), - ArgumentError(ArgumentError), - TypeError(TypeError), - SyntaxError(SyntaxError), - VoidReturnTypeRequired(VoidReturnTypeRequired), - AsyncNotAllowed(AsyncNotAllowed), - ArrayDestructuringInParamsNotSupported(ArrayDestructuringInParamsNotSupported), - ComputedPropertyNotAllowed(ComputedPropertyNotAllowed), - FileSyntaxError(FileSyntaxError), - FunctionParamsMustHaveType(FunctionParamsMustHaveType), - InvalidClassMember(InvalidClassMember), - InvalidDecorator(InvalidDecorator), - InvalidParams(InvalidParams), - InvalidReturnType(InvalidReturnType), - MissingCallResultAnnotation(MissingCallResultAnnotation), - MissingDecorator(MissingDecorator), - MissingReturnType(MissingReturnType), - MissingTypeAnnotation(MissingTypeAnnotation), - MissingTypeArgument(MissingTypeArguments), - MissingSbtmTypeArgument(MissingSbtmTypeArguments), - NotEnclosedInFunc(NotEnclosedInFunc), - NotExactlyOneDecorator(NotExactlyOneDecorator), - NoTypeAnnotation(NoTypeAnnotation), - ObjectDestructuringNotSupported(ObjectDestructuringNotSupported), - ParamDefaultValue(ParamDefaultValue), - RecordPropertySignature(RecordPropertySignature), - RestParametersNotSupported(RestParametersNotSupported), - TooManyReturnTypes(TooManyReturnTypes), - UnableToLoadFile(UnableToLoadFile), - UnableToLoadPlugin(UnableToLoadPlugin), - UnableToParsePlugin(UnableToParsePlugin), - UnexpectedTsTupleType(UnexpectedTsTupleTypes), - UnexpectedTsType(UnexpectedTsType), - UnexpectedTsTypeLiteral(UnexpectedTsTypeLiteral), - UnsupportedType(UnsupportedType), - UntypedParam(UntypedParam), - VariantPropertySignature(VariantPropertySignature), - WrongEnclosedType(WrongEnclosedType), - WrongNumberOfParams(WrongNumberOfParams), - ArgSpread(ArgSpread), - IncorrectNumberOfArgs(IncorrectNumberOfArgs), - IncorrectTypeArgs(IncorrectTypeArgs), - InvalidArg(InvalidArg), - UnsupportedMemberName(UnsupportedMemberName), - MissingArgs(MissingArgs), - MultipleTypeDefinitions(MultipleTypeDefinitions), - MultipleGuardFunctionDefinitions(MultipleGuardFunctionDefinitions), - MultipleCanisterMethodDefinitions(MultipleCanisterMethodDefinitions), -} - -impl std::error::Error for Error {} - -impl Error { - fn get_error<'a>(&'a self) -> &'a dyn std::error::Error { - match self { - Self::TypeNotFound(e) => e, - Self::GuardFunctionNotFound(e) => e, - Self::DuplicateSystemMethodImplementation(e) => e, - Self::ExtraneousCanisterMethodAnnotation(e) => e, - Self::MissingReturnTypeAnnotation(e) => e, - Self::InternalError(e) => e, - Self::ArgumentError(e) => e, - Self::TypeError(e) => e, - Self::SyntaxError(e) => e, - Self::VoidReturnTypeRequired(e) => e, - Self::AsyncNotAllowed(e) => e, - Self::ArrayDestructuringInParamsNotSupported(e) => e, - Self::ComputedPropertyNotAllowed(e) => e, - Self::FileSyntaxError(e) => e, - Self::FunctionParamsMustHaveType(e) => e, - Self::InvalidClassMember(e) => e, - Self::InvalidDecorator(e) => e, - Self::InvalidParams(e) => e, - Self::InvalidReturnType(e) => e, - Self::MissingCallResultAnnotation(e) => e, - Self::MissingDecorator(e) => e, - Self::MissingReturnType(e) => e, - Self::MissingTypeAnnotation(e) => e, - Self::MissingTypeArgument(e) => e, - Self::NotEnclosedInFunc(e) => e, - Self::NotExactlyOneDecorator(e) => e, - Self::NoTypeAnnotation(e) => e, - Self::ObjectDestructuringNotSupported(e) => e, - Self::ParamDefaultValue(e) => e, - Self::RecordPropertySignature(e) => e, - Self::RestParametersNotSupported(e) => e, - Self::TooManyReturnTypes(e) => e, - Self::UnableToLoadFile(e) => e, - Self::UnexpectedTsTupleType(e) => e, - Self::UnexpectedTsType(e) => e, - Self::UnexpectedTsTypeLiteral(e) => e, - Self::UnsupportedType(e) => e, - Self::UntypedParam(e) => e, - Self::VariantPropertySignature(e) => e, - Self::WrongEnclosedType(e) => e, - Self::WrongNumberOfParams(e) => e, - Self::ArgSpread(e) => e, - Self::IncorrectNumberOfArgs(e) => e, - Self::IncorrectTypeArgs(e) => e, - Self::InvalidArg(e) => e, - Self::MissingArgs(e) => e, - Self::UnsupportedMemberName(e) => e, - Self::UnableToParsePlugin(e) => e, - Self::UnableToLoadPlugin(e) => e, - Self::MissingSbtmTypeArgument(e) => e, - Self::MultipleTypeDefinitions(e) => e, - Self::MultipleGuardFunctionDefinitions(e) => e, - Self::MultipleCanisterMethodDefinitions(e) => e, - } - } -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Display::fmt(&self.get_error(), f) - } -} - -impl From for crate::Error { - fn from(value: CdkfError) -> Self { - match value { - CdkfError::TypeNotFound(name) => TypeNotFound { name }.into(), - CdkfError::GuardFunctionNotFound(name) => GuardFunctionNotFound { name }.into(), - CdkfError::MultipleTypeDefinitions(name) => { - MultipleCanisterMethodDefinitions { name }.into() - } - CdkfError::MultipleGuardFunctionDefinitions(name) => { - MultipleGuardFunctionDefinitions { name }.into() - } - CdkfError::MultipleCanisterMethodDefinitions(name) => { - MultipleCanisterMethodDefinitions { name }.into() - } - } - } -} - -impl From for Vec { - fn from(value: Error) -> Self { - vec![value] - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/errors/suggestion.rs b/src/compiler/typescript_to_rust/azle_generate/src/errors/suggestion.rs deleted file mode 100644 index 779a00e81f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/errors/suggestion.rs +++ /dev/null @@ -1,8 +0,0 @@ -#[derive(Clone, Debug, PartialEq)] -pub struct Suggestion { - pub title: String, - pub source: String, - pub range: (usize, usize), - pub annotation: Option, - pub import_suggestion: Option, -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/guard_function/get_fn_decls.rs b/src/compiler/typescript_to_rust/azle_generate/src/guard_function/get_fn_decls.rs deleted file mode 100644 index 79c59583d9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/guard_function/get_fn_decls.rs +++ /dev/null @@ -1,66 +0,0 @@ -use std::ops::Deref; -use swc_ecma_ast::{Decl, FnDecl, Module, ModuleDecl, ModuleItem, Stmt}; - -use crate::ts_ast::{Program, SourceMapped}; - -pub trait GetProgramFnDecls { - fn get_fn_decls(&self) -> Vec>; -} - -impl GetProgramFnDecls for Vec { - fn get_fn_decls(&self) -> Vec> { - self.iter() - .flat_map(|azle_program| azle_program.get_fn_decls()) - .collect() - } -} - -impl Program { - fn get_fn_decls(&self) -> Vec> { - match self.deref() { - swc_ecma_ast::Program::Module(module) => module.get_fn_decls(&self), - swc_ecma_ast::Program::Script(_) => vec![], - } - } -} - -pub trait GetModuleFnDecls { - fn get_fn_decls<'a>(&'a self, parent: &'a Program) -> Vec>; -} - -impl GetModuleFnDecls for Module { - fn get_fn_decls<'a>(&'a self, parent: &'a Program) -> Vec> { - self.body - .iter() - .filter_map(|module_item| module_item.as_decl()) - .filter_map(|decl| decl.as_fn_decl()) - .filter_map(|fn_decl| { - Some(SourceMapped::new( - fn_decl, - &parent.source_map, - &parent.alias_table, - &parent.alias_list, - )) - }) - .collect() - } -} - -trait AsDecl { - fn as_decl(&self) -> Option<&Decl>; -} - -impl AsDecl for ModuleItem { - fn as_decl(&self) -> Option<&Decl> { - match self { - ModuleItem::ModuleDecl(decl) => match decl { - ModuleDecl::ExportDecl(export_decl) => Some(&export_decl.decl), - _ => None, - }, - ModuleItem::Stmt(stmt) => match stmt { - Stmt::Decl(decl) => Some(decl), - _ => None, - }, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/guard_function/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/guard_function/mod.rs deleted file mode 100644 index ebdcbb78fd..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/guard_function/mod.rs +++ /dev/null @@ -1,42 +0,0 @@ -use cdk_framework::act::node::GuardFunction; -use std::ops::Deref; -use swc_ecma_ast::{FnDecl, TsEntityName}; - -use crate::{traits::GetName, ts_ast::SourceMapped, TsAst}; -use get_fn_decls::GetProgramFnDecls; - -mod get_fn_decls; -mod rust; - -impl TsAst { - pub fn build_guard_functions(&self) -> Vec { - self.programs - .get_fn_decls() - .iter() - .filter(|fn_decl| fn_decl.has_guard_result_return_type()) - .map(|fn_decl| { - let name = fn_decl.ident.get_name(); - let body = rust::generate(&name); - - GuardFunction { name, body } - }) - .collect() - } -} - -impl SourceMapped<'_, FnDecl> { - pub fn has_guard_result_return_type(&self) -> bool { - self.function - .return_type - .as_ref() - .and_then(|ts_type_ann| ts_type_ann.type_ann.deref().as_ts_type_ref()) - .map(|ts_type_ref| { - let name = match &ts_type_ref.type_name { - TsEntityName::TsQualifiedName(qualified_name) => qualified_name.get_name(), - TsEntityName::Ident(ident) => ident.get_name(), - }; - self.alias_table.guard_result.contains(&name) - }) - .unwrap_or(false) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/guard_function/rust.rs b/src/compiler/typescript_to_rust/azle_generate/src/guard_function/rust.rs deleted file mode 100644 index a7355cd3bb..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/guard_function/rust.rs +++ /dev/null @@ -1,21 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; - -pub fn generate(function_name: &String) -> TokenStream { - let function_call = format!("{function_name}()"); - quote! { - BOA_CONTEXT_REF_CELL.with(|boa_context_ref_cell| { - let mut boa_context = boa_context_ref_cell.borrow_mut(); - - boa_context - .eval(boa_engine::Source::from_bytes(#function_call)) - .map_err(|js_error: boa_engine::JsError| { - format!("\nUncaught {}", js_error.to_std_string(&mut *boa_context)) - })? - .try_from_vm_value(&mut *boa_context) - .map_err(|js_error: boa_engine::JsError| { - format!("\nUncaught {}", js_error.to_std_string(&mut *boa_context)) - })? - }) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/header/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/header/mod.rs deleted file mode 100644 index b0a1dccafb..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/header/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -mod ref_cells; -mod use_statements; - -pub fn generate(main_js: &str) -> proc_macro2::TokenStream { - let use_statements = use_statements::generate(); - let ref_cells = ref_cells::generate(); - - quote::quote! { - // This code is automatically generated by Azle - - #![allow(warnings, unused)] - - #use_statements - - #ref_cells - - static MAIN_JS: &'static str = #main_js; - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/header/ref_cells.rs b/src/compiler/typescript_to_rust/azle_generate/src/header/ref_cells.rs deleted file mode 100644 index f191471b3b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/header/ref_cells.rs +++ /dev/null @@ -1,40 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - thread_local! { - // TODO all of this is for when we embrace native async functions - // static SIMPLE_JOB_QUEUE_REF_CELL: std::cell::RefCell = std::cell::RefCell::new(boa_engine::job::SimpleJobQueue::new()); - // let queue: Rc = Rc::new(queue); - // let context = Context::builder().job_queue(queue).build().unwrap(); - // static BOA_CONTEXT_REF_CELL: std::cell::RefCell> = - // std::cell::RefCell::new(boa_engine::Context::default()); - // let job_queue: &dyn boa_engine::job::JobQueue = &boa_engine::job::SimpleJobQueue::new(); - // let job_queue: &dyn boa_engine::job::JobQueue = SIMPLE_JOB_QUEUE_REF_CELL.with(|jq| jq.borrow()); - // let job_queue: &dyn boa_engine::job::JobQueue = &SIMPLE_JOB_QUEUE_REF_CELL.with(|jq| *jq.borrow()); - - static BOA_CONTEXT_REF_CELL: std::cell::RefCell> = { - let mut context = boa_engine::context::ContextBuilder::new() - .build() - .unwrap_or_else(|err| ic_cdk::trap(err.to_string().as_str())); - - context - .runtime_limits_mut() - .set_loop_iteration_limit(u64::MAX); - - context - .runtime_limits_mut() - .set_recursion_limit(usize::MAX); - - std::cell::RefCell::new(context) - }; - static PROMISE_MAP_REF_CELL: std::cell::RefCell< - std::collections::HashMap, - > = std::cell::RefCell::new(std::collections::HashMap::new()); - static UUID_REF_CELL: std::cell::RefCell = - std::cell::RefCell::new("".to_string()); - static METHOD_NAME_REF_CELL: std::cell::RefCell = - std::cell::RefCell::new("".to_string()); - static MANUAL_REF_CELL: std::cell::RefCell = - std::cell::RefCell::new(false); - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/header/use_statements.rs b/src/compiler/typescript_to_rust/azle_generate/src/header/use_statements.rs deleted file mode 100644 index 93a8f7ba46..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/header/use_statements.rs +++ /dev/null @@ -1,10 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - use azle_vm_value_derive::{CdkActTryIntoVmValue, CdkActTryFromVmValue}; - use candid::{Decode, Encode}; - use rand::Rng as _AzleTraitRng; - use slotmap::Key as _AzleTraitSlotMapKey; - use std::convert::TryInto as _AzleTraitTryInto; - use std::str::FromStr as _AzleTraitFromStr; - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/lib.rs b/src/compiler/typescript_to_rust/azle_generate/src/lib.rs deleted file mode 100644 index 6dbe43de16..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/lib.rs +++ /dev/null @@ -1,79 +0,0 @@ -use alias_table::AliasLists; -use cdk_framework::{traits::CollectResults, AbstractCanisterTree}; -use proc_macro2::TokenStream; - -pub use crate::errors::{Error, GuardFunctionNotFound}; -use crate::{body::stable_b_tree_map::StableBTreeMapNode, ts_ast::TsAst}; - -mod body; -mod candid_type; -mod canister_method; -mod guard_function; -mod header; -mod macros; -mod ts_ast; -mod ts_keywords; -mod vm_value_conversion; - -pub mod alias_table; -pub mod errors; -pub mod plugin; -pub mod traits; - -pub use alias_table::AliasTable; -pub use alias_table::AliasTables; -pub use plugin::Plugin; - -pub fn generate_canister( - ts_file_names: &Vec, - main_js: String, - alias_tables: AliasTables, - alias_lists: AliasLists, - plugins: &Vec, - environment_variables: &Vec<(String, String)>, -) -> Result> { - TsAst::new(ts_file_names, main_js, alias_tables, alias_lists)? - .to_act(plugins, environment_variables)? - .to_token_stream() - .map_err(|cdkf_errors| cdkf_errors.into_iter().map(Error::from).collect()) -} - -impl TsAst { - pub fn to_act( - &self, - plugins: &Vec, - environment_variables: &Vec<(String, String)>, - ) -> Result> { - let (candid_types, canister_methods, stable_b_tree_maps) = ( - self.build_candid_types(), - self.build_canister_methods(plugins, environment_variables), - self.build_stable_b_tree_map_nodes(), - ) - .collect_results()?; - - let guard_functions = self.build_guard_functions(); - let body = body::generate( - self, - &canister_methods.query_methods, - &canister_methods.update_methods, - &candid_types.services, - &stable_b_tree_maps, - plugins, - )?; - let cdk_name = "azle".to_string(); - let header = header::generate(&self.main_js); - let keywords = ts_keywords::ts_keywords(); - let vm_value_conversion = self.build_vm_value_conversion(); - - Ok(AbstractCanisterTree { - body, - canister_methods, - cdk_name, - candid_types, - guard_functions, - header, - keywords, - vm_value_conversion, - }) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/macros.rs b/src/compiler/typescript_to_rust/azle_generate/src/macros.rs deleted file mode 100644 index 72ec78c481..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/macros.rs +++ /dev/null @@ -1,18 +0,0 @@ -/// Indicates a branch of logic that should be unreachable because other checks -/// should have caught this case before. -/// -/// Unlike `unreachable!` however, this does not panic, but rather returns an -/// error. -/// -/// Expands to: -/// ```rust -/// return Err(Error::InternalError(InternalError {})) -/// ``` -#[macro_export] -macro_rules! internal_error { - () => { - return Err(crate::Error::InternalError( - crate::errors::InternalError::new(), - )) - }; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/main.rs b/src/compiler/typescript_to_rust/azle_generate/src/main.rs deleted file mode 100644 index ea32e05bb2..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/main.rs +++ /dev/null @@ -1,128 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::{ - env, - fs::{self, File}, - io::Write, - process, -}; - -use azle_generate::{alias_table::AliasLists, generate_canister, AliasTables, Plugin}; - -const USAGE_ERROR: i32 = 1; -const COMPILER_INFO_READ_ERROR: i32 = 2; -const JSON_PARSE_ERROR: i32 = 3; -const ENV_READ_ERROR: i32 = 4; -const MAIN_JS_READ_ERROR: i32 = 5; -const CANISTER_COMPILATION_ERROR: i32 = 6; -const LIB_PARSE_ERROR: i32 = 7; -const GENERATED_LIB_GENERATION_ERR: i32 = 8; -const GENERATED_LIB_WRITE_ERR: i32 = 9; - -#[derive(Debug, Serialize, Deserialize)] -struct CompilerInfo { - plugins: Vec, - file_names: Vec, - alias_tables: AliasTables, - alias_lists: AliasLists, -} - -fn main() { - let args: Vec = env::args().collect(); - - if args.len() < 2 { - let executable_name = &args[0]; - eprintln!("Usage: {executable_name} [env_vars_csv]"); - process::exit(USAGE_ERROR); - } - - let compiler_info_path = &args[1]; - let compiler_info_string = match fs::read_to_string(compiler_info_path) { - Ok(compiler_info_string) => compiler_info_string, - Err(err) => { - eprintln!("Error reading {compiler_info_path}: {err}"); - process::exit(COMPILER_INFO_READ_ERROR); - } - }; - let compiler_info: CompilerInfo = match serde_json::from_str(&compiler_info_string) { - Ok(compiler_info) => compiler_info, - Err(err) => { - eprintln!("Error parsing {compiler_info_path}: {err}"); - process::exit(JSON_PARSE_ERROR); - } - }; - - let environment_variables = create_environment_variables(&args); - - let main_js = match fs::read_to_string("src/main.js") { - Ok(content) => content, - Err(err) => { - eprintln!("Error reading src/main.js: {err}"); - process::exit(MAIN_JS_READ_ERROR); - } - }; - - let lib_file = match generate_canister( - &compiler_info.file_names, - main_js, - compiler_info.alias_tables, - compiler_info.alias_lists, - &compiler_info.plugins, - &environment_variables, - ) { - Ok(lib_file) => lib_file.to_string(), - Err(errors) => { - eprintln!("Canister compilation failed:"); - for error in errors { - eprintln!("{}", error); - } - process::exit(CANISTER_COMPILATION_ERROR); - } - }; - - let syntax_tree = match syn::parse_file(&lib_file) { - Ok(syntax_tree) => syntax_tree, - Err(_) => { - eprintln!("{}", azle_generate::errors::InternalError::new()); - process::exit(LIB_PARSE_ERROR); - } - }; - let formatted = prettyplease::unparse(&syntax_tree); - - let mut f = match File::create("../src/lib.rs") { - Ok(f) => f, - Err(_) => { - println!("Unable to create lib file"); - process::exit(GENERATED_LIB_GENERATION_ERR) - } - }; - match f.write_all(formatted.as_bytes()) { - Ok(_) => (), - Err(_) => { - println!("Unable to write data"); - process::exit(GENERATED_LIB_WRITE_ERR) - } - } -} - -// TODO consider writing the environment variables to disk instead of sending them over the command line -fn create_environment_variables(args: &Vec) -> Vec<(String, String)> { - if let Some(envs) = args.get(2) { - envs.split(',') - .filter(|env_var_name| env_var_name != &"") - .map(|env_var_name| { - ( - env_var_name.to_string(), - match std::env::var(env_var_name) { - Ok(env_var_value) => env_var_value, - Err(err) => { - eprintln!("Error reading env var {env_var_name}: {err}"); - process::exit(ENV_READ_ERROR) - } - }, - ) - }) - .collect() - } else { - vec![] - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/plugin/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/plugin/mod.rs deleted file mode 100644 index 19be6aa3dd..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/plugin/mod.rs +++ /dev/null @@ -1,38 +0,0 @@ -use std::path::PathBuf; - -use proc_macro2::TokenStream; -use serde::{Deserialize, Serialize}; - -use crate::{ - errors::errors::{UnableToLoadPlugin, UnableToParsePlugin}, - Error, -}; - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Plugin { - pub path: String, - pub register_function: String, -} - -impl Plugin { - pub fn to_code(&self) -> Result> { - let plugin_file_name = PathBuf::from(&self.path).join("src").join("lib.rs"); - let plugin_code = match std::fs::read_to_string(plugin_file_name.clone()) { - Ok(plugin_code) => plugin_code, - Err(err) => { - return Err(vec![ - UnableToLoadPlugin::from_error(err, &plugin_file_name).into() - ]) - } - }; - - match syn::parse_str::(&plugin_code) { - Ok(token_stream) => Ok(token_stream), - Err(err) => Err(vec![UnableToParsePlugin::from_error( - err, - &plugin_file_name, - ) - .into()]), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_name.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/get_name.rs deleted file mode 100644 index b65646cfd9..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_name.rs +++ /dev/null @@ -1,57 +0,0 @@ -use swc_ecma_ast::{Expr, Ident, MemberExpr, MemberProp, TsEntityName, TsQualifiedName}; - -pub trait GetName { - fn get_name(&self) -> String; -} - -impl GetName for Ident { - fn get_name(&self) -> String { - self.sym.chars().as_str().to_string() - } -} - -pub trait GetOptionalName { - fn get_name(&self) -> Option; -} - -impl GetName for TsQualifiedName { - fn get_name(&self) -> String { - let right = self.right.get_name(); - let left = self.left.get_name(); - return format!("{left}.{right}"); - } -} - -impl GetName for TsEntityName { - fn get_name(&self) -> String { - match self { - TsEntityName::TsQualifiedName(qualified_name) => qualified_name.get_name(), - TsEntityName::Ident(ident) => ident.get_name(), - } - } -} - -impl GetOptionalName for Expr { - fn get_name(&self) -> Option { - match self { - Expr::Call(call) => call.callee.as_expr()?.get_name(), - Expr::Member(member) => member.get_name(), - Expr::Ident(ident) => Some(ident.get_name()), - Expr::Class(class) => Some(class.ident.clone()?.get_name()), - Expr::Fn(func) => Some(func.ident.clone()?.get_name()), - _ => None, - } - } -} - -impl GetOptionalName for MemberExpr { - fn get_name(&self) -> Option { - let obj = self.obj.get_name()?; - let prop = match &self.prop { - MemberProp::Ident(ident) => ident.get_name(), - MemberProp::PrivateName(private_name) => private_name.id.get_name(), - MemberProp::Computed(computed) => computed.expr.get_name()?, - }; - Some(format!("{obj}.{prop}")) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_param_range.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/get_param_range.rs deleted file mode 100644 index 1948b0208b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_param_range.rs +++ /dev/null @@ -1,7 +0,0 @@ -use swc_common::SourceMap; - -use crate::ts_ast::source_map::Range; - -pub trait GetDestructureRange { - fn get_destructure_range(&self, source_map: &SourceMap) -> Range; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_file_info.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_file_info.rs deleted file mode 100644 index a1d502795b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_file_info.rs +++ /dev/null @@ -1,24 +0,0 @@ -use swc_common::{BytePos, Span}; - -use crate::{errors::Location, ts_ast::source_map::Range}; - -pub trait GetSourceFileInfo { - fn get_text(&self, span: Span) -> String; - fn get_origin(&self, span: Span) -> String; - fn get_source(&self, span: Span) -> String; - fn get_source_from_range(&self, range: (BytePos, BytePos)) -> String; - fn get_line_number(&self, span: Span) -> usize; - fn get_location(&self, span: Span) -> Location; - fn generate_line_highlight(&self, span: Span) -> String; - fn generate_highlighted_line(&self, span: Span) -> String; - fn get_range(&self, span: Span) -> Range; - fn get_multi_line_range(&self, span: &Span, adjuster: usize) -> Range; - fn generate_source_with_range_replaced( - &self, - span: Span, - range: Range, - replacement: &str, - ) -> String; - fn generate_modified_source(&self, span: Span, replacement: &str) -> String; - fn generate_modified_range(&self, span: Span, replacement: &str) -> Range; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_info.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_info.rs deleted file mode 100644 index 7ff9bb5f9b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_info.rs +++ /dev/null @@ -1,9 +0,0 @@ -use crate::errors::Location; - -pub trait GetSourceInfo { - fn get_source(&self) -> String; - fn get_line_number(&self) -> usize; - fn get_origin(&self) -> String; - fn get_range(&self) -> (usize, usize); - fn get_location(&self) -> Location; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_text.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_text.rs deleted file mode 100644 index 8bcd216b4a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_source_text.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub trait GetSourceText { - fn get_source_text(&self) -> String; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/get_span.rs deleted file mode 100644 index b4834505a2..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_span.rs +++ /dev/null @@ -1,5 +0,0 @@ -use swc_common::Span; - -pub trait GetSpan { - fn get_span(&self) -> Span; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_ts_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/get_ts_type.rs deleted file mode 100644 index df4beb7e10..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/get_ts_type.rs +++ /dev/null @@ -1,11 +0,0 @@ -use swc_ecma_ast::TsType; - -use crate::Error; - -pub trait GetTsType { - fn get_ts_type(&self) -> TsType; -} - -pub trait GetTsTypeWithError { - fn get_ts_type(&self) -> Result; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/mod.rs deleted file mode 100644 index 2fc93d3d5d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -mod get_name; -mod get_param_range; -mod get_source_file_info; -mod get_source_info; -mod get_source_text; -mod get_span; -mod get_ts_type; -mod prepend; -mod type_to_string; - -pub use get_name::GetName; -pub use get_name::GetOptionalName; -pub use get_param_range::GetDestructureRange; -pub use get_source_file_info::GetSourceFileInfo; -pub use get_source_info::GetSourceInfo; -pub use get_source_text::GetSourceText; -pub use get_span::GetSpan; -pub use get_ts_type::GetTsType; -pub use get_ts_type::GetTsTypeWithError; -pub use prepend::Prepend; -pub use type_to_string::TypeToString; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/prepend.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/prepend.rs deleted file mode 100644 index 457372cd58..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/prepend.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub trait Prepend { - fn prepend(&self, item: T) -> Self; -} - -impl Prepend for Vec { - fn prepend(&self, item: T) -> Self { - std::iter::once(item).chain(self.iter().cloned()).collect() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/traits/type_to_string.rs b/src/compiler/typescript_to_rust/azle_generate/src/traits/type_to_string.rs deleted file mode 100644 index fe4d6bfb3f..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/traits/type_to_string.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub trait TypeToString { - fn type_to_string(&self) -> String; -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/expr.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/expr.rs deleted file mode 100644 index 0f02092d17..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/expr.rs +++ /dev/null @@ -1,56 +0,0 @@ -use swc_common::Span; -use swc_ecma_ast::Expr; - -use crate::traits::GetSpan; - -impl GetSpan for Expr { - fn get_span(&self) -> Span { - match self { - Expr::This(this) => this.span, - Expr::Array(array) => array.span, - Expr::Object(object) => object.span, - Expr::Fn(fn_expr) => fn_expr.function.span, - Expr::Unary(unary) => unary.span, - Expr::Update(update) => update.span, - Expr::Bin(bin) => bin.span, - Expr::Assign(assign) => assign.span, - Expr::Member(member) => member.span, - Expr::SuperProp(super_prop) => super_prop.span, - Expr::Cond(cond) => cond.span, - Expr::Call(call) => call.span, - Expr::New(new) => new.span, - Expr::Seq(seq) => seq.span, - Expr::Ident(ident) => ident.span, - Expr::Lit(lit) => match lit { - swc_ecma_ast::Lit::Str(str) => str.span, - swc_ecma_ast::Lit::Bool(bool) => bool.span, - swc_ecma_ast::Lit::Null(null) => null.span, - swc_ecma_ast::Lit::Num(num) => num.span, - swc_ecma_ast::Lit::BigInt(big_int) => big_int.span, - swc_ecma_ast::Lit::Regex(regex) => regex.span, - swc_ecma_ast::Lit::JSXText(jsx_text) => jsx_text.span, - }, - Expr::Tpl(tpl) => tpl.span, - Expr::TaggedTpl(tagged_tpl) => tagged_tpl.span, - Expr::Arrow(arrow) => arrow.span, - Expr::Class(class) => class.class.span, - Expr::Yield(yield_expr) => yield_expr.span, - Expr::MetaProp(meta_prop) => meta_prop.span, - Expr::Await(await_expr) => await_expr.span, - Expr::Paren(paren) => paren.span, - Expr::JSXMember(jsx_member) => jsx_member.prop.span, - Expr::JSXNamespacedName(jsx_namespaced_name) => jsx_namespaced_name.ns.span, - Expr::JSXEmpty(jsx_empty) => jsx_empty.span, - Expr::JSXElement(jsx_element) => jsx_element.span, - Expr::JSXFragment(jsx_fragment) => jsx_fragment.span, - Expr::TsTypeAssertion(ts_type_assertion) => ts_type_assertion.span, - Expr::TsConstAssertion(ts_const_assertion) => ts_const_assertion.span, - Expr::TsNonNull(ts_non_null) => ts_non_null.span, - Expr::TsAs(ts_as) => ts_as.span, - Expr::TsInstantiation(ts_instantiation) => ts_instantiation.span, - Expr::PrivateName(private_name) => private_name.span, - Expr::OptChain(opt_chain) => opt_chain.span, - Expr::Invalid(invalid) => invalid.span, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/mod.rs deleted file mode 100644 index 9bdecc8485..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/mod.rs +++ /dev/null @@ -1,90 +0,0 @@ -use cdk_framework::traits::CollectIterResults; -pub use program::Program; -pub use source_map::SourceMapped; -use swc_ecma_ast::TsTypeAliasDecl; - -use crate::{alias_table::AliasLists, AliasTables, Error}; - -pub mod expr; -pub mod program; -pub mod source_map; -pub mod ts_type; -pub mod ts_type_element; - -pub struct TsAst { - pub programs: Vec, - pub main_js: String, -} - -impl TsAst { - pub fn new( - ts_file_names: &Vec, - main_js: String, - alias_tables: AliasTables, - alias_list: AliasLists, - ) -> Result> { - let file_name_to_program = |ts_file_name: &String| { - Program::from_file_name(ts_file_name, &alias_tables, &alias_list) - .map_err(Into::>::into) - }; - let programs = ts_file_names - .iter() - .map(file_name_to_program) - .collect_results()? - .into_iter() - .filter_map(|option| option) - .collect(); - - Ok(Self { programs, main_js }) - } - - // Note: Both module_items and decls seem like useful methods but we're not - // currently using them so I just commented them out for now. - - // pub fn module_items(&self) -> Vec> { - // self.programs.iter().fold(vec![], |mut acc, program| { - // if let swc_ecma_ast::Program::Module(module) = program.deref() { - // let source_mapped_module_items: Vec<_> = module - // .body - // .iter() - // .map(|module_item| SourceMapped::new(module_item, &program.source_map)) - // .collect(); - - // acc.extend(source_mapped_module_items); - // } - // acc - // }) - // } - - // pub fn decls(&self) -> Vec> { - // self.programs.iter().fold(vec![], |mut acc, program| { - // if let swc_ecma_ast::Program::Module(module) = program.deref() { - // module - // .body - // .iter() - // .for_each(|module_item| match module_item { - // ModuleItem::ModuleDecl(decl) => match decl { - // ModuleDecl::ExportDecl(export_decl) => { - // acc.push(SourceMapped::new(&export_decl.decl, &program.source_map)); - // } - // _ => (), - // }, - // ModuleItem::Stmt(stmt) => match stmt { - // Stmt::Decl(decl) => { - // acc.push(SourceMapped::new(decl, &program.source_map)); - // } - // _ => (), - // }, - // }) - // } - // acc - // }) - // } - - pub fn ts_type_alias_decls(&self) -> Vec> { - self.programs - .iter() - .flat_map(|program| program.ts_type_alias_decls()) - .collect() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/program.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/program.rs deleted file mode 100644 index a81b3eca9a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/program.rs +++ /dev/null @@ -1,138 +0,0 @@ -use std::ops::Deref; -use std::path::Path; -use swc_common::{sync::Lrc, SourceMap}; -use swc_ecma_ast::{Decl, ModuleDecl, ModuleItem, Stmt, TsTypeAliasDecl}; -use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsConfig}; - -use crate::alias_table::AliasLists; -use crate::AliasTables; -use crate::{ - errors::errors::{FileSyntaxError, UnableToLoadFile}, - internal_error, AliasTable, Error, -}; - -use super::SourceMapped; - -pub struct Program { - program: swc_ecma_ast::Program, - pub source_map: SourceMap, - pub filepath: String, - pub alias_table: AliasTable, - pub alias_list: Vec, -} - -impl Deref for Program { - type Target = swc_ecma_ast::Program; - - fn deref(&self) -> &Self::Target { - &self.program - } -} - -impl Program { - pub fn from_file_name( - ts_file_name: &str, - alias_tables: &AliasTables, - alias_lists: &AliasLists, - ) -> Result, Error> { - let filepath = Path::new(ts_file_name).to_path_buf(); - - let cm: Lrc = Default::default(); - - let fm = cm - .load_file(&filepath) - .map_err(|error| UnableToLoadFile::from_error(error, ts_file_name))?; - - let lexer = Lexer::new( - Syntax::Typescript(TsConfig { - decorators: true, - ..TsConfig::default() - }), - Default::default(), - StringInput::from(&*fm), - None, - ); - - let mut parser = Parser::new_from(lexer); - - let parse_result = parser.parse_program(); - match parse_result { - Ok(program) => { - if let Ok(source_map) = std::rc::Rc::try_unwrap(cm) { - let alias_table = match alias_tables.get(ts_file_name) { - Some(alias_table) => alias_table, - None => return Ok(None), // If there is no symbol table for the program then we don't need to process it for candid types - }; - let alias_list = match alias_lists.get(ts_file_name) { - Some(alias_lists) => alias_lists.clone(), - None => vec![], - }; - return Ok(Some(Program { - program, - source_map, - filepath: ts_file_name.to_string(), - alias_table: alias_table.clone(), - alias_list: alias_list.clone(), - })); - }; - internal_error!() - } - Err(_error) => return Err(FileSyntaxError::from_file_name(ts_file_name, _error).into()), - } - } - - pub fn ts_type_alias_decls(&self) -> Vec> { - if let swc_ecma_ast::Program::Module(module) = self.deref() { - module - .body - .iter() - .filter_map(|module_item| match module_item { - ModuleItem::ModuleDecl(decl) => match decl { - ModuleDecl::ExportDecl(export_decl) => { - let decl = &export_decl.decl; - if let Decl::TsTypeAlias(ts_type_alias_decl) = decl { - Some(SourceMapped::new( - ts_type_alias_decl, - &self.source_map, - &self.alias_table, - &self.alias_list, - )) - } else { - None - } - } - _ => None, - }, - ModuleItem::Stmt(stmt) => match stmt { - Stmt::Decl(decl) => { - if let Decl::TsTypeAlias(ts_type_alias_decl) = decl { - // acc is mut because SourceMapped can't be cloned, which is - // necessary to do something like: - // return vec![ - // acc, - // vec![SourceMapped::new( - // ts_type_alias_decl, - // &program.source_map, - // )], - // ] - // .concat(); - - Some(SourceMapped::new( - ts_type_alias_decl, - &self.source_map, - &self.alias_table, - &self.alias_list, - )) - } else { - None - } - } - _ => None, - }, - }) - .collect() - } else { - vec![] - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/get_source_file_info.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/get_source_file_info.rs deleted file mode 100644 index 4cc5279eab..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/get_source_file_info.rs +++ /dev/null @@ -1,151 +0,0 @@ -use std::borrow::Cow; - -use swc_common::{source_map::Pos, BytePos, SourceMap, Span}; - -use super::{private_get_source_file_info::PrivateGetSourceFileInfo, Range}; -use crate::{errors::Location, traits::GetSourceFileInfo}; - -impl GetSourceFileInfo for SourceMap { - fn get_text(&self, span: Span) -> String { - let line = self.get_source(span); - line[self.get_start_col(span)..self.get_end_col(span)].to_string() - } - - fn get_range(&self, span: Span) -> Range { - let start = self.get_start_col(span); - let end = self.get_end_col(span); - (start, end) - } - - fn get_multi_line_range(&self, span: &Span, offset: usize) -> Range { - (span.lo().to_usize() - offset, span.hi().to_usize() - offset) - } - - fn get_source(&self, span: Span) -> String { - let line_result = self.lookup_line(span.lo); - match line_result { - Ok(source_file_and_line) => { - let line_number = source_file_and_line.line; - match source_file_and_line.sf.get_line(line_number) { - Some(line) => line.to_string(), - None => "Unable to find line in source code".to_string(), - } - } - Err(_) => "Unable to find line in source code".to_string(), - } - } - - fn get_source_from_range(&self, range: (BytePos, BytePos)) -> String { - let (start, end) = if range.0.to_usize() > range.1.to_usize() { - println!( - "Invalid range {:?}. End value ({}) is less than start value ({})", - range, - range.0.to_usize(), - range.1.to_usize() - ); - (BytePos::from_usize(0), BytePos::from_usize(0)) // TODO make the ranges more robust - } else { - range - }; - - let start_line_source_file_and_line = match self.lookup_line(start) { - Ok(source_file_and_line) => source_file_and_line, - Err(_) => return "".to_string(), // if we can't get the start line just return an empty string because there is no source found. TODO make this more robust - }; - let source_file = start_line_source_file_and_line.sf; - - let start_line_number = start_line_source_file_and_line.line; - let end_line_number = match self.lookup_line(end) { - Ok(source_file_and_line) => source_file_and_line.line, - Err(_) => start_line_number, // if we can't get the end line just use the start line. TODO make this more robust - }; - - let source_lines: Vec = (start_line_number..=end_line_number) - .map(|line_number| { - match source_file.get_line(line_number) { - Some(line) => line.clone(), - None => Cow::from(""), // if we can't find one of the middle lines just fill it in with a black. TODO make this more robust - } - .to_string() - }) - .collect(); - - source_lines.join("\n") - } - - fn generate_highlighted_line(&self, span: Span) -> String { - format!( - "{}\n{}", - self.get_source(span), - self.generate_line_highlight(span) - ) - } - - fn generate_line_highlight(&self, span: Span) -> String { - let line = self.get_source(span); - let start = self.get_start_col(span); - let end = self.get_end_col(span); - - let mut highlight = String::new(); - - for i in 0..line.len() { - if i >= start && i < end { - highlight.push('^'); - } else { - highlight.push(' '); - } - } - - highlight - } - - fn generate_source_with_range_replaced( - &self, - span: Span, - range: Range, - replacement: &str, - ) -> String { - let source = self.get_source(span); - source - .chars() - .take(range.0) - .chain(replacement.chars()) - .chain(source.chars().skip(range.1)) - .collect() - } - - fn generate_modified_source(&self, span: Span, replacement: &str) -> String { - format!( - "{}{}{}", - self.get_well_formed_line(span), - replacement, - self.get_well_formed_end_line(span) - ) - } - - fn generate_modified_range(&self, span: Span, replacement: &str) -> Range { - ( - self.get_start_col(span), - self.get_start_col(span) + replacement.len(), - ) - } - - fn get_origin(&self, span: Span) -> String { - let loc = self.get_loc(span); - loc.file.name.to_string() - } - - fn get_line_number(&self, span: Span) -> usize { - let loc = self.get_loc(span); - loc.line - } - - fn get_location(&self, span: Span) -> Location { - Location { - origin: self.get_origin(span), - line_number: self.get_line_number(span), - source: self.get_source(span), - range: self.get_range(span), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/mod.rs deleted file mode 100644 index ce8abc21a4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -pub use source_mapped::SourceMapped; - -mod source_mapped; - -pub mod get_source_file_info; -pub mod private_get_source_file_info; - -pub type Range = (usize, usize); diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/private_get_source_file_info.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/private_get_source_file_info.rs deleted file mode 100644 index 10da4dc8d8..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/private_get_source_file_info.rs +++ /dev/null @@ -1,37 +0,0 @@ -use swc_common::{Loc, SourceMap, Span}; - -use crate::traits::GetSourceFileInfo; - -pub trait PrivateGetSourceFileInfo { - fn get_loc(&self, span: Span) -> Loc; - fn get_start_col(&self, span: Span) -> usize; - fn get_end_col(&self, span: Span) -> usize; - fn get_well_formed_end_line(&self, span: Span) -> String; - fn get_well_formed_line(&self, span: Span) -> String; -} - -impl PrivateGetSourceFileInfo for SourceMap { - fn get_loc(&self, span: Span) -> Loc { - self.lookup_char_pos(span.lo) - } - - fn get_start_col(&self, span: Span) -> usize { - let loc = self.lookup_char_pos(span.lo); - loc.col_display - } - - fn get_end_col(&self, span: Span) -> usize { - let loc = self.lookup_char_pos(span.hi); - loc.col_display - } - - fn get_well_formed_end_line(&self, span: Span) -> String { - let line = self.get_source(span); - line[self.get_end_col(span)..].to_string() - } - - fn get_well_formed_line(&self, span: Span) -> String { - let line = self.get_source(span); - line[..self.get_start_col(span)].to_string() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/source_mapped.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/source_mapped.rs deleted file mode 100644 index 575dedfbf4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/source_map/source_mapped.rs +++ /dev/null @@ -1,107 +0,0 @@ -use swc_common::SourceMap; - -use crate::{ - errors::Location, - traits::{GetSourceFileInfo, GetSourceInfo, GetSourceText, GetSpan}, - AliasTable, -}; - -pub struct SourceMapped<'a, T> { - inner: T, - pub source_map: &'a SourceMap, - pub alias_table: &'a AliasTable, - pub alias_list: &'a Vec, -} - -impl<'a, T> SourceMapped<'a, T> -where - T: Clone, -{ - pub fn new( - inner: &T, - source_map: &'a SourceMap, - alias_table: &'a AliasTable, - alias_list: &'a Vec, - ) -> Self { - Self { - inner: inner.clone(), - source_map, - alias_table, - alias_list, - } - } - - pub fn spawn(&self, inner: &'a C) -> SourceMapped - where - C: Clone, - { - SourceMapped { - inner: inner.clone(), - source_map: self.source_map, - alias_table: self.alias_table, - alias_list: self.alias_list, - } - } -} - -impl<'a, T> Clone for SourceMapped<'a, T> -where - T: Clone, -{ - fn clone(&self) -> Self { - Self { - inner: self.inner.clone(), - source_map: self.source_map, - alias_table: self.alias_table, - alias_list: self.alias_list, - } - } -} - -impl std::ops::Deref for SourceMapped<'_, T> { - type Target = T; - - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -impl GetSourceInfo for SourceMapped<'_, T> -where - T: GetSpan, -{ - fn get_range(&self) -> (usize, usize) { - self.source_map.get_range(self.get_span()) - } - - fn get_source(&self) -> String { - let span = self.get_span(); - self.source_map.get_source_from_range((span.lo, span.hi)) - } - - fn get_origin(&self) -> String { - self.source_map.get_origin(self.get_span()) - } - - fn get_line_number(&self) -> usize { - self.source_map.get_line_number(self.get_span()) - } - - fn get_location(&self) -> Location { - Location { - origin: self.get_origin(), - line_number: self.get_line_number(), - source: self.get_source(), - range: self.get_range(), - } - } -} - -impl GetSourceText for SourceMapped<'_, T> -where - T: GetSpan, -{ - fn get_source_text(&self) -> String { - self.source_map.get_text(self.get_span()) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/mod.rs deleted file mode 100644 index fe3b990dce..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -mod unexpected_ts_tuple_type; -mod unexpected_ts_type; -mod unexpected_ts_type_literal; - -pub use unexpected_ts_tuple_type::UnexpectedTsTupleTypes; -pub use unexpected_ts_type::UnexpectedTsType; -pub use unexpected_ts_type_literal::UnexpectedTsTypeLiteral; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_tuple_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_tuple_type.rs deleted file mode 100644 index 1a2c081126..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_tuple_type.rs +++ /dev/null @@ -1,35 +0,0 @@ -use swc_ecma_ast::TsType; - -use crate::{errors::Location, traits::GetSourceInfo, ts_ast::SourceMapped}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct UnexpectedTsTupleTypes { - location: Location, -} - -impl UnexpectedTsTupleTypes { - pub fn from_ts_type(sm_ts_type: &SourceMapped) -> Self { - Self { - location: sm_ts_type.get_location(), - } - } -} - -impl std::error::Error for UnexpectedTsTupleTypes {} - -impl From for crate::Error { - fn from(error: UnexpectedTsTupleTypes) -> Self { - Self::UnexpectedTsTupleType(error) - } -} - -impl std::fmt::Display for UnexpectedTsTupleTypes { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let column_number = self.location.range.0 + 1; - write!( - f, - "Unexpected TsTupleType\n at {}:{}:{}\n\nHelp: Try wrapping this with Tuple", - self.location.origin, self.location.line_number, column_number - ) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_type.rs deleted file mode 100644 index 81b88cda57..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_type.rs +++ /dev/null @@ -1,35 +0,0 @@ -use swc_ecma_ast::TsType; - -use crate::{errors::Location, traits::GetSourceInfo, ts_ast::SourceMapped}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct UnexpectedTsType { - location: Location, -} - -impl UnexpectedTsType { - pub fn from_ts_type(sm_ts_type: &SourceMapped) -> Self { - Self { - location: sm_ts_type.get_location(), - } - } -} - -impl std::error::Error for UnexpectedTsType {} - -impl From for crate::Error { - fn from(error: UnexpectedTsType) -> Self { - Self::UnexpectedTsType(error) - } -} - -impl std::fmt::Display for UnexpectedTsType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let column_number = self.location.range.0 + 1; - write!( - f, - "Unexpected TsType\n at {}:{}:{}\n\nHelp: Try removing this type", - self.location.origin, self.location.line_number, column_number - ) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_type_literal.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_type_literal.rs deleted file mode 100644 index a3975cfe21..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/errors/unexpected_ts_type_literal.rs +++ /dev/null @@ -1,35 +0,0 @@ -use swc_ecma_ast::TsType; - -use crate::{errors::Location, traits::GetSourceInfo, ts_ast::SourceMapped}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct UnexpectedTsTypeLiteral { - location: Location, -} - -impl UnexpectedTsTypeLiteral { - pub fn from_ts_type(sm_ts_type: &SourceMapped) -> Self { - Self { - location: sm_ts_type.get_location(), - } - } -} - -impl std::error::Error for UnexpectedTsTypeLiteral {} - -impl From for crate::Error { - fn from(error: UnexpectedTsTypeLiteral) -> Self { - Self::UnexpectedTsTypeLiteral(error) - } -} - -impl std::fmt::Display for UnexpectedTsTypeLiteral { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let column_number = self.location.range.0 + 1; - write!( - f, - "Unexpected TsTypeLiteral\n at {}:{}:{}\n\nHelp: Try wrapping this with either Record or Variant", - self.location.origin, self.location.line_number, column_number - ) - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/get_span.rs deleted file mode 100644 index 1a06e7f38e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/get_span.rs +++ /dev/null @@ -1,37 +0,0 @@ -use swc_common::Span; -use swc_ecma_ast::{TsFnOrConstructorType, TsType, TsUnionOrIntersectionType}; - -use crate::traits::GetSpan; - -impl GetSpan for TsType { - fn get_span(&self) -> Span { - match self { - TsType::TsKeywordType(keyword) => keyword.span, - TsType::TsThisType(this) => this.span, - TsType::TsFnOrConstructorType(fn_or_const) => match fn_or_const { - TsFnOrConstructorType::TsFnType(fn_type) => fn_type.span, - TsFnOrConstructorType::TsConstructorType(const_type) => const_type.span, - }, - TsType::TsTypeRef(type_ref) => type_ref.span, - TsType::TsTypeQuery(type_query) => type_query.span, - TsType::TsTypeLit(type_lit) => type_lit.span, - TsType::TsArrayType(array) => array.span, - TsType::TsTupleType(tuple) => tuple.span, - TsType::TsOptionalType(opt) => opt.span, - TsType::TsRestType(rest) => rest.span, - TsType::TsUnionOrIntersectionType(union_or_inter) => match union_or_inter { - TsUnionOrIntersectionType::TsUnionType(union) => union.span, - TsUnionOrIntersectionType::TsIntersectionType(inter) => inter.span, - }, - TsType::TsConditionalType(cond) => cond.span, - TsType::TsInferType(infer) => infer.span, - TsType::TsParenthesizedType(paren) => paren.span, - TsType::TsTypeOperator(operator) => operator.span, - TsType::TsIndexedAccessType(index) => index.span, - TsType::TsMappedType(map) => map.span, - TsType::TsLitType(lit_type) => lit_type.span, - TsType::TsTypePredicate(pred) => pred.span, - TsType::TsImportType(import) => import.span, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/mod.rs deleted file mode 100644 index 9ffd722d80..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::ops::Deref; -use swc_ecma_ast::{TsTupleType, TsType, TsTypeLit}; - -use crate::ts_ast::SourceMapped; - -pub mod errors; -mod get_span; -mod to_candid_type; -pub mod ts_fn_or_constructor_type; -mod type_to_string; - -impl<'a> SourceMapped<'a, TsType> { - pub fn as_ts_type_lit(&'a self) -> Option> { - match self.deref() { - TsType::TsTypeLit(type_lit) => Some(self.spawn(type_lit)), - _ => None, - } - } - - pub fn as_ts_tuple_type(&'a self) -> Option> { - match self.deref() { - TsType::TsTupleType(tuple_type) => Some(self.spawn(tuple_type)), - _ => None, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/to_candid_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/to_candid_type.rs deleted file mode 100644 index f4122dc54d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/to_candid_type.rs +++ /dev/null @@ -1,32 +0,0 @@ -use std::ops::Deref; -use swc_ecma_ast::{TsFnOrConstructorType, TsType}; - -use cdk_framework::act::node::CandidType; - -use crate::{ts_ast::SourceMapped, Error}; - -use super::errors::{UnexpectedTsTupleTypes, UnexpectedTsType, UnexpectedTsTypeLiteral}; - -impl SourceMapped<'_, TsType> { - pub fn to_candid_type(&self) -> Result> { - match self.deref() { - TsType::TsKeywordType(x) => Ok(CandidType::Primitive(self.spawn(x).to_primitive()?)), - TsType::TsFnOrConstructorType(TsFnOrConstructorType::TsFnType(x)) => { - return Err(self.spawn(x).to_func().into()) - } - TsType::TsTypeRef(x) => self.spawn(x).to_candid_type(), - TsType::TsTypeLit(_) => { - return Err(vec![UnexpectedTsTypeLiteral::from_ts_type(self).into()]); - } - TsType::TsTupleType(_) => { - return Err(vec![UnexpectedTsTupleTypes::from_ts_type(self).into()]); - } - TsType::TsArrayType(_) => { - return Err(vec![UnexpectedTsType::from_ts_type(self).into()]); - } - _ => { - return Err(vec![UnexpectedTsType::from_ts_type(self).into()]); - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/get_span.rs deleted file mode 100644 index 35ade5a5e1..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/get_span.rs +++ /dev/null @@ -1,14 +0,0 @@ -use swc_ecma_ast::TsFnOrConstructorType; - -use crate::traits::GetSpan; - -impl GetSpan for TsFnOrConstructorType { - fn get_span(&self) -> swc_common::Span { - match self { - TsFnOrConstructorType::TsFnType(ts_fn_type) => ts_fn_type.span, - TsFnOrConstructorType::TsConstructorType(ts_constructor_type) => { - ts_constructor_type.span - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/mod.rs deleted file mode 100644 index c4b4089f67..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -mod get_span; -pub mod ts_fn_type; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/errors/mod.rs deleted file mode 100644 index 49f54981cd..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/errors/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod not_enclosed_in_func; - -pub use not_enclosed_in_func::NotEnclosedInFunc; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/errors/not_enclosed_in_func.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/errors/not_enclosed_in_func.rs deleted file mode 100644 index 2fec3fba43..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/errors/not_enclosed_in_func.rs +++ /dev/null @@ -1,63 +0,0 @@ -use swc_ecma_ast::TsFnType; - -use crate::{ - errors::{CompilerOutput, Location, Suggestion, SuggestionModifications}, - traits::{GetSourceFileInfo, GetSourceInfo, GetSourceText}, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct NotEnclosedInFunc { - location: Location, - suggestion_modifications: SuggestionModifications, -} - -impl NotEnclosedInFunc { - pub fn from_ts_fn_type(sm_ts_fn_type: &SourceMapped) -> Self { - let replacement_code = format!("Func<{}>", sm_ts_fn_type.get_source_text()); - let modified_source = sm_ts_fn_type - .source_map - .generate_modified_source(sm_ts_fn_type.span, &replacement_code); - let modified_range = sm_ts_fn_type - .source_map - .generate_modified_range(sm_ts_fn_type.span, &replacement_code); - Self { - location: sm_ts_fn_type.get_location(), - suggestion_modifications: (modified_source, modified_range), - } - } - - fn not_enclosed_in_func_error(&self) -> CompilerOutput { - let suggestion = Suggestion { - title: - "Any function that will end up as part of the candid needs to be enclosed in Func<>" - .to_string(), - source: self.suggestion_modifications.0.clone(), - range: self.suggestion_modifications.1, - annotation: Some("Enclose in Func<> here.".to_string()), - import_suggestion: None, - }; - CompilerOutput { - title: "Invalid Func".to_string(), - location: self.location.clone(), - annotation: "Function must be enclosed in Func<>".to_string(), - suggestion: Some(suggestion), - } - } -} - -impl std::error::Error for NotEnclosedInFunc {} - -impl From for crate::Error { - fn from(error: NotEnclosedInFunc) -> Self { - Self::NotEnclosedInFunc(error) - } -} - -impl std::fmt::Display for NotEnclosedInFunc { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.not_enclosed_in_func_error()) - } -} - -impl SourceMapped<'_, TsFnType> {} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/get_span.rs deleted file mode 100644 index 20b4c0ec2d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/get_span.rs +++ /dev/null @@ -1,21 +0,0 @@ -use swc_common::Span; -use swc_ecma_ast::{TsFnParam, TsFnType}; - -use crate::traits::GetSpan; - -impl GetSpan for TsFnType { - fn get_span(&self) -> Span { - self.span - } -} - -impl GetSpan for TsFnParam { - fn get_span(&self) -> Span { - match self { - TsFnParam::Ident(ident) => ident.span, - TsFnParam::Array(array) => array.span, - TsFnParam::Rest(rest) => rest.span, - TsFnParam::Object(object) => object.span, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/mod.rs deleted file mode 100644 index ade14ad414..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/mod.rs +++ /dev/null @@ -1,62 +0,0 @@ -use std::ops::Deref; - -use cdk_framework::traits::CollectIterResults; -use swc_ecma_ast::{TsFnParam, TsFnType, TsType, TsTypeAnn}; - -use crate::{ - errors::errors::{ - ArrayDestructuringInParamsNotSupported, FunctionParamsMustHaveType, - ObjectDestructuringNotSupported, RestParametersNotSupported, - }, - traits::{GetTsType, GetTsTypeWithError}, - ts_ast::SourceMapped, - Error, -}; - -pub mod errors; -mod get_span; -mod to_candid_type; - -impl SourceMapped<'_, TsFnType> { - fn get_ts_fn_params(&self) -> Vec { - self.params.clone() - } - - pub fn get_ts_type_ann(&self) -> TsTypeAnn { - self.type_ann.clone() - } - - pub fn get_param_types(&self) -> Result, Vec> { - let param_to_ts_type = |param: &TsFnParam| { - self.spawn(param) - .get_ts_type() - .map_err(Into::>::into) - }; - self.get_ts_fn_params() - .iter() - .map(param_to_ts_type) - .collect_results() - } -} - -impl GetTsTypeWithError for SourceMapped<'_, TsFnParam> { - fn get_ts_type(&self) -> Result { - match self.deref() { - TsFnParam::Ident(identifier) => match &identifier.type_ann { - Some(param_type) => Ok(param_type.get_ts_type()), - None => Err(Into::::into( - FunctionParamsMustHaveType::from_ts_fn_param(self), - )), - }, - TsFnParam::Array(array_pat) => Err( - ArrayDestructuringInParamsNotSupported::from_ts_fn_param(self, array_pat).into(), - ), - TsFnParam::Rest(rest_pat) => { - Err(RestParametersNotSupported::from_ts_fn_param(self, rest_pat).into()) - } - TsFnParam::Object(object_pat) => { - Err(ObjectDestructuringNotSupported::from_ts_fn_param(self, object_pat).into()) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/to_candid_type.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/to_candid_type.rs deleted file mode 100644 index 66fb665b9e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/ts_fn_or_constructor_type/ts_fn_type/to_candid_type.rs +++ /dev/null @@ -1,11 +0,0 @@ -use swc_ecma_ast::TsFnType; - -use crate::{ts_ast::SourceMapped, Error}; - -use super::errors::NotEnclosedInFunc; - -impl SourceMapped<'_, TsFnType> { - pub fn to_func(&self) -> Error { - NotEnclosedInFunc::from_ts_fn_type(self).into() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/type_to_string.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/type_to_string.rs deleted file mode 100644 index c1a59963ed..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type/type_to_string.rs +++ /dev/null @@ -1,41 +0,0 @@ -use swc_ecma_ast::{TsFnOrConstructorType, TsType, TsUnionOrIntersectionType}; - -use crate::traits::TypeToString; - -impl TypeToString for TsType { - fn type_to_string(&self) -> String { - match self { - TsType::TsKeywordType(_) => "keyword", - TsType::TsThisType(_) => "this", - TsType::TsFnOrConstructorType(ts_fn_or_constructor_type) => { - match ts_fn_or_constructor_type { - TsFnOrConstructorType::TsFnType(_) => "function", - TsFnOrConstructorType::TsConstructorType(_) => "constructor", - } - } - TsType::TsTypeRef(_) => "type reference", - TsType::TsTypeQuery(_) => "type query", - TsType::TsTypeLit(_) => "type literal", - TsType::TsArrayType(_) => "array", - TsType::TsTupleType(_) => "tuple", - TsType::TsOptionalType(_) => "optional", - TsType::TsRestType(_) => "rest", - TsType::TsUnionOrIntersectionType(ts_union_or_intersection_type) => { - match ts_union_or_intersection_type { - TsUnionOrIntersectionType::TsUnionType(_) => "union", - TsUnionOrIntersectionType::TsIntersectionType(_) => "intersection", - } - } - TsType::TsConditionalType(_) => "conditional", - TsType::TsInferType(_) => "infer", - TsType::TsParenthesizedType(_) => "parenthesized", - TsType::TsTypeOperator(_) => "type operator", - TsType::TsIndexedAccessType(_) => "indexed access", - TsType::TsMappedType(_) => "mapped", - TsType::TsLitType(_) => "literal", - TsType::TsTypePredicate(_) => "type predicate", - TsType::TsImportType(_) => "import", - } - .to_string() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/get_span.rs deleted file mode 100644 index b0c9876dbd..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/get_span.rs +++ /dev/null @@ -1,22 +0,0 @@ -use swc_common::Span; -use swc_ecma_ast::TsTypeElement; - -use crate::traits::GetSpan; - -impl GetSpan for TsTypeElement { - fn get_span(&self) -> Span { - match self { - TsTypeElement::TsCallSignatureDecl(ts_call_signature_decl) => { - ts_call_signature_decl.span - } - TsTypeElement::TsConstructSignatureDecl(ts_construct_signature_decl) => { - ts_construct_signature_decl.span - } - TsTypeElement::TsPropertySignature(ts_property_signature) => ts_property_signature.span, - TsTypeElement::TsGetterSignature(ts_getter_signature) => ts_getter_signature.span, - TsTypeElement::TsSetterSignature(ts_setter_signature) => ts_setter_signature.span, - TsTypeElement::TsMethodSignature(ts_method_signature) => ts_method_signature.span, - TsTypeElement::TsIndexSignature(ts_index_signature) => ts_index_signature.span, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/mod.rs deleted file mode 100644 index 8f687ecdba..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -use std::ops::Deref; -use swc_ecma_ast::{TsPropertySignature, TsTypeElement}; - -use crate::ts_ast::SourceMapped; - -mod get_span; -pub mod ts_property_signature; -mod type_to_string; - -impl SourceMapped<'_, TsTypeElement> { - pub fn as_property_signature(&self) -> Option> { - match self.deref() { - TsTypeElement::TsPropertySignature(ts_property_signature) => { - Some(self.spawn(ts_property_signature)) - } - _ => None, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/mod.rs deleted file mode 100644 index 2b8cb7af86..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod no_type_annotation; -mod unsupported_member_name; - -pub use no_type_annotation::NoTypeAnnotation; -pub use unsupported_member_name::UnsupportedMemberName; diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/no_type_annotation.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/no_type_annotation.rs deleted file mode 100644 index d3ae33f1e4..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/no_type_annotation.rs +++ /dev/null @@ -1,45 +0,0 @@ -use swc_ecma_ast::TsPropertySignature; - -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; - -#[derive(Debug, Clone, PartialEq)] -pub struct NoTypeAnnotation { - location: Location, -} - -impl NoTypeAnnotation { - pub fn from_ts_property_signature(sm_property_sig: &SourceMapped) -> Self { - Self { - location: sm_property_sig.get_location(), - } - } - - fn no_type_annotation_error(&self) -> CompilerOutput { - CompilerOutput { - title: "Type Annotation Needed".to_string(), - location: self.location.clone(), - annotation: "type annotation needed for this member".to_string(), - suggestion: None, - } - } -} - -impl std::error::Error for NoTypeAnnotation {} - -impl From for crate::Error { - fn from(error: NoTypeAnnotation) -> Self { - Self::NoTypeAnnotation(error) - } -} - -impl std::fmt::Display for NoTypeAnnotation { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.no_type_annotation_error()) - } -} - -impl SourceMapped<'_, TsPropertySignature> {} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/unsupported_member_name.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/unsupported_member_name.rs deleted file mode 100644 index 53181500fa..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/errors/unsupported_member_name.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::{ - errors::{CompilerOutput, Location}, - traits::GetSourceInfo, - ts_ast::SourceMapped, -}; -use swc_ecma_ast::TsPropertySignature; - -#[derive(Debug, Clone, PartialEq)] -pub struct UnsupportedMemberName { - location: Location, -} - -impl UnsupportedMemberName { - pub fn from_ts_property_signature(sm_property_sig: &SourceMapped) -> Self { - Self { - location: sm_property_sig.get_location(), - } - } - - /// Note: This shouldn't ever be hit because it is mostly likely caught by - /// by the `unsupported_type_error` function in - /// ts_ast/azle_type/azle_type_lit/azle_type_element/errors.rs - /// - fn unsupported_member_name_error(&self) -> CompilerOutput { - CompilerOutput { - title: "Unsupported member name".to_string(), - location: self.location.clone(), - annotation: "change this to a simple identifier".to_string(), - suggestion: None, - } - } -} - -impl std::error::Error for UnsupportedMemberName {} - -impl From for crate::Error { - fn from(error: UnsupportedMemberName) -> Self { - Self::UnsupportedMemberName(error) - } -} - -impl std::fmt::Display for UnsupportedMemberName { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.unsupported_member_name_error()) - } -} - -impl SourceMapped<'_, TsPropertySignature> {} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/get_span.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/get_span.rs deleted file mode 100644 index f2d723459b..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/get_span.rs +++ /dev/null @@ -1,10 +0,0 @@ -use swc_common::Span; -use swc_ecma_ast::TsPropertySignature; - -use crate::traits::GetSpan; - -impl GetSpan for TsPropertySignature { - fn get_span(&self) -> Span { - self.span - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/mod.rs deleted file mode 100644 index 31c3fb66bd..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/ts_property_signature/mod.rs +++ /dev/null @@ -1,36 +0,0 @@ -use swc_ecma_ast::TsPropertySignature; - -use crate::{ - traits::{GetName, GetTsType}, - ts_ast::SourceMapped, - Error, -}; -use cdk_framework::act::node::CandidType; - -use self::errors::{NoTypeAnnotation, UnsupportedMemberName}; - -pub mod errors; -mod get_span; - -impl SourceMapped<'_, TsPropertySignature> { - pub fn get_member_name(&self) -> Result { - Ok(match self.key.as_ident() { - Some(ident) => ident, - None => return Err(UnsupportedMemberName::from_ts_property_signature(self).into()), - } - .get_name()) - } - - pub fn get_act_data_type(&self) -> Result> { - let ts_type = match &self.type_ann { - Some(ts_type_ann) => ts_type_ann.get_ts_type(), - None => { - return Err(vec![ - NoTypeAnnotation::from_ts_property_signature(self).into() - ]) - } - }; - - self.spawn(&ts_type).to_candid_type() - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/type_to_string.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/type_to_string.rs deleted file mode 100644 index 66e90c1e72..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_ast/ts_type_element/type_to_string.rs +++ /dev/null @@ -1,17 +0,0 @@ -use swc_ecma_ast::TsTypeElement; - -use crate::traits::TypeToString; - -impl TypeToString for TsTypeElement { - fn type_to_string(&self) -> String { - match &self { - TsTypeElement::TsCallSignatureDecl(_) => "call signature declaration".to_string(), - TsTypeElement::TsConstructSignatureDecl(_) => "construct signature".to_string(), - TsTypeElement::TsGetterSignature(_) => "getter signature".to_string(), - TsTypeElement::TsSetterSignature(_) => "setter signature".to_string(), - TsTypeElement::TsMethodSignature(_) => "method signature".to_string(), - TsTypeElement::TsIndexSignature(_) => "index signature".to_string(), - TsTypeElement::TsPropertySignature(_) => "property signature".to_string(), - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/ts_keywords.rs b/src/compiler/typescript_to_rust/azle_generate/src/ts_keywords.rs deleted file mode 100644 index db86fac26d..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/ts_keywords.rs +++ /dev/null @@ -1,14 +0,0 @@ -// I believe all TS keywords are allowed as property names in objects. -// If that's not the case then we should change to commented out approach below -pub fn ts_keywords() -> Vec { - vec![] -} - -// const TS_KEYWORDS: [&str; 2] = ["async", "etc"]; - -// pub fn ts_keywords() -> Vec { -// TS_KEYWORDS -// .iter() -// .map(|keyword| keyword.to_string()) -// .collect() -// } diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/mod.rs deleted file mode 100644 index 955e786a8e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -use cdk_framework::act::VmValueConversion; - -use super::TsAst; - -pub mod try_from_vm_value_impls; -pub mod try_into_vm_value_impls; - -impl TsAst { - pub fn build_vm_value_conversion(&self) -> VmValueConversion { - let try_into_vm_value_impls = try_into_vm_value_impls::generate(); - let try_from_vm_value_impls = try_from_vm_value_impls::generate(); - - VmValueConversion { - try_from_vm_value_impls, - try_into_vm_value_impls, - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/basic.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/basic.rs deleted file mode 100644 index 5a7b3ac307..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/basic.rs +++ /dev/null @@ -1,251 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - // TODO This was changed to allow null or undefined JsValues, - // this should be thought through and tested - impl CdkActTryFromVmValue<(), boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result<(), boa_engine::JsError> { - if self.is_null() || self.is_undefined() { - return Ok(()); - } - - Err("TypeError: Value is not of type 'null' or 'undefined'".to_js_error(None))? - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_boolean() - .ok_or_else(|| "TypeError: Value is not of type 'boolean'".to_js_error(None))?) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'string'"; - - Ok(self - .as_string() - .ok_or_else(|| error_message.to_js_error(None))? - .to_std_string() - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Err("TypeError: Value cannot be converted into type 'empty'".to_js_error(None))? - } - } - - impl - CdkActTryFromVmValue< - candid::Reserved, - boa_engine::JsError, - &mut boa_engine::Context<'_>, - > for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(candid::Reserved) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'Func'"; - - let js_object = self - .as_object() - .ok_or_else(|| error_message.to_js_error(None))?; - - if !js_object.is_array() { - let cause = "TypeError: Expected 'Array', given 'Object'".to_js_error(None); - - return Err(error_message.to_js_error(Some(cause))); - } - - let index0 = js_object.get("0", context)?; - - if index0.is_undefined() { - let cause = "TypeError: Index '0' is undefined".to_js_error(None); - - return Err(error_message.to_js_error(Some(cause))); - } - - let principal = - index0 - .try_from_vm_value(&mut *context) - .map_err(|principal_err| { - let cause = "TypeError: Index '0' is not of type 'Principal'" - .to_js_error(Some(principal_err)); - - error_message.to_js_error(Some(cause)) - })?; - - let index1 = js_object.get("1", context)?; - - if index1.is_undefined() { - let cause = "TypeError: Index '1' is undefined".to_js_error(None); - - return Err(error_message.to_js_error(Some(cause))); - } - - let method = index1.try_from_vm_value(&mut *context).map_err(|str_err| { - let cause = "TypeError: Index '1' is not of type 'string'".to_js_error(Some(str_err)); - - error_message.to_js_error(Some(cause)) - })?; - - Ok(candid::Func { principal, method }) - } - } - - impl - CdkActTryFromVmValue< - candid::Principal, - boa_engine::JsError, - &mut boa_engine::Context<'_>, - > for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'Principal'"; - - let principal_js_object = self - .as_object() - .ok_or_else(|| error_message.to_js_error(None))?; - - let principal_to_text_function_js_value = - principal_js_object.get("toText", context).map_err(|err| { - let cause = "TypeError: Property 'toText' of object is not a function" - .to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?; - - let principal_to_text_function_js_object = principal_to_text_function_js_value - .as_object() - .ok_or_else(|| { - let cause = "TypeError: Property 'toText' of object is not a function" - .to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?; - - let principal_text = principal_to_text_function_js_object - .call(&self, &[], context) - .map_err(|js_err| error_message.to_js_error(Some(js_err)))? - .as_string() - .ok_or_else(|| { - let cause = - "TypeError: Return value of method 'toText' is not of type 'string'" - .to_js_error(None); - - error_message.to_js_error(Some(cause)) - })? - .to_std_string() - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?; - - // If we get any of these errors it's because they didn't supply Dfinity's built-in - // `toText` method. Dfinity's `Principal.fromText` and `Principal.toText` both throw - // errors which means if their text value is invalid, the JS code will most likely - // throw before we can even return an invalid Principal. And if somehow they are - // able to return an invalid principal, `principal_to_text_function_js_object.call` - // above should error out. - let principal = - candid::Principal::from_text(principal_text).map_err(|principal_error| { - let inner_error_name = match principal_error { - candid::types::principal::PrincipalError::BytesTooLong() => { - "BytesTooLongError" - } - candid::types::principal::PrincipalError::InvalidBase32() => { - "InvalidBase32Error" - } - candid::types::principal::PrincipalError::TextTooShort() => { - "TextTooShortError" - } - candid::types::principal::PrincipalError::TextTooLong() => { - "TextTooLongError" - } - candid::types::principal::PrincipalError::CheckSequenceNotMatch() => { - "CheckSequenceNotMatchError" - } - candid::types::principal::PrincipalError::AbnormalGrouped(_) => { - "AbnormalGroupedError" - } - }; - - // TODO: Consider turning these inner errors into custom errors. - // Currently the inner error will be the base `Error` type. We should - // consider making a PrincipalError type and having each of these errors as - // children of that type. - // See https://github.com/demergent-labs/azle/issues/1121 - - let inner_error_message = principal_error.to_string(); - - let inner_error = - format!("{inner_error_name}: {inner_error_message}").to_js_error(None); - - error_message.to_js_error(Some(inner_error)) - })?; - - Ok(principal) - } - } - - impl - CdkActTryFromVmValue< - ic_cdk_timers::TimerId, - boa_engine::JsError, - &mut boa_engine::Context<'_>, - > for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(ic_cdk_timers::TimerId::from(slotmap::KeyData::from_ffi( - self.try_from_vm_value(context)?, - ))) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/generic.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/generic.rs deleted file mode 100644 index c3d02cd2da..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/generic.rs +++ /dev/null @@ -1,106 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - impl CdkActTryFromVmValue<(T,), boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - where - boa_engine::JsValue: for<'a, 'b> CdkActTryFromVmValue< - T, - boa_engine::JsError, - &'a mut boa_engine::Context<'b>, - >, - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result<(T,), boa_engine::JsError> { - Ok((self.try_from_vm_value(context)?,)) - } - } - - impl CdkActTryFromVmValue, boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - where - boa_engine::JsValue: for<'a, 'b> CdkActTryFromVmValue< - T, - boa_engine::JsError, - &'a mut boa_engine::Context<'b>, - >, - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> { - Ok(Box::new(self.try_from_vm_value(context)?)) - } - } - - impl CdkActTryFromVmValue, boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - where - boa_engine::JsValue: for<'a, 'b> CdkActTryFromVmValue< - T, - boa_engine::JsError, - &'a mut boa_engine::Context<'b>, - >, - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> { - let error_message = "TypeError: Value is not of type 'Opt'"; - - let js_object = self - .as_object() - .ok_or_else(|| error_message.to_js_error(None))?; - - let has_none_property = js_object.has_own_property("None", context)?; - - let has_some_property = js_object.has_own_property("Some", context)?; - - if has_none_property && has_some_property { - let cause = "TypeError: Value must contain exactly one of the \ - following properties: ['Some', 'None']" - .to_js_error(None); - - return Err(error_message.to_js_error(Some(cause)))?; - } - - if has_none_property { - let none_value = js_object.get("None", context).map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?; - - return if none_value.is_null() { - Ok(None) - } else { - let cause = "TypeError: Value is not of type 'null'".to_js_error(None); - - Err(error_message.to_js_error(Some(cause))) - }; - } - - if has_some_property { - return Ok(Some( - js_object - .get("Some", context) - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })? - .try_from_vm_value(context) - .map_err(|js_error| error_message.to_js_error(Some(js_error)))?, - )); - } - - let cause = "TypeError: Value must contain exactly one of the \ - following properties: ['Some', 'None']" - .to_js_error(None); - - Err(error_message.to_js_error(Some(cause)))? - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/mod.rs deleted file mode 100644 index 477eb96dea..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -mod basic; -mod generic; -mod numeric; -mod result; -mod vec; - -pub fn generate() -> proc_macro2::TokenStream { - let basic_impls = basic::generate(); - let generic_impls = generic::generate(); - let numeric_impls = numeric::generate(); - let result_impls = result::generate(); - let vec_impls = vec::generate(); - - quote::quote! { - #basic_impls - #generic_impls - #numeric_impls - #result_impls - #vec_impls - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/numeric.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/numeric.rs deleted file mode 100644 index dc3ecf604e..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/numeric.rs +++ /dev/null @@ -1,283 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'float64'".to_js_error(None))?) - } - } - - impl CdkActTryFromVmValue<_CdkFloat64, boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result<_CdkFloat64, boa_engine::JsError> { - Ok(_CdkFloat64(self.as_number().ok_or_else(|| { - "TypeError: Value is not of type 'float64'".to_js_error(None) - })?)) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'float32'".to_js_error(None))? - as f32) - } - } - - impl CdkActTryFromVmValue<_CdkFloat32, boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result<_CdkFloat32, boa_engine::JsError> { - Ok(_CdkFloat32( - self.as_number().ok_or_else(|| { - "TypeError: Value is not of type 'float32'".to_js_error(None) - })? as f32, - )) - } - } - - // TODO it would probably be better to get the BigInt out of the JsValue and convert it more - // TODO directly but we might run into problems with Nat and BigUint, thus I am doing a - // TODO string conversion for now - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'int'"; - - let int_string = self - .as_bigint() - .ok_or_else(|| error_message.to_js_error(None))? - .to_string(); - - // TODO probably not the best conversion - Ok(candid::Int::from_str(&int_string).map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'int'"; - - Ok(self - .as_bigint() - .ok_or_else(|| error_message.to_js_error(None))? - .to_string() - .parse::() - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - // TODO this might break since i64 may (will) not be a bigint - // TODO probably need to implement my own conversion here until try_from_js_value is fixed - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'int64'"; - - Ok(self - .as_bigint() - .ok_or_else(|| error_message.to_js_error(None))? - .to_string() - .parse::() - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'int32'".to_js_error(None))? - as i32) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'int16'".to_js_error(None))? - as i16) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'int8'".to_js_error(None))? - as i8) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'nat'"; - - let bigint_string = self - .as_bigint() - .ok_or_else(|| error_message.to_js_error(None))? - .to_string(); - - // TODO probably not the best conversion - Ok(candid::Nat::from_str(&bigint_string).map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'nat'"; - - Ok(self - .as_bigint() - .ok_or_else(|| error_message.to_js_error(None))? - .to_string() - .parse::() - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - // TODO this might break since i64 may (will) not be a bigint - // TODO probably need to implement my own conversion here until try_from_js_value is fixed - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let error_message = "TypeError: Value is not of type 'nat64'"; - - Ok(self - .as_bigint() - .ok_or_else(|| error_message.to_js_error(None))? - .to_string() - .parse::() - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'nat32'".to_js_error(None))? - as u32) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'nat16'".to_js_error(None))? - as u16) - } - } - - impl CdkActTryFromVmValue> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self - .as_number() - .ok_or_else(|| "TypeError: Value is not of type 'nat8'".to_js_error(None))? - as u8) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/result.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/result.rs deleted file mode 100644 index 89c38721af..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/result.rs +++ /dev/null @@ -1,76 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - // TODO: This really should be in generic.rs and should be a generic result handler... - quote::quote! { - impl - CdkActTryFromVmValue< - Result<(), String>, - boa_engine::JsError, - &mut boa_engine::Context<'_>, - > for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> { - let error_message = "TypeError: Value is not of type 'GuardResult'"; - - let js_object = self - .as_object() - .ok_or_else(|| error_message.to_js_error(None))?; - - let has_ok_property = js_object.has_own_property("Ok", context).map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?; - - let has_err_property = - js_object.has_own_property("Err", context).map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?; - - if has_ok_property && has_err_property { - let cause = "TypeError: TypeError: Value must contain exactly one of the \ - following properties: ['Ok', 'Err']" - .to_js_error(None); - - return Err(error_message.to_js_error(Some(cause))); - } - - if has_ok_property { - let ok_value = js_object.get("Ok", context).map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?; - - return if ok_value.is_null() { - Ok(Ok(())) - } else { - let cause = "TypeError: Value is not of type 'null'".to_js_error(None); - Err(error_message.to_js_error(Some(cause))) - }; - } - - if has_err_property { - return Ok(Err(js_object - .get("Err", context) - .map_err(|err| { - let cause = err.to_string().to_js_error(None); - - error_message.to_js_error(Some(cause)) - })? - .try_from_vm_value(context)?)); - } - - let cause = "TypeError: Value must contain exactly one of the \ - following properties: ['Ok', 'Err']" - .to_js_error(None); - - Err(error_message.to_js_error(Some(cause))) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/vec.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/vec.rs deleted file mode 100644 index e51d288d91..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_from_vm_value_impls/vec.rs +++ /dev/null @@ -1,148 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - trait AzleTryFromVec {} - - impl AzleTryFromVec for () {} - impl AzleTryFromVec for bool {} - impl AzleTryFromVec for String {} - impl AzleTryFromVec for candid::Empty {} - impl AzleTryFromVec for candid::Reserved {} - impl AzleTryFromVec for candid::Func {} - impl AzleTryFromVec for candid::Principal {} - impl AzleTryFromVec for ic_cdk_timers::TimerId {} - impl AzleTryFromVec for f64 {} - impl AzleTryFromVec for _CdkFloat64 {} - impl AzleTryFromVec for f32 {} - impl AzleTryFromVec for _CdkFloat32 {} - impl AzleTryFromVec for candid::Int {} - impl AzleTryFromVec for i128 {} - impl AzleTryFromVec for i64 {} - impl AzleTryFromVec for i32 {} - impl AzleTryFromVec for i16 {} - impl AzleTryFromVec for i8 {} - impl AzleTryFromVec for candid::Nat {} - impl AzleTryFromVec for u128 {} - impl AzleTryFromVec for u64 {} - impl AzleTryFromVec for u32 {} - impl AzleTryFromVec for u16 {} - impl AzleTryFromVec for Option {} - impl AzleTryFromVec for Vec {} - - impl CdkActTryFromVmValue, boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - where - T: AzleTryFromVec, - boa_engine::JsValue: for<'a, 'b> CdkActTryFromVmValue< - T, - boa_engine::JsError, - &'a mut boa_engine::Context<'b>, - >, - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> { - try_from_vm_value_generic_array::(self, context) - } - } - - impl CdkActTryFromVmValue, boa_engine::JsError, &mut boa_engine::Context<'_>> - for boa_engine::JsValue - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> { - // TODO maybe a better way to do this, I had some issues: - // https://github.com/boa-dev/boa/blob/main/boa_examples/src/bin/jsarraybuffer.rs#L24-L35 - // Ok(boa_engine::object::builtins::JsArrayBuffer::from_object( - // self.as_object().unwrap().clone(), - // ) - // .unwrap() - // .take() - // .unwrap()) - - let error_message = "TypeError: Value is not of type 'blob'"; - - Ok(self - .as_object() - .ok_or_else(|| error_message.to_js_error(None))? - .borrow() - .as_typed_array() - .ok_or_else(|| { - let cause = - "TypeError: Value is not an instance of 'TypedArray'".to_js_error(None); - - error_message.to_js_error(Some(cause)) - })? - .viewed_array_buffer() - .ok_or_else(|| { - let cause = - "TypedArray does not have an associated DataView".to_js_error(None); - - error_message.to_js_error(Some(cause)) - })? - .borrow() - .as_array_buffer() - .ok_or_else(|| { - let cause = - "TypedArray does not have an associated ArrayBuffer".to_js_error(None); - - error_message.to_js_error(Some(cause)) - })? - .array_buffer_data - .clone() - .ok_or_else(|| { - let cause = "No data in ArrayBuffer".to_js_error(None); - - error_message.to_js_error(Some(cause)) - })?) - } - } - - // TODO this seems like such a messy and inefficient way to do it - fn try_from_vm_value_generic_array( - js_value: boa_engine::JsValue, - context: &mut boa_engine::Context, - ) -> Result, boa_engine::JsError> - where - boa_engine::JsValue: for<'a, 'b> CdkActTryFromVmValue< - T, - boa_engine::JsError, - &'a mut boa_engine::Context<'b>, - >, - { - let error_message = "TypeError: Value is not of type 'Vec'"; - - let js_object = js_value - .as_object() - .ok_or_else(|| error_message.to_js_error(None))?; - - if !js_object.is_array() { - return Err(error_message.to_js_error(None)); - } - - let mut index: usize = 0; - let mut result = vec![]; - - loop { - let js_value = js_object - .get(index, context) - .map_err(|err| error_message.to_js_error(Some(err)))?; - - if js_value.is_undefined() { - break; - } - - result.push( - js_value - .try_from_vm_value(context) - .map_err(|err| error_message.to_js_error(Some(err)))?, - ); - index += 1; - } - - Ok(result) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/basic.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/basic.rs deleted file mode 100644 index 3e2c9d0acd..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/basic.rs +++ /dev/null @@ -1,298 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for () { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(boa_engine::JsValue::Null) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for bool { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for String { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for candid::Empty - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Err(CdkActTryIntoVmValueError( - "Empty cannot be converted into JsValue".to_string(), - )) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for candid::Reserved - { - fn try_into_vm_value( - self, - _: &mut boa_engine::Context, - ) -> Result { - Ok(boa_engine::JsValue::Null) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for candid::Func - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(boa_engine::object::builtins::JsArray::from_iter( - [ - self.principal.try_into_vm_value(context)?, - self.method.into(), - ], - context, - ) - .into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for candid::Principal - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let exports_js_value = - context.eval(boa_engine::Source::from_bytes("exports"))?; - - let exports_js_object = exports_js_value - .as_object() - .ok_or_else(|| "TypeError: 'exports' is not an object")?; - - let principal_class_js_value = exports_js_object.get("Principal", context)?; - let principal_class_js_object = principal_class_js_value - .as_object() - .ok_or_else(|| "ReferenceError: Principal is not defined")?; - - let from_text_js_value = principal_class_js_object.get("fromText", context)?; - let from_text_js_object = from_text_js_value - .as_object() - .ok_or_else(|| "TypeError: Principal.fromText is not a function")?; - - let principal_js_value = from_text_js_object.call( - &principal_class_js_value, - &[self.to_text().into()], - context, - )?; - - Ok(principal_js_value) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for ic_cdk_timers::TimerId - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let timer_id_as_u64 = self.data().as_ffi(); - Ok(boa_engine::JsValue::BigInt(timer_id_as_u64.into())) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for ic_cdk::api::stable::StableMemoryError - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - match self { - ic_cdk::api::stable::StableMemoryError::OutOfMemory => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "OutOfMemory", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_cdk::api::stable::StableMemoryError::OutOfBounds => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "OutOfBounds", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - } - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for ic_stable_structures::btreemap::InsertError - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - match self { - ic_stable_structures::btreemap::InsertError::KeyTooLarge { given, max } => { - let given_js_value = given.try_into_vm_value(context)?; - let max_js_value = max.try_into_vm_value(context)?; - - let key_too_large_object = - boa_engine::object::ObjectInitializer::new(context) - .property( - "given", - given_js_value, - boa_engine::property::Attribute::all(), - ) - .property( - "max", - max_js_value, - boa_engine::property::Attribute::all(), - ) - .build(); - - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "KeyTooLarge", - key_too_large_object, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_stable_structures::btreemap::InsertError::ValueTooLarge { given, max } => { - let given_js_value = given.try_into_vm_value(context)?; - let max_js_value = max.try_into_vm_value(context)?; - - let value_too_large_object = - boa_engine::object::ObjectInitializer::new(context) - .property( - "given", - given_js_value, - boa_engine::property::Attribute::all(), - ) - .property( - "max", - max_js_value, - boa_engine::property::Attribute::all(), - ) - .build(); - - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "ValueTooLarge", - value_too_large_object, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - } - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for ic_cdk::api::call::RejectionCode - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - match self { - ic_cdk::api::call::RejectionCode::NoError => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "NoError", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_cdk::api::call::RejectionCode::SysFatal => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "SysFatal", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_cdk::api::call::RejectionCode::SysTransient => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "SysTransient", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_cdk::api::call::RejectionCode::DestinationInvalid => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "DestinationInvalid", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_cdk::api::call::RejectionCode::CanisterReject => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "CanisterReject", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_cdk::api::call::RejectionCode::CanisterError => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "CanisterError", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - ic_cdk::api::call::RejectionCode::Unknown => { - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "Unknown", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - } - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/error_conversions.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/error_conversions.rs deleted file mode 100644 index dcd87ad2da..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/error_conversions.rs +++ /dev/null @@ -1,21 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - impl From<&str> for CdkActTryIntoVmValueError { - fn from(value: &str) -> Self { - Self(value.to_string()) - } - } - - impl From for CdkActTryIntoVmValueError { - fn from(value: String) -> Self { - Self(value) - } - } - - impl From for CdkActTryIntoVmValueError { - fn from(value: boa_engine::JsError) -> Self { - Self(value.to_string()) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/generic.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/generic.rs deleted file mode 100644 index f4e94b122a..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/generic.rs +++ /dev/null @@ -1,110 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for (T,) - where - T: for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - >, - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.0.try_into_vm_value(context)?) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for Box - where - T: for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - >, - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok((*self).try_into_vm_value(context)?) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for Option - where - T: for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - >, - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - match self { - Some(value) => { - let some_js_value = value.try_into_vm_value(context)?; - Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "Some", - some_js_value, - boa_engine::property::Attribute::all(), - ) - .build() - .into()) - } - None => Ok(boa_engine::object::ObjectInitializer::new(context) - .property( - "None", - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all(), - ) - .build() - .into()), - } - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for Result - where - T: for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - >, - K: for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - >, - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - match self { - Ok(ok) => { - let ok_js_value = ok.try_into_vm_value(context)?; - - let result_js_object = boa_engine::object::ObjectInitializer::new(context) - .property("Ok", ok_js_value, boa_engine::property::Attribute::all()) - .build(); - - let result_js_value = result_js_object.into(); - - Ok(result_js_value) - } - Err(err) => { - let err_js_value = err.try_into_vm_value(context)?; - - let result_js_object = boa_engine::object::ObjectInitializer::new(context) - .property("Err", err_js_value, boa_engine::property::Attribute::all()) - .build(); - - let result_js_value = result_js_object.into(); - - Ok(result_js_value) - } - } - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/mod.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/mod.rs deleted file mode 100644 index 95ca52c6ee..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -mod basic; -mod error_conversions; -mod generic; -mod numeric; -mod vec; - -pub fn generate() -> proc_macro2::TokenStream { - let error_conversions = error_conversions::generate(); - - let basic_impls = basic::generate(); - let generic_impls = generic::generate(); - let numeric_impls = numeric::generate(); - let vec_impls = vec::generate(); - - quote::quote! { - #error_conversions - #basic_impls - #generic_impls - #numeric_impls - #vec_impls - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/numeric.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/numeric.rs deleted file mode 100644 index e2327e1e95..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/numeric.rs +++ /dev/null @@ -1,172 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for f64 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for _CdkFloat64 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.0.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for f32 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for _CdkFloat32 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.0.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for candid::Int - { - fn try_into_vm_value( - self, - _: &mut boa_engine::Context, - ) -> Result { - Ok(boa_engine::JsValue::BigInt( - boa_engine::bigint::JsBigInt::new(self.0), - )) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for i128 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok( - boa_engine::bigint::JsBigInt::new(boa_engine::bigint::RawBigInt::from(self)) - .into(), - ) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for i64 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(boa_engine::JsValue::BigInt(self.into())) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for i32 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for i16 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for i8 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - // TODO a non-string conversion might be better - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> - for candid::Nat - { - fn try_into_vm_value( - self, - _: &mut boa_engine::Context, - ) -> Result { - Ok(boa_engine::JsValue::BigInt( - boa_engine::bigint::JsBigInt::from_string(&self.0.to_string()) - .ok_or_else(|| "TypeError: Value is not of type 'bigint'")?, - )) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for u128 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok( - boa_engine::bigint::JsBigInt::new(boa_engine::bigint::RawBigInt::from(self)) - .into(), - ) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for u64 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(boa_engine::JsValue::BigInt(self.into())) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for usize { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for u32 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for u16 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for u8 { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - Ok(self.into()) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/vec.rs b/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/vec.rs deleted file mode 100644 index b4113c7835..0000000000 --- a/src/compiler/typescript_to_rust/azle_generate/src/vm_value_conversion/try_into_vm_value_impls/vec.rs +++ /dev/null @@ -1,114 +0,0 @@ -pub fn generate() -> proc_macro2::TokenStream { - quote::quote! { - trait AzleTryIntoVec {} - - impl AzleTryIntoVec for () {} - - impl AzleTryIntoVec for bool {} - - impl AzleTryIntoVec for String {} - - impl AzleTryIntoVec for candid::Empty {} - - impl AzleTryIntoVec for candid::Reserved {} - - impl AzleTryIntoVec for candid::Func {} - - impl AzleTryIntoVec for candid::Principal {} - - impl AzleTryIntoVec for ic_cdk_timers::TimerId {} - - impl AzleTryIntoVec for ic_cdk::api::call::RejectionCode {} - - // TODO add all number types - // TODO need to figure out how to convert number Vecs to Vec - // TODO need to abstract the number vecs out - - impl AzleTryIntoVec for f64 {} - - impl AzleTryIntoVec for _CdkFloat64 {} - - impl AzleTryIntoVec for f32 {} - - impl AzleTryIntoVec for _CdkFloat32 {} - - impl AzleTryIntoVec for candid::Int {} - - impl AzleTryIntoVec for i128 {} - - impl AzleTryIntoVec for i64 {} - - impl AzleTryIntoVec for i32 {} - - impl AzleTryIntoVec for i16 {} - - impl AzleTryIntoVec for i8 {} - - impl AzleTryIntoVec for candid::Nat {} - - impl AzleTryIntoVec for u128 {} - - impl AzleTryIntoVec for u64 {} - - impl AzleTryIntoVec for usize {} - - impl AzleTryIntoVec for u32 {} - - impl AzleTryIntoVec for u16 {} - - impl AzleTryIntoVec for Option {} - - impl AzleTryIntoVec for Vec {} - - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for Vec - where - T: AzleTryIntoVec, - T: for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - >, - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - try_into_vm_value_generic_array(self, context) - } - } - - // TODO in the future maybe the other number types can be optimized like this - impl CdkActTryIntoVmValue<&mut boa_engine::Context<'_>, boa_engine::JsValue> for Vec { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context, - ) -> Result { - let js_array_buffer = - boa_engine::object::builtins::JsArrayBuffer::from_byte_block(self, context)?; - let js_uint8_array = boa_engine::object::builtins::JsUint8Array::from_array_buffer( - js_array_buffer, - context, - )?; - - Ok(js_uint8_array.into()) - } - } - - fn try_into_vm_value_generic_array( - generic_array: Vec, - context: &mut boa_engine::Context, - ) -> Result - where - T: for<'a, 'b> CdkActTryIntoVmValue< - &'a mut boa_engine::Context<'b>, - boa_engine::JsValue, - >, - { - let js_values: Vec<_> = generic_array - .into_iter() - .map(|item| item.try_into_vm_value(context)) - .collect::>()?; - - Ok(boa_engine::object::builtins::JsArray::from_iter(js_values, context).into()) - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/Cargo.toml b/src/compiler/typescript_to_rust/azle_vm_value_derive/Cargo.toml deleted file mode 100644 index 820a43ada8..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "azle-vm-value-derive" -version = "0.0.0" -edition = "2018" - -[lib] -proc_macro = true - -[dependencies] -quote = "1.0.17" -syn = "1.0.90" -proc-macro2 = "1.0.36" diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_enum.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_enum.rs deleted file mode 100644 index 0a7db157d1..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_enum.rs +++ /dev/null @@ -1,260 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; -use quote::{format_ident, quote}; -use syn::{DataEnum, Error, Field, Fields, Generics}; - -use crate::{derive_try_from_vm_value::derive_try_from_vm_value_vec, traits::MapTo}; - -pub fn generate( - enum_name: &Ident, - data_enum: &DataEnum, - generics: &Generics, -) -> Result { - let value_is_not_of_enum_type_error_message = - derive_value_is_not_of_enum_type_error_message(enum_name); - - let variant_names = data_enum - .variants - .iter() - .map(|variant| format!("'{}'", variant.ident)) - .collect::>(); - - let variant_names_vec_string = format!("[{}]", variant_names.join(", ")); - - let missing_valid_variant_error_message = format!( - "TypeError: Value must contain exactly one of the following properties: {}", - variant_names_vec_string - ); - - let properties = derive_properties(enum_name, data_enum)?; - - let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - let try_from_vm_value_vec_impl = derive_try_from_vm_value_vec::generate(enum_name, generics); - - Ok(quote! { - impl #impl_generics CdkActTryFromVmValue< - #enum_name #ty_generics, - boa_engine::JsError, - &mut boa_engine::Context<'_> - > - for boa_engine::JsValue - #where_clause - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context - ) -> Result<#enum_name #ty_generics, boa_engine::JsError> { - let object = self - .as_object() - .ok_or_else(|| { - let cause = "TypeError: Value is not an object".to_js_error(None); - - #value_is_not_of_enum_type_error_message.to_js_error(Some(cause)) - })?; - - #(#properties)* - - let cause = #missing_valid_variant_error_message.to_js_error(None); - - return Err(#value_is_not_of_enum_type_error_message.to_js_error(Some(cause))); - } - } - - #try_from_vm_value_vec_impl - }) -} - -fn derive_value_is_not_of_enum_type_error_message(enum_name: &Ident) -> String { - format!( - "TypeError: Value is not of type '{}'", - enum_name.to_string() - ) -} - -fn derive_properties(enum_name: &Ident, data_enum: &DataEnum) -> Result, Error> { - data_enum - .variants - .iter() - .map(|variant| { - let variant_name = &variant.ident; - - let object_variant_js_value_result_var_name = - format_ident!("object_{}_js_value_result", variant_name); - let object_variant_js_value_var_name = - format_ident!("object_{}_js_value", variant_name); - - match &variant.fields { - Fields::Named(fields_named) => derive_property_for_named_fields( - fields_named.named.iter().collect(), - enum_name, - variant_name, - &object_variant_js_value_result_var_name, - &object_variant_js_value_var_name, - ), - Fields::Unnamed(fields_unnamed) => Ok(derive_property_for_unnamed_fields( - fields_unnamed.unnamed.iter().collect(), - enum_name, - variant_name, - &object_variant_js_value_result_var_name, - &object_variant_js_value_var_name, - )), - Fields::Unit => Ok(derive_property_for_unnamed_fields( - vec![], - enum_name, - variant_name, - &object_variant_js_value_result_var_name, - &object_variant_js_value_var_name, - )), - } - }) - .collect::>() -} - -fn derive_property_for_named_fields( - named_fields: Vec<&Field>, - enum_name: &Ident, - variant_name: &Ident, - object_variant_js_value_result_var_name: &Ident, - object_variant_js_value_var_name: &Ident, -) -> Result { - let value_is_not_of_enum_type_error_message = - derive_value_is_not_of_enum_type_error_message(enum_name); - - let named_field_js_value_result_variable_names = - named_fields.map_to(enum_name, variant_name, |_, variable_name| { - quote! { #variable_name } - })?; - - let named_field_js_value_result_variable_declarations = - named_fields.map_to(enum_name, variant_name, |field_name, variable_name| { - quote! { - let #variable_name = #object_variant_js_value_var_name - .as_object() - .ok_or_else(|| { - let cause = "TypeError: Value is not an object".to_js_error(None); - - #value_is_not_of_enum_type_error_message.to_js_error(Some(cause)) - })? - .get(stringify!(#field_name), context); - } - })?; - - let named_field_js_value_oks = - named_fields.map_to(enum_name, variant_name, |_, variable_name| { - quote! { Ok(#variable_name) } - })?; - - let named_field_variable_declarations = - named_fields.map_to(enum_name, variant_name, |field_name, variable_name| { - let named_field_js_value_variable_name = format_ident!("{}_js_value", field_name); - - quote! { - let #variable_name = #named_field_js_value_variable_name - .try_from_vm_value(&mut *context); - } - })?; - - let named_field_variable_oks = - named_fields.map_to(enum_name, variant_name, |_, variable_name| { - quote! { #variable_name } - })?; - - let named_field_variable_names = - named_fields.map_to(enum_name, variant_name, |field_name, _| { - quote! { Ok(#field_name) } - })?; - - let tuple_struct_field_definition = - named_fields.map_to(enum_name, variant_name, |field_name, _| { - quote! { #field_name: #field_name } - })?; - - Ok(quote! { - let #object_variant_js_value_result_var_name = - object.get(stringify!(#variant_name), context); - - if let Ok(#object_variant_js_value_var_name) = #object_variant_js_value_result_var_name { - if #object_variant_js_value_var_name.is_undefined() == false { - #(#named_field_js_value_result_variable_declarations)* - - match (#(#named_field_js_value_result_variable_names),*) { - (#(#named_field_js_value_oks),*) => { - #(#named_field_variable_declarations)* - - match (#(#named_field_variable_oks),*) { - (#(#named_field_variable_names),*) => { - return Ok(#enum_name::#variant_name { - #(#tuple_struct_field_definition),* - }); - }, - _ => { - // TODO: Update this error message - return Err( - #value_is_not_of_enum_type_error_message.to_js_error(None) - ); - } - }; - }, - _ => { - // TODO: Update this error message - return Err( - #value_is_not_of_enum_type_error_message.to_js_error(None) - ); - } - }; - } - } - }) -} - -fn derive_property_for_unnamed_fields( - unnamed_fields: Vec<&Field>, - enum_name: &Ident, - variant_name: &Ident, - object_variant_js_value_result_var_name: &Ident, - object_variant_js_value_var_name: &Ident, -) -> TokenStream { - let value_is_not_of_enum_type_error_message = - derive_value_is_not_of_enum_type_error_message(enum_name); - - let property_is_not_of_variant_type_error_message = format!( - "TypeError: Property '{}' is not of the correct type", - variant_name.to_string() - ); - - if unnamed_fields.len() == 0 { - quote! { - let #object_variant_js_value_result_var_name = - object.get(stringify!(#variant_name), context); - - if let Ok(#object_variant_js_value_var_name) = - #object_variant_js_value_result_var_name - { - if #object_variant_js_value_var_name.is_undefined() == false { - return Ok(#enum_name::#variant_name); - } - } - } - } else { - quote! { - let #object_variant_js_value_result_var_name = - object.get(stringify!(#variant_name), context); - - if let Ok(#object_variant_js_value_var_name) = - #object_variant_js_value_result_var_name - { - if #object_variant_js_value_var_name.is_undefined() == false { - return Ok(#enum_name::#variant_name( - #object_variant_js_value_var_name - .try_from_vm_value(&mut *context) - .map_err(|err| { - let cause = #property_is_not_of_variant_type_error_message.to_js_error(Some(err)); - - #value_is_not_of_enum_type_error_message.to_js_error(Some(cause)) - })? - )); - } - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_struct.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_struct.rs deleted file mode 100644 index 65a2916698..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_struct.rs +++ /dev/null @@ -1,278 +0,0 @@ -use proc_macro2::{Ident, Span, TokenStream}; -use quote::{format_ident, quote}; -use syn::{DataStruct, Error, Fields, Generics, Index}; - -use crate::{ - derive_try_from_vm_value::derive_try_from_vm_value_vec, traits::TryGetStructFieldIdent, -}; - -pub fn generate( - struct_name: &Ident, - data_struct: &DataStruct, - generics: &Generics, -) -> Result { - let value_is_not_of_struct_type_error_message = derive_error_message(struct_name); - - let properties = derive_properties(struct_name, data_struct)?; - - let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - let try_from_vm_value_vec_impl = derive_try_from_vm_value_vec::generate(struct_name, generics); - - Ok(quote! { - impl #impl_generics CdkActTryFromVmValue< - #struct_name #ty_generics, - boa_engine::JsError, - &mut boa_engine::Context<'_> - > - for boa_engine::JsValue - #where_clause - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context - ) -> Result<#struct_name #ty_generics, boa_engine::JsError> { - let object = self - .as_object() - .ok_or_else(|| { - let cause = "TypeError: Value is not an object".to_js_error(None); - - #value_is_not_of_struct_type_error_message.to_js_error(Some(cause)) - })?; - - #properties - } - } - - #try_from_vm_value_vec_impl - }) -} - -fn derive_error_message(struct_name: &Ident) -> String { - let struct_name_string = struct_name.to_string(); - - format!("TypeError: Value is not of type '{}'", &struct_name_string) -} - -fn derive_properties(struct_name: &Ident, data_struct: &DataStruct) -> Result { - let value_is_not_of_struct_type_error_message = derive_error_message(struct_name); - - let field_js_value_result_variable_definitions = - derive_field_js_value_result_variable_definitions(struct_name, data_struct)?; - let field_js_value_result_names = derive_field_js_value_result_names(struct_name, data_struct)?; - let field_js_value_oks = derive_field_js_value_oks(struct_name, data_struct)?; - - let field_result_variable_definitions = - derive_field_result_variable_definitions(struct_name, data_struct)?; - let field_result_names = derive_field_result_names(struct_name, data_struct)?; - let field_oks = derive_field_oks(struct_name, data_struct)?; - - let field_initializers = derive_field_initializers(struct_name, data_struct)?; - let struct_instantiation = - derive_struct_instantiation(struct_name, data_struct, &field_initializers)?; - - Ok(quote! { - #(#field_js_value_result_variable_definitions)* - - match (#(#field_js_value_result_names),*) { - (#(#field_js_value_oks),*) => { - #(#field_result_variable_definitions)* - - match (#(#field_result_names),*) { - (#(#field_oks),*) => { - return Ok(#struct_instantiation); - }, - _ => { - let cause = "TypeError: One or more properties are of an incorrect type".to_js_error(None); - - return Err(#value_is_not_of_struct_type_error_message.to_js_error(Some(cause))); - } - }; - }, - _ => { - return Err( - #value_is_not_of_struct_type_error_message.to_js_error(None) - ); - } - }; - }) -} - -fn uniformly_map_fields( - struct_name: &Ident, - data_struct: &DataStruct, - closure: F, -) -> Result, Error> -where - F: Fn(&Ident) -> TokenStream, -{ - map_fields( - struct_name, - data_struct, - |field_name| closure(field_name), - |field_name, _| closure(field_name), - ) -} - -fn map_fields( - struct_name: &Ident, - data_struct: &DataStruct, - named_field_closure: F, - unnamed_field_closure: G, -) -> Result, Error> -where - F: Fn(&Ident) -> TokenStream, - G: Fn(&Ident, usize) -> TokenStream, -{ - match &data_struct.fields { - Fields::Named(fields_named) => fields_named - .named - .iter() - .enumerate() - .map(|(index, field)| { - let field_name = field.try_get_ident(struct_name, index)?; - - Ok(named_field_closure(field_name)) - }) - .collect::, _>>(), - Fields::Unnamed(field_unnamed) => field_unnamed - .unnamed - .iter() - .enumerate() - .map(|(index, _)| { - let field_name = format_ident!("field_{}", index); - - Ok(unnamed_field_closure(&field_name, index)) - }) - .collect::, _>>(), - Fields::Unit => Err(Error::new( - Span::call_site(), - format!("CdkActTryFromVmValue not supported for unit-like structs"), - )), - } -} - -fn derive_field_js_value_result_variable_definitions( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - map_fields( - struct_name, - data_struct, - |field_name| { - let field_js_value_result_name = format_ident!("object_{}_js_value_result", field_name); - - quote! { - let #field_js_value_result_name = object.get(stringify!(#field_name), context); - } - }, - |field_name, index| { - let field_js_value_result_name = format_ident!("object_{}_js_value_result", field_name); - - let syn_index = Index::from(index); - - quote! { - let #field_js_value_result_name = object.get(stringify!(#syn_index), context); - } - }, - ) -} - -fn derive_field_js_value_result_names( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - uniformly_map_fields(struct_name, data_struct, |field_name| { - let field_js_value_result_name = format_ident!("object_{}_js_value_result", field_name); - - quote! { #field_js_value_result_name } - }) -} - -fn derive_field_js_value_oks( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - uniformly_map_fields(struct_name, data_struct, |field_name| { - let field_js_value_name = format_ident!("object_{}_js_value", field_name); - - quote! { Ok(#field_js_value_name) } - }) -} - -fn derive_field_result_variable_definitions( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - uniformly_map_fields(struct_name, data_struct, |field_name| { - let field_js_value_name = format_ident!("object_{}_js_value", field_name); - let field_result_name = format_ident!("object_{}_result", field_name); - - quote! { let #field_result_name = #field_js_value_name.try_from_vm_value(&mut *context); } - }) -} - -fn derive_field_result_names( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - uniformly_map_fields(struct_name, data_struct, |field_name| { - let field_result_name = format_ident!("object_{}_result", field_name); - - quote! { #field_result_name } - }) -} - -fn derive_field_oks( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - uniformly_map_fields(struct_name, data_struct, |field_name| { - let field_var_name = format_ident!("object_{}", field_name); - - quote! { Ok(#field_var_name) } - }) -} - -fn derive_field_initializers( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - map_fields( - struct_name, - data_struct, - |field_name| { - let field_var_name = format_ident!("object_{}", field_name); - - quote! { #field_name: #field_var_name } - }, - |field_name, _| { - let field_var_name = format_ident!("object_{}", field_name); - - quote! { #field_var_name } - }, - ) -} - -fn derive_struct_instantiation( - struct_name: &Ident, - data_struct: &DataStruct, - field_initializers: &Vec, -) -> Result { - match &data_struct.fields { - Fields::Named(_) => Ok(quote! { - #struct_name { - #(#field_initializers),* - } - }), - Fields::Unnamed(_) => Ok(quote! { - #struct_name ( - #(#field_initializers),* - ) - }), - Fields::Unit => Err(Error::new( - Span::call_site(), - format!("CdkActTryFromVmValue not supported for unit-like structs"), - )), - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_vec.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_vec.rs deleted file mode 100644 index c95843d7bb..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/derive_try_from_vm_value_vec.rs +++ /dev/null @@ -1,54 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; -use quote::quote; -use syn::Generics; - -pub fn generate(name: &Ident, generics: &Generics) -> TokenStream { - let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - quote! { - impl #impl_generics CdkActTryFromVmValue< - Vec<#name #ty_generics>, - boa_engine::JsError, - &mut boa_engine::Context<'_> - > - for boa_engine::JsValue - #where_clause - { - fn try_from_vm_value( - self, - context: &mut boa_engine::Context - ) -> Result, boa_engine::JsError> { - let error_message = "TypeError: Value is not of type 'Vec'"; - - let js_object = self - .as_object() - .ok_or_else(|| error_message.to_js_error(None))?; - - if !js_object.is_array() { - return Err(error_message.to_js_error(None)); - } - - - let mut index: usize = 0; - let mut result = vec![]; - - loop { - let js_value = js_object.get(index, context).map_err(|err| { - error_message.to_js_error(Some(err)) - })?; - - if js_value.is_undefined() { - break; - } - - result.push(js_value - .try_from_vm_value(&mut *context) - .map_err(|variant_err| error_message.to_js_error(Some(variant_err)))?); - index += 1; - } - - Ok(result) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/mod.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/mod.rs deleted file mode 100644 index f93d1df5a6..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_from_vm_value/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod derive_try_from_vm_value_enum; -pub mod derive_try_from_vm_value_struct; -pub mod derive_try_from_vm_value_vec; diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_enum.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_enum.rs deleted file mode 100644 index eea0ce8239..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_enum.rs +++ /dev/null @@ -1,178 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; -use quote::{format_ident, quote}; -use syn::{DataEnum, Error, Field, Fields, Generics}; - -use crate::{derive_try_into_vm_value::derive_try_into_vm_value_vec, traits::TryGetEnumFieldIdent}; - -pub fn generate( - enum_name: &Ident, - data_enum: &DataEnum, - generics: &Generics, -) -> Result { - let variant_branches = derive_variant_branches(&enum_name, &data_enum)?; - - // Capture generic parameters and their bounds - let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - let try_into_vm_value_vec_impl = derive_try_into_vm_value_vec::generate(enum_name, generics); - - Ok(quote! { - impl #impl_generics CdkActTryIntoVmValue< - &mut boa_engine::Context<'_>, - boa_engine::JsValue - > - for #enum_name #ty_generics - #where_clause - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context - ) -> Result { - match self { - #(#variant_branches)*, - } - } - } - - #try_into_vm_value_vec_impl - }) -} - -fn derive_variant_branches( - enum_name: &Ident, - data_enum: &DataEnum, -) -> Result, Error> { - data_enum - .variants - .iter() - .map(|variant| { - let variant_name = &variant.ident; - - match &variant.fields { - Fields::Named(fields_named) => derive_variant_branches_named_fields( - enum_name, - variant_name, - fields_named.named.iter().collect(), - ), - Fields::Unnamed(fields_unnamed) => Ok(derive_variant_branches_unnamed_fields( - enum_name, - variant_name, - fields_unnamed.unnamed.iter().collect(), - )), - Fields::Unit => Ok(derive_variant_branches_unnamed_fields( - enum_name, - variant_name, - vec![], - )), - } - }) - .collect::, _>>() -} - -fn derive_variant_branches_named_fields( - enum_name: &Ident, - variant_name: &Ident, - named_fields: Vec<&Field>, -) -> Result { - let field_names = named_fields - .iter() - .enumerate() - .map(|(field_index, named_field)| { - let field_name = named_field.try_get_ident(enum_name, variant_name, field_index)?; - - Ok(quote! { - #field_name - }) - }) - .collect::, Error>>()?; - - let named_field_variable_declarations = named_fields - .iter() - .enumerate() - .map(|(field_index, named_field)| { - let field_name = named_field.try_get_ident(enum_name, variant_name, field_index)?; - let variable_name = format_ident!("{}_js_value", field_name); - - Ok(quote! { - let #variable_name = #field_name.try_into_vm_value(context)?; - }) - }) - .collect::, Error>>()?; - - let named_field_property_definitions = named_fields - .iter() - .enumerate() - .map(|(field_index, named_field)| { - let field_name = named_field.try_get_ident(enum_name, variant_name, field_index)?; - let variable_name = format_ident!("{}_js_value", field_name); - - Ok(quote! { - .property( - stringify!(#field_name), - #variable_name, - boa_engine::property::Attribute::all() - ) - }) - }) - .collect::, Error>>()?; - - let variant_object_variable_name = format_ident!("{}_js_object", variant_name); - - Ok(quote! { - #enum_name::#variant_name { #(#field_names),* } => { - #(#named_field_variable_declarations)* - - let #variant_object_variable_name = boa_engine::object::ObjectInitializer::new(context) - #(#named_field_property_definitions)* - .build(); - - let object = boa_engine::object::ObjectInitializer::new(context) - .property( - stringify!(#variant_name), - #variant_object_variable_name, - boa_engine::property::Attribute::all() - ) - .build(); - - Ok(object.into()) - } - }) -} - -fn derive_variant_branches_unnamed_fields( - enum_name: &Ident, - variant_name: &Ident, - unnamed_fields: Vec<&Field>, -) -> TokenStream { - if unnamed_fields.len() == 0 { - quote! { - #enum_name::#variant_name => { - let object = boa_engine::object::ObjectInitializer::new(context) - .property( - stringify!(#variant_name), - boa_engine::JsValue::Null, - boa_engine::property::Attribute::all() - ) - .build(); - - Ok(object.into()) - } - } - } else { - quote! { - #enum_name::#variant_name(value) => { - let js_value = value.try_into_vm_value(context)?; - - let object = boa_engine::object::ObjectInitializer::new(context) - .property( - stringify!(#variant_name), - js_value, - boa_engine::property::Attribute::all() - ) - .build(); - - Ok(object.into()) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_struct.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_struct.rs deleted file mode 100644 index 4848e0f454..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_struct.rs +++ /dev/null @@ -1,130 +0,0 @@ -use proc_macro2::{Ident, Span, TokenStream}; -use quote::{format_ident, quote}; -use syn::{DataStruct, Error, Fields, Generics, Index}; - -use crate::{ - derive_try_into_vm_value::derive_try_into_vm_value_vec, traits::TryGetStructFieldIdent, -}; - -pub fn generate( - struct_name: &Ident, - data_struct: &DataStruct, - generics: &Generics, -) -> Result { - let variable_definitions = derive_struct_fields_variable_definitions(struct_name, data_struct)?; - let property_definitions = derive_struct_fields_property_definitions(struct_name, data_struct)?; - - // Capture generic parameters and their bounds - let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - let try_into_vm_value_vec_impl = derive_try_into_vm_value_vec::generate(struct_name, generics); - - Ok(quote! { - impl #impl_generics CdkActTryIntoVmValue< - &mut boa_engine::Context<'_>, - boa_engine::JsValue - > - for #struct_name #ty_generics - #where_clause - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context - ) -> Result { - #(#variable_definitions)* - - let object = boa_engine::object::ObjectInitializer::new(context) - #(#property_definitions)* - .build(); - - Ok(object.into()) - } - } - - #try_into_vm_value_vec_impl - }) -} - -fn derive_struct_fields_variable_definitions( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - match &data_struct.fields { - Fields::Named(fields_named) => fields_named - .named - .iter() - .enumerate() - .map(|(index, field)| { - let field_name = field.try_get_ident(struct_name, index)?; - let variable_name = format_ident!("{}_js_value", field_name); - - Ok(quote! { - let #variable_name = self.#field_name.try_into_vm_value(context)?; - }) - }) - .collect::, Error>>(), - Fields::Unnamed(fields_unnamed) => Ok(fields_unnamed - .unnamed - .iter() - .enumerate() - .map(|(index, _)| { - let variable_name = format_ident!("field_{}_js_value", index); - let syn_index = Index::from(index); - - quote! { - let #variable_name = self.#syn_index.try_into_vm_value(context)?; - } - }) - .collect()), - Fields::Unit => Err(Error::new( - Span::call_site(), - format!("CdkActTryIntoVmValue not supported for unit-like structs"), - )), - } -} - -fn derive_struct_fields_property_definitions( - struct_name: &Ident, - data_struct: &DataStruct, -) -> Result, Error> { - match &data_struct.fields { - Fields::Named(fields_named) => fields_named - .named - .iter() - .enumerate() - .map(|(index, field)| { - let field_name = field.try_get_ident(struct_name, index)?; - let variable_name = format_ident!("{}_js_value", field_name); - - Ok(quote! { - .property( - stringify!(#field_name), - #variable_name, - boa_engine::property::Attribute::all() - ) - }) - }) - .collect::, Error>>(), - Fields::Unnamed(fields_unnamed) => Ok(fields_unnamed - .unnamed - .iter() - .enumerate() - .map(|(index, _)| { - let variable_name = format_ident!("field_{}_js_value", index); - let syn_index = Index::from(index); - - quote! { - .property( - stringify!(#syn_index), - #variable_name, - boa_engine::property::Attribute::all() - ) - } - }) - .collect()), - Fields::Unit => Err(Error::new( - Span::call_site(), - format!("CdkActTryIntoVmValue not supported for unit-like structs"), - )), - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_vec.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_vec.rs deleted file mode 100644 index 0f19ad60db..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/derive_try_into_vm_value_vec.rs +++ /dev/null @@ -1,29 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; -use quote::quote; -use syn::Generics; - -pub fn generate(name: &Ident, generics: &Generics) -> TokenStream { - let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - quote! { - impl #impl_generics CdkActTryIntoVmValue< - &mut boa_engine::Context<'_>, - boa_engine::JsValue - > - for Vec<#name #ty_generics> - #where_clause - { - fn try_into_vm_value( - self, - context: &mut boa_engine::Context - ) -> Result { - let js_values: Vec<_> = self - .into_iter() - .map(|item| item.try_into_vm_value(context)) - .collect::>()?; - - Ok(boa_engine::object::builtins::JsArray::from_iter(js_values, context).into()) - } - } - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/mod.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/mod.rs deleted file mode 100644 index f311f4068f..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/derive_try_into_vm_value/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod derive_try_into_vm_value_enum; -pub mod derive_try_into_vm_value_struct; -pub mod derive_try_into_vm_value_vec; diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/lib.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/lib.rs deleted file mode 100644 index b05436e5ea..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/lib.rs +++ /dev/null @@ -1,62 +0,0 @@ -use proc_macro::TokenStream; -use proc_macro2::Span; -use syn::{parse_macro_input, Data, DeriveInput, Error}; - -use derive_try_from_vm_value::{derive_try_from_vm_value_enum, derive_try_from_vm_value_struct}; -use derive_try_into_vm_value::{derive_try_into_vm_value_enum, derive_try_into_vm_value_struct}; - -mod derive_try_from_vm_value; -mod derive_try_into_vm_value; -mod traits; - -#[proc_macro_derive(CdkActTryIntoVmValue)] -pub fn derive_azle_try_into_vm_value(tokens: TokenStream) -> TokenStream { - let input = parse_macro_input!(tokens as DeriveInput); - - let name = input.ident; - let generics = input.generics; - - let generated_code = match input.data { - Data::Enum(data_enum) => { - derive_try_into_vm_value_enum::generate(&name, &data_enum, &generics) - } - Data::Struct(data_struct) => { - derive_try_into_vm_value_struct::generate(&name, &data_struct, &generics) - } - Data::Union(_) => Err(Error::new( - Span::call_site(), - format!("CdkActTryIntoVmValue not supported for unions"), - )), - }; - - match generated_code { - Ok(code) => TokenStream::from(code), - Err(err) => err.to_compile_error().into(), - } -} - -#[proc_macro_derive(CdkActTryFromVmValue)] -pub fn derive_azle_try_from_vm_value(tokens: TokenStream) -> TokenStream { - let input = parse_macro_input!(tokens as DeriveInput); - - let name = input.ident; - let generics = input.generics; - - let generated_code = match input.data { - Data::Enum(data_enum) => { - derive_try_from_vm_value_enum::generate(&name, &data_enum, &generics) - } - Data::Struct(data_struct) => { - derive_try_from_vm_value_struct::generate(&name, &data_struct, &generics) - } - Data::Union(_) => Err(Error::new( - Span::call_site(), - format!("CdkActTryFromVmValue not supported for unions"), - )), - }; - - match generated_code { - Ok(code) => TokenStream::from(code), - Err(err) => err.to_compile_error().into(), - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/map_to.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/map_to.rs deleted file mode 100644 index 162251baef..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/map_to.rs +++ /dev/null @@ -1,41 +0,0 @@ -use proc_macro2::{Ident, TokenStream}; -use quote::format_ident; -use syn::{Error, Field}; - -use crate::traits::TryGetEnumFieldIdent; - -pub trait MapTo { - fn map_to( - &self, - enum_name: &Ident, - variant_name: &Ident, - callback: T, - ) -> Result, Error> - where - T: Fn(&Ident, Ident) -> TokenStream; -} - -impl MapTo for Vec<&Field> { - fn map_to( - &self, - enum_name: &Ident, - variant_name: &Ident, - callback: T, - ) -> Result, Error> - where - T: Fn(&Ident, Ident) -> TokenStream, - { - let named_field_js_value_result_variable_names = self - .iter() - .enumerate() - .map(|(field_index, named_field)| -> Result { - let field_name = named_field.try_get_ident(enum_name, variant_name, field_index)?; - let variable_name = format_ident!("{}_js_value_result", field_name); - - Ok(callback(&field_name, variable_name)) - }) - .collect::, _>>(); - - named_field_js_value_result_variable_names - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/mod.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/mod.rs deleted file mode 100644 index b2ab217a52..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub use map_to::MapTo; -pub use try_get_enum_field_ident::TryGetEnumFieldIdent; -pub use try_get_struct_field_ident::TryGetStructFieldIdent; - -pub mod map_to; -pub mod try_get_enum_field_ident; -pub mod try_get_struct_field_ident; diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/try_get_enum_field_ident.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/try_get_enum_field_ident.rs deleted file mode 100644 index e4b47339f7..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/try_get_enum_field_ident.rs +++ /dev/null @@ -1,30 +0,0 @@ -use proc_macro2::{Ident, Span}; -use syn::{Error, Field}; - -pub trait TryGetEnumFieldIdent { - fn try_get_ident( - &self, - enum_name: &Ident, - variant_name: &Ident, - field_index: usize, - ) -> Result<&Ident, Error>; -} - -impl TryGetEnumFieldIdent for Field { - fn try_get_ident( - &self, - enum_name: &Ident, - variant_name: &Ident, - field_index: usize, - ) -> Result<&Ident, Error> { - self.ident.as_ref().ok_or_else(|| { - Error::new( - Span::call_site(), - format!( - "Internal Error: expected field {field_index} in \ - {enum_name}::{variant_name} to have a name but received None" - ), - ) - }) - } -} diff --git a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/try_get_struct_field_ident.rs b/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/try_get_struct_field_ident.rs deleted file mode 100644 index fc6308e6fb..0000000000 --- a/src/compiler/typescript_to_rust/azle_vm_value_derive/src/traits/try_get_struct_field_ident.rs +++ /dev/null @@ -1,20 +0,0 @@ -use proc_macro2::{Ident, Span}; -use syn::{Error, Field}; - -pub trait TryGetStructFieldIdent { - fn try_get_ident(&self, struct_name: &Ident, field_index: usize) -> Result<&Ident, Error>; -} - -impl TryGetStructFieldIdent for Field { - fn try_get_ident(&self, struct_name: &Ident, field_index: usize) -> Result<&Ident, Error> { - self.ident.as_ref().ok_or_else(|| { - Error::new( - Span::call_site(), - format!( - "Internal Error: expected field {field_index} in \ - {struct_name} to have a name but received None" - ), - ) - }) - } -} diff --git a/src/compiler/typescript_to_rust/canister_methods/src/lib.rs b/src/compiler/typescript_to_rust/canister_methods/src/lib.rs index 67f6184cc0..882c58bc60 100644 --- a/src/compiler/typescript_to_rust/canister_methods/src/lib.rs +++ b/src/compiler/typescript_to_rust/canister_methods/src/lib.rs @@ -20,8 +20,6 @@ impl ToIdent for String { #[derive(Debug, Serialize, Deserialize)] struct CompilerInfo { - file_names: Vec, - ts_root: String, canister_methods: CanisterMethods, } diff --git a/src/compiler/typescript_to_rust/generate_rust_canister.ts b/src/compiler/typescript_to_rust/generate_rust_canister.ts index 73f97d8335..a72ac79562 100644 --- a/src/compiler/typescript_to_rust/generate_rust_canister.ts +++ b/src/compiler/typescript_to_rust/generate_rust_canister.ts @@ -32,11 +32,6 @@ export function generateRustCanister( canisterMethods: CanisterMethods ): Result { const compilerInfo: CompilerInfo = { - plugins, - file_names: fileNames, - ts_root: join(process.cwd(), canisterConfig.ts), - alias_tables: aliasTables, - alias_lists: aliasLists, // TODO The spread is because canisterMethods is a function with properties canister_methods: { ...canisterMethods diff --git a/src/compiler/typescript_to_rust/index.ts b/src/compiler/typescript_to_rust/index.ts index f5badb3059..34ae1cde63 100644 --- a/src/compiler/typescript_to_rust/index.ts +++ b/src/compiler/typescript_to_rust/index.ts @@ -1,6 +1,4 @@ -import { dirname, join } from 'path'; -import * as ts from 'typescript'; - +import { join } from 'path'; import { compileTypeScriptToJavaScript } from './typescript_to_javascript'; import { generateLibCargoToml, @@ -8,23 +6,18 @@ import { generateWorkspaceCargoToml } from './typescript_to_javascript/cargo_toml_files'; import { writeCodeToFileSystem } from './write_code_to_file_system'; -import { generateRustCanister } from './generate_rust_canister'; -import { generateAliasStructures } from './type_alias_parsing'; import { Err, ok, unwrap } from '../utils/result'; import { - AliasLists, - AliasTables, AzleError, + CompilerInfo, JSCanisterConfig, - Plugin, Toml, TsCompilationError, TsSyntaxErrorLocation } from '../utils/types'; import { time } from '../utils'; -import { match } from '../../lib'; +import { writeFileSync } from 'fs'; import { red, dim } from '../utils/colors'; -import { readFileSync } from 'fs'; import { generateCandidAndCanisterMethods } from '../generate_candid_and_canister_methods'; export async function compileTypeScriptToRust( @@ -59,40 +52,7 @@ export async function compileTypeScriptToRust( canisterConfig.opt_level ?? '0' ); const workspaceCargoLock: Toml = generateWorkspaceCargoLock(); - - const { fileNames, plugins } = getFileNamesAndPlugins( - canisterConfig.ts - ); - - const program = ts.createProgram([canisterConfig.ts], {}); - const aliasTables = generateAliasStructures( - fileNames, - program, - 'TABLE' - ) as AliasTables; - const aliasLists = generateAliasStructures( - fileNames, - program, - 'LIST' - ) as AliasLists; - - const pluginsDependencies = plugins - .map((plugin) => { - const cargoTomlPath = join(plugin.path, 'Cargo.toml'); - - // TODO Toml parser - const cargoTomlString = readFileSync(cargoTomlPath) - .toString() - .replace('[dependencies]', ''); - - return cargoTomlString; - }) - .join(''); - - const libCargoToml: Toml = generateLibCargoToml( - canisterName, - pluginsDependencies - ); + const libCargoToml: Toml = generateLibCargoToml(canisterName, ''); const { candid, canisterMethods } = generateCandidAndCanisterMethods(candidJavaScript); @@ -108,39 +68,17 @@ export async function compileTypeScriptToRust( candid ); - const generateRustCanisterResult = generateRustCanister( - fileNames, - plugins, - aliasTables, - aliasLists, - canisterPath, - canisterConfig, - canisterName, - canisterMethods - ); + const compilerInfo: CompilerInfo = { + // TODO The spread is because canisterMethods is a function with properties + canister_methods: { + ...canisterMethods + } // TODO we should probably just grab the props out that we need + }; - match(generateRustCanisterResult, { - Err: (err) => { - match(err, { - Error: (err) => { - console.error(`Compilation failed: ${err}`); - }, - Signal: (signal) => { - console.error( - `Compilation failed with signal: ${signal}` - ); - }, - Status: (status) => { - console.error( - `Compilation failed with status: ${status}` - ); - } - }); + const compilerInfoPath = join(canisterPath, 'compiler_info.json'); - process.exit(1); - }, - _: () => {} - }); + // TODO why not just write the dfx.json file here as well? + writeFileSync(compilerInfoPath, JSON.stringify(compilerInfo)); if (isCompileOnlyMode()) { console.log('Compilation complete!'); @@ -205,97 +143,3 @@ function generateVisualDisplayOfErrorLocation( )}${marker}`; return `${preciseLocation}\n${previousLine}\n${offendingLine}\n${subsequentLine}`; } - -function getFileNamesAndPlugins(tsPath: string): { - fileNames: string[]; - plugins: Plugin[]; -} { - const program = ts.createProgram([tsPath], {}); - const sourceFiles = program.getSourceFiles(); - - const fileNames = sourceFiles.map((sourceFile) => { - if (!sourceFile.fileName.startsWith('/')) { - return join(process.cwd(), sourceFile.fileName); - } else { - return sourceFile.fileName; - } - }); - - const registerPlugins = findRegisterPlugins(sourceFiles); - - return { - fileNames, - plugins: registerPlugins.map((registerPlugin) => { - return { - path: dirname(registerPlugin.sourceFile.fileName), - register_function: getRustRegisterFunctionName( - registerPlugin.node, - registerPlugin.sourceFile - ) - }; - }) - }; -} - -type RegisterPluginNodeInfo = { - node: ts.CallExpression; - sourceFile: ts.SourceFile; -}; - -function findRegisterPlugins( - sourceFiles: readonly ts.SourceFile[] -): RegisterPluginNodeInfo[] { - return sourceFiles - .filter((sourceFile) => !sourceFile.isDeclarationFile) - .flatMap((sourceFile) => { - const registerPluginNodes = findRegisterPlugin( - sourceFile, - sourceFile - ); - return registerPluginNodes.map((node) => ({ node, sourceFile })); - }); -} - -function findRegisterPlugin( - node: ts.Node, - sourceFile: ts.SourceFile -): ts.CallExpression[] { - if (sourceFile === undefined) { - return []; - } - - const childNodes = node - .getChildren(sourceFile) - .map((child) => findRegisterPlugin(child, sourceFile)) - .reduce((acc, cur) => [...acc, ...cur], []); - - return ts.isCallExpression(node) && - node.expression.getText(sourceFile) === 'registerPlugin' - ? [node, ...childNodes] - : childNodes; -} - -function getRustRegisterFunctionName( - node: ts.CallExpression, - sourceFile: ts.SourceFile -): string { - const [arg] = node.arguments; - if (ts.isObjectLiteralExpression(arg)) { - const rustRegisterFunctionNameProperty = arg.properties.find( - (property) => - ts.isPropertyAssignment(property) && - property.name.getText(sourceFile) === 'rustRegisterFunctionName' - ) as ts.PropertyAssignment | undefined; - - if ( - rustRegisterFunctionNameProperty && - ts.isStringLiteralLike(rustRegisterFunctionNameProperty.initializer) - ) { - return rustRegisterFunctionNameProperty.initializer.text; - } - } - - throw new Error( - 'registerPlugin function must have a rustRegisterFunctionName property with a string literal value' - ); -} diff --git a/src/compiler/typescript_to_rust/typescript_to_javascript/cargo_toml_files.ts b/src/compiler/typescript_to_rust/typescript_to_javascript/cargo_toml_files.ts index f2dddd9978..fc0293648a 100644 --- a/src/compiler/typescript_to_rust/typescript_to_javascript/cargo_toml_files.ts +++ b/src/compiler/typescript_to_rust/typescript_to_javascript/cargo_toml_files.ts @@ -31,9 +31,7 @@ export function generateWorkspaceCargoToml( [workspace] members = [ - "${rootPath}", - "${rootPath}/azle_generate", - "${rootPath}/azle_generate_rearchitecture" + "azle_generate_rearchitecture" ] [profile.release] @@ -68,7 +66,6 @@ export function generateLibCargoToml( getrandom = { version = "=0.2.3", features = ["custom"] } chrono = { version = "0.4.26", default-features = false } serde = "1.0.137" - azle-vm-value-derive = { path = "./azle_vm_value_derive" } uuid = { version = "=1.2.2", features = ["v4"] } rand = "=0.8.5" slotmap = "=1.0.6" diff --git a/src/compiler/typescript_to_rust/write_code_to_file_system.ts b/src/compiler/typescript_to_rust/write_code_to_file_system.ts index a13912027b..9d19df476d 100644 --- a/src/compiler/typescript_to_rust/write_code_to_file_system.ts +++ b/src/compiler/typescript_to_rust/write_code_to_file_system.ts @@ -16,62 +16,30 @@ export function writeCodeToFileSystem( mkdirSync(canisterPath, { recursive: true }); writeFileSync(`${canisterPath}/Cargo.toml`, workspaceCargoToml); - writeFileSync(`${canisterPath}/Cargo.lock`, workspaceCargoLock); - if (!existsSync(`${canisterPath}/${rootPath}`)) { - mkdirSync(`${canisterPath}/${rootPath}`, { recursive: true }); - } - - writeFileSync(`${canisterPath}/${rootPath}/Cargo.toml`, libCargoToml); - - if (!existsSync(`${canisterPath}/${rootPath}/src`)) { - mkdirSync(`${canisterPath}/${rootPath}/src`); - } - - if (!existsSync(`${canisterPath}/${rootPath}/src/lib.rs`)) { - writeFileSync(`${canisterPath}/${rootPath}/src/lib.rs`, ''); - } - - if (!existsSync(`${canisterPath}/${rootPath}/azle_vm_value_derive`)) { - mkdirSync(`${canisterPath}/${rootPath}/azle_vm_value_derive`); - } - - copySync( - `${__dirname}/azle_vm_value_derive`, - `${canisterPath}/${rootPath}/azle_vm_value_derive` - ); - - if (!existsSync(`${canisterPath}/${rootPath}/azle_generate`)) { - mkdirSync(`${canisterPath}/${rootPath}/azle_generate`); - } - - copySync( - `${__dirname}/azle_generate`, - `${canisterPath}/${rootPath}/azle_generate` - ); + // TODO not sure what to do about the cargo.lock + // writeFileSync(`${canisterPath}/Cargo.lock`, workspaceCargoLock); - if ( - !existsSync(`${canisterPath}/${rootPath}/azle_generate_rearchitecture`) - ) { - mkdirSync(`${canisterPath}/${rootPath}/azle_generate_rearchitecture`); + if (!existsSync(`${canisterPath}/azle_generate_rearchitecture`)) { + mkdirSync(`${canisterPath}/azle_generate_rearchitecture`); } copySync( `${__dirname}/azle_generate_rearchitecture`, - `${canisterPath}/${rootPath}/azle_generate_rearchitecture` + `${canisterPath}/azle_generate_rearchitecture` ); - if (!existsSync(`${canisterPath}/${rootPath}/canister_methods`)) { - mkdirSync(`${canisterPath}/${rootPath}/canister_methods`); + if (!existsSync(`${canisterPath}/canister_methods`)) { + mkdirSync(`${canisterPath}/canister_methods`); } copySync( `${__dirname}/canister_methods`, - `${canisterPath}/${rootPath}/canister_methods` + `${canisterPath}/canister_methods` ); writeFileSync( - `${canisterPath}/${rootPath}/azle_generate_rearchitecture/src/main.js`, + `${canisterPath}/azle_generate_rearchitecture/src/main.js`, mainJs ); diff --git a/src/compiler/utils/types.ts b/src/compiler/utils/types.ts index b3a3e1a418..63a081df76 100644 --- a/src/compiler/utils/types.ts +++ b/src/compiler/utils/types.ts @@ -37,11 +37,6 @@ export type JSCanisterConfig = Readonly<{ export type OptLevel = '0' | '1' | '2' | '3' | '4'; export type CompilerInfo = { - plugins: Plugin[]; - alias_tables: AliasTables; - alias_lists: AliasLists; - file_names: string[]; - ts_root: string; canister_methods: CanisterMethods; };