Skip to content

Commit d230f2e

Browse files
authored
Improve incremental builds (#13168)
* ensure we don't crash on deleted files * change return type of `compile` to include a `rebuild()` function This will allow us in the future to perform incremental rebuilds after the initial rebuild. This is purely the API change so that we can prepare all the call sites to use this new API. * set `@tailwind utilities` nodes Instead of replacing the node that represents the `@tailwind utilities` with the generated AST nodes from the rawCandidates, we will set the nodes of the `@tailwind utilities` rule to the AST nodes instead. This way we dont' have to remove and replace the `@tailwind utilities` rule with `n` new nodes. This will later allow us to track the `@tailwindcss utilities` rule itself and update its `nodes` for incremental rebuilds. This also requires a small change to the printer where we now need to print the children of the `@tailwind utilities` rule. Note: we keep the same `depth` as-if the `@tailwindcss utilities` rule was not there. Otherwise additional indentation would be present. * move sorting to the `ast.sort()` call This will allow us to keep sorting AST nodes in a single spot. * move parser functions to the `DesignSystem` This allows us to put all the parsers in the `DesignSystem`, this allows us to scope the parsers to the current design system (the current theme, current utility values and variants). The implementation of these parsers are also using a `DefaultMap` implementation. This allows us to make use of caching and only parse a candidate, parse a variant or compile AST nodes for a given raw candidate once if we've already done this work in the past. Again, this is scoped to the `DesignSystem` itself. This means that if the corresponding theme changes, then we will create a new `DesignSystem` entirely and the caches will be garbage collected. This is important because a candidate like `bg-primary` can be invalid in `DesignSystem` A, but can be valid in `DesignSystem` B and vice versa. * ensure we sort variants alphabetically by root For incremental rebuilds we don't know all the used variants upfront, which means that we can't sort them upfront either (what we used to do). This code now allows us to sort the variants deterministically when sorting the variants themselves instead of relying on the fact that they used to be sorted before. The sort itself could change slightly compared to the previous implementation (especially when you used stacked variants in your candidates), but it will still be deterministic. * replace `localeCompare` comparisons Use cheaper comparisons than `localeCompare` when comparing 2 strings. We currently don't care if it is 100% correctly sorted, but we just want consistent sorting. This is currently faster compared to `localeCompare`. Another benefit is that `localeCompare` could result in non-deterministic results if the CSS was generated on 2 separate computers where the `locale` is different. We could solve that by adding a dedicated locale, but it would still be slower compared to this. * track invalid candidates When an incoming raw candidates doesn't produce any output, then we can mark it as an invalid candidate. This will allow us to reduce the amount of candidates to handle in incremental rebuilds. * add initial incremental rebuild implementation This includes a number of steps: 1. Track the `@tailwind utilities` rule, so that we can adjust its nodes later without re-parsing the full incoming CSS. 2. Add the new incoming raw candidates to the existing set of candidates. 3. Parse the merged set to `compileCandidates` (this can accept any `Iterable<string>`, which means `string[]`, `Set<string>`, ...) 4. Get the new AST nodes, update the `@tailwind utilities` rule's nodes and re-print the AST to CSS. * improvement 1: ignore known invalid candidates This will reduce the amount of candidates to handle. They would eventually be skipped anyway, but now we don't even have to re-parse (and hit a cache) at all. * improvement 2: skip work, when generated AST is the same Currently incremental rebuilds are additive, which means that we are not keeping track if we should remove CSS again in development. We can exploit this information, because now we can quickly check the amoutn of generated AST nodes. - If they are the same then nothing new is generated — this means that we can re-use the previous compiled CSS. We don't even have to re-print the AST because we already did do that work in the past. - If there are more AST nodes, something new is generated — this means that we should update the `@tailwind utilities` rule and re-print the CSS. We can store the result for future incremental rebuilds. * improvement 3: skip work if no new candidates are detected - We already know a set of candidates from previous runs. - We also already know a set of candidates that are invalid and don't produce anything. This means that an incremental rebuild could give us a new set of candidates that either already exist or are invalid. If nothing changes, then we can re-use the compiled CSS. This actually happens more often than you think, and the bigger your project is the better this optimization will be. For example: ``` // Imagine file A exists: <div class="flex items-center justify-center"></div> <button class="text-red-500">Delete</button> ``` ``` // Now you add a second file B: <div class="text-red-500 flex"></div> ``` You just created a brand new file with a bunch of HTML elements and classes, yet all of the candidates in file B already exist in file A, so nothing changes to the actual generated CSS. Now imagine the other hundreds of files that already contain hundreds of classes. The beauty of this optimization is two-fold: - On small projects, compiling is very fast even without this check. This means it is performant. - On bigger projects, we will be able to re-use existing candidates. This means it stays performant. * remove `getAstNodeSize` We can move this up the tree and move it to the `rebuild` function instead. * remove invalid candidate tracking from `DesignSystem` This isn't used anywhere but only in the `rebuild` of the compile step. This allows us to remove it entirely from core logic, and move it up the chain where it is needed. * replace `throwOnInvalidCandidate` with `onInvalidCanidate` This was only needed for working with `@apply`, now this logic _only_ exists in the code path where we are handling `@apply`. * update `compile` API signature * update callsite of `compile()` function * fix typo
1 parent 78d1c50 commit d230f2e

File tree

19 files changed

+281
-224
lines changed

19 files changed

+281
-224
lines changed

oxide/crates/core/src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -433,9 +433,9 @@ fn read_all_files_sync(changed_content: Vec<ChangedContent>) -> Vec<Vec<u8>> {
433433

434434
changed_content
435435
.into_iter()
436-
.map(|c| match (c.file, c.content) {
437-
(Some(file), None) => std::fs::read(file).unwrap(),
438-
(None, Some(content)) => content.into_bytes(),
436+
.filter_map(|c| match (c.file, c.content) {
437+
(Some(file), None) => std::fs::read(file).ok(),
438+
(None, Some(content)) => Some(content.into_bytes()),
439439
_ => Default::default(),
440440
})
441441
.collect()

packages/@tailwindcss-cli/src/commands/build/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,8 @@ export async function handle(args: Result<ReturnType<typeof options>>) {
100100
)
101101

102102
// Compile the input
103-
let result = compile(input, candidates)
103+
let { build } = compile(input)
104+
let result = build(candidates)
104105

105106
// Optimize the output
106107
if (args['--minify'] || args['--optimize']) {
@@ -193,7 +194,7 @@ export async function handle(args: Result<ReturnType<typeof options>>) {
193194
}
194195

195196
// Compile the input
196-
let result = compile(input, candidates)
197+
result = compile(input).build(candidates)
197198

198199
// Optimize the output
199200
if (args['--minify'] || args['--optimize']) {

packages/@tailwindcss-postcss/src/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
5353

5454
// No `@tailwind` means we don't have to look for candidates
5555
if (!hasTailwind) {
56-
replaceCss(compile(root.toString(), []))
56+
replaceCss(compile(root.toString()).build([]))
5757
return
5858
}
5959

@@ -83,7 +83,7 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
8383
})
8484
}
8585

86-
replaceCss(compile(root.toString(), candidates))
86+
replaceCss(compile(root.toString()).build(candidates))
8787
},
8888
],
8989
}

packages/@tailwindcss-vite/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export default function tailwindcss(): Plugin[] {
6363
}
6464

6565
function generateCss(css: string) {
66-
return compile(css, Array.from(candidates))
66+
return compile(css).build(Array.from(candidates))
6767
}
6868

6969
function generateOptimizedCss(css: string) {

packages/tailwindcss/src/ast.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,13 @@ export function toCss(ast: AstNode[]) {
105105
return css
106106
}
107107

108+
if (node.selector === '@tailwind utilities') {
109+
for (let child of node.nodes) {
110+
css += stringify(child, depth)
111+
}
112+
return css
113+
}
114+
108115
// Print at-rules without nodes with a `;` instead of an empty block.
109116
//
110117
// E.g.:
Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import { scanDir } from '@tailwindcss/oxide'
22
import { bench } from 'vitest'
3-
import { parseCandidate, parseVariant } from './candidate'
3+
import { parseCandidate } from './candidate'
44
import { buildDesignSystem } from './design-system'
55
import { Theme } from './theme'
6-
import { DefaultMap } from './utils/default-map'
76

87
// FOLDER=path/to/folder vitest bench
98
const root = process.env.FOLDER || process.cwd()
@@ -15,10 +14,6 @@ const designSystem = buildDesignSystem(new Theme())
1514

1615
bench('parseCandidate', () => {
1716
for (let candidate of result.candidates) {
18-
parseCandidate(
19-
candidate,
20-
designSystem.utilities,
21-
new DefaultMap((variant, map) => parseVariant(variant, designSystem.variants, map)),
22-
)
17+
parseCandidate(candidate, designSystem)
2318
}
2419
})

packages/tailwindcss/src/candidate.test.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { expect, it } from 'vitest'
2-
import { parseCandidate, parseVariant } from './candidate'
2+
import { buildDesignSystem } from './design-system'
3+
import { Theme } from './theme'
34
import { Utilities } from './utilities'
4-
import { DefaultMap } from './utils/default-map'
55
import { Variants } from './variants'
66

77
function run(
@@ -11,11 +11,12 @@ function run(
1111
utilities ??= new Utilities()
1212
variants ??= new Variants()
1313

14-
let parsedVariants = new DefaultMap((variant, map) => {
15-
return parseVariant(variant, variants!, map)
16-
})
14+
let designSystem = buildDesignSystem(new Theme())
1715

18-
return parseCandidate(candidate, utilities, parsedVariants)
16+
designSystem.utilities = utilities
17+
designSystem.variants = variants
18+
19+
return designSystem.parseCandidate(candidate)
1920
}
2021

2122
it('should skip unknown utilities', () => {

packages/tailwindcss/src/candidate.ts

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { DesignSystem } from './design-system'
12
import { decodeArbitraryValue } from './utils/decode-arbitrary-value'
23
import { segment } from './utils/segment'
34

@@ -206,14 +207,7 @@ export type Candidate =
206207
important: boolean
207208
}
208209

209-
export function parseCandidate(
210-
input: string,
211-
utilities: {
212-
has: (value: string) => boolean
213-
kind: (root: string) => Omit<Candidate['kind'], 'arbitrary'>
214-
},
215-
parsedVariants: { get: (value: string) => Variant | null },
216-
): Candidate | null {
210+
export function parseCandidate(input: string, designSystem: DesignSystem): Candidate | null {
217211
// hover:focus:underline
218212
// ^^^^^ ^^^^^^ -> Variants
219213
// ^^^^^^^^^ -> Base
@@ -228,7 +222,7 @@ export function parseCandidate(
228222
let parsedCandidateVariants: Variant[] = []
229223

230224
for (let variant of rawVariants) {
231-
let parsedVariant = parsedVariants.get(variant)
225+
let parsedVariant = designSystem.parseVariant(variant)
232226
if (parsedVariant === null) return null
233227

234228
// Variants are applied left-to-right meaning that any representing pseudo-
@@ -320,7 +314,7 @@ export function parseCandidate(
320314
base = base.slice(1)
321315
}
322316

323-
let [root, value] = findRoot(base, utilities)
317+
let [root, value] = findRoot(base, designSystem.utilities)
324318

325319
let modifierSegment: string | null = null
326320

@@ -335,13 +329,13 @@ export function parseCandidate(
335329
modifierSegment = rootModifierSegment
336330

337331
// Try to find the root and value, without the modifier present
338-
;[root, value] = findRoot(rootWithoutModifier, utilities)
332+
;[root, value] = findRoot(rootWithoutModifier, designSystem.utilities)
339333
}
340334

341335
// If there's no root, the candidate isn't a valid class and can be discarded.
342336
if (root === null) return null
343337

344-
let kind = utilities.kind(root)
338+
let kind = designSystem.utilities.kind(root)
345339

346340
if (kind === 'static') {
347341
if (value !== null) return null
@@ -475,15 +469,7 @@ function parseModifier(modifier: string): CandidateModifier {
475469
}
476470
}
477471

478-
export function parseVariant(
479-
variant: string,
480-
variants: {
481-
has: (value: string) => boolean
482-
kind: (root: string) => Omit<Variant['kind'], 'arbitrary'>
483-
compounds: (root: string) => boolean
484-
},
485-
parsedVariants: { get: (value: string) => Variant | null },
486-
): Variant | null {
472+
export function parseVariant(variant: string, designSystem: DesignSystem): Variant | null {
487473
// Arbitrary variants
488474
if (variant[0] === '[' && variant[variant.length - 1] === ']') {
489475
/**
@@ -535,20 +521,20 @@ export function parseVariant(
535521
// - `group-hover/foo/bar`
536522
if (additionalModifier) return null
537523

538-
let [root, value] = findRoot(variantWithoutModifier, variants)
524+
let [root, value] = findRoot(variantWithoutModifier, designSystem.variants)
539525

540526
// Variant is invalid, therefore the candidate is invalid and we can skip
541527
// continue parsing it.
542528
if (root === null) return null
543529

544-
switch (variants.kind(root)) {
530+
switch (designSystem.variants.kind(root)) {
545531
case 'static': {
546532
if (value !== null) return null
547533

548534
return {
549535
kind: 'static',
550536
root,
551-
compounds: variants.compounds(root),
537+
compounds: designSystem.variants.compounds(root),
552538
}
553539
}
554540

@@ -564,7 +550,7 @@ export function parseVariant(
564550
kind: 'arbitrary',
565551
value: decodeArbitraryValue(value.slice(1, -1)),
566552
},
567-
compounds: variants.compounds(root),
553+
compounds: designSystem.variants.compounds(root),
568554
}
569555
}
570556

@@ -573,14 +559,14 @@ export function parseVariant(
573559
root,
574560
modifier: modifier === null ? null : parseModifier(modifier),
575561
value: { kind: 'named', value },
576-
compounds: variants.compounds(root),
562+
compounds: designSystem.variants.compounds(root),
577563
}
578564
}
579565

580566
case 'compound': {
581567
if (value === null) return null
582568

583-
let subVariant = parsedVariants.get(value)
569+
let subVariant = designSystem.parseVariant(value)
584570
if (subVariant === null) return null
585571
if (subVariant.compounds === false) return null
586572

@@ -589,7 +575,7 @@ export function parseVariant(
589575
root,
590576
modifier: modifier === null ? null : { kind: 'named', value: modifier },
591577
variant: subVariant,
592-
compounds: variants.compounds(root),
578+
compounds: designSystem.variants.compounds(root),
593579
}
594580
}
595581
}

0 commit comments

Comments
 (0)