Merge branch 'rebis-dev' of https://github.com/mthom/scryer-prolog into rebis-dev

This commit is contained in:
Mark Thom
2021-02-02 22:59:28 -07:00
64 changed files with 10731 additions and 7644 deletions

View File

@@ -1,9 +1,9 @@
[package]
name = "prolog_parser"
name = "prolog_parser_rebis"
version = "0.8.68"
authors = ["Mark Thom <markjordanthom@gmail.com>"]
repository = "https://github.com/mthom/scryer-prolog"
description = " An operator precedence parser for scryer-prolog, an up and coming ISO Prolog implementation."
repository = "https://github.com/mthom/prolog_parser"
description = " An operator precedence parser for the Rebis development version of Scryer Prolog, an up and coming ISO Prolog implementation."
license = "BSD-3-Clause"
[dependencies]

View File

@@ -1,5 +1,5 @@
use ordered_float::*;
use rug::{Integer, Rational};
use ordered_float::*;
use tabled_rc::*;
use put_back_n::*;
@@ -10,6 +10,7 @@ use std::collections::HashMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::io::{Bytes, Error as IOError, Read};
use std::ops::Deref;
use std::rc::Rc;
use std::vec::Vec;
@@ -26,140 +27,112 @@ pub const MAX_ARITY: usize = 1023;
pub const XFX: u32 = 0x0001;
pub const XFY: u32 = 0x0002;
pub const YFX: u32 = 0x0004;
pub const XF: u32 = 0x0010;
pub const YF: u32 = 0x0020;
pub const FX: u32 = 0x0040;
pub const FY: u32 = 0x0080;
pub const XF: u32 = 0x0010;
pub const YF: u32 = 0x0020;
pub const FX: u32 = 0x0040;
pub const FY: u32 = 0x0080;
pub const DELIMITER: u32 = 0x0100;
pub const TERM: u32 = 0x1000;
pub const TERM: u32 = 0x1000;
pub const LTERM: u32 = 0x3000;
pub const NEGATIVE_SIGN: u32 = 0x0200;
#[macro_export]
macro_rules! clause_name {
($name: expr, $tbl: expr) => {
($name: expr, $tbl: expr) => (
ClauseName::User(TabledRc::new($name, $tbl.clone()))
};
($name: expr) => {
) ;
($name: expr) => (
ClauseName::BuiltIn($name)
};
)
}
#[macro_export]
macro_rules! atom {
($e:expr, $tbl:expr) => {
($e:expr, $tbl:expr) => (
Constant::Atom(ClauseName::User(tabled_rc!($e, $tbl)), None)
};
($e:expr) => {
);
($e:expr) => (
Constant::Atom(clause_name!($e), None)
};
)
}
#[macro_export]
macro_rules! rc_atom {
($e:expr) => {
($e:expr) => (
Rc::new(String::from($e))
};
)
}
macro_rules! is_term {
($x:expr) => {
($x & TERM) != 0
};
($x:expr) => ( ($x & TERM) != 0 )
}
macro_rules! is_lterm {
($x:expr) => {
($x & LTERM) != 0
};
($x:expr) => ( ($x & LTERM) != 0 )
}
macro_rules! is_op {
($x:expr) => {
$x & (XF | YF | FX | FY | XFX | XFY | YFX) != 0
};
($x:expr) => ( $x & (XF | YF | FX | FY | XFX | XFY | YFX) != 0 )
}
macro_rules! is_negate {
($x:expr) => {
($x & NEGATIVE_SIGN) != 0
};
($x:expr) => ( ($x & NEGATIVE_SIGN) != 0 )
}
#[macro_export]
macro_rules! is_prefix {
($x:expr) => {
$x & (FX | FY) != 0
};
($x:expr) => ( $x & (FX | FY) != 0 )
}
#[macro_export]
macro_rules! is_postfix {
($x:expr) => {
$x & (XF | YF) != 0
};
($x:expr) => ( $x & (XF | YF) != 0 )
}
#[macro_export]
macro_rules! is_infix {
($x:expr) => {
($x & (XFX | XFY | YFX)) != 0
};
($x:expr) => ( ($x & (XFX | XFY | YFX)) != 0 )
}
#[macro_export]
macro_rules! is_xfx {
($x:expr) => {
($x & XFX) != 0
};
($x:expr) => ( ($x & XFX) != 0 )
}
#[macro_export]
macro_rules! is_xfy {
($x:expr) => {
($x & XFY) != 0
};
($x:expr) => ( ($x & XFY) != 0 )
}
#[macro_export]
macro_rules! is_yfx {
($x:expr) => {
($x & YFX) != 0
};
($x:expr) => ( ($x & YFX) != 0 )
}
#[macro_export]
macro_rules! is_yf {
($x:expr) => {
($x & YF) != 0
};
($x:expr) => ( ($x & YF) != 0 )
}
#[macro_export]
macro_rules! is_xf {
($x:expr) => {
($x & XF) != 0
};
($x:expr) => ( ($x & XF) != 0 )
}
#[macro_export]
macro_rules! is_fx {
($x:expr) => {
($x & FX) != 0
};
($x:expr) => ( ($x & FX) != 0 )
}
#[macro_export]
macro_rules! is_fy {
($x:expr) => {
($x & FY) != 0
};
($x:expr) => ( ($x & FY) != 0 )
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RegType {
Perm(usize),
Temp(usize),
Temp(usize)
}
impl Default for RegType {
@@ -171,14 +144,14 @@ impl Default for RegType {
impl RegType {
pub fn reg_num(self) -> usize {
match self {
RegType::Perm(reg_num) | RegType::Temp(reg_num) => reg_num,
RegType::Perm(reg_num) | RegType::Temp(reg_num) => reg_num
}
}
pub fn is_perm(self) -> bool {
match self {
RegType::Perm(_) => true,
_ => false,
_ => false
}
}
}
@@ -187,7 +160,7 @@ impl fmt::Display for RegType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&RegType::Perm(val) => write!(f, "Y{}", val),
&RegType::Temp(val) => write!(f, "X{}", val),
&RegType::Temp(val) => write!(f, "X{}", val)
}
}
}
@@ -195,13 +168,13 @@ impl fmt::Display for RegType {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum VarReg {
ArgAndNorm(RegType, usize),
Norm(RegType),
Norm(RegType)
}
impl VarReg {
pub fn norm(self) -> RegType {
match self {
VarReg::ArgAndNorm(reg, _) | VarReg::Norm(reg) => reg,
VarReg::ArgAndNorm(reg, _) | VarReg::Norm(reg) => reg
}
}
}
@@ -211,8 +184,10 @@ impl fmt::Display for VarReg {
match self {
&VarReg::Norm(RegType::Perm(reg)) => write!(f, "Y{}", reg),
&VarReg::Norm(RegType::Temp(reg)) => write!(f, "X{}", reg),
&VarReg::ArgAndNorm(RegType::Perm(reg), arg) => write!(f, "Y{} A{}", reg, arg),
&VarReg::ArgAndNorm(RegType::Temp(reg), arg) => write!(f, "X{} A{}", reg, arg),
&VarReg::ArgAndNorm(RegType::Perm(reg), arg) =>
write!(f, "Y{} A{}", reg, arg),
&VarReg::ArgAndNorm(RegType::Temp(reg), arg) =>
write!(f, "X{} A{}", reg, arg)
}
}
}
@@ -225,30 +200,28 @@ impl Default for VarReg {
#[macro_export]
macro_rules! temp_v {
($x:expr) => {
($x:expr) => (
RegType::Temp($x)
};
)
}
#[macro_export]
macro_rules! perm_v {
($x:expr) => {
($x:expr) => (
RegType::Perm($x)
};
)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum GenContext {
Head,
Mid(usize),
Last(usize), // Mid & Last: chunk_num
Head, Mid(usize), Last(usize) // Mid & Last: chunk_num
}
impl GenContext {
pub fn chunk_num(self) -> usize {
match self {
GenContext::Head => 0,
GenContext::Mid(cn) | GenContext::Last(cn) => cn,
GenContext::Mid(cn) | GenContext::Last(cn) => cn
}
}
}
@@ -256,22 +229,17 @@ impl GenContext {
pub type OpDirKey = (ClauseName, Fixity);
#[derive(Debug, Clone)]
pub struct OpDirValue(pub SharedOpDesc, pub ClauseName);
pub struct OpDirValue(pub SharedOpDesc);
impl OpDirValue {
pub fn new(spec: Specifier, priority: usize, module_name: ClauseName) -> Self {
OpDirValue(SharedOpDesc::new(priority, spec), module_name)
pub fn new(spec: Specifier, priority: usize) -> Self {
OpDirValue(SharedOpDesc::new(priority, spec))
}
#[inline]
pub fn shared_op_desc(&self) -> SharedOpDesc {
self.0.clone()
}
#[inline]
pub fn owning_module(&self) -> ClauseName {
self.1.clone()
}
}
// name and fixity -> operator type and precedence.
@@ -279,22 +247,18 @@ pub type OpDir = HashMap<OpDirKey, OpDirValue>;
#[derive(Debug, Clone, Copy)]
pub struct MachineFlags {
pub double_quotes: DoubleQuotes,
pub double_quotes: DoubleQuotes
}
impl Default for MachineFlags {
fn default() -> Self {
MachineFlags {
double_quotes: DoubleQuotes::default(),
}
MachineFlags { double_quotes: DoubleQuotes::default() }
}
}
#[derive(Debug, Clone, Copy)]
pub enum DoubleQuotes {
Atom,
Chars,
Codes,
Atom, Chars, Codes
}
impl DoubleQuotes {
@@ -330,118 +294,78 @@ impl Default for DoubleQuotes {
}
pub fn default_op_dir() -> OpDir {
let module_name = clause_name!("builtins");
let mut op_dir = OpDir::new();
op_dir.insert(
(clause_name!(":-"), Fixity::In),
OpDirValue::new(XFX, 1200, module_name.clone()),
);
op_dir.insert(
(clause_name!(":-"), Fixity::Pre),
OpDirValue::new(FX, 1200, module_name.clone()),
);
op_dir.insert(
(clause_name!("?-"), Fixity::Pre),
OpDirValue::new(FX, 1200, module_name.clone()),
);
op_dir.insert(
(clause_name!(","), Fixity::In),
OpDirValue::new(XFY, 1000, module_name.clone()),
);
op_dir.insert((clause_name!(":-"), Fixity::In), OpDirValue::new(XFX, 1200));
op_dir.insert((clause_name!(":-"), Fixity::Pre), OpDirValue::new(FX, 1200));
op_dir.insert((clause_name!("?-"), Fixity::Pre), OpDirValue::new(FX, 1200));
op_dir.insert((clause_name!(","), Fixity::In), OpDirValue::new(XFY, 1000));
op_dir
}
#[derive(PartialEq, Debug, Clone)]
#[derive(Debug, Clone)]
pub enum ArithmeticError {
NonEvaluableFunctor(Constant, usize),
UninstantiatedVar,
UninstantiatedVar
}
#[derive(Debug)]
pub enum ParserError {
Arithmetic(ArithmeticError),
BackQuotedString(usize, usize),
BadPendingByte,
CannotParseCyclicTerm,
UnexpectedChar(char, usize, usize),
UnexpectedEOF,
IO(IOError),
ExpectedRel,
ExpectedTopLevelTerm,
InadmissibleFact,
InadmissibleQueryTerm,
IncompleteReduction(usize, usize),
InconsistentEntry,
InvalidDoubleQuotesDecl,
InvalidHook,
InvalidModuleDecl,
InvalidModuleExport,
InvalidRuleHead,
InvalidUseModuleDecl,
InvalidModuleResolution,
InvalidSingleQuotedCharacter(char),
MissingQuote(usize, usize),
NonPrologChar(usize, usize),
ParseBigInt(usize, usize),
ParseFloat(usize, usize),
Utf8Error(usize, usize),
Utf8Error(usize, usize)
}
impl ParserError {
pub fn line_and_col_num(&self) -> Option<(usize, usize)> {
match self {
&ParserError::BackQuotedString(line_num, col_num)
| &ParserError::UnexpectedChar(_, line_num, col_num)
| &ParserError::IncompleteReduction(line_num, col_num)
| &ParserError::MissingQuote(line_num, col_num)
| &ParserError::NonPrologChar(line_num, col_num)
| &ParserError::ParseBigInt(line_num, col_num)
| &ParserError::ParseFloat(line_num, col_num)
| &ParserError::Utf8Error(line_num, col_num) => Some((line_num, col_num)),
_ => None,
| &ParserError::UnexpectedChar(_, line_num, col_num)
| &ParserError::IncompleteReduction(line_num, col_num)
| &ParserError::MissingQuote(line_num, col_num)
| &ParserError::NonPrologChar(line_num, col_num)
| &ParserError::ParseBigInt(line_num, col_num)
| &ParserError::Utf8Error(line_num, col_num) =>
Some((line_num, col_num)),
_ =>
None
}
}
pub fn as_str(&self) -> &'static str {
match self {
&ParserError::Arithmetic(..) => "arithmetic_error",
&ParserError::BackQuotedString(..) => "back_quoted_string",
&ParserError::BadPendingByte => "bad_pending_byte",
&ParserError::UnexpectedChar(..) => "unexpected_char",
&ParserError::UnexpectedEOF => "unexpected_end_of_file",
&ParserError::ExpectedRel => "expected_relation",
&ParserError::ExpectedTopLevelTerm => "expected_atom_or_cons_or_clause",
&ParserError::InadmissibleFact => "inadmissible_fact",
&ParserError::InadmissibleQueryTerm => "inadmissible_query_term",
&ParserError::IncompleteReduction(..) => "incomplete_reduction",
&ParserError::InconsistentEntry => "inconsistent_entry",
&ParserError::InvalidDoubleQuotesDecl => "invalid_double_quotes_declaration",
&ParserError::InvalidHook => "invalid_hook",
&ParserError::InvalidModuleDecl => "invalid_module_declaration",
&ParserError::InvalidModuleExport => "invalid_module_export",
&ParserError::InvalidModuleResolution => "invalid_module_resolution",
&ParserError::InvalidRuleHead => "invalid_head_of_rule",
&ParserError::InvalidUseModuleDecl => "invalid_use_module_declaration",
&ParserError::InvalidSingleQuotedCharacter(..) => "invalid_single_quoted_character",
&ParserError::IO(_) => "input_output_error",
&ParserError::MissingQuote(..) => "missing_quote",
&ParserError::NonPrologChar(..) => "non_prolog_character",
&ParserError::ParseBigInt(..) => "cannot_parse_big_int",
&ParserError::ParseFloat(..) => "cannot_parse_float",
&ParserError::Utf8Error(..) => "utf8_conversion_error",
&ParserError::CannotParseCyclicTerm => "cannot_parse_cyclic_term",
&ParserError::BackQuotedString(..) =>
"back_quoted_string",
&ParserError::UnexpectedChar(..) =>
"unexpected_char",
&ParserError::UnexpectedEOF =>
"unexpected_end_of_file",
&ParserError::IncompleteReduction(..) =>
"incomplete_reduction",
&ParserError::InvalidSingleQuotedCharacter(..) =>
"invalid_single_quoted_character",
&ParserError::IO(_) =>
"input_output_error",
&ParserError::MissingQuote(..) =>
"missing_quote",
&ParserError::NonPrologChar(..) =>
"non_prolog_character",
&ParserError::ParseBigInt(..) =>
"cannot_parse_big_int",
&ParserError::Utf8Error(..) =>
"utf8_conversion_error",
}
}
}
impl From<ArithmeticError> for ParserError {
fn from(err: ArithmeticError) -> ParserError {
ParserError::Arithmetic(err)
}
}
impl From<IOError> for ParserError {
fn from(err: IOError) -> ParserError {
ParserError::IO(err)
@@ -458,11 +382,39 @@ impl From<&IOError> for ParserError {
}
}
#[derive(Debug, Clone, Copy)]
pub struct CompositeOpDir<'a, 'b> {
pub primary_op_dir: Option<&'b OpDir>,
pub secondary_op_dir: &'a OpDir,
}
impl<'a, 'b> CompositeOpDir<'a, 'b>
{
#[inline]
pub fn new(secondary_op_dir: &'a OpDir, primary_op_dir: Option<&'b OpDir>) -> Self {
CompositeOpDir { primary_op_dir, secondary_op_dir }
}
#[inline]
pub(crate)
fn get(&self, name: ClauseName, fixity: Fixity) -> Option<&OpDirValue>
{
let entry =
if let Some(ref primary_op_dir) = &self.primary_op_dir {
primary_op_dir.get(&(name.clone(), fixity))
} else {
None
};
entry.or_else(move || self.secondary_op_dir.get(&(name, fixity)))
}
}
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum Fixity {
In,
Post,
Pre,
In, Post, Pre
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
@@ -509,6 +461,15 @@ impl SharedOpDesc {
}
}
impl Deref for SharedOpDesc {
type Target = Cell<(usize, Specifier)>;
#[inline]
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
// this ensures that SharedOpDesc (which is not consistently placed in
// every atom!) doesn't affect the value of an atom hash. If
// SharedOpDesc values are to be indexed, a BTreeMap or BTreeSet
@@ -535,21 +496,28 @@ pub enum Constant {
impl fmt::Display for Constant {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Constant::Atom(ref atom, _) => {
&Constant::Atom(ref atom, _) =>
if atom.as_str().chars().any(|c| "`.$'\" ".contains(c)) {
write!(f, "'{}'", atom.as_str())
} else {
write!(f, "{}", atom.as_str())
}
}
&Constant::Char(c) => write!(f, "'{}'", c as u32),
&Constant::EmptyList => write!(f, "[]"),
&Constant::Fixnum(n) => write!(f, "{}", n),
&Constant::Integer(ref n) => write!(f, "{}", n),
&Constant::Rational(ref n) => write!(f, "{}", n),
&Constant::Float(ref n) => write!(f, "{}", n),
&Constant::String(ref s) => write!(f, "\"{}\"", &s),
&Constant::Usize(integer) => write!(f, "u{}", integer),
},
&Constant::Char(c) =>
write!(f, "'{}'", c as u32),
&Constant::EmptyList =>
write!(f, "[]"),
&Constant::Fixnum(n) =>
write!(f, "{}", n),
&Constant::Integer(ref n) =>
write!(f, "{}", n),
&Constant::Rational(ref n) =>
write!(f, "{}", n),
&Constant::Float(ref n) =>
write!(f, "{}", n),
&Constant::String(ref s) =>
write!(f, "\"{}\"", &s),
&Constant::Usize(integer) =>
write!(f, "u{}", integer),
}
}
}
@@ -558,27 +526,37 @@ impl PartialEq for Constant {
fn eq(&self, other: &Constant) -> bool {
match (self, other) {
(&Constant::Atom(ref atom, _), &Constant::Char(c))
| (&Constant::Char(c), &Constant::Atom(ref atom, _)) => {
atom.is_char() && Some(c) == atom.as_str().chars().next()
}
(&Constant::Atom(ref a1, _), &Constant::Atom(ref a2, _)) => a1.as_str() == a2.as_str(),
(&Constant::Char(c1), &Constant::Char(c2)) => c1 == c2,
(&Constant::Fixnum(n1), &Constant::Fixnum(n2)) => n1 == n2,
(&Constant::Fixnum(n1), &Constant::Integer(ref n2))
| (&Constant::Integer(ref n2), &Constant::Fixnum(n1)) => {
| (&Constant::Char(c), &Constant::Atom(ref atom, _)) => {
atom.is_char() && Some(c) == atom.as_str().chars().next()
},
(&Constant::Atom(ref a1, _), &Constant::Atom(ref a2, _)) =>
a1.as_str() == a2.as_str(),
(&Constant::Char(c1), &Constant::Char(c2)) =>
c1 == c2,
(&Constant::Fixnum(n1), &Constant::Fixnum(n2)) =>
n1 == n2,
(&Constant::Fixnum(n1), &Constant::Integer(ref n2)) |
(&Constant::Integer(ref n2), &Constant::Fixnum(n1)) => {
if let Some(n2) = n2.to_isize() {
n1 == n2
} else {
false
}
}
(&Constant::Integer(ref n1), &Constant::Integer(ref n2)) => n1 == n2,
(&Constant::Rational(ref n1), &Constant::Rational(ref n2)) => n1 == n2,
(&Constant::Float(ref n1), &Constant::Float(ref n2)) => n1 == n2,
(&Constant::String(ref s1), &Constant::String(ref s2)) => &s1 == &s2,
(&Constant::EmptyList, &Constant::EmptyList) => true,
(&Constant::Usize(u1), &Constant::Usize(u2)) => u1 == u2,
_ => false,
(&Constant::Integer(ref n1), &Constant::Integer(ref n2)) =>
n1 == n2,
(&Constant::Rational(ref n1), &Constant::Rational(ref n2)) =>
n1 == n2,
(&Constant::Float(ref n1), &Constant::Float(ref n2)) =>
n1 == n2,
(&Constant::String(ref s1), &Constant::String(ref s2)) => {
&s1 == &s2
}
(&Constant::EmptyList, &Constant::EmptyList) =>
true,
(&Constant::Usize(u1), &Constant::Usize(u2)) =>
u1 == u2,
_ => false
}
}
}
@@ -589,7 +567,7 @@ impl Constant {
pub fn to_atom(self) -> Option<ClauseName> {
match self {
Constant::Atom(a, _) => Some(a.defrock_brackets()),
_ => None,
_ => None
}
}
}
@@ -597,7 +575,7 @@ impl Constant {
#[derive(Debug, Clone)]
pub enum ClauseName {
BuiltIn(&'static str),
User(TabledRc<Atom>),
User(TabledRc<Atom>)
}
impl fmt::Display for ClauseName {
@@ -644,12 +622,10 @@ impl ClauseName {
match self {
&ClauseName::User(ref name) => {
let module = name.owning_module();
ClauseName::User(TabledRc {
atom: module.clone(),
table: TabledData::new(module),
})
}
_ => clause_name!("user"),
ClauseName::User(TabledRc { atom: module.clone(),
table: TabledData::new(module) })
},
_ => clause_name!("user")
}
}
@@ -657,7 +633,7 @@ impl ClauseName {
pub fn to_rc(&self) -> Rc<String> {
match self {
&ClauseName::BuiltIn(s) => Rc::new(s.to_string()),
&ClauseName::User(ref rc) => rc.inner(),
&ClauseName::User(ref rc) => rc.inner()
}
}
@@ -690,7 +666,9 @@ impl ClauseName {
false
}
}
ClauseName::User(ref name) => other.has_table(&name.table),
ClauseName::User(ref name) => {
other.has_table(&name.table)
}
}
}
@@ -698,7 +676,7 @@ impl ClauseName {
pub fn as_str(&self) -> &str {
match self {
&ClauseName::BuiltIn(s) => s,
&ClauseName::User(ref name) => name.as_ref(),
&ClauseName::User(ref name) => name.as_ref()
}
}
@@ -710,17 +688,17 @@ impl ClauseName {
pub fn defrock_brackets(self) -> Self {
fn defrock_brackets(s: &str) -> &str {
if s.starts_with('(') && s.ends_with(')') {
&s[1..s.len() - 1]
&s[1 .. s.len() - 1]
} else {
s
}
}
match self {
ClauseName::BuiltIn(s) => ClauseName::BuiltIn(defrock_brackets(s)),
ClauseName::User(s) => {
ClauseName::BuiltIn(s) =>
ClauseName::BuiltIn(defrock_brackets(s)),
ClauseName::User(s) =>
ClauseName::User(tabled_rc!(defrock_brackets(s.as_str()).to_owned(), s.table))
}
}
}
}
@@ -735,15 +713,10 @@ impl AsRef<str> for ClauseName {
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Term {
AnonVar,
Clause(
Cell<RegType>,
ClauseName,
Vec<Box<Term>>,
Option<SharedOpDesc>,
),
Clause(Cell<RegType>, ClauseName, Vec<Box<Term>>, Option<SharedOpDesc>),
Cons(Cell<RegType>, Box<Term>, Box<Term>),
Constant(Cell<RegType>, Constant),
Var(Cell<VarReg>, Rc<Var>),
Var(Cell<VarReg>, Rc<Var>)
}
impl Term {
@@ -751,29 +724,30 @@ impl Term {
match self {
&Term::Clause(_, _, _, ref spec) => spec.clone(),
&Term::Constant(_, Constant::Atom(_, ref spec)) => spec.clone(),
_ => None,
_ => None
}
}
pub fn to_constant(self) -> Option<Constant> {
match self {
Term::Constant(_, c) => Some(c),
_ => None,
_ => None
}
}
pub fn first_arg(&self) -> Option<&Term> {
match self {
&Term::Clause(_, _, ref terms, _) => terms.first().map(|bt| bt.as_ref()),
_ => None,
&Term::Clause(_, _, ref terms, _) =>
terms.first().map(|bt| bt.as_ref()),
_ => None
}
}
pub fn set_name(&mut self, new_name: ClauseName) {
match self {
Term::Constant(_, Constant::Atom(ref mut atom, _))
| Term::Clause(_, ref mut atom, ..) => {
*atom = new_name;
| Term::Clause(_, ref mut atom, ..) => {
*atom = new_name;
}
_ => {}
}
@@ -781,62 +755,20 @@ impl Term {
pub fn name(&self) -> Option<ClauseName> {
match self {
&Term::Constant(_, Constant::Atom(ref atom, _)) | &Term::Clause(_, ref atom, ..) => {
Some(atom.clone())
}
_ => None,
&Term::Constant(_, Constant::Atom(ref atom, _))
| &Term::Clause(_, ref atom, ..) => Some(atom.clone()),
_ => None
}
}
pub fn arity(&self) -> usize {
match self {
&Term::Clause(_, _, ref child_terms, ..) => child_terms.len(),
_ => 0,
_ => 0
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct CompositeOp<'a, 'b> {
pub op_dir: &'a OpDir,
pub static_op_dir: Option<&'b OpDir>,
}
#[macro_export]
macro_rules! composite_op {
($include_machine_p:expr, $op_dir:expr, $machine_op_dir:expr) => {
CompositeOp {
op_dir: $op_dir,
static_op_dir: if !$include_machine_p {
Some($machine_op_dir)
} else {
None
},
}
};
($op_dir:expr) => {
CompositeOp {
op_dir: $op_dir,
static_op_dir: None,
}
};
}
impl<'a, 'b> CompositeOp<'a, 'b> {
#[inline]
pub(crate) fn get(&self, name: ClauseName, fixity: Fixity) -> Option<OpDirValue> {
let entry = if let Some(ref static_op_dir) = &self.static_op_dir {
static_op_dir.get(&(name.clone(), fixity))
} else {
None
};
entry
.or_else(move || self.op_dir.get(&(name, fixity)))
.cloned()
}
}
fn unfold_by_str_once(term: &mut Term, s: &str) -> Option<(Term, Term)> {
if let &mut Term::Clause(_, ref name, ref mut subterms, _) = term {
if name.as_str() == s && subterms.len() == 2 {

View File

@@ -46,24 +46,24 @@ struct TokenDesc {
}
pub
fn get_clause_spec(name: ClauseName, arity: usize, op_dir: CompositeOp) -> Option<SharedOpDesc>
fn get_clause_spec(name: ClauseName, arity: usize, op_dir: &CompositeOpDir) -> Option<SharedOpDesc>
{
match arity {
1 => {
/* This is a clause with an operator principal functor. Prefix operators
are supposed over post.
*/
if let Some(OpDirValue(cell, _)) = op_dir.get(name.clone(), Fixity::Pre) {
return Some(cell);
if let Some(OpDirValue(cell)) = op_dir.get(name.clone(), Fixity::Pre) {
return Some(cell.clone());
}
if let Some(OpDirValue(cell, _)) = op_dir.get(name, Fixity::Post) {
return Some(cell);
if let Some(OpDirValue(cell)) = op_dir.get(name, Fixity::Post) {
return Some(cell.clone());
}
},
2 =>
if let Some(OpDirValue(cell, _)) = op_dir.get(name, Fixity::In) {
return Some(cell);
if let Some(OpDirValue(cell)) = op_dir.get(name, Fixity::In) {
return Some(cell.clone());
},
_ => {}
};
@@ -71,11 +71,11 @@ fn get_clause_spec(name: ClauseName, arity: usize, op_dir: CompositeOp) -> Optio
None
}
pub fn get_desc(name: ClauseName, op_dir: CompositeOp) -> Option<OpDesc>
pub fn get_op_desc(name: ClauseName, op_dir: &CompositeOpDir) -> Option<OpDesc>
{
let mut op_desc = OpDesc { pre: 0, inf: 0, post: 0, spec: 0 };
if let Some(OpDirValue(cell, _)) = op_dir.get(name.clone(), Fixity::Pre) {
if let Some(OpDirValue(cell)) = op_dir.get(name.clone(), Fixity::Pre) {
let (pri, spec) = cell.get();
if pri > 0 {
@@ -86,7 +86,7 @@ pub fn get_desc(name: ClauseName, op_dir: CompositeOp) -> Option<OpDesc>
}
}
if let Some(OpDirValue(cell, _)) = op_dir.get(name.clone(), Fixity::Post) {
if let Some(OpDirValue(cell)) = op_dir.get(name.clone(), Fixity::Post) {
let (pri, spec) = cell.get();
if pri > 0 {
@@ -95,7 +95,7 @@ pub fn get_desc(name: ClauseName, op_dir: CompositeOp) -> Option<OpDesc>
}
}
if let Some(OpDirValue(cell, _)) = op_dir.get(name.clone(), Fixity::In) {
if let Some(OpDirValue(cell)) = op_dir.get(name.clone(), Fixity::In) {
let (pri, spec) = cell.get();
if pri > 0 {
@@ -319,7 +319,7 @@ impl<'a, R: Read> Parser<'a, R> {
}
fn promote_atom_op(&mut self, atom: ClauseName, priority: usize, assoc: u32,
op_dir_val: Option<OpDirValue>)
op_dir_val: Option<&OpDirValue>)
{
let spec = op_dir_val.map(|op_dir_val| op_dir_val.shared_op_desc());
@@ -454,7 +454,7 @@ impl<'a, R: Read> Parser<'a, R> {
None
}
fn reduce_term(&mut self, op_dir: CompositeOp) -> bool
fn reduce_term(&mut self, op_dir: &CompositeOpDir) -> bool
{
if self.stack.is_empty() {
return false;
@@ -687,12 +687,18 @@ impl<'a, R: Read> Parser<'a, R> {
let term = match self.terms.pop() {
Some(term) => term,
_ => return Err(ParserError::IncompleteReduction(self.lexer.line_num,
self.lexer.col_num))
_ => return Err(ParserError::IncompleteReduction(
self.lexer.line_num,
self.lexer.col_num,
))
};
self.terms.push(Term::Clause(Cell::default(), clause_name!("{}"),
vec![Box::new(term)], None));
self.terms.push(Term::Clause(
Cell::default(),
clause_name!("{}"),
vec![Box::new(term)],
None
));
return Ok(true);
}
@@ -738,8 +744,8 @@ impl<'a, R: Read> Parser<'a, R> {
}
}
fn shift_op(&mut self, name: ClauseName, op_dir: CompositeOp) -> Result<bool, ParserError> {
if let Some(OpDesc { pre, inf, post, spec }) = get_desc(name.clone(), op_dir) {
fn shift_op(&mut self, name: ClauseName, op_dir: &CompositeOpDir) -> Result<bool, ParserError> {
if let Some(OpDesc { pre, inf, post, spec }) = get_op_desc(name.clone(), op_dir) {
if (pre > 0 && inf + post > 0) || is_negate!(spec) {
match self.tokens.last().ok_or(ParserError::UnexpectedEOF)? {
// do this when layout hasn't been inserted,
@@ -752,8 +758,12 @@ impl<'a, R: Read> Parser<'a, R> {
let fixity = if inf > 0 { Fixity::In } else { Fixity::Post };
let op_dir_val = op_dir.get(name.clone(), fixity);
self.promote_atom_op(name, inf + post, spec & (XFX | XFY | YFX | YF | XF),
op_dir_val);
self.promote_atom_op(
name,
inf + post,
spec & (XFX | XFY | YFX | YF | XF),
op_dir_val,
);
},
_ => {
self.reduce_op(inf + post);
@@ -764,9 +774,12 @@ impl<'a, R: Read> Parser<'a, R> {
let fixity = if inf > 0 { Fixity::In } else { Fixity::Post };
let op_dir_val = op_dir.get(name.clone(), fixity);
self.promote_atom_op(name, inf + post,
spec & (XFX | XFY | YFX | XF | YF),
op_dir_val);
self.promote_atom_op(
name,
inf + post,
spec & (XFX | XFY | YFX | XF | YF),
op_dir_val,
);
} else {
let op_dir_val = op_dir.get(name.clone(), Fixity::Pre);
self.promote_atom_op(name, pre, spec & (FX | FY | NEGATIVE_SIGN), op_dir_val);
@@ -778,14 +791,16 @@ impl<'a, R: Read> Parser<'a, R> {
}
}
} else {
let op_dir_val = op_dir.get(name.clone(),
if pre + inf == 0 {
Fixity::Post
} else if post + pre == 0 {
Fixity::In
} else {
Fixity::Pre
});
let op_dir_val = op_dir.get(
name.clone(),
if pre + inf == 0 {
Fixity::Post
} else if post + pre == 0 {
Fixity::In
} else {
Fixity::Pre
},
);
self.reduce_op(pre + inf + post); // only one non-zero priority among these.
self.promote_atom_op(name, pre + inf + post, spec, op_dir_val);
@@ -843,7 +858,7 @@ impl<'a, R: Read> Parser<'a, R> {
self.shift(Token::Constant(constr(n)), 0, TERM);
}
fn shift_token(&mut self, token: Token, op_dir: CompositeOp) -> Result<(), ParserError> {
fn shift_token(&mut self, token: Token, op_dir: &CompositeOpDir) -> Result<(), ParserError> {
fn negate_rc<T: NegAssign>(mut t: Rc<T>) -> Rc<T> {
match Rc::get_mut(&mut t) {
Some(t) => {
@@ -909,7 +924,7 @@ impl<'a, R: Read> 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 (priority, spec) = get_desc(clause_name!("|"), op_dir)
let (priority, spec) = get_op_desc(clause_name!("|"), op_dir)
.map(|OpDesc { inf, spec, .. }| (inf, spec))
.unwrap_or((1000, DELIMITER));
@@ -942,7 +957,7 @@ impl<'a, R: Read> Parser<'a, R> {
self.lexer.eof()
}
pub fn read_term(&mut self, op_dir: CompositeOp) -> Result<Term, ParserError>
pub fn read_term(&mut self, op_dir: &CompositeOpDir) -> Result<Term, ParserError>
{
self.tokens = read_tokens(&mut self.lexer)?;
@@ -966,7 +981,7 @@ impl<'a, R: Read> Parser<'a, R> {
}
}
pub fn read(&mut self, op_dir: CompositeOp) -> Result<Vec<Term>, ParserError>
pub fn read(&mut self, op_dir: &CompositeOpDir) -> Result<Vec<Term>, ParserError>
{
let mut terms = Vec::new();