1
//! Reader for the filter s-expression: text to a typed [`Filter`] tree.
2

            
3
use super::{self as op, Entity};
4

            
5
/// Nesting the reader accepts; deeper input would exhaust the native stack of
6
/// every recursive consumer of the tree.
7
const MAX_DEPTH: usize = 64;
8

            
9
/// A rational with a positive denominator.
10
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11
pub struct Amount {
12
    numer: i64,
13
    denom: i64,
14
}
15

            
16
/// The text is not in the number grammar of [`Amount::parse`].
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub struct NotAnAmount;
19

            
20
impl std::fmt::Display for NotAnAmount {
21
1
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22
1
        f.write_str("not a number")
23
1
    }
24
}
25

            
26
impl Amount {
27
    /// `None` unless the denominator is positive; `i64::MIN` has no written
28
    /// form the reader accepts.
29
    #[must_use]
30
38317
    pub fn new(numer: i64, denom: i64) -> Option<Self> {
31
38317
        (denom > 0 && numer != i64::MIN).then_some(Self { numer, denom })
32
38317
    }
33

            
34
    /// The reader's number grammar: `n`, `n/d`, decimals and `%`, signed,
35
    /// reduced to lowest terms.
36
    ///
37
    /// # Errors
38
    /// `NotAnAmount` for anything else, a zero denominator or an overflow.
39
198502
    pub fn parse(text: &str) -> Result<Self, NotAnAmount> {
40
198502
        Self::read(text).ok_or(NotAnAmount)
41
198502
    }
42

            
43
198502
    fn read(text: &str) -> Option<Self> {
44
198502
        let (negative, body) = match text.strip_prefix('-') {
45
5395
            Some(body) => (true, body),
46
193107
            None => (false, text.strip_prefix('+').unwrap_or(text)),
47
        };
48
198502
        let (body, percent) = body.strip_suffix('%').map_or((body, false), |b| (b, true));
49
198502
        let (mut numer, mut denom) = match body.split_once('/') {
50
9049
            Some((n, d)) => (digits(n)?, digits(d).filter(|d| *d != 0)?),
51
189453
            None => decimal(body)?,
52
        };
53
35401
        if percent {
54
1349
            denom = denom.checked_mul(100)?;
55
34052
        }
56
35401
        let divisor = gcd(numer, denom).max(1);
57
35401
        numer /= divisor;
58
35401
        denom /= divisor;
59
35401
        Self::new(if negative { -numer } else { numer }, denom)
60
198502
    }
61

            
62
    #[must_use]
63
22099
    pub fn numer(self) -> i64 {
64
22099
        self.numer
65
22099
    }
66

            
67
    #[must_use]
68
22099
    pub fn denom(self) -> i64 {
69
22099
        self.denom
70
22099
    }
71
}
72

            
73
/// A parsed filter. Ids stay text: the server checks them as UUIDs.
74
#[derive(Debug, Clone, PartialEq, Eq)]
75
pub 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
/// Why filter text did not parse, and the byte offset it went wrong at: the
97
/// offending text, or the start of the form whose argument is bad.
98
#[derive(Debug, Clone, PartialEq, Eq)]
99
pub struct ParseError {
100
    pub message: String,
101
    pub at: usize,
102
}
103

            
104
#[derive(Debug, Clone, PartialEq, Eq)]
105
enum Sexpr {
106
    Symbol(String),
107
    Str(String),
108
    Number(Amount),
109
    /// The items and the byte offset the list opens at.
110
    List(Vec<Sexpr>, usize),
111
}
112

            
113
struct Cursor<'a> {
114
    rest: &'a str,
115
    len: usize,
116
}
117

            
118
impl Cursor<'_> {
119
682167
    fn skip_blank(&mut self) {
120
        loop {
121
682169
            self.rest = self.rest.trim_start();
122
682169
            match self.rest.strip_prefix(';') {
123
                Some(comment) => {
124
2
                    self.rest = comment.split_once('\n').map_or("", |(_, tail)| tail);
125
                }
126
682167
                None => return,
127
            }
128
        }
129
682167
    }
130

            
131
269457
    fn offset(&self) -> usize {
132
269457
        self.len - self.rest.len()
133
269457
    }
134

            
135
2502
    fn error(&self, message: &str) -> ParseError {
136
2502
        ParseError {
137
2502
            message: message.to_owned(),
138
2502
            at: self.offset(),
139
2502
        }
140
2502
    }
141

            
142
460248
    fn expr(&mut self, depth: usize) -> Result<Sexpr, ParseError> {
143
460248
        if depth > MAX_DEPTH {
144
193
            return Err(self.error("filter is nested too deeply"));
145
460055
        }
146
460055
        if let Some(tail) = self.rest.strip_prefix('(') {
147
160549
            let at = self.offset();
148
160549
            self.rest = tail;
149
160549
            return self.list(depth, at);
150
299506
        }
151
299506
        if let Some(tail) = self.rest.strip_prefix('"') {
152
106406
            let at = self.offset();
153
106406
            self.rest = tail;
154
106406
            return self.string(at).map(Sexpr::Str);
155
193100
        }
156
193100
        if self.rest.starts_with(')') {
157
2
            return Err(self.error("unexpected )"));
158
193098
        }
159
193098
        let end = self
160
193098
            .rest
161
1477655
            .find(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | '"' | ';'))
162
193098
            .unwrap_or(self.rest.len());
163
193098
        let (atom, tail) = self.rest.split_at(end);
164
193098
        self.rest = tail;
165
193098
        Ok(Amount::parse(atom).map_or_else(|_| Sexpr::Symbol(atom.to_owned()), Sexpr::Number))
166
460248
    }
167

            
168
160549
    fn list(&mut self, depth: usize, at: usize) -> Result<Sexpr, ParseError> {
169
160549
        let mut items = Vec::new();
170
        loop {
171
531635
            self.skip_blank();
172
531635
            if let Some(tail) = self.rest.strip_prefix(')') {
173
145695
                self.rest = tail;
174
145695
                return Ok(Sexpr::List(items, at));
175
385940
            }
176
385940
            if self.rest.is_empty() {
177
2307
                return Err(self.error("missing )"));
178
383633
            }
179
383633
            items.push(self.expr(depth + 1)?);
180
        }
181
160549
    }
182

            
183
106406
    fn string(&mut self, at: usize) -> Result<String, ParseError> {
184
106406
        let mut out = String::new();
185
106406
        let mut chars = self.rest.char_indices();
186
653322
        while let Some((at, c)) = chars.next() {
187
653320
            match c {
188
                '"' => {
189
106404
                    self.rest = &self.rest[at + 1..];
190
106404
                    return Ok(out);
191
                }
192
3275
                '\\' => match chars.next() {
193
2
                    Some((_, 'n')) => out.push('\n'),
194
                    Some((_, 't')) => out.push('\t'),
195
1
                    Some((_, 'r')) => out.push('\r'),
196
3272
                    Some((_, c @ ('\\' | '"'))) => out.push(c),
197
                    Some((_, other)) => {
198
                        out.push('\\');
199
                        out.push(other);
200
                    }
201
                    None => break,
202
                },
203
543641
                other => out.push(other),
204
            }
205
        }
206
2
        Err(ParseError {
207
2
            message: "unterminated string".to_owned(),
208
2
            at,
209
2
        })
210
106406
    }
211
}
212

            
213
76421
fn read_all(input: &str) -> Result<Vec<Sexpr>, ParseError> {
214
76421
    let mut cursor = Cursor {
215
76421
        rest: input,
216
76421
        len: input.len(),
217
76421
    };
218
76421
    let mut exprs = Vec::new();
219
    loop {
220
150532
        cursor.skip_blank();
221
150532
        if cursor.rest.is_empty() {
222
73917
            return Ok(exprs);
223
76615
        }
224
76615
        exprs.push(cursor.expr(0)?);
225
    }
226
76421
}
227

            
228
209091
fn digits(text: &str) -> Option<i64> {
229
223781
    if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
230
162899
        return None;
231
46192
    }
232
46192
    text.parse().ok()
233
209091
}
234

            
235
189453
fn decimal(text: &str) -> Option<(i64, i64)> {
236
189453
    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
237
189453
    if whole.is_empty() && fraction.is_empty() {
238
196
        return None;
239
189257
    }
240
189257
    let scale = 10_i64.checked_pow(u32::try_from(fraction.len()).ok()?)?;
241
189257
    let whole = if whole.is_empty() { 0 } else { digits(whole)? };
242
26357
    let fraction = if fraction.is_empty() {
243
24618
        0
244
    } else {
245
1739
        digits(fraction)?
246
    };
247
26356
    Some((whole.checked_mul(scale)?.checked_add(fraction)?, scale))
248
189453
}
249

            
250
88324
fn gcd(a: i64, b: i64) -> i64 {
251
88324
    if b == 0 { a } else { gcd(b, a % b) }
252
88324
}
253

            
254
26940
fn id_arg(list: &[Sexpr], idx: usize) -> Result<String, String> {
255
26940
    match list.get(idx) {
256
26939
        Some(Sexpr::Str(s) | Sexpr::Symbol(s)) => Ok(s.clone()),
257
1
        _ => Err(format!("expected UUID string at position {idx}")),
258
    }
259
26940
}
260

            
261
20588
fn id_list(list: &[Sexpr]) -> Result<Vec<String>, String> {
262
20588
    list[1..]
263
20588
        .iter()
264
30789
        .map(|expr| match expr {
265
30788
            Sexpr::Str(s) | Sexpr::Symbol(s) => Ok(s.clone()),
266
1
            _ => Err("expected UUID string".to_owned()),
267
30789
        })
268
        .collect()
269
20588
}
270

            
271
28474
fn amount_arg(list: &[Sexpr], idx: usize) -> Result<Amount, String> {
272
28474
    match list.get(idx) {
273
28274
        Some(Sexpr::Number(amount)) => Ok(*amount),
274
200
        _ => Err(format!("expected number at position {idx}")),
275
    }
276
28474
}
277

            
278
/// Tag names and values are literals only: the old reader folded a bare
279
/// symbol to upper case, so reading one as written would silently select
280
/// other rows.
281
48316
fn string_arg(list: &[Sexpr], idx: usize) -> Result<String, String> {
282
48316
    match list.get(idx) {
283
48115
        Some(Sexpr::Str(s)) => Ok(s.clone()),
284
201
        _ => Err(format!("expected a string at position {idx}")),
285
    }
286
48316
}
287

            
288
24256
fn tag(entity: Entity, list: &[Sexpr]) -> Result<Filter, String> {
289
    Ok(Filter::Tag {
290
24256
        entity,
291
24256
        name: string_arg(list, 1)?,
292
24060
        value: string_arg(list, 2)?,
293
    })
294
24256
}
295

            
296
33492
fn children(list: &[Sexpr], at: usize) -> Result<Vec<Filter>, ParseError> {
297
64460
    list[1..].iter().map(|expr| filter_of(expr, at)).collect()
298
33492
}
299

            
300
/// Extra arguments used to be dropped in silence: `(amount> 0 (amount< 100))`
301
/// became `amount > 0`, a strictly broader report than the one asked for.
302
144337
fn arity(operator: &str) -> (usize, Option<usize>) {
303
144337
    match operator {
304
33492
        op::AND | op::OR => (0, None),
305
20973
        op::ACCOUNT_IN | op::COUNTERPARTY_IN | op::COMMODITY_IN => (1, None),
306
24449
        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
63308
        | op::NOT => (1, Some(1)),
315
2115
        _ => (0, None),
316
    }
317
144337
}
318

            
319
/// `outer` is the offset of the enclosing form, for an argument that is no list.
320
145111
fn filter_of(expr: &Sexpr, outer: usize) -> Result<Filter, ParseError> {
321
145111
    let Sexpr::List(list, at) = expr else {
322
579
        return Err(failure("expected a list expression", outer));
323
    };
324
144532
    let at = *at;
325
144532
    let Some(head) = list.first() else {
326
193
        return Err(failure("empty list", at));
327
    };
328
144339
    let Sexpr::Symbol(head) = head else {
329
2
        return Err(failure("expected symbol as first element", at));
330
    };
331
144337
    let operator = head.to_lowercase();
332
144337
    let args = list.len() - 1;
333
144337
    let (min, max) = arity(&operator);
334
144337
    if args < min || max.is_some_and(|m| args > m) {
335
1158
        return Err(failure(format!("{head} got {args} argument(s)"), at));
336
143179
    }
337
143179
    match operator.as_str() {
338
18674
        op::AND => children(list, at).map(Filter::And),
339
14818
        op::OR => children(list, at).map(Filter::Or),
340
        op::NOT => {
341
7314
            let inner = list
342
7314
                .get(1)
343
                .ok_or_else(|| failure("not got 0 argument(s)", at))?;
344
7314
            filter_of(inner, at).map(|inner| Filter::Not(Box::new(inner)))
345
        }
346
102373
        _ => leaf(&operator, list).map_err(|message| failure(message, at)),
347
    }
348
145111
}
349

            
350
5030
fn failure(message: impl Into<String>, at: usize) -> ParseError {
351
5030
    ParseError {
352
5030
        message: message.into(),
353
5030
        at,
354
5030
    }
355
5030
}
356

            
357
102373
fn leaf(operator: &str, list: &[Sexpr]) -> Result<Filter, String> {
358
102373
    match operator {
359
10970
        op::ACCOUNT_EQ => id_arg(list, 1).map(Filter::AccountEq),
360
9425
        op::ACCOUNT_IN => id_list(list).map(Filter::AccountIn),
361
4425
        op::ACCOUNT_SUBTREE => id_arg(list, 1).map(Filter::AccountSubtree),
362
6160
        op::COUNTERPARTY_EQ => id_arg(list, 1).map(Filter::CounterpartyEq),
363
5004
        op::COUNTERPARTY_IN => id_list(list).map(Filter::CounterpartyIn),
364
5385
        op::COMMODITY_EQ => id_arg(list, 1).map(Filter::CommodityEq),
365
6159
        op::COMMODITY_IN => id_list(list).map(Filter::CommodityIn),
366
12702
        op::AMOUNT_GT => amount_arg(list, 1).map(Filter::AmountGt),
367
9614
        op::AMOUNT_LT => amount_arg(list, 1).map(Filter::AmountLt),
368
6158
        op::AMOUNT_EQ => amount_arg(list, 1).map(Filter::AmountEq),
369
8077
        op::ACCOUNT_TAG_EQ => tag(Entity::Account, list),
370
3462
        op::TRANSACTION_TAG_EQ => tag(Entity::Transaction, list),
371
12717
        op::SPLIT_TAG_EQ => tag(Entity::Split, list),
372
2115
        other => Err(format!("unknown filter operator: {other}")),
373
    }
374
102373
}
375

            
376
impl Filter {
377
    /// # Errors
378
    /// The reason the text is not exactly one filter expression of the grammar.
379
66813
    pub fn parse(input: &str) -> Result<Self, String> {
380
66813
        Self::parse_located(input).map_err(|err| err.message)
381
66813
    }
382

            
383
    /// [`Self::parse`] with the offset the text went wrong at.
384
    ///
385
    /// # Errors
386
    /// The reason and place the text is not exactly one filter expression.
387
76421
    pub fn parse_located(input: &str) -> Result<Self, ParseError> {
388
76421
        let exprs = read_all(input)?;
389
        // One filter, not the first of several: `(account= a) (account= b)`
390
        // used to parse as `a` alone and drop the rest without a word.
391
73917
        let [expr] = exprs.as_slice() else {
392
580
            let at = match exprs.get(1) {
393
386
                Some(Sexpr::List(_, at)) => *at,
394
194
                _ => 0,
395
            };
396
580
            return Err(failure("a filter must be exactly one expression", at));
397
        };
398
73337
        filter_of(expr, 0)
399
76421
    }
400
}
401

            
402
#[cfg(test)]
403
#[path = "read_tests.rs"]
404
mod tests;