cooklang 0.18.6

Cooklang parser with opt-in extensions
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! Shopping list parser and serializer
//!
//! Parses a format that represents recipe references and free-hand ingredients
//! in a tree structure. Recipe references start with `./` and can have nested
//! children via indentation.

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::error::{CowStr, Label, RichError};
use crate::span::Span;

/// A shopping list containing recipe references and free-hand ingredients
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ShoppingList {
    /// Top-level items in the shopping list
    pub items: Vec<ShoppingListItem>,
}

/// An item in the shopping list
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ShoppingListItem {
    /// A recipe reference with a path, optional multiplier, and children
    Recipe(RecipeItem),
    /// A free-hand ingredient with a name and optional quantity
    Ingredient(IngredientItem),
}

/// A recipe reference in the shopping list
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecipeItem {
    /// Path to the recipe (e.g. "Breakfast/Easy Pancakes")
    pub path: String,
    /// Optional multiplier/scale factor
    pub multiplier: Option<f64>,
    /// Nested items (sub-recipes and ingredients of this recipe)
    pub children: Vec<ShoppingListItem>,
}

/// A free-hand ingredient in the shopping list
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IngredientItem {
    /// Name of the ingredient
    pub name: String,
    /// Optional quantity string (e.g. "4%l", "500%g", "2")
    pub quantity: Option<String>,
}

/// Error generated by [`parse`]
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ShoppingListError {
    #[error("Error parsing shopping list: {message}")]
    Parse { span: Span, message: String },
    #[error("Invalid multiplier: {message}")]
    InvalidMultiplier { span: Span, message: String },
    #[error("Invalid indentation at line")]
    InvalidIndentation { span: Span },
}

impl RichError for ShoppingListError {
    fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
        use crate::error::label;
        match self {
            ShoppingListError::Parse { span, .. } => vec![label!(span)],
            ShoppingListError::InvalidMultiplier { span, .. } => {
                vec![label!(span, "invalid multiplier here")]
            }
            ShoppingListError::InvalidIndentation { span } => {
                vec![label!(span, "unexpected indentation")]
            }
        }
        .into()
    }

    fn hints(&self) -> std::borrow::Cow<'_, [CowStr]> {
        match self {
            ShoppingListError::InvalidIndentation { .. } => {
                vec!["Use 2 spaces per indentation level".into()]
            }
            ShoppingListError::InvalidMultiplier { .. } => {
                vec!["Multiplier must be a number, e.g. {2} or {0.5}".into()]
            }
            _ => vec![],
        }
        .into()
    }

    fn severity(&self) -> crate::error::Severity {
        crate::error::Severity::Error
    }
}

/// Parse a [`ShoppingList`] from the shopping list format
pub fn parse(input: &str) -> Result<ShoppingList, ShoppingListError> {
    // Strip block comments [- ... -] before line-level parsing
    let stripped = strip_block_comments(input)?;
    let lines = collect_lines(&stripped);
    let items = parse_items(&lines, 0, 0, lines.len())?;
    Ok(ShoppingList { items })
}

struct ParsedLine<'a> {
    content: &'a str,
    indent: usize,
    offset: usize,
}

fn collect_lines(input: &str) -> Vec<ParsedLine<'_>> {
    let mut lines = Vec::new();
    let mut offset = 0;

    for line in input.split('\n') {
        let line_len = line.len();
        let line = line.trim_end_matches('\r');

        // Strip inline/line comments starting with --
        let content = match line.split_once("--") {
            Some((before, _)) => before,
            None => line,
        };

        let indent = content.len() - content.trim_start_matches(' ').len();
        let content = content.trim();

        if !content.is_empty() {
            lines.push(ParsedLine {
                content,
                indent,
                offset,
            });
        }

        offset += line_len + 1;
    }

    lines
}

/// Strip block comments `[- ... -]` from the input, preserving newlines so
/// line numbers stay stable. Each block comment is replaced with a single
/// space so adjacent tokens don't get glued together.
///
/// Returns `ShoppingListError::Parse` if a `[-` is opened but never closed.
fn strip_block_comments(input: &str) -> Result<String, ShoppingListError> {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.char_indices().peekable();

    while let Some((i, c)) = chars.next() {
        if c == '[' && input[i..].starts_with("[-") {
            // Skip the opening [-
            chars.next(); // skip '-'
            let open_offset = i;
            let mut terminated = false;
            // Find matching -]
            loop {
                match chars.next() {
                    Some((_, '\n')) => result.push('\n'),
                    Some((j, '-')) if input[j..].starts_with("-]") => {
                        chars.next(); // skip ']'
                        terminated = true;
                        break;
                    }
                    Some(_) => {} // drop character
                    None => break,
                }
            }
            if !terminated {
                return Err(ShoppingListError::Parse {
                    span: Span::new(open_offset, input.len()),
                    message: "unterminated block comment (missing `-]`)".to_string(),
                });
            }
            // Replace the block with a single space so surrounding tokens
            // don't get glued together (e.g. "a[-x-]b" -> "a b").
            result.push(' ');
        } else {
            result.push(c);
        }
    }

    Ok(result)
}

fn parse_items(
    lines: &[ParsedLine<'_>],
    base_indent: usize,
    start: usize,
    end: usize,
) -> Result<Vec<ShoppingListItem>, ShoppingListError> {
    let mut items = Vec::new();
    let mut i = start;

    while i < end {
        let line = &lines[i];

        if line.indent < base_indent {
            break;
        }

        if line.indent != base_indent {
            return Err(ShoppingListError::InvalidIndentation {
                span: Span::new(line.offset, line.offset + line.content.len()),
            });
        }

        if line.content.starts_with("./") {
            let (path, multiplier) = parse_recipe_line(line)?;

            let child_indent = base_indent + 2;
            let child_start = i + 1;
            let mut child_end = child_start;
            while child_end < end && lines[child_end].indent >= child_indent {
                child_end += 1;
            }

            let children = if child_start < child_end {
                parse_items(lines, child_indent, child_start, child_end)?
            } else {
                Vec::new()
            };

            items.push(ShoppingListItem::Recipe(RecipeItem {
                path,
                multiplier,
                children,
            }));

            i = child_end;
        } else {
            let (name, quantity) = parse_ingredient_line(line)?;
            items.push(ShoppingListItem::Ingredient(IngredientItem {
                name,
                quantity,
            }));
            i += 1;
        }
    }

    Ok(items)
}

/// Collapse runs of whitespace (left over from block comment stripping) into
/// single spaces, and trim ends.
fn normalize_whitespace(s: &str) -> String {
    s.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn parse_recipe_line(line: &ParsedLine<'_>) -> Result<(String, Option<f64>), ShoppingListError> {
    let content = &line.content[2..];

    if let Some(brace_start) = content.rfind('{') {
        if content.ends_with('}') {
            let path = normalize_whitespace(&content[..brace_start]);
            let multiplier_str = &content[brace_start + 1..content.len() - 1];
            let multiplier: f64 =
                multiplier_str
                    .parse()
                    .map_err(|_| ShoppingListError::InvalidMultiplier {
                        span: Span::new(
                            line.offset + 2 + brace_start + 1,
                            line.offset + 2 + content.len() - 1,
                        ),
                        message: format!("'{multiplier_str}' is not a valid number"),
                    })?;
            Ok((path, Some(multiplier)))
        } else {
            Ok((normalize_whitespace(content), None))
        }
    } else {
        Ok((normalize_whitespace(content), None))
    }
}

fn parse_ingredient_line(
    line: &ParsedLine<'_>,
) -> Result<(String, Option<String>), ShoppingListError> {
    let content = line.content;

    if let Some(brace_start) = content.rfind('{') {
        if content.ends_with('}') {
            let name = normalize_whitespace(&content[..brace_start]);
            let quantity = content[brace_start + 1..content.len() - 1].to_string();
            if name.is_empty() {
                return Err(ShoppingListError::Parse {
                    span: Span::new(line.offset, line.offset + content.len()),
                    message: "ingredient name cannot be empty".to_string(),
                });
            }
            Ok((name, Some(quantity)))
        } else {
            Ok((normalize_whitespace(content), None))
        }
    } else {
        Ok((normalize_whitespace(content), None))
    }
}

/// Write a [`ShoppingList`] in the shopping list format
pub fn write(list: &ShoppingList, mut w: impl std::io::Write) -> std::io::Result<()> {
    write_items(&list.items, 0, &mut w)
}

fn write_items(
    items: &[ShoppingListItem],
    depth: usize,
    w: &mut impl std::io::Write,
) -> std::io::Result<()> {
    let indent = "  ".repeat(depth);
    for item in items {
        match item {
            ShoppingListItem::Recipe(recipe) => {
                write!(w, "{indent}./{}", recipe.path)?;
                if let Some(m) = recipe.multiplier {
                    if m.fract() == 0.0 {
                        write!(w, "{{{}}}", m as i64)?;
                    } else {
                        write!(w, "{{{m}}}")?;
                    }
                }
                writeln!(w)?;
                write_items(&recipe.children, depth + 1, w)?;
            }
            ShoppingListItem::Ingredient(ingredient) => {
                write!(w, "{indent}{}", ingredient.name)?;
                if let Some(q) = &ingredient.quantity {
                    write!(w, "{{{q}}}")?;
                }
                writeln!(w)?;
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Checked file (.shopping-checked) — append-only log of checked/unchecked items
// ---------------------------------------------------------------------------

/// An entry in the checked log
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CheckEntry {
    /// Ingredient was checked (acquired): `+ name`
    Checked(String),
    /// Ingredient was unchecked: `- name`
    Unchecked(String),
}

/// Parse a `.shopping-checked` file and return the list of log entries.
///
/// This is an append-only log format: lines that don't match `+ <name>` or
/// `- <name>` (including malformed entries like `+salt` with no space) are
/// silently skipped so a corrupted suffix can't prevent the rest of the log
/// from replaying.
pub fn parse_checked(input: &str) -> Vec<CheckEntry> {
    let mut entries = Vec::new();
    for line in input.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        if let Some(name) = line.strip_prefix("+ ") {
            let name = name.trim();
            if !name.is_empty() {
                entries.push(CheckEntry::Checked(name.to_string()));
            }
        } else if let Some(name) = line.strip_prefix("- ") {
            let name = name.trim();
            if !name.is_empty() {
                entries.push(CheckEntry::Unchecked(name.to_string()));
            }
        }
    }
    entries
}

/// Replay a checked log and return the set of ingredient names that are
/// currently checked.
///
/// Matching is case-insensitive, so the returned set contains **lowercased
/// names only** — compare against your shopping list with
/// `name.to_lowercase()`.
pub fn checked_set(entries: &[CheckEntry]) -> std::collections::HashSet<String> {
    use std::collections::HashMap;
    let mut state: HashMap<String, bool> = HashMap::new();
    for entry in entries {
        match entry {
            CheckEntry::Checked(name) => {
                state.insert(name.to_lowercase(), true);
            }
            CheckEntry::Unchecked(name) => {
                state.insert(name.to_lowercase(), false);
            }
        }
    }
    state
        .into_iter()
        .filter_map(|(name, checked)| if checked { Some(name) } else { None })
        .collect()
}

/// Write a single check entry to the log.
pub fn write_check_entry(entry: &CheckEntry, mut w: impl std::io::Write) -> std::io::Result<()> {
    match entry {
        CheckEntry::Checked(name) => writeln!(w, "+ {name}"),
        CheckEntry::Unchecked(name) => writeln!(w, "- {name}"),
    }
}

/// Compact a checked log against the set of ingredient names currently in
/// the shopping list: keep only `+ name` entries for ingredients that are
/// still present.
///
/// `current_ingredients` must be the actual ingredient names as they would
/// be rendered to the user — after aggregating referenced recipes, applying
/// any pantry/aisle filtering, etc. A raw on-disk `ShoppingList` usually
/// contains only recipe *references* (not `Ingredient` items), so callers
/// that persist lists that way must expand them first. Passing an iterator
/// rather than a `ShoppingList` makes this contract explicit.
///
/// Matching is case-insensitive; returned `+ name` entries preserve the
/// lowercased form stored in `checked_set`.
pub fn compact_checked<'a, I>(entries: &[CheckEntry], current_ingredients: I) -> Vec<CheckEntry>
where
    I: IntoIterator<Item = &'a str>,
{
    let current = checked_set(entries);
    let list_ingredients: std::collections::HashSet<String> = current_ingredients
        .into_iter()
        .map(|n| n.to_lowercase())
        .collect();

    let mut compacted: Vec<CheckEntry> = current
        .into_iter()
        .filter(|name| list_ingredients.contains(name))
        .map(CheckEntry::Checked)
        .collect();
    compacted.sort_by(|a, b| {
        // Only `Checked` entries are ever pushed above, but match both arms
        // so this stays correct if the collection logic ever changes.
        let name_of = |e: &CheckEntry| match e {
            CheckEntry::Checked(n) | CheckEntry::Unchecked(n) => n.clone(),
        };
        name_of(a).cmp(&name_of(b))
    });
    compacted
}

/// Collect all ingredient names from a shopping list (recursively).
///
/// This only finds `Ingredient` items. Lists that only store recipe
/// *references* will produce an empty result — in that case, caller must
/// expand the references via their own recipe parser before feeding names
/// into [`compact_checked`].
pub fn collect_ingredient_names(list: &ShoppingList) -> Vec<String> {
    let mut names = Vec::new();
    collect_ingredient_names_from_items(&list.items, &mut names);
    names
}

fn collect_ingredient_names_from_items(items: &[ShoppingListItem], names: &mut Vec<String>) {
    for item in items {
        match item {
            ShoppingListItem::Ingredient(i) => names.push(i.name.clone()),
            ShoppingListItem::Recipe(r) => {
                collect_ingredient_names_from_items(&r.children, names);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_input() {
        let list = parse("").unwrap();
        assert!(list.items.is_empty());
    }

    #[test]
    fn single_recipe() {
        let list = parse("./Breakfast/Easy Pancakes{2}").unwrap();
        assert_eq!(list.items.len(), 1);
        match &list.items[0] {
            ShoppingListItem::Recipe(r) => {
                assert_eq!(r.path, "Breakfast/Easy Pancakes");
                assert_eq!(r.multiplier, Some(2.0));
                assert!(r.children.is_empty());
            }
            _ => panic!("expected recipe"),
        }
    }

    #[test]
    fn recipe_without_multiplier() {
        let list = parse("./Breakfast/Easy Pancakes").unwrap();
        match &list.items[0] {
            ShoppingListItem::Recipe(r) => {
                assert_eq!(r.path, "Breakfast/Easy Pancakes");
                assert_eq!(r.multiplier, None);
            }
            _ => panic!("expected recipe"),
        }
    }

    #[test]
    fn single_ingredient_with_quantity() {
        let list = parse("free hand ingredient{4%l}").unwrap();
        assert_eq!(list.items.len(), 1);
        match &list.items[0] {
            ShoppingListItem::Ingredient(i) => {
                assert_eq!(i.name, "free hand ingredient");
                assert_eq!(i.quantity.as_deref(), Some("4%l"));
            }
            _ => panic!("expected ingredient"),
        }
    }

    #[test]
    fn bare_ingredient() {
        let list = parse("salt").unwrap();
        assert_eq!(list.items.len(), 1);
        match &list.items[0] {
            ShoppingListItem::Ingredient(i) => {
                assert_eq!(i.name, "salt");
                assert_eq!(i.quantity, None);
            }
            _ => panic!("expected ingredient"),
        }
    }

    #[test]
    fn comment_lines() {
        let input = "-- this is a comment\nsalt\n-- another comment";
        let list = parse(input).unwrap();
        assert_eq!(list.items.len(), 1);
        match &list.items[0] {
            ShoppingListItem::Ingredient(i) => assert_eq!(i.name, "salt"),
            _ => panic!("expected ingredient"),
        }
    }

    #[test]
    fn inline_comment() {
        let list = parse("salt -- for seasoning").unwrap();
        match &list.items[0] {
            ShoppingListItem::Ingredient(i) => {
                assert_eq!(i.name, "salt");
                assert_eq!(i.quantity, None);
            }
            _ => panic!("expected ingredient"),
        }
    }

    #[test]
    fn block_comment() {
        let input = "salt\n[- this is a\nblock comment -]\npepper";
        let list = parse(input).unwrap();
        assert_eq!(list.items.len(), 2);
        match &list.items[0] {
            ShoppingListItem::Ingredient(i) => assert_eq!(i.name, "salt"),
            _ => panic!("expected ingredient"),
        }
        match &list.items[1] {
            ShoppingListItem::Ingredient(i) => assert_eq!(i.name, "pepper"),
            _ => panic!("expected ingredient"),
        }
    }

    #[test]
    fn inline_block_comment() {
        // The stripped block leaves surrounding whitespace; we normalize it
        // so consumers see a clean name.
        let list = parse("salt [- seasoning -] pepper").unwrap();
        assert_eq!(list.items.len(), 1);
        match &list.items[0] {
            ShoppingListItem::Ingredient(i) => assert_eq!(i.name, "salt pepper"),
            _ => panic!("expected ingredient"),
        }
    }

    #[test]
    fn unterminated_block_comment_errors() {
        let err = parse("salt [- seasoning\npepper").unwrap_err();
        assert!(matches!(err, ShoppingListError::Parse { .. }));
    }

    #[test]
    fn adjacent_block_comment_does_not_glue_tokens() {
        // Without the space replacement, "foo[-x-]bar" would become "foobar".
        let list = parse("foo[- note -]bar").unwrap();
        assert_eq!(list.items.len(), 1);
        match &list.items[0] {
            ShoppingListItem::Ingredient(i) => assert_eq!(i.name, "foo bar"),
            _ => panic!("expected ingredient"),
        }
    }

    #[test]
    fn nested_recipes() {
        let input = "\
./Breakfast/Easy Pancakes{2}
  ./Some/Nested Recipe{2}
  ./Another Nested{1}";
        let list = parse(input).unwrap();
        assert_eq!(list.items.len(), 1);
        match &list.items[0] {
            ShoppingListItem::Recipe(r) => {
                assert_eq!(r.path, "Breakfast/Easy Pancakes");
                assert_eq!(r.multiplier, Some(2.0));
                assert_eq!(r.children.len(), 2);
                match &r.children[0] {
                    ShoppingListItem::Recipe(nested) => {
                        assert_eq!(nested.path, "Some/Nested Recipe");
                        assert_eq!(nested.multiplier, Some(2.0));
                    }
                    _ => panic!("expected nested recipe"),
                }
            }
            _ => panic!("expected recipe"),
        }
    }

    #[test]
    fn full_example() {
        let input = "\
./Breakfast/Easy Pancakes{2}
  ./Some/Nested Recipe{2}
free hand ingredient{4%l}
salt";
        let list = parse(input).unwrap();
        assert_eq!(list.items.len(), 3);
        assert!(matches!(&list.items[0], ShoppingListItem::Recipe(_)));
        assert!(matches!(&list.items[1], ShoppingListItem::Ingredient(_)));
        assert!(matches!(&list.items[2], ShoppingListItem::Ingredient(_)));

        match &list.items[0] {
            ShoppingListItem::Recipe(r) => {
                assert_eq!(r.children.len(), 1);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn deeply_nested() {
        let input = "\
./Top{1}
  ./Mid{2}
    ./Deep{3}";
        let list = parse(input).unwrap();
        match &list.items[0] {
            ShoppingListItem::Recipe(top) => {
                assert_eq!(top.path, "Top");
                match &top.children[0] {
                    ShoppingListItem::Recipe(mid) => {
                        assert_eq!(mid.path, "Mid");
                        match &mid.children[0] {
                            ShoppingListItem::Recipe(deep) => {
                                assert_eq!(deep.path, "Deep");
                                assert_eq!(deep.multiplier, Some(3.0));
                            }
                            _ => panic!("expected deep recipe"),
                        }
                    }
                    _ => panic!("expected mid recipe"),
                }
            }
            _ => panic!("expected top recipe"),
        }
    }

    #[test]
    fn recipe_with_child_ingredients() {
        let input = "\
./Pancakes{2}
  flour{500%g}
  milk{200%ml}";
        let list = parse(input).unwrap();
        match &list.items[0] {
            ShoppingListItem::Recipe(r) => {
                assert_eq!(r.children.len(), 2);
                match &r.children[0] {
                    ShoppingListItem::Ingredient(i) => {
                        assert_eq!(i.name, "flour");
                        assert_eq!(i.quantity.as_deref(), Some("500%g"));
                    }
                    _ => panic!("expected ingredient child"),
                }
            }
            _ => panic!("expected recipe"),
        }
    }

    #[test]
    fn empty_lines_ignored() {
        let input = "\
./Recipe{1}

salt

pepper";
        let list = parse(input).unwrap();
        assert_eq!(list.items.len(), 3);
    }

    #[test]
    fn fractional_multiplier() {
        let list = parse("./Recipe{0.5}").unwrap();
        match &list.items[0] {
            ShoppingListItem::Recipe(r) => {
                assert_eq!(r.multiplier, Some(0.5));
            }
            _ => panic!("expected recipe"),
        }
    }

    #[test]
    fn write_roundtrip() {
        let input = "\
./Breakfast/Easy Pancakes{2}
  ./Some/Nested Recipe{2}
free hand ingredient{4%l}
salt
";
        let list = parse(input).unwrap();
        let mut buf = Vec::new();
        write(&list, &mut buf).unwrap();
        let output = String::from_utf8(buf).unwrap();
        let list2 = parse(&output).unwrap();
        assert_eq!(list, list2);
    }

    #[test]
    fn write_deep_nesting() {
        let input = "\
./Top{1}
  ./Mid{2}
    ./Deep{3}
    ingredient{1%kg}
";
        let list = parse(input).unwrap();
        let mut buf = Vec::new();
        write(&list, &mut buf).unwrap();
        let output = String::from_utf8(buf).unwrap();
        let list2 = parse(&output).unwrap();
        assert_eq!(list, list2);
    }

    #[test]
    fn write_empty() {
        let list = ShoppingList::default();
        let mut buf = Vec::new();
        write(&list, &mut buf).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert_eq!(output, "");
    }

    #[test]
    fn error_invalid_multiplier() {
        let err = parse("./Recipe{abc}").unwrap_err();
        assert!(matches!(err, ShoppingListError::InvalidMultiplier { .. }));
    }

    #[test]
    fn error_empty_ingredient_name() {
        let err = parse("{4%l}").unwrap_err();
        assert!(matches!(err, ShoppingListError::Parse { .. }));
    }

    #[test]
    fn error_bad_indentation() {
        let input = "./Recipe{1}\n   ./Bad{2}"; // 3 spaces instead of 2
        let err = parse(input).unwrap_err();
        assert!(matches!(err, ShoppingListError::InvalidIndentation { .. }));
    }

    // -- Checked file tests --

    #[test]
    fn parse_checked_empty() {
        let entries = parse_checked("");
        assert!(entries.is_empty());
    }

    #[test]
    fn parse_checked_basic() {
        let input = "+ salt\n+ avocados\n+ olive oil\n- avocados\n+ avocados\n";
        let entries = parse_checked(input);
        assert_eq!(entries.len(), 5);
        assert_eq!(entries[0], CheckEntry::Checked("salt".into()));
        assert_eq!(entries[3], CheckEntry::Unchecked("avocados".into()));
    }

    #[test]
    fn checked_set_last_wins() {
        let input = "+ salt\n+ avocados\n+ olive oil\n- avocados\n+ avocados\n";
        let entries = parse_checked(input);
        let set = checked_set(&entries);
        assert!(set.contains("salt"));
        assert!(set.contains("avocados"));
        assert!(set.contains("olive oil"));
        assert_eq!(set.len(), 3);
    }

    #[test]
    fn checked_set_uncheck_wins() {
        let input = "+ salt\n- salt\n";
        let entries = parse_checked(input);
        let set = checked_set(&entries);
        assert!(!set.contains("salt"));
    }

    #[test]
    fn checked_set_case_insensitive() {
        let input = "+ Salt\n";
        let entries = parse_checked(input);
        let set = checked_set(&entries);
        assert!(set.contains("salt"));
    }

    #[test]
    fn compact_removes_stale() {
        let list = parse("salt\npepper\n").unwrap();
        let names = collect_ingredient_names(&list);
        let entries = parse_checked("+ salt\n+ garlic\n");
        let compacted = compact_checked(&entries, names.iter().map(String::as_str));
        // garlic is not in list, should be dropped
        assert_eq!(compacted.len(), 1);
        assert!(matches!(&compacted[0], CheckEntry::Checked(n) if n == "salt"));
    }

    #[test]
    fn compact_accepts_arbitrary_name_iter() {
        // Typical use: caller has already aggregated ingredient names from
        // recipe references and passes them in directly.
        let entries = parse_checked("+ salt\n+ pepper\n+ garlic\n");
        let names = ["salt", "pepper"];
        let compacted = compact_checked(&entries, names.iter().copied());
        assert_eq!(compacted.len(), 2);
        let kept: Vec<&str> = compacted
            .iter()
            .map(|e| match e {
                CheckEntry::Checked(n) | CheckEntry::Unchecked(n) => n.as_str(),
            })
            .collect();
        assert!(kept.contains(&"salt"));
        assert!(kept.contains(&"pepper"));
        assert!(!kept.contains(&"garlic"));
    }

    #[test]
    fn compact_is_case_insensitive_against_names() {
        let entries = parse_checked("+ Salt\n");
        let compacted = compact_checked(&entries, ["SALT"].iter().copied());
        assert_eq!(compacted.len(), 1);
    }

    #[test]
    fn write_check_entry_roundtrip() {
        let entries = vec![
            CheckEntry::Checked("salt".into()),
            CheckEntry::Unchecked("pepper".into()),
        ];
        let mut buf = Vec::new();
        for e in &entries {
            write_check_entry(e, &mut buf).unwrap();
        }
        let output = String::from_utf8(buf).unwrap();
        assert_eq!(output, "+ salt\n- pepper\n");
        let parsed = parse_checked(&output);
        assert_eq!(parsed, entries);
    }
}