/
interpreter.zig
8058 lines (7023 loc) · 349 KB
/
interpreter.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
//! The interpreter for the shell language
//!
//! Normally, the implementation would be a very simple tree-walk of the AST,
//! but it needs to be non-blocking, and Zig does not have coroutines yet, so
//! this implementation is half tree-walk half one big state machine. The state
//! machine part manually keeps track of execution state (which coroutines would
//! do for us), but makes the code very confusing because control flow is less obvious.
//!
//! Things to note:
//! - If you want to do something analogous to yielding execution, you must
//! `return` from the function. For example in the code we start an async
//! BufferedWriter and "yield" execution by calling =.start()= on the writer and
//! then `return`ing form the function
//! - Sometimes a state machine will immediately finish and deinit itself so
//! that might cause some unintuitive things to happen. For example if you
//! `defer` some code, then try to yield execution to some state machine struct,
//! and it immediately finishes, it will deinit itself and the defer code might
//! use undefined memory.
const std = @import("std");
const builtin = @import("builtin");
const bun = @import("root").bun;
const os = std.os;
const Arena = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const JSC = bun.JSC;
const JSValue = bun.JSC.JSValue;
const JSPromise = bun.JSC.JSPromise;
const JSGlobalObject = bun.JSC.JSGlobalObject;
const which = @import("../which.zig").which;
const Braces = @import("./braces.zig");
const Syscall = @import("../sys.zig");
const Glob = @import("../glob.zig");
const ResolvePath = @import("../resolver/resolve_path.zig");
const DirIterator = @import("../bun.js/node/dir_iterator.zig");
const CodepointIterator = @import("../string_immutable.zig").PackedCodepointIterator;
const isAllAscii = @import("../string_immutable.zig").isAllASCII;
const TaggedPointerUnion = @import("../tagged_pointer.zig").TaggedPointerUnion;
// const Subprocess = bun.ShellSubprocess;
const TaggedPointer = @import("../tagged_pointer.zig").TaggedPointer;
pub const WorkPoolTask = @import("../work_pool.zig").Task;
pub const WorkPool = @import("../work_pool.zig").WorkPool;
const Maybe = JSC.Maybe;
const Pipe = [2]bun.FileDescriptor;
const shell = @import("./shell.zig");
const Token = shell.Token;
const ShellError = shell.ShellError;
const ast = shell.AST;
const GlobWalker = @import("../glob.zig").GlobWalker_(null, true);
pub const SUBSHELL_TODO_ERROR = "Subshells are not implemented, please open GitHub issue.";
const stdin_no = 0;
const stdout_no = 1;
const stderr_no = 2;
pub fn OOM(e: anyerror) noreturn {
if (comptime bun.Environment.allow_assert) {
if (e != error.OutOfMemory) @panic("Ruh roh");
}
@panic("Out of memory");
}
const log = bun.Output.scoped(.SHELL, false);
pub fn assert(cond: bool, comptime msg: []const u8) void {
if (bun.Environment.allow_assert) {
std.debug.assert(cond);
} else {
@panic("Assertion failed: " ++ msg);
}
}
const ExitCode = if (bun.Environment.isWindows) u16 else u8;
pub const StateKind = enum(u8) {
script,
stmt,
assign,
cmd,
cond,
pipeline,
expansion,
};
/// Copy-on-write
pub fn Cow(comptime T: type, comptime VTable: type) type {
const Handler = struct {
fn copy(this: *T) T {
if (@hasDecl(VTable, "copy")) @compileError(@typeName(VTable) ++ " needs `copy()` function");
return VTable.copy(this);
}
fn deinit(this: *T) void {
if (@hasDecl(VTable, "deinit")) @compileError(@typeName(VTable) ++ " needs `deinit()` function");
return VTable.deinit(this);
}
};
return union(enum) {
borrowed: *T,
owned: T,
pub fn borrow(val: *T) @This() {
return .{
.borrowed = val,
};
}
pub fn own(val: T) @This() {
return .{
.owned = val,
};
}
/// Get the underlying value.
pub inline fn inner(this: *@This()) *T {
return switch (this.*) {
.borrowed => this.borrowed,
.owned => &this.owned,
};
}
pub fn copy(this: *@This()) void {
switch (this.*) {
.borrowed => {
this.* = .{
.owned = Handler.copy(this.borrowed),
};
},
.owned => {},
}
}
pub fn deinit(this: *@This()) void {
Handler.deinit(this.inner());
}
};
}
pub const CoroutineResult = enum {
/// it's okay for the caller to continue its execution
cont,
yield,
};
pub const IO = struct {
stdin: Kind = .{ .std = .{} },
stdout: Kind = .{ .std = .{} },
stderr: Kind = .{ .std = .{} },
pub const Kind = union(enum) {
/// Use stdin/stdout/stderr of this process
/// If `captured` is non-null, it will write to std{out,err} and also buffer it.
/// The pointer points to the `buffered_stdout`/`buffered_stdin` fields
/// in the Interpreter struct
std: struct { captured: ?*bun.ByteList = null },
/// Write/Read to/from file descriptor
fd: bun.FileDescriptor,
/// Buffers the output (handled in Cmd.BufferedIoClosed.close())
pipe,
/// Discards output
ignore,
// fn dupeForSubshell(this: *ShellState,
fn close(this: Kind) void {
switch (this) {
.fd => {
closefd(this.fd);
},
else => {},
}
}
fn to_subproc_stdio(this: Kind) bun.shell.subproc.Stdio {
return switch (this) {
.std => .{ .inherit = .{ .captured = this.std.captured } },
.fd => |val| .{ .fd = val },
.pipe => .{ .pipe = null },
.ignore => .ignore,
};
}
};
fn to_subproc_stdio(this: IO, stdio: *[3]bun.shell.subproc.Stdio) void {
stdio[stdin_no] = this.stdin.to_subproc_stdio();
stdio[stdout_no] = this.stdout.to_subproc_stdio();
stdio[stderr_no] = this.stderr.to_subproc_stdio();
}
};
pub const Interpreter = NewInterpreter(.js);
pub const InterpreterMini = NewInterpreter(.mini);
/// Environment strings need to be copied a lot
/// So we make them reference counted
///
/// But sometimes we use strings that are statically allocated, or are allocated
/// with a predetermined lifetime (e.g. strings in the AST). In that case we
/// don't want to incur the cost of heap allocating them and refcounting them
///
/// So environment strings can be ref counted or borrowed slices
pub const EnvStr = packed struct {
ptr: u48,
tag: Tag,
len: usize = 0,
const print = bun.Output.scoped(.EnvStr, true);
const Tag = enum(u16) {
/// Dealloced by reference counting
refcounted,
/// Memory is managed elsewhere so don't dealloc it
slice,
};
inline fn initSlice(str: []const u8) EnvStr {
return .{
.ptr = @intCast(@intFromPtr(str.ptr)),
.tag = .slice,
.len = str.len,
};
}
fn initRefCounted(str: []const u8) EnvStr {
return .{
.ptr = @intCast(@intFromPtr(RefCountedStr.init(str))),
.tag = .refcounted,
};
}
pub fn slice(this: EnvStr) []const u8 {
if (this.asRefCounted()) |refc| {
return refc.byteSlice();
}
return this.castSlice();
}
fn ref(this: EnvStr) void {
if (this.asRefCounted()) |refc| {
refc.ref();
}
}
fn deref(this: EnvStr) void {
if (this.asRefCounted()) |refc| {
refc.deref();
}
}
inline fn asRefCounted(this: EnvStr) ?*RefCountedStr {
if (this.tag == .refcounted) return this.castRefCounted();
return null;
}
inline fn castSlice(this: EnvStr) []const u8 {
return @as([*]u8, @ptrFromInt(@as(usize, @intCast(this.ptr))))[0..this.len];
}
inline fn castRefCounted(this: EnvStr) *RefCountedStr {
return @ptrFromInt(@as(usize, @intCast(this.ptr)));
}
};
pub const RefCountedStr = struct {
refcount: u32 = 1,
len: u32 = 0,
ptr: [*]const u8 = undefined,
const print = bun.Output.scoped(.RefCountedEnvStr, true);
// /// Use bun.default_allocator
// const DEFAULT_ALLOC_TAG: usize = 1 << 63;
fn init(slice: []const u8) *RefCountedStr {
print("init: {s}", .{slice});
const this = bun.default_allocator.create(RefCountedStr) catch bun.outOfMemory();
this.* = .{
.refcount = 1,
.len = @intCast(slice.len),
.ptr = slice.ptr,
};
return this;
}
fn byteSlice(this: *RefCountedStr) []const u8 {
if (this.len == 0) return "";
return this.ptr[0..this.len];
}
fn ref(this: *RefCountedStr) void {
this.refcount += 1;
}
fn deref(this: *RefCountedStr) void {
this.refcount -= 1;
if (this.refcount == 0) {
this.deinit();
}
}
fn deinit(this: *RefCountedStr) void {
print("deinit: {s}", .{this.byteSlice()});
this.freeStr();
bun.default_allocator.destroy(this);
}
fn freeStr(this: *RefCountedStr) void {
if (this.len == 0) return;
// if (this.ptr & DEFAULT_ALLOC_TAG != 0) {
bun.default_allocator.free(this.ptr[0..this.len]);
// } else {}
}
};
/// TODO use this
/// Either
/// A: subshells (`$(...)` or `(...)`) or
/// B: commands in a pipeline
/// will need their own copy of the shell environment because they could modify it,
/// and those changes shouldn't affect the surounding environment.
///
/// This results in a lot of copying, which is wasteful since most of the time
/// A) or B) won't even mutate the environment anyway.
///
/// A way to reduce copying is to only do it when the env is mutated: copy-on-write.
pub const CowEnvMap = Cow(EnvMap, struct {
pub fn copy(val: *EnvMap) EnvMap {
return val.clone();
}
pub fn deinit(val: *EnvMap) void {
val.deinit();
}
});
pub const EnvMap = struct {
map: MapType,
pub const Iterator = MapType.Iterator;
const MapType = std.ArrayHashMap(EnvStr, EnvStr, struct {
pub fn hash(self: @This(), s: EnvStr) u32 {
_ = self;
return std.array_hash_map.hashString(s.slice());
}
pub fn eql(self: @This(), a: EnvStr, b: EnvStr, b_index: usize) bool {
_ = self;
_ = b_index;
return std.array_hash_map.eqlString(a.slice(), b.slice());
}
}, true);
fn init(alloc: Allocator) EnvMap {
return .{ .map = MapType.init(alloc) };
}
fn deinit(this: *EnvMap) void {
this.derefStrings();
this.map.deinit();
}
fn insert(this: *EnvMap, key: EnvStr, val: EnvStr) void {
const result = this.map.getOrPut(key) catch bun.outOfMemory();
if (!result.found_existing) {
key.ref();
} else {
result.value_ptr.deref();
}
val.ref();
result.value_ptr.* = val;
}
fn iterator(this: *EnvMap) MapType.Iterator {
return this.map.iterator();
}
fn clearRetainingCapacity(this: *EnvMap) void {
this.derefStrings();
this.map.clearRetainingCapacity();
}
fn ensureTotalCapacity(this: *EnvMap, new_capacity: usize) void {
this.map.ensureTotalCapacity(new_capacity) catch bun.outOfMemory();
}
/// NOTE: Make sure you deref the string when done!
fn get(this: *EnvMap, key: EnvStr) ?EnvStr {
const val = this.map.get(key) orelse return null;
val.ref();
return val;
}
fn clone(this: *EnvMap) EnvMap {
var new: EnvMap = .{
.map = this.map.clone() catch bun.outOfMemory(),
};
new.refStrings();
return new;
}
fn cloneWithAllocator(this: *EnvMap, allocator: Allocator) EnvMap {
var new: EnvMap = .{
.map = this.map.cloneWithAllocator(allocator) catch bun.outOfMemory(),
};
new.refStrings();
return new;
}
fn refStrings(this: *EnvMap) void {
var iter = this.map.iterator();
while (iter.next()) |entry| {
entry.key_ptr.ref();
entry.value_ptr.ref();
}
}
fn derefStrings(this: *EnvMap) void {
var iter = this.map.iterator();
while (iter.next()) |entry| {
entry.key_ptr.deref();
entry.value_ptr.deref();
}
}
};
/// This interpreter works by basically turning the AST into a state machine so
/// that execution can be suspended and resumed to support async.
pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
const GlobalRef = switch (EventLoopKind) {
.js => *JSGlobalObject,
.mini => *JSC.MiniEventLoop,
};
const GlobalHandle = switch (EventLoopKind) {
.js => bun.shell.GlobalJS,
.mini => bun.shell.GlobalMini,
};
const EventLoopRef = switch (EventLoopKind) {
.js => *JSC.EventLoop,
.mini => *JSC.MiniEventLoop,
};
const event_loop_ref = struct {
fn get() EventLoopRef {
return switch (EventLoopKind) {
.js => JSC.VirtualMachine.get().event_loop,
.mini => bun.JSC.MiniEventLoop.global,
};
}
};
const global_handle = struct {
fn get() GlobalHandle {
return switch (EventLoopKind) {
.js => bun.shell.GlobalJS.init(JSC.VirtualMachine.get().global),
.mini => bun.shell.GlobalMini.init(bun.JSC.MiniEventLoop.global),
};
}
};
const EventLoopTask = switch (EventLoopKind) {
.js => JSC.ConcurrentTask,
.mini => JSC.AnyTaskWithExtraContext,
};
// const Builtin = switch (EventLoopKind) {
// .js => NewBuiltin(.js),
// .mini => NewBuiltin(.mini),
// };
// const Subprocess = switch (EventLoopKind) {
// .js => bun.shell.Subprocess,
// .mini => bun.shell.SubprocessMini,
// };
// const Subprocess = bun.shell.subproc.NewShellSubprocess(EventLoopKind);
return struct {
global: GlobalRef,
/// This is the arena used to allocate the input shell script's AST nodes,
/// tokens, and a string pool used to store all strings.
arena: bun.ArenaAllocator,
/// This is the allocator used to allocate interpreter state
allocator: Allocator,
/// Root ast node
script: *ast.Script,
/// JS objects used as input for the shell script
/// This should be allocated using the arena
jsobjs: []JSValue,
root_shell: ShellState,
resolve: JSC.Strong = .{},
reject: JSC.Strong = .{},
has_pending_activity: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),
started: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
done: ?*bool = null,
const InterpreterChildPtr = StatePtrUnion(.{
Script,
});
pub const ShellState = struct {
io: IO = .{},
kind: Kind = .normal,
/// These MUST use the `bun.default_allocator` Allocator
_buffered_stdout: Bufio = .{ .owned = .{} },
_buffered_stderr: Bufio = .{ .owned = .{} },
/// TODO Performance optimization: make these env maps copy-on-write
/// Shell env for expansion by the shell
shell_env: EnvMap,
/// Local environment variables to be given to a subprocess
cmd_local_env: EnvMap,
/// Exported environment variables available to all subprocesses. This includes system ones.
export_env: EnvMap,
/// The current working directory of the shell.
/// Use an array list so we don't have to keep reallocating
/// Always has zero-sentinel
__prev_cwd: std.ArrayList(u8),
__cwd: std.ArrayList(u8),
cwd_fd: bun.FileDescriptor,
const Bufio = union(enum) { owned: bun.ByteList, borrowed: *bun.ByteList };
const Kind = enum {
normal,
cmd_subst,
subshell,
pipeline,
};
pub fn buffered_stdout(this: *ShellState) *bun.ByteList {
return switch (this._buffered_stdout) {
.owned => &this._buffered_stdout.owned,
.borrowed => this._buffered_stdout.borrowed,
};
}
pub fn buffered_stderr(this: *ShellState) *bun.ByteList {
return switch (this._buffered_stderr) {
.owned => &this._buffered_stderr.owned,
.borrowed => this._buffered_stderr.borrowed,
};
}
pub inline fn cwdZ(this: *ShellState) [:0]const u8 {
if (this.__cwd.items.len == 0) return "";
return this.__cwd.items[0..this.__cwd.items.len -| 1 :0];
}
pub inline fn prevCwdZ(this: *ShellState) [:0]const u8 {
if (this.__prev_cwd.items.len == 0) return "";
return this.__prev_cwd.items[0..this.__prev_cwd.items.len -| 1 :0];
}
pub inline fn prevCwd(this: *ShellState) []const u8 {
const prevcwdz = this.prevCwdZ();
return prevcwdz[0..prevcwdz.len];
}
pub inline fn cwd(this: *ShellState) []const u8 {
const cwdz = this.cwdZ();
return cwdz[0..cwdz.len];
}
pub fn deinit(this: *ShellState) void {
this.deinitImpl(true, true);
}
/// If called by interpreter we have to:
/// 1. not free this *ShellState, because its on a field on the interpreter
/// 2. don't free buffered_stdout and buffered_stderr, because that is used for output
fn deinitImpl(this: *ShellState, comptime destroy_this: bool, comptime free_buffered_io: bool) void {
log("[ShellState] deinit {x}", .{@intFromPtr(this)});
if (comptime free_buffered_io) {
if (this._buffered_stdout == .owned) {
this._buffered_stdout.owned.deinitWithAllocator(bun.default_allocator);
}
if (this._buffered_stderr == .owned) {
this._buffered_stderr.owned.deinitWithAllocator(bun.default_allocator);
}
}
this.shell_env.deinit();
this.cmd_local_env.deinit();
this.export_env.deinit();
this.__cwd.deinit();
this.__prev_cwd.deinit();
closefd(this.cwd_fd);
if (comptime destroy_this) bun.default_allocator.destroy(this);
}
pub fn dupeForSubshell(this: *ShellState, allocator: Allocator, io: IO, kind: Kind) Maybe(*ShellState) {
const duped = allocator.create(ShellState) catch bun.outOfMemory();
const dupedfd = switch (Syscall.dup(this.cwd_fd)) {
.err => |err| return .{ .err = err },
.result => |fd| fd,
};
const stdout: Bufio = if (io.stdout == .std) brk: {
if (io.stdout.std.captured != null) break :brk .{ .borrowed = io.stdout.std.captured.? };
break :brk .{ .owned = .{} };
} else if (kind == .pipeline)
.{ .borrowed = this.buffered_stdout() }
else
.{ .owned = .{} };
const stderr: Bufio = if (io.stderr == .std) brk: {
if (io.stderr.std.captured != null) break :brk .{ .borrowed = io.stderr.std.captured.? };
break :brk .{ .owned = .{} };
} else if (kind == .pipeline)
.{ .borrowed = this.buffered_stderr() }
else
.{ .owned = .{} };
duped.* = .{
.io = io,
.kind = kind,
._buffered_stdout = stdout,
._buffered_stderr = stderr,
.shell_env = this.shell_env.clone(),
.cmd_local_env = EnvMap.init(allocator),
.export_env = this.export_env.clone(),
.__prev_cwd = this.__prev_cwd.clone() catch bun.outOfMemory(),
.__cwd = this.__cwd.clone() catch bun.outOfMemory(),
// TODO probably need to use os.dup here
.cwd_fd = dupedfd,
};
return .{ .result = duped };
}
pub fn assignVar(this: *ShellState, interp: *ThisInterpreter, label: EnvStr, value: EnvStr, assign_ctx: AssignCtx) void {
_ = interp; // autofix
switch (assign_ctx) {
.cmd => this.cmd_local_env.insert(label, value),
.shell => this.shell_env.insert(label, value),
.exported => this.export_env.insert(label, value),
}
}
pub fn changePrevCwd(self: *ShellState, interp: *ThisInterpreter) Maybe(void) {
return self.changeCwd(interp, self.prevCwdZ());
}
// pub fn changeCwd(this: *ShellState, interp: *ThisInterpreter, new_cwd_: [:0]const u8) Maybe(void) {
pub fn changeCwd(this: *ShellState, interp: *ThisInterpreter, new_cwd_: anytype) Maybe(void) {
_ = interp; // autofix
if (comptime @TypeOf(new_cwd_) != [:0]const u8 and @TypeOf(new_cwd_) != []const u8) {
@compileError("Bad type for new_cwd " ++ @typeName(@TypeOf(new_cwd_)));
}
const is_sentinel = @TypeOf(new_cwd_) == [:0]const u8;
const new_cwd: [:0]const u8 = brk: {
if (ResolvePath.Platform.auto.isAbsolute(new_cwd_)) {
if (is_sentinel) {
@memcpy(ResolvePath.join_buf[0..new_cwd_.len], new_cwd_[0..new_cwd_.len]);
ResolvePath.join_buf[new_cwd_.len] = 0;
break :brk ResolvePath.join_buf[0..new_cwd_.len :0];
}
std.mem.copyForwards(u8, &ResolvePath.join_buf, new_cwd_);
ResolvePath.join_buf[new_cwd_.len] = 0;
break :brk ResolvePath.join_buf[0..new_cwd_.len :0];
}
const existing_cwd = this.cwd();
const cwd_str = ResolvePath.joinZ(&[_][]const u8{
existing_cwd,
new_cwd_,
}, .auto);
// remove trailing separator
if (cwd_str.len > 1 and cwd_str[cwd_str.len - 1] == '/') {
ResolvePath.join_buf[cwd_str.len - 1] = 0;
break :brk ResolvePath.join_buf[0 .. cwd_str.len - 1 :0];
}
break :brk cwd_str;
};
const new_cwd_fd = switch (Syscall.openat(
this.cwd_fd,
new_cwd,
std.os.O.DIRECTORY | std.os.O.RDONLY,
0,
)) {
.result => |fd| fd,
.err => |err| {
return Maybe(void).initErr(err);
},
};
_ = Syscall.close2(this.cwd_fd);
this.__prev_cwd.clearRetainingCapacity();
this.__prev_cwd.appendSlice(this.__cwd.items[0..]) catch bun.outOfMemory();
this.__cwd.clearRetainingCapacity();
this.__cwd.appendSlice(new_cwd[0 .. new_cwd.len + 1]) catch bun.outOfMemory();
if (comptime bun.Environment.allow_assert) {
std.debug.assert(this.__cwd.items[this.__cwd.items.len -| 1] == 0);
std.debug.assert(this.__prev_cwd.items[this.__prev_cwd.items.len -| 1] == 0);
}
this.cwd_fd = new_cwd_fd;
this.export_env.insert(EnvStr.initSlice("OLDPWD"), EnvStr.initSlice(this.prevCwd()));
this.export_env.insert(EnvStr.initSlice("PWD"), EnvStr.initSlice(this.cwd()));
return Maybe(void).success;
}
pub fn getHomedir(self: *ShellState) EnvStr {
if (comptime bun.Environment.isWindows) {
if (self.export_env.get(EnvStr.initSlice("USERPROFILE"))) |env| {
env.ref();
return env;
}
} else {
if (self.export_env.get(EnvStr.initSlice("HOME"))) |env| {
env.ref();
return env;
}
}
return EnvStr.initSlice("unknown");
}
pub fn writeFailingError(
this: *ShellState,
buf: []const u8,
ctx: anytype,
comptime handleIOWrite: fn (
c: @TypeOf(ctx),
bufw: BufferedWriter,
) void,
) CoroutineResult {
const IOWriteFn = struct {
pub fn run(c: @TypeOf(ctx), bufw: BufferedWriter) void {
handleIOWrite(c, bufw);
}
};
switch (this.writeIO(.stderr, buf, ctx, IOWriteFn.run)) {
.cont => {
ctx.parent.childDone(ctx, 1);
return .yield;
},
.yield => return .yield,
}
}
pub fn writeIO(
this: *ShellState,
comptime iotype: @Type(.EnumLiteral),
buf: []const u8,
ctx: anytype,
comptime handleIOWrite: fn (
c: @TypeOf(ctx),
bufw: BufferedWriter,
) void,
) CoroutineResult {
const io: *IO.Kind = &@field(this.io, @tagName(iotype));
switch (io.*) {
.std => |val| {
const bw = BufferedWriter{
.fd = if (iotype == .stdout) bun.STDOUT_FD else bun.STDERR_FD,
.remain = buf,
.parent = BufferedWriter.ParentPtr.init(ctx),
.bytelist = val.captured,
};
handleIOWrite(ctx, bw);
return .yield;
},
.fd => {
const bw = BufferedWriter{
.fd = if (iotype == .stdout) bun.STDOUT_FD else bun.STDERR_FD,
.remain = buf,
.parent = BufferedWriter.ParentPtr.init(ctx),
};
handleIOWrite(ctx, bw);
return .yield;
},
.pipe => {
const func = @field(ShellState, "buffered_" ++ @tagName(iotype));
const bufio: *bun.ByteList = func(this);
bufio.append(bun.default_allocator, buf) catch bun.outOfMemory();
// this.parent.childDone(this, 1);
return .cont;
},
.ignore => {
// this.parent.childDone(this, 1);
return .cont;
},
}
}
};
pub usingnamespace JSC.Codegen.JSShellInterpreter;
const ThisInterpreter = @This();
const ShellErrorKind = error{
OutOfMemory,
Syscall,
};
const ShellErrorCtx = union(enum) {
syscall: Syscall.Error,
other: ShellErrorKind,
fn toJSC(this: ShellErrorCtx, globalThis: *JSGlobalObject) JSValue {
return switch (this) {
.syscall => |err| err.toJSC(globalThis),
.other => |err| bun.JSC.ZigString.fromBytes(@errorName(err)).toValueGC(globalThis),
};
}
};
pub fn constructor(
globalThis: *JSC.JSGlobalObject,
callframe: *JSC.CallFrame,
) callconv(.C) ?*ThisInterpreter {
const allocator = bun.default_allocator;
var arena = bun.ArenaAllocator.init(allocator);
const arguments_ = callframe.arguments(1);
var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice());
const string_args = arguments.nextEat() orelse {
globalThis.throw("shell: expected 2 arguments, got 0", .{});
return null;
};
const template_args = callframe.argumentsPtr()[1..callframe.argumentsCount()];
var stack_alloc = std.heap.stackFallback(@sizeOf(bun.String) * 4, arena.allocator());
var jsstrings = std.ArrayList(bun.String).initCapacity(stack_alloc.get(), 4) catch {
globalThis.throwOutOfMemory();
return null;
};
defer {
for (jsstrings.items[0..]) |bunstr| {
bunstr.deref();
}
jsstrings.deinit();
}
var jsobjs = std.ArrayList(JSValue).init(arena.allocator());
var script = std.ArrayList(u8).init(arena.allocator());
if (!(bun.shell.shellCmdFromJS(globalThis, string_args, template_args, &jsobjs, &jsstrings, &script) catch {
globalThis.throwOutOfMemory();
return null;
})) {
return null;
}
var parser: ?bun.shell.Parser = null;
var lex_result: ?shell.LexResult = null;
const script_ast = ThisInterpreter.parse(
&arena,
script.items[0..],
jsobjs.items[0..],
jsstrings.items[0..],
&parser,
&lex_result,
) catch |err| {
if (err == shell.ParseError.Lex) {
std.debug.assert(lex_result != null);
const str = lex_result.?.combineErrors(arena.allocator());
globalThis.throwPretty("{s}", .{str});
return null;
}
if (parser) |*p| {
const errstr = p.combineErrors();
globalThis.throwPretty("{s}", .{errstr});
return null;
}
globalThis.throwError(err, "failed to lex/parse shell");
return null;
};
const script_heap = arena.allocator().create(bun.shell.AST.Script) catch {
globalThis.throwOutOfMemory();
return null;
};
script_heap.* = script_ast;
const interpreter = switch (ThisInterpreter.init(
globalThis,
allocator,
&arena,
script_heap,
jsobjs.items[0..],
)) {
.result => |i| i,
.err => |e| {
arena.deinit();
GlobalHandle.init(globalThis).actuallyThrow(e);
return null;
},
};
return interpreter;
}
pub fn parse(
arena: *bun.ArenaAllocator,
script: []const u8,
jsobjs: []JSValue,
jsstrings_to_escape: []bun.String,
out_parser: *?bun.shell.Parser,
out_lex_result: *?shell.LexResult,
) !ast.Script {
const lex_result = brk: {
if (bun.strings.isAllASCII(script)) {
var lexer = bun.shell.LexerAscii.new(arena.allocator(), script, jsstrings_to_escape);
try lexer.lex();
break :brk lexer.get_result();
}
var lexer = bun.shell.LexerUnicode.new(arena.allocator(), script, jsstrings_to_escape);
try lexer.lex();
break :brk lexer.get_result();
};
if (lex_result.errors.len > 0) {
out_lex_result.* = lex_result;
return shell.ParseError.Lex;
}
out_parser.* = try bun.shell.Parser.new(arena.allocator(), lex_result, jsobjs);
const script_ast = try out_parser.*.?.parse();
return script_ast;
}
// fn bunStringDealloc(this: *anyopaque, str: *anyopaque, size: u32) callconv(.C) void {}
/// If all initialization allocations succeed, the arena will be copied
/// into the interpreter struct, so it is not a stale reference and safe to call `arena.deinit()` on error.
pub fn init(
global: GlobalRef,
allocator: Allocator,
arena: *bun.ArenaAllocator,
script: *ast.Script,
jsobjs: []JSValue,
) shell.Result(*ThisInterpreter) {
var interpreter = allocator.create(ThisInterpreter) catch bun.outOfMemory();
interpreter.global = global;
interpreter.allocator = allocator;
const export_env = brk: {
var export_env = EnvMap.init(allocator);
// This will be set by in the shell builtin to `process.env`
if (EventLoopKind == .js) break :brk export_env;
var env_loader: *bun.DotEnv.Loader = env_loader: {
if (comptime EventLoopKind == .js) {
break :env_loader global.bunVM().bundler.env;
}
break :env_loader global.env.?;
};
var iter = env_loader.map.iterator();
while (iter.next()) |entry| {
const value = EnvStr.initSlice(entry.value_ptr.value);
const key = EnvStr.initSlice(entry.key_ptr.*);
export_env.insert(key, value);
}
break :brk export_env;
};
var pathbuf: [bun.MAX_PATH_BYTES]u8 = undefined;
const cwd = switch (Syscall.getcwd(&pathbuf)) {
.result => |cwd| cwd.ptr[0..cwd.len :0],
.err => |err| {
return .{ .err = .{ .sys = err.toSystemError() } };
},
};
// export_env.put("PWD", cwd) catch bun.outOfMemory();
// export_env.put("OLDPWD", "/") catch bun.outOfMemory();
const cwd_fd = switch (Syscall.open(cwd, std.os.O.DIRECTORY | std.os.O.RDONLY, 0)) {
.result => |fd| fd,
.err => |err| {
return .{ .err = .{ .sys = err.toSystemError() } };
},