diff --git a/.circleci/config.yml b/.circleci/config.yml
index b88b45f..74b2ecb 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -15,17 +15,13 @@ jobs:
rustup toolchain install nightly-2021-02-27
rustup default nightly-2021-02-27
rustup override set nightly-2021-02-27
- rustup target add wasm32-wasi
rustup component add rustfmt
rustup component add clippy
cargo fmt --all -- --check --color always
+ cargo build
+ (cd crates/marine-test-macro-impl; cargo test)
- (cd sdk; cargo build -v --target wasm32-wasi --all-features)
- (cd sdk; cargo clippy -v --target wasm32-wasi)
- (cd sdk-test; cargo build)
- (cd crates/marine-macro-impl; cargo test)
-
- TARGET=wasm32-wasi cargo test -v --all-features
+ cargo test -v --all-features
- save_cache:
paths:
diff --git a/.github/workflows/publish_release.yml b/.github/workflows/publish_release.yml
index 4b9a164..0414743 100644
--- a/.github/workflows/publish_release.yml
+++ b/.github/workflows/publish_release.yml
@@ -46,10 +46,10 @@ jobs:
- name: Login to crates.io
run: cargo login ${{ secrets.CRATES_IO_TOKEN }}
- - name: Save marine-rs-sdk's crate version to env
+ - name: Save marine-rs-sdk-test's crate version to env
run: |
set -x
- PKG_NAME=marine-rs-sdk
+ PKG_NAME=marine-rs-sdk-test
VERSION=$(cargo ws list -l | grep "$PKG_NAME\s" | head -n1 | awk '{ print $2 }')
echo "VERSION=$VERSION" | tee -a $GITHUB_ENV
echo "PKG_NAME=$PKG_NAME" | tee -a $GITHUB_ENV
@@ -65,7 +65,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ env.VERSION }}
- release_name: Marine Rust SDK ${{ env.VERSION }}
+ release_name: Marine Test Rust SDK ${{ env.VERSION }}
body: |
- [${{ env.VERSION }} @ crates.io](https://crates.io/crates/${{ env.PKG_NAME }}/${{ env.VERSION }})
draft: false
diff --git a/sdk-test/CHANGELOG.md b/CHANGELOG.md
similarity index 100%
rename from sdk-test/CHANGELOG.md
rename to CHANGELOG.md
diff --git a/Cargo.lock b/Cargo.lock
index ffa826d..68f7ec9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2,15 +2,6 @@
# It is not intended for manual editing.
version = 3
-[[package]]
-name = "ansi_term"
-version = "0.12.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
-dependencies = [
- "winapi",
-]
-
[[package]]
name = "anyhow"
version = "1.0.43"
@@ -29,17 +20,6 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b"
-[[package]]
-name = "atty"
-version = "0.2.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
-dependencies = [
- "hermit-abi",
- "libc",
- "winapi",
-]
-
[[package]]
name = "autocfg"
version = "1.0.1"
@@ -145,17 +125,6 @@ version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "475bd7aa7680b4ed8f6bb59745e882bcbaeb39326532bb79ffb1716480d9a274"
-[[package]]
-name = "colored"
-version = "1.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f4ffc801dacf156c5854b9df4f425a626539c3a6ef7893cc0c5084a23f0b6c59"
-dependencies = [
- "atty",
- "lazy_static",
- "winapi",
-]
-
[[package]]
name = "constant_time_eq"
version = "0.1.5"
@@ -321,12 +290,6 @@ dependencies = [
"syn",
]
-[[package]]
-name = "diff"
-version = "0.1.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e25ea47919b1560c4e3b7fe0aaab9becf5b84a10325ddf7db0f0ba5e1026499"
-
[[package]]
name = "digest"
version = "0.8.1"
@@ -407,8 +370,8 @@ dependencies = [
"itertools 0.9.0",
"log",
"marine-module-interface",
- "marine-rs-sdk 0.6.11",
- "marine-rs-sdk-main 0.6.10",
+ "marine-rs-sdk",
+ "marine-rs-sdk-main",
"marine-runtime",
"marine-utils",
"safe-transmute",
@@ -707,7 +670,7 @@ dependencies = [
"cargo_toml",
"it-lilo",
"marine-it-parser",
- "marine-macro-impl 0.6.10",
+ "marine-macro-impl",
"once_cell",
"serde",
"serde_json",
@@ -751,14 +714,7 @@ version = "0.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd64d5febc6b2ed709a4461c510c1429dc6e4cfcbd6ca0d88463911630acd67b"
dependencies = [
- "marine-macro-impl 0.6.10",
-]
-
-[[package]]
-name = "marine-macro"
-version = "0.6.13"
-dependencies = [
- "marine-macro-impl 0.6.13",
+ "marine-macro-impl",
]
[[package]]
@@ -775,23 +731,11 @@ dependencies = [
"uuid",
]
-[[package]]
-name = "marine-macro-impl"
-version = "0.6.13"
-dependencies = [
- "marine-macro-testing-utils",
- "pretty_assertions",
- "proc-macro2",
- "quote",
- "serde",
- "serde_json",
- "syn",
- "uuid",
-]
-
[[package]]
name = "marine-macro-testing-utils"
version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c7b78534db4804dab7e439ae93fc2478bb298a97819bbc50002187ef02f2df5"
dependencies = [
"proc-macro2",
"quote",
@@ -806,7 +750,7 @@ checksum = "b4a0951d77c38171d8b2ddcc888d1153a2c4f777b3b7a7dca093a06c69b32d77"
dependencies = [
"anyhow",
"chrono",
- "marine-rs-sdk-main 0.6.10",
+ "marine-rs-sdk-main",
"semver 0.11.0",
"serde",
"thiserror",
@@ -838,23 +782,12 @@ version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9157bae63a4bbdd7a29984f6ded08f8ed72991b83ca3bdd59d2f889fa8b8ea02"
dependencies = [
- "marine-macro 0.6.10",
- "marine-rs-sdk-main 0.6.10",
- "marine-timestamp-macro 0.6.10",
+ "marine-macro",
+ "marine-rs-sdk-main",
+ "marine-timestamp-macro",
"serde",
]
-[[package]]
-name = "marine-rs-sdk"
-version = "0.6.13"
-dependencies = [
- "marine-macro 0.6.13",
- "marine-rs-sdk-main 0.6.13",
- "marine-timestamp-macro 0.6.13",
- "serde",
- "trybuild",
-]
-
[[package]]
name = "marine-rs-sdk-main"
version = "0.6.10"
@@ -862,21 +795,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95c49b5893d8689589219e07cf67421cc415dc5f219ad0e9c197a9a050b5dd4f"
dependencies = [
"log",
- "marine-macro 0.6.10",
+ "marine-macro",
"serde",
]
-[[package]]
-name = "marine-rs-sdk-main"
-version = "0.6.13"
-dependencies = [
- "lazy_static",
- "log",
- "marine-macro 0.6.13",
- "serde",
- "simple_logger",
-]
-
[[package]]
name = "marine-rs-sdk-test"
version = "0.3.0"
@@ -957,14 +879,6 @@ dependencies = [
"quote",
]
-[[package]]
-name = "marine-timestamp-macro"
-version = "0.6.13"
-dependencies = [
- "chrono",
- "quote",
-]
-
[[package]]
name = "marine-utils"
version = "0.2.0"
@@ -1064,15 +978,6 @@ version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
-[[package]]
-name = "output_vt100"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53cdc5b785b7a58c5aad8216b3dfa114df64b0b06ae6e1501cef91df2fbdf8f9"
-dependencies = [
- "winapi",
-]
-
[[package]]
name = "page_size"
version = "0.4.2"
@@ -1128,18 +1033,6 @@ dependencies = [
"ucd-trie",
]
-[[package]]
-name = "pretty_assertions"
-version = "0.7.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1cab0e7c02cf376875e9335e0ba1da535775beb5450d21e1dffca068818ed98b"
-dependencies = [
- "ansi_term",
- "ctor",
- "diff",
- "output_vt100",
-]
-
[[package]]
name = "proc-macro-error"
version = "1.0.4"
@@ -1344,19 +1237,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "simple_logger"
-version = "1.13.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b7de33c687404ec3045d4a0d437580455257c0436f858d702f244e7d652f9f07"
-dependencies = [
- "atty",
- "chrono",
- "colored",
- "log",
- "winapi",
-]
-
[[package]]
name = "smallvec"
version = "1.6.1"
diff --git a/Cargo.toml b/Cargo.toml
index 761da89..4f3d6bb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,11 +1,35 @@
+[package]
+name = "marine-rs-sdk-test"
+version = "0.3.0" # remember to update html_root_url
+description = "Backend SDK that allows testing modules for the Marine runtime"
+documentation = "https://docs.rs/marine-rs-sdk-test"
+repository = "https://github.com/fluencelabs/marine-rs-sdk-test"
+authors = ["Fluence Labs"]
+keywords = ["fluence", "marine", "sdk", "webassembly", "test"]
+categories = ["api-bindings", "wasm", "development-tools::testing"]
+license = "Apache-2.0"
+edition = "2018"
+
+[package.metadata.docs.rs]
+all-features = true
+
+[lib]
+path = "src/lib.rs"
+doctest = false
+
+[dev-dependencies]
+trybuild = "1.0"
+
+[dependencies]
+marine-test-macro = { path = "crates/marine-test-macro", version = "=0.3.0" }
+fluence-app-service = { version = "0.9.0", features = ["raw-module-api"] }
+
+serde = { version = "1.0.118", features = ["derive"] }
+serde_json = "1.0.64"
+uuid = { version = "0.8.2", features = ["v4"] }
+
[workspace]
members = [
- "crates/main",
- "crates/marine-macro",
- "crates/marine-macro-impl",
- "crates/marine-test-macro",
- "crates/marine-test-macro-impl",
- "crates/timestamp-macro",
- "sdk",
- "sdk-test"
- ]
+ "crates/marine-test-macro",
+ "crates/marine-test-macro-impl",
+ ]
\ No newline at end of file
diff --git a/README.md b/README.md
index 1a20c52..c15a109 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,4 @@
-
+[](https://crates.io/crates/marine-rs-sdk-test)
-## Marine Rust SDK
-
-This SDK is intended to run backend application on the Fluence network with [Marine](https://github.com/fluencelabs/marine) runtime. More information about usage and some internals could found in [docs](https://doc.fluence.dev/docs/knowledge_knowledge/knowledge_aquamarine/marine/marine-rs-sdk).
+## Marine Test Rust SDK
+This SDK is intended to test application built with [Marine Rust SDK](https://github.com/fluencelabs/marine-rs-sdk). More information about usage and some internals could found in [docs](https://doc.fluence.dev/docs/knowledge_knowledge/knowledge_aquamarine/marine/marine-rs-sdk).
diff --git a/crates/macro-testing-utils/Cargo.toml b/crates/macro-testing-utils/Cargo.toml
deleted file mode 100644
index 54b876b..0000000
--- a/crates/macro-testing-utils/Cargo.toml
+++ /dev/null
@@ -1,21 +0,0 @@
-[package]
-name = "marine-macro-testing-utils"
-version = "0.1.0"
-edition = "2018"
-description = "Some functions for testing procedural macros"
-documentation = "https://docs.rs/fluence/marine-macro-testing-utils"
-repository = "https://github.com/fluencelabs/marine-rs-sdk/tree/master/crates/marine-macro-testing-utils"
-authors = ["Fluence Labs"]
-keywords = ["fluence", "marine", "sdk", "webassembly"]
-categories = ["development-tools::testing"]
-license = "Apache-2.0"
-
-[lib]
-path = "src/lib.rs"
-crate-type = ["rlib"]
-doctest = false
-
-[dependencies]
-quote = "1.0.9"
-proc-macro2 = "1.0.26"
-syn = { version = '1.0.64', features = ['full'] }
diff --git a/crates/macro-testing-utils/src/lib.rs b/crates/macro-testing-utils/src/lib.rs
deleted file mode 100644
index d3af384..0000000
--- a/crates/macro-testing-utils/src/lib.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2021 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use std::io::Read;
-use std::path::Path;
-
-pub fn stream_from_file
(path: P) -> proc_macro2::TokenStream
-where
- P: AsRef,
-{
- let items = items_from_file(path);
- quote::quote! { #(#items)* }
-}
-
-pub fn items_from_file(path: P) -> Vec
-where
- P: AsRef,
-{
- let mut file = std::fs::File::open(path).expect("Unable to open file");
-
- let mut src = String::new();
- file.read_to_string(&mut src).expect("Unable to read file");
-
- let token_file = syn::parse_file(&src).expect("Unable to parse file");
- token_file.items
-}
-
-pub fn to_syn_item(token_stream: proc_macro2::TokenStream) -> Vec {
- let file: syn::File = syn::parse2(token_stream).expect("token stream should be parsed");
- file.items
-}
diff --git a/crates/main/Cargo.toml b/crates/main/Cargo.toml
deleted file mode 100644
index 8478219..0000000
--- a/crates/main/Cargo.toml
+++ /dev/null
@@ -1,36 +0,0 @@
-[package]
-name = "marine-rs-sdk-main"
-version = "0.6.13" # remember to update html_root_url
-edition = "2018"
-description = "Contains logger, allocators and several other modules for marine-rs-sdk"
-documentation = "https://docs.rs/marine-rs-sdk-main"
-repository = "https://github.com/fluencelabs/marine-rs-sdk/tree/master/crates/main"
-authors = ["Fluence Labs"]
-keywords = ["fluence", "marine", "sdk", "webassembly"]
-categories = ["api-bindings", "wasm"]
-license = "Apache-2.0"
-
-[package.metadata.docs.rs]
-all-features = true
-
-[lib]
-path = "src/lib.rs"
-crate-type = ["rlib"]
-doctest = false
-
-[dependencies]
-marine-macro = { path = "../marine-macro", version = "=0.6.13" }
-
-log = { version = "0.4.8", features = ["std"] }
-serde = "1.0.118"
-
-[dev-dependencies]
-simple_logger = "1.6.0" # used in doc test
-lazy_static = "1.4.0" # used in doc test
-
-[features]
-# Print some internal logs by log_utf8_string
-debug = []
-
-# Enable logger (this will cause log_utf8_string to appear in imports)
-logger = []
diff --git a/crates/main/src/export_allocator.rs b/crates/main/src/export_allocator.rs
deleted file mode 100644
index 3facb54..0000000
--- a/crates/main/src/export_allocator.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/// Allocates memory area of specified size and type and returns its address.
-/// The allocated memory region is intended to be use as a Vec.
-#[no_mangle]
-pub unsafe fn allocate(elem_count: usize, elem_ty: usize) -> usize {
- if elem_count == 0 {
- // otherwise 1 would be returned due to the internals of Vec in Rust
- return 0;
- }
-
- let allocated_mem = allocate_impl(elem_count, elem_ty);
- crate::debug_log!(format!(
- "sdk.allocate: {} {} -> {}\n",
- elem_count, elem_ty, allocated_mem
- ));
-
- allocated_mem
-}
-
-fn allocate_impl(elem_count: usize, elem_ty: usize) -> usize {
- match elem_ty {
- 0 => allocate_vec::(elem_count), // for booleans
- 1 => allocate_vec::(elem_count),
- 2 => allocate_vec::(elem_count),
- 3 => allocate_vec::(elem_count),
- 4 => allocate_vec::(elem_count),
- 5 => allocate_vec::(elem_count),
- 6 => allocate_vec::(elem_count),
- 7 => allocate_vec::(elem_count),
- 8 => allocate_vec::(elem_count),
- 9 => allocate_vec::(elem_count),
- 10 => allocate_vec::(elem_count),
- _ => 0,
- }
-}
-
-fn allocate_vec(count: usize) -> usize {
- // TODO: handle OOM
- // This allocation scheme with vectors is needed to deal with internal Vec layout
- let vec = Vec::::with_capacity(count);
- let offset = vec.as_ptr() as usize;
- std::mem::forget(vec);
-
- offset
-}
diff --git a/crates/main/src/lib.rs b/crates/main/src/lib.rs
deleted file mode 100644
index 8dba853..0000000
--- a/crates/main/src/lib.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2018 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//! The main part of Fluence backend SDK. Contains `export_allocator`, `logger` and `result`
-//! modules.
-
-#![allow(clippy::missing_safety_doc)]
-#![allow(clippy::needless_doctest_main)]
-#![doc(html_root_url = "https://docs.rs/marine-rs-sdk-main/0.6.13")]
-#![deny(
- dead_code,
- nonstandard_style,
- unused_imports,
- unused_mut,
- unused_variables,
- unused_unsafe,
- unreachable_patterns
-)]
-#![warn(rust_2018_idioms)]
-
-mod export_allocator;
-#[cfg(any(feature = "debug", feature = "logger"))]
-mod logger;
-mod module_manifest;
-mod result;
-mod sdk_version_embedder;
-
-pub use export_allocator::allocate;
-
-#[cfg(feature = "logger")]
-pub use logger::WasmLoggerBuilder;
-#[cfg(feature = "logger")]
-pub use logger::TargetMap;
-#[cfg(feature = "logger")]
-pub use logger::WASM_LOG_ENV_NAME;
-
-pub use result::get_result_ptr;
-pub use result::get_result_size;
-pub use result::set_result_ptr;
-pub use result::set_result_size;
-pub use result::release_objects;
-pub use result::add_object_to_release;
-
-pub use module_manifest::MANIFEST_SECTION_NAME;
-pub use sdk_version_embedder::VERSION_SECTION_NAME;
-
-// these logs will be printed only if debug feature is enabled
-#[macro_export]
-macro_rules! debug_log {
- ($msg_generator:expr) => {
- #[cfg(feature = "debug")]
- {
- let level = log::Level::Info as i32;
- let target = 0i32;
- let msg = $msg_generator;
- crate::logger::log_utf8_string(level, target, msg.as_ptr() as i32, msg.len() as i32);
- }
- };
-}
diff --git a/crates/main/src/logger.rs b/crates/main/src/logger.rs
deleted file mode 100644
index 38ad1dc..0000000
--- a/crates/main/src/logger.rs
+++ /dev/null
@@ -1,349 +0,0 @@
-/*
- * Copyright 2018 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//! This module allows log messages from the Wasm side. It is implemented as a logging facade for
-//! crate [`log`].
-//!
-//! # Examples
-//!
-//! This example initializes [`WasmLogger`] with setting log level.
-//! Macros from crate [`log`] are used as a logging facade.
-//!
-//! ```ignore
-//! use marine_rs_sdk::logger;
-//! use log::{error, trace};
-//! use simple_logger;
-//!
-//! fn main() {
-//! logger::WasmLoggerBuilder::new()
-//! .with_log_leve(log::Level::Info)
-//! .build()
-//! .unwrap();
-//!
-//! error!("This message will be logged.");
-//! trace!("This message will not be logged.");
-//! }
-//!
-//! ```
-//!
-//! [`WasmLogger`]: struct.WasmLogger.html
-//! [`log`]: https://docs.rs/log
-
-use log::LevelFilter;
-use std::collections::HashMap;
-
-/// By default, logger will be initialized with log level from this environment variable.
-pub const WASM_LOG_ENV_NAME: &str = "WASM_LOG";
-
-/// If WASM_LOG_ENV isn't set, then this level will be used as the default.
-const WASM_DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::Info;
-
-/// Mapping from logging namespace string to its bitmask.
-/// TODO: use i64 for bitmask when wasmpack/bindgen issue with i64 is fixed.
-/// Currently, i64 doesn't work on some versions of V8 because log_utf8_string function
-/// isn't marked as #[wasm_bindgen]. In result, TS/JS code throws 'TypeError' on every log.
-pub type TargetMap = HashMap<&'static str, i32>;
-
-/// This structure is used to save information about particular log level for a particular module.
-#[derive(Debug)]
-struct LogDirective {
- module_name: String,
- level: LevelFilter,
-}
-
-impl LogDirective {
- pub fn new(module_name: String, level: LevelFilter) -> Self {
- Self { module_name, level }
- }
-}
-
-/// The Wasm Logger.
-///
-/// This struct implements the [`Log`] trait from the [`log`] crate, which allows it to act as a
-/// logger.
-///
-/// Builder pattern is used here for logger initialization. Please be aware that build must be called
-/// to set the logger up.
-///
-/// [log-crate-url]: https://docs.rs/log/
-/// [`Log`]: https://docs.rs/log/0.4.11/log/trait.Log.html
-struct WasmLogger {
- target_map: TargetMap,
- modules_directives: Vec,
- default_log_level: LevelFilter,
-}
-
-/// The Wasm logger builder.
-///
-/// Build logger for the Fluence network, allows specifying target map and log level while building.
-pub struct WasmLoggerBuilder {
- wasm_logger: WasmLogger,
-}
-
-impl WasmLoggerBuilder {
- /// Initializes a builder of the global logger. Set log level based on the WASM_LOG environment variable if it set,
- /// or [[WASM_DEFAULT_LOG_LEVEL]] otherwise. It is an initial method in this builder chain, please note,
- /// that logger wouldn't work without subsequent build() call.
- pub fn new() -> Self {
- use std::str::FromStr;
-
- let default_log_level = std::env::var(WASM_LOG_ENV_NAME)
- .map_or(WASM_DEFAULT_LOG_LEVEL, |log_level_str| {
- LevelFilter::from_str(&log_level_str).unwrap_or(WASM_DEFAULT_LOG_LEVEL)
- });
-
- let wasm_logger = WasmLogger {
- target_map: HashMap::new(),
- modules_directives: Vec::new(),
- default_log_level,
- };
-
- Self { wasm_logger }
- }
-
- /// Set the log level.
- pub fn with_log_level(mut self, level: LevelFilter) -> Self {
- self.wasm_logger.default_log_level = level;
- self
- }
-
- /// Set mapping between logging targets and numbers.
- /// Used to efficiently enable & disable logs per target on the host.
- pub fn with_target_map(mut self, map: TargetMap) -> Self {
- self.wasm_logger.target_map = map;
- self
- }
-
- pub fn filter(mut self, module_name: impl Into, level: LevelFilter) -> Self {
- let module_name = module_name.into();
- let log_directive = LogDirective::new(module_name, level);
-
- self.wasm_logger.modules_directives.push(log_directive);
- self
- }
-
- /// Build the real logger.
- ///
- /// This method is a last one in this builder chain and MUST be called to set logger up.
- /// Returns a error
- ///
- /// ```ignore
- /// # use marine_rs_sdk::logger;
- /// # use log::info;
- /// #
- /// # fn main() {
- /// logger::WasmLoggerBuilder::new()
- /// .with_log_level(log::LevelFilter::Trace)
- /// .with_target_map(<_>::default())
- /// .build()
- /// .unwrap();
- /// # }
- /// ```
- pub fn build(mut self) -> Result<(), log::SetLoggerError> {
- let max_level = self.max_log_level();
- self.sort_directives();
-
- let Self { wasm_logger } = self;
-
- log::set_boxed_logger(Box::new(wasm_logger))?;
- log::set_max_level(max_level);
- Ok(())
- }
-
- /// Sort supplied directive ny length of module names to make more efficient lookup at runtime.
- fn sort_directives(&mut self) {
- self.wasm_logger.modules_directives.sort_by(|l, r| {
- let llen = l.module_name.len();
- let rlen = r.module_name.len();
-
- rlen.cmp(&llen)
- });
- }
-
- fn max_log_level(&self) -> log::LevelFilter {
- let default_level = self.wasm_logger.default_log_level;
- let max_filter_level = self
- .wasm_logger
- .modules_directives
- .iter()
- .map(|d| d.level)
- .max()
- .unwrap_or(LevelFilter::Off);
-
- std::cmp::max(default_level, max_filter_level)
- }
-}
-
-impl log::Log for WasmLogger {
- #[inline]
- fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
- let target = metadata.target();
-
- for directive in self.modules_directives.iter() {
- if target.starts_with(&directive.module_name) {
- return metadata.level() <= directive.level;
- }
- }
-
- metadata.level() <= self.default_log_level
- }
-
- #[inline]
- fn log(&self, record: &log::Record<'_>) {
- if !self.enabled(record.metadata()) {
- return;
- }
-
- let level = record.metadata().level() as i32;
- let default_target = 0;
- let target = *self
- .target_map
- .get(record.metadata().target())
- .unwrap_or(&default_target);
- let msg = record.args().to_string();
-
- log_utf8_string(level, target, msg.as_ptr() as _, msg.len() as _);
- }
-
- // in our case flushing is performed by a host itself
- #[inline]
- fn flush(&self) {}
-}
-
-#[cfg(target_arch = "wasm32")]
-pub fn log_utf8_string(level: i32, target: i32, msg_ptr: i32, msg_size: i32) {
- unsafe { log_utf8_string_impl(level, target, msg_ptr, msg_size) };
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-pub fn log_utf8_string(level: i32, target: i32, msg_ptr: i32, msg_size: i32) {
- use std::str::from_utf8_unchecked;
- use core::slice::from_raw_parts;
-
- let level = level_from_i32(level);
- let msg = unsafe { from_utf8_unchecked(from_raw_parts(msg_ptr as _, msg_size as _)) };
- println!("[{}] {} {}", level, target, msg);
-}
-
-/// TODO: mark `log_utf8_string_impl` as #[wasm_bindgen], so it is polyfilled by bindgen
-/// log_utf8_string should be provided directly by a host.
-#[cfg(target_arch = "wasm32")]
-#[link(wasm_import_module = "host")]
-extern "C" {
- // Writes a byte string of size bytes that starts from ptr to a logger
- #[link_name = "log_utf8_string"]
- fn log_utf8_string_impl(level: i32, target: i32, msg_ptr: i32, msg_size: i32);
-}
-
-#[allow(dead_code)]
-fn level_from_i32(level: i32) -> log::Level {
- match level {
- 1 => log::Level::Error,
- 2 => log::Level::Warn,
- 3 => log::Level::Info,
- 4 => log::Level::Debug,
- 5 => log::Level::Trace,
- _ => log::Level::max(),
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::WasmLogger;
- use super::LogDirective;
- use super::WasmLoggerBuilder;
- use log::LevelFilter;
- use log::Log;
-
- use std::collections::HashMap;
-
- fn create_metadata(module_name: &str, level: log::Level) -> log::Metadata<'_> {
- log::MetadataBuilder::new()
- .level(level)
- .target(module_name)
- .build()
- }
-
- #[test]
- fn enabled_by_module_name() {
- let module_1_name = "module_1";
- let module_2_name = "module_2";
-
- let modules_directives = vec![
- LogDirective::new(module_1_name.to_string(), LevelFilter::Info),
- LogDirective::new(module_2_name.to_string(), LevelFilter::Warn),
- ];
-
- let logger = WasmLogger {
- target_map: HashMap::new(),
- modules_directives,
- default_log_level: LevelFilter::Error,
- };
-
- let allowed_metadata = create_metadata(module_1_name, log::Level::Info);
- assert!(logger.enabled(&allowed_metadata));
-
- let allowed_metadata = create_metadata(module_1_name, log::Level::Warn);
- assert!(logger.enabled(&allowed_metadata));
-
- let allowed_metadata = create_metadata(module_2_name, log::Level::Warn);
- assert!(logger.enabled(&allowed_metadata));
-
- let not_allowed_metadata = create_metadata(module_1_name, log::Level::Debug);
- assert!(!logger.enabled(¬_allowed_metadata));
-
- let not_allowed_metadata = create_metadata(module_2_name, log::Level::Info);
- assert!(!logger.enabled(¬_allowed_metadata));
- }
-
- #[test]
- fn default_log_level() {
- let modules_directives = vec![LogDirective::new("module_1".to_string(), LevelFilter::Info)];
-
- let logger = WasmLogger {
- target_map: HashMap::new(),
- modules_directives,
- default_log_level: LevelFilter::Warn,
- };
-
- let module_name = "some_module";
- let allowed_metadata = create_metadata(module_name, log::Level::Warn);
- assert!(logger.enabled(&allowed_metadata));
-
- let not_allowed_metadata = create_metadata(module_name, log::Level::Info);
- assert!(!logger.enabled(¬_allowed_metadata));
- }
-
- #[test]
- fn longest_directive_first() {
- let module_1_name = "module_1";
- let module_2_name = "module_1::some_name::func_name";
-
- WasmLoggerBuilder::new()
- .filter(module_1_name, LevelFilter::Info)
- .filter(module_2_name, LevelFilter::Warn)
- .build()
- .unwrap();
-
- let logger = log::logger();
-
- let allowed_metadata = create_metadata(module_1_name, log::Level::Info);
- assert!(logger.enabled(&allowed_metadata));
-
- let not_allowed_metadata = create_metadata(module_2_name, log::Level::Info);
- assert!(!logger.enabled(¬_allowed_metadata));
- }
-}
diff --git a/crates/main/src/module_manifest.rs b/crates/main/src/module_manifest.rs
deleted file mode 100644
index 51b8bca..0000000
--- a/crates/main/src/module_manifest.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// TODO: avoid duplication with the link_section when key-value attributes become stable
-pub const MANIFEST_SECTION_NAME: &str = "__fluence_wasm_module_manifest";
-
-#[macro_export]
-macro_rules! module_manifest {
- ($authors:expr, $version:expr, $description:expr, $repository:expr) => {
- marine_rs_sdk::internal::build_timestamp!();
-
- const __M_SDK_AUTHORS_SIZE: usize = $authors.as_bytes().len();
- const __M_SDK_VERSION_SIZE: usize = $version.as_bytes().len();
- const __M_SDK_DESCRIPTION_SIZE: usize = $description.as_bytes().len();
- const __M_SDK_REPOSITORY_SIZE: usize = $repository.as_bytes().len();
- const __M_SDK_BUILD_TIME_SIZE: usize = __M_SDK_BUILD_TIME.as_bytes().len();
- const __M_SDK_FIELD_PREFIX_SIZE: usize = std::mem::size_of::();
-
- const __M_MANIFEST_SIZE: usize = __M_SDK_AUTHORS_SIZE
- + __M_SDK_VERSION_SIZE
- + __M_SDK_DESCRIPTION_SIZE
- + __M_SDK_REPOSITORY_SIZE
- + __M_SDK_BUILD_TIME_SIZE
- + __M_SDK_FIELD_PREFIX_SIZE * 5;
-
- const fn __m_sdk_append_data(
- mut manifest: [u8; __M_MANIFEST_SIZE],
- data: &'static str,
- offset: usize,
- ) -> ([u8; __M_MANIFEST_SIZE], usize) {
- let data_as_bytes = data.as_bytes();
- let data_len = data_as_bytes.len();
-
- // write data prefix with data size in LE
- let data_len_u64 = data_len as u64;
- let data_len_le_bytes = data_len_u64.to_le_bytes();
- let mut byte_idx = 0;
- while byte_idx < __M_SDK_FIELD_PREFIX_SIZE {
- manifest[offset + byte_idx] = data_len_le_bytes[byte_idx];
- byte_idx += 1;
- }
-
- // write data
- let mut byte_idx = 0;
- while byte_idx < data_len {
- manifest[__M_SDK_FIELD_PREFIX_SIZE + offset + byte_idx] = data_as_bytes[byte_idx];
- byte_idx += 1;
- }
-
- (manifest, offset + __M_SDK_FIELD_PREFIX_SIZE + data_len)
- }
-
- const fn generate_manifest() -> [u8; __M_MANIFEST_SIZE] {
- let manifest: [u8; __M_MANIFEST_SIZE] = [0; __M_MANIFEST_SIZE];
-
- let offset = 0;
- let (manifest, offset) = __m_sdk_append_data(manifest, $authors, offset);
- let (manifest, offset) = __m_sdk_append_data(manifest, $version, offset);
- let (manifest, offset) = __m_sdk_append_data(manifest, $description, offset);
- let (manifest, offset) = __m_sdk_append_data(manifest, $repository, offset);
- let (manifest, _) = __m_sdk_append_data(manifest, __M_SDK_BUILD_TIME, offset);
-
- manifest
- }
-
- #[cfg(target_arch = "wasm32")]
- #[link_section = "__fluence_wasm_module_manifest"]
- #[doc(hidden)]
- pub static __M_WASM_MODULE_MANIFEST: [u8; __M_MANIFEST_SIZE] = generate_manifest();
- };
-
- () => {
- module_manifest!(
- env!("CARGO_PKG_AUTHORS"),
- env!("CARGO_PKG_VERSION"),
- env!("CARGO_PKG_DESCRIPTION"),
- env!("CARGO_PKG_REPOSITORY")
- );
- };
-}
diff --git a/crates/main/src/result.rs b/crates/main/src/result.rs
deleted file mode 100644
index b207b79..0000000
--- a/crates/main/src/result.rs
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//! Contains ad-hoc implementations of returning complex data types from function calls
-//! by two global variables that contain pointer and size. Will be refactored after multi-value
-//! support in Wasmer.
-
-use std::sync::atomic::AtomicUsize;
-use std::cell::RefCell;
-use std::any::Any;
-
-static mut RESULT_PTR: AtomicUsize = AtomicUsize::new(0);
-static mut RESULT_SIZE: AtomicUsize = AtomicUsize::new(0);
-
-thread_local!(static OBJECTS_TO_RELEASE: RefCell>> = RefCell::new(Vec::new()));
-
-#[no_mangle]
-pub unsafe fn get_result_ptr() -> usize {
- crate::debug_log!(format!(
- "sdk.get_result_ptr, returns {}\n",
- *RESULT_PTR.get_mut()
- ));
-
- *RESULT_PTR.get_mut()
-}
-
-#[no_mangle]
-pub unsafe fn get_result_size() -> usize {
- crate::debug_log!(format!(
- "sdk.get_result_size, returns {}\n",
- *RESULT_SIZE.get_mut()
- ));
-
- *RESULT_SIZE.get_mut()
-}
-
-#[no_mangle]
-pub unsafe fn set_result_ptr(ptr: usize) {
- crate::debug_log!(format!("sdk.set_result_ptr: {}\n", ptr));
-
- *RESULT_PTR.get_mut() = ptr;
-}
-
-#[no_mangle]
-pub unsafe fn set_result_size(size: usize) {
- crate::debug_log!(format!("sdk.set_result_size: {}\n", size));
-
- *RESULT_SIZE.get_mut() = size;
-}
-
-#[no_mangle]
-pub unsafe fn release_objects() {
- OBJECTS_TO_RELEASE.with(|objects| {
- let mut objects = objects.borrow_mut();
- while let Some(object) = objects.pop() {
- drop(object);
- }
- })
-}
-
-pub fn add_object_to_release(object: Box) {
- OBJECTS_TO_RELEASE.with(|objects| {
- let mut objects = objects.borrow_mut();
- objects.push(object);
- });
-}
diff --git a/crates/main/src/sdk_version_embedder.rs b/crates/main/src/sdk_version_embedder.rs
deleted file mode 100644
index e1036be..0000000
--- a/crates/main/src/sdk_version_embedder.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#![allow(dead_code)]
-
-const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
-const VERSION_SIZE: usize = PKG_VERSION.len();
-
-const fn sdk_version() -> [u8; VERSION_SIZE] {
- let version_as_slice = PKG_VERSION.as_bytes();
-
- let mut version_as_array: [u8; VERSION_SIZE] = [0; VERSION_SIZE];
- let mut byte_id = 0;
- while byte_id < VERSION_SIZE {
- version_as_array[byte_id] = version_as_slice[byte_id];
- byte_id += 1;
- }
-
- version_as_array
-}
-
-// TODO: avoid duplication with the link_section when key-value attributes become stable
-pub const VERSION_SECTION_NAME: &str = "__fluence_sdk_version";
-
-#[cfg(target_arch = "wasm32")]
-#[link_section = "__fluence_sdk_version"]
-#[doc(hidden)]
-pub static __M_SDK_VERSION: [u8; VERSION_SIZE] = sdk_version();
diff --git a/crates/marine-macro-impl/Cargo.toml b/crates/marine-macro-impl/Cargo.toml
deleted file mode 100644
index 43d3c75..0000000
--- a/crates/marine-macro-impl/Cargo.toml
+++ /dev/null
@@ -1,26 +0,0 @@
-[package]
-name = "marine-macro-impl"
-version = "0.6.13" # remember to update html_root_url
-edition = "2018"
-description = "Implementation of the `#[marine]` macro"
-documentation = "https://docs.rs/fluence/marine-macro-impl"
-repository = "https://github.com/fluencelabs/marine-rs-sdk/tree/master/crates/marine-macro-impl"
-authors = ["Fluence Labs"]
-keywords = ["fluence", "marine", "sdk", "webassembly", "interface-types"]
-categories = ["api-bindings", "wasm"]
-license = "Apache-2.0"
-
-[package.metadata.docs.rs]
-all-features = true
-
-[dependencies]
-quote = "1.0.9"
-proc-macro2 = "1.0.24"
-serde = { version = "1.0.118", features = ["derive"] }
-serde_json = "1.0.56"
-syn = { version = '1.0.64', features = ['full', "extra-traits"] }
-uuid = { version = "0.8.2", features = ["v4"] }
-
-[dev-dependencies]
-pretty_assertions = "0.7.1"
-marine-macro-testing-utils = {path = "../macro-testing-utils"}
diff --git a/crates/marine-macro-impl/src/ast_types.rs b/crates/marine-macro-impl/src/ast_types.rs
deleted file mode 100644
index 805c4cb..0000000
--- a/crates/marine-macro-impl/src/ast_types.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use crate::parsed_type::ParsedType;
-
-#[derive(Clone)]
-pub(crate) struct AstFnArgument {
- pub(crate) name: String,
- pub(crate) ty: ParsedType,
-}
-
-#[derive(Clone)]
-pub(crate) struct AstFnSignature {
- pub(crate) visibility: syn::Visibility,
- pub(crate) name: String,
- pub(crate) arguments: Vec,
- // only one or zero return values are supported now,
- // waiting for adding multi-value support in Wasmer
- pub(crate) output_type: Option,
-}
-
-#[derive(Clone)]
-pub(crate) struct AstRecord {
- pub(crate) name: String,
- pub(crate) fields: AstRecordFields,
- pub(crate) original: syn::ItemStruct,
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub(crate) enum AstRecordFields {
- Named(Vec),
-
- // named and unnamed variants have the same inner field types because of it's easy to handle it,
- // for additional info look at https://github.com/dtolnay/syn/issues/698
- #[allow(dead_code)] // at the moment tuple and unit structs aren't supported
- Unnamed(Vec),
-
- #[allow(dead_code)] // at the moment tuple and unit structs aren't supported
- Unit,
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub(crate) struct AstRecordField {
- /// Name of the field. Can be `None` for tuples.
- pub(crate) name: Option,
- pub(crate) ty: ParsedType,
-}
-
-#[derive(Clone)]
-pub(crate) struct AstExternFn {
- pub(crate) link_name: Option,
- // only imports are possible here
- pub(crate) signature: AstFnSignature,
-}
-
-#[derive(Clone)]
-pub(crate) struct AstExternMod {
- pub(crate) namespace: String,
- // only imports are possible here
- pub(crate) imports: Vec,
-}
-
-#[derive(Clone)]
-pub(crate) struct AstFn {
- pub(crate) signature: AstFnSignature,
- pub(crate) original: syn::ItemFn,
-}
-
-#[derive(Clone)]
-pub(crate) enum MarineAst {
- Function(AstFn),
- ExternMod(AstExternMod),
- Record(AstRecord),
-}
diff --git a/crates/marine-macro-impl/src/export_ast_types.rs b/crates/marine-macro-impl/src/export_ast_types.rs
deleted file mode 100644
index ff8bb83..0000000
--- a/crates/marine-macro-impl/src/export_ast_types.rs
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use crate::parsed_type::ParsedType;
-
-use serde::Serialize;
-use serde::Deserialize;
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct FnArgument {
- pub name: String,
- pub ty: ParsedType,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct FnSignature {
- pub name: String,
- pub arguments: Vec,
- pub output_types: Vec,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct RecordType {
- pub name: String,
- pub fields: RecordFields,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub enum RecordFields {
- Named(Vec),
- // named and unnamed variants have the same inner field types because of it's easy to handle it,
- // for additional info look at https://github.com/dtolnay/syn/issues/698
- Unnamed(Vec),
- Unit,
-}
-
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct RecordField {
- // fields of tuple structs haven't got name
- pub name: Option,
- pub ty: ParsedType,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct ExternFnType {
- pub link_name: Option,
- // only imports are possible here
- pub signature: FnSignature,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct ExternModType {
- pub namespace: String,
- // only imports are possible here
- pub imports: Vec,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct FnType {
- pub signature: FnSignature,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-#[serde(tag = "ast_type")]
-pub enum SDKAst {
- Function(FnType),
- ExternMod(ExternModType),
- Record(RecordType),
-}
-
-use crate::ast_types::{
- AstFn, AstFnSignature, AstFnArgument, AstExternMod, AstExternFn, AstRecordField, AstRecord,
- AstRecordFields,
-};
-
-impl From for SDKAst {
- fn from(ast_fn_item: AstFn) -> Self {
- let fn_item = ast_fn_item.into();
- Self::Function(fn_item)
- }
-}
-
-impl From for SDKAst {
- fn from(ast_extern_mod: AstExternMod) -> Self {
- let extern_mod = ast_extern_mod.into();
- Self::ExternMod(extern_mod)
- }
-}
-
-impl From for SDKAst {
- fn from(ast_record_item: AstRecord) -> Self {
- let record_item = ast_record_item.into();
- Self::Record(record_item)
- }
-}
-
-impl From for FnType {
- fn from(ast_fn_item: AstFn) -> Self {
- let signature = ast_fn_item.signature.into();
-
- Self { signature }
- }
-}
-
-impl From for ExternModType {
- fn from(ast_extern_mod: AstExternMod) -> Self {
- let imports = ast_extern_mod.imports.into_iter().map(Into::into).collect();
-
- Self {
- namespace: ast_extern_mod.namespace,
- imports,
- }
- }
-}
-
-impl From for RecordType {
- fn from(ast_record_item: AstRecord) -> Self {
- Self {
- name: ast_record_item.name,
- fields: ast_record_item.fields.into(),
- }
- }
-}
-
-impl From for RecordFields {
- fn from(ast_record_item: AstRecordFields) -> Self {
- match ast_record_item {
- AstRecordFields::Named(fields) => {
- let fields = fields.into_iter().map(Into::into).collect();
- Self::Named(fields)
- }
- AstRecordFields::Unnamed(fields) => {
- let fields = fields.into_iter().map(Into::into).collect();
- Self::Unnamed(fields)
- }
- AstRecordFields::Unit => Self::Unit,
- }
- }
-}
-
-impl From for FnSignature {
- fn from(ast_fn_sig: AstFnSignature) -> Self {
- // TODO: consider to do transmute here in case of optimization issues.
- let arguments = ast_fn_sig.arguments.into_iter().map(Into::into).collect();
- let output_type = match ast_fn_sig.output_type {
- Some(output_type) => vec![output_type],
- None => Vec::new(),
- };
-
- Self {
- name: ast_fn_sig.name,
- arguments,
- output_types: output_type,
- }
- }
-}
-
-impl From for FnArgument {
- fn from(ast_fn_arg: AstFnArgument) -> Self {
- Self {
- name: ast_fn_arg.name,
- ty: ast_fn_arg.ty,
- }
- }
-}
-
-impl From for ExternFnType {
- fn from(ast_extern_item: AstExternFn) -> Self {
- Self {
- link_name: ast_extern_item.link_name,
- signature: ast_extern_item.signature.into(),
- }
- }
-}
-
-impl From for RecordField {
- fn from(ast_record_field: AstRecordField) -> Self {
- Self {
- name: ast_record_field.name,
- ty: ast_record_field.ty,
- }
- }
-}
diff --git a/crates/marine-macro-impl/src/lib.rs b/crates/marine-macro-impl/src/lib.rs
deleted file mode 100644
index f87398d..0000000
--- a/crates/marine-macro-impl/src/lib.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#![doc(html_root_url = "https://docs.rs/marine-macro-impl/0.6.13")]
-#![deny(
- dead_code,
- nonstandard_style,
- unused_imports,
- unused_mut,
- unused_variables,
- unused_unsafe,
- unreachable_patterns
-)]
-#![recursion_limit = "1024"]
-#![warn(rust_2018_idioms)]
-
-/// This crate contains functions and types to support work with WebAssembly interface-types
-/// in Fluence.
-
-mod ast_types;
-mod export_ast_types;
-mod marine_macro_impl;
-mod parsed_type;
-mod parse_macro_input;
-mod token_stream_generator;
-mod utils;
-mod wasm_type;
-
-pub use export_ast_types::*;
-pub use crate::marine_macro_impl::marine;
-pub use parsed_type::ParsedType;
-pub use parsed_type::PassingStyle;
-pub use token_stream_generator::GENERATED_WRAPPER_FUNC_PREFIX;
-pub use token_stream_generator::GENERATED_SECTION_PREFIX;
-pub use token_stream_generator::GENERATED_GLOBAL_PREFIX;
-pub use wasm_type::RustType;
-
-pub const GENERATED_SECTION_PREFIX_FCE: &str = "__fce_generated_section__";
diff --git a/crates/marine-macro-impl/src/marine_macro_impl.rs b/crates/marine-macro-impl/src/marine_macro_impl.rs
deleted file mode 100644
index 5c5c4b8..0000000
--- a/crates/marine-macro-impl/src/marine_macro_impl.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use crate::parse_macro_input::ParseMacroInput;
-
-use proc_macro2::TokenStream;
-use quote::ToTokens;
-use syn::Result;
-
-pub fn marine(tokens: TokenStream) -> Result {
- let item = syn::parse2::(tokens)?;
- // convert proc_macro2 token to internal AST type
- let marine_ast_item = item.parse_macro_input()?;
-
- // convert internal AST type to sequence of tokens
- let mut tokens = TokenStream::new();
- marine_ast_item.to_tokens(&mut tokens);
-
- Ok(tokens)
-}
diff --git a/crates/marine-macro-impl/src/parse_macro_input.rs b/crates/marine-macro-impl/src/parse_macro_input.rs
deleted file mode 100644
index f119a72..0000000
--- a/crates/marine-macro-impl/src/parse_macro_input.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-mod item_fn;
-mod item_foreign_mod;
-mod item_record;
-mod utils;
-
-use crate::ast_types::MarineAst;
-
-pub(crate) trait ParseMacroInput {
- fn parse_macro_input(self) -> syn::Result;
-}
-
-impl ParseMacroInput for syn::Item {
- fn parse_macro_input(self) -> syn::Result {
- use syn::spanned::Spanned;
-
- match self {
- syn::Item::Fn(function) => function.parse_macro_input(),
- syn::Item::ForeignMod(extern_mod) => extern_mod.parse_macro_input(),
- syn::Item::Struct(item_struct) => item_struct.parse_macro_input(),
- _ => Err(syn::Error::new(
- self.span(),
- "At now, #[marine] could be applied only to a function, extern block or struct",
- )),
- }
- }
-}
diff --git a/crates/marine-macro-impl/src/parse_macro_input/item_fn.rs b/crates/marine-macro-impl/src/parse_macro_input/item_fn.rs
deleted file mode 100644
index 33b6230..0000000
--- a/crates/marine-macro-impl/src/parse_macro_input/item_fn.rs
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use super::ParseMacroInput;
-use crate::ast_types;
-use crate::ParsedType;
-use crate::ast_types::MarineAst;
-use crate::ast_types::AstFn;
-use crate::ast_types::AstFnArgument;
-use crate::syn_error;
-
-use syn::Result;
-use syn::spanned::Spanned;
-
-impl ParseMacroInput for syn::ItemFn {
- fn parse_macro_input(self) -> Result {
- let signature = try_to_ast_signature(self.sig.clone(), self.vis.clone())?;
-
- // this check specific only for export functions
- let parsed_args = signature
- .arguments
- .iter()
- .zip(self.sig.inputs.iter().map(|arg| arg.span()));
-
- check_args(parsed_args)?;
- check_output_type(&signature.output_type, self.sig.output.span())?;
-
- let ast_fn = MarineAst::Function(AstFn {
- signature,
- original: self,
- });
- Ok(ast_fn)
- }
-}
-
-pub(super) fn try_to_ast_signature(
- signature: syn::Signature,
- visibility: syn::Visibility,
-) -> Result {
- use quote::ToTokens;
-
- check_function(&signature)?;
-
- let syn::Signature { inputs, output, .. } = signature;
-
- let arguments = inputs
- .iter()
- .map(|arg| -> Result<_> {
- let pat = match arg {
- syn::FnArg::Typed(arg) => arg,
- _ => {
- return Err(syn::Error::new(
- arg.span(),
- "`self` argument types aren't supported",
- ))
- }
- };
-
- let name = pat
- .pat
- .to_token_stream()
- .to_string()
- .split(' ')
- .last()
- .unwrap_or_default()
- .to_string();
- let ty = ParsedType::from_type(pat.ty.as_ref())?;
- let ast_arg = AstFnArgument { name, ty };
-
- Ok(ast_arg)
- })
- .collect::>>()?;
-
- let output_type = ParsedType::from_return_type(&output)?;
-
- let ast_function_item = ast_types::AstFnSignature {
- visibility,
- name: signature.ident.to_string(),
- arguments,
- output_type,
- };
-
- Ok(ast_function_item)
-}
-
-/// Check whether the #[marine] macro could be applied to a function.
-#[rustfmt::skip]
-fn check_function(signature: &syn::Signature) -> Result<()> {
- let syn::Signature {
- constness,
- unsafety,
- abi,
- variadic,
- generics,
- ..
- } = signature;
-
- if let Some(constness) = constness {
- return syn_error!(constness.span, "Marine export function shouldn't be constant");
- }
- if let Some(unsafety) = unsafety {
- return syn_error!(unsafety.span, "Marine export function shouldn't be unsafe");
- }
- if let Some(abi) = abi {
- return syn_error!(abi.extern_token.span, "Marine export function shouldn't have any custom linkage");
- }
- if generics.where_clause.is_some() {
- return syn_error!(signature.span(), "Marine export function shouldn't use template parameters");
- }
- if variadic.is_some() {
- return syn_error!(variadic.span(), "Marine export function shouldn't use variadic interface");
- }
-
- // TODO: check for a lifetime
- Ok(())
-}
-
-fn check_args<'a>(
- args: impl ExactSizeIterator- ,
-) -> Result<()> {
- for (arg, span) in args {
- if contains_inner_ref(&arg.ty) {
- return crate::syn_error!(
- span,
- "a vector type in arguments of export functions shouldn't contain references"
- );
- }
- }
-
- Ok(())
-}
-
-fn check_output_type(output_type: &Option, span: proc_macro2::Span) -> Result<()> {
- let ty = match output_type {
- Some(ty) => ty,
- None => return Ok(()),
- };
-
- if contains_inner_ref(ty) {
- return crate::syn_error!(
- span,
- "a vector type in output types of export functions shouldn't contain references"
- );
- }
-
- Ok(())
-}
-
-/// Returns true if the given type is a vector contains a reference inside it's parameter type.
-/// F.e.
-/// Vec<&String> => true
-/// Vec>> => true
-/// &Vec => false
-fn contains_inner_ref(ty: &ParsedType) -> bool {
- use super::utils::contain_inner_ref;
-
- match ty {
- ParsedType::Vector(ty, _) => contain_inner_ref(ty),
- // Structs are checked while parsing
- _ => false,
- }
-}
diff --git a/crates/marine-macro-impl/src/parse_macro_input/item_foreign_mod.rs b/crates/marine-macro-impl/src/parse_macro_input/item_foreign_mod.rs
deleted file mode 100644
index 8e75f66..0000000
--- a/crates/marine-macro-impl/src/parse_macro_input/item_foreign_mod.rs
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use super::ParseMacroInput;
-use crate::ast_types;
-use crate::ast_types::MarineAst;
-use crate::syn_error;
-
-use syn::Result;
-use syn::spanned::Spanned;
-
-const LINK_DIRECTIVE_NAME: &str = "link";
-const LINK_NAME_DIRECTIVE_NAME: &str = "link_name";
-const WASM_IMPORT_MODULE_DIRECTIVE_NAME: &str = "wasm_import_module";
-
-impl ParseMacroInput for syn::ItemForeignMod {
- fn parse_macro_input(self) -> Result {
- check_foreign_section(&self)?;
-
- let wasm_import_module: Option = parse_wasm_import_module(&self);
- let namespace = try_extract_namespace(wasm_import_module, &self)?;
-
- let imports = extract_import_functions(&self)?;
- check_imports(imports.iter().zip(self.items.iter().map(|i| i.span())))?;
-
- let extern_mod_item = ast_types::AstExternMod { namespace, imports };
- Ok(MarineAst::ExternMod(extern_mod_item))
- }
-}
-
-fn check_foreign_section(foreign_mod: &syn::ItemForeignMod) -> Result<()> {
- match &foreign_mod.abi.name {
- Some(name) if name.value() != "C" => {
- syn_error!(foreign_mod.span(), "only 'C' abi is allowed")
- }
- _ => Ok(()),
- }
-}
-
-/// Tries to find and parse wasm module name from
-/// #[link(wasm_import_module = "host")]
-fn parse_wasm_import_module(foreign_mod: &syn::ItemForeignMod) -> Option {
- foreign_mod
- .attrs
- .iter()
- .filter_map(|attr| attr.parse_meta().ok())
- .filter(|meta| meta.path().is_ident(LINK_DIRECTIVE_NAME))
- .filter_map(|meta| {
- let pair = match meta {
- syn::Meta::List(mut meta_list) if meta_list.nested.len() == 1 => {
- meta_list.nested.pop().unwrap()
- }
- _ => return None,
- };
- Some(pair.into_tuple().0)
- })
- .filter_map(|nested| match nested {
- syn::NestedMeta::Meta(meta) => Some(meta),
- _ => None,
- })
- .filter(|meta| meta.path().is_ident(WASM_IMPORT_MODULE_DIRECTIVE_NAME))
- .map(extract_value)
- .collect()
-}
-
-fn try_extract_namespace(
- attr: Option,
- foreign_mod: &syn::ItemForeignMod,
-) -> Result {
- match attr {
- Some(namespace) if namespace.is_empty() => syn_error!(
- foreign_mod.span(),
- "import module name should be defined by 'wasm_import_module' directive"
- ),
- Some(namespace) => Ok(namespace),
- None => syn_error!(
- foreign_mod.span(),
- "import module name should be defined by 'wasm_import_module' directive"
- ),
- }
-}
-
-fn extract_import_functions(
- foreign_mod: &syn::ItemForeignMod,
-) -> Result> {
- foreign_mod
- .items
- .iter()
- .cloned()
- .map(parse_raw_foreign_item)
- .collect::>()
-}
-
-/// This function checks whether these imports contains inner references. In this case glue
-/// code couldn't be generated.
-fn check_imports<'i>(
- extern_fns: impl ExactSizeIterator
- ,
-) -> Result<()> {
- use super::utils::contain_inner_ref;
-
- for (extern_fn, span) in extern_fns {
- if let Some(output_type) = &extern_fn.signature.output_type {
- if contain_inner_ref(output_type) {
- return crate::syn_error!(
- span,
- "import function can't return a value with references"
- );
- }
- }
- }
-
- Ok(())
-}
-
-fn parse_raw_foreign_item(raw_item: syn::ForeignItem) -> Result {
- let function_item = match raw_item {
- syn::ForeignItem::Fn(function_item) => function_item,
- _ => {
- return syn_error!(
- raw_item.span(),
- "#[marine] could be applied only to a function, struct ot extern block"
- )
- }
- };
-
- // parse the link_name attribute
- // #[link_name = "put"]
- // fn ipfs_put(ptr: i32, size: i32);
- let link_name: Option = function_item
- .attrs
- .iter()
- .filter_map(|attr| attr.parse_meta().ok())
- .filter(|meta| meta.path().is_ident(LINK_NAME_DIRECTIVE_NAME))
- .map(extract_value)
- .collect();
-
- let link_name = match link_name {
- Some(name) if name.is_empty() => None,
- v @ Some(_) => v,
- None => None,
- };
-
- let signature = super::item_fn::try_to_ast_signature(function_item.sig, function_item.vis)?;
- let ast_extern_fn_item = ast_types::AstExternFn {
- link_name,
- signature,
- };
-
- Ok(ast_extern_fn_item)
-}
-
-fn extract_value(nested_meta: syn::Meta) -> Option {
- match nested_meta {
- syn::Meta::NameValue(name_value) => match name_value.lit {
- syn::Lit::Str(str) => Some(str.value()),
- _ => None,
- },
- _ => None,
- }
-}
diff --git a/crates/marine-macro-impl/src/parse_macro_input/item_record.rs b/crates/marine-macro-impl/src/parse_macro_input/item_record.rs
deleted file mode 100644
index 656f3ee..0000000
--- a/crates/marine-macro-impl/src/parse_macro_input/item_record.rs
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use super::ParseMacroInput;
-use crate::ast_types;
-use crate::ast_types::AstRecordField;
-use crate::ast_types::AstRecordFields;
-use crate::ast_types::MarineAst;
-use crate::syn_error;
-use crate::parsed_type::ParsedType;
-
-use syn::Result;
-use syn::spanned::Spanned;
-
-impl ParseMacroInput for syn::ItemStruct {
- fn parse_macro_input(self) -> Result {
- check_record(&self)?;
-
- let fields = match &self.fields {
- syn::Fields::Named(named_fields) => &named_fields.named,
- _ => return syn_error!(self.span(), "only named fields are allowed in structs"),
- };
-
- let fields = fields_into_ast(fields)?;
- let fields = AstRecordFields::Named(fields);
-
- let name = self.ident.to_string();
- let ast_record_item = ast_types::AstRecord {
- name,
- fields,
- original: self,
- };
-
- Ok(MarineAst::Record(ast_record_item))
- }
-}
-
-fn check_record(record: &syn::ItemStruct) -> Result<()> {
- if record.generics.lt_token.is_some()
- || record.generics.gt_token.is_some()
- || record.generics.where_clause.is_some()
- {
- return syn_error!(
- record.span(),
- "#[marine] couldn't be applied to a struct with generics or lifetimes"
- );
- }
-
- Ok(())
-}
-
-fn fields_into_ast(
- fields: &syn::punctuated::Punctuated,
-) -> Result> {
- fields
- .iter()
- .map(|field| {
- check_field(field)?;
- let name = field.ident.as_ref().map(|ident| {
- ident
- .to_string()
- .split(' ')
- .last()
- .unwrap_or_default()
- .to_string()
- });
- let ty = ParsedType::from_type(&field.ty)?;
-
- let record_field = AstRecordField { name, ty };
- Ok(record_field)
- })
- .collect::>>()
-}
-
-/// Check that record fields satisfy the following requirements:
-/// - all fields must be public
-/// - field must have only doc attributes
-fn check_field(field: &syn::Field) -> Result<()> {
- match field.vis {
- syn::Visibility::Public(_) => {}
- _ => {
- return syn_error!(
- field.span(),
- "#[marine] could be applied only to struct with all public fields"
- )
- }
- };
-
- const DOC_ATTR_NAME: &str = "doc";
-
- // Check that all attributes are doc attributes
- let is_all_attrs_public = field.attrs.iter().all(|attr| {
- let meta = match attr.parse_meta() {
- Ok(meta) => meta,
- Err(_) => return false,
- };
- meta.path().is_ident(DOC_ATTR_NAME)
- });
-
- if !is_all_attrs_public {
- return syn_error!(field.span(), "field attributes isn't allowed");
- }
-
- Ok(())
-}
diff --git a/crates/marine-macro-impl/src/parse_macro_input/utils.rs b/crates/marine-macro-impl/src/parse_macro_input/utils.rs
deleted file mode 100644
index f575d7e..0000000
--- a/crates/marine-macro-impl/src/parse_macro_input/utils.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2020 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-use crate::ParsedType;
-use crate::parsed_type::PassingStyle;
-use crate::parsed_type::passing_style_of;
-
-/// Checks whether a type contains a reference in one of types.
-pub(super) fn contain_inner_ref(ty: &ParsedType) -> bool {
- let passing_style = passing_style_of(ty);
- match passing_style {
- PassingStyle::ByValue => {}
- PassingStyle::ByRef | PassingStyle::ByMutRef => return true,
- };
-
- match ty {
- ParsedType::Vector(ty, _) => contain_inner_ref(ty),
- _ => false,
- }
-}
diff --git a/crates/marine-macro-impl/src/parsed_type.rs b/crates/marine-macro-impl/src/parsed_type.rs
deleted file mode 100644
index 62d5bf5..0000000
--- a/crates/marine-macro-impl/src/parsed_type.rs
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright 2018 Fluence Labs Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-mod fn_arg;
-mod fn_epilog;
-mod fn_prolog;
-mod foreign_mod_arg;
-mod foreign_mod_epilog;
-mod foreign_mod_prolog;
-mod traits;
-mod utils;
-mod vector_ser_der;
-
-pub(crate) use fn_arg::*;
-pub(crate) use fn_epilog::*;
-pub(crate) use fn_prolog::*;
-pub(crate) use foreign_mod_prolog::*;
-pub(crate) use foreign_mod_epilog::*;
-pub(crate) use utils::*;
-pub(crate) use vector_ser_der::*;
-
-use serde::Serialize;
-use serde::Deserialize;
-use syn::parse::Error;
-use syn::spanned::Spanned;
-
-/// An internal representation of supported Rust types.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub enum ParsedType {
- I8(PassingStyle),
- I16(PassingStyle),
- I32(PassingStyle),
- I64(PassingStyle),
- U8(PassingStyle),
- U16(PassingStyle),
- U32(PassingStyle),
- U64(PassingStyle),
- F32(PassingStyle),
- F64(PassingStyle),
- Boolean(PassingStyle),
- Utf8Str(PassingStyle),
- Utf8String(PassingStyle),
- Vector(Box, PassingStyle),
- Record(String, PassingStyle), // short type name
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
-pub enum PassingStyle {
- ByValue,
- ByRef,
- ByMutRef,
-}
-
-impl ParsedType {
- pub fn from_type(input_type: &syn::Type) -> syn::Result {
- use quote::ToTokens;
-
- let (path, passing_style) = type_to_path_passing_style(input_type)?;
-
- let type_segment = path
- .segments
- // argument can be given in full path form: ::std::string::String
- // that why the last one used
- .last()
- .ok_or_else(|| Error::new(path.span(), "Type should be specified"))?;
-
- match type_segment.ident.to_string().as_str() {
- "i8" => Ok(ParsedType::I8(passing_style)),
- "i16" => Ok(ParsedType::I16(passing_style)),
- "i32" => Ok(ParsedType::I32(passing_style)),
- "i64" => Ok(ParsedType::I64(passing_style)),
- "u8" => Ok(ParsedType::U8(passing_style)),
- "u16" => Ok(ParsedType::U16(passing_style)),
- "u32" => Ok(ParsedType::U32(passing_style)),
- "u64" => Ok(ParsedType::U64(passing_style)),
- "f32" => Ok(ParsedType::F32(passing_style)),
- "f64" => Ok(ParsedType::F64(passing_style)),
- "bool" => Ok(ParsedType::Boolean(passing_style)),
- "str" => Ok(ParsedType::Utf8Str(passing_style)),
- "String" => Ok(ParsedType::Utf8String(passing_style)),
- "Vec" => {
- let vec_type = parse_vec_bracket(&type_segment.arguments)?;
- let parsed_type = ParsedType::from_type(vec_type)?;
-
- Ok(ParsedType::Vector(Box::new(parsed_type), passing_style))
- }
- _ if !type_segment.arguments.is_empty() => Err(Error::new(
- type_segment.span(),
- "types with lifetimes or generics aren't allowed".to_string(),
- )),
- _ => Ok(ParsedType::Record(
- (&type_segment.ident).into_token_stream().to_string(),
- passing_style,
- )),
- }
- }
-
- pub fn from_fn_arg(fn_arg: &syn::FnArg) -> syn::Result {
- match fn_arg {
- syn::FnArg::Typed(arg) => ParsedType::from_type(&arg.ty),
- _ => Err(Error::new(
- fn_arg.span(),
- "`self` argument types aren't supported",
- )),
- }
- }
-
- pub fn from_return_type(ret_type: &syn::ReturnType) -> syn::Result