forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
js_ast.zig
7801 lines (6867 loc) · 278 KB
/
js_ast.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 JSXRuntime = @import("options.zig").JSX.Runtime;
const Runtime = @import("runtime.zig").Runtime;
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 Index = @import("ast/base.zig").Index;
const RefHashCtx = @import("ast/base.zig").RefHashCtx;
const ObjectPool = @import("./pool.zig").ObjectPool;
const ImportRecord = @import("import_record.zig").ImportRecord;
const allocators = @import("allocators.zig");
const JSC = bun.JSC;
const RefCtx = @import("./ast/base.zig").RefCtx;
const JSONParser = bun.JSON;
const is_bindgen = std.meta.globalOption("bindgen", bool) orelse false;
const ComptimeStringMap = bun.ComptimeStringMap;
const JSPrinter = @import("./js_printer.zig");
const js_lexer = @import("./js_lexer.zig");
const TypeScript = @import("./js_parser.zig").TypeScript;
const ThreadlocalArena = @import("./mimalloc_arena.zig").Arena;
const MimeType = bun.http.MimeType;
/// This is the index to the automatically-generated part containing code that
/// calls "__export(exports, { ... getters ... })". This is used to generate
/// getters on an exports object for ES6 export statements, and is both for
/// ES6 star imports and CommonJS-style modules. All files have one of these,
/// although it may contain no statements if there is nothing to export.
pub const namespace_export_part_index = 0;
pub fn NewBaseStore(comptime Union: anytype, comptime count: usize) type {
var max_size = 0;
var max_align = 1;
for (Union) |kind| {
max_size = @max(@sizeOf(kind), max_size);
max_align = if (@sizeOf(kind) == 0) max_align else @max(@alignOf(kind), max_align);
}
const UnionValueType = [max_size]u8;
const SizeType = std.math.IntFittingRange(0, (count + 1));
const MaxAlign = max_align;
return struct {
const Allocator = std.mem.Allocator;
const Self = @This();
pub const WithBase = struct {
head: Block = Block{},
store: Self,
};
pub const Block = struct {
used: SizeType = 0,
items: [count]UnionValueType align(MaxAlign) = undefined,
pub inline fn isFull(block: *const Block) bool {
return block.used >= @as(SizeType, count);
}
pub fn append(block: *Block, comptime ValueType: type, value: ValueType) *UnionValueType {
if (comptime Environment.allow_assert) bun.assert(block.used < count);
const index = block.used;
block.items[index][0..value.len].* = value.*;
block.used +|= 1;
return &block.items[index];
}
};
const Overflow = struct {
const max = 4096 * 3;
const UsedSize = std.math.IntFittingRange(0, max + 1);
used: UsedSize = 0,
allocated: UsedSize = 0,
allocator: Allocator = default_allocator,
ptrs: [max]*Block = undefined,
pub fn tail(this: *Overflow) *Block {
if (this.ptrs[this.used].isFull()) {
this.used +%= 1;
if (this.allocated > this.used) {
this.ptrs[this.used].used = 0;
}
}
if (this.allocated <= this.used) {
var new_ptrs = this.allocator.alloc(Block, 2) catch unreachable;
new_ptrs[0] = Block{};
new_ptrs[1] = Block{};
this.ptrs[this.allocated] = &new_ptrs[0];
this.ptrs[this.allocated + 1] = &new_ptrs[1];
this.allocated +%= 2;
}
return this.ptrs[this.used];
}
pub inline fn slice(this: *Overflow) []*Block {
return this.ptrs[0..this.used];
}
};
overflow: Overflow = Overflow{},
pub threadlocal var _self: ?*Self = null;
pub fn reclaim() []*Block {
var overflow = &_self.?.overflow;
if (overflow.used == 0) {
if (overflow.allocated == 0 or overflow.ptrs[0].used == 0) {
return &.{};
}
}
var to_move = overflow.ptrs[0..overflow.allocated][overflow.used..];
// This returns the list of maxed out blocks
var used_list = overflow.slice();
// The last block may be partially used.
if (overflow.allocated > overflow.used and to_move.len > 0 and to_move.ptr[0].used > 0) {
to_move = to_move[1..];
used_list.len += 1;
}
const used = overflow.allocator.dupe(*Block, used_list) catch unreachable;
for (to_move, overflow.ptrs[0..to_move.len]) |b, *out| {
b.* = Block{
.items = undefined,
.used = 0,
};
out.* = b;
}
overflow.allocated = @as(Overflow.UsedSize, @truncate(to_move.len));
overflow.used = 0;
return used;
}
/// Reset all AST nodes, allowing the memory to be reused for the next parse.
/// Only call this when we're done with ALL AST nodes, or you risk
/// undefined memory bugs.
///
/// Nested parsing should either use the same store, or call
/// Store.reclaim.
pub fn reset() void {
const blocks = _self.?.overflow.slice();
for (blocks) |b| {
if (comptime Environment.isDebug) {
// ensure we crash if we use a freed value
const bytes = std.mem.asBytes(&b.items);
@memset(bytes, undefined);
}
b.used = 0;
}
_self.?.overflow.used = 0;
}
pub fn init(allocator: std.mem.Allocator) *Self {
var base = allocator.create(WithBase) catch unreachable;
base.* = WithBase{ .store = .{ .overflow = Overflow{ .allocator = allocator } } };
var instance = &base.store;
instance.overflow.ptrs[0] = &base.head;
instance.overflow.allocated = 1;
_self = instance;
return _self.?;
}
pub fn onThreadExit(_: *anyopaque) callconv(.C) void {
deinit();
}
fn deinit() void {
if (_self) |this| {
_self = null;
const sliced = this.overflow.slice();
var allocator = this.overflow.allocator;
if (sliced.len > 1) {
var i: usize = 1;
const end = sliced.len;
while (i < end) {
const ptrs = @as(*[2]Block, @ptrCast(sliced[i]));
allocator.free(ptrs);
i += 2;
}
this.overflow.allocated = 1;
}
var base_store = @fieldParentPtr(WithBase, "store", this);
if (this.overflow.ptrs[0] == &base_store.head) {
allocator.destroy(base_store);
}
}
}
pub fn append(comptime Disabler: type, comptime ValueType: type, value: ValueType) *ValueType {
Disabler.assert();
return _self.?._append(ValueType, value);
}
inline fn _append(self: *Self, comptime ValueType: type, value: ValueType) *ValueType {
const bytes = std.mem.asBytes(&value);
const BytesAsSlice = @TypeOf(bytes);
var block = self.overflow.tail();
return @as(
*ValueType,
@ptrCast(@alignCast(block.append(BytesAsSlice, bytes))),
);
}
};
}
// There are three types.
// 1. Expr (expression)
// 2. Stmt (statement)
// 3. Binding
// Q: "What's the difference between an expression and a statement?"
// A: > Expression: Something which evaluates to a value. Example: 1+2/x
// > Statement: A line of code which does something. Example: GOTO 100
// > https://stackoverflow.com/questions/19132/expression-versus-statement/19224#19224
// Expr, Binding, and Stmt each wrap a Data:
// Data is where the actual data where the node lives.
// There are four possible versions of this structure:
// [ ] 1. *Expr, *Stmt, *Binding
// [ ] 1a. *Expr, *Stmt, *Binding something something dynamic dispatch
// [ ] 2. *Data
// [x] 3. Data.(*) (The union value in Data is a pointer)
// I chose #3 mostly for code simplification -- sometimes, the data is modified in-place.
// But also it uses the least memory.
// Since Data is a union, the size in bytes of Data is the max of all types
// So with #1 or #2, if S.Function consumes 768 bits, that means Data must be >= 768 bits
// Which means "true" in code now takes up over 768 bits, probably more than what v8 spends
// Instead, this approach means Data is the size of a pointer.
// It's not really clear which approach is best without benchmarking it.
// The downside with this approach is potentially worse memory locality, since the data for the node is somewhere else.
// But it could also be better memory locality due to smaller in-memory size (more likely to hit the cache)
// only benchmarks will provide an answer!
// But we must have pointers somewhere in here because can't have types that contain themselves
pub const BindingNodeIndex = Binding;
pub const StmtNodeIndex = Stmt;
pub const ExprNodeIndex = Expr;
pub const BabyList = bun.BabyList;
/// Slice that stores capacity and length in the same space as a regular slice.
pub const ExprNodeList = BabyList(Expr);
pub const StmtNodeList = []Stmt;
pub const BindingNodeList = []Binding;
pub const ImportItemStatus = enum(u2) {
none,
// The linker doesn't report import/export mismatch errors
generated,
// The printer will replace this import with "undefined"
missing,
pub fn jsonStringify(self: @This(), writer: anytype) !void {
return try writer.write(@tagName(self));
}
};
pub const AssignTarget = enum(u2) {
none = 0,
replace = 1, // "a = b"
update = 2, // "a += b"
pub fn jsonStringify(self: *const @This(), writer: anytype) !void {
return try writer.write(@tagName(self));
}
};
pub const LocRef = struct {
loc: logger.Loc = logger.Loc.Empty,
// TODO: remove this optional and make Ref a function getter
// That will make this struct 128 bits instead of 192 bits and we can remove some heap allocations
ref: ?Ref = null,
};
pub const Flags = struct {
pub const JSXElement = enum {
is_key_after_spread,
has_any_dynamic,
can_be_inlined,
can_be_hoisted,
pub const Bitset = std.enums.EnumSet(JSXElement);
};
pub const Property = enum {
is_computed,
is_method,
is_static,
was_shorthand,
is_spread,
pub inline fn init(fields: Fields) Set {
return Set.init(fields);
}
pub const None = Set{};
pub const Fields = std.enums.EnumFieldStruct(Flags.Property, bool, false);
pub const Set = std.enums.EnumSet(Flags.Property);
};
pub const Function = enum {
is_async,
is_generator,
has_rest_arg,
has_if_scope,
is_forward_declaration,
/// This is true if the function is a method
is_unique_formal_parameters,
/// Only applicable to function statements.
is_export,
/// Used for Hot Module Reloading's wrapper function
/// "iife" stands for "immediately invoked function expression"
print_as_iife,
pub inline fn init(fields: Fields) Set {
return Set.init(fields);
}
pub const None = Set{};
pub const Fields = std.enums.EnumFieldStruct(Function, bool, false);
pub const Set = std.enums.EnumSet(Function);
};
};
pub const Binding = struct {
loc: logger.Loc,
data: B,
const Serializable = struct {
type: Tag,
object: string,
value: B,
loc: logger.Loc,
};
pub fn jsonStringify(self: *const @This(), writer: anytype) !void {
return try writer.write(Serializable{ .type = std.meta.activeTag(self.data), .object = "binding", .value = self.data, .loc = self.loc });
}
pub fn ToExpr(comptime expr_type: type, comptime func_type: anytype) type {
const ExprType = expr_type;
return struct {
context: *ExprType,
allocator: std.mem.Allocator,
pub const Context = @This();
pub fn wrapIdentifier(ctx: *const Context, loc: logger.Loc, ref: Ref) Expr {
return func_type(ctx.context, loc, ref);
}
pub fn init(context: *ExprType) Context {
return Context{ .context = context, .allocator = context.allocator };
}
};
}
pub fn toExpr(binding: *const Binding, wrapper: anytype) Expr {
const loc = binding.loc;
switch (binding.data) {
.b_missing => {
return Expr{ .data = .{ .e_missing = E.Missing{} }, .loc = loc };
},
.b_identifier => |b| {
return wrapper.wrapIdentifier(loc, b.ref);
},
.b_array => |b| {
var exprs = wrapper.allocator.alloc(Expr, b.items.len) catch unreachable;
var i: usize = 0;
while (i < exprs.len) : (i += 1) {
const item = b.items[i];
exprs[i] = convert: {
const expr = toExpr(&item.binding, wrapper);
if (b.has_spread and i == exprs.len - 1) {
break :convert Expr.init(E.Spread, E.Spread{ .value = expr }, expr.loc);
} else if (item.default_value) |default| {
break :convert Expr.assign(expr, default);
} else {
break :convert expr;
}
};
}
return Expr.init(E.Array, E.Array{ .items = ExprNodeList.init(exprs), .is_single_line = b.is_single_line }, loc);
},
.b_object => |b| {
const properties = wrapper
.allocator
.alloc(G.Property, b.properties.len) catch unreachable;
for (properties, b.properties) |*property, item| {
property.* = .{
.flags = item.flags,
.key = item.key,
.kind = if (item.flags.contains(.is_spread))
.spread
else
.normal,
.value = toExpr(&item.value, wrapper),
.initializer = item.default_value,
};
}
return Expr.init(
E.Object,
E.Object{
.properties = G.Property.List.init(properties),
.is_single_line = b.is_single_line,
},
loc,
);
},
else => {
Global.panic("Internal error", .{});
},
}
}
pub const Tag = enum(u5) {
b_identifier,
b_array,
b_property,
b_object,
b_missing,
pub fn jsonStringify(self: @This(), writer: anytype) !void {
return try writer.write(@tagName(self));
}
};
pub var icount: usize = 0;
pub fn init(t: anytype, loc: logger.Loc) Binding {
icount += 1;
switch (@TypeOf(t)) {
*B.Identifier => {
return Binding{ .loc = loc, .data = B{ .b_identifier = t } };
},
*B.Array => {
return Binding{ .loc = loc, .data = B{ .b_array = t } };
},
*B.Property => {
return Binding{ .loc = loc, .data = B{ .b_property = t } };
},
*B.Object => {
return Binding{ .loc = loc, .data = B{ .b_object = t } };
},
B.Missing => {
return Binding{ .loc = loc, .data = B{ .b_missing = t } };
},
else => {
@compileError("Invalid type passed to Binding.init");
},
}
}
pub fn alloc(allocator: std.mem.Allocator, t: anytype, loc: logger.Loc) Binding {
icount += 1;
switch (@TypeOf(t)) {
B.Identifier => {
const data = allocator.create(B.Identifier) catch unreachable;
data.* = t;
return Binding{ .loc = loc, .data = B{ .b_identifier = data } };
},
B.Array => {
const data = allocator.create(B.Array) catch unreachable;
data.* = t;
return Binding{ .loc = loc, .data = B{ .b_array = data } };
},
B.Property => {
const data = allocator.create(B.Property) catch unreachable;
data.* = t;
return Binding{ .loc = loc, .data = B{ .b_property = data } };
},
B.Object => {
const data = allocator.create(B.Object) catch unreachable;
data.* = t;
return Binding{ .loc = loc, .data = B{ .b_object = data } };
},
B.Missing => {
return Binding{ .loc = loc, .data = B{ .b_missing = .{} } };
},
else => {
@compileError("Invalid type passed to Binding.alloc");
},
}
}
};
/// B is for Binding!
/// These are the types of bindings that can be used in the AST.
pub const B = union(Binding.Tag) {
b_identifier: *B.Identifier,
b_array: *B.Array,
b_property: *B.Property,
b_object: *B.Object,
b_missing: B.Missing,
pub const Identifier = struct {
ref: Ref,
};
pub const Property = struct {
flags: Flags.Property.Set = Flags.Property.None,
key: ExprNodeIndex,
value: BindingNodeIndex,
default_value: ?ExprNodeIndex = null,
};
pub const Object = struct { properties: []Property, is_single_line: bool = false };
pub const Array = struct {
items: []ArrayBinding,
has_spread: bool = false,
is_single_line: bool = false,
};
pub const Missing = struct {};
};
pub const ClauseItem = struct {
alias: string = "",
alias_loc: logger.Loc = logger.Loc.Empty,
name: LocRef,
/// This is the original name of the symbol stored in "Name". It's needed for
/// "SExportClause" statements such as this:
///
/// export {foo as bar} from 'path'
///
/// In this case both "foo" and "bar" are aliases because it's a re-export.
/// We need to preserve both aliases in case the symbol is renamed. In this
/// example, "foo" is "OriginalName" and "bar" is "Alias".
original_name: string = "",
pub const default_alias: string = "default";
};
pub const SlotCounts = struct {
slots: Symbol.SlotNamespace.CountsArray = Symbol.SlotNamespace.CountsArray.initFill(0),
pub fn unionMax(this: *SlotCounts, other: SlotCounts) void {
for (&this.slots.values, other.slots.values) |*a, b| {
if (a.* < b) a.* = b;
}
}
};
const char_freq_count = 64;
pub const CharAndCount = struct {
char: u8 = 0,
count: i32 = 0,
index: usize = 0,
pub const Array = [char_freq_count]CharAndCount;
pub fn lessThan(_: void, a: CharAndCount, b: CharAndCount) bool {
if (a.count != b.count) {
return a.count > b.count;
}
if (a.index != b.index) {
return a.index < b.index;
}
return a.char < b.char;
}
};
pub const CharFreq = struct {
const Vector = @Vector(char_freq_count, i32);
const Buffer = [char_freq_count]i32;
freqs: Buffer align(1) = undefined,
const scan_big_chunk_size = 32;
pub fn scan(this: *CharFreq, text: string, delta: i32) void {
if (delta == 0)
return;
if (text.len < scan_big_chunk_size) {
scanSmall(&this.freqs, text, delta);
} else {
scanBig(&this.freqs, text, delta);
}
}
fn scanBig(out: *align(1) Buffer, text: string, delta: i32) void {
// https://zig.godbolt.org/z/P5dPojWGK
var freqs = out.*;
defer out.* = freqs;
var deltas: [256]i32 = [_]i32{0} ** 256;
var remain = text;
bun.assert(remain.len >= scan_big_chunk_size);
const unrolled = remain.len - (remain.len % scan_big_chunk_size);
const remain_end = remain.ptr + unrolled;
var unrolled_ptr = remain.ptr;
remain = remain[unrolled..];
while (unrolled_ptr != remain_end) : (unrolled_ptr += scan_big_chunk_size) {
const chunk = unrolled_ptr[0..scan_big_chunk_size].*;
inline for (0..scan_big_chunk_size) |i| {
deltas[@as(usize, chunk[i])] += delta;
}
}
for (remain) |c| {
deltas[@as(usize, c)] += delta;
}
freqs[0..26].* = deltas['a' .. 'a' + 26].*;
freqs[26 .. 26 * 2].* = deltas['A' .. 'A' + 26].*;
freqs[26 * 2 .. 62].* = deltas['0' .. '0' + 10].*;
freqs[62] = deltas['_'];
freqs[63] = deltas['$'];
}
fn scanSmall(out: *align(1) Buffer, text: string, delta: i32) void {
var freqs: [char_freq_count]i32 = out.*;
defer out.* = freqs;
for (text) |c| {
const i: usize = switch (c) {
'a'...'z' => @as(usize, @intCast(c)) - 'a',
'A'...'Z' => @as(usize, @intCast(c)) - ('A' - 26),
'0'...'9' => @as(usize, @intCast(c)) + (53 - '0'),
'_' => 62,
'$' => 63,
else => continue,
};
freqs[i] += delta;
}
}
pub fn include(this: *CharFreq, other: CharFreq) void {
// https://zig.godbolt.org/z/Mq8eK6K9s
const left: @Vector(char_freq_count, i32) = this.freqs;
const right: @Vector(char_freq_count, i32) = other.freqs;
this.freqs = left + right;
}
pub fn compile(this: *const CharFreq, allocator: std.mem.Allocator) NameMinifier {
const array: CharAndCount.Array = brk: {
var _array: CharAndCount.Array = undefined;
for (&_array, NameMinifier.default_tail, this.freqs, 0..) |*dest, char, freq, i| {
dest.* = CharAndCount{
.char = char,
.index = i,
.count = freq,
};
}
std.sort.pdq(CharAndCount, &_array, {}, CharAndCount.lessThan);
break :brk _array;
};
var minifier = NameMinifier.init(allocator);
minifier.head.ensureTotalCapacityPrecise(NameMinifier.default_head.len) catch unreachable;
minifier.tail.ensureTotalCapacityPrecise(NameMinifier.default_tail.len) catch unreachable;
// TODO: investigate counting number of < 0 and > 0 and pre-allocating
for (array) |item| {
if (item.char < '0' or item.char > '9') {
minifier.head.append(item.char) catch unreachable;
}
minifier.tail.append(item.char) catch unreachable;
}
return minifier;
}
};
pub const NameMinifier = struct {
head: std.ArrayList(u8),
tail: std.ArrayList(u8),
pub const default_head = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
pub const default_tail = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$";
pub fn init(allocator: std.mem.Allocator) NameMinifier {
return .{
.head = std.ArrayList(u8).init(allocator),
.tail = std.ArrayList(u8).init(allocator),
};
}
pub fn numberToMinifiedName(this: *NameMinifier, name: *std.ArrayList(u8), _i: isize) !void {
name.clearRetainingCapacity();
var i = _i;
var j = @as(usize, @intCast(@mod(i, 54)));
try name.appendSlice(this.head.items[j .. j + 1]);
i = @divFloor(i, 54);
while (i > 0) {
i -= 1;
j = @as(usize, @intCast(@mod(i, char_freq_count)));
try name.appendSlice(this.tail.items[j .. j + 1]);
i = @divFloor(i, char_freq_count);
}
}
pub fn defaultNumberToMinifiedName(allocator: std.mem.Allocator, _i: isize) !string {
var i = _i;
var j = @as(usize, @intCast(@mod(i, 54)));
var name = std.ArrayList(u8).init(allocator);
try name.appendSlice(default_head[j .. j + 1]);
i = @divFloor(i, 54);
while (i > 0) {
i -= 1;
j = @as(usize, @intCast(@mod(i, char_freq_count)));
try name.appendSlice(default_tail[j .. j + 1]);
i = @divFloor(i, char_freq_count);
}
return name.items;
}
};
pub const G = struct {
pub const Decl = struct {
binding: BindingNodeIndex,
value: ?ExprNodeIndex = null,
pub const List = BabyList(Decl);
};
pub const NamespaceAlias = struct {
namespace_ref: Ref,
alias: string,
was_originally_property_access: bool = false,
import_record_index: u32 = std.math.maxInt(u32),
};
pub const ExportStarAlias = struct {
loc: logger.Loc,
// Although this alias name starts off as being the same as the statement's
// namespace symbol, it may diverge if the namespace symbol name is minified.
// The original alias name is preserved here to avoid this scenario.
original_name: string,
};
pub const Class = struct {
class_keyword: logger.Range = logger.Range.None,
ts_decorators: ExprNodeList = ExprNodeList{},
class_name: ?LocRef = null,
extends: ?ExprNodeIndex = null,
body_loc: logger.Loc = logger.Loc.Empty,
close_brace_loc: logger.Loc = logger.Loc.Empty,
properties: []Property = &([_]Property{}),
has_decorators: bool = false,
pub fn canBeMoved(this: *const Class) bool {
if (this.extends != null)
return false;
if (this.has_decorators) {
return false;
}
for (this.properties) |property| {
if (property.kind == .class_static_block)
return false;
const flags = property.flags;
if (flags.contains(.is_computed) or flags.contains(.is_spread)) {
return false;
}
if (property.kind == .normal) {
if (flags.contains(.is_static)) {
for ([2]?Expr{ property.value, property.initializer }) |val_| {
if (val_) |val| {
switch (val.data) {
.e_arrow, .e_function => {},
else => {
if (!val.canBeConstValue()) {
return false;
}
},
}
}
}
}
}
}
return true;
}
};
// invalid shadowing if left as Comment
pub const Comment = struct { loc: logger.Loc, text: string };
pub const ClassStaticBlock = struct {
stmts: BabyList(Stmt) = .{},
loc: logger.Loc,
};
pub const Property = struct {
// This is used when parsing a pattern that uses default values:
//
// [a = 1] = [];
// ({a = 1} = {});
//
// It's also used for class fields:
//
// class Foo { a = 1 }
//
initializer: ?ExprNodeIndex = null,
kind: Kind = Kind.normal,
flags: Flags.Property.Set = Flags.Property.None,
class_static_block: ?*ClassStaticBlock = null,
ts_decorators: ExprNodeList = ExprNodeList{},
// Key is optional for spread
key: ?ExprNodeIndex = null,
// This is omitted for class fields
value: ?ExprNodeIndex = null,
ts_metadata: TypeScript.Metadata = .m_none,
pub const List = BabyList(Property);
pub const Kind = enum(u3) {
normal,
get,
set,
spread,
declare,
class_static_block,
pub fn jsonStringify(self: @This(), writer: anytype) !void {
return try writer.write(@tagName(self));
}
};
};
pub const FnBody = struct {
loc: logger.Loc,
stmts: StmtNodeList,
};
pub const Fn = struct {
name: ?LocRef = null,
open_parens_loc: logger.Loc = logger.Loc.Empty,
args: []Arg = &([_]Arg{}),
// This was originally nullable, but doing so I believe caused a miscompilation
// Specifically, the body was always null.
body: FnBody = FnBody{ .loc = logger.Loc.Empty, .stmts = &([_]StmtNodeIndex{}) },
arguments_ref: ?Ref = null,
flags: Flags.Function.Set = Flags.Function.None,
return_ts_metadata: TypeScript.Metadata = .m_none,
};
pub const Arg = struct {
ts_decorators: ExprNodeList = ExprNodeList{},
binding: BindingNodeIndex,
default: ?ExprNodeIndex = null,
// "constructor(public x: boolean) {}"
is_typescript_ctor_field: bool = false,
ts_metadata: TypeScript.Metadata = .m_none,
};
};
pub const Symbol = struct {
/// This is the name that came from the parser. Printed names may be renamed
/// during minification or to avoid name collisions. Do not use the original
/// name during printing.
original_name: string,
/// This is used for symbols that represent items in the import clause of an
/// ES6 import statement. These should always be referenced by EImportIdentifier
/// instead of an EIdentifier. When this is present, the expression should
/// be printed as a property access off the namespace instead of as a bare
/// identifier.
///
/// For correctness, this must be stored on the symbol instead of indirectly
/// associated with the Ref for the symbol somehow. In ES6 "flat bundling"
/// mode, re-exported symbols are collapsed using MergeSymbols() and renamed
/// symbols from other files that end up at this symbol must be able to tell
/// if it has a namespace alias.
namespace_alias: ?G.NamespaceAlias = null,
/// Used by the parser for single pass parsing.
link: Ref = Ref.None,
/// An estimate of the number of uses of this symbol. This is used to detect
/// whether a symbol is used or not. For example, TypeScript imports that are
/// unused must be removed because they are probably type-only imports. This
/// is an estimate and may not be completely accurate due to oversights in the
/// code. But it should always be non-zero when the symbol is used.
use_count_estimate: u32 = 0,
/// This is for generating cross-chunk imports and exports for code splitting.
///
/// Do not use this directly. Use `chunkIndex()` instead.
chunk_index: u32 = invalid_chunk_index,
/// This is used for minification. Symbols that are declared in sibling scopes
/// can share a name. A good heuristic (from Google Closure Compiler) is to
/// assign names to symbols from sibling scopes in declaration order. That way
/// local variable names are reused in each global function like this, which
/// improves gzip compression:
///
/// function x(a, b) { ... }
/// function y(a, b, c) { ... }
///
/// The parser fills this in for symbols inside nested scopes. There are three
/// slot namespaces: regular symbols, label symbols, and private symbols.
///
/// Do not use this directly. Use `nestedScopeSlot()` instead.
nested_scope_slot: u32 = invalid_nested_scope_slot,
did_keep_name: bool = true,
must_start_with_capital_letter_for_jsx: bool = false,
/// The kind of symbol. This is used to determine how to print the symbol
/// and how to deal with conflicts, renaming, etc.
kind: Kind = Kind.other,
/// Certain symbols must not be renamed or minified. For example, the
/// "arguments" variable is declared by the runtime for every function.
/// Renaming can also break any identifier used inside a "with" statement.
must_not_be_renamed: bool = false,
/// We automatically generate import items for property accesses off of
/// namespace imports. This lets us remove the expensive namespace imports
/// while bundling in many cases, replacing them with a cheap import item
/// instead:
///
/// import * as ns from 'path'
/// ns.foo()
///
/// That can often be replaced by this, which avoids needing the namespace:
///
/// import {foo} from 'path'
/// foo()
///
/// However, if the import is actually missing then we don't want to report a
/// compile-time error like we do for real import items. This status lets us
/// avoid this. We also need to be able to replace such import items with
/// undefined, which this status is also used for.
import_item_status: ImportItemStatus = ImportItemStatus.none,
/// --- Not actually used yet -----------------------------------------------
/// Sometimes we lower private symbols even if they are supported. For example,
/// consider the following TypeScript code:
///
/// class Foo {
/// #foo = 123
/// bar = this.#foo
/// }
///
/// If "useDefineForClassFields: false" is set in "tsconfig.json", then "bar"
/// must use assignment semantics instead of define semantics. We can compile
/// that to this code:
///
/// class Foo {
/// constructor() {
/// this.#foo = 123;
/// this.bar = this.#foo;
/// }
/// #foo;
/// }
///