feat: add linkParenPossible to lexer state to fail fast for link token generation (#4070)

* 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 <steven@ceriously.com>

* Change inlineTokensInner to private method call

---------

Co-authored-by: Tony Brix <tony@brix.ninja>
Co-authored-by: Steven <steven@ceriously.com>
This commit is contained in:
Dương Ngọc Anh
2026-09-29 16:56:59 -06:00
committed by GitHub
co-authored by Steven Tony Brix
parent c61543ed0f
commit 4ee44f7f21
3 changed files with 43 additions and 0 deletions
+25
View File
@@ -16,6 +16,12 @@ export class _Lexer<ParserOutput = string, RendererOutput = string> {
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<ParserOutput = string, RendererOutput = string> {
inLink: false,
inRawBlock: false,
linkEmitted: false,
linkParenPossible: true,
top: true,
};
@@ -340,6 +347,24 @@ export class _Lexer<ParserOutput = string, RendererOutput = string> {
*/
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;
+9
View File
@@ -732,6 +732,15 @@ export class _Tokenizer<ParserOutput = string, RendererOutput = string> {
}
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;
@@ -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: `<p>${'[a](b'.repeat(50000)}</p>`,
},
];