Merge branch 'master' into library-use-case
# Conflicts: # Cargo.lock # Cargo.toml # src/http.rs # src/machine/mock_wam.rs # src/machine/mod.rs # src/machine/system_calls.rs
This commit is contained in:
@@ -386,8 +386,7 @@ pub(crate) fn rnd_i<'a>(n: &'a Number, arena: &mut Arena) -> Number {
|
||||
&Number::Rational(ref r) => {
|
||||
let (_, floor) = (r.fract(), r.floor());
|
||||
|
||||
let result = floor.clone().try_into();
|
||||
if let Ok(value) = result{
|
||||
if let Ok(value) = (&floor).try_into() {
|
||||
fixnum!(Number, value, arena)
|
||||
} else {
|
||||
Number::Integer(arena_alloc!(floor, arena))
|
||||
@@ -713,13 +712,13 @@ impl TryFrom<HeapCellValue> for Number {
|
||||
|
||||
// Computes n ^ power. Ignores the sign of power.
|
||||
pub(crate) fn binary_pow(mut n: Integer, power: &Integer) -> Integer {
|
||||
let mut power = Integer::from(power.abs());
|
||||
let mut power = power.abs();
|
||||
|
||||
if power.num_eq(&0) {
|
||||
return Integer::from(1);
|
||||
if power.is_zero() {
|
||||
return Integer::ONE;
|
||||
}
|
||||
|
||||
let mut oddand = Integer::from(1);
|
||||
let mut oddand = Integer::ONE;
|
||||
|
||||
while power.num_gt(&1) {
|
||||
if power.bit(0) {
|
||||
|
||||
207
src/heap_iter.rs
207
src/heap_iter.rs
@@ -6,6 +6,7 @@ use crate::machine::heap::*;
|
||||
use crate::machine::stack::*;
|
||||
use crate::types::*;
|
||||
|
||||
use core::marker::PhantomData;
|
||||
use modular_bitfield::prelude::*;
|
||||
|
||||
use std::ops::Deref;
|
||||
@@ -79,15 +80,40 @@ impl IterStackLoc {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ListElisionPolicy {
|
||||
fn elide_lists() -> bool;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct StackfulPreOrderHeapIter<'a> {
|
||||
pub struct ListElider {}
|
||||
|
||||
impl ListElisionPolicy for ListElider {
|
||||
#[inline(always)]
|
||||
fn elide_lists() -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NonListElider {}
|
||||
|
||||
impl ListElisionPolicy for NonListElider {
|
||||
#[inline(always)]
|
||||
fn elide_lists() -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
pub heap: &'a mut Vec<HeapCellValue>,
|
||||
pub machine_stack: &'a mut Stack,
|
||||
stack: Vec<IterStackLoc>,
|
||||
h: IterStackLoc,
|
||||
_marker: PhantomData<ElideLists>,
|
||||
}
|
||||
|
||||
impl<'a> Drop for StackfulPreOrderHeapIter<'a> {
|
||||
impl<'a, ElideLists> Drop for StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
fn drop(&mut self) {
|
||||
while let Some(h) = self.stack.pop() {
|
||||
let cell = self.read_cell_mut(h);
|
||||
@@ -104,53 +130,14 @@ pub trait FocusedHeapIter: Iterator<Item = HeapCellValue> {
|
||||
fn focus(&self) -> IterStackLoc;
|
||||
}
|
||||
|
||||
impl<'a> FocusedHeapIter for StackfulPreOrderHeapIter<'a> {
|
||||
impl<'a, ElideLists: ListElisionPolicy> FocusedHeapIter for StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
#[inline]
|
||||
fn focus(&self) -> IterStackLoc {
|
||||
self.h
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> StackfulPreOrderHeapIter<'a> {
|
||||
#[inline]
|
||||
fn new(heap: &'a mut Vec<HeapCellValue>, stack: &'a mut Stack, cell: HeapCellValue) -> Self {
|
||||
let h = IterStackLoc::iterable_loc(heap.len(), HeapOrStackTag::Heap);
|
||||
heap.push(cell);
|
||||
|
||||
Self {
|
||||
heap,
|
||||
h,
|
||||
machine_stack: stack,
|
||||
stack: vec![h],
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn forward_if_referent_marked(&mut self, loc: IterStackLoc) {
|
||||
read_heap_cell!(self.read_cell(loc),
|
||||
(HeapCellValueTag::Str |
|
||||
HeapCellValueTag::Lis |
|
||||
HeapCellValueTag::AttrVar |
|
||||
HeapCellValueTag::Var |
|
||||
HeapCellValueTag::PStrLoc, vh) => {
|
||||
if self.heap[vh].get_mark_bit() {
|
||||
self.read_cell_mut(loc).set_forwarding_bit(true);
|
||||
}
|
||||
}
|
||||
(HeapCellValueTag::StackVar, vs) => {
|
||||
if self.machine_stack[vs].get_mark_bit() {
|
||||
self.read_cell_mut(loc).set_forwarding_bit(true);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn push_stack(&mut self, h: IterStackLoc) {
|
||||
self.stack.push(h);
|
||||
}
|
||||
|
||||
impl<'a, ElideLists> StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
#[inline]
|
||||
pub fn read_cell_mut(&mut self, loc: IterStackLoc) -> &mut HeapCellValue {
|
||||
match loc.heap_or_stack() {
|
||||
@@ -167,6 +154,11 @@ impl<'a> StackfulPreOrderHeapIter<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn push_stack(&mut self, h: IterStackLoc) {
|
||||
self.stack.push(h);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn stack_last(&self) -> Option<IterStackLoc> {
|
||||
for h in self.stack.iter().rev() {
|
||||
@@ -222,6 +214,51 @@ impl<'a> StackfulPreOrderHeapIter<'a> {
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, ElideLists: ListElisionPolicy> StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
#[inline]
|
||||
fn new(heap: &'a mut Vec<HeapCellValue>, stack: &'a mut Stack, cell: HeapCellValue) -> Self {
|
||||
let h = IterStackLoc::iterable_loc(heap.len(), HeapOrStackTag::Heap);
|
||||
heap.push(cell);
|
||||
|
||||
Self {
|
||||
heap,
|
||||
h,
|
||||
machine_stack: stack,
|
||||
stack: vec![h],
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn forward_if_referent_marked(&mut self, loc: IterStackLoc) {
|
||||
let cell = self.read_cell(loc);
|
||||
|
||||
read_heap_cell!(cell,
|
||||
(HeapCellValueTag::Lis |
|
||||
HeapCellValueTag::Str |
|
||||
HeapCellValueTag::PStrLoc, vh) => {
|
||||
let forward = if ElideLists::elide_lists() { true } else { cell.get_mark_bit() };
|
||||
|
||||
if forward && self.heap[vh].get_mark_bit() {
|
||||
self.read_cell_mut(loc).set_forwarding_bit(true);
|
||||
}
|
||||
}
|
||||
(HeapCellValueTag::AttrVar |
|
||||
HeapCellValueTag::Var, vh) => {
|
||||
if self.heap[vh].get_mark_bit() {
|
||||
self.read_cell_mut(loc).set_forwarding_bit(true);
|
||||
}
|
||||
}
|
||||
(HeapCellValueTag::StackVar, vs) => {
|
||||
if self.machine_stack[vs].get_mark_bit() {
|
||||
self.read_cell_mut(loc).set_forwarding_bit(true);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
);
|
||||
}
|
||||
|
||||
fn follow(&mut self) -> Option<HeapCellValue> {
|
||||
while let Some(h) = self.stack.pop() {
|
||||
@@ -260,28 +297,27 @@ impl<'a> StackfulPreOrderHeapIter<'a> {
|
||||
(HeapCellValueTag::Lis, vh) => {
|
||||
let loc = IterStackLoc::iterable_loc(vh, HeapOrStackTag::Heap);
|
||||
|
||||
self.forward_if_referent_marked(loc);
|
||||
self.push_if_unmarked(loc);
|
||||
|
||||
self.stack.push(IterStackLoc::pending_mark_loc(vh + 1, HeapOrStackTag::Heap));
|
||||
self.stack.push(IterStackLoc::mark_loc(vh, HeapOrStackTag::Heap));
|
||||
|
||||
self.forward_if_referent_marked(loc);
|
||||
|
||||
return Some(self.read_cell(h));
|
||||
}
|
||||
(HeapCellValueTag::AttrVar | HeapCellValueTag::Var, vh) => {
|
||||
let loc = IterStackLoc::iterable_loc(vh, HeapOrStackTag::Heap);
|
||||
|
||||
self.forward_if_referent_marked(loc);
|
||||
self.push_if_unmarked(loc);
|
||||
self.stack.push(IterStackLoc::mark_loc(vh, HeapOrStackTag::Heap));
|
||||
self.forward_if_referent_marked(loc);
|
||||
}
|
||||
(HeapCellValueTag::StackVar, vs) => {
|
||||
let loc = IterStackLoc::iterable_loc(vs, HeapOrStackTag::Stack);
|
||||
|
||||
self.forward_if_referent_marked(loc);
|
||||
self.push_if_unmarked(loc);
|
||||
self.stack.push(IterStackLoc::mark_loc(vs, HeapOrStackTag::Stack));
|
||||
self.forward_if_referent_marked(loc);
|
||||
}
|
||||
(HeapCellValueTag::PStrOffset, offset) => {
|
||||
self.push_if_unmarked(IterStackLoc::iterable_loc(offset, HeapOrStackTag::Heap));
|
||||
@@ -325,7 +361,7 @@ impl<'a> StackfulPreOrderHeapIter<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for StackfulPreOrderHeapIter<'a> {
|
||||
impl<'a, ElideLists: ListElisionPolicy> Iterator for StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
type Item = HeapCellValue;
|
||||
|
||||
#[inline]
|
||||
@@ -344,11 +380,11 @@ pub(crate) fn stackless_preorder_iter(
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn stackful_preorder_iter<'a>(
|
||||
pub(crate) fn stackful_preorder_iter<'a, ElideLists: ListElisionPolicy>(
|
||||
heap: &'a mut Vec<HeapCellValue>,
|
||||
stack: &'a mut Stack,
|
||||
cell: HeapCellValue,
|
||||
) -> StackfulPreOrderHeapIter<'a> {
|
||||
) -> StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
StackfulPreOrderHeapIter::new(heap, stack, cell)
|
||||
}
|
||||
|
||||
@@ -455,9 +491,10 @@ impl<Iter: FocusedHeapIter> PostOrderIterator<Iter> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type LeftistPostOrderHeapIter<'a> = PostOrderIterator<StackfulPreOrderHeapIter<'a>>;
|
||||
pub(crate) type LeftistPostOrderHeapIter<'a, ElideLists> =
|
||||
PostOrderIterator<StackfulPreOrderHeapIter<'a, ElideLists>>;
|
||||
|
||||
impl<'a> LeftistPostOrderHeapIter<'a> {
|
||||
impl<'a, ElideLists: ListElisionPolicy> LeftistPostOrderHeapIter<'a, ElideLists> {
|
||||
#[inline]
|
||||
pub fn pop_stack(&mut self) {
|
||||
if let Some((child_count, ..)) = self.parent_stack.last() {
|
||||
@@ -476,11 +513,11 @@ impl<'a> LeftistPostOrderHeapIter<'a> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn stackful_post_order_iter<'a>(
|
||||
pub(crate) fn stackful_post_order_iter<'a, ElideLists: ListElisionPolicy>(
|
||||
heap: &'a mut Heap,
|
||||
stack: &'a mut Stack,
|
||||
cell: HeapCellValue,
|
||||
) -> LeftistPostOrderHeapIter<'a> {
|
||||
) -> LeftistPostOrderHeapIter<'a, ElideLists> {
|
||||
PostOrderIterator::new(StackfulPreOrderHeapIter::new(heap, stack, cell))
|
||||
}
|
||||
|
||||
@@ -1550,7 +1587,7 @@ mod tests {
|
||||
.extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
|
||||
|
||||
{
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
str_loc_as_cell!(0),
|
||||
@@ -1585,7 +1622,7 @@ mod tests {
|
||||
));
|
||||
|
||||
for _ in 0..20 {
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
str_loc_as_cell!(0),
|
||||
@@ -1617,7 +1654,7 @@ mod tests {
|
||||
{
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(0));
|
||||
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1644,7 +1681,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(1));
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(0));
|
||||
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1668,7 +1705,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(empty_list_as_cell!());
|
||||
|
||||
{
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1704,7 +1741,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(0));
|
||||
|
||||
{
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1736,7 +1773,7 @@ mod tests {
|
||||
}
|
||||
|
||||
{
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1775,7 +1812,7 @@ mod tests {
|
||||
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
|
||||
|
||||
{
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1800,7 +1837,7 @@ mod tests {
|
||||
let pstr_second_cell = wam.machine_st.heap[pstr_second_var_cell.get_value() as usize];
|
||||
|
||||
{
|
||||
let mut iter = stackful_preorder_iter(
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1827,7 +1864,7 @@ mod tests {
|
||||
.push(fixnum_as_cell!(Fixnum::build_with(0i64)));
|
||||
|
||||
{
|
||||
let mut iter = stackful_preorder_iter(
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
pstr_loc_as_cell!(0),
|
||||
@@ -1862,7 +1899,7 @@ mod tests {
|
||||
.push(fixnum_as_cell!(Fixnum::build_with(1i64)));
|
||||
|
||||
{
|
||||
let mut iter = stackful_preorder_iter(
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
pstr_loc_as_cell!(0),
|
||||
@@ -1906,7 +1943,7 @@ mod tests {
|
||||
wam.machine_st.heap.extend(functor);
|
||||
|
||||
{
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -1969,7 +2006,7 @@ mod tests {
|
||||
wam.machine_st.heap[4] = list_loc_as_cell!(1);
|
||||
|
||||
{
|
||||
let mut iter = stackful_preorder_iter(
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2038,7 +2075,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(list_loc_as_cell!(1));
|
||||
|
||||
{
|
||||
let mut iter = StackfulPreOrderHeapIter::new(
|
||||
let mut iter = StackfulPreOrderHeapIter::<NonListElider>::new(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2059,6 +2096,10 @@ mod tests {
|
||||
);
|
||||
assert_eq!(iter.next().unwrap(), cyclic_link);
|
||||
|
||||
assert_eq!(iter.next().unwrap(), cyclic_link);
|
||||
|
||||
assert_eq!(iter.next().unwrap(), cyclic_link);
|
||||
|
||||
assert_eq!(iter.next(), None);
|
||||
}
|
||||
|
||||
@@ -2070,7 +2111,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(empty_list_as_cell!());
|
||||
|
||||
{
|
||||
let mut iter = stackful_preorder_iter(
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2102,7 +2143,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(empty_list_as_cell!());
|
||||
|
||||
{
|
||||
let mut iter = stackful_preorder_iter(
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2140,7 +2181,7 @@ mod tests {
|
||||
.extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
str_loc_as_cell!(0),
|
||||
@@ -2176,7 +2217,7 @@ mod tests {
|
||||
|
||||
for _ in 0..20 {
|
||||
// 0000 {
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
str_loc_as_cell!(0),
|
||||
@@ -2210,7 +2251,7 @@ mod tests {
|
||||
{
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(0));
|
||||
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2237,7 +2278,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(1));
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(0));
|
||||
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2261,7 +2302,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(empty_list_as_cell!());
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2297,7 +2338,7 @@ mod tests {
|
||||
wam.machine_st.heap.push(heap_loc_as_cell!(0));
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2329,7 +2370,7 @@ mod tests {
|
||||
}
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2368,7 +2409,7 @@ mod tests {
|
||||
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
pstr_loc_as_cell!(0),
|
||||
@@ -2392,7 +2433,7 @@ mod tests {
|
||||
let pstr_second_cell = wam.machine_st.heap[pstr_second_var_cell.get_value() as usize];
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
pstr_loc_as_cell!(0),
|
||||
@@ -2419,7 +2460,7 @@ mod tests {
|
||||
.push(fixnum_as_cell!(Fixnum::build_with(0i64)));
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
pstr_loc_as_cell!(0),
|
||||
@@ -2446,7 +2487,7 @@ mod tests {
|
||||
.push(fixnum_as_cell!(Fixnum::build_with(1i64)));
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
pstr_loc_as_cell!(0),
|
||||
@@ -2480,7 +2521,7 @@ mod tests {
|
||||
wam.machine_st.heap.extend(functor);
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
@@ -2544,7 +2585,7 @@ mod tests {
|
||||
wam.machine_st.heap[4] = list_loc_as_cell!(1);
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(
|
||||
&mut wam.machine_st.heap,
|
||||
&mut wam.machine_st.stack,
|
||||
heap_loc_as_cell!(0),
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use crate::arena::*;
|
||||
use crate::atom_table::*;
|
||||
use crate::parser::ast::*;
|
||||
use crate::parser::dashu::{Integer, Rational};
|
||||
use crate::parser::dashu::{ibig, Integer, Rational};
|
||||
use crate::parser::dashu::base::RemEuclid;
|
||||
use crate::parser::dashu::integer::Sign;
|
||||
use crate::{
|
||||
alpha_numeric_char, capital_letter_char, cut_char, decimal_digit_char, graphic_token_char,
|
||||
is_fx, is_infix, is_postfix, is_prefix, is_xf, is_xfx, is_xfy, is_yfx, semicolon_char,
|
||||
@@ -18,8 +20,6 @@ use crate::machine::stack::*;
|
||||
use crate::machine::streams::*;
|
||||
use crate::types::*;
|
||||
|
||||
use dashu::base::DivRem;
|
||||
use dashu::base::DivRemEuclid;
|
||||
use ordered_float::OrderedFloat;
|
||||
|
||||
use indexmap::IndexMap;
|
||||
@@ -104,7 +104,7 @@ fn needs_bracketing(child_desc: OpDesc, op: &DirectedOp) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> StackfulPreOrderHeapIter<'a> {
|
||||
impl<'a, ElideLists> StackfulPreOrderHeapIter<'a, ElideLists> {
|
||||
/*
|
||||
* descend into the subtree where the iterator is currently parked
|
||||
* and check that the leftmost leaf is a number, with every node
|
||||
@@ -208,6 +208,15 @@ impl NumberFocus {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct CommaSeparatedCharList {
|
||||
pstr: PartialString,
|
||||
offset: usize,
|
||||
max_depth: usize,
|
||||
end_cell: HeapCellValue,
|
||||
end_h: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum TokenOrRedirect {
|
||||
Atom(Atom),
|
||||
@@ -233,6 +242,8 @@ enum TokenOrRedirect {
|
||||
OpenList(Rc<Cell<(bool, usize)>>),
|
||||
CloseList(Rc<Cell<(bool, usize)>>),
|
||||
HeadTailSeparator,
|
||||
StackPop,
|
||||
CommaSeparatedCharList(CommaSeparatedCharList),
|
||||
}
|
||||
|
||||
pub(crate) fn requires_space(atom: &str, op: &str) -> bool {
|
||||
@@ -396,7 +407,7 @@ fn is_numbered_var(name: Atom, arity: usize) -> bool {
|
||||
|
||||
#[inline]
|
||||
fn negated_op_needs_bracketing(
|
||||
iter: &StackfulPreOrderHeapIter,
|
||||
iter: &StackfulPreOrderHeapIter<ListElider>,
|
||||
op_dir: &OpDir,
|
||||
op: &Option<DirectedOp>,
|
||||
) -> bool {
|
||||
@@ -480,7 +491,7 @@ pub fn fmt_float(mut fl: f64) -> String {
|
||||
#[derive(Debug)]
|
||||
pub struct HCPrinter<'a, Outputter> {
|
||||
outputter: Outputter,
|
||||
iter: StackfulPreOrderHeapIter<'a>,
|
||||
iter: StackfulPreOrderHeapIter<'a, ListElider>,
|
||||
atom_tbl: Arc<AtomTable>,
|
||||
op_dir: &'a OpDir,
|
||||
state_stack: Vec<TokenOrRedirect>,
|
||||
@@ -515,13 +526,10 @@ pub(crate) fn numbervar(offset: &Integer, addr: HeapCellValue) -> Option<String>
|
||||
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
|
||||
];
|
||||
|
||||
let n_clone: Integer = n.clone();
|
||||
let i: usize = (&n).rem_euclid(ibig!(26)).try_into().unwrap();
|
||||
let j = n / ibig!(26);
|
||||
|
||||
let i = n.div_rem_euclid(Integer::from(26)).1.to_f32().value() as usize;
|
||||
let j = n_clone.div_rem(Integer::from(26));
|
||||
let j = <(Integer, Integer)>::from(j).0;
|
||||
|
||||
if j == Integer::from(0) {
|
||||
if j.is_zero() {
|
||||
CHAR_CODES[i].to_string()
|
||||
} else {
|
||||
format!("{}{}", CHAR_CODES[i], j)
|
||||
@@ -646,12 +654,26 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
} else if self.check_max_depth(&mut max_depth) {
|
||||
self.iter.pop_stack();
|
||||
self.iter.pop_stack();
|
||||
if is_xfy!(spec.get_spec()) {
|
||||
let left_directed_op = DirectedOp::Left(name, spec);
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
self.state_stack.push(TokenOrRedirect::Op(name, spec));
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
|
||||
0,
|
||||
left_directed_op,
|
||||
));
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Op(name, spec));
|
||||
self.state_stack.push(TokenOrRedirect::StackPop);
|
||||
} else { // is_yfx!
|
||||
let right_directed_op = DirectedOp::Right(name, spec);
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::StackPop);
|
||||
self.state_stack.push(TokenOrRedirect::Op(name, spec));
|
||||
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
|
||||
0,
|
||||
right_directed_op,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
let left_directed_op = DirectedOp::Left(name, spec);
|
||||
let right_directed_op = DirectedOp::Right(name, spec);
|
||||
@@ -660,6 +682,7 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
max_depth,
|
||||
left_directed_op,
|
||||
));
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Op(name, spec));
|
||||
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
|
||||
max_depth,
|
||||
@@ -838,54 +861,80 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
)
|
||||
}
|
||||
|
||||
fn check_for_seen(&mut self) -> Option<HeapCellValue> {
|
||||
if let Some(cell) = self.iter.next() {
|
||||
let is_cyclic = cell.get_forwarding_bit();
|
||||
fn check_for_seen(&mut self, max_depth: &mut usize) -> Option<HeapCellValue> {
|
||||
if let Some(mut orig_cell) = self.iter.next() {
|
||||
loop {
|
||||
let is_cyclic = orig_cell.get_forwarding_bit();
|
||||
|
||||
let cell = heap_bound_store(self.iter.heap, heap_bound_deref(self.iter.heap, cell));
|
||||
let cell = unmark_cell_bits!(cell);
|
||||
let cell = heap_bound_store(self.iter.heap, heap_bound_deref(self.iter.heap, orig_cell));
|
||||
let cell = unmark_cell_bits!(cell);
|
||||
|
||||
match self.var_names.get(&cell).cloned() {
|
||||
Some(var) if cell.is_var() => {
|
||||
// If cell is an unbound variable and maps to
|
||||
// a name via heap_locs, append the name to
|
||||
// the current output, and return None. None
|
||||
// short-circuits handle_heap_term.
|
||||
// self.iter.pop_stack();
|
||||
match self.var_names.get(&cell).cloned() {
|
||||
Some(var) if cell.is_var() => {
|
||||
// If cell is an unbound variable and maps to
|
||||
// a name via heap_locs, append the name to
|
||||
// the current output, and return None. None
|
||||
// short-circuits handle_heap_term.
|
||||
// self.iter.pop_stack();
|
||||
|
||||
let var_str = var.borrow().to_string();
|
||||
let var_str = var.borrow().to_string();
|
||||
|
||||
push_space_if_amb!(self, &var_str, {
|
||||
append_str!(self, &var_str);
|
||||
});
|
||||
|
||||
None
|
||||
}
|
||||
var_opt => {
|
||||
if is_cyclic && cell.is_compound(self.iter.heap) {
|
||||
// self-referential variables are marked "cyclic".
|
||||
match var_opt {
|
||||
Some(var) => {
|
||||
// If the term is bound to a named variable,
|
||||
// print the variable's name to output.
|
||||
let var_str = var.borrow().to_string();
|
||||
|
||||
push_space_if_amb!(self, &var_str, {
|
||||
append_str!(self, &var_str);
|
||||
});
|
||||
}
|
||||
None => {
|
||||
// otherwise, contract it to an ellipsis.
|
||||
push_space_if_amb!(self, "...", {
|
||||
append_str!(self, "...");
|
||||
});
|
||||
}
|
||||
}
|
||||
push_space_if_amb!(self, &var_str, {
|
||||
append_str!(self, &var_str);
|
||||
});
|
||||
|
||||
return None;
|
||||
}
|
||||
var_opt => {
|
||||
if is_cyclic && cell.is_compound(self.iter.heap) {
|
||||
// self-referential variables are marked "cyclic".
|
||||
match var_opt {
|
||||
Some(var) => {
|
||||
// If the term is bound to a named variable,
|
||||
// print the variable's name to output.
|
||||
let var_str = var.borrow().to_string();
|
||||
|
||||
Some(cell)
|
||||
push_space_if_amb!(self, &var_str, {
|
||||
append_str!(self, &var_str);
|
||||
});
|
||||
}
|
||||
None => {
|
||||
if self.max_depth == 0 || *max_depth == 0 {
|
||||
// otherwise, contract it to an ellipsis.
|
||||
push_space_if_amb!(self, "...", {
|
||||
append_str!(self, "...");
|
||||
});
|
||||
} else {
|
||||
debug_assert!(cell.is_ref());
|
||||
|
||||
// as usual, the WAM's
|
||||
// optimization of the Lis tag
|
||||
// (conflating the location of
|
||||
// the list and that of its
|
||||
// first element) needs
|
||||
// special consideration here
|
||||
// lest we find ourselves in
|
||||
// an infinite loop.
|
||||
if cell.get_tag() == HeapCellValueTag::Lis {
|
||||
*max_depth -= 1;
|
||||
}
|
||||
|
||||
let h = cell.get_value() as usize;
|
||||
self.iter.push_stack(IterStackLoc::iterable_loc(h, HeapOrStackTag::Heap));
|
||||
|
||||
if let Some(cell) = self.iter.next() {
|
||||
orig_cell = cell;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return None;
|
||||
}
|
||||
|
||||
return Some(cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -1024,7 +1073,7 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
|
||||
match self.op_dir.get(&(atom!("rdiv"), Fixity::In)) {
|
||||
Some(op_desc) => {
|
||||
if r.denominator().is_one() {
|
||||
if r.is_int() {
|
||||
let output_str = format!("{}", r);
|
||||
|
||||
push_space_if_amb!(self, &output_str, {
|
||||
@@ -1093,10 +1142,19 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
}
|
||||
|
||||
// returns true if max_depth limit is reached and ellipsis is printed.
|
||||
fn print_string_as_functor(&mut self, focus: usize, max_depth: usize) -> bool {
|
||||
fn print_string_as_functor(&mut self, focus: usize, max_depth: &mut usize) -> bool {
|
||||
let iter = HeapPStrIter::new(self.iter.heap, focus);
|
||||
|
||||
for (char_count, c) in iter.chars().enumerate() {
|
||||
if self.check_max_depth(max_depth) {
|
||||
if char_count > 0 {
|
||||
self.state_stack.push(TokenOrRedirect::Close);
|
||||
}
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
return true;
|
||||
}
|
||||
|
||||
append_str!(self, "'.'");
|
||||
push_char!(self, '(');
|
||||
|
||||
@@ -1104,16 +1162,13 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
push_char!(self, ',');
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Close);
|
||||
|
||||
if max_depth >= char_count + 1 {
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
// proper strings are terminal so there's no need for max_depth to
|
||||
// be a mutable ref here.
|
||||
fn print_proper_string(&mut self, focus: usize, max_depth: usize) {
|
||||
push_char!(self, '"');
|
||||
|
||||
@@ -1201,16 +1256,14 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
self.at_cdr(",");
|
||||
self.remove_list_children(focus.value() as usize);
|
||||
|
||||
if !self.print_string_as_functor(focus.value() as usize, max_depth) {
|
||||
if !self.print_string_as_functor(focus.value() as usize, &mut max_depth) {
|
||||
if end_cell == empty_list_as_cell!() {
|
||||
if !self.at_cdr("") {
|
||||
append_str!(self, "[]");
|
||||
}
|
||||
} else {
|
||||
self.state_stack
|
||||
.push(TokenOrRedirect::FunctorRedirect(max_depth));
|
||||
self.iter
|
||||
.push_stack(IterStackLoc::iterable_loc(end_h, HeapOrStackTag::Heap));
|
||||
self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth));
|
||||
self.iter.push_stack(IterStackLoc::iterable_loc(end_h, HeapOrStackTag::Heap));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -1228,49 +1281,27 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
let switch = self.close_list(switch);
|
||||
|
||||
let (h, offset) = pstr_loc_and_offset(self.iter.heap, focus.value() as usize);
|
||||
let pstr = cell_as_string!(self.iter.heap[h]);
|
||||
|
||||
let pstr = pstr.as_str_from(offset.get_num() as usize);
|
||||
let offset = offset.get_num() as usize;
|
||||
let tag = value.get_tag();
|
||||
|
||||
if tag == HeapCellValueTag::PStrOffset {
|
||||
let end_h = if tag == HeapCellValueTag::PStrOffset {
|
||||
// remove the fixnum offset from the iterator stack so we don't
|
||||
// print an extraneous number. pstr offset value cells are never
|
||||
// used by the iterator to mark cyclic terms so the removal is safe.
|
||||
self.iter.pop_stack();
|
||||
}
|
||||
|
||||
if max_depth > 0 && pstr.chars().count() + 1 >= max_depth {
|
||||
if tag != HeapCellValueTag::PStrOffset && tag != HeapCellValueTag::CStr {
|
||||
self.iter.pop_stack();
|
||||
}
|
||||
Some(end_h)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if !self.max_depth_exhausted(max_depth) {
|
||||
let pstr = cell_as_string!(self.iter.heap[h]);
|
||||
self.state_stack.push(TokenOrRedirect::CommaSeparatedCharList(CommaSeparatedCharList {
|
||||
pstr, offset, max_depth, end_cell, end_h,
|
||||
}));
|
||||
} else {
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
self.state_stack.push(TokenOrRedirect::HeadTailSeparator);
|
||||
} else if end_cell != empty_list_as_cell!() {
|
||||
if tag == HeapCellValueTag::PStrOffset {
|
||||
self.iter.push_stack(IterStackLoc::iterable_loc(end_h, HeapOrStackTag::Heap));
|
||||
}
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth));
|
||||
self.state_stack.push(TokenOrRedirect::HeadTailSeparator);
|
||||
}
|
||||
|
||||
let state_stack_len = self.state_stack.len();
|
||||
|
||||
for (char_count, c) in pstr.chars().enumerate() {
|
||||
if max_depth > 0 && char_count + 1 >= max_depth {
|
||||
break;
|
||||
}
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Comma);
|
||||
self.state_stack.push(TokenOrRedirect::Char(c));
|
||||
}
|
||||
|
||||
self.state_stack[state_stack_len ..].reverse();
|
||||
|
||||
if let Some(TokenOrRedirect::Comma) = self.state_stack.last() {
|
||||
self.state_stack.pop();
|
||||
}
|
||||
|
||||
self.open_list(switch);
|
||||
@@ -1342,11 +1373,9 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
|
||||
let switch = self.close_list(cell);
|
||||
|
||||
self.state_stack
|
||||
.push(TokenOrRedirect::FunctorRedirect(max_depth));
|
||||
self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth));
|
||||
self.state_stack.push(TokenOrRedirect::HeadTailSeparator); // bar
|
||||
self.state_stack
|
||||
.push(TokenOrRedirect::FunctorRedirect(max_depth + 1));
|
||||
self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth + 1));
|
||||
|
||||
self.open_list(switch);
|
||||
}
|
||||
@@ -1367,10 +1396,10 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
if self.numbervars && arity == 1 && name == atom!("$VAR") {
|
||||
!self.iter.immediate_leaf_has_property(|addr| {
|
||||
match Number::try_from(addr) {
|
||||
Ok(Number::Integer(n)) => &*n >= &Integer::from(0),
|
||||
Ok(Number::Integer(n)) => (*n).sign() == Sign::Positive,
|
||||
Ok(Number::Fixnum(n)) => n.get_num() >= 0,
|
||||
Ok(Number::Float(f)) => f >= OrderedFloat(0f64),
|
||||
Ok(Number::Rational(r)) => &*r >= &Rational::from(0),
|
||||
Ok(Number::Rational(r)) => (*r).sign() == Sign::Positive,
|
||||
_ => false,
|
||||
}
|
||||
}) && needs_bracketing(op_desc, op)
|
||||
@@ -1502,20 +1531,68 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
}
|
||||
}
|
||||
|
||||
fn print_comma_separated_char_list(&mut self, char_list: CommaSeparatedCharList) {
|
||||
let CommaSeparatedCharList { pstr, offset, max_depth, end_cell, end_h } = char_list;
|
||||
let pstr_str = pstr.as_str_from(offset);
|
||||
|
||||
if let Some(c) = pstr_str.chars().next() {
|
||||
let offset = offset + c.len_utf8();
|
||||
|
||||
if !self.max_depth_exhausted(max_depth) {
|
||||
self.state_stack.push(TokenOrRedirect::CommaSeparatedCharList(CommaSeparatedCharList {
|
||||
pstr,
|
||||
offset,
|
||||
max_depth: max_depth.saturating_sub(1),
|
||||
end_cell,
|
||||
end_h,
|
||||
}));
|
||||
|
||||
let max_depth_allows = self.max_depth == 0 || max_depth > 1;
|
||||
|
||||
if max_depth_allows && pstr_str.chars().skip(1).next().is_some() {
|
||||
self.state_stack.push(TokenOrRedirect::Comma);
|
||||
}
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::Char(c));
|
||||
} else {
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
self.state_stack.push(TokenOrRedirect::HeadTailSeparator);
|
||||
}
|
||||
} else if self.max_depth_exhausted(max_depth) {
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
self.state_stack.push(TokenOrRedirect::HeadTailSeparator);
|
||||
} else if end_cell != empty_list_as_cell!() {
|
||||
if let Some(end_h) = end_h {
|
||||
self.iter.push_stack(IterStackLoc::iterable_loc(end_h, HeapOrStackTag::Heap));
|
||||
}
|
||||
|
||||
self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth + 1));
|
||||
self.state_stack.push(TokenOrRedirect::HeadTailSeparator);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_heap_term(
|
||||
&mut self,
|
||||
op: Option<DirectedOp>,
|
||||
is_functor_redirect: bool,
|
||||
max_depth: usize,
|
||||
mut max_depth: usize,
|
||||
) {
|
||||
let negated_operand = negated_op_needs_bracketing(&self.iter, self.op_dir, &op);
|
||||
|
||||
let addr = match self.check_for_seen(&mut max_depth) {
|
||||
Some(addr) => addr,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let print_struct = |printer: &mut Self, name: Atom, arity: usize| {
|
||||
if name == atom!("[]") && arity == 0 {
|
||||
if let Some(TokenOrRedirect::CloseList(_)) = printer.state_stack.last() {
|
||||
if printer.at_cdr("") {
|
||||
return;
|
||||
match printer.state_stack.last() {
|
||||
Some(TokenOrRedirect::CloseList(_) | TokenOrRedirect::ChildCloseList) => {
|
||||
if printer.at_cdr("") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
append_str!(printer, "[]");
|
||||
@@ -1568,16 +1645,14 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
}
|
||||
};
|
||||
|
||||
let addr = match self.check_for_seen() {
|
||||
Some(addr) => addr,
|
||||
None => return,
|
||||
};
|
||||
|
||||
if !addr.is_var()
|
||||
&& !addr.is_compound(&self.iter.heap)
|
||||
&& self.max_depth_exhausted(max_depth)
|
||||
{
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
if !(addr == atom_as_cell!(atom!("[]")) && self.at_cdr("")) {
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1731,6 +1806,13 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
|
||||
TokenOrRedirect::Space => push_char!(self, ' '),
|
||||
TokenOrRedirect::LeftCurly => push_char!(self, '{'),
|
||||
TokenOrRedirect::RightCurly => push_char!(self, '}'),
|
||||
TokenOrRedirect::StackPop => {
|
||||
self.iter.pop_stack();
|
||||
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
|
||||
}
|
||||
TokenOrRedirect::CommaSeparatedCharList(char_list) => {
|
||||
self.print_comma_separated_char_list(char_list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
58
src/http.rs
58
src/http.rs
@@ -1,57 +1,23 @@
|
||||
use bytes::Bytes;
|
||||
use http_body_util::Full;
|
||||
use hyper::service::Service;
|
||||
use hyper::{body::Incoming as IncomingBody, Request, Response};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
use std::sync::{Arc, Mutex, Condvar};
|
||||
use std::io::BufRead;
|
||||
|
||||
use warp::http;
|
||||
|
||||
pub struct HttpListener {
|
||||
pub incoming: std::sync::mpsc::Receiver<HttpRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct HttpRequest {
|
||||
pub request: Request<IncomingBody>,
|
||||
pub request_data: HttpRequestData,
|
||||
pub response: HttpResponse,
|
||||
}
|
||||
|
||||
pub type HttpResponse = Arc<(Mutex<bool>, Mutex<Option<Response<Full<Bytes>>>>, Condvar)>;
|
||||
pub type HttpResponse = Arc<(Mutex<bool>, Mutex<Option<warp::reply::Response>>, Condvar)>;
|
||||
|
||||
pub struct HttpService {
|
||||
pub tx: std::sync::mpsc::SyncSender<HttpRequest>,
|
||||
}
|
||||
|
||||
impl Service<Request<IncomingBody>> for HttpService {
|
||||
type Response = Response<Full<Bytes>>;
|
||||
type Error = hyper::Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
|
||||
|
||||
fn call(self: &HttpService, req: Request<IncomingBody>) -> Self::Future {
|
||||
// new connection!
|
||||
// we send the Request info to Prolog
|
||||
let response = Arc::new((Mutex::new(false), Mutex::new(None), Condvar::new()));
|
||||
let http_request = HttpRequest {
|
||||
request: req,
|
||||
response: Arc::clone(&response)
|
||||
};
|
||||
self.tx.send(http_request).unwrap();
|
||||
|
||||
// we wait for the Response info from Prolog
|
||||
{
|
||||
let (ready, _response, cvar) = &*response;
|
||||
let mut ready = ready.lock().unwrap();
|
||||
while !*ready {
|
||||
ready = cvar.wait(ready).unwrap();
|
||||
}
|
||||
}
|
||||
{
|
||||
let (_, response, _) = &*response;
|
||||
let response = response.lock().unwrap().take();
|
||||
let res = response.expect("Data race error in HTTP Server");
|
||||
Box::pin(async move {
|
||||
Ok(res)
|
||||
})
|
||||
}
|
||||
}
|
||||
pub struct HttpRequestData {
|
||||
pub method: http::Method,
|
||||
pub headers: http::HeaderMap,
|
||||
pub path: String,
|
||||
pub query: String,
|
||||
pub body: Box<dyn BufRead + Send>,
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ call(_, _, _, _, _, _, _, _, _).
|
||||
% while others can be set with `set_prolog_flag/2`.
|
||||
%
|
||||
% The flags that Scryer Prolog support are:
|
||||
%
|
||||
%
|
||||
% * `max_arity`: The max arity a predicate can have in Prolog. On Scryer is set to 1023. Read only.
|
||||
% * `bounded`: `true` if integer arithmethic is bounded between some min/max values. On Scryer is always set
|
||||
% to `false` since it supports unbounded integer arithmethic. Read only.
|
||||
@@ -184,7 +184,7 @@ answer_write_options(Value) :-
|
||||
%% set_prolog_flag(Flag, Value).
|
||||
%
|
||||
% Sets the internal value of the flag. To see the list of flags supported by Scryer Prolog,
|
||||
% check `current_prolog_flag/2`. The flags that are read only will fail if you try to change their values
|
||||
% check `current_prolog_flag/2`. The flags that are read only will fail if you try to change their values
|
||||
set_prolog_flag(Flag, Value) :-
|
||||
(var(Flag) ; var(Value)),
|
||||
throw(error(instantiation_error, set_prolog_flag/2)). % 8.17.1.3 a, b
|
||||
@@ -574,26 +574,30 @@ parse_write_options(Options, OptionValues, Stub) :-
|
||||
|
||||
|
||||
parse_write_options_(double_quotes(DoubleQuotes), double_quotes-DoubleQuotes) :-
|
||||
( nonvar(DoubleQuotes),
|
||||
lists:member(DoubleQuotes, [true, false]),
|
||||
( var(DoubleQuotes) ->
|
||||
throw(error(instantiation_error, _))
|
||||
; lists:member(DoubleQuotes, [true, false]),
|
||||
!
|
||||
; throw(error(domain_error(write_option, double_quotes(DoubleQuotes)), _))
|
||||
).
|
||||
parse_write_options_(ignore_ops(IgnoreOps), ignore_ops-IgnoreOps) :-
|
||||
( nonvar(IgnoreOps),
|
||||
lists:member(IgnoreOps, [true, false]),
|
||||
( var(IgnoreOps) ->
|
||||
throw(error(instantiation_error, _))
|
||||
; lists:member(IgnoreOps, [true, false]),
|
||||
!
|
||||
; throw(error(domain_error(write_option, ignore_ops(IgnoreOps)), _))
|
||||
).
|
||||
parse_write_options_(quoted(Quoted), quoted-Quoted) :-
|
||||
( nonvar(Quoted),
|
||||
lists:member(Quoted, [true, false]),
|
||||
( var(Quoted) ->
|
||||
throw(error(instantiation_error, _))
|
||||
; lists:member(Quoted, [true, false]),
|
||||
!
|
||||
; throw(error(domain_error(write_option, quoted(Quoted)), _))
|
||||
).
|
||||
parse_write_options_(numbervars(NumberVars), numbervars-NumberVars) :-
|
||||
( nonvar(NumberVars),
|
||||
lists:member(NumberVars, [true, false]),
|
||||
( var(NumberVars) ->
|
||||
throw(error(instantiation_error, _))
|
||||
; lists:member(NumberVars, [true, false]),
|
||||
!
|
||||
; throw(error(domain_error(write_option, numbervars(NumberVars)), _))
|
||||
).
|
||||
@@ -601,7 +605,9 @@ parse_write_options_(variable_names(VNNames), variable_names-VNNames) :-
|
||||
must_be_var_names_list(VNNames),
|
||||
!.
|
||||
parse_write_options_(max_depth(MaxDepth), max_depth-MaxDepth) :-
|
||||
( integer(MaxDepth),
|
||||
( var(MaxDepth) ->
|
||||
throw(error(instantiation_error, _))
|
||||
; integer(MaxDepth),
|
||||
MaxDepth >= 0,
|
||||
!
|
||||
; throw(error(domain_error(write_option, max_depth(MaxDepth)), _))
|
||||
@@ -715,30 +721,9 @@ parse_read_term_options(Options, OptionValues, Stub) :-
|
||||
parse_options_list(Options, builtins:parse_read_term_options_, DefaultOptions, OptionValues, Stub).
|
||||
|
||||
|
||||
parse_read_term_options_(singletons(Vars), singletons-Vars) :-
|
||||
( ( var(Vars)
|
||||
; '$skip_max_list'(_, _, Vars, Rs),
|
||||
Rs == []
|
||||
) ->
|
||||
!
|
||||
; throw(error(domain_error(read_option, singletons(Vars)), read_term/2))
|
||||
).
|
||||
parse_read_term_options_(variables(Vars), variables-Vars) :-
|
||||
( ( var(Vars)
|
||||
; '$skip_max_list'(_, _, Vars, Rs),
|
||||
Rs == []
|
||||
) ->
|
||||
!
|
||||
; throw(error(domain_error(read_option, variables(Vars)), read_term/2))
|
||||
).
|
||||
parse_read_term_options_(variable_names(Vars), variable_names-Vars) :-
|
||||
( ( var(Vars)
|
||||
; '$skip_max_list'(_, _, Vars, Rs),
|
||||
Rs == []
|
||||
) ->
|
||||
!
|
||||
; throw(error(domain_error(read_option, variable_names(Vars)), read_term/2))
|
||||
).
|
||||
parse_read_term_options_(singletons(Vars), singletons-Vars) :- !.
|
||||
parse_read_term_options_(variables(Vars), variables-Vars) :- !.
|
||||
parse_read_term_options_(variable_names(Vars), variable_names-Vars) :- !.
|
||||
parse_read_term_options_(E,_) :-
|
||||
throw(error(domain_error(read_option, E), _)).
|
||||
|
||||
@@ -748,7 +733,7 @@ parse_read_term_options_(E,_) :-
|
||||
% Read Term from the stream Stream. It supports several options:
|
||||
% * `variables(-Vars)` unifies Vars with a list of variables in the term. Similar to do `term_variables/2` with the new term.
|
||||
% * `variable_names(-Vars)` unifies Vars with a list `Name=Var` with Name describing the variable name and Var the variable itself that appears in Term.
|
||||
% * `singletons` similar to `variable_names` but only reports variables occurring only once in Term.
|
||||
% * `singletons` similar to `variable_names` but only reports variables occurring only once in Term.
|
||||
read_term(Stream, Term, Options) :-
|
||||
parse_read_term_options(Options, [Singletons, VariableNames, Variables], read_term/3),
|
||||
'$read_term'(Stream, Term, Singletons, Variables, VariableNames).
|
||||
@@ -1616,7 +1601,7 @@ atom_concat(Atom_1, Atom_2, Atom_12) :-
|
||||
%% sub_atom(+Atom, ?Before, ?Length, ?After, ?SubAtom).
|
||||
%
|
||||
% Relates an atom to a subatom inside with some key properties:
|
||||
%
|
||||
%
|
||||
% * SubAtom starts at Before characters (0-based) from Atom
|
||||
% * SubAtom has Length characters
|
||||
% * After SubAtom there are After characters in Atom
|
||||
@@ -2241,4 +2226,7 @@ nl(Stream) :-
|
||||
%
|
||||
% Throws an exception of the following structure: `error(ErrorTerm, ImpDef)`.
|
||||
error(Error_term, Imp_def) :-
|
||||
throw(error(Error_term, Imp_def)).
|
||||
( var(Error_term) ->
|
||||
throw(error(instantiation_error, error/2))
|
||||
; throw(error(Error_term, Imp_def))
|
||||
).
|
||||
|
||||
@@ -7,7 +7,7 @@ arguments are different terms.
|
||||
|
||||
:- use_module(library(atts)).
|
||||
:- use_module(library(dcgs)).
|
||||
:- use_module(library(lists), [append/3]).
|
||||
:- use_module(library(lists), [append/3, maplist/3]).
|
||||
|
||||
:- attribute dif/1.
|
||||
|
||||
@@ -23,6 +23,32 @@ dif_set_variables([Var|Vars], X, Y) :-
|
||||
put_dif_att(Var, X, Y),
|
||||
dif_set_variables(Vars, X, Y).
|
||||
|
||||
remove_goal([], _, []).
|
||||
remove_goal([G0|G0s], Goal0, Goals) :-
|
||||
( G0 == Goal0 ->
|
||||
remove_goal(G0s, Goal0, Goals)
|
||||
; Goals = [G0|Goals1],
|
||||
remove_goal(G0s, Goal0, Goals1)
|
||||
).
|
||||
|
||||
vars_remove_goal([], _).
|
||||
vars_remove_goal([Var|Vars], Goal0) :-
|
||||
get_atts(Var, +dif(Goals0)),
|
||||
remove_goal(Goals0, Goal0, Goals),
|
||||
( Goals = [] ->
|
||||
put_atts(Var, -dif(_))
|
||||
; put_atts(Var, +dif(Goals))
|
||||
),
|
||||
vars_remove_goal(Vars, Goal0).
|
||||
|
||||
reinforce_goal(Goal0, Goal) :-
|
||||
Goal = (
|
||||
term_variables(Goal0, Vars),
|
||||
dif:vars_remove_goal(Vars, Goal0),
|
||||
Goal0 = (L \== R),
|
||||
dif(L, R)
|
||||
).
|
||||
|
||||
append_goals([], _).
|
||||
append_goals([Var|Vars], Goals) :-
|
||||
( get_atts(Var, +dif(VarGoals)) ->
|
||||
@@ -34,9 +60,10 @@ append_goals([Var|Vars], Goals) :-
|
||||
append_goals(Vars, Goals).
|
||||
|
||||
verify_attributes(Var, Value, Goals) :-
|
||||
( get_atts(Var, +dif(Goals)) ->
|
||||
( get_atts(Var, +dif(Goals0)) ->
|
||||
term_variables(Value, ValueVars),
|
||||
append_goals(ValueVars, Goals)
|
||||
append_goals(ValueVars, Goals0),
|
||||
maplist(reinforce_goal, Goals0, Goals)
|
||||
; Goals = []
|
||||
).
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
*/
|
||||
|
||||
/** This library provides an starting point to build HTTP server based applications.
|
||||
It is based on [Hyper](https://hyper.rs/), which allows for HTTP/1.0, HTTP/1.1 and HTTP/2. However,
|
||||
some advanced features that Hyper provides are still not accesible.
|
||||
It is based on [Warp](https://github.com/seanmonstar/warp), which allows for HTTP/1.0, HTTP/1.1 and HTTP/2. However,
|
||||
some advanced features that Warp provides are still not accesible.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -46,7 +46,6 @@ recommeded to use the helper predicates, which are easier to understand and clea
|
||||
Some things that are still missing:
|
||||
|
||||
- Read forms in multipart format
|
||||
- HTTP Basic Auth
|
||||
- Session handling via cookies
|
||||
- HTML Templating (but you can use [Teruel](https://github.com/aarroyoc/teruel/), [Marquete](https://github.com/aarroyoc/marquete/) or [Djota](https://github.com/aarroyoc/djota) for that)
|
||||
*/
|
||||
@@ -54,14 +53,19 @@ Some things that are still missing:
|
||||
|
||||
:- module(http_server, [
|
||||
http_listen/2,
|
||||
http_listen/3,
|
||||
http_headers/2,
|
||||
http_status_code/2,
|
||||
http_body/2,
|
||||
http_redirect/2,
|
||||
http_query/3
|
||||
http_query/3,
|
||||
http_basic_auth/4
|
||||
]).
|
||||
|
||||
:- meta_predicate http_listen(?, :).
|
||||
:- meta_predicate http_listen(?, :, ?).
|
||||
|
||||
:- meta_predicate http_basic_auth(:, :, ?, ?).
|
||||
|
||||
:- use_module(library(charsio)).
|
||||
:- use_module(library(crypto)).
|
||||
@@ -74,25 +78,58 @@ Some things that are still missing:
|
||||
|
||||
%% http_listen(+Port, +Handlers).
|
||||
%
|
||||
% Listens for HTTP connections on port Port. Each handler on the list Handlers should be of the form: `HttpVerb(PathUnification, Predicate)`.
|
||||
% For example: `get(user/User, get_info(User))` will match an HTTP request that is a GET, the path unifies with /user/User (where User is a variable)
|
||||
% and it will call `get_info` with three arguments: an `http_request` term, an `http_response` term and User.
|
||||
% Equivalent to `http_listen(Port, Handlers, [])`.
|
||||
http_listen(Port, Module:Handlers0) :-
|
||||
must_be(integer, Port),
|
||||
must_be(list, Handlers0),
|
||||
maplist(module_qualification(Module), Handlers0, Handlers),
|
||||
http_listen_(Port, Handlers).
|
||||
http_listen_(Port, Handlers, []).
|
||||
|
||||
%% http_listen(+Port, +Handlers, +Options).
|
||||
%
|
||||
% Listens for HTTP connections on port Port. Each handler on the list Handlers should be of the form: `HttpVerb(PathUnification, Predicate)`.
|
||||
% For example: `get(user/User, get_info(User))` will match an HTTP request that is a GET, the path unifies with /user/User (where User is a variable)
|
||||
% and it will call `get_info` with three arguments: an `http_request` term, an `http_response` term and User.
|
||||
%
|
||||
% The following options are supported:
|
||||
%
|
||||
% - `tls_key(+Key)` - a TLS key for HTTPS (string)
|
||||
% - `tls_cert(+Cert)` - a TLS cert for HTTPS (string)
|
||||
% - `content_length_limit(+Limit)` - maximum length (in bytes) for the incoming bodies. By default, 32KB.
|
||||
%
|
||||
% In order to have a HTTPS server (instead of plain HTTP), both `tls_key` and `tls_cert` options must be provided.
|
||||
http_listen(Port, Module:Handlers0, Options) :-
|
||||
must_be(integer, Port),
|
||||
must_be(list, Handlers0),
|
||||
must_be(list, Options),
|
||||
maplist(module_qualification(Module), Handlers0, Handlers),
|
||||
http_listen_(Port, Handlers, Options).
|
||||
|
||||
module_qualification(M, H0, H) :-
|
||||
H0 =.. [Method, Path, Goal],
|
||||
H =.. [Method, Path, M:Goal].
|
||||
|
||||
http_listen_(Port, Handlers) :-
|
||||
http_listen_(Port, Handlers, Options) :-
|
||||
parse_options(Options, TLSKey, TLSCert, ContentLengthLimit),
|
||||
phrase(format_("0.0.0.0:~d", [Port]), Addr),
|
||||
'$http_listen'(Addr, HttpListener),!,
|
||||
'$http_listen'(Addr, HttpListener, TLSKey, TLSCert, ContentLengthLimit),!,
|
||||
format("Listening at ~s\n", [Addr]),
|
||||
http_loop(HttpListener, Handlers).
|
||||
|
||||
parse_options(Options, TLSKey, TLSCert, ContentLengthLimit) :-
|
||||
member_option_default(tls_key, Options, "", TLSKey),
|
||||
member_option_default(tls_cert, Options, "", TLSCert),
|
||||
member_option_default(content_length_limit, Options, 32768, ContentLengthLimit),
|
||||
must_be(integer, ContentLengthLimit).
|
||||
|
||||
member_option_default(Key, List, _Default, Value) :-
|
||||
X =.. [Key, Value],
|
||||
member(X, List).
|
||||
member_option_default(Key, List, Default, Default) :-
|
||||
X =.. [Key, _],
|
||||
\+ member(X, List).
|
||||
|
||||
|
||||
http_loop(HttpListener, Handlers) :-
|
||||
'$http_accept'(HttpListener, RequestMethod, RequestPath, RequestHeaders, RequestQuery, RequestStream, ResponseHandle),
|
||||
current_time(Time),
|
||||
@@ -114,7 +151,7 @@ http_loop(HttpListener, Handlers) :-
|
||||
)
|
||||
; (
|
||||
'$http_answer'(ResponseHandle, 404, [], ResponseStream),
|
||||
call_cleanup(format(ResponseStream, "Not Found"), close(ResponseStream)))
|
||||
call_cleanup(format(ResponseStream, "Not Found", []), close(ResponseStream)))
|
||||
),
|
||||
http_loop(HttpListener, Handlers).
|
||||
|
||||
@@ -263,25 +300,21 @@ http_query(http_request(_, _, Queries), Key, Value) :- member(Key-Value, Queries
|
||||
|
||||
parse_queries([Key-Value|Queries]) -->
|
||||
string_without("=", Key0),
|
||||
{
|
||||
phrase(url_decode(Key), Key0)
|
||||
},
|
||||
"=",
|
||||
string_without("&", Value0),
|
||||
{
|
||||
phrase(url_decode(Value), Value0)
|
||||
},
|
||||
"&",
|
||||
parse_queries(Queries).
|
||||
parse_queries(Queries),
|
||||
{
|
||||
phrase(url_decode(Key), Key0),
|
||||
phrase(url_decode(Value), Value0)
|
||||
}.
|
||||
|
||||
parse_queries([Key-Value]) -->
|
||||
string_without("=", Key0),
|
||||
{
|
||||
phrase(url_decode(Key), Key0)
|
||||
},
|
||||
"=",
|
||||
string_without(" ", Value0),
|
||||
{
|
||||
phrase(url_decode(Key), Key0),
|
||||
phrase(url_decode(Value), Value0)
|
||||
}.
|
||||
|
||||
@@ -292,9 +325,13 @@ parse_queries([]) -->
|
||||
url_decode([Char|Chars]) -->
|
||||
[Char],
|
||||
{
|
||||
Char \= '%'
|
||||
Char \= '%',
|
||||
Char \= (+)
|
||||
},
|
||||
url_decode(Chars).
|
||||
url_decode([' '|Chars]) -->
|
||||
"+",
|
||||
url_decode(Chars).
|
||||
url_decode([Char|Chars]) -->
|
||||
"%",
|
||||
[A],
|
||||
@@ -352,3 +389,49 @@ url_decode([Char|Chars]) -->
|
||||
url_decode(Chars).
|
||||
|
||||
url_decode([]) --> [].
|
||||
|
||||
%% http_basic_auth(+LoginPredicate, +Handler, +Request, -Response)
|
||||
%
|
||||
% Metapredicate that wraps an existing Handler with an HTTP Basic Auth flow.
|
||||
% Checks if a given user + password is authorized to execute that handler, returning 401
|
||||
% if it's not satisfied.
|
||||
%
|
||||
% `LoginPredicate` must be a predicate of arity 2 that takes a User and a Password.
|
||||
% `Handler` will have, in addition to the Request and Response arguments, a User argument
|
||||
% containing the User given in the authentication.
|
||||
%
|
||||
% Example:
|
||||
%
|
||||
% ```
|
||||
% main :-
|
||||
% http_listen(8800,[get('/', http_basic_auth(login, inside_handler("data")))]).
|
||||
%
|
||||
% login(User, Pass) :-
|
||||
% User = "aarroyoc",
|
||||
% Pass = "123456".
|
||||
%
|
||||
% inside_handler(Data, User, Request, Response) :-
|
||||
% http_body(Response, text(User)).
|
||||
% ```
|
||||
http_basic_auth(LoginPredicate, Handler, Request, Response) :-
|
||||
http_headers(Request, Headers),
|
||||
member("authorization"-AuthorizationStr, Headers),
|
||||
append("Basic ", Coded, AuthorizationStr),
|
||||
chars_base64(UserPass, Coded, []),
|
||||
append(User, [':'|Password], UserPass),
|
||||
(
|
||||
call(LoginPredicate, User, Password) ->
|
||||
call(Handler, User, Request, Response)
|
||||
; http_basic_auth_unauthorized_response(Response)
|
||||
).
|
||||
|
||||
http_basic_auth(_LoginPredicate, _Handler, Request, Response) :-
|
||||
http_headers(Request, Headers),
|
||||
\+ member("authorization"-_, Headers),
|
||||
http_basic_auth_unauthorized_response(Response).
|
||||
|
||||
http_basic_auth_unauthorized_response(Response) :-
|
||||
http_status_code(Response, 401),
|
||||
http_headers(Response, ["www-authenticate"-"Basic realm=\"Scryer Prolog\", charset=\"UTF-8\""]),
|
||||
http_body(Response, text("Unauthorized")).
|
||||
|
||||
|
||||
@@ -214,27 +214,6 @@ run_cleaners_without_handling(Cp) :-
|
||||
|
||||
% call_with_inference_limit
|
||||
|
||||
:- non_counted_backtracking end_block/4.
|
||||
|
||||
end_block(_, Bb, NBb, _L) :-
|
||||
'$clean_up_block'(NBb),
|
||||
'$reset_block'(Bb).
|
||||
end_block(B, _Bb, NBb, L) :-
|
||||
'$install_inference_counter'(B, L, _),
|
||||
'$reset_block'(NBb),
|
||||
'$fail'.
|
||||
|
||||
:- non_counted_backtracking handle_ile/3.
|
||||
|
||||
handle_ile(B, inference_limit_exceeded(B), R) :-
|
||||
!,
|
||||
R = inference_limit_exceeded,
|
||||
'$pop_ball_stack'.
|
||||
handle_ile(B, _, _) :-
|
||||
'$remove_call_policy_check'(B),
|
||||
'$pop_from_ball_stack',
|
||||
'$unwind_stack'.
|
||||
|
||||
:- meta_predicate(call_with_inference_limit(0, ?, ?)).
|
||||
|
||||
:- non_counted_backtracking call_with_inference_limit/3.
|
||||
@@ -257,8 +236,6 @@ call_with_inference_limit(G, L, R) :-
|
||||
call_with_inference_limit(G, L, R, Bb, B),
|
||||
'$remove_call_policy_check'(B).
|
||||
|
||||
install_inference_counter(B, L, Count0) :-
|
||||
'$install_inference_counter'(B, L, Count0).
|
||||
|
||||
:- meta_predicate(call_with_inference_limit(0,?,?,?,?)).
|
||||
|
||||
@@ -266,23 +243,34 @@ install_inference_counter(B, L, Count0) :-
|
||||
|
||||
call_with_inference_limit(G, L, R, Bb, B) :-
|
||||
'$install_new_block'(NBb),
|
||||
'$install_inference_counter'(B, L, Count0),
|
||||
'$install_inference_counter'(NBb, L, Count0),
|
||||
'$call_with_inference_counting'(call(G)),
|
||||
'$inference_level'(R, B),
|
||||
'$remove_inference_counter'(B, Count1),
|
||||
'$remove_inference_counter'(NBb, Count1),
|
||||
Diff is L - (Count1 - Count0),
|
||||
end_block(B, Bb, NBb, Diff).
|
||||
( '$clean_up_block'(NBb),
|
||||
'$reset_block'(Bb)
|
||||
; '$install_inference_counter'(NBb, Diff, _),
|
||||
'$reset_block'(NBb),
|
||||
'$fail'
|
||||
).
|
||||
call_with_inference_limit(_, _, R, Bb, B) :-
|
||||
( '$inference_limit_exceeded' ->
|
||||
R = inference_limit_exceeded
|
||||
; true
|
||||
),
|
||||
'$get_current_block'(NBb),
|
||||
'$remove_inference_counter'(NBb, _),
|
||||
'$reset_block'(Bb),
|
||||
'$remove_inference_counter'(B, _),
|
||||
( '$get_ball'(Ball),
|
||||
'$remove_call_policy_check'(B),
|
||||
( '$get_ball'(_),
|
||||
'$push_ball_stack',
|
||||
'$get_cp'(Cp),
|
||||
'$set_cp_by_default'(Cp)
|
||||
; '$remove_call_policy_check'(B),
|
||||
'$fail'
|
||||
),
|
||||
handle_ile(B, Ball, R).
|
||||
'$set_cp_by_default'(Cp),
|
||||
'$pop_from_ball_stack',
|
||||
'$unwind_stack'
|
||||
; nonvar(R)
|
||||
).
|
||||
|
||||
%% partial_string(String, L, L0)
|
||||
%
|
||||
|
||||
147
src/lib/pio.pl
147
src/lib/pio.pl
@@ -9,6 +9,7 @@
|
||||
|
||||
:- module(pio, [phrase_from_file/2,
|
||||
phrase_from_file/3,
|
||||
phrase_from_stream/2,
|
||||
phrase_to_file/2,
|
||||
phrase_to_file/3,
|
||||
phrase_to_stream/2
|
||||
@@ -17,16 +18,30 @@
|
||||
:- use_module(library(dcgs)).
|
||||
:- use_module(library(error)).
|
||||
:- use_module(library(freeze)).
|
||||
:- use_module(library(iso_ext), [setup_call_cleanup/3, partial_string/3]).
|
||||
:- use_module(library(lists), [member/2, maplist/2]).
|
||||
:- use_module(library(gensym)).
|
||||
:- use_module(library(iso_ext), [
|
||||
bb_get/2, bb_put/2, setup_call_cleanup/3, partial_string/3, partial_string_tail/2
|
||||
]).
|
||||
:- use_module(library(lists), [append/3, length/2, member/2, maplist/2]).
|
||||
:- use_module(library(charsio), [get_n_chars/3]).
|
||||
|
||||
:- meta_predicate(phrase_from_file(2, ?)).
|
||||
:- meta_predicate(phrase_from_file(2, ?, ?)).
|
||||
:- meta_predicate(phrase_from_stream(2, ?)).
|
||||
:- meta_predicate(phrase_to_file(2, ?)).
|
||||
:- meta_predicate(phrase_to_file(2, ?, ?)).
|
||||
:- meta_predicate(phrase_to_stream(2, ?)).
|
||||
|
||||
|
||||
%% phrase_from_stream(+GRBody, +Stream)
|
||||
%
|
||||
% True if grammar rule body GRBody covers the contents of the stream,
|
||||
% represented as a list of characters.
|
||||
|
||||
phrase_from_stream(GRBody, Stream) :-
|
||||
stream_to_lazy_list(Stream, Ls),
|
||||
phrase(GRBody, Ls).
|
||||
|
||||
%% phrase_from_file(+GRBody, +File)
|
||||
%
|
||||
% True if grammar rule body GRBody covers the contents of File,
|
||||
@@ -48,25 +63,121 @@ phrase_from_file(NT, File, Options) :-
|
||||
member(Type, [text,binary])
|
||||
; Type = text
|
||||
),
|
||||
setup_call_cleanup(open(File, read, Stream, [reposition(true)|Options]),
|
||||
( stream_to_lazy_list(Stream, Xs),
|
||||
phrase(NT, Xs) ),
|
||||
close(Stream))
|
||||
).
|
||||
setup_call_cleanup(
|
||||
open(File, read, Stream, Options),
|
||||
phrase_from_stream(NT, Stream),
|
||||
close(Stream)
|
||||
)
|
||||
).
|
||||
|
||||
% How many chars to read from stream and buffer in each step
|
||||
chars_to_read(4096).
|
||||
|
||||
stream_to_lazy_list(Stream, Xs) :-
|
||||
stream_property(Stream, position(Pos)),
|
||||
freeze(Xs, reader_step(Stream, Pos, Xs)).
|
||||
stream_to_lazy_list(Stream, Ls) :-
|
||||
get_stream_buffer_position(Stream, Pos),
|
||||
freeze(Ls, render_step(Stream, Pos, Ls)).
|
||||
|
||||
reader_step(Stream, Pos, Xs0) :-
|
||||
set_stream_position(Stream, Pos),
|
||||
( at_end_of_stream(Stream)
|
||||
-> Xs0 = []
|
||||
; get_n_chars(Stream, 4096, Cs),
|
||||
partial_string(Cs, Xs0, Xs),
|
||||
stream_to_lazy_list(Stream, Xs)
|
||||
).
|
||||
render_step(Stream, Pos, Ls) :-
|
||||
set_stream_buffer_position(Stream, Pos),
|
||||
( buffer_at_end_of_stream(Stream) ->
|
||||
Ls = []
|
||||
; chars_to_read(CharsToRead),
|
||||
buffer_get_n_chars(Stream, CharsToRead, Chars),
|
||||
partial_string(Chars, Ls, Ls0),
|
||||
stream_to_lazy_list(Stream, Ls0)
|
||||
).
|
||||
|
||||
buffer_at_end_of_stream(Stream) :-
|
||||
stream_bufferids(Stream, _, BufferPosId, _),
|
||||
bb_get(BufferPosId, Pos),
|
||||
Pos = eof.
|
||||
|
||||
get_stream_buffer_position(Stream, Pos) :-
|
||||
stream_bufferids(Stream, _, BufferPosId, _),
|
||||
bb_get(BufferPosId, Pos).
|
||||
|
||||
set_stream_buffer_position(Stream, Pos) :-
|
||||
stream_bufferids(Stream, _, BufferPosId, _),
|
||||
bb_put(BufferPosId, Pos).
|
||||
|
||||
buffer_get_n_chars(Stream, N, Chars) :-
|
||||
stream_bufferids(Stream, BufferId, BufferPosId, BufferLenId),
|
||||
buffer_prepare_for_n(Stream, BufferId, BufferPosId, BufferLenId, N),
|
||||
bb_get(BufferId, Buffer),
|
||||
bb_get(BufferPosId, BufferPos),
|
||||
( BufferPos = eof ->
|
||||
Chars = []
|
||||
; string_get_n_chars(Buffer, BufferPos, N, Chars),
|
||||
length(Chars, NChars),
|
||||
( NChars = 0 ->
|
||||
BufferPos1 = eof
|
||||
; BufferPos1 is BufferPos + NChars
|
||||
),
|
||||
bb_put(BufferPosId, BufferPos1)
|
||||
).
|
||||
|
||||
buffer_prepare_for_n(Stream, BufferId, BufferPosId, BufferLenId, N) :-
|
||||
bb_get(BufferPosId, BufferPos),
|
||||
bb_get(BufferLenId, BufferLen),
|
||||
( BufferLen < BufferPos + N ->
|
||||
bb_get(BufferId, Buffer),
|
||||
(
|
||||
( var(Buffer) ->
|
||||
BufferTail = Buffer
|
||||
; partial_string_last_tail(Buffer, BufferTail)
|
||||
) ->
|
||||
( at_end_of_stream(Stream) ->
|
||||
BufferTail = [],
|
||||
bb_put(BufferId, Buffer)
|
||||
; chars_to_read(CharsToRead),
|
||||
get_n_chars(Stream, CharsToRead, Chars),
|
||||
length(Chars, NChars),
|
||||
partial_string(Chars, BufferTail, _),
|
||||
bb_put(BufferId, Buffer),
|
||||
BufferLen1 is BufferLen + NChars,
|
||||
bb_put(BufferLenId, BufferLen1),
|
||||
buffer_prepare_for_n(Stream, BufferId, BufferPosId, BufferLenId, N)
|
||||
)
|
||||
; true
|
||||
)
|
||||
; true
|
||||
).
|
||||
|
||||
partial_string_last_tail(PartialString, PartialStringTail) :-
|
||||
partial_string_tail(PartialString, PartialStringTail0),
|
||||
( var(PartialStringTail0) ->
|
||||
PartialStringTail = PartialStringTail0
|
||||
; partial_string_last_tail(PartialStringTail0, PartialStringTail)
|
||||
).
|
||||
|
||||
string_get_n_chars(String, Pos, N, Chars) :-
|
||||
'$skip_max_list'(_, Pos, String, String1),
|
||||
'$skip_max_list'(N1, N, String1, _),
|
||||
length(Chars, N1),
|
||||
append(Chars, _, String1).
|
||||
|
||||
stream_bufferids(Stream, BufferId, BufferPosId, BufferLenId) :-
|
||||
( bb_get(streams_buffers, _) ->
|
||||
true
|
||||
; bb_put(streams_buffers, [])
|
||||
),
|
||||
bb_get(streams_buffers, StreamsBuffers),
|
||||
( member(
|
||||
stream_buffer(Stream, BufferId, BufferPosId, BufferLenId),
|
||||
StreamsBuffers
|
||||
) ->
|
||||
true
|
||||
; gensym(buffer, BufferId),
|
||||
gensym(buffer_pos, BufferPosId),
|
||||
gensym(buffer_len, BufferLenId),
|
||||
bb_put(
|
||||
streams_buffers,
|
||||
[stream_buffer(Stream, BufferId, BufferPosId, BufferLenId)|StreamsBuffers]
|
||||
),
|
||||
bb_put(BufferId, _),
|
||||
bb_put(BufferPosId, 0),
|
||||
bb_put(BufferLenId, 0)
|
||||
).
|
||||
|
||||
%% phrase_to_stream(+GRBody, +Stream)
|
||||
%
|
||||
|
||||
@@ -380,6 +380,59 @@ remove_module(Module, Evacuable) :-
|
||||
).
|
||||
|
||||
|
||||
predicate_indicator(PI) :-
|
||||
( var(PI) ->
|
||||
throw(error(instantiation_error, _))
|
||||
; PI = Name/Arity,
|
||||
must_be(atom, Name),
|
||||
must_be(integer, Arity),
|
||||
Arity >= 0
|
||||
).
|
||||
|
||||
predicate_indicator_sequence(PI_Seq) :-
|
||||
( var(PI_Seq) ->
|
||||
throw(error(instantiation_error, load/1))
|
||||
; PI_Seq = (PI, PIs),
|
||||
predicate_indicator(PI),
|
||||
( predicate_indicator(PIs) ->
|
||||
true
|
||||
; predicate_indicator_sequence(PIs)
|
||||
)
|
||||
).
|
||||
|
||||
:- meta_predicate add_predicate_declaration(3, ?).
|
||||
|
||||
add_predicate_declaration(Handler, Name/Arity) :-
|
||||
predicate_indicator(Name/Arity),
|
||||
prolog_load_context(module, Module),
|
||||
call(Handler, Module, Name, Arity).
|
||||
add_predicate_declaration(Handler, Module:Name/Arity) :-
|
||||
must_be(atom, Module),
|
||||
predicate_indicator(Name/Arity),
|
||||
call(Handler, Module, Name, Arity).
|
||||
add_predicate_declaration(Handler, [PI|PIs]) :-
|
||||
'$skip_max_list'(_, _, PIs, Tail),
|
||||
( Tail == [],
|
||||
maplist(loader:predicate_indicator, PIs) ->
|
||||
maplist(loader:add_predicate_declaration(Handler), [PI|PIs])
|
||||
; throw(error(type_error(predicate_indicator_list, [PI|PIs]), load/1))
|
||||
).
|
||||
add_predicate_declaration(Handler, (PI, PIs)) :-
|
||||
( predicate_indicator_sequence((PI, PIs)) ->
|
||||
add_predicate_declaration(Handler, PI),
|
||||
add_predicate_declaration(Handler, PIs)
|
||||
; throw(error(type_error(predicate_indicator_sequence, (PI, PIs)), load/1))
|
||||
).
|
||||
|
||||
add_dynamic_predicate(Evacuable, Module, Name, Arity) :-
|
||||
'$add_dynamic_predicate'(Module, Name, Arity, Evacuable).
|
||||
|
||||
add_multifile_predicate(Evacuable, Module, Name, Arity) :-
|
||||
'$add_multifile_predicate'(Module, Name, Arity, Evacuable).
|
||||
|
||||
add_discontiguous_predicate(Evacuable, Module, Name, Arity) :-
|
||||
'$add_discontiguous_predicate'(Module, Name, Arity, Evacuable).
|
||||
|
||||
compile_declaration(use_module(Module), Evacuable) :-
|
||||
use_module(Module, [], Evacuable).
|
||||
compile_declaration(use_module(Module, Exports), Evacuable) :-
|
||||
@@ -392,39 +445,12 @@ compile_declaration(module(Module, Exports), Evacuable) :-
|
||||
'$declare_module'(Module, Exports, Evacuable)
|
||||
; type_error(atom, Module, load/1)
|
||||
).
|
||||
compile_declaration(dynamic(Module:Name/Arity), Evacuable) :-
|
||||
!,
|
||||
must_be(atom, Module),
|
||||
must_be(atom, Name),
|
||||
must_be(integer, Arity),
|
||||
'$add_dynamic_predicate'(Module, Name, Arity, Evacuable).
|
||||
compile_declaration(dynamic(Name/Arity), Evacuable) :-
|
||||
must_be(atom, Name),
|
||||
must_be(integer, Arity),
|
||||
prolog_load_context(module, Module),
|
||||
'$add_dynamic_predicate'(Module, Name, Arity, Evacuable).
|
||||
compile_declaration(multifile(Module:Name/Arity), Evacuable) :-
|
||||
!,
|
||||
must_be(atom, Module),
|
||||
must_be(atom, Name),
|
||||
must_be(integer, Arity),
|
||||
'$add_multifile_predicate'(Module, Name, Arity, Evacuable).
|
||||
compile_declaration(multifile(Name/Arity), Evacuable) :-
|
||||
must_be(atom, Name),
|
||||
must_be(integer, Arity),
|
||||
prolog_load_context(module, Module),
|
||||
'$add_multifile_predicate'(Module, Name, Arity, Evacuable).
|
||||
compile_declaration(discontiguous(Module:Name/Arity), Evacuable) :-
|
||||
!,
|
||||
must_be(atom, Module),
|
||||
must_be(atom, Name),
|
||||
must_be(integer, Arity),
|
||||
'$add_discontiguous_predicate'(Module, Name, Arity, Evacuable).
|
||||
compile_declaration(discontiguous(Name/Arity), Evacuable) :-
|
||||
must_be(atom, Name),
|
||||
must_be(integer, Arity),
|
||||
prolog_load_context(module, Module),
|
||||
'$add_discontiguous_predicate'(Module, Name, Arity, Evacuable).
|
||||
compile_declaration(dynamic(PIs), Evacuable) :-
|
||||
add_predicate_declaration(loader:add_dynamic_predicate(Evacuable), PIs).
|
||||
compile_declaration(multifile(PIs), Evacuable) :-
|
||||
add_predicate_declaration(loader:add_multifile_predicate(Evacuable), PIs).
|
||||
compile_declaration(discontiguous(PIs), Evacuable) :-
|
||||
add_predicate_declaration(loader:add_discontiguous_predicate(Evacuable), PIs).
|
||||
compile_declaration(initialization(Goal), Evacuable) :-
|
||||
prolog_load_context(module, Module),
|
||||
assertz(Module:'$initialization_goals'(Goal)).
|
||||
@@ -717,7 +743,7 @@ expand_subgoal(UnexpandedGoals, MS, M, ExpandedGoals, HeadVars) :-
|
||||
expand_module_names(UnexpandedGoals4, MetaSpecs, Module1, ExpandedGoals0, HeadVars)
|
||||
; ExpandedGoals0 = UnexpandedGoals4
|
||||
),
|
||||
'$compile_inline_or_expanded_goal'(ExpandedGoals0, SuppArgs, ExpandedGoals1, Module1),
|
||||
'$compile_inline_or_expanded_goal'(ExpandedGoals0, SuppArgs, ExpandedGoals1, Module1, UnexpandedGoals0),
|
||||
expand_module_name(ExpandedGoals1, MS, Module1, ExpandedGoals).
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
use dashu::base::Abs;
|
||||
use dashu::base::DivRem;
|
||||
use dashu::base::Gcd;
|
||||
use dashu::integer::IBig;
|
||||
use divrem::*;
|
||||
use num_order::NumOrd;
|
||||
|
||||
@@ -562,7 +560,7 @@ pub(crate) fn rdiv(
|
||||
r1: TypedArenaPtr<Rational>,
|
||||
r2: TypedArenaPtr<Rational>,
|
||||
) -> Result<Rational, MachineStubGen> {
|
||||
if &*r2 == &Rational::from(0) {
|
||||
if r2.is_zero() {
|
||||
let stub_gen = || {
|
||||
let rdiv_atom = atom!("rdiv");
|
||||
functor_stub(rdiv_atom, 2)
|
||||
@@ -596,7 +594,7 @@ pub(crate) fn idiv(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number,
|
||||
}
|
||||
}
|
||||
(Number::Fixnum(n1), Number::Integer(n2)) => {
|
||||
if (&*n2).num_eq(&0) {
|
||||
if n2.is_zero() {
|
||||
Err(zero_divisor_eval_error(stub_gen))
|
||||
} else {
|
||||
Ok(Number::arena_from(Integer::from(n1) / &*n2, arena))
|
||||
@@ -610,13 +608,10 @@ pub(crate) fn idiv(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number,
|
||||
}
|
||||
}
|
||||
(Number::Integer(n1), Number::Integer(n2)) => {
|
||||
if (&*n2).num_eq(&0) {
|
||||
if n2.is_zero() {
|
||||
Err(zero_divisor_eval_error(stub_gen))
|
||||
} else {
|
||||
Ok(Number::arena_from(
|
||||
<(Integer, Integer)>::from((&*n1).div_rem(&*n2)).0,
|
||||
arena,
|
||||
))
|
||||
Ok(Number::arena_from(&*n1 / &*n2, arena))
|
||||
}
|
||||
}
|
||||
(Number::Fixnum(_), n2) | (Number::Integer(_), n2) => {
|
||||
@@ -853,6 +848,16 @@ pub(crate) fn modulus(x: Number, y: Number, arena: &mut Arena) -> Result<Number,
|
||||
functor_stub(mod_atom, 2)
|
||||
};
|
||||
|
||||
fn ibig_rem_floor(n1: &Integer, n2: &Integer) -> Integer {
|
||||
if n1 > &Integer::ZERO && n2 < &Integer::ZERO {
|
||||
((n1 - Integer::ONE) / n2) - Integer::ONE
|
||||
} else if n1 < &Integer::ZERO && n2 > &Integer::ZERO {
|
||||
((n1 + Integer::ONE) / n2) - Integer::ONE
|
||||
} else {
|
||||
n1 / n2
|
||||
}
|
||||
}
|
||||
|
||||
match (x, y) {
|
||||
(Number::Fixnum(n1), Number::Fixnum(n2)) => {
|
||||
let n2_i = n2.get_num();
|
||||
@@ -865,14 +870,11 @@ pub(crate) fn modulus(x: Number, y: Number, arena: &mut Arena) -> Result<Number,
|
||||
}
|
||||
}
|
||||
(Number::Fixnum(n1), Number::Integer(n2)) => {
|
||||
if (&*n2).num_eq(&0) {
|
||||
if n2.is_zero() {
|
||||
Err(zero_divisor_eval_error(stub_gen))
|
||||
} else {
|
||||
let n1 = Integer::from(n1.get_num());
|
||||
Ok(Number::arena_from(
|
||||
<(Integer, Integer)>::from(n1.div_rem(&*n2)).1,
|
||||
arena,
|
||||
))
|
||||
Ok(Number::arena_from(ibig_rem_floor(&n1, &*n2), arena))
|
||||
}
|
||||
}
|
||||
(Number::Integer(n1), Number::Fixnum(n2)) => {
|
||||
@@ -882,20 +884,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(
|
||||
<(Integer, Integer)>::from((&*n1).div_rem(&n2)).1,
|
||||
arena,
|
||||
))
|
||||
Ok(Number::arena_from(ibig_rem_floor(&*n1, &n2), arena))
|
||||
}
|
||||
}
|
||||
(Number::Integer(x), Number::Integer(y)) => {
|
||||
if (&*y).num_eq(&0) {
|
||||
(Number::Integer(n1), Number::Integer(n2)) => {
|
||||
if n2.is_zero() {
|
||||
Err(zero_divisor_eval_error(stub_gen))
|
||||
} else {
|
||||
Ok(Number::arena_from(
|
||||
<(Integer, Integer)>::from((&*x).div_rem(&*y)).1,
|
||||
arena,
|
||||
))
|
||||
Ok(Number::arena_from(ibig_rem_floor(&*n1, &*n2), arena))
|
||||
}
|
||||
}
|
||||
(Number::Integer(_), n2) | (Number::Fixnum(_), n2) => {
|
||||
@@ -923,7 +919,7 @@ pub(crate) fn remainder(x: Number, y: Number, arena: &mut Arena) -> Result<Numbe
|
||||
}
|
||||
}
|
||||
(Number::Fixnum(n1), Number::Integer(n2)) => {
|
||||
if (&*n2).num_eq(&0) {
|
||||
if n2.is_zero() {
|
||||
Err(zero_divisor_eval_error(stub_gen))
|
||||
} else {
|
||||
let n1 = Integer::from(n1.get_num());
|
||||
@@ -941,7 +937,7 @@ pub(crate) fn remainder(x: Number, y: Number, arena: &mut Arena) -> Result<Numbe
|
||||
}
|
||||
}
|
||||
(Number::Integer(n1), Number::Integer(n2)) => {
|
||||
if (&*n2).num_eq(&0) {
|
||||
if n2.is_zero() {
|
||||
Err(zero_divisor_eval_error(stub_gen))
|
||||
} else {
|
||||
Ok(Number::arena_from(Integer::from(&*n1 % &*n2), arena))
|
||||
@@ -968,7 +964,7 @@ pub(crate) fn gcd(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
|
||||
if let Some(result) = isize_gcd(n1_i, n2_i) {
|
||||
Ok(Number::arena_from(result, arena))
|
||||
} else {
|
||||
let value: IBig = Integer::from(n1_i).gcd(&Integer::from(n2_i)).into();
|
||||
let value: Integer = Integer::from(n1_i).gcd(&Integer::from(n2_i)).into();
|
||||
Ok(Number::arena_from(value, arena))
|
||||
}
|
||||
}
|
||||
@@ -978,9 +974,9 @@ pub(crate) fn gcd(n1: Number, n2: Number, arena: &mut Arena) -> Result<Number, M
|
||||
Ok(Number::arena_from(Integer::from(n2_clone.gcd(&n1)), arena))
|
||||
}
|
||||
(Number::Integer(n1), Number::Integer(n2)) => {
|
||||
let n1_clone: Integer = (*n1).clone();
|
||||
let n2: isize = (&*n2).try_into().unwrap();
|
||||
Ok(Number::arena_from(Integer::from(n1_clone.gcd(&Integer::from(n2))) as IBig, arena))
|
||||
let value: Integer = (&*n1).gcd(&Integer::from(n2)).into();
|
||||
Ok(Number::arena_from(value, arena))
|
||||
}
|
||||
(Number::Float(f), _) | (_, Number::Float(f)) => {
|
||||
let n = Number::Float(f);
|
||||
@@ -1212,7 +1208,8 @@ impl MachineState {
|
||||
value: HeapCellValue,
|
||||
) -> Result<Number, MachineStub> {
|
||||
let stub_gen = || functor_stub(atom!("is"), 2);
|
||||
let mut iter = stackful_post_order_iter(&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() {
|
||||
|
||||
@@ -133,7 +133,8 @@ impl MachineState {
|
||||
let mut seen_set = IndexSet::new();
|
||||
let mut seen_vars = vec![];
|
||||
|
||||
let mut iter = stackful_preorder_iter(&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,
|
||||
|
||||
@@ -2331,7 +2331,7 @@ impl Machine {
|
||||
let mut loader: Loader<'_, InlineLoadState<'_>> =
|
||||
Loader::new(self, InlineTermStream {});
|
||||
|
||||
let term = loader.read_term_from_heap(term_loc)?;
|
||||
let term = loader.read_term_from_heap(term_loc);
|
||||
let clause = build_rule_body(vars, term);
|
||||
|
||||
let settings = CodeGenSettings {
|
||||
|
||||
@@ -34,6 +34,15 @@ macro_rules! try_or_throw {
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! increment_call_count {
|
||||
($s:expr) => {{
|
||||
if !($s.increment_call_count_fn)(&mut $s) {
|
||||
$s.backtrack();
|
||||
continue;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! try_or_throw_gen {
|
||||
($s:expr, $e:expr) => {{
|
||||
match $e {
|
||||
@@ -1096,12 +1105,7 @@ impl Machine {
|
||||
self.trust_me();
|
||||
}
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(
|
||||
&mut self.machine_st
|
||||
)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1174,12 +1178,7 @@ impl Machine {
|
||||
self.trust_me();
|
||||
}
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(
|
||||
&mut self.machine_st
|
||||
)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1205,19 +1204,11 @@ impl Machine {
|
||||
}
|
||||
&Instruction::RetryMeElse(offset) => {
|
||||
self.retry_me_else(offset);
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
&Instruction::TrustMe(_) => {
|
||||
self.trust_me();
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
&Instruction::NeckCut => {
|
||||
self.machine_st.neck_cut();
|
||||
@@ -1521,11 +1512,7 @@ impl Machine {
|
||||
if self.machine_st.is_cyclic_term(addr) {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1535,11 +1522,7 @@ impl Machine {
|
||||
if self.machine_st.is_cyclic_term(addr) {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1549,11 +1532,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1563,11 +1542,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1577,11 +1552,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1591,11 +1562,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1605,11 +1572,7 @@ impl Machine {
|
||||
|
||||
if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2)
|
||||
{
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
} else {
|
||||
self.machine_st.backtrack();
|
||||
@@ -1621,11 +1584,7 @@ impl Machine {
|
||||
|
||||
if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2)
|
||||
{
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
} else {
|
||||
self.machine_st.backtrack();
|
||||
@@ -1636,11 +1595,7 @@ impl Machine {
|
||||
let a2 = self.machine_st.registers[2];
|
||||
|
||||
if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
} else {
|
||||
self.machine_st.backtrack();
|
||||
@@ -1651,11 +1606,7 @@ impl Machine {
|
||||
let a2 = self.machine_st.registers[2];
|
||||
|
||||
if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
} else {
|
||||
self.machine_st.backtrack();
|
||||
@@ -1667,11 +1618,7 @@ impl Machine {
|
||||
|
||||
match compare_term_test!(self.machine_st, a1, a2) {
|
||||
Some(Ordering::Greater | Ordering::Equal) => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
_ => {
|
||||
@@ -1685,11 +1632,7 @@ impl Machine {
|
||||
|
||||
match compare_term_test!(self.machine_st, a1, a2) {
|
||||
Some(Ordering::Greater | Ordering::Equal) => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
_ => {
|
||||
@@ -1703,11 +1646,7 @@ impl Machine {
|
||||
|
||||
match compare_term_test!(self.machine_st, a1, a2) {
|
||||
Some(Ordering::Less | Ordering::Equal) => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
_ => {
|
||||
@@ -1721,11 +1660,7 @@ impl Machine {
|
||||
|
||||
match compare_term_test!(self.machine_st, a1, a2) {
|
||||
Some(Ordering::Less | Ordering::Equal) => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
_ => {
|
||||
@@ -1739,11 +1674,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1753,11 +1684,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1768,11 +1695,7 @@ impl Machine {
|
||||
if self.machine_st.eq_test(a1, a2) {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1783,11 +1706,7 @@ impl Machine {
|
||||
if self.machine_st.eq_test(a1, a2) {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1795,11 +1714,7 @@ impl Machine {
|
||||
if self.machine_st.ground_test() {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1807,11 +1722,7 @@ impl Machine {
|
||||
if self.machine_st.ground_test() {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1821,11 +1732,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1835,11 +1742,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1850,11 +1753,7 @@ impl Machine {
|
||||
if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1865,11 +1764,7 @@ impl Machine {
|
||||
if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1879,11 +1774,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1893,11 +1784,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1910,11 +1797,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1927,11 +1810,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1944,11 +1823,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1961,11 +1836,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -1975,11 +1846,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -1989,11 +1856,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -2003,11 +1866,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -2017,11 +1876,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -2039,10 +1894,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
&Instruction::ExecuteN(arity) => {
|
||||
@@ -2059,10 +1911,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
&Instruction::DefaultCallN(arity) => {
|
||||
@@ -2101,11 +1950,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Less | Ordering::Equal => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
_ => {
|
||||
@@ -2119,11 +1964,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Less | Ordering::Equal => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
_ => {
|
||||
@@ -2137,11 +1978,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Equal => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
_ => {
|
||||
@@ -2155,11 +1992,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Equal => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
_ => {
|
||||
@@ -2176,11 +2009,7 @@ impl Machine {
|
||||
self.machine_st.backtrack();
|
||||
}
|
||||
_ => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
}
|
||||
@@ -2194,11 +2023,7 @@ impl Machine {
|
||||
self.machine_st.backtrack();
|
||||
}
|
||||
_ => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
}
|
||||
@@ -2209,11 +2034,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Greater | Ordering::Equal => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
_ => {
|
||||
@@ -2227,11 +2048,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Greater | Ordering::Equal => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
_ => {
|
||||
@@ -2245,11 +2062,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Greater => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
_ => {
|
||||
@@ -2263,11 +2076,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Greater => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
_ => {
|
||||
@@ -2281,11 +2090,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Less => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p += 1;
|
||||
}
|
||||
_ => {
|
||||
@@ -2299,11 +2104,7 @@ impl Machine {
|
||||
|
||||
match n1.cmp(&n2) {
|
||||
Ordering::Less => {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
|
||||
increment_call_count!(self.machine_st);
|
||||
self.machine_st.p = self.machine_st.cp;
|
||||
}
|
||||
_ => {
|
||||
@@ -2878,10 +2679,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
&Instruction::ExecuteNamed(arity, name, ref idx) => {
|
||||
@@ -2892,10 +2690,7 @@ impl Machine {
|
||||
if self.machine_st.fail {
|
||||
self.machine_st.backtrack();
|
||||
} else {
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
&Instruction::DefaultCallNamed(arity, name, ref idx) => {
|
||||
@@ -3224,26 +3019,14 @@ impl Machine {
|
||||
}
|
||||
&IndexedChoiceInstruction::Retry(l) => {
|
||||
self.retry(l);
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(
|
||||
&mut self.machine_st
|
||||
)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
&IndexedChoiceInstruction::DefaultRetry(l) => {
|
||||
self.retry(l);
|
||||
}
|
||||
&IndexedChoiceInstruction::Trust(l) => {
|
||||
self.trust(l);
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(
|
||||
&mut self.machine_st
|
||||
)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
&IndexedChoiceInstruction::DefaultTrust(l) => {
|
||||
self.trust(l);
|
||||
@@ -3318,38 +3101,16 @@ impl Machine {
|
||||
// this is true iff ii + 1 < len.
|
||||
Some(_) => {
|
||||
self.retry(offset);
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self
|
||||
.machine_st
|
||||
.increment_call_count_fn)(
|
||||
&mut self.machine_st
|
||||
)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
_ => {
|
||||
self.trust(offset);
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self
|
||||
.machine_st
|
||||
.increment_call_count_fn)(
|
||||
&mut self.machine_st
|
||||
)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.trust(offset);
|
||||
|
||||
try_or_throw!(
|
||||
self.machine_st,
|
||||
(self.machine_st.increment_call_count_fn)(
|
||||
&mut self.machine_st
|
||||
)
|
||||
);
|
||||
increment_call_count!(self.machine_st);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5484,6 +5245,14 @@ impl Machine {
|
||||
self.get_db_refs();
|
||||
step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
|
||||
}
|
||||
&Instruction::CallInferenceLimitExceeded => {
|
||||
self.inference_limit_exceeded();
|
||||
step_or_fail!(self, self.machine_st.p += 1);
|
||||
}
|
||||
&Instruction::ExecuteInferenceLimitExceeded => {
|
||||
self.inference_limit_exceeded();
|
||||
step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5499,6 +5268,17 @@ impl Machine {
|
||||
if interruption {
|
||||
self.machine_st.throw_interrupt_exception();
|
||||
self.machine_st.backtrack();
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let old_runtime = std::mem::replace(&mut self.runtime, runtime);
|
||||
old_runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
Err(_) => unreachable!(),
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::parser::ast::*;
|
||||
|
||||
use fxhash::FxBuildHasher;
|
||||
use indexmap::IndexSet;
|
||||
use ref_thread_local::RefThreadLocal;
|
||||
pub use ref_thread_local::RefThreadLocal;
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fs::File;
|
||||
@@ -1004,10 +1004,22 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn add_module(&mut self, module_decl: ModuleDecl, listing_src: ListingSource) {
|
||||
self.reset_in_situ_module(module_decl.clone(), &listing_src);
|
||||
pub(crate) fn add_module(
|
||||
&mut self,
|
||||
module_decl: ModuleDecl,
|
||||
listing_src: ListingSource,
|
||||
) -> Result<(), SessionError> {
|
||||
let module_name = module_decl.name;
|
||||
|
||||
if let Some(module) = self.wam_prelude.indices.modules.get(&module_name) {
|
||||
if let ListingSource::DynamicallyGenerated = module.listing_src {
|
||||
} else {
|
||||
LS::err_on_builtin_module_overwrite(module_name)?;
|
||||
}
|
||||
}
|
||||
|
||||
self.reset_in_situ_module(module_decl.clone(), &listing_src);
|
||||
|
||||
let mut module = match self.wam_prelude.indices.modules.remove(&module_name) {
|
||||
Some(mut module) => {
|
||||
module.listing_src = listing_src;
|
||||
@@ -1045,6 +1057,8 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
|
||||
}
|
||||
|
||||
self.wam_prelude.indices.modules.insert(module_name, module);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn import_module(&mut self, module_name: Atom) -> Result<(), SessionError> {
|
||||
|
||||
@@ -265,6 +265,10 @@ pub trait LoadState<'a>: Sized {
|
||||
loader: &Loader<'a, Self>,
|
||||
key: PredicateKey,
|
||||
) -> Result<(), SessionError>;
|
||||
|
||||
fn err_on_builtin_module_overwrite(_module_name: Atom) -> Result<(), SessionError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LiveLoadAndMachineState<'a> {
|
||||
@@ -353,6 +357,15 @@ impl<'a> LoadState<'a> for LiveLoadAndMachineState<'a> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn err_on_builtin_module_overwrite(module_name: Atom) -> Result<(), SessionError> {
|
||||
if LIBRARIES.borrow().contains_key(&*module_name.as_str()) {
|
||||
Err(SessionError::CannotOverwriteBuiltInModule(module_name))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> LoadState<'a> for BootstrappingLoadState<'a> {
|
||||
@@ -483,7 +496,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read_term_from_heap(&mut self, r: RegType) -> Result<Term, SessionError> {
|
||||
pub(crate) fn read_term_from_heap(&mut self, r: RegType) -> Term {
|
||||
let machine_st = LS::machine_st(&mut self.payload);
|
||||
let cell = machine_st[r];
|
||||
|
||||
@@ -533,11 +546,13 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
|
||||
self.add_meta_predicate_record(module_name, name, meta_specs);
|
||||
}
|
||||
Declaration::Module(module_decl) => {
|
||||
self.payload.compilation_target = CompilationTarget::Module(module_decl.name);
|
||||
let module_name = module_decl.name;
|
||||
|
||||
self.payload.compilation_target = CompilationTarget::Module(module_name);
|
||||
self.payload.predicates.compilation_target = self.payload.compilation_target;
|
||||
|
||||
let listing_src = self.payload.term_stream.listing_src().clone();
|
||||
self.add_module(module_decl, listing_src);
|
||||
self.add_module(module_decl, listing_src)?;
|
||||
}
|
||||
Declaration::NonCountedBacktracking(name, arity) => {
|
||||
self.payload.non_counted_bt_preds.insert((name, arity));
|
||||
@@ -1074,7 +1089,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
|
||||
let machine_st = LS::machine_st(&mut self.payload);
|
||||
let cell = machine_st[r];
|
||||
|
||||
let export_list = machine_st.read_term_from_heap(cell)?;
|
||||
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)?;
|
||||
|
||||
@@ -1401,9 +1416,10 @@ impl MachineState {
|
||||
pub(super) fn read_term_from_heap(
|
||||
&mut self,
|
||||
term_addr: HeapCellValue,
|
||||
) -> Result<Term, SessionError> {
|
||||
) -> Term {
|
||||
let mut term_stack = vec![];
|
||||
let mut iter = stackful_post_order_iter(&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);
|
||||
@@ -1494,7 +1510,7 @@ impl MachineState {
|
||||
}
|
||||
|
||||
debug_assert!(term_stack.len() == 1);
|
||||
Ok(term_stack.pop().unwrap())
|
||||
term_stack.pop().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1636,7 +1652,7 @@ impl Machine {
|
||||
|
||||
let arity = self.deref_register(3);
|
||||
let arity = match Number::try_from(arity) {
|
||||
Ok(Number::Integer(n)) if &*n >= &Integer::from(0) && &*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)
|
||||
},
|
||||
@@ -1661,7 +1677,7 @@ impl Machine {
|
||||
let mut loader = self.loader_from_heap_evacuable(temp_v!(2));
|
||||
|
||||
let add_clause = || {
|
||||
let term = loader.read_term_from_heap(temp_v!(1))?;
|
||||
let term = loader.read_term_from_heap(temp_v!(1));
|
||||
|
||||
loader.incremental_compile_clause(
|
||||
(atom!("term_expansion"), 2),
|
||||
@@ -1691,7 +1707,7 @@ impl Machine {
|
||||
};
|
||||
|
||||
let add_clause = || {
|
||||
let term = loader.read_term_from_heap(temp_v!(2))?;
|
||||
let term = loader.read_term_from_heap(temp_v!(2));
|
||||
|
||||
let indexing_arg = match term.name() {
|
||||
Some(atom!(":-")) => term.first_arg().and_then(Term::first_arg),
|
||||
@@ -1849,9 +1865,7 @@ impl Machine {
|
||||
2,
|
||||
)?;
|
||||
|
||||
let path = cell_as_atom!(self
|
||||
.machine_st
|
||||
.store(self.machine_st.deref(self.machine_st.registers[2])));
|
||||
let path = cell_as_atom!(self.deref_register(2));
|
||||
|
||||
self.load_contexts
|
||||
.push(LoadContext::new(&*path.as_str(), stream));
|
||||
@@ -2008,7 +2022,7 @@ impl Machine {
|
||||
loader.payload.compilation_target = compilation_target;
|
||||
|
||||
let head = LiveLoadAndMachineState::machine_st(&mut loader.payload)
|
||||
.read_term_from_heap(head)?;
|
||||
.read_term_from_heap(head);
|
||||
|
||||
let name = if let Some(name) = head.name() {
|
||||
name
|
||||
@@ -2044,7 +2058,7 @@ impl Machine {
|
||||
return LiveLoadAndMachineState::evacuate(loader);
|
||||
}
|
||||
|
||||
let body = loader.read_term_from_heap(temp_v!(3))?;
|
||||
let body = loader.read_term_from_heap(temp_v!(3));
|
||||
|
||||
let asserted_clause = Term::Clause(
|
||||
Cell::default(),
|
||||
@@ -2482,7 +2496,7 @@ impl<'a> Loader<'a, LiveLoadAndMachineState<'a>> {
|
||||
self.payload.predicates.compilation_target = compilation_target;
|
||||
}
|
||||
|
||||
let term = self.read_term_from_heap(term_reg)?;
|
||||
let term = self.read_term_from_heap(term_reg);
|
||||
|
||||
self.add_clause_clause_if_dynamic(&term)?;
|
||||
self.payload.term_stream.term_queue.push_back(term);
|
||||
|
||||
@@ -77,6 +77,12 @@ impl ValidType {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum ResourceError {
|
||||
FiniteMemory(HeapCellValue),
|
||||
OutOfFiles
|
||||
}
|
||||
|
||||
pub(crate) trait TypeError {
|
||||
fn type_error(self, machine_st: &mut MachineState, valid_type: ValidType) -> MachineError;
|
||||
}
|
||||
@@ -155,6 +161,26 @@ pub(crate) trait PermissionError {
|
||||
) -> MachineError;
|
||||
}
|
||||
|
||||
impl PermissionError for Atom {
|
||||
fn permission_error(
|
||||
self,
|
||||
_machine_st: &mut MachineState,
|
||||
index_atom: Atom,
|
||||
perm: Permission,
|
||||
) -> MachineError {
|
||||
let stub = functor!(
|
||||
atom!("permission_error"),
|
||||
[atom(perm.as_atom()), atom(index_atom), cell(atom_as_cell!(self))]
|
||||
);
|
||||
|
||||
MachineError {
|
||||
stub,
|
||||
location: None,
|
||||
from: ErrorProvenance::Received,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PermissionError for HeapCellValue {
|
||||
fn permission_error(
|
||||
self,
|
||||
@@ -284,11 +310,21 @@ impl MachineState {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resource_error(&mut self, value: HeapCellValue) -> MachineError {
|
||||
let stub = functor!(
|
||||
atom!("resource_error"),
|
||||
[atom(atom!("finite_memory")), cell(value)]
|
||||
);
|
||||
pub(super) fn resource_error(&mut self, err: ResourceError) -> MachineError {
|
||||
let stub = match err {
|
||||
ResourceError::FiniteMemory(size_requested) => {
|
||||
functor!(
|
||||
atom!("resource_error"),
|
||||
[atom(atom!("finite_memory")), cell(size_requested)]
|
||||
)
|
||||
}
|
||||
ResourceError::OutOfFiles => {
|
||||
functor!(
|
||||
atom!("resource_error"),
|
||||
[atom(atom!("file_descriptors"))]
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
MachineError {
|
||||
stub,
|
||||
@@ -305,26 +341,6 @@ impl MachineState {
|
||||
culprit.type_error(self, valid_type)
|
||||
}
|
||||
|
||||
pub(super) fn module_resolution_error(
|
||||
&mut self,
|
||||
mod_name: Atom,
|
||||
name: Atom,
|
||||
arity: usize,
|
||||
) -> MachineError {
|
||||
let h = self.heap.len();
|
||||
|
||||
let res_stub = functor!(atom!(":"), [atom(mod_name), atom(name)]);
|
||||
let ind_stub = functor!(atom!("/"), [str(h + 2, 0), fixnum(arity)], [res_stub]);
|
||||
|
||||
let stub = functor!(atom!("evaluation_error"), [str(h, 0)], [ind_stub]);
|
||||
|
||||
MachineError {
|
||||
stub,
|
||||
location: None,
|
||||
from: ErrorProvenance::Constructed,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn existence_error(&mut self, err: ExistenceError) -> MachineError {
|
||||
match err {
|
||||
ExistenceError::Module(name) => {
|
||||
@@ -339,6 +355,20 @@ impl MachineState {
|
||||
from: ErrorProvenance::Received,
|
||||
}
|
||||
}
|
||||
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]);
|
||||
|
||||
MachineError {
|
||||
stub,
|
||||
location: None,
|
||||
from: ErrorProvenance::Constructed,
|
||||
}
|
||||
}
|
||||
ExistenceError::Procedure(name, arity) => {
|
||||
let culprit = functor!(atom!("/"), [atom(name), fixnum(arity)]);
|
||||
|
||||
@@ -443,7 +473,6 @@ impl MachineState {
|
||||
pub(super) fn session_error(&mut self, err: SessionError) -> MachineError {
|
||||
match err {
|
||||
SessionError::CannotOverwriteBuiltIn(key) => {
|
||||
// SessionError::CannotOverwriteImport(pred_atom) => {
|
||||
self.permission_error(
|
||||
Permission::Modify,
|
||||
atom!("static_procedure"),
|
||||
@@ -452,10 +481,14 @@ impl MachineState {
|
||||
.collect::<MachineStub>(),
|
||||
)
|
||||
}
|
||||
SessionError::CannotOverwriteBuiltInModule(module) => {
|
||||
self.permission_error(
|
||||
Permission::Modify,
|
||||
atom!("static_module"),
|
||||
module,
|
||||
)
|
||||
}
|
||||
SessionError::ExistenceError(err) => self.existence_error(err),
|
||||
// SessionError::InvalidFileName(filename) => {
|
||||
// Self::existence_error(h, ExistenceError::Module(filename))
|
||||
// }
|
||||
SessionError::ModuleDoesNotContainExport(..) => {
|
||||
let error_atom = atom!("module_does_not_contain_claimed_export");
|
||||
|
||||
@@ -953,6 +986,7 @@ pub enum ExistenceError {
|
||||
Module(Atom),
|
||||
ModuleSource(ModuleSource),
|
||||
Procedure(Atom, usize),
|
||||
QualifiedProcedure { module_name: Atom, name: Atom, arity: usize },
|
||||
SourceSink(HeapCellValue),
|
||||
Stream(HeapCellValue),
|
||||
}
|
||||
@@ -961,6 +995,7 @@ pub enum ExistenceError {
|
||||
pub enum SessionError {
|
||||
CompilationError(CompilationError),
|
||||
CannotOverwriteBuiltIn(PredicateKey),
|
||||
CannotOverwriteBuiltInModule(Atom),
|
||||
ExistenceError(ExistenceError),
|
||||
ModuleDoesNotContainExport(Atom, PredicateKey),
|
||||
ModuleCannotImportSelf(Atom),
|
||||
|
||||
@@ -96,7 +96,7 @@ pub struct MachineState {
|
||||
pub(crate) unify_fn: fn(&mut MachineState),
|
||||
pub(crate) bind_fn: fn(&mut MachineState, Ref, HeapCellValue),
|
||||
pub(crate) run_cleaners_fn: fn(&mut Machine) -> bool,
|
||||
pub(crate) increment_call_count_fn: fn(&mut MachineState) -> CallResult,
|
||||
pub(crate) increment_call_count_fn: fn(&mut MachineState) -> bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for MachineState {
|
||||
@@ -412,22 +412,24 @@ impl MachineState {
|
||||
self.fail = false;
|
||||
}
|
||||
|
||||
pub(crate) fn increment_call_count(&mut self) -> CallResult {
|
||||
pub(crate) fn increment_call_count(&mut self) -> bool {
|
||||
if self.cwil.inference_limit_exceeded || self.ball.stub.len() > 0 {
|
||||
return Ok(());
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(&(ref limit, bp)) = self.cwil.limits.last() {
|
||||
if let Some(&(ref limit, block)) = self.cwil.limits.last() {
|
||||
if self.cwil.count == *limit {
|
||||
self.cwil.inference_limit_exceeded = true;
|
||||
self.block = block;
|
||||
self.unwind_stack();
|
||||
|
||||
return Err(functor!(atom!("inference_limit_exceeded"), [fixnum(bp)]));
|
||||
return false;
|
||||
} else {
|
||||
self.cwil.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
true
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
@@ -588,7 +590,7 @@ impl MachineState {
|
||||
|
||||
let mut singleton_var_set: IndexMap<Ref, bool> = IndexMap::new();
|
||||
|
||||
for cell in stackful_preorder_iter(&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() {
|
||||
@@ -953,7 +955,7 @@ impl MachineState {
|
||||
pub(crate) struct CWIL {
|
||||
count: Integer,
|
||||
limits: Vec<(Integer, usize)>,
|
||||
inference_limit_exceeded: bool,
|
||||
pub(crate) inference_limit_exceeded: bool,
|
||||
}
|
||||
|
||||
impl CWIL {
|
||||
@@ -965,22 +967,22 @@ impl CWIL {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn add_limit(&mut self, limit: usize, b: usize) -> &Integer {
|
||||
pub(crate) fn add_limit(&mut self, limit: usize, block: usize) -> &Integer {
|
||||
let mut limit = Integer::from(limit);
|
||||
limit += &self.count;
|
||||
|
||||
match self.limits.last() {
|
||||
Some((ref inner_limit, _)) if *inner_limit <= limit => {}
|
||||
_ => self.limits.push((limit, b)),
|
||||
_ => self.limits.push((limit, block)),
|
||||
};
|
||||
|
||||
&self.count
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn remove_limit(&mut self, b: usize) -> &Integer {
|
||||
if let Some((_, bp)) = self.limits.last() {
|
||||
if bp == &b {
|
||||
pub(crate) fn remove_limit(&mut self, block: usize) -> &Integer {
|
||||
if let Some((_, bl)) = self.limits.last() {
|
||||
if bl == &block {
|
||||
self.limits.pop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ use crate::parser::dashu::{Integer, Rational};
|
||||
use crate::types::*;
|
||||
|
||||
use indexmap::IndexSet;
|
||||
use num_order::NumOrd;
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::convert::TryFrom;
|
||||
@@ -61,7 +60,7 @@ impl MachineState {
|
||||
unify_fn: MachineState::unify,
|
||||
bind_fn: MachineState::bind,
|
||||
run_cleaners_fn: |_| false,
|
||||
increment_call_count_fn: |_| Ok(()),
|
||||
increment_call_count_fn: |_| true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1136,7 +1135,8 @@ impl MachineState {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut iter = stackful_preorder_iter(&mut self.heap, &mut self.stack, value);
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>
|
||||
(&mut self.heap, &mut self.stack, value);
|
||||
|
||||
while let Some(value) = iter.next() {
|
||||
if value.get_forwarding_bit() {
|
||||
@@ -1183,10 +1183,7 @@ impl MachineState {
|
||||
|
||||
let n = match n {
|
||||
Number::Fixnum(n) => n.get_num() as usize,
|
||||
Number::Integer(n) if (*n).num_ge(&0) && (*n).num_le(&std::usize::MAX) => {
|
||||
let value: usize = (&*n).try_into().unwrap();
|
||||
value
|
||||
},
|
||||
Number::Integer(n) if usize::try_from(&*n).is_ok() => (&*n).try_into().unwrap(),
|
||||
_ => {
|
||||
self.fail = true;
|
||||
return Ok(());
|
||||
@@ -1637,24 +1634,36 @@ impl MachineState {
|
||||
}
|
||||
|
||||
let mut visited = IndexSet::with_hasher(FxBuildHasher::default());
|
||||
let mut iter = stackful_preorder_iter(&mut self.heap, &mut self.stack, value);
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(&mut self.heap, &mut self.stack, value);
|
||||
let mut stack_len = 0;
|
||||
|
||||
while let Some(value) = iter.next() {
|
||||
let mut value = unmark_cell_bits!(value);
|
||||
let is_var = |heap: &Heap, value: HeapCellValue| -> bool {
|
||||
let value = unmark_cell_bits!(value);
|
||||
|
||||
if value.is_var() {
|
||||
value = heap_bound_store(iter.heap, heap_bound_deref(iter.heap, value));
|
||||
let value = heap_bound_store(heap, heap_bound_deref(heap, value));
|
||||
|
||||
if value.is_var() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if value.is_compound(iter.heap) {
|
||||
false
|
||||
};
|
||||
|
||||
while let Some(value) = iter.next() {
|
||||
if is_var(iter.heap, value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if value.is_ref() {
|
||||
if visited.contains(&value) {
|
||||
for _ in stack_len..iter.stack_len() {
|
||||
iter.pop_stack();
|
||||
while iter.stack_len() > stack_len {
|
||||
if let Some(value) = iter.pop_stack() {
|
||||
if is_var(iter.heap, value) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
visited.insert(value);
|
||||
@@ -1689,7 +1698,7 @@ impl MachineState {
|
||||
},
|
||||
Ok(Number::Integer(n)) => {
|
||||
let b: u8 = (&*n).try_into().unwrap();
|
||||
|
||||
|
||||
bytes.push(b);
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -60,6 +60,9 @@ use std::sync::atomic::AtomicBool;
|
||||
|
||||
use self::config::MachineConfig;
|
||||
use self::parsed_results::*;
|
||||
use tokio::runtime::Runtime;
|
||||
use rand::rngs::StdRng;
|
||||
use rand::SeedableRng;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref INTERRUPT: AtomicBool = AtomicBool::new(false);
|
||||
@@ -76,6 +79,7 @@ pub struct Machine {
|
||||
pub(super) load_contexts: Vec<LoadContext>,
|
||||
#[cfg(feature = "ffi")]
|
||||
pub(super) foreign_function_table: ForeignFunctionTable,
|
||||
pub(super) rng: StdRng,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -487,6 +491,7 @@ impl Machine {
|
||||
load_contexts: vec![],
|
||||
#[cfg(feature = "ffi")]
|
||||
foreign_function_table: Default::default(),
|
||||
rng: StdRng::from_entropy(),
|
||||
};
|
||||
|
||||
let mut lib_path = current_dir();
|
||||
@@ -1178,7 +1183,7 @@ impl Machine {
|
||||
let stub = functor_stub(name, arity);
|
||||
let err = self
|
||||
.machine_st
|
||||
.module_resolution_error(module_name, name, arity);
|
||||
.existence_error(ExistenceError::QualifiedProcedure { module_name, name, arity });
|
||||
|
||||
Err(self.machine_st.error_form(err, stub))
|
||||
}
|
||||
@@ -1206,7 +1211,7 @@ impl Machine {
|
||||
let stub = functor_stub(name, arity);
|
||||
let err = self
|
||||
.machine_st
|
||||
.module_resolution_error(module_name, name, arity);
|
||||
.existence_error(ExistenceError::QualifiedProcedure { module_name, name, arity });
|
||||
|
||||
Err(self.machine_st.error_form(err, stub))
|
||||
}
|
||||
|
||||
@@ -58,10 +58,7 @@ fn setup_predicate_indicator(term: &mut Term) -> Result<PredicateKey, Compilatio
|
||||
let name = terms.pop().unwrap();
|
||||
|
||||
let arity = match arity {
|
||||
Term::Literal(_, Literal::Integer(n)) => {
|
||||
let value: usize = (&*n).try_into().unwrap();
|
||||
Some(value)
|
||||
},
|
||||
Term::Literal(_, Literal::Integer(n)) => (&*n).try_into().ok(),
|
||||
Term::Literal(_, Literal::Fixnum(n)) => usize::try_from(n.get_num()).ok(),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ use std::ptr;
|
||||
#[cfg(feature = "tls")]
|
||||
use native_tls::TlsStream;
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
use warp::hyper;
|
||||
|
||||
#[derive(Debug, BitfieldSpecifier, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[bits = 1]
|
||||
pub enum StreamType {
|
||||
@@ -290,9 +293,9 @@ impl Read for HttpReadStream {
|
||||
#[cfg(feature = "http")]
|
||||
pub struct HttpWriteStream {
|
||||
status_code: u16,
|
||||
headers: hyper::HeaderMap,
|
||||
headers: mem::ManuallyDrop<hyper::HeaderMap>,
|
||||
response: TypedArenaPtr<HttpResponse>,
|
||||
buffer: Vec<u8>,
|
||||
buffer: mem::ManuallyDrop<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
@@ -312,24 +315,33 @@ impl Write for HttpWriteStream {
|
||||
|
||||
#[inline]
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
let (ready, response, cvar) = &**self.response;
|
||||
|
||||
let mut ready = ready.lock().unwrap();
|
||||
{
|
||||
let mut response = response.lock().unwrap();
|
||||
|
||||
let bytes = bytes::Bytes::copy_from_slice(&self.buffer);
|
||||
let mut response_ = hyper::Response::builder().status(self.status_code);
|
||||
*response_.headers_mut().unwrap() = self.headers.clone();
|
||||
*response = Some(response_.body(http_body_util::Full::new(bytes)).unwrap());
|
||||
}
|
||||
*ready = true;
|
||||
cvar.notify_one();
|
||||
|
||||
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 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 {}
|
||||
|
||||
@@ -1243,15 +1255,15 @@ impl Stream {
|
||||
headers: hyper::HeaderMap,
|
||||
arena: &mut Arena,
|
||||
) -> Self {
|
||||
Stream::HttpWrite(arena_alloc!(
|
||||
StreamLayout::new(CharReader::new(HttpWriteStream {
|
||||
response,
|
||||
status_code,
|
||||
headers,
|
||||
buffer: 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]
|
||||
@@ -1299,7 +1311,8 @@ impl Stream {
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(feature = "http")]
|
||||
Stream::HttpWrite(ref mut http_stream) => {
|
||||
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 _);
|
||||
@@ -1804,7 +1817,7 @@ impl MachineState {
|
||||
) -> Result<Stream, MachineStub> {
|
||||
if file_spec == atom!("") {
|
||||
let stub = functor_stub(atom!("open"), 4);
|
||||
let err = self.domain_error(DomainErrorType::SourceSink, self[temp_v!(1)]);
|
||||
let err = self.domain_error(DomainErrorType::SourceSink, self.registers[1]);
|
||||
|
||||
return Err(self.error_form(err, stub));
|
||||
}
|
||||
@@ -1816,9 +1829,7 @@ impl MachineState {
|
||||
}
|
||||
}
|
||||
|
||||
let mode = MachineState::deref(self, self[temp_v!(2)]);
|
||||
let mode = cell_as_atom!(self.store(mode));
|
||||
|
||||
let mode = cell_as_atom!(self.store(MachineState::deref(self, self.registers[2])));
|
||||
let mut open_options = OpenOptions::new();
|
||||
|
||||
let (is_input_file, in_append_mode) = match mode {
|
||||
@@ -1875,8 +1886,9 @@ impl MachineState {
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
// assume the OS is out of file descriptors.
|
||||
let stub = functor_stub(atom!("open"), 4);
|
||||
let err = self.syntax_error(ParserError::IO(err));
|
||||
let err = self.resource_error(ResourceError::OutOfFiles);
|
||||
|
||||
return Err(self.error_form(err, stub));
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::forms::*;
|
||||
use crate::heap_iter::*;
|
||||
use crate::heap_print::*;
|
||||
#[cfg(feature = "http")]
|
||||
use crate::http::{HttpListener, HttpResponse, HttpService};
|
||||
use crate::http::{HttpRequestData, HttpListener, HttpResponse, HttpRequest};
|
||||
use crate::instructions::*;
|
||||
use crate::machine;
|
||||
use crate::machine::code_walker::*;
|
||||
@@ -42,17 +42,16 @@ use indexmap::IndexSet;
|
||||
|
||||
pub(crate) use ref_thread_local::RefThreadLocal;
|
||||
|
||||
use std::borrow::BorrowMut;
|
||||
use std::cell::Cell;
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeSet};
|
||||
use std::convert::TryFrom;
|
||||
use std::env;
|
||||
#[cfg(feature = "ffi")]
|
||||
use std::ffi::CString;
|
||||
use std::fs;
|
||||
use std::hash::{BuildHasher, BuildHasherDefault};
|
||||
use std::io::{ErrorKind, Read, Write};
|
||||
use std::io::{ErrorKind, Read, BufRead, Write};
|
||||
use std::iter::{once, FromIterator};
|
||||
use std::mem;
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
|
||||
@@ -60,6 +59,7 @@ use std::num::NonZeroU32;
|
||||
use std::ops::Sub;
|
||||
use std::process;
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Mutex, Arc, Condvar};
|
||||
|
||||
use chrono::{offset::Local, DateTime};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -77,7 +77,7 @@ use ring::{digest, hkdf, pbkdf2};
|
||||
|
||||
#[cfg(feature = "crypto-full")]
|
||||
use ring::{
|
||||
aead,
|
||||
aead,
|
||||
signature::{self, KeyPair},
|
||||
};
|
||||
use ripemd160::{Digest, Ripemd160};
|
||||
@@ -92,17 +92,16 @@ use base64;
|
||||
use roxmltree;
|
||||
use select;
|
||||
|
||||
use bytes::Buf;
|
||||
use http_body_util::BodyExt;
|
||||
#[cfg(feature = "http")]
|
||||
use hyper::header::{HeaderName, HeaderValue};
|
||||
use warp::hyper::header::{HeaderValue, HeaderName};
|
||||
#[cfg(feature = "http")]
|
||||
use hyper::server::conn::http1;
|
||||
use warp::hyper::{HeaderMap, Method};
|
||||
#[cfg(feature = "http")]
|
||||
use hyper::{HeaderMap, Method};
|
||||
use warp::{Buf, Filter};
|
||||
#[cfg(feature = "http")]
|
||||
use reqwest::Url;
|
||||
use hyper_util::rt::TokioIo;
|
||||
//use hyper_util::rt::TokioIo;
|
||||
use futures::future;
|
||||
|
||||
#[cfg(feature = "repl")]
|
||||
pub(crate) fn get_key() -> KeyEvent {
|
||||
@@ -182,12 +181,6 @@ impl BrentAlgState {
|
||||
}
|
||||
|
||||
pub fn to_result(mut self, heap: &[HeapCellValue]) -> CycleSearchResult {
|
||||
/*
|
||||
if let Some(var) = heap[self.hare].as_var() {
|
||||
return CycleSearchResult::PartialList(self.num_steps(), var);
|
||||
}
|
||||
*/
|
||||
|
||||
loop {
|
||||
read_heap_cell!(heap[self.hare],
|
||||
(HeapCellValueTag::PStrOffset) => {
|
||||
@@ -250,7 +243,7 @@ impl BrentAlgState {
|
||||
let cstr = PartialString::from(cstr_atom);
|
||||
let num_chars = cstr.as_str_from(offset).chars().count();
|
||||
|
||||
if self.max_steps == -1 || self.num_steps() + num_chars < self.max_steps as usize {
|
||||
if self.max_steps == -1 || self.num_steps() + num_chars <= self.max_steps as usize {
|
||||
self.pstr_chars += num_chars;
|
||||
Some(CycleSearchResult::ProperList(self.num_steps()))
|
||||
} else {
|
||||
@@ -263,7 +256,7 @@ impl BrentAlgState {
|
||||
let pstr = PartialString::from(pstr_atom);
|
||||
let num_chars = pstr.as_str_from(offset).chars().count();
|
||||
|
||||
if self.max_steps == -1 || self.num_steps() + num_chars < self.max_steps as usize {
|
||||
if self.max_steps == -1 || self.num_steps() + num_chars <= self.max_steps as usize {
|
||||
self.pstr_chars += num_chars - 1;
|
||||
self.step(h+1)
|
||||
} else {
|
||||
@@ -591,7 +584,7 @@ impl MachineState {
|
||||
seen_set: &mut IndexSet<HeapCellValue, S>,
|
||||
value: HeapCellValue,
|
||||
) {
|
||||
let mut iter = stackful_preorder_iter(&mut self.heap, &mut self.stack, value);
|
||||
let mut iter = stackful_preorder_iter::<NonListElider>(&mut self.heap, &mut self.stack, value);
|
||||
|
||||
while let Some(value) = iter.next() {
|
||||
let value = unmark_cell_bits!(value);
|
||||
@@ -801,7 +794,7 @@ impl MachineState {
|
||||
let mut seen_set = IndexSet::new();
|
||||
|
||||
{
|
||||
let mut iter = stackful_post_order_iter(&mut self.heap, &mut self.stack, term);
|
||||
let mut iter = stackful_post_order_iter::<NonListElider>(&mut self.heap, &mut self.stack, term);
|
||||
|
||||
while let Some(value) = iter.next() {
|
||||
if iter.parent_stack_len() >= max_depth {
|
||||
@@ -1419,7 +1412,6 @@ impl Machine {
|
||||
is_simple_goal: bool,
|
||||
goal: HeapCellValue,
|
||||
key: PredicateKey,
|
||||
expanded_vars: IndexSet<HeapCellValue, BuildHasherDefault<FxHasher>>,
|
||||
supp_vars: IndexSet<HeapCellValue, BuildHasherDefault<FxHasher>>,
|
||||
}
|
||||
|
||||
@@ -1444,7 +1436,7 @@ impl Machine {
|
||||
// insertion as well as the previous
|
||||
// supp_vars.len() argument's variables being
|
||||
// disjoint from them. if they are not, the
|
||||
// expanded goal are not simple.
|
||||
// expanded goal is not simple.
|
||||
|
||||
let post_supp_args = self.machine_st.heap[s+arity-supp_vars.len()+1 .. s+arity+1]
|
||||
.iter()
|
||||
@@ -1490,7 +1482,6 @@ impl Machine {
|
||||
is_simple_goal,
|
||||
goal,
|
||||
key: (name, arity),
|
||||
expanded_vars,
|
||||
supp_vars
|
||||
}
|
||||
}
|
||||
@@ -1504,7 +1495,6 @@ impl Machine {
|
||||
is_simple_goal: true,
|
||||
goal: str_loc_as_cell!(h),
|
||||
key: (name, 0),
|
||||
expanded_vars: IndexSet::with_hasher(FxBuildHasher::default()),
|
||||
supp_vars,
|
||||
}
|
||||
}
|
||||
@@ -1518,7 +1508,6 @@ impl Machine {
|
||||
is_simple_goal: true,
|
||||
goal: str_loc_as_cell!(h),
|
||||
key: (name, 0),
|
||||
expanded_vars: IndexSet::with_hasher(FxBuildHasher::default()),
|
||||
supp_vars,
|
||||
}
|
||||
}
|
||||
@@ -1540,9 +1529,12 @@ impl Machine {
|
||||
.push(untyped_arena_ptr_as_cell!(UntypedArenaPtr::from(idx)));
|
||||
result.goal
|
||||
} else {
|
||||
let mut unexpanded_vars = IndexSet::with_hasher(FxBuildHasher::default());
|
||||
self.machine_st.variable_set(&mut unexpanded_vars, self.machine_st.registers[5]);
|
||||
|
||||
// all supp_vars must appear later!
|
||||
let vars = IndexSet::<HeapCellValue, BuildHasherDefault<FxHasher>>::from_iter(
|
||||
result.expanded_vars.difference(&result.supp_vars).cloned(),
|
||||
unexpanded_vars.difference(&result.supp_vars).cloned(),
|
||||
);
|
||||
|
||||
let vars: Vec<_> = vars
|
||||
@@ -1564,7 +1556,7 @@ impl Machine {
|
||||
|
||||
self.machine_st.heap.push(atom_as_cell!(atom!("$aux"), 0));
|
||||
|
||||
for value in result.expanded_vars.difference(&result.supp_vars).cloned() {
|
||||
for value in unexpanded_vars.difference(&result.supp_vars).cloned() {
|
||||
self.machine_st.heap.push(value);
|
||||
}
|
||||
|
||||
@@ -3265,7 +3257,7 @@ impl Machine {
|
||||
match Number::try_from(addr) {
|
||||
Ok(Number::Integer(n)) => {
|
||||
let n: u8 = (&*n).try_into().unwrap();
|
||||
|
||||
|
||||
match n {
|
||||
nb => {
|
||||
match stream.write(&mut [nb]) {
|
||||
@@ -3916,6 +3908,11 @@ impl Machine {
|
||||
}
|
||||
);
|
||||
|
||||
if self.indices.builtin_property((name, arity)) {
|
||||
self.machine_st.fail = true;
|
||||
return;
|
||||
}
|
||||
|
||||
self.machine_st.fail = self
|
||||
.indices
|
||||
.get_predicate_code_index(name, arity, module_name)
|
||||
@@ -3995,6 +3992,10 @@ impl Machine {
|
||||
};
|
||||
|
||||
for (name, arity) in code_dir.keys() {
|
||||
if self.indices.builtin_property((*name, *arity)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if name_match(pred_atom, *name) && arity_match(pred_arity, *arity) {
|
||||
self.machine_st.heap.extend(functor!(
|
||||
atom!("/"),
|
||||
@@ -4217,25 +4218,7 @@ impl Machine {
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn maybe(&mut self) {
|
||||
fn generate_random_bits(num_bits: usize) -> u64 {
|
||||
let mut rng = rand::thread_rng();
|
||||
let rand = rng.borrow_mut();
|
||||
let mut random_bits: u64 = 0;
|
||||
|
||||
for _ in 0..num_bits {
|
||||
random_bits <<= 1;
|
||||
|
||||
if rand.gen_bool(0.5) {
|
||||
random_bits |= 1;
|
||||
}
|
||||
}
|
||||
|
||||
random_bits
|
||||
}
|
||||
|
||||
let result = { generate_random_bits(1) == 0 };
|
||||
|
||||
self.machine_st.fail = result;
|
||||
self.machine_st.fail = self.rng.gen();
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -4264,7 +4247,7 @@ impl Machine {
|
||||
Ok(Number::Integer(n)) => match (&*n).try_into() as Result<usize, _> {
|
||||
Ok(n) => n,
|
||||
Err(_) => {
|
||||
let err = self.machine_st.resource_error(len);
|
||||
let err = self.machine_st.resource_error(ResourceError::FiniteMemory(len));
|
||||
return Err(self.machine_st.error_form(err, stub_gen()));
|
||||
}
|
||||
},
|
||||
@@ -4429,64 +4412,128 @@ impl Machine {
|
||||
#[inline(always)]
|
||||
pub(crate) fn http_listen(&mut self) -> CallResult {
|
||||
let address_sink = self.deref_register(1);
|
||||
if let Some(address_str) = self.machine_st.value_to_str_like(address_sink) {
|
||||
let address_string = address_str.as_str();
|
||||
let addr: SocketAddr = match address_string
|
||||
.to_socket_addrs()
|
||||
.ok()
|
||||
.and_then(|mut s| s.next())
|
||||
{
|
||||
Some(addr) => addr,
|
||||
_ => {
|
||||
self.machine_st.fail = true;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let tls_key = self.deref_register(3);
|
||||
let tls_cert = self.deref_register(4);
|
||||
let content_length_limit = self.deref_register(5);
|
||||
const CONTENT_LENGTH_LIMIT_DEFAULT: u64 = 32768;
|
||||
let content_length_limit = match Number::try_from(content_length_limit) {
|
||||
Ok(Number::Fixnum(n)) => if n.get_num() >= 0 {
|
||||
n.get_num() as u64
|
||||
} else {
|
||||
CONTENT_LENGTH_LIMIT_DEFAULT
|
||||
},
|
||||
Ok(Number::Integer(n)) => {
|
||||
let n: Result<u64, _> = (&*n).try_into();
|
||||
match n {
|
||||
Ok(u) => u,
|
||||
Err(_) => CONTENT_LENGTH_LIMIT_DEFAULT,
|
||||
}
|
||||
}
|
||||
_ => CONTENT_LENGTH_LIMIT_DEFAULT,
|
||||
};
|
||||
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1024);
|
||||
let ssl_server: Option<(String,String)> = {
|
||||
match self.machine_st.value_to_str_like(tls_key) {
|
||||
Some(key) => {
|
||||
match self.machine_st.value_to_str_like(tls_cert) {
|
||||
Some(cert) => {
|
||||
let key_str = key.as_str();
|
||||
let cert_str = cert.as_str();
|
||||
|
||||
if key_str.is_empty() || cert_str.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some((key_str.to_string(), cert_str.to_string()))
|
||||
}
|
||||
}
|
||||
None => None
|
||||
}
|
||||
}
|
||||
None => None
|
||||
}
|
||||
};
|
||||
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let _guard = runtime.enter();
|
||||
if let Some(address_str) = self.machine_st.value_to_str_like(address_sink) {
|
||||
let address_string = address_str.as_str();
|
||||
let addr: SocketAddr = match address_string.to_socket_addrs().ok().and_then(|mut s| s.next()) {
|
||||
Some(addr) => addr,
|
||||
_ => {
|
||||
self.machine_st.fail = true;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let listener = match runtime
|
||||
.block_on(async { tokio::net::TcpListener::bind(addr).await })
|
||||
{
|
||||
Ok(listener) => listener,
|
||||
Err(_) => {
|
||||
return Err(self.machine_st.open_permission_error(
|
||||
address_sink,
|
||||
atom!("http_listen"),
|
||||
2,
|
||||
));
|
||||
}
|
||||
};
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1024);
|
||||
|
||||
runtime.spawn(async move {
|
||||
loop {
|
||||
let tx = tx.clone();
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
|
||||
tokio::task::spawn(async move {
|
||||
let io = TokioIo::new(stream);
|
||||
|
||||
if let Err(err) = http1::Builder::new()
|
||||
.serve_connection(io, HttpService {tx})
|
||||
.await
|
||||
{
|
||||
eprintln!("Error serving connection: {:?}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let http_listener = HttpListener { incoming: rx };
|
||||
let http_listener = arena_alloc!(http_listener, &mut self.machine_st.arena);
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let _guard = runtime.enter();
|
||||
|
||||
let addr = self.deref_register(2);
|
||||
self.machine_st.bind(
|
||||
addr.as_var().unwrap(),
|
||||
typed_arena_ptr_as_cell!(http_listener),
|
||||
);
|
||||
fn get_reader(body: impl Buf + Send + 'static) -> Box<dyn BufRead + Send> {
|
||||
Box::new(body.reader())
|
||||
}
|
||||
|
||||
let serve = warp::body::aggregate()
|
||||
.and(warp::header::optional::<u64>(warp::http::header::CONTENT_LENGTH.as_str()))
|
||||
.and(warp::method())
|
||||
.and(warp::header::headers_cloned())
|
||||
.and(warp::path::full())
|
||||
.and(warp::query::raw().or_else(|_| future::ready(Ok::<(String,), warp::Rejection>(("".to_string(),)))))
|
||||
.map(move |body, content_length, method, headers: warp::http::HeaderMap, path: warp::filters::path::FullPath, query| {
|
||||
if let Some(content_length) = content_length {
|
||||
if content_length > content_length_limit {
|
||||
return warp::http::Response::builder()
|
||||
.status(413)
|
||||
.body(warp::hyper::Body::empty())
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let http_request_data = HttpRequestData {
|
||||
method,
|
||||
headers,
|
||||
path: path.as_str().to_string(),
|
||||
query,
|
||||
body: get_reader(body),
|
||||
};
|
||||
let response = Arc::new((Mutex::new(false), Mutex::new(None), Condvar::new()));
|
||||
let http_request = HttpRequest { request_data: http_request_data, response: Arc::clone(&response) };
|
||||
// we send the request to http_accept
|
||||
tx.send(http_request).unwrap();
|
||||
|
||||
// we wait for the Response info from Prolog
|
||||
{
|
||||
let (ready, _response, cvar) = &*response;
|
||||
let mut ready = ready.lock().unwrap();
|
||||
while !*ready {
|
||||
ready = cvar.wait(ready).unwrap();
|
||||
}
|
||||
}
|
||||
{
|
||||
let (_, response, _) = &*response;
|
||||
let response = response.lock().unwrap().take();
|
||||
response.expect("Data race error in HTTP server")
|
||||
}
|
||||
});
|
||||
|
||||
runtime.spawn(async move {
|
||||
match ssl_server {
|
||||
Some((key, cert)) => {
|
||||
warp::serve(serve).tls().key(key).cert(cert).run(addr).await
|
||||
}
|
||||
None => {
|
||||
warp::serve(serve).run(addr).await
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let http_listener = HttpListener { incoming: rx };
|
||||
let http_listener = arena_alloc!(http_listener, &mut self.machine_st.arena);
|
||||
|
||||
let addr = self.deref_register(2);
|
||||
self.machine_st.bind(
|
||||
addr.as_var().unwrap(),
|
||||
typed_arena_ptr_as_cell!(http_listener),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -4494,75 +4541,94 @@ impl Machine {
|
||||
#[cfg(feature = "http")]
|
||||
#[inline(always)]
|
||||
pub(crate) fn http_accept(&mut self) -> CallResult {
|
||||
let culprit = self.deref_register(1);
|
||||
let method = self.deref_register(2);
|
||||
let path = self.deref_register(3);
|
||||
let query = self.deref_register(5);
|
||||
let stream_addr = self.deref_register(6);
|
||||
let handle_addr = self.deref_register(7);
|
||||
read_heap_cell!(culprit,
|
||||
(HeapCellValueTag::Cons, cons_ptr) => {
|
||||
match_untyped_arena_ptr!(cons_ptr,
|
||||
(ArenaHeaderTag::HttpListener, http_listener) => {
|
||||
match http_listener.incoming.recv() {
|
||||
Ok(request) => {
|
||||
let method_atom = match *request.request.method() {
|
||||
Method::GET => atom!("get"),
|
||||
Method::POST => atom!("post"),
|
||||
Method::PUT => atom!("put"),
|
||||
Method::DELETE => atom!("delete"),
|
||||
Method::PATCH => atom!("patch"),
|
||||
Method::HEAD => atom!("head"),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let path_atom = AtomTable::build_with(&self.machine_st.atom_tbl, request.request.uri().path());
|
||||
let path_cell = atom_as_cstr_cell!(path_atom);
|
||||
let headers: Vec<HeapCellValue> = request.request.headers().iter().map(|(header_name, header_value)| {
|
||||
let h = self.machine_st.heap.len();
|
||||
let culprit = self.deref_register(1);
|
||||
let method = self.deref_register(2);
|
||||
let path = self.deref_register(3);
|
||||
let query = self.deref_register(5);
|
||||
let stream_addr = self.deref_register(6);
|
||||
let handle_addr = self.deref_register(7);
|
||||
read_heap_cell!(culprit,
|
||||
(HeapCellValueTag::Cons, cons_ptr) => {
|
||||
match_untyped_arena_ptr!(cons_ptr,
|
||||
(ArenaHeaderTag::HttpListener, http_listener) => {
|
||||
loop {
|
||||
match http_listener.incoming.recv_timeout(std::time::Duration::from_millis(200)) {
|
||||
Ok(request) => {
|
||||
let method_atom = match request.request_data.method {
|
||||
Method::GET => atom!("get"),
|
||||
Method::POST => atom!("post"),
|
||||
Method::PUT => atom!("put"),
|
||||
Method::DELETE => atom!("delete"),
|
||||
Method::PATCH => atom!("patch"),
|
||||
Method::HEAD => atom!("head"),
|
||||
Method::OPTIONS => atom!("options"),
|
||||
Method::TRACE => atom!("trace"),
|
||||
Method::CONNECT => atom!("connect"),
|
||||
_ => atom!("unsupported_extension"),
|
||||
};
|
||||
let path_atom = AtomTable::build_with(&self.machine_st.atom_tbl, &request.request_data.path);
|
||||
let path_cell = atom_as_cstr_cell!(path_atom);
|
||||
let headers: Vec<HeapCellValue> = request.request_data.headers.iter().map(|(header_name, header_value)| {
|
||||
let h = self.machine_st.heap.len();
|
||||
let header_term = functor!(AtomTable::build_with(&self.machine_st.atom_tbl, header_name.as_str()), [cell(string_as_cstr_cell!(AtomTable::build_with(&self.machine_st.atom_tbl, header_value.to_str().unwrap())))]);
|
||||
|
||||
let header_term = functor!(
|
||||
AtomTable::build_with(&self.machine_st.atom_tbl, header_name.as_str()),
|
||||
[cell(string_as_cstr_cell!(AtomTable::build_with(&self.machine_st.atom_tbl, header_value.to_str().unwrap())))]
|
||||
);
|
||||
self.machine_st.heap.extend(header_term.into_iter());
|
||||
str_loc_as_cell!(h)
|
||||
}).collect();
|
||||
|
||||
self.machine_st.heap.extend(header_term.into_iter());
|
||||
str_loc_as_cell!(h)
|
||||
}).collect();
|
||||
let headers_list = iter_to_heap_list(&mut self.machine_st.heap, headers.into_iter());
|
||||
|
||||
let headers_list = iter_to_heap_list(&mut self.machine_st.heap, headers.into_iter());
|
||||
let query_str = request.request_data.query;
|
||||
let query_atom = AtomTable::build_with(&self.machine_st.atom_tbl, &query_str);
|
||||
let query_cell = string_as_cstr_cell!(query_atom);
|
||||
|
||||
let query_str = request.request.uri().query().unwrap_or("");
|
||||
let query_atom = AtomTable::build_with(&self.machine_st.atom_tbl, query_str);
|
||||
let query_cell = string_as_cstr_cell!(query_atom);
|
||||
let mut stream = Stream::from_http_stream(
|
||||
path_atom,
|
||||
request.request_data.body,
|
||||
&mut self.machine_st.arena
|
||||
);
|
||||
*stream.options_mut() = StreamOptions::default();
|
||||
stream.options_mut().set_stream_type(StreamType::Binary);
|
||||
self.indices.streams.insert(stream);
|
||||
let stream = stream_as_cell!(stream);
|
||||
|
||||
let hyper_req = request.request;
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let buf = runtime.block_on(async {hyper_req.collect().await.unwrap().aggregate()});
|
||||
let reader = buf.reader();
|
||||
let handle = arena_alloc!(request.response, &mut self.machine_st.arena);
|
||||
|
||||
let mut stream = Stream::from_http_stream(
|
||||
path_atom,
|
||||
Box::new(reader),
|
||||
&mut self.machine_st.arena
|
||||
);
|
||||
*stream.options_mut() = StreamOptions::default();
|
||||
stream.options_mut().set_stream_type(StreamType::Binary);
|
||||
self.indices.streams.insert(stream);
|
||||
let stream = stream_as_cell!(stream);
|
||||
self.machine_st.bind(method.as_var().unwrap(), atom_as_cell!(method_atom));
|
||||
self.machine_st.bind(path.as_var().unwrap(), path_cell);
|
||||
unify!(self.machine_st, heap_loc_as_cell!(headers_list), self.machine_st.registers[4]);
|
||||
self.machine_st.bind(query.as_var().unwrap(), query_cell);
|
||||
self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
|
||||
self.machine_st.bind(handle_addr.as_var().unwrap(), typed_arena_ptr_as_cell!(handle));
|
||||
break
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
let interrupted = machine::INTERRUPT.load(std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
let handle = arena_alloc!(request.response, &mut self.machine_st.arena);
|
||||
match machine::INTERRUPT.compare_exchange(
|
||||
interrupted,
|
||||
false,
|
||||
std::sync::atomic::Ordering::Relaxed,
|
||||
std::sync::atomic::Ordering::Relaxed,
|
||||
) {
|
||||
Ok(interruption) => {
|
||||
if interruption {
|
||||
self.machine_st.throw_interrupt_exception();
|
||||
self.machine_st.backtrack();
|
||||
let old_runtime = std::mem::replace(&mut self.runtime, tokio::runtime::Runtime::new().unwrap());
|
||||
old_runtime.shutdown_background();
|
||||
break
|
||||
}
|
||||
}
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
|
||||
self.machine_st.bind(method.as_var().unwrap(), atom_as_cell!(method_atom));
|
||||
self.machine_st.bind(path.as_var().unwrap(), path_cell);
|
||||
unify!(self.machine_st, heap_loc_as_cell!(headers_list), self.machine_st.registers[4]);
|
||||
self.machine_st.bind(query.as_var().unwrap(), query_cell);
|
||||
self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
|
||||
self.machine_st.bind(handle_addr.as_var().unwrap(), typed_arena_ptr_as_cell!(handle));
|
||||
}
|
||||
Err(_) => {
|
||||
self.machine_st.fail = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
self.machine_st.fail = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
unreachable!();
|
||||
@@ -4585,7 +4651,7 @@ impl Machine {
|
||||
Ok(Number::Fixnum(n)) => n.get_num() as u16,
|
||||
Ok(Number::Integer(n)) => {
|
||||
let n: Result<u16, _> = (&*n).try_into();
|
||||
|
||||
|
||||
if let Ok(value) = n {
|
||||
value
|
||||
} else {
|
||||
@@ -5597,7 +5663,9 @@ impl Machine {
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn redo_attr_var_binding(&mut self) {
|
||||
let var = self.deref_register(1);
|
||||
// registers[1] MUST NOT be dereferenced here. the original
|
||||
// AttrVar binding site must be preserved.
|
||||
let var = self.machine_st.registers[1];
|
||||
let value = self.deref_register(2);
|
||||
|
||||
debug_assert_eq!(HeapCellValueTag::AttrVar, var.get_tag());
|
||||
@@ -5631,7 +5699,7 @@ impl Machine {
|
||||
|
||||
if bp == self.machine_st.b && self.machine_st.cwil.is_empty() {
|
||||
self.machine_st.cwil.reset();
|
||||
self.machine_st.increment_call_count_fn = |_| Ok(());
|
||||
self.machine_st.increment_call_count_fn = |_| true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5640,11 +5708,10 @@ impl Machine {
|
||||
let a1 = self.deref_register(1);
|
||||
let a2 = self.deref_register(2);
|
||||
|
||||
let bp = cell_as_fixnum!(a1).get_num() as usize;
|
||||
|
||||
let count = self.machine_st.cwil.remove_limit(bp).clone();
|
||||
|
||||
let block = cell_as_fixnum!(a1).get_num() as usize;
|
||||
let count = self.machine_st.cwil.remove_limit(block).clone();
|
||||
let result = count.clone().try_into();
|
||||
|
||||
if let Ok(value) = result{
|
||||
self.machine_st.unify_fixnum(Fixnum::build_with(value), a2);
|
||||
} else {
|
||||
@@ -5811,6 +5878,11 @@ impl Machine {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn inference_limit_exceeded(&mut self) {
|
||||
self.machine_st.fail = !self.machine_st.cwil.inference_limit_exceeded;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn clean_up_block(&mut self) {
|
||||
let nb = self.deref_register(1);
|
||||
@@ -6191,16 +6263,19 @@ impl Machine {
|
||||
match Number::try_from(seed) {
|
||||
Ok(Number::Fixnum(n)) => {
|
||||
let n: u64 = Integer::from(n).try_into().unwrap();
|
||||
let _: StdRng = SeedableRng::seed_from_u64(n);
|
||||
let rng: StdRng = SeedableRng::seed_from_u64(n);
|
||||
self.rng = rng;
|
||||
},
|
||||
Ok(Number::Integer(n)) => {
|
||||
let n: u64 = (&*n).try_into().unwrap();
|
||||
let _: StdRng = SeedableRng::seed_from_u64(n);
|
||||
let rng: StdRng = SeedableRng::seed_from_u64(n);
|
||||
self.rng = rng;
|
||||
},
|
||||
Ok(Number::Rational(n)) => {
|
||||
if n.denominator() == &UBig::from(1 as u32) {
|
||||
let n: u64 = n.numerator().try_into().unwrap();
|
||||
let _: StdRng = SeedableRng::seed_from_u64(n);
|
||||
let rng: StdRng = SeedableRng::seed_from_u64(n);
|
||||
self.rng = rng;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
@@ -7330,7 +7405,7 @@ impl Machine {
|
||||
let iterations = match Number::try_from(iterations) {
|
||||
Ok(Number::Fixnum(n)) => u64::try_from(n.get_num()).unwrap(),
|
||||
Ok(Number::Integer(n)) => {
|
||||
let n: Result<u64, _> = (&*n).try_into();
|
||||
let n: Result<u64, _> = (&*n).try_into();
|
||||
match n {
|
||||
Ok(i) => i,
|
||||
_ => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::arena::*;
|
||||
use crate::forms::*;
|
||||
use crate::heap_iter::stackful_preorder_iter;
|
||||
use crate::heap_iter::{NonListElider, stackful_preorder_iter};
|
||||
use crate::machine::machine_state::*;
|
||||
use crate::machine::partial_string::*;
|
||||
use crate::machine::*;
|
||||
@@ -717,7 +717,7 @@ 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(&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() {
|
||||
|
||||
@@ -34,6 +34,7 @@ pub const FY: u32 = 0x0080;
|
||||
pub const DELIMITER: u32 = 0x0100;
|
||||
pub const TERM: u32 = 0x1000;
|
||||
pub const LTERM: u32 = 0x3000;
|
||||
pub const BTERM: u32 = 0x11000;
|
||||
|
||||
pub const NEGATIVE_SIGN: u32 = 0x0200;
|
||||
|
||||
@@ -808,7 +809,7 @@ pub fn source_arity(terms: &[Term]) -> usize {
|
||||
terms.len()
|
||||
}
|
||||
|
||||
fn unfold_by_str_once(term: &mut Term, s: Atom) -> Option<(Term, Term)> {
|
||||
pub(crate) fn unfold_by_str_once(term: &mut Term, s: Atom) -> Option<(Term, Term)> {
|
||||
if let Term::Clause(_, ref name, ref mut subterms) = term {
|
||||
if let Some(last_arg) = subterms.last() {
|
||||
if let Term::Literal(_, Literal::CodeIndex(_)) = last_arg {
|
||||
|
||||
@@ -132,7 +132,7 @@ macro_rules! hexadecimal_digit_char {
|
||||
#[macro_export]
|
||||
macro_rules! layout_char {
|
||||
($c: expr) => {
|
||||
$crate::char_class!($c, [' ', '\n', '\t', '\u{0B}', '\u{0C}'])
|
||||
$crate::char_class!($c, [' ', '\r', '\n', '\t', '\u{0B}', '\u{0C}'])
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ struct TokenDesc {
|
||||
tt: TokenType,
|
||||
priority: usize,
|
||||
spec: u32,
|
||||
unfold_bounds: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn as_partial_string(
|
||||
@@ -371,6 +372,7 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
tt: TokenType::Term,
|
||||
priority: td.priority,
|
||||
spec,
|
||||
unfold_bounds: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -392,6 +394,7 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
tt: TokenType::Term,
|
||||
priority: td.priority,
|
||||
spec,
|
||||
unfold_bounds: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -405,6 +408,7 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
tt: TokenType::Term,
|
||||
priority,
|
||||
spec: assoc,
|
||||
unfold_bounds: 0,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -460,7 +464,7 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
Token::End => TokenType::End,
|
||||
};
|
||||
|
||||
self.stack.push(TokenDesc { tt, priority, spec });
|
||||
self.stack.push(TokenDesc { tt, priority, spec, unfold_bounds: 0, });
|
||||
}
|
||||
|
||||
fn reduce_op(&mut self, priority: usize) {
|
||||
@@ -602,14 +606,20 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
}
|
||||
|
||||
if let Some(&mut TokenDesc {
|
||||
ref mut tt,
|
||||
ref mut priority,
|
||||
ref mut spec,
|
||||
ref mut tt,
|
||||
ref mut unfold_bounds,
|
||||
}) = self.stack.last_mut()
|
||||
{
|
||||
if *spec == BTERM {
|
||||
return false;
|
||||
}
|
||||
|
||||
*tt = TokenType::Term;
|
||||
*priority = 0;
|
||||
*spec = TERM;
|
||||
*unfold_bounds = 0;
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -625,8 +635,8 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
}
|
||||
|
||||
fn expand_comma_compacted_terms(&mut self, index: usize) -> usize {
|
||||
if let Some(term) = self.terms.pop() {
|
||||
let op_desc = self.stack[index - 1];
|
||||
if let Some(mut term) = self.terms.pop() {
|
||||
let mut op_desc = self.stack[index - 1];
|
||||
|
||||
if 0 < op_desc.priority && op_desc.priority < self.stack[index].priority {
|
||||
/* '|' is a head-tail separator here, not
|
||||
@@ -634,7 +644,26 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
* terms it compacted out again. */
|
||||
match (term.name(), term.arity()) {
|
||||
(Some(name), 2) if name == atom!(",") => {
|
||||
let terms = unfold_by_str(term, name); // notice: name == "," here.
|
||||
let terms = if op_desc.unfold_bounds == 0 {
|
||||
unfold_by_str(term, atom!(","))
|
||||
} else {
|
||||
let mut terms = vec![];
|
||||
|
||||
while let Some((fst, snd)) = unfold_by_str_once(&mut term, atom!(",")) {
|
||||
terms.push(fst);
|
||||
term = snd;
|
||||
|
||||
op_desc.unfold_bounds -= 2;
|
||||
|
||||
if op_desc.unfold_bounds == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
terms.push(term);
|
||||
terms
|
||||
};
|
||||
|
||||
let arity = terms.len() - 1;
|
||||
|
||||
self.terms.extend(terms.into_iter());
|
||||
@@ -750,6 +779,7 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
tt: TokenType::Term,
|
||||
priority: 0,
|
||||
spec: TERM,
|
||||
unfold_bounds: 0,
|
||||
});
|
||||
|
||||
self.terms.push(match list {
|
||||
@@ -852,7 +882,7 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
.push(Term::Literal(Cell::default(), Literal::Atom(atom)));
|
||||
}
|
||||
|
||||
self.stack[idx].spec = TERM;
|
||||
self.stack[idx].spec = if self.stack[idx].priority > 0 { TERM } else { BTERM };
|
||||
self.stack[idx].tt = TokenType::Term;
|
||||
self.stack[idx].priority = 0;
|
||||
|
||||
@@ -975,6 +1005,7 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
),
|
||||
Token::Literal(c) => {
|
||||
let atomized = atomize_constant(&self.lexer.machine_st.atom_tbl, c);
|
||||
|
||||
if let Some(name) = atomized {
|
||||
if !self.shift_op(name, op_dir)? {
|
||||
self.shift(Token::Literal(c), 0, TERM);
|
||||
@@ -1018,13 +1049,20 @@ impl<'a, R: CharRead> Parser<'a, R> {
|
||||
/* '|' as an operator must have priority > 1000 and can only be infix.
|
||||
* See: http://www.complang.tuwien.ac.at/ulrich/iso-prolog/dtc2#Res_A78
|
||||
*/
|
||||
let bar_atom = atom!("|");
|
||||
|
||||
let (priority, spec) = get_op_desc(bar_atom, op_dir)
|
||||
let (priority, spec) = get_op_desc(atom!("|"), op_dir)
|
||||
.map(|CompositeOpDesc { inf, spec, .. }| (inf, spec))
|
||||
.unwrap_or((1000, DELIMITER));
|
||||
|
||||
let old_stack_len = self.stack.len();
|
||||
|
||||
self.reduce_op(priority);
|
||||
|
||||
let new_stack_len = self.stack.len();
|
||||
|
||||
if let Some(term_desc) = self.stack.last_mut() {
|
||||
term_desc.unfold_bounds = old_stack_len - new_stack_len;
|
||||
}
|
||||
|
||||
self.shift(Token::HeadTailSeparator, priority, spec);
|
||||
}
|
||||
Token::Comma => {
|
||||
|
||||
270
src/tests/dif.pl
Normal file
270
src/tests/dif.pl
Normal file
@@ -0,0 +1,270 @@
|
||||
/**/
|
||||
|
||||
:- use_module(library(format)).
|
||||
:- use_module(library(dcgs)).
|
||||
:- use_module(library(lists)).
|
||||
:- use_module(library(debug)).
|
||||
:- use_module(library(atts)).
|
||||
:- use_module(library(dif)).
|
||||
|
||||
% Tests from https://www.complang.tuwien.ac.at/ulrich/iso-prolog/dif
|
||||
|
||||
test("dif#1",(
|
||||
call_residual_goals(dif(1,2), Res),
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#2",(
|
||||
\+ (dif(1,Y), Y = 1)
|
||||
)).
|
||||
|
||||
test("dif#3",(
|
||||
call_residual_goals((dif(1,Y), Y=2), Res),
|
||||
Y == 2,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#4",(
|
||||
\+ (dif(X,-Y), X= -Y)
|
||||
)).
|
||||
|
||||
test("dif#5",(
|
||||
\+ (dif(X,Y), X=Y)
|
||||
)).
|
||||
|
||||
test("dif#6",(
|
||||
\+ (dif(X,Y), X=Y, X=1)
|
||||
)).
|
||||
|
||||
test("dif#7",(
|
||||
\+ (dif(-X,-Y), X=Y)
|
||||
)).
|
||||
|
||||
test("dif#8",(
|
||||
\+ (dif(-X,-Y), X=Y, X=1)
|
||||
)).
|
||||
|
||||
% I don't understand exactly what is expected for dif#9 and dif#10
|
||||
|
||||
test("dif#11",(
|
||||
call_residual_goals((X=Y, dif(X-Y,1-2)), Res),
|
||||
X == Y,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#12",(
|
||||
call_residual_goals((dif(X-Y,1-2), X=Y), Res),
|
||||
X == Y,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#13",(
|
||||
call_residual_goals((X=Y, Y=1, dif(X-Y,1-2)), Res),
|
||||
X == 1,
|
||||
Y == 1,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#14",(
|
||||
call_residual_goals((dif(X-Y,1-2), X=Y, Y=1), Res),
|
||||
X == 1,
|
||||
Y == 1,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#15",(
|
||||
call_residual_goals((dif(X-Y,1-2), X=Y, X=2), Res),
|
||||
X == 2,
|
||||
Y == 2,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#16",(
|
||||
call_residual_goals((dif(A-C,B-D), C-D=z-z, A-B=1-2), Res),
|
||||
A == 1,
|
||||
B == 2,
|
||||
C == z,
|
||||
D == z,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#17",(
|
||||
call_residual_goals((A-B=1-2, C-D=z-z, dif(A-C,B-D)), Res),
|
||||
A == 1,
|
||||
B == 2,
|
||||
C == z,
|
||||
D == z,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#18",(
|
||||
call_residual_goals((dif(A,[C|B]), A=[[]|_], A=[B]), Res),
|
||||
A == [[]],
|
||||
B == [],
|
||||
Res = [dif:dif([[]], [C])]
|
||||
)).
|
||||
|
||||
test("dif#19",(
|
||||
call_residual_goals((dif([E],[/]), E=1), Res),
|
||||
E == 1,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#20",(
|
||||
call_residual_goals((dif([a],B), B=[_|_], B=[b]), Res),
|
||||
B == [b],
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#21",(
|
||||
call_residual_goals((dif([],A), A = [_]), Res),
|
||||
A = [_],
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#22",(
|
||||
call_residual_goals((A = [_], dif([],A)), Res),
|
||||
A = [_],
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#t1",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
\+ \+ -X=X
|
||||
)).
|
||||
|
||||
test("dif#t2",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
\+ (-X=X, -Y=Y, X\=Y)
|
||||
)).
|
||||
|
||||
test("dif#t3",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
call_residual_goals((-X=X, dif(X,1)), Res),
|
||||
X == -X,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#t4",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
\+ (-X=X, -Y=Y, dif(X,Y))
|
||||
)).
|
||||
|
||||
test("dif#t5",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
\+ (dif(X,Y), -X=X, -Y=Y)
|
||||
)).
|
||||
|
||||
test("dif#t6",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
\+ (A=[[]|A],dif(A,B),B=[[]|A])
|
||||
)).
|
||||
|
||||
test("dif#t7",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
\+ (dif(-X,X),-Y=Y,X=Y)
|
||||
)).
|
||||
|
||||
test("dif#o1",(
|
||||
set_prolog_flag(occurs_check, true),
|
||||
\+ (-X = X)
|
||||
)).
|
||||
|
||||
test("dif#o2",(
|
||||
set_prolog_flag(occurs_check, true),
|
||||
call_residual_goals((dif(-X,X)), Res),
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#o3",(
|
||||
set_prolog_flag(occurs_check, true),
|
||||
call_residual_goals((dif(-X,Y), X=Y), Res),
|
||||
X == Y,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
test("dif#12 but with multiple variables in the residuals",(
|
||||
call_residual_goals((dif(X-Y-_, 1-2-3), X = Y), Res),
|
||||
X == Y,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
% https://github.com/mthom/scryer-prolog/issues/1956
|
||||
test("scryer-prolog#1956",(
|
||||
call_residue_vars((dif(a-a,X-_),X=b), Res),
|
||||
X == b,
|
||||
Res = []
|
||||
)).
|
||||
|
||||
% https://github.com/mthom/scryer-prolog/issues/2056
|
||||
test("scryer-prolog#2056",(
|
||||
set_prolog_flag(occurs_check, false),
|
||||
C=[D|E],
|
||||
D=[C],
|
||||
A=[A],
|
||||
dif(A,[D]),
|
||||
|
||||
\+ E=[]
|
||||
)).
|
||||
|
||||
main :-
|
||||
findall(test(Name, Goal), test(Name, Goal), Tests),
|
||||
run_tests(Tests, Failed),
|
||||
show_failed(Failed),
|
||||
halt.
|
||||
|
||||
main_quiet :-
|
||||
findall(test(Name, Goal), test(Name, Goal), Tests),
|
||||
run_tests_quiet(Tests, Failed),
|
||||
( Failed = [] ->
|
||||
format("All tests passed", [])
|
||||
; format("Some tests failed", [])
|
||||
),
|
||||
halt.
|
||||
|
||||
portray_failed_([]) --> [].
|
||||
portray_failed_([F|Fs]) -->
|
||||
"\"", F, "\"", "\n", portray_failed_(Fs).
|
||||
|
||||
portray_failed([]) --> [].
|
||||
portray_failed([F|Fs]) -->
|
||||
"\n", "Failed tests:", "\n", portray_failed_([F|Fs]).
|
||||
|
||||
show_failed(Failed) :-
|
||||
phrase(portray_failed(Failed), F),
|
||||
format("~s", [F]).
|
||||
|
||||
run_tests([], []).
|
||||
run_tests([test(Name, Goal)|Tests], Failed) :-
|
||||
format("Running test \"~s\"~n", [Name]),
|
||||
( call(Goal) ->
|
||||
Failed = Failed1
|
||||
; format("Failed test \"~s\"~n", [Name]),
|
||||
Failed = [Name|Failed1]
|
||||
),
|
||||
run_tests(Tests, Failed1).
|
||||
|
||||
run_tests_quiet([], []).
|
||||
run_tests_quiet([test(Name, Goal)|Tests], Failed) :-
|
||||
( call(Goal) ->
|
||||
Failed = Failed1
|
||||
; Failed = [Name|Failed1]
|
||||
),
|
||||
run_tests_quiet(Tests, Failed1).
|
||||
|
||||
assert_p(A, B) :-
|
||||
phrase(portray_clause_(A), Portrayed),
|
||||
phrase((B, ".\n"), Portrayed).
|
||||
|
||||
call_residual_goals(Goal, ResidualGoals) :-
|
||||
call_residue_vars(Goal, Vars),
|
||||
variables_residual_goals(Vars, ResidualGoals).
|
||||
|
||||
variables_residual_goals(Vars, Goals) :-
|
||||
phrase(variables_residual_goals(Vars), Goals).
|
||||
|
||||
variables_residual_goals([]) --> [].
|
||||
variables_residual_goals([Var|Vars]) -->
|
||||
dif:attribute_goals(Var),
|
||||
variables_residual_goals(Vars).
|
||||
|
||||
Reference in New Issue
Block a user