diff --git a/build.rs b/build.rs index c0865b523..0133c93ec 100644 --- a/build.rs +++ b/build.rs @@ -44,7 +44,7 @@ fn main() { libraries .write_all( b"ref_thread_local::ref_thread_local! { - pub static managed LIBRARIES: IndexMap<&'static str, &'static str> = { + pub(crate) static managed LIBRARIES: IndexMap<&'static str, &'static str> = { let mut m = IndexMap::new();\n", ) .unwrap(); diff --git a/src/allocator.rs b/src/allocator.rs index 73d281cde..cc8de305c 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -9,7 +9,7 @@ use crate::targets::*; use std::cell::Cell; use std::rc::Rc; -pub trait Allocator<'a> { +pub(crate) trait Allocator<'a> { fn new() -> Self; fn mark_anon_var(&mut self, _: Level, _: GenContext, _: &mut Vec) diff --git a/src/arithmetic.rs b/src/arithmetic.rs index bcaf239f6..87e72d45f 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -25,11 +25,11 @@ use std::rc::Rc; use std::vec::Vec; #[derive(Debug)] -pub struct ArithInstructionIterator<'a> { +pub(crate) struct ArithInstructionIterator<'a> { state_stack: Vec>, } -pub type ArithCont = (Code, Option); +pub(crate) type ArithCont = (Code, Option); impl<'a> ArithInstructionIterator<'a> { fn push_subterm(&mut self, lvl: Level, term: &'a Term) { @@ -71,7 +71,7 @@ impl<'a> ArithInstructionIterator<'a> { } #[derive(Debug)] -pub enum ArithTermRef<'a> { +pub(crate) enum ArithTermRef<'a> { Constant(&'a Constant), Op(ClauseName, usize), // name, arity. Var(&'a Cell, Rc), @@ -113,13 +113,13 @@ impl<'a> Iterator for ArithInstructionIterator<'a> { } #[derive(Debug)] -pub struct ArithmeticEvaluator<'a> { +pub(crate) struct ArithmeticEvaluator<'a> { bindings: &'a AllocVarDict, interm: Vec, interm_c: usize, } -pub trait ArithmeticTermIter<'a> { +pub(crate) trait ArithmeticTermIter<'a> { type Iter: Iterator, ArithmeticError>>; fn iter(self) -> Result; @@ -134,7 +134,7 @@ impl<'a> ArithmeticTermIter<'a> for &'a Term { } impl<'a> ArithmeticEvaluator<'a> { - pub fn new(bindings: &'a AllocVarDict, target_int: usize) -> Self { + pub(crate) fn new(bindings: &'a AllocVarDict, target_int: usize) -> Self { ArithmeticEvaluator { bindings, interm: Vec::new(), @@ -296,7 +296,7 @@ impl<'a> ArithmeticEvaluator<'a> { Ok(()) } - pub fn eval(&mut self, src: Iter) -> Result + pub(crate) fn eval(&mut self, src: Iter) -> Result where Iter: ArithmeticTermIter<'a>, { @@ -329,7 +329,7 @@ impl<'a> ArithmeticEvaluator<'a> { } // integer division rounding function -- 9.1.3.1. -pub fn rnd_i<'a>(n: &'a Number) -> RefOrOwned<'a, Number> { +pub(crate) 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( @@ -347,7 +347,7 @@ pub fn rnd_i<'a>(n: &'a Number) -> RefOrOwned<'a, Number> { } // floating point rounding function -- 9.1.4.1. -pub fn rnd_f(n: &Number) -> f64 { +pub(crate) fn rnd_f(n: &Number) -> f64 { match n { &Number::Fixnum(n) => n as f64, &Number::Integer(ref n) => n.to_f64(), @@ -357,7 +357,7 @@ pub fn rnd_f(n: &Number) -> f64 { } // floating point result function -- 9.1.4.2. -pub fn result_f(n: &Number, round: Round) -> Result +pub(crate) fn result_f(n: &Number, round: Round) -> Result where Round: Fn(&Number) -> f64, { @@ -752,7 +752,7 @@ impl<'a> From<&'a Integer> for Number { } // Computes n ^ power. Ignores the sign of power. -pub fn binary_pow(mut n: Integer, power: &Integer) -> Integer { +pub(crate) fn binary_pow(mut n: Integer, power: &Integer) -> Integer { let mut power = Integer::from(power.abs_ref()); if power == 0 { diff --git a/src/bin/scryer-prolog.rs b/src/bin/scryer-prolog.rs new file mode 100644 index 000000000..e3330c0ae --- /dev/null +++ b/src/bin/scryer-prolog.rs @@ -0,0 +1,11 @@ +fn main() { + use nix::sys::signal; + use scryer_prolog::read::readline; + use scryer_prolog::*; + + let handler = signal::SigHandler::Handler(handle_sigint); + unsafe { signal::signal(signal::Signal::SIGINT, handler) }.unwrap(); + + let mut wam = machine::Machine::new(readline::input_stream(), machine::Stream::stdout()); + wam.run_top_level(); +} diff --git a/src/clause_types.rs b/src/clause_types.rs index abbacbf5c..67b3b101b 100644 --- a/src/clause_types.rs +++ b/src/clause_types.rs @@ -10,7 +10,7 @@ use ref_thread_local::{ref_thread_local, RefThreadLocal}; use std::collections::BTreeMap; #[derive(Debug, Clone, Copy, Eq, PartialEq)] -pub enum CompareNumberQT { +pub(crate) enum CompareNumberQT { GreaterThan, LessThan, GreaterThanOrEqual, @@ -33,7 +33,7 @@ impl CompareNumberQT { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CompareTermQT { +pub(crate) enum CompareTermQT { LessThan, LessThanOrEqual, GreaterThanOrEqual, @@ -52,14 +52,14 @@ impl CompareTermQT { } #[derive(Debug, Clone, PartialEq, Eq)] -pub enum ArithmeticTerm { +pub(crate) enum ArithmeticTerm { Reg(RegType), Interm(usize), Number(Number), } impl ArithmeticTerm { - pub fn interm_or(&self, interm: usize) -> usize { + pub(crate) fn interm_or(&self, interm: usize) -> usize { if let &ArithmeticTerm::Interm(interm) = self { interm } else { @@ -69,7 +69,7 @@ impl ArithmeticTerm { } #[derive(Debug, Clone, Eq, PartialEq)] -pub enum InlinedClauseType { +pub(crate) enum InlinedClauseType { CompareNumber(CompareNumberQT, ArithmeticTerm, ArithmeticTerm), IsAtom(RegType), IsAtomic(RegType), @@ -83,11 +83,11 @@ pub enum InlinedClauseType { } ref_thread_local! { - pub static managed RANDOM_STATE: RandState<'static> = RandState::new(); + pub(crate)static managed RANDOM_STATE: RandState<'static> = RandState::new(); } ref_thread_local! { - pub static managed CLAUSE_TYPE_FORMS: BTreeMap<(&'static str, usize), ClauseType> = { + pub(crate)static managed CLAUSE_TYPE_FORMS: BTreeMap<(&'static str, usize), ClauseType> = { let mut m = BTreeMap::new(); let r1 = temp_v!(1); @@ -133,7 +133,7 @@ ref_thread_local! { } impl InlinedClauseType { - pub fn name(&self) -> &'static str { + pub(crate) fn name(&self) -> &'static str { match self { &InlinedClauseType::CompareNumber(qt, ..) => qt.name(), &InlinedClauseType::IsAtom(..) => "atom", @@ -150,7 +150,7 @@ impl InlinedClauseType { } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum SystemClauseType { +pub(crate) enum SystemClauseType { AtomChars, AtomCodes, AtomLength, @@ -311,7 +311,7 @@ pub enum SystemClauseType { } impl SystemClauseType { - pub fn name(&self) -> ClauseName { + pub(crate) fn name(&self) -> ClauseName { match self { &SystemClauseType::AtomChars => clause_name!("$atom_chars"), &SystemClauseType::AtomCodes => clause_name!("$atom_codes"), @@ -596,7 +596,7 @@ impl SystemClauseType { } } - pub fn from(name: &str, arity: usize) -> Option { + pub(crate) fn from(name: &str, arity: usize) -> Option { match (name, arity) { ("$abolish_clause", 3) => Some(SystemClauseType::REPL(REPLCodePtr::AbolishClause)), ("$add_dynamic_predicate", 4) => { @@ -605,9 +605,9 @@ impl SystemClauseType { ("$add_multifile_predicate", 4) => { Some(SystemClauseType::REPL(REPLCodePtr::AddMultifilePredicate)) } - ("$add_discontiguous_predicate", 4) => { - Some(SystemClauseType::REPL(REPLCodePtr::AddDiscontiguousPredicate)) - } + ("$add_discontiguous_predicate", 4) => Some(SystemClauseType::REPL( + REPLCodePtr::AddDiscontiguousPredicate, + )), ("$add_goal_expansion_clause", 3) => { Some(SystemClauseType::REPL(REPLCodePtr::AddGoalExpansionClause)) } @@ -766,18 +766,16 @@ impl SystemClauseType { ("$asserta", 5) => Some(SystemClauseType::REPL(REPLCodePtr::Asserta)), ("$assertz", 5) => Some(SystemClauseType::REPL(REPLCodePtr::Assertz)), ("$retract_clause", 4) => Some(SystemClauseType::REPL(REPLCodePtr::Retract)), - ("$is_consistent_with_term_queue", 4) => { - Some(SystemClauseType::REPL(REPLCodePtr::IsConsistentWithTermQueue)) - } - ("$flush_term_queue", 1) => { - Some(SystemClauseType::REPL(REPLCodePtr::FlushTermQueue)) - } + ("$is_consistent_with_term_queue", 4) => Some(SystemClauseType::REPL( + REPLCodePtr::IsConsistentWithTermQueue, + )), + ("$flush_term_queue", 1) => Some(SystemClauseType::REPL(REPLCodePtr::FlushTermQueue)), ("$remove_module_exports", 2) => { Some(SystemClauseType::REPL(REPLCodePtr::RemoveModuleExports)) } - ("$add_non_counted_backtracking", 3) => { - Some(SystemClauseType::REPL(REPLCodePtr::AddNonCountedBacktracking)) - } + ("$add_non_counted_backtracking", 3) => Some(SystemClauseType::REPL( + REPLCodePtr::AddNonCountedBacktracking, + )), ("$variant", 2) => Some(SystemClauseType::Variant), ("$wam_instructions", 4) => Some(SystemClauseType::WAMInstructions), ("$write_term", 7) => Some(SystemClauseType::WriteTerm), @@ -848,7 +846,7 @@ impl SystemClauseType { } #[derive(Debug, Clone, Eq, PartialEq)] -pub enum BuiltInClauseType { +pub(crate) enum BuiltInClauseType { AcyclicTerm, Arg, Compare, @@ -866,7 +864,7 @@ pub enum BuiltInClauseType { } #[derive(Debug, Clone, PartialEq, Eq)] -pub enum ClauseType { +pub(crate) enum ClauseType { BuiltIn(BuiltInClauseType), CallN, Inlined(InlinedClauseType), @@ -876,7 +874,7 @@ pub enum ClauseType { } impl BuiltInClauseType { - pub fn name(&self) -> ClauseName { + pub(crate) fn name(&self) -> ClauseName { match self { &BuiltInClauseType::AcyclicTerm => clause_name!("acyclic_term"), &BuiltInClauseType::Arg => clause_name!("arg"), @@ -895,7 +893,7 @@ impl BuiltInClauseType { } } - pub fn arity(&self) -> usize { + pub(crate) fn arity(&self) -> usize { match self { &BuiltInClauseType::AcyclicTerm => 1, &BuiltInClauseType::Arg => 3, @@ -916,7 +914,7 @@ impl BuiltInClauseType { } impl ClauseType { - pub fn spec(&self) -> Option { + pub(crate) fn spec(&self) -> Option { match self { &ClauseType::Op(_, ref spec, _) => Some(spec.clone()), &ClauseType::Inlined(InlinedClauseType::CompareNumber(..)) @@ -928,7 +926,7 @@ impl ClauseType { } } - pub fn name(&self) -> ClauseName { + pub(crate) fn name(&self) -> ClauseName { match self { &ClauseType::BuiltIn(ref built_in) => built_in.name(), &ClauseType::CallN => clause_name!("$call"), @@ -939,7 +937,7 @@ impl ClauseType { } } - pub fn from(name: ClauseName, arity: usize, spec: Option) -> Self { + pub(crate) fn from(name: ClauseName, arity: usize, spec: Option) -> Self { CLAUSE_TYPE_FORMS .borrow() .get(&(name.as_str(), arity)) diff --git a/src/codegen.rs b/src/codegen.rs index 7a5d8ba39..a678549b1 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -22,10 +22,10 @@ use std::collections::VecDeque; use std::rc::Rc; #[derive(Debug)] -pub struct ConjunctInfo<'a> { - pub perm_vs: VariableFixtures<'a>, - pub num_of_chunks: usize, - pub has_deep_cut: bool, +pub(crate) struct ConjunctInfo<'a> { + pub(crate) perm_vs: VariableFixtures<'a>, + pub(crate) num_of_chunks: usize, + pub(crate) has_deep_cut: bool, } impl<'a> ConjunctInfo<'a> { @@ -90,7 +90,7 @@ impl<'a> ConjunctInfo<'a> { } #[derive(Clone, Copy, Debug)] -pub struct CodeGenSettings { +pub(crate) struct CodeGenSettings { pub global_clock_tick: Option, pub is_extensible: bool, pub non_counted_bt: bool, @@ -98,12 +98,12 @@ pub struct CodeGenSettings { impl CodeGenSettings { #[inline] - pub fn is_dynamic(&self) -> bool { + pub(crate) fn is_dynamic(&self) -> bool { self.global_clock_tick.is_some() } #[inline] - pub fn internal_try_me_else(&self, offset: usize) -> ChoiceInstruction { + pub(crate) fn internal_try_me_else(&self, offset: usize) -> ChoiceInstruction { if let Some(global_clock_time) = self.global_clock_tick { ChoiceInstruction::DynamicInternalElse( global_clock_time, @@ -115,7 +115,7 @@ impl CodeGenSettings { } } - pub fn try_me_else(&self, offset: usize) -> ChoiceInstruction { + pub(crate) fn try_me_else(&self, offset: usize) -> ChoiceInstruction { if let Some(global_clock_tick) = self.global_clock_tick { ChoiceInstruction::DynamicElse( global_clock_tick, @@ -127,7 +127,7 @@ impl CodeGenSettings { } } - pub fn internal_retry_me_else(&self, offset: usize) -> ChoiceInstruction { + pub(crate) fn internal_retry_me_else(&self, offset: usize) -> ChoiceInstruction { if let Some(global_clock_tick) = self.global_clock_tick { ChoiceInstruction::DynamicInternalElse( global_clock_tick, @@ -139,7 +139,7 @@ impl CodeGenSettings { } } - pub fn retry_me_else(&self, offset: usize) -> ChoiceInstruction { + pub(crate) fn retry_me_else(&self, offset: usize) -> ChoiceInstruction { if let Some(global_clock_tick) = self.global_clock_tick { ChoiceInstruction::DynamicElse( global_clock_tick, @@ -153,7 +153,7 @@ impl CodeGenSettings { } } - pub fn internal_trust_me(&self) -> ChoiceInstruction { + pub(crate) fn internal_trust_me(&self) -> ChoiceInstruction { if let Some(global_clock_tick) = self.global_clock_tick { ChoiceInstruction::DynamicInternalElse( global_clock_tick, @@ -167,7 +167,7 @@ impl CodeGenSettings { } } - pub fn trust_me(&self) -> ChoiceInstruction { + pub(crate) fn trust_me(&self) -> ChoiceInstruction { if let Some(global_clock_tick) = self.global_clock_tick { ChoiceInstruction::DynamicElse( global_clock_tick, @@ -183,18 +183,18 @@ impl CodeGenSettings { } #[derive(Debug)] -pub struct CodeGenerator { +pub(crate) struct CodeGenerator { atom_tbl: TabledData, marker: TermMarker, - pub var_count: IndexMap, usize>, + pub(crate) var_count: IndexMap, usize>, settings: CodeGenSettings, - pub skeleton: PredicateSkeleton, - pub jmp_by_locs: Vec, + pub(crate) skeleton: PredicateSkeleton, + pub(crate) jmp_by_locs: Vec, global_jmp_by_locs_offset: usize, } impl<'a, TermMarker: Allocator<'a>> CodeGenerator { - pub fn new(atom_tbl: TabledData, settings: CodeGenSettings) -> Self { + pub(crate) fn new(atom_tbl: TabledData, settings: CodeGenSettings) -> Self { CodeGenerator { atom_tbl, marker: Allocator::new(), @@ -837,7 +837,10 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { } } - pub fn compile_rule<'b: 'a>(&mut self, rule: &'b Rule) -> Result { + pub(crate) fn compile_rule<'b: 'a>( + &mut self, + rule: &'b Rule, + ) -> Result { let iter = ChunkedIterator::from_rule(rule); let conjunct_info = self.collect_var_data(iter); @@ -894,7 +897,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { UnsafeVarMarker::from_safe_vars(safe_vars) } - pub fn compile_fact<'b: 'a>(&mut self, term: &'b Term) -> Code { + pub(crate) fn compile_fact<'b: 'a>(&mut self, term: &'b Term) -> Code { self.update_var_count(post_order_iter(term)); let mut vs = VariableFixtures::new(); @@ -1119,7 +1122,7 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator { Ok(Vec::from(code)) } - pub fn compile_predicate<'b: 'a>( + pub(crate) fn compile_predicate<'b: 'a>( &mut self, clauses: &'b Vec, ) -> Result { diff --git a/src/debray_allocator.rs b/src/debray_allocator.rs index 4d69a344b..7525a79ad 100644 --- a/src/debray_allocator.rs +++ b/src/debray_allocator.rs @@ -14,7 +14,7 @@ use std::collections::BTreeSet; use std::rc::Rc; #[derive(Debug)] -pub struct DebrayAllocator { +pub(crate) struct DebrayAllocator { bindings: IndexMap, VarData>, arg_c: usize, temp_lb: usize, diff --git a/src/fixtures.rs b/src/fixtures.rs index 94d10c259..0ecdd9e86 100644 --- a/src/fixtures.rs +++ b/src/fixtures.rs @@ -14,23 +14,23 @@ use std::vec::Vec; // labeled with chunk numbers. #[derive(Debug)] -pub enum VarStatus { +pub(crate) enum VarStatus { Perm(usize), Temp(usize, TempVarData), // Perm(chunk_num) | Temp(chunk_num, _) } -pub type OccurrenceSet = BTreeSet<(GenContext, usize)>; +pub(crate) type OccurrenceSet = BTreeSet<(GenContext, usize)>; // Perm: 0 initially, a stack register once processed. // Temp: labeled with chunk_num and temp offset (unassigned if 0). #[derive(Debug)] -pub enum VarData { +pub(crate) enum VarData { Perm(usize), Temp(usize, usize, TempVarData), } impl VarData { - pub fn as_reg_type(&self) -> RegType { + pub(crate) fn as_reg_type(&self) -> RegType { match self { &VarData::Temp(_, r, _) => RegType::Temp(r), &VarData::Perm(r) => RegType::Perm(r), @@ -39,15 +39,15 @@ impl VarData { } #[derive(Debug)] -pub struct TempVarData { - pub last_term_arity: usize, - pub use_set: OccurrenceSet, - pub no_use_set: BTreeSet, - pub conflict_set: BTreeSet, +pub(crate) struct TempVarData { + pub(crate) last_term_arity: usize, + pub(crate) use_set: OccurrenceSet, + pub(crate) no_use_set: BTreeSet, + pub(crate) conflict_set: BTreeSet, } impl TempVarData { - pub fn new(last_term_arity: usize) -> Self { + pub(crate) fn new(last_term_arity: usize) -> Self { TempVarData { last_term_arity: last_term_arity, use_set: BTreeSet::new(), @@ -56,7 +56,7 @@ impl TempVarData { } } - pub fn uses_reg(&self, reg: usize) -> bool { + pub(crate) fn uses_reg(&self, reg: usize) -> bool { for &(_, nreg) in self.use_set.iter() { if reg == nreg { return true; @@ -66,7 +66,7 @@ impl TempVarData { return false; } - pub fn populate_conflict_set(&mut self) { + pub(crate) fn populate_conflict_set(&mut self) { if self.last_term_arity > 0 { let arity = self.last_term_arity; let mut conflict_set: BTreeSet = (1..arity).collect(); @@ -83,29 +83,29 @@ impl TempVarData { type VariableFixture<'a> = (VarStatus, Vec<&'a Cell>); #[derive(Debug)] -pub struct VariableFixtures<'a> { +pub(crate) struct VariableFixtures<'a> { perm_vars: IndexMap, VariableFixture<'a>>, last_chunk_temp_vars: IndexSet>, } impl<'a> VariableFixtures<'a> { - pub fn new() -> Self { + pub(crate) fn new() -> Self { VariableFixtures { perm_vars: IndexMap::new(), last_chunk_temp_vars: IndexSet::new(), } } - pub fn insert(&mut self, var: Rc, vs: VariableFixture<'a>) { + pub(crate) fn insert(&mut self, var: Rc, vs: VariableFixture<'a>) { self.perm_vars.insert(var, vs); } - pub fn insert_last_chunk_temp_var(&mut self, var: Rc) { + pub(crate) fn insert_last_chunk_temp_var(&mut self, var: Rc) { self.last_chunk_temp_vars.insert(var); } // computes no_use and conflict sets for all temp vars. - pub fn populate_restricting_sets(&mut self) { + pub(crate) fn populate_restricting_sets(&mut self) { // three stages: // 1. move the use sets of each variable to a local IndexMap, use_set // (iterate mutably, swap mutable refs). @@ -170,7 +170,7 @@ impl<'a> VariableFixtures<'a> { }; } - pub fn vars_above_threshold(&self, index: usize) -> usize { + pub(crate) fn vars_above_threshold(&self, index: usize) -> usize { let mut var_count = 0; for &(ref var_status, _) in self.values() { @@ -184,7 +184,7 @@ impl<'a> VariableFixtures<'a> { var_count } - pub fn mark_vars_in_chunk(&mut self, iter: I, lt_arity: usize, term_loc: GenContext) + pub(crate) fn mark_vars_in_chunk(&mut self, iter: I, lt_arity: usize, term_loc: GenContext) where I: Iterator>, { @@ -218,7 +218,7 @@ impl<'a> VariableFixtures<'a> { } } - pub fn into_iter(self) -> indexmap::map::IntoIter, VariableFixture<'a>> { + pub(crate) fn into_iter(self) -> indexmap::map::IntoIter, VariableFixture<'a>> { self.perm_vars.into_iter() } @@ -226,11 +226,11 @@ impl<'a> VariableFixtures<'a> { self.perm_vars.values() } - pub fn size(&self) -> usize { + pub(crate) fn size(&self) -> usize { self.perm_vars.len() } - pub fn set_perm_vals(&self, has_deep_cuts: bool) { + pub(crate) fn set_perm_vals(&self, has_deep_cuts: bool) { let mut values_vec: Vec<_> = self .values() .filter_map(|ref v| match &v.0 { @@ -252,27 +252,27 @@ impl<'a> VariableFixtures<'a> { } #[derive(Debug)] -pub struct UnsafeVarMarker { - pub unsafe_vars: IndexMap, - pub safe_vars: IndexSet, +pub(crate) struct UnsafeVarMarker { + pub(crate) unsafe_vars: IndexMap, + pub(crate) safe_vars: IndexSet, } impl UnsafeVarMarker { - pub fn new() -> Self { + pub(crate) fn new() -> Self { UnsafeVarMarker { unsafe_vars: IndexMap::new(), safe_vars: IndexSet::new(), } } - pub fn from_safe_vars(safe_vars: IndexSet) -> Self { + pub(crate) fn from_safe_vars(safe_vars: IndexSet) -> Self { UnsafeVarMarker { unsafe_vars: IndexMap::new(), safe_vars, } } - pub fn mark_safe_vars(&mut self, query_instr: &QueryInstruction) -> bool { + pub(crate) fn mark_safe_vars(&mut self, query_instr: &QueryInstruction) -> bool { match query_instr { &QueryInstruction::PutVariable(r @ RegType::Temp(_), _) | &QueryInstruction::SetVariable(r) => { @@ -283,7 +283,7 @@ impl UnsafeVarMarker { } } - pub fn mark_phase(&mut self, query_instr: &QueryInstruction, phase: usize) { + pub(crate) fn mark_phase(&mut self, query_instr: &QueryInstruction, phase: usize) { match query_instr { &QueryInstruction::PutValue(r @ RegType::Perm(_), _) | &QueryInstruction::SetValue(r) => { @@ -294,7 +294,7 @@ impl UnsafeVarMarker { } } - pub fn mark_unsafe_vars(&mut self, query_instr: &mut QueryInstruction, phase: usize) { + pub(crate) fn mark_unsafe_vars(&mut self, query_instr: &mut QueryInstruction, phase: usize) { match query_instr { &mut QueryInstruction::PutValue(RegType::Perm(i), arg) => { if let Some(p) = self.unsafe_vars.swap_remove(&RegType::Perm(i)) { diff --git a/src/forms.rs b/src/forms.rs index 3f0bd2887..3d07ec8af 100644 --- a/src/forms.rs +++ b/src/forms.rs @@ -18,16 +18,16 @@ use std::ops::AddAssign; use std::path::PathBuf; use std::rc::Rc; -pub type PredicateKey = (ClauseName, usize); // name, arity. +pub(crate) type PredicateKey = (ClauseName, usize); // name, arity. -pub type Predicate = Vec; +pub(crate) type Predicate = Vec; // vars of predicate, toplevel offset. Vec is always a vector // of vars (we get their adjoining cells this way). -pub type JumpStub = Vec; +pub(crate) type JumpStub = Vec; #[derive(Debug, Clone)] -pub enum TopLevel { +pub(crate) enum TopLevel { Fact(Term), // Term, line_num, col_num Predicate(Predicate), Query(Vec), @@ -35,14 +35,14 @@ pub enum TopLevel { } #[derive(Debug, Clone, Copy)] -pub enum AppendOrPrepend { +pub(crate) enum AppendOrPrepend { Append, Prepend, } impl AppendOrPrepend { #[inline] - pub fn is_append(self) -> bool { + pub(crate) fn is_append(self) -> bool { match self { AppendOrPrepend::Append => true, AppendOrPrepend::Prepend => false, @@ -51,14 +51,14 @@ impl AppendOrPrepend { } #[derive(Debug, Clone, Copy)] -pub enum Level { +pub(crate) enum Level { Deep, Root, Shallow, } impl Level { - pub fn child_level(self) -> Level { + pub(crate) fn child_level(self) -> Level { match self { Level::Root => Level::Shallow, _ => Level::Deep, @@ -67,7 +67,7 @@ impl Level { } #[derive(Debug, Clone)] -pub enum QueryTerm { +pub(crate) enum QueryTerm { // register, clause type, subterms, use default call policy. Clause(Cell, ClauseType, Vec>, bool), BlockedCut, // a cut which is 'blocked by letters', like the P term in P -> Q. @@ -77,14 +77,14 @@ pub enum QueryTerm { } impl QueryTerm { - pub fn set_default_caller(&mut self) { + pub(crate) fn set_default_caller(&mut self) { match self { &mut QueryTerm::Clause(_, _, _, ref mut use_default_cp) => *use_default_cp = true, _ => {} } } - pub fn arity(&self) -> usize { + pub(crate) fn arity(&self) -> usize { match self { &QueryTerm::Clause(_, _, ref subterms, ..) => subterms.len(), &QueryTerm::BlockedCut | &QueryTerm::UnblockedCut(..) => 0, @@ -95,28 +95,30 @@ impl QueryTerm { } #[derive(Debug, Clone)] -pub struct Rule { - pub head: (ClauseName, Vec>, QueryTerm), - pub clauses: Vec, +pub(crate) struct Rule { + pub(crate) head: (ClauseName, Vec>, QueryTerm), + pub(crate) clauses: Vec, } #[derive(Clone, Debug, Hash)] -pub enum ListingSource { +pub(crate) enum ListingSource { DynamicallyGenerated, File(ClauseName, PathBuf), // filename, path User, } impl ListingSource { - pub fn from_file_and_path(filename: ClauseName, path_buf: PathBuf) -> Self { + pub(crate) fn from_file_and_path(filename: ClauseName, path_buf: PathBuf) -> Self { ListingSource::File(filename, path_buf) } } -pub trait ClauseInfo { +pub(crate) trait ClauseInfo { fn is_consistent(&self, clauses: &PredicateQueue) -> bool { match clauses.first() { - Some(cl) => self.name() == ClauseInfo::name(cl) && self.arity() == ClauseInfo::arity(cl), + Some(cl) => { + self.name() == ClauseInfo::name(cl) && self.arity() == ClauseInfo::arity(cl) + } None => true, } } @@ -198,17 +200,17 @@ impl ClauseInfo for PredicateClause { } } -// pub type CompiledResult = (Predicate, VecDeque); +// pub(crate) type CompiledResult = (Predicate, VecDeque); #[derive(Debug, Clone)] -pub enum PredicateClause { +pub(crate) enum PredicateClause { Fact(Term), Rule(Rule), } impl PredicateClause { // TODO: add this to `Term` in `prolog_parser` like `first_arg`. - pub fn args(&self) -> Option<&[Box]> { + pub(crate) fn args(&self) -> Option<&[Box]> { match *self { PredicateClause::Fact(ref term, ..) => match term { Term::Clause(_, _, args, _) => Some(&args), @@ -226,13 +228,13 @@ impl PredicateClause { } #[derive(Debug, Clone)] -pub enum ModuleSource { +pub(crate) enum ModuleSource { Library(ClauseName), File(ClauseName), } impl ModuleSource { - pub fn as_functor_stub(&self) -> MachineStub { + pub(crate) fn as_functor_stub(&self) -> MachineStub { match self { ModuleSource::Library(ref name) => { functor!("library", [clause_name(name.clone())]) @@ -244,18 +246,18 @@ impl ModuleSource { } } -// pub type ScopedPredicateKey = (ClauseName, PredicateKey); // module name, predicate indicator. +// pub(crate) type ScopedPredicateKey = (ClauseName, PredicateKey); // module name, predicate indicator. /* #[derive(Debug, Clone)] -pub enum MultiFileIndicator { +pub(crate) enum MultiFileIndicator { LocalScoped(ClauseName, usize), // name, arity ModuleScoped(ScopedPredicateKey), } */ #[derive(Clone, Copy, Hash, Debug)] -pub enum MetaSpec { +pub(crate) enum MetaSpec { Minus, Plus, Either, @@ -263,7 +265,7 @@ pub enum MetaSpec { } #[derive(Debug, Clone)] -pub enum Declaration { +pub(crate) enum Declaration { Dynamic(ClauseName, usize), MetaPredicate(ClauseName, ClauseName, Vec), // module name, name, meta-specs Module(ModuleDecl), @@ -274,20 +276,20 @@ pub enum Declaration { } #[derive(Debug, Clone, Eq, Hash, PartialEq, Ord, PartialOrd)] -pub struct OpDecl { - pub prec: usize, - pub spec: Specifier, - pub name: ClauseName, +pub(crate) struct OpDecl { + pub(crate) prec: usize, + pub(crate) spec: Specifier, + pub(crate) name: ClauseName, } impl OpDecl { #[inline] - pub fn new(prec: usize, spec: Specifier, name: ClauseName) -> Self { + pub(crate) fn new(prec: usize, spec: Specifier, name: ClauseName) -> Self { Self { prec, spec, name } } #[inline] - pub fn remove(&mut self, op_dir: &mut OpDir) { + pub(crate) fn remove(&mut self, op_dir: &mut OpDir) { let prec = self.prec; self.prec = 0; @@ -296,7 +298,7 @@ impl OpDecl { } #[inline] - pub fn fixity(&self) -> Fixity { + pub(crate) fn fixity(&self) -> Fixity { match self.spec { XFY | XFX | YFX => Fixity::In, XF | YF => Fixity::Post, @@ -305,7 +307,7 @@ impl OpDecl { } } - pub fn insert_into_op_dir(&self, op_dir: &mut OpDir) -> Option<(usize, Specifier)> { + pub(crate) fn insert_into_op_dir(&self, op_dir: &mut OpDir) -> Option<(usize, Specifier)> { let key = (self.name.clone(), self.fixity()); match op_dir.get(&key) { @@ -320,7 +322,7 @@ impl OpDecl { .map(|op_dir_value| op_dir_value.shared_op_desc().get()) } - pub fn submit( + pub(crate) fn submit( &self, existing_desc: Option, op_dir: &mut OpDir, @@ -348,7 +350,7 @@ impl OpDecl { } } -pub fn fetch_atom_op_spec( +pub(crate) fn fetch_atom_op_spec( name: ClauseName, spec: Option, op_dir: &OpDir, @@ -357,7 +359,7 @@ pub fn fetch_atom_op_spec( .or_else(|| fetch_op_spec_from_existing(name, 2, spec, op_dir)) } -pub fn fetch_op_spec_from_existing( +pub(crate) fn fetch_op_spec_from_existing( name: ClauseName, arity: usize, spec: Option, @@ -375,7 +377,11 @@ 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(crate) fn fetch_op_spec( + name: ClauseName, + arity: usize, + op_dir: &OpDir, +) -> Option { match arity { 2 => op_dir .get(&(name, Fixity::In)) @@ -407,35 +413,35 @@ pub fn fetch_op_spec(name: ClauseName, arity: usize, op_dir: &OpDir) -> Option; +pub(crate) type ModuleDir = IndexMap; #[derive(Debug, Clone, Eq, Hash, PartialEq)] -pub enum ModuleExport { +pub(crate) enum ModuleExport { OpDecl(OpDecl), PredicateKey(PredicateKey), } #[derive(Debug, Clone)] -pub struct ModuleDecl { - pub name: ClauseName, - pub exports: Vec, +pub(crate) struct ModuleDecl { + pub(crate) name: ClauseName, + pub(crate) exports: Vec, } #[derive(Debug)] -pub struct Module { - pub module_decl: ModuleDecl, - pub code_dir: CodeDir, - pub op_dir: OpDir, - pub meta_predicates: MetaPredicateDir, - pub extensible_predicates: ExtensiblePredicates, - pub local_extensible_predicates: LocalExtensiblePredicates, - pub is_impromptu_module: bool, - pub listing_src: ListingSource, +pub(crate) struct Module { + pub(crate) module_decl: ModuleDecl, + pub(crate) code_dir: CodeDir, + pub(crate) op_dir: OpDir, + pub(crate) meta_predicates: MetaPredicateDir, + pub(crate) extensible_predicates: ExtensiblePredicates, + pub(crate) local_extensible_predicates: LocalExtensiblePredicates, + pub(crate) is_impromptu_module: bool, + pub(crate) listing_src: ListingSource, } // Module's and related types are defined in forms. impl Module { - pub fn new(module_decl: ModuleDecl, listing_src: ListingSource) -> Self { + pub(crate) fn new(module_decl: ModuleDecl, listing_src: ListingSource) -> Self { Module { module_decl, code_dir: CodeDir::new(), @@ -450,7 +456,7 @@ impl Module { } #[derive(Debug, Clone)] -pub enum Number { +pub(crate) enum Number { Float(OrderedFloat), Integer(Rc), Rational(Rc), @@ -510,7 +516,7 @@ impl Into for Number { impl Number { #[inline] - pub fn is_positive(&self) -> bool { + pub(crate) fn is_positive(&self) -> bool { match self { &Number::Fixnum(n) => n > 0, &Number::Integer(ref n) => &**n > &0, @@ -520,7 +526,7 @@ impl Number { } #[inline] - pub fn is_negative(&self) -> bool { + pub(crate) fn is_negative(&self) -> bool { match self { &Number::Fixnum(n) => n < 0, &Number::Integer(ref n) => &**n < &0, @@ -530,7 +536,7 @@ impl Number { } #[inline] - pub fn is_zero(&self) -> bool { + pub(crate) fn is_zero(&self) -> bool { match self { &Number::Fixnum(n) => n == 0, &Number::Integer(ref n) => &**n == &0, @@ -540,7 +546,7 @@ impl Number { } #[inline] - pub fn abs(self) -> Self { + pub(crate) fn abs(self) -> Self { match self { Number::Fixnum(n) => { if let Some(n) = n.checked_abs() { @@ -557,7 +563,7 @@ impl Number { } #[derive(Debug, Clone)] -pub enum OptArgIndexKey { +pub(crate) enum OptArgIndexKey { Constant(usize, usize, Constant, Vec), // index, IndexingCode location, opt arg, alternatives List(usize, usize), // index, IndexingCode location None, @@ -566,12 +572,12 @@ pub enum OptArgIndexKey { impl OptArgIndexKey { #[inline] - pub fn take(&mut self) -> OptArgIndexKey { + pub(crate) fn take(&mut self) -> OptArgIndexKey { std::mem::replace(self, OptArgIndexKey::None) } #[inline] - pub fn arg_num(&self) -> usize { + pub(crate) fn arg_num(&self) -> usize { match &self { OptArgIndexKey::Constant(arg_num, ..) | OptArgIndexKey::Structure(arg_num, ..) @@ -584,12 +590,12 @@ impl OptArgIndexKey { } #[inline] - pub fn is_some(&self) -> bool { + pub(crate) fn is_some(&self) -> bool { self.switch_on_term_loc().is_some() } #[inline] - pub fn switch_on_term_loc(&self) -> Option { + pub(crate) fn switch_on_term_loc(&self) -> Option { match &self { OptArgIndexKey::Constant(_, loc, ..) | OptArgIndexKey::Structure(_, loc, ..) @@ -599,7 +605,7 @@ impl OptArgIndexKey { } #[inline] - pub fn set_switch_on_term_loc(&mut self, value: usize) { + pub(crate) fn set_switch_on_term_loc(&mut self, value: usize) { match self { OptArgIndexKey::Constant(_, ref mut loc, ..) | OptArgIndexKey::Structure(_, ref mut loc, ..) @@ -626,14 +632,14 @@ impl AddAssign for OptArgIndexKey { } #[derive(Clone, Debug)] -pub struct ClauseIndexInfo { - pub clause_start: usize, - pub opt_arg_index_key: OptArgIndexKey, +pub(crate) struct ClauseIndexInfo { + pub(crate) clause_start: usize, + pub(crate) opt_arg_index_key: OptArgIndexKey, } impl ClauseIndexInfo { #[inline] - pub fn new(clause_start: usize) -> Self { + pub(crate) fn new(clause_start: usize) -> Self { Self { clause_start, opt_arg_index_key: OptArgIndexKey::None, @@ -643,12 +649,12 @@ impl ClauseIndexInfo { } #[derive(Clone, Copy, Debug)] -pub struct PredicateInfo { - pub is_extensible: bool, - pub is_discontiguous: bool, - pub is_dynamic: bool, - pub is_multifile: bool, - pub has_clauses: bool, +pub(crate) struct PredicateInfo { + pub(crate) is_extensible: bool, + pub(crate) is_discontiguous: bool, + pub(crate) is_dynamic: bool, + pub(crate) is_multifile: bool, + pub(crate) has_clauses: bool, } impl Default for PredicateInfo { @@ -666,30 +672,30 @@ impl Default for PredicateInfo { impl PredicateInfo { #[inline] - pub fn compile_incrementally(&self) -> bool { + pub(crate) fn compile_incrementally(&self) -> bool { let base = self.is_extensible && self.has_clauses; base && (self.is_discontiguous || self.is_multifile) } #[inline] - pub fn must_retract_local_clauses(&self) -> bool { + pub(crate) fn must_retract_local_clauses(&self) -> bool { self.is_extensible && self.has_clauses && !self.is_discontiguous } } #[derive(Debug)] -pub struct PredicateSkeleton { - pub is_discontiguous: bool, - pub is_dynamic: bool, - pub is_multifile: bool, - pub clauses: SliceDeque, - pub clause_clause_locs: SliceDeque, - pub clause_assert_margin: usize, +pub(crate) struct PredicateSkeleton { + pub(crate) is_discontiguous: bool, + pub(crate) is_dynamic: bool, + pub(crate) is_multifile: bool, + pub(crate) clauses: SliceDeque, + pub(crate) clause_clause_locs: SliceDeque, + pub(crate) clause_assert_margin: usize, } impl PredicateSkeleton { #[inline] - pub fn new() -> Self { + pub(crate) fn new() -> Self { PredicateSkeleton { is_discontiguous: false, is_dynamic: false, @@ -701,7 +707,7 @@ impl PredicateSkeleton { } #[inline] - pub fn predicate_info(&self) -> PredicateInfo { + pub(crate) fn predicate_info(&self) -> PredicateInfo { PredicateInfo { is_extensible: true, is_discontiguous: self.is_discontiguous, @@ -712,13 +718,13 @@ impl PredicateSkeleton { } #[inline] - pub fn reset(&mut self) { + pub(crate) fn reset(&mut self) { self.clauses.clear(); self.clause_clause_locs.clear(); self.clause_assert_margin = 0; } - pub fn target_pos_of_clause_clause_loc( + pub(crate) fn target_pos_of_clause_clause_loc( &self, clause_clause_loc: usize, ) -> Option { @@ -727,10 +733,10 @@ impl PredicateSkeleton { match search_result { Ok(loc) => Some(loc), - Err(_) => self.clause_clause_locs[self.clause_assert_margin..] + Err(_) => self.clause_clause_locs[self.clause_assert_margin..] .binary_search_by(|loc| loc.cmp(&clause_clause_loc)) .map(|loc| loc + self.clause_assert_margin) - .ok() + .ok(), } } } diff --git a/src/heap_iter.rs b/src/heap_iter.rs index a6d2e5fa1..fd057ac3c 100644 --- a/src/heap_iter.rs +++ b/src/heap_iter.rs @@ -8,13 +8,13 @@ use std::ops::Deref; use std::vec::Vec; #[derive(Debug)] -pub struct HCPreOrderIterator<'a> { - pub machine_st: &'a MachineState, - pub state_stack: Vec, +pub(crate) struct HCPreOrderIterator<'a> { + pub(crate) machine_st: &'a MachineState, + pub(crate) state_stack: Vec, } impl<'a> HCPreOrderIterator<'a> { - pub fn new(machine_st: &'a MachineState, a: Addr) -> Self { + pub(crate) fn new(machine_st: &'a MachineState, a: Addr) -> Self { HCPreOrderIterator { machine_st, state_stack: vec![a], @@ -22,7 +22,7 @@ impl<'a> HCPreOrderIterator<'a> { } #[inline] - pub fn machine_st(&self) -> &MachineState { + pub(crate) fn machine_st(&self) -> &MachineState { &self.machine_st } @@ -116,7 +116,7 @@ impl<'a> Iterator for HCPreOrderIterator<'a> { } } -pub trait MutStackHCIterator<'b> +pub(crate) trait MutStackHCIterator<'b> where Self: Iterator, { @@ -126,7 +126,7 @@ where } #[derive(Debug)] -pub struct HCPostOrderIterator<'a> { +pub(crate) struct HCPostOrderIterator<'a> { base_iter: HCPreOrderIterator<'a>, parent_stack: Vec<(usize, Addr)>, // number of children, parent node. } @@ -140,7 +140,7 @@ impl<'a> Deref for HCPostOrderIterator<'a> { } impl<'a> HCPostOrderIterator<'a> { - pub fn new(base_iter: HCPreOrderIterator<'a>) -> Self { + pub(crate) fn new(base_iter: HCPreOrderIterator<'a>) -> Self { HCPostOrderIterator { base_iter, parent_stack: vec![], @@ -201,19 +201,19 @@ impl<'a> Iterator for HCPostOrderIterator<'a> { } impl MachineState { - pub fn pre_order_iter<'a>(&'a self, a: Addr) -> HCPreOrderIterator<'a> { + pub(crate) fn pre_order_iter<'a>(&'a self, a: Addr) -> HCPreOrderIterator<'a> { HCPreOrderIterator::new(self, a) } - pub fn post_order_iter<'a>(&'a self, a: Addr) -> HCPostOrderIterator<'a> { + pub(crate) fn post_order_iter<'a>(&'a self, a: Addr) -> HCPostOrderIterator<'a> { HCPostOrderIterator::new(HCPreOrderIterator::new(self, a)) } - pub fn acyclic_pre_order_iter<'a>(&'a self, a: Addr) -> HCAcyclicIterator<'a> { + pub(crate) fn acyclic_pre_order_iter<'a>(&'a self, a: Addr) -> HCAcyclicIterator<'a> { HCAcyclicIterator::new(HCPreOrderIterator::new(self, a)) } - pub fn zipped_acyclic_pre_order_iter<'a>( + pub(crate) fn zipped_acyclic_pre_order_iter<'a>( &'a self, a1: Addr, a2: Addr, @@ -234,13 +234,13 @@ impl<'b, 'a: 'b> MutStackHCIterator<'b> for HCPreOrderIterator<'a> { } #[derive(Debug)] -pub struct HCAcyclicIterator<'a> { +pub(crate) struct HCAcyclicIterator<'a> { iter: HCPreOrderIterator<'a>, seen: IndexSet, } impl<'a> HCAcyclicIterator<'a> { - pub fn new(iter: HCPreOrderIterator<'a>) -> Self { + pub(crate) fn new(iter: HCPreOrderIterator<'a>) -> Self { HCAcyclicIterator { iter, seen: IndexSet::new(), @@ -282,11 +282,11 @@ impl<'a> Iterator for HCAcyclicIterator<'a> { } #[derive(Debug)] -pub struct HCZippedAcyclicIterator<'a> { +pub(crate) struct HCZippedAcyclicIterator<'a> { i1: HCPreOrderIterator<'a>, i2: HCPreOrderIterator<'a>, seen: IndexSet<(Addr, Addr)>, - pub first_to_expire: Ordering, + pub(crate) first_to_expire: Ordering, } impl<'b, 'a: 'b> MutStackHCIterator<'b> for HCZippedAcyclicIterator<'a> { @@ -298,7 +298,7 @@ impl<'b, 'a: 'b> MutStackHCIterator<'b> for HCZippedAcyclicIterator<'a> { } impl<'a> HCZippedAcyclicIterator<'a> { - pub fn new(i1: HCPreOrderIterator<'a>, i2: HCPreOrderIterator<'a>) -> Self { + pub(crate) fn new(i1: HCPreOrderIterator<'a>, i2: HCPreOrderIterator<'a>) -> Self { HCZippedAcyclicIterator { i1, i2, diff --git a/src/heap_print.rs b/src/heap_print.rs index a7250c2f2..5e05d5b5f 100644 --- a/src/heap_print.rs +++ b/src/heap_print.rs @@ -27,7 +27,7 @@ use std::rc::Rc; /* contains the location, name, precision and Specifier of the parent op. */ #[derive(Debug, Clone)] -pub enum DirectedOp { +pub(crate) enum DirectedOp { Left(ClauseName, SharedOpDesc), Right(ClauseName, SharedOpDesc), } @@ -190,7 +190,7 @@ enum TokenOrRedirect { HeadTailSeparator, } -pub trait HCValueOutputter { +pub(crate) trait HCValueOutputter { type Output; fn new() -> Self; @@ -207,7 +207,7 @@ pub trait HCValueOutputter { } #[derive(Debug)] -pub struct PrinterOutputter { +pub(crate) struct PrinterOutputter { contents: String, } @@ -306,7 +306,7 @@ fn numbervar(n: Integer) -> Var { } impl MachineState { - pub fn numbervar(&self, offset: &Integer, addr: Addr) -> Option { + pub(crate) fn numbervar(&self, offset: &Integer, addr: Addr) -> Option { let addr = self.store(self.deref(addr)); match Number::try_from((addr, &self.heap)) { @@ -332,7 +332,7 @@ impl MachineState { type ReverseHeapVarDict = IndexMap>; #[derive(Debug)] -pub struct HCPrinter<'a, Outputter> { +pub(crate) struct HCPrinter<'a, Outputter> { outputter: Outputter, machine_st: &'a MachineState, op_dir: &'a OpDir, @@ -363,7 +363,7 @@ macro_rules! push_space_if_amb { }; } -pub fn requires_space(atom: &str, op: &str) -> bool { +pub(crate) fn requires_space(atom: &str, op: &str) -> bool { match atom.chars().last() { Some(ac) => op .chars() @@ -473,7 +473,7 @@ fn functor_location(addr: &Addr) -> Option { } impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { - pub fn new(machine_st: &'a MachineState, op_dir: &'a OpDir, output: Outputter) -> Self { + pub(crate) fn new(machine_st: &'a MachineState, op_dir: &'a OpDir, output: Outputter) -> Self { HCPrinter { outputter: output, machine_st, @@ -495,7 +495,7 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } } /* - pub fn from_heap_locs( + pub(crate) fn from_heap_locs( machine_st: &'a MachineState, op_dir: &'a OpDir, output: Outputter, @@ -513,13 +513,13 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } */ /* - pub fn drop_toplevel_spec(&mut self) { + pub(crate) fn drop_toplevel_spec(&mut self) { self.toplevel_spec = None; } */ /* #[inline] - pub fn see_all_locs(&mut self) { + pub(crate) fn see_all_locs(&mut self) { for key in self.heap_locs.keys().cloned() { self.printed_vars.insert(key); } @@ -1517,7 +1517,7 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { } } - pub fn print(mut self, addr: Addr) -> Outputter { + pub(crate) fn print(mut self, addr: Addr) -> Outputter { let mut iter = self.machine_st.pre_order_iter(addr); loop { diff --git a/src/indexing.rs b/src/indexing.rs index 754cc57d8..be6d72604 100644 --- a/src/indexing.rs +++ b/src/indexing.rs @@ -17,7 +17,7 @@ use std::mem; use std::rc::Rc; #[derive(Debug, Clone, Copy)] -pub enum IndexingCodePtr { +pub(crate) enum IndexingCodePtr { External(usize), // the index points past the indexing instruction prelude. DynamicExternal(usize), // an External index of a dynamic predicate, potentially invalidated by retraction. Fail, @@ -585,7 +585,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { } } -pub fn merge_clause_index( +pub(crate) 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. @@ -638,7 +638,7 @@ pub fn merge_clause_index( } } -pub fn remove_constant_indices( +pub(crate) fn remove_constant_indices( constant: &Constant, overlapping_constants: &[Constant], indexing_code: &mut Vec, @@ -778,7 +778,7 @@ pub fn remove_constant_indices( } } -pub fn remove_structure_index( +pub(crate) fn remove_structure_index( name: &ClauseName, arity: usize, indexing_code: &mut Vec, @@ -917,7 +917,7 @@ pub fn remove_structure_index( } } -pub fn remove_list_index(indexing_code: &mut Vec, offset: usize) { +pub(crate) fn remove_list_index(indexing_code: &mut Vec, offset: usize) { let mut index = 0; match &mut indexing_code[index] { @@ -995,7 +995,7 @@ pub fn remove_list_index(indexing_code: &mut Vec, offset: usize) { } } -pub fn remove_index( +pub(crate) fn remove_index( opt_arg_index_key: &OptArgIndexKey, indexing_code: &mut Vec, clause_loc: usize, @@ -1065,7 +1065,7 @@ fn uncap_choice_seq_with_try(prelude: &mut [IndexedChoiceInstruction]) { }); } -pub fn constant_key_alternatives(constant: &Constant, atom_tbl: TabledData) -> Vec { +pub(crate) fn constant_key_alternatives(constant: &Constant, atom_tbl: TabledData) -> Vec { let mut constants = vec![]; match constant { @@ -1128,7 +1128,7 @@ pub(crate) struct DynamicCodeIndices { structures: IndexMap<(ClauseName, usize), SliceDeque>, } -pub trait Indexer { +pub(crate) trait Indexer { type ThirdLevelIndex; fn new() -> Self; @@ -1383,14 +1383,14 @@ impl Indexer for DynamicCodeIndices { } #[derive(Debug)] -pub struct CodeOffsets { +pub(crate) struct CodeOffsets { atom_tbl: TabledData, indices: I, optimal_index: usize, } impl CodeOffsets { - pub fn new( + pub(crate) fn new( atom_tbl: TabledData, indices: I, optimal_index: usize, @@ -1440,7 +1440,7 @@ impl CodeOffsets { code_len } - pub fn index_term( + pub(crate) fn index_term( &mut self, optimal_arg: &Term, index: usize, @@ -1472,7 +1472,7 @@ impl CodeOffsets { } } - pub fn no_indices(&mut self) -> bool { + pub(crate) fn no_indices(&mut self) -> bool { let no_constants = self.indices.constants().is_empty(); let no_structures = self.indices.structures().is_empty(); let no_lists = self.indices.lists().is_empty(); @@ -1480,7 +1480,7 @@ impl CodeOffsets { no_constants && no_structures && no_lists } - pub fn compute_indices(mut self, skip_stub_try_me_else: bool) -> Vec { + pub(crate) fn compute_indices(mut self, skip_stub_try_me_else: bool) -> Vec { if self.no_indices() { return vec![]; } @@ -1488,7 +1488,7 @@ impl CodeOffsets { let mut prelude = sdeq![]; let mut emitted_switch_on_structure = false; - let mut emitted_switch_on_constant = false; + let mut emitted_switch_on_constant = false; let mut lst_loc = I::switch_on_list(self.indices.lists(), &mut prelude); diff --git a/src/instructions.rs b/src/instructions.rs index e552c8e34..90cbeeab0 100644 --- a/src/instructions.rs +++ b/src/instructions.rs @@ -47,7 +47,7 @@ impl ArithmeticTerm { } #[derive(Debug, Clone, Copy)] -pub enum NextOrFail { +pub(crate) enum NextOrFail { Next(usize), Fail(usize), } @@ -64,13 +64,13 @@ impl NextOrFail { } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub enum Death { +pub(crate) enum Death { Finite(usize), Infinity, } #[derive(Debug)] -pub enum ChoiceInstruction { +pub(crate) enum ChoiceInstruction { DynamicElse(usize, Death, NextOrFail), DynamicInternalElse(usize, Death, NextOrFail), DefaultRetryMeElse(usize), @@ -81,7 +81,7 @@ pub enum ChoiceInstruction { } impl ChoiceInstruction { - pub fn to_functor(&self, h: usize) -> MachineStub { + pub(crate) fn to_functor(&self, h: usize) -> MachineStub { match self { &ChoiceInstruction::DynamicElse(birth, death, next_or_fail) => { match (death, next_or_fail) { @@ -171,7 +171,7 @@ impl ChoiceInstruction { } #[derive(Debug)] -pub enum CutInstruction { +pub(crate) enum CutInstruction { Cut(RegType), GetLevel(RegType), GetLevelAndUnify(RegType), @@ -179,7 +179,7 @@ pub enum CutInstruction { } impl CutInstruction { - pub fn to_functor(&self, h: usize) -> MachineStub { + pub(crate) fn to_functor(&self, h: usize) -> MachineStub { match self { &CutInstruction::Cut(r) => { let rt_stub = reg_type_into_functor(r); @@ -201,14 +201,14 @@ impl CutInstruction { } #[derive(Clone, Copy, Debug)] -pub enum IndexedChoiceInstruction { +pub(crate) enum IndexedChoiceInstruction { Retry(usize), Trust(usize), Try(usize), } impl IndexedChoiceInstruction { - pub fn offset(&self) -> usize { + pub(crate) fn offset(&self) -> usize { match self { &IndexedChoiceInstruction::Retry(offset) => offset, &IndexedChoiceInstruction::Trust(offset) => offset, @@ -216,7 +216,7 @@ impl IndexedChoiceInstruction { } } - pub fn to_functor(&self) -> MachineStub { + pub(crate) fn to_functor(&self) -> MachineStub { match self { &IndexedChoiceInstruction::Try(offset) => { functor!("try", [integer(offset)]) @@ -233,7 +233,7 @@ impl IndexedChoiceInstruction { /// A `Line` is an instruction (cf. page 98 of wambook). #[derive(Debug)] -pub enum IndexingLine { +pub(crate) enum IndexingLine { Indexing(IndexingInstruction), IndexedChoice(SliceDeque), DynamicIndexedChoice(SliceDeque), @@ -254,7 +254,7 @@ impl From> for IndexingLine { } #[derive(Debug)] -pub enum Line { +pub(crate) enum Line { Arithmetic(ArithmeticInstruction), Choice(ChoiceInstruction), Control(ControlInstruction), @@ -268,7 +268,7 @@ pub enum Line { impl Line { #[inline] - pub fn is_head_instr(&self) -> bool { + pub(crate) fn is_head_instr(&self) -> bool { match self { &Line::Fact(_) => true, &Line::Query(_) => true, @@ -276,7 +276,7 @@ impl Line { } } - pub fn enqueue_functors(&self, mut h: usize, functors: &mut Vec) { + pub(crate) 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(h)), @@ -320,7 +320,7 @@ impl Line { } #[inline] -pub fn to_indexing_line_mut(line: &mut Line) -> Option<&mut Vec> { +pub(crate) fn to_indexing_line_mut(line: &mut Line) -> Option<&mut Vec> { match line { Line::IndexingCode(ref mut indexing_code) => Some(indexing_code), _ => None, @@ -328,7 +328,7 @@ pub fn to_indexing_line_mut(line: &mut Line) -> Option<&mut Vec> { } #[inline] -pub fn to_indexing_line(line: &Line) -> Option<&Vec> { +pub(crate) fn to_indexing_line(line: &Line) -> Option<&Vec> { match line { Line::IndexingCode(ref indexing_code) => Some(indexing_code), _ => None, @@ -336,7 +336,7 @@ pub fn to_indexing_line(line: &Line) -> Option<&Vec> { } #[derive(Debug, Clone)] -pub enum ArithmeticInstruction { +pub(crate) enum ArithmeticInstruction { Add(ArithmeticTerm, ArithmeticTerm, usize), Sub(ArithmeticTerm, ArithmeticTerm, usize), Mul(ArithmeticTerm, ArithmeticTerm, usize), @@ -407,7 +407,7 @@ fn arith_instr_bin_functor( } impl ArithmeticInstruction { - pub fn to_functor(&self, h: usize) -> MachineStub { + pub(crate) fn to_functor(&self, h: usize) -> MachineStub { match self { &ArithmeticInstruction::Add(ref at_1, ref at_2, t) => { arith_instr_bin_functor(h, "add", at_1, at_2, t) @@ -505,7 +505,7 @@ impl ArithmeticInstruction { } #[derive(Debug)] -pub enum ControlInstruction { +pub(crate) enum ControlInstruction { Allocate(usize), // num_frames. // name, arity, perm_vars after threshold, last call, use default call policy. CallClause(ClauseType, usize, usize, bool, bool), @@ -518,7 +518,7 @@ pub enum ControlInstruction { } impl ControlInstruction { - pub fn perm_vars(&self) -> Option { + pub(crate) fn perm_vars(&self) -> Option { match self { ControlInstruction::CallClause(_, _, num_cells, ..) => Some(*num_cells), ControlInstruction::JmpBy(_, _, num_cells, ..) => Some(*num_cells), @@ -526,7 +526,7 @@ impl ControlInstruction { } } - pub fn to_functor(&self) -> MachineStub { + pub(crate) fn to_functor(&self) -> MachineStub { match self { &ControlInstruction::Allocate(num_frames) => { functor!("allocate", [integer(num_frames)]) @@ -555,7 +555,7 @@ impl ControlInstruction { /// `IndexingInstruction` cf. page 110 of wambook. #[derive(Debug)] -pub enum IndexingInstruction { +pub(crate) enum IndexingInstruction { // The first index is the optimal argument being indexed. SwitchOnTerm( usize, @@ -569,7 +569,7 @@ pub enum IndexingInstruction { } impl IndexingInstruction { - pub fn to_functor(&self, mut h: usize) -> MachineStub { + pub(crate) fn to_functor(&self, mut h: usize) -> MachineStub { match self { &IndexingInstruction::SwitchOnTerm(arg, vars, constants, lists, structures) => { functor!( @@ -657,7 +657,7 @@ impl IndexingInstruction { } #[derive(Debug, Clone)] -pub enum FactInstruction { +pub(crate) enum FactInstruction { GetConstant(Level, Constant, RegType), GetList(Level, RegType), GetPartialString(Level, String, RegType, bool), @@ -672,7 +672,7 @@ pub enum FactInstruction { } impl FactInstruction { - pub fn to_functor(&self, h: usize) -> MachineStub { + pub(crate) fn to_functor(&self, h: usize) -> MachineStub { match self { &FactInstruction::GetConstant(lvl, ref c, r) => { let lvl_stub = lvl.into_functor(); @@ -745,7 +745,7 @@ impl FactInstruction { } #[derive(Debug, Clone)] -pub enum QueryInstruction { +pub(crate) enum QueryInstruction { GetVariable(RegType, usize), PutConstant(Level, Constant, RegType), PutList(Level, RegType), @@ -762,7 +762,7 @@ pub enum QueryInstruction { } impl QueryInstruction { - pub fn to_functor(&self, h: usize) -> MachineStub { + pub(crate) fn to_functor(&self, h: usize) -> MachineStub { match self { &QueryInstruction::PutUnsafeValue(norm, arg) => { functor!("put_unsafe_value", [integer(norm), integer(arg)]) @@ -842,6 +842,6 @@ impl QueryInstruction { } } -pub type CompiledFact = Vec; +pub(crate) type CompiledFact = Vec; -pub type Code = Vec; +pub(crate) type Code = Vec; diff --git a/src/iterators.rs b/src/iterators.rs index fc4fbdc3d..a83c57962 100644 --- a/src/iterators.rs +++ b/src/iterators.rs @@ -13,7 +13,7 @@ use std::rc::Rc; use std::vec::Vec; #[derive(Debug, Clone)] -pub enum TermRef<'a> { +pub(crate) enum TermRef<'a> { AnonVar(Level), Cons(Level, &'a Cell, &'a Term, &'a Term), Constant(Level, &'a Cell, &'a Constant), @@ -23,7 +23,7 @@ pub enum TermRef<'a> { } impl<'a> TermRef<'a> { - pub fn level(self) -> Level { + pub(crate) fn level(self) -> Level { match self { TermRef::AnonVar(lvl) | TermRef::Cons(lvl, ..) @@ -36,7 +36,7 @@ impl<'a> TermRef<'a> { } #[derive(Debug)] -pub enum TermIterState<'a> { +pub(crate) enum TermIterState<'a> { AnonVar(Level), Constant(Level, &'a Cell, &'a Constant), Clause( @@ -97,7 +97,7 @@ fn is_partial_string<'a>(head: &'a Term, mut tail: &'a Term) -> Option<(String, } impl<'a> TermIterState<'a> { - pub fn subterm_to_state(lvl: Level, term: &'a Term) -> TermIterState<'a> { + pub(crate) fn subterm_to_state(lvl: Level, term: &'a Term) -> TermIterState<'a> { match term { &Term::AnonVar => TermIterState::AnonVar(lvl), &Term::Clause(ref cell, ref name, ref subterms, ref spec) => { @@ -119,7 +119,7 @@ impl<'a> TermIterState<'a> { } #[derive(Debug)] -pub struct QueryIterator<'a> { +pub(crate) struct QueryIterator<'a> { state_stack: Vec>, } @@ -286,7 +286,7 @@ impl<'a> Iterator for QueryIterator<'a> { } #[derive(Debug)] -pub struct FactIterator<'a> { +pub(crate) struct FactIterator<'a> { state_queue: VecDeque>, iterable_root: bool, } @@ -297,7 +297,7 @@ impl<'a> FactIterator<'a> { .push_back(TermIterState::subterm_to_state(lvl, term)); } - pub fn from_rule_head_clause(terms: &'a Vec>) -> Self { + pub(crate) fn from_rule_head_clause(terms: &'a Vec>) -> Self { let state_queue = terms .iter() .map(|bt| TermIterState::subterm_to_state(Level::Shallow, bt.as_ref())) @@ -386,26 +386,26 @@ impl<'a> Iterator for FactIterator<'a> { } } -pub fn post_order_iter(term: &Term) -> QueryIterator { +pub(crate) fn post_order_iter(term: &Term) -> QueryIterator { QueryIterator::from_term(term) } -pub fn breadth_first_iter(term: &Term, iterable_root: bool) -> FactIterator { +pub(crate) fn breadth_first_iter(term: &Term, iterable_root: bool) -> FactIterator { FactIterator::new(term, iterable_root) } #[derive(Debug)] -pub enum ChunkedTerm<'a> { +pub(crate) enum ChunkedTerm<'a> { HeadClause(ClauseName, &'a Vec>), BodyTerm(&'a QueryTerm), } -pub fn query_term_post_order_iter<'a>(query_term: &'a QueryTerm) -> QueryIterator<'a> { +pub(crate) fn query_term_post_order_iter<'a>(query_term: &'a QueryTerm) -> QueryIterator<'a> { QueryIterator::new(query_term) } impl<'a> ChunkedTerm<'a> { - pub fn post_order_iter(&self) -> QueryIterator<'a> { + pub(crate) fn post_order_iter(&self) -> QueryIterator<'a> { match self { &ChunkedTerm::BodyTerm(ref qt) => QueryIterator::new(qt), &ChunkedTerm::HeadClause(_, terms) => QueryIterator::from_rule_head_clause(terms), @@ -425,8 +425,8 @@ fn contains_cut_var<'a, Iter: Iterator>(terms: Iter) -> bool { false } -pub struct ChunkedIterator<'a> { - pub chunk_num: usize, +pub(crate) struct ChunkedIterator<'a> { + pub(crate) chunk_num: usize, iter: Box> + 'a>, deep_cut_encountered: bool, cut_var_in_head: bool, @@ -448,7 +448,7 @@ type ChunkedIteratorItem<'a> = (usize, usize, Vec>); type RuleBodyIteratorItem<'a> = (usize, usize, Vec<&'a QueryTerm>); impl<'a> ChunkedIterator<'a> { - pub fn rule_body_iter(self) -> Box> + 'a> { + pub(crate) fn rule_body_iter(self) -> Box> + 'a> { Box::new(self.filter_map(|(cn, lt_arity, terms)| { let filtered_terms: Vec<_> = terms .into_iter() @@ -466,7 +466,7 @@ impl<'a> ChunkedIterator<'a> { })) } /* - pub fn from_term_sequence(terms: &'a [QueryTerm]) -> Self { + pub(crate) fn from_term_sequence(terms: &'a [QueryTerm]) -> Self { ChunkedIterator { chunk_num: 0, iter: Box::new(terms.iter().map(|t| ChunkedTerm::BodyTerm(t))), @@ -475,7 +475,7 @@ impl<'a> ChunkedIterator<'a> { } } */ - pub fn from_rule_body(p1: &'a QueryTerm, clauses: &'a Vec) -> Self { + pub(crate) 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))); @@ -487,7 +487,7 @@ impl<'a> ChunkedIterator<'a> { } } - pub fn from_rule(rule: &'a Rule) -> Self { + pub(crate) fn from_rule(rule: &'a Rule) -> Self { let &Rule { head: (ref name, ref args, ref p1), ref clauses, @@ -505,7 +505,7 @@ impl<'a> ChunkedIterator<'a> { } } - pub fn encountered_deep_cut(&self) -> bool { + pub(crate) fn encountered_deep_cut(&self) -> bool { self.deep_cut_encountered } diff --git a/src/main.rs b/src/lib.rs similarity index 61% rename from src/main.rs rename to src/lib.rs index a79563b6a..06fead04f 100644 --- a/src/main.rs +++ b/src/lib.rs @@ -17,29 +17,19 @@ mod heap_print; mod indexing; mod instructions; mod iterators; -mod machine; -mod read; +pub mod machine; +pub mod read; mod targets; mod write; -use machine::streams::*; use machine::*; -use read::*; use nix::sys::signal; use std::sync::atomic::Ordering; -extern "C" fn handle_sigint(signal: libc::c_int) { +pub 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); } } - -fn main() { - let handler = signal::SigHandler::Handler(handle_sigint); - unsafe { signal::signal(signal::Signal::SIGINT, handler) }.unwrap(); - - let mut wam = Machine::new(readline::input_stream(), Stream::stdout()); - wam.run_top_level(); -} diff --git a/src/machine/code_repo.rs b/src/machine/code_repo.rs index 1a812b58d..bb21462e2 100644 --- a/src/machine/code_repo.rs +++ b/src/machine/code_repo.rs @@ -3,58 +3,44 @@ use crate::instructions::*; use crate::machine::machine_indices::*; #[derive(Debug)] -pub struct CodeRepo { +pub(crate) struct CodeRepo { pub(super) code: Code, } impl CodeRepo { #[inline] - pub(super) - fn new() -> Self { - CodeRepo { - code: Code::new(), - } + pub(super) fn new() -> Self { + CodeRepo { code: Code::new() } } #[inline] - pub(super) - fn lookup_local_instr<'a>( - &'a self, - p: LocalCodePtr, - ) -> RefOrOwned<'a, Line> { + pub(super) fn lookup_local_instr<'a>(&'a self, p: LocalCodePtr) -> RefOrOwned<'a, Line> { match p { LocalCodePtr::Halt => { // exit with the interrupt exit code. std::process::exit(1); } - LocalCodePtr::DirEntry(p) => { - RefOrOwned::Borrowed(&self.code[p as usize]) - } - LocalCodePtr::IndexingBuf(p, o, i) => { - match &self.code[p] { - &Line::IndexingCode(ref indexing_lines) => { - match &indexing_lines[o] { - &IndexingLine::IndexedChoice(ref indexed_choice_instrs) => { - RefOrOwned::Owned(Line::IndexedChoice(indexed_choice_instrs[i])) - } - &IndexingLine::DynamicIndexedChoice(ref indexed_choice_instrs) => { - RefOrOwned::Owned(Line::DynamicIndexedChoice(indexed_choice_instrs[i])) - } - _ => { - unreachable!() - } - } + LocalCodePtr::DirEntry(p) => RefOrOwned::Borrowed(&self.code[p as usize]), + LocalCodePtr::IndexingBuf(p, o, i) => match &self.code[p] { + &Line::IndexingCode(ref indexing_lines) => match &indexing_lines[o] { + &IndexingLine::IndexedChoice(ref indexed_choice_instrs) => { + RefOrOwned::Owned(Line::IndexedChoice(indexed_choice_instrs[i])) + } + &IndexingLine::DynamicIndexedChoice(ref indexed_choice_instrs) => { + RefOrOwned::Owned(Line::DynamicIndexedChoice(indexed_choice_instrs[i])) } _ => { unreachable!() } + }, + _ => { + unreachable!() } - } + }, } } - pub(super) - fn lookup_instr<'a>( + pub(super) fn lookup_instr<'a>( &'a self, last_call: bool, p: &CodePtr, @@ -63,9 +49,7 @@ impl CodeRepo { &CodePtr::Local(local) => { return Some(self.lookup_local_instr(local)); } - &CodePtr::REPL(..) => { - None - } + &CodePtr::REPL(..) => None, &CodePtr::BuiltInClause(ref built_in, _) => { let call_clause = call_clause!( ClauseType::BuiltIn(built_in.clone()), @@ -77,26 +61,26 @@ impl CodeRepo { Some(RefOrOwned::Owned(call_clause)) } &CodePtr::CallN(arity, _, last_call) => { - let call_clause = call_clause!( - ClauseType::CallN, - arity, - 0, - last_call - ); + let call_clause = call_clause!(ClauseType::CallN, arity, 0, last_call); Some(RefOrOwned::Owned(call_clause)) } - &CodePtr::VerifyAttrInterrupt(p) => { - Some(RefOrOwned::Borrowed(&self.code[p])) - } + &CodePtr::VerifyAttrInterrupt(p) => Some(RefOrOwned::Borrowed(&self.code[p])), } } - pub(super) - fn find_living_dynamic_else(&self, mut p: usize, cc: usize) -> Option<(usize, usize)> { + pub(super) fn find_living_dynamic_else( + &self, + mut p: usize, + cc: usize, + ) -> Option<(usize, usize)> { loop { match &self.code[p] { - &Line::Choice(ChoiceInstruction::DynamicElse(birth, death, NextOrFail::Next(i))) => { + &Line::Choice(ChoiceInstruction::DynamicElse( + birth, + death, + NextOrFail::Next(i), + )) => { if birth < cc && Death::Finite(cc) <= death { return Some((p, i)); } else if i > 0 { @@ -105,7 +89,11 @@ impl CodeRepo { return None; } } - &Line::Choice(ChoiceInstruction::DynamicElse(birth, death, NextOrFail::Fail(_))) => { + &Line::Choice(ChoiceInstruction::DynamicElse( + birth, + death, + NextOrFail::Fail(_), + )) => { if birth < cc && Death::Finite(cc) <= death { return Some((p, 0)); } else { @@ -128,8 +116,8 @@ impl CodeRepo { &Line::Choice(ChoiceInstruction::DynamicInternalElse( birth, death, - NextOrFail::Fail(_)), - ) => { + NextOrFail::Fail(_), + )) => { if birth < cc && Death::Finite(cc) <= death { return Some((p, 0)); } else { @@ -146,8 +134,11 @@ impl CodeRepo { } } - pub(super) - fn find_living_dynamic(&self, p: LocalCodePtr, cc: usize) -> Option<(usize, usize, usize, bool)> { + pub(super) fn find_living_dynamic( + &self, + p: LocalCodePtr, + cc: usize, + ) -> Option<(usize, usize, usize, bool)> { let (p, oi, mut ii) = match p { LocalCodePtr::IndexingBuf(p, oi, ii) => (p, oi, ii), _ => unreachable!(), @@ -158,27 +149,27 @@ impl CodeRepo { IndexingLine::DynamicIndexedChoice(ref indexed_choice_instrs) => { indexed_choice_instrs } - _ => unreachable!() - } - _ => unreachable!() + _ => unreachable!(), + }, + _ => unreachable!(), }; loop { match &indexed_choice_instrs.get(ii) { - Some(&offset) => { - match &self.code[p + offset - 1] { - &Line::Choice(ChoiceInstruction::DynamicInternalElse( - birth, death, next_or_fail, - )) => { - if birth < cc && Death::Finite(cc) <= death { - return Some((offset, oi, ii, next_or_fail.is_next())); - } else { - ii += 1; - } + Some(&offset) => match &self.code[p + offset - 1] { + &Line::Choice(ChoiceInstruction::DynamicInternalElse( + birth, + death, + next_or_fail, + )) => { + if birth < cc && Death::Finite(cc) <= death { + return Some((offset, oi, ii, next_or_fail.is_next())); + } else { + ii += 1; } - _ => unreachable!(), } - } + _ => unreachable!(), + }, None => return None, } } diff --git a/src/machine/code_walker.rs b/src/machine/code_walker.rs index 2d199fd67..9bde8a360 100644 --- a/src/machine/code_walker.rs +++ b/src/machine/code_walker.rs @@ -7,8 +7,10 @@ fn capture_offset(line: &Line, index: usize, stack: &mut Vec) -> bool { &Line::Choice(ChoiceInstruction::TryMeElse(offset)) if offset > 0 => { stack.push(index + offset); } - &Line::Choice(ChoiceInstruction::DefaultRetryMeElse(offset)) | - &Line::Choice(ChoiceInstruction::RetryMeElse(offset)) if offset > 0 => { + &Line::Choice(ChoiceInstruction::DefaultRetryMeElse(offset)) + | &Line::Choice(ChoiceInstruction::RetryMeElse(offset)) + if offset > 0 => + { stack.push(index + offset); } &Line::Choice(ChoiceInstruction::DynamicElse(_, _, NextOrFail::Next(offset))) @@ -26,8 +28,8 @@ fn capture_offset(line: &Line, index: usize, stack: &mut Vec) -> bool { stack.push(index + offset); return true; } - &Line::Control(ControlInstruction::Proceed) | - &Line::Control(ControlInstruction::CallClause(_, _, _, true, _)) => { + &Line::Control(ControlInstruction::Proceed) + | &Line::Control(ControlInstruction::CallClause(_, _, _, true, _)) => { return true; } &Line::Control(ControlInstruction::RevJmpBy(offset)) => { @@ -37,8 +39,7 @@ fn capture_offset(line: &Line, index: usize, stack: &mut Vec) -> bool { return true; } } - _ => { - } + _ => {} }; false @@ -48,8 +49,7 @@ fn capture_offset(line: &Line, index: usize, stack: &mut Vec) -> bool { * begin in code at the offset p. Each instruction is passed to the * walker function. */ -pub fn walk_code(code: &Code, p: usize, mut walker: impl FnMut(&Line)) -{ +pub(crate) fn walk_code(code: &Code, p: usize, mut walker: impl FnMut(&Line)) { let mut stack = vec![p]; let mut visited_indices = IndexSet::new(); @@ -60,7 +60,7 @@ pub fn walk_code(code: &Code, p: usize, mut walker: impl FnMut(&Line)) visited_indices.insert(first_index); } - for (index, instr) in code[first_index ..].iter().enumerate() { + for (index, instr) in code[first_index..].iter().enumerate() { walker(instr); if capture_offset(instr, first_index + index, &mut stack) { @@ -74,7 +74,7 @@ pub fn walk_code(code: &Code, p: usize, mut walker: impl FnMut(&Line)) * the code. Otherwise identical to walk_code. */ /* -pub fn walk_code_mut(code: &mut Code, p: usize, mut walker: impl FnMut(&mut Line)) +pub(crate) fn walk_code_mut(code: &mut Code, p: usize, mut walker: impl FnMut(&mut Line)) { let mut queue = VecDeque::from(vec![p]); diff --git a/src/machine/copier.rs b/src/machine/copier.rs index ba2eff535..fdd52c96d 100644 --- a/src/machine/copier.rs +++ b/src/machine/copier.rs @@ -7,13 +7,12 @@ use std::ops::IndexMut; type Trail = Vec<(Ref, HeapCellValue)>; #[derive(Debug, Clone, Copy)] -pub enum AttrVarPolicy { +pub(crate) enum AttrVarPolicy { DeepCopy, - StripAttributes + StripAttributes, } -pub(crate) -trait CopierTarget: IndexMut { +pub(crate) trait CopierTarget: IndexMut { fn deref(&self, val: Addr) -> Addr; fn push(&mut self, val: HeapCellValue); fn stack(&mut self) -> &mut Stack; @@ -21,8 +20,7 @@ trait CopierTarget: IndexMut { fn threshold(&self) -> usize; } -pub(crate) -fn copy_term(target: T, addr: Addr, attr_var_policy: AttrVarPolicy) { +pub(crate) fn copy_term(target: T, addr: Addr, attr_var_policy: AttrVarPolicy) { let mut copy_term_state = CopyTermState::new(target, attr_var_policy); copy_term_state.copy_term_impl(addr); } @@ -43,7 +41,7 @@ impl CopyTermState { scan: 0, old_h: target.threshold(), target, - attr_var_policy + attr_var_policy, } } @@ -59,14 +57,11 @@ impl CopyTermState { HeapCellValue::Addr(Addr::Lis(threshold)), ); - self.trail.push(( - Ref::HeapCell(addr), - trail_item, - )); + self.trail.push((Ref::HeapCell(addr), trail_item)); } fn copy_list(&mut self, addr: usize) { - for offset in 0 .. 2 { + for offset in 0..2 { if let Addr::Lis(h) = self.target[addr + offset].as_addr(addr + offset) { if h >= self.old_h { *self.value_at_scan() = HeapCellValue::Addr(Addr::Lis(h)); @@ -81,12 +76,14 @@ impl CopyTermState { *self.value_at_scan() = HeapCellValue::Addr(Addr::Lis(threshold)); - for i in 0 .. 2 { + for i in 0..2 { let hcv = self.target[addr + i].context_free_clone(); self.target.push(hcv); } - let cdr = self.target.store(self.target.deref(Addr::HeapCell(addr + 1))); + let cdr = self + .target + .store(self.target.deref(Addr::HeapCell(addr + 1))); if !cdr.is_ref() { self.trail_list_cell(addr + 1, threshold); @@ -113,34 +110,27 @@ impl CopyTermState { let threshold = self.target.threshold(); - *self.value_at_scan() = - HeapCellValue::Addr(Addr::PStrLocation(threshold, n)); + *self.value_at_scan() = HeapCellValue::Addr(Addr::PStrLocation(threshold, n)); self.scan += 1; - let (pstr, has_tail) = - match &self.target[addr] { - &HeapCellValue::PartialString(ref pstr, has_tail) => { - (pstr.clone_from_offset(0), has_tail) - } - _ => { - unreachable!() - } - }; + let (pstr, has_tail) = match &self.target[addr] { + &HeapCellValue::PartialString(ref pstr, has_tail) => { + (pstr.clone_from_offset(0), has_tail) + } + _ => { + unreachable!() + } + }; - self.target.push(HeapCellValue::PartialString(pstr, has_tail)); + self.target + .push(HeapCellValue::PartialString(pstr, has_tail)); let replacement = HeapCellValue::Addr(Addr::PStrLocation(threshold, n)); - let trail_item = mem::replace( - &mut self.target[addr], - replacement, - ); + let trail_item = mem::replace(&mut self.target[addr], replacement); - self.trail.push(( - Ref::HeapCell(addr), - trail_item, - )); + self.trail.push((Ref::HeapCell(addr), trail_item)); if has_tail { let tail_addr = self.target[addr + 1].as_addr(addr + 1); @@ -154,10 +144,8 @@ impl CopyTermState { self.target[frontier] = HeapCellValue::Addr(Addr::HeapCell(frontier)); self.target[h] = HeapCellValue::Addr(Addr::HeapCell(frontier)); - self.trail.push(( - Ref::HeapCell(h), - HeapCellValue::Addr(Addr::HeapCell(h)), - )); + self.trail + .push((Ref::HeapCell(h), HeapCellValue::Addr(Addr::HeapCell(h)))); } Addr::StackCell(fr, sc) => { self.target[frontier] = HeapCellValue::Addr(Addr::HeapCell(frontier)); @@ -178,13 +166,12 @@ impl CopyTermState { self.target[frontier] = HeapCellValue::Addr(Addr::HeapCell(threshold)); self.target[h] = HeapCellValue::Addr(Addr::HeapCell(threshold)); - self.trail.push(( - Ref::AttrVar(h), - HeapCellValue::Addr(Addr::AttrVar(h)), - )); + self.trail + .push((Ref::AttrVar(h), HeapCellValue::Addr(Addr::AttrVar(h)))); if let AttrVarPolicy::DeepCopy = self.attr_var_policy { - self.target.push(HeapCellValue::Addr(Addr::AttrVar(threshold))); + self.target + .push(HeapCellValue::Addr(Addr::AttrVar(threshold))); let list_val = self.target[h + 1].context_free_clone(); self.target.push(list_val); @@ -226,12 +213,10 @@ impl CopyTermState { HeapCellValue::Addr(Addr::Str(threshold)), ); - self.trail.push(( - Ref::HeapCell(addr), - trail_item, - )); + self.trail.push((Ref::HeapCell(addr), trail_item)); - self.target.push(HeapCellValue::NamedStr(arity, name, fixity)); + self.target + .push(HeapCellValue::NamedStr(arity, name, fixity)); for i in 0..arity { let hcv = self.target[addr + 1 + i].context_free_clone(); @@ -255,43 +240,41 @@ impl CopyTermState { while self.scan < self.target.threshold() { match self.value_at_scan() { - &mut HeapCellValue::Addr(addr) => { - match addr { - Addr::Con(h) => { - let addr = self.target[h].as_addr(h); - - if addr == Addr::Con(h) { - *self.value_at_scan() = self.target[h].context_free_clone(); - } else { - *self.value_at_scan() = HeapCellValue::Addr(addr); - } - } - Addr::Lis(h) => { - if h >= self.old_h { - self.scan += 1; - } else { - self.copy_list(h); - } - } - addr @ Addr::AttrVar(_) | - addr @ Addr::HeapCell(_) | - addr @ Addr::StackCell(..) => { - self.copy_var(addr); - } - Addr::Str(addr) => { - self.copy_structure(addr); - } - Addr::PStrLocation(addr, n) => { - self.copy_partial_string(addr, n); - } - Addr::Stream(h) => { + &mut HeapCellValue::Addr(addr) => match addr { + Addr::Con(h) => { + let addr = self.target[h].as_addr(h); + + if addr == Addr::Con(h) { *self.value_at_scan() = self.target[h].context_free_clone(); + } else { + *self.value_at_scan() = HeapCellValue::Addr(addr); } - _ => { + } + Addr::Lis(h) => { + if h >= self.old_h { self.scan += 1; + } else { + self.copy_list(h); } } - } + addr @ Addr::AttrVar(_) + | addr @ Addr::HeapCell(_) + | addr @ Addr::StackCell(..) => { + self.copy_var(addr); + } + Addr::Str(addr) => { + self.copy_structure(addr); + } + Addr::PStrLocation(addr, n) => { + self.copy_partial_string(addr, n); + } + Addr::Stream(h) => { + *self.value_at_scan() = self.target[h].context_free_clone(); + } + _ => { + self.scan += 1; + } + }, _ => { self.scan += 1; } @@ -304,10 +287,10 @@ impl CopyTermState { fn unwind_trail(&mut self) { for (r, value) in self.trail.drain(0..) { match r { - Ref::AttrVar(h) | Ref::HeapCell(h) => - self.target[h] = value, - Ref::StackCell(fr, sc) => - self.target.stack().index_and_frame_mut(fr)[sc] = value.as_addr(0), + Ref::AttrVar(h) | Ref::HeapCell(h) => self.target[h] = value, + Ref::StackCell(fr, sc) => { + self.target.stack().index_and_frame_mut(fr)[sc] = value.as_addr(0) + } } } } diff --git a/src/machine/heap.rs b/src/machine/heap.rs index 935bad8bf..067bfa939 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -429,7 +429,7 @@ impl HeapTemplate { } #[inline] - pub fn index_addr<'a>(&'a self, addr: &Addr) -> RefOrOwned<'a, HeapCellValue> { + pub(crate) fn index_addr<'a>(&'a self, addr: &Addr) -> RefOrOwned<'a, HeapCellValue> { match addr { &Addr::Con(h) | &Addr::Str(h) | &Addr::Stream(h) | &Addr::TcpListener(h) => { RefOrOwned::Borrowed(&self[h]) diff --git a/src/machine/loader.rs b/src/machine/loader.rs index a98c8fc02..c5c5e2e87 100644 --- a/src/machine/loader.rs +++ b/src/machine/loader.rs @@ -184,18 +184,16 @@ impl<'a> Drop for LoadState<'a> { module_decl, listing_src, local_extensible_predicates, - ) => { - match self.wam.indices.modules.get_mut(&module_decl.name) { - Some(ref mut module) => { - module.module_decl = module_decl; - module.listing_src = listing_src; - module.local_extensible_predicates = local_extensible_predicates; - } - _ => { - unreachable!() - } + ) => match self.wam.indices.modules.get_mut(&module_decl.name) { + Some(ref mut module) => { + module.module_decl = module_decl; + module.listing_src = listing_src; + module.local_extensible_predicates = local_extensible_predicates; } - } + _ => { + unreachable!() + } + }, RetractionRecord::AddedDiscontiguousPredicate(compilation_target, key) => { match compilation_target { CompilationTarget::User => { @@ -487,17 +485,15 @@ impl<'a> Drop for LoadState<'a> { } } RetractionRecord::SkeletonLocalClauseClausePopFront( - src_compilation_target, local_compilation_target, key, + src_compilation_target, + local_compilation_target, + key, ) => { - match self - .wam - .indices - .get_local_predicate_skeleton_mut( - &src_compilation_target, - local_compilation_target, - key, - ) - { + match self.wam.indices.get_local_predicate_skeleton_mut( + &src_compilation_target, + local_compilation_target, + key, + ) { Some(skeleton) => { skeleton.clause_clause_locs.pop_front(); } @@ -505,17 +501,15 @@ impl<'a> Drop for LoadState<'a> { } } RetractionRecord::SkeletonLocalClauseClausePopBack( - src_compilation_target, local_compilation_target, key, + src_compilation_target, + local_compilation_target, + key, ) => { - match self - .wam - .indices - .get_local_predicate_skeleton_mut( - &src_compilation_target, - local_compilation_target, - key, - ) - { + match self.wam.indices.get_local_predicate_skeleton_mut( + &src_compilation_target, + local_compilation_target, + key, + ) { Some(skeleton) => { skeleton.clause_clause_locs.pop_back(); } @@ -528,15 +522,11 @@ impl<'a> Drop for LoadState<'a> { key, len, ) => { - match self - .wam - .indices - .get_local_predicate_skeleton_mut( - &src_compilation_target, - local_compilation_target, - key, - ) - { + match self.wam.indices.get_local_predicate_skeleton_mut( + &src_compilation_target, + local_compilation_target, + key, + ) { Some(skeleton) => { skeleton.clause_clause_locs.truncate_back(len); } @@ -603,15 +593,11 @@ impl<'a> Drop for LoadState<'a> { key, clause_locs, ) => { - match self - .wam - .indices - .get_local_predicate_skeleton_mut( - &compilation_target, - local_compilation_target, - key, - ) - { + match self.wam.indices.get_local_predicate_skeleton_mut( + &compilation_target, + local_compilation_target, + key, + ) { Some(skeleton) => skeleton.clause_clause_locs = clause_locs, None => {} } @@ -663,7 +649,7 @@ impl<'a> Drop for LoadState<'a> { } #[derive(Debug, Clone, Hash, PartialEq, Eq)] -pub enum CompilationTarget { +pub(crate) enum CompilationTarget { Module(ClauseName), User, } @@ -682,7 +668,7 @@ impl CompilationTarget { } #[inline] - pub fn module_name(&self) -> ClauseName { + pub(crate) fn module_name(&self) -> ClauseName { match self { CompilationTarget::User => { clause_name!("user") @@ -692,7 +678,7 @@ impl CompilationTarget { } } -pub struct PredicateQueue { +pub(crate) struct PredicateQueue { pub(super) predicates: Vec, pub(super) compilation_target: CompilationTarget, } @@ -781,10 +767,9 @@ impl<'a, TS: TermStream> Loader<'a, TS> { } let term = match term { - Term::Clause(_, name, terms, _) - if name.as_str() == ":-" && terms.len() == 1 => { - return Ok(Some(setup_declaration(&self.load_state, terms)?)); - }, + Term::Clause(_, name, terms, _) if name.as_str() == ":-" && terms.len() == 1 => { + return Ok(Some(setup_declaration(&self.load_state, terms)?)); + } term => term, }; @@ -808,8 +793,7 @@ impl<'a, TS: TermStream> Loader<'a, TS> { self.load_state.compilation_target = CompilationTarget::Module(module_decl.name.clone()); - self.predicates.compilation_target = - self.load_state.compilation_target.clone(); + self.predicates.compilation_target = self.load_state.compilation_target.clone(); self.load_state .add_module(module_decl, self.term_stream.listing_src().clone()); @@ -975,9 +959,10 @@ impl<'a, TS: TermStream> Loader<'a, TS> { if !*flag_accessor(skeleton) { *flag_accessor(skeleton) = true; - self.load_state.retraction_info.push_record( - retraction_fn(compilation_target.clone(), key.clone()), - ); + self.load_state.retraction_info.push_record(retraction_fn( + compilation_target.clone(), + key.clone(), + )); } } None => { @@ -1003,9 +988,10 @@ impl<'a, TS: TermStream> Loader<'a, TS> { if !*flag_accessor(skeleton) { *flag_accessor(skeleton) = true; - self.load_state.retraction_info.push_record( - retraction_fn(compilation_target.clone(), key.clone()), - ); + self.load_state.retraction_info.push_record(retraction_fn( + compilation_target.clone(), + key.clone(), + )); } } None => { @@ -1024,7 +1010,8 @@ impl<'a, TS: TermStream> Loader<'a, TS> { } }, None => { - self.load_state.add_dynamically_generated_module(module_name); + self.load_state + .add_dynamically_generated_module(module_name); let mut skeleton = PredicateSkeleton::new(); *flag_accessor(&mut skeleton) = true; @@ -1068,28 +1055,29 @@ impl<'a, TS: TermStream> Loader<'a, TS> { } CompilationTarget::Module(ref module_name) => { match self.load_state.wam.indices.modules.get_mut(module_name) { - Some(ref mut module) => - match module.local_extensible_predicates.get_mut( - &(compilation_target.clone(), key.clone()), - ) { - Some(ref mut skeleton) => { - if !*flag_accessor(skeleton) { - *flag_accessor(skeleton) = true; - } + Some(ref mut module) => match module + .local_extensible_predicates + .get_mut(&(compilation_target.clone(), key.clone())) + { + Some(ref mut skeleton) => { + if !*flag_accessor(skeleton) { + *flag_accessor(skeleton) = true; } - None => { - let mut skeleton = PredicateSkeleton::new(); - *flag_accessor(&mut skeleton) = true; - - self.load_state.add_local_extensible_predicate( - compilation_target.clone(), - key.clone(), - skeleton, - ); - } - }, + } + None => { + let mut skeleton = PredicateSkeleton::new(); + *flag_accessor(&mut skeleton) = true; + + self.load_state.add_local_extensible_predicate( + compilation_target.clone(), + key.clone(), + skeleton, + ); + } + }, None => { - self.load_state.add_dynamically_generated_module(module_name); + self.load_state + .add_dynamically_generated_module(module_name); let mut skeleton = PredicateSkeleton::new(); *flag_accessor(&mut skeleton) = true; @@ -1106,7 +1094,10 @@ impl<'a, TS: TermStream> Loader<'a, TS> { Ok(()) } else { - Err(SessionError::PredicateNotMultifileOrDiscontiguous(compilation_target, key)) + Err(SessionError::PredicateNotMultifileOrDiscontiguous( + compilation_target, + key, + )) } } @@ -1139,10 +1130,9 @@ impl<'a, TS: TermStream> Loader<'a, TS> { RetractionRecord::AddedDynamicPredicate, )?; - let code_index = self.load_state.get_or_insert_code_index( - (name.clone(), arity), - compilation_target.clone(), - ); + let code_index = self + .load_state + .get_or_insert_code_index((name.clone(), arity), compilation_target.clone()); if let IndexPtr::Undefined = code_index.get() { set_code_index( @@ -1204,12 +1194,11 @@ impl<'a, TS: TermStream> Loader<'a, TS> { &self.load_state.compilation_target, self.predicates.compilation_target.clone(), key.clone(), - ) - { - Some(skeleton) if !skeleton.clause_clause_locs.is_empty() => - mem::replace(&mut skeleton.clause_clause_locs, sdeq![]), - _ => - return, + ) { + Some(skeleton) if !skeleton.clause_clause_locs.is_empty() => { + mem::replace(&mut skeleton.clause_clause_locs, sdeq![]) + } + _ => return, }; self.load_state.retraction_info.push_record( @@ -1233,10 +1222,8 @@ impl<'a, TS: TermStream> Loader<'a, TS> { module_name => module_name.clone(), }; - self.load_state.retract_local_clause_clauses( - clause_clause_compilation_target, - &clause_locs, - ); + self.load_state + .retract_local_clause_clauses(clause_clause_compilation_target, &clause_locs); } } } @@ -1305,7 +1292,9 @@ impl Machine { if export_list.is_empty() { loader.load_state.import_module(library)?; } else { - loader.load_state.import_qualified_module(library, export_list)?; + loader + .load_state + .import_qualified_module(library, export_list)?; } LiveTermStream::evacuate(loader) @@ -1347,29 +1336,39 @@ impl Machine { #[inline] pub(crate) fn add_discontiguous_predicate(&mut self) { - self.add_extensible_predicate_declaration(|loader, compilation_target, clause_name, arity| { - loader.add_discontiguous_predicate(compilation_target, clause_name, arity) - }); + self.add_extensible_predicate_declaration( + |loader, compilation_target, clause_name, arity| { + loader.add_discontiguous_predicate(compilation_target, clause_name, arity) + }, + ); } #[inline] pub(crate) fn add_dynamic_predicate(&mut self) { - self.add_extensible_predicate_declaration(|loader, compilation_target, clause_name, arity| { - loader.add_dynamic_predicate(compilation_target, clause_name, arity) - }); + self.add_extensible_predicate_declaration( + |loader, compilation_target, clause_name, arity| { + loader.add_dynamic_predicate(compilation_target, clause_name, arity) + }, + ); } #[inline] pub(crate) fn add_multifile_predicate(&mut self) { - self.add_extensible_predicate_declaration(|loader, compilation_target, clause_name, arity| { - loader.add_multifile_predicate(compilation_target, clause_name, arity) - }); + self.add_extensible_predicate_declaration( + |loader, compilation_target, clause_name, arity| { + loader.add_multifile_predicate(compilation_target, clause_name, arity) + }, + ); } fn add_extensible_predicate_declaration( &mut self, - decl_adder: impl Fn(&mut Loader, CompilationTarget, ClauseName, usize) - -> Result<(), SessionError>, + decl_adder: impl Fn( + &mut Loader, + CompilationTarget, + ClauseName, + usize, + ) -> Result<(), SessionError>, ) { let module_name = atom_from!( self.machine_st, @@ -1805,15 +1804,10 @@ impl Machine { let mut loader = Loader::new(LiveTermStream::new(ListingSource::User), self); loader.load_state.compilation_target = compilation_target; - let clause_clause_compilation_target = - match &loader.load_state.compilation_target { - CompilationTarget::User => { - CompilationTarget::Module(clause_name!("builtins")) - } - module => { - module.clone() - } - }; + let clause_clause_compilation_target = match &loader.load_state.compilation_target { + CompilationTarget::User => CompilationTarget::Module(clause_name!("builtins")), + module => module.clone(), + }; let mut clause_clause_target_poses: Vec<_> = loader .load_state @@ -1830,12 +1824,13 @@ impl Machine { &(clause_name!("$clause"), 2), ) .map(|clause_clause_skeleton| { - skeleton.clause_clause_locs + skeleton + .clause_clause_locs .iter() .map(|clause_clause_loc| { - clause_clause_skeleton.target_pos_of_clause_clause_loc( - *clause_clause_loc, - ).unwrap() + clause_clause_skeleton + .target_pos_of_clause_clause_loc(*clause_clause_loc) + .unwrap() }) .collect() }) @@ -1850,17 +1845,18 @@ impl Machine { .get_predicate_skeleton_mut(&loader.load_state.compilation_target, &key) .map(|skeleton| skeleton.reset()); - let code_index = loader.load_state.get_or_insert_code_index( - key, - loader.load_state.compilation_target.clone(), - ); + let code_index = loader + .load_state + .get_or_insert_code_index(key, loader.load_state.compilation_target.clone()); code_index.set(IndexPtr::DynamicUndefined); loader.load_state.compilation_target = clause_clause_compilation_target; while let Some(target_pos) = clause_clause_target_poses.pop() { - 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) @@ -1918,11 +1914,9 @@ impl Machine { &clause_clause_compilation_target, &(clause_name!("$clause"), 2), ) { - Some(skeleton) => { - skeleton.target_pos_of_clause_clause_loc( - clause_clause_loc, - ).unwrap() - } + Some(skeleton) => skeleton + .target_pos_of_clause_clause_loc(clause_clause_loc) + .unwrap(), None => { unreachable!(); } @@ -1962,10 +1956,9 @@ impl Machine { let (loader, evacuable_h) = self.loader_from_heap_evacuable(temp_v!(4)); - loader.load_state.wam.machine_st.fail = - (!loader.predicates.is_empty() && - loader.predicates.compilation_target != compilation_target) || - !key.is_consistent(&loader.predicates); + loader.load_state.wam.machine_st.fail = (!loader.predicates.is_empty() + && loader.predicates.compilation_target != compilation_target) + || !key.is_consistent(&loader.predicates); let result = LiveTermStream::evacuate(loader); self.restore_load_state_payload(result, evacuable_h); @@ -2263,5 +2256,6 @@ pub(super) fn load_module( code_dir, op_dir, meta_predicate_dir, - ).unwrap(); + ) + .unwrap(); } diff --git a/src/machine/machine_errors.rs b/src/machine/machine_errors.rs index c446107f5..8175d2613 100644 --- a/src/machine/machine_errors.rs +++ b/src/machine/machine_errors.rs @@ -2,11 +2,11 @@ use prolog_parser::ast::*; use prolog_parser::{clause_name, temp_v}; use crate::forms::{ModuleSource, Number}; //, PredicateKey}; -use crate::machine::PredicateKey; use crate::machine::heap::*; use crate::machine::loader::CompilationTarget; use crate::machine::machine_indices::*; use crate::machine::machine_state::*; +use crate::machine::PredicateKey; use crate::rug::Integer; use std::rc::Rc; @@ -321,14 +321,12 @@ impl MachineError { // SessionError::InvalidFileName(filename) => { // Self::existence_error(h, ExistenceError::Module(filename)) // } - SessionError::ModuleDoesNotContainExport(..) => { - Self::permission_error( - h, - Permission::Access, - "private_procedure", - functor!("module_does_not_contain_claimed_export"), - ) - } + SessionError::ModuleDoesNotContainExport(..) => Self::permission_error( + h, + Permission::Access, + "private_procedure", + functor!("module_does_not_contain_claimed_export"), + ), SessionError::ModuleCannotImportSelf(module_name) => Self::permission_error( h, Permission::Modify, @@ -417,7 +415,7 @@ impl MachineError { } #[derive(Debug)] -pub enum CompilationError { +pub(crate) enum CompilationError { Arithmetic(ArithmeticError), ParserError(ParserError), // BadPendingByte, @@ -454,14 +452,14 @@ impl From for CompilationError { } impl CompilationError { - pub fn line_and_col_num(&self) -> Option<(usize, usize)> { + pub(crate) fn line_and_col_num(&self) -> Option<(usize, usize)> { match self { &CompilationError::ParserError(ref err) => err.line_and_col_num(), _ => None, } } - pub fn as_functor(&self, _h: usize) -> MachineStub { + pub(crate) fn as_functor(&self, _h: usize) -> MachineStub { match self { &CompilationError::Arithmetic(..) => functor!("arithmetic_error"), // &CompilationError::BadPendingByte => @@ -494,7 +492,7 @@ impl CompilationError { } #[derive(Debug, Clone, Copy)] -pub enum Permission { +pub(crate) enum Permission { Access, Create, InputStream, @@ -506,7 +504,7 @@ pub enum Permission { impl Permission { #[inline] - pub fn as_str(self) -> &'static str { + pub(crate) fn as_str(self) -> &'static str { match self { Permission::Access => "access", Permission::Create => "create", @@ -521,7 +519,7 @@ impl Permission { // from 7.12.2 b) of 13211-1:1995 #[derive(Debug, Clone, Copy)] -pub enum ValidType { +pub(crate) enum ValidType { Atom, Atomic, // Boolean, @@ -543,7 +541,7 @@ pub enum ValidType { } impl ValidType { - pub fn as_str(self) -> &'static str { + pub(crate) fn as_str(self) -> &'static str { match self { ValidType::Atom => "atom", ValidType::Atomic => "atomic", @@ -568,7 +566,7 @@ impl ValidType { } #[derive(Debug, Clone, Copy)] -pub enum DomainErrorType { +pub(crate) enum DomainErrorType { IOMode, NotLessThanZero, Order, @@ -578,7 +576,7 @@ pub enum DomainErrorType { } impl DomainErrorType { - pub fn as_str(self) -> &'static str { + pub(crate) fn as_str(self) -> &'static str { match self { DomainErrorType::IOMode => "io_mode", DomainErrorType::NotLessThanZero => "not_less_than_zero", @@ -592,7 +590,7 @@ impl DomainErrorType { // from 7.12.2 f) of 13211-1:1995 #[derive(Debug, Clone, Copy)] -pub enum RepFlag { +pub(crate) enum RepFlag { Character, CharacterCode, InCharacterCode, @@ -602,7 +600,7 @@ pub enum RepFlag { } impl RepFlag { - pub fn as_str(self) -> &'static str { + pub(crate) fn as_str(self) -> &'static str { match self { RepFlag::Character => "character", RepFlag::CharacterCode => "character_code", @@ -616,7 +614,7 @@ impl RepFlag { // from 7.12.2 g) of 13211-1:1995 #[derive(Debug, Clone, Copy)] -pub enum EvalError { +pub(crate) enum EvalError { FloatOverflow, Undefined, // Underflow, @@ -624,7 +622,7 @@ pub enum EvalError { } impl EvalError { - pub fn as_str(self) -> &'static str { + pub(crate) fn as_str(self) -> &'static str { match self { EvalError::FloatOverflow => "float_overflow", EvalError::Undefined => "undefined", @@ -806,7 +804,7 @@ impl MachineState { } #[derive(Debug)] -pub enum ExistenceError { +pub(crate) enum ExistenceError { Module(ClauseName), ModuleSource(ModuleSource), Procedure(ClauseName, usize), @@ -815,7 +813,7 @@ pub enum ExistenceError { } #[derive(Debug)] -pub enum SessionError { +pub(crate) enum SessionError { CompilationError(CompilationError), // CannotOverwriteBuiltIn(ClauseName), // CannotOverwriteImport(ClauseName), @@ -830,7 +828,7 @@ pub enum SessionError { } #[derive(Debug)] -pub enum EvalSession { +pub(crate) enum EvalSession { // EntrySuccess, Error(SessionError), } diff --git a/src/machine/machine_indices.rs b/src/machine/machine_indices.rs index 17bfa4a69..ab2f332d8 100644 --- a/src/machine/machine_indices.rs +++ b/src/machine/machine_indices.rs @@ -29,12 +29,12 @@ use std::ops::{Add, AddAssign, Deref, Sub, SubAssign}; use std::rc::Rc; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct OrderedOpDirKey(pub ClauseName, pub Fixity); +pub(crate) struct OrderedOpDirKey(pub(crate) ClauseName, pub(crate) Fixity); -pub type OssifiedOpDir = BTreeMap; +pub(crate) type OssifiedOpDir = BTreeMap; #[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub enum DBRef { +pub(crate) enum DBRef { NamedPred(ClauseName, usize, Option), Op( usize, @@ -47,7 +47,7 @@ pub enum DBRef { // 7.2 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub enum TermOrderCategory { +pub(crate) enum TermOrderCategory { Variable, FloatingPoint, Integer, @@ -56,7 +56,7 @@ pub enum TermOrderCategory { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum Addr { +pub(crate) enum Addr { AttrVar(usize), Char(char), Con(usize), @@ -76,14 +76,14 @@ pub enum Addr { } #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, PartialOrd)] -pub enum Ref { +pub(crate) enum Ref { AttrVar(usize), HeapCell(usize), StackCell(usize, usize), } impl Ref { - pub fn as_addr(self) -> Addr { + pub(crate) fn as_addr(self) -> Addr { match self { Ref::AttrVar(h) => Addr::AttrVar(h), Ref::HeapCell(h) => Addr::HeapCell(h), @@ -141,7 +141,7 @@ impl PartialOrd for Addr { impl Addr { #[inline] - pub fn is_heap_bound(&self) -> bool { + pub(crate) fn is_heap_bound(&self) -> bool { match self { Addr::Char(_) | Addr::EmptyList @@ -154,7 +154,7 @@ impl Addr { } #[inline] - pub fn is_ref(&self) -> bool { + pub(crate) fn is_ref(&self) -> bool { match self { Addr::HeapCell(_) | Addr::StackCell(_, _) | Addr::AttrVar(_) => true, _ => false, @@ -162,7 +162,7 @@ impl Addr { } #[inline] - pub fn as_var(&self) -> Option { + pub(crate) fn as_var(&self) -> Option { match self { &Addr::AttrVar(h) => Some(Ref::AttrVar(h)), &Addr::HeapCell(h) => Some(Ref::HeapCell(h)), @@ -202,7 +202,7 @@ impl Addr { } } - pub fn as_constant_index(&self, machine_st: &MachineState) -> Option { + pub(crate) 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] { @@ -222,7 +222,7 @@ impl Addr { } } - pub fn is_protected(&self, e: usize) -> bool { + pub(crate) fn is_protected(&self, e: usize) -> bool { match self { &Addr::StackCell(addr, _) if addr >= e => false, _ => true, @@ -292,7 +292,7 @@ impl SubAssign for Addr { } #[derive(Debug, Clone, Copy)] -pub enum TrailRef { +pub(crate) enum TrailRef { Ref(Ref), AttrVarHeapLink(usize), AttrVarListLink(usize, usize), @@ -307,7 +307,7 @@ impl From for TrailRef { } #[derive(Debug)] -pub enum HeapCellValue { +pub(crate) enum HeapCellValue { Addr(Addr), Atom(ClauseName, Option), DBRef(DBRef), @@ -322,13 +322,13 @@ pub enum HeapCellValue { impl HeapCellValue { #[inline] - pub fn as_addr(&self, focus: usize) -> Addr { + pub(crate) 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::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), @@ -338,7 +338,7 @@ impl HeapCellValue { } #[inline] - pub fn context_free_clone(&self) -> HeapCellValue { + pub(crate) 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()), @@ -370,7 +370,7 @@ impl From for HeapCellValue { } #[derive(Debug, Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum IndexPtr { +pub(crate) enum IndexPtr { DynamicUndefined, // a predicate, declared as dynamic, whose location in code is as yet undefined. DynamicIndex(usize), Index(usize), @@ -378,7 +378,7 @@ pub enum IndexPtr { } #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)] -pub struct CodeIndex(pub Rc>); +pub(crate) struct CodeIndex(pub(crate) Rc>); impl Deref for CodeIndex { type Target = Cell; @@ -396,14 +396,14 @@ impl CodeIndex { } #[inline] - pub fn is_undefined(&self) -> bool { + pub(crate) fn is_undefined(&self) -> bool { match self.0.get() { IndexPtr::Undefined => true, // | &IndexPtr::DynamicUndefined => true, _ => false, } } - pub fn local(&self) -> Option { + pub(crate) fn local(&self) -> Option { match self.0.get() { IndexPtr::Index(i) => Some(i), IndexPtr::DynamicIndex(i) => Some(i), @@ -419,7 +419,7 @@ impl Default for CodeIndex { } #[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] -pub enum REPLCodePtr { +pub(crate) enum REPLCodePtr { AddDiscontiguousPredicate, AddDynamicPredicate, AddMultifilePredicate, @@ -456,7 +456,7 @@ pub enum REPLCodePtr { } #[derive(Debug, Clone, PartialEq)] -pub enum CodePtr { +pub(crate) enum CodePtr { BuiltInClause(BuiltInClauseType, LocalCodePtr), // local is the successor call. CallN(usize, LocalCodePtr, bool), // arity, local, last call. Local(LocalCodePtr), @@ -466,7 +466,7 @@ pub enum CodePtr { } impl CodePtr { - pub fn local(&self) -> LocalCodePtr { + pub(crate) fn local(&self) -> LocalCodePtr { match self { &CodePtr::BuiltInClause(_, ref local) | &CodePtr::CallN(_, ref local, _) @@ -477,7 +477,7 @@ impl CodePtr { } #[inline] - pub fn is_halt(&self) -> bool { + pub(crate) fn is_halt(&self) -> bool { if let CodePtr::Local(LocalCodePtr::Halt) = self { true } else { @@ -487,7 +487,7 @@ impl CodePtr { } #[derive(Copy, Clone, Debug, PartialEq)] -pub enum LocalCodePtr { +pub(crate) enum LocalCodePtr { DirEntry(usize), // offset Halt, IndexingBuf(usize, usize, usize), // DirEntry offset, first internal offset, second internal offset @@ -659,22 +659,23 @@ impl SubAssign for CodePtr { } } -pub type HeapVarDict = IndexMap, Addr>; -pub type AllocVarDict = IndexMap, VarData>; +pub(crate) type HeapVarDict = IndexMap, Addr>; +pub(crate) type AllocVarDict = IndexMap, VarData>; -pub type GlobalVarDir = IndexMap)>; +pub(crate) type GlobalVarDir = IndexMap)>; pub(crate) type StreamAliasDir = IndexMap; pub(crate) type StreamDir = BTreeSet; -pub type MetaPredicateDir = IndexMap>; +pub(crate) type MetaPredicateDir = IndexMap>; -pub type ExtensiblePredicates = IndexMap; +pub(crate) type ExtensiblePredicates = IndexMap; -pub type LocalExtensiblePredicates = IndexMap<(CompilationTarget, PredicateKey), PredicateSkeleton>; +pub(crate) type LocalExtensiblePredicates = + IndexMap<(CompilationTarget, PredicateKey), PredicateSkeleton>; #[derive(Debug)] -pub struct IndexStore { +pub(crate) struct IndexStore { pub(super) code_dir: CodeDir, pub(super) extensible_predicates: ExtensiblePredicates, pub(super) local_extensible_predicates: LocalExtensiblePredicates, @@ -694,7 +695,7 @@ impl Default for IndexStore { } impl IndexStore { - pub fn get_predicate_skeleton_mut( + pub(crate) fn get_predicate_skeleton_mut( &mut self, compilation_target: &CompilationTarget, key: &PredicateKey, @@ -714,29 +715,25 @@ impl IndexStore { } } - pub fn get_local_predicate_skeleton_mut( + pub(crate) fn get_local_predicate_skeleton_mut( &mut self, src_compilation_target: &CompilationTarget, local_compilation_target: CompilationTarget, key: PredicateKey, ) -> Option<&mut PredicateSkeleton> { match (key.0.as_str(), key.1) { - ("term_expansion", 2) => { - self.local_extensible_predicates.get_mut( - &(local_compilation_target, key), - ) - } + ("term_expansion", 2) => self + .local_extensible_predicates + .get_mut(&(local_compilation_target, key)), _ => match src_compilation_target { - CompilationTarget::User => { - self.local_extensible_predicates.get_mut( - &(local_compilation_target, key), - ) - } + CompilationTarget::User => self + .local_extensible_predicates + .get_mut(&(local_compilation_target, key)), CompilationTarget::Module(ref module_name) => { if let Some(module) = self.modules.get_mut(module_name) { - module.local_extensible_predicates.get_mut( - &(local_compilation_target, key), - ) + module + .local_extensible_predicates + .get_mut(&(local_compilation_target, key)) } else { None } @@ -745,29 +742,25 @@ impl IndexStore { } } - pub fn get_local_predicate_skeleton( + pub(crate) fn get_local_predicate_skeleton( &self, src_compilation_target: &CompilationTarget, local_compilation_target: CompilationTarget, key: PredicateKey, ) -> Option<&PredicateSkeleton> { match (key.0.as_str(), key.1) { - ("term_expansion", 2) => { - self.local_extensible_predicates.get( - &(local_compilation_target, key), - ) - } + ("term_expansion", 2) => self + .local_extensible_predicates + .get(&(local_compilation_target, key)), _ => match src_compilation_target { - CompilationTarget::User => { - self.local_extensible_predicates.get( - &(local_compilation_target, key), - ) - } + CompilationTarget::User => self + .local_extensible_predicates + .get(&(local_compilation_target, key)), CompilationTarget::Module(ref module_name) => { if let Some(module) = self.modules.get(module_name) { - module.local_extensible_predicates.get( - &(local_compilation_target, key), - ) + module + .local_extensible_predicates + .get(&(local_compilation_target, key)) } else { None } @@ -776,7 +769,7 @@ impl IndexStore { } } - pub fn get_predicate_skeleton( + pub(crate) fn get_predicate_skeleton( &self, compilation_target: &CompilationTarget, key: &PredicateKey, @@ -796,19 +789,15 @@ impl IndexStore { } } - pub fn remove_predicate_skeleton( + pub(crate) fn remove_predicate_skeleton( &mut self, compilation_target: &CompilationTarget, key: &PredicateKey, ) -> Option { match (key.0.as_str(), key.1) { - ("term_expansion", 2) => { - self.extensible_predicates.remove(key) - } + ("term_expansion", 2) => self.extensible_predicates.remove(key), _ => match compilation_target { - CompilationTarget::User => { - self.extensible_predicates.remove(key) - } + 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) @@ -820,7 +809,7 @@ impl IndexStore { } } - pub fn get_predicate_code_index( + pub(crate) fn get_predicate_code_index( &self, name: ClauseName, arity: usize, @@ -848,7 +837,7 @@ impl IndexStore { } } - pub fn get_meta_predicate_spec( + pub(crate) fn get_meta_predicate_spec( &self, name: ClauseName, arity: usize, @@ -866,7 +855,7 @@ impl IndexStore { } } - pub fn is_dynamic_predicate(&self, module_name: ClauseName, key: PredicateKey) -> bool { + pub(crate) fn is_dynamic_predicate(&self, module_name: ClauseName, key: PredicateKey) -> bool { match module_name.as_str() { "user" => self .extensible_predicates @@ -911,9 +900,9 @@ impl IndexStore { } } -pub type CodeDir = BTreeMap; +pub(crate) type CodeDir = BTreeMap; -pub enum RefOrOwned<'a, T: 'a> { +pub(crate) enum RefOrOwned<'a, T: 'a> { Borrowed(&'a T), Owned(T), } @@ -928,14 +917,14 @@ impl<'a, T: 'a + fmt::Debug> fmt::Debug for RefOrOwned<'a, T> { } impl<'a, T> RefOrOwned<'a, T> { - pub fn as_ref(&'a self) -> &'a T { + pub(crate) fn as_ref(&'a self) -> &'a T { match self { &RefOrOwned::Borrowed(r) => r, &RefOrOwned::Owned(ref r) => r, } } - pub fn to_owned(self) -> T + pub(crate) fn to_owned(self) -> T where T: Clone, { diff --git a/src/machine/machine_state.rs b/src/machine/machine_state.rs index 87af5a419..b94de7362 100644 --- a/src/machine/machine_state.rs +++ b/src/machine/machine_state.rs @@ -30,7 +30,7 @@ use std::ops::{Index, IndexMut}; use std::rc::Rc; #[derive(Debug)] -pub struct Ball { +pub(crate) struct Ball { pub(super) boundary: usize, pub(super) stub: Heap, } @@ -225,7 +225,7 @@ impl IndexMut for MachineState { } } -pub type Registers = Vec; +pub(crate) type Registers = Vec; #[derive(Debug, Clone, Copy)] pub(super) enum MachineMode { @@ -276,7 +276,7 @@ pub enum FirstOrNext { } // #[derive(Debug)] -pub struct MachineState { +pub(crate) struct MachineState { pub(crate) atom_tbl: TabledData, pub(super) s: HeapPtr, pub(super) p: CodePtr, @@ -347,7 +347,7 @@ impl MachineState { pub(crate) fn read_term(&mut self, mut stream: Stream, indices: &mut IndexStore) -> CallResult { fn push_var_eq_functors<'a>( heap: &mut Heap, - iter: impl Iterator, &'a Addr)>, + iter: impl Iterator, &'a Addr)>, op_dir: &OpDir, atom_tbl: TabledData, ) -> Vec { @@ -1303,7 +1303,8 @@ impl CallPolicy for CWILCallPolicy { offset: usize, global_variables: &mut GlobalVarDir, ) -> CallResult { - self.prev_policy.retry_me_else(machine_st, offset, global_variables)?; + self.prev_policy + .retry_me_else(machine_st, offset, global_variables)?; self.increment(machine_st) } @@ -1313,7 +1314,8 @@ impl CallPolicy for CWILCallPolicy { offset: usize, global_variables: &mut GlobalVarDir, ) -> CallResult { - self.prev_policy.retry(machine_st, offset, global_variables)?; + self.prev_policy + .retry(machine_st, offset, global_variables)?; self.increment(machine_st) } @@ -1332,7 +1334,8 @@ impl CallPolicy for CWILCallPolicy { offset: usize, global_variables: &mut GlobalVarDir, ) -> CallResult { - self.prev_policy.trust(machine_st, offset, global_variables)?; + self.prev_policy + .trust(machine_st, offset, global_variables)?; self.increment(machine_st) } diff --git a/src/machine/machine_state_impl.rs b/src/machine/machine_state_impl.rs index 5ae448f9c..efb0e6a92 100644 --- a/src/machine/machine_state_impl.rs +++ b/src/machine/machine_state_impl.rs @@ -61,7 +61,7 @@ impl MachineState { } #[inline] - pub fn machine_flags(&self) -> MachineFlags { + pub(crate) fn machine_flags(&self) -> MachineFlags { self.flags } @@ -590,8 +590,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 { @@ -3460,14 +3459,20 @@ impl MachineState { } &ChoiceInstruction::DefaultRetryMeElse(offset) => { let mut call_policy = DefaultCallPolicy {}; - try_or_fail!(self, call_policy.retry_me_else(self, offset, global_variables)) + try_or_fail!( + self, + call_policy.retry_me_else(self, offset, global_variables) + ) } &ChoiceInstruction::DefaultTrustMe(_) => { let mut call_policy = DefaultCallPolicy {}; try_or_fail!(self, call_policy.trust_me(self, global_variables)) } &ChoiceInstruction::RetryMeElse(offset) => { - try_or_fail!(self, call_policy.retry_me_else(self, offset, global_variables)) + try_or_fail!( + self, + call_policy.retry_me_else(self, offset, global_variables) + ) } &ChoiceInstruction::TrustMe(_) => { try_or_fail!(self, call_policy.trust_me(self, global_variables)) diff --git a/src/machine/mod.rs b/src/machine/mod.rs index 419401548..51a88762a 100644 --- a/src/machine/mod.rs +++ b/src/machine/mod.rs @@ -14,17 +14,17 @@ use crate::read::*; mod attributed_variables; pub(super) mod code_repo; -pub mod code_walker; +pub(crate) mod code_walker; #[macro_use] pub(crate) mod loader; mod compile; mod copier; -pub mod heap; +pub(crate) mod heap; mod load_state; -pub mod machine_errors; -pub mod machine_indices; +pub(crate) mod machine_errors; +pub(crate) mod machine_indices; pub(super) mod machine_state; -pub mod partial_string; +pub(crate) mod partial_string; mod preprocessor; mod raw_block; mod stack; @@ -42,7 +42,7 @@ use crate::machine::compile::*; use crate::machine::machine_errors::*; use crate::machine::machine_indices::*; use crate::machine::machine_state::*; -use crate::machine::streams::*; +pub use crate::machine::streams::Stream; use indexmap::IndexMap; @@ -54,13 +54,13 @@ use std::path::PathBuf; use std::sync::atomic::AtomicBool; #[derive(Debug)] -pub struct MachinePolicies { +pub(crate) struct MachinePolicies { call_policy: Box, cut_policy: Box, } lazy_static! { - pub static ref INTERRUPT: AtomicBool = AtomicBool::new(false); + pub(crate) static ref INTERRUPT: AtomicBool = AtomicBool::new(false); } impl MachinePolicies { @@ -141,7 +141,7 @@ impl Machine { unreachable!(); } - fn load_file(&mut self, path: String, stream: Stream) { + pub 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))); @@ -224,7 +224,7 @@ impl Machine { self.run_module_predicate(clause_name!("$toplevel"), (clause_name!("$repl"), 1)); } - fn configure_modules(&mut self) { + pub(crate) fn configure_modules(&mut self) { fn update_call_n_indices(loader: &Module, target_code_dir: &mut CodeDir) { for arity in 1..66 { let key = (clause_name!("call"), arity); @@ -358,7 +358,7 @@ impl Machine { wam } - pub fn configure_streams(&mut self) { + pub(crate) fn configure_streams(&mut self) { self.user_input.options_mut().alias = Some(clause_name!("user_input")); self.indices @@ -493,7 +493,7 @@ impl Machine { self.machine_st.p = CodePtr::Local(p); } - pub(super) fn run_query(&mut self) { + pub(crate) fn run_query(&mut self) { while !self.machine_st.p.is_halt() { self.machine_st.query_stepper( &mut self.indices, diff --git a/src/machine/partial_string.rs b/src/machine/partial_string.rs index 7d865d497..bdaacc780 100644 --- a/src/machine/partial_string.rs +++ b/src/machine/partial_string.rs @@ -1,20 +1,20 @@ -use crate::machine::*; use crate::machine::machine_indices::*; +use crate::machine::*; use core::marker::PhantomData; use std::alloc; use std::cmp::Ordering; use std::mem; -use std::ptr; use std::ops::RangeFrom; +use std::ptr; use std::slice; use std::str; use indexmap::IndexSet; #[derive(Debug)] -pub struct PartialString { +pub(crate) struct PartialString { buf: *const u8, len: usize, _marker: PhantomData<[u8]>, @@ -54,7 +54,7 @@ fn scan_for_terminator>(iter: Iter) -> usize { } #[derive(Debug)] -pub struct PStrIter { +pub(crate) struct PStrIter { buf: *const u8, len: usize, } @@ -91,17 +91,14 @@ impl Iterator for PStrIter { impl PartialString { #[inline] - pub(super) - fn new(src: &str) -> Option<(Self, &str)> { + pub(super) fn new(src: &str) -> Option<(Self, &str)> { let pstr = PartialString { buf: ptr::null_mut(), len: 0, _marker: PhantomData, }; - unsafe { - pstr.append_chars(src) - } + unsafe { pstr.append_chars(src) } } unsafe fn append_chars(mut self, src: &str) -> Option<(Self, &str)> { @@ -115,29 +112,23 @@ impl PartialString { self.buf = alloc::alloc(layout) as *const _; self.len = terminator_idx + '\u{0}'.len_utf8(); - ptr::copy( - src.as_ptr(), - self.buf as *mut _, - terminator_idx, - ); + ptr::copy(src.as_ptr(), self.buf as *mut _, terminator_idx); self.write_terminator_at(terminator_idx); Some(if terminator_idx != src.as_bytes().len() { - (self, &src[terminator_idx ..]) + (self, &src[terminator_idx..]) } else { (self, "") }) } - pub(super) - fn clone_from_offset(&self, n: usize) -> Self { - let len = - if self.len - '\u{0}'.len_utf8() > n { - self.len - n - '\u{0}'.len_utf8() - } else { - 0 - }; + pub(super) fn clone_from_offset(&self, n: usize) -> Self { + let len = if self.len - '\u{0}'.len_utf8() > n { + self.len - n - '\u{0}'.len_utf8() + } else { + 0 + }; let mut pstr = PartialString { buf: ptr::null_mut(), @@ -168,18 +159,14 @@ impl PartialString { } #[inline] - pub(super) - fn write_terminator_at(&mut self, index: usize) { + pub(super) fn write_terminator_at(&mut self, index: usize) { unsafe { - ptr::write( - (self.buf as usize + index) as *mut u8, - 0u8, - ); + ptr::write((self.buf as usize + index) as *mut u8, 0u8); } } #[inline] - pub fn range_from(&self, index: RangeFrom) -> PStrIter { + pub(crate) fn range_from(&self, index: RangeFrom) -> PStrIter { if self.len >= '\u{0}'.len_utf8() { PStrIter::from(self.buf, self.len - '\u{0}'.len_utf8(), index.start) } else { @@ -188,21 +175,18 @@ impl PartialString { } #[inline] - pub fn at_end(&self, end_n: usize) -> bool { + pub(crate) fn at_end(&self, end_n: usize) -> bool { end_n + 1 == self.len } #[inline] - pub fn as_str_from(&self, n: usize) -> &str { + pub(crate) fn as_str_from(&self, n: usize) -> &str { unsafe { - let slice = slice::from_raw_parts( - self.buf, - self.len - '\u{0}'.len_utf8(), - ); + let slice = slice::from_raw_parts(self.buf, self.len - '\u{0}'.len_utf8()); let s = str::from_utf8(slice).unwrap(); - &s[n ..] + &s[n..] } } } @@ -216,8 +200,7 @@ pub(crate) struct HeapPStrIter<'a> { impl<'a> HeapPStrIter<'a> { #[inline] - pub(super) - fn new(machine_st: &'a MachineState, focus: Addr) -> Self { + pub(super) fn new(machine_st: &'a MachineState, focus: Addr) -> Self { HeapPStrIter { focus, machine_st, @@ -226,14 +209,12 @@ impl<'a> HeapPStrIter<'a> { } #[inline] - pub(crate) - fn focus(&self) -> Addr { + pub(crate) fn focus(&self) -> Addr { self.machine_st.store(self.machine_st.deref(self.focus)) } #[inline] - pub(crate) - fn to_string(&mut self) -> String { + pub(crate) fn to_string(&mut self) -> String { let mut buf = String::new(); while let Some(iteratee) = self.next() { @@ -241,16 +222,14 @@ impl<'a> HeapPStrIter<'a> { PStrIteratee::Char(c) => { buf.push(c); } - PStrIteratee::PStrSegment(h, n) => { - match &self.machine_st.heap[h] { - HeapCellValue::PartialString(ref pstr, _) => { - buf += pstr.as_str_from(n); - } - _ => { - unreachable!() - } + PStrIteratee::PStrSegment(h, n) => match &self.machine_st.heap[h] { + HeapCellValue::PartialString(ref pstr, _) => { + buf += pstr.as_str_from(n); } - } + _ => { + unreachable!() + } + }, } } @@ -291,7 +270,9 @@ impl<'a> Iterator for HeapPStrIter<'a> { } } Addr::Lis(l) => { - let addr = self.machine_st.store(self.machine_st.deref(Addr::HeapCell(l))); + let addr = self + .machine_st + .store(self.machine_st.deref(Addr::HeapCell(l))); let opt_c = match addr { Addr::Con(h) if self.machine_st.heap.atom_at(h) => { @@ -305,12 +286,8 @@ impl<'a> Iterator for HeapPStrIter<'a> { unreachable!() } } - Addr::Char(c) => { - Some(c) - } - _ => { - None - } + Addr::Char(c) => Some(c), + _ => None, }; if let Some(c) = opt_c { @@ -332,8 +309,7 @@ impl<'a> Iterator for HeapPStrIter<'a> { } #[inline] -pub(super) -fn compare_pstr_prefixes<'a>( +pub(super) fn compare_pstr_prefixes<'a>( i1: &mut HeapPStrIter<'a>, i2: &mut HeapPStrIter<'a>, ) -> Option { @@ -425,25 +401,16 @@ fn compare_pstr_prefixes<'a>( } return match (i1.focus(), i2.focus()) { - (Addr::EmptyList, Addr::EmptyList) => { - Some(Ordering::Equal) - } - (Addr::EmptyList, _) => { - Some(Ordering::Less) - } - (_, Addr::EmptyList) => { - Some(Ordering::Greater) - } - _ => { - None - } + (Addr::EmptyList, Addr::EmptyList) => Some(Ordering::Equal), + (Addr::EmptyList, _) => Some(Ordering::Less), + (_, Addr::EmptyList) => Some(Ordering::Greater), + _ => None, }; } } #[inline] -pub(super) -fn compare_pstr_to_string<'a>( +pub(super) fn compare_pstr_to_string<'a>( heap_pstr_iter: &mut HeapPStrIter<'a>, s: &String, ) -> Option { @@ -452,7 +419,7 @@ fn compare_pstr_to_string<'a>( while let Some(iteratee) = heap_pstr_iter.next() { match iteratee { PStrIteratee::Char(c1) => { - if let Some(c2) = s[s_offset ..].chars().next() { + if let Some(c2) = s[s_offset..].chars().next() { if c1 != c2 { return None; } else { @@ -462,31 +429,28 @@ fn compare_pstr_to_string<'a>( return Some(s_offset); } } - PStrIteratee::PStrSegment(h, n) => { - match heap_pstr_iter.machine_st.heap[h] { - HeapCellValue::PartialString(ref pstr, _) => { - let t = pstr.as_str_from(n); + PStrIteratee::PStrSegment(h, n) => match heap_pstr_iter.machine_st.heap[h] { + HeapCellValue::PartialString(ref pstr, _) => { + let t = pstr.as_str_from(n); - if s[s_offset ..].starts_with(t) { - s_offset += t.len(); - } else if t.starts_with(&s[s_offset ..]) { - heap_pstr_iter.focus = - Addr::PStrLocation(h, n + s[s_offset ..].len()); + if s[s_offset..].starts_with(t) { + s_offset += t.len(); + } else if t.starts_with(&s[s_offset..]) { + heap_pstr_iter.focus = Addr::PStrLocation(h, n + s[s_offset..].len()); - s_offset += s[s_offset ..].len(); - return Some(s_offset); - } else { - return None; - } - } - _ => { - unreachable!() + s_offset += s[s_offset..].len(); + return Some(s_offset); + } else { + return None; } } - } + _ => { + unreachable!() + } + }, } - if s[s_offset ..].is_empty() { + if s[s_offset..].is_empty() { return Some(s_offset); } } diff --git a/src/machine/preprocessor.rs b/src/machine/preprocessor.rs index bbc99c22e..62a446f81 100644 --- a/src/machine/preprocessor.rs +++ b/src/machine/preprocessor.rs @@ -30,7 +30,7 @@ pub(crate) enum CutContext { HasCutVariable, } -pub fn fold_by_str(terms: I, mut term: Term, sym: ClauseName) -> Term +pub(crate) fn fold_by_str(terms: I, mut term: Term, sym: ClauseName) -> Term where I: DoubleEndedIterator, { @@ -46,7 +46,11 @@ where term } -pub fn to_op_decl(prec: usize, spec: &str, name: ClauseName) -> Result { +pub(crate) fn to_op_decl( + prec: usize, + spec: &str, + name: ClauseName, +) -> Result { match spec { "xfx" => Ok(OpDecl::new(prec, XFX, name)), "xfy" => Ok(OpDecl::new(prec, XFY, name)), @@ -825,11 +829,7 @@ impl Preprocessor { cut_context: CutContext, ) -> Result { 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 qt = query_terms.pop().unwrap(); @@ -894,11 +894,7 @@ impl Preprocessor { let mut results = VecDeque::new(); for term in terms.into_iter() { - results.push_back(self.try_term_to_tl( - load_state, - term, - cut_context, - )?); + results.push_back(self.try_term_to_tl(load_state, term, cut_context)?); } Ok(results) diff --git a/src/machine/stack.rs b/src/machine/stack.rs index ab7d48e2a..8240d2a87 100644 --- a/src/machine/stack.rs +++ b/src/machine/stack.rs @@ -23,9 +23,7 @@ impl RawBlockTraits for StackTraits { #[inline] fn base_offset(base: *const u8) -> *const u8 { - unsafe { - base.offset(Self::align() as isize) - } + unsafe { base.offset(Self::align() as isize) } } } @@ -37,7 +35,7 @@ const fn prelude_size() -> usize { } #[derive(Debug)] -pub struct Stack { +pub(crate) struct Stack { buf: RawBlock, _marker: PhantomData, } @@ -50,25 +48,25 @@ impl Drop for Stack { } #[derive(Debug, Clone, Copy)] -pub struct FramePrelude { - pub num_cells: usize, +pub(crate) struct FramePrelude { + pub(crate) num_cells: usize, } #[derive(Debug)] -pub struct AndFramePrelude { - pub univ_prelude: FramePrelude, - pub e: usize, - pub cp: LocalCodePtr, - pub interrupt_cp: LocalCodePtr, +pub(crate) struct AndFramePrelude { + pub(crate) univ_prelude: FramePrelude, + pub(crate) e: usize, + pub(crate) cp: LocalCodePtr, + pub(crate) interrupt_cp: LocalCodePtr, } #[derive(Debug)] -pub struct AndFrame { - pub prelude: AndFramePrelude, +pub(crate) struct AndFrame { + pub(crate) prelude: AndFramePrelude, } impl AndFrame { - pub fn size_of(num_cells: usize) -> usize { + pub(crate) fn size_of(num_cells: usize) -> usize { prelude_size::() + num_cells * mem::size_of::() } } @@ -104,23 +102,23 @@ impl IndexMut for AndFrame { } #[derive(Debug)] -pub struct OrFramePrelude { - pub univ_prelude: FramePrelude, - pub e: usize, - pub cp: LocalCodePtr, - pub b: usize, - pub bp: LocalCodePtr, - pub tr: usize, - pub pstr_tr: usize, - pub h: usize, - pub b0: usize, - pub attr_var_init_queue_b: usize, - pub attr_var_init_bindings_b: usize, +pub(crate) struct OrFramePrelude { + pub(crate) univ_prelude: FramePrelude, + pub(crate) e: usize, + pub(crate) cp: LocalCodePtr, + pub(crate) b: usize, + pub(crate) bp: LocalCodePtr, + pub(crate) tr: usize, + pub(crate) pstr_tr: usize, + pub(crate) h: usize, + pub(crate) b0: usize, + pub(crate) attr_var_init_queue_b: usize, + pub(crate) attr_var_init_bindings_b: usize, } #[derive(Debug)] -pub struct OrFrame { - pub prelude: OrFramePrelude, +pub(crate) struct OrFrame { + pub(crate) prelude: OrFramePrelude, } impl Index for OrFrame { @@ -156,24 +154,27 @@ impl IndexMut for OrFrame { } impl OrFrame { - pub fn size_of(num_cells: usize) -> usize { + pub(crate) fn size_of(num_cells: usize) -> usize { prelude_size::() + num_cells * mem::size_of::() } } impl Stack { - pub fn new() -> Self { - Stack { buf: RawBlock::new(), _marker: PhantomData } + pub(crate) fn new() -> Self { + Stack { + buf: RawBlock::new(), + _marker: PhantomData, + } } - pub fn allocate_and_frame(&mut self, num_cells: usize) -> usize { + pub(crate) fn allocate_and_frame(&mut self, num_cells: usize) -> usize { let frame_size = AndFrame::size_of(num_cells); unsafe { let new_top = self.buf.new_block(frame_size); let e = self.buf.top as usize - self.buf.base as usize; - for idx in 0 .. num_cells { + for idx in 0..num_cells { let offset = prelude_size::() + idx * mem::size_of::(); ptr::write( (self.buf.top as usize + offset) as *mut Addr, @@ -190,14 +191,14 @@ impl Stack { } } - pub fn allocate_or_frame(&mut self, num_cells: usize) -> usize { + pub(crate) fn allocate_or_frame(&mut self, num_cells: usize) -> usize { let frame_size = OrFrame::size_of(num_cells); unsafe { let new_top = self.buf.new_block(frame_size); let b = self.buf.top as usize - self.buf.base as usize; - for idx in 0 .. num_cells { + for idx in 0..num_cells { let offset = prelude_size::() + idx * mem::size_of::(); ptr::write( (self.buf.top as usize + offset) as *mut Addr, @@ -215,7 +216,7 @@ impl Stack { } #[inline] - pub fn index_and_frame(&self, e: usize) -> &AndFrame { + pub(crate) fn index_and_frame(&self, e: usize) -> &AndFrame { unsafe { let ptr = self.buf.base as usize + e; &*(ptr as *const AndFrame) @@ -223,7 +224,7 @@ impl Stack { } #[inline] - pub fn index_and_frame_mut(&mut self, e: usize) -> &mut AndFrame { + pub(crate) fn index_and_frame_mut(&mut self, e: usize) -> &mut AndFrame { unsafe { let ptr = self.buf.base as usize + e; &mut *(ptr as *mut AndFrame) @@ -231,7 +232,7 @@ impl Stack { } #[inline] - pub fn index_or_frame(&self, b: usize) -> &OrFrame { + pub(crate) fn index_or_frame(&self, b: usize) -> &OrFrame { unsafe { let ptr = self.buf.base as usize + b; &*(ptr as *const OrFrame) @@ -239,7 +240,7 @@ impl Stack { } #[inline] - pub fn index_or_frame_mut(&mut self, b: usize) -> &mut OrFrame { + pub(crate) fn index_or_frame_mut(&mut self, b: usize) -> &mut OrFrame { unsafe { let ptr = self.buf.base as usize + b; &mut *(ptr as *mut OrFrame) @@ -247,7 +248,7 @@ impl Stack { } #[inline] - pub fn truncate(&mut self, b: usize) { + pub(crate) fn truncate(&mut self, b: usize) { if b == 0 { self.inner_truncate(mem::align_of::()); } else { @@ -264,7 +265,7 @@ impl Stack { } } - pub fn drop_in_place(&mut self) { + pub(crate) fn drop_in_place(&mut self) { self.truncate(mem::align_of::()); debug_assert!(if self.buf.top.is_null() { diff --git a/src/machine/streams.rs b/src/machine/streams.rs index 56bb38364..e1401b0ed 100644 --- a/src/machine/streams.rs +++ b/src/machine/streams.rs @@ -23,7 +23,7 @@ use std::rc::Rc; use native_tls::TlsStream; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum StreamType { +pub(crate) enum StreamType { Binary, Text, } @@ -55,14 +55,14 @@ impl StreamType { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum EOFAction { +pub(crate) enum EOFAction { EOFCode, Error, Reset, } #[derive(Debug, PartialEq)] -pub enum AtEndOfStream { +pub(crate) enum AtEndOfStream { Not, At, Past, @@ -198,7 +198,7 @@ impl fmt::Debug for StreamInstance { } #[derive(Debug)] -struct InnerStream { +pub(crate) struct InnerStream { options: StreamOptions, stream_inst: StreamInstance, past_end_of_stream: bool, @@ -211,14 +211,12 @@ struct WrappedStreamInstance(Rc>); impl WrappedStreamInstance { #[inline] fn new(stream_inst: StreamInstance, past_end_of_stream: bool) -> Self { - WrappedStreamInstance(Rc::new(RefCell::new( - InnerStream { - options: StreamOptions::default(), - stream_inst, - past_end_of_stream, - lines_read: 0, - } - ))) + WrappedStreamInstance(Rc::new(RefCell::new(InnerStream { + options: StreamOptions::default(), + stream_inst, + past_end_of_stream, + lines_read: 0, + }))) } } @@ -287,11 +285,11 @@ impl fmt::Display for StreamError { impl Error for StreamError {} #[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct StreamOptions { - pub stream_type: StreamType, - pub reposition: bool, - pub alias: Option, - pub eof_action: EOFAction, +pub(crate) struct StreamOptions { + pub(crate) stream_type: StreamType, + pub(crate) reposition: bool, + pub(crate) alias: Option, + pub(crate) eof_action: EOFAction, } impl Default for StreamOptions { @@ -366,6 +364,23 @@ impl Stream { ptr as *const u8 } + pub fn bytes(&self) -> Option>> { + // if Ref had an and_then function this could be simplified + let val = std::cell::Ref::map(self.stream_inst.0.borrow(), |inner_stream| { + &inner_stream.stream_inst + }); + match std::ops::Deref::deref(&val) { + StreamInstance::Bytes(_) => Some(std::cell::Ref::map( + std::cell::Ref::clone(&val), + |instance| match instance { + StreamInstance::Bytes(cursor) => cursor.get_ref(), + _ => unreachable!(), + }, + )), + _ => None, + } + } + #[inline] pub(crate) fn lines_read(&mut self) -> usize { self.stream_inst.0.borrow_mut().lines_read @@ -378,30 +393,29 @@ impl Stream { #[inline] pub(crate) fn options(&self) -> std::cell::Ref<'_, StreamOptions> { - std::cell::Ref::map( - self.stream_inst.0.borrow(), - |inner_stream| &inner_stream.options, - ) + std::cell::Ref::map(self.stream_inst.0.borrow(), |inner_stream| { + &inner_stream.options + }) } #[inline] pub(crate) fn options_mut(&mut self) -> std::cell::RefMut<'_, StreamOptions> { - std::cell::RefMut::map( - self.stream_inst.0.borrow_mut(), - |inner_stream| &mut inner_stream.options, - ) + std::cell::RefMut::map(self.stream_inst.0.borrow_mut(), |inner_stream| { + &mut inner_stream.options + }) } #[inline] - pub(crate) fn position(&mut self) -> Option<(u64, usize)> { // returns lines_read, position. + pub(crate) fn position(&mut self) -> Option<(u64, usize)> { + // returns lines_read, position. let result = match self.stream_inst.0.borrow_mut().stream_inst { StreamInstance::InputFile(_, ref mut file) => file.seek(SeekFrom::Current(0)).ok(), - StreamInstance::TcpStream(..) | - StreamInstance::TlsStream(..) | - StreamInstance::ReadlineStream(..) | - StreamInstance::StaticStr(..) | - StreamInstance::PausedPrologStream(..) | - StreamInstance::Bytes(..) => Some(0), + StreamInstance::TcpStream(..) + | StreamInstance::TlsStream(..) + | StreamInstance::ReadlineStream(..) + | StreamInstance::StaticStr(..) + | StreamInstance::PausedPrologStream(..) + | StreamInstance::Bytes(..) => Some(0), _ => None, }; @@ -411,9 +425,11 @@ impl Stream { #[inline] pub(crate) fn set_position(&mut self, position: u64) { match self.stream_inst.0.borrow_mut().deref_mut() { - InnerStream { past_end_of_stream, - stream_inst: StreamInstance::InputFile(_, ref mut file), - .. } => { + InnerStream { + past_end_of_stream, + stream_inst: StreamInstance::InputFile(_, ref mut file), + .. + } => { file.seek(SeekFrom::Start(position)).unwrap(); if let Ok(metadata) = file.metadata() { @@ -446,31 +462,31 @@ impl Stream { } match self.stream_inst.0.borrow_mut().deref_mut() { - InnerStream { past_end_of_stream, - stream_inst: StreamInstance::InputFile(_, ref mut file), - .. } => { - match file.metadata() { - 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::Greater => { - *past_end_of_stream = true; - AtEndOfStream::Past - } - }; - } else { - *past_end_of_stream = true; - AtEndOfStream::Past - } - } - _ => { + InnerStream { + past_end_of_stream, + stream_inst: StreamInstance::InputFile(_, ref mut file), + .. + } => match file.metadata() { + 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::Greater => { + *past_end_of_stream = true; + AtEndOfStream::Past + } + }; + } else { *past_end_of_stream = true; AtEndOfStream::Past } } - } + _ => { + *past_end_of_stream = true; + AtEndOfStream::Past + } + }, _ => AtEndOfStream::Not, } } @@ -488,11 +504,11 @@ impl Stream { #[inline] pub(crate) fn mode(&self) -> &'static str { match self.stream_inst.0.borrow().stream_inst { - StreamInstance::Bytes(_) | - StreamInstance::PausedPrologStream(..) | - StreamInstance::ReadlineStream(_) | - StreamInstance::StaticStr(_) | - StreamInstance::InputFile(..) => "read", + 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", @@ -508,7 +524,7 @@ impl Stream { } #[inline] - pub(crate) fn stdout() -> Self { + pub fn stdout() -> Self { Stream::from_inst(StreamInstance::Stdout) } @@ -568,13 +584,13 @@ impl Stream { #[inline] pub(crate) fn is_input_stream(&self) -> bool { match self.stream_inst.0.borrow().stream_inst { - StreamInstance::TcpStream(..) | - StreamInstance::TlsStream(..) | - StreamInstance::Bytes(_) | - StreamInstance::PausedPrologStream(..) | - StreamInstance::ReadlineStream(_) | - StreamInstance::StaticStr(_) | - StreamInstance::InputFile(..) => true, + StreamInstance::TcpStream(..) + | StreamInstance::TlsStream(..) + | StreamInstance::Bytes(_) + | StreamInstance::PausedPrologStream(..) + | StreamInstance::ReadlineStream(_) + | StreamInstance::StaticStr(_) + | StreamInstance::InputFile(..) => true, _ => false, } } @@ -582,11 +598,11 @@ impl Stream { #[inline] pub(crate) fn is_output_stream(&self) -> bool { match self.stream_inst.0.borrow().stream_inst { - StreamInstance::Stdout | - StreamInstance::TcpStream(..) | - StreamInstance::TlsStream(..) | - StreamInstance::Bytes(_) | - StreamInstance::OutputFile(..) => true, + StreamInstance::Stdout + | StreamInstance::TcpStream(..) + | StreamInstance::TlsStream(..) + | StreamInstance::Bytes(_) + | StreamInstance::OutputFile(..) => true, _ => false, } } @@ -1084,11 +1100,11 @@ impl Write for Stream { 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( + StreamInstance::PausedPrologStream(..) + | StreamInstance::StaticStr(_) + | StreamInstance::ReadlineStream(_) + | StreamInstance::InputFile(..) + | StreamInstance::Null => Err(std::io::Error::new( ErrorKind::PermissionDenied, StreamError::WriteToInputStream, )), @@ -1102,11 +1118,11 @@ impl Write for Stream { 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( + 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 bc6724a5f..a37e4efee 100644 --- a/src/machine/system_calls.rs +++ b/src/machine/system_calls.rs @@ -71,7 +71,7 @@ use base64; use roxmltree; use select; -pub fn get_key() -> KeyEvent { +pub(crate) fn get_key() -> KeyEvent { let key; enable_raw_mode().expect("failed to enable raw mode"); loop { diff --git a/src/machine/term_stream.rs b/src/machine/term_stream.rs index 6a23ff664..e55a54996 100644 --- a/src/machine/term_stream.rs +++ b/src/machine/term_stream.rs @@ -78,7 +78,7 @@ impl<'a> TermStream for BootstrappingTermStream<'a> { } } -pub struct LiveTermStream { +pub(crate) struct LiveTermStream { pub(super) term_queue: VecDeque, pub(super) listing_src: ListingSource, } @@ -93,7 +93,7 @@ impl LiveTermStream { } } -pub struct LoadStatePayload { +pub(crate) struct LoadStatePayload { pub(super) term_stream: LiveTermStream, pub(super) compilation_target: CompilationTarget, pub(super) retraction_info: RetractionInfo, diff --git a/src/read.rs b/src/read.rs index 78de8e301..366962cb0 100644 --- a/src/read.rs +++ b/src/read.rs @@ -12,7 +12,7 @@ use std::collections::VecDeque; type SubtermDeque = VecDeque<(usize, usize)>; -pub type PrologStream = ParsingStream; +pub(crate) type PrologStream = ParsingStream; pub mod readline { use crate::machine::streams::Stream; @@ -24,7 +24,7 @@ pub mod readline { const HISTORY_FILE: &'static str = ".scryer_history"; - pub fn set_prompt(value: bool) { + pub(crate) fn set_prompt(value: bool) { unsafe { PROMPT = value; } @@ -49,10 +49,8 @@ pub mod readline { impl ReadlineStream { #[inline] - pub fn new(pending_input: String) -> Self { - let config = Config::builder() - .check_cursor_position(true) - .build(); + pub(crate) fn new(pending_input: String) -> Self { + let config = Config::builder().check_cursor_position(true).build(); let mut rl = Editor::<()>::with_config(config); //Editor::<()>::new(); if let Some(mut path) = dirs_next::home_dir() { @@ -72,7 +70,7 @@ pub mod readline { } #[inline] - pub fn input_stream(pending_input: String) -> Stream { + pub(crate) fn input_stream(pending_input: String) -> Stream { Stream::from(Self::new(pending_input)) } @@ -116,7 +114,7 @@ pub mod readline { } } - pub fn peek_byte(&mut self) -> std::io::Result { + pub(crate) fn peek_byte(&mut self) -> std::io::Result { set_prompt(false); loop { @@ -137,7 +135,7 @@ pub mod readline { } } - pub fn peek_char(&mut self) -> std::io::Result { + pub(crate) fn peek_char(&mut self) -> std::io::Result { set_prompt(false); loop { @@ -176,7 +174,7 @@ pub mod readline { } impl MachineState { - pub fn devour_whitespace( + pub(crate) fn devour_whitespace( &mut self, mut inner: Stream, atom_tbl: TabledData, @@ -196,7 +194,7 @@ impl MachineState { result } - pub fn read( + pub(crate) fn read( &mut self, mut inner: Stream, atom_tbl: TabledData, @@ -241,7 +239,7 @@ struct TermWriter<'a> { } #[derive(Debug)] -pub struct TermWriteResult { +pub(crate) struct TermWriteResult { pub(crate) heap_loc: usize, pub(crate) var_dict: HeapVarDict, } diff --git a/src/targets.rs b/src/targets.rs index 956da22af..78e988e5d 100644 --- a/src/targets.rs +++ b/src/targets.rs @@ -5,7 +5,7 @@ use crate::forms::*; use crate::instructions::*; use crate::iterators::*; -pub trait CompilationTarget<'a> { +pub(crate) trait CompilationTarget<'a> { type Iterator: Iterator>; fn iter(_: &'a Term) -> Self::Iterator; diff --git a/src/tests/hello_world.pl b/src/tests/hello_world.pl new file mode 100644 index 000000000..e7fd4e202 --- /dev/null +++ b/src/tests/hello_world.pl @@ -0,0 +1,6 @@ +:- use_module(library(debug)). +:- use_module(library(format)). + +hello_world :- write('Hello World!'), nl. + +:- initialization(hello_world). \ No newline at end of file diff --git a/tests/scryer.rs b/tests/scryer.rs new file mode 100644 index 000000000..55d67a73f --- /dev/null +++ b/tests/scryer.rs @@ -0,0 +1,65 @@ +/// Loads the file and if some expected output is given checks that it matches +fn test_file(file: &str, expected: Option<&[u8]>) { + use scryer_prolog::*; + + let input = machine::Stream::from(""); + let output = machine::Stream::from(String::new()); + + let mut wam = machine::Machine::new(input, output.clone()); + + wam.load_file( + file.into(), + machine::Stream::from( + std::fs::read_to_string(AsRef::::as_ref(file)).unwrap(), + ), + ); + + if let Some(expected) = expected { + let output = output.bytes().unwrap(); + assert_eq!(output.as_slice(), expected); + } +} + +#[test] +fn builtins() { + test_file("src/tests/builtins.pl", Some(b"")); +} + +#[test] +fn call_with_inference_limit() { + test_file("src/tests/call_with_inference_limit.pl", Some(b"")); +} + +#[test] +fn facts() { + test_file("src/tests/facts.pl", Some(b"")); +} + +#[test] +fn hello_world() { + test_file( + "src/tests/hello_world.pl", + Some("Hello World!\n".as_bytes()), + ); +} + +#[test] +fn predicates() { + test_file("src/tests/predicates.pl", Some(b"")); +} + +#[test] +fn rules() { + test_file("src/tests/rules.pl", Some(b"")); +} + +#[test] +#[ignore] // ignored as this does not appear to terminate +fn setup_call_cleanup() { + test_file("src/tests/setup_call_cleanup.pl", Some(b"")); +} + +#[test] +fn clpz() { + test_file("src/tests/clpz/test_clpz.pl", Some(b"")); +}