Fix errors, move prolog_parser

This commit is contained in:
Caden Haustein
2021-01-31 12:43:39 -06:00
parent cf5960afad
commit 092f8e6482
11 changed files with 250 additions and 236 deletions

View File

@@ -12,7 +12,7 @@ categories = ["command-line-utilities"]
build = "build.rs" build = "build.rs"
[workspace] [workspace]
members = ["prolog_parser"] members = ["crates/prolog_parser"]
[build-dependencies] [build-dependencies]
indexmap = "1.0.2" indexmap = "1.0.2"
@@ -35,7 +35,7 @@ libc = "0.2.62"
nix = "0.15.0" nix = "0.15.0"
num-rug-adapter = { optional = true, version = "0.1.4" } num-rug-adapter = { optional = true, version = "0.1.4" }
ordered-float = "0.5.0" ordered-float = "0.5.0"
prolog_parser = { path = "./prolog_parser", default-features = false } prolog_parser = { path = "./crates/prolog_parser", default-features = false }
ref_thread_local = "0.0.0" ref_thread_local = "0.0.0"
rug = { version = "1.4.0", optional = true } rug = { version = "1.4.0", optional = true }
rustyline = "7.0.0" rustyline = "7.0.0"

View File

@@ -2,8 +2,8 @@
name = "prolog_parser" name = "prolog_parser"
version = "0.8.68" version = "0.8.68"
authors = ["Mark Thom <markjordanthom@gmail.com>"] authors = ["Mark Thom <markjordanthom@gmail.com>"]
repository = "https://github.com/mthom/prolog_parser" repository = "https://github.com/mthom/scryer-prolog"
description = " An operator precedence parser for rusty-wam, an up and coming ISO Prolog implementation." description = " An operator precedence parser for scryer-prolog, an up and coming ISO Prolog implementation."
license = "BSD-3-Clause" license = "BSD-3-Clause"
[dependencies] [dependencies]

View File

@@ -1,5 +1,5 @@
use rug::{Integer, Rational};
use ordered_float::*; use ordered_float::*;
use rug::{Integer, Rational};
use tabled_rc::*; use tabled_rc::*;
use put_back_n::*; use put_back_n::*;
@@ -26,112 +26,140 @@ pub const MAX_ARITY: usize = 1023;
pub const XFX: u32 = 0x0001; pub const XFX: u32 = 0x0001;
pub const XFY: u32 = 0x0002; pub const XFY: u32 = 0x0002;
pub const YFX: u32 = 0x0004; pub const YFX: u32 = 0x0004;
pub const XF: u32 = 0x0010; pub const XF: u32 = 0x0010;
pub const YF: u32 = 0x0020; pub const YF: u32 = 0x0020;
pub const FX: u32 = 0x0040; pub const FX: u32 = 0x0040;
pub const FY: u32 = 0x0080; pub const FY: u32 = 0x0080;
pub const DELIMITER: u32 = 0x0100; pub const DELIMITER: u32 = 0x0100;
pub const TERM: u32 = 0x1000; pub const TERM: u32 = 0x1000;
pub const LTERM: u32 = 0x3000; pub const LTERM: u32 = 0x3000;
pub const NEGATIVE_SIGN: u32 = 0x0200; pub const NEGATIVE_SIGN: u32 = 0x0200;
#[macro_export] #[macro_export]
macro_rules! clause_name { macro_rules! clause_name {
($name: expr, $tbl: expr) => ( ($name: expr, $tbl: expr) => {
ClauseName::User(TabledRc::new($name, $tbl.clone())) ClauseName::User(TabledRc::new($name, $tbl.clone()))
) ; };
($name: expr) => ( ($name: expr) => {
ClauseName::BuiltIn($name) ClauseName::BuiltIn($name)
) };
} }
#[macro_export] #[macro_export]
macro_rules! atom { macro_rules! atom {
($e:expr, $tbl:expr) => ( ($e:expr, $tbl:expr) => {
Constant::Atom(ClauseName::User(tabled_rc!($e, $tbl)), None) Constant::Atom(ClauseName::User(tabled_rc!($e, $tbl)), None)
); };
($e:expr) => ( ($e:expr) => {
Constant::Atom(clause_name!($e), None) Constant::Atom(clause_name!($e), None)
) };
} }
#[macro_export] #[macro_export]
macro_rules! rc_atom { macro_rules! rc_atom {
($e:expr) => ( ($e:expr) => {
Rc::new(String::from($e)) Rc::new(String::from($e))
) };
} }
macro_rules! is_term { macro_rules! is_term {
($x:expr) => ( ($x & TERM) != 0 ) ($x:expr) => {
($x & TERM) != 0
};
} }
macro_rules! is_lterm { macro_rules! is_lterm {
($x:expr) => ( ($x & LTERM) != 0 ) ($x:expr) => {
($x & LTERM) != 0
};
} }
macro_rules! is_op { 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 { macro_rules! is_negate {
($x:expr) => ( ($x & NEGATIVE_SIGN) != 0 ) ($x:expr) => {
($x & NEGATIVE_SIGN) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_prefix { macro_rules! is_prefix {
($x:expr) => ( $x & (FX | FY) != 0 ) ($x:expr) => {
$x & (FX | FY) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_postfix { macro_rules! is_postfix {
($x:expr) => ( $x & (XF | YF) != 0 ) ($x:expr) => {
$x & (XF | YF) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_infix { macro_rules! is_infix {
($x:expr) => ( ($x & (XFX | XFY | YFX)) != 0 ) ($x:expr) => {
($x & (XFX | XFY | YFX)) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_xfx { macro_rules! is_xfx {
($x:expr) => ( ($x & XFX) != 0 ) ($x:expr) => {
($x & XFX) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_xfy { macro_rules! is_xfy {
($x:expr) => ( ($x & XFY) != 0 ) ($x:expr) => {
($x & XFY) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_yfx { macro_rules! is_yfx {
($x:expr) => ( ($x & YFX) != 0 ) ($x:expr) => {
($x & YFX) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_yf { macro_rules! is_yf {
($x:expr) => ( ($x & YF) != 0 ) ($x:expr) => {
($x & YF) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_xf { macro_rules! is_xf {
($x:expr) => ( ($x & XF) != 0 ) ($x:expr) => {
($x & XF) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_fx { macro_rules! is_fx {
($x:expr) => ( ($x & FX) != 0 ) ($x:expr) => {
($x & FX) != 0
};
} }
#[macro_export] #[macro_export]
macro_rules! is_fy { macro_rules! is_fy {
($x:expr) => ( ($x & FY) != 0 ) ($x:expr) => {
($x & FY) != 0
};
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RegType { pub enum RegType {
Perm(usize), Perm(usize),
Temp(usize) Temp(usize),
} }
impl Default for RegType { impl Default for RegType {
@@ -143,14 +171,14 @@ impl Default for RegType {
impl RegType { impl RegType {
pub fn reg_num(self) -> usize { pub fn reg_num(self) -> usize {
match self { 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 { pub fn is_perm(self) -> bool {
match self { match self {
RegType::Perm(_) => true, RegType::Perm(_) => true,
_ => false _ => false,
} }
} }
} }
@@ -159,7 +187,7 @@ impl fmt::Display for RegType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
&RegType::Perm(val) => write!(f, "Y{}", val), &RegType::Perm(val) => write!(f, "Y{}", val),
&RegType::Temp(val) => write!(f, "X{}", val) &RegType::Temp(val) => write!(f, "X{}", val),
} }
} }
} }
@@ -167,13 +195,13 @@ impl fmt::Display for RegType {
#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum VarReg { pub enum VarReg {
ArgAndNorm(RegType, usize), ArgAndNorm(RegType, usize),
Norm(RegType) Norm(RegType),
} }
impl VarReg { impl VarReg {
pub fn norm(self) -> RegType { pub fn norm(self) -> RegType {
match self { match self {
VarReg::ArgAndNorm(reg, _) | VarReg::Norm(reg) => reg VarReg::ArgAndNorm(reg, _) | VarReg::Norm(reg) => reg,
} }
} }
} }
@@ -183,10 +211,8 @@ impl fmt::Display for VarReg {
match self { match self {
&VarReg::Norm(RegType::Perm(reg)) => write!(f, "Y{}", reg), &VarReg::Norm(RegType::Perm(reg)) => write!(f, "Y{}", reg),
&VarReg::Norm(RegType::Temp(reg)) => write!(f, "X{}", reg), &VarReg::Norm(RegType::Temp(reg)) => write!(f, "X{}", reg),
&VarReg::ArgAndNorm(RegType::Perm(reg), arg) => &VarReg::ArgAndNorm(RegType::Perm(reg), arg) => write!(f, "Y{} A{}", reg, arg),
write!(f, "Y{} A{}", reg, arg), &VarReg::ArgAndNorm(RegType::Temp(reg), arg) => write!(f, "X{} A{}", reg, arg),
&VarReg::ArgAndNorm(RegType::Temp(reg), arg) =>
write!(f, "X{} A{}", reg, arg)
} }
} }
} }
@@ -199,28 +225,30 @@ impl Default for VarReg {
#[macro_export] #[macro_export]
macro_rules! temp_v { macro_rules! temp_v {
($x:expr) => ( ($x:expr) => {
RegType::Temp($x) RegType::Temp($x)
) };
} }
#[macro_export] #[macro_export]
macro_rules! perm_v { macro_rules! perm_v {
($x:expr) => ( ($x:expr) => {
RegType::Perm($x) RegType::Perm($x)
) };
} }
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum GenContext { pub enum GenContext {
Head, Mid(usize), Last(usize) // Mid & Last: chunk_num Head,
Mid(usize),
Last(usize), // Mid & Last: chunk_num
} }
impl GenContext { impl GenContext {
pub fn chunk_num(self) -> usize { pub fn chunk_num(self) -> usize {
match self { match self {
GenContext::Head => 0, GenContext::Head => 0,
GenContext::Mid(cn) | GenContext::Last(cn) => cn GenContext::Mid(cn) | GenContext::Last(cn) => cn,
} }
} }
} }
@@ -251,18 +279,22 @@ pub type OpDir = HashMap<OpDirKey, OpDirValue>;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct MachineFlags { pub struct MachineFlags {
pub double_quotes: DoubleQuotes pub double_quotes: DoubleQuotes,
} }
impl Default for MachineFlags { impl Default for MachineFlags {
fn default() -> Self { fn default() -> Self {
MachineFlags { double_quotes: DoubleQuotes::default() } MachineFlags {
double_quotes: DoubleQuotes::default(),
}
} }
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum DoubleQuotes { pub enum DoubleQuotes {
Atom, Chars, Codes Atom,
Chars,
Codes,
} }
impl DoubleQuotes { impl DoubleQuotes {
@@ -301,18 +333,30 @@ pub fn default_op_dir() -> OpDir {
let module_name = clause_name!("builtins"); let module_name = clause_name!("builtins");
let mut op_dir = OpDir::new(); let mut op_dir = OpDir::new();
op_dir.insert((clause_name!(":-"), Fixity::In), OpDirValue::new(XFX, 1200, module_name.clone())); op_dir.insert(
op_dir.insert((clause_name!(":-"), Fixity::Pre), OpDirValue::new(FX, 1200, module_name.clone())); (clause_name!(":-"), Fixity::In),
op_dir.insert((clause_name!("?-"), Fixity::Pre), OpDirValue::new(FX, 1200, module_name.clone())); OpDirValue::new(XFX, 1200, module_name.clone()),
op_dir.insert((clause_name!(","), Fixity::In), OpDirValue::new(XFY, 1000, 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 op_dir
} }
#[derive(Debug, Clone)] #[derive(PartialEq, Debug, Clone)]
pub enum ArithmeticError { pub enum ArithmeticError {
NonEvaluableFunctor(Constant, usize), NonEvaluableFunctor(Constant, usize),
UninstantiatedVar UninstantiatedVar,
} }
#[derive(Debug)] #[derive(Debug)]
@@ -342,80 +386,52 @@ pub enum ParserError {
NonPrologChar(usize, usize), NonPrologChar(usize, usize),
ParseBigInt(usize, usize), ParseBigInt(usize, usize),
ParseFloat(usize, usize), ParseFloat(usize, usize),
Utf8Error(usize, usize) Utf8Error(usize, usize),
} }
impl ParserError { impl ParserError {
pub fn line_and_col_num(&self) -> Option<(usize, usize)> { pub fn line_and_col_num(&self) -> Option<(usize, usize)> {
match self { match self {
&ParserError::BackQuotedString(line_num, col_num) &ParserError::BackQuotedString(line_num, col_num)
| &ParserError::UnexpectedChar(_, line_num, col_num) | &ParserError::UnexpectedChar(_, line_num, col_num)
| &ParserError::IncompleteReduction(line_num, col_num) | &ParserError::IncompleteReduction(line_num, col_num)
| &ParserError::MissingQuote(line_num, col_num) | &ParserError::MissingQuote(line_num, col_num)
| &ParserError::NonPrologChar(line_num, col_num) | &ParserError::NonPrologChar(line_num, col_num)
| &ParserError::ParseBigInt(line_num, col_num) | &ParserError::ParseBigInt(line_num, col_num)
| &ParserError::ParseFloat(line_num, col_num) | &ParserError::ParseFloat(line_num, col_num)
| &ParserError::Utf8Error(line_num, col_num) => | &ParserError::Utf8Error(line_num, col_num) => Some((line_num, col_num)),
Some((line_num, col_num)), _ => None,
_ =>
None
} }
} }
pub fn as_str(&self) -> &'static str { pub fn as_str(&self) -> &'static str {
match self { match self {
&ParserError::Arithmetic(..) => &ParserError::Arithmetic(..) => "arithmetic_error",
"arithmetic_error", &ParserError::BackQuotedString(..) => "back_quoted_string",
&ParserError::BackQuotedString(..) => &ParserError::BadPendingByte => "bad_pending_byte",
"back_quoted_string", &ParserError::UnexpectedChar(..) => "unexpected_char",
&ParserError::BadPendingByte => &ParserError::UnexpectedEOF => "unexpected_end_of_file",
"bad_pending_byte", &ParserError::ExpectedRel => "expected_relation",
&ParserError::UnexpectedChar(..) => &ParserError::ExpectedTopLevelTerm => "expected_atom_or_cons_or_clause",
"unexpected_char", &ParserError::InadmissibleFact => "inadmissible_fact",
&ParserError::UnexpectedEOF => &ParserError::InadmissibleQueryTerm => "inadmissible_query_term",
"unexpected_end_of_file", &ParserError::IncompleteReduction(..) => "incomplete_reduction",
&ParserError::ExpectedRel => &ParserError::InconsistentEntry => "inconsistent_entry",
"expected_relation", &ParserError::InvalidDoubleQuotesDecl => "invalid_double_quotes_declaration",
&ParserError::ExpectedTopLevelTerm => &ParserError::InvalidHook => "invalid_hook",
"expected_atom_or_cons_or_clause", &ParserError::InvalidModuleDecl => "invalid_module_declaration",
&ParserError::InadmissibleFact => &ParserError::InvalidModuleExport => "invalid_module_export",
"inadmissible_fact", &ParserError::InvalidModuleResolution => "invalid_module_resolution",
&ParserError::InadmissibleQueryTerm => &ParserError::InvalidRuleHead => "invalid_head_of_rule",
"inadmissible_query_term", &ParserError::InvalidUseModuleDecl => "invalid_use_module_declaration",
&ParserError::IncompleteReduction(..) => &ParserError::InvalidSingleQuotedCharacter(..) => "invalid_single_quoted_character",
"incomplete_reduction", &ParserError::IO(_) => "input_output_error",
&ParserError::InconsistentEntry => &ParserError::MissingQuote(..) => "missing_quote",
"inconsistent_entry", &ParserError::NonPrologChar(..) => "non_prolog_character",
&ParserError::InvalidDoubleQuotesDecl => &ParserError::ParseBigInt(..) => "cannot_parse_big_int",
"invalid_double_quotes_declaration", &ParserError::ParseFloat(..) => "cannot_parse_float",
&ParserError::InvalidHook => &ParserError::Utf8Error(..) => "utf8_conversion_error",
"invalid_hook", &ParserError::CannotParseCyclicTerm => "cannot_parse_cyclic_term",
&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"
} }
} }
} }
@@ -442,10 +458,11 @@ impl From<&IOError> for ParserError {
} }
} }
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum Fixity { pub enum Fixity {
In, Post, Pre In,
Post,
Pre,
} }
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
@@ -518,28 +535,21 @@ pub enum Constant {
impl fmt::Display for Constant { impl fmt::Display for Constant {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
&Constant::Atom(ref atom, _) => &Constant::Atom(ref atom, _) => {
if atom.as_str().chars().any(|c| "`.$'\" ".contains(c)) { if atom.as_str().chars().any(|c| "`.$'\" ".contains(c)) {
write!(f, "'{}'", atom.as_str()) write!(f, "'{}'", atom.as_str())
} else { } else {
write!(f, "{}", atom.as_str()) write!(f, "{}", atom.as_str())
}, }
&Constant::Char(c) => }
write!(f, "'{}'", c as u32), &Constant::Char(c) => write!(f, "'{}'", c as u32),
&Constant::EmptyList => &Constant::EmptyList => write!(f, "[]"),
write!(f, "[]"), &Constant::Fixnum(n) => write!(f, "{}", n),
&Constant::Fixnum(n) => &Constant::Integer(ref n) => write!(f, "{}", n),
write!(f, "{}", n), &Constant::Rational(ref n) => write!(f, "{}", n),
&Constant::Integer(ref n) => &Constant::Float(ref n) => write!(f, "{}", n),
write!(f, "{}", n), &Constant::String(ref s) => write!(f, "\"{}\"", &s),
&Constant::Rational(ref n) => &Constant::Usize(integer) => write!(f, "u{}", integer),
write!(f, "{}", n),
&Constant::Float(ref n) =>
write!(f, "{}", n),
&Constant::String(ref s) =>
write!(f, "\"{}\"", &s),
&Constant::Usize(integer) =>
write!(f, "u{}", integer),
} }
} }
} }
@@ -548,37 +558,27 @@ impl PartialEq for Constant {
fn eq(&self, other: &Constant) -> bool { fn eq(&self, other: &Constant) -> bool {
match (self, other) { match (self, other) {
(&Constant::Atom(ref atom, _), &Constant::Char(c)) (&Constant::Atom(ref atom, _), &Constant::Char(c))
| (&Constant::Char(c), &Constant::Atom(ref atom, _)) => { | (&Constant::Char(c), &Constant::Atom(ref atom, _)) => {
atom.is_char() && Some(c) == atom.as_str().chars().next() atom.is_char() && Some(c) == atom.as_str().chars().next()
}, }
(&Constant::Atom(ref a1, _), &Constant::Atom(ref a2, _)) => (&Constant::Atom(ref a1, _), &Constant::Atom(ref a2, _)) => a1.as_str() == a2.as_str(),
a1.as_str() == a2.as_str(), (&Constant::Char(c1), &Constant::Char(c2)) => c1 == c2,
(&Constant::Char(c1), &Constant::Char(c2)) => (&Constant::Fixnum(n1), &Constant::Fixnum(n2)) => n1 == n2,
c1 == c2, (&Constant::Fixnum(n1), &Constant::Integer(ref n2))
(&Constant::Fixnum(n1), &Constant::Fixnum(n2)) => | (&Constant::Integer(ref n2), &Constant::Fixnum(n1)) => {
n1 == n2,
(&Constant::Fixnum(n1), &Constant::Integer(ref n2)) |
(&Constant::Integer(ref n2), &Constant::Fixnum(n1)) => {
if let Some(n2) = n2.to_isize() { if let Some(n2) = n2.to_isize() {
n1 == n2 n1 == n2
} else { } else {
false false
} }
} }
(&Constant::Integer(ref n1), &Constant::Integer(ref n2)) => (&Constant::Integer(ref n1), &Constant::Integer(ref n2)) => n1 == n2,
n1 == n2, (&Constant::Rational(ref n1), &Constant::Rational(ref n2)) => n1 == n2,
(&Constant::Rational(ref n1), &Constant::Rational(ref n2)) => (&Constant::Float(ref n1), &Constant::Float(ref n2)) => n1 == n2,
n1 == n2, (&Constant::String(ref s1), &Constant::String(ref s2)) => &s1 == &s2,
(&Constant::Float(ref n1), &Constant::Float(ref n2)) => (&Constant::EmptyList, &Constant::EmptyList) => true,
n1 == n2, (&Constant::Usize(u1), &Constant::Usize(u2)) => u1 == u2,
(&Constant::String(ref s1), &Constant::String(ref s2)) => { _ => false,
&s1 == &s2
}
(&Constant::EmptyList, &Constant::EmptyList) =>
true,
(&Constant::Usize(u1), &Constant::Usize(u2)) =>
u1 == u2,
_ => false
} }
} }
} }
@@ -589,7 +589,7 @@ impl Constant {
pub fn to_atom(self) -> Option<ClauseName> { pub fn to_atom(self) -> Option<ClauseName> {
match self { match self {
Constant::Atom(a, _) => Some(a.defrock_brackets()), Constant::Atom(a, _) => Some(a.defrock_brackets()),
_ => None _ => None,
} }
} }
} }
@@ -597,7 +597,7 @@ impl Constant {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum ClauseName { pub enum ClauseName {
BuiltIn(&'static str), BuiltIn(&'static str),
User(TabledRc<Atom>) User(TabledRc<Atom>),
} }
impl fmt::Display for ClauseName { impl fmt::Display for ClauseName {
@@ -644,10 +644,12 @@ impl ClauseName {
match self { match self {
&ClauseName::User(ref name) => { &ClauseName::User(ref name) => {
let module = name.owning_module(); let module = name.owning_module();
ClauseName::User(TabledRc { atom: module.clone(), ClauseName::User(TabledRc {
table: TabledData::new(module) }) atom: module.clone(),
}, table: TabledData::new(module),
_ => clause_name!("user") })
}
_ => clause_name!("user"),
} }
} }
@@ -655,7 +657,7 @@ impl ClauseName {
pub fn to_rc(&self) -> Rc<String> { pub fn to_rc(&self) -> Rc<String> {
match self { match self {
&ClauseName::BuiltIn(s) => Rc::new(s.to_string()), &ClauseName::BuiltIn(s) => Rc::new(s.to_string()),
&ClauseName::User(ref rc) => rc.inner() &ClauseName::User(ref rc) => rc.inner(),
} }
} }
@@ -688,9 +690,7 @@ impl ClauseName {
false false
} }
} }
ClauseName::User(ref name) => { ClauseName::User(ref name) => other.has_table(&name.table),
other.has_table(&name.table)
}
} }
} }
@@ -698,7 +698,7 @@ impl ClauseName {
pub fn as_str(&self) -> &str { pub fn as_str(&self) -> &str {
match self { match self {
&ClauseName::BuiltIn(s) => s, &ClauseName::BuiltIn(s) => s,
&ClauseName::User(ref name) => name.as_ref() &ClauseName::User(ref name) => name.as_ref(),
} }
} }
@@ -710,17 +710,17 @@ impl ClauseName {
pub fn defrock_brackets(self) -> Self { pub fn defrock_brackets(self) -> Self {
fn defrock_brackets(s: &str) -> &str { fn defrock_brackets(s: &str) -> &str {
if s.starts_with('(') && s.ends_with(')') { if s.starts_with('(') && s.ends_with(')') {
&s[1 .. s.len() - 1] &s[1..s.len() - 1]
} else { } else {
s s
} }
} }
match self { match self {
ClauseName::BuiltIn(s) => ClauseName::BuiltIn(s) => ClauseName::BuiltIn(defrock_brackets(s)),
ClauseName::BuiltIn(defrock_brackets(s)), ClauseName::User(s) => {
ClauseName::User(s) =>
ClauseName::User(tabled_rc!(defrock_brackets(s.as_str()).to_owned(), s.table)) ClauseName::User(tabled_rc!(defrock_brackets(s.as_str()).to_owned(), s.table))
}
} }
} }
} }
@@ -735,10 +735,15 @@ impl AsRef<str> for ClauseName {
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum Term { pub enum Term {
AnonVar, 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>), Cons(Cell<RegType>, Box<Term>, Box<Term>),
Constant(Cell<RegType>, Constant), Constant(Cell<RegType>, Constant),
Var(Cell<VarReg>, Rc<Var>) Var(Cell<VarReg>, Rc<Var>),
} }
impl Term { impl Term {
@@ -746,30 +751,29 @@ impl Term {
match self { match self {
&Term::Clause(_, _, _, ref spec) => spec.clone(), &Term::Clause(_, _, _, ref spec) => spec.clone(),
&Term::Constant(_, Constant::Atom(_, ref spec)) => spec.clone(), &Term::Constant(_, Constant::Atom(_, ref spec)) => spec.clone(),
_ => None _ => None,
} }
} }
pub fn to_constant(self) -> Option<Constant> { pub fn to_constant(self) -> Option<Constant> {
match self { match self {
Term::Constant(_, c) => Some(c), Term::Constant(_, c) => Some(c),
_ => None _ => None,
} }
} }
pub fn first_arg(&self) -> Option<&Term> { pub fn first_arg(&self) -> Option<&Term> {
match self { match self {
&Term::Clause(_, _, ref terms, _) => &Term::Clause(_, _, ref terms, _) => terms.first().map(|bt| bt.as_ref()),
terms.first().map(|bt| bt.as_ref()), _ => None,
_ => None
} }
} }
pub fn set_name(&mut self, new_name: ClauseName) { pub fn set_name(&mut self, new_name: ClauseName) {
match self { match self {
Term::Constant(_, Constant::Atom(ref mut atom, _)) Term::Constant(_, Constant::Atom(ref mut atom, _))
| Term::Clause(_, ref mut atom, ..) => { | Term::Clause(_, ref mut atom, ..) => {
*atom = new_name; *atom = new_name;
} }
_ => {} _ => {}
} }
@@ -777,16 +781,17 @@ impl Term {
pub fn name(&self) -> Option<ClauseName> { pub fn name(&self) -> Option<ClauseName> {
match self { match self {
&Term::Constant(_, Constant::Atom(ref atom, _)) &Term::Constant(_, Constant::Atom(ref atom, _)) | &Term::Clause(_, ref atom, ..) => {
| &Term::Clause(_, ref atom, ..) => Some(atom.clone()), Some(atom.clone())
_ => None }
_ => None,
} }
} }
pub fn arity(&self) -> usize { pub fn arity(&self) -> usize {
match self { match self {
&Term::Clause(_, _, ref child_terms, ..) => child_terms.len(), &Term::Clause(_, _, ref child_terms, ..) => child_terms.len(),
_ => 0 _ => 0,
} }
} }
} }
@@ -794,39 +799,41 @@ impl Term {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct CompositeOp<'a, 'b> { pub struct CompositeOp<'a, 'b> {
pub op_dir: &'a OpDir, pub op_dir: &'a OpDir,
pub static_op_dir: Option<&'b OpDir> pub static_op_dir: Option<&'b OpDir>,
} }
#[macro_export] #[macro_export]
macro_rules! composite_op { macro_rules! composite_op {
($include_machine_p:expr, $op_dir:expr, $machine_op_dir:expr) => ( ($include_machine_p:expr, $op_dir:expr, $machine_op_dir:expr) => {
CompositeOp { op_dir: $op_dir, CompositeOp {
static_op_dir: if !$include_machine_p { op_dir: $op_dir,
Some($machine_op_dir) static_op_dir: if !$include_machine_p {
} else { Some($machine_op_dir)
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 { } else {
None None
}; },
}
};
($op_dir:expr) => {
CompositeOp {
op_dir: $op_dir,
static_op_dir: None,
}
};
}
entry.or_else(move || self.op_dir.get(&(name, fixity))) impl<'a, 'b> CompositeOp<'a, 'b> {
.cloned() #[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()
} }
} }

View File

@@ -44,25 +44,33 @@ fn simple_char() -> Result<(), ParserError> {
#[test] #[test]
fn char_with_meta_seq() -> Result<(), ParserError> { fn char_with_meta_seq() -> Result<(), ParserError> {
let tokens = read_all_tokens(r#"'\\' '\'' '\"' '\`' "#)?; // use literal string so \ are escaped let tokens = read_all_tokens(r#"'\\' '\'' '\"' '\`' "#)?; // use literal string so \ are escaped
assert_eq!(tokens, [Token::Constant(Constant::Char('\\')), assert_eq!(
Token::Constant(Constant::Char('\'')), tokens,
Token::Constant(Constant::Char('"')), [
Token::Constant(Constant::Char('`'))]); Token::Constant(Constant::Char('\\')),
Token::Constant(Constant::Char('\'')),
Token::Constant(Constant::Char('"')),
Token::Constant(Constant::Char('`'))
]
);
Ok(()) Ok(())
} }
#[test] #[test]
fn char_with_control_seq() -> Result<(), ParserError> { fn char_with_control_seq() -> Result<(), ParserError> {
let tokens = read_all_tokens(r"'\a' '\b' '\r' '\f' '\t' '\n' '\v' ")?; let tokens = read_all_tokens(r"'\a' '\b' '\r' '\f' '\t' '\n' '\v' ")?;
assert_eq!(tokens, [ assert_eq!(
Token::Constant(Constant::Char('\u{07}')), tokens,
Token::Constant(Constant::Char('\u{08}')), [
Token::Constant(Constant::Char('\r')), Token::Constant(Constant::Char('\u{07}')),
Token::Constant(Constant::Char('\u{0c}')), Token::Constant(Constant::Char('\u{08}')),
Token::Constant(Constant::Char('\t')), Token::Constant(Constant::Char('\r')),
Token::Constant(Constant::Char('\n')), Token::Constant(Constant::Char('\u{0c}')),
Token::Constant(Constant::Char('\u{0b}')), Token::Constant(Constant::Char('\t')),
]); Token::Constant(Constant::Char('\n')),
Token::Constant(Constant::Char('\u{0b}')),
]
);
Ok(()) Ok(())
} }
@@ -101,7 +109,6 @@ fn empty() -> Result<(), ParserError> {
#[test] #[test]
fn comment_then_eof() -> Result<(), ParserError> { fn comment_then_eof() -> Result<(), ParserError> {
let tokens = read_all_tokens("% only a comment")?; assert!(read_all_tokens("% only a comment").is_err());
assert_eq!(tokens, [Token::End]);
Ok(()) Ok(())
} }