diff --git a/src/__tests__/compiler/visitor-returns.test.ts b/src/__tests__/compiler/visitor-returns.test.ts index 7282c1f1..ad0b48f5 100644 --- a/src/__tests__/compiler/visitor-returns.test.ts +++ b/src/__tests__/compiler/visitor-returns.test.ts @@ -73,3 +73,136 @@ test("the first pass hands back only the lengths it converts", () => { { unit: "px", value: 28 }, ]); }); + +function containsNull(value: unknown): boolean { + if (value === null) return true; + if (Array.isArray(value)) return value.some(containsNull); + if (value && typeof value === "object") { + return Object.values(value).some(containsNull); + } + return false; +} + +function containsUnsafeF32Node(value: unknown): boolean { + if (Array.isArray(value)) return value.some(containsUnsafeF32Node); + if (!value || typeof value !== "object") return false; + + const record = value as Record; + const type = record.type; + if ( + type === "length" || + type === "angle" || + type === "time" || + type === "resolution" + ) { + const inner = record.value as { value?: unknown } | undefined; + if ( + typeof inner?.value === "number" && + ((Number.isInteger(inner.value) && + (inner.value < -32768 || inner.value > 65535)) || + !Number.isFinite(inner.value)) + ) { + return true; + } + } + + return Object.values(record).some(containsUnsafeF32Node); +} + +test("the first pass never hands a StyleSheet back, with or without variable inlining", () => { + const css = ` +:root { --a: 10px; } +.a { width: var(--a); border-style: var(--tw-border-style); border-radius: calc(infinity * 1px); } +`; + + compile(css); + compile(css, { inlineVariables: false }); + + const sheetCalls = calls.filter( + (call) => + call.pass === 1 && + (call.visitor === "StyleSheet" || call.visitor === "StyleSheetExit"), + ); + + expect(sheetCalls.length).toBeGreaterThan(0); + expect(sheetCalls.filter((call) => call.returned !== undefined)).toEqual([]); +}); + +test("the first pass hands nothing back for untouched declarations", () => { + compile(` +@layer { .border { border-style: var(--tw-border-style); } } +.rounded-full { border-radius: calc(infinity * 1px); width: 99999px; } +`); + + const firstPassReturned = calls.filter( + (call) => call.pass === 1 && call.returned !== undefined, + ); + + expect(firstPassReturned).toEqual([]); +}); + +test("declarations returned by the first pass contain no null Option fields", () => { + compile(` +:root { --a: 10px; --b: var(--missing); } +.mixed { + margin: var(--a) var(--unknown); + padding: var(--a) env(safe-area-inset-top); + border-width: var(--unknown, var(--a)); + top: var(--b); +} +`); + + const returnedDecls = calls + .filter( + (call) => + call.pass === 1 && + call.visitor === "Declaration" && + call.returned !== undefined, + ) + .map((call) => call.returned); + + expect(returnedDecls.length).toBeGreaterThan(0); + expect(returnedDecls.some(containsNull)).toBe(false); +}); + +test("declarations returned by the first pass rewrite out-of-range integer dimensions as raw dimension tokens", () => { + const sheet = compile(` +:root { --big: 99999px; --neg: -99999px; --rem-big: 70000rem; } +.vars { border-radius: var(--big); margin-left: var(--neg); width: var(--rem-big); } +.transforms { translate: 99999px 0px; rotate: 0 0 1 99999deg; } +`).stylesheet(); + + const returnedDecls = calls + .filter( + (call) => + call.pass === 1 && + call.visitor === "Declaration" && + call.returned !== undefined, + ) + .map((call) => call.returned); + + expect(returnedDecls.length).toBeGreaterThan(0); + expect(returnedDecls.some(containsUnsafeF32Node)).toBe(false); + + const varsRule = sheet.s?.find(([name]) => name === "vars")?.[1]?.[0]; + expect(varsRule?.d).toContainEqual({ + borderRadius: 99999, + marginLeft: -99999, + width: 980000, + }); +}); + +test("same-block variable folding stays scoped to its keyframe block", () => { + const sheet = compile(` +@keyframes grow { + from { --x: 10px; width: var(--x); } + to { height: var(--x); } +} +`).stylesheet(); + + const fromDecls = sheet.k?.[0]?.[1]?.find(([key]) => key === "from")?.[1]; + const toDecls = sheet.k?.[0]?.[1]?.find(([key]) => key === "to")?.[1]; + + expect(fromDecls).toContainEqual(expect.objectContaining({ width: 10 })); + expect(toDecls).toContainEqual([[{}, "var", "x", 1], "height"]); +}); diff --git a/src/compiler/compiler.ts b/src/compiler/compiler.ts index a5ec49e1..12f213b5 100644 --- a/src/compiler/compiler.ts +++ b/src/compiler/compiler.ts @@ -35,7 +35,13 @@ import { round, } from "./declarations"; import { unparseIndividualTransform } from "./individual-transforms"; -import { inlineVariables } from "./inline-variables"; +import { + blockLocalVarNames, + declarationCount, + foldDeclaration, + planVariableInlining, + type VariableInliningPlan, +} from "./inline-variables"; import { extractKeyFrames } from "./keyframes"; import { lightningcssLoader } from "./lightningcss-loader"; import { parseMediaQuery } from "./media-query"; @@ -121,23 +127,30 @@ export function compile( const inlining = options.inlineVariables; + let inliningPlan: VariableInliningPlan | undefined; + let currentLocals: ReadonlySet | undefined; + let remainingInBlock = 0; + let keyframeQueue: + | { locals: ReadonlySet | undefined; remaining: number }[] + | undefined; + let keyframeIndex = 0; + const firstPassVisitor: Visitor = { - // Registered from the first pass, since lightningcss prints only the last @property of a name, valid or not - StyleSheetExit(sheet) { + // Registered from the first pass, since lightningcss prints only the last @property of a name, valid or not. + // Returns nothing so lightningcss never deserializes untouched rules back across the visitor boundary. + StyleSheet(sheet) { const nonInheriting = registerProperties( collectRegistrations(sheet.rules), builder, ); - if (inlining === false) { - return sheet; + if (inlining !== false) { + inliningPlan = planVariableInlining( + sheet, + inlining?.exclude ?? [], + nonInheriting, + ); } - - return inlineVariables( - sheet, - inlining?.exclude ?? [], - nonInheriting, - ); }, Rule(rule) { if ( @@ -168,6 +181,41 @@ export function compile( "Class-qualified :root selectors are unsupported on native. Use @media (prefers-color-scheme: dark) for dark mode, and React Native Appearance.setColorScheme() for manual selection.", ); } + + if (!inliningPlan) return; + + if (rule.type === "style" || rule.type === "nested-declarations") { + keyframeQueue = undefined; + const count = declarationCount(rule.value.declarations); + currentLocals = + count > 0 + ? blockLocalVarNames(rule.value.declarations, inliningPlan) + : undefined; + remainingInBlock = currentLocals ? count : 0; + } else if (rule.type === "keyframes") { + currentLocals = undefined; + remainingInBlock = 0; + keyframeQueue = undefined; + let anyLocals = false; + const queue: { + locals: ReadonlySet | undefined; + remaining: number; + }[] = []; + for (const keyframe of rule.value.keyframes) { + const count = declarationCount(keyframe.declarations); + if (count === 0) continue; + const locals = blockLocalVarNames( + keyframe.declarations, + inliningPlan, + ); + if (locals) anyLocals = true; + queue.push({ locals, remaining: count }); + } + if (anyLocals) { + keyframeQueue = queue; + keyframeIndex = 0; + } + } }, }; @@ -186,7 +234,37 @@ export function compile( } firstPassVisitor.Declaration = (decl) => { - return unparseIndividualTransform(decl); + let locals: ReadonlySet | undefined; + if (keyframeQueue !== undefined) { + const entry = keyframeQueue[keyframeIndex]; + if (entry) { + locals = entry.locals; + entry.remaining--; + if (entry.remaining === 0) { + keyframeIndex++; + if (keyframeIndex >= keyframeQueue.length) { + keyframeQueue = undefined; + } + } + } + } else if (remainingInBlock > 0) { + locals = currentLocals; + remainingInBlock--; + if (remainingInBlock === 0) { + currentLocals = undefined; + } + } + + const unparsed = unparseIndividualTransform(decl); + if (unparsed) { + return unparsed; + } + + if (inliningPlan) { + return foldDeclaration(decl, inliningPlan, locals); + } + + return undefined; }; const { code: firstPass, warnings: firstPassWarnings } = lightningcss({ diff --git a/src/compiler/individual-transforms.ts b/src/compiler/individual-transforms.ts index 2687cbcf..9eb161ad 100644 --- a/src/compiler/individual-transforms.ts +++ b/src/compiler/individual-transforms.ts @@ -81,14 +81,35 @@ function numberOrPercentageToken(value: NumberOrPercentage): TokenOrValue { : percentageToken(value.value); } +// lightningcss >= 1.30.2 fails to deserialize integers outside i16/u16 bounds into f32 enum variants (parcel-bundler/lightningcss#1188). +// Emitting a raw dimension token avoids the buffered f32 deserializer while printing identically. +export function needsDimensionToken(value: number): boolean { + return ( + (Number.isInteger(value) && (value < -32768 || value > 65535)) || + !Number.isFinite(value) + ); +} + // No token holds a calc(), which React Native cannot take anyway: the compiler warns for one and ignores the declaration function lengthToken( value: Length | DimensionPercentageFor_LengthValue, ): TokenOrValue | undefined { switch (value.type) { case "value": - case "dimension": - return { type: "length", value: value.value }; + case "dimension": { + const length = value.value; + if (needsDimensionToken(length.value)) { + return { + type: "token", + value: { + type: "dimension", + value: length.value, + unit: length.unit, + }, + }; + } + return { type: "length", value: length }; + } case "percentage": return percentageToken(value.value); case "calc": @@ -110,11 +131,22 @@ function translateTokens(value: Translate): TokenOrValue[] | undefined { } function rotateTokens(value: Rotate): TokenOrValue[] { + const angleToken: TokenOrValue = needsDimensionToken(value.angle.value) + ? { + type: "token", + value: { + type: "dimension", + value: value.angle.value, + unit: value.angle.type, + }, + } + : { type: "angle", value: value.angle }; + return spaceSeparated([ numberToken(value.x), numberToken(value.y), numberToken(value.z), - { type: "angle", value: value.angle }, + angleToken, ]); } diff --git a/src/compiler/inline-variables.ts b/src/compiler/inline-variables.ts index 978baf42..b7eace13 100644 --- a/src/compiler/inline-variables.ts +++ b/src/compiler/inline-variables.ts @@ -9,13 +9,21 @@ import type { } from "lightningcss"; import type { UniqueVarInfo } from "./compiler.types"; +import { needsDimensionToken } from "./individual-transforms"; -// A custom property is scoped to the elements its rule matches (css-variables-1 §2), so a value folds only where every matching element provably holds it -export function inlineVariables( +export interface VariableInliningPlan { + readonly vars: ReadonlyMap; + readonly universalNames: ReadonlySet; + readonly unreadVars: ReadonlySet; +} + +// A custom property is scoped to the elements its rule matches (css-variables-1 §2), so a value folds only where every matching element provably holds it. +// Runs over a read-only StyleSheet snapshot so callers can apply only changed declarations back to lightningcss. +export function planVariableInlining( stylesheet: StyleSheet, exclude: readonly string[], nonInheriting: ReadonlySet, -) { +): VariableInliningPlan { const scope = collectVariableScope(stylesheet, exclude, nonInheriting); for (const name of [...scope.vars.keys()]) { @@ -27,12 +35,108 @@ export function inlineVariables( }); const reads = collectRuntimeReads(stylesheet.rules, scope); + const unreadVars = new Set(); - forEachDeclarationBlock(stylesheet.rules, (block) => { - removeUnreadDeclarations(block, scope, reads); - }); + for (const name of scope.vars.keys()) { + if (!reads.has(name)) { + unreadVars.add(name); + } + } - return stylesheet; + return { + vars: scope.vars, + universalNames: scope.universalNames, + unreadVars, + }; +} + +export function declarationCount(block: DeclarationBlock | undefined): number { + if (!block) return 0; + return ( + (block.importantDeclarations?.length ?? 0) + + (block.declarations?.length ?? 0) + ); +} + +export function blockLocalVarNames( + block: DeclarationBlock | undefined, + plan: VariableInliningPlan, +): Set | undefined { + if (!block) return undefined; + + let found: Set | undefined; + + const scan = (declarations: readonly Declaration[] | undefined) => { + if (!declarations) return; + for (const declaration of declarations) { + if ( + declaration.property === "custom" && + plan.vars.has(declaration.value.name) && + !plan.universalNames.has(declaration.value.name) + ) { + found ??= new Set(); + found.add(declaration.value.name); + } + } + }; + + scan(block.importantDeclarations); + scan(block.declarations); + + return found; +} + +export function foldDeclaration( + declaration: Declaration, + plan: VariableInliningPlan, + blockLocalNames: ReadonlySet | undefined, +): Declaration | Declaration[] | undefined { + const isFoldable = (name: string) => + plan.universalNames.has(name) || blockLocalNames?.has(name) === true; + + if (declaration.property === "custom") { + if (plan.unreadVars.has(declaration.value.name)) { + return []; + } + + const folded = foldTokenList( + declaration.value.value, + plan.vars, + isFoldable, + ); + if (!folded) { + return undefined; + } + + return { + property: "custom", + value: { + name: declaration.value.name, + value: sanitizeTokenList(folded), + }, + }; + } + + if (declaration.property === "unparsed") { + const folded = foldTokenList( + declaration.value.value, + plan.vars, + isFoldable, + ); + if (!folded) { + return undefined; + } + + return { + property: "unparsed", + value: { + propertyId: declaration.value.propertyId, + value: sanitizeTokenList(folded), + }, + }; + } + + return undefined; } interface VariableScope { @@ -111,14 +215,21 @@ function declarationsOf(block: DeclarationBlock): Declaration[] { } function foldDeclarationBlock(block: DeclarationBlock, scope: VariableScope) { + const isFoldable = (name: string) => canFold(name, block, scope); + for (const declaration of declarationsOf(block)) { if ( declaration.property === "unparsed" || declaration.property === "custom" ) { - declaration.value.value = declaration.value.value.flatMap((part) => { - return flattenPart(part, scope, block); - }); + const next = foldTokenList( + declaration.value.value, + scope.vars, + isFoldable, + ); + if (next) { + declaration.value.value = next; + } } } } @@ -199,56 +310,199 @@ function forEachReadName( } } -function removeUnreadDeclarations( - block: DeclarationBlock, - scope: VariableScope, - reads: Set, -) { - const isKept = (declaration: Declaration) => { - return ( - declaration.property !== "custom" || - !scope.vars.has(declaration.value.name) || - reads.has(declaration.value.name) - ); - }; +function foldTokenList( + parts: TokenOrValue[], + vars: ReadonlyMap, + isFoldable: (name: string) => boolean, +): TokenOrValue[] | undefined { + let changed = false; + const out: TokenOrValue[] = []; - block.declarations = block.declarations?.filter(isKept); - block.importantDeclarations = block.importantDeclarations?.filter(isKept); + for (const part of parts) { + const next = foldPart(part, vars, isFoldable); + if (next !== part) { + changed = true; + if (Array.isArray(next)) { + for (const item of next) { + out.push(item); + } + } else { + out.push(next); + } + } else { + out.push(part); + } + } + + return changed ? out : undefined; } -function flattenPart( +function foldPart( part: TokenOrValue, - scope: VariableScope, - block: DeclarationBlock | undefined, + vars: ReadonlyMap, + isFoldable: (name: string) => boolean, ): TokenOrValue | TokenOrValue[] { if (part.type === "var") { const name = part.value.name.ident; - const varInfo = scope.vars.get(name); - - if (!varInfo || !canFold(name, block, scope)) { - part.value.fallback = part.value.fallback?.flatMap((arg) => { - return flattenPart(arg, scope, block); - }); + const varInfo = vars.get(name); + + if (!varInfo || !isFoldable(name)) { + if (part.value.fallback) { + const nextFallback = foldTokenList( + part.value.fallback, + vars, + isFoldable, + ); + if (nextFallback) { + return { + type: "var", + value: { ...part.value, fallback: nextFallback }, + }; + } + } return part; - } else if (varInfo.value === undefined) { - const fallback = part.value.fallback?.flatMap((arg) => { - return flattenPart(arg, scope, block); - }); + } + + if (varInfo.value === undefined) { + if (part.value.fallback) { + return ( + foldTokenList(part.value.fallback, vars, isFoldable) ?? + part.value.fallback + ); + } - return fallback ?? []; + return []; } return varInfo.value; } else if (part.type === "function") { - part.value.arguments = part.value.arguments.flatMap((arg) => { - return flattenPart(arg, scope, block); - }); + const nextArgs = foldTokenList(part.value.arguments, vars, isFoldable); + if (!nextArgs) { + return part; + } + + return { + type: "function", + value: { name: part.value.name, arguments: nextArgs }, + }; } return part; } +function dimensionToken(value: number, unit: string): TokenOrValue { + return { type: "token", value: { type: "dimension", value, unit } }; +} + +// Strips null Option fields (parcel-bundler/lightningcss#1065, #1081) and rewrites +// out-of-range integer dimensions as raw dimension tokens (#1188) on declarations +// returned to lightningcss >= 1.30.2. +function sanitizeTokenList(parts: TokenOrValue[]): TokenOrValue[] { + return parts.map((part) => sanitizeTokenOrValue(part)); +} + +function sanitizeTokenOrValue(part: TokenOrValue): TokenOrValue { + switch (part.type) { + case "var": { + const name = + part.value.name.from == null + ? { ident: part.value.name.ident } + : part.value.name; + + return part.value.fallback == null + ? { type: "var", value: { name } } + : { + type: "var", + value: { + name, + fallback: sanitizeTokenList(part.value.fallback), + }, + }; + } + case "env": { + const name = + part.value.name.type === "custom" && part.value.name.from == null + ? { type: "custom" as const, ident: part.value.name.ident } + : part.value.name; + const base = + part.value.indices !== undefined + ? { name, indices: part.value.indices } + : { name }; + + return part.value.fallback == null + ? { type: "env", value: base } + : { + type: "env", + value: { + ...base, + fallback: sanitizeTokenList(part.value.fallback), + }, + }; + } + case "function": + return { + type: "function", + value: { + name: part.value.name, + arguments: sanitizeTokenList(part.value.arguments), + }, + }; + case "unresolved-color": + switch (part.value.type) { + case "rgb": + case "hsl": + return { + type: "unresolved-color", + value: { + ...part.value, + alpha: sanitizeTokenList(part.value.alpha), + }, + }; + case "light-dark": + return { + type: "unresolved-color", + value: { + type: "light-dark", + light: sanitizeTokenList(part.value.light), + dark: sanitizeTokenList(part.value.dark), + }, + }; + default: + part.value satisfies never; + return part; + } + case "length": + return needsDimensionToken(part.value.value) + ? dimensionToken(part.value.value, part.value.unit) + : part; + case "angle": + return needsDimensionToken(part.value.value) + ? dimensionToken(part.value.value, part.value.type) + : part; + case "time": + return needsDimensionToken(part.value.value) + ? dimensionToken( + part.value.value, + part.value.type === "seconds" ? "s" : "ms", + ) + : part; + case "resolution": + return needsDimensionToken(part.value.value) + ? dimensionToken(part.value.value, part.value.type) + : part; + case "token": + case "color": + case "url": + case "dashed-ident": + case "animation-name": + return part; + default: + part satisfies never; + return part; + } +} + function flattenVar( name: string, scope: VariableScope, @@ -268,6 +522,8 @@ function flattenVar( // A value is substituted only into its declaring block, so a var() inside it folds on that block's terms const declaringBlock = scope.declaringBlocks.get(name); + const isFoldable = (nestedName: string) => + canFold(nestedName, declaringBlock, scope); let varInfoValue = varInfo.value?.flatMap((part) => { if (part.type === "var") { @@ -275,14 +531,14 @@ function flattenVar( flattenVar(nestedName, scope, seen); - if (canFold(nestedName, declaringBlock, scope)) { + if (isFoldable(nestedName)) { const nestedVarInfo = scope.vars.get(nestedName); if (nestedVarInfo?.value) { return nestedVarInfo.value; } } } - return flattenPart(part, scope, declaringBlock); + return foldPart(part, scope.vars, isFoldable); }); // If the variable is shorthand for "initial", substitute it for undefined