Skip to content

Commit 6c705d5

Browse files
fb55claude
andcommitted
perf(parser): read attributes once, only for annotation-xml integration points
The integration-point check read the attribute list of every foreign element to decide whether it is an HTML integration point, but only MathML `annotation-xml` needs the `encoding` attribute. It also read that element's list every time it was asked: after each pop back to it, for each `mglyph` or `malignmark` start tag and each foreign-content exit while it is current, and for a fragment context after each pop to the root. With the htmlparser2 adapter, which materialises the list on each call, a foreign element with many attributes made every check allocate them again, and an `annotation-xml` with N attributes and N children made N + 1 reads of N attributes (N = 8000 took 7 s). The list is now read only for `annotation-xml`, and the verdict is kept for each open `annotation-xml` element and dropped when the element is popped, so the list is read once per element. Changing `encoding` on an open `annotation-xml` element (from a `ParserStream` `script` listener), or on a fragment context after its parser is created, no longer changes the verdict: the HTML Standard (https://html.spec.whatwg.org/multipage/parsing.html#html-integration-point) defines it by "a MathML annotation-xml element whose start tag token had an attribute with the name "encoding" whose value was an ASCII case-insensitive match for "text/html"", and a fragment context's start tag token is made from its attributes when parsing starts. The tests count attribute reads for other foreign elements, for children, `</p>` end tags, stack edits and the fragment context, keep the MathML-only check from answering for `annotation-xml`, and pin the start-tag decision through a `script` listener. Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2059146 commit 6c705d5

4 files changed

Lines changed: 152 additions & 5 deletions

File tree

‎packages/parse5-parser-stream/test/scripting.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { it } from 'vitest';
1+
import { it, assert } from 'vitest';
2+
import { serialize, type DefaultTreeAdapterTypes } from 'parse5';
23
import { ParserStream } from '../lib/index.js';
34
import { generateParsingTests } from 'parse5-test-utils/utils/generate-parsing-tests.js';
45
import { makeChunks, generateTestsForEachTreeAdapter, finished } from 'parse5-test-utils/utils/common.js';
@@ -79,3 +80,21 @@ generateTestsForEachTreeAdapter('ParserStream', (treeAdapter) => {
7980
return finished(parser);
8081
});
8182
});
83+
84+
it('decides an annotation-xml integration point from its start tag', async () => {
85+
const parser = new ParserStream();
86+
87+
parser.on('script', (scriptElement, _documentWrite, resume) => {
88+
(scriptElement.parentNode as DefaultTreeAdapterTypes.Element).attrs[0].value = 'application/xml';
89+
resume();
90+
});
91+
92+
parser.end('<math><annotation-xml encoding=text/html><script></script><x-a/>TAIL<![CDATA[x]]>');
93+
await finished(parser);
94+
95+
// The script edits `encoding` after the start tag, so the element stays an HTML integration point.
96+
assert.strictEqual(
97+
serialize(parser.document),
98+
'<html><head></head><body><math><annotation-xml encoding="application/xml"><script></script><x-a>TAIL<!--[CDATA[x]]--></x-a></annotation-xml></math></body></html>',
99+
);
100+
});

‎packages/parse5/lib/common/foreign-content.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ function isMathMLTextIntegrationPoint(tn: $, ns: NS): boolean {
233233
return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT);
234234
}
235235

236-
function isHtmlIntegrationPoint(tn: $, ns: NS, attrs: Attribute[]): boolean {
236+
function isHtmlIntegrationPoint(tn: $, ns: NS, attrs: readonly Attribute[]): boolean {
237237
if (ns === NS.MATHML && tn === $.ANNOTATION_XML) {
238238
for (let i = 0; i < attrs.length; i++) {
239239
if (attrs[i].name === ATTRS.ENCODING) {
@@ -247,7 +247,7 @@ function isHtmlIntegrationPoint(tn: $, ns: NS, attrs: Attribute[]): boolean {
247247
return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE);
248248
}
249249

250-
export function isIntegrationPoint(tn: $, ns: NS, attrs: Attribute[], foreignNS?: NS): boolean {
250+
export function isIntegrationPoint(tn: $, ns: NS, attrs: readonly Attribute[], foreignNS?: NS): boolean {
251251
return (
252252
((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) ||
253253
((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns))

‎packages/parse5/lib/parser/index.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ import {
3434
//Misc constants
3535
const HIDDEN_INPUT_TYPE = 'hidden';
3636

37+
// For the integration-point check of elements whose attributes do not matter; never attached to a node.
38+
const EMPTY_ATTRS: readonly Attribute[] = [];
39+
3740
//Adoption agency loops iteration count
3841
const AA_OUTER_LOOP_ITER = 8;
3942
const AA_INNER_LOOP_ITER = 3;
@@ -292,6 +295,7 @@ export class Parser<T extends TreeAdapterTypeMap> implements TokenHandler, Stack
292295
}
293296

294297
this.treeAdapter.onItemPop?.(node, this.openElements.current);
298+
this.annotationXmlIntegrationPoints?.delete(node);
295299

296300
if (isTop) {
297301
let current;
@@ -667,12 +671,29 @@ export class Parser<T extends TreeAdapterTypeMap> implements TokenHandler, Stack
667671

668672
//Integration points
669673

674+
/**
675+
* Whether each open MathML `annotation-xml` element, or the fragment context, is an HTML integration point. The
676+
* standard decides this by the element's start tag, so its attributes are read once; `onItemPop` drops the entry.
677+
*/
678+
private annotationXmlIntegrationPoints: Map<T['element'], boolean> | undefined;
679+
670680
/** @protected */
671681
_isIntegrationPoint(tid: $, element: T['element'], foreignNS?: NS): boolean {
672682
const ns = this.treeAdapter.getNamespaceURI(element);
673-
const attrs = this.treeAdapter.getAttrList(element);
674683

675-
return foreignContent.isIntegrationPoint(tid, ns, attrs, foreignNS);
684+
if (tid === $.ANNOTATION_XML && ns === NS.MATHML && foreignNS !== NS.MATHML) {
685+
const verdicts = (this.annotationXmlIntegrationPoints ??= new Map());
686+
let isIntegrationPoint = verdicts.get(element);
687+
688+
if (isIntegrationPoint === undefined) {
689+
isIntegrationPoint = foreignContent.isIntegrationPoint(tid, ns, this.treeAdapter.getAttrList(element));
690+
verdicts.set(element, isIntegrationPoint);
691+
}
692+
693+
return isIntegrationPoint;
694+
}
695+
696+
return foreignContent.isIntegrationPoint(tid, ns, EMPTY_ATTRS, foreignNS);
676697
}
677698

678699
//Active formatting elements reconstruction
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { it, expect } from 'vitest';
2+
import { parse, parseFragment, Parser, html, defaultTreeAdapter, type TreeAdapter } from 'parse5';
3+
import { treeAdapters } from 'parse5-test-utils/utils/common.js';
4+
5+
it.each(Object.entries(treeAdapters) as [string, TreeAdapter][])(
6+
'only reads integration-point attributes for MathML annotation-xml (%s)',
7+
(_name, adapter) => {
8+
let reads = 0;
9+
const treeAdapter: TreeAdapter = {
10+
...adapter,
11+
getAttrList(element) {
12+
reads++;
13+
return adapter.getAttrList(element);
14+
},
15+
};
16+
parse('<svg a="1"><a></a><desc><b></b></desc></svg><math><mi><b></b></mi></math>', { treeAdapter });
17+
expect(reads).toBe(0);
18+
19+
const element = adapter.createElement('annotation-xml', html.NS.MATHML, []);
20+
const encoded = adapter.createElement('annotation-xml', html.NS.MATHML, [
21+
{ name: 'encoding', value: 'text/html' },
22+
]);
23+
const parser = new Parser({ treeAdapter });
24+
expect(parser._isIntegrationPoint(html.TAG_ID.ANNOTATION_XML, element)).toBe(false);
25+
expect(parser._isIntegrationPoint(html.TAG_ID.ANNOTATION_XML, encoded)).toBe(true);
26+
expect(parser._isIntegrationPoint(html.TAG_ID.ANNOTATION_XML, encoded, html.NS.MATHML)).toBe(false);
27+
expect(reads).toBe(2);
28+
},
29+
);
30+
31+
const encodedContext = defaultTreeAdapter.createElement('annotation-xml', html.NS.MATHML, [
32+
{ name: 'encoding', value: 'text/html' },
33+
]);
34+
35+
it.each([
36+
['children of an HTML integration point', '<math><annotation-xml encoding=text/html>', '<i></i>', null],
37+
['children of a plain annotation-xml', '<math><annotation-xml>', '<x></x>', null],
38+
['p end tags', '<math><annotation-xml encoding=text/html>', '</p>', null],
39+
['children of the fragment context', '', '<i></i>', encodedContext],
40+
])('reads the attributes of an annotation-xml element once: %s', (_name, start, repeated, context) => {
41+
let reads = 0;
42+
const treeAdapter: TreeAdapter = {
43+
...defaultTreeAdapter,
44+
getAttrList(element) {
45+
reads++;
46+
return defaultTreeAdapter.getAttrList(element);
47+
},
48+
};
49+
const input = start + repeated.repeat(8);
50+
51+
if (context) parseFragment(context, input, { treeAdapter });
52+
else parse(input, { treeAdapter });
53+
54+
expect(reads).toBe(1);
55+
});
56+
57+
it.each(Object.entries(treeAdapters) as [string, TreeAdapter][])(
58+
'keeps the decision with the element across stack edits (%s)',
59+
(_name, adapter) => {
60+
let reads = 0;
61+
const treeAdapter: TreeAdapter = {
62+
...adapter,
63+
getAttrList(element) {
64+
reads++;
65+
return adapter.getAttrList(element);
66+
},
67+
};
68+
const parser = new Parser({ treeAdapter });
69+
const stack = parser.openElements;
70+
const root = adapter.createElement('html', html.NS.HTML, []);
71+
const encoded = adapter.createElement('annotation-xml', html.NS.MATHML, [
72+
{ name: 'encoding', value: 'text/html' },
73+
]);
74+
const plain = adapter.createElement(
75+
'annotation-xml',
76+
html.NS.MATHML,
77+
Array.from({ length: 64 }, (_, i) => ({ name: `a${i}`, value: 'v' })),
78+
);
79+
stack.push(root, html.TAG_ID.HTML);
80+
stack.push(encoded, html.TAG_ID.ANNOTATION_XML);
81+
expect(parser.tokenizer.inForeignNode).toBe(false);
82+
stack.push(plain, html.TAG_ID.ANNOTATION_XML);
83+
expect(parser.tokenizer.inForeignNode).toBe(true);
84+
stack.pop();
85+
expect(parser.tokenizer.inForeignNode).toBe(false);
86+
stack.insertAfter(root, plain, html.TAG_ID.ANNOTATION_XML);
87+
stack.remove(plain);
88+
stack.replace(encoded, plain);
89+
expect(parser._isIntegrationPoint(html.TAG_ID.ANNOTATION_XML, stack.current)).toBe(false);
90+
stack.push(encoded, html.TAG_ID.ANNOTATION_XML);
91+
stack.shortenToLength(2);
92+
expect(parser.tokenizer.inForeignNode).toBe(true);
93+
stack.push(encoded, html.TAG_ID.ANNOTATION_XML);
94+
stack.popAllUpToHtmlElement();
95+
stack.push(plain, html.TAG_ID.ANNOTATION_XML);
96+
expect(parser.tokenizer.inForeignNode).toBe(true);
97+
// Each element is read on its first check and again on the first check after it was popped.
98+
expect(reads).toBe(5);
99+
},
100+
);
101+
102+
it('decides a fragment context afresh for each parser', () => {
103+
const context = defaultTreeAdapter.createElement('annotation-xml', html.NS.MATHML, []);
104+
expect(Parser.getFragmentParser(context).tokenizer.inForeignNode).toBe(true);
105+
defaultTreeAdapter.adoptAttributes(context, [{ name: 'encoding', value: 'text/html' }]);
106+
expect(Parser.getFragmentParser(context).tokenizer.inForeignNode).toBe(false);
107+
});

0 commit comments

Comments
 (0)