forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_printer.zig
6119 lines (5397 loc) · 232 KB
/
js_printer.zig
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
const std = @import("std");
const logger = bun.logger;
const js_lexer = bun.js_lexer;
const importRecord = @import("import_record.zig");
const js_ast = bun.JSAst;
const options = @import("options.zig");
const rename = @import("renamer.zig");
const runtime = @import("runtime.zig");
const Lock = @import("./lock.zig").Lock;
const Api = @import("./api/schema.zig").Api;
const fs = @import("fs.zig");
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const Ref = @import("ast/base.zig").Ref;
const StoredFileDescriptorType = bun.StoredFileDescriptorType;
const FeatureFlags = bun.FeatureFlags;
const FileDescriptorType = bun.FileDescriptor;
const expect = std.testing.expect;
const ImportKind = importRecord.ImportKind;
const BindingNodeIndex = js_ast.BindingNodeIndex;
const LocRef = js_ast.LocRef;
const S = js_ast.S;
const B = js_ast.B;
const G = js_ast.G;
const T = js_lexer.T;
const E = js_ast.E;
const Stmt = js_ast.Stmt;
const Expr = js_ast.Expr;
const Binding = js_ast.Binding;
const Symbol = js_ast.Symbol;
const Level = js_ast.Op.Level;
const Op = js_ast.Op;
const Scope = js_ast.Scope;
const locModuleScope = logger.Loc.Empty;
const Ast = js_ast.Ast;
const hex_chars = "0123456789ABCDEF";
const first_ascii = 0x20;
const last_ascii = 0x7E;
const first_high_surrogate = 0xD800;
const last_high_surrogate = 0xDBFF;
const first_low_surrogate = 0xDC00;
const last_low_surrogate = 0xDFFF;
const CodepointIterator = @import("./string_immutable.zig").UnsignedCodepointIterator;
const assert = bun.assert;
threadlocal var imported_module_ids_list: std.ArrayList(u32) = undefined;
threadlocal var imported_module_ids_list_unset: bool = true;
const ImportRecord = bun.ImportRecord;
const SourceMap = @import("./sourcemap/sourcemap.zig");
/// For support JavaScriptCore
const ascii_only_always_on_unless_minifying = true;
fn formatUnsignedIntegerBetween(comptime len: u16, buf: *[len]u8, val: u64) void {
comptime var i: u16 = len;
var remainder = val;
// Write out the number from the end to the front
inline while (i > 0) {
comptime i -= 1;
buf[comptime i] = @as(u8, @intCast((remainder % 10))) + '0';
remainder /= 10;
}
}
pub fn writeModuleId(comptime Writer: type, writer: Writer, module_id: u32) void {
bun.assert(module_id != 0); // either module_id is forgotten or it should be disabled
_ = writer.writeAll("$") catch unreachable;
std.fmt.formatInt(module_id, 16, .lower, .{}, writer) catch unreachable;
}
pub fn canPrintWithoutEscape(comptime CodePointType: type, c: CodePointType, comptime ascii_only: bool) bool {
if (c <= last_ascii) {
return c >= first_ascii and c != '\\' and c != '"' and c != '\'' and c != '`' and c != '$';
} else {
return !ascii_only and c != 0xFEFF and c != 0x2028 and c != 0x2029 and (c < first_high_surrogate or c > last_low_surrogate);
}
}
const indentation_space_buf = [_]u8{' '} ** 128;
const indentation_tab_buf = [_]u8{'\t'} ** 128;
pub fn bestQuoteCharForString(comptime Type: type, str: []const Type, allow_backtick: bool) u8 {
var single_cost: usize = 0;
var double_cost: usize = 0;
var backtick_cost: usize = 0;
var i: usize = 0;
while (i < @min(str.len, 1024)) {
switch (str[i]) {
'\'' => {
single_cost += 1;
},
'"' => {
double_cost += 1;
},
'`' => {
backtick_cost += 1;
},
'\n' => {
single_cost += 1;
double_cost += 1;
},
'\\' => {
i += 1;
},
'$' => {
if (i + 1 < str.len and str[i + 1] == '{') {
backtick_cost += 1;
}
},
else => {},
}
i += 1;
}
if (allow_backtick and backtick_cost < @min(single_cost, double_cost)) {
return '`';
}
if (single_cost < double_cost) {
return '\'';
}
return '"';
}
const Whitespacer = struct {
normal: []const u8,
minify: []const u8,
pub fn append(this: Whitespacer, comptime str: []const u8) Whitespacer {
return .{ .normal = this.normal ++ str, .minify = this.minify ++ str };
}
};
fn ws(comptime str: []const u8) Whitespacer {
const Static = struct {
pub const with = str;
pub const without = brk: {
var buf = std.mem.zeroes([str.len]u8);
var buf_i: usize = 0;
for (str) |c| {
if (c != ' ') {
buf[buf_i] = c;
buf_i += 1;
}
}
const final = buf[0..buf_i].*;
break :brk &final;
};
};
return .{ .normal = Static.with, .minify = Static.without };
}
pub fn estimateLengthForUTF8(input: []const u8, comptime ascii_only: bool, comptime quote_char: u8) usize {
var remaining = input;
var len: usize = 2; // for quotes
while (strings.indexOfNeedsEscape(remaining, quote_char)) |i| {
len += i;
remaining = remaining[i..];
const char_len = strings.wtf8ByteSequenceLengthWithInvalid(remaining[0]);
const c = strings.decodeWTF8RuneT(
&switch (char_len) {
// 0 is not returned by `wtf8ByteSequenceLengthWithInvalid`
1 => .{ remaining[0], 0, 0, 0 },
2 => remaining[0..2].* ++ .{ 0, 0 },
3 => remaining[0..3].* ++ .{0},
4 => remaining[0..4].*,
else => unreachable,
},
char_len,
i32,
0,
);
if (canPrintWithoutEscape(i32, c, ascii_only)) {
len += @as(usize, char_len);
} else if (c <= 0xFFFF) {
len += 6;
} else {
len += 12;
}
remaining = remaining[char_len..];
} else {
return remaining.len + 2;
}
return len;
}
pub fn quoteForJSON(text: []const u8, output_: MutableString, comptime ascii_only: bool) !MutableString {
var bytes = output_;
try quoteForJSONBuffer(text, &bytes, ascii_only);
return bytes;
}
pub fn writePreQuotedString(text_in: []const u8, comptime Writer: type, writer: Writer, comptime quote_char: u8, comptime ascii_only: bool, comptime json: bool, comptime encoding: strings.Encoding) !void {
const text = if (comptime encoding == .utf16) @as([]const u16, @alignCast(std.mem.bytesAsSlice(u16, text_in))) else text_in;
var i: usize = 0;
const n: usize = text.len;
while (i < n) {
const width = switch (comptime encoding) {
.latin1, .ascii => 1,
.utf8 => strings.wtf8ByteSequenceLengthWithInvalid(text[i]),
.utf16 => 1,
};
const clamped_width = @min(@as(usize, width), n -| i);
const c = switch (encoding) {
.utf8 => strings.decodeWTF8RuneT(
&switch (clamped_width) {
// 0 is not returned by `wtf8ByteSequenceLengthWithInvalid`
1 => .{ text[i], 0, 0, 0 },
2 => text[i..][0..2].* ++ .{ 0, 0 },
3 => text[i..][0..3].* ++ .{0},
4 => text[i..][0..4].*,
else => unreachable,
},
width,
i32,
0,
),
.ascii => brk: {
std.debug.assert(text[i] <= 0x7F);
break :brk text[i];
},
.latin1 => brk: {
if (text[i] <= 0x7F) break :brk text[i];
break :brk strings.latin1ToCodepointAssumeNotASCII(text[i], i32);
},
.utf16 => brk: {
// TODO: if this is a part of a surrogate pair, we could parse the whole codepoint in order
// to emit it as a single \u{result} rather than two paired \uLOW\uHIGH.
// eg: "\u{10334}" will convert to "\uD800\uDF34" without this.
break :brk @as(i32, text[i]);
},
};
if (canPrintWithoutEscape(i32, c, ascii_only)) {
const remain = text[i + clamped_width ..];
switch (encoding) {
.ascii, .utf8 => {
if (strings.indexOfNeedsEscape(remain, quote_char)) |j| {
const text_chunk = text[i .. i + clamped_width];
try writer.writeAll(text_chunk);
i += clamped_width;
try writer.writeAll(remain[0..j]);
i += j;
} else {
try writer.writeAll(text[i..]);
i = n;
break;
}
},
.latin1, .utf16 => {
var codepoint_bytes: [4]u8 = undefined;
const codepoint_len = strings.encodeWTF8Rune(codepoint_bytes[0..4], c);
try writer.writeAll(codepoint_bytes[0..codepoint_len]);
i += clamped_width;
},
}
continue;
}
switch (c) {
0x07 => {
try writer.writeAll("\\x07");
i += 1;
},
0x08 => {
try writer.writeAll("\\b");
i += 1;
},
0x0C => {
try writer.writeAll("\\f");
i += 1;
},
'\n' => {
if (quote_char == '`') {
try writer.writeAll("\n");
} else {
try writer.writeAll("\\n");
}
i += 1;
},
std.ascii.control_code.cr => {
try writer.writeAll("\\r");
i += 1;
},
// \v
std.ascii.control_code.vt => {
try writer.writeAll("\\v");
i += 1;
},
// "\\"
'\\' => {
try writer.writeAll("\\\\");
i += 1;
},
'"' => {
if (quote_char == '"') {
try writer.writeAll("\\\"");
} else {
try writer.writeAll("\"");
}
i += 1;
},
'\'' => {
if (quote_char == '\'') {
try writer.writeAll("\\'");
} else {
try writer.writeAll("'");
}
i += 1;
},
'`' => {
if (quote_char == '`') {
try writer.writeAll("\\`");
} else {
try writer.writeAll("`");
}
i += 1;
},
'$' => {
if (quote_char == '`') {
const remain = text[i + clamped_width ..];
if (remain.len > 0 and remain[0] == '{') {
try writer.writeAll("\\$");
} else {
try writer.writeAll("$");
}
} else {
try writer.writeAll("$");
}
i += 1;
},
'\t' => {
try writer.writeAll("\\t");
i += 1;
},
else => {
i += @as(usize, width);
if (c <= 0xFF and !json) {
const k = @as(usize, @intCast(c));
try writer.writeAll(&[_]u8{
'\\',
'x',
hex_chars[(k >> 4) & 0xF],
hex_chars[k & 0xF],
});
} else if (c <= 0xFFFF) {
const k = @as(usize, @intCast(c));
try writer.writeAll(&[_]u8{
'\\',
'u',
hex_chars[(k >> 12) & 0xF],
hex_chars[(k >> 8) & 0xF],
hex_chars[(k >> 4) & 0xF],
hex_chars[k & 0xF],
});
} else {
const k = c - 0x10000;
const lo = @as(usize, @intCast(first_high_surrogate + ((k >> 10) & 0x3FF)));
const hi = @as(usize, @intCast(first_low_surrogate + (k & 0x3FF)));
try writer.writeAll(&[_]u8{
'\\',
'u',
hex_chars[lo >> 12],
hex_chars[(lo >> 8) & 15],
hex_chars[(lo >> 4) & 15],
hex_chars[lo & 15],
'\\',
'u',
hex_chars[hi >> 12],
hex_chars[(hi >> 8) & 15],
hex_chars[(hi >> 4) & 15],
hex_chars[hi & 15],
});
}
},
}
}
}
pub fn quoteForJSONBuffer(text: []const u8, bytes: *MutableString, comptime ascii_only: bool) !void {
const writer = bytes.writer();
try bytes.growIfNeeded(estimateLengthForUTF8(text, ascii_only, '"'));
try bytes.appendChar('"');
try writePreQuotedString(text, @TypeOf(writer), writer, '"', ascii_only, true, .utf8);
bytes.appendChar('"') catch unreachable;
}
pub fn writeJSONString(input: []const u8, comptime Writer: type, writer: Writer, comptime encoding: strings.Encoding) !void {
try writer.writeAll("\"");
try writePreQuotedString(input, Writer, writer, '"', false, true, encoding);
try writer.writeAll("\"");
}
pub const SourceMapHandler = struct {
ctx: *anyopaque,
callback: Callback,
const Callback = *const fn (*anyopaque, chunk: SourceMap.Chunk, source: logger.Source) anyerror!void;
pub fn onSourceMapChunk(self: *const @This(), chunk: SourceMap.Chunk, source: logger.Source) anyerror!void {
try self.callback(self.ctx, chunk, source);
}
pub fn For(comptime Type: type, comptime handler: (fn (t: *Type, chunk: SourceMap.Chunk, source: logger.Source) anyerror!void)) type {
return struct {
pub fn onChunk(self: *anyopaque, chunk: SourceMap.Chunk, source: logger.Source) anyerror!void {
try handler(@as(*Type, @ptrCast(@alignCast(self))), chunk, source);
}
pub fn init(self: *Type) SourceMapHandler {
return SourceMapHandler{ .ctx = self, .callback = onChunk };
}
};
}
};
pub const Options = struct {
transform_imports: bool = true,
to_commonjs_ref: Ref = Ref.None,
to_esm_ref: Ref = Ref.None,
require_ref: ?Ref = null,
import_meta_ref: Ref = Ref.None,
indent: Indentation = .{},
runtime_imports: runtime.Runtime.Imports = runtime.Runtime.Imports{},
module_hash: u32 = 0,
source_path: ?fs.Path = null,
allocator: std.mem.Allocator = default_allocator,
source_map_handler: ?SourceMapHandler = null,
source_map_builder: ?*bun.sourcemap.Chunk.Builder = null,
css_import_behavior: Api.CssInJsBehavior = Api.CssInJsBehavior.facade,
target: options.Target = .browser,
runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache = null,
input_files_for_dev_server: ?[]logger.Source = null,
commonjs_named_exports: js_ast.Ast.CommonJSNamedExports = .{},
commonjs_named_exports_deoptimized: bool = false,
commonjs_module_exports_assigned_deoptimized: bool = false,
commonjs_named_exports_ref: Ref = Ref.None,
commonjs_module_ref: Ref = Ref.None,
minify_whitespace: bool = false,
minify_identifiers: bool = false,
minify_syntax: bool = false,
print_dce_annotations: bool = true,
transform_only: bool = false,
inline_require_and_import_errors: bool = true,
has_run_symbol_renamer: bool = false,
require_or_import_meta_for_source_callback: RequireOrImportMeta.Callback = .{},
module_type: options.Format = .esm,
// /// Used for cross-module inlining of import items when bundling
// const_values: Ast.ConstValuesMap = .{},
ts_enums: Ast.TsEnumsMap = .{},
// TODO: remove this
// The reason for this is:
// 1. You're bundling a React component
// 2. jsx auto imports are prepended to the list of parts
// 3. The AST modification for bundling only applies to the final part
// 4. This means that it will try to add a toplevel part which is not wrapped in the arrow function, which is an error
// TypeError: $30851277 is not a function. (In '$30851277()', '$30851277' is undefined)
// at (anonymous) (0/node_modules.server.e1b5ffcd183e9551.jsb:1463:21)
// at #init_react/jsx-dev-runtime.js (0/node_modules.server.e1b5ffcd183e9551.jsb:1309:8)
// at (esm) (0/node_modules.server.e1b5ffcd183e9551.jsb:1480:30)
// The temporary fix here is to tag a stmts ptr as the one we want to prepend to
// Then, when we're JUST about to print it, we print the body of prepend_part_value first
prepend_part_key: ?*anyopaque = null,
prepend_part_value: ?*js_ast.Part = null,
// If we're writing out a source map, this table of line start indices lets
// us do binary search on to figure out what line a given AST node came from
line_offset_tables: ?SourceMap.LineOffsetTable.List = null,
// Default indentation is 2 spaces
pub const Indentation = struct {
scalar: usize = 2,
count: usize = 0,
character: Character = .space,
pub const Character = enum { tab, space };
};
pub fn requireOrImportMetaForSource(
self: *const Options,
id: u32,
was_unwrapped_require: bool,
) RequireOrImportMeta {
if (self.require_or_import_meta_for_source_callback.ctx == null)
return .{};
return self.require_or_import_meta_for_source_callback.call(id, was_unwrapped_require);
}
};
pub const RequireOrImportMeta = struct {
// CommonJS files will return the "require_*" wrapper function and an invalid
// exports object reference. Lazily-initialized ESM files will return the
// "init_*" wrapper function and the exports object for that file.
wrapper_ref: Ref = Ref.None,
exports_ref: Ref = Ref.None,
is_wrapper_async: bool = false,
was_unwrapped_require: bool = false,
pub const Callback = struct {
const Fn = fn (*anyopaque, u32, bool) RequireOrImportMeta;
ctx: ?*anyopaque = null,
callback: *const Fn = undefined,
pub fn call(self: Callback, id: u32, was_unwrapped_require: bool) RequireOrImportMeta {
return self.callback(self.ctx.?, id, was_unwrapped_require);
}
pub fn init(
comptime Type: type,
comptime callback: (fn (t: *Type, id: u32, was_unwrapped_require: bool) RequireOrImportMeta),
ctx: *Type,
) Callback {
return Callback{
.ctx = bun.cast(*anyopaque, ctx),
.callback = @as(*const Fn, @ptrCast(&callback)),
};
}
};
};
pub const PrintResult = union(enum) {
result: struct {
code: []u8,
source_map: ?SourceMap.Chunk = null,
},
err: anyerror,
pub fn clone(
this: PrintResult,
allocator: std.mem.Allocator,
) !PrintResult {
return switch (this) {
.result => PrintResult{
.result = .{
.code = try allocator.dupe(u8, this.result.code),
.source_map = this.result.source_map,
},
},
.err => PrintResult{
.err = this.err,
},
};
}
};
// do not make this a packed struct
// stage1 compiler bug:
// > /optional-chain-with-function.js: Evaluation failed: TypeError: (intermediate value) is not a function
// this test failure was caused by the packed structi mplementation
const ExprFlag = enum {
forbid_call,
forbid_in,
has_non_optional_chain_parent,
expr_result_is_unused,
pub const Set = std.enums.EnumSet(ExprFlag);
pub fn None() ExprFlag.Set {
return Set{};
}
pub fn ForbidCall() ExprFlag.Set {
return Set.init(.{ .forbid_call = true });
}
pub fn ForbidAnd() ExprFlag.Set {
return Set.init(.{ .forbid_and = true });
}
pub fn HasNonOptionalChainParent() ExprFlag.Set {
return Set.init(.{ .has_non_optional_chain_parent = true });
}
pub fn ExprResultIsUnused() ExprFlag.Set {
return Set.init(.{ .expr_result_is_unused = true });
}
};
const ImportVariant = enum {
path_only,
import_star,
import_default,
import_star_and_import_default,
import_items,
import_items_and_default,
import_items_and_star,
import_items_and_default_and_star,
pub inline fn hasItems(import_variant: @This()) @This() {
return switch (import_variant) {
.import_default => .import_items_and_default,
.import_star => .import_items_and_star,
.import_star_and_import_default => .import_items_and_default_and_star,
else => .import_items,
};
}
// We always check star first so don't need to be exhaustive here
pub inline fn hasStar(import_variant: @This()) @This() {
return switch (import_variant) {
.path_only => .import_star,
else => import_variant,
};
}
// We check default after star
pub inline fn hasDefault(import_variant: @This()) @This() {
return switch (import_variant) {
.path_only => .import_default,
.import_star => .import_star_and_import_default,
else => import_variant,
};
}
pub fn determine(record: *const ImportRecord, s_import: *const S.Import) ImportVariant {
var variant = ImportVariant.path_only;
if (record.contains_import_star) {
variant = variant.hasStar();
}
if (!record.was_originally_bare_import) {
if (!record.contains_default_alias) {
if (s_import.default_name) |default_name| {
if (default_name.ref != null) {
variant = variant.hasDefault();
}
}
} else {
variant = variant.hasDefault();
}
}
if (s_import.items.len > 0) {
variant = variant.hasItems();
}
return variant;
}
};
fn NewPrinter(
comptime ascii_only: bool,
comptime Writer: type,
comptime rewrite_esm_to_cjs: bool,
comptime is_bun_platform: bool,
comptime is_json: bool,
comptime generate_source_map: bool,
) type {
return struct {
import_records: []const ImportRecord,
needs_semicolon: bool = false,
stmt_start: i32 = -1,
options: Options,
export_default_start: i32 = -1,
arrow_expr_start: i32 = -1,
for_of_init_start: i32 = -1,
prev_op: Op.Code = Op.Code.bin_add,
prev_op_end: i32 = -1,
prev_num_end: i32 = -1,
prev_reg_exp_end: i32 = -1,
call_target: ?Expr.Data = null,
writer: Writer,
has_printed_bundled_import_statement: bool = false,
imported_module_ids: std.ArrayList(u32),
renamer: rename.Renamer,
prev_stmt_tag: Stmt.Tag = .s_empty,
source_map_builder: SourceMap.Chunk.Builder = undefined,
symbol_counter: u32 = 0,
temporary_bindings: std.ArrayListUnmanaged(B.Property) = .{},
binary_expression_stack: std.ArrayList(BinaryExpressionVisitor) = undefined,
const Printer = @This();
/// When Printer is used as a io.Writer, this represents it's error type, aka nothing.
pub const Error = error{};
/// The handling of binary expressions is convoluted because we're using
/// iteration on the heap instead of recursion on the call stack to avoid
/// stack overflow for deeply-nested ASTs. See the comments for the similar
/// code in the JavaScript parser for details.
pub const BinaryExpressionVisitor = struct {
// Inputs
e: *E.Binary,
level: Level = .lowest,
flags: ExprFlag.Set = ExprFlag.None(),
// Input for visiting the left child
left_level: Level = .lowest,
left_flags: ExprFlag.Set = ExprFlag.None(),
// "Local variables" passed from "checkAndPrepare" to "visitRightAndFinish"
entry: *const Op = undefined,
wrap: bool = false,
right_level: Level = .lowest,
pub fn checkAndPrepare(v: *BinaryExpressionVisitor, p: *Printer) bool {
var e = v.e;
const entry: *const Op = Op.Table.getPtrConst(e.op);
const e_level = entry.level;
v.entry = entry;
v.wrap = v.level.gte(e_level) or (e.op == Op.Code.bin_in and v.flags.contains(.forbid_in));
// Destructuring assignments must be parenthesized
const n = p.writer.written;
if (n == p.stmt_start or n == p.arrow_expr_start) {
switch (e.left.data) {
.e_object => {
v.wrap = true;
},
else => {},
}
}
if (v.wrap) {
p.print("(");
v.flags.insert(.forbid_in);
}
v.left_level = e_level.sub(1);
v.right_level = e_level.sub(1);
const left_level = &v.left_level;
const right_level = &v.right_level;
if (e.op.isRightAssociative()) {
left_level.* = e_level;
}
if (e.op.isLeftAssociative()) {
right_level.* = e_level;
}
switch (e.op) {
// "??" can't directly contain "||" or "&&" without being wrapped in parentheses
.bin_nullish_coalescing => {
switch (e.left.data) {
.e_binary => {
const left = e.left.data.e_binary;
switch (left.op) {
.bin_logical_and, .bin_logical_or => {
left_level.* = .prefix;
},
else => {},
}
},
else => {},
}
switch (e.right.data) {
.e_binary => {
const right = e.right.data.e_binary;
switch (right.op) {
.bin_logical_and, .bin_logical_or => {
right_level.* = .prefix;
},
else => {},
}
},
else => {},
}
},
// "**" can't contain certain unary expressions
.bin_pow => {
switch (e.left.data) {
.e_unary => {
const left = e.left.data.e_unary;
if (left.op.unaryAssignTarget() == .none) {
left_level.* = .call;
}
},
.e_await, .e_undefined, .e_number => {
left_level.* = .call;
},
.e_boolean => {
// When minifying, booleans are printed as "!0 and "!1"
if (p.options.minify_syntax) {
left_level.* = .call;
}
},
else => {},
}
},
else => {},
}
// Special-case "#foo in bar"
if (e.left.data == .e_private_identifier and e.op == .bin_in) {
const private = e.left.data.e_private_identifier;
const name = p.renamer.nameForSymbol(private.ref);
p.addSourceMappingForName(e.left.loc, name, private.ref);
p.printIdentifier(name);
v.visitRightAndFinish(p);
return false;
}
v.left_flags = ExprFlag.Set{};
if (v.flags.contains(.forbid_in)) {
v.left_flags.insert(.forbid_in);
}
if (e.op == .bin_comma)
v.left_flags.insert(.expr_result_is_unused);
return true;
}
pub fn visitRightAndFinish(v: *BinaryExpressionVisitor, p: *Printer) void {
const e = v.e;
const entry = v.entry;
var flags = ExprFlag.Set{};
if (e.op != .bin_comma) {
p.printSpace();
}
if (entry.is_keyword) {
p.printSpaceBeforeIdentifier();
p.print(entry.text);
} else {
p.printSpaceBeforeOperator(e.op);
p.print(entry.text);
p.prev_op = e.op;
p.prev_op_end = p.writer.written;
}
p.printSpace();
// The result of the right operand of the comma operator is unused if the caller doesn't use it
if (e.op == .bin_comma and v.flags.contains(.expr_result_is_unused)) {
flags.insert(.expr_result_is_unused);
}
if (v.flags.contains(.forbid_in)) {
flags.insert(.forbid_in);
}
p.printExpr(e.right, v.right_level, flags);
if (v.wrap) {
p.print(")");
}
}
};
pub fn writeAll(p: *Printer, bytes: anytype) anyerror!void {
p.print(bytes);
}
pub fn writeByteNTimes(self: *Printer, byte: u8, n: usize) !void {
var bytes: [256]u8 = undefined;
@memset(bytes[0..], byte);
var remaining: usize = n;
while (remaining > 0) {
const to_write = @min(remaining, bytes.len);
try self.writeAll(bytes[0..to_write]);
remaining -= to_write;
}
}
pub fn writeBytesNTimes(self: *Printer, bytes: []const u8, n: usize) anyerror!void {
var i: usize = 0;
while (i < n) : (i += 1) {
try self.writeAll(bytes);
}
}
fn fmt(p: *Printer, comptime str: string, args: anytype) !void {
const len = @call(
.always_inline,
std.fmt.count,
.{ str, args },
);
var ptr = try p.writer.reserve(len);
const written = @call(
.always_inline,
std.fmt.bufPrint,
.{ ptr[0..len], str, args },
) catch unreachable;
p.writer.advance(written.len);
}
pub fn printBuffer(p: *Printer, str: []const u8) void {
p.writer.print([]const u8, str);
}
pub fn print(p: *Printer, str: anytype) void {
const StringType = @TypeOf(str);
switch (comptime StringType) {
comptime_int, u16, u8 => {
p.writer.print(StringType, str);
},
[6]u8 => {
const span = str[0..6];
p.writer.print(@TypeOf(span), span);
},
else => {
p.writer.print(StringType, str);
},
}
}
pub inline fn unindent(p: *Printer) void {
p.options.indent.count -|= 1;
}
pub inline fn indent(p: *Printer) void {
p.options.indent.count += 1;
}
pub fn printIndent(p: *Printer) void {
if (p.options.indent.count == 0 or p.options.minify_whitespace) {
return;
}
const indentation_buf = switch (p.options.indent.character) {
.space => indentation_space_buf,
.tab => indentation_tab_buf,
};
var i: usize = p.options.indent.count * p.options.indent.scalar;
while (i > 0) {
const amt = @min(i, indentation_buf.len);
p.print(indentation_buf[0..amt]);
i -= amt;
}
}
pub inline fn printSpace(p: *Printer) void {
if (!p.options.minify_whitespace)
p.print(" ");
}
pub inline fn printNewline(p: *Printer) void {
if (!p.options.minify_whitespace)
p.print("\n");
}
pub inline fn printSemicolonAfterStatement(p: *Printer) void {
if (!p.options.minify_whitespace) {
p.print(";\n");
} else {
p.needs_semicolon = true;
}
}
pub fn printSemicolonIfNeeded(p: *Printer) void {
if (p.needs_semicolon) {
p.print(";");
p.needs_semicolon = false;
}
}
fn @"print = "(p: *Printer) void {
if (p.options.minify_whitespace) {
p.print("=");
} else {
p.print(" = ");
}
}
fn printBunJestImportStatement(p: *Printer, import: S.Import) void {
comptime bun.assert(is_bun_platform);