use crate::layer0::limits::{
SPEC_ASCII_BACKSLASH, SPEC_ASCII_BANG, SPEC_ASCII_DOT, SPEC_ASCII_DQUOTE, SPEC_ASCII_EQ,
SPEC_ASCII_LPAREN, SPEC_ASCII_RPAREN, SPEC_ASCII_SPACE, SPEC_ASCII_SQUOTE,
SPEC_ASCII_UNDERSCORE, SPEC_U16_BYTES,
};
use crate::layer0::vocabulary::{
GUARD_OP_AND, GUARD_OP_NOT, GUARD_OP_OR, GUARD_OUTCOME_FAIL, GUARD_OUTCOME_PASS,
GUARD_OUTCOME_UNMATCHED, GUARD_WORD_AND, GUARD_WORD_NOT, GUARD_WORD_OR,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GuardVerdict {
Pass,
Fail(String),
Unmatched(String),
}
impl GuardVerdict {
pub fn outcome(&self) -> &'static str {
match self {
GuardVerdict::Pass => GUARD_OUTCOME_PASS,
GuardVerdict::Fail(_) => GUARD_OUTCOME_FAIL,
GuardVerdict::Unmatched(_) => GUARD_OUTCOME_UNMATCHED,
}
}
pub fn is_pass(&self) -> bool {
matches!(self, GuardVerdict::Pass)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GuardAst {
Or(Box<GuardAst>, Box<GuardAst>),
And(Box<GuardAst>, Box<GuardAst>),
Not(Box<GuardAst>),
Atom(String),
}
pub(crate) fn is_ident_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == SPEC_ASCII_UNDERSCORE as u8
}
pub(crate) fn is_lhs_byte(b: u8) -> bool {
is_ident_byte(b)
|| b == SPEC_ASCII_DOT as u8
|| b == SPEC_ASCII_LPAREN as u8
|| b == SPEC_ASCII_RPAREN as u8
}
fn skip_ws(bytes: &[u8], mut pos: usize, end: usize) -> usize {
while pos < end && bytes[pos] <= SPEC_ASCII_SPACE as u8 {
pos += 1;
}
pos
}
fn match_word_op(bytes: &[u8], pos: usize, end: usize, word: &[u8]) -> Option<usize> {
if pos + word.len() > end
|| (pos > 0 && is_ident_byte(bytes[pos - 1]))
|| &bytes[pos..pos + word.len()] != word
{
return None;
}
let after = pos + word.len();
if after < end && is_ident_byte(bytes[after]) {
None
} else {
Some(after)
}
}
fn match_or_at(bytes: &[u8], pos: usize, end: usize, words: bool) -> Option<usize> {
let op_len = SPEC_U16_BYTES as usize;
if pos + op_len <= end && &bytes[pos..pos + op_len] == GUARD_OP_OR.as_bytes() {
return Some(pos + op_len);
}
if words {
match_word_op(bytes, pos, end, GUARD_WORD_OR.as_bytes())
} else {
None
}
}
fn match_and_at(bytes: &[u8], pos: usize, end: usize, words: bool) -> Option<usize> {
let op_len = SPEC_U16_BYTES as usize;
if pos + op_len <= end && &bytes[pos..pos + op_len] == GUARD_OP_AND.as_bytes() {
return Some(pos + op_len);
}
if words {
match_word_op(bytes, pos, end, GUARD_WORD_AND.as_bytes())
} else {
None
}
}
fn find_matching_paren(bytes: &[u8], open_pos: usize, end: usize) -> Option<usize> {
let (mut depth, mut quote, mut i) = (0usize, 0u8, open_pos);
while i < end {
let c = bytes[i];
if quote != 0 {
if c == SPEC_ASCII_BACKSLASH as u8 {
i += SPEC_U16_BYTES as usize;
continue;
}
if c == quote {
quote = 0;
}
i += 1;
continue;
}
if c == SPEC_ASCII_SQUOTE as u8 || c == SPEC_ASCII_DQUOTE as u8 {
quote = c;
i += 1;
continue;
}
if c == SPEC_ASCII_LPAREN as u8 {
depth += 1;
} else if c == SPEC_ASCII_RPAREN as u8 {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
i += 1;
}
None
}
struct GuardParser<'a> {
src: &'a str,
bytes: &'a [u8],
pos: usize,
end: usize,
words: bool,
}
impl<'a> GuardParser<'a> {
fn new(src: &'a str, start: usize, end: usize, words: bool) -> Self {
Self {
src,
bytes: src.as_bytes(),
pos: start,
end,
words,
}
}
fn parse_full(&mut self) -> Option<GuardAst> {
self.pos = skip_ws(self.bytes, self.pos, self.end);
if self.pos >= self.end {
return None;
}
let ast = self.parse_or()?;
self.pos = skip_ws(self.bytes, self.pos, self.end);
if self.pos == self.end {
Some(ast)
} else {
None
}
}
fn parse_or(&mut self) -> Option<GuardAst> {
let mut left = self.parse_and()?;
while let Some(next) = match_or_at(
self.bytes,
skip_ws(self.bytes, self.pos, self.end),
self.end,
self.words,
) {
self.pos = next;
left = GuardAst::Or(Box::new(left), Box::new(self.parse_and()?));
}
Some(left)
}
fn parse_and(&mut self) -> Option<GuardAst> {
let mut left = self.parse_not()?;
while let Some(next) = match_and_at(
self.bytes,
skip_ws(self.bytes, self.pos, self.end),
self.end,
self.words,
) {
self.pos = next;
left = GuardAst::And(Box::new(left), Box::new(self.parse_not()?));
}
Some(left)
}
fn parse_not(&mut self) -> Option<GuardAst> {
self.pos = skip_ws(self.bytes, self.pos, self.end);
if self.pos >= self.end {
return None;
}
if self.bytes[self.pos] == SPEC_ASCII_BANG as u8
&& (self.pos + 1 >= self.end || self.bytes[self.pos + 1] != SPEC_ASCII_EQ as u8)
{
self.pos += 1;
return Some(GuardAst::Not(Box::new(self.parse_not()?)));
}
if self.words
&& let Some(next) =
match_word_op(self.bytes, self.pos, self.end, GUARD_WORD_NOT.as_bytes())
{
self.pos = next;
return Some(GuardAst::Not(Box::new(self.parse_not()?)));
}
self.parse_primary()
}
fn parse_primary(&mut self) -> Option<GuardAst> {
self.pos = skip_ws(self.bytes, self.pos, self.end);
if self.pos >= self.end {
return None;
}
if self.bytes[self.pos] == SPEC_ASCII_LPAREN as u8 {
let close_pos = find_matching_paren(self.bytes, self.pos, self.end)?;
let after = skip_ws(self.bytes, close_pos + 1, self.end);
let is_group = after >= self.end
|| self.bytes[after] == SPEC_ASCII_RPAREN as u8
|| match_or_at(self.bytes, after, self.end, self.words).is_some()
|| match_and_at(self.bytes, after, self.end, self.words).is_some();
if is_group {
let sub =
GuardParser::new(self.src, self.pos + 1, close_pos, self.words).parse_full()?;
self.pos = close_pos + 1;
return Some(sub);
}
}
self.scan_atom()
}
fn scan_atom(&mut self) -> Option<GuardAst> {
let (start, mut depth, mut quote, mut i) = (self.pos, 0usize, 0u8, self.pos);
while i < self.end {
let c = self.bytes[i];
if quote != 0 {
if c == SPEC_ASCII_BACKSLASH as u8 {
i += 1;
if i >= self.end {
return None;
}
} else if c == quote {
quote = 0;
}
i += 1;
continue;
}
if c == SPEC_ASCII_SQUOTE as u8 || c == SPEC_ASCII_DQUOTE as u8 {
quote = c;
i += 1;
continue;
}
if c == SPEC_ASCII_LPAREN as u8 {
depth += 1;
i += 1;
continue;
}
if c == SPEC_ASCII_RPAREN as u8 {
if depth == 0 {
break;
}
depth -= 1;
i += 1;
continue;
}
if depth == 0
&& (match_or_at(self.bytes, i, self.end, self.words).is_some()
|| match_and_at(self.bytes, i, self.end, self.words).is_some())
{
break;
}
i += 1;
}
if quote != 0 || depth != 0 {
return None;
}
let text = self.src[start..i].trim();
if text.is_empty() {
return None;
}
self.pos = i;
Some(GuardAst::Atom(text.to_string()))
}
}
pub fn parse_guard_expression(source: &str, allow_word_ops: bool) -> Result<GuardAst, String> {
GuardParser::new(source, 0, source.len(), allow_word_ops)
.parse_full()
.ok_or_else(|| source.to_string())
}
pub fn eval_kleene_not(verdict: GuardVerdict, label: &str) -> GuardVerdict {
match verdict {
GuardVerdict::Pass => GuardVerdict::Fail(label.to_string()),
GuardVerdict::Fail(_) => GuardVerdict::Pass,
GuardVerdict::Unmatched(e) => GuardVerdict::Unmatched(e),
}
}
pub fn eval_kleene_and<F: FnOnce() -> GuardVerdict>(
left: GuardVerdict,
eval_right: F,
) -> GuardVerdict {
if matches!(left, GuardVerdict::Fail(_)) {
return left;
}
let right = eval_right();
match left {
GuardVerdict::Pass => right,
GuardVerdict::Unmatched(_) => {
if matches!(right, GuardVerdict::Fail(_)) {
right
} else {
left
}
}
GuardVerdict::Fail(_) => left,
}
}
pub fn eval_kleene_or<F: FnOnce() -> GuardVerdict>(
left: GuardVerdict,
eval_right: F,
) -> GuardVerdict {
if matches!(left, GuardVerdict::Pass) {
return left;
}
let right = eval_right();
match left {
GuardVerdict::Fail(_) => right,
GuardVerdict::Unmatched(_) => {
if matches!(right, GuardVerdict::Pass) {
right
} else {
left
}
}
GuardVerdict::Pass => left,
}
}
pub fn evaluate_guard_ast<F: Fn(&str) -> GuardVerdict>(
ast: &GuardAst,
eval_atom: &F,
) -> GuardVerdict {
match ast {
GuardAst::Atom(text) => eval_atom(text),
GuardAst::Not(inner) => {
let label = match inner.as_ref() {
GuardAst::Atom(t) => t.as_str(),
_ => GUARD_OP_NOT,
};
eval_kleene_not(evaluate_guard_ast(inner, eval_atom), label)
}
GuardAst::And(l, r) => eval_kleene_and(evaluate_guard_ast(l, eval_atom), || {
evaluate_guard_ast(r, eval_atom)
}),
GuardAst::Or(l, r) => eval_kleene_or(evaluate_guard_ast(l, eval_atom), || {
evaluate_guard_ast(r, eval_atom)
}),
}
}