-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
js_printer.go
4923 lines (4364 loc) · 130 KB
/
js_printer.go
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package js_printer
import (
"bytes"
"fmt"
"math"
"strconv"
"strings"
"unicode/utf8"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/helpers"
"github.com/evanw/esbuild/internal/js_ast"
"github.com/evanw/esbuild/internal/logger"
"github.com/evanw/esbuild/internal/renamer"
"github.com/evanw/esbuild/internal/sourcemap"
)
var positiveInfinity = math.Inf(1)
var negativeInfinity = math.Inf(-1)
const hexChars = "0123456789ABCDEF"
const firstASCII = 0x20
const lastASCII = 0x7E
const firstHighSurrogate = 0xD800
const lastHighSurrogate = 0xDBFF
const firstLowSurrogate = 0xDC00
const lastLowSurrogate = 0xDFFF
func QuoteIdentifier(js []byte, name string, unsupportedFeatures compat.JSFeature) []byte {
isASCII := false
asciiStart := 0
for i, c := range name {
if c >= firstASCII && c <= lastASCII {
// Fast path: a run of ASCII characters
if !isASCII {
isASCII = true
asciiStart = i
}
} else {
// Slow path: escape non-ACSII characters
if isASCII {
js = append(js, name[asciiStart:i]...)
isASCII = false
}
if c <= 0xFFFF {
js = append(js, '\\', 'u', hexChars[c>>12], hexChars[(c>>8)&15], hexChars[(c>>4)&15], hexChars[c&15])
} else if !unsupportedFeatures.Has(compat.UnicodeEscapes) {
js = append(js, fmt.Sprintf("\\u{%X}", c)...)
} else {
panic("Internal error: Cannot encode identifier: Unicode escapes are unsupported")
}
}
}
if isASCII {
// Print one final run of ASCII characters
js = append(js, name[asciiStart:]...)
}
return js
}
func (p *printer) printUnquotedUTF16(text []uint16, quote rune, flags printQuotedFlags) {
temp := make([]byte, utf8.UTFMax)
js := p.js
i := 0
n := len(text)
// Only compute the line length if necessary
var startLineLength int
wrapLongLines := false
if p.options.LineLimit > 0 && (flags&printQuotedNoWrap) == 0 {
startLineLength = p.currentLineLength()
if startLineLength > p.options.LineLimit {
startLineLength = p.options.LineLimit
}
wrapLongLines = true
}
for i < n {
// Wrap long lines that are over the limit using escaped newlines
if wrapLongLines && startLineLength+i >= p.options.LineLimit {
js = append(js, "\\\n"...)
startLineLength -= p.options.LineLimit
}
c := text[i]
i++
switch c {
// Special-case the null character since it may mess with code written in C
// that treats null characters as the end of the string.
case '\x00':
// We don't want "\x001" to be written as "\01"
if i < n && text[i] >= '0' && text[i] <= '9' {
js = append(js, "\\x00"...)
} else {
js = append(js, "\\0"...)
}
// Special-case the bell character since it may cause dumping this file to
// the terminal to make a sound, which is undesirable. Note that we can't
// use an octal literal to print this shorter since octal literals are not
// allowed in strict mode (or in template strings).
case '\x07':
js = append(js, "\\x07"...)
case '\b':
js = append(js, "\\b"...)
case '\f':
js = append(js, "\\f"...)
case '\n':
if quote == '`' {
startLineLength = -i // Printing a real newline resets the line length
js = append(js, '\n')
} else {
js = append(js, "\\n"...)
}
case '\r':
js = append(js, "\\r"...)
case '\v':
js = append(js, "\\v"...)
case '\x1B':
js = append(js, "\\x1B"...)
case '\\':
js = append(js, "\\\\"...)
case '/':
// Avoid generating the sequence "</script" in JS code
if !p.options.UnsupportedFeatures.Has(compat.InlineScript) && i >= 2 && text[i-2] == '<' && i+6 <= len(text) {
script := "script"
matches := true
for j := 0; j < 6; j++ {
a := text[i+j]
b := uint16(script[j])
if a >= 'A' && a <= 'Z' {
a += 'a' - 'A'
}
if a != b {
matches = false
break
}
}
if matches {
js = append(js, '\\')
}
}
js = append(js, '/')
case '\'':
if quote == '\'' {
js = append(js, '\\')
}
js = append(js, '\'')
case '"':
if quote == '"' {
js = append(js, '\\')
}
js = append(js, '"')
case '`':
if quote == '`' {
js = append(js, '\\')
}
js = append(js, '`')
case '$':
if quote == '`' && i < n && text[i] == '{' {
js = append(js, '\\')
}
js = append(js, '$')
case '\u2028':
js = append(js, "\\u2028"...)
case '\u2029':
js = append(js, "\\u2029"...)
case '\uFEFF':
js = append(js, "\\uFEFF"...)
default:
switch {
// Common case: just append a single byte
case c <= lastASCII:
js = append(js, byte(c))
// Is this a high surrogate?
case c >= firstHighSurrogate && c <= lastHighSurrogate:
// Is there a next character?
if i < n {
c2 := text[i]
// Is it a low surrogate?
if c2 >= firstLowSurrogate && c2 <= lastLowSurrogate {
r := (rune(c) << 10) + rune(c2) + (0x10000 - (firstHighSurrogate << 10) - firstLowSurrogate)
i++
// Escape this character if UTF-8 isn't allowed
if p.options.ASCIIOnly {
if !p.options.UnsupportedFeatures.Has(compat.UnicodeEscapes) {
js = append(js, fmt.Sprintf("\\u{%X}", r)...)
} else {
js = append(js,
'\\', 'u', hexChars[c>>12], hexChars[(c>>8)&15], hexChars[(c>>4)&15], hexChars[c&15],
'\\', 'u', hexChars[c2>>12], hexChars[(c2>>8)&15], hexChars[(c2>>4)&15], hexChars[c2&15],
)
}
continue
}
// Otherwise, encode to UTF-8
width := utf8.EncodeRune(temp, r)
js = append(js, temp[:width]...)
continue
}
}
// Write an unpaired high surrogate
js = append(js, '\\', 'u', hexChars[c>>12], hexChars[(c>>8)&15], hexChars[(c>>4)&15], hexChars[c&15])
// Is this an unpaired low surrogate or four-digit hex escape?
case (c >= firstLowSurrogate && c <= lastLowSurrogate) || (p.options.ASCIIOnly && c > 0xFF):
js = append(js, '\\', 'u', hexChars[c>>12], hexChars[(c>>8)&15], hexChars[(c>>4)&15], hexChars[c&15])
// Can this be a two-digit hex escape?
case p.options.ASCIIOnly:
js = append(js, '\\', 'x', hexChars[c>>4], hexChars[c&15])
// Otherwise, just encode to UTF-8
default:
width := utf8.EncodeRune(temp, rune(c))
js = append(js, temp[:width]...)
}
}
}
p.js = js
}
// JSX tag syntax doesn't support character escapes so non-ASCII identifiers
// must be printed as UTF-8 even when the charset is set to ASCII.
func (p *printer) printJSXTag(tagOrNil js_ast.Expr) {
switch e := tagOrNil.Data.(type) {
case *js_ast.EString:
p.addSourceMapping(tagOrNil.Loc)
p.print(helpers.UTF16ToString(e.Value))
case *js_ast.EIdentifier:
name := p.renamer.NameForSymbol(e.Ref)
p.addSourceMappingForName(tagOrNil.Loc, name, e.Ref)
p.print(name)
case *js_ast.EDot:
p.printJSXTag(e.Target)
p.print(".")
p.addSourceMapping(e.NameLoc)
p.print(e.Name)
default:
if tagOrNil.Data != nil {
p.printExpr(tagOrNil, js_ast.LLowest, 0)
}
}
}
type printer struct {
symbols ast.SymbolMap
astHelpers js_ast.HelperContext
renamer renamer.Renamer
importRecords []ast.ImportRecord
callTarget js_ast.E
exprComments map[logger.Loc][]string
printedExprComments map[logger.Loc]bool
hasLegalComment map[string]struct{}
extractedLegalComments []string
js []byte
jsonMetadataImports []string
binaryExprStack []binaryExprVisitor
options Options
builder sourcemap.ChunkBuilder
printNextIndentAsSpace bool
stmtStart int
exportDefaultStart int
arrowExprStart int
forOfInitStart int
withNesting int
prevOpEnd int
needSpaceBeforeDot int
prevRegExpEnd int
noLeadingNewlineHere int
oldLineStart int
oldLineEnd int
intToBytesBuffer [64]byte
needsSemicolon bool
wasLazyExport bool
prevOp js_ast.OpCode
moduleType js_ast.ModuleType
}
func (p *printer) print(text string) {
p.js = append(p.js, text...)
}
// This is the same as "print(string(bytes))" without any unnecessary temporary
// allocations
func (p *printer) printBytes(bytes []byte) {
p.js = append(p.js, bytes...)
}
type printQuotedFlags uint8
const (
printQuotedAllowBacktick printQuotedFlags = 1 << iota
printQuotedNoWrap
)
func (p *printer) printQuotedUTF8(text string, flags printQuotedFlags) {
p.printQuotedUTF16(helpers.StringToUTF16(text), flags)
}
func (p *printer) addSourceMapping(loc logger.Loc) {
if p.options.AddSourceMappings {
p.builder.AddSourceMapping(loc, "", p.js)
}
}
func (p *printer) addSourceMappingForName(loc logger.Loc, name string, ref ast.Ref) {
if p.options.AddSourceMappings {
if originalName := p.symbols.Get(ast.FollowSymbols(p.symbols, ref)).OriginalName; originalName != name {
p.builder.AddSourceMapping(loc, originalName, p.js)
} else {
p.builder.AddSourceMapping(loc, "", p.js)
}
}
}
func (p *printer) printIndent() {
if p.options.MinifyWhitespace {
return
}
if p.printNextIndentAsSpace {
p.print(" ")
p.printNextIndentAsSpace = false
return
}
indent := p.options.Indent
if p.options.LineLimit > 0 && indent*2 >= p.options.LineLimit {
indent = p.options.LineLimit / 2
}
for i := 0; i < indent; i++ {
p.print(" ")
}
}
func (p *printer) mangledPropName(ref ast.Ref) string {
ref = ast.FollowSymbols(p.symbols, ref)
if name, ok := p.options.MangledProps[ref]; ok {
return name
}
return p.renamer.NameForSymbol(ref)
}
func (p *printer) tryToGetImportedEnumValue(target js_ast.Expr, name string) (js_ast.TSEnumValue, bool) {
if id, ok := target.Data.(*js_ast.EImportIdentifier); ok {
ref := ast.FollowSymbols(p.symbols, id.Ref)
if symbol := p.symbols.Get(ref); symbol.Kind == ast.SymbolTSEnum {
if enum, ok := p.options.TSEnums[ref]; ok {
value, ok := enum[name]
return value, ok
}
}
}
return js_ast.TSEnumValue{}, false
}
func (p *printer) tryToGetImportedEnumValueUTF16(target js_ast.Expr, name []uint16) (js_ast.TSEnumValue, string, bool) {
if id, ok := target.Data.(*js_ast.EImportIdentifier); ok {
ref := ast.FollowSymbols(p.symbols, id.Ref)
if symbol := p.symbols.Get(ref); symbol.Kind == ast.SymbolTSEnum {
if enum, ok := p.options.TSEnums[ref]; ok {
name := helpers.UTF16ToString(name)
value, ok := enum[name]
return value, name, ok
}
}
}
return js_ast.TSEnumValue{}, "", false
}
func (p *printer) printClauseAlias(loc logger.Loc, alias string) {
if js_ast.IsIdentifier(alias) {
p.printSpaceBeforeIdentifier()
p.addSourceMapping(loc)
p.printIdentifier(alias)
} else {
p.addSourceMapping(loc)
p.printQuotedUTF8(alias, 0)
}
}
// Note: The functions below check whether something can be printed as an
// identifier or if it needs to be quoted (e.g. "x.y" vs. "x['y']") using the
// ES5 identifier validity test to maximize cross-platform portability. Even
// though newer JavaScript environments can handle more Unicode characters,
// there isn't a published document that says which Unicode versions are
// supported by which browsers. Even if a character is considered valid in the
// latest version of Unicode, we don't know if the browser we're targeting
// contains an older version of Unicode or not. So for safety, we quote
// anything that isn't guaranteed to be compatible with ES5, the oldest
// JavaScript language target that we support.
func CanEscapeIdentifier(name string, UnsupportedFeatures compat.JSFeature, asciiOnly bool) bool {
return js_ast.IsIdentifierES5AndESNext(name) && (!asciiOnly ||
!UnsupportedFeatures.Has(compat.UnicodeEscapes) ||
!helpers.ContainsNonBMPCodePoint(name))
}
func (p *printer) canPrintIdentifier(name string) bool {
return js_ast.IsIdentifierES5AndESNext(name) && (!p.options.ASCIIOnly ||
!p.options.UnsupportedFeatures.Has(compat.UnicodeEscapes) ||
!helpers.ContainsNonBMPCodePoint(name))
}
func (p *printer) canPrintIdentifierUTF16(name []uint16) bool {
return js_ast.IsIdentifierES5AndESNextUTF16(name) && (!p.options.ASCIIOnly ||
!p.options.UnsupportedFeatures.Has(compat.UnicodeEscapes) ||
!helpers.ContainsNonBMPCodePointUTF16(name))
}
func (p *printer) printIdentifier(name string) {
if p.options.ASCIIOnly {
p.js = QuoteIdentifier(p.js, name, p.options.UnsupportedFeatures)
} else {
p.print(name)
}
}
// This is the same as "printIdentifier(StringToUTF16(bytes))" without any
// unnecessary temporary allocations
func (p *printer) printIdentifierUTF16(name []uint16) {
var temp [utf8.UTFMax]byte
n := len(name)
for i := 0; i < n; i++ {
c := rune(name[i])
if c >= firstHighSurrogate && c <= lastHighSurrogate && i+1 < n {
if c2 := rune(name[i+1]); c2 >= firstLowSurrogate && c2 <= lastLowSurrogate {
c = (c << 10) + c2 + (0x10000 - (firstHighSurrogate << 10) - firstLowSurrogate)
i++
}
}
if p.options.ASCIIOnly && c > lastASCII {
if c <= 0xFFFF {
p.js = append(p.js, '\\', 'u', hexChars[c>>12], hexChars[(c>>8)&15], hexChars[(c>>4)&15], hexChars[c&15])
} else if !p.options.UnsupportedFeatures.Has(compat.UnicodeEscapes) {
p.js = append(p.js, fmt.Sprintf("\\u{%X}", c)...)
} else {
panic("Internal error: Cannot encode identifier: Unicode escapes are unsupported")
}
continue
}
width := utf8.EncodeRune(temp[:], c)
p.js = append(p.js, temp[:width]...)
}
}
func (p *printer) printNumber(value float64, level js_ast.L) {
absValue := math.Abs(value)
if value != value {
p.printSpaceBeforeIdentifier()
if p.withNesting != 0 {
// "with (x) NaN" really means "x.NaN" so avoid identifiers when "with" is present
wrap := level >= js_ast.LMultiply
if wrap {
p.print("(")
}
if p.options.MinifyWhitespace {
p.print("0/0")
} else {
p.print("0 / 0")
}
if wrap {
p.print(")")
}
} else {
p.print("NaN")
}
} else if value == positiveInfinity || value == negativeInfinity {
// "with (x) Infinity" really means "x.Infinity" so avoid identifiers when "with" is present
wrap := ((p.options.MinifySyntax || p.withNesting != 0) && level >= js_ast.LMultiply) ||
(value == negativeInfinity && level >= js_ast.LPrefix)
if wrap {
p.print("(")
}
if value == negativeInfinity {
p.printSpaceBeforeOperator(js_ast.UnOpNeg)
p.print("-")
} else {
p.printSpaceBeforeIdentifier()
}
if !p.options.MinifySyntax && p.withNesting == 0 {
p.print("Infinity")
} else if p.options.MinifyWhitespace {
p.print("1/0")
} else {
p.print("1 / 0")
}
if wrap {
p.print(")")
}
} else {
if !math.Signbit(value) {
p.printSpaceBeforeIdentifier()
p.printNonNegativeFloat(absValue)
} else if level >= js_ast.LPrefix {
// Expressions such as "(-1).toString" need to wrap negative numbers.
// Instead of testing for "value < 0" we test for "signbit(value)" and
// "!isNaN(value)" because we need this to be true for "-0" and "-0 < 0"
// is false.
p.print("(-")
p.printNonNegativeFloat(absValue)
p.print(")")
} else {
p.printSpaceBeforeOperator(js_ast.UnOpNeg)
p.print("-")
p.printNonNegativeFloat(absValue)
}
}
}
func (p *printer) willPrintExprCommentsAtLoc(loc logger.Loc) bool {
return !p.options.MinifyWhitespace && p.exprComments[loc] != nil && !p.printedExprComments[loc]
}
func (p *printer) willPrintExprCommentsForAnyOf(exprs []js_ast.Expr) bool {
for _, expr := range exprs {
if p.willPrintExprCommentsAtLoc(expr.Loc) {
return true
}
}
return false
}
func (p *printer) printBinding(binding js_ast.Binding) {
switch b := binding.Data.(type) {
case *js_ast.BMissing:
p.addSourceMapping(binding.Loc)
case *js_ast.BIdentifier:
name := p.renamer.NameForSymbol(b.Ref)
p.printSpaceBeforeIdentifier()
p.addSourceMappingForName(binding.Loc, name, b.Ref)
p.printIdentifier(name)
case *js_ast.BArray:
isMultiLine := (len(b.Items) > 0 && !b.IsSingleLine) || p.willPrintExprCommentsAtLoc(b.CloseBracketLoc)
if !p.options.MinifyWhitespace && !isMultiLine {
for _, item := range b.Items {
if p.willPrintExprCommentsAtLoc(item.Loc) {
isMultiLine = true
break
}
}
}
p.addSourceMapping(binding.Loc)
p.print("[")
if len(b.Items) > 0 || isMultiLine {
if isMultiLine {
p.options.Indent++
}
for i, item := range b.Items {
if i != 0 {
p.print(",")
}
if p.options.LineLimit <= 0 || !p.printNewlinePastLineLimit() {
if isMultiLine {
p.printNewline()
p.printIndent()
} else if i != 0 {
p.printSpace()
}
}
p.printExprCommentsAtLoc(item.Loc)
if b.HasSpread && i+1 == len(b.Items) {
p.addSourceMapping(item.Loc)
p.print("...")
p.printExprCommentsAtLoc(item.Binding.Loc)
}
p.printBinding(item.Binding)
if item.DefaultValueOrNil.Data != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExprWithoutLeadingNewline(item.DefaultValueOrNil, js_ast.LComma, 0)
}
// Make sure there's a comma after trailing missing items
if _, ok := item.Binding.Data.(*js_ast.BMissing); ok && i == len(b.Items)-1 {
p.print(",")
}
}
if isMultiLine {
p.printNewline()
p.printExprCommentsAfterCloseTokenAtLoc(b.CloseBracketLoc)
p.options.Indent--
p.printIndent()
}
}
p.addSourceMapping(b.CloseBracketLoc)
p.print("]")
case *js_ast.BObject:
isMultiLine := (len(b.Properties) > 0 && !b.IsSingleLine) || p.willPrintExprCommentsAtLoc(b.CloseBraceLoc)
if !p.options.MinifyWhitespace && !isMultiLine {
for _, property := range b.Properties {
if p.willPrintExprCommentsAtLoc(property.Loc) {
isMultiLine = true
break
}
}
}
p.addSourceMapping(binding.Loc)
p.print("{")
if len(b.Properties) > 0 || isMultiLine {
if isMultiLine {
p.options.Indent++
}
for i, property := range b.Properties {
if i != 0 {
p.print(",")
}
if p.options.LineLimit <= 0 || !p.printNewlinePastLineLimit() {
if isMultiLine {
p.printNewline()
p.printIndent()
} else {
p.printSpace()
}
}
p.printExprCommentsAtLoc(property.Loc)
if property.IsSpread {
p.addSourceMapping(property.Loc)
p.print("...")
p.printExprCommentsAtLoc(property.Value.Loc)
} else {
if property.IsComputed {
p.addSourceMapping(property.Loc)
isMultiLine := p.willPrintExprCommentsAtLoc(property.Key.Loc) || p.willPrintExprCommentsAtLoc(property.CloseBracketLoc)
p.print("[")
if isMultiLine {
p.printNewline()
p.options.Indent++
p.printIndent()
}
p.printExpr(property.Key, js_ast.LComma, 0)
if isMultiLine {
p.printNewline()
p.printExprCommentsAfterCloseTokenAtLoc(property.CloseBracketLoc)
p.options.Indent--
p.printIndent()
}
if property.CloseBracketLoc.Start > property.Loc.Start {
p.addSourceMapping(property.CloseBracketLoc)
}
p.print("]:")
p.printSpace()
p.printBinding(property.Value)
if property.DefaultValueOrNil.Data != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExprWithoutLeadingNewline(property.DefaultValueOrNil, js_ast.LComma, 0)
}
continue
}
if str, ok := property.Key.Data.(*js_ast.EString); ok && !property.PreferQuotedKey && p.canPrintIdentifierUTF16(str.Value) {
// Use a shorthand property if the names are the same
if id, ok := property.Value.Data.(*js_ast.BIdentifier); ok &&
!p.willPrintExprCommentsAtLoc(property.Value.Loc) &&
helpers.UTF16EqualsString(str.Value, p.renamer.NameForSymbol(id.Ref)) {
if p.options.AddSourceMappings {
p.addSourceMappingForName(property.Key.Loc, helpers.UTF16ToString(str.Value), id.Ref)
}
p.printIdentifierUTF16(str.Value)
if property.DefaultValueOrNil.Data != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExprWithoutLeadingNewline(property.DefaultValueOrNil, js_ast.LComma, 0)
}
continue
}
p.addSourceMapping(property.Key.Loc)
p.printIdentifierUTF16(str.Value)
} else if mangled, ok := property.Key.Data.(*js_ast.ENameOfSymbol); ok {
if name := p.mangledPropName(mangled.Ref); p.canPrintIdentifier(name) {
p.addSourceMappingForName(property.Key.Loc, name, mangled.Ref)
p.printIdentifier(name)
// Use a shorthand property if the names are the same
if id, ok := property.Value.Data.(*js_ast.BIdentifier); ok &&
!p.willPrintExprCommentsAtLoc(property.Value.Loc) &&
name == p.renamer.NameForSymbol(id.Ref) {
if property.DefaultValueOrNil.Data != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExprWithoutLeadingNewline(property.DefaultValueOrNil, js_ast.LComma, 0)
}
continue
}
} else {
p.addSourceMapping(property.Key.Loc)
p.printQuotedUTF8(name, 0)
}
} else {
p.printExpr(property.Key, js_ast.LLowest, 0)
}
p.print(":")
p.printSpace()
}
p.printBinding(property.Value)
if property.DefaultValueOrNil.Data != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExprWithoutLeadingNewline(property.DefaultValueOrNil, js_ast.LComma, 0)
}
}
if isMultiLine {
p.printNewline()
p.printExprCommentsAfterCloseTokenAtLoc(b.CloseBraceLoc)
p.options.Indent--
p.printIndent()
} else {
// This block is only reached if len(b.Properties) > 0
p.printSpace()
}
}
p.addSourceMapping(b.CloseBraceLoc)
p.print("}")
default:
panic(fmt.Sprintf("Unexpected binding of type %T", binding.Data))
}
}
func (p *printer) printSpace() {
if !p.options.MinifyWhitespace {
p.print(" ")
}
}
func (p *printer) printNewline() {
if !p.options.MinifyWhitespace {
p.print("\n")
}
}
func (p *printer) currentLineLength() int {
js := p.js
n := len(js)
stop := p.oldLineEnd
// Update "oldLineStart" to the start of the current line
for i := n; i > stop; i-- {
if c := js[i-1]; c == '\r' || c == '\n' {
p.oldLineStart = i
break
}
}
p.oldLineEnd = n
return n - p.oldLineStart
}
func (p *printer) printNewlinePastLineLimit() bool {
if p.currentLineLength() < p.options.LineLimit {
return false
}
p.print("\n")
p.printIndent()
return true
}
func (p *printer) printSpaceBeforeOperator(next js_ast.OpCode) {
if p.prevOpEnd == len(p.js) {
prev := p.prevOp
// "+ + y" => "+ +y"
// "+ ++ y" => "+ ++y"
// "x + + y" => "x+ +y"
// "x ++ + y" => "x+++y"
// "x + ++ y" => "x+ ++y"
// "-- >" => "-- >"
// "< ! --" => "<! --"
if ((prev == js_ast.BinOpAdd || prev == js_ast.UnOpPos) && (next == js_ast.BinOpAdd || next == js_ast.UnOpPos || next == js_ast.UnOpPreInc)) ||
((prev == js_ast.BinOpSub || prev == js_ast.UnOpNeg) && (next == js_ast.BinOpSub || next == js_ast.UnOpNeg || next == js_ast.UnOpPreDec)) ||
(prev == js_ast.UnOpPostDec && next == js_ast.BinOpGt) ||
(prev == js_ast.UnOpNot && next == js_ast.UnOpPreDec && len(p.js) > 1 && p.js[len(p.js)-2] == '<') {
p.print(" ")
}
}
}
func (p *printer) printSemicolonAfterStatement() {
if !p.options.MinifyWhitespace {
p.print(";\n")
} else {
p.needsSemicolon = true
}
}
func (p *printer) printSemicolonIfNeeded() {
if p.needsSemicolon {
p.print(";")
p.needsSemicolon = false
}
}
func (p *printer) printSpaceBeforeIdentifier() {
if c, _ := utf8.DecodeLastRune(p.js); js_ast.IsIdentifierContinue(c) || p.prevRegExpEnd == len(p.js) {
p.print(" ")
}
}
type fnArgsOpts struct {
openParenLoc logger.Loc
addMappingForOpenParenLoc bool
hasRestArg bool
isArrow bool
}
func (p *printer) printFnArgs(args []js_ast.Arg, opts fnArgsOpts) {
wrap := true
// Minify "(a) => {}" as "a=>{}"
if p.options.MinifyWhitespace && !opts.hasRestArg && opts.isArrow && len(args) == 1 {
if _, ok := args[0].Binding.Data.(*js_ast.BIdentifier); ok && args[0].DefaultOrNil.Data == nil {
wrap = false
}
}
if wrap {
if opts.addMappingForOpenParenLoc {
p.addSourceMapping(opts.openParenLoc)
}
p.print("(")
}
for i, arg := range args {
if i != 0 {
p.print(",")
p.printSpace()
}
p.printDecorators(arg.Decorators, printSpaceAfterDecorator)
if opts.hasRestArg && i+1 == len(args) {
p.print("...")
}
p.printBinding(arg.Binding)
if arg.DefaultOrNil.Data != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExprWithoutLeadingNewline(arg.DefaultOrNil, js_ast.LComma, 0)
}
}
if wrap {
p.print(")")
}
}
func (p *printer) printFn(fn js_ast.Fn) {
p.printFnArgs(fn.Args, fnArgsOpts{hasRestArg: fn.HasRestArg})
p.printSpace()
p.printBlock(fn.Body.Loc, fn.Body.Block)
}
type printAfterDecorator uint8
const (
printNewlineAfterDecorator printAfterDecorator = iota
printSpaceAfterDecorator
)
func (p *printer) printDecorators(decorators []js_ast.Decorator, defaultMode printAfterDecorator) (omitIndentAfter bool) {
oldMode := defaultMode
for _, decorator := range decorators {
wrap := false
wasCallTarget := false
expr := decorator.Value
mode := defaultMode
if decorator.OmitNewlineAfter {
mode = printSpaceAfterDecorator
}
outer:
for {
isCallTarget := wasCallTarget
wasCallTarget = false
switch e := expr.Data.(type) {
case *js_ast.EIdentifier:
// "@foo"
break outer
case *js_ast.ECall:
// "@foo()"
expr = e.Target
wasCallTarget = true
continue
case *js_ast.EDot:
// "@foo.bar"
if p.canPrintIdentifier(e.Name) {
expr = e.Target
continue
}
// "@foo.\u30FF" => "@(foo['\u30FF'])"
break
case *js_ast.EIndex:
if _, ok := e.Index.Data.(*js_ast.EPrivateIdentifier); ok {
// "@foo.#bar"
expr = e.Target
continue
}
// "@(foo[bar])"
break
case *js_ast.EImportIdentifier:
ref := ast.FollowSymbols(p.symbols, e.Ref)
symbol := p.symbols.Get(ref)
if symbol.ImportItemStatus == ast.ImportItemMissing {
// "@(void 0)"
break
}
if symbol.NamespaceAlias != nil && isCallTarget && e.WasOriginallyIdentifier {
// "@((0, import_ns.fn)())"
break
}
if value := p.options.ConstValues[ref]; value.Kind != js_ast.ConstValueNone {
// "@(<inlined constant>)"
break
}
// "@foo"
// "@import_ns.fn"
break outer
default:
// "@(foo + bar)"
// "@(() => {})"
break
}
wrap = true
break outer
}
p.addSourceMapping(decorator.AtLoc)
if oldMode == printNewlineAfterDecorator {
p.printIndent()