refactor(i18n,kitchen): read every ingredient quantity through a single term model #151

Merged
abiwab merged 1 commit from refactor/quantity-terms into dev/1.5 2026-11-15 13:28:56 +01:00
18 changed files with 788 additions and 149 deletions

View file

@ -9,7 +9,12 @@ import type {
CompositeItem, CompositeItem,
} from "@gram-lang/kitchen"; } from "@gram-lang/kitchen";
import { normalizeUnit } from "@gram-lang/i18n"; import { normalizeUnit } from "@gram-lang/i18n";
import { getNumericQty, scheduleFor, scheduleTimes } from "@gram-lang/kitchen"; import {
numericTotal,
scheduleFor,
scheduleTimes,
termsOfUsage,
} from "@gram-lang/kitchen";
// Structural, analyzer-local shapes for the module-composition metadata a // Structural, analyzer-local shapes for the module-composition metadata a
// `CompilationResult` may carry when it actually came from // `CompilationResult` may carry when it actually came from
@ -197,7 +202,7 @@ function flattenShoppingItems(items: ShoppingItem[]): SimpleShoppingItem[] {
} }
const numericQty = (item: ShoppingItem): number | null => const numericQty = (item: ShoppingItem): number | null =>
getNumericQty(item.qty); numericTotal(termsOfUsage(item));
function fmtTimerQty( function fmtTimerQty(
qty: ProcessedTimer["quantity"], qty: ProcessedTimer["quantity"],

View file

@ -19,7 +19,8 @@ import type {
RegistryEntry, RegistryEntry,
} from "@gram-lang/kitchen"; } from "@gram-lang/kitchen";
import { import {
getNumericQty, numericTotal,
termsOfUsage,
WarningCode, WarningCode,
round2, round2,
isPurchasableReference, isPurchasableReference,
@ -107,7 +108,7 @@ function standardizeUsageMass(
enableYieldCalculation: boolean, enableYieldCalculation: boolean,
lang?: string, lang?: string,
): void { ): void {
const numericQty = getNumericQty(usage.qty); const numericQty = numericTotal(termsOfUsage(usage));
if (numericQty === null) return; if (numericQty === null) return;
const norm = standardizeMass( const norm = standardizeMass(

View file

@ -1,5 +1,6 @@
import { import {
getNumericQty, numericTotal,
termsOfUsage,
WarningCode, WarningCode,
pushWarning, pushWarning,
type Warning, type Warning,
@ -116,7 +117,7 @@ export function calculateNutrition(
mass = item.normalizedMass; mass = item.normalizedMass;
if (item.isEstimate) isEst = true; if (item.isEstimate) isEst = true;
} else if (item.qty) { } else if (item.qty) {
const val = getNumericQty(item.qty); const val = numericTotal(termsOfUsage(item));
if (val !== null) { if (val !== null) {
const unit = item.unit || "unit"; const unit = item.unit || "unit";

View file

@ -7,3 +7,4 @@ export * from "./categories";
export * from "./locales"; export * from "./locales";
export * from "./template"; export * from "./template";
export * from "./duration"; export * from "./duration";
export * from "./quantity";

View file

@ -0,0 +1,217 @@
/**
* The one model every amount of an ingredient goes through: a list of terms,
* each a value and a unit, added or taken away (`1 cup + 1 tbsp`,
* `1 cup - 2 tbsp`). A plain `{200 g}` is one term.
*
* Pure and neutral: it knows nothing of the parser's AST or of the compiled
* recipe. `@gram-lang/kitchen` reads its usages and AST nodes into terms
* (`termsOfUsage`, `termsOfAst`) and writes them back (`usageFromTerms`).
*/
import { normalizeUnit } from "./units";
/**
* A numeric value as the compiled recipe stores it: a plain number, or the
* parser's single / fraction / range shape (structurally the parser's
* `QuantityValueAST`, redeclared here so this module stays free of it).
*/
export type QuantityValue =
| { type: "single"; value: number; text?: string }
| {
type: "fraction";
value: number;
numerator: number;
denominator: number;
text?: string;
}
| {
type: "range";
value: number;
range: { min: number; max: number };
text?: string;
};
/** The value of one term: kept in the shape it was written in. */
export type TermValue = number | QuantityValue;
export interface Term {
value: TermValue;
unit: string | null;
/** Taken away from the total (`- 2 tbsp`). */
minus?: boolean;
}
/** What a list of terms amounts to, in the compiled recipe's `qty` / `unit` shape. */
export interface TermsTotal {
qty: TermValue;
unit: string | null;
}
/** Raised by `scaleTerms` when a scaled value stops being a finite number. */
export class QuantityOverflowError extends RangeError {
constructor(public readonly factor: number) {
super(
`Scaling by a factor of ${factor} overflowed a quantity to a non-finite value.`,
);
this.name = "QuantityOverflowError";
}
}
/**
* Rounds a mass/quantity value to 2 decimal places, returning a `number`
* (not a string). Centralizes the `parseFloat(x.toFixed(2))` idiom used
* throughout kitchen/analyzer so there is a single, documented rounding rule
* to port when the compiler is reimplemented in another language: `toFixed`
* uses round-half-away-from-zero on the value's shortest decimal
* representation, which differs from IEEE round-half-to-even on exact ties.
*/
export const round2 = (value: number): number => parseFloat(value.toFixed(2));
/** True for a value a term can hold (a number, or a single / fraction / range). */
export function isTermValue(value: unknown): value is TermValue {
if (typeof value === "number") return true;
if (!value || typeof value !== "object") return false;
const type = (value as { type?: unknown }).type;
return type === "single" || type === "fraction" || type === "range";
}
/**
* The number a value stands for: the number itself, or its `value` (the
* middle of a range). `null` when the value carries no number.
*/
export function termValueNumber(value: TermValue): number | null {
if (typeof value === "number") return value;
return value.value ?? null;
}
/** Terms added first, then terms taken away, each group in its written order. */
function addedFirst(terms: readonly Term[]): Term[] {
return [...terms.filter((t) => !t.minus), ...terms.filter((t) => t.minus)];
}
/**
* What the terms amount to.
*
* - no term: `null`;
* - one term added: that term as written (a range stays a range, a fraction
* keeps its text);
* - several terms of one unit (its spellings count as one: `cup` / `cups`):
* the sum of their numbers (a range counts for its middle), in the unit of
* the first term added;
* - several units: `null` (the terms do not add up to one amount).
*/
export function termsTotal(terms: readonly Term[]): TermsTotal | null {
const ordered = addedFirst(terms);
const [first] = ordered;
if (!first) return null;
if (ordered.length === 1 && !first.minus) {
return { qty: first.value, unit: first.unit };
}
const unitKey = normalizeUnit(first.unit);
let sum = 0;
for (const term of ordered) {
if (normalizeUnit(term.unit) !== unitKey) return null;
const n = termValueNumber(term.value);
if (n === null) return null;
sum = term.minus ? sum - n : sum + n;
}
return { qty: sum, unit: first.unit };
}
export type MergeMode = "unit";
/**
* Puts the terms of several amounts of one ingredient together, terms added
* before terms taken away (`2 tbsp` then `1 cup - 4 tbsp` gives
* `1 cup`, `2 tbsp`, `- 4 tbsp`, never a term taken away first).
*
* `"unit"` keeps every term as it is, one after the other: this is how a
* section lists an ingredient it uses several times.
*/
export function mergeTerms(terms: readonly Term[], _mode: MergeMode): Term[] {
return addedFirst(terms);
}
/**
* Multiplies a value by `factor`, rounded to 2 decimals. The source text of a
* value (`text`, a fraction's `numerator` / `denominator`) only describes the
* unscaled value, so it is dropped: a scaled fraction becomes a single value.
* A value that is not a number (a malformed object) comes back untouched.
* Throws `QuantityOverflowError` when the product is no longer finite.
*/
export function scaleTermValue<T extends TermValue>(
value: T,
factor: number,
): TermValue {
if (factor === 1) return value;
const scale = (n: number): number => {
const scaled = n * factor;
if (!Number.isFinite(scaled)) throw new QuantityOverflowError(factor);
return round2(scaled);
};
if (typeof value === "number") return scale(value);
if (!value || typeof value !== "object") return value;
if (value.type === "single" && typeof value.value === "number") {
return { ...value, value: scale(value.value), text: undefined };
}
if (value.type === "range") {
return {
...value,
value: typeof value.value === "number" ? scale(value.value) : value.value,
range: value.range
? { min: scale(value.range.min), max: scale(value.range.max) }
: value.range,
text: undefined,
};
}
if (value.type === "fraction" && typeof value.value === "number") {
return { type: "single", value: scale(value.value) };
}
return value;
}
/** Every term multiplied by `factor` (see `scaleTermValue`); units are kept. */
export function scaleTerms(terms: readonly Term[], factor: number): Term[] {
return terms.map((term) => ({
...term,
value: scaleTermValue(term.value, factor),
}));
}
/** One term as written: its number (or source text) and its unit, without its sign. */
export function formatTerm(term: Term): string {
const v = term.value;
const text =
typeof v === "number"
? String(v)
: (v.text ?? String((v as { value?: unknown }).value ?? v));
return term.unit ? `${text} ${term.unit}` : text;
}
export interface FormatTermsOptions {
/** Placed between two terms added. Default ` + `. */
plus?: string;
/** Placed before a term taken away. Default ` − `. */
minus?: string;
}
/**
* The terms as written, terms added first (`1 cup + 1 tbsp`, `1 cup − 2 tbsp`).
* A list that starts with a term taken away still writes it after the others.
*/
export function formatTerms(
terms: readonly Term[],
options: FormatTermsOptions = {},
): string {
const plus = options.plus ?? " + ";
const minus = options.minus ?? " − ";
return addedFirst(terms)
.map((term, i) => {
const text = formatTerm(term);
if (i === 0) return term.minus ? `${minus.trimStart()}${text}` : text;
return `${term.minus ? minus : plus}${text}`;
})
.join("");
}

View file

@ -0,0 +1,227 @@
import { describe, it, expect } from "bun:test";
import {
formatTerm,
formatTerms,
isTermValue,
mergeTerms,
QuantityOverflowError,
round2,
scaleTerms,
scaleTermValue,
type Term,
termsTotal,
termValueNumber,
} from "../src/quantity";
const range = (min: number, max: number, text?: string) => ({
type: "range" as const,
value: (min + max) / 2,
range: { min, max },
...(text !== undefined && { text }),
});
describe("termValueNumber", () => {
it("reads a number, a single, a fraction and the middle of a range", () => {
expect(termValueNumber(3)).toBe(3);
expect(termValueNumber({ type: "single", value: 2 })).toBe(2);
expect(
termValueNumber({
type: "fraction",
value: 0.5,
numerator: 1,
denominator: 2,
text: "1/2",
}),
).toBe(0.5);
expect(termValueNumber(range(2, 3))).toBe(2.5);
});
it("tells a term value from a text or a relative quantity", () => {
expect(isTermValue(1)).toBe(true);
expect(isTermValue(range(1, 2))).toBe(true);
expect(isTermValue("une pincée")).toBe(false);
expect(isTermValue({ type: "RelativeQuantity", percent: 10 })).toBe(false);
expect(isTermValue(null)).toBe(false);
});
});
describe("termsTotal", () => {
it("has no total without a term", () => {
expect(termsTotal([])).toBeNull();
});
it("keeps one term as written", () => {
const fraction = {
type: "fraction" as const,
value: 0.5,
numerator: 1,
denominator: 2,
text: "1/2",
};
expect(termsTotal([{ value: fraction, unit: "cup" }])).toEqual({
qty: fraction,
unit: "cup",
});
});
it("keeps a range a range", () => {
const total = termsTotal([{ value: range(2, 3, "2-3"), unit: "g" }]);
expect(total?.qty).toEqual(range(2, 3, "2-3"));
});
it("adds the spellings of one unit, in the first unit written", () => {
expect(
termsTotal([
{ value: 1, unit: "cup" },
{ value: 2, unit: "cups" },
]),
).toEqual({ qty: 3, unit: "cup" });
});
it("adds a range by its middle", () => {
expect(
termsTotal([
{ value: range(2, 3), unit: "g" },
{ value: 200, unit: "g" },
]),
).toEqual({ qty: 202.5, unit: "g" });
});
it("takes away a term taken away, in the unit of a term added", () => {
expect(
termsTotal([
{ value: 4, unit: "tbsp", minus: true },
{ value: 10, unit: "tbsp" },
]),
).toEqual({ qty: 6, unit: "tbsp" });
});
it("has no single total across units", () => {
expect(
termsTotal([
{ value: 1, unit: "cup" },
{ value: 20, unit: "g" },
]),
).toBeNull();
});
});
describe("mergeTerms", () => {
it("keeps every term, terms added before terms taken away", () => {
const terms: Term[] = [
{ value: 2, unit: "tbsp" },
{ value: 4, unit: "tbsp", minus: true },
{ value: 1, unit: "cup" },
];
expect(mergeTerms(terms, "unit")).toEqual([
{ value: 2, unit: "tbsp" },
{ value: 1, unit: "cup" },
{ value: 4, unit: "tbsp", minus: true },
]);
});
it("never moves a term among the terms of its own sign", () => {
const terms: Term[] = [
{ value: 1, unit: "g" },
{ value: 2, unit: "kg" },
{ value: 3, unit: "g" },
];
expect(mergeTerms(terms, "unit")).toEqual(terms);
});
});
describe("scaleTerms", () => {
it("leaves every value alone at a factor of 1", () => {
const value = { type: "single" as const, value: 2, text: "2" };
expect(scaleTermValue(value, 1)).toBe(value);
});
it("scales a number and rounds it to 2 decimals", () => {
expect(scaleTermValue(1, 1 / 3)).toBe(0.33);
});
it("drops the source text of a scaled value", () => {
expect(scaleTermValue({ type: "single", value: 2, text: "2" }, 2)).toEqual({
type: "single",
value: 4,
text: undefined,
});
expect(scaleTermValue(range(1, 2, "1-2"), 2)).toEqual({
type: "range",
value: 3,
range: { min: 2, max: 4 },
text: undefined,
});
});
it("turns a scaled fraction into a single value", () => {
expect(
scaleTermValue(
{ type: "fraction", value: 0.5, numerator: 1, denominator: 2 },
3,
),
).toEqual({ type: "single", value: 1.5 });
});
it("keeps units and signs", () => {
expect(
scaleTerms(
[
{ value: 1, unit: "cup" },
{ value: 2, unit: "tbsp", minus: true },
],
2,
),
).toEqual([
{ value: 2, unit: "cup" },
{ value: 4, unit: "tbsp", minus: true },
]);
});
it("refuses a product that is no longer finite", () => {
expect(() => scaleTerms([{ value: 500, unit: "g" }], 1e308)).toThrow(
QuantityOverflowError,
);
});
it("scales the total like each term (one unit)", () => {
const terms: Term[] = [
{ value: 1.25, unit: "g" },
{ value: 2.5, unit: "g" },
];
const total = termsTotal(terms)?.qty as number;
const scaledTotal = termsTotal(scaleTerms(terms, 2))?.qty as number;
expect(round2(total * 2)).toBe(scaledTotal);
});
});
describe("formatTerms", () => {
it("writes a term with its source text first", () => {
expect(formatTerm({ value: range(1, 2, "1-2"), unit: "cups" })).toBe(
"1-2 cups",
);
expect(formatTerm({ value: 3, unit: null })).toBe("3");
});
it("writes terms added before terms taken away", () => {
expect(
formatTerms([
{ value: 4, unit: "tbsp", minus: true },
{ value: 1, unit: "cup" },
{ value: 2, unit: "tbsp" },
]),
).toBe("1 cup + 2 tbsp − 4 tbsp");
});
it("takes its separators as options", () => {
expect(
formatTerms(
[
{ value: 1, unit: "cup" },
{ value: 1, unit: "tbsp" },
],
{ plus: " plus " },
),
).toBe("1 cup plus 1 tbsp");
});
});

View file

@ -7,6 +7,7 @@ export * from "./registry";
export * from "./warnings"; export * from "./warnings";
export * from "./types"; export * from "./types";
export * from "./section"; export * from "./section";
export * from "./terms";
export * from "./scale"; export * from "./scale";
export * from "./graph"; export * from "./graph";
export * from "./schedule-mode"; export * from "./schedule-mode";

View file

@ -3,16 +3,18 @@ import {
type RecipeAST, type RecipeAST,
type StepAST, type StepAST,
type IngredientAST, type IngredientAST,
type QuantityAST,
type QuantityValueAST, type QuantityValueAST,
} from "@gram-lang/parser"; } from "@gram-lang/parser";
import { scaleQty } from "../utils"; import { scaleUsageTerms, termsOfAst } from "../terms";
function scaleQuantityValue( /**
value: QuantityValueAST | undefined, * Scales a quantity node in place, through the same helper as `applyScale`
factor: number, * (`scaleUsageTerms`), so the AST and the compiled recipe scale alike.
): QuantityValueAST | undefined { */
if (!value) return value; function scaleQuantityNode(node: QuantityAST, factor: number): void {
return scaleQty(value, factor) as QuantityValueAST; const total = scaleUsageTerms(termsOfAst(node), factor);
if (total) node.value = total.qty as QuantityValueAST;
} }
function scaleIngredient(ing: IngredientAST, factor: number): void { function scaleIngredient(ing: IngredientAST, factor: number): void {
@ -21,11 +23,11 @@ function scaleIngredient(ing: IngredientAST, factor: number): void {
ing.quantity.type === ASTNodeType.Quantity && ing.quantity.type === ASTNodeType.Quantity &&
!ing.quantity.fixed !ing.quantity.fixed
) { ) {
ing.quantity.value = scaleQuantityValue(ing.quantity.value, factor); scaleQuantityNode(ing.quantity, factor);
} }
const compositeQty = ing.composite?.quantity; const compositeQty = ing.composite?.quantity;
if (compositeQty && !compositeQty.fixed) { if (compositeQty && !compositeQty.fixed) {
compositeQty.value = scaleQuantityValue(compositeQty.value, factor); scaleQuantityNode(compositeQty, factor);
} }
} }

View file

@ -1,5 +1,6 @@
import { normalizeUnit } from "@gram-lang/i18n"; import { normalizeUnit } from "@gram-lang/i18n";
import { slugify, scaleQty, round2 } from "../utils"; import { slugify, scaleQty, round2 } from "../utils";
import { scaleUsageTerms, termsOfQuantity, termsOfUsage } from "../terms";
import type { CompilationResult, Usage } from "../types"; import type { CompilationResult, Usage } from "../types";
import type { ShoppingListItem, CompositeItem } from "../shopping"; import type { ShoppingListItem, CompositeItem } from "../shopping";
import { import {
@ -186,19 +187,23 @@ function mutateUsage(
// guard it would be scaled twice (factor²) here. // guard it would be scaled twice (factor²) here.
const usage = item as Partial<Usage>; const usage = item as Partial<Usage>;
if (usage.fixed) return; // @= modifier or TextQuantity — never scaled if (usage.fixed) return; // @= modifier or TextQuantity — never scaled
if ("qty" in usage && usage.qty !== undefined) { // Text (`{une pincée}`) and relative (`{10%}`) quantities have no terms:
usage.qty = scaleQty(usage.qty, factor); // they are never scaled.
} const total = scaleUsageTerms(termsOfUsage(usage), factor);
if (total) usage.qty = total.qty;
// A composite child's own record of how much of the parent it draws // A composite child's own record of how much of the parent it draws
// (`@egg-yolks{2}<@eggs{3}` -> composite.quantity 3) is a separate field // (`@egg-yolks{2}<@eggs{3}` -> composite.quantity 3) is a separate field
// from `.qty` — the shopping list's own aggregated composite total is // from `.qty` — the shopping list's own aggregated composite total is
// scaled independently, further down, but this per-section copy wasn't. // scaled independently, further down, but this per-section copy wasn't.
const composite = usage.composite; const composite = usage.composite;
if (composite && composite.quantity !== undefined) { if (composite) {
composite.quantity = scaleQty( const parentTotal = scaleUsageTerms(
composite.quantity, termsOfQuantity(composite.quantity, composite.unit),
factor, factor,
) as typeof composite.quantity; );
if (parentTotal) {
composite.quantity = parentTotal.qty as typeof composite.quantity;
}
} }
scaled.add(item); scaled.add(item);
} }

View file

@ -1,4 +1,6 @@
import type { StepToken, Usage } from "./types"; import type { StepToken, Usage } from "./types";
import { mergeTerms } from "@gram-lang/i18n";
import { termsOfUsage } from "./terms";
import { round2 } from "./utils"; import { round2 } from "./utils";
export interface AggregatedIngredient { export interface AggregatedIngredient {
@ -50,6 +52,23 @@ function createBaseEntry(
}; };
} }
/**
* The quantities one occurrence adds to its entry: its terms, put together
* by `mergeTerms` (terms added before terms taken away), or the quantity as
* written when it has no terms (a text such as `{une pincée}`, a relative
* quantity), which a section still lists.
*/
function occurrenceQuantities(
ing: Usage,
): NonNullable<AggregatedIngredient["quantities"]> {
const terms = termsOfUsage(ing);
if (terms.length === 0) return [{ qty: ing.qty!, unit: ing.unit ?? null }];
return mergeTerms(terms, "unit").map((term) => ({
qty: term.value,
unit: term.unit,
}));
}
/** /**
* Aggregates a flat list of section Usage items into display-ready entries: * Aggregates a flat list of section Usage items into display-ready entries:
* *
@ -94,7 +113,7 @@ export function aggregateSectionIngredients(
if (hasMeasuredQty) { if (hasMeasuredQty) {
const existing = measuredByKey.get(key); const existing = measuredByKey.get(key);
if (existing) { if (existing) {
existing.quantities!.push({ qty: ing.qty!, unit: ing.unit ?? null }); existing.quantities!.push(...occurrenceQuantities(ing));
if (ing.normalizedMass) { if (ing.normalizedMass) {
existing.normalizedMass = existing.normalizedMass =
(existing.normalizedMass || 0) + ing.normalizedMass; (existing.normalizedMass || 0) + ing.normalizedMass;
@ -111,7 +130,7 @@ export function aggregateSectionIngredients(
} else { } else {
const entry: AggregatedIngredient = { const entry: AggregatedIngredient = {
...createBaseEntry(ing, name), ...createBaseEntry(ing, name),
quantities: [{ qty: ing.qty!, unit: ing.unit ?? null }], quantities: occurrenceQuantities(ing),
normalizedMass: ing.normalizedMass, normalizedMass: ing.normalizedMass,
conversionMethod: ing.conversionMethod, conversionMethod: ing.conversionMethod,
isEstimate: ing.isEstimate, isEstimate: ing.isEstimate,

View file

@ -1,7 +1,8 @@
import { slugify, getNumericQty, round2 } from "./utils"; import { slugify, round2 } from "./utils";
import { numericTotal, termsOfQuantity, termsOfUsage } from "./terms";
import { detectCycles } from "./graph"; import { detectCycles } from "./graph";
import { ASTNodeType } from "@gram-lang/parser"; import { ASTNodeType } from "@gram-lang/parser";
import { normalizeUnit } from "@gram-lang/i18n"; import { normalizeUnit, type Term } from "@gram-lang/i18n";
import type { ProcessedSection, Registry, Usage } from "./types"; import type { ProcessedSection, Registry, Usage } from "./types";
import type { CompilerOptions } from "./core"; import type { CompilerOptions } from "./core";
import { isPurchasableReference } from "./registry"; import { isPurchasableReference } from "./registry";
@ -22,6 +23,8 @@ export interface ShoppingListItem {
multiUnit?: boolean; multiUnit?: boolean;
modifiers?: string[]; modifiers?: string[];
// Internal fields for calculation // Internal fields for calculation
// No longer set: the sum is kept as terms, outside the item. Still declared
// so code that read it keeps type-checking.
otherUnits?: Record<string, number>; otherUnits?: Record<string, number>;
variableParts?: string[]; variableParts?: string[];
_usageIds?: string[]; _usageIds?: string[];
@ -117,6 +120,9 @@ export function generateShoppingList(
_options?: CompilerOptions, _options?: CompilerOptions,
): (ShoppingListItem | CompositeItem | Usage)[] { ): (ShoppingListItem | CompositeItem | Usage)[] {
const listMap = new Map<string, ShoppingListItem>(); const listMap = new Map<string, ShoppingListItem>();
// The terms each entry of `listMap` adds up, by the same key: one unit
// (its spellings merged), so they always amount to a single number.
const termsByKey = new Map<string, Term[]>();
const compositeMap = new Map<string, CompositeAccumulator>(); const compositeMap = new Map<string, CompositeAccumulator>();
const alternatives: Usage[] = []; const alternatives: Usage[] = [];
@ -149,7 +155,9 @@ export function generateShoppingList(
let declParentQty = 1; let declParentQty = 1;
if (item.composite?.quantity) { if (item.composite?.quantity) {
const numQ = getNumericQty(item.composite.quantity); const numQ = numericTotal(
termsOfQuantity(item.composite.quantity, item.composite.unit),
);
if (numQ !== null) declParentQty = numQ; if (numQ !== null) declParentQty = numQ;
} }
@ -175,7 +183,7 @@ export function generateShoppingList(
} }
const uEntry = comp.usageAccumulator.get(uKey)!; const uEntry = comp.usageAccumulator.get(uKey)!;
const numQ = getNumericQty(item.qty); const numQ = numericTotal(termsOfUsage(item));
if (numQ !== null) { if (numQ !== null) {
uEntry.qty = (typeof uEntry.qty === "number" ? uEntry.qty : 0) + numQ; uEntry.qty = (typeof uEntry.qty === "number" ? uEntry.qty : 0) + numQ;
} }
@ -184,21 +192,13 @@ export function generateShoppingList(
const id = item.id; const id = item.id;
let numericQty: number | null = null;
const unit = item.unit || ""; const unit = item.unit || "";
let isGhost = false; const isGhost = item.formula?.isGhost === true;
// The usage's terms, kept only when they amount to a number: a
if (item.formula) { // ghost formula has none to add, and a term without a number goes
if (item.formula.isGhost) { // to the variable parts below, as written.
isGhost = true; const terms = isGhost ? [] : termsOfUsage(item);
} else { const numericQty = numericTotal(terms);
const numQ = getNumericQty(item.qty);
if (numQ !== null) numericQty = numQ;
}
} else {
const numQ = getNumericQty(item.qty);
if (numQ !== null) numericQty = numQ;
}
// Group by ID AND unit (and ghost status) to prevent semantic data loss // Group by ID AND unit (and ghost status) to prevent semantic data loss
// where secondary units were stringified into variable_entries. The // where secondary units were stringified into variable_entries. The
@ -214,7 +214,6 @@ export function generateShoppingList(
id: id, id: id,
name: name, name: name,
unit: unit, unit: unit,
otherUnits: {},
variableParts: [], variableParts: [],
_usageIds: [], _usageIds: [],
}); });
@ -250,9 +249,9 @@ export function generateShoppingList(
const display = `${text} ❓`; const display = `${text} ❓`;
existing.variableParts!.push(`(${display})`); existing.variableParts!.push(`(${display})`);
} else if (numericQty !== null) { } else if (numericQty !== null) {
const u = existing.unit ?? ""; const entryTerms = termsByKey.get(key);
if (!existing.otherUnits![u]) existing.otherUnits![u] = 0; if (entryTerms) entryTerms.push(...terms);
existing.otherUnits![u] += numericQty; else termsByKey.set(key, [...terms]);
} else { } else {
if (item.qty) { if (item.qty) {
const qStr = formatQuantity(item.qty); const qStr = formatQuantity(item.qty);
@ -267,7 +266,7 @@ export function generateShoppingList(
}); });
}); });
const standardList = [...listMap.values()].map((item) => { const standardList = [...listMap.entries()].map(([key, item]) => {
const res: ShoppingListItem = { const res: ShoppingListItem = {
id: item.id, id: item.id,
name: item.name, name: item.name,
@ -280,29 +279,15 @@ export function generateShoppingList(
if (item.modifierSet && item.modifierSet.size > 0) if (item.modifierSet && item.modifierSet.size > 0)
res.modifiers = [...item.modifierSet]; res.modifiers = [...item.modifierSet];
const units = Object.keys(item.otherUnits!); const terms = termsByKey.get(key);
const primaryUnit = units[0]; if (terms) {
if (primaryUnit !== undefined) { // A range adds up by its middle.
res.qty = round2(item.otherUnits![primaryUnit] || 0); res.qty = round2(numericTotal(terms) ?? 0);
res.unit = primaryUnit || null; res.unit = item.unit || null;
} }
const hasOther = Object.keys(item.otherUnits!).length > 0; if (item.variableParts && item.variableParts.length > 0) {
res.variable_entries = [...item.variableParts];
const extraEntries: string[] = [];
if (hasOther) {
const units = Object.keys(item.otherUnits!);
for (let i = 1; i < units.length; i++) {
const u = units[i];
if (u === undefined) continue;
const uStr = u ? ` ${u}` : "";
extraEntries.push(`${round2(item.otherUnits![u] || 0)}${uStr}`);
}
}
const allVars = [...extraEntries, ...(item.variableParts || [])];
if (allVars.length > 0) {
res.variable_entries = allVars;
} }
return res; return res;

View file

@ -0,0 +1,103 @@
/**
* The bridge between the compiled recipe (and the AST) and the quantity model
* of `@gram-lang/i18n`: every reading of an ingredient's amount goes through
* `termsOfUsage` / `termsOfAst`, every writing through `usageFromTerms`, so
* the shape a quantity is stored in is known in one place only.
*/
import {
ASTNodeType,
type QuantityAST,
type RelativeQuantityAST,
type TextQuantityAST,
} from "@gram-lang/parser";
import {
isTermValue,
QuantityOverflowError,
scaleTerms,
type Term,
type TermsTotal,
termsTotal,
termValueNumber,
} 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";
/** A record that carries an amount the way the compiled recipe does. */
export interface QuantityHolder {
qty?: Usage["qty"] | null;
unit?: string | null;
}
/**
* The terms of a `qty` / `unit` pair: one term for a number, a single, a
* fraction or a range; none for a text (`{une pincée}`), a relative quantity
* (`{10%}`) or no quantity at all.
*/
export function termsOfQuantity(
qty: Usage["qty"] | null | undefined,
unit: string | null | undefined,
): Term[] {
if (!isTermValue(qty)) return [];
return [{ value: qty, unit: unit ?? null }];
}
/** The terms of a compiled usage (an ingredient, a reference, a shopping entry). */
export function termsOfUsage(usage: QuantityHolder | null | undefined): Term[] {
if (!usage) return [];
return termsOfQuantity(usage.qty, usage.unit);
}
/**
* The terms of a quantity node of the AST, read like `termsOfUsage` reads a
* usage. The values keep their AST shape (`{ type: "single", … }`), so terms
* scaled here can be written back into the node.
*/
export function termsOfAst(
node: QuantityAST | RelativeQuantityAST | TextQuantityAST | null | undefined,
): Term[] {
if (!node || node.type !== ASTNodeType.Quantity) return [];
return termsOfQuantity(node.value, node.unit);
}
/**
* Writes what `terms` amount to into `usage` (`qty`, and `unit` when it
* changes). Terms with no single total leave the usage as it is.
*/
export function usageFromTerms<T extends QuantityHolder>(
usage: T,
terms: readonly Term[],
): T {
const total = termsTotal(terms);
if (!total) return usage;
usage.qty = total.qty;
if (total.unit !== (usage.unit ?? null)) usage.unit = total.unit;
return usage;
}
/** The number the terms amount to (the middle of a range), or `null`. */
export function numericTotal(terms: readonly Term[]): number | null {
const total = termsTotal(terms);
return total ? termValueNumber(total.qty) : null;
}
/**
* The terms scaled by `factor`, and what they amount to: one helper for the
* compiled recipe (`applyScale`) and the AST (`scaleAst`), so both scale
* alike. `null` when there is nothing to scale. An overflow is reported as
* the scaler's own `InvalidFactorError`.
*/
export function scaleUsageTerms(
terms: readonly Term[],
factor: number,
): TermsTotal | null {
if (terms.length === 0) return null;
try {
return termsTotal(scaleTerms(terms, factor));
} catch (error) {
if (error instanceof QuantityOverflowError) {
throw new InvalidFactorError(factor, error.message);
}
throw error;
}
}

View file

@ -7,7 +7,15 @@ import {
ASTNodeType, ASTNodeType,
} from "@gram-lang/parser"; } from "@gram-lang/parser";
import type { Usage, UsageComposite } from "./types"; import type { Usage, UsageComposite } from "./types";
import { resolveTimeUnit, TIME_TO_MINUTES } from "@gram-lang/i18n"; import {
isTermValue,
QuantityOverflowError,
resolveTimeUnit,
round2,
scaleTermValue,
termValueNumber,
TIME_TO_MINUTES,
} from "@gram-lang/i18n";
import type { CompilerOptions } from "./core"; import type { CompilerOptions } from "./core";
// Imported from "./scale/types" (not the "./scale" barrel) to avoid a cycle: // Imported from "./scale/types" (not the "./scale" barrel) to avoid a cycle:
// "./scale" re-exports engine.ts, which itself imports from this file. // "./scale" re-exports engine.ts, which itself imports from this file.
@ -317,74 +325,31 @@ export const quantityToMinutes = (
* Handles plain numbers, single/range/fraction QuantityValueAST objects. * Handles plain numbers, single/range/fraction QuantityValueAST objects.
* String quantities (TextQuantity) and undefined values are left unchanged. * String quantities (TextQuantity) and undefined values are left unchanged.
* *
* `text`/`numerator`/`denominator` capture the original source string (e.g. "1/2") * The arithmetic lives in `@gram-lang/i18n` (`scaleTermValue`, the quantity
* and are only valid for the unscaled value, so they're cleared here rather than * model every amount goes through): rounded to 2 decimals, source text
* carried over stale — display code must fall back to the scaled numeric `value`. * (`text`, a fraction's `numerator`/`denominator`) dropped, a scaled fraction
* * turned into a single value. An overflow to a non-finite value throws
* The scale *factor* is validated (`isPositiveFinite` in scale/engine.ts, * `InvalidFactorError` instead of serializing as JSON `null`.
* `CompilerOptionsSchema`), but the *product* never was —
* `scaleQty(500, 1e308)` silently produced `Infinity`,
* which serializes to JSON `null`. Every multiplication here now goes through
* `scaleValue`, which throws `InvalidFactorError` on overflow instead, and
* applies `round2` uniformly so scaled quantities don't carry float noise
* (`110.00000000000001`) — previously only `applyScale`'s `meta.portions`
* was rounded, not the quantities themselves.
*/ */
export const scaleQty = (qty: Usage["qty"], factor: number): Usage["qty"] => { export const scaleQty = (qty: Usage["qty"], factor: number): Usage["qty"] => {
if (factor === 1) return qty; if (factor === 1) return qty;
if (!isTermValue(qty)) return qty;
const scaleValue = (value: number): number => { try {
const scaled = value * factor; return scaleTermValue(qty, factor) as Usage["qty"];
if (!Number.isFinite(scaled)) { } catch (error) {
throw new InvalidFactorError( if (error instanceof QuantityOverflowError) {
factor, throw new InvalidFactorError(factor, error.message);
`Scaling by a factor of ${factor} overflowed a quantity to a non-finite value.`,
);
} }
return round2(scaled); throw error;
};
if (typeof qty === "number") return scaleValue(qty);
if (!qty || typeof qty !== "object") return qty;
if (qty.type === "single" && typeof qty.value === "number") {
return { ...qty, value: scaleValue(qty.value), text: undefined };
} }
if (qty.type === "range") {
return {
...qty,
value: typeof qty.value === "number" ? scaleValue(qty.value) : qty.value,
range: qty.range
? { min: scaleValue(qty.range.min), max: scaleValue(qty.range.max) }
: qty.range,
text: undefined,
};
}
if (qty.type === "fraction" && typeof qty.value === "number") {
// `numerator`/`denominator` are required, non-optional fields on the
// "fraction" variant of QuantityValueAST — setting them `undefined`
// while keeping `type: "fraction"` produced a structurally malformed
// value (`{type:"fraction", value:1}`, no numerator/denominator).
// Scaling breaks the clean numerator/denominator relationship anyway
// (the doc comment above already says display must fall back to the
// scaled numeric `value`), so this becomes a "single" value instead —
// the type that actually matches what's left. Routed through
// `scaleValue` (not a raw multiply) for the same overflow/rounding
// protection as every other branch here (kitchen finding F-015).
return { type: "single", value: scaleValue(qty.value) };
}
return qty;
}; };
/** /**
* Rounds a mass/quantity value to 2 decimal places, returning a `number` * Rounds a mass/quantity value to 2 decimal places (see `round2` in
* (not a string). Centralizes the `parseFloat(x.toFixed(2))` idiom used * `@gram-lang/i18n`, where the rule is documented): re-exported here, where
* throughout kitchen/analyzer so there is a single, documented rounding rule * kitchen, analyzer and renderer have always imported it from.
* to port when the compiler is reimplemented in another language: `toFixed`
* uses round-half-away-from-zero on the value's shortest decimal
* representation, which differs from IEEE round-half-to-even on exact ties.
*/ */
export const round2 = (value: number): number => parseFloat(value.toFixed(2)); export { round2 };
// Lives in the scheduler, which builds the timeline breakdowns with it. // Lives in the scheduler, which builds the timeline breakdowns with it.
export { addToBreakdown } from "@gram-lang/scheduler"; export { addToBreakdown } from "@gram-lang/scheduler";
@ -392,14 +357,9 @@ export { addToBreakdown } from "@gram-lang/scheduler";
export const getNumericQty = ( export const getNumericQty = (
q: Usage["qty"] | null | undefined, q: Usage["qty"] | null | undefined,
): number | null => { ): number | null => {
if (q === undefined || q === null) return null; // A text (TextQuantity's cleaned string) or a RelativeQuantityAST /
if (typeof q === "number") return q; // TextQuantityAST is not a term value: only a number or a real
if (typeof q !== "object") return null; // string (TextQuantity's cleaned value) // QuantityValueAST is. Kept as public API; kitchen itself reads amounts
// through `termsOfUsage` / `numericTotal` (terms.ts).
// RelativeQuantityAST/TextQuantityAST have no "fraction"/"range"/"single" return isTermValue(q) ? termValueNumber(q) : null;
// variant — only a real QuantityValueAST does.
if (q.type === "fraction" || q.type === "range" || q.type === "single") {
return q.value ?? null;
}
return null;
}; };

View file

@ -0,0 +1,109 @@
import { describe, it, expect } from "bun:test";
import { ASTNodeType, getAST, type IngredientAST } from "@gram-lang/parser";
import {
numericTotal,
scaleUsageTerms,
termsOfAst,
termsOfUsage,
usageFromTerms,
} from "../src/terms";
import { InvalidFactorError } from "../src/scale/types";
describe("termsOfUsage", () => {
it("reads one term from a number, a single, a fraction or a range", () => {
expect(termsOfUsage({ qty: 200, unit: "g" })).toEqual([
{ value: 200, unit: "g" },
]);
const range = {
type: "range" as const,
value: 2.5,
range: { min: 2, max: 3 },
};
expect(termsOfUsage({ qty: range })).toEqual([
{ value: range, unit: null },
]);
});
it("reads no term from a text, a relative quantity or no quantity", () => {
expect(termsOfUsage({ qty: "une pincée" })).toEqual([]);
expect(
termsOfUsage({
qty: {
type: ASTNodeType.RelativeQuantity,
percent: 10,
target: "farine",
referenceType: "ingredient",
},
}),
).toEqual([]);
expect(termsOfUsage({})).toEqual([]);
expect(termsOfUsage(null)).toEqual([]);
});
});
describe("termsOfAst", () => {
it("reads a quantity node like a usage, keeping the AST shape", () => {
const ast = getAST("Mix @flour{1/2 cup}.\n");
const step = ast.children[0];
if (step?.type !== ASTNodeType.Step) throw new Error("no step");
const ing = step.children.find(
(c): c is IngredientAST => c.type === ASTNodeType.Ingredient,
);
const [term] = termsOfAst(ing?.quantity);
expect(term?.unit).toBe("cup");
expect(term?.value).toMatchObject({ type: "fraction", value: 0.5 });
});
it("reads no term from a text quantity", () => {
expect(
termsOfAst({
type: ASTNodeType.TextQuantity,
value: "a pinch",
loc: { start: 0, end: 0 },
}),
).toEqual([]);
});
});
describe("usageFromTerms", () => {
it("writes the total back, the unit only when it changes", () => {
const usage = { id: "flour", qty: 1, unit: "cup" };
usageFromTerms(usage, [{ value: 2, unit: "cup" }]);
expect(usage).toEqual({ id: "flour", qty: 2, unit: "cup" });
const bare: { id: string; qty?: number } = { id: "eggs" };
usageFromTerms(bare, [{ value: 3, unit: null }]);
expect(bare).toEqual({ id: "eggs", qty: 3 });
});
it("leaves the usage alone when the terms have no single total", () => {
const usage = { id: "flour", qty: 1, unit: "cup" };
usageFromTerms(usage, [
{ value: 1, unit: "cup" },
{ value: 20, unit: "g" },
]);
expect(usage).toEqual({ id: "flour", qty: 1, unit: "cup" });
});
});
describe("numericTotal and scaleUsageTerms", () => {
it("reads the middle of a range", () => {
expect(
numericTotal(
termsOfUsage({
qty: { type: "range", value: 2.5, range: { min: 2, max: 3 } },
}),
),
).toBe(2.5);
});
it("has nothing to scale without a term", () => {
expect(scaleUsageTerms([], 2)).toBeNull();
});
it("reports an overflow as the scaler's InvalidFactorError", () => {
expect(() => scaleUsageTerms([{ value: 500, unit: "g" }], 1e308)).toThrow(
InvalidFactorError,
);
});
});

View file

@ -17,7 +17,7 @@ import { type IngredientDB, lookupIngredient } from "../ingredient-loader";
import { normalizeUnit } from "@gram-lang/i18n"; import { normalizeUnit } from "@gram-lang/i18n";
import { ASTNodeType, type QuantityAST } from "@gram-lang/parser"; import { ASTNodeType, type QuantityAST } from "@gram-lang/parser";
import { standardizeMass } from "@gram-lang/analyzer"; import { standardizeMass } from "@gram-lang/analyzer";
import { getNumericQty } from "@gram-lang/kitchen"; import { numericTotal, termsOfAst } from "@gram-lang/kitchen";
export function provideCodeActions( export function provideCodeActions(
state: DocumentState, state: DocumentState,
@ -248,7 +248,7 @@ export function provideCodeActions(
: null; : null;
if (qty?.unit && qty.value && qty.loc) { if (qty?.unit && qty.value && qty.loc) {
const amount = getNumericQty(qty.value); const amount = numericTotal(termsOfAst(qty));
const canon = amount && amount > 0 ? normalizeUnit(qty.unit) : null; const canon = amount && amount > 0 ? normalizeUnit(qty.unit) : null;
if (canon) { if (canon) {
const norm = standardizeMass(amount!, canon, db, entry?.name); const norm = standardizeMass(amount!, canon, db, entry?.name);

View file

@ -15,7 +15,7 @@ import {
import { normalizeUnit } from "@gram-lang/i18n"; import { normalizeUnit } from "@gram-lang/i18n";
import { NUTRIENTS, standardizeMass } from "@gram-lang/analyzer"; import { NUTRIENTS, standardizeMass } from "@gram-lang/analyzer";
import { type QuantityAST, isQuantity } from "@gram-lang/parser"; import { type QuantityAST, isQuantity } from "@gram-lang/parser";
import { getNumericQty } from "@gram-lang/kitchen"; import { numericTotal, termsOfAst } from "@gram-lang/kitchen";
function buildConversionSection( function buildConversionSection(
qty: QuantityAST, qty: QuantityAST,
@ -29,9 +29,7 @@ function buildConversionSection(
const canon = normalizeUnit(rawUnit); const canon = normalizeUnit(rawUnit);
if (!canon) return null; if (!canon) return null;
const qtyValue = qty.value; const amount = numericTotal(termsOfAst(qty));
if (!qtyValue) return null;
const amount = getNumericQty(qtyValue);
if (amount === null || amount <= 0) return null; if (amount === null || amount <= 0) return null;
const norm = standardizeMass(amount, canon, db, entry.name); const norm = standardizeMass(amount, canon, db, entry.name);

View file

@ -5,8 +5,9 @@ import {
type ImportDecl, type ImportDecl,
} from "@gram-lang/parser"; } from "@gram-lang/parser";
import { import {
getNumericQty, numericTotal,
round2, round2,
termsOfAst,
forEachStep, forEachStep,
type Warning, type Warning,
} from "@gram-lang/kitchen"; } from "@gram-lang/kitchen";
@ -137,7 +138,7 @@ function collectReferenceQuantities(
if (ref.name !== name) return; if (ref.name !== name) return;
const q = ref.quantity; const q = ref.quantity;
if (!q || q.type !== ASTNodeType.Quantity) return; if (!q || q.type !== ASTNodeType.Quantity) return;
const value = getNumericQty(q.value); const value = numericTotal(termsOfAst(q));
if (value === null) return; if (value === null) return;
requests.push({ value, unit: q.unit ?? null }); requests.push({ value, unit: q.unit ?? null });
} }

View file

@ -4,6 +4,8 @@ import type { AggregatedIngredient, StepToken } from "@gram-lang/kitchen";
import { import {
commonFraction, commonFraction,
formatNumber, formatNumber,
formatTerm,
isTermValue,
getDictionary, getDictionary,
isCoarseUnit, isCoarseUnit,
localizeDecimals, localizeDecimals,
@ -61,10 +63,12 @@ export function aggToRendererItem(
} }
if (rest.length > 0) { if (rest.length > 0) {
base.variable_entries = rest.map((q) => { base.variable_entries = rest.map((q) => {
if (isTermValue(q.qty)) {
return formatTerm({ value: q.qty, unit: q.unit ?? null });
}
// A text or relative quantity has no terms: written as it is.
const qty = q.qty as any; const qty = q.qty as any;
const qStr = const qStr = qty?.text ?? String(qty?.value ?? qty);
qty?.text ??
(typeof qty === "number" ? String(qty) : String(qty?.value ?? qty));
return q.unit ? `${qStr} ${q.unit}` : qStr; return q.unit ? `${qStr} ${q.unit}` : qStr;
}); });
} }