1use super::{self as op, Entity};
4
5const MAX_DEPTH: usize = 64;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct Amount {
12 numer: i64,
13 denom: i64,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct NotAnAmount;
19
20impl std::fmt::Display for NotAnAmount {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 f.write_str("not a number")
23 }
24}
25
26impl Amount {
27 #[must_use]
30 pub fn new(numer: i64, denom: i64) -> Option<Self> {
31 (denom > 0 && numer != i64::MIN).then_some(Self { numer, denom })
32 }
33
34 pub fn parse(text: &str) -> Result<Self, NotAnAmount> {
40 Self::read(text).ok_or(NotAnAmount)
41 }
42
43 fn read(text: &str) -> Option<Self> {
44 let (negative, body) = match text.strip_prefix('-') {
45 Some(body) => (true, body),
46 None => (false, text.strip_prefix('+').unwrap_or(text)),
47 };
48 let (body, percent) = body.strip_suffix('%').map_or((body, false), |b| (b, true));
49 let (mut numer, mut denom) = match body.split_once('/') {
50 Some((n, d)) => (digits(n)?, digits(d).filter(|d| *d != 0)?),
51 None => decimal(body)?,
52 };
53 if percent {
54 denom = denom.checked_mul(100)?;
55 }
56 let divisor = gcd(numer, denom).max(1);
57 numer /= divisor;
58 denom /= divisor;
59 Self::new(if negative { -numer } else { numer }, denom)
60 }
61
62 #[must_use]
63 pub fn numer(self) -> i64 {
64 self.numer
65 }
66
67 #[must_use]
68 pub fn denom(self) -> i64 {
69 self.denom
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Filter {
76 AccountEq(String),
77 AccountIn(Vec<String>),
78 AccountSubtree(String),
79 CounterpartyEq(String),
80 CounterpartyIn(Vec<String>),
81 CommodityEq(String),
82 CommodityIn(Vec<String>),
83 AmountGt(Amount),
84 AmountLt(Amount),
85 AmountEq(Amount),
86 Tag {
87 entity: Entity,
88 name: String,
89 value: String,
90 },
91 And(Vec<Filter>),
92 Or(Vec<Filter>),
93 Not(Box<Filter>),
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct ParseError {
100 pub message: String,
101 pub at: usize,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
105enum Sexpr {
106 Symbol(String),
107 Str(String),
108 Number(Amount),
109 List(Vec<Sexpr>, usize),
111}
112
113struct Cursor<'a> {
114 rest: &'a str,
115 len: usize,
116}
117
118impl Cursor<'_> {
119 fn skip_blank(&mut self) {
120 loop {
121 self.rest = self.rest.trim_start();
122 match self.rest.strip_prefix(';') {
123 Some(comment) => {
124 self.rest = comment.split_once('\n').map_or("", |(_, tail)| tail);
125 }
126 None => return,
127 }
128 }
129 }
130
131 fn offset(&self) -> usize {
132 self.len - self.rest.len()
133 }
134
135 fn error(&self, message: &str) -> ParseError {
136 ParseError {
137 message: message.to_owned(),
138 at: self.offset(),
139 }
140 }
141
142 fn expr(&mut self, depth: usize) -> Result<Sexpr, ParseError> {
143 if depth > MAX_DEPTH {
144 return Err(self.error("filter is nested too deeply"));
145 }
146 if let Some(tail) = self.rest.strip_prefix('(') {
147 let at = self.offset();
148 self.rest = tail;
149 return self.list(depth, at);
150 }
151 if let Some(tail) = self.rest.strip_prefix('"') {
152 let at = self.offset();
153 self.rest = tail;
154 return self.string(at).map(Sexpr::Str);
155 }
156 if self.rest.starts_with(')') {
157 return Err(self.error("unexpected )"));
158 }
159 let end = self
160 .rest
161 .find(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | '"' | ';'))
162 .unwrap_or(self.rest.len());
163 let (atom, tail) = self.rest.split_at(end);
164 self.rest = tail;
165 Ok(Amount::parse(atom).map_or_else(|_| Sexpr::Symbol(atom.to_owned()), Sexpr::Number))
166 }
167
168 fn list(&mut self, depth: usize, at: usize) -> Result<Sexpr, ParseError> {
169 let mut items = Vec::new();
170 loop {
171 self.skip_blank();
172 if let Some(tail) = self.rest.strip_prefix(')') {
173 self.rest = tail;
174 return Ok(Sexpr::List(items, at));
175 }
176 if self.rest.is_empty() {
177 return Err(self.error("missing )"));
178 }
179 items.push(self.expr(depth + 1)?);
180 }
181 }
182
183 fn string(&mut self, at: usize) -> Result<String, ParseError> {
184 let mut out = String::new();
185 let mut chars = self.rest.char_indices();
186 while let Some((at, c)) = chars.next() {
187 match c {
188 '"' => {
189 self.rest = &self.rest[at + 1..];
190 return Ok(out);
191 }
192 '\\' => match chars.next() {
193 Some((_, 'n')) => out.push('\n'),
194 Some((_, 't')) => out.push('\t'),
195 Some((_, 'r')) => out.push('\r'),
196 Some((_, c @ ('\\' | '"'))) => out.push(c),
197 Some((_, other)) => {
198 out.push('\\');
199 out.push(other);
200 }
201 None => break,
202 },
203 other => out.push(other),
204 }
205 }
206 Err(ParseError {
207 message: "unterminated string".to_owned(),
208 at,
209 })
210 }
211}
212
213fn read_all(input: &str) -> Result<Vec<Sexpr>, ParseError> {
214 let mut cursor = Cursor {
215 rest: input,
216 len: input.len(),
217 };
218 let mut exprs = Vec::new();
219 loop {
220 cursor.skip_blank();
221 if cursor.rest.is_empty() {
222 return Ok(exprs);
223 }
224 exprs.push(cursor.expr(0)?);
225 }
226}
227
228fn digits(text: &str) -> Option<i64> {
229 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
230 return None;
231 }
232 text.parse().ok()
233}
234
235fn decimal(text: &str) -> Option<(i64, i64)> {
236 let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
237 if whole.is_empty() && fraction.is_empty() {
238 return None;
239 }
240 let scale = 10_i64.checked_pow(u32::try_from(fraction.len()).ok()?)?;
241 let whole = if whole.is_empty() { 0 } else { digits(whole)? };
242 let fraction = if fraction.is_empty() {
243 0
244 } else {
245 digits(fraction)?
246 };
247 Some((whole.checked_mul(scale)?.checked_add(fraction)?, scale))
248}
249
250fn gcd(a: i64, b: i64) -> i64 {
251 if b == 0 { a } else { gcd(b, a % b) }
252}
253
254fn id_arg(list: &[Sexpr], idx: usize) -> Result<String, String> {
255 match list.get(idx) {
256 Some(Sexpr::Str(s) | Sexpr::Symbol(s)) => Ok(s.clone()),
257 _ => Err(format!("expected UUID string at position {idx}")),
258 }
259}
260
261fn id_list(list: &[Sexpr]) -> Result<Vec<String>, String> {
262 list[1..]
263 .iter()
264 .map(|expr| match expr {
265 Sexpr::Str(s) | Sexpr::Symbol(s) => Ok(s.clone()),
266 _ => Err("expected UUID string".to_owned()),
267 })
268 .collect()
269}
270
271fn amount_arg(list: &[Sexpr], idx: usize) -> Result<Amount, String> {
272 match list.get(idx) {
273 Some(Sexpr::Number(amount)) => Ok(*amount),
274 _ => Err(format!("expected number at position {idx}")),
275 }
276}
277
278fn string_arg(list: &[Sexpr], idx: usize) -> Result<String, String> {
282 match list.get(idx) {
283 Some(Sexpr::Str(s)) => Ok(s.clone()),
284 _ => Err(format!("expected a string at position {idx}")),
285 }
286}
287
288fn tag(entity: Entity, list: &[Sexpr]) -> Result<Filter, String> {
289 Ok(Filter::Tag {
290 entity,
291 name: string_arg(list, 1)?,
292 value: string_arg(list, 2)?,
293 })
294}
295
296fn children(list: &[Sexpr], at: usize) -> Result<Vec<Filter>, ParseError> {
297 list[1..].iter().map(|expr| filter_of(expr, at)).collect()
298}
299
300fn arity(operator: &str) -> (usize, Option<usize>) {
303 match operator {
304 op::AND | op::OR => (0, None),
305 op::ACCOUNT_IN | op::COUNTERPARTY_IN | op::COMMODITY_IN => (1, None),
306 op::ACCOUNT_TAG_EQ | op::TRANSACTION_TAG_EQ | op::SPLIT_TAG_EQ => (2, Some(2)),
307 op::ACCOUNT_EQ
308 | op::ACCOUNT_SUBTREE
309 | op::COUNTERPARTY_EQ
310 | op::COMMODITY_EQ
311 | op::AMOUNT_GT
312 | op::AMOUNT_LT
313 | op::AMOUNT_EQ
314 | op::NOT => (1, Some(1)),
315 _ => (0, None),
316 }
317}
318
319fn filter_of(expr: &Sexpr, outer: usize) -> Result<Filter, ParseError> {
321 let Sexpr::List(list, at) = expr else {
322 return Err(failure("expected a list expression", outer));
323 };
324 let at = *at;
325 let Some(head) = list.first() else {
326 return Err(failure("empty list", at));
327 };
328 let Sexpr::Symbol(head) = head else {
329 return Err(failure("expected symbol as first element", at));
330 };
331 let operator = head.to_lowercase();
332 let args = list.len() - 1;
333 let (min, max) = arity(&operator);
334 if args < min || max.is_some_and(|m| args > m) {
335 return Err(failure(format!("{head} got {args} argument(s)"), at));
336 }
337 match operator.as_str() {
338 op::AND => children(list, at).map(Filter::And),
339 op::OR => children(list, at).map(Filter::Or),
340 op::NOT => {
341 let inner = list
342 .get(1)
343 .ok_or_else(|| failure("not got 0 argument(s)", at))?;
344 filter_of(inner, at).map(|inner| Filter::Not(Box::new(inner)))
345 }
346 _ => leaf(&operator, list).map_err(|message| failure(message, at)),
347 }
348}
349
350fn failure(message: impl Into<String>, at: usize) -> ParseError {
351 ParseError {
352 message: message.into(),
353 at,
354 }
355}
356
357fn leaf(operator: &str, list: &[Sexpr]) -> Result<Filter, String> {
358 match operator {
359 op::ACCOUNT_EQ => id_arg(list, 1).map(Filter::AccountEq),
360 op::ACCOUNT_IN => id_list(list).map(Filter::AccountIn),
361 op::ACCOUNT_SUBTREE => id_arg(list, 1).map(Filter::AccountSubtree),
362 op::COUNTERPARTY_EQ => id_arg(list, 1).map(Filter::CounterpartyEq),
363 op::COUNTERPARTY_IN => id_list(list).map(Filter::CounterpartyIn),
364 op::COMMODITY_EQ => id_arg(list, 1).map(Filter::CommodityEq),
365 op::COMMODITY_IN => id_list(list).map(Filter::CommodityIn),
366 op::AMOUNT_GT => amount_arg(list, 1).map(Filter::AmountGt),
367 op::AMOUNT_LT => amount_arg(list, 1).map(Filter::AmountLt),
368 op::AMOUNT_EQ => amount_arg(list, 1).map(Filter::AmountEq),
369 op::ACCOUNT_TAG_EQ => tag(Entity::Account, list),
370 op::TRANSACTION_TAG_EQ => tag(Entity::Transaction, list),
371 op::SPLIT_TAG_EQ => tag(Entity::Split, list),
372 other => Err(format!("unknown filter operator: {other}")),
373 }
374}
375
376impl Filter {
377 pub fn parse(input: &str) -> Result<Self, String> {
380 Self::parse_located(input).map_err(|err| err.message)
381 }
382
383 pub fn parse_located(input: &str) -> Result<Self, ParseError> {
388 let exprs = read_all(input)?;
389 let [expr] = exprs.as_slice() else {
392 let at = match exprs.get(1) {
393 Some(Sexpr::List(_, at)) => *at,
394 _ => 0,
395 };
396 return Err(failure("a filter must be exactly one expression", at));
397 };
398 filter_of(expr, 0)
399 }
400}
401
402#[cfg(test)]
403#[path = "read_tests.rs"]
404mod tests;