From eab1e483fe88e559288d3003d493bbc0ec4ecf53 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 2 Nov 2026 06:48:07 -0800 Subject: [PATCH] fix: avoid quadratic scan for unmatched emphasis delimiters (#4103) * fix: avoid quadratic scan for unmatched emphasis delimiters Tokenizer.emStrong and del walked every later delimiter for each unmatched opener, so parse time grew ~4x when those inputs doubled. Cache the last possible closer on maskedSrc and skip the scan when none remains after the opener. Fixes #4099 Co-authored-by: David * fix: keep emphasis closer hints on the inline pass Address review on the unmatched-delimiter scan: remove the timing unit tests, cover mid-run openers in test/specs/new, name the emphasis and strikethrough closer indexes, and drop the module-level maskedSrc cache. Co-authored-by: David * refactor: scan unmatched emphasis closers in internal helpers Tokenizer no longer gains public methods. The last-closer scan still runs once per inline pass and the hint stack is dropped when that pass ends, so the masked source is not retained. Co-authored-by: David --------- Co-authored-by: David <244863912+dyk1454683243-sudo@users.noreply.github.com> Co-authored-by: David Co-authored-by: Cursor Agent --- src/Lexer.ts | 14 +- src/Tokenizer.ts | 19 ++- src/helpers.ts | 123 ++++++++++++++++++ test/specs/new/em_strong_mid_run_opener.html | 5 + test/specs/new/em_strong_mid_run_opener.md | 5 + .../redos/quadratic_unmatched_emphasis.cjs | 21 +++ 6 files changed, 182 insertions(+), 5 deletions(-) create mode 100644 test/specs/new/em_strong_mid_run_opener.html create mode 100644 test/specs/new/em_strong_mid_run_opener.md create mode 100644 test/specs/redos/quadratic_unmatched_emphasis.cjs diff --git a/src/Lexer.ts b/src/Lexer.ts index 47ecefd1..eda38679 100644 --- a/src/Lexer.ts +++ b/src/Lexer.ts @@ -1,7 +1,7 @@ import { _Tokenizer } from './Tokenizer.ts'; import { _defaults } from './defaults.ts'; import { other, block, inline } from './rules.ts'; -import { normalizeLabel } from './helpers.ts'; +import { beginEmStrongDelCloserScan, endEmStrongDelCloserScan, normalizeLabel } from './helpers.ts'; import type { Token, TokensList, Tokens } from './Tokens.ts'; import type { MarkedOptions } from './MarkedOptions.ts'; @@ -382,6 +382,18 @@ export class _Lexer { ? this.#maskSrc(src) : src; + // One scan of this maskedSrc for the last emphasis, strong, and + // strikethrough closers, shared by every opener in the pass. Popped + // when the pass ends so the source is not retained (#4099). + beginEmStrongDelCloserScan(this.tokenizer, maskedSrc); + try { + return this.#tokenizeInlines(src, maskedSrc, tokens); + } finally { + endEmStrongDelCloserScan(this.tokenizer); + } + } + + #tokenizeInlines(src: string, maskedSrc: string, tokens: Token[]): Token[] { let keepPrevChar = false; let prevChar = ''; let srcLength = Infinity; diff --git a/src/Tokenizer.ts b/src/Tokenizer.ts index 26fcb34e..7ebc1926 100644 --- a/src/Tokenizer.ts +++ b/src/Tokenizer.ts @@ -7,6 +7,8 @@ import { normalizeLabel, decodeNumericCharacterReferences, trimTrailingBlankLines, + cachedLastPossibleEmStrongCloserIndex, + cachedLastPossibleDelCloserIndex, } from './helpers.ts'; import type { Rules } from './rules.ts'; import type { _Lexer } from './Lexer.ts'; @@ -906,13 +908,18 @@ export class _Tokenizer { const runLength = srcStart - runStart + lLength; const openerCanClose = !this.options.pedantic && !!runPrevChar.trim() && (!!nextChar || (delimChar === '*' && !runPrevPunct)); + if (delimChar !== '*' && delimChar !== '_') return; const endReg = delimChar === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; - endReg.lastIndex = 0; - + const lastPossibleEmStrongCloserIndex = cachedLastPossibleEmStrongCloserIndex(this, maskedSrc, delimChar); + const emStrongCloserWindowStart = maskedSrc.length - src.length + lLength; + if (lastPossibleEmStrongCloserIndex < emStrongCloserWindowStart) return; // Clip maskedSrc to same section of string as src (move to lexer?) maskedSrc = maskedSrc.slice(-1 * src.length + lLength); + const lastPossibleEmStrongCloserIndexInWindow = lastPossibleEmStrongCloserIndex - emStrongCloserWindowStart; + endReg.lastIndex = 0; while ((match = endReg.exec(maskedSrc)) !== null) { + if (match.index > lastPossibleEmStrongCloserIndexInWindow) break; rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; if (!rDelim) continue; // skip single * in __abc*abc__ @@ -1006,12 +1013,16 @@ export class _Tokenizer { let rDelim, rLength, delimTotal = lLength; const endReg = this.rules.inline.delRDelim; - endReg.lastIndex = 0; - + const lastPossibleDelCloserIndex = cachedLastPossibleDelCloserIndex(this, maskedSrc); + const delCloserWindowStart = maskedSrc.length - src.length + lLength; + if (lastPossibleDelCloserIndex < delCloserWindowStart) return; // Clip maskedSrc to same section of string as src maskedSrc = maskedSrc.slice(-1 * src.length + lLength); + const lastPossibleDelCloserIndexInWindow = lastPossibleDelCloserIndex - delCloserWindowStart; + endReg.lastIndex = 0; while ((match = endReg.exec(maskedSrc)) !== null) { + if (match.index > lastPossibleDelCloserIndexInWindow) break; rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; if (!rDelim) continue; diff --git a/src/helpers.ts b/src/helpers.ts index edfeaa69..49b38693 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -186,6 +186,129 @@ export function findClosingBracket(str: string, b: string) { return -1; } +interface LastPossibleEmStrongCloserIndex { + /** Last `*` run that can close emphasis or strong. `-1` if none. */ + '*': number; + /** Last `_` run that can close emphasis or strong. `-1` if none. */ + _: number; +} + +/** + * Closer hints for one inline `maskedSrc`. Held only while that pass runs. + */ +interface EmStrongDelCloserHintFrame { + maskedSrc: string; + lastPossibleEmStrongCloserIndex: LastPossibleEmStrongCloserIndex; + /** Last `~` run that can close strikethrough. `-1` if none. */ + lastPossibleDelCloserIndex: number; +} + +/** + * Hint stacks for inline passes currently running. Keyed by the tokenizer + * instance so parses do not share frames. Nested `inlineTokens` calls push + * a frame. The entry is removed when the outermost pass ends, so + * `maskedSrc` is not retained once parsing returns (#4099). + */ +const emStrongDelCloserHintStacks = new WeakMap(); + +/** + * Last indexes of `*` / `_` runs that can close emphasis or strong, and of + * a `~` run that can close strikethrough. + * + * A run can close only when it is not preceded by ASCII whitespace or the + * start of the string. The right-delim regexes accept a closer only in + * groups 1, 2, 5, and 6, and each of those requires that predecessor. When + * the opener's window has no such run, the regex scan cannot succeed. + * Finding one only means "keep looking": CommonMark rules 9–10 and mid-run + * openers are still applied in the loop (#4099). + */ +function scanLastPossibleEmStrongDelClosers(src: string): EmStrongDelCloserHintFrame { + const lastPossibleEmStrongCloserIndex: LastPossibleEmStrongCloserIndex = { '*': -1, _: -1 }; + let lastPossibleDelCloserIndex = -1; + const len = src.length; + for (let i = 0; i < len; i++) { + const ch = src[i]; + if (ch !== '*' && ch !== '_' && ch !== '~') { + continue; + } + // A leading run has no predecessor, same as one after a line break. + const prev = i === 0 ? '\n' : src[i - 1]; + let j = i + 1; + while (j < len && src[j] === ch) { + j++; + } + if (prev !== ' ' && prev !== '\t' && prev !== '\n' && prev !== '\r' && prev !== '\f') { + if (ch === '~') { + lastPossibleDelCloserIndex = i; + } else { + lastPossibleEmStrongCloserIndex[ch] = i; + } + } + i = j - 1; + } + return { + maskedSrc: src, + lastPossibleEmStrongCloserIndex, + lastPossibleDelCloserIndex, + }; +} + +/** + * Scan `maskedSrc` once for the last `*` / `_` run that can close emphasis + * or strong and the last `~` run that can close strikethrough. + * `endEmStrongDelCloserScan` drops this frame when the inline pass ends. + */ +export function beginEmStrongDelCloserScan(tokenizer: object, maskedSrc: string): void { + const frame = scanLastPossibleEmStrongDelClosers(maskedSrc); + const stack = emStrongDelCloserHintStacks.get(tokenizer); + if (stack) { + stack.push(frame); + } else { + emStrongDelCloserHintStacks.set(tokenizer, [frame]); + } +} + +/** + * Drop the closer-hint frame for the inline pass that just finished. + * Removing the last frame drops the tokenizer's `maskedSrc` reference. + */ +export function endEmStrongDelCloserScan(tokenizer: object): void { + const stack = emStrongDelCloserHintStacks.get(tokenizer); + if (!stack) { + return; + } + stack.pop(); + if (stack.length === 0) { + emStrongDelCloserHintStacks.delete(tokenizer); + } +} + +/** + * Index in `maskedSrc` of the last `*` or `_` run that can close emphasis + * or strong. Uses the active inline-pass scan when `maskedSrc` is that + * pass's source; otherwise scans this string and discards the result. + */ +export function cachedLastPossibleEmStrongCloserIndex(tokenizer: object, maskedSrc: string, delim: '*' | '_'): number { + const frame = emStrongDelCloserHintStacks.get(tokenizer)?.at(-1); + if (frame && frame.maskedSrc === maskedSrc) { + return frame.lastPossibleEmStrongCloserIndex[delim]; + } + return scanLastPossibleEmStrongDelClosers(maskedSrc).lastPossibleEmStrongCloserIndex[delim]; +} + +/** + * Index in `maskedSrc` of the last `~` run that can close strikethrough. + * Uses the active inline-pass scan when `maskedSrc` is that pass's + * source; otherwise scans this string and discards the result. + */ +export function cachedLastPossibleDelCloserIndex(tokenizer: object, maskedSrc: string): number { + const frame = emStrongDelCloserHintStacks.get(tokenizer)?.at(-1); + if (frame && frame.maskedSrc === maskedSrc) { + return frame.lastPossibleDelCloserIndex; + } + return scanLastPossibleEmStrongDelClosers(maskedSrc).lastPossibleDelCloserIndex; +} + export function expandTabs(line: string, indent = 0) { let col = indent; let expanded = ''; diff --git a/test/specs/new/em_strong_mid_run_opener.html b/test/specs/new/em_strong_mid_run_opener.html new file mode 100644 index 00000000..3f457e10 --- /dev/null +++ b/test/specs/new/em_strong_mid_run_opener.html @@ -0,0 +1,5 @@ +

**abc

+ +

foo**bar

+ +

*foo bar

diff --git a/test/specs/new/em_strong_mid_run_opener.md b/test/specs/new/em_strong_mid_run_opener.md new file mode 100644 index 00000000..bbc3fa15 --- /dev/null +++ b/test/specs/new/em_strong_mid_run_opener.md @@ -0,0 +1,5 @@ +**a*b*c + +*foo**bar* + +*foo *bar* diff --git a/test/specs/redos/quadratic_unmatched_emphasis.cjs b/test/specs/redos/quadratic_unmatched_emphasis.cjs new file mode 100644 index 00000000..bd2af931 --- /dev/null +++ b/test/specs/redos/quadratic_unmatched_emphasis.cjs @@ -0,0 +1,21 @@ +// Unmatched left-flanking emphasis / strikethrough delimiters. Before the +// last-closer early-exit, each opener walked every later delimiter +// (issue #4099). These sizes exceed the spec harness 1s budget on that path. +module.exports = [ + { + markdown: ('- *').repeat(2000), + html: `
    \n
  • ${'*- '.repeat(1999)}*
  • \n
\n`, + }, + { + markdown: ('+ _').repeat(2000), + html: `
    \n
  • ${'_+ '.repeat(1999)}_
  • \n
\n`, + }, + { + markdown: ('*x *x ').repeat(2000), + html: `

${'*x *x '.repeat(2000)}

\n`, + }, + { + markdown: ('~x ~x ').repeat(2000), + html: `

${'~x ~x '.repeat(2000)}

\n`, + }, +];