rustledger-core 0.16.0

Core types for rustledger: Amount, Position, Inventory, and all directive types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! `ShiftSpans` impls for every type reachable from a `Directive`.
//!
//! The discipline introduced in round 18 lifted span shifting out of
//! the parser (monolithic `shift_directive_inner_spans` with per-
//! variant named-field destructure) and into the type system. Round
//! 19 closes the residual hole: enum-variant payloads are now bound
//! BY NAME and dispatched via `value.shift_spans(shift)` rather than
//! via a wildcard `Self::Variant(_)` arm. A future payload type
//! change (e.g., wrapping a leaf `String` payload in `Spanned<String>`)
//! routes through the wrapper's `ShiftSpans` impl automatically —
//! no edit to this file required, no silent discipline gap.
//!
//! Each type that appears anywhere inside a `Directive` payload
//! either:
//!
//! 1. **Carries no spans** — implements `ShiftSpans` as a no-op via
//!    the `impl_shift_spans_noop!` macro (for foreign leaf types
//!    like `Decimal`, `NaiveDate`) or via an explicit empty body
//!    with exhaustive structural destructure (for variant enums
//!    whose payloads currently have no spans, like `PriceKind`).
//!
//! 2. **Has structural payloads** — implements `ShiftSpans` by
//!    destructuring every field/variant BY NAME and dispatching
//!    into the binding's own impl. Compound shapes (`Vec`,
//!    `Option`, `Box`, `Spanned`, `HashMap`) are handled by blanket
//!    impls in `crate::span` and below.
//!
//! All impls live here (not next to each type) so the discipline is
//! reviewable in one place; a contributor adding a new directive-
//! payload type can use the existing impls as a template.

use crate::cost::{BookedCost, Cost, CostNumber, CostSpec};
use crate::directive::{
    Balance, Close, Commodity, Custom, Directive, Document, Event, MetaValue, Note, Open, Pad,
    Posting, Price, PriceAnnotation, PriceKind, Query, Transaction,
};
use crate::identifiers::{Account, Currency, Link, Tag};
use crate::{Amount, IncompleteAmount, InternedStr, ShiftSpans, Span};

// --- HashMap blanket impl ------------------------------------------
//
// Round-19 replacement for the pre-19 `shift_metadata` free fn. The
// orphan rule allows the impl because rustledger-core owns the
// `ShiftSpans` trait — the type can be foreign. The `S` type
// parameter covers both `std::collections::HashMap`'s default
// `RandomState` and `rustc_hash::FxHashMap`'s `FxBuildHasher`, so
// `Metadata = FxHashMap<String, MetaValue>` is covered without a
// separate impl.
//
// Keys are not visited today (`Metadata`'s key is `String`, span-
// free). If a future Metadata changes its key type to something
// span-bearing, extend this impl to also dispatch on keys via
// `keys_mut()` — but that doesn't exist on HashMap; the impl would
// need to rebuild via `drain()`+`insert()`.

impl<K, V: ShiftSpans, S> ShiftSpans for std::collections::HashMap<K, V, S> {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        for value in self.values_mut() {
            value.shift_spans(shift);
        }
    }
}

// --- External / foreign leaf types ---------------------------------
//
// Types from std / outside crates that appear in directive payloads
// but carry no spans. Grouped here so the "we treat these as span-
// free" set is easy to audit.

crate::impl_shift_spans_noop!(
    rust_decimal::Decimal,
    jiff::civil::Date,
    char,
    f32,
    f64,
    InternedStr,
    Account,
    Currency,
    Tag,
    Link,
);

// --- Amount / IncompleteAmount -------------------------------------

impl ShiftSpans for Amount {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self { number, currency } = self;
        number.shift_spans(shift);
        currency.shift_spans(shift);
    }
}

impl ShiftSpans for IncompleteAmount {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        // Round-19 discipline: bind each variant payload BY NAME and
        // dispatch via the payload's own impl. Pre-round-19 used
        // `Self::Variant(_)` which silently bound any payload type
        // (including future Spanned wrappers) without dispatching.
        match self {
            Self::Complete(amount) => amount.shift_spans(shift),
            Self::NumberOnly(number) => number.shift_spans(shift),
            Self::CurrencyOnly(currency) => currency.shift_spans(shift),
        }
    }
}

// --- Cost / CostSpec / CostNumber ----------------------------------

impl ShiftSpans for Cost {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            number,
            currency,
            date,
            label,
        } = self;
        number.shift_spans(shift);
        currency.shift_spans(shift);
        date.shift_spans(shift);
        label.shift_spans(shift);
    }
}

impl ShiftSpans for CostSpec {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            number,
            currency,
            date,
            label,
            merge,
        } = self;
        number.shift_spans(shift);
        currency.shift_spans(shift);
        date.shift_spans(shift);
        label.shift_spans(shift);
        merge.shift_spans(shift);
    }
}

impl ShiftSpans for CostNumber {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        match self {
            Self::PerUnit { value } | Self::Total { value } => value.shift_spans(shift),
            Self::PerUnitFromTotal(booked) => booked.shift_spans(shift),
        }
    }
}

impl ShiftSpans for BookedCost {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self { per_unit, total } = self;
        per_unit.shift_spans(shift);
        total.shift_spans(shift);
    }
}

// --- PriceAnnotation -----------------------------------------------

impl ShiftSpans for PriceAnnotation {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self { kind, amount } = self;
        kind.shift_spans(shift);
        amount.shift_spans(shift);
    }
}

impl ShiftSpans for PriceKind {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, _: &F) {
        // Unit-like variants — no payload to dispatch into. The
        // exhaustive match still gates against added variants.
        match self {
            Self::Unit | Self::Total => {}
        }
    }
}

// --- MetaValue -----------------------------------------------------

impl ShiftSpans for MetaValue {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        // Round-19 discipline: bind each variant payload BY NAME and
        // dispatch via the payload's own `ShiftSpans` impl. Pre-
        // round-19's `Self::String(_) | Self::Account(_) | ...`
        // silently bound any payload type to `_` without dispatching
        // — a future `MetaValue::String(Spanned<String>)` would have
        // kept the new span in the BOM-stripped frame undetected.
        //
        // Today every payload type is a no-span leaf (`String`,
        // `Account`, `Currency`, `Tag`, `Link`, `NaiveDate`,
        // `Decimal`, `bool`, `Amount`), so each binding's dispatch
        // resolves to a no-op impl and the body is still a runtime
        // no-op. Wrapping any payload in a `Spanned<T>` automatically
        // routes through the wrapper's recursing impl — no edit to
        // this file required.
        match self {
            Self::String(s) => s.shift_spans(shift),
            Self::Account(a) => a.shift_spans(shift),
            Self::Currency(c) => c.shift_spans(shift),
            Self::Tag(t) => t.shift_spans(shift),
            Self::Link(l) => l.shift_spans(shift),
            Self::Date(d) => d.shift_spans(shift),
            Self::Number(n) => n.shift_spans(shift),
            Self::Bool(b) => b.shift_spans(shift),
            Self::Amount(a) => a.shift_spans(shift),
            Self::None => {}
        }
    }
}

// --- Posting --------------------------------------------------------

impl ShiftSpans for Posting {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            account,
            units,
            cost,
            price,
            flag,
            meta,
            comments,
            trailing_comments,
        } = self;
        account.shift_spans(shift);
        units.shift_spans(shift);
        cost.shift_spans(shift);
        price.shift_spans(shift);
        flag.shift_spans(shift);
        meta.shift_spans(shift);
        comments.shift_spans(shift);
        trailing_comments.shift_spans(shift);
    }
}

// --- Directive variant structs -------------------------------------

impl ShiftSpans for Transaction {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            flag,
            payee,
            narration,
            tags,
            links,
            meta,
            postings,
            trailing_comments,
        } = self;
        date.shift_spans(shift);
        flag.shift_spans(shift);
        payee.shift_spans(shift);
        narration.shift_spans(shift);
        tags.shift_spans(shift);
        links.shift_spans(shift);
        meta.shift_spans(shift);
        postings.shift_spans(shift);
        trailing_comments.shift_spans(shift);
    }
}

impl ShiftSpans for Open {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            account,
            currencies,
            booking,
            meta,
        } = self;
        date.shift_spans(shift);
        account.shift_spans(shift);
        currencies.shift_spans(shift);
        booking.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Close {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            account,
            meta,
        } = self;
        date.shift_spans(shift);
        account.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Balance {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            account,
            amount,
            tolerance,
            meta,
        } = self;
        date.shift_spans(shift);
        account.shift_spans(shift);
        amount.shift_spans(shift);
        tolerance.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Pad {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            account,
            source_account,
            meta,
        } = self;
        date.shift_spans(shift);
        account.shift_spans(shift);
        source_account.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Note {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            account,
            comment,
            meta,
        } = self;
        date.shift_spans(shift);
        account.shift_spans(shift);
        comment.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Document {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            account,
            path,
            tags,
            links,
            meta,
        } = self;
        date.shift_spans(shift);
        account.shift_spans(shift);
        path.shift_spans(shift);
        tags.shift_spans(shift);
        links.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Price {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            currency,
            amount,
            meta,
        } = self;
        date.shift_spans(shift);
        currency.shift_spans(shift);
        amount.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Custom {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            custom_type,
            values,
            meta,
        } = self;
        date.shift_spans(shift);
        custom_type.shift_spans(shift);
        // `values: Vec<MetaValue>` — routes through the Vec blanket
        // impl in crate::span, which delegates per-element to
        // `MetaValue::shift_spans`. Consistent with how `tags`,
        // `links`, `postings`, `comments` are handled across sibling
        // impls; the round-18 hand-rolled `for v in values` loop was
        // inconsistent.
        values.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Event {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            event_type,
            value,
            meta,
        } = self;
        date.shift_spans(shift);
        event_type.shift_spans(shift);
        value.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Query {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            name,
            query,
            meta,
        } = self;
        date.shift_spans(shift);
        name.shift_spans(shift);
        query.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

impl ShiftSpans for Commodity {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        let Self {
            date,
            currency,
            meta,
        } = self;
        date.shift_spans(shift);
        currency.shift_spans(shift);
        meta.shift_spans(shift);
    }
}

// --- Directive enum ------------------------------------------------

impl ShiftSpans for Directive {
    fn shift_spans<F: Fn(&mut Span)>(&mut self, shift: &F) {
        match self {
            Self::Transaction(t) => t.shift_spans(shift),
            Self::Balance(b) => b.shift_spans(shift),
            Self::Open(o) => o.shift_spans(shift),
            Self::Close(c) => c.shift_spans(shift),
            Self::Commodity(c) => c.shift_spans(shift),
            Self::Pad(p) => p.shift_spans(shift),
            Self::Event(e) => e.shift_spans(shift),
            Self::Query(q) => q.shift_spans(shift),
            Self::Note(n) => n.shift_spans(shift),
            Self::Document(d) => d.shift_spans(shift),
            Self::Price(p) => p.shift_spans(shift),
            Self::Custom(c) => c.shift_spans(shift),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{NaiveDate, Spanned};

    /// `Directive::shift_spans` recurses through `Transaction.postings`
    /// and shifts every `Spanned<Posting>`'s outer span.
    #[test]
    fn directive_shift_spans_propagates_into_posting_spans() {
        use crate::Amount;
        use rust_decimal_macros::dec;

        let posting = Spanned::new(
            Posting::new("Assets:Bank", Amount::new(dec!(100), "USD")),
            Span::new(50, 75),
        );
        let txn = Transaction {
            date: NaiveDate::new(2024, 1, 1).unwrap(),
            flag: '*',
            payee: None,
            narration: "Test".into(),
            tags: Vec::new(),
            links: Vec::new(),
            meta: crate::Metadata::default(),
            postings: vec![posting],
            trailing_comments: Vec::new(),
        };
        let mut d = Directive::Transaction(txn);
        d.shift_spans(&|s: &mut Span| {
            s.start += 10;
            s.end += 10;
        });
        if let Directive::Transaction(t) = d {
            assert_eq!(t.postings[0].span, Span::new(60, 85));
        } else {
            unreachable!();
        }
    }

    /// Round-19 contract: `MetaValue::String(value)` dispatches via
    /// the payload's `ShiftSpans` impl, NOT via a wildcard `_` arm.
    /// Concretely, if `MetaValue::String` ever carried a `Spanned<T>`
    /// payload, that wrapper's impl would be invoked automatically.
    ///
    /// This test pins the dispatch shape via a `MetaValue::Amount`
    /// variant carrying a (no-span) `Amount` — the dispatch path
    /// resolves to `Amount::shift_spans`, which destructures
    /// exhaustively. The compile-time check on the binding pattern
    /// itself catches the discipline gap; this runtime test pins
    /// that the wiring works end-to-end through the `HashMap` impl.
    #[test]
    fn metadata_shift_spans_dispatches_via_value_impl() {
        use crate::Amount;
        use rust_decimal_macros::dec;

        let mut meta = crate::Metadata::default();
        meta.insert(
            "amt".to_string(),
            MetaValue::Amount(Amount::new(dec!(1), "USD")),
        );

        // The shift closure here panics if invoked — we want to
        // verify it is NOT called (because no payload carries a
        // span today), but the dispatch chain (HashMap → MetaValue
        // → Amount → Currency/Decimal no-ops) must execute without
        // dispatching the shift on any leaf.
        let shift = |_: &mut Span| {
            // No-op; the test passes iff the dispatch tree resolves
            // without ever calling shift on a Span.
        };
        meta.shift_spans(&shift);
    }
}