File: css_reduce_calc.go

package info (click to toggle)
golang-github-evanw-esbuild 0.25.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 10,184 kB
  • sloc: javascript: 28,602; makefile: 856; sh: 17
file content (605 lines) | stat: -rw-r--r-- 18,073 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
package css_parser

import (
	"fmt"
	"math"
	"strconv"
	"strings"

	"github.com/evanw/esbuild/internal/css_ast"
	"github.com/evanw/esbuild/internal/css_lexer"
	"github.com/evanw/esbuild/internal/logger"
)

func (p *parser) tryToReduceCalcExpression(token css_ast.Token) css_ast.Token {
	if term := tryToParseCalcTerm(*token.Children); term != nil {
		whitespace := css_ast.WhitespaceBefore | css_ast.WhitespaceAfter
		if p.options.minifyWhitespace {
			whitespace = 0
		}
		term = term.partiallySimplify()
		if result, ok := term.convertToToken(whitespace); ok {
			if result.Kind == css_lexer.TOpenParen {
				result.Kind = css_lexer.TFunction
				result.Text = "calc"
			}
			result.Loc = token.Loc
			result.Whitespace = css_ast.WhitespaceBefore | css_ast.WhitespaceAfter
			return result
		}
	}
	return token
}

type calcTermWithOp struct {
	data  calcTerm
	opLoc logger.Loc
}

// See: https://www.w3.org/TR/css-values-4/#calc-internal
type calcTerm interface {
	convertToToken(whitespace css_ast.WhitespaceFlags) (css_ast.Token, bool)
	partiallySimplify() calcTerm
}

type calcSum struct {
	terms []calcTermWithOp
}

type calcProduct struct {
	terms []calcTermWithOp
}

type calcNegate struct {
	term calcTermWithOp
}

type calcInvert struct {
	term calcTermWithOp
}

type calcNumeric struct {
	unit   string
	number float64
	loc    logger.Loc
}

type calcValue struct {
	token                css_ast.Token
	isInvalidPlusOrMinus bool
}

func floatToStringForCalc(a float64) (string, bool) {
	// Handle non-finite cases
	if math.IsNaN(a) || math.IsInf(a, 0) {
		return "", false
	}

	// Print the number as a string
	text := fmt.Sprintf("%.05f", a)
	for text[len(text)-1] == '0' {
		text = text[:len(text)-1]
	}
	if text[len(text)-1] == '.' {
		text = text[:len(text)-1]
	}
	if strings.HasPrefix(text, "0.") {
		text = text[1:]
	} else if strings.HasPrefix(text, "-0.") {
		text = "-" + text[2:]
	}

	// Bail if the number is not exactly represented
	if number, err := strconv.ParseFloat(text, 64); err != nil || number != a {
		return "", false
	}

	return text, true
}

func (c *calcSum) convertToToken(whitespace css_ast.WhitespaceFlags) (css_ast.Token, bool) {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-serialize
	tokens := make([]css_ast.Token, 0, len(c.terms)*2)

	// ALGORITHM DEVIATION: Avoid parenthesizing product nodes inside sum nodes
	if product, ok := c.terms[0].data.(*calcProduct); ok {
		token, ok := product.convertToToken(whitespace)
		if !ok {
			return css_ast.Token{}, false
		}
		tokens = append(tokens, *token.Children...)
	} else {
		token, ok := c.terms[0].data.convertToToken(whitespace)
		if !ok {
			return css_ast.Token{}, false
		}
		tokens = append(tokens, token)
	}

	for _, term := range c.terms[1:] {
		// If child is a Negate node, append " - " to s, then serialize the Negate’s child and append the result to s.
		if negate, ok := term.data.(*calcNegate); ok {
			token, ok := negate.term.data.convertToToken(whitespace)
			if !ok {
				return css_ast.Token{}, false
			}
			tokens = append(tokens, css_ast.Token{
				Loc:        term.opLoc,
				Kind:       css_lexer.TDelimMinus,
				Text:       "-",
				Whitespace: css_ast.WhitespaceBefore | css_ast.WhitespaceAfter,
			}, token)
			continue
		}

		// If child is a negative numeric value, append " - " to s, then serialize the negation of child as normal and append the result to s.
		if numeric, ok := term.data.(*calcNumeric); ok && numeric.number < 0 {
			clone := *numeric
			clone.number = -clone.number
			token, ok := clone.convertToToken(whitespace)
			if !ok {
				return css_ast.Token{}, false
			}
			tokens = append(tokens, css_ast.Token{
				Loc:        term.opLoc,
				Kind:       css_lexer.TDelimMinus,
				Text:       "-",
				Whitespace: css_ast.WhitespaceBefore | css_ast.WhitespaceAfter,
			}, token)
			continue
		}

		// Otherwise, append " + " to s, then serialize child and append the result to s.
		tokens = append(tokens, css_ast.Token{
			Loc:        term.opLoc,
			Kind:       css_lexer.TDelimPlus,
			Text:       "+",
			Whitespace: css_ast.WhitespaceBefore | css_ast.WhitespaceAfter,
		})

		// ALGORITHM DEVIATION: Avoid parenthesizing product nodes inside sum nodes
		if product, ok := term.data.(*calcProduct); ok {
			token, ok := product.convertToToken(whitespace)
			if !ok {
				return css_ast.Token{}, false
			}
			tokens = append(tokens, *token.Children...)
		} else {
			token, ok := term.data.convertToToken(whitespace)
			if !ok {
				return css_ast.Token{}, false
			}
			tokens = append(tokens, token)
		}
	}

	return css_ast.Token{
		Loc:      tokens[0].Loc,
		Kind:     css_lexer.TOpenParen,
		Text:     "(",
		Children: &tokens,
	}, true
}

func (c *calcProduct) convertToToken(whitespace css_ast.WhitespaceFlags) (css_ast.Token, bool) {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-serialize
	tokens := make([]css_ast.Token, 0, len(c.terms)*2)
	token, ok := c.terms[0].data.convertToToken(whitespace)
	if !ok {
		return css_ast.Token{}, false
	}
	tokens = append(tokens, token)

	for _, term := range c.terms[1:] {
		// If child is an Invert node, append " / " to s, then serialize the Invert’s child and append the result to s.
		if invert, ok := term.data.(*calcInvert); ok {
			token, ok := invert.term.data.convertToToken(whitespace)
			if !ok {
				return css_ast.Token{}, false
			}
			tokens = append(tokens, css_ast.Token{
				Loc:        term.opLoc,
				Kind:       css_lexer.TDelimSlash,
				Text:       "/",
				Whitespace: whitespace,
			}, token)
			continue
		}

		// Otherwise, append " * " to s, then serialize child and append the result to s.
		token, ok := term.data.convertToToken(whitespace)
		if !ok {
			return css_ast.Token{}, false
		}
		tokens = append(tokens, css_ast.Token{
			Loc:        term.opLoc,
			Kind:       css_lexer.TDelimAsterisk,
			Text:       "*",
			Whitespace: whitespace,
		}, token)
	}

	return css_ast.Token{
		Loc:      tokens[0].Loc,
		Kind:     css_lexer.TOpenParen,
		Text:     "(",
		Children: &tokens,
	}, true
}

func (c *calcNegate) convertToToken(whitespace css_ast.WhitespaceFlags) (css_ast.Token, bool) {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-serialize
	token, ok := c.term.data.convertToToken(whitespace)
	if !ok {
		return css_ast.Token{}, false
	}
	return css_ast.Token{
		Kind: css_lexer.TOpenParen,
		Text: "(",
		Children: &[]css_ast.Token{
			{Loc: c.term.opLoc, Kind: css_lexer.TNumber, Text: "-1"},
			{Loc: c.term.opLoc, Kind: css_lexer.TDelimSlash, Text: "*", Whitespace: css_ast.WhitespaceBefore | css_ast.WhitespaceAfter},
			token,
		},
	}, true
}

func (c *calcInvert) convertToToken(whitespace css_ast.WhitespaceFlags) (css_ast.Token, bool) {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-serialize
	token, ok := c.term.data.convertToToken(whitespace)
	if !ok {
		return css_ast.Token{}, false
	}
	return css_ast.Token{
		Kind: css_lexer.TOpenParen,
		Text: "(",
		Children: &[]css_ast.Token{
			{Loc: c.term.opLoc, Kind: css_lexer.TNumber, Text: "1"},
			{Loc: c.term.opLoc, Kind: css_lexer.TDelimSlash, Text: "/", Whitespace: css_ast.WhitespaceBefore | css_ast.WhitespaceAfter},
			token,
		},
	}, true
}

func (c *calcNumeric) convertToToken(whitespace css_ast.WhitespaceFlags) (css_ast.Token, bool) {
	text, ok := floatToStringForCalc(c.number)
	if !ok {
		return css_ast.Token{}, false
	}
	if c.unit == "" {
		return css_ast.Token{
			Loc:  c.loc,
			Kind: css_lexer.TNumber,
			Text: text,
		}, true
	}
	if c.unit == "%" {
		return css_ast.Token{
			Loc:  c.loc,
			Kind: css_lexer.TPercentage,
			Text: text + "%",
		}, true
	}
	return css_ast.Token{
		Loc:        c.loc,
		Kind:       css_lexer.TDimension,
		Text:       text + c.unit,
		UnitOffset: uint16(len(text)),
	}, true
}

func (c *calcValue) convertToToken(whitespace css_ast.WhitespaceFlags) (css_ast.Token, bool) {
	t := c.token
	t.Whitespace = 0
	return t, true
}

func (c *calcSum) partiallySimplify() calcTerm {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-simplification

	// For each of root’s children that are Sum nodes, replace them with their children.
	terms := make([]calcTermWithOp, 0, len(c.terms))
	for _, term := range c.terms {
		term.data = term.data.partiallySimplify()
		if sum, ok := term.data.(*calcSum); ok {
			terms = append(terms, sum.terms...)
		} else {
			terms = append(terms, term)
		}
	}

	// For each set of root’s children that are numeric values with identical units, remove
	// those children and replace them with a single numeric value containing the sum of the
	// removed nodes, and with the same unit. (E.g. combine numbers, combine percentages,
	// combine px values, etc.)
	for i := 0; i < len(terms); i++ {
		term := terms[i]
		if numeric, ok := term.data.(*calcNumeric); ok {
			end := i + 1
			for j := end; j < len(terms); j++ {
				term2 := terms[j]
				if numeric2, ok := term2.data.(*calcNumeric); ok && strings.EqualFold(numeric2.unit, numeric.unit) {
					numeric.number += numeric2.number
				} else {
					terms[end] = term2
					end++
				}
			}
			terms = terms[:end]
		}
	}

	// If root has only a single child at this point, return the child.
	if len(terms) == 1 {
		return terms[0].data
	}

	// Otherwise, return root.
	c.terms = terms
	return c
}

func (c *calcProduct) partiallySimplify() calcTerm {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-simplification

	// For each of root’s children that are Product nodes, replace them with their children.
	terms := make([]calcTermWithOp, 0, len(c.terms))
	for _, term := range c.terms {
		term.data = term.data.partiallySimplify()
		if product, ok := term.data.(*calcProduct); ok {
			terms = append(terms, product.terms...)
		} else {
			terms = append(terms, term)
		}
	}

	// If root has multiple children that are numbers (not percentages or dimensions), remove
	// them and replace them with a single number containing the product of the removed nodes.
	for i, term := range terms {
		if numeric, ok := term.data.(*calcNumeric); ok && numeric.unit == "" {
			end := i + 1
			for j := end; j < len(terms); j++ {
				term2 := terms[j]
				if numeric2, ok := term2.data.(*calcNumeric); ok && numeric2.unit == "" {
					numeric.number *= numeric2.number
				} else {
					terms[end] = term2
					end++
				}
			}
			terms = terms[:end]
			break
		}
	}

	// If root contains only numeric values and/or Invert nodes containing numeric values,
	// and multiplying the types of all the children (noting that the type of an Invert
	// node is the inverse of its child’s type) results in a type that matches any of the
	// types that a math function can resolve to, return the result of multiplying all the
	// values of the children (noting that the value of an Invert node is the reciprocal
	// of its child’s value), expressed in the result’s canonical unit.
	if len(terms) == 2 {
		// Right now, only handle the case of two numbers, one of which has no unit
		if first, ok := terms[0].data.(*calcNumeric); ok {
			if second, ok := terms[1].data.(*calcNumeric); ok {
				if first.unit == "" {
					second.number *= first.number
					return second
				}
				if second.unit == "" {
					first.number *= second.number
					return first
				}
			}
		}
	}

	// ALGORITHM DEVIATION: Divide instead of multiply if the reciprocal is shorter
	for i := 1; i < len(terms); i++ {
		if numeric, ok := terms[i].data.(*calcNumeric); ok {
			reciprocal := 1 / numeric.number
			if multiply, ok := floatToStringForCalc(numeric.number); ok {
				if divide, ok := floatToStringForCalc(reciprocal); ok && len(divide) < len(multiply) {
					numeric.number = reciprocal
					terms[i].data = &calcInvert{term: calcTermWithOp{
						data:  numeric,
						opLoc: terms[i].opLoc,
					}}
				}
			}
		}
	}

	// If root has only a single child at this point, return the child.
	if len(terms) == 1 {
		return terms[0].data
	}

	// Otherwise, return root.
	c.terms = terms
	return c
}

func (c *calcNegate) partiallySimplify() calcTerm {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-simplification

	c.term.data = c.term.data.partiallySimplify()

	// If root’s child is a numeric value, return an equivalent numeric value, but with the value negated (0 - value).
	if numeric, ok := c.term.data.(*calcNumeric); ok {
		numeric.number = -numeric.number
		return numeric
	}

	// If root’s child is a Negate node, return the child’s child.
	if negate, ok := c.term.data.(*calcNegate); ok {
		return negate.term.data
	}

	return c
}

func (c *calcInvert) partiallySimplify() calcTerm {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-simplification

	c.term.data = c.term.data.partiallySimplify()

	// If root’s child is a number (not a percentage or dimension) return the reciprocal of the child’s value.
	if numeric, ok := c.term.data.(*calcNumeric); ok && numeric.unit == "" {
		numeric.number = 1 / numeric.number
		return numeric
	}

	// If root’s child is an Invert node, return the child’s child.
	if invert, ok := c.term.data.(*calcInvert); ok {
		return invert.term.data
	}

	return c
}

func (c *calcNumeric) partiallySimplify() calcTerm {
	return c
}

func (c *calcValue) partiallySimplify() calcTerm {
	return c
}

func tryToParseCalcTerm(tokens []css_ast.Token) calcTerm {
	// Specification: https://www.w3.org/TR/css-values-4/#calc-internal
	terms := make([]calcTermWithOp, len(tokens))

	for i, token := range tokens {
		var term calcTerm
		if token.Kind == css_lexer.TFunction && strings.EqualFold(token.Text, "var") {
			// Using "var()" should bail because it can expand to any number of tokens
			return nil
		} else if token.Kind == css_lexer.TOpenParen || (token.Kind == css_lexer.TFunction && strings.EqualFold(token.Text, "calc")) {
			term = tryToParseCalcTerm(*token.Children)
			if term == nil {
				return nil
			}
		} else if token.Kind == css_lexer.TNumber {
			if number, err := strconv.ParseFloat(token.Text, 64); err == nil {
				term = &calcNumeric{loc: token.Loc, number: number}
			} else {
				term = &calcValue{token: token}
			}
		} else if token.Kind == css_lexer.TPercentage {
			if number, err := strconv.ParseFloat(token.PercentageValue(), 64); err == nil {
				term = &calcNumeric{loc: token.Loc, number: number, unit: "%"}
			} else {
				term = &calcValue{token: token}
			}
		} else if token.Kind == css_lexer.TDimension {
			if number, err := strconv.ParseFloat(token.DimensionValue(), 64); err == nil {
				term = &calcNumeric{loc: token.Loc, number: number, unit: token.DimensionUnit()}
			} else {
				term = &calcValue{token: token}
			}
		} else if token.Kind == css_lexer.TIdent && strings.EqualFold(token.Text, "Infinity") {
			term = &calcNumeric{loc: token.Loc, number: math.Inf(1)}
		} else if token.Kind == css_lexer.TIdent && strings.EqualFold(token.Text, "-Infinity") {
			term = &calcNumeric{loc: token.Loc, number: math.Inf(-1)}
		} else if token.Kind == css_lexer.TIdent && strings.EqualFold(token.Text, "NaN") {
			term = &calcNumeric{loc: token.Loc, number: math.NaN()}
		} else {
			term = &calcValue{
				token: token,

				// From the specification: "In addition, whitespace is required on both sides of the
				// + and - operators. (The * and / operators can be used without white space around them.)"
				isInvalidPlusOrMinus: i > 0 && i+1 < len(tokens) &&
					(token.Kind == css_lexer.TDelimPlus || token.Kind == css_lexer.TDelimMinus) &&
					(((token.Whitespace&css_ast.WhitespaceBefore) == 0 && (tokens[i-1].Whitespace&css_ast.WhitespaceAfter) == 0) ||
						(token.Whitespace&css_ast.WhitespaceAfter) == 0 && (tokens[i+1].Whitespace&css_ast.WhitespaceBefore) == 0),
			}
		}
		terms[i].data = term
	}

	// Collect children into Product and Invert nodes
	first := 1
	for first+1 < len(terms) {
		// If this is a "*" or "/" operator
		if value, ok := terms[first].data.(*calcValue); ok && (value.token.Kind == css_lexer.TDelimAsterisk || value.token.Kind == css_lexer.TDelimSlash) {
			// Scan over the run
			last := first
			for last+3 < len(terms) {
				if value, ok := terms[last+2].data.(*calcValue); ok && (value.token.Kind == css_lexer.TDelimAsterisk || value.token.Kind == css_lexer.TDelimSlash) {
					last += 2
				} else {
					break
				}
			}

			// Generate a node for the run
			product := calcProduct{terms: make([]calcTermWithOp, (last-first)/2+2)}
			for i := range product.terms {
				term := terms[first+i*2-1]
				if i > 0 {
					op := terms[first+i*2-2].data.(*calcValue).token
					term.opLoc = op.Loc
					if op.Kind == css_lexer.TDelimSlash {
						term.data = &calcInvert{term: term}
					}
				}
				product.terms[i] = term
			}

			// Replace the run with a single node
			terms[first-1].data = &product
			terms = append(terms[:first], terms[last+2:]...)
			continue
		}

		first++
	}

	// Collect children into Sum and Negate nodes
	first = 1
	for first+1 < len(terms) {
		// If this is a "+" or "-" operator
		if value, ok := terms[first].data.(*calcValue); ok && !value.isInvalidPlusOrMinus &&
			(value.token.Kind == css_lexer.TDelimPlus || value.token.Kind == css_lexer.TDelimMinus) {
			// Scan over the run
			last := first
			for last+3 < len(terms) {
				if value, ok := terms[last+2].data.(*calcValue); ok && !value.isInvalidPlusOrMinus &&
					(value.token.Kind == css_lexer.TDelimPlus || value.token.Kind == css_lexer.TDelimMinus) {
					last += 2
				} else {
					break
				}
			}

			// Generate a node for the run
			sum := calcSum{terms: make([]calcTermWithOp, (last-first)/2+2)}
			for i := range sum.terms {
				term := terms[first+i*2-1]
				if i > 0 {
					op := terms[first+i*2-2].data.(*calcValue).token
					term.opLoc = op.Loc
					if op.Kind == css_lexer.TDelimMinus {
						term.data = &calcNegate{term: term}
					}
				}
				sum.terms[i] = term
			}

			// Replace the run with a single node
			terms[first-1].data = &sum
			terms = append(terms[:first], terms[last+2:]...)
			continue
		}

		first++
	}

	// This only succeeds if everything reduces to a single term
	if len(terms) == 1 {
		return terms[0].data
	}
	return nil
}