expand goals inside (\+)/1

This commit is contained in:
Mark Thom
2019-12-11 21:42:15 -07:00
parent 196784bd09
commit 02d8b1441d
14 changed files with 212 additions and 212 deletions

View File

@@ -134,33 +134,12 @@ impl CodeRepo {
);
Some(RefOrOwned::Owned(call_clause))
}
&CodePtr::CallN(arity, _, 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::DynamicTransaction(..) => None,
}
}
pub(super)
fn at_end_of_hook(&self, hook: CompileTimeHook, cp: LocalCodePtr) -> bool {
match hook {
CompileTimeHook::UserGoalExpansion | CompileTimeHook::GoalExpansion => {
let len = self.goal_expanders.len();
if len > 0 {
cp == LocalCodePtr::UserGoalExpansion(len - 1)
} else {
true
}
}
CompileTimeHook::UserTermExpansion | CompileTimeHook::TermExpansion => {
let len = self.term_expanders.len();
if len > 0 {
cp == LocalCodePtr::UserTermExpansion(len - 1)
} else {
true
}
}
}
}
}

View File

@@ -94,6 +94,7 @@ fn load_module<R: Read>(
results.and_then(|results| compile_work_impl(&mut compiler, wam, indices, results))
.or_else(|e| {
wam.indices.take_module(module_name.clone());
compiler.print_error(&e);
Err(e)
})?;

View File

@@ -80,6 +80,7 @@ impl MachineError {
],
SharedOpDesc::new(400, YFX)
));
stub.append(&mut functor!(
":",
2,

View File

@@ -236,7 +236,7 @@ impl CodeIndex {
module_name
))))
}
#[inline]
pub fn module_name(&self) -> ClauseName {
self.0.borrow().1.clone()
@@ -311,6 +311,7 @@ pub enum REPLCodePtr {
#[derive(Clone, PartialEq)]
pub enum CodePtr {
BuiltInClause(BuiltInClauseType, LocalCodePtr), // local is the successor call.
CallN(usize, LocalCodePtr, bool), // arity, local, last call.
Local(LocalCodePtr),
DynamicTransaction(DynamicTransactionType, LocalCodePtr), // the type of transaction, the return pointer.
REPL(REPLCodePtr, LocalCodePtr), // the REPL code, the return pointer.
@@ -321,6 +322,7 @@ impl CodePtr {
pub fn local(&self) -> LocalCodePtr {
match self {
&CodePtr::BuiltInClause(_, ref local)
| &CodePtr::CallN(_, ref local, _)
| &CodePtr::Local(ref local) => local.clone(),
&CodePtr::VerifyAttrInterrupt(p) => LocalCodePtr::DirEntry(p),
&CodePtr::REPL(_, p) | &CodePtr::DynamicTransaction(_, p) => p,
@@ -418,7 +420,7 @@ impl Add<usize> for CodePtr {
| p @ CodePtr::VerifyAttrInterrupt(_)
| p @ CodePtr::DynamicTransaction(..) => p,
CodePtr::Local(local) => CodePtr::Local(local + rhs),
CodePtr::BuiltInClause(_, local) => {
CodePtr::BuiltInClause(_, local) | CodePtr::CallN(_, local, _) => {
CodePtr::Local(local + rhs)
}
}
@@ -467,7 +469,7 @@ pub struct IndexStore {
pub(super) op_dir: OpDir,
}
impl IndexStore {
impl IndexStore {
pub fn predicate_exists(
&self,
name: ClauseName,
@@ -492,18 +494,18 @@ impl IndexStore {
}
pub fn add_term_and_goal_expansion_indices(&mut self) {
self.code_dir.insert((clause_name!("term_expansion"), 2),
self.code_dir.insert((clause_name!("term_expansion"), 2),
CodeIndex(Rc::new(RefCell::new(
(IndexPtr::UserTermExpansion,
clause_name!("user"))
))));
self.code_dir.insert((clause_name!("goal_expansion"), 2),
self.code_dir.insert((clause_name!("goal_expansion"), 2),
CodeIndex(Rc::new(RefCell::new(
(IndexPtr::UserGoalExpansion,
clause_name!("user"))
))));
}
#[inline]
pub fn remove_clause_subsection(&mut self, module: ClauseName, name: ClauseName, arity: usize) {
self.dynamic_code_dir.swap_remove(&(module, name, arity));

View File

@@ -261,7 +261,7 @@ pub struct MachineState {
pub(super) last_call: bool,
pub(crate) heap_locs: HeapVarDict,
pub(crate) flags: MachineFlags,
pub(crate) at_end_of_expansion: LocalCodePtr
pub(crate) at_end_of_expansion: bool
}
impl MachineState {
@@ -865,39 +865,49 @@ pub(crate) trait CallPolicy: Any {
fn call_n(
&mut self,
machine_st: &mut MachineState,
name: ClauseName,
arity: usize,
indices: &mut IndexStore,
parsing_stream: &mut PrologStream,
) -> CallResult {
match ClauseType::from(name.clone(), arity, None) {
ClauseType::BuiltIn(built_in) => {
machine_st.setup_built_in_call(built_in.clone());
self.call_builtin(machine_st, &built_in, indices, parsing_stream)?;
}
ClauseType::Inlined(inlined) => {
machine_st.execute_inlined(&inlined);
if machine_st.last_call {
machine_st.p = CodePtr::Local(machine_st.cp);
if let Some((name, arity)) = machine_st.setup_call_n(arity) {
match ClauseType::from(name.clone(), arity, None) {
ClauseType::BuiltIn(built_in) => {
machine_st.setup_built_in_call(built_in.clone());
self.call_builtin(machine_st, &built_in, indices, parsing_stream)?;
}
}
ClauseType::Op(..) | ClauseType::Named(..) => {
let module = name.owning_module();
ClauseType::CallN => {
machine_st.handle_internal_call_n(arity);
if let Some(idx) = indices.get_code_index((name.clone(), arity), module) {
self.context_call(machine_st, name, arity, idx, indices)?;
} else {
try_in_situ(machine_st, name, arity, indices, machine_st.last_call)?;
if machine_st.fail {
return Ok(());
}
machine_st.p = CodePtr::CallN(arity, machine_st.p.local(), machine_st.last_call);
}
}
ClauseType::Hook(_) | ClauseType::System(_) => {
let name = Addr::Con(Constant::Atom(name, None));
let stub = MachineError::functor_stub(clause_name!("call"), arity + 1);
ClauseType::Inlined(inlined) => {
machine_st.execute_inlined(&inlined);
return Err(machine_st
.error_form(MachineError::type_error(ValidType::Callable, name), stub));
}
if machine_st.last_call {
machine_st.p = CodePtr::Local(machine_st.cp);
}
}
ClauseType::Op(..) | ClauseType::Named(..) => {
let module = name.owning_module();
if let Some(idx) = indices.get_code_index((name.clone(), arity), module) {
self.context_call(machine_st, name, arity, idx, indices)?;
} else {
try_in_situ(machine_st, name, arity, indices, machine_st.last_call)?;
}
}
ClauseType::Hook(_) | ClauseType::System(_) => {
let name = Addr::Con(Constant::Atom(name, None));
let stub = MachineError::functor_stub(clause_name!("call"), arity + 1);
return Err(machine_st
.error_form(MachineError::type_error(ValidType::Callable, name), stub));
}
};
}
Ok(())
@@ -953,13 +963,12 @@ impl CallPolicy for CWILCallPolicy {
fn call_n(
&mut self,
machine_st: &mut MachineState,
name: ClauseName,
arity: usize,
indices: &mut IndexStore,
parsing_stream: &mut PrologStream,
) -> CallResult {
self.prev_policy
.call_n(machine_st, name, arity, indices, parsing_stream)?;
.call_n(machine_st, arity, indices, parsing_stream)?;
self.increment(machine_st)
}
}

View File

@@ -75,7 +75,7 @@ impl MachineState {
last_call: false,
heap_locs: HeapVarDict::new(),
flags: MachineFlags::default(),
at_end_of_expansion: LocalCodePtr::TopLevel(0, 0),
at_end_of_expansion: false
}
}
@@ -106,7 +106,7 @@ impl MachineState {
last_call: false,
heap_locs: HeapVarDict::new(),
flags: MachineFlags::default(),
at_end_of_expansion: LocalCodePtr::TopLevel(0, 0),
at_end_of_expansion: false
}
}
@@ -2003,6 +2003,75 @@ impl MachineState {
);
}
pub(super) fn handle_internal_call_n(&mut self, arity: usize) {
let arity = arity + 1;
let pred = self.registers[1].clone();
for i in 2..arity {
self.registers[i - 1] = self.registers[i].clone();
}
if arity > 1 {
self.registers[arity - 1] = pred;
return;
}
self.fail = true;
}
pub(super) fn setup_call_n(&mut self, arity: usize) -> Option<PredicateKey> {
let stub = MachineError::functor_stub(clause_name!("call"), arity + 1);
let addr = self.store(self.deref(self.registers[arity].clone()));
let (name, narity) = match addr {
Addr::Str(a) => {
let result = self.heap[a].clone();
if let HeapCellValue::NamedStr(narity, name, _) = result {
if narity + arity > 63 {
let representation_error = self.error_form(
MachineError::representation_error(RepFlag::MaxArity),
stub,
);
self.throw_exception(representation_error);
return None;
}
for i in (1 .. arity).rev() {
self.registers[i + narity] = self.registers[i].clone();
}
for i in 1 .. narity + 1 {
self.registers[i] = self.heap[a + i].as_addr(a + i);
}
(name, narity)
} else {
self.fail = true;
return None;
}
}
Addr::Con(Constant::Atom(name, _)) => (name, 0),
Addr::HeapCell(_) | Addr::StackCell(_, _) => {
let instantiation_error =
self.error_form(MachineError::instantiation_error(), stub);
self.throw_exception(instantiation_error);
return None;
}
_ => {
let type_error =
self.error_form(MachineError::type_error(ValidType::Callable, addr), stub);
self.throw_exception(type_error);
return None;
}
};
Some((name, arity + narity - 1))
}
pub(super) fn unwind_stack(&mut self) {
self.b = self.block;
self.truncate_stack();
@@ -3087,6 +3156,10 @@ impl MachineState {
self,
call_policy.call_builtin(self, ct, indices, parsing_stream)
),
&ClauseType::CallN => try_or_fail!(
self,
call_policy.call_n(self, arity, indices, parsing_stream)
),
&ClauseType::Hook(ref hook) => try_or_fail!(self, call_policy.compile_hook(self, hook)),
&ClauseType::Inlined(ref ct) => {
self.execute_inlined(ct);
@@ -3304,7 +3377,6 @@ impl MachineState {
self.mode = MachineMode::Write;
self.registers = vec![Addr::HeapCell(0); MAX_ARITY + 1]; // self.registers[0] is never used.
self.block = 0;
self.at_end_of_expansion = LocalCodePtr::TopLevel(0, 0);
self.ball.reset();
self.heap_locs.clear();

View File

@@ -619,7 +619,9 @@ impl MachineState {
return Ok(());
}
&SystemClauseType::AtEndOfExpansion => {
self.at_end_of_expansion = self.p.local();
if self.cp == LocalCodePtr::TopLevel(0, 0) {
self.at_end_of_expansion = true;
}
}
&SystemClauseType::AtomChars => {
let a1 = self[temp_v!(1)].clone();
@@ -763,64 +765,6 @@ impl MachineState {
return Ok(());
}
&SystemClauseType::CallN => {
let (name, arity) = match self.store(self.deref(self[temp_v!(1)].clone())) {
Addr::Str(a) => {
let result = self.heap[a].clone();
if let HeapCellValue::NamedStr(arity, name, _) = result {
if arity > MAX_ARITY {
let stub = MachineError::functor_stub(
clause_name!("$call"),
1,
);
return Err(self.error_form(
MachineError::representation_error(RepFlag::MaxArity),
stub,
));
}
for i in 1 .. arity + 1 {
self.registers[i] = self.heap[a + i].as_addr(a + i);
}
(name, arity)
} else {
unreachable!()
}
}
Addr::Con(Constant::Atom(name, _)) =>
(name, 0),
Addr::HeapCell(_) | Addr::StackCell(_, _) => {
let stub = MachineError::functor_stub(
clause_name!("$call"),
1,
);
return Err(self.error_form(MachineError::instantiation_error(), stub));
}
addr => {
let stub = MachineError::functor_stub(
clause_name!("$call"),
1,
);
return Err(self.error_form(
MachineError::type_error(ValidType::Callable, addr),
stub,
));
}
};
return call_policy.call_n(
self,
name,
arity,
indices,
current_input_stream,
);
}
&SystemClauseType::CharsToNumber => {
let stub = MachineError::functor_stub(clause_name!("number_chars"), 2);
@@ -1673,6 +1617,16 @@ impl MachineState {
}
};
}
&SystemClauseType::ModuleExists => {
let module = self.store(self.deref(self[temp_v!(1)].clone()));
match module {
Addr::Con(Constant::Atom(ref name, _)) => {
self.fail = !indices.modules.contains_key(name);
}
_ => unreachable!()
};
}
&SystemClauseType::ModuleOf => {
let module = self.store(self.deref(self[temp_v!(2)].clone()));

View File

@@ -365,7 +365,7 @@ impl MachineState {
wam.code_repo.cached_query = code;
self.cp = LocalCodePtr::TopLevel(0, 0);
self.at_end_of_expansion = self.cp;
self.at_end_of_expansion = false;
self.query_stepper(
&mut wam.indices,
@@ -374,7 +374,7 @@ impl MachineState {
&mut readline::input_stream(),
);
if self.fail || wam.code_repo.at_end_of_hook(hook, self.at_end_of_expansion) {
if self.fail || self.at_end_of_expansion {
self.reset_with_heap_preservation();
None
} else {

View File

@@ -678,6 +678,26 @@ impl RelationWorker {
self.queue.push_back(clauses);
Ok(QueryTerm::Jump(stub))
}
("\\+", 1) => {
terms.push(Box::new(Term::Constant(
Cell::default(),
Constant::Atom(clause_name!("$fail"), None)
)));
let conq = Term::Constant(
Cell::default(),
Constant::Atom(clause_name!("true"), None)
);
let prec = Term::Clause(Cell::default(), clause_name!("->"), terms, None);
let terms = vec![Box::new(prec), Box::new(conq)];
let term = Term::Clause(Cell::default(), clause_name!(";"), terms, None);
let (stub, clauses) = self.fabricate_disjunct(term);
self.queue.push_back(clauses);
Ok(QueryTerm::Jump(stub))
}
("$get_level", 1) => {
if let Term::Var(_, ref var) = *terms[0] {
Ok(QueryTerm::GetLevelAndUnify(Cell::default(), var.clone()))
@@ -694,10 +714,12 @@ impl RelationWorker {
Ok(QueryTerm::Clause(Cell::default(), ct, terms, false))
}
}
arg @ Term::Var(..) => {
let ct = ClauseType::Named(clause_name!("call"), 1, CodeIndex::default());
Ok(QueryTerm::Clause(Cell::default(), ct, vec![Box::new(arg)], false))
}
Term::Var(..) => Ok(QueryTerm::Clause(
Cell::default(),
ClauseType::CallN,
vec![Box::new(term)],
false,
)),
_ => Err(ParserError::InadmissibleQueryTerm),
}
}