From 01f0cc028b0e7d18fd1d2095572c16116032f6d5 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Sat, 17 Apr 2021 15:15:54 +0800 Subject: [PATCH] Use no-std-compat to build no-std. --- Cargo.toml | 8 ++++- src/ast.rs | 38 +++++++++++---------- src/dynamic.rs | 40 +++++++++++----------- src/engine.rs | 39 +++++++++++---------- src/engine_api.rs | 54 +++++++++++++----------------- src/engine_settings.rs | 8 ++--- src/fn_args.rs | 2 +- src/fn_builtin.rs | 4 ++- src/fn_call.rs | 22 ++++++------ src/fn_func.rs | 3 +- src/fn_native.rs | 24 ++++++------- src/fn_register.rs | 20 ++++++----- src/lib.rs | 13 ++++--- src/module/mod.rs | 27 +++++++-------- src/module/resolvers/collection.rs | 4 ++- src/module/resolvers/dummy.rs | 3 +- src/module/resolvers/file.rs | 11 +++--- src/module/resolvers/mod.rs | 3 +- src/module/resolvers/stat.rs | 4 ++- src/optimize.rs | 18 +++++----- src/packages/arithmetic.rs | 3 +- src/packages/array_basic.rs | 4 ++- src/packages/fn_basic.rs | 5 ++- src/packages/iter_basic.rs | 12 ++++--- src/packages/logic.rs | 2 ++ src/packages/map_basic.rs | 2 ++ src/packages/math_basic.rs | 15 ++++----- src/packages/pkg_core.rs | 2 ++ src/packages/pkg_std.rs | 2 ++ src/packages/string_basic.rs | 11 +++--- src/packages/string_more.rs | 7 ++-- src/packages/time_basic.rs | 5 +-- src/parse_error.rs | 13 +++---- src/parser.rs | 23 ++++++------- src/plugin.rs | 4 ++- src/result.rs | 19 +++++------ src/scope.rs | 6 ++-- src/serde/de.rs | 4 ++- src/serde/deserialize.rs | 8 +++-- src/serde/metadata.rs | 9 ++--- src/serde/ser.rs | 10 +++--- src/serde/serialize.rs | 3 +- src/serde/str.rs | 4 ++- src/stdlib.rs | 32 ------------------ src/syntax.rs | 3 +- src/token.rs | 9 ++--- src/unsafe.rs | 5 +-- src/utils.rs | 19 +++++------ 48 files changed, 293 insertions(+), 293 deletions(-) delete mode 100644 src/stdlib.rs diff --git a/Cargo.toml b/Cargo.toml index c9f5166b..d6e30562 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,7 @@ internals = [] # expose internal data structures unicode-xid-ident = ["unicode-xid"] # allow Unicode Standard Annex #31 for identifiers. metadata = ["serde_json", "rhai_codegen/metadata"] # enable exporting functions metadata -no_std = ["num-traits/libm", "core-error", "libm", "ahash/compile-time-rng"] +no_std = ["no-std-compat", "num-traits/libm", "core-error", "libm", "ahash/compile-time-rng"] # compiling for WASM wasm-bindgen = ["instant/wasm-bindgen"] @@ -53,6 +53,12 @@ codegen-units = 1 #opt-level = "z" # optimize for size #panic = 'abort' # remove stack backtrace for no-std +[dependencies.no-std-compat] +version = "0.4" +default_features = false +features = ["alloc"] +optional = true + [dependencies.libm] version = "0.2" default_features = false diff --git a/src/ast.rs b/src/ast.rs index c158c75f..154d8024 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -3,26 +3,28 @@ use crate::dynamic::{AccessMode, Union}; use crate::fn_native::shared_make_mut; use crate::module::NamespaceRef; -use crate::stdlib::{ - boxed::Box, - collections::BTreeMap, - fmt, - hash::Hash, - iter::empty, - num::{NonZeroU8, NonZeroUsize}, - ops::{Add, AddAssign, Deref, DerefMut}, - vec, - vec::Vec, -}; use crate::token::Token; use crate::utils::calc_fn_hash; use crate::{ Dynamic, FnNamespace, FnPtr, Identifier, ImmutableString, Module, Position, Shared, StaticVec, INT, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ + collections::BTreeMap, + fmt, + hash::Hash, + iter::empty, + num::{NonZeroU8, NonZeroUsize}, + ops::{Add, AddAssign, Deref, DerefMut}, +}; #[cfg(not(feature = "no_float"))] -use crate::{stdlib::str::FromStr, FLOAT}; +use std::str::FromStr; + +#[cfg(not(feature = "no_float"))] +use crate::FLOAT; #[cfg(not(feature = "no_float"))] use num_traits::Float; @@ -62,11 +64,11 @@ pub struct ScriptFnDef { pub params: StaticVec, /// Access to external variables. #[cfg(not(feature = "no_closure"))] - pub externals: crate::stdlib::collections::BTreeSet, + pub externals: std::collections::BTreeSet, /// Function doc-comments (if any). #[cfg(not(feature = "no_function"))] #[cfg(feature = "metadata")] - pub comments: StaticVec, + pub comments: StaticVec, } impl fmt::Display for ScriptFnDef { @@ -1478,7 +1480,7 @@ pub struct FloatWrapper(F); #[cfg(not(feature = "no_float"))] impl Hash for FloatWrapper { #[inline(always)] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.0.to_ne_bytes().hash(state); } } @@ -1500,7 +1502,7 @@ impl AsMut for FloatWrapper { } #[cfg(not(feature = "no_float"))] -impl crate::stdlib::ops::Deref for FloatWrapper { +impl std::ops::Deref for FloatWrapper { type Target = F; #[inline(always)] @@ -1510,7 +1512,7 @@ impl crate::stdlib::ops::Deref for FloatWrapper { } #[cfg(not(feature = "no_float"))] -impl crate::stdlib::ops::DerefMut for FloatWrapper { +impl std::ops::DerefMut for FloatWrapper { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 @@ -2037,8 +2039,8 @@ mod tests { /// This test is to make sure no code changes increase the sizes of critical data structures. #[test] fn check_struct_sizes() { - use crate::stdlib::mem::size_of; use crate::*; + use std::mem::size_of; assert_eq!(size_of::(), 16); assert_eq!(size_of::>(), 16); diff --git a/src/dynamic.rs b/src/dynamic.rs index 272066fc..4ae4d80f 100644 --- a/src/dynamic.rs +++ b/src/dynamic.rs @@ -2,15 +2,15 @@ use crate::fn_native::SendSync; use crate::r#unsafe::{unsafe_cast_box, unsafe_try_cast}; -use crate::stdlib::{ +use crate::{FnPtr, ImmutableString, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ any::{type_name, Any, TypeId}, - boxed::Box, fmt, hash::{Hash, Hasher}, ops::{Deref, DerefMut}, - string::String, }; -use crate::{FnPtr, ImmutableString, INT}; #[cfg(not(feature = "no_float"))] use crate::{ast::FloatWrapper, FLOAT}; @@ -26,7 +26,7 @@ use crate::Map; #[cfg(not(feature = "no_std"))] #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] -use crate::stdlib::time::Instant; +use std::time::Instant; use fmt::Debug; #[cfg(not(feature = "no_std"))] @@ -35,7 +35,7 @@ use instant::Instant; mod private { use crate::fn_native::SendSync; - use crate::stdlib::any::Any; + use std::any::Any; /// A sealed trait that prevents other crates from implementing [`Variant`]. pub trait Sealed {} @@ -199,11 +199,11 @@ enum DynamicReadLockInner<'d, T: Variant + Clone> { /// A read guard to a shared [`RefCell`][std::cell::RefCell]. #[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "sync"))] - Guard(crate::stdlib::cell::Ref<'d, Dynamic>), + Guard(std::cell::Ref<'d, Dynamic>), /// A read guard to a shared [`RwLock`][std::sync::RwLock]. #[cfg(not(feature = "no_closure"))] #[cfg(feature = "sync")] - Guard(crate::stdlib::sync::RwLockReadGuard<'d, Dynamic>), + Guard(std::sync::RwLockReadGuard<'d, Dynamic>), } impl<'d, T: Variant + Clone> Deref for DynamicReadLock<'d, T> { @@ -236,11 +236,11 @@ enum DynamicWriteLockInner<'d, T: Variant + Clone> { /// A write guard to a shared [`RefCell`][std::cell::RefCell]. #[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "sync"))] - Guard(crate::stdlib::cell::RefMut<'d, Dynamic>), + Guard(std::cell::RefMut<'d, Dynamic>), /// A write guard to a shared [`RwLock`][std::sync::RwLock]. #[cfg(not(feature = "no_closure"))] #[cfg(feature = "sync")] - Guard(crate::stdlib::sync::RwLockWriteGuard<'d, Dynamic>), + Guard(std::sync::RwLockWriteGuard<'d, Dynamic>), } impl<'d, T: Variant + Clone> Deref for DynamicWriteLock<'d, T> { @@ -1233,7 +1233,7 @@ impl Dynamic { pub(crate) fn flatten_in_place(&mut self) { #[cfg(not(feature = "no_closure"))] match self.0 { - Union::Shared(_, _) => match crate::stdlib::mem::take(self).0 { + Union::Shared(_, _) => match std::mem::take(self).0 { Union::Shared(cell, _) => { *self = crate::fn_native::shared_try_take(cell).map_or_else( |cell| { @@ -1717,13 +1717,13 @@ impl From<&ImmutableString> for Dynamic { impl From<&crate::Identifier> for Dynamic { #[inline(always)] fn from(value: &crate::Identifier) -> Self { - crate::stdlib::string::ToString::to_string(value).into() + std::string::ToString::to_string(value).into() } } #[cfg(not(feature = "no_index"))] -impl From> for Dynamic { +impl From> for Dynamic { #[inline(always)] - fn from(value: crate::stdlib::vec::Vec) -> Self { + fn from(value: std::vec::Vec) -> Self { Self(Union::Array( Box::new(value.into_iter().map(Dynamic::from).collect()), AccessMode::ReadWrite, @@ -1741,7 +1741,7 @@ impl From<&[T]> for Dynamic { } } #[cfg(not(feature = "no_index"))] -impl crate::stdlib::iter::FromIterator for Dynamic { +impl std::iter::FromIterator for Dynamic { #[inline(always)] fn from_iter>(iter: X) -> Self { Self(Union::Array( @@ -1752,11 +1752,11 @@ impl crate::stdlib::iter::FromIterator for Dynamic { } #[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_std"))] -impl, T: Variant + Clone> From> +impl, T: Variant + Clone> From> for Dynamic { #[inline(always)] - fn from(value: crate::stdlib::collections::HashMap) -> Self { + fn from(value: std::collections::HashMap) -> Self { Self(Union::Map( Box::new( value @@ -1769,11 +1769,11 @@ impl, T: Variant + Clone> From, T: Variant + Clone> - From> for Dynamic +impl, T: Variant + Clone> From> + for Dynamic { #[inline(always)] - fn from(value: crate::stdlib::collections::BTreeMap) -> Self { + fn from(value: std::collections::BTreeMap) -> Self { Self(Union::Map( Box::new( value diff --git a/src/engine.rs b/src/engine.rs index a721919e..7541a56a 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -10,27 +10,26 @@ use crate::module::NamespaceRef; use crate::optimize::OptimizationLevel; use crate::packages::{Package, StandardPackage}; use crate::r#unsafe::unsafe_cast_var_name_to_lifetime; -use crate::stdlib::{ - any::{type_name, TypeId}, - borrow::Cow, - boxed::Box, - collections::{BTreeMap, BTreeSet}, - fmt, format, - hash::{Hash, Hasher}, - num::{NonZeroU8, NonZeroUsize}, - ops::{Deref, DerefMut}, - string::{String, ToString}, - vec::Vec, -}; use crate::syntax::CustomSyntax; use crate::utils::get_hasher; use crate::{ Dynamic, EvalAltResult, FnPtr, Identifier, ImmutableString, Module, Position, RhaiResult, Scope, Shared, StaticVec, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ + any::{type_name, TypeId}, + borrow::Cow, + collections::{BTreeMap, BTreeSet}, + fmt, + hash::{Hash, Hasher}, + num::{NonZeroU8, NonZeroUsize}, + ops::{Deref, DerefMut}, +}; #[cfg(not(feature = "no_index"))] -use crate::{calc_fn_hash, stdlib::iter::empty, Array}; +use crate::{calc_fn_hash, Array}; #[cfg(not(feature = "no_object"))] use crate::Map; @@ -616,7 +615,7 @@ pub struct Limits { #[cfg(not(feature = "no_function"))] pub max_function_expr_depth: Option, /// Maximum number of operations allowed to run. - pub max_operations: Option, + pub max_operations: Option, /// Maximum number of [modules][Module] allowed to load. /// /// Set to zero to effectively disable loading any [module][Module]. @@ -1174,8 +1173,11 @@ impl Engine { let val_type_name = target.type_name(); let ((_, val_pos), _) = new_val; - let hash_set = - FnCallHash::from_native(calc_fn_hash(empty(), FN_IDX_SET, 3)); + let hash_set = FnCallHash::from_native(calc_fn_hash( + std::iter::empty(), + FN_IDX_SET, + 3, + )); let args = &mut [target, &mut idx_val2, &mut (new_val.0).0]; self.exec_fn_call( @@ -1688,7 +1690,8 @@ impl Engine { _ if _indexers => { let type_name = target.type_name(); let args = &mut [target, &mut _idx]; - let hash_get = FnCallHash::from_native(calc_fn_hash(empty(), FN_IDX_GET, 2)); + let hash_get = + FnCallHash::from_native(calc_fn_hash(std::iter::empty(), FN_IDX_GET, 2)); self.exec_fn_call( _mods, state, _lib, FN_IDX_GET, hash_get, args, _is_ref, true, idx_pos, None, _level, @@ -2594,7 +2597,7 @@ impl Engine { if !val.is_shared() { // Replace the variable with a shared value. - *val = crate::stdlib::mem::take(val).into_shared(); + *val = std::mem::take(val).into_shared(); } } Ok(Dynamic::UNIT) diff --git a/src/engine_api.rs b/src/engine_api.rs index e3ace3d6..b0aab3e1 100644 --- a/src/engine_api.rs +++ b/src/engine_api.rs @@ -6,15 +6,13 @@ use crate::fn_native::{FnCallArgs, SendSync}; use crate::fn_register::RegisterNativeFunction; use crate::optimize::OptimizationLevel; use crate::parser::ParseState; -use crate::stdlib::{ - any::{type_name, TypeId}, - boxed::Box, - string::String, -}; use crate::{ scope::Scope, Dynamic, Engine, EvalAltResult, FnAccess, FnNamespace, Identifier, Module, NativeCallContext, ParseError, Position, RhaiResult, Shared, AST, }; +use std::any::{type_name, TypeId}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_index"))] use crate::Array; @@ -61,7 +59,7 @@ impl Engine { #[cfg(feature = "metadata")] let mut param_type_names: crate::StaticVec<_> = F::param_names() .iter() - .map(|ty| crate::stdlib::format!("_: {}", self.map_type_name(ty))) + .map(|ty| std::format!("_: {}", self.map_type_name(ty))) .collect(); #[cfg(feature = "metadata")] @@ -121,8 +119,8 @@ impl Engine { #[cfg(feature = "metadata")] let param_type_names: crate::StaticVec<_> = F::param_names() .iter() - .map(|ty| crate::stdlib::format!("_: {}", self.map_type_name(ty))) - .chain(crate::stdlib::iter::once( + .map(|ty| std::format!("_: {}", self.map_type_name(ty))) + .chain(std::iter::once( self.map_type_name(F::return_type_name()).into(), )) .collect(); @@ -905,7 +903,7 @@ impl Engine { module: Shared, ) -> &mut Self { fn register_static_module_raw( - root: &mut crate::stdlib::collections::BTreeMap>, + root: &mut std::collections::BTreeMap>, name: impl AsRef + Into, module: Shared, ) { @@ -1039,8 +1037,8 @@ impl Engine { ast::{ASTNode, Expr, Stmt}, fn_native::shared_take_or_clone, module::resolvers::StaticModuleResolver, - stdlib::collections::BTreeSet, }; + use std::collections::BTreeSet; fn collect_imports( ast: &AST, @@ -1169,12 +1167,12 @@ impl Engine { /// Read the contents of a file into a string. #[cfg(not(feature = "no_std"))] #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] - fn read_file(path: crate::stdlib::path::PathBuf) -> Result> { - use crate::stdlib::io::Read; + fn read_file(path: std::path::PathBuf) -> Result> { + use std::io::Read; - let mut f = crate::stdlib::fs::File::open(path.clone()).map_err(|err| { + let mut f = std::fs::File::open(path.clone()).map_err(|err| { EvalAltResult::ErrorSystem( - crate::stdlib::format!("Cannot open script file '{}'", path.to_string_lossy()), + std::format!("Cannot open script file '{}'", path.to_string_lossy()), err.into(), ) })?; @@ -1183,7 +1181,7 @@ impl Engine { f.read_to_string(&mut contents).map_err(|err| { EvalAltResult::ErrorSystem( - crate::stdlib::format!("Cannot read script file '{}'", path.to_string_lossy()), + std::format!("Cannot read script file '{}'", path.to_string_lossy()), err.into(), ) })?; @@ -1224,10 +1222,7 @@ impl Engine { #[cfg(not(feature = "no_std"))] #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] #[inline(always)] - pub fn compile_file( - &self, - path: crate::stdlib::path::PathBuf, - ) -> Result> { + pub fn compile_file(&self, path: std::path::PathBuf) -> Result> { self.compile_file_with_scope(&Default::default(), path) } /// Compile a script file into an [`AST`] using own scope, which can be used later for evaluation. @@ -1269,7 +1264,7 @@ impl Engine { pub fn compile_file_with_scope( &self, scope: &Scope, - path: crate::stdlib::path::PathBuf, + path: std::path::PathBuf, ) -> Result> { Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?)) } @@ -1465,7 +1460,7 @@ impl Engine { #[inline(always)] pub fn eval_file( &self, - path: crate::stdlib::path::PathBuf, + path: std::path::PathBuf, ) -> Result> { Self::read_file(path).and_then(|contents| self.eval::(&contents)) } @@ -1496,7 +1491,7 @@ impl Engine { pub fn eval_file_with_scope( &self, scope: &mut Scope, - path: crate::stdlib::path::PathBuf, + path: std::path::PathBuf, ) -> Result> { Self::read_file(path).and_then(|contents| self.eval_with_scope::(scope, &contents)) } @@ -1711,10 +1706,7 @@ impl Engine { #[cfg(not(feature = "no_std"))] #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] #[inline(always)] - pub fn consume_file( - &self, - path: crate::stdlib::path::PathBuf, - ) -> Result<(), Box> { + pub fn consume_file(&self, path: std::path::PathBuf) -> Result<(), Box> { Self::read_file(path).and_then(|contents| self.consume(&contents)) } /// Evaluate a file with own scope, but throw away the result and only return error (if any). @@ -1727,7 +1719,7 @@ impl Engine { pub fn consume_file_with_scope( &self, scope: &mut Scope, - path: crate::stdlib::path::PathBuf, + path: std::path::PathBuf, ) -> Result<(), Box> { Self::read_file(path).and_then(|contents| self.consume_with_scope(scope, &contents)) } @@ -1999,7 +1991,7 @@ impl Engine { #[cfg(feature = "no_function")] let lib = Default::default(); - let stmt = crate::stdlib::mem::take(ast.statements_mut()); + let stmt = std::mem::take(ast.statements_mut()); crate::optimize::optimize_into_ast(self, scope, stmt.into_vec(), lib, optimization_level) } /// Generate a list of all registered functions. @@ -2010,15 +2002,15 @@ impl Engine { /// 2) Functions in registered sub-modules /// 3) Functions in packages (optional) #[cfg(feature = "metadata")] - pub fn gen_fn_signatures(&self, include_packages: bool) -> crate::stdlib::vec::Vec { - let mut signatures: crate::stdlib::vec::Vec<_> = Default::default(); + pub fn gen_fn_signatures(&self, include_packages: bool) -> std::vec::Vec { + let mut signatures: std::vec::Vec<_> = Default::default(); signatures.extend(self.global_namespace.gen_fn_signatures()); self.global_sub_modules.iter().for_each(|(name, m)| { signatures.extend( m.gen_fn_signatures() - .map(|f| crate::stdlib::format!("{}::{}", name, f)), + .map(|f| std::format!("{}::{}", name, f)), ) }); diff --git a/src/engine_settings.rs b/src/engine_settings.rs index f2860b25..ce6aa1e3 100644 --- a/src/engine_settings.rs +++ b/src/engine_settings.rs @@ -1,15 +1,13 @@ //! Configuration settings for [`Engine`]. -use crate::stdlib::{format, string::String}; use crate::token::Token; use crate::Engine; use crate::{engine::Precedence, Identifier}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "unchecked"))] -use crate::stdlib::num::{NonZeroU64, NonZeroUsize}; - -#[cfg(not(feature = "no_module"))] -use crate::stdlib::boxed::Box; +use std::num::{NonZeroU64, NonZeroUsize}; impl Engine { /// Control whether and how the [`Engine`] will optimize an [`AST`][crate::AST] after compilation. diff --git a/src/fn_args.rs b/src/fn_args.rs index 6b3baf78..c71a5c65 100644 --- a/src/fn_args.rs +++ b/src/fn_args.rs @@ -4,8 +4,8 @@ #![allow(non_snake_case)] use crate::dynamic::Variant; -use crate::stdlib::vec::Vec; use crate::{Dynamic, StaticVec}; +use std::vec::Vec; /// Trait that parses arguments to a function call. /// diff --git a/src/fn_builtin.rs b/src/fn_builtin.rs index 515c6a68..87f7bcba 100644 --- a/src/fn_builtin.rs +++ b/src/fn_builtin.rs @@ -2,8 +2,10 @@ use crate::engine::OP_CONTAINS; use crate::fn_native::{FnCallArgs, NativeCallContext}; -use crate::stdlib::{any::TypeId, format, string::ToString}; use crate::{Dynamic, ImmutableString, RhaiResult, INT}; +use std::any::TypeId; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_float"))] use crate::FLOAT; diff --git a/src/fn_call.rs b/src/fn_call.rs index 9ddf21bd..2a5c904c 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -10,16 +10,6 @@ use crate::fn_builtin::{get_builtin_binary_op_fn, get_builtin_op_assignment_fn}; use crate::fn_native::{FnAny, FnCallArgs}; use crate::module::NamespaceRef; use crate::optimize::OptimizationLevel; -use crate::stdlib::{ - any::{type_name, TypeId}, - boxed::Box, - convert::TryFrom, - format, - iter::{empty, once}, - mem, - string::{String, ToString}, - vec::Vec, -}; use crate::{ ast::{Expr, Stmt}, fn_native::CallableFunction, @@ -29,6 +19,14 @@ use crate::{ calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, EvalAltResult, FnPtr, ImmutableString, Module, ParseErrorType, Position, Scope, StaticVec, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ + any::{type_name, TypeId}, + convert::TryFrom, + iter::{empty, once}, + mem, +}; #[cfg(not(feature = "no_object"))] use crate::Map; @@ -465,7 +463,7 @@ impl Engine { ) -> RhaiResult { #[inline(always)] fn make_error( - name: crate::stdlib::string::String, + name: std::string::String, fn_def: &crate::ast::ScriptFnDef, state: &State, err: Box, @@ -512,7 +510,7 @@ impl Engine { .iter() .zip(args.iter_mut().map(|v| mem::take(*v))) .map(|(name, value)| { - let var_name: crate::stdlib::borrow::Cow<'_, str> = + let var_name: std::borrow::Cow<'_, str> = crate::r#unsafe::unsafe_cast_var_name_to_lifetime(name).into(); (var_name, value) }), diff --git a/src/fn_func.rs b/src/fn_func.rs index 93c036ff..3c51911a 100644 --- a/src/fn_func.rs +++ b/src/fn_func.rs @@ -4,8 +4,9 @@ #![allow(non_snake_case)] use crate::dynamic::Variant; -use crate::stdlib::{boxed::Box, string::ToString}; use crate::{Engine, EvalAltResult, ParseError, Scope, AST}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; /// Trait to create a Rust closure from a script. /// diff --git a/src/fn_native.rs b/src/fn_native.rs index b98bf0ae..b84df08c 100644 --- a/src/fn_native.rs +++ b/src/fn_native.rs @@ -3,19 +3,19 @@ use crate::ast::{FnAccess, FnCallHash}; use crate::engine::Imports; use crate::plugin::PluginFunction; -use crate::stdlib::{ - boxed::Box, - convert::{TryFrom, TryInto}, - fmt, - iter::{empty, once}, - mem, - string::String, -}; use crate::token::is_valid_identifier; use crate::{ calc_fn_hash, Dynamic, Engine, EvalAltResult, EvalContext, Identifier, ImmutableString, Module, Position, RhaiResult, StaticVec, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ + convert::{TryFrom, TryInto}, + fmt, + iter::{empty, once}, + mem, +}; /// Trait that maps to `Send + Sync` only under the `sync` feature. #[cfg(feature = "sync")] @@ -33,19 +33,19 @@ impl SendSync for T {} /// Immutable reference-counted container. #[cfg(not(feature = "sync"))] -pub use crate::stdlib::rc::Rc as Shared; +pub use std::rc::Rc as Shared; /// Immutable reference-counted container. #[cfg(feature = "sync")] -pub use crate::stdlib::sync::Arc as Shared; +pub use std::sync::Arc as Shared; /// Synchronized shared object. #[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "sync"))] -pub use crate::stdlib::cell::RefCell as Locked; +pub use std::cell::RefCell as Locked; /// Synchronized shared object. #[cfg(not(feature = "no_closure"))] #[cfg(feature = "sync")] -pub use crate::stdlib::sync::RwLock as Locked; +pub use std::sync::RwLock as Locked; /// Context of a native Rust function call. #[derive(Debug)] diff --git a/src/fn_register.rs b/src/fn_register.rs index 48fae4b8..a4535ead 100644 --- a/src/fn_register.rs +++ b/src/fn_register.rs @@ -5,8 +5,10 @@ use crate::dynamic::{DynamicWriteLock, Variant}; use crate::fn_native::{CallableFunction, FnAny, FnCallArgs, SendSync}; use crate::r#unsafe::unsafe_try_cast; -use crate::stdlib::{any::TypeId, boxed::Box, mem, string::String, vec}; use crate::{Dynamic, EvalAltResult, NativeCallContext}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{any::TypeId, mem}; // These types are used to build a unique _marker_ tuple type for each combination // of function parameter types in order to make each trait implementation unique. @@ -91,9 +93,9 @@ macro_rules! def_register { RET: Variant + Clone > RegisterNativeFunction<($($mark,)*), ()> for FN { #[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() } - #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(crate::stdlib::any::type_name::<$par>()),*].into_boxed_slice() } + #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() } #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { crate::stdlib::any::type_name::() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::() } #[inline(always)] fn into_callable_function(self) -> CallableFunction { CallableFunction::$abi(Box::new(move |_: NativeCallContext, args: &mut FnCallArgs| { // The arguments are assumed to be of the correct number and types! @@ -115,9 +117,9 @@ macro_rules! def_register { RET: Variant + Clone > RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), ()> for FN { #[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() } - #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(crate::stdlib::any::type_name::<$par>()),*].into_boxed_slice() } + #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() } #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { crate::stdlib::any::type_name::() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::() } #[inline(always)] fn into_callable_function(self) -> CallableFunction { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { // The arguments are assumed to be of the correct number and types! @@ -139,9 +141,9 @@ macro_rules! def_register { RET: Variant + Clone > RegisterNativeFunction<($($mark,)*), Result>> for FN { #[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() } - #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(crate::stdlib::any::type_name::<$par>()),*].into_boxed_slice() } + #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() } #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::>>() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { crate::stdlib::any::type_name::>>() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::>>() } #[inline(always)] fn into_callable_function(self) -> CallableFunction { CallableFunction::$abi(Box::new(move |_: NativeCallContext, args: &mut FnCallArgs| { // The arguments are assumed to be of the correct number and types! @@ -160,9 +162,9 @@ macro_rules! def_register { RET: Variant + Clone > RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), Result>> for FN { #[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() } - #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(crate::stdlib::any::type_name::<$par>()),*].into_boxed_slice() } + #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() } #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::>>() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { crate::stdlib::any::type_name::>>() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::>>() } #[inline(always)] fn into_callable_function(self) -> CallableFunction { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { // The arguments are assumed to be of the correct number and types! diff --git a/src/lib.rs b/src/lib.rs index 2d607f36..6771162e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -61,6 +61,12 @@ #[cfg(feature = "no_std")] extern crate alloc; +#[cfg(feature = "no_std")] +extern crate no_std_compat as std; + +#[cfg(feature = "no_std")] +use std::prelude::v1::*; + // Internal modules mod ast; @@ -82,13 +88,12 @@ mod parser; pub mod plugin; mod result; mod scope; -mod stdlib; mod syntax; mod token; mod r#unsafe; mod utils; -type RhaiResult = stdlib::result::Result>; +type RhaiResult = Result>; /// The system integer type. It is defined as [`i64`]. /// @@ -180,12 +185,12 @@ pub use ast::ScriptFnMetadata; /// Variable-sized array of [`Dynamic`] values. /// Not available under `no_index`. #[cfg(not(feature = "no_index"))] -pub type Array = stdlib::vec::Vec; +pub type Array = Vec; /// Hash map of [`Dynamic`] values with [`ImmutableString`] keys. /// Not available under `no_object`. #[cfg(not(feature = "no_object"))] -pub type Map = stdlib::collections::BTreeMap; +pub type Map = std::collections::BTreeMap; #[cfg(not(feature = "no_module"))] pub use module::ModuleResolver; diff --git a/src/module/mod.rs b/src/module/mod.rs index aa20b2df..3542d6b3 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -4,23 +4,22 @@ use crate::ast::{FnAccess, Ident}; use crate::dynamic::Variant; use crate::fn_native::{shared_take_or_clone, CallableFunction, FnCallArgs, IteratorFn, SendSync}; use crate::fn_register::RegisterNativeFunction; -use crate::stdlib::{ - any::TypeId, - boxed::Box, - collections::{BTreeMap, BTreeSet}, - fmt, - iter::empty, - num::NonZeroUsize, - ops::{Add, AddAssign, Deref, DerefMut}, - string::String, - vec::Vec, -}; use crate::token::Token; use crate::utils::IdentifierBuilder; use crate::{ calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, EvalAltResult, Identifier, ImmutableString, NativeCallContext, Position, Shared, StaticVec, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ + any::TypeId, + collections::{BTreeMap, BTreeSet}, + fmt, + iter::empty, + num::NonZeroUsize, + ops::{Add, AddAssign, Deref, DerefMut}, +}; #[cfg(not(feature = "no_index"))] use crate::Array; @@ -73,7 +72,7 @@ impl FuncInfo { let mut sig = format!("{}(", self.name); if !self.param_names.is_empty() { - let mut params: crate::stdlib::vec::Vec = + let mut params: std::vec::Vec = self.param_names.iter().map(|s| s.as_str().into()).collect(); let return_type = params.pop().unwrap_or_else(|| "()".into()); sig.push_str(¶ms.join(", ")); @@ -198,7 +197,7 @@ impl fmt::Debug for Module { &self .functions .values() - .map(|f| crate::stdlib::string::ToString::to_string(&f.func)) + .map(|f| std::string::ToString::to_string(&f.func)) .collect::>(), ); } @@ -1231,7 +1230,7 @@ impl Module { &mut self, filter: impl Fn(FnNamespace, FnAccess, &str, usize) -> bool, ) -> &mut Self { - self.functions = crate::stdlib::mem::take(&mut self.functions) + self.functions = std::mem::take(&mut self.functions) .into_iter() .filter(|(_, f)| { if f.func.is_script() { diff --git a/src/module/resolvers/collection.rs b/src/module/resolvers/collection.rs index f974ce09..7ee036f0 100644 --- a/src/module/resolvers/collection.rs +++ b/src/module/resolvers/collection.rs @@ -1,5 +1,7 @@ -use crate::stdlib::{boxed::Box, ops::AddAssign, vec::Vec}; use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, Shared}; +use std::ops::AddAssign; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; /// [Module] resolution service that holds a collection of module resolvers, /// to be searched in sequential order. diff --git a/src/module/resolvers/dummy.rs b/src/module/resolvers/dummy.rs index 157de26d..3feb6852 100644 --- a/src/module/resolvers/dummy.rs +++ b/src/module/resolvers/dummy.rs @@ -1,5 +1,6 @@ -use crate::stdlib::boxed::Box; use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, Shared}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; /// Empty/disabled [module][Module] resolution service that acts as a dummy. /// diff --git a/src/module/resolvers/file.rs b/src/module/resolvers/file.rs index 2915eb08..ab3800e6 100644 --- a/src/module/resolvers/file.rs +++ b/src/module/resolvers/file.rs @@ -1,10 +1,11 @@ -use crate::stdlib::{ - boxed::Box, +use crate::{Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, Shared}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ collections::BTreeMap, io::Error as IoError, path::{Path, PathBuf}, }; -use crate::{Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, Shared}; pub const RHAI_SCRIPT_EXTENSION: &str = "rhai"; @@ -45,9 +46,9 @@ pub struct FileModuleResolver { cache_enabled: bool, #[cfg(not(feature = "sync"))] - cache: crate::stdlib::cell::RefCell>>, + cache: std::cell::RefCell>>, #[cfg(feature = "sync")] - cache: crate::stdlib::sync::RwLock>>, + cache: std::sync::RwLock>>, } impl Default for FileModuleResolver { diff --git a/src/module/resolvers/mod.rs b/src/module/resolvers/mod.rs index 56eb6c03..6014d23e 100644 --- a/src/module/resolvers/mod.rs +++ b/src/module/resolvers/mod.rs @@ -1,6 +1,7 @@ use crate::fn_native::SendSync; -use crate::stdlib::boxed::Box; use crate::{Engine, EvalAltResult, Module, Position, Shared, AST}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; mod dummy; pub use dummy::DummyModuleResolver; diff --git a/src/module/resolvers/stat.rs b/src/module/resolvers/stat.rs index 11c99c76..5e905926 100644 --- a/src/module/resolvers/stat.rs +++ b/src/module/resolvers/stat.rs @@ -1,5 +1,7 @@ -use crate::stdlib::{boxed::Box, collections::BTreeMap, ops::AddAssign}; use crate::{Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, Shared}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{collections::BTreeMap, ops::AddAssign}; /// A static [module][Module] resolution service that serves [modules][Module] added into it. /// diff --git a/src/optimize.rs b/src/optimize.rs index abb2dd35..35ae9148 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -5,21 +5,19 @@ use crate::dynamic::AccessMode; use crate::engine::{KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT, KEYWORD_TYPE_OF}; use crate::fn_builtin::get_builtin_binary_op_fn; use crate::parser::map_dynamic_to_expr; -use crate::stdlib::{ - any::TypeId, - boxed::Box, - hash::{Hash, Hasher}, - iter::empty, - mem, - string::{String, ToString}, - vec, - vec::Vec, -}; use crate::utils::get_hasher; use crate::{ calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, ImmutableString, Module, Position, Scope, StaticVec, AST, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ + any::TypeId, + hash::{Hash, Hasher}, + iter::empty, + mem, +}; /// Level of optimization performed. #[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)] diff --git a/src/packages/arithmetic.rs b/src/packages/arithmetic.rs index efefbd87..e70ef146 100644 --- a/src/packages/arithmetic.rs +++ b/src/packages/arithmetic.rs @@ -1,8 +1,9 @@ #![allow(non_snake_case)] use crate::plugin::*; -use crate::stdlib::{format, string::String}; use crate::{def_package, EvalAltResult, Position, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_float"))] use crate::FLOAT; diff --git a/src/packages/array_basic.rs b/src/packages/array_basic.rs index 1703194e..0751428c 100644 --- a/src/packages/array_basic.rs +++ b/src/packages/array_basic.rs @@ -3,8 +3,10 @@ use crate::engine::OP_EQUALS; use crate::plugin::*; -use crate::stdlib::{any::TypeId, boxed::Box, cmp::Ordering, mem, string::ToString}; use crate::{def_package, Array, Dynamic, EvalAltResult, FnPtr, NativeCallContext, Position, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{any::TypeId, cmp::Ordering, mem}; def_package!(crate:BasicArrayPackage:"Basic array utilities.", lib, { combine_with_exported_module!(lib, "array", array_functions); diff --git a/src/packages/fn_basic.rs b/src/packages/fn_basic.rs index ab589415..63688c04 100644 --- a/src/packages/fn_basic.rs +++ b/src/packages/fn_basic.rs @@ -1,5 +1,7 @@ use crate::plugin::*; use crate::{def_package, FnPtr, ImmutableString, NativeCallContext}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; def_package!(crate:BasicFnPackage:"Basic Fn functions.", lib, { combine_with_exported_module!(lib, "FnPtr", fn_ptr_functions); @@ -34,7 +36,8 @@ mod fn_ptr_functions { #[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_object"))] fn collect_fn_metadata(ctx: NativeCallContext) -> crate::Array { - use crate::{ast::ScriptFnDef, stdlib::collections::BTreeSet, Array, Identifier, Map}; + use crate::{ast::ScriptFnDef, Array, Identifier, Map}; + use std::collections::BTreeSet; // Create a metadata record for a function. fn make_metadata( diff --git a/src/packages/iter_basic.rs b/src/packages/iter_basic.rs index 9d482fae..e79e5473 100644 --- a/src/packages/iter_basic.rs +++ b/src/packages/iter_basic.rs @@ -1,15 +1,17 @@ use crate::dynamic::Variant; -use crate::stdlib::{boxed::Box, ops::Range}; use crate::{def_package, EvalAltResult, INT}; +use std::ops::Range; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "unchecked"))] -use crate::stdlib::string::ToString; +use std::string::ToString; #[cfg(not(feature = "unchecked"))] use num_traits::{CheckedAdd as Add, CheckedSub as Sub}; #[cfg(feature = "unchecked")] -use crate::stdlib::ops::{Add, Sub}; +use std::ops::{Add, Sub}; fn get_range(from: T, to: T) -> Result, Box> { Ok(from..to) @@ -207,7 +209,7 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { pub fn new(from: Decimal, to: Decimal, step: Decimal) -> Result> { #[cfg(not(feature = "unchecked"))] if step.is_zero() { - use crate::stdlib::string::ToString; + use std::string::ToString; return EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE)), @@ -251,7 +253,7 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { } } - impl crate::stdlib::iter::FusedIterator for StepDecimalRange {} + impl std::iter::FusedIterator for StepDecimalRange {} lib.set_iterator::(); diff --git a/src/packages/logic.rs b/src/packages/logic.rs index 6a2cbe68..56339aa4 100644 --- a/src/packages/logic.rs +++ b/src/packages/logic.rs @@ -2,6 +2,8 @@ use crate::def_package; use crate::plugin::*; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(any( not(feature = "no_float"), diff --git a/src/packages/map_basic.rs b/src/packages/map_basic.rs index d76dbcb7..a7f068da 100644 --- a/src/packages/map_basic.rs +++ b/src/packages/map_basic.rs @@ -3,6 +3,8 @@ use crate::engine::OP_EQUALS; use crate::plugin::*; use crate::{def_package, Dynamic, ImmutableString, Map, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_index"))] use crate::Array; diff --git a/src/packages/math_basic.rs b/src/packages/math_basic.rs index 977fe2ed..1012b6d2 100644 --- a/src/packages/math_basic.rs +++ b/src/packages/math_basic.rs @@ -2,6 +2,8 @@ use crate::plugin::*; use crate::{def_package, Position, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_float"))] use crate::FLOAT; @@ -9,9 +11,6 @@ use crate::FLOAT; #[cfg(not(feature = "no_float"))] use crate::result::EvalAltResult; -#[cfg(not(feature = "no_float"))] -use crate::stdlib::format; - #[cfg(feature = "no_std")] #[cfg(not(feature = "no_float"))] use num_traits::Float; @@ -194,16 +193,16 @@ mod float_functions { #[rhai_fn(name = "E")] pub fn e() -> FLOAT { #[cfg(not(feature = "f32_float"))] - return crate::stdlib::f64::consts::E; + return std::f64::consts::E; #[cfg(feature = "f32_float")] - return crate::stdlib::f32::consts::E; + return std::f32::consts::E; } #[rhai_fn(name = "PI")] pub fn pi() -> FLOAT { #[cfg(not(feature = "f32_float"))] - return crate::stdlib::f64::consts::PI; + return std::f64::consts::PI; #[cfg(feature = "f32_float")] - return crate::stdlib::f32::consts::PI; + return std::f32::consts::PI; } pub fn to_radians(x: FLOAT) -> FLOAT { x.to_radians() @@ -304,11 +303,11 @@ mod float_functions { #[cfg(feature = "decimal")] #[export_module] mod decimal_functions { - use crate::stdlib::convert::TryFrom; use rust_decimal::{ prelude::{FromStr, RoundingStrategy}, Decimal, }; + use std::convert::TryFrom; #[rhai_fn(name = "floor", get = "floor")] pub fn floor(x: Decimal) -> Decimal { diff --git a/src/packages/pkg_core.rs b/src/packages/pkg_core.rs index 284c5997..54dff2ca 100644 --- a/src/packages/pkg_core.rs +++ b/src/packages/pkg_core.rs @@ -3,6 +3,8 @@ use super::fn_basic::BasicFnPackage; use super::iter_basic::BasicIteratorPackage; use super::logic::LogicPackage; use super::string_basic::BasicStringPackage; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; use crate::def_package; diff --git a/src/packages/pkg_std.rs b/src/packages/pkg_std.rs index d2790d50..3c18d603 100644 --- a/src/packages/pkg_std.rs +++ b/src/packages/pkg_std.rs @@ -7,6 +7,8 @@ use super::pkg_core::CorePackage; use super::string_more::MoreStringPackage; #[cfg(not(feature = "no_std"))] use super::time_basic::BasicTimePackage; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; use crate::def_package; diff --git a/src/packages/string_basic.rs b/src/packages/string_basic.rs index 5d05da0b..8959e868 100644 --- a/src/packages/string_basic.rs +++ b/src/packages/string_basic.rs @@ -1,8 +1,9 @@ #![allow(non_snake_case)] use crate::plugin::*; -use crate::stdlib::{format, string::ToString}; use crate::{def_package, FnPtr}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_index"))] use crate::Array; @@ -69,10 +70,6 @@ mod print_debug_functions { #[cfg(not(feature = "no_float"))] pub mod float_functions { - #[cfg(feature = "no_std")] - #[cfg(not(feature = "no_float"))] - use num_traits::Float; - use crate::ast::FloatWrapper; #[rhai_fn(name = "print", name = "to_string")] @@ -106,7 +103,7 @@ mod print_debug_functions { )] pub fn format_array(ctx: NativeCallContext, array: &mut Array) -> ImmutableString { let len = array.len(); - let mut result = crate::stdlib::string::String::with_capacity(len * 5 + 2); + let mut result = std::string::String::with_capacity(len * 5 + 2); result.push_str("["); array.iter_mut().enumerate().for_each(|(i, x)| { @@ -133,7 +130,7 @@ mod print_debug_functions { )] pub fn format_map(ctx: NativeCallContext, map: &mut Map) -> ImmutableString { let len = map.len(); - let mut result = crate::stdlib::string::String::with_capacity(len * 5 + 3); + let mut result = std::string::String::with_capacity(len * 5 + 3); result.push_str("#{"); map.iter_mut().enumerate().for_each(|(i, (k, v))| { diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index 3efd6dd2..97700e86 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -1,10 +1,10 @@ #![allow(non_snake_case)] use crate::plugin::*; -use crate::stdlib::{ - any::TypeId, boxed::Box, format, mem, string::String, string::ToString, vec::Vec, -}; use crate::{def_package, Dynamic, ImmutableString, StaticVec, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{any::TypeId, mem}; use super::string_basic::{print_with_func, FUNC_TO_STRING}; @@ -422,7 +422,6 @@ mod string_functions { #[cfg(not(feature = "no_index"))] pub mod arrays { - use crate::stdlib::vec; use crate::{Array, ImmutableString}; #[rhai_fn(name = "split")] diff --git a/src/packages/time_basic.rs b/src/packages/time_basic.rs index b60d4f6a..0ef705c9 100644 --- a/src/packages/time_basic.rs +++ b/src/packages/time_basic.rs @@ -2,14 +2,15 @@ use super::{arithmetic::make_err as make_arithmetic_err, math_basic::MAX_INT}; use crate::plugin::*; -use crate::stdlib::boxed::Box; use crate::{def_package, Dynamic, EvalAltResult, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_float"))] use crate::FLOAT; #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] -use crate::stdlib::time::{Duration, Instant}; +use std::time::{Duration, Instant}; #[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))] use instant::{Duration, Instant}; diff --git a/src/parse_error.rs b/src/parse_error.rs index a7b75cba..87454019 100644 --- a/src/parse_error.rs +++ b/src/parse_error.rs @@ -1,12 +1,13 @@ //! Module containing error definitions for the parsing process. -use crate::stdlib::{ - boxed::Box, - error::Error, - fmt, - string::{String, ToString}, -}; use crate::{EvalAltResult, Position}; +#[cfg(feature = "no_std")] +use core_error::Error; +#[cfg(not(feature = "no_std"))] +use std::error::Error; +use std::fmt; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; /// _(INTERNALS)_ Error encountered when tokenizing the script text. /// Exported under the `internals` feature only. diff --git a/src/parser.rs b/src/parser.rs index a7024884..a0d03b43 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -9,17 +9,6 @@ use crate::engine::{Precedence, KEYWORD_THIS, OP_CONTAINS}; use crate::module::NamespaceRef; use crate::optimize::optimize_into_ast; use crate::optimize::OptimizationLevel; -use crate::stdlib::{ - boxed::Box, - collections::BTreeMap, - format, - hash::{Hash, Hasher}, - iter::empty, - num::{NonZeroU8, NonZeroUsize}, - string::ToString, - vec, - vec::Vec, -}; use crate::syntax::{CustomSyntax, MARKER_BLOCK, MARKER_EXPR, MARKER_IDENT}; use crate::token::{ is_keyword_function, is_valid_identifier, Token, TokenStream, TokenizerControl, @@ -29,6 +18,14 @@ use crate::{ calc_fn_hash, Dynamic, Engine, Identifier, LexError, ParseError, ParseErrorType, Position, Scope, Shared, StaticVec, AST, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ + collections::BTreeMap, + hash::{Hash, Hasher}, + iter::empty, + num::{NonZeroU8, NonZeroUsize}, +}; #[cfg(not(feature = "no_float"))] use crate::FLOAT; @@ -2501,7 +2498,7 @@ fn parse_stmt( #[cfg(not(feature = "no_function"))] #[cfg(feature = "metadata")] let comments = { - let mut comments: StaticVec = Default::default(); + let mut comments: StaticVec = Default::default(); let mut comments_pos = Position::NONE; // Handle doc-comments. @@ -2756,7 +2753,7 @@ fn parse_fn( mut settings: ParseSettings, #[cfg(not(feature = "no_function"))] #[cfg(feature = "metadata")] - comments: StaticVec, + comments: StaticVec, ) -> Result { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; diff --git a/src/plugin.rs b/src/plugin.rs index 9ea4bb10..c183d736 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -1,11 +1,13 @@ //! Module defining macros for developing _plugins_. pub use crate::fn_native::{CallableFunction, FnCallArgs}; -pub use crate::stdlib::{any::TypeId, boxed::Box, format, mem, string::ToString}; pub use crate::{ Dynamic, Engine, EvalAltResult, FnAccess, FnNamespace, ImmutableString, Module, NativeCallContext, Position, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +pub use std::{any::TypeId, mem}; pub type RhaiResult = Result>; #[cfg(not(features = "no_module"))] diff --git a/src/result.rs b/src/result.rs index 4652aaa1..8a873f2a 100644 --- a/src/result.rs +++ b/src/result.rs @@ -1,12 +1,13 @@ //! Module containing error definitions for the evaluation process. -use crate::stdlib::{ - boxed::Box, - error::Error, - fmt, - string::{String, ToString}, -}; use crate::{Dynamic, ImmutableString, ParseErrorType, Position, INT}; +#[cfg(feature = "no_std")] +use core_error::Error; +#[cfg(not(feature = "no_std"))] +use std::error::Error; +use std::fmt; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; /// Evaluation result. /// @@ -335,11 +336,7 @@ impl EvalAltResult { pub(crate) fn dump_fields(&self, map: &mut crate::Map) { map.insert( "error".into(), - crate::stdlib::format!("{:?}", self) - .split('(') - .next() - .unwrap() - .into(), + format!("{:?}", self).split('(').next().unwrap().into(), ); match self { diff --git a/src/scope.rs b/src/scope.rs index 7d4b114b..373ad0cb 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -1,8 +1,10 @@ //! Module that defines the [`Scope`] type representing a function call-stack scope. use crate::dynamic::{AccessMode, Variant}; -use crate::stdlib::{borrow::Cow, boxed::Box, iter, vec::Vec}; use crate::{Dynamic, Identifier, StaticVec}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{borrow::Cow, iter::Extend}; /// Keep a number of entries inline (since [`Dynamic`] is usually small enough). const SCOPE_SIZE: usize = 16; @@ -498,7 +500,7 @@ impl<'a> Scope<'a> { } } -impl<'a, K: Into>> iter::Extend<(K, Dynamic)> for Scope<'a> { +impl<'a, K: Into>> Extend<(K, Dynamic)> for Scope<'a> { #[inline(always)] fn extend>(&mut self, iter: T) { iter.into_iter().for_each(|(name, value)| { diff --git a/src/serde/de.rs b/src/serde/de.rs index 802a47e2..2d81cff9 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -2,10 +2,12 @@ use super::str::StringSliceDeserializer; use crate::dynamic::Union; -use crate::stdlib::{any::type_name, boxed::Box, fmt, string::ToString}; use crate::{Dynamic, EvalAltResult, ImmutableString, LexError, Position}; use serde::de::{DeserializeSeed, Error, IntoDeserializer, MapAccess, SeqAccess, Visitor}; use serde::{Deserialize, Deserializer}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{any::type_name, fmt}; #[cfg(not(feature = "no_index"))] use crate::Array; diff --git a/src/serde/deserialize.rs b/src/serde/deserialize.rs index a507eb0c..b3cf6098 100644 --- a/src/serde/deserialize.rs +++ b/src/serde/deserialize.rs @@ -1,8 +1,10 @@ //! Implementations of [`serde::Deserialize`]. -use crate::stdlib::{fmt, string::ToString}; use crate::{Dynamic, ImmutableString, INT}; use serde::de::{Deserialize, Deserializer, Error, Visitor}; +use std::fmt; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_index"))] use crate::Array; @@ -95,8 +97,8 @@ impl<'d> Visitor<'d> for DynamicVisitor { #[cfg(feature = "no_float")] #[cfg(feature = "decimal")] fn visit_f32(self, v: f32) -> Result { - use crate::stdlib::convert::TryFrom; use rust_decimal::Decimal; + use std::convert::TryFrom; Decimal::try_from(v) .map(|v| v.into()) @@ -105,8 +107,8 @@ impl<'d> Visitor<'d> for DynamicVisitor { #[cfg(feature = "no_float")] #[cfg(feature = "decimal")] fn visit_f64(self, v: f64) -> Result { - use crate::stdlib::convert::TryFrom; use rust_decimal::Decimal; + use std::convert::TryFrom; Decimal::try_from(v) .map(|v| v.into()) diff --git a/src/serde/metadata.rs b/src/serde/metadata.rs index 96b67acd..2fe005fd 100644 --- a/src/serde/metadata.rs +++ b/src/serde/metadata.rs @@ -1,11 +1,8 @@ -use crate::stdlib::{ - cmp::Ordering, - collections::BTreeMap, - string::{String, ToString}, - vec::Vec, -}; use crate::{Engine, AST}; use serde::{Deserialize, Serialize}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{cmp::Ordering, collections::BTreeMap}; #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/src/serde/ser.rs b/src/serde/ser.rs index 73cab25c..147f290f 100644 --- a/src/serde/ser.rs +++ b/src/serde/ser.rs @@ -1,11 +1,13 @@ //! Implement serialization support of [`Dynamic`][crate::Dynamic] for [`serde`]. -use crate::stdlib::{boxed::Box, fmt, string::ToString}; use crate::{Dynamic, EvalAltResult, Position, RhaiResult}; use serde::ser::{ Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct, }; use serde::{Serialize, Serializer}; +use std::fmt; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_index"))] use crate::Array; @@ -220,8 +222,8 @@ impl Serializer for &mut DynamicSerializer { #[cfg(feature = "no_float")] #[cfg(feature = "decimal")] { - use crate::stdlib::convert::TryFrom; use rust_decimal::Decimal; + use std::convert::TryFrom; Decimal::try_from(v) .map(|v| v.into()) @@ -236,8 +238,8 @@ impl Serializer for &mut DynamicSerializer { #[cfg(feature = "no_float")] #[cfg(feature = "decimal")] { - use crate::stdlib::convert::TryFrom; use rust_decimal::Decimal; + use std::convert::TryFrom; Decimal::try_from(v) .map(|v| v.into()) @@ -539,7 +541,7 @@ impl SerializeMap for DynamicSerializer { ) -> Result<(), Box> { #[cfg(not(feature = "no_object"))] { - let key = crate::stdlib::mem::take(&mut self._key) + let key = std::mem::take(&mut self._key) .take_immutable_string() .map_err(|typ| { EvalAltResult::ErrorMismatchDataType( diff --git a/src/serde/serialize.rs b/src/serde/serialize.rs index ba75842a..43d5189a 100644 --- a/src/serde/serialize.rs +++ b/src/serde/serialize.rs @@ -1,9 +1,10 @@ //! Implementations of [`serde::Serialize`]. use crate::dynamic::{Union, Variant}; -use crate::stdlib::string::ToString; use crate::{Dynamic, ImmutableString}; use serde::ser::{Serialize, Serializer}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; #[cfg(not(feature = "no_object"))] use serde::ser::SerializeMap; diff --git a/src/serde/str.rs b/src/serde/str.rs index ccc7a0a7..1063ffd4 100644 --- a/src/serde/str.rs +++ b/src/serde/str.rs @@ -1,8 +1,10 @@ //! Implement deserialization support of [`ImmutableString`][crate::ImmutableString] for [`serde`]. -use crate::stdlib::{any::type_name, boxed::Box}; use crate::{EvalAltResult, Position}; use serde::de::{Deserializer, Visitor}; +use std::any::type_name; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; /// Deserializer for `ImmutableString`. pub struct StringSliceDeserializer<'a> { diff --git a/src/stdlib.rs b/src/stdlib.rs deleted file mode 100644 index e0a32470..00000000 --- a/src/stdlib.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! Helper module which defines most of the needed features from `std` for `no-std` builds. - -#[cfg(feature = "no_std")] -mod inner { - pub use core::{ - any, arch, array, ascii, cell, char, clone, cmp, convert, default, f32, f64, ffi, fmt, - future, hash, hint, i16, i32, i64, i8, isize, iter, marker, mem, num, ops, option, panic, - pin, prelude, ptr, result, slice, str, task, time, u16, u32, u64, u8, usize, - }; - - #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] - pub use core::{i128, u128}; - - #[cfg(feature = "sync")] - pub use alloc::sync; - - pub use alloc::{borrow, boxed, format, rc, string, vec}; - - pub use core_error as error; - - pub mod collections { - pub use alloc::collections::btree_map::BTreeMap; - pub use alloc::collections::btree_set::BTreeSet; - } -} - -#[cfg(not(feature = "no_std"))] -mod inner { - pub use std::*; -} - -pub use self::inner::*; diff --git a/src/syntax.rs b/src/syntax.rs index dc661ea8..7d951cea 100644 --- a/src/syntax.rs +++ b/src/syntax.rs @@ -3,12 +3,13 @@ use crate::ast::Expr; use crate::engine::EvalContext; use crate::fn_native::SendSync; -use crate::stdlib::{boxed::Box, format, string::ToString}; use crate::token::{is_valid_identifier, Token}; use crate::{ Engine, Identifier, ImmutableString, LexError, ParseError, Position, RhaiResult, Shared, StaticVec, }; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; pub const MARKER_EXPR: &str = "$expr$"; pub const MARKER_BLOCK: &str = "$block$"; diff --git a/src/token.rs b/src/token.rs index a035d278..7b497665 100644 --- a/src/token.rs +++ b/src/token.rs @@ -4,18 +4,19 @@ use crate::engine::{ Precedence, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_THIS, KEYWORD_TYPE_OF, }; -use crate::stdlib::{ +use crate::{Engine, LexError, StaticVec, INT}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ borrow::Cow, cell::Cell, - char, fmt, format, + char, fmt, iter::{FusedIterator, Peekable}, num::NonZeroUsize, ops::{Add, AddAssign}, rc::Rc, str::{Chars, FromStr}, - string::{String, ToString}, }; -use crate::{Engine, LexError, StaticVec, INT}; #[cfg(not(feature = "no_float"))] use crate::{ast::FloatWrapper, FLOAT}; diff --git a/src/unsafe.rs b/src/unsafe.rs index de7aa1bc..54cbab67 100644 --- a/src/unsafe.rs +++ b/src/unsafe.rs @@ -1,9 +1,10 @@ //! A helper module containing unsafe utility functions. use crate::dynamic::Variant; -use crate::stdlib::{ +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ any::{Any, TypeId}, - boxed::Box, mem, ptr, }; diff --git a/src/utils.rs b/src/utils.rs index e972d023..6b73aa64 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,20 +1,19 @@ //! Module containing various utility types and functions. use crate::fn_native::{shared_make_mut, shared_take}; -use crate::stdlib::{ +use crate::{Identifier, Shared}; +#[cfg(feature = "no_std")] +use std::prelude::v1::*; +use std::{ any::TypeId, borrow::Borrow, - boxed::Box, cmp::Ordering, fmt, - fmt::{Debug, Display}, hash::{BuildHasher, Hash, Hasher}, iter::FromIterator, ops::{Add, AddAssign, Deref, Sub, SubAssign}, str::FromStr, - string::{String, ToString}, }; -use crate::{Identifier, Shared}; /// A hasher that only takes one single [`u64`] and returns it as a hash key. /// @@ -251,17 +250,17 @@ impl<'a> FromIterator for ImmutableString { } } -impl Display for ImmutableString { +impl fmt::Display for ImmutableString { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - Display::fmt(self.0.as_str(), f) + fmt::Display::fmt(self.0.as_str(), f) } } -impl Debug for ImmutableString { +impl fmt::Debug for ImmutableString { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - Debug::fmt(self.0.as_str(), f) + fmt::Debug::fmt(self.0.as_str(), f) } } @@ -631,7 +630,7 @@ impl ImmutableString { /// yet interned. #[derive(Debug, Clone, Default, Hash)] pub struct IdentifierBuilder( - #[cfg(feature = "no_smartstring")] crate::stdlib::collections::BTreeSet, + #[cfg(feature = "no_smartstring")] std::collections::BTreeSet, ); impl IdentifierBuilder {