diff --git a/src/Lexer.ts b/src/Lexer.ts index c71d51dfff..fb50d43a12 100644 --- a/src/Lexer.ts +++ b/src/Lexer.ts @@ -1,7 +1,14 @@ import { _Tokenizer } from './Tokenizer.ts'; import { _defaults } from './defaults.ts'; import { other, block, inline } from './rules.ts'; -import { beginEmStrongDelCloserScan, cachedLastPossibleDelCloserIndex, cachedLastPossibleEmStrongCloserIndex, endEmStrongDelCloserScan, normalizeLabel } from './helpers.ts'; +import { + beginEmStrongDelCloserScan, + cachedLastPossibleDelCloserIndex, + cachedLastPossibleEmStrongCloserIndex, + endEmStrongDelCloserScan, + normalizeLabel, + type EmStrongDelCloserHintFrame, +} from './helpers.ts'; import type { Token, TokensList, Tokens } from './Tokens.ts'; import type { MarkedOptions } from './MarkedOptions.ts'; @@ -378,16 +385,17 @@ export class _Lexer { // `'[a](b'.repeat(n)`. Extension tokenizers can pass generated text to // nested runs, so each run must check its own source. const prevLinkParenPossible = this.state.linkParenPossible; - this.state.linkParenPossible = src.includes(')'); + const firstParen = src.indexOf(')'); + this.state.linkParenPossible = firstParen !== -1; try { - return this.#inlineTokensInner(src, tokens); + return this.#inlineTokensInner(src, tokens, firstParen); } finally { // Restore the outer run's flag for the rest of its loop. this.state.linkParenPossible = prevLinkParenPossible; } } - #inlineTokensInner(src: string, tokens: Token[]): Token[] { + #inlineTokensInner(src: string, tokens: Token[], firstParen: number): Token[] { // The masked source is only read by emStrong and del, which need a *, _ or // ~ to start. Skip building it for a run without one, unless a custom // tokenizer or an emStrongMask hook may read it. @@ -401,212 +409,387 @@ export class _Lexer { // Without a delimiter no opener can match, so nothing reads the closer scan. if (!hasDelimiter) { - return this.#tokenizeInlines(src, maskedSrc, tokens); + return this.#tokenizeInlines(src, maskedSrc, tokens, null, firstParen); } // 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); + const hintFrame = beginEmStrongDelCloserScan(this.tokenizer, maskedSrc); try { - return this.#tokenizeInlines(src, maskedSrc, tokens); + return this.#tokenizeInlines(src, maskedSrc, tokens, hintFrame, firstParen); } finally { endEmStrongDelCloserScan(this.tokenizer); } } - #tokenizeInlines(src: string, maskedSrc: string, tokens: Token[]): Token[] { + #tokenizeInlines( + rootSrc: string, + rootMaskedSrc: string, + rootTokens: Token[], + rootHintFrame: EmStrongDelCloserHintFrame | null, + firstParen: number, + ): Token[] { + interface InlineFrame { + src: string; + maskedSrc: string; + tokens: Token[]; + prevChar: string; + keepPrevChar: boolean; + srcLength: number; + rootOffset: number; + nextParen: number; + ownsCloserFrame: boolean; + prevLinkParenPossible: boolean; + hintFrame: EmStrongDelCloserHintFrame | null; + subMaskedSrc: string; + subStart: number; + subEnd: number; + subLastAst: number; + subLastUnd: number; + subLastDel: number; + } + + const canDeferEmStrong = rootHintFrame !== null && this.tokenizer.emStrong === _Tokenizer.prototype.emStrong; + const canDeferDel = rootHintFrame !== null && this.tokenizer.del === _Tokenizer.prototype.del; + const canReuseMask = !this.options.hooks?.emStrongMask; + + let src = rootSrc; + let maskedSrc = rootMaskedSrc; + let tokens = rootTokens; + let hintFrame = rootHintFrame; let keepPrevChar = false; let prevChar = ''; let srcLength = Infinity; - while (src) { - if (src.length < srcLength) { - srcLength = src.length; - } else { - this.infiniteLoopError(src.charCodeAt(0)); - break; + let rootOffset = 0; + let nextParen = firstParen; + let ownsCloserFrame = false; + let subLastAst = -2; + let subLastUnd = -2; + let subLastDel = -2; + let stack: InlineFrame[] | undefined; + let extraCloserFrames = 0; + let pushedChild = false; + + const scanSliceLastCloser = (slice: string, delim: '*' | '_' | '~'): number => { + for (let i = slice.length - 1; i >= 0; i--) { + if (slice[i] !== delim) { + continue; + } + let start = i; + while (start > 0 && slice[start - 1] === delim) { + start--; + } + const prev = start === 0 ? '\n' : slice[start - 1]; + if (prev !== ' ' && prev !== '\t' && prev !== '\n' && prev !== '\r' && prev !== '\f') { + return start; + } + i = start; } + return -1; + }; - if (!keepPrevChar) { - prevChar = ''; - } - keepPrevChar = false; + try { + while (true) { + while (src) { + if (src.length < srcLength) { + srcLength = src.length; + } else { + this.infiniteLoopError(src.charCodeAt(0)); + break; + } - let token: Tokens.Generic | undefined; + if (!keepPrevChar) { + prevChar = ''; + } + keepPrevChar = false; + + let token: Tokens.Generic | undefined; + + // extensions + if (this.options.extensions?.inline?.some((extTokenizer) => { + if (token = extTokenizer.call({ lexer: this }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } - // extensions - if (this.options.extensions?.inline?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } + // escape + if (token = this.tokenizer.escape(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } - // escape - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + // tag + if (token = this.tokenizer.tag(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } - // tag - if (token = this.tokenizer.tag(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + // link + if (token = this.tokenizer.link(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } - // link - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + // reflink, nolink + if (token = this.tokenizer.reflink(src, this.tokens.links)) { + src = src.substring(token.raw.length); + const lastToken = tokens.at(-1); + if (token.type === 'text' && lastToken?.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } else { + tokens.push(token); + } + continue; + } - // reflink, nolink - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.type === 'text' && lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } else { - tokens.push(token); - } - continue; - } + // #4099 follow-up: for a run of `*`, `_`, or `~` with no possible closer + // anywhere ahead in maskedSrc, every opener position fails identically + // and the outer loop walks the run char-by-char, giving O(n^2) time. + // Consume the whole run as literal text in one step. + const firstChar = src[0]; + if (firstChar === '*' || firstChar === '_' || firstChar === '~') { + const pos = maskedSrc.length - src.length; + let lastCloser = firstChar === '~' + ? cachedLastPossibleDelCloserIndex(this.tokenizer, maskedSrc) + : cachedLastPossibleEmStrongCloserIndex(this.tokenizer, maskedSrc, firstChar); + if (lastCloser >= maskedSrc.length) { + if (firstChar === '*') { + if (subLastAst === -2) subLastAst = scanSliceLastCloser(maskedSrc, '*'); + lastCloser = subLastAst; + } else if (firstChar === '_') { + if (subLastUnd === -2) subLastUnd = scanSliceLastCloser(maskedSrc, '_'); + lastCloser = subLastUnd; + } else { + if (subLastDel === -2) subLastDel = scanSliceLastCloser(maskedSrc, '~'); + lastCloser = subLastDel; + } + } + if (lastCloser <= pos) { + const code = firstChar.charCodeAt(0); + let runEnd = 1; + while (runEnd < src.length && src.charCodeAt(runEnd) === code) runEnd++; + const raw = src.substring(0, runEnd); + const lastToken = tokens.at(-1); + if (lastToken?.type === 'text' && !lastToken.escaped) { + lastToken.raw += raw; + lastToken.text += raw; + } else { + tokens.push({ type: 'text', raw, text: raw, escaped: false } as Tokens.Text); + } + src = src.substring(runEnd); + prevChar = firstChar; + keepPrevChar = true; + continue; + } + } - // #4099 follow-up: for a run of `*` or `_` with no possible closer - // anywhere ahead in maskedSrc, every opener position fails identically - // and the outer loop walks the run char-by-char, giving O(n^2) time. - // Consume the whole run as literal text in one step. - const firstChar = src[0]; - if (firstChar === '*' || firstChar === '_') { - const pos = maskedSrc.length - src.length; - const lastCloser = cachedLastPossibleEmStrongCloserIndex(this.tokenizer, maskedSrc, firstChar); - if (lastCloser <= pos) { - let runEnd = 1; - while (runEnd < src.length && src.charCodeAt(runEnd) === firstChar.charCodeAt(0)) runEnd++; - const raw = src.substring(0, runEnd); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text' && !lastToken.escaped) { - lastToken.raw += raw; - lastToken.text += raw; + // em & strong + if (canDeferEmStrong && hintFrame) { + hintFrame.deferInline = true; + hintFrame.deferred = false; + token = this.tokenizer.emStrong(src, maskedSrc, prevChar); + hintFrame.deferInline = false; } else { - tokens.push({ type: 'text', raw, text: raw, escaped: false } as Tokens.Text); + token = this.tokenizer.emStrong(src, maskedSrc, prevChar); } - src = src.substring(runEnd); - prevChar = firstChar; - keepPrevChar = true; - continue; - } - } else if (firstChar === '~') { - const pos = maskedSrc.length - src.length; - const lastCloser = cachedLastPossibleDelCloserIndex(this.tokenizer, maskedSrc); - if (lastCloser <= pos) { - let runEnd = 1; - while (runEnd < src.length && src.charCodeAt(runEnd) === 126 /* ~ */) runEnd++; - const raw = src.substring(0, runEnd); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text' && !lastToken.escaped) { - lastToken.raw += raw; - lastToken.text += raw; - } else { - tokens.push({ type: 'text', raw, text: raw, escaped: false } as Tokens.Text); + if (!token) { + // code + if (token = this.tokenizer.codespan(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // br + if (token = this.tokenizer.br(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // del (gfm) + if (canDeferDel && hintFrame) { + hintFrame.deferInline = true; + hintFrame.deferred = false; + token = this.tokenizer.del(src, maskedSrc, prevChar); + hintFrame.deferInline = false; + } else { + token = this.tokenizer.del(src, maskedSrc, prevChar); + } } - src = src.substring(runEnd); - prevChar = firstChar; - keepPrevChar = true; - continue; - } - } - // em & strong - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + if (token) { + const posInFrame = maskedSrc.length - src.length; + src = src.substring(token.raw.length); + tokens.push(token); + if (hintFrame?.deferred) { + hintFrame.deferred = false; + stack ??= []; + stack.push({ + src, + maskedSrc, + tokens, + prevChar, + keepPrevChar, + srcLength, + rootOffset, + nextParen, + ownsCloserFrame, + prevLinkParenPossible: this.state.linkParenPossible, + hintFrame, + subMaskedSrc: hintFrame.subMaskedSrc, + subStart: hintFrame.subStart, + subEnd: hintFrame.subEnd, + subLastAst, + subLastUnd, + subLastDel, + }); + const childText = token.text as string; + const delimLen = (token.raw.length - childText.length) >> 1; + src = childText; + tokens = token.tokens!; + prevChar = ''; + keepPrevChar = false; + srcLength = Infinity; + subLastAst = -2; + subLastUnd = -2; + subLastDel = -2; + if (canReuseMask && rootOffset !== -1) { + const childStart = rootOffset + posInFrame + delimLen; + const childEnd = childStart + childText.length; + maskedSrc = maskedSrc.slice(posInFrame + delimLen, posInFrame + token.raw.length - delimLen); + rootOffset = childStart; + ownsCloserFrame = false; + hintFrame.subMaskedSrc = maskedSrc; + hintFrame.subStart = childStart; + hintFrame.subEnd = childEnd; + if (nextParen === -1) { + this.state.linkParenPossible = false; + } else { + if (nextParen < childStart) { + nextParen = rootSrc.indexOf(')', childStart); + } + this.state.linkParenPossible = nextParen !== -1 && nextParen < childEnd; + } + } else { + maskedSrc = this.#maskSrc(childText); + rootOffset = -1; + const childParen = childText.indexOf(')'); + nextParen = childParen; + this.state.linkParenPossible = childParen !== -1; + hintFrame = beginEmStrongDelCloserScan(this.tokenizer, maskedSrc); + ownsCloserFrame = true; + extraCloserFrames++; + } + pushedChild = true; + break; + } + continue; + } - // code - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + // autolink + if (token = this.tokenizer.autolink(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } - // br - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + // url (gfm) + if (!this.state.inLink && (token = this.tokenizer.url(src))) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } - // del (gfm) - if (token = this.tokenizer.del(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + // text + // prevent inlineText consuming extensions by clipping 'src' to extension start + let cutSrc = src; + if (this.options.extensions?.startInline) { + let startIndex = Infinity; + const tempSrc = src.slice(1); + let tempStart; + this.options.extensions.startInline.forEach((getStartIndex) => { + tempStart = getStartIndex.call({ lexer: this }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + } + if (token = this.tokenizer.inlineText(cutSrc)) { + src = src.substring(token.raw.length); + if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started + prevChar = token.raw.slice(-1); + } + keepPrevChar = true; + const lastToken = tokens.at(-1); + if (lastToken?.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } else { + tokens.push(token); + } + continue; + } - // autolink - if (token = this.tokenizer.autolink(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + if (src) { + this.infiniteLoopError(src.charCodeAt(0)); + break; + } + } - // url (gfm) - if (!this.state.inLink && (token = this.tokenizer.url(src))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } + if (pushedChild) { + pushedChild = false; + continue; + } - // text - // prevent inlineText consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startInline) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startInline.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); + if (!stack || stack.length === 0) { + break; } - } - if (token = this.tokenizer.inlineText(cutSrc)) { - src = src.substring(token.raw.length); - if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started - prevChar = token.raw.slice(-1); + if (ownsCloserFrame) { + endEmStrongDelCloserScan(this.tokenizer); + extraCloserFrames--; } - keepPrevChar = true; - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } else { - tokens.push(token); + const parent = stack.pop()!; + src = parent.src; + maskedSrc = parent.maskedSrc; + tokens = parent.tokens; + prevChar = parent.prevChar; + keepPrevChar = parent.keepPrevChar; + srcLength = parent.srcLength; + rootOffset = parent.rootOffset; + nextParen = parent.nextParen; + ownsCloserFrame = parent.ownsCloserFrame; + this.state.linkParenPossible = parent.prevLinkParenPossible; + hintFrame = parent.hintFrame; + if (hintFrame) { + hintFrame.subMaskedSrc = parent.subMaskedSrc; + hintFrame.subStart = parent.subStart; + hintFrame.subEnd = parent.subEnd; } - continue; + subLastAst = parent.subLastAst; + subLastUnd = parent.subLastUnd; + subLastDel = parent.subLastDel; } - - if (src) { - this.infiniteLoopError(src.charCodeAt(0)); - break; + } finally { + while (extraCloserFrames-- > 0) { + endEmStrongDelCloserScan(this.tokenizer); } } - return tokens; + return rootTokens; } /** diff --git a/src/Tokenizer.ts b/src/Tokenizer.ts index 3b2cc1ea5f..2b4c28e389 100644 --- a/src/Tokenizer.ts +++ b/src/Tokenizer.ts @@ -10,6 +10,13 @@ import { trimTrailingBlankLines, cachedLastPossibleEmStrongCloserIndex, cachedLastPossibleDelCloserIndex, + getActiveEmStrongDelCloserFrame, + isBuiltinEmStrongRDelim, + isBuiltinDelRDelim, + buildEmStrongCloserIndex, + findEmStrongCloserIndexed, + buildDelCloserIndex, + findDelCloserIndexed, } from './helpers.ts'; import type { Rules } from './rules.ts'; import type { _Lexer } from './Lexer.ts'; @@ -1075,63 +1082,109 @@ export class _Tokenizer { 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__ + const frame = getActiveEmStrongDelCloserFrame(this, maskedSrc); + const indexFrame = isBuiltinEmStrongRDelim(endReg) ? frame : undefined; + let rawLength = -1; + let matchedRLength = 0; + const existingIndex = indexFrame?.emStrongIndex?.[delimChar]; + + if (existingIndex && indexFrame) { + const found = findEmStrongCloserIndexed( + indexFrame, + existingIndex, + maskedSrc, + srcStart, + lLength, + runLength, + openerCanClose, + midRun, + delimChar, + endReg, + ); + if (!found) return; + rawLength = found.rawLength; + matchedRLength = found.rLength; + } else { + // Clip maskedSrc to same section of string as src (move to lexer?) + const sliceMasked = maskedSrc.slice(-1 * src.length + lLength); + const lastPossibleEmStrongCloserIndexInWindow = lastPossibleEmStrongCloserIndex - emStrongCloserWindowStart; + endReg.lastIndex = 0; + let steps = 0; + + while ((match = endReg.exec(sliceMasked)) !== 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__ + + if (indexFrame && ++steps > 16) { + const index = buildEmStrongCloserIndex(indexFrame, endReg, delimChar); + const found = findEmStrongCloserIndexed( + indexFrame, + index, + maskedSrc, + srcStart, + lLength, + runLength, + openerCanClose, + midRun, + delimChar, + endReg, + ); + if (!found) return; + rawLength = found.rawLength; + matchedRLength = found.rLength; + break; + } - rLength = [...rDelim].length; + rLength = [...rDelim].length; - if (match[3] || match[4]) { // found another Left Delim - delimTotal += rLength; - continue; - } else if (match[5] || match[6] || openerCanClose) { // either Left or Right Delim - if (runLength % 3 && !((runLength + rLength) % 3)) { // CommonMark Emphasis Rules 9-10 - if (midRun && (match[5] || match[6])) { - // A delimiter that can also open and cannot close this run - // opens its own span; a later closer pairs with it, not with a - // mid-run opener (`**a*a*` must be `**aa`). - break; - } - midDelimTotal += rLength; + if (match[3] || match[4]) { // found another Left Delim + delimTotal += rLength; continue; + } else if (match[5] || match[6] || openerCanClose) { // either Left or Right Delim + if (runLength % 3 && !((runLength + rLength) % 3)) { // CommonMark Emphasis Rules 9-10 + if (midRun && (match[5] || match[6])) { + // A delimiter that can also open and cannot close this run + // opens its own span; a later closer pairs with it, not with a + // mid-run opener (`**a*a*` must be `**aa`). + break; + } + midDelimTotal += rLength; + continue; + } } - } - - delimTotal -= rLength; - if (delimTotal > 0) continue; // Haven't found enough closing delimiters + delimTotal -= rLength; - // Remove extra characters. *a*** -> *a* - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - // char length can be >1 for unicode characters; - const lastCharLength = [...match[0]][0].length; - const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); + if (delimTotal > 0) continue; // Haven't found enough closing delimiters - // Create `em` if smallest delimiter has odd char count. *a*** - if (Math.min(lLength, rLength) % 2) { - const text = raw.slice(1, -1); - return { - type: 'em', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; + // Remove extra characters. *a*** -> *a* + rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); + // char length can be >1 for unicode characters; + const lastCharLength = [...match[0]][0].length; + rawLength = lLength + match.index + lastCharLength + rLength; + matchedRLength = rLength; + break; } + } - // Create 'strong' if smallest delimiter has even char count. **a*** - const text = raw.slice(2, -2); + if (rawLength !== -1) { + const raw = src.slice(0, rawLength); + // Odd min delimiter length produces `em` (*a***), even produces `strong` (**a***). + const delimLen = Math.min(lLength, matchedRLength) % 2 ? 1 : 2; + const type = delimLen === 1 ? 'em' : 'strong'; + const text = raw.slice(delimLen, -delimLen); + const defer = !!frame?.deferInline; + if (defer) { + frame.deferred = true; + } return { - type: 'strong', + type, raw, text, - tokens: this.lexer.inlineTokens(text), + tokens: defer ? [] : this.lexer.inlineTokens(text), }; } } @@ -1181,45 +1234,71 @@ export class _Tokenizer { const endReg = this.rules.inline.delRDelim; const lastPossibleDelCloserIndex = cachedLastPossibleDelCloserIndex(this, maskedSrc); - const delCloserWindowStart = maskedSrc.length - src.length + lLength; + const delSrcStart = maskedSrc.length - src.length; + const delCloserWindowStart = delSrcStart + 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]; + const frame = getActiveEmStrongDelCloserFrame(this, maskedSrc); + const indexFrame = isBuiltinDelRDelim(endReg) ? frame : undefined; + let rawLength = -1; + const existingIndex = indexFrame?.delIndex; - if (!rDelim) continue; + if (existingIndex && indexFrame) { + rawLength = findDelCloserIndexed(indexFrame, existingIndex, maskedSrc, delSrcStart, lLength, endReg); + } else { + // Clip maskedSrc to same section of string as src + const sliceMasked = maskedSrc.slice(-1 * src.length + lLength); + const lastPossibleDelCloserIndexInWindow = lastPossibleDelCloserIndex - delCloserWindowStart; + endReg.lastIndex = 0; + let steps = 0; - rLength = [...rDelim].length; + while ((match = endReg.exec(sliceMasked)) !== null) { + if (match.index > lastPossibleDelCloserIndexInWindow) break; + rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (rLength !== lLength) continue; + if (!rDelim) continue; - if (match[3] || match[4]) { // found another Left Delim - delimTotal += rLength; - continue; - } + if (indexFrame && ++steps > 16) { + const index = buildDelCloserIndex(indexFrame, endReg); + rawLength = findDelCloserIndexed(indexFrame, index, maskedSrc, delSrcStart, lLength, endReg); + break; + } - delimTotal -= rLength; + rLength = [...rDelim].length; - if (delimTotal > 0) continue; // Haven't found enough closing delimiters + if (rLength !== lLength) continue; - // Remove extra characters - rLength = Math.min(rLength, rLength + delimTotal); - // char length can be >1 for unicode characters - const lastCharLength = [...match[0]][0].length; - const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); + if (match[3] || match[4]) { // found another Left Delim + delimTotal += rLength; + continue; + } + delimTotal -= rLength; + + if (delimTotal > 0) continue; // Haven't found enough closing delimiters + + // Remove extra characters + rLength = Math.min(rLength, rLength + delimTotal); + // char length can be >1 for unicode characters + const lastCharLength = [...match[0]][0].length; + rawLength = lLength + match.index + lastCharLength + rLength; + break; + } + } + + if (rawLength !== -1) { + const raw = src.slice(0, rawLength); // Create del token - only single ~ or double ~~ supported const text = raw.slice(lLength, -lLength); + const defer = !!frame?.deferInline; + if (defer) { + frame.deferred = true; + } return { type: 'del', raw, text, - tokens: this.lexer.inlineTokens(text), + tokens: defer ? [] : this.lexer.inlineTokens(text), }; } } diff --git a/src/helpers.ts b/src/helpers.ts index 41e26c4d8a..07e31a5e70 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -1,4 +1,4 @@ -import { other } from './rules.ts'; +import { inline, other } from './rules.ts'; /** * Helpers @@ -194,14 +194,45 @@ interface LastPossibleEmStrongCloserIndex { _: number; } +interface CloserQueryTable { + bal: Int32Array; + mid: Int32Array | null; + nextBreak: Int32Array | null; + tree: Int32Array; + cap: number; +} + +interface EmStrongCloserIndex { + starts: number[]; + lens: number[]; + kinds: number[]; // 0 = RIGHT, 1 = LEFT, 2 = BOTH + tables: (CloserQueryTable | undefined)[]; +} + +interface DelCloserIndex { + starts: number[]; + lens: number[]; + kinds: number[]; // 0 = RIGHT/BOTH, 1 = LEFT + tables: (CloserQueryTable | undefined)[]; +} + /** * Closer hints for one inline `maskedSrc`. Held only while that pass runs. */ -interface EmStrongDelCloserHintFrame { +export interface EmStrongDelCloserHintFrame { maskedSrc: string; lastPossibleEmStrongCloserIndex: LastPossibleEmStrongCloserIndex; /** Last `~` run that can close strikethrough. `-1` if none. */ lastPossibleDelCloserIndex: number; + /** Active sub-slice of `maskedSrc` for iterative nested emphasis frames. */ + subMaskedSrc: string; + subStart: number; + subEnd: number; + /** Set by `Lexer.#tokenizeInlines` when default `emStrong`/`del` may defer child tokenization. */ + deferInline: boolean; + deferred: boolean; + emStrongIndex?: { '*': EmStrongCloserIndex | null; _: EmStrongCloserIndex | null }; + delIndex?: DelCloserIndex | null; } /** @@ -251,6 +282,11 @@ function scanLastPossibleEmStrongDelClosers(src: string): EmStrongDelCloserHintF maskedSrc: src, lastPossibleEmStrongCloserIndex, lastPossibleDelCloserIndex, + subMaskedSrc: src, + subStart: 0, + subEnd: len, + deferInline: false, + deferred: false, }; } @@ -259,7 +295,7 @@ function scanLastPossibleEmStrongDelClosers(src: string): EmStrongDelCloserHintF * 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 { +export function beginEmStrongDelCloserScan(tokenizer: object, maskedSrc: string): EmStrongDelCloserHintFrame { const frame = scanLastPossibleEmStrongDelClosers(maskedSrc); const stack = emStrongDelCloserHintStacks.get(tokenizer); if (stack) { @@ -267,6 +303,7 @@ export function beginEmStrongDelCloserScan(tokenizer: object, maskedSrc: string) } else { emStrongDelCloserHintStacks.set(tokenizer, [frame]); } + return frame; } /** @@ -284,15 +321,34 @@ export function endEmStrongDelCloserScan(tokenizer: object): void { } } +/** + * Return the active closer-hint frame when `maskedSrc` matches either the + * frame's root `maskedSrc` or its current iterative sub-frame slice. + */ +export function getActiveEmStrongDelCloserFrame(tokenizer: object, maskedSrc: string): EmStrongDelCloserHintFrame | undefined { + const frame = emStrongDelCloserHintStacks.get(tokenizer)?.at(-1); + if (frame && (frame.maskedSrc === maskedSrc || frame.subMaskedSrc === maskedSrc)) { + return frame; + } + return undefined; +} + /** * 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. + * pass's source (or an iterative sub-frame); 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]; + if (frame) { + if (frame.maskedSrc === maskedSrc) { + return frame.lastPossibleEmStrongCloserIndex[delim]; + } + if (frame.subMaskedSrc === maskedSrc) { + const rootLast = frame.lastPossibleEmStrongCloserIndex[delim]; + return rootLast < frame.subStart ? -1 : rootLast - frame.subStart; + } } return scanLastPossibleEmStrongDelClosers(maskedSrc).lastPossibleEmStrongCloserIndex[delim]; } @@ -300,16 +356,424 @@ export function cachedLastPossibleEmStrongCloserIndex(tokenizer: object, maskedS /** * 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. + * source (or an iterative sub-frame); 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; + if (frame) { + if (frame.maskedSrc === maskedSrc) { + return frame.lastPossibleDelCloserIndex; + } + if (frame.subMaskedSrc === maskedSrc) { + const rootLast = frame.lastPossibleDelCloserIndex; + return rootLast < frame.subStart ? -1 : rootLast - frame.subStart; + } } return scanLastPossibleEmStrongDelClosers(maskedSrc).lastPossibleDelCloserIndex; } +export function isBuiltinEmStrongRDelim(reg: RegExp): boolean { + return reg === inline.normal.emStrongRDelimAst + || reg === inline.gfm.emStrongRDelimAst + || reg === inline.pedantic.emStrongRDelimAst + || reg === inline.normal.emStrongRDelimUnd + || reg === inline.pedantic.emStrongRDelimUnd; +} + +export function isBuiltinDelRDelim(reg: RegExp): boolean { + return reg === inline.gfm.delRDelim; +} + +function buildMinSegTree(bal: Int32Array, k: number): { tree: Int32Array; cap: number } { + let cap = 1; + while (cap < k) { + cap <<= 1; + } + const tree = new Int32Array(cap << 1); + tree.fill(0x7fffffff, cap + k); + for (let i = 0; i < k; i++) { + tree[cap + i] = bal[i + 1]; + } + for (let p = cap - 1; p > 0; p--) { + const left = tree[p << 1]; + const right = tree[(p << 1) | 1]; + tree[p] = left < right ? left : right; + } + return { tree, cap }; +} + +function queryFirstLe(tree: Int32Array, cap: number, lIdx: number, rIdx: number, target: number): number { + let l = lIdx + cap; + let r = rIdx + cap; + let bestRight = 0; + while (l < r) { + if (l & 1) { + if (tree[l] <= target) { + let p = l; + while (p < cap) { + p = tree[p << 1] <= target ? p << 1 : (p << 1) | 1; + } + return p - cap; + } + l++; + } + if (r & 1) { + --r; + if (tree[r] <= target) { + bestRight = r; + } + } + l >>= 1; + r >>= 1; + } + if (bestRight !== 0) { + let p = bestRight; + while (p < cap) { + p = tree[p << 1] <= target ? p << 1 : (p << 1) | 1; + } + return p - cap; + } + return -1; +} + +function lowerBound(arr: number[], target: number): number { + let lo = 0; + let hi = arr.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (arr[mid] < target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +/** + * Match the `^[^_*]*?__[^_*]*?\*[^_*]*?(?=__)` (or `**` / `_`) orphan-inside-strong + * prefix of the right-delimiter regex at `[start, end)` without regex slicing. + */ +function findOrphanInsideStrongEnd(maskedSrc: string, start: number, end: number, delimChar: '*' | '_'): number { + const other = delimChar === '*' ? '_' : '*'; + let i = start; + while (i < end) { + const ch = maskedSrc[i]; + if (ch === delimChar) { + return -1; + } + if (ch === other) { + if (i + 1 >= end || maskedSrc[i + 1] !== other) { + return -1; + } + let j = i + 2; + while (j < end) { + const c2 = maskedSrc[j]; + if (c2 === other) { + return -1; + } + if (c2 === delimChar) { + let k = j + 1; + while (k < end) { + const c3 = maskedSrc[k]; + if (c3 === delimChar) { + return -1; + } + if (c3 === other) { + return k + 1 < end && maskedSrc[k + 1] === other ? k : -1; + } + k++; + } + return -1; + } + j++; + } + return -1; + } + i++; + } + return -1; +} + +function scanDelimiterRuns(rootMaskedSrc: string, endReg: RegExp, delimChar: string, distinguishBoth: boolean) { + const starts: number[] = []; + const lens: number[] = []; + const kinds: number[] = []; + // Prepending `delimChar` blocks the `^` orphan-inside-strong prefix at index 0 + // and cannot match rules (1)-(6) as a predecessor. + const scanSrc = delimChar + rootMaskedSrc; + endReg.lastIndex = 0; + let match: RegExpExecArray | null; + while ((match = endReg.exec(scanSrc)) !== null) { + const rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; + if (!rDelim) { + continue; + } + const len = rDelim.length; + const start = endReg.lastIndex - 1 - len; + const kind = (match[3] || match[4]) ? 1 : (distinguishBoth && (match[5] || match[6])) ? 2 : 0; + starts.push(start); + lens.push(len); + kinds.push(kind); + } + return { starts, lens, kinds }; +} + +function buildEmStrongQueryTable(index: EmStrongCloserIndex, mod: number, openerCanClose: boolean, midRun: boolean): CloserQueryTable { + const { lens, kinds } = index; + const k = lens.length; + const bal = new Int32Array(k + 1); + const mid = new Int32Array(k + 1); + const nextBreak = midRun ? new Int32Array(k + 1) : null; + + for (let i = 0; i < k; i++) { + const kind = kinds[i]; + const len = lens[i]; + let delta = 0; + let midDelta = 0; + if (kind === 1) { + delta = len; + } else if (kind === 0) { + if (openerCanClose && mod !== 0 && (mod + len) % 3 === 0) { + midDelta = len; + } else { + delta = -len; + } + } else if (mod !== 0 && (mod + len) % 3 === 0) { + midDelta = len; + } else { + delta = -len; + } + bal[i + 1] = bal[i] + delta; + mid[i + 1] = mid[i] + midDelta; + } + + if (nextBreak) { + let brk = k; + nextBreak[k] = k; + for (let i = k - 1; i >= 0; i--) { + if (kinds[i] === 2 && mod !== 0 && (mod + lens[i]) % 3 === 0) { + brk = i; + } + nextBreak[i] = brk; + } + } + + return { + bal, + mid, + nextBreak, + ...buildMinSegTree(bal, k), + }; +} + +function isTailRunCloser(localMaskedSrc: string, tailLocalStart: number, minCheckFrom: number, endReg: RegExp): boolean { + endReg.lastIndex = Math.max(minCheckFrom, tailLocalStart - 2); + let match: RegExpExecArray | null; + while ((match = endReg.exec(localMaskedSrc)) !== null) { + const rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; + if (!rDelim) { + continue; + } + if (endReg.lastIndex - rDelim.length === tailLocalStart) { + return !(match[3] || match[4]); + } + } + return false; +} + +export function buildEmStrongCloserIndex(frame: EmStrongDelCloserHintFrame, endReg: RegExp, delimChar: '*' | '_'): EmStrongCloserIndex { + const runs = scanDelimiterRuns(frame.maskedSrc, endReg, delimChar, true); + const index: EmStrongCloserIndex = { + ...runs, + tables: new Array(12), + }; + if (!frame.emStrongIndex) { + frame.emStrongIndex = { '*': null, _: null }; + } + frame.emStrongIndex[delimChar] = index; + return index; +} + +export function findEmStrongCloserIndexed( + frame: EmStrongDelCloserHintFrame, + index: EmStrongCloserIndex, + localMaskedSrc: string, + localSrcStart: number, + lLength: number, + runLength: number, + openerCanClose: boolean, + midRun: boolean, + delimChar: '*' | '_', + endReg: RegExp, +): { rawLength: number; rLength: number } | undefined { + const isSubFrame = frame.subMaskedSrc === localMaskedSrc && frame.maskedSrc !== localMaskedSrc; + const frameStart = isSubFrame ? frame.subStart : 0; + const frameEnd = isSubFrame ? frame.subEnd : frame.maskedSrc.length; + const rootSrcStart = frameStart + localSrcStart; + let effectiveRootSliceStart = rootSrcStart + lLength; + + const orphanEnd = findOrphanInsideStrongEnd(frame.maskedSrc, effectiveRootSliceStart, frameEnd, delimChar); + if (orphanEnd !== -1) { + effectiveRootSliceStart = orphanEnd; + } + + const { starts, lens, tables } = index; + const k = starts.length; + const firstRunIdx = lowerBound(starts, effectiveRootSliceStart); + if (firstRunIdx >= k) { + return undefined; + } + + let limitIdx = k; + let tailLen = 0; + if (frameEnd < frame.maskedSrc.length) { + limitIdx = lowerBound(starts, frameEnd); + if (limitIdx > 0 && starts[limitIdx - 1] + lens[limitIdx - 1] >= frameEnd) { + limitIdx--; + } + if (limitIdx >= firstRunIdx && limitIdx < k && starts[limitIdx] < frameEnd) { + const candidateTailLen = frameEnd - starts[limitIdx]; + if (isTailRunCloser(localMaskedSrc, starts[limitIdx] - frameStart, localSrcStart + lLength, endReg)) { + tailLen = candidateTailLen; + } + } + } + + const mod = runLength % 3; + const tableKey = (mod << 2) | (openerCanClose ? 2 : 0) | (midRun ? 1 : 0); + let table = tables[tableKey]; + if (!table) { + table = buildEmStrongQueryTable(index, mod, openerCanClose, midRun); + tables[tableKey] = table; + } + + if (midRun && table.nextBreak) { + const brk = table.nextBreak[firstRunIdx]; + if (brk < limitIdx) { + limitIdx = brk; + tailLen = 0; + } + } + + if (firstRunIdx < limitIdx) { + const target = table.bal[firstRunIdx] - lLength; + const matchIdx = queryFirstLe(table.tree, table.cap, firstRunIdx, limitIdx, target); + if (matchIdx !== -1) { + const delimTotal = lLength + (table.bal[matchIdx + 1] - table.bal[firstRunIdx]); + const midDelimTotal = table.mid![matchIdx + 1] - table.mid![firstRunIdx]; + const rLength = Math.min(lens[matchIdx], lens[matchIdx] + delimTotal + midDelimTotal); + return { + rawLength: (starts[matchIdx] - rootSrcStart) + rLength, + rLength, + }; + } + } + + if (tailLen > 0 && !(openerCanClose && mod !== 0 && (mod + tailLen) % 3 === 0)) { + const delimTotal = lLength + (table.bal[limitIdx] - table.bal[firstRunIdx]) - tailLen; + if (delimTotal <= 0) { + const midDelimTotal = table.mid![limitIdx] - table.mid![firstRunIdx]; + const rLength = Math.min(tailLen, tailLen + delimTotal + midDelimTotal); + return { + rawLength: (starts[limitIdx] - rootSrcStart) + rLength, + rLength, + }; + } + } + + return undefined; +} + +function buildDelQueryTable(index: DelCloserIndex, targetLen: number): CloserQueryTable { + const { lens, kinds } = index; + const k = lens.length; + const bal = new Int32Array(k + 1); + for (let i = 0; i < k; i++) { + const len = lens[i]; + const delta = len === targetLen ? (kinds[i] === 1 ? len : -len) : 0; + bal[i + 1] = bal[i] + delta; + } + return { + bal, + mid: null, + nextBreak: null, + ...buildMinSegTree(bal, k), + }; +} + +export function buildDelCloserIndex(frame: EmStrongDelCloserHintFrame, endReg: RegExp): DelCloserIndex { + const runs = scanDelimiterRuns(frame.maskedSrc, endReg, '~', false); + const index: DelCloserIndex = { + ...runs, + tables: new Array(2), + }; + frame.delIndex = index; + return index; +} + +export function findDelCloserIndexed( + frame: EmStrongDelCloserHintFrame, + index: DelCloserIndex, + localMaskedSrc: string, + localSrcStart: number, + lLength: number, + endReg: RegExp, +): number { + const isSubFrame = frame.subMaskedSrc === localMaskedSrc && frame.maskedSrc !== localMaskedSrc; + const frameStart = isSubFrame ? frame.subStart : 0; + const frameEnd = isSubFrame ? frame.subEnd : frame.maskedSrc.length; + const rootSrcStart = frameStart + localSrcStart; + const rootSliceStart = rootSrcStart + lLength; + + const { starts, lens, tables } = index; + const k = starts.length; + const firstRunIdx = lowerBound(starts, rootSliceStart); + if (firstRunIdx >= k) { + return -1; + } + + let limitIdx = k; + let tailLen = 0; + if (frameEnd < frame.maskedSrc.length) { + limitIdx = lowerBound(starts, frameEnd); + if (limitIdx > 0 && starts[limitIdx - 1] + lens[limitIdx - 1] >= frameEnd) { + limitIdx--; + } + if (limitIdx >= firstRunIdx && limitIdx < k && starts[limitIdx] < frameEnd) { + const candidateTailLen = frameEnd - starts[limitIdx]; + if (candidateTailLen === lLength && isTailRunCloser(localMaskedSrc, starts[limitIdx] - frameStart, localSrcStart + lLength, endReg)) { + tailLen = candidateTailLen; + } + } + } + + const slot = lLength - 1; + let table = tables[slot]; + if (!table) { + table = buildDelQueryTable(index, lLength); + tables[slot] = table; + } + + if (firstRunIdx < limitIdx) { + const target = table.bal[firstRunIdx] - lLength; + const matchIdx = queryFirstLe(table.tree, table.cap, firstRunIdx, limitIdx, target); + if (matchIdx !== -1) { + return (starts[matchIdx] - rootSrcStart) + lLength; + } + } + + if (tailLen > 0) { + const delimTotal = lLength + (table.bal[limitIdx] - table.bal[firstRunIdx]) - tailLen; + if (delimTotal <= 0) { + return (starts[limitIdx] - rootSrcStart) + lLength; + } + } + + return -1; +} + export function expandTabs(line: string, indent = 0) { let col = indent; let expanded = ''; diff --git a/test/specs/redos/quadratic_nested_emphasis.cjs b/test/specs/redos/quadratic_nested_emphasis.cjs new file mode 100644 index 0000000000..51a5fa611c --- /dev/null +++ b/test/specs/redos/quadratic_nested_emphasis.cjs @@ -0,0 +1,24 @@ +// Deeply nested emphasis and strikethrough previously ran in quadratic time +// and overflowed the call stack in the lexer (issue #4286). +module.exports = [ + { + markdown: '*a '.repeat(2000) + 'b' + ' c*'.repeat(2000), + html: `

${'a '.repeat(2000)}b${' c'.repeat(2000)}

`, + }, + { + markdown: '**a '.repeat(2000) + 'b' + ' c**'.repeat(2000), + html: `

${'a '.repeat(2000)}b${' c'.repeat(2000)}

`, + }, + { + markdown: '*a '.repeat(2000) + 'c*', + html: `

${'*a '.repeat(1999)}a c

`, + }, + { + markdown: '~~a '.repeat(2000) + 'b' + ' c~~'.repeat(2000), + html: `

${'a '.repeat(2000)}b${' c'.repeat(2000)}

`, + }, + { + markdown: '**a*b '.repeat(2000), + html: `

${'**a*b '.repeat(2000)}

`, + }, +]; diff --git a/test/unit/Lexer.test.js b/test/unit/Lexer.test.js index 13c3b9b869..09c55d26f4 100644 --- a/test/unit/Lexer.test.js +++ b/test/unit/Lexer.test.js @@ -2323,4 +2323,65 @@ paragraph assert.deepEqual(tokensA, tokensB); }); }); + + describe('deeply nested emphasis and strikethrough (#4286)', () => { + it('should lex 20000 nested emphasis levels without stack overflow', () => { + const depth = 20000; + const md = '*a '.repeat(depth) + 'b' + ' c*'.repeat(depth); + const tokens = Lexer.lex(md); + assert.strictEqual(tokens.length, 1); + assert.strictEqual(tokens[0].type, 'paragraph'); + assert.strictEqual(tokens[0].tokens.length, 1); + assert.strictEqual(tokens[0].tokens[0].type, 'em'); + let cur = tokens[0].tokens[0].tokens; + for (let i = 1; i < depth; i++) { + assert.strictEqual(cur.length, 3); + assert.strictEqual(cur[0].text, 'a '); + assert.strictEqual(cur[1].type, 'em'); + assert.strictEqual(cur[2].text, ' c'); + cur = cur[1].tokens; + } + assert.strictEqual(cur.length, 1); + assert.strictEqual(cur[0].text, 'a b c'); + }); + + it('should lex 20000 nested strikethrough levels without stack overflow', () => { + const depth = 20000; + const md = '~~a '.repeat(depth) + 'b' + ' c~~'.repeat(depth); + const tokens = Lexer.lex(md); + assert.strictEqual(tokens.length, 1); + assert.strictEqual(tokens[0].type, 'paragraph'); + assert.strictEqual(tokens[0].tokens.length, 1); + assert.strictEqual(tokens[0].tokens[0].type, 'del'); + let cur = tokens[0].tokens[0].tokens; + for (let i = 1; i < depth; i++) { + assert.strictEqual(cur.length, 3); + assert.strictEqual(cur[0].text, 'a '); + assert.strictEqual(cur[1].type, 'del'); + assert.strictEqual(cur[2].text, ' c'); + cur = cur[1].tokens; + } + assert.strictEqual(cur.length, 1); + assert.strictEqual(cur[0].text, 'a b c'); + }); + + it('should match fast-path tokens when the delimiter closer index is active', () => { + const pad = '`|`' + '*x *y* z* '.repeat(20); + const padTokens = Lexer.lex(pad)[0].tokens; + const cases = [ + '*a *b***', + '***a*b***', + '__ *#**__', + '~~*a**~~', + '*__a*b__*', + 'a*b**c*', + '**a *b** c*', + ]; + for (const sample of cases) { + const direct = Lexer.lex(sample)[0].tokens; + const indexed = Lexer.lex(sample + pad)[0].tokens; + assert.deepEqual(indexed, [...direct, ...padTokens]); + } + }); + }); });