use std::cell::RefCell;
use std::cmp::Ordering;
use std::fmt;
use std::slice;
use memchr::memmem::Finder;
use crate::json::Slots;
use crate::record::{Json, Miss, ReadPlan, Record, Typed};
use crate::strmatch::StrMatcher;
use super::parse::{self, Ast, Cmp, Lit, Method, Path, Refusal};
use super::value::{ErrorKind, read_error};
pub const MAX_FIELDS: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
True,
False,
Error(ErrorKind),
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Options {
pub allow_regex: bool,
pub root_presence: bool,
pub missing_parent_false: bool,
}
impl Options {
#[must_use]
pub const fn with_regex() -> Self {
Self {
allow_regex: true,
root_presence: false,
missing_parent_false: false,
}
}
}
#[derive(Debug)]
pub struct Program {
pub(super) slots: Vec<Slot>,
root: Node,
reads: Reads,
}
#[derive(Debug)]
struct Reads {
plan: ReadPlan,
at: Box<[usize]>,
}
pub(super) const FRAME: usize = 2 * MAX_FIELDS;
thread_local! {
static SCRATCH: RefCell<Slots> = const { RefCell::new(Slots::new()) };
}
impl Reads {
fn new(slots: &[Slot], read: &[usize], probes: &[Vec<String>], probe_base: usize) -> Self {
let mut chosen: Vec<(usize, &[String])> = Vec::new();
for &i in read {
if chosen.iter().all(|&(at, _)| at != i) && !slots[i].path.0.is_empty() {
chosen.push((i, &slots[i].path.0));
}
}
for (j, key) in probes.iter().enumerate() {
chosen.push((probe_base + j, key));
}
let paths: Vec<&[String]> = chosen.iter().map(|&(_, p)| p).collect();
Self {
plan: ReadPlan::new(&paths),
at: chosen.iter().map(|&(at, _)| at).collect(),
}
}
fn fill<'a, R: Record<'a>>(&self, record: R, frame: &mut Frame<R::At>) {
let Some((bytes, at)) = record.raw_json() else {
return;
};
if self.at.is_empty() {
return;
}
let mut fill = |scratch: &mut Slots| {
Json::new(bytes).find_all(&self.plan, scratch, |i, got| {
frame[self.at[i]] = Some(got.map(at).map_err(read_error));
});
};
let done = SCRATCH.try_with(|cell| {
cell.try_borrow_mut()
.map(|mut scratch| fill(&mut scratch))
.is_ok()
});
if !matches!(done, Ok(true)) {
fill(&mut Slots::new());
}
}
}
#[derive(Debug)]
pub(super) struct Slot {
parent: Option<usize>,
path: Path,
shared: bool,
}
#[derive(Debug)]
pub(super) enum Node {
And(Vec<Self>),
Or(Vec<Self>),
Not(Box<Self>),
Const(bool),
Leaf(Leaf),
}
#[derive(Debug)]
pub(super) enum Leaf {
Has {
parent: usize,
key: String,
missing_parent_false: bool,
},
HasRoot {
key: String,
probe: Option<usize>,
},
Cmp {
slot: usize,
op: Cmp,
lit: Lit,
},
In {
slot: usize,
lits: Vec<Lit>,
},
StartsWith {
slot: usize,
prefix: String,
},
EndsWith {
slot: usize,
suffix: String,
},
Contains {
slot: usize,
needle: String,
find: Find,
},
Matches {
slot: usize,
pattern: String,
matcher: Option<Box<StrMatcher>>,
},
}
#[derive(Debug)]
pub(super) enum Find {
Byte(u8),
Bytes(Box<Finder<'static>>),
}
pub(super) type Frame<A> = [Option<Result<A, ErrorKind>>];
impl Program {
pub fn compile(text: &str) -> Result<Self, Refusal> {
Self::compile_with(text, &Options::default())
}
pub fn compile_with(text: &str, options: &Options) -> Result<Self, Refusal> {
let ast = parse::parse(text)?;
let mut lower = Lower::new(options, text.len(), MAX_FIELDS);
let root = lower.node(ast)?;
let mut program = Self::from_lower(lower);
program.root = root;
Ok(program)
}
pub(super) fn from_lower(lower: Lower) -> Self {
let Lower {
mut slots,
read,
probes,
max_fields,
..
} = lower;
mark_shared(&mut slots, &read);
Self {
reads: Reads::new(&slots, &read, &probes, max_fields),
slots,
root: Node::Const(true),
}
}
#[must_use]
pub fn eval(&self, json: &[u8]) -> Outcome {
self.eval_record(Json::new(json))
}
pub(super) fn prefill<'a, R: Record<'a>>(&self, record: R, frame: &mut Frame<R::At>) {
self.reads.fill(record, frame);
}
#[must_use]
pub fn matches(&self, json: &[u8]) -> bool {
self.eval(json) == Outcome::True
}
#[must_use]
pub fn eval_record<'a, R: Record<'a>>(&self, record: R) -> Outcome {
let mut frame = [None; FRAME];
self.prefill(record, &mut frame);
self.node(&self.root, record, &mut frame)
}
#[must_use]
pub fn matches_record<'a, R: Record<'a>>(&self, record: R) -> bool {
self.eval_record(record) == Outcome::True
}
pub(super) fn node<'a, R: Record<'a>>(
&self,
node: &Node,
record: R,
frame: &mut Frame<R::At>,
) -> Outcome {
match node {
Node::And(children) => {
let mut error = None;
for child in children {
match self.node(child, record, frame) {
Outcome::False => return Outcome::False,
Outcome::Error(kind) => {
error.get_or_insert(kind);
}
Outcome::True => {}
}
}
error.map_or(Outcome::True, Outcome::Error)
}
Node::Or(children) => {
let mut error = None;
for child in children {
match self.node(child, record, frame) {
Outcome::True => return Outcome::True,
Outcome::Error(kind) => {
error.get_or_insert(kind);
}
Outcome::False => {}
}
}
error.map_or(Outcome::False, Outcome::Error)
}
Node::Not(inner) => match self.node(inner, record, frame) {
Outcome::True => Outcome::False,
Outcome::False => Outcome::True,
error @ Outcome::Error(_) => error,
},
Node::Const(v) => outcome(*v),
Node::Leaf(leaf) => self
.leaf(leaf, record, frame)
.map_or_else(Outcome::Error, outcome),
}
}
fn leaf<'a, R: Record<'a>>(
&self,
leaf: &Leaf,
record: R,
frame: &mut Frame<R::At>,
) -> Result<bool, ErrorKind> {
match leaf {
Leaf::Has {
parent,
key,
missing_parent_false,
} => {
let obj = match self.resolve(*parent, record, frame) {
Ok(obj) => obj,
Err(ErrorKind::MissingRoot | ErrorKind::MissingField)
if *missing_parent_false =>
{
return Ok(false);
}
Err(e) => return Err(e),
};
match record.find_below(obj, slice::from_ref(key)) {
Ok(_) => Ok(true),
Err(Miss::MissingField | Miss::MissingRoot) => Ok(false),
Err(Miss::WrongParentType) => Err(ErrorKind::TypeMismatch),
Err(Miss::Malformed) => Err(ErrorKind::Malformed),
}
}
Leaf::HasRoot { key, probe } => {
let read = probe.and_then(|i| frame.get(i).copied().flatten());
match read.unwrap_or_else(|| record.find(slice::from_ref(key)).map_err(read_error))
{
Ok(_) => Ok(true),
Err(ErrorKind::MissingRoot) => Ok(false),
Err(e) => Err(e),
}
}
Leaf::Cmp { slot, op, lit } => {
let v = self.typed(*slot, record, frame)?;
Ok(match op {
Cmp::Eq => equal(&v, lit),
Cmp::Ne => !equal(&v, lit),
Cmp::Lt => order(&v, lit)? == Ordering::Less,
Cmp::Le => order(&v, lit)? != Ordering::Greater,
Cmp::Gt => order(&v, lit)? == Ordering::Greater,
Cmp::Ge => order(&v, lit)? != Ordering::Less,
})
}
Leaf::In { slot, lits } => {
let v = self.typed(*slot, record, frame)?;
Ok(lits.iter().any(|lit| equal(&v, lit)))
}
Leaf::StartsWith { slot, prefix } => match self.typed(*slot, record, frame)? {
Typed::Str(s) => Ok(s.starts_with(prefix.as_str())),
_ => Err(ErrorKind::TypeMismatch),
},
Leaf::EndsWith { slot, suffix } => match self.typed(*slot, record, frame)? {
Typed::Str(s) => Ok(s.ends_with(suffix.as_str())),
_ => Err(ErrorKind::TypeMismatch),
},
Leaf::Matches { slot, matcher, .. } => match self.typed(*slot, record, frame)? {
Typed::Str(s) => Ok(matcher.as_ref().is_none_or(|m| m.is_match(s.as_bytes()))),
_ => Err(ErrorKind::TypeMismatch),
},
Leaf::Contains { slot, find, .. } => match self.typed(*slot, record, frame)? {
Typed::Str(s) => Ok(match find {
Find::Byte(b) => memchr::memchr(*b, s.as_bytes()).is_some(),
Find::Bytes(f) => f.find(s.as_bytes()).is_some(),
}),
_ => Err(ErrorKind::TypeMismatch),
},
}
}
pub(super) fn typed<'a, R: Record<'a>>(
&self,
i: usize,
record: R,
frame: &mut Frame<R::At>,
) -> Result<Typed<'a>, ErrorKind> {
record
.typed(self.resolve(i, record, frame)?)
.map_err(read_error)
}
pub(super) fn resolve<'a, R: Record<'a>>(
&self,
i: usize,
record: R,
frame: &mut Frame<R::At>,
) -> Result<R::At, ErrorKind> {
if let Some(done) = frame[i] {
return done;
}
let slot = &self.slots[i];
let mut base = slot.parent;
while let Some(p) = base {
if self.slots[p].shared {
break;
}
base = self.slots[p].parent;
}
let got = match base {
Some(p) => {
let obj = self.resolve(p, record, frame)?;
record.find_below(obj, &slot.path.0[self.slots[p].path.0.len()..])
}
None => record.find(&slot.path.0),
}
.map_err(read_error);
frame[i] = Some(got);
got
}
}
const fn outcome(v: bool) -> Outcome {
if v { Outcome::True } else { Outcome::False }
}
#[allow(
clippy::cast_precision_loss,
clippy::float_cmp,
reason = "cel compares an int with a double through f64, exactly"
)]
fn equal(v: &Typed<'_>, lit: &Lit) -> bool {
match (v, lit) {
(Typed::Str(a), Lit::Str(b)) => a == b,
(Typed::Int(a), Lit::Int(b)) => a == b,
(Typed::Uint(a), Lit::Uint(b)) => a == b,
(Typed::Double(a), Lit::Double(b)) => a == b,
(Typed::Int(a), Lit::Uint(b)) => u64::try_from(*a).is_ok_and(|a| a == *b),
(Typed::Uint(a), Lit::Int(b)) => i64::try_from(*a).is_ok_and(|a| a == *b),
(Typed::Int(a), Lit::Double(b)) => *a as f64 == *b,
(Typed::Uint(a), Lit::Double(b)) => *a as f64 == *b,
(Typed::Double(a), Lit::Int(b)) => *a == *b as f64,
(Typed::Double(a), Lit::Uint(b)) => *a == *b as f64,
(Typed::Bool(a), Lit::Bool(b)) => a == b,
(Typed::Null, Lit::Null) => true,
_ => false,
}
}
#[allow(
clippy::cast_precision_loss,
reason = "cel orders an int against a double through f64"
)]
fn order(v: &Typed<'_>, lit: &Lit) -> Result<Ordering, ErrorKind> {
let mismatch = ErrorKind::TypeMismatch;
match (v, lit) {
(Typed::Int(a), Lit::Int(b)) => Ok(a.cmp(b)),
(Typed::Uint(a), Lit::Uint(b)) => Ok(a.cmp(b)),
(Typed::Int(a), Lit::Uint(b)) => Ok(u64::try_from(*a).map_or(Ordering::Less, |a| a.cmp(b))),
(Typed::Uint(a), Lit::Int(b)) => {
Ok(i64::try_from(*a).map_or(Ordering::Greater, |a| a.cmp(b)))
}
(Typed::Int(a), Lit::Double(b)) => (*a as f64).partial_cmp(b).ok_or(mismatch),
(Typed::Uint(a), Lit::Double(b)) => (*a as f64).partial_cmp(b).ok_or(mismatch),
(Typed::Double(a), Lit::Int(b)) => a.partial_cmp(&(*b as f64)).ok_or(mismatch),
(Typed::Double(a), Lit::Uint(b)) => a.partial_cmp(&(*b as f64)).ok_or(mismatch),
(Typed::Double(a), Lit::Double(b)) => a.partial_cmp(b).ok_or(mismatch),
(Typed::Str(a), Lit::Str(b)) => Ok(a.as_ref().cmp(b.as_str())),
_ => Err(mismatch),
}
}
pub(super) struct Lower {
pub(super) slots: Vec<Slot>,
pub(super) read: Vec<usize>,
pub(super) probes: Vec<Vec<String>>,
pub(super) len: usize,
allow_regex: bool,
root_presence: bool,
missing_parent_false: bool,
max_fields: usize,
}
fn mark_shared(slots: &mut [Slot], read: &[usize]) {
let mut through = vec![0_u32; slots.len()];
let mut seen = Vec::new();
for &leaf in read {
if seen.contains(&leaf) {
continue;
}
seen.push(leaf);
let mut at = Some(leaf);
while let Some(i) = at {
through[i] += 1;
at = slots[i].parent;
}
}
for (slot, n) in slots.iter_mut().zip(through) {
slot.shared = n > 1;
}
}
impl Lower {
pub(super) const fn new(options: &Options, len: usize, max_fields: usize) -> Self {
Self {
slots: Vec::new(),
read: Vec::new(),
len,
allow_regex: options.allow_regex,
root_presence: options.root_presence,
missing_parent_false: options.missing_parent_false,
max_fields,
probes: Vec::new(),
}
}
fn nodes(&mut self, terms: Vec<Ast>) -> Result<Vec<Node>, Refusal> {
terms.into_iter().map(|t| self.node(t)).collect()
}
pub(super) fn node(&mut self, ast: Ast) -> Result<Node, Refusal> {
Ok(match ast {
Ast::Or(terms) => Node::Or(self.nodes(terms)?),
Ast::And(terms) => Node::And(self.nodes(terms)?),
Ast::Not(inner) => Node::Not(Box::new(self.node(*inner)?)),
Ast::Const(v) => Node::Const(v),
Ast::Has(path, at) => {
let Some((key, parent)) = path.0.split_last() else {
return Err(self.refuse("has() with no field"));
};
if parent.is_empty() {
if !self.root_presence {
return Err(Refusal {
span: at,
why: "has() on a bare name, which runs only with Options::root_presence",
});
}
let probe = self.probe(key);
return Ok(Node::Leaf(Leaf::HasRoot {
key: key.clone(),
probe,
}));
}
let parent = self.read(&Path(parent.to_vec()))?;
Node::Leaf(Leaf::Has {
parent,
key: key.clone(),
missing_parent_false: self.missing_parent_false,
})
}
Ast::Cmp(path, op, lit) => {
if !matches!(op, Cmp::Eq | Cmp::Ne) && matches!(lit, Lit::Bool(_) | Lit::Null) {
return Err(self.refuse("an ordering against a bool or null"));
}
Node::Leaf(Leaf::Cmp {
slot: self.read(&path)?,
op,
lit,
})
}
Ast::In(path, lits) => Node::Leaf(Leaf::In {
slot: self.read(&path)?,
lits,
}),
Ast::Method(path, method, arg) => {
let slot = self.read(&path)?;
Node::Leaf(match method {
Method::StartsWith => Leaf::StartsWith { slot, prefix: arg },
Method::EndsWith => Leaf::EndsWith { slot, suffix: arg },
Method::Contains => {
let find = match arg.as_bytes() {
[b] => Find::Byte(*b),
bytes => Find::Bytes(Box::new(Finder::new(bytes).into_owned())),
};
Leaf::Contains {
slot,
needle: arg,
find,
}
}
Method::Matches => self.matches(slot, arg)?,
})
}
})
}
fn matches(&self, slot: usize, pattern: String) -> Result<Leaf, Refusal> {
if !self.allow_regex {
return Err(self.refuse("matches(), which runs only with Options::allow_regex"));
}
if regex_syntax::Parser::new().parse(&pattern).is_err() {
return Err(self.refuse("a matches() pattern cel's regex refuses"));
}
let matcher = if pattern.is_empty() {
None
} else {
let m = StrMatcher::new(&pattern)
.map_err(|_| self.refuse("a matches() pattern strmatch can't build"))?;
Some(Box::new(m))
};
Ok(Leaf::Matches {
slot,
pattern,
matcher,
})
}
fn slot(&mut self, path: &Path) -> Result<usize, Refusal> {
if let Some(i) = self.slots.iter().position(|s| &s.path == path) {
return Ok(i);
}
let Some((_, prefix)) = path.0.split_last() else {
return Err(self.refuse("an empty field path"));
};
let parent = if prefix.is_empty() {
None
} else {
Some(self.slot(&Path(prefix.to_vec()))?)
};
if self.slots.len() == self.max_fields {
return Err(self.refuse("more field paths than one program holds"));
}
self.slots.push(Slot {
parent,
path: path.clone(),
shared: false,
});
Ok(self.slots.len() - 1)
}
fn probe(&mut self, key: &str) -> Option<usize> {
let j = match self.probes.iter().position(|p| p[0] == key) {
Some(j) => j,
None if self.probes.len() < self.max_fields => {
self.probes.push(vec![key.to_owned()]);
self.probes.len() - 1
}
None => return None,
};
Some(self.max_fields + j)
}
pub(super) fn read(&mut self, path: &Path) -> Result<usize, Refusal> {
let i = self.slot(path)?;
self.read.push(i);
Ok(i)
}
pub(super) const fn refuse(&self, why: &'static str) -> Refusal {
Refusal {
span: 0..self.len,
why,
}
}
}
impl fmt::Display for Program {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.write_node(&self.root, f)
}
}
impl Program {
fn write_node(&self, node: &Node, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match node {
Node::And(c) => self.write_list("and", c, f),
Node::Or(c) => self.write_list("or", c, f),
Node::Not(inner) => {
f.write_str("not(")?;
self.write_node(inner, f)?;
f.write_str(")")
}
Node::Const(v) => write!(f, "{v}"),
Node::Leaf(leaf) => self.write_leaf(leaf, f),
}
}
fn write_list(&self, name: &str, children: &[Node], f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{name}(")?;
for (i, c) in children.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
self.write_node(c, f)?;
}
f.write_str(")")
}
fn write_leaf(&self, leaf: &Leaf, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let path = |i: usize| self.slots[i].path.0.join(".");
match leaf {
Leaf::Has { parent, key, .. } => write!(f, "has({}.{key})", path(*parent)),
Leaf::HasRoot { key, .. } => write!(f, "has({key})"),
Leaf::Cmp { slot, op, lit } => write!(f, "{op:?}({}, {lit:?})", path(*slot)),
Leaf::In { slot, lits } => write!(f, "in({}, {} values)", path(*slot), lits.len()),
Leaf::StartsWith { slot, prefix } => write!(f, "prefix({}, {prefix:?})", path(*slot)),
Leaf::EndsWith { slot, suffix } => write!(f, "suffix({}, {suffix:?})", path(*slot)),
Leaf::Matches { slot, pattern, .. } => {
write!(f, "matches({}, {pattern:?})", path(*slot))
}
Leaf::Contains { slot, needle, find } => {
let how = match find {
Find::Byte(_) => "memchr",
Find::Bytes(_) => "memmem",
};
write!(f, "{how}({}, {needle:?})", path(*slot))
}
}
}
}