optimized up to section 5.11
This commit is contained in:
@@ -3,7 +3,8 @@ use prolog::iterators::{FactIterator, QueryIterator};
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::cmp::max;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::vec::Vec;
|
||||
|
||||
trait CompilationTarget<'a> {
|
||||
@@ -244,6 +245,239 @@ impl<'a> TermMarker<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum IntIndex {
|
||||
External(usize), Fail, Internal(usize)
|
||||
}
|
||||
|
||||
impl Into<usize> for IntIndex {
|
||||
fn into(self) -> usize {
|
||||
match self {
|
||||
IntIndex::Internal(i) => i,
|
||||
_ => 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CodeOffsets {
|
||||
constants: HashMap<Constant, ThirdLevelIndex>,
|
||||
lists: ThirdLevelIndex,
|
||||
structures: HashMap<(Atom, usize), ThirdLevelIndex>
|
||||
}
|
||||
|
||||
impl CodeOffsets {
|
||||
fn new() -> Self {
|
||||
CodeOffsets {
|
||||
constants: HashMap::new(),
|
||||
lists: Vec::new(),
|
||||
structures: HashMap::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn cap_choice_seq_with_trust(prelude: &mut ThirdLevelIndex) {
|
||||
prelude.last_mut().map(|instr| {
|
||||
match instr {
|
||||
&mut IndexedChoiceInstruction::Retry(i) =>
|
||||
*instr = IndexedChoiceInstruction::Trust(i),
|
||||
_ => {}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
fn add_index(is_first_index: bool, index: usize) -> IndexedChoiceInstruction {
|
||||
if is_first_index {
|
||||
IndexedChoiceInstruction::Try(index)
|
||||
} else {
|
||||
IndexedChoiceInstruction::Retry(index)
|
||||
}
|
||||
}
|
||||
|
||||
fn index_term(&mut self, first_arg: &Term, index: usize) {
|
||||
match first_arg {
|
||||
&Term::Clause(_, ref name, ref terms) => {
|
||||
let code = self.structures.entry((name.clone(), terms.len()))
|
||||
.or_insert(Vec::new());
|
||||
|
||||
let is_initial_index = code.is_empty();
|
||||
code.push(Self::add_index(is_initial_index, index));
|
||||
},
|
||||
&Term::Cons(_, _, _) => {
|
||||
let is_initial_index = self.lists.is_empty();
|
||||
self.lists.push(Self::add_index(is_initial_index, index));
|
||||
},
|
||||
&Term::Constant(_, ref constant) => {
|
||||
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));
|
||||
},
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
fn second_level_index<Index>(indices: HashMap<Index, ThirdLevelIndex>,
|
||||
prelude: &mut CodeDeque)
|
||||
-> HashMap<Index, IntIndex>
|
||||
where Index: Eq + Hash
|
||||
{
|
||||
let mut index_locs = HashMap::new();
|
||||
|
||||
for (key, mut code) in indices.into_iter() {
|
||||
if code.len() > 1 {
|
||||
index_locs.insert(key, IntIndex::Internal(prelude.len()));
|
||||
Self::cap_choice_seq_with_trust(&mut code);
|
||||
prelude.extend(code.into_iter().map(|code| Line::from(code)));
|
||||
} else {
|
||||
code.first().map(|i| {
|
||||
index_locs.insert(key, IntIndex::External(i.offset()));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
index_locs
|
||||
}
|
||||
|
||||
fn no_indices(&self) -> bool {
|
||||
let no_constants = self.constants.is_empty();
|
||||
let no_structures = self.structures.is_empty();
|
||||
let no_lists = self.lists.is_empty();
|
||||
|
||||
no_constants && no_structures && no_lists
|
||||
}
|
||||
|
||||
fn flatten_index<Index>(index: HashMap<Index, IntIndex>, len: usize)
|
||||
-> HashMap<Index, usize>
|
||||
where Index: Eq + Hash
|
||||
{
|
||||
let mut flattened_index = HashMap::new();
|
||||
|
||||
for (key, int_index) in index.into_iter() {
|
||||
match int_index {
|
||||
IntIndex::External(offset) => {
|
||||
flattened_index.insert(key, offset + len + 1);
|
||||
},
|
||||
IntIndex::Internal(offset) => {
|
||||
flattened_index.insert(key, offset + 1);
|
||||
},
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
flattened_index
|
||||
}
|
||||
|
||||
fn switch_on_constant(con_ind: HashMap<Constant, ThirdLevelIndex>,
|
||||
prelude: &mut CodeDeque)
|
||||
-> IntIndex
|
||||
{
|
||||
let con_ind = Self::second_level_index(con_ind, prelude);
|
||||
|
||||
if con_ind.len() > 1 {
|
||||
let index = Self::flatten_index(con_ind, prelude.len());
|
||||
let instr = IndexingInstruction::SwitchOnConstant(index.len(), index);
|
||||
|
||||
prelude.push_front(Line::from(instr));
|
||||
|
||||
IntIndex::Internal(1)
|
||||
} else {
|
||||
con_ind.values().next()
|
||||
.map(|i| *i)
|
||||
.unwrap_or(IntIndex::Fail)
|
||||
}
|
||||
}
|
||||
|
||||
fn switch_on_list(mut lists: ThirdLevelIndex, prelude: &mut CodeDeque) -> IntIndex
|
||||
{
|
||||
if lists.len() > 1 {
|
||||
Self::cap_choice_seq_with_trust(&mut lists);
|
||||
prelude.extend(lists.into_iter().map(|i| Line::from(i)));
|
||||
IntIndex::Internal(0)
|
||||
} else {
|
||||
lists.first()
|
||||
.map(|i| IntIndex::External(i.offset()))
|
||||
.unwrap_or(IntIndex::Fail)
|
||||
}
|
||||
}
|
||||
|
||||
fn switch_on_structure(str_ind: HashMap<(Atom, usize), ThirdLevelIndex>,
|
||||
prelude: &mut CodeDeque)
|
||||
-> IntIndex
|
||||
{
|
||||
let str_ind = Self::second_level_index(str_ind, prelude);
|
||||
|
||||
if str_ind.len() > 1 {
|
||||
let index = Self::flatten_index(str_ind, prelude.len());
|
||||
let instr = IndexingInstruction::SwitchOnStructure(index.len(), index);
|
||||
|
||||
prelude.push_front(Line::from(instr));
|
||||
|
||||
IntIndex::Internal(1)
|
||||
} else {
|
||||
str_ind.values().next()
|
||||
.map(|i| *i)
|
||||
.unwrap_or(IntIndex::Fail)
|
||||
}
|
||||
}
|
||||
|
||||
fn add_indices(self, code: &mut Code, mut code_body: Code)
|
||||
{
|
||||
if self.no_indices() {
|
||||
*code = code_body;
|
||||
return;
|
||||
}
|
||||
|
||||
let mut prelude = VecDeque::new();
|
||||
|
||||
let lst_step = Self::switch_on_list(self.lists, &mut prelude);
|
||||
let lst_offset = prelude.len();
|
||||
|
||||
let str_step = Self::switch_on_structure(self.structures, &mut prelude);
|
||||
let con_step = Self::switch_on_constant(self.constants, &mut prelude);
|
||||
|
||||
let prelude_length = prelude.len();
|
||||
|
||||
for (index, line) in prelude.iter_mut().enumerate() {
|
||||
match line {
|
||||
&mut Line::IndexedChoice(IndexedChoiceInstruction::Try(ref mut i))
|
||||
| &mut Line::IndexedChoice(IndexedChoiceInstruction::Retry(ref mut i))
|
||||
| &mut Line::IndexedChoice(IndexedChoiceInstruction::Trust(ref mut i)) =>
|
||||
*i += prelude_length - index,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let str_step = match str_step {
|
||||
IntIndex::External(o) => o + prelude.len() + 1,
|
||||
IntIndex::Fail => 0,
|
||||
IntIndex::Internal(_) => match con_step {
|
||||
IntIndex::Internal(_) => 2,
|
||||
_ => 1
|
||||
}
|
||||
};
|
||||
let con_step = match con_step {
|
||||
IntIndex::External(offset) => offset + prelude.len() + 1,
|
||||
IntIndex::Fail => 0,
|
||||
IntIndex::Internal(offset) => offset,
|
||||
};
|
||||
let lst_step = match lst_step {
|
||||
IntIndex::External(o) => o + prelude.len() + 1,
|
||||
IntIndex::Fail => 0,
|
||||
IntIndex::Internal(_) => prelude.len() - lst_offset + 1
|
||||
};
|
||||
|
||||
let switch_instr = IndexingInstruction::SwitchOnTerm(prelude.len() + 1,
|
||||
con_step,
|
||||
lst_step,
|
||||
str_step);
|
||||
|
||||
prelude.push_front(Line::from(switch_instr));
|
||||
|
||||
*code = Vec::from(prelude);
|
||||
code.append(&mut code_body);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
enum VarStatus {
|
||||
New, Old, Permanent(usize)
|
||||
@@ -643,7 +877,7 @@ impl<'a> CodeGenerator<'a> {
|
||||
Self::add_conditional_call(&mut body, p1, perm_vars);
|
||||
|
||||
body = clauses.iter().enumerate()
|
||||
.map(|(i, ref term)| {
|
||||
.map(|(i, term)| {
|
||||
let num_vars = Self::vars_above_threshold(&vs, i+1);
|
||||
self.compile_internal_query(term, num_vars)
|
||||
})
|
||||
@@ -705,13 +939,13 @@ impl<'a> CodeGenerator<'a> {
|
||||
self.update_var_count(term.breadth_first_iter());
|
||||
|
||||
let mut code = Vec::new();
|
||||
|
||||
|
||||
if term.is_clause() {
|
||||
let mut compiled_fact = self.compile_target(term, false);
|
||||
let mut compiled_fact = self.compile_target(term, false);
|
||||
Self::mark_unsafe_fact_vars(&mut compiled_fact, self.vars());
|
||||
code.push(Line::Fact(compiled_fact));
|
||||
}
|
||||
|
||||
|
||||
let proceed = Line::Control(ControlInstruction::Proceed);
|
||||
|
||||
code.push(proceed);
|
||||
@@ -725,11 +959,11 @@ impl<'a> CodeGenerator<'a> {
|
||||
|
||||
let mut code = Vec::new();
|
||||
|
||||
if term.is_clause() {
|
||||
if term.is_clause() {
|
||||
let compiled_query = Line::Query(self.compile_target(term, false));
|
||||
code.push(compiled_query);
|
||||
}
|
||||
|
||||
|
||||
Self::add_conditional_call(&mut code, term, index);
|
||||
|
||||
code
|
||||
@@ -741,19 +975,45 @@ impl<'a> CodeGenerator<'a> {
|
||||
|
||||
let mut code = Vec::new();
|
||||
|
||||
if term.is_clause() {
|
||||
if term.is_clause() {
|
||||
let compiled_query = Line::Query(self.compile_target(term, false));
|
||||
code.push(compiled_query);
|
||||
}
|
||||
|
||||
|
||||
Self::add_conditional_call(&mut code, term, 0);
|
||||
|
||||
code
|
||||
}
|
||||
|
||||
pub fn compile_predicate(&mut self, clauses: &'a Vec<PredicateClause>) -> Code
|
||||
fn split_predicate(clauses: &Vec<PredicateClause>) -> Vec<(usize, usize)>
|
||||
{
|
||||
let mut code = Vec::new();
|
||||
let mut subseqs = Vec::new();
|
||||
let mut left_index = 0;
|
||||
|
||||
for (right_index, clause) in clauses.iter().enumerate() {
|
||||
if let Some(&Term::Var(_, _)) = clause.first_arg() {
|
||||
if left_index < right_index {
|
||||
subseqs.push((left_index, right_index));
|
||||
}
|
||||
|
||||
subseqs.push((right_index, right_index + 1));
|
||||
left_index = right_index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if left_index < clauses.len() {
|
||||
subseqs.push((left_index, clauses.len()));
|
||||
}
|
||||
|
||||
subseqs
|
||||
}
|
||||
|
||||
fn compile_pred_subseq(&mut self, clauses: &'a [PredicateClause]) -> Code
|
||||
{
|
||||
let mut code_body = Vec::new();
|
||||
let mut code_offsets = CodeOffsets::new();
|
||||
|
||||
let multi_clause = clauses.len() > 1;
|
||||
|
||||
for (i, clause) in clauses.iter().enumerate() {
|
||||
self.marker.reset();
|
||||
@@ -765,14 +1025,50 @@ impl<'a> CodeGenerator<'a> {
|
||||
self.compile_rule(rule)
|
||||
};
|
||||
|
||||
let choice = match i {
|
||||
0 => ChoiceInstruction::TryMeElse(clause_code.len() + 1),
|
||||
_ if i == clauses.len() - 1 => ChoiceInstruction::TrustMe,
|
||||
_ => ChoiceInstruction::RetryMeElse(clause_code.len() + 1)
|
||||
};
|
||||
if multi_clause {
|
||||
let choice = match i {
|
||||
0 => ChoiceInstruction::TryMeElse(clause_code.len() + 1),
|
||||
_ if i == clauses.len() - 1 => ChoiceInstruction::TrustMe,
|
||||
_ => ChoiceInstruction::RetryMeElse(clause_code.len() + 1)
|
||||
};
|
||||
|
||||
code.push(Line::Choice(choice));
|
||||
code.append(&mut clause_code);
|
||||
code_body.push(Line::Choice(choice));
|
||||
}
|
||||
|
||||
clause.first_arg().map(|arg| {
|
||||
let index = code_body.len();
|
||||
code_offsets.index_term(arg, index);
|
||||
});
|
||||
|
||||
code_body.append(&mut clause_code);
|
||||
}
|
||||
|
||||
let mut code = Vec::new();
|
||||
|
||||
code_offsets.add_indices(&mut code, code_body);
|
||||
code
|
||||
}
|
||||
|
||||
pub fn compile_predicate(&mut self, clauses: &'a Vec<PredicateClause>) -> Code
|
||||
{
|
||||
let mut code = Vec::new();
|
||||
let split_pred = Self::split_predicate(clauses);
|
||||
let multi_seq = split_pred.len() > 1;
|
||||
|
||||
for &(l, r) in split_pred.iter() {
|
||||
let mut code_segment = self.compile_pred_subseq(&clauses[l .. r]);
|
||||
|
||||
if multi_seq {
|
||||
let choice = match l {
|
||||
0 => ChoiceInstruction::TryMeElse(code_segment.len() + 1),
|
||||
_ if r == clauses.len() => ChoiceInstruction::TrustMe,
|
||||
_ => ChoiceInstruction::RetryMeElse(code_segment.len() + 1)
|
||||
};
|
||||
|
||||
code.push(Line::Choice(choice));
|
||||
}
|
||||
|
||||
code.append(&mut code_segment);
|
||||
}
|
||||
|
||||
code
|
||||
|
||||
Reference in New Issue
Block a user