diff --git a/build.rs b/build.rs index aaa876ab..3cd4421d 100644 --- a/build.rs +++ b/build.rs @@ -15,15 +15,13 @@ fn find_prolog_files(libraries: &mut File, prefix: &str, current_dir: &Path) { for entry in entries.filter_map(Result::ok).map(|e| e.path()) { if entry.is_dir() { if let Some(file_name) = entry.file_name() { - let new_prefix = - prefix.to_owned() + file_name.to_str().unwrap() + "/"; + let new_prefix = prefix.to_owned() + file_name.to_str().unwrap() + "/"; find_prolog_files(libraries, &new_prefix, &entry); } } else if entry.is_file() { let ext = std::ffi::OsStr::new("pl"); if entry.extension() == Some(ext) { - let contain = - String::from_utf8(fs::read(&entry).unwrap()).unwrap(); + let contain = String::from_utf8(fs::read(&entry).unwrap()).unwrap(); let name = entry.file_stem().unwrap().to_str().unwrap(); let line = format!( @@ -47,7 +45,7 @@ fn main() { libraries .write_all( - b"ref_thread_local! { + b"ref_thread_local::ref_thread_local! { pub static managed LIBRARIES: IndexMap<&'static str, &'static str> = { let mut m = IndexMap::new();\n", ) diff --git a/src/allocator.rs b/src/allocator.rs index f2b2cd0c..c0e46da0 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -1,4 +1,5 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::temp_v; use crate::fixtures::*; use crate::forms::*; @@ -14,8 +15,13 @@ pub trait Allocator<'a> { fn mark_anon_var(&mut self, _: Level, _: GenContext, _: &mut Vec) where Target: CompilationTarget<'a>; - fn mark_non_var(&mut self, _: Level, _: GenContext, _: &'a Cell, _: &mut Vec) - where + fn mark_non_var( + &mut self, + _: Level, + _: GenContext, + _: &'a Cell, + _: &mut Vec, + ) where Target: CompilationTarget<'a>; fn mark_reserved_var( &mut self, @@ -28,8 +34,14 @@ pub trait Allocator<'a> { _: bool, ) where Target: CompilationTarget<'a>; - fn mark_var(&mut self, _: Rc, _: Level, _: &'a Cell, _: GenContext, _: &mut Vec) - where + fn mark_var( + &mut self, + _: Rc, + _: Level, + _: &'a Cell, + _: GenContext, + _: &mut Vec, + ) where Target: CompilationTarget<'a>; fn reset(&mut self); @@ -47,7 +59,7 @@ pub trait Allocator<'a> { fn drain_var_data( &mut self, vs: VariableFixtures<'a>, - num_of_chunks: usize + num_of_chunks: usize, ) -> VariableFixtures<'a> { let mut perm_vs = VariableFixtures::new(); diff --git a/src/arithmetic.rs b/src/arithmetic.rs index 1231dfa6..c3492f31 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -1,4 +1,5 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::{atom, clause_name}; use crate::clause_types::*; use crate::fixtures::*; @@ -267,9 +268,7 @@ impl<'a> ArithmeticEvaluator<'a> { fn push_constant(&mut self, c: &Constant) -> Result<(), ArithmeticError> { match c { - &Constant::Fixnum(n) => self - .interm - .push(ArithmeticTerm::Number(Number::Fixnum(n))), + &Constant::Fixnum(n) => self.interm.push(ArithmeticTerm::Number(Number::Fixnum(n))), &Constant::Integer(ref n) => self .interm .push(ArithmeticTerm::Number(Number::Integer(n.clone()))), @@ -326,17 +325,11 @@ impl<'a> ArithmeticEvaluator<'a> { // integer division rounding function -- 9.1.3.1. pub fn rnd_i<'a>(n: &'a Number) -> RefOrOwned<'a, Number> { match n { - &Number::Integer(_) => { - RefOrOwned::Borrowed(n) - } - &Number::Float(OrderedFloat(f)) => { - RefOrOwned::Owned(Number::from( - Integer::from_f64(f.floor()).unwrap_or_else(|| Integer::from(0)) - )) - } - &Number::Fixnum(n) => { - RefOrOwned::Owned(Number::from(n)) - } + &Number::Integer(_) => RefOrOwned::Borrowed(n), + &Number::Float(OrderedFloat(f)) => RefOrOwned::Owned(Number::from( + Integer::from_f64(f.floor()).unwrap_or_else(|| Integer::from(0)), + )), + &Number::Fixnum(n) => RefOrOwned::Owned(Number::from(n)), &Number::Rational(ref r) => { let r_ref = r.fract_floor_ref(); let (mut fract, mut floor) = (Rational::new(), Integer::new()); @@ -432,31 +425,31 @@ impl Add for Number { Number::from(Integer::from(n1) + Integer::from(n2)) }) } - (Number::Fixnum(n1), Number::Integer(n2)) | - (Number::Integer(n2), Number::Fixnum(n1)) => { + (Number::Fixnum(n1), Number::Integer(n2)) + | (Number::Integer(n2), Number::Fixnum(n1)) => { Ok(Number::from(Integer::from(n1) + &*n2)) } - (Number::Fixnum(n1), Number::Rational(n2)) | - (Number::Rational(n2), Number::Fixnum(n1)) => { + (Number::Fixnum(n1), Number::Rational(n2)) + | (Number::Rational(n2), Number::Fixnum(n1)) => { Ok(Number::from(Rational::from(n1) + &*n2)) } - (Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) | - (Number::Float(OrderedFloat(n2)), Number::Fixnum(n1)) => { + (Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) + | (Number::Float(OrderedFloat(n2)), Number::Fixnum(n1)) => { Ok(Number::Float(add_f(float_fn_to_f(n1)?, n2)?)) } (Number::Integer(n1), Number::Integer(n2)) => { Ok(Number::from(Integer::from(&*n1) + &*n2)) // add_i } (Number::Integer(n1), Number::Float(OrderedFloat(n2))) - | (Number::Float(OrderedFloat(n2)), Number::Integer(n1)) => { + | (Number::Float(OrderedFloat(n2)), Number::Integer(n1)) => { Ok(Number::Float(add_f(float_i_to_f(&n1)?, n2)?)) } (Number::Integer(n1), Number::Rational(n2)) - | (Number::Rational(n2), Number::Integer(n1)) => { + | (Number::Rational(n2), Number::Integer(n1)) => { Ok(Number::from(Rational::from(&*n1) + &*n2)) } (Number::Rational(n1), Number::Float(OrderedFloat(n2))) - | (Number::Float(OrderedFloat(n2)), Number::Rational(n1)) => { + | (Number::Float(OrderedFloat(n2)), Number::Rational(n1)) => { Ok(Number::Float(add_f(float_r_to_f(&n1)?, n2)?)) } (Number::Float(OrderedFloat(f1)), Number::Float(OrderedFloat(f2))) => { @@ -474,12 +467,13 @@ impl Neg for Number { fn neg(self) -> Self::Output { match self { - Number::Fixnum(n) => + Number::Fixnum(n) => { if let Some(n) = n.checked_neg() { Number::Fixnum(n) } else { Number::from(-Integer::from(n)) } + } Number::Integer(n) => Number::Integer(Rc::new(-Integer::from(&*n))), Number::Float(OrderedFloat(f)) => Number::Float(OrderedFloat(-f)), Number::Rational(r) => Number::Rational(Rc::new(-Rational::from(&*r))), @@ -507,16 +501,16 @@ impl Mul for Number { Number::from(Integer::from(n1) * Integer::from(n2)) }) } - (Number::Fixnum(n1), Number::Integer(n2)) | - (Number::Integer(n2), Number::Fixnum(n1)) => { + (Number::Fixnum(n1), Number::Integer(n2)) + | (Number::Integer(n2), Number::Fixnum(n1)) => { Ok(Number::from(Integer::from(n1) * &*n2)) } - (Number::Fixnum(n1), Number::Rational(n2)) | - (Number::Rational(n2), Number::Fixnum(n1)) => { + (Number::Fixnum(n1), Number::Rational(n2)) + | (Number::Rational(n2), Number::Fixnum(n1)) => { Ok(Number::from(Rational::from(n1) * &*n2)) } - (Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) | - (Number::Float(OrderedFloat(n2)), Number::Fixnum(n1)) => { + (Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) + | (Number::Float(OrderedFloat(n2)), Number::Fixnum(n1)) => { Ok(Number::Float(mul_f(float_fn_to_f(n1)?, n2)?)) } (Number::Integer(n1), Number::Integer(n2)) => { @@ -549,72 +543,50 @@ impl Div for Number { fn div(self, rhs: Number) -> Self::Output { match (self, rhs) { - (Number::Fixnum(n1), Number::Fixnum(n2)) => { - Ok(Number::Float(div_f( - float_fn_to_f(n1)?, - float_fn_to_f(n2)?, - )?)) - } - (Number::Fixnum(n1), Number::Integer(n2)) => { - Ok(Number::Float(div_f( - float_fn_to_f(n1)?, - float_i_to_f(&n2)?, - )?)) - } - (Number::Integer(n1), Number::Fixnum(n2)) => { - Ok(Number::Float(div_f( - float_i_to_f(&n1)?, - float_fn_to_f(n2)?, - )?)) - } - (Number::Fixnum(n1), Number::Rational(n2)) => { - Ok(Number::Float(div_f( - float_fn_to_f(n1)?, - float_r_to_f(&n2)?, - )?)) - } - (Number::Rational(n1), Number::Fixnum(n2)) => { - Ok(Number::Float(div_f( - float_r_to_f(&n1)?, - float_fn_to_f(n2)?, - )?)) - } + (Number::Fixnum(n1), Number::Fixnum(n2)) => Ok(Number::Float(div_f( + float_fn_to_f(n1)?, + float_fn_to_f(n2)?, + )?)), + (Number::Fixnum(n1), Number::Integer(n2)) => Ok(Number::Float(div_f( + float_fn_to_f(n1)?, + float_i_to_f(&n2)?, + )?)), + (Number::Integer(n1), Number::Fixnum(n2)) => Ok(Number::Float(div_f( + float_i_to_f(&n1)?, + float_fn_to_f(n2)?, + )?)), + (Number::Fixnum(n1), Number::Rational(n2)) => Ok(Number::Float(div_f( + float_fn_to_f(n1)?, + float_r_to_f(&n2)?, + )?)), + (Number::Rational(n1), Number::Fixnum(n2)) => Ok(Number::Float(div_f( + float_r_to_f(&n1)?, + float_fn_to_f(n2)?, + )?)), (Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) => { - Ok(Number::Float(div_f( - float_fn_to_f(n1)?, - n2, - )?)) + Ok(Number::Float(div_f(float_fn_to_f(n1)?, n2)?)) } (Number::Float(OrderedFloat(n1)), Number::Fixnum(n2)) => { - Ok(Number::Float(div_f( - n1, - float_fn_to_f(n2)?, - )?)) - } - (Number::Integer(n1), Number::Integer(n2)) => { - Ok(Number::Float(div_f( - float_i_to_f(&n1)?, - float_i_to_f(&n2)?, - )?)) + Ok(Number::Float(div_f(n1, float_fn_to_f(n2)?)?)) } + (Number::Integer(n1), Number::Integer(n2)) => Ok(Number::Float(div_f( + float_i_to_f(&n1)?, + float_i_to_f(&n2)?, + )?)), (Number::Integer(n1), Number::Float(OrderedFloat(n2))) => { Ok(Number::Float(div_f(float_i_to_f(&n1)?, n2)?)) } (Number::Float(OrderedFloat(n2)), Number::Integer(n1)) => { Ok(Number::Float(div_f(n2, float_i_to_f(&n1)?)?)) } - (Number::Integer(n1), Number::Rational(n2)) => { - Ok(Number::Float(div_f( - float_i_to_f(&n1)?, - float_r_to_f(&n2)?, - )?)) - } - (Number::Rational(n2), Number::Integer(n1)) => { - Ok(Number::Float(div_f( - float_r_to_f(&n2)?, - float_i_to_f(&n1)?, - )?)) - } + (Number::Integer(n1), Number::Rational(n2)) => Ok(Number::Float(div_f( + float_i_to_f(&n1)?, + float_r_to_f(&n2)?, + )?)), + (Number::Rational(n2), Number::Integer(n1)) => Ok(Number::Float(div_f( + float_r_to_f(&n2)?, + float_i_to_f(&n1)?, + )?)), (Number::Rational(n1), Number::Float(OrderedFloat(n2))) => { Ok(Number::Float(div_f(float_r_to_f(&n1)?, n2)?)) } @@ -727,12 +699,8 @@ impl<'a> TryFrom<(Addr, &'a Heap)> for Number { fn try_from((addr, heap): (Addr, &'a Heap)) -> Result { match addr { - Addr::Fixnum(n) => { - Ok(Number::from(n)) - } - Addr::Float(n) => { - Ok(Number::Float(n)) - } + Addr::Fixnum(n) => Ok(Number::from(n)), + Addr::Float(n) => Ok(Number::Float(n)), Addr::Usize(n) => { if let Ok(n) = isize::try_from(n) { Ok(Number::from(n)) @@ -740,12 +708,8 @@ impl<'a> TryFrom<(Addr, &'a Heap)> for Number { Ok(Number::from(Integer::from(n))) } } - Addr::Con(h) => { - Number::try_from(&heap[h]) - } - _ => { - Err(()) - } + Addr::Con(h) => Number::try_from(&heap[h]), + _ => Err(()), } } } @@ -755,35 +719,21 @@ impl<'a> TryFrom<&'a HeapCellValue> for Number { fn try_from(value: &'a HeapCellValue) -> Result { match value { - HeapCellValue::Addr(addr) => { - match addr { - &Addr::Fixnum(n) => { + HeapCellValue::Addr(addr) => match addr { + &Addr::Fixnum(n) => Ok(Number::from(n)), + &Addr::Float(n) => Ok(Number::Float(n)), + &Addr::Usize(n) => { + if let Ok(n) = isize::try_from(n) { Ok(Number::from(n)) - } - &Addr::Float(n) => { - Ok(Number::Float(n)) - } - &Addr::Usize(n) => { - if let Ok(n) = isize::try_from(n) { - Ok(Number::from(n)) - } else { - Ok(Number::from(Integer::from(n))) - } - } - _ => { - Err(()) + } else { + Ok(Number::from(Integer::from(n))) } } - } - HeapCellValue::Integer(n) => { - Ok(Number::Integer(n.clone())) - } - HeapCellValue::Rational(n) => { - Ok(Number::Rational(n.clone())) - } - _ => { - Err(()) - } + _ => Err(()), + }, + HeapCellValue::Integer(n) => Ok(Number::Integer(n.clone())), + HeapCellValue::Rational(n) => Ok(Number::Rational(n.clone())), + _ => Err(()), } } } diff --git a/src/clause_types.rs b/src/clause_types.rs index 6f412b78..335e24f8 100644 --- a/src/clause_types.rs +++ b/src/clause_types.rs @@ -1,10 +1,11 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::{clause_name, temp_v}; use crate::forms::Number; use crate::machine::machine_indices::*; use crate::rug::rand::RandState; -use crate::ref_thread_local::RefThreadLocal; +use crate::ref_thread_local::{ref_thread_local, RefThreadLocal}; use std::collections::BTreeMap; @@ -322,7 +323,9 @@ impl SystemClauseType { &SystemClauseType::ClearAttributeGoals => clause_name!("$clear_attribute_goals"), &SystemClauseType::CloneAttributeGoals => clause_name!("$clone_attribute_goals"), &SystemClauseType::CodesToNumber => clause_name!("$codes_to_number"), - &SystemClauseType::CopyTermWithoutAttrVars => clause_name!("$copy_term_without_attr_vars"), + &SystemClauseType::CopyTermWithoutAttrVars => { + clause_name!("$copy_term_without_attr_vars") + } &SystemClauseType::CreatePartialString => clause_name!("$create_partial_string"), &SystemClauseType::CurrentInput => clause_name!("$current_input"), &SystemClauseType::CurrentHostname => clause_name!("$current_hostname"), @@ -337,58 +340,70 @@ impl SystemClauseType { &SystemClauseType::WorkingDirectory => clause_name!("$working_directory"), &SystemClauseType::PathCanonical => clause_name!("$path_canonical"), &SystemClauseType::FileTime => clause_name!("$file_time"), - &SystemClauseType::REPL(REPLCodePtr::AddDynamicPredicate) => - clause_name!("$add_dynamic_predicate"), - &SystemClauseType::REPL(REPLCodePtr::AddGoalExpansionClause) => - clause_name!("$add_goal_expansion_clause"), - &SystemClauseType::REPL(REPLCodePtr::AddTermExpansionClause) => - clause_name!("$add_term_expansion_clause"), - &SystemClauseType::REPL(REPLCodePtr::ClauseToEvacuable) => - clause_name!("$clause_to_evacuable"), - &SystemClauseType::REPL(REPLCodePtr::ConcludeLoad) => - clause_name!("$conclude_load"), - &SystemClauseType::REPL(REPLCodePtr::DeclareModule) => - clause_name!("$declare_module"), - &SystemClauseType::REPL(REPLCodePtr::LoadCompiledLibrary) => - clause_name!("$load_compiled_library"), - &SystemClauseType::REPL(REPLCodePtr::PushLoadStatePayload) => - clause_name!("$push_load_state_payload"), - &SystemClauseType::REPL(REPLCodePtr::Asserta) => - clause_name!("$asserta"), - &SystemClauseType::REPL(REPLCodePtr::Assertz) => - clause_name!("$assertz"), - &SystemClauseType::REPL(REPLCodePtr::Retract) => - clause_name!("$retract_clause"), - &SystemClauseType::REPL(REPLCodePtr::UseModule) => - clause_name!("$use_module"), - &SystemClauseType::REPL(REPLCodePtr::PushLoadContext) => - clause_name!("$push_load_context"), - &SystemClauseType::REPL(REPLCodePtr::PopLoadContext) => - clause_name!("$pop_load_context"), - &SystemClauseType::REPL(REPLCodePtr::PopLoadStatePayload) => - clause_name!("$pop_load_state_payload"), - &SystemClauseType::REPL(REPLCodePtr::LoadContextSource) => - clause_name!("$prolog_lc_source"), - &SystemClauseType::REPL(REPLCodePtr::LoadContextFile) => - clause_name!("$prolog_lc_file"), - &SystemClauseType::REPL(REPLCodePtr::LoadContextDirectory) => - clause_name!("$prolog_lc_dir"), - &SystemClauseType::REPL(REPLCodePtr::LoadContextModule) => - clause_name!("$prolog_lc_module"), - &SystemClauseType::REPL(REPLCodePtr::LoadContextStream) => - clause_name!("$prolog_lc_stream"), - &SystemClauseType::REPL(REPLCodePtr::MetaPredicateProperty) => - clause_name!("$cpp_meta_predicate_property"), - &SystemClauseType::REPL(REPLCodePtr::BuiltInProperty) => - clause_name!("$cpp_built_in_property"), - &SystemClauseType::REPL(REPLCodePtr::DynamicProperty) => - clause_name!("$cpp_dynamic_property"), - &SystemClauseType::REPL(REPLCodePtr::MultifileProperty) => - clause_name!("$cpp_multifile_property"), - &SystemClauseType::REPL(REPLCodePtr::DiscontiguousProperty) => - clause_name!("$cpp_discontiguous_property"), - &SystemClauseType::REPL(REPLCodePtr::AbolishClause) => - clause_name!("$abolish_clause"), + &SystemClauseType::REPL(REPLCodePtr::AddDynamicPredicate) => { + clause_name!("$add_dynamic_predicate") + } + &SystemClauseType::REPL(REPLCodePtr::AddGoalExpansionClause) => { + clause_name!("$add_goal_expansion_clause") + } + &SystemClauseType::REPL(REPLCodePtr::AddTermExpansionClause) => { + clause_name!("$add_term_expansion_clause") + } + &SystemClauseType::REPL(REPLCodePtr::ClauseToEvacuable) => { + clause_name!("$clause_to_evacuable") + } + &SystemClauseType::REPL(REPLCodePtr::ConcludeLoad) => clause_name!("$conclude_load"), + &SystemClauseType::REPL(REPLCodePtr::DeclareModule) => clause_name!("$declare_module"), + &SystemClauseType::REPL(REPLCodePtr::LoadCompiledLibrary) => { + clause_name!("$load_compiled_library") + } + &SystemClauseType::REPL(REPLCodePtr::PushLoadStatePayload) => { + clause_name!("$push_load_state_payload") + } + &SystemClauseType::REPL(REPLCodePtr::Asserta) => clause_name!("$asserta"), + &SystemClauseType::REPL(REPLCodePtr::Assertz) => clause_name!("$assertz"), + &SystemClauseType::REPL(REPLCodePtr::Retract) => clause_name!("$retract_clause"), + &SystemClauseType::REPL(REPLCodePtr::UseModule) => clause_name!("$use_module"), + &SystemClauseType::REPL(REPLCodePtr::PushLoadContext) => { + clause_name!("$push_load_context") + } + &SystemClauseType::REPL(REPLCodePtr::PopLoadContext) => { + clause_name!("$pop_load_context") + } + &SystemClauseType::REPL(REPLCodePtr::PopLoadStatePayload) => { + clause_name!("$pop_load_state_payload") + } + &SystemClauseType::REPL(REPLCodePtr::LoadContextSource) => { + clause_name!("$prolog_lc_source") + } + &SystemClauseType::REPL(REPLCodePtr::LoadContextFile) => { + clause_name!("$prolog_lc_file") + } + &SystemClauseType::REPL(REPLCodePtr::LoadContextDirectory) => { + clause_name!("$prolog_lc_dir") + } + &SystemClauseType::REPL(REPLCodePtr::LoadContextModule) => { + clause_name!("$prolog_lc_module") + } + &SystemClauseType::REPL(REPLCodePtr::LoadContextStream) => { + clause_name!("$prolog_lc_stream") + } + &SystemClauseType::REPL(REPLCodePtr::MetaPredicateProperty) => { + clause_name!("$cpp_meta_predicate_property") + } + &SystemClauseType::REPL(REPLCodePtr::BuiltInProperty) => { + clause_name!("$cpp_built_in_property") + } + &SystemClauseType::REPL(REPLCodePtr::DynamicProperty) => { + clause_name!("$cpp_dynamic_property") + } + &SystemClauseType::REPL(REPLCodePtr::MultifileProperty) => { + clause_name!("$cpp_multifile_property") + } + &SystemClauseType::REPL(REPLCodePtr::DiscontiguousProperty) => { + clause_name!("$cpp_discontiguous_property") + } + &SystemClauseType::REPL(REPLCodePtr::AbolishClause) => clause_name!("$abolish_clause"), &SystemClauseType::Close => clause_name!("$close"), &SystemClauseType::CopyToLiftedHeap => clause_name!("$copy_to_lh"), &SystemClauseType::DeleteAttribute => clause_name!("$del_attr_non_head"), @@ -397,8 +412,9 @@ impl SystemClauseType { &SystemClauseType::EnqueueAttributeGoal => clause_name!("$enqueue_attribute_goal"), &SystemClauseType::EnqueueAttributedVar => clause_name!("$enqueue_attr_var"), &SystemClauseType::FetchGlobalVar => clause_name!("$fetch_global_var"), - &SystemClauseType::FetchGlobalVarWithOffset => - clause_name!("$fetch_global_var_with_offset"), + &SystemClauseType::FetchGlobalVarWithOffset => { + clause_name!("$fetch_global_var_with_offset") + } &SystemClauseType::FirstStream => clause_name!("$first_stream"), &SystemClauseType::FlushOutput => clause_name!("$flush_output"), &SystemClauseType::GetByte => clause_name!("$get_byte"), @@ -424,13 +440,13 @@ impl SystemClauseType { clause_name!("$get_lh_from_offset_diff") } &SystemClauseType::GetBValue => clause_name!("$get_b_value"), -// &SystemClauseType::GetClause => clause_name!("$get_clause"), + // &SystemClauseType::GetClause => clause_name!("$get_clause"), &SystemClauseType::GetNextDBRef => clause_name!("$get_next_db_ref"), &SystemClauseType::GetNextOpDBRef => clause_name!("$get_next_op_db_ref"), &SystemClauseType::LookupDBRef => clause_name!("$lookup_db_ref"), &SystemClauseType::LookupOpDBRef => clause_name!("$lookup_op_db_ref"), &SystemClauseType::GetDoubleQuotes => clause_name!("$get_double_quotes"), -// &SystemClauseType::GetModuleClause => clause_name!("$get_module_clause"), + // &SystemClauseType::GetModuleClause => clause_name!("$get_module_clause"), &SystemClauseType::GetSCCCleaner => clause_name!("$get_scc_cleaner"), &SystemClauseType::Halt => clause_name!("$halt"), &SystemClauseType::HeadIsDynamic => clause_name!("$head_is_dynamic"), @@ -455,7 +471,7 @@ impl SystemClauseType { // &SystemClauseType::ModuleAssertDynamicPredicateToBack => { // clause_name!("$module_assertz") // } -// &SystemClauseType::ModuleHeadIsDynamic => clause_name!("$module_head_is_dynamic"), + // &SystemClauseType::ModuleHeadIsDynamic => clause_name!("$module_head_is_dynamic"), &SystemClauseType::ModuleExists => clause_name!("$module_exists"), &SystemClauseType::NextStream => clause_name!("$next_stream"), &SystemClauseType::NoSuchPredicate => clause_name!("$no_such_predicate"), @@ -507,7 +523,9 @@ impl SystemClauseType { &SystemClauseType::ReadTerm => clause_name!("$read_term"), &SystemClauseType::ReadTermFromChars => clause_name!("$read_term_from_chars"), &SystemClauseType::ResetGlobalVarAtKey => clause_name!("$reset_global_var_at_key"), - &SystemClauseType::ResetGlobalVarAtOffset => clause_name!("$reset_global_var_at_offset"), + &SystemClauseType::ResetGlobalVarAtOffset => { + clause_name!("$reset_global_var_at_offset") + } &SystemClauseType::ResetBlock => clause_name!("$reset_block"), &SystemClauseType::ResetContinuationMarker => clause_name!("$reset_cont_marker"), &SystemClauseType::ReturnFromVerifyAttr => clause_name!("$return_from_verify_attr"), @@ -521,7 +539,9 @@ impl SystemClauseType { &SystemClauseType::SocketServerAccept => clause_name!("$socket_server_accept"), &SystemClauseType::SocketServerClose => clause_name!("$socket_server_close"), &SystemClauseType::Succeed => clause_name!("$succeed"), - &SystemClauseType::TermAttributedVariables => clause_name!("$term_attributed_variables"), + &SystemClauseType::TermAttributedVariables => { + clause_name!("$term_attributed_variables") + } &SystemClauseType::TermVariables => clause_name!("$term_variables"), &SystemClauseType::TruncateLiftedHeapTo => clause_name!("$truncate_lh_to"), &SystemClauseType::UnifyWithOccursCheck => clause_name!("$unify_with_occurs_check"), @@ -542,7 +562,9 @@ impl SystemClauseType { &SystemClauseType::Ed25519Sign => clause_name!("$ed25519_sign"), &SystemClauseType::Ed25519Verify => clause_name!("$ed25519_verify"), &SystemClauseType::Ed25519NewKeyPair => clause_name!("$ed25519_new_keypair"), - &SystemClauseType::Ed25519KeyPairPublicKey => clause_name!("$ed25519_keypair_public_key"), + &SystemClauseType::Ed25519KeyPairPublicKey => { + clause_name!("$ed25519_keypair_public_key") + } &SystemClauseType::Curve25519ScalarMult => clause_name!("$curve25519_scalar_mult"), &SystemClauseType::LoadHTML => clause_name!("$load_html"), &SystemClauseType::LoadXML => clause_name!("$load_xml"), @@ -556,14 +578,16 @@ impl SystemClauseType { pub fn from(name: &str, arity: usize) -> Option { match (name, arity) { - ("$abolish_clause", 3) => - Some(SystemClauseType::REPL(REPLCodePtr::AbolishClause)), - ("$add_dynamic_predicate", 3) => - Some(SystemClauseType::REPL(REPLCodePtr::AddDynamicPredicate)), - ("$add_goal_expansion_clause", 4) => - Some(SystemClauseType::REPL(REPLCodePtr::AddGoalExpansionClause)), - ("$add_term_expansion_clause", 3) => - Some(SystemClauseType::REPL(REPLCodePtr::AddTermExpansionClause)), + ("$abolish_clause", 3) => Some(SystemClauseType::REPL(REPLCodePtr::AbolishClause)), + ("$add_dynamic_predicate", 3) => { + Some(SystemClauseType::REPL(REPLCodePtr::AddDynamicPredicate)) + } + ("$add_goal_expansion_clause", 4) => { + Some(SystemClauseType::REPL(REPLCodePtr::AddGoalExpansionClause)) + } + ("$add_term_expansion_clause", 3) => { + Some(SystemClauseType::REPL(REPLCodePtr::AddTermExpansionClause)) + } ("$atom_chars", 2) => Some(SystemClauseType::AtomChars), ("$atom_codes", 2) => Some(SystemClauseType::AtomCodes), ("$atom_length", 2) => Some(SystemClauseType::AtomLength), @@ -602,7 +626,9 @@ impl SystemClauseType { ("$peek_code", 2) => Some(SystemClauseType::PeekCode), ("$is_partial_string", 1) => Some(SystemClauseType::IsPartialString), ("$fetch_global_var", 2) => Some(SystemClauseType::FetchGlobalVar), - ("$fetch_global_var_with_offset", 3) => Some(SystemClauseType::FetchGlobalVarWithOffset), + ("$fetch_global_var_with_offset", 3) => { + Some(SystemClauseType::FetchGlobalVarWithOffset) + } ("$get_byte", 2) => Some(SystemClauseType::GetByte), ("$get_char", 2) => Some(SystemClauseType::GetChar), ("$get_n_chars", 3) => Some(SystemClauseType::GetNChars), @@ -611,18 +637,10 @@ impl SystemClauseType { ("$points_to_cont_reset_marker", 1) => { Some(SystemClauseType::PointsToContinuationResetMarker) } - ("$put_byte", 2) => { - Some(SystemClauseType::PutByte) - } - ("$put_char", 2) => { - Some(SystemClauseType::PutChar) - } - ("$put_chars", 2) => { - Some(SystemClauseType::PutChars) - } - ("$put_code", 2) => { - Some(SystemClauseType::PutCode) - } + ("$put_byte", 2) => Some(SystemClauseType::PutByte), + ("$put_char", 2) => Some(SystemClauseType::PutChar), + ("$put_chars", 2) => Some(SystemClauseType::PutChars), + ("$put_code", 2) => Some(SystemClauseType::PutCode), ("$reset_attr_var_state", 0) => Some(SystemClauseType::ResetAttrVarState), ("$truncate_if_no_lh_growth", 1) => { Some(SystemClauseType::TruncateIfNoLiftedHeapGrowth) @@ -691,7 +709,9 @@ impl SystemClauseType { ("$socket_server_accept", 7) => Some(SystemClauseType::SocketServerAccept), ("$socket_server_close", 1) => Some(SystemClauseType::SocketServerClose), ("$store_global_var", 2) => Some(SystemClauseType::StoreGlobalVar), - ("$store_global_var_with_offset", 2) => Some(SystemClauseType::StoreGlobalVarWithOffset), + ("$store_global_var_with_offset", 2) => { + Some(SystemClauseType::StoreGlobalVarWithOffset) + } ("$term_attributed_variables", 2) => Some(SystemClauseType::TermAttributedVariables), ("$term_variables", 2) => Some(SystemClauseType::TermVariables), ("$truncate_lh_to", 1) => Some(SystemClauseType::TruncateLiftedHeapTo), @@ -708,12 +728,18 @@ impl SystemClauseType { ("$working_directory", 2) => Some(SystemClauseType::WorkingDirectory), ("$path_canonical", 2) => Some(SystemClauseType::PathCanonical), ("$file_time", 3) => Some(SystemClauseType::FileTime), - ("$clause_to_evacuable", 3) => Some(SystemClauseType::REPL(REPLCodePtr::ClauseToEvacuable)), + ("$clause_to_evacuable", 3) => { + Some(SystemClauseType::REPL(REPLCodePtr::ClauseToEvacuable)) + } ("$conclude_load", 1) => Some(SystemClauseType::REPL(REPLCodePtr::ConcludeLoad)), ("$use_module", 3) => Some(SystemClauseType::REPL(REPLCodePtr::UseModule)), ("$declare_module", 3) => Some(SystemClauseType::REPL(REPLCodePtr::DeclareModule)), - ("$load_compiled_library", 2) => Some(SystemClauseType::REPL(REPLCodePtr::LoadCompiledLibrary)), - ("$push_load_state_payload", 1) => Some(SystemClauseType::REPL(REPLCodePtr::PushLoadStatePayload)), + ("$load_compiled_library", 2) => { + Some(SystemClauseType::REPL(REPLCodePtr::LoadCompiledLibrary)) + } + ("$push_load_state_payload", 1) => { + Some(SystemClauseType::REPL(REPLCodePtr::PushLoadStatePayload)) + } ("$asserta", 5) => Some(SystemClauseType::REPL(REPLCodePtr::Asserta)), ("$assertz", 5) => Some(SystemClauseType::REPL(REPLCodePtr::Assertz)), ("$retract_clause", 4) => Some(SystemClauseType::REPL(REPLCodePtr::Retract)), @@ -742,18 +768,38 @@ impl SystemClauseType { ("$chars_base64", 4) => Some(SystemClauseType::CharsBase64), ("$load_library_as_stream", 3) => Some(SystemClauseType::LoadLibraryAsStream), ("$push_load_context", 2) => Some(SystemClauseType::REPL(REPLCodePtr::PushLoadContext)), - ("$pop_load_state_payload", 1) => Some(SystemClauseType::REPL(REPLCodePtr::PopLoadStatePayload)), + ("$pop_load_state_payload", 1) => { + Some(SystemClauseType::REPL(REPLCodePtr::PopLoadStatePayload)) + } ("$pop_load_context", 0) => Some(SystemClauseType::REPL(REPLCodePtr::PopLoadContext)), - ("$prolog_lc_source", 1) => Some(SystemClauseType::REPL(REPLCodePtr::LoadContextSource)), + ("$prolog_lc_source", 1) => { + Some(SystemClauseType::REPL(REPLCodePtr::LoadContextSource)) + } ("$prolog_lc_file", 1) => Some(SystemClauseType::REPL(REPLCodePtr::LoadContextFile)), - ("$prolog_lc_dir", 1) => Some(SystemClauseType::REPL(REPLCodePtr::LoadContextDirectory)), - ("$prolog_lc_module", 1) => Some(SystemClauseType::REPL(REPLCodePtr::LoadContextModule)), - ("$prolog_lc_stream", 1) => Some(SystemClauseType::REPL(REPLCodePtr::LoadContextStream)), - ("$cpp_meta_predicate_property", 4) => Some(SystemClauseType::REPL(REPLCodePtr::MetaPredicateProperty)), - ("$cpp_built_in_property", 2) => Some(SystemClauseType::REPL(REPLCodePtr::BuiltInProperty)), - ("$cpp_dynamic_property", 3) => Some(SystemClauseType::REPL(REPLCodePtr::DynamicProperty)), - ("$cpp_multifile_property", 3) => Some(SystemClauseType::REPL(REPLCodePtr::MultifileProperty)), - ("$cpp_discontiguous_property", 3) => Some(SystemClauseType::REPL(REPLCodePtr::DiscontiguousProperty)), + ("$prolog_lc_dir", 1) => { + Some(SystemClauseType::REPL(REPLCodePtr::LoadContextDirectory)) + } + ("$prolog_lc_module", 1) => { + Some(SystemClauseType::REPL(REPLCodePtr::LoadContextModule)) + } + ("$prolog_lc_stream", 1) => { + Some(SystemClauseType::REPL(REPLCodePtr::LoadContextStream)) + } + ("$cpp_meta_predicate_property", 4) => { + Some(SystemClauseType::REPL(REPLCodePtr::MetaPredicateProperty)) + } + ("$cpp_built_in_property", 2) => { + Some(SystemClauseType::REPL(REPLCodePtr::BuiltInProperty)) + } + ("$cpp_dynamic_property", 3) => { + Some(SystemClauseType::REPL(REPLCodePtr::DynamicProperty)) + } + ("$cpp_multifile_property", 3) => { + Some(SystemClauseType::REPL(REPLCodePtr::MultifileProperty)) + } + ("$cpp_discontiguous_property", 3) => { + Some(SystemClauseType::REPL(REPLCodePtr::DiscontiguousProperty)) + } _ => None, } } @@ -832,10 +878,10 @@ impl ClauseType { match self { &ClauseType::Op(_, ref spec, _) => Some(spec.clone()), &ClauseType::Inlined(InlinedClauseType::CompareNumber(..)) - | &ClauseType::BuiltIn(BuiltInClauseType::Is(..)) - | &ClauseType::BuiltIn(BuiltInClauseType::CompareTerm(_)) - | &ClauseType::BuiltIn(BuiltInClauseType::NotEq) - | &ClauseType::BuiltIn(BuiltInClauseType::Eq) => Some(SharedOpDesc::new(700, XFX)), + | &ClauseType::BuiltIn(BuiltInClauseType::Is(..)) + | &ClauseType::BuiltIn(BuiltInClauseType::CompareTerm(_)) + | &ClauseType::BuiltIn(BuiltInClauseType::NotEq) + | &ClauseType::BuiltIn(BuiltInClauseType::Eq) => Some(SharedOpDesc::new(700, XFX)), _ => None, } } diff --git a/src/codegen.rs b/src/codegen.rs index f2a1c5ab..46e2ea82 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -1,6 +1,7 @@ /// Code generation to WAM-like instructions. use crate::prolog_parser_rebis::ast::*; use crate::prolog_parser_rebis::tabled_rc::TabledData; +use crate::prolog_parser_rebis::{perm_v, temp_v}; use crate::allocator::*; use crate::arithmetic::*; @@ -66,18 +67,14 @@ impl<'a> ConjunctInfo<'a> { self.has_deep_cut as usize } - fn mark_unsafe_vars( - &self, - mut unsafe_var_marker: UnsafeVarMarker, - code: &mut Code, - ) { + fn mark_unsafe_vars(&self, mut unsafe_var_marker: UnsafeVarMarker, code: &mut Code) { if code.is_empty() { return; } let mut code_index = 0; - for phase in 0 .. { + for phase in 0.. { while let Line::Query(ref query_instr) = &code[code_index] { if !unsafe_var_marker.mark_safe_vars(query_instr) { unsafe_var_marker.mark_phase(query_instr, phase); @@ -95,7 +92,7 @@ impl<'a> ConjunctInfo<'a> { code_index = 0; - for phase in 0 .. { + for phase in 0.. { while let Line::Query(ref mut query_instr) = &mut code[code_index] { unsafe_var_marker.mark_unsafe_vars(query_instr, phase); code_index += 1; @@ -173,7 +170,8 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { code: &mut Code, ) -> RegType { let mut target = Vec::new(); - self.marker.mark_var(name, Level::Shallow, vr, term_loc, &mut target); + self.marker + .mark_var(name, Level::Shallow, vr, term_loc, &mut target); if !target.is_empty() { code.extend(target.into_iter().map(Line::Query)); @@ -191,9 +189,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { code: &mut Code, ) -> RegType { match self.marker.bindings().get(&name) { - Some(&VarData::Temp(_, t, _)) if t != 0 => { - RegType::Temp(t) - } + Some(&VarData::Temp(_, t, _)) if t != 0 => RegType::Temp(t), Some(&VarData::Perm(p)) if p != 0 => { if let GenContext::Last(_) = term_loc { self.mark_var_in_non_callable(name.clone(), term_loc, vr, code); @@ -202,9 +198,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { RegType::Perm(p) } } - _ => { - self.mark_var_in_non_callable(name, term_loc, vr, code) - } + _ => self.mark_var_in_non_callable(name, term_loc, vr, code), } } @@ -231,7 +225,8 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { target: &mut Vec, ) { if is_exposed || self.get_var_count(var.as_ref()) > 1 { - self.marker.mark_var(var.clone(), Level::Deep, cell, term_loc, target); + self.marker + .mark_var(var.clone(), Level::Deep, cell, term_loc, target); } else { Self::add_or_increment_void_instr(target); } @@ -252,7 +247,8 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { Self::add_or_increment_void_instr(target); } &Term::Cons(ref cell, _, _) | &Term::Clause(ref cell, _, _, _) => { - self.marker.mark_non_var(Level::Deep, term_loc, cell, target); + self.marker + .mark_non_var(Level::Deep, term_loc, cell, target); target.push(Target::clause_arg_to_instr(cell.get())); } &Term::Constant(_, ref constant) => { @@ -264,7 +260,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { }; } - fn compile_target( + fn compile_target( &mut self, iter: Iter, term_loc: GenContext, @@ -334,13 +330,14 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { } } - self.marker.mark_var(var.clone(), lvl, cell, term_loc, &mut target); + self.marker + .mark_var(var.clone(), lvl, cell, term_loc, &mut target); } TermRef::Var(lvl @ Level::Shallow, cell, var) => { - self.marker.mark_var(var.clone(), lvl, cell, term_loc, &mut target); - } - _ => { + self.marker + .mark_var(var.clone(), lvl, cell, term_loc, &mut target); } + _ => {} }; } @@ -353,8 +350,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { while let Some((chunk_num, lt_arity, chunked_terms)) = iter.next() { for (i, chunked_term) in chunked_terms.iter().enumerate() { let term_loc = match chunked_term { - &ChunkedTerm::HeadClause(..) => - GenContext::Head, + &ChunkedTerm::HeadClause(..) => GenContext::Head, &ChunkedTerm::BodyTerm(_) => { if i < chunked_terms.len() - 1 { GenContext::Mid(chunk_num) @@ -391,8 +387,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { &QueryTerm::Clause(_, ref ct, ref terms, false) => { code.push(call_clause!(ct.clone(), terms.len(), pvs)); } - _ => { - } + _ => {} } } @@ -407,8 +402,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { &mut ControlInstruction::JmpBy(_, _, _, ref mut last_call) => { *last_call = true; } - &mut ControlInstruction::Proceed => { - } + &mut ControlInstruction::Proceed => {} _ => { dealloc_index += 1; } @@ -416,8 +410,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { Some(&mut Line::Cut(CutInstruction::Cut(_))) => { dealloc_index += 1; } - _ => { - } + _ => {} }; dealloc_index @@ -437,23 +430,17 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { let (mut lcode, at_1) = self.call_arith_eval(terms[0].as_ref(), 1)?; let (mut rcode, at_2) = self.call_arith_eval(terms[1].as_ref(), 2)?; - let at_1 = - if let &Term::Var(ref vr, ref name) = terms[0].as_ref() { - ArithmeticTerm::Reg( - self.mark_non_callable(name.clone(), 1, term_loc, vr, code) - ) - } else { - at_1.unwrap_or(interm!(1)) - }; + let at_1 = if let &Term::Var(ref vr, ref name) = terms[0].as_ref() { + ArithmeticTerm::Reg(self.mark_non_callable(name.clone(), 1, term_loc, vr, code)) + } else { + at_1.unwrap_or(interm!(1)) + }; - let at_2 = - if let &Term::Var(ref vr, ref name) = terms[1].as_ref() { - ArithmeticTerm::Reg( - self.mark_non_callable(name.clone(), 2, term_loc, vr, code) - ) - } else { - at_2.unwrap_or(interm!(2)) - }; + let at_2 = if let &Term::Var(ref vr, ref name) = terms[1].as_ref() { + ArithmeticTerm::Reg(self.mark_non_callable(name.clone(), 2, term_loc, vr, code)) + } else { + at_2.unwrap_or(interm!(2)) + }; code.append(&mut lcode); code.append(&mut rcode); @@ -461,9 +448,9 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { code.push(compare_number_instr!(cmp, at_1, at_2)); } &InlinedClauseType::IsAtom(..) => match terms[0].as_ref() { - &Term::Constant(_, Constant::Char(_)) | - &Term::Constant(_, Constant::EmptyList) | - &Term::Constant(_, Constant::Atom(..)) => { + &Term::Constant(_, Constant::Char(_)) + | &Term::Constant(_, Constant::EmptyList) + | &Term::Constant(_, Constant::Atom(..)) => { code.push(succeed!()); } &Term::Var(ref vr, ref name) => { @@ -528,11 +515,11 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { } }, &InlinedClauseType::IsNumber(..) => match terms[0].as_ref() { - &Term::Constant(_, Constant::Float(_)) | - &Term::Constant(_, Constant::Rational(_)) | - &Term::Constant(_, Constant::Integer(_)) | - &Term::Constant(_, Constant::Fixnum(_)) | - &Term::Constant(_, Constant::Usize(_)) => { + &Term::Constant(_, Constant::Float(_)) + | &Term::Constant(_, Constant::Rational(_)) + | &Term::Constant(_, Constant::Integer(_)) + | &Term::Constant(_, Constant::Fixnum(_)) + | &Term::Constant(_, Constant::Usize(_)) => { code.push(succeed!()); } &Term::Var(ref vr, ref name) => { @@ -558,9 +545,9 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { } }, &InlinedClauseType::IsInteger(..) => match terms[0].as_ref() { - &Term::Constant(_, Constant::Integer(_)) | - &Term::Constant(_, Constant::Fixnum(_)) | - &Term::Constant(_, Constant::Usize(_)) => { + &Term::Constant(_, Constant::Integer(_)) + | &Term::Constant(_, Constant::Fixnum(_)) + | &Term::Constant(_, Constant::Usize(_)) => { code.push(succeed!()); } &Term::Var(ref vr, ref name) => { @@ -615,14 +602,15 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { &Term::Var(ref vr, ref name) => { let mut target = vec![]; - self.marker.mark_var(name.clone(), Level::Shallow, vr, term_loc, &mut target); + self.marker + .mark_var(name.clone(), Level::Shallow, vr, term_loc, &mut target); if !target.is_empty() { code.extend(target.into_iter().map(Line::Query)); } } - &Term::Constant(_, ref c @ Constant::Integer(_)) | - &Term::Constant(_, ref c @ Constant::Fixnum(_)) => { + &Term::Constant(_, ref c @ Constant::Integer(_)) + | &Term::Constant(_, ref c @ Constant::Fixnum(_)) => { code.push(Line::Query(put_constant!( Level::Shallow, c.clone(), @@ -655,14 +643,11 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { } } - let at = - if let &Term::Var(ref vr, ref name) = terms[1].as_ref() { - ArithmeticTerm::Reg( - self.mark_non_callable(name.clone(), 2, term_loc, vr, code) - ) - } else { - at.unwrap_or(interm!(1)) - }; + let at = if let &Term::Var(ref vr, ref name) = terms[1].as_ref() { + ArithmeticTerm::Reg(self.mark_non_callable(name.clone(), 2, term_loc, vr, code)) + } else { + at.unwrap_or(interm!(1)) + }; Ok(if use_default_call_policy { code.push(is_call_by_default!(temp_v!(1), at)); @@ -721,24 +706,18 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { &QueryTerm::GetLevelAndUnify(ref cell, ref var) => { self.compile_get_level_and_unify(code, cell, var.clone(), term_loc) } - &QueryTerm::UnblockedCut(ref cell) => { - self.compile_unblocked_cut(code, cell) - } - &QueryTerm::BlockedCut => { - code.push(if chunk_num == 0 { - Line::Cut(CutInstruction::NeckCut) - } else { - Line::Cut(CutInstruction::Cut(perm_v!(1))) - }) - } + &QueryTerm::UnblockedCut(ref cell) => self.compile_unblocked_cut(code, cell), + &QueryTerm::BlockedCut => code.push(if chunk_num == 0 { + Line::Cut(CutInstruction::NeckCut) + } else { + Line::Cut(CutInstruction::Cut(perm_v!(1))) + }), &QueryTerm::Clause( _, ClauseType::BuiltIn(BuiltInClauseType::Is(..)), ref terms, use_default_call_policy, - ) => { - self.compile_is_call(terms, code, term_loc, use_default_call_policy)? - } + ) => self.compile_is_call(terms, code, term_loc, use_default_call_policy)?, &QueryTerm::Clause(_, ClauseType::Inlined(ref ct), ref terms, _) => { self.compile_inlined(ct, terms, term_loc, code)? } @@ -772,7 +751,12 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { } } - fn compile_cleanup(&mut self, code: &mut Code, conjunct_info: &ConjunctInfo, toc: &'a QueryTerm) { + fn compile_cleanup( + &mut self, + code: &mut Code, + conjunct_info: &ConjunctInfo, + toc: &'a QueryTerm, + ) { // add a proceed to bookend any trailing cuts. match toc { &QueryTerm::BlockedCut | &QueryTerm::UnblockedCut(..) => code.push(proceed!()), @@ -786,7 +770,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { if conjunct_info.allocates() { let offset = self.global_jmp_by_locs_offset; - if let Some(jmp_by_offset) = self.jmp_by_locs[offset ..].last_mut() { + if let Some(jmp_by_offset) = self.jmp_by_locs[offset..].last_mut() { if *jmp_by_offset == dealloc_index { *jmp_by_offset += 1; } @@ -905,32 +889,32 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { self.add_conditional_call(code, term, num_perm_vars_left); } -/* - pub fn compile_query(&mut self, query: &'a Vec) -> Result { - let iter = ChunkedIterator::from_term_sequence(query); - let conjunct_info = self.collect_var_data(iter); + /* + pub fn compile_query(&mut self, query: &'a Vec) -> Result { + let iter = ChunkedIterator::from_term_sequence(query); + let conjunct_info = self.collect_var_data(iter); - let mut code = Vec::new(); - self.compile_seq_prelude(&conjunct_info, &mut code); + let mut code = Vec::new(); + self.compile_seq_prelude(&conjunct_info, &mut code); - let iter = ChunkedIterator::from_term_sequence(query); - self.compile_seq(iter, &conjunct_info, &mut code, true)?; + let iter = ChunkedIterator::from_term_sequence(query); + self.compile_seq(iter, &conjunct_info, &mut code, true)?; - conjunct_info.mark_unsafe_vars(UnsafeVarMarker::new(), &mut code); + conjunct_info.mark_unsafe_vars(UnsafeVarMarker::new(), &mut code); - if let Some(query_term) = query.last() { - Self::compile_cleanup(&mut code, &conjunct_info, query_term); + if let Some(query_term) = query.last() { + Self::compile_cleanup(&mut code, &conjunct_info, query_term); + } + + Ok(code) } - - Ok(code) - } -*/ + */ #[inline] fn increment_jmp_by_locs_by(&mut self, incr: usize) { let offset = self.global_jmp_by_locs_offset; - for loc in &mut self.jmp_by_locs[offset ..] { + for loc in &mut self.jmp_by_locs[offset..] { *loc += incr; } } @@ -1077,7 +1061,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { if skip_stub_try_me_else { // skip the TryMeElse(0) also. - self.increment_jmp_by_locs_by(2); + self.increment_jmp_by_locs_by(2); } else { self.increment_jmp_by_locs_by(1); } @@ -1105,7 +1089,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { for (l, r) in split_pred { let skel_lower_bound = self.skeleton.clauses.len(); - let code_segment = self.compile_pred_subseq(&clauses[l .. r], optimal_index)?; + let code_segment = self.compile_pred_subseq(&clauses[l..r], optimal_index)?; let clause_start_offset = code.len(); if multi_seq { @@ -1123,11 +1107,10 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { if self.is_extensible { let segment_is_indexed = to_indexing_line(&code_segment[0]).is_some(); - for clause_index_info in self.skeleton.clauses[skel_lower_bound ..].iter_mut() { + for clause_index_info in self.skeleton.clauses[skel_lower_bound..].iter_mut() { clause_index_info.clause_start += clause_start_offset + 2 * (segment_is_indexed as usize); - clause_index_info.opt_arg_index_key += - clause_start_offset + 1; + clause_index_info.opt_arg_index_key += clause_start_offset + 1; } } diff --git a/src/debray_allocator.rs b/src/debray_allocator.rs index 3c69bda2..39b5a886 100644 --- a/src/debray_allocator.rs +++ b/src/debray_allocator.rs @@ -1,6 +1,7 @@ use crate::indexmap::IndexMap; use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::temp_v; use crate::allocator::*; use crate::fixtures::*; @@ -293,9 +294,7 @@ impl<'a> Allocator<'a> for DebrayAllocator { (pr, true) } - r => { - (r, false) - } + r => (r, false), }; self.mark_reserved_var(var, lvl, cell, term_loc, target, r, is_new_var); diff --git a/src/forms.rs b/src/forms.rs index c039e603..f71df86c 100644 --- a/src/forms.rs +++ b/src/forms.rs @@ -1,5 +1,6 @@ use crate::prolog_parser_rebis::ast::*; use crate::prolog_parser_rebis::parser::OpDesc; +use crate::prolog_parser_rebis::{clause_name, is_infix, is_postfix}; use crate::clause_types::*; use crate::machine::machine_errors::*; @@ -36,7 +37,7 @@ pub enum TopLevel { #[derive(Debug, Clone, Copy)] pub enum AppendOrPrepend { Append, - Prepend + Prepend, } impl AppendOrPrepend { @@ -115,12 +116,8 @@ impl ListingSource { pub trait ClauseInfo { fn is_consistent(&self, clauses: &Vec) -> bool { match clauses.first() { - Some(cl) => { - self.name() == cl.name() && self.arity() == cl.arity() - } - None => { - true - } + Some(cl) => self.name() == cl.name() && self.arity() == cl.arity(), + None => true, } } @@ -140,38 +137,25 @@ impl ClauseInfo for Term { _ => Some(clause_name!(":-")), } } - _ => { - Some(name.clone()) - } + _ => Some(name.clone()), } } - Term::Constant(_, Constant::Atom(ref name, _)) => { - Some(name.clone()) - } - _ => { - None - } + Term::Constant(_, Constant::Atom(ref name, _)) => Some(name.clone()), + _ => None, } } fn arity(&self) -> usize { match self { - Term::Clause(_, ref name, ref terms, _) => - match name.as_str() { - ":-" => { - match terms.len() { - 1 => 0, - 2 => terms[0].arity(), - _ => terms.len(), - } - } - _ => { - terms.len() - } + Term::Clause(_, ref name, ref terms, _) => match name.as_str() { + ":-" => match terms.len() { + 1 => 0, + 2 => terms[0].arity(), + _ => terms.len(), }, - _ => { - 0 - } + _ => terms.len(), + }, + _ => 0, } } } @@ -189,23 +173,15 @@ impl ClauseInfo for Rule { impl ClauseInfo for PredicateClause { fn name(&self) -> Option { match self { - &PredicateClause::Fact(ref term, ..) => { - term.name() - } - &PredicateClause::Rule(ref rule, ..) => { - rule.name() - } + &PredicateClause::Fact(ref term, ..) => term.name(), + &PredicateClause::Rule(ref rule, ..) => rule.name(), } } fn arity(&self) -> usize { match self { - &PredicateClause::Fact(ref term, ..) => { - term.arity() - } - &PredicateClause::Rule(ref rule, ..) => { - rule.arity() - } + &PredicateClause::Fact(ref term, ..) => term.arity(), + &PredicateClause::Rule(ref rule, ..) => rule.arity(), } } } @@ -222,11 +198,9 @@ impl PredicateClause { // TODO: add this to `Term` in `prolog_parser` like `first_arg`. pub fn args(&self) -> Option<&[Box]> { match *self { - PredicateClause::Fact(ref term, ..) => { - match term { - Term::Clause(_, _, args, _) => Some(&args), - _ => None, - } + PredicateClause::Fact(ref term, ..) => match term { + Term::Clause(_, _, args, _) => Some(&args), + _ => None, }, PredicateClause::Rule(ref rule, ..) => { if rule.head.1.is_empty() { @@ -240,14 +214,11 @@ impl PredicateClause { pub fn arity(&self) -> usize { match self { - &PredicateClause::Fact(ref term, ..) => { - term.arity() - } + &PredicateClause::Fact(ref term, ..) => term.arity(), &PredicateClause::Rule(ref rule, ..) => { if rule.head.0.as_str() == ":" && rule.head.1.len() == 2 { match (rule.head.1)[0].as_ref() { - &Term::Constant(_, Constant::Atom(..)) => { - } + &Term::Constant(_, Constant::Atom(..)) => {} _ => { return 2; } @@ -321,7 +292,7 @@ pub enum Declaration { pub struct OpDecl { pub prec: usize, pub spec: Specifier, - pub name: ClauseName + pub name: ClauseName, } impl OpDecl { @@ -345,7 +316,7 @@ impl OpDecl { XFY | XFX | YFX => Fixity::In, XF | YF => Fixity::Post, FX | FY => Fixity::Pre, - _ => unreachable!() + _ => unreachable!(), } } @@ -356,12 +327,12 @@ impl OpDecl { Some(cell) => { return Some(cell.shared_op_desc().replace((self.prec, self.spec))); } - None => { - } + None => {} } - op_dir.insert(key, OpDirValue::new(self.spec, self.prec)) - .map(|op_dir_value| op_dir_value.shared_op_desc().get()) + op_dir + .insert(key, OpDirValue::new(self.spec, self.prec)) + .map(|op_dir_value| op_dir_value.shared_op_desc().get()) } pub fn submit( @@ -419,11 +390,7 @@ pub fn fetch_op_spec_from_existing( spec.or_else(|| fetch_op_spec(name, arity, op_dir)) } -pub fn fetch_op_spec( - name: ClauseName, - arity: usize, - op_dir: &OpDir, -) -> Option { +pub fn fetch_op_spec(name: ClauseName, arity: usize, op_dir: &OpDir) -> Option { match arity { 2 => op_dir .get(&(name, Fixity::In)) @@ -451,9 +418,7 @@ pub fn fetch_op_spec( } }) } - _ => { - None - } + _ => None, } } @@ -499,7 +464,6 @@ impl Module { } } - #[derive(Debug, Clone)] pub enum Number { Float(OrderedFloat), @@ -559,7 +523,6 @@ impl Into for Number { } } - impl Number { #[inline] pub fn is_positive(&self) -> bool { @@ -594,12 +557,13 @@ impl Number { #[inline] pub fn abs(self) -> Self { match self { - Number::Fixnum(n) => + Number::Fixnum(n) => { if let Some(n) = n.checked_abs() { Number::from(n) } else { Number::from(Integer::from(n).abs()) } + } Number::Integer(n) => Number::from(Integer::from(n.abs_ref())), Number::Float(f) => Number::Float(OrderedFloat(f.abs())), Number::Rational(r) => Number::from(Rational::from(r.abs_ref())), @@ -624,15 +588,13 @@ impl OptArgIndexKey { #[inline] pub fn arg_num(&self) -> usize { match &self { - OptArgIndexKey::Constant(arg_num, ..) | - OptArgIndexKey::Structure(arg_num, ..) | - OptArgIndexKey::List(arg_num, _) => { + OptArgIndexKey::Constant(arg_num, ..) + | OptArgIndexKey::Structure(arg_num, ..) + | OptArgIndexKey::List(arg_num, _) => { // these are always at least 1. *arg_num } - OptArgIndexKey::None => { - 0 - } + OptArgIndexKey::None => 0, } } @@ -644,27 +606,22 @@ impl OptArgIndexKey { #[inline] pub fn switch_on_term_loc(&self) -> Option { match &self { - OptArgIndexKey::Constant(_, loc, ..) | - OptArgIndexKey::Structure(_, loc, ..) | - OptArgIndexKey::List(_, loc) => { - Some(*loc) - } - OptArgIndexKey::None => { - None - } + OptArgIndexKey::Constant(_, loc, ..) + | OptArgIndexKey::Structure(_, loc, ..) + | OptArgIndexKey::List(_, loc) => Some(*loc), + OptArgIndexKey::None => None, } } #[inline] pub fn set_switch_on_term_loc(&mut self, value: usize) { match self { - OptArgIndexKey::Constant(_, ref mut loc, ..) | - OptArgIndexKey::Structure(_, ref mut loc, ..) | - OptArgIndexKey::List(_, ref mut loc) => { + OptArgIndexKey::Constant(_, ref mut loc, ..) + | OptArgIndexKey::Structure(_, ref mut loc, ..) + | OptArgIndexKey::List(_, ref mut loc) => { *loc = value; } - OptArgIndexKey::None => { - } + OptArgIndexKey::None => {} } } } @@ -673,13 +630,12 @@ impl AddAssign for OptArgIndexKey { #[inline] fn add_assign(&mut self, n: usize) { match self { - OptArgIndexKey::Constant(_, ref mut o, ..) | - OptArgIndexKey::List(_, ref mut o) | - OptArgIndexKey::Structure(_, ref mut o, ..) => { + OptArgIndexKey::Constant(_, ref mut o, ..) + | OptArgIndexKey::List(_, ref mut o) + | OptArgIndexKey::Structure(_, ref mut o, ..) => { *o += n; } - OptArgIndexKey::None => { - } + OptArgIndexKey::None => {} } } } diff --git a/src/heap_print.rs b/src/heap_print.rs index 29530fa5..d4b9b09f 100644 --- a/src/heap_print.rs +++ b/src/heap_print.rs @@ -1,4 +1,10 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::{ + alpha_char, alpha_numeric_char, backslash_char, capital_letter_char, char_class, clause_name, + cut_char, decimal_digit_char, graphic_char, graphic_token_char, is_fx, is_infix, is_postfix, + is_prefix, is_xf, is_xfx, is_xfy, is_yfx, semicolon_char, sign_char, single_quote_char, + small_letter_char, solo_char, variable_indicator_char, +}; use crate::clause_types::*; use crate::forms::*; @@ -14,7 +20,7 @@ use crate::indexmap::{IndexMap, IndexSet}; use std::cell::Cell; use std::convert::TryFrom; -use std::iter::{FromIterator, once}; +use std::iter::{once, FromIterator}; use std::net::{IpAddr, TcpListener}; use std::ops::{Range, RangeFrom}; use std::rc::Rc; @@ -99,10 +105,7 @@ impl<'a> HCPreOrderIterator<'a> { None => return false, }; - let mut parent_spec = DirectedOp::Left( - clause_name!("-"), - SharedOpDesc::new(200, FY), - ); + let mut parent_spec = DirectedOp::Left(clause_name!("-"), SharedOpDesc::new(200, FY)); loop { match self.machine_st.store(self.machine_st.deref(addr)) { @@ -154,12 +157,13 @@ fn char_to_string(is_quoted: bool, c: char) -> String { '\u{07}' if is_quoted => "\\a".to_string(), // UTF-8 alert '"' if is_quoted => "\\\"".to_string(), '\\' if is_quoted => "\\\\".to_string(), - '\'' | '\n' | '\r' | '\t' | '\u{0b}' | '\u{0c}' | '\u{08}' | '\u{07}' | '"' | '\\' => - c.to_string(), - '\u{a0}' ..= '\u{d6}' => c.to_string(), - '\u{d8}' ..= '\u{f6}' => c.to_string(), - '\u{f8}' ..= '\u{74f}' => c.to_string(), - '\x20' ..= '\x7e' => c.to_string(), + '\'' | '\n' | '\r' | '\t' | '\u{0b}' | '\u{0c}' | '\u{08}' | '\u{07}' | '"' | '\\' => { + c.to_string() + } + '\u{a0}'..='\u{d6}' => c.to_string(), + '\u{d8}'..='\u{f6}' => c.to_string(), + '\u{f8}'..='\u{74f}' => c.to_string(), + '\x20'..='\x7e' => c.to_string(), _ => format!("\\x{:x}\\", c as u32), } } @@ -271,25 +275,13 @@ fn is_numbered_var(ct: &ClauseType, arity: usize) -> bool { #[inline] fn negated_op_needs_bracketing(iter: &HCPreOrderIterator, op: &Option) -> bool { if let Some(ref op) = op { - op.is_negative_sign() && - iter.leftmost_leaf_has_property(|addr, heap| { - match Number::try_from((addr, heap)) { - Ok(Number::Fixnum(n)) => { - n > 0 - } - Ok(Number::Float(f)) => { - f > OrderedFloat(0f64) - } - Ok(Number::Integer(n)) => { - &*n > &0 - } - Ok(Number::Rational(n)) => { - &*n > &0 - } - _ => { - false - } - } + op.is_negative_sign() + && iter.leftmost_leaf_has_property(|addr, heap| match Number::try_from((addr, heap)) { + Ok(Number::Fixnum(n)) => n > 0, + Ok(Number::Float(f)) => f > OrderedFloat(0f64), + Ok(Number::Integer(n)) => &*n > &0, + Ok(Number::Rational(n)) => &*n > &0, + _ => false, }) } else { false @@ -298,8 +290,8 @@ fn negated_op_needs_bracketing(iter: &HCPreOrderIterator, op: &Option Var { static CHAR_CODES: [char; 26] = [ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', + 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ]; let i = n.mod_u(26) as usize; @@ -332,9 +324,7 @@ impl MachineState { None } } - _ => { - None - } + _ => None, } } } @@ -446,8 +436,7 @@ fn non_quoted_graphic_token>(mut iter: Iter, c: char } } -pub(super) -fn non_quoted_token>(mut iter: Iter) -> bool { +pub(super) fn non_quoted_token>(mut iter: Iter) -> bool { if let Some(c) = iter.next() { if small_letter_char!(c) { iter.all(|c| alpha_numeric_char!(c)) @@ -505,37 +494,37 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { max_depth: 0, } } -/* - pub fn from_heap_locs( - machine_st: &'a MachineState, - op_dir: &'a OpDir, - output: Outputter, - ) -> Self { - let mut printer = Self::new(machine_st, op_dir, output); + /* + pub fn from_heap_locs( + machine_st: &'a MachineState, + op_dir: &'a OpDir, + output: Outputter, + ) -> Self { + let mut printer = Self::new(machine_st, op_dir, output); - printer.toplevel_spec = Some(DirectedOp::Right( - clause_name!("="), - SharedOpDesc::new(700, XFX), - )); + printer.toplevel_spec = Some(DirectedOp::Right( + clause_name!("="), + SharedOpDesc::new(700, XFX), + )); - printer.heap_locs = reverse_heap_locs(machine_st); + printer.heap_locs = reverse_heap_locs(machine_st); - printer - } -*/ -/* - pub fn drop_toplevel_spec(&mut self) { - self.toplevel_spec = None; - } -*/ -/* - #[inline] - pub fn see_all_locs(&mut self) { - for key in self.heap_locs.keys().cloned() { - self.printed_vars.insert(key); + printer } - } -*/ + */ + /* + pub fn drop_toplevel_spec(&mut self) { + self.toplevel_spec = None; + } + */ + /* + #[inline] + pub fn see_all_locs(&mut self) { + for key in self.heap_locs.keys().cloned() { + self.printed_vars.insert(key); + } + } + */ #[inline] fn ambiguity_check(&self, atom: &str) -> bool { @@ -555,7 +544,8 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { iter.stack().pop(); self.state_stack.push(TokenOrRedirect::Op(ct.name(), spec)); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); return; } @@ -579,7 +569,8 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { if self.check_max_depth(&mut max_depth) { iter.stack().pop(); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); self.state_stack.push(TokenOrRedirect::Op(ct.name(), spec)); return; @@ -587,7 +578,10 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let left_directed_op = DirectedOp::Left(ct.name(), spec.clone()); - self.state_stack.push(TokenOrRedirect::CompositeRedirect(max_depth, left_directed_op)); + self.state_stack.push(TokenOrRedirect::CompositeRedirect( + max_depth, + left_directed_op, + )); self.state_stack.push(TokenOrRedirect::Op(ct.name(), spec)); } else { match ct.name().as_str() { @@ -602,9 +596,11 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { iter.stack().pop(); iter.stack().pop(); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); self.state_stack.push(TokenOrRedirect::Op(ct.name(), spec)); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); return; } @@ -612,11 +608,15 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let left_directed_op = DirectedOp::Left(ct.name(), spec.clone()); let right_directed_op = DirectedOp::Right(ct.name(), spec.clone()); - self.state_stack - .push(TokenOrRedirect::CompositeRedirect(max_depth, left_directed_op)); + self.state_stack.push(TokenOrRedirect::CompositeRedirect( + max_depth, + left_directed_op, + )); self.state_stack.push(TokenOrRedirect::Op(ct.name(), spec)); - self.state_stack - .push(TokenOrRedirect::CompositeRedirect(max_depth, right_directed_op)); + self.state_stack.push(TokenOrRedirect::CompositeRedirect( + max_depth, + right_directed_op, + )); } } @@ -626,15 +626,15 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { mut max_depth: usize, arity: usize, name: ClauseName, - ) -> bool - { + ) -> bool { if self.check_max_depth(&mut max_depth) { - for _ in 0 .. arity { + for _ in 0..arity { iter.stack().pop(); } self.state_stack.push(TokenOrRedirect::Close); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); self.state_stack.push(TokenOrRedirect::Open); self.state_stack.push(TokenOrRedirect::Atom(name)); @@ -644,8 +644,9 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { self.state_stack.push(TokenOrRedirect::Close); - for _ in 0 .. arity { - self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth)); + for _ in 0..arity { + self.state_stack + .push(TokenOrRedirect::FunctorRedirect(max_depth)); self.state_stack.push(TokenOrRedirect::Comma); } @@ -662,12 +663,13 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { iter: &mut HCPreOrderIterator, mut max_depth: usize, name: ClauseName, - spec: SharedOpDesc) - { + spec: SharedOpDesc, + ) { if self.check_max_depth(&mut max_depth) { iter.stack().pop(); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); self.state_stack.push(TokenOrRedirect::Space); self.state_stack.push(TokenOrRedirect::Atom(name)); @@ -676,7 +678,8 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let op = DirectedOp::Left(name.clone(), spec); - self.state_stack.push(TokenOrRedirect::CompositeRedirect(max_depth, op)); + self.state_stack + .push(TokenOrRedirect::CompositeRedirect(max_depth, op)); self.state_stack.push(TokenOrRedirect::Space); self.state_stack.push(TokenOrRedirect::Atom(name)); } @@ -687,14 +690,15 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { mut max_depth: usize, name: ClauseName, spec: SharedOpDesc, - ) - { + ) { if self.check_max_depth(&mut max_depth) { iter.stack().pop(); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); self.state_stack.push(TokenOrRedirect::BarAsOp); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); return; } @@ -702,25 +706,32 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let left_directed_op = DirectedOp::Left(name.clone(), spec.clone()); let right_directed_op = DirectedOp::Right(name.clone(), spec.clone()); - self.state_stack.push(TokenOrRedirect::CompositeRedirect(max_depth, left_directed_op)); + self.state_stack.push(TokenOrRedirect::CompositeRedirect( + max_depth, + left_directed_op, + )); self.state_stack.push(TokenOrRedirect::BarAsOp); - self.state_stack.push(TokenOrRedirect::CompositeRedirect(max_depth, right_directed_op)); + self.state_stack.push(TokenOrRedirect::CompositeRedirect( + max_depth, + right_directed_op, + )); } - fn format_curly_braces(&mut self, iter: &mut HCPreOrderIterator, mut max_depth: usize) -> bool - { + fn format_curly_braces(&mut self, iter: &mut HCPreOrderIterator, mut max_depth: usize) -> bool { if self.check_max_depth(&mut max_depth) { iter.stack().pop(); self.state_stack.push(TokenOrRedirect::RightCurly); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); self.state_stack.push(TokenOrRedirect::LeftCurly); return false; } self.state_stack.push(TokenOrRedirect::RightCurly); - self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth)); + self.state_stack + .push(TokenOrRedirect::FunctorRedirect(max_depth)); self.state_stack.push(TokenOrRedirect::LeftCurly); true @@ -795,18 +806,12 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } match addr { - Addr::Lis(h) | Addr::Str(h) => { - Some(format!("{}", h)) - } + Addr::Lis(h) | Addr::Str(h) => Some(format!("{}", h)), _ => { if let Some(r) = addr.as_var() { match r { - Ref::StackCell(fr, sc) => { - Some(format!("_s_{}_{}", fr, sc)) - } - Ref::HeapCell(h) | Ref::AttrVar(h) => { - Some(format!("_{}", h)) - } + Ref::StackCell(fr, sc) => Some(format!("_s_{}_{}", fr, sc)), + Ref::HeapCell(h) | Ref::AttrVar(h) => Some(format!("_{}", h)), } } else { None @@ -818,8 +823,12 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { fn record_children_as_non_cyclic(&mut self, addr: &Addr) { match addr { &Addr::Lis(l) => { - let c1 = self.machine_st.store(self.machine_st.deref(Addr::HeapCell(l))); - let c2 = self.machine_st.store(self.machine_st.deref(Addr::HeapCell(l + 1))); + let c1 = self + .machine_st + .store(self.machine_st.deref(Addr::HeapCell(l))); + let c2 = self + .machine_st + .store(self.machine_st.deref(Addr::HeapCell(l + 1))); if let Some(c) = functor_location(&c1) { self.non_cyclic_terms.insert(c); @@ -830,18 +839,17 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } } &Addr::Str(s) => { - let arity = - match &self.machine_st.heap[s] { - HeapCellValue::NamedStr(arity, ..) => { - arity - } - _ => { - unreachable!() - } - }; + let arity = match &self.machine_st.heap[s] { + HeapCellValue::NamedStr(arity, ..) => arity, + _ => { + unreachable!() + } + }; - for i in 1 .. arity + 1 { - let c = self.machine_st.store(self.machine_st.deref(Addr::HeapCell(s + i))); + for i in 1..arity + 1 { + let c = self + .machine_st + .store(self.machine_st.deref(Addr::HeapCell(s + i))); if let Some(c) = functor_location(&c) { self.non_cyclic_terms.insert(c); @@ -856,15 +864,11 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { self.non_cyclic_terms.insert(c); } } - _ => { - } + _ => {} } } - fn check_for_seen( - &mut self, - iter: &mut HCPreOrderIterator, - ) -> Option { + fn check_for_seen(&mut self, iter: &mut HCPreOrderIterator) -> Option { iter.stack().last().cloned().and_then(|addr| { let addr = self.machine_st.store(self.machine_st.deref(addr)); @@ -889,9 +893,7 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } None => { let offset = match functor_location(&addr) { - Some(offset) => { - offset - } + Some(offset) => offset, None => { return iter.next(); } @@ -1036,19 +1038,17 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let rdiv_ct = clause_name!("rdiv"); - let left_directed_op = - if spec.prec() > 0 { - Some(DirectedOp::Left(rdiv_ct.clone(), spec.clone())) - } else { - None - }; + let left_directed_op = if spec.prec() > 0 { + Some(DirectedOp::Left(rdiv_ct.clone(), spec.clone())) + } else { + None + }; - let right_directed_op = - if spec.prec() > 0 { - Some(DirectedOp::Right(rdiv_ct.clone(), spec.clone())) - } else { - None - }; + let right_directed_op = if spec.prec() > 0 { + Some(DirectedOp::Right(rdiv_ct.clone(), spec.clone())) + } else { + None + }; if spec.prec() > 0 { self.state_stack.push(TokenOrRedirect::Number( @@ -1056,10 +1056,8 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { left_directed_op, )); - self.state_stack.push(TokenOrRedirect::Op( - rdiv_ct, - spec.clone(), - )); + self.state_stack + .push(TokenOrRedirect::Op(rdiv_ct, spec.clone())); self.state_stack.push(TokenOrRedirect::Number( Number::from(r.numer()), @@ -1068,17 +1066,13 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } else { self.state_stack.push(TokenOrRedirect::Close); - self.state_stack.push(TokenOrRedirect::Number( - Number::from(r.denom()), - None, - )); + self.state_stack + .push(TokenOrRedirect::Number(Number::from(r.denom()), None)); self.state_stack.push(TokenOrRedirect::Comma); - self.state_stack.push(TokenOrRedirect::Number( - Number::from(r.numer()), - None, - )); + self.state_stack + .push(TokenOrRedirect::Number(Number::from(r.numer()), None)); self.state_stack.push(TokenOrRedirect::Open); self.state_stack.push(TokenOrRedirect::Atom(rdiv_ct)); @@ -1092,8 +1086,7 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } } - fn print_char(&mut self, is_quoted: bool, c: char) - { + fn print_char(&mut self, is_quoted: bool, c: char) { if non_quoted_token(once(c)) { let c = char_to_string(false, c); @@ -1120,46 +1113,37 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { fn print_proper_string(&mut self, buf: String, max_depth: usize) { self.push_char('"'); - let buf = - if max_depth == 0 { - String::from_iter(buf.chars().map(|c| { - char_to_string(self.quoted, c) - })) - } else { - let mut char_count = 0; - let mut buf = - String::from_iter(buf.chars().take(max_depth).map(|c| { - char_count += 1; - char_to_string(self.quoted, c) - })); + let buf = if max_depth == 0 { + String::from_iter(buf.chars().map(|c| char_to_string(self.quoted, c))) + } else { + let mut char_count = 0; + let mut buf = String::from_iter(buf.chars().take(max_depth).map(|c| { + char_count += 1; + char_to_string(self.quoted, c) + })); - if char_count == max_depth { - buf += " ..."; - } + if char_count == max_depth { + buf += " ..."; + } - buf - }; + buf + }; self.append_str(&buf); self.push_char('"'); } - fn print_list_like( - &mut self, - iter: &mut HCPreOrderIterator, - addr: Addr, - mut max_depth: usize, - ) { + fn print_list_like(&mut self, iter: &mut HCPreOrderIterator, addr: Addr, mut max_depth: usize) { if self.check_max_depth(&mut max_depth) { iter.stack().pop(); iter.stack().pop(); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); return; } - let mut heap_pstr_iter = - self.machine_st.heap_pstr_iter(addr); + let mut heap_pstr_iter = self.machine_st.heap_pstr_iter(addr); let buf = heap_pstr_iter.to_string(); @@ -1184,12 +1168,11 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let buf_len = buf.len(); - let buf_iter: Box> = - if self.max_depth == 0 { - Box::new(buf.chars()) - } else { - Box::new(buf.chars().take(max_depth)) - }; + let buf_iter: Box> = if self.max_depth == 0 { + Box::new(buf.chars()) + } else { + Box::new(buf.chars().take(max_depth)) + }; let mut byte_len = 0; @@ -1207,14 +1190,16 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { byte_len += c.len_utf8(); } - for _ in 0 .. char_count { + for _ in 0..char_count { self.state_stack.push(TokenOrRedirect::Close); } if self.max_depth > 0 && buf_len > byte_len { - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); } else { - self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth)); + self.state_stack + .push(TokenOrRedirect::FunctorRedirect(max_depth)); iter.stack().push(end_addr); } } else { @@ -1232,15 +1217,17 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { byte_len += c.len_utf8(); } - self.state_stack.push(TokenOrRedirect::CloseList(Rc::new( - Cell::new((switch, 0)) - ))); + self.state_stack + .push(TokenOrRedirect::CloseList(Rc::new(Cell::new((switch, 0))))); if self.max_depth > 0 && buf_len > byte_len { - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); - } else { - self.outputter.truncate(self.outputter.len() - ','.len_utf8()); - self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth)); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); + } else { + self.outputter + .truncate(self.outputter.len() - ','.len_utf8()); + self.state_stack + .push(TokenOrRedirect::FunctorRedirect(max_depth)); iter.stack().push(end_addr); } @@ -1268,8 +1255,10 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let cell = Rc::new(Cell::new((true, 0))); - self.state_stack.push(TokenOrRedirect::CloseList(cell.clone())); - self.state_stack.push(TokenOrRedirect::Atom(clause_name!("..."))); + self.state_stack + .push(TokenOrRedirect::CloseList(cell.clone())); + self.state_stack + .push(TokenOrRedirect::Atom(clause_name!("..."))); self.state_stack.push(TokenOrRedirect::OpenList(cell)); return; @@ -1277,11 +1266,14 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { let cell = Rc::new(Cell::new((true, max_depth))); - self.state_stack.push(TokenOrRedirect::CloseList(cell.clone())); + self.state_stack + .push(TokenOrRedirect::CloseList(cell.clone())); - self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth)); + self.state_stack + .push(TokenOrRedirect::FunctorRedirect(max_depth)); self.state_stack.push(TokenOrRedirect::HeadTailSeparator); // bar - self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth)); + self.state_stack + .push(TokenOrRedirect::FunctorRedirect(max_depth)); self.state_stack.push(TokenOrRedirect::OpenList(cell)); } @@ -1298,23 +1290,24 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { max_depth: usize, ) { let add_brackets = if !self.ignore_ops { - negated_operand || if let Some(ref op) = op { - if self.numbervars && arity == 1 && name.as_str() == "$VAR" { - !iter.immediate_leaf_has_property(|addr, heap| { - match heap.index_addr(&addr).as_ref() { - &HeapCellValue::Integer(ref n) => &**n >= &0, - &HeapCellValue::Addr(Addr::Fixnum(n)) => n >= 0, - &HeapCellValue::Addr(Addr::Float(f)) => f >= OrderedFloat(0f64), - &HeapCellValue::Rational(ref r) => &**r >= &0, - _ => false - } - }) && needs_bracketing(&spec, op) + negated_operand + || if let Some(ref op) = op { + if self.numbervars && arity == 1 && name.as_str() == "$VAR" { + !iter.immediate_leaf_has_property(|addr, heap| { + match heap.index_addr(&addr).as_ref() { + &HeapCellValue::Integer(ref n) => &**n >= &0, + &HeapCellValue::Addr(Addr::Fixnum(n)) => n >= 0, + &HeapCellValue::Addr(Addr::Float(f)) => f >= OrderedFloat(0f64), + &HeapCellValue::Rational(ref r) => &**r >= &0, + _ => false, + } + }) && needs_bracketing(&spec, op) + } else { + needs_bracketing(&spec, op) + } } else { - needs_bracketing(&spec, op) + is_functor_redirect && spec.prec() >= 1000 } - } else { - is_functor_redirect && spec.prec() >= 1000 - } } else { false }; @@ -1344,15 +1337,15 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { tcp_listener: &TcpListener, max_depth: usize, ) { - let (ip, port) = - if let Some(addr) = tcp_listener.local_addr().ok() { - (addr.ip(), Number::from(addr.port() as isize)) - } else { - let disconnected_atom = clause_name!("$disconnected_tcp_listener"); - self.state_stack.push(TokenOrRedirect::Atom(disconnected_atom)); + let (ip, port) = if let Some(addr) = tcp_listener.local_addr().ok() { + (addr.ip(), Number::from(addr.port() as isize)) + } else { + let disconnected_atom = clause_name!("$disconnected_tcp_listener"); + self.state_stack + .push(TokenOrRedirect::Atom(disconnected_atom)); - return; - }; + return; + }; if self.format_struct(iter, max_depth, 1, clause_name!("$tcp_listener")) { let atom = self.state_stack.pop().unwrap(); @@ -1369,22 +1362,16 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } } - fn print_stream( - &mut self, - iter: &mut HCPreOrderIterator, - stream: &Stream, - max_depth: usize, - ) { + fn print_stream(&mut self, iter: &mut HCPreOrderIterator, stream: &Stream, max_depth: usize) { if let Some(alias) = &stream.options.alias { self.print_atom(alias); } else { if self.format_struct(iter, max_depth, 1, clause_name!("$stream")) { - let atom = - if stream.is_stdout() || stream.is_stdin() { - TokenOrRedirect::Atom(clause_name!("user")) - } else { - TokenOrRedirect::RawPtr(stream.as_ptr()) - }; + let atom = if stream.is_stdout() || stream.is_stdin() { + TokenOrRedirect::Atom(clause_name!("user")) + } else { + TokenOrRedirect::RawPtr(stream.as_ptr()) + }; let stream_root = self.state_stack.pop().unwrap(); @@ -1414,7 +1401,8 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { match self.machine_st.heap.index_addr(&addr).as_ref() { &HeapCellValue::NamedStr(arity, ref name, ref spec) => { - let spec = fetch_op_spec_from_existing(name.clone(), arity, spec.clone(), self.op_dir); + let spec = + fetch_op_spec_from_existing(name.clone(), arity, spec.clone(), self.op_dir); if let Some(spec) = spec { self.handle_op_as_struct( diff --git a/src/indexing.rs b/src/indexing.rs index 9359e18c..80bd4c17 100644 --- a/src/indexing.rs +++ b/src/indexing.rs @@ -1,4 +1,5 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::clause_name; use crate::prolog_parser_rebis::tabled_rc::*; use crate::forms::*; @@ -43,14 +44,10 @@ impl OptArgIndexKey { #[inline] fn has_key_type(&self, key_type: OptArgIndexKeyType) -> bool { match (self, key_type) { - (OptArgIndexKey::Constant(..), OptArgIndexKeyType::Constant) | - (OptArgIndexKey::Structure(..), OptArgIndexKeyType::Structure) | - (OptArgIndexKey::List(..), OptArgIndexKeyType::List) => { - true - } - _ => { - false - } + (OptArgIndexKey::Constant(..), OptArgIndexKeyType::Constant) + | (OptArgIndexKey::Structure(..), OptArgIndexKeyType::Structure) + | (OptArgIndexKey::List(..), OptArgIndexKeyType::List) => true, + _ => false, } } } @@ -93,16 +90,20 @@ impl<'a> IndexingCodeMergingPtr<'a> { indexing_code: &'a mut Vec, append_or_prepend: AppendOrPrepend, ) -> Self { - Self { skeleton, indexing_code, offset: 0, append_or_prepend } + Self { + skeleton, + indexing_code, + offset: 0, + append_or_prepend, + } } - fn internalize_constant(&mut self, constant_ptr: IndexingCodePtr) { - let constant_key = - search_skeleton_for_first_key_type( - self.skeleton, - OptArgIndexKeyType::Constant, - self.append_or_prepend, - ); + fn internalize_constant(&mut self, constant_ptr: IndexingCodePtr) { + let constant_key = search_skeleton_for_first_key_type( + self.skeleton, + OptArgIndexKeyType::Constant, + self.append_or_prepend, + ); let mut constants = IndexMap::new(); @@ -117,7 +118,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { if let IndexingCodePtr::Internal(_) = constant_ptr { self.indexing_code.push(IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(constants) + IndexingInstruction::SwitchOnConstant(constants), )); let last_index = self.indexing_code.len() - 1; @@ -126,34 +127,39 @@ impl<'a> IndexingCodeMergingPtr<'a> { self.offset = self.indexing_code.len(); self.indexing_code.push(IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(constants) + IndexingInstruction::SwitchOnConstant(constants), )); } } - fn add_indexed_choice_for_constant(&mut self, external: usize, constant: Constant, index: usize) - { - let third_level_index = - if self.append_or_prepend.is_append() { - sdeq![ - IndexedChoiceInstruction::Try(external), - IndexedChoiceInstruction::Trust(index) - ] - } else { - sdeq![ - IndexedChoiceInstruction::Try(index), - IndexedChoiceInstruction::Trust(external) - ] - }; + fn add_indexed_choice_for_constant( + &mut self, + external: usize, + constant: Constant, + index: usize, + ) { + let third_level_index = if self.append_or_prepend.is_append() { + sdeq![ + IndexedChoiceInstruction::Try(external), + IndexedChoiceInstruction::Trust(index) + ] + } else { + sdeq![ + IndexedChoiceInstruction::Try(index), + IndexedChoiceInstruction::Trust(external) + ] + }; let indexing_code_len = self.indexing_code.len(); - self.indexing_code.push(IndexingLine::IndexedChoice(third_level_index)); + self.indexing_code + .push(IndexingLine::IndexedChoice(third_level_index)); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(ref mut constants) - ) => { - constants.insert(constant, IndexingCodePtr::Internal(indexing_code_len - self.offset)); + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref mut constants)) => { + constants.insert( + constant, + IndexingCodePtr::Internal(indexing_code_len - self.offset), + ); } _ => { unreachable!() @@ -164,10 +170,11 @@ impl<'a> IndexingCodeMergingPtr<'a> { fn extend_indexed_choice(&mut self, index: usize) { match &mut self.indexing_code[self.offset] { IndexingLine::IndexedChoice(ref mut indexed_choice_instrs) - if self.append_or_prepend.is_append() => { - uncap_choice_seq_with_trust(indexed_choice_instrs); - indexed_choice_instrs.push_back(IndexedChoiceInstruction::Trust(index)); - } + if self.append_or_prepend.is_append() => + { + uncap_choice_seq_with_trust(indexed_choice_instrs); + indexed_choice_instrs.push_back(IndexedChoiceInstruction::Trust(index)); + } IndexingLine::IndexedChoice(ref mut indexed_choice_instrs) => { uncap_choice_seq_with_try(indexed_choice_instrs); indexed_choice_instrs.push_front(IndexedChoiceInstruction::Try(index)); @@ -188,9 +195,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { match *c { IndexingCodePtr::Fail => { *c = IndexingCodePtr::External(index); @@ -203,7 +208,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { *c = IndexingCodePtr::Internal(indexing_code_len); self.indexing_code.push(IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(constants) + IndexingInstruction::SwitchOnConstant(constants), )); self.offset = indexing_code_len; @@ -213,12 +218,11 @@ impl<'a> IndexingCodeMergingPtr<'a> { } } } - IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(constants) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) => { match constants.get(&overlapping_constant).cloned() { None | Some(IndexingCodePtr::Fail) => { - constants.insert(overlapping_constant, IndexingCodePtr::External(index)); + constants + .insert(overlapping_constant, IndexingCodePtr::External(index)); } Some(IndexingCodePtr::External(o)) => { self.add_indexed_choice_for_constant(o, overlapping_constant, index); @@ -232,9 +236,9 @@ impl<'a> IndexingCodeMergingPtr<'a> { break; } IndexingLine::IndexedChoice(_) => { - self.internalize_constant( - IndexingCodePtr::Internal(indexing_code_len - self.offset), - ); + self.internalize_constant(IndexingCodePtr::Internal( + indexing_code_len - self.offset, + )); } _ => { unreachable!() @@ -248,9 +252,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { match *c { IndexingCodePtr::Fail => { *c = IndexingCodePtr::External(index); @@ -265,9 +267,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { } } } - IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(constants) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) => { match constants.get(&constant).cloned() { None | Some(IndexingCodePtr::Fail) => { constants.insert(constant, IndexingCodePtr::External(index)); @@ -284,9 +284,9 @@ impl<'a> IndexingCodeMergingPtr<'a> { break; } IndexingLine::IndexedChoice(_) => { - self.internalize_constant( - IndexingCodePtr::Internal(indexing_code_len - self.offset), - ); + self.internalize_constant(IndexingCodePtr::Internal( + indexing_code_len - self.offset, + )); } _ => { unreachable!() @@ -295,13 +295,12 @@ impl<'a> IndexingCodeMergingPtr<'a> { } } - fn internalize_structure(&mut self, structure_ptr: IndexingCodePtr) { - let structure_key = - search_skeleton_for_first_key_type( - self.skeleton, - OptArgIndexKeyType::Structure, - self.append_or_prepend, - ); + fn internalize_structure(&mut self, structure_ptr: IndexingCodePtr) { + let structure_key = search_skeleton_for_first_key_type( + self.skeleton, + OptArgIndexKeyType::Structure, + self.append_or_prepend, + ); let mut structures = IndexMap::new(); @@ -316,7 +315,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { if let IndexingCodePtr::Internal(_) = structure_ptr { self.indexing_code.push(IndexingLine::Indexing( - IndexingInstruction::SwitchOnStructure(structures) + IndexingInstruction::SwitchOnStructure(structures), )); let last_index = self.indexing_code.len() - 1; @@ -325,34 +324,39 @@ impl<'a> IndexingCodeMergingPtr<'a> { self.offset = self.indexing_code.len(); self.indexing_code.push(IndexingLine::Indexing( - IndexingInstruction::SwitchOnStructure(structures) + IndexingInstruction::SwitchOnStructure(structures), )); } } - fn add_indexed_choice_for_structure(&mut self, external: usize, key: PredicateKey, index: usize) - { - let third_level_index = - if self.append_or_prepend.is_append() { - sdeq![ - IndexedChoiceInstruction::Try(external), - IndexedChoiceInstruction::Trust(index) - ] - } else { - sdeq![ - IndexedChoiceInstruction::Try(index), - IndexedChoiceInstruction::Trust(external) - ] - }; + fn add_indexed_choice_for_structure( + &mut self, + external: usize, + key: PredicateKey, + index: usize, + ) { + let third_level_index = if self.append_or_prepend.is_append() { + sdeq![ + IndexedChoiceInstruction::Try(external), + IndexedChoiceInstruction::Trust(index) + ] + } else { + sdeq![ + IndexedChoiceInstruction::Try(index), + IndexedChoiceInstruction::Trust(external) + ] + }; let indexing_code_len = self.indexing_code.len(); - self.indexing_code.push(IndexingLine::IndexedChoice(third_level_index)); + self.indexing_code + .push(IndexingLine::IndexedChoice(third_level_index)); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnStructure(ref mut structures) - ) => { - structures.insert(key, IndexingCodePtr::Internal(indexing_code_len - self.offset)); + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref mut structures)) => { + structures.insert( + key, + IndexingCodePtr::Internal(indexing_code_len - self.offset), + ); } _ => { unreachable!() @@ -365,26 +369,26 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, _, _, ref mut s) - ) => { - match *s { - IndexingCodePtr::Fail => { - *s = IndexingCodePtr::External(index); - break; - } - 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::SwitchOnTerm( + _, + _, + _, + _, + ref mut s, + )) => match *s { + IndexingCodePtr::Fail => { + *s = IndexingCodePtr::External(index); + break; } - } - IndexingLine::Indexing( - IndexingInstruction::SwitchOnStructure(structures) - ) => { + 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) => { structures.insert(key, IndexingCodePtr::External(index)); @@ -404,9 +408,9 @@ impl<'a> IndexingCodeMergingPtr<'a> { // replace this value, at self.offset, with // SwitchOnStructures, and swap this IndexedChoice // vector to the end of self.indexing_code. - self.internalize_structure( - IndexingCodePtr::Internal(indexing_code_len - self.offset), - ); + self.internalize_structure(IndexingCodePtr::Internal( + indexing_code_len - self.offset, + )); } _ => { unreachable!() @@ -419,9 +423,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, _, ref mut l, _) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, ref mut l, _)) => { match *l { IndexingCodePtr::Fail => { *l = IndexingCodePtr::External(index); @@ -429,22 +431,20 @@ impl<'a> IndexingCodeMergingPtr<'a> { IndexingCodePtr::External(o) => { *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); - let third_level_index = - if self.append_or_prepend.is_append() { - sdeq![ - IndexedChoiceInstruction::Try(o), - IndexedChoiceInstruction::Trust(index) - ] - } else { - sdeq![ - IndexedChoiceInstruction::Try(index), - IndexedChoiceInstruction::Trust(o) - ] - }; + let third_level_index = if self.append_or_prepend.is_append() { + sdeq![ + IndexedChoiceInstruction::Try(o), + IndexedChoiceInstruction::Trust(index) + ] + } else { + sdeq![ + IndexedChoiceInstruction::Try(index), + IndexedChoiceInstruction::Trust(o) + ] + }; - self.indexing_code.push( - IndexingLine::IndexedChoice(third_level_index), - ); + self.indexing_code + .push(IndexingLine::IndexedChoice(third_level_index)); } IndexingCodePtr::Internal(o) => { self.offset += o; @@ -462,24 +462,16 @@ impl<'a> IndexingCodeMergingPtr<'a> { pub fn merge_clause_index( target_indexing_code: &mut Vec, skeleton: &mut [ClauseIndexInfo], // the clause to be merged is the last element in the skeleton. - new_clause_loc: usize, // the absolute location of the new clause in the code vector. + new_clause_loc: usize, // the absolute location of the new clause in the code vector. append_or_prepend: AppendOrPrepend, ) { - let opt_arg_index_key = - match append_or_prepend { - AppendOrPrepend::Append => { - skeleton.last_mut().unwrap().opt_arg_index_key.take() - } - AppendOrPrepend::Prepend => { - skeleton.first_mut().unwrap().opt_arg_index_key.take() - } - }; + let opt_arg_index_key = match append_or_prepend { + AppendOrPrepend::Append => skeleton.last_mut().unwrap().opt_arg_index_key.take(), + AppendOrPrepend::Prepend => skeleton.first_mut().unwrap().opt_arg_index_key.take(), + }; - let mut merging_ptr = IndexingCodeMergingPtr::new( - skeleton, - target_indexing_code, - append_or_prepend, - ); + let mut merging_ptr = + IndexingCodeMergingPtr::new(skeleton, target_indexing_code, append_or_prepend); match &opt_arg_index_key { OptArgIndexKey::Constant(_, index_loc, ref constant, ref overlapping_constants) => { @@ -488,7 +480,9 @@ pub fn merge_clause_index( for overlapping_constant in overlapping_constants { merging_ptr.index_overlapping_constant( - constant, overlapping_constant.clone(), offset, + constant, + overlapping_constant.clone(), + offset, ); } } @@ -514,10 +508,7 @@ pub fn merge_clause_index( } #[inline] -fn remove_instruction_with_offset( - code: &mut SliceDeque, - offset: usize, -) { +fn remove_instruction_with_offset(code: &mut SliceDeque, offset: usize) { for (index, line) in code.iter().enumerate() { if offset == line.offset() { code.remove(index); @@ -537,9 +528,7 @@ pub fn remove_constant_indices( let iter = once(constant).chain(overlapping_constants.iter()); match &mut indexing_code[index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { match *c { IndexingCodePtr::External(_) => { *c = IndexingCodePtr::Fail; @@ -560,12 +549,13 @@ pub fn remove_constant_indices( let mut constants_index = 0; - for constant in iter { // (constant, index_loc) in iter.zip(index_locs.iter()) { + for constant in iter { + // (constant, index_loc) in iter.zip(index_locs.iter()) { loop { match &mut indexing_code[index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(ref mut constants) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant( + ref mut constants, + )) => { constants_index = index; match constants.get(constant).cloned() { @@ -586,18 +576,21 @@ pub fn remove_constant_indices( if indexed_choice_instrs.len() == 1 { let ext = IndexingCodePtr::External( - indexed_choice_instrs.pop_back().unwrap().offset() + indexed_choice_instrs.pop_back().unwrap().offset(), ); match &mut indexing_code[constants_index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( + _, + _, + ref mut c, + .., + )) => { *c = ext; } - IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(ref mut constants) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant( + ref mut constants, + )) => { constants.insert(constant.clone(), ext); } _ => { @@ -616,13 +609,11 @@ pub fn remove_constant_indices( } match &indexing_code[constants_index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnConstant(ref constants) - ) if constants.is_empty() => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref constants)) + if constants.is_empty() => + { match &mut indexing_code[0] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { *c = IndexingCodePtr::Fail; } _ => { @@ -630,8 +621,7 @@ pub fn remove_constant_indices( } } } - _ => { - } + _ => {} } } @@ -644,9 +634,7 @@ pub fn remove_structure_index( let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, _, _, ref mut s) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, ref mut s)) => { match *s { IndexingCodePtr::External(_) => { *s = IndexingCodePtr::Fail; @@ -669,9 +657,7 @@ pub fn remove_structure_index( loop { match &mut indexing_code[index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnStructure(ref mut structures) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref mut structures)) => { structures_index = index; match structures.get(&(name.clone(), arity)).cloned() { @@ -692,18 +678,22 @@ pub fn remove_structure_index( if indexed_choice_instrs.len() == 1 { let ext = IndexingCodePtr::External( - indexed_choice_instrs.pop_back().unwrap().offset() + indexed_choice_instrs.pop_back().unwrap().offset(), ); match &mut indexing_code[structures_index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, _, _, ref mut s) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( + _, + _, + _, + _, + ref mut s, + )) => { *s = ext; } - IndexingLine::Indexing( - IndexingInstruction::SwitchOnStructure(ref mut structures) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure( + ref mut structures, + )) => { structures.insert((name.clone(), arity), ext); } _ => { @@ -721,13 +711,17 @@ pub fn remove_structure_index( } match &indexing_code[structures_index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnStructure(ref structures) - ) if structures.is_empty() => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref structures)) + if structures.is_empty() => + { match &mut indexing_code[0] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, _, _, ref mut s) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( + _, + _, + _, + _, + ref mut s, + )) => { *s = IndexingCodePtr::Fail; } _ => { @@ -735,21 +729,15 @@ pub fn remove_structure_index( } } } - _ => { - } + _ => {} } } -pub fn remove_list_index( - indexing_code: &mut Vec, - offset: usize, -) { +pub fn remove_list_index(indexing_code: &mut Vec, offset: usize) { let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, _, ref mut l, _) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, ref mut l, _)) => { match *l { IndexingCodePtr::External(_) => { *l = IndexingCodePtr::Fail; @@ -773,14 +761,17 @@ pub fn remove_list_index( remove_instruction_with_offset(indexed_choice_instrs, offset); if indexed_choice_instrs.len() == 1 { - let ext = IndexingCodePtr::External( - indexed_choice_instrs.pop_back().unwrap().offset() - ); + let ext = + IndexingCodePtr::External(indexed_choice_instrs.pop_back().unwrap().offset()); match &mut indexing_code[0] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, _, _, ref mut l, _) - ) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( + _, + _, + _, + ref mut l, + _, + )) => { *l = ext; } _ => { @@ -836,8 +827,7 @@ pub fn remove_index( fn second_level_index( indices: IndexMap>, prelude: &mut SliceDeque, -) -> IndexMap -{ +) -> IndexMap { let mut index_locs = IndexMap::new(); for (key, mut code) in indices.into_iter() { @@ -868,10 +858,11 @@ fn switch_on( IndexingCodePtr::Internal(1) } else { - index.into_iter() - .next() - .map(|(_, v)| v) - .unwrap_or(IndexingCodePtr::Fail) + index + .into_iter() + .next() + .map(|(_, v)| v) + .unwrap_or(IndexingCodePtr::Fail) } } @@ -884,9 +875,10 @@ fn switch_on_list( prelude.push_back(IndexingLine::from(lists)); IndexingCodePtr::Internal(1) } else { - lists.first() - .map(|i| IndexingCodePtr::External(i.offset())) - .unwrap_or(IndexingCodePtr::Fail) + lists + .first() + .map(|i| IndexingCodePtr::External(i.offset())) + .unwrap_or(IndexingCodePtr::Fail) } } @@ -978,8 +970,7 @@ pub fn constant_key_alternatives(constant: &Constant, atom_tbl: TabledData constants.push(Constant::Fixnum(n)); } } - _ => { - } + _ => {} } constants @@ -1001,7 +992,7 @@ impl CodeOffsets { constants: IndexMap::new(), lists: sdeq![], structures: IndexMap::new(), - optimal_index + optimal_index, } } @@ -1011,20 +1002,15 @@ impl CodeOffsets { } fn index_constant(&mut self, constant: &Constant, index: usize) -> Vec { - let overlapping_constants = - constant_key_alternatives(constant, self.atom_tbl.clone()); + let overlapping_constants = constant_key_alternatives(constant, self.atom_tbl.clone()); - let code = self.constants - .entry(constant.clone()) - .or_insert(sdeq![]); + let code = self.constants.entry(constant.clone()).or_insert(sdeq![]); let is_initial_index = code.is_empty(); code.push_back(compute_index(is_initial_index, index)); for constant in &overlapping_constants { - let code = self.constants - .entry(constant.clone()) - .or_insert(sdeq![]); + let code = self.constants.entry(constant.clone()).or_insert(sdeq![]); let is_initial_index = code.is_empty(); let index = compute_index(is_initial_index, index); @@ -1062,25 +1048,21 @@ impl CodeOffsets { self.index_structure(name, terms.len(), index); } &Term::Cons(..) | &Term::Constant(_, Constant::String(_)) => { - clause_index_info.opt_arg_index_key = - OptArgIndexKey::List(self.optimal_index, 0); + clause_index_info.opt_arg_index_key = OptArgIndexKey::List(self.optimal_index, 0); self.index_list(index); } &Term::Constant(_, ref constant) => { - let overlapping_constants = - self.index_constant(constant, index); + let overlapping_constants = self.index_constant(constant, index); - clause_index_info.opt_arg_index_key = - OptArgIndexKey::Constant( - self.optimal_index, - 0, - constant.clone(), - overlapping_constants, - ); - } - _ => { + clause_index_info.opt_arg_index_key = OptArgIndexKey::Constant( + self.optimal_index, + 0, + constant.clone(), + overlapping_constants, + ); } + _ => {} } } @@ -1117,8 +1099,7 @@ impl CodeOffsets { IndexingCodePtr::Internal(ref mut i) => { *i += con_loc.is_internal() as usize; } - _ => { - } + _ => {} }; match &mut lst_loc { @@ -1126,15 +1107,18 @@ impl CodeOffsets { *i += con_loc.is_internal() as usize; *i += str_loc.is_internal() as usize; } - _ => { - } + _ => {} }; let var_offset = 1 + skip_stub_try_me_else as usize; - prelude.push_front(IndexingLine::from( - IndexingInstruction::SwitchOnTerm(self.optimal_index, var_offset, con_loc, lst_loc, str_loc) - )); + prelude.push_front(IndexingLine::from(IndexingInstruction::SwitchOnTerm( + self.optimal_index, + var_offset, + con_loc, + lst_loc, + str_loc, + ))); prelude.into_iter().collect() } diff --git a/src/instructions.rs b/src/instructions.rs index d27d120a..91982ea2 100644 --- a/src/instructions.rs +++ b/src/instructions.rs @@ -1,4 +1,5 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::clause_name; use crate::clause_types::*; use crate::forms::*; @@ -34,9 +35,7 @@ impl Level { impl ArithmeticTerm { fn into_functor(&self) -> MachineStub { match self { - &ArithmeticTerm::Reg(r) => { - reg_type_into_functor(r) - } + &ArithmeticTerm::Reg(r) => reg_type_into_functor(r), &ArithmeticTerm::Interm(i) => { functor!("intermediate", [integer(i)]) } @@ -185,16 +184,11 @@ impl Line { pub fn enqueue_functors(&self, mut h: usize, functors: &mut Vec) { match self { - &Line::Arithmetic(ref arith_instr) => - functors.push(arith_instr.to_functor(h)), - &Line::Choice(ref choice_instr) => - functors.push(choice_instr.to_functor()), - &Line::Control(ref control_instr) => - functors.push(control_instr.to_functor()), - &Line::Cut(ref cut_instr) => - functors.push(cut_instr.to_functor(h)), - &Line::Fact(ref fact_instr) => - functors.push(fact_instr.to_functor(h)), + &Line::Arithmetic(ref arith_instr) => functors.push(arith_instr.to_functor(h)), + &Line::Choice(ref choice_instr) => functors.push(choice_instr.to_functor()), + &Line::Control(ref control_instr) => functors.push(control_instr.to_functor()), + &Line::Cut(ref cut_instr) => functors.push(cut_instr.to_functor(h)), + &Line::Fact(ref fact_instr) => functors.push(fact_instr.to_functor(h)), &Line::IndexingCode(ref indexing_instrs) => { for indexing_instr in indexing_instrs { match indexing_instr { @@ -213,10 +207,10 @@ impl Line { } } } - &Line::IndexedChoice(ref indexed_choice_instr) => - functors.push(indexed_choice_instr.to_functor()), - &Line::Query(ref query_instr) => - functors.push(query_instr.to_functor(h)), + &Line::IndexedChoice(ref indexed_choice_instr) => { + functors.push(indexed_choice_instr.to_functor()) + } + &Line::Query(ref query_instr) => functors.push(query_instr.to_functor(h)), } } } @@ -224,24 +218,16 @@ impl Line { #[inline] pub fn to_indexing_line_mut(line: &mut Line) -> Option<&mut Vec> { match line { - Line::IndexingCode(ref mut indexing_code) => { - Some(indexing_code) - } - _ => { - None - } + Line::IndexingCode(ref mut indexing_code) => Some(indexing_code), + _ => None, } } #[inline] pub fn to_indexing_line(line: &Line) -> Option<&Vec> { match line { - Line::IndexingCode(ref indexing_code) => { - Some(indexing_code) - } - _ => { - None - } + Line::IndexingCode(ref indexing_code) => Some(indexing_code), + _ => None, } } @@ -296,11 +282,7 @@ fn arith_instr_unary_functor( ) -> MachineStub { let at_stub = at.into_functor(); - functor!( - name, - [aux(h, 0), integer(t)], - [at_stub] - ) + functor!(name, [aux(h, 0), integer(t)], [at_stub]) } fn arith_instr_bin_functor( @@ -383,39 +365,17 @@ impl ArithmeticInstruction { &ArithmeticInstruction::Gcd(ref at_1, ref at_2, t) => { arith_instr_bin_functor(h, "gcd", at_1, at_2, t) } - &ArithmeticInstruction::Sign(ref at, t) => { - arith_instr_unary_functor(h, "sign", at, t) - } - &ArithmeticInstruction::Cos(ref at, t) => { - arith_instr_unary_functor(h, "cos", at, t) - } - &ArithmeticInstruction::Sin(ref at, t) => { - arith_instr_unary_functor(h, "sin", at, t) - } - &ArithmeticInstruction::Tan(ref at, t) => { - arith_instr_unary_functor(h, "tan", at, t) - } - &ArithmeticInstruction::Log(ref at, t) => { - arith_instr_unary_functor(h, "log", at, t) - } - &ArithmeticInstruction::Exp(ref at, t) => { - arith_instr_unary_functor(h, "exp", at, t) - } - &ArithmeticInstruction::ACos(ref at, t) => { - arith_instr_unary_functor(h, "acos", at, t) - } - &ArithmeticInstruction::ASin(ref at, t) => { - arith_instr_unary_functor(h, "asin", at, t) - } - &ArithmeticInstruction::ATan(ref at, t) => { - arith_instr_unary_functor(h, "atan", at, t) - } - &ArithmeticInstruction::Sqrt(ref at, t) => { - arith_instr_unary_functor(h, "sqrt", at, t) - } - &ArithmeticInstruction::Abs(ref at, t) => { - arith_instr_unary_functor(h, "abs", at, t) - } + &ArithmeticInstruction::Sign(ref at, t) => arith_instr_unary_functor(h, "sign", at, t), + &ArithmeticInstruction::Cos(ref at, t) => arith_instr_unary_functor(h, "cos", at, t), + &ArithmeticInstruction::Sin(ref at, t) => arith_instr_unary_functor(h, "sin", at, t), + &ArithmeticInstruction::Tan(ref at, t) => arith_instr_unary_functor(h, "tan", at, t), + &ArithmeticInstruction::Log(ref at, t) => arith_instr_unary_functor(h, "log", at, t), + &ArithmeticInstruction::Exp(ref at, t) => arith_instr_unary_functor(h, "exp", at, t), + &ArithmeticInstruction::ACos(ref at, t) => arith_instr_unary_functor(h, "acos", at, t), + &ArithmeticInstruction::ASin(ref at, t) => arith_instr_unary_functor(h, "asin", at, t), + &ArithmeticInstruction::ATan(ref at, t) => arith_instr_unary_functor(h, "atan", at, t), + &ArithmeticInstruction::Sqrt(ref at, t) => arith_instr_unary_functor(h, "sqrt", at, t), + &ArithmeticInstruction::Abs(ref at, t) => arith_instr_unary_functor(h, "abs", at, t), &ArithmeticInstruction::Float(ref at, t) => { arith_instr_unary_functor(h, "float", at, t) } @@ -431,12 +391,8 @@ impl ArithmeticInstruction { &ArithmeticInstruction::Floor(ref at, t) => { arith_instr_unary_functor(h, "floor", at, t) } - &ArithmeticInstruction::Neg(ref at, t) => { - arith_instr_unary_functor(h, "-", at, t) - } - &ArithmeticInstruction::Plus(ref at, t) => { - arith_instr_unary_functor(h, "+", at, t) - } + &ArithmeticInstruction::Neg(ref at, t) => arith_instr_unary_functor(h, "-", at, t), + &ArithmeticInstruction::Plus(ref at, t) => arith_instr_unary_functor(h, "+", at, t), &ArithmeticInstruction::BitwiseComplement(ref at, t) => { arith_instr_unary_functor(h, "\\", at, t) } @@ -451,21 +407,18 @@ pub enum ControlInstruction { CallClause(ClauseType, usize, usize, bool, bool), Deallocate, JmpBy(usize, usize, usize, bool), // arity, global_offset, perm_vars after threshold, last call. - RevJmpBy(usize), // notice the lack of context change as in - // JmpBy. RevJmpBy is used only to patch extensible - // predicates together. + RevJmpBy(usize), // notice the lack of context change as in + // JmpBy. RevJmpBy is used only to patch extensible + // predicates together. Proceed, } impl ControlInstruction { pub fn perm_vars(&self) -> Option { match self { - ControlInstruction::CallClause(_, _, num_cells, ..) => - Some(*num_cells), - ControlInstruction::JmpBy(_, _, num_cells, ..) => - Some(*num_cells), - _ => - None + ControlInstruction::CallClause(_, _, num_cells, ..) => Some(*num_cells), + ControlInstruction::JmpBy(_, _, num_cells, ..) => Some(*num_cells), + _ => None, } } @@ -500,7 +453,13 @@ impl ControlInstruction { #[derive(Debug)] pub enum IndexingInstruction { // The first index is the optimal argument being indexed. - SwitchOnTerm(usize, usize, IndexingCodePtr, IndexingCodePtr, IndexingCodePtr), + SwitchOnTerm( + usize, + usize, + IndexingCodePtr, + IndexingCodePtr, + IndexingCodePtr, + ), SwitchOnConstant(IndexMap), SwitchOnStructure(IndexMap<(ClauseName, usize), IndexingCodePtr>), } @@ -511,11 +470,13 @@ impl IndexingInstruction { &IndexingInstruction::SwitchOnTerm(arg, vars, constants, lists, structures) => { functor!( "switch_on_term", - [integer(arg), - integer(vars), - indexing_code_ptr(h, constants), - indexing_code_ptr(h, lists), - indexing_code_ptr(h, structures)] + [ + integer(arg), + integer(vars), + indexing_code_ptr(h, constants), + indexing_code_ptr(h, lists), + indexing_code_ptr(h, structures) + ] ) } &IndexingInstruction::SwitchOnConstant(ref constants) => { @@ -528,15 +489,14 @@ impl IndexingInstruction { let key_value_pair = functor!( ":", SharedOpDesc::new(600, XFY), - [constant(c), - indexing_code_ptr(h + 3, *ptr)] + [constant(c), indexing_code_ptr(h + 3, *ptr)] ); key_value_list_stub.push(HeapCellValue::Addr(Addr::Lis(h + 1))); key_value_list_stub.push(HeapCellValue::Addr(Addr::Str(h + 3))); - key_value_list_stub.push(HeapCellValue::Addr( - Addr::HeapCell(h + 3 + key_value_pair.len()) - )); + key_value_list_stub.push(HeapCellValue::Addr(Addr::HeapCell( + h + 3 + key_value_pair.len(), + ))); h += key_value_pair.len() + 3; key_value_list_stub.extend(key_value_pair.into_iter()); @@ -560,23 +520,21 @@ impl IndexingInstruction { let predicate_indicator_stub = functor!( "/", SharedOpDesc::new(400, YFX), - [clause_name(name.clone()), - integer(*arity)] + [clause_name(name.clone()), integer(*arity)] ); let key_value_pair = functor!( ":", SharedOpDesc::new(600, XFY), - [aux(h + 3, 0), - indexing_code_ptr(h + 3, *ptr)], + [aux(h + 3, 0), indexing_code_ptr(h + 3, *ptr)], [predicate_indicator_stub] ); key_value_list_stub.push(HeapCellValue::Addr(Addr::Lis(h + 1))); key_value_list_stub.push(HeapCellValue::Addr(Addr::Str(h + 3))); - key_value_list_stub.push(HeapCellValue::Addr( - Addr::HeapCell(h + 3 + key_value_pair.len()) - )); + key_value_list_stub.push(HeapCellValue::Addr(Addr::HeapCell( + h + 3 + key_value_pair.len(), + ))); h += key_value_pair.len() + 3; key_value_list_stub.extend(key_value_pair.into_iter()); @@ -614,7 +572,7 @@ impl FactInstruction { match self { &FactInstruction::GetConstant(lvl, ref c, r) => { let lvl_stub = lvl.into_functor(); - let rt_stub = reg_type_into_functor(r); + let rt_stub = reg_type_into_functor(r); functor!( "get_constant", @@ -624,17 +582,13 @@ impl FactInstruction { } &FactInstruction::GetList(lvl, r) => { let lvl_stub = lvl.into_functor(); - let rt_stub = reg_type_into_functor(r); + let rt_stub = reg_type_into_functor(r); - functor!( - "get_list", - [aux(h, 0), aux(h, 1)], - [lvl_stub, rt_stub] - ) + functor!("get_list", [aux(h, 0), aux(h, 1)], [lvl_stub, rt_stub]) } &FactInstruction::GetPartialString(lvl, ref s, r, has_tail) => { let lvl_stub = lvl.into_functor(); - let rt_stub = reg_type_into_functor(r); + let rt_stub = reg_type_into_functor(r); functor!( "get_partial_string", @@ -654,20 +608,12 @@ impl FactInstruction { &FactInstruction::GetValue(r, arg) => { let rt_stub = reg_type_into_functor(r); - functor!( - "get_value", - [aux(h, 0), integer(arg)], - [rt_stub] - ) + functor!("get_value", [aux(h, 0), integer(arg)], [rt_stub]) } &FactInstruction::GetVariable(r, arg) => { let rt_stub = reg_type_into_functor(r); - functor!( - "get_variable", - [aux(h, 0), integer(arg)], - [rt_stub] - ) + functor!("get_variable", [aux(h, 0), integer(arg)], [rt_stub]) } &FactInstruction::UnifyConstant(ref c) => { functor!("unify_constant", [constant(h, c)], []) @@ -675,29 +621,17 @@ impl FactInstruction { &FactInstruction::UnifyLocalValue(r) => { let rt_stub = reg_type_into_functor(r); - functor!( - "unify_local_value", - [aux(h, 0)], - [rt_stub] - ) + functor!("unify_local_value", [aux(h, 0)], [rt_stub]) } &FactInstruction::UnifyVariable(r) => { let rt_stub = reg_type_into_functor(r); - functor!( - "unify_variable", - [aux(h, 0)], - [rt_stub] - ) + functor!("unify_variable", [aux(h, 0)], [rt_stub]) } &FactInstruction::UnifyValue(r) => { let rt_stub = reg_type_into_functor(r); - functor!( - "unify_value", - [aux(h, 0)], - [rt_stub] - ) + functor!("unify_value", [aux(h, 0)], [rt_stub]) } &FactInstruction::UnifyVoid(vars) => { functor!("unify_void", [integer(vars)]) @@ -726,13 +660,12 @@ pub enum QueryInstruction { impl QueryInstruction { pub fn to_functor(&self, h: usize) -> MachineStub { match self { - &QueryInstruction::PutUnsafeValue(norm, arg) => functor!( - "put_unsafe_value", - [integer(norm), integer(arg)] - ), + &QueryInstruction::PutUnsafeValue(norm, arg) => { + functor!("put_unsafe_value", [integer(norm), integer(arg)]) + } &QueryInstruction::PutConstant(lvl, ref c, r) => { let lvl_stub = lvl.into_functor(); - let rt_stub = reg_type_into_functor(r); + let rt_stub = reg_type_into_functor(r); functor!( "put_constant", @@ -742,17 +675,13 @@ impl QueryInstruction { } &QueryInstruction::PutList(lvl, r) => { let lvl_stub = lvl.into_functor(); - let rt_stub = reg_type_into_functor(r); + let rt_stub = reg_type_into_functor(r); - functor!( - "put_list", - [aux(h, 0), aux(h, 1)], - [lvl_stub, rt_stub] - ) + functor!("put_list", [aux(h, 0), aux(h, 1)], [lvl_stub, rt_stub]) } &QueryInstruction::PutPartialString(lvl, ref s, r, has_tail) => { let lvl_stub = lvl.into_functor(); - let rt_stub = reg_type_into_functor(r); + let rt_stub = reg_type_into_functor(r); functor!( "put_partial_string", @@ -772,29 +701,17 @@ impl QueryInstruction { &QueryInstruction::PutValue(r, arg) => { let rt_stub = reg_type_into_functor(r); - functor!( - "put_value", - [aux(h, 0), integer(arg)], - [rt_stub] - ) + functor!("put_value", [aux(h, 0), integer(arg)], [rt_stub]) } &QueryInstruction::GetVariable(r, arg) => { let rt_stub = reg_type_into_functor(r); - functor!( - "get_variable", - [aux(h, 0), integer(arg)], - [rt_stub] - ) + functor!("get_variable", [aux(h, 0), integer(arg)], [rt_stub]) } &QueryInstruction::PutVariable(r, arg) => { let rt_stub = reg_type_into_functor(r); - functor!( - "put_variable", - [aux(h, 0), integer(arg)], - [rt_stub] - ) + functor!("put_variable", [aux(h, 0), integer(arg)], [rt_stub]) } &QueryInstruction::SetConstant(ref c) => { functor!("set_constant", [constant(h, c)], []) @@ -802,29 +719,17 @@ impl QueryInstruction { &QueryInstruction::SetLocalValue(r) => { let rt_stub = reg_type_into_functor(r); - functor!( - "set_local_value", - [aux(h, 0)], - [rt_stub] - ) + functor!("set_local_value", [aux(h, 0)], [rt_stub]) } &QueryInstruction::SetVariable(r) => { let rt_stub = reg_type_into_functor(r); - functor!( - "set_variable", - [aux(h, 0)], - [rt_stub] - ) + functor!("set_variable", [aux(h, 0)], [rt_stub]) } &QueryInstruction::SetValue(r) => { let rt_stub = reg_type_into_functor(r); - functor!( - "set_value", - [aux(h, 0)], - [rt_stub] - ) + functor!("set_value", [aux(h, 0)], [rt_stub]) } &QueryInstruction::SetVoid(vars) => { functor!("set_void", [integer(vars)]) diff --git a/src/iterators.rs b/src/iterators.rs index a3b5956b..ce3733ec 100644 --- a/src/iterators.rs +++ b/src/iterators.rs @@ -1,4 +1,5 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::rc_atom; use crate::clause_types::*; use crate::forms::*; @@ -25,11 +26,11 @@ impl<'a> TermRef<'a> { pub fn level(self) -> Level { match self { TermRef::AnonVar(lvl) - | TermRef::Cons(lvl, ..) - | TermRef::Constant(lvl, ..) - | TermRef::Var(lvl, ..) - | TermRef::Clause(lvl, ..) => lvl, - | TermRef::PartialString(lvl, ..) => lvl, + | TermRef::Cons(lvl, ..) + | TermRef::Constant(lvl, ..) + | TermRef::Var(lvl, ..) + | TermRef::Clause(lvl, ..) => lvl, + TermRef::PartialString(lvl, ..) => lvl, } } } @@ -51,23 +52,16 @@ pub enum TermIterState<'a> { Var(Level, &'a Cell, Rc), } -fn is_partial_string<'a>( - head: &'a Term, - mut tail: &'a Term, -) -> Option<(String, Option<&'a Term>)> -{ - let mut string = - match head { - &Term::Constant(_, Constant::Atom(ref atom, _)) if atom.is_char() => { - atom.as_str().chars().next().unwrap().to_string() - } - &Term::Constant(_, Constant::Char(c)) => { - c.to_string() - } - _ => { - return None; - } - }; +fn is_partial_string<'a>(head: &'a Term, mut tail: &'a Term) -> Option<(String, Option<&'a Term>)> { + let mut string = match head { + &Term::Constant(_, Constant::Atom(ref atom, _)) if atom.is_char() => { + atom.as_str().chars().next().unwrap().to_string() + } + &Term::Constant(_, Constant::Char(c)) => c.to_string(), + _ => { + return None; + } + }; while let Term::Cons(_, ref head, ref succ) = tail { match head.as_ref() { @@ -105,9 +99,7 @@ fn is_partial_string<'a>( impl<'a> TermIterState<'a> { pub fn subterm_to_state(lvl: Level, term: &'a Term) -> TermIterState<'a> { match term { - &Term::AnonVar => { - TermIterState::AnonVar(lvl) - } + &Term::AnonVar => TermIterState::AnonVar(lvl), &Term::Clause(ref cell, ref name, ref subterms, ref spec) => { let ct = if let Some(spec) = spec { ClauseType::Op(name.clone(), spec.clone(), CodeIndex::default()) @@ -120,12 +112,8 @@ impl<'a> TermIterState<'a> { &Term::Cons(ref cell, ref head, ref tail) => { TermIterState::InitialCons(lvl, cell, head.as_ref(), tail.as_ref()) } - &Term::Constant(ref cell, ref constant) => { - TermIterState::Constant(lvl, cell, constant) - } - &Term::Var(ref cell, ref var) => { - TermIterState::Var(lvl, cell, var.clone()) - } + &Term::Constant(ref cell, ref constant) => TermIterState::Constant(lvl, cell, constant), + &Term::Var(ref cell, ref var) => TermIterState::Var(lvl, cell, var.clone()), } } } @@ -175,8 +163,7 @@ impl<'a> QueryIterator<'a> { state_stack: vec![], } } - &Term::Var(ref cell, ref var) => - TermIterState::Var(Level::Root, cell, (*var).clone()), + &Term::Var(ref cell, ref var) => TermIterState::Var(Level::Root, cell, (*var).clone()), }; QueryIterator { @@ -265,18 +252,15 @@ impl<'a> Iterator for QueryIterator<'a> { } TermIterState::InitialCons(lvl, cell, head, tail) => { if let Some((string, tail)) = is_partial_string(head, tail) { - self.state_stack.push(TermIterState::PartialString( - lvl, - cell, - string, - tail, - )); + self.state_stack + .push(TermIterState::PartialString(lvl, cell, string, tail)); if let Some(tail) = tail { self.push_subterm(lvl.child_level(), tail); } } else { - self.state_stack.push(TermIterState::FinalCons(lvl, cell, head, tail)); + self.state_stack + .push(TermIterState::FinalCons(lvl, cell, head, tail)); self.push_subterm(lvl.child_level(), tail); self.push_subterm(lvl.child_level(), head); @@ -309,7 +293,8 @@ pub struct FactIterator<'a> { impl<'a> FactIterator<'a> { fn push_subterm(&mut self, lvl: Level, term: &'a Term) { - self.state_queue.push_back(TermIterState::subterm_to_state(lvl, term)); + self.state_queue + .push_back(TermIterState::subterm_to_state(lvl, term)); } pub fn from_rule_head_clause(terms: &'a Vec>) -> Self { @@ -393,8 +378,7 @@ impl<'a> Iterator for FactIterator<'a> { TermIterState::Var(lvl, cell, var) => { return Some(TermRef::Var(lvl, cell, var)); } - _ => { - } + _ => {} } } @@ -481,16 +465,16 @@ impl<'a> ChunkedIterator<'a> { } })) } -/* - pub fn from_term_sequence(terms: &'a [QueryTerm]) -> Self { - ChunkedIterator { - chunk_num: 0, - iter: Box::new(terms.iter().map(|t| ChunkedTerm::BodyTerm(t))), - deep_cut_encountered: false, - cut_var_in_head: false, + /* + pub fn from_term_sequence(terms: &'a [QueryTerm]) -> Self { + ChunkedIterator { + chunk_num: 0, + iter: Box::new(terms.iter().map(|t| ChunkedTerm::BodyTerm(t))), + deep_cut_encountered: false, + cut_var_in_head: false, + } } - } -*/ + */ pub fn from_rule_body(p1: &'a QueryTerm, clauses: &'a Vec) -> Self { let inner_iter = Box::new(once(ChunkedTerm::BodyTerm(p1))); let iter = inner_iter.chain(clauses.iter().map(|t| ChunkedTerm::BodyTerm(t))); diff --git a/src/machine/arithmetic_ops.rs b/src/machine/arithmetic_ops.rs index 0c8fb8ff..aee346a2 100644 --- a/src/machine/arithmetic_ops.rs +++ b/src/machine/arithmetic_ops.rs @@ -1,6 +1,7 @@ use crate::divrem::*; use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::clause_name; use crate::arithmetic::*; use crate::clause_types::*; @@ -19,19 +20,16 @@ use std::rc::Rc; #[macro_export] macro_rules! try_numeric_result { - ($s: ident, $e: expr, $caller: expr) => ( + ($s: ident, $e: expr, $caller: expr) => { match $e { - Ok(val) => { - Ok(val) - } + Ok(val) => Ok(val), Err(e) => { - let caller_copy = - $caller.iter().map(|v| v.context_free_clone()).collect(); + let caller_copy = $caller.iter().map(|v| v.context_free_clone()).collect(); Err($s.error_form(MachineError::evaluation_error(e), caller_copy)) } } - ); + }; } fn isize_gcd(n1: isize, n2: isize) -> Option { @@ -83,52 +81,29 @@ fn isize_gcd(n1: isize, n2: isize) -> Option { } impl MachineState { - pub(crate) - fn get_number(&mut self, at: &ArithmeticTerm) -> Result { + pub(crate) fn get_number(&mut self, at: &ArithmeticTerm) -> Result { match at { - &ArithmeticTerm::Reg(r) => { - self.arith_eval_by_metacall(r) - } - &ArithmeticTerm::Interm(i) => Ok(mem::replace( - &mut self.interms[i - 1], - Number::Fixnum(0), - )), - &ArithmeticTerm::Number(ref n) => { - Ok(n.clone()) + &ArithmeticTerm::Reg(r) => self.arith_eval_by_metacall(r), + &ArithmeticTerm::Interm(i) => { + Ok(mem::replace(&mut self.interms[i - 1], Number::Fixnum(0))) } + &ArithmeticTerm::Number(ref n) => Ok(n.clone()), } } - pub(super) - fn rational_from_number( - &self, - n: Number, - ) -> Result, MachineError> { + pub(super) fn rational_from_number(&self, n: Number) -> Result, MachineError> { match n { - Number::Fixnum(n) => { - Ok(Rc::new(Rational::from(n))) - } - Number::Rational(r) => { - Ok(r) - } - Number::Float(OrderedFloat(f)) => { - match Rational::from_f64(f) { - Some(r) => { - Ok(Rc::new(r)) - } - None => { - Err(MachineError::instantiation_error()) - } - } - } - Number::Integer(n) => { - Ok(Rc::new(Rational::from(&*n))) - } + Number::Fixnum(n) => Ok(Rc::new(Rational::from(n))), + Number::Rational(r) => Ok(r), + Number::Float(OrderedFloat(f)) => match Rational::from_f64(f) { + Some(r) => Ok(Rc::new(r)), + None => Err(MachineError::instantiation_error()), + }, + Number::Integer(n) => Ok(Rc::new(Rational::from(&*n))), } } - pub(crate) - fn get_rational( + pub(crate) fn get_rational( &mut self, at: &ArithmeticTerm, caller: MachineStub, @@ -137,12 +112,11 @@ impl MachineState { match self.rational_from_number(n) { Ok(r) => Ok((r, caller)), - Err(e) => Err(self.error_form(e, caller)) + Err(e) => Err(self.error_form(e, caller)), } } - pub(crate) - fn arith_eval_by_metacall(&self, r: RegType) -> Result { + pub(crate) fn arith_eval_by_metacall(&self, r: RegType) -> Result { let caller = MachineError::functor_stub(clause_name!("is"), 2); let mut interms: Vec = Vec::with_capacity(64); @@ -163,9 +137,8 @@ impl MachineState { "min" => interms.push(self.min(a1, a2)?), "rdiv" => { let r1 = self.rational_from_number(a1); - let r2 = r1.and_then(|r1| { - self.rational_from_number(a2).map(|r2| (r1, r2)) - }); + let r2 = + r1.and_then(|r1| self.rational_from_number(a2).map(|r2| (r1, r2))); match r2 { Ok((r1, r2)) => { @@ -242,18 +215,12 @@ impl MachineState { &HeapCellValue::Addr(Addr::Fixnum(n)) => { interms.push(Number::Fixnum(n)); } - &HeapCellValue::Addr(Addr::Float(n)) => { - interms.push(Number::Float(n)) - } - &HeapCellValue::Integer(ref n) => { - interms.push(Number::Integer(n.clone())) - } + &HeapCellValue::Addr(Addr::Float(n)) => interms.push(Number::Float(n)), + &HeapCellValue::Integer(ref n) => interms.push(Number::Integer(n.clone())), &HeapCellValue::Addr(Addr::Usize(n)) => { interms.push(Number::Integer(Rc::new(Integer::from(n)))); } - &HeapCellValue::Rational(ref n) => { - interms.push(Number::Rational(n.clone())) - } + &HeapCellValue::Rational(ref n) => interms.push(Number::Rational(n.clone())), &HeapCellValue::Atom(ref name, _) if name.as_str() == "pi" => { interms.push(Number::Float(OrderedFloat(f64::consts::PI))) } @@ -282,10 +249,7 @@ impl MachineState { )); } &HeapCellValue::Addr(addr) if addr.is_ref() => { - return Err(self.error_form( - MachineError::instantiation_error(), - caller, - )); + return Err(self.error_form(MachineError::instantiation_error(), caller)); } val => { return Err(self.type_error( @@ -301,8 +265,7 @@ impl MachineState { Ok(interms.pop().unwrap()) } - pub(crate) - fn rdiv(&self, r1: Rc, r2: Rc) -> Result { + pub(crate) fn rdiv(&self, r1: Rc, r2: Rc) -> Result { if &*r2 == &0 { let stub = MachineError::functor_stub(clause_name!("(rdiv)"), 2); Err(self.error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) @@ -311,27 +274,21 @@ impl MachineState { } } - pub(crate) - fn int_floor_div(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn int_floor_div(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(div)"), 2); let modulus = self.modulus(n1.clone(), n2.clone())?; self.idiv(try_numeric_result!(self, n1 - modulus, stub)?, n2) } - pub(crate) - fn idiv(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn idiv(&self, n1: Number, n2: Number) -> Result { match (n1, n2) { (Number::Fixnum(n1), Number::Fixnum(n2)) => { if n2 == 0 { let stub = MachineError::functor_stub(clause_name!("(//)"), 2); - Err(self.error_form( - MachineError::evaluation_error( - EvalError::ZeroDivisor - ), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { if let Some(result) = n1.checked_div(n2) { Ok(Number::from(result)) @@ -347,12 +304,8 @@ impl MachineState { if &*n2 == &0 { let stub = MachineError::functor_stub(clause_name!("(//)"), 2); - Err(self.error_form( - MachineError::evaluation_error( - EvalError::ZeroDivisor - ), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { Ok(Number::from(Integer::from(n1) / &*n2)) } @@ -361,12 +314,8 @@ impl MachineState { if n1 == 0 { let stub = MachineError::functor_stub(clause_name!("(//)"), 2); - Err(self.error_form( - MachineError::evaluation_error( - EvalError::ZeroDivisor - ), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { Ok(Number::from(&*n2 / Integer::from(n1))) } @@ -375,25 +324,19 @@ impl MachineState { if &*n2 == &0 { let stub = MachineError::functor_stub(clause_name!("(//)"), 2); - Err(self.error_form( - MachineError::evaluation_error( - EvalError::ZeroDivisor - ), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { - Ok(Number::from(<(Integer, Integer)>::from(n1.div_rem_ref(&*n2)).0)) + Ok(Number::from( + <(Integer, Integer)>::from(n1.div_rem_ref(&*n2)).0, + )) } } (Number::Fixnum(_), n2) | (Number::Integer(_), n2) => { let stub = MachineError::functor_stub(clause_name!("(//)"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), stub, )) } @@ -401,19 +344,14 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("(//)"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), stub, )) } } } - pub(crate) - fn div(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn div(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(/)"), 2); if n2.is_zero() { @@ -423,8 +361,7 @@ impl MachineState { } } - pub(crate) - fn atan2(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn atan2(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("is"), 2); if n1.is_zero() && n2.is_zero() { @@ -437,8 +374,7 @@ impl MachineState { } } - pub(crate) - fn int_pow(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn int_pow(&self, n1: Number, n2: Number) -> Result { if n1.is_zero() && n2.is_negative() { let stub = MachineError::functor_stub(clause_name!("is"), 2); return Err(self.error_form(MachineError::evaluation_error(EvalError::Undefined), stub)); @@ -451,11 +387,7 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("^"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Float, - n - ), + MachineError::type_error(self.heap.h(), ValidType::Float, n), stub, )) } else { @@ -477,11 +409,7 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("^"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Float, - n - ), + MachineError::type_error(self.heap.h(), ValidType::Float, n), stub, )) } else { @@ -495,11 +423,7 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("^"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Float, - n - ), + MachineError::type_error(self.heap.h(), ValidType::Float, n), stub, )) } else { @@ -513,11 +437,7 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("^"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Float, - n - ), + MachineError::type_error(self.heap.h(), ValidType::Float, n), stub, )) } else { @@ -548,8 +468,7 @@ impl MachineState { } } - pub(crate) - fn gcd(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn gcd(&self, n1: Number, n2: Number) -> Result { match (n1, n2) { (Number::Fixnum(n1), Number::Fixnum(n2)) => { if let Some(result) = isize_gcd(n1, n2) { @@ -558,8 +477,8 @@ impl MachineState { Ok(Number::from(Integer::from(n1).gcd(&Integer::from(n2)))) } } - (Number::Fixnum(n1), Number::Integer(n2)) | - (Number::Integer(n2), Number::Fixnum(n1)) => { + (Number::Fixnum(n1), Number::Integer(n2)) + | (Number::Integer(n2), Number::Fixnum(n1)) => { let n1 = Integer::from(n1); Ok(Number::from(Integer::from(n2.gcd_ref(&n1)))) } @@ -571,11 +490,7 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("gcd"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n), stub, )) } @@ -584,19 +499,14 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("gcd"), 2); Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n), stub, )) } } } - pub(crate) - fn float_pow(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn float_pow(&self, n1: Number, n2: Number) -> Result { let f1 = result_f(&n1, rnd_f); let f2 = result_f(&n2, rnd_f); @@ -612,8 +522,12 @@ impl MachineState { )?))) } - pub(crate) - fn pow(&self, n1: Number, n2: Number, culprit: &'static str) -> Result { + pub(crate) fn pow( + &self, + n1: Number, + n2: Number, + culprit: &'static str, + ) -> Result { if n2.is_negative() && n1.is_zero() { let stub = MachineError::functor_stub(clause_name!(culprit), 2); return Err(self.error_form(MachineError::evaluation_error(EvalError::Undefined), stub)); @@ -623,8 +537,11 @@ impl MachineState { } #[inline] - pub(crate) - fn unary_float_fn_template(&self, n1: Number, f: FloatFn) -> Result + pub(crate) fn unary_float_fn_template( + &self, + n1: Number, + f: FloatFn, + ) -> Result where FloatFn: Fn(f64) -> f64, { @@ -637,56 +554,47 @@ impl MachineState { } #[inline] - pub(crate) - fn sin(&self, n1: Number) -> Result { + pub(crate) fn sin(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.sin()) } #[inline] - pub(crate) - fn cos(&self, n1: Number) -> Result { + pub(crate) fn cos(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.cos()) } #[inline] - pub(crate) - fn tan(&self, n1: Number) -> Result { + pub(crate) fn tan(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.tan()) } #[inline] - pub(crate) - fn log(&self, n1: Number) -> Result { + pub(crate) fn log(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.log(f64::consts::E)) } #[inline] - pub(crate) - fn exp(&self, n1: Number) -> Result { + pub(crate) fn exp(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.exp()) } #[inline] - pub(crate) - fn asin(&self, n1: Number) -> Result { + pub(crate) fn asin(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.asin()) } #[inline] - pub(crate) - fn acos(&self, n1: Number) -> Result { + pub(crate) fn acos(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.acos()) } #[inline] - pub(crate) - fn atan(&self, n1: Number) -> Result { + pub(crate) fn atan(&self, n1: Number) -> Result { self.unary_float_fn_template(n1, |f| f.atan()) } #[inline] - pub(crate) - fn sqrt(&self, n1: Number) -> Result { + pub(crate) fn sqrt(&self, n1: Number) -> Result { if n1.is_negative() { let stub = MachineError::functor_stub(clause_name!("is"), 2); return Err(self.error_form(MachineError::evaluation_error(EvalError::Undefined), stub)); @@ -696,27 +604,23 @@ impl MachineState { } #[inline] - pub(crate) - fn float(&self, n: Number) -> Result { + pub(crate) fn float(&self, n: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("is"), 2); try_numeric_result!(self, result_f(&n, rnd_f), stub) } #[inline] - pub(crate) - fn floor(&self, n1: Number) -> Number { + pub(crate) fn floor(&self, n1: Number) -> Number { rnd_i(&n1).to_owned() } #[inline] - pub(crate) - fn ceiling(&self, n1: Number) -> Number { + pub(crate) fn ceiling(&self, n1: Number) -> Number { -self.floor(-n1) } #[inline] - pub(crate) - fn truncate(&self, n: Number) -> Number { + pub(crate) fn truncate(&self, n: Number) -> Number { if n.is_negative() { -self.floor(n.abs()) } else { @@ -724,8 +628,7 @@ impl MachineState { } } - pub(crate) - fn round(&self, n: Number) -> Result { + pub(crate) fn round(&self, n: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("is"), 2); let result = n + Number::Float(OrderedFloat(0.5f64)); @@ -734,8 +637,7 @@ impl MachineState { Ok(self.floor(result)) } - pub(crate) - fn shr(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn shr(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(>>)"), 2); match (n1, n2) { @@ -756,38 +658,26 @@ impl MachineState { _ => Ok(Number::from(n1 >> u32::max_value())), } } - (Number::Integer(n1), Number::Fixnum(n2)) => { - match u32::try_from(n2) { - Ok(n2) => Ok(Number::from(Integer::from(&*n1 >> n2))), - _ => Ok(Number::from(Integer::from(&*n1 >> u32::max_value()))), - } - } - (Number::Integer(n1), Number::Integer(n2)) => - match n2.to_u32() { - Some(n2) => Ok(Number::from(Integer::from(&*n1 >> n2))), - _ => Ok(Number::from(Integer::from(&*n1 >> u32::max_value()))), - }, + (Number::Integer(n1), Number::Fixnum(n2)) => match u32::try_from(n2) { + Ok(n2) => Ok(Number::from(Integer::from(&*n1 >> n2))), + _ => Ok(Number::from(Integer::from(&*n1 >> u32::max_value()))), + }, + (Number::Integer(n1), Number::Integer(n2)) => match n2.to_u32() { + Some(n2) => Ok(Number::from(Integer::from(&*n1 >> n2))), + _ => Ok(Number::from(Integer::from(&*n1 >> u32::max_value()))), + }, (Number::Integer(_), n2) => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), stub, )), (n1, _) => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), stub, )), } } - pub(crate) - fn shl(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn shl(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(<<)"), 2); match (n1, n2) { @@ -808,263 +698,181 @@ impl MachineState { _ => Ok(Number::from(n1 << u32::max_value())), } } - (Number::Integer(n1), Number::Fixnum(n2)) => { - match u32::try_from(n2) { - Ok(n2) => Ok(Number::from(Integer::from(&*n1 << n2))), - _ => Ok(Number::from(Integer::from(&*n1 << u32::max_value()))), - } - } + (Number::Integer(n1), Number::Fixnum(n2)) => match u32::try_from(n2) { + Ok(n2) => Ok(Number::from(Integer::from(&*n1 << n2))), + _ => Ok(Number::from(Integer::from(&*n1 << u32::max_value()))), + }, (Number::Integer(n1), Number::Integer(n2)) => match n2.to_u32() { Some(n2) => Ok(Number::from(Integer::from(&*n1 << n2))), _ => Ok(Number::from(Integer::from(&*n1 << u32::max_value()))), }, (Number::Integer(_), n2) => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), stub, )), (n1, _) => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), stub, )), } } - pub(crate) - fn bitwise_complement(&self, n1: Number) -> Result { + pub(crate) fn bitwise_complement(&self, n1: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(\\)"), 2); match n1 { Number::Fixnum(n) => Ok(Number::Fixnum(!n)), Number::Integer(n1) => Ok(Number::from(Integer::from(!&*n1))), _ => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), stub, )), } } - pub(crate) - fn xor(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn xor(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(xor)"), 2); match (n1, n2) { - (Number::Fixnum(n1), Number::Fixnum(n2)) => { - Ok(Number::from(n1 ^ n2)) - } + (Number::Fixnum(n1), Number::Fixnum(n2)) => Ok(Number::from(n1 ^ n2)), (Number::Fixnum(n1), Number::Integer(n2)) => { let n1 = Integer::from(n1); Ok(Number::from(n1 ^ &*n2)) } - (Number::Integer(n1), Number::Fixnum(n2)) => { - Ok(Number::from(&*n1 ^ Integer::from(n2))) - } + (Number::Integer(n1), Number::Fixnum(n2)) => Ok(Number::from(&*n1 ^ Integer::from(n2))), (Number::Integer(n1), Number::Integer(n2)) => { Ok(Number::from(Integer::from(&*n1 ^ &*n2))) } - (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2 - ), - stub, - )) - } - (n1, _) => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1 - ), - stub, - )) - } - } - } - - pub(crate) - fn and(&self, n1: Number, n2: Number) -> Result { - let stub = MachineError::functor_stub(clause_name!("(/\\)"), 2); - - match (n1, n2) { - (Number::Fixnum(n1), Number::Fixnum(n2)) => { - Ok(Number::from(n1 & n2)) - } - (Number::Fixnum(n1), Number::Integer(n2)) => { - let n1 = Integer::from(n1); - Ok(Number::from(n1 & &*n2)) - } - (Number::Integer(n1), Number::Fixnum(n2)) => { - Ok(Number::from(&*n1 & Integer::from(n2))) - } - (Number::Integer(n1), Number::Integer(n2)) => { - Ok(Number::from(Integer::from(&*n1 & &*n2))) - } - (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2, - ), - stub, - )) - } + (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), + stub, + )), (n1, _) => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), stub, )), } } - pub(crate) - fn or(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn and(&self, n1: Number, n2: Number) -> Result { + let stub = MachineError::functor_stub(clause_name!("(/\\)"), 2); + + match (n1, n2) { + (Number::Fixnum(n1), Number::Fixnum(n2)) => Ok(Number::from(n1 & n2)), + (Number::Fixnum(n1), Number::Integer(n2)) => { + let n1 = Integer::from(n1); + Ok(Number::from(n1 & &*n2)) + } + (Number::Integer(n1), Number::Fixnum(n2)) => Ok(Number::from(&*n1 & Integer::from(n2))), + (Number::Integer(n1), Number::Integer(n2)) => { + Ok(Number::from(Integer::from(&*n1 & &*n2))) + } + (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), + stub, + )), + (n1, _) => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), + stub, + )), + } + } + + pub(crate) fn or(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(\\/)"), 2); match (n1, n2) { - (Number::Fixnum(n1), Number::Fixnum(n2)) => { - Ok(Number::from(n1 | n2)) - } + (Number::Fixnum(n1), Number::Fixnum(n2)) => Ok(Number::from(n1 | n2)), (Number::Fixnum(n1), Number::Integer(n2)) => { let n1 = Integer::from(n1); Ok(Number::from(n1 | &*n2)) } - (Number::Integer(n1), Number::Fixnum(n2)) => { - Ok(Number::from(&*n1 | Integer::from(n2))) - } + (Number::Integer(n1), Number::Fixnum(n2)) => Ok(Number::from(&*n1 | Integer::from(n2))), (Number::Integer(n1), Number::Integer(n2)) => { Ok(Number::from(Integer::from(&*n1 | &*n2))) } - (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2, - ), - stub, - )) - } - (n1, _) => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1 - ), - stub, - )) - } + (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), + stub, + )), + (n1, _) => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), + stub, + )), } } - pub(crate) - fn modulus(&self, x: Number, y: Number) -> Result { + pub(crate) fn modulus(&self, x: Number, y: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(mod)"), 2); match (x, y) { (Number::Fixnum(n1), Number::Fixnum(n2)) => { if n2 == 0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { Ok(Number::from(n1.rem_floor(n2))) } } (Number::Fixnum(n1), Number::Integer(n2)) => { if &*n2 == &0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { let n1 = Integer::from(n1); - Ok(Number::from(<(Integer, Integer)>::from(n1.div_rem_floor_ref(&*n2)).1)) + Ok(Number::from( + <(Integer, Integer)>::from(n1.div_rem_floor_ref(&*n2)).1, + )) } } (Number::Integer(n1), Number::Fixnum(n2)) => { if n2 == 0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { let n2 = Integer::from(n2); - Ok(Number::from(<(Integer, Integer)>::from(n1.div_rem_floor_ref(&n2)).1)) + Ok(Number::from( + <(Integer, Integer)>::from(n1.div_rem_floor_ref(&n2)).1, + )) } } (Number::Integer(x), Number::Integer(y)) => { if &*y == &0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { - Ok(Number::from(<(Integer, Integer)>::from(x.div_rem_floor_ref(&*y)).1)) + Ok(Number::from( + <(Integer, Integer)>::from(x.div_rem_floor_ref(&*y)).1, + )) } } - (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2, - ), - stub, - )) - } + (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), + stub, + )), (n1, _) => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), stub, )), } } - pub(crate) - fn remainder(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn remainder(&self, n1: Number, n2: Number) -> Result { let stub = MachineError::functor_stub(clause_name!("(rem)"), 2); match (n1, n2) { (Number::Fixnum(n1), Number::Fixnum(n2)) => { if n2 == 0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { Ok(Number::from(n1 % n2)) } } (Number::Fixnum(n1), Number::Integer(n2)) => { if &*n2 == &0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { let n1 = Integer::from(n1); Ok(Number::from(n1 % &*n2)) @@ -1072,10 +880,8 @@ impl MachineState { } (Number::Integer(n1), Number::Fixnum(n2)) => { if n2 == 0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { let n2 = Integer::from(n2); Ok(Number::from(&*n1 % n2)) @@ -1083,37 +889,24 @@ impl MachineState { } (Number::Integer(n1), Number::Integer(n2)) => { if &*n2 == &0 { - Err(self.error_form( - MachineError::evaluation_error(EvalError::ZeroDivisor), - stub, - )) + Err(self + .error_form(MachineError::evaluation_error(EvalError::ZeroDivisor), stub)) } else { Ok(Number::from(Integer::from(&*n1 % &*n2))) } } - (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n2, - ), - stub, - )) - } + (Number::Integer(_), n2) | (Number::Fixnum(_), n2) => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, n2), + stub, + )), (n1, _) => Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - n1, - ), + MachineError::type_error(self.heap.h(), ValidType::Integer, n1), stub, )), } } - pub(crate) - fn max(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn max(&self, n1: Number, n2: Number) -> Result { match (n1, n2) { (Number::Fixnum(n1), Number::Fixnum(n2)) => { if n1 > n2 { @@ -1154,8 +947,7 @@ impl MachineState { } } - pub(crate) - fn min(&self, n1: Number, n2: Number) -> Result { + pub(crate) fn min(&self, n1: Number, n2: Number) -> Result { match (n1, n2) { (Number::Fixnum(n1), Number::Fixnum(n2)) => { if n1 < n2 { @@ -1196,8 +988,7 @@ impl MachineState { } } - pub(crate) - fn sign(&self, n: Number) -> Number { + pub(crate) fn sign(&self, n: Number) -> Number { if n.is_positive() { Number::from(1) } else if n.is_negative() { diff --git a/src/machine/attributed_variables.rs b/src/machine/attributed_variables.rs index 790114fc..dff8e90e 100644 --- a/src/machine/attributed_variables.rs +++ b/src/machine/attributed_variables.rs @@ -1,5 +1,6 @@ use crate::heap_iter::*; use crate::machine::*; +use crate::prolog_parser_rebis::temp_v; use crate::indexmap::IndexSet; @@ -20,8 +21,7 @@ pub(super) struct AttrVarInitializer { } impl AttrVarInitializer { - pub(super) - fn new(verify_attrs_loc: usize, project_attrs_loc: usize) -> Self { + pub(super) fn new(verify_attrs_loc: usize, project_attrs_loc: usize) -> Self { AttrVarInitializer { attribute_goals: vec![], attr_var_queue: vec![], @@ -34,24 +34,21 @@ impl AttrVarInitializer { } #[inline] - pub(super) - fn reset(&mut self) { - self.attribute_goals.clear(); + pub(super) fn reset(&mut self) { + self.attribute_goals.clear(); self.attr_var_queue.clear(); self.bindings.clear(); } #[inline] - pub(super) - fn backtrack(&mut self, queue_b: usize, bindings_b: usize) { + pub(super) fn backtrack(&mut self, queue_b: usize, bindings_b: usize) { self.attr_var_queue.truncate(queue_b); self.bindings.truncate(bindings_b); } } impl MachineState { - pub(super) - fn push_attr_var_binding(&mut self, h: usize, addr: Addr) { + pub(super) fn push_attr_var_binding(&mut self, h: usize, addr: Addr) { if self.attr_var_init.bindings.is_empty() { self.attr_var_init.instigating_p = self.p.local(); @@ -79,7 +76,7 @@ impl MachineState { let iter = self .attr_var_init .bindings - .drain(0 ..) + .drain(0..) .map(|(_, addr)| HeapCellValue::Addr(addr)); let value_list_addr = Addr::HeapCell(self.heap.to_list(iter)); @@ -97,8 +94,7 @@ impl MachineState { self[temp_v!(2)] = value_list_addr; } - pub(super) - fn gather_attr_vars_created_since(&self, b: usize) -> IntoIter { + pub(super) fn gather_attr_vars_created_since(&self, b: usize) -> IntoIter { let mut attr_vars: Vec<_> = self.attr_var_init.attr_var_queue[b..] .iter() .filter_map(|h| match self.store(self.deref(Addr::HeapCell(*h))) { @@ -107,29 +103,25 @@ impl MachineState { }) .collect(); - attr_vars.sort_unstable_by(|a1, a2| { - self.compare_term_test(a1, a2).unwrap_or(Ordering::Less) - }); + attr_vars + .sort_unstable_by(|a1, a2| self.compare_term_test(a1, a2).unwrap_or(Ordering::Less)); self.term_dedup(&mut attr_vars); attr_vars.into_iter() } - pub(super) - fn verify_attr_interrupt(&mut self, p: usize) { + pub(super) fn verify_attr_interrupt(&mut self, p: usize) { self.allocate(self.num_of_args + 2); let e = self.e; self.stack.index_and_frame_mut(e).prelude.interrupt_cp = self.attr_var_init.cp; - for i in 1 .. self.num_of_args + 1 { + for i in 1..self.num_of_args + 1 { self.stack.index_and_frame_mut(e)[i] = self[RegType::Temp(i)]; } - self.stack.index_and_frame_mut(e)[self.num_of_args + 1] = - Addr::CutPoint(self.b0); - self.stack.index_and_frame_mut(e)[self.num_of_args + 2] = - Addr::Usize(self.num_of_args); + self.stack.index_and_frame_mut(e)[self.num_of_args + 1] = Addr::CutPoint(self.b0); + self.stack.index_and_frame_mut(e)[self.num_of_args + 2] = Addr::Usize(self.num_of_args); self.verify_attributes(); @@ -138,9 +130,8 @@ impl MachineState { self.p = CodePtr::Local(LocalCodePtr::DirEntry(p)); } - pub(super) - fn attr_vars_of_term(&self, addr: Addr) -> Vec { - let mut seen_set = IndexSet::new(); + pub(super) fn attr_vars_of_term(&self, addr: Addr) -> Vec { + let mut seen_set = IndexSet::new(); let mut seen_vars = vec![]; let mut iter = self.acyclic_pre_order_iter(addr); diff --git a/src/machine/compile.rs b/src/machine/compile.rs index a9ab5108..766c117a 100644 --- a/src/machine/compile.rs +++ b/src/machine/compile.rs @@ -1,11 +1,13 @@ +use crate::prolog_parser_rebis::clause_name; + use crate::codegen::*; use crate::debray_allocator::*; use crate::indexing::{merge_clause_index, remove_index}; use crate::machine::load_state::set_code_index; -use crate::machine::loader::*; use crate::machine::load_state::LoadState; -use crate::machine::*; +use crate::machine::loader::*; use crate::machine::term_stream::*; +use crate::machine::*; use slice_deque::sdeq; @@ -18,20 +20,18 @@ struct StandaloneCompileResult { standalone_skeleton: PredicateSkeleton, } -pub(super) -fn bootstrapping_compile( +pub(super) fn bootstrapping_compile( stream: Stream, wam: &mut Machine, listing_src: ListingSource, ) -> Result<(), SessionError> { let stream = &mut parsing_stream(stream)?; - let term_stream = - BootstrappingTermStream::from_prolog_stream( - stream, - wam.machine_st.atom_tbl.clone(), - wam.machine_st.flags, - listing_src, - ); + let term_stream = BootstrappingTermStream::from_prolog_stream( + stream, + wam.machine_st.atom_tbl.clone(), + wam.machine_st.flags, + listing_src, + ); let loader = Loader::new(term_stream, wam); loader.load()?; @@ -40,25 +40,19 @@ fn bootstrapping_compile( } // throw errors if declaration or query found. -pub(super) -fn compile_relation( +pub(super) fn compile_relation( cg: &mut CodeGenerator, - tl: &TopLevel + tl: &TopLevel, ) -> Result { match tl { - &TopLevel::Declaration(_) | &TopLevel::Query(_) => - Err(CompilationError::ExpectedRel), - &TopLevel::Predicate(ref clauses) => - cg.compile_predicate(&clauses), - &TopLevel::Fact(ref fact, ..) => - Ok(cg.compile_fact(fact)), - &TopLevel::Rule(ref rule, ..) => - cg.compile_rule(rule), + &TopLevel::Declaration(_) | &TopLevel::Query(_) => Err(CompilationError::ExpectedRel), + &TopLevel::Predicate(ref clauses) => cg.compile_predicate(&clauses), + &TopLevel::Fact(ref fact, ..) => Ok(cg.compile_fact(fact)), + &TopLevel::Rule(ref rule, ..) => cg.compile_rule(rule), } } -pub(super) -fn compile_appendix( +pub(super) fn compile_appendix( code: &mut Code, queue: &VecDeque, jmp_by_locs: Vec, @@ -104,7 +98,7 @@ fn lower_bound_of_target_clause(skeleton: &PredicateSkeleton, target_pos: usize) return target_pos - 1; } - for index in (0 .. target_pos - 1).rev() { + for index in (0..target_pos - 1).rev() { let current_arg_num = skeleton.clauses[index].opt_arg_index_key.arg_num(); if current_arg_num == 0 || current_arg_num != arg_num { @@ -144,13 +138,9 @@ fn derelictize_try_me_else( retraction_info: &mut RetractionInfo, ) -> Option { match &mut code[index] { - Line::Choice(ChoiceInstruction::TryMeElse(0)) => { - None - } + Line::Choice(ChoiceInstruction::TryMeElse(0)) => None, Line::Choice(ChoiceInstruction::TryMeElse(ref mut offset)) => { - retraction_info.push_record( - RetractionRecord::ModifiedTryMeElse(index, *offset), - ); + retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(index, *offset)); Some(mem::replace(offset, 0)) } @@ -168,43 +158,41 @@ fn merge_indices( retraction_info: &mut RetractionInfo, ) { for clause_index in index_range { - if let Some(index_loc) = skeleton[clause_index].opt_arg_index_key.switch_on_term_loc() { + if let Some(index_loc) = skeleton[clause_index] + .opt_arg_index_key + .switch_on_term_loc() + { let clause_loc = find_inner_choice_instr(code, skeleton[clause_index].clause_start, index_loc); - let target_indexing_line = - to_indexing_line_mut(&mut code[target_index_loc]).unwrap(); + let target_indexing_line = to_indexing_line_mut(&mut code[target_index_loc]).unwrap(); - skeleton[clause_index].opt_arg_index_key.set_switch_on_term_loc(target_index_loc); + skeleton[clause_index] + .opt_arg_index_key + .set_switch_on_term_loc(target_index_loc); merge_clause_index( target_indexing_line, - &mut skeleton[0 .. clause_index + 1], + &mut skeleton[0..clause_index + 1], clause_loc, AppendOrPrepend::Append, ); - retraction_info.push_record( - RetractionRecord::AddedIndex( - skeleton[clause_index].opt_arg_index_key.clone(), - clause_loc, - ), - ); + retraction_info.push_record(RetractionRecord::AddedIndex( + skeleton[clause_index].opt_arg_index_key.clone(), + clause_loc, + )); } else { break; } } } -fn find_inner_choice_instr( - code: &Code, - mut index: usize, - index_loc: usize, -) -> usize { +fn find_inner_choice_instr(code: &Code, mut index: usize, index_loc: usize) -> usize { loop { match &code[index] { - Line::Choice(ChoiceInstruction::TryMeElse(o)) | - Line::Choice(ChoiceInstruction::RetryMeElse(o)) => { + Line::Choice(ChoiceInstruction::TryMeElse(o)) + | Line::Choice(ChoiceInstruction::RetryMeElse(o)) => { if *o > 0 { return index; } else { @@ -214,18 +202,14 @@ fn find_inner_choice_instr( Line::Choice(ChoiceInstruction::TrustMe(_)) => { return index; } - Line::IndexingCode(indexing_code) => { - match &indexing_code[0] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, v, ..) - ) => { - index += v; - } - _ => { - unreachable!(); - } + Line::IndexingCode(indexing_code) => match &indexing_code[0] { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, v, ..)) => { + index += v; } - } + _ => { + unreachable!(); + } + }, Line::Control(ControlInstruction::RevJmpBy(offset)) => { index -= offset; } @@ -250,8 +234,7 @@ fn remove_index_from_subsequence( if let Some(index_loc) = opt_arg_index_key.switch_on_term_loc() { let clause_start = find_inner_choice_instr(code, clause_start, index_loc); - let target_indexing_line = - to_indexing_line_mut(&mut code[index_loc]).unwrap(); + let target_indexing_line = to_indexing_line_mut(&mut code[index_loc]).unwrap(); let offset = clause_start - index_loc + 1; @@ -259,13 +242,11 @@ fn remove_index_from_subsequence( // TODO: this isn't sufficiently precise. The removed offset could // appear anywhere inside an Internal record. - retraction_info.push_record( - RetractionRecord::RemovedIndex( - index_loc, - opt_arg_index_key.clone(), - offset, - ), - ); + retraction_info.push_record(RetractionRecord::RemovedIndex( + index_loc, + opt_arg_index_key.clone(), + offset, + )); } } @@ -281,46 +262,40 @@ fn merge_indexed_subsequences( // instruction to TrustMe (or RetryMeElse), and derelict-ize // target_pos + 1's inner TryMeElse. - let inner_trust_me_loc = - skeleton.clauses[upper_lower_bound - 2].clause_start; + let inner_trust_me_loc = skeleton.clauses[upper_lower_bound - 2].clause_start; let inner_try_me_else_loc = find_inner_choice_instr( code, skeleton.clauses[upper_lower_bound].clause_start, - skeleton.clauses[upper_lower_bound].opt_arg_index_key - .switch_on_term_loc().unwrap(), + skeleton.clauses[upper_lower_bound] + .opt_arg_index_key + .switch_on_term_loc() + .unwrap(), ); match &mut code[inner_try_me_else_loc] { Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) => { - retraction_info.push_record( - RetractionRecord::ModifiedTryMeElse( - skeleton.clauses[upper_lower_bound].clause_start, - *o, - ), - ); + retraction_info.push_record(RetractionRecord::ModifiedTryMeElse( + skeleton.clauses[upper_lower_bound].clause_start, + *o, + )); match *o { 0 => { - code[inner_try_me_else_loc] = - Line::Choice(ChoiceInstruction::TrustMe(0)); + code[inner_try_me_else_loc] = Line::Choice(ChoiceInstruction::TrustMe(0)); } - o => { - match &code[inner_try_me_else_loc + o] { - Line::Control(ControlInstruction::RevJmpBy(0)) => { - code[inner_try_me_else_loc] = - Line::Choice(ChoiceInstruction::TrustMe(o)); - } - _ => { - code[inner_try_me_else_loc] = - Line::Choice(ChoiceInstruction::RetryMeElse(o)); - } + o => match &code[inner_try_me_else_loc + o] { + Line::Control(ControlInstruction::RevJmpBy(0)) => { + code[inner_try_me_else_loc] = Line::Choice(ChoiceInstruction::TrustMe(o)); } - } + _ => { + code[inner_try_me_else_loc] = + Line::Choice(ChoiceInstruction::RetryMeElse(o)); + } + }, } } - _ => { - } + _ => {} } thread_choice_instr_at_to( @@ -332,15 +307,14 @@ fn merge_indexed_subsequences( let mut end_of_upper_lower_bound = None; - for index in upper_lower_bound .. skeleton.clauses.len() { + for index in upper_lower_bound..skeleton.clauses.len() { if !skeleton.clauses[index].opt_arg_index_key.is_some() { end_of_upper_lower_bound = Some(index); break; } } - let outer_threaded_choice_instr_loc = - skeleton.clauses[lower_upper_bound].clause_start - 2; + let outer_threaded_choice_instr_loc = skeleton.clauses[lower_upper_bound].clause_start - 2; match end_of_upper_lower_bound { Some(outer_threaded_clause_index) => { @@ -351,21 +325,17 @@ fn merge_indexed_subsequences( retraction_info, ); } - None => { - match &mut code[outer_threaded_choice_instr_loc] { - Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) => { - retraction_info.push_record( - RetractionRecord::ModifiedTryMeElse(inner_trust_me_loc, *o), - ); + None => match &mut code[outer_threaded_choice_instr_loc] { + Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) => { + retraction_info + .push_record(RetractionRecord::ModifiedTryMeElse(inner_trust_me_loc, *o)); - *o = 0; + *o = 0; - return Some(IndexPtr::Index(outer_threaded_choice_instr_loc + 1)); - } - _ => { - } + return Some(IndexPtr::Index(outer_threaded_choice_instr_loc + 1)); } - } + _ => {} + }, } None @@ -381,15 +351,13 @@ fn delete_from_dynamic_skeleton( let clause_clause_loc = skeleton.clause_clause_locs.remove(target_pos); let clause_index_info = skeleton.clauses.remove(target_pos); - retraction_info.push_record( - RetractionRecord::RemovedDynamicSkeletonClause( - compilation_target, - key, - target_pos, - clause_index_info, - clause_clause_loc, - ), - ); + retraction_info.push_record(RetractionRecord::RemovedDynamicSkeletonClause( + compilation_target, + key, + target_pos, + clause_index_info, + clause_clause_loc, + )); clause_clause_loc } @@ -402,18 +370,15 @@ fn blunt_leading_choice_instr( loop { match &mut code[instr_loc] { Line::Choice(ChoiceInstruction::RetryMeElse(o)) => { - retraction_info.push_record( - RetractionRecord::ModifiedRetryMeElse(instr_loc, *o), - ); + retraction_info.push_record(RetractionRecord::ModifiedRetryMeElse(instr_loc, *o)); code[instr_loc] = Line::Choice(ChoiceInstruction::TryMeElse(*o)); return instr_loc; } Line::Choice(ChoiceInstruction::TrustMe(offset)) => { - retraction_info.push_record( - RetractionRecord::AppendedTrustMe(instr_loc, *offset, false), - ); + retraction_info + .push_record(RetractionRecord::AppendedTrustMe(instr_loc, *offset, false)); code[instr_loc] = Line::Choice(ChoiceInstruction::TryMeElse(0)); return instr_loc + 1; @@ -440,29 +405,19 @@ fn set_switch_var_offset_to_choice_instr( offset: usize, retraction_info: &mut RetractionInfo, ) { - let target_indexing_line = - to_indexing_line_mut(&mut code[index_loc]).unwrap(); + let target_indexing_line = to_indexing_line_mut(&mut code[index_loc]).unwrap(); - let v = - match &mut target_indexing_line[0] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, v, ..)) => { - *v - } - _ => { - unreachable!(); - } - }; + let v = match &mut target_indexing_line[0] { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, v, ..)) => *v, + _ => { + unreachable!(); + } + }; match &code[index_loc + v] { - Line::Choice(ChoiceInstruction::TryMeElse(_)) => { - } + Line::Choice(ChoiceInstruction::TryMeElse(_)) => {} _ => { - set_switch_var_offset( - code, - index_loc, - offset, - retraction_info, - ); + set_switch_var_offset(code, index_loc, offset, retraction_info); } } } @@ -474,22 +429,20 @@ fn set_switch_var_offset( offset: usize, retraction_info: &mut RetractionInfo, ) { - let target_indexing_line = - to_indexing_line_mut(&mut code[index_loc]).unwrap(); + let target_indexing_line = to_indexing_line_mut(&mut code[index_loc]).unwrap(); - let old_v = - match &mut target_indexing_line[0] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, ref mut v, ..)) => { - mem::replace(v, offset) - } - _ => { - unreachable!() - } - }; + let old_v = match &mut target_indexing_line[0] { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, ref mut v, ..)) => { + mem::replace(v, offset) + } + _ => { + unreachable!() + } + }; - retraction_info.push_record( - RetractionRecord::ReplacedSwitchOnTermVarIndex(index_loc, old_v), - ); + retraction_info.push_record(RetractionRecord::ReplacedSwitchOnTermVarIndex( + index_loc, old_v, + )); } fn internalize_choice_instr_at( @@ -499,24 +452,19 @@ fn internalize_choice_instr_at( ) { match &mut code[instr_loc] { Line::Choice(ChoiceInstruction::TryMeElse(0)) => { - retraction_info.push_record( - RetractionRecord::ModifiedTryMeElse(instr_loc, 0), - ); + retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(instr_loc, 0)); code[instr_loc] = Line::Choice(ChoiceInstruction::TrustMe(0)); } Line::Choice(ChoiceInstruction::TryMeElse(o)) => { let o = *o; - retraction_info.push_record( - RetractionRecord::ModifiedTryMeElse(instr_loc, o), - ); + retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(instr_loc, o)); match &mut code[instr_loc + o] { - Line::Control(ControlInstruction::RevJmpBy(p)) - if *p == 0 => { - code[instr_loc] = Line::Choice(ChoiceInstruction::TrustMe(o)); - } + Line::Control(ControlInstruction::RevJmpBy(p)) if *p == 0 => { + code[instr_loc] = Line::Choice(ChoiceInstruction::TrustMe(o)); + } _ => { code[instr_loc] = Line::Choice(ChoiceInstruction::RetryMeElse(o)); } @@ -536,45 +484,39 @@ fn thread_choice_instr_at_to( ) { loop { match &mut code[instr_loc] { - Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) | - Line::Choice(ChoiceInstruction::RetryMeElse(ref mut o)) - if target_loc >= instr_loc => { - retraction_info.push_record( - RetractionRecord::ReplacedChoiceOffset(instr_loc, *o), - ); + Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) + | Line::Choice(ChoiceInstruction::RetryMeElse(ref mut o)) + if target_loc >= instr_loc => + { + retraction_info.push_record(RetractionRecord::ReplacedChoiceOffset(instr_loc, *o)); - *o = target_loc - instr_loc; - return; - } - Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) | - Line::Choice(ChoiceInstruction::RetryMeElse(ref mut o)) => { + *o = target_loc - instr_loc; + return; + } + Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) + | Line::Choice(ChoiceInstruction::RetryMeElse(ref mut o)) => { instr_loc += *o; } - Line::Control(ControlInstruction::RevJmpBy(ref mut o)) - if instr_loc >= target_loc => { - retraction_info.push_record( - RetractionRecord::ModifiedRevJmpBy(instr_loc, *o), - ); + Line::Control(ControlInstruction::RevJmpBy(ref mut o)) if instr_loc >= target_loc => { + retraction_info.push_record(RetractionRecord::ModifiedRevJmpBy(instr_loc, *o)); - *o = instr_loc - target_loc; - return; - } - Line::Choice(ChoiceInstruction::TrustMe(ref mut o)) - if target_loc >= instr_loc => { - retraction_info.push_record( - RetractionRecord::AppendedTrustMe(instr_loc, *o, false), - //choice_instr.is_default()), - ); + *o = instr_loc - target_loc; + return; + } + Line::Choice(ChoiceInstruction::TrustMe(ref mut o)) if target_loc >= instr_loc => { + retraction_info.push_record( + RetractionRecord::AppendedTrustMe(instr_loc, *o, false), + //choice_instr.is_default()), + ); - code[instr_loc] = - Line::Choice(ChoiceInstruction::RetryMeElse(target_loc - instr_loc)); + code[instr_loc] = + Line::Choice(ChoiceInstruction::RetryMeElse(target_loc - instr_loc)); - return; - } - Line::Choice(ChoiceInstruction::TrustMe(o)) - if *o > 0 => { - instr_loc += *o; - } + return; + } + Line::Choice(ChoiceInstruction::TrustMe(o)) if *o > 0 => { + instr_loc += *o; + } _ => { unreachable!() } @@ -604,25 +546,20 @@ fn remove_non_leading_clause( Line::Choice(ChoiceInstruction::TrustMe(_)) => { match &mut code[preceding_choice_instr_loc] { Line::Choice(ChoiceInstruction::RetryMeElse(o)) => { - retraction_info.push_record( - RetractionRecord::ModifiedRetryMeElse( - preceding_choice_instr_loc, - *o, - ), - ); + retraction_info.push_record(RetractionRecord::ModifiedRetryMeElse( + preceding_choice_instr_loc, + *o, + )); - code[preceding_choice_instr_loc] = - Line::Choice(ChoiceInstruction::TrustMe(0)); + code[preceding_choice_instr_loc] = Line::Choice(ChoiceInstruction::TrustMe(0)); None } Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) => { - retraction_info.push_record( - RetractionRecord::ModifiedTryMeElse( - preceding_choice_instr_loc, - *o, - ) - ); + retraction_info.push_record(RetractionRecord::ModifiedTryMeElse( + preceding_choice_instr_loc, + *o, + )); *o = 0; @@ -648,14 +585,13 @@ fn finalize_retract( index_ptr_opt: Option, retraction_info: &mut RetractionInfo, ) -> usize { - let clause_clause_loc = - delete_from_dynamic_skeleton( - compilation_target.clone(), - key.clone(), - skeleton, - target_pos, - retraction_info, - ); + let clause_clause_loc = delete_from_dynamic_skeleton( + compilation_target.clone(), + key.clone(), + skeleton, + target_pos, + retraction_info, + ); if let Some(index_ptr) = index_ptr_opt { set_code_index( @@ -678,12 +614,10 @@ fn remove_leading_unindexed_clause( match &mut code[non_indexed_choice_instr_loc] { Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) => { if *o > 0 { - retraction_info.push_record( - RetractionRecord::ModifiedTryMeElse( - non_indexed_choice_instr_loc, - *o, - ) - ); + retraction_info.push_record(RetractionRecord::ModifiedTryMeElse( + non_indexed_choice_instr_loc, + *o, + )); let o = mem::replace(o, 0); @@ -718,60 +652,54 @@ fn prepend_compiled_clause( let target_arg_num = skeleton.clauses[0].opt_arg_index_key.arg_num(); let head_arg_num = skeleton.clauses[1].opt_arg_index_key.arg_num(); - if skeleton.clauses[0].opt_arg_index_key.switch_on_term_loc().is_some() { + if skeleton.clauses[0] + .opt_arg_index_key + .switch_on_term_loc() + .is_some() + { match skeleton.clauses[1].opt_arg_index_key.switch_on_term_loc() { Some(index_loc) if target_arg_num == head_arg_num => { - prepend_queue.extend(clause_code.drain(3 ..)); + prepend_queue.extend(clause_code.drain(3..)); skeleton.clauses[0].opt_arg_index_key += index_loc - 1; skeleton.clauses[0].clause_start = clause_loc + 2; - retraction_info.push_record( - RetractionRecord::AddedIndex( - skeleton.clauses[0].opt_arg_index_key.clone(), - skeleton.clauses[0].clause_start, - ), - ); + retraction_info.push_record(RetractionRecord::AddedIndex( + skeleton.clauses[0].opt_arg_index_key.clone(), + skeleton.clauses[0].clause_start, + )); let outer_thread_choice_loc = skeleton.clauses[1].clause_start - 2; - retraction_info.push_record( - RetractionRecord::SkeletonClauseStartReplaced( - compilation_target, - key.clone(), - 1, - skeleton.clauses[1].clause_start, - ), - ); + retraction_info.push_record(RetractionRecord::SkeletonClauseStartReplaced( + compilation_target, + key.clone(), + 1, + skeleton.clauses[1].clause_start, + )); skeleton.clauses[1].clause_start = - find_inner_choice_instr( - code, - skeleton.clauses[1].clause_start, - index_loc, - ); + find_inner_choice_instr(code, skeleton.clauses[1].clause_start, index_loc); let inner_thread_rev_offset = 3 + prepend_queue.len() + clause_loc - skeleton.clauses[1].clause_start; - prepend_queue.push_back( - Line::Control(ControlInstruction::RevJmpBy(inner_thread_rev_offset)), - ); + prepend_queue.push_back(Line::Control(ControlInstruction::RevJmpBy( + inner_thread_rev_offset, + ))); - prepend_queue.push_front( - Line::Choice(ChoiceInstruction::TryMeElse(prepend_queue.len())), - ); + prepend_queue.push_front(Line::Choice(ChoiceInstruction::TryMeElse( + prepend_queue.len(), + ))); // prepend_queue is now: // | TryMeElse N_2 // | (clause_code) // +N_2 | RevJmpBy (RetryMeElse(M_1) or TryMeElse(0) at index_loc + 1) - prepend_queue.push_front( - Line::Control(ControlInstruction::RevJmpBy( - 1 + clause_loc - index_loc - )), - ); + prepend_queue.push_front(Line::Control(ControlInstruction::RevJmpBy( + 1 + clause_loc - index_loc, + ))); let outer_thread_choice_offset = // outer_thread_choice_loc WAS index_loc - 1.. match derelictize_try_me_else(code, outer_thread_choice_loc, retraction_info) { @@ -807,9 +735,9 @@ fn prepend_compiled_clause( } }; - prepend_queue.push_front( - Line::Choice(ChoiceInstruction::TryMeElse(outer_thread_choice_offset)), - ); + prepend_queue.push_front(Line::Choice(ChoiceInstruction::TryMeElse( + outer_thread_choice_offset, + ))); // prepend_queue is now: // | TryMeElse N_3 @@ -828,21 +756,20 @@ fn prepend_compiled_clause( AppendOrPrepend::Prepend, ); - set_switch_var_offset( + set_switch_var_offset(code, index_loc, clause_loc - index_loc + 2, retraction_info); + + internalize_choice_instr_at( code, - index_loc, - clause_loc - index_loc + 2, + skeleton.clauses[1].clause_start, retraction_info, ); - internalize_choice_instr_at(code, skeleton.clauses[1].clause_start, retraction_info); - code.extend(prepend_queue.into_iter()); clause_loc + (outer_thread_choice_offset == 0) as usize } _ => { - prepend_queue.extend(clause_code.drain(1 ..)); + prepend_queue.extend(clause_code.drain(1..)); skeleton.clauses[0].opt_arg_index_key += clause_loc; skeleton.clauses[0].clause_start = clause_loc + 2; @@ -854,29 +781,26 @@ fn prepend_compiled_clause( // this is a stub for chaining inner-threaded choice // instructions. - prepend_queue.push_back( - Line::Control(ControlInstruction::RevJmpBy(0)) - ); + prepend_queue.push_back(Line::Control(ControlInstruction::RevJmpBy(0))); let prepend_queue_len = prepend_queue.len(); match &mut prepend_queue[1] { - Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) - if *o == 0 => { - *o = prepend_queue_len - 2; - } + Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) if *o == 0 => { + *o = prepend_queue_len - 2; + } _ => { unreachable!(); } } - prepend_queue.push_back( - Line::Control(ControlInstruction::RevJmpBy(inner_thread_rev_offset)), - ); + prepend_queue.push_back(Line::Control(ControlInstruction::RevJmpBy( + inner_thread_rev_offset, + ))); - prepend_queue.push_front( - Line::Choice(ChoiceInstruction::TryMeElse(prepend_queue.len())), - ); + prepend_queue.push_front(Line::Choice(ChoiceInstruction::TryMeElse( + prepend_queue.len(), + ))); // prepend_queue is now: // | TryMeElse(N_2) @@ -895,20 +819,20 @@ fn prepend_compiled_clause( } else { match skeleton.clauses[1].opt_arg_index_key.switch_on_term_loc() { Some(_) => { - prepend_queue.extend(clause_code.drain(1 ..)); + prepend_queue.extend(clause_code.drain(1..)); let old_clause_start = skeleton.clauses[1].clause_start - 2; let inner_thread_rev_offset = 1 + prepend_queue.len() + clause_loc - old_clause_start; - prepend_queue.push_back( - Line::Control(ControlInstruction::RevJmpBy(inner_thread_rev_offset)), - ); + prepend_queue.push_back(Line::Control(ControlInstruction::RevJmpBy( + inner_thread_rev_offset, + ))); - prepend_queue.push_front( - Line::Choice(ChoiceInstruction::TryMeElse(prepend_queue.len())), - ); + prepend_queue.push_front(Line::Choice(ChoiceInstruction::TryMeElse( + prepend_queue.len(), + ))); // prepend_queue is now: // | TryMeElse(N_2) @@ -925,20 +849,20 @@ fn prepend_compiled_clause( clause_loc // + (outer_thread_choice_offset == 0 as usize) } None => { - prepend_queue.extend(clause_code.drain(1 ..)); + prepend_queue.extend(clause_code.drain(1..)); let old_clause_start = skeleton.clauses[1].clause_start; let inner_thread_rev_offset = 1 + prepend_queue.len() + clause_loc - old_clause_start; - prepend_queue.push_back( - Line::Control(ControlInstruction::RevJmpBy(inner_thread_rev_offset)), - ); + prepend_queue.push_back(Line::Control(ControlInstruction::RevJmpBy( + inner_thread_rev_offset, + ))); - prepend_queue.push_front( - Line::Choice(ChoiceInstruction::TryMeElse(prepend_queue.len())), - ); + prepend_queue.push_front(Line::Choice(ChoiceInstruction::TryMeElse( + prepend_queue.len(), + ))); // prepend_queue is now: // | TryMeElse(N_2) @@ -976,88 +900,88 @@ fn append_compiled_clause( let lower_bound_arg_num = skeleton.clauses[lower_bound].opt_arg_index_key.arg_num(); let target_arg_num = skeleton.clauses[target_pos].opt_arg_index_key.arg_num(); - let threaded_choice_instr_loc = - match skeleton.clauses[lower_bound].opt_arg_index_key.switch_on_term_loc() { - Some(index_loc) if lower_bound_arg_num == target_arg_num => { - code.extend(clause_code.drain(3 ..)); // skip the indexing code + let threaded_choice_instr_loc = match skeleton.clauses[lower_bound] + .opt_arg_index_key + .switch_on_term_loc() + { + Some(index_loc) if lower_bound_arg_num == target_arg_num => { + code.extend(clause_code.drain(3..)); // skip the indexing code - // set skeleton[target_pos].opt_arg_index_key to - // index_loc. its original value is always 1. - skeleton.clauses[target_pos].opt_arg_index_key += index_loc - 1; + // set skeleton[target_pos].opt_arg_index_key to + // index_loc. its original value is always 1. + skeleton.clauses[target_pos].opt_arg_index_key += index_loc - 1; - retraction_info.push_record( - RetractionRecord::AddedIndex( - skeleton.clauses[target_pos].opt_arg_index_key.clone(), - skeleton.clauses[target_pos].clause_start, - ), - ); + retraction_info.push_record(RetractionRecord::AddedIndex( + skeleton.clauses[target_pos].opt_arg_index_key.clone(), + skeleton.clauses[target_pos].clause_start, + )); - let target_indexing_line = to_indexing_line_mut(&mut code[index_loc]).unwrap(); + let target_indexing_line = to_indexing_line_mut(&mut code[index_loc]).unwrap(); - merge_clause_index( - target_indexing_line, - &mut skeleton.clauses[lower_bound ..], - clause_loc, - AppendOrPrepend::Append, - ); + merge_clause_index( + target_indexing_line, + &mut skeleton.clauses[lower_bound..], + clause_loc, + AppendOrPrepend::Append, + ); - let target_pos_clause_start = find_inner_choice_instr( + let target_pos_clause_start = find_inner_choice_instr( + code, + skeleton.clauses[target_pos - 1].clause_start, + index_loc, + ); + + if lower_bound + 1 == target_pos { + set_switch_var_offset( code, - skeleton.clauses[target_pos - 1].clause_start, index_loc, + target_pos_clause_start - index_loc, + retraction_info, ); - - if lower_bound + 1 == target_pos { - set_switch_var_offset( - code, - index_loc, - target_pos_clause_start - index_loc, - retraction_info, - ); - } - - target_pos_clause_start // skeleton.clauses[target_pos - 1].clause_start } - _ => { - skeleton.clauses[target_pos].opt_arg_index_key += clause_loc; - code.extend(clause_code.drain(1 ..)); - match skeleton.clauses[lower_bound].opt_arg_index_key.switch_on_term_loc() { - Some(_) => { - if lower_bound == 0 { - code_ptr_opt = Some(skeleton.clauses[lower_bound].clause_start - 2); - } + target_pos_clause_start // skeleton.clauses[target_pos - 1].clause_start + } + _ => { + skeleton.clauses[target_pos].opt_arg_index_key += clause_loc; + code.extend(clause_code.drain(1..)); - skeleton.clauses[lower_bound].clause_start - 2 + match skeleton.clauses[lower_bound] + .opt_arg_index_key + .switch_on_term_loc() + { + Some(_) => { + if lower_bound == 0 { + code_ptr_opt = Some(skeleton.clauses[lower_bound].clause_start - 2); } - None => { - if lower_bound == 0 { - code_ptr_opt = Some(skeleton.clauses[lower_bound].clause_start); - } - match skeleton.clauses[target_pos].opt_arg_index_key.switch_on_term_loc() { - Some(index_loc) => { - // point to the inner-threaded TryMeElse(0) if target_pos is - // indexed, and make switch_on_term point one line after it in - // its variable offset. - skeleton.clauses[target_pos].clause_start += 2; - - set_switch_var_offset( - code, - index_loc, - 2, - retraction_info, - ); - } - None => { - } - } - - skeleton.clauses[lower_bound].clause_start + skeleton.clauses[lower_bound].clause_start - 2 + } + None => { + if lower_bound == 0 { + code_ptr_opt = Some(skeleton.clauses[lower_bound].clause_start); } + + match skeleton.clauses[target_pos] + .opt_arg_index_key + .switch_on_term_loc() + { + Some(index_loc) => { + // point to the inner-threaded TryMeElse(0) if target_pos is + // indexed, and make switch_on_term point one line after it in + // its variable offset. + skeleton.clauses[target_pos].clause_start += 2; + + set_switch_var_offset(code, index_loc, 2, retraction_info); + } + None => {} + } + + skeleton.clauses[lower_bound].clause_start } } - }; + } + }; thread_choice_instr_at_to(code, threaded_choice_instr_loc, clause_loc, retraction_info); @@ -1073,7 +997,7 @@ fn mergeable_indexed_subsequences( let lower_bound_arg_num = skeleton.clauses[lower_bound].opt_arg_index_key.arg_num(); if target_pos + 1 < skeleton.clauses.len() { - let succ_arg_num = skeleton.clauses[target_pos + 1].opt_arg_index_key.arg_num(); + let succ_arg_num = skeleton.clauses[target_pos + 1].opt_arg_index_key.arg_num(); let target_arg_num = skeleton.clauses[target_pos].opt_arg_index_key.arg_num(); return target_arg_num != succ_arg_num && lower_bound_arg_num == succ_arg_num; @@ -1094,10 +1018,8 @@ impl<'a> LoadState<'a> { let code_len = self.wam.code_repo.code.len(); let mut code_ptr = code_len; - let mut cg = CodeGenerator::::new( - self.wam.machine_st.atom_tbl.clone(), - settings, - ); + let mut cg = + CodeGenerator::::new(self.wam.machine_st.atom_tbl.clone(), settings); let mut code = cg.compile_predicate(predicates)?; @@ -1119,22 +1041,21 @@ impl<'a> LoadState<'a> { Line::Choice(ChoiceInstruction::TryMeElse(0)) => { code_ptr += 1; } - _ => { - } + _ => {} } - match self.wam.indices.get_predicate_skeleton( - &self.compilation_target, - &key, - ) { + match self + .wam + .indices + .get_predicate_skeleton(&self.compilation_target, &key) + { Some(skeleton) => { - self.retraction_info.push_record( - RetractionRecord::SkeletonClauseTruncateBack( + self.retraction_info + .push_record(RetractionRecord::SkeletonClauseTruncateBack( self.compilation_target.clone(), key.clone(), skeleton.clauses.len(), - ), - ); + )); skeleton.clauses.extend(cg.skeleton.clauses.into_iter()); } @@ -1156,44 +1077,37 @@ impl<'a> LoadState<'a> { Ok(code_index.get()) } - fn record_incremental_compile(&mut self, key: PredicateKey, append_or_prepend: AppendOrPrepend) - { - self.retraction_info.push_record( - match &self.compilation_target { - CompilationTarget::User => { - match append_or_prepend { - AppendOrPrepend::Append => { - RetractionRecord::AppendedUserExtensiblePredicate( - key, - ) - } - AppendOrPrepend::Prepend => { - RetractionRecord::PrependedUserExtensiblePredicate( - key, - ) - } + fn record_incremental_compile( + &mut self, + key: PredicateKey, + append_or_prepend: AppendOrPrepend, + ) { + self.retraction_info + .push_record(match &self.compilation_target { + CompilationTarget::User => match append_or_prepend { + AppendOrPrepend::Append => { + RetractionRecord::AppendedUserExtensiblePredicate(key) } - } - CompilationTarget::Module(ref module_name) => { - match append_or_prepend { - AppendOrPrepend::Append => { - RetractionRecord::AppendedModuleExtensiblePredicate( - module_name.clone(), key, - ) - } - AppendOrPrepend::Prepend => { - RetractionRecord::PrependedModuleExtensiblePredicate( - module_name.clone(), key, - ) - } + AppendOrPrepend::Prepend => { + RetractionRecord::PrependedUserExtensiblePredicate(key) } - } - } - ); + }, + CompilationTarget::Module(ref module_name) => match append_or_prepend { + AppendOrPrepend::Append => RetractionRecord::AppendedModuleExtensiblePredicate( + module_name.clone(), + key, + ), + AppendOrPrepend::Prepend => { + RetractionRecord::PrependedModuleExtensiblePredicate( + module_name.clone(), + key, + ) + } + }, + }); } - pub(super) - fn incremental_compile_clause( + pub(super) fn incremental_compile_clause( &mut self, key: PredicateKey, clause: PredicateClause, @@ -1203,45 +1117,45 @@ impl<'a> LoadState<'a> { ) -> Result { self.record_incremental_compile(key.clone(), append_or_prepend); - let skeleton = - match self.wam.indices.get_predicate_skeleton( - &self.compilation_target, - &key, - ) { - Some(skeleton) if !skeleton.clauses.is_empty() => { - skeleton - } - _ => { - // true because this predicate is extensible. - let settings = CodeGenSettings::new(true, non_counted_bt); - return self.compile(key, &vec![clause], &queue, settings); - } - }; + let skeleton = match self + .wam + .indices + .get_predicate_skeleton(&self.compilation_target, &key) + { + Some(skeleton) if !skeleton.clauses.is_empty() => skeleton, + _ => { + // true because this predicate is extensible. + let settings = CodeGenSettings::new(true, non_counted_bt); + return self.compile(key, &vec![clause], &queue, settings); + } + }; let settings = CodeGenSettings::new(true, non_counted_bt); let atom_tbl = self.wam.machine_st.atom_tbl.clone(); - let StandaloneCompileResult { clause_code, mut standalone_skeleton } = - compile_standalone_clause(clause, queue, settings, atom_tbl)?; + let StandaloneCompileResult { + clause_code, + mut standalone_skeleton, + } = compile_standalone_clause(clause, queue, settings, atom_tbl)?; match append_or_prepend { AppendOrPrepend::Append => { - skeleton.clauses.push_back(standalone_skeleton.clauses.pop_back().unwrap()); + skeleton + .clauses + .push_back(standalone_skeleton.clauses.pop_back().unwrap()); - self.retraction_info.push_record( - RetractionRecord::SkeletonClausePopBack( + self.retraction_info + .push_record(RetractionRecord::SkeletonClausePopBack( self.compilation_target.clone(), key.clone(), - ), - ); + )); - let result = - append_compiled_clause( - &mut self.wam.code_repo.code, - clause_code, - skeleton, - &mut self.retraction_info, - ); + let result = append_compiled_clause( + &mut self.wam.code_repo.code, + clause_code, + skeleton, + &mut self.retraction_info, + ); let code_index = self.get_or_insert_code_index(key.clone()); @@ -1258,25 +1172,25 @@ impl<'a> LoadState<'a> { Ok(code_index.get()) } AppendOrPrepend::Prepend => { - skeleton.clauses.push_front(standalone_skeleton.clauses.pop_back().unwrap()); + skeleton + .clauses + .push_front(standalone_skeleton.clauses.pop_back().unwrap()); - self.retraction_info.push_record( - RetractionRecord::SkeletonClausePopFront( + self.retraction_info + .push_record(RetractionRecord::SkeletonClausePopFront( self.compilation_target.clone(), key.clone(), - ), + )); + + let threaded_choice_instr_loc = prepend_compiled_clause( + &mut self.wam.code_repo.code, + self.compilation_target.clone(), + key.clone(), + clause_code, + skeleton, + &mut self.retraction_info, ); - let threaded_choice_instr_loc = - prepend_compiled_clause( - &mut self.wam.code_repo.code, - self.compilation_target.clone(), - key.clone(), - clause_code, - skeleton, - &mut self.retraction_info, - ); - let code_index = self.get_or_insert_code_index(key.clone()); set_code_index( @@ -1292,22 +1206,19 @@ impl<'a> LoadState<'a> { } } - pub(super) - fn retract_clause(&mut self, key: PredicateKey, target_pos: usize) -> usize { + pub(super) fn retract_clause(&mut self, key: PredicateKey, target_pos: usize) -> usize { let code_index = self.get_or_insert_code_index(key.clone()); - let skeleton = - match self.wam.indices.get_predicate_skeleton( - &self.compilation_target, - &key, - ) { - Some(skeleton) => { - skeleton - } - None => { - unreachable!(); - } - }; + let skeleton = match self + .wam + .indices + .get_predicate_skeleton(&self.compilation_target, &key) + { + Some(skeleton) => skeleton, + None => { + unreachable!(); + } + }; let code = &mut self.wam.code_repo.code; let lower_bound = lower_bound_of_target_clause(skeleton, target_pos); @@ -1316,7 +1227,10 @@ impl<'a> LoadState<'a> { if target_pos == 0 || (lower_bound + 1 == target_pos && lower_bound_is_unindexed) { // the clause preceding target_pos, if there is one, is of key type // OptArgIndexKey::None. - match skeleton.clauses[target_pos].opt_arg_index_key.switch_on_term_loc() { + match skeleton.clauses[target_pos] + .opt_arg_index_key + .switch_on_term_loc() + { Some(index_loc) => { let inner_clause_start = find_inner_choice_instr( code, @@ -1377,24 +1291,23 @@ impl<'a> LoadState<'a> { ); } None => { - let index_ptr_opt = - if target_pos > 0 { - let preceding_choice_instr_loc = - skeleton.clauses[target_pos - 1].clause_start; + let index_ptr_opt = if target_pos > 0 { + let preceding_choice_instr_loc = + skeleton.clauses[target_pos - 1].clause_start; - remove_non_leading_clause( - code, - preceding_choice_instr_loc, - skeleton.clauses[target_pos].clause_start - 2, - &mut self.retraction_info, - ) - } else { - remove_leading_unindexed_clause( - code, - skeleton.clauses[target_pos].clause_start - 2, - &mut self.retraction_info, - ) - }; + remove_non_leading_clause( + code, + preceding_choice_instr_loc, + skeleton.clauses[target_pos].clause_start - 2, + &mut self.retraction_info, + ) + } else { + remove_leading_unindexed_clause( + code, + skeleton.clauses[target_pos].clause_start - 2, + &mut self.retraction_info, + ) + }; return finalize_retract( key, @@ -1408,161 +1321,166 @@ impl<'a> LoadState<'a> { } } } - None => { - } + None => {} } } - let index_ptr_opt = - match skeleton.clauses[lower_bound].opt_arg_index_key.switch_on_term_loc() { - Some(target_indexing_loc) - if mergeable_indexed_subsequences(lower_bound, target_pos, skeleton) => + let index_ptr_opt = match skeleton.clauses[lower_bound] + .opt_arg_index_key + .switch_on_term_loc() + { + Some(target_indexing_loc) + if mergeable_indexed_subsequences(lower_bound, target_pos, skeleton) => + { + let lower_bound_clause_start = find_inner_choice_instr( + code, + skeleton.clauses[lower_bound].clause_start, + target_indexing_loc, + ); + + let result; + + match skeleton.clauses[target_pos + 1] + .opt_arg_index_key + .switch_on_term_loc() { - let lower_bound_clause_start = find_inner_choice_instr( - code, - skeleton.clauses[lower_bound].clause_start, - target_indexing_loc, - ); + Some(later_indexing_loc) if later_indexing_loc < target_indexing_loc => { + let target_indexing_line = mem::replace( + &mut code[target_indexing_loc], + Line::Control(ControlInstruction::RevJmpBy( + target_indexing_loc - later_indexing_loc, + )), + ); - let result; - - match skeleton.clauses[target_pos + 1].opt_arg_index_key.switch_on_term_loc() { - Some(later_indexing_loc) if later_indexing_loc < target_indexing_loc => { - let target_indexing_line = mem::replace( - &mut code[target_indexing_loc], - Line::Control(ControlInstruction::RevJmpBy( - target_indexing_loc - later_indexing_loc - )), - ); - - match target_indexing_line { - Line::IndexingCode(indexing_code) => { - self.retraction_info.push_record( - RetractionRecord::ReplacedIndexingLine( - target_indexing_loc, - indexing_code, - ), - ); - } - _ => { - } + match target_indexing_line { + Line::IndexingCode(indexing_code) => { + self.retraction_info.push_record( + RetractionRecord::ReplacedIndexingLine( + target_indexing_loc, + indexing_code, + ), + ); } - - result = merge_indexed_subsequences( - code, - skeleton, - lower_bound, - target_pos + 1, - &mut self.retraction_info, - ); - - merge_indices( - code, - later_indexing_loc, - 0 .. target_pos - lower_bound, - &mut skeleton.clauses[lower_bound ..], - &mut self.retraction_info, - ); - - set_switch_var_offset( - code, - later_indexing_loc, - lower_bound_clause_start - later_indexing_loc, - &mut self.retraction_info, - ); + _ => {} } - _ => { - result = merge_indexed_subsequences( - code, - skeleton, - lower_bound, - target_pos + 1, - &mut self.retraction_info, - ); - merge_indices( - code, - target_indexing_loc, - target_pos + 1 - lower_bound .. skeleton.clauses.len() - lower_bound, - &mut skeleton.clauses[lower_bound ..], - &mut self.retraction_info, - ); - - set_switch_var_offset_to_choice_instr( - code, - target_indexing_loc, - lower_bound_clause_start - target_indexing_loc, - &mut self.retraction_info, - ); - } - }; - - result - } - _ => { - if target_pos > 0 { - remove_index_from_subsequence( + result = merge_indexed_subsequences( code, - &skeleton.clauses[target_pos].opt_arg_index_key, - skeleton.clauses[target_pos].clause_start, + skeleton, + lower_bound, + target_pos + 1, &mut self.retraction_info, ); - match skeleton.clauses[target_pos].opt_arg_index_key.switch_on_term_loc() { - Some(index_loc) => { - let preceding_choice_instr_loc = find_inner_choice_instr( - code, - skeleton.clauses[target_pos - 1].clause_start, - index_loc, - ); - - remove_non_leading_clause( - code, - preceding_choice_instr_loc, - skeleton.clauses[target_pos].clause_start, - &mut self.retraction_info, - ); - - match &mut code[preceding_choice_instr_loc] { - Line::Choice(ChoiceInstruction::TryMeElse(0)) => { - set_switch_var_offset( - code, - index_loc, - preceding_choice_instr_loc + 1 - index_loc, - &mut self.retraction_info, - ); - } - _ => { - } - } - - None - } - None => { - let preceding_choice_instr_loc = - if skeleton.clauses[lower_bound].opt_arg_index_key.is_some() { - skeleton.clauses[lower_bound].clause_start - 2 - } else { - skeleton.clauses[lower_bound].clause_start - }; - - remove_non_leading_clause( - code, - preceding_choice_instr_loc, - skeleton.clauses[target_pos].clause_start, - &mut self.retraction_info, - ) - } - } - } else { - remove_leading_unindexed_clause( + merge_indices( code, - skeleton.clauses[target_pos].clause_start, + later_indexing_loc, + 0..target_pos - lower_bound, + &mut skeleton.clauses[lower_bound..], &mut self.retraction_info, - ) + ); + + set_switch_var_offset( + code, + later_indexing_loc, + lower_bound_clause_start - later_indexing_loc, + &mut self.retraction_info, + ); } + _ => { + result = merge_indexed_subsequences( + code, + skeleton, + lower_bound, + target_pos + 1, + &mut self.retraction_info, + ); + + merge_indices( + code, + target_indexing_loc, + target_pos + 1 - lower_bound..skeleton.clauses.len() - lower_bound, + &mut skeleton.clauses[lower_bound..], + &mut self.retraction_info, + ); + + set_switch_var_offset_to_choice_instr( + code, + target_indexing_loc, + lower_bound_clause_start - target_indexing_loc, + &mut self.retraction_info, + ); + } + }; + + result + } + _ => { + if target_pos > 0 { + remove_index_from_subsequence( + code, + &skeleton.clauses[target_pos].opt_arg_index_key, + skeleton.clauses[target_pos].clause_start, + &mut self.retraction_info, + ); + + match skeleton.clauses[target_pos] + .opt_arg_index_key + .switch_on_term_loc() + { + Some(index_loc) => { + let preceding_choice_instr_loc = find_inner_choice_instr( + code, + skeleton.clauses[target_pos - 1].clause_start, + index_loc, + ); + + remove_non_leading_clause( + code, + preceding_choice_instr_loc, + skeleton.clauses[target_pos].clause_start, + &mut self.retraction_info, + ); + + match &mut code[preceding_choice_instr_loc] { + Line::Choice(ChoiceInstruction::TryMeElse(0)) => { + set_switch_var_offset( + code, + index_loc, + preceding_choice_instr_loc + 1 - index_loc, + &mut self.retraction_info, + ); + } + _ => {} + } + + None + } + None => { + let preceding_choice_instr_loc = + if skeleton.clauses[lower_bound].opt_arg_index_key.is_some() { + skeleton.clauses[lower_bound].clause_start - 2 + } else { + skeleton.clauses[lower_bound].clause_start + }; + + remove_non_leading_clause( + code, + preceding_choice_instr_loc, + skeleton.clauses[target_pos].clause_start, + &mut self.retraction_info, + ) + } + } + } else { + remove_leading_unindexed_clause( + code, + skeleton.clauses[target_pos].clause_start, + &mut self.retraction_info, + ) } - }; + } + }; finalize_retract( key, @@ -1577,35 +1495,26 @@ impl<'a> LoadState<'a> { } impl<'a, TS: TermStream> Loader<'a, TS> { - pub(super) - fn compile_clause_clauses>( + pub(super) fn compile_clause_clauses>( &mut self, key: PredicateKey, compilation_target: CompilationTarget, clause_clauses: ClauseIter, append_or_prepend: AppendOrPrepend, ) -> Result<(), SessionError> { - let clause_predicates = - clause_clauses.map(|(head, body)| { - PredicateClause::Fact( - Term::Clause( - Cell::default(), - clause_name!("$clause"), - vec![Box::new(head), Box::new(body)], - None, - ) - ) - }); + let clause_predicates = clause_clauses.map(|(head, body)| { + PredicateClause::Fact(Term::Clause( + Cell::default(), + clause_name!("$clause"), + vec![Box::new(head), Box::new(body)], + None, + )) + }); - let clause_clause_compilation_target = - match compilation_target { - CompilationTarget::User => { - CompilationTarget::Module(clause_name!("builtins")) - } - _ => { - compilation_target.clone() - } - }; + let clause_clause_compilation_target = match compilation_target { + CompilationTarget::User => CompilationTarget::Module(clause_name!("builtins")), + _ => compilation_target.clone(), + }; let old_compilation_target = mem::replace( &mut self.load_state.compilation_target, @@ -1636,7 +1545,9 @@ impl<'a, TS: TermStream> Loader<'a, TS> { &(clause_name!("$clause"), 2), ) { Some(skeleton) if append_or_prepend.is_append() => { - skeleton.clause_clause_locs.extend_from_slice(&clause_clause_locs[0 ..]); + skeleton + .clause_clause_locs + .extend_from_slice(&clause_clause_locs[0..]); } Some(skeleton) => { for loc in clause_clause_locs.iter() { @@ -1648,10 +1559,12 @@ impl<'a, TS: TermStream> Loader<'a, TS> { } } - match self.load_state.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .load_state + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) if append_or_prepend.is_append() => { self.load_state.retraction_info.push_record( RetractionRecord::SkeletonClauseClausesTruncateBack( @@ -1661,9 +1574,7 @@ impl<'a, TS: TermStream> Loader<'a, TS> { ), ); - skeleton.clause_clause_locs.append( - &mut clause_clause_locs - ); + skeleton.clause_clause_locs.append(&mut clause_clause_locs); } Some(skeleton) => { self.load_state.retraction_info.push_record( @@ -1678,9 +1589,8 @@ impl<'a, TS: TermStream> Loader<'a, TS> { skeleton.clause_clause_locs.push_front(*loc); } - self.load_state.increment_clause_assert_margin( - clause_clause_locs.len() - ); + self.load_state + .increment_clause_assert_margin(clause_clause_locs.len()); } None => { unreachable!(); @@ -1691,11 +1601,11 @@ impl<'a, TS: TermStream> Loader<'a, TS> { Ok(()) } - pub(super) - fn compile_and_submit(&mut self) -> Result<(), SessionError> { + pub(super) fn compile_and_submit(&mut self) -> Result<(), SessionError> { let queue = self.preprocessor.parse_queue(&mut self.load_state)?; - let key = self.predicates + let key = self + .predicates .first() .and_then(|cl| { let arity = cl.arity(); @@ -1703,7 +1613,10 @@ impl<'a, TS: TermStream> Loader<'a, TS> { }) .ok_or(SessionError::NamelessEntry)?; - let (is_dynamic, is_extensible) = self.load_state.wam.indices + let (is_dynamic, is_extensible) = self + .load_state + .wam + .indices .get_predicate_skeleton(&self.load_state.compilation_target, &key) .map(|skeleton| (skeleton.is_dynamic, true)) .unwrap_or((false, false)); @@ -1711,18 +1624,14 @@ impl<'a, TS: TermStream> Loader<'a, TS> { let non_counted_bt = self.non_counted_bt_preds.contains(&key); let settings = CodeGenSettings::new(is_extensible, non_counted_bt); - self.load_state.compile(key.clone(), &self.predicates, &queue, settings)?; + self.load_state + .compile(key.clone(), &self.predicates, &queue, settings)?; if is_dynamic { let iter = mem::replace(&mut self.clause_clauses, vec![]).into_iter(); let compilation_target = self.load_state.compilation_target.clone(); - self.compile_clause_clauses( - key, - compilation_target, - iter, - AppendOrPrepend::Append, - )?; + self.compile_clause_clauses(key, compilation_target, iter, AppendOrPrepend::Append)?; } Ok(self.predicates.clear()) diff --git a/src/machine/load_state.rs b/src/machine/load_state.rs index bef493b5..466b2f99 100644 --- a/src/machine/load_state.rs +++ b/src/machine/load_state.rs @@ -1,7 +1,8 @@ -use crate::machine::*; use crate::machine::machine_indices::*; -use crate::machine::term_stream::*; +use crate::machine::*; +use crate::prolog_parser_rebis::clause_name; +use crate::machine::term_stream::*; use indexmap::IndexSet; use crate::ref_thread_local::RefThreadLocal; @@ -19,37 +20,35 @@ pub(super) struct LoadState<'a> { pub(super) wam: &'a mut Machine, } -pub(super) -fn set_code_index( +pub(super) fn set_code_index( retraction_info: &mut RetractionInfo, compilation_target: &CompilationTarget, key: PredicateKey, code_index: &CodeIndex, code_ptr: IndexPtr, ) { - let record = - match compilation_target { - CompilationTarget::User => { - if IndexPtr::Undefined == code_index.get() { - code_index.set(code_ptr); - RetractionRecord::AddedUserPredicate(key) - } else { - // TODO: emit warning about overwriting previous record - let replaced = code_index.replace(code_ptr); - RetractionRecord::ReplacedUserPredicate(key, replaced) - } + let record = match compilation_target { + CompilationTarget::User => { + if IndexPtr::Undefined == code_index.get() { + code_index.set(code_ptr); + RetractionRecord::AddedUserPredicate(key) + } else { + // TODO: emit warning about overwriting previous record + let replaced = code_index.replace(code_ptr); + RetractionRecord::ReplacedUserPredicate(key, replaced) } - CompilationTarget::Module(ref module_name) => { - if IndexPtr::Undefined == code_index.get() { - code_index.set(code_ptr); - RetractionRecord::AddedModulePredicate(module_name.clone(), key) - } else { - // TODO: emit warning about overwriting previous record - let replaced = code_index.replace(code_ptr); - RetractionRecord::ReplacedModulePredicate(module_name.clone(), key, replaced) - } + } + CompilationTarget::Module(ref module_name) => { + if IndexPtr::Undefined == code_index.get() { + code_index.set(code_ptr); + RetractionRecord::AddedModulePredicate(module_name.clone(), key) + } else { + // TODO: emit warning about overwriting previous record + let replaced = code_index.replace(code_ptr); + RetractionRecord::ReplacedModulePredicate(module_name.clone(), key, replaced) } - }; + } + }; retraction_info.push_record(record); } @@ -71,16 +70,16 @@ fn add_op_decl_as_module_export( match op_decl.insert_into_op_dir(wam_op_dir) { Some((prec, spec)) => { - retraction_info.push_record( - RetractionRecord::ReplacedUserOp(op_decl.clone(), prec, spec) - ); + retraction_info.push_record(RetractionRecord::ReplacedUserOp( + op_decl.clone(), + prec, + spec, + )); module_op_exports.push((op_decl.clone(), Some((prec, spec)))); } None => { - retraction_info.push_record( - RetractionRecord::AddedUserOp(op_decl.clone()) - ); + retraction_info.push_record(RetractionRecord::AddedUserOp(op_decl.clone())); module_op_exports.push((op_decl.clone(), None)); } @@ -89,49 +88,45 @@ fn add_op_decl_as_module_export( add_op_decl(retraction_info, compilation_target, module_op_dir, op_decl); } -pub(super) -fn add_op_decl( +pub(super) fn add_op_decl( retraction_info: &mut RetractionInfo, compilation_target: &CompilationTarget, op_dir: &mut OpDir, op_decl: &OpDecl, ) { match op_decl.insert_into_op_dir(op_dir) { - Some((prec, spec)) => { - match &compilation_target { - CompilationTarget::User => { - retraction_info.push_record( - RetractionRecord::ReplacedUserOp(op_decl.clone(), prec, spec), - ); - } - CompilationTarget::Module(ref module_name) => { - retraction_info.push_record( - RetractionRecord::ReplacedModuleOp( - module_name.clone(), op_decl.clone(), prec, spec, - ), - ); - } + Some((prec, spec)) => match &compilation_target { + CompilationTarget::User => { + retraction_info.push_record(RetractionRecord::ReplacedUserOp( + op_decl.clone(), + prec, + spec, + )); } - } - None => { - match &compilation_target { - CompilationTarget::User => { - retraction_info.push_record( - RetractionRecord::AddedUserOp(op_decl.clone()), - ); - } - CompilationTarget::Module(ref module_name) => { - retraction_info.push_record( - RetractionRecord::AddedModuleOp(module_name.clone(), op_decl.clone()), - ); - } + CompilationTarget::Module(ref module_name) => { + retraction_info.push_record(RetractionRecord::ReplacedModuleOp( + module_name.clone(), + op_decl.clone(), + prec, + spec, + )); } - } + }, + None => match &compilation_target { + CompilationTarget::User => { + retraction_info.push_record(RetractionRecord::AddedUserOp(op_decl.clone())); + } + CompilationTarget::Module(ref module_name) => { + retraction_info.push_record(RetractionRecord::AddedModuleOp( + module_name.clone(), + op_decl.clone(), + )); + } + }, } } -pub(super) -fn import_module_exports( +pub(super) fn import_module_exports( retraction_info: &mut RetractionInfo, compilation_target: &CompilationTarget, imported_module: &Module, @@ -166,12 +161,7 @@ fn import_module_exports( } } ModuleExport::OpDecl(ref op_decl) => { - add_op_decl( - retraction_info, - compilation_target, - op_dir, - op_decl, - ); + add_op_decl(retraction_info, compilation_target, op_dir, op_decl); } } } @@ -185,7 +175,7 @@ fn import_module_exports_into_module( op_dir: &mut OpDir, meta_predicates: &mut MetaPredicateDir, wam_op_dir: &mut OpDir, - module_op_exports: &mut ModuleOpExports + module_op_exports: &mut ModuleOpExports, ) { for export in imported_module.module_decl.exports.iter() { match export { @@ -227,7 +217,6 @@ fn import_module_exports_into_module( } } - fn import_qualified_module_exports( retraction_info: &mut RetractionInfo, compilation_target: &CompilationTarget, @@ -263,12 +252,7 @@ fn import_qualified_module_exports( } } ModuleExport::OpDecl(ref op_decl) => { - add_op_decl( - retraction_info, - compilation_target, - op_dir, - op_decl, - ); + add_op_decl(retraction_info, compilation_target, op_dir, op_decl); } } } @@ -326,29 +310,28 @@ fn import_qualified_module_exports_into_module( impl<'a> LoadState<'a> { #[inline] - pub(super) - fn increment_clause_assert_margin(&mut self, incr: usize) { + pub(super) fn increment_clause_assert_margin(&mut self, incr: usize) { match &self.compilation_target { - CompilationTarget::User => { - } + CompilationTarget::User => {} CompilationTarget::Module(ref module_name) => { - self.retraction_info.push_record( - RetractionRecord::IncreasedClauseAssertMargin( + self.retraction_info + .push_record(RetractionRecord::IncreasedClauseAssertMargin( module_name.clone(), incr, - ), - ); + )); - self.wam.indices.modules.get_mut(module_name) + self.wam + .indices + .modules + .get_mut(module_name) .map(|module| module.clause_assert_margin += incr); } } } #[inline] - pub(super) - fn remove_module_op_exports(&mut self) { - for (mut op_decl, record) in self.module_op_exports.drain(0 ..) { + pub(super) fn remove_module_op_exports(&mut self) { + for (mut op_decl, record) in self.module_op_exports.drain(0..) { op_decl.remove(&mut self.wam.indices.op_dir); if let Some((prec, spec)) = record { @@ -365,26 +348,28 @@ impl<'a> LoadState<'a> { key: PredicateKey, ) -> CodeIndex { match self.wam.indices.modules.get_mut(&module_name) { - Some(ref mut module) => { - module.code_dir - .entry(key) - .or_insert_with(|| CodeIndex::new(IndexPtr::Undefined)) - .clone() - } + Some(ref mut module) => module + .code_dir + .entry(key) + .or_insert_with(|| CodeIndex::new(IndexPtr::Undefined)) + .clone(), None => { let mut module = Module::new( - ModuleDecl { name: module_name.clone(), exports: vec![] }, + ModuleDecl { + name: module_name.clone(), + exports: vec![], + }, ListingSource::DynamicallyGenerated, ); - let code_index = module.code_dir + let code_index = module + .code_dir .entry(key) .or_insert_with(|| CodeIndex::new(IndexPtr::Undefined)) .clone(); - self.retraction_info.push_record( - RetractionRecord::AddedModule(module_name.clone()), - ); + self.retraction_info + .push_record(RetractionRecord::AddedModule(module_name.clone())); self.wam.indices.modules.insert(module_name, module); code_index @@ -392,29 +377,31 @@ impl<'a> LoadState<'a> { } } - pub(super) - fn get_or_insert_code_index(&mut self, key: PredicateKey) -> CodeIndex { + pub(super) fn get_or_insert_code_index(&mut self, key: PredicateKey) -> CodeIndex { match self.compilation_target.clone() { - CompilationTarget::User => { - self.wam.indices.code_dir - .entry(key) - .or_insert_with(|| CodeIndex::new(IndexPtr::Undefined)) - .clone() - } + CompilationTarget::User => self + .wam + .indices + .code_dir + .entry(key) + .or_insert_with(|| CodeIndex::new(IndexPtr::Undefined)) + .clone(), CompilationTarget::Module(module_name) => { self.get_or_insert_local_code_index(module_name, key) } } } - pub(super) - fn get_or_insert_qualified_code_index( + pub(super) fn get_or_insert_qualified_code_index( &mut self, module_name: ClauseName, key: PredicateKey, ) -> CodeIndex { if module_name.as_str() == "user" { - return self.wam.indices.code_dir + return self + .wam + .indices + .code_dir .entry(key) .or_insert_with(|| CodeIndex::new(IndexPtr::Undefined)) .clone(); @@ -424,15 +411,20 @@ impl<'a> LoadState<'a> { } #[inline] - pub(super) - fn add_extensible_predicate(&mut self, key: PredicateKey, skeleton: PredicateSkeleton) { + pub(super) fn add_extensible_predicate( + &mut self, + key: PredicateKey, + skeleton: PredicateSkeleton, + ) { match &self.compilation_target { CompilationTarget::User => { - self.wam.indices.extensible_predicates.insert(key.clone(), skeleton); + self.wam + .indices + .extensible_predicates + .insert(key.clone(), skeleton); - self.retraction_info.push_record( - RetractionRecord::AddedUserExtensiblePredicate(key), - ); + self.retraction_info + .push_record(RetractionRecord::AddedUserExtensiblePredicate(key)); } CompilationTarget::Module(ref module_name) => { if let Some(module) = self.wam.indices.modules.get_mut(module_name) { @@ -448,8 +440,7 @@ impl<'a> LoadState<'a> { } } - pub(super) - fn add_op_decl(&mut self, op_decl: &OpDecl) { + pub(super) fn add_op_decl(&mut self, op_decl: &OpDecl) { match &self.compilation_target { CompilationTarget::User => { add_op_decl( @@ -479,8 +470,7 @@ impl<'a> LoadState<'a> { } } - pub(super) - fn get_clause_type( + pub(super) fn get_clause_type( &mut self, name: ClauseName, arity: usize, @@ -495,14 +485,11 @@ impl<'a> LoadState<'a> { let idx = self.get_or_insert_code_index((name.clone(), arity)); ClauseType::Op(name, fixity, idx) } - ct => { - ct - } + ct => ct, } } - pub(super) - fn get_qualified_clause_type( + pub(super) fn get_qualified_clause_type( &mut self, module_name: ClauseName, name: ClauseName, @@ -522,14 +509,11 @@ impl<'a> LoadState<'a> { ClauseType::Op(name, fixity, idx) } - ct => { - ct - } + ct => ct, } } - pub(super) - fn add_meta_predicate_record( + pub(super) fn add_meta_predicate_record( &mut self, module_name: ClauseName, name: ClauseName, @@ -540,20 +524,26 @@ impl<'a> LoadState<'a> { match module_name.as_str() { "user" => { - match self.wam.indices.meta_predicates.insert(key.clone(), meta_specs) { + match self + .wam + .indices + .meta_predicates + .insert(key.clone(), meta_specs) + { Some(old_meta_specs) => { - self.retraction_info.push_record( - RetractionRecord::ReplacedMetaPredicate( - module_name.clone(), key.0, old_meta_specs, - ), - ); + self.retraction_info + .push_record(RetractionRecord::ReplacedMetaPredicate( + module_name.clone(), + key.0, + old_meta_specs, + )); } None => { - self.retraction_info.push_record( - RetractionRecord::AddedMetaPredicate( - module_name.clone(), key, - ) - ); + self.retraction_info + .push_record(RetractionRecord::AddedMetaPredicate( + module_name.clone(), + key, + )); } } } @@ -564,15 +554,15 @@ impl<'a> LoadState<'a> { Some(old_meta_specs) => { self.retraction_info.push_record( RetractionRecord::ReplacedMetaPredicate( - module_name.clone(), key.0, old_meta_specs, + module_name.clone(), + key.0, + old_meta_specs, ), ); } None => { self.retraction_info.push_record( - RetractionRecord::AddedMetaPredicate( - module_name.clone(), key, - ) + RetractionRecord::AddedMetaPredicate(module_name.clone(), key), ); } } @@ -588,15 +578,14 @@ impl<'a> LoadState<'a> { module.meta_predicates.insert(key.clone(), meta_specs); - self.retraction_info.push_record( - RetractionRecord::AddedMetaPredicate( - module_name.clone(), key, - ) - ); + self.retraction_info + .push_record(RetractionRecord::AddedMetaPredicate( + module_name.clone(), + key, + )); - self.retraction_info.push_record( - RetractionRecord::AddedModule(module_name.clone()), - ); + self.retraction_info + .push_record(RetractionRecord::AddedModule(module_name.clone())); self.wam.indices.modules.insert(module_name, module); } @@ -623,32 +612,29 @@ impl<'a> LoadState<'a> { } } - pub(crate) - fn add_module(&mut self, module_decl: ModuleDecl, listing_src: ListingSource) { + pub(crate) fn add_module(&mut self, module_decl: ModuleDecl, listing_src: ListingSource) { let module_name = module_decl.name.clone(); - let mut module = - match self.wam.indices.modules.remove(&module_name) { - Some(mut module) => { - let old_module_decl = mem::replace(&mut module.module_decl, module_decl); + let mut module = match self.wam.indices.modules.remove(&module_name) { + Some(mut module) => { + let old_module_decl = mem::replace(&mut module.module_decl, module_decl); - self.retraction_info.push_record( - RetractionRecord::ReplacedModule( - old_module_decl, listing_src.clone(), - ), - ); + self.retraction_info + .push_record(RetractionRecord::ReplacedModule( + old_module_decl, + listing_src.clone(), + )); - module.listing_src = listing_src; - module - } - None => { - self.retraction_info.push_record( - RetractionRecord::AddedModule(module_name.clone()), - ); + module.listing_src = listing_src; + module + } + None => { + self.retraction_info + .push_record(RetractionRecord::AddedModule(module_name.clone())); - Module::new(module_decl, listing_src) - } - }; + Module::new(module_decl, listing_src) + } + }; self.import_builtins_in_module( &mut module.code_dir, @@ -676,8 +662,7 @@ impl<'a> LoadState<'a> { self.wam.indices.modules.insert(module_name, module); } - pub(super) - fn import_module(&mut self, module_name: ClauseName) -> Result<(), SessionError> { + pub(super) fn import_module(&mut self, module_name: ClauseName) -> Result<(), SessionError> { if let Some(module) = self.wam.indices.modules.remove(&module_name) { match &self.compilation_target { CompilationTarget::User => { @@ -717,7 +702,9 @@ impl<'a> LoadState<'a> { self.wam.indices.modules.insert(module_name, module); Ok(()) } else { - Err(SessionError::ExistenceError(ExistenceError::Module(module_name))) + Err(SessionError::ExistenceError(ExistenceError::Module( + module_name, + ))) } } @@ -765,41 +752,41 @@ impl<'a> LoadState<'a> { self.wam.indices.modules.insert(module_name, module); Ok(()) } else { - Err(SessionError::ExistenceError(ExistenceError::Module(module_name))) + Err(SessionError::ExistenceError(ExistenceError::Module( + module_name, + ))) } } - pub(crate) - fn use_module(&mut self, module_src: ModuleSource) -> Result<(), SessionError> { - let (stream, listing_src) = - match module_src { - ModuleSource::File(filename) => { - let mut path_buf = PathBuf::from(filename.as_str()); - path_buf.set_extension("pl"); - let file = File::open(&path_buf)?; + pub(crate) fn use_module(&mut self, module_src: ModuleSource) -> Result<(), SessionError> { + let (stream, listing_src) = match module_src { + ModuleSource::File(filename) => { + let mut path_buf = PathBuf::from(filename.as_str()); + path_buf.set_extension("pl"); + let file = File::open(&path_buf)?; - (Stream::from_file_as_input(filename.clone(), file), - ListingSource::File(filename, path_buf)) - } - ModuleSource::Library(library) => { - match LIBRARIES.borrow().get(library.as_str()) { - Some(code) => { - if let Some(ref module) = self.wam.indices.modules.get(&library) { - if let ListingSource::DynamicallyGenerated = &module.listing_src { - (Stream::from(*code), ListingSource::User) - } else { - return self.import_module(library); - } - } else { - (Stream::from(*code), ListingSource::User) - } - } - None => { + ( + Stream::from_file_as_input(filename.clone(), file), + ListingSource::File(filename, path_buf), + ) + } + ModuleSource::Library(library) => match LIBRARIES.borrow().get(library.as_str()) { + Some(code) => { + if let Some(ref module) = self.wam.indices.modules.get(&library) { + if let ListingSource::DynamicallyGenerated = &module.listing_src { + (Stream::from(*code), ListingSource::User) + } else { return self.import_module(library); } + } else { + (Stream::from(*code), ListingSource::User) } } - }; + None => { + return self.import_module(library); + } + }, + }; let compilation_target = { let stream = &mut parsing_stream(stream)?; @@ -820,43 +807,39 @@ impl<'a> LoadState<'a> { // nothing to do. Ok(()) } - CompilationTarget::Module(module_name) => { - self.import_module(module_name) - } + CompilationTarget::Module(module_name) => self.import_module(module_name), } } - pub(crate) - fn use_qualified_module( + pub(crate) fn use_qualified_module( &mut self, module_src: ModuleSource, exports: IndexSet, ) -> Result<(), SessionError> { - let (stream, listing_src) = - match module_src { - ModuleSource::File(filename) => { - let mut path_buf = PathBuf::from(filename.as_str()); - path_buf.set_extension("pl"); - let file = File::open(&path_buf)?; + let (stream, listing_src) = match module_src { + ModuleSource::File(filename) => { + let mut path_buf = PathBuf::from(filename.as_str()); + path_buf.set_extension("pl"); + let file = File::open(&path_buf)?; - (Stream::from_file_as_input(filename.clone(), file), - ListingSource::File(filename, path_buf)) - } - ModuleSource::Library(library) => { - match LIBRARIES.borrow().get(library.as_str()) { - Some(code) => { - if self.wam.indices.modules.contains_key(&library) { - return self.import_qualified_module(library, exports); - } else { - (Stream::from(*code), ListingSource::User) - } - } - None => { - return self.import_qualified_module(library, exports); - } + ( + Stream::from_file_as_input(filename.clone(), file), + ListingSource::File(filename, path_buf), + ) + } + ModuleSource::Library(library) => match LIBRARIES.borrow().get(library.as_str()) { + Some(code) => { + if self.wam.indices.modules.contains_key(&library) { + return self.import_qualified_module(library, exports); + } else { + (Stream::from(*code), ListingSource::User) } } - }; + None => { + return self.import_qualified_module(library, exports); + } + }, + }; let compilation_target = { let stream = &mut parsing_stream(stream)?; @@ -884,12 +867,9 @@ impl<'a> LoadState<'a> { } #[inline] - pub(super) - fn composite_op_dir(&self) -> CompositeOpDir { + pub(super) fn composite_op_dir(&self) -> CompositeOpDir { match &self.compilation_target { - CompilationTarget::User => { - CompositeOpDir::new(&self.wam.indices.op_dir, None) - } + CompilationTarget::User => CompositeOpDir::new(&self.wam.indices.op_dir, None), CompilationTarget::Module(ref module_name) => { match self.wam.indices.modules.get(module_name) { Some(ref module) => { diff --git a/src/machine/loader.rs b/src/machine/loader.rs index e7eb1165..040e478c 100644 --- a/src/machine/loader.rs +++ b/src/machine/loader.rs @@ -1,11 +1,12 @@ use prolog_parser_rebis::ast::*; +use prolog_parser_rebis::{clause_name, temp_v}; use crate::forms::*; use crate::indexing::*; -use crate::machine::*; use crate::machine::load_state::*; use crate::machine::machine_indices::*; use crate::machine::preprocessor::*; +use crate::machine::*; use indexmap::IndexSet; @@ -77,7 +78,13 @@ pub(crate) enum RetractionRecord { SkeletonClausePopFront(CompilationTarget, PredicateKey), SkeletonClauseTruncateBack(CompilationTarget, PredicateKey, usize), SkeletonClauseStartReplaced(CompilationTarget, PredicateKey, usize, usize), - RemovedDynamicSkeletonClause(CompilationTarget, PredicateKey, usize, ClauseIndexInfo, usize), + RemovedDynamicSkeletonClause( + CompilationTarget, + PredicateKey, + usize, + ClauseIndexInfo, + usize, + ), ReplacedIndexingLine(usize, Vec), } @@ -97,8 +104,7 @@ pub(super) struct RetractionInfo { impl RetractionInfo { #[inline] - pub(super) - fn new(orig_code_extent: usize) -> Self { + pub(super) fn new(orig_code_extent: usize) -> Self { Self { orig_code_extent, records: vec![], //BTreeMap::new(), @@ -106,14 +112,12 @@ impl RetractionInfo { } #[inline] - pub(crate) - fn push_record(&mut self, record: RetractionRecord) { + pub(crate) fn push_record(&mut self, record: RetractionRecord) { self.records.push(record); } #[inline] - pub(crate) - fn reset(&mut self, code_len: usize) -> Self { + pub(crate) fn reset(&mut self, code_len: usize) -> Self { let orig_code_extent = self.orig_code_extent; self.orig_code_extent = code_len; @@ -133,39 +137,34 @@ impl<'a> Drop for LoadState<'a> { "user" => { self.wam.indices.meta_predicates.remove(&key); } - _ => { - match self.wam.indices.modules.get_mut(&target_module_name) { - Some(ref mut module) => { - module.meta_predicates.remove(&key); - } - _ => { - unreachable!() - } + _ => match self.wam.indices.modules.get_mut(&target_module_name) { + Some(ref mut module) => { + module.meta_predicates.remove(&key); } - } + _ => { + unreachable!() + } + }, } } RetractionRecord::ReplacedMetaPredicate(target_module_name, name, meta_specs) => { match target_module_name.as_str() { "user" => { - self.wam.indices.meta_predicates.insert( - (name, meta_specs.len()), - meta_specs, - ); + self.wam + .indices + .meta_predicates + .insert((name, meta_specs.len()), meta_specs); } - _ => { - match self.wam.indices.modules.get_mut(&target_module_name) { - Some(ref mut module) => { - module.meta_predicates.insert( - (name, meta_specs.len()), - meta_specs, - ); - } - _ => { - unreachable!() - } + _ => match self.wam.indices.modules.get_mut(&target_module_name) { + Some(ref mut module) => { + module + .meta_predicates + .insert((name, meta_specs.len()), meta_specs); } - } + _ => { + unreachable!() + } + }, } } RetractionRecord::AddedModule(module_name) => { @@ -185,44 +184,40 @@ impl<'a> Drop for LoadState<'a> { RetractionRecord::AddedModuleDynamicPredicate(module_name, key) => { match self.wam.indices.modules.get_mut(&module_name) { Some(ref mut module) => { - module.extensible_predicates.get_mut(&key) - .map(|skeleton| { - skeleton.is_dynamic = false; - }); - } - None => { + module.extensible_predicates.get_mut(&key).map(|skeleton| { + skeleton.is_dynamic = false; + }); } + None => {} } } RetractionRecord::AddedModuleExtensiblePredicate(module_name, key) => { - self.wam.indices.remove_predicate_skeleton( - &CompilationTarget::Module(module_name), - &key, - ); + self.wam + .indices + .remove_predicate_skeleton(&CompilationTarget::Module(module_name), &key); } RetractionRecord::AppendedModuleExtensiblePredicate(module_name, key) => { - self.wam.indices.get_predicate_skeleton( - &CompilationTarget::Module(module_name), - &key, - ).map(|skeleton| { - skeleton.clauses.pop_back(); - }); + self.wam + .indices + .get_predicate_skeleton(&CompilationTarget::Module(module_name), &key) + .map(|skeleton| { + skeleton.clauses.pop_back(); + }); } RetractionRecord::PrependedModuleExtensiblePredicate(module_name, key) => { - self.wam.indices.get_predicate_skeleton( - &CompilationTarget::Module(module_name), - &key, - ).map(|skeleton| { - skeleton.clauses.pop_front(); - }); + self.wam + .indices + .get_predicate_skeleton(&CompilationTarget::Module(module_name), &key) + .map(|skeleton| { + skeleton.clauses.pop_front(); + }); } RetractionRecord::AddedModuleOp(module_name, mut op_decl) => { match self.wam.indices.modules.get_mut(&module_name) { Some(ref mut module) => { op_decl.remove(&mut module.op_dir); } - None => { - } + None => {} } } RetractionRecord::ReplacedModuleOp(module_name, mut op_decl, prec, spec) => { @@ -232,8 +227,7 @@ impl<'a> Drop for LoadState<'a> { op_decl.spec = spec; op_decl.insert_into_op_dir(&mut module.op_dir); } - None => { - } + None => {} } } RetractionRecord::AddedModulePredicate(module_name, key) => { @@ -241,48 +235,49 @@ impl<'a> Drop for LoadState<'a> { Some(ref mut module) => { module.code_dir.remove(&key); } - None => { - } + None => {} } } RetractionRecord::ReplacedModulePredicate(module_name, key, old_code_idx) => { match self.wam.indices.modules.get_mut(&module_name) { Some(ref mut module) => { - module.code_dir + module + .code_dir .get_mut(&key) .map(|code_idx| code_idx.replace(old_code_idx)); } - None => { - } + None => {} } } RetractionRecord::AddedUserDynamicPredicate(key) => { - self.wam.indices.extensible_predicates.get_mut(&key) + self.wam + .indices + .extensible_predicates + .get_mut(&key) .map(|skeleton| { skeleton.is_dynamic = false; }); } RetractionRecord::AddedUserExtensiblePredicate(key) => { - self.wam.indices.remove_predicate_skeleton( - &CompilationTarget::User, - &key, - ); + self.wam + .indices + .remove_predicate_skeleton(&CompilationTarget::User, &key); } RetractionRecord::AppendedUserExtensiblePredicate(key) => { - self.wam.indices.get_predicate_skeleton( - &CompilationTarget::User, - &key, - ).map(|skeleton| { - skeleton.clauses.pop_back(); - }); + self.wam + .indices + .get_predicate_skeleton(&CompilationTarget::User, &key) + .map(|skeleton| { + skeleton.clauses.pop_back(); + }); } RetractionRecord::PrependedUserExtensiblePredicate(key) => { - self.wam.indices.get_predicate_skeleton( - &CompilationTarget::User, - &key, - ).map(|skeleton| { - skeleton.clauses.pop_front(); - }); + self.wam + .indices + .get_predicate_skeleton(&CompilationTarget::User, &key) + .map(|skeleton| { + skeleton.clauses.pop_front(); + }); } RetractionRecord::AddedUserOp(mut op_decl) => { op_decl.remove(&mut self.wam.indices.op_dir); @@ -296,24 +291,29 @@ impl<'a> Drop for LoadState<'a> { self.wam.indices.code_dir.remove(&key); } RetractionRecord::ReplacedUserPredicate(key, old_code_idx) => { - self.wam.indices.code_dir + self.wam + .indices + .code_dir .get_mut(&key) .map(|code_idx| code_idx.replace(old_code_idx)); } - RetractionRecord::AddedIndex(index_key, clause_loc) => { // WAS: inner_index_locs) => { + RetractionRecord::AddedIndex(index_key, clause_loc) => { + // WAS: inner_index_locs) => { if let Some(index_loc) = index_key.switch_on_term_loc() { - let indexing_code = - match &mut self.wam.code_repo.code[index_loc] { - Line::IndexingCode(indexing_code) => { - indexing_code - } - _ => { - unreachable!() - } - }; + let indexing_code = match &mut self.wam.code_repo.code[index_loc] { + Line::IndexingCode(indexing_code) => indexing_code, + _ => { + unreachable!() + } + }; match index_key { - OptArgIndexKey::Constant(_, index_loc, constant, overlapping_constants) => { + OptArgIndexKey::Constant( + _, + index_loc, + constant, + overlapping_constants, + ) => { remove_constant_indices( &constant, &overlapping_constants, @@ -348,9 +348,9 @@ impl<'a> Drop for LoadState<'a> { } RetractionRecord::ReplacedChoiceOffset(instr_loc, offset) => { match &mut self.wam.code_repo.code[instr_loc] { - Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) | - Line::Choice(ChoiceInstruction::RetryMeElse(ref mut o)) | - Line::Choice(ChoiceInstruction::DefaultRetryMeElse(ref mut o)) => { + Line::Choice(ChoiceInstruction::TryMeElse(ref mut o)) + | Line::Choice(ChoiceInstruction::RetryMeElse(ref mut o)) + | Line::Choice(ChoiceInstruction::DefaultRetryMeElse(ref mut o)) => { *o = offset; } _ => { @@ -374,19 +374,17 @@ impl<'a> Drop for LoadState<'a> { } RetractionRecord::ReplacedSwitchOnTermVarIndex(index_loc, old_v) => { match &mut self.wam.code_repo.code[index_loc] { - Line::IndexingCode(ref mut indexing_code) => { - match &mut indexing_code[0] { - IndexingLine::Indexing( - IndexingInstruction::SwitchOnTerm(_, ref mut v, ..) - ) => { - *v = old_v; - } - _ => { - } + Line::IndexingCode(ref mut indexing_code) => match &mut indexing_code[0] { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( + _, + ref mut v, + .., + )) => { + *v = old_v; } - } - _ => { - } + _ => {} + }, + _ => {} } } RetractionRecord::ModifiedTryMeElse(instr_loc, o) => { @@ -406,106 +404,108 @@ impl<'a> Drop for LoadState<'a> { module.clause_assert_margin -= incr; } } - RetractionRecord::SkeletonClauseClausesTruncateFront(compilation_target, key, len) => { - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + RetractionRecord::SkeletonClauseClausesTruncateFront( + compilation_target, + key, + len, + ) => { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { skeleton.clause_clause_locs.truncate_front(len); } - None => { - } + None => {} } - let compilation_target = - match compilation_target { - CompilationTarget::User => { - CompilationTarget::Module(clause_name!("builtins")) - } - _ => { - compilation_target - } - }; + let compilation_target = match compilation_target { + CompilationTarget::User => { + CompilationTarget::Module(clause_name!("builtins")) + } + _ => compilation_target, + }; - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &(clause_name!("$clause"), 2), - ) { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &(clause_name!("$clause"), 2)) + { Some(skeleton) => { skeleton.clause_clause_locs.truncate_front(len); } - None => { - } + None => {} } } - RetractionRecord::SkeletonClauseClausesTruncateBack(compilation_target, key, len) => { - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + RetractionRecord::SkeletonClauseClausesTruncateBack( + compilation_target, + key, + len, + ) => { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { skeleton.clause_clause_locs.truncate_back(len); } - None => { - } + None => {} } - let compilation_target = - match compilation_target { - CompilationTarget::User => { - CompilationTarget::Module(clause_name!("builtins")) - } - _ => { - compilation_target - } - }; + let compilation_target = match compilation_target { + CompilationTarget::User => { + CompilationTarget::Module(clause_name!("builtins")) + } + _ => compilation_target, + }; - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &(clause_name!("$clause"), 2), - ) { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &(clause_name!("$clause"), 2)) + { Some(skeleton) => { skeleton.clause_clause_locs.truncate_back(len); } - None => { - } + None => {} } } RetractionRecord::SkeletonClausePopBack(compilation_target, key) => { - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { skeleton.clauses.pop_back(); } - None => { - } + None => {} } } RetractionRecord::SkeletonClausePopFront(compilation_target, key) => { - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { skeleton.clauses.pop_front(); } - None => { - } + None => {} } } RetractionRecord::SkeletonClauseTruncateBack(compilation_target, key, len) => { - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { skeleton.clauses.truncate_back(len); } - None => { - } + None => {} } } RetractionRecord::SkeletonClauseStartReplaced( @@ -514,15 +514,15 @@ impl<'a> Drop for LoadState<'a> { target_pos, clause_start, ) => { - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { skeleton.clauses[target_pos].clause_start = clause_start; } - None => { - } + None => {} } } RetractionRecord::RemovedDynamicSkeletonClause( @@ -532,16 +532,18 @@ impl<'a> Drop for LoadState<'a> { clause_index_info, clause_clause_loc, ) => { - match self.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { - skeleton.clause_clause_locs.insert(target_pos, clause_clause_loc); + skeleton + .clause_clause_locs + .insert(target_pos, clause_clause_loc); skeleton.clauses.insert(target_pos, clause_index_info); } - None => { - } + None => {} } } RetractionRecord::ReplacedIndexingLine(index_loc, indexing_code) => { @@ -570,21 +572,17 @@ impl Default for CompilationTarget { impl CompilationTarget { #[inline] - pub(super) - fn take(&mut self) -> CompilationTarget { + pub(super) fn take(&mut self) -> CompilationTarget { mem::replace(self, CompilationTarget::User) } #[inline] - pub(super) - fn module_name(&self) -> ClauseName { + pub(super) fn module_name(&self) -> ClauseName { match self { CompilationTarget::User => { clause_name!("user") } - CompilationTarget::Module(ref module_name) => { - module_name.clone() - } + CompilationTarget::Module(ref module_name) => module_name.clone(), } } } @@ -600,8 +598,7 @@ pub(crate) struct Loader<'a, TermStream> { impl<'a, TS: TermStream> Loader<'a, TS> { #[inline] - pub(super) - fn new(term_stream: TS, wam: &'a mut Machine) -> Self { + pub(super) fn new(term_stream: TS, wam: &'a mut Machine) -> Self { let flags = wam.machine_st.flags; let load_state = LoadState { compilation_target: CompilationTarget::User, @@ -620,8 +617,7 @@ impl<'a, TS: TermStream> Loader<'a, TS> { } } - pub(crate) - fn load(mut self) -> Result { + pub(crate) fn load(mut self) -> Result { while let Some(decl) = self.dequeue_terms()? { self.load_decl(decl)?; } @@ -645,43 +641,32 @@ impl<'a, TS: TermStream> Loader<'a, TS> { )?; match tl { - TopLevel::Fact(fact) => - self.predicates.push(PredicateClause::Fact(fact)), - TopLevel::Rule(rule) => - self.predicates.push(PredicateClause::Rule(rule)), - TopLevel::Predicate(pred) => - self.predicates.extend(pred), - TopLevel::Declaration(decl) => - return Ok(Some(decl)), - TopLevel::Query(_) => - return Err(SessionError::QueryCannotBeDefinedAsFact), + TopLevel::Fact(fact) => self.predicates.push(PredicateClause::Fact(fact)), + TopLevel::Rule(rule) => self.predicates.push(PredicateClause::Rule(rule)), + TopLevel::Predicate(pred) => self.predicates.extend(pred), + TopLevel::Declaration(decl) => return Ok(Some(decl)), + TopLevel::Query(_) => return Err(SessionError::QueryCannotBeDefinedAsFact), } } Ok(None) } - pub(super) - fn load_decl(&mut self, decl: Declaration) -> Result<(), SessionError> { + pub(super) fn load_decl(&mut self, decl: Declaration) -> Result<(), SessionError> { match decl { Declaration::Dynamic(name, arity) => { self.add_dynamic_predicate(name, arity); } Declaration::MetaPredicate(module_name, name, meta_specs) => { - self.load_state.add_meta_predicate_record( - module_name, - name, - meta_specs, - ); + self.load_state + .add_meta_predicate_record(module_name, name, meta_specs); } Declaration::Module(module_decl) => { self.load_state.compilation_target = CompilationTarget::Module(module_decl.name.clone()); - self.load_state.add_module( - module_decl, - self.term_stream.listing_src().clone(), - ); + self.load_state + .add_module(module_decl, self.term_stream.listing_src().clone()); } Declaration::NonCountedBacktracking(name, arity) => { self.non_counted_bt_preds.insert((name, arity)); @@ -700,10 +685,9 @@ impl<'a, TS: TermStream> Loader<'a, TS> { Ok(()) } - pub(super) - fn read_term_from_heap(&self, heap_term_loc: RegType) -> Result { + pub(super) fn read_term_from_heap(&self, heap_term_loc: RegType) -> Result { let machine_st = &self.load_state.wam.machine_st; - let term_addr = machine_st[heap_term_loc]; + let term_addr = machine_st[heap_term_loc]; if machine_st.is_cyclic_term(term_addr) { return Err(SessionError::from(CompilationError::CannotParseCyclicTerm)); @@ -713,31 +697,20 @@ impl<'a, TS: TermStream> Loader<'a, TS> { for addr in machine_st.post_order_iter(term_addr) { match machine_st.heap.index_addr(&addr).as_ref() { - HeapCellValue::Addr(Addr::Lis(_)) | - HeapCellValue::Addr(Addr::PStrLocation(..)) => { + HeapCellValue::Addr(Addr::Lis(_)) | HeapCellValue::Addr(Addr::PStrLocation(..)) => { let tail = term_stack.pop().unwrap(); let head = term_stack.pop().unwrap(); - term_stack.push(Term::Cons( - Cell::default(), - Box::new(head), - Box::new(tail), - )); + term_stack.push(Term::Cons(Cell::default(), Box::new(head), Box::new(tail))); } HeapCellValue::Addr(addr) => { if let Some(r) = addr.as_var() { - let offset_string = - match r { - Ref::HeapCell(h) | Ref::AttrVar(h) => - format!("_{}", h), - Ref::StackCell(fr, sc) => - format!("_s_{}_{}", fr, sc), - }; + let offset_string = match r { + Ref::HeapCell(h) | Ref::AttrVar(h) => format!("_{}", h), + Ref::StackCell(fr, sc) => format!("_s_{}_{}", fr, sc), + }; - term_stack.push(Term::Var( - Cell::default(), - Rc::new(offset_string), - )); + term_stack.push(Term::Var(Cell::default(), Rc::new(offset_string))); } else { match addr.as_constant_index(machine_st) { Some(constant) => { @@ -762,7 +735,8 @@ impl<'a, TS: TermStream> Loader<'a, TS> { )); } HeapCellValue::NamedStr(arity, ref name, ref shared_op_desc) => { - let subterms = term_stack.drain(term_stack.len() - arity ..) + let subterms = term_stack + .drain(term_stack.len() - arity..) .map(Box::new) .collect(); @@ -810,18 +784,16 @@ impl<'a, TS: TermStream> Loader<'a, TS> { fn add_clause_clause(&mut self, term: Term) -> Result<(), CompilationError> { match term { Term::Clause(_, turnstile, mut terms, _) - if turnstile.as_str() == ":-" && terms.len() == 2 => { - let body = *terms.pop().unwrap(); - let head = *terms.pop().unwrap(); + if turnstile.as_str() == ":-" && terms.len() == 2 => + { + let body = *terms.pop().unwrap(); + let head = *terms.pop().unwrap(); - self.clause_clauses.push((head, body)); - } - head @ Term::Constant(_, Constant::Atom(..)) | - head @ Term::Clause(..) => { - let body = Term::Constant( - Cell::default(), - Constant::Atom(clause_name!("true"), None), - ); + self.clause_clauses.push((head, body)); + } + head @ Term::Constant(_, Constant::Atom(..)) | head @ Term::Clause(..) => { + let body = + Term::Constant(Cell::default(), Constant::Atom(clause_name!("true"), None)); self.clause_clauses.push((head, body)); } @@ -838,59 +810,63 @@ impl<'a, TS: TermStream> Loader<'a, TS> { match &self.load_state.compilation_target { CompilationTarget::User => { - match self.load_state.wam.indices.extensible_predicates.get_mut(&key) { + match self + .load_state + .wam + .indices + .extensible_predicates + .get_mut(&key) + { Some(ref mut skeleton) => { if !skeleton.is_dynamic { skeleton.is_dynamic = true; self.load_state.retraction_info.push_record( - RetractionRecord::AddedUserDynamicPredicate(key.clone()) + RetractionRecord::AddedUserDynamicPredicate(key.clone()), ); } } None => { - self.load_state.wam.indices.extensible_predicates.insert( - key.clone(), - PredicateSkeleton::new().set_dynamic(true), - ); + self.load_state + .wam + .indices + .extensible_predicates + .insert(key.clone(), PredicateSkeleton::new().set_dynamic(true)); self.load_state.retraction_info.push_record( - RetractionRecord::AddedUserExtensiblePredicate(key.clone()) + RetractionRecord::AddedUserExtensiblePredicate(key.clone()), ); } } } CompilationTarget::Module(ref module_name) => { match self.load_state.wam.indices.modules.get_mut(module_name) { - Some(ref mut module) => { - match module.extensible_predicates.get_mut(&key) { - Some(ref mut skeleton) => { - if !skeleton.is_dynamic { - skeleton.is_dynamic = true; - - self.load_state.retraction_info.push_record( - RetractionRecord::AddedModuleDynamicPredicate( - module_name.clone(), - key.clone(), - ), - ); - } - } - None => { - module.extensible_predicates.insert( - key.clone(), - PredicateSkeleton::new().set_dynamic(true), - ); + Some(ref mut module) => match module.extensible_predicates.get_mut(&key) { + Some(ref mut skeleton) => { + if !skeleton.is_dynamic { + skeleton.is_dynamic = true; self.load_state.retraction_info.push_record( - RetractionRecord::AddedModuleExtensiblePredicate( + RetractionRecord::AddedModuleDynamicPredicate( module_name.clone(), key.clone(), ), ); } } - } + None => { + module + .extensible_predicates + .insert(key.clone(), PredicateSkeleton::new().set_dynamic(true)); + + self.load_state.retraction_info.push_record( + RetractionRecord::AddedModuleExtensiblePredicate( + module_name.clone(), + key.clone(), + ), + ); + } + }, None => { unreachable!(); } @@ -911,36 +887,27 @@ impl<'a, TS: TermStream> Loader<'a, TS> { } impl Machine { - pub(crate) - fn use_module(&mut self) { - let subevacuable_addr = - self.machine_st.store(self.machine_st.deref(self.machine_st[temp_v!(2)])); + pub(crate) fn use_module(&mut self) { + let subevacuable_addr = self + .machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(2)])); - let module_src = - ModuleSource::Library( - match subevacuable_addr { - Addr::LoadStatePayload(payload) => { - match &self.machine_st.heap[payload] { - HeapCellValue::LoadStatePayload(payload) => { - match &payload.compilation_target { - CompilationTarget::Module(ref module_name) => { - module_name.clone() - } - CompilationTarget::User => { - return; - } - } - } - _ => { - unreachable!() - } - } - } - _ => { - unreachable!() + let module_src = ModuleSource::Library(match subevacuable_addr { + Addr::LoadStatePayload(payload) => match &self.machine_st.heap[payload] { + HeapCellValue::LoadStatePayload(payload) => match &payload.compilation_target { + CompilationTarget::Module(ref module_name) => module_name.clone(), + CompilationTarget::User => { + return; } + }, + _ => { + unreachable!() } - ); + }, + _ => { + unreachable!() + } + }); let (mut loader, evacuable_h) = self.loader_from_heap_evacuable(temp_v!(1)); @@ -950,7 +917,9 @@ impl Machine { if export_list.is_empty() { loader.load_state.use_module(module_src)?; } else { - loader.load_state.use_qualified_module(module_src, export_list)?; + loader + .load_state + .use_qualified_module(module_src, export_list)?; } LiveTermStream::evacuate(loader) @@ -960,13 +929,11 @@ impl Machine { self.restore_load_state_payload(result, evacuable_h); } - pub(crate) - fn load_compiled_library(&mut self) { + pub(crate) fn load_compiled_library(&mut self) { let library = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); if let Some(module) = self.indices.modules.get(&library) { @@ -989,13 +956,11 @@ impl Machine { } } - pub(crate) - fn declare_module(&mut self) { + pub(crate) fn declare_module(&mut self) { let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); // let export_list = self.machine_st.extract_module_export_list(temp_v!(2)); @@ -1018,27 +983,24 @@ impl Machine { self.restore_load_state_payload(result, evacuable_h); } - pub(crate) - fn add_dynamic_predicate(&mut self) { + pub(crate) fn add_dynamic_predicate(&mut self) { let predicate_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); - let arity = - self.machine_st.store(self.machine_st.deref(self.machine_st[temp_v!(2)])); + let arity = self + .machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(2)])); - let arity = - match Number::try_from((arity, &self.machine_st.heap)) { - Ok(Number::Integer(n)) if &*n >= &0 && &*n <= &MAX_ARITY => - Ok(n.to_usize().unwrap()), - Ok(Number::Fixnum(n)) if n >= 0 && n <= MAX_ARITY as isize => - Ok(usize::try_from(n).unwrap()), - _ => - Err(SessionError::from(CompilationError::InvalidRuleHead)) - }; + let arity = match Number::try_from((arity, &self.machine_st.heap)) { + Ok(Number::Integer(n)) if &*n >= &0 && &*n <= &MAX_ARITY => Ok(n.to_usize().unwrap()), + Ok(Number::Fixnum(n)) if n >= 0 && n <= MAX_ARITY as isize => { + Ok(usize::try_from(n).unwrap()) + } + _ => Err(SessionError::from(CompilationError::InvalidRuleHead)), + }; let (mut loader, evacuable_h) = self.loader_from_heap_evacuable(temp_v!(3)); @@ -1051,8 +1013,7 @@ impl Machine { self.restore_load_state_payload(result, evacuable_h); } - pub(crate) - fn add_term_expansion_clause(&mut self) { + pub(crate) fn add_term_expansion_clause(&mut self) { let (mut loader, evacuable_h) = self.loader_from_heap_evacuable(temp_v!(2)); let add_clause = || { @@ -1073,22 +1034,19 @@ impl Machine { self.restore_load_state_payload(result, evacuable_h); } - pub(crate) - fn add_goal_expansion_clause(&mut self) { + pub(crate) fn add_goal_expansion_clause(&mut self) { let target_module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); let (mut loader, evacuable_h) = self.loader_from_heap_evacuable(temp_v!(3)); - let compilation_target = - match target_module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(target_module_name), - }; + let compilation_target = match target_module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(target_module_name), + }; let add_clause = || { let term = loader.read_term_from_heap(temp_v!(2))?; @@ -1108,22 +1066,25 @@ impl Machine { self.restore_load_state_payload(result, evacuable_h); } - pub(crate) - fn loader_from_heap_evacuable(&mut self, r: RegType) -> (Loader, usize) { - let (load_state_payload, evacuable_h) = - match self.machine_st.store(self.machine_st.deref(self.machine_st[r])) { - Addr::LoadStatePayload(h) => { - ( mem::replace( - &mut self.machine_st.heap[h], - HeapCellValue::Addr(Addr::EmptyList), - ), - h, - ) - } - _ => { - unreachable!() - } - }; + pub(crate) fn loader_from_heap_evacuable( + &mut self, + r: RegType, + ) -> (Loader, usize) { + let (load_state_payload, evacuable_h) = match self + .machine_st + .store(self.machine_st.deref(self.machine_st[r])) + { + Addr::LoadStatePayload(h) => ( + mem::replace( + &mut self.machine_st.heap[h], + HeapCellValue::Addr(Addr::EmptyList), + ), + h, + ), + _ => { + unreachable!() + } + }; match load_state_payload { HeapCellValue::LoadStatePayload(payload) => { @@ -1136,31 +1097,32 @@ impl Machine { } #[inline] - pub(crate) - fn push_load_state_payload(&mut self) { + pub(crate) fn push_load_state_payload(&mut self) { let payload = LoadStatePayload::new(self); let addr = Addr::LoadStatePayload( - self.machine_st.heap.push(HeapCellValue::LoadStatePayload(payload)) + self.machine_st + .heap + .push(HeapCellValue::LoadStatePayload(payload)), ); - self.machine_st.bind(self.machine_st[temp_v!(1)].as_var().unwrap(), addr); + self.machine_st + .bind(self.machine_st[temp_v!(1)].as_var().unwrap(), addr); } #[inline] - pub(crate) - fn pop_load_state_payload(&mut self) { - let load_state_payload = - match self.machine_st.store(self.machine_st.deref(self.machine_st[temp_v!(1)])) { - Addr::LoadStatePayload(h) => { - mem::replace( - &mut self.machine_st.heap[h], - HeapCellValue::Addr(Addr::EmptyList), - ) - } - _ => { - unreachable!() - } - }; + pub(crate) fn pop_load_state_payload(&mut self) { + let load_state_payload = match self + .machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) + { + Addr::LoadStatePayload(h) => mem::replace( + &mut self.machine_st.heap[h], + HeapCellValue::Addr(Addr::EmptyList), + ), + _ => { + unreachable!() + } + }; match load_state_payload { HeapCellValue::LoadStatePayload(payload) => { @@ -1177,46 +1139,39 @@ impl Machine { } #[inline] - pub(crate) - fn pop_load_context(&mut self) { + pub(crate) fn pop_load_context(&mut self) { self.load_contexts.pop(); } - pub(crate) - fn push_load_context(&mut self) { - let stream = - try_or_fail!( - self.machine_st, - self.machine_st.get_stream_or_alias( - self.machine_st[temp_v!(1)], - &self.indices, - "$push_load_context", - 2, - ) - ); + pub(crate) fn push_load_context(&mut self) { + let stream = try_or_fail!( + self.machine_st, + self.machine_st.get_stream_or_alias( + self.machine_st[temp_v!(1)], + &self.indices, + "$push_load_context", + 2, + ) + ); - let path = - atom_from!( - self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(2)] - )) - ); + let path = atom_from!( + self.machine_st, + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(2)])) + ); - self.load_contexts.push(LoadContext::new(path.as_str(), stream)); + self.load_contexts + .push(LoadContext::new(path.as_str(), stream)); } - pub(crate) - fn restore_load_state_payload( + pub(crate) fn restore_load_state_payload( &mut self, result: Result, evacuable_h: usize, ) { match result { Ok(payload) => { - self.machine_st.heap[evacuable_h] = HeapCellValue::LoadStatePayload( - payload - ); + self.machine_st.heap[evacuable_h] = HeapCellValue::LoadStatePayload(payload); } Err(e) => { self.throw_session_error(e, (clause_name!("load"), 1)); @@ -1224,8 +1179,7 @@ impl Machine { } } - pub(crate) - fn clause_to_evacuable(&mut self) { + pub(crate) fn clause_to_evacuable(&mut self) { let (mut loader, evacuable_h) = self.loader_from_heap_evacuable(temp_v!(2)); let enqueue_term = || { @@ -1234,12 +1188,16 @@ impl Machine { if let Some(predicate_name) = ClauseInfo::name(&term) { let arity = ClauseInfo::arity(&term); - let is_dynamic = - loader.load_state.wam.indices.get_predicate_skeleton( + let is_dynamic = loader + .load_state + .wam + .indices + .get_predicate_skeleton( &loader.load_state.compilation_target, &(predicate_name, arity), - ).map(|skeleton| skeleton.is_dynamic) - .unwrap_or(false); + ) + .map(|skeleton| skeleton.is_dynamic) + .unwrap_or(false); if is_dynamic { loader.add_clause_clause(term.clone())?; @@ -1254,8 +1212,7 @@ impl Machine { self.restore_load_state_payload(result, evacuable_h); } - pub(crate) - fn conclude_load(&mut self) { + pub(crate) fn conclude_load(&mut self) { let (mut loader, evacuable_h) = self.loader_from_heap_evacuable(temp_v!(1)); let compile_final_terms = || { @@ -1271,25 +1228,25 @@ impl Machine { self.restore_load_state_payload(result, evacuable_h); } - pub(crate) - fn load_context_source(&mut self) { + pub(crate) fn load_context_source(&mut self) { if let Some(load_context) = self.load_contexts.last() { let path_str = load_context.path.to_str().unwrap(); - let path_atom = - clause_name!(path_str.to_string(), self.machine_st.atom_tbl); + let path_atom = clause_name!(path_str.to_string(), self.machine_st.atom_tbl); let path_addr = Addr::Con( - self.machine_st.heap.push(HeapCellValue::Atom(path_atom, None)) + self.machine_st + .heap + .push(HeapCellValue::Atom(path_atom, None)), ); - self.machine_st.unify(path_addr, self.machine_st[temp_v!(1)]); + self.machine_st + .unify(path_addr, self.machine_st[temp_v!(1)]); } else { self.machine_st.fail = true; } } - pub(crate) - fn load_context_file(&mut self) { + pub(crate) fn load_context_file(&mut self) { if let Some(load_context) = self.load_contexts.last() { if let Some(file_name) = load_context.path.file_name() { let file_name_str = file_name.to_str().unwrap(); @@ -1297,10 +1254,13 @@ impl Machine { clause_name!(file_name_str.to_string(), self.machine_st.atom_tbl); let file_name_addr = Addr::Con( - self.machine_st.heap.push(HeapCellValue::Atom(file_name_atom, None)) + self.machine_st + .heap + .push(HeapCellValue::Atom(file_name_atom, None)), ); - self.machine_st.unify(file_name_addr, self.machine_st[temp_v!(1)]); + self.machine_st + .unify(file_name_addr, self.machine_st[temp_v!(1)]); return; } } @@ -1308,8 +1268,7 @@ impl Machine { self.machine_st.fail = true; } - pub(crate) - fn load_context_directory(&mut self) { + pub(crate) fn load_context_directory(&mut self) { if let Some(load_context) = self.load_contexts.last() { if let Some(directory) = load_context.path.ancestors().next() { let directory_str = directory.to_str().unwrap(); @@ -1317,10 +1276,13 @@ impl Machine { clause_name!(directory_str.to_string(), self.machine_st.atom_tbl); let directory_addr = Addr::Con( - self.machine_st.heap.push(HeapCellValue::Atom(directory_atom, None)) + self.machine_st + .heap + .push(HeapCellValue::Atom(directory_atom, None)), ); - self.machine_st.unify(directory_addr, self.machine_st[temp_v!(1)]); + self.machine_st + .unify(directory_addr, self.machine_st[temp_v!(1)]); return; } } @@ -1328,56 +1290,51 @@ impl Machine { self.machine_st.fail = true; } - pub(crate) - fn load_context_module(&mut self) { + pub(crate) fn load_context_module(&mut self) { if let Some(load_context) = self.load_contexts.last() { let module_name_addr = Addr::Con( - self.machine_st.heap.push(HeapCellValue::Atom( - load_context.module.clone(), - None, - )) + self.machine_st + .heap + .push(HeapCellValue::Atom(load_context.module.clone(), None)), ); - self.machine_st.unify(module_name_addr, self.machine_st[temp_v!(1)]); + self.machine_st + .unify(module_name_addr, self.machine_st[temp_v!(1)]); } else { self.machine_st.fail = true; } } - pub(crate) - fn load_context_stream(&mut self) { + pub(crate) fn load_context_stream(&mut self) { if let Some(load_context) = self.load_contexts.last() { let stream_addr = Addr::Stream( - self.machine_st.heap.push(HeapCellValue::Stream( - load_context.stream.clone() - )) + self.machine_st + .heap + .push(HeapCellValue::Stream(load_context.stream.clone())), ); - self.machine_st.unify(stream_addr, self.machine_st[temp_v!(1)]); + self.machine_st + .unify(stream_addr, self.machine_st[temp_v!(1)]); } else { self.machine_st.fail = true; } } - pub(crate) - fn compile_assert(&mut self, append_or_prepend: AppendOrPrepend) { - let key = self.machine_st.read_predicate_key( - self.machine_st[temp_v!(3)], - self.machine_st[temp_v!(4)], - ); + pub(crate) fn compile_assert(&mut self, append_or_prepend: AppendOrPrepend) { + let key = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(3)], self.machine_st[temp_v!(4)]); let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(5)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(5)])) ); - let compilation_target = - match module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(module_name), - }; + let compilation_target = match module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(module_name), + }; let compile_assert = || { let mut loader = Loader::new(LiveTermStream::new(ListingSource::User), self); @@ -1385,13 +1342,12 @@ impl Machine { let head = loader.read_term_from_heap(temp_v!(1))?; let body = loader.read_term_from_heap(temp_v!(2))?; - let asserted_clause = - Term::Clause( - Cell::default(), - clause_name!(":-"), - vec![Box::new(head.clone()), Box::new(body.clone())], - fetch_op_spec(clause_name!(":-"), 2, &loader.load_state.wam.indices.op_dir), - ); + let asserted_clause = Term::Clause( + Cell::default(), + clause_name!(":-"), + vec![Box::new(head.clone()), Box::new(body.clone())], + fetch_op_spec(clause_name!(":-"), 2, &loader.load_state.wam.indices.op_dir), + ); loader.incremental_compile_clause( key.clone(), @@ -1402,10 +1358,12 @@ impl Machine { )?; // if a new predicate was just created, make it dynamic. - loader.load_state.wam.indices.get_predicate_skeleton( - &compilation_target, - &key, - ).map(|skeleton| skeleton.is_dynamic = true); + loader + .load_state + .wam + .indices + .get_predicate_skeleton(&compilation_target, &key) + .map(|skeleton| skeleton.is_dynamic = true); loader.compile_clause_clauses( key, @@ -1418,48 +1376,43 @@ impl Machine { }; match compile_assert() { - Ok(_) => { - } + Ok(_) => {} Err(e) => { - let error_pi = - match append_or_prepend { - AppendOrPrepend::Append => (clause_name!("assertz"), 1), - AppendOrPrepend::Prepend => (clause_name!("asserta"), 1), - }; + let error_pi = match append_or_prepend { + AppendOrPrepend::Append => (clause_name!("assertz"), 1), + AppendOrPrepend::Prepend => (clause_name!("asserta"), 1), + }; self.throw_session_error(e, error_pi); } } } - pub(crate) - fn abolish_clause(&mut self) { + pub(crate) fn abolish_clause(&mut self) { let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); - let key = - self.machine_st.read_predicate_key( - self.machine_st[temp_v!(2)], - self.machine_st[temp_v!(3)], - ); + let key = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(2)], self.machine_st[temp_v!(3)]); - let compilation_target = - match module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(module_name), - }; + let compilation_target = match module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(module_name), + }; let mut loader = Loader::new(LiveTermStream::new(ListingSource::User), self); loader.load_state.compilation_target = compilation_target; - match loader.load_state.wam.indices.get_predicate_skeleton( - &loader.load_state.compilation_target, - &key - ) { + match loader + .load_state + .wam + .indices + .get_predicate_skeleton(&loader.load_state.compilation_target, &key) + { Some(skeleton) => { skeleton.clauses.clear(); skeleton.clause_clause_locs.clear(); @@ -1477,8 +1430,7 @@ impl Machine { loader.load_state.compilation_target = CompilationTarget::Module(clause_name!("builtins")); } - _ => { - } + _ => {} }; match loader.load_state.wam.indices.get_predicate_skeleton( @@ -1494,56 +1446,43 @@ impl Machine { } } - let clause_clause_code_index = loader.load_state.get_or_insert_code_index( - (clause_name!("$clause"), 2), - ); + let clause_clause_code_index = loader + .load_state + .get_or_insert_code_index((clause_name!("$clause"), 2)); clause_clause_code_index.set(IndexPtr::DynamicUndefined); } - pub(crate) - fn retract_clause(&mut self) { - let key = - self.machine_st.read_predicate_key( - self.machine_st[temp_v!(1)], - self.machine_st[temp_v!(2)], - ); + pub(crate) fn retract_clause(&mut self) { + let key = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(1)], self.machine_st[temp_v!(2)]); - let target_pos = - self.machine_st.store(self.machine_st.deref(self.machine_st[temp_v!(3)])); + let target_pos = self + .machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(3)])); - let target_pos = - match Number::try_from((target_pos, &self.machine_st.heap)) { - Ok(Number::Integer(n)) => - n.to_usize().unwrap(), - Ok(Number::Fixnum(n)) => - usize::try_from(n).unwrap(), - _ => - unreachable!() - }; + let target_pos = match Number::try_from((target_pos, &self.machine_st.heap)) { + Ok(Number::Integer(n)) => n.to_usize().unwrap(), + Ok(Number::Fixnum(n)) => usize::try_from(n).unwrap(), + _ => unreachable!(), + }; let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(4)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(4)])) ); - let compilation_target = - match module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(module_name), - }; + let compilation_target = match module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(module_name), + }; - let clause_clause_compilation_target = - match &compilation_target { - CompilationTarget::User => { - CompilationTarget::Module(clause_name!("builtins")) - } - _ => { - compilation_target.clone() - } - }; + let clause_clause_compilation_target = match &compilation_target { + CompilationTarget::User => CompilationTarget::Module(clause_name!("builtins")), + _ => compilation_target.clone(), + }; let retract_clause = || { let mut loader = Loader::new(LiveTermStream::new(ListingSource::User), self); @@ -1551,99 +1490,107 @@ impl Machine { let clause_clause_loc = loader.load_state.retract_clause(key, target_pos); - let clause_assert_margin = - loader.load_state.wam.indices.modules - .get(&clause_clause_compilation_target.module_name()) - .map(|module| module.clause_assert_margin) - .unwrap(); + let clause_assert_margin = loader + .load_state + .wam + .indices + .modules + .get(&clause_clause_compilation_target.module_name()) + .map(|module| module.clause_assert_margin) + .unwrap(); - let target_pos = - match loader.load_state.wam.indices.get_predicate_skeleton( - &clause_clause_compilation_target, - &(clause_name!("$clause"), 2), - ) { - Some(skeleton) => { - let search_result = - skeleton.clause_clause_locs[0 .. clause_assert_margin] - .binary_search_by(|loc| clause_clause_loc.cmp(&loc)); + let target_pos = match loader.load_state.wam.indices.get_predicate_skeleton( + &clause_clause_compilation_target, + &(clause_name!("$clause"), 2), + ) { + Some(skeleton) => { + let search_result = skeleton.clause_clause_locs[0..clause_assert_margin] + .binary_search_by(|loc| clause_clause_loc.cmp(&loc)); - let result = - search_result.unwrap_or_else(|_| { - skeleton.clause_clause_locs[clause_assert_margin ..] - .binary_search_by(|loc| loc.cmp(&clause_clause_loc)) - .unwrap() + clause_assert_margin - }); + let result = search_result.unwrap_or_else(|_| { + skeleton.clause_clause_locs[clause_assert_margin..] + .binary_search_by(|loc| loc.cmp(&clause_clause_loc)) + .unwrap() + + clause_assert_margin + }); - if result < clause_assert_margin { - loader.load_state.wam.indices.modules - .get_mut(&clause_clause_compilation_target.module_name()) - .map(|module| module.clause_assert_margin -= 1); - } - - result + if result < clause_assert_margin { + loader + .load_state + .wam + .indices + .modules + .get_mut(&clause_clause_compilation_target.module_name()) + .map(|module| module.clause_assert_margin -= 1); } - None => { - unreachable!(); - } - }; + + result + } + None => { + unreachable!(); + } + }; loader.load_state.compilation_target = clause_clause_compilation_target; - loader.load_state.retract_clause((clause_name!("$clause"), 2), target_pos); + loader + .load_state + .retract_clause((clause_name!("$clause"), 2), target_pos); LiveTermStream::evacuate(loader) }; match retract_clause() { - Ok(_) => { - } + Ok(_) => {} Err(e) => { self.throw_session_error(e, (clause_name!("retract"), 1)); } } } - pub(crate) - fn meta_predicate_property(&mut self) { + pub(crate) fn meta_predicate_property(&mut self) { let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); - let (predicate_name, arity) = - self.machine_st.read_predicate_key( - self.machine_st[temp_v!(2)], - self.machine_st[temp_v!(3)], - ); + let (predicate_name, arity) = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(2)], self.machine_st[temp_v!(3)]); - let compilation_target = - match module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(module_name), - }; + let compilation_target = match module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(module_name), + }; - match self.indices.get_meta_predicate_spec(predicate_name, arity, &compilation_target) { + match self + .indices + .get_meta_predicate_spec(predicate_name, arity, &compilation_target) + { Some(meta_specs) => { - let list_loc = self.machine_st.heap.to_list( - meta_specs.iter().map(|meta_spec| { - match meta_spec { - MetaSpec::Minus => HeapCellValue::Atom(clause_name!("+"), None), - MetaSpec::Plus => HeapCellValue::Atom(clause_name!("-"), None), - MetaSpec::Either => HeapCellValue::Atom(clause_name!("?"), None), - MetaSpec::RequiresExpansionWithArgument(ref arg_num) => { - HeapCellValue::Addr(Addr::Usize(*arg_num)) - } + let list_loc = self + .machine_st + .heap + .to_list(meta_specs.iter().map(|meta_spec| match meta_spec { + MetaSpec::Minus => HeapCellValue::Atom(clause_name!("+"), None), + MetaSpec::Plus => HeapCellValue::Atom(clause_name!("-"), None), + MetaSpec::Either => HeapCellValue::Atom(clause_name!("?"), None), + MetaSpec::RequiresExpansionWithArgument(ref arg_num) => { + HeapCellValue::Addr(Addr::Usize(*arg_num)) } - }), - ); + })); - let heap_loc = self.machine_st.heap.push( - HeapCellValue::NamedStr(1, clause_name!("meta_predicate"), None), - ); + let heap_loc = self.machine_st.heap.push(HeapCellValue::NamedStr( + 1, + clause_name!("meta_predicate"), + None, + )); - self.machine_st.heap.push(HeapCellValue::Addr(Addr::HeapCell(list_loc))); - self.machine_st.unify(Addr::HeapCell(heap_loc), self.machine_st[temp_v!(4)]); + self.machine_st + .heap + .push(HeapCellValue::Addr(Addr::HeapCell(list_loc))); + self.machine_st + .unify(Addr::HeapCell(heap_loc), self.machine_st[temp_v!(4)]); } None => { self.machine_st.fail = true; @@ -1651,31 +1598,26 @@ impl Machine { } } - pub(crate) - fn dynamic_property(&mut self) { + pub(crate) fn dynamic_property(&mut self) { let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); - let key = - self.machine_st.read_predicate_key( - self.machine_st[temp_v!(2)], - self.machine_st[temp_v!(3)], - ); + let key = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(2)], self.machine_st[temp_v!(3)]); - let compilation_target = - match module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(module_name), - }; + let compilation_target = match module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(module_name), + }; - match self.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { self.machine_st.fail = !skeleton.is_dynamic; } @@ -1685,31 +1627,26 @@ impl Machine { } } - pub(crate) - fn multifile_property(&mut self) { + pub(crate) fn multifile_property(&mut self) { let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); - let key = - self.machine_st.read_predicate_key( - self.machine_st[temp_v!(2)], - self.machine_st[temp_v!(3)], - ); + let key = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(2)], self.machine_st[temp_v!(3)]); - let compilation_target = - match module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(module_name), - }; + let compilation_target = match module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(module_name), + }; - match self.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { self.machine_st.fail = !skeleton.is_multifile; } @@ -1719,31 +1656,26 @@ impl Machine { } } - pub(crate) - fn discontiguous_property(&mut self) { + pub(crate) fn discontiguous_property(&mut self) { let module_name = atom_from!( self.machine_st, - self.machine_st.store(self.machine_st.deref( - self.machine_st[temp_v!(1)] - )) + self.machine_st + .store(self.machine_st.deref(self.machine_st[temp_v!(1)])) ); - let key = - self.machine_st.read_predicate_key( - self.machine_st[temp_v!(2)], - self.machine_st[temp_v!(3)], - ); + let key = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(2)], self.machine_st[temp_v!(3)]); - let compilation_target = - match module_name.as_str() { - "user" => CompilationTarget::User, - _ => CompilationTarget::Module(module_name), - }; + let compilation_target = match module_name.as_str() { + "user" => CompilationTarget::User, + _ => CompilationTarget::Module(module_name), + }; - match self.indices.get_predicate_skeleton( - &compilation_target, - &key, - ) { + match self + .indices + .get_predicate_skeleton(&compilation_target, &key) + { Some(skeleton) => { self.machine_st.fail = !skeleton.is_discontiguous; } @@ -1753,13 +1685,10 @@ impl Machine { } } - pub(crate) - fn builtin_property(&mut self) { - let key = - self.machine_st.read_predicate_key( - self.machine_st[temp_v!(1)], - self.machine_st[temp_v!(2)], - ); + pub(crate) fn builtin_property(&mut self) { + let key = self + .machine_st + .read_predicate_key(self.machine_st[temp_v!(1)], self.machine_st[temp_v!(2)]); match ClauseType::from(key.0, key.1, None) { ClauseType::BuiltIn(_) | ClauseType::Inlined(..) | ClauseType::CallN => { @@ -1767,24 +1696,21 @@ impl Machine { } ClauseType::Named(ref name, arity, _) => { if let Some(module) = self.indices.modules.get(&(clause_name!("builtins"))) { - self.machine_st.fail = !module.code_dir.contains_key( - &(name.clone(), arity), - ); + self.machine_st.fail = !module.code_dir.contains_key(&(name.clone(), arity)); return; } } ClauseType::Op(ref name, ref op_desc, _) => { if let Some(module) = self.indices.modules.get(&(clause_name!("builtins"))) { - self.machine_st.fail = !module.code_dir.contains_key( - &(name.clone(), op_desc.arity()), - ); + self.machine_st.fail = !module + .code_dir + .contains_key(&(name.clone(), op_desc.arity())); return; } } - _ => { - } + _ => {} } self.machine_st.fail = true; @@ -1792,89 +1718,48 @@ impl Machine { } impl<'a> Loader<'a, LiveTermStream> { - pub(super) - fn to_load_state_payload(mut self) -> LoadStatePayload { + pub(super) fn to_load_state_payload(mut self) -> LoadStatePayload { LoadStatePayload { - term_stream: - mem::replace( - &mut self.term_stream, - LiveTermStream::new(ListingSource::User), - ), - preprocessor: - mem::replace( - &mut self.preprocessor, - Preprocessor::new(self.load_state.wam.machine_st.flags), - ), - non_counted_bt_preds: - mem::replace( - &mut self.non_counted_bt_preds, - IndexSet::new(), - ), - compilation_target: - self.load_state.compilation_target.take(), - retraction_info: - mem::replace( - &mut self.load_state.retraction_info, - RetractionInfo::new(self.load_state.wam.code_repo.code.len()), - ), - predicates: - mem::replace( - &mut self.predicates, - vec![], - ), - clause_clauses: - mem::replace( - &mut self.clause_clauses, - vec![], - ), - module_op_exports: - mem::replace( - &mut self.load_state.module_op_exports, - vec![], - ), + term_stream: mem::replace( + &mut self.term_stream, + LiveTermStream::new(ListingSource::User), + ), + preprocessor: mem::replace( + &mut self.preprocessor, + Preprocessor::new(self.load_state.wam.machine_st.flags), + ), + non_counted_bt_preds: mem::replace(&mut self.non_counted_bt_preds, IndexSet::new()), + compilation_target: self.load_state.compilation_target.take(), + retraction_info: mem::replace( + &mut self.load_state.retraction_info, + RetractionInfo::new(self.load_state.wam.code_repo.code.len()), + ), + predicates: mem::replace(&mut self.predicates, vec![]), + clause_clauses: mem::replace(&mut self.clause_clauses, vec![]), + module_op_exports: mem::replace(&mut self.load_state.module_op_exports, vec![]), } } - pub(super) - fn from_load_state_payload(wam: &'a mut Machine, mut payload: LoadStatePayload) -> Self { + pub(super) fn from_load_state_payload( + wam: &'a mut Machine, + mut payload: LoadStatePayload, + ) -> Self { Loader { - term_stream: - mem::replace( - &mut payload.term_stream, - LiveTermStream::new(ListingSource::User), - ), - preprocessor: - mem::replace( - &mut payload.preprocessor, - Preprocessor::new(MachineFlags::default()), - ), - non_counted_bt_preds: - mem::replace( - &mut payload.non_counted_bt_preds, - IndexSet::new(), - ), - clause_clauses: - mem::replace( - &mut payload.clause_clauses, - vec![], - ), - predicates: - mem::replace( - &mut payload.predicates, - vec![], - ), + term_stream: mem::replace( + &mut payload.term_stream, + LiveTermStream::new(ListingSource::User), + ), + preprocessor: mem::replace( + &mut payload.preprocessor, + Preprocessor::new(MachineFlags::default()), + ), + non_counted_bt_preds: mem::replace(&mut payload.non_counted_bt_preds, IndexSet::new()), + clause_clauses: mem::replace(&mut payload.clause_clauses, vec![]), + predicates: mem::replace(&mut payload.predicates, vec![]), load_state: LoadState { compilation_target: payload.compilation_target.take(), - module_op_exports: - mem::replace( - &mut payload.module_op_exports, - vec![], - ), - retraction_info: - mem::replace( - &mut payload.retraction_info, - RetractionInfo::new(0), - ), + module_op_exports: mem::replace(&mut payload.module_op_exports, vec![]), + retraction_info: mem::replace(&mut payload.retraction_info, RetractionInfo::new(0)), wam, }, } @@ -1890,26 +1775,17 @@ impl<'a> Loader<'a, LiveTermStream> { ) -> Result<(), SessionError> { let mut preprocessor = Preprocessor::new(self.load_state.wam.machine_st.flags); - let tl = preprocessor.try_term_to_tl( - &mut self.load_state, - term, - CutContext::BlocksCuts, - )?; + let tl = preprocessor.try_term_to_tl(&mut self.load_state, term, CutContext::BlocksCuts)?; let queue = preprocessor.parse_queue(&mut self.load_state)?; - let clause = - match tl { - TopLevel::Fact(fact) => { - PredicateClause::Fact(fact) - } - TopLevel::Rule(rule) => { - PredicateClause::Rule(rule) - } - _ => { - unreachable!() - } - }; + let clause = match tl { + TopLevel::Fact(fact) => PredicateClause::Fact(fact), + TopLevel::Rule(rule) => PredicateClause::Rule(rule), + _ => { + unreachable!() + } + }; let compilation_target = mem::replace(&mut self.load_state.compilation_target, compilation_target); @@ -1935,8 +1811,7 @@ impl<'a> Loader<'a, LiveTermStream> { } #[inline] -pub(super) -fn load_module( +pub(super) fn load_module( code_dir: &mut CodeDir, op_dir: &mut OpDir, meta_predicate_dir: &mut MetaPredicateDir, diff --git a/src/machine/machine_errors.rs b/src/machine/machine_errors.rs index ffb95aef..1ca1861d 100644 --- a/src/machine/machine_errors.rs +++ b/src/machine/machine_errors.rs @@ -1,4 +1,5 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::{clause_name, temp_v}; use crate::forms::{ModuleSource, Number}; //, PredicateKey}; use crate::machine::heap::*; @@ -23,74 +24,59 @@ pub(crate) struct MachineError { from: ErrorProvenance, } -pub(crate) -trait TypeError { +pub(crate) trait TypeError { fn type_error(self, h: usize, valid_type: ValidType) -> MachineError; } impl TypeError for Addr { fn type_error(self, _: usize, valid_type: ValidType) -> MachineError { - let stub = functor!( - "type_error", - [atom(valid_type.as_str()), addr(self)] - ); + let stub = functor!("type_error", [atom(valid_type.as_str()), addr(self)]); MachineError { stub, location: None, - from: ErrorProvenance::Received + from: ErrorProvenance::Received, } } } impl TypeError for HeapCellValue { fn type_error(self, _: usize, valid_type: ValidType) -> MachineError { - let stub = functor!( - "type_error", - [atom(valid_type.as_str()), value(self)] - ); + let stub = functor!("type_error", [atom(valid_type.as_str()), value(self)]); MachineError { stub, location: None, - from: ErrorProvenance::Received + from: ErrorProvenance::Received, } } } impl TypeError for MachineStub { fn type_error(self, h: usize, valid_type: ValidType) -> MachineError { - let stub = functor!( - "type_error", - [atom(valid_type.as_str()), aux(h, 0)], - [self] - ); + let stub = functor!("type_error", [atom(valid_type.as_str()), aux(h, 0)], [self]); MachineError { stub, location: None, - from: ErrorProvenance::Constructed + from: ErrorProvenance::Constructed, } } } impl TypeError for Number { fn type_error(self, _h: usize, valid_type: ValidType) -> MachineError { - let stub = functor!( - "type_error", - [atom(valid_type.as_str()), number(self)] - ); + let stub = functor!("type_error", [atom(valid_type.as_str()), number(self)]); MachineError { stub, location: None, - from: ErrorProvenance::Received + from: ErrorProvenance::Received, } } } -pub(crate) -trait PermissionError { +pub(crate) trait PermissionError { fn permission_error(self, h: usize, index_str: &'static str, perm: Permission) -> MachineError; } @@ -104,7 +90,7 @@ impl PermissionError for Addr { MachineError { stub, location: None, - from: ErrorProvenance::Received + from: ErrorProvenance::Received, } } } @@ -120,22 +106,18 @@ impl PermissionError for MachineStub { MachineError { stub, location: None, - from: ErrorProvenance::Constructed + from: ErrorProvenance::Constructed, } } } -pub(super) -trait DomainError { +pub(super) trait DomainError { fn domain_error(self, error: DomainErrorType) -> MachineError; } impl DomainError for Addr { fn domain_error(self, error: DomainErrorType) -> MachineError { - let stub = functor!( - "domain_error", - [atom(error.as_str()), addr(self)] - ); + let stub = functor!("domain_error", [atom(error.as_str()), addr(self)]); MachineError { stub, @@ -147,10 +129,7 @@ impl DomainError for Addr { impl DomainError for Number { fn domain_error(self, error: DomainErrorType) -> MachineError { - let stub = functor!( - "domain_error", - [atom(error.as_str()), number(self)] - ); + let stub = functor!("domain_error", [atom(error.as_str()), number(self)]); MachineError { stub, @@ -161,8 +140,7 @@ impl DomainError for Number { } impl MachineError { - pub(super) - fn functor_stub(name: ClauseName, arity: usize) -> MachineStub { + pub(super) fn functor_stub(name: ClauseName, arity: usize) -> MachineStub { functor!( "/", SharedOpDesc::new(400, YFX), @@ -171,8 +149,7 @@ impl MachineError { } #[inline] - pub(super) - fn interrupt_error() -> Self { + pub(super) fn interrupt_error() -> Self { let stub = functor!("$interrupt_thrown"); MachineError { @@ -182,8 +159,7 @@ impl MachineError { } } - pub(super) - fn evaluation_error(eval_error: EvalError) -> Self { + pub(super) fn evaluation_error(eval_error: EvalError) -> Self { let stub = functor!("evaluation_error", [atom(eval_error.as_str())]); MachineError { @@ -193,13 +169,11 @@ impl MachineError { } } - pub(super) - fn type_error(h: usize, valid_type: ValidType, culprit: T) -> Self { + pub(super) fn type_error(h: usize, valid_type: ValidType, culprit: T) -> Self { culprit.type_error(h, valid_type) } - pub(super) - fn module_resolution_error( + pub(super) fn module_resolution_error( h: usize, mod_name: ClauseName, name: ClauseName, @@ -218,11 +192,7 @@ impl MachineError { [res_stub] ); - let stub = functor!( - "evaluation_error", - [aux(h, 0)], - [ind_stub] - ); + let stub = functor!("evaluation_error", [aux(h, 0)], [ind_stub]); MachineError { stub, @@ -231,14 +201,10 @@ impl MachineError { } } - pub(super) - fn existence_error(h: usize, err: ExistenceError) -> Self { + pub(super) fn existence_error(h: usize, err: ExistenceError) -> Self { match err { ExistenceError::Module(name) => { - let stub = functor!( - "existence_error", - [atom("source_sink"), clause_name(name)] - ); + let stub = functor!("existence_error", [atom("source_sink"), clause_name(name)]); MachineError { stub, @@ -253,11 +219,7 @@ impl MachineError { [clause_name(name), integer(arity)] ); - let stub = functor!( - "existence_error", - [atom("procedure"), aux(h, 0)], - [culprit] - ); + let stub = functor!("existence_error", [atom("procedure"), aux(h, 0)], [culprit]); MachineError { stub, @@ -281,10 +243,7 @@ impl MachineError { } } ExistenceError::SourceSink(culprit) => { - let stub = functor!( - "existence_error", - [atom("source_sink"), addr(culprit)] - ); + let stub = functor!("existence_error", [atom("source_sink"), addr(culprit)]); MachineError { stub, @@ -293,10 +252,7 @@ impl MachineError { } } ExistenceError::Stream(culprit) => { - let stub = functor!( - "existence_error", - [atom("stream"), addr(culprit)] - ); + let stub = functor!("existence_error", [atom("stream"), addr(culprit)]); MachineError { stub, @@ -307,25 +263,18 @@ impl MachineError { } } - pub(super) - fn permission_error( + pub(super) fn permission_error( h: usize, err: Permission, index_str: &'static str, culprit: T, ) -> Self { - culprit.permission_error( - h, - index_str, - err, - ) + culprit.permission_error(h, index_str, err) } fn arithmetic_error(h: usize, err: ArithmeticError) -> Self { match err { - ArithmeticError::UninstantiatedVar => { - Self::instantiation_error() - } + ArithmeticError::UninstantiatedVar => Self::instantiation_error(), ArithmeticError::NonEvaluableFunctor(name, arity) => { let culprit = functor!( "/", @@ -339,13 +288,11 @@ impl MachineError { } #[inline] - pub(super) - fn domain_error(error: DomainErrorType, culprit: T) -> Self { + pub(super) fn domain_error(error: DomainErrorType, culprit: T) -> Self { culprit.domain_error(error) } - pub(super) - fn instantiation_error() -> Self { + pub(super) fn instantiation_error() -> Self { let stub = functor!("instantiation_error"); MachineError { @@ -355,8 +302,7 @@ impl MachineError { } } - pub(super) - fn session_error(h: usize, err: SessionError) -> Self { + pub(super) fn session_error(h: usize, err: SessionError) -> Self { match err { // SessionError::CannotOverwriteBuiltIn(pred_str) | /* @@ -369,9 +315,7 @@ impl MachineError { ) } */ - SessionError::ExistenceError(err) => { - Self::existence_error(h, err) - } + SessionError::ExistenceError(err) => Self::existence_error(h, err), // SessionError::InvalidFileName(filename) => { // Self::existence_error(h, ExistenceError::Module(filename)) // } @@ -385,46 +329,32 @@ impl MachineError { ) } */ - SessionError::ModuleCannotImportSelf(module_name) => { - Self::permission_error( - h, - Permission::Modify, - "module", - functor!("module_cannot_import_self", [clause_name(module_name)]), - ) - } - SessionError::NamelessEntry => { - Self::permission_error( - h, - Permission::Create, - "static_procedure", - functor!("nameless_procedure") - ) - } + SessionError::ModuleCannotImportSelf(module_name) => Self::permission_error( + h, + Permission::Modify, + "module", + functor!("module_cannot_import_self", [clause_name(module_name)]), + ), + SessionError::NamelessEntry => Self::permission_error( + h, + Permission::Create, + "static_procedure", + functor!("nameless_procedure"), + ), SessionError::OpIsInfixAndPostFix(op) => { - Self::permission_error( - h, - Permission::Create, - "operator", - functor!(clause_name(op)), - ) - } - SessionError::CompilationError(err) => { - Self::syntax_error(h, err) - } - SessionError::QueryCannotBeDefinedAsFact => { - Self::permission_error( - h, - Permission::Create, - "static_procedure", - functor!("query_cannot_be_defined_as_fact") - ) + Self::permission_error(h, Permission::Create, "operator", functor!(clause_name(op))) } + SessionError::CompilationError(err) => Self::syntax_error(h, err), + SessionError::QueryCannotBeDefinedAsFact => Self::permission_error( + h, + Permission::Create, + "static_procedure", + functor!("query_cannot_be_defined_as_fact"), + ), } } - pub(super) - fn syntax_error>(h: usize, err: E) -> Self { + pub(super) fn syntax_error>(h: usize, err: E) -> Self { let err = err.into(); if let CompilationError::Arithmetic(err) = err { @@ -434,11 +364,7 @@ impl MachineError { let location = err.line_and_col_num(); let stub = err.as_functor(h); - let stub = functor!( - "syntax_error", - [aux(h, 0)], - [stub] - ); + let stub = functor!("syntax_error", [aux(h, 0)], [stub]); MachineError { stub, @@ -447,8 +373,7 @@ impl MachineError { } } - pub(super) - fn representation_error(flag: RepFlag) -> Self { + pub(super) fn representation_error(flag: RepFlag) -> Self { let stub = functor!("representation_error", [atom(flag.as_str())]); MachineError { @@ -515,56 +440,39 @@ impl From for CompilationError { impl CompilationError { pub fn line_and_col_num(&self) -> Option<(usize, usize)> { match self { - &CompilationError::ParserError(ref err) => - err.line_and_col_num(), - _ => - None + &CompilationError::ParserError(ref err) => err.line_and_col_num(), + _ => None, } } pub fn as_functor(&self, _h: usize) -> MachineStub { match self { - &CompilationError::Arithmetic(..) => - functor!("arithmetic_error"), + &CompilationError::Arithmetic(..) => functor!("arithmetic_error"), // &CompilationError::BadPendingByte => // functor!("bad_pending_byte"), - &CompilationError::CannotParseCyclicTerm => - functor!("cannot_parse_cyclic_term"), + &CompilationError::CannotParseCyclicTerm => functor!("cannot_parse_cyclic_term"), // &CompilationError::ExpandedTermsListNotAList => // functor!("expanded_terms_list_is_not_a_list"), - &CompilationError::ExpectedRel => - functor!("expected_relation"), + &CompilationError::ExpectedRel => functor!("expected_relation"), // &CompilationError::ExpectedTopLevelTerm => // functor!("expected_atom_or_cons_or_clause"), - &CompilationError::InadmissibleFact => - functor!("inadmissible_fact"), - &CompilationError::InadmissibleQueryTerm => - functor!("inadmissible_query_term"), - &CompilationError::InconsistentEntry => - functor!("inconsistent_entry"), + &CompilationError::InadmissibleFact => functor!("inadmissible_fact"), + &CompilationError::InadmissibleQueryTerm => functor!("inadmissible_query_term"), + &CompilationError::InconsistentEntry => functor!("inconsistent_entry"), // &CompilationError::InvalidDoubleQuotesDecl => // functor!("invalid_double_quotes_declaration"), // &CompilationError::InvalidHook => // functor!("invalid_hook"), - &CompilationError::InvalidMetaPredicateDecl => - functor!("invalid_meta_predicate_decl"), - &CompilationError::InvalidModuleDecl => - functor!("invalid_module_declaration"), - &CompilationError::InvalidModuleExport => - functor!("invalid_module_export"), - &CompilationError::InvalidModuleResolution(ref module_name) => - functor!( - "no_such_module", - [clause_name(module_name.clone())] - ), - &CompilationError::InvalidRuleHead => - functor!("invalid_head_of_rule"), - &CompilationError::InvalidUseModuleDecl => - functor!("invalid_use_module_declaration"), - &CompilationError::ParserError(ref err) => - functor!(err.as_str()), - &CompilationError::UnreadableTerm => - functor!("unreadable_term"), + &CompilationError::InvalidMetaPredicateDecl => functor!("invalid_meta_predicate_decl"), + &CompilationError::InvalidModuleDecl => functor!("invalid_module_declaration"), + &CompilationError::InvalidModuleExport => functor!("invalid_module_export"), + &CompilationError::InvalidModuleResolution(ref module_name) => { + functor!("no_such_module", [clause_name(module_name.clone())]) + } + &CompilationError::InvalidRuleHead => functor!("invalid_head_of_rule"), + &CompilationError::InvalidUseModuleDecl => functor!("invalid_use_module_declaration"), + &CompilationError::ParserError(ref err) => functor!(err.as_str()), + &CompilationError::UnreadableTerm => functor!("unreadable_term"), } } } @@ -715,16 +623,15 @@ impl EvalError { pub(super) enum CycleSearchResult { EmptyList, NotList, - PartialList(usize, Ref), // the list length (up to max), and an offset into the heap. - ProperList(usize), // the list length. + PartialList(usize, Ref), // the list length (up to max), and an offset into the heap. + ProperList(usize), // the list length. PStrLocation(usize, usize, usize), // the list length (up to max), the heap offset, byte offset into the string. UntouchedList(usize), // the address of an uniterated Addr::Lis(address). } impl MachineState { // see 8.4.3 of Draft Technical Corrigendum 2. - pub(super) - fn check_sort_errors(&self) -> CallResult { + pub(super) fn check_sort_errors(&self) -> CallResult { let stub = MachineError::functor_stub(clause_name!("sort"), 2); let list = self.store(self.deref(self[temp_v!(1)].clone())); let sorted = self.store(self.deref(self[temp_v!(2)].clone())); @@ -734,7 +641,9 @@ impl MachineState { return Err(self.error_form(MachineError::instantiation_error(), stub)) } CycleSearchResult::NotList => { - return Err(self.error_form(MachineError::type_error(0, ValidType::List, list), stub)) + return Err( + self.error_form(MachineError::type_error(0, ValidType::List, list), stub) + ) } _ => {} }; @@ -766,7 +675,8 @@ impl MachineState { new_l = l; } HeapCellValue::NamedStr(2, ref name, Some(_)) - if name.as_str() == "-" => { + if name.as_str() == "-" => + { break; } HeapCellValue::Addr(Addr::HeapCell(_)) => { @@ -793,11 +703,10 @@ impl MachineState { } // see 8.4.4 of Draft Technical Corrigendum 2. - pub(super) - fn check_keysort_errors(&self) -> CallResult { + pub(super) fn check_keysort_errors(&self) -> CallResult { let stub = MachineError::functor_stub(clause_name!("keysort"), 2); - let pairs = self.store(self.deref(self[temp_v!(1)].clone())); + let pairs = self.store(self.deref(self[temp_v!(1)].clone())); let sorted = self.store(self.deref(self[temp_v!(2)].clone())); match self.detect_cycles(pairs.clone()) { @@ -814,8 +723,7 @@ impl MachineState { } #[inline] - pub(crate) - fn type_error( + pub(crate) fn type_error( &self, valid_type: ValidType, culprit: T, @@ -823,33 +731,25 @@ impl MachineState { arity: usize, ) -> MachineStub { let stub = MachineError::functor_stub(caller, arity); - let err = MachineError::type_error( - self.heap.h(), - valid_type, - culprit, - ); + let err = MachineError::type_error(self.heap.h(), valid_type, culprit); return self.error_form(err, stub); } #[inline] - pub(crate) - fn representation_error( + pub(crate) fn representation_error( &self, rep_flag: RepFlag, caller: ClauseName, arity: usize, ) -> MachineStub { let stub = MachineError::functor_stub(caller, arity); - let err = MachineError::representation_error( - rep_flag, - ); + let err = MachineError::representation_error(rep_flag); return self.error_form(err, stub); } - pub(super) - fn error_form(&self, err: MachineError, src: MachineStub) -> MachineStub { + pub(super) fn error_form(&self, err: MachineError, src: MachineStub) -> MachineStub { let location = err.location; let err_len = err.len(); @@ -874,8 +774,7 @@ impl MachineState { stub } - pub(super) - fn throw_exception(&mut self, err: MachineStub) { + pub(super) fn throw_exception(&mut self, err: MachineStub) { let h = self.heap.h(); self.ball.boundary = 0; diff --git a/src/machine/machine_indices.rs b/src/machine/machine_indices.rs index b6883e77..b4089147 100644 --- a/src/machine/machine_indices.rs +++ b/src/machine/machine_indices.rs @@ -1,18 +1,19 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::clause_name; use crate::clause_types::*; use crate::fixtures::*; use crate::forms::*; -use crate::machine::CompilationTarget; +use crate::instructions::*; use crate::machine::code_repo::CodeRepo; -use crate::machine::Ball; use crate::machine::heap::*; use crate::machine::machine_state::*; use crate::machine::partial_string::*; use crate::machine::raw_block::RawBlockTraits; use crate::machine::streams::Stream; use crate::machine::term_stream::LoadStatePayload; -use crate::instructions::*; +use crate::machine::Ball; +use crate::machine::CompilationTarget; use crate::ordered_float::OrderedFloat; use crate::rug::{Integer, Rational}; @@ -96,20 +97,14 @@ impl Ord for Ref { fn cmp(&self, other: &Ref) -> Ordering { match (self, other) { (Ref::AttrVar(h1), Ref::AttrVar(h2)) - | (Ref::HeapCell(h1), Ref::HeapCell(h2)) - | (Ref::HeapCell(h1), Ref::AttrVar(h2)) - | (Ref::AttrVar(h1), Ref::HeapCell(h2)) => { - h1.cmp(&h2) - } + | (Ref::HeapCell(h1), Ref::HeapCell(h2)) + | (Ref::HeapCell(h1), Ref::AttrVar(h2)) + | (Ref::AttrVar(h1), Ref::HeapCell(h2)) => h1.cmp(&h2), (Ref::StackCell(fr1, sc1), Ref::StackCell(fr2, sc2)) => { fr1.cmp(&fr2).then_with(|| sc1.cmp(&sc2)) } - (Ref::StackCell(..), _) => { - Ordering::Greater - } - (_, Ref::StackCell(..)) => { - Ordering::Less - } + (Ref::StackCell(..), _) => Ordering::Greater, + (_, Ref::StackCell(..)) => Ordering::Less, } } } @@ -124,35 +119,23 @@ impl PartialEq for Addr { impl PartialOrd for Addr { fn partial_cmp(&self, r: &Ref) -> Option { match self { - &Addr::StackCell(fr, sc) => { - match *r { - Ref::AttrVar(_) | Ref::HeapCell(_) => { + &Addr::StackCell(fr, sc) => match *r { + Ref::AttrVar(_) | Ref::HeapCell(_) => Some(Ordering::Greater), + Ref::StackCell(fr1, sc1) => { + if fr1 < fr || (fr1 == fr && sc1 < sc) { Some(Ordering::Greater) - } - Ref::StackCell(fr1, sc1) => { - if fr1 < fr || (fr1 == fr && sc1 < sc) { - Some(Ordering::Greater) - } else if fr1 == fr && sc1 == sc { - Some(Ordering::Equal) - } else { - Some(Ordering::Less) - } - } - } - } - &Addr::HeapCell(h) | &Addr::AttrVar(h) => { - match r { - Ref::StackCell(..) => { + } else if fr1 == fr && sc1 == sc { + Some(Ordering::Equal) + } else { Some(Ordering::Less) } - Ref::AttrVar(h1) | Ref::HeapCell(h1) => { - h.partial_cmp(h1) - } } - } - _ => { - None - } + }, + &Addr::HeapCell(h) | &Addr::AttrVar(h) => match r { + Ref::StackCell(..) => Some(Ordering::Less), + Ref::AttrVar(h1) | Ref::HeapCell(h1) => h.partial_cmp(h1), + }, + _ => None, } } } @@ -161,26 +144,21 @@ impl Addr { #[inline] pub fn is_heap_bound(&self) -> bool { match self { - Addr::Char(_) | Addr::EmptyList | - Addr::CutPoint(_) | Addr::Usize(_) | Addr::Fixnum(_) | - Addr::Float(_) => { - false - } - _ => { - true - } + Addr::Char(_) + | Addr::EmptyList + | Addr::CutPoint(_) + | Addr::Usize(_) + | Addr::Fixnum(_) + | Addr::Float(_) => false, + _ => true, } } #[inline] pub fn is_ref(&self) -> bool { match self { - Addr::HeapCell(_) | Addr::StackCell(_, _) | Addr::AttrVar(_) => { - true - } - _ => { - false - } + Addr::HeapCell(_) | Addr::StackCell(_, _) | Addr::AttrVar(_) => true, + _ => false, } } @@ -194,92 +172,54 @@ impl Addr { } } - pub(super) - fn order_category(&self, heap: &Heap) -> Option { + pub(super) fn order_category(&self, heap: &Heap) -> Option { match Number::try_from((*self, heap)) { Ok(Number::Integer(_)) | Ok(Number::Fixnum(_)) | Ok(Number::Rational(_)) => { Some(TermOrderCategory::Integer) } - Ok(Number::Float(_)) => { - Some(TermOrderCategory::FloatingPoint) - } - _ => { - match self { - Addr::HeapCell(_) | Addr::AttrVar(_) | Addr::StackCell(..) => { - Some(TermOrderCategory::Variable) - } - Addr::Float(_) => { - Some(TermOrderCategory::FloatingPoint) - } - &Addr::Con(h) => { - match &heap[h] { - HeapCellValue::Atom(..) => { - Some(TermOrderCategory::Atom) - } - HeapCellValue::DBRef(_) => { - None - } - _ => { - unreachable!() - } - } - } - Addr::Char(_) | Addr::EmptyList => { - Some(TermOrderCategory::Atom) - } - Addr::Fixnum(_) | Addr::Usize(_) => { - Some(TermOrderCategory::Integer) - } - Addr::Lis(_) | Addr::PStrLocation(..) | Addr::Str(_) => { - Some(TermOrderCategory::Compound) - } - Addr::CutPoint(_) | Addr::LoadStatePayload(_) | Addr::Stream(_) | Addr::TcpListener(_) => { - None - } + Ok(Number::Float(_)) => Some(TermOrderCategory::FloatingPoint), + _ => match self { + Addr::HeapCell(_) | Addr::AttrVar(_) | Addr::StackCell(..) => { + Some(TermOrderCategory::Variable) } - } + Addr::Float(_) => Some(TermOrderCategory::FloatingPoint), + &Addr::Con(h) => match &heap[h] { + HeapCellValue::Atom(..) => Some(TermOrderCategory::Atom), + HeapCellValue::DBRef(_) => None, + _ => { + unreachable!() + } + }, + Addr::Char(_) | Addr::EmptyList => Some(TermOrderCategory::Atom), + Addr::Fixnum(_) | Addr::Usize(_) => Some(TermOrderCategory::Integer), + Addr::Lis(_) | Addr::PStrLocation(..) | Addr::Str(_) => { + Some(TermOrderCategory::Compound) + } + Addr::CutPoint(_) + | Addr::LoadStatePayload(_) + | Addr::Stream(_) + | Addr::TcpListener(_) => None, + }, } } pub fn as_constant_index(&self, machine_st: &MachineState) -> Option { match self { - &Addr::Char(c) => { - Some(Constant::Char(c)) - } - &Addr::Con(h) => { - match &machine_st.heap[h] { - &HeapCellValue::Atom(ref name, _) if name.is_char() => { - Some(Constant::Char(name.as_str().chars().next().unwrap())) - } - &HeapCellValue::Atom(ref name, _) => { - Some(Constant::Atom(name.clone(), None)) - } - &HeapCellValue::Integer(ref n) => { - Some(Constant::Integer(n.clone())) - } - &HeapCellValue::Rational(ref n) => { - Some(Constant::Rational(n.clone())) - } - _ => { - None - } + &Addr::Char(c) => Some(Constant::Char(c)), + &Addr::Con(h) => match &machine_st.heap[h] { + &HeapCellValue::Atom(ref name, _) if name.is_char() => { + Some(Constant::Char(name.as_str().chars().next().unwrap())) } - } - &Addr::EmptyList => { - Some(Constant::EmptyList) - } - &Addr::Fixnum(n) => { - Some(Constant::Fixnum(n)) - } - &Addr::Float(f) => { - Some(Constant::Float(f)) - } - &Addr::Usize(n) => { - Some(Constant::Usize(n)) - } - _ => { - None - } + &HeapCellValue::Atom(ref name, _) => Some(Constant::Atom(name.clone(), None)), + &HeapCellValue::Integer(ref n) => Some(Constant::Integer(n.clone())), + &HeapCellValue::Rational(ref n) => Some(Constant::Rational(n.clone())), + _ => None, + }, + &Addr::EmptyList => Some(Constant::EmptyList), + &Addr::Fixnum(n) => Some(Constant::Fixnum(n)), + &Addr::Float(f) => Some(Constant::Float(f)), + &Addr::Usize(n) => Some(Constant::Usize(n)), + _ => None, } } @@ -383,61 +323,37 @@ impl HeapCellValue { #[inline] pub fn as_addr(&self, focus: usize) -> Addr { match self { - HeapCellValue::Addr(ref a) => { - *a - } - HeapCellValue::Atom(..) | HeapCellValue::DBRef(..) | HeapCellValue::Integer(..) | - HeapCellValue::Rational(..) => { - Addr::Con(focus) - } - HeapCellValue::LoadStatePayload(_) => { - Addr::LoadStatePayload(focus) - } - HeapCellValue::NamedStr(_, _, _) => { - Addr::Str(focus) - } - HeapCellValue::PartialString(..) => { - Addr::PStrLocation(focus, 0) - } - HeapCellValue::Stream(_) => { - Addr::Stream(focus) - } - HeapCellValue::TcpListener(_) => { - Addr::TcpListener(focus) - } + HeapCellValue::Addr(ref a) => *a, + HeapCellValue::Atom(..) + | HeapCellValue::DBRef(..) + | HeapCellValue::Integer(..) + | HeapCellValue::Rational(..) => Addr::Con(focus), + HeapCellValue::LoadStatePayload(_) => Addr::LoadStatePayload(focus), + HeapCellValue::NamedStr(_, _, _) => Addr::Str(focus), + HeapCellValue::PartialString(..) => Addr::PStrLocation(focus, 0), + HeapCellValue::Stream(_) => Addr::Stream(focus), + HeapCellValue::TcpListener(_) => Addr::TcpListener(focus), } } #[inline] pub fn context_free_clone(&self) -> HeapCellValue { match self { - &HeapCellValue::Addr(addr) => { - HeapCellValue::Addr(addr) - } - &HeapCellValue::Atom(ref name, ref op) => { - HeapCellValue::Atom(name.clone(), op.clone()) - } - &HeapCellValue::DBRef(ref db_ref) => { - HeapCellValue::DBRef(db_ref.clone()) - } - &HeapCellValue::Integer(ref n) => { - HeapCellValue::Integer(n.clone()) - } + &HeapCellValue::Addr(addr) => HeapCellValue::Addr(addr), + &HeapCellValue::Atom(ref name, ref op) => HeapCellValue::Atom(name.clone(), op.clone()), + &HeapCellValue::DBRef(ref db_ref) => HeapCellValue::DBRef(db_ref.clone()), + &HeapCellValue::Integer(ref n) => HeapCellValue::Integer(n.clone()), &HeapCellValue::LoadStatePayload(_) => { HeapCellValue::Atom(clause_name!("$live_term_stream"), None) } &HeapCellValue::NamedStr(arity, ref name, ref op) => { HeapCellValue::NamedStr(arity, name.clone(), op.clone()) } - &HeapCellValue::Rational(ref r) => { - HeapCellValue::Rational(r.clone()) - } + &HeapCellValue::Rational(ref r) => HeapCellValue::Rational(r.clone()), &HeapCellValue::PartialString(ref pstr, has_tail) => { HeapCellValue::PartialString(pstr.clone(), has_tail) } - &HeapCellValue::Stream(ref stream) => { - HeapCellValue::Stream(stream.clone()) - } + &HeapCellValue::Stream(ref stream) => HeapCellValue::Stream(stream.clone()), &HeapCellValue::TcpListener(_) => { HeapCellValue::Atom(clause_name!("$tcp_listener"), None) } @@ -473,8 +389,7 @@ impl Deref for CodeIndex { impl CodeIndex { #[inline] - pub(super) - fn new(ptr: IndexPtr) -> Self { + pub(super) fn new(ptr: IndexPtr) -> Self { CodeIndex(Rc::new(Cell::new(ptr))) } @@ -482,7 +397,7 @@ impl CodeIndex { pub fn is_undefined(&self) -> bool { match self.0.get() { IndexPtr::Undefined => true, // | &IndexPtr::DynamicUndefined => true, - _ => false + _ => false, } } @@ -536,7 +451,7 @@ pub enum CodePtr { CallN(usize, LocalCodePtr, bool), // arity, local, last call. Local(LocalCodePtr), // DynamicTransaction(DynamicTransactionType, LocalCodePtr), // the type of transaction, the return pointer. - REPL(REPLCodePtr, LocalCodePtr), // the REPL code, the return pointer. + REPL(REPLCodePtr, LocalCodePtr), // the REPL code, the return pointer. VerifyAttrInterrupt(usize), // location of the verify attribute interrupt code in the CodeDir. } @@ -544,10 +459,10 @@ impl CodePtr { pub fn local(&self) -> LocalCodePtr { match self { &CodePtr::BuiltInClause(_, ref local) - | &CodePtr::CallN(_, ref local, _) - | &CodePtr::Local(ref local) => local.clone(), + | &CodePtr::CallN(_, ref local, _) + | &CodePtr::Local(ref local) => local.clone(), &CodePtr::VerifyAttrInterrupt(p) => LocalCodePtr::DirEntry(p), - &CodePtr::REPL(_, p) => p // | &CodePtr::DynamicTransaction(_, p) => p, + &CodePtr::REPL(_, p) => p, // | &CodePtr::DynamicTransaction(_, p) => p, } } @@ -566,12 +481,11 @@ pub enum LocalCodePtr { DirEntry(usize), // offset Halt, IndexingBuf(usize, usize, usize), // DirEntry offset, first internal offset, second internal offset - // TopLevel(usize, usize), // chunk_num, offset + // TopLevel(usize, usize), // chunk_num, offset } impl LocalCodePtr { - pub(crate) - fn assign_if_local(&mut self, cp: CodePtr) { + pub(crate) fn assign_if_local(&mut self, cp: CodePtr) { match cp { CodePtr::Local(local) => *self = local, _ => {} @@ -579,8 +493,7 @@ impl LocalCodePtr { } #[inline] - pub(crate) - fn abs_loc(&self) -> usize { + pub(crate) fn abs_loc(&self) -> usize { match self { LocalCodePtr::DirEntry(ref p) => *p, LocalCodePtr::IndexingBuf(ref p, ..) => *p, @@ -588,35 +501,28 @@ impl LocalCodePtr { } } - pub(crate) - fn is_reset_cont_marker(&self, code_repo: &CodeRepo, last_call: bool) -> bool { + pub(crate) fn is_reset_cont_marker(&self, code_repo: &CodeRepo, last_call: bool) -> bool { match code_repo.lookup_instr(last_call, &CodePtr::Local(*self)) { - Some(line) => { - match line.as_ref() { - Line::Control(ControlInstruction::CallClause(ref ct, ..)) => { - if let ClauseType::System(SystemClauseType::ResetContinuationMarker) = *ct { - return true; - } + Some(line) => match line.as_ref() { + Line::Control(ControlInstruction::CallClause(ref ct, ..)) => { + if let ClauseType::System(SystemClauseType::ResetContinuationMarker) = *ct { + return true; } - _ => {} } - } + _ => {} + }, None => {} } false } - pub(crate) - fn as_functor(&self, heap: &mut HeapTemplate) -> Addr { + pub(crate) fn as_functor(&self, heap: &mut HeapTemplate) -> Addr { let addr = Addr::HeapCell(heap.h()); match self { LocalCodePtr::DirEntry(p) => { - heap.append(functor!( - "dir_entry", - [integer(*p)] - )); + heap.append(functor!("dir_entry", [integer(*p)])); } LocalCodePtr::Halt => { heap.append(functor!("halt")); @@ -658,7 +564,7 @@ impl PartialOrd for CodePtr { impl PartialOrd for LocalCodePtr { fn partial_cmp(&self, other: &LocalCodePtr) -> Option { match (self, other) { - (&LocalCodePtr::DirEntry(p1), &LocalCodePtr::DirEntry(ref p2)) | + (&LocalCodePtr::DirEntry(p1), &LocalCodePtr::DirEntry(ref p2)) | (&LocalCodePtr::TopLevel(_, p1), &LocalCodePtr::TopLevel(_, ref p2)) => { p1.partial_cmp(p2) } @@ -693,12 +599,9 @@ impl Add for LocalCodePtr { #[inline] fn add(self, rhs: usize) -> Self::Output { match self { - LocalCodePtr::DirEntry(p) => - LocalCodePtr::DirEntry(p + rhs), - LocalCodePtr::Halt => - unreachable!(), - LocalCodePtr::IndexingBuf(p, o, i) => - LocalCodePtr::IndexingBuf(p, o, i + rhs), + LocalCodePtr::DirEntry(p) => LocalCodePtr::DirEntry(p + rhs), + LocalCodePtr::Halt => unreachable!(), + LocalCodePtr::IndexingBuf(p, o, i) => LocalCodePtr::IndexingBuf(p, o, i + rhs), } } } @@ -709,12 +612,11 @@ impl Sub for LocalCodePtr { #[inline] fn sub(self, rhs: usize) -> Self::Output { match self { - LocalCodePtr::DirEntry(p) => - p.checked_sub(rhs).map(LocalCodePtr::DirEntry), - LocalCodePtr::Halt => - unreachable!(), - LocalCodePtr::IndexingBuf(p, o, i) => - i.checked_sub(rhs).map(|r| LocalCodePtr::IndexingBuf(p, o, r)), + LocalCodePtr::DirEntry(p) => p.checked_sub(rhs).map(LocalCodePtr::DirEntry), + LocalCodePtr::Halt => unreachable!(), + LocalCodePtr::IndexingBuf(p, o, i) => i + .checked_sub(rhs) + .map(|r| LocalCodePtr::IndexingBuf(p, o, r)), } } } @@ -723,15 +625,12 @@ impl SubAssign for LocalCodePtr { #[inline] fn sub_assign(&mut self, rhs: usize) { match self { - LocalCodePtr::DirEntry(ref mut p) => - *p -= rhs, - LocalCodePtr::Halt | LocalCodePtr::IndexingBuf(..) => - unreachable!(), + LocalCodePtr::DirEntry(ref mut p) => *p -= rhs, + LocalCodePtr::Halt | LocalCodePtr::IndexingBuf(..) => unreachable!(), } } } - impl AddAssign for LocalCodePtr { #[inline] fn add_assign(&mut self, rhs: usize) { @@ -749,14 +648,12 @@ impl Add for CodePtr { fn add(self, rhs: usize) -> Self::Output { match self { - p @ CodePtr::REPL(..) | - p @ CodePtr::VerifyAttrInterrupt(_) => { // | - // p @ CodePtr::DynamicTransaction(..) => { + p @ CodePtr::REPL(..) | p @ CodePtr::VerifyAttrInterrupt(_) => { + // | + // p @ CodePtr::DynamicTransaction(..) => { p } - CodePtr::Local(local) => { - CodePtr::Local(local + rhs) - } + CodePtr::Local(local) => CodePtr::Local(local + rhs), CodePtr::BuiltInClause(_, local) | CodePtr::CallN(_, local, _) => { CodePtr::Local(local + rhs) } @@ -784,7 +681,6 @@ impl SubAssign for CodePtr { } } - pub type HeapVarDict = IndexMap, Addr>; pub type AllocVarDict = IndexMap, VarData>; @@ -830,23 +726,17 @@ impl IndexStore { key: &PredicateKey, ) -> Option<&mut PredicateSkeleton> { match (key.0.as_str(), key.1) { - ("term_expansion", 2) => { - self.extensible_predicates.get_mut(key) - } - _ => { - match compilation_target { - CompilationTarget::User => { - self.extensible_predicates.get_mut(key) - } - CompilationTarget::Module(ref module_name) => { - if let Some(module) = self.modules.get_mut(module_name) { - module.extensible_predicates.get_mut(key) - } else { - None - } + ("term_expansion", 2) => self.extensible_predicates.get_mut(key), + _ => match compilation_target { + CompilationTarget::User => self.extensible_predicates.get_mut(key), + CompilationTarget::Module(ref module_name) => { + if let Some(module) = self.modules.get_mut(module_name) { + module.extensible_predicates.get_mut(key) + } else { + None } } - } + }, } } @@ -858,19 +748,17 @@ impl IndexStore { match (key.0.as_str(), key.1) { ("term_expansion", 2) => { self.extensible_predicates.remove(key); - }, - _ => { - match compilation_target { - CompilationTarget::User => { - self.extensible_predicates.remove(key); - } - CompilationTarget::Module(ref module_name) => { - if let Some(module) = self.modules.get_mut(module_name) { - module.extensible_predicates.remove(key); - } + } + _ => match compilation_target { + CompilationTarget::User => { + self.extensible_predicates.remove(key); + } + CompilationTarget::Module(ref module_name) => { + if let Some(module) = self.modules.get_mut(module_name) { + module.extensible_predicates.remove(key); } } - } + }, } } @@ -883,15 +771,9 @@ impl IndexStore { ) -> Option { if module.as_str() == "user" { match ClauseType::from(name, arity, op_spec) { - ClauseType::Named(name, arity, _) => { - self.code_dir.get(&(name, arity)).cloned() - } - ClauseType::Op(name, spec, ..) => { - self.code_dir.get(&(name, spec.arity())).cloned() - } - _ => { - None - } + ClauseType::Named(name, arity, _) => self.code_dir.get(&(name, arity)).cloned(), + ClauseType::Op(name, spec, ..) => self.code_dir.get(&(name, spec.arity())).cloned(), + _ => None, } } else { self.modules.get(&module).and_then(|module| { @@ -902,9 +784,7 @@ impl IndexStore { ClauseType::Op(name, spec, ..) => { module.code_dir.get(&(name, spec.arity())).cloned() } - _ => { - None - } + _ => None, } }) } @@ -917,44 +797,32 @@ impl IndexStore { compilation_target: &CompilationTarget, ) -> Option<&Vec> { match compilation_target { - CompilationTarget::User => { - self.meta_predicates.get(&(name, arity)) - } - CompilationTarget::Module(ref module_name) => { - match self.modules.get(module_name) { - Some(ref module) => { - module.meta_predicates.get(&(name.clone(), arity)) - .or_else(|| { - self.meta_predicates.get(&(name, arity)) - }) - } - None => { - self.meta_predicates.get(&(name, arity)) - } - } - } + CompilationTarget::User => self.meta_predicates.get(&(name, arity)), + CompilationTarget::Module(ref module_name) => match self.modules.get(module_name) { + Some(ref module) => module + .meta_predicates + .get(&(name.clone(), arity)) + .or_else(|| self.meta_predicates.get(&(name, arity))), + None => self.meta_predicates.get(&(name, arity)), + }, } } pub fn is_dynamic_predicate(&self, module_name: ClauseName, key: PredicateKey) -> bool { match module_name.as_str() { - "user" => { - self.extensible_predicates.get(&key) + "user" => self + .extensible_predicates + .get(&key) + .map(|skeleton| skeleton.is_dynamic) + .unwrap_or(false), + _ => match self.modules.get(&module_name) { + Some(ref module) => module + .extensible_predicates + .get(&key) .map(|skeleton| skeleton.is_dynamic) - .unwrap_or(false) - } - _ => { - match self.modules.get(&module_name) { - Some(ref module) => { - module.extensible_predicates.get(&key) - .map(|skeleton| skeleton.is_dynamic) - .unwrap_or(false) - } - None => { - false - } - } - } + .unwrap_or(false), + None => false, + }, } } @@ -963,8 +831,7 @@ impl IndexStore { IndexStore::default() } - pub(super) - fn get_cleaner_sites(&self) -> (usize, usize) { + pub(super) fn get_cleaner_sites(&self) -> (usize, usize) { let r_w_h = clause_name!("run_cleaners_with_handling"); let r_wo_h = clause_name!("run_cleaners_without_handling"); let iso_ext = clause_name!("iso_ext"); @@ -996,10 +863,8 @@ pub enum RefOrOwned<'a, T: 'a> { impl<'a, T: 'a + fmt::Debug> fmt::Debug for RefOrOwned<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &RefOrOwned::Borrowed(ref borrowed) => - write!(f, "Borrowed({:?})", borrowed), - &RefOrOwned::Owned(ref owned) => - write!(f, "Owned({:?})", owned), + &RefOrOwned::Borrowed(ref borrowed) => write!(f, "Borrowed({:?})", borrowed), + &RefOrOwned::Owned(ref owned) => write!(f, "Owned({:?})", owned), } } } @@ -1012,7 +877,9 @@ impl<'a, T> RefOrOwned<'a, T> { } } - pub fn to_owned(self) -> T where T: Clone + pub fn to_owned(self) -> T + where + T: Clone, { match self { RefOrOwned::Borrowed(item) => item.clone(), diff --git a/src/machine/machine_state.rs b/src/machine/machine_state.rs index a49465ec..c8338c94 100644 --- a/src/machine/machine_state.rs +++ b/src/machine/machine_state.rs @@ -1,5 +1,6 @@ use crate::prolog_parser_rebis::ast::*; use crate::prolog_parser_rebis::tabled_rc::*; +use crate::prolog_parser_rebis::{clause_name, temp_v}; use crate::clause_types::*; use crate::forms::*; @@ -14,7 +15,9 @@ use crate::machine::stack::*; use crate::machine::streams::*; use crate::rug::Integer; -use crate::downcast::Any; +use crate::downcast::{ + downcast, downcast_methods, downcast_methods_core, downcast_methods_std, impl_downcast, Any, +}; use crate::indexmap::IndexMap; @@ -32,33 +35,26 @@ pub struct Ball { } impl Ball { - pub(super) - fn new() -> Self { + pub(super) fn new() -> Self { Ball { boundary: 0, stub: Heap::new(), } } - pub(super) - fn reset(&mut self) { + pub(super) fn reset(&mut self) { self.boundary = 0; self.stub.clear(); } - pub(super) - fn copy_and_align(&self, h: usize) -> Heap { + pub(super) fn copy_and_align(&self, h: usize) -> Heap { let diff = self.boundary as i64 - h as i64; let mut stub = Heap::new(); for heap_value in self.stub.iter_from(0) { stub.push(match heap_value { - &HeapCellValue::Addr(addr) => { - HeapCellValue::Addr(addr - diff) - } - heap_value => { - heap_value.context_free_clone() - } + &HeapCellValue::Addr(addr) => HeapCellValue::Addr(addr - diff), + heap_value => heap_value.context_free_clone(), }); } @@ -123,11 +119,7 @@ pub(super) struct CopyBallTerm<'a> { } impl<'a> CopyBallTerm<'a> { - pub(super) fn new( - stack: &'a mut Stack, - heap: &'a mut Heap, - stub: &'a mut Heap, - ) -> Self { + pub(super) fn new(stack: &'a mut Stack, heap: &'a mut Heap, stub: &'a mut Heap) -> Self { let hb = heap.h(); CopyBallTerm { @@ -182,12 +174,8 @@ impl<'a> CopierTarget for CopyBallTerm<'a> { let index = h - self.heap_boundary; self.stub[index].as_addr(h) } - Addr::StackCell(fr, sc) => { - self.stack.index_and_frame(fr)[sc] - } - addr => { - addr - } + Addr::StackCell(fr, sc) => self.stack.index_and_frame(fr)[sc], + addr => addr, } } @@ -226,9 +214,7 @@ impl Index for MachineState { impl IndexMut for MachineState { fn index_mut(&mut self, reg: RegType) -> &mut Self::Output { match reg { - RegType::Temp(temp) => { - &mut self.registers[temp] - } + RegType::Temp(temp) => &mut self.registers[temp], RegType::Perm(perm) => { let e = self.e; @@ -255,15 +241,12 @@ pub(super) enum HeapPtr { impl HeapPtr { #[inline] - pub(super) - fn read(&self, heap: &Heap) -> Addr { + pub(super) fn read(&self, heap: &Heap) -> Addr { match self { - &HeapPtr::HeapCell(h) => { - Addr::HeapCell(h) - } + &HeapPtr::HeapCell(h) => Addr::HeapCell(h), &HeapPtr::PStrChar(h, n) => { if let &HeapCellValue::PartialString(ref pstr, has_tail) = &heap[h] { - if let Some(c) = pstr.range_from(n ..).next() { + if let Some(c) = pstr.range_from(n..).next() { Addr::Char(c) } else if has_tail { Addr::HeapCell(h + 1) @@ -274,9 +257,7 @@ impl HeapPtr { unreachable!() } } - &HeapPtr::PStrLocation(h, n) => { - Addr::PStrLocation(h, n) - } + &HeapPtr::PStrLocation(h, n) => Addr::PStrLocation(h, n), } } } @@ -313,16 +294,11 @@ pub struct MachineState { pub(super) last_call: bool, pub(crate) heap_locs: HeapVarDict, pub(crate) flags: MachineFlags, - pub(crate) at_end_of_expansion: bool + pub(crate) at_end_of_expansion: bool, } impl MachineState { - pub(crate) - fn read_term( - &mut self, - mut stream: Stream, - indices: &mut IndexStore, - ) -> CallResult { + pub(crate) fn read_term(&mut self, mut stream: Stream, indices: &mut IndexStore) -> CallResult { self.check_stream_properties( &mut stream, StreamType::Text, @@ -342,11 +318,7 @@ impl MachineState { let mut orig_stream = stream.clone(); loop { - match self.read( - stream.clone(), - self.atom_tbl.clone(), - &indices.op_dir, - ) { + match self.read(stream.clone(), self.atom_tbl.clone(), &indices.op_dir) { Ok(term_write_result) => { let term = self[temp_v!(2)]; self.unify(Addr::HeapCell(term_write_result.heap_loc), term); @@ -363,7 +335,8 @@ impl MachineState { let h = self.heap.h(); let spec = fetch_atom_op_spec(clause_name!("="), None, &indices.op_dir); - self.heap.push(HeapCellValue::NamedStr(2, clause_name!("="), spec)); + self.heap + .push(HeapCellValue::NamedStr(2, clause_name!("="), spec)); self.heap.push(HeapCellValue::Atom(var_atom, None)); self.heap.push(HeapCellValue::Addr(binding)); @@ -406,8 +379,7 @@ impl MachineState { } let vars_addr = self[temp_v!(4)]; - let vars_offset = - Addr::HeapCell(self.heap.to_list(var_list.into_iter())); + let vars_offset = Addr::HeapCell(self.heap.to_list(var_list.into_iter())); self.unify(vars_offset, vars_addr); @@ -427,7 +399,7 @@ impl MachineState { self[temp_v!(2)], &mut orig_stream, clause_name!("read_term"), - 3 + 3, )?; if orig_stream.options.eof_action == EOFAction::Reset { @@ -448,12 +420,10 @@ impl MachineState { } } - pub(crate) - fn write_term<'a>( + pub(crate) fn write_term<'a>( &'a self, op_dir: &'a OpDir, - ) -> Result>, MachineStub> - { + ) -> Result>, MachineStub> { let ignore_ops = self.store(self.deref(self[temp_v!(3)])); let numbervars = self.store(self.deref(self[temp_v!(4)])); let quoted = self.store(self.deref(self[temp_v!(5)])); @@ -462,7 +432,7 @@ impl MachineState { let mut printer = HCPrinter::new(&self, op_dir, PrinterOutputter::new()); if let &Addr::Con(h) = &ignore_ops { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { printer.ignore_ops = name.as_str() == "true"; } else { unreachable!() @@ -470,7 +440,7 @@ impl MachineState { } if let &Addr::Con(h) = &numbervars { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { printer.numbervars = name.as_str() == "true"; } else { unreachable!() @@ -478,7 +448,7 @@ impl MachineState { } if let &Addr::Con(h) = "ed { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { printer.quoted = name.as_str() == "true"; } else { unreachable!() @@ -514,9 +484,7 @@ impl MachineState { for addr in addrs { match addr { Addr::Str(s) => match &self.heap[s] { - &HeapCellValue::NamedStr(2, ref name, _) - if name.as_str() == "=" => - { + &HeapCellValue::NamedStr(2, ref name, _) if name.as_str() == "=" => { let atom = self.heap[s + 1].as_addr(s + 1); let var = self.heap[s + 2].as_addr(s + 2); @@ -540,11 +508,9 @@ impl MachineState { var_names.insert(var, atom); } - _ => { - } + _ => {} }, - _ => { - } + _ => {} } } @@ -558,8 +524,7 @@ impl MachineState { Ok(Some(printer)) } - pub(super) - fn throw_undefined_error(&mut self, name: ClauseName, arity: usize) -> MachineStub { + pub(super) fn throw_undefined_error(&mut self, name: ClauseName, arity: usize) -> MachineStub { let stub = MachineError::functor_stub(name.clone(), arity); let h = self.heap.h(); let key = ExistenceError::Procedure(name, arity); @@ -568,13 +533,11 @@ impl MachineState { } #[inline] - pub(crate) - fn heap_pstr_iter<'a>(&'a self, focus: Addr) -> HeapPStrIter<'a> { + pub(crate) fn heap_pstr_iter<'a>(&'a self, focus: Addr) -> HeapPStrIter<'a> { HeapPStrIter::new(self, focus) } - pub(super) - fn try_char_list(&self, addrs: Vec) -> Result { + pub(super) fn try_char_list(&self, addrs: Vec) -> Result { let mut chars = String::new(); let mut iter = addrs.iter(); @@ -594,55 +557,46 @@ impl MachineState { } } } - _ => { - } + _ => {} }; let h = self.heap.h(); - return Err( - MachineError::type_error(h, ValidType::Character, addr) - ); + return Err(MachineError::type_error(h, ValidType::Character, addr)); } Ok(chars) } - pub(super) - fn read_predicate_key(&self, name: Addr, arity: Addr) -> (ClauseName, usize) { + pub(super) fn read_predicate_key(&self, name: Addr, arity: Addr) -> (ClauseName, usize) { let predicate_name = atom_from!(self, self.store(self.deref(name))); let arity = self.store(self.deref(arity)); - let arity = - match Number::try_from((arity, &self.heap)) { - Ok(Number::Integer(n)) if &*n >= &0 && &*n <= &MAX_ARITY => - n.to_usize().unwrap(), - Ok(Number::Fixnum(n)) if n >= 0 && n <= MAX_ARITY as isize => - usize::try_from(n).unwrap(), - _ => - unreachable!() - }; + let arity = match Number::try_from((arity, &self.heap)) { + Ok(Number::Integer(n)) if &*n >= &0 && &*n <= &MAX_ARITY => n.to_usize().unwrap(), + Ok(Number::Fixnum(n)) if n >= 0 && n <= MAX_ARITY as isize => { + usize::try_from(n).unwrap() + } + _ => unreachable!(), + }; (predicate_name, arity) } - pub(super) - fn call_at_index(&mut self, arity: usize, p: LocalCodePtr) { + pub(super) fn call_at_index(&mut self, arity: usize, p: LocalCodePtr) { self.cp.assign_if_local(self.p.clone() + 1); self.num_of_args = arity; self.b0 = self.b; self.p = CodePtr::Local(p); } - pub(super) - fn execute_at_index(&mut self, arity: usize, p: LocalCodePtr) { + pub(super) fn execute_at_index(&mut self, arity: usize, p: LocalCodePtr) { self.num_of_args = arity; self.b0 = self.b; self.p = CodePtr::Local(p); } - pub(super) - fn module_lookup( + pub(super) fn module_lookup( &mut self, indices: &IndexStore, call_policy: &mut Box, @@ -687,10 +641,15 @@ pub(crate) type CallResult = Result<(), Vec>; pub(crate) trait CallPolicy: Any + fmt::Debug { fn retry_me_else(&mut self, machine_st: &mut MachineState, offset: usize) -> CallResult { let b = machine_st.b; - let n = machine_st.stack.index_or_frame(b).prelude.univ_prelude.num_cells; + let n = machine_st + .stack + .index_or_frame(b) + .prelude + .univ_prelude + .num_cells; - for i in 1 .. n + 1 { - machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i-1]; + for i in 1..n + 1 { + machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i - 1]; } machine_st.num_of_args = n; @@ -706,17 +665,24 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { machine_st.tr = machine_st.stack.index_or_frame(b).prelude.tr; machine_st.trail.truncate(machine_st.tr); - machine_st.heap.truncate(machine_st.stack.index_or_frame(b).prelude.h); + machine_st + .heap + .truncate(machine_st.stack.index_or_frame(b).prelude.h); - let attr_var_init_queue_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_queue_b; - let attr_var_init_bindings_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_bindings_b; + let attr_var_init_queue_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_queue_b; + let attr_var_init_bindings_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_bindings_b; - machine_st.attr_var_init.backtrack( - attr_var_init_queue_b, - attr_var_init_bindings_b, - ); + machine_st + .attr_var_init + .backtrack(attr_var_init_queue_b, attr_var_init_bindings_b); machine_st.hb = machine_st.heap.h(); machine_st.p += 1; @@ -726,10 +692,15 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { fn retry(&mut self, machine_st: &mut MachineState, offset: usize) -> CallResult { let b = machine_st.b; - let n = machine_st.stack.index_or_frame(b).prelude.univ_prelude.num_cells; + let n = machine_st + .stack + .index_or_frame(b) + .prelude + .univ_prelude + .num_cells; - for i in 1 .. n + 1 { - machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i-1]; + for i in 1..n + 1 { + machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i - 1]; } machine_st.num_of_args = n; @@ -745,14 +716,24 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { machine_st.tr = machine_st.stack.index_or_frame(b).prelude.tr; machine_st.trail.truncate(machine_st.tr); - machine_st.heap.truncate(machine_st.stack.index_or_frame(b).prelude.h); + machine_st + .heap + .truncate(machine_st.stack.index_or_frame(b).prelude.h); - let attr_var_init_queue_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_queue_b; - let attr_var_init_bindings_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_bindings_b; + let attr_var_init_queue_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_queue_b; + let attr_var_init_bindings_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_bindings_b; - machine_st.attr_var_init.backtrack(attr_var_init_queue_b, attr_var_init_bindings_b); + machine_st + .attr_var_init + .backtrack(attr_var_init_queue_b, attr_var_init_bindings_b); machine_st.hb = machine_st.heap.h(); machine_st.p = CodePtr::Local(dir_entry!(machine_st.p.local().abs_loc() + offset)); @@ -762,10 +743,15 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { fn trust(&mut self, machine_st: &mut MachineState, offset: usize) -> CallResult { let b = machine_st.b; - let n = machine_st.stack.index_or_frame(b).prelude.univ_prelude.num_cells; + let n = machine_st + .stack + .index_or_frame(b) + .prelude + .univ_prelude + .num_cells; - for i in 1 .. n + 1 { - machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i-1]; + for i in 1..n + 1 { + machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i - 1]; } machine_st.num_of_args = n; @@ -779,17 +765,24 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { machine_st.tr = machine_st.stack.index_or_frame(b).prelude.tr; machine_st.trail.truncate(machine_st.tr); - machine_st.heap.truncate(machine_st.stack.index_or_frame(b).prelude.h); + machine_st + .heap + .truncate(machine_st.stack.index_or_frame(b).prelude.h); - let attr_var_init_queue_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_queue_b; - let attr_var_init_bindings_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_bindings_b; + let attr_var_init_queue_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_queue_b; + let attr_var_init_bindings_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_bindings_b; - machine_st.attr_var_init.backtrack( - attr_var_init_queue_b, - attr_var_init_bindings_b, - ); + machine_st + .attr_var_init + .backtrack(attr_var_init_queue_b, attr_var_init_bindings_b); machine_st.b = machine_st.stack.index_or_frame(b).prelude.b; machine_st.stack.truncate(b); @@ -802,10 +795,15 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { fn trust_me(&mut self, machine_st: &mut MachineState) -> CallResult { let b = machine_st.b; - let n = machine_st.stack.index_or_frame(b).prelude.univ_prelude.num_cells; + let n = machine_st + .stack + .index_or_frame(b) + .prelude + .univ_prelude + .num_cells; - for i in 1 .. n + 1 { - machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i-1]; + for i in 1..n + 1 { + machine_st.registers[i] = machine_st.stack.index_or_frame(b)[i - 1]; } machine_st.num_of_args = n; @@ -819,17 +817,24 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { machine_st.tr = machine_st.stack.index_or_frame(b).prelude.tr; machine_st.trail.truncate(machine_st.tr); - machine_st.heap.truncate(machine_st.stack.index_or_frame(b).prelude.h); + machine_st + .heap + .truncate(machine_st.stack.index_or_frame(b).prelude.h); - let attr_var_init_queue_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_queue_b; - let attr_var_init_bindings_b = - machine_st.stack.index_or_frame(b).prelude.attr_var_init_bindings_b; + let attr_var_init_queue_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_queue_b; + let attr_var_init_bindings_b = machine_st + .stack + .index_or_frame(b) + .prelude + .attr_var_init_bindings_b; - machine_st.attr_var_init.backtrack( - attr_var_init_queue_b, - attr_var_init_bindings_b, - ); + machine_st + .attr_var_init + .backtrack(attr_var_init_queue_b, attr_var_init_bindings_b); machine_st.b = machine_st.stack.index_or_frame(b).prelude.b; machine_st.stack.truncate(b); @@ -928,13 +933,13 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { Addr::Con(h) if machine_st.heap.atom_at(h) => { if let HeapCellValue::Atom(ref atom, _) = &machine_st.heap[h] { match atom.as_str() { - ">" | "<" | "=" => { - } + ">" | "<" | "=" => {} _ => { let stub = MachineError::functor_stub(clause_name!("compare"), 3); - let err = MachineError::domain_error(DomainErrorType::Order, a1); + let err = + MachineError::domain_error(DomainErrorType::Order, a1); return Err(machine_st.error_form(err, stub)); } } @@ -948,8 +953,7 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { let err = MachineError::type_error(h, ValidType::Atom, a1); return Err(machine_st.error_form(err, stub)); } - _ => { - } + _ => {} } let atom = match machine_st.compare_term_test(&a2, &a3) { @@ -998,9 +1002,7 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { let addr = machine_st[temp_v!(1)]; let eof = clause_name!("end_of_file".to_string(), machine_st.atom_tbl); - let atom = machine_st.heap.to_unifiable( - HeapCellValue::Atom(eof, None) - ); + let atom = machine_st.heap.to_unifiable(HeapCellValue::Atom(eof, None)); machine_st.unify(addr, atom); } @@ -1056,7 +1058,9 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { let mut list = machine_st.try_from_list(temp_v!(1), stub)?; list.sort_unstable_by(|a1, a2| { - machine_st.compare_term_test(a1, a2).unwrap_or(Ordering::Less) + machine_st + .compare_term_test(a1, a2) + .unwrap_or(Ordering::Less) }); machine_st.term_dedup(&mut list); @@ -1081,7 +1085,9 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { } key_pairs.sort_by(|a1, a2| { - machine_st.compare_term_test(&a1.0, &a2.0).unwrap_or(Ordering::Less) + machine_st + .compare_term_test(&a1.0, &a2.0) + .unwrap_or(Ordering::Less) }); let key_pairs = key_pairs.into_iter().map(|kp| kp.1); @@ -1155,11 +1161,7 @@ pub(crate) trait CallPolicy: Any + fmt::Debug { let stub = MachineError::functor_stub(clause_name!("call"), arity + 1); return Err(machine_st.error_form( - MachineError::type_error( - machine_st.heap.h(), - ValidType::Callable, - name - ), + MachineError::type_error(machine_st.heap.h(), ValidType::Callable, name), stub, )); } @@ -1200,7 +1202,8 @@ impl CallPolicy for CWILCallPolicy { arity: usize, idx: &CodeIndex, ) -> CallResult { - self.prev_policy.context_call(machine_st, name, arity, idx)?;//, indices)?; + self.prev_policy + .context_call(machine_st, name, arity, idx)?; //, indices)?; self.increment(machine_st) } @@ -1239,7 +1242,7 @@ impl CallPolicy for CWILCallPolicy { code_dir, op_dir, current_input_stream, - current_output_stream + current_output_stream, )?; self.increment(machine_st) @@ -1283,8 +1286,7 @@ pub(crate) struct CWILCallPolicy { } impl CWILCallPolicy { - pub(crate) - fn new_in_place(policy: &mut Box) { + pub(crate) fn new_in_place(policy: &mut Box) { let mut prev_policy: Box = Box::new(DefaultCallPolicy {}); mem::swap(&mut prev_policy, policy); @@ -1319,8 +1321,7 @@ impl CWILCallPolicy { Ok(()) } - pub(crate) - fn add_limit(&mut self, mut limit: Integer, b: usize) -> &Integer { + pub(crate) fn add_limit(&mut self, mut limit: Integer, b: usize) -> &Integer { limit += &self.count; match self.limits.last().cloned() { @@ -1331,8 +1332,7 @@ impl CWILCallPolicy { &self.count } - pub(crate) - fn remove_limit(&mut self, b: usize) -> &Integer { + pub(crate) fn remove_limit(&mut self, b: usize) -> &Integer { if let Some((_, bp)) = self.limits.last().cloned() { if bp == b { self.limits.pop(); @@ -1342,13 +1342,11 @@ impl CWILCallPolicy { &self.count } - pub(crate) - fn is_empty(&self) -> bool { + pub(crate) fn is_empty(&self) -> bool { self.limits.is_empty() } - pub(crate) - fn into_inner(&mut self) -> Box { + pub(crate) fn into_inner(&mut self) -> Box { let mut new_inner: Box = Box::new(DefaultCallPolicy {}); mem::swap(&mut self.prev_policy, &mut new_inner); new_inner diff --git a/src/machine/machine_state_impl.rs b/src/machine/machine_state_impl.rs index 1b62431e..d0348f9f 100644 --- a/src/machine/machine_state_impl.rs +++ b/src/machine/machine_state_impl.rs @@ -1,12 +1,12 @@ use crate::prolog_parser_rebis::ast::*; use crate::prolog_parser_rebis::tabled_rc::*; +use crate::prolog_parser_rebis::{clause_name, perm_v, temp_v}; use crate::clause_types::*; use crate::forms::*; use crate::heap_iter::*; use crate::indexing::*; use crate::instructions::*; -use crate::machine::INTERRUPT; use crate::machine::attributed_variables::*; use crate::machine::code_repo::CodeRepo; use crate::machine::copier::*; @@ -17,6 +17,7 @@ use crate::machine::machine_state::*; use crate::machine::partial_string::*; use crate::machine::stack::*; use crate::machine::streams::*; +use crate::machine::INTERRUPT; use crate::ordered_float::*; use crate::rug::Integer; @@ -27,8 +28,7 @@ use std::convert::TryFrom; use std::rc::Rc; impl MachineState { - pub(crate) - fn new() -> Self { + pub(crate) fn new() -> Self { MachineState { atom_tbl: TabledData::new(Rc::new("".to_owned())), s: HeapPtr::default(), @@ -54,7 +54,7 @@ impl MachineState { last_call: false, heap_locs: HeapVarDict::new(), flags: MachineFlags::default(), - at_end_of_expansion: false + at_end_of_expansion: false, } } @@ -63,15 +63,10 @@ impl MachineState { self.flags } - pub(crate) - fn store(&self, addr: Addr) -> Addr { + pub(crate) fn store(&self, addr: Addr) -> Addr { match addr { - Addr::AttrVar(h) | Addr::HeapCell(h) => { - self.heap[h].as_addr(h) - } - Addr::StackCell(fr, sc) => { - self.stack.index_and_frame(fr)[sc] - } + Addr::AttrVar(h) | Addr::HeapCell(h) => self.heap[h].as_addr(h), + Addr::StackCell(fr, sc) => self.stack.index_and_frame(fr)[sc], Addr::PStrLocation(h, n) => { if let &HeapCellValue::PartialString(ref pstr, has_tail) = &self.heap[h] { if !pstr.at_end(n) { @@ -85,14 +80,11 @@ impl MachineState { unreachable!() } } - addr => { - addr - } + addr => addr, } } - pub(crate) - fn deref(&self, mut addr: Addr) -> Addr { + pub(crate) fn deref(&self, mut addr: Addr) -> Addr { loop { let value = self.store(addr); @@ -123,8 +115,7 @@ impl MachineState { } } - pub(super) - fn bind(&mut self, r1: Ref, a2: Addr) { + pub(super) fn bind(&mut self, r1: Ref, a2: Addr) { let t1 = self.store(r1.as_addr()); let t2 = self.store(a2); @@ -155,8 +146,7 @@ impl MachineState { Some(Ref::AttrVar(h)) => { self.bind_attr_var(h, t1); } - None => { - } + None => {} } } } @@ -185,8 +175,7 @@ impl MachineState { self.bind(r, addr); } - pub(super) - fn unify_with_occurs_check(&mut self, a1: Addr, a2: Addr) { + pub(super) fn unify_with_occurs_check(&mut self, a1: Addr, a2: Addr) { let mut pdl = vec![a1, a2]; let mut tabu_list: IndexSet<(Addr, Addr)> = IndexSet::new(); @@ -231,10 +220,10 @@ impl MachineState { self.fail = true; } - (Addr::PStrLocation(h, n), Addr::Lis(l)) | - (Addr::Lis(l), Addr::PStrLocation(h, n)) => { + (Addr::PStrLocation(h, n), Addr::Lis(l)) + | (Addr::Lis(l), Addr::PStrLocation(h, n)) => { if let HeapCellValue::PartialString(ref pstr, _) = &self.heap[h] { - if let Some(c) = pstr.range_from(n ..).next() { + if let Some(c) = pstr.range_from(n..).next() { pdl.push(Addr::PStrLocation(h, n + c.len_utf8())); pdl.push(Addr::HeapCell(l + 1)); @@ -248,20 +237,22 @@ impl MachineState { } } (Addr::PStrLocation(h1, n1), Addr::PStrLocation(h2, n2)) => { - if let &HeapCellValue::PartialString(ref pstr1, has_tail_1) = &self.heap[h1] { - if let &HeapCellValue::PartialString(ref pstr2, has_tail_2) = &self.heap[h2] { + if let &HeapCellValue::PartialString(ref pstr1, has_tail_1) = &self.heap[h1] + { + if let &HeapCellValue::PartialString(ref pstr2, has_tail_2) = + &self.heap[h2] + { let pstr1_s = pstr1.as_str_from(n1); let pstr2_s = pstr2.as_str_from(n2); - let m_len = - if pstr1_s.starts_with(pstr2_s) { - pstr2_s.len() - } else if pstr2_s.starts_with(pstr1_s) { - pstr1_s.len() - } else { - self.fail = true; - return; - }; + let m_len = if pstr1_s.starts_with(pstr2_s) { + pstr2_s.len() + } else if pstr2_s.starts_with(pstr1_s) { + pstr1_s.len() + } else { + self.fail = true; + return; + }; if pstr1.at_end(n1 + m_len) { if has_tail_1 { @@ -325,34 +316,25 @@ impl MachineState { self.fail = true; } - (Addr::Con(c1), Addr::Con(c2)) => { - match (&self.heap[c1], &self.heap[c2]) { - ( - &HeapCellValue::Atom(ref n1, _), - &HeapCellValue::Atom(ref n2, _), - ) if n1.as_str() == n2.as_str() => { - } - ( - &HeapCellValue::DBRef(ref db_ref_1), - &HeapCellValue::DBRef(ref db_ref_2), - ) if db_ref_1 == db_ref_2 => { - } - ( - v1, - v2, - ) => { - if let Ok(n1) = Number::try_from(v1) { - if let Ok(n2) = Number::try_from(v2) { - if n1 == n2 { - continue; - } + (Addr::Con(c1), Addr::Con(c2)) => match (&self.heap[c1], &self.heap[c2]) { + (&HeapCellValue::Atom(ref n1, _), &HeapCellValue::Atom(ref n2, _)) + if n1.as_str() == n2.as_str() => {} + ( + &HeapCellValue::DBRef(ref db_ref_1), + &HeapCellValue::DBRef(ref db_ref_2), + ) if db_ref_1 == db_ref_2 => {} + (v1, v2) => { + if let Ok(n1) = Number::try_from(v1) { + if let Ok(n2) = Number::try_from(v2) { + if n1 == n2 { + continue; } } - - self.fail = true; } + + self.fail = true; } - } + }, (Addr::Con(h), Addr::Char(c)) | (Addr::Char(c), Addr::Con(h)) => { match &self.heap[h] { &HeapCellValue::Atom(ref name, _) if name.is_char() => { @@ -401,8 +383,7 @@ impl MachineState { } } - pub(super) - fn unify(&mut self, a1: Addr, a2: Addr) { + pub(super) fn unify(&mut self, a1: Addr, a2: Addr) { let mut pdl = vec![a1, a2]; let mut tabu_list: IndexSet<(Addr, Addr)> = IndexSet::new(); @@ -448,37 +429,39 @@ impl MachineState { self.fail = true; } - (Addr::PStrLocation(h, n), Addr::Lis(l)) | - (Addr::Lis(l), Addr::PStrLocation(h, n)) => { - if let HeapCellValue::PartialString(ref pstr, _) = &self.heap[h] { - if let Some(c) = pstr.range_from(n ..).next() { - pdl.push(Addr::PStrLocation(h, n + c.len_utf8())); - pdl.push(Addr::HeapCell(l + 1)); + (Addr::PStrLocation(h, n), Addr::Lis(l)) + | (Addr::Lis(l), Addr::PStrLocation(h, n)) => { + if let HeapCellValue::PartialString(ref pstr, _) = &self.heap[h] { + if let Some(c) = pstr.range_from(n..).next() { + pdl.push(Addr::PStrLocation(h, n + c.len_utf8())); + pdl.push(Addr::HeapCell(l + 1)); - pdl.push(Addr::Char(c)); - pdl.push(Addr::HeapCell(l)); - } else { - unreachable!() - } - } else { - unreachable!() - } + pdl.push(Addr::Char(c)); + pdl.push(Addr::HeapCell(l)); + } else { + unreachable!() + } + } else { + unreachable!() + } } (Addr::PStrLocation(h1, n1), Addr::PStrLocation(h2, n2)) => { - if let &HeapCellValue::PartialString(ref pstr1, has_tail_1) = &self.heap[h1] { - if let &HeapCellValue::PartialString(ref pstr2, has_tail_2) = &self.heap[h2] { + if let &HeapCellValue::PartialString(ref pstr1, has_tail_1) = &self.heap[h1] + { + if let &HeapCellValue::PartialString(ref pstr2, has_tail_2) = + &self.heap[h2] + { let pstr1_s = pstr1.as_str_from(n1); let pstr2_s = pstr2.as_str_from(n2); - let m_len = - if pstr1_s.starts_with(pstr2_s) { - pstr2_s.len() - } else if pstr2_s.starts_with(pstr1_s) { - pstr1_s.len() - } else { - self.fail = true; - return; - }; + let m_len = if pstr1_s.starts_with(pstr2_s) { + pstr2_s.len() + } else if pstr2_s.starts_with(pstr1_s) { + pstr1_s.len() + } else { + self.fail = true; + return; + }; if pstr1.at_end(n1 + m_len) { if has_tail_1 { @@ -538,34 +521,25 @@ impl MachineState { self.fail = true; } - (Addr::Con(c1), Addr::Con(c2)) => { - match (&self.heap[c1], &self.heap[c2]) { - ( - &HeapCellValue::Atom(ref n1, _), - &HeapCellValue::Atom(ref n2, _), - ) if n1.as_str() == n2.as_str() => { - } -( - &HeapCellValue::DBRef(ref db_ref_1), - &HeapCellValue::DBRef(ref db_ref_2), - ) if db_ref_1 == db_ref_2 => { - } - ( - v1, - v2, - ) => { - if let Ok(n1) = Number::try_from(v1) { - if let Ok(n2) = Number::try_from(v2) { - if n1 == n2 { - continue; - } + (Addr::Con(c1), Addr::Con(c2)) => match (&self.heap[c1], &self.heap[c2]) { + (&HeapCellValue::Atom(ref n1, _), &HeapCellValue::Atom(ref n2, _)) + if n1.as_str() == n2.as_str() => {} + ( + &HeapCellValue::DBRef(ref db_ref_1), + &HeapCellValue::DBRef(ref db_ref_2), + ) if db_ref_1 == db_ref_2 => {} + (v1, v2) => { + if let Ok(n1) = Number::try_from(v1) { + if let Ok(n2) = Number::try_from(v2) { + if n1 == n2 { + continue; } } - - self.fail = true; } + + self.fail = true; } - } + }, (Addr::Con(h), Addr::Char(c)) | (Addr::Char(c), Addr::Con(h)) => { match &self.heap[h] { &HeapCellValue::Atom(ref name, _) if name.is_char() => { @@ -614,8 +588,7 @@ impl MachineState { } } - pub(super) - fn trail(&mut self, r: TrailRef) { + pub(super) fn trail(&mut self, r: TrailRef) { match r { TrailRef::Ref(Ref::HeapCell(h)) => { if h < self.hb { @@ -655,25 +628,22 @@ impl MachineState { HeapPtr::HeapCell(ref mut h) => { *h += rhs; } - &mut HeapPtr::PStrChar(h, ref mut n) | - &mut HeapPtr::PStrLocation(h, ref mut n) => { + &mut HeapPtr::PStrChar(h, ref mut n) | &mut HeapPtr::PStrLocation(h, ref mut n) => { match &self.heap[h] { &HeapCellValue::PartialString(ref pstr, _) => { - for c in pstr.range_from(*n ..).take(rhs) { + for c in pstr.range_from(*n..).take(rhs) { *n += c.len_utf8(); } self.s = HeapPtr::PStrLocation(h, *n); } - _ => { - } + _ => {} } } } } - pub(super) - fn unwind_trail(&mut self, a1: usize, a2: usize) { + pub(super) fn unwind_trail(&mut self, a1: usize, a2: usize) { // the sequence is reversed to respect the chronology of trail // additions, now that deleted attributes can be undeleted by // backtracking. @@ -698,8 +668,7 @@ impl MachineState { } } - pub(super) - fn tidy_trail(&mut self) { + pub(super) fn tidy_trail(&mut self) { if self.b == 0 { return; } @@ -708,12 +677,12 @@ impl MachineState { let hb = self.hb; let mut offset = 0; - for i in self.stack.index_or_frame(b).prelude.tr .. self.tr { + for i in self.stack.index_or_frame(b).prelude.tr..self.tr { match self.trail[i] { TrailRef::Ref(Ref::AttrVar(tr_i)) - | TrailRef::Ref(Ref::HeapCell(tr_i)) - | TrailRef::AttrVarHeapLink(tr_i) - | TrailRef::AttrVarListLink(tr_i, _) => { + | TrailRef::Ref(Ref::HeapCell(tr_i)) + | TrailRef::AttrVarHeapLink(tr_i) + | TrailRef::AttrVarListLink(tr_i, _) => { if tr_i >= hb { offset += 1; } else { @@ -734,8 +703,7 @@ impl MachineState { self.trail.truncate(self.tr); } - pub(super) - fn match_partial_string(&mut self, addr: Addr, string: &String, has_tail: bool) { + pub(super) fn match_partial_string(&mut self, addr: Addr, string: &String, has_tail: bool) { let mut heap_pstr_iter = self.heap_pstr_iter(addr); match compare_pstr_to_string(&mut heap_pstr_iter, string) { @@ -770,81 +738,64 @@ impl MachineState { } } } - Some(prefix_len) => { - match heap_pstr_iter.focus() { - addr if addr.is_ref() => { - let h = self.heap.h(); + Some(prefix_len) => match heap_pstr_iter.focus() { + addr if addr.is_ref() => { + let h = self.heap.h(); - let pstr_addr = - if has_tail { - self.s = HeapPtr::HeapCell(h+1); - self.mode = MachineMode::Read; + let pstr_addr = if has_tail { + self.s = HeapPtr::HeapCell(h + 1); + self.mode = MachineMode::Read; - self.heap.allocate_pstr(&string[prefix_len ..]) - } else { - self.heap.put_complete_string(&string[prefix_len ..]) - }; + self.heap.allocate_pstr(&string[prefix_len..]) + } else { + self.heap.put_complete_string(&string[prefix_len..]) + }; - self.bind(addr.as_var().unwrap(), pstr_addr); - } - Addr::Lis(l) => { - let h = self.heap.h(); - - let pstr_addr = - if has_tail { - self.s = HeapPtr::HeapCell(h+1); - self.mode = MachineMode::Read; - - self.heap.allocate_pstr(&string[prefix_len ..]) - } else { - self.heap.put_complete_string(&string[prefix_len ..]) - }; - - self.unify(Addr::Lis(l), pstr_addr); - } - _ => { - self.fail = true; - } + self.bind(addr.as_var().unwrap(), pstr_addr); } - } + Addr::Lis(l) => { + let h = self.heap.h(); + + let pstr_addr = if has_tail { + self.s = HeapPtr::HeapCell(h + 1); + self.mode = MachineMode::Read; + + self.heap.allocate_pstr(&string[prefix_len..]) + } else { + self.heap.put_complete_string(&string[prefix_len..]) + }; + + self.unify(Addr::Lis(l), pstr_addr); + } + _ => { + self.fail = true; + } + }, None => { self.fail = true; } } } - pub(super) - fn write_constant_to_var(&mut self, addr: Addr, c: &Constant) { + pub(super) fn write_constant_to_var(&mut self, addr: Addr, c: &Constant) { match self.store(self.deref(addr)) { Addr::Con(c1) => { match &self.heap[c1] { HeapCellValue::Atom(ref n1, _) => { self.fail = match c { - Constant::Atom(ref n2, _) => { - n1 != n2 - } + Constant::Atom(ref n2, _) => n1 != n2, Constant::Char(c) if n1.is_char() => { Some(*c) != n1.as_str().chars().next() } - _ => { - true - } + _ => true, }; } HeapCellValue::Integer(ref n1) => { self.fail = match c { - Constant::Fixnum(n2) => { - n1.to_isize() != Some(*n2) - } - Constant::Integer(ref n2) => { - n1 != n2 - } - Constant::Usize(n2) => { - n1.to_usize() != Some(*n2) - } - _ => { - true - } + Constant::Fixnum(n2) => n1.to_isize() != Some(*n2), + Constant::Integer(ref n2) => n1 != n2, + Constant::Usize(n2) => n1.to_usize() != Some(*n2), + _ => true, }; } HeapCellValue::Rational(ref r1) => { @@ -856,11 +807,7 @@ impl MachineState { } HeapCellValue::PartialString(..) => { if let Constant::String(ref s2) = c { - self.match_partial_string( - Addr::PStrLocation(c1, 0), - &s2, - false, - ); + self.match_partial_string(Addr::PStrLocation(c1, 0), &s2, false); } else { self.fail = true; } @@ -875,12 +822,8 @@ impl MachineState { Constant::Atom(ref n2, _) if n2.is_char() => { Some(ch) != n2.as_str().chars().next() } - Constant::Char(c) => { - *c != ch - } - _ => { - true - } + Constant::Char(c) => *c != ch, + _ => true, }; } Addr::EmptyList => { @@ -895,11 +838,7 @@ impl MachineState { } Addr::PStrLocation(h, n) => { if let Constant::String(ref s2) = c { - self.match_partial_string( - Addr::PStrLocation(h, n), - &s2, - false, - ) + self.match_partial_string(Addr::PStrLocation(h, n), &s2, false) } else { self.fail = true; }; @@ -919,8 +858,7 @@ impl MachineState { }; } - pub(super) - fn execute_arith_instr(&mut self, instr: &ArithmeticInstruction) { + pub(super) fn execute_arith_instr(&mut self, instr: &ArithmeticInstruction) { let stub = MachineError::functor_stub(clause_name!("is"), 2); match instr { @@ -984,7 +922,7 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!("(rdiv)"), 2); let (r1, stub) = try_or_fail!(self, self.get_rational(a1, stub)); - let (r2, _) = try_or_fail!(self, self.get_rational(a2, stub)); + let (r2, _) = try_or_fail!(self, self.get_rational(a2, stub)); self.interms[t - 1] = Number::Rational(Rc::new(try_or_fail!(self, self.rdiv(r1, r2)))); @@ -1190,8 +1128,7 @@ impl MachineState { }; } - pub(super) - fn execute_fact_instr(&mut self, instr: &FactInstruction) { + pub(super) fn execute_fact_instr(&mut self, instr: &FactInstruction) { match instr { &FactInstruction::GetConstant(_, ref c, reg) => { let addr = self[reg]; @@ -1205,9 +1142,9 @@ impl MachineState { self.s = HeapPtr::PStrChar(h, n); self.mode = MachineMode::Read; } - addr @ Addr::AttrVar(_) | - addr @ Addr::StackCell(..) | - addr @ Addr::HeapCell(_) => { + addr @ Addr::AttrVar(_) + | addr @ Addr::StackCell(..) + | addr @ Addr::HeapCell(_) => { let h = self.heap.h(); self.heap.push(HeapCellValue::Addr(Addr::Lis(h + 1))); @@ -1248,7 +1185,8 @@ impl MachineState { let h = self.heap.h(); self.heap.push(HeapCellValue::Addr(Addr::Str(h + 1))); - self.heap.push(HeapCellValue::NamedStr(arity, ct.name(), ct.spec())); + self.heap + .push(HeapCellValue::NamedStr(arity, ct.name(), ct.spec())); self.bind(addr.as_var().unwrap(), Addr::HeapCell(h)); @@ -1358,22 +1296,20 @@ impl MachineState { }; } - pub(super) - fn execute_indexing_instr( + pub(super) fn execute_indexing_instr( &mut self, indexing_lines: &Vec, call_policy: &mut Box, ) { let mut index = 0; - let addr = - match &indexing_lines[0] { - &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(arg, ..)) => { - self.store(self.deref(self[temp_v!(arg)])) - } - _ => { - unreachable!() - } - }; + let addr = match &indexing_lines[0] { + &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(arg, ..)) => { + self.store(self.deref(self[temp_v!(arg)])) + } + _ => { + unreachable!() + } + }; loop { match &indexing_lines[index] { @@ -1385,19 +1321,16 @@ impl MachineState { Addr::HeapCell(_) | Addr::StackCell(..) | Addr::AttrVar(..) => { IndexingCodePtr::External(v) } - Addr::PStrLocation(..) => { - l - } - Addr::Char(_) | Addr::Con(_) | Addr::CutPoint(_) | - Addr::EmptyList | Addr::Fixnum(_) | Addr::Float(_) | Addr::Usize(_) => { - c - } - Addr::Lis(_) => { - l - } - Addr::Str(_) => { - s - } + Addr::PStrLocation(..) => l, + Addr::Char(_) + | Addr::Con(_) + | Addr::CutPoint(_) + | Addr::EmptyList + | Addr::Fixnum(_) + | Addr::Float(_) + | Addr::Usize(_) => c, + Addr::Lis(_) => l, + Addr::Str(_) => s, }; match offset { @@ -1415,18 +1348,13 @@ impl MachineState { }; } &IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref hm)) => { - let offset = - match addr.as_constant_index(&self) { - Some(c) => { - match hm.get(&c) { - Some(offset) => *offset, - _ => IndexingCodePtr::Fail, - } - } - None => { - IndexingCodePtr::Fail - } - }; + let offset = match addr.as_constant_index(&self) { + Some(c) => match hm.get(&c) { + Some(offset) => *offset, + _ => IndexingCodePtr::Fail, + }, + None => IndexingCodePtr::Fail, + }; match offset { IndexingCodePtr::Fail => { @@ -1448,15 +1376,13 @@ impl MachineState { if let &HeapCellValue::NamedStr(arity, ref name, _) = &self.heap[s] { match hm.get(&(name.clone(), arity)) { Some(offset) => *offset, - _ => IndexingCodePtr::Fail + _ => IndexingCodePtr::Fail, } } else { IndexingCodePtr::Fail } } - _ => { - IndexingCodePtr::Fail - } + _ => IndexingCodePtr::Fail, }; match offset { @@ -1484,7 +1410,7 @@ impl MachineState { break; } } - }; + } } pub(super) fn execute_query_instr(&mut self, instr: &QueryInstruction) { @@ -1499,25 +1425,25 @@ impl MachineState { self[reg] = Addr::Lis(self.heap.h()); } &QueryInstruction::PutPartialString(_, ref string, reg, has_tail) => { - let pstr_addr = - if has_tail { - if !string.is_empty() { - let pstr_addr = self.heap.allocate_pstr(&string); - self.heap.pop(); // the tail will be added by the next instruction. - pstr_addr - } else { - Addr::EmptyList - } + let pstr_addr = if has_tail { + if !string.is_empty() { + let pstr_addr = self.heap.allocate_pstr(&string); + self.heap.pop(); // the tail will be added by the next instruction. + pstr_addr } else { - self.heap.put_complete_string(&string) - }; + Addr::EmptyList + } + } else { + self.heap.put_complete_string(&string) + }; self[reg] = pstr_addr; } &QueryInstruction::PutStructure(ref ct, arity, reg) => { let h = self.heap.h(); - self.heap.push(HeapCellValue::NamedStr(arity, ct.name(), ct.spec())); + self.heap + .push(HeapCellValue::NamedStr(arity, ct.name(), ct.spec())); self[reg] = Addr::Str(h); } &QueryInstruction::PutUnsafeValue(n, arg) => { @@ -1586,7 +1512,7 @@ impl MachineState { &QueryInstruction::SetVoid(n) => { let h = self.heap.h(); - for i in h .. h + n { + for i in h..h + n { self.heap.push(HeapCellValue::Addr(Addr::HeapCell(i))); } } @@ -1606,8 +1532,7 @@ impl MachineState { ); } - pub(super) - fn handle_internal_call_n(&mut self, arity: usize) { + pub(super) fn handle_internal_call_n(&mut self, arity: usize) { let arity = arity + 1; let pred = self.registers[1]; @@ -1623,8 +1548,7 @@ impl MachineState { self.fail = true; } - pub(super) - fn setup_call_n(&mut self, arity: usize) -> Option { + pub(super) fn setup_call_n(&mut self, arity: usize) -> Option { let addr = self.store(self.deref(self.registers[arity])); let (name, narity) = match addr { @@ -1644,11 +1568,11 @@ impl MachineState { return None; } - for i in (1 .. arity).rev() { + for i in (1..arity).rev() { self.registers[i + narity] = self.registers[i]; } - for i in 1 .. narity + 1 { + for i in 1..narity + 1 { self.registers[i] = self.heap[a + i].as_addr(a + i); } @@ -1658,22 +1582,17 @@ impl MachineState { return None; } } - Addr::Con(h) => - match &self.heap[h] { - HeapCellValue::Atom(ref name, _) => { - (name.clone(), 0) - } - _ => { - self.fail = true; - return None; - } + Addr::Con(h) => match &self.heap[h] { + HeapCellValue::Atom(ref name, _) => (name.clone(), 0), + _ => { + self.fail = true; + return None; } + }, Addr::HeapCell(_) | Addr::StackCell(_, _) => { let stub = MachineError::functor_stub(clause_name!("call"), arity + 1); - let instantiation_error = self.error_form( - MachineError::instantiation_error(), - stub, - ); + let instantiation_error = + self.error_form(MachineError::instantiation_error(), stub); self.throw_exception(instantiation_error); return None; @@ -1693,27 +1612,19 @@ impl MachineState { Some((name, arity + narity - 1)) } - pub(super) - fn unwind_stack(&mut self) { + pub(super) fn unwind_stack(&mut self) { self.b = self.block; self.fail = true; } - pub(crate) - fn is_cyclic_term(&self, addr: Addr) -> bool { + pub(crate) fn is_cyclic_term(&self, addr: Addr) -> bool { let mut seen = IndexSet::new(); let mut fail = false; let mut iter = self.pre_order_iter(addr); - let is_composite = |addr: &Addr| { - match *addr { - Addr::Str(_) | Addr::Lis(_) | Addr::PStrLocation(..) => { - true - } - _ => { - false - } - } + let is_composite = |addr: &Addr| match *addr { + Addr::Str(_) | Addr::Lis(_) | Addr::PStrLocation(..) => true, + _ => false, }; loop { @@ -1737,56 +1648,49 @@ impl MachineState { } // arg(+N, +Term, ?Arg) - pub(super) - fn try_arg(&mut self) -> CallResult { + pub(super) fn try_arg(&mut self) -> CallResult { let stub = MachineError::functor_stub(clause_name!("arg"), 3); let n = self.store(self.deref(self[temp_v!(1)])); match n { - Addr::HeapCell(_) | Addr::StackCell(..) => { // 8.5.2.3 a) - return Err(self.error_form(MachineError::instantiation_error(), stub)) + Addr::HeapCell(_) | Addr::StackCell(..) => { + // 8.5.2.3 a) + return Err(self.error_form(MachineError::instantiation_error(), stub)); } addr => { - let n = - match Number::try_from((addr, &self.heap)) { - Ok(Number::Fixnum(n)) => Integer::from(n), - Ok(Number::Integer(n)) => Integer::from(n.as_ref()), - _ => { - return Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - addr, - ), - stub, - )); - } - }; + let n = match Number::try_from((addr, &self.heap)) { + Ok(Number::Fixnum(n)) => Integer::from(n), + Ok(Number::Integer(n)) => Integer::from(n.as_ref()), + _ => { + return Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, addr), + stub, + )); + } + }; - if n < 0 { // 8.5.2.3 e) + if n < 0 { + // 8.5.2.3 e) let n = Number::from(n); - let dom_err = MachineError::domain_error( - DomainErrorType::NotLessThanZero, - n, - ); + let dom_err = MachineError::domain_error(DomainErrorType::NotLessThanZero, n); return Err(self.error_form(dom_err, stub)); } - let n = - match n.to_usize() { - Some(n) => n, - None => { - self.fail = true; - return Ok(()); - } - }; + let n = match n.to_usize() { + Some(n) => n, + None => { + self.fail = true; + return Ok(()); + } + }; let term = self.store(self.deref(self[temp_v!(2)])); match term { - Addr::HeapCell(_) | Addr::StackCell(..) | Addr::AttrVar(_) => { // 8.5.2.3 b) - return Err(self.error_form(MachineError::instantiation_error(), stub)) + Addr::HeapCell(_) | Addr::StackCell(..) | Addr::AttrVar(_) => { + // 8.5.2.3 b) + return Err(self.error_form(MachineError::instantiation_error(), stub)); } Addr::Str(o) => match self.heap.clone(o) { HeapCellValue::NamedStr(arity, _, _) if 1 <= n && n <= arity => { @@ -1814,7 +1718,7 @@ impl MachineState { let a3 = self[temp_v!(3)]; let h_a = if let HeapCellValue::PartialString(ref pstr, _) = &self.heap[h] { - if let Some(c) = pstr.range_from(offset ..).next() { + if let Some(c) = pstr.range_from(offset..).next() { if n == 1 { Addr::Char(c) } else { @@ -1832,15 +1736,12 @@ impl MachineState { self.fail = true; } } - _ => { // 8.5.2.3 d) + _ => { + // 8.5.2.3 d) return Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Compound, - term, - ), + MachineError::type_error(self.heap.h(), ValidType::Compound, term), stub, - )) + )); } } } @@ -1865,8 +1766,7 @@ impl MachineState { self.p += 1; } - pub(super) - fn compare_term(&mut self, qt: CompareTermQT) { + pub(super) fn compare_term(&mut self, qt: CompareTermQT) { let a1 = self[temp_v!(1)]; let a2 = self[temp_v!(2)]; @@ -1890,8 +1790,7 @@ impl MachineState { } // returns true on failure. - pub(super) - fn eq_test(&self, a1: Addr, a2: Addr) -> bool { + pub(super) fn eq_test(&self, a1: Addr, a2: Addr) -> bool { let mut iter = self.zipped_acyclic_pre_order_iter(a1, a2); while let Some((v1, v2)) = iter.next() { @@ -1909,8 +1808,7 @@ impl MachineState { unreachable!() } } - (Addr::PStrLocation(..), Addr::Lis(_)) | - (Addr::Lis(_), Addr::PStrLocation(..)) => { + (Addr::PStrLocation(..), Addr::Lis(_)) | (Addr::Lis(_), Addr::PStrLocation(..)) => { continue; } (pstr1 @ Addr::PStrLocation(..), pstr2 @ Addr::PStrLocation(..)) => { @@ -1939,40 +1837,32 @@ impl MachineState { (Addr::Lis(_), Addr::Lis(_)) => { continue; } - (Addr::Con(h1), Addr::Con(h2)) => { - match (&self.heap[h1], &self.heap[h2]) { - ( - &HeapCellValue::Atom(ref n1, ref spec_1), - &HeapCellValue::Atom(ref n2, ref spec_2), - ) => { - if n1 != n2 || spec_1 != spec_2 { - return true; - } - } - ( - &HeapCellValue::DBRef(ref db_ref_1), - &HeapCellValue::DBRef(ref db_ref_2), - ) => { - if db_ref_1 != db_ref_2 { - return true; - } - } - ( - v1, - v2, - ) => { - if let Ok(n1) = Number::try_from(v1) { - if let Ok(n2) = Number::try_from(v2) { - if n1 == n2 { - continue; - } - } - } - + (Addr::Con(h1), Addr::Con(h2)) => match (&self.heap[h1], &self.heap[h2]) { + ( + &HeapCellValue::Atom(ref n1, ref spec_1), + &HeapCellValue::Atom(ref n2, ref spec_2), + ) => { + if n1 != n2 || spec_1 != spec_2 { return true; } } - } + (&HeapCellValue::DBRef(ref db_ref_1), &HeapCellValue::DBRef(ref db_ref_2)) => { + if db_ref_1 != db_ref_2 { + return true; + } + } + (v1, v2) => { + if let Ok(n1) = Number::try_from(v1) { + if let Ok(n2) = Number::try_from(v2) { + if n1 == n2 { + continue; + } + } + } + + return true; + } + }, (Addr::Con(h), Addr::Char(c)) | (Addr::Char(c), Addr::Con(h)) => { match &self.heap[h] { &HeapCellValue::Atom(ref name, _) if name.is_char() => { @@ -2007,8 +1897,7 @@ impl MachineState { iter.first_to_expire != Ordering::Equal } - pub(super) - fn compare_term_test(&self, a1: &Addr, a2: &Addr) -> Option { + pub(super) fn compare_term_test(&self, a1: &Addr, a2: &Addr) -> Option { let mut iter = self.zipped_acyclic_pre_order_iter(*a1, *a2); while let Some((v1, v2)) = iter.next() { @@ -2039,294 +1928,224 @@ impl MachineState { unreachable!() } } - Some(TermOrderCategory::Integer) => { - match (v1, v2) { - ( - Addr::Con(h1), - Addr::Con(h2), - ) => { - if let Ok(n1) = Number::try_from(&self.heap[h1]) { - if let Ok(n2) = Number::try_from(&self.heap[h2]) { - if n1 != n2 { - return Some(n1.cmp(&n2)); - } - } else { - unreachable!() - } - } else { - unreachable!() - } - } - ( - Addr::Con(h1), - v2, - ) => { - if let Ok(n1) = Number::try_from(&self.heap[h1]) { - if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(v2)) { - if n1 != n2 { - return Some(n1.cmp(&n2)); - } - } else { - unreachable!() - } - } else { - unreachable!() - } - } - ( - v1, - Addr::Con(h2), - ) => { - if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(v1)) { - if let Ok(n2) = Number::try_from(&self.heap[h2]) { - if n1 != n2 { - return Some(n1.cmp(&n2)); - } - } else { - unreachable!() - } - } else { - unreachable!() - } - } - (v1, v2) => { - if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(v1)) { - if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(v2)) { - if n1 != n2 { - return Some(n1.cmp(&n2)); - } - } else { - unreachable!() + Some(TermOrderCategory::Integer) => match (v1, v2) { + (Addr::Con(h1), Addr::Con(h2)) => { + if let Ok(n1) = Number::try_from(&self.heap[h1]) { + if let Ok(n2) = Number::try_from(&self.heap[h2]) { + if n1 != n2 { + return Some(n1.cmp(&n2)); } } else { unreachable!() } + } else { + unreachable!() } } - } - Some(TermOrderCategory::Atom) => { - match (v1, v2) { - ( - Addr::Con(h1), - Addr::Con(h2), - ) => { - if let HeapCellValue::Atom(ref n1, _) = &self.heap[h1] { - if let HeapCellValue::Atom(ref n2, _) = &self.heap[h2] { - if n1 != n2 { - return Some(n1.cmp(&n2)); - } - } else { - unreachable!() + (Addr::Con(h1), v2) => { + if let Ok(n1) = Number::try_from(&self.heap[h1]) { + if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(v2)) { + if n1 != n2 { + return Some(n1.cmp(&n2)); } } else { unreachable!() } - } - ( - Addr::Con(h1), - Addr::Char(c), - ) => { - if let HeapCellValue::Atom(ref n1, _) = &self.heap[h1] { - if n1.is_char() { - if n1.as_str().chars().next() != Some(c) { - return Some(n1.as_str().chars().next().cmp(&Some(c))); - } - } else { - return Some(Ordering::Greater); - } - } else { - unreachable!() - } - } - ( - Addr::Char(c), - Addr::Con(h1), - ) => { - if let HeapCellValue::Atom(ref n1, _) = &self.heap[h1] { - if n1.is_char() { - if n1.as_str().chars().next() != Some(c) { - return Some(Some(c).cmp(&n1.as_str().chars().next())); - } - } else { - return Some(Ordering::Less); - } - } else { - unreachable!() - } - } - ( - Addr::EmptyList, - Addr::Con(h), - ) => { - if let HeapCellValue::Atom(ref n1, _) = &self.heap[h] { - if "[]" != n1.as_str() { - return Some("[]".cmp(n1.as_str())); - } - } else { - unreachable!() - } - } - ( - Addr::Con(h), - Addr::EmptyList, - ) => { - if let HeapCellValue::Atom(ref n1, _) = &self.heap[h] { - if "[]" != n1.as_str() { - return Some(n1.as_str().cmp("[]")); - } - } else { - unreachable!() - } - } - ( - Addr::Char(c1), - Addr::Char(c2), - ) => { - if c1 != c2 { - return Some(c1.cmp(&c2)); - } - } - ( - Addr::Char(c), - Addr::EmptyList, - ) => { - return if c == '[' { - Some(Ordering::Less) - } else { - Some(c.cmp(&'[')) - }; - } - ( - Addr::EmptyList, - Addr::Char(c), - ) => { - return if c == '[' { - Some(Ordering::Greater) - } else { - Some('['.cmp(&c)) - }; - } - ( - Addr::EmptyList, - Addr::EmptyList, - ) => { - } - _ => { - return None; + } else { + unreachable!() } } - } - Some(TermOrderCategory::Compound) => { - match (v1, v2) { - ( - Addr::Lis(_), - Addr::Lis(_), - ) => { - } - ( - pstr1 @ Addr::PStrLocation(..), - pstr2 @ Addr::PStrLocation(..), - ) => { - let mut i1 = self.heap_pstr_iter(pstr1); - let mut i2 = self.heap_pstr_iter(pstr2); - - let ordering = compare_pstr_prefixes(&mut i1, &mut i2); - - if let Some(ordering) = ordering { - if ordering != Ordering::Equal { - return Some(ordering); - } - } else { - let (lstack, rstack) = iter.stack(); - - lstack.pop(); - lstack.pop(); - - rstack.pop(); - rstack.pop(); - - lstack.push(i1.focus()); - rstack.push(i2.focus()); - } - } - ( - Addr::Str(h1), - Addr::Str(h2), - ) => { - if let HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[h1] { - if let HeapCellValue::NamedStr(a2, ref n2, _) = &self.heap[h2] { - if a1 != a2 || n1.as_str() != n2.as_str() { - return Some(a1.cmp(&a2).then_with(|| n1.as_str().cmp(n2.as_str()))); - } - } else { - unreachable!() + (v1, Addr::Con(h2)) => { + if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(v1)) { + if let Ok(n2) = Number::try_from(&self.heap[h2]) { + if n1 != n2 { + return Some(n1.cmp(&n2)); } } else { unreachable!() } - } - ( - Addr::Lis(_), - Addr::PStrLocation(..), - ) | - ( - Addr::PStrLocation(..), - Addr::Lis(_), - ) => { - } - ( - Addr::Lis(_), - Addr::Str(s), - ) => { - if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { - if a1 != 2 || n1.as_str() != "." { - return Some(a1.cmp(&2).then_with(|| n1.as_str().cmp("."))); - } - } else { - unreachable!() - } - } - ( - Addr::Str(s), - Addr::Lis(_), - ) => { - if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { - if a1 != 2 || n1.as_str() != "." { - return Some(2.cmp(&a1).then_with(|| ".".cmp(n1.as_str()))); - } - } else { - unreachable!() - } - } - ( - Addr::PStrLocation(..), - Addr::Str(s), - ) => { - if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { - if a1 != 2 || n1.as_str() != "." { - return Some(a1.cmp(&2).then_with(|| n1.as_str().cmp("."))); - } - } else { - unreachable!() - } - } - ( - Addr::Str(s), - Addr::PStrLocation(..), - ) => { - if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { - if a1 != 2 || n1.as_str() != "." { - return Some(2.cmp(&a1).then_with(|| ".".cmp(n1.as_str()))); - } - } else { - unreachable!() - } - } - _ => { - return None; + } else { + unreachable!() } } - } + (v1, v2) => { + if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(v1)) { + if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(v2)) { + if n1 != n2 { + return Some(n1.cmp(&n2)); + } + } else { + unreachable!() + } + } else { + unreachable!() + } + } + }, + Some(TermOrderCategory::Atom) => match (v1, v2) { + (Addr::Con(h1), Addr::Con(h2)) => { + if let HeapCellValue::Atom(ref n1, _) = &self.heap[h1] { + if let HeapCellValue::Atom(ref n2, _) = &self.heap[h2] { + if n1 != n2 { + return Some(n1.cmp(&n2)); + } + } else { + unreachable!() + } + } else { + unreachable!() + } + } + (Addr::Con(h1), Addr::Char(c)) => { + if let HeapCellValue::Atom(ref n1, _) = &self.heap[h1] { + if n1.is_char() { + if n1.as_str().chars().next() != Some(c) { + return Some(n1.as_str().chars().next().cmp(&Some(c))); + } + } else { + return Some(Ordering::Greater); + } + } else { + unreachable!() + } + } + (Addr::Char(c), Addr::Con(h1)) => { + if let HeapCellValue::Atom(ref n1, _) = &self.heap[h1] { + if n1.is_char() { + if n1.as_str().chars().next() != Some(c) { + return Some(Some(c).cmp(&n1.as_str().chars().next())); + } + } else { + return Some(Ordering::Less); + } + } else { + unreachable!() + } + } + (Addr::EmptyList, Addr::Con(h)) => { + if let HeapCellValue::Atom(ref n1, _) = &self.heap[h] { + if "[]" != n1.as_str() { + return Some("[]".cmp(n1.as_str())); + } + } else { + unreachable!() + } + } + (Addr::Con(h), Addr::EmptyList) => { + if let HeapCellValue::Atom(ref n1, _) = &self.heap[h] { + if "[]" != n1.as_str() { + return Some(n1.as_str().cmp("[]")); + } + } else { + unreachable!() + } + } + (Addr::Char(c1), Addr::Char(c2)) => { + if c1 != c2 { + return Some(c1.cmp(&c2)); + } + } + (Addr::Char(c), Addr::EmptyList) => { + return if c == '[' { + Some(Ordering::Less) + } else { + Some(c.cmp(&'[')) + }; + } + (Addr::EmptyList, Addr::Char(c)) => { + return if c == '[' { + Some(Ordering::Greater) + } else { + Some('['.cmp(&c)) + }; + } + (Addr::EmptyList, Addr::EmptyList) => {} + _ => { + return None; + } + }, + Some(TermOrderCategory::Compound) => match (v1, v2) { + (Addr::Lis(_), Addr::Lis(_)) => {} + (pstr1 @ Addr::PStrLocation(..), pstr2 @ Addr::PStrLocation(..)) => { + let mut i1 = self.heap_pstr_iter(pstr1); + let mut i2 = self.heap_pstr_iter(pstr2); + + let ordering = compare_pstr_prefixes(&mut i1, &mut i2); + + if let Some(ordering) = ordering { + if ordering != Ordering::Equal { + return Some(ordering); + } + } else { + let (lstack, rstack) = iter.stack(); + + lstack.pop(); + lstack.pop(); + + rstack.pop(); + rstack.pop(); + + lstack.push(i1.focus()); + rstack.push(i2.focus()); + } + } + (Addr::Str(h1), Addr::Str(h2)) => { + if let HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[h1] { + if let HeapCellValue::NamedStr(a2, ref n2, _) = &self.heap[h2] { + if a1 != a2 || n1.as_str() != n2.as_str() { + return Some( + a1.cmp(&a2).then_with(|| n1.as_str().cmp(n2.as_str())), + ); + } + } else { + unreachable!() + } + } else { + unreachable!() + } + } + (Addr::Lis(_), Addr::PStrLocation(..)) + | (Addr::PStrLocation(..), Addr::Lis(_)) => {} + (Addr::Lis(_), Addr::Str(s)) => { + if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { + if a1 != 2 || n1.as_str() != "." { + return Some(a1.cmp(&2).then_with(|| n1.as_str().cmp("."))); + } + } else { + unreachable!() + } + } + (Addr::Str(s), Addr::Lis(_)) => { + if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { + if a1 != 2 || n1.as_str() != "." { + return Some(2.cmp(&a1).then_with(|| ".".cmp(n1.as_str()))); + } + } else { + unreachable!() + } + } + (Addr::PStrLocation(..), Addr::Str(s)) => { + if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { + if a1 != 2 || n1.as_str() != "." { + return Some(a1.cmp(&2).then_with(|| n1.as_str().cmp("."))); + } + } else { + unreachable!() + } + } + (Addr::Str(s), Addr::PStrLocation(..)) => { + if let &HeapCellValue::NamedStr(a1, ref n1, _) = &self.heap[s] { + if a1 != 2 || n1.as_str() != "." { + return Some(2.cmp(&a1).then_with(|| ".".cmp(n1.as_str()))); + } + } else { + unreachable!() + } + } + _ => { + return None; + } + }, None => { return None; } @@ -2336,16 +2155,14 @@ impl MachineState { Some(iter.first_to_expire) } - pub(super) - fn reset_block(&mut self, addr: Addr) { + pub(super) fn reset_block(&mut self, addr: Addr) { match self.store(addr) { Addr::Usize(b) => self.block = b, _ => self.fail = true, }; } - pub(super) - fn execute_inlined(&mut self, inlined: &InlinedClauseType) { + pub(super) fn execute_inlined(&mut self, inlined: &InlinedClauseType) { match inlined { &InlinedClauseType::CompareNumber(cmp, ref at_1, ref at_2) => { let n1 = try_or_fail!(self, self.get_number(at_1)); @@ -2357,12 +2174,13 @@ impl MachineState { let d = self.store(self.deref(self[r1])); match d { - Addr::Con(h) => + Addr::Con(h) => { if let HeapCellValue::Atom(..) = &self.heap[h] { self.p += 1; } else { self.fail = true; - }, + } + } Addr::Char(_) => self.p += 1, Addr::EmptyList => self.p += 1, _ => self.fail = true, @@ -2372,12 +2190,12 @@ impl MachineState { let d = self.store(self.deref(self[r1])); match d { - Addr::Char(_) | - Addr::Con(_) | - Addr::EmptyList | - Addr::Fixnum(_) | - Addr::Float(_) | - Addr::Usize(_) => self.p += 1, + Addr::Char(_) + | Addr::Con(_) + | Addr::EmptyList + | Addr::Fixnum(_) + | Addr::Float(_) + | Addr::Usize(_) => self.p += 1, _ => self.fail = true, }; } @@ -2419,29 +2237,27 @@ impl MachineState { _ => self.fail = true, }; } - &InlinedClauseType::IsNumber(r1) => { - match self.store(self.deref(self[r1])) { - Addr::Float(_) => self.p += 1, - d => match Number::try_from((d, &self.heap)) { - Ok(Number::Fixnum(_)) => { + &InlinedClauseType::IsNumber(r1) => match self.store(self.deref(self[r1])) { + Addr::Float(_) => self.p += 1, + d => match Number::try_from((d, &self.heap)) { + Ok(Number::Fixnum(_)) => { + self.p += 1; + } + Ok(Number::Integer(_)) => { + self.p += 1; + } + Ok(Number::Rational(n)) => { + if n.denom() == &1 { self.p += 1; - } - Ok(Number::Integer(_)) => { - self.p += 1; - } - Ok(Number::Rational(n)) => { - if n.denom() == &1 { - self.p += 1; - } else { - self.fail = true; - } - } - _ => { + } else { self.fail = true; } } - } - } + _ => { + self.fail = true; + } + }, + }, &InlinedClauseType::IsRational(r1) => { let d = self.store(self.deref(self[r1])); @@ -2495,11 +2311,7 @@ impl MachineState { self.try_functor_unify_components(name, arity); } - fn try_functor_unify_components( - &mut self, - name: Addr, - arity: usize, - ) { + fn try_functor_unify_components(&mut self, name: Addr, arity: usize) { let a2 = self[temp_v!(2)]; let a3 = self[temp_v!(3)]; @@ -2529,20 +2341,20 @@ impl MachineState { let f_a = if name.as_str() == "." && arity == 2 { Addr::Lis(self.heap.h()) } else { - self.heap.to_unifiable(HeapCellValue::NamedStr(arity, name, spec)) + self.heap + .to_unifiable(HeapCellValue::NamedStr(arity, name, spec)) }; let h = self.heap.h(); - for i in 0 .. arity { + for i in 0..arity { self.heap.push(HeapCellValue::Addr(Addr::HeapCell(h + i))); } self.bind(r, f_a); } - pub(super) - fn try_functor(&mut self, op_dir: &OpDir) -> CallResult { + pub(super) fn try_functor(&mut self, op_dir: &OpDir) -> CallResult { let stub = MachineError::functor_stub(clause_name!("functor"), 3); let a1 = self.store(self.deref(self[temp_v!(1)])); @@ -2550,18 +2362,17 @@ impl MachineState { Addr::Stream(_) => { self.fail = true; } - Addr::Char(_) | Addr::Con(_) | Addr::Fixnum(_) | - Addr::Float(_) | Addr::EmptyList | Addr::Usize(_) => { + Addr::Char(_) + | Addr::Con(_) + | Addr::Fixnum(_) + | Addr::Float(_) + | Addr::EmptyList + | Addr::Usize(_) => { self.try_functor_unify_components(a1, 0); } Addr::Str(o) => match self.heap.clone(o) { HeapCellValue::NamedStr(arity, name, spec) => { - let spec = fetch_op_spec_from_existing( - name.clone(), - arity, - spec, - &op_dir, - ); + let spec = fetch_op_spec_from_existing(name.clone(), arity, spec, &op_dir); self.try_functor_compound_case(name, arity, spec) } @@ -2570,17 +2381,12 @@ impl MachineState { } }, Addr::Lis(_) | Addr::PStrLocation(..) => { - let spec = fetch_op_spec_from_existing( - clause_name!("."), - 2, - None, - &op_dir, - ); + let spec = fetch_op_spec_from_existing(clause_name!("."), 2, None, &op_dir); self.try_functor_compound_case(clause_name!("."), 2, spec) } Addr::AttrVar(..) | Addr::HeapCell(_) | Addr::StackCell(..) => { - let name = self.store(self.deref(self[temp_v!(2)])); + let name = self.store(self.deref(self[temp_v!(2)])); let arity = self.store(self.deref(self[temp_v!(3)])); if name.is_ref() || arity.is_ref() { @@ -2588,35 +2394,22 @@ impl MachineState { return Err(self.error_form(MachineError::instantiation_error(), stub)); } - let arity = - match Number::try_from((arity, &self.heap)) { - Ok(Number::Fixnum(n)) => Some(n), - Ok(Number::Integer(n)) => n.to_isize(), - Ok(Number::Rational(n)) - if n.denom() == &1 => { - n.numer().to_isize() - }, - _ => - match arity { - arity => { - return Err( - self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - arity, - ), - stub, - ) - ); - } - } - }; + let arity = match Number::try_from((arity, &self.heap)) { + Ok(Number::Fixnum(n)) => Some(n), + Ok(Number::Integer(n)) => n.to_isize(), + Ok(Number::Rational(n)) if n.denom() == &1 => n.numer().to_isize(), + _ => match arity { + arity => { + return Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, arity), + stub, + )); + } + }, + }; let arity = match arity { - Some(arity) => { - arity - } + Some(arity) => arity, None => { self.fail = true; return Ok(()); @@ -2630,17 +2423,22 @@ impl MachineState { } else if arity < 0 { // 8.5.1.3 g) let arity = Number::Integer(Rc::new(Integer::from(arity))); - let dom_err = MachineError::domain_error( - DomainErrorType::NotLessThanZero, - arity, - ); + let dom_err = + MachineError::domain_error(DomainErrorType::NotLessThanZero, arity); return Err(self.error_form(dom_err, stub)); } match name { - Addr::Char(_) | Addr::Con(_) | Addr::Fixnum(_) | Addr::Float(_) | - Addr::EmptyList | Addr::PStrLocation(..) | Addr::Usize(_) if arity == 0 => { + Addr::Char(_) + | Addr::Con(_) + | Addr::Fixnum(_) + | Addr::Float(_) + | Addr::EmptyList + | Addr::PStrLocation(..) + | Addr::Usize(_) + if arity == 0 => + { self.unify(a1, name); } Addr::Con(h) => { @@ -2655,13 +2453,9 @@ impl MachineState { } else { // 8.5.1.3 e) return Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Atom, - name, - ), + MachineError::type_error(self.heap.h(), ValidType::Atom, name), stub, - )) + )); } } Addr::Char(c) => { @@ -2689,8 +2483,7 @@ impl MachineState { Ok(()) } - pub(super) - fn term_dedup(&self, list: &mut Vec) { + pub(super) fn term_dedup(&self, list: &mut Vec) { let mut result = vec![]; for a2 in list.iter() { @@ -2706,20 +2499,14 @@ impl MachineState { *list = result; } - - pub(super) - fn integers_to_bytevec( - &self, - r: RegType, - caller: MachineStub, - ) -> Vec { - + pub(super) fn integers_to_bytevec(&self, r: RegType, caller: MachineStub) -> Vec { let mut bytes: Vec = Vec::new(); match self.try_from_list(r, caller) { - Err(_) => { unreachable!() } + Err(_) => { + unreachable!() + } Ok(addrs) => { - for addr in addrs { let addr = self.store(self.deref(addr)); @@ -2729,20 +2516,19 @@ impl MachineState { Ok(b) => { bytes.push(b); } - Err(_) => { } + Err(_) => {} } continue; } Ok(Number::Integer(n)) => { if let Some(b) = n.to_u8() { - bytes.push(b); + bytes.push(b); } continue; } - _ => { - } + _ => {} } } } @@ -2750,9 +2536,7 @@ impl MachineState { bytes } - - pub(super) - fn try_from_list( + pub(super) fn try_from_list( &self, r: RegType, caller: MachineStub, @@ -2760,24 +2544,16 @@ impl MachineState { let a1 = self.store(self.deref(self[r])); match a1 { - Addr::Lis(l) => { - self.try_from_inner_list(vec![], l, caller, a1) - } - Addr::PStrLocation(h, n) => { - self.try_from_partial_string(vec![], h, n, caller, a1) - } + Addr::Lis(l) => self.try_from_inner_list(vec![], l, caller, a1), + Addr::PStrLocation(h, n) => self.try_from_partial_string(vec![], h, n, caller, a1), Addr::AttrVar(_) | Addr::HeapCell(_) | Addr::StackCell(..) => { Err(self.error_form(MachineError::instantiation_error(), caller)) } - Addr::EmptyList => { - Ok(vec![]) - } - _ => { - Err(self.error_form( - MachineError::type_error(self.heap.h(), ValidType::List, a1), - caller, - )) - } + Addr::EmptyList => Ok(vec![]), + _ => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::List, a1), + caller, + )), } } @@ -2793,31 +2569,27 @@ impl MachineState { loop { match &self.heap[l] { - HeapCellValue::Addr(ref addr) => - match self.store(self.deref(*addr)) { - Addr::Lis(hcp) => { - result.push(self.heap[hcp].as_addr(hcp)); - l = hcp + 1; - } - Addr::PStrLocation(h, n) => { - return self.try_from_partial_string(result, h, n, caller, a1); - } - Addr::EmptyList => { - break; - } - Addr::AttrVar(_) | Addr::HeapCell(_) | Addr::StackCell(..) => { - return Err(self.error_form( - MachineError::instantiation_error(), - caller, - )) - } - _ => { - return Err(self.error_form( - MachineError::type_error(self.heap.h(), ValidType::List, a1), - caller, - )) - } - }, + HeapCellValue::Addr(ref addr) => match self.store(self.deref(*addr)) { + Addr::Lis(hcp) => { + result.push(self.heap[hcp].as_addr(hcp)); + l = hcp + 1; + } + Addr::PStrLocation(h, n) => { + return self.try_from_partial_string(result, h, n, caller, a1); + } + Addr::EmptyList => { + break; + } + Addr::AttrVar(_) | Addr::HeapCell(_) | Addr::StackCell(..) => { + return Err(self.error_form(MachineError::instantiation_error(), caller)) + } + _ => { + return Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::List, a1), + caller, + )) + } + }, _ => { return Err(self.error_form( MachineError::type_error(self.heap.h(), ValidType::List, a1), @@ -2840,7 +2612,7 @@ impl MachineState { ) -> Result, MachineStub> { loop { if let &HeapCellValue::PartialString(ref pstr, has_tail) = &self.heap[h] { - chars.extend(pstr.range_from(n ..).map(Addr::Char)); + chars.extend(pstr.range_from(n..).map(Addr::Char)); if !has_tail { return Ok(chars); @@ -2882,39 +2654,27 @@ impl MachineState { Addr::HeapCell(_) | Addr::StackCell(..) => { Err(self.error_form(MachineError::instantiation_error(), stub)) } - Addr::Str(s) => { - match self.heap.clone(s) { - HeapCellValue::NamedStr(2, ref name, Some(_)) - if *name == clause_name!("-") => { - Ok(Addr::HeapCell(s + 1)) - } - _ => { - Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Pair, - self.heap[s].as_addr(s), - ), - stub, - )) - } + Addr::Str(s) => match self.heap.clone(s) { + HeapCellValue::NamedStr(2, ref name, Some(_)) if *name == clause_name!("-") => { + Ok(Addr::HeapCell(s + 1)) } - } - a => { - Err(self.error_form( + _ => Err(self.error_form( MachineError::type_error( self.heap.h(), ValidType::Pair, - a, + self.heap[s].as_addr(s), ), stub, - )) - } + )), + }, + a => Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Pair, a), + stub, + )), } } - pub(super) - fn copy_term(&mut self, attr_var_policy: AttrVarPolicy) { + pub(super) fn copy_term(&mut self, attr_var_policy: AttrVarPolicy) { let old_h = self.heap.h(); let a1 = self[temp_v!(1)]; @@ -2926,8 +2686,7 @@ impl MachineState { } // returns true on failure. - pub(super) - fn structural_eq_test(&self) -> bool { + pub(super) fn structural_eq_test(&self) -> bool { let a1 = self[temp_v!(1)]; let a2 = self[temp_v!(2)]; @@ -2947,21 +2706,13 @@ impl MachineState { | ( HeapCellValue::Addr(Addr::PStrLocation(..)), HeapCellValue::Addr(Addr::Lis(_)), - ) => { - } - ( - HeapCellValue::NamedStr(ar1, n1, _), - HeapCellValue::NamedStr(ar2, n2, _), - ) => { + ) => {} + (HeapCellValue::NamedStr(ar1, n1, _), HeapCellValue::NamedStr(ar2, n2, _)) => { if ar1 != ar2 || n1 != n2 { return true; } } - ( - HeapCellValue::Addr(Addr::Lis(_)), - HeapCellValue::Addr(Addr::Lis(_)), - ) => { - } + (HeapCellValue::Addr(Addr::Lis(_)), HeapCellValue::Addr(Addr::Lis(_))) => {} ( &HeapCellValue::Addr(v1 @ Addr::HeapCell(_)), &HeapCellValue::Addr(v2 @ Addr::AttrVar(_)), @@ -2997,19 +2748,18 @@ impl MachineState { | ( &HeapCellValue::Addr(v1 @ Addr::StackCell(..)), &HeapCellValue::Addr(v2 @ Addr::HeapCell(_)), - ) => - match (var_pairs.get(&v1), var_pairs.get(&v2)) { - (Some(ref v2_p), Some(ref v1_p)) if **v1_p == v1 && **v2_p == v2 => { - continue; - } - (Some(_), _) | (_, Some(_)) => { - return true; - } - (None, None) => { - var_pairs.insert(v1, v2); - var_pairs.insert(v2, v1); - } - }, + ) => match (var_pairs.get(&v1), var_pairs.get(&v2)) { + (Some(ref v2_p), Some(ref v1_p)) if **v1_p == v1 && **v2_p == v2 => { + continue; + } + (Some(_), _) | (_, Some(_)) => { + return true; + } + (None, None) => { + var_pairs.insert(v1, v2); + var_pairs.insert(v2, v1); + } + }, ( HeapCellValue::PartialString(ref pstr1, has_tail_1), HeapCellValue::PartialString(ref pstr2, has_tail_2), @@ -3018,8 +2768,8 @@ impl MachineState { return true; } - let pstr1_iter = pstr1.range_from(0 ..); - let pstr2_iter = pstr2.range_from(0 ..); + let pstr1_iter = pstr1.range_from(0..); + let pstr2_iter = pstr2.range_from(0..); for (c1, c2) in pstr1_iter.zip(pstr2_iter) { if c1 != c2 { @@ -3030,8 +2780,7 @@ impl MachineState { ( HeapCellValue::Addr(Addr::PStrLocation(..)), HeapCellValue::Addr(Addr::PStrLocation(..)), - ) => { - } + ) => {} ( HeapCellValue::Atom(ref n1, ref spec_1), HeapCellValue::Atom(ref n2, ref spec_2), @@ -3040,18 +2789,12 @@ impl MachineState { return true; } } - ( - HeapCellValue::DBRef(ref db_ref_1), - HeapCellValue::DBRef(ref db_ref_2), - ) => { + (HeapCellValue::DBRef(ref db_ref_1), HeapCellValue::DBRef(ref db_ref_2)) => { if db_ref_1 != db_ref_2 { return true; } } - ( - v1, - v2, - ) => { + (v1, v2) => { if let Ok(n1) = Number::try_from(v1) { if let Ok(n2) = Number::try_from(v2) { if n1 != n2 { @@ -3065,10 +2808,7 @@ impl MachineState { } match (v1, v2) { - ( - HeapCellValue::Addr(a1), - HeapCellValue::Addr(a2), - ) => { + (HeapCellValue::Addr(a1), HeapCellValue::Addr(a2)) => { if a1 != a2 { return true; } @@ -3085,8 +2825,7 @@ impl MachineState { } // returns true on failure. - pub(super) - fn ground_test(&self) -> bool { + pub(super) fn ground_test(&self) -> bool { let a = self.store(self.deref(self[temp_v!(1)])); for v in self.acyclic_pre_order_iter(a) { @@ -3101,33 +2840,30 @@ impl MachineState { false } - pub(super) - fn setup_built_in_call(&mut self, ct: BuiltInClauseType) { + pub(super) fn setup_built_in_call(&mut self, ct: BuiltInClauseType) { self.num_of_args = ct.arity(); self.b0 = self.b; self.p = CodePtr::BuiltInClause(ct, self.p.local()); } - pub(super) - fn allocate(&mut self, num_cells: usize) { + pub(super) fn allocate(&mut self, num_cells: usize) { let e = self.stack.allocate_and_frame(num_cells); let and_frame = self.stack.index_and_frame_mut(e); - and_frame.prelude.e = self.e; + and_frame.prelude.e = self.e; and_frame.prelude.cp = self.cp; self.e = e; self.p += 1; } - pub(super) - fn deallocate(&mut self) { + pub(super) fn deallocate(&mut self) { let e = self.e; let frame = self.stack.index_and_frame(e); self.cp = frame.prelude.cp; - self.e = frame.prelude.e; + self.e = frame.prelude.e; if e > self.b { self.stack.truncate(e); @@ -3157,17 +2893,22 @@ impl MachineState { lco: bool, use_default_cp: bool, ) { - let interrupted = INTERRUPT.load(std::sync::atomic::Ordering::Relaxed); + let interrupted = INTERRUPT.load(std::sync::atomic::Ordering::Relaxed); - match INTERRUPT.compare_exchange(interrupted, false, std::sync::atomic::Ordering::Relaxed, std::sync::atomic::Ordering::Relaxed) { + match INTERRUPT.compare_exchange( + interrupted, + false, + std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, + ) { Ok(interruption) => { if interruption { self.throw_interrupt_exception(); return; } - }, - Err(_) => unreachable!() - } + } + Err(_) => unreachable!(), + } let mut default_call_policy: Box = Box::new(DefaultCallPolicy {}); @@ -3232,8 +2973,7 @@ impl MachineState { self.last_call = false; } - pub(super) - fn execute_ctrl_instr( + pub(super) fn execute_ctrl_instr( &mut self, indices: &mut IndexStore, code_repo: &CodeRepo, @@ -3296,18 +3036,16 @@ impl MachineState { or_frame.prelude.b = self.b; or_frame.prelude.bp = self.p.local() + 1; or_frame.prelude.tr = self.tr; - or_frame.prelude.h = self.heap.h(); + or_frame.prelude.h = self.heap.h(); or_frame.prelude.b0 = self.b0; - or_frame.prelude.attr_var_init_queue_b = - self.attr_var_init.attr_var_queue.len(); - or_frame.prelude.attr_var_init_bindings_b = - self.attr_var_init.bindings.len(); + or_frame.prelude.attr_var_init_queue_b = self.attr_var_init.attr_var_queue.len(); + or_frame.prelude.attr_var_init_bindings_b = self.attr_var_init.bindings.len(); self.b = b; - for i in 1 .. n + 1 { - self.stack.index_or_frame_mut(b)[i-1] = self.registers[i]; + for i in 1..n + 1 { + self.stack.index_or_frame_mut(b)[i - 1] = self.registers[i]; } self.hb = self.heap.h(); @@ -3322,8 +3060,7 @@ impl MachineState { }; } - pub(super) - fn execute_choice_instr( + pub(super) fn execute_choice_instr( &mut self, instr: &ChoiceInstruction, call_policy: &mut Box, @@ -3340,17 +3077,15 @@ impl MachineState { or_frame.prelude.b = self.b; or_frame.prelude.bp = self.p.local() + offset; or_frame.prelude.tr = self.tr; - or_frame.prelude.h = self.heap.h(); + or_frame.prelude.h = self.heap.h(); or_frame.prelude.b0 = self.b0; - or_frame.prelude.attr_var_init_queue_b = - self.attr_var_init.attr_var_queue.len(); - or_frame.prelude.attr_var_init_bindings_b = - self.attr_var_init.attr_var_queue.len(); + or_frame.prelude.attr_var_init_queue_b = self.attr_var_init.attr_var_queue.len(); + or_frame.prelude.attr_var_init_bindings_b = self.attr_var_init.attr_var_queue.len(); self.b = b; - for i in 1 .. n + 1 { - self.stack.index_or_frame_mut(b)[i-1] = self.registers[i]; + for i in 1..n + 1 { + self.stack.index_or_frame_mut(b)[i - 1] = self.registers[i]; } self.hb = self.heap.h(); diff --git a/src/machine/mod.rs b/src/machine/mod.rs index 6a73369e..eb9dd534 100644 --- a/src/machine/mod.rs +++ b/src/machine/mod.rs @@ -1,5 +1,8 @@ use crate::prolog_parser_rebis::ast::*; use crate::prolog_parser_rebis::tabled_rc::*; +use crate::prolog_parser_rebis::{clause_name, temp_v}; + +use crate::lazy_static::lazy_static; use crate::clause_types::*; use crate::forms::*; @@ -34,8 +37,8 @@ mod machine_state_impl; mod system_calls; //use crate::machine::attributed_variables::*; -use crate::machine::compile::*; use crate::machine::code_repo::*; +use crate::machine::compile::*; // use crate::machine::loader::*; use crate::machine::machine_errors::*; use crate::machine::machine_indices::*; @@ -45,6 +48,7 @@ use crate::machine::streams::*; use crate::indexmap::IndexMap; //use std::convert::TryFrom; +use prolog_parser_rebis::ast::ClauseName; use std::fs::File; use std::mem; use std::path::PathBuf; @@ -162,18 +166,13 @@ impl Machine { } fn load_file(&mut self, path: String, stream: Stream) { - self.machine_st[temp_v!(1)] = Addr::Stream( - self.machine_st.heap.push(HeapCellValue::Stream( - stream, - )) - ); + self.machine_st[temp_v!(1)] = + Addr::Stream(self.machine_st.heap.push(HeapCellValue::Stream(stream))); - self.machine_st[temp_v!(2)] = Addr::Con( - self.machine_st.heap.push(HeapCellValue::Atom( - clause_name!(path, self.machine_st.atom_tbl), - None, - )) - ); + self.machine_st[temp_v!(2)] = Addr::Con(self.machine_st.heap.push(HeapCellValue::Atom( + clause_name!(path, self.machine_st.atom_tbl), + None, + ))); self.run_module_predicate(clause_name!("loader"), (clause_name!("file_load"), 2)); } @@ -206,11 +205,9 @@ impl Machine { bootstrapping_compile( Stream::from(include_str!("attributed_variables.pl")), self, - ListingSource::from_file_and_path( - clause_name!("attributed_variables"), - path_buf, - ), - ).unwrap(); + ListingSource::from_file_and_path(clause_name!("attributed_variables"), path_buf), + ) + .unwrap(); let mut path_buf = current_dir(); path_buf.push("machine/project_attributes.pl"); @@ -218,11 +215,9 @@ impl Machine { bootstrapping_compile( Stream::from(include_str!("project_attributes.pl")), self, - ListingSource::from_file_and_path( - clause_name!("project_attributes"), - path_buf, - ), - ).unwrap(); + ListingSource::from_file_and_path(clause_name!("project_attributes"), path_buf), + ) + .unwrap(); if let Some(module) = self.indices.modules.get(&clause_name!("$atts")) { if let Some(code_index) = module.code_dir.get(&(clause_name!("driver"), 2)) { @@ -255,12 +250,13 @@ impl Machine { fn configure_modules(&mut self) { fn update_call_n_indices(loader: &Module, target_module: &mut Module) { - for arity in 1 .. 66 { + for arity in 1..66 { let key = (clause_name!("call"), arity); match loader.code_dir.get(&key) { Some(src_code_index) => { - let target_code_index = target_module.code_dir + let target_code_index = target_module + .code_dir .entry(key.clone()) .or_insert_with(|| CodeIndex::new(IndexPtr::Undefined)); @@ -289,10 +285,11 @@ impl Machine { builtins.module_decl.exports.push(export.clone()); } - for arity in 10 .. 66 { - builtins.module_decl.exports.push( - ModuleExport::PredicateKey((clause_name!("call"), arity)), - ); + for arity in 10..66 { + builtins + .module_decl + .exports + .push(ModuleExport::PredicateKey((clause_name!("call"), arity))); } } @@ -306,8 +303,7 @@ impl Machine { } } - pub fn new(user_input: Stream, user_output: Stream) -> Self - { + pub fn new(user_input: Stream, user_output: Stream) -> Self { use crate::ref_thread_local::RefThreadLocal; let mut wam = Machine { @@ -333,16 +329,15 @@ impl Machine { clause_name!("ops_and_meta_predicates.pl"), lib_path.clone(), ), - ).unwrap(); + ) + .unwrap(); bootstrapping_compile( Stream::from(LIBRARIES.borrow()["builtins"]), &mut wam, - ListingSource::from_file_and_path( - clause_name!("builtins.pl"), - lib_path.clone(), - ), - ).unwrap(); + ListingSource::from_file_and_path(clause_name!("builtins.pl"), lib_path.clone()), + ) + .unwrap(); if let Some(builtins) = wam.indices.modules.get(&clause_name!("builtins")) { load_module( @@ -361,11 +356,9 @@ impl Machine { bootstrapping_compile( Stream::from(include_str!("../loader.pl")), &mut wam, - ListingSource::from_file_and_path( - clause_name!("loader.pl"), - lib_path.clone(), - ), - ).unwrap(); + ListingSource::from_file_and_path(clause_name!("loader.pl"), lib_path.clone()), + ) + .unwrap(); wam.configure_modules(); @@ -391,25 +384,19 @@ impl Machine { pub fn configure_streams(&mut self) { self.user_input.options.alias = Some(clause_name!("user_input")); - self.indices.stream_aliases.insert( - clause_name!("user_input"), - self.user_input.clone(), - ); + self.indices + .stream_aliases + .insert(clause_name!("user_input"), self.user_input.clone()); - self.indices.streams.insert( - self.user_input.clone() - ); + self.indices.streams.insert(self.user_input.clone()); self.user_output.options.alias = Some(clause_name!("user_output")); - self.indices.stream_aliases.insert( - clause_name!("user_output"), - self.user_output.clone(), - ); + self.indices + .stream_aliases + .insert(clause_name!("user_output"), self.user_output.clone()); - self.indices.streams.insert( - self.user_output.clone() - ); + self.indices.streams.insert(self.user_output.clone()); } fn throw_session_error(&mut self, err: SessionError, key: PredicateKey) { @@ -508,8 +495,7 @@ impl Machine { self.machine_st.p = CodePtr::Local(p); } - pub(super) - fn run_query(&mut self) { + pub(super) fn run_query(&mut self) { while !self.machine_st.p.is_halt() { self.machine_st.query_stepper( &mut self.indices, @@ -546,26 +532,22 @@ impl MachineState { user_output: &mut Stream, ) { match instr { - &Line::Arithmetic(ref arith_instr) => { - self.execute_arith_instr(arith_instr) - } + &Line::Arithmetic(ref arith_instr) => self.execute_arith_instr(arith_instr), &Line::Choice(ref choice_instr) => { self.execute_choice_instr(choice_instr, &mut policies.call_policy) } &Line::Cut(ref cut_instr) => { self.execute_cut_instr(cut_instr, &mut policies.cut_policy) } - &Line::Control(ref control_instr) => { - self.execute_ctrl_instr( - indices, - code_repo, - &mut policies.call_policy, - &mut policies.cut_policy, - user_input, - user_output, - control_instr, - ) - } + &Line::Control(ref control_instr) => self.execute_ctrl_instr( + indices, + code_repo, + &mut policies.call_policy, + &mut policies.cut_policy, + user_input, + user_output, + control_instr, + ), &Line::Fact(ref fact_instr) => { self.execute_fact_instr(&fact_instr); self.p += 1; @@ -617,15 +599,13 @@ impl MachineState { fn check_machine_index(&mut self, code_repo: &CodeRepo) -> bool { match self.p { - CodePtr::Local(LocalCodePtr::DirEntry(p)) | - CodePtr::Local(LocalCodePtr::IndexingBuf(p, ..)) - if p < code_repo.code.len() => { - } + CodePtr::Local(LocalCodePtr::DirEntry(p)) + | CodePtr::Local(LocalCodePtr::IndexingBuf(p, ..)) + if p < code_repo.code.len() => {} CodePtr::Local(LocalCodePtr::Halt) | CodePtr::REPL(..) => { return false; } - _ => { - } + _ => {} } true @@ -689,13 +669,7 @@ impl MachineState { user_output: &mut Stream, ) { loop { - self.execute_instr( - indices, - policies, - code_repo, - user_input, - user_output, - ); + self.execute_instr(indices, policies, code_repo, user_input, user_output); if self.fail { self.backtrack(); diff --git a/src/machine/preprocessor.rs b/src/machine/preprocessor.rs index ab82b1f9..34d47ebe 100644 --- a/src/machine/preprocessor.rs +++ b/src/machine/preprocessor.rs @@ -1,11 +1,12 @@ use crate::prolog_parser_rebis::ast::*; use crate::prolog_parser_rebis::tabled_rc::*; +use crate::prolog_parser_rebis::{atom, clause_name, rc_atom}; use crate::forms::*; use crate::iterators::*; -use crate::machine::*; use crate::machine::load_state::*; use crate::machine::machine_errors::*; +use crate::machine::*; use crate::indexmap::IndexSet; @@ -85,27 +86,24 @@ fn setup_op_decl( to_op_decl(prec, spec.as_str(), name) } -fn setup_predicate_indicator(term: &mut Term) -> Result -{ +fn setup_predicate_indicator(term: &mut Term) -> Result { match term { Term::Clause(_, ref slash, ref mut terms, Some(_)) if (slash.as_str() == "/" || slash.as_str() == "//") && terms.len() == 2 => { let arity = *terms.pop().unwrap(); - let name = *terms.pop().unwrap(); + let name = *terms.pop().unwrap(); let arity = arity .to_constant() - .and_then(|c| { - match c { - Constant::Integer(n) => n.to_usize(), - Constant::Fixnum(n) => usize::try_from(n).ok(), - _ => None - } + .and_then(|c| match c { + Constant::Integer(n) => n.to_usize(), + Constant::Fixnum(n) => usize::try_from(n).ok(), + _ => None, }) .ok_or(CompilationError::InvalidModuleExport)?; - let name = name + let name = name .to_constant() .and_then(|c| c.to_atom()) .ok_or(CompilationError::InvalidModuleExport)?; @@ -116,9 +114,7 @@ fn setup_predicate_indicator(term: &mut Term) -> Result { - Err(CompilationError::InvalidModuleExport) - } + _ => Err(CompilationError::InvalidModuleExport), } } @@ -155,10 +151,7 @@ fn setup_module_export( .or_else(|_| { if let Term::Clause(_, name, terms, _) = term { if terms.len() == 3 && name.as_str() == "op" { - Ok(ModuleExport::OpDecl(setup_op_decl( - terms, - atom_tbl - )?)) + Ok(ModuleExport::OpDecl(setup_op_decl(terms, atom_tbl)?)) } else { Err(CompilationError::InvalidModuleDecl) } @@ -168,8 +161,7 @@ fn setup_module_export( }) } -pub(super) -fn setup_module_export_list( +pub(super) fn setup_module_export_list( mut export_list: Term, atom_tbl: TabledData, ) -> Result, CompilationError> { @@ -218,8 +210,7 @@ fn setup_use_module_decl(mut terms: Vec>) -> Result - Ok(ModuleSource::File(name.clone())), + Term::Constant(_, Constant::Atom(ref name, _)) => Ok(ModuleSource::File(name.clone())), _ => Err(CompilationError::InvalidUseModuleDecl), } } @@ -271,12 +262,8 @@ fn setup_qualified_import( .map(|c| ModuleSource::Library(c)) .ok_or(CompilationError::InvalidUseModuleDecl) } - Term::Constant(_, Constant::Atom(ref name, _)) => { - Ok(ModuleSource::File(name.clone())) - } - _ => { - Err(CompilationError::InvalidUseModuleDecl) - } + Term::Constant(_, Constant::Atom(ref name, _)) => Ok(ModuleSource::File(name.clone())), + _ => Err(CompilationError::InvalidUseModuleDecl), }?; let mut exports = IndexSet::new(); @@ -334,8 +321,7 @@ fn setup_qualified_import( fn setup_meta_predicate<'a>( mut terms: Vec>, load_state: &LoadState<'a>, -) -> Result<(ClauseName, ClauseName, Vec), CompilationError> -{ +) -> Result<(ClauseName, ClauseName, Vec), CompilationError> { fn get_name_and_meta_specs( name: ClauseName, terms: &mut [Box], @@ -345,26 +331,23 @@ fn setup_meta_predicate<'a>( for meta_spec in terms.into_iter() { match &**meta_spec { Term::Constant(_, Constant::Atom(meta_spec, _)) => { - let meta_spec = - match meta_spec.as_str() { - "+" => MetaSpec::Plus, - "-" => MetaSpec::Minus, - "?" => MetaSpec::Either, - _ => return Err(CompilationError::InvalidMetaPredicateDecl), - }; + let meta_spec = match meta_spec.as_str() { + "+" => MetaSpec::Plus, + "-" => MetaSpec::Minus, + "?" => MetaSpec::Either, + _ => return Err(CompilationError::InvalidMetaPredicateDecl), + }; meta_specs.push(meta_spec); } - Term::Constant(_, Constant::Fixnum(n)) => { - match usize::try_from(*n) { - Ok(n) if n <= MAX_ARITY => { - meta_specs.push(MetaSpec::RequiresExpansionWithArgument(n)); - } - _ => { - return Err(CompilationError::InvalidMetaPredicateDecl); - } + Term::Constant(_, Constant::Fixnum(n)) => match usize::try_from(*n) { + Ok(n) if n <= MAX_ARITY => { + meta_specs.push(MetaSpec::RequiresExpansionWithArgument(n)); } - } + _ => { + return Err(CompilationError::InvalidMetaPredicateDecl); + } + }, _ => { return Err(CompilationError::InvalidMetaPredicateDecl); } @@ -375,42 +358,35 @@ fn setup_meta_predicate<'a>( } match *terms.pop().unwrap() { - Term::Clause(_, name, mut terms, _) - if name.as_str() == ":" && terms.len() == 2 => { - let spec = *terms.pop().unwrap(); - let module_name = *terms.pop().unwrap(); + Term::Clause(_, name, mut terms, _) if name.as_str() == ":" && terms.len() == 2 => { + let spec = *terms.pop().unwrap(); + let module_name = *terms.pop().unwrap(); - match module_name { - Term::Constant(_, Constant::Atom(module_name, _)) => { - match spec { - Term::Clause(_, name, mut terms, _) => { - let (name, meta_specs) = - get_name_and_meta_specs(name, &mut terms)?; + match module_name { + Term::Constant(_, Constant::Atom(module_name, _)) => match spec { + Term::Clause(_, name, mut terms, _) => { + let (name, meta_specs) = get_name_and_meta_specs(name, &mut terms)?; - Ok((module_name, name, meta_specs)) - } - _ => { - Err(CompilationError::InvalidMetaPredicateDecl) - } - } + Ok((module_name, name, meta_specs)) } - _ => { - Err(CompilationError::InvalidMetaPredicateDecl) - } - } + _ => Err(CompilationError::InvalidMetaPredicateDecl), + }, + _ => Err(CompilationError::InvalidMetaPredicateDecl), } + } Term::Clause(_, name, mut terms, _) => { let (name, meta_specs) = get_name_and_meta_specs(name, &mut terms)?; - Ok((load_state.compilation_target.module_name(), name, meta_specs)) - } - _ => { - Err(CompilationError::InvalidMetaPredicateDecl) + Ok(( + load_state.compilation_target.module_name(), + name, + meta_specs, + )) } + _ => Err(CompilationError::InvalidMetaPredicateDecl), } } -fn merge_clauses(tls: &mut VecDeque) -> Result -{ +fn merge_clauses(tls: &mut VecDeque) -> Result { let mut clauses = vec![]; while let Some(tl) = tls.pop_front() { @@ -432,9 +408,7 @@ fn merge_clauses(tls: &mut VecDeque) -> Result { - clauses.extend(predicate.into_iter()) - } + TopLevel::Predicate(predicate) => clauses.extend(predicate.into_iter()), _ => { tls.push_front(tl); break; @@ -506,8 +480,8 @@ fn check_for_internal_if_then(terms: &mut Vec) { conq_terms.push_front(Term::Constant( Cell::default(), - Constant::Atom(clause_name!("blocked_!"), None)) - ); + Constant::Atom(clause_name!("blocked_!"), None), + )); while let Some(term) = pre_cut_terms.pop_back() { conq_terms.push_front(term); @@ -531,38 +505,29 @@ fn setup_declaration<'a>( let atom_tbl = load_state.wam.machine_st.atom_tbl.clone(); match term { - Term::Clause(_, name, mut terms, _) => - match (name.as_str(), terms.len()) { - ("dynamic", 1) => { - let (name, arity) = setup_predicate_indicator(&mut *terms.pop().unwrap())?; - Ok(Declaration::Dynamic(name, arity)) - } - ("module", 2) => - Ok(Declaration::Module(setup_module_decl(terms, atom_tbl)?)), - ("op", 3) => - Ok(Declaration::Op(setup_op_decl(terms, atom_tbl)?)), - ("non_counted_backtracking", 1) => { - let (name, arity) = setup_predicate_indicator(&mut *terms.pop().unwrap())?; - Ok(Declaration::NonCountedBacktracking(name, arity)) - } - ("use_module", 1) => { - Ok(Declaration::UseModule(setup_use_module_decl(terms)?)) - } - ("use_module", 2) => { - let (name, exports) = setup_qualified_import(terms, atom_tbl)?; - Ok(Declaration::UseQualifiedModule(name, exports)) - } - ("meta_predicate", 1) => { - let (module_name, name, meta_specs) = setup_meta_predicate(terms, load_state)?; - Ok(Declaration::MetaPredicate(module_name, name, meta_specs)) - } - _ => { - Err(CompilationError::InconsistentEntry) - } - }, - _ => { - Err(CompilationError::InconsistentEntry) - } + Term::Clause(_, name, mut terms, _) => match (name.as_str(), terms.len()) { + ("dynamic", 1) => { + let (name, arity) = setup_predicate_indicator(&mut *terms.pop().unwrap())?; + Ok(Declaration::Dynamic(name, arity)) + } + ("module", 2) => Ok(Declaration::Module(setup_module_decl(terms, atom_tbl)?)), + ("op", 3) => Ok(Declaration::Op(setup_op_decl(terms, atom_tbl)?)), + ("non_counted_backtracking", 1) => { + let (name, arity) = setup_predicate_indicator(&mut *terms.pop().unwrap())?; + Ok(Declaration::NonCountedBacktracking(name, arity)) + } + ("use_module", 1) => Ok(Declaration::UseModule(setup_use_module_decl(terms)?)), + ("use_module", 2) => { + let (name, exports) = setup_qualified_import(terms, atom_tbl)?; + Ok(Declaration::UseQualifiedModule(name, exports)) + } + ("meta_predicate", 1) => { + let (module_name, name, meta_specs) = setup_meta_predicate(terms, load_state)?; + Ok(Declaration::MetaPredicate(module_name, name, meta_specs)) + } + _ => Err(CompilationError::InconsistentEntry), + }, + _ => Err(CompilationError::InconsistentEntry), } } @@ -596,8 +561,7 @@ pub(crate) struct Preprocessor { } impl Preprocessor { - pub(super) - fn new(flags: MachineFlags) -> Self { + pub(super) fn new(flags: MachineFlags) -> Self { Preprocessor { flags, queue: VecDeque::new(), @@ -606,12 +570,8 @@ impl Preprocessor { fn setup_fact(&mut self, term: Term) -> Result { match term { - Term::Clause(..) | Term::Constant(_, Constant::Atom(..)) => { - Ok(term) - } - _ => { - Err(CompilationError::InadmissibleFact) - } + Term::Clause(..) | Term::Constant(_, Constant::Atom(..)) => Ok(term), + _ => Err(CompilationError::InadmissibleFact), } } @@ -712,109 +672,97 @@ impl Preprocessor { Ok(clause_to_query_term(load_state, name, vec![], fixity)) } } - Term::Constant(_, Constant::Char('!')) => { - Ok(QueryTerm::BlockedCut) - } + Term::Constant(_, Constant::Char('!')) => Ok(QueryTerm::BlockedCut), Term::Var(_, ref v) if v.as_str() == "!" => { Ok(QueryTerm::UnblockedCut(Cell::default())) } - Term::Clause(r, name, mut terms, fixity) => { - match (name.as_str(), terms.len()) { - (";", 2) => { - let term = Term::Clause(r, name.clone(), terms, fixity); + Term::Clause(r, name, mut terms, fixity) => match (name.as_str(), terms.len()) { + (";", 2) => { + let term = Term::Clause(r, name.clone(), terms, fixity); - let (stub, clauses) = self.fabricate_disjunct(term); - self.queue.push_back(clauses); + let (stub, clauses) = self.fabricate_disjunct(term); + self.queue.push_back(clauses); - Ok(QueryTerm::Jump(stub)) - } - ("->", 2) => { - let conq = *terms.pop().unwrap(); - let prec = *terms.pop().unwrap(); + Ok(QueryTerm::Jump(stub)) + } + ("->", 2) => { + let conq = *terms.pop().unwrap(); + let prec = *terms.pop().unwrap(); - let (stub, clauses) = self.fabricate_if_then(prec, conq); - self.queue.push_back(clauses); + let (stub, clauses) = self.fabricate_if_then(prec, conq); + self.queue.push_back(clauses); - Ok(QueryTerm::Jump(stub)) - } - ("\\+", 1) => { - terms.push(Box::new(Term::Constant( - Cell::default(), - Constant::Atom(clause_name!("$fail"), None) - ))); + Ok(QueryTerm::Jump(stub)) + } + ("\\+", 1) => { + terms.push(Box::new(Term::Constant( + Cell::default(), + Constant::Atom(clause_name!("$fail"), None), + ))); - let conq = Term::Constant( - Cell::default(), - Constant::Atom(clause_name!("true"), None) - ); + let conq = + Term::Constant(Cell::default(), Constant::Atom(clause_name!("true"), None)); - let prec = Term::Clause(Cell::default(), clause_name!("->"), terms, None); - let terms = vec![Box::new(prec), Box::new(conq)]; + let prec = Term::Clause(Cell::default(), clause_name!("->"), terms, None); + let terms = vec![Box::new(prec), Box::new(conq)]; - let term = Term::Clause(Cell::default(), clause_name!(";"), terms, None); - let (stub, clauses) = self.fabricate_disjunct(term); + let term = Term::Clause(Cell::default(), clause_name!(";"), terms, None); + let (stub, clauses) = self.fabricate_disjunct(term); - debug_assert!(clauses.len() > 0); - self.queue.push_back(clauses); + debug_assert!(clauses.len() > 0); + self.queue.push_back(clauses); - Ok(QueryTerm::Jump(stub)) - } - ("$get_level", 1) => { - if let Term::Var(_, ref var) = *terms[0] { - Ok(QueryTerm::GetLevelAndUnify(Cell::default(), var.clone())) - } else { - Err(CompilationError::InadmissibleQueryTerm) - } - } - (":", 2) => { - let predicate_name = *terms.pop().unwrap(); - let module_name = *terms.pop().unwrap(); - - match (module_name, predicate_name) { - (Term::Constant(_, Constant::Atom(module_name, _)), - Term::Constant(_, Constant::Atom(predicate_name, fixity))) => { - Ok(qualified_clause_to_query_term( - load_state, - module_name, - predicate_name, - vec![], - fixity, - )) - } - (Term::Constant(_, Constant::Atom(module_name, _)), - Term::Clause(_, name, terms, fixity)) => { - Ok(qualified_clause_to_query_term( - load_state, - module_name, - name, - terms, - fixity, - )) - } - (module_name, predicate_name) => { - terms.push(Box::new(module_name)); - terms.push(Box::new(predicate_name)); - - Ok(clause_to_query_term(load_state, name, terms, fixity)) - } - } - } - _ => { - Ok(clause_to_query_term(load_state, name, terms, fixity)) + Ok(QueryTerm::Jump(stub)) + } + ("$get_level", 1) => { + if let Term::Var(_, ref var) = *terms[0] { + Ok(QueryTerm::GetLevelAndUnify(Cell::default(), var.clone())) + } else { + Err(CompilationError::InadmissibleQueryTerm) } } - } - Term::Var(..) => { - Ok(QueryTerm::Clause( - Cell::default(), - ClauseType::CallN, - vec![Box::new(term)], - false, - )) - } - _ => { - Err(CompilationError::InadmissibleQueryTerm) - } + (":", 2) => { + let predicate_name = *terms.pop().unwrap(); + let module_name = *terms.pop().unwrap(); + + match (module_name, predicate_name) { + ( + Term::Constant(_, Constant::Atom(module_name, _)), + Term::Constant(_, Constant::Atom(predicate_name, fixity)), + ) => Ok(qualified_clause_to_query_term( + load_state, + module_name, + predicate_name, + vec![], + fixity, + )), + ( + Term::Constant(_, Constant::Atom(module_name, _)), + Term::Clause(_, name, terms, fixity), + ) => Ok(qualified_clause_to_query_term( + load_state, + module_name, + name, + terms, + fixity, + )), + (module_name, predicate_name) => { + terms.push(Box::new(module_name)); + terms.push(Box::new(predicate_name)); + + Ok(clause_to_query_term(load_state, name, terms, fixity)) + } + } + } + _ => Ok(clause_to_query_term(load_state, name, terms, fixity)), + }, + Term::Var(..) => Ok(QueryTerm::Clause( + Cell::default(), + ClauseType::CallN, + vec![Box::new(term)], + false, + )), + _ => Err(CompilationError::InadmissibleQueryTerm), } } @@ -835,9 +783,7 @@ impl Preprocessor { self.to_query_term(load_state, Term::Clause(r, name, subterms, fixity)) } } - _ => { - self.to_query_term(load_state, term) - } + _ => self.to_query_term(load_state, term), } } @@ -884,30 +830,23 @@ impl Preprocessor { mut terms: Vec>, cut_context: CutContext, ) -> Result { - let post_head_terms: Vec<_> = terms.drain(1 ..).collect(); + let post_head_terms: Vec<_> = terms.drain(1..).collect(); - let mut query_terms = - self.setup_query(load_state, post_head_terms, cut_context)?; + let mut query_terms = self.setup_query(load_state, post_head_terms, cut_context)?; - let clauses = query_terms.drain(1 ..).collect(); + let clauses = query_terms.drain(1..).collect(); let qt = query_terms.pop().unwrap(); match *terms.pop().unwrap() { - Term::Clause(_, name, terms, _) => { - Ok(Rule { - head: (name, terms, qt), - clauses, - }) - } - Term::Constant(_, Constant::Atom(name, _)) => { - Ok(Rule { - head: (name, vec![], qt), - clauses, - }) - } - _ => { - Err(CompilationError::InvalidRuleHead) - } + Term::Clause(_, name, terms, _) => Ok(Rule { + head: (name, terms, qt), + clauses, + }), + Term::Constant(_, Constant::Atom(name, _)) => Ok(Rule { + head: (name, vec![], qt), + clauses, + }), + _ => Err(CompilationError::InvalidRuleHead), } } @@ -917,11 +856,14 @@ impl Preprocessor { terms: Vec>, cut_context: CutContext, ) -> Result { - Ok(TopLevel::Query(self.setup_query(load_state, terms, cut_context)?)) + Ok(TopLevel::Query(self.setup_query( + load_state, + terms, + cut_context, + )?)) } - pub(super) - fn try_term_to_tl<'a>( + pub(super) fn try_term_to_tl<'a>( &mut self, load_state: &mut LoadState<'a>, term: Term, @@ -944,9 +886,7 @@ impl Preprocessor { Ok(TopLevel::Fact(self.setup_fact(term)?)) } } - term => { - Ok(TopLevel::Fact(self.setup_fact(term)?)) - } + term => Ok(TopLevel::Fact(self.setup_fact(term)?)), } } @@ -965,21 +905,18 @@ impl Preprocessor { Ok(results) } - pub(super) - fn parse_queue<'a>( + pub(super) fn parse_queue<'a>( &mut self, load_state: &mut LoadState<'a>, ) -> Result, CompilationError> { let mut queue = VecDeque::new(); while let Some(terms) = self.queue.pop_front() { - let clauses = merge_clauses( - &mut self.try_terms_to_tls( - load_state, - terms, - CutContext::HasCutVariable, - )? - )?; + let clauses = merge_clauses(&mut self.try_terms_to_tls( + load_state, + terms, + CutContext::HasCutVariable, + )?)?; queue.push_back(clauses); } diff --git a/src/machine/streams.rs b/src/machine/streams.rs index 21040c60..531b47c4 100644 --- a/src/machine/streams.rs +++ b/src/machine/streams.rs @@ -1,19 +1,20 @@ use crate::prolog_parser_rebis::ast::*; +use crate::prolog_parser_rebis::clause_name; -use crate::read::PrologStream; -use crate::read::readline::*; use crate::machine::machine_errors::*; use crate::machine::machine_indices::*; use crate::machine::machine_state::*; +use crate::read::readline::*; +use crate::read::PrologStream; -use std::cmp::Ordering; use std::cell::RefCell; +use std::cmp::Ordering; use std::error::Error; use std::fmt; use std::fs::File; +use std::hash::{Hash, Hasher}; use std::io; use std::io::{stdout, Cursor, ErrorKind, Read, Seek, SeekFrom, Write}; -use std::hash::{Hash, Hasher}; use std::mem; use std::net::{Shutdown, TcpStream}; use std::ops::DerefMut; @@ -29,8 +30,7 @@ pub enum StreamType { impl StreamType { #[inline] - pub(crate) - fn as_str(&self) -> &'static str { + pub(crate) fn as_str(&self) -> &'static str { match self { StreamType::Binary => "binary_stream", StreamType::Text => "text_stream", @@ -38,8 +38,7 @@ impl StreamType { } #[inline] - pub(crate) - fn as_property_str(&self) -> &'static str { + pub(crate) fn as_property_str(&self) -> &'static str { match self { StreamType::Binary => "binary", StreamType::Text => "text", @@ -47,8 +46,7 @@ impl StreamType { } #[inline] - pub(crate) - fn other(self) -> StreamType { + pub(crate) fn other(self) -> StreamType { match self { StreamType::Binary => StreamType::Text, StreamType::Text => StreamType::Binary, @@ -67,13 +65,12 @@ pub enum EOFAction { pub enum AtEndOfStream { Not, At, - Past + Past, } impl AtEndOfStream { #[inline] - pub(crate) - fn as_str(&self) -> &'static str { + pub(crate) fn as_str(&self) -> &'static str { match self { AtEndOfStream::Not => "not", AtEndOfStream::Past => "past", @@ -84,8 +81,7 @@ impl AtEndOfStream { impl EOFAction { #[inline] - pub(crate) - fn as_str(&self) -> &'static str { + pub(crate) fn as_str(&self) -> &'static str { match self { EOFAction::EOFCode => "eof_code", EOFAction::Error => "error", @@ -120,7 +116,7 @@ enum StreamInstance { StaticStr(Cursor<&'static str>), Stdout, TcpStream(ClauseName, TcpStream), - TlsStream(ClauseName, TlsStream) + TlsStream(ClauseName, TlsStream), } impl StreamInstance { @@ -141,31 +137,18 @@ impl StreamInstance { if index == buf.len() { Ok(buf.len()) } else { - stream.read(&mut buf[index ..]) - .map(|bytes_read| bytes_read + index) + stream + .read(&mut buf[index..]) + .map(|bytes_read| bytes_read + index) } } - StreamInstance::InputFile(_, ref mut file) => { - file.read(buf) - } - StreamInstance::TcpStream(_, ref mut tcp_stream) => { - tcp_stream.read(buf) - } - StreamInstance::TlsStream(_, ref mut tls_stream) => { - tls_stream.read(buf) - } - StreamInstance::ReadlineStream(ref mut rl_stream) => { - rl_stream.read(buf) - } - StreamInstance::StaticStr(ref mut src) => { - src.read(buf) - } - StreamInstance::Bytes(ref mut cursor) => { - cursor.read(buf) - } - StreamInstance::OutputFile(..) | - StreamInstance::Stdout | - StreamInstance::Null => { + StreamInstance::InputFile(_, ref mut file) => file.read(buf), + StreamInstance::TcpStream(_, ref mut tcp_stream) => tcp_stream.read(buf), + StreamInstance::TlsStream(_, ref mut tls_stream) => tls_stream.read(buf), + StreamInstance::ReadlineStream(ref mut rl_stream) => rl_stream.read(buf), + StreamInstance::StaticStr(ref mut src) => src.read(buf), + StreamInstance::Bytes(ref mut cursor) => cursor.read(buf), + StreamInstance::OutputFile(..) | StreamInstance::Stdout | StreamInstance::Null => { Err(std::io::Error::new( ErrorKind::PermissionDenied, StreamError::ReadFromOutputStream, @@ -184,8 +167,7 @@ impl Drop for StreamInstance { StreamInstance::TlsStream(_, ref mut tls_stream) => { tls_stream.shutdown().unwrap(); } - _ => { - } + _ => {} } } } @@ -193,26 +175,24 @@ impl Drop for StreamInstance { impl fmt::Debug for StreamInstance { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { - &StreamInstance::Bytes(ref bytes) => - write!(fmt, "Bytes({:?})", bytes), - &StreamInstance::StaticStr(_) => - write!(fmt, "StaticStr(_)"), // Hacky solution. - &StreamInstance::InputFile(_, ref file) => - write!(fmt, "InputFile({:?})", file), - &StreamInstance::OutputFile(_, ref file, _) => - write!(fmt, "OutputFile({:?})", file), - &StreamInstance::Null => - write!(fmt, "Null"), - &StreamInstance::PausedPrologStream(ref put_back, ref stream) => - write!(fmt, "PausedPrologStream({:?}, {:?})", put_back, stream), - &StreamInstance::ReadlineStream(ref readline_stream) => - write!(fmt, "ReadlineStream({:?})", readline_stream), - &StreamInstance::Stdout => - write!(fmt, "Stdout"), - &StreamInstance::TcpStream(_, ref tcp_stream) => - write!(fmt, "TcpStream({:?})", tcp_stream), - &StreamInstance::TlsStream(_, ref tls_stream) => - write!(fmt, "TlsStream({:?})", tls_stream), + &StreamInstance::Bytes(ref bytes) => write!(fmt, "Bytes({:?})", bytes), + &StreamInstance::StaticStr(_) => write!(fmt, "StaticStr(_)"), // Hacky solution. + &StreamInstance::InputFile(_, ref file) => write!(fmt, "InputFile({:?})", file), + &StreamInstance::OutputFile(_, ref file, _) => write!(fmt, "OutputFile({:?})", file), + &StreamInstance::Null => write!(fmt, "Null"), + &StreamInstance::PausedPrologStream(ref put_back, ref stream) => { + write!(fmt, "PausedPrologStream({:?}, {:?})", put_back, stream) + } + &StreamInstance::ReadlineStream(ref readline_stream) => { + write!(fmt, "ReadlineStream({:?})", readline_stream) + } + &StreamInstance::Stdout => write!(fmt, "Stdout"), + &StreamInstance::TcpStream(_, ref tcp_stream) => { + write!(fmt, "TcpStream({:?})", tcp_stream) + } + &StreamInstance::TlsStream(_, ref tls_stream) => { + write!(fmt, "TlsStream({:?})", tls_stream) + } } } } @@ -223,9 +203,7 @@ struct WrappedStreamInstance(Rc>); impl WrappedStreamInstance { #[inline] fn new(stream_inst: StreamInstance) -> Self { - WrappedStreamInstance( - Rc::new(RefCell::new((false, stream_inst))) - ) + WrappedStreamInstance(Rc::new(RefCell::new((false, stream_inst)))) } } @@ -362,8 +340,7 @@ impl From<&'static str> for Stream { impl Stream { #[inline] - pub(crate) - fn as_ptr(&self) -> *const u8 { + pub(crate) fn as_ptr(&self) -> *const u8 { let rc = self.stream_inst.0.clone(); let ptr = Rc::into_raw(rc); @@ -376,21 +353,15 @@ impl Stream { } #[inline] - pub(crate) - fn position(&mut self) -> Option { + pub(crate) fn position(&mut self) -> Option { match self.stream_inst.0.borrow_mut().1 { - StreamInstance::InputFile(_, ref mut file) => { - file.seek(SeekFrom::Current(0)).ok() - } - _ => { - None - } + StreamInstance::InputFile(_, ref mut file) => file.seek(SeekFrom::Current(0)).ok(), + _ => None, } } #[inline] - pub(crate) - fn set_position(&mut self, position: u64) { + pub(crate) fn set_position(&mut self, position: u64) { match self.stream_inst.0.borrow_mut().deref_mut() { (past_end_of_stream, StreamInstance::InputFile(_, ref mut file)) => { file.seek(SeekFrom::Start(position)).unwrap(); @@ -399,32 +370,27 @@ impl Stream { *past_end_of_stream = position > metadata.len(); } } - _ => { - } + _ => {} } } #[inline] - pub(crate) - fn past_end_of_stream(&self) -> bool { + pub(crate) fn past_end_of_stream(&self) -> bool { self.stream_inst.0.borrow_mut().0 } #[inline] - pub(crate) - fn at_end_of_stream(&mut self) -> bool { + pub(crate) fn at_end_of_stream(&mut self) -> bool { self.position_relative_to_end() == AtEndOfStream::At } #[inline] - pub(crate) - fn set_past_end_of_stream(&mut self) { + pub(crate) fn set_past_end_of_stream(&mut self) { self.stream_inst.0.borrow_mut().0 = true; } #[inline] - pub(crate) - fn position_relative_to_end(&mut self) -> AtEndOfStream { + pub(crate) fn position_relative_to_end(&mut self) -> AtEndOfStream { if self.past_end_of_stream() { return AtEndOfStream::Past; } @@ -435,12 +401,8 @@ impl Stream { Ok(metadata) => { if let Ok(position) = file.seek(SeekFrom::Current(0)) { return match position.cmp(&metadata.len()) { - Ordering::Equal => { - AtEndOfStream::At - } - Ordering::Less => { - AtEndOfStream::Not - } + Ordering::Equal => AtEndOfStream::At, + Ordering::Less => AtEndOfStream::Not, Ordering::Greater => { *past_end_of_stream = true; //self.set_past_end_of_stream(); AtEndOfStream::Past @@ -457,56 +419,32 @@ impl Stream { } } } - _ => { - AtEndOfStream::Not - } + _ => AtEndOfStream::Not, } } #[inline] - pub(crate) - fn file_name(&self) -> Option { + pub(crate) fn file_name(&self) -> Option { match self.stream_inst.0.borrow().1 { - StreamInstance::InputFile(ref name, _) => { - Some(name.clone()) - } - StreamInstance::OutputFile(ref name, ..) => { - Some(name.clone()) - } - StreamInstance::TcpStream(ref name, _) => { - Some(name.clone()) - } - _ => { - None - } + StreamInstance::InputFile(ref name, _) => Some(name.clone()), + StreamInstance::OutputFile(ref name, ..) => Some(name.clone()), + StreamInstance::TcpStream(ref name, _) => Some(name.clone()), + _ => None, } } #[inline] - pub(crate) - fn mode(&self) -> &'static str { + pub(crate) fn mode(&self) -> &'static str { match self.stream_inst.0.borrow().1 { - StreamInstance::Bytes(_) | - StreamInstance::PausedPrologStream(..) | - StreamInstance::ReadlineStream(_) | - StreamInstance::StaticStr(_) | - StreamInstance::InputFile(..) => { - "read" - } - StreamInstance::TcpStream(..) | - StreamInstance::TlsStream(..) => { - "read_append" - } - StreamInstance::OutputFile(_, _, true) => { - "append" - } - StreamInstance::Stdout | - StreamInstance::OutputFile(_, _, false) => { - "write" - } - StreamInstance::Null => { - "" - } + StreamInstance::Bytes(_) + | StreamInstance::PausedPrologStream(..) + | StreamInstance::ReadlineStream(_) + | StreamInstance::StaticStr(_) + | StreamInstance::InputFile(..) => "read", + StreamInstance::TcpStream(..) | StreamInstance::TlsStream(..) => "read_append", + StreamInstance::OutputFile(_, _, true) => "append", + StreamInstance::Stdout | StreamInstance::OutputFile(_, _, false) => "write", + StreamInstance::Null => "", } } @@ -514,19 +452,17 @@ impl Stream { fn from_inst(stream_inst: StreamInstance) -> Self { Stream { options: StreamOptions::default(), - stream_inst: WrappedStreamInstance::new(stream_inst) + stream_inst: WrappedStreamInstance::new(stream_inst), } } #[inline] - pub(crate) - fn stdout() -> Self { + pub(crate) fn stdout() -> Self { Stream::from_inst(StreamInstance::Stdout) } #[inline] - pub(crate) - fn from_tcp_stream(address: ClauseName, tcp_stream: TcpStream) -> Self { + pub(crate) fn from_tcp_stream(address: ClauseName, tcp_stream: TcpStream) -> Self { tcp_stream.set_read_timeout(None).unwrap(); tcp_stream.set_write_timeout(None).unwrap(); @@ -534,58 +470,43 @@ impl Stream { } #[inline] - pub(crate) - fn from_tls_stream(address: ClauseName, tls_stream: TlsStream) -> Self { + pub(crate) fn from_tls_stream(address: ClauseName, tls_stream: TlsStream) -> Self { Stream::from_inst(StreamInstance::TlsStream(address, tls_stream)) } #[inline] - pub(crate) - fn from_file_as_output(name: ClauseName, file: File, in_append_mode: bool) -> Self { + pub(crate) fn from_file_as_output(name: ClauseName, file: File, in_append_mode: bool) -> Self { Stream::from_inst(StreamInstance::OutputFile(name, file, in_append_mode)) } #[inline] - pub(crate) - fn from_file_as_input(name: ClauseName, file: File) -> Self { + pub(crate) fn from_file_as_input(name: ClauseName, file: File) -> Self { Stream::from_inst(StreamInstance::InputFile(name, file)) } #[inline] - pub(crate) - fn is_stdout(&self) -> bool { + pub(crate) fn is_stdout(&self) -> bool { match self.stream_inst.0.borrow().1 { - StreamInstance::Stdout => { - true - } - _ => { - false - } + StreamInstance::Stdout => true, + _ => false, } } #[inline] - pub(crate) - fn is_stdin(&self) -> bool { + pub(crate) fn is_stdin(&self) -> bool { match self.stream_inst.0.borrow().1 { - StreamInstance::ReadlineStream(_) => { - true - } - _ => { - false - } + StreamInstance::ReadlineStream(_) => true, + _ => false, } } #[inline] - pub(crate) - fn close(&mut self) { + pub(crate) fn close(&mut self) { self.stream_inst.0.borrow_mut().1 = StreamInstance::Null; } #[inline] - pub(crate) - fn is_null_stream(&self) -> bool { + pub(crate) fn is_null_stream(&self) -> bool { if let StreamInstance::Null = self.stream_inst.0.borrow().1 { true } else { @@ -594,60 +515,49 @@ impl Stream { } #[inline] - pub(crate) - fn is_input_stream(&self) -> bool { + pub(crate) fn is_input_stream(&self) -> bool { match self.stream_inst.0.borrow().1 { - StreamInstance::TcpStream(..) | - StreamInstance::TlsStream(..) | - StreamInstance::Bytes(_) | - StreamInstance::PausedPrologStream(..) | - StreamInstance::ReadlineStream(_) | - StreamInstance::StaticStr(_) | - StreamInstance::InputFile(..) => { - true - } - _ => { - false - } + StreamInstance::TcpStream(..) + | StreamInstance::TlsStream(..) + | StreamInstance::Bytes(_) + | StreamInstance::PausedPrologStream(..) + | StreamInstance::ReadlineStream(_) + | StreamInstance::StaticStr(_) + | StreamInstance::InputFile(..) => true, + _ => false, } } #[inline] - pub(crate) - fn is_output_stream(&self) -> bool { + pub(crate) fn is_output_stream(&self) -> bool { match self.stream_inst.0.borrow().1 { StreamInstance::Stdout - | StreamInstance::TcpStream(..) - | StreamInstance::TlsStream(..) - | StreamInstance::Bytes(_) - | StreamInstance::OutputFile(..) => { - true - } - _ => { - false - } + | StreamInstance::TcpStream(..) + | StreamInstance::TlsStream(..) + | StreamInstance::Bytes(_) + | StreamInstance::OutputFile(..) => true, + _ => false, } } fn unpause_stream(&mut self) { - let stream_inst = - match self.stream_inst.0.borrow_mut().1 { - StreamInstance::PausedPrologStream(ref put_back, ref mut stream_inst) - if put_back.is_empty() => { - mem::replace(&mut **stream_inst, StreamInstance::Null) - } - _ => { - return; - } - }; + let stream_inst = match self.stream_inst.0.borrow_mut().1 { + StreamInstance::PausedPrologStream(ref put_back, ref mut stream_inst) + if put_back.is_empty() => + { + mem::replace(&mut **stream_inst, StreamInstance::Null) + } + _ => { + return; + } + }; self.stream_inst.0.borrow_mut().1 = stream_inst; } // returns true on success. #[inline] - pub(super) - fn reset(&mut self) -> bool { + pub(super) fn reset(&mut self) -> bool { self.stream_inst.0.borrow_mut().0 = false; loop { @@ -676,8 +586,7 @@ impl Stream { } #[inline] - pub(crate) - fn peek_byte(&mut self) -> std::io::Result { + pub(crate) fn peek_byte(&mut self) -> std::io::Result { match self.stream_inst.0.borrow_mut().1 { StreamInstance::Bytes(ref mut cursor) => { let mut b = [0u8; 1]; @@ -688,12 +597,7 @@ impl Stream { cursor.set_position(pos); Ok(b[0]) } - _ => { - Err(std::io::Error::new( - ErrorKind::UnexpectedEof, - "end of file", - )) - } + _ => Err(std::io::Error::new(ErrorKind::UnexpectedEof, "end of file")), } } StreamInstance::InputFile(_, ref mut file) => { @@ -704,34 +608,27 @@ impl Stream { file.seek(SeekFrom::Current(-1))?; Ok(b[0]) } - _ => { - Err(std::io::Error::new( - ErrorKind::UnexpectedEof, - StreamError::PeekByteFailed, - )) - } + _ => Err(std::io::Error::new( + ErrorKind::UnexpectedEof, + StreamError::PeekByteFailed, + )), } } - StreamInstance::ReadlineStream(ref mut stream) => { - stream.peek_byte() - } + StreamInstance::ReadlineStream(ref mut stream) => stream.peek_byte(), StreamInstance::TcpStream(_, ref mut tcp_stream) => { let mut b = [0u8; 1]; tcp_stream.peek(&mut b)?; Ok(b[0]) } - _ => { - Err(std::io::Error::new( - ErrorKind::PermissionDenied, - StreamError::PeekByteFromNonPeekableStream, - )) - } + _ => Err(std::io::Error::new( + ErrorKind::PermissionDenied, + StreamError::PeekByteFromNonPeekableStream, + )), } } #[inline] - pub(crate) - fn peek_char(&mut self) -> std::io::Result { + pub(crate) fn peek_char(&mut self) -> std::io::Result { use crate::unicode_reader::CodePoints; match self.stream_inst.0.borrow_mut().1 { @@ -744,18 +641,16 @@ impl Stream { } else { return Err(std::io::Error::new( ErrorKind::UnexpectedEof, - StreamError::PeekCharFailed + StreamError::PeekCharFailed, )); } }; - file.seek(SeekFrom::Current(- (c.len_utf8() as i64)))?; + file.seek(SeekFrom::Current(-(c.len_utf8() as i64)))?; Ok(c) } - StreamInstance::ReadlineStream(ref mut stream) => { - stream.peek_char() - } + StreamInstance::ReadlineStream(ref mut stream) => stream.peek_char(), StreamInstance::TcpStream(_, ref tcp_stream) => { let c = { let mut buf = [0u8; 8]; @@ -768,45 +663,38 @@ impl Stream { } else { return Err(std::io::Error::new( ErrorKind::UnexpectedEof, - StreamError::PeekCharFailed + StreamError::PeekCharFailed, )); } }; Ok(c) } - _ => { - Err(std::io::Error::new( - ErrorKind::PermissionDenied, - StreamError::PeekCharFromNonPeekableStream, - )) - } + _ => Err(std::io::Error::new( + ErrorKind::PermissionDenied, + StreamError::PeekCharFromNonPeekableStream, + )), } } #[inline] - pub(crate) - fn pause_stream(&mut self, buf: Vec>) -> io::Result<()> { + pub(crate) fn pause_stream(&mut self, buf: Vec>) -> io::Result<()> { match self.stream_inst.0.borrow_mut().1 { StreamInstance::PausedPrologStream(ref mut inner_buf, _) => { inner_buf.extend(parser_top_to_bytes(buf)?.into_iter()); return Ok(()); } - _ => { - } + _ => {} } if !buf.is_empty() { - let stream_inst = mem::replace( - &mut self.stream_inst.0.borrow_mut().1, - StreamInstance::Null, - ); + let stream_inst = + mem::replace(&mut self.stream_inst.0.borrow_mut().1, StreamInstance::Null); - self.stream_inst.0.borrow_mut().1 = - StreamInstance::PausedPrologStream( - parser_top_to_bytes(buf)?, - Box::new(stream_inst), - ); + self.stream_inst.0.borrow_mut().1 = StreamInstance::PausedPrologStream( + parser_top_to_bytes(buf)?, + Box::new(stream_inst), + ); } Ok(()) @@ -815,8 +703,7 @@ impl Stream { impl MachineState { #[inline] - pub(crate) - fn eof_action( + pub(crate) fn eof_action( &mut self, result: Addr, stream: &mut Stream, @@ -829,14 +716,12 @@ impl MachineState { return Err(self.open_past_eos_error(stream.clone(), caller, arity)); } EOFAction::EOFCode => { - let end_of_stream = - if stream.options.stream_type == StreamType::Binary { - Addr::Fixnum(-1) - } else { - self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("end_of_file"), None) - ) - }; + let end_of_stream = if stream.options.stream_type == StreamType::Binary { + Addr::Fixnum(-1) + } else { + self.heap + .to_unifiable(HeapCellValue::Atom(clause_name!("end_of_file"), None)) + }; stream.set_past_end_of_stream(); Ok(self.unify(result, end_of_stream)) @@ -851,114 +736,106 @@ impl MachineState { } } - pub(crate) - fn to_stream_options( + pub(crate) fn to_stream_options( &self, alias: Addr, eof_action: Addr, reposition: Addr, stream_type: Addr, ) -> StreamOptions { - let alias = - match self.store(self.deref(alias)) { - Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { - Some(name.clone()) - } else { - unreachable!() - } - } - _ => { - None - } - }; - - let eof_action = - match self.store(self.deref(eof_action)) { - Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { - match name.as_str() { - "eof_code" => EOFAction::EOFCode, - "error" => EOFAction::Error, - "reset" => EOFAction::Reset, - _ => unreachable!(), - } - } else { - unreachable!() - } - } - _ => { + let alias = match self.store(self.deref(alias)) { + Addr::Con(h) if self.heap.atom_at(h) => { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + Some(name.clone()) + } else { unreachable!() } - }; + } + _ => None, + }; - let reposition = - match self.store(self.deref(reposition)) { - Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { - name.as_str() == "true" - } else { - unreachable!() + let eof_action = match self.store(self.deref(eof_action)) { + Addr::Con(h) if self.heap.atom_at(h) => { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + match name.as_str() { + "eof_code" => EOFAction::EOFCode, + "error" => EOFAction::Error, + "reset" => EOFAction::Reset, + _ => unreachable!(), } - } - _ => { + } else { unreachable!() } - }; + } + _ => { + unreachable!() + } + }; - let stream_type = - match self.store(self.deref(stream_type)) { - Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { - match name.as_str() { - "text" => StreamType::Text, - "binary" => StreamType::Binary, - _ => unreachable!() - } - } else { - unreachable!() - } - } - _ => { + let reposition = match self.store(self.deref(reposition)) { + Addr::Con(h) if self.heap.atom_at(h) => { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + name.as_str() == "true" + } else { unreachable!() } - }; + } + _ => { + unreachable!() + } + }; + + let stream_type = match self.store(self.deref(stream_type)) { + Addr::Con(h) if self.heap.atom_at(h) => { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + match name.as_str() { + "text" => StreamType::Text, + "binary" => StreamType::Binary, + _ => unreachable!(), + } + } else { + unreachable!() + } + } + _ => { + unreachable!() + } + }; let mut options = StreamOptions::default(); options.stream_type = stream_type; - options.reposition = reposition; + options.reposition = reposition; options.alias = alias; options.eof_action = eof_action; options } - pub(crate) - fn get_stream_or_alias( + pub(crate) fn get_stream_or_alias( &mut self, addr: Addr, indices: &IndexStore, caller: &'static str, arity: usize, - ) -> Result - { + ) -> Result { Ok(match self.store(self.deref(addr)) { Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref atom, ref spec) = self.heap.clone(h) { + if let HeapCellValue::Atom(ref atom, ref spec) = self.heap.clone(h) { match indices.stream_aliases.get(atom) { - Some(stream) if !stream.is_null_stream() => { - stream.clone() - } + Some(stream) if !stream.is_null_stream() => stream.clone(), _ => { let stub = MachineError::functor_stub(clause_name!(caller), arity); - let addr = self.heap.to_unifiable( - HeapCellValue::Atom(atom.clone(), spec.clone()) - ); + let addr = self + .heap + .to_unifiable(HeapCellValue::Atom(atom.clone(), spec.clone())); return Err(self.error_form( - MachineError::existence_error(self.heap.h(), ExistenceError::Stream(addr)), + MachineError::existence_error( + self.heap.h(), + ExistenceError::Stream(addr), + ), stub, )); } @@ -970,11 +847,7 @@ impl MachineState { Addr::Stream(h) => { if let HeapCellValue::Stream(ref stream) = &self.heap[h] { if stream.is_null_stream() { - return Err(self.open_permission_error( - Addr::Stream(h), - caller, - arity, - )); + return Err(self.open_permission_error(Addr::Stream(h), caller, arity)); } else { stream.clone() } @@ -986,10 +859,7 @@ impl MachineState { let stub = MachineError::functor_stub(clause_name!(caller), arity); if addr.is_ref() { - return Err(self.error_form( - MachineError::instantiation_error(), - stub, - )); + return Err(self.error_form(MachineError::instantiation_error(), stub)); } else { return Err(self.error_form( MachineError::domain_error(DomainErrorType::StreamOrAlias, addr), @@ -1000,31 +870,24 @@ impl MachineState { }) } - pub(crate) - fn open_parsing_stream( + pub(crate) fn open_parsing_stream( &self, stream: Stream, stub_name: &'static str, stub_arity: usize, ) -> Result { match parsing_stream(stream) { - Ok(parsing_stream) => { - Ok(parsing_stream) - } + Ok(parsing_stream) => Ok(parsing_stream), Err(e) => { let stub = MachineError::functor_stub(clause_name!(stub_name), stub_arity); - let err = MachineError::session_error( - self.heap.h(), - SessionError::from(e), - ); + let err = MachineError::session_error(self.heap.h(), SessionError::from(e)); Err(self.error_form(err, stub)) } } } - pub(crate) - fn stream_permission_error( + pub(crate) fn stream_permission_error( &self, perm: Permission, err_string: &'static str, @@ -1033,23 +896,15 @@ impl MachineState { arity: usize, ) -> MachineStub { let stub = MachineError::functor_stub(caller, arity); - let payload = vec![ - HeapCellValue::Stream(stream) - ]; + let payload = vec![HeapCellValue::Stream(stream)]; - let err = MachineError::permission_error( - self.heap.h(), - perm, - err_string, - payload, - ); + let err = MachineError::permission_error(self.heap.h(), perm, err_string, payload); return self.error_form(err, stub); } #[inline] - pub(crate) - fn open_past_eos_error( + pub(crate) fn open_past_eos_error( &self, stream: Stream, caller: ClauseName, @@ -1064,26 +919,20 @@ impl MachineState { ) } - pub(crate) - fn open_permission_error( + pub(crate) fn open_permission_error( &self, culprit: T, stub_name: &'static str, stub_arity: usize, ) -> MachineStub { let stub = MachineError::functor_stub(clause_name!(stub_name), stub_arity); - let err = MachineError::permission_error( - self.heap.h(), - Permission::Open, - "source_sink", - culprit, - ); + let err = + MachineError::permission_error(self.heap.h(), Permission::Open, "source_sink", culprit); return self.error_form(err, stub); } - pub(crate) - fn occupied_alias_permission_error( + pub(crate) fn occupied_alias_permission_error( &self, alias: ClauseName, stub_name: &'static str, @@ -1100,8 +949,7 @@ impl MachineState { return self.error_form(err, stub); } - pub(crate) - fn reposition_error( + pub(crate) fn reposition_error( &self, stub_name: &'static str, stub_arity: usize, @@ -1119,9 +967,7 @@ impl MachineState { return self.error_form(err, stub); } - - pub(crate) - fn check_stream_properties( + pub(crate) fn check_stream_properties( &mut self, stream: &mut Stream, expected_type: StreamType, @@ -1129,19 +975,21 @@ impl MachineState { caller: ClauseName, arity: usize, ) -> CallResult { - let opt_err = - if input.is_some() && !stream.is_input_stream() { - Some("stream") // 8.14.2.3 g) - } else if input.is_none() && !stream.is_output_stream() { - Some("stream") // 8.14.2.3 g) - } else if stream.options.stream_type != expected_type { - Some(expected_type.other().as_str()) // 8.14.2.3 h) - } else { - None - }; + let opt_err = if input.is_some() && !stream.is_input_stream() { + Some("stream") // 8.14.2.3 g) + } else if input.is_none() && !stream.is_output_stream() { + Some("stream") // 8.14.2.3 g) + } else if stream.options.stream_type != expected_type { + Some(expected_type.other().as_str()) // 8.14.2.3 h) + } else { + None + }; - let permission = - if input.is_some() { Permission::InputStream } else { Permission::OutputStream }; + let permission = if input.is_some() { + Permission::InputStream + } else { + Permission::OutputStream + }; if let Some(err_string) = opt_err { return Err(self.stream_permission_error( @@ -1155,12 +1003,7 @@ impl MachineState { if let Some(input) = input { if stream.past_end_of_stream() { - self.eof_action( - input, - stream, - caller, - arity, - )?; + self.eof_action(input, stream, caller, arity)?; } } @@ -1180,61 +1023,37 @@ impl Read for Stream { impl Write for Stream { fn write(&mut self, buf: &[u8]) -> std::io::Result { match self.stream_inst.0.borrow_mut().1 { - StreamInstance::OutputFile(_, ref mut file, _) => { - file.write(buf) - } - StreamInstance::TcpStream(_, ref mut tcp_stream) => { - tcp_stream.write(buf) - } - StreamInstance::TlsStream(_, ref mut tls_stream) => { - tls_stream.write(buf) - } - StreamInstance::Bytes(ref mut cursor) => { - cursor.write(buf) - } - StreamInstance::Stdout => { - stdout().write(buf) - } - StreamInstance::PausedPrologStream(..) | - StreamInstance::StaticStr(_) | - StreamInstance::ReadlineStream(_) | - StreamInstance::InputFile(..) | - StreamInstance::Null => { - Err(std::io::Error::new( - ErrorKind::PermissionDenied, - StreamError::WriteToInputStream, - )) - } + StreamInstance::OutputFile(_, ref mut file, _) => file.write(buf), + StreamInstance::TcpStream(_, ref mut tcp_stream) => tcp_stream.write(buf), + StreamInstance::TlsStream(_, ref mut tls_stream) => tls_stream.write(buf), + StreamInstance::Bytes(ref mut cursor) => cursor.write(buf), + StreamInstance::Stdout => stdout().write(buf), + StreamInstance::PausedPrologStream(..) + | StreamInstance::StaticStr(_) + | StreamInstance::ReadlineStream(_) + | StreamInstance::InputFile(..) + | StreamInstance::Null => Err(std::io::Error::new( + ErrorKind::PermissionDenied, + StreamError::WriteToInputStream, + )), } } fn flush(&mut self) -> std::io::Result<()> { match self.stream_inst.0.borrow_mut().1 { - StreamInstance::OutputFile(_, ref mut file, _) => { - file.flush() - } - StreamInstance::TcpStream(_, ref mut tcp_stream) => { - tcp_stream.flush() - } - StreamInstance::TlsStream(_, ref mut tls_stream) => { - tls_stream.flush() - } - StreamInstance::Bytes(ref mut cursor) => { - cursor.flush() - } - StreamInstance::Stdout => { - stdout().flush() - } - StreamInstance::PausedPrologStream(..) | - StreamInstance::StaticStr(_) | - StreamInstance::ReadlineStream(_) | - StreamInstance::InputFile(..) | - StreamInstance::Null => { - Err(std::io::Error::new( - ErrorKind::PermissionDenied, - StreamError::FlushToInputStream, - )) - } + StreamInstance::OutputFile(_, ref mut file, _) => file.flush(), + StreamInstance::TcpStream(_, ref mut tcp_stream) => tcp_stream.flush(), + StreamInstance::TlsStream(_, ref mut tls_stream) => tls_stream.flush(), + StreamInstance::Bytes(ref mut cursor) => cursor.flush(), + StreamInstance::Stdout => stdout().flush(), + StreamInstance::PausedPrologStream(..) + | StreamInstance::StaticStr(_) + | StreamInstance::ReadlineStream(_) + | StreamInstance::InputFile(..) + | StreamInstance::Null => Err(std::io::Error::new( + ErrorKind::PermissionDenied, + StreamError::FlushToInputStream, + )), } } } diff --git a/src/machine/system_calls.rs b/src/machine/system_calls.rs index 03aa1244..81bf2da5 100644 --- a/src/machine/system_calls.rs +++ b/src/machine/system_calls.rs @@ -1,6 +1,14 @@ use crate::prolog_parser_rebis::ast::*; use crate::prolog_parser_rebis::parser::*; use crate::prolog_parser_rebis::tabled_rc::*; +use crate::prolog_parser_rebis::{ + alpha_char, alpha_numeric_char, backslash_char, binary_digit_char, char_class, clause_name, + decimal_digit_char, exponent_char, graphic_char, graphic_token_char, hexadecimal_digit_char, + layout_char, meta_char, new_line_char, octal_digit_char, prolog_char, sign_char, solo_char, + symbolic_control_char, symbolic_hexadecimal_char, temp_v, +}; + +use crate::lazy_static::lazy_static; use crate::clause_types::*; use crate::forms::*; @@ -8,8 +16,8 @@ use crate::heap_print::*; use crate::instructions::*; use crate::machine; use crate::machine::code_repo::CodeRepo; -use crate::machine::copier::*; use crate::machine::code_walker::*; +use crate::machine::copier::*; use crate::machine::machine_errors::*; use crate::machine::machine_indices::*; use crate::machine::machine_state::*; @@ -25,32 +33,35 @@ use crate::indexmap::IndexSet; use crate::ref_thread_local::RefThreadLocal; use std::cmp; -use std::fs; use std::collections::BTreeSet; use std::convert::TryFrom; +use std::env; +use std::fs; use std::io::{ErrorKind, Read, Write}; use std::iter::{once, FromIterator}; use std::net::{TcpListener, TcpStream}; +use std::num::NonZeroU32; use std::ops::Sub; use std::rc::Rc; -use std::num::NonZeroU32; -use std::env; -use std::time::{Duration, SystemTime}; +use crate::chrono::{offset::Local, DateTime}; use crate::cpu_time::ProcessTime; -use crate::chrono::{offset::Local,DateTime}; +use std::time::{Duration, SystemTime}; use crate::crossterm::event::{read, Event, KeyCode, KeyEvent, KeyModifiers}; -use crate::crossterm::terminal::{enable_raw_mode, disable_raw_mode}; +use crate::crossterm::terminal::{disable_raw_mode, enable_raw_mode}; +use crate::blake2::{Blake2b, Blake2s}; use crate::ring::rand::{SecureRandom, SystemRandom}; -use crate::ring::{digest,hkdf,pbkdf2,aead,signature::{self,KeyPair}}; -use crate::ripemd160::{Ripemd160, Digest}; +use crate::ring::{ + aead, digest, hkdf, pbkdf2, + signature::{self, KeyPair}, +}; +use crate::ripemd160::{Digest, Ripemd160}; use crate::sha3::{Sha3_224, Sha3_256, Sha3_384, Sha3_512}; -use crate::blake2::{Blake2s, Blake2b}; -use crate::openssl::ec::{EcGroup, EcPoint}; use crate::openssl::bn::{BigNum, BigNumContext}; +use crate::openssl::ec::{EcGroup, EcPoint}; use crate::openssl::nid::Nid; use sodiumoxide::crypto::scalarmult::curve25519::*; @@ -58,8 +69,9 @@ use sodiumoxide::crypto::scalarmult::curve25519::*; use crate::native_tls::TlsConnector; extern crate select; -use roxmltree; + use base64; +use roxmltree; pub fn get_key() -> KeyEvent { let key; @@ -72,8 +84,8 @@ pub fn get_key() -> KeyEvent { KeyCode::Char(_) | KeyCode::Enter | KeyCode::Tab => { key = key_; break; - }, - _ => () + } + _ => (), } } } @@ -125,15 +137,9 @@ impl BrentAlgState { addr @ Addr::HeapCell(_) | addr @ Addr::StackCell(..) | addr @ Addr::AttrVar(_) => { CycleSearchResult::PartialList(self.steps, addr.as_var().unwrap()) } - Addr::PStrLocation(h, n) => { - CycleSearchResult::PStrLocation(self.steps, h, n) - } - Addr::EmptyList => { - CycleSearchResult::ProperList(self.steps) - } - _ => { - CycleSearchResult::NotList - } + Addr::PStrLocation(h, n) => CycleSearchResult::PStrLocation(self.steps, h, n), + Addr::EmptyList => CycleSearchResult::ProperList(self.steps), + _ => CycleSearchResult::NotList, } } } @@ -149,50 +155,37 @@ impl MachineState { // a step in Brent's algorithm. fn brents_alg_step(&self, brent_st: &mut BrentAlgState) -> Option { match self.store(self.deref(brent_st.hare)) { - Addr::EmptyList => { - Some(CycleSearchResult::ProperList(brent_st.steps)) - } + Addr::EmptyList => Some(CycleSearchResult::ProperList(brent_st.steps)), addr @ Addr::HeapCell(_) | addr @ Addr::StackCell(..) | addr @ Addr::AttrVar(_) => { Some(CycleSearchResult::PartialList( brent_st.steps, addr.as_var().unwrap(), )) } - Addr::PStrLocation(h, n) => { - match &self.heap[h] { - HeapCellValue::PartialString(ref pstr, _) => { - if let Some(c) = pstr.range_from(n ..).next() { - brent_st.step(Addr::PStrLocation(h, n + c.len_utf8())) - } else { - unreachable!() - } - } - _ => { + Addr::PStrLocation(h, n) => match &self.heap[h] { + HeapCellValue::PartialString(ref pstr, _) => { + if let Some(c) = pstr.range_from(n..).next() { + brent_st.step(Addr::PStrLocation(h, n + c.len_utf8())) + } else { unreachable!() } } - } - Addr::Lis(l) => { - brent_st.step(Addr::HeapCell(l + 1)) - } - _ => { - Some(CycleSearchResult::NotList) - } + _ => { + unreachable!() + } + }, + Addr::Lis(l) => brent_st.step(Addr::HeapCell(l + 1)), + _ => Some(CycleSearchResult::NotList), } } - pub(super) - fn detect_cycles_with_max(&self, max_steps: usize, addr: Addr) -> CycleSearchResult { + pub(super) fn detect_cycles_with_max(&self, max_steps: usize, addr: Addr) -> CycleSearchResult { let hare = match self.store(self.deref(addr)) { - Addr::Lis(offset) if max_steps > 0 => { - Addr::Lis(offset) - } + Addr::Lis(offset) if max_steps > 0 => Addr::Lis(offset), Addr::Lis(offset) => { return CycleSearchResult::UntouchedList(offset); } - Addr::PStrLocation(h, n) if max_steps > 0 => { - Addr::PStrLocation(h, n) - } + Addr::PStrLocation(h, n) if max_steps > 0 => Addr::PStrLocation(h, n), Addr::PStrLocation(h, _) => { return CycleSearchResult::UntouchedList(h); } @@ -231,19 +224,14 @@ impl MachineState { } } - pub(super) - fn detect_cycles(&self, addr: Addr) -> CycleSearchResult { + pub(super) fn detect_cycles(&self, addr: Addr) -> CycleSearchResult { let addr = self.store(self.deref(addr)); let hare = match addr { - Addr::Lis(offset) => { - Addr::Lis(offset) - } + Addr::Lis(offset) => Addr::Lis(offset), Addr::EmptyList => { return CycleSearchResult::EmptyList; } - Addr::PStrLocation(h, n) => { - Addr::PStrLocation(h, n) - } + Addr::PStrLocation(h, n) => Addr::PStrLocation(h, n), Addr::Con(h) => { if let HeapCellValue::PartialString(..) = &self.heap[h] { Addr::PStrLocation(h, 0) @@ -276,33 +264,23 @@ impl MachineState { } fn skip_max_list_result(&mut self, max_steps: Option) { - let search_result = - if let Some(max_steps) = max_steps { - if max_steps == -1 { - self.detect_cycles(self[temp_v!(3)]) - } else { - self.detect_cycles_with_max( - max_steps as usize, - self[temp_v!(3)], - ) - } - } else { + let search_result = if let Some(max_steps) = max_steps { + if max_steps == -1 { self.detect_cycles(self[temp_v!(3)]) - }; + } else { + self.detect_cycles_with_max(max_steps as usize, self[temp_v!(3)]) + } + } else { + self.detect_cycles(self[temp_v!(3)]) + }; match search_result { CycleSearchResult::PStrLocation(steps, h, n) => { self.finalize_skip_max_list(steps, Addr::PStrLocation(h, n)); } - CycleSearchResult::UntouchedList(l) => { - self.finalize_skip_max_list(0, Addr::Lis(l)) - } - CycleSearchResult::EmptyList => { - self.finalize_skip_max_list(0, Addr::EmptyList) - } - CycleSearchResult::PartialList(n, r) => { - self.finalize_skip_max_list(n, r.as_addr()) - } + CycleSearchResult::UntouchedList(l) => self.finalize_skip_max_list(0, Addr::Lis(l)), + CycleSearchResult::EmptyList => self.finalize_skip_max_list(0, Addr::EmptyList), + CycleSearchResult::PartialList(n, r) => self.finalize_skip_max_list(n, r.as_addr()), CycleSearchResult::ProperList(steps) => { self.finalize_skip_max_list(steps, Addr::EmptyList) } @@ -313,8 +291,7 @@ impl MachineState { }; } - pub(super) - fn skip_max_list(&mut self) -> CallResult { + pub(super) fn skip_max_list(&mut self) -> CallResult { let max_steps = self.store(self.deref(self[temp_v!(2)])); match max_steps { @@ -323,12 +300,11 @@ impl MachineState { return Err(self.error_form(MachineError::instantiation_error(), stub)); } addr => { - let max_steps_n = - match Number::try_from((max_steps, &self.heap)) { - Ok(Number::Integer(n)) => n.to_isize(), - Ok(Number::Fixnum(n)) => Some(n), - _ => None, - }; + let max_steps_n = match Number::try_from((max_steps, &self.heap)) { + Ok(Number::Integer(n)) => n.to_isize(), + Ok(Number::Fixnum(n)) => Some(n), + _ => None, + }; if max_steps_n.map(|i| i >= -1).unwrap_or(false) { let n = self.store(self.deref(self[temp_v!(1)])); @@ -337,7 +313,7 @@ impl MachineState { Ok(Number::Integer(n)) => { if n.as_ref() == &0 { let xs0 = self[temp_v!(3)]; - let xs = self[temp_v!(4)]; + let xs = self[temp_v!(4)]; self.unify(xs0, xs); } else { @@ -347,7 +323,7 @@ impl MachineState { Ok(Number::Fixnum(n)) => { if n == 0 { let xs0 = self[temp_v!(3)]; - let xs = self[temp_v!(4)]; + let xs = self[temp_v!(4)]; self.unify(xs0, xs); } else { @@ -360,16 +336,10 @@ impl MachineState { } } else { let stub = MachineError::functor_stub(clause_name!("$skip_max_list"), 4); - return Err( - self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - addr - ), - stub, - ) - ); + return Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, addr), + stub, + )); } } } @@ -385,10 +355,7 @@ impl MachineState { ) -> Result { if file_spec.as_str().is_empty() { let stub = MachineError::functor_stub(clause_name!("open"), 4); - let err = MachineError::domain_error( - DomainErrorType::SourceSink, - self[temp_v!(1)], - ); + let err = MachineError::domain_error(DomainErrorType::SourceSink, self[temp_v!(1)]); return Err(self.error_form(err, stub)); } @@ -396,84 +363,72 @@ impl MachineState { // 8.11.5.3l) if let Some(ref alias) = &options.alias { if indices.stream_aliases.contains_key(alias) { - return Err(self.occupied_alias_permission_error( - alias.clone(), - "open", - 4, - )); + return Err(self.occupied_alias_permission_error(alias.clone(), "open", 4)); } } let mode = atom_from!(self, self.store(self.deref(self[temp_v!(2)]))); let mut open_options = fs::OpenOptions::new(); - let (is_input_file, in_append_mode) = - match mode.as_str() { - "read" => { - open_options.read(true).write(false).create(false); - (true, false) - } - "write" => { - open_options.read(false).write(true).truncate(true).create(true); - (false, false) - } - "append" => { - open_options.read(false).write(true).create(true).append(true); - (false, true) - } - _ => { - let stub = MachineError::functor_stub(clause_name!("open"), 4); - let err = MachineError::domain_error( - DomainErrorType::IOMode, - self[temp_v!(2)], - ); + let (is_input_file, in_append_mode) = match mode.as_str() { + "read" => { + open_options.read(true).write(false).create(false); + (true, false) + } + "write" => { + open_options + .read(false) + .write(true) + .truncate(true) + .create(true); + (false, false) + } + "append" => { + open_options + .read(false) + .write(true) + .create(true) + .append(true); + (false, true) + } + _ => { + let stub = MachineError::functor_stub(clause_name!("open"), 4); + let err = MachineError::domain_error(DomainErrorType::IOMode, self[temp_v!(2)]); - // 8.11.5.3h) - return Err(self.error_form(err, stub)); - } - }; + // 8.11.5.3h) + return Err(self.error_form(err, stub)); + } + }; - let file = - match open_options.open(file_spec.as_str()) { - Ok(file) => { - file - } - Err(err) => { - match err.kind() { - ErrorKind::NotFound => { - // 8.11.5.3j) - let stub = MachineError::functor_stub( - clause_name!("open"), - 4, - ); + let file = match open_options.open(file_spec.as_str()) { + Ok(file) => file, + Err(err) => { + match err.kind() { + ErrorKind::NotFound => { + // 8.11.5.3j) + let stub = MachineError::functor_stub(clause_name!("open"), 4); - let err = MachineError::existence_error( - self.heap.h(), - ExistenceError::SourceSink(self[temp_v!(1)]), - ); + let err = MachineError::existence_error( + self.heap.h(), + ExistenceError::SourceSink(self[temp_v!(1)]), + ); - return Err(self.error_form(err, stub)); - } - ErrorKind::PermissionDenied => { - // 8.11.5.3k) - return Err(self.open_permission_error(self[temp_v!(1)], "open", 4)); - } - _ => { - let stub = MachineError::functor_stub( - clause_name!("open"), - 4, - ); + return Err(self.error_form(err, stub)); + } + ErrorKind::PermissionDenied => { + // 8.11.5.3k) + return Err(self.open_permission_error(self[temp_v!(1)], "open", 4)); + } + _ => { + let stub = MachineError::functor_stub(clause_name!("open"), 4); - let err = MachineError::syntax_error( - self.heap.h(), - ParserError::IO(err), - ); + let err = MachineError::syntax_error(self.heap.h(), ParserError::IO(err)); - return Err(self.error_form(err, stub)); - } + return Err(self.error_form(err, stub)); } } - }; + } + }; Ok(if is_input_file { Stream::from_file_as_input(file_spec, file) @@ -496,11 +451,8 @@ impl MachineState { fn copy_findall_solution(&mut self, lh_offset: usize, copy_target: Addr) -> usize { let threshold = self.lifted_heap.h() - lh_offset; - let mut copy_ball_term = CopyBallTerm::new( - &mut self.stack, - &mut self.heap, - &mut self.lifted_heap, - ); + let mut copy_ball_term = + CopyBallTerm::new(&mut self.stack, &mut self.heap, &mut self.lifted_heap); copy_ball_term.push(HeapCellValue::Addr(Addr::Lis(threshold + 1))); copy_ball_term.push(HeapCellValue::Addr(Addr::HeapCell(threshold + 3))); @@ -531,7 +483,8 @@ impl MachineState { self.lifted_heap.truncate(lh_offset); } else { let threshold = self.lifted_heap.h() - lh_offset; - self.lifted_heap.push(HeapCellValue::Addr(addr_constr(threshold))); + self.lifted_heap + .push(HeapCellValue::Addr(addr_constr(threshold))); } } _ => self.fail = true, @@ -563,13 +516,13 @@ impl MachineState { &CompositeOpDir::new(&indices.op_dir, None), ); - let addr = self.heap.to_unifiable(HeapCellValue::DBRef( - DBRef::NamedPred( + let addr = self + .heap + .to_unifiable(HeapCellValue::DBRef(DBRef::NamedPred( name.clone(), *arity, spec, - ) - )); + ))); self.bind(r, addr); @@ -593,17 +546,13 @@ impl MachineState { let a2 = self[temp_v!(2)]; if let Some(r) = a2.as_var() { - let addr = self.heap.to_unifiable( - HeapCellValue::DBRef( - DBRef::Op( - *priority, - *spec, - name.clone(), - op_dir.clone(), - SharedOpDesc::new(*priority, *spec) - ), - ), - ); + let addr = self.heap.to_unifiable(HeapCellValue::DBRef(DBRef::Op( + *priority, + *spec, + name.clone(), + op_dir.clone(), + SharedOpDesc::new(*priority, *spec), + ))); self.bind(r, addr); } else { @@ -621,8 +570,7 @@ impl MachineState { n: &Integer, stub: &'static str, arity: usize, - ) -> Result - { + ) -> Result { let c = n.to_u32().and_then(std::char::from_u32); if let Some(c) = c { @@ -664,26 +612,16 @@ impl MachineState { string.push('.'); - let mut stream = - match parsing_stream(std::io::Cursor::new(string)) { - Ok(stream) => { - stream - } - Err(e) => { - let err = MachineError::session_error( - self.heap.h(), - SessionError::from(e), - ); + let mut stream = match parsing_stream(std::io::Cursor::new(string)) { + Ok(stream) => stream, + Err(e) => { + let err = MachineError::session_error(self.heap.h(), SessionError::from(e)); - return Err(self.error_form(err, stub)); - } - }; + return Err(self.error_form(err, stub)); + } + }; - let mut parser = Parser::new( - &mut stream, - self.atom_tbl.clone(), - self.machine_flags(), - ); + let mut parser = Parser::new(&mut stream, self.atom_tbl.clone(), self.machine_flags()); match parser.read_term(&CompositeOpDir::new(&indices.op_dir, None)) { Err(err) => { @@ -743,7 +681,7 @@ impl MachineState { match &self.heap[s] { HeapCellValue::NamedStr(arity, ..) => { let num_cells = arity - 1; - let p_functor = self.heap[s+1].as_addr(s+1); + let p_functor = self.heap[s + 1].as_addr(s + 1); let cp = self.heap.to_local_code_ptr(&p_functor).unwrap(); let prev_e = self.e; @@ -751,37 +689,36 @@ impl MachineState { let e = self.stack.allocate_and_frame(num_cells); let and_frame = self.stack.index_and_frame_mut(e); - and_frame.prelude.e = prev_e; + and_frame.prelude.e = prev_e; and_frame.prelude.cp = return_p; self.p = CodePtr::Local(cp + 1); // adjust cut point to occur after call_continuation. if num_cells > 0 { - if let Addr::CutPoint(_) = self.heap[s+2].as_addr(s+2) { + if let Addr::CutPoint(_) = self.heap[s + 2].as_addr(s + 2) { and_frame[1] = Addr::CutPoint(self.b); } else { - and_frame[1] = self.heap[s+2].as_addr(s+2); + and_frame[1] = self.heap[s + 2].as_addr(s + 2); } } - for index in s+3 .. s+2+num_cells { - and_frame[index - (s+1)] = self.heap[index].as_addr(index); + for index in s + 3..s + 2 + num_cells { + and_frame[index - (s + 1)] = self.heap[index].as_addr(index); } self.e = e; self.p.local() } - _ => unreachable!() + _ => unreachable!(), } } - _ => unreachable!() + _ => unreachable!(), } } - pub(super) - fn system_call( + pub(super) fn system_call( &mut self, ct: &SystemClauseType, code_repo: &CodeRepo, @@ -794,23 +731,18 @@ impl MachineState { match ct { &SystemClauseType::BindFromRegister => { let reg = self.store(self.deref(self[temp_v!(2)])); - let n = - match Number::try_from((reg, &self.heap)) { - Ok(Number::Integer(n)) => { - n.to_usize() - } - Ok(Number::Fixnum(n)) => { - usize::try_from(n).ok() - } - _ => { - unreachable!() - } - }; + let n = match Number::try_from((reg, &self.heap)) { + Ok(Number::Integer(n)) => n.to_usize(), + Ok(Number::Fixnum(n)) => usize::try_from(n).ok(), + _ => { + unreachable!() + } + }; if let Some(n) = n { if n <= MAX_ARITY { let target = self[temp_v!(n)]; - let addr = self[temp_v!(1)]; + let addr = self[temp_v!(1)]; self.unify(addr, target); return return_from_clause!(self.last_call, self); @@ -821,22 +753,19 @@ impl MachineState { } &SystemClauseType::CurrentHostname => { match hostname::get().ok() { - Some(host) => { - match host.into_string().ok() { - Some(host) => { - let hostname = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!(host, self.atom_tbl), None) - ); + Some(host) => match host.into_string().ok() { + Some(host) => { + let hostname = self.heap.to_unifiable(HeapCellValue::Atom( + clause_name!(host, self.atom_tbl), + None, + )); - self.unify(self[temp_v!(1)], hostname); - return return_from_clause!(self.last_call, self); - } - None => { - } + self.unify(self[temp_v!(1)], hostname); + return return_from_clause!(self.last_call, self); } - } - None => { - } + None => {} + }, + None => {} } self.fail = true; @@ -860,15 +789,9 @@ impl MachineState { } } addr => { - let stub = MachineError::functor_stub( - clause_name!("current_input"), - 1, - ); + let stub = MachineError::functor_stub(clause_name!("current_input"), 1); - let err = MachineError::domain_error( - DomainErrorType::Stream, - addr, - ); + let err = MachineError::domain_error(DomainErrorType::Stream, addr); return Err(self.error_form(err, stub)); } @@ -891,15 +814,9 @@ impl MachineState { } } addr => { - let stub = MachineError::functor_stub( - clause_name!("current_input"), - 1, - ); + let stub = MachineError::functor_stub(clause_name!("current_input"), 1); - let err = MachineError::domain_error( - DomainErrorType::Stream, - addr, - ); + let err = MachineError::domain_error(DomainErrorType::Stream, addr); return Err(self.error_form(err, stub)); } @@ -914,10 +831,16 @@ impl MachineState { for entry in entries { if let Ok(entry) = entry { match entry.file_name().into_string() { - Ok(name) => { files.push(self.heap.put_complete_string(&name)); } + Ok(name) => { + files.push(self.heap.put_complete_string(&name)); + } _ => { - let stub = MachineError::functor_stub(clause_name!("directory_files"), 2); - let err = MachineError::representation_error(RepFlag::Character); + let stub = MachineError::functor_stub( + clause_name!("directory_files"), + 2, + ); + let err = + MachineError::representation_error(RepFlag::Character); let err = self.error_form(err, stub); return Err(err); @@ -940,29 +863,35 @@ impl MachineState { } &SystemClauseType::FileExists => { let file = self.heap_pstr_iter(self[temp_v!(1)]).to_string(); - if !std::path::Path::new(&file).exists() || !fs::metadata(&file).unwrap().is_file() { + if !std::path::Path::new(&file).exists() || !fs::metadata(&file).unwrap().is_file() + { self.fail = true; return Ok(()); } } &SystemClauseType::DirectoryExists => { let directory = self.heap_pstr_iter(self[temp_v!(1)]).to_string(); - if !std::path::Path::new(&directory).exists() || !fs::metadata(&directory).unwrap().is_dir() { + if !std::path::Path::new(&directory).exists() + || !fs::metadata(&directory).unwrap().is_dir() + { self.fail = true; return Ok(()); } } &SystemClauseType::DirectorySeparator => { - let addr = self.heap.put_constant(Constant::Char(std::path::MAIN_SEPARATOR)); + let addr = self + .heap + .put_constant(Constant::Char(std::path::MAIN_SEPARATOR)); self.unify(self[temp_v!(1)], addr); } &SystemClauseType::MakeDirectory => { let directory = self.heap_pstr_iter(self[temp_v!(1)]).to_string(); match fs::create_dir(directory) { - Ok(_) => { } - _ => { self.fail = true; - return Ok(()); + Ok(_) => {} + _ => { + self.fail = true; + return Ok(()); } } } @@ -970,24 +899,26 @@ impl MachineState { let file = self.heap_pstr_iter(self[temp_v!(1)]).to_string(); match fs::remove_file(file) { - Ok(_) => { } - _ => { self.fail = true; - return Ok(()); + Ok(_) => {} + _ => { + self.fail = true; + return Ok(()); } } } &SystemClauseType::WorkingDirectory => { if let Ok(dir) = env::current_dir() { - let current = - match dir.to_str() { - Some(d) => { d } - _ => { let stub = MachineError::functor_stub(clause_name!("working_directory"), 2); - let err = MachineError::representation_error(RepFlag::Character); - let err = self.error_form(err, stub); + let current = match dir.to_str() { + Some(d) => d, + _ => { + let stub = + MachineError::functor_stub(clause_name!("working_directory"), 2); + let err = MachineError::representation_error(RepFlag::Character); + let err = self.error_form(err, stub); - return Err(err); - } - }; + return Err(err); + } + }; let chars = self.heap.put_complete_string(current); self.unify(self[temp_v!(1)], chars); @@ -995,9 +926,10 @@ impl MachineState { let next = self.heap_pstr_iter(self[temp_v!(2)]).to_string(); match env::set_current_dir(std::path::Path::new(&next)) { - Ok(_) => { } - _ => { self.fail = true; - return Ok(()); + Ok(_) => {} + _ => { + self.fail = true; + return Ok(()); } } } else { @@ -1010,17 +942,17 @@ impl MachineState { match fs::canonicalize(path) { Ok(canonical) => { - let cs = - match canonical.to_str() { - Some(s) => { s } - _ => { - let stub = MachineError::functor_stub(clause_name!("path_canonical"), 2); - let err = MachineError::representation_error(RepFlag::Character); - let err = self.error_form(err, stub); + let cs = match canonical.to_str() { + Some(s) => s, + _ => { + let stub = + MachineError::functor_stub(clause_name!("path_canonical"), 2); + let err = MachineError::representation_error(RepFlag::Character); + let err = self.error_form(err, stub); - return Err(err); - } - }; + return Err(err); + } + }; let chars = self.heap.put_complete_string(cs); self.unify(self[temp_v!(2)], chars); } @@ -1047,13 +979,14 @@ impl MachineState { }; if let Ok(md) = fs::metadata(file) { - if let Ok(time) = - match which { - "modification" => { md.modified() } - "access" => { md.accessed() } - "creation" => { md.created() } - _ => { unreachable!() } - } { + if let Ok(time) = match which { + "modification" => md.modified(), + "access" => md.accessed(), + "creation" => md.created(), + _ => { + unreachable!() + } + } { let chars = self.systemtime_to_timestamp(time); self.unify(self[temp_v!(3)], chars); } else { @@ -1077,8 +1010,8 @@ impl MachineState { self.unify(a2, list_of_chars); } Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(name, _) = self.heap.clone(h) { - let s = self.heap.put_complete_string(name.as_str()); + if let HeapCellValue::Atom(name, _) = self.heap.clone(h) { + let s = self.heap.put_complete_string(name.as_str()); let a2 = self[temp_v!(2)]; self.unify(s, a2); @@ -1088,13 +1021,9 @@ impl MachineState { } Addr::EmptyList => { let a2 = self[temp_v!(2)]; - let chars = vec![ - Addr::Char('['), - Addr::Char(']'), - ]; + let chars = vec![Addr::Char('['), Addr::Char(']')]; - let list_of_chars = - Addr::HeapCell(self.heap.to_list(chars.into_iter())); + let list_of_chars = Addr::HeapCell(self.heap.to_list(chars.into_iter())); self.unify(a2, list_of_chars); } @@ -1108,19 +1037,16 @@ impl MachineState { self.unify(addr, Addr::EmptyList); } else { let chars = clause_name!(string, self.atom_tbl); - let atom = self.heap.to_unifiable( - HeapCellValue::Atom(chars, None) - ); + let atom = + self.heap.to_unifiable(HeapCellValue::Atom(chars, None)); self.unify(addr, atom); } } focus => { if let Addr::Lis(l) = focus { - let stub = MachineError::functor_stub( - clause_name!("atom_chars"), - 2, - ); + let stub = + MachineError::functor_stub(clause_name!("atom_chars"), 2); let err = MachineError::type_error( self.heap.h(), @@ -1150,13 +1076,10 @@ impl MachineState { self.unify(a2, list_of_codes); } Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(name, _) = self.heap.clone(h) { + if let HeapCellValue::Atom(name, _) = self.heap.clone(h) { let a2 = self.store(self.deref(self[temp_v!(2)])); - let iter = name - .as_str() - .chars() - .map(|c| Addr::Fixnum(c as isize)); + let iter = name.as_str().chars().map(|c| Addr::Fixnum(c as isize)); let list_of_codes = Addr::HeapCell(self.heap.to_list(iter)); @@ -1166,10 +1089,7 @@ impl MachineState { } } Addr::EmptyList => { - let chars = vec![ - Addr::Fixnum('[' as isize), - Addr::Fixnum(']' as isize), - ]; + let chars = vec![Addr::Fixnum('[' as isize), Addr::Fixnum(']' as isize)]; let list_of_codes = Addr::HeapCell(self.heap.to_list(chars.into_iter())); let a2 = self[temp_v!(2)]; @@ -1221,9 +1141,10 @@ impl MachineState { } } - let string = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!(chars, self.atom_tbl), None) - ); + let string = self.heap.to_unifiable(HeapCellValue::Atom( + clause_name!(chars, self.atom_tbl), + None, + )); self.bind(addr.as_var().unwrap(), string); } @@ -1292,22 +1213,17 @@ impl MachineState { Err(e) => { return Err(e); } - Ok(addrs) => { - match self.try_char_list(addrs) { - Ok(string) => { - let stub = MachineError::functor_stub(clause_name!("number_chars"), 2); - self.parse_number_from_string(string, indices, stub)?; - } - Err(err) => { - let stub = MachineError::functor_stub( - clause_name!("number_chars"), - 2, - ); - - return Err(self.error_form(err, stub)); - } + Ok(addrs) => match self.try_char_list(addrs) { + Ok(string) => { + let stub = MachineError::functor_stub(clause_name!("number_chars"), 2); + self.parse_number_from_string(string, indices, stub)?; } - } + Err(err) => { + let stub = MachineError::functor_stub(clause_name!("number_chars"), 2); + + return Err(self.error_form(err, stub)); + } + }, } } &SystemClauseType::CreatePartialString => { @@ -1350,24 +1266,20 @@ impl MachineState { self.fail = true; return Ok(()); } - _ => { - } + _ => {} } let mut heap_pstr_iter = self.heap_pstr_iter(addr); while let Some(_) = heap_pstr_iter.next() {} - self.fail = - match heap_pstr_iter.focus() { - Addr::AttrVar(_) | Addr::HeapCell(_) | Addr::StackCell(..) | - Addr::EmptyList => { - false - } - _ => { - true - } - }; + self.fail = match heap_pstr_iter.focus() { + Addr::AttrVar(_) + | Addr::HeapCell(_) + | Addr::StackCell(..) + | Addr::EmptyList => false, + _ => true, + }; } &SystemClauseType::PartialStringTail => { let pstr = self.store(self.deref(self[temp_v!(1)])); @@ -1422,48 +1334,43 @@ impl MachineState { return return_from_clause!(self.last_call, self); } - let addr = - match self.store(self.deref(self[temp_v!(2)])) { - addr if addr.is_ref() => { - addr - } - addr => { - match Number::try_from((addr, &self.heap)) { - Ok(Number::Integer(n)) => { - if let Some(nb) = n.to_u8() { - Addr::Usize(nb as usize) - } else { - return Err(self.type_error( - ValidType::InByte, - addr, - clause_name!("peek_byte"), - 2, - )); - } - } - Ok(Number::Fixnum(n)) => { - if let Ok(nb) = u8::try_from(n) { - Addr::Usize(nb as usize) - } else { - return Err(self.type_error( - ValidType::InByte, - addr, - clause_name!("peek_byte"), - 2, - )); - } - } - _ => { - return Err(self.type_error( - ValidType::InByte, - addr, - clause_name!("peek_byte"), - 2, - )); - } + let addr = match self.store(self.deref(self[temp_v!(2)])) { + addr if addr.is_ref() => addr, + addr => match Number::try_from((addr, &self.heap)) { + Ok(Number::Integer(n)) => { + if let Some(nb) = n.to_u8() { + Addr::Usize(nb as usize) + } else { + return Err(self.type_error( + ValidType::InByte, + addr, + clause_name!("peek_byte"), + 2, + )); } } - }; + Ok(Number::Fixnum(n)) => { + if let Ok(nb) = u8::try_from(n) { + Addr::Usize(nb as usize) + } else { + return Err(self.type_error( + ValidType::InByte, + addr, + clause_name!("peek_byte"), + 2, + )); + } + } + _ => { + return Err(self.type_error( + ValidType::InByte, + addr, + clause_name!("peek_byte"), + 2, + )); + } + }, + }; loop { match stream.peek_byte().map_err(|e| e.kind()) { @@ -1521,9 +1428,9 @@ impl MachineState { if stream.at_end_of_stream() { let end_of_file = clause_name!("end_of_file"); - let end_of_file = self.heap.to_unifiable( - HeapCellValue::Atom(end_of_file, None), - ); + let end_of_file = self + .heap + .to_unifiable(HeapCellValue::Atom(end_of_file, None)); stream.set_past_end_of_stream(); @@ -1531,42 +1438,35 @@ impl MachineState { return return_from_clause!(self.last_call, self); } - let addr = - match self.store(self.deref(self[temp_v!(2)])) { - addr if addr.is_ref() => { - addr - } - Addr::Con(h) if self.heap.atom_at(h) => { - match &self.heap[h] { - HeapCellValue::Atom(ref atom, _) if atom.is_char() => { - if let Some(c) = atom.as_str().chars().next() { - Addr::Char(c) - } else { - unreachable!() - } - } - culprit => { - return Err(self.type_error( - ValidType::InCharacter, - culprit.as_addr(h), - clause_name!("peek_char"), - 2, - )); - } + let addr = match self.store(self.deref(self[temp_v!(2)])) { + addr if addr.is_ref() => addr, + Addr::Con(h) if self.heap.atom_at(h) => match &self.heap[h] { + HeapCellValue::Atom(ref atom, _) if atom.is_char() => { + if let Some(c) = atom.as_str().chars().next() { + Addr::Char(c) + } else { + unreachable!() } } - Addr::Char(d) => { - Addr::Char(d) - } culprit => { return Err(self.type_error( ValidType::InCharacter, - culprit, + culprit.as_addr(h), clause_name!("peek_char"), 2, )); } - }; + }, + Addr::Char(d) => Addr::Char(d), + culprit => { + return Err(self.type_error( + ValidType::InCharacter, + culprit, + clause_name!("peek_char"), + 2, + )); + } + }; loop { match stream.peek_char().map_err(|e| e.kind()) { @@ -1598,14 +1498,14 @@ impl MachineState { } else if self.fail { return Ok(()); } - }/* - _ => { - let stub = MachineError::functor_stub(clause_name!("peek_char"), 2); - let err = MachineError::representation_error(RepFlag::Character); - let err = self.error_form(err, stub); + } /* + _ => { + let stub = MachineError::functor_stub(clause_name!("peek_char"), 2); + let err = MachineError::representation_error(RepFlag::Character); + let err = self.error_form(err, stub); - return Err(err); - }*/ + return Err(err); + }*/ } } } @@ -1631,9 +1531,9 @@ impl MachineState { if stream.at_end_of_stream() { let end_of_file = clause_name!("end_of_file"); - let end_of_file = self.heap.to_unifiable( - HeapCellValue::Atom(end_of_file, None), - ); + let end_of_file = self + .heap + .to_unifiable(HeapCellValue::Atom(end_of_file, None)); stream.set_past_end_of_stream(); @@ -1641,54 +1541,49 @@ impl MachineState { return return_from_clause!(self.last_call, self); } - let addr = - match self.store(self.deref(self[temp_v!(2)])) { - addr if addr.is_ref() => { - addr - } - addr => { - match Number::try_from((addr, &self.heap)) { - Ok(Number::Integer(n)) => { - let n = n.to_u32().and_then(|n| { - std::char::from_u32(n).and_then(|_| Some(n)) - }); + let addr = match self.store(self.deref(self[temp_v!(2)])) { + addr if addr.is_ref() => addr, + addr => match Number::try_from((addr, &self.heap)) { + Ok(Number::Integer(n)) => { + let n = n + .to_u32() + .and_then(|n| std::char::from_u32(n).and_then(|_| Some(n))); - if let Some(n) = n { - Addr::Fixnum(n as isize) - } else { - return Err(self.representation_error( - RepFlag::InCharacterCode, - clause_name!("peek_code"), - 2, - )); - } - } - Ok(Number::Fixnum(n)) => { - let n = u32::try_from(n).ok().and_then(|n| { - std::char::from_u32(n).and_then(|_| Some(n)) - }); - - if let Some(n) = n { - Addr::Fixnum(n as isize) - } else { - return Err(self.representation_error( - RepFlag::InCharacterCode, - clause_name!("peek_code"), - 2, - )); - } - } - _ => { - return Err(self.type_error( - ValidType::Integer, - self[temp_v!(2)], - clause_name!("peek_code"), - 2, - )); - } + if let Some(n) = n { + Addr::Fixnum(n as isize) + } else { + return Err(self.representation_error( + RepFlag::InCharacterCode, + clause_name!("peek_code"), + 2, + )); } } - }; + Ok(Number::Fixnum(n)) => { + let n = u32::try_from(n) + .ok() + .and_then(|n| std::char::from_u32(n).and_then(|_| Some(n))); + + if let Some(n) = n { + Addr::Fixnum(n as isize) + } else { + return Err(self.representation_error( + RepFlag::InCharacterCode, + clause_name!("peek_code"), + 2, + )); + } + } + _ => { + return Err(self.type_error( + ValidType::Integer, + self[temp_v!(2)], + clause_name!("peek_code"), + 2, + )); + } + }, + }; loop { let result = stream.peek_char(); @@ -1722,7 +1617,8 @@ impl MachineState { } else if self.fail { return Ok(()); } - } } + } + } } } &SystemClauseType::NumberToChars => { @@ -1731,27 +1627,22 @@ impl MachineState { let n = self.store(self.deref(n)); - let string = - match Number::try_from((n, &self.heap)) { - Ok(Number::Float(OrderedFloat(n))) => { - format!("{0:<20?}", n) - } - Ok(Number::Fixnum(n)) => { - n.to_string() - } - Ok(Number::Integer(n)) => { - n.to_string() - } - Ok(Number::Rational(r)) => { - // n has already been confirmed as an integer, and - // internally, Rational is assumed reduced, so its denominator - // must be 1. - r.numer().to_string() - } - _ => { - unreachable!() - } - }; + let string = match Number::try_from((n, &self.heap)) { + Ok(Number::Float(OrderedFloat(n))) => { + format!("{0:<20?}", n) + } + Ok(Number::Fixnum(n)) => n.to_string(), + Ok(Number::Integer(n)) => n.to_string(), + Ok(Number::Rational(r)) => { + // n has already been confirmed as an integer, and + // internally, Rational is assumed reduced, so its denominator + // must be 1. + r.numer().to_string() + } + _ => { + unreachable!() + } + }; let chars = string.trim().chars().map(|c| Addr::Char(c)); let char_list = Addr::HeapCell(self.heap.to_list(chars)); @@ -1762,32 +1653,24 @@ impl MachineState { let n = self[temp_v!(1)]; let chs = self[temp_v!(2)]; - let string = - match Number::try_from((n, &self.heap)) { - Ok(Number::Float(OrderedFloat(n))) => { - format!("{0:<20?}", n) - } - Ok(Number::Fixnum(n)) => { - n.to_string() - } - Ok(Number::Integer(n)) => { - n.to_string() - } - Ok(Number::Rational(r)) => { - // n has already been confirmed as an integer, and - // internally, Rational is assumed reduced, so its - // denominator must be 1. - r.numer().to_string() - } - _ => { - unreachable!() - } - }; + let string = match Number::try_from((n, &self.heap)) { + Ok(Number::Float(OrderedFloat(n))) => { + format!("{0:<20?}", n) + } + Ok(Number::Fixnum(n)) => n.to_string(), + Ok(Number::Integer(n)) => n.to_string(), + Ok(Number::Rational(r)) => { + // n has already been confirmed as an integer, and + // internally, Rational is assumed reduced, so its + // denominator must be 1. + r.numer().to_string() + } + _ => { + unreachable!() + } + }; - let codes = string - .trim() - .chars() - .map(|c| Addr::Fixnum(c as isize)); + let codes = string.trim().chars().map(|c| Addr::Fixnum(c as isize)); let codes_list = Addr::HeapCell(self.heap.to_list(codes)); @@ -1800,22 +1683,17 @@ impl MachineState { Err(e) => { return Err(e); } - Ok(addrs) => { - match self.try_char_list(addrs) { - Ok(chars) => { - let stub = MachineError::functor_stub(clause_name!("number_codes"), 2); - self.parse_number_from_string(chars, indices, stub)?; - } - Err(err) => { - let stub = MachineError::functor_stub( - clause_name!("number_codes"), - 2, - ); - - return Err(self.error_form(err, stub)); - } + Ok(addrs) => match self.try_char_list(addrs) { + Ok(chars) => { + let stub = MachineError::functor_stub(clause_name!("number_codes"), 2); + self.parse_number_from_string(chars, indices, stub)?; } - } + Err(err) => { + let stub = MachineError::functor_stub(clause_name!("number_codes"), 2); + + return Err(self.error_form(err, stub)); + } + }, } } &SystemClauseType::LiftedHeapLength => { @@ -1829,17 +1707,16 @@ impl MachineState { match self.store(self.deref(a1)) { Addr::Con(h) if self.heap.atom_at(h) => { - let c = - if let HeapCellValue::Atom(name, _) = &self.heap[h] { - if name.is_char() { - name.as_str().chars().next().unwrap() - } else { - self.fail = true; - return Ok(()); - } + let c = if let HeapCellValue::Atom(name, _) = &self.heap[h] { + if name.is_char() { + name.as_str().chars().next().unwrap() } else { - unreachable!() - }; + self.fail = true; + return Ok(()); + } + } else { + unreachable!() + }; let a2 = self[temp_v!(2)]; self.unify(Addr::Fixnum(c as isize), a2); @@ -1853,9 +1730,7 @@ impl MachineState { let a2 = self.store(self.deref(a2)); let c = match Number::try_from((a2, &self.heap)) { - Ok(Number::Integer(n)) => { - self.int_to_char(&n, "char_code", 2)? - } + Ok(Number::Integer(n)) => self.int_to_char(&n, "char_code", 2)?, Ok(Number::Fixnum(n)) => { self.int_to_char(&Integer::from(n), "char_code", 2)? } @@ -1881,45 +1756,41 @@ impl MachineState { Addr::Con(h) if self.heap.atom_at(h) => { if let HeapCellValue::Atom(name, _) = &self.heap[h] { name.as_str().chars().next().unwrap() - } - else { + } else { unreachable!() } } - _ => unreachable!() + _ => unreachable!(), }; let chars = match a2 { Addr::Con(h) if self.heap.atom_at(h) => { if let HeapCellValue::Atom(name, _) = &self.heap[h] { name.as_str().to_string() - } - else { + } else { unreachable!() } } - Addr::Char(c) => { - c.to_string() - } - _ => unreachable!() + Addr::Char(c) => c.to_string(), + _ => unreachable!(), }; self.fail = true; // This predicate fails by default. macro_rules! macro_check { ($id:ident, $name:tt) => { - if $id!(c) && chars == $name { - self.fail = false; + if $id!(c) && chars == $name { + self.fail = false; - return return_from_clause!(self.last_call, self); - } - } + return return_from_clause!(self.last_call, self); + } + }; } macro_rules! method_check { ($id:ident, $name:tt) => { - if c.$id() && chars == $name { - self.fail = false; + if c.$id() && chars == $name { + self.fail = false; - return return_from_clause!(self.last_call, self); - } - } + return return_from_clause!(self.last_call, self); + } + }; } macro_check!(symbolic_control_char, "symbolic_control"); // macro_check!(space_char, "space"); @@ -2006,9 +1877,7 @@ impl MachineState { self.heap.extend(stub.into_iter()); self.unify(addr, Addr::HeapCell(h)); } - Some((_, Some(h))) => { - self.unify(addr, Addr::HeapCell(*h)) - } + Some((_, Some(h))) => self.unify(addr, Addr::HeapCell(*h)), None => self.fail = true, }; } @@ -2049,9 +1918,7 @@ impl MachineState { self.unify(addr, Addr::HeapCell(*h)); } } - None => { - self.fail = true - } + None => self.fail = true, }; } &SystemClauseType::PutCode => { @@ -2082,7 +1949,9 @@ impl MachineState { } } Ok(Number::Fixnum(n)) => { - if let Some(c) = u32::try_from(n).ok().and_then(|c| char::try_from(c).ok()) { + if let Some(c) = + u32::try_from(n).ok().and_then(|c| char::try_from(c).ok()) + { write!(&mut stream, "{}", c).unwrap(); return return_from_clause!(self.last_call, self); } @@ -2100,9 +1969,7 @@ impl MachineState { } let stub = MachineError::functor_stub(clause_name!("put_code"), 2); - let err = MachineError::representation_error( - RepFlag::CharacterCode, - ); + let err = MachineError::representation_error(RepFlag::CharacterCode); return Err(self.error_form(err, stub)); } @@ -2129,34 +1996,27 @@ impl MachineState { } addr => { match self.store(self.deref(self[temp_v!(2)])) { - Addr::Con(h) if self.heap.atom_at(h) => { - match &self.heap[h] { - HeapCellValue::Atom(ref atom, _) if atom.is_char() => { - if let Some(c) = atom.as_str().chars().next() { - write!(&mut stream, "{}", c).unwrap(); - return return_from_clause!(self.last_call, self); - } else { - unreachable!() - } - } - _ => { + Addr::Con(h) if self.heap.atom_at(h) => match &self.heap[h] { + HeapCellValue::Atom(ref atom, _) if atom.is_char() => { + if let Some(c) = atom.as_str().chars().next() { + write!(&mut stream, "{}", c).unwrap(); + return return_from_clause!(self.last_call, self); + } else { + unreachable!() } } - } + _ => {} + }, Addr::Char(c) => { write!(&mut stream, "{}", c).unwrap(); return return_from_clause!(self.last_call, self); } - _ => { - } + _ => {} } let stub = MachineError::functor_stub(clause_name!("put_char"), 2); - let err = MachineError::type_error( - self.heap.h(), - ValidType::Character, - addr, - ); + let err = + MachineError::type_error(self.heap.h(), ValidType::Character, addr); return Err(self.error_form(err, stub)); } @@ -2172,7 +2032,6 @@ impl MachineState { if stream.options.stream_type == StreamType::Binary { for c in string.chars() { if c as u32 > 255 { - let stub = MachineError::functor_stub(clause_name!("$put_chars"), 2); let err = MachineError::type_error( @@ -2195,14 +2054,11 @@ impl MachineState { return return_from_clause!(self.last_call, self); } _ => { - let stub = MachineError::functor_stub( - clause_name!("$put_chars"), - 2, - ); + let stub = MachineError::functor_stub(clause_name!("$put_chars"), 2); - let addr = self.heap.to_unifiable( - HeapCellValue::Stream(stream.clone()), - ); + let addr = self + .heap + .to_unifiable(HeapCellValue::Stream(stream.clone())); return Err(self.error_form( MachineError::existence_error( @@ -2289,8 +2145,7 @@ impl MachineState { } } } - _ => { - } + _ => {} } let stub = MachineError::functor_stub(clause_name!("put_byte"), 2); @@ -2317,12 +2172,7 @@ impl MachineState { )?; if stream.past_end_of_stream() { - self.eof_action( - self[temp_v!(2)], - &mut stream, - clause_name!("get_byte"), - 2, - )?; + self.eof_action(self[temp_v!(2)], &mut stream, clause_name!("get_byte"), 2)?; if EOFAction::Reset != stream.options.eof_action { return return_from_clause!(self.last_call, self); @@ -2331,48 +2181,43 @@ impl MachineState { } } - let addr = - match self.store(self.deref(self[temp_v!(2)])) { - addr if addr.is_ref() => { - addr - } - addr => { - match Number::try_from((addr, &self.heap)) { - Ok(Number::Integer(n)) => { - if let Some(nb) = n.to_u8() { - Addr::Usize(nb as usize) - } else { - return Err(self.type_error( - ValidType::InByte, - addr, - clause_name!("get_byte"), - 2, - )); - } - } - Ok(Number::Fixnum(n)) => { - if let Ok(nb) = u8::try_from(n) { - Addr::Usize(nb as usize) - } else { - return Err(self.type_error( - ValidType::InByte, - addr, - clause_name!("get_byte"), - 2, - )); - } - } - _ => { - return Err(self.type_error( - ValidType::InByte, - addr, - clause_name!("get_byte"), - 2, - )); - } + let addr = match self.store(self.deref(self[temp_v!(2)])) { + addr if addr.is_ref() => addr, + addr => match Number::try_from((addr, &self.heap)) { + Ok(Number::Integer(n)) => { + if let Some(nb) = n.to_u8() { + Addr::Usize(nb as usize) + } else { + return Err(self.type_error( + ValidType::InByte, + addr, + clause_name!("get_byte"), + 2, + )); } } - }; + Ok(Number::Fixnum(n)) => { + if let Ok(nb) = u8::try_from(n) { + Addr::Usize(nb as usize) + } else { + return Err(self.type_error( + ValidType::InByte, + addr, + clause_name!("get_byte"), + 2, + )); + } + } + _ => { + return Err(self.type_error( + ValidType::InByte, + addr, + clause_name!("get_byte"), + 2, + )); + } + }, + }; loop { let mut b = [0u8; 1]; @@ -2419,9 +2264,9 @@ impl MachineState { if stream.at_end_of_stream() { let end_of_file = clause_name!("end_of_file"); - let end_of_file = self.heap.to_unifiable( - HeapCellValue::Atom(end_of_file, None), - ); + let end_of_file = self + .heap + .to_unifiable(HeapCellValue::Atom(end_of_file, None)); stream.set_past_end_of_stream(); @@ -2429,48 +2274,37 @@ impl MachineState { return return_from_clause!(self.last_call, self); } - let mut iter = self.open_parsing_stream( - stream.clone(), - "get_char", - 2, - )?; + let mut iter = self.open_parsing_stream(stream.clone(), "get_char", 2)?; - let addr = - match self.store(self.deref(self[temp_v!(2)])) { - addr if addr.is_ref() => { - addr - } - Addr::Con(h) if self.heap.atom_at(h) => { - match &self.heap[h] { - HeapCellValue::Atom(ref atom, _) if atom.is_char() => { - if let Some(c) = atom.as_str().chars().next() { - Addr::Char(c) - } else { - unreachable!() - } - } - culprit => { - return Err(self.type_error( - ValidType::InCharacter, - culprit.as_addr(h), - clause_name!("get_char"), - 2, - )); - } + let addr = match self.store(self.deref(self[temp_v!(2)])) { + addr if addr.is_ref() => addr, + Addr::Con(h) if self.heap.atom_at(h) => match &self.heap[h] { + HeapCellValue::Atom(ref atom, _) if atom.is_char() => { + if let Some(c) = atom.as_str().chars().next() { + Addr::Char(c) + } else { + unreachable!() } } - Addr::Char(d) => { - Addr::Char(d) - } culprit => { return Err(self.type_error( ValidType::InCharacter, - culprit, + culprit.as_addr(h), clause_name!("get_char"), 2, )); } - }; + }, + Addr::Char(d) => Addr::Char(d), + culprit => { + return Err(self.type_error( + ValidType::InCharacter, + culprit, + clause_name!("get_char"), + 2, + )); + } + }; loop { let result = iter.next(); @@ -2500,14 +2334,14 @@ impl MachineState { } else if self.fail { return Ok(()); } - }/* - _ => { - let stub = MachineError::functor_stub(clause_name!("get_char"), 2); - let err = MachineError::representation_error(RepFlag::Character); - let err = self.error_form(err, stub); + } /* + _ => { + let stub = MachineError::functor_stub(clause_name!("get_char"), 2); + let err = MachineError::representation_error(RepFlag::Character); + let err = self.error_form(err, stub); - return Err(err); - }*/ + return Err(err); + }*/ } } } @@ -2515,19 +2349,19 @@ impl MachineState { let stream = self.get_stream_or_alias(self[temp_v!(1)], indices, "get_n_chars", 3)?; - let num = - match Number::try_from((self[temp_v!(2)], &self.heap)) { - Ok(Number::Fixnum(n)) => { - usize::try_from(n).unwrap() + let num = match Number::try_from((self[temp_v!(2)], &self.heap)) { + Ok(Number::Fixnum(n)) => usize::try_from(n).unwrap(), + Ok(Number::Integer(n)) => match n.to_usize() { + Some(u) => u, + _ => { + self.fail = true; + return Ok(()); } - Ok(Number::Integer(n)) => { - match n.to_usize() { - Some(u) => { u } - _ => { self.fail = true; return Ok(()); } - } - } - _ => { unreachable!() } - }; + }, + _ => { + unreachable!() + } + }; let mut string = String::new(); @@ -2539,23 +2373,20 @@ impl MachineState { string.push(c as char); } } else { - let mut iter = self.open_parsing_stream( - stream.clone(), - "get_n_chars", - 2, - )?; + let mut iter = self.open_parsing_stream(stream.clone(), "get_n_chars", 2)?; for _ in 0..num { - let result = iter.next(); + let result = iter.next(); - match result { - Some(Ok(c)) => { + match result { + Some(Ok(c)) => { string.push(c); - } - _ => { break; - } - } - } + } + _ => { + break; + } + } + } }; let string = self.heap.put_complete_string(&string); self.unify(self[temp_v!(3)], string); @@ -2582,9 +2413,9 @@ impl MachineState { if stream.at_end_of_stream() { let end_of_file = clause_name!("end_of_file"); - let end_of_file = self.heap.to_unifiable( - HeapCellValue::Atom(end_of_file, None), - ); + let end_of_file = self + .heap + .to_unifiable(HeapCellValue::Atom(end_of_file, None)); stream.set_past_end_of_stream(); @@ -2592,60 +2423,51 @@ impl MachineState { return return_from_clause!(self.last_call, self); } - let addr = - match self.store(self.deref(self[temp_v!(2)])) { - addr if addr.is_ref() => { - addr - } - addr => { - match Number::try_from((addr, &self.heap)) { - Ok(Number::Integer(n)) => { - let n = n.to_u32().and_then(|n| { - std::char::from_u32(n).and_then(|_| Some(n)) - }); + let addr = match self.store(self.deref(self[temp_v!(2)])) { + addr if addr.is_ref() => addr, + addr => match Number::try_from((addr, &self.heap)) { + Ok(Number::Integer(n)) => { + let n = n + .to_u32() + .and_then(|n| std::char::from_u32(n).and_then(|_| Some(n))); - if let Some(n) = n { - Addr::Fixnum(n as isize) - } else { - return Err(self.representation_error( - RepFlag::InCharacterCode, - clause_name!("get_code"), - 2, - )); - } - } - Ok(Number::Fixnum(n)) => { - let n = u32::try_from(n).ok().and_then(|n| { - std::char::from_u32(n).and_then(|_| Some(n)) - }); - - if let Some(n) = n { - Addr::Fixnum(n as isize) - } else { - return Err(self.representation_error( - RepFlag::InCharacterCode, - clause_name!("get_code"), - 2, - )); - } - } - _ => { - return Err(self.type_error( - ValidType::Integer, - self[temp_v!(2)], - clause_name!("get_code"), - 2, - )); - } + if let Some(n) = n { + Addr::Fixnum(n as isize) + } else { + return Err(self.representation_error( + RepFlag::InCharacterCode, + clause_name!("get_code"), + 2, + )); } } - }; + Ok(Number::Fixnum(n)) => { + let n = u32::try_from(n) + .ok() + .and_then(|n| std::char::from_u32(n).and_then(|_| Some(n))); - let mut iter = self.open_parsing_stream( - stream.clone(), - "get_code", - 2, - )?; + if let Some(n) = n { + Addr::Fixnum(n as isize) + } else { + return Err(self.representation_error( + RepFlag::InCharacterCode, + clause_name!("get_code"), + 2, + )); + } + } + _ => { + return Err(self.type_error( + ValidType::Integer, + self[temp_v!(2)], + clause_name!("get_code"), + 2, + )); + } + }, + }; + + let mut iter = self.open_parsing_stream(stream.clone(), "get_code", 2)?; loop { let result = iter.next(); @@ -2705,24 +2527,28 @@ impl MachineState { } } &SystemClauseType::NextStream => { - let prev_stream = - match self.store(self.deref(self[temp_v!(1)])) { - Addr::Stream(h) => { - if let HeapCellValue::Stream(ref stream) = &self.heap[h] { - stream.clone() - } else { - unreachable!() - } - } - _ => { + let prev_stream = match self.store(self.deref(self[temp_v!(1)])) { + Addr::Stream(h) => { + if let HeapCellValue::Stream(ref stream) = &self.heap[h] { + stream.clone() + } else { unreachable!() } - }; + } + _ => { + unreachable!() + } + }; - let mut next_stream = None; + let mut next_stream = None; let mut null_streams = BTreeSet::new(); - for stream in indices.streams.range(prev_stream.clone() ..).skip(1).cloned() { + for stream in indices + .streams + .range(prev_stream.clone()..) + .skip(1) + .cloned() + { if !stream.is_null_stream() { next_stream = Some(stream); break; @@ -2750,9 +2576,7 @@ impl MachineState { if !stream.is_output_stream() { let stub = MachineError::functor_stub(clause_name!("flush_output"), 1); - let addr = vec![ - HeapCellValue::Stream(stream) - ]; + let addr = vec![HeapCellValue::Stream(stream)]; let err = MachineError::permission_error( self.heap.h(), @@ -2769,14 +2593,11 @@ impl MachineState { &SystemClauseType::GetSingleChar => { let ctrl_c = KeyEvent { code: KeyCode::Char('c'), - modifiers: KeyModifiers::CONTROL + modifiers: KeyModifiers::CONTROL, }; let key = get_key(); if key == ctrl_c { - let stub = MachineError::functor_stub( - clause_name!("get_single_char"), - 1 - ); + let stub = MachineError::functor_stub(clause_name!("get_single_char"), 1); let err = MachineError::interrupt_error(); let err = self.error_form(err, stub); @@ -2786,7 +2607,7 @@ impl MachineState { KeyCode::Enter => '\n', KeyCode::Tab => '\t', KeyCode::Char(c) => c, - _ => unreachable!() + _ => unreachable!(), }; let a1 = self[temp_v!(1)]; @@ -2794,21 +2615,17 @@ impl MachineState { self.unify(Addr::Char(c), a1); } &SystemClauseType::HeadIsDynamic => { - let module_name = atom_from!( - self, - self.store(self.deref( - self[temp_v!(1)] - )) - ); + let module_name = atom_from!(self, self.store(self.deref(self[temp_v!(1)]))); self.fail = !match self.store(self.deref(self[temp_v!(2)])) { Addr::Str(s) => match &self.heap[s] { - &HeapCellValue::NamedStr(arity, ref name, ..) => - indices.is_dynamic_predicate(module_name, (name.clone(), arity)), + &HeapCellValue::NamedStr(arity, ref name, ..) => { + indices.is_dynamic_predicate(module_name, (name.clone(), arity)) + } _ => unreachable!(), }, Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(name, _) = &self.heap[h] { + if let HeapCellValue::Atom(name, _) = &self.heap[h] { indices.is_dynamic_predicate(module_name, (name.clone(), 0)) } else { unreachable!() @@ -2820,8 +2637,7 @@ impl MachineState { }; } &SystemClauseType::Close => { - let mut stream = - self.get_stream_or_alias(self[temp_v!(1)], indices, "close", 2)?; + let mut stream = self.get_stream_or_alias(self[temp_v!(1)], indices, "close", 2)?; if !stream.is_input_stream() { stream.flush().unwrap(); // 8.11.6.1b) @@ -2830,15 +2646,19 @@ impl MachineState { indices.streams.remove(&stream); if stream == *current_input_stream { - *current_input_stream = indices.stream_aliases.get( - &clause_name!("user_input") - ).cloned().unwrap(); + *current_input_stream = indices + .stream_aliases + .get(&clause_name!("user_input")) + .cloned() + .unwrap(); indices.streams.insert(current_input_stream.clone()); } else if stream == *current_output_stream { - *current_output_stream = indices.stream_aliases.get( - &clause_name!("user_output") - ).cloned().unwrap(); + *current_output_stream = indices + .stream_aliases + .get(&clause_name!("user_output")) + .cloned() + .unwrap(); indices.streams.insert(current_output_stream.clone()); } @@ -2851,31 +2671,29 @@ impl MachineState { } } } - &SystemClauseType::CopyToLiftedHeap => { - match self.store(self.deref(self[temp_v!(1)])) { - Addr::Usize(lh_offset) => { - let copy_target = self[temp_v!(2)]; + &SystemClauseType::CopyToLiftedHeap => match self.store(self.deref(self[temp_v!(1)])) { + Addr::Usize(lh_offset) => { + let copy_target = self[temp_v!(2)]; - let old_threshold = self.copy_findall_solution(lh_offset, copy_target); - let new_threshold = self.lifted_heap.h() - lh_offset; + let old_threshold = self.copy_findall_solution(lh_offset, copy_target); + let new_threshold = self.lifted_heap.h() - lh_offset; - self.lifted_heap[old_threshold] = - HeapCellValue::Addr(Addr::HeapCell(new_threshold)); + self.lifted_heap[old_threshold] = + HeapCellValue::Addr(Addr::HeapCell(new_threshold)); - for addr in self.lifted_heap.iter_mut_from(old_threshold + 1) { - match addr { - HeapCellValue::Addr(ref mut addr) => { - *addr -= self.heap.h() + lh_offset; - } - _ => {} + for addr in self.lifted_heap.iter_mut_from(old_threshold + 1) { + match addr { + HeapCellValue::Addr(ref mut addr) => { + *addr -= self.heap.h() + lh_offset; } + _ => {} } } - _ => { - self.fail = true; - } } - } + _ => { + self.fail = true; + } + }, &SystemClauseType::DeleteAttribute => { let ls0 = self.store(self.deref(self[temp_v!(1)])); @@ -2893,7 +2711,7 @@ impl MachineState { let trail_ref = match old_addr { Addr::HeapCell(h) => TrailRef::AttrVarHeapLink(h), Addr::Lis(l) => TrailRef::AttrVarListLink(l1 + 1, l), - _ => unreachable!() + _ => unreachable!(), }; self.heap[l1 + 1] = HeapCellValue::Addr(tail); @@ -2953,11 +2771,11 @@ impl MachineState { match self.store(self.deref(self[temp_v!(2 + narity)])) { Addr::Str(a) => { if let HeapCellValue::NamedStr(arity, name, _) = self.heap.clone(a) { - for i in (arity + 1 .. arity + narity + 1).rev() { + for i in (arity + 1..arity + narity + 1).rev() { self.registers[i] = self.registers[i - arity]; } - for i in 1 .. arity + 1 { + for i in 1..arity + 1 { self.registers[i] = self.heap[a + i].as_addr(a + i); } @@ -2975,7 +2793,7 @@ impl MachineState { } } Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(name, _) = self.heap.clone(h) { + if let HeapCellValue::Atom(name, _) = self.heap.clone(h) { return self.module_lookup( indices, call_policy, @@ -2992,11 +2810,8 @@ impl MachineState { addr => { let stub = MachineError::functor_stub(clause_name!("(:)"), 2); - let type_error = MachineError::type_error( - self.heap.h(), - ValidType::Callable, - addr, - ); + let type_error = + MachineError::type_error(self.heap.h(), ValidType::Callable, addr); let type_error = self.error_form(type_error, stub); return Err(type_error); @@ -3014,8 +2829,7 @@ impl MachineState { Addr::AttrVar(h) => { self.attr_var_init.attr_var_queue.push(h); } - _ => { - } + _ => {} } } /* @@ -3033,8 +2847,8 @@ impl MachineState { match self.store(self.deref(a1)) { addr @ Addr::HeapCell(_) - | addr @ Addr::StackCell(..) - | addr @ Addr::AttrVar(_) => { + | addr @ Addr::StackCell(..) + | addr @ Addr::AttrVar(_) => { let mut iter = indices.code_dir.iter(); while let Some(((name, arity), _)) = iter.next() { @@ -3051,9 +2865,7 @@ impl MachineState { let db_ref = DBRef::NamedPred(name.clone(), *arity, spec); let r = addr.as_var().unwrap(); - let addr = self.heap.to_unifiable( - HeapCellValue::DBRef(db_ref) - ); + let addr = self.heap.to_unifiable(HeapCellValue::DBRef(db_ref)); self.bind(r, addr); @@ -3062,19 +2874,17 @@ impl MachineState { self.fail = true; } - Addr::Con(h) => { - match self.heap.clone(h) { - HeapCellValue::DBRef(DBRef::Op(..)) => { - self.fail = true; - } - HeapCellValue::DBRef(ref db_ref) => { - self.get_next_db_ref(indices, db_ref); - } - _ => { - self.fail = true; - } + Addr::Con(h) => match self.heap.clone(h) { + HeapCellValue::DBRef(DBRef::Op(..)) => { + self.fail = true; } - } + HeapCellValue::DBRef(ref db_ref) => { + self.get_next_db_ref(indices, db_ref); + } + _ => { + self.fail = true; + } + }, _ => { self.fail = true; } @@ -3085,8 +2895,8 @@ impl MachineState { match self.store(self.deref(a1)) { addr @ Addr::HeapCell(_) - | addr @ Addr::StackCell(..) - | addr @ Addr::AttrVar(_) => { + | addr @ Addr::StackCell(..) + | addr @ Addr::AttrVar(_) => { let mut unossified_op_dir = OssifiedOpDir::new(); unossified_op_dir.extend(indices.op_dir.iter().filter_map( @@ -3118,9 +2928,7 @@ impl MachineState { ); let r = addr.as_var().unwrap(); - let addr = self.heap.to_unifiable( - HeapCellValue::DBRef(db_ref) - ); + let addr = self.heap.to_unifiable(HeapCellValue::DBRef(db_ref)); self.bind(r, addr); } @@ -3130,19 +2938,17 @@ impl MachineState { } } } - Addr::Con(h) => { - match self.heap.clone(h) { - HeapCellValue::DBRef(DBRef::NamedPred(..)) => { - self.fail = true; - } - HeapCellValue::DBRef(ref db_ref) => { - self.get_next_db_ref(indices, db_ref); - } - _ => { - self.fail = true; - } + Addr::Con(h) => match self.heap.clone(h) { + HeapCellValue::DBRef(DBRef::NamedPred(..)) => { + self.fail = true; } - } + HeapCellValue::DBRef(ref db_ref) => { + self.get_next_db_ref(indices, db_ref); + } + _ => { + self.fail = true; + } + }, _ => { self.fail = true; } @@ -3152,27 +2958,23 @@ impl MachineState { let a1 = self[temp_v!(1)]; match self.store(self.deref(a1)) { - Addr::Con(h) => { - match self.heap.clone(h) { - HeapCellValue::DBRef(DBRef::NamedPred(name, arity, spec)) => { - let a2 = self[temp_v!(2)]; - let a3 = self[temp_v!(3)]; + Addr::Con(h) => match self.heap.clone(h) { + HeapCellValue::DBRef(DBRef::NamedPred(name, arity, spec)) => { + let a2 = self[temp_v!(2)]; + let a3 = self[temp_v!(3)]; - let atom = self.heap.to_unifiable( - HeapCellValue::Atom(name, spec) - ); + let atom = self.heap.to_unifiable(HeapCellValue::Atom(name, spec)); - self.unify(a2, atom); + self.unify(a2, atom); - if !self.fail { - self.unify(a3, Addr::Usize(arity)); - } - } - _ => { - self.fail = true; + if !self.fail { + self.unify(a3, Addr::Usize(arity)); } } - } + _ => { + self.fail = true; + } + }, _ => { self.fail = true; } @@ -3182,56 +2984,54 @@ impl MachineState { let a1 = self[temp_v!(1)]; match self.store(self.deref(a1)) { - Addr::Con(h) => { - match self.heap.clone(h) { - HeapCellValue::DBRef(DBRef::Op( - priority, - spec, - name, - _, - shared_op_desc, - )) => { - let prec = self[temp_v!(2)]; - let specifier = self[temp_v!(3)]; - let op = self[temp_v!(4)]; + Addr::Con(h) => match self.heap.clone(h) { + HeapCellValue::DBRef(DBRef::Op( + priority, + spec, + name, + _, + shared_op_desc, + )) => { + let prec = self[temp_v!(2)]; + let specifier = self[temp_v!(3)]; + let op = self[temp_v!(4)]; - let spec = match spec { - FX => "fx", - FY => "fy", - XF => "xf", - YF => "yf", - XFX => "xfx", - XFY => "xfy", - YFX => "yfx", - _ => { - self.fail = true; - return Ok(()); - } - }; - - let a3 = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!(spec), None) - ); - - let a4 = self.heap.to_unifiable( - HeapCellValue::Atom(name, Some(shared_op_desc)) - ); - - self.unify(Addr::Usize(priority), prec); - - if !self.fail { - self.unify(a3, specifier); + let spec = match spec { + FX => "fx", + FY => "fy", + XF => "xf", + YF => "yf", + XFX => "xfx", + XFY => "xfy", + YFX => "yfx", + _ => { + self.fail = true; + return Ok(()); } + }; - if !self.fail { - self.unify(a4, op); - } + let a3 = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!(spec), None)); + + let a4 = self + .heap + .to_unifiable(HeapCellValue::Atom(name, Some(shared_op_desc))); + + self.unify(Addr::Usize(priority), prec); + + if !self.fail { + self.unify(a3, specifier); } - _ => { - self.fail = true; + + if !self.fail { + self.unify(a4, op); } } - } + _ => { + self.fail = true; + } + }, _ => { self.fail = true; } @@ -3263,41 +3063,35 @@ impl MachineState { let priority = self.store(self.deref(priority)); - let priority = - match Number::try_from((priority, &self.heap)) { - Ok(Number::Integer(n)) => { - n.to_usize().unwrap() - } - Ok(Number::Fixnum(n)) => { - usize::try_from(n).unwrap() - } - _ => { - unreachable!(); - } - }; + let priority = match Number::try_from((priority, &self.heap)) { + Ok(Number::Integer(n)) => n.to_usize().unwrap(), + Ok(Number::Fixnum(n)) => usize::try_from(n).unwrap(), + _ => { + unreachable!(); + } + }; let specifier = match self.store(self.deref(specifier)) { - Addr::Con(h) if self.heap.atom_at(h) => + Addr::Con(h) if self.heap.atom_at(h) => { if let HeapCellValue::Atom(ref specifier, _) = &self.heap[h] { specifier.clone() } else { unreachable!() - }, - _ => - unreachable!(), + } + } + _ => unreachable!(), }; let op = match self.store(self.deref(op)) { - Addr::Char(c) => - clause_name!(c.to_string(), self.atom_tbl), - Addr::Con(h) if self.heap.atom_at(h) => + Addr::Char(c) => clause_name!(c.to_string(), self.atom_tbl), + Addr::Con(h) if self.heap.atom_at(h) => { if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { name.clone() } else { unreachable!() - }, - _ => - unreachable!(), + } + } + _ => unreachable!(), }; let result = to_op_decl(priority, specifier.as_str(), op) @@ -3316,8 +3110,7 @@ impl MachineState { }); match result { - Ok(()) => { - } + Ok(()) => {} Err(e) => { // 8.14.3.3 l) let e = MachineError::session_error(self.heap.h(), e); @@ -3334,48 +3127,33 @@ impl MachineState { let reposition = self[temp_v!(6)]; let stream_type = self[temp_v!(7)]; - let options = - self.to_stream_options(alias, eof_action, reposition, stream_type); + let options = self.to_stream_options(alias, eof_action, reposition, stream_type); - let mut stream = - match self.store(self.deref(self[temp_v!(1)])) { - Addr::Con(h) if self.heap.atom_at(h) => { - match &self.heap[h] { - &HeapCellValue::Atom(ref atom, _) => { - self.stream_from_file_spec(atom.clone(), indices, &options)? - } - _ => { - unreachable!() - } - } - } - Addr::Char(c) => { - let atom = clause_name!(c.to_string(), self.atom_tbl); - self.stream_from_file_spec(atom, indices, &options)? - } - Addr::PStrLocation(h, n) => { - match &self.heap[h] { - &HeapCellValue::PartialString(_, true) => { - let mut heap_pstr_iter = - self.heap_pstr_iter(Addr::PStrLocation(h, n)); - - let file_spec = - clause_name!( - heap_pstr_iter.to_string(), - self.atom_tbl - ); - - self.stream_from_file_spec(file_spec, indices, &options)? - } - _ => { - self.stream_from_file_spec(clause_name!(""), indices, &options)? - } - } + let mut stream = match self.store(self.deref(self[temp_v!(1)])) { + Addr::Con(h) if self.heap.atom_at(h) => match &self.heap[h] { + &HeapCellValue::Atom(ref atom, _) => { + self.stream_from_file_spec(atom.clone(), indices, &options)? } _ => { - self.stream_from_file_spec(clause_name!(""), indices, &options)? + unreachable!() } - }; + }, + Addr::Char(c) => { + let atom = clause_name!(c.to_string(), self.atom_tbl); + self.stream_from_file_spec(atom, indices, &options)? + } + Addr::PStrLocation(h, n) => match &self.heap[h] { + &HeapCellValue::PartialString(_, true) => { + let mut heap_pstr_iter = self.heap_pstr_iter(Addr::PStrLocation(h, n)); + + let file_spec = clause_name!(heap_pstr_iter.to_string(), self.atom_tbl); + + self.stream_from_file_spec(file_spec, indices, &options)? + } + _ => self.stream_from_file_spec(clause_name!(""), indices, &options)?, + }, + _ => self.stream_from_file_spec(clause_name!(""), indices, &options)?, + }; stream.options = options; @@ -3405,27 +3183,23 @@ impl MachineState { } &SystemClauseType::GetAttributedVariableList => { let attr_var = self.store(self.deref(self[temp_v!(1)])); - let attr_var_list = - match attr_var { - Addr::AttrVar(h) => { - h + 1 - } - attr_var @ Addr::HeapCell(_) | - attr_var @ Addr::StackCell(..) => { - // create an AttrVar in the heap. - let h = self.heap.h(); + let attr_var_list = match attr_var { + Addr::AttrVar(h) => h + 1, + attr_var @ Addr::HeapCell(_) | attr_var @ Addr::StackCell(..) => { + // create an AttrVar in the heap. + let h = self.heap.h(); - self.heap.push(HeapCellValue::Addr(Addr::AttrVar(h))); - self.heap.push(HeapCellValue::Addr(Addr::HeapCell(h + 1))); + self.heap.push(HeapCellValue::Addr(Addr::AttrVar(h))); + self.heap.push(HeapCellValue::Addr(Addr::HeapCell(h + 1))); - self.bind(Ref::AttrVar(h), attr_var); - h + 1 - } - _ => { - self.fail = true; - return Ok(()); - } - }; + self.bind(Ref::AttrVar(h), attr_var); + h + 1 + } + _ => { + self.fail = true; + return Ok(()); + } + }; let list_addr = self[temp_v!(2)]; self.bind(Ref::HeapCell(attr_var_list), list_addr); @@ -3440,26 +3214,17 @@ impl MachineState { let addr = self[temp_v!(1)]; let addr = self.store(self.deref(addr)); - let b = - match addr { - Addr::Usize(b) => { - Some(b) - } + let b = match addr { + Addr::Usize(b) => Some(b), + _ => match Number::try_from((addr, &self.heap)) { + Ok(Number::Integer(n)) => n.to_usize(), + Ok(Number::Fixnum(n)) => usize::try_from(n).ok(), _ => { - match Number::try_from((addr, &self.heap)) { - Ok(Number::Integer(n)) => { - n.to_usize() - } - Ok(Number::Fixnum(n)) => { - usize::try_from(n).ok() - } - _ => { - self.fail = true; - return Ok(()); - } - } + self.fail = true; + return Ok(()); } - }; + }, + }; if let Some(b) = b { let iter = self.gather_attr_vars_created_since(b); @@ -3483,22 +3248,21 @@ impl MachineState { let p_functor = self.store(self.deref(self[temp_v!(2)])); let p = self.heap.to_local_code_ptr(&p_functor).unwrap(); - let num_cells = - match code_repo.lookup_instr(self.last_call, &CodePtr::Local(p)) { - Some(line) => { - let perm_vars = match line.as_ref() { - Line::Control(ref ctrl_instr) => ctrl_instr.perm_vars(), - _ => None - }; + let num_cells = match code_repo.lookup_instr(self.last_call, &CodePtr::Local(p)) { + Some(line) => { + let perm_vars = match line.as_ref() { + Line::Control(ref ctrl_instr) => ctrl_instr.perm_vars(), + _ => None, + }; - perm_vars.unwrap() - } - _ => unreachable!() - }; + perm_vars.unwrap() + } + _ => unreachable!(), + }; let mut addrs = vec![]; - for index in 1 .. num_cells + 1 { + for index in 1..num_cells + 1 { addrs.push(self.stack.index_and_frame(e)[index]); } @@ -3606,23 +3370,23 @@ impl MachineState { match self.flags.double_quotes { DoubleQuotes::Chars => { - let atom = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("chars"), None) - ); + let atom = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("chars"), None)); self.unify(a1, atom); } - DoubleQuotes::Atom => { - let atom = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("atom"), None) - ); + DoubleQuotes::Atom => { + let atom = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("atom"), None)); self.unify(a1, atom); } DoubleQuotes::Codes => { - let atom = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("codes"), None) - ); + let atom = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("codes"), None)); self.unify(a1, atom); } @@ -3648,8 +3412,7 @@ impl MachineState { } } } - None => { - } + None => {} }; self.fail = true; @@ -3666,7 +3429,9 @@ impl MachineState { // denominator must be 1. r.numer().to_i32().unwrap() } - _ => { unreachable!() } + _ => { + unreachable!() + } }; std::process::exit(code); @@ -3701,39 +3466,30 @@ impl MachineState { CWILCallPolicy::new_in_place(call_policy); } - let n = - match Number::try_from((a2, &self.heap)) { - Ok(Number::Integer(n)) => { - Integer::from(&*n.clone()) - } - Ok(Number::Fixnum(n)) => { - Integer::from(n) - } - _ => { - let stub = MachineError::functor_stub( - clause_name!("call_with_inference_limit"), - 3, - ); + let n = match Number::try_from((a2, &self.heap)) { + Ok(Number::Integer(n)) => Integer::from(&*n.clone()), + Ok(Number::Fixnum(n)) => Integer::from(n), + _ => { + let stub = MachineError::functor_stub( + clause_name!("call_with_inference_limit"), + 3, + ); - return Err(self.error_form( - MachineError::type_error( - self.heap.h(), - ValidType::Integer, - a2, - ), - stub, - )); - } - }; + return Err(self.error_form( + MachineError::type_error(self.heap.h(), ValidType::Integer, a2), + stub, + )); + } + }; match a1 { Addr::Usize(bp) | Addr::CutPoint(bp) => { match call_policy.downcast_mut::().ok() { Some(call_policy) => { let count = call_policy.add_limit(n, bp).clone(); - let count = self.heap.to_unifiable( - HeapCellValue::Integer(Rc::new(count)) - ); + let count = self + .heap + .to_unifiable(HeapCellValue::Integer(Rc::new(count))); let a3 = self[temp_v!(3)]; self.unify(a3, count); @@ -3756,7 +3512,7 @@ impl MachineState { match module { Addr::Con(h) => { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { self.fail = !indices.modules.contains_key(name); } else { unreachable!() @@ -3772,34 +3528,33 @@ impl MachineState { self.fail = match self.store(self.deref(self[temp_v!(2)])) { Addr::Str(s) => match &self.heap[s] { - &HeapCellValue::NamedStr(arity, ref name, ref spec) => { - indices.get_predicate_code_index( + &HeapCellValue::NamedStr(arity, ref name, ref spec) => indices + .get_predicate_code_index( name.clone(), arity, module_name, spec.clone(), - ).is_some() - } + ) + .is_some(), _ => { unreachable!() } }, Addr::Con(h) if self.heap.atom_at(h) => { - if let &HeapCellValue::Atom(ref name, ref spec) = &self.heap[h] { - let spec = fetch_atom_op_spec( - name.clone(), - spec.clone(), - &indices.op_dir, - ); + if let &HeapCellValue::Atom(ref name, ref spec) = &self.heap[h] { + let spec = + fetch_atom_op_spec(name.clone(), spec.clone(), &indices.op_dir); - indices.get_predicate_code_index(name.clone(), 0, module_name, spec) - .is_some() + indices + .get_predicate_code_index(name.clone(), 0, module_name, spec) + .is_some() } else { unreachable!() } } head => { - let err = MachineError::type_error(self.heap.h(), ValidType::Callable, head); + let err = + MachineError::type_error(self.heap.h(), ValidType::Callable, head); let stub = MachineError::functor_stub(clause_name!("clause"), 2); return Err(self.error_form(err, stub)); @@ -3807,7 +3562,7 @@ impl MachineState { }; } &SystemClauseType::RedoAttrVarBinding => { - let var = self.store(self.deref(self[temp_v!(1)])); + let var = self.store(self.deref(self[temp_v!(1)])); let value = self.store(self.deref(self[temp_v!(2)])); match var { @@ -3872,34 +3627,33 @@ impl MachineState { indices.global_variables.insert(key, (ball, None)); } } - }, + } &SystemClauseType::ResetAttrVarState => { self.attr_var_init.reset(); } &SystemClauseType::RemoveCallPolicyCheck => { - let restore_default = - match call_policy.downcast_mut::().ok() { - Some(call_policy) => { - let a1 = self.store(self.deref(self[temp_v!(1)])); + let restore_default = match call_policy.downcast_mut::().ok() { + Some(call_policy) => { + let a1 = self.store(self.deref(self[temp_v!(1)])); - match a1 { - Addr::Usize(bp) | Addr::CutPoint(bp) => { - if call_policy.is_empty() && bp == self.b { - Some(call_policy.into_inner()) - } else { - None - } - } - _ => { - panic!("remove_call_policy_check: expected Usize in A1."); + match a1 { + Addr::Usize(bp) | Addr::CutPoint(bp) => { + if call_policy.is_empty() && bp == self.b { + Some(call_policy.into_inner()) + } else { + None } } + _ => { + panic!("remove_call_policy_check: expected Usize in A1."); + } } - None => panic!( - "remove_call_policy_check: requires \\ + } + None => panic!( + "remove_call_policy_check: requires \\ CWILCallPolicy." - ), - }; + ), + }; if let Some(new_policy) = restore_default { *call_policy = new_policy; @@ -3913,9 +3667,9 @@ impl MachineState { match a1 { Addr::Usize(bp) | Addr::CutPoint(bp) => { let count = call_policy.remove_limit(bp).clone(); - let count = self.heap.to_unifiable( - HeapCellValue::Integer(Rc::new(count)), - ); + let count = self + .heap + .to_unifiable(HeapCellValue::Integer(Rc::new(count))); let a2 = self[temp_v!(2)]; @@ -3955,7 +3709,7 @@ impl MachineState { let e = self.e; let frame_len = self.stack.index_and_frame(e).prelude.univ_prelude.num_cells; - for i in 1 .. frame_len - 1 { + for i in 1..frame_len - 1 { self[RegType::Temp(i)] = self.stack.index_and_frame(e)[i]; } @@ -3989,22 +3743,17 @@ impl MachineState { return Ok(()); } } - &SystemClauseType::SetCutPointByDefault(r) => { - deref_cut(self, r) - } + &SystemClauseType::SetCutPointByDefault(r) => deref_cut(self, r), &SystemClauseType::SetInput => { let addr = self.store(self.deref(self[temp_v!(1)])); let stream = self.get_stream_or_alias(addr, indices, "set_input", 1)?; if !stream.is_input_stream() { - let stub = MachineError::functor_stub( - clause_name!("set_input"), - 1, - ); + let stub = MachineError::functor_stub(clause_name!("set_input"), 1); - let user_alias = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("user"), None), - ); + let user_alias = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("user"), None)); let err = MachineError::permission_error( self.heap.h(), @@ -4023,14 +3772,11 @@ impl MachineState { let stream = self.get_stream_or_alias(addr, indices, "set_output", 1)?; if !stream.is_output_stream() { - let stub = MachineError::functor_stub( - clause_name!("set_input"), - 1, - ); + let stub = MachineError::functor_stub(clause_name!("set_input"), 1); - let user_alias = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("user"), None), - ); + let user_alias = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("user"), None)); let err = MachineError::permission_error( self.heap.h(), @@ -4044,29 +3790,26 @@ impl MachineState { *current_output_stream = stream; } - &SystemClauseType::SetDoubleQuotes => { - match self[temp_v!(1)] { - Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref atom, _) = &self.heap[h] { - self.flags.double_quotes = - match atom.as_str() { - "atom" => DoubleQuotes::Atom, - "chars" => DoubleQuotes::Chars, - "codes" => DoubleQuotes::Codes, - _ => { - self.fail = true; - return Ok(()); - } - }; - } else { - unreachable!() - } - } - _ => { - self.fail = true; + &SystemClauseType::SetDoubleQuotes => match self[temp_v!(1)] { + Addr::Con(h) if self.heap.atom_at(h) => { + if let HeapCellValue::Atom(ref atom, _) = &self.heap[h] { + self.flags.double_quotes = match atom.as_str() { + "atom" => DoubleQuotes::Atom, + "chars" => DoubleQuotes::Chars, + "codes" => DoubleQuotes::Codes, + _ => { + self.fail = true; + return Ok(()); + } + }; + } else { + unreachable!() } } - } + _ => { + self.fail = true; + } + }, &SystemClauseType::InferenceLevel => { let a1 = self[temp_v!(1)]; let a2 = self.store(self.deref(self[temp_v!(2)])); @@ -4076,15 +3819,15 @@ impl MachineState { let prev_b = self.stack.index_or_frame(self.b).prelude.b; if prev_b <= bp { - let a2 = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("!"), None) - ); + let a2 = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("!"), None)); self.unify(a1, a2); } else { - let a2 = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("true"), None) - ); + let a2 = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("true"), None)); self.unify(a1, a2); } @@ -4147,54 +3890,54 @@ impl MachineState { self.unify(a1, a2); } -/* - &SystemClauseType::GetClause => { - let head = self[temp_v!(1)]; + /* + &SystemClauseType::GetClause => { + let head = self[temp_v!(1)]; - let subsection = match self.store(self.deref(head)) { - Addr::Str(s) => match &self.heap[s] { - &HeapCellValue::NamedStr(arity, ref name, ..) => { - indices.get_clause_subsection( - name.owning_module(), - name.clone(), - arity, - ) - } - _ => { + let subsection = match self.store(self.deref(head)) { + Addr::Str(s) => match &self.heap[s] { + &HeapCellValue::NamedStr(arity, ref name, ..) => { + indices.get_clause_subsection( + name.owning_module(), + name.clone(), + arity, + ) + } + _ => { + unreachable!() + } + }, + Addr::Con(h) if self.heap.atom_at(h) => { + if let &HeapCellValue::Atom(ref name, _) = &self.heap[h] { + indices.get_clause_subsection( + name.owning_module(), + name.clone(), + 0, + ) + } else { unreachable!() - } - }, - Addr::Con(h) if self.heap.atom_at(h) => { - if let &HeapCellValue::Atom(ref name, _) = &self.heap[h] { - indices.get_clause_subsection( - name.owning_module(), - name.clone(), - 0, - ) - } else { - unreachable!() - } - } - _ => { - unreachable!() - } - }; + } + } + _ => { + unreachable!() + } + }; - match subsection { - Some(dynamic_predicate_info) => { - self.execute_at_index( - 2, - dir_entry!(dynamic_predicate_info.clauses_subsection_p), - ); + match subsection { + Some(dynamic_predicate_info) => { + self.execute_at_index( + 2, + dir_entry!(dynamic_predicate_info.clauses_subsection_p), + ); - return Ok(()); - } - _ => { - unreachable!() - } - } - } -*/ + return Ok(()); + } + _ => { + unreachable!() + } + } + } + */ &SystemClauseType::GetCutPoint => { let a1 = self[temp_v!(1)]; let a2 = Addr::CutPoint(self.b0); @@ -4216,7 +3959,8 @@ impl MachineState { return Ok(()); } - let cp = (self.stack.index_and_frame(self.e).prelude.cp - 1).unwrap(); + let cp = + (self.stack.index_and_frame(self.e).prelude.cp - 1).unwrap(); let e = self.stack.index_and_frame(self.e).prelude.e; let e = Addr::Usize(e); @@ -4265,9 +4009,7 @@ impl MachineState { let addr = self.store(self.deref(self[temp_v!(1)])); let p = match self.heap.to_local_code_ptr(&addr) { - Some(p) => { - p + 1 - } + Some(p) => p + 1, None => { self.fail = true; return Ok(()); @@ -4290,19 +4032,15 @@ impl MachineState { let n = n.and_then(std::char::from_u32); self.fail = match n { - Some(c) => { - non_quoted_token(once(c)) - } - None => { - true - } + Some(c) => non_quoted_token(once(c)), + None => true, }; } Addr::Char(c) => { self.fail = non_quoted_token(once(c)); } Addr::Con(h) => { - if let HeapCellValue::Atom(atom, _) = &self.heap[h] { + if let HeapCellValue::Atom(atom, _) = &self.heap[h] { self.fail = non_quoted_token(atom.as_str().chars()); } } @@ -4319,8 +4057,7 @@ impl MachineState { readline::set_prompt(false); match result { - Ok(()) => { - } + Ok(()) => {} Err(e) => { *current_input_stream = readline::input_stream(); return Err(e); @@ -4330,12 +4067,7 @@ impl MachineState { &SystemClauseType::ReadTerm => { readline::set_prompt(false); - let stream = self.get_stream_or_alias( - self[temp_v!(1)], - indices, - "read_term", - 3, - )?; + let stream = self.get_stream_or_alias(self[temp_v!(1)], indices, "read_term", 3)?; self.read_term(stream, indices)?; } @@ -4344,27 +4076,22 @@ impl MachineState { let chars = heap_pstr_iter.to_string(); if let Addr::EmptyList = heap_pstr_iter.focus() { - let term_write_result = - match self.read( - Stream::from(chars), - self.atom_tbl.clone(), - &indices.op_dir, - ) { - Ok(term_write_result) => { - term_write_result - } - Err(e) => { - let stub = MachineError::functor_stub( - clause_name!("read_term_from_chars"), - 2, - ); + let term_write_result = match self.read( + Stream::from(chars), + self.atom_tbl.clone(), + &indices.op_dir, + ) { + Ok(term_write_result) => term_write_result, + Err(e) => { + let stub = + MachineError::functor_stub(clause_name!("read_term_from_chars"), 2); - let h = self.heap.h(); - let e = MachineError::session_error(h, SessionError::from(e)); + let h = self.heap.h(); + let e = MachineError::session_error(h, SessionError::from(e)); - return Err(self.error_form(e, stub)); - } - }; + return Err(self.error_form(e, stub)); + } + }; let result = Addr::HeapCell(term_write_result.heap_loc); @@ -4382,9 +4109,9 @@ impl MachineState { self.reset_block(addr); } &SystemClauseType::ResetContinuationMarker => { - self[temp_v!(3)] = self.heap.to_unifiable( - HeapCellValue::Atom(clause_name!("none"), None) - ); + self[temp_v!(3)] = self + .heap + .to_unifiable(HeapCellValue::Atom(clause_name!("none"), None)); let h = self.heap.h(); @@ -4397,23 +4124,15 @@ impl MachineState { &SystemClauseType::SetSeed => { let seed = self.store(self.deref(self[temp_v!(1)])); - let seed = - match Number::try_from((seed, &self.heap)) { - Ok(Number::Fixnum(n)) => { - Integer::from(n) - } - Ok(Number::Integer(n)) => { - Integer::from(n.as_ref()) - } - Ok(Number::Rational(n)) - if n.denom() == &1 => { - n.numer().clone() - } - _ => { - self.fail = true; - return Ok(()); - } - }; + let seed = match Number::try_from((seed, &self.heap)) { + Ok(Number::Fixnum(n)) => Integer::from(n), + Ok(Number::Integer(n)) => Integer::from(n.as_ref()), + Ok(Number::Rational(n)) if n.denom() == &1 => n.numer().clone(), + _ => { + self.fail = true; + return Ok(()); + } + }; let mut rand = RANDOM_STATE.borrow_mut(); rand.seed(&seed); @@ -4443,64 +4162,50 @@ impl MachineState { let addr = self.store(self.deref(self[temp_v!(1)])); let port = self.store(self.deref(self[temp_v!(2)])); - let socket_atom = - match addr { - Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { - name.clone() - } else { - unreachable!() - } - } - _ => { - unreachable!() - } - }; - - let port = - match port { - Addr::Fixnum(n) => { - n.to_string() - } - Addr::Usize(n) => { - n.to_string() - } - Addr::Con(h) => { - match &self.heap[h] { - HeapCellValue::Atom(ref name, _) => { - name.as_str().to_string() - } - HeapCellValue::Integer(ref n) => { - n.to_string() - } - _ => { - unreachable!() - } - } - } - _ => { - unreachable!() - } - }; - - let socket_addr = - format!( - "{}:{}", - if socket_atom.as_str() == "" { - "127.0.0.1" + let socket_atom = match addr { + Addr::Con(h) if self.heap.atom_at(h) => { + if let HeapCellValue::Atom(ref name, _) = &self.heap[h] { + name.clone() } else { - socket_atom.as_str() - }, - port, - ); + unreachable!() + } + } + _ => { + unreachable!() + } + }; + + let port = match port { + Addr::Fixnum(n) => n.to_string(), + Addr::Usize(n) => n.to_string(), + Addr::Con(h) => match &self.heap[h] { + HeapCellValue::Atom(ref name, _) => name.as_str().to_string(), + HeapCellValue::Integer(ref n) => n.to_string(), + _ => { + unreachable!() + } + }, + _ => { + unreachable!() + } + }; + + let socket_addr = format!( + "{}:{}", + if socket_atom.as_str() == "" { + "127.0.0.1" + } else { + socket_atom.as_str() + }, + port, + ); let alias = self[temp_v!(4)]; let eof_action = self[temp_v!(5)]; let reposition = self[temp_v!(6)]; let stream_type = self[temp_v!(7)]; - let options = - self.to_stream_options(alias, eof_action, reposition, stream_type); + let options = self.to_stream_options(alias, eof_action, reposition, stream_type); if options.reposition { return Err(self.reposition_error("socket_client_open", 3)); @@ -4516,122 +4221,111 @@ impl MachineState { } } - let stream = - match TcpStream::connect(&socket_addr).map_err(|e| e.kind()) { - Ok(tcp_stream) => { - let socket_addr = clause_name!(socket_addr, self.atom_tbl); + let stream = match TcpStream::connect(&socket_addr).map_err(|e| e.kind()) { + Ok(tcp_stream) => { + let socket_addr = clause_name!(socket_addr, self.atom_tbl); - let mut stream = { - let tls = match self.store(self.deref(self[temp_v!(8)])) { - Addr::Con(h) if self.heap.atom_at(h) => { - if let HeapCellValue::Atom(ref atom, _) = &self.heap[h] { - atom.as_str() - } else { - unreachable!() - } - } - _ => { + let mut stream = { + let tls = match self.store(self.deref(self[temp_v!(8)])) { + Addr::Con(h) if self.heap.atom_at(h) => { + if let HeapCellValue::Atom(ref atom, _) = &self.heap[h] { + atom.as_str() + } else { unreachable!() } - }; - - match tls { - "false" => { Stream::from_tcp_stream(socket_addr, tcp_stream) } - "true" => { let connector = TlsConnector::new().unwrap(); - let stream = match connector.connect(socket_atom.as_str(), tcp_stream) { - Ok(tls_stream) => { tls_stream } - Err(_) => { return Err(self.open_permission_error(addr, "socket_client_open", 3)); } - }; - - Stream::from_tls_stream(socket_addr, stream) - } - _ => { unreachable!() } } - }; + _ => { + unreachable!() + } + }; - stream.options = options; + match tls { + "false" => Stream::from_tcp_stream(socket_addr, tcp_stream), + "true" => { + let connector = TlsConnector::new().unwrap(); + let stream = + match connector.connect(socket_atom.as_str(), tcp_stream) { + Ok(tls_stream) => tls_stream, + Err(_) => { + return Err(self.open_permission_error( + addr, + "socket_client_open", + 3, + )); + } + }; - if let Some(ref alias) = &stream.options.alias { - indices.stream_aliases.insert(alias.clone(), stream.clone()); + Stream::from_tls_stream(socket_addr, stream) + } + _ => { + unreachable!() + } } + }; - indices.streams.insert(stream.clone()); + stream.options = options; - self.heap.to_unifiable(HeapCellValue::Stream(stream)) + if let Some(ref alias) = &stream.options.alias { + indices.stream_aliases.insert(alias.clone(), stream.clone()); } - Err(ErrorKind::PermissionDenied) => { - return Err(self.open_permission_error(addr, "socket_client_open", 3)); - } - Err(ErrorKind::NotFound) => { - let stub = MachineError::functor_stub( - clause_name!("socket_client_open"), - 3, - ); - let err = MachineError::existence_error( - self.heap.h(), - ExistenceError::SourceSink(addr), - ); + indices.streams.insert(stream.clone()); - return Err(self.error_form(err, stub)); - } - Err(_) => { - // for now, just fail. expand to meaningful error messages later. - self.fail = true; - return Ok(()); - } - }; + self.heap.to_unifiable(HeapCellValue::Stream(stream)) + } + Err(ErrorKind::PermissionDenied) => { + return Err(self.open_permission_error(addr, "socket_client_open", 3)); + } + Err(ErrorKind::NotFound) => { + let stub = + MachineError::functor_stub(clause_name!("socket_client_open"), 3); + + let err = MachineError::existence_error( + self.heap.h(), + ExistenceError::SourceSink(addr), + ); + + return Err(self.error_form(err, stub)); + } + Err(_) => { + // for now, just fail. expand to meaningful error messages later. + self.fail = true; + return Ok(()); + } + }; let stream_addr = self.store(self.deref(self[temp_v!(3)])); self.bind(stream_addr.as_var().unwrap(), stream); } &SystemClauseType::SocketServerOpen => { let addr = self.store(self.deref(self[temp_v!(1)])); - let socket_atom = - match addr { - Addr::EmptyList => { - "127.0.0.1".to_string() - } - Addr::Con(h) if self.heap.atom_at(h) => { - match &self.heap[h] { - HeapCellValue::Atom(ref name, _) => { - name.as_str().to_string() - } - _ => { - unreachable!() - } - } - } + let socket_atom = match addr { + Addr::EmptyList => "127.0.0.1".to_string(), + Addr::Con(h) if self.heap.atom_at(h) => match &self.heap[h] { + HeapCellValue::Atom(ref name, _) => name.as_str().to_string(), _ => { unreachable!() } - }; + }, + _ => { + unreachable!() + } + }; - let port = - match self.store(self.deref(self[temp_v!(2)])) { - Addr::Fixnum(n) => { - n.to_string() - } - Addr::Usize(n) => { - n.to_string() - } - Addr::Con(h) => { - match &self.heap[h] { - HeapCellValue::Integer(ref n) => { - n.to_string() - } - _ => { - unreachable!() - } - } - } - addr if addr.is_ref() => { - "0".to_string() - } + let port = match self.store(self.deref(self[temp_v!(2)])) { + Addr::Fixnum(n) => n.to_string(), + Addr::Usize(n) => n.to_string(), + Addr::Con(h) => match &self.heap[h] { + HeapCellValue::Integer(ref n) => n.to_string(), _ => { unreachable!() } - }; + }, + addr if addr.is_ref() => "0".to_string(), + _ => { + unreachable!() + } + }; let had_zero_port = &port == "0"; @@ -4648,7 +4342,8 @@ impl MachineState { if let Some(port) = port { ( - self.heap.to_unifiable(HeapCellValue::TcpListener(tcp_listener)), + self.heap + .to_unifiable(HeapCellValue::TcpListener(tcp_listener)), port as usize, ) } else { @@ -4678,8 +4373,7 @@ impl MachineState { let reposition = self[temp_v!(6)]; let stream_type = self[temp_v!(7)]; - let options = - self.to_stream_options(alias, eof_action, reposition, stream_type); + let options = self.to_stream_options(alias, eof_action, reposition, stream_type); if options.reposition { return Err(self.reposition_error("socket_server_accept", 4)); @@ -4696,58 +4390,55 @@ impl MachineState { } match self.store(self.deref(self[temp_v!(1)])) { - Addr::TcpListener(h) => { - match &mut self.heap[h] { - HeapCellValue::TcpListener(ref mut tcp_listener) => { - match tcp_listener.accept().ok() { - Some((tcp_stream, socket_addr)) => { - let client = - clause_name!(format!("{}", socket_addr), self.atom_tbl); + Addr::TcpListener(h) => match &mut self.heap[h] { + HeapCellValue::TcpListener(ref mut tcp_listener) => { + match tcp_listener.accept().ok() { + Some((tcp_stream, socket_addr)) => { + let client = + clause_name!(format!("{}", socket_addr), self.atom_tbl); - let mut tcp_stream = - Stream::from_tcp_stream(client.clone(), tcp_stream); + let mut tcp_stream = + Stream::from_tcp_stream(client.clone(), tcp_stream); - tcp_stream.options = options; + tcp_stream.options = options; - if let Some(ref alias) = &tcp_stream.options.alias { - indices.stream_aliases.insert( - alias.clone(), - tcp_stream.clone(), - ); - } - - indices.streams.insert(tcp_stream.clone()); - - let tcp_stream = - self.heap.to_unifiable(HeapCellValue::Stream(tcp_stream)); - - let client = - self.heap.to_unifiable(HeapCellValue::Atom(client, None)); - - let client_addr = self.store(self.deref(self[temp_v!(2)])); - let stream_addr = self.store(self.deref(self[temp_v!(3)])); - - self.bind(client_addr.as_var().unwrap(), client); - self.bind(stream_addr.as_var().unwrap(), tcp_stream); - } - None => { - self.fail = true; - return Ok(()); + if let Some(ref alias) = &tcp_stream.options.alias { + indices + .stream_aliases + .insert(alias.clone(), tcp_stream.clone()); } + + indices.streams.insert(tcp_stream.clone()); + + let tcp_stream = + self.heap.to_unifiable(HeapCellValue::Stream(tcp_stream)); + + let client = + self.heap.to_unifiable(HeapCellValue::Atom(client, None)); + + let client_addr = self.store(self.deref(self[temp_v!(2)])); + let stream_addr = self.store(self.deref(self[temp_v!(3)])); + + self.bind(client_addr.as_var().unwrap(), client); + self.bind(stream_addr.as_var().unwrap(), tcp_stream); + } + None => { + self.fail = true; + return Ok(()); } } - culprit => { - let culprit = culprit.as_addr(h); - - return Err(self.type_error( - ValidType::TcpListener, - culprit, - clause_name!("socket_server_accept"), - 4, - )); - } } - } + culprit => { + let culprit = culprit.as_addr(h); + + return Err(self.type_error( + ValidType::TcpListener, + culprit, + clause_name!("socket_server_accept"), + 4, + )); + } + }, culprit => { return Err(self.type_error( ValidType::TcpListener, @@ -4775,12 +4466,8 @@ impl MachineState { } } &SystemClauseType::SetStreamPosition => { - let mut stream = self.get_stream_or_alias( - self[temp_v!(1)], - indices, - "set_stream_position", - 2, - )?; + let mut stream = + self.get_stream_or_alias(self[temp_v!(1)], indices, "set_stream_position", 2)?; if !stream.options.reposition { let stub = MachineError::functor_stub(clause_name!("set_stream_position"), 2); @@ -4797,132 +4484,98 @@ impl MachineState { let position = self.store(self.deref(self[temp_v!(2)])); - let position = - match Number::try_from((position, &self.heap)) { - Ok(Number::Fixnum(n)) => { - n as u64 + let position = match Number::try_from((position, &self.heap)) { + Ok(Number::Fixnum(n)) => n as u64, + Ok(Number::Integer(n)) => { + if let Some(n) = n.to_u64() { + n + } else { + self.fail = true; + return Ok(()); } - Ok(Number::Integer(n)) => { - if let Some(n) = n.to_u64() { - n - } else { - self.fail = true; - return Ok(()); - } - } - _ => { - unreachable!() - } - }; + } + _ => { + unreachable!() + } + }; stream.set_position(position); } &SystemClauseType::StreamProperty => { - let mut stream = self.get_stream_or_alias( - self[temp_v!(1)], - indices, - "stream_property", - 2, - )?; + let mut stream = + self.get_stream_or_alias(self[temp_v!(1)], indices, "stream_property", 2)?; - let property = - match self.store(self.deref(self[temp_v!(2)])) { - Addr::Con(h) if self.heap.atom_at(h) => { - match &self.heap[h] { - HeapCellValue::Atom(ref name, _) => { - match name.as_str() { - "file_name" => { - if let Some(file_name) = stream.file_name() { - HeapCellValue::Atom( - file_name, - None, - ) - } else { - self.fail = true; - return Ok(()); - } - } - "mode" => { - HeapCellValue::Atom( - clause_name!(stream.mode()), - None, - ) - } - "direction" => { - HeapCellValue::Atom( - if stream.is_input_stream() && stream.is_output_stream() { - clause_name!("input_output") - } else if stream.is_input_stream() { - clause_name!("input") - } else { - clause_name!("output") - }, - None, - ) - } - "alias" => { - if let Some(alias) = &stream.options.alias { - HeapCellValue::Atom( - alias.clone(), - None, - ) - } else { - self.fail = true; - return Ok(()); - } - } - "position" => { - if let Some(position) = stream.position() { - HeapCellValue::Addr(Addr::Usize(position as usize)) - } else { - self.fail = true; - return Ok(()); - } - } - "end_of_stream" => { - let end_of_stream_pos = stream.position_relative_to_end(); - - HeapCellValue::Atom( - clause_name!(end_of_stream_pos.as_str()), - None, - ) - } - "eof_action" => { - HeapCellValue::Atom( - clause_name!(stream.options.eof_action.as_str()), - None, - ) - } - "reposition" => { - HeapCellValue::Atom( - clause_name!(if stream.options.reposition { - "true" - } else { - "false" - }), - None, - ) - } - "type" => { - HeapCellValue::Atom( - clause_name!(stream.options.stream_type.as_property_str()), - None, - ) - } - _ => { - unreachable!() - } - } - } - _ => { - unreachable!() + let property = match self.store(self.deref(self[temp_v!(2)])) { + Addr::Con(h) if self.heap.atom_at(h) => match &self.heap[h] { + HeapCellValue::Atom(ref name, _) => match name.as_str() { + "file_name" => { + if let Some(file_name) = stream.file_name() { + HeapCellValue::Atom(file_name, None) + } else { + self.fail = true; + return Ok(()); } } - } + "mode" => HeapCellValue::Atom(clause_name!(stream.mode()), None), + "direction" => HeapCellValue::Atom( + if stream.is_input_stream() && stream.is_output_stream() { + clause_name!("input_output") + } else if stream.is_input_stream() { + clause_name!("input") + } else { + clause_name!("output") + }, + None, + ), + "alias" => { + if let Some(alias) = &stream.options.alias { + HeapCellValue::Atom(alias.clone(), None) + } else { + self.fail = true; + return Ok(()); + } + } + "position" => { + if let Some(position) = stream.position() { + HeapCellValue::Addr(Addr::Usize(position as usize)) + } else { + self.fail = true; + return Ok(()); + } + } + "end_of_stream" => { + let end_of_stream_pos = stream.position_relative_to_end(); + + HeapCellValue::Atom(clause_name!(end_of_stream_pos.as_str()), None) + } + "eof_action" => HeapCellValue::Atom( + clause_name!(stream.options.eof_action.as_str()), + None, + ), + "reposition" => HeapCellValue::Atom( + clause_name!(if stream.options.reposition { + "true" + } else { + "false" + }), + None, + ), + "type" => HeapCellValue::Atom( + clause_name!(stream.options.stream_type.as_property_str()), + None, + ), + _ => { + unreachable!() + } + }, _ => { unreachable!() } - }; + }, + _ => { + unreachable!() + } + }; let property = self.heap.to_unifiable(property); self.unify(self[temp_v!(3)], property); @@ -4991,8 +4644,7 @@ impl MachineState { self.unify(value, Addr::HeapCell(h)); } - &SystemClauseType::Succeed => { - } + &SystemClauseType::Succeed => {} &SystemClauseType::TermAttributedVariables => { let seen_vars = self.attr_vars_of_term(self[temp_v!(1)]); let outcome = Addr::HeapCell(self.heap.to_list(seen_vars.into_iter())); @@ -5001,7 +4653,7 @@ impl MachineState { } &SystemClauseType::TermVariables => { let a1 = self[temp_v!(1)]; - let mut seen_set = IndexSet::new(); + let mut seen_set = IndexSet::new(); let mut seen_vars = vec![]; for addr in self.acyclic_pre_order_iter(a1) { @@ -5016,10 +4668,8 @@ impl MachineState { } &SystemClauseType::TruncateLiftedHeapTo => { match self.store(self.deref(self[temp_v!(1)])) { - Addr::Usize(lh_offset) => - self.lifted_heap.truncate(lh_offset), - _ => - self.fail = true, + Addr::Usize(lh_offset) => self.lifted_heap.truncate(lh_offset), + _ => self.fail = true, } } &SystemClauseType::UnifyWithOccursCheck => { @@ -5051,12 +4701,9 @@ impl MachineState { self.fail = self.structural_eq_test(); } &SystemClauseType::WAMInstructions => { - let module_name = atom_from!( - self, - self.store(self.deref(self[temp_v!(1)])) - ); + let module_name = atom_from!(self, self.store(self.deref(self[temp_v!(1)]))); - let name = self[temp_v!(2)]; + let name = self[temp_v!(2)]; let arity = self[temp_v!(3)]; let name = match self.store(self.deref(name)) { @@ -5074,18 +4721,13 @@ impl MachineState { let arity = self.store(self.deref(arity)); - let arity = - match Number::try_from((arity, &self.heap)) { - Ok(Number::Fixnum(n)) => { - Integer::from(n) - } - Ok(Number::Integer(n)) => { - Integer::from(n.as_ref()) - } - _ => { - unreachable!() - } - }; + let arity = match Number::try_from((arity, &self.heap)) { + Ok(Number::Fixnum(n)) => Integer::from(n), + Ok(Number::Integer(n)) => Integer::from(n.as_ref()), + _ => { + unreachable!() + } + }; let key = (name.clone(), arity.to_usize().unwrap()); @@ -5099,11 +4741,9 @@ impl MachineState { let err = MachineError::session_error( h, - SessionError::from( - CompilationError::InvalidModuleResolution( - module_name - ) - ), + SessionError::from(CompilationError::InvalidModuleResolution( + module_name, + )), ); let err = self.error_form(err, stub); @@ -5114,50 +4754,45 @@ impl MachineState { }, }; - let first_idx = - match first_idx { - Some(ref idx) if idx.local().is_some() => { - if let Some(idx) = idx.local() { - idx - } else { - unreachable!() - } + let first_idx = match first_idx { + Some(ref idx) if idx.local().is_some() => { + if let Some(idx) = idx.local() { + idx + } else { + unreachable!() } - _ => { - let arity = arity.to_usize().unwrap(); - let stub = MachineError::functor_stub(name.clone(), arity); - let h = self.heap.h(); + } + _ => { + let arity = arity.to_usize().unwrap(); + let stub = MachineError::functor_stub(name.clone(), arity); + let h = self.heap.h(); - let err = MachineError::existence_error( - h, - ExistenceError::Procedure(name, arity), - ); + let err = MachineError::existence_error( + h, + ExistenceError::Procedure(name, arity), + ); - let err = self.error_form(err, stub); + let err = self.error_form(err, stub); - self.throw_exception(err); - return Ok(()); - } - }; + self.throw_exception(err); + return Ok(()); + } + }; let mut h = self.heap.h(); let mut functors = vec![]; let mut functor_list = vec![]; - walk_code( - &code_repo.code, - first_idx, - |instr| { - let old_len = functors.len(); - instr.enqueue_functors(h, &mut functors); - let new_len = functors.len(); + walk_code(&code_repo.code, first_idx, |instr| { + let old_len = functors.len(); + instr.enqueue_functors(h, &mut functors); + let new_len = functors.len(); - for index in old_len .. new_len { - functor_list.push(Addr::HeapCell(h)); - h += functors[index].len(); - } - }, - ); + for index in old_len..new_len { + functor_list.push(Addr::HeapCell(h)); + h += functors[index].len(); + } + }); for functor in functors { self.heap.extend(functor.into_iter()); @@ -5169,12 +4804,8 @@ impl MachineState { self.unify(listing, listing_var); } &SystemClauseType::WriteTerm => { - let mut stream = self.get_stream_or_alias( - self[temp_v!(1)], - indices, - "write_term", - 3, - )?; + let mut stream = + self.get_stream_or_alias(self[temp_v!(1)], indices, "write_term", 3)?; self.check_stream_properties( &mut stream, @@ -5184,14 +4815,13 @@ impl MachineState { 3, )?; - let opt_err = - if !stream.is_output_stream() { - Some("stream") // 8.14.2.3 g) - } else if stream.options.stream_type == StreamType::Binary { - Some("binary_stream") // 8.14.2.3 h) - } else { - None - }; + let opt_err = if !stream.is_output_stream() { + Some("stream") // 8.14.2.3 g) + } else if stream.options.stream_type == StreamType::Binary { + Some("binary_stream") // 8.14.2.3 h) + } else { + None + }; if let Some(err_string) = opt_err { return Err(self.stream_permission_error( @@ -5205,22 +4835,18 @@ impl MachineState { let addr = self[temp_v!(2)]; - let printer = - match self.write_term(&indices.op_dir)? { - None => { - self.fail = true; - return Ok(()); - } - Some(printer) => { - printer - } - }; + let printer = match self.write_term(&indices.op_dir)? { + None => { + self.fail = true; + return Ok(()); + } + Some(printer) => printer, + }; let output = printer.print(addr); match write!(&mut stream, "{}", output.result()) { - Ok(_) => { - } + Ok(_) => {} Err(_) => { let stub = MachineError::functor_stub(clause_name!("open"), 4); let err = MachineError::existence_error( @@ -5237,16 +4863,13 @@ impl MachineState { &SystemClauseType::WriteTermToChars => { let addr = self[temp_v!(2)]; - let printer = - match self.write_term(&indices.op_dir)? { - None => { - self.fail = true; - return Ok(()); - } - Some(printer) => { - printer - } - }; + let printer = match self.write_term(&indices.op_dir)? { + None => { + self.fail = true; + return Ok(()); + } + Some(printer) => printer, + }; let result = printer.print(addr).result(); let chars = self.heap.put_complete_string(&result); @@ -5262,8 +4885,7 @@ impl MachineState { &SystemClauseType::ScryerPrologVersion => { use crate::git_version::git_version; let version = self[temp_v!(1)]; - let buffer = - git_version!(cargo_prefix = "cargo:", fallback = "unknown"); + let buffer = git_version!(cargo_prefix = "cargo:", fallback = "unknown"); let chars = buffer.chars().map(|c| Addr::Char(c)); let result = Addr::HeapCell(self.heap.to_list(chars)); self.unify(version, result); @@ -5273,8 +4895,7 @@ impl MachineState { let mut bytes: [u8; 1] = [0]; match rng().fill(&mut bytes) { - Ok(()) => { - } + Ok(()) => {} Err(_) => { // the error payload here is of type 'Unspecified', // which contains no information whatsoever. So, for now, @@ -5284,9 +4905,9 @@ impl MachineState { } } - let byte = self.heap.to_unifiable( - HeapCellValue::Integer(Rc::new(Integer::from(bytes[0]))) - ); + let byte = self + .heap + .to_unifiable(HeapCellValue::Integer(Rc::new(Integer::from(bytes[0])))); self.unify(arg, byte); } @@ -5296,41 +4917,120 @@ impl MachineState { let algorithm = self.atom_argument_to_string(4); - let ints_list = - match algorithm.as_str() { - "sha3_224" => { let mut context = Sha3_224::new(); - context.input(&bytes); - Addr::HeapCell(self.heap.to_list(context.result().as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) } - "sha3_256" => { let mut context = Sha3_256::new(); - context.input(&bytes); - Addr::HeapCell(self.heap.to_list(context.result().as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) } - "sha3_384" => { let mut context = Sha3_384::new(); - context.input(&bytes); - Addr::HeapCell(self.heap.to_list(context.result().as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) } - "sha3_512" => { let mut context = Sha3_512::new(); - context.input(&bytes); - Addr::HeapCell(self.heap.to_list(context.result().as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) } - "blake2s256" => { let mut context = Blake2s::new(); - context.input(&bytes); - Addr::HeapCell(self.heap.to_list(context.result().as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) } - "blake2b512" => { let mut context = Blake2b::new(); - context.input(&bytes); - Addr::HeapCell(self.heap.to_list(context.result().as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) } - "ripemd160" => { let mut context = Ripemd160::new(); - context.input(&bytes); - Addr::HeapCell(self.heap.to_list(context.result().as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) } - _ => { let ints = digest::digest( - match algorithm.as_str() { - "sha256" => { &digest::SHA256 } - "sha384" => { &digest::SHA384 } - "sha512" => { &digest::SHA512 } - "sha512_256" => { &digest::SHA512_256 } - _ => { unreachable!() } - }, - &bytes); - Addr::HeapCell(self.heap.to_list(ints.as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) - } - }; + let ints_list = match algorithm.as_str() { + "sha3_224" => { + let mut context = Sha3_224::new(); + context.input(&bytes); + Addr::HeapCell( + self.heap.to_list( + context + .result() + .as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + "sha3_256" => { + let mut context = Sha3_256::new(); + context.input(&bytes); + Addr::HeapCell( + self.heap.to_list( + context + .result() + .as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + "sha3_384" => { + let mut context = Sha3_384::new(); + context.input(&bytes); + Addr::HeapCell( + self.heap.to_list( + context + .result() + .as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + "sha3_512" => { + let mut context = Sha3_512::new(); + context.input(&bytes); + Addr::HeapCell( + self.heap.to_list( + context + .result() + .as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + "blake2s256" => { + let mut context = Blake2s::new(); + context.input(&bytes); + Addr::HeapCell( + self.heap.to_list( + context + .result() + .as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + "blake2b512" => { + let mut context = Blake2b::new(); + context.input(&bytes); + Addr::HeapCell( + self.heap.to_list( + context + .result() + .as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + "ripemd160" => { + let mut context = Ripemd160::new(); + context.input(&bytes); + Addr::HeapCell( + self.heap.to_list( + context + .result() + .as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + _ => { + let ints = digest::digest( + match algorithm.as_str() { + "sha256" => &digest::SHA256, + "sha384" => &digest::SHA384, + "sha512" => &digest::SHA512, + "sha512_256" => &digest::SHA512_256, + _ => { + unreachable!() + } + }, + &bytes, + ); + Addr::HeapCell( + self.heap.to_list( + ints.as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + } + }; self.unify(self[temp_v!(3)], ints_list); } @@ -5346,38 +5046,51 @@ impl MachineState { let length = self.store(self.deref(self[temp_v!(6)])); - let length = - match Number::try_from((length, &self.heap)) { - Ok(Number::Fixnum(n)) => { - usize::try_from(n).unwrap() + let length = match Number::try_from((length, &self.heap)) { + Ok(Number::Fixnum(n)) => usize::try_from(n).unwrap(), + Ok(Number::Integer(n)) => match n.to_usize() { + Some(u) => u, + _ => { + self.fail = true; + return Ok(()); } - Ok(Number::Integer(n)) => { - match n.to_usize() { - Some(u) => { u } - _ => { self.fail = true; return Ok(()); } - } + }, + _ => { + unreachable!() + } + }; + + let ints_list = { + let digest_alg = match algorithm.as_str() { + "sha256" => hkdf::HKDF_SHA256, + "sha384" => hkdf::HKDF_SHA384, + "sha512" => hkdf::HKDF_SHA512, + _ => { + self.fail = true; + return Ok(()); } - _ => { unreachable!() } }; + let salt = hkdf::Salt::new(digest_alg, &salt); + let mut bytes: Vec = Vec::new(); + bytes.resize(length, 0); + match salt.extract(&data).expand(&[&info[..]], MyKey(length)) { + Ok(r) => { + r.fill(&mut bytes).unwrap(); + } + _ => { + self.fail = true; + return Ok(()); + } + } - let ints_list = - { let digest_alg = - match algorithm.as_str() { - "sha256" => { hkdf::HKDF_SHA256 } - "sha384" => { hkdf::HKDF_SHA384 } - "sha512" => { hkdf::HKDF_SHA512 } - _ => { self.fail = true; return Ok(()); } - }; - let salt = hkdf::Salt::new(digest_alg, &salt); - let mut bytes : Vec = Vec::new(); - bytes.resize(length, 0); - match salt.extract(&data).expand(&[&info[..]], MyKey(length)) { - Ok(r) => { r.fill(&mut bytes).unwrap(); } - _ => { self.fail = true; return Ok(()); } - } - - Addr::HeapCell(self.heap.to_list(bytes.iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) - }; + Addr::HeapCell( + self.heap.to_list( + bytes + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + }; self.unify(self[temp_v!(7)], ints_list); } @@ -5389,33 +5102,38 @@ impl MachineState { let iterations = self.store(self.deref(self[temp_v!(3)])); - let iterations = - match Number::try_from((iterations, &self.heap)) { - Ok(Number::Fixnum(n)) => { - u64::try_from(n).unwrap() + let iterations = match Number::try_from((iterations, &self.heap)) { + Ok(Number::Fixnum(n)) => u64::try_from(n).unwrap(), + Ok(Number::Integer(n)) => match n.to_u64() { + Some(i) => i, + None => { + self.fail = true; + return Ok(()); } - Ok(Number::Integer(n)) => { - match n.to_u64() { - Some(i) => { i } - None => { - self.fail = true; - return Ok(()); - } - } - } - _ => { - unreachable!() - } - }; + }, + _ => { + unreachable!() + } + }; - let ints_list = - { let mut bytes = [0u8; digest::SHA512_OUTPUT_LEN]; - pbkdf2::derive(pbkdf2::PBKDF2_HMAC_SHA512, - NonZeroU32::new(iterations as u32).unwrap(), &salt, - &data, &mut bytes); + let ints_list = { + let mut bytes = [0u8; digest::SHA512_OUTPUT_LEN]; + pbkdf2::derive( + pbkdf2::PBKDF2_HMAC_SHA512, + NonZeroU32::new(iterations as u32).unwrap(), + &salt, + &data, + &mut bytes, + ); - Addr::HeapCell(self.heap.to_list(bytes.iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))) - }; + Addr::HeapCell( + self.heap.to_list( + bytes + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ) + }; self.unify(self[temp_v!(4)], ints_list); } @@ -5433,19 +5151,30 @@ impl MachineState { let key = aead::LessSafeKey::new(unbound_key); let mut in_out = data.clone(); - let tag = - match key.seal_in_place_separate_tag(nonce, aead::Aad::from(aad), &mut in_out) { - Ok(d) => { d } - _ => { self.fail = true; return Ok(()); } - }; + let tag = match key.seal_in_place_separate_tag( + nonce, + aead::Aad::from(aad), + &mut in_out, + ) { + Ok(d) => d, + _ => { + self.fail = true; + return Ok(()); + } + }; - let tag_list = - Addr::HeapCell(self.heap.to_list(tag.as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))); + let tag_list = Addr::HeapCell( + self.heap.to_list( + tag.as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ); let complete_string = { - let buffer = String::from_iter(in_out.iter().map(|b| *b as char)); - self.heap.put_complete_string(&buffer) - }; + let buffer = String::from_iter(in_out.iter().map(|b| *b as char)); + self.heap.put_complete_string(&buffer) + }; self.unify(self[temp_v!(6)], tag_list); self.unify(self[temp_v!(7)], complete_string); @@ -5466,47 +5195,53 @@ impl MachineState { let mut in_out = data.clone(); let complete_string = { - let decrypted_data = - match key.open_in_place(nonce, aead::Aad::from(aad), &mut in_out) { - Ok(d) => { d } - _ => { self.fail = true; return Ok(()); } - }; + let decrypted_data = + match key.open_in_place(nonce, aead::Aad::from(aad), &mut in_out) { + Ok(d) => d, + _ => { + self.fail = true; + return Ok(()); + } + }; - let buffer = match encoding.as_str() { - "octet" => { String::from_iter(decrypted_data.iter().map(|b| *b as char)) } - "utf8" => { match String::from_utf8(decrypted_data.to_vec()) { - Ok(str) => { str } - _ => { self.fail = true; return Ok(()); } - } - } - _ => { unreachable!() } - }; + let buffer = match encoding.as_str() { + "octet" => String::from_iter(decrypted_data.iter().map(|b| *b as char)), + "utf8" => match String::from_utf8(decrypted_data.to_vec()) { + Ok(str) => str, + _ => { + self.fail = true; + return Ok(()); + } + }, + _ => { + unreachable!() + } + }; - self.heap.put_complete_string(&buffer) - }; + self.heap.put_complete_string(&buffer) + }; self.unify(self[temp_v!(6)], complete_string); } &SystemClauseType::CryptoCurveScalarMult => { let curve = self.atom_argument_to_string(1); let curve_id = match curve.as_str() { - "secp112r1" => { Nid::SECP112R1 } - "secp256k1" => { Nid::SECP256K1 } - _ => { unreachable!() } - }; + "secp112r1" => Nid::SECP112R1, + "secp256k1" => Nid::SECP256K1, + _ => { + unreachable!() + } + }; let scalar = self.store(self.deref(self[temp_v!(2)])); - let scalar = - match Number::try_from((scalar, &self.heap)) { - Ok(Number::Fixnum(n)) => { - Integer::from(n) - } - Ok(Number::Integer(n)) => { - Integer::from(&*n.clone()) - } - _ => { unreachable!() } - }; + let scalar = match Number::try_from((scalar, &self.heap)) { + Ok(Number::Fixnum(n)) => Integer::from(n), + Ok(Number::Integer(n)) => Integer::from(&*n.clone()), + _ => { + unreachable!() + } + }; let stub = MachineError::functor_stub(clause_name!("crypto_curve_scalar_mult"), 5); let qbytes = self.integers_to_bytevec(temp_v!(3), stub); @@ -5520,9 +5255,15 @@ impl MachineState { let mut rx = BigNum::new().unwrap(); let mut ry = BigNum::new().unwrap(); - result.affine_coordinates_gfp(&group, &mut rx, &mut ry, &mut bnctx).ok(); - let sx = self.heap.put_complete_string(&rx.to_dec_str().unwrap().to_string()); - let sy = self.heap.put_complete_string(&ry.to_dec_str().unwrap().to_string()); + result + .affine_coordinates_gfp(&group, &mut rx, &mut ry, &mut bnctx) + .ok(); + let sx = self + .heap + .put_complete_string(&rx.to_dec_str().unwrap().to_string()); + let sy = self + .heap + .put_complete_string(&ry.to_dec_str().unwrap().to_string()); self.unify(self[temp_v!(4)], sx); self.unify(self[temp_v!(5)], sy); @@ -5530,9 +5271,9 @@ impl MachineState { &SystemClauseType::Ed25519NewKeyPair => { let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(rng()).unwrap(); let complete_string = { - let buffer = String::from_iter(pkcs8_bytes.as_ref().iter().map(|b| *b as char)); - self.heap.put_complete_string(&buffer) - }; + let buffer = String::from_iter(pkcs8_bytes.as_ref().iter().map(|b| *b as char)); + self.heap.put_complete_string(&buffer) + }; self.unify(self[temp_v!(1)], complete_string); } @@ -5540,14 +5281,19 @@ impl MachineState { let bytes = self.string_encoding_bytes(1, "octet"); let key_pair = match signature::Ed25519KeyPair::from_pkcs8(&bytes) { - Ok(kp) => { kp } - _ => { self.fail = true; return Ok(()); } - }; + Ok(kp) => kp, + _ => { + self.fail = true; + return Ok(()); + } + }; let complete_string = { - let buffer = String::from_iter(key_pair.public_key().as_ref().iter().map(|b| *b as char)); - self.heap.put_complete_string(&buffer) - }; + let buffer = String::from_iter( + key_pair.public_key().as_ref().iter().map(|b| *b as char), + ); + self.heap.put_complete_string(&buffer) + }; self.unify(self[temp_v!(2)], complete_string); } @@ -5557,14 +5303,22 @@ impl MachineState { let data = self.string_encoding_bytes(2, &encoding); let key_pair = match signature::Ed25519KeyPair::from_pkcs8(&key) { - Ok(kp) => { kp } - _ => { self.fail = true; return Ok(()); } - }; + Ok(kp) => kp, + _ => { + self.fail = true; + return Ok(()); + } + }; let sig = key_pair.sign(&data); - let sig_list = - Addr::HeapCell(self.heap.to_list(sig.as_ref().iter().map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))))); + let sig_list = Addr::HeapCell( + self.heap.to_list( + sig.as_ref() + .iter() + .map(|b| HeapCellValue::from(Addr::Fixnum(*b as isize))), + ), + ); self.unify(self[temp_v!(4)], sig_list); } @@ -5577,8 +5331,11 @@ impl MachineState { let peer_public_key = signature::UnparsedPublicKey::new(&signature::ED25519, &key); match peer_public_key.verify(&data, &signature) { - Ok(_) => { } - _ => { self.fail = true; return Ok(()); } + Ok(_) => {} + _ => { + self.fail = true; + return Ok(()); + } } } &SystemClauseType::Curve25519ScalarMult => { @@ -5606,11 +5363,13 @@ impl MachineState { &SystemClauseType::LoadXML => { let string = self.heap_pstr_iter(self[temp_v!(1)]).to_string(); match roxmltree::Document::parse(&string) { - Ok(doc) => { let result = self.xml_node_to_term(indices, doc.root_element()); - self.unify(self[temp_v!(2)], result); + Ok(doc) => { + let result = self.xml_node_to_term(indices, doc.root_element()); + self.unify(self[temp_v!(2)], result); } - _ => { self.fail = true; - return Ok(()); + _ => { + self.fail = true; + return Ok(()); } } } @@ -5640,20 +5399,19 @@ impl MachineState { let padding = self.atom_argument_to_string(3); let charset = self.atom_argument_to_string(4); - let config = - if padding == "true" { - if charset == "standard" { - base64::STANDARD - } else { - base64::URL_SAFE - } + let config = if padding == "true" { + if charset == "standard" { + base64::STANDARD } else { - if charset == "standard" { - base64::STANDARD_NO_PAD - } else { - base64::URL_SAFE_NO_PAD - } - }; + base64::URL_SAFE + } + } else { + if charset == "standard" { + base64::STANDARD_NO_PAD + } else { + base64::URL_SAFE_NO_PAD + } + }; if self.store(self.deref(self[temp_v!(1)])).is_ref() { let b64 = self.heap_pstr_iter(self[temp_v!(2)]).to_string(); @@ -5674,7 +5432,6 @@ impl MachineState { let mut bytes = vec![]; for c in self.heap_pstr_iter(self[temp_v!(1)]).to_string().chars() { if c as u32 > 255 { - let stub = MachineError::functor_stub(clause_name!("chars_base64"), 3); let err = MachineError::type_error( @@ -5695,19 +5452,16 @@ impl MachineState { } } &SystemClauseType::LoadLibraryAsStream => { - let library_name = - atom_from!( - self, - self.store(self.deref(self[temp_v!(1)])) - ); + let library_name = atom_from!(self, self.store(self.deref(self[temp_v!(1)]))); use crate::LIBRARIES; match LIBRARIES.borrow().get(library_name.as_str()) { Some(library) => { - let var_ref = Ref::HeapCell(self.heap.push( - HeapCellValue::Stream(Stream::from(*library)) - )); + let var_ref = Ref::HeapCell( + self.heap + .push(HeapCellValue::Stream(Stream::from(*library))), + ); self.bind(var_ref, self[temp_v!(2)]); @@ -5720,24 +5474,19 @@ impl MachineState { let library_path = clause_name!(library_path_str.to_string(), self.atom_tbl); - let library_path_ref = Ref::HeapCell( - self.heap.push(HeapCellValue::Atom(library_path, None)) - ); + let library_path_ref = + Ref::HeapCell(self.heap.push(HeapCellValue::Atom(library_path, None))); self.bind(library_path_ref, self[temp_v!(3)]); } None => { - return Err( - self.error_form( - MachineError::existence_error( - self.heap.h(), - ExistenceError::ModuleSource( - ModuleSource::Library(library_name) - ), - ), - MachineError::functor_stub(clause_name!("load"), 1), - ) - ); + return Err(self.error_form( + MachineError::existence_error( + self.heap.h(), + ExistenceError::ModuleSource(ModuleSource::Library(library_name)), + ), + MachineError::functor_stub(clause_name!("load"), 1), + )); } } } @@ -5746,15 +5495,14 @@ impl MachineState { return_from_clause!(self.last_call, self) } - pub(super) - fn systemtime_to_timestamp( - &mut self, - system_time: SystemTime - ) -> Addr { + pub(super) fn systemtime_to_timestamp(&mut self, system_time: SystemTime) -> Addr { let datetime: DateTime = system_time.into(); let mut fstr = "[".to_string(); - let specifiers = vec!["Y","m","d","H","M","S","y","b","B","a","A","w","u","U","W","j","D","x","v"]; + let specifiers = vec![ + "Y", "m", "d", "H", "M", "S", "y", "b", "B", "a", "A", "w", "u", "U", "W", "j", "D", + "x", "v", + ]; for spec in specifiers { fstr.push_str(&format!("'{}'=\"%{}\", ", spec, spec).to_string()); } @@ -5763,11 +5511,7 @@ impl MachineState { self.heap.put_complete_string(&s) } - pub(super) - fn atom_argument_to_string( - &mut self, - atom_arg: usize, - ) -> String { + pub(super) fn atom_argument_to_string(&mut self, atom_arg: usize) -> String { match self.store(self.deref(self[temp_v!(atom_arg)])) { Addr::Con(h) if self.heap.atom_at(h) => { if let HeapCellValue::Atom(ref atom, _) = &self.heap[h] { @@ -5782,29 +5526,25 @@ impl MachineState { } } - pub(super) - fn string_encoding_bytes( - &mut self, - data_arg: usize, - encoding: &str, - ) -> Vec { + pub(super) fn string_encoding_bytes(&mut self, data_arg: usize, encoding: &str) -> Vec { let data = self.heap_pstr_iter(self[temp_v!(data_arg)]).to_string(); match encoding { - "utf8" => { data.into_bytes() } + "utf8" => data.into_bytes(), "octet" => { let mut buf = vec![]; - for c in data.chars() { + for c in data.chars() { buf.push(c as u8); } buf } - _ => { unreachable!() } + _ => { + unreachable!() + } } } - pub(super) - fn xml_node_to_term( + pub(super) fn xml_node_to_term( &mut self, indices: &mut IndexStore, node: roxmltree::Node, @@ -5816,15 +5556,14 @@ impl MachineState { let mut avec = Vec::new(); for attr in node.attributes() { let chars = clause_name!(String::from(attr.name()), self.atom_tbl); - let name = self.heap.to_unifiable( - HeapCellValue::Atom(chars, None) - ); + let name = self.heap.to_unifiable(HeapCellValue::Atom(chars, None)); let value = self.heap.put_complete_string(&attr.value()); avec.push(HeapCellValue::Addr(Addr::HeapCell(self.heap.h()))); - self.heap.push(HeapCellValue::NamedStr(2, clause_name!("="), None)); + self.heap + .push(HeapCellValue::NamedStr(2, clause_name!("="), None)); self.heap.push(HeapCellValue::Addr(name)); self.heap.push(HeapCellValue::Addr(value)); } @@ -5837,13 +5576,12 @@ impl MachineState { let children = Addr::HeapCell(self.heap.to_list(cvec.into_iter())); let chars = clause_name!(String::from(node.tag_name().name()), self.atom_tbl); - let tag = self.heap.to_unifiable( - HeapCellValue::Atom(chars, None) - ); + let tag = self.heap.to_unifiable(HeapCellValue::Atom(chars, None)); let result = Addr::HeapCell(self.heap.h()); - self.heap.push(HeapCellValue::NamedStr(3, clause_name!("element"), None)); + self.heap + .push(HeapCellValue::NamedStr(3, clause_name!("element"), None)); self.heap.push(HeapCellValue::Addr(tag)); self.heap.push(HeapCellValue::Addr(attrs)); self.heap.push(HeapCellValue::Addr(children)); @@ -5852,29 +5590,28 @@ impl MachineState { } } - pub(super) - fn html_node_to_term( + pub(super) fn html_node_to_term( &mut self, indices: &mut IndexStore, node: select::node::Node, ) -> Addr { match node.name() { - None => { let string = String::from(node.text()); - self.heap.put_complete_string(&string) + None => { + let string = String::from(node.text()); + self.heap.put_complete_string(&string) } Some(name) => { let mut avec = Vec::new(); for attr in node.attrs() { let chars = clause_name!(String::from(attr.0), self.atom_tbl); - let name = self.heap.to_unifiable( - HeapCellValue::Atom(chars, None) - ); + let name = self.heap.to_unifiable(HeapCellValue::Atom(chars, None)); let value = self.heap.put_complete_string(&String::from(attr.1)); avec.push(HeapCellValue::Addr(Addr::HeapCell(self.heap.h()))); - self.heap.push(HeapCellValue::NamedStr(2, clause_name!("="), None)); + self.heap + .push(HeapCellValue::NamedStr(2, clause_name!("="), None)); self.heap.push(HeapCellValue::Addr(name)); self.heap.push(HeapCellValue::Addr(value)); } @@ -5887,13 +5624,12 @@ impl MachineState { let children = Addr::HeapCell(self.heap.to_list(cvec.into_iter())); let chars = clause_name!(String::from(name), self.atom_tbl); - let tag = self.heap.to_unifiable( - HeapCellValue::Atom(chars, None) - ); + let tag = self.heap.to_unifiable(HeapCellValue::Atom(chars, None)); let result = Addr::HeapCell(self.heap.h()); - self.heap.push(HeapCellValue::NamedStr(3, clause_name!("element"), None)); + self.heap + .push(HeapCellValue::NamedStr(3, clause_name!("element"), None)); self.heap.push(HeapCellValue::Addr(tag)); self.heap.push(HeapCellValue::Addr(attrs)); self.heap.push(HeapCellValue::Addr(children)); @@ -5904,7 +5640,6 @@ impl MachineState { } } - fn rng() -> &'static dyn SecureRandom { use std::ops::Deref; diff --git a/src/main.rs b/src/main.rs index 07684b61..82b89c95 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,43 +1,35 @@ -extern crate blake2; -extern crate chrono; -extern crate cpu_time; -extern crate crossterm; -extern crate divrem; -#[macro_use] -extern crate downcast; -extern crate git_version; -extern crate hostname; -extern crate indexmap; -#[macro_use] -extern crate lazy_static; -extern crate libc; -extern crate native_tls; -extern crate nix; -extern crate openssl; -extern crate ordered_float; -#[macro_use] -extern crate prolog_parser_rebis; -#[macro_use] -extern crate ref_thread_local; -extern crate ring; -extern crate ripemd160; -#[cfg(feature = "rug")] -extern crate rug; -#[cfg(feature = "num-rug-adapter")] -extern crate num_rug_adapter as rug; -extern crate rustyline; -extern crate sha3; -extern crate unicode_reader; +use blake2; +use chrono; +use cpu_time; +use crossterm; +use divrem; +use downcast; +use git_version; +use indexmap; +use lazy_static; +use native_tls; +use nix::sys::signal; +use openssl; +use ordered_float; +use prolog_parser_rebis; +use ref_thread_local; +use ring; +use ripemd160; +use rustyline; +use sha3; +use unicode_reader; -use crate::nix::sys::signal; +#[cfg(feature = "num-rug-adapter")] +use num_rug_adapter as rug; +#[cfg(feature = "rug")] +use rug; #[macro_use] mod macros; mod allocator; mod arithmetic; -mod machine; -mod codegen; mod clause_types; +mod codegen; mod debray_allocator; mod fixtures; mod forms; @@ -46,17 +38,18 @@ mod heap_print; mod indexing; mod instructions; mod iterators; +mod machine; mod read; mod targets; mod write; -use machine::*; use machine::streams::*; +use machine::*; use read::*; use std::sync::atomic::Ordering; -extern fn handle_sigint(signal: libc::c_int) { +extern "C" fn handle_sigint(signal: libc::c_int) { let signal = signal::Signal::from_c_int(signal).unwrap(); if signal == signal::Signal::SIGINT { INTERRUPT.store(true, Ordering::Relaxed);