From 4608f9682369dd0ddbe692ba8911059624bb9e21 Mon Sep 17 00:00:00 2001 From: abiwab Date: Fri, 13 Nov 2026 14:23:28 +0100 Subject: [PATCH] fix(parser): report leftover text in section headers instead of dropping the section --- .changeset/section-header-leftover-text.md | 8 +++ .../error.json | 7 +++ .../input.gram | 7 +++ packages/parser/grammar.ohm | 10 ++- packages/parser/src/grammar-content.ts | 2 +- packages/parser/src/index.ts | 23 ++++++- .../parser/tests/grammar-edge-cases.test.ts | 63 +++++++++++++++++++ 7 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 .changeset/section-header-leftover-text.md create mode 100644 conformance/cases/err-014-multiword-intermediate-in-header/error.json create mode 100644 conformance/cases/err-014-multiword-intermediate-in-header/input.gram diff --git a/.changeset/section-header-leftover-text.md b/.changeset/section-header-leftover-text.md new file mode 100644 index 00000000..fabe5449 --- /dev/null +++ b/.changeset/section-header-leftover-text.md @@ -0,0 +1,8 @@ +--- +"@gram-lang/parser": patch +--- + +**Parser**: A section header with text left after its anchor or intermediate now raises a clear error, instead of losing the section without a word or blaming the anchor: + - `## Garnish ~{-10h} ->&glazed rhubarb` now asks for the braces a multi-word intermediate needs (`->&glazed rhubarb{}`), instead of reporting "Invalid quantity '{-10h}' for timer". + - Without an anchor, the same header used to turn silently into a step, so the section vanished from the recipe. + - A section header written on the very last line of a file, with no final line break, is now read as a header too. diff --git a/conformance/cases/err-014-multiword-intermediate-in-header/error.json b/conformance/cases/err-014-multiword-intermediate-in-header/error.json new file mode 100644 index 00000000..81a03bf4 --- /dev/null +++ b/conformance/cases/err-014-multiword-intermediate-in-header/error.json @@ -0,0 +1,7 @@ +{ + "message": "Gram Syntax Error: Intermediate name 'rhubarbe laquée' in a section header has several words and must end with braces, e.g. ->&rhubarbe laquée{}.", + "offset": 30, + "expected": "a multi-word intermediate name ending with braces, e.g. ->&rhubarbe laquée{}", + "code": null, + "file": null +} diff --git a/conformance/cases/err-014-multiword-intermediate-in-header/input.gram b/conformance/cases/err-014-multiword-intermediate-in-header/input.gram new file mode 100644 index 00000000..0de9c281 --- /dev/null +++ b/conformance/cases/err-014-multiword-intermediate-in-header/input.gram @@ -0,0 +1,7 @@ +## Garniture rhubarbe ~{-10h} ->&rhubarbe laquée + +Couper la @rhubarbe{500g} en tronçons. + +## Montage + +Disposer la &rhubarbe laquée{} sur la pâte. diff --git a/packages/parser/grammar.ohm b/packages/parser/grammar.ohm index fe31cb2b..c688fdfb 100644 --- a/packages/parser/grammar.ohm +++ b/packages/parser/grammar.ohm @@ -41,7 +41,15 @@ GRAM { bindingStop = space | nl | syntaxChar | sentencePunct | "~{" Section = header Block* - header = "##" sp+ title headerExtension? sp* nl+ + header = + | "##" sp+ title headerExtension? sp* (nl+ | end) -- ok + | "##" sp+ title headerExtension sp* headerTrailing (nl+ | end) -- trailing + // 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 diff --git a/packages/parser/src/grammar-content.ts b/packages/parser/src/grammar-content.ts index 89cce5d7..99786f5a 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 = \"##\" sp+ title headerExtension? sp* nl+\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 | 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 ingredientQuantity -- 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? ingredientQuantity 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 relativeQuantity = number space* \"%\" space* (\"@&\" | \"&\") space* name\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 preparation = \"(\" (~\")\" 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 ingredientQuantity 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 Timer =\n | \"~\" \"_\"? name? ingredientQuantity -- full\n | \"~\" \"_\"? name? malformedBraces -- malformed\n \n // Temperature\n Temperature = \"^\" name? (ingredientQuantity | textQuantity)\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 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 ingredientQuantity -- 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 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 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 | 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 ingredientQuantity -- 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? ingredientQuantity 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 relativeQuantity = number space* \"%\" space* (\"@&\" | \"&\") space* name\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 preparation = \"(\" (~\")\" 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 ingredientQuantity 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 Timer =\n | \"~\" \"_\"? name? ingredientQuantity -- full\n | \"~\" \"_\"? name? malformedBraces -- malformed\n \n // Temperature\n Temperature = \"^\" name? (ingredientQuantity | textQuantity)\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 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 ingredientQuantity -- 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 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 f6a2db30..8deff0e0 100644 --- a/packages/parser/src/index.ts +++ b/packages/parser/src/index.ts @@ -219,7 +219,28 @@ semantics.addOperation("toAST", { }; }, - header(_1, _2, title, extension, _3, _4): HeaderResult { + header_trailing(_1, _2, _title, extension, _sp, trailing, _end): never { + const text = trailing.sourceString.trimEnd(); + // `->&rhubarbe laquée`: the bare form keeps one word, so the next word + // lands here. Point at the braces rather than at the leftover text. + const bareDecl = extension.sourceString.trimEnd().match(/->&([^\s{}]+)$/); + const nextWords = (text.split("~{")[0] ?? "").trim(); + if (bareDecl && /^[\p{L}\p{N}]/u.test(nextWords)) { + const example = `->&${bareDecl[1]} ${nextWords}{}`; + throw new GramParseError( + `Gram Syntax Error: Intermediate name '${bareDecl[1]} ${nextWords}' in a section header has several words and must end with braces, e.g. ${example}.`, + extension.source.startIdx + (bareDecl.index ?? 0), + `a multi-word intermediate name ending with braces, e.g. ${example}`, + ); + } + throw new GramParseError( + `Gram Syntax Error: Unexpected text '${text}' in a section header. A header ends with its anchor '~{...}' and its intermediate '->&name', with nothing after them.`, + trailing.source.startIdx, + "the end of the section header", + ); + }, + + header_ok(_1, _2, title, extension, _3, _4): HeaderResult { let retroPlanning = null; let intermediateDecl = null; diff --git a/packages/parser/tests/grammar-edge-cases.test.ts b/packages/parser/tests/grammar-edge-cases.test.ts index b313b5a4..98e32b23 100644 --- a/packages/parser/tests/grammar-edge-cases.test.ts +++ b/packages/parser/tests/grammar-edge-cases.test.ts @@ -353,6 +353,69 @@ describe("section retro-planning", () => { }); }); +describe("text left after a section header's anchor / intermediate", () => { + // Before 1.4.1 any text after `~{...}` / `->&name` made the header rule fail: + // the `##` line fell back to a step, so the section vanished silently, or its + // `~{-10h}` anchor surfaced as a misleading "Invalid quantity for timer". + function parseError(source: string): GramParseError { + try { + getAST(source); + } catch (e) { + expect(e).toBeInstanceOf(GramParseError); + return e as GramParseError; + } + throw new Error("expected a GramParseError"); + } + + const MULTI_WORD = + /Intermediate name 'rhubarbe laquée' .* ->&rhubarbe laquée\{\}/; + + it.each([ + ["anchor first", "## Garniture ~{-10h} ->&rhubarbe laquée\n\nStep.\n", 21], + ["anchor last", "## Garniture ->&rhubarbe laquée ~{-10h}\n\nStep.\n", 13], + ["no anchor", "## Garniture ->&rhubarbe laquée\n\nStep.\n", 13], + ["end of file", "## Garniture ->&rhubarbe laquée", 13], + ])("asks for braces on a multi-word intermediate (%s)", (_label, source, offset) => { + const err = parseError(source); + expect(err.message).toMatch(MULTI_WORD); + expect(err.offset).toBe(offset); + }); + + it.each([ + [ + "text after the anchor", + "## Garniture ~{-10h} au frais\n\nStep.\n", + "au frais", + ], + ["two intermediates", "## Garniture ->&a ->&b\n\nStep.\n", "->&b"], + ])("rejects any other leftover text (%s)", (_label, source, leftover) => { + expect(parseError(source).message).toContain( + `Unexpected text '${leftover}' in a section header`, + ); + }); + + it("still accepts braces, trailing spaces and either order", () => { + for (const header of [ + "## Garniture ->&rhubarbe laquée{} ~{-10h}", + "## Garniture ~{-10h} ->&rhubarbe laquée{} ", + ]) { + const section = getAST(`${header}\n\nStep.\n`).children[0] as any; + expect(section.type).toBe(ASTNodeType.Section); + expect(section.retroPlanning.raw).toBe("-10h"); + expect(section.intermediateDecl.name).toBe("rhubarbe laquée"); + } + }); + + it("keeps a header written on the last line, without a final newline", () => { + const section = getAST("Step.\n\n## Mousse ->&mousse ~{-1d}").children.at( + -1, + ) as any; + expect(section.type).toBe(ASTNodeType.Section); + expect(section.retroPlanning.raw).toBe("-1d"); + expect(section.intermediateDecl.name).toBe("mousse"); + }); +}); + describe("known hard error", () => { it("throws a descriptive syntax error for a space before the composite `<` sigil", () => { expect(() => getAST("## Section\n@ <@parent\n")).toThrow(/composite/i); -- 2.54.0