From c36e76b8db8a0458c90614e48f1492dcb91f8cb5 Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:46 +0100 Subject: [PATCH 01/11] fix(format): trim trailing zeros the same way in every quantity --- .changeset/compound-quantity-tooling.md | 2 +- packages/format/src/index.ts | 96 +++++++++++++---------- packages/format/tests/formatter.test.ts | 35 +++++++++ packages/format/tests/unit-ratios.test.ts | 2 +- 4 files changed, 90 insertions(+), 45 deletions(-) diff --git a/.changeset/compound-quantity-tooling.md b/.changeset/compound-quantity-tooling.md index 7d4fe2f1..3da33c39 100644 --- a/.changeset/compound-quantity-tooling.md +++ b/.changeset/compound-quantity-tooling.md @@ -8,4 +8,4 @@ - Quick Fixes for the quantity warnings: two quantities written side by side (`{1 cup 5 tbsp}`) become a sum (`{1 cup + 5 tbsp}`), a sum with a percentage takes the result Gram suggests (`{100 g + 10%}` → `{110 g}`), and `oz` after a volume becomes `fl oz`. - Hovering an ingredient written as a sum shows what it adds up to (`= 17 tbsp`), or the kinds of amount it keeps apart (a volume and a weight), and its weight when the ingredient database can tell. - Unit completion works in each term of a sum, once its number is typed (`{1 cup + 2`). - - `gram format` and format on save put one space around the `+` and `-` of a sum in an ingredient's braces (`{1 cup-2 tbsp}` → `{1 cup - 2 tbsp}`), never in a range (`{1-2 cups}`), a timer or a temperature, and remove trailing zeros term by term (`{1.50 cup + 2.0 tbsp}` → `{1.5 cup + 2 tbsp}`). The count of these fixes is reported in the new `quantityOperatorSpacing` field. + - `gram format` and format on save put one space around the `+` and `-` of a sum in an ingredient's braces (`{1 cup-2 tbsp}` → `{1 cup - 2 tbsp}`), never in a range (`{1-2 cups}`), a timer or a temperature, and remove trailing zeros from every number of a quantity, with its unit glued or spaced, in a range, a sum, a ratio or a timer (`{1.50-2.50 cup + 2.0 tbsp}` → `{1.5-2.5 cup + 2 tbsp}`, `{1.50 kg}` → `{1.5 kg}`, `~{1.50 h}` → `~{1.5 h}`). The count of these fixes is reported in the new `quantityOperatorSpacing` field. diff --git a/packages/format/src/index.ts b/packages/format/src/index.ts index ef723618..8e9d0371 100644 --- a/packages/format/src/index.ts +++ b/packages/format/src/index.ts @@ -112,8 +112,44 @@ function splitFrontmatter(source: string): { /** An operator between two terms of a sum, once spaced (` + `, ` - `). */ const SUM_OPERATOR = / [+-] /; -/** A term of a sum whose decimals end in zeros (`1.50 cup`, `2.0 tbsp`). */ -const TERM_TRAILING_ZEROS = /^(\d+)([.,])(\d*?)(0+)(\s*[\p{L}°%].*)?$/u; +/** A target after the first character: `5% @&flour`, `1 / 100 g &dough`. */ +const HAS_TARGET = /.(?:@&|&)/u; + +/** + * A decimal number whose decimals end in zeros (`1.50`, `2,0`), standing on + * its own: not inside a longer number, nor part of a name (`v2.0`, + * `chocolat-70.0`); a `-` before it is a range's or a sign's. + */ +const DECIMAL_WITH_ZEROS = + /(? { + if (sep === "," && digits.length + zeros.length === 3) return match; + count++; + return digits ? `${n}${sep}${digits}` : n; + }, + ); + return { text: amount + inner.slice(end), count }; +} /** What the brace at an offset opens (see `braceOwner`). */ type BraceOwner = @@ -148,9 +184,6 @@ function braceOwner(body: string, offset: number): BraceOwner { const isCheckpoint = (body: string, offset: number) => braceOwner(body, offset) === "checkpoint"; -/** A target after the first character: `5% @&flour`, `1 / 100 g &dough`. */ -const HAS_TARGET = /.(?:@&|&)/u; - /** * One space around each operator of a sum: a `+` between an amount and a * number, a `-` only after a unit (`1 cup-2 tbsp`), never between two @@ -232,53 +265,30 @@ export function formatGram(source: string): { return `{${fixed}}`; }); - // Rule 4: Remove trailing decimal zeros in quantities ({500.0g} → {500g}, {1.50g} → {1.5g}), - // after a point or a comma ({1,50} → {1,5}). A comma followed by exactly three - // digits ({1,000}) is left as written: it may be a thousands separator, which - // the compiler flags (AMBIGUOUS_NUMBER), and stripping it would hide the question. - const looksLikeThousands = (sep: string, decimals: string) => - sep === "," && decimals.length === 3; - body = body.replace( - /\{(\d+)([.,])(0+)([a-zA-Z°%]*)\}/g, - (match, n, sep, zeros, u, offset) => { - if (looksLikeThousands(sep, zeros)) return match; - if (isCheckpoint(body, offset)) return match; - changes.trailingZeros++; - return `{${n}${u}}`; - }, - ); - body = body.replace( - /\{(\d+)([.,])(\d*[1-9])(0+)([a-zA-Z°%]*)\}/g, - (match, n, sep, digits, zeros, u, offset) => { - if (looksLikeThousands(sep, digits + zeros)) return match; - if (isCheckpoint(body, offset)) return match; - changes.trailingZeros++; - return `{${n}${sep}${digits}${u}}`; - }, - ); + // Rule 4: Remove trailing decimal zeros from every number in a quantity's + // braces ({500.0g} → {500g}, {1.50 kg} → {1.5 kg}), whatever follows it: + // a unit, a range's other bound ({1.50-2.50 cup}), a sum's next term, a + // ratio's slash or a timer's unit (~{1.50 h}). See `trimTrailingZeros`. + body = body.replace(/\{([^{}\n]*)\}/g, (match, inner: string, offset) => { + if (isCheckpoint(body, offset)) return match; + const { text, count } = trimTrailingZeros(inner); + if (count === 0) return match; + changes.trailingZeros += count; + return `{${text}}`; + }); // Rule 4b: A sum of quantities, in an ingredient's braces only (`@…{`, // `<@…{`, `&…{`; never a timer's `~{1h30-2h}` nor a temperature's): - // one space around each operator, and rule 4 term by term. + // one space around each operator (rule 4 has trimmed its terms). body = body.replace(/\{([^{}\n]*)\}/g, (match, inner: string, offset) => { if (braceOwner(body, offset) !== "ingredient") return match; // A quantity relative to a target (`5% @&chocolat-70`) is never a sum: // spacing the `-` of its target's name would rename the target. if (HAS_TARGET.test(inner)) return match; const spaced = spaceSumOperators(inner); - if (!SUM_OPERATOR.test(spaced)) return match; - if (spaced !== inner) changes.quantityOperatorSpacing++; - const terms = spaced.split(/( [+-] )/); - const trimmed = terms.map((term, i) => { - if (i % 2 === 1) return term; - const zeros = TERM_TRAILING_ZEROS.exec(term); - if (!zeros) return term; - const [, n, sep = "", digits = "", tail = "", unit = ""] = zeros; - if (looksLikeThousands(sep, digits + tail)) return term; - changes.trailingZeros++; - return digits ? `${n}${sep}${digits}${unit}` : `${n}${unit}`; - }); - return `{${trimmed.join("")}}`; + if (!SUM_OPERATOR.test(spaced) || spaced === inner) return match; + changes.quantityOperatorSpacing++; + return `{${spaced}}`; }); // Rule 6 (from language-server): normalize composite separator spacing diff --git a/packages/format/tests/formatter.test.ts b/packages/format/tests/formatter.test.ts index 28b77966..7ab0c846 100644 --- a/packages/format/tests/formatter.test.ts +++ b/packages/format/tests/formatter.test.ts @@ -484,3 +484,38 @@ describe("a target state (1.5)", () => { ).toMatchObject({ state: "la nappe", note: "test" }); }); }); + +describe("trailing zeros, the same rule for every quantity", () => { + const format = (step: string) => formatGram(`## T\n\n${step}\n`).content; + + for (const [input, output] of [ + ["@flour{1.50 cup + 1 tbsp}", "@flour{1.5 cup + 1 tbsp}"], + ["@flour{1.50 kg}", "@flour{1.5 kg}"], + ["@flour{1.50kg}", "@flour{1.5kg}"], + ["@flour{2.0 kg}", "@flour{2 kg}"], + ["@b{0.50 / 100 g @&a}", "@b{0.5 / 100 g @&a}"], + ["~{1.50 h}", "~{1.5 h}"], + ["@flour{1.50-2.50 cup+1 tbsp}", "@flour{1.5-2.5 cup + 1 tbsp}"], + ["@flour{1,50-2,0 kg}", "@flour{1,5-2 kg}"], + ["@flour{1 1/2-2.0 cups}", "@flour{1 1/2-2 cups}"], + ]) { + it(`writes ${input} as ${output}, then leaves it`, () => { + const once = format(input); + expect(once).toContain(output); + expect(format(output)).toBe(once); + expect(hasChanges(formatGram(once).changes)).toBe(false); + }); + } + + for (const kept of [ + "@flour{1,000 g}", + "@flour{1,000-2,500 g}", + "@flour{1.25 kg}", + "@salt{2.0 g / 100 g @&chocolat-70.0}", + "@x{v2.0 sachets}", + ]) { + it(`keeps the zeros that may matter in ${kept}`, () => { + expect(format(kept)).toContain(kept.replace("@salt{2.0 g", "@salt{2 g")); + }); + } +}); diff --git a/packages/format/tests/unit-ratios.test.ts b/packages/format/tests/unit-ratios.test.ts index 3669ac11..4229a67f 100644 --- a/packages/format/tests/unit-ratios.test.ts +++ b/packages/format/tests/unit-ratios.test.ts @@ -12,7 +12,7 @@ const format = (step: string) => describe("format: ratios with units", () => { for (const ratio of [ "@eggs{1 / 100 g @&flour}", - "@eggs{1,50 / 100 g @&flour}", + "@eggs{1,5 / 100 g @&flour}", "@x{1/2 / 100 g @&flour}", "@x{15-20 g / 100 g @&flour}", "@x{1 /100 g @&flour}", -- 2.54.0 From ce80b846ed442193ad7615f0bd07eb857eba872d Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:46 +0100 Subject: [PATCH 02/11] fix(kitchen): say what a ratio's target problem is, by the name its author wrote --- .changeset/unit-ratios.md | 4 +- .../analyzed.json | 4 +- .../compiled.json | 4 +- packages/analyzer/src/index.ts | 15 +++++- packages/analyzer/tests/unit-ratios.test.ts | 15 ++++++ .../docs/docs/reference/api/warnings.mdx | 2 + .../reference/syntax/relative-quantities.mdx | 2 +- .../docs/fr/docs/reference/api/warnings.mdx | 2 + .../reference/syntax/relative-quantities.mdx | 2 +- packages/kitchen/src/compound.ts | 6 +++ packages/kitchen/src/processor.ts | 49 ++++++++++++----- packages/kitchen/src/ratio.ts | 8 ++- packages/kitchen/src/warnings.ts | 18 +++++-- .../kitchen/tests/zero-denominator.test.ts | 29 ++++++++++ packages/modules/src/rename.ts | 21 ++++++-- .../modules/tests/private-target-name.test.ts | 53 +++++++++++++++++++ packages/parser/src/types.ts | 12 +++++ 17 files changed, 212 insertions(+), 34 deletions(-) create mode 100644 packages/modules/tests/private-target-name.test.ts diff --git a/.changeset/unit-ratios.md b/.changeset/unit-ratios.md index 00e00e03..9b0d2698 100644 --- a/.changeset/unit-ratios.md +++ b/.changeset/unit-ratios.md @@ -12,7 +12,7 @@ **Parser, Kitchen & Analyzer**: Ingredients and timers can now be written as ratios with units: - Write `@eggs{1 / 100 g @&flour}` or `@salt{15 g / 1 L @&water}` for an amount that follows another ingredient across units or piece counts, `&stock{250 ml / 100 g @&rice}` for a homemade preparation (a percentage such as `&stock{250% @&rice}`, ignored until now, works too), and `~{15 min / 500 g @&roast}` or `~{4 min / @&cutlet}` for a cooking time that follows a weight or a count. - - Ratios within one unit family or between pieces resolve at compile time; across mass and volume, or between weight and pieces, they use the density or unit weight of the ingredient database, and mismatched units are refused with a warning that says why (`RELATIVE_QUANTITY_UNKNOWN_MASS` now carries a `reason`) instead of guessed. - - A percentage or ratio of a homemade preparation used whole (`Roll out the &dough`) now takes the mass of the section that makes it, marked as an estimate, instead of warning that the mass is unknown. + - Ratios within one unit family or between pieces resolve at compile time; across mass and volume, or between weight and pieces, they use the density or unit weight of the ingredient database, and mismatched units are refused with a warning that says why (`RELATIVE_QUANTITY_UNKNOWN_MASS` now carries a `reason`) instead of guessed; a ratio per nothing (`/ 0 g`) raises `INVALID_QUANTITY` with the new `reason: "zeroRatioDenominator"`. + - A percentage or ratio of a homemade preparation used whole (`Roll out the &dough`) now takes the mass of the section that makes it, marked as an estimate, instead of warning that the mass is unknown; one made by a step (`Mix … ->&dough`) is refused with the new reason `stepProducer`, which asks for the amount used. Inside an imported base, a private intermediate is shown in formulas and warnings by the name its author wrote, never by its internal one (`dough$pate`). - Scaling a recipe now resolves these ratios again and recalculates the schedule, the total times and the shopping list. - Views show the resolved amount with its ratio in a tooltip, and the language server highlights ratios, completes their targets, renames an intermediate inside them, and adds hovers and inlay hints with what each one came to. diff --git a/conformance/cases/warn-023-ratio-unit-guardrail/analyzed.json b/conformance/cases/warn-023-ratio-unit-guardrail/analyzed.json index 9da65ba8..df76f0ab 100644 --- a/conformance/cases/warn-023-ratio-unit-guardrail/analyzed.json +++ b/conformance/cases/warn-023-ratio-unit-guardrail/analyzed.json @@ -643,14 +643,14 @@ "warnings": [ { "code": "INVALID_QUANTITY", - "message": "Number \"1 / 0 g @&flour\" of \"a\" is not read: a fraction cannot have 0 below the bar (write e.g. 1/2). It is left out, as if no number had been written.", + "message": "\"a\" is per \"0 g\": a ratio cannot be per nothing of its target: write the amount it is per (e.g. / 100 g). It is left out, as if no amount had been written.", "item": "a", "loc": { "start": 79, "end": 94 }, "data": { - "reason": "zeroDenominator" + "reason": "zeroRatioDenominator" } }, { diff --git a/conformance/cases/warn-023-ratio-unit-guardrail/compiled.json b/conformance/cases/warn-023-ratio-unit-guardrail/compiled.json index cdd866c6..05c23b1d 100644 --- a/conformance/cases/warn-023-ratio-unit-guardrail/compiled.json +++ b/conformance/cases/warn-023-ratio-unit-guardrail/compiled.json @@ -604,14 +604,14 @@ "warnings": [ { "code": "INVALID_QUANTITY", - "message": "Number \"1 / 0 g @&flour\" of \"a\" is not read: a fraction cannot have 0 below the bar (write e.g. 1/2). It is left out, as if no number had been written.", + "message": "\"a\" is per \"0 g\": a ratio cannot be per nothing of its target: write the amount it is per (e.g. / 100 g). It is left out, as if no amount had been written.", "item": "a", "loc": { "start": 79, "end": 94 }, "data": { - "reason": "zeroDenominator" + "reason": "zeroRatioDenominator" } }, { diff --git a/packages/analyzer/src/index.ts b/packages/analyzer/src/index.ts index 3c98eb1b..957517df 100644 --- a/packages/analyzer/src/index.ts +++ b/packages/analyzer/src/index.ts @@ -340,7 +340,9 @@ function producersFirst(sections: AnalyzedSection[]): AnalyzedSection[] { * What an intermediate used whole in `sec` weighs (`Roll out the &dough`, * no amount written for it in the section): the mass of the section that * makes it, when that section declares it in its title and its mass is - * complete. Refused when another section uses it too (who takes what?). + * complete. Refused when another section uses it too (who takes what?), and + * when a step makes it (`stepProducer`): what a step makes has no mass of its + * own yet. * `null` when the section does write an amount for it. */ function wholeUseMass( @@ -362,6 +364,17 @@ function wholeUseMass( s.intermediate_preparation && slugify(s.intermediate_preparation) === targetId, ); + if ( + !producer && + sections.some((s) => + s.steps.some( + (step) => + step.type === "step" && step.intermediate_preparation === targetId, + ), + ) + ) { + return { reason: "stepProducer" }; + } const metrics = producer?.metrics; if (!metrics || metrics.massStatus === "incomplete" || !metrics.totalMass) { return { reason: "producerMassUnknown" }; diff --git a/packages/analyzer/tests/unit-ratios.test.ts b/packages/analyzer/tests/unit-ratios.test.ts index 9b0fff3c..302442dd 100644 --- a/packages/analyzer/tests/unit-ratios.test.ts +++ b/packages/analyzer/tests/unit-ratios.test.ts @@ -178,6 +178,21 @@ Mix @flour{500 g} and @water{60% @&flour}. "mass of the section that makes it is unknown", ); }); + + it("says a step makes it, for a ratio, a share and a timer", () => { + const result = run( + "## Dough\n\nMix @flour{500 g} and @water{300 g}. ->&dough\n\n## Bake\n\nRoll out the &dough, add @salt{2 g / 100 g &dough} and @sugar{1% &dough}, bake ~{30 min / 1 kg &dough}.\n", + ); + const said = result.warnings.filter( + (w) => w.code === WarningCode.RELATIVE_QUANTITY_UNKNOWN_MASS, + ); + expect(said.map((w) => w.item).sort()).toEqual(["Timer", "salt", "sugar"]); + for (const warning of said) { + expect(warning.message).toContain( + "'&dough' is made by a step, not by a whole section", + ); + } + }); }); describe("the schedule of a proportional time resolved here", () => { diff --git a/packages/docs/src/content/docs/docs/reference/api/warnings.mdx b/packages/docs/src/content/docs/docs/reference/api/warnings.mdx index d911f9fe..e461b133 100644 --- a/packages/docs/src/content/docs/docs/reference/api/warnings.mdx +++ b/packages/docs/src/content/docs/docs/reference/api/warnings.mdx @@ -54,6 +54,7 @@ For a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with - `incompatibleUnits`: mismatched counts (`2 slices` against cloves), a weight against a named piece, or trailing words (`100 g of`). - `missingDensity` / `missingUnitWeight`: converting between weight and volume or pieces requires `density` or `unit_weight` in the database. - `wholeUseAmbiguous` / `producerMassUnknown`: for an intermediate used whole (`&dough`), either another section also consumes it or the producing section's mass is incomplete. +- `stepProducer`: the intermediate used whole is made by a step (`Mix … ->&dough`), not by a whole section, and only a section's mass is weighed. Write the amount used (`&dough{500 g}`), or make it in its own section. **Fix**: match the target's unit, add `density` or `unit_weight` to the database, or specify the intermediate's used quantity (`&dough{500 g}`). @@ -87,6 +88,7 @@ Emitted when a [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-q | `rangeAfterMinus` | `{1 cup - 1-2 tbsp}` | Put ranges on added terms, or write the total as a range. | | `minusAcrossFamilies` | `{1 cup - 20 g}` | Subtract only from the same unit family (volume from volume, weight from weight). | | `zeroDenominator` | `{1/0 cup}`, `{1/0% &dough}`, `#pan{1/0}`, `^{1/0 °C}` | Division by zero is ignored; write a valid fraction (`1/2`). | +| `zeroRatioDenominator` | `{2 g / 0 g @&flour}`, `~{15 min / 0 g @&roast}` | A ratio per nothing is ignored; write the amount it is per (`/ 100 g`). | | `relativeNotSupported` | `@eggs{3}<@box{50% @&flour}`, `@eggs{1}<@box{1 / 100 g @&flour}` | Percentages and ratios are not supported on composite parents yet; specify the parent's quantity (`@eggs{3}<@box{1}`). | Subtraction is checked per unit family: `{1 cup - 2 tbsp + 30 g}` is valid (2 tbsp are subtracted from 1 cup), while `{1 cup - 20 g}` has no weight to subtract from. diff --git a/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx b/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx index b6844cec..34827a13 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx @@ -86,7 +86,7 @@ If a ratio cannot be resolved, it remains as written in views and shopping lists ### Scope, intermediates & scaling - **Same scope as percentages**: target an `@&ingredient` declared earlier in the section (repeated uses sum up), an earlier option in an alternative group, or an `&intermediate`. -- **Whole intermediates**: if a section consumes an intermediate without a quantity (`Roll out the &dough`), ratios and percentages (`@salt{2 g / 100 g &dough}`, `@sugar{5% &dough}`) resolve against the total mass of the section that produces it—provided only that section consumes it. +- **Whole intermediates**: if a section consumes an intermediate without a quantity (`Roll out the &dough`), ratios and percentages (`@salt{2 g / 100 g &dough}`, `@sugar{5% &dough}`) resolve against the total mass of the section that produces it—provided only that section consumes it. An intermediate made by a step (`Mix … ->&dough`) has no mass of its own: write the amount used (`&dough{800 g}`), or make it in its own section. - **References & composites**: ratios and percentages work on homemade intermediate references (`&stock{250 ml / 100 g @&rice}`), but are not yet supported on composite parents (`@eggs{1}<@box{1 / 100 g @&flour}>`). - **Scaling**: scaling a recipe recalculates ratios from the scaled targets (unless the target is fixed with `@=`). Marking a ratio itself with `=` is not allowed. diff --git a/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx b/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx index 0824b373..d04fd346 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx @@ -55,6 +55,7 @@ Pour une [proportion avec unités](/fr/docs/reference/syntax/relative-quantities - `incompatibleUnits` : pièces incompatibles (`2 tranches` face à des gousses), poids face à une pièce nommée, ou mot après l'unité (`100 g de`). - `missingDensity` / `missingUnitWeight` : la conversion entre poids et volume ou pièces requiert `density` ou `unit_weight` dans la base d'ingrédients. - `wholeUseAmbiguous` / `producerMassUnknown` : pour une préparation utilisée en entier (`&pâte`), une autre section la consomme aussi ou la masse de sa section productrice est incomplète. +- `stepProducer` : la préparation utilisée en entier sort d'une étape (`Mélanger … ->&pâte`) et non d'une section entière, or Gram ne pèse que ce qu'une section produit. Indiquez la quantité utilisée (`&pâte{500 g}`), ou préparez-la dans sa propre section. **Correction** : écrivez la proportion dans l'unité de la cible, renseignez `density` ou `unit_weight` dans la base, ou indiquez la quantité utilisée (`&pâte{500 g}`). @@ -88,6 +89,7 @@ Un `Timer` (minuteur) ou une `Temperature` a été écrit sans unité explicite | `rangeAfterMinus` | `{1 tasse - 1-2 càs}` | Placez les fourchettes sur un terme ajouté, ou écrivez le total en fourchette. | | `minusAcrossFamilies` | `{1 tasse - 20 g}` | Soustrayez uniquement au sein d'une même famille d'unités (volume d'un volume, masse d'une masse). | | `zeroDenominator` | `{1/0 tasse}`, `{1/0% &pâte}`, `#poêle{1/0}`, `^{1/0 °C}` | Une division par zéro est ignorée ; écrivez une fraction valide (`1/2`). | +| `zeroRatioDenominator` | `{2 g / 0 g @&farine}`, `~{15 min / 0 g @&rôti}` | Une proportion rapportée à rien est ignorée ; indiquez la quantité de référence (`/ 100 g`). | | `relativeNotSupported` | `@œufs{3}<@boîte{50% @&farine}`, `@œufs{1}<@boîte{1 / 100 g @&farine}` | Pourcentages et proportions ne sont pas encore pris en charge sur un parent composite ; indiquez sa quantité (`@œufs{3}<@boîte{1}`). | La soustraction est vérifiée par famille d'unités : `{1 tasse - 2 càs + 30 g}` est valide (2 càs retirées de 1 tasse), tandis que `{1 tasse - 20 g}` n'a aucune masse dont soustraire les 20 g. diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx index b4386c30..ab67c4bb 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx @@ -86,7 +86,7 @@ Si une proportion ne peut pas être résolue, elle conserve son écriture dans l ### Portée, préparations intermédiaires et mise à l'échelle - **Même portée que les pourcentages** : ciblez un `@&ingrédient` déclaré plus tôt dans la section (les mentions s'additionnent), une option précédente d'une alternative ou une `&préparation`. -- **Préparations utilisées en entier** : si une section utilise une préparation intermédiaire sans quantité (`Étaler la &pâte`), proportions et pourcentages (`@sel{2 g / 100 g &pâte}`, `@sucre{5% &pâte}`) se calculent sur la masse totale de la section qui la produit, à condition qu'elle seule la consomme. +- **Préparations utilisées en entier** : si une section utilise une préparation intermédiaire sans quantité (`Étaler la &pâte`), proportions et pourcentages (`@sel{2 g / 100 g &pâte}`, `@sucre{5% &pâte}`) se calculent sur la masse totale de la section qui la produit, à condition qu'elle seule la consomme. Une préparation qui sort d'une étape (`Mélanger … ->&pâte`) n'a pas de masse propre : indiquez la quantité utilisée (`&pâte{800 g}`), ou préparez-la dans sa propre section. - **Références et composites** : proportions et pourcentages fonctionnent sur les références à une préparation maison (`&bouillon{250 ml / 100 g @&riz}`), mais pas encore sur un parent composite (`@œufs{1}<@boîte{1 / 100 g @&farine}`). - **Mise à l'échelle** : changer l'échelle d'une recette recalcule les proportions à partir des cibles mises à l'échelle (sauf si la cible est figée avec `@=`). Le modificateur `=` sur la proportion elle-même est refusé. diff --git a/packages/kitchen/src/compound.ts b/packages/kitchen/src/compound.ts index 7b93ea0b..b6fcfe9b 100644 --- a/packages/kitchen/src/compound.ts +++ b/packages/kitchen/src/compound.ts @@ -38,6 +38,12 @@ export type InvalidQuantityReason = * temperature. Since 1.5.0. */ | "zeroDenominator" + /** + * `@salt{2 g / 0 g @&flour}`, `~{15 min / 0 g @&roast}`: a ratio per + * zero of its target has no value. `value` is the denominator as written + * (`0 g`). Since 1.5.0. + */ + | "zeroRatioDenominator" /** * `@eggs{3}<@box{50% @&flour}>`: a share of another ingredient on a * composite parent. Refused until composites are reworked (1.6): the diff --git a/packages/kitchen/src/processor.ts b/packages/kitchen/src/processor.ts index c3b53509..bcfdec41 100644 --- a/packages/kitchen/src/processor.ts +++ b/packages/kitchen/src/processor.ts @@ -452,6 +452,17 @@ function checkRelativeParent(ctx: ProcessorContext, item: IngredientAST) { }); } +/** + * A share's or a ratio's target as its author wrote it (`pate`), for what a + * reader sees: the compiled `target`, its formula, its warnings. Module + * composition renames a base's private intermediate (`dough$pate`); the + * target is still found by `targetId`. + */ +const shownTarget = (quantity: { + target: string; + targetDisplayName?: string; +}): string => quantity.targetDisplayName ?? quantity.target; + /** * The target of a share or a ratio (`@&flour`, `&dough`): its id, and * whether it is where it should be. An intermediate must be defined; an @@ -464,7 +475,11 @@ function checkRelativeTarget( ctx: ProcessorContext, registry: RecipeRegistry, secIngredients: Usage[], - target: { target: string; referenceType: "variable" | "ingredient" }, + target: { + target: string; + targetDisplayName?: string; + referenceType: "variable" | "ingredient"; + }, item: { name: string; loc?: Location }, selfId?: string, ): { targetId: string; isGhost: boolean; isCircular: boolean } { @@ -476,7 +491,7 @@ function checkRelativeTarget( if (!ctx.definedIntermediates.has(targetName)) { isGhost = true; pushWarning(ctx, WarningCode.VARIABLE_NOT_FOUND, { - targetName, + targetName: shownTarget(target), item: item.name, loc: item.loc, }); @@ -510,20 +525,24 @@ const ratioRefusedNumbers = (quantity: RatioQuantityAST) => /** * True when a ratio can be read: none of its numbers was refused (already * said, `zeroDenominator`), and its denominator is not zero (`/ 0 g`, said - * here). One that cannot reads as if no amount had been written. + * here, `zeroRatioDenominator`). One that cannot reads as if no amount had + * been written. */ function isReadableRatio( ctx: ProcessorContext, quantity: RatioQuantityAST, item: string, loc?: Location, + type?: "Timer", ): boolean { if (ratioRefusedNumbers(quantity).length > 0) return false; if (quantity.denominator.value?.value === 0) { + const { unit } = quantity.denominator; pushWarning(ctx, WarningCode.INVALID_QUANTITY, { - value: quantity.raw, - reason: "zeroDenominator", + value: unit ? `0 ${unit}` : "0", + reason: "zeroRatioDenominator", item, + ...(type && { type }), loc: quantity.loc ?? loc, }); return false; @@ -544,7 +563,7 @@ function ratioSpecOf( value: quantity.denominator.value?.value ?? 1, unit: quantity.denominator.unit, }, - target: quantity.target, + target: shownTarget(quantity), targetId, referenceType: quantity.referenceType, raw: quantity.raw, @@ -576,7 +595,7 @@ function writeRatioUsage( usage.dependencies = [target.targetId]; usage.formula = { raw: quantity.raw, - target: quantity.target, + target: shownTarget(quantity), ratio: spec, isGhost: target.isGhost, }; @@ -686,15 +705,16 @@ function processIngredient( const usage = createCleanUsage(item, id, ctx.usageCounter, ctx.options); // Defer evaluation to analyzer. The percentage's `text` stays in the // AST: the compiled JSON keeps the shape 1.3.0 published. - const { text: _text, ...qty } = rel; + const { text: _text, targetDisplayName: _shown, ...qty } = rel; + qty.target = shownTarget(rel); usage.qty = qty; usage.unit = null; if (target.isCircular) usage.isCircular = true; usage.dependencies = [target.targetId]; usage.formula = { - raw: `${rel.percent}% of ${rel.target}`, - target: rel.target, + raw: `${rel.percent}% of ${shownTarget(rel)}`, + target: shownTarget(rel), percent: rel.percent, isGhost: target.isGhost, }; @@ -901,14 +921,15 @@ function processReference( { name: item.displayName ?? cleanName, loc: item.loc }, id, ); - const { text: _text, ...qty } = rel; + const { text: _text, targetDisplayName: _shown, ...qty } = rel; + qty.target = shownTarget(rel); obj.qty = qty; obj.unit = null; if (target.isCircular) obj.isCircular = true; obj.dependencies = [target.targetId]; obj.formula = { - raw: `${rel.percent}% of ${rel.target}`, - target: rel.target, + raw: `${rel.percent}% of ${shownTarget(rel)}`, + target: shownTarget(rel), percent: rel.percent, isGhost: target.isGhost, }; @@ -989,7 +1010,7 @@ function processTimer( ); return obj; } - if (!isReadableRatio(ctx, ratio, name, item.loc)) return obj; + if (!isReadableRatio(ctx, ratio, name, item.loc, "Timer")) return obj; const target = checkRelativeTarget(ctx, registry, secIngredients, ratio, { name, loc: item.loc, diff --git a/packages/kitchen/src/ratio.ts b/packages/kitchen/src/ratio.ts index b4450a65..17c3f5c8 100644 --- a/packages/kitchen/src/ratio.ts +++ b/packages/kitchen/src/ratio.ts @@ -35,7 +35,10 @@ import { * - `missingDensity`: across mass and volume, with no density; * - `missingUnitWeight`: between pieces and a weight, with no unit weight; * - `wholeUseAmbiguous`, `producerMassUnknown`: an intermediate used whole, - * when its mass cannot be told (analyzer). + * when its mass cannot be told (analyzer); + * - `stepProducer`: an intermediate used whole that a step makes + * (`Mix … ->&dough`), not a section: only a section's mass is weighed + * (analyzer). Since 1.5.0. */ export type RatioFailure = | "deferred" @@ -44,7 +47,8 @@ export type RatioFailure = | "missingDensity" | "missingUnitWeight" | "wholeUseAmbiguous" - | "producerMassUnknown"; + | "producerMassUnknown" + | "stepProducer"; export type RatioResolution = | { ok: true; amount: Term } diff --git a/packages/kitchen/src/warnings.ts b/packages/kitchen/src/warnings.ts index 86fd53f0..5cb8cd7e 100644 --- a/packages/kitchen/src/warnings.ts +++ b/packages/kitchen/src/warnings.ts @@ -111,6 +111,8 @@ export interface WarningPayloads { /** What to write instead, when Gram can tell (`110 g`). */ suggestion?: string; item: string; + /** `"Timer"` when the quantity is a timer's (`~{15 min / 0 g @&roast}`). */ + type?: "Timer"; loc?: Location; }; [WarningCode.OZ_AFTER_VOLUME]: { @@ -248,6 +250,8 @@ function ratioHint( return `'&${target}' is used whole in several sections: write the amount used here (e.g. &${target}{500 g}).`; case "producerMassUnknown": return `'&${target}' is used whole and the mass of the section that makes it is unknown: write the amount used here (e.g. &${target}{500 g}).`; + case "stepProducer": + return `'&${target}' is made by a step, not by a whole section, and Gram only weighs what a section makes (## Dough ->&dough): write the amount used here (e.g. &${target}{500 g}), or make it in a section of its own.`; } } @@ -266,6 +270,8 @@ const QUANTITY_HINTS: Record = { rangeAfterMinus: "a range cannot be taken away (its bounds would swap): write the range on a term that is added, or the total as a range.", zeroDenominator: "a fraction cannot have 0 below the bar (write e.g. 1/2).", + zeroRatioDenominator: + "a ratio cannot be per nothing of its target: write the amount it is per (e.g. / 100 g).", relativeNotSupported: "a share of another ingredient is not supported on a composite parent yet: write the parent's amount.", minusAcrossFamilies: @@ -306,11 +312,13 @@ export const warningTemplates: { ? `Retro-planning offset "${p.value}" on "${p.item}" is not read: ${DURATION_HINTS[p.reason] ?? p.reason} The section is not anchored.` : `Timer duration "${p.value}"${p.item === "Timer" ? "" : ` on "${p.item}"`} is not read: ${DURATION_HINTS[p.reason] ?? p.reason} It is not counted in the total time.`, [WarningCode.INVALID_QUANTITY]: (p) => - p.reason === "zeroDenominator" - ? `Number "${p.value}" of "${p.item}" is not read: ${QUANTITY_HINTS.zeroDenominator} It is left out, as if no number had been written.` - : p.reason === "relativeNotSupported" - ? `Quantity "${p.value}" of "${p.item}" is not read: ${QUANTITY_HINTS.relativeNotSupported} The parent is read with no quantity.` - : `Quantity "${p.value}" of "${p.item}" is not read: ${QUANTITY_HINTS[p.reason] ?? p.reason}${p.suggestion ? ` Did you mean {${p.suggestion}}?` : ""} It is not counted in the shopping list or the nutrition.`, + p.reason === "zeroRatioDenominator" + ? `${p.type === "Timer" ? (p.item === "Timer" ? "A timer" : `Timer "${p.item}"`) : `"${p.item}"`} is per "${p.value}": ${QUANTITY_HINTS.zeroRatioDenominator} ${p.type === "Timer" ? "It is not counted in the total time." : "It is left out, as if no amount had been written."}` + : p.reason === "zeroDenominator" + ? `Number "${p.value}" of "${p.item}" is not read: ${QUANTITY_HINTS.zeroDenominator} It is left out, as if no number had been written.` + : p.reason === "relativeNotSupported" + ? `Quantity "${p.value}" of "${p.item}" is not read: ${QUANTITY_HINTS.relativeNotSupported} The parent is read with no quantity.` + : `Quantity "${p.value}" of "${p.item}" is not read: ${QUANTITY_HINTS[p.reason] ?? p.reason}${p.suggestion ? ` Did you mean {${p.suggestion}}?` : ""} It is not counted in the shopping list or the nutrition.`, [WarningCode.OZ_AFTER_VOLUME]: (p) => `"${p.value}" of "${p.item}" is a weight: oz weighs, ${p.suggestion} measures a volume. Write ${p.suggestion} if a volume is meant.`, [WarningCode.AMBIGUOUS_NUMBER]: (p) => diff --git a/packages/kitchen/tests/zero-denominator.test.ts b/packages/kitchen/tests/zero-denominator.test.ts index fc6b1afc..7d46386b 100644 --- a/packages/kitchen/tests/zero-denominator.test.ts +++ b/packages/kitchen/tests/zero-denominator.test.ts @@ -47,3 +47,32 @@ describe("a fraction over zero (INVALID_QUANTITY, zeroDenominator)", () => { expect(codes).toEqual(["INVALID_DURATION"]); }); }); + +describe("a ratio per zero of its target (INVALID_QUANTITY, zeroRatioDenominator)", () => { + it("quotes the denominator, not the whole ratio as a number", () => { + const [warning, ...rest] = warningsOf( + "Add @flour{100 g} and @eggs{1 / 0 g @&flour}.", + ); + expect(rest).toHaveLength(0); + expect(warning?.data).toEqual({ reason: "zeroRatioDenominator" }); + expect(warning?.message).toBe( + '"eggs" is per "0 g": a ratio cannot be per nothing of its target: write the amount it is per (e.g. / 100 g). It is left out, as if no amount had been written.', + ); + }); + + it("speaks of a timer, never of a type name, and of the total time", () => { + const [warning] = warningsOf("Roast @roast{1 kg} ~{15 min / 0 g @&roast}."); + expect(warning?.data).toEqual({ reason: "zeroRatioDenominator" }); + expect(warning?.message).toStartWith('A timer is per "0 g": '); + expect(warning?.message).toEndWith("It is not counted in the total time."); + expect(warning?.message).not.toContain("fraction"); + }); + + it("names a named timer", () => { + const [warning] = warningsOf( + "Roast @roast{1 kg} ~roast{15 min / 0 kg @&roast}.", + ); + expect(warning?.message).toStartWith('Timer "roast" is per "0 kg": '); + expect(warning?.message).toEndWith("It is not counted in the total time."); + }); +}); diff --git a/packages/modules/src/rename.ts b/packages/modules/src/rename.ts index a1c08206..148d7e63 100644 --- a/packages/modules/src/rename.ts +++ b/packages/modules/src/rename.ts @@ -91,10 +91,16 @@ export function buildRenameTable( */ function renameRelativeTarget( quantity: - | { type: string; referenceType?: string; target?: string } + | { + type: string; + referenceType?: string; + target?: string; + targetDisplayName?: string; + } | null | undefined, rename: (name: string) => string, + scoped?: ReadonlySet, ): void { if ( quantity && @@ -103,6 +109,13 @@ function renameRelativeTarget( quantity.referenceType === "variable" && quantity.target !== undefined ) { + // As for a name (`rename` in `applyRename`): a scoped target keeps + // what its author wrote for the reader, the innermost across splices. + if (scoped?.has(quantity.target)) { + quantity.targetDisplayName ??= quantity.target; + } else if (rename(quantity.target) !== quantity.target) { + delete quantity.targetDisplayName; + } quantity.target = rename(quantity.target); } } @@ -138,16 +151,16 @@ export function applyRename( rename(c); } else if (c.type === ASTNodeType.Reference) { rename(c); - renameRelativeTarget(c.quantity, renameName); + renameRelativeTarget(c.quantity, renameName, table.scoped); } else if ( c.type === ASTNodeType.Ingredient || c.type === ASTNodeType.Timer ) { - renameRelativeTarget(c.quantity, renameName); + renameRelativeTarget(c.quantity, renameName, table.scoped); } else if (c.type === ASTNodeType.Alternative) { c.options.forEach((opt) => { if (opt.type === ASTNodeType.Ingredient) { - renameRelativeTarget(opt.quantity, renameName); + renameRelativeTarget(opt.quantity, renameName, table.scoped); } }); } diff --git a/packages/modules/tests/private-target-name.test.ts b/packages/modules/tests/private-target-name.test.ts new file mode 100644 index 00000000..3e065c84 --- /dev/null +++ b/packages/modules/tests/private-target-name.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "bun:test"; +import { analyze } from "@gram-lang/analyzer"; +import { compile } from "@gram-lang/kitchen"; +import { composeRecipe, finalizeComposed } from "../src/compose"; +import { loadModuleGraph } from "../src/graph"; +import { createFakeHost } from "./fake-host"; + +// A base's private intermediate is renamed when it is spliced (`pate` → +// `dough$pate`), so it can never collide with one of the importer's. The +// new name is an identity: a share or a ratio still finds its target by it, +// but what a reader sees (a formula, a warning) is what the author wrote. + +async function build(base: string) { + const host = createFakeHost({ + "/recipe.gram": `@use "./pate.gram" as &dough\n\n## Montage\n\nFill the &dough{}.\n`, + "/pate.gram": base, + }); + const graph = await loadModuleGraph("/recipe.gram", host); + const composed = composeRecipe(graph, { db: {} }); + const { result } = analyze(compile(composed.ast), { + ...composed.syntheticIngredients, + }); + const final = finalizeComposed(result, composed); + return { result: final, warnings: final.warnings }; +} + +const salt = (result: Awaited>["result"]) => + result.sections.flatMap((s) => s.ingredients).find((i) => i.id === "salt"); + +describe("a base's private intermediate, as a target", () => { + it("is found by its new name and shown by the one written", async () => { + const { result, warnings } = await build( + "## Petrissage\n\nMix @flour{500 g} and @water{300 g}. ->&pate\n\n## Repos\n\nWork @salt{2 g / 100 g &pate} into the &pate{800 g}.\n", + ); + const usage = salt(result); + expect(usage?.qty).toEqual({ type: "single", value: 16 }); + expect(usage?.formula?.target).toBe("pate"); + expect(usage?.dependencies).toEqual(["dough-pate"]); + expect(JSON.stringify(warnings)).not.toContain("$"); + }); + + it("never shows its new name in a warning", async () => { + const { warnings } = await build( + "## Petrissage\n\nMix @flour{500 g} and @water{300 g}. ->&pate\n\n## Repos\n\nWork @salt{2% &pate} into the &pate{}.\n", + ); + const said = warnings.filter( + (w) => w.code === "RELATIVE_QUANTITY_UNKNOWN_MASS", + ); + expect(said).toHaveLength(1); + expect(said[0]?.message).toContain("'&pate' is made by a step"); + expect(said[0]?.message).not.toContain("$"); + }); +}); diff --git a/packages/parser/src/types.ts b/packages/parser/src/types.ts index d1798036..2326e288 100644 --- a/packages/parser/src/types.ts +++ b/packages/parser/src/types.ts @@ -181,6 +181,12 @@ export interface RelativeQuantityAST extends NodeAST { /** The percentage as written, e.g. `12,5` (so a comma can be told from a point). */ text?: string; target: string; + /** + * The target as its author wrote it (`pate`), when module composition + * renamed `target` to an internal name (`dough$pate`): for what a reader + * sees, never for finding the target. Omitted otherwise. Since 1.5.0. + */ + targetDisplayName?: string; referenceType: "variable" | "ingredient"; /** * A number Gram refused, as written: a fraction over zero (`1/0`, @@ -220,6 +226,12 @@ export interface RatioQuantityAST extends NodeAST { /** A timer's numerator as written (`15 min`, `1:30 h`), read by `parseDuration`. Timers only. */ durationRaw?: string; target: string; + /** + * The target as its author wrote it (`pate`), when module composition + * renamed `target` to an internal name (`dough$pate`): for what a reader + * sees, never for finding the target. Omitted otherwise. Since 1.5.0. + */ + targetDisplayName?: string; referenceType: "variable" | "ingredient"; /** The ratio as written between the braces, trimmed (`1 / 100 g @&flour`). */ raw: string; -- 2.54.0 From b706629157844dd0da8fcd3e04b595419c5371ec Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:46 +0100 Subject: [PATCH 03/11] test(conformance): add a ratio and a proportional timer inside a used base --- .../cases/mod-032-ratio-in-base/analyzed.json | 954 ++++++++++++++++++ .../cases/mod-032-ratio-in-base/ast.json | 217 ++++ .../mod-032-ratio-in-base/bases/pate.gram | 13 + .../cases/mod-032-ratio-in-base/compiled.json | 827 +++++++++++++++ .../cases/mod-032-ratio-in-base/input.gram | 13 + 5 files changed, 2024 insertions(+) create mode 100644 conformance/cases/mod-032-ratio-in-base/analyzed.json create mode 100644 conformance/cases/mod-032-ratio-in-base/ast.json create mode 100644 conformance/cases/mod-032-ratio-in-base/bases/pate.gram create mode 100644 conformance/cases/mod-032-ratio-in-base/compiled.json create mode 100644 conformance/cases/mod-032-ratio-in-base/input.gram diff --git a/conformance/cases/mod-032-ratio-in-base/analyzed.json b/conformance/cases/mod-032-ratio-in-base/analyzed.json new file mode 100644 index 00000000..3581a335 --- /dev/null +++ b/conformance/cases/mod-032-ratio-in-base/analyzed.json @@ -0,0 +1,954 @@ +{ + "title": "Mod Ratio In Base", + "slug": "mod-ratio-in-base", + "meta": { + "title": "Mod Ratio In Base" + }, + "registry": { + "ingredients": { + "flour": { + "id": "flour", + "name": "flour", + "default_unit": "g" + }, + "water": { + "id": "water", + "name": "water", + "default_unit": "g" + }, + "dough-pate": { + "id": "dough-pate", + "name": "pate", + "is_intermediate": true + }, + "dough": { + "id": "dough", + "name": "dough", + "is_intermediate": true + }, + "salt": { + "id": "salt", + "name": "salt" + }, + "ricotta": { + "id": "ricotta", + "name": "ricotta", + "default_unit": "g" + }, + "spinach": { + "id": "spinach", + "name": "spinach", + "default_unit": "g" + }, + "pate": { + "id": "pate", + "name": "pate", + "is_intermediate": true + } + }, + "cookware": {} + }, + "shopping_list": [ + { + "id": "flour", + "name": "flour", + "_usageIds": [ + "1" + ], + "qty": 500, + "unit": "g", + "normalizedMass": 500, + "isEstimate": false, + "conversionMethod": "physical" + }, + { + "id": "water", + "name": "water", + "_usageIds": [ + "2" + ], + "qty": 300, + "unit": "g", + "normalizedMass": 300, + "isEstimate": false, + "conversionMethod": "physical" + }, + { + "id": "salt", + "name": "salt", + "_usageIds": [ + "3" + ], + "relative": true, + "qty": 16, + "unit": "g", + "normalizedMass": 16, + "isEstimate": false, + "conversionMethod": "physical" + }, + { + "id": "ricotta", + "name": "ricotta", + "_usageIds": [ + "5" + ], + "qty": 250, + "unit": "g", + "normalizedMass": 250, + "isEstimate": false, + "conversionMethod": "physical" + }, + { + "id": "spinach", + "name": "spinach", + "_usageIds": [ + "6" + ], + "qty": 200, + "unit": "g", + "normalizedMass": 200, + "isEstimate": false, + "conversionMethod": "physical" + } + ], + "cookware": [], + "sections": [ + { + "title": "Petrissage", + "ingredients": [ + { + "id": "flour", + "_usageId": "1", + "qty": 500, + "unit": "g", + "conversionMethod": "physical", + "isEstimate": false, + "normalizedMass": 500 + }, + { + "id": "water", + "_usageId": "2", + "qty": 300, + "unit": "g", + "conversionMethod": "physical", + "isEstimate": false, + "normalizedMass": 300 + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Mix ", + { + "id": "flour", + "_usageId": "1", + "qty": 500, + "unit": "g", + "normalizedMass": 500, + "conversionMethod": "physical", + "isEstimate": false + }, + "and ", + { + "id": "water", + "_usageId": "2", + "qty": 300, + "unit": "g", + "normalizedMass": 300, + "conversionMethod": "physical", + "isEstimate": false + }, + ". ", + { + "type": "declaration", + "name": "dough$pate", + "id": "dough-pate" + } + ], + "timings": { + "start": 0, + "end": 2, + "activeDuration": 2 + }, + "intermediate_preparation": "dough-pate" + } + ], + "module": { + "binding": "dough", + "uri": "bases/pate.gram", + "title": "Pate", + "mode": "inline" + }, + "metrics": { + "totalMass": 800, + "massStatus": "precise", + "missingMassIngredients": [] + } + }, + { + "title": "Repos", + "ingredients": [ + { + "id": "salt", + "_usageId": "3", + "qty": { + "type": "single", + "value": 16 + }, + "dependencies": [ + "dough-pate" + ], + "formula": { + "raw": "2 g / 100 g &pate", + "target": "pate", + "ratio": { + "numerator": { + "value": { + "type": "single", + "value": 2, + "text": "2" + }, + "unit": "g" + }, + "denominator": { + "value": 100, + "unit": "g" + }, + "target": "pate", + "targetId": "dough-pate", + "referenceType": "variable", + "raw": "2 g / 100 g &pate", + "loc": { + "start": 103, + "end": 120 + } + }, + "isGhost": false + }, + "conversionMethod": "physical", + "isEstimate": false, + "normalizedMass": 16, + "unit": "g" + }, + { + "type": "reference", + "id": "dough-pate", + "name": "dough$pate", + "_usageId": "4", + "qty": 800, + "unit": "g", + "conversionMethod": "physical", + "isEstimate": false, + "normalizedMass": 800 + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Work ", + { + "id": "salt", + "_usageId": "3", + "qty": { + "type": "single", + "value": 16 + }, + "dependencies": [ + "dough-pate" + ], + "formula": { + "raw": "2 g / 100 g &pate", + "target": "pate", + "ratio": { + "numerator": { + "value": { + "type": "single", + "value": 2, + "text": "2" + }, + "unit": "g" + }, + "denominator": { + "value": 100, + "unit": "g" + }, + "target": "pate", + "targetId": "dough-pate", + "referenceType": "variable", + "raw": "2 g / 100 g &pate", + "loc": { + "start": 103, + "end": 120 + } + }, + "isGhost": false + }, + "unit": "g", + "normalizedMass": 16, + "conversionMethod": "physical", + "isEstimate": false + }, + "into the ", + { + "type": "reference", + "id": "dough-pate", + "name": "dough$pate", + "_usageId": "4", + "qty": 800, + "unit": "g", + "normalizedMass": 800, + "conversionMethod": "physical", + "isEstimate": false + }, + "." + ], + "timings": { + "start": 2, + "end": 4, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Rest ", + { + "type": "timer", + "raw": "15 min / 500 g &pate", + "ratio": { + "numerator": { + "value": { + "type": "single", + "value": 15 + }, + "unit": "min" + }, + "denominator": { + "value": 500, + "unit": "g" + }, + "target": "pate", + "targetId": "dough-pate", + "referenceType": "variable", + "raw": "15 min / 500 g &pate", + "loc": { + "start": 153, + "end": 173 + } + }, + "quantity": { + "type": "single", + "value": 24 + }, + "unit": "min", + "minutes": 24 + }, + "." + ], + "timings": { + "start": 4, + "end": 28, + "activeDuration": 24 + } + } + ], + "intermediate_preparation": "dough", + "module": { + "binding": "dough", + "uri": "bases/pate.gram", + "title": "Pate", + "mode": "inline" + }, + "metrics": { + "totalMass": 816, + "massStatus": "precise", + "missingMassIngredients": [] + } + }, + { + "title": "Garniture", + "ingredients": [ + { + "id": "ricotta", + "_usageId": "5", + "qty": 250, + "unit": "g", + "conversionMethod": "physical", + "isEstimate": false, + "normalizedMass": 250 + }, + { + "id": "spinach", + "_usageId": "6", + "qty": 200, + "unit": "g", + "conversionMethod": "physical", + "isEstimate": false, + "normalizedMass": 200 + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Mix ", + { + "id": "ricotta", + "_usageId": "5", + "qty": 250, + "unit": "g", + "normalizedMass": 250, + "conversionMethod": "physical", + "isEstimate": false + }, + "and ", + { + "id": "spinach", + "_usageId": "6", + "qty": 200, + "unit": "g", + "normalizedMass": 200, + "conversionMethod": "physical", + "isEstimate": false + }, + ". ", + { + "type": "declaration", + "name": "pate", + "id": "pate" + } + ], + "timings": { + "start": 28, + "end": 30, + "activeDuration": 2 + }, + "intermediate_preparation": "pate" + } + ], + "metrics": { + "totalMass": 450, + "massStatus": "precise", + "missingMassIngredients": [] + } + }, + { + "title": "Montage", + "ingredients": [ + { + "type": "reference", + "id": "dough", + "name": "dough", + "_usageId": "7" + }, + { + "type": "reference", + "id": "pate", + "name": "pate", + "_usageId": "8" + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Fill the ", + { + "type": "reference", + "id": "dough", + "name": "dough", + "_usageId": "7" + }, + "with the ", + { + "type": "reference", + "id": "pate", + "name": "pate", + "_usageId": "8" + }, + "." + ], + "timings": { + "start": 30, + "end": 32, + "activeDuration": 2 + } + } + ], + "metrics": { + "totalMass": 0, + "massStatus": "incomplete", + "missingMassIngredients": [] + } + } + ], + "warnings": [ + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"flour\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"water\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"salt\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"ricotta\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"spinach\" not found in database — nutritional metrics and density conversions unavailable." + } + ], + "metrics": { + "totalTime": 40, + "totalBreakdown": [ + { + "label": "section_active:Petrissage", + "duration": 2 + }, + { + "label": "section_active:Repos", + "duration": 26 + }, + { + "label": "section_active:Garniture", + "duration": 2 + }, + { + "label": "section_active:Montage", + "duration": 2 + } + ], + "idleTime": 0, + "activeTime": 32, + "activeBreakdown": [ + { + "label": "section_active:Petrissage", + "duration": 2 + }, + { + "label": "section_active:Repos", + "duration": 26 + }, + { + "label": "section_active:Garniture", + "duration": 2 + }, + { + "label": "section_active:Montage", + "duration": 2 + } + ], + "preparationTime": 8, + "prepBreakdown": [ + { + "label": "ingredients_overhead", + "duration": 8 + } + ], + "totalMass": 1266, + "massStatus": "precise", + "missingMassIngredients": [], + "nutrition": { + "total": { + "calories": 0, + "fat": 0, + "carbs": 0, + "protein": 0 + }, + "isEstimate": false, + "coverage": 0, + "warnings": [ + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"flour\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"water\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"salt\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"ricotta\" not found in database — nutritional metrics and density conversions unavailable." + }, + { + "code": "MISSING_INGREDIENT", + "message": "Ingredient \"spinach\" not found in database — nutritional metrics and density conversions unavailable." + } + ] + } + }, + "miseEnPlace": [ + { + "section": 0, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ] + }, + { + "section": 1, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2, + "intermediates": 1 + } + ] + }, + { + "section": 2, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ] + }, + { + "section": 3, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2, + "intermediates": 2 + } + ] + } + ], + "tasks": { + "tasks": [ + { + "id": "s0.prep", + "kind": "prep", + "section": 0, + "duration": { + "nominal": 2 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ], + "after": [] + }, + { + "id": "s0.0", + "kind": "step", + "section": 0, + "step": 0, + "duration": { + "nominal": 2 + }, + "produces": [ + "dough$pate" + ], + "after": [] + }, + { + "id": "s1.prep", + "kind": "prep", + "section": 1, + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1 + } + ], + "after": [] + }, + { + "id": "s1.prep.dough-pate", + "kind": "prep", + "section": 1, + "intermediate": "dough-pate", + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1, + "intermediates": 1 + } + ], + "after": [ + "s0.0" + ] + }, + { + "id": "s1.0", + "kind": "step", + "section": 1, + "step": 0, + "duration": { + "nominal": 2 + }, + "consumes": [ + "dough$pate" + ], + "after": [ + "s0.0" + ] + }, + { + "id": "s1.1", + "kind": "step", + "section": 1, + "step": 1, + "duration": { + "nominal": 24 + }, + "after": [ + "s1.0" + ] + }, + { + "id": "s2.prep", + "kind": "prep", + "section": 2, + "duration": { + "nominal": 2 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ], + "after": [] + }, + { + "id": "s2.0", + "kind": "step", + "section": 2, + "step": 0, + "duration": { + "nominal": 2 + }, + "produces": [ + "pate" + ], + "after": [] + }, + { + "id": "s3.prep.dough", + "kind": "prep", + "section": 3, + "intermediate": "dough", + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1, + "intermediates": 1 + } + ], + "after": [ + "s1.1" + ] + }, + { + "id": "s3.prep.pate", + "kind": "prep", + "section": 3, + "intermediate": "pate", + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1, + "intermediates": 1 + } + ], + "after": [ + "s2.0" + ] + }, + { + "id": "s3.0", + "kind": "step", + "section": 3, + "step": 0, + "duration": { + "nominal": 2 + }, + "consumes": [ + "dough", + "pate" + ], + "after": [ + "s1.1", + "s2.0" + ] + } + ], + "sections": [ + { + "day": 0 + }, + { + "day": 0, + "intermediate": "dough" + }, + { + "day": 0 + }, + { + "day": 0 + } + ] + }, + "schedule": { + "miseEnPlace": "perSection", + "rests": "shortest", + "totalTime": 40, + "activeTime": 32, + "preparationTime": 8, + "idleTime": 0, + "blocks": [ + { + "kind": "prep", + "task": "s0.prep", + "section": 0, + "start": 0, + "end": 2 + }, + { + "kind": "step", + "task": "s0.0", + "section": 0, + "step": 0, + "start": 2, + "end": 4 + }, + { + "kind": "prep", + "task": "s1.prep", + "section": 1, + "start": 4, + "end": 6 + }, + { + "kind": "step", + "task": "s1.0", + "section": 1, + "step": 0, + "start": 6, + "end": 8 + }, + { + "kind": "step", + "task": "s1.1", + "section": 1, + "step": 1, + "start": 8, + "end": 32 + }, + { + "kind": "prep", + "task": "s2.prep", + "section": 2, + "start": 32, + "end": 34 + }, + { + "kind": "step", + "task": "s2.0", + "section": 2, + "step": 0, + "start": 34, + "end": 36 + }, + { + "kind": "prep", + "task": "s3.prep.dough", + "section": 3, + "start": 36, + "end": 38 + }, + { + "kind": "step", + "task": "s3.0", + "section": 3, + "step": 0, + "start": 38, + "end": 40 + } + ], + "days": [ + { + "day": 0, + "start": 0, + "end": 40, + "sections": [ + 0, + 1, + 2, + 3 + ] + } + ] + }, + "modules": [ + { + "binding": "dough", + "uri": "bases/pate.gram", + "title": "Pate", + "meta": { + "title": "Pate" + }, + "scaleFactor": 1, + "mode": "inline" + } + ] +} diff --git a/conformance/cases/mod-032-ratio-in-base/ast.json b/conformance/cases/mod-032-ratio-in-base/ast.json new file mode 100644 index 00000000..3a9baf96 --- /dev/null +++ b/conformance/cases/mod-032-ratio-in-base/ast.json @@ -0,0 +1,217 @@ +{ + "type": "Recipe", + "meta": { + "title": "Mod Ratio In Base" + }, + "imports": [ + { + "type": "ImportDecl", + "specifier": "./bases/pate.gram", + "bindings": [ + { + "exported": "default", + "local": "dough", + "loc": { + "start": 62, + "end": 68 + } + } + ], + "retroPlanning": null, + "loc": { + "start": 34, + "end": 69 + } + } + ], + "children": [ + { + "type": "Section", + "title": "Garniture", + "retroPlanning": null, + "intermediateDecl": null, + "children": [ + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Mix ", + "loc": { + "start": 84, + "end": 88 + } + }, + { + "type": "Ingredient", + "name": "ricotta", + "modifiers": [], + "quantity": { + "type": "Quantity", + "value": { + "type": "single", + "value": 250, + "text": "250" + }, + "unit": "g", + "fixed": false, + "loc": { + "start": 97, + "end": 102 + } + }, + "alias": null, + "preparation": null, + "composite": null, + "loc": { + "start": 88, + "end": 103 + } + }, + { + "type": "Text", + "value": "and ", + "loc": { + "start": 104, + "end": 108 + } + }, + { + "type": "Ingredient", + "name": "spinach", + "modifiers": [], + "quantity": { + "type": "Quantity", + "value": { + "type": "single", + "value": 200, + "text": "200" + }, + "unit": "g", + "fixed": false, + "loc": { + "start": 117, + "end": 122 + } + }, + "alias": null, + "preparation": null, + "composite": null, + "loc": { + "start": 108, + "end": 123 + } + }, + { + "type": "Text", + "value": ". ", + "loc": { + "start": 123, + "end": 125 + } + }, + { + "type": "IntermediateDecl", + "name": "pate", + "loc": { + "start": 125, + "end": 132 + } + } + ], + "loc": { + "start": 84, + "end": 134 + } + } + ], + "loc": { + "start": 70, + "end": 134 + } + }, + { + "type": "Section", + "title": "Montage", + "retroPlanning": null, + "intermediateDecl": null, + "children": [ + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Fill the ", + "loc": { + "start": 146, + "end": 155 + } + }, + { + "type": "Reference", + "name": "dough", + "quantity": { + "type": "Quantity", + "value": null, + "unit": null, + "fixed": false, + "loc": { + "start": 162, + "end": 162 + } + }, + "loc": { + "start": 155, + "end": 163 + } + }, + { + "type": "Text", + "value": "with the ", + "loc": { + "start": 164, + "end": 173 + } + }, + { + "type": "Reference", + "name": "pate", + "quantity": { + "type": "Quantity", + "value": null, + "unit": null, + "fixed": false, + "loc": { + "start": 179, + "end": 179 + } + }, + "loc": { + "start": 173, + "end": 180 + } + }, + { + "type": "Text", + "value": ".", + "loc": { + "start": 180, + "end": 181 + } + } + ], + "loc": { + "start": 146, + "end": 182 + } + } + ], + "loc": { + "start": 134, + "end": 182 + } + } + ] +} diff --git a/conformance/cases/mod-032-ratio-in-base/bases/pate.gram b/conformance/cases/mod-032-ratio-in-base/bases/pate.gram new file mode 100644 index 00000000..8f236766 --- /dev/null +++ b/conformance/cases/mod-032-ratio-in-base/bases/pate.gram @@ -0,0 +1,13 @@ +--- +title: Pate +--- + +## Petrissage + +Mix @flour{500 g} and @water{300 g}. ->&pate + +## Repos + +Work @salt{2 g / 100 g &pate} into the &pate{800 g}. + +Rest ~{15 min / 500 g &pate}. diff --git a/conformance/cases/mod-032-ratio-in-base/compiled.json b/conformance/cases/mod-032-ratio-in-base/compiled.json new file mode 100644 index 00000000..6a2b7405 --- /dev/null +++ b/conformance/cases/mod-032-ratio-in-base/compiled.json @@ -0,0 +1,827 @@ +{ + "title": "Mod Ratio In Base", + "slug": "mod-ratio-in-base", + "meta": { + "title": "Mod Ratio In Base" + }, + "registry": { + "ingredients": { + "flour": { + "id": "flour", + "name": "flour", + "default_unit": "g" + }, + "water": { + "id": "water", + "name": "water", + "default_unit": "g" + }, + "dough-pate": { + "id": "dough-pate", + "name": "pate", + "is_intermediate": true + }, + "dough": { + "id": "dough", + "name": "dough", + "is_intermediate": true + }, + "salt": { + "id": "salt", + "name": "salt" + }, + "ricotta": { + "id": "ricotta", + "name": "ricotta", + "default_unit": "g" + }, + "spinach": { + "id": "spinach", + "name": "spinach", + "default_unit": "g" + }, + "pate": { + "id": "pate", + "name": "pate", + "is_intermediate": true + } + }, + "cookware": {} + }, + "shopping_list": [ + { + "id": "flour", + "name": "flour", + "_usageIds": [ + "1" + ], + "qty": 500, + "unit": "g" + }, + { + "id": "water", + "name": "water", + "_usageIds": [ + "2" + ], + "qty": 300, + "unit": "g" + }, + { + "id": "salt", + "name": "salt", + "_usageIds": [ + "3" + ], + "relative": true, + "qty": 16, + "unit": "g" + }, + { + "id": "ricotta", + "name": "ricotta", + "_usageIds": [ + "5" + ], + "qty": 250, + "unit": "g" + }, + { + "id": "spinach", + "name": "spinach", + "_usageIds": [ + "6" + ], + "qty": 200, + "unit": "g" + } + ], + "cookware": [], + "sections": [ + { + "title": "Petrissage", + "ingredients": [ + { + "id": "flour", + "_usageId": "1", + "qty": 500, + "unit": "g" + }, + { + "id": "water", + "_usageId": "2", + "qty": 300, + "unit": "g" + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Mix ", + { + "id": "flour", + "_usageId": "1", + "qty": 500, + "unit": "g" + }, + "and ", + { + "id": "water", + "_usageId": "2", + "qty": 300, + "unit": "g" + }, + ". ", + { + "type": "declaration", + "name": "dough$pate", + "id": "dough-pate" + } + ], + "timings": { + "start": 0, + "end": 2, + "activeDuration": 2 + }, + "intermediate_preparation": "dough-pate" + } + ], + "module": { + "binding": "dough", + "uri": "bases/pate.gram", + "title": "Pate", + "mode": "inline" + } + }, + { + "title": "Repos", + "ingredients": [ + { + "id": "salt", + "_usageId": "3", + "qty": { + "type": "single", + "value": 16 + }, + "dependencies": [ + "dough-pate" + ], + "formula": { + "raw": "2 g / 100 g &pate", + "target": "pate", + "ratio": { + "numerator": { + "value": { + "type": "single", + "value": 2, + "text": "2" + }, + "unit": "g" + }, + "denominator": { + "value": 100, + "unit": "g" + }, + "target": "pate", + "targetId": "dough-pate", + "referenceType": "variable", + "raw": "2 g / 100 g &pate", + "loc": { + "start": 103, + "end": 120 + } + }, + "isGhost": false + }, + "unit": "g" + }, + { + "type": "reference", + "id": "dough-pate", + "name": "dough$pate", + "_usageId": "4", + "qty": 800, + "unit": "g" + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Work ", + { + "id": "salt", + "_usageId": "3", + "qty": { + "type": "single", + "value": 16 + }, + "dependencies": [ + "dough-pate" + ], + "formula": { + "raw": "2 g / 100 g &pate", + "target": "pate", + "ratio": { + "numerator": { + "value": { + "type": "single", + "value": 2, + "text": "2" + }, + "unit": "g" + }, + "denominator": { + "value": 100, + "unit": "g" + }, + "target": "pate", + "targetId": "dough-pate", + "referenceType": "variable", + "raw": "2 g / 100 g &pate", + "loc": { + "start": 103, + "end": 120 + } + }, + "isGhost": false + }, + "unit": "g" + }, + "into the ", + { + "type": "reference", + "id": "dough-pate", + "name": "dough$pate", + "_usageId": "4", + "qty": 800, + "unit": "g" + }, + "." + ], + "timings": { + "start": 2, + "end": 4, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Rest ", + { + "type": "timer", + "raw": "15 min / 500 g &pate", + "ratio": { + "numerator": { + "value": { + "type": "single", + "value": 15 + }, + "unit": "min" + }, + "denominator": { + "value": 500, + "unit": "g" + }, + "target": "pate", + "targetId": "dough-pate", + "referenceType": "variable", + "raw": "15 min / 500 g &pate", + "loc": { + "start": 153, + "end": 173 + } + }, + "quantity": { + "type": "single", + "value": 24 + }, + "unit": "min", + "minutes": 24 + }, + "." + ], + "timings": { + "start": 4, + "end": 28, + "activeDuration": 24 + } + } + ], + "intermediate_preparation": "dough", + "module": { + "binding": "dough", + "uri": "bases/pate.gram", + "title": "Pate", + "mode": "inline" + } + }, + { + "title": "Garniture", + "ingredients": [ + { + "id": "ricotta", + "_usageId": "5", + "qty": 250, + "unit": "g" + }, + { + "id": "spinach", + "_usageId": "6", + "qty": 200, + "unit": "g" + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Mix ", + { + "id": "ricotta", + "_usageId": "5", + "qty": 250, + "unit": "g" + }, + "and ", + { + "id": "spinach", + "_usageId": "6", + "qty": 200, + "unit": "g" + }, + ". ", + { + "type": "declaration", + "name": "pate", + "id": "pate" + } + ], + "timings": { + "start": 28, + "end": 30, + "activeDuration": 2 + }, + "intermediate_preparation": "pate" + } + ] + }, + { + "title": "Montage", + "ingredients": [ + { + "type": "reference", + "id": "dough", + "name": "dough", + "_usageId": "7" + }, + { + "type": "reference", + "id": "pate", + "name": "pate", + "_usageId": "8" + } + ], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Fill the ", + { + "type": "reference", + "id": "dough", + "name": "dough", + "_usageId": "7" + }, + "with the ", + { + "type": "reference", + "id": "pate", + "name": "pate", + "_usageId": "8" + }, + "." + ], + "timings": { + "start": 30, + "end": 32, + "activeDuration": 2 + } + } + ] + } + ], + "warnings": [], + "metrics": { + "totalTime": 40, + "totalBreakdown": [ + { + "label": "section_active:Petrissage", + "duration": 2 + }, + { + "label": "section_active:Repos", + "duration": 26 + }, + { + "label": "section_active:Garniture", + "duration": 2 + }, + { + "label": "section_active:Montage", + "duration": 2 + } + ], + "idleTime": 0, + "activeTime": 32, + "activeBreakdown": [ + { + "label": "section_active:Petrissage", + "duration": 2 + }, + { + "label": "section_active:Repos", + "duration": 26 + }, + { + "label": "section_active:Garniture", + "duration": 2 + }, + { + "label": "section_active:Montage", + "duration": 2 + } + ], + "preparationTime": 8, + "prepBreakdown": [ + { + "label": "ingredients_overhead", + "duration": 8 + } + ] + }, + "miseEnPlace": [ + { + "section": 0, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ] + }, + { + "section": 1, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2, + "intermediates": 1 + } + ] + }, + { + "section": 2, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ] + }, + { + "section": 3, + "duration": 2, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2, + "intermediates": 2 + } + ] + } + ], + "tasks": { + "tasks": [ + { + "id": "s0.prep", + "kind": "prep", + "section": 0, + "duration": { + "nominal": 2 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ], + "after": [] + }, + { + "id": "s0.0", + "kind": "step", + "section": 0, + "step": 0, + "duration": { + "nominal": 2 + }, + "produces": [ + "dough$pate" + ], + "after": [] + }, + { + "id": "s1.prep", + "kind": "prep", + "section": 1, + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1 + } + ], + "after": [] + }, + { + "id": "s1.prep.dough-pate", + "kind": "prep", + "section": 1, + "intermediate": "dough-pate", + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1, + "intermediates": 1 + } + ], + "after": [ + "s0.0" + ] + }, + { + "id": "s1.0", + "kind": "step", + "section": 1, + "step": 0, + "duration": { + "nominal": 2 + }, + "consumes": [ + "dough$pate" + ], + "after": [ + "s0.0" + ] + }, + { + "id": "s1.1", + "kind": "step", + "section": 1, + "step": 1, + "duration": { + "nominal": 24 + }, + "after": [ + "s1.0" + ] + }, + { + "id": "s2.prep", + "kind": "prep", + "section": 2, + "duration": { + "nominal": 2 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 2, + "duration": 2 + } + ], + "after": [] + }, + { + "id": "s2.0", + "kind": "step", + "section": 2, + "step": 0, + "duration": { + "nominal": 2 + }, + "produces": [ + "pate" + ], + "after": [] + }, + { + "id": "s3.prep.dough", + "kind": "prep", + "section": 3, + "intermediate": "dough", + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1, + "intermediates": 1 + } + ], + "after": [ + "s1.1" + ] + }, + { + "id": "s3.prep.pate", + "kind": "prep", + "section": 3, + "intermediate": "pate", + "duration": { + "nominal": 1 + }, + "items": [ + { + "kind": "gather", + "target": "ingredient", + "count": 1, + "duration": 1, + "intermediates": 1 + } + ], + "after": [ + "s2.0" + ] + }, + { + "id": "s3.0", + "kind": "step", + "section": 3, + "step": 0, + "duration": { + "nominal": 2 + }, + "consumes": [ + "dough", + "pate" + ], + "after": [ + "s1.1", + "s2.0" + ] + } + ], + "sections": [ + { + "day": 0 + }, + { + "day": 0, + "intermediate": "dough" + }, + { + "day": 0 + }, + { + "day": 0 + } + ] + }, + "schedule": { + "miseEnPlace": "perSection", + "rests": "shortest", + "totalTime": 40, + "activeTime": 32, + "preparationTime": 8, + "idleTime": 0, + "blocks": [ + { + "kind": "prep", + "task": "s0.prep", + "section": 0, + "start": 0, + "end": 2 + }, + { + "kind": "step", + "task": "s0.0", + "section": 0, + "step": 0, + "start": 2, + "end": 4 + }, + { + "kind": "prep", + "task": "s1.prep", + "section": 1, + "start": 4, + "end": 6 + }, + { + "kind": "step", + "task": "s1.0", + "section": 1, + "step": 0, + "start": 6, + "end": 8 + }, + { + "kind": "step", + "task": "s1.1", + "section": 1, + "step": 1, + "start": 8, + "end": 32 + }, + { + "kind": "prep", + "task": "s2.prep", + "section": 2, + "start": 32, + "end": 34 + }, + { + "kind": "step", + "task": "s2.0", + "section": 2, + "step": 0, + "start": 34, + "end": 36 + }, + { + "kind": "prep", + "task": "s3.prep.dough", + "section": 3, + "start": 36, + "end": 38 + }, + { + "kind": "step", + "task": "s3.0", + "section": 3, + "step": 0, + "start": 38, + "end": 40 + } + ], + "days": [ + { + "day": 0, + "start": 0, + "end": 40, + "sections": [ + 0, + 1, + 2, + 3 + ] + } + ] + }, + "modules": [ + { + "binding": "dough", + "uri": "bases/pate.gram", + "title": "Pate", + "meta": { + "title": "Pate" + }, + "scaleFactor": 1, + "mode": "inline" + } + ] +} diff --git a/conformance/cases/mod-032-ratio-in-base/input.gram b/conformance/cases/mod-032-ratio-in-base/input.gram new file mode 100644 index 00000000..efff09ff --- /dev/null +++ b/conformance/cases/mod-032-ratio-in-base/input.gram @@ -0,0 +1,13 @@ +--- +title: Mod Ratio In Base +--- + +@use "./bases/pate.gram" as &dough + +## Garniture + +Mix @ricotta{250 g} and @spinach{200 g}. ->&pate + +## Montage + +Fill the &dough{} with the &pate{}. -- 2.54.0 From 578a2eaa267323f8feb0b694738c3d5f8814b027 Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:46 +0100 Subject: [PATCH 04/11] refactor(language-server): weigh a hovered sum with weighAmount --- .../src/features/hover-nutrition.ts | 27 +++++++++---------- .../tests/compound-quantity-tooling.test.ts | 25 +++++++++++++++++ 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/packages/language-server/src/features/hover-nutrition.ts b/packages/language-server/src/features/hover-nutrition.ts index 39553b75..1e011f12 100644 --- a/packages/language-server/src/features/hover-nutrition.ts +++ b/packages/language-server/src/features/hover-nutrition.ts @@ -14,7 +14,7 @@ import { type IngredientEntry, } from "../ingredient-loader"; import { formatTerms, normalizeUnit, termsTotal } from "@gram-lang/i18n"; -import { massOf, NUTRIENTS, standardizeMass } from "@gram-lang/analyzer"; +import { NUTRIENTS, standardizeMass, weighAmount } from "@gram-lang/analyzer"; import { type CompoundQuantityAST, isCompoundQuantity, @@ -104,21 +104,18 @@ function buildSumSection( } if (entry) { - const { known, unknown } = massOf(sum.terms, db, entry.name); - if (unknown.length === 0 && known.length > 0) { - const mass = known.reduce( - (acc, part) => acc + (part.term.minus ? -part.mass : part.mass), - 0, + // Weighed as the views weigh it (`weighAmount`), so the hover can never + // tell another mass, nor call exact what they call an estimate. + const weighed = weighAmount(sum.terms, db, entry.name); + if (weighed && weighed.normalizedMass > 0) { + const density = + weighed.isEstimate && + sum.terms.some((term) => familyOf(term.unit) === "volume") + ? entry.physical?.density + : undefined; + lines.push( + `**Conversion**: ${written} ${weighed.isEstimate ? "≈" : "="} **${Math.round(weighed.normalizedMass)} g**${density ? ` _(density: ${density} g/ml)_` : ""}`, ); - const exact = known.every((part) => part.method === "physical"); - const density = known.some((part) => part.method === "density") - ? entry.physical?.density - : undefined; - if (mass > 0) { - lines.push( - `**Conversion**: ${written} ${exact ? "=" : "≈"} **${Math.round(mass)} g**${density ? ` _(density: ${density} g/ml)_` : ""}`, - ); - } } } diff --git a/packages/language-server/tests/compound-quantity-tooling.test.ts b/packages/language-server/tests/compound-quantity-tooling.test.ts index d7677f8b..d09e2aa7 100644 --- a/packages/language-server/tests/compound-quantity-tooling.test.ts +++ b/packages/language-server/tests/compound-quantity-tooling.test.ts @@ -4,6 +4,7 @@ import { parseDocument } from "../src/document-state"; import { provideCodeActions } from "../src/features/code-actions"; import { provideCompletions } from "../src/features/completions"; import { provideDiagnostics } from "../src/features/diagnostics"; +import { weighAmount } from "@gram-lang/analyzer"; import { provideHover } from "../src/features/hover"; import type { IngredientDB } from "../src/ingredient-loader"; import { positionToOffset } from "../src/utils/position"; @@ -118,6 +119,30 @@ describe("hover on a sum", () => { expect(hover).toMatch(/1 cup \+ 20 g ≈ \*\*145 g\*\*/); }); + it("calls exact a sum of weights, and weighs what is taken away", () => { + const text = recipe("Add @flour{1 kg - 200 g + 50 g}."); + expect(hoverAt(text, "@flour", db)).toContain( + "**Conversion**: 1 kg − 200 g + 50 g = **850 g**", + ); + }); + + it("tells the mass the views tell (weighAmount)", () => { + const text = recipe("Add @flour{1 cup - 2 tbsp + 30 g}."); + const weighed = weighAmount( + [ + { value: 1, unit: "cup" }, + { value: 2, unit: "tbsp", minus: true }, + { value: 30, unit: "g" }, + ], + db, + "Flour", + ); + expect(weighed?.isEstimate).toBe(true); + expect(hoverAt(text, "@flour", db)).toContain( + `≈ **${Math.round(weighed!.normalizedMass)} g** _(density: 0.53 g/ml)_`, + ); + }); + it("shows what each kind comes to when a sum takes away within one kind", () => { const text = recipe("Add @butter{1 cup - 2 tbsp + 30 g}."); expect(hoverAt(text, "@butter", db)).toContain( -- 2.54.0 From ee63441707d5426b3f167181bdd92f0fdd6e116d Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:46 +0100 Subject: [PATCH 05/11] refactor(i18n): group terms by family in groupTerms --- packages/i18n/src/quantity.ts | 29 ++++++++++++++++++++++++----- packages/kitchen/src/terms.ts | 28 ++++++---------------------- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/packages/i18n/src/quantity.ts b/packages/i18n/src/quantity.ts index 146c7d4f..8dd566cc 100644 --- a/packages/i18n/src/quantity.ts +++ b/packages/i18n/src/quantity.ts @@ -240,7 +240,24 @@ export function termsTotal(terms: readonly Term[]): TermsTotal | null { }; } -export type MergeMode = "unit" | "ladder"; +/** + * How terms are grouped (`mergeKey`): by unit, by ladder of units (`cup` and + * `tbsp`), or by family, the kind of amount a unit measures (`familyOf`: + * every mass together, every volume together). + */ +export type MergeMode = "unit" | "ladder" | "family"; + +/** + * The kind of amount a unit measures, for telling the families of a sum + * apart: a mass, a volume, or (a unit Gram cannot convert, `gousse`) that + * unit itself. + */ +export function familyOf(unit: string | null): string { + const key = normalizeUnit(unit); + if (UNIT_CONVERSIONS.mass.map[key] !== undefined) return "mass"; + if (UNIT_CONVERSIONS.volume.map[key] !== undefined) return "volume"; + return `unit:${key}`; +} /** A total read back as one term: a negative total becomes a term taken away. */ function totalAsTerm(total: TermsTotal): Term { @@ -265,12 +282,14 @@ function totalAsTerm(total: TermsTotal): Term { } /** - * The key `mergeTerms` groups a term's unit under: its ladder in `"ladder"` - * mode (`cup` and `tbsp`, `g` and `kg`), otherwise the unit itself, its - * spellings counted as one (`cup` / `cups`). A unit Gram does not know - * (`gousse`) is only lowercased: `gousse` and `gousses` stay two units. + * The key `mergeTerms` groups a term's unit under: its family in `"family"` + * mode (`familyOf`), its ladder in `"ladder"` mode (`cup` and `tbsp`, `g` + * and `kg`), otherwise the unit itself, its spellings counted as one (`cup` + * / `cups`). A unit Gram does not know (`gousse`) is only lowercased: + * `gousse` and `gousses` stay two units. */ export function mergeKey(unit: string | null, mode: MergeMode): string { + if (mode === "family") return familyOf(unit); const step = mode === "ladder" ? ladderOf(unit) : null; return step ? `ladder:${step.ladder.id}` : `unit:${normalizeUnit(unit)}`; } diff --git a/packages/kitchen/src/terms.ts b/packages/kitchen/src/terms.ts index 0b78d7f5..1d59cc2a 100644 --- a/packages/kitchen/src/terms.ts +++ b/packages/kitchen/src/terms.ts @@ -12,9 +12,10 @@ import { type TextQuantityAST, } from "@gram-lang/parser"; import { + familyOf, formatTerms, + groupTerms, isTermValue, - normalizeUnit, QuantityOverflowError, scaleTerms, type Term, @@ -23,12 +24,14 @@ import { type TermsTotal, termsTotal, termValueNumber, - UNIT_CONVERSIONS, } from "@gram-lang/i18n"; // Imported from "./scale/types" (not the "./scale" barrel) to avoid a cycle. import { InvalidFactorError } from "./scale/types"; import type { Usage } from "./types"; +/** Re-exported for kitchen's callers (the analyzer, the language server). */ +export { familyOf }; + /** * One term of a sum as the compiled recipe stores it (`Usage.parts`): its * number (a plain number, or a fraction / range object), its unit, and @@ -248,18 +251,6 @@ export function numericTotal(terms: readonly Term[]): number | null { return total ? termValueNumber(total.qty) : null; } -/** - * The kind of amount a unit measures, for telling the families of a sum - * apart: a mass, a volume, or (a unit Gram cannot convert, `gousse`) that - * unit itself. - */ -export function familyOf(unit: string | null): string { - const key = normalizeUnit(unit); - if (UNIT_CONVERSIONS.mass.map[key] !== undefined) return "mass"; - if (UNIT_CONVERSIONS.volume.map[key] !== undefined) return "volume"; - return `unit:${key}`; -} - /** * The terms grouped by family (`familyOf`), groups in the order their first * term is written. Each group adds up to one amount (`termsTotal`): a sum of @@ -267,14 +258,7 @@ export function familyOf(unit: string | null): string { * written apart. */ export function termsByFamily(terms: readonly Term[]): Term[][] { - const groups = new Map(); - for (const term of terms) { - const key = familyOf(term.unit); - const group = groups.get(key); - if (group) group.push(term); - else groups.set(key, [term]); - } - return [...groups.values()]; + return groupTerms(terms, "family"); } /** -- 2.54.0 From 2d8db537872458b2c14b0378c433b7989d01f081 Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:47 +0100 Subject: [PATCH 06/11] fix(i18n): refuse 60 or more after a prime --- packages/docs/public/llms-full.txt | 8 +++++--- .../docs/src/content/docs/docs/reference/syntax/times.mdx | 4 ++-- .../src/content/docs/fr/docs/reference/syntax/times.mdx | 4 ++-- packages/i18n/src/duration.ts | 8 ++++++-- packages/i18n/tests/duration-cases.ts | 6 ++++++ 5 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/docs/public/llms-full.txt b/packages/docs/public/llms-full.txt index fffcc1f6..c333f391 100644 --- a/packages/docs/public/llms-full.txt +++ b/packages/docs/public/llms-full.txt @@ -1016,9 +1016,9 @@ Write durations the way recipes naturally do. Spaces don't matter (`~{1h30}`, `~ [Age] The @ham{1} in the cellar ~_{2d 4h}. ``` -- **Compound units** (`~{1h30min}`, `~{2 d 4 h}`, `~{1h + 30min}`): list units from largest to smallest, each once. A trailing number without a unit is allowed right after hours (minutes) or minutes (seconds) if it is a whole number under 60 (`~{1h30}`, `~{2min30}`, not `~{1h75}`). Decimals and fractions only apply to single-unit durations (`~{1.5 h}`, `~{1½ h}`, not `~{1.5h30}`). +- **Compound units** (`~{1h30min}`, `~{2 d 4 h}`, `~{1h + 30min}`): list units from largest to smallest, each once. A trailing number without a unit is allowed right after hours (minutes) or minutes (seconds) if it is a whole number under 60 (`~{1h30}`, `~{2min30}`, not `~{1h75}`). With its unit written out, a number is read as written, even past 60: `~{1 h 75 min}` is 2 h 15 min. Decimals and fractions only apply to single-unit durations (`~{1.5 h}`, `~{1½ h}`, not `~{1.5h30}`). - **Clock notation** (`~{1:30:00}`, `~{1:30 h}`, `~{4:30 min}`): three parts always work (`hh:mm:ss`); two parts require a leading unit so `1:30` isn't ambiguous between hours and minutes. -- **Prime notation** (`~{5'}`, `~{5'30"}`, `~{45"}`): `'` counts whole minutes and `"` counts whole seconds (typographic quotes `’`, `′`, `″`, and `''` also work). +- **Prime notation** (`~{5'}`, `~{5'30"}`, `~{45"}`): `'` counts whole minutes and `"` counts whole seconds (typographic quotes `’`, `′`, `″`, and `''` also work). Primes read like a clock: after minutes, seconds stay under 60 (`~{6'30"}`, not `~{5'90"}`). - **Decimals** (`~{1.5 h}`, `~{1,5 h}`): periods and commas both work (see [decimal numbers](/docs/reference/syntax/ingredients/#decimal-numbers)). :::caution @@ -1645,7 +1645,7 @@ If a ratio cannot be resolved, it remains as written in views and shopping lists ### Scope, intermediates & scaling - **Same scope as percentages**: target an `@&ingredient` declared earlier in the section (repeated uses sum up), an earlier option in an alternative group, or an `&intermediate`. -- **Whole intermediates**: if a section consumes an intermediate without a quantity (`Roll out the &dough`), ratios and percentages (`@salt{2 g / 100 g &dough}`, `@sugar{5% &dough}`) resolve against the total mass of the section that produces it—provided only that section consumes it. +- **Whole intermediates**: if a section consumes an intermediate without a quantity (`Roll out the &dough`), ratios and percentages (`@salt{2 g / 100 g &dough}`, `@sugar{5% &dough}`) resolve against the total mass of the section that produces it—provided only that section consumes it. An intermediate made by a step (`Mix … ->&dough`) has no mass of its own: write the amount used (`&dough{800 g}`), or make it in its own section. - **References & composites**: ratios and percentages work on homemade intermediate references (`&stock{250 ml / 100 g @&rice}`), but are not yet supported on composite parents (`@eggs{1}<@box{1 / 100 g @&flour}>`). - **Scaling**: scaling a recipe recalculates ratios from the scaled targets (unless the target is fixed with `@=`). Marking a ratio itself with `=` is not allowed. @@ -2745,6 +2745,7 @@ For a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with - `incompatibleUnits`: mismatched counts (`2 slices` against cloves), a weight against a named piece, or trailing words (`100 g of`). - `missingDensity` / `missingUnitWeight`: converting between weight and volume or pieces requires `density` or `unit_weight` in the database. - `wholeUseAmbiguous` / `producerMassUnknown`: for an intermediate used whole (`&dough`), either another section also consumes it or the producing section's mass is incomplete. +- `stepProducer`: the intermediate used whole is made by a step (`Mix … ->&dough`), not by a whole section, and only a section's mass is weighed. Write the amount used (`&dough{500 g}`), or make it in its own section. **Fix**: match the target's unit, add `density` or `unit_weight` to the database, or specify the intermediate's used quantity (`&dough{500 g}`). @@ -2778,6 +2779,7 @@ Emitted when a [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-q | `rangeAfterMinus` | `{1 cup - 1-2 tbsp}` | Put ranges on added terms, or write the total as a range. | | `minusAcrossFamilies` | `{1 cup - 20 g}` | Subtract only from the same unit family (volume from volume, weight from weight). | | `zeroDenominator` | `{1/0 cup}`, `{1/0% &dough}`, `#pan{1/0}`, `^{1/0 °C}` | Division by zero is ignored; write a valid fraction (`1/2`). | +| `zeroRatioDenominator` | `{2 g / 0 g @&flour}`, `~{15 min / 0 g @&roast}` | A ratio per nothing is ignored; write the amount it is per (`/ 100 g`). | | `relativeNotSupported` | `@eggs{3}<@box{50% @&flour}`, `@eggs{1}<@box{1 / 100 g @&flour}` | Percentages and ratios are not supported on composite parents yet; specify the parent's quantity (`@eggs{3}<@box{1}`). | Subtraction is checked per unit family: `{1 cup - 2 tbsp + 30 g}` is valid (2 tbsp are subtracted from 1 cup), while `{1 cup - 20 g}` has no weight to subtract from. diff --git a/packages/docs/src/content/docs/docs/reference/syntax/times.mdx b/packages/docs/src/content/docs/docs/reference/syntax/times.mdx index ddfb4dd1..6bfafc96 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/times.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/times.mdx @@ -42,9 +42,9 @@ Write durations the way recipes naturally do. Spaces don't matter (`~{1h30}`, `~ [Age] The @ham{1} in the cellar ~_{2d 4h}. ``` -- **Compound units** (`~{1h30min}`, `~{2 d 4 h}`, `~{1h + 30min}`): list units from largest to smallest, each once. A trailing number without a unit is allowed right after hours (minutes) or minutes (seconds) if it is a whole number under 60 (`~{1h30}`, `~{2min30}`, not `~{1h75}`). Decimals and fractions only apply to single-unit durations (`~{1.5 h}`, `~{1½ h}`, not `~{1.5h30}`). +- **Compound units** (`~{1h30min}`, `~{2 d 4 h}`, `~{1h + 30min}`): list units from largest to smallest, each once. A trailing number without a unit is allowed right after hours (minutes) or minutes (seconds) if it is a whole number under 60 (`~{1h30}`, `~{2min30}`, not `~{1h75}`). With its unit written out, a number is read as written, even past 60: `~{1 h 75 min}` is 2 h 15 min. Decimals and fractions only apply to single-unit durations (`~{1.5 h}`, `~{1½ h}`, not `~{1.5h30}`). - **Clock notation** (`~{1:30:00}`, `~{1:30 h}`, `~{4:30 min}`): three parts always work (`hh:mm:ss`); two parts require a leading unit so `1:30` isn't ambiguous between hours and minutes. -- **Prime notation** (`~{5'}`, `~{5'30"}`, `~{45"}`): `'` counts whole minutes and `"` counts whole seconds (typographic quotes `’`, `′`, `″`, and `''` also work). +- **Prime notation** (`~{5'}`, `~{5'30"}`, `~{45"}`): `'` counts whole minutes and `"` counts whole seconds (typographic quotes `’`, `′`, `″`, and `''` also work). Primes read like a clock: after minutes, seconds stay under 60 (`~{6'30"}`, not `~{5'90"}`). - **Decimals** (`~{1.5 h}`, `~{1,5 h}`): periods and commas both work (see [decimal numbers](/docs/reference/syntax/ingredients/#decimal-numbers)). :::caution diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx index 6050dd65..5baea6b0 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx @@ -42,9 +42,9 @@ Ces unités s'appuient sur le dictionnaire temporel multilingue de Gram : les al [Affiner] Le @jambon{1} à la cave ~_{2 j 4 h}. ``` -- **Plusieurs unités** (`~{1h30min}`, `~{2 j 4 h}`, `~{1h + 30min}`) : rangez les unités de la plus grande à la plus petite, chacune une seule fois. Un dernier nombre sans unité est accepté juste après les heures (minutes) ou les minutes (secondes), s'il est entier et inférieur à 60 (`~{1h30}`, `~{2min30}`, mais pas `~{1h75}`). Décimales et fractions ne s'emploient que sur une durée d'une seule unité (`~{1,5 h}`, `~{1½ h}`, pas `~{1,5h30}`). +- **Plusieurs unités** (`~{1h30min}`, `~{2 j 4 h}`, `~{1h + 30min}`) : rangez les unités de la plus grande à la plus petite, chacune une seule fois. Un dernier nombre sans unité est accepté juste après les heures (minutes) ou les minutes (secondes), s'il est entier et inférieur à 60 (`~{1h30}`, `~{2min30}`, mais pas `~{1h75}`). Avec son unité écrite en toutes lettres, un nombre se lit tel quel, même au-delà de 60 : `~{1 h 75 min}` fait 2 h 15 min. Décimales et fractions ne s'emploient que sur une durée d'une seule unité (`~{1,5 h}`, `~{1½ h}`, pas `~{1,5h30}`). - **Notation horaire** (`~{1:30:00}`, `~{1:30 h}`, `~{4:30 min}`) : trois parties sont toujours comprises (`hh:mm:ss`) ; deux parties exigent une unité pour lever l'ambiguïté entre heures et minutes. -- **Notation en primes** (`~{5'}`, `~{5'30"}`, `~{45"}`) : `'` compte des minutes entières et `"` des secondes entières (les variantes typographiques `’`, `′`, `″` et `''` sont aussi acceptées). +- **Notation en primes** (`~{5'}`, `~{5'30"}`, `~{45"}`) : `'` compte des minutes entières et `"` des secondes entières (les variantes typographiques `’`, `′`, `″` et `''` sont aussi acceptées). Les primes se lisent comme une horloge : après les minutes, les secondes restent sous 60 (`~{6'30"}`, pas `~{5'90"}`). - **Nombres décimaux** (`~{1,5 h}`, `~{1.5 h}`) : virgule et point sont acceptés (voir les [nombres décimaux](/fr/docs/reference/syntax/ingredients/#nombres-décimaux)). :::caution diff --git a/packages/i18n/src/duration.ts b/packages/i18n/src/duration.ts index 77e96621..9a88ee27 100644 --- a/packages/i18n/src/duration.ts +++ b/packages/i18n/src/duration.ts @@ -48,7 +48,9 @@ export interface DurationSide { * - `clockFormat`: a malformed clock (`1:5 h`, `1:30 d`, more than three parts); * - `unitOrder`: units not from the largest to the smallest (`30min 1h`); * - `duplicateUnit`: the same unit twice (`1h 2h`); - * - `overflow60`: 60 or more after an hour or a minute (`1h75`, `1:75 h`); + * - `overflow60`: 60 or more after an hour or a minute, where the unit is + * implied, in a clock or with a prime (`1h75`, `1:75 h`, `5'90"`); with its + * unit written out it is read as written (`1 h 75 min` is 2 h 15 min); * - `decimalInCompound`: a decimal or a fraction in a duration of several terms (`1.5h30`); * - `decimalPrime`: a decimal or a fraction with a prime (`1.5'`); * - `bareNumber`: a number with no unit where none can be implied (`1j3`, `1 30 min`); @@ -406,11 +408,13 @@ function analyzeTerms(tokens: Token[]): Analysis { } const unit = next.unit as DurationUnit; + const last = parts[parts.length - 1]; if (next.kind === "prime") { if (num.num !== "int") return fail("decimalPrime"); + // Primes read as a clock (`5'30"` is 5:30): its rule, not a unit's. + if (last && num.value >= 60) return fail("overflow60"); primes++; } - const last = parts[parts.length - 1]; if (last) { if (last.unit === unit) return fail("duplicateUnit"); if (RANK[last.unit] > RANK[unit]) return fail("unitOrder"); diff --git a/packages/i18n/tests/duration-cases.ts b/packages/i18n/tests/duration-cases.ts index 507be627..7aed194b 100644 --- a/packages/i18n/tests/duration-cases.ts +++ b/packages/i18n/tests/duration-cases.ts @@ -45,6 +45,9 @@ export const COMMON_CASES: DurationCases = { ["5-7'", [5, 7]], ["5'-7'30\"", [5, 7.5]], ["1h 30'", 90], + // A unit written out is read as written, even past 60 (primes are not). + ["1 h 75 min", 135], + ["2min90s", 3.5], // Symbols. ["1h30", 90], ["1h30min15", 90.25], @@ -73,6 +76,9 @@ export const COMMON_CASES: DurationCases = { ["30min 1h", "unitOrder"], ["1h 2h", "duplicateUnit"], ["1h75", "overflow60"], + ["5'90\"", "overflow60"], + ["5' 60\"", "overflow60"], + ["1h 75'", "overflow60"], ["30s5", "bareNumber"], ["5'30\"15", "bareNumber"], ["1 30 min", "bareNumber"], -- 2.54.0 From 6d4ff0382ec26d682712fbe880e41ab517f8b850 Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:47 +0100 Subject: [PATCH 07/11] perf(renderer): build the 12-hour formatter once per language --- packages/renderer/src/shared/clock.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/renderer/src/shared/clock.ts b/packages/renderer/src/shared/clock.ts index cfdf087b..34e6ebf2 100644 --- a/packages/renderer/src/shared/clock.ts +++ b/packages/renderer/src/shared/clock.ts @@ -106,14 +106,29 @@ export function formatClock( .join(""); } +/** + * The 12-hour formatter of each language, built once: a run sheet writes + * dozens of times, and building an `Intl.DateTimeFormat` is the costly part. + */ +const twelveHourFormats = new Map(); + +function twelveHourFormat(lang: string): Intl.DateTimeFormat { + let format = twelveHourFormats.get(lang); + if (!format) { + format = new Intl.DateTimeFormat(lang, { + timeZone: "UTC", + ...clockFormatOptions("h12"), + }); + twelveHourFormats.set(lang, format); + } + return format; +} + /** "13:05" in 12 hours, as `Intl` cuts it up: the hour, the minutes, the day period. */ function clockParts(hhmm: string, lang?: string): Intl.DateTimeFormatPart[] { const minutes = (Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3, 5))) % 1440; - return new Intl.DateTimeFormat(lang || "en", { - timeZone: "UTC", - ...clockFormatOptions("h12"), - }).formatToParts(minutes * 60_000); + return twelveHourFormat(lang || "en").formatToParts(minutes * 60_000); } /** -- 2.54.0 From 89d591e9e4c4bccfb17fe1d1aca5e0e806b07e78 Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:47 +0100 Subject: [PATCH 08/11] test(renderer): cover target states and temperature notes against XSS --- packages/renderer/tests/xss-escaping.test.ts | 39 ++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/packages/renderer/tests/xss-escaping.test.ts b/packages/renderer/tests/xss-escaping.test.ts index 6ac31ebc..2ee1d143 100644 --- a/packages/renderer/tests/xss-escaping.test.ts +++ b/packages/renderer/tests/xss-escaping.test.ts @@ -127,6 +127,45 @@ describe("escaping sweep — every text field, every HTML backend", () => { } }); +// The 1.5 elements whose words come straight from the recipe: a target state +// and its note (`={…}(…)`), a temperature's note (`^{…}(…)`). A note ends at +// its first `)`, so the payload holds no parenthesis. +describe("escaping — target states and temperature notes (1.5)", () => { + const PAYLOAD = ""; + const ESCAPED = "<svg/onload=1>"; + + const fields: Record = { + "target state": `## Section + +Whisk until ={${PAYLOAD}}. +`, + "target state note": `## Section + +Whisk until ={ribbon stage}(${PAYLOAD}). +`, + "temperature note": `## Section + +Bake at ^{180°C}(${PAYLOAD}). +`, + }; + + const backends: Record string> = { + toHTML: (data) => toHTML(data), + toPrintHTML: (data) => toPrintHTML(data), + }; + + for (const [field, source] of Object.entries(fields)) { + const compiled = compile(getAST(source)); + for (const [backendName, render] of Object.entries(backends)) { + it(`shows a ${field} escaped via ${backendName}`, () => { + const html = render(compiled); + expect(html).not.toContain(PAYLOAD); + expect(html).toContain(ESCAPED); + }); + } + } +}); + describe("toMarkdown escaping", () => { it("neutralizes a raw HTML payload in the recipe title (frontmatter)", () => { const source = -- 2.54.0 From f204f88da6ee381985df7ace7e7db94d9464722d Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:47 +0100 Subject: [PATCH 09/11] chore(audit): trust target-states and transcribe the new mistake examples --- audit/src/config.ts | 1 + audit/src/extract/self-test-cases.ts | 32 +++++++++++++++++++++++++--- audit/tests/config.test.ts | 2 +- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/audit/src/config.ts b/audit/src/config.ts index c5244ff1..0a506b42 100644 --- a/audit/src/config.ts +++ b/audit/src/config.ts @@ -41,6 +41,7 @@ export const TRUSTED_SYNTAX_FILES: string[] = [ "ingredients", "intermediate-variables", "relative-quantities", + "target-states", "temperatures", "times", ].flatMap((name) => [ diff --git a/audit/src/extract/self-test-cases.ts b/audit/src/extract/self-test-cases.ts index 8bc58400..74c1c29b 100644 --- a/audit/src/extract/self-test-cases.ts +++ b/audit/src/extract/self-test-cases.ts @@ -86,14 +86,40 @@ export const SELF_TEST_CASES: SelfTestCase[] = [ bad: "## Bake\n\nBake for ~{45min}.\n", good: "## Bake\n\nBake for ~_{45min}.\n", }, + { + label: "comma-as-thousands-separator", + bad: "## Prep\n\nAdd @flour{1,000 g} to the bowl.\n", + good: "## Prep\n\nAdd @flour{1000 g} to the bowl.\n", + }, + { + label: "decimal-point-for-hours-and-minutes", + bad: "## Bake\n\nBake for ~{1.30 h}.\n", + good: "## Bake\n\nBake for ~{1h30}.\n", + }, + { + label: "space-before-ingredient-preparation", + bad: "## Prep\n\nAdd @onion{1} (diced) to the pan.\n", + good: "## Prep\n\nAdd @onion{1}(diced) to the pan.\n", + }, + { + label: "space-before-cookware-preparation", + bad: "## Prep\n\nHeat the #pan{} (20cm, non-stick).\n", + good: "## Prep\n\nHeat the #pan{}(20cm, non-stick).\n", + }, + { + label: "ratio-without-spaces", + bad: "## Prep\n\nWeigh @flour{500 g}.\n\nAdd @eggs{1/100g @&flour}.\n", + good: "## Prep\n\nWeigh @flour{500 g}.\n\nAdd @eggs{1 / 100 g @&flour}.\n", + }, ]; // Raw ❌ glyph count observed in the EN doc as of this transcription. If the // live count drifts, the doc likely gained (or lost) a mistake example that // nobody transcribed here yet — print an informational note, don't fail. -// The 4 added in 1.5 (temperature note, target state) are prose mistakes no -// check can flag, so they are counted here rather than transcribed above. -const EXPECTED_BAD_GLYPH_COUNT = 26; +// The 6 prose mistakes added in 1.5 (temperature note, target state, a ratio +// or a proportional time worked out by hand) are ones no check can flag, so +// they are counted here rather than transcribed above. +const EXPECTED_BAD_GLYPH_COUNT = 33; export function extractSelfTestSnippets(): { bad: Snippet[]; diff --git a/audit/tests/config.test.ts b/audit/tests/config.test.ts index b0d2b1c0..bc6f9c41 100644 --- a/audit/tests/config.test.ts +++ b/audit/tests/config.test.ts @@ -25,7 +25,7 @@ describe("audit configuration", () => { }); it("finds every trusted syntax page, in both languages", () => { - expect(TRUSTED_SYNTAX_FILES).toHaveLength(18); + expect(TRUSTED_SYNTAX_FILES).toHaveLength(20); expect(AI_GENERATION_NOTES_FILES).toHaveLength(2); for (const file of TRUSTED_SYNTAX_FILES) { expect(file).toMatch(/\.mdx?$/); -- 2.54.0 From 22a30f53bd95bb0c6c7ba1913efc501b4e56aaab Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:47 +0100 Subject: [PATCH 10/11] chore: tighten the any-ratchet baseline --- scripts/any-ratchet-baseline.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/any-ratchet-baseline.json b/scripts/any-ratchet-baseline.json index 6fc128dd..d7a38f2d 100644 --- a/scripts/any-ratchet-baseline.json +++ b/scripts/any-ratchet-baseline.json @@ -1,13 +1,13 @@ { "analyzer": 0, - "cli": 79, + "cli": 78, "format": 0, "i18n": 0, "kitchen": 0, "language-server": 1, "modules": 0, "parser": 0, - "renderer": 28, + "renderer": 25, "scheduler": 0, "vscode-extension": 0 } -- 2.54.0 From f0dc4fc6347c504dd4f0a6e88f7c4cb6cd0e08b7 Mon Sep 17 00:00:00 2001 From: abiwab Date: Thu, 19 Nov 2026 20:06:47 +0100 Subject: [PATCH 11/11] docs(changeset): fix the format command name and complete the i18n and shopping entries --- .changeset/compound-quantities.md | 3 ++- .changeset/decimal-comma.md | 2 +- .changeset/shopping-ladder-merge.md | 6 ++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.changeset/compound-quantities.md b/.changeset/compound-quantities.md index 990ab76d..0a606b5e 100644 --- a/.changeset/compound-quantities.md +++ b/.changeset/compound-quantities.md @@ -1,6 +1,7 @@ --- "@gram-lang/parser": minor "@gram-lang/kitchen": minor +"@gram-lang/i18n": minor "@gram-lang/modules": minor "@gram-lang/analyzer": minor "@gram-lang/renderer": minor @@ -9,7 +10,7 @@ **Parser & Kitchen**: An ingredient's quantity can be written as a sum, the way American recipes measure: `@flour{1 cup + 1 tbsp}`, `@sugar{1 cup - 2 tbsp}`, `@butter{1 cup + 20 g}`: - Any number of terms, added with `+` or taken away with `-`, each with its unit; a term can be a fraction or a range (`{1 cup + 1-2 tbsp}`). It works for an ingredient, a composite parent (`<@oranges{1 lb + 4 oz}`) and a reference (`&dough{1 kg + 200 g}`, which also sets how much of a `@use` base is made). These sums used to be a syntax error. - - A sum counts exactly as its terms written one after the other: one kind of amount adds up into one total, exactly (`1 cup + 1 tbsp` is 17 tbsp, a range by its bounds), and is usable with `gram scale --target`; a volume and a weight (`1 cup + 20 g`) stay two lines of the shopping list. Scaling multiplies each term. A step shows a sum as written; a section lists each mention as written (`100 g + 100 g`, two portions to weigh); a scaled amount and the shopping list are written the way a cook measures (`2 cup + 2 tbsp`, never `2 1/8 cup` or `34 tbsp`; `2.4 kg` in a step, `1.5 kg` to buy), for any amount, not only sums, in the views as in `gram shop` and `gram scale`; the renderer's new `formatUsageQuantity` writes an amount this way for other tools. + - A sum counts exactly as its terms written one after the other: one kind of amount adds up into one total, exactly (`1 cup + 1 tbsp` is 17 tbsp, a range by its bounds), and is usable with `gram scale --target`; a volume and a weight (`1 cup + 20 g`) stay two lines of the shopping list. Scaling multiplies each term. A step shows a sum as written; a section lists each mention as written (`100 g + 100 g`, two portions to weigh); a scaled amount and the shopping list are written the way a cook measures (`2 cup + 2 tbsp`, never `2 1/8 cup` or `34 tbsp`; `2.4 kg` in a step, `1.5 kg` to buy), for any amount, not only sums, in the views as in `gram shop` and `gram scale`; the renderer's new `formatUsageQuantity` writes an amount this way for other tools, and `@gram-lang/i18n` exports the arithmetic behind it (`termsTotal`, `mergeTerms`, `formatTerms` and the `Term` type). - Gram never guesses: a term without a unit, a percentage, a multiplication, a range taken away, a subtraction from another kind of amount or a sum that comes to nothing raises the new `INVALID_QUANTITY` warning, with the result to write when it can tell (`{100 g + 10%}` suggests `{110 g}`), and the sum is not counted. The new `OZ_AFTER_VOLUME` note says that `oz` is a weight in `{1 cup + 2 oz}`, and `INVALID_UNIT` now asks for two quantities written side by side (`{1 kg 200 g}`) to be written as a sum. - In the compiled JSON, a sum keeps its terms in a new `parts` field (`minus: true` on a term taken away), and its total in `qty` / `unit` as before; a sum of several kinds of amount keeps its text in `unit`, like a quantity written in words. A warning that a tool can act on carries a new `data` field (its reason and suggestion). - Masses and nutrition weigh a sum by its parts: `@flour{1 cup + 20 g}` weighs its cup (with the flour's density) plus its 20 g, a term taken away weighs against the total, and a sum with a part Gram cannot weigh gets no mass rather than a partial one. `gram diff` shows amounts as the shopping list writes them (`1 cup + 1 tbsp → 1 cup + 3 tbsp`, `202-203 g`), from the new `fromText` / `toText` fields of an ingredient change. diff --git a/.changeset/decimal-comma.md b/.changeset/decimal-comma.md index a34070e6..e8df8d48 100644 --- a/.changeset/decimal-comma.md +++ b/.changeset/decimal-comma.md @@ -8,5 +8,5 @@ **Parser & Kitchen**: Decimal numbers can be written with a comma as well as a point, so `{1,5 kg}` and `{1.5 kg}` are the same quantity: - Works in every number in braces: ingredients, ranges, relative quantities (`{12,5% &dough}`), cookware, temperatures, timers and section anchors. Scaling, masses and the schedule read it like any other number. - Gram has no thousands separator. A comma followed by exactly three digits, in any of these numbers (`{1,000 g}`, `{1,000% &dough}`, `~{-1,000h}`), is still read as a decimal (1 g), with a new `AMBIGUOUS_NUMBER` warning saying how it was read, in case a thousand was meant. A point keeps its meaning: `{1.000 kg}` is 1 kg, with no warning. - - `gram fmt` removes trailing zeros after a comma too (`{1,50}` → `{1,5}`), but leaves `{1,000}` as written. + - `gram format` removes trailing zeros after a comma too (`{1,50}` → `{1,5}`), but leaves `{1,000}` as written. - Numbers written with a comma are shown in the reader's language like the others (`1,5` → `1.5` in English). diff --git a/.changeset/shopping-ladder-merge.md b/.changeset/shopping-ladder-merge.md index 447bb9fb..03b0d8cd 100644 --- a/.changeset/shopping-ladder-merge.md +++ b/.changeset/shopping-ladder-merge.md @@ -4,5 +4,7 @@ --- **Kitchen & Rendering**: The shopping list adds up repeated quantities of an ingredient wherever it can: - - The units of one measuring system add up into one line, in the smallest unit written (`1 cup` and `2 tbsp` give `18 tbsp`, `1 kg` and `200 g` give `1200 g`), so fewer ingredients are flagged as mixed units and more of them work with `gram scale --target`. Two systems (`1 cup` and `100 ml`) or two kinds of amount still get a line each. - - Ranges add up by their bounds (`2-3 g` and `200 g` give `202-203 g`, no longer `202.5 g`). A shopping-list entry keeps the middle in `qty` and gains a `range` field with both bounds. + - The units of one measuring system add up into one line, written the way a cook measures (`1 cup` and `2 tbsp` give `1 cup + 2 tbsp`, `1 kg` and `200 g` give `1.2 kg`), so fewer ingredients are flagged as mixed units and more of them work with `gram scale --target`. + - Two systems (`1 cup` and `100 ml`) or two kinds of amount (a volume and a weight) still get a line each. + - Ranges add up by their bounds (`2-3 g` and `200 g` give `202-203 g`, no longer `202.5 g`). + - In the compiled JSON, a shopping-list entry keeps its total in the smallest unit written (`18 tbsp`, `1200 g`) and, for a range, the middle in `qty` with a new `range` field giving both bounds. -- 2.54.0