diff --git a/examples/compiler.rs b/examples/compiler.rs index e4ef2755..84de661c 100644 --- a/examples/compiler.rs +++ b/examples/compiler.rs @@ -1,11 +1,11 @@ -use std::{error::Error as StdError, fs::File, io::Read}; - use clap::{crate_description, crate_name, crate_version, Arg, Command}; - -use piccolo::{ - compiler::{self, interning::BasicInterner, string_utils::debug_utf8_lossy, CompiledPrototype}, - io, -}; +use piccolo::compiler::interning::BasicInterner; +use piccolo::compiler::string_utils::debug_utf8_lossy; +use piccolo::compiler::{self, CompiledPrototype}; +use piccolo::io; +use std::error::Error as StdError; +use std::fs::File; +use std::io::Read; fn print_function>(function: &CompiledPrototype, depth: usize) { let indent = " ".repeat(depth); diff --git a/examples/execute.rs b/examples/execute.rs index 0b6a1d9f..d5da51f5 100644 --- a/examples/execute.rs +++ b/examples/execute.rs @@ -1,8 +1,8 @@ +use piccolo::io::buffered_read; +use piccolo::{Closure, Executor, Lua}; use std::fs::File; use std::io::Read; -use piccolo::{io::buffered_read, Closure, Executor, Lua}; - fn main() -> Result<(), Box> { // Load the Lua file let mut file = buffered_read(File::open("./examples/execute.lua")?)?; diff --git a/examples/interpreter.rs b/examples/interpreter.rs index 91f18592..6b3b9679 100644 --- a/examples/interpreter.rs +++ b/examples/interpreter.rs @@ -1,14 +1,13 @@ -use std::fs::File; -use std::{error::Error as StdError, io::Read}; - use clap::{crate_description, crate_name, crate_version, Arg, ArgAction, Command}; -use rustyline::DefaultEditor; - +use piccolo::compiler::{ParseError, ParseErrorKind}; use piccolo::{ - compiler::{ParseError, ParseErrorKind}, io, meta_ops, Callback, CallbackReturn, Closure, Executor, ExternError, Function, Lua, StashedExecutor, }; +use rustyline::DefaultEditor; +use std::error::Error as StdError; +use std::fs::File; +use std::io::Read; fn run_code(lua: &mut Lua, executor: &StashedExecutor, code: &str) -> Result<(), ExternError> { lua.try_enter(|ctx| { diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..76e76247 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +newline_style = "Unix" +imports_granularity = "Module" +group_imports = "One" diff --git a/src/any.rs b/src/any.rs index 2c505217..d30b4fa3 100644 --- a/src/any.rs +++ b/src/any.rs @@ -1,14 +1,9 @@ -use std::{ - any::TypeId, - fmt, - hash::{Hash, Hasher}, -}; - -use gc_arena::{ - arena::Root, - barrier::{self, Write}, - Collect, Gc, Mutation, Rootable, -}; +use core::any::TypeId; +use core::fmt; +use core::hash::{Hash, Hasher}; +use gc_arena::arena::Root; +use gc_arena::barrier::{self, Write}; +use gc_arena::{Collect, Gc, Mutation, Rootable}; /// A `Gc` pointer to any type `T: Collect + 'gc` which allows safe downcasting. /// @@ -187,9 +182,8 @@ impl<'gc, M> Any<'gc, M> { #[cfg(test)] mod tests { - use gc_arena::arena::rootless_mutate; - use super::*; + use gc_arena::arena::rootless_mutate; #[test] fn test_any_value() { diff --git a/src/async_callback.rs b/src/async_callback.rs index 675f8873..357e7f39 100644 --- a/src/async_callback.rs +++ b/src/async_callback.rs @@ -1,21 +1,16 @@ -use std::{ - cell::Cell, - future::{poll_fn, Future}, - marker::PhantomData, - mem, - pin::Pin, - ptr, - rc::Rc, - task::{self, Poll, RawWaker, RawWakerVTable, Waker}, -}; - -use gc_arena::{Collect, DynamicRootSet, Mutation}; - +use crate::stash::{Fetchable, Stashable}; use crate::{ - stash::{Fetchable, Stashable}, BoxSequence, Context, Error, Execution, Function, Sequence, SequencePoll, Stack, StashedError, StashedFunction, StashedThread, Thread, }; +use alloc::rc::Rc; +use core::cell::Cell; +use core::future::{poll_fn, Future}; +use core::marker::PhantomData; +use core::pin::Pin; +use core::task::{self, Poll, RawWaker, RawWakerVTable, Waker}; +use core::{mem, ptr}; +use gc_arena::{Collect, DynamicRootSet, Mutation}; /// Create a [`Sequence`] impl from a [`Future`] that can suspend, call Lua functions, yield to Lua, /// and resume threads as async method calls via a held [`AsyncSequence`] proxy. @@ -23,12 +18,12 @@ use crate::{ /// Can be used to implement `Sequence` in a way MUCH easier than manual state machines. /// /// Currently uses `async` to do what in the future could be more directly accomplished with -/// coroutines (see the unstable [`std::ops::Coroutine`] trait). The [`std::task::Context`] +/// coroutines (see the unstable [`core::ops::Coroutine`] trait). The [`core::task::Context`] /// available within the created future is **meaningless** and has a NOOP waker; we are only using /// `async` as a stable way to express what would be better expressed as a simple coroutine. /// /// It is possible to integrate proper async APIs with `piccolo`, and to even have a method to -/// "wake" Lua coroutines with a *real* [`std::task::Waker`], but simply calling an external async +/// "wake" Lua coroutines with a *real* [`core::task::Waker`], but simply calling an external async /// function from the created future here is *not* the way to do it. It will not do what you want, /// and probably will result in panics. /// diff --git a/src/callback.rs b/src/callback.rs index 28898ba9..3bdcebb5 100644 --- a/src/callback.rs +++ b/src/callback.rs @@ -1,13 +1,10 @@ -use std::{ - fmt, - hash::{Hash, Hasher}, - pin::Pin, -}; - -use allocator_api2::boxed; -use gc_arena::{allocator_api::MetricsAlloc, Collect, Gc, Mutation}; - use crate::{Context, Error, Execution, Function, Stack, Thread}; +use allocator_api2::boxed; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::pin::Pin; +use gc_arena::allocator_api::MetricsAlloc; +use gc_arena::{Collect, Gc, Mutation}; /// Describes the next action for an [`Executor`](crate::Executor) to take after a callback has /// returned. diff --git a/src/closure.rs b/src/closure.rs index 31325544..a91d6bed 100644 --- a/src/closure.rs +++ b/src/closure.rs @@ -1,17 +1,15 @@ -use std::hash::{Hash, Hasher}; - +use crate::compiler::{self, CompiledPrototype, FunctionRef, LineNumber}; +use crate::opcode::OpCode; +use crate::thread::OpenUpValue; +use crate::types::UpValueDescriptor; +use crate::{Constant, Context, String, Table, Value}; use allocator_api2::{boxed, vec, SliceExt}; -use gc_arena::{allocator_api::MetricsAlloc, lock::Lock, Collect, Gc, Mutation}; +use core::hash::{Hash, Hasher}; +use gc_arena::allocator_api::MetricsAlloc; +use gc_arena::lock::Lock; +use gc_arena::{Collect, Gc, Mutation}; use thiserror::Error; -use crate::{ - compiler::{self, CompiledPrototype, FunctionRef, LineNumber}, - opcode::OpCode, - thread::OpenUpValue, - types::UpValueDescriptor, - Constant, Context, String, Table, Value, -}; - // Note: These errors must not have #[error(transparent)] so that // anyhow::Error::root_cause and downcasting work as expected by the // interpreter. (Even though that gives slightly cleaner error messages). diff --git a/src/compiler/compiler.rs b/src/compiler/compiler.rs index 29a2b79a..48b184eb 100644 --- a/src/compiler/compiler.rs +++ b/src/compiler/compiler.rs @@ -1,41 +1,33 @@ -use std::{ - collections::{hash_map, VecDeque}, - fmt, iter, mem, +use super::lexer::LineNumber; +use super::operators::{ + categorize_binop, comparison_binop_const_fold, comparison_binop_operation, + simple_binop_const_fold, simple_binop_operation, unop_const_fold, unop_operation, + BinOpCategory, ComparisonBinOp, ShortCircuitBinOp, SimpleBinOp, }; - +use super::parser::{ + AssignmentStatement, AssignmentTarget, BinaryOperator, Block, CallSuffix, Chunk, + ConstructorField, Expression, FieldSuffix, ForStatement, FunctionCallStatement, + FunctionDefinition, FunctionStatement, HeadExpression, IfStatement, LocalAttributes, + LocalFunctionStatement, LocalStatement, PrimaryExpression, RecordKey, RepeatStatement, + ReturnStatement, SimpleExpression, Statement, SuffixPart, SuffixedExpression, TableConstructor, + UnaryOperator, WhileStatement, +}; +use super::register_allocator::RegisterAllocator; +use super::StringInterner; +use crate::constant::IdenticalConstant; +use crate::opcode::{OpCode, Operation, RCIndex}; +use crate::types::{ + ConstantIndex16, ConstantIndex8, Opt254, PrototypeIndex, RegisterIndex, UpValueDescriptor, + UpValueIndex, VarCount, +}; +use crate::Constant; use ahash::HashMap; +use alloc::collections::VecDeque; +use core::{fmt, iter, mem}; use gc_arena::Collect; +use std::collections::hash_map; use thiserror::Error; -use crate::{ - constant::IdenticalConstant, - opcode::{OpCode, Operation, RCIndex}, - types::{ - ConstantIndex16, ConstantIndex8, Opt254, PrototypeIndex, RegisterIndex, UpValueDescriptor, - UpValueIndex, VarCount, - }, - Constant, -}; - -use super::{ - lexer::LineNumber, - operators::{ - categorize_binop, comparison_binop_const_fold, comparison_binop_operation, - simple_binop_const_fold, simple_binop_operation, unop_const_fold, unop_operation, - BinOpCategory, ComparisonBinOp, ShortCircuitBinOp, SimpleBinOp, - }, - parser::{ - AssignmentStatement, AssignmentTarget, BinaryOperator, Block, CallSuffix, Chunk, - ConstructorField, Expression, FieldSuffix, ForStatement, FunctionCallStatement, - FunctionDefinition, FunctionStatement, HeadExpression, IfStatement, LocalAttributes, - LocalFunctionStatement, LocalStatement, PrimaryExpression, RecordKey, RepeatStatement, - ReturnStatement, SimpleExpression, Statement, SuffixPart, SuffixedExpression, - TableConstructor, UnaryOperator, WhileStatement, - }, - register_allocator::RegisterAllocator, - StringInterner, -}; - #[derive(Debug, Copy, Clone, Error)] pub enum CompileErrorKind { #[error("insufficient available registers")] diff --git a/src/compiler/interning.rs b/src/compiler/interning.rs index 2579545a..04a2ece1 100644 --- a/src/compiler/interning.rs +++ b/src/compiler/interning.rs @@ -1,6 +1,5 @@ -use std::rc::Rc; - use ahash::HashSet; +use alloc::rc::Rc; pub trait StringInterner { type String: AsRef<[u8]> + Clone; diff --git a/src/compiler/lexer.rs b/src/compiler/lexer.rs index f016b9f8..a62fefed 100644 --- a/src/compiler/lexer.rs +++ b/src/compiler/lexer.rs @@ -1,17 +1,14 @@ -use std::{char, fmt}; - -use gc_arena::Collect; -use thiserror::Error; - +use super::string_utils::{ + debug_utf8_lossy, is_alpha, is_digit, is_newline, FORM_FEED, VERTICAL_TAB, +}; +use super::StringInterner; use crate::compiler::string_utils::{ from_digit, from_hex_digit, is_hex_digit, is_space, read_dec_float, read_dec_integer, read_hex_float, read_hex_integer, ALERT_BEEP, BACKSPACE, }; - -use super::{ - string_utils::{debug_utf8_lossy, is_alpha, is_digit, is_newline, FORM_FEED, VERTICAL_TAB}, - StringInterner, -}; +use core::{char, fmt}; +use gc_arena::Collect; +use thiserror::Error; #[derive(Clone)] pub enum Token { @@ -920,11 +917,9 @@ fn get_reserved_word_token(word: &[u8]) -> Option> { #[cfg(test)] mod tests { - use std::rc::Rc; - - use crate::compiler::interning::BasicInterner; - use super::*; + use crate::compiler::interning::BasicInterner; + use alloc::rc::Rc; fn test_tokens(source: &str, tokens: &[Token>]) { let mut lexer = Lexer::new(source.as_bytes(), BasicInterner::default()); diff --git a/src/compiler/mod.rs b/src/compiler/mod.rs index 4be527cb..479c8b13 100644 --- a/src/compiler/mod.rs +++ b/src/compiler/mod.rs @@ -6,9 +6,9 @@ pub mod parser; mod register_allocator; pub mod string_utils; -pub use self::{ - compiler::{compile_chunk, CompileError, CompileErrorKind, CompiledPrototype, FunctionRef}, - interning::StringInterner, - lexer::LineNumber, - parser::{parse_chunk, ParseError, ParseErrorKind}, +pub use self::compiler::{ + compile_chunk, CompileError, CompileErrorKind, CompiledPrototype, FunctionRef, }; +pub use self::interning::StringInterner; +pub use self::lexer::LineNumber; +pub use self::parser::{parse_chunk, ParseError, ParseErrorKind}; diff --git a/src/compiler/operators.rs b/src/compiler/operators.rs index 12a2b171..5b6a257a 100644 --- a/src/compiler/operators.rs +++ b/src/compiler/operators.rs @@ -1,10 +1,7 @@ -use crate::{ - opcode::{Operation, RCIndex}, - types::RegisterIndex, - Constant, -}; - use super::parser::{BinaryOperator, UnaryOperator}; +use crate::opcode::{Operation, RCIndex}; +use crate::types::RegisterIndex; +use crate::Constant; // Binary operators which map directly to a single opcode #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] diff --git a/src/compiler/parser.rs b/src/compiler/parser.rs index 7ced0c28..f47de924 100644 --- a/src/compiler/parser.rs +++ b/src/compiler/parser.rs @@ -1,12 +1,9 @@ -use std::{fmt, ops, rc::Rc}; - +use super::lexer::{LexError, Lexer, LineNumber, Token}; +use super::StringInterner; +use alloc::rc::Rc; +use core::{fmt, ops}; use thiserror::Error; -use super::{ - lexer::{LexError, Lexer, LineNumber, Token}, - StringInterner, -}; - #[derive(Debug, Clone)] pub struct LineAnnotated { pub inner: T, diff --git a/src/compiler/string_utils.rs b/src/compiler/string_utils.rs index 1abe1f96..ac41814f 100644 --- a/src/compiler/string_utils.rs +++ b/src/compiler/string_utils.rs @@ -1,7 +1,5 @@ -use std::{ - fmt::{self, Write as _}, - str, -}; +use core::fmt::{self, Write as _}; +use core::str; pub fn trim_whitespace(mut s: &[u8]) -> &[u8] { s = &s[s.iter().position(|&c| !is_space(c)).unwrap_or(s.len())..]; diff --git a/src/constant.rs b/src/constant.rs index fb0bb259..f675683c 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -1,8 +1,6 @@ -use std::hash::{Hash, Hasher}; - -use gc_arena::Collect; - use crate::compiler::string_utils::{read_float, read_integer, trim_whitespace}; +use core::hash::{Hash, Hasher}; +use gc_arena::Collect; #[derive(Debug, Copy, Clone, Collect)] #[collect(no_drop)] diff --git a/src/conversion.rs b/src/conversion.rs index 6a1616d0..2396de8a 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -1,8 +1,8 @@ -use std::{array, iter, ops, string::String as StdString}; - use crate::{ Callback, Closure, Context, Function, String, Table, Thread, TypeError, UserData, Value, }; +use alloc::string::String as StdString; +use core::{array, iter, ops}; pub trait IntoValue<'gc> { fn into_value(self, ctx: Context<'gc>) -> Value<'gc>; diff --git a/src/error.rs b/src/error.rs index 462c9cd3..635b289b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,12 +1,13 @@ -use std::{error::Error as StdError, fmt, string::String as StdString, sync::Arc}; - -use gc_arena::{Collect, Gc, Rootable}; -use thiserror::Error; - use crate::{ Callback, CallbackReturn, Context, FromValue, Function, IntoValue, MetaMethod, Singleton, Table, UserData, Value, }; +use alloc::string::String as StdString; +use alloc::sync::Arc; +use core::error::Error as StdError; +use core::fmt; +use gc_arena::{Collect, Gc, Rootable}; +use thiserror::Error; #[derive(Debug, Clone, Copy, Error)] #[error("type error, expected {expected}, found {found}")] diff --git a/src/finalizers.rs b/src/finalizers.rs index 9a94d0b8..bb101e81 100644 --- a/src/finalizers.rs +++ b/src/finalizers.rs @@ -1,6 +1,7 @@ -use gc_arena::{lock::RefLock, Collect, Finalization, Gc, GcWeak, Mutation}; - -use crate::{thread::ThreadInner, Thread}; +use crate::thread::ThreadInner; +use crate::Thread; +use gc_arena::lock::RefLock; +use gc_arena::{Collect, Finalization, Gc, GcWeak, Mutation}; #[derive(Copy, Clone, Collect)] #[collect(no_drop)] diff --git a/src/function.rs b/src/function.rs index 10558768..1f24221a 100644 --- a/src/function.rs +++ b/src/function.rs @@ -1,11 +1,9 @@ -use std::pin::Pin; - -use gc_arena::{Collect, Gc, Mutation}; - use crate::{ BoxSequence, Callback, CallbackReturn, Closure, Context, Error, Execution, IntoMultiValue, Sequence, SequencePoll, Stack, }; +use core::pin::Pin; +use gc_arena::{Collect, Gc, Mutation}; /// Any callable Lua value (either a [`Closure`] or a [`Callback`]). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Collect)] diff --git a/src/io.rs b/src/io.rs index 681d481b..29c9ecf0 100644 --- a/src/io.rs +++ b/src/io.rs @@ -1,4 +1,4 @@ -use std::io::{self, BufRead, BufReader, Read}; +use std::io::{BufRead, BufReader, Error, Read}; /// Takes an `R: BufRead` and: /// @@ -8,16 +8,14 @@ use std::io::{self, BufRead, BufReader, Read}; /// /// This mimics the initial behavior of luaL_loadfile(x). In order to correctly detect and skip the /// BOM and unix shebang, the internal buffer of the BufRead must be >= 3 bytes. -pub fn skip_prefix(r: &mut R) -> Result<(), io::Error> { - if { - let buf = r.fill_buf()?; - buf.len() >= 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf - } { +pub fn skip_prefix(r: &mut R) -> Result<(), Error> { + let buf = r.fill_buf()?; + if buf.len() >= 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf { r.consume(3); } let buf = r.fill_buf()?; - let has_shebang = buf.len() >= 1 && buf[0] == b'#'; + let has_shebang = !buf.is_empty() && buf[0] == b'#'; if has_shebang { r.consume(1); loop { @@ -46,7 +44,7 @@ pub fn skip_prefix(r: &mut R) -> Result<(), io::Error> { /// Reads a Lua script from a `R: Read` and wraps it in a BufReader /// /// Also calls `skip_prefix` to skip any leading UTF-8 BOM or unix shebang. -pub fn buffered_read(r: R) -> Result, io::Error> { +pub fn buffered_read(r: R) -> Result, Error> { let mut r = BufReader::new(r); skip_prefix(&mut r)?; Ok(r) diff --git a/src/lib.rs b/src/lib.rs index 0df7831e..c2946ff1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +extern crate alloc; + pub mod any; pub mod async_callback; pub mod callback; @@ -24,26 +26,26 @@ pub mod types; pub mod userdata; pub mod value; -pub use self::{ - async_callback::{async_sequence, SequenceReturn}, - callback::{BoxSequence, Callback, CallbackFn, CallbackReturn, Sequence, SequencePoll}, - closure::{Closure, CompilerError, FunctionPrototype}, - constant::Constant, - conversion::{FromMultiValue, FromValue, IntoMultiValue, IntoValue, Variadic}, - error::{Error, ExternError, RuntimeError, TypeError}, - fuel::Fuel, - function::Function, - lua::{Context, Lua}, - meta_ops::MetaMethod, - registry::{Registry, Singleton}, - stack::Stack, - stash::{ - StashedCallback, StashedClosure, StashedError, StashedExecutor, StashedFunction, - StashedString, StashedTable, StashedThread, StashedUserData, StashedValue, - }, - string::String, - table::Table, - thread::{Execution, Executor, ExecutorMode, Thread, ThreadMode}, - userdata::UserData, - value::Value, +pub use self::async_callback::{async_sequence, SequenceReturn}; +pub use self::callback::{ + BoxSequence, Callback, CallbackFn, CallbackReturn, Sequence, SequencePoll, +}; +pub use self::closure::{Closure, CompilerError, FunctionPrototype}; +pub use self::constant::Constant; +pub use self::conversion::{FromMultiValue, FromValue, IntoMultiValue, IntoValue, Variadic}; +pub use self::error::{Error, ExternError, RuntimeError, TypeError}; +pub use self::fuel::Fuel; +pub use self::function::Function; +pub use self::lua::{Context, Lua}; +pub use self::meta_ops::MetaMethod; +pub use self::registry::{Registry, Singleton}; +pub use self::stack::Stack; +pub use self::stash::{ + StashedCallback, StashedClosure, StashedError, StashedExecutor, StashedFunction, StashedString, + StashedTable, StashedThread, StashedUserData, StashedValue, }; +pub use self::string::String; +pub use self::table::Table; +pub use self::thread::{Execution, Executor, ExecutorMode, Thread, ThreadMode}; +pub use self::userdata::UserData; +pub use self::value::Value; diff --git a/src/lua.rs b/src/lua.rs index 67f03007..f37ac5bd 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -1,20 +1,16 @@ -use std::ops; - -use gc_arena::{ - arena::{CollectionPhase, Root}, - metrics::Metrics, - Arena, Collect, Mutation, Rootable, -}; - +use crate::finalizers::Finalizers; +use crate::stash::{Fetchable, Stashable}; +use crate::stdlib::{load_base, load_coroutine, load_io, load_math, load_string, load_table}; +use crate::string::InternedStringSet; +use crate::thread::BadThreadMode; use crate::{ - finalizers::Finalizers, - stash::{Fetchable, Stashable}, - stdlib::{load_base, load_coroutine, load_io, load_math, load_string, load_table}, - string::InternedStringSet, - thread::BadThreadMode, Error, ExternError, FromMultiValue, FromValue, Fuel, IntoValue, Registry, RuntimeError, Singleton, StashedExecutor, String, Table, TypeError, Value, }; +use core::ops; +use gc_arena::arena::{CollectionPhase, Root}; +use gc_arena::metrics::Metrics; +use gc_arena::{Arena, Collect, Mutation, Rootable}; /// A value representing the main "execution context" of a Lua state. /// diff --git a/src/meta_ops.rs b/src/meta_ops.rs index 6fd0517a..b2bb2201 100644 --- a/src/meta_ops.rs +++ b/src/meta_ops.rs @@ -1,13 +1,11 @@ -use std::io::Write; - -use gc_arena::Collect; -use thiserror::Error; - use crate::async_callback::{AsyncSequence, Locals}; -use crate::{async_sequence, SequenceReturn, Stack}; +use crate::table::InvalidTableKey; use crate::{ - table::InvalidTableKey, Callback, CallbackReturn, Context, Function, IntoValue, Table, Value, + async_sequence, Callback, CallbackReturn, Context, Function, IntoValue, SequenceReturn, Stack, + Table, Value, }; +use gc_arena::Collect; +use thiserror::Error; /// An enum of every possible Lua metamethod. /// @@ -762,12 +760,7 @@ pub fn concat<'gc>( if a.is_implicit_string() && b.is_implicit_string() { let mut bytes = Vec::new(); for value in [a, b] { - match value { - Value::Integer(i) => write!(&mut bytes, "{}", i).unwrap(), - Value::Number(n) => write!(&mut bytes, "{}", n).unwrap(), - Value::String(s) => bytes.extend(s.as_bytes()), - _ => return None, - } + value_to_string(&mut bytes, &value)? } Some(Value::String(ctx.intern(&bytes))) } else { @@ -803,21 +796,16 @@ pub fn concat_many<'gc>( ) -> Result, MetaOperatorError> { // Fast path scope; never loops, returns if successful, otherwise // breaks to fall back to the slow impl. - loop { + 'fast: { // Since we have to make two passes to check for complex types, // estimate the length in the first pass. let Some(len) = estimate_concatenated_len(values)? else { - break; + break 'fast; }; let mut bytes = Vec::with_capacity(len); for value in values { - match value { - Value::Integer(i) => write!(&mut bytes, "{}", i).unwrap(), - Value::Number(n) => write!(&mut bytes, "{}", n).unwrap(), - Value::String(s) => bytes.extend(s.as_bytes()), - _ => unreachable!(), - } + value_to_string(&mut bytes, value).unwrap(); } return Ok(ConcatMetaResult::Value(Value::String(ctx.intern(&bytes)))); } @@ -826,7 +814,7 @@ pub fn concat_many<'gc>( let func = Callback::from_fn(&ctx, |ctx, _, stack| { let args = stack.len(); let s = async_sequence(&ctx, |_, mut seq| async move { - for i in (1..args).into_iter().rev() { + for i in (1..args).rev() { let call = seq.try_enter(|ctx, locals, _, mut stack| { let bottom = i - 1; let call = concat(ctx, stack[i - 1], stack[i])?; @@ -853,16 +841,16 @@ pub fn concat_separated<'gc>( // Fast path scope; never loops, returns if successful, otherwise // breaks to fall back to the slow impl. - loop { + 'fast: { let sep_str = match separator.into_string(ctx) { Some(s) => s, - None => break, + None => break 'fast, }; // Since we have to make two passes to check for complex types, // estimate the length in the first pass. let Some(len) = estimate_concatenated_len(values)? else { - break; + break 'fast; }; let sep_count = values.len().saturating_sub(1); @@ -876,21 +864,11 @@ pub fn concat_separated<'gc>( let mut iter = values.iter(); if let Some(val) = iter.next() { - match val { - Value::Integer(i) => write!(&mut bytes, "{}", i).unwrap(), - Value::Number(n) => write!(&mut bytes, "{}", n).unwrap(), - Value::String(s) => bytes.extend(s.as_bytes()), - _ => unreachable!(), - } + value_to_string(&mut bytes, val).unwrap(); - while let Some(val) = iter.next() { + for val in iter.by_ref() { bytes.extend(&*sep_str); - match val { - Value::Integer(i) => write!(&mut bytes, "{}", i).unwrap(), - Value::Number(n) => write!(&mut bytes, "{}", n).unwrap(), - Value::String(s) => bytes.extend(s.as_bytes()), - _ => unreachable!(), - } + value_to_string(&mut bytes, val).unwrap(); } } drop(iter); @@ -904,7 +882,7 @@ pub fn concat_separated<'gc>( let b = async_sequence(&ctx, |locals, mut seq| { let sep = locals.stash(&ctx, sep); async move { - for i in (1..args).into_iter().rev() { + for i in (1..args).rev() { let call = seq.try_enter(|ctx, locals, _, mut stack| { let bottom = i; let call = concat(ctx, locals.fetch(&sep), stack[i])?; @@ -929,6 +907,16 @@ pub fn concat_separated<'gc>( Ok(ConcatMetaResult::Call(func.into())) } +fn value_to_string(bytes: &mut Vec, value: &Value<'_>) -> Option<()> { + match value { + Value::Integer(i) => bytes.extend(i.to_string().as_bytes()), + Value::Number(n) => bytes.extend(n.to_string().as_bytes()), + Value::String(s) => bytes.extend(s.as_bytes()), + _ => return None, + } + Some(()) +} + #[must_use] struct PreparedCall { func: Option, diff --git a/src/opcode.rs b/src/opcode.rs index fb014d43..dedf87e2 100644 --- a/src/opcode.rs +++ b/src/opcode.rs @@ -1,8 +1,7 @@ -use gc_arena::Collect; - use crate::types::{ ConstantIndex16, ConstantIndex8, Opt254, PrototypeIndex, RegisterIndex, UpValueIndex, VarCount, }; +use gc_arena::Collect; #[derive(Debug, Copy, Clone, Collect)] #[collect(require_static)] diff --git a/src/registry.rs b/src/registry.rs index 981d8f03..b20c4cfe 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -1,18 +1,15 @@ -use std::{any::TypeId, hash::BuildHasherDefault}; - +use crate::any::Any; +use crate::stash::{Fetchable, Stashable}; +use crate::Context; use ahash::AHasher; -use gc_arena::{ - allocator_api::MetricsAlloc, arena::Root, lock::RefLock, Collect, DynamicRootSet, Gc, Mutation, - Rootable, -}; +use core::any::TypeId; +use core::hash::BuildHasherDefault; +use gc_arena::allocator_api::MetricsAlloc; +use gc_arena::arena::Root; +use gc_arena::lock::RefLock; +use gc_arena::{Collect, DynamicRootSet, Gc, Mutation, Rootable}; use hashbrown::{hash_map, HashMap}; -use crate::{ - any::Any, - stash::{Fetchable, Stashable}, - Context, -}; - /// A type which can have a single registered value per [`Lua`](crate::Lua) instance. /// /// By implementing this trait, you can store things like metatables globally per `Lua` instance, diff --git a/src/stack.rs b/src/stack.rs index 4b24858c..06e0da67 100644 --- a/src/stack.rs +++ b/src/stack.rs @@ -1,14 +1,10 @@ -use std::{ - iter, - ops::{Bound, Index, IndexMut, RangeBounds}, - slice::{self, SliceIndex}, -}; - +use crate::{Context, FromMultiValue, FromValue, IntoMultiValue, IntoValue, TypeError, Value}; use allocator_api2::vec; +use core::iter; +use core::ops::{Bound, Index, IndexMut, RangeBounds}; +use core::slice::{self, SliceIndex}; use gc_arena::allocator_api::MetricsAlloc; -use crate::{Context, FromMultiValue, FromValue, IntoMultiValue, IntoValue, TypeError, Value}; - /// The mechanism through which all callbacks receive parameters and return values. /// /// Each [`Thread`](crate::Thread) has its own internal stack of [`Value`]s, and this stack is diff --git a/src/stash.rs b/src/stash.rs index 784a2433..02681f8e 100644 --- a/src/stash.rs +++ b/src/stash.rs @@ -1,17 +1,15 @@ -use std::fmt; - -use gc_arena::{DynamicRoot, DynamicRootSet, Mutation, Rootable}; - +use crate::callback::CallbackInner; +use crate::closure::ClosureInner; +use crate::string::StringInner; +use crate::table::TableInner; +use crate::thread::{ExecutorInner, ThreadInner}; +use crate::userdata::UserDataInner; use crate::{ - callback::CallbackInner, - closure::ClosureInner, - string::StringInner, - table::TableInner, - thread::{ExecutorInner, ThreadInner}, - userdata::UserDataInner, Callback, Closure, Error, Executor, Function, RuntimeError, String, Table, Thread, UserData, Value, }; +use core::fmt; +use gc_arena::{DynamicRoot, DynamicRootSet, Mutation, Rootable}; /// A trait for types that can be stashed into a [`DynamicRootSet`]. /// diff --git a/src/stdlib/base.rs b/src/stdlib/base.rs index 5a18ca80..4556c7d3 100644 --- a/src/stdlib/base.rs +++ b/src/stdlib/base.rs @@ -1,13 +1,11 @@ -use std::pin::Pin; - -use gc_arena::Collect; - +use crate::meta_ops::{self, MetaResult}; +use crate::table::NextValue; use crate::{ - meta_ops::{self, MetaResult}, - table::NextValue, BoxSequence, Callback, CallbackReturn, Context, Error, Execution, IntoValue, MetaMethod, Sequence, SequencePoll, Stack, String, Table, TypeError, Value, Variadic, }; +use core::pin::Pin; +use gc_arena::Collect; pub fn load_base<'gc>(ctx: Context<'gc>) { ctx.set_global( diff --git a/src/stdlib/coroutine.rs b/src/stdlib/coroutine.rs index c315fa4f..9f6f2c9c 100644 --- a/src/stdlib/coroutine.rs +++ b/src/stdlib/coroutine.rs @@ -1,6 +1,5 @@ -use crate::{meta_ops, BoxSequence, Callback, CallbackReturn, Context, Table, Thread, ThreadMode}; - use super::base::PCall; +use crate::{meta_ops, BoxSequence, Callback, CallbackReturn, Context, Table, Thread, ThreadMode}; pub fn load_coroutine<'gc>(ctx: Context<'gc>) { let coroutine = Table::new(&ctx); diff --git a/src/stdlib/io.rs b/src/stdlib/io.rs index 39254fcd..8b9914d3 100644 --- a/src/stdlib/io.rs +++ b/src/stdlib/io.rs @@ -1,15 +1,11 @@ -use std::{ - io::{self, Write}, - pin::Pin, -}; - -use gc_arena::Collect; - +use crate::meta_ops::{self, MetaResult}; use crate::{ - meta_ops::{self, MetaResult}, BoxSequence, Callback, CallbackReturn, Context, Error, Execution, Sequence, SequencePoll, Stack, Value, }; +use core::pin::Pin; +use gc_arena::Collect; +use std::io::{stdout, Write}; pub fn load_io<'gc>(ctx: Context<'gc>) { ctx.set_global( @@ -28,7 +24,7 @@ pub fn load_io<'gc>(ctx: Context<'gc>) { _exec: Execution<'gc, '_>, mut stack: Stack<'gc, '_>, ) -> Result, Error<'gc>> { - let mut stdout = io::stdout(); + let mut stdout = stdout(); while let Some(value) = stack.pop_back() { match meta_ops::tostring(ctx, value)? { diff --git a/src/stdlib/math.rs b/src/stdlib/math.rs index 99ae3e65..d0cdd953 100644 --- a/src/stdlib/math.rs +++ b/src/stdlib/math.rs @@ -1,9 +1,8 @@ -use gc_arena::Mutation; - use crate::{ async_sequence, meta_ops, Callback, CallbackReturn, Context, FromMultiValue, IntoMultiValue, IntoValue, SequenceReturn, Table, Value, }; +use gc_arena::Mutation; fn callback<'gc, F, A, R>(name: &'static str, mc: &Mutation<'gc>, f: F) -> Callback<'gc> where @@ -289,9 +288,10 @@ pub fn load_trig<'gc>(ctx: Context<'gc>, math: Table<'gc>) { } pub fn load_random<'gc>(ctx: Context<'gc>, math: Table<'gc>) { - use std::{cell::RefCell, rc::Rc}; - - use rand::{rngs::SmallRng, Rng, SeedableRng}; + use alloc::rc::Rc; + use core::cell::RefCell; + use rand::rngs::SmallRng; + use rand::{Rng, SeedableRng}; let seeded_rng = Rc::new(RefCell::new(SmallRng::from_entropy())); diff --git a/src/stdlib/mod.rs b/src/stdlib/mod.rs index aa766153..88c671a5 100644 --- a/src/stdlib/mod.rs +++ b/src/stdlib/mod.rs @@ -5,7 +5,9 @@ mod math; mod string; mod table; -pub use self::{ - base::load_base, coroutine::load_coroutine, io::load_io, math::load_math, string::load_string, - table::load_table, -}; +pub use self::base::load_base; +pub use self::coroutine::load_coroutine; +pub use self::io::load_io; +pub use self::math::load_math; +pub use self::string::load_string; +pub use self::table::load_table; diff --git a/src/stdlib/string.rs b/src/stdlib/string.rs index 556537c8..0a58f135 100644 --- a/src/stdlib/string.rs +++ b/src/stdlib/string.rs @@ -100,7 +100,7 @@ pub fn load_string<'gc>(ctx: Context<'gc>) { ctx.set_global("string", string); } -fn sub(string: &[u8], i: i64, j: Option) -> Result<&[u8], std::num::TryFromIntError> { +fn sub(string: &[u8], i: i64, j: Option) -> Result<&[u8], core::num::TryFromIntError> { let i = match i { i if i > 0 => i.saturating_sub(1).try_into()?, 0 => 0, diff --git a/src/stdlib/table.rs b/src/stdlib/table.rs index d06dbe1d..e0d36dc4 100644 --- a/src/stdlib/table.rs +++ b/src/stdlib/table.rs @@ -1,19 +1,16 @@ -use std::mem; -use std::pin::Pin; - -use anyhow::Context as _; -use gc_arena::Collect; - +use crate::async_callback::{AsyncSequence, Locals}; +use crate::fuel::count_fuel; +use crate::meta_ops::{self, concat_separated, ConcatMetaResult, MetaResult}; +use crate::table::RawTable; use crate::{ - async_callback::{AsyncSequence, Locals}, - async_sequence, - fuel::count_fuel, - meta_ops::{self, concat_separated, ConcatMetaResult, MetaResult}, - table::RawTable, - BoxSequence, Callback, CallbackReturn, Closure, Context, Error, Execution, Function, IntoValue, - MetaMethod, Sequence, SequencePoll, SequenceReturn, Stack, StashedError, StashedFunction, - StashedTable, StashedValue, Table, Value, + async_sequence, BoxSequence, Callback, CallbackReturn, Closure, Context, Error, Execution, + Function, IntoValue, MetaMethod, Sequence, SequencePoll, SequenceReturn, Stack, StashedError, + StashedFunction, StashedTable, StashedValue, Table, Value, }; +use anyhow::Context as _; +use core::mem; +use core::pin::Pin; +use gc_arena::Collect; pub fn load_table<'gc>(ctx: Context<'gc>) { let table = Table::new(&ctx); diff --git a/src/string.rs b/src/string.rs index a3f43107..d3d917df 100644 --- a/src/string.rs +++ b/src/string.rs @@ -1,18 +1,15 @@ -use std::{ - alloc, fmt, - hash::{BuildHasherDefault, Hash, Hasher}, - ops, slice, - str::{self, Utf8Error}, -}; - -use ahash::AHasher; -use gc_arena::{ - allocator_api::MetricsAlloc, barrier::Unlock, lock::RefLock, metrics::Metrics, Collect, - Collection, Gc, GcWeak, Mutation, Static, -}; -use hashbrown::{hash_map, raw::RawTable, HashMap}; - use crate::compiler::string_utils::{debug_utf8_lossy, display_utf8_lossy}; +use ahash::AHasher; +use core::hash::{BuildHasherDefault, Hash, Hasher}; +use core::str::{self, Utf8Error}; +use core::{alloc, fmt, ops, slice}; +use gc_arena::allocator_api::MetricsAlloc; +use gc_arena::barrier::Unlock; +use gc_arena::lock::RefLock; +use gc_arena::metrics::Metrics; +use gc_arena::{Collect, Collection, Gc, GcWeak, Mutation, Static}; +use hashbrown::raw::RawTable; +use hashbrown::{hash_map, HashMap}; /// The Lua string type. /// @@ -365,9 +362,8 @@ impl<'gc> InternedStringSet<'gc> { #[cfg(test)] mod tests { - use gc_arena::arena::rootless_mutate; - use super::*; + use gc_arena::arena::rootless_mutate; #[test] fn test_string_header() { diff --git a/src/table/mod.rs b/src/table/mod.rs index 0d970ddf..6952f813 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -1,7 +1,5 @@ mod raw; mod table; -pub use self::{ - raw::{InvalidTableKey, NextValue, RawTable}, - table::{Table, TableInner, TableState}, -}; +pub use self::raw::{InvalidTableKey, NextValue, RawTable}; +pub use self::table::{Table, TableInner, TableState}; diff --git a/src/table/raw.rs b/src/table/raw.rs index b5a458c8..6d891188 100644 --- a/src/table/raw.rs +++ b/src/table/raw.rs @@ -1,12 +1,12 @@ -use std::{fmt, hash::Hash, i64, mem}; - +use crate::{Callback, Closure, Function, String, Table, Thread, UserData, Value}; use allocator_api2::vec; -use gc_arena::{allocator_api::MetricsAlloc, Collect, Gc, Mutation}; +use core::hash::Hash; +use core::{fmt, i64, mem}; +use gc_arena::allocator_api::MetricsAlloc; +use gc_arena::{Collect, Gc, Mutation}; use hashbrown::{hash_map, HashMap}; use thiserror::Error; -use crate::{Callback, Closure, Function, String, Table, Thread, UserData, Value}; - #[derive(Debug, Copy, Clone, Error)] pub enum InvalidTableKey { #[error("table key is NaN")] diff --git a/src/table/table.rs b/src/table/table.rs index b15ba2d2..7129b91a 100644 --- a/src/table/table.rs +++ b/src/table/table.rs @@ -1,14 +1,9 @@ -use std::{ - fmt, - hash::{Hash, Hasher}, - i64, mem, -}; - -use gc_arena::{lock::RefLock, Collect, Gc, Mutation}; - -use crate::{Context, FromValue, IntoValue, TypeError, Value}; - use super::raw::{InvalidTableKey, NextValue, RawTable}; +use crate::{Context, FromValue, IntoValue, TypeError, Value}; +use core::hash::{Hash, Hasher}; +use core::{fmt, i64, mem}; +use gc_arena::lock::RefLock; +use gc_arena::{Collect, Gc, Mutation}; pub type TableInner<'gc> = RefLock>; diff --git a/src/thread/executor.rs b/src/thread/executor.rs index 4f4630bd..e0f187c6 100644 --- a/src/thread/executor.rs +++ b/src/thread/executor.rs @@ -1,20 +1,17 @@ -use std::hash::{Hash, Hasher}; - -use allocator_api2::vec; -use gc_arena::{allocator_api::MetricsAlloc, lock::RefLock, Collect, Gc, Mutation}; -use thiserror::Error; - +use super::thread::{Frame, LuaFrame, ThreadState}; +use super::vm::run_vm; +use crate::compiler::{FunctionRef, LineNumber}; +use crate::thread::BadThreadMode; use crate::{ - compiler::{FunctionRef, LineNumber}, - thread::BadThreadMode, CallbackReturn, Context, Error, FromMultiValue, Fuel, Function, IntoMultiValue, SequencePoll, Stack, String, Thread, ThreadMode, Variadic, }; - -use super::{ - thread::{Frame, LuaFrame, ThreadState}, - vm::run_vm, -}; +use allocator_api2::vec; +use core::hash::{Hash, Hasher}; +use gc_arena::allocator_api::MetricsAlloc; +use gc_arena::lock::RefLock; +use gc_arena::{Collect, Gc, Mutation}; +use thiserror::Error; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExecutorMode { diff --git a/src/thread/mod.rs b/src/thread/mod.rs index 8e6a0591..0649bca9 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -2,17 +2,12 @@ mod executor; mod thread; mod vm; -use thiserror::Error; - -use crate::meta_ops::{MetaCallError, MetaOperatorError}; - -pub use self::{ - executor::{ - BadExecutorMode, CurrentThread, Execution, Executor, ExecutorInner, ExecutorMode, - UpperLuaFrame, - }, - thread::{BadThreadMode, OpenUpValue, Thread, ThreadInner, ThreadMode}, +pub use self::executor::{ + BadExecutorMode, CurrentThread, Execution, Executor, ExecutorInner, ExecutorMode, UpperLuaFrame, }; +pub use self::thread::{BadThreadMode, OpenUpValue, Thread, ThreadInner, ThreadMode}; +use crate::meta_ops::{MetaCallError, MetaOperatorError}; +use thiserror::Error; #[derive(Debug, Clone, Error)] pub enum VMError { diff --git a/src/thread/thread.rs b/src/thread/thread.rs index a03d4c2a..a28d0308 100644 --- a/src/thread/thread.rs +++ b/src/thread/thread.rs @@ -1,25 +1,19 @@ -use std::{ - cell::RefMut, - hash::{Hash, Hasher}, +use super::VMError; +use crate::closure::{UpValue, UpValueState}; +use crate::fuel::count_fuel; +use crate::types::{RegisterIndex, VarCount}; +use crate::{ + meta_ops, BoxSequence, Callback, Closure, Context, Error, FromMultiValue, Fuel, Function, + IntoMultiValue, String, Table, UserData, Value, }; - use allocator_api2::vec; -use gc_arena::{ - allocator_api::MetricsAlloc, lock::RefLock, Collect, Finalization, Gc, GcWeak, Mutation, -}; +use core::cell::RefMut; +use core::hash::{Hash, Hasher}; +use gc_arena::allocator_api::MetricsAlloc; +use gc_arena::lock::RefLock; +use gc_arena::{Collect, Finalization, Gc, GcWeak, Mutation}; use thiserror::Error; -use crate::{ - closure::{UpValue, UpValueState}, - fuel::count_fuel, - meta_ops, - types::{RegisterIndex, VarCount}, - BoxSequence, Callback, Closure, Context, Error, FromMultiValue, Fuel, Function, IntoMultiValue, - String, Table, UserData, Value, -}; - -use super::VMError; - /// The current state of a [`Thread`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ThreadMode { diff --git a/src/thread/vm.rs b/src/thread/vm.rs index 51e42b6f..bcd12c3b 100644 --- a/src/thread/vm.rs +++ b/src/thread/vm.rs @@ -1,17 +1,14 @@ +use super::thread::LuaFrame; +use super::VMError; +use crate::meta_ops::{self, ConcatMetaResult, MetaResult}; +use crate::opcode::{Operation, RCIndex}; +use crate::table::RawTable; +use crate::thread::thread::MetaReturn; +use crate::types::{RegisterIndex, UpValueDescriptor, VarCount}; +use crate::{Closure, Constant, Context, Function, String, Table, Value}; use allocator_api2::vec; use gc_arena::allocator_api::MetricsAlloc; -use crate::{ - meta_ops::{self, ConcatMetaResult, MetaResult}, - opcode::{Operation, RCIndex}, - table::RawTable, - thread::thread::MetaReturn, - types::{RegisterIndex, UpValueDescriptor, VarCount}, - Closure, Constant, Context, Function, String, Table, Value, -}; - -use super::{thread::LuaFrame, VMError}; - // Runs the VM for the given number of instructions or until the current LuaFrame may have been // changed. // diff --git a/src/types.rs b/src/types.rs index c5eb49d1..d88a3130 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,5 +1,4 @@ -use std::fmt::{self, Debug}; - +use core::fmt::{self, Debug}; use gc_arena::Collect; /// An index that points to a register in the stack relative to the current frame. diff --git a/src/userdata.rs b/src/userdata.rs index d8b860e0..0754311a 100644 --- a/src/userdata.rs +++ b/src/userdata.rs @@ -1,16 +1,11 @@ -use std::{ - hash::{Hash, Hasher}, - mem, -}; - -use gc_arena::{arena::Root, barrier, lock, Collect, Gc, Mutation, Rootable, Static}; +use crate::any::{Any, AnyInner}; +use crate::Table; +use core::hash::{Hash, Hasher}; +use core::mem; +use gc_arena::arena::Root; +use gc_arena::{barrier, lock, Collect, Gc, Mutation, Rootable, Static}; use thiserror::Error; -use crate::{ - any::{Any, AnyInner}, - Table, -}; - #[derive(Debug, Copy, Clone, Error)] #[error("UserData type mismatch")] pub struct BadUserDataType; @@ -38,7 +33,7 @@ pub type UserDataInner<'gc> = AnyInner>; /// /// There is no automatic mechanism to provide internal mutability on the held value. If the held /// value needs to be internally mutable and is `'static`, consider normal mechanisms for Rust -/// internal mutability like [`std::cell::RefCell`]. If the type is a GC type and needs to be +/// internal mutability like [`core::cell::RefCell`]. If the type is a GC type and needs to be /// internally mutable, use the mechanisms in `gc-arena` for this like [`gc_arena::lock::RefLock`] /// instead. /// diff --git a/src/value.rs b/src/value.rs index 8409bd42..c2aaf281 100644 --- a/src/value.rs +++ b/src/value.rs @@ -1,8 +1,6 @@ -use std::{f64, fmt, i64}; - -use gc_arena::{Collect, Gc}; - use crate::{Callback, Closure, Constant, Function, String, Table, Thread, UserData}; +use core::{f64, fmt, i64}; +use gc_arena::{Collect, Gc}; /// The single data type for all Lua variables. /// @@ -56,7 +54,7 @@ impl<'gc> Value<'gc> { struct ValueDisplay<'gc>(Value<'gc>); impl<'gc> fmt::Display for ValueDisplay<'gc> { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> core::fmt::Result { match self.0 { Value::Nil => write!(fmt, "nil"), Value::Boolean(b) => write!(fmt, "{}", b), @@ -85,7 +83,7 @@ impl<'gc> Value<'gc> { struct ShallowDebug<'gc>(Value<'gc>); impl<'gc> fmt::Debug for ShallowDebug<'gc> { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> core::fmt::Result { match self.0 { Value::Table(t) => { write!(fmt, "Value::Table({:p})", Gc::as_ptr(t.into_inner())) @@ -261,10 +259,9 @@ impl<'gc> From> for Value<'gc> { #[cfg(test)] mod tests { - use gc_arena::Rootable; - use crate::table::Table; use crate::{Lua, UserData}; + use gc_arena::Rootable; #[test] fn recursive_table_debug() { diff --git a/tests/callback.rs b/tests/callback.rs index 6670fd5f..3798d335 100644 --- a/tests/callback.rs +++ b/tests/callback.rs @@ -1,5 +1,4 @@ -use std::pin::Pin; - +use core::pin::Pin; use gc_arena::Collect; use piccolo::{ BoxSequence, Callback, CallbackReturn, Closure, Context, Error, Execution, Executor, diff --git a/tests/error.rs b/tests/error.rs index 46360df7..73b60da3 100644 --- a/tests/error.rs +++ b/tests/error.rs @@ -1,4 +1,5 @@ -use piccolo::{error::LuaError, Callback, Closure, Error, Executor, ExternError, Lua, Value}; +use piccolo::error::LuaError; +use piccolo::{Callback, Closure, Error, Executor, ExternError, Lua, Value}; use thiserror::Error; #[test] diff --git a/tests/goldenscripts.rs b/tests/goldenscripts.rs index 57029c45..9d54ec58 100644 --- a/tests/goldenscripts.rs +++ b/tests/goldenscripts.rs @@ -11,23 +11,23 @@ //! where `mode` dictates how to handle errors //! and `script` is a valid Lua script. -use piccolo::{Closure, Executor, Lua}; -use std::{fs::read_dir, io::BufRead, path::PathBuf, sync::mpsc::channel}; - use crate::collected_print::print_callback; +use piccolo::{Closure, Executor, Lua}; +use std::fs::read_dir; +use std::io::BufRead; +use std::path::PathBuf; +use std::sync::mpsc::channel; mod collected_print { use gc_arena::Collect; + use piccolo::meta_ops::{self, MetaResult}; use piccolo::{ - meta_ops::{self, MetaResult}, BoxSequence, Callback, CallbackReturn, Context, Execution, Sequence, SequencePoll, Stack, Value, }; - use std::{ - io::{Cursor, Write}, - pin::Pin, - sync::mpsc::Sender, - }; + use std::io::{Cursor, Write}; + use std::pin::Pin; + use std::sync::mpsc::Sender; pub fn print_callback<'gc>(ctx: piccolo::Context<'gc>, tx: Sender>) -> Callback<'gc> { Callback::from_fn( diff --git a/tests/scripts.rs b/tests/scripts.rs index 3f43a066..a7305362 100644 --- a/tests/scripts.rs +++ b/tests/scripts.rs @@ -1,9 +1,6 @@ -use std::{ - fs::{read_dir, File}, - io::{stdout, Read, Write}, -}; - use piccolo::{io, Closure, Executor, ExternError, Lua}; +use std::fs::{read_dir, File}; +use std::io::{stdout, Read, Write}; fn run_lua_code(name: &str, code: &[u8]) -> Result<(), ExternError> { let mut lua = Lua::full(); diff --git a/tests/sizes.rs b/tests/sizes.rs index 11098a3a..fd854533 100644 --- a/tests/sizes.rs +++ b/tests/sizes.rs @@ -1,6 +1,6 @@ -use std::mem; - -use piccolo::{opcode::OpCode, Callback, Closure, String, Table, Thread, UserData, Value}; +use core::mem; +use piccolo::opcode::OpCode; +use piccolo::{Callback, Closure, String, Table, Thread, UserData, Value}; #[test] fn test_sizes() { diff --git a/tests/table.rs b/tests/table.rs index a55558b4..681a737f 100644 --- a/tests/table.rs +++ b/tests/table.rs @@ -1,5 +1,4 @@ -use std::cmp::Ordering; - +use core::cmp::Ordering; use piccolo::{Lua, Table, Value}; #[test] diff --git a/tests/tail_call_stack_panic.rs b/tests/tail_call_stack_panic.rs index d64356f3..dfd985e9 100644 --- a/tests/tail_call_stack_panic.rs +++ b/tests/tail_call_stack_panic.rs @@ -1,7 +1,7 @@ +use piccolo::meta_ops::MetaCallError; +use piccolo::{Closure, Executor, Lua}; use std::string::String as StdString; -use piccolo::{meta_ops::MetaCallError, Closure, Executor, Lua}; - const SOURCE: &str = r#" -- Purposeful typo of 'tostring' return tosting("hello") diff --git a/tests/userdata.rs b/tests/userdata.rs index ecf211c8..33048dfa 100644 --- a/tests/userdata.rs +++ b/tests/userdata.rs @@ -1,4 +1,5 @@ -use gc_arena::{lock::Lock, Collect, Gc, Rootable}; +use gc_arena::lock::Lock; +use gc_arena::{Collect, Gc, Rootable}; use piccolo::{Callback, CallbackReturn, Closure, Executor, Lua, UserData, Value}; #[derive(Collect)] diff --git a/util/src/freeze.rs b/util/src/freeze.rs index 58e57d3d..a2156a8a 100644 --- a/util/src/freeze.rs +++ b/util/src/freeze.rs @@ -1,5 +1,7 @@ -use std::{cell::RefCell, marker::PhantomData, mem, rc::Rc}; - +use alloc::rc::Rc; +use core::cell::RefCell; +use core::marker::PhantomData; +use core::mem; use thiserror::Error; #[derive(Debug, Copy, Clone, Eq, PartialEq, Error)] diff --git a/util/src/lib.rs b/util/src/lib.rs index e20d32da..f9c08e80 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -1,3 +1,5 @@ +extern crate alloc; + pub mod freeze; pub mod user_methods; diff --git a/util/src/serde/de.rs b/util/src/serde/de.rs index 56e389f2..21785304 100644 --- a/util/src/serde/de.rs +++ b/util/src/serde/de.rs @@ -1,11 +1,10 @@ -use std::fmt; - -use piccolo::{table::NextValue, Table, Value}; +use super::markers::{is_none, is_unit}; +use core::fmt; +use piccolo::table::NextValue; +use piccolo::{Table, Value}; use serde::de; use thiserror::Error; -use super::markers::{is_none, is_unit}; - #[derive(Debug, Error)] pub enum Error { #[error("{0}")] diff --git a/util/src/serde/mod.rs b/util/src/serde/mod.rs index 7b0185e4..c62c0f58 100644 --- a/util/src/serde/mod.rs +++ b/util/src/serde/mod.rs @@ -2,13 +2,10 @@ pub mod de; pub mod markers; pub mod ser; +pub use self::de::from_value; +pub use self::ser::{to_value, to_value_with, Options as SerOptions}; use piccolo::Lua; -pub use self::{ - de::from_value, - ser::{to_value, to_value_with, Options as SerOptions}, -}; - pub trait LuaSerdeExt { fn load_serde(&mut self); } diff --git a/util/src/serde/ser.rs b/util/src/serde/ser.rs index 371348d4..eb6913d7 100644 --- a/util/src/serde/ser.rs +++ b/util/src/serde/ser.rs @@ -1,11 +1,9 @@ -use std::fmt; - +use super::markers::{none, unit}; +use core::fmt; use piccolo::{Context, Table, Value}; use serde::ser; use thiserror::Error; -use super::markers::{none, unit}; - #[derive(Debug, Error)] #[error("{0}")] pub struct Error(String); diff --git a/util/src/user_methods.rs b/util/src/user_methods.rs index 403e0469..12aa09d6 100644 --- a/util/src/user_methods.rs +++ b/util/src/user_methods.rs @@ -1,6 +1,6 @@ -use std::marker::PhantomData; - -use gc_arena::{arena::Root, barrier, Collect, Rootable, Static}; +use core::marker::PhantomData; +use gc_arena::arena::Root; +use gc_arena::{barrier, Collect, Rootable, Static}; use piccolo::{ Callback, CallbackReturn, Context, Error, Execution, FromMultiValue, IntoMultiValue, MetaMethod, Table, UserData,