fix(analyzer): resolve explicit-mass percentage targets when mass standardization is off #325
3 changed files with 156 additions and 3 deletions
5
.changeset/analyzer-percent-without-mass-std.md
Normal file
5
.changeset/analyzer-percent-without-mass-std.md
Normal file
|
|
@ -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.
|
||||||
|
|
@ -31,6 +31,7 @@ import {
|
||||||
isTermValue,
|
isTermValue,
|
||||||
mergeKey,
|
mergeKey,
|
||||||
termsTotal,
|
termsTotal,
|
||||||
|
termValueNumber,
|
||||||
} from "@gram-lang/i18n";
|
} from "@gram-lang/i18n";
|
||||||
import {
|
import {
|
||||||
termsOfUsage,
|
termsOfUsage,
|
||||||
|
|
@ -435,7 +436,7 @@ function resolveRelativeQuantities(
|
||||||
progress = false;
|
progress = false;
|
||||||
const waiting: RelativeEntry[] = [];
|
const waiting: RelativeEntry[] = [];
|
||||||
for (const entry of shares) {
|
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);
|
if (outcome === "wait") waiting.push(entry);
|
||||||
else progress = true;
|
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
|
* Resolves one share (`10% @&flour`) against the mentions it may target, in
|
||||||
* grams: `wait` while a target is itself pending.
|
* grams: `wait` while a target is itself pending.
|
||||||
|
|
@ -554,6 +569,7 @@ function resolveShare(
|
||||||
sec: AnalyzedSection,
|
sec: AnalyzedSection,
|
||||||
sections: AnalyzedSection[],
|
sections: AnalyzedSection[],
|
||||||
warnings: CompilationResult["warnings"],
|
warnings: CompilationResult["warnings"],
|
||||||
|
opts: AnalyzerOptions,
|
||||||
): "wait" | "done" {
|
): "wait" | "done" {
|
||||||
const item = entry.usage;
|
const item = entry.usage;
|
||||||
const formula = item.formula as PercentFormula;
|
const formula = item.formula as PercentFormula;
|
||||||
|
|
@ -566,11 +582,22 @@ function resolveShare(
|
||||||
|
|
||||||
let targetMass = 0;
|
let targetMass = 0;
|
||||||
let estimate = false;
|
let estimate = false;
|
||||||
|
let massless = false;
|
||||||
for (const other of targets) {
|
for (const other of targets) {
|
||||||
if (other.normalizedMass === undefined) continue;
|
// With mass standardization off, no target carries a `normalizedMass`:
|
||||||
targetMass += other.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;
|
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.
|
// An intermediate used whole: the mass of the section that makes it.
|
||||||
if (!(targetMass > 0) && targetId) {
|
if (!(targetMass > 0) && targetId) {
|
||||||
|
|
|
||||||
|
|
@ -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<string, IngredientData> = {
|
||||||
|
"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"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue