diff --git a/.changeset/analyzer-percent-without-mass-std.md b/.changeset/analyzer-percent-without-mass-std.md new file mode 100644 index 00000000..e26a9860 --- /dev/null +++ b/.changeset/analyzer-percent-without-mass-std.md @@ -0,0 +1,5 @@ +--- +"@gram-lang/analyzer": patch +--- + +**Analyzer**: With mass standardization turned off, a percentage of an ingredient already written in a unit of mass (`@water{65% @&flour}` with `@flour{500 g}`) is now resolved instead of raising a false `RELATIVE_QUANTITY_UNKNOWN_MASS` warning; a target in volume or in pieces, which needs the ingredient database, still warns. diff --git a/packages/analyzer/src/index.ts b/packages/analyzer/src/index.ts index 6047839a..53ccf85c 100644 --- a/packages/analyzer/src/index.ts +++ b/packages/analyzer/src/index.ts @@ -31,6 +31,7 @@ import { isTermValue, mergeKey, termsTotal, + termValueNumber, } from "@gram-lang/i18n"; import { termsOfUsage, @@ -435,7 +436,7 @@ function resolveRelativeQuantities( progress = false; const waiting: RelativeEntry[] = []; for (const entry of shares) { - const outcome = resolveShare(entry, sec, sections, warnings); + const outcome = resolveShare(entry, sec, sections, warnings, opts); if (outcome === "wait") waiting.push(entry); else progress = true; } @@ -545,6 +546,20 @@ function warnUnknownMass( }); } +/** + * The grams of a usage written in a unit of mass (`500 g`, `8 oz`, `1 kg + + * 200 g`), converted within the mass family alone; `undefined` for a volume, + * a count or no quantity, which need the database. + */ +function writtenMass(usage: AnalyzedUsage, lang?: string): number | undefined { + const total = termsTotal(termsOfUsage(usage)); + if (!total) return undefined; + const value = termValueNumber(total.qty); + if (value === null || !total.unit) return undefined; + const grams = convertUnitInFamily(value, total.unit, "g", lang); + return grams === null ? undefined : grams; +} + /** * Resolves one share (`10% @&flour`) against the mentions it may target, in * grams: `wait` while a target is itself pending. @@ -554,6 +569,7 @@ function resolveShare( sec: AnalyzedSection, sections: AnalyzedSection[], warnings: CompilationResult["warnings"], + opts: AnalyzerOptions, ): "wait" | "done" { const item = entry.usage; const formula = item.formula as PercentFormula; @@ -566,11 +582,22 @@ function resolveShare( let targetMass = 0; let estimate = false; + let massless = false; for (const other of targets) { - if (other.normalizedMass === undefined) continue; - targetMass += other.normalizedMass; + // With mass standardization off, no target carries a `normalizedMass`: + // a mention already written in a unit of mass (`500 g`, `1 lb`) still + // gives its grams with no database. A volume or a count does not. + const mass = other.normalizedMass ?? writtenMass(other, opts.lang); + if (mass === undefined) { + massless = true; + continue; + } + targetMass += mass; if (other.isEstimate) estimate = true; } + // Off, a mention with no mass would leave a share of only part of its + // target: unknown rather than wrong. + if (massless && opts.enableMassStandardization === false) targetMass = 0; // An intermediate used whole: the mass of the section that makes it. if (!(targetMass > 0) && targetId) { diff --git a/packages/analyzer/tests/percent-without-mass-standardization.test.ts b/packages/analyzer/tests/percent-without-mass-standardization.test.ts new file mode 100644 index 00000000..99fab1d9 --- /dev/null +++ b/packages/analyzer/tests/percent-without-mass-standardization.test.ts @@ -0,0 +1,121 @@ +import { describe, it, expect } from "bun:test"; +import { getAST } from "@gram-lang/parser"; +import { compile, WarningCode } from "@gram-lang/kitchen"; +import type { Usage } from "@gram-lang/kitchen"; +import { analyze } from "../src/index"; +import type { IngredientData } from "../src/types"; + +// A share (`65% @&flour`) of an ingredient already written in a unit of mass +// used to stay unresolved when mass standardization was off: the target had +// no `normalizedMass`, the only thing `resolveShare()` read, and the share +// raised RELATIVE_QUANTITY_UNKNOWN_MASS although `500 g` needs no database. +const database: Record = { + "bread-flour": { name: "Bread flour", physical: { density: 0.55 } }, + flour: { name: "Flour", physical: { density: 0.55 } }, + butter: { name: "Butter", physical: { density: 0.91 } }, + egg: { name: "Egg", physical: { unitWeight: 50 } }, +}; + +function run(body: string) { + const compiled = compile(getAST(`## Dough\n\n${body}\n`)); + return analyze(compiled, database, { enableMassStandardization: false }); +} + +function usage(items: Usage[], id: string): Usage { + const found = items.find((i) => i.id === id); + if (!found) throw new Error(`no usage ${id}`); + return found; +} + +const unknownMass = (warnings: { code: string; item?: string }[]) => + warnings.filter((w) => w.code === WarningCode.RELATIVE_QUANTITY_UNKNOWN_MASS); + +describe("percentages when mass standardization is off", () => { + it("resolves a share of a target written in grams", () => { + const { result } = run( + "[Mix] Combine @*bread flour{500 g}, @water{65% @&bread flour}, @salt{2.8% @&bread flour}.", + ); + const items = result.sections[0]!.ingredients as Usage[]; + + expect(unknownMass(result.warnings)).toEqual([]); + expect(usage(items, "water")).toMatchObject({ + qty: { type: "single", value: 325 }, + unit: "g", + conversionMethod: "relative", + }); + expect(usage(items, "salt")).toMatchObject({ + qty: { type: "single", value: 14 }, + unit: "g", + }); + }); + + it("does not standardize the target itself", () => { + const { result } = run( + "Combine @bread flour{500 g} and @water{65% @&bread flour}.", + ); + const flour = usage( + result.sections[0]!.ingredients as Usage[], + "bread-flour", + ); + expect(flour.normalizedMass).toBeUndefined(); + expect(flour.conversionMethod).toBeUndefined(); + }); + + it("converts other units of mass straight to grams", () => { + const { result } = run( + "Combine @flour{1.2 kg}, @butter{8 oz}, @water{50% @&flour} and @salt{10% @&butter}.", + ); + const items = result.sections[0]!.ingredients as Usage[]; + expect(unknownMass(result.warnings)).toEqual([]); + expect(usage(items, "water").qty).toEqual({ type: "single", value: 600 }); + expect(usage(items, "salt").qty).toEqual({ + type: "single", + value: 22.68, + }); + }); + + it("chains shares (B a share of A, C a share of B)", () => { + const { result } = run( + "Combine @flour{200 g}, @water{70% @&flour} and @salt{10% @&water}.", + ); + const items = result.sections[0]!.ingredients as Usage[]; + expect(unknownMass(result.warnings)).toEqual([]); + expect(usage(items, "water").qty).toEqual({ type: "single", value: 140 }); + expect(usage(items, "salt").qty).toEqual({ type: "single", value: 14 }); + }); + + it("resolves a share inside an alternative, and one of an earlier option", () => { + const { result } = run( + "Mix @flour{200 g} and @butter{10% @&flour}|@oil{8% @&flour}.\n\nAdd @butter{100 g}|@lard{80% @&butter}.", + ); + expect(unknownMass(result.warnings)).toEqual([]); + const options = result.sections[0]!.ingredients.filter( + (i) => (i as Usage).type === "alternative", + ).flatMap((alt) => (alt as Usage).options as Usage[]); + const shares = options.filter((o) => o.conversionMethod === "relative"); + expect(shares.map((o) => [o.id, o.qty, o.unit])).toEqual([ + ["butter", { type: "single", value: 20 }, "g"], + ["oil", { type: "single", value: 16 }, "g"], + ["lard", { type: "single", value: 80 }, "g"], + ]); + }); + + it("still warns on a target in volume, which needs a density", () => { + const { result } = run("Combine @flour{2 cup} and @water{60% @&flour}."); + expect(unknownMass(result.warnings).map((w) => w.item)).toEqual(["water"]); + const water = usage(result.sections[0]!.ingredients as Usage[], "water"); + expect(water.normalizedMass).toBeUndefined(); + }); + + it("still warns on a target in pieces, which needs a unit weight", () => { + const { result } = run("Beat @egg{3} with @sugar{50% @&egg}."); + expect(unknownMass(result.warnings).map((w) => w.item)).toEqual(["sugar"]); + }); + + it("still warns when a mention of the target has no mass", () => { + const { result } = run( + "Combine @flour{200 g}, @flour{1 cup} and @water{60% @&flour}.", + ); + expect(unknownMass(result.warnings).map((w) => w.item)).toEqual(["water"]); + }); +});