GRAM { // Blank lines may end the document whatever comes before them, nothing // included: "\n" (an empty file once formatted), the blank line after a // frontmatter or after the last `@use`. // A byte order mark opening the file is an encoding signature, not content: // without `bom?`, `\uFEFF## Prep` read its header as a step. Recipe = bom? Frontmatter? UseBlock? Content? nl* Content = | (nl* Block)* (nl* Section)+ -- explicit | (nl* Block)+ -- implicit Frontmatter = "---" nl KeyValue* "---" (nl | end) emptyLine = sp* nl KeyValue = emptyLine* key ":" sp* value nl key = (alnum | "_" | "-")+ value = (~nl any)* // Import directives, constrained between the frontmatter and the content -- // this is what makes "@use" unambiguous with an ingredient literally named // "use" that happens to appear in a step (unchanged, still parses as such). // The block must open with a real `UseDirective`: a leading `UseComment` on // its own (no `@use` anywhere in the block) is deliberately NOT swallowed // here, so a document with no imports at all keeps treating its opening // comment as ordinary content, exactly as before this feature existed. Once // the block has started, a comment between two directives doesn't break it. UseBlock = nl* useDirective (nl* (useDirective | useComment))* // `end` too: without it, a comment closing a file with no final newline // fell out of the block and became the recipe's content, while the same // file with its newline (the formatter adds one) had none (#207). useComment = applySyntactic (nl | end) useDirective = "@use" sp+ moduleSpecifier sp+ "as" sp+ bindings sp* retroPlanning? sp* (nl | end) moduleSpecifier = "\"" (~("\"" | nl) any)+ "\"" bindings = | "{" sp* binding moreBindings* sp* "}" -- named | binding -- default moreBindings = sp* "," sp* binding binding = "&" bindingName (sp+ "as" sp+ "&" bindingName)? bindingName = | bindingFullName "{}" -- full | bindingBareName -- bare // Unlike `name`, this must stop at "," and "&" -- a `{}`-delimited multi-word // binding sits inside a comma-separated list (`{ &a, &b multi{} }`) and can be // followed by a rename (`&a as &b multi{}`), so it must not swallow past the // next binding's separator or sigil while scanning ahead for its own "{}". bindingFullName = (~bindingFullNameStop any)+ bindingFullNameStop = syntaxChar | nl | "," | refSigil bindingBareName = (~bindingStop any)+ bindingStop = space | nl | syntaxChar | sentencePunct | "~{" Section = header Block* header = | "##" sp+ title headerExtension? sp* (lineEnd | end) -- ok | "##" sp+ title headerExtension sp* headerTrailing (lineEnd | end) -- trailing // `##` alone is an untitled header, like `## `: the formatter strips // the blank after it (rule 10), and `##` read as text + a cookware // named "#" made the section vanish on format (#205). | "##" sp* (lineEnd | end) -- empty // Text left after a header's `~{...}` / `->&name` (most often the second // word of a multi-word intermediate written without `{}`). Without this // branch the whole `##` line silently fell back to a step: the section // vanished, or its `~{-1d}` anchor surfaced as a misleading timer error. // Matched only to raise a readable error (see `header_trailing`). headerTrailing = (~nl any)+ headerExtension = | retroPlanning sp* intermediateDecl? -- retro | intermediateDecl sp* retroPlanning? -- decl titleStop = nl | "->&" | "~{" title = (~titleStop any)* // On one line, like every element but a block comment: an unclosed brace // never reaches into the next line (#216). Empty braces too, like a // timer's: the formatter trims `~{ }` to `~{}`, which used to stop being // an anchor and drop the section on format (#205). retroPlanning = "~{" (~("}" | nl) any)* "}" Block = | Comment nl* -- comment | (~header step) -- step // A line holding only blanks (`sp`) is a blank line, so it ends the step // just like an empty one: the formatter strips those blanks (rule 10), and // reading the line as more step text made formatting split the step. step = startAction? line (nl ~blankLine line)* (lineEnd | end) blankLine = sp* (nl | end) // A line break and the blank lines after it, blanks included: inside a // section nothing between two blocks skips them (`Block*`). lineEnd = nl (sp* nl)* // On one line: the action's text kept the source line break (`[Mix\r\nwell]`), // which formatting writes as LF, so the compiled recipe changed (#216). startAction = "[" (~("]" | nl) any)+ "]" sp* line = stepContent+ stepContent = | invalidUseDirective | invalidComposite | invalidAlternativeBar | text | ws | intermediateDecl | applySyntactic | fallback // A `@use "..."` past the import block (after the first step, misspelled, // or otherwise misplaced) would otherwise silently parse as an ingredient // literally named "use" followed by prose -- this turns it into a readable // error instead. Only triggers on the exact `@use "` prefix, so an actual // ingredient named "use" followed by unrelated quoted text is unaffected. invalidUseDirective = "@use" sp+ "\"" // Only reached when nothing before the blanks took them: a continuation line // opening on ` <@b`, or a lone `@` before ` <@parent`. After an ingredient // (`@zest{1} < @lemon{2}`) the blanks are already read, the line parses as // two ingredients and kitchen raises SPACED_COMPOSITE instead. invalidComposite = space+ "<" space* "@" name invalidAlternativeBar = "|" ws = space+ // A run of sigils with no name falls back in one piece, but for its last // sigil, which may still start an element (`@~{10 min}`: a timer). One // character at a time, each `@` of `@@@…` read the whole run again to // learn it has no name (singleWordName, #221): quadratic. fallback = sigilRun | ~nl any sigilRun = (refSigil &refSigil)+ Element = | Ingredient | Cookware | Timer | temperature | checkpoint | reference | CommentBlock | Comment // A full name stops at `~{`, like a title: `->&dough ~{}` declares // `dough` before an empty anchor, not a "dough ~" (#205). intermediateDecl = | "->&" declName "{}" -- full | "->&" singleWordName -- bare // Ingredients Ingredient = | Alternative | simpleIngredient Alternative = simpleIngredient ("|" simpleIngredient)+ // Rule: Quantity is mandatory unless it's a single word name // Uses refName (not name) so a bare @&chicken mention can't have its name // greedily swallow everything up to an unrelated later {...} that happens // to close a valid ingredientAmount -- e.g. "@&chicken for ~{3min}" must // stop at "~" and fall back to the bare alternative, not consume "chicken // for ~" as a bogus multi-word name with the timer's quantity attached. simpleIngredient = | "@" modifier* refName alias? ingredientAmount preparation? composite? -- full | "@" modifier* refName alias? malformedBraces -- malformed | "@" modifier* singleWordName alias? preparation? composite? -- bare modifier = "?" | "-" | "*" | "&" | "=" // Blanks alone up to the end of the line are no alias: `@salt: ` took them // as an empty one and the `:` vanished from the step, while `@salt:` kept // it as text, so stripping a trailing blank (the formatter) changed the // recipe. The `:` is text in both now. alias = ":" ~(sp* (nl | end)) refName ingredientQuantity = "{" space* (relativeQuantity | absoluteQuantity) space* "}" // The amount of an ingredient, a composite parent or a reference: an // ingredientQuantity, or a sum of quantities (`{1 cup + 1 tbsp}`, // `{1 cup - 2 tbsp}`). Since 1.5.0. Timers and temperatures keep // ingredientQuantity. PEG order matters: a choice that matches a prefix is // final, so a plain quantity is only taken when the braces close right // after it (`&`), otherwise it would take `1 cup` from `{1 cup + 1 tbsp}` // and fail on the `+`. Tried before the sum, it also keeps its range // (`{1 - 2 cup}` is one range, not 1 minus 2 cups) and its AST. ingredientAmount = "{" space* (ratioQuantity | relativeQuantity | closedQuantity | compoundQuantity) space* "}" closedQuantity = absoluteQuantity &(space* "}") compoundQuantity = quantityTerm (space* compoundOp space* quantityTerm)+ // The unit is optional so `{1 + 1 cup}` reaches the compiler, which says // what is wrong with it, instead of failing as a syntax error. quantityTerm = (range | number) (space* unit)? compoundOp = "+" | "-" relativeQuantity = number space* "%" space* ("@&" | "&") space* name // A ratio with units (`1 / 100 g @&farine`, `15 g / L @&eau`, `1 / @&côtelette`): // an amount per amount of a target. A fraction glued to a slash stays a // fraction (`plainNumber` takes `1/100`), so `{1/100g @&farine}` and // `{1/2 @&farine}` fail here and end as malformedBraces: a ratio needs a // space on one side of its slash at least. Since 1.5.0. ratioQuantity = ratioTerm space* "/" space* ratioDenominator? space* targetRef ratioTerm = (range | number) (space* unit)? ratioDenominator = | number (space* unit)? -- amount | unit -- unit // Stops at `*` and `×` so a cycle multiplier can follow a ratio later on. targetRef = ("@&" | "&") space* ratioTargetName ratioTargetName = (~(syntaxChar | "*" | "×" | nl) any)+ absoluteQuantity = (range | number)? space* (unit space*)? // On one line, like timerText (#216). textQuantity = "{" space* (~("}" | nl) any)+ space* "}" fixed = "=" // A unit is one or more words. A word may contain "." or an apostrophe after // its first character (c.à.s, fl. oz., d'eau) but never starts with one, so a // stray "{1. kg}" or "{.5 g}" is still rejected rather than half-parsed. unit = unitName unitName = unitWord (sp+ unitWord)* unitWord = unitLead unitChar* unitLead = alnum | "°" | "%" unitChar = unitLead | "." | "'" | "’" // A "{...}" glued to an element that did not parse as a valid quantity. Without // this, the element silently fell back to its bare form (name truncated to its // first word) and the braces leaked into prose -- merging distinct ingredients. // Each "-- malformed" branch below turns that into a readable error instead. malformedBraces = "{" (~("}" | nl) any)* ("}" | &nl | end) // The parenthesis glued to an element: an ingredient's or a tool's // preparation, a composite parent's, a temperature's or a target state's // note. Every rule using it is lexical, so it touches what comes before it. // On one line: an unclosed `(` is prose, never the start // of a preparation that would run to the next `)` further down the recipe, // over blank lines and section headers. preparation = "(" (~(")" | nl) any)* ")" // `modifier*` mirrors simpleIngredient: a composite parent is an ingredient // reference like any other, and authors (and AI importers) write `<@&parent` // to mark a parent already introduced earlier. Without it, `refName` rejected // the leading "&" (it is a refSigil), the `bare` branch fell through to // `singleWordName` -- which does allow "&" -- and a multi-word parent silently // truncated at the first space, registering a phantom ingredient literally // named "&citron" alongside the real one. The modifiers are parsed and then // ignored (see composite_full/composite_bare): "&" is redundant on a parent // because the MAX rule already collapses repeat draws into one purchase. composite = | "<@" modifier* refName ingredientAmount preparation? -- full | "<@" modifier* refName malformedBraces -- malformed | "<@" modifier* singleWordName preparation? -- bare // Cookware Cookware = | CookwareAlternative | simpleCookware CookwareAlternative = simpleCookware ("|" simpleCookware)+ // Same refName fix as simpleIngredient above -- a bare #pan mention must not // swallow an unrelated later {...} (e.g. another ingredient's integer-only // quantity) into its own name. simpleCookware = | "#" modifier* refName alias? cookwareQuantity preparation? -- full | "#" modifier* refName alias? malformedBraces -- malformed | "#" modifier* singleWordName alias? preparation? -- bare // Cookware quantity is numbers only, no units (e.g. {}, {2}) -- unlike ingredientQuantity. cookwareQuantity = "{" space* number? space* "}" // Timer // `ingredientQuantity` comes first (PEG order) so a plain timer keeps its // AST: `~{10 min}`, and also `~{1h30}`, read as 1 + unit "h30". Anything // else closed on the same line (`1:30 h`, `5'30"`, `1h + 30min`, `1h30-2h`) // is kept as text. Either way the AST carries `raw`, the text between the // braces, and the compiler reads the duration from it (`parseDuration` in // @gram-lang/i18n), never from the quantity. Only an unclosed brace is // still a syntax error. // // A proportional time (`~{15 min / 500 g @&roti}`) is tried first: its // numerator is read by parseDuration like any timer (`1:30 h`, `5'30"`). // Since 1.5.0. Timer = | "~" "_"? name? timerRatio -- ratio | "~" "_"? name? ingredientQuantity -- full | "~" "_"? name? timerText -- text | "~" "_"? name? malformedBraces -- malformed timerText = "{" (~("}" | nl) any)* "}" timerRatio = "{" space* timerRatioDuration space* "/" space* ratioDenominator? space* targetRef space* "}" timerRatioDuration = (number | (~("/" | "*" | "×" | "}" | nl) any))+ // Temperature // Lexical, so only a note glued to `}` is one: `^{180°C}(fan)` has a note, // `^{180°C} (preheated)` keeps its parenthesis in the prose. `name` may // start with a space, as it could when the rule was syntactic: `^ {180°C}` // and `^oven {180°C}` read as before (`clean` drops the space). The note // since 1.5.0. temperature = "^" name? (ingredientQuantity | textQuantity) preparation? // Target state (a checkpoint in the AST): the state that ends a step // (`until ={ribbon stage}`), with an optional note glued to `}` that says // how to check it (`={coats the spoon}(a finger leaves a clean line)`). // Lexical, like `temperature`: `={ribbon} (prose)` keeps its parenthesis in // the prose. The state is words for the cook, never read by Gram. An empty // or unclosed `={` is a readable error, not prose. Since 1.5.0. checkpoint = | "={" checkpointState "}" preparation? -- full | "=" malformedBraces -- malformed checkpointState = (~("}" | nl) any)+ // Comments Comment = "//" (~nl any)* CommentBlock = "/*" (~"*/" any)* "*/" // Primitives name = (~(syntaxChar | nl) any)+ declName = (~(syntaxChar | nl | "~{") any)+ // A word made only of element sigils (`##`, `@@`, `#~`, `&&`) is no name: // the element falls back to text, like `@` or `#` alone, instead of // registering a tool or an ingredient called `#` (#221). singleWordName = ~(refSigil+ (wordStop | end)) (~wordStop any)+ wordStop = syntaxChar | space | nl | sentencePunct sentencePunct = "," | ";" | "!" | "?" | "." // Like name, but also stops at element sigils so a bare &dough is not consumed // into a Reference -- full when a sigil like # or @ appears later on the line. refName = (~(syntaxChar | refSigil | nl) any)+ refSigil = "@" | "#" | "~" | "^" | "&" number = mixedFraction | unicodeFraction | plainNumber // "." or "," between two digits is a decimal separator (1.5, 1,5): Gram has // no thousands separator. A comma not between two digits ({1, 5 kg}) still // fails, so the commas of the prose around an element are never touched. plainNumber = digit+ (("." | ",") digit+)? ("/" digit+)? mixedFraction = digit+ sp+ digit+ "/" digit+ unicodeFraction = | digit+ unicodeFractionChar -- mixed | unicodeFractionChar -- bare unicodeFractionChar = "¼" | "½" | "¾" | "⅓" | "⅔" | "⅕" | "⅖" | "⅗" | "⅘" | "⅙" | "⅚" | "⅛" | "⅜" | "⅝" | "⅞" range = number space* "-" space* number text = space* (~(elementStart | nl | "|") any)+ // Lexical, like simpleIngredient and simpleCookware: as a syntactic rule // it skipped the blanks after `&`, so the `&` of prose (`Rock & roll.`, // `Salt & pepper{}`) took the next word as a reference. The name starts // right after the `&`, or the `&` is text. reference = | "&" ~space refName ingredientAmount -- full | "&" ~space refName malformedBraces -- malformed | "&" singleWordName -- bare // Delimiters that end a name (start of quantity/alias/preparation/composite/alternative). // @, #, ~, !, &, ?, * are deliberately absent here, so names may contain them freely -- // only elementStart (below) treats those as starting a new element, and only in free text. // A `=` ends a name only before `{`, where a target state starts: without it a bare // `@salt until ={taste}` read an ingredient "salt until =" of unit "taste" (1.5.0). syntaxChar = "={" | "{" | "}" | "[" | "]" | "(" | ")" | "<" | "|" | ":" // Stricter than syntaxChar: used to detect where an element starts within free text. elementStart = "@" | "#" | "~" | "^" | "={" | "//" | "/*" | "->&" | "&" // The blank characters of Gram are exactly these. A line break is LF, CRLF // or a lone CR (old Mac files; the editor counts it as one too), and a // blank is a space or a tab: no other Unicode space (a no-break space is // French typography, a mid-file U+FEFF a character), so the formatter may // only ever strip `sp` and line breaks (packages/format, rules 10 and 12). nl = "\r\n" | "\n" | "\r" sp = " " | "\t" space := sp bom = "\uFEFF" }