diff --git a/benches/run_criterion.rs b/benches/run_criterion.rs index 4622e039..09efbc10 100644 --- a/benches/run_criterion.rs +++ b/benches/run_criterion.rs @@ -1,5 +1,5 @@ #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] -use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] #[cfg(not(target_os = "windows"))] diff --git a/build/instructions_template.rs b/build/instructions_template.rs index 2dad5291..f1015215 100644 --- a/build/instructions_template.rs +++ b/build/instructions_template.rs @@ -4,7 +4,7 @@ // use proc_macro2::TokenStream; -use quote::{format_ident, quote, ToTokens, TokenStreamExt}; +use quote::{ToTokens, TokenStreamExt, format_ident, quote}; use strum_macros::{EnumDiscriminants, EnumProperty, EnumString}; use syn::*; use to_syn_value_derive::ToDeriveInput; diff --git a/build/main.rs b/build/main.rs index fd2f8c46..e762929c 100644 --- a/build/main.rs +++ b/build/main.rs @@ -8,9 +8,9 @@ use std::collections::BTreeMap; use std::env; use std::fs::File; use std::io::Write; +use std::path::MAIN_SEPARATOR_STR; use std::path::Path; use std::path::PathBuf; -use std::path::MAIN_SEPARATOR_STR; use std::process::{Command, Stdio}; fn find_prolog_files(path_prefix: &str, current_dir: &Path) -> Vec<(String, PathBuf)> { diff --git a/src/arena.rs b/src/arena.rs index aae81e4e..f8cd9695 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -21,8 +21,8 @@ use std::net::TcpListener; use std::ops::{Deref, DerefMut}; use std::process::Child; use std::ptr; -use std::ptr::addr_of_mut; use std::ptr::NonNull; +use std::ptr::addr_of_mut; macro_rules! arena_alloc { ($e:expr, $arena:expr) => {{ @@ -32,9 +32,7 @@ macro_rules! arena_alloc { } macro_rules! float_alloc { - ($e:expr, $arena:expr) => {{ - $arena.f64_tbl.build_with(OrderedFloat($e)) - }}; + ($e:expr, $arena:expr) => {{ $arena.f64_tbl.build_with(OrderedFloat($e)) }}; } pub fn header_offset_from_payload() -> usize @@ -281,14 +279,16 @@ pub trait ArenaAllocated { unsafe fn typed_ptr(ptr: UntypedArenaPtr) -> TypedArenaPtr where Self::Payload: Sized, - { unsafe { - TypedArenaPtr(NonNull::new_unchecked( - ptr.get_ptr() - .byte_add(Self::header_offset_from_payload()) - .cast_mut() - .cast::(), - )) - }} + { + unsafe { + TypedArenaPtr(NonNull::new_unchecked( + ptr.get_ptr() + .byte_add(Self::header_offset_from_payload()) + .cast_mut() + .cast::(), + )) + } + } #[allow(clippy::missing_safety_doc)] fn alloc(arena: &mut Arena, value: Self::Payload) -> TypedArenaPtr @@ -496,91 +496,93 @@ impl Arena { } } -unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { unsafe { - macro_rules! drop_typed_slab_in_place { - ($payload: ty, $value: expr) => { - <$payload as ArenaAllocated>::dealloc($value.cast::>()) - }; - } +unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { + unsafe { + macro_rules! drop_typed_slab_in_place { + ($payload: ty, $value: expr) => { + <$payload as ArenaAllocated>::dealloc($value.cast::>()) + }; + } - match tag { - ArenaHeaderTag::Integer => { - drop_typed_slab_in_place!(Integer, value); - } - ArenaHeaderTag::Rational => { - drop_typed_slab_in_place!(Rational, value); - } - ArenaHeaderTag::InputFileStream => { - drop_typed_slab_in_place!(InputFileStream, value); - } - ArenaHeaderTag::OutputFileStream => { - drop_typed_slab_in_place!(OutputFileStream, value); - } - ArenaHeaderTag::NamedTcpStream => { - drop_typed_slab_in_place!(NamedTcpStream, value); - } - ArenaHeaderTag::NamedTlsStream => { - #[cfg(feature = "tls")] - drop_typed_slab_in_place!(NamedTlsStream, value); - } - ArenaHeaderTag::HttpReadStream => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpReadStream, value); - } - ArenaHeaderTag::HttpWriteStream => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpWriteStream, value); - } - ArenaHeaderTag::ReadlineStream => { - drop_typed_slab_in_place!(ReadlineStream, value); - } - ArenaHeaderTag::StaticStringStream => { - drop_typed_slab_in_place!(StaticStringStream, value); - } - ArenaHeaderTag::ByteStream => { - drop_typed_slab_in_place!(ByteStream, value); - } - ArenaHeaderTag::CallbackStream => { - drop_typed_slab_in_place!(CallbackStream, value); - } - ArenaHeaderTag::InputChannelStream => { - drop_typed_slab_in_place!(InputChannelStream, value); - } - ArenaHeaderTag::LiveLoadState | ArenaHeaderTag::InactiveLoadState => { - drop_typed_slab_in_place!(LiveLoadState, value); - } - ArenaHeaderTag::Dropped => {} - ArenaHeaderTag::TcpListener => { - drop_typed_slab_in_place!(TcpListener, value); - } - ArenaHeaderTag::HttpListener => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpListener, value); - } - ArenaHeaderTag::HttpResponse => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpResponse, value); - } - ArenaHeaderTag::StandardOutputStream => { - drop_typed_slab_in_place!(StandardOutputStream, value); - } - ArenaHeaderTag::StandardErrorStream => { - drop_typed_slab_in_place!(StandardErrorStream, value); - } - ArenaHeaderTag::PipeReader => { - drop_typed_slab_in_place!(PipeReader, value); - } - ArenaHeaderTag::PipeWriter => { - drop_typed_slab_in_place!(PipeWriter, value); - } - ArenaHeaderTag::ChildProcess => { - drop_typed_slab_in_place!(Child, value); - } - ArenaHeaderTag::NullStream => { - unreachable!("NullStream is never arena allocated!"); + match tag { + ArenaHeaderTag::Integer => { + drop_typed_slab_in_place!(Integer, value); + } + ArenaHeaderTag::Rational => { + drop_typed_slab_in_place!(Rational, value); + } + ArenaHeaderTag::InputFileStream => { + drop_typed_slab_in_place!(InputFileStream, value); + } + ArenaHeaderTag::OutputFileStream => { + drop_typed_slab_in_place!(OutputFileStream, value); + } + ArenaHeaderTag::NamedTcpStream => { + drop_typed_slab_in_place!(NamedTcpStream, value); + } + ArenaHeaderTag::NamedTlsStream => { + #[cfg(feature = "tls")] + drop_typed_slab_in_place!(NamedTlsStream, value); + } + ArenaHeaderTag::HttpReadStream => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpReadStream, value); + } + ArenaHeaderTag::HttpWriteStream => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpWriteStream, value); + } + ArenaHeaderTag::ReadlineStream => { + drop_typed_slab_in_place!(ReadlineStream, value); + } + ArenaHeaderTag::StaticStringStream => { + drop_typed_slab_in_place!(StaticStringStream, value); + } + ArenaHeaderTag::ByteStream => { + drop_typed_slab_in_place!(ByteStream, value); + } + ArenaHeaderTag::CallbackStream => { + drop_typed_slab_in_place!(CallbackStream, value); + } + ArenaHeaderTag::InputChannelStream => { + drop_typed_slab_in_place!(InputChannelStream, value); + } + ArenaHeaderTag::LiveLoadState | ArenaHeaderTag::InactiveLoadState => { + drop_typed_slab_in_place!(LiveLoadState, value); + } + ArenaHeaderTag::Dropped => {} + ArenaHeaderTag::TcpListener => { + drop_typed_slab_in_place!(TcpListener, value); + } + ArenaHeaderTag::HttpListener => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpListener, value); + } + ArenaHeaderTag::HttpResponse => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpResponse, value); + } + ArenaHeaderTag::StandardOutputStream => { + drop_typed_slab_in_place!(StandardOutputStream, value); + } + ArenaHeaderTag::StandardErrorStream => { + drop_typed_slab_in_place!(StandardErrorStream, value); + } + ArenaHeaderTag::PipeReader => { + drop_typed_slab_in_place!(PipeReader, value); + } + ArenaHeaderTag::PipeWriter => { + drop_typed_slab_in_place!(PipeWriter, value); + } + ArenaHeaderTag::ChildProcess => { + drop_typed_slab_in_place!(Child, value); + } + ArenaHeaderTag::NullStream => { + unreachable!("NullStream is never arena allocated!"); + } } } -}} +} impl Drop for Arena { fn drop(&mut self) { diff --git a/src/arithmetic.rs b/src/arithmetic.rs index df5b6268..b714ddc1 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -64,7 +64,7 @@ impl<'a> ArithInstructionIterator<'a> { return Err(ArithmeticError::NonEvaluableFunctor( Literal::Atom(atom!(".")), 2, - )) + )); } Term::Var(cell, var_ptr) => TermIterState::Var(Level::Shallow, cell, var_ptr.clone()), }; @@ -519,26 +519,16 @@ impl PartialEq for Number { (&Number::Fixnum(n1), Number::Rational(n2)) => { Integer::from(n1.get_num()).num_eq(&**n2) } - (Number::Rational(n1), &Number::Fixnum(n2)) => { - n1.num_eq(&Integer::from(n2.get_num())) - } + (Number::Rational(n1), &Number::Fixnum(n2)) => n1.num_eq(&Integer::from(n2.get_num())), (&Number::Fixnum(n1), &Number::Float(n2)) => OrderedFloat(n1.get_num() as f64).eq(&n2), (&Number::Float(n1), &Number::Fixnum(n2)) => n1.eq(&OrderedFloat(n2.get_num() as f64)), (Number::Integer(n1), Number::Integer(n2)) => n1.eq(n2), - (Number::Integer(n1), Number::Float(n2)) => { - OrderedFloat(n1.to_f64().value()).eq(n2) - } - (&Number::Float(n1), Number::Integer(n2)) => { - n1.eq(&OrderedFloat(n2.to_f64().value())) - } + (Number::Integer(n1), Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).eq(n2), + (&Number::Float(n1), Number::Integer(n2)) => n1.eq(&OrderedFloat(n2.to_f64().value())), (Number::Integer(n1), Number::Rational(n2)) => n1.num_eq(&**n2), (Number::Rational(n1), Number::Integer(n2)) => n1.num_eq(&**n2), - (Number::Rational(n1), &Number::Float(n2)) => { - OrderedFloat(n1.to_f64().value()).eq(&n2) - } - (&Number::Float(n1), Number::Rational(n2)) => { - n1.eq(&OrderedFloat(n2.to_f64().value())) - } + (Number::Rational(n1), &Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).eq(&n2), + (&Number::Float(n1), Number::Rational(n2)) => n1.eq(&OrderedFloat(n2.to_f64().value())), (&Number::Float(f1), &Number::Float(f2)) => f1.eq(&f2), (Number::Rational(r1), Number::Rational(r2)) => r1.eq(r2), } @@ -607,9 +597,7 @@ impl Ord for Number { (&Number::Float(n1), &Number::Fixnum(n2)) => n1.cmp(&OrderedFloat(n2.get_num() as f64)), (&Number::Integer(n1), &Number::Integer(n2)) => (*n1).cmp(&*n2), (&Number::Integer(n1), Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).cmp(n2), - (&Number::Float(n1), Number::Integer(n2)) => { - n1.cmp(&OrderedFloat(n2.to_f64().value())) - } + (&Number::Float(n1), Number::Integer(n2)) => n1.cmp(&OrderedFloat(n2.to_f64().value())), (&Number::Integer(n1), &Number::Rational(n2)) => { (*n1).num_partial_cmp(&*n2).unwrap_or(Ordering::Less) } diff --git a/src/atom_table.rs b/src/atom_table.rs index 5526b1ff..5292d208 100644 --- a/src/atom_table.rs +++ b/src/atom_table.rs @@ -14,10 +14,10 @@ use std::sync::Mutex; use std::sync::RwLock; use std::sync::Weak; +use arcu::Rcu; use arcu::atomic::Arcu; use arcu::epoch_counters::GlobalEpochCounterPool; use arcu::rcu_ref::RcuRef; -use arcu::Rcu; use indexmap::IndexSet; use modular_bitfield::prelude::*; @@ -344,11 +344,7 @@ impl Atom { let c1 = it.next(); let c2 = it.next(); - if c2.is_none() { - c1 - } else { - None - } + if c2.is_none() { c1 } else { None } } #[inline] @@ -387,8 +383,10 @@ impl Atom { } } -unsafe fn write_to_ptr(string: &str, ptr: *mut u8) { - unsafe { ptr::write(ptr as *mut _, AtomHeader::build_with(string.len() as u64)); } +unsafe fn write_to_ptr(string: &str, ptr: *mut u8) { + unsafe { + ptr::write(ptr as *mut _, AtomHeader::build_with(string.len() as u64)); + } unsafe { let str_ptr = ptr.add(mem::size_of::()); ptr::copy_nonoverlapping(string.as_ptr(), str_ptr, string.len()); diff --git a/src/debray_allocator.rs b/src/debray_allocator.rs index 39d37820..e901fc6e 100644 --- a/src/debray_allocator.rs +++ b/src/debray_allocator.rs @@ -551,8 +551,7 @@ impl DebrayAllocator { } else if let Some(&temp_var_num) = self.shallow_temp_mappings.get(&self.arg_c) { match &mut self.var_data.records[temp_var_num].allocation { VarAlloc::Temp { - to_perm_var_num, - .. + to_perm_var_num, .. } => { *to_perm_var_num = Some(var_num); } @@ -578,13 +577,7 @@ impl DebrayAllocator { let branch_designator = Arc::new(self.branch_stack.current_branch_designator()); match &mut self.var_data.records[var_num].allocation { - VarAlloc::Perm( - _, - PermVarAllocation::Done { - shallow_safety, - .. - }, - ) => { + VarAlloc::Perm(_, PermVarAllocation::Done { shallow_safety, .. }) => { if !self.in_tail_position || self .branch_stack @@ -614,13 +607,7 @@ impl DebrayAllocator { let branch_designator = Arc::new(self.branch_stack.current_branch_designator()); match &mut self.var_data.records[var_num].allocation { - VarAlloc::Perm( - _, - PermVarAllocation::Done { - deep_safety, - .. - }, - ) => { + VarAlloc::Perm(_, PermVarAllocation::Done { deep_safety, .. }) => { if self .branch_stack .safety_unneeded_in_branch(deep_safety, &branch_designator) diff --git a/src/ffi.rs b/src/ffi.rs index 3a4f9dde..d319cfc7 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -32,7 +32,7 @@ use ordered_float::OrderedFloat; use std::alloc::{self, Layout}; use std::collections::HashMap; use std::error::Error; -use std::ffi::{c_char, c_void, CStr, CString}; +use std::ffi::{CStr, CString, c_char, c_void}; use std::fmt::Debug; use std::marker::PhantomData; use std::mem::ManuallyDrop; @@ -53,27 +53,33 @@ pub struct FunctionImpl { } impl FunctionImpl { - unsafe fn call_void(&self, args: &[Arg], _: &mut Arena) -> Result { unsafe { - self.cif.call_return_into(self.code_ptr, args, Ret::void()); - Ok(Value::Number(Number::Fixnum(Fixnum::build_with(0)))) - }} + unsafe fn call_void(&self, args: &[Arg], _: &mut Arena) -> Result { + unsafe { + self.cif.call_return_into(self.code_ptr, args, Ret::void()); + Ok(Value::Number(Number::Fixnum(Fixnum::build_with(0)))) + } + } unsafe fn call_int(&self, args: &[Arg], arena: &mut Arena) -> Result where Integer: From, T: Copy + TryInto + MightNotFitInFixnum, - { unsafe { - let n = self.cif.call::(self.code_ptr, args); - Ok(Value::Number(fixnum!(Number, n, arena))) - }} + { + unsafe { + let n = self.cif.call::(self.code_ptr, args); + Ok(Value::Number(fixnum!(Number, n, arena))) + } + } unsafe fn call_float(&self, args: &[Arg], _: &mut Arena) -> Result where T: Into, - { unsafe { - let n = self.cif.call::(self.code_ptr, args); - Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - }} + { + unsafe { + let n = self.cif.call::(self.code_ptr, args); + Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) + } + } unsafe fn call_ptr(&self, args: &[Arg], arena: &mut Arena) -> Result { let ptr = unsafe { self.cif.call::<*mut c_void>(self.code_ptr, args) }; @@ -147,7 +153,7 @@ impl FunctionImpl { FfiType::Ptr => FunctionImpl::call_ptr, FfiType::CStr => FunctionImpl::call_cstr, FfiType::Struct(name) => { - return unsafe { self.call_struct(name, args, arena, structs_table) } + return unsafe { self.call_struct(name, args, arena, structs_table) }; } }; unsafe { call_fn(self, args, arena) } @@ -197,14 +203,16 @@ impl StructImpl { ptr: NonNull, layout: &mut Layout, val: T, - ) -> Result<(), FfiError> { unsafe { - let (new_layout, offset) = layout - .extend(Layout::new::()) - .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; - ptr.byte_offset(offset as isize).cast::().write(val); - Ok(()) - }} + ) -> Result<(), FfiError> { + unsafe { + let (new_layout, offset) = layout + .extend(Layout::new::()) + .map_err(|_| FfiError::LayoutError)?; + *layout = new_layout; + ptr.byte_offset(offset as isize).cast::().write(val); + Ok(()) + } + } for arg in args { unsafe { @@ -258,14 +266,16 @@ impl StructImpl { unsafe fn read_primitive( ptr: *mut c_void, layout: &mut Layout, - ) -> Result { unsafe { - let (new_layout, offset) = layout - .extend(Layout::new::()) - .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; - let n = std::ptr::read::(ptr.byte_offset(offset as isize).cast()); - Ok(n) - }} + ) -> Result { + unsafe { + let (new_layout, offset) = layout + .extend(Layout::new::()) + .map_err(|_| FfiError::LayoutError)?; + *layout = new_layout; + let n = std::ptr::read::(ptr.byte_offset(offset as isize).cast()); + Ok(n) + } + } unsafe fn read_int( ptr: *mut c_void, @@ -275,10 +285,12 @@ impl StructImpl { where T: Copy + TryInto + MightNotFitInFixnum, Integer: From, - { unsafe { - let n = read_primitive::(ptr, layout)?; - Ok(Value::Number(fixnum!(Number, n, arena))) - }} + { + unsafe { + let n = read_primitive::(ptr, layout)?; + Ok(Value::Number(fixnum!(Number, n, arena))) + } + } unsafe fn read_float( ptr: *mut c_void, @@ -286,10 +298,12 @@ impl StructImpl { ) -> Result where T: Into, - { unsafe { - let n = read_primitive::(ptr, layout)?; - Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - }} + { + unsafe { + let n = read_primitive::(ptr, layout)?; + Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) + } + } let mut layout = Layout::from_size_align(0, 1).map_err(|_| FfiError::LayoutError)?; @@ -332,7 +346,7 @@ impl StructImpl { Ok(struct_val) } FfiType::Void => { - return Err(FfiError::UnsupportedArgumentType(Some(atom!("void")))) + return Err(FfiError::UnsupportedArgumentType(Some(atom!("void")))); } }; returns.push(val?); @@ -788,10 +802,12 @@ impl ForeignFunctionTable { where T: Copy + TryInto + MightNotFitInFixnum, Integer: From, - { unsafe { - let n = ptr.cast::().read(); - Value::Number(fixnum!(Number, n, arena)) - }} + { + unsafe { + let n = ptr.cast::().read(); + Value::Number(fixnum!(Number, n, arena)) + } + } let ptr = ptr.as_ptr()?; diff --git a/src/functor_macro.rs b/src/functor_macro.rs index 82d6d98e..37daf72b 100644 --- a/src/functor_macro.rs +++ b/src/functor_macro.rs @@ -230,9 +230,9 @@ pub(crate) fn variadic_functor( #[allow(unused_parens)] mod tests { use super::*; + use FunctorElement::*; use indexmap::indexmap; use std::string::String; - use FunctorElement::*; #[test] fn basic_terms() { diff --git a/src/heap_print.rs b/src/heap_print.rs index fcc0cc0c..8f0cd7fe 100644 --- a/src/heap_print.rs +++ b/src/heap_print.rs @@ -3,7 +3,7 @@ use crate::atom_table::*; use crate::parser::ast::*; use crate::parser::dashu::base::RemEuclid; use crate::parser::dashu::integer::Sign; -use crate::parser::dashu::{ibig, Integer, Rational}; +use crate::parser::dashu::{Integer, Rational, ibig}; use crate::forms::*; use crate::heap_iter::*; diff --git a/src/http.rs b/src/http.rs index d9f669d7..241b2e10 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,4 +1,4 @@ -use bytes::{buf::Reader, Bytes}; +use bytes::{Bytes, buf::Reader}; use std::sync::{Arc, Condvar, Mutex}; use tokio::sync::Notify; diff --git a/src/indexing.rs b/src/indexing.rs index 2b5b9767..d6c3247e 100644 --- a/src/indexing.rs +++ b/src/indexing.rs @@ -491,33 +491,29 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( - _, - _, - _, - _, - s, - )) => match *s { - IndexingCodePtr::Fail if self.is_dynamic => { - *s = IndexingCodePtr::DynamicExternal(index); - break; + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => { + match *s { + IndexingCodePtr::Fail if self.is_dynamic => { + *s = IndexingCodePtr::DynamicExternal(index); + break; + } + IndexingCodePtr::Fail => { + *s = IndexingCodePtr::External(index); + break; + } + IndexingCodePtr::DynamicExternal(o) => { + *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); + self.internalize_structure(IndexingCodePtr::DynamicExternal(o)); + } + IndexingCodePtr::External(o) => { + *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); + self.internalize_structure(IndexingCodePtr::External(o)); + } + IndexingCodePtr::Internal(o) => { + self.offset += o; + } } - IndexingCodePtr::Fail => { - *s = IndexingCodePtr::External(index); - break; - } - IndexingCodePtr::DynamicExternal(o) => { - *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); - self.internalize_structure(IndexingCodePtr::DynamicExternal(o)); - } - IndexingCodePtr::External(o) => { - *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); - self.internalize_structure(IndexingCodePtr::External(o)); - } - IndexingCodePtr::Internal(o) => { - self.offset += o; - } - }, + } IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(structures)) => { match structures.get(&key).cloned() { None | Some(IndexingCodePtr::Fail) if self.is_dynamic => { @@ -559,52 +555,50 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => { - match *l { - IndexingCodePtr::Fail if self.is_dynamic => { - *l = IndexingCodePtr::DynamicExternal(index); - } - IndexingCodePtr::Fail => { - *l = IndexingCodePtr::External(index); - } - IndexingCodePtr::DynamicExternal(o) => { - *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); - - let third_level_index = if self.append_or_prepend.is_append() { - vec![o, index].into() - } else { - vec![index, o].into() - }; - - self.indexing_code - .push(IndexingLine::DynamicIndexedChoice(third_level_index)); - } - IndexingCodePtr::External(o) => { - *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); - - let third_level_index = if self.append_or_prepend.is_append() { - vec![ - IndexedChoiceInstruction::Try(o), - IndexedChoiceInstruction::Trust(index), - ] - .into() - } else { - vec![ - IndexedChoiceInstruction::Try(index), - IndexedChoiceInstruction::Trust(o), - ] - .into() - }; - - self.indexing_code - .push(IndexingLine::IndexedChoice(third_level_index)); - } - IndexingCodePtr::Internal(o) => { - self.offset += o; - self.extend_indexed_choice(index); - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => match *l { + IndexingCodePtr::Fail if self.is_dynamic => { + *l = IndexingCodePtr::DynamicExternal(index); } - } + IndexingCodePtr::Fail => { + *l = IndexingCodePtr::External(index); + } + IndexingCodePtr::DynamicExternal(o) => { + *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); + + let third_level_index = if self.append_or_prepend.is_append() { + vec![o, index].into() + } else { + vec![index, o].into() + }; + + self.indexing_code + .push(IndexingLine::DynamicIndexedChoice(third_level_index)); + } + IndexingCodePtr::External(o) => { + *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); + + let third_level_index = if self.append_or_prepend.is_append() { + vec![ + IndexedChoiceInstruction::Try(o), + IndexedChoiceInstruction::Trust(index), + ] + .into() + } else { + vec![ + IndexedChoiceInstruction::Try(index), + IndexedChoiceInstruction::Trust(o), + ] + .into() + }; + + self.indexing_code + .push(IndexingLine::IndexedChoice(third_level_index)); + } + IndexingCodePtr::Internal(o) => { + self.offset += o; + self.extend_indexed_choice(index); + } + }, _ => { unreachable!() } @@ -676,20 +670,18 @@ pub(crate) fn remove_constant_indices( let iter = once(&constant).chain(overlapping_constants.iter()); match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => { - match *c { - IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { - *c = IndexingCodePtr::Fail; - return; - } - IndexingCodePtr::Internal(o) => { - index += o; - } - IndexingCodePtr::Fail => { - return; - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => match *c { + IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { + *c = IndexingCodePtr::Fail; + return; } - } + IndexingCodePtr::Internal(o) => { + index += o; + } + IndexingCodePtr::Fail => { + return; + } + }, _ => { unreachable!() } @@ -700,9 +692,7 @@ pub(crate) fn remove_constant_indices( for constant in iter.map(|l| HeapCellValue::from(*l)) { loop { match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant( - constants, - )) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) => { constants_index = index; match constants.get(&constant).cloned() { @@ -819,20 +809,18 @@ pub(crate) fn remove_structure_index( let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => { - match *s { - IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { - *s = IndexingCodePtr::Fail; - return; - } - IndexingCodePtr::Internal(o) => { - index += o; - } - IndexingCodePtr::Fail => { - return; - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => match *s { + IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { + *s = IndexingCodePtr::Fail; + return; } - } + IndexingCodePtr::Internal(o) => { + index += o; + } + IndexingCodePtr::Fail => { + return; + } + }, _ => { unreachable!() } @@ -932,13 +920,7 @@ pub(crate) fn remove_structure_index( if structures.is_empty() => { match &mut indexing_code[0] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( - _, - _, - _, - _, - s, - )) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => { *s = IndexingCodePtr::Fail; } _ => { @@ -954,20 +936,18 @@ pub(crate) fn remove_list_index(indexing_code: &mut [IndexingLine], offset: usiz let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => { - match *l { - IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { - *l = IndexingCodePtr::Fail; - return; - } - IndexingCodePtr::Internal(o) => { - index += o; - } - IndexingCodePtr::Fail => { - return; - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => match *l { + IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { + *l = IndexingCodePtr::Fail; + return; } - } + IndexingCodePtr::Internal(o) => { + index += o; + } + IndexingCodePtr::Fail => { + return; + } + }, _ => { unreachable!() } diff --git a/src/iterators.rs b/src/iterators.rs index eadeb093..fb318a44 100644 --- a/src/iterators.rs +++ b/src/iterators.rs @@ -90,7 +90,7 @@ impl<'a> QueryIterator<'a> { | Term::CompleteString(..) => { return QueryIterator { state_stack: vec![], - } + }; } Term::Clause(r, name, terms) => TermIterState::Clause(Level::Root, 0, r, *name, terms), Term::Var(cell, var_ptr) => TermIterState::Var(Level::Root, cell, var_ptr.clone()), @@ -143,7 +143,7 @@ impl<'a> Iterator for QueryIterator<'a> { return match lvl { Level::Root => None, lvl => Some(TermRef::Clause(lvl, cell, name, child_terms)), - } + }; } }; } else { @@ -293,7 +293,7 @@ impl<'a> Iterator for FactIterator<'a> { return Some(TermRef::CompleteString(lvl, cell, atom)); } TermIterState::Literal(lvl, cell, constant) => { - return Some(TermRef::Literal(lvl, cell, constant)) + return Some(TermRef::Literal(lvl, cell, constant)); } TermIterState::Var(lvl, cell, var_ptr) => { return Some(TermRef::Var(lvl, cell, var_ptr)); diff --git a/src/lib.rs b/src/lib.rs index ee73d4f2..d1677c43 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,9 +43,9 @@ mod targets; pub(crate) mod types; // Re-exports +pub use machine::Machine; pub use machine::config::*; pub use machine::lib_machine::*; -pub use machine::Machine; #[cfg(target_arch = "wasm32")] pub mod wasm; diff --git a/src/machine/arithmetic_ops.rs b/src/machine/arithmetic_ops.rs index 84105a38..92aa0ca9 100644 --- a/src/machine/arithmetic_ops.rs +++ b/src/machine/arithmetic_ops.rs @@ -1,6 +1,6 @@ use dashu::base::{Abs, Gcd, Signed, UnsignedAbs}; -use dashu::integer::fast_div::ConstDivisor; use dashu::integer::IBig; +use dashu::integer::fast_div::ConstDivisor; use divrem::*; use num_order::NumOrd; diff --git a/src/machine/compile.rs b/src/machine/compile.rs index c4789328..40b5275f 100644 --- a/src/machine/compile.rs +++ b/src/machine/compile.rs @@ -564,9 +564,7 @@ fn thread_choice_instr_at_to( ) { loop { match &mut code[instr_loc] { - Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) - if target_loc >= instr_loc => - { + Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) if target_loc >= instr_loc => { retraction_info.push_record(RetractionRecord::ReplacedChoiceOffset(instr_loc, *o)); *o = target_loc - instr_loc; @@ -1632,8 +1630,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { }; match &mut self.wam_prelude.code[clause_loc] { - Instruction::DynamicElse(_, d, _) - | Instruction::DynamicInternalElse(_, d, _) => { + Instruction::DynamicElse(_, d, _) | Instruction::DynamicInternalElse(_, d, _) => { *d = Death::Finite(LS::machine_st(&mut self.payload).global_clock); } _ => unreachable!(), diff --git a/src/machine/config.rs b/src/machine/config.rs index d4839d69..0471dcf4 100644 --- a/src/machine/config.rs +++ b/src/machine/config.rs @@ -1,14 +1,14 @@ use std::borrow::Cow; use std::io::Write; -use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::mpsc::{Receiver, Sender, channel}; -use rand::{rngs::StdRng, SeedableRng}; +use rand::{SeedableRng, rngs::StdRng}; use crate::Machine; use super::{ - bootstrapping_compile, current_dir, import_builtin_impls, libraries, load_module, Arena, Atom, - Callback, CompilationTarget, IndexStore, ListingSource, MachineArgs, MachineState, Stream, + Arena, Atom, Callback, CompilationTarget, IndexStore, ListingSource, MachineArgs, MachineState, + Stream, bootstrapping_compile, current_dir, import_builtin_impls, libraries, load_module, }; #[derive(Default)] diff --git a/src/machine/dispatch.rs b/src/machine/dispatch.rs index f0184122..46f9af13 100644 --- a/src/machine/dispatch.rs +++ b/src/machine/dispatch.rs @@ -1366,9 +1366,7 @@ impl Machine { let indexed_choice_instrs = match &self.code[p] { Instruction::IndexingCode(indexing_code) => match &indexing_code[oi as usize] { - IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => { - indexed_choice_instrs - } + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => indexed_choice_instrs, _ => unreachable!(), }, _ => unreachable!(), diff --git a/src/machine/heap.rs b/src/machine/heap.rs index 37a30315..3353056f 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -57,38 +57,41 @@ struct InnerHeap { } impl InnerHeap { - unsafe fn grow(&mut self) -> bool { unsafe { - let new_cap = if self.byte_cap == 0 { - 256 * 256 * 8 - } else { - 2 * self.byte_cap - }; + unsafe fn grow(&mut self) -> bool { + unsafe { + let new_cap = if self.byte_cap == 0 { + 256 * 256 * 8 + } else { + 2 * self.byte_cap + }; - let new_layout = - alloc::Layout::from_size_align(new_cap, size_of::()).unwrap(); + let new_layout = + alloc::Layout::from_size_align(new_cap, size_of::()).unwrap(); - assert!( - new_layout.size() <= isize::MAX as usize, - "Allocation too large. We should probably GC (TODO)" - ); + assert!( + new_layout.size() <= isize::MAX as usize, + "Allocation too large. We should probably GC (TODO)" + ); - let new_ptr = if self.byte_cap == 0 { - alloc::alloc(new_layout) - } else { - let old_layout = - alloc::Layout::from_size_align(self.byte_cap, size_of::()).unwrap(); - alloc::realloc(self.ptr, old_layout, new_layout.size()) - }; + let new_ptr = if self.byte_cap == 0 { + alloc::alloc(new_layout) + } else { + let old_layout = + alloc::Layout::from_size_align(self.byte_cap, size_of::()) + .unwrap(); + alloc::realloc(self.ptr, old_layout, new_layout.size()) + }; - if !new_ptr.is_null() { - self.ptr = new_ptr; - self.byte_cap = new_cap; + if !new_ptr.is_null() { + self.ptr = new_ptr; + self.byte_cap = new_cap; - true - } else { - false + true + } else { + false + } } - }} + } } unsafe impl Send for Heap {} @@ -101,48 +104,52 @@ pub struct HeapStringScan<'a> { } // The heap_slice should be inside the heap -unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { unsafe { - let string_len = heap_slice - .iter() - .position(|b| *b == 0u8) - .unwrap_or(heap_slice.len()); - let zero_byte_addr = heap_slice.as_ptr().add(string_len); +unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { + unsafe { + let string_len = heap_slice + .iter() + .position(|b| *b == 0u8) + .unwrap_or(heap_slice.len()); + let zero_byte_addr = heap_slice.as_ptr().add(string_len); - let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); - let tail_idx = cell_index!( - (string_len + sentinel_len).next_multiple_of(ALIGN) - + if sentinel_len <= 1 { heap_index!(1) } else { 0 } - ); + let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); + let tail_idx = cell_index!( + (string_len + sentinel_len).next_multiple_of(ALIGN) + + if sentinel_len <= 1 { heap_index!(1) } else { 0 } + ); - let str_slice = &heap_slice[..string_len]; + let str_slice = &heap_slice[..string_len]; - HeapStringScan { - string: std::str::from_utf8_unchecked(str_slice), - tail_idx, + HeapStringScan { + string: std::str::from_utf8_unchecked(str_slice), + tail_idx, + } } -}} +} // Same as scan_slice_to_str but assumes that the slice is from the start of a string. // Can be used on strings out of the heap. -unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { unsafe { - let string_len = heap_slice - .iter() - .position(|b| *b == 0u8) - .unwrap_or(heap_slice.len()); +unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { + unsafe { + let string_len = heap_slice + .iter() + .position(|b| *b == 0u8) + .unwrap_or(heap_slice.len()); - let sentinel_len = pstr_sentinel_length(string_len); - let tail_idx = cell_index!( - (string_len + sentinel_len).next_multiple_of(ALIGN) - + if sentinel_len <= 1 { heap_index!(1) } else { 0 } - ); + let sentinel_len = pstr_sentinel_length(string_len); + let tail_idx = cell_index!( + (string_len + sentinel_len).next_multiple_of(ALIGN) + + if sentinel_len <= 1 { heap_index!(1) } else { 0 } + ); - let str_slice = &heap_slice[..string_len]; + let str_slice = &heap_slice[..string_len]; - HeapStringScan { - string: std::str::from_utf8_unchecked(str_slice), - tail_idx, + HeapStringScan { + string: std::str::from_utf8_unchecked(str_slice), + tail_idx, + } } -}} +} #[derive(Debug, Clone, Copy)] pub(crate) enum PStrContinuable { @@ -450,11 +457,7 @@ fn pstr_sentinel_length(chunk_len: usize) -> usize { let res = chunk_len.next_multiple_of(ALIGN) - chunk_len; // No bytes available in last chunk - if res == 0 { - ALIGN - } else { - res - } + if res == 0 { ALIGN } else { res } } #[must_use] @@ -585,9 +588,9 @@ impl Heap { } #[inline(always)] - unsafe fn grow(&mut self) -> bool { unsafe { - self.inner.grow() - }} + unsafe fn grow(&mut self) -> bool { + unsafe { self.inner.grow() } + } #[inline] fn resource_error_offset(&self) -> usize { diff --git a/src/machine/lib_machine/mod.rs b/src/machine/lib_machine/mod.rs index 75aeffc6..069cf3e7 100644 --- a/src/machine/lib_machine/mod.rs +++ b/src/machine/lib_machine/mod.rs @@ -3,23 +3,23 @@ use std::collections::BTreeMap; use std::rc::Rc; use crate::atom_table; -use crate::heap_iter::{stackful_post_order_iter, NonListElider}; +use crate::heap_iter::{NonListElider, stackful_post_order_iter}; use crate::machine::heap::AllocError; use crate::machine::machine_indices::VarKey; use crate::machine::mock_wam::CompositeOpDir; use crate::machine::{ - ArenaHeaderTag, Fixnum, Number, BREAK_FROM_DISPATCH_LOOP_LOC, LIB_QUERY_SUCCESS, + ArenaHeaderTag, BREAK_FROM_DISPATCH_LOOP_LOC, Fixnum, LIB_QUERY_SUCCESS, Number, }; use crate::offset_table::*; use crate::parser::ast::{Var, VarPtr}; use crate::parser::parser::{Parser, Tokens}; -use crate::read::{write_term_to_heap, TermWriteResult}; +use crate::read::{TermWriteResult, write_term_to_heap}; use crate::types::UntypedArenaPtr; use dashu::{Integer, Rational}; use indexmap::IndexMap; -use super::{streams::Stream, Atom, AtomCell, HeapCellValue, HeapCellValueTag, Machine}; +use super::{Atom, AtomCell, HeapCellValue, HeapCellValueTag, Machine, streams::Stream}; #[cfg(test)] mod tests; diff --git a/src/machine/loader.rs b/src/machine/loader.rs index 26508756..0e31e8a0 100644 --- a/src/machine/loader.rs +++ b/src/machine/loader.rs @@ -819,11 +819,8 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { if let Instruction::IndexingCode(ref mut indexing_code) = self.wam_prelude.code[index_loc] { - if let IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( - _, - v, - .., - )) = &mut indexing_code[0] + if let IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, v, ..)) = + &mut indexing_code[0] { *v = old_v; } @@ -1364,14 +1361,12 @@ impl<'a> MachinePreludeView<'a> { ) -> CompositeOpDir<'_, '_> { match compilation_target { CompilationTarget::User => CompositeOpDir::new(&self.indices.op_dir, None), - CompilationTarget::Module(module_name) => { - match self.indices.modules.get(module_name) { - Some(module) => CompositeOpDir::new(&self.indices.op_dir, Some(&module.op_dir)), - None => { - unreachable!() - } + CompilationTarget::Module(module_name) => match self.indices.modules.get(module_name) { + Some(module) => CompositeOpDir::new(&self.indices.op_dir, Some(&module.op_dir)), + None => { + unreachable!() } - } + }, } } } @@ -1504,9 +1499,10 @@ impl Machine { } pub(crate) fn load_compiled_library(&mut self) -> CallResult { - let library = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let library = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); if let Some(module) = self.indices.modules.get(&library) { if let ListingSource::DynamicallyGenerated = module.listing_src { @@ -1537,9 +1533,10 @@ impl Machine { } pub(crate) fn declare_module(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let mut loader = self.loader_from_heap_evacuable(temp_v!(3)); @@ -1649,9 +1646,10 @@ impl Machine { } pub(crate) fn add_goal_expansion_clause(&mut self) -> CallResult { - let target_module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let target_module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let mut loader = self.loader_from_heap_evacuable(temp_v!(3)); @@ -1744,9 +1742,10 @@ impl Machine { &mut self, r: RegType, ) -> Loader<'_, LiveLoadAndMachineState<'_>> { - let mut load_state = cell_as_load_state_payload!(self - .machine_st - .store(self.machine_st.deref(self.machine_st[r]))); + let mut load_state = cell_as_load_state_payload!( + self.machine_st + .store(self.machine_st.deref(self.machine_st[r])) + ); load_state.set_tag(ArenaHeaderTag::LiveLoadState); @@ -2098,9 +2097,10 @@ impl Machine { } pub(crate) fn abolish_clause(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2214,9 +2214,10 @@ impl Machine { _ => unreachable!(), }; - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[4]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[4])) + ); let compilation_target = match module_name { atom!("user") => CompilationTarget::User, @@ -2269,9 +2270,10 @@ impl Machine { } pub(crate) fn is_consistent_with_term_queue(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2309,9 +2311,10 @@ impl Machine { } pub(crate) fn remove_module_exports(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let mut loader = self.loader_from_heap_evacuable(temp_v!(2)); @@ -2337,9 +2340,10 @@ impl Machine { } pub(crate) fn meta_predicate_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let (predicate_name, arity) = self .machine_st @@ -2401,9 +2405,10 @@ impl Machine { } pub(crate) fn dynamic_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2428,9 +2433,10 @@ impl Machine { } pub(crate) fn multifile_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2455,9 +2461,10 @@ impl Machine { } pub(crate) fn discontiguous_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st diff --git a/src/machine/machine_errors.rs b/src/machine/machine_errors.rs index c07e18ce..26320951 100644 --- a/src/machine/machine_errors.rs +++ b/src/machine/machine_errors.rs @@ -777,7 +777,9 @@ impl MachineState { // throw an error pre-allocated in the heap pub(super) fn throw_resource_error(&mut self, err: AllocError) { if self.throwing_resource_error { - panic!("attempted to throw `error(resource_error(memory), [])` while attempting to throw `error(resource_error(memory), [])`"); + panic!( + "attempted to throw `error(resource_error(memory), [])` while attempting to throw `error(resource_error(memory), [])`" + ); } self.throwing_resource_error = true; diff --git a/src/machine/machine_indices.rs b/src/machine/machine_indices.rs index e452786b..5b69986d 100644 --- a/src/machine/machine_indices.rs +++ b/src/machine/machine_indices.rs @@ -2,17 +2,17 @@ use crate::parser::ast::*; use crate::atom_table::*; use crate::forms::*; +use crate::machine::ClauseType; +use crate::machine::MachineStubGen; use crate::machine::loader::*; use crate::machine::machine_state::*; use crate::machine::streams::{Stream, StreamOptions}; -use crate::machine::ClauseType; -use crate::machine::MachineStubGen; use crate::offset_table::*; use fxhash::FxBuildHasher; use indexmap::{IndexMap, IndexSet}; use modular_bitfield::specifiers::*; -use modular_bitfield::{bitfield, Specifier}; +use modular_bitfield::{Specifier, bitfield}; use std::cmp::Ordering; use std::collections::BTreeSet; diff --git a/src/machine/machine_state.rs b/src/machine/machine_state.rs index 32b86aeb..d9f95cbf 100644 --- a/src/machine/machine_state.rs +++ b/src/machine/machine_state.rs @@ -3,6 +3,7 @@ use crate::atom_table::*; use crate::forms::*; use crate::heap_iter::*; use crate::heap_print::*; +use crate::machine::Machine; use crate::machine::attributed_variables::*; use crate::machine::copier::*; use crate::machine::heap::AllocError; @@ -11,7 +12,6 @@ use crate::machine::machine_errors::*; use crate::machine::machine_indices::*; use crate::machine::stack::*; use crate::machine::streams::*; -use crate::machine::Machine; use crate::parser::ast::*; use crate::read::TermWriteResult; use crate::types::*; diff --git a/src/machine/mod.rs b/src/machine/mod.rs index f7a21bf8..ed4de159 100644 --- a/src/machine/mod.rs +++ b/src/machine/mod.rs @@ -61,8 +61,8 @@ use std::env; use std::io::Read; use std::path::PathBuf; use std::process::ExitCode; -use std::sync::atomic::AtomicBool; use std::sync::OnceLock; +use std::sync::atomic::AtomicBool; pub static INTERRUPT: AtomicBool = AtomicBool::new(false); diff --git a/src/machine/preprocessor.rs b/src/machine/preprocessor.rs index 1cfa8bb0..c1b3d344 100644 --- a/src/machine/preprocessor.rs +++ b/src/machine/preprocessor.rs @@ -37,7 +37,7 @@ fn setup_op_decl(mut terms: Vec) -> Result { other => { return Err(CompilationError::InvalidDirective( DirectiveError::InvalidOpDeclSpecDomain(other), - )) + )); } }; diff --git a/src/machine/stack.rs b/src/machine/stack.rs index 258cfdd2..df9cd111 100644 --- a/src/machine/stack.rs +++ b/src/machine/stack.rs @@ -175,15 +175,17 @@ impl Stack { } #[inline(always)] - unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { unsafe { - loop { - let ptr = self.buf.alloc(frame_size); - if let Some(ptr) = NonNull::new(ptr) { - return Ok(ptr); + unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { + unsafe { + loop { + let ptr = self.buf.alloc(frame_size); + if let Some(ptr) = NonNull::new(ptr) { + return Ok(ptr); + } + self.buf.grow()?; } - self.buf.grow()?; } - }} + } pub(crate) fn allocate_and_frame(&mut self, num_cells: usize) -> Result { let frame_size = AndFrame::size_of(num_cells); diff --git a/src/machine/streams.rs b/src/machine/streams.rs index 5fdf5c01..26afde37 100644 --- a/src/machine/streams.rs +++ b/src/machine/streams.rs @@ -15,7 +15,7 @@ use crate::types::*; pub use modular_bitfield::prelude::*; #[cfg(feature = "http")] -use bytes::{buf::Reader as BufReader, Buf, Bytes}; +use bytes::{Buf, Bytes, buf::Reader as BufReader}; use std::cmp::Ordering; use std::error::Error; use std::fmt; @@ -2195,8 +2195,8 @@ mod test { use crate::*; use std::{cell::RefCell, io::Read, io::Write, rc::Rc}; - use crate::machine::config::*; use crate::LeafAnswer; + use crate::machine::config::*; use super::{Stream, StreamOptions}; diff --git a/src/machine/system_calls.rs b/src/machine/system_calls.rs index 5c859ba4..18fb8896 100644 --- a/src/machine/system_calls.rs +++ b/src/machine/system_calls.rs @@ -24,7 +24,7 @@ use crate::machine::machine_state::*; use crate::machine::partial_string::*; use crate::machine::stack::*; use crate::machine::streams::*; -use crate::machine::{get_structure_index, Machine}; +use crate::machine::{Machine, get_structure_index}; use crate::parser::ast::*; use crate::parser::char_reader::*; use crate::parser::dashu::Integer; @@ -48,7 +48,7 @@ use std::ffi::CString; use std::fs; use std::hash::{BuildHasher, BuildHasherDefault}; use std::io::{ErrorKind, Read, Write}; -use std::iter::{once, FromIterator}; +use std::iter::{FromIterator, once}; use std::mem; #[cfg(feature = "http")] use std::net::{SocketAddr, ToSocketAddrs}; @@ -63,13 +63,13 @@ use std::sync::LazyLock; use std::sync::{Arc, Condvar, Mutex}; use tokio::sync::Notify; -use chrono::{offset::Local, DateTime}; +use chrono::{DateTime, offset::Local}; #[cfg(not(target_arch = "wasm32"))] use cpu_time::ProcessTime; use std::time::{Duration, SystemTime}; #[cfg(feature = "repl")] -use crate::read::user_interaction::{get_key, KeyCode, KeyModifiers}; +use crate::read::user_interaction::{KeyCode, KeyModifiers, get_key}; use blake2::{Blake2b512, Blake2s256}; diff --git a/src/machine/system_calls/special_math.rs b/src/machine/system_calls/special_math.rs index 57e933f9..925345f1 100644 --- a/src/machine/system_calls/special_math.rs +++ b/src/machine/system_calls/special_math.rs @@ -1,5 +1,5 @@ -use crate::machine::Number; use crate::Machine; +use crate::machine::Number; use ordered_float::OrderedFloat; use puruspe::beta::*; use puruspe::error::*; diff --git a/src/machine/unify.rs b/src/machine/unify.rs index 58015ea6..4b28cd36 100644 --- a/src/machine/unify.rs +++ b/src/machine/unify.rs @@ -1,6 +1,6 @@ use crate::arena::*; use crate::forms::*; -use crate::heap_iter::{stackful_preorder_iter, NonListElider}; +use crate::heap_iter::{NonListElider, stackful_preorder_iter}; use crate::machine::machine_state::*; use crate::machine::*; use crate::offset_table::*; diff --git a/src/macros.rs b/src/macros.rs index 659eef4b..3cd39596 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -138,9 +138,7 @@ macro_rules! typed_arena_ptr_as_cell { } macro_rules! raw_ptr_as_cell { - ($ptr:expr) => {{ - HeapCellValue::from_arena_header_ptr($ptr) - }}; + ($ptr:expr) => {{ HeapCellValue::from_arena_header_ptr($ptr) }}; } macro_rules! untyped_arena_ptr_as_cell { diff --git a/src/offset_table.rs b/src/offset_table.rs index f496ca54..849fead6 100644 --- a/src/offset_table.rs +++ b/src/offset_table.rs @@ -2,10 +2,10 @@ use std::cell::UnsafeCell; use std::sync::Arc; use std::{fmt, mem, ptr}; +use arcu::Rcu; use arcu::atomic::Arcu; use arcu::epoch_counters::GlobalEpochCounterPool; use arcu::rcu_ref::RcuRef; -use arcu::Rcu; use fxhash::FxBuildHasher; use indexmap::IndexMap; use parking_lot::{Mutex, RwLock}; @@ -211,7 +211,7 @@ impl SerialOffsetTable { }) } - unsafe fn build_with(&mut self, value: T) -> usize { unsafe { + unsafe fn build_with(&mut self, value: T) -> usize { let mut ptr; loop { @@ -228,17 +228,17 @@ impl SerialOffsetTable { ptr::write(ptr as *mut T, value); // SAFETY: `ptr` was obtained from `self.block.alloc()` self.block.get_offset(ptr) - }} + } #[inline] - unsafe fn lookup(&self, offset: usize) -> &T { unsafe { + unsafe fn lookup(&self, offset: usize) -> &T { &*self.block.get_unchecked(offset).cast::() - }} + } #[inline] - unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { unsafe { + unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { &mut *self.block.get_unchecked(offset).cast::().cast_mut() - }} + } #[allow(clippy::wrong_self_convention)] fn to_concurrent(&mut self) -> ConcurrentOffsetTable diff --git a/src/parser/ast.rs b/src/parser/ast.rs index fb835611..4e4bf052 100644 --- a/src/parser/ast.rs +++ b/src/parser/ast.rs @@ -362,11 +362,7 @@ impl OpDesc { #[inline] pub fn arity(self) -> usize { - if !self.get_spec().is_infix() { - 1 - } else { - 2 - } + if !self.get_spec().is_infix() { 1 } else { 2 } } } diff --git a/src/parser/lexer.rs b/src/parser/lexer.rs index e617c7d9..3cbde243 100644 --- a/src/parser/lexer.rs +++ b/src/parser/lexer.rs @@ -85,7 +85,7 @@ macro_rules! try_nt { Ok(NumberToken::Partial($token)) } else { Err(e) - } + }; } } }}; @@ -771,7 +771,7 @@ impl<'a, R: CharRead> Lexer<'a, R> { Err(_) => { return self .vacate_with_float(token) - .map(|(offset, fl)| NumberToken::Float(offset, fl)) + .map(|(offset, fl)| NumberToken::Float(offset, fl)); } Ok(c) => c, }; diff --git a/src/read.rs b/src/read.rs index f0346ad2..45a06f7e 100644 --- a/src/read.rs +++ b/src/read.rs @@ -102,13 +102,7 @@ pub(crate) fn set_prompt(value: bool) { #[cfg(feature = "repl")] #[inline] fn get_prompt() -> &'static str { - unsafe { - if PROMPT { - "?- " - } else { - "" - } - } + unsafe { if PROMPT { "?- " } else { "" } } } thread_local! { diff --git a/src/read/user_interaction.rs b/src/read/user_interaction.rs index e6eab103..a0c96511 100644 --- a/src/read/user_interaction.rs +++ b/src/read/user_interaction.rs @@ -1,4 +1,4 @@ -use crossterm::event::{read, Event, KeyEventKind}; +use crossterm::event::{Event, KeyEventKind, read}; pub(crate) use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; use crossterm::tty::IsTty; diff --git a/src/types.rs b/src/types.rs index 9cec6926..7de134a5 100644 --- a/src/types.rs +++ b/src/types.rs @@ -761,9 +761,9 @@ impl UntypedArenaPtr { pub unsafe fn as_typed_ptr(self) -> TypedArenaPtr where T::Payload: Sized, - { unsafe { - T::typed_ptr(self) - }} + { + unsafe { T::typed_ptr(self) } + } #[inline] pub fn get_mark_bit(self) -> bool { diff --git a/src/variable_records.rs b/src/variable_records.rs index 2e05634a..9565b2da 100644 --- a/src/variable_records.rs +++ b/src/variable_records.rs @@ -106,9 +106,7 @@ impl VarAlloc { pub(crate) fn set_register(&mut self, reg_num: usize) { match self { VarAlloc::Perm(p, _) => *p = reg_num, - VarAlloc::Temp { - temp_reg, .. - } => *temp_reg = reg_num, + VarAlloc::Temp { temp_reg, .. } => *temp_reg = reg_num, }; } } diff --git a/tests/scryer/issues.rs b/tests/scryer/issues.rs index ac8c21d9..bfbd5303 100644 --- a/tests/scryer/issues.rs +++ b/tests/scryer/issues.rs @@ -16,7 +16,10 @@ fn call_0() { #[test] #[cfg_attr(miri, ignore = "unsupported operation when isolation is enabled")] fn issue2588_load_html() { - load_module_test("tests-pl/issue2588.pl", "[element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])]"); + load_module_test( + "tests-pl/issue2588.pl", + "[element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])]", + ); } // issue #2914 @@ -38,7 +41,10 @@ fn issue3256_load_xml_returns_list() { #[test] #[cfg_attr(miri, ignore = "unsupported operation when isolation is enabled")] fn issue2949_load_html() { - load_module_test("tests-pl/issue2949.pl", "[doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])][doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]]),comment([ ,c,o,m,m,e,n,t, ])]),element(body,[],[])])][comment([]),element(html,[],[element(head,[],[]),element(body,[],[])])]"); + load_module_test( + "tests-pl/issue2949.pl", + "[doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])][doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]]),comment([ ,c,o,m,m,e,n,t, ])]),element(body,[],[])])][comment([]),element(html,[],[element(head,[],[]),element(body,[],[])])]", + ); } // issue #2361 @@ -168,7 +174,7 @@ async fn http_open_hanging() { load_module_test_with_input( "tests-pl/issue-http_open-hanging.pl", format!("PROLOG={:?}.", env!("CARGO_BIN_EXE_scryer-prolog")), - "received response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\n" + "received response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\n", ); }