From 4ee44f7f2167bec4079255e32b520dd47f16486c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C6=B0=C6=A1ng=20Ng=E1=BB=8Dc=20Anh?= Date: Wed, 30 Sep 2026 05:56:59 +0700 Subject: [PATCH] feat: add linkParenPossible to lexer state to fail fast for link token generation (#4070) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * perf: fast-fail link tokenizing when no ')' remains ahead The inline link rule backtracks quadratically over unterminated link sequences. '[a](b'.repeat(n) parses in O(n^2) — 97KB took ~2.5s — because at every '[' the regex's greedy unquoted-href run re-partitions the whole remainder while hunting for a closing ')' that never comes. Lexer.inlineTokens now anchors one paren scan per inline run (lastIndexOf(')') over the paragraph), and Tokenizer.link consults it: since every src it receives during the run is a suffix of that anchor, 'is there a ) ahead?' is O(1). When none remains the regex cannot match anyway, so skipping is semantics-preserving; anchors are saved/restored around nested runs (e.g. link labels) and live in a WeakMap so they stay off the public tokenizer API. Measured on Node 24: '[a](b'.repeat(20000) ~2500ms -> ~24ms '[a](b'.repeat(80000) (OOM-adjacent) -> ~60ms Differential check: 1506 generated documents (links with titles, balanced parens, angle destinations, images, autolinks, code spans, reflinks + defs, nested brackets, unterminated sequences) x gfm on/ off produce byte-identical output before and after the change. Adds test/specs/redos/quadratic_unterminated_links.cjs following the existing guard convention; it exceeds the redos budget on master and passes with this change. * refactor: one paren scan per inline run via lexer state Per review feedback: drop the WeakMap anchor machinery in favor of a single state flag. Lexer.inlineTokens scans for ')' once per run and stores it in state.linkParenPossible (same pattern as linkEmitted), restoring the previous value after nested runs. Tokenizer.link bails out only when the flag is false, which is exactly when its regex cannot match. This keeps the fast-fail while avoiding a repeated full-text includes() on reflink-heavy paragraphs, where attempting link() at every token would otherwise re-scan the remainder each time (quadratic_inline_masking[2]: ~1.03s vs ~144ms here, upstream ~140ms). * refactor: skip paren scan for nested runs when outer had no ')' When the outer inline run contains no ')' (linkParenPossible=false), a nested run's substring can't contain one either, so skip the redundant src.includes(')') scan. Addresses UziTech's observation on line 354: 'This also only needs to be checked if prevLinkParenPossible is true.' * make inner function private Co-authored-by: Steven * Change inlineTokensInner to private method call --------- Co-authored-by: Tony Brix Co-authored-by: Steven --- src/Lexer.ts | 25 +++++++++++++++++++ src/Tokenizer.ts | 9 +++++++ .../redos/quadratic_unterminated_links.cjs | 9 +++++++ 3 files changed, 43 insertions(+) create mode 100644 test/specs/redos/quadratic_unterminated_links.cjs diff --git a/src/Lexer.ts b/src/Lexer.ts index b7f20aaf..50b15d9a 100644 --- a/src/Lexer.ts +++ b/src/Lexer.ts @@ -16,6 +16,12 @@ export class _Lexer { inRawBlock: boolean; /** a link was produced in the inline run currently being scanned */ linkEmitted: boolean; + /** + * false while scanning an inline run whose source contains no ')', + * letting Tokenizer.link bail out before its quadratic backtracking. + * Anchored once per run by inlineTokens. + */ + linkParenPossible: boolean; top: boolean; }; @@ -37,6 +43,7 @@ export class _Lexer { inLink: false, inRawBlock: false, linkEmitted: false, + linkParenPossible: true, top: true, }; @@ -340,6 +347,24 @@ export class _Lexer { */ inlineTokens(src: string, tokens: Token[] = []): Token[] { this.tokenizer.lexer = this; + // One paren scan per inline run, shared with Tokenizer.link: without a + // ')' ahead the link regex cannot match, and skipping it avoids its + // quadratic backtracking over unterminated-link inputs like + // `'[a](b'.repeat(n)`. A nested run receives a substring of the outer + // run, so if the outer had no ')' neither does this substring — skip + // the scan in that case. + const prevLinkParenPossible = this.state.linkParenPossible; + this.state.linkParenPossible = prevLinkParenPossible && src.includes(')'); + try { + return this.#inlineTokensInner(src, tokens); + } finally { + // A nested run (e.g. a link label) anchored on its own substring; + // restore the outer run's flag for the rest of its loop. + this.state.linkParenPossible = prevLinkParenPossible; + } + } + + #inlineTokensInner(src: string, tokens: Token[]): Token[] { // String with links masked to avoid interference with em and strong let maskedSrc = src; diff --git a/src/Tokenizer.ts b/src/Tokenizer.ts index b0d0eeb7..baf4b021 100644 --- a/src/Tokenizer.ts +++ b/src/Tokenizer.ts @@ -732,6 +732,15 @@ export class _Tokenizer { } link(src: string): Tokens.Link | Tokens.Image | undefined { + // The link regex backtracks quadratically over unterminated-link inputs + // like '[a](b'.repeat(n): at every '[' its greedy unquoted-href run + // re-partitions the whole remainder while hunting for a ')' that never + // comes. inlineTokens anchors one paren scan per run in + // state.linkParenPossible; when it is false the regex cannot match, so + // bail out before running it. + if (this.lexer.state.linkParenPossible === false) { + return undefined; + } const cap = this.rules.inline.link.exec(src); if (cap) { const labelStart = cap[0].charAt(0) === '!' ? 2 : 1; diff --git a/test/specs/redos/quadratic_unterminated_links.cjs b/test/specs/redos/quadratic_unterminated_links.cjs new file mode 100644 index 00000000..dc40e3ad --- /dev/null +++ b/test/specs/redos/quadratic_unterminated_links.cjs @@ -0,0 +1,9 @@ +module.exports = [ + { + // Unterminated inline links: each '[' starts a link candidate whose + // href backtracking scanned the whole remainder before the paren-hint + // fast fail in Tokenizer.link landed. + markdown: '[a](b'.repeat(50000), + html: `

${'[a](b'.repeat(50000)}

`, + }, +];