Skip to content

Compilation (@gram-lang/kitchen)

If @gram-lang/parser defines the language grammar and vocabulary, @gram-lang/kitchen provides its logical and structural engine.

The Kitchen compiler takes the Abstract Syntax Tree (AST) generated by the parser. Its role: simulate recipe execution from start to finish, resolve intermediate variable bindings, generate the task scheduling graph, and assemble the initial consolidated shopping list.

The compilation pipeline (orchestrated by core.ts) delegates to several specialized sub-modules:

1. Structural scoping & processing (processor.ts)

Section titled “1. Structural scoping & processing (processor.ts)”

The processor traverses every section and step within the AST sequentially to build the execution timeline.

  • Variable Resolution: Every intermediate declaration (->&dough) is registered in the global symbol scope and linked to subsequent consuming steps (&dough).
  • Structural Diagnostics: The processor catches logical inconsistencies. Rather than throwing uncaught exceptions, it collects structured warning objects in CompilationResult.warnings, allowing renderers and tooling to display usable partial output. Referencing an undeclared intermediate emits an UNDEFINED_REFERENCE diagnostic. Multi-hop circular dependencies (&a -> &b -> &a) are identified via depth-first search (graph.ts) and reported as CIRCULAR_REFERENCE. Under gram check --strict, these warnings become fatal build errors.
  • ALAP Reverse Scheduling: The compiler applies ALAP (As Late As Possible) scheduling, delegated to the dedicated @gram-lang/scheduler package (see The scheduling engine). Multiple passes guarantee a deterministic and optimized schedule:
    • Phase 1 (Forward Pass): The compiler computes active durations and passive tasks to establish production durations for intermediate variables (->&name) in each section.
    • Phase 2 (Backward Pass): It walks backward from the end of the recipe (alap.ts). When an intermediate is consumed (&name), the engine determines its latest allowable completion deadline, honoring explicit section retro-planning anchors (~{-1d}). The producing step is then scheduled just-in-time.
    • Phase 3 (Serialization): Dedicated equipment tracks (named tracks, tracks.ts) are serialized to ensure passive timers sharing a constrained hardware resource (e.g. ~_oven) do not collide physically. Start times are adjusted sequentially without idle gaps.
    • Phase 4 (Positive Rebasing): Final chronological normalization (rebase.ts). If any preparation steps shifted into negative time relative to serving, the entire timeline is translated forward. The final timeline strictly starts at 0 with positive timestamps, simplifying frontend consumption.
    • Phase 5 (Task Graph and Default Schedule): Kitchen encapsulates forward pass results into an agnostic task graph (tasks): preparation tasks per section (prep), active steps (step), passive timers (passive) with elastic ranges ({ nominal, min, max }), and explicit dependency links (after). The @gram-lang/scheduler engine then calculates the default schedule (schedule: mise en place by section, shortest passive durations). Any alternative timeline (upfront preparation, per working day, longer passive durations) is computed on demand from this same graph via layout(), without recompiling. Section working days are derived from ~{-Nd} day anchors.
flowchart LR
    AST["📄 AST<br/>(from Parser)"] --> P1["Phase 1: Forward Pass<br/><i>Duration Estimation</i>"]
    P1 --> P2["Phase 2: Backward Pass<br/><i>ALAP Retro-Planning</i>"]
    P2 --> P3["Phase 3: Serialization<br/><i>Named Tracks Queueing</i>"]
    P3 --> P4["Phase 4: Rebasing<br/><i>Shift Timeline to 0</i>"]
    P4 --> P5["Phase 5: Task Graph<br/><i>Layout by Scheduler</i>"]
    P5 --> Result["⚙️ CompilationResult<br/><i>(tasks + schedule)</i>"]

2. Time metrics and mise en place (metrics.ts / processor.ts)

Section titled “2. Time metrics and mise en place (metrics.ts / processor.ts)”

Kitchen calculates four core time metrics, combined in core.ts:

  • Active Cooking Time (activeTime): Sum of all active timer durations, plus a 2-minute default for any step declaring no explicit timer.
  • Idle Time (idleTime): Total waiting duration during which the cook has no active tasks or mise en place to perform (totalTime - activeTime - preparationTime). This duration depends on the chosen scheduling mode and is read from schedule.
  • Preparation Time (preparationTime): Baseline mise en place allowance, independent of timers. It assigns 1 minute per unique ingredient and cookware item, plus 2 minutes for items requiring preliminary preparation notes (e.g. @onion(peeled and chopped)). Each ingredient is counted once in the first section using it; intermediates (&dough) are counted in the section that consumes them.
  • Total Time (totalTime): Sum of preparationTime + activeTime + idleTime. This is also read from schedule, as it varies depending on whether mise en place is absorbed in masked time or performed upfront.

Preparation time is broken down by section in miseEnPlace, describing item categorization (gathering ingredients, gathering cookware, slicing/prepping). The sum of all entries equals preparationTime.

3. Shopping list aggregation (shopping.ts)

Section titled “3. Shopping list aggregation (shopping.ts)”

Kitchen builds the consolidated ingredient purchasing list:

  • Syntactic Merging: Aggregates ingredient occurrences sharing the exact same raw identifier and unit. For instance, @butter{50g} in the dough and @butter{20g} in the frosting are summed into a single 70g entry.
  • Composite Ingredient Rules: Evaluates MAX and SUM logic for composite ingredients. Sibling portions use the maximum quantity (e.g. the greater of “zest of 2 lemons” and “juice of 3 lemons” wins), before summing (SUM) any parent ingredient quantity used as-is.
  • Hybrid Aggregation: Formulas for relative quantities are kept separate from absolute quantities until scaling.

Kitchen outputs the CompilationResult object (the compiled recipe). While structurally validated and chronologically scheduled, this JSON is not yet physically standardized.

For instance, Kitchen notes that 1 cup of flour is needed, but does not know its mass in grams. Physical enrichment is handled by the next stage: the Analyzer.

  • Dynamic Scaling: When a scale factor is provided during compilation, all numeric quantities are multiplied proportionally, except fixed quantities marked with = (e.g. @salt{=5g}) and non-numeric descriptions.
  • Baker’s Percentage Validation: The compiler validates that at most one ingredient is marked as the baker’s percentage reference (*). Multiple references throw a fatal compilation error.