use fixnums in place of bignums where possible

This commit is contained in:
Mark Thom
2020-04-05 20:32:16 -06:00
parent c8855f97e8
commit d76ae413c4
26 changed files with 1915 additions and 1195 deletions

6
Cargo.lock generated
View File

@@ -444,7 +444,7 @@ dependencies = [
[[package]]
name = "prolog_parser"
version = "0.8.48"
version = "0.8.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"lexical 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -580,7 +580,7 @@ dependencies = [
"nix 0.15.0 (registry+https://github.com/rust-lang/crates.io-index)",
"num-rug-adapter 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"ordered-float 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
"prolog_parser 0.8.48 (registry+https://github.com/rust-lang/crates.io-index)",
"prolog_parser 0.8.49 (registry+https://github.com/rust-lang/crates.io-index)",
"ref_thread_local 0.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rug 1.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
"rustyline 6.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -791,7 +791,7 @@ dependencies = [
"checksum parking_lot 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "92e98c49ab0b7ce5b222f2cc9193fc4efe11c6d0bd4f648e374684a6857b1cfc"
"checksum parking_lot_core 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7582838484df45743c8434fbff785e8edf260c28748353d44bc0da32e0ceabf1"
"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759"
"checksum prolog_parser 0.8.48 (registry+https://github.com/rust-lang/crates.io-index)" = "301d67e5905691f8d5dc5f08c8c6e12cf849a12bea779af8b5221c35b89faf95"
"checksum prolog_parser 0.8.49 (registry+https://github.com/rust-lang/crates.io-index)" = "82f46113e58039861f82f6b6cdaca94c0997eda2c7317a4c4f13d549c4601eec"
"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1"
"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"
"checksum rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc"

View File

@@ -25,7 +25,7 @@ libc = "0.2.62"
nix = "0.15.0"
num-rug-adapter = { optional = true, version = "0.1.1" }
ordered-float = "0.5.0"
prolog_parser = { version = "0.8.48", default-features = false }
prolog_parser = { version = "0.8.49", default-features = false }
ref_thread_local = "0.0.0"
rug = { version = "1.4.0", optional = true }
rustyline = "6.0.0"

View File

@@ -6,6 +6,7 @@ use crate::prolog::forms::*;
use crate::prolog::instructions::*;
use crate::prolog::iterators::*;
use crate::prolog::machine::heap::*;
use crate::prolog::machine::machine_errors::*;
use crate::prolog::machine::machine_indices::*;
@@ -15,6 +16,7 @@ use crate::prolog::rug::{Assign, Integer, Rational};
use std::cell::Cell;
use std::cmp::{max, min, Ordering};
use std::convert::TryFrom;
use std::f64;
use std::num::FpCategory;
use std::ops::{Add, Div, Mul, Neg, Sub};
@@ -262,6 +264,9 @@ impl<'a> ArithmeticEvaluator<'a> {
fn push_constant(&mut self, c: &Constant) -> Result<(), ArithmeticError> {
match c {
&Constant::Fixnum(n) => self
.interm
.push(ArithmeticTerm::Number(Number::Fixnum(n))),
&Constant::Integer(ref n) => self
.interm
.push(ArithmeticTerm::Number(Number::Integer(n.clone()))),
@@ -316,18 +321,25 @@ impl<'a> ArithmeticEvaluator<'a> {
}
// integer division rounding function -- 9.1.3.1.
pub fn rnd_i<'a>(n: &'a Number) -> RefOrOwned<'a, Integer> {
pub fn rnd_i<'a>(n: &'a Number) -> RefOrOwned<'a, Number> {
match n {
&Number::Integer(ref n) => RefOrOwned::Borrowed(n),
&Number::Integer(_) => {
RefOrOwned::Borrowed(n)
}
&Number::Float(OrderedFloat(f)) => {
RefOrOwned::Owned(Integer::from_f64(f.floor()).unwrap_or_else(|| Integer::from(0)))
RefOrOwned::Owned(Number::from(
Integer::from_f64(f.floor()).unwrap_or_else(|| Integer::from(0))
))
}
&Number::Fixnum(n) => {
RefOrOwned::Owned(Number::from(n))
}
&Number::Rational(ref r) => {
let r_ref = r.fract_floor_ref();
let (mut fract, mut floor) = (Rational::new(), Integer::new());
(&mut fract, &mut floor).assign(r_ref);
RefOrOwned::Owned(floor)
RefOrOwned::Owned(Number::from(floor))
}
}
}
@@ -335,6 +347,7 @@ pub fn rnd_i<'a>(n: &'a Number) -> RefOrOwned<'a, Integer> {
// floating point rounding function -- 9.1.4.1.
pub fn rnd_f(n: &Number) -> f64 {
match n {
&Number::Fixnum(n) => n as f64,
&Number::Integer(ref n) => n.to_f64(),
&Number::Float(OrderedFloat(f)) => f,
&Number::Rational(ref r) => r.to_f64(),
@@ -370,22 +383,32 @@ where
}
}
#[inline]
fn float_fn_to_f(n: isize) -> Result<f64, EvalError> {
classify_float(n as f64, rnd_f)
}
#[inline]
fn float_i_to_f(n: &Integer) -> Result<f64, EvalError> {
classify_float(n.to_f64(), rnd_f)
}
#[inline]
fn float_r_to_f(r: &Rational) -> Result<f64, EvalError> {
classify_float(r.to_f64(), rnd_f)
}
#[inline]
fn add_f(f1: f64, f2: f64) -> Result<OrderedFloat<f64>, EvalError> {
Ok(OrderedFloat(classify_float(f1 + f2, rnd_f)?))
}
#[inline]
fn mul_f(f1: f64, f2: f64) -> Result<OrderedFloat<f64>, EvalError> {
Ok(OrderedFloat(classify_float(f1 * f2, rnd_f)?))
}
#[inline]
fn div_f(f1: f64, f2: f64) -> Result<OrderedFloat<f64>, EvalError> {
if FpCategory::Zero == f2.classify() {
Err(EvalError::ZeroDivisor)
@@ -399,8 +422,27 @@ impl Add<Number> for Number {
fn add(self, rhs: Number) -> Self::Output {
match (self, rhs) {
(Number::Fixnum(n1), Number::Fixnum(n2)) => {
Ok(if let Some(result) = n1.checked_add(n2) {
Number::Fixnum(result)
} else {
Number::from(Integer::from(n1) + Integer::from(n2))
})
}
(Number::Fixnum(n1), Number::Integer(n2)) |
(Number::Integer(n2), Number::Fixnum(n1)) => {
Ok(Number::from(Integer::from(n1) + &*n2))
}
(Number::Fixnum(n1), Number::Rational(n2)) |
(Number::Rational(n2), Number::Fixnum(n1)) => {
Ok(Number::from(Rational::from(n1) + &*n2))
}
(Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) |
(Number::Float(OrderedFloat(n2)), Number::Fixnum(n1)) => {
Ok(Number::Float(add_f(float_fn_to_f(n1)?, n2)?))
}
(Number::Integer(n1), Number::Integer(n2)) => {
Ok(Number::Integer(Rc::new(Integer::from(&*n1) + &*n2))) // add_i
Ok(Number::from(Integer::from(&*n1) + &*n2)) // add_i
}
(Number::Integer(n1), Number::Float(OrderedFloat(n2)))
| (Number::Float(OrderedFloat(n2)), Number::Integer(n1)) => {
@@ -408,7 +450,7 @@ impl Add<Number> for Number {
}
(Number::Integer(n1), Number::Rational(n2))
| (Number::Rational(n2), Number::Integer(n1)) => {
Ok(Number::Rational(Rc::new(Rational::from(&*n1) + &*n2)))
Ok(Number::from(Rational::from(&*n1) + &*n2))
}
(Number::Rational(n1), Number::Float(OrderedFloat(n2)))
| (Number::Float(OrderedFloat(n2)), Number::Rational(n1)) => {
@@ -418,7 +460,7 @@ impl Add<Number> for Number {
Ok(Number::Float(add_f(f1, f2)?))
}
(Number::Rational(r1), Number::Rational(r2)) => {
Ok(Number::Rational(Rc::new(Rational::from(&*r1) + &*r2)))
Ok(Number::from(Rational::from(&*r1) + &*r2))
}
}
}
@@ -429,6 +471,7 @@ impl Neg for Number {
fn neg(self) -> Self::Output {
match self {
Number::Fixnum(n) => Number::Fixnum(-n),
Number::Integer(n) => Number::Integer(Rc::new(-Integer::from(&*n))),
Number::Float(OrderedFloat(f)) => Number::Float(OrderedFloat(-f)),
Number::Rational(r) => Number::Rational(Rc::new(-Rational::from(&*r))),
@@ -449,6 +492,25 @@ impl Mul<Number> for Number {
fn mul(self, rhs: Number) -> Self::Output {
match (self, rhs) {
(Number::Fixnum(n1), Number::Fixnum(n2)) => {
Ok(if let Some(result) = n1.checked_mul(n2) {
Number::Fixnum(result)
} else {
Number::from(Integer::from(n1) * Integer::from(n2))
})
}
(Number::Fixnum(n1), Number::Integer(n2)) |
(Number::Integer(n2), Number::Fixnum(n1)) => {
Ok(Number::from(Integer::from(n1) * &*n2))
}
(Number::Fixnum(n1), Number::Rational(n2)) |
(Number::Rational(n2), Number::Fixnum(n1)) => {
Ok(Number::from(Rational::from(n1) * &*n2))
}
(Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) |
(Number::Float(OrderedFloat(n2)), Number::Fixnum(n1)) => {
Ok(Number::Float(mul_f(float_fn_to_f(n1)?, n2)?))
}
(Number::Integer(n1), Number::Integer(n2)) => {
Ok(Number::Integer(Rc::new(Integer::from(&*n1) * &*n2))) // mul_i
}
@@ -479,24 +541,72 @@ impl Div<Number> for Number {
fn div(self, rhs: Number) -> Self::Output {
match (self, rhs) {
(Number::Integer(n1), Number::Integer(n2)) => Ok(Number::Float(div_f(
(Number::Fixnum(n1), Number::Fixnum(n2)) => {
Ok(Number::Float(div_f(
float_fn_to_f(n1)?,
float_fn_to_f(n2)?,
)?))
}
(Number::Fixnum(n1), Number::Integer(n2)) => {
Ok(Number::Float(div_f(
float_fn_to_f(n1)?,
float_i_to_f(&n2)?,
)?))
}
(Number::Integer(n1), Number::Fixnum(n2)) => {
Ok(Number::Float(div_f(
float_i_to_f(&n1)?,
float_fn_to_f(n2)?,
)?))
}
(Number::Fixnum(n1), Number::Rational(n2)) => {
Ok(Number::Float(div_f(
float_fn_to_f(n1)?,
float_r_to_f(&n2)?,
)?))
}
(Number::Rational(n1), Number::Fixnum(n2)) => {
Ok(Number::Float(div_f(
float_r_to_f(&n1)?,
float_fn_to_f(n2)?,
)?))
}
(Number::Fixnum(n1), Number::Float(OrderedFloat(n2))) => {
Ok(Number::Float(div_f(
float_fn_to_f(n1)?,
n2,
)?))
}
(Number::Float(OrderedFloat(n1)), Number::Fixnum(n2)) => {
Ok(Number::Float(div_f(
n1,
float_fn_to_f(n2)?,
)?))
}
(Number::Integer(n1), Number::Integer(n2)) => {
Ok(Number::Float(div_f(
float_i_to_f(&n1)?,
float_i_to_f(&n2)?,
)?)),
)?))
}
(Number::Integer(n1), Number::Float(OrderedFloat(n2))) => {
Ok(Number::Float(div_f(float_i_to_f(&n1)?, n2)?))
}
(Number::Float(OrderedFloat(n2)), Number::Integer(n1)) => {
Ok(Number::Float(div_f(n2, float_i_to_f(&n1)?)?))
}
(Number::Integer(n1), Number::Rational(n2)) => Ok(Number::Float(div_f(
(Number::Integer(n1), Number::Rational(n2)) => {
Ok(Number::Float(div_f(
float_i_to_f(&n1)?,
float_r_to_f(&n2)?,
)?)),
(Number::Rational(n2), Number::Integer(n1)) => Ok(Number::Float(div_f(
)?))
}
(Number::Rational(n2), Number::Integer(n1)) => {
Ok(Number::Float(div_f(
float_r_to_f(&n2)?,
float_i_to_f(&n1)?,
)?)),
)?))
}
(Number::Rational(n1), Number::Float(OrderedFloat(n2))) => {
Ok(Number::Float(div_f(float_r_to_f(&n1)?, n2)?))
}
@@ -514,25 +624,47 @@ impl Div<Number> for Number {
}
}
impl PartialEq for Number {
fn eq(&self, rhs: &Self) -> bool {
match (self, rhs) {
(&Number::Fixnum(n1), &Number::Fixnum(n2)) => n1.eq(&n2),
(&Number::Fixnum(n1), &Number::Integer(ref n2)) => n1.eq(&**n2),
(&Number::Integer(ref n1), &Number::Fixnum(n2)) => (&**n1).eq(&n2),
(&Number::Fixnum(n1), &Number::Rational(ref n2)) => n1.eq(&**n2),
(&Number::Rational(ref n1), &Number::Fixnum(n2)) => (&**n1).eq(&n2),
(&Number::Fixnum(_), &Number::Float(OrderedFloat(_))) => false,
(&Number::Float(OrderedFloat(_)), &Number::Fixnum(_)) => false,
(&Number::Integer(ref n1), &Number::Integer(ref n2)) => n1.eq(n2),
(&Number::Integer(_), Number::Float(_)) => false,
(&Number::Float(_), &Number::Integer(_)) => false,
(&Number::Integer(_), &Number::Rational(_)) => false,
(&Number::Rational(_), &Number::Integer(_)) => false,
(&Number::Rational(_), Number::Float(_)) => false,
(&Number::Float(_), &Number::Rational(_)) => false,
(&Number::Float(f1), &Number::Float(f2)) => f1.eq(&f2),
(&Number::Rational(ref r1), &Number::Rational(ref r2)) => r1.eq(&r2),
}
}
}
impl Eq for Number {}
impl PartialOrd for Number {
fn partial_cmp(&self, rhs: &Number) -> Option<Ordering> {
match (self, rhs) {
(&Number::Integer(ref n1), &Number::Integer(ref n2)) => Some(n1.cmp(n2)),
(&Number::Integer(_), Number::Float(_)) => Some(Ordering::Greater),
(&Number::Float(_), &Number::Integer(_)) => Some(Ordering::Less),
(&Number::Integer(_), &Number::Rational(_)) => Some(Ordering::Greater),
(&Number::Rational(_), &Number::Integer(_)) => Some(Ordering::Less),
(&Number::Rational(_), Number::Float(_)) => Some(Ordering::Greater),
(&Number::Float(_), &Number::Rational(_)) => Some(Ordering::Less),
(&Number::Float(f1), &Number::Float(f2)) => Some(f1.cmp(&f2)),
(&Number::Rational(ref r1), &Number::Rational(ref r2)) => Some(r1.cmp(&r2)),
}
Some(self.cmp(rhs))
}
}
impl Ord for Number {
fn cmp(&self, rhs: &Number) -> Ordering {
match (self, rhs) {
(&Number::Fixnum(n1), &Number::Fixnum(n2)) => n1.cmp(&n2),
(&Number::Fixnum(n1), Number::Integer(n2)) => Integer::from(n1).cmp(&*n2),
(Number::Integer(n1), &Number::Fixnum(n2)) => (&**n1).cmp(&Integer::from(n2)),
(&Number::Fixnum(n1), Number::Rational(n2)) => Rational::from(n1).cmp(&*n2),
(Number::Rational(n1), &Number::Fixnum(n2)) => (&**n1).cmp(&Rational::from(n2)),
(&Number::Fixnum(_), &Number::Float(OrderedFloat(_))) => Ordering::Greater,
(&Number::Float(OrderedFloat(_)), &Number::Fixnum(_)) => Ordering::Less,
(&Number::Integer(ref n1), &Number::Integer(ref n2)) => n1.cmp(n2),
(&Number::Integer(_), Number::Float(_)) => Ordering::Greater,
(&Number::Float(_), &Number::Integer(_)) => Ordering::Less,
@@ -546,6 +678,78 @@ impl Ord for Number {
}
}
impl<'a> TryFrom<(Addr, &'a Heap)> for Number {
type Error = ();
fn try_from((addr, heap): (Addr, &'a Heap)) -> Result<Number, Self::Error> {
match addr {
Addr::CharCode(c) => {
Ok(Number::from(c as isize))
}
Addr::Fixnum(n) => {
Ok(Number::from(n))
}
Addr::Float(n) => {
Ok(Number::Float(n))
}
Addr::Usize(n) => {
if let Ok(n) = isize::try_from(n) {
Ok(Number::from(n))
} else {
Ok(Number::from(Integer::from(n)))
}
}
Addr::Con(h) => {
Number::try_from(&heap[h])
}
_ => {
Err(())
}
}
}
}
impl<'a> TryFrom<&'a HeapCellValue> for Number {
type Error = ();
fn try_from(value: &'a HeapCellValue) -> Result<Number, Self::Error> {
match value {
HeapCellValue::Addr(addr) => {
match addr {
&Addr::CharCode(c) => {
Ok(Number::from(c as isize))
}
&Addr::Fixnum(n) => {
Ok(Number::from(n))
}
&Addr::Float(n) => {
Ok(Number::Float(n))
}
&Addr::Usize(n) => {
if let Ok(n) = isize::try_from(n) {
Ok(Number::from(n))
} else {
Ok(Number::from(Integer::from(n)))
}
}
_ => {
Err(())
}
}
}
HeapCellValue::Integer(n) => {
Ok(Number::Integer(n.clone()))
}
HeapCellValue::Rational(n) => {
Ok(Number::Rational(n.clone()))
}
_ => {
Err(())
}
}
}
}
// Computes n ^ power. Ignores the sign of power.
pub fn binary_pow(mut n: Integer, power: &Integer) -> Integer {
let mut power = Integer::from(power.abs_ref());

View File

@@ -159,7 +159,6 @@ pub enum SystemClauseType {
AtomCodes,
AtomLength,
BindFromRegister,
CallAttributeGoals,
CallContinuation,
CharCode,
CharsToNumber,
@@ -179,7 +178,6 @@ pub enum SystemClauseType {
EnqueueAttributedVar,
ExpandGoal,
ExpandTerm,
FetchAttributeGoals,
FetchGlobalVar,
FetchGlobalVarWithOffset,
GetChar,
@@ -277,7 +275,6 @@ impl SystemClauseType {
&SystemClauseType::AtomCodes => clause_name!("$atom_codes"),
&SystemClauseType::AtomLength => clause_name!("$atom_length"),
&SystemClauseType::BindFromRegister => clause_name!("$bind_from_register"),
&SystemClauseType::CallAttributeGoals => clause_name!("$call_attribute_goals"),
&SystemClauseType::CallContinuation => clause_name!("$call_continuation"),
&SystemClauseType::CharCode => clause_name!("$char_code"),
&SystemClauseType::CharsToNumber => clause_name!("$chars_to_number"),
@@ -308,7 +305,6 @@ impl SystemClauseType {
&SystemClauseType::EnqueueAttributedVar => clause_name!("$enqueue_attr_var"),
&SystemClauseType::ExpandTerm => clause_name!("$expand_term"),
&SystemClauseType::ExpandGoal => clause_name!("$expand_goal"),
&SystemClauseType::FetchAttributeGoals => clause_name!("$fetch_attribute_goals"),
&SystemClauseType::FetchGlobalVar => clause_name!("$fetch_global_var"),
&SystemClauseType::FetchGlobalVarWithOffset => {
clause_name!("$fetch_global_var_with_offset")
@@ -429,7 +425,6 @@ impl SystemClauseType {
("$module_assertz", 5) => Some(SystemClauseType::ModuleAssertDynamicPredicateToBack),
("$asserta", 4) => Some(SystemClauseType::AssertDynamicPredicateToFront),
("$assertz", 4) => Some(SystemClauseType::AssertDynamicPredicateToBack),
("$call_attribute_goals", 2) => Some(SystemClauseType::CallAttributeGoals),
("$call_continuation", 1) => Some(SystemClauseType::CallContinuation),
("$char_code", 2) => Some(SystemClauseType::CharCode),
("$chars_to_number", 2) => Some(SystemClauseType::CharsToNumber),
@@ -456,7 +451,6 @@ impl SystemClauseType {
("$is_partial_string", 1) => Some(SystemClauseType::IsPartialString),
("$expand_term", 2) => Some(SystemClauseType::ExpandTerm),
("$expand_goal", 2) => Some(SystemClauseType::ExpandGoal),
("$fetch_attribute_goals", 1) => Some(SystemClauseType::FetchAttributeGoals),
("$fetch_global_var", 2) => Some(SystemClauseType::FetchGlobalVar),
("$fetch_global_var_with_offset", 3) => Some(SystemClauseType::FetchGlobalVarWithOffset),
("$get_char", 1) => Some(SystemClauseType::GetChar),

View File

@@ -446,7 +446,8 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator<TermMarker> {
}
},
&InlinedClauseType::IsInteger(..) => match terms[0].as_ref() {
&Term::Constant(_, Constant::Integer(_)) => {
&Term::Constant(_, Constant::Integer(_)) |
&Term::Constant(_, Constant::Fixnum(_)) => {
code.push(succeed!());
}
&Term::Var(ref vr, ref name) => {
@@ -511,7 +512,8 @@ impl<'a, TermMarker: Allocator<'a>> CodeGenerator<TermMarker> {
code.push(is_call!(temp_v!(1), at.unwrap_or(interm!(1))))
}
}
&Term::Constant(_, ref c @ Constant::Integer(_)) => {
&Term::Constant(_, ref c @ Constant::Integer(_)) |
&Term::Constant(_, ref c @ Constant::Fixnum(_)) => {
code.push(Line::Query(put_constant!(
Level::Shallow,
c.clone(),

View File

@@ -12,6 +12,7 @@ use indexmap::IndexMap;
use std::cell::Cell;
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::path::PathBuf;
use std::rc::Rc;
@@ -573,11 +574,33 @@ pub struct Module {
pub listing_src: ListingSource,
}
#[derive(Clone, PartialEq, Eq)]
#[derive(Clone)]
pub enum Number {
Float(OrderedFloat<f64>),
Integer(Rc<Integer>),
Rational(Rc<Rational>),
Fixnum(isize),
}
impl From<Integer> for Number {
#[inline]
fn from(n: Integer) -> Self {
Number::Integer(Rc::new(n))
}
}
impl From<Rational> for Number {
#[inline]
fn from(n: Rational) -> Self {
Number::Rational(Rc::new(n))
}
}
impl From<isize> for Number {
#[inline]
fn from(n: isize) -> Self {
Number::Fixnum(n)
}
}
impl Default for Number {
@@ -586,10 +609,23 @@ impl Default for Number {
}
}
impl Into<Constant> for Number {
#[inline]
fn into(self) -> Constant {
match self {
Number::Fixnum(n) => Constant::Fixnum(n),
Number::Integer(n) => Constant::Integer(n),
Number::Float(f) => Constant::Float(f),
Number::Rational(r) => Constant::Rational(r),
}
}
}
impl Into<HeapCellValue> for Number {
#[inline]
fn into(self) -> HeapCellValue {
match self {
Number::Fixnum(n) => HeapCellValue::Addr(Addr::Fixnum(n)),
Number::Integer(n) => HeapCellValue::Integer(n),
Number::Float(f) => HeapCellValue::Addr(Addr::Float(f)),
Number::Rational(r) => HeapCellValue::Rational(r),
@@ -597,10 +633,27 @@ impl Into<HeapCellValue> for Number {
}
}
impl Number {
#[inline]
pub fn to_u32(&self) -> Option<u32> {
match self {
&Number::Fixnum(n) => u32::try_from(n).ok(),
&Number::Integer(ref n) => n.to_u32(),
&Number::Float(_) => None,
&Number::Rational(ref r) =>
if r.denom() == &1 {
r.numer().to_u32()
} else {
None
}
}
}
#[inline]
pub fn is_positive(&self) -> bool {
match self {
&Number::Fixnum(n) => n > 0,
&Number::Integer(ref n) => &**n > &0,
&Number::Float(OrderedFloat(f)) => f.is_sign_positive(),
&Number::Rational(ref r) => &**r > &0,
@@ -610,6 +663,7 @@ impl Number {
#[inline]
pub fn is_negative(&self) -> bool {
match self {
&Number::Fixnum(n) => n < 0,
&Number::Integer(ref n) => &**n < &0,
&Number::Float(OrderedFloat(f)) => f.is_sign_negative(),
&Number::Rational(ref r) => &**r < &0,
@@ -619,6 +673,7 @@ impl Number {
#[inline]
pub fn is_zero(&self) -> bool {
match self {
&Number::Fixnum(n) => n == 0,
&Number::Integer(ref n) => &**n == &0,
&Number::Float(f) => f == OrderedFloat(0f64),
&Number::Rational(ref r) => &**r == &0,
@@ -628,9 +683,15 @@ impl Number {
#[inline]
pub fn abs(self) -> Self {
match self {
Number::Integer(n) => Number::Integer(Rc::new(Integer::from(n.abs_ref()))),
Number::Fixnum(n) =>
if let Some(n) = n.checked_abs() {
Number::from(n)
} else {
Number::from(Integer::from(n).abs())
}
Number::Integer(n) => Number::from(Integer::from(n.abs_ref())),
Number::Float(f) => Number::Float(OrderedFloat(f.abs())),
Number::Rational(r) => Number::Rational(Rc::new(Rational::from(r.abs_ref()))),
Number::Rational(r) => Number::from(Rational::from(r.abs_ref())),
}
}
}

View File

@@ -12,6 +12,7 @@ use crate::prolog::rug::Integer;
use indexmap::{IndexMap, IndexSet};
use std::cell::Cell;
use std::convert::TryFrom;
use std::iter::{FromIterator, once};
use std::ops::{Range, RangeFrom};
use std::rc::Rc;
@@ -263,25 +264,22 @@ fn is_numbered_var(ct: &ClauseType, arity: usize) -> bool {
#[inline]
fn negated_op_needs_bracketing(iter: &HCPreOrderIterator, op: &Option<DirectedOp>) -> bool {
if let &Some(ref op) = op {
op.is_negative_sign() && iter.leftmost_leaf_has_property(|addr, heap| {
match addr {
Addr::Con(h) => {
match &heap[h] {
HeapCellValue::Integer(ref n) => {
&**n > &0
if let Some(ref op) = op {
op.is_negative_sign() &&
iter.leftmost_leaf_has_property(|addr, heap| {
match Number::try_from((addr, heap)) {
Ok(Number::Fixnum(n)) => {
n > 0
}
&HeapCellValue::Rational(ref r) => {
&**r > &0
}
_ => {
false
}
}
}
Addr::Float(f) => {
Ok(Number::Float(f)) => {
f > OrderedFloat(0f64)
}
Ok(Number::Integer(n)) => {
&*n > &0
}
Ok(Number::Rational(n)) => {
&*n > &0
}
_ => {
false
}
@@ -311,14 +309,19 @@ fn numbervar(n: Integer) -> Var {
impl MachineState {
pub fn numbervar(&self, offset: &Integer, addr: Addr) -> Option<Var> {
match self.store(self.deref(addr)) {
Addr::Con(h) => {
if let &HeapCellValue::Integer(ref n) = &self.heap[h] {
if &**n >= &0 {
Some(numbervar(Integer::from(offset + &**n)))
let addr = self.store(self.deref(addr));
match Number::try_from((addr, &self.heap)) {
Ok(Number::Fixnum(n)) => {
if n >= 0 {
Some(numbervar(Integer::from(offset + Integer::from(n))))
} else {
None
}
}
Ok(Number::Integer(n)) => {
if &*n >= &0 {
Some(numbervar(Integer::from(offset + &*n)))
} else {
None
}
@@ -1336,6 +1339,9 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
&HeapCellValue::Addr(Addr::Float(n)) => {
self.print_number(Number::Float(n), &op);
}
&HeapCellValue::Addr(Addr::Fixnum(n)) => {
self.print_number(Number::Fixnum(n), &op);
}
&HeapCellValue::Addr(Addr::Usize(u)) => {
self.append_str(&format!("{}", u));
}

View File

@@ -1,11 +1,13 @@
use prolog_parser::ast::*;
use crate::prolog::instructions::*;
use crate::prolog::rug::Integer;
use indexmap::IndexMap;
use std::collections::VecDeque;
use std::hash::Hash;
use std::rc::Rc;
#[derive(Clone, Copy)]
enum IntIndex {
@@ -48,6 +50,41 @@ impl CodeOffsets {
}
}
fn intercept_constant(&mut self, constant: &Constant, index: usize) {
match constant {
&Constant::Atom(ref name, _) if name.is_char() => {
let c = name.as_str().chars().next().unwrap();
let code = self.constants
.entry(Constant::Char(c))
.or_insert(vec![]);
code.push(Self::add_index(code.is_empty(), index));
}
&Constant::Fixnum(n) => {
let code = self.constants
.entry(Constant::Integer(Rc::new(Integer::from(n))))
.or_insert(vec![]);
code.push(Self::add_index(code.is_empty(), index));
}
&Constant::Integer(ref n) => {
if let Some(n) = n.to_isize() {
let code = self.constants
.entry(Constant::Fixnum(n))
.or_insert(vec![]);
code.push(Self::add_index(code.is_empty(), index));
}
}
&Constant::String(_) => {
let is_initial_index = self.lists.is_empty();
self.lists.push(Self::add_index(is_initial_index, index));
}
_ => {
}
}
}
pub fn index_term(&mut self, first_arg: &Term, index: usize) {
match first_arg {
&Term::Clause(_, ref name, ref terms, _) => {
@@ -63,30 +100,13 @@ impl CodeOffsets {
let is_initial_index = self.lists.is_empty();
self.lists.push(Self::add_index(is_initial_index, index));
}
&Term::Constant(_, Constant::String(ref s)) => {
let is_initial_index = self.lists.is_empty();
self.lists.push(Self::add_index(is_initial_index, index));
let constant = Constant::String(s.clone());
let code = self.constants.entry(constant).or_insert(Vec::new());
let is_initial_index = code.is_empty();
code.push(Self::add_index(is_initial_index, index));
}
&Term::Constant(_, ref constant) => {
if let Constant::Atom(ref name, _) = constant {
if name.is_char() {
let c = name.as_str().chars().next().unwrap();
self.intercept_constant(constant, index);
let code = self.constants
.entry(Constant::Char(c))
.entry(constant.clone())
.or_insert(vec![]);
code.push(Self::add_index(code.is_empty(), index));
}
}
let code = self.constants.entry(constant.clone()).or_insert(Vec::new());
let is_initial_index = code.is_empty();
code.push(Self::add_index(is_initial_index, index));
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,6 +6,8 @@ use crate::prolog::machine::compile::*;
use crate::prolog::machine::machine_errors::*;
use crate::prolog::machine::streams::*;
use std::convert::TryFrom;
impl Machine {
pub(super) fn atom_tbl_of(&self, name: &ClauseName) -> TabledData<Atom> {
match name {
@@ -52,12 +54,18 @@ impl Machine {
let arity = match self.machine_st.store(self.machine_st.deref(arity)) {
Addr::Con(h) => {
if let HeapCellValue::Integer(ref arity) = &self.machine_st.heap[h] {
match &self.machine_st.heap[h] {
HeapCellValue::Integer(ref arity) => {
arity.to_usize().unwrap()
} else {
}
HeapCellValue::Addr(Addr::Fixnum(arity)) => {
usize::try_from(*arity).unwrap()
}
_ => {
unreachable!()
}
}
}
Addr::Usize(n) => {
n
}
@@ -239,11 +247,17 @@ impl Machine {
let index = self.machine_st[temp_v!(3)].clone();
let index = match self.machine_st.store(self.machine_st.deref(index)) {
Addr::Con(h) =>
if let HeapCellValue::Integer(ref n) = &self.machine_st.heap[h] {
n.to_usize().unwrap()
} else {
match &self.machine_st.heap[h] {
HeapCellValue::Integer(ref arity) => {
arity.to_usize().unwrap()
}
HeapCellValue::Addr(Addr::Fixnum(arity)) => {
usize::try_from(*arity).unwrap()
}
_ => {
unreachable!()
},
}
}
_ => unreachable!(),
};
@@ -280,12 +294,19 @@ impl Machine {
fn retract_from_dynamic_predicate(&mut self) {
let index = self.machine_st[temp_v!(3)].clone();
let index = match self.machine_st.store(self.machine_st.deref(index)) {
Addr::Con(h) =>
if let HeapCellValue::Integer(n) = &self.machine_st.heap[h] {
n.to_usize().unwrap()
} else {
Addr::Con(h) => {
match &self.machine_st.heap[h] {
HeapCellValue::Integer(ref arity) => {
arity.to_usize().unwrap()
}
HeapCellValue::Addr(Addr::Fixnum(arity)) => {
usize::try_from(*arity).unwrap()
}
_ => {
unreachable!()
},
}
}
}
_ => {
unreachable!()
}

View File

@@ -6,6 +6,7 @@ use crate::prolog::machine::machine_indices::*;
use crate::prolog::machine::partial_string::*;
use crate::prolog::machine::raw_block::*;
use std::convert::TryFrom;
use std::mem;
use std::ops::{Index, IndexMut};
use std::ptr;
@@ -202,6 +203,9 @@ impl<T: RawBlockTraits> HeapTemplate<T> {
Constant::EmptyList => {
Addr::EmptyList
}
Constant::Fixnum(n) => {
Addr::Fixnum(n)
}
Constant::Integer(n) => {
Addr::Con(self.push(HeapCellValue::Integer(n)))
}
@@ -252,26 +256,6 @@ impl<T: RawBlockTraits> HeapTemplate<T> {
h
}
#[inline]
pub(crate)
fn rational_at(&self, h: usize) -> bool {
if let HeapCellValue::Rational(_) = &self[h] {
true
} else {
false
}
}
#[inline]
pub(crate)
fn integer_at(&self, h: usize) -> bool {
if let HeapCellValue::Integer(_) = &self[h] {
true
} else {
false
}
}
#[inline]
pub(crate)
fn atom_at(&self, h: usize) -> bool {
@@ -475,6 +459,7 @@ impl<T: RawBlockTraits> HeapTemplate<T> {
fn to_local_code_ptr(&self, addr: &Addr) -> Option<LocalCodePtr> {
let extract_integer = |s: usize| -> Option<usize> {
match &self[s] {
&HeapCellValue::Addr(Addr::Fixnum(n)) => usize::try_from(n).ok(),
&HeapCellValue::Integer(ref n) => n.to_usize(),
_ => None
}

View File

@@ -20,6 +20,7 @@ use indexmap::IndexMap;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::{BTreeMap, VecDeque};
use std::convert::TryFrom;
use std::mem;
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::rc::Rc;
@@ -59,6 +60,7 @@ pub enum Addr {
Con(usize),
CutPoint(usize),
EmptyList,
Fixnum(isize),
Float(OrderedFloat<f64>),
Lis(usize),
HeapCell(usize),
@@ -155,8 +157,9 @@ impl Addr {
#[inline]
pub fn is_heap_bound(&self) -> bool {
match self {
Addr::Char(_) | Addr::CharCode(_) | Addr::EmptyList
| Addr::CutPoint(_) | Addr::Usize(_) | Addr::Float(_) => {
Addr::Char(_) | Addr::CharCode(_) | Addr::EmptyList |
Addr::CutPoint(_) | Addr::Usize(_) | Addr::Fixnum(_) |
Addr::Float(_) => {
false
}
_ => {
@@ -189,6 +192,14 @@ impl Addr {
pub(super)
fn order_category(&self, heap: &Heap) -> Option<TermOrderCategory> {
match Number::try_from((*self, heap)) {
Ok(Number::Integer(_)) | Ok(Number::Fixnum(_)) | Ok(Number::Rational(_)) => {
Some(TermOrderCategory::Integer)
}
Ok(Number::Float(_)) => {
Some(TermOrderCategory::FloatingPoint)
}
_ => {
match self {
Addr::HeapCell(_) | Addr::AttrVar(_) | Addr::StackCell(..) => {
Some(TermOrderCategory::Variable)
@@ -201,12 +212,6 @@ impl Addr {
HeapCellValue::Atom(..) => {
Some(TermOrderCategory::Atom)
}
HeapCellValue::Integer(_) => {
Some(TermOrderCategory::Integer)
}
HeapCellValue::Rational(_) => {
Some(TermOrderCategory::Integer)
}
HeapCellValue::DBRef(_) => {
None
}
@@ -218,7 +223,7 @@ impl Addr {
Addr::Char(_) | Addr::EmptyList => {
Some(TermOrderCategory::Atom)
}
Addr::Usize(_) | Addr::CharCode(_) => {
Addr::CharCode(_) | Addr::Fixnum(_) | Addr::Usize(_) => {
Some(TermOrderCategory::Integer)
}
Addr::Lis(_) | Addr::PStrLocation(..) | Addr::Str(_) => {
@@ -229,6 +234,8 @@ impl Addr {
}
}
}
}
}
pub fn as_constant(&self, machine_st: &MachineState) -> Option<Constant> {
match self {
@@ -257,6 +264,9 @@ impl Addr {
&Addr::EmptyList => {
Some(Constant::EmptyList)
}
&Addr::Fixnum(n) => {
Some(Constant::Fixnum(n))
}
&Addr::Float(f) => {
Some(Constant::Float(f))
}

View File

@@ -965,7 +965,7 @@ pub(crate) trait CallPolicy: Any {
let a1 = machine_st[r];
let n2 = machine_st.get_number(at)?;
let n2 = Addr::Con(machine_st.heap.push(n2.into()));
let n2 = machine_st.heap.put_constant(n2.into());
machine_st.unify(a1, n2);
return_from_clause!(machine_st.last_call, machine_st)

View File

@@ -21,6 +21,7 @@ use crate::prolog::rug::Integer;
use indexmap::{IndexMap, IndexSet};
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::rc::Rc;
macro_rules! try_or_fail {
@@ -261,8 +262,8 @@ impl MachineState {
self.fail = true;
}
(Addr::PStrLocation(h, n), Addr::Lis(l))
| (Addr::Lis(l), Addr::PStrLocation(h, n)) => {
(Addr::PStrLocation(h, n), Addr::Lis(l)) |
(Addr::Lis(l), Addr::PStrLocation(h, n)) => {
if let HeapCellValue::PartialString(ref pstr, _) = &self.heap[h] {
if let Some(c) = pstr.range_from(n ..).next() {
pdl.push(Addr::PStrLocation(h, n + c.len_utf8()));
@@ -369,16 +370,17 @@ impl MachineState {
) if db_ref_1 == db_ref_2 => {
}
(
&HeapCellValue::Integer(ref n1),
&HeapCellValue::Integer(ref n2),
) if &**n1 == &**n2 => {
v1,
v2,
) => {
if let Ok(n1) = Number::try_from(v1) {
if let Ok(n2) = Number::try_from(v2) {
if n1 == n2 {
continue;
}
(
&HeapCellValue::Rational(ref n1),
&HeapCellValue::Rational(ref n2),
) if &**n1 == &**n2 => {
}
_ => {
}
self.fail = true;
}
}
@@ -397,34 +399,31 @@ impl MachineState {
}
}
}
(Addr::Usize(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::Usize(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_usize() {
if n1 == n2 {
continue;
}
}
}
self.fail = true;
}
(Addr::CharCode(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::CharCode(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_u32() {
if n1 == n2 {
continue;
}
}
}
self.fail = true;
}
(Addr::Stream(s1), Addr::Stream(s2)) => {
if s1 != s2 {
self.fail = true;
}
}
(v, Addr::Con(h)) | (Addr::Con(h), v) => {
if let Ok(n1) = Number::try_from(&self.heap[h]) {
if let Ok(v) = Number::try_from(&HeapCellValue::Addr(v)) {
if n1 == v {
continue;
}
}
}
self.fail = true;
}
(a1, a2) => {
if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(a1)) {
if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(a2)) {
if n1 == n2 {
continue;
}
}
}
if a1 != a2 {
self.fail = true;
}
@@ -481,8 +480,8 @@ impl MachineState {
self.fail = true;
}
(Addr::PStrLocation(h, n), Addr::Lis(l))
| (Addr::Lis(l), Addr::PStrLocation(h, n)) => {
(Addr::PStrLocation(h, n), Addr::Lis(l)) |
(Addr::Lis(l), Addr::PStrLocation(h, n)) => {
if let HeapCellValue::PartialString(ref pstr, _) = &self.heap[h] {
if let Some(c) = pstr.range_from(n ..).next() {
pdl.push(Addr::PStrLocation(h, n + c.len_utf8()));
@@ -585,16 +584,17 @@ impl MachineState {
) if db_ref_1 == db_ref_2 => {
}
(
&HeapCellValue::Integer(ref n1),
&HeapCellValue::Integer(ref n2),
) if &**n1 == &**n2 => {
v1,
v2,
) => {
if let Ok(n1) = Number::try_from(v1) {
if let Ok(n2) = Number::try_from(v2) {
if n1 == n2 {
continue;
}
(
&HeapCellValue::Rational(ref n1),
&HeapCellValue::Rational(ref n2),
) if &**n1 == &**n2 => {
}
_ => {
}
self.fail = true;
}
}
@@ -613,34 +613,31 @@ impl MachineState {
}
}
}
(Addr::Usize(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::Usize(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_usize() {
if n1 == n2 {
continue;
}
}
}
self.fail = true;
}
(Addr::CharCode(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::CharCode(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_u32() {
if n1 == n2 {
continue;
}
}
}
self.fail = true;
}
(Addr::Stream(s1), Addr::Stream(s2)) => {
if s1 != s2 {
self.fail = true;
}
}
(v, Addr::Con(h)) | (Addr::Con(h), v) => {
if let Ok(n1) = Number::try_from(&self.heap[h]) {
if let Ok(v) = Number::try_from(&HeapCellValue::Addr(v)) {
if n1 == v {
continue;
}
}
}
self.fail = true;
}
(a1, a2) => {
if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(a1)) {
if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(a2)) {
if n1 == n2 {
continue;
}
}
}
if a1 != a2 {
self.fail = true;
}
@@ -791,6 +788,9 @@ impl MachineState {
}
HeapCellValue::Integer(ref n1) => {
match c {
Constant::Fixnum(n2) => {
n1.to_isize() != Some(*n2)
}
Constant::Integer(ref n2) => {
n1 != n2
}
@@ -919,8 +919,7 @@ impl MachineState {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.gcd(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.gcd(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Pow(ref a1, ref a2, t) => {
@@ -944,16 +943,14 @@ impl MachineState {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.int_floor_div(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.int_floor_div(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::IDiv(ref a1, ref a2, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.idiv(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.idiv(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Abs(ref a1, t) => {
@@ -965,7 +962,7 @@ impl MachineState {
&ArithmeticInstruction::Sign(ref a1, t) => {
let n = try_or_fail!(self, self.get_number(a1));
self.interms[t - 1] = Number::Integer(Rc::new(self.sign(n)));
self.interms[t - 1] = self.sign(n);
self.p += 1;
}
&ArithmeticInstruction::Neg(ref a1, t) => {
@@ -977,8 +974,7 @@ impl MachineState {
&ArithmeticInstruction::BitwiseComplement(ref a1, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.bitwise_complement(n1))));
self.interms[t - 1] = try_or_fail!(self, self.bitwise_complement(n1));
self.p += 1;
}
&ArithmeticInstruction::Div(ref a1, ref a2, t) => {
@@ -992,56 +988,49 @@ impl MachineState {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.shr(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.shr(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Shl(ref a1, ref a2, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.shl(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.shl(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Xor(ref a1, ref a2, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.xor(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.xor(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::And(ref a1, ref a2, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.and(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.and(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Or(ref a1, ref a2, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.or(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.or(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Mod(ref a1, ref a2, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.modulus(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.modulus(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Rem(ref a1, ref a2, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
let n2 = try_or_fail!(self, self.get_number(a2));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.remainder(n1, n2))));
self.interms[t - 1] = try_or_fail!(self, self.remainder(n1, n2));
self.p += 1;
}
&ArithmeticInstruction::Cos(ref a1, t) => {
@@ -1120,29 +1109,25 @@ impl MachineState {
&ArithmeticInstruction::Truncate(ref a1, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
self.interms[t - 1] =
Number::Integer(Rc::new(self.truncate(n1)));
self.interms[t - 1] = self.truncate(n1);
self.p += 1;
}
&ArithmeticInstruction::Round(ref a1, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
self.interms[t - 1] =
Number::Integer(Rc::new(try_or_fail!(self, self.round(n1))));
self.interms[t - 1] = try_or_fail!(self, self.round(n1));
self.p += 1;
}
&ArithmeticInstruction::Ceiling(ref a1, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
self.interms[t - 1] =
Number::Integer(Rc::new(self.ceiling(n1)));
self.interms[t - 1] = self.ceiling(n1);
self.p += 1;
}
&ArithmeticInstruction::Floor(ref a1, t) => {
let n1 = try_or_fail!(self, self.get_number(a1));
self.interms[t - 1] =
Number::Integer(Rc::new(self.floor(n1)));
self.interms[t - 1] = self.floor(n1);
self.p += 1;
}
&ArithmeticInstruction::Plus(ref a1, t) => {
@@ -1332,7 +1317,7 @@ impl MachineState {
}
}
Addr::Char(_) | Addr::CharCode(_) | Addr::Con(_) | Addr::CutPoint(_) |
Addr::EmptyList | Addr::Float(_) | Addr::Usize(_) => {
Addr::EmptyList | Addr::Fixnum(_) | Addr::Float(_) | Addr::Usize(_) => {
c
}
Addr::Lis(_) => {
@@ -1624,10 +1609,25 @@ impl MachineState {
Addr::HeapCell(_) | Addr::StackCell(..) => { // 8.5.2.3 a)
return Err(self.error_form(MachineError::instantiation_error(), stub))
}
Addr::Con(h) => {
if let HeapCellValue::Integer(n) = self.heap.clone(h) {
if &*n < &0 { // 8.5.2.3 e)
let n = Number::Integer(n);
addr => {
let n =
match Number::try_from((addr, &self.heap)) {
Ok(Number::Fixnum(n)) => Integer::from(n),
Ok(Number::Integer(n)) => Integer::from(n.as_ref()),
_ => {
return Err(self.error_form(
MachineError::type_error(
self.heap.h(),
ValidType::Integer,
addr,
),
stub,
));
}
};
if n < 0 { // 8.5.2.3 e)
let n = Number::from(n);
let dom_err = MachineError::domain_error(
DomainErrorType::NotLessThanZero,
n,
@@ -1636,7 +1636,8 @@ impl MachineState {
return Err(self.error_form(dom_err, stub));
}
let n = match n.to_usize() {
let n =
match n.to_usize() {
Some(n) => n,
None => {
self.fail = true;
@@ -1647,7 +1648,7 @@ impl MachineState {
let term = self.store(self.deref(self[temp_v!(2)]));
match term {
Addr::HeapCell(_) | Addr::StackCell(..) => { // 8.5.2.3 b)
Addr::HeapCell(_) | Addr::StackCell(..) | Addr::AttrVar(_) => { // 8.5.2.3 b)
return Err(self.error_form(MachineError::instantiation_error(), stub))
}
Addr::Str(o) => match self.heap.clone(o) {
@@ -1705,26 +1706,6 @@ impl MachineState {
))
}
}
} else {
return Err(self.error_form(
MachineError::type_error(
self.heap.h(),
ValidType::Integer,
Addr::HeapCell(h),
),
stub,
))
}
}
_ => { // 8.5.2.3 c)
return Err(self.error_form(
MachineError::type_error(
self.heap.h(),
ValidType::Integer,
n,
),
stub,
))
}
}
@@ -1747,7 +1728,8 @@ impl MachineState {
self.p += 1;
}
pub(super) fn compare_term(&mut self, qt: CompareTermQT) {
pub(super)
fn compare_term(&mut self, qt: CompareTermQT) {
let a1 = self[temp_v!(1)];
let a2 = self[temp_v!(2)];
@@ -1804,18 +1786,10 @@ impl MachineState {
(Addr::Con(h1), Addr::Con(h2)) => {
match (&self.heap[h1], &self.heap[h2]) {
(
&HeapCellValue::Integer(ref n1),
&HeapCellValue::Integer(ref n2),
&HeapCellValue::Atom(ref n1, ref spec_1),
&HeapCellValue::Atom(ref n2, ref spec_2),
) => {
if n1 != n2 {
return true;
}
}
(
&HeapCellValue::Rational(ref n1),
&HeapCellValue::Rational(ref n2),
) => {
if n1 != n2 {
if n1 != n2 || spec_1 != spec_2 {
return true;
}
}
@@ -1828,14 +1802,17 @@ impl MachineState {
}
}
(
&HeapCellValue::Atom(ref n1, ref spec_1),
&HeapCellValue::Atom(ref n2, ref spec_2),
v1,
v2,
) => {
if n1 != n2 || spec_1 != spec_2 {
return true;
if let Ok(n1) = Number::try_from(v1) {
if let Ok(n2) = Number::try_from(v2) {
if n1 == n2 {
continue;
}
}
_ => {
}
return true;
}
}
@@ -1852,25 +1829,26 @@ impl MachineState {
}
}
}
(Addr::Usize(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::Usize(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_usize() {
(Addr::CharCode(n1), v2) | (v2, Addr::CharCode(n1)) => {
if let Ok(n2) = Number::try_from((v2, &self.heap)) {
if let Some(n2) = n2.to_u32() {
if n1 != n2 {
return true;
}
}
}
}
(Addr::CharCode(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::CharCode(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_u32() {
if n1 == n2 {
return true;
}
}
}
}
(a1, a2) => {
if let Ok(n1) = Number::try_from((a1, &self.heap)) {
if let Ok(n2) = Number::try_from((a2, &self.heap)) {
if n1 != n2 {
return true;
} else {
continue;
}
}
}
if a1 != a2 {
return true;
}
@@ -1919,75 +1897,63 @@ impl MachineState {
Addr::Con(h1),
Addr::Con(h2),
) => {
match (&self.heap[h1], &self.heap[h2]) {
(
HeapCellValue::Integer(ref n1),
HeapCellValue::Integer(ref n2),
) => {
if &*n1 != &*n2 {
return Some(n1.cmp(&*n2));
if let Ok(n1) = Number::try_from(&self.heap[h1]) {
if let Ok(n2) = Number::try_from(&self.heap[h2]) {
if n1 != n2 {
return Some(n1.cmp(&n2));
}
} else {
unreachable!()
}
(
HeapCellValue::Rational(ref n1),
HeapCellValue::Integer(ref n2),
) => {
if &**n1 != &**n2 {
return n1.as_ref().partial_cmp(n2.as_ref());
}
}
(
HeapCellValue::Integer(ref n1),
HeapCellValue::Rational(ref n2),
) => {
if &**n1 != &**n2 {
return n1.as_ref().partial_cmp(n2.as_ref());
}
}
(
HeapCellValue::Rational(ref r1),
HeapCellValue::Rational(ref r2),
) => {
if &*r1 != &*r2 {
return Some(r1.cmp(r2));
}
}
_ => {
} else {
unreachable!()
}
}
}
(Addr::Usize(n1), Addr::Usize(n2)) => {
(
Addr::Con(h1),
v2,
) => {
if let Ok(n1) = Number::try_from(&self.heap[h1]) {
if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(v2)) {
if n1 != n2 {
return Some(n1.cmp(&n2));
}
}
(Addr::CharCode(n1), Addr::CharCode(n2)) => {
if n1 != n2 {
return Some(n1.cmp(&n2));
}
}
(Addr::Usize(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::Usize(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_usize() {
if n1 != n2 {
return Some(n1.cmp(&n2));
}
}
}
}
(Addr::CharCode(n1), Addr::Con(n2)) | (Addr::Con(n2), Addr::CharCode(n1)) => {
if let HeapCellValue::Integer(ref n2) = &self.heap[n2] {
if let Some(n2) = n2.to_u32() {
if n1 != n2 {
return Some(n1.cmp(&n2));
}
}
}
}
_ => {
} else {
unreachable!()
}
} else {
unreachable!()
}
}
(
v1,
Addr::Con(h2),
) => {
if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(v1)) {
if let Ok(n2) = Number::try_from(&self.heap[h2]) {
if n1 != n2 {
return Some(n1.cmp(&n2));
}
} else {
unreachable!()
}
} else {
unreachable!()
}
}
(v1, v2) => {
if let Ok(n1) = Number::try_from(&HeapCellValue::Addr(v1)) {
if let Ok(n2) = Number::try_from(&HeapCellValue::Addr(v2)) {
if n1 != n2 {
return Some(n1.cmp(&n2));
}
} else {
unreachable!()
}
} else {
unreachable!()
}
}
}
}
Some(TermOrderCategory::Atom) => {
@@ -2330,25 +2296,23 @@ impl MachineState {
&InlinedClauseType::IsInteger(r1) => {
let d = self.store(self.deref(self[r1]));
match d {
Addr::Con(h) => {
match &self.heap[h] {
HeapCellValue::Integer(_) => {
match Number::try_from((d, &self.heap)) {
Ok(Number::Fixnum(_)) => {
self.p += 1;
}
HeapCellValue::Rational(ref r) => {
if r.denom() == &1 {
Ok(Number::Integer(_)) => {
self.p += 1;
}
Ok(Number::Rational(n)) => {
if n.denom() == &1 {
self.p += 1;
} else {
self.fail = true;
}
}
_ => {
self.fail = true;
}
}
}
Addr::CharCode(_) | Addr::Usize(_) => {
match d {
Addr::CharCode(_) => {
self.p += 1;
}
Addr::Char(_) if self.flags.double_quotes.is_codes() => {
@@ -2357,7 +2321,9 @@ impl MachineState {
_ => {
self.fail = true;
}
};
}
}
}
}
&InlinedClauseType::IsCompound(r1) => {
let d = self.store(self.deref(self[r1]));
@@ -2484,8 +2450,8 @@ impl MachineState {
Addr::Stream(_) => {
self.fail = true;
}
Addr::Char(_) | Addr::CharCode(_) | Addr::Con(_) | Addr::Float(_) |
Addr::EmptyList | Addr::Usize(_) => {
Addr::Char(_) | Addr::CharCode(_) | Addr::Con(_) | Addr::Fixnum(_) |
Addr::Float(_) | Addr::EmptyList | Addr::Usize(_) => {
self.try_functor_unify_components(a1, 0);
}
Addr::Str(o) => match self.heap.clone(o) {
@@ -2510,32 +2476,16 @@ impl MachineState {
return Err(self.error_form(MachineError::instantiation_error(), stub));
}
let arity = match arity {
Addr::Con(h) => {
match &self.heap[h] {
&HeapCellValue::Integer(ref n) => {
n.to_isize()
}
&HeapCellValue::Addr(Addr::Usize(n)) => {
Some(n as isize)
}
_ => {
return Err(
self.error_form(
MachineError::type_error(
self.heap.h(),
ValidType::Integer,
arity,
),
stub,
)
);
}
}
let arity =
match Number::try_from((arity, &self.heap)) {
Ok(Number::Fixnum(n)) => Some(n),
Ok(Number::Integer(n)) => n.to_isize(),
Ok(Number::Rational(n))
if n.denom() == &1 => {
n.numer().to_isize()
},
Addr::Usize(n) => {
Some(n as isize)
}
_ =>
match arity {
Addr::CharCode(c) => {
Some(c as isize)
}
@@ -2551,6 +2501,7 @@ impl MachineState {
)
);
}
}
};
let arity = match arity {
@@ -2579,7 +2530,7 @@ impl MachineState {
}
match name {
Addr::Char(_) | Addr::CharCode(_) | Addr::Con(_) | Addr::Float(_) |
Addr::Char(_) | Addr::CharCode(_) | Addr::Con(_) | Addr::Fixnum(_) | Addr::Float(_) |
Addr::EmptyList | Addr::PStrLocation(..) | Addr::Usize(_) if arity == 0 => {
self.unify(a1, name);
}
@@ -2925,34 +2876,6 @@ impl MachineState {
HeapCellValue::Addr(Addr::PStrLocation(..)),
) => {
}
(
HeapCellValue::Integer(n1),
HeapCellValue::Integer(n2),
) => {
if &*n1 != &*n2 {
return true;
}
}
(
HeapCellValue::Rational(n1),
HeapCellValue::Rational(n2),
) => {
if &*n1 != &*n2 {
return true;
}
}
(
HeapCellValue::Integer(ref n1),
HeapCellValue::Rational(ref n2),
) |
(
HeapCellValue::Rational(ref n2),
HeapCellValue::Integer(ref n1),
) => {
if n1.as_ref().partial_cmp(&**n2) == Some(Ordering::Equal) {
return true;
}
}
(
HeapCellValue::Atom(ref n1, ref spec_1),
HeapCellValue::Atom(ref n2, ref spec_2),
@@ -2969,6 +2892,23 @@ impl MachineState {
return true;
}
}
(
v1,
v2,
) => {
if let Ok(n1) = Number::try_from(v1) {
if let Ok(n2) = Number::try_from(v2) {
if n1 != n2 {
return true;
} else {
continue;
}
} else {
return true;
}
}
match (v1, v2) {
(
HeapCellValue::Addr(a1),
HeapCellValue::Addr(a2),
@@ -2982,6 +2922,8 @@ impl MachineState {
}
}
}
}
}
false
}
@@ -3192,8 +3134,12 @@ impl MachineState {
self.hb = self.heap.h();
self.p += offset;
}
&IndexedChoiceInstruction::Retry(l) => try_or_fail!(self, call_policy.retry(self, l)),
&IndexedChoiceInstruction::Trust(l) => try_or_fail!(self, call_policy.trust(self, l)),
&IndexedChoiceInstruction::Retry(l) => {
try_or_fail!(self, call_policy.retry(self, l));
}
&IndexedChoiceInstruction::Trust(l) => {
try_or_fail!(self, call_policy.trust(self, l));
}
};
}
@@ -3241,7 +3187,9 @@ impl MachineState {
&ChoiceInstruction::RetryMeElse(offset) => {
try_or_fail!(self, call_policy.retry_me_else(self, offset))
}
&ChoiceInstruction::TrustMe => try_or_fail!(self, call_policy.trust_me(self)),
&ChoiceInstruction::TrustMe => {
try_or_fail!(self, call_policy.trust_me(self))
}
}
}

View File

@@ -45,6 +45,7 @@ use crate::prolog::machine::toplevel::*;
use indexmap::IndexMap;
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::fs::File;
use std::mem;
use std::ops::Index;
@@ -558,6 +559,8 @@ impl Machine {
let arity = match &self.machine_st.heap[s+2] {
&HeapCellValue::Integer(ref arity) =>
arity.to_usize().unwrap(),
&HeapCellValue::Addr(Addr::Fixnum(n)) =>
usize::try_from(n).unwrap(),
_ =>
unreachable!()
};
@@ -583,6 +586,8 @@ impl Machine {
let prec = match &self.machine_st.heap[s+1] {
&HeapCellValue::Integer(ref arity) =>
arity.to_usize().unwrap(),
&HeapCellValue::Addr(Addr::Fixnum(n)) =>
usize::try_from(n).unwrap(),
_ =>
unreachable!()
};

View File

@@ -23,9 +23,9 @@ use crate::ref_thread_local::RefThreadLocal;
use indexmap::{IndexMap, IndexSet};
use std::cmp;
use std::convert::TryFrom;
use std::io::{stdout, Write};
use std::iter::once;
use std::mem;
use std::rc::Rc;
use crate::crossterm::event::{read, Event, KeyCode, KeyEvent};
@@ -269,9 +269,9 @@ impl MachineState {
}
}
fn skip_max_list_result(&mut self, max_steps: &Integer) {
fn skip_max_list_result(&mut self, max_steps: Option<isize>) {
let search_result =
if let Some(max_steps) = max_steps.to_isize() {
if let Some(max_steps) = max_steps {
if max_steps == -1 {
self.detect_cycles(self[temp_v!(3)])
} else {
@@ -307,46 +307,52 @@ impl MachineState {
};
}
pub(super) fn skip_max_list(&mut self) -> CallResult {
pub(super)
fn skip_max_list(&mut self) -> CallResult {
let max_steps = self.store(self.deref(self[temp_v!(2)]));
match max_steps {
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(ref max_steps) = self.heap.clone(h) {
if max_steps.to_isize().map(|i| i >= -1).unwrap_or(false) {
Addr::HeapCell(_) | Addr::StackCell(..) | Addr::AttrVar(_) => {
let stub = MachineError::functor_stub(clause_name!("$skip_max_list"), 4);
return Err(self.error_form(MachineError::instantiation_error(), stub));
}
addr => {
let max_steps_n =
match Number::try_from((max_steps, &self.heap)) {
Ok(Number::Integer(n)) => n.to_isize(),
Ok(Number::Fixnum(n)) => Some(n),
_ => None,
};
if max_steps_n.map(|i| i >= -1).unwrap_or(false) {
let n = self.store(self.deref(self[temp_v!(1)]));
match n {
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
match Number::try_from((n, &self.heap)) {
Ok(Number::Integer(n)) => {
if n.as_ref() == &0 {
let xs0 = self[temp_v!(3)];
let xs = self[temp_v!(4)];
self.unify(xs0, xs);
} else {
self.skip_max_list_result(max_steps.as_ref());
self.skip_max_list_result(max_steps_n);
}
}
Ok(Number::Fixnum(n)) => {
if n == 0 {
let xs0 = self[temp_v!(3)];
let xs = self[temp_v!(4)];
self.unify(xs0, xs);
} else {
unreachable!()
self.skip_max_list_result(max_steps_n);
}
}
_ => {
self.skip_max_list_result(max_steps.as_ref());
self.skip_max_list_result(max_steps_n);
}
}
} else {
self.fail = true;
}
} else {
unreachable!()
}
}
Addr::HeapCell(_) | Addr::StackCell(..) => {
let stub = MachineError::functor_stub(clause_name!("$skip_max_list"), 4);
return Err(self.error_form(MachineError::instantiation_error(), stub));
}
addr => {
let stub = MachineError::functor_stub(clause_name!("$skip_max_list"), 4);
return Err(
self.error_form(
@@ -359,7 +365,8 @@ impl MachineState {
)
);
}
};
}
}
Ok(())
}
@@ -671,6 +678,10 @@ impl MachineState {
let addr = self.heap.put_constant(Constant::Integer(n));
self.unify(nx, addr);
}
Ok(Term::Constant(_, Constant::Fixnum(n))) => {
let addr = self.heap.put_constant(Constant::Fixnum(n));
self.unify(nx, addr);
}
Ok(Term::Constant(_, Constant::CharCode(c))) => {
self.unify(nx, Addr::CharCode(c))
}
@@ -774,12 +785,13 @@ impl MachineState {
}
&SystemClauseType::BindFromRegister => {
let reg = self.store(self.deref(self[temp_v!(2)]));
let n = match reg {
Addr::Con(h) =>
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
let n =
match Number::try_from((reg, &self.heap)) {
Ok(Number::Integer(n)) => {
n.to_usize()
} else {
unreachable!()
}
Ok(Number::Fixnum(n)) => {
usize::try_from(n).ok()
}
_ => {
unreachable!()
@@ -1020,15 +1032,36 @@ impl MachineState {
let mut chars = String::new();
for addr in addrs {
match addr {
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
match Number::try_from((addr, &self.heap)) {
Ok(Number::Fixnum(n)) => {
match u32::try_from(n) {
Ok(c) => {
chars.push(std::char::from_u32(c).unwrap());
}
_ => {
let c = self.int_to_char_code(
&Integer::from(n),
"atom_codes",
2,
)?;
chars.push(std::char::from_u32(c).unwrap());
}
}
continue;
}
Ok(Number::Integer(n)) => {
let c = self.int_to_char_code(&n, "atom_codes", 2)?;
chars.push(std::char::from_u32(c).unwrap());
} else {
unreachable!()
continue;
}
_ => {
}
}
match addr {
Addr::CharCode(c) => {
chars.push(std::char::from_u32(c).unwrap());
}
@@ -1056,7 +1089,9 @@ impl MachineState {
}
}
}
_ => unreachable!(),
_ => {
unreachable!()
}
};
}
&SystemClauseType::AtomLength => {
@@ -1088,17 +1123,6 @@ impl MachineState {
self.unify(a2, len);
}
&SystemClauseType::CallAttributeGoals => {
let p = self.attr_var_init.project_attrs_loc;
if self.last_call {
self.execute_at_index(2, dir_entry!(p));
} else {
self.call_at_index(2, dir_entry!(p));
}
return Ok(());
}
&SystemClauseType::CallContinuation => {
let stub = MachineError::functor_stub(clause_name!("call_continuation"), 1);
@@ -1201,16 +1225,18 @@ impl MachineState {
let n = self[temp_v!(1)];
let chs = self[temp_v!(2)];
let string = match self.store(self.deref(n)) {
Addr::Float(OrderedFloat(n)) => {
let n = self.store(self.deref(n));
let string =
match Number::try_from((n, &self.heap)) {
Ok(Number::Float(OrderedFloat(n))) => {
format!("{0:<20?}", n)
}
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
Ok(Number::Fixnum(n)) => {
n.to_string()
} else {
unreachable!()
}
Ok(Number::Integer(n)) => {
n.to_string()
}
_ => {
unreachable!()
@@ -1226,16 +1252,16 @@ impl MachineState {
let n = self[temp_v!(1)];
let chs = self[temp_v!(2)];
let string = match self.store(self.deref(n)) {
Addr::Float(OrderedFloat(n)) => {
let string =
match Number::try_from((n, &self.heap)) {
Ok(Number::Float(OrderedFloat(n))) => {
format!("{0:<20?}", n)
}
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
Ok(Number::Fixnum(n)) => {
n.to_string()
} else {
unreachable!()
}
Ok(Number::Integer(n)) => {
n.to_string()
}
_ => {
unreachable!()
@@ -1322,21 +1348,26 @@ impl MachineState {
}
addr if addr.is_ref() => {
let a2 = self[temp_v!(2)];
let a2 = self.store(self.deref(a2));
match self.store(self.deref(a2)) {
Addr::CharCode(code) => {
if let Some(c) = std::char::from_u32(code) {
self.unify(Addr::Char(c), addr);
} else {
self.fail = true;
}
}
Addr::Con(h) if self.heap.integer_at(h) => {
let c =
if let HeapCellValue::Integer(n) = &self.heap[h] {
let c = match Number::try_from((a2, &self.heap)) {
Ok(Number::Integer(n)) => {
self.int_to_char_code(&n, "char_code", 2)?
} else {
unreachable!()
}
Ok(Number::Fixnum(n)) => {
self.int_to_char_code(&Integer::from(n), "char_code", 2)?
}
_ => {
match addr {
Addr::CharCode(c) => {
c
}
_ => {
self.fail = true;
return Ok(());
}
}
}
};
if let Some(c) = std::char::from_u32(c) {
@@ -1345,10 +1376,9 @@ impl MachineState {
self.fail = true;
}
}
_ => self.fail = true,
};
_ => {
unreachable!();
}
_ => unreachable!(),
};
}
&SystemClauseType::CheckCutPoint => {
@@ -1967,15 +1997,19 @@ impl MachineState {
let specifier = self[temp_v!(2)];
let op = self[temp_v!(3)];
let priority = match self.store(self.deref(priority)) {
Addr::Con(h) if self.heap.integer_at(h) =>
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
let priority = self.store(self.deref(priority));
let priority =
match Number::try_from((priority, &self.heap)) {
Ok(Number::Integer(n)) => {
n.to_usize().unwrap()
} else {
unreachable!()
},
_ =>
unreachable!(),
}
Ok(Number::Fixnum(n)) => {
usize::try_from(n).unwrap()
}
_ => {
unreachable!();
}
};
let specifier = match self.store(self.deref(specifier)) {
@@ -2041,10 +2075,6 @@ impl MachineState {
let attr_goals = self.attr_var_init.attribute_goals.clone();
self.fetch_attribute_goals(attr_goals);
}
&SystemClauseType::FetchAttributeGoals => {
let attr_goals = mem::replace(&mut self.attr_var_init.attribute_goals, vec![]);
self.fetch_attribute_goals(attr_goals);
}
&SystemClauseType::GetAttributedVariableList => {
let attr_var = self.store(self.deref(self[temp_v!(1)]));
let attr_var_list =
@@ -2080,37 +2110,38 @@ impl MachineState {
}
&SystemClauseType::GetAttrVarQueueBeyond => {
let addr = self[temp_v!(1)];
let addr = self.store(self.deref(addr));
match self.store(self.deref(addr)) {
let b =
match addr {
Addr::Usize(b) => {
let iter = self.gather_attr_vars_created_since(b);
let var_list_addr = Addr::HeapCell(self.heap.to_list(iter));
let list_addr = self[temp_v!(2)];
self.unify(var_list_addr, list_addr);
Some(b)
}
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(n) = self.heap.clone(h) {
if let Some(b) = n.to_usize() {
let iter = self.gather_attr_vars_created_since(b);
let var_list_addr = Addr::HeapCell(self.heap.to_list(iter));
let list_addr = self[temp_v!(2)];
self.unify(var_list_addr, list_addr);
} else {
self.fail = true;
}
} else {
unreachable!()
_ => {
match Number::try_from((addr, &self.heap)) {
Ok(Number::Integer(n)) => {
n.to_usize()
}
Ok(Number::Fixnum(n)) => {
usize::try_from(n).ok()
}
_ => {
self.fail = true;
return Ok(());
}
}
}
};
if let Some(b) = b {
let iter = self.gather_attr_vars_created_since(b);
let var_list_addr = Addr::HeapCell(self.heap.to_list(iter));
let list_addr = self[temp_v!(2)];
self.unify(var_list_addr, list_addr);
}
}
&SystemClauseType::GetContinuationChunk => {
let e = self.store(self.deref(self[temp_v!(1)]));
@@ -2327,32 +2358,13 @@ impl MachineState {
CWILCallPolicy::new_in_place(call_policy);
}
match (a1, a2) {
(Addr::Usize(bp), Addr::Con(h))
| (Addr::CutPoint(bp), Addr::Con(h))
if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(n) = self.heap.clone(h) {
match call_policy.downcast_mut::<CWILCallPolicy>().ok() {
Some(call_policy) => {
let count = call_policy.add_limit(Integer::from(&*n), bp);
let count = self.heap.to_unifiable(
HeapCellValue::Integer(Rc::new(count.clone()))
);
let a3 = self[temp_v!(3)];
self.unify(a3, count);
}
None => {
panic!(
"install_inference_counter: should have installed \\
CWILCallPolicy."
)
}
}
} else {
unreachable!()
let n =
match Number::try_from((a2, &self.heap)) {
Ok(Number::Integer(n)) => {
Integer::from(&*n.clone())
}
Ok(Number::Fixnum(n)) => {
Integer::from(n)
}
_ => {
let stub = MachineError::functor_stub(
@@ -2369,9 +2381,35 @@ impl MachineState {
stub,
);
self.throw_exception(type_error)
self.throw_exception(type_error);
return Ok(());
}
};
match a1 {
Addr::Usize(bp) | Addr::CutPoint(bp) => {
match call_policy.downcast_mut::<CWILCallPolicy>().ok() {
Some(call_policy) => {
let count = call_policy.add_limit(n, bp).clone();
let count = self.heap.to_unifiable(
HeapCellValue::Integer(Rc::new(count))
);
let a3 = self[temp_v!(3)];
self.unify(a3, count);
}
None => {
panic!(
"install_inference_counter: should have installed \\
CWILCallPolicy."
)
}
}
}
_ => {
unreachable!();
}
}
}
&SystemClauseType::ModuleExists => {
let module = self.store(self.deref(self[temp_v!(1)]));
@@ -2582,9 +2620,9 @@ impl MachineState {
match a1 {
Addr::Usize(bp) | Addr::CutPoint(bp) => {
let count = call_policy.remove_limit(bp);
let count = call_policy.remove_limit(bp).clone();
let count = self.heap.to_unifiable(
HeapCellValue::Integer(Rc::new(count.clone())),
HeapCellValue::Integer(Rc::new(count)),
);
let a2 = self[temp_v!(2)];
@@ -3029,29 +3067,24 @@ impl MachineState {
Addr::CharCode(c) => {
Integer::from(c)
}
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
Integer::from(&**n)
} else {
unreachable!()
_ => {
match Number::try_from((seed, &self.heap)) {
Ok(Number::Fixnum(n)) => {
Integer::from(n)
}
Ok(Number::Integer(n)) => {
Integer::from(n.as_ref())
}
Addr::Con(h) if self.heap.rational_at(h) => {
if let HeapCellValue::Rational(r) = &self.heap[h] {
if r.denom() == &1 {
r.numer().clone()
} else {
self.fail = true;
return Ok(());
}
} else {
unreachable!()
}
Ok(Number::Rational(n))
if n.denom() == &1 => {
n.numer().clone()
}
_ => {
self.fail = true;
return Ok(());
}
}
}
};
let mut rand = RANDOM_STATE.borrow_mut();
@@ -3195,13 +3228,15 @@ impl MachineState {
}
};
let arity = match self.store(self.deref(arity)) {
Addr::Con(h) if self.heap.integer_at(h) => {
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
n.clone()
} else {
unreachable!()
let arity = self.store(self.deref(arity));
let arity =
match Number::try_from((arity, &self.heap)) {
Ok(Number::Fixnum(n)) => {
Integer::from(n)
}
Ok(Number::Integer(n)) => {
Integer::from(n.as_ref())
}
_ => {
unreachable!()
@@ -3212,26 +3247,14 @@ impl MachineState {
.code_dir
.get(&(name.clone(), arity.to_usize().unwrap()))
{
Some(ref idx) => {
Some(ref idx) if idx.local().is_some() => {
if let Some(idx) = idx.local() {
idx
} else {
let arity = arity.to_usize().unwrap();
let stub = MachineError::functor_stub(name.clone(), arity);
let h = self.heap.h();
let err = MachineError::existence_error(
h,
ExistenceError::Procedure(name, arity),
);
let err = self.error_form(err, stub);
self.throw_exception(err);
return Ok(());
unreachable!()
}
}
None => {
_ => {
let arity = arity.to_usize().unwrap();
let stub = MachineError::functor_stub(name.clone(), arity);
let h = self.heap.h();
@@ -3302,16 +3325,25 @@ impl MachineState {
}
}
if let &Addr::Con(h) = &max_depth {
if let HeapCellValue::Integer(ref n) = &self.heap[h] {
match Number::try_from((max_depth, &self.heap)) {
Ok(Number::Fixnum(n)) => {
if let Ok(n) = usize::try_from(n) {
printer.max_depth = n;
} else {
self.fail = true;
return Ok(());
}
}
Ok(Number::Integer(n)) => {
if let Some(n) = n.to_usize() {
printer.max_depth = n;
} else {
self.fail = true;
return Ok(());
}
} else {
unreachable!()
}
_ => {
unreachable!();
}
}

View File

@@ -13,6 +13,7 @@ use indexmap::{IndexMap, IndexSet};
use std::borrow::BorrowMut;
use std::cell::Cell;
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::mem;
use std::ops::DerefMut;
use std::rc::Rc;
@@ -211,8 +212,8 @@ fn setup_op_decl(
};
let prec = match *terms.pop().unwrap() {
Term::Constant(_, Constant::Integer(bi)) => match bi.to_usize() {
Some(n) if n <= 1200 => n,
Term::Constant(_, Constant::Fixnum(bi)) => match usize::try_from(bi) {
Ok(n) if n <= 1200 => n,
_ => return Err(ParserError::InconsistentEntry),
},
_ => return Err(ParserError::InconsistentEntry),
@@ -232,8 +233,13 @@ fn setup_predicate_indicator(term: &mut Term) -> Result<PredicateKey, ParserErro
let arity = arity
.to_constant()
.and_then(|c| c.to_integer())
.and_then(|n| n.to_usize())
.and_then(|c| {
match c {
Constant::Integer(n) => n.to_usize(),
Constant::Fixnum(n) => usize::try_from(n).ok(),
_ => None
}
})
.ok_or(ParserError::InvalidModuleExport)?;
let name = name
@@ -656,14 +662,16 @@ fn setup_declaration<'a, 'b, 'c>(
let mut term = *terms.pop().unwrap();
match setup_predicate_indicator(&mut term) {
Ok((name, arity)) =>
Ok(Declaration::MultiFile(MultiFileIndicator::LocalScoped(name, arity))),
_ =>
Ok((name, arity)) => {
Ok(Declaration::MultiFile(MultiFileIndicator::LocalScoped(name, arity)))
}
_ => {
setup_scoped_predicate_indicator(&mut term)
.map(|key| {
Declaration::MultiFile(MultiFileIndicator::ModuleScoped(key))
})
}
}
}
("use_module", 1) => {
Ok(Declaration::UseModule(setup_use_module_decl(terms)?))
@@ -676,7 +684,9 @@ fn setup_declaration<'a, 'b, 'c>(
Err(ParserError::InconsistentEntry)
}
},
_ => Err(ParserError::InconsistentEntry),
_ => {
Err(ParserError::InconsistentEntry)
}
}
}

View File

@@ -138,6 +138,9 @@ macro_rules! from_constant {
&Constant::CharCode(c) => {
HeapCellValue::Addr(Addr::CharCode(c))
}
&Constant::Fixnum(n) => {
HeapCellValue::Addr(Addr::Fixnum(n))
}
&Constant::Integer(ref n) => {
HeapCellValue::Integer(n.clone())
}

View File

@@ -39,7 +39,8 @@
E,
'$print_exception_with_check'(E))
)
; '$submit_query_and_print_results'(Term, VarList)
;
'$submit_query_and_print_results'(Term, VarList)
).
'$submit_query_and_print_results'(Term0, VarList) :-
@@ -225,10 +226,8 @@
).
'$gather_goals'([], VarList, Goals) :-
'$get_attr_var_queue_beyond'(0, AttrVars),
'$gather_query_vars'(VarList, QueryVars),
'$call_attribute_goals'(QueryVars, AttrVars),
'$fetch_attribute_goals'(Goals).
copy_term(QueryVars, QueryVars, Goals).
'$gather_goals'([Var = Value | Pairs], VarList, Goals) :-
( ( nonvar(Value)
; '$is_a_different_variable'(Pairs, Value)

View File

@@ -187,6 +187,7 @@ impl fmt::Display for Addr {
&Addr::Char(c) => write!(f, "Addr::Char({})", c),
&Addr::CharCode(c) => write!(f, "Addr::CharCode({})", c),
&Addr::EmptyList => write!(f, "Addr::EmptyList"),
&Addr::Fixnum(n) => write!(f, "Addr::Fixnum({})", n),
&Addr::Float(fl) => write!(f, "Addr::Float({})", fl),
&Addr::CutPoint(cp) => write!(f, "Addr::CutPoint({})", cp),
&Addr::Con(ref c) => write!(f, "Addr::Con({})", c),
@@ -319,6 +320,7 @@ impl fmt::Display for Line {
impl fmt::Display for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Number::Fixnum(n) => write!(f, "{}", n),
&Number::Float(fl) => write!(f, "{}", fl),
&Number::Integer(ref bi) => write!(f, "{}", bi),
&Number::Rational(ref r) => write!(f, "{}", r),

View File

@@ -23,6 +23,6 @@ test_queries_on_facts :-
retract(p(_,_,_)),
assertz(p(Z, h(Z, W), f(W))),
p(f(f(a)), h(f(f(a)), f(a)), f(f(a))),
retract(p(Z, h(Z, W), f(W))).[
retract(p(Z, h(Z, W), f(W))).
:- initialization(test_queries_on_facts).

View File

@@ -62,4 +62,3 @@ cleanup :- abolish(p/3),
abolish(h/1).
:- initialization(test_queries_on_rules).