Skip to content

Commit 48aba8c

Browse files
fb55claude
andcommitted
fix(sax-parser): enter and leave foreign namespaces where tree construction does
Tree construction pops a self-closing `svg` or `math` element at once, but the feedback simulator kept its namespace frame, so the content after `<svg/>` was tokenized as foreign (a CDATA section became text instead of a bogus comment) and a stream of self-closing roots grew the namespace stack without bound. The end tag of an `annotation-xml` integration point never left its HTML frame either, because the check looked for the `encoding` attribute on an end tag, while a stray end tag of another integration point (`</mo>` inside `mi`) or the end tag of a nested HTML element of the same name (`<mi></mi>` inside `mi`) left a frame that tree construction keeps. The simulator also opened a frame for every `svg` or `math` start tag, while in foreign content tree construction inserts them as elements of the current namespace and only `svg` in `annotation-xml` opens SVG content, so in `<math><svg><desc>` the `desc` became an HTML integration point and a CDATA section in it a bogus comment. `mglyph` and `malignmark` in a MathML text integration point stay MathML elements, where the simulator kept HTML content. The `</p>` and `</br>` end tags break out of foreign content as `<p>` and `<br>` do, where the simulator stayed in it, and a breakout pops every foreign element up to an HTML element or integration point, where the simulator left only one frame. Each frame now remembers the name of the tag that opened it: an HTML element of that name inside the frame opens a frame of its own, and an end tag closes the frame only when it is that tag's. The simulator also knows whether the current node is the element that opened the last frame and whether each frame's element is the parent of the next. An `svg` or `math` start tag in foreign content opens a frame of its own namespace, and one of the other namespace only while the current node is not known: it may be `annotation-xml`, or the tree may already have left the frame. `mglyph` and `malignmark` open a MathML frame directly in a text integration point, and the end tag of that element or of the frame's below closes it too. A self-closing element ends the frame it opened at once, and a breakout leaves all foreign frames. Where one wrong frame cancelled another gap of the simulator, the input now shows that gap: an HTML ancestor's end tag (`<div><svg><math><ms></div>`), an HTML element still open at an integration point's end tag (`<math><mo><svg></p><desc></mo>`), a stray `</math>` inside an integration point, and tags that `select` ignores. The tests cover self-closing svg, math, repeated roots and svg inside math; MathML content after an annotation-xml end tag, in desc inside svg inside math and in mglyph inside mi; stray end tags inside mi and annotation-xml frames, the end tag of an annotation-xml nested inside one, and `</p>` in svg inside mi. Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f52fa37 commit 48aba8c

2 files changed

Lines changed: 141 additions & 27 deletions

File tree

‎packages/parse5-sax-parser/lib/parser-feedback-simulator.ts‎

Lines changed: 87 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ const LINE_FEED_CODE_POINT = 0x0a;
1818
*/
1919
export class ParserFeedbackSimulator implements TokenHandler {
2020
private namespaceStack: html.NS[] = [];
21+
/** The name of the tag that opened each namespace frame, lowercase as in end tags; its end tag closes the frame. */
22+
private frameTags: string[] = [];
23+
/**
24+
* Above 0 while the current node is the element that opened the last frame; each further count is a frame below
25+
* whose element is the parent of the next frame's, so the current node stays known as the frames close.
26+
*/
27+
private directFrames = 0;
2128
public inForeignContent = false;
2229
public skipNextNewLine = false;
2330
public tokenizer: Tokenizer;
@@ -27,7 +34,7 @@ export class ParserFeedbackSimulator implements TokenHandler {
2734
private handler: TokenHandler,
2835
) {
2936
this.tokenizer = new Tokenizer(options, this);
30-
this._enterNamespace(html.NS.HTML);
37+
this._enterNamespace(html.NS.HTML, '');
3138
}
3239

3340
/** @internal */
@@ -85,14 +92,18 @@ export class ParserFeedbackSimulator implements TokenHandler {
8592
}
8693

8794
//Namespace stack mutations
88-
private _enterNamespace(namespace: html.NS): void {
95+
private _enterNamespace(namespace: html.NS, tagName: string): void {
8996
this.namespaceStack.push(namespace);
97+
this.frameTags.push(tagName);
98+
this.directFrames++;
9099
this.inForeignContent = namespace !== html.NS.HTML;
91100
this.tokenizer.inForeignNode = this.inForeignContent;
92101
}
93102

94103
private _leaveCurrentNamespace(): void {
95104
this.namespaceStack.pop();
105+
this.frameTags.pop();
106+
if (this.directFrames > 0) this.directFrames--;
96107
this.inForeignContent = this.namespaceStack[this.namespaceStack.length - 1] !== html.NS.HTML;
97108
this.tokenizer.inForeignNode = this.inForeignContent;
98109
}
@@ -130,14 +141,39 @@ export class ParserFeedbackSimulator implements TokenHandler {
130141
/** @internal */
131142
onStartTag(token: Token.TagToken): void {
132143
let tn = token.tagID;
144+
const frames = this.namespaceStack.length;
145+
const ns = this.namespaceStack[frames - 1];
133146

134147
switch (tn) {
135-
case $.SVG: {
136-
this._enterNamespace(html.NS.SVG);
148+
case $.SVG:
149+
case $.MATH: {
150+
const target = tn === $.SVG ? html.NS.SVG : html.NS.MATHML;
151+
152+
// Foreign content keeps these in its namespace, except svg in annotation-xml. Unless the current node is
153+
// the frame's element, it may be annotation-xml or outside the frame: switch, as a guess nothing builds on.
154+
if (ns === html.NS.HTML || ns === target) {
155+
this._enterNamespace(target, token.tagName);
156+
} else if (this.directFrames === 0) {
157+
this._enterNamespace(target, token.tagName);
158+
this.directFrames = 0;
159+
}
137160
break;
138161
}
139-
case $.MATH: {
140-
this._enterNamespace(html.NS.MATHML);
162+
case $.MGLYPH:
163+
case $.MALIGNMARK: {
164+
// A MathML text integration point keeps these children in MathML.
165+
if (
166+
this.directFrames > 0 &&
167+
this.namespaceStack[frames - 2] === html.NS.MATHML &&
168+
foreignContent.isIntegrationPoint(
169+
html.getTagID(this.frameTags[frames - 1]),
170+
html.NS.MATHML,
171+
[],
172+
html.NS.MATHML,
173+
)
174+
) {
175+
this._enterNamespace(html.NS.MATHML, token.tagName);
176+
}
141177
break;
142178
}
143179
default:
@@ -146,8 +182,11 @@ export class ParserFeedbackSimulator implements TokenHandler {
146182

147183
if (this.inForeignContent) {
148184
if (foreignContent.causesExit(token)) {
149-
this._leaveCurrentNamespace();
185+
// Tree construction pops foreign elements up to an HTML element or integration point.
186+
while (this.inForeignContent) this._leaveCurrentNamespace();
187+
this.directFrames = 0;
150188
} else {
189+
const { tagName } = token;
151190
const currentNs = this.namespaceStack[this.namespaceStack.length - 1];
152191

153192
if (currentNs === html.NS.MATHML) {
@@ -161,11 +200,23 @@ export class ParserFeedbackSimulator implements TokenHandler {
161200

162201
tn = token.tagID;
163202

164-
if (!token.selfClosing && foreignContent.isIntegrationPoint(tn, currentNs, token.attrs)) {
165-
this._enterNamespace(html.NS.HTML);
203+
// Unless the switch above opened a frame for it, the element is an integration point or a new current node.
204+
if (!token.selfClosing && this.namespaceStack.length === frames) {
205+
if (foreignContent.isIntegrationPoint(tn, currentNs, token.attrs)) {
206+
this._enterNamespace(html.NS.HTML, tagName);
207+
} else {
208+
this.directFrames = 0;
209+
}
166210
}
167211
}
168212
} else {
213+
// An HTML element named like the integration point closes before it does, so it gets a frame of its own.
214+
if (token.tagName === this.frameTags[frames - 1]) {
215+
this._enterNamespace(html.NS.HTML, token.tagName);
216+
} else {
217+
this.directFrames = 0;
218+
}
219+
169220
switch (tn) {
170221
case $.PRE:
171222
case $.TEXTAREA:
@@ -185,34 +236,43 @@ export class ParserFeedbackSimulator implements TokenHandler {
185236
this._ensureTokenizerMode(tn);
186237
}
187238

239+
// Tree construction pops a self-closing foreign element at once, so a frame it opened ends with the tag.
240+
if (token.selfClosing && this.inForeignContent && this.namespaceStack.length > frames) {
241+
this._leaveCurrentNamespace();
242+
}
243+
188244
this.handler.onStartTag(token);
189245
}
190246

191247
/** @internal */
192248
onEndTag(token: Token.TagToken): void {
193-
let tn = token.tagID;
249+
const tn = token.tagID;
250+
const frames = this.frameTags.length;
194251

195252
if (!this.inForeignContent) {
196-
const previousNs =
197-
this.namespaceStack.length > 1 ? this.namespaceStack[this.namespaceStack.length - 2] : undefined;
198-
199-
if (previousNs === html.NS.SVG) {
200-
const adjustedTagName = foreignContent.SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);
201-
202-
if (adjustedTagName) {
203-
tn = html.getTagID(adjustedTagName);
204-
}
253+
// Leaving an integration point: only the end tag of the element that opened the HTML frame closes it.
254+
if (token.tagName === this.frameTags[frames - 1]) {
255+
this._leaveCurrentNamespace();
256+
} else {
257+
this.directFrames = 0;
205258
}
259+
} else if (tn === $.P || tn === $.BR) {
260+
// These end tags leave foreign content, as the start tags of `causesExit` do.
261+
while (this.inForeignContent) this._leaveCurrentNamespace();
262+
} else {
263+
// The frame's own end tag closes it; an mglyph or malignmark frame sits directly in its text integration
264+
// point, a MathML element, so the end tags of that element and of the next frame's below close it too.
265+
const tag = this.frameTags[frames - 1];
266+
const last = tag === html.TAG_NAMES.MGLYPH || tag === html.TAG_NAMES.MALIGNMARK ? frames - 3 : frames - 1;
267+
let i = frames - 1;
206268

207-
//NOTE: check for exit from integration point
208-
if (previousNs !== undefined && foreignContent.isIntegrationPoint(tn, previousNs, token.attrs)) {
209-
this._leaveCurrentNamespace();
269+
while (i >= last && token.tagName !== this.frameTags[i]) i--;
270+
271+
if (i >= last) {
272+
while (this.frameTags.length > i) this._leaveCurrentNamespace();
273+
} else {
274+
this.directFrames = 0;
210275
}
211-
} else if (
212-
(tn === $.SVG && this.namespaceStack[this.namespaceStack.length - 1] === html.NS.SVG) ||
213-
(tn === $.MATH && this.namespaceStack[this.namespaceStack.length - 1] === html.NS.MATHML)
214-
) {
215-
this._leaveCurrentNamespace();
216276
}
217277

218278
// NOTE: adjust end tag name as well for consistency

‎packages/parse5-sax-parser/test/sax-parser.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,60 @@ it('adds no replacement character after flushed null characters in foreign conte
223223
assert.equal(actual, '\uFFFDx');
224224
});
225225

226+
it.each([
227+
['svg', '<svg/>'],
228+
['math', '<math/>'],
229+
['repeated svg', '<svg/><svg/><svg/>'],
230+
['svg inside math', '<math><svg/></math>'],
231+
])('leaves the namespace of a self-closing %s root', async (_name, prefix) => {
232+
const parser = new SAXParser();
233+
const events: string[] = [];
234+
parser.on('comment', ({ text }) => events.push(`comment:${text}`));
235+
parser.on('text', ({ text }) => events.push(`text:${text}`));
236+
parser.end(`${prefix}<![CDATA[x]]>`);
237+
await finished(parser);
238+
// Back in HTML content, a CDATA section is a bogus comment rather than text.
239+
assert.deepEqual(events, ['comment:[CDATA[x]]']);
240+
});
241+
242+
it.each([
243+
[
244+
'after the end tag of an annotation-xml integration point',
245+
'<math><annotation-xml encoding="text/html"></annotation-xml>',
246+
],
247+
['in desc inside svg inside math', '<math><svg><desc>'],
248+
['in mglyph inside mi', '<math><mi><mglyph>'],
249+
])('tokenizes MathML content %s', async (_name, prefix) => {
250+
const parser = new SAXParser();
251+
const events: string[] = [];
252+
parser.on('comment', ({ text }) => events.push(`comment:${text}`));
253+
parser.on('text', ({ text }) => events.push(`text:${text}`));
254+
parser.end(`${prefix}<![CDATA[x]]>`);
255+
await finished(parser);
256+
// In MathML content, a CDATA section is text, as tree construction sees it.
257+
assert.deepEqual(events, ['text:x']);
258+
});
259+
260+
it.each([
261+
['mo end tag inside mi', '<math><mi></mo>'],
262+
['mi end tag inside annotation-xml', '<math><annotation-xml encoding="text/html"></mi>'],
263+
[
264+
'end tag of a nested HTML annotation-xml',
265+
'<math><annotation-xml encoding="text/html"><annotation-xml></annotation-xml>',
266+
],
267+
['p end tag in svg inside mi', '<math><mi><svg></p>'],
268+
])("keeps an HTML integration-point frame open for another element's end tag: %s", async (_name, prefix) => {
269+
const parser = new SAXParser();
270+
const events: string[] = [];
271+
parser.on('comment', ({ text }) => events.push(`comment:${text}`));
272+
parser.on('text', ({ text }) => events.push(`text:${text}`));
273+
parser.end(`${prefix}<![CDATA[x]]>`);
274+
await finished(parser);
275+
// Tree construction ignores a stray end tag or closes the nested element with it, so the CDATA section is still a
276+
// bogus comment in HTML content.
277+
assert.deepEqual(events, ['comment:[CDATA[x]]']);
278+
});
279+
226280
it('only skips the first newline after pre, even when whitespace is flushed', async () => {
227281
const parser = new SAXParser();
228282
let text = '';

0 commit comments

Comments
 (0)