Skip to content

Commit 581d97f

Browse files
authored
fix(css): reach the printer branches the corpus never took, and settle the three it found (#22314)
* fix(css): read a relative hsla() in the space the model holds it under Counting each printer table over every stylesheet on disk found the transform reducers and half the relative-color functions at zero hits, so nothing held them to printing the same bytes twice. A fixture drives every reducer shape beside a value it must decline. Its first run threw: `hsla(from …)` looked its space up under its own name, which the model holds under `hsl()`. * fix(css): fold a fallback's mix and relative reference over the author's arguments A fallback resolved the calls the target cannot read one at a time, so a mix or a relative reference written over one was left for a second pass to fold. It also read the bytes the first pass wrote, and a mix of two colors rounded into eight bits is not the color the mix names. Both settle in one pass now, over the arguments as written and over a call holding a call. * fix(css): ignore recurseBlocks while printing, as skip already is `recurseBlocks: false` threw on every stylesheet it printed, down to `a{color:red}`: a block is printed from its children, and the option is what leaves the walk without any. A writer already reads `skip` that way for the same reason, so it now reads this one the same. The walk keeps it. The option had no test of its own, which is what let the throw stand.
1 parent 74dd5f0 commit 581d97f

6 files changed

Lines changed: 348 additions & 15 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
fold a fallback's colors over the author's arguments, and print with
6+
`recurseBlocks: false` rather than throwing

‎lib/css/syntax-parser.js‎

Lines changed: 71 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4180,7 +4180,7 @@ const TOP_LEVEL_CONSUMERS = {
41804180
/**
41814181
* @typedef {object} CssProcessOptions
41824182
* @property {LocConverter=} locConverter shared loc converter (default a fresh one over the input)
4183-
* @property {boolean=} recurseBlocks walk into block bodies' nested rules (default true)
4183+
* @property {boolean=} recurseBlocks walk into block bodies' nested rules (default true); ignored while printing, as `skip` is, since a block is printed from the children it would leave unread
41844184
* @property {("stylesheet" | "block-contents")=} as which top-level production to consume the source as (see `TOP_LEVEL_CONSUMERS`): `"stylesheet"` (default) or `"block-contents"` (a block's contents, e.g. an HTML `style` attribute)
41854185
* @property {SkipOptions=} skip what the grammar may leave un-materialized to go faster — safe only for parts nothing reads in the active parse; default skip nothing. Ignored while printing (`minimize`), which needs every node
41864186
* @property {boolean=} minimize print the safely-minified serialization (collapsed whitespace, dropped redundant separators, the `printer`'s value transforms) as `process` walks and return `{ code, map }` (default false = walk only, return `undefined`)
@@ -7057,7 +7057,9 @@ const grammar = (input, visitors, writer, options) => {
70577057
_skipActive = _skipTypes !== _NO_SKIP_TYPES;
70587058
_skipSelectorPrelude = skip !== undefined && skip.selectorPrelude === true;
70597059
_skipAtRulePrelude = skip !== undefined && skip.atRulePrelude === true;
7060-
_recurseBlocks = options.recurseBlocks !== false;
7060+
// ...and `recurseBlocks` is ignored there for the same reason: a block body
7061+
// the walk never enters holds no children, and a block is printed from them.
7062+
_recurseBlocks = writer !== undefined || options.recurseBlocks !== false;
70617063
// The walk always streams, there being nothing to trade off: a block under the
70627064
// threshold is collected and walked in one batch as ever. Printing streams
70637065
// with it, so no parent is assembled from text already released.
@@ -9981,9 +9983,12 @@ const _foldRelativeColor = (fn, inner, hexAlpha, forFallback) => {
99819983
write = (/** @type {number[]} */ c) =>
99829984
c.map((byte) => _gammaDecode(byte / 255));
99839985
} else {
9984-
spaceName = fn;
9986+
// `hsla()` states the same channels in the same space `hsl()` does, and
9987+
// the model holds it under that name — which is the name resolving the
9988+
// origin already reads it as, so the two agree on what a color is in.
9989+
spaceName = fn === "hsla" ? "hsl" : fn;
99859990
space = /** @type {import("./data").ColorSpaceModel} */ (
9986-
COLOR_SPACE_MODEL.get(fn)
9991+
COLOR_SPACE_MODEL.get(spaceName)
99879992
);
99889993
conversion = Math.max(conversion, space.conversion);
99899994
channels = space.to(origin.linear).map((c, i) => c * shape.scale[i]);
@@ -10062,6 +10067,61 @@ const _RELATIVE_FROM_RE = /^\s*from(?![-\w])/i;
1006210067
const _FALLBACK_COLOR_FUNCTION_RE =
1006310068
/(^|[^-\w])(hwb|lab|lch|oklab|oklch|color-mix|color)\(([^()]*)\)/gi;
1006410069

10070+
// The name of a call that folds on what it is written over rather than on
10071+
// channels of its own, wherever it stands and whatever it holds — the
10072+
// arguments are not read here. `color-mix` before `color`, which is its prefix.
10073+
const _FALLBACK_WHOLE_CALL_RE =
10074+
/(^|[^-\w])(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color-mix|color)\(/gi;
10075+
10076+
// The `from` a relative reference opens with, which is the whole of what makes
10077+
// one fold on its origin rather than on channels the author wrote out.
10078+
const _RELATIVE_ORIGIN_RE = /^\s*from\s/i;
10079+
10080+
// Whether folding the calls below clamped one into the sRGB gamut, read by the
10081+
// caller: a second result, and no object built per value to carry it.
10082+
let _wholeCallClipped = false;
10083+
10084+
/**
10085+
* The same value with every `color-mix()` and relative reference written as the
10086+
* color it names, read over the arguments the author wrote. Substituting each
10087+
* of those for a byte first would round every one into eight bits, and a mix of
10088+
* those bytes is not the color the mix names.
10089+
* @param {string} value the declaration's value, as printed
10090+
* @returns {string | null} the value, or null where none of them folded
10091+
*/
10092+
const _foldWholeColorCalls = (value) => {
10093+
let out = "";
10094+
let from = 0;
10095+
_wholeCallClipped = false;
10096+
_FALLBACK_WHOLE_CALL_RE.lastIndex = 0;
10097+
for (
10098+
let match = _FALLBACK_WHOLE_CALL_RE.exec(value);
10099+
match !== null;
10100+
match = _FALLBACK_WHOLE_CALL_RE.exec(value)
10101+
) {
10102+
const open = match.index + match[0].length - 1;
10103+
const close = _closingParenthesis(value, open);
10104+
const inner = value.slice(open + 1, close);
10105+
const fn = asciiLowerCaseName(match[2]);
10106+
// Anything else stands as the author wrote it: whether the target reads
10107+
// it is what the pass after this one answers, and this is not here to
10108+
// reopen that.
10109+
if (fn !== "color-mix" && !_RELATIVE_ORIGIN_RE.test(inner)) continue;
10110+
const color = _minifyPolarColorFunction(
10111+
fn,
10112+
inner,
10113+
_S._hexAlphaAllowed,
10114+
true
10115+
);
10116+
if (color === null) continue;
10117+
if (_fallbackClipped) _wholeCallClipped = true;
10118+
out += value.slice(from, match.index + match[1].length) + color;
10119+
from = close + 1;
10120+
_FALLBACK_WHOLE_CALL_RE.lastIndex = from;
10121+
}
10122+
return from === 0 ? null : out + value.slice(from);
10123+
};
10124+
1006510125
/**
1006610126
* Whether a color function is one some target does not read, so a declaration
1006710127
* naming it needs a fallback before it — and a fallback still naming one is no
@@ -10108,9 +10168,13 @@ const _colorFallbackDeclaration = (text, colon) => {
1010810168
// when what it substitutes is unreadable — which is `unset`, not the earlier
1010910169
// declaration — so a pair standing before one is bytes nothing ever reads.
1011010170
if (_hasSubstitution(value)) return null;
10111-
let folded = false;
10112-
let clipped = false;
10113-
const written = value.replace(
10171+
// The calls that fold on what they are written over go first, while their
10172+
// arguments are still the author's: the pass after this one reaches only
10173+
// what holds no call of its own, so it would read bytes this left behind.
10174+
const outer = _foldWholeColorCalls(value);
10175+
let folded = outer !== null;
10176+
let clipped = folded && _wholeCallClipped;
10177+
const written = (outer === null ? value : outer).replace(
1011410178
_FALLBACK_COLOR_FUNCTION_RE,
1011510179
(whole, before, name, inner) => {
1011610180
const fn = asciiLowerCaseName(name);
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
"use strict";
2+
3+
const { SourceProcessor } = require("../../lib/css/syntax");
4+
const { COLD_BRANCHES } = require("../../tooling/compare-css-tools");
5+
6+
// What each rewrite the fixture is there for writes. Every one was counted at
7+
// zero over every stylesheet on disk before the fixture was written, so an edit
8+
// dropping one would take a branch out of reach with it.
9+
const REDUCED = [
10+
["matrix to a scale", "matrix(2,0,0,3,0,0)", "scale(2,3)"],
11+
["matrix to a translate", "matrix(1,0,0,1,10,20)", "translate(10px,20px)"],
12+
["matrix to a quarter turn", "matrix(0,1,-1,0,0,0)", "rotate(90deg)"],
13+
["matrix to three quarters", "matrix(0,-1,1,0,0,0)", "rotate(270deg)"],
14+
[
15+
"matrix3d to a 2D matrix",
16+
"matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,10,20,0,1)",
17+
"translate(10px,20px)"
18+
],
19+
[
20+
"matrix3d to a translate3d",
21+
"matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,10,20,30,1)",
22+
"translate3d(10px,20px,30px)"
23+
],
24+
[
25+
"matrix3d to a scale3d",
26+
"matrix3d(2,0,0,0,0,3,0,0,0,0,4,0,0,0,0,1)",
27+
"scale3d(2,3,4)"
28+
],
29+
["scale3d to a scaleZ", "scale3d(1,1,2)", "scaleZ(2)"]
30+
];
31+
32+
// The value each rewrite must decline, which is what says the guard is read
33+
// rather than the branch alone.
34+
const KEPT = [
35+
["a matrix of no named shape", "matrix(1,2,3,4,5,6)"],
36+
[
37+
"a matrix3d that is a shear",
38+
"matrix3d(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)"
39+
],
40+
["a rotation about no axis", "rotate3d(1,1,0,45deg)"]
41+
];
42+
43+
/**
44+
* @param {string} css a stylesheet
45+
* @param {import("../../lib/css/syntax-parser").CssPrintOptions} options print options
46+
* @returns {string} it, minified
47+
*/
48+
const minify = (css, options) =>
49+
new SourceProcessor().process(css, { mode: "minify", ...options }).code;
50+
51+
describe("compare-css-tools — the cold branches fixture", () => {
52+
it.each(REDUCED)("carries %s", (_name, written) => {
53+
expect(COLD_BRANCHES).toContain(written);
54+
});
55+
56+
it.each(KEPT)("carries %s", (_name, written) => {
57+
expect(COLD_BRANCHES).toContain(written);
58+
});
59+
60+
it.each(REDUCED)("writes %s as the shorter call", (_name, written, into) => {
61+
expect(minify(`a{transform:${written}}`, {})).toBe(`a{transform:${into}}`);
62+
});
63+
64+
it.each(KEPT)("keeps %s", (_name, written) => {
65+
expect(minify(`a{transform:${written}}`, {})).toBe(
66+
`a{transform:${written}}`
67+
);
68+
});
69+
70+
it.each([
71+
["rgb", "rgb(from #808080 r g b)"],
72+
["rgba", "rgba(from #808080 r g b / 0.5)"],
73+
["hsl", "hsl(from #808080 h s l)"],
74+
["hsla", "hsla(from #808080 h s l / 0.5)"],
75+
["hwb", "hwb(from #808080 h w b)"],
76+
["lab", "lab(from #808080 l a b)"],
77+
["lch", "lch(from #808080 l c h)"],
78+
["oklab", "oklab(from #808080 l a b)"],
79+
["oklch", "oklch(from #808080 l c h)"],
80+
["color", "color(from #808080 srgb r g b)"]
81+
])("carries a relative reference through %s", (_name, written) => {
82+
expect(COLD_BRANCHES).toContain(written);
83+
});
84+
85+
it("carries what the fixture reaches beyond the reducers", () => {
86+
// An escaped paren inside an unquoted `url()`, and the column combinator —
87+
// neither is written by any stylesheet the sweep installs.
88+
expect(COLD_BRANCHES).toContain("url(a\\(b\\).png)");
89+
expect(COLD_BRANCHES).toContain(" || ");
90+
// A reference the fold cannot pin down, so the printer keeps the call.
91+
expect(COLD_BRANCHES).toContain("rgb(from currentcolor r g b)");
92+
});
93+
94+
it("is its own output under every preset it is swept with", () => {
95+
for (const options of [
96+
{},
97+
{ environment: { browsers: ["chrome 100", "firefox 100", "safari 15.4"] } }
98+
]) {
99+
const once = minify(COLD_BRANCHES, options);
100+
expect(minify(once, options)).toBe(once);
101+
}
102+
});
103+
});

0 commit comments

Comments
 (0)