forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_ast.zig
8283 lines (7374 loc) · 328 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 = @import("logger.zig");
const JSXRuntime = @import("options.zig").JSX.Runtime;
const Runtime = @import("runtime.zig").Runtime;
const bun = @import("global.zig");
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 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 = @import("javascript_core");
const HTTP = @import("http");
const RefCtx = @import("./ast/base.zig").RefCtx;
const _hash_map = @import("hash_map.zig");
const JSONParser = @import("./json_parser.zig");
const StringHashMap = _hash_map.StringHashMap;
const AutoHashMap = _hash_map.AutoHashMap;
const StringHashMapUnmanaged = _hash_map.StringHashMapUnmanaged;
const is_bindgen = std.meta.globalOption("bindgen", bool) orelse false;
const ComptimeStringMap = bun.ComptimeStringMap;
const JSPrinter = @import("./js_printer.zig");
pub fn NewBaseStore(comptime Union: anytype, comptime count: usize) type {
var max_size = 0;
var max_align = 1;
for (Union) |kind| {
max_size = std.math.max(@sizeOf(kind), max_size);
max_align = if (@sizeOf(kind) == 0) max_align else std.math.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,
};
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) std.debug.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,
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 = undefined;
pub fn reclaim() []*Block {
if (_self.overflow.used == 0) return &[_]*Block{};
var used = _self.overflow.allocator.dupe(*Block, _self.overflow.slice()) catch unreachable;
var new_head = _self.overflow.allocator.create(Block) catch unreachable;
new_head.* = Block{};
var to_move = _self.overflow.ptrs[0.._self.overflow.allocated][_self.overflow.used..];
if (to_move.len > 0) {
to_move = to_move[1..];
}
std.mem.copyBackwards(*Block, _self.overflow.ptrs[1..], to_move);
_self.overflow.ptrs[0] = new_head;
_self.overflow.allocated = 1 + @truncate(Overflow.UsedSize, to_move.len);
reset();
return used;
}
pub fn reset() void {
for (_self.overflow.slice()) |b| {
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;
}
fn deinit() void {
var sliced = _self.overflow.slice();
if (sliced.len > 1) {
var i: usize = 1;
const end = sliced.len;
while (i < end) {
var ptrs = @ptrCast(*[2]Block, sliced[i]);
default_allocator.free(ptrs);
i += 2;
}
_self.overflow.allocated = 1;
}
var base_store = @fieldParentPtr(WithBase, "store", _self);
if (_self.overflow.ptrs[0] == &base_store.head) {
default_allocator.destroy(base_store);
}
_self = undefined;
}
pub fn append(comptime ValueType: type, value: ValueType) *ValueType {
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 @ptrCast(
*ValueType,
@alignCast(
@alignOf(ValueType),
@alignCast(@alignOf(ValueType), 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 = @import("./baby_list.zig").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(), opts: anytype, o: anytype) !void {
return try std.json.stringify(@tagName(self), opts, o);
}
};
pub const AssignTarget = enum(u2) {
none = 0,
replace = 1, // "a = b"
update = 2, // "a += b"
pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void {
return try std.json.stringify(@tagName(self), opts, o);
}
};
pub const LocRef = struct { loc: logger.Loc, ref: ?Ref = null };
pub const Flags = struct {
pub const JSXElement = enum {
is_key_before_rest,
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(), options: anytype, writer: anytype) !void {
return try std.json.stringify(Serializable{ .@"type" = std.meta.activeTag(self.data), .object = "binding", .value = self.data, .loc = self.loc }, options, writer);
}
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 {
var 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, wrapper.allocator);
} 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| {
var properties = wrapper
.allocator
.alloc(G.Property, b.properties.len) catch unreachable;
var i: usize = 0;
while (i < properties.len) : (i += 1) {
const item = b.properties[i];
properties[i] = G.Property{
.flags = item.flags,
.key = item.key,
.kind = if (item.flags.contains(.is_spread))
G.Property.Kind.spread
else
G.Property.Kind.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("Interanl error", .{});
},
}
}
pub const Tag = enum(u5) {
b_identifier,
b_array,
b_property,
b_object,
b_missing,
pub fn jsonStringify(self: @This(), opts: anytype, o: anytype) !void {
return try std.json.stringify(@tagName(self), opts, o);
}
};
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 => {
var data = allocator.create(B.Identifier) catch unreachable;
data.* = t;
return Binding{ .loc = loc, .data = B{ .b_identifier = data } };
},
B.Array => {
var data = allocator.create(B.Array) catch unreachable;
data.* = t;
return Binding{ .loc = loc, .data = B{ .b_array = data } };
},
B.Property => {
var data = allocator.create(B.Property) catch unreachable;
data.* = t;
return Binding{ .loc = loc, .data = B{ .b_property = data } };
},
B.Object => {
var 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,
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 G = struct {
pub const Decl = struct {
binding: BindingNodeIndex,
value: ?ExprNodeIndex = null,
};
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{}),
};
// 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 {
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,
// 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,
pub const List = BabyList(Property);
pub const Kind = enum(u3) {
normal,
get,
set,
spread,
class_static_block,
pub fn jsonStringify(self: @This(), opts: anytype, o: anytype) !void {
return try std.json.stringify(@tagName(self), opts, o);
}
};
};
pub const FnBody = struct {
loc: logger.Loc,
stmts: StmtNodeList,
};
pub const Fn = struct {
name: ?LocRef,
open_parens_loc: logger.Loc,
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,
};
pub const Arg = struct {
ts_decorators: ExprNodeList = ExprNodeList{},
binding: BindingNodeIndex,
default: ?ExprNodeIndex = null,
// "constructor(public x: boolean) {}"
is_typescript_ctor_field: bool = false,
};
};
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.
chunk_index: ?u32 = null,
// 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.
nested_scope_slot: ?u32 = null,
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,
// 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;
// }
//
// However, we can't do the same for static fields:
//
// class Foo {
// static #foo = 123
// static bar = this.#foo
// }
//
// Compiling these static fields to something like this would be invalid:
//
// class Foo {
// static #foo;
// }
// Foo.#foo = 123;
// Foo.bar = Foo.#foo;
//
// Thus "#foo" must be lowered even though it's supported. Another case is
// when we're converting top-level class declarations to class expressions
// to avoid the TDZ and the class shadowing symbol is referenced within the
// class body:
//
// class Foo {
// static #foo = Foo
// }
//
// This cannot be converted into something like this:
//
// var Foo = class {
// static #foo;
// };
// Foo.#foo = Foo;
//
private_symbol_must_be_lowered: bool = false,
pub inline fn hasLink(this: *const Symbol) bool {
return !this.link.isNull();
}
pub const Kind = enum {
// An unbound symbol is one that isn't declared in the file it's referenced
// in. For example, using "window" without declaring it will be unbound.
unbound,
// This has special merging behavior. You're allowed to re-declare these
// symbols more than once in the same scope. These symbols are also hoisted
// out of the scope they are declared in to the closest containing function
// or module scope. These are the symbols with this kind:
//
// - Function arguments
// - Function statements
// - Variables declared using "var"
//
hoisted,
hoisted_function,
// There's a weird special case where catch variables declared using a simple
// identifier (i.e. not a binding pattern) block hoisted variables instead of
// becoming an error:
//
// var e = 0;
// try { throw 1 } catch (e) {
// print(e) // 1
// var e = 2
// print(e) // 2
// }
// print(e) // 0 (since the hoisting stops at the catch block boundary)
//
// However, other forms are still a syntax error:
//
// try {} catch (e) { let e }
// try {} catch ({e}) { var e }
//
// This symbol is for handling this weird special case.
catch_identifier,
// Generator and async functions are not hoisted, but still have special
// properties such as being able to overwrite previous functions with the
// same name
generator_or_async_function,
// This is the special "arguments" variable inside functions
arguments,
// Classes can merge with TypeScript namespaces.
class,
// A class-private identifier (i.e. "#foo").
private_field,
private_method,
private_get,
private_set,
private_get_set_pair,
private_static_field,
private_static_method,
private_static_get,
private_static_set,
private_static_get_set_pair,
// Labels are in their own namespace
label,
// TypeScript enums can merge with TypeScript namespaces and other TypeScript
// enums.
ts_enum,
// TypeScript namespaces can merge with classes, functions, TypeScript enums,
// and other TypeScript namespaces.
ts_namespace,
// In TypeScript, imports are allowed to silently collide with symbols within
// the module. Presumably this is because the imports may be type-only.
import,
// Assigning to a "const" symbol will throw a TypeError at runtime
cconst,
// This annotates all other symbols that don't have special behavior.
other,
pub fn jsonStringify(self: @This(), opts: anytype, o: anytype) !void {
return try std.json.stringify(@tagName(self), opts, o);
}
};
pub const Use = struct {
count_estimate: u32 = 0,
};
pub const Map = struct {
// This could be represented as a "map[Ref]Symbol" but a two-level array was
// more efficient in profiles. This appears to be because it doesn't involve
// a hash. This representation also makes it trivial to quickly merge symbol
// maps from multiple files together. Each file only generates symbols in a
// single inner array, so you can join the maps together by just make a
// single outer array containing all of the inner arrays. See the comment on
// "Ref" for more detail.
symbols_for_source: [][]Symbol,
pub fn get(self: *Map, ref: Ref) ?*Symbol {
if (Ref.isSourceIndexNull(ref.sourceIndex()) or ref.isSourceContentsSlice()) {
return null;
}
return &self.symbols_for_source[ref.sourceIndex()][ref.innerIndex()];
}
pub fn getConst(self: *Map, ref: Ref) ?*const Symbol {
if (Ref.isSourceIndexNull(ref.sourceIndex()) or ref.isSourceContentsSlice()) {
return null;
}
return &self.symbols_for_source[ref.sourceIndex()][ref.innerIndex()];
}
pub fn init(sourceCount: usize, allocator: std.mem.Allocator) !Map {
var symbols_for_source: [][]Symbol = try allocator.alloc([]Symbol, sourceCount);
return Map{ .symbols_for_source = symbols_for_source };
}
pub fn initList(list: [][]Symbol) Map {
return Map{ .symbols_for_source = list };
}
pub fn getWithLink(symbols: *Map, ref: Ref) ?*Symbol {
var symbol: *Symbol = symbols.get(ref) orelse return null;
if (symbol.hasLink()) {
return symbols.get(symbol.link) orelse symbol;
}
return symbol;
}
pub fn getWithLinkConst(symbols: *Map, ref: Ref) ?*const Symbol {
var symbol: *const Symbol = symbols.getConst(ref) orelse return null;
if (symbol.hasLink()) {
return symbols.getConst(symbol.link) orelse symbol;
}
return symbol;
}
pub fn follow(symbols: *Map, ref: Ref) Ref {
if (symbols.get(ref)) |symbol| {
const link = symbol.link;
if (link.isNull())
return ref;
if (link.eql(ref)) {
symbol.link = ref;
}
return symbol.link;
} else {
return ref;
}
}
};
pub inline fn isKindPrivate(kind: Symbol.Kind) bool {
return @enumToInt(kind) >= @enumToInt(Symbol.Kind.private_field) and @enumToInt(kind) <= @enumToInt(Symbol.Kind.private_static_get_set_pair);
}
pub inline fn isKindHoisted(kind: Symbol.Kind) bool {
return switch (kind) {
.hoisted, .hoisted_function => true,
else => false,
};
}
pub inline fn isHoisted(self: *const Symbol) bool {
return Symbol.isKindHoisted(self.kind);
}
pub inline fn isKindHoistedOrFunction(kind: Symbol.Kind) bool {
return switch (kind) {
.hoisted, .hoisted_function, .generator_or_async_function => true,
else => false,
};
}
pub inline fn isKindFunction(kind: Symbol.Kind) bool {
return switch (kind) {
.hoisted_function, .generator_or_async_function => true,
else => false,
};
}
pub fn isReactComponentishName(symbol: *const Symbol) bool {
switch (symbol.kind) {
.hoisted, .hoisted_function, .cconst, .class, .other => {
return switch (symbol.original_name[0]) {
'A'...'Z' => true,
else => false,
};
},
else => {
return false;
},
}
}
};
pub const OptionalChain = enum(u2) {
// "a?.b"
start,
// "a?.b.c" => ".c" is OptionalChainContinue
// "(a?.b).c" => ".c" is OptionalChain null
ccontinue,
pub fn jsonStringify(self: @This(), opts: anytype, o: anytype) !void {
return try std.json.stringify(@tagName(self), opts, o);
}
};
pub const E = struct {
pub const Array = struct {
items: ExprNodeList = ExprNodeList{},
comma_after_spread: ?logger.Loc = null,
is_single_line: bool = false,
is_parenthesized: bool = false,
was_originally_macro: bool = false,
close_bracket_loc: logger.Loc = logger.Loc.Empty,
pub fn push(this: *Array, allocator: std.mem.Allocator, item: Expr) !void {
try this.items.push(allocator, item);
}
pub inline fn slice(this: Array) []Expr {
return this.items.slice();
}
pub fn toJS(this: @This(), ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef {
var stack = std.heap.stackFallback(32 * @sizeOf(ExprNodeList), JSC.getAllocator(ctx));
var allocator = stack.get();
var results = allocator.alloc(JSC.C.JSValueRef, this.items.len) catch {
return JSC.C.JSValueMakeUndefined(ctx);
};
defer if (stack.fixed_buffer_allocator.end_index >= stack.fixed_buffer_allocator.buffer.len - 1) allocator.free(results);
var i: usize = 0;
const items = this.items.slice();
while (i < results.len) : (i += 1) {
results[i] = items[i].toJS(ctx, exception);
}
return JSC.C.JSObjectMakeArray(ctx, results.len, results.ptr, exception);
}
};
pub const Unary = struct {
op: Op.Code,
value: ExprNodeIndex,
};