Skip to content

Deep dive: shopping list aggregation

When the @gram-lang/kitchen package processes an Abstract Syntax Tree (AST), one of its core responsibilities is generating the shopping list.

This is not a simple concatenation of ingredients. The compiler performs a complex aggregation process to ensure the list is physically accurate and optimized for purchasing.

When a recipe (or a batch of multiple recipes) is passed to the Kitchen for shopping list generation, the following pipeline executes:

flowchart TD
    Raw["Raw Ingredients (.gram)"] --> KitchenGroup["@gram-lang/kitchen<br/>Group by Raw ID & Unit Scale"]
    KitchenGroup --> HasDB{Ingredient DB Supplied?}
    
    HasDB -- Yes --> AliasRes["@gram-lang/analyzer<br/>Alias Resolution (e.g., beurre ➔ butter)"]
    HasDB -- No --> UnitsCheck
    
    AliasRes --> UnitsCheck{Identical Units?}
    UnitsCheck -- Yes --> SumUnits["Direct Quantity Summation"]
    UnitsCheck -- No (Mixed) --> DensityCheck{Density Available?}
    
    DensityCheck -- Yes --> ConvertGram["Convert to Mass (grams) & Merge"]
    DensityCheck -- No --> MultiUnit["Fallback: multiUnit=true<br/>(Cluster Entries Under Single Heading)"]
  1. @gram-lang/kitchen itself groups ingredients purely by the raw id it assigned during parsing (a slug of the name you wrote) — it has no access to ingredients.yaml and can’t know that @butter and @beurre refer to the same ingredient. On its own, kitchen’s shopping list lists them as two separate entries.

    Alias resolution happens one layer up, in @gram-lang/analyzer, which does have access to the ingredient database. If beurre is listed as an alias of butter in ingredients.yaml, the analyzer re-groups kitchen’s raw entries by this canonical id, merging @butter and @beurre into a single butter entry. This step only runs when an ingredient database is supplied — without one (compiling with @gram-lang/kitchen alone, or a CLI command run without a database), aliases are not resolved and the two ingredients stay separate.

  2. @gram-lang/kitchen merges exact quantities without a database across three levels:

    • Same unit: 100g and 50g sum to 150g, and spelling variants (cup/cups, tbsp/tablespoon) collapse together.
    • Same scale: units with exact integer conversions sum in the smallest unit written. US kitchen measures (tsp, tbsp, fl oz, cup, pt, qt, gal), imperial weights (oz, lb), metric weights (mg, g, kg), and metric volumes (ml, cl, dl, l) each form a scale: 1 cup and 2 tbsp sum to 18 tbsp (formatted as 1 cup + 2 tbsp), and 1 kg and 200 g sum to 1200 g (formatted as 1.2 kg).
    • Different systems or kinds (cup and ml, or volume and weight): kept as separate entries flagged multiUnit: true. Imprecise measures like pinch and dash stay off every scale.

    A sum of quantities behaves like separate mentions (@milk{1 cup + 50 ml} acts just like @milk{1 cup} followed by @&milk{50 ml}), so shopping lists never depend on how quantities were grouped. Ranges sum bound by bound (2-3 g and 200 g yield 202-203 g), while unrecognized units stay as written (clove and cloves remain distinct).

    Entries in different kinds of units (e.g., 100g and 1 cup) can only be summed converting through mass, which — like aliasing — depends on the ingredient database and therefore happens in @gram-lang/analyzer. If every contributing quantity resolves to a mass (density known, from the database or a recipe-level override), the analyzer converts them all to grams and merges them into a single entry.

    Fallback: missing density. If the density can’t be resolved for at least one of the units involved, the analyzer can’t produce a single reliable mass total. Rather than guessing, it keeps the entries separate, renames them to the canonical id, and flags all of them with multiUnit: true. Renderers use this flag to cluster the entries together under one heading (e.g. “⚠️ Mixed units”) instead of scattering them across the list — making it clear to the cook that they’re the same ingredient, without silently mis-adding incompatible units.

  3. Relative quantities and unresolved formulas

    Section titled “Relative quantities and unresolved formulas”

    When a relative quantity (@water{50% @&flour}) or a ratio with units (@eggs{1 / 100 g @&flour}) resolves to a concrete amount—using a known mass, matching unit, or database density—it merges directly into the shopping list alongside static ingredients.

    If the target’s mass or unit conversion cannot be resolved (for instance, missing density in ingredients.yaml), Gram keeps the static entries separate and preserves the unresolved formula (50% of flour) instead of guessing or dropping it, ensuring static totals stay accurate.

  4. The most complex part of the aggregation pipeline is handling Composite Ingredients (<@).

    When multiple children point to the same parent, the compiler uses two distinct rules to figure out how many parents you need to buy:

    1. The MAX Rule (Non-Destructive): If the children use different parts of the parent (e.g., lemon juice and lemon zest), you don’t need two lemons. The compiler takes the maximum equivalent parent mass required by either child. If you need 3 lemons worth of juice, but only 1 lemon worth of zest, the shopping list will say 3 lemons.
    2. The SUM Rule (Destructive): If the children use the same part of the parent (e.g., chicken breast for a salad, and chicken breast for a soup), you cannot reuse the same chicken. The compiler sums the equivalent parent masses required by both children.

The result is a highly optimized, deduplicated, and mathematically sound array of ShoppingItem objects, grouped by stable culinary categories (CATEGORY_KEYS from @gram-lang/i18n) and sorted according to localized category rules (getCategoryLabels(lang)), ready to be rendered in the terminal or a web UI.

The same amount is formatted differently depending on how you use it:

  • What you buy, or read as a total: starting at 1000 g (or 1000 ml), shopping lists, recipe and section totals, and nutrition reference weights switch to kilograms (3.9 kg instead of 3900 g) and liters (2.25 l of milk), the units you actually buy at the store.
  • What you weigh: steps, section ingredient lists, and the run sheet stay in grams even past 1000 g (1500 g of flour). Kitchen scales usually read in grams, and rounding 1234 g to 1.23 kg loses precision.

Formatting rules:

  • Explicit units in steps stay as authored (@flour{2kg} shows as 2 kg, and @milk{1500ml} stays 1500 ml).
  • Only metric units move up (g and mg to kg, ml, cl and dl to l), never cups or ounces. Kilograms and liters keep three significant digits (1.23 kg, 12.3 kg).
  • A quantity already in metric mass (mg, g, kg) is its own weight, so its standardized mass is not repeated.

Every surface follows this rule via toLargerMetricUnit (@gram-lang/i18n): the Playground recipe view, gram view, gram export, and gram shop, while gram cook keeps masses in grams.