diff --git a/packages/analyzer/src/diff.ts b/packages/analyzer/src/diff.ts index 082e9090..3f02e113 100644 --- a/packages/analyzer/src/diff.ts +++ b/packages/analyzer/src/diff.ts @@ -9,7 +9,12 @@ import type { CompositeItem, } from "@gram-lang/kitchen"; 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 // `CompilationResult` may carry when it actually came from @@ -197,7 +202,7 @@ function flattenShoppingItems(items: ShoppingItem[]): SimpleShoppingItem[] { } const numericQty = (item: ShoppingItem): number | null => - getNumericQty(item.qty); + numericTotal(termsOfUsage(item)); function fmtTimerQty( qty: ProcessedTimer["quantity"], diff --git a/packages/analyzer/src/index.ts b/packages/analyzer/src/index.ts index d858041e..8962919e 100644 --- a/packages/analyzer/src/index.ts +++ b/packages/analyzer/src/index.ts @@ -19,7 +19,8 @@ import type { RegistryEntry, } from "@gram-lang/kitchen"; import { - getNumericQty, + numericTotal, + termsOfUsage, WarningCode, round2, isPurchasableReference, @@ -107,7 +108,7 @@ function standardizeUsageMass( enableYieldCalculation: boolean, lang?: string, ): void { - const numericQty = getNumericQty(usage.qty); + const numericQty = numericTotal(termsOfUsage(usage)); if (numericQty === null) return; const norm = standardizeMass( diff --git a/packages/analyzer/src/nutrition.ts b/packages/analyzer/src/nutrition.ts index df937d4d..3c4bb6ab 100644 --- a/packages/analyzer/src/nutrition.ts +++ b/packages/analyzer/src/nutrition.ts @@ -1,5 +1,6 @@ import { - getNumericQty, + numericTotal, + termsOfUsage, WarningCode, pushWarning, type Warning, @@ -116,7 +117,7 @@ export function calculateNutrition( mass = item.normalizedMass; if (item.isEstimate) isEst = true; } else if (item.qty) { - const val = getNumericQty(item.qty); + const val = numericTotal(termsOfUsage(item)); if (val !== null) { const unit = item.unit || "unit"; diff --git a/packages/i18n/src/index.ts b/packages/i18n/src/index.ts index e6800cce..8c2e7515 100644 --- a/packages/i18n/src/index.ts +++ b/packages/i18n/src/index.ts @@ -7,3 +7,4 @@ export * from "./categories"; export * from "./locales"; export * from "./template"; export * from "./duration"; +export * from "./quantity"; diff --git a/packages/i18n/src/quantity.ts b/packages/i18n/src/quantity.ts new file mode 100644 index 00000000..43bf7427 --- /dev/null +++ b/packages/i18n/src/quantity.ts @@ -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( + 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(""); +} diff --git a/packages/i18n/tests/quantity.test.ts b/packages/i18n/tests/quantity.test.ts new file mode 100644 index 00000000..669c2a60 --- /dev/null +++ b/packages/i18n/tests/quantity.test.ts @@ -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"); + }); +}); diff --git a/packages/kitchen/src/index.ts b/packages/kitchen/src/index.ts index 3c4976ae..41efd478 100644 --- a/packages/kitchen/src/index.ts +++ b/packages/kitchen/src/index.ts @@ -7,6 +7,7 @@ export * from "./registry"; export * from "./warnings"; export * from "./types"; export * from "./section"; +export * from "./terms"; export * from "./scale"; export * from "./graph"; export * from "./schedule-mode"; diff --git a/packages/kitchen/src/scale/ast.ts b/packages/kitchen/src/scale/ast.ts index e83051c5..0edb7be3 100644 --- a/packages/kitchen/src/scale/ast.ts +++ b/packages/kitchen/src/scale/ast.ts @@ -3,16 +3,18 @@ import { type RecipeAST, type StepAST, type IngredientAST, + type QuantityAST, type QuantityValueAST, } from "@gram-lang/parser"; -import { scaleQty } from "../utils"; +import { scaleUsageTerms, termsOfAst } from "../terms"; -function scaleQuantityValue( - value: QuantityValueAST | undefined, - factor: number, -): QuantityValueAST | undefined { - if (!value) return value; - return scaleQty(value, factor) as QuantityValueAST; +/** + * Scales a quantity node in place, through the same helper as `applyScale` + * (`scaleUsageTerms`), so the AST and the compiled recipe scale alike. + */ +function scaleQuantityNode(node: QuantityAST, factor: number): void { + const total = scaleUsageTerms(termsOfAst(node), factor); + if (total) node.value = total.qty as QuantityValueAST; } 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.fixed ) { - ing.quantity.value = scaleQuantityValue(ing.quantity.value, factor); + scaleQuantityNode(ing.quantity, factor); } const compositeQty = ing.composite?.quantity; if (compositeQty && !compositeQty.fixed) { - compositeQty.value = scaleQuantityValue(compositeQty.value, factor); + scaleQuantityNode(compositeQty, factor); } } diff --git a/packages/kitchen/src/scale/engine.ts b/packages/kitchen/src/scale/engine.ts index f4565ec4..11e88c5b 100644 --- a/packages/kitchen/src/scale/engine.ts +++ b/packages/kitchen/src/scale/engine.ts @@ -1,5 +1,6 @@ import { normalizeUnit } from "@gram-lang/i18n"; import { slugify, scaleQty, round2 } from "../utils"; +import { scaleUsageTerms, termsOfQuantity, termsOfUsage } from "../terms"; import type { CompilationResult, Usage } from "../types"; import type { ShoppingListItem, CompositeItem } from "../shopping"; import { @@ -186,19 +187,23 @@ function mutateUsage( // guard it would be scaled twice (factor²) here. const usage = item as Partial; if (usage.fixed) return; // @= modifier or TextQuantity — never scaled - if ("qty" in usage && usage.qty !== undefined) { - usage.qty = scaleQty(usage.qty, factor); - } + // Text (`{une pincée}`) and relative (`{10%}`) quantities have no terms: + // 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 // (`@egg-yolks{2}<@eggs{3}` -> composite.quantity 3) is a separate field // from `.qty` — the shopping list's own aggregated composite total is // scaled independently, further down, but this per-section copy wasn't. const composite = usage.composite; - if (composite && composite.quantity !== undefined) { - composite.quantity = scaleQty( - composite.quantity, + if (composite) { + const parentTotal = scaleUsageTerms( + termsOfQuantity(composite.quantity, composite.unit), factor, - ) as typeof composite.quantity; + ); + if (parentTotal) { + composite.quantity = parentTotal.qty as typeof composite.quantity; + } } scaled.add(item); } diff --git a/packages/kitchen/src/section.ts b/packages/kitchen/src/section.ts index 95b967af..5ac5bfda 100644 --- a/packages/kitchen/src/section.ts +++ b/packages/kitchen/src/section.ts @@ -1,4 +1,6 @@ import type { StepToken, Usage } from "./types"; +import { mergeTerms } from "@gram-lang/i18n"; +import { termsOfUsage } from "./terms"; import { round2 } from "./utils"; 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 { + 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: * @@ -94,7 +113,7 @@ export function aggregateSectionIngredients( if (hasMeasuredQty) { const existing = measuredByKey.get(key); if (existing) { - existing.quantities!.push({ qty: ing.qty!, unit: ing.unit ?? null }); + existing.quantities!.push(...occurrenceQuantities(ing)); if (ing.normalizedMass) { existing.normalizedMass = (existing.normalizedMass || 0) + ing.normalizedMass; @@ -111,7 +130,7 @@ export function aggregateSectionIngredients( } else { const entry: AggregatedIngredient = { ...createBaseEntry(ing, name), - quantities: [{ qty: ing.qty!, unit: ing.unit ?? null }], + quantities: occurrenceQuantities(ing), normalizedMass: ing.normalizedMass, conversionMethod: ing.conversionMethod, isEstimate: ing.isEstimate, diff --git a/packages/kitchen/src/shopping.ts b/packages/kitchen/src/shopping.ts index a782c08d..b6acae27 100644 --- a/packages/kitchen/src/shopping.ts +++ b/packages/kitchen/src/shopping.ts @@ -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 { 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 { CompilerOptions } from "./core"; import { isPurchasableReference } from "./registry"; @@ -22,6 +23,8 @@ export interface ShoppingListItem { multiUnit?: boolean; modifiers?: string[]; // 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; variableParts?: string[]; _usageIds?: string[]; @@ -117,6 +120,9 @@ export function generateShoppingList( _options?: CompilerOptions, ): (ShoppingListItem | CompositeItem | Usage)[] { const listMap = new Map(); + // 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(); const compositeMap = new Map(); const alternatives: Usage[] = []; @@ -149,7 +155,9 @@ export function generateShoppingList( let declParentQty = 1; 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; } @@ -175,7 +183,7 @@ export function generateShoppingList( } const uEntry = comp.usageAccumulator.get(uKey)!; - const numQ = getNumericQty(item.qty); + const numQ = numericTotal(termsOfUsage(item)); if (numQ !== null) { uEntry.qty = (typeof uEntry.qty === "number" ? uEntry.qty : 0) + numQ; } @@ -184,21 +192,13 @@ export function generateShoppingList( const id = item.id; - let numericQty: number | null = null; const unit = item.unit || ""; - let isGhost = false; - - if (item.formula) { - if (item.formula.isGhost) { - isGhost = true; - } else { - const numQ = getNumericQty(item.qty); - if (numQ !== null) numericQty = numQ; - } - } else { - const numQ = getNumericQty(item.qty); - if (numQ !== null) numericQty = numQ; - } + const isGhost = item.formula?.isGhost === true; + // The usage's terms, kept only when they amount to a number: a + // ghost formula has none to add, and a term without a number goes + // to the variable parts below, as written. + const terms = isGhost ? [] : termsOfUsage(item); + const numericQty = numericTotal(terms); // Group by ID AND unit (and ghost status) to prevent semantic data loss // where secondary units were stringified into variable_entries. The @@ -214,7 +214,6 @@ export function generateShoppingList( id: id, name: name, unit: unit, - otherUnits: {}, variableParts: [], _usageIds: [], }); @@ -250,9 +249,9 @@ export function generateShoppingList( const display = `${text} ❓`; existing.variableParts!.push(`(${display})`); } else if (numericQty !== null) { - const u = existing.unit ?? ""; - if (!existing.otherUnits![u]) existing.otherUnits![u] = 0; - existing.otherUnits![u] += numericQty; + const entryTerms = termsByKey.get(key); + if (entryTerms) entryTerms.push(...terms); + else termsByKey.set(key, [...terms]); } else { if (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 = { id: item.id, name: item.name, @@ -280,29 +279,15 @@ export function generateShoppingList( if (item.modifierSet && item.modifierSet.size > 0) res.modifiers = [...item.modifierSet]; - const units = Object.keys(item.otherUnits!); - const primaryUnit = units[0]; - if (primaryUnit !== undefined) { - res.qty = round2(item.otherUnits![primaryUnit] || 0); - res.unit = primaryUnit || null; + const terms = termsByKey.get(key); + if (terms) { + // A range adds up by its middle. + res.qty = round2(numericTotal(terms) ?? 0); + res.unit = item.unit || null; } - const hasOther = Object.keys(item.otherUnits!).length > 0; - - 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; + if (item.variableParts && item.variableParts.length > 0) { + res.variable_entries = [...item.variableParts]; } return res; diff --git a/packages/kitchen/src/terms.ts b/packages/kitchen/src/terms.ts new file mode 100644 index 00000000..dd6df27f --- /dev/null +++ b/packages/kitchen/src/terms.ts @@ -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( + 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; + } +} diff --git a/packages/kitchen/src/utils.ts b/packages/kitchen/src/utils.ts index 0deb7176..bca0ec55 100644 --- a/packages/kitchen/src/utils.ts +++ b/packages/kitchen/src/utils.ts @@ -7,7 +7,15 @@ import { ASTNodeType, } from "@gram-lang/parser"; 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"; // Imported from "./scale/types" (not the "./scale" barrel) to avoid a cycle: // "./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. * String quantities (TextQuantity) and undefined values are left unchanged. * - * `text`/`numerator`/`denominator` capture the original source string (e.g. "1/2") - * and are only valid for the unscaled value, so they're cleared here rather than - * carried over stale — display code must fall back to the scaled numeric `value`. - * - * The scale *factor* is validated (`isPositiveFinite` in scale/engine.ts, - * `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. + * The arithmetic lives in `@gram-lang/i18n` (`scaleTermValue`, the quantity + * model every amount goes through): rounded to 2 decimals, source text + * (`text`, a fraction's `numerator`/`denominator`) dropped, a scaled fraction + * turned into a single value. An overflow to a non-finite value throws + * `InvalidFactorError` instead of serializing as JSON `null`. */ export const scaleQty = (qty: Usage["qty"], factor: number): Usage["qty"] => { if (factor === 1) return qty; - - const scaleValue = (value: number): number => { - const scaled = value * factor; - if (!Number.isFinite(scaled)) { - throw new InvalidFactorError( - factor, - `Scaling by a factor of ${factor} overflowed a quantity to a non-finite value.`, - ); + if (!isTermValue(qty)) return qty; + try { + return scaleTermValue(qty, factor) as Usage["qty"]; + } catch (error) { + if (error instanceof QuantityOverflowError) { + throw new InvalidFactorError(factor, error.message); } - return round2(scaled); - }; - - 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 }; + throw error; } - 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` - * (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. + * Rounds a mass/quantity value to 2 decimal places (see `round2` in + * `@gram-lang/i18n`, where the rule is documented): re-exported here, where + * kitchen, analyzer and renderer have always imported it from. */ -export const round2 = (value: number): number => parseFloat(value.toFixed(2)); +export { round2 }; // Lives in the scheduler, which builds the timeline breakdowns with it. export { addToBreakdown } from "@gram-lang/scheduler"; @@ -392,14 +357,9 @@ export { addToBreakdown } from "@gram-lang/scheduler"; export const getNumericQty = ( q: Usage["qty"] | null | undefined, ): number | null => { - if (q === undefined || q === null) return null; - if (typeof q === "number") return q; - if (typeof q !== "object") return null; // string (TextQuantity's cleaned value) - - // RelativeQuantityAST/TextQuantityAST have no "fraction"/"range"/"single" - // variant — only a real QuantityValueAST does. - if (q.type === "fraction" || q.type === "range" || q.type === "single") { - return q.value ?? null; - } - return null; + // A text (TextQuantity's cleaned string) or a RelativeQuantityAST / + // TextQuantityAST is not a term value: only a number or a real + // QuantityValueAST is. Kept as public API; kitchen itself reads amounts + // through `termsOfUsage` / `numericTotal` (terms.ts). + return isTermValue(q) ? termValueNumber(q) : null; }; diff --git a/packages/kitchen/tests/terms.test.ts b/packages/kitchen/tests/terms.test.ts new file mode 100644 index 00000000..e2bf49c1 --- /dev/null +++ b/packages/kitchen/tests/terms.test.ts @@ -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, + ); + }); +}); diff --git a/packages/language-server/src/features/code-actions.ts b/packages/language-server/src/features/code-actions.ts index 5057306e..a07e675f 100644 --- a/packages/language-server/src/features/code-actions.ts +++ b/packages/language-server/src/features/code-actions.ts @@ -17,7 +17,7 @@ import { type IngredientDB, lookupIngredient } from "../ingredient-loader"; import { normalizeUnit } from "@gram-lang/i18n"; import { ASTNodeType, type QuantityAST } from "@gram-lang/parser"; import { standardizeMass } from "@gram-lang/analyzer"; -import { getNumericQty } from "@gram-lang/kitchen"; +import { numericTotal, termsOfAst } from "@gram-lang/kitchen"; export function provideCodeActions( state: DocumentState, @@ -248,7 +248,7 @@ export function provideCodeActions( : null; 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; if (canon) { const norm = standardizeMass(amount!, canon, db, entry?.name); diff --git a/packages/language-server/src/features/hover-nutrition.ts b/packages/language-server/src/features/hover-nutrition.ts index 51673573..90280976 100644 --- a/packages/language-server/src/features/hover-nutrition.ts +++ b/packages/language-server/src/features/hover-nutrition.ts @@ -15,7 +15,7 @@ import { import { normalizeUnit } from "@gram-lang/i18n"; import { NUTRIENTS, standardizeMass } from "@gram-lang/analyzer"; import { type QuantityAST, isQuantity } from "@gram-lang/parser"; -import { getNumericQty } from "@gram-lang/kitchen"; +import { numericTotal, termsOfAst } from "@gram-lang/kitchen"; function buildConversionSection( qty: QuantityAST, @@ -29,9 +29,7 @@ function buildConversionSection( const canon = normalizeUnit(rawUnit); if (!canon) return null; - const qtyValue = qty.value; - if (!qtyValue) return null; - const amount = getNumericQty(qtyValue); + const amount = numericTotal(termsOfAst(qty)); if (amount === null || amount <= 0) return null; const norm = standardizeMass(amount, canon, db, entry.name); diff --git a/packages/modules/src/yield.ts b/packages/modules/src/yield.ts index 3d48e761..03c25af7 100644 --- a/packages/modules/src/yield.ts +++ b/packages/modules/src/yield.ts @@ -5,8 +5,9 @@ import { type ImportDecl, } from "@gram-lang/parser"; import { - getNumericQty, + numericTotal, round2, + termsOfAst, forEachStep, type Warning, } from "@gram-lang/kitchen"; @@ -137,7 +138,7 @@ function collectReferenceQuantities( if (ref.name !== name) return; const q = ref.quantity; if (!q || q.type !== ASTNodeType.Quantity) return; - const value = getNumericQty(q.value); + const value = numericTotal(termsOfAst(q)); if (value === null) return; requests.push({ value, unit: q.unit ?? null }); } diff --git a/packages/renderer/src/shared/utils.ts b/packages/renderer/src/shared/utils.ts index f85d7000..297c108c 100644 --- a/packages/renderer/src/shared/utils.ts +++ b/packages/renderer/src/shared/utils.ts @@ -4,6 +4,8 @@ import type { AggregatedIngredient, StepToken } from "@gram-lang/kitchen"; import { commonFraction, formatNumber, + formatTerm, + isTermValue, getDictionary, isCoarseUnit, localizeDecimals, @@ -61,10 +63,12 @@ export function aggToRendererItem( } if (rest.length > 0) { 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 qStr = - qty?.text ?? - (typeof qty === "number" ? String(qty) : String(qty?.value ?? qty)); + const qStr = qty?.text ?? String(qty?.value ?? qty); return q.unit ? `${qStr} ${q.unit}` : qStr; }); }