-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathprinter.go
2953 lines (2555 loc) · 65.8 KB
/
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 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/lexer"
"github.com/evanw/esbuild/internal/logging"
"github.com/evanw/esbuild/internal/sourcemap"
)
var positiveInfinity = math.Inf(1)
var negativeInfinity = math.Inf(-1)
// Coordinates in source maps are stored using relative offsets for size
// reasons. When joining together chunks of a source map that were emitted
// in parallel for different parts of a file, we need to fix up the first
// segment of each chunk to be relative to the end of the previous chunk.
type SourceMapState struct {
// This isn't stored in the source map. It's only used by the bundler to join
// source map chunks together correctly.
GeneratedLine int
// These are stored in the source map in VLQ format.
GeneratedColumn int
SourceIndex int
OriginalLine int
OriginalColumn int
}
// Source map chunks are computed in parallel for speed. Each chunk is relative
// to the zero state instead of being relative to the end state of the previous
// chunk, since it's impossible to know the end state of the previous chunk in
// a parallel computation.
//
// After all chunks are computed, they are joined together in a second pass.
// This rewrites the first mapping in each chunk to be relative to the end
// state of the previous chunk.
func AppendSourceMapChunk(j *Joiner, prevEndState SourceMapState, startState SourceMapState, sourceMap []byte) {
// Handle line breaks in between this mapping and the previous one
if startState.GeneratedLine != 0 {
j.AddBytes(bytes.Repeat([]byte{';'}, startState.GeneratedLine))
prevEndState.GeneratedColumn = 0
}
// Skip past any leading semicolons, which indicate line breaks
semicolons := 0
for sourceMap[semicolons] == ';' {
semicolons++
}
if semicolons > 0 {
j.AddBytes(sourceMap[:semicolons])
sourceMap = sourceMap[semicolons:]
prevEndState.GeneratedColumn = 0
startState.GeneratedColumn = 0
}
// Strip off the first mapping from the buffer. The first mapping should be
// for the start of the original file (the printer always generates one for
// the start of the file).
generatedColumn, i := sourcemap.DecodeVLQ(sourceMap, 0)
sourceIndex, i := sourcemap.DecodeVLQ(sourceMap, i)
originalLine, i := sourcemap.DecodeVLQ(sourceMap, i)
originalColumn, i := sourcemap.DecodeVLQ(sourceMap, i)
sourceMap = sourceMap[i:]
// Rewrite the first mapping to be relative to the end state of the previous
// chunk. We now know what the end state is because we're in the second pass
// where all chunks have already been generated.
startState.SourceIndex += sourceIndex
startState.GeneratedColumn += generatedColumn
startState.OriginalLine = originalLine
startState.OriginalColumn = originalColumn
j.AddBytes(appendMapping(nil, j.lastByte, prevEndState, startState))
// Then append everything after that without modification.
j.AddBytes(sourceMap)
}
func appendMapping(buffer []byte, lastByte byte, prevState SourceMapState, currentState SourceMapState) []byte {
// Put commas in between mappings
if lastByte != 0 && lastByte != ';' && lastByte != '"' {
buffer = append(buffer, ',')
}
// Record the generated column (the line is recorded using ';' elsewhere)
buffer = append(buffer, sourcemap.EncodeVLQ(currentState.GeneratedColumn-prevState.GeneratedColumn)...)
prevState.GeneratedColumn = currentState.GeneratedColumn
// Record the generated source
buffer = append(buffer, sourcemap.EncodeVLQ(currentState.SourceIndex-prevState.SourceIndex)...)
prevState.SourceIndex = currentState.SourceIndex
// Record the original line
buffer = append(buffer, sourcemap.EncodeVLQ(currentState.OriginalLine-prevState.OriginalLine)...)
prevState.OriginalLine = currentState.OriginalLine
// Record the original column
buffer = append(buffer, sourcemap.EncodeVLQ(currentState.OriginalColumn-prevState.OriginalColumn)...)
prevState.OriginalColumn = currentState.OriginalColumn
return buffer
}
// This provides an efficient way to join lots of big string and byte slices
// together. It avoids the cost of repeatedly reallocating as the buffer grows
// by measuring exactly how big the buffer should be and then allocating once.
// This is a measurable speedup.
type Joiner struct {
lastByte byte
strings []joinerString
bytes []joinerBytes
length uint32
}
type joinerString struct {
data string
offset uint32
}
type joinerBytes struct {
data []byte
offset uint32
}
func (j *Joiner) AddString(data string) {
if len(data) > 0 {
j.lastByte = data[len(data)-1]
}
j.strings = append(j.strings, joinerString{data, j.length})
j.length += uint32(len(data))
}
func (j *Joiner) AddBytes(data []byte) {
if len(data) > 0 {
j.lastByte = data[len(data)-1]
}
j.bytes = append(j.bytes, joinerBytes{data, j.length})
j.length += uint32(len(data))
}
func (j *Joiner) LastByte() byte {
return j.lastByte
}
func (j *Joiner) Length() uint32 {
return j.length
}
func (j *Joiner) Done() []byte {
buffer := make([]byte, j.length)
for _, item := range j.strings {
copy(buffer[item.offset:], item.data)
}
for _, item := range j.bytes {
copy(buffer[item.offset:], item.data)
}
return buffer
}
const hexChars = "0123456789ABCDEF"
func QuoteForJSON(text string) string {
return quoteImpl(text, true)
}
func Quote(text string) string {
return quoteImpl(text, false)
}
func quoteImpl(text string, forJSON bool) string {
b := strings.Builder{}
i := 0
n := len(text)
b.WriteByte('"')
for i < n {
c := text[i]
// Fast path: a run of characters that don't need escaping
if c >= 0x20 && c <= 0x7E && c != '\\' && c != '"' {
start := i
i += 1
for i < n {
c = text[i]
if c < 0x20 || c > 0x7E || c == '\\' || c == '"' {
break
}
i += 1
}
b.WriteString(text[start:i])
continue
}
switch c {
case '\b':
b.WriteString("\\b")
i++
case '\f':
b.WriteString("\\f")
i++
case '\n':
b.WriteString("\\n")
i++
case '\r':
b.WriteString("\\r")
i++
case '\t':
b.WriteString("\\t")
i++
case '\v':
b.WriteString("\\v")
i++
case '\\':
b.WriteString("\\\\")
i++
case '"':
b.WriteString("\\\"")
i++
default:
r, width := lexer.DecodeWTF8Rune(text[i:])
i += width
if r <= 0xFF && !forJSON {
b.WriteString("\\x")
b.WriteByte(hexChars[r>>4])
b.WriteByte(hexChars[r&15])
} else if r <= 0xFFFF {
b.WriteString("\\u")
b.WriteByte(hexChars[r>>12])
b.WriteByte(hexChars[(r>>8)&15])
b.WriteByte(hexChars[(r>>4)&15])
b.WriteByte(hexChars[r&15])
} else {
r -= 0x10000
lo := 0xD800 + ((r >> 10) & 0x3FF)
hi := 0xDC00 + (r & 0x3FF)
b.WriteString("\\u")
b.WriteByte(hexChars[lo>>12])
b.WriteByte(hexChars[(lo>>8)&15])
b.WriteByte(hexChars[(lo>>4)&15])
b.WriteByte(hexChars[lo&15])
b.WriteString("\\u")
b.WriteByte(hexChars[hi>>12])
b.WriteByte(hexChars[(hi>>8)&15])
b.WriteByte(hexChars[(hi>>4)&15])
b.WriteByte(hexChars[hi&15])
}
}
}
b.WriteByte('"')
return b.String()
}
// This is the same as "print(quoteUTF16(text))" without any unnecessary
// temporary allocations
func (p *printer) printQuotedUTF16(text []uint16, quote rune) {
temp := make([]byte, utf8.UTFMax)
js := p.js
i := 0
n := len(text)
for i < n {
c := text[i]
i++
switch c {
case '\x00':
// We don't want "\x001" to be written as "\01"
if i >= n || text[i] < '0' || text[i] > '9' {
js = append(js, "\\0"...)
} else {
js = append(js, "\\x00"...)
}
case '\b':
js = append(js, "\\b"...)
case '\f':
js = append(js, "\\f"...)
case '\n':
if quote == '`' {
js = append(js, '\n')
} else {
js = append(js, "\\n"...)
}
case '\r':
js = append(js, "\\r"...)
case '\v':
js = append(js, "\\v"...)
case '\\':
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"...)
default:
switch {
// Is this a high surrogate?
case c >= 0xD800 && c <= 0xDBFF:
// Is there a next character?
if i < n {
c2 := text[i]
// Is it a low surrogate?
if c2 >= 0xDC00 && c2 <= 0xDFFF {
i++
width := utf8.EncodeRune(temp, (rune(c)<<10)+rune(c2)+(0x10000-(0xD800<<10)-0xDC00))
js = append(js, temp[:width]...)
continue
}
}
// Write an escaped character
js = append(js, '\\', 'u', hexChars[c>>12], hexChars[(c>>8)&15], hexChars[(c>>4)&15], hexChars[c&15])
// Is this a low surrogate?
case c >= 0xDC00 && c <= 0xDFFF:
// Write an escaped character
js = append(js, '\\', 'u', hexChars[c>>12], hexChars[(c>>8)&15], hexChars[(c>>4)&15], hexChars[c&15])
default:
if c < utf8.RuneSelf {
js = append(js, byte(c))
} else {
width := utf8.EncodeRune(temp, rune(c))
js = append(js, temp[:width]...)
}
}
}
}
p.js = js
}
type printer struct {
symbols ast.SymbolMap
importRecords []ast.ImportRecord
options PrintOptions
extractedComments map[string]bool
needsSemicolon bool
js []byte
stmtStart int
exportDefaultStart int
arrowExprStart int
prevOp ast.OpCode
prevOpEnd int
prevNumEnd int
prevRegExpEnd int
intToBytesBuffer [64]byte
// For source maps
sourceMap []byte
prevLoc ast.Loc
prevState SourceMapState
lastGeneratedUpdate int
generatedColumn int
hasPrevState bool
lineOffsetTables []lineOffsetTable
// This is a workaround for a bug in the popular "source-map" library:
// https://github.com/mozilla/source-map/issues/261. The library will
// sometimes return null when querying a source map unless every line
// starts with a mapping at column zero.
//
// The workaround is to replicate the previous mapping if a line ends
// up not starting with a mapping. This is done lazily because we want
// to avoid replicating the previous mapping if we don't need to.
lineStartsWithMapping bool
coverLinesWithoutMappings bool
}
type lineOffsetTable struct {
byteOffsetToStartOfLine int32
// The source map specification is very loose and does not specify what
// column numbers actually mean. The popular "source-map" library from Mozilla
// appears to interpret them as counts of UTF-16 code units, so we generate
// those too for compatibility.
//
// We keep mapping tables around to accelerate conversion from byte offsets
// to UTF-16 code unit counts. However, this mapping takes up a lot of memory
// and generates a lot of garbage. Since most JavaScript is ASCII and the
// mapping for ASCII is 1:1, we avoid creating a table for ASCII-only lines
// as an optimization.
byteOffsetToFirstNonASCII int32
columnsForNonASCII []int32
}
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...)
}
// This is the same as "print(lexer.UTF16ToString(text))" without any
// unnecessary temporary allocations
func (p *printer) printUTF16(text []uint16) {
p.js = lexer.AppendUTF16ToBytes(p.js, text)
}
func (p *printer) addSourceMapping(loc ast.Loc) {
if p.options.SourceForSourceMap == nil || loc == p.prevLoc {
return
}
p.prevLoc = loc
// Binary search to find the line
lineOffsetTables := p.lineOffsetTables
count := len(lineOffsetTables)
originalLine := 0
for count > 0 {
step := count / 2
i := originalLine + step
if lineOffsetTables[i].byteOffsetToStartOfLine <= loc.Start {
originalLine = i + 1
count = count - step - 1
} else {
count = step
}
}
originalLine--
// Use the line to compute the column
line := &lineOffsetTables[originalLine]
originalColumn := int(loc.Start - line.byteOffsetToStartOfLine)
if line.columnsForNonASCII != nil && originalColumn >= int(line.byteOffsetToFirstNonASCII) {
originalColumn = int(line.columnsForNonASCII[originalColumn-int(line.byteOffsetToFirstNonASCII)])
}
p.updateGeneratedLineAndColumn()
// If this line doesn't start with a mapping and we're about to add a mapping
// that's not at the start, insert a mapping first so the line starts with one.
if p.coverLinesWithoutMappings && !p.lineStartsWithMapping && p.generatedColumn > 0 && p.hasPrevState {
p.appendMappingWithoutRemapping(SourceMapState{
GeneratedLine: p.prevState.GeneratedLine,
GeneratedColumn: 0,
SourceIndex: p.prevState.SourceIndex,
OriginalLine: p.prevState.OriginalLine,
OriginalColumn: p.prevState.OriginalColumn,
})
}
p.appendMapping(SourceMapState{
GeneratedLine: p.prevState.GeneratedLine,
GeneratedColumn: p.generatedColumn,
OriginalLine: originalLine,
OriginalColumn: originalColumn,
})
// This line now has a mapping on it, so don't insert another one
p.lineStartsWithMapping = true
}
// Scan over the printed text since the last source mapping and update the
// generated line and column numbers
func (p *printer) updateGeneratedLineAndColumn() {
for i, c := range string(p.js[p.lastGeneratedUpdate:]) {
switch c {
case '\r', '\n', '\u2028', '\u2029':
// Handle Windows-specific "\r\n" newlines
if c == '\r' {
newlineCheck := p.lastGeneratedUpdate + i + 1
if newlineCheck < len(p.js) && p.js[newlineCheck] == '\n' {
continue
}
}
// If we're about to move to the next line and the previous line didn't have
// any mappings, add a mapping at the start of the previous line.
if p.coverLinesWithoutMappings && !p.lineStartsWithMapping && p.hasPrevState {
p.appendMappingWithoutRemapping(SourceMapState{
GeneratedLine: p.prevState.GeneratedLine,
GeneratedColumn: 0,
SourceIndex: p.prevState.SourceIndex,
OriginalLine: p.prevState.OriginalLine,
OriginalColumn: p.prevState.OriginalColumn,
})
}
p.prevState.GeneratedLine++
p.prevState.GeneratedColumn = 0
p.generatedColumn = 0
p.sourceMap = append(p.sourceMap, ';')
// This new line doesn't have a mapping yet
p.lineStartsWithMapping = false
default:
// Mozilla's "source-map" library counts columns using UTF-16 code units
if c <= 0xFFFF {
p.generatedColumn++
} else {
p.generatedColumn += 2
}
}
}
p.lastGeneratedUpdate = len(p.js)
}
func generateLineOffsetTables(contents string) []lineOffsetTable {
var lineOffsetTables []lineOffsetTable
var columnsForNonASCII []int32
byteOffsetToFirstNonASCII := int32(0)
lineByteOffset := 0
columnByteOffset := 0
column := int32(0)
for i, c := range contents {
// Mark the start of the next line
if column == 0 {
lineByteOffset = i
}
// Start the mapping if this character is non-ASCII
if c > 0x7F && columnsForNonASCII == nil {
columnByteOffset = i - lineByteOffset
byteOffsetToFirstNonASCII = int32(columnByteOffset)
columnsForNonASCII = []int32{}
}
// Update the per-byte column offsets
if columnsForNonASCII != nil {
for lineBytesSoFar := i - lineByteOffset; columnByteOffset <= lineBytesSoFar; columnByteOffset++ {
columnsForNonASCII = append(columnsForNonASCII, column)
}
}
switch c {
case '\r', '\n', '\u2028', '\u2029':
// Handle Windows-specific "\r\n" newlines
if c == '\r' {
if i+1 < len(contents) && contents[i+1] == '\n' {
continue
}
}
lineOffsetTables = append(lineOffsetTables, lineOffsetTable{
byteOffsetToStartOfLine: int32(lineByteOffset),
byteOffsetToFirstNonASCII: byteOffsetToFirstNonASCII,
columnsForNonASCII: columnsForNonASCII,
})
columnByteOffset = 0
byteOffsetToFirstNonASCII = 0
columnsForNonASCII = nil
column = 0
default:
// Mozilla's "source-map" library counts columns using UTF-16 code units
if c <= 0xFFFF {
column++
} else {
column += 2
}
}
}
// Mark the start of the next line
if column == 0 {
lineByteOffset = len(contents)
}
// Do one last update for the column at the end of the file
if columnsForNonASCII != nil {
for lineBytesSoFar := len(contents) - lineByteOffset; columnByteOffset <= lineBytesSoFar; columnByteOffset++ {
columnsForNonASCII = append(columnsForNonASCII, column)
}
}
lineOffsetTables = append(lineOffsetTables, lineOffsetTable{
byteOffsetToStartOfLine: int32(lineByteOffset),
byteOffsetToFirstNonASCII: byteOffsetToFirstNonASCII,
columnsForNonASCII: columnsForNonASCII,
})
return lineOffsetTables
}
func (p *printer) appendMapping(currentState SourceMapState) {
// If the input file had a source map, map all the way back to the original
if p.options.InputSourceMap != nil {
mapping := p.options.InputSourceMap.Find(
int32(currentState.OriginalLine),
int32(currentState.OriginalColumn))
// Some locations won't have a mapping
if mapping == nil {
return
}
currentState.SourceIndex = int(mapping.SourceIndex)
currentState.OriginalLine = int(mapping.OriginalLine)
currentState.OriginalColumn = int(mapping.OriginalColumn)
}
p.appendMappingWithoutRemapping(currentState)
}
func (p *printer) appendMappingWithoutRemapping(currentState SourceMapState) {
var lastByte byte
if len(p.sourceMap) != 0 {
lastByte = p.sourceMap[len(p.sourceMap)-1]
}
p.sourceMap = appendMapping(p.sourceMap, lastByte, p.prevState, currentState)
p.prevState = currentState
p.hasPrevState = true
}
func (p *printer) printIndent() {
if !p.options.RemoveWhitespace {
for i := 0; i < p.options.Indent; i++ {
p.print(" ")
}
}
}
func (p *printer) symbolName(ref ast.Ref) string {
ref = ast.FollowSymbols(p.symbols, ref)
return p.symbols.Get(ref).Name
}
func (p *printer) printSymbol(ref ast.Ref) {
ref = ast.FollowSymbols(p.symbols, ref)
symbol := p.symbols.Get(ref)
p.printSpaceBeforeIdentifier()
p.print(symbol.Name)
}
func (p *printer) printBinding(binding ast.Binding) {
p.addSourceMapping(binding.Loc)
switch b := binding.Data.(type) {
case *ast.BMissing:
case *ast.BIdentifier:
p.printSymbol(b.Ref)
case *ast.BArray:
p.print("[")
if len(b.Items) > 0 {
if !b.IsSingleLine {
p.options.Indent++
}
for i, item := range b.Items {
if i != 0 {
p.print(",")
if b.IsSingleLine {
p.printSpace()
}
}
if !b.IsSingleLine {
p.printNewline()
p.printIndent()
}
if b.HasSpread && i+1 == len(b.Items) {
p.print("...")
}
p.printBinding(item.Binding)
if item.DefaultValue != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExpr(*item.DefaultValue, ast.LComma, 0)
}
// Make sure there's a comma after trailing missing items
if _, ok := item.Binding.Data.(*ast.BMissing); ok && i == len(b.Items)-1 {
p.print(",")
}
}
if !b.IsSingleLine {
p.options.Indent--
p.printNewline()
p.printIndent()
}
}
p.print("]")
case *ast.BObject:
p.print("{")
if len(b.Properties) > 0 {
if !b.IsSingleLine {
p.options.Indent++
}
for i, property := range b.Properties {
if i != 0 {
p.print(",")
if b.IsSingleLine {
p.printSpace()
}
}
if !b.IsSingleLine {
p.printNewline()
p.printIndent()
}
if property.IsSpread {
p.print("...")
} else {
if property.IsComputed {
p.print("[")
p.printExpr(property.Key, ast.LComma, 0)
p.print("]:")
p.printSpace()
p.printBinding(property.Value)
if property.DefaultValue != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExpr(*property.DefaultValue, ast.LComma, 0)
}
continue
}
if str, ok := property.Key.Data.(*ast.EString); ok {
if lexer.IsIdentifierUTF16(str.Value) {
p.addSourceMapping(property.Key.Loc)
p.printSpaceBeforeIdentifier()
p.printUTF16(str.Value)
// Use a shorthand property if the names are the same
if id, ok := property.Value.Data.(*ast.BIdentifier); ok && lexer.UTF16EqualsString(str.Value, p.symbolName(id.Ref)) {
if property.DefaultValue != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExpr(*property.DefaultValue, ast.LComma, 0)
}
continue
}
} else {
p.printExpr(property.Key, ast.LLowest, 0)
}
} else {
p.printExpr(property.Key, ast.LLowest, 0)
}
p.print(":")
p.printSpace()
}
p.printBinding(property.Value)
if property.DefaultValue != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExpr(*property.DefaultValue, ast.LComma, 0)
}
}
if !b.IsSingleLine {
p.options.Indent--
p.printNewline()
p.printIndent()
}
}
p.print("}")
default:
panic(fmt.Sprintf("Unexpected binding of type %T", binding.Data))
}
}
func (p *printer) printSpace() {
if !p.options.RemoveWhitespace {
p.print(" ")
}
}
func (p *printer) printNewline() {
if !p.options.RemoveWhitespace {
p.print("\n")
}
}
func (p *printer) printSpaceBeforeOperator(next 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 == ast.BinOpAdd || prev == ast.UnOpPos) && (next == ast.BinOpAdd || next == ast.UnOpPos || next == ast.UnOpPreInc)) ||
((prev == ast.BinOpSub || prev == ast.UnOpNeg) && (next == ast.BinOpSub || next == ast.UnOpNeg || next == ast.UnOpPreDec)) ||
(prev == ast.UnOpPostDec && next == ast.BinOpGt) ||
(prev == ast.UnOpNot && next == ast.UnOpPreDec && len(p.js) > 1 && p.js[len(p.js)-2] == '<') {
p.print(" ")
}
}
}
func (p *printer) printSemicolonAfterStatement() {
if !p.options.RemoveWhitespace {
p.print(";\n")
} else {
p.needsSemicolon = true
}
}
func (p *printer) printSemicolonIfNeeded() {
if p.needsSemicolon {
p.print(";")
p.needsSemicolon = false
}
}
func (p *printer) printSpaceBeforeIdentifier() {
buffer := p.js
n := len(buffer)
if n > 0 && (lexer.IsIdentifierContinue(rune(buffer[n-1])) || n == p.prevRegExpEnd) {
p.print(" ")
}
}
func (p *printer) printFnArgs(args []ast.Arg, hasRestArg bool, isArrow bool) {
wrap := true
// Minify "(a) => {}" as "a=>{}"
if p.options.RemoveWhitespace && !hasRestArg && isArrow && len(args) == 1 {
if _, ok := args[0].Binding.Data.(*ast.BIdentifier); ok && args[0].Default == nil {
wrap = false
}
}
if wrap {
p.print("(")
}
for i, arg := range args {
if i != 0 {
p.print(",")
p.printSpace()
}
if hasRestArg && i+1 == len(args) {
p.print("...")
}
p.printBinding(arg.Binding)
if arg.Default != nil {
p.printSpace()
p.print("=")
p.printSpace()
p.printExpr(*arg.Default, ast.LComma, 0)
}
}
if wrap {
p.print(")")
}
}
func (p *printer) printFn(fn ast.Fn) {
p.printFnArgs(fn.Args, fn.HasRestArg, false)
p.printSpace()
p.printBlock(fn.Body.Stmts)
}
func (p *printer) printClass(class ast.Class) {
if class.Extends != nil {
p.print(" extends")
p.printSpace()
p.printExpr(*class.Extends, ast.LNew-1, 0)
}
p.printSpace()
p.print("{")
p.printNewline()
p.options.Indent++
for _, item := range class.Properties {
p.printSemicolonIfNeeded()
p.printIndent()
p.printProperty(item)
// Need semicolons after class fields
if item.Value == nil {
p.printSemicolonAfterStatement()
} else {
p.printNewline()
}
}
p.needsSemicolon = false
p.options.Indent--
p.printIndent()
p.print("}")
}
func (p *printer) printProperty(item ast.Property) {
if item.Kind == ast.PropertySpread {
p.print("...")
p.printExpr(*item.Value, ast.LComma, 0)
return
}
if item.IsStatic {
p.print("static")
p.printSpace()
}
switch item.Kind {
case ast.PropertyGet:
p.printSpaceBeforeIdentifier()
p.print("get")
p.printSpace()
case ast.PropertySet:
p.printSpaceBeforeIdentifier()
p.print("set")
p.printSpace()
}
if item.Value != nil {
if fn, ok := item.Value.Data.(*ast.EFunction); item.IsMethod && ok {
if fn.Fn.IsAsync {
p.printSpaceBeforeIdentifier()
p.print("async")
p.printSpace()
}
if fn.Fn.IsGenerator {
p.print("*")
}
}
}
if item.IsComputed {
p.print("[")
p.printExpr(item.Key, ast.LComma, 0)
p.print("]")
if item.Value != nil {
if fn, ok := item.Value.Data.(*ast.EFunction); item.IsMethod && ok {
p.printFn(fn.Fn)
return
}
p.print(":")
p.printSpace()
p.printExpr(*item.Value, ast.LComma, 0)