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 <dyk1454683243-sudo@users.noreply.github.com>

* 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 <dyk1454683243-sudo@users.noreply.github.com>

* 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 <dyk1454683243-sudo@users.noreply.github.com>

---------

Co-authored-by: David <244863912+dyk1454683243-sudo@users.noreply.github.com>
Co-authored-by: David <dyk1454683243-sudo@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
David
2026-11-02 07:48:07 -07:00
committed by GitHub
co-authored by David David Cursor Agent
parent 8babc79680
commit eab1e483fe
6 changed files with 182 additions and 5 deletions
+13 -1
View File
@@ -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<ParserOutput = string, RendererOutput = string> {
? 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;
+15 -4
View File
@@ -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<ParserOutput = string, RendererOutput = string> {
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<ParserOutput = string, RendererOutput = string> {
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;
+123
View File
@@ -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<object, EmStrongDelCloserHintFrame[]>();
/**
* 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 = '';
@@ -0,0 +1,5 @@
<p>**a<em>b</em>c</p>
<p><em>foo**bar</em></p>
<p>*foo <em>bar</em></p>
@@ -0,0 +1,5 @@
**a*b*c
*foo**bar*
*foo *bar*
@@ -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: `<ul>\n<li>${'*- '.repeat(1999)}*</li>\n</ul>\n`,
},
{
markdown: ('+ _').repeat(2000),
html: `<ul>\n<li>${'_+ '.repeat(1999)}_</li>\n</ul>\n`,
},
{
markdown: ('*x *x ').repeat(2000),
html: `<p>${'*x *x '.repeat(2000)}</p>\n`,
},
{
markdown: ('~x ~x ').repeat(2000),
html: `<p>${'~x ~x '.repeat(2000)}</p>\n`,
},
];