Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions src/Lexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,14 +306,11 @@ export class _Lexer<ParserOutput = string, RendererOutput = string> {
let maskedSrc = src;

// Mask out reflinks
if (this.tokens.links) {
const links = Object.keys(this.tokens.links);
if (links.length > 0) {
maskedSrc = maskedSrc.replace(this.tokenizer.rules.inline.reflinkSearch, match0 =>
links.includes(match0.slice(match0.lastIndexOf('[') + 1, -1))
? '[' + 'a'.repeat(match0.length - 2) + ']'
: match0);
}
if (this.tokens.links && src.includes('[')) {
maskedSrc = maskedSrc.replace(this.tokenizer.rules.inline.reflinkSearch, match0 =>
Object.hasOwn(this.tokens.links, match0.slice(match0.lastIndexOf('[') + 1, -1))
? '[' + 'a'.repeat(match0.length - 2) + ']'
: match0);
}

// Mask out escaped characters
Expand Down
17 changes: 17 additions & 0 deletions test/specs/redos/quadratic_footnote_defs.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Regression: many reference definitions + references must not be quadratic.
// Lexer.inlineTokens rebuilt its reflink-masking preamble on every call;
// with n defs and n refs that took ~24s at n=13000 (exponent ~3).
const n = 13000;
let refs = '';
const defs = [];
const links = [];
for (let i = 0; i < n; i++) {
refs += `[^${i}] `;
defs.push(`[^${i}]: x`);
links.push(`<a href="x">^${i}</a>`);
}

module.exports = {
markdown: `${refs}\n\n${defs.join('\n')}`,
html: `<p>${links.join(' ')}</p>\n`,
};
14 changes: 14 additions & 0 deletions test/specs/redos/quadratic_nested_reflink_defs.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Regression: recursive link text containing '[' must not rebuild lookup state
// for every reference when many link definitions are present.
const n = 13000;
const defs = ['[id]: /url'];
const links = [];
for (let i = 0; i < n; i++) {
defs.push(`[unused-${i}]: /${i}`);
links.push('<a href="/url">[x]</a>');
}

module.exports = {
markdown: `${'[[x]][id] '.repeat(n)}\n\n${defs.join('\n')}`,
html: `<p>${links.join(' ')}</p>\n`,
};