forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_parser.zig
18860 lines (16647 loc) · 894 KB
/
js_parser.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
pub const std = @import("std");
pub const logger = @import("./logger.zig");
pub const js_lexer = @import("./js_lexer.zig");
pub const importRecord = @import("./import_record.zig");
pub const js_ast = @import("./js_ast.zig");
pub const options = @import("./options.zig");
pub const js_printer = @import("./js_printer.zig");
pub const renamer = @import("./renamer.zig");
const _runtime = @import("./runtime.zig");
pub const RuntimeImports = _runtime.Runtime.Imports;
pub const RuntimeFeatures = _runtime.Runtime.Features;
pub const RuntimeNames = _runtime.Runtime.Names;
pub const fs = @import("./fs.zig");
const _hash_map = @import("./hash_map.zig");
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 = @import("./string_mutable.zig").MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const G = js_ast.G;
const Define = @import("./defines.zig").Define;
const DefineData = @import("./defines.zig").DefineData;
const FeatureFlags = @import("./feature_flags.zig");
pub const isPackagePath = @import("./resolver/resolver.zig").isPackagePath;
pub const ImportKind = importRecord.ImportKind;
pub const BindingNodeIndex = js_ast.BindingNodeIndex;
const Decl = G.Decl;
const Property = G.Property;
const Arg = G.Arg;
const Allocator = std.mem.Allocator;
pub const StmtNodeIndex = js_ast.StmtNodeIndex;
pub const ExprNodeIndex = js_ast.ExprNodeIndex;
pub const ExprNodeList = js_ast.ExprNodeList;
pub const StmtNodeList = js_ast.StmtNodeList;
pub const BindingNodeList = js_ast.BindingNodeList;
const ComptimeStringMap = @import("./comptime_string_map.zig").ComptimeStringMap;
const JSC = @import("javascript_core");
fn _disabledAssert(_: bool) void {
if (!Environment.allow_assert) @compileLog("assert is missing an if (Environment.allow_assert)");
unreachable;
}
const assert = if (Environment.allow_assert) std.debug.assert else _disabledAssert;
const ExprListLoc = struct {
list: ExprNodeList,
loc: logger.Loc,
};
pub const LocRef = js_ast.LocRef;
pub const S = js_ast.S;
pub const B = js_ast.B;
pub const T = js_lexer.T;
pub const E = js_ast.E;
pub const Stmt = js_ast.Stmt;
pub const Expr = js_ast.Expr;
pub const Binding = js_ast.Binding;
pub const Symbol = js_ast.Symbol;
pub const Level = js_ast.Op.Level;
pub const Op = js_ast.Op;
pub const Scope = js_ast.Scope;
pub const locModuleScope = logger.Loc{ .start = -100 };
const Ref = @import("./ast/base.zig").Ref;
pub const StringHashMap = _hash_map.StringHashMap;
pub const AutoHashMap = _hash_map.AutoHashMap;
const StringHashMapUnamanged = _hash_map.StringHashMapUnamanged;
const ObjectPool = @import("./pool.zig").ObjectPool;
const NodeFallbackModules = @import("./node_fallbacks.zig");
// Dear reader,
// There are some things you should know about this file to make it easier for humans to read
// "P" is the internal parts of the parser
// "p.e" allocates a new Expr
// "p.b" allocates a new Binding
// "p.s" allocates a new Stmt
// We do it this way so if we want to refactor how these are allocated in the future, we only have to modify one function to change it everywhere
// Everything in JavaScript is either an Expression, a Binding, or a Statement.
// Expression: foo(1)
// Statement: let a = 1;
// Binding: a
// While the names for Expr, Binding, and Stmt are directly copied from esbuild, those were likely inspired by Go's parser.
// which is another example of a very fast parser.
const ScopeOrderList = std.ArrayListUnmanaged(?ScopeOrder);
const JSXFactoryName = "JSX";
const JSXAutomaticName = "jsx_module";
// kept as a static reference
const exports_string_name: string = "exports";
const MacroRefs = std.AutoArrayHashMap(Ref, u32);
pub const AllocatedNamesPool = ObjectPool(
std.ArrayList(string),
struct {
pub fn init(allocator: std.mem.Allocator) anyerror!std.ArrayList(string) {
return std.ArrayList(string).init(allocator);
}
}.init,
true,
4,
);
fn foldStringAddition(lhs: Expr, rhs: Expr) ?Expr {
switch (lhs.data) {
.e_string => |left| {
if (rhs.data == .e_string and left.isUTF8() and rhs.data.e_string.isUTF8()) {
lhs.data.e_string.push(rhs.data.e_string);
return lhs;
}
},
.e_binary => |bin| {
// 123 + "bar" + "baz"
if (bin.op == .bin_add) {
if (foldStringAddition(bin.right, rhs)) |out| {
return Expr.init(E.Binary, E.Binary{ .op = bin.op, .left = bin.left, .right = out }, lhs.loc);
}
}
},
else => {},
}
return null;
}
// If we are currently in a hoisted child of the module scope, relocate these
// declarations to the top level and return an equivalent assignment statement.
// Make sure to check that the declaration kind is "var" before calling this.
// And make sure to check that the returned statement is not the zero value.
//
// This is done to make some transformations non-destructive
// Without relocating vars to the top level, simplifying this:
// if (false) var foo = 1;
// to nothing is unsafe
// Because "foo" was defined. And now it's not.
pub const RelocateVars = struct {
pub const Mode = enum { normal, for_in_or_for_of };
stmt: ?Stmt = null,
ok: bool = false,
};
const VisitArgsOpts = struct {
body: []Stmt = &([_]Stmt{}),
has_rest_arg: bool = false,
// This is true if the function is an arrow function or a method
is_unique_formal_parameters: bool = false,
};
const BunJSX = struct {
pub threadlocal var bun_jsx_identifier: E.Identifier = undefined;
};
pub fn ExpressionTransposer(
comptime Kontext: type,
visitor: fn (ptr: *Kontext, arg: Expr, state: anytype) Expr,
) type {
return struct {
pub const Context = Kontext;
pub const This = @This();
context: *Context,
pub fn init(c: *Context) This {
return This{
.context = c,
};
}
pub fn maybeTransposeIf(self: *This, arg: Expr, state: anytype) Expr {
switch (arg.data) {
.e_if => |ex| {
ex.yes = self.maybeTransposeIf(ex.yes, state);
ex.no = self.maybeTransposeIf(ex.no, state);
return arg;
},
else => {
return visitor(self.context, arg, state);
},
}
}
};
}
pub fn locAfterOp(e: E.Binary) logger.Loc {
if (e.left.loc.start < e.right.loc.start) {
return e.right.loc;
} else {
// handle the case when we have transposed the operands
return e.left.loc;
}
}
const ExportsStringName = "exports";
const TransposeState = struct {
is_await_target: bool = false,
is_then_catch_target: bool = false,
loc: logger.Loc,
};
var true_args = &[_]Expr{
.{
.data = .{ .e_boolean = .{ .value = true } },
.loc = logger.Loc.Empty,
},
};
const JSXTag = struct {
pub const TagType = enum { fragment, tag };
pub const Data = union(TagType) {
fragment: u8,
tag: Expr,
pub fn asExpr(d: *const Data) ?ExprNodeIndex {
switch (d.*) {
.tag => |tag| {
return tag;
},
else => {
return null;
},
}
}
};
data: Data,
range: logger.Range,
name: string = "",
pub fn parse(comptime P: type, p: *P) anyerror!JSXTag {
const loc = p.lexer.loc();
// A missing tag is a fragment
if (p.lexer.token == .t_greater_than) {
return JSXTag{
.range = logger.Range{ .loc = loc, .len = 0 },
.data = Data{ .fragment = 1 },
.name = "",
};
}
// The tag is an identifier
var name = p.lexer.identifier;
var tag_range = p.lexer.range();
try p.lexer.expectInsideJSXElement(.t_identifier);
// Certain identifiers are strings
// <div
// <button
// <Hello-:Button
if (strings.containsComptime(name, "-:") or (p.lexer.token != .t_dot and name[0] >= 'a' and name[0] <= 'z')) {
return JSXTag{
.data = Data{ .tag = p.e(E.String{
.data = name,
}, loc) },
.range = tag_range,
};
}
// Otherwise, this is an identifier
// <Button>
var tag = p.e(E.Identifier{ .ref = try p.storeNameInRef(name) }, loc);
// Parse a member expression chain
// <Button.Red>
while (p.lexer.token == .t_dot) {
try p.lexer.nextInsideJSXElement();
const member_range = p.lexer.range();
const member = p.lexer.identifier;
try p.lexer.expectInsideJSXElement(.t_identifier);
if (strings.indexOfChar(member, '-')) |index| {
try p.log.addError(p.source, logger.Loc{ .start = member_range.loc.start + @intCast(i32, index) }, "Unexpected \"-\"");
return error.SyntaxError;
}
var _name = try p.allocator.alloc(u8, name.len + 1 + member.len);
std.mem.copy(u8, _name, name);
_name[name.len] = '.';
std.mem.copy(u8, _name[name.len + 1 .. _name.len], member);
name = _name;
tag_range.len = member_range.loc.start + member_range.len - tag_range.loc.start;
tag = p.e(E.Dot{ .target = tag, .name = member, .name_loc = member_range.loc }, loc);
}
return JSXTag{ .data = Data{ .tag = tag }, .range = tag_range, .name = name };
}
};
pub const TypeScript = struct {
// This function is taken from the official TypeScript compiler source code:
// https://github.com/microsoft/TypeScript/blob/master/src/compiler/parser.ts
pub fn canFollowTypeArgumentsInExpression(token: js_lexer.T) bool {
switch (token) {
// These are the only tokens can legally follow a type argument list. So we
// definitely want to treat them as type arg lists.
.t_open_paren, // foo<x>(
.t_no_substitution_template_literal, // foo<T> `...`
// foo<T> `...${100}...`
.t_template_head,
=> {
return true;
},
// These cases can't legally follow a type arg list. However, they're not
// legal expressions either. The user is probably in the middle of a
// generic type. So treat it as such.
.t_dot, // foo<x>.
.t_close_paren, // foo<x>)
.t_close_bracket, // foo<x>]
.t_colon, // foo<x>:
.t_semicolon, // foo<x>;
.t_question, // foo<x>?
.t_equals_equals, // foo<x> ==
.t_equals_equals_equals, // foo<x> ===
.t_exclamation_equals, // foo<x> !=
.t_exclamation_equals_equals, // foo<x> !==
.t_ampersand_ampersand, // foo<x> &&
.t_bar_bar, // foo<x> ||
.t_question_question, // foo<x> ??
.t_caret, // foo<x> ^
.t_ampersand, // foo<x> &
.t_bar, // foo<x> |
.t_close_brace, // foo<x> }
.t_end_of_file, // foo<x>
=> {
return true;
},
// We don't want to treat these as type arguments. Otherwise we'll parse
// this as an invocation expression. Instead, we want to parse out the
// expression in isolation from the type arguments.
.t_comma, // foo<x>,
.t_open_brace, // foo<x> {
=> {
return false;
},
else => {
// Anything else treat as an expression
return false;
},
}
}
pub const Identifier = struct {
pub const StmtIdentifier = enum {
s_type,
s_namespace,
s_abstract,
s_module,
s_interface,
s_declare,
};
pub fn forStr(str: string) ?StmtIdentifier {
switch (str.len) {
"type".len => return if (strings.eqlComptimeIgnoreLen(str, "type"))
.s_type
else
null,
"interface".len => {
if (strings.eqlComptime(str, "interface")) {
return .s_interface;
} else if (strings.eqlComptime(str, "namespace")) {
return .s_namespace;
} else {
return null;
}
},
"abstract".len => {
if (strings.eqlComptime(str, "abstract")) {
return .s_abstract;
} else {
return null;
}
},
"declare".len => {
if (strings.eqlComptime(str, "declare")) {
return .s_declare;
} else {
return null;
}
},
"module".len => {
if (strings.eqlComptime(str, "module")) {
return .s_module;
} else {
return null;
}
},
else => return null,
}
}
pub const IMap = ComptimeStringMap(Kind, .{
.{ "unique", .unique },
.{ "abstract", .abstract },
.{ "asserts", .asserts },
.{ "keyof", .prefix },
.{ "readonly", .prefix },
.{ "infer", .prefix },
.{ "any", .primitive },
.{ "never", .primitive },
.{ "unknown", .primitive },
.{ "undefined", .primitive },
.{ "object", .primitive },
.{ "number", .primitive },
.{ "string", .primitive },
.{ "boolean", .primitive },
.{ "bigint", .primitive },
.{ "symbol", .primitive },
});
pub const Kind = enum {
normal,
unique,
abstract,
asserts,
prefix,
primitive,
};
};
pub const SkipTypeOptions = struct {
is_return_type: bool = false,
};
};
// We must prevent collisions from generated names.
// We want to avoid adding a pass over all the symbols in the file.
// To do that:
// For every generated symbol, we reserve two backup symbol names
// If any usages of the preferred ref, we swap original_name with the backup
// If any usages of the backup ref, we swap original_name with the internal
// We *assume* the internal name is never used.
// In practice, it is possible. But, the internal names are so crazy long you'd have to be deliberately trying to use them.
const GeneratedSymbol = @import("./runtime.zig").Runtime.GeneratedSymbol;
pub const ImportScanner = struct {
stmts: []Stmt = &([_]Stmt{}),
kept_import_equals: bool = false,
removed_import_equals: bool = false,
pub fn scan(comptime P: type, p: *P, stmts: []Stmt, will_transform_to_common_js: bool) !ImportScanner {
var scanner = ImportScanner{};
var stmts_end: usize = 0;
const allocator = p.allocator;
const is_typescript_enabled: bool = comptime P.parser_features.typescript;
for (stmts) |_stmt| {
// zls needs the hint, it seems.
var stmt: Stmt = _stmt;
switch (stmt.data) {
.s_import => |st__| {
var st = st__.*;
defer {
st__.* = st;
}
var record: *ImportRecord = &p.import_records.items[st.import_record_index];
if (record.path.isMacro()) {
record.is_unused = true;
record.path.is_disabled = true;
continue;
}
// The official TypeScript compiler always removes unused imported
// symbols. However, we deliberately deviate from the official
// TypeScript compiler's behavior doing this in a specific scenario:
// we are not bundling, symbol renaming is off, and the tsconfig.json
// "importsNotUsedAsValues" setting is present and is not set to
// "remove".
//
// This exists to support the use case of compiling partial modules for
// compile-to-JavaScript languages such as Svelte. These languages try
// to reference imports in ways that are impossible for esbuild to know
// about when esbuild is only given a partial module to compile. Here
// is an example of some Svelte code that might use esbuild to convert
// TypeScript to JavaScript:
//
// <script lang="ts">
// import Counter from './Counter.svelte';
// export let name: string = 'world';
// </script>
// <main>
// <h1>Hello {name}!</h1>
// <Counter />
// </main>
//
// Tools that use esbuild to compile TypeScript code inside a Svelte
// file like this only give esbuild the contents of the <script> tag.
// These tools work around this missing import problem when using the
// official TypeScript compiler by hacking the TypeScript AST to
// remove the "unused import" flags. This isn't possible in esbuild
// because esbuild deliberately does not expose an AST manipulation
// API for performance reasons.
//
// We deviate from the TypeScript compiler's behavior in this specific
// case because doing so is useful for these compile-to-JavaScript
// languages and is benign in other cases. The rationale is as follows:
//
// * If "importsNotUsedAsValues" is absent or set to "remove", then
// we don't know if these imports are values or types. It's not
// safe to keep them because if they are types, the missing imports
// will cause run-time failures because there will be no matching
// exports. It's only safe keep imports if "importsNotUsedAsValues"
// is set to "preserve" or "error" because then we can assume that
// none of the imports are types (since the TypeScript compiler
// would generate an error in that case).
//
// * If we're bundling, then we know we aren't being used to compile
// a partial module. The parser is seeing the entire code for the
// module so it's safe to remove unused imports. And also we don't
// want the linker to generate errors about missing imports if the
// imported file is also in the bundle.
//
// * If identifier minification is enabled, then using esbuild as a
// partial-module transform library wouldn't work anyway because
// the names wouldn't match. And that means we're minifying so the
// user is expecting the output to be as small as possible. So we
// should omit unused imports.
//
var did_remove_star_loc = false;
const keep_unused_imports = !p.options.features.trim_unused_imports;
// TypeScript always trims unused imports. This is important for
// correctness since some imports might be fake (only in the type
// system and used for type-only imports).
if (!keep_unused_imports) {
var found_imports = false;
var is_unused_in_typescript = true;
if (st.default_name) |default_name| {
found_imports = true;
const symbol = p.symbols.items[default_name.ref.?.innerIndex()];
// TypeScript has a separate definition of unused
if (is_typescript_enabled and p.ts_use_counts.items[default_name.ref.?.innerIndex()] != 0) {
is_unused_in_typescript = false;
}
// Remove the symbol if it's never used outside a dead code region
if (symbol.use_count_estimate == 0) {
st.default_name = null;
}
}
// Remove the star import if it's unused
if (st.star_name_loc) |_| {
found_imports = true;
const symbol = p.symbols.items[st.namespace_ref.innerIndex()];
// TypeScript has a separate definition of unused
if (is_typescript_enabled and p.ts_use_counts.items[st.namespace_ref.innerIndex()] != 0) {
is_unused_in_typescript = false;
}
// Remove the symbol if it's never used outside a dead code region
if (symbol.use_count_estimate == 0) {
// Make sure we don't remove this if it was used for a property
// access while bundling
var has_any = false;
if (p.import_items_for_namespace.get(st.namespace_ref)) |entry| {
if (entry.count() > 0) {
has_any = true;
break;
}
}
if (!has_any) {
st.star_name_loc = null;
did_remove_star_loc = true;
}
}
}
// Remove items if they are unused
if (st.items.len > 0) {
found_imports = true;
var items_end: usize = 0;
var i: usize = 0;
while (i < st.items.len) : (i += 1) {
const item = st.items[i];
const ref = item.name.ref.?;
const symbol: Symbol = p.symbols.items[ref.innerIndex()];
// TypeScript has a separate definition of unused
if (is_typescript_enabled and p.ts_use_counts.items[ref.innerIndex()] != 0) {
is_unused_in_typescript = false;
}
// Remove the symbol if it's never used outside a dead code region
if (symbol.use_count_estimate != 0) {
st.items[items_end] = item;
items_end += 1;
}
}
st.items = st.items[0..items_end];
}
// -- Original Comment --
// Omit this statement if we're parsing TypeScript and all imports are
// unused. Note that this is distinct from the case where there were
// no imports at all (e.g. "import 'foo'"). In that case we want to keep
// the statement because the user is clearly trying to import the module
// for side effects.
//
// This culling is important for correctness when parsing TypeScript
// because a) the TypeScript compiler does ths and we want to match it
// and b) this may be a fake module that only exists in the type system
// and doesn't actually exist in reality.
//
// We do not want to do this culling in JavaScript though because the
// module may have side effects even if all imports are unused.
// -- Original Comment --
// jarred: I think, in this project, we want this behavior, even in JavaScript.
// I think this would be a big performance improvement.
// The less you import, the less code you transpile.
// Side-effect imports are nearly always done through identifier-less imports
// e.g. `import 'fancy-stylesheet-thing/style.css';`
// This is a breaking change though. We can make it an option with some guardrail
// so maybe if it errors, it shows a suggestion "retry without trimming unused imports"
if ((is_typescript_enabled and found_imports and is_unused_in_typescript and !p.options.preserve_unused_imports_ts) or
(!is_typescript_enabled and p.options.features.trim_unused_imports and found_imports and st.star_name_loc == null and st.items.len == 0 and st.default_name == null))
{
// internal imports are presumed to be always used
// require statements cannot be stripped
if (!record.is_internal and !record.was_originally_require) {
record.is_unused = true;
continue;
}
}
}
const namespace_ref = st.namespace_ref;
const convert_star_to_clause = !p.options.enable_bundling and !p.options.can_import_from_bundle and p.symbols.items[namespace_ref.innerIndex()].use_count_estimate == 0;
if (convert_star_to_clause and !keep_unused_imports) {
st.star_name_loc = null;
}
record.contains_default_alias = record.contains_default_alias or st.default_name != null;
const existing_items: ImportItemForNamespaceMap = p.import_items_for_namespace.get(namespace_ref) orelse
ImportItemForNamespaceMap.init(allocator);
// ESM requires live bindings
// CommonJS does not require live bindings
// We load ESM in browsers & in Bun.js
// We have to simulate live bindings for cases where the code is bundled
// We do not know at this stage whether or not the import statement is bundled
// This keeps track of the `namespace_alias` incase, at printing time, we determine that we should print it with the namespace
for (st.items) |item| {
const is_default = strings.eqlComptime(item.alias, "default");
record.contains_default_alias = record.contains_default_alias or is_default;
const name: LocRef = item.name;
const name_ref = name.ref.?;
try p.named_imports.put(name_ref, js_ast.NamedImport{
.alias = item.alias,
.alias_loc = name.loc,
.namespace_ref = namespace_ref,
.import_record_index = st.import_record_index,
});
// Make sure the printer prints this as a property access
var symbol: *Symbol = &p.symbols.items[name_ref.innerIndex()];
symbol.namespace_alias = G.NamespaceAlias{
.namespace_ref = namespace_ref,
.alias = item.alias,
.import_record_index = st.import_record_index,
.was_originally_property_access = st.star_name_loc != null and existing_items.contains(symbol.original_name),
};
}
try p.import_records_for_current_part.append(allocator, st.import_record_index);
if (st.star_name_loc != null) {
record.contains_import_star = true;
}
if (record.was_originally_require) {
var symbol = &p.symbols.items[namespace_ref.innerIndex()];
symbol.namespace_alias = G.NamespaceAlias{
.namespace_ref = namespace_ref,
.alias = "",
.import_record_index = st.import_record_index,
.was_originally_property_access = false,
};
}
},
.s_function => |st| {
if (st.func.flags.contains(.is_export)) {
if (st.func.name) |name| {
const original_name = p.symbols.items[name.ref.?.innerIndex()].original_name;
try p.recordExport(name.loc, original_name, name.ref.?);
if (p.options.features.hot_module_reloading) {
st.func.flags.remove(.is_export);
}
} else {
try p.log.addRangeError(p.source, logger.Range{ .loc = st.func.open_parens_loc, .len = 2 }, "Exported functions must have a name");
}
}
},
.s_class => |st| {
if (st.is_export) {
if (st.class.class_name) |name| {
try p.recordExport(name.loc, p.symbols.items[name.ref.?.innerIndex()].original_name, name.ref.?);
if (p.options.features.hot_module_reloading) {
st.is_export = false;
}
} else {
try p.log.addRangeError(p.source, logger.Range{ .loc = st.class.body_loc, .len = 0 }, "Exported classes must have a name");
}
}
},
.s_local => |st| {
if (st.is_export) {
for (st.decls) |decl| {
p.recordExportedBinding(decl.binding);
}
}
// Remove unused import-equals statements, since those likely
// correspond to types instead of values
if (st.was_ts_import_equals and !st.is_export and st.decls.len > 0) {
var decl = st.decls[0];
// Skip to the underlying reference
var value = decl.value;
if (decl.value) |val| {
while (true) {
if (@as(Expr.Tag, val.data) == .e_dot) {
value = val.data.e_dot.target;
} else {
break;
}
}
}
// Is this an identifier reference and not a require() call?
if (value) |val| {
if (@as(Expr.Tag, val.data) == .e_identifier) {
// Is this import statement unused?
if (@as(Binding.Tag, decl.binding.data) == .b_identifier and p.symbols.items[decl.binding.data.b_identifier.ref.innerIndex()].use_count_estimate == 0) {
p.ignoreUsage(val.data.e_identifier.ref);
scanner.removed_import_equals = true;
continue;
} else {
scanner.kept_import_equals = true;
}
}
}
}
// We must do this at the end to not mess up import =
if (p.options.features.hot_module_reloading and st.is_export) {
st.is_export = false;
}
},
.s_export_default => |st| {
// This is defer'd so that we still record export default for identifiers
defer {
if (st.default_name.ref) |ref| {
p.recordExport(st.default_name.loc, "default", ref) catch {};
}
}
// Rewrite this export to be:
// exports.default =
// But only if it's anonymous
if (p.options.features.hot_module_reloading) {
// export default can be:
// - an expression
// - a function
// - a class
// it cannot be a declaration!
// we want to avoid adding a new name
// but we must remove the export default clause.
transform_export_default_when_its_anonymous: {
switch (st.value) {
.expr => |ex| {
switch (ex.data) {
.e_identifier => {
continue;
},
.e_import_identifier => |import_ident| {
st.default_name.ref = import_ident.ref;
continue;
},
.e_function => |func| {
if (func.func.name) |name_ref| {
if (name_ref.ref != null) {
stmt = p.s(S.Function{ .func = func.func }, ex.loc);
st.default_name.ref = name_ref.ref.?;
break :transform_export_default_when_its_anonymous;
}
}
},
.e_class => |class| {
if (class.class_name) |name_ref| {
if (name_ref.ref != null) {
stmt = p.s(
S.Class{
.class = class.*,
},
ex.loc,
);
st.default_name.ref = name_ref.ref.?;
break :transform_export_default_when_its_anonymous;
}
}
},
else => {},
}
var decls = try allocator.alloc(G.Decl, 1);
decls[0] = G.Decl{ .binding = p.b(B.Identifier{ .ref = st.default_name.ref.? }, stmt.loc), .value = ex };
stmt = p.s(S.Local{
.decls = decls,
.kind = S.Local.Kind.k_var,
.is_export = false,
}, ex.loc);
},
.stmt => |class_or_func| {
switch (class_or_func.data) {
.s_function => |func| {
if (func.func.name) |name_ref| {
if (name_ref.ref != null) {
stmt = class_or_func;
st.default_name.ref = name_ref.ref.?;
break :transform_export_default_when_its_anonymous;
}
}
var decls = try allocator.alloc(G.Decl, 1);
decls[0] = G.Decl{ .binding = p.b(B.Identifier{ .ref = st.default_name.ref.? }, stmt.loc), .value = p.e(E.Function{ .func = func.func }, stmt.loc) };
stmt = p.s(S.Local{
.decls = decls,
.kind = S.Local.Kind.k_var,
.is_export = false,
}, stmt.loc);
},
.s_class => |class| {
if (class.class.class_name) |name_ref| {
if (name_ref.ref != null) {
stmt = class_or_func;
st.default_name.ref = name_ref.ref.?;
break :transform_export_default_when_its_anonymous;
}
}
var decls = try allocator.alloc(G.Decl, 1);
decls[0] = G.Decl{
.binding = p.b(B.Identifier{ .ref = st.default_name.ref.? }, stmt.loc),
.value = p.e(E.Class{
.class_keyword = class.class.class_keyword,
.ts_decorators = class.class.ts_decorators,
.class_name = class.class.class_name,
.extends = class.class.extends,
.body_loc = class.class.body_loc,
.properties = class.class.properties,
.close_brace_loc = class.class.close_brace_loc,
}, stmt.loc),
};
stmt = p.s(S.Local{
.decls = decls,
.kind = S.Local.Kind.k_var,
.is_export = false,
}, stmt.loc);
},
else => unreachable,
}
},
}
}
} else if (will_transform_to_common_js) {
const expr: js_ast.Expr = switch (st.value) {
.expr => |exp| exp,
.stmt => |s2| brk2: {
switch (s2.data) {
.s_function => |func| {
break :brk2 p.e(E.Function{ .func = func.func }, s2.loc);
},
.s_class => |class| {
break :brk2 p.e(class.class, s2.loc);
},
else => unreachable,
}
},
};
var export_default_args = p.allocator.alloc(Expr, 2) catch unreachable;
export_default_args[0] = p.@"module.exports"(expr.loc);
export_default_args[1] = expr;
stmt = p.s(S.SExpr{ .value = p.callRuntime(expr.loc, "__exportDefault", export_default_args) }, expr.loc);
}
},
.s_export_clause => |st| {
for (st.items) |item| {
try p.recordExport(item.alias_loc, item.alias, item.name.ref.?);
}
// export clauses simply disappear when we have HMR on, we use NamedExports to regenerate it at the end
if (p.options.features.hot_module_reloading) {
continue;
}
},
.s_export_star => |st| {
try p.import_records_for_current_part.append(allocator, st.import_record_index);
if (st.alias) |alias| {
// "export * as ns from 'path'"
try p.named_imports.put(st.namespace_ref, js_ast.NamedImport{
.alias = null,
.alias_is_star = true,
.alias_loc = alias.loc,
.namespace_ref = Ref.None,
.import_record_index = st.import_record_index,
.is_exported = true,
});
try p.recordExport(alias.loc, alias.original_name, st.namespace_ref);
} else {
// "export * from 'path'"
try p.export_star_import_records.append(allocator, st.import_record_index);
}
},
.s_export_from => |st| {
try p.import_records_for_current_part.append(allocator, st.import_record_index);
for (st.items) |item| {
const ref = item.name.ref orelse p.panic("Expected export from item to have a name {s}", .{st});
// Note that the imported alias is not item.Alias, which is the
// exported alias. This is somewhat confusing because each
// SExportFrom statement is basically SImport + SExportClause in one.
try p.named_imports.put(ref, js_ast.NamedImport{
.alias_is_star = false,
.alias = item.original_name,
.alias_loc = item.name.loc,
.namespace_ref = st.namespace_ref,
.import_record_index = st.import_record_index,
.is_exported = true,
});
try p.recordExport(item.name.loc, item.alias, ref);
}
},
else => {},
}
stmts[stmts_end] = stmt;
stmts_end += 1;
}
scanner.stmts = stmts[0..stmts_end];
return scanner;
}
};
const StaticSymbolName = struct {
internal: string,
primary: string,
backup: string,
pub const List = struct {
fn NewStaticSymbol(comptime basename: string) StaticSymbolName {
return comptime StaticSymbolName{
.internal = basename ++ "_" ++ std.fmt.comptimePrint("{x}", .{std.hash.Wyhash.hash(0, basename)}),
.primary = basename,
.backup = "_" ++ basename ++ "$",
};
}
fn NewStaticSymbolWithBackup(comptime basename: string, comptime backup: string) StaticSymbolName {
return comptime StaticSymbolName{
.internal = basename ++ "_" ++ std.fmt.comptimePrint("{x}", .{std.hash.Wyhash.hash(0, basename)}),
.primary = basename,
.backup = backup,
};
}
pub const jsx = NewStaticSymbol("jsx");
pub const jsxs = NewStaticSymbol("jsxs");
pub const ImportSource = NewStaticSymbol("JSX");
pub const ClassicImportSource = NewStaticSymbol("JSXClassic");
pub const jsxFilename = NewStaticSymbolWithBackup("fileName", "jsxFileName");
pub const REACT_ELEMENT_TYPE = NewStaticSymbolWithBackup("$$typeof", "$$reactEl");
pub const Symbol = NewStaticSymbolWithBackup("Symbol", "Symbol");