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();
use std::cell::Cell;
use std::rc::Rc;
-pub trait Allocator<'a> {
+pub(crate) trait Allocator<'a> {
fn new() -> Self;
fn mark_anon_var<Target>(&mut self, _: Level, _: GenContext, _: &mut Vec<Target>)
use std::vec::Vec;
#[derive(Debug)]
-pub struct ArithInstructionIterator<'a> {
+pub(crate) struct ArithInstructionIterator<'a> {
state_stack: Vec<TermIterState<'a>>,
}
-pub type ArithCont = (Code, Option<ArithmeticTerm>);
+pub(crate) type ArithCont = (Code, Option<ArithmeticTerm>);
impl<'a> ArithInstructionIterator<'a> {
fn push_subterm(&mut self, lvl: Level, term: &'a Term) {
}
#[derive(Debug)]
-pub enum ArithTermRef<'a> {
+pub(crate) enum ArithTermRef<'a> {
Constant(&'a Constant),
Op(ClauseName, usize), // name, arity.
Var(&'a Cell<VarReg>, Rc<Var>),
}
#[derive(Debug)]
-pub struct ArithmeticEvaluator<'a> {
+pub(crate) struct ArithmeticEvaluator<'a> {
bindings: &'a AllocVarDict,
interm: Vec<ArithmeticTerm>,
interm_c: usize,
}
-pub trait ArithmeticTermIter<'a> {
+pub(crate) trait ArithmeticTermIter<'a> {
type Iter: Iterator<Item = Result<ArithTermRef<'a>, ArithmeticError>>;
fn iter(self) -> Result<Self::Iter, ArithmeticError>;
}
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(),
Ok(())
}
- pub fn eval<Iter>(&mut self, src: Iter) -> Result<ArithCont, ArithmeticError>
+ pub(crate) fn eval<Iter>(&mut self, src: Iter) -> Result<ArithCont, ArithmeticError>
where
Iter: ArithmeticTermIter<'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(
}
// 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(),
}
// floating point result function -- 9.1.4.2.
-pub fn result_f<Round>(n: &Number, round: Round) -> Result<f64, EvalError>
+pub(crate) fn result_f<Round>(n: &Number, round: Round) -> Result<f64, EvalError>
where
Round: Fn(&Number) -> f64,
{
}
// 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 {
--- /dev/null
+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();
+}
use std::collections::BTreeMap;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
-pub enum CompareNumberQT {
+pub(crate) enum CompareNumberQT {
GreaterThan,
LessThan,
GreaterThanOrEqual,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum CompareTermQT {
+pub(crate) enum CompareTermQT {
LessThan,
LessThanOrEqual,
GreaterThanOrEqual,
}
#[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 {
}
#[derive(Debug, Clone, Eq, PartialEq)]
-pub enum InlinedClauseType {
+pub(crate) enum InlinedClauseType {
CompareNumber(CompareNumberQT, ArithmeticTerm, ArithmeticTerm),
IsAtom(RegType),
IsAtomic(RegType),
}
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);
}
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",
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
-pub enum SystemClauseType {
+pub(crate) enum SystemClauseType {
AtomChars,
AtomCodes,
AtomLength,
}
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"),
}
}
- pub fn from(name: &str, arity: usize) -> Option<SystemClauseType> {
+ pub(crate) fn from(name: &str, arity: usize) -> Option<SystemClauseType> {
match (name, arity) {
("$abolish_clause", 3) => Some(SystemClauseType::REPL(REPLCodePtr::AbolishClause)),
("$add_dynamic_predicate", 4) => {
("$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))
}
("$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),
}
#[derive(Debug, Clone, Eq, PartialEq)]
-pub enum BuiltInClauseType {
+pub(crate) enum BuiltInClauseType {
AcyclicTerm,
Arg,
Compare,
}
#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ClauseType {
+pub(crate) enum ClauseType {
BuiltIn(BuiltInClauseType),
CallN,
Inlined(InlinedClauseType),
}
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"),
}
}
- pub fn arity(&self) -> usize {
+ pub(crate) fn arity(&self) -> usize {
match self {
&BuiltInClauseType::AcyclicTerm => 1,
&BuiltInClauseType::Arg => 3,
}
impl ClauseType {
- pub fn spec(&self) -> Option<SharedOpDesc> {
+ pub(crate) fn spec(&self) -> Option<SharedOpDesc> {
match self {
&ClauseType::Op(_, ref spec, _) => Some(spec.clone()),
&ClauseType::Inlined(InlinedClauseType::CompareNumber(..))
}
}
- 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"),
}
}
- pub fn from(name: ClauseName, arity: usize, spec: Option<SharedOpDesc>) -> Self {
+ pub(crate) fn from(name: ClauseName, arity: usize, spec: Option<SharedOpDesc>) -> Self {
CLAUSE_TYPE_FORMS
.borrow()
.get(&(name.as_str(), arity))
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> {
}
#[derive(Clone, Copy, Debug)]
-pub struct CodeGenSettings {
+pub(crate) struct CodeGenSettings {
pub global_clock_tick: Option<usize>,
pub is_extensible: bool,
pub non_counted_bt: bool,
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,
}
}
- 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,
}
}
- 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,
}
}
- 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,
}
}
- 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,
}
}
- 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,
}
#[derive(Debug)]
-pub struct CodeGenerator<TermMarker> {
+pub(crate) struct CodeGenerator<TermMarker> {
atom_tbl: TabledData<Atom>,
marker: TermMarker,
- pub var_count: IndexMap<Rc<Var>, usize>,
+ pub(crate) var_count: IndexMap<Rc<Var>, usize>,
settings: CodeGenSettings,
- pub skeleton: PredicateSkeleton,
- pub jmp_by_locs: Vec<usize>,
+ pub(crate) skeleton: PredicateSkeleton,
+ pub(crate) jmp_by_locs: Vec<usize>,
global_jmp_by_locs_offset: usize,
}
impl<'a, TermMarker: Allocator<'a>> CodeGenerator<TermMarker> {
- pub fn new(atom_tbl: TabledData<Atom>, settings: CodeGenSettings) -> Self {
+ pub(crate) fn new(atom_tbl: TabledData<Atom>, settings: CodeGenSettings) -> Self {
CodeGenerator {
atom_tbl,
marker: Allocator::new(),
}
}
- pub fn compile_rule<'b: 'a>(&mut self, rule: &'b Rule) -> Result<Code, CompilationError> {
+ pub(crate) fn compile_rule<'b: 'a>(
+ &mut self,
+ rule: &'b Rule,
+ ) -> Result<Code, CompilationError> {
let iter = ChunkedIterator::from_rule(rule);
let conjunct_info = self.collect_var_data(iter);
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();
Ok(Vec::from(code))
}
- pub fn compile_predicate<'b: 'a>(
+ pub(crate) fn compile_predicate<'b: 'a>(
&mut self,
clauses: &'b Vec<PredicateClause>,
) -> Result<Code, CompilationError> {
use std::rc::Rc;
#[derive(Debug)]
-pub struct DebrayAllocator {
+pub(crate) struct DebrayAllocator {
bindings: IndexMap<Rc<Var>, VarData>,
arg_c: usize,
temp_lb: usize,
// 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),
}
#[derive(Debug)]
-pub struct TempVarData {
- pub last_term_arity: usize,
- pub use_set: OccurrenceSet,
- pub no_use_set: BTreeSet<usize>,
- pub conflict_set: BTreeSet<usize>,
+pub(crate) struct TempVarData {
+ pub(crate) last_term_arity: usize,
+ pub(crate) use_set: OccurrenceSet,
+ pub(crate) no_use_set: BTreeSet<usize>,
+ pub(crate) conflict_set: BTreeSet<usize>,
}
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(),
}
}
- 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;
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<usize> = (1..arity).collect();
type VariableFixture<'a> = (VarStatus, Vec<&'a Cell<VarReg>>);
#[derive(Debug)]
-pub struct VariableFixtures<'a> {
+pub(crate) struct VariableFixtures<'a> {
perm_vars: IndexMap<Rc<Var>, VariableFixture<'a>>,
last_chunk_temp_vars: IndexSet<Rc<Var>>,
}
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<Var>, vs: VariableFixture<'a>) {
+ pub(crate) fn insert(&mut self, var: Rc<Var>, vs: VariableFixture<'a>) {
self.perm_vars.insert(var, vs);
}
- pub fn insert_last_chunk_temp_var(&mut self, var: Rc<Var>) {
+ pub(crate) fn insert_last_chunk_temp_var(&mut self, var: Rc<Var>) {
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).
};
}
- 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() {
var_count
}
- pub fn mark_vars_in_chunk<I>(&mut self, iter: I, lt_arity: usize, term_loc: GenContext)
+ pub(crate) fn mark_vars_in_chunk<I>(&mut self, iter: I, lt_arity: usize, term_loc: GenContext)
where
I: Iterator<Item = TermRef<'a>>,
{
}
}
- pub fn into_iter(self) -> indexmap::map::IntoIter<Rc<Var>, VariableFixture<'a>> {
+ pub(crate) fn into_iter(self) -> indexmap::map::IntoIter<Rc<Var>, VariableFixture<'a>> {
self.perm_vars.into_iter()
}
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 {
}
#[derive(Debug)]
-pub struct UnsafeVarMarker {
- pub unsafe_vars: IndexMap<RegType, usize>,
- pub safe_vars: IndexSet<RegType>,
+pub(crate) struct UnsafeVarMarker {
+ pub(crate) unsafe_vars: IndexMap<RegType, usize>,
+ pub(crate) safe_vars: IndexSet<RegType>,
}
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<RegType>) -> Self {
+ pub(crate) fn from_safe_vars(safe_vars: IndexSet<RegType>) -> 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) => {
}
}
- 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) => {
}
}
- 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)) {
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<PredicateClause>;
+pub(crate) type Predicate = Vec<PredicateClause>;
// vars of predicate, toplevel offset. Vec<Term> is always a vector
// of vars (we get their adjoining cells this way).
-pub type JumpStub = Vec<Term>;
+pub(crate) type JumpStub = Vec<Term>;
#[derive(Debug, Clone)]
-pub enum TopLevel {
+pub(crate) enum TopLevel {
Fact(Term), // Term, line_num, col_num
Predicate(Predicate),
Query(Vec<QueryTerm>),
}
#[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,
}
#[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,
}
#[derive(Debug, Clone)]
-pub enum QueryTerm {
+pub(crate) enum QueryTerm {
// register, clause type, subterms, use default call policy.
Clause(Cell<RegType>, ClauseType, Vec<Box<Term>>, bool),
BlockedCut, // a cut which is 'blocked by letters', like the P term in P -> Q.
}
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,
}
#[derive(Debug, Clone)]
-pub struct Rule {
- pub head: (ClauseName, Vec<Box<Term>>, QueryTerm),
- pub clauses: Vec<QueryTerm>,
+pub(crate) struct Rule {
+ pub(crate) head: (ClauseName, Vec<Box<Term>>, QueryTerm),
+ pub(crate) clauses: Vec<QueryTerm>,
}
#[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,
}
}
}
}
-// pub type CompiledResult = (Predicate, VecDeque<TopLevel>);
+// pub(crate) type CompiledResult = (Predicate, VecDeque<TopLevel>);
#[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<Term>]> {
+ pub(crate) fn args(&self) -> Option<&[Box<Term>]> {
match *self {
PredicateClause::Fact(ref term, ..) => match term {
Term::Clause(_, _, args, _) => Some(&args),
}
#[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())])
}
}
-// 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,
}
#[derive(Debug, Clone)]
-pub enum Declaration {
+pub(crate) enum Declaration {
Dynamic(ClauseName, usize),
MetaPredicate(ClauseName, ClauseName, Vec<MetaSpec>), // module name, name, meta-specs
Module(ModuleDecl),
}
#[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;
}
#[inline]
- pub fn fixity(&self) -> Fixity {
+ pub(crate) fn fixity(&self) -> Fixity {
match self.spec {
XFY | XFX | YFX => Fixity::In,
XF | YF => Fixity::Post,
}
}
- 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) {
.map(|op_dir_value| op_dir_value.shared_op_desc().get())
}
- pub fn submit(
+ pub(crate) fn submit(
&self,
existing_desc: Option<OpDesc>,
op_dir: &mut OpDir,
}
}
-pub fn fetch_atom_op_spec(
+pub(crate) fn fetch_atom_op_spec(
name: ClauseName,
spec: Option<SharedOpDesc>,
op_dir: &OpDir,
.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<SharedOpDesc>,
spec.or_else(|| fetch_op_spec(name, arity, op_dir))
}
-pub fn fetch_op_spec(name: ClauseName, arity: usize, op_dir: &OpDir) -> Option<SharedOpDesc> {
+pub(crate) fn fetch_op_spec(
+ name: ClauseName,
+ arity: usize,
+ op_dir: &OpDir,
+) -> Option<SharedOpDesc> {
match arity {
2 => op_dir
.get(&(name, Fixity::In))
}
}
-pub type ModuleDir = IndexMap<ClauseName, Module>;
+pub(crate) type ModuleDir = IndexMap<ClauseName, Module>;
#[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<ModuleExport>,
+pub(crate) struct ModuleDecl {
+ pub(crate) name: ClauseName,
+ pub(crate) exports: Vec<ModuleExport>,
}
#[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(),
}
#[derive(Debug, Clone)]
-pub enum Number {
+pub(crate) enum Number {
Float(OrderedFloat<f64>),
Integer(Rc<Integer>),
Rational(Rc<Rational>),
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,
}
#[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,
}
#[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,
}
#[inline]
- pub fn abs(self) -> Self {
+ pub(crate) fn abs(self) -> Self {
match self {
Number::Fixnum(n) => {
if let Some(n) = n.checked_abs() {
}
#[derive(Debug, Clone)]
-pub enum OptArgIndexKey {
+pub(crate) enum OptArgIndexKey {
Constant(usize, usize, Constant, Vec<Constant>), // index, IndexingCode location, opt arg, alternatives
List(usize, usize), // index, IndexingCode location
None,
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, ..)
}
#[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<usize> {
+ pub(crate) fn switch_on_term_loc(&self) -> Option<usize> {
match &self {
OptArgIndexKey::Constant(_, loc, ..)
| OptArgIndexKey::Structure(_, loc, ..)
}
#[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, ..)
}
#[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,
}
#[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 {
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<ClauseIndexInfo>,
- pub clause_clause_locs: SliceDeque<usize>,
- 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<ClauseIndexInfo>,
+ pub(crate) clause_clause_locs: SliceDeque<usize>,
+ 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,
}
#[inline]
- pub fn predicate_info(&self) -> PredicateInfo {
+ pub(crate) fn predicate_info(&self) -> PredicateInfo {
PredicateInfo {
is_extensible: true,
is_discontiguous: self.is_discontiguous,
}
#[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<usize> {
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(),
}
}
}
use std::vec::Vec;
#[derive(Debug)]
-pub struct HCPreOrderIterator<'a> {
- pub machine_st: &'a MachineState,
- pub state_stack: Vec<Addr>,
+pub(crate) struct HCPreOrderIterator<'a> {
+ pub(crate) machine_st: &'a MachineState,
+ pub(crate) state_stack: Vec<Addr>,
}
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],
}
#[inline]
- pub fn machine_st(&self) -> &MachineState {
+ pub(crate) fn machine_st(&self) -> &MachineState {
&self.machine_st
}
}
}
-pub trait MutStackHCIterator<'b>
+pub(crate) trait MutStackHCIterator<'b>
where
Self: Iterator,
{
}
#[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.
}
}
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![],
}
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,
}
#[derive(Debug)]
-pub struct HCAcyclicIterator<'a> {
+pub(crate) struct HCAcyclicIterator<'a> {
iter: HCPreOrderIterator<'a>,
seen: IndexSet<Addr>,
}
impl<'a> HCAcyclicIterator<'a> {
- pub fn new(iter: HCPreOrderIterator<'a>) -> Self {
+ pub(crate) fn new(iter: HCPreOrderIterator<'a>) -> Self {
HCAcyclicIterator {
iter,
seen: IndexSet::new(),
}
#[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> {
}
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,
/* 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),
}
HeadTailSeparator,
}
-pub trait HCValueOutputter {
+pub(crate) trait HCValueOutputter {
type Output;
fn new() -> Self;
}
#[derive(Debug)]
-pub struct PrinterOutputter {
+pub(crate) struct PrinterOutputter {
contents: String,
}
}
impl MachineState {
- pub fn numbervar(&self, offset: &Integer, addr: Addr) -> Option<Var> {
+ pub(crate) fn numbervar(&self, offset: &Integer, addr: Addr) -> Option<Var> {
let addr = self.store(self.deref(addr));
match Number::try_from((addr, &self.heap)) {
type ReverseHeapVarDict = IndexMap<Addr, Rc<Var>>;
#[derive(Debug)]
-pub struct HCPrinter<'a, Outputter> {
+pub(crate) struct HCPrinter<'a, Outputter> {
outputter: Outputter,
machine_st: &'a MachineState,
op_dir: &'a OpDir,
};
}
-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()
}
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,
}
}
/*
- pub fn from_heap_locs(
+ pub(crate) fn from_heap_locs(
machine_st: &'a MachineState,
op_dir: &'a OpDir,
output: 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);
}
}
}
- 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 {
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,
}
}
-pub fn merge_clause_index(
+pub(crate) fn merge_clause_index(
target_indexing_code: &mut Vec<IndexingLine>,
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.
}
}
-pub fn remove_constant_indices(
+pub(crate) fn remove_constant_indices(
constant: &Constant,
overlapping_constants: &[Constant],
indexing_code: &mut Vec<IndexingLine>,
}
}
-pub fn remove_structure_index(
+pub(crate) fn remove_structure_index(
name: &ClauseName,
arity: usize,
indexing_code: &mut Vec<IndexingLine>,
}
}
-pub fn remove_list_index(indexing_code: &mut Vec<IndexingLine>, offset: usize) {
+pub(crate) fn remove_list_index(indexing_code: &mut Vec<IndexingLine>, offset: usize) {
let mut index = 0;
match &mut indexing_code[index] {
}
}
-pub fn remove_index(
+pub(crate) fn remove_index(
opt_arg_index_key: &OptArgIndexKey,
indexing_code: &mut Vec<IndexingLine>,
clause_loc: usize,
});
}
-pub fn constant_key_alternatives(constant: &Constant, atom_tbl: TabledData<Atom>) -> Vec<Constant> {
+pub(crate) fn constant_key_alternatives(constant: &Constant, atom_tbl: TabledData<Atom>) -> Vec<Constant> {
let mut constants = vec![];
match constant {
structures: IndexMap<(ClauseName, usize), SliceDeque<usize>>,
}
-pub trait Indexer {
+pub(crate) trait Indexer {
type ThirdLevelIndex;
fn new() -> Self;
}
#[derive(Debug)]
-pub struct CodeOffsets<I: Indexer> {
+pub(crate) struct CodeOffsets<I: Indexer> {
atom_tbl: TabledData<Atom>,
indices: I,
optimal_index: usize,
}
impl<I: Indexer> CodeOffsets<I> {
- pub fn new(
+ pub(crate) fn new(
atom_tbl: TabledData<Atom>,
indices: I,
optimal_index: usize,
code_len
}
- pub fn index_term(
+ pub(crate) fn index_term(
&mut self,
optimal_arg: &Term,
index: usize,
}
}
- 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();
no_constants && no_structures && no_lists
}
- pub fn compute_indices(mut self, skip_stub_try_me_else: bool) -> Vec<IndexingLine> {
+ pub(crate) fn compute_indices(mut self, skip_stub_try_me_else: bool) -> Vec<IndexingLine> {
if self.no_indices() {
return vec![];
}
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);
}
#[derive(Debug, Clone, Copy)]
-pub enum NextOrFail {
+pub(crate) enum NextOrFail {
Next(usize),
Fail(usize),
}
}
#[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),
}
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) {
}
#[derive(Debug)]
-pub enum CutInstruction {
+pub(crate) enum CutInstruction {
Cut(RegType),
GetLevel(RegType),
GetLevelAndUnify(RegType),
}
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);
}
#[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,
}
}
- pub fn to_functor(&self) -> MachineStub {
+ pub(crate) fn to_functor(&self) -> MachineStub {
match self {
&IndexedChoiceInstruction::Try(offset) => {
functor!("try", [integer(offset)])
/// A `Line` is an instruction (cf. page 98 of wambook).
#[derive(Debug)]
-pub enum IndexingLine {
+pub(crate) enum IndexingLine {
Indexing(IndexingInstruction),
IndexedChoice(SliceDeque<IndexedChoiceInstruction>),
DynamicIndexedChoice(SliceDeque<usize>),
}
#[derive(Debug)]
-pub enum Line {
+pub(crate) enum Line {
Arithmetic(ArithmeticInstruction),
Choice(ChoiceInstruction),
Control(ControlInstruction),
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,
}
}
- pub fn enqueue_functors(&self, mut h: usize, functors: &mut Vec<MachineStub>) {
+ pub(crate) fn enqueue_functors(&self, mut h: usize, functors: &mut Vec<MachineStub>) {
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)),
}
#[inline]
-pub fn to_indexing_line_mut(line: &mut Line) -> Option<&mut Vec<IndexingLine>> {
+pub(crate) fn to_indexing_line_mut(line: &mut Line) -> Option<&mut Vec<IndexingLine>> {
match line {
Line::IndexingCode(ref mut indexing_code) => Some(indexing_code),
_ => None,
}
#[inline]
-pub fn to_indexing_line(line: &Line) -> Option<&Vec<IndexingLine>> {
+pub(crate) fn to_indexing_line(line: &Line) -> Option<&Vec<IndexingLine>> {
match line {
Line::IndexingCode(ref indexing_code) => Some(indexing_code),
_ => None,
}
#[derive(Debug, Clone)]
-pub enum ArithmeticInstruction {
+pub(crate) enum ArithmeticInstruction {
Add(ArithmeticTerm, ArithmeticTerm, usize),
Sub(ArithmeticTerm, ArithmeticTerm, usize),
Mul(ArithmeticTerm, ArithmeticTerm, usize),
}
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)
}
#[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),
}
impl ControlInstruction {
- pub fn perm_vars(&self) -> Option<usize> {
+ pub(crate) fn perm_vars(&self) -> Option<usize> {
match self {
ControlInstruction::CallClause(_, _, num_cells, ..) => Some(*num_cells),
ControlInstruction::JmpBy(_, _, num_cells, ..) => Some(*num_cells),
}
}
- pub fn to_functor(&self) -> MachineStub {
+ pub(crate) fn to_functor(&self) -> MachineStub {
match self {
&ControlInstruction::Allocate(num_frames) => {
functor!("allocate", [integer(num_frames)])
/// `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,
}
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!(
}
#[derive(Debug, Clone)]
-pub enum FactInstruction {
+pub(crate) enum FactInstruction {
GetConstant(Level, Constant, RegType),
GetList(Level, RegType),
GetPartialString(Level, String, RegType, bool),
}
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();
}
#[derive(Debug, Clone)]
-pub enum QueryInstruction {
+pub(crate) enum QueryInstruction {
GetVariable(RegType, usize),
PutConstant(Level, Constant, RegType),
PutList(Level, RegType),
}
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)])
}
}
-pub type CompiledFact = Vec<FactInstruction>;
+pub(crate) type CompiledFact = Vec<FactInstruction>;
-pub type Code = Vec<Line>;
+pub(crate) type Code = Vec<Line>;
use std::vec::Vec;
#[derive(Debug, Clone)]
-pub enum TermRef<'a> {
+pub(crate) enum TermRef<'a> {
AnonVar(Level),
Cons(Level, &'a Cell<RegType>, &'a Term, &'a Term),
Constant(Level, &'a Cell<RegType>, &'a Constant),
}
impl<'a> TermRef<'a> {
- pub fn level(self) -> Level {
+ pub(crate) fn level(self) -> Level {
match self {
TermRef::AnonVar(lvl)
| TermRef::Cons(lvl, ..)
}
#[derive(Debug)]
-pub enum TermIterState<'a> {
+pub(crate) enum TermIterState<'a> {
AnonVar(Level),
Constant(Level, &'a Cell<RegType>, &'a Constant),
Clause(
}
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) => {
}
#[derive(Debug)]
-pub struct QueryIterator<'a> {
+pub(crate) struct QueryIterator<'a> {
state_stack: Vec<TermIterState<'a>>,
}
}
#[derive(Debug)]
-pub struct FactIterator<'a> {
+pub(crate) struct FactIterator<'a> {
state_queue: VecDeque<TermIterState<'a>>,
iterable_root: bool,
}
.push_back(TermIterState::subterm_to_state(lvl, term));
}
- pub fn from_rule_head_clause(terms: &'a Vec<Box<Term>>) -> Self {
+ pub(crate) fn from_rule_head_clause(terms: &'a Vec<Box<Term>>) -> Self {
let state_queue = terms
.iter()
.map(|bt| TermIterState::subterm_to_state(Level::Shallow, bt.as_ref()))
}
}
-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<Box<Term>>),
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),
false
}
-pub struct ChunkedIterator<'a> {
- pub chunk_num: usize,
+pub(crate) struct ChunkedIterator<'a> {
+ pub(crate) chunk_num: usize,
iter: Box<dyn Iterator<Item = ChunkedTerm<'a>> + 'a>,
deep_cut_encountered: bool,
cut_var_in_head: bool,
type RuleBodyIteratorItem<'a> = (usize, usize, Vec<&'a QueryTerm>);
impl<'a> ChunkedIterator<'a> {
- pub fn rule_body_iter(self) -> Box<dyn Iterator<Item = RuleBodyIteratorItem<'a>> + 'a> {
+ pub(crate) fn rule_body_iter(self) -> Box<dyn Iterator<Item = RuleBodyIteratorItem<'a>> + 'a> {
Box::new(self.filter_map(|(cn, lt_arity, terms)| {
let filtered_terms: Vec<_> = terms
.into_iter()
}))
}
/*
- 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))),
}
}
*/
- pub fn from_rule_body(p1: &'a QueryTerm, clauses: &'a Vec<QueryTerm>) -> Self {
+ pub(crate) fn from_rule_body(p1: &'a QueryTerm, clauses: &'a Vec<QueryTerm>) -> Self {
let inner_iter = Box::new(once(ChunkedTerm::BodyTerm(p1)));
let iter = inner_iter.chain(clauses.iter().map(|t| ChunkedTerm::BodyTerm(t)));
}
}
- 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,
}
}
- pub fn encountered_deep_cut(&self) -> bool {
+ pub(crate) fn encountered_deep_cut(&self) -> bool {
self.deep_cut_encountered
}
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();
-}
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,
&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()),
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 {
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 {
&Line::Choice(ChoiceInstruction::DynamicInternalElse(
birth,
death,
- NextOrFail::Fail(_)),
- ) => {
+ NextOrFail::Fail(_),
+ )) => {
if birth < cc && Death::Finite(cc) <= death {
return Some((p, 0));
} else {
}
}
- 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!(),
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,
}
}
&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)))
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)) => {
return true;
}
}
- _ => {
- }
+ _ => {}
};
false
* 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();
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) {
* 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]);
type Trail = Vec<(Ref, HeapCellValue)>;
#[derive(Debug, Clone, Copy)]
-pub enum AttrVarPolicy {
+pub(crate) enum AttrVarPolicy {
DeepCopy,
- StripAttributes
+ StripAttributes,
}
-pub(crate)
-trait CopierTarget: IndexMut<usize, Output = HeapCellValue> {
+pub(crate) trait CopierTarget: IndexMut<usize, Output = HeapCellValue> {
fn deref(&self, val: Addr) -> Addr;
fn push(&mut self, val: HeapCellValue);
fn stack(&mut self) -> &mut Stack;
fn threshold(&self) -> usize;
}
-pub(crate)
-fn copy_term<T: CopierTarget>(target: T, addr: Addr, attr_var_policy: AttrVarPolicy) {
+pub(crate) fn copy_term<T: CopierTarget>(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);
}
scan: 0,
old_h: target.threshold(),
target,
- attr_var_policy
+ attr_var_policy,
}
}
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));
*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);
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);
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));
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);
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();
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;
}
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)
+ }
}
}
}
}
#[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])
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 => {
}
}
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();
}
}
}
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();
}
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);
}
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 => {}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
-pub enum CompilationTarget {
+pub(crate) enum CompilationTarget {
Module(ClauseName),
User,
}
}
#[inline]
- pub fn module_name(&self) -> ClauseName {
+ pub(crate) fn module_name(&self) -> ClauseName {
match self {
CompilationTarget::User => {
clause_name!("user")
}
}
-pub struct PredicateQueue {
+pub(crate) struct PredicateQueue {
pub(super) predicates: Vec<Term>,
pub(super) compilation_target: CompilationTarget,
}
}
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,
};
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());
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 => {
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 => {
}
},
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;
}
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;
Ok(())
} else {
- Err(SessionError::PredicateNotMultifileOrDiscontiguous(compilation_target, key))
+ Err(SessionError::PredicateNotMultifileOrDiscontiguous(
+ compilation_target,
+ key,
+ ))
}
}
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(
&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(
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);
}
}
}
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)
#[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<LiveTermStream>, CompilationTarget, ClauseName, usize)
- -> Result<(), SessionError>,
+ decl_adder: impl Fn(
+ &mut Loader<LiveTermStream>,
+ CompilationTarget,
+ ClauseName,
+ usize,
+ ) -> Result<(), SessionError>,
) {
let module_name = atom_from!(
self.machine_st,
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
&(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()
})
.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)
&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!();
}
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);
code_dir,
op_dir,
meta_predicate_dir,
- ).unwrap();
+ )
+ .unwrap();
}
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;
// 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,
}
#[derive(Debug)]
-pub enum CompilationError {
+pub(crate) enum CompilationError {
Arithmetic(ArithmeticError),
ParserError(ParserError),
// BadPendingByte,
}
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 =>
}
#[derive(Debug, Clone, Copy)]
-pub enum Permission {
+pub(crate) enum Permission {
Access,
Create,
InputStream,
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",
// from 7.12.2 b) of 13211-1:1995
#[derive(Debug, Clone, Copy)]
-pub enum ValidType {
+pub(crate) enum ValidType {
Atom,
Atomic,
// Boolean,
}
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",
}
#[derive(Debug, Clone, Copy)]
-pub enum DomainErrorType {
+pub(crate) enum DomainErrorType {
IOMode,
NotLessThanZero,
Order,
}
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",
// from 7.12.2 f) of 13211-1:1995
#[derive(Debug, Clone, Copy)]
-pub enum RepFlag {
+pub(crate) enum RepFlag {
Character,
CharacterCode,
InCharacterCode,
}
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",
// from 7.12.2 g) of 13211-1:1995
#[derive(Debug, Clone, Copy)]
-pub enum EvalError {
+pub(crate) enum EvalError {
FloatOverflow,
Undefined,
// Underflow,
}
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",
}
#[derive(Debug)]
-pub enum ExistenceError {
+pub(crate) enum ExistenceError {
Module(ClauseName),
ModuleSource(ModuleSource),
Procedure(ClauseName, usize),
}
#[derive(Debug)]
-pub enum SessionError {
+pub(crate) enum SessionError {
CompilationError(CompilationError),
// CannotOverwriteBuiltIn(ClauseName),
// CannotOverwriteImport(ClauseName),
}
#[derive(Debug)]
-pub enum EvalSession {
+pub(crate) enum EvalSession {
// EntrySuccess,
Error(SessionError),
}
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<OrderedOpDirKey, (usize, Specifier)>;
+pub(crate) type OssifiedOpDir = BTreeMap<OrderedOpDirKey, (usize, Specifier)>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum DBRef {
+pub(crate) enum DBRef {
NamedPred(ClauseName, usize, Option<SharedOpDesc>),
Op(
usize,
// 7.2
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
-pub enum TermOrderCategory {
+pub(crate) enum TermOrderCategory {
Variable,
FloatingPoint,
Integer,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub enum Addr {
+pub(crate) enum Addr {
AttrVar(usize),
Char(char),
Con(usize),
}
#[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),
impl Addr {
#[inline]
- pub fn is_heap_bound(&self) -> bool {
+ pub(crate) fn is_heap_bound(&self) -> bool {
match self {
Addr::Char(_)
| Addr::EmptyList
}
#[inline]
- pub fn is_ref(&self) -> bool {
+ pub(crate) fn is_ref(&self) -> bool {
match self {
Addr::HeapCell(_) | Addr::StackCell(_, _) | Addr::AttrVar(_) => true,
_ => false,
}
#[inline]
- pub fn as_var(&self) -> Option<Ref> {
+ pub(crate) fn as_var(&self) -> Option<Ref> {
match self {
&Addr::AttrVar(h) => Some(Ref::AttrVar(h)),
&Addr::HeapCell(h) => Some(Ref::HeapCell(h)),
}
}
- pub fn as_constant_index(&self, machine_st: &MachineState) -> Option<Constant> {
+ pub(crate) fn as_constant_index(&self, machine_st: &MachineState) -> Option<Constant> {
match self {
&Addr::Char(c) => Some(Constant::Char(c)),
&Addr::Con(h) => match &machine_st.heap[h] {
}
}
- 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,
}
#[derive(Debug, Clone, Copy)]
-pub enum TrailRef {
+pub(crate) enum TrailRef {
Ref(Ref),
AttrVarHeapLink(usize),
AttrVarListLink(usize, usize),
}
#[derive(Debug)]
-pub enum HeapCellValue {
+pub(crate) enum HeapCellValue {
Addr(Addr),
Atom(ClauseName, Option<SharedOpDesc>),
DBRef(DBRef),
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),
}
#[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()),
}
#[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),
}
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]
-pub struct CodeIndex(pub Rc<Cell<IndexPtr>>);
+pub(crate) struct CodeIndex(pub(crate) Rc<Cell<IndexPtr>>);
impl Deref for CodeIndex {
type Target = Cell<IndexPtr>;
}
#[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<usize> {
+ pub(crate) fn local(&self) -> Option<usize> {
match self.0.get() {
IndexPtr::Index(i) => Some(i),
IndexPtr::DynamicIndex(i) => Some(i),
}
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
-pub enum REPLCodePtr {
+pub(crate) enum REPLCodePtr {
AddDiscontiguousPredicate,
AddDynamicPredicate,
AddMultifilePredicate,
}
#[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),
}
impl CodePtr {
- pub fn local(&self) -> LocalCodePtr {
+ pub(crate) fn local(&self) -> LocalCodePtr {
match self {
&CodePtr::BuiltInClause(_, ref local)
| &CodePtr::CallN(_, ref local, _)
}
#[inline]
- pub fn is_halt(&self) -> bool {
+ pub(crate) fn is_halt(&self) -> bool {
if let CodePtr::Local(LocalCodePtr::Halt) = self {
true
} else {
}
#[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
}
}
-pub type HeapVarDict = IndexMap<Rc<Var>, Addr>;
-pub type AllocVarDict = IndexMap<Rc<Var>, VarData>;
+pub(crate) type HeapVarDict = IndexMap<Rc<Var>, Addr>;
+pub(crate) type AllocVarDict = IndexMap<Rc<Var>, VarData>;
-pub type GlobalVarDir = IndexMap<ClauseName, (Ball, Option<Addr>)>;
+pub(crate) type GlobalVarDir = IndexMap<ClauseName, (Ball, Option<Addr>)>;
pub(crate) type StreamAliasDir = IndexMap<ClauseName, Stream>;
pub(crate) type StreamDir = BTreeSet<Stream>;
-pub type MetaPredicateDir = IndexMap<PredicateKey, Vec<MetaSpec>>;
+pub(crate) type MetaPredicateDir = IndexMap<PredicateKey, Vec<MetaSpec>>;
-pub type ExtensiblePredicates = IndexMap<PredicateKey, PredicateSkeleton>;
+pub(crate) type ExtensiblePredicates = IndexMap<PredicateKey, PredicateSkeleton>;
-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,
}
impl IndexStore {
- pub fn get_predicate_skeleton_mut(
+ pub(crate) fn get_predicate_skeleton_mut(
&mut self,
compilation_target: &CompilationTarget,
key: &PredicateKey,
}
}
- 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
}
}
}
- 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
}
}
}
- pub fn get_predicate_skeleton(
+ pub(crate) fn get_predicate_skeleton(
&self,
compilation_target: &CompilationTarget,
key: &PredicateKey,
}
}
- pub fn remove_predicate_skeleton(
+ pub(crate) fn remove_predicate_skeleton(
&mut self,
compilation_target: &CompilationTarget,
key: &PredicateKey,
) -> Option<PredicateSkeleton> {
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)
}
}
- pub fn get_predicate_code_index(
+ pub(crate) fn get_predicate_code_index(
&self,
name: ClauseName,
arity: usize,
}
}
- pub fn get_meta_predicate_spec(
+ pub(crate) fn get_meta_predicate_spec(
&self,
name: ClauseName,
arity: usize,
}
}
- 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
}
}
-pub type CodeDir = BTreeMap<PredicateKey, CodeIndex>;
+pub(crate) type CodeDir = BTreeMap<PredicateKey, CodeIndex>;
-pub enum RefOrOwned<'a, T: 'a> {
+pub(crate) enum RefOrOwned<'a, T: 'a> {
Borrowed(&'a T),
Owned(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,
{
use std::rc::Rc;
#[derive(Debug)]
-pub struct Ball {
+pub(crate) struct Ball {
pub(super) boundary: usize,
pub(super) stub: Heap,
}
}
}
-pub type Registers = Vec<Addr>;
+pub(crate) type Registers = Vec<Addr>;
#[derive(Debug, Clone, Copy)]
pub(super) enum MachineMode {
}
// #[derive(Debug)]
-pub struct MachineState {
+pub(crate) struct MachineState {
pub(crate) atom_tbl: TabledData<Atom>,
pub(super) s: HeapPtr,
pub(super) p: CodePtr,
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<Item=(&'a Rc<Var>, &'a Addr)>,
+ iter: impl Iterator<Item = (&'a Rc<Var>, &'a Addr)>,
op_dir: &OpDir,
atom_tbl: TabledData<Atom>,
) -> Vec<Addr> {
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)
}
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)
}
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)
}
}
#[inline]
- pub fn machine_flags(&self) -> MachineFlags {
+ pub(crate) fn machine_flags(&self) -> MachineFlags {
self.flags
}
}
}
- 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 {
}
&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))
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;
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;
use std::sync::atomic::AtomicBool;
#[derive(Debug)]
-pub struct MachinePolicies {
+pub(crate) struct MachinePolicies {
call_policy: Box<dyn CallPolicy>,
cut_policy: Box<dyn CutPolicy>,
}
lazy_static! {
- pub static ref INTERRUPT: AtomicBool = AtomicBool::new(false);
+ pub(crate) static ref INTERRUPT: AtomicBool = AtomicBool::new(false);
}
impl MachinePolicies {
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)));
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);
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
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,
-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]>,
}
#[derive(Debug)]
-pub struct PStrIter {
+pub(crate) struct PStrIter {
buf: *const u8,
len: usize,
}
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)> {
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(),
}
#[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<usize>) -> PStrIter {
+ pub(crate) fn range_from(&self, index: RangeFrom<usize>) -> PStrIter {
if self.len >= '\u{0}'.len_utf8() {
PStrIter::from(self.buf, self.len - '\u{0}'.len_utf8(), index.start)
} else {
}
#[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..]
}
}
}
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,
}
#[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() {
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!()
+ }
+ },
}
}
}
}
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) => {
unreachable!()
}
}
- Addr::Char(c) => {
- Some(c)
- }
- _ => {
- None
- }
+ Addr::Char(c) => Some(c),
+ _ => None,
};
if let Some(c) = opt_c {
}
#[inline]
-pub(super)
-fn compare_pstr_prefixes<'a>(
+pub(super) fn compare_pstr_prefixes<'a>(
i1: &mut HeapPStrIter<'a>,
i2: &mut HeapPStrIter<'a>,
) -> Option<Ordering> {
}
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<usize> {
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 {
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);
}
}
HasCutVariable,
}
-pub fn fold_by_str<I>(terms: I, mut term: Term, sym: ClauseName) -> Term
+pub(crate) fn fold_by_str<I>(terms: I, mut term: Term, sym: ClauseName) -> Term
where
I: DoubleEndedIterator<Item = Term>,
{
term
}
-pub fn to_op_decl(prec: usize, spec: &str, name: ClauseName) -> Result<OpDecl, CompilationError> {
+pub(crate) fn to_op_decl(
+ prec: usize,
+ spec: &str,
+ name: ClauseName,
+) -> Result<OpDecl, CompilationError> {
match spec {
"xfx" => Ok(OpDecl::new(prec, XFX, name)),
"xfy" => Ok(OpDecl::new(prec, XFY, name)),
cut_context: CutContext,
) -> Result<Rule, CompilationError> {
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();
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)
#[inline]
fn base_offset(base: *const u8) -> *const u8 {
- unsafe {
- base.offset(Self::align() as isize)
- }
+ unsafe { base.offset(Self::align() as isize) }
}
}
}
#[derive(Debug)]
-pub struct Stack {
+pub(crate) struct Stack {
buf: RawBlock<StackTraits>,
_marker: PhantomData<Addr>,
}
}
#[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::<AndFramePrelude>() + num_cells * mem::size_of::<Addr>()
}
}
}
#[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<usize> for OrFrame {
}
impl OrFrame {
- pub fn size_of(num_cells: usize) -> usize {
+ pub(crate) fn size_of(num_cells: usize) -> usize {
prelude_size::<OrFramePrelude>() + num_cells * mem::size_of::<Addr>()
}
}
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::<AndFramePrelude>() + idx * mem::size_of::<Addr>();
ptr::write(
(self.buf.top as usize + offset) as *mut Addr,
}
}
- 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::<OrFramePrelude>() + idx * mem::size_of::<Addr>();
ptr::write(
(self.buf.top as usize + offset) as *mut Addr,
}
#[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)
}
#[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)
}
#[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)
}
#[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)
}
#[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::<Addr>());
} else {
}
}
- pub fn drop_in_place(&mut self) {
+ pub(crate) fn drop_in_place(&mut self) {
self.truncate(mem::align_of::<Addr>());
debug_assert!(if self.buf.top.is_null() {
use native_tls::TlsStream;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub enum StreamType {
+pub(crate) enum StreamType {
Binary,
Text,
}
}
#[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,
}
#[derive(Debug)]
-struct InnerStream {
+pub(crate) struct InnerStream {
options: StreamOptions,
stream_inst: StreamInstance,
past_end_of_stream: bool,
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,
+ })))
}
}
impl Error for StreamError {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct StreamOptions {
- pub stream_type: StreamType,
- pub reposition: bool,
- pub alias: Option<ClauseName>,
- pub eof_action: EOFAction,
+pub(crate) struct StreamOptions {
+ pub(crate) stream_type: StreamType,
+ pub(crate) reposition: bool,
+ pub(crate) alias: Option<ClauseName>,
+ pub(crate) eof_action: EOFAction,
}
impl Default for StreamOptions {
ptr as *const u8
}
+ pub fn bytes(&self) -> Option<std::cell::Ref<Vec<u8>>> {
+ // 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
#[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,
};
#[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() {
}
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,
}
}
#[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",
}
#[inline]
- pub(crate) fn stdout() -> Self {
+ pub fn stdout() -> Self {
Stream::from_inst(StreamInstance::Stdout)
}
#[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,
}
}
#[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,
}
}
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,
)),
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,
)),
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 {
}
}
-pub struct LiveTermStream {
+pub(crate) struct LiveTermStream {
pub(super) term_queue: VecDeque<Term>,
pub(super) listing_src: ListingSource,
}
}
}
-pub struct LoadStatePayload {
+pub(crate) struct LoadStatePayload {
pub(super) term_stream: LiveTermStream,
pub(super) compilation_target: CompilationTarget,
pub(super) retraction_info: RetractionInfo,
type SubtermDeque = VecDeque<(usize, usize)>;
-pub type PrologStream = ParsingStream<Stream>;
+pub(crate) type PrologStream = ParsingStream<Stream>;
pub mod readline {
use crate::machine::streams::Stream;
const HISTORY_FILE: &'static str = ".scryer_history";
- pub fn set_prompt(value: bool) {
+ pub(crate) fn set_prompt(value: bool) {
unsafe {
PROMPT = value;
}
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() {
}
#[inline]
- pub fn input_stream(pending_input: String) -> Stream {
+ pub(crate) fn input_stream(pending_input: String) -> Stream {
Stream::from(Self::new(pending_input))
}
}
}
- pub fn peek_byte(&mut self) -> std::io::Result<u8> {
+ pub(crate) fn peek_byte(&mut self) -> std::io::Result<u8> {
set_prompt(false);
loop {
}
}
- pub fn peek_char(&mut self) -> std::io::Result<char> {
+ pub(crate) fn peek_char(&mut self) -> std::io::Result<char> {
set_prompt(false);
loop {
}
impl MachineState {
- pub fn devour_whitespace(
+ pub(crate) fn devour_whitespace(
&mut self,
mut inner: Stream,
atom_tbl: TabledData<Atom>,
result
}
- pub fn read(
+ pub(crate) fn read(
&mut self,
mut inner: Stream,
atom_tbl: TabledData<Atom>,
}
#[derive(Debug)]
-pub struct TermWriteResult {
+pub(crate) struct TermWriteResult {
pub(crate) heap_loc: usize,
pub(crate) var_dict: HeapVarDict,
}
use crate::instructions::*;
use crate::iterators::*;
-pub trait CompilationTarget<'a> {
+pub(crate) trait CompilationTarget<'a> {
type Iterator: Iterator<Item = TermRef<'a>>;
fn iter(_: &'a Term) -> Self::Iterator;
--- /dev/null
+:- use_module(library(debug)).
+:- use_module(library(format)).
+
+hello_world :- write('Hello World!'), nl.
+
+:- initialization(hello_world).
\ No newline at end of file
--- /dev/null
+/// 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::<std::path::Path>::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""));
+}