Lines
97.86 %
Functions
96.34 %
Branches
100 %
//! Reader for the filter s-expression: text to a typed [`Filter`] tree.
use super::{self as op, Entity};
/// Nesting the reader accepts; deeper input would exhaust the native stack of
/// every recursive consumer of the tree.
const MAX_DEPTH: usize = 64;
/// A rational with a positive denominator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Amount {
numer: i64,
denom: i64,
}
/// The text is not in the number grammar of [`Amount::parse`].
pub struct NotAnAmount;
impl std::fmt::Display for NotAnAmount {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("not a number")
impl Amount {
/// `None` unless the denominator is positive; `i64::MIN` has no written
/// form the reader accepts.
#[must_use]
pub fn new(numer: i64, denom: i64) -> Option<Self> {
(denom > 0 && numer != i64::MIN).then_some(Self { numer, denom })
/// The reader's number grammar: `n`, `n/d`, decimals and `%`, signed,
/// reduced to lowest terms.
///
/// # Errors
/// `NotAnAmount` for anything else, a zero denominator or an overflow.
pub fn parse(text: &str) -> Result<Self, NotAnAmount> {
Self::read(text).ok_or(NotAnAmount)
fn read(text: &str) -> Option<Self> {
let (negative, body) = match text.strip_prefix('-') {
Some(body) => (true, body),
None => (false, text.strip_prefix('+').unwrap_or(text)),
};
let (body, percent) = body.strip_suffix('%').map_or((body, false), |b| (b, true));
let (mut numer, mut denom) = match body.split_once('/') {
Some((n, d)) => (digits(n)?, digits(d).filter(|d| *d != 0)?),
None => decimal(body)?,
if percent {
denom = denom.checked_mul(100)?;
let divisor = gcd(numer, denom).max(1);
numer /= divisor;
denom /= divisor;
Self::new(if negative { -numer } else { numer }, denom)
pub fn numer(self) -> i64 {
self.numer
pub fn denom(self) -> i64 {
self.denom
/// A parsed filter. Ids stay text: the server checks them as UUIDs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Filter {
AccountEq(String),
AccountIn(Vec<String>),
AccountSubtree(String),
CounterpartyEq(String),
CounterpartyIn(Vec<String>),
CommodityEq(String),
CommodityIn(Vec<String>),
AmountGt(Amount),
AmountLt(Amount),
AmountEq(Amount),
Tag {
entity: Entity,
name: String,
value: String,
},
And(Vec<Filter>),
Or(Vec<Filter>),
Not(Box<Filter>),
/// Why filter text did not parse, and the byte offset it went wrong at: the
/// offending text, or the start of the form whose argument is bad.
pub struct ParseError {
pub message: String,
pub at: usize,
enum Sexpr {
Symbol(String),
Str(String),
Number(Amount),
/// The items and the byte offset the list opens at.
List(Vec<Sexpr>, usize),
struct Cursor<'a> {
rest: &'a str,
len: usize,
impl Cursor<'_> {
fn skip_blank(&mut self) {
loop {
self.rest = self.rest.trim_start();
match self.rest.strip_prefix(';') {
Some(comment) => {
self.rest = comment.split_once('\n').map_or("", |(_, tail)| tail);
None => return,
fn offset(&self) -> usize {
self.len - self.rest.len()
fn error(&self, message: &str) -> ParseError {
ParseError {
message: message.to_owned(),
at: self.offset(),
fn expr(&mut self, depth: usize) -> Result<Sexpr, ParseError> {
if depth > MAX_DEPTH {
return Err(self.error("filter is nested too deeply"));
if let Some(tail) = self.rest.strip_prefix('(') {
let at = self.offset();
self.rest = tail;
return self.list(depth, at);
if let Some(tail) = self.rest.strip_prefix('"') {
return self.string(at).map(Sexpr::Str);
if self.rest.starts_with(')') {
return Err(self.error("unexpected )"));
let end = self
.rest
.find(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | '"' | ';'))
.unwrap_or(self.rest.len());
let (atom, tail) = self.rest.split_at(end);
Ok(Amount::parse(atom).map_or_else(|_| Sexpr::Symbol(atom.to_owned()), Sexpr::Number))
fn list(&mut self, depth: usize, at: usize) -> Result<Sexpr, ParseError> {
let mut items = Vec::new();
self.skip_blank();
if let Some(tail) = self.rest.strip_prefix(')') {
return Ok(Sexpr::List(items, at));
if self.rest.is_empty() {
return Err(self.error("missing )"));
items.push(self.expr(depth + 1)?);
fn string(&mut self, at: usize) -> Result<String, ParseError> {
let mut out = String::new();
let mut chars = self.rest.char_indices();
while let Some((at, c)) = chars.next() {
match c {
'"' => {
self.rest = &self.rest[at + 1..];
return Ok(out);
'\\' => match chars.next() {
Some((_, 'n')) => out.push('\n'),
Some((_, 't')) => out.push('\t'),
Some((_, 'r')) => out.push('\r'),
Some((_, c @ ('\\' | '"'))) => out.push(c),
Some((_, other)) => {
out.push('\\');
out.push(other);
None => break,
other => out.push(other),
Err(ParseError {
message: "unterminated string".to_owned(),
at,
})
fn read_all(input: &str) -> Result<Vec<Sexpr>, ParseError> {
let mut cursor = Cursor {
rest: input,
len: input.len(),
let mut exprs = Vec::new();
cursor.skip_blank();
if cursor.rest.is_empty() {
return Ok(exprs);
exprs.push(cursor.expr(0)?);
fn digits(text: &str) -> Option<i64> {
if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
return None;
text.parse().ok()
fn decimal(text: &str) -> Option<(i64, i64)> {
let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
if whole.is_empty() && fraction.is_empty() {
let scale = 10_i64.checked_pow(u32::try_from(fraction.len()).ok()?)?;
let whole = if whole.is_empty() { 0 } else { digits(whole)? };
let fraction = if fraction.is_empty() {
0
} else {
digits(fraction)?
Some((whole.checked_mul(scale)?.checked_add(fraction)?, scale))
fn gcd(a: i64, b: i64) -> i64 {
if b == 0 { a } else { gcd(b, a % b) }
fn id_arg(list: &[Sexpr], idx: usize) -> Result<String, String> {
match list.get(idx) {
Some(Sexpr::Str(s) | Sexpr::Symbol(s)) => Ok(s.clone()),
_ => Err(format!("expected UUID string at position {idx}")),
fn id_list(list: &[Sexpr]) -> Result<Vec<String>, String> {
list[1..]
.iter()
.map(|expr| match expr {
Sexpr::Str(s) | Sexpr::Symbol(s) => Ok(s.clone()),
_ => Err("expected UUID string".to_owned()),
.collect()
fn amount_arg(list: &[Sexpr], idx: usize) -> Result<Amount, String> {
Some(Sexpr::Number(amount)) => Ok(*amount),
_ => Err(format!("expected number at position {idx}")),
/// Tag names and values are literals only: the old reader folded a bare
/// symbol to upper case, so reading one as written would silently select
/// other rows.
fn string_arg(list: &[Sexpr], idx: usize) -> Result<String, String> {
Some(Sexpr::Str(s)) => Ok(s.clone()),
_ => Err(format!("expected a string at position {idx}")),
fn tag(entity: Entity, list: &[Sexpr]) -> Result<Filter, String> {
Ok(Filter::Tag {
entity,
name: string_arg(list, 1)?,
value: string_arg(list, 2)?,
fn children(list: &[Sexpr], at: usize) -> Result<Vec<Filter>, ParseError> {
list[1..].iter().map(|expr| filter_of(expr, at)).collect()
/// Extra arguments used to be dropped in silence: `(amount> 0 (amount< 100))`
/// became `amount > 0`, a strictly broader report than the one asked for.
fn arity(operator: &str) -> (usize, Option<usize>) {
match operator {
op::AND | op::OR => (0, None),
op::ACCOUNT_IN | op::COUNTERPARTY_IN | op::COMMODITY_IN => (1, None),
op::ACCOUNT_TAG_EQ | op::TRANSACTION_TAG_EQ | op::SPLIT_TAG_EQ => (2, Some(2)),
op::ACCOUNT_EQ
| op::ACCOUNT_SUBTREE
| op::COUNTERPARTY_EQ
| op::COMMODITY_EQ
| op::AMOUNT_GT
| op::AMOUNT_LT
| op::AMOUNT_EQ
| op::NOT => (1, Some(1)),
_ => (0, None),
/// `outer` is the offset of the enclosing form, for an argument that is no list.
fn filter_of(expr: &Sexpr, outer: usize) -> Result<Filter, ParseError> {
let Sexpr::List(list, at) = expr else {
return Err(failure("expected a list expression", outer));
let at = *at;
let Some(head) = list.first() else {
return Err(failure("empty list", at));
let Sexpr::Symbol(head) = head else {
return Err(failure("expected symbol as first element", at));
let operator = head.to_lowercase();
let args = list.len() - 1;
let (min, max) = arity(&operator);
if args < min || max.is_some_and(|m| args > m) {
return Err(failure(format!("{head} got {args} argument(s)"), at));
match operator.as_str() {
op::AND => children(list, at).map(Filter::And),
op::OR => children(list, at).map(Filter::Or),
op::NOT => {
let inner = list
.get(1)
.ok_or_else(|| failure("not got 0 argument(s)", at))?;
filter_of(inner, at).map(|inner| Filter::Not(Box::new(inner)))
_ => leaf(&operator, list).map_err(|message| failure(message, at)),
fn failure(message: impl Into<String>, at: usize) -> ParseError {
message: message.into(),
fn leaf(operator: &str, list: &[Sexpr]) -> Result<Filter, String> {
op::ACCOUNT_EQ => id_arg(list, 1).map(Filter::AccountEq),
op::ACCOUNT_IN => id_list(list).map(Filter::AccountIn),
op::ACCOUNT_SUBTREE => id_arg(list, 1).map(Filter::AccountSubtree),
op::COUNTERPARTY_EQ => id_arg(list, 1).map(Filter::CounterpartyEq),
op::COUNTERPARTY_IN => id_list(list).map(Filter::CounterpartyIn),
op::COMMODITY_EQ => id_arg(list, 1).map(Filter::CommodityEq),
op::COMMODITY_IN => id_list(list).map(Filter::CommodityIn),
op::AMOUNT_GT => amount_arg(list, 1).map(Filter::AmountGt),
op::AMOUNT_LT => amount_arg(list, 1).map(Filter::AmountLt),
op::AMOUNT_EQ => amount_arg(list, 1).map(Filter::AmountEq),
op::ACCOUNT_TAG_EQ => tag(Entity::Account, list),
op::TRANSACTION_TAG_EQ => tag(Entity::Transaction, list),
op::SPLIT_TAG_EQ => tag(Entity::Split, list),
other => Err(format!("unknown filter operator: {other}")),
impl Filter {
/// The reason the text is not exactly one filter expression of the grammar.
pub fn parse(input: &str) -> Result<Self, String> {
Self::parse_located(input).map_err(|err| err.message)
/// [`Self::parse`] with the offset the text went wrong at.
/// The reason and place the text is not exactly one filter expression.
pub fn parse_located(input: &str) -> Result<Self, ParseError> {
let exprs = read_all(input)?;
// One filter, not the first of several: `(account= a) (account= b)`
// used to parse as `a` alone and drop the rest without a word.
let [expr] = exprs.as_slice() else {
let at = match exprs.get(1) {
Some(Sexpr::List(_, at)) => *at,
_ => 0,
return Err(failure("a filter must be exactly one expression", at));
filter_of(expr, 0)
#[cfg(test)]
#[path = "read_tests.rs"]
mod tests;