diff --git a/.changeset/parser-alias-no-leading-blank.md b/.changeset/parser-alias-no-leading-blank.md new file mode 100644 index 00000000..e4fbc1a5 --- /dev/null +++ b/.changeset/parser-alias-no-leading-blank.md @@ -0,0 +1,5 @@ +--- +"@gram-lang/parser": minor +--- + +**Parser**: A component alias now starts right after the colon, with no blank (`@dry white wine:wine{10ml}`, `#cast iron skillet:skillet{}`); a colon followed by a space or a tab is ordinary punctuation. `Heat the #pan: then add oil.` read `then add oil.` as the alias of `pan`, and that text vanished from the step without a word; it now stays in the step. A recipe that wrote an alias after a blank (`@salt: fleur de sel{1g}`) should glue it to the colon (`@salt:fleur de sel{1g}`). diff --git a/fuzz/regressions/273-colon-blank-alias.gram b/fuzz/regressions/273-colon-blank-alias.gram new file mode 100644 index 00000000..c6dd814a --- /dev/null +++ b/fuzz/regressions/273-colon-blank-alias.gram @@ -0,0 +1,3 @@ +Heat the #pan: then add oil. + +Add @flour: sifted. diff --git a/packages/docs/src/content/docs/docs/reference/syntax/cookware.mdx b/packages/docs/src/content/docs/docs/reference/syntax/cookware.mdx index ea939c02..e3bc2f8d 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/cookware.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/cookware.mdx @@ -4,6 +4,7 @@ description: "How to declare cookware with the # symbol, including quantity coun --- import { Badge, Tabs, TabItem, LinkCard, CardGrid } from '@astrojs/starlight/components'; +import Since from '../../../../../components/Since.astro'; You can define the tools and equipment needed for a recipe using the `#` symbol. @@ -84,6 +85,8 @@ You can rename an equipment item for display while keeping a clean canonical slu ```gram [Use] The #cast iron skillet:skillet{}. ``` + +The display name is glued to the colon: in `Heat the #pan: then add oil.`, the colon followed by a space is punctuation and the rest of the line stays text . You can declare acceptable equipment substitutions using the pipe `|` operator: diff --git a/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx b/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx index f7a63cda..cea6bf06 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx @@ -145,6 +145,8 @@ You can rename an `@ingredient` for display purposes using a colon `:` immediate **Format**: `@Real Name:Display Name{Quantity}` +The display name starts right after the colon, with no space. A colon followed by a space is ordinary punctuation: `Heat the @butter: then add the onions.` keeps `: then add the onions.` as text . + ```gram title="Code" [Deglaze] With @dry white wine:wine{100ml}. diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/cookware.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/cookware.mdx index 1e0e6a46..e3e08a59 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/cookware.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/cookware.mdx @@ -4,6 +4,7 @@ description: "Comment déclarer le matériel de cuisine avec le symbole #, entre --- import { Badge, Tabs, TabItem, LinkCard, CardGrid } from '@astrojs/starlight/components'; +import Since from '../../../../../../components/Since.astro'; Le matériel, les ustensiles et l'équipement requis par une recette se déclarent à l'aide du symbole `#`. @@ -84,6 +85,8 @@ Vous pouvez renommer un équipement pour l'affichage tout en conservant un ident ```gram [Utiliser] La #poêle en fonte:poêle{}. ``` + +Le nom d'affichage se colle aux deux-points : dans `Chauffez la #poêle: puis versez l'huile.`, les deux-points suivis d'une espace sont une ponctuation et la fin de la ligne reste du texte . Vous pouvez définir des alternatives d'ustensiles interchangeables avec l'opérateur `|` : diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx index 59624cc4..0ca96cb0 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx @@ -145,6 +145,8 @@ Vous pouvez surcharger le nom d'affichage d'un `@ingrédient` en utilisant les d **Format** : `@Vrai Nom:Nom d'Affichage{Quantité}` +Le nom d'affichage se colle aux deux-points, sans espace. Suivis d'une espace, les deux-points redeviennent une simple ponctuation : dans `Faites fondre le @beurre: puis ajoutez les oignons.`, la suite `: puis ajoutez les oignons.` reste du texte . + ```gram title="Code" [Déglacer] Avec le @vin blanc sec:vin{100 ml}. diff --git a/packages/parser/grammar.ohm b/packages/parser/grammar.ohm index aae63386..fc1aa68e 100644 --- a/packages/parser/grammar.ohm +++ b/packages/parser/grammar.ohm @@ -159,11 +159,12 @@ GRAM { | "@" 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 + // The alias starts right after the `:`, with no blank (`@dry white + // wine:wine{10ml}`). A `:` followed by a blank is punctuation: `Heat the + // #pan: then add oil.` read the rest of the line as the alias of `pan` and + // it vanished from the step (#273). It also covers `@salt: ` at the end of + // a line, which took the blanks as an empty alias (#281). + alias = ":" ~sp 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}`, diff --git a/packages/parser/src/grammar-content.ts b/packages/parser/src/grammar-content.ts index 3e90e19e..33c1d0e5 100644 --- a/packages/parser/src/grammar-content.ts +++ b/packages/parser/src/grammar-content.ts @@ -1,2 +1,2 @@ // AUTO-GENERATED FILE. DO NOT EDIT. -export const grammarContent = "GRAM {\n // Blank lines may end the document whatever comes before them, nothing\n // included: \"\\n\" (an empty file once formatted), the blank line after a\n // frontmatter or after the last `@use`.\n // A byte order mark opening the file is an encoding signature, not content:\n // without `bom?`, `\\uFEFF## Prep` read its header as a step.\n Recipe = bom? Frontmatter? UseBlock? Content? nl*\n\n Content =\n | (nl* Block)* (nl* Section)+ -- explicit\n | (nl* Block)+ -- implicit\n\n Frontmatter = \"---\" nl KeyValue* \"---\" (nl | end)\n emptyLine = sp* nl\n KeyValue = emptyLine* key \":\" sp* value nl\n key = (alnum | \"_\" | \"-\")+\n value = (~nl any)*\n\n // Import directives, constrained between the frontmatter and the content --\n // this is what makes \"@use\" unambiguous with an ingredient literally named\n // \"use\" that happens to appear in a step (unchanged, still parses as such).\n // The block must open with a real `UseDirective`: a leading `UseComment` on\n // its own (no `@use` anywhere in the block) is deliberately NOT swallowed\n // here, so a document with no imports at all keeps treating its opening\n // comment as ordinary content, exactly as before this feature existed. Once\n // the block has started, a comment between two directives doesn't break it.\n UseBlock = nl* useDirective (nl* (useDirective | useComment))*\n // `end` too: without it, a comment closing a file with no final newline\n // fell out of the block and became the recipe's content, while the same\n // file with its newline (the formatter adds one) had none (#207).\n useComment = applySyntactic (nl | end)\n useDirective = \"@use\" sp+ moduleSpecifier sp+ \"as\" sp+ bindings sp* retroPlanning? sp* (nl | end)\n moduleSpecifier = \"\\\"\" (~(\"\\\"\" | nl) any)+ \"\\\"\"\n bindings =\n | \"{\" sp* binding moreBindings* sp* \"}\" -- named\n | binding -- default\n moreBindings = sp* \",\" sp* binding\n binding = \"&\" bindingName (sp+ \"as\" sp+ \"&\" bindingName)?\n bindingName =\n | bindingFullName \"{}\" -- full\n | bindingBareName -- bare\n // Unlike `name`, this must stop at \",\" and \"&\" -- a `{}`-delimited multi-word\n // binding sits inside a comma-separated list (`{ &a, &b multi{} }`) and can be\n // followed by a rename (`&a as &b multi{}`), so it must not swallow past the\n // next binding's separator or sigil while scanning ahead for its own \"{}\".\n bindingFullName = (~bindingFullNameStop any)+\n bindingFullNameStop = syntaxChar | nl | \",\" | refSigil\n bindingBareName = (~bindingStop any)+\n bindingStop = space | nl | syntaxChar | sentencePunct | \"~{\"\n\n Section = header Block*\n header =\n | \"##\" sp+ title headerExtension? sp* (lineEnd | end) -- ok\n | \"##\" sp+ title headerExtension sp* headerTrailing (lineEnd | end) -- trailing\n // `##` alone is an untitled header, like `## `: the formatter strips\n // the blank after it (rule 10), and `##` read as text + a cookware\n // named \"#\" made the section vanish on format (#205).\n | \"##\" sp* (lineEnd | end) -- empty\n // Text left after a header's `~{...}` / `->&name` (most often the second\n // word of a multi-word intermediate written without `{}`). Without this\n // branch the whole `##` line silently fell back to a step: the section\n // vanished, or its `~{-1d}` anchor surfaced as a misleading timer error.\n // Matched only to raise a readable error (see `header_trailing`).\n headerTrailing = (~nl any)+\n headerExtension = \n | retroPlanning sp* intermediateDecl? -- retro\n | intermediateDecl sp* retroPlanning? -- decl\n titleStop = nl | \"->&\" | \"~{\"\n title = (~titleStop any)*\n \n // On one line, like every element but a block comment: an unclosed brace\n // never reaches into the next line (#216). Empty braces too, like a\n // timer's: the formatter trims `~{ }` to `~{}`, which used to stop being\n // an anchor and drop the section on format (#205).\n retroPlanning = \"~{\" (~(\"}\" | nl) any)* \"}\"\n \n Block = \n | Comment nl* -- comment\n | (~header step) -- step\n \n // A line holding only blanks (`sp`) is a blank line, so it ends the step\n // just like an empty one: the formatter strips those blanks (rule 10), and\n // reading the line as more step text made formatting split the step.\n step = startAction? line (nl ~blankLine line)* (lineEnd | end)\n blankLine = sp* (nl | end)\n // A line break and the blank lines after it, blanks included: inside a\n // section nothing between two blocks skips them (`Block*`).\n lineEnd = nl (sp* nl)*\n // On one line: the action's text kept the source line break (`[Mix\\r\\nwell]`),\n // which formatting writes as LF, so the compiled recipe changed (#216).\n startAction = \"[\" (~(\"]\" | nl) any)+ \"]\" sp*\n line = stepContent+\n stepContent =\n | invalidUseDirective\n | invalidComposite\n | invalidAlternativeBar\n | text\n | ws\n | intermediateDecl\n | applySyntactic\n | fallback\n\n // A `@use \"...\"` past the import block (after the first step, misspelled,\n // or otherwise misplaced) would otherwise silently parse as an ingredient\n // literally named \"use\" followed by prose -- this turns it into a readable\n // error instead. Only triggers on the exact `@use \"` prefix, so an actual\n // ingredient named \"use\" followed by unrelated quoted text is unaffected.\n invalidUseDirective = \"@use\" sp+ \"\\\"\"\n\n // Only reached when nothing before the blanks took them: a continuation line\n // opening on ` <@b`, or a lone `@` before ` <@parent`. After an ingredient\n // (`@zest{1} < @lemon{2}`) the blanks are already read, the line parses as\n // two ingredients and kitchen raises SPACED_COMPOSITE instead.\n invalidComposite = space+ \"<\" space* \"@\" name\n\n invalidAlternativeBar = \"|\"\n\n ws = space+\n\n // A run of sigils with no name falls back in one piece, but for its last\n // sigil, which may still start an element (`@~{10 min}`: a timer). One\n // character at a time, each `@` of `@@@…` read the whole run again to\n // learn it has no name (singleWordName, #221): quadratic.\n fallback = sigilRun | ~nl any\n sigilRun = (refSigil &refSigil)+\n\n Element = \n | Ingredient\n | Cookware\n | Timer\n | temperature\n | checkpoint\n | reference\n | CommentBlock\n | Comment\n\n // A full name stops at `~{`, like a title: `->&dough ~{}` declares\n // `dough` before an empty anchor, not a \"dough ~\" (#205).\n intermediateDecl =\n | \"->&\" declName \"{}\" -- full\n | \"->&\" singleWordName -- bare\n\n // Ingredients\n Ingredient = \n | Alternative\n | simpleIngredient\n\n Alternative = simpleIngredient (\"|\" simpleIngredient)+\n \n // Rule: Quantity is mandatory unless it's a single word name\n // Uses refName (not name) so a bare @&chicken mention can't have its name\n // greedily swallow everything up to an unrelated later {...} that happens\n // to close a valid ingredientAmount -- e.g. \"@&chicken for ~{3min}\" must\n // stop at \"~\" and fall back to the bare alternative, not consume \"chicken\n // for ~\" as a bogus multi-word name with the timer's quantity attached.\n simpleIngredient =\n | \"@\" modifier* refName alias? ingredientAmount preparation? composite? -- full\n | \"@\" modifier* refName alias? malformedBraces -- malformed\n | \"@\" modifier* singleWordName alias? preparation? composite? -- bare\n\n modifier = \"?\" | \"-\" | \"*\" | \"&\" | \"=\"\n // Blanks alone up to the end of the line are no alias: `@salt: ` took them\n // as an empty one and the `:` vanished from the step, while `@salt:` kept\n // it as text, so stripping a trailing blank (the formatter) changed the\n // recipe. The `:` is text in both now.\n alias = \":\" ~(sp* (nl | end)) refName\n ingredientQuantity = \"{\" space* (relativeQuantity | absoluteQuantity) space* \"}\"\n // The amount of an ingredient, a composite parent or a reference: an\n // ingredientQuantity, or a sum of quantities (`{1 cup + 1 tbsp}`,\n // `{1 cup - 2 tbsp}`). Since 1.5.0. Timers and temperatures keep\n // ingredientQuantity. PEG order matters: a choice that matches a prefix is\n // final, so a plain quantity is only taken when the braces close right\n // after it (`&`), otherwise it would take `1 cup` from `{1 cup + 1 tbsp}`\n // and fail on the `+`. Tried before the sum, it also keeps its range\n // (`{1 - 2 cup}` is one range, not 1 minus 2 cups) and its AST.\n ingredientAmount = \"{\" space* (ratioQuantity | relativeQuantity | closedQuantity | compoundQuantity) space* \"}\"\n closedQuantity = absoluteQuantity &(space* \"}\")\n compoundQuantity = quantityTerm (space* compoundOp space* quantityTerm)+\n // The unit is optional so `{1 + 1 cup}` reaches the compiler, which says\n // what is wrong with it, instead of failing as a syntax error.\n quantityTerm = (range | number) (space* unit)?\n compoundOp = \"+\" | \"-\"\n relativeQuantity = number space* \"%\" space* (\"@&\" | \"&\") space* name\n // A ratio with units (`1 / 100 g @&farine`, `15 g / L @&eau`, `1 / @&côtelette`):\n // an amount per amount of a target. A fraction glued to a slash stays a\n // fraction (`plainNumber` takes `1/100`), so `{1/100g @&farine}` and\n // `{1/2 @&farine}` fail here and end as malformedBraces: a ratio needs a\n // space on one side of its slash at least. Since 1.5.0.\n ratioQuantity = ratioTerm space* \"/\" space* ratioDenominator? space* targetRef\n ratioTerm = (range | number) (space* unit)?\n ratioDenominator =\n | number (space* unit)? -- amount\n | unit -- unit\n // Stops at `*` and `×` so a cycle multiplier can follow a ratio later on.\n targetRef = (\"@&\" | \"&\") space* ratioTargetName\n ratioTargetName = (~(syntaxChar | \"*\" | \"×\" | nl) any)+\n absoluteQuantity = (range | number)? space* (unit space*)?\n // On one line, like timerText (#216).\n textQuantity = \"{\" space* (~(\"}\" | nl) any)+ space* \"}\"\n fixed = \"=\"\n // A unit is one or more words. A word may contain \".\" or an apostrophe after\n // its first character (c.à.s, fl. oz., d'eau) but never starts with one, so a\n // stray \"{1. kg}\" or \"{.5 g}\" is still rejected rather than half-parsed.\n unit = unitName\n unitName = unitWord (sp+ unitWord)*\n unitWord = unitLead unitChar*\n unitLead = alnum | \"°\" | \"%\"\n unitChar = unitLead | \".\" | \"'\" | \"’\"\n\n // A \"{...}\" glued to an element that did not parse as a valid quantity. Without\n // this, the element silently fell back to its bare form (name truncated to its\n // first word) and the braces leaked into prose -- merging distinct ingredients.\n // Each \"-- malformed\" branch below turns that into a readable error instead.\n malformedBraces = \"{\" (~(\"}\" | nl) any)* (\"}\" | &nl | end)\n // The parenthesis glued to an element: an ingredient's or a tool's\n // preparation, a composite parent's, a temperature's or a target state's\n // note. Every rule using it is lexical, so it touches what comes before it.\n // On one line: an unclosed `(` is prose, never the start\n // of a preparation that would run to the next `)` further down the recipe,\n // over blank lines and section headers.\n preparation = \"(\" (~(\")\" | nl) any)* \")\"\n // `modifier*` mirrors simpleIngredient: a composite parent is an ingredient\n // reference like any other, and authors (and AI importers) write `<@&parent`\n // to mark a parent already introduced earlier. Without it, `refName` rejected\n // the leading \"&\" (it is a refSigil), the `bare` branch fell through to\n // `singleWordName` -- which does allow \"&\" -- and a multi-word parent silently\n // truncated at the first space, registering a phantom ingredient literally\n // named \"&citron\" alongside the real one. The modifiers are parsed and then\n // ignored (see composite_full/composite_bare): \"&\" is redundant on a parent\n // because the MAX rule already collapses repeat draws into one purchase.\n composite =\n | \"<@\" modifier* refName ingredientAmount preparation? -- full\n | \"<@\" modifier* refName malformedBraces -- malformed\n | \"<@\" modifier* singleWordName preparation? -- bare\n\n // Cookware\n Cookware =\n | CookwareAlternative\n | simpleCookware\n\n CookwareAlternative = simpleCookware (\"|\" simpleCookware)+\n // Same refName fix as simpleIngredient above -- a bare #pan mention must not\n // swallow an unrelated later {...} (e.g. another ingredient's integer-only\n // quantity) into its own name.\n simpleCookware =\n | \"#\" modifier* refName alias? cookwareQuantity preparation? -- full\n | \"#\" modifier* refName alias? malformedBraces -- malformed\n | \"#\" modifier* singleWordName alias? preparation? -- bare\n\n // Cookware quantity is numbers only, no units (e.g. {}, {2}) -- unlike ingredientQuantity.\n cookwareQuantity = \"{\" space* number? space* \"}\"\n\n // Timer\n // `ingredientQuantity` comes first (PEG order) so a plain timer keeps its\n // AST: `~{10 min}`, and also `~{1h30}`, read as 1 + unit \"h30\". Anything\n // else closed on the same line (`1:30 h`, `5'30\"`, `1h + 30min`, `1h30-2h`)\n // is kept as text. Either way the AST carries `raw`, the text between the\n // braces, and the compiler reads the duration from it (`parseDuration` in\n // @gram-lang/i18n), never from the quantity. Only an unclosed brace is\n // still a syntax error.\n //\n // A proportional time (`~{15 min / 500 g @&roti}`) is tried first: its\n // numerator is read by parseDuration like any timer (`1:30 h`, `5'30\"`).\n // Since 1.5.0.\n Timer =\n | \"~\" \"_\"? name? timerRatio -- ratio\n | \"~\" \"_\"? name? ingredientQuantity -- full\n | \"~\" \"_\"? name? timerText -- text\n | \"~\" \"_\"? name? malformedBraces -- malformed\n timerText = \"{\" (~(\"}\" | nl) any)* \"}\"\n timerRatio = \"{\" space* timerRatioDuration space* \"/\" space* ratioDenominator? space* targetRef space* \"}\"\n timerRatioDuration = (number | (~(\"/\" | \"*\" | \"×\" | \"}\" | nl) any))+\n \n // Temperature\n // Lexical, so only a note glued to `}` is one: `^{180°C}(fan)` has a note,\n // `^{180°C} (preheated)` keeps its parenthesis in the prose. `name` may\n // start with a space, as it could when the rule was syntactic: `^ {180°C}`\n // and `^oven {180°C}` read as before (`clean` drops the space). The note\n // since 1.5.0.\n temperature = \"^\" name? (ingredientQuantity | textQuantity) preparation?\n\n // Target state (a checkpoint in the AST): the state that ends a step\n // (`until ={ribbon stage}`), with an optional note glued to `}` that says\n // how to check it (`={coats the spoon}(a finger leaves a clean line)`).\n // Lexical, like `temperature`: `={ribbon} (prose)` keeps its parenthesis in\n // the prose. The state is words for the cook, never read by Gram. An empty\n // or unclosed `={` is a readable error, not prose. Since 1.5.0.\n checkpoint =\n | \"={\" checkpointState \"}\" preparation? -- full\n | \"=\" malformedBraces -- malformed\n checkpointState = (~(\"}\" | nl) any)+\n\n\n // Comments\n Comment = \"//\" (~nl any)*\n CommentBlock = \"/*\" (~\"*/\" any)* \"*/\"\n\n // Primitives\n name = (~(syntaxChar | nl) any)+\n declName = (~(syntaxChar | nl | \"~{\") any)+\n // A word made only of element sigils (`##`, `@@`, `#~`, `&&`) is no name:\n // the element falls back to text, like `@` or `#` alone, instead of\n // registering a tool or an ingredient called `#` (#221).\n singleWordName = ~(refSigil+ (wordStop | end)) (~wordStop any)+\n wordStop = syntaxChar | space | nl | sentencePunct\n sentencePunct = \",\" | \";\" | \"!\" | \"?\" | \".\"\n // Like name, but also stops at element sigils so a bare &dough is not consumed\n // into a Reference -- full when a sigil like # or @ appears later on the line.\n refName = (~(syntaxChar | refSigil | nl) any)+\n refSigil = \"@\" | \"#\" | \"~\" | \"^\" | \"&\"\n\n number = mixedFraction | unicodeFraction | plainNumber\n // \".\" or \",\" between two digits is a decimal separator (1.5, 1,5): Gram has\n // no thousands separator. A comma not between two digits ({1, 5 kg}) still\n // fails, so the commas of the prose around an element are never touched.\n plainNumber = digit+ ((\".\" | \",\") digit+)? (\"/\" digit+)?\n mixedFraction = digit+ sp+ digit+ \"/\" digit+\n unicodeFraction =\n | digit+ unicodeFractionChar -- mixed\n | unicodeFractionChar -- bare\n unicodeFractionChar = \"¼\" | \"½\" | \"¾\" | \"⅓\" | \"⅔\" | \"⅕\" | \"⅖\" | \"⅗\" | \"⅘\" | \"⅙\" | \"⅚\" | \"⅛\" | \"⅜\" | \"⅝\" | \"⅞\"\n range = number space* \"-\" space* number\n\n text = space* (~(elementStart | nl | \"|\") any)+\n\n // Lexical, like simpleIngredient and simpleCookware: as a syntactic rule\n // it skipped the blanks after `&`, so the `&` of prose (`Rock & roll.`,\n // `Salt & pepper{}`) took the next word as a reference. The name starts\n // right after the `&`, or the `&` is text.\n reference =\n | \"&\" ~space refName ingredientAmount -- full\n | \"&\" ~space refName malformedBraces -- malformed\n | \"&\" singleWordName -- bare\n\n // Delimiters that end a name (start of quantity/alias/preparation/composite/alternative).\n // @, #, ~, !, &, ?, * are deliberately absent here, so names may contain them freely --\n // only elementStart (below) treats those as starting a new element, and only in free text.\n // A `=` ends a name only before `{`, where a target state starts: without it a bare\n // `@salt until ={taste}` read an ingredient \"salt until =\" of unit \"taste\" (1.5.0).\n syntaxChar = \"={\" | \"{\" | \"}\" | \"[\" | \"]\" | \"(\" | \")\" | \"<\" | \"|\" | \":\"\n\n // Stricter than syntaxChar: used to detect where an element starts within free text.\n elementStart = \"@\" | \"#\" | \"~\" | \"^\" | \"={\" | \"//\" | \"/*\" | \"->&\" | \"&\"\n \n // The blank characters of Gram are exactly these. A line break is LF, CRLF\n // or a lone CR (old Mac files; the editor counts it as one too), and a\n // blank is a space or a tab: no other Unicode space (a no-break space is\n // French typography, a mid-file U+FEFF a character), so the formatter may\n // only ever strip `sp` and line breaks (packages/format, rules 10 and 12).\n nl = \"\\r\\n\" | \"\\n\" | \"\\r\"\n sp = \" \" | \"\\t\"\n space := sp\n bom = \"\\uFEFF\"\n}\n"; +export const grammarContent = "GRAM {\n // Blank lines may end the document whatever comes before them, nothing\n // included: \"\\n\" (an empty file once formatted), the blank line after a\n // frontmatter or after the last `@use`.\n // A byte order mark opening the file is an encoding signature, not content:\n // without `bom?`, `\\uFEFF## Prep` read its header as a step.\n Recipe = bom? Frontmatter? UseBlock? Content? nl*\n\n Content =\n | (nl* Block)* (nl* Section)+ -- explicit\n | (nl* Block)+ -- implicit\n\n Frontmatter = \"---\" nl KeyValue* \"---\" (nl | end)\n emptyLine = sp* nl\n KeyValue = emptyLine* key \":\" sp* value nl\n key = (alnum | \"_\" | \"-\")+\n value = (~nl any)*\n\n // Import directives, constrained between the frontmatter and the content --\n // this is what makes \"@use\" unambiguous with an ingredient literally named\n // \"use\" that happens to appear in a step (unchanged, still parses as such).\n // The block must open with a real `UseDirective`: a leading `UseComment` on\n // its own (no `@use` anywhere in the block) is deliberately NOT swallowed\n // here, so a document with no imports at all keeps treating its opening\n // comment as ordinary content, exactly as before this feature existed. Once\n // the block has started, a comment between two directives doesn't break it.\n UseBlock = nl* useDirective (nl* (useDirective | useComment))*\n // `end` too: without it, a comment closing a file with no final newline\n // fell out of the block and became the recipe's content, while the same\n // file with its newline (the formatter adds one) had none (#207).\n useComment = applySyntactic (nl | end)\n useDirective = \"@use\" sp+ moduleSpecifier sp+ \"as\" sp+ bindings sp* retroPlanning? sp* (nl | end)\n moduleSpecifier = \"\\\"\" (~(\"\\\"\" | nl) any)+ \"\\\"\"\n bindings =\n | \"{\" sp* binding moreBindings* sp* \"}\" -- named\n | binding -- default\n moreBindings = sp* \",\" sp* binding\n binding = \"&\" bindingName (sp+ \"as\" sp+ \"&\" bindingName)?\n bindingName =\n | bindingFullName \"{}\" -- full\n | bindingBareName -- bare\n // Unlike `name`, this must stop at \",\" and \"&\" -- a `{}`-delimited multi-word\n // binding sits inside a comma-separated list (`{ &a, &b multi{} }`) and can be\n // followed by a rename (`&a as &b multi{}`), so it must not swallow past the\n // next binding's separator or sigil while scanning ahead for its own \"{}\".\n bindingFullName = (~bindingFullNameStop any)+\n bindingFullNameStop = syntaxChar | nl | \",\" | refSigil\n bindingBareName = (~bindingStop any)+\n bindingStop = space | nl | syntaxChar | sentencePunct | \"~{\"\n\n Section = header Block*\n header =\n | \"##\" sp+ title headerExtension? sp* (lineEnd | end) -- ok\n | \"##\" sp+ title headerExtension sp* headerTrailing (lineEnd | end) -- trailing\n // `##` alone is an untitled header, like `## `: the formatter strips\n // the blank after it (rule 10), and `##` read as text + a cookware\n // named \"#\" made the section vanish on format (#205).\n | \"##\" sp* (lineEnd | end) -- empty\n // Text left after a header's `~{...}` / `->&name` (most often the second\n // word of a multi-word intermediate written without `{}`). Without this\n // branch the whole `##` line silently fell back to a step: the section\n // vanished, or its `~{-1d}` anchor surfaced as a misleading timer error.\n // Matched only to raise a readable error (see `header_trailing`).\n headerTrailing = (~nl any)+\n headerExtension = \n | retroPlanning sp* intermediateDecl? -- retro\n | intermediateDecl sp* retroPlanning? -- decl\n titleStop = nl | \"->&\" | \"~{\"\n title = (~titleStop any)*\n \n // On one line, like every element but a block comment: an unclosed brace\n // never reaches into the next line (#216). Empty braces too, like a\n // timer's: the formatter trims `~{ }` to `~{}`, which used to stop being\n // an anchor and drop the section on format (#205).\n retroPlanning = \"~{\" (~(\"}\" | nl) any)* \"}\"\n \n Block = \n | Comment nl* -- comment\n | (~header step) -- step\n \n // A line holding only blanks (`sp`) is a blank line, so it ends the step\n // just like an empty one: the formatter strips those blanks (rule 10), and\n // reading the line as more step text made formatting split the step.\n step = startAction? line (nl ~blankLine line)* (lineEnd | end)\n blankLine = sp* (nl | end)\n // A line break and the blank lines after it, blanks included: inside a\n // section nothing between two blocks skips them (`Block*`).\n lineEnd = nl (sp* nl)*\n // On one line: the action's text kept the source line break (`[Mix\\r\\nwell]`),\n // which formatting writes as LF, so the compiled recipe changed (#216).\n startAction = \"[\" (~(\"]\" | nl) any)+ \"]\" sp*\n line = stepContent+\n stepContent =\n | invalidUseDirective\n | invalidComposite\n | invalidAlternativeBar\n | text\n | ws\n | intermediateDecl\n | applySyntactic\n | fallback\n\n // A `@use \"...\"` past the import block (after the first step, misspelled,\n // or otherwise misplaced) would otherwise silently parse as an ingredient\n // literally named \"use\" followed by prose -- this turns it into a readable\n // error instead. Only triggers on the exact `@use \"` prefix, so an actual\n // ingredient named \"use\" followed by unrelated quoted text is unaffected.\n invalidUseDirective = \"@use\" sp+ \"\\\"\"\n\n // Only reached when nothing before the blanks took them: a continuation line\n // opening on ` <@b`, or a lone `@` before ` <@parent`. After an ingredient\n // (`@zest{1} < @lemon{2}`) the blanks are already read, the line parses as\n // two ingredients and kitchen raises SPACED_COMPOSITE instead.\n invalidComposite = space+ \"<\" space* \"@\" name\n\n invalidAlternativeBar = \"|\"\n\n ws = space+\n\n // A run of sigils with no name falls back in one piece, but for its last\n // sigil, which may still start an element (`@~{10 min}`: a timer). One\n // character at a time, each `@` of `@@@…` read the whole run again to\n // learn it has no name (singleWordName, #221): quadratic.\n fallback = sigilRun | ~nl any\n sigilRun = (refSigil &refSigil)+\n\n Element = \n | Ingredient\n | Cookware\n | Timer\n | temperature\n | checkpoint\n | reference\n | CommentBlock\n | Comment\n\n // A full name stops at `~{`, like a title: `->&dough ~{}` declares\n // `dough` before an empty anchor, not a \"dough ~\" (#205).\n intermediateDecl =\n | \"->&\" declName \"{}\" -- full\n | \"->&\" singleWordName -- bare\n\n // Ingredients\n Ingredient = \n | Alternative\n | simpleIngredient\n\n Alternative = simpleIngredient (\"|\" simpleIngredient)+\n \n // Rule: Quantity is mandatory unless it's a single word name\n // Uses refName (not name) so a bare @&chicken mention can't have its name\n // greedily swallow everything up to an unrelated later {...} that happens\n // to close a valid ingredientAmount -- e.g. \"@&chicken for ~{3min}\" must\n // stop at \"~\" and fall back to the bare alternative, not consume \"chicken\n // for ~\" as a bogus multi-word name with the timer's quantity attached.\n simpleIngredient =\n | \"@\" modifier* refName alias? ingredientAmount preparation? composite? -- full\n | \"@\" modifier* refName alias? malformedBraces -- malformed\n | \"@\" modifier* singleWordName alias? preparation? composite? -- bare\n\n modifier = \"?\" | \"-\" | \"*\" | \"&\" | \"=\"\n // The alias starts right after the `:`, with no blank (`@dry white\n // wine:wine{10ml}`). A `:` followed by a blank is punctuation: `Heat the\n // #pan: then add oil.` read the rest of the line as the alias of `pan` and\n // it vanished from the step (#273). It also covers `@salt: ` at the end of\n // a line, which took the blanks as an empty alias (#281).\n alias = \":\" ~sp refName\n ingredientQuantity = \"{\" space* (relativeQuantity | absoluteQuantity) space* \"}\"\n // The amount of an ingredient, a composite parent or a reference: an\n // ingredientQuantity, or a sum of quantities (`{1 cup + 1 tbsp}`,\n // `{1 cup - 2 tbsp}`). Since 1.5.0. Timers and temperatures keep\n // ingredientQuantity. PEG order matters: a choice that matches a prefix is\n // final, so a plain quantity is only taken when the braces close right\n // after it (`&`), otherwise it would take `1 cup` from `{1 cup + 1 tbsp}`\n // and fail on the `+`. Tried before the sum, it also keeps its range\n // (`{1 - 2 cup}` is one range, not 1 minus 2 cups) and its AST.\n ingredientAmount = \"{\" space* (ratioQuantity | relativeQuantity | closedQuantity | compoundQuantity) space* \"}\"\n closedQuantity = absoluteQuantity &(space* \"}\")\n compoundQuantity = quantityTerm (space* compoundOp space* quantityTerm)+\n // The unit is optional so `{1 + 1 cup}` reaches the compiler, which says\n // what is wrong with it, instead of failing as a syntax error.\n quantityTerm = (range | number) (space* unit)?\n compoundOp = \"+\" | \"-\"\n relativeQuantity = number space* \"%\" space* (\"@&\" | \"&\") space* name\n // A ratio with units (`1 / 100 g @&farine`, `15 g / L @&eau`, `1 / @&côtelette`):\n // an amount per amount of a target. A fraction glued to a slash stays a\n // fraction (`plainNumber` takes `1/100`), so `{1/100g @&farine}` and\n // `{1/2 @&farine}` fail here and end as malformedBraces: a ratio needs a\n // space on one side of its slash at least. Since 1.5.0.\n ratioQuantity = ratioTerm space* \"/\" space* ratioDenominator? space* targetRef\n ratioTerm = (range | number) (space* unit)?\n ratioDenominator =\n | number (space* unit)? -- amount\n | unit -- unit\n // Stops at `*` and `×` so a cycle multiplier can follow a ratio later on.\n targetRef = (\"@&\" | \"&\") space* ratioTargetName\n ratioTargetName = (~(syntaxChar | \"*\" | \"×\" | nl) any)+\n absoluteQuantity = (range | number)? space* (unit space*)?\n // On one line, like timerText (#216).\n textQuantity = \"{\" space* (~(\"}\" | nl) any)+ space* \"}\"\n fixed = \"=\"\n // A unit is one or more words. A word may contain \".\" or an apostrophe after\n // its first character (c.à.s, fl. oz., d'eau) but never starts with one, so a\n // stray \"{1. kg}\" or \"{.5 g}\" is still rejected rather than half-parsed.\n unit = unitName\n unitName = unitWord (sp+ unitWord)*\n unitWord = unitLead unitChar*\n unitLead = alnum | \"°\" | \"%\"\n unitChar = unitLead | \".\" | \"'\" | \"’\"\n\n // A \"{...}\" glued to an element that did not parse as a valid quantity. Without\n // this, the element silently fell back to its bare form (name truncated to its\n // first word) and the braces leaked into prose -- merging distinct ingredients.\n // Each \"-- malformed\" branch below turns that into a readable error instead.\n malformedBraces = \"{\" (~(\"}\" | nl) any)* (\"}\" | &nl | end)\n // The parenthesis glued to an element: an ingredient's or a tool's\n // preparation, a composite parent's, a temperature's or a target state's\n // note. Every rule using it is lexical, so it touches what comes before it.\n // On one line: an unclosed `(` is prose, never the start\n // of a preparation that would run to the next `)` further down the recipe,\n // over blank lines and section headers.\n preparation = \"(\" (~(\")\" | nl) any)* \")\"\n // `modifier*` mirrors simpleIngredient: a composite parent is an ingredient\n // reference like any other, and authors (and AI importers) write `<@&parent`\n // to mark a parent already introduced earlier. Without it, `refName` rejected\n // the leading \"&\" (it is a refSigil), the `bare` branch fell through to\n // `singleWordName` -- which does allow \"&\" -- and a multi-word parent silently\n // truncated at the first space, registering a phantom ingredient literally\n // named \"&citron\" alongside the real one. The modifiers are parsed and then\n // ignored (see composite_full/composite_bare): \"&\" is redundant on a parent\n // because the MAX rule already collapses repeat draws into one purchase.\n composite =\n | \"<@\" modifier* refName ingredientAmount preparation? -- full\n | \"<@\" modifier* refName malformedBraces -- malformed\n | \"<@\" modifier* singleWordName preparation? -- bare\n\n // Cookware\n Cookware =\n | CookwareAlternative\n | simpleCookware\n\n CookwareAlternative = simpleCookware (\"|\" simpleCookware)+\n // Same refName fix as simpleIngredient above -- a bare #pan mention must not\n // swallow an unrelated later {...} (e.g. another ingredient's integer-only\n // quantity) into its own name.\n simpleCookware =\n | \"#\" modifier* refName alias? cookwareQuantity preparation? -- full\n | \"#\" modifier* refName alias? malformedBraces -- malformed\n | \"#\" modifier* singleWordName alias? preparation? -- bare\n\n // Cookware quantity is numbers only, no units (e.g. {}, {2}) -- unlike ingredientQuantity.\n cookwareQuantity = \"{\" space* number? space* \"}\"\n\n // Timer\n // `ingredientQuantity` comes first (PEG order) so a plain timer keeps its\n // AST: `~{10 min}`, and also `~{1h30}`, read as 1 + unit \"h30\". Anything\n // else closed on the same line (`1:30 h`, `5'30\"`, `1h + 30min`, `1h30-2h`)\n // is kept as text. Either way the AST carries `raw`, the text between the\n // braces, and the compiler reads the duration from it (`parseDuration` in\n // @gram-lang/i18n), never from the quantity. Only an unclosed brace is\n // still a syntax error.\n //\n // A proportional time (`~{15 min / 500 g @&roti}`) is tried first: its\n // numerator is read by parseDuration like any timer (`1:30 h`, `5'30\"`).\n // Since 1.5.0.\n Timer =\n | \"~\" \"_\"? name? timerRatio -- ratio\n | \"~\" \"_\"? name? ingredientQuantity -- full\n | \"~\" \"_\"? name? timerText -- text\n | \"~\" \"_\"? name? malformedBraces -- malformed\n timerText = \"{\" (~(\"}\" | nl) any)* \"}\"\n timerRatio = \"{\" space* timerRatioDuration space* \"/\" space* ratioDenominator? space* targetRef space* \"}\"\n timerRatioDuration = (number | (~(\"/\" | \"*\" | \"×\" | \"}\" | nl) any))+\n \n // Temperature\n // Lexical, so only a note glued to `}` is one: `^{180°C}(fan)` has a note,\n // `^{180°C} (preheated)` keeps its parenthesis in the prose. `name` may\n // start with a space, as it could when the rule was syntactic: `^ {180°C}`\n // and `^oven {180°C}` read as before (`clean` drops the space). The note\n // since 1.5.0.\n temperature = \"^\" name? (ingredientQuantity | textQuantity) preparation?\n\n // Target state (a checkpoint in the AST): the state that ends a step\n // (`until ={ribbon stage}`), with an optional note glued to `}` that says\n // how to check it (`={coats the spoon}(a finger leaves a clean line)`).\n // Lexical, like `temperature`: `={ribbon} (prose)` keeps its parenthesis in\n // the prose. The state is words for the cook, never read by Gram. An empty\n // or unclosed `={` is a readable error, not prose. Since 1.5.0.\n checkpoint =\n | \"={\" checkpointState \"}\" preparation? -- full\n | \"=\" malformedBraces -- malformed\n checkpointState = (~(\"}\" | nl) any)+\n\n\n // Comments\n Comment = \"//\" (~nl any)*\n CommentBlock = \"/*\" (~\"*/\" any)* \"*/\"\n\n // Primitives\n name = (~(syntaxChar | nl) any)+\n declName = (~(syntaxChar | nl | \"~{\") any)+\n // A word made only of element sigils (`##`, `@@`, `#~`, `&&`) is no name:\n // the element falls back to text, like `@` or `#` alone, instead of\n // registering a tool or an ingredient called `#` (#221).\n singleWordName = ~(refSigil+ (wordStop | end)) (~wordStop any)+\n wordStop = syntaxChar | space | nl | sentencePunct\n sentencePunct = \",\" | \";\" | \"!\" | \"?\" | \".\"\n // Like name, but also stops at element sigils so a bare &dough is not consumed\n // into a Reference -- full when a sigil like # or @ appears later on the line.\n refName = (~(syntaxChar | refSigil | nl) any)+\n refSigil = \"@\" | \"#\" | \"~\" | \"^\" | \"&\"\n\n number = mixedFraction | unicodeFraction | plainNumber\n // \".\" or \",\" between two digits is a decimal separator (1.5, 1,5): Gram has\n // no thousands separator. A comma not between two digits ({1, 5 kg}) still\n // fails, so the commas of the prose around an element are never touched.\n plainNumber = digit+ ((\".\" | \",\") digit+)? (\"/\" digit+)?\n mixedFraction = digit+ sp+ digit+ \"/\" digit+\n unicodeFraction =\n | digit+ unicodeFractionChar -- mixed\n | unicodeFractionChar -- bare\n unicodeFractionChar = \"¼\" | \"½\" | \"¾\" | \"⅓\" | \"⅔\" | \"⅕\" | \"⅖\" | \"⅗\" | \"⅘\" | \"⅙\" | \"⅚\" | \"⅛\" | \"⅜\" | \"⅝\" | \"⅞\"\n range = number space* \"-\" space* number\n\n text = space* (~(elementStart | nl | \"|\") any)+\n\n // Lexical, like simpleIngredient and simpleCookware: as a syntactic rule\n // it skipped the blanks after `&`, so the `&` of prose (`Rock & roll.`,\n // `Salt & pepper{}`) took the next word as a reference. The name starts\n // right after the `&`, or the `&` is text.\n reference =\n | \"&\" ~space refName ingredientAmount -- full\n | \"&\" ~space refName malformedBraces -- malformed\n | \"&\" singleWordName -- bare\n\n // Delimiters that end a name (start of quantity/alias/preparation/composite/alternative).\n // @, #, ~, !, &, ?, * are deliberately absent here, so names may contain them freely --\n // only elementStart (below) treats those as starting a new element, and only in free text.\n // A `=` ends a name only before `{`, where a target state starts: without it a bare\n // `@salt until ={taste}` read an ingredient \"salt until =\" of unit \"taste\" (1.5.0).\n syntaxChar = \"={\" | \"{\" | \"}\" | \"[\" | \"]\" | \"(\" | \")\" | \"<\" | \"|\" | \":\"\n\n // Stricter than syntaxChar: used to detect where an element starts within free text.\n elementStart = \"@\" | \"#\" | \"~\" | \"^\" | \"={\" | \"//\" | \"/*\" | \"->&\" | \"&\"\n \n // The blank characters of Gram are exactly these. A line break is LF, CRLF\n // or a lone CR (old Mac files; the editor counts it as one too), and a\n // blank is a space or a tab: no other Unicode space (a no-break space is\n // French typography, a mid-file U+FEFF a character), so the formatter may\n // only ever strip `sp` and line breaks (packages/format, rules 10 and 12).\n nl = \"\\r\\n\" | \"\\n\" | \"\\r\"\n sp = \" \" | \"\\t\"\n space := sp\n bom = \"\\uFEFF\"\n}\n"; diff --git a/packages/parser/tests/grammar-edge-cases.test.ts b/packages/parser/tests/grammar-edge-cases.test.ts index b1882bde..b7ec2eb2 100644 --- a/packages/parser/tests/grammar-edge-cases.test.ts +++ b/packages/parser/tests/grammar-edge-cases.test.ts @@ -976,14 +976,61 @@ describe("a colon followed by blanks alone is no alias", () => { ]); }); - it("still reads a real alias, with or without a blank after the colon", () => { + it("still reads a real alias, glued to the colon", () => { expect(step("With @dry white wine:wine{100ml}.")[1]).toEqual({ name: "dry white wine", alias: "wine", }); - expect(step("Add @salt: fleur de sel.")[1]).toEqual({ + expect(step("Use the #cast iron skillet:skillet{}.")[1]).toEqual({ + name: "cast iron skillet", + alias: "skillet", + }); + expect(step("Add @salt:fleur de sel.")[1]).toEqual({ name: "salt", alias: "fleur de sel.", }); }); }); + +// #273: `alias = ":" refName` also took a name starting with a blank, so a `:` +// written as punctuation after a bare mention read the rest of the line as +// its alias, and that text vanished from the step. The alias now starts right +// after the colon, or the colon is text. +describe("a colon followed by a blank is punctuation, not an alias", () => { + const step = (source: string) => + (getAST(source).children[0] as any).children.map((c: any) => + c.type === ASTNodeType.Ingredient || c.type === ASTNodeType.Cookware + ? { name: c.name, alias: c.alias } + : c.value, + ); + + it("keeps the rest of the line after a bare #cookware", () => { + expect(step("Heat the #pan: then add oil.")).toEqual([ + "Heat the ", + { name: "pan", alias: null }, + ": then add oil.", + ]); + }); + + it("keeps the rest of the line after a bare @ingredient", () => { + expect(step("Add @flour: sifted.")).toEqual([ + "Add ", + { name: "flour", alias: null }, + ": sifted.", + ]); + }); + + it("keeps it after a tab too", () => { + expect(step("Heat the #pan:\tthen add oil.")).toEqual([ + "Heat the ", + { name: "pan", alias: null }, + ":\tthen add oil.", + ]); + }); + + it("leaves a colon after braces as text, as before", () => { + expect(step("Mix @flour{200g}: then rest.").slice(2)).toEqual([ + ": then rest.", + ]); + }); +});