Skip to content

Commit 7978462

Browse files
perf(css): read declaration properties off the node in the minifier passes (#22886)
* refactor(css): give a declaration node its property id Step 1 of reading node fields instead of printed text: `_propertyIdOf` returns the canonical `_declarationTable` id of a declaration's property (case folded, escapes and aliases resolved; -1 custom, -2 unknown). It is looked up on first read and kept in the declaration's free `aux1` slot behind a private `_flags` bit, which `_makeContainer` already clears, so parsing writes nothing for it. The lookup hashes the name in place against an open-addressed table, so an unescaped name allocates nothing. * fix(css): keep the property id's flag off the memo's bits Bits 8 and 16 of a declaration's flags already mark a memo-printed value, so a memo hit made `_propertyIdOf` return a stale `aux1`. Use bit 32. * refactor(css): read a declaration's property off its node in three passes The longhand fold, the dead-write pass and the declaration order read the property from the node instead of slicing the printed text, wherever the text is still the one the declaration printed (a reference check) and its name has no escape; anything a pass rewrote keeps reading the text. The node now caches the spelling id (`_spellingIdOf`), which the order pass ranks by, and `_propertyIdOf` resolves aliases from it. * chore: add a changeset for the CSS minifier property ids
1 parent 8e4b437 commit 7978462

3 files changed

Lines changed: 229 additions & 23 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Speed up CSS minification by reading declaration properties off the parsed nodes.

‎lib/css/syntax-parser.js‎

Lines changed: 188 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1839,7 +1839,8 @@ const _takeList = () =>
18391839
// extras, and child lists on three object arrays. Aux slot meaning by type:
18401840
// url: aux0 contentStart, aux1 contentEnd
18411841
// function: aux0 nameEnd
1842-
// declaration: aux0 nameEnd, flags bit0 important
1842+
// declaration: aux0 nameEnd, flags bit0 important, aux1 spelling id once
1843+
// `_FLAG_PROPERTY_ID_READ` says it was read (see `_spellingIdOf`)
18431844
// at-rule: aux0 nameEnd, aux1 blockStart (blockEnd == end)
18441845
// qualified: aux1 blockStart (blockEnd == end)
18451846
// `name` / `nameStart` / a simple block's `token` are derived from the source
@@ -2027,6 +2028,109 @@ const _rulesOf = (n) => {
20272028
* @returns {boolean} whether a declaration is `!important`
20282029
*/
20292030
const _isImportant = (n) => (_flags[_nodeIndex(n)] & Flag.important) !== 0;
2031+
2032+
/**
2033+
* The `_declarationTable` number of the property a declaration's name spells:
2034+
* case folded and escapes resolved; -1 custom, -2 a name it does not know.
2035+
* @param {Node} n declaration
2036+
* @returns {number} the spelling id, looked up on first read
2037+
*/
2038+
const _spellingIdOf = (n) => {
2039+
const i = _nodeIndex(n);
2040+
if ((_flags[i] & _FLAG_PROPERTY_ID_READ) !== 0) return _aux1[i];
2041+
const id = _S._input.startsWith("--", _starts[i]) ? -1 : _lookUpSpellingId(i);
2042+
_aux1[i] = id;
2043+
_flags[i] |= _FLAG_PROPERTY_ID_READ;
2044+
return id;
2045+
};
2046+
2047+
/**
2048+
* The canonical `_declarationTable` number of a declaration's property: its
2049+
* spelling's, with aliases resolved; -1 custom, -2 a name it does not know.
2050+
* @param {Node} n declaration
2051+
* @returns {number} the property id
2052+
*/
2053+
const _propertyIdOf = (n) => {
2054+
const id = _spellingIdOf(n);
2055+
return id < 0 ? id : _declarationTable().canonical[id];
2056+
};
2057+
2058+
/**
2059+
* A declaration's spelling id while `text` is still what it printed as, its
2060+
* name unescaped. Compared by reference: the text is a rope, which reading it
2061+
* by `charCodeAt` walks per call.
2062+
* @param {Node} item a declaration of a block
2063+
* @param {string} text its text as a pass now holds it, not empty
2064+
* @param {PrintContext} writer the print context holding what each item printed
2065+
* @returns {number} the spelling id, or -3 where only the text can say
2066+
*/
2067+
const _ownSpellingId = (item, text, writer) => {
2068+
const i = _nodeIndex(item);
2069+
if (text !== writer.get(item)) return -3;
2070+
const id = _spellingIdOf(item);
2071+
return (_flags[i] & _FLAG_NAME_ESCAPED) === 0 ? id : -3;
2072+
};
2073+
2074+
/**
2075+
* `_spellingIdOf` of a declaration not written `--`, read in place from the
2076+
* input, so a name written without escapes allocates nothing.
2077+
* @param {number} i the declaration's node id
2078+
* @returns {number} the spelling id, -1 custom or -2 unknown
2079+
*/
2080+
const _lookUpSpellingId = (i) => {
2081+
const input = _S._input;
2082+
const start = _starts[i];
2083+
const end = _aux0[i];
2084+
const table = _declarationTable();
2085+
let hash = _NAME_HASH_SEED;
2086+
for (let at = start; at < end; at++) {
2087+
const cc = input.charCodeAt(at);
2088+
if (cc === CC_REVERSE_SOLIDUS || cc > 127) {
2089+
const written = input.slice(start, end);
2090+
if (written.includes("\\")) _flags[i] |= _FLAG_NAME_ESCAPED;
2091+
return _spellingIdOfName(table, written);
2092+
}
2093+
hash = _nameHashStep(
2094+
hash,
2095+
cc >= CC_UPPER_A && cc <= CC_UPPER_Z ? cc | 0x20 : cc
2096+
);
2097+
}
2098+
const { slots, names } = table;
2099+
const length = end - start;
2100+
for (let slot = hash & table.mask; ; slot = (slot + 1) & table.mask) {
2101+
const entry = slots[slot];
2102+
if (entry === 0) return -2;
2103+
const name = names[entry - 1];
2104+
if (name.length !== length) continue;
2105+
let at = 0;
2106+
while (at < length) {
2107+
const cc = input.charCodeAt(start + at);
2108+
const folded = cc >= CC_UPPER_A && cc <= CC_UPPER_Z ? cc | 0x20 : cc;
2109+
if (folded !== name.charCodeAt(at)) break;
2110+
at++;
2111+
}
2112+
if (at === length) return entry - 1;
2113+
}
2114+
};
2115+
2116+
/**
2117+
* `_lookUpSpellingId` for a name written with an escape or a non-ASCII character.
2118+
* @param {DeclarationTable} table the numbering
2119+
* @param {string} written the name as written
2120+
* @returns {number} the spelling id, -1 custom or -2 unknown
2121+
*/
2122+
const _spellingIdOfName = (table, written) => {
2123+
const name = unescapeIdentifier(written);
2124+
if (name.startsWith("--")) return -1;
2125+
const id = table.ids.get(toLowerCaseIfNeeded(name));
2126+
return id === undefined ? -2 : id;
2127+
};
2128+
2129+
// FNV-1a over a name's char codes, which `_declarationTable` and
2130+
// `_lookUpSpellingId` must agree on.
2131+
const _NAME_HASH_SEED = 0x811c9dc5 | 0;
2132+
/** @type {(hash: number, cc: number) => number} */
2133+
const _nameHashStep = (hash, cc) => Math.imul(hash ^ cc, 0x01000193);
20302134
// Raw token value (the lazy `Token.value` form): hash / at-keyword drop their
20312135
// one-char prefix, url uses its content range. Shared by the parser's
20322136
// mid-parse reads and the accessor.
@@ -5235,6 +5339,12 @@ const _walkRule = (node, parent, index, writer) => {
52355339
// value is one component, which is all a box merge reads of them.
52365340
const _FLAG_MEMO_PRINTED = 8;
52375341
const _FLAG_SINGLE_VALUE = 16;
5342+
// That `aux1` holds the declaration's spelling id. Looked up on first read
5343+
// rather than at parse, which would cost every declaration; `_makeContainer`
5344+
// clears it, so parsing writes nothing for it.
5345+
const _FLAG_PROPERTY_ID_READ = 32;
5346+
// Set with it when the name has an escape, so it may print spelled otherwise.
5347+
const _FLAG_NAME_ESCAPED = 64;
52385348

52395349
/**
52405350
* Whether a declaration's value is one component, as `_valueComponents` splits
@@ -14058,9 +14168,10 @@ const _expandBox = (value, slots) => {
1405814168
* @param {Node[]} items the block's children
1405914169
* @param {string[]} texts their printed text, rewritten in place
1406014170
* @param {Set<number>} superseded the indices already dropped, added to here
14171+
* @param {PrintContext} writer the print context holding what each item printed
1406114172
* @returns {void}
1406214173
*/
14063-
const _foldFollowingLonghands = (path, items, texts, superseded) => {
14174+
const _foldFollowingLonghands = (path, items, texts, superseded, writer) => {
1406414175
let shorthand = -1;
1406514176
/** @type {Set<string> | null} */
1406614177
let written = null;
@@ -14103,8 +14214,12 @@ const _foldFollowingLonghands = (path, items, texts, superseded) => {
1410314214
const propertyAt = (at) => {
1410414215
let property = properties[at];
1410514216
if (property === undefined) {
14106-
const printed = _printedProperty(texts[at], texts[at].indexOf(":"));
14107-
const id = table.ids.get(printed);
14217+
const own = _ownSpellingId(items[at], texts[at], writer);
14218+
const printed =
14219+
own >= 0
14220+
? table.names[own]
14221+
: _printedProperty(texts[at], texts[at].indexOf(":"));
14222+
const id = own >= 0 ? own : table.ids.get(printed);
1410814223
if (id === undefined) {
1410914224
property = printed;
1411014225
ids[at] = -1;
@@ -16960,7 +17075,11 @@ const _lastDeclarationCloses = (declarations) => {
1696017075
const _orderJoinedDeclarations = (declarations, plain) => {
1696117076
if (!plain || !_S._transforms.reorderDeclarations) return declarations;
1696217077
if (declarations.length < 2) return declarations;
16963-
const order = _declarationOrder(declarations.map((one) => one.text));
17078+
const order = _declarationOrder(
17079+
declarations.map((one) => one.text),
17080+
null,
17081+
null
17082+
);
1696417083
return order === null ? declarations : order.map((at) => declarations[at]);
1696517084
};
1696617085

@@ -18561,11 +18680,20 @@ const _customWriteDead = (path, earlier, later, keyframe) => {
1856118680
* @param {string[]} texts each item's printed text
1856218681
* @param {Set<number>} superseded where a dead item's index is added
1856318682
* @param {boolean} keyframe whether the block is a keyframe
18683+
* @param {PrintContext} writer the print context holding what each item printed
1856418684
* @returns {void}
1856518685
*/
18566-
const _supersedeByPairs = (path, items, texts, superseded, keyframe) => {
18686+
const _supersedeByPairs = (
18687+
path,
18688+
items,
18689+
texts,
18690+
superseded,
18691+
keyframe,
18692+
writer
18693+
) => {
1856718694
const properties = _pairProperties;
1856818695
const gone = _pairGone;
18696+
const table = _declarationTable();
1856918697
// Where the run of declarations since the last nested rule starts: a rule
1857018698
// parts the ones either side of it into their own places in the cascade.
1857118699
let segment = 0;
@@ -18607,7 +18735,9 @@ const _supersedeByPairs = (path, items, texts, superseded, keyframe) => {
1860718735
}
1860818736
continue;
1860918737
}
18610-
const property = _printedProperty(text, colon);
18738+
const own = _ownSpellingId(items[i], text, writer);
18739+
const property =
18740+
own >= 0 ? table.names[own] : _printedProperty(text, colon);
1861118741
properties[i] = property;
1861218742
let value = "";
1861318743
let names = false;
@@ -18850,27 +18980,44 @@ const _writesOnlyDeclarations = (path, items, texts) => {
1885018980
* it stands, then the ranked ones family by family, so blocks setting the same
1885118981
* things read alike. Null keeps the block as written — a property no dataset
1885218982
* names, or two declarations whose order can decide what is read, would move.
18853-
* @param {string[]} texts the declarations as printed
18983+
* @param {string[]} texts the declarations as printed, or a block's item texts
18984+
* @param {Node[] | null} items the block's items, read by `_ownSpellingId`
18985+
* @param {number[] | null} indices which of `texts` are the declarations, or null for all
18986+
* @param {PrintContext=} writer the print context, given with `items`
1885418987
* @returns {number[] | null} where each comes from, or null to keep them as written
1885518988
*/
18856-
const _declarationOrder = (texts) => {
18989+
const _declarationOrder = (texts, items, indices, writer) => {
1885718990
const table = _declarationTable();
1885818991
/** @type {number[]} */
1885918992
const properties = [];
1886018993
/** @type {number[]} */
1886118994
const rankOf = [];
1886218995
let ranked = false;
18863-
for (const text of texts) {
18864-
const colon = text.indexOf(":");
18865-
if (colon <= 0) return null;
18866-
const property = toLowerCaseIfNeeded(text.slice(0, colon));
18867-
if (property.startsWith("--")) {
18996+
const count = indices === null ? texts.length : indices.length;
18997+
for (let k = 0; k < count; k++) {
18998+
const at = indices === null ? k : indices[k];
18999+
let id =
19000+
items === null
19001+
? -3
19002+
: _ownSpellingId(
19003+
items[at],
19004+
texts[at],
19005+
/** @type {PrintContext} */ (writer)
19006+
);
19007+
if (id === -3) {
19008+
const text = texts[at];
19009+
const colon = text.indexOf(":");
19010+
if (colon <= 0) return null;
19011+
const property = toLowerCaseIfNeeded(text.slice(0, colon));
19012+
const known = table.ids.get(property);
19013+
id = property.startsWith("--") ? -1 : known === undefined ? -2 : known;
19014+
}
19015+
if (id === -1) {
1886819016
properties.push(-1);
1886919017
rankOf.push(-1);
1887019018
continue;
1887119019
}
18872-
const id = table.ids.get(property);
18873-
if (id === undefined) return null;
19020+
if (id === -2) return null;
1887419021
const rank = table.ranks[id];
1887519022
if (rank !== -1) ranked = true;
1887619023
properties.push(table.canonical[id]);
@@ -18925,6 +19072,8 @@ const _declarationOrder = (texts) => {
1892519072
* @property {string[]} names the property each number stands for
1892619073
* @property {number} all the number of `all`
1892719074
* @property {Uint8Array} matters `_orderMatters` by `a * names.length + b`: 0 unknown, 1 no, 2 yes
19075+
* @property {Int32Array} slots open-addressed by `_nameHashStep` of each name: its number + 1, 0 empty
19076+
* @property {number} mask `slots.length - 1`
1892819077
*/
1892919078

1893019079
/** @type {DeclarationTable | undefined} */
@@ -18951,13 +19100,28 @@ const _declarationTable = () => {
1895119100
const id = ids.get(_canonicalProperty(names[i]));
1895219101
canonical[i] = id === undefined ? i : id;
1895319102
}
19103+
let size = 1;
19104+
while (size < names.length * 4) size *= 2;
19105+
const slots = new Int32Array(size);
19106+
for (let i = 0; i < names.length; i++) {
19107+
const name = names[i];
19108+
let hash = _NAME_HASH_SEED;
19109+
for (let at = 0; at < name.length; at++) {
19110+
hash = _nameHashStep(hash, name.charCodeAt(at));
19111+
}
19112+
let slot = hash & (size - 1);
19113+
while (slots[slot] !== 0) slot = (slot + 1) & (size - 1);
19114+
slots[slot] = i + 1;
19115+
}
1895419116
_declarationTableValue = {
1895519117
ids,
1895619118
ranks,
1895719119
canonical,
1895819120
names,
1895919121
all: /** @type {number} */ (ids.get("all")),
18960-
matters: new Uint8Array(names.length * names.length)
19122+
matters: new Uint8Array(names.length * names.length),
19123+
slots,
19124+
mask: size - 1
1896119125
};
1896219126
return _declarationTableValue;
1896319127
};
@@ -19201,7 +19365,7 @@ const _composeBlockBody = (
1920119365
}
1920219366
}
1920319367
if (items.length <= _PAIRWISE_ITEMS) {
19204-
_supersedeByPairs(path, items, texts, superseded, keyframe);
19368+
_supersedeByPairs(path, items, texts, superseded, keyframe, writer);
1920519369
} else {
1920619370
/** @type {Map<string, number>} */
1920719371
const seen = new Map();
@@ -19294,7 +19458,7 @@ const _composeBlockBody = (
1929419458
// After the supersedes: a declaration a later one already made dead is
1929519459
// no shorthand to fold into, and folding never makes one dead.
1929619460
if (foldLonghands) {
19297-
_foldFollowingLonghands(path, items, texts, superseded);
19461+
_foldFollowingLonghands(path, items, texts, superseded, writer);
1929819462
}
1929919463
// A dead child parts nothing, so the two that stood either side of one
1930019464
// are adjacent in what goes out and join there rather than a pass later.
@@ -19543,8 +19707,8 @@ const _composeBlockBody = (
1954319707
_writesOnlyDeclarations(path, items, texts)
1954419708
? []
1954519709
: null;
19546-
/** @type {string[]} */
19547-
const pieceTexts = [];
19710+
/** @type {number[]} */
19711+
const pieceAt = [];
1954819712
// The body before its last piece, and that piece: the `;` a `}` makes
1954919713
// redundant is cut off the piece, as reading the body's end would flatten it.
1955019714
let prior = "";
@@ -19585,7 +19749,7 @@ const _composeBlockBody = (
1958519749
}
1958619750
if (pieces !== null) {
1958719751
pieces.push(body + text);
19588-
pieceTexts.push(texts[i]);
19752+
pieceAt.push(i);
1958919753
body = "";
1959019754
continue;
1959119755
}
@@ -19600,7 +19764,7 @@ const _composeBlockBody = (
1960019764
}
1960119765
}
1960219766
if (pieces !== null) {
19603-
const order = _declarationOrder(pieceTexts);
19767+
const order = _declarationOrder(texts, items, pieceAt, writer);
1960419768
for (let i = 0; i < pieces.length; i++) {
1960519769
prior = body;
1960619770
last = pieces[order === null ? i : order[i]];
@@ -20743,6 +20907,7 @@ module.exports._trimCssWhiteSpace = _trimCssWhiteSpace;
2074320907
module.exports._declarationsOf = _declarationsOf;
2074420908
module.exports._rulesOf = _rulesOf;
2074520909
module.exports._isImportant = _isImportant;
20910+
module.exports._propertyIdOf = _propertyIdOf;
2074620911
module.exports._rawValue = _rawValue;
2074720912
module.exports._S = _S;
2074820913
module.exports._SEP = _SEP;

0 commit comments

Comments
 (0)