simplified rule interface

This commit is contained in:
2022-07-07 01:25:50 +02:00
parent 5d8d515c28
commit 119f41076e
5 changed files with 67 additions and 22 deletions

View File

@@ -0,0 +1,11 @@
use std::{fmt, error::Error};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BadState(Vec<String>);
impl fmt::Display for BadState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "The following key(s) weren't produced by the matching pattern: {:?}", self.0)
}
}
impl Error for BadState {}

14
src/rule/executor.rs Normal file
View File

@@ -0,0 +1,14 @@
use crate::expression::Expr;
use super::{Rule, BadState};
pub fn execute<Src, Tgt>(src: &Src, tgt: &Tgt, mut input: Vec<Expr>)
-> Result<(Vec<Expr>, bool), BadState> where Src: Rule, Tgt: Rule {
let (range, state) = match src.scan_slice(&input) {
Some(res) => res,
None => return Ok((input, false))
};
let output = tgt.write(&state)?;
input.splice(range, output);
Ok((input, true))
}

View File

@@ -1 +1,6 @@
mod rule;
mod executor;
mod bad_state_error;
pub use rule::Rule;
pub use bad_state_error::BadState;

3
src/rule/name.rs Normal file
View File

@@ -0,0 +1,3 @@
struct Name {
qualified: Vec<String>
}

View File

@@ -1,38 +1,50 @@
use std::cmp::{min, max};
use std::{cmp::{min, max}, error::Error, fmt, ops::Range};
use hashbrown::HashSet;
use hashbrown::HashMap;
use crate::expression::Expr;
use super::BadState;
type State = HashMap<String, Expr>;
pub trait Rule {
type OutIter: Iterator<Item = Option<Expr>>;
type Out: Iterator<Item = Expr>;
/// The minimum and maximum set of symbols this rule may match.
fn len(&self) -> (Option<usize>, Option<usize>);
/// The exact tokens the pattern consumes (None if varies)
fn consumes(&self) -> Option<HashSet<Vec<String>>>;
/// The exact tokens the pattern produces (None if varies)
fn produces(&self) -> Option<HashSet<Vec<String>>>;
/// Check if the slice matches, and produce the necessary transformations
fn produce(&self, base: &[Expr]) -> Option<Self::OutIter>;
/// Check if the slice matches, and extract data
fn read(&self, input: &[Expr]) -> Option<State>;
/// Construct item from state
fn write(&self, state: &State) -> Result<Self::Out, BadState>;
/// Placeholders present in this pattern (all consumed must also be provided)
fn placeholders(&'_ self) -> &'_ [&'_ str];
/// Try all subsections of Vec of appropriate size, longest first, front-to-back
/// Match the first, execute the substitution, return the vector and whether any
/// substitutions happened
fn apply(&self, mut base: Vec<Expr>) -> (Vec<Expr>, bool) {
/// Match the first, return the position and produced state
fn scan_slice(&self, input: &[Expr]) -> Option<(Range<usize>, State)> {
let len_range = self.len();
let lo = max(len_range.0.unwrap_or(1), 1);
let hi = min(len_range.1.unwrap_or(base.len()), base.len());
let hi = min(len_range.1.unwrap_or(input.len()), input.len());
for width in (lo..hi).rev() {
let starts = (0..base.len() - width).into_iter();
let starts = (0..input.len() - width).into_iter();
let first_match = starts.filter_map(|start| {
self.produce(&base[start..start+width])
.map(|res| (start, res))
let res = self.read(&input[start..start+width])?;
Some((start..start+width, res))
}).next();
if let Some((start, substitution)) = first_match {
let diff = substitution.enumerate().filter_map(|(i, opt)| opt.map(|val| (i, val)));
for (idx, item) in diff { base[start + idx] = item }
return (base, true)
if first_match.is_some() {
return first_match;
}
}
(base, false)
None
}
}
pub fn verify<Src, Tgt>(src: &Src, tgt: &Tgt) -> Option<Vec<String>> where Src: Rule, Tgt: Rule {
let mut amiss: Vec<String> = Vec::new();
for ent in tgt.placeholders() {
if src.placeholders().iter().find(|x| x == &ent).is_none() {
amiss.push(ent.to_string())
}
}
if amiss.len() > 0 { Some(amiss) }
else { None }
}