diff --git a/.changeset/parser-trailing-blank-lines.md b/.changeset/parser-trailing-blank-lines.md new file mode 100644 index 00000000..15067e31 --- /dev/null +++ b/.changeset/parser-trailing-blank-lines.md @@ -0,0 +1,5 @@ +--- +"@gram-lang/parser": patch +--- + +**Parser**: A file holding only blank lines, or only a frontmatter or `@use` lines followed by a blank line, now parses as an empty recipe instead of failing with a syntax error. Since formatting an empty file gives it a final newline, a new `.gram` file no longer shows an error in the editor after its first save. diff --git a/conformance/cases/055-blank-lines-only/analyzed.json b/conformance/cases/055-blank-lines-only/analyzed.json new file mode 100644 index 00000000..7e2a899f --- /dev/null +++ b/conformance/cases/055-blank-lines-only/analyzed.json @@ -0,0 +1,49 @@ +{ + "title": "Blank", + "slug": "blank", + "meta": { + "title": "Blank" + }, + "registry": { + "ingredients": {}, + "cookware": {} + }, + "shopping_list": [], + "cookware": [], + "sections": [], + "warnings": [], + "metrics": { + "totalTime": 0, + "idleTime": 0, + "activeTime": 0, + "preparationTime": 0, + "totalMass": 0, + "massStatus": "incomplete", + "missingMassIngredients": [], + "nutrition": { + "total": { + "calories": 0, + "fat": 0, + "carbs": 0, + "protein": 0 + }, + "isEstimate": false, + "coverage": 0 + } + }, + "miseEnPlace": [], + "tasks": { + "tasks": [], + "sections": [] + }, + "schedule": { + "miseEnPlace": "perSection", + "rests": "shortest", + "totalTime": 0, + "activeTime": 0, + "preparationTime": 0, + "idleTime": 0, + "blocks": [], + "days": [] + } +} diff --git a/conformance/cases/055-blank-lines-only/ast.json b/conformance/cases/055-blank-lines-only/ast.json new file mode 100644 index 00000000..20875989 --- /dev/null +++ b/conformance/cases/055-blank-lines-only/ast.json @@ -0,0 +1,8 @@ +{ + "type": "Recipe", + "meta": { + "title": "Blank" + }, + "imports": [], + "children": [] +} diff --git a/conformance/cases/055-blank-lines-only/compiled.json b/conformance/cases/055-blank-lines-only/compiled.json new file mode 100644 index 00000000..404a8164 --- /dev/null +++ b/conformance/cases/055-blank-lines-only/compiled.json @@ -0,0 +1,36 @@ +{ + "title": "Blank", + "slug": "blank", + "meta": { + "title": "Blank" + }, + "registry": { + "ingredients": {}, + "cookware": {} + }, + "shopping_list": [], + "cookware": [], + "sections": [], + "warnings": [], + "metrics": { + "totalTime": 0, + "idleTime": 0, + "activeTime": 0, + "preparationTime": 0 + }, + "miseEnPlace": [], + "tasks": { + "tasks": [], + "sections": [] + }, + "schedule": { + "miseEnPlace": "perSection", + "rests": "shortest", + "totalTime": 0, + "activeTime": 0, + "preparationTime": 0, + "idleTime": 0, + "blocks": [], + "days": [] + } +} diff --git a/conformance/cases/055-blank-lines-only/input.gram b/conformance/cases/055-blank-lines-only/input.gram new file mode 100644 index 00000000..497d6e0c --- /dev/null +++ b/conformance/cases/055-blank-lines-only/input.gram @@ -0,0 +1,5 @@ +--- +title: Blank +--- + + diff --git a/fuzz/known-failures.json b/fuzz/known-failures.json index bc0febe0..039ad045 100644 --- a/fuzz/known-failures.json +++ b/fuzz/known-failures.json @@ -59,12 +59,6 @@ "issue": "https://git.gram-lang.org/gram-lang/gram/issues/200", "example": "@\r" }, - { - "signature": "format-preserves-meaning | formatted source no longer parses | parser:getAST", - "invariant": "format-preserves-meaning", - "issue": "https://git.gram-lang.org/gram-lang/gram/issues/199", - "example": "" - }, { "signature": "format-preserves-meaning | compilation differs after formatting at $.meta", "invariant": "format-preserves-meaning", diff --git a/fuzz/regressions/199-blank-after-frontmatter.gram b/fuzz/regressions/199-blank-after-frontmatter.gram new file mode 100644 index 00000000..906fbdb3 --- /dev/null +++ b/fuzz/regressions/199-blank-after-frontmatter.gram @@ -0,0 +1,4 @@ +--- +title: x +--- + diff --git a/fuzz/regressions/199-empty-file.gram b/fuzz/regressions/199-empty-file.gram new file mode 100644 index 00000000..e69de29b diff --git a/packages/parser/grammar.ohm b/packages/parser/grammar.ohm index 74a87b93..3ab6745e 100644 --- a/packages/parser/grammar.ohm +++ b/packages/parser/grammar.ohm @@ -1,5 +1,8 @@ GRAM { - Recipe = Frontmatter? UseBlock? Content? + // 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`. + Recipe = Frontmatter? UseBlock? Content? nl* Content = | (nl* Block)* (nl* Section)+ -- explicit diff --git a/packages/parser/src/grammar-content.ts b/packages/parser/src/grammar-content.ts index 308c777b..c90f897b 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 Recipe = Frontmatter? UseBlock? Content?\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 useComment = applySyntactic nl\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* (nl+ | end) -- ok\n | \"##\" sp+ title headerExtension sp* headerTrailing (nl+ | end) -- trailing\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 retroPlanning = \"~{\" (~\"}\" any)+ \"}\"\n \n Block = \n | Comment nl* -- comment\n | (~header step) -- step\n \n step = startAction? line (nl line)* (nl+ | end)\n startAction = \"[\" (~\"]\" 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 invalidComposite = space+ \"<\" space* \"@\" name\n\n invalidAlternativeBar = \"|\"\n\n ws = space+\n\n fallback = ~nl any\n\n Element = \n | Ingredient\n | Cookware\n | Timer\n | temperature\n | checkpoint\n | Reference\n | CommentBlock\n | Comment\n\n intermediateDecl =\n | \"->&\" name \"{}\" -- 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 alias = \":\" 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 textQuantity = \"{\" space* (~\"}\" 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 singleWordName = (~(syntaxChar | space | nl | sentencePunct) any)+\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 Reference =\n | \"&\" refName ingredientAmount -- full\n | \"&\" 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 nl = \"\\r\"? \"\\n\"\n sp = \" \" | \"\\t\"\n space := sp\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 Recipe = 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 useComment = applySyntactic nl\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* (nl+ | end) -- ok\n | \"##\" sp+ title headerExtension sp* headerTrailing (nl+ | end) -- trailing\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 retroPlanning = \"~{\" (~\"}\" any)+ \"}\"\n \n Block = \n | Comment nl* -- comment\n | (~header step) -- step\n \n step = startAction? line (nl line)* (nl+ | end)\n startAction = \"[\" (~\"]\" 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 invalidComposite = space+ \"<\" space* \"@\" name\n\n invalidAlternativeBar = \"|\"\n\n ws = space+\n\n fallback = ~nl any\n\n Element = \n | Ingredient\n | Cookware\n | Timer\n | temperature\n | checkpoint\n | Reference\n | CommentBlock\n | Comment\n\n intermediateDecl =\n | \"->&\" name \"{}\" -- 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 alias = \":\" 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 textQuantity = \"{\" space* (~\"}\" 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 singleWordName = (~(syntaxChar | space | nl | sentencePunct) any)+\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 Reference =\n | \"&\" refName ingredientAmount -- full\n | \"&\" 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 nl = \"\\r\"? \"\\n\"\n sp = \" \" | \"\\t\"\n space := sp\n}\n"; diff --git a/packages/parser/src/index.ts b/packages/parser/src/index.ts index b742b232..7dc1af74 100644 --- a/packages/parser/src/index.ts +++ b/packages/parser/src/index.ts @@ -260,7 +260,7 @@ const semantics = grammar.createSemantics(); semantics.addOperation("toAST", { // --- Structure --- - Recipe(frontmatter, useBlock, content): RecipeAST { + Recipe(frontmatter, useBlock, content, _trailingBlankLines): RecipeAST { const rawMeta = getOpt(frontmatter) || {}; const metaResult = MetaSchema.safeParse(rawMeta); let meta: Meta; diff --git a/packages/parser/tests/grammar-edge-cases.test.ts b/packages/parser/tests/grammar-edge-cases.test.ts index 433da1ab..3dc9572c 100644 --- a/packages/parser/tests/grammar-edge-cases.test.ts +++ b/packages/parser/tests/grammar-edge-cases.test.ts @@ -858,3 +858,30 @@ describe("sums of quantities (since 1.5.0)", () => { expect(() => getAST(`## T\n\n${src}\n`)).toThrow(fragment); }); }); + +// #199: `formatGram("")` returns "\n", so an empty file must parse once +// formatted; and nothing but blank lines may follow a frontmatter or the +// last `@use`. +describe("blank lines with nothing after them", () => { + for (const source of ["\n", "\n\n", " \n", "\r\n"]) { + it(`parses ${JSON.stringify(source)} as an empty recipe`, () => { + expect(getAST(source)).toMatchObject({ children: [], imports: [] }); + }); + } + + it("parses a frontmatter followed by a blank line", () => { + const ast = getAST("---\ntitle: Bread\n---\n\n"); + expect(ast.meta).toEqual({ title: "Bread" }); + expect(ast.children).toEqual([]); + }); + + it("parses @use followed by a blank line", () => { + const ast = getAST('@use "./dough.gram" as &dough\n\n'); + expect(ast.imports).toHaveLength(1); + expect(ast.children).toEqual([]); + }); + + it("keeps the steps before trailing blank lines", () => { + expect(getAST("Mix.\n\nBake.\n\n\n").children).toHaveLength(2); + }); +});