Resolve lints and format

This commit is contained in:
infogulch
2023-11-04 02:16:54 -05:00
parent dddffb01a6
commit 9444e62df9
58 changed files with 2521 additions and 2820 deletions

View File

@@ -14,3 +14,9 @@ impl MachineArgs {
}
}
}
impl Default for MachineArgs {
fn default() -> Self {
Self::new()
}
}

View File

@@ -1,6 +1,6 @@
use dashu::base::{Abs, Gcd, Signed, UnsignedAbs};
use dashu::integer::IBig;
use dashu::integer::fast_div::ConstDivisor;
use dashu::integer::IBig;
use divrem::*;
use num_order::NumOrd;
@@ -84,18 +84,18 @@ fn numerical_type_error(
fn isize_gcd(n1: isize, n2: isize) -> Option<isize> {
if n1 == 0 {
return n2.checked_abs().map(|n| n as isize);
return n2.checked_abs();
}
if n2 == 0 {
return n1.checked_abs().map(|n| n as isize);
return n1.checked_abs();
}
let n1 = n1.checked_abs();
let n2 = n2.checked_abs();
let mut n1 = if let Some(n1) = n1 { n1 } else { return None };
let mut n2 = if let Some(n2) = n2 { n2 } else { return None };
let mut n1 = n1?;
let mut n2 = n2?;
let mut shift = 0;
@@ -115,9 +115,7 @@ fn isize_gcd(n1: isize, n2: isize) -> Option<isize> {
}
if n1 > n2 {
let t = n2;
n2 = n1;
n1 = t;
std::mem::swap(&mut n2, &mut n1);
}
n2 -= n1;
@@ -350,22 +348,18 @@ pub(crate) fn int_pow(n1: Number, n2: Number, arena: &mut Arena) -> Result<Numbe
(Number::Fixnum(n1), Number::Integer(n2)) => {
let n1_i = n1.get_num();
if !(n1_i == 1 || n1_i == 0 || n1_i == -1) && &*n2 < &Integer::from(0) {
if !(n1_i == 1 || n1_i == 0 || n1_i == -1) && n2.is_zero() {
let n = Number::Fixnum(n1);
Err(numerical_type_error(ValidType::Float, n, stub_gen))
} else {
let n1 = Integer::from(n1_i);
Ok(Number::arena_from(binary_pow(n1, &*n2), arena))
Ok(Number::arena_from(binary_pow(n1, &n2), arena))
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => {
let n2_i = n2.get_num();
if !(&*n1 == &Integer::from(1)
|| &*n1 == &Integer::from(0)
|| &*n1 == &Integer::from(-1))
&& n2_i < 0
{
if !(*n1 == Integer::from(1) || n1.is_zero() || *n1 == Integer::from(-1)) && n2_i < 0 {
let n = Number::Integer(n1);
Err(numerical_type_error(ValidType::Float, n, stub_gen))
} else {
@@ -374,15 +368,13 @@ pub(crate) fn int_pow(n1: Number, n2: Number, arena: &mut Arena) -> Result<Numbe
}
}
(Number::Integer(n1), Number::Integer(n2)) => {
if !(&*n1 == &Integer::from(1)
|| &*n1 == &Integer::from(0)
|| &*n1 == &Integer::from(-1))
&& &*n2 < &Integer::from(0)
if !(*n1 == Integer::from(1) || n1.is_zero() || *n1 == Integer::from(-1))
&& n2.is_zero()
{
let n = Number::Integer(n1);
Err(numerical_type_error(ValidType::Float, n, stub_gen))
} else {
Ok(Number::arena_from(binary_pow((*n1).clone(), &*n2), arena))
Ok(Number::arena_from(binary_pow((*n1).clone(), &n2), arena))
}
}
(n1, Number::Integer(n2)) => {
@@ -455,14 +447,14 @@ pub(crate) fn max(n1: Number, n2: Number) -> Result<Number, MachineStubGen> {
}
}
(Number::Fixnum(n1), Number::Integer(n2)) => {
if (&*n2).num_gt(&n1.get_num()) {
if (*n2).num_gt(&n1.get_num()) {
Ok(Number::Integer(n2))
} else {
Ok(Number::Fixnum(n1))
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => {
if (&*n1).num_gt(&n2.get_num()) {
if (*n1).num_gt(&n2.get_num()) {
Ok(Number::Integer(n1))
} else {
Ok(Number::Fixnum(n2))
@@ -499,14 +491,14 @@ pub(crate) fn min(n1: Number, n2: Number) -> Result<Number, MachineStubGen> {
}
}
(Number::Fixnum(n1), Number::Integer(n2)) => {
if (&*n2).num_lt(&n1.get_num()) {
if (*n2).num_lt(&n1.get_num()) {
Ok(Number::Integer(n2))
} else {
Ok(Number::Fixnum(n1))
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => {
if (&*n1).num_lt(&n2.get_num()) {
if (*n1).num_lt(&n2.get_num()) {
Ok(Number::Integer(n1))
} else {
Ok(Number::Fixnum(n2))
@@ -583,15 +575,13 @@ pub(crate) fn idiv(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number,
(Number::Fixnum(n1), Number::Fixnum(n2)) => {
if n2.get_num() == 0 {
Err(zero_divisor_eval_error(stub_gen))
} else if let Some(result) = n1.get_num().checked_div(n2.get_num()) {
Ok(Number::arena_from(result, arena))
} else {
if let Some(result) = n1.get_num().checked_div(n2.get_num()) {
Ok(Number::arena_from(result, arena))
} else {
let n1 = Integer::from(n1.get_num());
let n2 = Integer::from(n2.get_num());
let n1 = Integer::from(n1.get_num());
let n2 = Integer::from(n2.get_num());
Ok(Number::arena_from(n1 / n2, arena))
}
Ok(Number::arena_from(n1 / n2, arena))
}
}
(Number::Fixnum(n1), Number::Integer(n2)) => {
@@ -656,9 +646,9 @@ pub(crate) fn shr(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
let n1 = Integer::from(n1_i);
if let Ok(n2) = usize::try_from(n2_i) {
return Ok(Number::arena_from(n1 >> n2, arena));
Ok(Number::arena_from(n1 >> n2, arena))
} else {
return Ok(Number::arena_from(n1 >> usize::max_value(), arena));
Ok(Number::arena_from(n1 >> usize::max_value(), arena))
}
}
(Number::Fixnum(n1), Number::Integer(n2)) => {
@@ -667,12 +657,8 @@ pub(crate) fn shr(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
let result: Result<usize, _> = (&*n2).try_into();
match result {
Ok(n2) => {
Ok(Number::arena_from(n1 >> n2, arena))
}
Err(_) => {
Ok(Number::arena_from(n1 >> usize::max_value(), arena))
}
Ok(n2) => Ok(Number::arena_from(n1 >> n2, arena)),
Err(_) => Ok(Number::arena_from(n1 >> usize::max_value(), arena)),
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => match usize::try_from(n2.get_num()) {
@@ -686,14 +672,13 @@ pub(crate) fn shr(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
let result: Result<usize, _> = (&*n2).try_into();
match result {
Ok(n2) => {
Ok(Number::arena_from(Integer::from(&*n1 >> n2), arena))
}
Err(_) => {
Ok(Number::arena_from(Integer::from(&*n1 >> usize::max_value()), arena))
}
Ok(n2) => Ok(Number::arena_from(Integer::from(&*n1 >> n2), arena)),
Err(_) => Ok(Number::arena_from(
Integer::from(&*n1 >> usize::max_value()),
arena,
)),
}
},
}
(Number::Integer(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
(Number::Fixnum(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
(n1, _) => Err(numerical_type_error(ValidType::Integer, n1, stub_gen)),
@@ -718,9 +703,9 @@ pub(crate) fn shl(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
let n1 = Integer::from(n1_i);
if let Ok(n2) = usize::try_from(n2_i) {
return Ok(Number::arena_from(n1 << n2, arena));
Ok(Number::arena_from(n1 << n2, arena))
} else {
return Ok(Number::arena_from(n1 << usize::max_value(), arena));
Ok(Number::arena_from(n1 << usize::max_value(), arena))
}
}
(Number::Fixnum(n1), Number::Integer(n2)) => {
@@ -730,10 +715,8 @@ pub(crate) fn shl(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
Ok(n2) => {
let n1: u64 = n1.try_into().unwrap();
Ok(Number::arena_from(n1 << n2, arena))
},
_ => {
Ok(Number::arena_from(n1 << usize::max_value(), arena))
}
}
_ => Ok(Number::arena_from(n1 << usize::max_value(), arena)),
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => match usize::try_from(n2.get_num()) {
@@ -747,10 +730,11 @@ pub(crate) fn shl(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
Ok(n2) => {
let n1: u64 = (&*n1).try_into().unwrap();
Ok(Number::arena_from(Integer::from(n1 << n2), arena))
},
_ => {
Ok(Number::arena_from(Integer::from(&*n1 << usize::max_value()),arena))
}
}
_ => Ok(Number::arena_from(
Integer::from(&*n1 << usize::max_value()),
arena,
)),
},
(Number::Integer(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
(Number::Fixnum(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
@@ -882,7 +866,7 @@ pub(crate) fn modulus(x: Number, y: Number, arena: &mut Arena) -> Result<Number,
Err(zero_divisor_eval_error(stub_gen))
} else {
let n1 = Integer::from(n1.get_num());
Ok(Number::arena_from(ibig_rem_floor(&n1, &*n2), arena))
Ok(Number::arena_from(ibig_rem_floor(&n1, &n2), arena))
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => {
@@ -892,14 +876,14 @@ pub(crate) fn modulus(x: Number, y: Number, arena: &mut Arena) -> Result<Number,
Err(zero_divisor_eval_error(stub_gen))
} else {
let n2 = Integer::from(n2_i);
Ok(Number::arena_from(ibig_rem_floor(&*n1, &n2), arena))
Ok(Number::arena_from(ibig_rem_floor(&n1, &n2), arena))
}
}
(Number::Integer(n1), Number::Integer(n2)) => {
if n2.is_zero() {
Err(zero_divisor_eval_error(stub_gen))
} else {
Ok(Number::arena_from(ibig_rem_floor(&*n1, &*n2), arena))
Ok(Number::arena_from(ibig_rem_floor(&n1, &n2), arena))
}
}
(Number::Integer(_), n2) | (Number::Fixnum(_), n2) => {
@@ -1145,7 +1129,7 @@ impl MachineState {
&mut self.interms[i - 1],
Number::Fixnum(Fixnum::build_with(0)),
)),
&ArithmeticTerm::Number(n) => Ok(n),
ArithmeticTerm::Number(n) => Ok(*n),
}
}
@@ -1167,8 +1151,8 @@ impl MachineState {
value: HeapCellValue,
) -> Result<Number, MachineStub> {
let stub_gen = || functor_stub(atom!("is"), 2);
let mut iter = stackful_post_order_iter::<NonListElider>
(&mut self.heap, &mut self.stack, value);
let mut iter =
stackful_post_order_iter::<NonListElider>(&mut self.heap, &mut self.stack, value);
while let Some(value) = iter.next() {
if value.get_forwarding_bit() {

View File

@@ -133,8 +133,8 @@ impl MachineState {
let mut seen_set = IndexSet::new();
let mut seen_vars = vec![];
let mut iter = stackful_preorder_iter::<NonListElider>
(&mut self.heap, &mut self.stack, cell);
let mut iter =
stackful_preorder_iter::<NonListElider>(&mut self.heap, &mut self.stack, cell);
while let Some(value) = iter.next() {
read_heap_cell!(value,

View File

@@ -282,28 +282,25 @@ fn merge_indexed_subsequences(
.unwrap(),
);
match &mut code[inner_try_me_else_loc] {
Instruction::TryMeElse(ref mut o) => {
retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(
inner_try_me_else_loc,
*o,
));
if let Instruction::TryMeElse(ref mut o) = &mut code[inner_try_me_else_loc] {
retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(
inner_try_me_else_loc,
*o,
));
match *o {
0 => {
code[inner_try_me_else_loc] = Instruction::TrustMe(0);
}
o => match &code[inner_try_me_else_loc + o] {
Instruction::RevJmpBy(0) => {
code[inner_try_me_else_loc] = Instruction::TrustMe(o);
}
_ => {
code[inner_try_me_else_loc] = Instruction::RetryMeElse(o);
}
},
match *o {
0 => {
code[inner_try_me_else_loc] = Instruction::TrustMe(0);
}
o => match &code[inner_try_me_else_loc + o] {
Instruction::RevJmpBy(0) => {
code[inner_try_me_else_loc] = Instruction::TrustMe(o);
}
_ => {
code[inner_try_me_else_loc] = Instruction::RetryMeElse(o);
}
},
}
_ => {}
}
thread_choice_instr_at_to(
@@ -333,8 +330,8 @@ fn merge_indexed_subsequences(
retraction_info,
);
}
None => match &mut code[outer_threaded_choice_instr_loc] {
Instruction::TryMeElse(ref mut o) => {
None => {
if let Instruction::TryMeElse(ref mut o) = &mut code[outer_threaded_choice_instr_loc] {
retraction_info
.push_record(RetractionRecord::ModifiedTryMeElse(inner_trust_me_loc, *o));
@@ -342,8 +339,7 @@ fn merge_indexed_subsequences(
return Some(IndexPtr::index(outer_threaded_choice_instr_loc + 1));
}
_ => {}
},
}
}
None
@@ -919,7 +915,7 @@ fn prepend_compiled_clause(
retraction_info,
);
code.extend(prepend_queue.into_iter());
code.extend(prepend_queue);
if skeleton.core.is_dynamic {
clause_loc
@@ -975,7 +971,7 @@ fn prepend_compiled_clause(
internalize_choice_instr_at(code, old_clause_start, retraction_info);
code.extend(prepend_queue.into_iter());
code.extend(prepend_queue);
clause_loc // + (outer_thread_choice_offset == 0 as usize)
}
@@ -1004,7 +1000,7 @@ fn prepend_compiled_clause(
internalize_choice_instr_at(code, old_clause_start, retraction_info);
code.extend(prepend_queue.into_iter());
code.extend(prepend_queue);
// skeleton.clauses[0].opt_arg_index_key += clause_loc;
skeleton.clauses[0].clause_start = clause_loc;
@@ -1029,7 +1025,7 @@ fn prepend_compiled_clause(
internalize_choice_instr_at(code, old_clause_start, retraction_info);
code.extend(prepend_queue.into_iter());
code.extend(prepend_queue);
// skeleton.clauses[0].opt_arg_index_key += clause_loc;
skeleton.clauses[0].clause_start = clause_loc;
@@ -1134,21 +1130,18 @@ fn append_compiled_clause(
skeleton.clauses[target_pos].opt_arg_index_key += clause_loc;
code.extend(clause_code.drain(1..));
match skeleton.clauses[target_pos]
if let Some(index_loc) = skeleton.clauses[target_pos]
.opt_arg_index_key
.switch_on_term_loc()
{
Some(index_loc) => {
// point to the inner-threaded TryMeElse(0) if target_pos is
// indexed, and make switch_on_term point one line after it in
// its variable offset.
skeleton.clauses[target_pos].clause_start += 2;
// point to the inner-threaded TryMeElse(0) if target_pos is
// indexed, and make switch_on_term point one line after it in
// its variable offset.
skeleton.clauses[target_pos].clause_start += 2;
if !skeleton.core.is_dynamic {
set_switch_var_offset(code, index_loc, 2, retraction_info);
}
if !skeleton.core.is_dynamic {
set_switch_var_offset(code, index_loc, 2, retraction_info);
}
None => {}
}
match skeleton.clauses[lower_bound]
@@ -1302,11 +1295,8 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
clause_clause_locs.push_back(clause_index_info.clause_start);
}
match &mut code[0] {
Instruction::TryMeElse(0) => {
code_ptr += 1;
}
_ => {}
if let Instruction::TryMeElse(0) = &mut code[0] {
code_ptr += 1;
}
match self
@@ -1317,7 +1307,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
Some(skeleton) => {
let skeleton_clause_len = skeleton.clauses.len();
skeleton.clauses.extend(cg.skeleton.clauses.into_iter());
skeleton.clauses.extend(cg.skeleton.clauses);
skeleton
.core
.clause_clause_locs
@@ -1371,7 +1361,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
index_ptr,
);
self.wam_prelude.code.extend(code.into_iter());
self.wam_prelude.code.extend(code);
Ok(code_index)
}
@@ -1563,7 +1553,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
let global_clock = LS::machine_st(&mut self.payload).global_clock;
let result = append_compiled_clause(
&mut self.wam_prelude.code,
self.wam_prelude.code,
clause_code,
skeleton,
&mut self.payload.retraction_info,
@@ -1603,7 +1593,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
let global_clock = LS::machine_st(&mut self.payload).global_clock;
let new_code_ptr = prepend_compiled_clause(
&mut self.wam_prelude.code,
self.wam_prelude.code,
compilation_target,
key,
clause_code,
@@ -1646,7 +1636,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
.switch_on_term_loc()
{
Some(index_loc) => find_inner_choice_instr(
&self.wam_prelude.code,
self.wam_prelude.code,
skeleton.clauses[target_pos].clause_start,
index_loc,
),
@@ -1687,115 +1677,109 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
if target_pos == 0 || (lower_bound + 1 == target_pos && lower_bound_is_unindexed) {
// the clause preceding target_pos, if there is one, is of
// key type OptArgIndexKey::None.
match skeleton.clauses[target_pos]
if let Some(index_loc) = skeleton.clauses[target_pos]
.opt_arg_index_key
.switch_on_term_loc()
{
Some(index_loc) => {
let inner_clause_start = find_inner_choice_instr(
code,
skeleton.clauses[target_pos].clause_start,
index_loc,
);
let inner_clause_start = find_inner_choice_instr(
code,
skeleton.clauses[target_pos].clause_start,
index_loc,
);
remove_index_from_subsequence(
code,
&skeleton.clauses[target_pos].opt_arg_index_key,
inner_clause_start,
&mut self.payload.retraction_info,
);
remove_index_from_subsequence(
code,
&skeleton.clauses[target_pos].opt_arg_index_key,
inner_clause_start,
&mut self.payload.retraction_info,
);
match derelictize_try_me_else(
code,
inner_clause_start,
&mut self.payload.retraction_info,
) {
Some(offset) => {
let instr_loc = find_inner_choice_instr(
code,
inner_clause_start + offset,
index_loc,
);
match derelictize_try_me_else(
code,
inner_clause_start,
&mut self.payload.retraction_info,
) {
Some(offset) => {
let instr_loc =
find_inner_choice_instr(code, inner_clause_start + offset, index_loc);
let clause_loc = blunt_leading_choice_instr(
code,
instr_loc,
&mut self.payload.retraction_info,
);
let clause_loc = blunt_leading_choice_instr(
code,
instr_loc,
&mut self.payload.retraction_info,
);
set_switch_var_offset(
code,
index_loc,
clause_loc - index_loc,
&mut self.payload.retraction_info,
);
set_switch_var_offset(
code,
index_loc,
clause_loc - index_loc,
&mut self.payload.retraction_info,
);
self.payload.retraction_info.push_record(
RetractionRecord::SkeletonClauseStartReplaced(
payload_compilation_target,
key,
target_pos + 1,
skeleton.clauses[target_pos + 1].clause_start,
),
);
skeleton.clauses[target_pos + 1].clause_start =
skeleton.clauses[target_pos].clause_start;
let update_code_index = target_pos == 0
&& skeleton.clauses[target_pos + 1]
.opt_arg_index_key
.switch_on_term_loc()
.is_none();
let index_ptr_opt = if update_code_index {
Some(IndexPtr::index(clause_loc))
} else {
None
};
return finalize_retract(
key,
self.payload.retraction_info.push_record(
RetractionRecord::SkeletonClauseStartReplaced(
payload_compilation_target,
skeleton,
code_index,
target_pos,
index_ptr_opt,
&mut self.payload.retraction_info,
);
}
None => {
let index_ptr_opt = if target_pos > 0 {
let preceding_choice_instr_loc =
skeleton.clauses[target_pos - 1].clause_start;
remove_non_leading_clause(
code,
preceding_choice_instr_loc,
skeleton.clauses[target_pos].clause_start - 2,
&mut self.payload.retraction_info,
)
} else {
remove_leading_unindexed_clause(
code,
skeleton.clauses[target_pos].clause_start - 2,
&mut self.payload.retraction_info,
)
};
return finalize_retract(
key,
payload_compilation_target,
skeleton,
code_index,
target_pos,
index_ptr_opt,
target_pos + 1,
skeleton.clauses[target_pos + 1].clause_start,
),
);
skeleton.clauses[target_pos + 1].clause_start =
skeleton.clauses[target_pos].clause_start;
let update_code_index = target_pos == 0
&& skeleton.clauses[target_pos + 1]
.opt_arg_index_key
.switch_on_term_loc()
.is_none();
let index_ptr_opt = if update_code_index {
Some(IndexPtr::index(clause_loc))
} else {
None
};
return finalize_retract(
key,
payload_compilation_target,
skeleton,
code_index,
target_pos,
index_ptr_opt,
&mut self.payload.retraction_info,
);
}
None => {
let index_ptr_opt = if target_pos > 0 {
let preceding_choice_instr_loc =
skeleton.clauses[target_pos - 1].clause_start;
remove_non_leading_clause(
code,
preceding_choice_instr_loc,
skeleton.clauses[target_pos].clause_start - 2,
&mut self.payload.retraction_info,
);
}
)
} else {
remove_leading_unindexed_clause(
code,
skeleton.clauses[target_pos].clause_start - 2,
&mut self.payload.retraction_info,
)
};
return finalize_retract(
key,
payload_compilation_target,
skeleton,
code_index,
target_pos,
index_ptr_opt,
&mut self.payload.retraction_info,
);
}
}
None => {}
}
}
@@ -1824,16 +1808,13 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
Instruction::RevJmpBy(target_indexing_loc - later_indexing_loc),
);
match target_indexing_line {
Instruction::IndexingCode(indexing_code) => {
self.payload.retraction_info.push_record(
RetractionRecord::ReplacedIndexingLine(
target_indexing_loc,
indexing_code,
),
);
}
_ => {}
if let Instruction::IndexingCode(indexing_code) = target_indexing_line {
self.payload.retraction_info.push_record(
RetractionRecord::ReplacedIndexingLine(
target_indexing_loc,
indexing_code,
),
);
}
result = merge_indexed_subsequences(
@@ -1977,16 +1958,15 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
&mut self.payload.retraction_info,
);
match &mut code[preceding_choice_instr_loc] {
Instruction::TryMeElse(0) => {
set_switch_var_offset(
code,
index_loc,
preceding_choice_instr_loc + 1 - index_loc,
&mut self.payload.retraction_info,
);
}
_ => {}
if let Instruction::TryMeElse(0) =
&mut code[preceding_choice_instr_loc]
{
set_switch_var_offset(
code,
index_loc,
preceding_choice_instr_loc + 1 - index_loc,
&mut self.payload.retraction_info,
);
}
}
}
@@ -2068,16 +2048,11 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
{
Some(skeleton) if append_or_prepend.is_append() => {
let tail_num = skeleton.core.clause_clause_locs.len() - num_clause_predicates;
skeleton.core.clause_clause_locs.make_contiguous()[tail_num..]
.iter()
.cloned()
.collect()
skeleton.core.clause_clause_locs.make_contiguous()[tail_num..].to_vec()
}
Some(skeleton) => skeleton.core.clause_clause_locs.make_contiguous()
[0..num_clause_predicates]
.iter()
.cloned()
.collect(),
.to_vec(),
None => {
unreachable!()
}
@@ -2205,46 +2180,47 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
)?;
}
} else {
if is_cross_module_clause {
if !local_predicate_info.is_extensible {
if predicate_info.is_multifile {
println!(
"Warning: overwriting multifile predicate {}:{}/{} because \
it was not locally declared multifile.",
self.payload.predicates.compilation_target,
key.0.as_str(),
key.1
if is_cross_module_clause && !local_predicate_info.is_extensible {
if predicate_info.is_multifile {
println!(
"Warning: overwriting multifile predicate {}:{}/{} because \
it was not locally declared multifile.",
self.payload.predicates.compilation_target,
key.0.as_str(),
key.1
);
}
if let Some(skeleton) = self
.wam_prelude
.indices
.remove_predicate_skeleton(&self.payload.predicates.compilation_target, &key)
{
let compilation_target = self.payload.predicates.compilation_target;
if predicate_info.is_dynamic {
let clause_clause_compilation_target = match compilation_target {
CompilationTarget::User => CompilationTarget::Module(atom!("builtins")),
module => module,
};
self.retract_local_clauses_by_locs(
clause_clause_compilation_target,
(atom!("$clause"), 2),
(0..skeleton.clauses.len()).map(Some).collect(),
false, // the builtin M:'$clause'/2 is never dynamic.
);
predicate_info.is_dynamic = false;
}
if let Some(skeleton) = self.wam_prelude.indices.remove_predicate_skeleton(
&self.payload.predicates.compilation_target,
&key,
) {
let compilation_target = self.payload.predicates.compilation_target;
if predicate_info.is_dynamic {
let clause_clause_compilation_target = match compilation_target {
CompilationTarget::User => {
CompilationTarget::Module(atom!("builtins"))
}
module => module,
};
self.retract_local_clauses_by_locs(
clause_clause_compilation_target,
(atom!("$clause"), 2),
(0..skeleton.clauses.len()).map(Some).collect(),
false, // the builtin M:'$clause'/2 is never dynamic.
);
predicate_info.is_dynamic = false;
}
self.payload.retraction_info.push_record(
RetractionRecord::RemovedSkeleton(compilation_target, key, skeleton),
);
}
self.payload
.retraction_info
.push_record(RetractionRecord::RemovedSkeleton(
compilation_target,
key,
skeleton,
));
}
}
@@ -2262,20 +2238,17 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
let code_index = self.compile(key, predicates, settings)?;
if let Some(filename) = self.listing_src_file_name() {
match self.wam_prelude.indices.modules.get_mut(&filename) {
Some(ref mut module) => {
let index_ptr = code_index.get();
let code_index = module.code_dir.entry(key).or_insert(code_index).clone();
if let Some(ref mut module) = self.wam_prelude.indices.modules.get_mut(&filename) {
let index_ptr = code_index.get();
let code_index = *module.code_dir.entry(key).or_insert(code_index);
set_code_index(
&mut self.payload.retraction_info,
&CompilationTarget::Module(filename),
key,
code_index,
index_ptr,
);
}
None => {}
set_code_index(
&mut self.payload.retraction_info,
&CompilationTarget::Module(filename),
key,
code_index,
index_ptr,
);
}
}
}
@@ -2344,7 +2317,7 @@ impl Machine {
};
let StandaloneCompileResult { clause_code, .. } = compile()?;
self.code.extend(clause_code.into_iter());
self.code.extend(clause_code);
Ok(())
}

View File

@@ -174,7 +174,7 @@ impl<T: CopierTarget> CopyTermState<T> {
fn copy_attr_var_lists(&mut self) {
while !self.attr_var_list_locs.is_empty() {
let iter = mem::replace(&mut self.attr_var_list_locs, vec![]);
let iter = std::mem::take(&mut self.attr_var_list_locs);
for (threshold, list_loc) in iter {
self.target[threshold] = list_loc_as_cell!(self.target.threshold());

View File

@@ -73,7 +73,7 @@ impl<'a, const STOP_AT_CYCLES: bool> CycleDetectingIter<'a, STOP_AT_CYCLES> {
fn traverse_subterm(&mut self, h: usize, arity: usize) -> Option<usize> {
let mut last_cell_loc = h + arity - 1;
for idx in (h .. h + arity).rev() {
for idx in (h..h + arity).rev() {
if self.heap[idx].get_forwarding_bit() {
if self.cycle_detection_active() {
self.cycle_found = true;
@@ -93,8 +93,8 @@ impl<'a, const STOP_AT_CYCLES: bool> CycleDetectingIter<'a, STOP_AT_CYCLES> {
#[inline]
fn continue_forwarding(&self) -> bool {
self.heap[self.current].get_mark_bit() != self.mark_phase ||
self.heap[self.current].get_forwarding_bit()
self.heap[self.current].get_mark_bit() != self.mark_phase
|| self.heap[self.current].get_forwarding_bit()
}
fn forward(&mut self) -> Option<HeapCellValue> {
@@ -150,7 +150,7 @@ impl<'a, const STOP_AT_CYCLES: bool> CycleDetectingIter<'a, STOP_AT_CYCLES> {
}
if self.cycle_detection_active() {
for idx in (h + 1 .. last_cell_loc).rev() {
for idx in (h + 1..last_cell_loc).rev() {
if self.heap[idx].get_forwarding_bit() {
self.cycle_found = true;
return None;
@@ -176,7 +176,7 @@ impl<'a, const STOP_AT_CYCLES: bool> CycleDetectingIter<'a, STOP_AT_CYCLES> {
};
if self.cycle_detection_active() {
for idx in (self.next as usize .. last_cell_loc).rev() {
for idx in (self.next as usize..last_cell_loc).rev() {
if self.heap[idx].get_forwarding_bit() {
self.cycle_found = true;
return None;
@@ -309,19 +309,19 @@ impl<'a, const STOP_AT_CYCLES: bool> CycleDetectingIter<'a, STOP_AT_CYCLES> {
HeapCellValueTag::Str => {
let mut new_str_back_link = self.current;
for idx in (0 .. self.current).rev() {
if self.heap[idx].get_tag() == HeapCellValueTag::Atom {
if cell_as_atom_cell!(self.heap[idx]).get_arity() > 0 {
new_str_back_link = idx;
break;
}
for idx in (0..self.current).rev() {
if self.heap[idx].get_tag() == HeapCellValueTag::Atom
&& cell_as_atom_cell!(self.heap[idx]).get_arity() > 0
{
new_str_back_link = idx;
break;
}
if self.heap[idx].get_mark_bit() != self.mark_phase {
if !self.heap[idx].get_forwarding_bit() {
new_str_back_link = idx;
break;
}
if self.heap[idx].get_mark_bit() != self.mark_phase
&& !self.heap[idx].get_forwarding_bit()
{
new_str_back_link = idx;
break;
}
}
@@ -402,7 +402,7 @@ impl<'a, const STOP_AT_CYCLES: bool> CycleDetectingIter<'a, STOP_AT_CYCLES> {
self.next = self.heap[self.start].get_value();
self.current = self.start;
while let Some(_) = self.forward() {}
while self.forward().is_some() {}
}
}
@@ -415,7 +415,6 @@ impl<'a, const STOP_AT_CYCLES: bool> Iterator for CycleDetectingIter<'a, STOP_AT
}
}
impl<'a, const STOP_AT_CYCLES: bool> Drop for CycleDetectingIter<'a, STOP_AT_CYCLES> {
fn drop(&mut self) {
self.invert_marker();

View File

@@ -226,7 +226,7 @@ fn merge_branch_seq(branches: impl Iterator<Item = BranchInfo>) -> BranchInfo {
for mut branch in branches {
branch_info.branch_num = branch.branch_num;
branch_info.chunks.extend(branch.chunks.drain(..));
branch_info.chunks.append(&mut branch.chunks);
}
branch_info.branch_num.delta = branch_info.branch_num.delta * Integer::from(2);
@@ -298,7 +298,7 @@ impl VariableClassifier {
fn merge_branches(&mut self) {
for branches in self.branch_map.values_mut() {
let mut old_branches = std::mem::replace(branches, vec![]);
let mut old_branches = std::mem::take(branches);
while let Some(last_branch_num) = old_branches.last().map(|bi| &bi.branch_num) {
let mut old_branches_len = old_branches.len();
@@ -361,10 +361,7 @@ impl VariableClassifier {
.current_chunk_type
.to_gen_context(self.current_chunk_num);
let branch_info_v = self
.branch_map
.entry(var_info.var_ptr.clone())
.or_insert_with(|| vec![]);
let branch_info_v = self.branch_map.entry(var_info.var_ptr.clone()).or_default();
let needs_new_branch = if let Some(last_bi) = branch_info_v.last() {
!self.root_set.contains(&last_bi.branch_num)
@@ -420,56 +417,49 @@ impl VariableClassifier {
arity: term.arity(),
};
match term {
Term::Clause(_, _, terms) => {
for term in terms.into_iter() {
for term_ref in breadth_first_iter(term, RootIterationPolicy::Iterated) {
if let TermRef::Var(lvl, _, var_ptr) = term_ref {
// a body term, so we need the child level here.
let lvl = lvl.child_level();
if let Term::Clause(_, _, terms) = term {
for term in terms.iter() {
for term_ref in breadth_first_iter(term, RootIterationPolicy::Iterated) {
if let TermRef::Var(lvl, _, var_ptr) = term_ref {
// a body term, so we need the child level here.
let lvl = lvl.child_level();
// the body of the if let here is an inlined
// "probe_head_var". note the difference between it
// and "probe_body_var".
let branch_info_v = self
.branch_map
.entry(var_ptr.clone())
.or_insert_with(|| vec![]);
// the body of the if let here is an inlined
// "probe_head_var". note the difference between it
// and "probe_body_var".
let branch_info_v = self.branch_map.entry(var_ptr.clone()).or_default();
let needs_new_branch = branch_info_v.is_empty();
let needs_new_branch = branch_info_v.is_empty();
if needs_new_branch {
branch_info_v
.push(BranchInfo::new(self.current_branch_num.clone()));
}
let branch_info = branch_info_v.last_mut().unwrap();
let needs_new_chunk = branch_info.chunks.is_empty();
if needs_new_chunk {
branch_info.chunks.push(ChunkInfo {
chunk_num: self.current_chunk_num,
term_loc: GenContext::Head,
vars: vec![],
});
}
let chunk_info = branch_info.chunks.last_mut().unwrap();
let var_info = VarInfo {
var_ptr,
classify_info,
chunk_type: self.current_chunk_type,
lvl,
};
chunk_info.vars.push(var_info);
if needs_new_branch {
branch_info_v.push(BranchInfo::new(self.current_branch_num.clone()));
}
}
classify_info.arg_c += 1;
let branch_info = branch_info_v.last_mut().unwrap();
let needs_new_chunk = branch_info.chunks.is_empty();
if needs_new_chunk {
branch_info.chunks.push(ChunkInfo {
chunk_num: self.current_chunk_num,
term_loc: GenContext::Head,
vars: vec![],
});
}
let chunk_info = branch_info.chunks.last_mut().unwrap();
let var_info = VarInfo {
var_ptr,
classify_info,
chunk_type: self.current_chunk_type,
lvl,
};
chunk_info.vars.push(var_info);
}
}
classify_info.arg_c += 1;
}
_ => {}
}
Ok(())
@@ -538,7 +528,10 @@ impl VariableClassifier {
build_stack.push_chunk_term(if is_global {
QueryTerm::GlobalCut(var_num)
} else {
QueryTerm::LocalCut { var_num, cut_prev: false }
QueryTerm::LocalCut {
var_num,
cut_prev: false,
}
});
}
TraversalState::CutPrev(var_num) => {
@@ -548,7 +541,10 @@ impl VariableClassifier {
self.probe_in_situ_var(var_num);
build_stack.push_chunk_term(QueryTerm::LocalCut { var_num, cut_prev: true });
build_stack.push_chunk_term(QueryTerm::LocalCut {
var_num,
cut_prev: true,
});
}
TraversalState::Fail => {
build_stack.push_chunk_term(QueryTerm::Fail);
@@ -705,7 +701,9 @@ impl VariableClassifier {
state_stack.push(TraversalState::BuildDisjunct(build_stack_len));
state_stack.push(TraversalState::Fail);
state_stack.push(TraversalState::CutPrev(self.var_num));
state_stack.push(TraversalState::ResetGlobalCutVarOverride(self.global_cut_var_num_override));
state_stack.push(TraversalState::ResetGlobalCutVarOverride(
self.global_cut_var_num_override,
));
state_stack.push(TraversalState::Term(not_term));
state_stack.push(TraversalState::OverrideGlobalCutVar(self.var_num));
state_stack.push(TraversalState::GetCutPoint {

View File

@@ -313,8 +313,8 @@ impl MachineState {
impl Machine {
pub(super) fn find_living_dynamic_else(&self, mut p: usize) -> Option<(usize, usize)> {
loop {
match &self.code[p] {
&Instruction::DynamicElse(birth, death, NextOrFail::Next(i)) => {
match self.code[p] {
Instruction::DynamicElse(birth, death, NextOrFail::Next(i)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, i));
} else if i > 0 {
@@ -323,14 +323,14 @@ impl Machine {
return None;
}
}
&Instruction::DynamicElse(birth, death, NextOrFail::Fail(_)) => {
Instruction::DynamicElse(birth, death, NextOrFail::Fail(_)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, 0));
} else {
return None;
}
}
&Instruction::DynamicInternalElse(birth, death, NextOrFail::Next(i)) => {
Instruction::DynamicInternalElse(birth, death, NextOrFail::Next(i)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, i));
} else if i > 0 {
@@ -339,14 +339,14 @@ impl Machine {
return None;
}
}
&Instruction::DynamicInternalElse(birth, death, NextOrFail::Fail(_)) => {
Instruction::DynamicInternalElse(birth, death, NextOrFail::Fail(_)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, 0));
} else {
return None;
}
}
&Instruction::RevJmpBy(i) => {
Instruction::RevJmpBy(i) => {
p -= i;
}
_ => {
@@ -395,25 +395,14 @@ impl Machine {
fn execute_switch_on_term(&mut self) {
#[inline(always)]
fn dynamic_external_of_clause_is_valid(machine: &mut Machine, p: usize) -> bool {
match &machine.code[p] {
Instruction::DynamicInternalElse(..) => {
machine.machine_st.dynamic_mode = FirstOrNext::First;
return true;
}
_ => {}
if let Instruction::DynamicInternalElse(..) = machine.code[p] {
machine.machine_st.dynamic_mode = FirstOrNext::First;
return true;
}
match &machine.code[p - 1] {
&Instruction::DynamicInternalElse(birth, death, _) => {
if birth < machine.machine_st.cc
&& Death::Finite(machine.machine_st.cc) <= death
{
return true;
} else {
return false;
}
}
_ => {}
if let Instruction::DynamicInternalElse(birth, death, _) = machine.code[p - 1] {
return birth < machine.machine_st.cc
&& Death::Finite(machine.machine_st.cc) <= death;
}
true
@@ -1896,7 +1885,7 @@ impl Machine {
self.machine_st.backtrack();
}
}
&Instruction::CallNumberLessThanOrEqual(ref at_1, ref at_2) => {
Instruction::CallNumberLessThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -1910,7 +1899,7 @@ impl Machine {
}
}
}
&Instruction::ExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
Instruction::ExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -1924,7 +1913,7 @@ impl Machine {
}
}
}
&Instruction::CallNumberEqual(ref at_1, ref at_2) => {
Instruction::CallNumberEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -1938,7 +1927,7 @@ impl Machine {
}
}
}
&Instruction::ExecuteNumberEqual(ref at_1, ref at_2) => {
Instruction::ExecuteNumberEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -1952,7 +1941,7 @@ impl Machine {
}
}
}
&Instruction::CallNumberNotEqual(ref at_1, ref at_2) => {
Instruction::CallNumberNotEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -1966,7 +1955,7 @@ impl Machine {
}
}
}
&Instruction::ExecuteNumberNotEqual(ref at_1, ref at_2) => {
Instruction::ExecuteNumberNotEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -1980,7 +1969,7 @@ impl Machine {
}
}
}
&Instruction::CallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
Instruction::CallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -1994,7 +1983,7 @@ impl Machine {
}
}
}
&Instruction::ExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
Instruction::ExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2008,7 +1997,7 @@ impl Machine {
}
}
}
&Instruction::CallNumberGreaterThan(ref at_1, ref at_2) => {
Instruction::CallNumberGreaterThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2022,7 +2011,7 @@ impl Machine {
}
}
}
&Instruction::ExecuteNumberGreaterThan(ref at_1, ref at_2) => {
Instruction::ExecuteNumberGreaterThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2036,7 +2025,7 @@ impl Machine {
}
}
}
&Instruction::CallNumberLessThan(ref at_1, ref at_2) => {
Instruction::CallNumberLessThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2050,7 +2039,7 @@ impl Machine {
}
}
}
&Instruction::ExecuteNumberLessThan(ref at_1, ref at_2) => {
Instruction::ExecuteNumberLessThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2064,7 +2053,7 @@ impl Machine {
}
}
}
&Instruction::DefaultCallNumberLessThanOrEqual(ref at_1, ref at_2) => {
Instruction::DefaultCallNumberLessThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2077,7 +2066,7 @@ impl Machine {
}
}
}
&Instruction::DefaultExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
Instruction::DefaultExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2090,7 +2079,7 @@ impl Machine {
}
}
}
&Instruction::DefaultCallNumberNotEqual(ref at_1, ref at_2) => {
Instruction::DefaultCallNumberNotEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2103,7 +2092,7 @@ impl Machine {
}
}
}
&Instruction::DefaultExecuteNumberNotEqual(ref at_1, ref at_2) => {
Instruction::DefaultExecuteNumberNotEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2116,7 +2105,7 @@ impl Machine {
}
}
}
&Instruction::DefaultCallNumberEqual(ref at_1, ref at_2) => {
Instruction::DefaultCallNumberEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2129,7 +2118,7 @@ impl Machine {
}
}
}
&Instruction::DefaultExecuteNumberEqual(ref at_1, ref at_2) => {
Instruction::DefaultExecuteNumberEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2142,7 +2131,7 @@ impl Machine {
}
}
}
&Instruction::DefaultCallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
Instruction::DefaultCallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2155,7 +2144,7 @@ impl Machine {
}
}
}
&Instruction::DefaultExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
Instruction::DefaultExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2168,7 +2157,7 @@ impl Machine {
}
}
}
&Instruction::DefaultCallNumberGreaterThan(ref at_1, ref at_2) => {
Instruction::DefaultCallNumberGreaterThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2181,7 +2170,7 @@ impl Machine {
}
}
}
&Instruction::DefaultExecuteNumberGreaterThan(ref at_1, ref at_2) => {
Instruction::DefaultExecuteNumberGreaterThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2194,7 +2183,7 @@ impl Machine {
}
}
}
&Instruction::DefaultCallNumberLessThan(ref at_1, ref at_2) => {
Instruction::DefaultCallNumberLessThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2207,7 +2196,7 @@ impl Machine {
}
}
}
&Instruction::DefaultExecuteNumberLessThan(ref at_1, ref at_2) => {
Instruction::DefaultExecuteNumberLessThan(ref at_1, ref at_2) => {
let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
@@ -2955,7 +2944,7 @@ impl Machine {
self.machine_st.p += 1;
}
&Instruction::IndexingCode(ref indexing_lines) => {
Instruction::IndexingCode(ref indexing_lines) => {
match &indexing_lines[self.machine_st.oip as usize] {
IndexingLine::Indexing(_) => {
self.execute_switch_on_term();
@@ -2965,22 +2954,22 @@ impl Machine {
}
}
IndexingLine::IndexedChoice(ref indexed_choice) => {
match &indexed_choice[self.machine_st.iip as usize] {
&IndexedChoiceInstruction::Try(offset) => {
match indexed_choice[self.machine_st.iip as usize] {
IndexedChoiceInstruction::Try(offset) => {
self.indexed_try(offset);
}
&IndexedChoiceInstruction::Retry(l) => {
IndexedChoiceInstruction::Retry(l) => {
self.retry(l);
increment_call_count!(self.machine_st);
}
&IndexedChoiceInstruction::DefaultRetry(l) => {
IndexedChoiceInstruction::DefaultRetry(l) => {
self.retry(l);
}
&IndexedChoiceInstruction::Trust(l) => {
IndexedChoiceInstruction::Trust(l) => {
self.trust(l);
increment_call_count!(self.machine_st);
}
&IndexedChoiceInstruction::DefaultTrust(l) => {
IndexedChoiceInstruction::DefaultTrust(l) => {
self.trust(l);
}
}
@@ -5089,16 +5078,13 @@ impl Machine {
.get_predicate_skeleton_mut(&compilation_target, &key)
.unwrap();
match skeleton.target_pos_of_clause_clause_loc(l) {
Some(n) => {
let r = self
.machine_st
.store(self.machine_st.deref(self.machine_st.registers[5]));
if let Some(n) = skeleton.target_pos_of_clause_clause_loc(l) {
let r = self
.machine_st
.store(self.machine_st.deref(self.machine_st.registers[5]));
self.machine_st
.unify_fixnum(Fixnum::build_with(n as i64), r);
}
None => {}
self.machine_st
.unify_fixnum(Fixnum::build_with(n as i64), r);
}
self.machine_st.call_at_index(2, p);
@@ -5135,16 +5121,13 @@ impl Machine {
.get_predicate_skeleton_mut(&compilation_target, &key)
.unwrap();
match skeleton.target_pos_of_clause_clause_loc(l) {
Some(n) => {
let r = self
.machine_st
.store(self.machine_st.deref(self.machine_st.registers[5]));
if let Some(n) = skeleton.target_pos_of_clause_clause_loc(l) {
let r = self
.machine_st
.store(self.machine_st.deref(self.machine_st.registers[5]));
self.machine_st
.unify_fixnum(Fixnum::build_with(n as i64), r);
}
None => {}
self.machine_st
.unify_fixnum(Fixnum::build_with(n as i64), r);
}
self.machine_st.execute_at_index(2, p);
@@ -5226,7 +5209,7 @@ impl Machine {
// So we only have access to a runtime handle in here and can't shut it down.
// Since I'm not aware of the consequences of deactivating this new code which came in while PR 1880
// was not merged, I'm only deactivating it for now.
//#[cfg(not(target_arch = "wasm32"))]
//let runtime = tokio::runtime::Runtime::new().unwrap();
//#[cfg(target_arch = "wasm32")]

View File

@@ -9,14 +9,22 @@ pub(crate) trait UnmarkPolicy {
fn forward_attr_var(iter: &mut StacklessPreOrderHeapIter<Self>) -> Option<HeapCellValue>
where
Self: Sized;
fn invert_marker(iter: &mut StacklessPreOrderHeapIter<Self>) where Self: Sized;
fn invert_marker(iter: &mut StacklessPreOrderHeapIter<Self>)
where
Self: Sized;
fn mark_phase(&self) -> bool;
#[inline]
fn report_var_link(iter: &StacklessPreOrderHeapIter<Self>) -> bool where Self: Sized {
fn report_var_link(iter: &StacklessPreOrderHeapIter<Self>) -> bool
where
Self: Sized,
{
iter.heap[iter.next as usize].get_mark_bit() == iter.iter_state.mark_phase()
}
#[inline(always)]
fn record_focus(_iter: &mut StacklessPreOrderHeapIter<Self>) where Self: Sized {
fn record_focus(_iter: &mut StacklessPreOrderHeapIter<Self>)
where
Self: Sized,
{
}
}
@@ -34,7 +42,7 @@ fn invert_marker<UMP: UnmarkPolicy>(iter: &mut StacklessPreOrderHeapIter<UMP>) {
iter.next = iter.heap[iter.start].get_value();
iter.current = iter.start;
while let Some(_) = iter.forward() {}
while iter.forward().is_some() {}
}
impl UnmarkPolicy for IteratorUMP {
@@ -139,7 +147,7 @@ impl<'a> StacklessPreOrderHeapIter<'a, IteratorUMP> {
start,
current: start,
next,
iter_state: IteratorUMP { mark_phase: true,},
iter_state: IteratorUMP { mark_phase: true },
}
}
}
@@ -189,11 +197,9 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
return Some(cell);
}
if self.next < self.heap.len() as u64 {
if UMP::report_var_link(self) {
let tag = HeapCellValueTag::AttrVar;
return Some(HeapCellValue::build_with(tag, next as u64));
}
if self.next < self.heap.len() as u64 && UMP::report_var_link(self) {
let tag = HeapCellValueTag::AttrVar;
return Some(HeapCellValue::build_with(tag, next as u64));
}
}
HeapCellValueTag::Var => {
@@ -203,11 +209,9 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
return Some(cell);
}
if self.next < self.heap.len() as u64 {
if UMP::report_var_link(self) {
let tag = HeapCellValueTag::Var;
return Some(HeapCellValue::build_with(tag, next as u64));
}
if self.next < self.heap.len() as u64 && UMP::report_var_link(self) {
let tag = HeapCellValueTag::Var;
return Some(HeapCellValue::build_with(tag, next as u64));
}
}
HeapCellValueTag::Str => {
@@ -311,10 +315,8 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
return Some(self.backward_and_return());
}
}
} else {
if self.backward() {
return None;
}
} else if self.backward() {
return None;
}
}
}
@@ -358,7 +360,7 @@ impl<'a, UMP: UnmarkPolicy> Iterator for StacklessPreOrderHeapIter<'a, UMP> {
pub fn mark_cells(heap: &mut Heap, start: usize) {
let mut iter = StacklessPreOrderHeapIter::<MarkerUMP>::new(heap, start);
while let Some(_) = iter.forward() {}
while iter.forward().is_some() {}
}
#[cfg(test)]
@@ -665,14 +667,18 @@ mod tests {
wam.machine_st.heap.push(pstr_loc_as_cell!(1));
let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "abc ", &wam.machine_st.atom_tbl);
let pstr_var_cell =
put_partial_string(&mut wam.machine_st.heap, "abc ", &wam.machine_st.atom_tbl);
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
mark_cells(&mut wam.machine_st.heap, 0);
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_loc_as_cell!(1));
assert_eq!(
unmark_cell_bits!(wam.machine_st.heap[0]),
pstr_loc_as_cell!(1)
);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_cell);
assert_eq!(
unmark_cell_bits!(wam.machine_st.heap[2]),
@@ -720,7 +726,7 @@ mod tests {
mark_cells(&mut wam.machine_st.heap, 7);
all_cells_marked_and_unforwarded(&wam.machine_st.heap[1 ..]);
all_cells_marked_and_unforwarded(&wam.machine_st.heap[1..]);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_cell);
assert_eq!(
@@ -1536,10 +1542,10 @@ mod tests {
mark_cells(&mut wam.machine_st.heap, 0);
all_cells_marked_and_unforwarded(&mut wam.machine_st.heap[0..24]);
all_cells_marked_and_unforwarded(&wam.machine_st.heap[0..24]);
for cell in &wam.machine_st.heap[24..] {
assert_eq!(cell.get_mark_bit(), false);
assert!(!cell.get_mark_bit());
}
assert_eq!(

View File

@@ -169,7 +169,7 @@ pub(crate) fn allocate_pstr(heap: &mut Heap, mut src: &str, atom_tbl: &AtomTable
let orig_h = heap.len();
loop {
if src == "" {
if src.is_empty() {
return if orig_h == heap.len() {
None
} else {
@@ -199,7 +199,7 @@ pub(crate) fn allocate_pstr(heap: &mut Heap, mut src: &str, atom_tbl: &AtomTable
heap.push(string_as_pstr_cell!(pstr));
if rest_src != "" {
if !rest_src.is_empty() {
heap.push(pstr_loc_as_cell!(h + 2));
src = rest_src;
} else {
@@ -249,7 +249,7 @@ pub(crate) fn to_local_code_ptr(heap: &Heap, addr: HeapCellValue) -> Option<usiz
Ok(Number::Integer(n)) => {
let value: usize = (&*n).try_into().unwrap();
Some(value)
},
}
_ => None,
}
};

View File

@@ -3,18 +3,17 @@ use std::sync::Arc;
use crate::atom_table;
use crate::heap_print::{HCPrinter, HCValueOutputter, PrinterOutputter};
use crate::machine::{BREAK_FROM_DISPATCH_LOOP_LOC, LIB_QUERY_SUCCESS};
use crate::machine::machine_indices::VarKey;
use crate::machine::mock_wam::CompositeOpDir;
use crate::machine::{BREAK_FROM_DISPATCH_LOOP_LOC, LIB_QUERY_SUCCESS};
use crate::parser::ast::{Var, VarPtr};
use crate::parser::parser::{Parser, Tokens};
use crate::read::write_term_to_heap;
use crate::machine::machine_indices::VarKey;
use crate::parser::ast::{Var, VarPtr};
use indexmap::IndexMap;
use super::{
Machine, MachineConfig, QueryResult, QueryResolutionLine,
Atom, AtomCell, HeapCellValue, HeapCellValueTag, Value, QueryResolution,
streams::Stream
streams::Stream, Atom, AtomCell, HeapCellValue, HeapCellValueTag, Machine, MachineConfig,
QueryResolution, QueryResolutionLine, QueryResult, Value,
};
impl Machine {
@@ -30,7 +29,10 @@ impl Machine {
pub fn consult_module_string(&mut self, module_name: &str, program: String) {
let stream = Stream::from_owned_string(program, &mut self.machine_st.arena);
self.machine_st.registers[1] = stream_as_cell!(stream);
self.machine_st.registers[2] = atom_as_cell!(&atom_table::AtomTable::build_with(&self.machine_st.atom_tbl, module_name));
self.machine_st.registers[2] = atom_as_cell!(&atom_table::AtomTable::build_with(
&self.machine_st.atom_tbl,
module_name
));
self.run_module_predicate(atom!("loader"), (atom!("consult_stream"), 2));
}
@@ -62,21 +64,33 @@ impl Machine {
// Parse the query so we can analyze and then call the term
let mut parser = Parser::new(
Stream::from_owned_string(query, &mut self.machine_st.arena),
&mut self.machine_st
&mut self.machine_st,
);
let op_dir = CompositeOpDir::new(&self.indices.op_dir, None);
let term = parser.read_term(&op_dir, Tokens::Default).expect("Failed to parse query");
let term = parser
.read_term(&op_dir, Tokens::Default)
.expect("Failed to parse query");
// Write parsed term to heap
let term_write_result = write_term_to_heap(&term, &mut self.machine_st.heap, &mut self.machine_st.atom_tbl).expect("couldn't write term to heap");
let term_write_result =
write_term_to_heap(&term, &mut self.machine_st.heap, &self.machine_st.atom_tbl)
.expect("couldn't write term to heap");
// Write term to heap
self.machine_st.registers[1] = self.machine_st.heap[term_write_result.heap_loc];
self.machine_st.cp = LIB_QUERY_SUCCESS; // BREAK_FROM_DISPATCH_LOOP_LOC;
self.machine_st.p = self.indices.code_dir.get(&(atom!("call"), 1)).expect("couldn't get code index").local().unwrap();
self.machine_st.p = self
.indices
.code_dir
.get(&(atom!("call"), 1))
.expect("couldn't get code index")
.local()
.unwrap();
let var_names: IndexMap<_, _> = term_write_result.var_dict.iter()
let var_names: IndexMap<_, _> = term_write_result
.var_dict
.iter()
.map(|(var_key, cell)| match var_key {
// NOTE: not the intention behind Var::InSitu here but
// we can hijack it to store anonymous variables
@@ -99,27 +113,29 @@ impl Machine {
//println!("stub_b: {}", stub_b);
//println!("fail: {}", self.machine_st.fail);
if self.machine_st.ball.stub.len() != 0 {
if !self.machine_st.ball.stub.is_empty() {
// NOTE: this means an exception was thrown, at which
// point we backtracked to the stub choice point.
// this should halt the search for solutions as it
// does in the Scryer top-level. the exception term is
// contained in self.machine_st.ball.
let error_string = self.machine_st.ball.stub
let error_string = self
.machine_st
.ball
.stub
.iter()
.filter(|h| match h.get_tag() {
HeapCellValueTag::Atom => true,
HeapCellValueTag::Fixnum => true,
_ => false,
.filter(|h| {
matches!(
h.get_tag(),
HeapCellValueTag::Atom | HeapCellValueTag::Fixnum
)
})
.map(|h| match h.get_tag() {
HeapCellValueTag::Atom => {
let (name, _) = cell_as_atom_cell!(h).get_name_and_arity();
name.as_str().to_string()
}
HeapCellValueTag::Fixnum => {
h.get_value().clone().to_string()
},
HeapCellValueTag::Fixnum => h.get_value().clone().to_string(),
_ => unreachable!(),
})
.collect::<Vec<String>>()
@@ -154,7 +170,7 @@ impl Machine {
let mut bindings: BTreeMap<String, Value> = BTreeMap::new();
for (var_key, term_to_be_printed) in &term_write_result.var_dict {
if var_key.to_string().starts_with("_") {
if var_key.to_string().starts_with('_') {
continue;
}
let mut printer = HCPrinter::new(
@@ -210,7 +226,7 @@ mod tests {
use ordered_float::OrderedFloat;
use super::*;
use crate::machine::{QueryMatch, Value, QueryResolution};
use crate::machine::{QueryMatch, QueryResolution, Value};
#[test]
fn programatic_query() {
@@ -258,7 +274,9 @@ mod tests {
let output = machine.run_query(query);
assert_eq!(
output,
Err(String::from("error existence_error procedure / triple 3 / triple 3"))
Err(String::from(
"error existence_error procedure / triple 3 / triple 3"
))
);
}
@@ -278,26 +296,30 @@ mod tests {
constructor(xyz, '[{action: "addLink", source: "this", predicate: "recipe://title", target: "literal://string:Meta%20Muffins"}]').
"#.to_string());
let result = machine.run_query(String::from("subject_class(\"Todo\", C), constructor(C, Actions)."));
let result = machine.run_query(String::from(
"subject_class(\"Todo\", C), constructor(C, Actions).",
));
assert_eq!(
result,
Ok(QueryResolution::Matches(vec![
QueryMatch::from(btreemap! {
Ok(QueryResolution::Matches(vec![QueryMatch::from(
btreemap! {
"C" => Value::from("c"),
"Actions" => Value::from("[{action: \"addLink\", source: \"this\", predicate: \"todo://state\", target: \"todo://ready\"}]"),
}),
]))
}
),]))
);
let result = machine.run_query(String::from("subject_class(\"Recipe\", C), constructor(C, Actions)."));
let result = machine.run_query(String::from(
"subject_class(\"Recipe\", C), constructor(C, Actions).",
));
assert_eq!(
result,
Ok(QueryResolution::Matches(vec![
QueryMatch::from(btreemap! {
Ok(QueryResolution::Matches(vec![QueryMatch::from(
btreemap! {
"C" => Value::from("xyz"),
"Actions" => Value::from("[{action: \"addLink\", source: \"this\", predicate: \"recipe://title\", target: \"literal://string:Meta%20Muffins\"}]"),
}),
]))
}
),]))
);
let result = machine.run_query(String::from("subject_class(Class, _)."));
@@ -319,15 +341,17 @@ mod tests {
let mut machine = Machine::new_lib();
machine.load_module_string(
"facts",
r#"
r#"
list([1,2,3]).
"#.to_string());
"#
.to_string(),
);
let result = machine.run_query(String::from("list(X)."));
assert_eq!(
result,
Ok(QueryResolution::Matches(vec![
QueryMatch::from(btreemap! {
Ok(QueryResolution::Matches(vec![QueryMatch::from(
btreemap! {
"X" => Value::List(
Vec::from([
Value::Float(OrderedFloat::from(1.0)),
@@ -335,12 +359,11 @@ mod tests {
Value::Float(OrderedFloat::from(3.0))
])
)
}),
]))
}
),]))
);
}
#[test]
fn consult() {
let mut machine = Machine::new_lib();
@@ -397,7 +420,6 @@ mod tests {
machine.run_query(String::from(r#"triple("a","new","b")."#)),
Ok(QueryResolution::True)
);
}
#[ignore = "fails on windows"]
@@ -462,12 +484,13 @@ mod tests {
),
);
let query = String::from(r#"findall([Predicate, Target], triple(_,Predicate,Target), Result)."#);
let query =
String::from(r#"findall([Predicate, Target], triple(_,Predicate,Target), Result)."#);
let output = machine.run_query(query);
assert_eq!(
output,
Ok(QueryResolution::Matches(vec![
QueryMatch::from(btreemap! {
Ok(QueryResolution::Matches(vec![QueryMatch::from(
btreemap! {
"Predicate" => Value::from("Predicate"),
"Result" => Value::List(
Vec::from([
@@ -476,9 +499,8 @@ mod tests {
])
),
"Target" => Value::from("Target"),
}),
]))
}
),]))
);
}
}

View File

@@ -137,10 +137,9 @@ pub(super) fn import_module_exports<'a, LS: LoadState<'a>>(
if let Some(src_code_index) = imported_module.code_dir.get(&key).cloned() {
let arena = &mut LS::machine_st(payload).arena;
let target_code_index = code_dir
let target_code_index = *code_dir
.entry(key)
.or_insert_with(|| CodeIndex::default(arena))
.clone();
.or_insert_with(|| CodeIndex::default(arena));
set_code_index(
&mut payload.retraction_info,
@@ -189,16 +188,15 @@ fn import_module_exports_into_module<'a, LS: LoadState<'a>>(
let key = (*name, *arity);
if let Some(meta_specs) = imported_module.meta_predicates.get(&key) {
meta_predicates.insert(key.clone(), meta_specs.clone());
meta_predicates.insert(key, meta_specs.clone());
}
if let Some(src_code_index) = imported_module.code_dir.get(&key) {
let arena = &mut LS::machine_st(payload).arena;
let target_code_index = code_dir
let target_code_index = *code_dir
.entry(key)
.or_insert_with(|| CodeIndex::default(arena))
.clone();
.or_insert_with(|| CodeIndex::default(arena));
set_code_index(
&mut payload.retraction_info,
@@ -209,7 +207,7 @@ fn import_module_exports_into_module<'a, LS: LoadState<'a>>(
);
} else {
return Err(SessionError::ModuleDoesNotContainExport(
imported_module.module_decl.name.clone(),
imported_module.module_decl.name,
(*name, *arity),
));
}
@@ -243,18 +241,17 @@ fn import_qualified_module_exports<'a, LS: LoadState<'a>>(
wam_prelude
.indices
.meta_predicates
.insert(key.clone(), meta_specs.clone());
.insert(key, meta_specs.clone());
}
if let Some(src_code_index) = imported_module.code_dir.get(&key) {
let arena = &mut LS::machine_st(payload).arena;
let target_code_index = wam_prelude
let target_code_index = *wam_prelude
.indices
.code_dir
.entry(key.clone())
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena))
.clone();
.entry(key)
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena));
set_code_index(
&mut payload.retraction_info,
@@ -265,7 +262,7 @@ fn import_qualified_module_exports<'a, LS: LoadState<'a>>(
);
} else {
return Err(SessionError::ModuleDoesNotContainExport(
imported_module.module_decl.name.clone(),
imported_module.module_decl.name,
(*name, *arity),
));
}
@@ -311,10 +308,9 @@ fn import_qualified_module_exports_into_module<'a, LS: LoadState<'a>>(
if let Some(src_code_index) = imported_module.code_dir.get(&key) {
let arena = &mut LS::machine_st(payload).arena;
let target_code_index = code_dir
let target_code_index = *code_dir
.entry(key)
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena))
.clone();
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena));
set_code_index(
&mut payload.retraction_info,
@@ -325,7 +321,7 @@ fn import_qualified_module_exports_into_module<'a, LS: LoadState<'a>>(
);
} else {
return Err(SessionError::ModuleDoesNotContainExport(
imported_module.module_decl.name.clone(),
imported_module.module_decl.name,
(*name, *arity),
));
}
@@ -423,7 +419,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
payload_compilation_target,
clause_clause_compilation_target,
key,
mem::replace(&mut skeleton.clause_clause_locs, VecDeque::new()),
std::mem::take(&mut skeleton.clause_clause_locs),
),
);
@@ -436,7 +432,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
}
};
self.retract_local_clauses_impl(clause_clause_compilation_target, key, &clause_locs);
self.retract_local_clauses_impl(clause_clause_compilation_target, key, clause_locs);
}
pub(super) fn try_term_to_tl(
@@ -600,30 +596,22 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
key: PredicateKey,
) -> CodeIndex {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => module
.code_dir
.entry(key)
.or_insert_with(|| {
CodeIndex::new(
IndexPtr::undefined(),
&mut LS::machine_st(&mut self.payload).arena,
)
})
.clone(),
Some(ref mut module) => *module.code_dir.entry(key).or_insert_with(|| {
CodeIndex::new(
IndexPtr::undefined(),
&mut LS::machine_st(&mut self.payload).arena,
)
}),
None => {
self.add_dynamically_generated_module(module_name);
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => module
.code_dir
.entry(key)
.or_insert_with(|| {
CodeIndex::new(
IndexPtr::undefined(),
&mut LS::machine_st(&mut self.payload).arena,
)
})
.clone(),
Some(ref mut module) => *module.code_dir.entry(key).or_insert_with(|| {
CodeIndex::new(
IndexPtr::undefined(),
&mut LS::machine_st(&mut self.payload).arena,
)
}),
None => {
unreachable!()
}
@@ -640,13 +628,12 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
let arena = &mut LS::machine_st(&mut self.payload).arena;
match compilation_target {
CompilationTarget::User => self
CompilationTarget::User => *self
.wam_prelude
.indices
.code_dir
.entry(key)
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena))
.clone(),
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena)),
CompilationTarget::Module(module_name) => {
self.get_or_insert_local_code_index(module_name, key)
}
@@ -661,13 +648,12 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
let arena = &mut LS::machine_st(&mut self.payload).arena;
if module_name == atom!("user") {
return self
return *self
.wam_prelude
.indices
.code_dir
.entry(key)
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena))
.clone();
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena));
} else {
self.get_or_insert_local_code_index(module_name, key)
}
@@ -694,7 +680,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
}
CompilationTarget::Module(module_name) => {
if let Some(module) = self.wam_prelude.indices.modules.get_mut(&module_name) {
module.extensible_predicates.insert(key.clone(), skeleton);
module.extensible_predicates.insert(key, skeleton);
let record = RetractionRecord::AddedExtensiblePredicate(
CompilationTarget::Module(module_name),
@@ -747,11 +733,10 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
match payload_compilation_target {
CompilationTarget::User => {
if let Some(filename) = listing_src_file_name {
match self.wam_prelude.indices.modules.get_mut(&filename) {
Some(ref mut module) => {
op_decl.insert_into_op_dir(&mut module.op_dir);
}
None => {}
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&filename)
{
op_decl.insert_into_op_dir(&mut module.op_dir);
}
}
@@ -855,48 +840,43 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
}
}
}
_ => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
match module.meta_predicates.insert(key.clone(), meta_specs) {
Some(old_meta_specs) => {
self.payload.retraction_info.push_record(
RetractionRecord::ReplacedMetaPredicate(
module_name,
key.0,
old_meta_specs,
),
);
}
None => {
self.payload.retraction_info.push_record(
RetractionRecord::AddedMetaPredicate(module_name, key),
);
}
}
}
None => {
self.add_dynamically_generated_module(module_name);
if let Some(module) = self.wam_prelude.indices.modules.get_mut(&module_name)
{
module.meta_predicates.insert(key.clone(), meta_specs);
} else {
unreachable!()
}
_ => match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => match module.meta_predicates.insert(key, meta_specs) {
Some(old_meta_specs) => {
self.payload.retraction_info.push_record(
RetractionRecord::AddedMetaPredicate(module_name.clone(), key),
RetractionRecord::ReplacedMetaPredicate(
module_name,
key.0,
old_meta_specs,
),
);
}
None => {
self.payload
.retraction_info
.push_record(RetractionRecord::AddedMetaPredicate(module_name, key));
}
},
None => {
self.add_dynamically_generated_module(module_name);
if let Some(module) = self.wam_prelude.indices.modules.get_mut(&module_name) {
module.meta_predicates.insert(key, meta_specs);
} else {
unreachable!()
}
self.payload
.retraction_info
.push_record(RetractionRecord::AddedMetaPredicate(module_name, key));
}
}
},
}
}
pub(super) fn add_dynamically_generated_module(&mut self, module_name: Atom) {
let module_decl = ModuleDecl {
name: module_name.clone(),
name: module_name,
exports: vec![],
};
@@ -912,12 +892,9 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
self.payload
.retraction_info
.push_record(RetractionRecord::AddedModule(module_name.clone()));
.push_record(RetractionRecord::AddedModule(module_name));
self.wam_prelude
.indices
.modules
.insert(module_name.clone(), module);
self.wam_prelude.indices.modules.insert(module_name, module);
}
fn import_builtins_in_module(
@@ -956,51 +933,48 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
self.remove_module_exports(module_name);
self.remove_replaced_in_situ_module(module_name);
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(module) => {
let old_module_decl = mem::replace(&mut module.module_decl, module_decl.clone());
if let Some(module) = self.wam_prelude.indices.modules.get_mut(&module_name) {
let old_module_decl = mem::replace(&mut module.module_decl, module_decl.clone());
let local_extensible_predicates = mem::replace(
&mut module.local_extensible_predicates,
LocalExtensiblePredicates::with_hasher(FxBuildHasher::default()),
let local_extensible_predicates = mem::replace(
&mut module.local_extensible_predicates,
LocalExtensiblePredicates::with_hasher(FxBuildHasher::default()),
);
for ((compilation_target, key), skeleton) in local_extensible_predicates.iter() {
self.retract_local_clauses_impl(
*compilation_target,
*key,
&skeleton.clause_clause_locs,
);
for ((compilation_target, key), skeleton) in local_extensible_predicates.iter() {
self.retract_local_clauses_impl(
*compilation_target,
*key,
let is_dynamic = self
.wam_prelude
.indices
.get_predicate_skeleton(compilation_target, key)
.map(|skeleton| skeleton.core.is_dynamic)
.unwrap_or(false);
if is_dynamic {
let clause_clause_compilation_target = match compilation_target {
CompilationTarget::User => CompilationTarget::Module(atom!("builtins")),
module => *module,
};
self.retract_local_clause_clauses(
clause_clause_compilation_target,
&skeleton.clause_clause_locs,
);
let is_dynamic = self
.wam_prelude
.indices
.get_predicate_skeleton(compilation_target, key)
.map(|skeleton| skeleton.core.is_dynamic)
.unwrap_or(false);
if is_dynamic {
let clause_clause_compilation_target = match compilation_target {
CompilationTarget::User => CompilationTarget::Module(atom!("builtins")),
module => module.clone(),
};
self.retract_local_clause_clauses(
clause_clause_compilation_target,
&skeleton.clause_clause_locs,
);
}
}
self.payload
.retraction_info
.push_record(RetractionRecord::ReplacedModule(
old_module_decl,
listing_src.clone(),
local_extensible_predicates,
));
}
None => {}
self.payload
.retraction_info
.push_record(RetractionRecord::ReplacedModule(
old_module_decl,
listing_src.clone(),
local_extensible_predicates,
));
}
}
@@ -1180,11 +1154,11 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
}
ModuleSource::Library(library) => match LIBRARIES.borrow().get(&*library.as_str()) {
Some(code) => {
if let Some(ref module) = self.wam_prelude.indices.modules.get(&library) {
if let Some(module) = self.wam_prelude.indices.modules.get(&library) {
if let ListingSource::DynamicallyGenerated = &module.listing_src {
(
Stream::from_static_string(
*code,
code,
&mut LS::machine_st(&mut self.payload).arena,
),
ListingSource::User,
@@ -1195,7 +1169,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
} else {
(
Stream::from_static_string(
*code,
code,
&mut LS::machine_st(&mut self.payload).arena,
),
ListingSource::User,
@@ -1266,7 +1240,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
} else {
(
Stream::from_static_string(
*code,
code,
&mut LS::machine_st(&mut self.payload).arena,
),
ListingSource::User,

View File

@@ -19,7 +19,6 @@ use std::cell::Cell;
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
/*
@@ -136,7 +135,7 @@ impl RetractionInfo {
Self {
orig_code_extent,
records: mem::replace(&mut self.records, vec![]),
records: std::mem::take(&mut self.records),
}
}
}
@@ -207,8 +206,8 @@ impl PredicateQueue {
#[inline]
pub(super) fn take(&mut self) -> Self {
Self {
predicates: mem::replace(&mut self.predicates, vec![]),
compilation_target: self.compilation_target.clone(),
predicates: std::mem::take(&mut self.predicates),
compilation_target: self.compilation_target,
}
}
@@ -404,7 +403,7 @@ impl<'a> LoadState<'a> for BootstrappingLoadState<'a> {
#[inline(always)]
fn machine_st(loader: &mut Self::LoaderFieldType) -> &mut MachineState {
&mut loader.term_stream.parser.lexer.machine_st
loader.term_stream.parser.lexer.machine_st
}
#[inline(always)]
@@ -467,7 +466,7 @@ impl<'a> LoadState<'a> for InlineLoadState<'a> {
#[inline(always)]
fn machine_st(load_state: &mut Self::LoaderFieldType) -> &mut MachineState {
&mut load_state.machine_st
load_state.machine_st
}
#[inline(always)]
@@ -639,22 +638,19 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
RetractionRecord::AddedDiscontiguousPredicate(compilation_target, key) => {
match compilation_target {
CompilationTarget::User => {
self.wam_prelude
.indices
.extensible_predicates
.get_mut(&key)
.map(|skeleton| {
skeleton.core.is_discontiguous = false;
});
if let Some(skeleton) =
self.wam_prelude.indices.extensible_predicates.get_mut(&key)
{
skeleton.core.is_discontiguous = false;
}
}
CompilationTarget::Module(module_name) => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
module.extensible_predicates.get_mut(&key).map(|skeleton| {
skeleton.core.is_discontiguous = false;
});
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&module_name)
{
if let Some(skeleton) = module.extensible_predicates.get_mut(&key) {
skeleton.core.is_discontiguous = false;
}
None => {}
}
}
}
@@ -662,23 +658,20 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
RetractionRecord::AddedDynamicPredicate(compilation_target, key) => {
match compilation_target {
CompilationTarget::User => {
self.wam_prelude
.indices
.extensible_predicates
.get_mut(&key)
.map(|skeleton| {
skeleton.core.is_dynamic = false;
});
if let Some(skeleton) =
self.wam_prelude.indices.extensible_predicates.get_mut(&key)
{
skeleton.core.is_dynamic = false;
}
}
CompilationTarget::Module(module_name) => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
module.extensible_predicates.get_mut(&key).map(|skeleton| {
skeleton.core.is_dynamic = false;
skeleton.core.retracted_dynamic_clauses = None;
});
}
None => {}
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&module_name)
{
if let Some(skeleton) = module.extensible_predicates.get_mut(&key) {
skeleton.core.is_dynamic = false;
skeleton.core.retracted_dynamic_clauses = None;
};
}
}
}
@@ -686,60 +679,52 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
RetractionRecord::AddedMultifilePredicate(compilation_target, key) => {
match compilation_target {
CompilationTarget::User => {
self.wam_prelude
.indices
.extensible_predicates
.get_mut(&key)
.map(|skeleton| {
skeleton.core.is_multifile = false;
});
if let Some(skeleton) =
self.wam_prelude.indices.extensible_predicates.get_mut(&key)
{
skeleton.core.is_multifile = false;
}
}
CompilationTarget::Module(module_name) => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
module.extensible_predicates.get_mut(&key).map(|skeleton| {
skeleton.core.is_multifile = false;
});
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&module_name)
{
if let Some(skeleton) = module.extensible_predicates.get_mut(&key) {
skeleton.core.is_multifile = false;
}
None => {}
}
}
}
}
RetractionRecord::AddedModuleOp(module_name, mut op_decl) => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
op_decl.remove(&mut module.op_dir);
}
None => {}
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&module_name)
{
op_decl.remove(&mut module.op_dir);
}
}
RetractionRecord::ReplacedModuleOp(module_name, mut op_decl, op_desc) => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
op_decl.op_desc = op_desc;
op_decl.insert_into_op_dir(&mut module.op_dir);
}
None => {}
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&module_name)
{
op_decl.op_desc = op_desc;
op_decl.insert_into_op_dir(&mut module.op_dir);
}
}
RetractionRecord::AddedModulePredicate(module_name, key) => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
module.code_dir.remove(&key);
}
None => {}
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&module_name)
{
module.code_dir.remove(&key);
}
}
RetractionRecord::ReplacedModulePredicate(module_name, key, old_code_idx) => {
match self.wam_prelude.indices.modules.get_mut(&module_name) {
Some(ref mut module) => {
module
.code_dir
.get_mut(&key)
.map(|code_idx| code_idx.set(old_code_idx));
if let Some(ref mut module) =
self.wam_prelude.indices.modules.get_mut(&module_name)
{
if let Some(code_idx) = module.code_dir.get_mut(&key) {
code_idx.set(old_code_idx)
}
None => {}
}
}
RetractionRecord::AddedExtensiblePredicate(compilation_target, key) => {
@@ -758,11 +743,9 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
self.wam_prelude.indices.code_dir.remove(&key);
}
RetractionRecord::ReplacedUserPredicate(key, old_code_idx) => {
self.wam_prelude
.indices
.code_dir
.get_mut(&key)
.map(|code_idx| code_idx.set(old_code_idx));
if let Some(code_idx) = self.wam_prelude.indices.code_dir.get_mut(&key) {
code_idx.set(old_code_idx)
}
}
RetractionRecord::AddedIndex(index_key, clause_loc) => {
if let Some(index_loc) = index_key.switch_on_term_loc() {
@@ -832,20 +815,17 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
};
}
RetractionRecord::ReplacedSwitchOnTermVarIndex(index_loc, old_v) => {
match self.wam_prelude.code[index_loc] {
Instruction::IndexingCode(ref mut indexing_code) => {
match &mut indexing_code[0] {
IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(
_,
ref mut v,
..,
)) => {
*v = old_v;
}
_ => {}
}
if let Instruction::IndexingCode(ref mut indexing_code) =
self.wam_prelude.code[index_loc]
{
if let IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(
_,
ref mut v,
..,
)) = &mut indexing_code[0]
{
*v = old_v;
}
_ => {}
}
}
RetractionRecord::ModifiedTryMeElse(instr_loc, o) => {
@@ -858,30 +838,24 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
self.wam_prelude.code[instr_loc] = Instruction::RevJmpBy(o);
}
RetractionRecord::SkeletonClausePopBack(compilation_target, key) => {
match self
if let Some(skeleton) = self
.wam_prelude
.indices
.get_predicate_skeleton_mut(&compilation_target, &key)
{
Some(skeleton) => {
skeleton.clauses.pop_back();
skeleton.core.clause_clause_locs.pop_back();
}
None => {}
skeleton.clauses.pop_back();
skeleton.core.clause_clause_locs.pop_back();
}
}
RetractionRecord::SkeletonClausePopFront(compilation_target, key) => {
match self
if let Some(skeleton) = self
.wam_prelude
.indices
.get_predicate_skeleton_mut(&compilation_target, &key)
{
Some(skeleton) => {
skeleton.clauses.pop_front();
skeleton.core.clause_clause_locs.pop_front();
skeleton.core.clause_assert_margin -= 1;
}
None => {}
skeleton.clauses.pop_front();
skeleton.core.clause_clause_locs.pop_front();
skeleton.core.clause_assert_margin -= 1;
}
}
RetractionRecord::SkeletonLocalClauseClausePopFront(
@@ -891,16 +865,15 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
) => {
let listing_src_file_name = self.listing_src_file_name();
match self.wam_prelude.indices.get_local_predicate_skeleton_mut(
src_compilation_target,
local_compilation_target,
listing_src_file_name,
key,
) {
Some(skeleton) => {
skeleton.clause_clause_locs.pop_front();
}
None => {}
if let Some(skeleton) =
self.wam_prelude.indices.get_local_predicate_skeleton_mut(
src_compilation_target,
local_compilation_target,
listing_src_file_name,
key,
)
{
skeleton.clause_clause_locs.pop_front();
}
}
RetractionRecord::SkeletonLocalClauseClausePopBack(
@@ -910,16 +883,15 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
) => {
let listing_src_file_name = self.listing_src_file_name();
match self.wam_prelude.indices.get_local_predicate_skeleton_mut(
src_compilation_target,
local_compilation_target,
listing_src_file_name,
key,
) {
Some(skeleton) => {
skeleton.clause_clause_locs.pop_back();
}
None => {}
if let Some(skeleton) =
self.wam_prelude.indices.get_local_predicate_skeleton_mut(
src_compilation_target,
local_compilation_target,
listing_src_file_name,
key,
)
{
skeleton.clause_clause_locs.pop_back();
}
}
RetractionRecord::SkeletonLocalClauseTruncateBack(
@@ -930,29 +902,25 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
) => {
let listing_src_file_name = self.listing_src_file_name();
match self.wam_prelude.indices.get_local_predicate_skeleton_mut(
src_compilation_target,
local_compilation_target,
listing_src_file_name,
key,
) {
Some(skeleton) => {
skeleton.clause_clause_locs.truncate(len);
}
None => {}
if let Some(skeleton) =
self.wam_prelude.indices.get_local_predicate_skeleton_mut(
src_compilation_target,
local_compilation_target,
listing_src_file_name,
key,
)
{
skeleton.clause_clause_locs.truncate(len);
}
}
RetractionRecord::SkeletonClauseTruncateBack(compilation_target, key, len) => {
match self
if let Some(skeleton) = self
.wam_prelude
.indices
.get_predicate_skeleton_mut(&compilation_target, &key)
{
Some(skeleton) => {
skeleton.clauses.truncate(len);
skeleton.core.clause_clause_locs.truncate(len);
}
None => {}
skeleton.clauses.truncate(len);
skeleton.core.clause_clause_locs.truncate(len);
}
}
RetractionRecord::SkeletonClauseStartReplaced(
@@ -961,15 +929,12 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
target_pos,
clause_start,
) => {
match self
if let Some(skeleton) = self
.wam_prelude
.indices
.get_predicate_skeleton_mut(&compilation_target, &key)
{
Some(skeleton) => {
skeleton.clauses[target_pos].clause_start = clause_start;
}
None => {}
skeleton.clauses[target_pos].clause_start = clause_start;
}
}
RetractionRecord::RemovedDynamicSkeletonClause(
@@ -978,26 +943,22 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
target_pos,
clause_clause_loc,
) => {
match self
if let Some(skeleton) = self
.wam_prelude
.indices
.get_predicate_skeleton_mut(&compilation_target, &key)
{
Some(skeleton) => {
if let Some(removed_clauses) =
&mut skeleton.core.retracted_dynamic_clauses
{
let clause_index_info = removed_clauses.pop().unwrap();
if let Some(removed_clauses) = &mut skeleton.core.retracted_dynamic_clauses
{
let clause_index_info = removed_clauses.pop().unwrap();
skeleton
.core
.clause_clause_locs
.insert(target_pos, clause_clause_loc);
skeleton
.core
.clause_clause_locs
.insert(target_pos, clause_clause_loc);
skeleton.clauses.insert(target_pos, clause_index_info);
}
skeleton.clauses.insert(target_pos, clause_index_info);
}
None => {}
}
}
RetractionRecord::RemovedSkeletonClause(
@@ -1007,19 +968,16 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
clause_index_info,
clause_clause_loc,
) => {
match self
if let Some(skeleton) = self
.wam_prelude
.indices
.get_predicate_skeleton_mut(&compilation_target, &key)
{
Some(skeleton) => {
skeleton
.core
.clause_clause_locs
.insert(target_pos, clause_clause_loc);
skeleton.clauses.insert(target_pos, clause_index_info);
}
None => {}
skeleton
.core
.clause_clause_locs
.insert(target_pos, clause_clause_loc);
skeleton.clauses.insert(target_pos, clause_index_info);
}
}
RetractionRecord::ReplacedIndexingLine(index_loc, indexing_code) => {
@@ -1033,14 +991,15 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
) => {
let listing_src_file_name = self.listing_src_file_name();
match self.wam_prelude.indices.get_local_predicate_skeleton_mut(
compilation_target,
local_compilation_target,
listing_src_file_name,
key,
) {
Some(skeleton) => skeleton.clause_clause_locs = clause_locs,
None => {}
if let Some(skeleton) =
self.wam_prelude.indices.get_local_predicate_skeleton_mut(
compilation_target,
local_compilation_target,
listing_src_file_name,
key,
)
{
skeleton.clause_clause_locs = clause_locs
}
}
RetractionRecord::RemovedSkeleton(compilation_target, key, skeleton) => {
@@ -1091,7 +1050,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
let export_list = machine_st.read_term_from_heap(cell);
let atom_tbl = &mut LS::machine_st(&mut self.payload).atom_tbl;
let export_list = setup_module_export_list(export_list, &atom_tbl)?;
let export_list = setup_module_export_list(export_list, atom_tbl)?;
Ok(export_list.into_iter().collect())
}
@@ -1363,7 +1322,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
*key,
) {
Some(skeleton) if !skeleton.clause_clause_locs.is_empty() => {
mem::replace(&mut skeleton.clause_clause_locs, VecDeque::new())
std::mem::take(&mut skeleton.clause_clause_locs)
}
_ => return,
};
@@ -1400,9 +1359,7 @@ impl<'a> MachinePreludeView<'a> {
CompilationTarget::User => CompositeOpDir::new(&self.indices.op_dir, None),
CompilationTarget::Module(ref module_name) => {
match self.indices.modules.get(module_name) {
Some(ref module) => {
CompositeOpDir::new(&self.indices.op_dir, Some(&module.op_dir))
}
Some(module) => CompositeOpDir::new(&self.indices.op_dir, Some(&module.op_dir)),
None => {
unreachable!()
}
@@ -1413,13 +1370,10 @@ impl<'a> MachinePreludeView<'a> {
}
impl MachineState {
pub(super) fn read_term_from_heap(
&mut self,
term_addr: HeapCellValue,
) -> Term {
pub(super) fn read_term_from_heap(&mut self, term_addr: HeapCellValue) -> Term {
let mut term_stack = vec![];
let mut iter = stackful_post_order_iter::<NonListElider>
(&mut self.heap, &mut self.stack, term_addr);
let mut iter =
stackful_post_order_iter::<NonListElider>(&mut self.heap, &mut self.stack, term_addr);
while let Some(addr) = iter.next() {
let addr = unmark_cell_bits!(addr);
@@ -1652,10 +1606,10 @@ impl Machine {
let arity = self.deref_register(3);
let arity = match Number::try_from(arity) {
Ok(Number::Integer(n)) if &*n >= &Integer::ZERO && &*n <= &Integer::from(MAX_ARITY) => {
Ok(Number::Integer(n)) if *n >= Integer::ZERO && *n <= Integer::from(MAX_ARITY) => {
let value: usize = (&*n).try_into().unwrap();
Ok(value)
},
}
Ok(Number::Fixnum(n)) if n.get_num() >= 0 && n.get_num() <= MAX_ARITY as i64 => {
Ok(usize::try_from(n.get_num()).unwrap())
}
@@ -1770,14 +1724,11 @@ impl Machine {
&ListingSource::DynamicallyGenerated,
);
match loader.wam_prelude.indices.modules.get_mut(&module_name) {
Some(module) => {
for (key, value) in module.op_dir.drain(0..) {
let mut op_decl = OpDecl::new(value, key.0);
op_decl.remove(&mut loader.wam_prelude.indices.op_dir);
}
if let Some(module) = loader.wam_prelude.indices.modules.get_mut(&module_name) {
for (key, value) in module.op_dir.drain(0..) {
let mut op_decl = OpDecl::new(value, key.0);
op_decl.remove(&mut loader.wam_prelude.indices.op_dir);
}
None => {}
}
}
}
@@ -1789,10 +1740,10 @@ impl Machine {
self.restore_load_state_payload(result)
}
pub(crate) fn loader_from_heap_evacuable<'a>(
&'a mut self,
pub(crate) fn loader_from_heap_evacuable(
&mut self,
r: RegType,
) -> Loader<'a, LiveLoadAndMachineState<'a>> {
) -> Loader<'_, LiveLoadAndMachineState<'_>> {
let mut load_state = cell_as_load_state_payload!(self
.machine_st
.store(self.machine_st.deref(self.machine_st[r])));
@@ -1868,7 +1819,7 @@ impl Machine {
let path = cell_as_atom!(self.deref_register(2));
self.load_contexts
.push(LoadContext::new(&*path.as_str(), stream));
.push(LoadContext::new(&path.as_str(), stream));
Ok(())
}
@@ -2021,8 +1972,8 @@ impl Machine {
loader.payload.compilation_target = compilation_target;
let head = LiveLoadAndMachineState::machine_st(&mut loader.payload)
.read_term_from_heap(head);
let head =
LiveLoadAndMachineState::machine_st(&mut loader.payload).read_term_from_heap(head);
let name = if let Some(name) = head.name() {
name
@@ -2218,7 +2169,7 @@ impl Machine {
Ok(Number::Integer(n)) => {
let value: usize = (&*n).try_into().unwrap();
value
},
}
Ok(Number::Fixnum(n)) => usize::try_from(n.get_num()).unwrap(),
_ => unreachable!(),
};
@@ -2520,7 +2471,7 @@ pub(super) fn load_module(
import_module_exports::<LiveLoadAndMachineState>(
&mut payload,
&compilation_target,
compilation_target,
module,
code_dir,
op_dir,

View File

@@ -80,7 +80,7 @@ impl ValidType {
#[derive(Debug, Clone, Copy)]
pub(crate) enum ResourceError {
FiniteMemory(HeapCellValue),
OutOfFiles
OutOfFiles,
}
pub(crate) trait TypeError {
@@ -170,7 +170,11 @@ impl PermissionError for Atom {
) -> MachineError {
let stub = functor!(
atom!("permission_error"),
[atom(perm.as_atom()), atom(index_atom), cell(atom_as_cell!(self))]
[
atom(perm.as_atom()),
atom(index_atom),
cell(atom_as_cell!(self))
]
);
MachineError {
@@ -319,10 +323,7 @@ impl MachineState {
)
}
ResourceError::OutOfFiles => {
functor!(
atom!("resource_error"),
[atom(atom!("file_descriptors"))]
)
functor!(atom!("resource_error"), [atom(atom!("file_descriptors"))])
}
};
@@ -355,13 +356,21 @@ impl MachineState {
from: ErrorProvenance::Received,
}
}
ExistenceError::QualifiedProcedure { module_name, name, arity } => {
ExistenceError::QualifiedProcedure {
module_name,
name,
arity,
} => {
let h = self.heap.len();
let ind_stub = functor!(atom!("/"), [atom(name), fixnum(arity)]);
let res_stub = functor!(atom!(":"), [atom(module_name), str(h + 3, 0)], [ind_stub]);
let stub = functor!(atom!("existence_error"), [atom(atom!("procedure")), str(h, 0)], [res_stub]);
let stub = functor!(
atom!("existence_error"),
[atom(atom!("procedure")), str(h, 0)],
[res_stub]
);
MachineError {
stub,
@@ -472,21 +481,15 @@ impl MachineState {
pub(super) fn session_error(&mut self, err: SessionError) -> MachineError {
match err {
SessionError::CannotOverwriteBuiltIn(key) => {
self.permission_error(
Permission::Modify,
atom!("static_procedure"),
functor_stub(key.0, key.1)
.into_iter()
.collect::<MachineStub>(),
)
}
SessionError::CannotOverwriteBuiltIn(key) => self.permission_error(
Permission::Modify,
atom!("static_procedure"),
functor_stub(key.0, key.1)
.into_iter()
.collect::<MachineStub>(),
),
SessionError::CannotOverwriteBuiltInModule(module) => {
self.permission_error(
Permission::Modify,
atom!("static_module"),
module,
)
self.permission_error(Permission::Modify, atom!("static_module"), module)
}
SessionError::ExistenceError(err) => self.existence_error(err),
SessionError::ModuleDoesNotContainExport(..) => {
@@ -641,7 +644,7 @@ impl MachineState {
self.ball.boundary = 0;
self.ball.stub.truncate(0);
self.heap.extend(err.into_iter());
self.heap.extend(err);
self.registers[1] = if err_len == 1 {
heap_loc_as_cell!(h)
@@ -705,58 +708,58 @@ impl From<ParserError> for CompilationError {
impl CompilationError {
pub(crate) fn line_and_col_num(&self) -> Option<(usize, usize)> {
match self {
&CompilationError::ParserError(ref err) => err.line_and_col_num(),
CompilationError::ParserError(err) => err.line_and_col_num(),
_ => None,
}
}
pub(crate) fn as_functor(&self) -> MachineStub {
match self {
&CompilationError::Arithmetic(..) => {
CompilationError::Arithmetic(..) => {
functor!(atom!("arithmetic_error"))
}
&CompilationError::CannotParseCyclicTerm => {
CompilationError::CannotParseCyclicTerm => {
functor!(atom!("cannot_parse_cyclic_term"))
}
&CompilationError::ExceededMaxArity => {
CompilationError::ExceededMaxArity => {
functor!(atom!("exceeded_max_arity"))
}
&CompilationError::ExpectedRel => {
CompilationError::ExpectedRel => {
functor!(atom!("expected_relation"))
}
&CompilationError::InadmissibleFact => {
CompilationError::InadmissibleFact => {
// TODO: type_error(callable, _).
functor!(atom!("inadmissible_fact"))
}
&CompilationError::InadmissibleQueryTerm => {
CompilationError::InadmissibleQueryTerm => {
// TODO: type_error(callable, _).
functor!(atom!("inadmissible_query_term"))
}
&CompilationError::InconsistentEntry => {
CompilationError::InconsistentEntry => {
functor!(atom!("inconsistent_entry"))
}
&CompilationError::InvalidMetaPredicateDecl => {
CompilationError::InvalidMetaPredicateDecl => {
functor!(atom!("invalid_meta_predicate_decl"))
}
&CompilationError::InvalidModuleDecl => {
CompilationError::InvalidModuleDecl => {
functor!(atom!("invalid_module_declaration"))
}
&CompilationError::InvalidModuleExport => {
CompilationError::InvalidModuleExport => {
functor!(atom!("invalid_module_export"))
}
&CompilationError::InvalidModuleResolution(ref module_name) => {
CompilationError::InvalidModuleResolution(ref module_name) => {
functor!(atom!("no_such_module"), [atom(module_name)])
}
&CompilationError::InvalidRuleHead => {
CompilationError::InvalidRuleHead => {
functor!(atom!("invalid_head_of_rule")) // TODO: type_error(callable, _).
}
&CompilationError::InvalidUseModuleDecl => {
CompilationError::InvalidUseModuleDecl => {
functor!(atom!("invalid_use_module_declaration"))
}
&CompilationError::ParserError(ref err) => {
CompilationError::ParserError(ref err) => {
functor!(err.as_atom())
}
&CompilationError::UnreadableTerm => {
CompilationError::UnreadableTerm => {
functor!(atom!("unreadable_term"))
}
}
@@ -986,7 +989,11 @@ pub enum ExistenceError {
Module(Atom),
ModuleSource(ModuleSource),
Procedure(Atom, usize),
QualifiedProcedure { module_name: Atom, name: Atom, arity: usize },
QualifiedProcedure {
module_name: Atom,
name: Atom,
arity: usize,
},
SourceSink(HeapCellValue),
Stream(HeapCellValue),
}

View File

@@ -118,18 +118,12 @@ impl IndexPtr {
#[inline(always)]
pub(crate) fn is_undefined(&self) -> bool {
match self.tag() {
IndexPtrTag::Undefined => true,
_ => false,
}
matches!(self.tag(), IndexPtrTag::Undefined)
}
#[inline(always)]
pub(crate) fn is_dynamic_undefined(&self) -> bool {
match self.tag() {
IndexPtrTag::DynamicUndefined => true,
_ => false,
}
matches!(self.tag(), IndexPtrTag::DynamicUndefined)
}
}
@@ -231,6 +225,7 @@ pub enum VarKey {
}
impl VarKey {
#[allow(clippy::inherent_to_string)]
#[inline]
pub(crate) fn to_string(&self) -> String {
match self {
@@ -241,11 +236,7 @@ impl VarKey {
#[inline(always)]
pub(crate) fn is_anon(&self) -> bool {
if let VarKey::AnonVar(_) = self {
true
} else {
false
}
matches!(self, VarKey::AnonVar(_))
}
}
@@ -429,9 +420,9 @@ impl IndexStore {
match compilation_target {
CompilationTarget::User => self.meta_predicates.get(&(name, arity)),
CompilationTarget::Module(ref module_name) => match self.modules.get(module_name) {
Some(ref module) => module
Some(module) => module
.meta_predicates
.get(&(name.clone(), arity))
.get(&(name, arity))
.or_else(|| self.meta_predicates.get(&(name, arity))),
None => self.meta_predicates.get(&(name, arity)),
},
@@ -446,7 +437,7 @@ impl IndexStore {
.map(|skeleton| skeleton.core.is_dynamic)
.unwrap_or(false),
_ => match self.modules.get(&module_name) {
Some(ref module) => module
Some(module) => module
.extensible_predicates
.get(&key)
.map(|skeleton| skeleton.core.is_dynamic)

View File

@@ -413,7 +413,7 @@ impl MachineState {
}
pub(crate) fn increment_call_count(&mut self) -> bool {
if self.cwil.inference_limit_exceeded || self.ball.stub.len() > 0 {
if self.cwil.inference_limit_exceeded || !self.ball.stub.is_empty() {
return true;
}
@@ -590,7 +590,9 @@ impl MachineState {
let mut singleton_var_set: IndexMap<Ref, bool> = IndexMap::new();
for cell in stackful_preorder_iter::<NonListElider>(&mut self.heap, &mut self.stack, heap_loc) {
for cell in
stackful_preorder_iter::<NonListElider>(&mut self.heap, &mut self.stack, heap_loc)
{
let cell = unmark_cell_bits!(cell);
if let Some(var) = cell.as_var() {
@@ -644,10 +646,8 @@ impl MachineState {
) -> Result<OnEOF, MachineStub> {
self.eof_action(self.registers[2], stream, atom!("read_term"), 3)?;
if stream.options().eof_action() == EOFAction::Reset {
if self.fail == false {
return Ok(OnEOF::Continue);
}
if stream.options().eof_action() == EOFAction::Reset && !self.fail {
return Ok(OnEOF::Continue);
}
Ok(OnEOF::Return)
@@ -674,10 +674,10 @@ impl MachineState {
if let Stream::Byte(_) = stream {
return self.read_term(
stream,
indices,
MachineState::read_term_from_user_input_eof_handler
)
stream,
indices,
MachineState::read_term_from_user_input_eof_handler,
);
}
unreachable!("Stream must be a Stream::Readline(_)")
@@ -691,10 +691,8 @@ impl MachineState {
} else if stream.past_end_of_stream() {
self.eof_action(self.registers[2], stream, atom!("read_term"), 3)?;
if stream.options().eof_action() == EOFAction::Reset {
if self.fail == false {
return Ok(OnEOF::Continue);
}
if stream.options().eof_action() == EOFAction::Reset && !self.fail {
return Ok(OnEOF::Continue);
}
}
@@ -716,11 +714,7 @@ impl MachineState {
)?;
if stream.past_end_of_stream() {
if EOFAction::Reset != stream.options().eof_action() {
return Ok(());
} else if self.fail {
return Ok(());
}
return Ok(());
}
loop {
@@ -970,6 +964,7 @@ impl MachineState {
}
}
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug)]
pub(crate) struct CWIL {
count: Integer,

View File

@@ -149,7 +149,7 @@ impl MachineState {
TrailRef::BlackboardEntry(key_atom) => {
self.trail.push(TrailEntry::build_with(
TrailEntryTag::TrailedBlackboardEntry,
key_atom.index as u64,
key_atom.index,
));
self.tr += 1;
@@ -157,7 +157,7 @@ impl MachineState {
TrailRef::BlackboardOffset(key_atom, value_cell) => {
self.trail.push(TrailEntry::build_with(
TrailEntryTag::TrailedBlackboardOffset,
key_atom.index as u64,
key_atom.index,
));
self.trail
@@ -432,8 +432,7 @@ impl MachineState {
pub fn compare_term_test(&mut self, var_comparison: VarComparison) -> Option<Ordering> {
let mut tabu_list = IndexSet::new();
while !self.pdl.is_empty() {
let s1 = self.pdl.pop().unwrap();
while let Some(s1) = self.pdl.pop() {
let s1 = self.deref(s1);
let s2 = self.pdl.pop().unwrap();
@@ -896,7 +895,7 @@ impl MachineState {
let s = string.as_str();
match heap_pstr_iter.compare_pstr_to_string(&*s) {
match heap_pstr_iter.compare_pstr_to_string(&s) {
Some(PStrPrefixCmpResult {
focus,
offset,
@@ -1142,7 +1141,7 @@ impl MachineState {
let cycle_found = {
let mut iter = cycle_detecting_stackless_preorder_iter(&mut self.heap, h);
while let Some(_) = iter.next() {}
for _ in iter.by_ref() {}
iter.cycle_found()
};
@@ -1376,7 +1375,7 @@ impl MachineState {
let mut type_error = |arity| {
let err = self.type_error(ValidType::Integer, arity);
return Err(self.error_form(err, stub_gen()));
Err(self.error_form(err, stub_gen()))
};
let arity = match Number::try_from(arity) {
@@ -1573,7 +1572,7 @@ impl MachineState {
) -> Result<Vec<HeapCellValue>, MachineStub> {
let mut heap_pstr_iter = HeapPStrIter::new(&self.heap, h);
while let Some(iteratee) = heap_pstr_iter.next() {
for iteratee in heap_pstr_iter.by_ref() {
match iteratee {
PStrIteratee::Char(_, c) => chars.push(char_as_cell!(c)),
PStrIteratee::PStrSegment(_, pstr_atom, n) => {
@@ -1644,10 +1643,11 @@ impl MachineState {
let addr = self.store(self.deref(addr));
match Number::try_from(addr) {
Ok(Number::Fixnum(n)) => match u8::try_from(n.get_num()) {
Ok(b) => bytes.push(b),
Err(_) => {}
},
Ok(Number::Fixnum(n)) => {
if let Ok(b) = u8::try_from(n.get_num()) {
bytes.push(b)
}
}
Ok(Number::Integer(n)) => {
let b: u8 = (&*n).try_into().unwrap();

View File

@@ -82,6 +82,12 @@ impl MockWAM {
}
}
impl Default for MockWAM {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
pub struct TermCopyingMockWAM<'a> {
pub wam: &'a mut MockWAM,
@@ -109,14 +115,14 @@ impl<'a> Deref for TermCopyingMockWAM<'a> {
type Target = MockWAM;
fn deref(&self) -> &Self::Target {
&self.wam
self.wam
}
}
#[cfg(test)]
impl<'a> DerefMut for TermCopyingMockWAM<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.wam
self.wam
}
}
@@ -165,9 +171,8 @@ impl<'a> CopierTarget for TermCopyingMockWAM<'a> {
#[cfg(test)]
pub fn all_cells_marked_and_unforwarded(heap: &[HeapCellValue]) {
for (idx, cell) in heap.iter().enumerate() {
assert_eq!(
assert!(
cell.get_mark_bit(),
true,
"cell {:?} at index {} is not marked",
cell,
idx
@@ -230,20 +235,16 @@ impl Machine {
&mut self.machine_st.arena,
);
self.load_file(file.into(), stream);
self.load_file(file, stream);
self.user_output.bytes().map(|b| b.unwrap()).collect()
}
pub fn test_load_string(&mut self, code: &str) -> Vec<u8> {
let stream = Stream::from_owned_string(
code.to_owned(),
&mut self.machine_st.arena,
);
let stream = Stream::from_owned_string(code.to_owned(), &mut self.machine_st.arena);
self.load_file("<stdin>".into(), stream);
self.load_file("<stdin>", stream);
self.user_output.bytes().map(|b| b.unwrap()).collect()
}
}
#[cfg(test)]

View File

@@ -53,6 +53,8 @@ use indexmap::IndexMap;
use lazy_static::lazy_static;
use ordered_float::OrderedFloat;
use rand::rngs::StdRng;
use rand::SeedableRng;
use std::cmp::Ordering;
use std::env;
use std::io::Read;
@@ -61,8 +63,6 @@ use std::sync::atomic::AtomicBool;
use self::config::MachineConfig;
use self::parsed_results::*;
use rand::rngs::StdRng;
use rand::SeedableRng;
lazy_static! {
pub static ref INTERRUPT: AtomicBool = AtomicBool::new(false);
@@ -172,7 +172,7 @@ pub(crate) fn import_builtin_impls(code_dir: &CodeDir, builtins: &mut Module) {
for key in keys {
let idx = code_dir.get(&key).unwrap();
builtins.code_dir.insert(key, idx.clone());
builtins.code_dir.insert(key, *idx);
builtins
.module_decl
.exports
@@ -225,7 +225,7 @@ impl Machine {
key: PredicateKey,
) -> std::process::ExitCode {
if let Some(module) = self.indices.modules.get(&module_name) {
if let Some(ref code_index) = module.code_dir.get(&key) {
if let Some(code_index) = module.code_dir.get(&key) {
let p = code_index.local().unwrap();
self.machine_st.cp = BREAK_FROM_DISPATCH_LOOP_LOC;
@@ -252,9 +252,7 @@ impl Machine {
path_buf.push("src/toplevel.pl");
let path = path_buf.to_str().unwrap();
let toplevel_stream =
Stream::from_static_string(program, &mut self.machine_st.arena);
let toplevel_stream = Stream::from_static_string(program, &mut self.machine_st.arena);
self.load_file(path, toplevel_stream);
@@ -300,7 +298,11 @@ impl Machine {
}
}
pub fn run_top_level(&mut self, module_name: Atom, key: PredicateKey) -> std::process::ExitCode {
pub fn run_top_level(
&mut self,
module_name: Atom,
key: PredicateKey,
) -> std::process::ExitCode {
let mut arg_pstrs = vec![];
for arg in env::args() {
@@ -400,57 +402,51 @@ impl Machine {
pub(crate) fn add_impls_to_indices(&mut self) {
let impls_offset = self.code.len() + 4;
self.code.extend(
vec![
Instruction::BreakFromDispatchLoop,
Instruction::InstallVerifyAttr,
Instruction::VerifyAttrInterrupt,
Instruction::BreakFromDispatchLoop, // the location of LIB_QUERY_SUCCESS
Instruction::ExecuteTermGreaterThan,
Instruction::ExecuteTermLessThan,
Instruction::ExecuteTermGreaterThanOrEqual,
Instruction::ExecuteTermLessThanOrEqual,
Instruction::ExecuteTermEqual,
Instruction::ExecuteTermNotEqual,
Instruction::ExecuteNumberGreaterThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberLessThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberGreaterThanOrEqual(
ar_reg!(temp_v!(1)),
ar_reg!(temp_v!(2)),
),
Instruction::ExecuteNumberLessThanOrEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberNotEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteIs(temp_v!(1), ar_reg!(temp_v!(2))),
Instruction::ExecuteAcyclicTerm,
Instruction::ExecuteArg,
Instruction::ExecuteCompare,
Instruction::ExecuteCopyTerm,
Instruction::ExecuteFunctor,
Instruction::ExecuteGround,
Instruction::ExecuteKeySort,
Instruction::ExecuteSort,
Instruction::ExecuteN(1),
Instruction::ExecuteN(2),
Instruction::ExecuteN(3),
Instruction::ExecuteN(4),
Instruction::ExecuteN(5),
Instruction::ExecuteN(6),
Instruction::ExecuteN(7),
Instruction::ExecuteN(8),
Instruction::ExecuteN(9),
Instruction::ExecuteIsAtom(temp_v!(1)),
Instruction::ExecuteIsAtomic(temp_v!(1)),
Instruction::ExecuteIsCompound(temp_v!(1)),
Instruction::ExecuteIsInteger(temp_v!(1)),
Instruction::ExecuteIsNumber(temp_v!(1)),
Instruction::ExecuteIsRational(temp_v!(1)),
Instruction::ExecuteIsFloat(temp_v!(1)),
Instruction::ExecuteIsNonVar(temp_v!(1)),
Instruction::ExecuteIsVar(temp_v!(1)),
]
.into_iter(),
);
self.code.extend(vec![
Instruction::BreakFromDispatchLoop,
Instruction::InstallVerifyAttr,
Instruction::VerifyAttrInterrupt,
Instruction::BreakFromDispatchLoop, // the location of LIB_QUERY_SUCCESS
Instruction::ExecuteTermGreaterThan,
Instruction::ExecuteTermLessThan,
Instruction::ExecuteTermGreaterThanOrEqual,
Instruction::ExecuteTermLessThanOrEqual,
Instruction::ExecuteTermEqual,
Instruction::ExecuteTermNotEqual,
Instruction::ExecuteNumberGreaterThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberLessThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberGreaterThanOrEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberLessThanOrEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteNumberNotEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
Instruction::ExecuteIs(temp_v!(1), ar_reg!(temp_v!(2))),
Instruction::ExecuteAcyclicTerm,
Instruction::ExecuteArg,
Instruction::ExecuteCompare,
Instruction::ExecuteCopyTerm,
Instruction::ExecuteFunctor,
Instruction::ExecuteGround,
Instruction::ExecuteKeySort,
Instruction::ExecuteSort,
Instruction::ExecuteN(1),
Instruction::ExecuteN(2),
Instruction::ExecuteN(3),
Instruction::ExecuteN(4),
Instruction::ExecuteN(5),
Instruction::ExecuteN(6),
Instruction::ExecuteN(7),
Instruction::ExecuteN(8),
Instruction::ExecuteN(9),
Instruction::ExecuteIsAtom(temp_v!(1)),
Instruction::ExecuteIsAtomic(temp_v!(1)),
Instruction::ExecuteIsCompound(temp_v!(1)),
Instruction::ExecuteIsInteger(temp_v!(1)),
Instruction::ExecuteIsNumber(temp_v!(1)),
Instruction::ExecuteIsRational(temp_v!(1)),
Instruction::ExecuteIsFloat(temp_v!(1)),
Instruction::ExecuteIsNonVar(temp_v!(1)),
Instruction::ExecuteIsVar(temp_v!(1)),
]);
for (p, instr) in self.code[impls_offset..].iter().enumerate() {
let key = instr.to_name_and_arity();
@@ -464,6 +460,7 @@ impl Machine {
}
}
#[allow(clippy::new_without_default)]
pub fn new(config: MachineConfig) -> Self {
use ref_thread_local::RefThreadLocal;
@@ -1048,7 +1045,7 @@ impl Machine {
self.reset_attr_var_state(or_frame.prelude.attr_var_queue_len);
self.machine_st.hb = target_h;
self.machine_st.p = self.machine_st.p + offset;
self.machine_st.p += offset;
self.machine_st.stack.truncate(b);
self.machine_st.heap.truncate(target_h);
@@ -1174,21 +1171,23 @@ impl Machine {
} else {
Err(self.machine_st.throw_undefined_error(name, arity))
}
} else {
if let Some(module) = self.indices.modules.get(&module_name) {
if let Some(idx) = module.code_dir.get(&(name, arity)).cloned() {
self.try_call(name, arity, idx.get())
} else {
self.undefined_procedure(name, arity)
}
} else if let Some(module) = self.indices.modules.get(&module_name) {
if let Some(idx) = module.code_dir.get(&(name, arity)).cloned() {
self.try_call(name, arity, idx.get())
} else {
let stub = functor_stub(name, arity);
let err = self
.machine_st
.existence_error(ExistenceError::QualifiedProcedure { module_name, name, arity });
Err(self.machine_st.error_form(err, stub))
self.undefined_procedure(name, arity)
}
} else {
let stub = functor_stub(name, arity);
let err = self
.machine_st
.existence_error(ExistenceError::QualifiedProcedure {
module_name,
name,
arity,
});
Err(self.machine_st.error_form(err, stub))
}
}
@@ -1202,21 +1201,23 @@ impl Machine {
} else {
self.undefined_procedure(name, arity)
}
} else {
if let Some(module) = self.indices.modules.get(&module_name) {
if let Some(idx) = module.code_dir.get(&(name, arity)).cloned() {
self.try_execute(name, arity, idx.get())
} else {
self.undefined_procedure(name, arity)
}
} else if let Some(module) = self.indices.modules.get(&module_name) {
if let Some(idx) = module.code_dir.get(&(name, arity)).cloned() {
self.try_execute(name, arity, idx.get())
} else {
let stub = functor_stub(name, arity);
let err = self
.machine_st
.existence_error(ExistenceError::QualifiedProcedure { module_name, name, arity });
Err(self.machine_st.error_form(err, stub))
self.undefined_procedure(name, arity)
}
} else {
let stub = functor_stub(name, arity);
let err = self
.machine_st
.existence_error(ExistenceError::QualifiedProcedure {
module_name,
name,
arity,
});
Err(self.machine_st.error_form(err, stub))
}
}

View File

@@ -1,6 +1,6 @@
use crate::atom_table::*;
use ordered_float::OrderedFloat;
use dashu::*;
use ordered_float::OrderedFloat;
use std::collections::BTreeMap;
use std::collections::HashMap;
@@ -67,13 +67,10 @@ impl From<Vec<QueryResolutionLine>> for QueryResolution {
// If there is only one line, and it is an empty match, return true.
if query_result_lines.len() == 1 {
match query_result_lines[0].clone() {
QueryResolutionLine::Match(m) => {
if m.is_empty() {
return QueryResolution::True;
}
if let QueryResolutionLine::Match(m) = query_result_lines[0].clone() {
if m.is_empty() {
return QueryResolution::True;
}
_ => {}
}
}
@@ -81,13 +78,9 @@ impl From<Vec<QueryResolutionLine>> for QueryResolution {
if query_result_lines
.iter()
.any(|l| l == &QueryResolutionLine::True)
&& !query_result_lines.iter().any(|l| {
if let &QueryResolutionLine::Match(_) = l {
true
} else {
false
}
})
&& !query_result_lines
.iter()
.any(|l| matches!(l, QueryResolutionLine::Match(_)))
{
return QueryResolution::True;
}
@@ -95,13 +88,7 @@ impl From<Vec<QueryResolutionLine>> for QueryResolution {
// If there is at least one match, return all matches.
let all_matches = query_result_lines
.into_iter()
.filter(|l| {
if let &QueryResolutionLine::Match(_) = l {
true
} else {
false
}
})
.filter(|l| matches!(l, QueryResolutionLine::Match(_)))
.map(|l| match l {
QueryResolutionLine::Match(m) => QueryMatch::from(m),
_ => unreachable!(),
@@ -132,7 +119,11 @@ fn split_response_string(input: &str) -> Vec<String> {
')' => level_parenthesis -= 1,
'"' => in_double_quotes = !in_double_quotes,
'\'' => in_single_quotes = !in_single_quotes,
',' if level_bracket == 0 && level_parenthesis == 0 && !in_double_quotes && !in_single_quotes => {
',' if level_bracket == 0
&& level_parenthesis == 0
&& !in_double_quotes
&& !in_single_quotes =>
{
result.push(input[start..i].trim().to_string());
start = i + 1;
}
@@ -167,13 +158,13 @@ fn parse_prolog_response(input: &str) -> HashMap<String, String> {
let key = result.0;
let value = result.1;
// cut off at given characters/strings:
let value = value.split("\n").next().unwrap().to_string();
let value = value.split(" ").next().unwrap().to_string();
let value = value.split("\t").next().unwrap().to_string();
let value = value.split('\n').next().unwrap().to_string();
let value = value.split(' ').next().unwrap().to_string();
let value = value.split('\t').next().unwrap().to_string();
let value = value.split("error").next().unwrap().to_string();
map.insert(key, value);
}
map
}
@@ -192,9 +183,8 @@ impl TryFrom<String> for QueryResolutionLine {
Ok((key, Value::try_from(value)?))
})
.filter_map(Result::ok)
.collect::<BTreeMap<_, _>>()
)
),
.collect::<BTreeMap<_, _>>(),
)),
}
}
}
@@ -229,25 +219,25 @@ impl TryFrom<String> for Value {
Ok(Value::Float(OrderedFloat(float_value)))
} else if let Ok(int_value) = string.parse::<i128>() {
Ok(Value::Integer(int_value.into()))
} else if trimmed.starts_with("'") && trimmed.ends_with("'") {
} else if trimmed.starts_with('\'') && trimmed.ends_with('\'')
|| trimmed.starts_with('"') && trimmed.ends_with('"')
{
Ok(Value::String(trimmed[1..trimmed.len() - 1].into()))
} else if trimmed.starts_with("\"") && trimmed.ends_with("\"") {
Ok(Value::String(trimmed[1..trimmed.len() - 1].into()))
} else if trimmed.starts_with("[") && trimmed.ends_with("]") {
} else if trimmed.starts_with('[') && trimmed.ends_with(']') {
let split = split_nested_list(&trimmed[1..trimmed.len() - 1]);
let values = split
.into_iter()
.map(Value::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok(Value::List(values))
} else if trimmed.starts_with("{") && trimmed.ends_with("}") {
let mut iter = trimmed[1..trimmed.len() - 1].split(",");
} else if trimmed.starts_with('{') && trimmed.ends_with('}') {
let iter = trimmed[1..trimmed.len() - 1].split(',');
let mut values = vec![];
while let Some(value) = iter.next() {
let items: Vec<_> = value.split(":").collect();
for value in iter {
let items: Vec<_> = value.split(':').collect();
if items.len() == 2 {
let _key = items[0].to_string();
let value = items[1].to_string();
@@ -257,11 +247,11 @@ impl TryFrom<String> for Value {
Ok(Value::Structure(atom!("{}"), values))
} else if trimmed.starts_with("<<") && trimmed.ends_with(">>") {
let mut iter = trimmed[2..trimmed.len() - 2].split(",");
let iter = trimmed[2..trimmed.len() - 2].split(',');
let mut values = vec![];
while let Some(value) = iter.next() {
let items: Vec<_> = value.split(":").collect();
for value in iter {
let items: Vec<_> = value.split(':').collect();
if items.len() == 2 {
let _key = items[0].to_string();
let value = items[1].to_string();
@@ -270,7 +260,7 @@ impl TryFrom<String> for Value {
}
Ok(Value::Structure(atom!("<<>>"), values))
} else if !trimmed.contains(",") && !trimmed.contains("'") && !trimmed.contains("\"") {
} else if !trimmed.contains(',') && !trimmed.contains('\'') && !trimmed.contains('"') {
Ok(Value::String(trimmed.into()))
} else {
Err(())

View File

@@ -34,10 +34,10 @@ impl From<Atom> for PartialString {
}
}
impl Into<Atom> for PartialString {
impl From<PartialString> for Atom {
#[inline]
fn into(self: Self) -> Atom {
self.0
fn from(val: PartialString) -> Self {
val.0
}
}
@@ -45,7 +45,7 @@ impl PartialString {
#[inline]
pub(super) fn new<'a>(src: &'a str, atom_tbl: &AtomTable) -> Option<(Self, &'a str)> {
let terminator_idx = scan_for_terminator(src.chars());
let pstr = PartialString(AtomTable::build_with(&atom_tbl, &src[..terminator_idx]));
let pstr = PartialString(AtomTable::build_with(atom_tbl, &src[..terminator_idx]));
Some(if terminator_idx < src.as_bytes().len() {
(pstr, &src[terminator_idx + 1..])
} else {
@@ -154,13 +154,13 @@ impl<'a> HeapPStrIter<'a> {
let s = &s[result.prefix_len..];
if s.len() >= t.len() {
if (&*s).starts_with(&*t) {
if s.starts_with(&*t) {
result.prefix_len += t.len();
result.offset += t.len();
} else {
return None;
}
} else if t.starts_with(&s) {
} else if t.starts_with(s) {
result.prefix_len += s.len();
result.offset += s.len();
@@ -218,10 +218,11 @@ impl<'a> HeapPStrIter<'a> {
self.brent_st.hare = orig_hare;
}
#[allow(clippy::inherent_to_string)]
pub fn to_string(&mut self) -> String {
let mut buf = String::with_capacity(32);
while let Some(iteratee) = self.next() {
for iteratee in self.by_ref() {
match iteratee {
PStrIteratee::Char(_, c) => {
buf.push(c);
@@ -334,14 +335,10 @@ impl<'a> HeapPStrIter<'a> {
heap_bound_deref(self.heap, self.heap[h]),
);
return if let Some(c) = value.as_char() {
Some(PStrIterStep {
return value.as_char().map(|c| PStrIterStep {
iteratee: PStrIteratee::Char(curr_hare, c),
next_hare: h+1,
})
} else {
None
};
});
}
(HeapCellValueTag::Str, s) => {
let (name, arity) = cell_as_atom_cell!(self.heap[s])
@@ -353,14 +350,10 @@ impl<'a> HeapPStrIter<'a> {
heap_bound_deref(self.heap, self.heap[s+1]),
);
if let Some(c) = value.as_char() {
Some(PStrIterStep {
value.as_char().map(|c| PStrIterStep {
iteratee: PStrIteratee::Char(curr_hare, c),
next_hare: s+2,
})
} else {
None
}
} else {
None
};
@@ -405,10 +398,7 @@ impl<'a> HeapPStrIter<'a> {
match self.brent_st.step(next_hare) {
Some(cycle_result) => {
debug_assert!(match cycle_result {
CycleSearchResult::Cyclic(..) => true,
_ => false,
});
debug_assert!(matches!(cycle_result, CycleSearchResult::Cyclic(..)));
self.walk_hare_to_cycle_end();
self.stepper = HeapPStrIter::post_cycle_discovery_stepper;
@@ -550,11 +540,7 @@ pub enum PStrCmpResult {
impl PStrCmpResult {
#[inline]
pub fn is_second_iter(&self) -> bool {
if let PStrCmpResult::SecondIterContinuable(_) = self {
true
} else {
false
}
matches!(self, PStrCmpResult::SecondIterContinuable(_))
}
}
@@ -600,8 +586,8 @@ pub fn compare_pstr_prefixes<'a>(
return PStrCmpResult::Ordered(c1.cmp(&c2));
}
cycle_detection_step(i1, i2, &step_1);
let both_cyclic = cycle_detection_step(i2, i1, &step_2);
cycle_detection_step(i1, i2, step_1);
let both_cyclic = cycle_detection_step(i2, i1, step_2);
r1 = step(i1, i1.brent_st.hare);
r2 = step(i2, i2.brent_st.hare);
@@ -623,15 +609,15 @@ pub fn compare_pstr_prefixes<'a>(
if n1 < pstr_atom.len() {
step_2.iteratee = PStrIteratee::PStrSegment(f2, pstr_atom, n1);
let c1_result = cycle_detection_step(i1, i2, &step_1);
let c1_result = cycle_detection_step(i1, i2, step_1);
r1 = step(i1, i1.brent_st.hare);
if !c1_result {
continue;
}
} else {
cycle_detection_step(i1, i2, &step_1);
let both_cyclic = cycle_detection_step(i2, i1, &step_2);
cycle_detection_step(i1, i2, step_1);
let both_cyclic = cycle_detection_step(i2, i1, step_2);
r1 = step(i1, i1.brent_st.hare);
r2 = step(i2, i2.brent_st.hare);
@@ -641,7 +627,7 @@ pub fn compare_pstr_prefixes<'a>(
}
}
} else {
let c2_result = cycle_detection_step(i2, i1, &step_2);
let c2_result = cycle_detection_step(i2, i1, step_2);
r2 = step(i2, i2.brent_st.hare);
if !c2_result {
@@ -662,15 +648,15 @@ pub fn compare_pstr_prefixes<'a>(
if n1 < pstr_atom.len() {
step_1.iteratee = PStrIteratee::PStrSegment(f1, pstr_atom, n1);
let c2_result = cycle_detection_step(i2, i1, &step_2);
let c2_result = cycle_detection_step(i2, i1, step_2);
r2 = step(i2, step_2.next_hare);
if !c2_result {
continue;
}
} else {
cycle_detection_step(i1, i2, &step_1);
let both_cyclic = cycle_detection_step(i2, i1, &step_2);
cycle_detection_step(i1, i2, step_1);
let both_cyclic = cycle_detection_step(i2, i1, step_2);
r1 = step(i1, i1.brent_st.hare);
r2 = step(i2, i2.brent_st.hare);
@@ -680,7 +666,7 @@ pub fn compare_pstr_prefixes<'a>(
}
}
} else {
let c1_result = cycle_detection_step(i1, i2, &step_1);
let c1_result = cycle_detection_step(i1, i2, step_1);
r1 = step(i1, i1.brent_st.hare);
if !c1_result {
@@ -693,8 +679,8 @@ pub fn compare_pstr_prefixes<'a>(
PStrIteratee::PStrSegment(f2, pstr2_atom, n2),
) => {
if pstr1_atom == pstr2_atom && n1 == n2 {
cycle_detection_step(i1, i2, &step_1);
let both_cyclic = cycle_detection_step(i2, i1, &step_2);
cycle_detection_step(i1, i2, step_1);
let both_cyclic = cycle_detection_step(i2, i1, step_2);
r1 = step(i1, i1.brent_st.hare);
r2 = step(i2, i2.brent_st.hare);
@@ -713,9 +699,9 @@ pub fn compare_pstr_prefixes<'a>(
let str2 = pstr2.as_str_from(n2);
match str1.len().cmp(&str2.len()) {
Ordering::Equal if &*str1 == &*str2 => {
cycle_detection_step(i1, i2, &step_1);
let both_cyclic = cycle_detection_step(i2, i1, &step_2);
Ordering::Equal if *str1 == *str2 => {
cycle_detection_step(i1, i2, step_1);
let both_cyclic = cycle_detection_step(i2, i1, step_2);
r1 = step(i1, i1.brent_st.hare);
r2 = step(i2, i2.brent_st.hare);
@@ -727,7 +713,7 @@ pub fn compare_pstr_prefixes<'a>(
Ordering::Less if str2.starts_with(&*str1) => {
step_2.iteratee =
PStrIteratee::PStrSegment(f2, pstr2_atom, n2 + str1.len());
let c1_result = cycle_detection_step(i1, i2, &step_1);
let c1_result = cycle_detection_step(i1, i2, step_1);
r1 = step(i1, i1.brent_st.hare);
if !c1_result {
@@ -737,7 +723,7 @@ pub fn compare_pstr_prefixes<'a>(
Ordering::Greater if str1.starts_with(&*str2) => {
step_1.iteratee =
PStrIteratee::PStrSegment(f1, pstr1_atom, n1 + str2.len());
let c2_result = cycle_detection_step(i2, i1, &step_2);
let c2_result = cycle_detection_step(i2, i1, step_2);
r2 = step(i2, i2.brent_st.hare);
if !c2_result {
@@ -786,12 +772,10 @@ pub fn compare_pstr_prefixes<'a>(
} else {
PStrCmpResult::FirstIterContinuable(r1.unwrap().iteratee)
}
} else if i1.is_continuable() && i2.is_continuable() {
PStrCmpResult::Ordered(Ordering::Equal)
} else {
if i1.is_continuable() && i2.is_continuable() {
PStrCmpResult::Ordered(Ordering::Equal)
} else {
PStrCmpResult::Unordered
}
PStrCmpResult::Unordered
}
}
@@ -885,7 +869,7 @@ mod test {
{
let mut iter = HeapPStrIter::new(&wam.machine_st.heap, 0);
while let Some(_) = iter.next() {}
for _ in iter.by_ref() {}
assert!(!iter.at_string_terminator());
}
@@ -1009,7 +993,7 @@ mod test {
unify!(wam.machine_st, cstr_var_cell, heap_loc_as_cell!(1));
assert_eq!(wam.machine_st.fail, false);
assert!(!wam.machine_st.fail);
assert_eq!(wam.machine_st.heap[2], char_as_cell!('a'),);
@@ -1032,7 +1016,7 @@ mod test {
unify!(wam.machine_st, cstr_var_cell, heap_loc_as_cell!(1));
assert_eq!(wam.machine_st.fail, false);
assert!(!wam.machine_st.fail);
// test "abc" = [X,b,Z].
@@ -1054,7 +1038,7 @@ mod test {
unify!(wam.machine_st, cstr_var_cell, heap_loc_as_cell!(1));
assert_eq!(wam.machine_st.fail, false);
assert!(!wam.machine_st.fail);
assert_eq!(wam.machine_st.heap[2], char_as_cell!('a'),);
@@ -1075,7 +1059,7 @@ mod test {
print_heap_terms(wam.machine_st.heap.iter(), 0);
assert_eq!(wam.machine_st.fail, false);
assert!(!wam.machine_st.fail);
assert_eq!(wam.machine_st.heap[2], pstr_loc_as_cell!(5));
assert_eq!(wam.machine_st.heap[3], pstr_loc_as_cell!(1));
@@ -1107,7 +1091,7 @@ mod test {
// assert!(iter.next().is_none());
while let Some(_) = iter.next() {}
for _ in iter {}
}
}
}

View File

@@ -100,7 +100,7 @@ fn setup_module_export(
}
pub(crate) fn build_rule_body(vars: &[Term], body_term: Term) -> Term {
let head_term = Term::Clause(Cell::default(), atom!(""), vars.iter().cloned().collect());
let head_term = Term::Clause(Cell::default(), atom!(""), vars.to_vec());
let rule = vec![head_term, body_term];
Term::Clause(Cell::default(), atom!(":-"), rule)
@@ -238,7 +238,7 @@ fn setup_meta_predicate<'a, LS: LoadState<'a>>(
) -> Result<(Atom, Vec<MetaSpec>), CompilationError> {
let mut meta_specs = vec![];
for meta_spec in terms.into_iter() {
for meta_spec in terms.iter_mut() {
match meta_spec {
Term::Literal(_, Literal::Atom(meta_spec)) => {
let meta_spec = match meta_spec {
@@ -310,11 +310,11 @@ pub(super) fn setup_declaration<'a, LS: LoadState<'a>>(
}
(atom!("module"), 2) => {
let atom_tbl = &mut LS::machine_st(&mut loader.payload).atom_tbl;
Ok(Declaration::Module(setup_module_decl(terms, &atom_tbl)?))
Ok(Declaration::Module(setup_module_decl(terms, atom_tbl)?))
}
(atom!("op"), 3) => {
let atom_tbl = &mut LS::machine_st(&mut loader.payload).atom_tbl;
Ok(Declaration::Op(setup_op_decl(terms, &atom_tbl)?))
Ok(Declaration::Op(setup_op_decl(terms, atom_tbl)?))
}
(atom!("non_counted_backtracking"), 1) => {
let (name, arity) = setup_predicate_indicator(&mut terms.pop().unwrap())?;
@@ -323,7 +323,7 @@ pub(super) fn setup_declaration<'a, LS: LoadState<'a>>(
(atom!("use_module"), 1) => Ok(Declaration::UseModule(setup_use_module_decl(terms)?)),
(atom!("use_module"), 2) => {
let atom_tbl = &mut LS::machine_st(&mut loader.payload).atom_tbl;
let (name, exports) = setup_qualified_import(terms, &atom_tbl)?;
let (name, exports) = setup_qualified_import(terms, atom_tbl)?;
Ok(Declaration::UseQualifiedModule(name, exports))
}

View File

@@ -56,7 +56,7 @@ impl Index<usize> for AndFrame {
let index_offset = (index - 1) * mem::size_of::<HeapCellValue>();
unsafe {
let ptr = mem::transmute::<&AndFrame, *const u8>(self);
let ptr = self as *const crate::machine::stack::AndFrame as *const u8;
let ptr = ptr as usize + prelude_offset + index_offset;
&*(ptr as *const HeapCellValue)
@@ -70,7 +70,7 @@ impl IndexMut<usize> for AndFrame {
let index_offset = (index - 1) * mem::size_of::<HeapCellValue>();
unsafe {
let ptr = mem::transmute::<&mut AndFrame, *const u8>(self);
let ptr = self as *mut crate::machine::stack::AndFrame as *const u8;
let ptr = ptr as usize + prelude_offset + index_offset;
&mut *(ptr as *mut HeapCellValue)
@@ -129,7 +129,7 @@ impl Index<usize> for OrFrame {
let index_offset = index * mem::size_of::<HeapCellValue>();
unsafe {
let ptr = mem::transmute::<&OrFrame, *const u8>(self);
let ptr = self as *const crate::machine::stack::OrFrame as *const u8;
let ptr = ptr as usize + prelude_offset + index_offset;
&*(ptr as *const HeapCellValue)
@@ -144,7 +144,7 @@ impl IndexMut<usize> for OrFrame {
let index_offset = index * mem::size_of::<HeapCellValue>();
unsafe {
let ptr = mem::transmute::<&mut OrFrame, *const u8>(self);
let ptr = self as *mut crate::machine::stack::OrFrame as *const u8;
let ptr = ptr as usize + prelude_offset + index_offset;
&mut *(ptr as *mut HeapCellValue)

View File

@@ -21,9 +21,9 @@ use std::fmt::Debug;
use std::fs::{File, OpenOptions};
use std::hash::Hash;
use std::io;
use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
#[cfg(feature = "http")]
use std::io::BufRead;
use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
use std::mem;
use std::net::{Shutdown, TcpStream};
use std::ops::{Deref, DerefMut};
@@ -161,7 +161,7 @@ impl StreamLayout<CharReader<InputFileStream>> {
// its pending buffer length from position.
self.get_mut()
.file
.seek(SeekFrom::Current(0))
.stream_position()
.map(|pos| pos - self.stream.rem_buf_len() as u64)
.ok()
}
@@ -317,33 +317,31 @@ impl Write for HttpWriteStream {
#[inline]
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
Ok(())
}
}
#[cfg(feature = "http")]
impl HttpWriteStream {
fn drop(&mut self) {
let headers = unsafe { mem::ManuallyDrop::take(&mut self.headers) };
let buffer = unsafe { mem::ManuallyDrop::take(&mut self.buffer) };
let (ready, response, cvar) = &**self.response;
let headers = unsafe { mem::ManuallyDrop::take(&mut self.headers) };
let buffer = unsafe { mem::ManuallyDrop::take(&mut self.buffer) };
let mut ready = ready.lock().unwrap();
{
let mut response = response.lock().unwrap();
let mut response_ = warp::http::Response::builder()
.status(self.status_code);
*response_.headers_mut().unwrap() = headers;
*response = Some(response_.body(warp::hyper::Body::from(buffer)).unwrap());
}
*ready = true;
cvar.notify_one();
let (ready, response, cvar) = &**self.response;
let mut ready = ready.lock().unwrap();
{
let mut response = response.lock().unwrap();
let mut response_ = warp::http::Response::builder().status(self.status_code);
*response_.headers_mut().unwrap() = headers;
*response = Some(response_.body(warp::hyper::Body::from(buffer)).unwrap());
}
*ready = true;
cvar.notify_one();
}
}
#[derive(Debug)]
pub struct StandardOutputStream {}
@@ -389,7 +387,7 @@ impl StreamOptions {
#[inline]
pub fn get_alias(self) -> Option<Atom> {
if self.has_alias() {
Some(Atom::from((self.alias() as u64) << 3))
Some(Atom::from(self.alias() << 3))
} else {
None
}
@@ -466,6 +464,7 @@ macro_rules! arena_allocated_impl_for_stream {
mem::size_of::<StreamLayout<$stream_type>>()
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[inline]
fn copy_to_arena(self, dst: *mut Self) -> Self::PtrToAllocated {
unsafe {
@@ -585,29 +584,17 @@ impl Stream {
#[inline]
pub fn is_stderr(&self) -> bool {
if let Stream::StandardError(_) = self {
true
} else {
false
}
matches!(self, Stream::StandardError(_))
}
#[inline]
pub fn is_stdout(&self) -> bool {
if let Stream::StandardOutput(_) = self {
true
} else {
false
}
matches!(self, Stream::StandardOutput(_))
}
#[inline]
pub fn is_stdin(&self) -> bool {
if let Stream::Readline(_) = self {
true
} else {
false
}
matches!(self, Stream::Readline(_))
}
pub fn as_ptr(&self) -> *const ArenaHeader {
@@ -831,7 +818,7 @@ impl CharRead for Stream {
impl Read for Stream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let bytes_read = match self {
match self {
Stream::InputFile(file) => (*file).read(buf),
Stream::NamedTcp(tcp_stream) => (*tcp_stream).read(buf),
#[cfg(feature = "tls")]
@@ -853,9 +840,7 @@ impl Read for Stream {
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
)),
};
bytes_read
}
}
}
@@ -984,18 +969,14 @@ fn cursor_position<T>(
cursor: &Cursor<T>,
cursor_len: u64,
) -> AtEndOfStream {
let position = cursor.position();
let at_end_of_stream = match position.cmp(&cursor_len) {
match cursor.position().cmp(&cursor_len) {
Ordering::Equal => AtEndOfStream::At,
Ordering::Greater => {
*past_end_of_stream = true;
AtEndOfStream::Past
}
Ordering::Less => AtEndOfStream::Not,
};
at_end_of_stream
}
}
impl Stream {
@@ -1021,26 +1002,23 @@ impl Stream {
#[inline]
pub(crate) fn set_position(&mut self, position: u64) {
match self {
Stream::InputFile(stream_layout) => {
let StreamLayout {
past_end_of_stream,
stream,
..
} = &mut **stream_layout;
if let Stream::InputFile(stream_layout) = self {
let StreamLayout {
past_end_of_stream,
stream,
..
} = &mut **stream_layout;
stream
.get_mut()
.file
.seek(SeekFrom::Start(position))
.unwrap();
stream.reset_buffer(); // flush the internal buffer.
stream
.get_mut()
.file
.seek(SeekFrom::Start(position))
.unwrap();
stream.reset_buffer(); // flush the internal buffer.
if let Ok(metadata) = stream.get_ref().file.metadata() {
*past_end_of_stream = position > metadata.len();
}
if let Ok(metadata) = stream.get_ref().file.metadata() {
*past_end_of_stream = position > metadata.len();
}
_ => {}
}
}
@@ -1257,15 +1235,15 @@ impl Stream {
headers: hyper::HeaderMap,
arena: &mut Arena,
) -> Self {
Stream::HttpWrite(arena_alloc!(
StreamLayout::new(CharReader::new(HttpWriteStream {
response,
status_code,
headers: mem::ManuallyDrop::new(headers),
buffer: mem::ManuallyDrop::new(Vec::new()),
})),
arena
))
Stream::HttpWrite(arena_alloc!(
StreamLayout::new(CharReader::new(HttpWriteStream {
response,
status_code,
headers: mem::ManuallyDrop::new(headers),
buffer: mem::ManuallyDrop::new(Vec::new()),
})),
arena
))
}
#[inline]
@@ -1313,8 +1291,8 @@ impl Stream {
Ok(())
}
#[cfg(feature = "http")]
Stream::HttpWrite(ref mut http_stream) => {
http_stream.inner_mut().drop();
Stream::HttpWrite(ref mut http_stream) => {
http_stream.inner_mut().drop();
unsafe {
http_stream.set_tag(ArenaHeaderTag::Dropped);
std::ptr::drop_in_place(&mut http_stream.inner_mut().buffer as *mut _);
@@ -1346,11 +1324,7 @@ impl Stream {
#[inline]
pub(crate) fn is_null_stream(&self) -> bool {
if let Stream::Null(_) = self {
true
} else {
false
}
matches!(self, Stream::Null(_))
}
#[inline]
@@ -1391,29 +1365,25 @@ impl Stream {
self.set_lines_read(0);
self.set_past_end_of_stream(false);
loop {
match self {
Stream::Byte(ref mut cursor) => {
cursor.stream.get_mut().0.set_position(0);
return true;
}
Stream::InputFile(ref mut file_stream) => {
file_stream
.stream
.get_mut()
.file
.seek(SeekFrom::Start(0))
.unwrap();
return true;
}
Stream::Readline(ref mut readline_stream) => {
readline_stream.reset();
return true;
}
_ => {
return false;
}
match self {
Stream::Byte(ref mut cursor) => {
cursor.stream.get_mut().0.set_position(0);
true
}
Stream::InputFile(ref mut file_stream) => {
file_stream
.stream
.get_mut()
.file
.seek(SeekFrom::Start(0))
.unwrap();
true
}
Stream::Readline(ref mut readline_stream) => {
readline_stream.reset();
true
}
_ => false,
}
}
@@ -1484,12 +1454,13 @@ impl MachineState {
stream.set_past_end_of_stream(true);
}
Ok(self.fail = stream.past_end_of_stream())
self.fail = stream.past_end_of_stream();
Ok(())
}
}
}
pub(crate) fn to_stream_options(
pub(crate) fn get_stream_options(
&mut self,
alias: HeapCellValue,
eof_action: HeapCellValue,
@@ -1782,9 +1753,9 @@ impl MachineState {
caller: Atom,
arity: usize,
) -> CallResult {
let opt_err = if input.is_some() && !stream.is_input_stream() {
Some(atom!("stream")) // 8.14.2.3 g)
} else if input.is_none() && !stream.is_output_stream() {
let opt_err = if input.is_some() && !stream.is_input_stream()
|| input.is_none() && !stream.is_output_stream()
{
Some(atom!("stream")) // 8.14.2.3 g)
} else if stream.options().stream_type() != expected_type {
Some(expected_type.other().as_atom()) // 8.14.2.3 h)

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
use crate::arena::*;
use crate::forms::*;
use crate::heap_iter::{NonListElider, stackful_preorder_iter};
use crate::heap_iter::{stackful_preorder_iter, NonListElider};
use crate::machine::machine_state::*;
use crate::machine::partial_string::*;
use crate::machine::*;
@@ -204,7 +204,7 @@ pub(crate) trait Unifier: DerefMut<Target = MachineState> {
let mut focus = pstr_iter2.focus;
'outer: loop {
'outer: {
while let Some(c) = chars_iter.peek() {
read_heap_cell!(focus,
(HeapCellValueTag::Lis, l) => {
@@ -329,8 +329,6 @@ pub(crate) trait Unifier: DerefMut<Target = MachineState> {
machine_st.pdl.push(focus);
machine_st.pdl.push(chars_iter.iter.focus);
break;
}
}
PStrCmpResult::Unordered => {
@@ -609,10 +607,8 @@ pub(crate) trait Unifier: DerefMut<Target = MachineState> {
}
}
(HeapCellValueTag::Lis, l1) => {
if d2.is_ref() {
if tabu_list.contains(&(d1, d2)) {
continue;
}
if d2.is_ref() && tabu_list.contains(&(d1, d2)) {
continue;
}
Self::unify_list(self, l1, d2);
@@ -720,7 +716,11 @@ fn bind_with_occurs_check<U: Unifier>(unifier: &mut U, r: Ref, value: HeapCellVa
if !value.is_constant() {
let machine_st: &mut MachineState = unifier.deref_mut();
for cell in stackful_preorder_iter::<NonListElider>(&mut machine_st.heap, &mut machine_st.stack, value) {
for cell in stackful_preorder_iter::<NonListElider>(
&mut machine_st.heap,
&mut machine_st.stack,
value,
) {
let cell = unmark_cell_bits!(cell);
if let Some(inner_r) = cell.as_var() {
@@ -738,7 +738,7 @@ fn bind_with_occurs_check<U: Unifier>(unifier: &mut U, r: Ref, value: HeapCellVa
U::bind(unifier, r, value);
}
return occurs_triggered;
occurs_triggered
}
#[derive(Deref, DerefMut)]