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.
The aggregation pipeline
Section titled “The aggregation pipeline”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)"]
-
ID normalization and aliasing
Section titled “ID normalization and aliasing”@gram-lang/kitchenitself groups ingredients purely by the raw id it assigned during parsing (a slug of the name you wrote) — it has no access toingredients.yamland can’t know that@butterand@beurrerefer 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. Ifbeurreis listed as an alias ofbutteriningredients.yaml, the analyzer re-groups kitchen’s raw entries by this canonical id, merging@butterand@beurreinto a singlebutterentry. This step only runs when an ingredient database is supplied — without one (compiling with@gram-lang/kitchenalone, or a CLI command run without a database), aliases are not resolved and the two ingredients stay separate. -
Unit merging
Section titled “Unit merging”@gram-lang/kitchenmerges exact quantities without a database across three levels:- Same unit:
100gand50gsum to150g, 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 cupand2 tbspsum to18 tbsp(formatted as1 cup + 2 tbsp), and1 kgand200 gsum to1200 g(formatted as1.2 kg). - Different systems or kinds (
cupandml, or volume and weight): kept as separate entries flaggedmultiUnit: true. Imprecise measures likepinchanddashstay 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 gand200 gyield202-203 g), while unrecognized units stay as written (cloveandclovesremain distinct).Entries in different kinds of units (e.g.,
100gand1 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. - Same unit:
-
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. -
Resolving composites (MAX vs SUM)
Section titled “Resolving composites (MAX vs SUM)”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:
- 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. - 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 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
The final output
Section titled “The final output”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.
Kilograms to buy, grams to weigh
Section titled “Kilograms to buy, grams to weigh”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 kginstead of3900 g) and liters (2.25 lof 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 gof flour). Kitchen scales usually read in grams, and rounding1234 gto1.23 kgloses precision.
Formatting rules:
- Explicit units in steps stay as authored (
@flour{2kg}shows as2 kg, and@milk{1500ml}stays1500 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.