use std::ops::Range;
use super::lex::{self, Tok, Token};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct Path(pub(super) Vec<String>);
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Lit {
Str(String),
Int(i64),
Uint(u64),
Double(f64),
Bool(bool),
Null,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Cmp {
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
}
impl Cmp {
const fn flipped(self) -> Self {
match self {
Self::Eq => Self::Eq,
Self::Ne => Self::Ne,
Self::Lt => Self::Gt,
Self::Le => Self::Ge,
Self::Gt => Self::Lt,
Self::Ge => Self::Le,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Method {
StartsWith,
EndsWith,
Contains,
Matches,
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Ast {
Or(Vec<Self>),
And(Vec<Self>),
Not(Box<Self>),
Const(bool),
Has(Path, Range<usize>),
Cmp(Path, Cmp, Lit),
Method(Path, Method, String),
In(Path, Vec<Lit>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
pub span: Range<usize>,
pub why: &'static str,
}
impl std::fmt::Display for Refusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} at bytes {}..{}",
self.why, self.span.start, self.span.end
)
}
}
impl std::error::Error for Refusal {}
const RESERVED: &[&str] = &[
"as",
"break",
"const",
"continue",
"else",
"false",
"for",
"function",
"if",
"import",
"in",
"let",
"loop",
"package",
"namespace",
"null",
"return",
"true",
"var",
"void",
"while",
];
pub(super) fn parse(text: &str) -> Result<Ast, Refusal> {
let tokens = lex::tokens(text).map_err(|e| Refusal {
span: e.span,
why: e.why,
})?;
let mut p = Parser {
tokens: &tokens,
at: 0,
len: text.len(),
};
let ast = p.or()?;
p.peek().map_or(Ok(ast), |t| {
Err(refuse(t.span.clone(), "a form outside the lowered subset"))
})
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Value {
Pred(Ast),
Cond(Ast, Box<Self>, Box<Self>),
Add(Vec<Self>),
Lit(Lit),
Field(Path),
}
pub(super) fn parse_value(text: &str) -> Result<Value, Refusal> {
let tokens = lex::tokens(text).map_err(|e| Refusal {
span: e.span,
why: e.why,
})?;
let mut p = Parser {
tokens: &tokens,
at: 0,
len: text.len(),
};
let v = p.value()?;
p.peek().map_or(Ok(v), |t| {
Err(refuse(t.span.clone(), "a form outside the lowered subset"))
})
}
struct Parser<'t, 'a> {
tokens: &'t [Token<'a>],
at: usize,
len: usize,
}
impl<'a> Parser<'_, 'a> {
fn peek(&self) -> Option<&Token<'a>> {
self.tokens.get(self.at)
}
fn peek_tok(&self, ahead: usize) -> Option<&Tok<'a>> {
self.tokens.get(self.at + ahead).map(|t| &t.tok)
}
fn here(&self) -> Range<usize> {
self.peek().map_or(self.len..self.len, |t| t.span.clone())
}
fn eat(&mut self, tok: &Tok<'_>) -> bool {
if self.peek_tok(0) == Some(tok) {
self.at += 1;
true
} else {
false
}
}
fn expect(&mut self, tok: &Tok<'_>, why: &'static str) -> Result<(), Refusal> {
if self.eat(tok) {
Ok(())
} else {
Err(refuse(self.here(), why))
}
}
fn value(&mut self) -> Result<Value, Refusal> {
let start = self.at;
if let Ok(cond) = self.or() {
if self.eat(&Tok::Question) {
let then = self.value()?;
self.expect(&Tok::Colon, "a ternary with no `:`")?;
let other = self.value()?;
return Ok(Value::Cond(cond, Box::new(then), Box::new(other)));
}
if matches!(self.peek_tok(0), None | Some(Tok::Colon | Tok::RParen)) {
return Ok(Value::Pred(cond));
}
}
self.at = start;
let mut terms = vec![self.atom()?];
while self.eat(&Tok::Plus) {
terms.push(self.atom()?);
}
Ok(if terms.len() == 1 {
terms.remove(0)
} else {
Value::Add(terms)
})
}
fn atom(&mut self) -> Result<Value, Refusal> {
if self.eat(&Tok::LParen) {
let inner = self.value()?;
self.expect(&Tok::RParen, "an unclosed parenthesis")?;
return Ok(inner);
}
match self.peek_tok(0) {
Some(Tok::Ident(w)) if !RESERVED.contains(w) => {
let path = self.path()?;
if self.peek_tok(0) == Some(&Tok::Dot) {
return Err(refuse(
self.here(),
"a method in a value outside the subset",
));
}
Ok(Value::Field(path))
}
_ => self.lit().map(Value::Lit),
}
}
fn or(&mut self) -> Result<Ast, Refusal> {
let mut terms = vec![self.and()?];
while self.eat(&Tok::OrOr) {
terms.push(self.and()?);
}
Ok(if terms.len() == 1 {
terms.remove(0)
} else {
Ast::Or(terms)
})
}
fn and(&mut self) -> Result<Ast, Refusal> {
let mut terms = vec![self.unary()?];
while self.eat(&Tok::AndAnd) {
terms.push(self.unary()?);
}
Ok(if terms.len() == 1 {
terms.remove(0)
} else {
Ast::And(terms)
})
}
fn unary(&mut self) -> Result<Ast, Refusal> {
if self.eat(&Tok::Not) {
return Ok(Ast::Not(Box::new(self.unary()?)));
}
if self.eat(&Tok::LParen) {
let inner = self.or()?;
self.expect(&Tok::RParen, "an unclosed parenthesis")?;
return Ok(inner);
}
self.leaf()
}
fn leaf(&mut self) -> Result<Ast, Refusal> {
let start = self.here();
match self.peek_tok(0) {
Some(Tok::Ident("has")) if self.peek_tok(1) == Some(&Tok::LParen) => {
self.at += 2;
let path = self.path()?;
let named_last = matches!(self.tokens[self.at - 1].tok, Tok::Ident(_));
let before = &self.tokens[self.at - 2].tok;
let bare = path.0.len() == 1 && *before == Tok::LParen;
if !named_last || !(bare || *before == Tok::Dot) {
return Err(refuse(start, "has() on an index, which cel refuses"));
}
self.expect(&Tok::RParen, "has() takes one field path")?;
return Ok(Ast::Has(path, start));
}
Some(Tok::Ident("true" | "false")) if !matches!(self.peek_tok(1), Some(t) if cmp_of(t).is_some()) =>
{
let v = self.peek_tok(0) == Some(&Tok::Ident("true"));
self.at += 1;
return Ok(Ast::Const(v));
}
Some(Tok::Ident(w)) if !RESERVED.contains(w) => {}
_ => {
let lit = self.lit()?;
let Some(cmp) = self.peek_tok(0).and_then(cmp_of) else {
return Err(refuse(start, "a literal with no comparison"));
};
self.at += 1;
let path = self.path()?;
return Ok(Ast::Cmp(path, cmp.flipped(), lit));
}
}
let path = self.path()?;
if self.peek_tok(0) == Some(&Tok::Dot) {
return self.method(path);
}
if self.peek_tok(0) == Some(&Tok::Ident("in")) {
self.at += 1;
self.expect(&Tok::LBracket, "`in` over anything but a list literal")?;
let mut lits = Vec::new();
if !self.eat(&Tok::RBracket) {
loop {
lits.push(self.lit()?);
if self.eat(&Tok::RBracket) {
break;
}
self.expect(&Tok::Comma, "a malformed list literal")?;
if self.eat(&Tok::RBracket) {
break;
}
}
}
return Ok(Ast::In(path, lits));
}
let Some(cmp) = self.peek_tok(0).and_then(cmp_of) else {
if self.peek_tok(0) == Some(&Tok::LParen) {
return Err(refuse(start, "a function call outside the subset"));
}
let span = if self.peek().is_some() {
self.here()
} else {
start
};
return Err(refuse(
span,
"a bare field, or a field in a form outside the subset",
));
};
self.at += 1;
if matches!(self.peek_tok(0), Some(Tok::Ident(w)) if !matches!(*w, "true" | "false" | "null"))
{
return Err(refuse(self.here(), "a comparison between two fields"));
}
let lit = self.lit()?;
Ok(Ast::Cmp(path, cmp, lit))
}
fn method(&mut self, path: Path) -> Result<Ast, Refusal> {
self.at += 1;
let span = self.here();
let method = match self.peek_tok(0) {
Some(Tok::Ident("startsWith")) => Method::StartsWith,
Some(Tok::Ident("endsWith")) => Method::EndsWith,
Some(Tok::Ident("contains")) => Method::Contains,
Some(Tok::Ident("matches")) => Method::Matches,
_ => return Err(refuse(span, "a method outside the lowered subset")),
};
self.at += 1;
self.expect(&Tok::LParen, "a method name with no call")?;
let Some(Tok::Str(arg)) = self.peek_tok(0).cloned() else {
return Err(refuse(
self.here(),
"a string method takes one string literal",
));
};
self.at += 1;
self.expect(&Tok::RParen, "a string method takes one string literal")?;
Ok(Ast::Method(path, method, arg.into_owned()))
}
fn path(&mut self) -> Result<Path, Refusal> {
let mut segs = Vec::new();
match self.peek_tok(0) {
Some(Tok::Ident(w)) if !RESERVED.contains(w) => {
segs.push((*w).to_owned());
self.at += 1;
}
_ => return Err(refuse(self.here(), "a field path")),
}
loop {
match (self.peek_tok(0), self.peek_tok(1), self.peek_tok(2)) {
(Some(Tok::Dot), Some(Tok::Ident(_)), Some(Tok::LParen)) => break,
(Some(Tok::Dot), Some(Tok::Ident(w)), _) if !RESERVED.contains(w) => {
segs.push((*w).to_owned());
self.at += 2;
}
(Some(Tok::LBracket), Some(Tok::Str(s)), Some(Tok::RBracket)) => {
segs.push(s.to_string());
self.at += 3;
}
(Some(Tok::Dot | Tok::LBracket), _, _) => {
return Err(refuse(self.here(), "a path step outside the subset"));
}
_ => break,
}
}
Ok(Path(segs))
}
fn lit(&mut self) -> Result<Lit, Refusal> {
let span = self.here();
let negative = self.eat(&Tok::Minus);
let lit = match (self.peek_tok(0).cloned(), negative) {
(Some(Tok::Int(n)), _) => Lit::Int(if negative { -n } else { n }),
(Some(Tok::Double(d)), _) => Lit::Double(if negative { -d } else { d }),
(Some(Tok::Uint(u)), false) => Lit::Uint(u),
(Some(Tok::Str(s)), false) => Lit::Str(s.into_owned()),
(Some(Tok::Ident("true")), false) => Lit::Bool(true),
(Some(Tok::Ident("false")), false) => Lit::Bool(false),
(Some(Tok::Ident("null")), false) => Lit::Null,
(Some(Tok::Bytes), false) => {
return Err(refuse(span, "a bytes literal"));
}
_ => return Err(refuse(span, "a literal")),
};
self.at += 1;
Ok(lit)
}
}
const fn cmp_of(tok: &Tok<'_>) -> Option<Cmp> {
Some(match tok {
Tok::EqEq => Cmp::Eq,
Tok::Ne => Cmp::Ne,
Tok::Lt => Cmp::Lt,
Tok::Le => Cmp::Le,
Tok::Gt => Cmp::Gt,
Tok::Ge => Cmp::Ge,
_ => return None,
})
}
const fn refuse(span: Range<usize>, why: &'static str) -> Refusal {
Refusal { span, why }
}