Lines
99.03 %
Functions
97.62 %
Branches
100 %
//! Report filter grammar: the operator names the server parser reads and the
//! writer the visual builder emits them with.
use crate::sexpr::escape_str;
mod check;
#[cfg(any(test, feature = "test-fixtures"))]
pub mod fixtures;
mod read;
mod restore;
pub use check::{Fault, Reason, check, check_item};
pub use read::{Amount, Filter, NotAnAmount, ParseError};
pub use restore::{Restored, restore};
pub const AND: &str = "and";
pub const OR: &str = "or";
pub const NOT: &str = "not";
pub const ACCOUNT_EQ: &str = "account=";
pub const ACCOUNT_IN: &str = "account-in";
pub const ACCOUNT_SUBTREE: &str = "account-subtree";
pub const COUNTERPARTY_EQ: &str = "counterparty=";
pub const COUNTERPARTY_IN: &str = "counterparty-in";
pub const COMMODITY_EQ: &str = "commodity=";
pub const COMMODITY_IN: &str = "commodity-in";
pub const AMOUNT_GT: &str = "amount>";
pub const AMOUNT_LT: &str = "amount<";
pub const AMOUNT_EQ: &str = "amount=";
pub const ACCOUNT_TAG_EQ: &str = "account-tag=";
pub const TRANSACTION_TAG_EQ: &str = "transaction-tag=";
pub const SPLIT_TAG_EQ: &str = "split-tag=";
/// Written when the builder holds a condition it cannot express. It is not in
/// the grammar, so the server refuses the request instead of running a broader
/// report than the one asked for.
pub const UNBUILDABLE: &str = "(unbuildable-filter)";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Entity {
Account,
Transaction,
Split,
}
impl Entity {
pub const ALL: [Self; 3] = [Self::Transaction, Self::Split, Self::Account];
#[must_use]
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|entity| entity.name() == name)
/// The name the builder's checkboxes and the tag routes use.
pub fn name(self) -> &'static str {
match self {
Self::Account => "account",
Self::Transaction => "transaction",
Self::Split => "split",
fn operator(self) -> &'static str {
Self::Account => ACCOUNT_TAG_EQ,
Self::Transaction => TRANSACTION_TAG_EQ,
Self::Split => SPLIT_TAG_EQ,
pub enum Logic {
And,
Or,
Not,
impl Logic {
match name {
AND => Some(Self::And),
OR => Some(Self::Or),
NOT => Some(Self::Not),
_ => None,
pub fn operator(self) -> &'static str {
Self::And => AND,
Self::Or => OR,
Self::Not => NOT,
pub enum Comparison {
Gt,
Lt,
Eq,
impl Comparison {
Self::Gt => AMOUNT_GT,
Self::Lt => AMOUNT_LT,
Self::Eq => AMOUNT_EQ,
/// One row or nested group of the visual builder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Item {
Tag {
entities: Vec<Entity>,
name: String,
values: Vec<String>,
},
Account {
id: String,
subtree: bool,
AccountIn {
ids: Vec<String>,
CounterpartyEq {
CounterpartyIn {
CommodityEq {
CommodityIn {
Amount {
comparison: Comparison,
value: Amount,
Group {
logic: Logic,
items: Vec<Item>,
fn call(operator: &str, args: &[String]) -> String {
format!("({operator} {})", args.join(" "))
fn any_of(mut parts: Vec<String>) -> String {
if parts.len() == 1 {
return parts.swap_remove(0);
call(OR, &parts)
fn tag_sexpr(entities: &[Entity], name: &str, values: &[String]) -> String {
let mut seen = Vec::new();
for entity in entities {
if !seen.contains(entity) {
seen.push(*entity);
let per_entity = seen
.into_iter()
.map(|entity| {
let leaves = values
.iter()
.map(|value| call(entity.operator(), &[escape_str(name), escape_str(value)]))
.collect();
any_of(leaves)
})
any_of(per_entity)
fn id_sexpr(operator: &str, id: &str) -> String {
call(operator, &[escape_str(id.trim())])
fn ids_sexpr(operator: &str, ids: &[String]) -> String {
let args: Vec<String> = ids.iter().map(|id| escape_str(id.trim())).collect();
call(operator, &args)
fn amount_sexpr(comparison: Comparison, value: Amount) -> String {
let text = match value.denom() {
1 => value.numer().to_string(),
denom => format!("{}/{denom}", value.numer()),
};
call(comparison.operator(), &[text])
/// The text of a checked row or group.
fn render(item: &Item) -> String {
match item {
Item::Tag {
entities,
name,
values,
} => tag_sexpr(entities, name, values),
Item::Account { id, subtree } => id_sexpr(
if *subtree {
ACCOUNT_SUBTREE
} else {
ACCOUNT_EQ
id,
),
Item::AccountIn { ids } => ids_sexpr(ACCOUNT_IN, ids),
Item::CounterpartyEq { id } => id_sexpr(COUNTERPARTY_EQ, id),
Item::CounterpartyIn { ids } => ids_sexpr(COUNTERPARTY_IN, ids),
Item::CommodityEq { id } => id_sexpr(COMMODITY_EQ, id),
Item::CommodityIn { ids } => ids_sexpr(COMMODITY_IN, ids),
Item::Amount { comparison, value } => amount_sexpr(*comparison, *value),
Item::Group { logic, items } => render_group(*logic, items),
fn render_group(logic: Logic, items: &[Item]) -> String {
let mut parts: Vec<String> = items.iter().map(render).collect();
match (logic, parts.len()) {
(Logic::Not, _) => call(NOT, &parts),
(_, 1) => parts.swap_remove(0),
(logic, _) => call(logic.operator(), &parts),
/// The filter text for one builder row or group.
///
/// # Errors
/// The `Fault` of a row or group no condition can be built from.
pub fn item_sexpr(item: &Item) -> Result<String, Fault> {
check_item(item)?;
Ok(render(item))
/// The filter text for the rows of the builder; `None` for an empty builder,
/// which means no filter. A single child stands for its group.
/// The `Fault` of the first row or group no condition can be built from.
pub fn group_sexpr(logic: Logic, items: &[Item]) -> Result<Option<String>, Fault> {
check(logic, items)?;
Ok((!items.is_empty()).then(|| render_group(logic, items)))
#[cfg(test)]
#[path = "filter_tests.rs"]
mod tests;