Initial commit.

This commit is contained in:
Mark Thom
2016-10-28 19:53:08 -06:00
parent a8b1d8bd4d
commit 8d1441e20f
11 changed files with 2494 additions and 1 deletions

63
src/l0/ast.rs Normal file
View File

@@ -0,0 +1,63 @@
use std::vec::{Vec};
pub type Var = String;
pub type Atom = String;
#[derive(Debug)]
pub enum TopLevel {
Fact(Term),
Query(Term)
}
#[derive(Debug)]
pub enum Term {
Atom(Atom),
Clause(Atom, Vec<Box<Term>>),
Var(Var)
}
impl Term {
pub fn name(&self) -> &Atom {
match self {
&Term::Atom(ref atom) => atom,
&Term::Var(ref var) => var,
&Term::Clause(ref atom, _) => atom
}
}
pub fn is_variable(&self) -> bool {
if let &Term::Var(_) = self {
return true;
}
return false;
}
}
#[derive(Clone)]
pub enum MachineInstruction {
GetStructure(Atom, usize, usize),
PutStructure(Atom, usize, usize),
SetVariable(usize),
SetValue(usize),
UnifyVariable(usize),
UnifyValue(usize)
}
pub type Program = Vec<MachineInstruction>;
#[derive(Clone, Copy, PartialEq)]
pub enum Addr {
HeapCell(usize),
RegNum(usize)
}
impl Addr {
pub fn heap_offset(&self) -> usize {
match self {
&Addr::HeapCell(hc) => hc,
&Addr::RegNum(reg) => reg
}
}
}

160
src/l0/codegen.rs Normal file
View File

@@ -0,0 +1,160 @@
use l0::ast::{Atom, Term, MachineInstruction, Program, TopLevel, Var};
use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::vec::{Vec};
impl fmt::Display for MachineInstruction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&MachineInstruction::GetStructure(ref a, ref s, ref r) =>
write!(f, "get_structure {}/{}, X{}", a, s, r),
&MachineInstruction::PutStructure(ref a, ref s, ref r) =>
write!(f, "put_structure {}/{}, X{}", a, s, r),
&MachineInstruction::SetVariable(ref r) =>
write!(f, "set_variable X{}", r),
&MachineInstruction::SetValue(ref r) =>
write!(f, "set_value X{}", r),
&MachineInstruction::UnifyVariable(ref r) =>
write!(f, "unify_variable X{}", r),
&MachineInstruction::UnifyValue(ref r) =>
write!(f, "unify_value X{}", r)
}
}
}
enum IntTerm<'a> {
FinishedClause(usize, &'a Atom, &'a Vec<Box<Term>>),
UnfinishedClause(usize, &'a Atom, &'a Vec<Box<Term>>),
FinishedAtom(usize, &'a Atom)
}
pub fn compile_query<'a>(t: &'a Term) -> Program
{
let mut stack : Vec<IntTerm<'a>> = Vec::new();
let mut variable_allocs : HashMap<&Var, (usize, bool)> = HashMap::new();
let mut query : Program = Vec::new();
match t {
&Term::Clause(ref atom, ref terms) => {
stack.push(IntTerm::UnfinishedClause(1, atom, terms));
variable_allocs.insert(atom, (1, true));
},
&Term::Atom(ref atom) => {
query.push(MachineInstruction::PutStructure(atom.clone(), 0, 1));
return query;
},
&Term::Var(_) => {
query.push(MachineInstruction::SetVariable(1));
return query;
},
};
while let Some(int_term) = stack.pop() {
match int_term {
IntTerm::UnfinishedClause(r, atom, terms) => {
stack.push(IntTerm::FinishedClause(r, atom, terms));
let mut counter : usize = r + 1;
for t in terms {
if t.is_variable() && !variable_allocs.contains_key(t.name()) {
variable_allocs.insert(t.name(), (counter, false));
}
counter += 1;
}
counter = r + terms.len();
for t in terms.iter().rev() {
let r = if t.is_variable() {
variable_allocs.get(t.name()).unwrap().0
} else {
counter
};
match t.as_ref() {
&Term::Atom(ref atom) =>
stack.push(IntTerm::FinishedAtom(r, atom)),
&Term::Clause(ref atom, ref terms) =>
stack.push(IntTerm::UnfinishedClause(r, atom, terms)),
_ => {}
};
counter -= 1;
}
},
IntTerm::FinishedAtom(r, atom) =>
query.push(MachineInstruction::PutStructure(atom.clone(), 0, r)),
IntTerm::FinishedClause(r, atom, terms) => {
query.push(MachineInstruction::PutStructure(atom.clone(), terms.len(), r));
let mut counter : usize = r + 1;
for t in terms {
if let &Term::Var(ref var) = t.as_ref() {
let &mut (reg, ref mut seen) = variable_allocs.get_mut(var).unwrap();
if !*seen {
query.push(MachineInstruction::SetVariable(reg));
*seen = true;
} else {
query.push(MachineInstruction::SetValue(reg));
}
} else {
query.push(MachineInstruction::SetValue(counter));
}
counter += 1;
}
}
};
}
query
}
pub fn compile_fact<'a>(t: &'a Term) -> Program {
let mut reg : usize = 2;
let mut queue : VecDeque<(usize, &'a Term)> = VecDeque::new();
let mut variable_allocs : HashMap<&Var, usize> = HashMap::new();
let mut fact : Program = Vec::new();
queue.push_back((1, t));
while let Some(t) = queue.pop_front() {
match t {
(r, &Term::Clause(ref atom, ref terms)) => {
fact.push(MachineInstruction::GetStructure(atom.clone(), terms.len(), r));
let mut counter : usize = reg;
for t in terms {
if t.is_variable() && !variable_allocs.contains_key(t.name()) {
variable_allocs.insert(t.name(), counter);
fact.push(MachineInstruction::UnifyVariable(counter));
counter += 1;
} else if t.is_variable() {
let r = variable_allocs.get(t.name()).unwrap();
fact.push(MachineInstruction::UnifyValue(*r));
} else {
fact.push(MachineInstruction::UnifyVariable(counter));
queue.push_back((counter, t));
counter += 1;
}
}
reg = counter;
},
(r, &Term::Atom(ref atom)) =>
fact.push(MachineInstruction::GetStructure(atom.clone(), 0, r)),
(r, &Term::Var(_)) => {
fact.push(MachineInstruction::UnifyVariable(r));
return fact;
}
};
}
fact
}

30
src/l0/l0_parser.lalrpop Normal file
View File

@@ -0,0 +1,30 @@
use l0::ast::{Atom, Term, TopLevel, Var};
grammar;
pub TopLevel: TopLevel = {
"?-" <t:Term> "." => TopLevel::Query(t),
<t:Term> "." => TopLevel::Fact(t),
};
Atom : Atom = {
r"[a-z][a-z0-9_]*" => <>.trim().to_string(),
};
Var : Var = {
r"[A-Z][a-z0-9_]*" => <>.trim().to_string(),
};
BoxedTerm : Box<Term> = {
<t:Term> => Box::new(t),
};
Term : Term = {
<a:Atom> "(" <ts: (<BoxedTerm> ",")*> <t:BoxedTerm> ")" => {
let mut ts = ts;
ts.push(t);
Term::Clause(a, ts)
},
<Atom> => Term::Atom(<>),
<Var> => Term::Var(<>),
};

1593
src/l0/l0_parser.rs Normal file

File diff suppressed because it is too large Load Diff

240
src/l0/machine.rs Normal file
View File

@@ -0,0 +1,240 @@
use l0::ast::{Addr, Atom, MachineInstruction, Program, Term, TopLevel, Var};
use std::fmt;
use std::vec::{Vec};
#[derive(Clone)]
enum HeapCell {
NamedStr(usize, Atom),
Ref(usize), // these offsets are always in reference to cells on the Heap!
Str(usize),
}
#[derive(Clone, Copy)]
enum MachineMode {
Read,
Write
}
type Heap = Vec<HeapCell>;
type Registers = Vec<HeapCell>;
pub struct MachineState {
h : usize,
s : usize,
pub fail : bool,
heap : Heap,
mode : MachineMode,
pub program : Option<Program>,
registers : Registers
}
impl MachineState {
pub fn new() -> MachineState {
MachineState { h : 0,
s : 0,
fail : false,
heap : Vec::with_capacity(256),
mode : MachineMode::Write,
program : None,
registers : vec![HeapCell::Ref(0); 33] }
}
fn lookup(&self, a: Addr) -> &HeapCell {
match a {
Addr::HeapCell(hc) => &self.heap[hc],
Addr::RegNum(reg) => &self.registers[reg]
}
}
fn deref(&self, a: Addr) -> Addr {
let mut a = a;
loop {
if let &HeapCell::Ref(value) = self.lookup(a) {
if value != a.heap_offset() {
a = Addr::HeapCell(value);
continue;
} else {
return a;
}
}
return a;
};
}
fn bind(&mut self, a: Addr, val: Addr) {
match a {
Addr::RegNum(reg) => self.registers[reg] = HeapCell::Ref(val.heap_offset()),
Addr::HeapCell(hc) => self.heap[hc] = HeapCell::Ref(val.heap_offset()),
};
}
fn unify(&mut self, a1: Addr, a2: Addr) {
let mut pdl : Vec<Addr> = vec![a1, a2];
self.fail = false;
while !(pdl.is_empty() || self.fail) {
let d1 = self.deref(pdl.pop().unwrap());
let d2 = self.deref(pdl.pop().unwrap());
if d1 != d2 {
match (self.lookup(d1), self.lookup(d2)) {
(&HeapCell::Ref(_), _) | (_, &HeapCell::Ref(_)) =>
self.bind(d1, d2),
(&HeapCell::Str(a1), &HeapCell::Str(a2)) => {
let r1 = &self.heap[a1];
let r2 = &self.heap[a2];
if let &HeapCell::NamedStr(n1, ref f1) = r1 {
if let &HeapCell::NamedStr(n2, ref f2) = r2 {
if n1 == n2 && *f1 == *f2 {
for i in 1 .. n1 {
pdl.push(Addr::HeapCell(a1 + i));
pdl.push(Addr::HeapCell(a2 + i));
}
continue;
}
}
}
self.fail = true;
},
_ => self.fail = true,
};
}
}
}
pub fn execute(&mut self, instr: MachineInstruction) {
match instr {
MachineInstruction::GetStructure(name, arity, reg) => {
let addr = self.deref(Addr::RegNum(reg));
match self.lookup(addr) {
&HeapCell::Str(a) => {
let result = &self.heap[a];
if let &HeapCell::NamedStr(named_arity, ref named_str) = result {
if arity == named_arity && name == *named_str {
self.s = a + 1;
self.mode = MachineMode::Read;
} else {
self.fail = true;
}
}
},
&HeapCell::Ref(reg) => {
self.heap.push(HeapCell::Str(self.h + 1));
self.heap.push(HeapCell::NamedStr(arity, name));
let h = self.h;
self.bind(Addr::RegNum(reg), Addr::HeapCell(h));
self.h += 2;
self.mode = MachineMode::Write;
},
_ => {
self.fail = true;
}
};
},
MachineInstruction::PutStructure(name, arity, reg) => {
self.heap.push(HeapCell::Str(self.h + 1));
self.heap.push(HeapCell::NamedStr(arity, name));
self.registers[reg] = self.heap[self.h].clone();
self.h += 2;
},
MachineInstruction::SetVariable(reg) => {
self.heap.push(HeapCell::Ref(self.h));
self.registers[reg] = self.heap[self.h].clone();
self.h += 1;
},
MachineInstruction::SetValue(reg) => {
self.heap.push(self.registers[reg].clone());
self.h += 1;
},
MachineInstruction::UnifyVariable(reg) => {
if self.s < self.h {
match self.mode {
MachineMode::Read => self.registers[reg] = self.heap[self.s].clone(),
MachineMode::Write => {
self.heap.push(HeapCell::Ref(self.h));
self.registers[reg] = self.heap[self.h].clone();
self.h += 1;
}
};
self.s += 1;
} else {
self.fail = true;
}
},
MachineInstruction::UnifyValue(reg) => {
if self.s < self.h {
let s = self.s;
match self.mode {
MachineMode::Read => self.unify(Addr::RegNum(reg), Addr::HeapCell(s)),
MachineMode::Write => {
self.heap.push(self.registers[reg].clone());
self.h += 1;
}
};
self.s += 1;
} else {
self.fail = true;
}
}
}
}
pub fn reset_heap(&mut self) {
let program = self.program.take();
*self = MachineState::new();
self.program = program;
}
pub fn dump_registers_and_heap(&self) {
let mut c = 0;
let printer = |contents, c| {
match contents {
&HeapCell::NamedStr(ref arity, ref atom) => {
println!("{} = NAME({}, {})", c, arity, atom);
},
&HeapCell::Ref(hc) => {
println!("{} = REF({})", c, hc);
},
&HeapCell::Str(hc) => {
println!("{} = STR({})", c, hc);
}
};
};
for contents in &self.registers {
print!("X");
printer(contents, c);
c += 1;
}
println!("");
c = 0;
for contents in &self.heap {
printer(contents, c);
c += 1;
}
}
}

4
src/l0/mod.rs Normal file
View File

@@ -0,0 +1,4 @@
pub mod ast;
pub mod l0_parser;
pub mod codegen;
pub mod machine;

76
src/main.rs Normal file
View File

@@ -0,0 +1,76 @@
mod l0;
use l0::ast::{Atom, Program, Term, TopLevel, Var};
use l0::codegen::{compile_fact, compile_query};
use l0::machine::{MachineState};
use std::io::{self, Write};
fn print_instructions(program : Program) {
for instruction in program {
println!("{:}", instruction);
}
}
fn l0_repl<'a>() {
let mut ms = MachineState::new();
loop {
print!("l0> ");
io::stdout().flush();
let mut buffer = String::new();
io::stdin().read_line(&mut buffer).unwrap();
let result = l0::l0_parser::parse_TopLevel(&*buffer);
if &*buffer == "quit\n" {
break;
} else if &*buffer == "clear\n" {
ms = MachineState::new();
}
match result {
Ok(TopLevel::Fact(fact)) => {
let program = compile_fact(&fact);
ms = MachineState::new();
ms.program = Some(program);
println!("Program stored.");
},
Ok(TopLevel::Query(query)) => {
if let Some(program) = ms.program.clone().take() {
let query = compile_query(&query);
for instruction in query {
ms.execute(instruction);
}
for instruction in program {
ms.execute(instruction);
if ms.fail {
break;
}
}
if ms.fail {
println!("no");
} else {
println!("yes");
}
ms.reset_heap();
} else {
println!("No program to speak of.");
}
},
Err(_) => println!("Grammatical error of some kind!"),
};
}
}
fn main() {
l0_repl();
}